9 Commits
Author SHA1 Message Date
schmidt.florian 284e692993 web: allow direct IP dashboard and worker access (#26)
Support direct HTTP IP access on port 5187 without hostname registration or a required proxy. Preserve dashboard/machine authentication and CSRF checks. Update Proxmox setup, D14, tests and documentation for 1.2.3.

Closes #25
2026-11-15 16:42:12 +01:00
schmidt.florian f45e065994 tools: register the updater in the normal command path (#24)
Use /usr/local/bin for container updater discovery and print an absolute command path for custom shells. Preserve managed links and operator files; cover shell lookup without sbin.

Closes #23
2026-11-15 15:10:56 +01:00
schmidt.florian 43caf1e412 tools: update inside LXC and use the existing proxy (#22)
Use the operator's HTTPS proxy with a private backend on port 5187. Limit the Proxmox host script to container creation and install a self-updating command inside the LXC. Preserve keys/history during legacy proxy migration and keep root updater code isolated from unprivileged build output.

Closes #21
2026-11-15 13:06:04 +01:00
schmidt.florian c75446008c core: publish self-hosted weekly dashboard and Proxmox deployment (#20)
Reuse existing weekly/reset analysis in an authenticated dashboard and local official CLI workers. Add safe Proxmox installation and updates, account-attributed history, and MIT distribution. Provider credentials stay owned by each CLI.

Closes #19
2026-11-15 11:24:55 +01:00
schmidt.florian c02829e2e1 app: let the settings hide limit windows and give the app an icon (#18)
The developer asked for an option to hide Claude's Fable week and for an
app icon that Windows can use (2026-11-04).

- Core: each provider's settings hold hidden limit windows by window
  series, so a hidden Codex week stays hidden across slot moves (D7, D8).
  Older settings files load with nothing hidden. Hidden windows give no
  pace popups.
- App: Settings → Providers lists each provider's limit windows with a
  Show checkbox, including hidden windows that are absent right now. The
  panel drops hidden windows in one place before it renders and queries
  history; the snapshot and history keep every window (D9).
- App: a usage gauge in the provider colours is the executable's icon,
  the window icon and the tray icon. tools/icon/make_icon.py renders it
  with Pillow, a development-only dependency, into a multi-size ICO and a
  PNG.

Closes #17
2026-11-04 19:41:44 +01:00
schmidt.florian 82fece85f5 app: show the reset history of each long limit window (#16)
The developer asked for a detailed breakdown of every reset (feedback of
2026-10-18). Limits do not only reset at the end of their week: most Codex
weeks in the local history ended early.

- Core: a limit's samples form a window series (provider, limit name and
  length), so the history follows Codex's week across slots (D7). Instance
  spans are built once. One backward walk gives each instance, real or
  inferred, the start of the instance after it. The hour that holds a
  boundary goes to the instance that starts in it, or else to the one that
  ends in it (#9). A stale sample that would put its instance after a later
  one is ignored. The reset history lists the real instances with their
  figures, totals and early-reset hours (D12). API value uses a dated list
  price table; unknown models stay unpriced (D13).
- App: a Resets section per long window with totals, a timeline of
  burn-ups side by side with skipped time in lanes below, early resets by
  hour and weekday, and a sortable table (D8). The reset tooltip lists
  every model with its tokens and API value. Tall tooltips open beside the
  pointer, and Fluent's 320 px tooltip cap no longer wraps data values.
- Docs: D12 and D13 are new; D7 and D8 cover window series, boundary
  hours and the Resets section.

Closes #14
Closes #9
2026-10-18 11:12:38 +02:00
schmidt.florian 0a08b508a2 core: plan the daily budget per day, start forecasts at 2 % and follow the limit week (#15)
The developer's feedback of 2026-10-18 named four problems at the top
of the panel: late forecasts, a daily budget that shrank with every use,
unequal Claude and Codex tiles, and an unclear "This week".

- Core: forecasts start at 2 % of a window (D7). Each day of a long
  instance has a share, an even pace and a budget. Today's budget starts
  from the use at the start of the day and stays put while today is
  spent. An estimated start-of-day use counts only the whole hours before
  the first sample's hour, so later samples and tokens do not move it.
  Week token totals follow the provider's limit week, with the calendar
  week as the named fallback; the snapshot carries `weekStart` and
  `weekWindow` (D9).
- App: tiles of one window kind show the same rows, with muted
  placeholders that say why (D8). The stale warning sits in the Used row.
  Week charts draw even pace and budget as steps per day, mark the
  instance start and reset, and label full-day rates. Token tiles say
  since when.
- CLI: prints which week it uses and since when.

Closes #13
2026-10-18 10:53:00 +02:00
schmidt.florian d5ad3ecee9 app: render the panel with an injected clock so tests do not depend on the date (#12)
The headless forecast test failed from 2026-10-16 on because the panel
read the real clock while its fixture fixes the time.

- App: PanelWindow takes an optional TimeProvider (the system clock by
  default) and passes it to the pace bar, burn-up, peak and usage charts
  and every forecast label. The burn-up chart uses the panel's render
  time as now.
- Tests: headless panels run on a fixed clock at fixture time, with a
  check before, at and after the forecast start. App and Core tests
  with fixed-date Claude events pin HistoryStore's clock, so the 60-day
  retention cannot drop them later.

Closes #11
2026-10-17 09:28:15 +02:00
schmidt.florian adb8f5b88d app: redesign the panel and add limit forecasts and daily week use (#6)
Redesign the stats panel after the developer's feedback on v1 and add
limit forecasts, daily week use and token-based estimates (D7, D8).

- Panel: a fixed header with range and provider controls, limit tiles
  with pace chips, meters and forecasts, week use per day, token KPIs
  and charts, one burn-up chart per limit window with past instances,
  and a sortable breakdown whose "Other" row expands. One tooltip
  component for every chart, tile and table.
- Core (D7): average and recent-rate forecasts, the reach date whenever
  use is over pace, days of a long window with even pace and daily
  budget, window instances derived from resets with a 15-minute
  tolerance, and estimates from price-weighted tokens where samples are
  missing. Forecasts start at 10 % of a window, or as soon as it is
  ahead, so a Codex week far ahead right after its reset warns too.
- Settings, popups and the version (1.1.0) follow the new design.

Closes #5
Closes #7
2026-10-15 19:06:04 +02:00
121 changed files with 9321 additions and 320 deletions
+13
View File
@@ -0,0 +1,13 @@
# Architecture
- [2026-11-14] D14's Fleet library reuses Core Pace/LimitAnalysis/ApiPrices; the web host and outbound worker add no second forecast implementation. Working-time schedules remain outside D7.
- [2026-11-14] Quota is one newest observation per account/window, not a sum. Source ids dedupe consumption across machines; local/session figures include shared copies and cannot be summed as machine-exclusive use.
- [2026-11-15] Legacy hourly history needs one account-attributed source and UTC-hour cutoff; provider and DataEmail checks match raw usage even after rebinding. Reconcile Codex increases before clipping; without a pre-cutoff baseline, omit the first cumulative total and warn rather than counting imported use twice.
- [2026-11-14] LoginCoordinator is memory-only and binds browser session/machine/profile/worker boot/deadline. CLI identity verification is separate from process success; never serialize login URLs, codes or authorization responses into fleet state.
- [2026-11-14] Persist worker export metadata before cursor advancement. Server merges acknowledged source records so an empty restart heartbeat cannot erase history. Current login health and historical data attribution are separate fields.
- [2026-11-15] Proxmox host creates the CT only. HTTP :5187 works directly by IP; HTTPS/proxy is optional, with no fixed host allowlist (D14). `finaltoken-update` fetches/builds/activates inside the CT, preserving state. Legacy migration changes only the known listener and disables the owned proxy; binaries and listener have separate rollback.
- [2026-11-15] Public source uses MIT; notices travel with ZIP/plugin and Proxmox outputs. `tools/source_policy.py` excludes recognized live config/keys/runtime data from both publication checks and source archives. Audit disk and index separately; inspect all historical trees, not just one filename hint per blob. Visibility/history changes need explicit authorization.
## Archive
+18
View File
@@ -2,5 +2,23 @@
- [2026-10-14] `claude -p "/usage"` writes a transcript into the working directory's project folder unless `--no-session-persistence` is passed; that transcript would show up in Claude token history. - [2026-10-14] `claude -p "/usage"` writes a transcript into the working directory's project folder unless `--no-session-persistence` is passed; that transcript would show up in Claude token history.
- [2026-10-14] Git Bash rewrites an argument that starts with `/` (`/usage` becomes `C:/Program Files/Git/usage`). Run CLI probes from PowerShell, or set `MSYS_NO_PATHCONV=1`. The app itself starts processes with an argument list, so it is not affected. - [2026-10-14] Git Bash rewrites an argument that starts with `/` (`/usage` becomes `C:/Program Files/Git/usage`). Run CLI probes from PowerShell, or set `MSYS_NO_PATHCONV=1`. The app itself starts processes with an argument list, so it is not affected.
- [2026-10-18] Avalonia 12 `CustomPopupPlacementCallback` gets the target's bounds in window coordinates, and a flip mirrors anchor and gravity but not the offset. Put a gap into the anchor rectangle (see `DataTooltip.BesidePointer`).
- [2026-10-18] Fluent caps `ToolTip` `MaxWidth` at 320 px, and a tooltip that covers the pointer takes pointer-over from its control, which raises `PointerExited`. `Ui.Theme` raises the cap; tall tips open beside the pointer.
- [2026-11-14] Official Claude manual-code login must be relayed to the original process, not a browser's remote localhost. Redirected-stdin support needs live verification; Codex uses device auth. Worker D3 print-mode quota probing is opt-in because current docs do not promise it as a non-interactive quota API.
- [2026-11-14] Proxmox `pct exec` environment defaults differ by version. Installer calls explicitly use `--keep-env 0`; build/CLI installation also uses a clean environment under the intended non-root user.
- [2026-11-15] Documentation checks must skip `artifacts/` as well as `.artifacts/`: ignored build/audit downloads can contain third-party Markdown and are not project documentation.
- [2026-11-15] Plain `git pull` can silently overwrite ignored files newly tracked upstream. The Proxmox updater fetches then merges with `--ff-only --no-overwrite-ignore`; a real-Git regression covers ignored operator-state collisions.
- [2026-11-15] npm's local `--prefix` install writes `node_modules/.bin`; the Linux worker's `.local/bin/codex` requires a user-owned global prefix. The regression installs an offline synthetic package with real npm.
- [2026-11-15] Compare copied/archived license bytes with source bytes. `read_text()` normalizes Windows CRLF while ZIP reads retain it; explicit LF/CRLF fixtures cover both checkouts.
- [2026-11-15] Do not assume a proxy or host-driven updates for LXC deployments. Direct IP HTTP is supported; use the in-container updater. An optional TLS proxy preserves the browser's Host/Origin.
- [2026-11-15] A build-owned source/output cannot supply code later executed as root. Capture updater bytes from the verified archive before build handoff and atomically install them in the root-owned release, excluding build-supplied updater files.
- [2026-11-15] Container shells can omit `/usr/local/sbin`. Register the updater in `/usr/local/bin`, print an absolute-path fallback, and test real shell lookup with sbin excluded.
- [2026-11-15] A legacy `FINALTOKEN_PUBLIC_ORIGIN=https://usage.example.com` caused HTTP 400 for IP access. Ignore this old setting; compare browser mutation Origin to actual request Host and derive Secure cookies from TLS or its validated HTTPS Origin. Health checks must not hide regressions with a forged Host.
## Archive ## Archive
+5 -4
View File
@@ -2,13 +2,14 @@
> Always-loaded. Everything else is on-demand. Update TOC when files change. > Always-loaded. Everything else is on-demand. Update TOC when files change.
## Current Focus ## Current Focus
- [2026-10-14] v1 on issue #1: Core collectors and store, Avalonia app, Stream Deck plugin. - [2026-11-15] 1.2.3 removes fixed hostname/HTTPS requirements for direct IP access. Debian 13 native build/update was user-exercised; this IP correction and official provider flows still need live verification.
## Invariants ## Invariants
- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2). - Provider access/refresh tokens, API keys and cookies stay with the CLIs; only a pending login's authorization response may be relayed transiently (D2, D14).
- Everything shipped stays NativeAOT-safe on win-x64 and linux-x64 (D1). - Everything shipped stays NativeAOT-safe on win-x64 and linux-x64 (D1).
- A response counts once, across restarts, rescans and resumed sessions (D3, D4, D5). - A response counts once, across restarts, rescans and resumed sessions (D3, D4, D5).
- `snapshot.json` is the only interface between the app and other processes (D9). - Desktop/Stream Deck retain `snapshot.json` (D9); the optional authenticated server/worker transport is separate (D14).
## Table of Contents ## Table of Contents
- `gotchas.md` — 2 entries — CLI probing pitfalls on this machine. - `gotchas.md` — 14 entries — CLI login, IP/Origin and updater boundaries, publication checks and Avalonia tooltips.
- `architecture.md` — 7 entries — Fleet analysis, attribution, migration, authentication, durability, Proxmox and publication.
+3
View File
@@ -0,0 +1,3 @@
tools/proxmox*.sh text eol=lf
tools/proxmox/*.py text eol=lf
tools/lxc_update.py text eol=lf
+47
View File
@@ -6,3 +6,50 @@ artifacts/
*.user *.user
*.suo *.suo
TestResults/ TestResults/
# Local deployment configuration and transport keys. Commit examples, never live values.
**/server.json
**/worker.json
**/server.env
**/worker.env
*.env
**/transport-keys.json
**/dashboard-key
**/worker-key
.env
.env.*
!.env.example
*.key
*.pem
*.pfx
*.p12
**/.ssh/
**/.aws/
**/.azure/
id_rsa
id_ecdsa
id_ed25519
# Provider profiles and FinalToken usage/history are local runtime data.
**/.claude/
**/.codex/
**/auth.json
**/.credentials.json
**/snapshot.json
**/fleet.json
**/history.json
**/history.state.json
**/history.journal.jsonl
**/usage.json
**/profile.json
**/settings.json
/history/
/data/
/state/
/runs/
/logs/
*.log
# Python tooling outputs.
__pycache__/
*.py[cod]
+19 -4
View File
@@ -1,8 +1,8 @@
# FinalToken # FinalToken
A small tray app that tracks Claude Code and Codex usage and limits on Windows 11 and CachyOS. It A small tray app that tracks Claude Code and Codex usage and limits on Windows 11 and CachyOS. It
never signs in to a provider and never handles a token: all data comes from the installed CLIs keeps provider credentials owned by the installed CLIs. The optional web dashboard coordinates
and the files they write. A stats panel shows history, small popups warn when usage runs ahead official CLI login with transient authorization-code relay (D14). A stats panel shows history, small popups warn when usage runs ahead
of or behind a limit's pace, and a Stream Deck plugin puts stats on keys. Developer: of or behind a limit's pace, and a Stream Deck plugin puts stats on keys. Developer:
schmidt.florian (Gitea user name). schmidt.florian (Gitea user name).
@@ -30,6 +30,9 @@ the decision, why and gives-up format, and carries the `type/decision` label.
| `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups | | `src/FinalToken.App` | Avalonia desktop app (D8): stats panel, tray, settings, popups |
| `src/FinalToken.Cli` | `finaltoken-cli` console: runs a refresh and prints the snapshot, for scripts and checks | | `src/FinalToken.Cli` | `finaltoken-cli` console: runs a refresh and prints the snapshot, for scripts and checks |
| `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) | | `src/FinalToken.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) |
| `src/FinalToken.Fleet` | Account/machine metadata, shared analysis and pending official CLI logins (D14) |
| `src/FinalToken.Web` | Authenticated self-hosted dashboard and outbound-worker API (D14) |
| `src/FinalToken.Worker` | Per-OS-user collector and official CLI login process host (D14) |
| `tests/*` | One test project per tested project, named `<Project>.Tests` | | `tests/*` | One test project per tested project, named `<Project>.Tests` |
| `tools/` | Repository tools, listed under [Tools](#tools) | | `tools/` | Repository tools, listed under [Tools](#tools) |
@@ -41,8 +44,10 @@ the decision, why and gives-up format, and carries the `type/decision` label.
no reflection-driven serialization, binding or loading, no `dynamic`, no runtime code no reflection-driven serialization, binding or loading, no `dynamic`, no runtime code
generation. Trim and AOT analyzer warnings are errors; never suppress one without a one-line generation. Trim and AOT analyzer warnings are errors; never suppress one without a one-line
reason at that spot. reason at that spot.
- Never touch credentials (D2): do not open credential files, environment secrets or keychains, - Never touch provider credentials (D2): do not open credential files, provider environment secrets or keychains,
never log message text, and never call a provider's HTTP API. never log message text, and never call a provider's HTTP API. D14 permits authenticated,
transient authorization-response relay to the pending official CLI login. Dashboard/worker
access keys authenticate FinalToken transport; they are not provider credentials.
- Child processes (`claude`, `codex`) run without a shell, with arguments as a list, a timeout and - Child processes (`claude`, `codex`) run without a shell, with arguments as a list, a timeout and
cancellation, and are killed with their process tree when they overrun (D6). cancellation, and are killed with their process tree when they overrun (D6).
- Every file the app writes for itself is written atomically (D5). - Every file the app writes for itself is written atomically (D5).
@@ -120,6 +125,8 @@ a screenshot of each changed view: compiling is not working.
## Tools ## Tools
- `tools/icon/make_icon.py`: renders the shared app icon with development-only Pillow 11.3.0.
Run `python -B tools/icon/make_icon.py`; test with `python -B tools/icon/test_make_icon.py`.
- `tools/docs/check_docs.py`: the documentation check; its tests are - `tools/docs/check_docs.py`: the documentation check; its tests are
`python -B tools/docs/test_check_docs.py`. `python -B tools/docs/test_check_docs.py`.
- `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. - `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`.
@@ -128,6 +135,14 @@ a screenshot of each changed view: compiling is not working.
- `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT - `tools/publish.py`: publishes the app, `finaltoken-cli` and Stream Deck plugin with NativeAOT
into an empty output directory and creates a ZIP beside it. Run on the target OS. It stamps into an empty output directory and creates a ZIP beside it. Run on the target OS. It stamps
the plugin manifest's `Version` from `<Version>`; its test is `python -B tools/test_publish.py`. the plugin manifest's `Version` from `<Version>`; its test is `python -B tools/test_publish.py`.
- `tools/test_web_dashboard.py`: provider-free HTTP/worker/process integration; build Release first.
`--serve-fixture` runs a temporary synthetic dashboard for screenshots. See `docs/web-dashboard.md`.
- `tools/proxmox.sh`: creates a managed Debian 13 LXC from the Proxmox host. Its Python
helpers live in `tools/proxmox/`; test with `python -B tools/proxmox/test_installer.py`. See `docs/proxmox.md`.
- `tools/lxc_update.py`: installed as `finaltoken-update` inside the CT. Fetches/builds/activates
locally without Proxmox host commands; test with `python -B tools/proxmox/test_update.py`.
- `tools/check_public.py --history`: read-only publication pattern check. It reports paths/pattern
names, never matching values; tests are `python -B tools/test_check_public.py`. See `docs/publication.md`.
## Writing ## Writing
+49
View File
@@ -0,0 +1,49 @@
# Contributing
FinalToken is licensed under [MIT](LICENSE). Contributions should preserve its main question:
will the user's measured provider allowance last until the actual reset?
Read [AGENTS.md](AGENTS.md), [requirements](docs/requirements.md) and the relevant
[recorded decisions](docs/decisions.md) before changing behavior. Core owns forecasting and
history calculations; reuse them in each host. New behavior needs deterministic tests. Use
small synthetic fixtures, never real transcripts, rollout files, credential files or customer data.
## Get the source
When anonymous repository access is enabled, these HTTPS commands need no account/token:
```bash
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
cd FinalToken
```
Update a clean checkout with:
```bash
git pull --ff-only
```
A public repository does not grant push permission. Authenticated Gitea maintenance commands
are separate from read-only clone/pull. Do not embed passwords, tokens or an email/password in
the remote URL. If anonymous access is still disabled, the host must first make it public.
## Build and check
Use the .NET SDK selected by `global.json` and run commands from the repository root:
```text
dotnet build FinalToken.slnx -c Release
dotnet test --solution FinalToken.slnx -c Release
python -B tools/docs/check_docs.py
python -B tools/check_public.py --history
```
For Proxmox tooling, also run `python -B tools/proxmox/test_installer.py`,
`python -B tools/proxmox/test_update.py`, `bash -n tools/proxmox.sh` and
`bash -n tools/proxmox-update.sh`. [Web setup](docs/web-dashboard.md) and [Proxmox setup](docs/proxmox.md)
describe additional integration checks. State exactly what was exercised; mocked provider/Proxmox
tests do not establish that live login, native publishing or CT creation worked.
Use the Gitea issue/branch/review workflow in [AGENTS.md](AGENTS.md#workflow). Keep changes focused
and preserve unrelated work. Contributions do not require granting an agent permission to push
or publish; those actions still need explicit authorization.
+1 -1
View File
@@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>1.0.1</Version> <Version>1.2.3</Version>
<TargetFramework>net10.0</TargetFramework> <TargetFramework>net10.0</TargetFramework>
<LangVersion>14</LangVersion> <LangVersion>14</LangVersion>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
+5
View File
@@ -3,9 +3,14 @@
<Project Path="src/FinalToken.Core/FinalToken.Core.csproj" /> <Project Path="src/FinalToken.Core/FinalToken.Core.csproj" />
<Project Path="src/FinalToken.Cli/FinalToken.Cli.csproj" /> <Project Path="src/FinalToken.Cli/FinalToken.Cli.csproj" />
<Project Path="src/FinalToken.App/FinalToken.App.csproj" /> <Project Path="src/FinalToken.App/FinalToken.App.csproj" />
<Project Path="src/FinalToken.Fleet/FinalToken.Fleet.csproj" />
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" /> <Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
<Project Path="src/FinalToken.Web/FinalToken.Web.csproj" />
<Project Path="src/FinalToken.Worker/FinalToken.Worker.csproj" />
</Folder> </Folder>
<Folder Name="/tests/"> <Folder Name="/tests/">
<Project Path="tests/FinalToken.FakeCli/FinalToken.FakeCli.csproj" />
<Project Path="tests/FinalToken.Fleet.Tests/FinalToken.Fleet.Tests.csproj" />
<Project Path="tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" /> <Project Path="tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" />
<Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj" /> <Project Path="tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj" />
<Project Path="tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj" /> <Project Path="tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj" />
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 FinalFactory contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+27 -7
View File
@@ -1,18 +1,28 @@
# FinalToken # FinalToken
FinalToken is a tray app for Claude Code and Codex usage. It shows token history, provider limits, FinalToken answers: **at my current usage, will my allowance last until the weekly reset?**
and pace, warns when usage runs ahead of or behind a limit, and puts selected stats on Stream Deck It tracks Claude Code and Codex limits, average/recent forecasts, daily budgets and reset history.
keys. Starting the app opens the stats panel; closing it keeps the tray app running by default. Use the desktop tray app, the optional self-hosted web dashboard, or Stream Deck keys.
Starting the desktop app opens its stats panel; closing it keeps the tray app running by default.
FinalToken does not sign in to a provider, handle API keys or OAuth tokens, or read credential FinalToken reads the installed CLIs' usage files and runs their commands. Provider credentials
files. It reads the installed CLIs' usage files and runs their local commands. It never calls a stay owned by those CLIs; FinalToken never reads credential files or calls a provider's HTTP API.
provider's HTTP API itself. Missing or logged-out CLIs show as unavailable. The optional [self-hosted dashboard and worker](docs/web-dashboard.md) combine multiple machines
and coordinate official CLI login with transient authorization-code relay. Weekly forecasts,
daily budgets and reset history reuse the desktop app's analysis. Missing or logged-out CLIs
show their observed health; stale allowances have no current forecast.
For automatic container creation from a Proxmox host, use the [LXC install/update script](docs/proxmox.md).
It creates a server-only LXC at `http://<container-ip>:5187`, with no hostname or proxy required.
Run `finaltoken-update` inside
the container for updates; no Proxmox-host checkout is needed afterwards.
## Requirements ## Requirements
- Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be - Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be
overridden in Settings. overridden in Settings.
- Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland. - Desktop: Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland.
- Web server/client: .NET 10 source build or a target-OS NativeAOT build; no desktop required.
- For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional. - For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional.
## Install and use ## Install and use
@@ -55,3 +65,13 @@ python -B tools/publish.py win-x64 --out artifacts/package-win-x64
The publish directory must be empty. The tool bundles all three executables and plugin assets, The publish directory must be empty. The tool bundles all three executables and plugin assets,
then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux. then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux.
## Public source and contributing
Once the repository is publicly readable, cloning/fetching/pulling over HTTPS needs no Git login.
Push access, dashboard access and official provider logins remain separate authenticated operations.
See [contributing](CONTRIBUTING.md) and [publication checks](docs/publication.md).
## License
[MIT](LICENSE). Third-party dependencies retain their own licenses.
+235 -14
View File
@@ -7,7 +7,7 @@ the IDs instead of restating the text. The requirements (R1 to R7) are in
## D1 — .NET 10, C# 14 and NativeAOT for win-x64 and linux-x64 ## D1 — .NET 10, C# 14 and NativeAOT for win-x64 and linux-x64
**Decision.** Every shipped executable (the app, the CLI and the Stream Deck plugin) targets **Decision.** Every shipped executable (the app, the CLI, Stream Deck plugin and optional web/worker hosts) targets
`net10.0` with C# 14 and publishes NativeAOT for `win-x64` and `linux-x64`. `global.json` asks `net10.0` with C# 14 and publishes NativeAOT for `win-x64` and `linux-x64`. `global.json` asks
for SDK 10.0.100 or newer within 10.0 (`rollForward: latestFeature`), so the SDK from CachyOS's for SDK 10.0.100 or newer within 10.0 (`rollForward: latestFeature`), so the SDK from CachyOS's
package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers. package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers.
@@ -20,8 +20,10 @@ serialization, binding or loading, or runtime code generation.
## D2 — The CLIs are the only interface to a provider ## D2 — The CLIs are the only interface to a provider
**Decision.** FinalToken never reads, stores, logs or sends a credential (OAuth token, API key, **Decision.** FinalToken never reads, stores, logs or sends a provider access/refresh token,
cookie). It never opens a provider login and never calls a provider's HTTP API itself. It reads API key or cookie. It can invoke an official CLI login and transiently relay the browser's
authorization response to that exact pending process ([D14](#d14--self-hosted-dashboard-and-workers)).
It never calls a provider's HTTP API itself. It reads
the files the CLIs write and runs the installed `claude` and `codex` executables as child the files the CLIs write and runs the installed `claude` and `codex` executables as child
processes, which use their own login. It never opens credential files such as processes, which use their own login. It never opens credential files such as
`~/.claude/.credentials.json` or `~/.codex/auth.json`, or the OS keychain. Only counts, model `~/.claude/.credentials.json` or `~/.codex/auth.json`, or the OS keychain. Only counts, model
@@ -32,6 +34,7 @@ working.
**Why.** R2, R3. **Why.** R2, R3.
**Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed. **Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed.
Login coordination needs the installed CLI's supported flow; no central credential pool is possible.
## D3 — Claude data sources ## D3 — Claude data sources
@@ -149,15 +152,89 @@ probe.
- expected use `100·e`, pace delta `d = u − 100·e` in percentage points - expected use `100·e`, pace delta `d = u − 100·e` in percentage points
- **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track** - **ahead** when `d ≥ +threshold`; **behind** when `d ≤ −threshold` and `e ≥ 0.5`; **on track**
otherwise. The threshold defaults to 10 points and is a setting. otherwise. The threshold defaults to 10 points and is a setting.
- when ahead, the projected time of reaching 100 % at the average rate so far, - **Forecasts.** At the average rate so far, the use at reset is `u / e` (for `e > 0`). Whenever
`t + (100 − u) · e·W / u`, shown only if it comes before `r`. that passes 100 % (that is, `d > 0`, whatever the threshold), the time of reaching 100 %,
`t + (100 − u) · e·W / u`, is shown; it always comes before `r`. A second forecast uses the
recent rate: the rise of `u` over the window's samples from the last 24 h, when they span at
least 3 h. It is shown beside the average forecast, never instead of it. Forecasts start once
2 % of the window has passed (6 min of a session, about 3 h 22 min of a week), or as soon as
the window is ahead. Before either, a few minutes of use already "reach" 100 % within days,
which is noise. Early forecasts are rough and firm up as the window goes on. Until forecasts
start, the tile and the window chart say when they will.
- **Window instance.** The samples of one window whose reset times lie within 15 minutes of each
other. Claude reports resets to the minute and drifts by a minute between probes ("8pm", then
"7:59pm"), so exact equality would split one week. A reset starts a new instance at 0 %.
- **Days of a long window.** For a window longer than a day: today's use is `u` now minus `u` at
the local start of today (the last sample of the same instance at or before it, or 0 when the
instance began today). The use of each local day of the instance is computed the same way.
A day's share is the time of that day inside the instance. A 7-day instance that resets at
another time than midnight touches 8 local dates; the first and the last have shorter shares,
and both are shown. The even pace of a day is `100 · share / W`. The daily budget plans the
rest of the instance from the start of today. With `s` the local start of today, or the
instance start when that is later, and `u₀` the use at `s`, today's budget is
`(100 − u₀) · today's share / (r − s)`; use during the day does not change it. A later day's
budget is `(100 − max(u, u₀ + today's budget)) · its share / (r − end of today)`, so later days
lose budget only once today's use passes today's budget. `u₀` is measured, or estimated as
below and then marked. An estimated `u₀` takes `k` from the first sample at or after `s`, not
the newest, and counts only the whole hours before that sample's hour, so later samples and
tokens do not move it. Without `u₀` there is no budget.
- **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the
token history. Tokens are weighted by the provider's API price ratios: Claude input 1,
output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1,
output 8. A window whose label names a model family ("Fable") counts only that family's
models; any other window counts all of the provider's models. Because an instance starts at
0 %, the scale `k = u / (weighted tokens from the instance start to the sample)` turns weighted
tokens into percent of the limit; the newest sample gives `k`. A day, or a stretch of the
window chart, then uses samples where they exist at both ends, and `k` × its weighted tokens
where they do not. A finished instance uses its own last sample for `k` when it has one, else
the current `k`. Estimates are always marked as estimates and never exceed 100 %: a limit that
is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at
the time it crosses. No tokens in the instance means no estimate. Instance boundaries come from
resets: an instance starts at its reset minus its length, and ends at its reset or at the next
instance's start, whichever comes first (Codex can start a new window early). Tokens are
hourly (D5): an hour that holds a boundary goes to the instance that starts in it, or, when
none does, to the instance that ends in it. Other spans between instances (a session window
opens only with the next message) belong to none. A sample that would place its instance
after an instance sampled later is stale and is ignored. A past instance
with samples is always the real one; an instance is only inferred where no samples exist, by
stepping back one window length, and never overlaps a real one. Windows of a day or shorter are
never inferred, since a session starts with whatever message comes next. Past instances are
labelled with their real start and end.
- **Window series.** The samples of one limit share the provider, the limit name and the
length. The limit name is the window id without a Codex slot suffix (`:primary`,
`:secondary`): Codex moves a limit between its slots when another limit appears or goes, as
its week did on 2026-09-13 when its 5 h limit went away. Every analysis of a window reads its
series, never a window of another length under the same id.
A window without a known length or reset has no pace; FinalToken never guesses one. A window without a known length or reset has no pace; FinalToken never guesses one; an estimate
is a marked calculation from measured tokens, not a guess.
**Why.** R5. A straight line from the window's start to its reset is a pace the user can check **Why.** R5. A straight line from the window's start to its reset is a pace the user can check
by hand. by hand. A user over pace by less than the threshold still runs out before the reset, so the
date shows from the first point over pace. The day figures answer "how much of the week did I
use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14). A
budget computed from `u` and the time now fell with every use, even within the day's plan, and
held a partial first day to a full day's pace; a budget set at the start of the day can be
compared with the day's bar (developer feedback, 2026-10-18). An estimated `u₀` with the newest
`k` moved whenever use from the web or another device changed the scale, and the budget moved
with it; the token hour that holds the first sample keeps growing after it.
Measured samples alone left the day chart empty until the app had run for a whole week, while the
token history already covers it; the estimate fills it at once and agrees with the measured use
of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is
no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within a day, and that is
the warning the user needs (developer feedback, 2026-10-15). Starting at 10 % hid every forecast
for the first 17 h of a week, and Codex weeks that reset early spent much of their time there;
the developer prefers a rough forecast that firms up with data (developer feedback, 2026-10-18).
**Gives up.** Weekday and working-hour patterns. **Gives up.** Weekday and working-hour patterns. Forecasts assume a constant rate; early in a
window, a burst that puts it ahead gives a reach date that a quiet hour moves out again, and in
the first hours a forecast can move by days.
Measured day figures are only as fine as the samples (D5 keeps one per hour while the value
stands still). Estimates miss use from other devices and from claude.ai or the web, which
counts against the limit but leaves no local tokens; they also miss changes in model mix within
an instance and any weighting the provider applies beyond the price ratios. An estimated `u₀`
keeps the first sample's scale for the whole day, even when later samples would estimate it
better, and overstates `u₀` by the use in that sample's hour before the sample.
## D8 — Desktop app ## D8 — Desktop app
@@ -173,19 +250,46 @@ by hand.
The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app The tray icon offers Open, Refresh now, Settings and Quit. Closing the window keeps the app
running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an running in the tray. Starting the app opens the stats panel (R4). Start with the OS is an
opt-in setting. opt-in setting.
- **Panel (R4).** It leads with one tile per limit window: used percent, pace, the forecasts of
[D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Tiles of
one window kind show the same rows in the same order; a value that is not known yet shows a
muted placeholder that says why or from when. Then follow the per-day use of the long
windows, with each day's even pace and budget for its share and the instance start and reset
marked on the first and last day; token totals for today, the current session and the week of
[D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes), each saying since
when; charts, one window chart per limit window; the reset history of each long window
([D12](#d12--reset-history)); and the top entries by model and by project, with the rest folded
into an expandable
"Other". A window chart is a burn-up of one instance from its start to its reset: the used
percent as a line (measured, or estimated before the first sample), the even-pace diagonal
from 0 % to 100 %, the forecast to the reset and the previous instance faintly behind, with no
point markers; under it, the peak each past instance reached. Tooltips are one component: a
title and a label/value grid. Diagnostics are collapsed. Provider colours are fixed (Claude orange, Codex blue, validated for colour vision
deficiency on both themes). Pace states use status colours with an icon and a label, never
colour alone.
- **Popups (R5).** A small borderless, topmost window that does not take focus, at the - **Popups (R5).** A small borderless, topmost window that does not take focus, at the
bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click bottom right of the primary screen's work area. It goes away after 8 s or on a click; a click
opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to opens the stats panel. A popup shows when a window's pace state ([D7](#d7--pace)) changes to
ahead or behind, at most once per window and state until the state changes again, with ahead or behind, at most once per window and state until the state changes again, with
hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per
provider and per state. provider and per state.
- **Hidden windows.** The settings can hide single limit windows, such as Claude's Fable week.
A hidden window is a window series ([D7](#d7--pace)), so it stays hidden when Codex moves it to
another slot. It leaves every part of the panel and gives no popups. Its samples are still
recorded, and the snapshot still carries it
([D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes)). Nothing is hidden
by default.
- **Icon.** One icon, rendered from a committed source by a repository tool, is the Windows
executable's icon, the window icon and the tray icon.
- **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma - **Linux.** The app runs on Avalonia's X11 backend, under XWayland on CachyOS's KDE Plasma
Wayland session, because Wayland clients cannot place their own windows. Wayland session, because Wayland clients cannot place their own windows.
**Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A **Why.** R1, R4, R5. Avalonia is the cross-platform .NET UI toolkit with NativeAOT support. A
chart library would add reflection and size for three chart types. chart library would add reflection and size for three chart types. A limit that a user does not
use only adds noise to the panel, and an app without its own icon is hard to find in the taskbar.
**Gives up.** Native OS notification styling, and a native Wayland window. **Gives up.** Native OS notification styling, and a native Wayland window. A hidden window's
pace goes unnoticed until it is shown again.
## D9 — The snapshot file is the app's only output to other processes ## D9 — The snapshot file is the app's only output to other processes
@@ -193,18 +297,80 @@ chart library would add reflection and size for three chart types.
([D5](#d5--own-history-store)). It carries a schema version `v` (1 to begin with), the time it ([D5](#d5--own-history-store)). It carries a schema version `v` (1 to begin with), the time it
was made, the refresh interval, the path of the app's executable and, per provider, its status was made, the refresh interval, the path of the app's executable and, per provider, its status
and reason, its limit windows (used percent, reset, length, pace state, delta and projection) and reason, its limit windows (used percent, reset, length, pace state, delta and projection)
and its token totals for today, the current session window and the current week. The DTOs and and its token totals for today, the current session window and the current week, with the
their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the week's start and the id of the limit window it follows (`weekStart`, `weekWindow`). The week is
Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats a the current instance of the provider's weekly limit: its longest window over a day whose label
names no model family. Without one, it is the local calendar week from Monday, and `weekWindow`
is absent. The DTOs and their source-generated JSON context live in `FinalToken.Core`, shared by
the app, the CLI and the Stream Deck plugin. The optional separate dashboard/worker hosts use
[D14](#d14--self-hosted-dashboard-and-workers); the desktop app itself has no server. A reader treats a
snapshot older than three refresh intervals as stale. The app gives the engine its own path; a snapshot older than three refresh intervals as stale. The app gives the engine its own path; a
CLI refresh keeps the path already in the snapshot, and a snapshot without one has none, so a CLI refresh keeps the path already in the snapshot, and a snapshot without one has none, so a
reader never mistakes its own path for the app's. reader never mistakes its own path for the app's.
**Why.** R6 needs the stats outside the app. A file has no network surface, and it survives a **Why.** R6 needs the stats outside the app. A file has no network surface, and it survives a
restart of either side. restart of either side. Beside the limit tiles, "this week" reads as the limit's week, not the
calendar week (developer feedback, 2026-10-18).
**Gives up.** Updates faster than the reader's poll interval. **Gives up.** Updates faster than the reader's poll interval.
## D14 — Self-hosted dashboard and workers
**Decision.** Add a separate ASP.NET Core slim/NativeAOT-compatible server and an outbound .NET
worker per OS user, following the developer's direction in
[#19](https://git.finalfactory.de/FinalFactory/FinalToken/issues/19).
- Account ids, expected emails and machine/profile bindings are configured by the operator.
The server has a dashboard access key and distinct per-machine keys. Browser sessions are
HttpOnly, SameSite cookies with CSRF checks. Direct IP or hostname access supports HTTP and
HTTPS without a fixed-host allowlist. Browser mutations compare Origin with the actual request
Host; HTTPS sessions use Secure cookies, including through a proxy preserving Host/Origin.
HTTP transport is unencrypted. A worker cannot select
another machine's identity or execute arbitrary remote commands.
- The dashboard calls Core's D7, D12 and D13 APIs. No second forecasting implementation is added.
Local settings remain local; the newest quota observation's profile supplies the pace threshold,
hidden windows and freshness interval. Account timezone controls calendar days. No working-hour
forecast is added. Old/expired limits are displayed but have no current forecast.
- The Proxmox host script creates the LXC only. It does not install a reverse proxy. The server
exposes HTTP port 5187 directly at the container IP; an operator's HTTPS proxy is optional.
`finaltoken-update` fetches/builds/activates updates inside the container. An update from the
old bundled-proxy layout changes its known listener and disables only the installer-owned
proxy, with configuration rollback on a failed backend check. See
[the deployment guide](proxmox.md).
- Quota is the newest observed account/window value, never the sum across machines. Consumption
uses Claude response ids and ordered Codex session cumulative counts across machine copies.
Conflicting event metadata is excluded with a warning. Raw metadata history and observations
survive offline clients and restarts; messages and project paths are not exported.
- Old hourly history cannot be deduplicated after aggregation. An optional designated source and
fixed UTC-hour cutoff import it once; identified source events own the interval after the cutoff.
Historical profile/account attribution is an operator assertion; identity probes cannot prove
which account produced older transcripts. Use a separate profile/data directory per account.
- A login is bound to browser session, machine, OS user, config profile, worker boot and a
15-minute maximum attempt deadline. That deadline is not a provider credential expiry.
Claude uses `auth login --claudeai` and manual code relay through stdin; Codex uses
`login --device-auth`. The CLI exchanges and stores its own credentials. A status probe verifies
the resulting email. Unknown identity or account mismatch cannot be reported as success.
Responses, URLs and device codes live only in pending-session memory and are not logged.
- Cancellation, timeout, worker restart and concurrent attempts have explicit outcomes.
No remote localhost callback forwarding or private provider endpoint is implemented.
CLI output/flow changes fail visibly and may require terminal login on that machine.
- The worker reuses the local store and scanner. Claude's legacy D3 print-mode quota probe is
opt-in: current official documentation does not promise that slash commands in print mode are
a supported quota API. Without it, existing observations remain available and age to stale.
Codex uses D4's CLI app-server and rollout fallback. No provider HTTP API is added.
**Why.** R8, and the developer's clarification that the browser authorization response must
travel through FinalToken to the CLI, without being stored. D7's analysis answers whether the
remaining allowance will last through the actual reset; token prices alone cannot answer it.
The developer requires direct IP access without hostname registration or a mandatory proxy
([#25](https://git.finalfactory.de/FinalFactory/FinalToken/issues/25)).
**Gives up.** Automatic remote callbacks, provider-token sharing, automatic account switching,
unverified identities, universal login lifetimes, and exact cross-machine attribution of old
hourly buckets. The metadata inventory currently has a 100,000-record per-profile export bound;
the collector retains prior data and reports failure when full. This version uses atomic JSON
inventories, not an unbounded fleet database. See [operation and limits](web-dashboard.md).
## D10 — Stream Deck plugin ## D10 — Stream Deck plugin
**Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder **Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder
@@ -237,3 +403,58 @@ setting says so and nothing happens.
**Why.** R7. **Why.** R7.
**Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks. **Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks.
## D12 — Reset history
**Decision.** For each limit window longer than a day, the panel lists the instances of its
window series ([D7](#d7--pace)) that have samples and overlap the panel's range, newest first,
with totals over them. Inferred instances are left out, because their resets were not observed.
- **End.** An instance ends at its reset or at the next instance's start (D7). One that ends
more than 15 minutes before its reset **reset early**, and the time from its end to its reset
is **skipped**. The running instance is marked as running and has no end figures yet.
- **Figures.** Start, end, duration and reset; peak and final use (the last point of its D7
burn-up, marked when estimated); when it reached 100 % and how long it stayed there; tokens by
kind and by model in its hours (the window's model family only, boundary hours as in D7); and
their API value ([D13](#d13--api-value-at-list-prices)).
- **Unused.** A finished instance leaves `100 − final use` percent of its limit unused.
- **Gift.** An early reset hands out a fresh limit ahead of schedule: its gift is
`100 · skipped / W` percent of a limit. Over many windows, that is how many extra limits the
provider gave.
- **Value of a percent.** Unused and gift percent become tokens and money at the instance's own
tokens and API value per percent point when its final use is at least 5 %; otherwise at the
median of the series' instances that qualify. Without one, only the percent is shown.
- **Totals** over the listed instances: their number, early resets, tokens, API value, unused
and gift (in limits and value), and how often and how long 100 % was reached.
- **Timeline.** Each series shows its instances on one time axis without joining their lines,
marks each reset and the skipped time of early resets, and counts its early resets by local
hour and weekday.
**Why.** R4. The developer asked for figures per reset, including wastage, API value and what
early resets give (developer feedback, 2026-10-18). Codex resets early often: 11 of its 12 week
instances from 2026-09-21 to 2026-10-17 ended early, some after 10 hours.
**Gives up.** Resets FinalToken never saw: before its first sample, and instances without any
sample. Token figures at a boundary are only as fine as an hour. The gift assumes the provider
would have kept its schedule. Unused and gift values assume the instance's model mix. A drop in
use without a new reset is not a reset.
## D13 — API value at list prices
**Decision.** FinalToken estimates what tokens would cost at the providers' public API list
prices. A table compiled into Core gives, per model, US dollars per million tokens for input,
output, cache write and cache read (Claude) or input, cached input and output (Codex), with the
day it was checked and its source pages. A model id matches its entry exactly or with a
trailing date suffix (`claude-haiku-4-5-20251001`). A model without an entry has no value; its
tokens are counted and shown as unpriced. Claude cache writes use the 5-minute price. Reasoning
is part of output and Codex cached input part of input, as in [D7](#d7--pace). Values are
shown with "≈" as "at API list prices".
**Why.** The developer asked what each window would cost at API prices (developer feedback,
2026-10-18). [D2](#d2--the-clis-are-the-only-interface-to-a-provider) rules out asking a
provider; a dated table can be checked by hand and is updated with a release.
**Gives up.** Price changes after the check until a release updates the table. Long-context
prices (OpenAI above 272K input tokens, Claude Haiku 5.5 above 100K), because hourly buckets do
not keep request sizes. The 1-hour cache write price, fast and batch prices, and models not in
the table.
+192
View File
@@ -0,0 +1,192 @@
# Proxmox LXC install and update
Use the **Proxmox host only to create the container**. Updates run **inside the LXC**.
Open the dashboard at **`http://<container-ip>:5187`**. No hostname, HTTPS or proxy is required;
FinalToken installs no Caddy or other proxy. This follows
[D14](decisions.md#d14--self-hosted-dashboard-and-workers).
## Install the server
As root on the Proxmox host, with Git and Python 3 installed:
```bash
git clone --branch master --single-branch https://git.finalfactory.de/FinalFactory/FinalToken.git /opt/finaltoken-src && \
bash /opt/finaltoken-src/tools/proxmox.sh install --role server --ctid 201 \
--storage local-lvm --timezone Europe/Berlin
```
Use a free CT id and your storage and timezone. Omit `--ctid` for the next free id.
The optional legacy `--domain` argument is accepted but does not restrict dashboard access.
Add `--dry-run` to validate without creating a CT. Anonymous HTTPS clone needs no Git login.
The installer prints the container IP URL. You can also find the address with `hostname -I`
inside the CT. HTTP transport is unencrypted. If you choose to use an HTTPS reverse proxy:
- Public URL: `https://usage.example.com` (your chosen hostname).
- Backend: `http://<LXC-IP>:5187`.
- Preserve the public `Host` and browser `Origin` headers.
- Allow worker metadata POST bodies up to 32 MiB, matching the server's request-size limit.
- TLS/certificates stay on your existing proxy. The LXC needs no inbound 80/443 or certificates.
The dashboard key, machine keys and CSRF checks remain required. Browser mutation Origins must
match the actual request Host; no fixed hostname allowlist applies. HTTPS sessions use Secure
cookies, and direct HTTP login works. No forwarded-header trust is enabled.
The proxy must not log authorization headers or request bodies containing login responses.
Read the dashboard key on the CT's root console:
```bash
cat /etc/finaltoken/dashboard-key
```
`--role server` installs no coding CLIs or worker. Optional `--email` seeds provider account
metadata; no provider email/login is needed to install the server. Configure account/machine
bindings and distinct machine keys as in [web setup](web-dashboard.md#run-locally).
## Update inside the container
Open the LXC console as root and run:
```bash
finaltoken-update
```
This fetches public `master` into temporary source, builds NativeAOT as the isolated build user,
and activates the update **inside this container**. It does not call `pct`, contact the Proxmox
host or require the original host checkout. It preserves the CT role, service keys, settings,
CLI profiles and history. Official provider CLIs keep their own update/login lifecycle.
The updater is included in each binary release, so switching/rolling back releases updates it too.
Its root-executed code comes directly from the verified source archive; build-user modifications
to extracted source or build output cannot replace the installed updater.
The command is installed in `/usr/local/bin`; the updater also prints its absolute path for
shells with a custom PATH. Version 1.2.1 used `/usr/local/sbin`, which some container shells omit.
For that version you can invoke `/usr/local/sbin/finaltoken-update` directly, or add the normal
command without rebuilding:
```bash
mkdir -p /usr/local/bin
ln -s /opt/finaltoken/current/finaltoken-update /usr/local/bin/finaltoken-update
finaltoken-update --dry-run
```
This does not overwrite an existing file. Later updates preserve the matching managed link;
the old valid sbin link can remain for compatibility.
```bash
finaltoken-update --dry-run
```
Dry-run reads the managed marker and prints the plan without downloading or changing services.
Concurrent updates are refused. A new binary release is built before switching `current`;
only previously running services restart, and a failed local health check restores the old binaries.
Stopped services stay stopped. Package/configuration/history rollback is not implied by binary rollback.
### Existing 1.2.0 containers
The old installer did not install this command and bundled a proxy. Run the following **once as
root inside that LXC** to fetch the corrected updater and perform the update:
```bash
(
set -e
update_script=$(mktemp)
trap 'rm -f -- "$update_script"' EXIT
curl --fail --silent --show-error --location --proto '=https' --tlsv1.2 \
https://git.finalfactory.de/FinalFactory/FinalToken/raw/branch/master/tools/lxc_update.py \
--output "$update_script"
python3 "$update_script"
)
```
This installs Git in the CT if needed, updates the app, changes the old known loopback listener
to `0.0.0.0:5187` and disables **only** `finaltoken-proxy.service`. Open the container IP on
HTTP port 5187. Keys, old environment settings, profiles, history, certificate files and installed packages
are retained. It does not stop an unrelated `caddy.service` or purge packages/configuration.
The old server environment is backed up as root-only `server.env.pre-external-proxy`. If the
backend health check fails, its listener and prior service states are restored. A custom listener
is retained and migration reports that it needs manual configuration. The application update
may already have succeeded when a later network migration fails; retry after fixing the cause.
Subsequent updates need only `finaltoken-update`. The old host updater refuses deployment and
points to this in-container command.
## Install dashboard and client
Omit `--role server` (or choose `--role both`) to create a CT that also collects its own coding
CLI usage. Add `--email [email protected]`; provider-specific emails override it independently.
The installer installs official CLIs as their own user and never performs provider login.
Open the dashboard and use **Log in / renew** for the selected profile.
It observes only coding activity inside this CT, not desktop activity on another machine.
For a worker-only CT, configure the matching machine/account/key on the existing server first:
```bash
bash tools/proxmox.sh install --ctid 202 --storage local-lvm --role worker \
--server-url http://10.0.30.150:5187 --machine-id lxc_202 \
--worker-key-file /root/lxc_202.key --email [email protected]
```
The enrollment file holds a FinalToken transport key, not a provider token. The worker's OS user
is `finaltoken`; selected provider names are its profile ids. Workers connect outbound over
the configured HTTP or HTTPS URL.
Use `finaltoken-update` inside worker CTs too.
## Host and container requirements
The host needs `pct`, `pvesh`, `pveam`, `pvesm` and Python 3. Its package repositories are untouched.
Creation uses an unprivileged Debian 13 amd64 standard CT, DHCP on `vmbr0`, on-boot startup,
2 cores, 4096 MiB RAM, 2048 MiB swap and a 20 GiB root disk. No privileged mode/nesting is enabled.
The CT needs DNS/outbound HTTPS and working package repositories. Builds install .NET 10/native
prerequisites and Git in the CT and run under `finaltoken-build`, not root. Increase resources
when needed. This is not an offline or byte-for-byte reproducible dependency build.
For static IPv4, add `--ip 192.0.2.20/24 --gateway 192.0.2.1`; `--bridge`, `--vlan`,
`--template-storage` and `--template` select host-specific resources. No host firewall, DNS or NAT
rules are changed. Your browser and workers must reach the CT on port 5187.
The host installer snapshots the selected local checkout, including uncommitted source, through
the shared allowlist in `tools/proxmox/source_bundle.py`. It excludes recognized local config,
credentials and runtime data independently of Git ignore rules, rejects symlinks and bounds size.
`--source` selects a different local checkout. It never overwrites an existing CT.
## Files and service ownership
| Location | Purpose |
|---|---|
| `/etc/finaltoken/install.json` | Managed identity, role, source checksum and successful release |
| `/etc/finaltoken/server.json`, `worker.json` | Operator account/profile configuration |
| `/etc/finaltoken/server.env`, `worker.env` | Root-only service environment and transport keys |
| `/opt/finaltoken/releases/`, `/opt/finaltoken/current` | Root-owned native releases and updater |
| `/usr/local/bin/finaltoken-update` | Link to the active release's in-container updater |
| `/var/lib/finaltoken-server/`, `/var/lib/finaltoken-worker/` | Metadata, history and CLI-owned profiles |
| `/var/cache/finaltoken-build/` | Separate build user's cache; temporary source is removed |
No CT or old release is automatically deleted. A future incompatible schema needs its own
migration/backup plan. Update/restart interrupts pending CLI login attempts.
```bash
systemctl status finaltoken-server finaltoken-worker
journalctl -u finaltoken-server -u finaltoken-worker --since today
```
Units use non-root users, restrictive permissions and process-group shutdown. Application output
is discarded to keep CLI/login material out of the journal; service lifecycle events remain.
Never dump provider credential files into support reports. For coding in a worker CT use
`su - finaltoken`; its installed CLIs are in `~/.local/bin`.
## Verification and limits
```text
python -B tools/proxmox/test_installer.py
python -B tools/proxmox/test_update.py
bash -n tools/proxmox.sh
bash -n tools/proxmox-update.sh
python -B tools/docs/check_docs.py
```
Tests substitute Proxmox, systemd, native publishing, package operations and Linux locking.
They cover source safety, service/config/key preservation, failed activation and legacy proxy
migration rollback. Updater tests use real local Git clones with a synthetic guest provisioner.
The npm regression uses an offline synthetic package and real npm; Windows adapts its global
prefix boundary to the expected Linux launcher directory. It explicitly skips without Node/npm.
No real Linux/LXC update, NativeAOT publish, advisory locking or provider login is claimed by these tests.
+71
View File
@@ -0,0 +1,71 @@
# Preparing a public repository
The repository uses the [MIT license](../LICENSE). Build/runtime dependencies keep their own
licenses. MIT licensing does not change authentication to providers or the running dashboard.
## Anonymous Git reads
After the repository host enables anonymous read access, HTTPS clone/fetch/pull need no login,
email, password or Git token. Use the public URL in [contributing](../CONTRIBUTING.md#get-the-source).
Pushes and maintainer API operations still require their own authorization.
For the Proxmox workflow, clone the published source on the host, then run its installer:
```bash
git clone https://git.finalfactory.de/FinalFactory/FinalToken.git
cd FinalToken
bash tools/proxmox.sh install --ctid 201 --storage local-lvm --email [email protected]
```
For a later update, run as root **inside the LXC**:
```bash
finaltoken-update
```
Here `--email` is the intended **provider account identity**, not a Git login. The installer
reads the local checkout only during creation; the in-container updater fetches public master itself. The branch being cloned must contain the
web/worker/installer changes. A public visibility setting alone does not publish uncommitted work.
## Files to keep local
The ignore rules exclude live deployment configuration, service keys, provider profiles, usage
history, build outputs and screenshots/logs. Keep real configuration outside the checkout when
possible. Example files must use reserved example domains and explicit placeholders.
Ignoring a file does not remove a copy that was already committed.
The dashboard and client still authenticate their transport. Provider authorization goes through
the official CLI on its machine; making source public does not make your running instance or
CLI credentials public. Do not remove dashboard/client authentication to simplify Git downloads.
## Read-only audit
From the repository root:
```text
python -B tools/check_public.py --history
```
This checks Git-listed source files (including non-ignored untracked files), the actual staged
index blobs and reachable local history (source, commit and tag text) for sensitive runtime filenames and recognizable
private-key/provider-token patterns.
It reports paths, line numbers and pattern names, never matching values. Credential/config files
are reported by filename without opening them. Binary/oversized objects are reported as skipped.
The check is a targeted pattern check, not proof that arbitrary secrets are absent.
Index blobs are checked even when the working copy is clean or different. Historical trees are
checked for private filenames even when the same blob also appeared under a harmless name.
The shared path policy in `tools/source_policy.py` also keeps recognized runtime files out of
Proxmox source archives; `.gitignore` alone does not filter a custom deployment archive.
For an independent secret-detector check, use a verified [Gitleaks release](https://github.com/gitleaks/gitleaks).
Scan the candidate source snapshot, staged index and reachable Git history with full redaction.
Keep reports outside the published source, review every finding, and never paste secret values
into issues. A clean detector report is limited to its rules and scanned inputs.
Git author/committer identities and old source remain in history. Review whether those identities
are suitable for publication. Do not silently rewrite attribution/history or delete branches to
hide findings. Any real credential exposure needs revocation and a separately authorized history
cleanup. Re-run the audit after that work and on the actual refs intended for publication.
Publication is a separate action: review the local changes, commit/push with authorization, and
enable anonymous access on the intended host. This cleanup does not change repository visibility.
+8 -2
View File
@@ -4,11 +4,17 @@ Set by schmidt.florian on 2026-10-14 ([#1](https://git.finalfactory.de/FinalFact
Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken meets them. Each requirement has a stable ID. [Decisions](decisions.md) say how FinalToken meets them.
- **R1** NativeAOT on the newest .NET. Cross-platform: at least Windows 11 and CachyOS. - **R1** NativeAOT on the newest .NET. Cross-platform: at least Windows 11 and CachyOS.
- **R2** No sign-in to an AI provider inside the app and no API key or OAuth token. Data comes - **R2** Provider credentials stay owned by the installed command-line tools. FinalToken can
through the providers' command-line tools. coordinate their official login and transiently relay an authorization response to the exact
pending CLI process. It never stores or distributes provider access/refresh tokens or API keys.
- **R3** Supported providers: at least Codex and Claude. - **R3** Supported providers: at least Codex and Claude.
- **R4** Opening the app shows a comprehensive stats panel, history included. - **R4** Opening the app shows a comprehensive stats panel, history included.
- **R5** Small, non-intrusive popups remind the user when usage runs ahead of or behind the pace - **R5** Small, non-intrusive popups remind the user when usage runs ahead of or behind the pace
of a limit. of a limit.
- **R6** A Stream Deck plugin shows selected stats on its buttons. - **R6** A Stream Deck plugin shows selected stats on its buttons.
- **R7** The app installs or updates the Stream Deck plugin automatically, as the user chooses. - **R7** The app installs or updates the Stream Deck plugin automatically, as the user chooses.
- **R8** An authenticated self-hosted dashboard combines the user's Windows/Linux machines,
keeping weekly sustainability central, account quota separate from deduplicated consumption,
and measured, estimated, unknown and stale values distinct. See [D14](decisions.md#d14--self-hosted-dashboard-and-workers).
Proxmox installation uses the host only to create the CT. Updates run inside the CT. Direct IP
access works over HTTP port 5187 without a hostname or proxy; HTTPS is optional.
+214
View File
@@ -0,0 +1,214 @@
# Self-hosted dashboard and workers
The web dashboard leads with “will my allowance last until reset?” It uses Core's existing
[D7 analysis](decisions.md#d7--pace), daily budgets, measured/estimated burn-up, recent-rate forecast,
[reset history](decisions.md#d12--reset-history) and dated API list-price estimates.
There is no inference gateway. Coding traffic continues through the user's own coding CLIs.
## Run locally
For automatic CT creation from a Proxmox host, use the [Proxmox installer](proxmox.md).
It exposes HTTP :5187 directly at the container IP; updates run inside the CT
with `finaltoken-update`.
Build from the repository root:
```text
dotnet build FinalToken.slnx -c Release
```
Create an operator-owned `server.json` outside the source tree. Account ids represent one actual
provider subscription/account. Bind every profile using the same account to the same id.
Do not merge separate provider organizations/workspaces simply because their email is the same:
this version verifies email, not organization entitlement. Use distinct account ids/profiles.
```json
{
"accounts": [
{ "id": "personal-claude", "provider": "Claude", "label": "Personal Claude", "expectedEmail": "[email protected]", "timeZone": "Europe/Berlin" },
{ "id": "personal-codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "[email protected]", "timeZone": "Europe/Berlin" }
],
"machines": [
{ "id": "desktop", "label": "Desktop", "osUser": "your-os-user", "profiles": [
{ "id": "claude", "accountId": "personal-claude" },
{ "id": "codex", "accountId": "personal-codex" }
] }
]
}
```
Set `FINALTOKEN_SERVER_CONFIG` to that file, `FINALTOKEN_SERVER_DATA` to a writable data directory,
`FINALTOKEN_DASHBOARD_KEY` to a random key of at least 32 characters and
`FINALTOKEN_MACHINE_desktop` to a different random key of at least 32 characters.
For example generate keys with your password manager or `openssl rand -hex 32`.
Do not put keys in source control, command arguments, URLs or screenshots.
Start the server from the repository root:
```text
dotnet run --project src/FinalToken.Web -c Release --no-build
```
By default it listens on `http://127.0.0.1:5187`. Set `ASPNETCORE_URLS=http://0.0.0.0:5187`
for network access, then open `http://<server-ip>:5187` and enter the dashboard key. The Proxmox
installer sets this listener automatically. No hostname registration, proxy or HTTPS is required.
The old `FINALTOKEN_PUBLIC_ORIGIN` setting is ignored, including placeholder values in existing CTs.
HTTP transport is unencrypted; an optional HTTPS proxy must preserve Host and browser Origin,
or you can configure HTTPS directly in Kestrel. Browser mutations still require the matching
request Host/Origin and CSRF protection. HTTP sessions work over HTTP; HTTPS sessions use Secure
cookies. No forwarded-header trust is enabled automatically. Proxies must not log request bodies
or authorization headers. Login URLs/codes are absent from server logs and disk state.
Keys authorize all profiles on their configured machine; use service-account file/environment
permissions and a private network/firewall. Rotate a machine key on both ends to revoke it.
## Configure each worker
Run one worker under the OS user that owns the official CLIs. It cannot switch OS users remotely.
Use absolute paths in `worker.json`; a profile's `configDirectory` is the existing `.claude` or
`.codex` directory (or the relevant environment override), and `dataDirectory` is its existing
FinalToken history/settings directory. Use a separate data/config/state directory per account.
```json
{
"machineId": "desktop",
"serverUrl": "http://127.0.0.1:5187",
"stateDirectory": "<absolute worker metadata directory>",
"profiles": [
{ "id": "claude", "provider": "Claude", "expectedEmail": "[email protected]", "configDirectory": "<absolute Claude config directory>", "dataDirectory": "<absolute existing FinalToken data directory>" },
{ "id": "codex", "provider": "Codex", "expectedEmail": "[email protected]", "configDirectory": "<absolute Codex config directory>", "dataDirectory": "<absolute separate FinalToken data directory>" }
]
}
```
JSON backslashes must be escaped on Windows, or use forward slashes. `cliPath` is an optional
local executable override; ordinary native/npm CLI discovery reuses the desktop code.
Set `FINALTOKEN_WORKER_KEY` to the server's key for this machine. Start from the repository root:
```text
dotnet run --project src/FinalToken.Worker -c Release --no-build -- <absolute worker.json path>
```
Worker URLs accept HTTP or HTTPS origins, including direct IP addresses. Workers only make
outbound connections; no worker port is open.
Use the OS service manager/Task Scheduler for unattended startup, under the intended user with
the CLI on PATH. A Linux/LXC worker needs .NET 10 (or a future locally built NativeAOT binary),
installed official CLIs, writable profile directories, outbound HTTPS and any CLI keychain
requirements. It needs no desktop/X11. Actual Linux/LXC operation has not been exercised here.
The existing release ZIP tool does not package the new hosts yet; source builds and the
[Proxmox installer](proxmox.md) are the supported setup paths.
## History, account identity and settings
The worker acquires the normal store lock before refreshing the existing store. When the desktop
app owns it, the worker reads existing observations and independently scans metadata using its
own cursors. It does not replace the user's existing settings. Both provider settings may remain
in an older desktop store; for two worker profiles, point one at that existing store and give
the other a new directory. Shared-provider historical import can use a read-only copy made while
the desktop is stopped. Never run two writers against a copied active journal.
Source metadata is durably saved before export cursor advancement. The server persists received
metadata and last-seen state atomically; offline data remains visible. Claude response ids dedupe
across transcripts, resumed copies and machines. Codex session ids/timestamps are merged before
calculating cumulative increases. Conflicting response/counter metadata is excluded with a
warning. A source copied under a different session id cannot be recognized as the same session.
Per-machine attribution of a shared session is inherently ambiguous; the dashboard shows configured
profiles/health, while consumption charts show the deduplicated account total.
Existing hourly history has no response identities. To import older history without overlapping
identified records, add these account fields to `server.json`:
```json
{ "legacyMachine": "desktop", "legacyProfile": "claude", "historyBefore": "2026-11-01T00:00:00Z" }
```
This is a fragment to merge into one account entry. Choose one source and a fixed whole UTC hour
within the still-available source logs. Before it, use that source's hourly buckets once; after
it, use identified events only. Missing source logs after the cutoff produce incomplete history,
not reconstructed guesses. Account assignment of older logs is an operator assertion. Never
reuse a profile directory for another account; configure a new profile instead.
For Codex sessions without a cumulative sample before the cutoff, the first available total
has an unknown migration baseline and is omitted with a warning. Later increases still count.
This can omit a new session's first use too; supplying complete pre-cutoff session history or
avoiding legacy import is preferable to counting potentially imported usage twice.
The newest account/window observation wins; quotas are never added. Its profile's existing
threshold, hidden-window settings and probe interval control that window. A sample older than
three probe intervals, an expired reset, offline source or unhealthy login withholds forecasts.
The account timezone controls days/DST. There is no working-hour schedule in existing D7.
API list-price values are labelled estimates; unknown models stay unpriced, and prices never
imply guaranteed subscription capacity.
## Official login coordination
Select a machine/profile under **Machines & official CLI logins**, then **Log in / renew**.
Verify its OS user and expected email before opening the official authorization page.
- Claude: the worker invokes `claude auth login --claudeai --email <expected email>` with the
selected `CLAUDE_CONFIG_DIR`. When the CLI prints its manual-code prompt, paste the browser's
authorization code into the dashboard. It travels transiently to that exact process's stdin.
There is no automatic forwarding of a desktop browser's localhost callback to a worker.
- Codex: the worker invokes `codex login --device-auth` with the selected `CODEX_HOME`, displays
the CLI's official URL/device code and lets the CLI poll/exchange/store locally. Device auth
must be enabled for that account/workspace. No remote localhost callback is needed.
- FinalToken verifies the resulting email with `claude auth status --json` or Codex app-server
`account/read`. A CLI exit code alone is not success. A mismatch may already have replaced that
profile's CLI login; FinalToken flags it and excludes new collection. Log in again with the
correct account. It does not copy, revert or auto-switch credentials.
Only the initiating browser session can inspect/respond/cancel its pending login. One attempt
per machine/profile is allowed. Cancellation and the 15-minute deadline kill the process tree;
worker restart invalidates pending routing. A server restart loses memory-only attempts; the
worker's local deadline still cancels its CLI. Closing the dialog does not cancel a login:
press **Cancel login** first if that is intended. Access/refresh tokens, API keys, cookies and
credential files are never sent through FinalToken. The authorization code necessarily passes
through browser/server/worker memory; it is never deliberately persisted or logged.
Provider login health is observed, not a fabricated 30-day expiry. The official CLI owns refresh.
The real manual Claude stdin handoff and real provider authorization still need an interactive
test with the installed CLI version. If redirected stdin is unsupported, cancel and run the login
in the selected machine's terminal. Synthetic CLI integration tests exercise the implementation,
not a provider's live service or changing terminal behavior.
## Provider usage limitations
Codex quota comes through its CLI app-server/rollout integration (D4). Claude's existing D3
`-p /usage` probe is a legacy integration; current official docs do not establish it as a
supported non-interactive quota API. Worker profiles default `enableLegacyClaudeProbe` to false.
Existing Claude observations can be read but become stale; current subscription allowance may
remain unknown. Enable the legacy probe only after verifying that your installed CLI resolves
it locally without a model request. No private OAuth usage endpoint was added. Tokens are still
collected locally from supported log parsers after identity verification.
The metadata inventory currently exports at most 100,000 source records, 30,000 quota samples
and 100,000 legacy hourly/model points per profile. Requests are capped at 32 MiB. Full inventory
exchange favors small personal fleets; it is not a streaming fleet database. When bounds or
collection fail, previous metadata is retained and collection failure is shown. Server history
has no automatic retention/deletion UI. Back up its metadata directory and the worker state.
Official references checked 2026-11-14:
- [Claude authentication and manual code handoff](https://code.claude.com/docs/en/authentication)
- [Claude CLI auth commands](https://code.claude.com/docs/en/cli-reference)
- [Codex authentication](https://learn.chatgpt.com/docs/auth?surface=cli)
- [Codex CLI flags](https://learn.chatgpt.com/docs/cli/reference)
- [Official Codex device-code implementation](https://github.com/openai/codex/blob/main/codex-rs/login/src/device_code_auth.rs)
- [Official Codex app-server account identity](https://github.com/openai/codex/blob/main/codex-rs/app-server/README.md)
## Verification
Run from the repository root:
```text
dotnet build FinalToken.slnx -c Release
dotnet test --solution FinalToken.slnx -c Release
python -B tools/test_web_dashboard.py
python -B tools/docs/check_docs.py
node --check src/FinalToken.Web/wwwroot/app.js
```
The Python check launches the real web/worker executables with a synthetic C# CLI and temporary
profiles. It tests HTTP authentication/CSRF/session isolation, Claude code relay, Codex device
flow, cancellation, account mismatch, deduplicated history and absence of login payloads in
server state. `--serve-fixture` starts the same provider-free setup for local visual inspection.
It never invokes the installed Claude or Codex CLIs. NativeAOT publishing and live provider
authorization require separate verification; analyzers/build success alone do not prove them.
+65
View File
@@ -4,7 +4,72 @@ properties use CommunityToolkit.Mvvm source generators. Custom charts use Drawin
Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI; Program owns StoreLock for the engine lifetime. DesktopApp marshals Core events to the UI;
Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots. Program passes its executable path to RefreshEngine for desktop activation through D9 snapshots.
history queries run on worker threads and discard superseded results. Keep all writes atomic (D5). history queries run on worker threads and discard superseded results. Keep all writes atomic (D5).
Panel rendering and child views take time from the panel's TimeProvider; never read the system clock directly.
Daily charts use local calendar boundaries; never assume a day lasts 24 hours. Daily charts use local calendar boundaries; never assume a day lasts 24 hours.
Stream Deck policy and the real installer come through IPluginInstaller (D11). Stream Deck policy and the real installer come through IPluginInstaller (D11).
UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support. UsePlatformDetect selects X11 on Linux in the pinned Avalonia version. Keep XWayland support.
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root. Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
## Panel and visual rules
- Keep this order: fixed 56 px header; Limits; Week use per day; Tokens (totals, hourly and daily
charts); Window charts (current-instance burn-up and past peaks); Resets (one full-width card per
provider); Breakdown by model and project; collapsed Diagnostics, hidden when empty.
Preserve scroll offset on snapshots. Sections have two columns from 1200 px content width;
limit tiles have three from 1400 px. Cards align at the top and size to their content.
- Follow the OS light/dark theme through `Ui.Theme` and `Ui.NeutralTheme`. Selection never uses
the OS accent. Selected segments use primary ink, semibold and the neutral selection surface;
checkboxes use primary ink on that surface. Keep all other Fluent accent states neutral too.
- Dark/light tokens: page `#0d0d0d`/`#f9f9f7`; surface `#1a1a19`/`#fcfcfb`;
border white/`#0b0b0b` at 10%; primary ink `#f0efec`/`#0b0b0b`;
secondary `#c3c2b7`/`#52514e`; muted `#898781` on both;
grid `#2c2c2a`/`#e1e0d9`; axis `#383835`/`#c3c2b7`;
neutral selection `#383835`/`#e1e0d9`; cache read `#5c5b57`/`#c3c2b7`.
- Claude is always orange `#d95926`/`#eb6834`; Codex always blue `#3987e5`/`#2a78d6`.
Model breakdown dots use the provider identity returned by the query, never a name heuristic.
Filtered model charts sort names into six categorical slots; later names fold into Other.
Slots in order: dark `#3987e5 #d95926 #199e70 #c98500 #d55181 #9085e9`;
light `#2a78d6 #eb6834 #1baf7a #eda100 #e87ba4 #6250d6`. Other is muted.
- Status chips always have icon and label: `#0ca30c` ✓ On track, `#ec835a` ▲ Ahead,
`#fab219` ▼ Behind. Forecasts start at 2% elapsed or as soon as Ahead, using the configured pace (D7);
until then, tiles and window charts show the Core forecast start time. Dates remain visible for every positive pace delta, but
only Ahead gets the critical `#d03b3b` mark and ⚠. Other states say "At this pace 100 % on …"
in secondary ink. Text paragraphs stay in ink colours; colour belongs to marks and meters.
- Spacing is 8/16/24 px; card radius 10, padding 16–20; system sans. Use about 12 px captions,
13 body, 15 card titles, 20 section titles and 32–36 hero numbers. Tabular figures only in
tables and axes. Compact counts use three significant digits; axes omit trailing zeros.
Exact values stay in tooltips.
- Show one composition legend in the Tokens header. Cache reads are neutral; input/output/cache
write use full/65%/40% provider colour. Reasoning is part of output; Codex cache read is part
of input. Never add either subset twice.
- Week charts show per-day steps: dashed muted even pace, and thin solid secondary budget from
today onward. Mark partial start and reset times. Keep labels beside
their own right endpoints and separated when close. No known day values means a collecting
message. Use CalendarDays, including partial dates at both ends of a window (D7).
Use `LimitAnalysis.SameInstance` for reset membership, history gaps and previous-window lookup;
resets within 15 minutes belong together, including minute drift in either direction.
- Charts use 2 px lines, hit targets at least 8 px, tooltips and recessive grids. Bars normally
have a 2 px surface gap; below 6 px width remove gaps and snap shared edges to physical pixels.
Breakdowns show eight rows plus expandable Other; keep every detail column sortable and right-aligned.
- Estimated day bars use provider outlines and 45-degree hatching; measured days stay solid. Align past
days by index and burn-ups by elapsed time. The Resets timeline puts real instances side by side
on one time axis without joining their lines; mark observed resets and show skipped time as thin
hatched bars below the plot, with overlapping spans in separate lanes (D12). Its axis ends at
the latest of now and the early resets' nominal resets, never the running instance's reset.
Burn-ups use solid measured and lighter dashed estimated lines, with no point markers.
- Use DataTooltip for every data hover: bold title, two-column label/value grid, exact and compact
counts, optional series swatches. Future days have no cumulative value. Share one date formatter
for resets and forecasts. Recent-rate captions name the actual span. Tall tooltips open beside
the pointer through `DataTooltip.BesidePointer`; a tooltip over the pointer takes the hover from
its control. Do not clear a chart's tip on pointer exit.
- Custom segments and checkboxes must show keyboard focus. NeutralCheckBox owns checked state;
templates bind its MarkVisible property and must never register checked handlers.
- Cap token estimates at 100%, retain the estimated crossing time and leave measured samples intact.
Instances start at reset minus length and end at reset or the next start. Keep gaps unassigned;
never infer short windows or overlap a sampled window with an inferred one (D7). Label real dates.
Page wheel events must never change a selection: WindowSelector bubbles them to the scroll view.
- Resets use the shared detail-table sorting, headers, row placement and expansion. Preserve
the selected window, sort and expansion on renders. Money is invariant USD at API list prices;
unknown models stay unpriced, and percent-derived values and token estimates carry `≈` (D13).
Reset tooltips list every model in Core's token order, with its tokens and API list value.
+15
View File
@@ -0,0 +1,15 @@
using Avalonia.Controls;
using Avalonia.Platform;
namespace FinalToken.App;
public static class AppIcon
{
// Keep the ICO's multiple sizes on Windows; X11 uses the same artwork as a PNG (D8).
public static WindowIcon Load()
{
var extension = OperatingSystem.IsWindows() ? "ico" : "png";
using var stream = AssetLoader.Open(new Uri($"avares://FinalToken/Assets/FinalToken.{extension}"));
return new WindowIcon(stream);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+105
View File
@@ -0,0 +1,105 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public enum BreakdownColumn { Name, Total, Share, Input, Output, CacheWrite, CacheRead, Reasoning }
public sealed class BreakdownState() : TableState<BreakdownColumn>(BreakdownColumn.Total);
public sealed class BreakdownTable : StackPanel
{
private readonly IReadOnlyList<BreakdownRow> rows;
private readonly BreakdownState state;
private readonly string title;
private readonly bool projects;
private readonly Provider? filter;
public BreakdownTable(string title, IReadOnlyList<BreakdownRow> rows, bool projects, Provider? filter, BreakdownState state)
{
this.title = title; this.rows = rows; this.projects = projects; this.filter = filter; this.state = state; Spacing = 12;
AttachedToVisualTree += (_, _) => RenderTable();
}
public static IReadOnlyList<BreakdownRow> SortRows(IEnumerable<BreakdownRow> rows, BreakdownColumn column, bool descending)
{
if (column == BreakdownColumn.Name) return DetailTable.Sort(rows, r => r.Name, descending, StringComparer.OrdinalIgnoreCase).ToArray();
double Key(BreakdownRow r) => column switch
{
BreakdownColumn.Total => r.Counts.Total, BreakdownColumn.Share => r.Share, BreakdownColumn.Input => r.Counts.Input,
BreakdownColumn.Output => r.Counts.Output, BreakdownColumn.CacheWrite => r.Counts.CacheWrite,
BreakdownColumn.CacheRead => r.Counts.CacheRead, _ => r.Counts.ReasoningOutput
};
return DetailTable.Sort(rows, Key, descending).ThenBy(r => r.Name, StringComparer.OrdinalIgnoreCase).ToArray();
}
private void RenderTable()
{
Children.Clear(); var header = new DockPanel();
if (rows.Count > 8)
{
var expand = DetailTable.Expansion(rows.Count, state, RenderTable);
DockPanel.SetDock(expand, Dock.Right); header.Children.Add(expand);
}
header.Children.Add(Ui.Text(title, 15)); Children.Add(header);
var sorted = SortRows(rows, state.Sort, state.Descending);
var visible = state.Expanded ? sorted.ToList() : sorted.Take(8).ToList();
if (!state.Expanded && sorted.Count > 8)
{
var tail = sorted.Skip(8).ToArray();
visible.Add(new($"Other ({tail.Length})", tail.Aggregate(new TokenCounts(), (sum, row) => sum + row.Counts), tail.Sum(r => r.Share), tail.SelectMany(r => r.Providers ?? []).Distinct().Order().ToArray()));
}
var reasoning = rows.Any(r => r.Providers?.Contains(Provider.Codex) == true || r.Counts.ReasoningOutput > 0);
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(reasoning ? "*,90,130,90,90,90,90,90" : "*,90,130,90,90,90,90"),
ColumnSpacing = 12, RowSpacing = 6, MinWidth = reasoning ? 1060 : 960 };
var headers = new[] { "Name", "Total", "Share", "Input", "Output", "Cache write", "Cache read", "Reasoning" };
for (var c = 0; c < (reasoning ? 8 : 7); c++)
{
var column = (BreakdownColumn)c;
var button = DetailTable.Header(headers[c], column, state, RenderTable, title.Replace(" ", "") + "Sort" + column, c == 0);
Add(button, 0, c);
}
var names = projects ? PanelWindow.ShortProjectNames(visible.Select(r => r.Name).ToArray()) : visible.Select(r => r.Name).ToArray();
for (var i = 0; i < visible.Count; i++)
{
var row = visible[i]; var tooltip = DataTooltip.Tokens(row.Name, row.Counts);
Control name;
if (!state.Expanded && i == 8 && sorted.Count > 8)
name = Ui.Button(row.Name + " ▸", () => { state.Expanded = true; RenderTable(); });
else
{
var label = Ui.Text(names[i]); label.TextWrapping = TextWrapping.NoWrap; label.TextTrimming = TextTrimming.CharacterEllipsis;
var cell = new DockPanel();
if (!projects && filter is null)
foreach (var provider in row.Providers ?? [])
{
var dot = Ui.Mark("●", Ui.ProviderColour(provider, Ui.Dark(this))); dot.Margin = new Thickness(0, 0, 6, 0);
DockPanel.SetDock(dot, Dock.Left); cell.Children.Add(dot);
}
cell.Children.Add(label); name = cell;
}
ToolTip.SetTip(name, tooltip); Add(name, i + 1, 0);
var counts = row.Counts;
long[] numbers = [counts.Total, 0, counts.Input, counts.Output, counts.CacheWrite, counts.CacheRead, counts.ReasoningOutput];
for (var c = 1; c < (reasoning ? 8 : 7); c++)
{
Control value;
if (c == 2)
{
var share = new Grid { ColumnDefinitions = new ColumnDefinitions("*,48"), ColumnSpacing = 6 };
share.Children.Add(new ProgressBar { Value = row.Share, Maximum = 1, Width = 70, MinWidth = 0, Height = 4, VerticalAlignment = VerticalAlignment.Center,
Foreground = filter is { } p ? Ui.ProviderColour(p, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this)) });
var percent = Ui.TableNumber(row.Share.ToString("P1"), 12); percent.HorizontalAlignment = HorizontalAlignment.Right; Grid.SetColumn(percent, 1); share.Children.Add(percent); value = share;
}
else { var text = Ui.TableNumber(Display.Compact(numbers[c - 1]), 12); text.HorizontalAlignment = HorizontalAlignment.Right; value = text; }
ToolTip.SetTip(value, DataTooltip.Tokens(row.Name, counts)); Add(value, i + 1, c);
}
}
Children.Add(DetailTable.Scroll(grid));
if (rows.Count == 0) Children.Add(Ui.Text("No tokens in this range.", 12, "Muted"));
void Add(Control control, int row, int column)
{
DetailTable.Add(grid, control, row, column);
}
}
}
+147
View File
@@ -0,0 +1,147 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed class BurnUpChart(LimitChart chart, TimeProvider? clock = null) : Decorator
{
private Rect plot;
private double? crosshair;
public BurnUpChart() : this(new("", [])) { }
protected override void OnInitialized()
{
base.OnInitialized(); Height = 240; ToolTip.SetShowDelay(this, 0);
if (chart.Window is { } snapshot && Display.ForecastWaiting(snapshot, chart.Now, clock) is { } waiting)
Child = new TextBlock { Text = waiting, FontSize = 12, Foreground = Ui.Colour("Muted", Ui.Dark(this)),
HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
VerticalAlignment = Avalonia.Layout.VerticalAlignment.Top, Margin = new Thickness(42, 40, 16, 0) };
PointerMoved += (_, e) =>
{
if (chart.Analysis is not { } analysis || !plot.Contains(e.GetPosition(this))) return;
crosshair = Math.Clamp(e.GetPosition(this).X, plot.Left, plot.Right);
var time = analysis.Current.Start.AddTicks((long)((analysis.Current.Reset - analysis.Current.Start).Ticks * (crosshair.Value - plot.Left) / plot.Width));
var current = analysis.Current;
var before = current.Points.LastOrDefault(p => p.Time <= time);
var after = current.Points.FirstOrDefault(p => p.Time >= time);
double? used = before?.Used;
var source = before?.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured";
if (time > chart.Now)
{
if (current.ReachedOrigin == UseOrigin.Estimated)
{ used = 100; source = "Limit reached (estimated)"; }
else if (chart.Window is { } window && LimitAnalysis.AverageUseAtReset(window.Window, chart.Now, window.Pace) is { } forecast)
{
used = window.Window.UsedPercent + (forecast - window.Window.UsedPercent) * (time - chart.Now).TotalSeconds / (current.Reset - chart.Now).TotalSeconds;
source = "Average forecast";
}
else used = null;
}
else if (before is not null && after is not null && after.Time > before.Time)
{
if (before.Time == current.Start && current.Scale is null && after.Time > current.Start) used = null;
else used = before.Used + (after.Used - before.Used) * (time - before.Time).TotalSeconds / (after.Time - before.Time).TotalSeconds;
if (before.Origin == UseOrigin.Estimated || after.Origin == UseOrigin.Estimated) source = "Estimated from tokens";
}
var expected = 100 * (time - current.Start).TotalSeconds / (current.Reset - current.Start).TotalSeconds;
ToolTip.SetTip(this, new DataTooltip(Display.Projection(time, clock), new("Used", used is { } use ? $"{use:0.##} %" : "Collecting history", Ui.ProviderColour(chart.Provider, Ui.Dark(this))),
new("Expected", $"{expected:0.##} %"), new("Delta", used is { } value ? $"{value - expected:+0.##;-0.##;0} points" : "Unknown"),
new("Source", used is null ? "No baseline" : source)));
InvalidateVisual();
};
PointerExited += (_, _) => { crosshair = null; InvalidateVisual(); };
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
if (chart.Analysis is not { } data || chart.Window is not { } snapshot) return;
var instance = data.Current; var dark = Ui.Dark(this); var muted = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(chart.Provider, dark);
plot = new Rect(42, 22, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 60));
var duration = (instance.Reset - instance.Start).TotalSeconds;
double X(DateTimeOffset time) => plot.Left + (time - instance.Start).TotalSeconds / duration * plot.Width;
double Y(double use) => plot.Bottom - use / 100 * plot.Height;
foreach (var tick in new[] { 0, 25, 50, 75, 100 })
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted);
}
context.DrawLine(new Pen(muted, 1), new(plot.Left, plot.Bottom), new(plot.Right, plot.Top));
using (context.PushClip(plot))
{
if (data.Previous is { } previous)
using (context.PushOpacity(.2)) DrawSeries(previous, true);
DrawSeries(instance, false);
if (instance.ReachedLimit is null && LimitAnalysis.AverageUseAtReset(snapshot.Window, chart.Now, snapshot.Pace) is { } average && instance.Reset > chart.Now)
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), new(X(chart.Now), Y(snapshot.Window.UsedPercent)), new(plot.Right, Y(average)));
var nowX = X(chart.Now);
if (nowX >= plot.Left && nowX <= plot.Right) context.DrawLine(new Pen(muted, 1, new DashStyle([3, 3], 0)), new(nowX, plot.Top), new(nowX, plot.Bottom));
if (crosshair is { } x) context.DrawLine(new Pen(Ui.Colour("Secondary", dark), 1), new(x, plot.Top), new(x, plot.Bottom));
}
if (instance.ReachedLimit is null && snapshot.Pace.Projection is { } crossing && crossing <= instance.Reset && crossing >= chart.Now)
{
var x = X(crossing); var mark = snapshot.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : colour;
context.DrawLine(new Pen(mark, 2), new(x, plot.Top - 5), new(x, plot.Top + 5));
ChartText.Draw(context, "100 % " + Display.Projection(crossing, clock), new(Math.Clamp(x - 80, plot.Left, Math.Max(plot.Left, plot.Right - 175)), 0), Ui.Colour("Secondary", dark));
}
if (instance.ReachedLimit is { } reached && instance.ReachedOrigin == UseOrigin.Estimated)
{
var labelX = Math.Clamp(X(reached) - 80, plot.Left, Math.Max(plot.Left, plot.Right - 260));
context.DrawLine(new Pen(colour, 2), new(X(reached), plot.Top - 5), new(X(reached), plot.Top + 5));
ChartText.Draw(context, "Limit reached (estimated) " + Display.Projection(reached, clock), new(labelX, 0), Ui.Colour("Secondary", dark));
}
ChartText.Draw(context, Display.Projection(instance.Start, clock), new(plot.Left, plot.Bottom + 12), muted);
ChartText.Draw(context, Display.Projection(instance.Reset, clock), new(Math.Max(plot.Left, plot.Right - 120), plot.Bottom + 12), muted);
var tickX = X(chart.Now);
if (tickX > plot.Left + 160 && tickX < plot.Right - 160) ChartText.Draw(context, "now", new(tickX - 10, plot.Bottom + 12), Ui.Colour("Secondary", dark));
void DrawSeries(LimitInstance series, bool previous)
{
for (var i = 1; i < series.Points.Count; i++)
{
var a = series.Points[i - 1]; var b = series.Points[i];
if (i == 1 && a.Time == series.Start && b.Origin == UseOrigin.Measured && series.Scale is null && b.Time > series.Start) continue;
var offset = previous ? instance.Start - series.Start : TimeSpan.Zero;
var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated;
using (context.PushOpacity(estimated ? .55 : 1))
context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null, lineCap: PenLineCap.Round), new(X(a.Time + offset), Y(a.Used)), new(X(b.Time + offset), Y(b.Used)));
}
}
}
}
public sealed class InstancePeaks(IReadOnlyList<LimitInstance> instances, Provider provider, TimeProvider? clock = null) : Control
{
private readonly List<(Rect Bounds, LimitInstance Instance)> hits = [];
protected override void OnInitialized()
{
base.OnInitialized(); Height = 96; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) =>
{
var instance = hits.FirstOrDefault(h => h.Bounds.Contains(e.GetPosition(this))).Instance;
ToolTip.SetTip(this, instance is null ? null : new DataTooltip(Display.Projection(instance.Start, clock) + " — " + Display.Projection(instance.End, clock),
new("Peak", $"{instance.Peak:0.##} %", Ui.ProviderColour(provider, Ui.Dark(this))),
new(instance.ReachedOrigin == UseOrigin.Estimated ? "Limit reached (estimated)" : "100 % reached", instance.ReachedLimit is { } time ? "⚠ " + Display.Projection(time, clock) : "Not reached"),
new("Source", instance.Points.Any(p => p.Origin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
};
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear(); if (instances.Count == 0) return;
var colour = Ui.ProviderColour(provider, Ui.Dark(this)); var width = Bounds.Width / instances.Count;
for (var i = 0; i < instances.Count; i++)
{
var instance = instances[instances.Count - 1 - i]; var x = i * width + width / 2;
context.DrawLine(new Pen(colour, 5, lineCap: PenLineCap.Round), new(x, 44), new(x, 44 - Math.Clamp(instance.Peak ?? 0, 0, 100) / 100 * 26));
var session = instance.Reset - instance.Start <= TimeSpan.FromDays(1);
var label = session ? instance.Start.LocalDateTime.ToString("HH:mm") + "\u2013" + instance.End.LocalDateTime.ToString("HH:mm")
: instance.Start.LocalDateTime.ToString("dd.MM") + "\u2013" + instance.End.LocalDateTime.ToString("dd.MM");
ChartText.Draw(context, label, new(Math.Max(i * width, x - 26), 52), Ui.Colour("Muted", Ui.Dark(this)), 9);
var caption = instance.ReachedLimit is { } reached ? "\u26a0 " + reached.LocalDateTime.ToString("dd.MM HH:mm")
: session ? instance.Start.LocalDateTime.ToString("dd.MM") : "";
ChartText.Draw(context, caption, new(Math.Max(i * width, x - 30), 68), Ui.Colour("Secondary", Ui.Dark(this)), 9);
ChartText.Draw(context, $"{instance.Peak:0.#}%", new(x - 16, 0), Ui.Colour("Secondary", Ui.Dark(this)));
hits.Add((new Rect(i * width, 0, width, Bounds.Height), instance));
}
}
}
+212 -48
View File
@@ -1,8 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Styling;
using FinalToken.Core; using FinalToken.Core;
using System.Globalization; using System.Globalization;
@@ -10,9 +8,26 @@ namespace FinalToken.App;
public sealed class UsageChart : Control public sealed class UsageChart : Control
{ {
private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")]; public static Rect BarBounds(double x, double bottom, double width, double height, double scaling = 1)
public static IBrush SeriesColour(int index) => Palette[index % Palette.Length]; {
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary> var gap = width < 6 ? 0 : 2;
if (gap == 0)
{
var left = Math.Round(x * scaling) / scaling;
var right = Math.Round((x + width) * scaling) / scaling;
return new Rect(left, bottom - height, Math.Max(0, right - left), Math.Max(0, height));
}
return new Rect(x + gap / 2, bottom - height, Math.Max(0, width - gap), Math.Max(0, height - gap));
}
public static IBrush SeriesColour(int index) => ModelColour(index, true);
private static IBrush ModelColour(int index, bool dark) => Brush.Parse((dark
? new[] { "#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#9085e9" }
: new[] { "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6" })[index % 6]);
public static IBrush SeriesColour(string name, IReadOnlyList<string> names, bool dark) => name switch
{
"Claude" => Ui.ProviderColour(Provider.Claude, dark), "Codex" => Ui.ProviderColour(Provider.Codex, dark),
"Other" => Ui.Colour("Muted", dark), _ => ModelColour(Math.Max(0, names.Where(n => n != "Other").Order(StringComparer.Ordinal).ToList().IndexOf(name)), dark)
};
public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false) public static IReadOnlyList<double> AxisTicks(double maximum, bool percent = false)
{ {
if (!double.IsFinite(maximum) || maximum <= 0) return [0]; if (!double.IsFinite(maximum) || maximum <= 0) return [0];
@@ -21,94 +36,243 @@ public sealed class UsageChart : Control
var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target))); var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target)));
var fraction = target / magnitude; var fraction = target / magnitude;
var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude; var step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * magnitude;
var intervals = (int)Math.Ceiling(maximum / step); return Enumerable.Range(0, (int)Math.Ceiling(maximum / step) + 1).Select(i => i * step).ToArray();
return Enumerable.Range(0, intervals + 1).Select(i => i * step).ToArray();
} }
public IReadOnlyList<ChartValue> Values { get; init; } = []; public IReadOnlyList<ChartValue> Values { get; init; } = [];
public IReadOnlyList<string> SeriesNames { get; init; } = [];
public TimeProvider Clock { get; init; } = TimeProvider.System;
public bool Percent { get; init; } public bool Percent { get; init; }
public Provider LimitProvider { get; init; }
public ChartValue? Forecast { get; init; }
public ChartValue? ForecastStart { get; init; }
public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1); public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1);
private readonly List<(Rect Rect, string Text)> hits = []; private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public UsageChart() public UsageChart()
{ {
Height = 180; Height = 208;
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text); ToolTip.SetShowDelay(this, 0);
PointerExited += (_, _) => ToolTip.SetTip(this, null); PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
} }
public override void Render(DrawingContext context) public override void Render(DrawingContext context)
{ {
base.Render(context); base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
hits.Clear(); var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark);
var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray; var plot = new Rect(50, 16, Math.Max(1, Bounds.Width - 66), Math.Max(1, Bounds.Height - 48));
var plot = new Rect(58, 12, Math.Max(1, Bounds.Width - 74), Math.Max(1, Bounds.Height - 46));
var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray(); var groups = Values.GroupBy(v => v.Time).OrderBy(g => g.Key).ToArray();
var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent); var ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent);
var max = Math.Max(1, ticks[^1]); var max = Math.Max(1, ticks[^1]);
foreach (var tick in ticks) foreach (var tick in ticks)
{ {
var y = plot.Bottom - plot.Height * tick / max; var y = plot.Bottom - plot.Height * tick / max;
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brush.Parse("#354052") : Brush.Parse("#DFE5EE")), new(plot.Left, y), new(plot.Right, y)); context.DrawLine(new Pen(Ui.Colour(tick == 0 ? "Axis" : "Grid", dark)), new(plot.Left, y), new(plot.Right, y));
var label = Percent ? $"{tick:0}%" : tick >= 1e9 ? $"{tick / 1e9:0.#}B" : tick >= 1e6 ? $"{tick / 1e6:0.#}M" : tick >= 1000 ? $"{tick / 1000:0.#}K" : $"{tick:0}"; ChartText.Draw(context, Percent ? $"{tick:0}%" : Display.Axis(tick), new(0, y - 8), ink);
Text(context, label, new(0, y - 8), ink);
} }
if (groups.Length == 0) { Text(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; } if (groups.Length == 0) { ChartText.Draw(context, "No samples in this range", new(plot.Left + 12, plot.Top + 32), ink); return; }
var series = Values.Select(v => v.Series).Distinct().ToArray(); var series = SeriesNames.Count > 0 ? SeriesNames : Values.Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
var minTime = groups[0].Key;
var lastTime = Forecast is { } f && f.Time > groups[^1].Key ? f.Time : groups[^1].Key;
var duration = Math.Max(Interval.TotalSeconds, (lastTime - minTime).TotalSeconds + (Percent ? 0 : Interval.TotalSeconds));
double X(DateTimeOffset time) => plot.Left + (time - minTime).TotalSeconds / duration * plot.Width;
Point Position(ChartValue v, double value) => new(X(v.Time), plot.Bottom - Math.Clamp(value, 0, max) / max * plot.Height);
if (Percent) if (Percent)
{ {
var colour = Ui.ProviderColour(LimitProvider, dark);
ChartValue? previous = null; ChartValue? previous = null;
var minTime = groups[0].Key;
var timeSpan = Math.Max(1, (groups[^1].Key - minTime).TotalSeconds);
Point Position(ChartValue v, double value) => new(plot.Left + (v.Time - minTime).TotalSeconds / timeSpan * plot.Width, plot.Bottom - Math.Clamp(value, 0, 100) / 100 * plot.Height);
foreach (var value in Values.OrderBy(v => v.Time)) foreach (var value in Values.OrderBy(v => v.Time))
{ {
var point = Position(value, value.Value); var point = Position(value, value.Value);
if (previous is { } p && !value.BreakBefore) if (previous is { } p && !value.BreakBefore)
{ {
context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point); context.DrawLine(new Pen(colour, 2, lineCap: PenLineCap.Round), Position(p, p.Value), point);
if (p.Expected is { } pe && value.Expected is { } expected) if (p.Expected is { } pe && value.Expected is { } expected)
context.DrawLine(new Pen(Palette[2], 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected)); context.DrawLine(new Pen(ink, 1, new DashStyle([4, 3], 0)), Position(p, pe), Position(value, expected));
} }
context.DrawEllipse(Palette[0], null, point, 3, 3); context.DrawEllipse(colour, null, point, 2, 2);
hits.Add((new(point.X - 8, point.Y - 10, 16, 20), $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Value:0.##}% · expected {(value.Expected is { } e ? $"{e:0.##}%" : "unknown")}")); hits.Add((new(point.X - 8, point.Y - 10, 16, 20), () => new DataTooltip(Display.ChartTimestamp(value.Time, Interval), new("Used", $"{value.Value:0.##} %"), new("Expected", $"{value.Expected:0.##} %"))));
previous = value; previous = value;
} }
if (previous is { } tail && Forecast is { } forecast)
{
var start = ForecastStart ?? tail;
context.DrawLine(new Pen(colour, 2, new DashStyle([1, 3], 0)), Position(start, start.Value), Position(forecast, forecast.Value));
hits.Add((new Rect(Position(forecast, forecast.Value) - new Vector(8, 8), new Size(16, 16)), () => new DataTooltip("Average forecast", new("Time", Display.Projection(forecast.Time, Clock)), new("Use", $"{forecast.Value:0.#} %"))));
}
} }
else else
{ {
var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds);
var width = plot.Width * Interval.TotalSeconds / duration; var width = plot.Width * Interval.TotalSeconds / duration;
for (var i = 0; i < groups.Length; i++) foreach (var group in groups)
{ {
var bottom = plot.Bottom; var bottom = plot.Bottom;
foreach (var value in groups[i]) foreach (var value in group.OrderBy(v => v.Series, StringComparer.Ordinal))
{ {
var height = value.Value / max * plot.Height; var height = value.Value / max * plot.Height;
var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width; var x = X(group.Key);
var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height); var gap = width < 6 ? 0 : 2;
context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect); var rect = BarBounds(x, bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens")); if (height > 0) context.DrawRectangle(SeriesColour(value.Series, series, dark), null, rect, gap == 0 ? 0 : 3, gap == 0 ? 0 : 3);
hits.Add((new(x, bottom - Math.Max(8, height), Math.Max(8, width), Math.Max(8, height)), () => new DataTooltip(Display.ChartTimestamp(group.Key, Interval),
group.Select(v => new TooltipRow(v.Series, Display.Compact(v.Value) + " · " + v.Value.ToString("N0"), SeriesColour(v.Series, series, dark))).ToArray())));
bottom -= height; bottom -= height;
} }
} }
} }
Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink); // Daily calendar ticks remain anchored to local dates through DST.
Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink); var spanDays = (lastTime - minTime).TotalDays;
ToolTip.SetShowDelay(this, 0); var stride = Math.Max(1, (int)Math.Ceiling(spanDays / Math.Max(2, plot.Width / 70)));
var day = Interval >= TimeSpan.FromDays(1) ? minTime : CalendarDays.Start(minTime);
var index = 0;
while (day <= lastTime)
{
if (day >= minTime && index % stride == 0)
ChartText.Draw(context, day.DateTime.ToString("dd.MM"), new(Math.Clamp(X(day) - 12, plot.Left, plot.Right - 40), plot.Bottom + 8), ink);
day = CalendarDays.NextStart(day); index++;
}
if (spanDays < 1) ChartText.Draw(context, minTime.LocalDateTime.ToString("dd.MM HH:mm"), new(plot.Left, plot.Bottom + 8), ink);
} }
private static void Text(DrawingContext context, string text, Point point, IBrush brush) => context.DrawText(
new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, 11, brush), point);
} }
public sealed class PaceBar(WindowSnapshot window) : Control internal static class ChartText
{ {
public static IBrush Colour(PaceState state) => Brush.Parse(state switch public static void Draw(DrawingContext context, string text, Point point, IBrush brush, double size = 11)
{ PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" });
public override void Render(DrawingContext context)
{ {
base.Render(context); var formatted = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, Typeface.Default, size, brush);
context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4); formatted.SetFontFeatures(FontFeatureCollection.Parse("tnum")); context.DrawText(formatted, point);
context.DrawRectangle(Colour(window.Pace.State), null, new Rect(0, 0, Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1), Bounds.Height), 4, 4); }
}
public sealed class PaceBar(WindowSnapshot window, DateTimeOffset now) : Control
{
public static IBrush Colour(PaceState state) => Brush.Parse(state switch
{ PaceState.Ahead => "#ec835a", PaceState.Behind => "#fab219", PaceState.OnTrack => "#0ca30c", _ => "#898781" });
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(window.Window.Provider, dark);
context.DrawRectangle(Ui.Colour("Grid", dark), null, new Rect(Bounds.Size), 3, 3);
var used = Bounds.Width * Math.Clamp(window.Window.UsedPercent / 100, 0, 1);
if (LimitAnalysis.AverageUseAtReset(window.Window, now, window.Pace) is { } forecast && forecast > window.Window.UsedPercent)
{
using (context.PushOpacity(0.25)) context.DrawRectangle(colour, null, new Rect(used, 0, Math.Max(0, Bounds.Width * Math.Min(1, forecast / 100) - used), Bounds.Height), 3, 3);
if (forecast > 100) context.DrawLine(new Pen(window.Pace.State == PaceState.Ahead ? Brush.Parse("#d03b3b") : Ui.Colour("Secondary", dark), 3), new(Bounds.Width - 2, 0), new(Bounds.Width - 2, Bounds.Height));
}
context.DrawRectangle(colour, null, new Rect(0, 0, used, Bounds.Height), 3, 3);
if (window.Pace.ElapsedFraction is { } elapsed) if (window.Pace.ElapsedFraction is { } elapsed)
context.DrawLine(new Pen(ActualThemeVariant == ThemeVariant.Dark ? Brushes.White : Brushes.Black, 2), new(Bounds.Width * elapsed, 0), new(Bounds.Width * elapsed, Bounds.Height)); context.DrawLine(new Pen(Ui.Colour("Ink", dark), 2), new(Bounds.Width * elapsed, -2), new(Bounds.Width * elapsed, Bounds.Height + 2));
ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%"); ToolTip.SetTip(this, new DataTooltip(window.Window.Label, new("Used", $"{window.Window.UsedPercent:0.##} %"), new("Expected", $"{window.Pace.ElapsedFraction * 100:0.##} %")));
}
}
public sealed class CompositionBar(TokenCounts counts, Provider provider, bool includeCache) : Control
{
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size));
var input = Math.Max(0, counts.Input - (provider == Provider.Codex ? counts.CacheRead : 0));
double[] values = [input, counts.Output, counts.CacheWrite, includeCache ? counts.CacheRead : 0];
var sum = Math.Max(1, values.Sum()); var x = 0d;
for (var i = 0; i < values.Length; i++)
{
var width = Bounds.Width * values[i] / sum;
using (context.PushOpacity(i == 1 ? .65 : i == 2 ? .4 : 1))
context.DrawRectangle(i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : Ui.ProviderColour(provider, Ui.Dark(this)), null,
new Rect(x, 0, Math.Max(0, width - 2), Bounds.Height), 3, 3);
x += width;
}
ToolTip.SetTip(this, DataTooltip.Tokens(provider + " · token composition", counts));
}
}
public sealed class DailyLimitChart(WindowDays days, Provider provider, TimeProvider? clock = null) : Control
{
private readonly TimeProvider clock = clock ?? TimeProvider.System;
private readonly List<(Rect Rect, Func<DataTooltip> Tip)> hits = [];
public DailyLimitChart() : this(new([], [], null, 0, null), Provider.Claude) { }
public IReadOnlyList<string> AxisLabels => days.Current.Select((day, i) => day.Start.DateTime.ToString("ddd") +
(i == 0 && days.InstanceStart is { } start && start != CalendarDays.Start(start, clock.LocalTimeZone) ? "\nfrom " + Display.Time(start, clock) : "") +
(i == days.Current.Count - 1 && days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone) ? "\nreset " + Display.Time(reset, clock) : "")).ToArray();
protected override void OnInitialized()
{
base.OnInitialized(); Height = 264; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Tip?.Invoke());
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
var dark = Ui.Dark(this); var ink = Ui.Colour("Muted", dark); var colour = Ui.ProviderColour(provider, dark);
var plot = new Rect(40, 24, Math.Max(1, Bounds.Width - 174), Math.Max(1, Bounds.Height - 76));
var maximum = days.Current.Concat(days.Previous).Select(d => Math.Max(d.Used ?? 0, Math.Max(d.EvenPace, d.Budget ?? 0))).DefaultIfEmpty(0).Max();
var ticks = UsageChart.AxisTicks(maximum * 1.15); var max = Math.Max(1, ticks[^1]);
double Y(double value) => plot.Bottom - value / max * plot.Height;
foreach (var tick in ticks)
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, $"{tick:0.#}%", new(0, Y(tick) - 7), ink);
}
var width = plot.Width / Math.Max(1, days.Current.Count);
var labels = AxisLabels;
for (var i = 0; i < days.Current.Count; i++)
{
var day = days.Current[i]; var x = plot.Left + i * width;
if (i < days.Previous.Count && days.Previous[i].Used is { } prior)
using (context.PushOpacity(.18)) context.DrawRectangle(null, new Pen(colour, 2), new Rect(x + 4, Y(prior), Math.Max(1, width - 8), plot.Bottom - Y(prior)), 3, 3);
if (day.Used is { } use)
{
var rect = new Rect(x + 8, Y(use), Math.Max(1, width - 16), Math.Max(0, plot.Bottom - Y(use)));
using (context.PushOpacity(day.Origin == UseOrigin.Estimated ? .45 : day.IsToday ? 1 : .5))
{
if (day.Origin == UseOrigin.Measured) context.DrawRectangle(colour, null, rect, 3, 3);
else
{
context.DrawRectangle(null, new Pen(colour, 1), rect, 3, 3);
using (context.PushClip(rect))
for (var hatchX = rect.Left - rect.Height; hatchX < rect.Right; hatchX += 8)
context.DrawLine(new Pen(colour, 1), new(hatchX, rect.Bottom), new(hatchX + rect.Height, rect.Top));
}
}
if (day.IsToday) ChartText.Draw(context, $"{use:0.#}%", new(x + 8, Y(use) - 18), Ui.Colour("Ink", dark), 12);
}
ChartText.Draw(context, labels[i], new(x + 4, plot.Bottom + 8), day.IsToday ? Ui.Colour("Ink", dark) : ink);
hits.Add((new Rect(x, plot.Top, width, plot.Height + 48), () => DataTooltip.Day(day)));
}
if (days.Current.Count == 0) return;
if (days.Reset is { } reset && reset != CalendarDays.Start(reset, clock.LocalTimeZone))
{
var start = CalendarDays.Start(reset, clock.LocalTimeZone);
var fraction = (reset - start).TotalSeconds / (CalendarDays.NextStart(start, clock.LocalTimeZone) - start).TotalSeconds;
var x = plot.Left + (days.Current.Count - 1 + fraction) * width;
context.DrawLine(new Pen(ink, 1, new DashStyle([3, 3], 0)), new(x, plot.Top), new(x, plot.Bottom));
}
var even = days.Current[^1].EvenPace; var budget = days.Current[^1].Budget;
var evenLabel = Math.Clamp(Y(even) - 7, plot.Top, plot.Bottom - 14);
var budgetLabel = budget is { } b ? Math.Clamp(Y(b) - 7, plot.Top, plot.Bottom - 14) : 0;
if (budget is { } value && Math.Abs(evenLabel - budgetLabel) < 18)
{
var middle = Math.Clamp((evenLabel + budgetLabel) / 2, plot.Top + 9, plot.Bottom - 23);
evenLabel = middle + (value >= even ? 9 : -9);
budgetLabel = middle + (value >= even ? -9 : 9);
}
// Labels name the full-day rates of the tile's plan row; partial days draw their share of it.
Reference(d => d.EvenPace, $"Even {days.EvenPace:0.#}%/day", ink, evenLabel, true);
if (budget is { } lastBudget) Reference(d => d.Budget, days.LaterBudget is { } later ? $"Budget {later:0.#}%/day" : $"Budget {lastBudget:0.#}%",
Ui.Colour("Secondary", dark), budgetLabel, false);
void Reference(Func<LimitDay, double?> select, string label, IBrush brush, double labelY, bool dashed)
{
var pen = new Pen(brush, 1, dashed ? new DashStyle([4, 4], 0) : null);
double? prior = null;
for (var i = 0; i < days.Current.Count; i++)
{
var current = select(days.Current[i]); var x = plot.Left + i * width;
if (current is { } v)
{
if (prior is { } p) context.DrawLine(pen, new(x, Y(p)), new(x, Y(v)));
context.DrawLine(pen, new(x, Y(v)), new(x + width, Y(v)));
}
prior = current;
}
if (prior is { } end && Math.Abs(labelY + 7 - Y(end)) > 3)
context.DrawLine(new Pen(brush, 1), new(plot.Right, Y(end)), new(plot.Right + 6, labelY + 7));
ChartText.Draw(context, label, new(plot.Right + 8, labelY), brush);
}
} }
} }
+68
View File
@@ -0,0 +1,68 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Layout;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed record TooltipRow(string Label, string Value, IBrush? Swatch = null);
/// <summary>D8: every data tooltip uses the same title and aligned label/value layout.</summary>
public sealed partial class DataTooltip : Border
{
public string Title { get; }
public IReadOnlyList<TooltipRow> Rows { get; }
public DataTooltip(string title, params TooltipRow[] rows)
{
Title = title; Rows = rows; MaxWidth = 520; MinWidth = 260; Padding = new Thickness(12); CornerRadius = new CornerRadius(8);
this.Bind(BackgroundProperty, this.GetResourceObservable("Surface"));
this.Bind(BorderBrushProperty, this.GetResourceObservable("Border")); BorderThickness = new Thickness(1);
var heading = Ui.Text(title, 13); heading.FontWeight = FontWeight.SemiBold; heading.MaxWidth = 480;
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 20, RowSpacing = 6 };
for (var i = 0; i < rows.Length; i++)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
var row = rows[i]; var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6 };
if (row.Swatch is { } colour) label.Children.Add(new Border { Width = 6, Height = 6, Background = colour, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center });
var labelText = Ui.Text(row.Label, 12, "Secondary"); labelText.MaxWidth = 180; label.Children.Add(labelText);
var value = Ui.TableNumber(row.Value, 12); value.HorizontalAlignment = HorizontalAlignment.Right;
Grid.SetRow(label, i); grid.Children.Add(label); Grid.SetRow(value, i); Grid.SetColumn(value, 1); grid.Children.Add(value);
}
Child = Ui.Stack(heading, grid);
}
public static string Count(long value) => Display.Compact(value) + " · " + value.ToString("N0");
public static DataTooltip Tokens(string title, TokenCounts counts) => new(title,
new("Total", Count(counts.Total)), new("Input", Count(counts.Input)), new("Output", Count(counts.Output)),
new("Cache write", Count(counts.CacheWrite)), new("Cache read", Count(counts.CacheRead)), new("Reasoning", Count(counts.ReasoningOutput)));
public static DataTooltip Day(LimitDay day)
{
var rows = new List<TooltipRow> { new("Use", day.IsFuture ? "Future day" : day.Used is { } use ? $"{use:0.##} % of the week" : "Collecting history") };
if (!day.IsFuture && day.Used is not null) rows.Add(new("Source", day.Origin == UseOrigin.Estimated ? "Estimated from tokens" : "Measured"));
if (!day.IsFuture && day.Cumulative is { } cumulative) rows.Add(new("Cumulative", $"{cumulative:0.##} %"));
if (day.IsPartial) rows.Add(new("Share", $"{day.Share.TotalHours:0.##} h"));
rows.Add(new("Even pace", $"{day.EvenPace:0.##} %"));
rows.Add(new("Budget", day.Budget is { } budget ? $"{budget:0.##} %" + (day.BudgetOrigin == UseOrigin.Estimated ? " (estimated)" : "") : "Unavailable"));
return new(day.Start.DateTime.ToString("D"), rows.ToArray());
}
/// <summary>
/// Opens a tall tooltip beside the pointer, never over it: a tooltip that covers the pointer takes
/// it from <paramref name="control"/>, which then loses the tooltip. Call before other pointer handlers.
/// </summary>
public static void BesidePointer(Control control)
{
var pointer = default(Point);
control.PointerMoved += (_, e) => pointer = e.GetPosition(control);
ToolTip.SetPlacement(control, PlacementMode.Custom);
ToolTip.SetCustomPopupPlacementCallback(control, placement =>
{
// The anchor arrives as the control's bounds in window coordinates. The gap lives in the anchor,
// because a flip mirrors anchor and gravity but not the offset.
placement.AnchorRectangle = new Rect(placement.AnchorRectangle.TopLeft + pointer - new Point(16, 0), new Size(32, 1));
placement.Anchor = PopupAnchor.Right; placement.Gravity = PopupGravity.Right;
placement.ConstraintAdjustment = PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.SlideY;
});
}
public override string ToString() => Title + "\n" + string.Join('\n', Rows.Select(r => r.Label + ": " + r.Value));
}
+14 -13
View File
@@ -1,9 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes; using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Themes.Fluent;
using Avalonia.Threading; using Avalonia.Threading;
using FinalToken.Core; using FinalToken.Core;
using FinalToken.Core.StreamDeck; using FinalToken.Core.StreamDeck;
@@ -27,7 +24,7 @@ public sealed class DesktopApp : Application
private bool quitting; private bool quitting;
private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound); private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound);
public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault(); public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault();
public override void Initialize() => Styles.Add(new FluentTheme()); public override void Initialize() => Styles.Add(Ui.NeutralTheme());
public override void OnFrameworkInitializationCompleted() public override void OnFrameworkInitializationCompleted()
{ {
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime) if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
@@ -49,10 +46,11 @@ public sealed class DesktopApp : Application
CreateTray(); panel.Show(); CreateTray(); panel.Show();
if (engine is not null) if (engine is not null)
{ {
engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.Snapshot = snapshot; model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); }); engine.SnapshotChanged += snapshot => Dispatcher.UIThread.Post(() => { model.ApplySnapshot(snapshot, engine.Settings); model.Diagnostics = engine.RecentDiagnostics; model.Message = "Updated " + snapshot.MadeAt.LocalDateTime.ToString("g"); Run(LoadHistory); });
engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); }); engine.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); });
engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel); engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel);
model.Snapshot = engine.CurrentSnapshot; if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, engine.Settings);
model.ProbeInterval = engine.Settings.ProbeInterval;
ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) }; ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) };
ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; }; ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; };
ageTimer.Start(); ageTimer.Start();
@@ -74,11 +72,7 @@ public sealed class DesktopApp : Application
var menu = new NativeMenu(); var menu = new NativeMenu();
foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) }) foreach (var (label, action) in new (string, Action)[] { ("Open", OpenPanel), ("Refresh now", () => Run(Refresh)), ("Settings", OpenSettings), ("Quit", () => Run(Quit)) })
{ var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); } { var item = new NativeMenuItem(label); item.Click += (_, _) => action(); menu.Items.Add(item); }
using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32)); tray = new TrayIcon { Icon = AppIcon.Load(), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
using (var context = bitmap.CreateDrawingContext())
{ context.DrawRectangle(Brush.Parse("#3878D4"), null, new Rect(0, 0, 32, 32), 7, 7); context.DrawLine(new Pen(Brushes.White, 4), new(9, 9), new(23, 9)); context.DrawLine(new Pen(Brushes.White, 4), new(16, 9), new(16, 25)); }
using var stream = new MemoryStream(); bitmap.Save(stream, PngBitmapEncoderOptions.Default); stream.Position = 0;
tray = new TrayIcon { Icon = new WindowIcon(stream), ToolTipText = "FinalToken", Menu = menu, IsVisible = true };
tray.Clicked += (_, _) => OpenPanel(); tray.Clicked += (_, _) => OpenPanel();
TrayIcon.SetIcons(this, [tray]); TrayIcon.SetIcons(this, [tray]);
} }
@@ -88,7 +82,11 @@ public sealed class DesktopApp : Application
panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate(); panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate();
if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel); if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel);
} }
private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync(); private async Task Refresh()
{
if (engine is null) return;
await model.RefreshAsync(() => engine.RefreshNowAsync());
}
private async Task LoadHistory() private async Task LoadHistory()
{ {
if (engine is null || model.Snapshot is not { } snapshot || quitting) return; if (engine is null || model.Snapshot is not { } snapshot || quitting) return;
@@ -100,7 +98,7 @@ public sealed class DesktopApp : Application
{ {
if (engine is null) return; if (engine is null) return;
if (settingsWindow is not null) { settingsWindow.Activate(); return; } if (settingsWindow is not null) { settingsWindow.Activate(); return; }
settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value)); settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value), () => Run(Quit), snapshot: engine.CurrentSnapshot);
settingsWindow.Closed += (_, _) => settingsWindow = null; settingsWindow.Closed += (_, _) => settingsWindow = null;
settingsWindow.Show(); settingsWindow.Show();
} }
@@ -113,6 +111,9 @@ public sealed class DesktopApp : Application
try { await engine.UpdateSettingsAsync(value); } try { await engine.UpdateSettingsAsync(value); }
catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; } catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; }
if (quitting) return; if (quitting) return;
model.ProbeInterval = value.ProbeInterval;
if (engine.CurrentSnapshot is { } snapshot) model.ApplySnapshot(snapshot, value);
await LoadHistory();
await CheckPlugin(); await CheckPlugin();
if (!quitting) await engine.RefreshNowAsync(); if (!quitting) await engine.RefreshNowAsync();
} }
+43
View File
@@ -0,0 +1,43 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
namespace FinalToken.App;
public class TableState<TColumn>(TColumn sort) where TColumn : struct, Enum
{
public bool Expanded { get; set; }
public TColumn Sort { get; set; } = sort;
public bool Descending { get; set; } = true;
}
/// <summary>Shared sorting, headers, row placement and expansion for detail tables.</summary>
public static class DetailTable
{
public static IOrderedEnumerable<TRow> Sort<TRow, TKey>(IEnumerable<TRow> rows, Func<TRow, TKey> key,
bool descending, IComparer<TKey>? comparer = null) =>
descending ? rows.OrderByDescending(key, comparer) : rows.OrderBy(key, comparer);
public static Button Header<TColumn>(string label, TColumn column, TableState<TColumn> state,
Action render, string name, bool first = false) where TColumn : struct, Enum
{
var button = Ui.Button(label + (state.Sort.Equals(column) ? state.Descending ? " ↓" : " ↑" : ""), () =>
{
state.Descending = !state.Sort.Equals(column) || !state.Descending; state.Sort = column; render();
});
button.Name = name; button.Padding = new Thickness(0, 4);
button.HorizontalAlignment = first ? HorizontalAlignment.Left : HorizontalAlignment.Right;
return button;
}
public static Button Expansion<TColumn>(int count, TableState<TColumn> state, Action render) where TColumn : struct, Enum =>
Ui.Button(state.Expanded ? "Show top 8" : $"Show all {count}", () => { state.Expanded = !state.Expanded; render(); });
public static void Add(Grid grid, Control control, int row, int column)
{
while (grid.RowDefinitions.Count <= row) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetRow(control, row); Grid.SetColumn(control, column); grid.Children.Add(control);
}
public static ScrollViewer Scroll(Grid grid) => new() { Content = grid,
HorizontalScrollBarVisibility = ScrollBarVisibility.Auto, VerticalScrollBarVisibility = ScrollBarVisibility.Disabled };
}
+2
View File
@@ -5,8 +5,10 @@
<PublishAot>true</PublishAot> <PublishAot>true</PublishAot>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault> <AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks> <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets/FinalToken.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup> <ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
<ItemGroup><AvaloniaResource Include="Assets/*" /></ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Avalonia.Desktop" /> <PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" /> <PackageReference Include="Avalonia.Themes.Fluent" />
+18
View File
@@ -0,0 +1,18 @@
using Avalonia;
using Avalonia.Controls;
namespace FinalToken.App;
/// <summary>Template reapplication never registers another checked handler.</summary>
public sealed class NeutralCheckBox : CheckBox
{
public static readonly DirectProperty<NeutralCheckBox, bool> MarkVisibleProperty =
AvaloniaProperty.RegisterDirect<NeutralCheckBox, bool>(nameof(MarkVisible), c => c.MarkVisible);
private bool markVisible;
public bool MarkVisible => markVisible;
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == IsCheckedProperty) SetAndRaise(MarkVisibleProperty, ref markVisible, IsChecked == true);
}
}
+111 -23
View File
@@ -4,11 +4,18 @@ using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public enum HistoryRange { Hours24, Days7, Days30, Days90, All } public enum HistoryRange { Hours24, Days7, Days30, Days90, All }
public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false); public sealed record ChartValue(DateTimeOffset Time, string Series, double Value, double? Expected = null, bool BreakBefore = false, double CacheRead = 0);
public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share); public sealed record BreakdownRow(string Name, TokenCounts Counts, double Share, IReadOnlyList<Provider>? Providers = null);
public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values); public sealed record LimitChart(string Label, IReadOnlyList<ChartValue> Values, Provider Provider = Provider.Claude,
DateTimeOffset? Since = null, ChartValue? Forecast = null, ChartValue? ForecastStart = null,
LimitEstimate? Analysis = null, WindowSnapshot? Window = null, DateTimeOffset Now = default);
public sealed record LimitDetail(Provider Provider, string Id, RateForecast? Recent, WindowDays? Days, DateTimeOffset? Since = null);
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily, public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects); IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> Projects)
{
public IReadOnlyList<LimitDetail> Details { get; init; } = [];
public IReadOnlyList<ResetHistory> Resets { get; init; } = [];
}
public partial class PanelViewModel : ObservableObject public partial class PanelViewModel : ObservableObject
{ {
@@ -18,6 +25,32 @@ public partial class PanelViewModel : ObservableObject
[ObservableProperty] private HistoryView history = new([], [], [], [], []); [ObservableProperty] private HistoryView history = new([], [], [], [], []);
[ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = []; [ObservableProperty] private IReadOnlyList<Diagnostic> diagnostics = [];
[ObservableProperty] private string message = "Reading local CLI data…"; [ObservableProperty] private string message = "Reading local CLI data…";
[ObservableProperty] private bool includeCacheReads = true;
[ObservableProperty] private bool refreshing;
public async Task RefreshAsync(Func<Task> refresh)
{
if (Refreshing) return;
Refreshing = true;
try { await refresh(); }
finally { Refreshing = false; }
}
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
// D8: only the panel's copy loses hidden windows; D9 totals and the engine snapshot stay intact.
public void ApplySnapshot(Snapshot snapshot, Settings settings)
{
var visible = snapshot with { Providers = snapshot.Providers.Select(p => p with
{ Windows = p.Windows.Where(w => !settings.For(p.Provider).IsHidden(w.Window)).ToArray() }).ToArray() };
var windows = visible.Providers.SelectMany(p => p.Windows).Select(w => w.Window).ToArray();
// Retire old window views immediately, before the replacement history query finishes.
History = History with
{
Limits = History.Limits.Where(l => l.Window is { } w && windows.Any(v => WindowSeries.For(v).Matches(w.Window))).ToArray(),
Details = History.Details.Where(d => windows.Any(w => w.Provider == d.Provider && w.Id == d.Id)).ToArray(),
Resets = History.Resets.Where(r => windows.Any(w => WindowSeries.For(w).Matches(r.Window))).ToArray()
};
Snapshot = visible;
}
public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch
{ {
@@ -33,43 +66,71 @@ public partial class PanelViewModel : ObservableObject
var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray(); var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray();
var hourly = Series(SeriesInterval.Hour); var hourly = Series(SeriesInterval.Hour);
var daily = Series(SeriesInterval.Day); var daily = Series(SeriesInterval.Day);
var details = new List<LimitDetail>();
var resets = new List<ResetHistory>();
var limits = providers.SelectMany(p => p.Windows.Select(w => var limits = providers.SelectMany(p => p.Windows.Select(w =>
{ {
var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now); var instanceFrom = w.Window.ResetsAt is { } r && w.Window.Length is { } l
? r - l * 9 - TimeSpan.FromMinutes(15) : now.AddDays(-14);
var resetFrom = from == DateTimeOffset.MinValue ? from : from - (w.Window.Length ?? TimeSpan.Zero) - TimeSpan.FromMinutes(15);
var series = store.LimitSamples(w.Window, resetFrom < instanceFrom ? resetFrom : instanceFrom, now);
var samples = series.Where(s => s.SampleTime >= from).ToArray();
var instanceSamples = series.Where(s => s.SampleTime >= instanceFrom).ToArray();
var tokens = w.Window.ResetsAt is { } tokenReset && w.Window.Length is { } tokenLength
? store.TokenSeriesByModel(p.Provider, tokenReset - tokenLength * 9 - TimeSpan.FromMinutes(15), now, SeriesInterval.Hour) : [];
var analysis = LimitAnalysis.Analyze(w.Window, instanceSamples, tokens, now);
if (w.Window.Length > TimeSpan.FromDays(1))
{
var tokenFrom = series.Where(s => s.ResetsAt is not null).Select(s => s.ResetsAt!.Value - s.Length!.Value)
.Append(w.Window.ResetsAt is { } resetAt ? resetAt - w.Window.Length.Value : now).Min();
resets.Add(LimitAnalysis.Resets(w.Window, series,
store.TokenSeriesByModel(p.Provider, tokenFrom, now, SeriesInterval.Hour), from, now));
}
details.Add(new(p.Provider, w.Window.Id, LimitAnalysis.Recent(w.Window, instanceSamples, now, w.Pace),
analysis?.Days,
instanceSamples.Where(s => LimitAnalysis.SameInstance(s, w.Window)).Select(s => s.SampleTime).DefaultIfEmpty(w.Window.SampleTime).Min()));
return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) => return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) =>
new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent, new ChartValue(s.SampleTime, p.Provider.ToString(), s.UsedPercent,
Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100, Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100,
i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray()); i > 0 && !LimitAnalysis.SameInstance(s, samples[i - 1]))).ToArray(), p.Provider,
samples.FirstOrDefault()?.SampleTime ?? instanceSamples.FirstOrDefault()?.SampleTime ?? w.Window.SampleTime,
w.Pace.Projection is { } projection ? new(projection, p.Provider.ToString(), 100) :
w.Window.ResetsAt is { } reset && LimitAnalysis.AverageUseAtReset(w.Window, now, w.Pace) is { } average ? new(reset, p.Provider.ToString(), average) : null,
new(now, p.Provider.ToString(), w.Window.UsedPercent), analysis, w, now);
})).ToArray(); })).ToArray();
return new(hourly, daily, limits, Breakdown(true), Breakdown(false)); var models = Breakdown(true); var projects = Breakdown(false);
return new(hourly, daily, limits, models, projects) { Details = details, Resets = resets };
IReadOnlyList<ChartValue> Series(SeriesInterval interval) => providers.SelectMany(p => IReadOnlyList<ChartValue> Series(SeriesInterval interval)
store.TokenSeries(p.Provider, from, now, interval).SelectMany(point => filter is null
? new[] { new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total) }
: ModelsAtPoint(p.Provider, point.Time, interval))).ToArray();
IEnumerable<ChartValue> ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval)
{ {
var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time); if (filter is null) return providers.SelectMany(p => store.TokenSeries(p.Provider, from, now, interval)
return store.ByModel(provider, time < from ? from : time, end > now ? now : end) .Select(point => new ChartValue(point.Time, p.Provider.ToString(), point.Counts.Total, CacheRead: point.Counts.CacheRead))).ToArray();
.Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total)); var points = store.TokenSeriesByModel(filter.Value, from, now, interval);
var names = points.Select(p => p.Model ?? "Unknown model").Distinct().Order(StringComparer.Ordinal).Take(6).ToHashSet();
return points.GroupBy(p => (p.Time, Name: names.Contains(p.Model ?? "Unknown model") ? p.Model ?? "Unknown model" : "Other"))
.Select(g => new ChartValue(g.Key.Time, g.Key.Name, g.Sum(p => (double)p.Counts.Total), CacheRead: g.Sum(p => (double)p.Counts.CacheRead))).ToArray();
} }
IReadOnlyList<BreakdownRow> Breakdown(bool models) IReadOnlyList<BreakdownRow> Breakdown(bool models)
{ {
var rows = providers.SelectMany(p => models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now)) var rows = providers.SelectMany(p => (models ? store.ByModel(p.Provider, from, now) : store.ByProject(p.Provider, from, now))
.GroupBy(r => r.Name ?? "Unknown").Select(g => new TokenBreakdown(g.Key, .Select(r => (p.Provider, r.Name, r.Counts)))
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray(); .GroupBy(r => r.Name ?? "Unknown").Select(g => new BreakdownRow(g.Key,
g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts), 0, g.Select(r => r.Provider).Distinct().Order().ToArray())).OrderByDescending(r => r.Counts.Total).ToArray();
var total = rows.Sum(r => (double)r.Counts.Total); var total = rows.Sum(r => (double)r.Counts.Total);
return rows.Select(r => new BreakdownRow(r.Name!, r.Counts, total == 0 ? 0 : r.Counts.Total / total)).ToArray(); return rows.Select(r => r with { Share = total == 0 ? 0 : r.Counts.Total / total }).ToArray();
} }
} }
} }
public static class Display public static class Display
{ {
public static string? ForecastWaiting(WindowSnapshot window, DateTimeOffset now, TimeProvider? clock = null) =>
window.Pace.State != PaceState.Unknown && !Pace.CanForecast(window.Window, now, window.Pace) &&
Pace.ForecastStartsAt(window.Window) is { } start && start > now ? "Forecast from " + Projection(start, clock) : null;
public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm");
public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval)
=> ChartTime(time, interval).ToString("g"); => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "d" : "g");
private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval) private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval)
=> interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime; => interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime;
public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null) public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null)
@@ -79,10 +140,37 @@ public static class Display
return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g", return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g",
culture ?? System.Globalization.CultureInfo.CurrentCulture); culture ?? System.Globalization.CultureInfo.CurrentCulture);
} }
public static string Time(DateTimeOffset time, TimeProvider? clock = null) =>
TimeZoneInfo.ConvertTime(time, (clock ?? TimeProvider.System).LocalTimeZone).ToString("t");
public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1 public static string Duration(TimeSpan span) => span <= TimeSpan.Zero ? "now" : span.TotalDays >= 1
? $"{span.TotalDays:0.0} d" : span.TotalHours >= 1 ? $"{span.TotalHours:0.0} h" : $"{Math.Ceiling(span.TotalMinutes):0} min"; ? $"{(int)span.TotalDays} d {span.Hours} h" : span.TotalHours >= 1 ? $"{(int)span.TotalHours} h {span.Minutes} min" : $"{Math.Ceiling(span.TotalMinutes):0} min";
public static string Span(TimeSpan span) => span.TotalHours >= 1 ? $"{span.TotalHours:0.#} h" : $"{span.TotalMinutes:0} min";
public static string Tokens(TokenCounts? counts) => counts is { } c public static string Tokens(TokenCounts? counts) => counts is { } c
? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}" ? $"{c.Total:N0} total · input {c.Input:N0} · cache read {c.CacheRead:N0} · cache write {c.CacheWrite:N0} · output {c.Output:N0} · reasoning {c.ReasoningOutput:N0}"
: "Unavailable — no known session window"; : "Unavailable — no known session window";
public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() }; public static string Compact(double count) => CompactNumber(count, false);
public static string Axis(double count) => CompactNumber(count, true);
private static string CompactNumber(double count, bool trimTrailingZeros)
{
var unit = Math.Abs(count) >= 1e9 ? 3 : Math.Abs(count) >= 1e6 ? 2 : Math.Abs(count) >= 1000 ? 1 : 0;
if (unit == 0) return count.ToString("0");
var value = count / Math.Pow(1000, unit);
var decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
value = Math.Round(value, decimals, MidpointRounding.AwayFromZero);
if (Math.Abs(value) >= 1000 && unit < 3) { value /= 1000; unit++; }
decimals = Math.Max(0, 2 - (int)Math.Floor(Math.Log10(Math.Abs(value))));
var format = trimTrailingZeros ? decimals == 0 ? "0" : "0." + new string('#', decimals) : "F" + decimals;
return value.ToString(format) + new[] { "", " K", " M", " B" }[unit];
}
public static string Forecast(DateTimeOffset date, PaceState state, TimeProvider? clock = null) =>
(state == PaceState.Ahead ? "⚠ " : "At this pace ") + "100 % on " + Projection(date, clock);
public static string State(PaceState state) => state switch { PaceState.OnTrack => "✓ On track", PaceState.Ahead => "▲ Ahead", PaceState.Behind => "▼ Behind", _ => "? Pace unknown" };
public static string Money(decimal? value) => value is { } dollars
? "≈ $" + dollars.ToString(dollars >= 100 ? "N0" : "N2", System.Globalization.CultureInfo.InvariantCulture) : "Unpriced";
public static string Limits(double percent) => "≈ " + (percent / 100).ToString("0.0") + " limits";
public static string ResetPercent(double percent, UseOrigin origin) => (origin == UseOrigin.Estimated ? "≈ " : "") +
percent.ToString("0.#") + " %";
public static string ResetDate(DateTimeOffset time, TimeProvider clock) => TimeZoneInfo.ConvertTime(time, clock.LocalTimeZone).ToString("MM-dd HH:mm");
public static string ResetFigure(string figure) => figure.Replace(' ', '\u00a0');
public static string ResetDuration(TimeSpan span) => ResetFigure(span <= TimeSpan.Zero ? "0 min" : Duration(span));
} }
+296 -99
View File
@@ -1,130 +1,327 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout; using Avalonia.Layout;
using Avalonia.Media; using Avalonia.Media;
using Avalonia.Threading;
using FinalToken.Core; using FinalToken.Core;
namespace FinalToken.App; namespace FinalToken.App;
public static class Ui
{
public static TextBlock Text(string text, double size = 13) => new() { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 10 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content) => new() { Child = content, Padding = new Thickness(18), CornerRadius = new CornerRadius(9), BorderThickness = new Thickness(1), BorderBrush = Brush.Parse("#558795A5") };
public static Button Button(string text, Action action)
{
var button = new Button { Content = text };
button.Click += (_, _) => action();
return button;
}
}
public sealed class PanelWindow : Window public sealed class PanelWindow : Window
{ {
private readonly PanelViewModel model; private readonly PanelViewModel model;
private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) }; private readonly TimeProvider clock;
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload) private readonly StackPanel body = new() { Spacing = 24, Margin = new Thickness(24) };
private readonly StackPanel statuses = new() { Orientation = Orientation.Horizontal, Spacing = 8 };
private readonly TextBlock updated = Ui.Text("", 12, "Muted");
private readonly ScrollViewer scroll;
private readonly Button refreshButton;
private bool queued;
private bool wide;
private int limitColumns;
private readonly Dictionary<Provider, string> selectedDailyWindow = [];
private readonly Dictionary<Provider, WindowSeries> selectedResetWindow = [];
private readonly Dictionary<WindowSeries, TableState<ResetColumn>> resetTables = [];
private readonly BreakdownState modelBreakdown = new(), projectBreakdown = new();
public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload, TimeProvider? clock = null)
{ {
this.model = model; this.model = model;
Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500; this.clock = clock ?? TimeProvider.System;
var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; Icon = AppIcon.Load();
header.Children.Add(Ui.Text("FinalToken", 28)); Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}";
header.Children.Add(Ui.Button("Refresh now", refresh)); Width = 1280; Height = 900; MinWidth = 960; MinHeight = 500; Ui.Theme(this);
header.Children.Add(Ui.Button("Settings", settings)); var brand = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
header.Children.Add(Ui.Button("Quit", quit)); brand.Children.Add(Ui.Text("FinalToken", 20));
var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 }; var version = Ui.Text(typeof(Program).Assembly.GetName().Version?.ToString(3) ?? "", 12, "Muted"); version.VerticalAlignment = VerticalAlignment.Center;
range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); }; brand.Children.Add(version);
var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 }; updated.VerticalAlignment = VerticalAlignment.Center; statuses.VerticalAlignment = VerticalAlignment.Center;
providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); }; var left = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, VerticalAlignment = VerticalAlignment.Center };
var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; left.Children.Add(brand); left.Children.Add(updated); left.Children.Add(statuses);
filters.Children.Add(range); filters.Children.Add(providers); var range = Segments(["24 h", "7 d", "30 d", "90 d", "All"], (int)model.Range, i => { model.Range = (HistoryRange)i; reload(); });
var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) }; var providers = Segments(["All", "Claude", "Codex"], model.ProviderFilter is { } p ? (int)p + 1 : 0,
var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0); i => { model.ProviderFilter = i == 0 ? null : (Provider)(i - 1); reload(); });
DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top); refreshButton = Ui.Button("↻", refresh); ToolTip.SetTip(refreshButton, "Refresh local data");
dock.Children.Add(new ScrollViewer { Content = body }); Content = dock; var settingsButton = Ui.Button("⚙", settings); ToolTip.SetTip(settingsButton, "Settings");
model.PropertyChanged += (_, _) => RenderModel(); var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center };
actions.Children.Add(range); actions.Children.Add(providers); actions.Children.Add(refreshButton); actions.Children.Add(settingsButton);
var header = new Grid { Name = "PanelHeader", ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(24, 0), Height = 56, ColumnSpacing = 16 };
header.Children.Add(left); Grid.SetColumn(actions, 1); header.Children.Add(actions);
var dock = new DockPanel(); DockPanel.SetDock(header, Dock.Top); dock.Children.Add(header);
scroll = new ScrollViewer { Content = body }; dock.Children.Add(scroll); Content = dock;
model.PropertyChanged += (_, _) => QueueRender();
SizeChanged += (_, _) => { if (wide != (Bounds.Width - 48 >= 1200) || limitColumns != LimitColumnCount(Bounds.Width - 48)) QueueRender(); };
ActualThemeVariantChanged += (_, _) => QueueRender();
RenderModel(); RenderModel();
} }
public static Control Segments(string[] labels, int selected, Action<int> change)
{
var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 0 };
var changing = false;
var buttons = labels.Select((label, index) => new ToggleButton { Content = label, IsChecked = index == selected,
Padding = new Thickness(8, 6), FontSize = 12 }).ToArray();
foreach (var button in buttons) button.Classes.Add("segment");
for (var i = 0; i < buttons.Length; i++)
{
var index = i;
buttons[i].IsCheckedChanged += (_, _) =>
{
if (changing) return;
changing = true;
foreach (var other in buttons.Where((_, j) => j != index)) other.IsChecked = false;
buttons[index].IsChecked = true; changing = false; change(index);
};
panel.Children.Add(buttons[i]);
}
return panel;
}
private void QueueRender()
{
if (queued) return; queued = true;
Dispatcher.UIThread.Post(() => { queued = false; RenderModel(); }, DispatcherPriority.Background);
}
public void RenderModel() public void RenderModel()
{ {
body.Children.Clear(); var offset = scroll.Offset;
body.Children.Add(Ui.Text(model.Message)); wide = (Bounds.Width > 0 ? Bounds.Width : Width) - 48 >= 1200;
limitColumns = LimitColumnCount((Bounds.Width > 0 ? Bounds.Width : Width) - 48);
var content = new List<Control>();
statuses.Children.Clear(); refreshButton.IsEnabled = !model.Refreshing;
var now = clock.GetUtcNow();
updated.Text = model.Snapshot is { } s ? "Updated " + (now - s.MadeAt < TimeSpan.FromMinutes(1) ? "just now" : Display.Duration(now - s.MadeAt) + " ago") : model.Message;
ToolTip.SetTip(updated, model.Snapshot?.MadeAt.LocalDateTime.ToString("F"));
if (model.Snapshot is { } snapshot) if (model.Snapshot is { } snapshot)
{ {
foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter)) foreach (var p in snapshot.Providers)
{ {
var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}")); var label = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
foreach (var window in provider.Windows) label.Children.Add(Ui.Mark("●", p.Status == ProviderStatus.Available ? Ui.ProviderColour(p.Provider, Ui.Dark(this)) : Ui.Colour("Muted", Ui.Dark(this))));
{ label.Children.Add(Ui.Text(p.Provider.ToString(), 12));
var w = window.Window; var pace = window.Pace; var pill = new Border { Child = label, CornerRadius = new CornerRadius(10), Padding = new Thickness(8, 4), BorderThickness = new Thickness(1), BorderBrush = Ui.Colour("Border", Ui.Dark(this)) };
var title = Ui.Text($"{w.Label} {w.UsedPercent:0.##}% {Display.State(pace.State)} {(pace.Delta is { } d ? $"{d:+0.0;-0.0;0} points" : "")}", 15); ToolTip.SetTip(pill, p.Reason ?? p.Status.ToString()); statuses.Children.Add(pill);
title.Foreground = PaceBar.Colour(pace.State);
card.Children.Add(title);
card.Children.Add(new PaceBar(window) { Height = 14 });
card.Children.Add(Ui.Text($"Reset: {(w.ResetsAt is { } reset ? Display.Duration(reset - DateTimeOffset.UtcNow) + " · " + reset.LocalDateTime.ToString("g") : "unknown")} Sample age: {Display.Duration(DateTimeOffset.UtcNow - w.SampleTime)}" +
(pace.Projection is { } projection ? $" Reaches 100%: {Display.Projection(projection)}" : "")));
}
card.Children.Add(Ui.Text("Tokens · provider totals", 15));
card.Children.Add(Ui.Text("Today " + Display.Tokens(provider.Today)));
card.Children.Add(Ui.Text("Session " + Display.Tokens(provider.Session)));
card.Children.Add(Ui.Text("Week " + Display.Tokens(provider.Week)));
card.Children.Add(Ui.Text("Cache read is included in Codex input; reasoning is included in output.", 11));
body.Children.Add(Ui.Card(card));
} }
var providers = snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter).ToArray();
content.Add(Ui.Text("Limits", 20));
var tiles = new List<Control>();
foreach (var provider in providers)
{
if (provider.Status != ProviderStatus.Available)
tiles.Add(Ui.Card(Ui.Stack(Ui.Text(provider.Provider + " · " + provider.Status, 15), Ui.Text(provider.Reason ?? "Provider disabled", 13, "Secondary"))));
else foreach (var window in provider.Windows) tiles.Add(LimitTile(window, now));
}
content.Add(Ui.Columns(tiles, limitColumns));
var longWindows = model.History.Details.Where(d => d.Days is not null && providers.Any(p => p.Provider == d.Provider &&
p.Status == ProviderStatus.Available && p.Windows.Any(w => w.Window.Id == d.Id))).ToArray();
if (longWindows.Length > 0)
{
content.Add(Ui.Text("Week use per day", 20));
content.Add(Ui.Columns(longWindows.GroupBy(d => d.Provider).Select(group =>
{
var entries = group.ToArray();
var index = Array.FindIndex(entries, d => d.Id == selectedDailyWindow.GetValueOrDefault(group.Key));
if (index < 0) index = 0;
var labels = entries.Select(d => providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == d.Provider && w.Window.Id == d.Id).Window.Label).ToArray();
Control DayView(LimitDetail item) => item.Days!.Current.Any(d => d.Used is not null)
? new DailyLimitChart(item.Days, item.Provider, clock)
: Ui.Text($"Collecting history since {(item.Since ?? providers.SelectMany(p => p.Windows).First(w => w.Window.Provider == item.Provider && w.Window.Id == item.Id).Window.SampleTime).LocalDateTime:dd.MM. HH:mm}", 12, "Muted");
var chart = new Border { Child = DayView(entries[index]) };
var title = Ui.Text(group.Key + " · " + labels[index], 15);
var stack = Ui.Stack(title);
var explanation = Ui.Text("Measured · Estimated from tokens (hatched) · faint: previous window, same day of the window", 12, "Muted");
void UpdateExplanation(LimitDetail item) => explanation.IsVisible = item.Days!.Current.Any(d => d.Used is not null);
UpdateExplanation(entries[index]);
if (entries.Length > 1)
{
var selector = new WindowSelector { ItemsSource = labels, SelectedIndex = index };
selector.SelectionChanged += (_, _) =>
{
if (selector.SelectedIndex < 0) return;
var item = entries[selector.SelectedIndex]; selectedDailyWindow[group.Key] = item.Id;
title.Text = group.Key + " · " + labels[selector.SelectedIndex];
chart.Child = DayView(item);
UpdateExplanation(item);
};
stack.Children.Add(selector);
}
stack.Children.Add(explanation);
stack.Children.Add(chart); return Ui.Card(stack);
}), wide));
}
var tokenHeader = new DockPanel();
var toggle = new NeutralCheckBox { Content = "Include cache reads", IsChecked = model.IncludeCacheReads, HorizontalAlignment = HorizontalAlignment.Right };
toggle.IsCheckedChanged += (_, _) => model.IncludeCacheReads = toggle.IsChecked == true;
DockPanel.SetDock(toggle, Dock.Right); tokenHeader.Children.Add(toggle);
var tokenTitle = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 24, VerticalAlignment = VerticalAlignment.Center };
tokenTitle.Children.Add(Ui.Text("Tokens", 20)); tokenTitle.Children.Add(CompositionLegend()); tokenHeader.Children.Add(tokenTitle); content.Add(tokenHeader);
var totals = providers.Select(p =>
{
var row = new WrapPanel();
row.Children.Add(TokenTile(p, "Today", "since 00:00", p.Today));
if (p.Session is { } session && p.Windows.FirstOrDefault(w => w.Window.Length <= TimeSpan.FromHours(5) && w.Window.ResetsAt > now) is { Window: { ResetsAt: { } reset, Length: { } length } })
row.Children.Add(TokenTile(p, "Current session", "since " + Display.Time(reset - length, clock), session));
row.Children.Add(TokenTile(p, p.WeekWindow is not null ? "Limit week" : "Calendar week",
p.WeekWindow is not null ? "since " + TimeZoneInfo.ConvertTime(p.WeekStart, clock.LocalTimeZone).ToString("ddd HH:mm") : "since Mon 00:00", p.Week));
return (Control)Ui.Card(Ui.Stack(Ui.Text(p.Provider.ToString(), 15), row));
});
content.Add(Ui.Columns(totals, wide));
} }
var h = model.History; var h = model.History;
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly }))); var seriesNames = h.Hourly.Concat(h.Daily).Select(v => v.Series).Distinct().Order(StringComparer.Ordinal).ToArray();
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), Legend(h.Daily), new UsageChart { Values = h.Daily, Interval = TimeSpan.FromDays(1) }))); Control TokenChart(string title, IReadOnlyList<ChartValue> values, bool daily) => Ui.Card(Ui.Stack(Ui.Text(title, 15),
foreach (var limit in h.Limits) Legend(seriesNames), new UsageChart { Values = values.Select(v => v with { Value = Math.Max(0, v.Value - (model.IncludeCacheReads ? 0 : v.CacheRead)) }).ToArray(),
body.Children.Add(Ui.Card(Ui.Stack(Ui.Text(limit.Label, 19), Ui.Text("Blue: used · dashed green: expected pace · gaps: window reset", 11), new UsageChart { Values = limit.Values, Percent = true }))); Clock = clock, SeriesNames = seriesNames, Interval = daily ? TimeSpan.FromDays(1) : TimeSpan.FromHours(1) }));
body.Children.Add(Breakdown("By model", h.Models)); content.Add(Ui.Columns([TokenChart("Tokens per hour", h.Hourly, false), TokenChart("Tokens per day", h.Daily, true)], wide));
body.Children.Add(Breakdown("By project", h.Projects)); var windows = h.Limits.Where(l => l.Analysis?.Current.HasData == true).ToArray();
var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19)); if (windows.Length > 0)
foreach (var d in model.Diagnostics) diagnostics.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary}"));
if (model.Diagnostics.Count == 0) diagnostics.Children.Add(Ui.Text("No recent problems."));
body.Children.Add(Ui.Card(diagnostics));
}
private static Control Legend(IReadOnlyList<ChartValue> values)
{
var legend = new WrapPanel { Orientation = Orientation.Horizontal };
var index = 0;
foreach (var series in values.Select(v => v.Series).Distinct())
{ {
var label = Ui.Text("● " + series, 12); label.Foreground = UsageChart.SeriesColour(index++); content.Add(Ui.Text("Window charts", 20));
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label); content.Add(Ui.Columns(windows.Select(limit => Ui.Card(Ui.Stack(Ui.Text(limit.Label, 15),
Ui.Text("Measured · dashed: estimated · faint: previous · dotted: forecast", 12, "Muted"), new BurnUpChart(limit with { Now = now }, clock),
Ui.Text("Past instances · peak use", 12, "Muted"), new InstancePeaks(limit.Analysis!.Past, limit.Provider, clock)))), wide));
}
var resetHistories = h.Resets.Where(r => model.ProviderFilter is null || r.Window.Provider == model.ProviderFilter).ToArray();
if (resetHistories.Length > 0)
{
content.Add(Ui.Text("Resets", 20));
foreach (var group in resetHistories.GroupBy(r => r.Window.Provider))
{
var entries = group.ToArray();
var index = Array.FindIndex(entries, r => WindowSeries.For(r.Window) == selectedResetWindow.GetValueOrDefault(group.Key));
if (index < 0) index = 0;
var title = Ui.Text(group.Key + " · " + entries[index].Window.Label, 15);
Control View(ResetHistory history)
{
var key = WindowSeries.For(history.Window);
if (!resetTables.TryGetValue(key, out var state)) resetTables[key] = state = new(ResetColumn.Start);
return new ResetCard(history, state, clock);
}
var view = new Border { Child = View(entries[index]) };
var stack = Ui.Stack(title);
if (entries.Length > 1)
{
var selector = new WindowSelector { Name = "ResetWindowSelector", ItemsSource = entries.Select(r => r.Window.Label).ToArray(), SelectedIndex = index };
selector.SelectionChanged += (_, _) =>
{
if (selector.SelectedIndex < 0) return;
var history = entries[selector.SelectedIndex]; selectedResetWindow[group.Key] = WindowSeries.For(history.Window);
title.Text = group.Key + " · " + history.Window.Label; view.Child = View(history);
};
stack.Children.Add(selector);
}
stack.Children.Add(view); content.Add(Ui.Card(stack));
}
}
content.Add(Ui.Text("Breakdown", 20));
content.Add(Ui.Card(new BreakdownTable("By model", h.Models, false, model.ProviderFilter, modelBreakdown)));
content.Add(Ui.Card(new BreakdownTable("By project", h.Projects, true, model.ProviderFilter, projectBreakdown)));
if (model.Diagnostics.Count > 0)
{
var lines = Ui.Stack();
foreach (var d in model.Diagnostics) lines.Children.Add(Ui.Text($"{d.Time.LocalDateTime:g} · {d.Provider} · {d.Code} · {d.Summary} ({d.Count})", 12, "Secondary"));
content.Add(Ui.Card(new Expander { Header = $"Diagnostics ({model.Diagnostics.Count})", Content = lines, IsExpanded = false }));
}
body.Children.Clear(); foreach (var control in content) body.Children.Add(control);
scroll.UpdateLayout(); scroll.Offset = offset;
}
private Control LimitTile(WindowSnapshot window, DateTimeOffset now)
{
var w = window.Window; var pace = window.Pace;
var detail = model.History.Details.FirstOrDefault(d => d.Provider == w.Provider && d.Id == w.Id);
var title = new DockPanel { Name = "Title" };
var chip = new Border { Child = Ui.Mark(Display.State(pace.State), Brush.Parse("#0b0b0b")), Background = PaceBar.Colour(pace.State), CornerRadius = new CornerRadius(6), Padding = new Thickness(8, 4) };
DockPanel.SetDock(chip, Dock.Right); title.Children.Add(chip); title.Children.Add(Ui.Text(w.Provider + " · " + w.Label, 15));
var card = Ui.Stack(title);
void Row(string name, Control control) { control.Name = name; card.Children.Add(control); }
Row("Percent", Ui.Text($"{w.UsedPercent:0.#} %", 36));
Row("Used", Ui.Text(now - w.SampleTime > model.ProbeInterval * 2
? $"used · ⚠ sample {Display.Duration(now - w.SampleTime)} old" : "used", 12, "Muted"));
Row("Pace", new PaceBar(window, now) { Height = 10 });
Row("Reset", Ui.Text(w.ResetsAt is { } reset ? $"Resets in {Display.Duration(reset - now)} · {Display.Projection(reset, clock)}" : "Reset unknown", 13, "Secondary"));
if (pace.Projection is { } projection)
{
var caption = Display.Forecast(projection, pace.State, clock) + $" ({Display.Duration(w.ResetsAt!.Value - projection)} before reset)";
if (pace.State == PaceState.Ahead)
{
var line = new DockPanel(); var mark = Ui.Mark("⚠ ", Brush.Parse("#d03b3b"), 13);
DockPanel.SetDock(mark, Dock.Left); line.Children.Add(mark); line.Children.Add(Ui.Text(caption[2..], 13, "Secondary")); Row("Forecast", line);
}
else Row("Forecast", Ui.Text(caption, 13, "Secondary"));
}
else if (LimitAnalysis.AverageUseAtReset(w, now, pace) is { } average)
Row("Forecast", Ui.Text($"≈ {average:0.#} % at reset", 13, "Secondary"));
else Row("Forecast", Ui.Text(Display.ForecastWaiting(window, now, clock) ?? "No forecast: pace unknown", 13, "Muted"));
if (detail?.Recent is { } recent)
{
var line = Ui.Text($"Last {Display.Span(recent.Span)}: +{recent.Increase:0.#} %" + (recent.ReachesLimit is { } date ? $" · 100 % on {Display.Projection(date, clock)}" : $" · ≈ {recent.UseAtReset:0.#} % at reset"), 13, "Secondary");
ToolTip.SetTip(line, new DataTooltip("Recent rate", new("Rate", $"{recent.PercentPerDay:0.##} %/day"), new("Observed span", Display.Duration(recent.Span)))); Row("Recent", line);
}
else Row("Recent", Ui.Text(Display.ForecastWaiting(window, now, clock) is not null && Pace.ForecastStartsAt(w) is { } forecastStart
? "Recent rate from " + Display.Projection(forecastStart, clock) : "Recent rate needs 3 h of samples", 13, "Muted"));
if (w.Length > TimeSpan.FromDays(1))
{
var days = detail?.Days;
var estimated = days?.TodayOrigin == UseOrigin.Estimated || days?.BudgetOrigin == UseOrigin.Estimated;
Row("Today", Ui.Text(days?.Today is { } today
? $"Today {(estimated ? "≈ " : "")}+{today:0.#} %" + (days.TodayBudget is { } budget ? $" of {budget:0.#} % budget" : " of the week") + (estimated ? " (estimated)" : "")
: "Today · collecting a day baseline", 15, days?.Today is null ? "Muted" : "Ink"));
var plan = $"Even pace {days?.EvenPace ?? 100 / w.Length.Value.TotalDays:0.#} %/day";
if (days?.LaterBudget is { } later) plan += $" · from tomorrow {later:0.#} %/day";
else if (days?.TodayBudget is not null && w.ResetsAt is { } lastReset) plan += " · last day, resets " + Display.Time(lastReset, clock);
Row("Plan", Ui.Text(plan, 13, "Secondary"));
}
var tile = Ui.Card(card); tile.Name = $"LimitTile-{w.Provider}-{w.Id}";
ToolTip.SetTip(tile, new DataTooltip(w.Provider + " · " + w.Label, new("Used", $"{w.UsedPercent:0.##} %"), new("Expected", $"{pace.ElapsedFraction * 100:0.##} %"),
new("State", Display.State(pace.State)), new("Reset", w.ResetsAt is { } r ? Display.Projection(r, clock) : "Unknown"), new("Sample", w.SampleTime.LocalDateTime.ToString("g")))); return tile;
}
private Control TokenTile(ProviderSnapshot provider, string label, string caption, TokenCounts counts)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.Compact(Math.Max(0, counts.Total - (model.IncludeCacheReads ? 0 : counts.CacheRead))), 32),
new CompositionBar(counts, provider.Provider, model.IncludeCacheReads) { Height = 6 }, Ui.Text(caption, 12, "Muted"));
tile.Name = $"TokenTile-{provider.Provider}-{label.Replace(' ', '-')}";
tile.Width = wide ? 164 : 188; tile.Margin = new Thickness(0, 8, 16, 0);
ToolTip.SetTip(tile, DataTooltip.Tokens(provider.Provider + " · " + label + " · " + caption, counts)); return tile;
}
private Control CompositionLegend()
{
var panel = new WrapPanel { Name = "CompositionLegend", VerticalAlignment = VerticalAlignment.Center }; var colour = model.ProviderFilter is { } provider
? Ui.ProviderColour(provider, Ui.Dark(this)) : Ui.Colour("Secondary", Ui.Dark(this));
var labels = new[] { "Input", "Output", "Cache write", "Cache read" };
for (var i = 0; i < labels.Length; i++)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(0, 0, 6, 0) };
row.Children.Add(new Border { Background = i == 3 ? Ui.Colour("Cache", Ui.Dark(this)) : colour,
Opacity = i == 1 ? .65 : i == 2 ? .4 : 1, Width = 5, Height = 5, CornerRadius = new CornerRadius(2), VerticalAlignment = VerticalAlignment.Center });
row.Children.Add(Ui.Text(labels[i], 11, "Muted")); panel.Children.Add(row);
}
return panel;
}
private Control Legend(string[] names)
{
var legend = new WrapPanel();
foreach (var name in names)
{
var item = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };
item.Children.Add(Ui.Mark("●", UsageChart.SeriesColour(name, names, Ui.Dark(this)))); item.Children.Add(Ui.Text(name, 12, "Secondary"));
item.Margin = new Thickness(0, 0, 16, 0); legend.Children.Add(item);
} }
return legend; return legend;
} }
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> rows) public static string[] ShortProjectNames(string[] paths)
{ {
var table = Ui.Stack(Ui.Text(title, 19)); var parts = paths.Select(p => p.Replace('\\', '/').Split('/', StringSplitOptions.RemoveEmptyEntries)).ToArray();
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 }; return parts.Select((p, i) =>
var headers = new[] { "Name", "Total", "Share", "Input", "Cache read", "Cache write", "Output", "Reasoning" };
AddRow(headers, 0);
var index = 1;
foreach (var row in rows)
{ {
var c = row.Counts; var depth = Math.Min(2, p.Length);
AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"), while (depth < p.Length && parts.Where((_, j) => j != i).Any(other => string.Join('/', other.TakeLast(depth)) == string.Join('/', p.TakeLast(depth)))) depth++;
c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++); return string.Join('/', p.TakeLast(depth));
} }).ToArray();
table.Children.Add(new ScrollViewer { Content = grid, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,
VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled });
if (rows.Count == 0) table.Children.Add(Ui.Text("No tokens in this range."));
return Ui.Card(table);
void AddRow(string[] values, int row)
{
grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
for (var column = 0; column < values.Length; column++)
{
var text = Ui.Text(values[column], 11); text.Margin = new Thickness(0, 4, 8, 4);
Grid.SetRow(text, row); Grid.SetColumn(text, column); grid.Children.Add(text);
}
}
} }
// Leave wheel events unhandled so they bubble to the page instead of changing selection.
private sealed class WindowSelector : ComboBox
{
protected override Type StyleKeyOverride => typeof(ComboBox);
protected override void OnPointerWheelChanged(Avalonia.Input.PointerWheelEventArgs e) { }
}
public static int LimitColumnCount(double contentWidth) => contentWidth >= 1400 ? 3 : contentWidth >= 1200 ? 2 : 1;
} }
+4 -7
View File
@@ -13,8 +13,7 @@ public sealed class PopupWindow : Window
{ {
public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null) public PopupWindow(string title, string message, Action open, string? installLabel = null, Action? install = null, Action? dismiss = null, IBrush? accent = null)
{ {
Width = 380; Height = install is null ? 145 : 180; Width = 400; Height = install is null ? 152 : 184; Ui.Theme(this);
RequestedThemeVariant = ThemeVariant.Dark;
WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false; WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false;
var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message)); var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message));
if (install is not null) if (install is not null)
@@ -24,10 +23,8 @@ public sealed class PopupWindow : Window
actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); })); actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); }));
body.Children.Add(actions); body.Children.Add(actions);
} }
var card = Ui.Card(body); card.Background = Brush.Parse("#202C40"); var card = Ui.Card(body);
body.Resources["TextControlForeground"] = Brushes.WhiteSmoke; if (accent is not null) { card.Resources["Border"] = accent; card.BorderThickness = new Thickness(3, 1, 1, 1); }
foreach (var text in body.Children.OfType<TextBlock>()) text.Foreground = Brushes.WhiteSmoke;
((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke;
Content = card; Content = card;
PointerPressed += (_, e) => PointerPressed += (_, e) =>
{ {
@@ -38,7 +35,7 @@ public sealed class PopupWindow : Window
} }
public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}", public static PopupWindow Pace(PopupEvent alert, Action open) => new($"{alert.Provider} · {Display.State(alert.State)}",
$"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." + $"{alert.Label}: {alert.Delta:+0.0;-0.0;0} points from pace." +
(alert.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State)); (alert.Projection is { } projection ? "\n" + Display.Forecast(projection, alert.State) : ""), open, accent: PaceBar.Colour(alert.State));
} }
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
+58
View File
@@ -0,0 +1,58 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using FinalToken.Core;
namespace FinalToken.App;
public sealed class ResetCard : StackPanel
{
public ResetCard(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
{
Spacing = 16;
var totals = history.Totals;
if (totals.Finished == 0)
Children.Add(Ui.Text("No reset observed since " + Display.Projection(history.FirstSample, clock), 12, "Muted"));
if (history.Instances.Count == 0) return;
var stats = new UniformGrid { Columns = 6, Rows = 1 };
void Stat(string label, string value, string caption, DataTooltip tooltip, bool available = true)
{
var tile = Ui.Stack(Ui.Text(label, 12, "Secondary"), Ui.Text(Display.ResetFigure(value), 24, available ? "Ink" : "Muted"), Ui.Text(caption, 12, "Muted"));
tile.Margin = new Thickness(0, 0, 12, 0); ToolTip.SetTip(tile, tooltip); stats.Children.Add(tile);
}
DataTooltip ValueTip(string title, ResetValue value) => new(title, new("Limits", Display.Limits(value.Percent)),
new("Percent", $"{value.Percent:N2} %"), new("Estimated tokens", value.Tokens is { } tokens ? "≈ " + tokens.ToString("N0") : "No qualifying instance"),
new("Estimated API value", Display.Money(value.ApiValue)), new("Basis", "Own instance ≥ 5 %, else series median"),
new("Coverage", "Whole listed instances; hourly boundary tokens"));
string ValueCaption(ResetValue value) => (value.Tokens is { } tokens ? Display.ResetFigure("≈ " + Display.Compact(tokens) + " tokens") + " · " : "") + Display.ResetFigure(Display.Money(value.ApiValue));
var resetCaption = totals.Finished == 0 ? "none yet" : Display.ResetFigure($"{totals.Early} early");
if (history.Instances[0].Running) resetCaption += " · " + Display.ResetFigure("1 running");
Stat("Resets", totals.Finished.ToString(), resetCaption, new DataTooltip("Listed instances",
new("Total", totals.Instances.ToString()), new("Finished", totals.Finished.ToString()), new("Early", totals.Early.ToString()),
new("Running", (totals.Instances - totals.Finished).ToString())));
Stat("Tokens", Display.Compact(totals.Tokens.Total), "in listed instances", DataTooltip.Tokens("Reset history tokens", totals.Tokens));
Stat("API value", Display.Money(totals.ApiValue), "at API list prices", new DataTooltip("API value at list prices",
new("Value", Display.Money(totals.ApiValue)), new("Unpriced tokens", DataTooltip.Count(totals.UnpricedTokens)),
new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd"))));
Stat("Unused", totals.Finished > 0 ? Display.Limits(totals.Unused.Percent) : "—",
totals.Finished > 0 ? ValueCaption(totals.Unused) : "no finished instance",
totals.Finished > 0 ? ValueTip("Unused limit · estimated value", totals.Unused) : new DataTooltip("Unused limit", new TooltipRow("Coverage", "No finished instance")), totals.Finished > 0);
Stat("Gift", totals.Early > 0 ? Display.Limits(totals.Gift.Percent) : "—",
totals.Early > 0 ? ValueCaption(totals.Gift) + " · " + Display.ResetDuration(totals.Skipped) + " skipped" : "no early reset",
totals.Early > 0 ? ValueTip("Early-reset gift · estimated value", totals.Gift) : new DataTooltip("Early-reset gift", new TooltipRow("Coverage", "No early reset")), totals.Early > 0);
Stat("100 % reached", totals.ReachedLimit + "×", Display.ResetDuration(totals.TimeAtLimit) + " at 100\u00a0%", new DataTooltip("100 % reached",
new("Instances", totals.ReachedLimit.ToString()), new("Total time", Display.ResetDuration(totals.TimeAtLimit)),
new("Source", history.Instances.Any(r => r.BurnUp.ReachedOrigin == UseOrigin.Estimated) ? "Includes token estimates" : "Measured")));
Children.Add(stats);
Children.Add(Ui.Text("Measured · dashed: estimated · vertical: reset · hatched bars below: skipped · top band: time at 100 %", 12, "Muted"));
Children.Add(new ResetTimeline(history, clock));
if (totals.Early == 0) Children.Add(Ui.Text("No early resets in this range", 12, "Muted"));
else Children.Add(Ui.Columns([
Ui.Stack(Ui.Text("Early resets by hour · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByHour, history.Window.Provider, false)),
Ui.Stack(Ui.Text("Early resets by weekday · local time", 13, "Secondary"), new ResetHistogram(history.EarlyByWeekday, history.Window.Provider, true))], true));
Children.Add(Ui.Text((history.MedianDuration is { } median ? "Median instance " + Display.ResetDuration(median) : "No finished instance yet") +
$" · early resets {totals.Early} of {totals.Finished}", 12, "Secondary"));
Children.Add(new ResetTable(history, state, clock));
}
}
+145
View File
@@ -0,0 +1,145 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Media;
using FinalToken.Core;
namespace FinalToken.App;
public sealed record ResetSkippedLane(ResetInstance Instance, int Lane);
public sealed record ResetTimelineLayout(DateTimeOffset From, DateTimeOffset To, IReadOnlyList<ResetSkippedLane> Skipped)
{
public int LaneCount => Skipped.Count == 0 ? 0 : Skipped.Max(s => s.Lane) + 1;
}
/// <summary>D12: real instances share a time axis; their burn-ups are never connected.</summary>
public sealed class ResetTimeline(ResetHistory history, TimeProvider clock) : Control
{
private const double LaneHeight = 10;
private readonly ResetTimelineLayout layout = CalculateLayout(history, clock.GetUtcNow());
private readonly List<(Rect Bounds, ResetInstance Instance)> hits = [];
public static ResetTimelineLayout CalculateLayout(ResetHistory history, DateTimeOffset now)
{
var from = history.Instances.Select(r => r.Start).DefaultIfEmpty(now).Min();
var to = history.Instances.Where(r => r.Early).Select(r => r.Reset).Append(now).Max();
if (to <= from) to = from.AddHours(1);
var laneEnds = new List<DateTimeOffset>();
var skipped = new List<ResetSkippedLane>();
foreach (var row in history.Instances.Where(r => r.Early).OrderBy(r => r.End).ThenBy(r => r.Reset))
{
var lane = laneEnds.FindIndex(end => end <= row.End);
if (lane < 0) { lane = laneEnds.Count; laneEnds.Add(row.Reset); }
else laneEnds[lane] = row.Reset;
skipped.Add(new(row, lane));
}
return new(from, to, skipped);
}
protected override void OnInitialized()
{
base.OnInitialized(); Height = 210 + layout.LaneCount * LaneHeight; ToolTip.SetShowDelay(this, 0); DataTooltip.BesidePointer(this);
PointerMoved += (_, e) =>
{
var point = e.GetPosition(this);
var instance = hits.Where(h => h.Bounds.Contains(point)).OrderBy(h => Math.Abs(h.Bounds.Center.X - point.X))
.Select(h => h.Instance).FirstOrDefault();
ToolTip.SetTip(this, instance is null ? null : DataTooltip.Reset(instance, clock));
};
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
if (history.Instances.Count == 0) return;
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(history.Window.Provider, dark); var muted = Ui.Colour("Muted", dark);
var laneSpace = layout.LaneCount * LaneHeight;
var plot = new Rect(42, 12, Math.Max(1, Bounds.Width - 58), Math.Max(1, Bounds.Height - 48 - laneSpace));
var from = layout.From; var to = layout.To;
double X(DateTimeOffset time) => plot.Left + (time - from).TotalSeconds / (to - from).TotalSeconds * plot.Width;
double Y(double used) => plot.Bottom - used / 100 * plot.Height;
foreach (var tick in new[] { 0, 25, 50, 75, 100 })
{
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), new(plot.Left, Y(tick)), new(plot.Right, Y(tick)));
ChartText.Draw(context, tick + "%", new(0, Y(tick) - 7), muted);
}
using (context.PushClip(plot))
{
foreach (var row in history.Instances.Reverse())
{
var hitWidth = Math.Max(8, X(row.End) - X(row.Start));
hits.Add((new Rect((X(row.Start) + X(row.End) - hitWidth) / 2, plot.Top, hitWidth, plot.Height), row));
if (!row.Running)
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), new(X(row.End), plot.Top), new(X(row.End), plot.Bottom));
if (row.ReachedLimit is { } reached)
{
using (context.PushOpacity(.16)) context.DrawRectangle(colour, null,
new Rect(X(reached), plot.Top, Math.Max(1, X(row.End) - X(reached)), 7));
context.DrawLine(new Pen(colour, 3), new(X(reached), plot.Top + 1), new(X(row.End), plot.Top + 1));
}
var points = row.BurnUp.Points;
for (var i = 1; i < points.Count; i++)
{
var a = points[i - 1]; var b = points[i];
if (i == 1 && a.Time == row.Start && row.BurnUp.Scale is null && b.Origin == UseOrigin.Measured && b.Time > row.Start) continue;
var estimated = a.Origin == UseOrigin.Estimated || b.Origin == UseOrigin.Estimated;
using (context.PushOpacity(estimated ? .55 : 1))
context.DrawLine(new Pen(colour, 2, estimated ? new DashStyle([4, 3], 0) : null), new(X(a.Time), Y(a.Used)), new(X(b.Time), Y(b.Used)));
}
}
}
foreach (var skipped in layout.Skipped)
{
var row = skipped.Instance;
var band = new Rect(X(row.End), plot.Bottom + 4 + skipped.Lane * LaneHeight, Math.Max(0, X(row.Reset) - X(row.End)), 6);
var hitWidth = Math.Max(8, band.Width);
hits.Add((new Rect(band.Center.X - hitWidth / 2, band.Top - 1, hitWidth, 8), row));
using (context.PushClip(band))
{
using (context.PushOpacity(.08)) context.DrawRectangle(colour, null, band);
using (context.PushOpacity(.5))
for (var x = band.Left - band.Height; x < band.Right; x += 8)
context.DrawLine(new Pen(colour), new(x, band.Bottom), new(x + band.Height, band.Top));
}
}
for (var i = 0; i < 5; i++)
{
var time = from.AddTicks((to - from).Ticks * i / 4);
ChartText.Draw(context, Display.ResetDate(time, clock), new(Math.Clamp(X(time) - 36, plot.Left, Math.Max(plot.Left, plot.Right - 86)), plot.Bottom + laneSpace + 12), muted);
}
}
}
public sealed class ResetHistogram(IReadOnlyList<int> counts, Provider provider, bool weekdays) : Control
{
private readonly List<(Rect Bounds, int Index)> hits = [];
private static readonly string[] Weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
protected override void OnInitialized()
{
base.OnInitialized(); Height = 104; ToolTip.SetShowDelay(this, 0);
PointerMoved += (_, e) =>
{
var hit = hits.Where(h => h.Bounds.Contains(e.GetPosition(this))).Select(h => (int?)h.Index).FirstOrDefault();
ToolTip.SetTip(this, hit is { } index ? new DataTooltip(weekdays ? Weekdays[index] : $"{index:00}:00–{index:00}:59 local",
new TooltipRow("Early resets", counts[index].ToString())) : null);
};
}
public override void Render(DrawingContext context)
{
base.Render(context); context.DrawRectangle(Brushes.Transparent, null, new Rect(Bounds.Size)); hits.Clear();
if (counts.Count == 0) return;
var dark = Ui.Dark(this); var colour = Ui.ProviderColour(provider, dark); var muted = Ui.Colour("Muted", dark);
var plot = new Rect(26, 10, Math.Max(1, Bounds.Width - 34), Math.Max(1, Bounds.Height - 34));
var maximum = Math.Max(1, counts.Max()); var width = plot.Width / counts.Count;
ChartText.Draw(context, maximum.ToString(), new(0, plot.Top - 6), muted);
ChartText.Draw(context, "0", new(8, plot.Bottom - 6), muted);
context.DrawLine(new Pen(Ui.Colour("Grid", dark)), plot.TopLeft, plot.TopRight);
context.DrawLine(new Pen(Ui.Colour("Axis", dark)), plot.BottomLeft, plot.BottomRight);
for (var i = 0; i < counts.Count; i++)
{
var height = plot.Height * counts[i] / maximum;
var left = plot.Left + i * width;
var bar = UsageChart.BarBounds(left, plot.Bottom, width, height, TopLevel.GetTopLevel(this)?.RenderScaling ?? 1);
if (height > 0) context.DrawRectangle(colour, null, bar);
hits.Add((new(left, plot.Top, Math.Max(8, width), plot.Height), i));
if (weekdays || i % 3 == 0)
ChartText.Draw(context, weekdays ? Weekdays[i] : i.ToString("00"), new(left + width / 2 - (weekdays ? 10 : 6), plot.Bottom + 8), muted, 11);
}
}
}
+65
View File
@@ -0,0 +1,65 @@
using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core;
namespace FinalToken.App;
public enum ResetColumn { Start, End, Lasted, Reset, Final, Reached, Tokens, ApiValue, Unused, Gift }
public sealed class ResetTable : StackPanel
{
private readonly ResetHistory history;
private readonly TableState<ResetColumn> state;
private readonly TimeProvider clock;
public ResetTable(ResetHistory history, TableState<ResetColumn> state, TimeProvider clock)
{
this.history = history; this.state = state; this.clock = clock; Spacing = 8;
AttachedToVisualTree += (_, _) => RenderTable();
}
public static IReadOnlyList<ResetInstance> SortRows(IEnumerable<ResetInstance> rows, ResetColumn column, bool descending)
{
double Key(ResetInstance row) => column switch
{
ResetColumn.Start => row.Start.UtcTicks, ResetColumn.End => row.End.UtcTicks,
ResetColumn.Lasted => row.Duration.Ticks, ResetColumn.Reset => row.Skipped.Ticks,
ResetColumn.Final => row.Final.Used, ResetColumn.Reached => row.ReachedLimit?.UtcTicks ?? double.MinValue,
ResetColumn.Tokens => row.Tokens.Total, ResetColumn.ApiValue => (double?)row.ApiValue ?? double.MinValue,
ResetColumn.Unused => row.Unused?.Percent ?? double.MinValue, _ => row.Gift?.Percent ?? double.MinValue
};
return DetailTable.Sort(rows, Key, descending).ThenByDescending(r => r.Start).ToArray();
}
private void RenderTable()
{
Children.Clear();
var heading = new DockPanel();
if (history.Instances.Count > 8)
{
var expand = DetailTable.Expansion(history.Instances.Count, state, RenderTable);
expand.Name = "ResetExpand"; DockPanel.SetDock(expand, Dock.Right); heading.Children.Add(expand);
}
heading.Children.Add(Ui.Text(state.Sort == ResetColumn.Start && state.Descending ? "Instances · newest first" : "Instances", 13, "Secondary")); Children.Add(heading);
var grid = new Grid { Name = "ResetRows", ColumnDefinitions = new ColumnDefinitions("100,100,90,150,110,110,80,90,100,100"),
ColumnSpacing = 12, RowSpacing = 8, MinWidth = 1138 };
string[] headers = ["Start", "End", "Lasted", "Reset", "Final (peak)", "100 % at", "Tokens", "API value", "Unused", "Gift"];
for (var c = 0; c < headers.Length; c++)
DetailTable.Add(grid, DetailTable.Header(headers[c], (ResetColumn)c, state, RenderTable, "ResetSort" + (ResetColumn)c, c == 0), 0, c);
var sorted = SortRows(history.Instances, state.Sort, state.Descending);
var visible = state.Expanded ? sorted : sorted.Take(8).ToArray();
for (var r = 0; r < visible.Count; r++)
{
var row = visible[r];
string Value(ResetValue? value) => value is null ? "—" : Display.ResetPercent(value.Percent, UseOrigin.Estimated);
string[] cells = [Display.ResetDate(row.Start, clock), row.Running ? "Running" : Display.ResetDate(row.End, clock), Display.ResetDuration(row.Duration),
row.Running ? "Running" : row.Early ? "Early by " + Display.ResetDuration(row.Skipped) : "On time",
Display.ResetPercent(row.Final.Used, row.Final.Origin) + (row.Peak is { } peak ? " (" + Display.ResetPercent(peak, row.PeakOrigin) + ")" : ""),
row.ReachedLimit is { } reached ? (row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.ResetDate(reached, clock) : "—",
Display.Compact(row.Tokens.Total), Display.Money(row.ApiValue), Value(row.Unused), Value(row.Gift)];
for (var c = 0; c < cells.Length; c++)
{
var text = Ui.TableNumber(cells[c], 12); text.HorizontalAlignment = c == 0 ? HorizontalAlignment.Left : HorizontalAlignment.Right;
ToolTip.SetTip(text, DataTooltip.Reset(row, clock)); DataTooltip.BesidePointer(text); DetailTable.Add(grid, text, r + 1, c);
}
}
Children.Add(DetailTable.Scroll(grid));
}
}
+53
View File
@@ -0,0 +1,53 @@
using FinalToken.Core;
namespace FinalToken.App;
public sealed partial class DataTooltip
{
public static DataTooltip Reset(ResetInstance row, TimeProvider clock)
{
var rows = new List<TooltipRow>
{
new("Start", Display.Projection(row.Start, clock)),
new(row.Running ? "As of" : "End", Display.Projection(row.End, clock)),
new("Nominal reset", Display.Projection(row.Reset, clock)),
new("Lasted", Display.ResetDuration(row.Duration)),
new("Final use", Display.ResetPercent(row.Final.Used, row.Final.Origin)),
new("Peak", row.Peak is { } peak ? Display.ResetPercent(peak, row.PeakOrigin) : "Collecting history"),
new("100 % reached", row.ReachedLimit is { } reached ?
(row.BurnUp.ReachedOrigin == UseOrigin.Estimated ? "≈ " : "") + Display.Projection(reached, clock) : "Not reached"),
new("Time at 100 %", Display.ResetDuration(row.TimeAtLimit)),
new("Total tokens", Count(row.Tokens.Total)), new("Input", Count(row.Tokens.Input)),
new("Cache read", Count(row.Tokens.CacheRead)), new("Cache write", Count(row.Tokens.CacheWrite)),
new("Output", Count(row.Tokens.Output)), new("Reasoning (in output)", Count(row.Tokens.ReasoningOutput)),
new("API list value", Display.Money(row.ApiValue)), new("Unpriced tokens", Count(row.UnpricedTokens))
};
if (row.Models.Count > 0) rows.Add(new("Models", row.Models.Count.ToString()));
foreach (var model in row.Models)
rows.Add(new(model.Model ?? "Unknown model", Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue)));
rows.Add(new("Tokens per percent", row.ValuePerPercent is { } rate ? "≈ " + Display.Compact(rate.Tokens) +
" · " + rate.Tokens.ToString("N2") : "No qualifying instance"));
rows.Add(new("API value per percent", Display.Money(row.ValuePerPercent?.ApiValue)));
rows.Add(new("Value basis", row.ValuePerPercent?.Basis switch
{
PercentBasis.OwnInstance => "Own instance (final ≥ 5 %)",
PercentBasis.SeriesMedian => "Median of qualifying listed instances",
_ => "No instance with final ≥ 5 %"
}));
if (row.Unused is { } unused) AddValue("Unused", unused);
if (row.Gift is { } gift) { AddValue("Gift", gift); rows.Add(new("Skipped", Display.ResetDuration(row.Skipped))); }
var estimates = new List<string>();
if (row.Final.Origin == UseOrigin.Estimated) estimates.Add("final");
if (row.PeakOrigin == UseOrigin.Estimated) estimates.Add("peak");
if (row.BurnUp.ReachedOrigin == UseOrigin.Estimated) estimates.Add("100 % time");
if (row.Unused is not null) estimates.Add("unused value");
if (row.Gift is not null) estimates.Add("gift value");
rows.Add(new("Estimated figures", estimates.Count == 0 ? "API list value" : string.Join(", ", estimates) + ", API list value"));
rows.Add(new("Prices checked", ApiPrices.CheckedOn.ToString("yyyy-MM-dd") + " · hourly boundary tokens"));
return new(row.Running ? "Running instance" : row.Early ? "Early reset" : "On-time reset", rows.ToArray());
void AddValue(string label, ResetValue value) => rows.Add(new(label,
Display.ResetPercent(value.Percent, UseOrigin.Estimated) + " · " +
(value.Tokens is { } count ? "≈ " + Display.Compact(count) + " tokens · " : "") + Display.Money(value.ApiValue)));
}
}
+97 -34
View File
@@ -1,5 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Layout;
using FinalToken.Core; using FinalToken.Core;
using FinalToken.Core.StreamDeck; using FinalToken.Core.StreamDeck;
@@ -7,30 +8,64 @@ namespace FinalToken.App;
public sealed class SettingsWindow : Window public sealed class SettingsWindow : Window
{ {
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save) public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save, Action? quit = null, Action<string>? openFolder = null,
Snapshot? snapshot = null)
{ {
Title = "FinalToken settings"; Width = 620; Height = 800; Icon = AppIcon.Load();
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24); Title = "FinalToken settings"; Width = 760; Height = 900; MinWidth = 600; MinHeight = 500; Ui.Theme(this);
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60); var body = new StackPanel { Spacing = 16, Margin = new Thickness(24) };
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60); body.Children.Add(Ui.Text("Settings", 24));
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100); var general = Ui.Stack(Ui.Text("General", 15));
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind); var refresh = Number(general, "Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray); var probe = Number(general, "Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex); var threshold = Number(general, "Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
body.Children.Add(Ui.Text("Stream Deck", 19)); var startup = Check(general, "Start with the OS", initial.StartWithOs);
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}")); var tray = Check(general, "Close to tray", initial.CloseToTray);
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode }; body.Children.Add(Ui.Card(general));
body.Children.Add(mode); var popups = Ui.Stack(Ui.Text("Popups", 15));
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)")); var ahead = Check(popups, "Ahead popups", initial.PopupAhead);
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed); var behind = Check(popups, "Behind popups", initial.PopupBehind);
var error = Ui.Text(""); body.Children.Add(error); var claudePopups = PopupControls(popups, "Claude", initial.Claude);
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right }; var codexPopups = PopupControls(popups, "Codex", initial.Codex);
body.Children.Add(Ui.Card(popups));
var providers = Ui.Stack(Ui.Text("Providers", 15));
var claude = ProviderControls(providers, Provider.Claude, initial.Claude, snapshot);
var codex = ProviderControls(providers, Provider.Codex, initial.Codex, snapshot);
body.Children.Add(Ui.Card(providers));
var streamDeck = Ui.Stack(Ui.Text("Stream Deck", 15), Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}", 13, "Secondary"));
var selectedMode = initial.StreamDeckInstallMode;
streamDeck.Children.Add(PanelWindow.Segments(["Off", "Ask", "Automatic"], (int)selectedMode, i => selectedMode = (InstallMode)i));
streamDeck.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)", 12, "Secondary"));
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; streamDeck.Children.Add(dismissed);
body.Children.Add(Ui.Card(streamDeck));
var about = Ui.Stack(Ui.Text("About", 15), Ui.Text("FinalToken " + typeof(Program).Assembly.GetName().Version?.ToString(3)), Ui.Text(DataPaths.DataDirectory, 12, "Secondary"));
var error = Ui.Text("", 12, "Secondary");
about.Children.Add(Ui.Button("Open folder", () =>
{
try
{
if (openFolder is not null) openFolder(DataPaths.DataDirectory);
else System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(DataPaths.DataDirectory) { UseShellExecute = true });
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or System.ComponentModel.Win32Exception or InvalidOperationException)
{ error.Text = "Could not open the data folder."; }
}));
body.Children.Add(Ui.Card(about));
var footer = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto,Auto"), ColumnSpacing = 8, Margin = new Thickness(24, 16) };
var quitButton = Ui.Button("Quit FinalToken", () => quit?.Invoke()); quitButton.IsEnabled = quit is not null;
footer.Children.Add(quitButton);
var cancel = Ui.Button("Cancel", Close); Grid.SetColumn(cancel, 2); footer.Children.Add(cancel);
var button = Ui.Button("Save", () => { }); Grid.SetColumn(button, 3); footer.Children.Add(button);
button.Click += async (_, _) => button.Click += async (_, _) =>
{ {
var value = initial with { RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)), var value = initial with
{
RefreshInterval = TimeSpan.FromSeconds((double)(refresh.Value ?? 0)), ProbeInterval = TimeSpan.FromMinutes((double)(probe.Value ?? 0)),
PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true, PaceThreshold = (double)(threshold.Value ?? 0), PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true,
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(), StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true,
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() }; Claude = claudePopups(claude()), Codex = codexPopups(codex()), StreamDeckInstallMode = selectedMode,
DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim()
};
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; } if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
button.IsEnabled = false; button.IsEnabled = false;
try { await save(value); Close(); } try { await save(value); Close(); }
@@ -38,21 +73,49 @@ public sealed class SettingsWindow : Window
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException) catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; } { error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
}; };
body.Children.Add(button); Content = new ScrollViewer { Content = body }; var dock = new DockPanel();
var bottom = Ui.Stack(error, footer); DockPanel.SetDock(bottom, Dock.Bottom); dock.Children.Add(bottom);
NumericUpDown Number(string label, decimal value, decimal min, decimal max) dock.Children.Add(new ScrollViewer { Content = body }); Content = dock;
{ body.Children.Add(Ui.Text(label)); var c = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; body.Children.Add(c); return c; } }
CheckBox Check(string label, bool value) private static NumericUpDown Number(StackPanel parent, string label, decimal value, decimal min, decimal max)
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; } {
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config) var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,160"), ColumnSpacing = 16 };
grid.Children.Add(Ui.Text(label, 13, "Secondary"));
var control = new NumericUpDown { Value = value, Minimum = min, Maximum = max }; Grid.SetColumn(control, 1); grid.Children.Add(control);
parent.Children.Add(grid); return control;
}
private static CheckBox Check(StackPanel parent, string label, bool value)
{
var c = new NeutralCheckBox { Content = label, IsChecked = value, Name = label.Replace(" ", "") }; parent.Children.Add(c); return c;
}
private static Func<ProviderSettings, ProviderSettings> PopupControls(StackPanel parent, string name, ProviderSettings config)
{
var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 16 };
row.Children.Add(Ui.Text(name));
var enabled = Check(row, "Popups enabled", config.PopupsEnabled);
var ahead = Check(row, "Ahead", config.PopupAhead); var behind = Check(row, "Behind", config.PopupBehind);
foreach (var c in row.Children.OfType<CheckBox>()) c.Name = name + c.Name;
parent.Children.Add(row);
return value => value with { PopupsEnabled = enabled.IsChecked == true, PopupAhead = ahead.IsChecked == true, PopupBehind = behind.IsChecked == true };
}
private static Func<ProviderSettings> ProviderControls(StackPanel parent, Provider provider, ProviderSettings config, Snapshot? snapshot)
{
var name = provider.ToString();
parent.Children.Add(Ui.Text(name)); var enabled = Check(parent, "Enabled", config.Enabled);
enabled.Name = name + "Enabled";
parent.Children.Add(Ui.Text("CLI path (empty uses PATH)", 12, "Secondary"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; parent.Children.Add(path);
var known = (snapshot?.Providers.Where(p => p.Provider == provider).SelectMany(p => p.Windows).Select(w => HiddenLimitWindow.For(w.Window)) ?? [])
.Concat(config.HiddenWindows).DistinctBy(w => w.Series(provider)).ToArray();
var windows = new List<(HiddenLimitWindow Window, CheckBox Show)>();
foreach (var window in known)
{ {
body.Children.Add(Ui.Text(name, 19)); var show = Check(parent, "Show " + window.Label, !config.IsHidden(window.Series(provider)));
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled); show.Name = name + "Window" + windows.Count;
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind); windows.Add((window, show));
body.Children.Add(Ui.Text("CLI path (empty uses PATH)"));
var path = new TextBox { Name = name + "CliPath", Text = config.CliPath ?? "" }; body.Children.Add(path);
return () => config with { Enabled = enabled.IsChecked == true, PopupsEnabled = popups.IsChecked == true, PopupAhead = pa.IsChecked == true,
PopupBehind = pb.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim() };
} }
if (known.Length == 0) parent.Children.Add(Ui.Text("No known limit windows", 12, "Muted"));
return () => config with { Enabled = enabled.IsChecked == true, CliPath = string.IsNullOrWhiteSpace(path.Text) ? null : path.Text.Trim(),
HiddenWindows = windows.Where(w => w.Show.IsChecked != true).Select(w => w.Window).ToArray() };
} }
} }
+141
View File
@@ -0,0 +1,141 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Styling;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Templates;
using Avalonia.Markup.Xaml.MarkupExtensions;
using Avalonia.Themes.Fluent;
using FinalToken.Core;
namespace FinalToken.App;
public static class Ui
{
public static IBrush Colour(string role, bool dark) => Brush.Parse(role switch
{
"Page" => dark ? "#0d0d0d" : "#f9f9f7",
"Surface" => dark ? "#1a1a19" : "#fcfcfb",
"Border" => dark ? "#1affffff" : "#1a0b0b0b",
"Ink" => dark ? "#f0efec" : "#0b0b0b",
"Secondary" => dark ? "#c3c2b7" : "#52514e",
"Grid" => dark ? "#2c2c2a" : "#e1e0d9",
"Axis" => dark ? "#383835" : "#c3c2b7",
"Selection" => dark ? "#383835" : "#e1e0d9",
"Claude" => dark ? "#d95926" : "#eb6834",
"Codex" => dark ? "#3987e5" : "#2a78d6",
"Cache" => dark ? "#5c5b57" : "#c3c2b7",
_ => "#898781"
});
public static bool Dark(StyledElement element) => element.ActualThemeVariant == ThemeVariant.Dark;
public static IBrush ProviderColour(Provider provider, bool dark) => Colour(provider.ToString(), dark);
public static void Theme(Window window)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var resources = new ResourceDictionary();
foreach (var role in new[] { "Page", "Surface", "Border", "Ink", "Secondary", "Muted", "Grid", "Axis", "Selection", "Claude", "Codex", "Cache" })
resources[role] = Colour(role, theme == ThemeVariant.Dark);
window.Resources.ThemeDictionaries[theme] = resources;
}
window.Bind(TemplatedControl.BackgroundProperty, window.GetResourceObservable("Page"));
window.Bind(TemplatedControl.ForegroundProperty, window.GetResourceObservable("Ink"));
window.FontSize = 13;
var segments = new Style(s => s.OfType<ToggleButton>().Class("segment"));
segments.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Surface")));
segments.Setters.Add(new Setter(TemplatedControl.ForegroundProperty, new DynamicResourceExtension("Ink")));
segments.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<ToggleButton>((button, _) =>
{
var presenter = new ContentPresenter { HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center };
presenter.Bind(ContentPresenter.ContentProperty, button.GetObservable(ContentControl.ContentProperty));
presenter.Bind(ContentPresenter.ForegroundProperty, button.GetObservable(TemplatedControl.ForegroundProperty));
presenter.Bind(ContentPresenter.FontWeightProperty, button.GetObservable(TemplatedControl.FontWeightProperty));
var border = new Border { Child = presenter, Padding = new Thickness(8, 6), CornerRadius = new CornerRadius(4) };
border.Bind(Border.BackgroundProperty, button.GetObservable(TemplatedControl.BackgroundProperty));
border.BorderThickness = new Thickness(1); border.Bind(Border.BorderBrushProperty, button.GetObservable(TemplatedControl.BorderBrushProperty));
return border;
})));
window.Styles.Add(segments);
var focusSegment = new Style(s => s.OfType<ToggleButton>().Class("segment").Class(":focus-visible"));
focusSegment.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusSegment);
var selected = new Style(s => s.OfType<ToggleButton>().Class("segment").Class(":checked"));
selected.Setters.Add(new Setter(TemplatedControl.BackgroundProperty, new DynamicResourceExtension("Selection")));
selected.Setters.Add(new Setter(TemplatedControl.FontWeightProperty, FontWeight.SemiBold)); window.Styles.Add(selected);
var checks = new Style(s => s.OfType<NeutralCheckBox>());
checks.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, Brushes.Transparent));
checks.Setters.Add(new Setter(TemplatedControl.TemplateProperty, new FuncControlTemplate<NeutralCheckBox>((check, _) =>
{
var glyph = Text("✓", 14); glyph.Name = "NeutralCheckGlyph"; glyph.HorizontalAlignment = HorizontalAlignment.Center;
var box = new Border { Name = "NeutralCheckSurface", Child = glyph, Width = 20, Height = 20, CornerRadius = new CornerRadius(4),
BorderThickness = new Thickness(1), VerticalAlignment = VerticalAlignment.Center };
box.Bind(Border.BackgroundProperty, box.GetResourceObservable("Selection")); box.Bind(Border.BorderBrushProperty, box.GetResourceObservable("Axis"));
glyph.Bind(Visual.IsVisibleProperty, check.GetObservable(NeutralCheckBox.MarkVisibleProperty));
var label = new ContentPresenter { Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
label.Bind(ContentPresenter.ContentProperty, check.GetObservable(ContentControl.ContentProperty));
label.Bind(ContentPresenter.ForegroundProperty, label.GetResourceObservable("Ink"));
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("20,*"), MinHeight = 32 };
grid.Children.Add(box); Grid.SetColumn(label, 1); grid.Children.Add(label);
var focus = new Border { Child = grid, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(4) };
focus.Bind(Border.BorderBrushProperty, check.GetObservable(TemplatedControl.BorderBrushProperty)); return focus;
})));
window.Styles.Add(checks);
var focusCheck = new Style(s => s.OfType<NeutralCheckBox>().Class(":focus-visible"));
focusCheck.Setters.Add(new Setter(TemplatedControl.BorderBrushProperty, new DynamicResourceExtension("Ink"))); window.Styles.Add(focusCheck);
// Fluent caps tooltips at 320 px, which wraps the values of a data tooltip below its own width.
var tips = new Style(s => s.OfType<ToolTip>()); tips.Setters.Add(new Setter(Layoutable.MaxWidthProperty, 560d)); window.Styles.Add(tips);
}
// Explicit palettes keep every remaining Fluent control independent of the OS accent.
public static FluentTheme NeutralTheme()
{
var theme = new FluentTheme();
theme.Palettes[ThemeVariant.Dark] = new ColorPaletteResources { Accent = Color.Parse("#383835") };
theme.Palettes[ThemeVariant.Light] = new ColorPaletteResources { Accent = Color.Parse("#e1e0d9") };
return theme;
}
public static TextBlock Text(string text, double size = 13, string role = "Ink")
{
var block = new TextBlock { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
block.Bind(TextBlock.ForegroundProperty, block.GetResourceObservable(role));
return block;
}
public static TextBlock Mark(string text, IBrush colour, double size = 12) => new() { Text = text, FontSize = size, Foreground = colour };
public static TextBlock TableNumber(string text, double size = 13, string role = "Ink")
{
var block = Text(text, size, role); block.FontFeatures = FontFeatureCollection.Parse("tnum"); return block;
}
public static StackPanel Stack(params Control[] children)
{
var stack = new StackPanel { Spacing = 8 };
foreach (var child in children) stack.Children.Add(child);
return stack;
}
public static Border Card(Control content)
{
var card = new Border { Child = content, Padding = new Thickness(16), CornerRadius = new CornerRadius(10), BorderThickness = new Thickness(1) };
card.Bind(Border.BackgroundProperty, card.GetResourceObservable("Surface"));
card.Bind(Border.BorderBrushProperty, card.GetResourceObservable("Border"));
return card;
}
public static Button Button(string text, Action action)
{
var button = new Button { Content = text, Padding = new Thickness(12, 6) };
button.Click += (_, _) => action();
return button;
}
public static Control Columns(IEnumerable<Control> children, bool wide) => Columns(children, wide ? 2 : 1);
public static Control Columns(IEnumerable<Control> children, int columns)
{
var grid = new Grid { ColumnDefinitions = new ColumnDefinitions(string.Join(',', Enumerable.Repeat("*", columns))), ColumnSpacing = 16, RowSpacing = 16 };
var index = 0;
foreach (var child in children)
{
child.VerticalAlignment = VerticalAlignment.Top;
if (index % columns == 0) grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
Grid.SetColumn(child, index % columns); Grid.SetRow(child, index / columns);
grid.Children.Add(child); index++;
}
return grid;
}
}
+2
View File
@@ -40,6 +40,8 @@ public static class CliApplication
{ {
await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}"); await output.WriteLineAsync($"{provider.Provider}: {provider.Status} {provider.Reason}");
await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}"); await output.WriteLineAsync($" Tokens today: {provider.Today.Total}; session: {provider.Session?.Total.ToString(CultureInfo.InvariantCulture) ?? "unknown"}; week: {provider.Week.Total}");
await output.WriteLineAsync($" {(provider.WeekWindow is null ? "Calendar week" : "Limit week")}: since {provider.WeekStart:O}" +
(provider.WeekWindow is { } weekWindow ? $" ({weekWindow})" : ""));
foreach (var window in provider.Windows) foreach (var window in provider.Windows)
await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}")); await output.WriteLineAsync(FormattableString.Invariant($" {window.Window.Label}: {window.Window.UsedPercent:0.##}% used; resets {window.Window.ResetsAt:O}; {window.Pace.State}; delta {window.Pace.Delta:0.##}; sampled {window.Window.SampleTime:O}"));
} }
+17 -2
View File
@@ -1,5 +1,5 @@
# Core # Core
UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract. UI-free domain and file/CLI integration. Implements D1–D7, D9 and D11–D13.
Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock. Keep parsers total. Only metadata leaves them. JSON uses CoreJsonContext. Hosts own StoreLock.
Persisted defaults use settable properties: source-generated init-only property factories can Persisted defaults use settable properties: source-generated init-only property factories can
overwrite initializers for missing JSON members. Treat settings as values; update them with `with`. overwrite initializers for missing JSON members. Treat settings as values; update them with `with`.
@@ -18,7 +18,8 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
propagates. The background engine records other tick failures and retries without faulting its loop. propagates. The background engine records other tick failures and retries without faulting its loop.
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and - Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
`RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples. `RecentDiagnostics`. `History` offers token series, model/project breakdowns and limit samples.
- Snapshot provider totals use local today and Monday-based calendar week. Session totals use the - Snapshot provider totals use local today and the current provider-wide limit week, falling back
to the Monday-based local calendar week (D9). Session totals use the
reset and length of a known short limit. Hourly storage includes whole boundary hours (D5). reset and length of a known short limit. Hourly storage includes whole boundary hours (D5).
Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`. Day series use local calendar days, including DST. Tests can supply a zone to `TokenSeries`.
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days. Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
@@ -28,6 +29,19 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
No shipped production dependency is needed in Core. Source parsers use temporary memory for one No shipped production dependency is needed in Core. Source parsers use temporary memory for one
complete line; memory usage therefore scales with the largest transcript entry. complete line; memory usage therefore scales with the largest transcript entry.
## Limit analysis
- Use `WindowSeries` (provider, name, length) for all sample queries and instance membership (D7).
Codex `:primary` and `:secondary` suffixes identify slots, not limits. Read across ids with
`HistoryStore.LimitSamples(window, from, to)`; the original id query remains available.
- `LimitAnalysis` shares real spans and burn-up construction between `Analyze` and `Resets`.
Keep the current instance, ignore stale samples and leave gaps unassigned. A boundary hour
belongs to its starting instance, else to its ending instance (D7).
- Reset history lists only real instances overlapping the range, with whole-instance values (D12).
Percent values use the instance at final ≥ 5 %, else the qualifying listed-instance median.
- `ApiPrices` is the dated D13 list-price table. Match exact ids or a valid trailing date.
Unknown models remain unpriced; never infer a price from a family or count token subsets twice.
## Store persistence and scaling ## Store persistence and scaling
- Refresh changes append as one durable, newline-terminated transaction to - Refresh changes append as one durable, newline-terminated transaction to
@@ -45,6 +59,7 @@ Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root
Codex replay protection uses the last session timestamp and cumulative counts, with no Codex replay protection uses the last session timestamp and cumulative counts, with no
per-event dedupe keys. A later counter reset still permits subsequent increases. per-event dedupe keys. A later counter reset still permits subsequent increases.
- Store changed percent/reset samples and at most one unchanged sample per window per hour. - Store changed percent/reset samples and at most one unchanged sample per window per hour.
A reset that moves within 15 minutes is unchanged for sampling and instance identity (D7).
Late observations from archived files use neighbouring timestamps so they keep real changes Late observations from archived files use neighbouring timestamps so they keep real changes
without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have without inserting redundant unchanged points. Bucket lookup is O(1); stored limit points have
a per-window time index for ordered lookup. a per-window time index for ordered lookup.
+65
View File
@@ -0,0 +1,65 @@
using System.Globalization;
namespace FinalToken.Core;
public sealed record ApiPrice(decimal Input, decimal CacheWrite, decimal CacheRead, decimal Output);
/// <summary>D13: USD per million tokens, checked 2026-10-18. Standard short-context prices.
/// https://platform.claude.com/docs/en/about-claude/pricing
/// https://developers.openai.com/api/docs/pricing
/// Claude writes use the 5-minute price; Haiku 5.5 assumes prompts up to 100K.</summary>
public static class ApiPrices
{
public static DateOnly CheckedOn => new(2026, 10, 18);
private static readonly Dictionary<string, ApiPrice> Claude = new(StringComparer.Ordinal)
{
["claude-fable-5-1"] = new(10, 12.50m, .25m, 50),
["claude-fable-5"] = new(10, 12.50m, 1, 50),
["claude-opus-5-5"] = new(4, 5, .20m, 20),
["claude-opus-5"] = new(5, 6.25m, .50m, 25),
["claude-opus-4-8"] = new(5, 6.25m, .50m, 25),
["claude-opus-4-7"] = new(5, 6.25m, .50m, 25),
["claude-opus-4-6"] = new(5, 6.25m, .50m, 25),
["claude-opus-4-5"] = new(5, 6.25m, .50m, 25),
["claude-sonnet-5-5"] = new(2, 2.50m, .10m, 10),
["claude-sonnet-5"] = new(2, 2.50m, .20m, 10),
["claude-sonnet-4-6"] = new(3, 3.75m, .30m, 15),
["claude-sonnet-4-5"] = new(3, 3.75m, .30m, 15),
["claude-haiku-5-5"] = new(.10m, .125m, .01m, .50m),
["claude-haiku-4-5"] = new(1, 1.25m, .10m, 5)
};
private static readonly Dictionary<string, ApiPrice> Codex = new(StringComparer.Ordinal)
{
["gpt-6-astra"] = new(10, 0, 1, 50),
["gpt-6.1-sol"] = new(2, 0, .10m, 10),
["gpt-6-sol"] = new(2, 0, .20m, 10),
["gpt-6-luna"] = new(.10m, 0, .01m, .50m),
["gpt-5.6-sol"] = new(4, 0, .40m, 20),
["gpt-5.6-terra"] = new(2, 0, .20m, 12),
["gpt-5.6-luna"] = new(.20m, 0, .02m, 1.20m),
["gpt-5.5"] = new(5, 0, .50m, 30),
["gpt-5.4"] = new(2.50m, 0, .25m, 15),
["gpt-5.4-mini"] = new(.75m, 0, .075m, 4.50m),
["gpt-5.3-codex"] = new(1.75m, 0, .175m, 14),
["gpt-5.2"] = new(1.75m, 0, .175m, 14),
["gpt-5.1"] = new(1.25m, 0, .125m, 10),
["gpt-5"] = new(1.25m, 0, .125m, 10)
};
public static ApiPrice? Find(Provider provider, string? model)
{
if (model is null) return null;
var prices = provider == Provider.Claude ? Claude : Codex;
if (prices.TryGetValue(model, out var price)) return price;
return model.Length > 9 && model[^9] == '-' &&
DateOnly.TryParseExact(model[^8..], "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None, out _) &&
prices.TryGetValue(model[..^9], out price) ? price : null;
}
public static decimal? Value(Provider provider, string? model, TokenCounts counts)
{
if (Find(provider, model) is not { } p) return null;
var input = provider == Provider.Claude ? Math.Max(0, counts.Input) : Math.Max(0, counts.Input - counts.CacheRead);
return (input * p.Input + Math.Max(0, counts.CacheRead) * p.CacheRead +
(provider == Provider.Claude ? Math.Max(0, counts.CacheWrite) * p.CacheWrite : 0) +
Math.Max(0, counts.Output) * p.Output) / 1_000_000;
}
}
+1 -1
View File
@@ -68,7 +68,7 @@ public static class ActivationFile
} }
} }
internal static class SharedFile public static class SharedFile
{ {
public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan); FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan);
@@ -9,7 +9,7 @@ public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> Code
/// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only. /// <summary>Only opens transcript/rollout jsonl paths. Offsets advance through complete lines only.
/// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary> /// Prefix and consumed-tail fingerprints detect replacements without rereading whole files.</summary>
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics, public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
string claudeDirectory, string codexDirectory) string claudeDirectory, string codexDirectory, Action<UsageEvent, string?>? observe = null)
{ {
private static readonly UTF8Encoding StrictUtf8 = new(false, true); private static readonly UTF8Encoding StrictUtf8 = new(false, true);
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default, public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
@@ -93,12 +93,20 @@ public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagn
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r'); var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
if (text.Length > 0 && provider == Provider.Claude) if (text.Length > 0 && provider == Provider.Claude)
{ {
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++; if (TranscriptParser.Parse(text, diagnostics) is { } usage)
{
observe?.Invoke(usage, cursor.SessionId);
if (history.Add(usage)) added++;
}
} }
else if (text.Length > 0) else if (text.Length > 0)
{ {
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics); var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++; if (entry.CumulativeUsage is { } usage)
{
observe?.Invoke(usage, cursor.SessionId);
if (history.AddCodex(cursor.SessionId!, usage)) added++;
}
if (entry.Limits.Count > 0) if (entry.Limits.Count > 0)
{ {
latestLimits.Clear(); latestLimits.AddRange(entry.Limits); latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
+25 -6
View File
@@ -5,6 +5,7 @@ namespace FinalToken.Core;
public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts); public sealed record TokenBucket(Provider Provider, DateTimeOffset Hour, string? Model, string? Project, TokenCounts Counts);
public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts); public sealed record TokenPoint(DateTimeOffset Time, TokenCounts Counts);
public sealed record ModelTokenPoint(DateTimeOffset Time, string? Model, TokenCounts Counts);
public sealed record TokenBreakdown(string? Name, TokenCounts Counts); public sealed record TokenBreakdown(string? Name, TokenCounts Counts);
public enum SeriesInterval { Hour, Day } public enum SeriesInterval { Hour, Day }
@@ -185,10 +186,10 @@ public sealed class HistoryStore
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; } if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
} }
if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent && if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent &&
window.ResetsAt == chronologicalPrevious.ResetsAt && LimitAnalysis.SameInstance(window, chronologicalPrevious) &&
window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue; window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue;
if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent && if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent &&
window.ResetsAt == chronologicalNext.ResetsAt && LimitAnalysis.SameInstance(window, chronologicalNext) &&
chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue; chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue;
if (previous is null || window.SampleTime >= previous.SampleTime) if (previous is null || window.SampleTime >= previous.SampleTime)
state.LastSamples[key] = pending.LastSamples[key] = window; state.LastSamples[key] = pending.LastSamples[key] = window;
@@ -198,6 +199,7 @@ public sealed class HistoryStore
foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider]; foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider];
} }
} }
// D5: retain exact probe metadata; D7 tolerance applies only to instance identity and sampling.
private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) => private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) =>
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source); (window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider) public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
@@ -210,6 +212,14 @@ public sealed class HistoryStore
.Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to) .Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to)
.OrderBy(w => w.SampleTime).ToArray(); .OrderBy(w => w.SampleTime).ToArray();
} }
public IReadOnlyList<LimitWindow> LimitSamples(Provider provider, DateTimeOffset from, DateTimeOffset to)
{
lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits)
.Where(w => w.Provider == provider && w.SampleTime >= from && w.SampleTime < to)
.OrderBy(w => w.SampleTime).ToArray();
}
public IReadOnlyList<LimitWindow> LimitSamples(LimitWindow window, DateTimeOffset from, DateTimeOffset to) =>
LimitSamples(window.Provider, from, to).Where(WindowSeries.For(window).Matches).ToArray();
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval) public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local); => TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval, public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
@@ -227,6 +237,14 @@ public sealed class HistoryStore
} }
} }
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true); public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true);
public IReadOnlyList<ModelTokenPoint> TokenSeriesByModel(Provider provider, DateTimeOffset from, DateTimeOffset to,
SeriesInterval interval, TimeZoneInfo? zone = null)
{
lock (gate) return Range(provider, from, to)
.GroupBy(b => (Time: interval == SeriesInterval.Hour ? b.Hour : CalendarDays.Start(b.Hour, zone), b.Model))
.OrderBy(g => g.Key.Time).ThenBy(g => g.Key.Model, StringComparer.Ordinal)
.Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model, Sum(g.Select(b => b.Counts)))).ToArray();
}
public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false); public IReadOnlyList<TokenBreakdown> ByProject(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, false);
private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model) private IReadOnlyList<TokenBreakdown> Breakdown(Provider provider, DateTimeOffset from, DateTimeOffset to, bool model)
{ {
@@ -235,17 +253,18 @@ public sealed class HistoryStore
} }
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to) public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); } { lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now, public (TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart, string? WeekWindow) Totals(Provider provider, DateTimeOffset now,
LimitWindow? session, TimeZoneInfo? zone = null) LimitWindow? session, TimeZoneInfo? zone = null, LimitWindow? weekWindow = null)
{ {
zone ??= TimeZoneInfo.Local; zone ??= TimeZoneInfo.Local;
var local = TimeZoneInfo.ConvertTime(now, zone); var local = TimeZoneInfo.ConvertTime(now, zone);
var today = local.Date; var today = local.Date;
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7)); var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
var todayUtc = CalendarDays.Start(today, zone); var todayUtc = CalendarDays.Start(today, zone);
var weekUtc = CalendarDays.Start(week, zone); var followsLimit = weekWindow is { ResetsAt: { } r, Length: { Ticks: > 0 } l } && r > now;
var weekUtc = followsLimit ? weekWindow!.ResetsAt!.Value - weekWindow.Length!.Value : CalendarDays.Start(week, zone);
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now)); ? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now), weekUtc, followsLimit ? weekWindow!.Id : null);
} }
private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) => private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values) SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values)
+51
View File
@@ -0,0 +1,51 @@
namespace FinalToken.Core;
public sealed record RateForecast(double PercentPerDay, double UseAtReset, DateTimeOffset? ReachesLimit,
double Increase = 0, TimeSpan Span = default);
public sealed record LimitDay(DateTimeOffset Start, DateTimeOffset End, double? Used, double? Cumulative,
bool IsToday, bool IsFuture, UseOrigin Origin = UseOrigin.Measured, TimeSpan Share = default, double EvenPace = 0, double? Budget = null,
bool IsPartial = false, UseOrigin? BudgetOrigin = null);
public sealed record WindowDays(IReadOnlyList<LimitDay> Current, IReadOnlyList<LimitDay> Previous,
double? Today, double EvenPace, double? TodayBudget, double? LaterBudget = null, UseOrigin TodayOrigin = UseOrigin.Measured,
UseOrigin? BudgetOrigin = null, DateTimeOffset? InstanceStart = null, DateTimeOffset? Reset = null);
/// <summary>Pure D7 calculations. Missing baselines use marked token estimates when calibration is available.</summary>
public static partial class LimitAnalysis
{
/// <summary>D7: minute-rounded probe resets may drift within 15 minutes in either direction.</summary>
public static bool SameInstance(LimitWindow first, LimitWindow second) =>
WindowSeries.For(first) == WindowSeries.For(second) &&
first.ResetsAt is { } firstReset && second.ResetsAt is { } secondReset &&
(firstReset - secondReset).Duration() <= TimeSpan.FromMinutes(15);
public static double? AverageUseAtReset(LimitWindow window, DateTimeOffset now, PaceResult? pace = null)
{
pace ??= Pace.Calculate(window, now);
return Pace.CanForecast(window, now, pace) && pace.ElapsedFraction is > 0 and var elapsed ? window.UsedPercent / elapsed : null;
}
public static RateForecast? Recent(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, PaceResult? pace = null)
{
pace ??= Pace.Calculate(window, now);
if (!Pace.CanForecast(window, now, pace) || window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || reset <= now) return null;
var points = Instance(window, samples).Append(window).Where(s => s.SampleTime >= now.AddHours(-24) &&
s.SampleTime >= reset - length && s.SampleTime <= now).OrderBy(s => s.SampleTime).ToArray();
if (points.Length < 2) return null;
var first = points[0]; var last = points[^1];
var span = last.SampleTime - first.SampleTime;
if (span < TimeSpan.FromHours(3) || points.Zip(points.Skip(1)).Any(p => p.Second.UsedPercent < p.First.UsedPercent)) return null;
var rate = (last.UsedPercent - first.UsedPercent) / span.TotalDays;
var projected = window.UsedPercent + rate * (reset - now).TotalDays;
DateTimeOffset? reaches = null;
if (rate > 0 && projected > 100)
reaches = now.AddDays((100 - window.UsedPercent) / rate);
return new(rate, projected, reaches, last.UsedPercent - first.UsedPercent, span);
}
public static WindowDays? Days(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now, TimeZoneInfo? zone = null)
=> Analyze(window, samples, [], now, zone)?.Days;
private static IEnumerable<LimitWindow> Instance(LimitWindow window, IEnumerable<LimitWindow> samples) =>
samples.Where(s => SameInstance(window, s) &&
double.IsFinite(s.UsedPercent) && s.UsedPercent is >= 0 and <= 100);
}
+60
View File
@@ -0,0 +1,60 @@
namespace FinalToken.Core;
public static partial class LimitAnalysis
{
// Hour buckets of one instance in [from, to); tokenEnd excludes the boundary hour a later instance owns.
private static double WeightedTokens(IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
DateTimeOffset start, DateTimeOffset tokenEnd, DateTimeOffset from, DateTimeOffset to)
{
var hour = Hour(from < start ? start : from);
return weighted.Where(p => p.Time >= hour && p.Time < to && p.Time < tokenEnd).Sum(p => p.Weight);
}
// D7: plan from the day baseline; spending within that plan does not take from later days.
private static WindowDays PlanDays(LimitWindow window, LimitInstance current, LimitInstance? previous,
LimitDay? today, IReadOnlyList<LimitWindow> observations, IReadOnlyList<(DateTimeOffset Time, double Weight)> weighted,
DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone)
{
var length = window.Length!.Value;
double? baseline = null; UseOrigin? origin = null;
double? todayBudget = null, laterBudget = null;
if (today is not null && current.Start <= now && current.Reset > now)
{
var start = today.Start > current.Start ? today.Start : current.Start;
if (start == current.Start) { baseline = 0; origin = UseOrigin.Measured; }
else if (Instance(window, observations).LastOrDefault(s => s.SampleTime >= current.Start && s.SampleTime <= start) is { } sample)
{ baseline = sample.UsedPercent; origin = UseOrigin.Measured; }
else if (Instance(window, observations).FirstOrDefault(s => s.SampleTime >= start) is { } first)
{
// D7: use only completed hours before the first sample; its own hour can still grow.
var sampleHour = Hour(first.SampleTime);
var baselineEnd = start < sampleHour ? start : sampleHour;
var denominator = WeightedTokens(weighted, current.Start, tokenEnd, current.Start, sampleHour);
if (denominator > 0)
{
baseline = first.UsedPercent * WeightedTokens(weighted, current.Start, tokenEnd, current.Start, baselineEnd) / denominator;
origin = UseOrigin.Estimated;
}
}
if (baseline is { } used)
{
todayBudget = Math.Max(0, 100 - used) * (today.End - start).TotalDays / (current.Reset - start).TotalDays;
if (today.End < current.Reset)
laterBudget = Math.Max(0, 100 - Math.Max(window.UsedPercent, used + todayBudget.Value)) / (current.Reset - today.End).TotalDays;
}
}
LimitDay Plan(LimitDay day, bool isCurrent)
{
var instance = isCurrent ? current : previous!;
var start = day.Start > instance.Start ? day.Start : instance.Start;
var share = day.End - start;
return day with { Share = share, EvenPace = 100 * share.TotalDays / (instance.Reset - instance.Start).TotalDays,
Budget = !isCurrent ? null : day.IsToday ? todayBudget : day.IsFuture ? laterBudget * share.TotalDays : null,
IsPartial = share != CalendarDays.NextStart(day.Start, zone) - day.Start,
BudgetOrigin = isCurrent && (day.IsToday || day.IsFuture) ? origin : null };
}
return new(current.Days.Select(d => Plan(d, true)).ToArray(), previous?.Days.Select(d => Plan(d, false)).ToArray() ?? [],
today?.Used, 100 / length.TotalDays, todayBudget, laterBudget, today?.Origin ?? UseOrigin.Measured,
origin, current.Start, current.Reset);
}
}
+115
View File
@@ -0,0 +1,115 @@
namespace FinalToken.Core;
public enum UseOrigin { Measured, Estimated }
public sealed record LimitPoint(DateTimeOffset Time, double Used, UseOrigin Origin);
public sealed record LimitInstance(DateTimeOffset Start, DateTimeOffset Reset, IReadOnlyList<LimitPoint> Points,
IReadOnlyList<LimitDay> Days, double? Scale, double? Peak, DateTimeOffset? ReachedLimit, DateTimeOffset? EndedAt = null, UseOrigin? ReachedOrigin = null)
{
public DateTimeOffset End => EndedAt ?? Reset;
public bool HasData => Points.Count > 1;
}
public sealed record LimitEstimate(LimitInstance Current, IReadOnlyList<LimitInstance> Past, WindowDays? Days)
{
public LimitInstance? Previous => Past.FirstOrDefault();
}
public static partial class LimitAnalysis
{
private static DateTimeOffset Hour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
/// <summary>D7: pure estimates from hourly token buckets, calibrated to the newest sample.
/// Boundary hours are included as in D5; estimates cannot recover sub-hour token timing.</summary>
public static LimitEstimate? Analyze(LimitWindow window, IEnumerable<LimitWindow> samples,
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset now, TimeZoneInfo? zone = null)
{
if (window.ResetsAt is not { } reset || window.Length is not { Ticks: > 0 } length || Pace.Calculate(window, now).State == PaceState.Unknown) return null;
zone ??= TimeZoneInfo.Local;
var spans = RealSpans(window, samples, now);
var observations = spans.SelectMany(s => s.Samples).ToArray();
var weighted = WeightedTokens(window, tokens);
var currentSpan = spans.Single(g => SameInstance(g.Anchor, window));
var currentTokenEnd = TokenEnd(currentSpan.End, null);
var current = BuildInstance(window, observations, weighted, currentSpan.Start, currentSpan.End,
now < currentSpan.End ? now : currentSpan.End, null, currentTokenEnd, now, zone);
var past = new List<LimitInstance>();
foreach (var (span, successorStart) in SpansWithSuccessors(window, spans).Skip(1).Take(8))
{
var instance = BuildInstance(span.Anchor, observations, weighted, span.Start, span.End,
span.End < now ? span.End : now, current.Scale, TokenEnd(span.End, successorStart), now, zone);
if (instance.HasData) past.Add(instance);
}
WindowDays? days = null;
if (length > TimeSpan.FromDays(1))
{
var today = current.Days.FirstOrDefault(d => d.IsToday);
days = PlanDays(window, current, past.FirstOrDefault(), today, observations, weighted, currentTokenEnd, now, zone);
}
return new(current, past, days);
}
private static LimitInstance BuildInstance(LimitWindow anchor, IReadOnlyList<LimitWindow> observations,
(DateTimeOffset Time, double Weight)[] weighted, DateTimeOffset start, DateTimeOffset end, DateTimeOffset until,
double? fallback, DateTimeOffset tokenEnd, DateTimeOffset now, TimeZoneInfo zone)
{
double Weight(DateTimeOffset from, DateTimeOffset to) => WeightedTokens(weighted, start, tokenEnd, from, to);
var measured = Instance(anchor, observations).Where(s => s.SampleTime >= start - TimeSpan.FromMinutes(15) && s.SampleTime <= until)
.GroupBy(s => s.SampleTime).Select(g => g.Last()).OrderBy(s => s.SampleTime).ToArray();
var last = measured.LastOrDefault();
var denominator = last is null ? 0 : Weight(start, last.SampleTime);
var total = Weight(start, until);
double? scale = total <= 0 ? null : last is not null ? denominator > 0 ? last.UsedPercent / denominator : null : fallback;
var points = new SortedDictionary<DateTimeOffset, LimitPoint> { [start] = new(start, 0, UseOrigin.Measured) };
if (scale is { } k)
{
foreach (var time in weighted.Where(p => p.Time >= Hour(start) && p.Time < until && p.Time < tokenEnd).SelectMany(p => new[] { p.Time, p.Time.AddHours(1) }).Append(until).Distinct())
{
var cutoff = time < until ? time : until;
if (cutoff <= start) continue;
// Samples own the measured span; tokens fill before the first sample and after the last.
if (measured.Length == 0 || cutoff < measured[0].SampleTime)
points[cutoff] = new(cutoff, k * Weight(start, cutoff), UseOrigin.Estimated);
else if (last is not null && cutoff > last.SampleTime)
points[cutoff] = new(cutoff, last.UsedPercent + k * (Weight(start, cutoff) - Weight(start, last.SampleTime)), UseOrigin.Estimated);
}
}
foreach (var sample in measured) points[sample.SampleTime] = new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured);
DateTimeOffset? reached = null; UseOrigin? reachedOrigin = null;
var raw = points.Values.OrderBy(p => p.Time).ToArray();
for (var i = 1; i < raw.Length; i++)
{
var point = raw[i]; var prior = raw[i - 1];
if (reached is null && point.Used >= 100)
{
reached = point.Origin == UseOrigin.Measured || point.Used <= prior.Used ? point.Time
: prior.Time.AddTicks((long)((point.Time - prior.Time).Ticks * Math.Clamp((100 - prior.Used) / (point.Used - prior.Used), 0, 1)));
reachedOrigin = point.Origin;
if (point.Origin == UseOrigin.Estimated) points[reached.Value] = new(reached.Value, 100, UseOrigin.Estimated);
}
if (point.Origin == UseOrigin.Estimated)
points[point.Time] = point with { Used = reached is not null ? 100 : Math.Min(100, point.Used) };
}
double EstimatedAt(DateTimeOffset time, double factor) => reachedOrigin == UseOrigin.Estimated && time >= reached
? 100 : Math.Min(100, factor * Weight(start, time));
var daily = new List<LimitDay>();
for (var day = CalendarDays.Start(start, zone); day < end; day = CalendarDays.NextStart(day, zone))
{
var next = CalendarDays.NextStart(day, zone); var dayEnd = next < end ? next : end;
var cutoff = dayEnd < until ? dayEnd : until; var future = day > until;
var baseline = day <= start ? 0 : Last(day);
var cumulative = cutoff >= start ? Last(cutoff) : null;
if (last is not null && scale is not null && cutoff > last.SampleTime && Weight(start, cutoff) > Weight(start, last.SampleTime)) cumulative = null;
double? use = !future && baseline is { } b && cumulative is { } c ? Math.Max(0, c - b) : null;
var origin = UseOrigin.Measured;
if (!future && use is null && scale is { } factor)
{
use = Math.Max(0, EstimatedAt(cutoff, factor) - (day > start ? EstimatedAt(day, factor) : 0)); origin = UseOrigin.Estimated;
cumulative ??= EstimatedAt(cutoff, factor);
}
daily.Add(new(day, dayEnd, use, future ? null : cumulative, day == CalendarDays.Start(now, zone), future, origin));
}
var series = points.Values.OrderBy(p => p.Time).ToArray();
double? peak = series.Length > 1 ? series.Max(p => p.Used) : null;
return new(start, anchor.ResetsAt!.Value, series, daily, scale, peak, reached, end, reachedOrigin);
double? Last(DateTimeOffset time) => measured.LastOrDefault(s => s.SampleTime <= time)?.UsedPercent;
}
}
+81
View File
@@ -0,0 +1,81 @@
namespace FinalToken.Core;
public static partial class LimitAnalysis
{
private sealed record InstanceSpan(LimitWindow Anchor, IReadOnlyList<LimitWindow> Samples,
DateTimeOffset Start, DateTimeOffset End);
private static InstanceSpan[] RealSpans(LimitWindow window, IEnumerable<LimitWindow> samples, DateTimeOffset now)
{
var key = WindowSeries.For(window);
var observations = samples.Append(window).Where(s => key.Matches(s) && s.ResetsAt is not null &&
s.Length is { Ticks: > 0 } && s.SampleTime <= now && double.IsFinite(s.UsedPercent) &&
s.UsedPercent is >= 0 and <= 100).Distinct().OrderByDescending(s => s.SampleTime).ToArray();
var groups = new List<List<LimitWindow>> { new() { window } };
foreach (var sample in observations)
{
var group = groups.FirstOrDefault(g => SameInstance(g[0], sample));
if (group is null) groups.Add([sample]); else group.Add(sample);
}
var candidates = groups.Select(g =>
{
var anchor = SameInstance(g[0], window) ? window : g.MaxBy(s => s.SampleTime)!;
return new InstanceSpan(anchor, g.Distinct().OrderBy(s => s.SampleTime).ToArray(),
anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value);
}).ToArray();
var current = candidates[0];
var accepted = new List<InstanceSpan> { current };
var latestStart = current.Start;
// D7 / #9: earlier observations cannot put an instance after a later observed instance.
// Order by first observation so an interleaved late rollout cannot reorder real resets.
foreach (var span in candidates.Skip(1).OrderByDescending(s => s.Samples.Min(p => p.SampleTime)))
{
if (span.Start > latestStart) continue;
accepted.Add(span); latestStart = span.Start;
}
var result = accepted.OrderBy(s => s.Start).ToArray();
for (var i = 0; i + 1 < result.Length; i++)
if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start };
// A late sample of the old instance after an early reset is stale too.
result = result.Select(s =>
{
var valid = s.Samples.Where(p => p.SampleTime <= s.End).ToArray();
var anchor = SameInstance(s.Anchor, window) ? window : valid.LastOrDefault() ?? s.Anchor;
return new InstanceSpan(anchor, valid, anchor.ResetsAt!.Value - anchor.Length!.Value, anchor.ResetsAt.Value);
}).Where(s => s.Samples.Count > 0 || SameInstance(s.Anchor, window)).OrderBy(s => s.Start).ToArray();
for (var i = 0; i + 1 < result.Length; i++)
if (result[i + 1].Start < result[i].End) result[i] = result[i] with { End = result[i + 1].Start };
return result.Select(s => s with { Samples = s.Samples.Where(p => p.SampleTime <= s.End).ToArray() }).ToArray();
}
private static IEnumerable<(InstanceSpan Span, DateTimeOffset? SuccessorStart)> SpansWithSuccessors(
LimitWindow window, IReadOnlyList<InstanceSpan> spans)
{
var current = spans.Single(s => SameInstance(s.Anchor, window));
yield return (current, null);
var realPast = spans.Where(s => s.Start < current.Start).OrderByDescending(s => s.Start).ToArray();
var length = window.Length!.Value;
var canInfer = length > TimeSpan.FromDays(1);
var realIndex = 0;
var cursor = current.Start;
while (canInfer || realIndex < realPast.Length)
{
var inferredStart = cursor - length;
// D7: a candidate overlapping the nearest real span yields to that whole span.
// A shorter gap stays unassigned. Sessions never produce inferred candidates.
var span = realIndex < realPast.Length && (!canInfer || realPast[realIndex].End > inferredStart)
? realPast[realIndex++]
: new InstanceSpan(window with { ResetsAt = cursor }, [], inferredStart, cursor);
yield return (span, cursor);
cursor = span.Start;
}
}
private static DateTimeOffset TokenEnd(DateTimeOffset end, DateTimeOffset? successorStart) =>
end == Hour(end) || successorStart is { } start && Hour(start) == Hour(end) ? Hour(end) : Hour(end).AddHours(1);
private static (DateTimeOffset Time, double Weight)[] WeightedTokens(LimitWindow window, IReadOnlyList<ModelTokenPoint> tokens) =>
tokens.Where(p => TokenWeights.Matches(window, p.Model)).GroupBy(p => p.Time)
.Select(g => (Time: g.Key, Weight: g.Sum(p => TokenWeights.Weighted(window.Provider, p.Counts))))
.OrderBy(p => p.Time).ToArray();
}
+15 -1
View File
@@ -2,6 +2,19 @@ namespace FinalToken.Core;
public static class Pace public static class Pace
{ {
// D7: use ticks at the boundary so exactly 2% is eligible despite floating-point rounding.
public static DateTimeOffset? ForecastStartsAt(LimitWindow window) =>
window.Length is { Ticks: > 0 } length && window.ResetsAt is { } reset
? reset - TimeSpan.FromTicks(length.Ticks - length.Ticks / 50) : null;
public static bool CanForecast(LimitWindow window, DateTimeOffset now, double threshold = 10) =>
CanForecast(window, now, Calculate(window, now, threshold));
// Reuse the configured pace, so every forecast agrees with the chip's Ahead state.
public static bool CanForecast(LimitWindow window, DateTimeOffset now, PaceResult pace) =>
pace.State != PaceState.Unknown && pace.ElapsedFraction is > 0 &&
ForecastStartsAt(window) is { } start && (now >= start || pace.State == PaceState.Ahead);
// D7. A reset in the past clamps elapsed to one; it never has a future projection. // D7. A reset in the past clamps elapsed to one; it never has a future projection.
public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10) public static PaceResult Calculate(LimitWindow window, DateTimeOffset now, double threshold = 10)
{ {
@@ -14,7 +27,7 @@ public static class Pace
var state = delta >= threshold ? PaceState.Ahead : var state = delta >= threshold ? PaceState.Ahead :
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack; delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
DateTimeOffset? projection = null; DateTimeOffset? projection = null;
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0) if (delta > 0 && window.UsedPercent > 0 && CanForecast(window, now, new PaceResult(state, elapsed, delta)))
{ {
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent; var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds); if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
@@ -41,6 +54,7 @@ public sealed class PopupDecider
} }
states[key] = next; states[key] = next;
if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) || if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) ||
settings.For(window.Provider).IsHidden(window) ||
!settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled || !settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled ||
(next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead : (next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead :
!settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null; !settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null;
@@ -5,7 +5,8 @@ using System.Text.Json;
namespace FinalToken.Core.Processes; namespace FinalToken.Core.Processes;
public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory, public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory,
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024); TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024,
IReadOnlyDictionary<string, string>? EnvironmentOverrides = null, string RpcMethod = "account/rateLimits/read");
public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false); public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false);
public interface IProcessRunner public interface IProcessRunner
{ {
@@ -31,6 +32,8 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR
StandardInputEncoding = new UTF8Encoding(false) StandardInputEncoding = new UTF8Encoding(false)
} }; } };
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument); foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
if (request.EnvironmentOverrides is not null)
foreach (var (key, value) in request.EnvironmentOverrides) process.StartInfo.Environment[key] = value;
process.Start(); process.Start();
// D6: a WinExe host can have no standard input handle. Give every child a valid // D6: a WinExe host can have no standard input handle. Give every child a valid
// pipe; non-interactive probes get EOF, while app-server keeps its RPC input open. // pipe; non-interactive probes get EOF, while app-server keeps its RPC input open.
@@ -44,7 +47,9 @@ public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessR
await process.StandardInput.WriteLineAsync("{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"finaltoken\",\"version\":\"1.0.0\"},\"capabilities\":{\"experimentalApi\":false,\"explicitGatewayOauth\":true}}}".AsMemory(), token); await process.StandardInput.WriteLineAsync("{\"id\":1,\"method\":\"initialize\",\"params\":{\"clientInfo\":{\"name\":\"finaltoken\",\"version\":\"1.0.0\"},\"capabilities\":{\"experimentalApi\":false,\"explicitGatewayOauth\":true}}}".AsMemory(), token);
await ReadResponseAsync(process.StandardOutput, 1, request.OutputLimit, token); await ReadResponseAsync(process.StandardOutput, 1, request.OutputLimit, token);
await process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token); await process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token);
await process.StandardInput.WriteLineAsync("{\"id\":2,\"method\":\"account/rateLimits/read\",\"params\":null}".AsMemory(), token); if (request.RpcMethod is not ("account/rateLimits/read" or "account/read"))
throw new ArgumentException("Unsupported metadata RPC.");
await process.StandardInput.WriteLineAsync(($"{{\"id\":2,\"method\":\"{request.RpcMethod}\",\"params\":null}}").AsMemory(), token);
var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token); var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token);
Kill(process); Kill(process);
await process.WaitForExitAsync(CancellationToken.None); await process.WaitForExitAsync(CancellationToken.None);
+5 -2
View File
@@ -199,10 +199,13 @@ public sealed class RefreshEngine : IAsyncDisposable
var windows = History.LatestLimits(provider); var windows = History.LatestLimits(provider);
// Session totals follow an explicitly short limit window, never a week mislabeled primary. // Session totals follow an explicitly short limit window, never a week mislabeled primary.
var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5)); var session = windows.FirstOrDefault(w => w.Length is { } length && length <= TimeSpan.FromHours(5));
var totals = History.Totals(provider, now, session); // D9: the longest provider-wide limit defines the week; family limits do not.
var week = windows.Where(w => w.Length > TimeSpan.FromDays(1) && TokenWeights.Family(w) is null)
.OrderByDescending(w => w.Length).FirstOrDefault();
var totals = History.Totals(provider, now, session, clock.LocalTimeZone, week);
var state = statuses[provider]; var state = statuses[provider];
var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray(); var snapshots = windows.Select(w => new WindowSnapshot(w, Pace.Calculate(w, now, config.PaceThreshold))).ToArray();
providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week)); providers.Add(new(provider, state.Status, state.Reason, snapshots, totals.Today, totals.Session, totals.Week, totals.WeekStart, totals.WeekWindow));
foreach (var window in snapshots) foreach (var window in snapshots)
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert) if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
alerts.Add(alert); alerts.Add(alert);
+112
View File
@@ -0,0 +1,112 @@
namespace FinalToken.Core;
public enum PercentBasis { OwnInstance, SeriesMedian }
public sealed record PercentRate(double Tokens, decimal? ApiValue, PercentBasis Basis);
public sealed record ResetValue(double Percent, double? Tokens, decimal? ApiValue);
public sealed record ResetModel(string? Model, TokenCounts Tokens, decimal? ApiValue);
public sealed record ResetInstance(LimitInstance BurnUp, DateTimeOffset End, bool Running, bool Early,
TimeSpan Skipped, TokenCounts Tokens, IReadOnlyList<ResetModel> Models, decimal? ApiValue, long UnpricedTokens,
PercentRate? ValuePerPercent = null, ResetValue? Unused = null, ResetValue? Gift = null)
{
public DateTimeOffset Start => BurnUp.Start;
public DateTimeOffset Reset => BurnUp.Reset;
public TimeSpan Duration => End - Start;
public LimitPoint Final => BurnUp.Points[^1];
public double? Peak => BurnUp.Peak;
public UseOrigin PeakOrigin => BurnUp.Points.Any(p => p.Used == Peak && p.Origin == UseOrigin.Measured)
? UseOrigin.Measured : UseOrigin.Estimated;
public DateTimeOffset? ReachedLimit => BurnUp.ReachedLimit;
public TimeSpan TimeAtLimit => ReachedLimit is { } time && End > time ? End - time : TimeSpan.Zero;
}
public sealed record ResetTotals(int Instances, int Finished, int Early, TokenCounts Tokens, decimal? ApiValue,
long UnpricedTokens, ResetValue Unused, ResetValue Gift, TimeSpan Skipped, int ReachedLimit, TimeSpan TimeAtLimit);
public sealed record ResetHistory(LimitWindow Window, IReadOnlyList<ResetInstance> Instances, ResetTotals Totals,
IReadOnlyList<int> EarlyByHour, IReadOnlyList<int> EarlyByWeekday, TimeSpan? MedianDuration, DateTimeOffset FirstSample);
public static partial class LimitAnalysis
{
/// <summary>D12: only observed real instances; values cover whole overlapping instances, not a clipped range.</summary>
public static ResetHistory Resets(LimitWindow window, IEnumerable<LimitWindow> samples,
IReadOnlyList<ModelTokenPoint> tokens, DateTimeOffset from, DateTimeOffset now, TimeZoneInfo? zone = null)
{
zone ??= TimeZoneInfo.Local;
var rows = new List<ResetInstance>();
var hours = new int[24]; var weekdays = new int[7];
var firstSample = window.SampleTime;
if (window.ResetsAt is not null && window.Length is { } length && length > TimeSpan.FromDays(1) &&
Pace.Calculate(window, now).State != PaceState.Unknown)
{
var spans = RealSpans(window, samples, now);
firstSample = spans.SelectMany(s => s.Samples).Select(s => s.SampleTime).DefaultIfEmpty(window.SampleTime).Min();
var weighted = WeightedTokens(window, tokens);
foreach (var (span, successorStart) in SpansWithSuccessors(window, spans)
.TakeWhile(s => s.Span.Start >= spans[0].Start)
.Where(s => s.Span.Samples.Count > 0 && s.Span.End > from && s.Span.Start <= now))
{
var running = span.End > now;
var end = running ? now : span.End;
var tokenEnd = TokenEnd(span.End, successorStart);
var burn = BuildInstance(span.Anchor, span.Samples, weighted, span.Start, span.End, end,
null, tokenEnd, now, zone);
var models = tokens.Where(p => p.Time >= Hour(span.Start) && p.Time < end &&
p.Time < tokenEnd && TokenWeights.Matches(window, p.Model))
.GroupBy(p => p.Model).Select(g =>
{
var counts = g.Aggregate(new TokenCounts(), (sum, p) => sum + p.Counts);
return new ResetModel(g.Key, counts, ApiPrices.Value(window.Provider, g.Key, counts));
}).OrderByDescending(m => m.Tokens.Total).ToArray();
var early = !running && span.Anchor.ResetsAt!.Value - end > TimeSpan.FromMinutes(15);
rows.Add(new(burn, end, running, early, early ? span.Anchor.ResetsAt!.Value - end : TimeSpan.Zero,
models.Aggregate(new TokenCounts(), (sum, m) => sum + m.Tokens), models,
SumMoney(models.Select(m => m.ApiValue)), models.Where(m => m.ApiValue is null).Sum(m => m.Tokens.Total)));
if (early)
{
var local = TimeZoneInfo.ConvertTime(end, zone);
hours[local.Hour]++; weekdays[((int)local.DayOfWeek + 6) % 7]++;
}
}
var qualifying = rows.Where(r => r.Final.Used >= 5).ToArray();
var medianTokens = Median(qualifying.Select(r => r.Tokens.Total / r.Final.Used));
var medianMoney = MedianMoney(qualifying.Where(r => r.ApiValue is not null).Select(r => r.ApiValue!.Value / (decimal)r.Final.Used));
for (var i = 0; i < rows.Count; i++)
{
var row = rows[i];
var rate = row.Final.Used >= 5 ? new PercentRate(row.Tokens.Total / row.Final.Used,
row.ApiValue / (decimal)row.Final.Used, PercentBasis.OwnInstance) : medianTokens is { } median
? new PercentRate(median, medianMoney, PercentBasis.SeriesMedian) : null;
ResetValue Value(double percent) => new(percent, rate?.Tokens * percent, rate?.ApiValue * (decimal)percent);
rows[i] = row with { ValuePerPercent = rate, Unused = row.Running ? null : Value(100 - row.Final.Used),
Gift = row.Early ? Value(100 * row.Skipped.TotalSeconds / length.TotalSeconds) : null };
}
}
ResetValue TotalValue(IEnumerable<ResetValue?> source)
{
var values = source.OfType<ResetValue>().ToArray();
return new(values.Sum(v => v.Percent), values.All(v => v.Tokens is not null) ? values.Sum(v => v.Tokens) : null,
values.All(v => v.ApiValue is not null) ? values.Sum(v => v.ApiValue) : null);
}
var totals = new ResetTotals(rows.Count, rows.Count(r => !r.Running), rows.Count(r => r.Early),
rows.Aggregate(new TokenCounts(), (sum, r) => sum + r.Tokens), SumMoney(rows.Select(r => r.ApiValue)),
rows.Sum(r => r.UnpricedTokens), TotalValue(rows.Select(r => r.Unused)), TotalValue(rows.Select(r => r.Gift)),
TimeSpan.FromTicks(rows.Sum(r => r.Skipped.Ticks)), rows.Count(r => r.ReachedLimit is not null),
TimeSpan.FromTicks(rows.Sum(r => r.TimeAtLimit.Ticks)));
return new(window, rows, totals, hours, weekdays,
Median(rows.Where(r => !r.Running).Select(r => (double)r.Duration.Ticks)) is { } ticks ? TimeSpan.FromTicks((long)ticks) : null, firstSample);
}
private static decimal? SumMoney(IEnumerable<decimal?> values)
{
var known = values.OfType<decimal>().ToArray();
return known.Length == 0 ? null : known.Sum();
}
private static double? Median(IEnumerable<double> source)
{
var sorted = source.Order().ToArray(); var n = sorted.Length;
return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2;
}
private static decimal? MedianMoney(IEnumerable<decimal> source)
{
var sorted = source.Order().ToArray(); var n = sorted.Length;
return n == 0 ? null : (sorted[(n - 1) / 2] + sorted[n / 2]) / 2;
}
}
+31 -2
View File
@@ -2,6 +2,12 @@ using System.Text.Json;
namespace FinalToken.Core; namespace FinalToken.Core;
public sealed record HiddenLimitWindow(string Name, TimeSpan? Length, string Label)
{
public static HiddenLimitWindow For(LimitWindow window) => new(WindowSeries.For(window).Name, window.Length, window.Label);
public WindowSeries Series(Provider provider) => new(provider, Name, Length);
}
public sealed record ProviderSettings public sealed record ProviderSettings
{ {
// Setters let source-generated JSON construct defaults before assigning present properties. // Setters let source-generated JSON construct defaults before assigning present properties.
@@ -10,6 +16,27 @@ public sealed record ProviderSettings
public bool PopupAhead { get; set; } = true; public bool PopupAhead { get; set; } = true;
public bool PopupBehind { get; set; } = true; public bool PopupBehind { get; set; } = true;
public string? CliPath { get; set; } public string? CliPath { get; set; }
public IReadOnlyList<HiddenLimitWindow> HiddenWindows { get; set; } = [];
// D8: visibility follows the D7 series, never a Codex slot or the current reset.
public bool IsHidden(LimitWindow window) => IsHidden(WindowSeries.For(window));
public bool IsHidden(WindowSeries series) => HiddenWindows.Any(hidden => hidden.Series(series.Provider) == series);
[System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => HiddenWindows is not null && HiddenWindows.All(hidden => hidden is not null &&
!string.IsNullOrWhiteSpace(hidden.Name) && !string.IsNullOrWhiteSpace(hidden.Label) &&
(hidden.Length is null || hidden.Length > TimeSpan.Zero));
public bool Equals(ProviderSettings? other) => other is not null && Enabled == other.Enabled &&
PopupsEnabled == other.PopupsEnabled && PopupAhead == other.PopupAhead && PopupBehind == other.PopupBehind &&
CliPath == other.CliPath && (ReferenceEquals(HiddenWindows, other.HiddenWindows) ||
HiddenWindows is not null && other.HiddenWindows is not null && HiddenWindows.SequenceEqual(other.HiddenWindows));
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Enabled); hash.Add(PopupsEnabled); hash.Add(PopupAhead); hash.Add(PopupBehind); hash.Add(CliPath);
if (HiddenWindows is not null) foreach (var window in HiddenWindows) hash.Add(window);
return hash.ToHashCode();
}
} }
public sealed record Settings public sealed record Settings
@@ -30,7 +57,7 @@ public sealed record Settings
[System.Text.Json.Serialization.JsonIgnore] [System.Text.Json.Serialization.JsonIgnore]
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) && public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(60) &&
ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) && ProbeInterval >= TimeSpan.FromMinutes(1) && ProbeInterval <= TimeSpan.FromMinutes(60) &&
double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is not null && Codex is not null && double.IsFinite(PaceThreshold) && PaceThreshold is > 0 and <= 100 && Claude is { IsValid: true } && Codex is { IsValid: true } &&
Enum.IsDefined(StreamDeckInstallMode); Enum.IsDefined(StreamDeckInstallMode);
} }
@@ -53,8 +80,10 @@ public static class SettingsFile
var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings); var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
if (value is { IsValid: true }) return value; if (value is { IsValid: true }) return value;
} }
catch (FileNotFoundException) { return new(); }
catch (DirectoryNotFoundException) { return new(); }
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { } catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults."); diagnostics.Add(null, "settings-defaults", "Settings invalid or unreadable; using defaults.");
return new(); return new();
} }
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default) public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
+2 -1
View File
@@ -8,7 +8,8 @@ public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime; public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
} }
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason, public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week); IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week, DateTimeOffset WeekStart = default,
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? WeekWindow = null);
public sealed record Snapshot public sealed record Snapshot
{ {
// Keep this initializer for omitted properties in source-generated JSON (D9). // Keep this initializer for omitted properties in source-generated JSON (D9).
+28
View File
@@ -0,0 +1,28 @@
namespace FinalToken.Core;
/// <summary>D7 price ratios. Reasoning is already included in output; Codex cached input is a subset of input.</summary>
public static class TokenWeights
{
public const double Input = 1;
public const double ClaudeOutput = 5;
public const double ClaudeCacheWrite = 1.25;
public const double CacheRead = 0.1;
public const double CodexOutput = 8;
private static readonly string[] ClaudeFamilies = ["Fable", "Opus", "Sonnet", "Haiku"];
public static double Weighted(Provider provider, TokenCounts counts) => provider == Provider.Claude
? Math.Max(0, counts.Input) * Input + Math.Max(0, counts.Output) * ClaudeOutput + Math.Max(0, counts.CacheWrite) * ClaudeCacheWrite + Math.Max(0, counts.CacheRead) * CacheRead
: Math.Max(0, counts.Input - counts.CacheRead) * Input + Math.Max(0, counts.CacheRead) * CacheRead + Math.Max(0, counts.Output) * CodexOutput;
public static string? Family(LimitWindow window)
{
// Provider labels expose the family in parentheses; the dashboard also uses a middle dot.
var label = window.Label;
var open = label.LastIndexOf('('); var close = label.LastIndexOf(')');
var separator = label.LastIndexOf('\u00b7');
var family = open >= 0 && close > open ? label[(open + 1)..close].Trim()
: separator >= 0 ? label[(separator + 1)..].Trim() : null;
if (family is { Length: > 0 } && !family.Equals("all models", StringComparison.OrdinalIgnoreCase) &&
!family.Equals("all", StringComparison.OrdinalIgnoreCase) && !char.IsDigit(family[0])) return family;
return ClaudeFamilies.FirstOrDefault(f => label.Contains(f, StringComparison.OrdinalIgnoreCase));
}
public static bool Matches(LimitWindow window, string? model) => Family(window) is not { } family || model?.Contains(family, StringComparison.OrdinalIgnoreCase) == true;
}
+15
View File
@@ -0,0 +1,15 @@
namespace FinalToken.Core;
/// <summary>D7: Codex slots can change; a limit's name and length identify its series.</summary>
public readonly record struct WindowSeries(Provider Provider, string Name, TimeSpan? Length)
{
public static WindowSeries For(LimitWindow window)
{
var name = window.Id;
if (window.Provider == Provider.Codex)
foreach (var suffix in new[] { ":primary", ":secondary" })
if (name.EndsWith(suffix, StringComparison.Ordinal)) { name = name[..^suffix.Length]; break; }
return new(window.Provider, name, window.Length);
}
public bool Matches(LimitWindow window) => this == For(window);
}
+2
View File
@@ -0,0 +1,2 @@
# Fleet
Shared metadata transport, account aggregation and official CLI login coordination. Reuse Core D7/D12/D13 analysis. No provider credentials or raw process output in persisted state. Authorization responses and login URLs exist only in live session memory (D14). Run Fleet tests from the root.
+236
View File
@@ -0,0 +1,236 @@
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using FinalToken.Core;
using FinalToken.Core.Processes;
namespace FinalToken.Fleet;
public static class CliAuthentication
{
public static IReadOnlyDictionary<string, string> EnvironmentFor(WorkerProfile profile) =>
new Dictionary<string, string> { [profile.Provider == Provider.Claude ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME"] = Path.GetFullPath(profile.ConfigDirectory) };
public static async Task<AuthHealth> ReadAsync(WorkerProfile profile, IProcessRunner? runner = null, CancellationToken token = default)
{
var now = DateTimeOffset.UtcNow;
var command = CliDiscovery.Find(profile.Provider, profile.CliPath).Command;
if (command is null) return new("Unavailable", null, now, "Configured CLI not found.");
try
{
var result = await (runner ?? new ProcessRunner()).RunAsync(new(command,
profile.Provider == Provider.Claude ? ["auth", "status", "--json"] : ["app-server"],
profile.DataDirectory, TimeSpan.FromSeconds(30), CodexRpc: profile.Provider == Provider.Codex,
EnvironmentOverrides: EnvironmentFor(profile), RpcMethod: "account/read"), token);
return Parse(profile, result, now);
}
catch (Exception) when (!token.IsCancellationRequested) { return new("Unknown", null, now, "CLI identity probe failed; no expiry inferred."); }
}
public static AuthHealth Parse(WorkerProfile profile, ProcessResult result, DateTimeOffset now)
{
if (result.ExitCode != 0 || result.TimedOut || result.OutputTruncated) return new("Unavailable", null, now, "CLI status failed; login may require renewal.");
try
{
using var json = JsonDocument.Parse(result.Output);
var root = json.RootElement;
if (profile.Provider == Provider.Claude)
{
if (!root.TryGetProperty("loggedIn", out var logged) || logged.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
return new("Unknown", null, now, "CLI did not expose login status.");
if (logged.ValueKind != JsonValueKind.True)
return new("Unavailable", null, now, "CLI reports signed out.");
if (root.TryGetProperty("configDirectory", out var directory) && directory.ValueKind == JsonValueKind.String &&
!Path.GetFullPath(directory.GetString()!).Equals(Path.GetFullPath(profile.ConfigDirectory), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
return new("ProfileMismatch", null, now, "CLI reports a different config directory.");
}
else
{
root = root.GetProperty("result").GetProperty("account");
if (root.ValueKind != JsonValueKind.Object) return new("Unavailable", null, now, "CLI reports no account.");
}
var email = root.TryGetProperty("email", out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;
if (email is not { Length: > 0 and <= 320 }) return new("Unknown", null, now, "CLI did not expose account identity; no expiry inferred.");
return new(string.Equals(email, profile.ExpectedEmail, StringComparison.OrdinalIgnoreCase) ? "Healthy" : "AccountMismatch",
email, now, "CLI-reported account identity; refresh/expiry remains owned by the CLI.");
}
catch (Exception e) when (e is JsonException or InvalidOperationException or KeyNotFoundException or ArgumentException)
{ return new("Unknown", null, now, "Unrecognized CLI identity response; no expiry inferred."); }
}
}
public static partial class LoginOutput
{
[GeneratedRegex(@"\x1B\[[0-?]*[ -/]*[@-~]", RegexOptions.None, 100)]
private static partial Regex Ansi();
[GeneratedRegex(@"https://[^\s\x1b<>""']+", RegexOptions.None, 100)]
private static partial Regex Url();
[GeneratedRegex(@"\b[A-Z0-9]{4}-[A-Z0-9]{4,5}\b", RegexOptions.None, 100)]
private static partial Regex DeviceCode();
public static bool OfficialUrl(Provider provider, string url) => Uri.TryCreate(url, UriKind.Absolute, out var u) &&
u.Scheme == "https" && u.IsDefaultPort && u.UserInfo.Length == 0 && (provider == Provider.Claude
? (u.Host is "claude.ai" or "platform.claude.com" or "console.anthropic.com") && u.AbsolutePath.StartsWith("/oauth/", StringComparison.Ordinal)
: u.Host == "auth.openai.com" && u.AbsolutePath == "/codex/device");
public static LoginUpdate Parse(string id, WorkerProfile profile, string output, bool accepted)
{
var text = Ansi().Replace(output, "");
var url = Url().Matches(text).Select(m => m.Value.TrimEnd(')', '.', ',')).LastOrDefault(u => OfficialUrl(profile.Provider, u));
var code = profile.Provider == Provider.Codex ? DeviceCode().Match(text).Value : null;
var state = accepted ? "Verifying" : profile.Provider == Provider.Claude && url is not null &&
(text.Contains("Paste code", StringComparison.OrdinalIgnoreCase) || text.Contains("Enter code", StringComparison.OrdinalIgnoreCase))
? "WaitingForCode" : url is not null ? "WaitingForBrowser" : "Starting";
return new(id, profile.Id, state, url, string.IsNullOrEmpty(code) ? null : code, InputAccepted: accepted);
}
}
public interface ILoginProcess : IAsyncDisposable
{
LoginUpdate Current { get; }
Task SubmitAsync(string response, CancellationToken token);
void Cancel();
}
/// <summary>Real installed CLI; bounded output stays only in memory and is reduced to allowlisted login fields.</summary>
public sealed class CliLoginProcess : ILoginProcess
{
private readonly WorkerProfile profile;
private readonly string id;
private readonly CancellationTokenSource stop;
private readonly Process process;
private readonly Task run;
private readonly Lock gate = new();
private readonly SemaphoreSlim inputGate = new(1, 1);
private string output = "";
private bool accepted, cancelled, outputFailed;
private LoginUpdate current;
public LoginUpdate Current { get { lock (gate) return current; } }
public CliLoginProcess(LoginCommand command, WorkerProfile profile)
{
this.profile = profile; id = command.Id;
current = new(id, profile.Id, "Starting");
var remaining = command.ExpiresAt - DateTimeOffset.UtcNow;
if (remaining <= TimeSpan.Zero || remaining > TimeSpan.FromMinutes(16)) throw new InvalidDataException("Invalid login deadline.");
stop = new(remaining);
var cli = CliDiscovery.Find(profile.Provider, profile.CliPath).Command ?? throw new InvalidDataException("CLI not found.");
process = new() { StartInfo = new()
{
FileName = cli.FileName, WorkingDirectory = profile.DataDirectory, UseShellExecute = false, CreateNoWindow = true,
RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true,
StandardInputEncoding = new UTF8Encoding(false), StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false)
} };
foreach (var arg in cli.PrefixArguments.Concat(profile.Provider == Provider.Claude ? new[] { "auth", "login", "--claudeai", "--email", profile.ExpectedEmail } : ["login", "--device-auth"]))
process.StartInfo.ArgumentList.Add(arg);
foreach (var (key, value) in CliAuthentication.EnvironmentFor(profile)) process.StartInfo.Environment[key] = value;
process.Start(); run = RunAsync();
}
public async Task SubmitAsync(string response, CancellationToken token)
{
await inputGate.WaitAsync(token);
try
{
lock (gate)
{
if (accepted) return; // retransmitted transport command is idempotent
if (current.State != "WaitingForCode" || stop.IsCancellationRequested) throw new InvalidDataException("CLI is not waiting for a code.");
accepted = true; current = current with { State = "Verifying", InputAccepted = true };
}
await process.StandardInput.WriteLineAsync(response.AsMemory(), token);
await process.StandardInput.FlushAsync(token);
}
finally { inputGate.Release(); }
}
public void Cancel() { cancelled = true; stop.Cancel(); }
private async Task PumpAsync(StreamReader reader)
{
try
{
var buffer = new char[1024]; int count;
while ((count = await reader.ReadAsync(buffer, stop.Token)) > 0)
{
lock (gate)
{
if (output.Length + count > 64 * 1024) throw new InvalidDataException("Login output exceeded bound.");
output += new string(buffer, 0, count);
current = LoginOutput.Parse(id, profile, output, accepted);
}
}
}
catch (Exception) when (!stop.IsCancellationRequested)
{
// Task.WhenAll alone waits for the other pipe: cancel immediately so a CLI
// waiting for stdin cannot keep the failed pump/process alive until timeout.
lock (gate) outputFailed = true;
stop.Cancel(); throw;
}
}
private async Task RunAsync()
{
var stdout = PumpAsync(process.StandardOutput); var stderr = PumpAsync(process.StandardError);
try
{
// A failed output pump must stop the process promptly, even when it is waiting for stdin.
var pumps = Task.WhenAll(stdout, stderr);
var exited = process.WaitForExitAsync(stop.Token);
if (await Task.WhenAny(pumps, exited) == pumps) await pumps;
await exited; await pumps;
if (process.ExitCode != 0) { Set("Failed"); return; }
Set("Verifying");
var health = await CliAuthentication.ReadAsync(profile, token: stop.Token);
Set(health.State == "Healthy" ? "Succeeded" : health.State == "AccountMismatch" ? "AccountMismatch" : "IdentityUnknown", health.Email);
}
catch (OperationCanceledException) { Set(outputFailed ? "Failed" : cancelled ? "Cancelled" : "TimedOut"); }
catch (Exception) { Set("Failed"); }
finally
{
try { if (!process.HasExited) process.Kill(true); } catch (InvalidOperationException) { }
await process.WaitForExitAsync(CancellationToken.None);
stop.Cancel();
try { await Task.WhenAll(stdout, stderr); } catch (Exception) { }
lock (gate) output = "";
}
}
private void Set(string state, string? email = null)
{ lock (gate) current = new(id, profile.Id, state, Email: email, InputAccepted: accepted); }
public async ValueTask DisposeAsync() { stop.Cancel(); await run; process.Dispose(); stop.Dispose(); inputGate.Dispose(); }
}
public sealed class WorkerLogins(IReadOnlyList<WorkerProfile> profiles, Func<LoginCommand, WorkerProfile, ILoginProcess>? factory = null) : IAsyncDisposable
{
private readonly Dictionary<string, ILoginProcess> processes = [];
private readonly Dictionary<string, LoginUpdate> failures = [];
private readonly HashSet<string> identityChanges = [];
public IReadOnlyList<LoginUpdate> Updates => processes.Values.Select(p => p.Current).Concat(failures.Values).ToArray();
public bool TakeIdentityChanges()
{
var changed = false;
foreach (var update in Updates.Where(u => u.State is "Succeeded" or "AccountMismatch" or "IdentityUnknown"))
changed |= identityChanges.Add(update.Id);
return changed;
}
public async Task ApplyAsync(WorkerReply reply, CancellationToken token)
{
foreach (var command in reply.Commands)
{
if (processes.TryGetValue(command.Id, out var process))
{
if (process.Current.ProfileId != command.ProfileId) continue;
if (command.Cancel) process.Cancel();
else if (command.Response is { } response) await process.SubmitAsync(response, token);
continue;
}
if (command.Cancel) { failures[command.Id] = new(command.Id, command.ProfileId, "Cancelled"); continue; }
if (failures.ContainsKey(command.Id)) continue;
var profile = profiles.SingleOrDefault(p => p.Id == command.ProfileId);
if (profile is null || processes.Values.Any(p => p.Current.ProfileId == command.ProfileId &&
p.Current.State is "Starting" or "WaitingForCode" or "WaitingForBrowser" or "Verifying"))
{ failures[command.Id] = new(command.Id, command.ProfileId, "Failed"); continue; }
try { processes.Add(command.Id, (factory ?? ((c, p) => new CliLoginProcess(c, p)))(command, profile)); }
catch (Exception) { failures[command.Id] = new(command.Id, command.ProfileId, "Failed"); }
}
// Only the server's current commands are live. Keep recent outcomes for acknowledgement, bound memory.
if (processes.Count > 80)
foreach (var key in processes.Where(p => !reply.Commands.Any(c => c.Id == p.Key)).Select(p => p.Key).Take(40).ToArray())
{ await processes[key].DisposeAsync(); processes.Remove(key); identityChanges.Remove(key); }
if (failures.Count > 80) failures.Clear();
}
public async ValueTask DisposeAsync() { foreach (var p in processes.Values) await p.DisposeAsync(); }
}
+97
View File
@@ -0,0 +1,97 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using FinalToken.Core;
namespace FinalToken.Fleet;
public sealed record AccountConfig(string Id, Provider Provider, string Label, string ExpectedEmail,
string TimeZone = "UTC", string? LegacyMachine = null, string? LegacyProfile = null, DateTimeOffset? HistoryBefore = null);
public sealed record ProfileBinding(string Id, string AccountId);
public sealed record MachineConfig(string Id, string Label, string OsUser, IReadOnlyList<ProfileBinding> Profiles);
public sealed record ServerConfig(IReadOnlyList<AccountConfig> Accounts, IReadOnlyList<MachineConfig> Machines);
public sealed record WorkerProfile(string Id, Provider Provider, string ExpectedEmail, string ConfigDirectory,
string DataDirectory, string? CliPath = null, bool EnableLegacyClaudeProbe = false);
public sealed record WorkerConfig(string MachineId, string ServerUrl, string StateDirectory, IReadOnlyList<WorkerProfile> Profiles);
public sealed record AuthHealth(string State, string? Email, DateTimeOffset CheckedAt, string Reason);
// Claude: absolute response counts; Codex: cumulative session counts. Never send transcript content/project paths.
public sealed record SourceUsage(string Key, string? Session, DateTimeOffset Time, string? Model, TokenCounts Counts);
public sealed record ProfileReport(string Id, Provider Provider, AuthHealth Auth, Settings Settings,
IReadOnlyList<SourceUsage> Usage, IReadOnlyList<LimitWindow> Samples, IReadOnlyList<ModelTokenPoint> LegacyTokens,
string? CollectionError = null, string? DataEmail = null, string? CollectionNote = null);
public sealed record WorkerReport(string MachineId, string OsUser, string BootId, DateTimeOffset CollectedAt,
IReadOnlyList<ProfileReport> Profiles, IReadOnlyList<LoginUpdate> Logins);
public sealed record MachineState(string MachineId, DateTimeOffset SeenAt, WorkerReport Report);
public sealed record FleetState(IReadOnlyList<MachineState> Machines);
public sealed record LoginUpdate(string Id, string ProfileId, string State, string? Url = null,
string? DeviceCode = null, string? Email = null, bool InputAccepted = false);
public sealed record LoginCommand(string Id, string ProfileId, DateTimeOffset ExpiresAt, bool Cancel = false, string? Response = null);
public sealed record WorkerReply(IReadOnlyList<LoginCommand> Commands);
public sealed record LoginView(string Id, string MachineId, string ProfileId, string State, DateTimeOffset ExpiresAt,
string? Url, string? DeviceCode, string? Email);
public sealed record StartLogin(string MachineId, string ProfileId);
public sealed record LoginResponse(string Response);
public sealed record SignIn(string Key);
public sealed record BrowserSession(string Csrf);
public sealed record WindowView(LimitWindow Window, bool Stale, PaceResult Pace, double? UseAtReset,
double? RemainingAtReset, RateForecast? Recent, LimitEstimate? Analysis, ResetHistory? Resets);
public sealed record AccountView(AccountConfig Account, IReadOnlyList<WindowView> Windows,
IReadOnlyList<ModelTokenPoint> Tokens, TokenCounts Total, decimal? ApiValue, long UnpricedTokens,
IReadOnlyList<string> Warnings, DateOnly PricesCheckedOn, IReadOnlyList<SessionConsumption> Sessions, bool HasConsumptionData);
public sealed record SessionConsumption(string Id, TokenCounts Tokens);
public sealed record ProfileConsumption(string ProfileId, TokenCounts? Tokens, int Sessions);
public sealed record MachineView(string Id, string Label, string OsUser, bool Online, DateTimeOffset? SeenAt,
IReadOnlyList<ProfileReport> Profiles, IReadOnlyList<ProfileBinding> Bindings, IReadOnlyList<ProfileConsumption> Consumption);
public sealed record DashboardView(DateTimeOffset Now, IReadOnlyList<AccountView> Accounts, IReadOnlyList<MachineView> Machines);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, UseStringEnumConverter = true)]
[JsonSerializable(typeof(ServerConfig))]
[JsonSerializable(typeof(WorkerConfig))]
[JsonSerializable(typeof(WorkerReport))]
[JsonSerializable(typeof(FleetState))]
[JsonSerializable(typeof(WorkerReply))]
[JsonSerializable(typeof(DashboardView))]
[JsonSerializable(typeof(LoginView))]
[JsonSerializable(typeof(StartLogin))]
[JsonSerializable(typeof(LoginResponse))]
[JsonSerializable(typeof(SignIn))]
[JsonSerializable(typeof(BrowserSession))]
[JsonSerializable(typeof(List<SourceUsage>))]
public partial class FleetJsonContext : JsonSerializerContext;
public static class FleetValidation
{
public static bool TryHttpOrigin(string? value, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out Uri? origin) =>
Uri.TryCreate(value, UriKind.Absolute, out origin) && origin.Scheme is "http" or "https" &&
origin.Host.Length > 0 && origin.UserInfo.Length == 0 && origin.AbsolutePath == "/" &&
origin.Query.Length == 0 && origin.Fragment.Length == 0;
public static bool MatchesRequestHost(Uri origin, string? host) =>
!string.IsNullOrEmpty(host) && TryHttpOrigin(origin.Scheme + "://" + host, out var requestOrigin) && origin == requestOrigin;
public static bool Identifier(string? value) => value is { Length: > 0 and <= 64 } &&
value.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_');
public static void Config(ServerConfig config)
{
if (config.Accounts is null || config.Machines is null ||
config.Accounts.Select(a => a.Id).Distinct().Count() != config.Accounts.Count ||
config.Machines.Select(m => m.Id).Distinct().Count() != config.Machines.Count)
throw new InvalidDataException("Duplicate or missing configuration.");
foreach (var account in config.Accounts)
{
if (!Identifier(account.Id) || !Enum.IsDefined(account.Provider) || string.IsNullOrWhiteSpace(account.ExpectedEmail))
throw new InvalidDataException("Invalid account configuration.");
_ = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone);
if (account.HistoryBefore is { } cutoff && (cutoff.UtcTicks % TimeSpan.TicksPerHour != 0 ||
!config.Machines.Any(m => m.Id == account.LegacyMachine && m.Profiles.Any(p => p.Id == account.LegacyProfile && p.AccountId == account.Id))))
throw new InvalidDataException("Legacy history requires one bound source and an exact UTC hour cutoff.");
}
foreach (var machine in config.Machines)
if (!Identifier(machine.Id) || string.IsNullOrWhiteSpace(machine.OsUser) || machine.Profiles is null ||
machine.Profiles.Select(p => p.Id).Distinct().Count() != machine.Profiles.Count ||
machine.Profiles.Any(p => !Identifier(p.Id) || !config.Accounts.Any(a => a.Id == p.AccountId)))
throw new InvalidDataException("Invalid machine/profile configuration.");
}
public static bool Counts(TokenCounts c) => c.Input is >= 0 and <= 1_000_000_000_000 && c.Output is >= 0 and <= 1_000_000_000_000 &&
c.CacheRead is >= 0 and <= 1_000_000_000_000 && c.CacheWrite is >= 0 and <= 1_000_000_000_000 &&
c.ReasoningOutput is >= 0 and <= 1_000_000_000_000 && c.Total is >= 0 and <= 4_000_000_000_000;
}
@@ -0,0 +1,3 @@
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
</Project>
+125
View File
@@ -0,0 +1,125 @@
using FinalToken.Core;
namespace FinalToken.Fleet;
public static class FleetAnalysis
{
public static DashboardView Build(ServerConfig config, FleetState state, DateTimeOffset now)
{
var machines = config.Machines.Select(m =>
{
var saved = state.Machines.SingleOrDefault(s => s.MachineId == m.Id);
return new MachineView(m.Id, m.Label, m.OsUser, saved is not null && now - saved.SeenAt <= TimeSpan.FromSeconds(90),
saved?.SeenAt, saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p => p with { Usage = [], Samples = [], LegacyTokens = [] }).ToArray() ?? [], m.Profiles,
saved?.Report.Profiles.Where(p => m.Profiles.Any(b => b.Id == p.Id)).Select(p =>
{
var account = config.Accounts.Single(a => a.Id == m.Profiles.Single(b => b.Id == p.Id).AccountId);
var usage = Reconcile(p.Usage, p.Provider, []);
return new ProfileConsumption(p.Id, string.Equals(p.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase) ? Sum(usage) : null,
usage.Where(u => u.Session is not null).Select(u => u.Session).Distinct().Count());
}).ToArray() ?? []);
}).ToArray();
var accounts = config.Accounts.Select(account => Account(account, config, state, now)).ToArray();
return new(now, accounts.OrderByDescending(a => a.Windows.Any(w => !w.Stale)).ToArray(), machines);
}
private static AccountView Account(AccountConfig account, ServerConfig config, FleetState state, DateTimeOffset now)
{
List<string> warnings = [];
var profiles = (from machine in config.Machines
from binding in machine.Profiles where binding.AccountId == account.Id
let saved = state.Machines.SingleOrDefault(s => s.MachineId == machine.Id)
let profile = saved?.Report.Profiles.SingleOrDefault(p => p.Id == binding.Id)
where profile is not null
select (Machine: machine.Id, Profile: profile, Saved: saved!)).ToArray();
var verified = profiles.Where(p => p.Profile.Provider == account.Provider &&
string.Equals(p.Profile.DataEmail, account.ExpectedEmail, StringComparison.OrdinalIgnoreCase)).ToArray();
if (verified.Length != profiles.Length) warnings.Add("Unverified or mismatched profiles excluded from this account's analysis.");
if (profiles.Any(p => p.Profile.Auth.State != "Healthy")) warnings.Add("One or more CLI logins need attention; previously attributed history is retained.");
if (profiles.Length == 0) warnings.Add("No machine has reported this account yet.");
if (verified.Any(p => p.Profile.CollectionError is not null)) warnings.Add("A collector failed; retained metadata may be incomplete or stale.");
warnings.AddRange(verified.Select(p => p.Profile.CollectionNote).OfType<string>());
if (verified.Select(p => (p.Profile.Settings.PaceThreshold,p.Profile.Settings.ProbeInterval)).Distinct().Count() > 1)
warnings.Add("Profile analysis settings differ; each window uses the newest observation's source settings.");
var records = verified.SelectMany(p => p.Profile.Usage).ToArray();
// D4/D14: compute cumulative increases before clipping, or the first post-cutoff
// event would charge the already-imported pre-cutoff session total a second time.
var allUsage = Reconcile(records, account.Provider, warnings);
if (account.Provider == Provider.Codex && account.HistoryBefore is { } cutoff)
{
var uncertain = allUsage.GroupBy(u => u.Session).Where(g => g.Min(u => u.Time) >= cutoff)
.Select(g => g.OrderBy(u => u.Time).First()).ToHashSet();
if (uncertain.Count > 0)
warnings.Add("Migration baseline unknown for some Codex sessions: their first cumulative totals are omitted; consumption history is incomplete.");
allUsage = allUsage.Where(u => !uncertain.Contains(u)).ToArray();
}
var reconciled = allUsage.Where(u => account.HistoryBefore is null || u.Time >= account.HistoryBefore).ToArray();
List<ModelTokenPoint> tokens = reconciled.Select(u => new ModelTokenPoint(Hour(u.Time), u.Model, u.Counts)).ToList();
if (account.HistoryBefore is { } before)
{
var legacy = verified.SingleOrDefault(p => p.Machine == account.LegacyMachine && p.Profile.Id == account.LegacyProfile).Profile;
if (legacy is null) warnings.Add("Designated legacy history source is unavailable or unverified.");
else tokens.AddRange(legacy.LegacyTokens.Where(t => t.Time < before));
warnings.Add("Before the migration cutoff, history uses one designated machine; cross-machine attribution is unavailable.");
}
tokens = tokens.GroupBy(t => (t.Time, t.Model)).Select(g => new ModelTokenPoint(g.Key.Time, g.Key.Model,
g.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts))).OrderBy(t => t.Time).ToList();
var observations = verified.SelectMany(p => p.Profile.Samples).Distinct().ToArray();
List<WindowView> windows = [];
foreach (var series in observations.GroupBy(WindowSeries.For))
{
var window = series.OrderBy(w => w.SampleTime).ThenBy(w => w.Id, StringComparer.Ordinal).Last();
var owner = verified.Where(p => p.Profile.Samples.Contains(window)).OrderByDescending(p => p.Saved.SeenAt).First();
var stale = now - window.SampleTime > owner.Profile.Settings.ProbeInterval * 3 || owner.Profile.Auth.State != "Healthy" ||
!owner.Profile.Settings.For(account.Provider).Enabled ||
now - owner.Saved.SeenAt > TimeSpan.FromSeconds(90) || window.ResetsAt <= now;
var settings = owner.Profile.Settings;
if (settings.For(account.Provider).IsHidden(window)) continue;
var pace = stale ? new PaceResult(PaceState.Unknown) : Pace.Calculate(window, now, settings.PaceThreshold);
var forecast = stale ? null : LimitAnalysis.AverageUseAtReset(window, now, pace);
var zone = TimeZoneInfo.FindSystemTimeZoneById(account.TimeZone);
windows.Add(new(window, stale, pace, forecast, forecast is null ? null : 100 - forecast,
stale ? null : LimitAnalysis.Recent(window, series, now, pace),
stale ? null : LimitAnalysis.Analyze(window, series, tokens, now, zone),
window.Length > TimeSpan.FromDays(1) ? LimitAnalysis.Resets(window, series, tokens, now.AddDays(-90), now, zone) : null));
}
if (windows.Count == 0) warnings.Add("Provider allowance unknown. Token costs cannot establish subscription capacity.");
if (windows.Any(w => w.Stale)) warnings.Add("Stale or expired allowance: forecasts withheld until a fresh CLI observation.");
var costs = tokens.Select(t => (Point: t, Value: ApiPrices.Value(account.Provider, t.Model, t.Counts))).ToArray();
var priced = costs.Where(c => c.Value is not null).ToArray();
return new(account, windows.OrderByDescending(w => w.Window.Length).ToArray(), tokens,
tokens.Aggregate(new TokenCounts(), (sum, t) => sum + t.Counts), priced.Length == 0 ? null : priced.Sum(c => c.Value!.Value),
costs.Where(c => c.Value is null).Sum(c => c.Point.Counts.Total), warnings.Distinct().ToArray(), ApiPrices.CheckedOn,
reconciled.Where(u => u.Session is not null).GroupBy(u => u.Session!).Select(g => new SessionConsumption(g.Key, Sum(g)))
.OrderByDescending(s => s.Tokens.Total).ToArray(), verified.Length > 0);
}
private static TokenCounts Sum(IEnumerable<SourceUsage> events) => events.Aggregate(new TokenCounts(), (sum,u) => sum + u.Counts);
private static IReadOnlyList<SourceUsage> Reconcile(IEnumerable<SourceUsage> records, Provider provider, List<string> warnings)
{
List<SourceUsage> result = [];
if (provider == Provider.Claude)
{
foreach (var group in records.GroupBy(u => u.Key))
{
if (group.Select(u => (u.Time,u.Model,u.Counts)).Distinct().Count() != 1)
{ warnings.Add("Conflicting response metadata excluded; consumption is incomplete."); continue; }
if (group.Select(u => u.Session).Distinct().Count() > 1)
warnings.Add("Shared/resumed responses are assigned once to a stable session id; session attribution is approximate.");
result.Add(group.OrderBy(u => u.Session, StringComparer.Ordinal).First());
}
}
else
foreach (var session in records.GroupBy(u => u.Session))
{
var previous = new TokenCounts();
foreach (var group in session.GroupBy(u => u.Time).OrderBy(g => g.Key))
{
if (group.Select(u => (u.Model,u.Counts)).Distinct().Count() != 1)
{ warnings.Add("Conflicting session metadata excluded; consumption is incomplete."); continue; }
var value = group.First();
result.Add(value with { Counts = value.Counts.IncreaseFrom(previous) }); previous = value.Counts;
}
}
return result;
}
private static DateTimeOffset Hour(DateTimeOffset t) => new(t.UtcTicks - t.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
}
+86
View File
@@ -0,0 +1,86 @@
using System.Text.Json;
using FinalToken.Core;
namespace FinalToken.Fleet;
/// <summary>D14: only durable metadata. LoginCoordinator has a separate, memory-only lifetime.</summary>
public sealed class FleetStore
{
private readonly SemaphoreSlim gate = new(1, 1);
private readonly string path;
private FleetState state;
public ServerConfig Config { get; }
public FleetStore(string directory, ServerConfig config)
{
FleetValidation.Config(config);
Config = config;
path = Path.Combine(directory, "fleet.json");
state = File.Exists(path) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(path), FleetJsonContext.Default.FleetState)
?? throw new InvalidDataException("Invalid fleet state; refusing overwrite.") : new([]);
}
public FleetState Current => Volatile.Read(ref state);
public void Validate(WorkerReport report, string authenticatedMachine, DateTimeOffset now)
{
var machine = Config.Machines.Single(m => m.Id == authenticatedMachine);
if (report.MachineId != machine.Id || report.OsUser != machine.OsUser ||
string.IsNullOrWhiteSpace(report.BootId) || report.BootId.Length > 64 ||
report.CollectedAt > now.AddMinutes(2) || report.Profiles is null || report.Logins is null ||
report.Logins.Count > 200 || report.Profiles.Count != machine.Profiles.Count ||
report.Logins.Any(u => u is null || !FleetValidation.Identifier(u.Id) || !FleetValidation.Identifier(u.ProfileId) ||
u.State is not { Length: > 0 and <= 40 } || u.Url?.Length > 16384 || u.DeviceCode?.Length > 24 || u.Email?.Length > 320) ||
report.Profiles.Any(p => p is null) ||
report.Profiles.Select(p => p.Id).Distinct().Count() != report.Profiles.Count)
throw new InvalidDataException("Machine/user/profile mismatch or invalid report.");
foreach (var profile in report.Profiles)
{
var binding = machine.Profiles.SingleOrDefault(p => p.Id == profile.Id) ?? throw new InvalidDataException("Unknown profile.");
var account = Config.Accounts.Single(a => a.Id == binding.AccountId);
if (profile.Provider != account.Provider || profile.Auth is null || profile.Settings is not { IsValid: true } ||
profile.Usage is null || profile.Samples is null || profile.LegacyTokens is null ||
profile.Usage.Count > 100_000 || profile.Samples.Count > 30_000 || profile.LegacyTokens.Count > 100_000 ||
profile.Auth.Email?.Length > 320 || profile.DataEmail?.Length > 320 || profile.CollectionNote?.Length > 300 ||
profile.Auth.Reason is not { Length: <= 300 } || profile.Auth.State is not { Length: > 0 and <= 40 } || profile.CollectionError?.Length > 300 ||
profile.Auth.CheckedAt > now.AddMinutes(2) ||
profile.Usage.Any(u => u is null || u.Key is not { Length: > 0 and <= 512 } || u.Session?.Length > 256 || u.Model?.Length > 160 ||
u.Time > now.AddMinutes(2) || !FleetValidation.Counts(u.Counts) || (profile.Provider == Provider.Codex && string.IsNullOrWhiteSpace(u.Session))) ||
profile.Samples.Any(w => w is null || w.Provider != profile.Provider || w.Id is not { Length: > 0 and <= 160 } || w.Label is not { Length: <= 160 } || w.Source is not { Length: <= 80 } ||
!double.IsFinite(w.UsedPercent) || w.UsedPercent is < 0 or > 100 || w.Length is { Ticks: <= 0 } ||
w.Length > TimeSpan.FromDays(366) || w.SampleTime > now.AddMinutes(2)) ||
profile.LegacyTokens.Any(p => p is null || p.Model?.Length > 160 || !FleetValidation.Counts(p.Counts) || p.Time > now.AddMinutes(2)))
throw new InvalidDataException("Invalid or oversized profile metadata.");
}
}
public async Task AcceptAsync(WorkerReport report, string authenticatedMachine, DateTimeOffset now, CancellationToken token = default)
{
Validate(report, authenticatedMachine, now);
await gate.WaitAsync(token);
try
{
var old = state.Machines.SingleOrDefault(m => m.MachineId == report.MachineId);
if (old is not null && report.CollectedAt < old.Report.CollectedAt) throw new InvalidDataException("Out-of-order report.");
// D14: a starting/reinstalled worker cannot erase acknowledged historical metadata.
// Values are source identities/absolute hourly values, never additive report counters.
var merged = report.Profiles.Select(profile =>
{
var prior = old?.Report.Profiles.SingleOrDefault(p => p.Id == profile.Id);
if (prior is null) return profile;
if (profile.DataEmail is not null && prior.DataEmail is not null &&
!string.Equals(profile.DataEmail, prior.DataEmail, StringComparison.OrdinalIgnoreCase))
throw new InvalidDataException("Profile attribution changed; configure a separate profile.");
return profile with
{
DataEmail = profile.DataEmail ?? prior.DataEmail,
Usage = prior.Usage.Union(profile.Usage).ToArray(),
Samples = prior.Samples.Union(profile.Samples).ToArray(),
LegacyTokens = prior.LegacyTokens.Concat(profile.LegacyTokens).GroupBy(p => (p.Time,p.Model)).Select(g => g.Last()).ToArray()
};
}).ToArray();
var next = new FleetState(state.Machines.Where(m => m.MachineId != report.MachineId)
.Append(new(report.MachineId, now, report with { Profiles = merged, Logins = [] })).ToArray());
await AtomicFile.WriteAsync(path, JsonSerializer.Serialize(next, FleetJsonContext.Default.FleetState), token);
Volatile.Write(ref state, next);
}
finally { gate.Release(); }
}
public DashboardView Dashboard(DateTimeOffset now) => FleetAnalysis.Build(Config, Current, now);
}
+100
View File
@@ -0,0 +1,100 @@
namespace FinalToken.Fleet;
/// <summary>D14: short-lived routing state only. Never serialized or logged.</summary>
public sealed class LoginCoordinator(ServerConfig config)
{
private sealed class Pending(string id, string owner, string machine, string profile, string boot, DateTimeOffset expires)
{
public readonly string Id = id, Owner = owner, Machine = machine, Profile = profile, Boot = boot;
public readonly DateTimeOffset Expires = expires;
public string State = "Queued";
public string? Url, DeviceCode, Email, Response;
public bool InputAccepted;
public LoginView View => new(Id, Machine, Profile, State, Expires, Url, DeviceCode, Email);
}
private readonly Lock gate = new();
private readonly Dictionary<string, Pending> pending = [];
private static bool Terminal(string state) => state is "Succeeded" or "Failed" or "Cancelled" or "TimedOut" or "AccountMismatch" or "IdentityUnknown" or "WorkerRestarted";
public LoginView Start(string owner, string machine, string profile, FleetState fleet, DateTimeOffset now)
{
lock (gate)
{
Expire(now);
var definition = config.Machines.SingleOrDefault(m => m.Id == machine);
if (definition is null || !definition.Profiles.Any(p => p.Id == profile)) throw new InvalidDataException("Unknown machine/profile.");
var saved = fleet.Machines.SingleOrDefault(m => m.MachineId == machine);
if (saved is null || now - saved.SeenAt > TimeSpan.FromSeconds(90)) throw new InvalidDataException("Machine is offline.");
if (pending.Values.Any(p => p.Machine == machine && p.Profile == profile && !Terminal(p.State)))
throw new InvalidDataException("A login is already pending for this profile.");
if (pending.Count >= 100) throw new InvalidDataException("Too many login attempts; wait for expiry.");
var id = Guid.NewGuid().ToString("N");
var entry = new Pending(id, owner, machine, profile, saved.Report.BootId, now.AddMinutes(15));
pending.Add(id, entry); return entry.View;
}
}
public LoginView Get(string id, string owner, DateTimeOffset now)
{
lock (gate) { Expire(now); return Owned(id, owner).View; }
}
public void Respond(string id, string owner, string response, DateTimeOffset now)
{
lock (gate)
{
Expire(now); var entry = Owned(id, owner);
var binding = config.Machines.Single(m => m.Id == entry.Machine).Profiles.Single(p => p.Id == entry.Profile);
if (config.Accounts.Single(a => a.Id == binding.AccountId).Provider != Core.Provider.Claude ||
entry.State != "WaitingForCode" || entry.InputAccepted || entry.Response is not null)
throw new InvalidDataException("This login is not waiting for an authorization response.");
if (string.IsNullOrWhiteSpace(response) || response.Length > 2048 || response.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not ('_' or '-' or '.' or '#')))
throw new InvalidDataException("Paste only the official authorization code, not a URL or credential file.");
entry.Response = response;
}
}
public void Cancel(string id, string owner, DateTimeOffset now)
{
lock (gate)
{
Expire(now); var p = Owned(id, owner);
if (!Terminal(p.State)) { p.State = "Cancelling"; Clear(p); }
}
}
public WorkerReply Exchange(string machine, string boot, IReadOnlyList<LoginUpdate> updates, DateTimeOffset now)
{
lock (gate)
{
Expire(now);
foreach (var p in pending.Values.Where(p => p.Machine == machine && !Terminal(p.State)))
if (p.Boot != boot) { p.State = "WorkerRestarted"; Clear(p); }
foreach (var update in updates)
{
if (!pending.TryGetValue(update.Id, out var p) || p.Machine != machine || p.Boot != boot ||
p.Profile != update.ProfileId || Terminal(p.State)) continue;
if (update.State is not ("Starting" or "WaitingForBrowser" or "WaitingForCode" or "Verifying" or "Succeeded" or "Failed" or "Cancelled" or "TimedOut" or "AccountMismatch" or "IdentityUnknown")) continue;
if (p.State == "Cancelling" && !Terminal(update.State)) continue;
var binding = config.Machines.Single(m => m.Id == machine).Profiles.Single(b => b.Id == p.Profile);
var account = config.Accounts.Single(a => a.Id == binding.AccountId);
if (update.Url is not null && !LoginOutput.OfficialUrl(account.Provider, update.Url)) continue;
p.State = update.State;
p.Url = update.Url;
p.DeviceCode = update.DeviceCode is { Length: <= 24 } code && code.All(c => char.IsAsciiLetterOrDigit(c) || c == '-') ? code : null;
p.Email = update.Email is { Length: <= 320 } ? update.Email : null;
p.InputAccepted |= update.InputAccepted;
if (p.State == "Succeeded" && !string.Equals(account.ExpectedEmail, p.Email, StringComparison.OrdinalIgnoreCase)) p.State = "AccountMismatch";
if (p.InputAccepted) p.Response = null;
if (Terminal(p.State)) Clear(p);
}
return new(pending.Values.Where(p => p.Machine == machine && p.Boot == boot &&
(!Terminal(p.State) || p.State is "Cancelled" or "TimedOut"))
.Select(p => new LoginCommand(p.Id, p.Profile, p.Expires, Terminal(p.State) || p.State == "Cancelling", p.Response)).ToArray());
}
}
private Pending Owned(string id, string owner) => pending.TryGetValue(id, out var p) && p.Owner == owner
? p : throw new KeyNotFoundException("Login not found in this browser session.");
private void Expire(DateTimeOffset now)
{
foreach (var p in pending.Values)
if (p.Expires <= now && !Terminal(p.State)) { p.State = "TimedOut"; Clear(p); }
foreach (var p in pending.Values.Where(p => p.Expires.AddMinutes(15) < now).ToArray()) pending.Remove(p.Id);
}
private static void Clear(Pending p) { p.Url = null; p.DeviceCode = null; p.Response = null; }
}
+104
View File
@@ -0,0 +1,104 @@
using System.Text.Json;
using FinalToken.Core;
using FinalToken.Core.Collectors;
using FinalToken.Core.Processes;
namespace FinalToken.Fleet;
/// <summary>Independent metadata export cursors preserve response/session identities across rescans and offline restarts.</summary>
public sealed class ProfileCollector
{
private readonly WorkerProfile profile;
private readonly string directory;
private readonly Dictionary<string, SourceUsage> records;
private readonly HistoryStore cursors;
private readonly IncrementalScanner scanner;
private ProfileReport? previous;
private DateTimeOffset lastProbe = DateTimeOffset.MinValue;
private readonly DiagnosticLog diagnostics = new();
public ProfileCollector(WorkerProfile profile, string stateDirectory)
{
this.profile = profile;
directory = Path.Combine(stateDirectory, profile.Id);
Directory.CreateDirectory(directory); Directory.CreateDirectory(profile.DataDirectory);
var ledger = Path.Combine(directory, "usage.json");
var loaded = File.Exists(ledger) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(ledger), FleetJsonContext.Default.ListSourceUsage)
?? throw new InvalidDataException("Invalid usage export; refusing overwrite.") : [];
records = loaded.ToDictionary(Key, StringComparer.Ordinal);
var saved = Path.Combine(directory, "profile.json");
if (File.Exists(saved))
{
var report = JsonSerializer.Deserialize(SharedFile.ReadAllText(saved), FleetJsonContext.Default.WorkerReport);
previous = report?.Profiles.SingleOrDefault();
}
cursors = new(Path.Combine(directory, "scan"), diagnostics);
scanner = new(cursors, diagnostics,
profile.Provider == Provider.Claude ? profile.ConfigDirectory : Path.Combine(directory, "no-claude"),
profile.Provider == Provider.Codex ? profile.ConfigDirectory : Path.Combine(directory, "no-codex"), Observe);
}
private string Key(SourceUsage u) => profile.Provider == Provider.Claude ? u.Key : $"{u.Session!.Length}:{u.Session}:{u.Time:O}";
private void Observe(UsageEvent usage, string? session)
{
// Original source ids survive cross-machine copies. Never transmit project paths or message text.
var value = new SourceUsage(usage.DedupeKey, session, usage.Time, usage.Model, usage.Counts);
var key = Key(value);
if (!records.ContainsKey(key) && records.Count >= 100_000) throw new InvalidDataException("Metadata export is full; increase capacity with an explicit retention design.");
records[key] = value;
}
public async Task<ProfileReport> CollectAsync(CancellationToken token)
{
var auth = await CliAuthentication.ReadAsync(profile, token: token);
var settings = SettingsFile.Load(profile.DataDirectory, diagnostics);
if (!settings.For(profile.Provider).Enabled)
return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with
{ Auth = auth, Settings = settings, CollectionNote = "Collection is disabled in this profile's existing settings." };
if (auth.State != "Healthy") return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with { Auth = auth };
if (previous?.DataEmail is { } old && !string.Equals(old, auth.Email, StringComparison.OrdinalIgnoreCase))
return previous with { Auth = auth with { State = "AccountMismatch", Reason = "Profile account changed; use a separate worker profile/state directory." } };
try
{
var scan = await scanner.ScanAsync(token, profile.Provider == Provider.Claude, profile.Provider == Provider.Codex);
// Persist records BEFORE cursor progress: a crash can replay metadata, but cannot lose an event.
await AtomicFile.WriteAsync(Path.Combine(directory, "usage.json"),
JsonSerializer.Serialize(records.Values.ToList(), FleetJsonContext.Default.ListSourceUsage), token);
await cursors.SaveAsync(token);
// The existing store remains the authoritative local history/settings. A desktop host may own it.
using (var storeLock = StoreLock.TryAcquire(profile.DataDirectory))
{
if (storeLock is not null)
{
await using var engine = new RefreshEngine(profile.DataDirectory, processRunner: new ProfileRunner(profile),
claudeDirectory: profile.Provider == Provider.Claude ? profile.ConfigDirectory : Path.Combine(directory, "no-claude"),
codexDirectory: profile.Provider == Provider.Codex ? profile.ConfigDirectory : Path.Combine(directory, "no-codex"),
cliDiscovery: (provider, path) => provider == profile.Provider && (provider != Provider.Claude || profile.EnableLegacyClaudeProbe)
? CliDiscovery.Find(provider, profile.CliPath ?? path) : new(null, "Provider probe disabled for this worker profile."));
var since = DateTimeOffset.UtcNow - lastProbe;
var probeDue = since >= TimeSpan.FromMinutes(1) && (since >= settings.ProbeInterval || scan.AddedEvents > 0);
if (probeDue) lastProbe = DateTimeOffset.UtcNow;
await engine.RefreshNowAsync(noProbe: !probeDue, cancellationToken: token);
}
}
var history = new HistoryStore(profile.DataDirectory, diagnostics);
var now = DateTimeOffset.UtcNow;
var samples = history.LimitSamples(profile.Provider, DateTimeOffset.MinValue, now.AddMinutes(1))
.Concat(history.LatestLimits(profile.Provider)).Concat(scan.CodexFallback).Distinct().ToArray();
var legacy = history.TokenSeriesByModel(profile.Provider, DateTimeOffset.MinValue, now.AddHours(1), SeriesInterval.Hour);
previous = new(profile.Id, profile.Provider, auth, settings, records.Values.ToArray(), samples, legacy,
DataEmail: auth.Email, CollectionNote: profile.Provider == Provider.Claude && !profile.EnableLegacyClaudeProbe
? "Claude quota probe is disabled; only existing observed quota history is available." : null);
await AtomicFile.WriteAsync(Path.Combine(directory, "profile.json"), JsonSerializer.Serialize(
new WorkerReport("local", Environment.UserName, "persisted", now, [previous], []), FleetJsonContext.Default.WorkerReport), token);
return previous;
}
catch (Exception) when (!token.IsCancellationRequested)
{
return (previous ?? new(profile.Id, profile.Provider, auth, settings, [], [], [])) with
{ Auth = auth, CollectionError = "Metadata collection failed; previous data retained." };
}
}
private sealed class ProfileRunner(WorkerProfile profile) : IProcessRunner
{
public Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken token) => new ProcessRunner().RunAsync(
request with { EnvironmentOverrides = CliAuthentication.EnvironmentFor(profile) }, token);
}
}
+2
View File
@@ -0,0 +1,2 @@
# Web
Authenticated private dashboard. All JSON uses FleetJsonContext. No request-body logging. Login responses stay in memory, session-bound and profile-bound; never serialize LoginCoordinator into durable state. Browser code uses textContent for external metadata. See D14.
+39
View File
@@ -0,0 +1,39 @@
using System.Security.Cryptography;
using System.Text;
namespace FinalToken.Web;
public sealed class BrowserSessions
{
private sealed record Session(string Csrf, DateTimeOffset Expires);
private readonly Lock gate = new();
private readonly Dictionary<string, Session> sessions = [];
private readonly Dictionary<string, (DateTimeOffset Since, int Count)> attempts = [];
public static bool Matches(string? supplied, string expected) => supplied is not null &&
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(supplied)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
public bool AllowAttempt(string address, DateTimeOffset now)
{
lock (gate)
{
foreach (var key in attempts.Where(p => now - p.Value.Since >= TimeSpan.FromMinutes(1)).Select(p => p.Key).ToArray()) attempts.Remove(key);
if (!attempts.TryGetValue(address, out var value))
{ if (attempts.Count >= 1000) return false; value = (now, 0); }
attempts[address] = (value.Since, value.Count + 1);
return value.Count < 10;
}
}
public (string Id, string Csrf) Create(DateTimeOffset now)
{
lock (gate)
{
foreach (var expired in sessions.Where(s => s.Value.Expires <= now).Select(s => s.Key).ToArray()) sessions.Remove(expired);
if (sessions.Count >= 100) throw new InvalidDataException("Too many dashboard sessions.");
var id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var csrf = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
sessions.Add(id, new(csrf, now.AddHours(8))); return (id, csrf);
}
}
public string? Csrf(string? id, DateTimeOffset now)
{ lock (gate) return id is not null && sessions.TryGetValue(id, out var s) && s.Expires > now ? s.Csrf : null; }
public void Remove(string? id) { lock (gate) if (id is not null) sessions.Remove(id); }
}
+4
View File
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup><PublishAot>true</PublishAot><EnableRequestDelegateGenerator>true</EnableRequestDelegateGenerator></PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
</Project>
+110
View File
@@ -0,0 +1,110 @@
using System.Text.Json;
using FinalToken.Core;
using FinalToken.Fleet;
using FinalToken.Web;
var configPath = Environment.GetEnvironmentVariable("FINALTOKEN_SERVER_CONFIG") ?? "server.json";
var directory = Environment.GetEnvironmentVariable("FINALTOKEN_SERVER_DATA") ?? Path.Combine(DataPaths.DataDirectory, "server");
var config = JsonSerializer.Deserialize(File.ReadAllText(configPath), FleetJsonContext.Default.ServerConfig)
?? throw new InvalidDataException("Invalid server configuration.");
var dashboardKey = Environment.GetEnvironmentVariable("FINALTOKEN_DASHBOARD_KEY");
if (dashboardKey is not { Length: >= 32 }) throw new InvalidDataException("Set FINALTOKEN_DASHBOARD_KEY to a random key of at least 32 characters.");
var machineKeys = config.Machines.ToDictionary(m => m.Id, m => Environment.GetEnvironmentVariable("FINALTOKEN_MACHINE_" + m.Id));
if (machineKeys.Values.Any(k => k is not { Length: >= 32 }) || machineKeys.Values.Append(dashboardKey).Distinct().Count() != machineKeys.Count + 1)
throw new InvalidDataException("Set a separate random FINALTOKEN_MACHINE_<id> key for every machine.");
using var serverLock = StoreLock.TryAcquire(directory) ?? throw new InvalidDataException("Server data directory is already in use.");
var store = new FleetStore(directory, config);
var logins = new LoginCoordinator(config);
var sessions = new BrowserSessions();
var builder = WebApplication.CreateSlimBuilder(args);
builder.Logging.ClearProviders(); // Never log request bodies, authorization codes, CLI output or URL query strings.
if (string.IsNullOrEmpty(Environment.GetEnvironmentVariable("ASPNETCORE_URLS"))) builder.WebHost.UseUrls("http://127.0.0.1:5187");
builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 32 * 1024 * 1024);
builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.TypeInfoResolverChain.Insert(0, FleetJsonContext.Default));
var app = builder.Build();
app.Use(async (ctx, next) =>
{
ctx.Response.Headers.CacheControl = "no-store";
ctx.Response.Headers["Referrer-Policy"] = "no-referrer";
ctx.Response.Headers["X-Content-Type-Options"] = "nosniff";
ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
var worker = ctx.Request.Path == "/worker/report";
if (worker)
{
var id = ctx.Request.Headers["X-FinalToken-Machine"].ToString();
var auth = ctx.Request.Headers.Authorization.ToString();
if (!machineKeys.TryGetValue(id, out var key) || !auth.StartsWith("Bearer ", StringComparison.Ordinal) || !BrowserSessions.Matches(auth[7..], key!))
{ ctx.Response.StatusCode = 401; return; }
ctx.Items["machine"] = id;
}
else
{
// D14: accept IPs and hostnames; browser mutations must originate from the requested host.
if (ctx.Request.Method != "GET")
{
if (ctx.Request.Headers["X-FinalToken"] != "1") { ctx.Response.StatusCode = 403; return; }
if (ctx.Request.Headers.Origin.Count > 0)
{
if (!FleetValidation.TryHttpOrigin(ctx.Request.Headers.Origin.ToString(), out var browserOrigin) ||
!FleetValidation.MatchesRequestHost(browserOrigin, ctx.Request.Host.Value))
{ ctx.Response.StatusCode = 403; return; }
ctx.Items["https-origin"] = browserOrigin.Scheme == "https";
}
}
if (ctx.Request.Path.StartsWithSegments("/api"))
{
var session = ctx.Request.Cookies["finaltoken"];
var csrf = sessions.Csrf(session, DateTimeOffset.UtcNow);
if (csrf is null) { ctx.Response.StatusCode = 401; return; }
if (ctx.Request.Method != "GET" && !BrowserSessions.Matches(ctx.Request.Headers["X-CSRF"], csrf))
{ ctx.Response.StatusCode = 403; return; }
ctx.Items["session"] = session; ctx.Items["csrf"] = csrf;
}
}
try { await next(ctx); }
catch (KeyNotFoundException) { ctx.Response.StatusCode = 404; }
catch (InvalidDataException) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsync("Operation rejected: profile, login state or metadata is invalid."); }
catch (BadHttpRequestException) { ctx.Response.StatusCode = 400; }
catch (JsonException) { ctx.Response.StatusCode = 400; }
catch (OperationCanceledException) when (ctx.RequestAborted.IsCancellationRequested) { }
catch (Exception) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsync("Operation failed; no secret details are logged."); }
});
app.MapPost("/session", async (HttpContext ctx) =>
{
if (!sessions.AllowAttempt(ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown", DateTimeOffset.UtcNow)) return Results.StatusCode(429);
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.SignIn, ctx.RequestAborted);
if (!BrowserSessions.Matches(input?.Key, dashboardKey)) return Results.Unauthorized();
sessions.Remove(ctx.Request.Cookies["finaltoken"]);
var session = sessions.Create(DateTimeOffset.UtcNow);
ctx.Response.Cookies.Append("finaltoken", session.Id, new CookieOptions { HttpOnly = true, Secure = ctx.Request.IsHttps || ctx.Items["https-origin"] is true, SameSite = SameSiteMode.Strict, Path = "/", MaxAge = TimeSpan.FromHours(8) });
return Results.Json(new BrowserSession(session.Csrf), FleetJsonContext.Default.BrowserSession);
});
app.MapGet("/api/session", (HttpContext ctx) => Results.Json(new BrowserSession((string)ctx.Items["csrf"]!), FleetJsonContext.Default.BrowserSession));
app.MapPost("/api/logout", (HttpContext ctx) => { sessions.Remove(ctx.Request.Cookies["finaltoken"]); ctx.Response.Cookies.Delete("finaltoken"); return Results.NoContent(); });
app.MapGet("/api/dashboard", () => Results.Json(store.Dashboard(DateTimeOffset.UtcNow), FleetJsonContext.Default.DashboardView));
app.MapPost("/api/logins", async (HttpContext ctx) =>
{
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.StartLogin, ctx.RequestAborted) ?? throw new InvalidDataException();
return Results.Json(logins.Start((string)ctx.Items["session"]!, input.MachineId, input.ProfileId, store.Current, DateTimeOffset.UtcNow), FleetJsonContext.Default.LoginView);
});
app.MapGet("/api/logins/{id}", (HttpContext ctx, string id) => Results.Json(logins.Get(id, (string)ctx.Items["session"]!, DateTimeOffset.UtcNow), FleetJsonContext.Default.LoginView));
app.MapPost("/api/logins/{id}/response", async (HttpContext ctx, string id) =>
{
var input = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.LoginResponse, ctx.RequestAborted) ?? throw new InvalidDataException();
logins.Respond(id, (string)ctx.Items["session"]!, input.Response, DateTimeOffset.UtcNow); return Results.NoContent();
});
app.MapPost("/api/logins/{id}/cancel", (HttpContext ctx, string id) => { logins.Cancel(id, (string)ctx.Items["session"]!, DateTimeOffset.UtcNow); return Results.NoContent(); });
app.MapPost("/worker/report", async (HttpContext ctx) =>
{
var report = await ctx.Request.ReadFromJsonAsync(FleetJsonContext.Default.WorkerReport, ctx.RequestAborted) ?? throw new InvalidDataException();
var machine = (string)ctx.Items["machine"]!;
await store.AcceptAsync(report, machine, DateTimeOffset.UtcNow, ctx.RequestAborted);
return Results.Json(logins.Exchange(machine, report.BootId, report.Logins, DateTimeOffset.UtcNow), FleetJsonContext.Default.WorkerReply);
});
// Explicit allowlist; never serve configuration, state files or a fallback path from the repository.
foreach (var (route, file, mime) in new[] { ("/", "index.html", "text/html"), ("/app.js", "app.js", "text/javascript"), ("/style.css", "style.css", "text/css") })
{
var path = Path.Combine(app.Environment.ContentRootPath, "wwwroot", file);
app.MapGet(route, () => Results.File(path, mime));
}
await app.RunAsync();
+96
View File
@@ -0,0 +1,96 @@
'use strict';
const $ = id => document.getElementById(id);
let csrf = null, dashboard = null, login = null, loginTimer = null;
const fmt = n => n == null ? 'Unknown' : new Intl.NumberFormat(undefined, {maximumFractionDigits:1}).format(n);
const pct = n => n == null ? 'Unknown' : `${fmt(n)}%`;
const money = n => n == null ? 'Unpriced' : `≈ $${new Intl.NumberFormat(undefined,{minimumFractionDigits:2,maximumFractionDigits:6}).format(n)}`;
const date = (t, zone) => t ? new Date(t).toLocaleString(undefined, {timeZone:zone, month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'}) : 'Unknown';
const shortDate = (t, zone) => new Date(t).toLocaleDateString(undefined,{timeZone:zone,month:'short',day:'numeric'});
const el = (tag, text, cls) => { const n = document.createElement(tag); if(text != null) n.textContent=text; if(cls) n.className=cls; return n; };
function error(e) { $('error').textContent=e.message; $('error').hidden=false; }
async function api(path, body) {
const r = await fetch(path,{method:body === undefined?'GET':'POST',headers:{'Content-Type':'application/json','X-FinalToken':'1',...(csrf?{'X-CSRF':csrf}:{})},...(body===undefined?{}:{body:JSON.stringify(body)}),cache:'no-store'});
if(!r.ok) { if(r.status===401) { csrf=null; $('signin').hidden=false; $('dashboard').hidden=true; $('logout').hidden=true; } throw new Error(r.status===409?'Operation rejected. Check profile, pending login state and machine status.':`Request failed (${r.status}).`); }
return r.status===204?null:r.json();
}
async function load() {
dashboard=await api('/api/dashboard'); $('signin').hidden=true; $('dashboard').hidden=false; $('logout').hidden=false; $('error').hidden=true;
$('updated').textContent=`View updated ${new Date(dashboard.now).toLocaleTimeString()}`;
$('accounts').replaceChildren(...dashboard.accounts.map(accountCard)); renderMachines();
}
function metric(label,value,detail) { const n=el('div',null,'metric'); n.append(el('div',label,'metric-label'),el('div',value,'metric-value'),el('div',detail,'metric-detail')); return n; }
function table(headers,rows) { const wrap=el('div',null,'table-scroll'),t=el('table'),head=el('thead'),tr=el('tr'); headers.forEach(h=>tr.append(el('th',h))); head.append(tr);t.append(head);const body=el('tbody');rows.forEach(row=>{const r=el('tr');row.forEach(cell=>r.append(el('td',cell)));body.append(r);});t.append(body);wrap.append(t);return wrap; }
function disclosure(title,child) { const d=el('details');d.append(el('summary',title),child);return d; }
function svgNode(tag,attrs,text) { const n=document.createElementNS('http://www.w3.org/2000/svg',tag);Object.entries(attrs).forEach(([k,v])=>n.setAttribute(k,String(v)));if(text)n.textContent=text;return n; }
function chartBase(title) { const box=el('div',null,'chart-frame');box.append(el('h4',title));const svg=svgNode('svg',{viewBox:'0 0 560 230',class:'chart',role:'img','aria-label':title});box.append(svg);return {box,svg}; }
function burnChart(v,zone) {
const {box,svg}=chartBase('Allowance used · current reset window');const a=v.analysis;
if(!a){box.append(el('p',v.stale?'Stale allowance — fresh observation needed.':'Not enough reset information for a projection.','muted'));return box;}
const start=+new Date(a.current.start),end=+new Date(a.current.reset),x=t=>40+480*(+new Date(t)-start)/(end-start);
const top=Math.max(100,Math.min(200,v.useAtReset??100)),y=p=>190-160*p/top;
[0,50,100].forEach(p=>{svg.append(svgNode('line',{x1:40,x2:520,y1:y(p),y2:y(p),class:'axis'}),svgNode('text',{x:4,y:y(p)+4},`${p}%`));});
svg.append(svgNode('line',{x1:40,y1:y(0),x2:520,y2:y(100),class:'pace'}));
const points=a.current.points;
for(let i=1;i<points.length;i++) svg.append(svgNode('path',{d:`M ${x(points[i-1].time)} ${y(points[i-1].used)} L ${x(points[i].time)} ${y(points[i].used)}`,class:points[i].origin==='Estimated'||points[i-1].origin==='Estimated'?'estimated':'measured'}));
if(v.useAtReset!=null) svg.append(svgNode('path',{d:`M ${x(dashboard.now)} ${y(v.window.usedPercent)} L 520 ${y(Math.min(top,v.useAtReset))}`,class:'projection'}));
svg.append(svgNode('text',{x:40,y:215},shortDate(start,zone)),svgNode('text',{x:520,y:215,'text-anchor':'end'},`Reset ${date(end,zone)}`));
box.append(el('p','Solid: measured · short dash: token estimate · grey: even pace · green dash: average projection','legend'));return box;
}
function accountCard(a) {
const n=el('article',null,`account ${a.account.provider.toLowerCase()}`),head=el('div',null,'account-heading'),name=el('div');
name.append(el('div',a.account.provider.toUpperCase(),'provider'),el('h2',a.account.label),el('p',`${a.account.expectedEmail} · account-wide allowance · ${a.account.timeZone}`));
head.append(name,el('span',`${a.windows.length} observed limit${a.windows.length===1?'':'s'}`,'badge'));n.append(head);const content=el('div',null,'account-content');
a.warnings.forEach(w=>content.append(el('p',w,'warning-note')));
if(!a.windows.length) content.append(el('h3','Allowance unknown'),el('p','Connect a verified CLI profile with observed provider limits. Token totals alone cannot answer whether the week will last.','muted'));
a.windows.forEach(w=>content.append(windowCard(w,a.account.timeZone)));
const totals=el('div',null,'metrics');totals.append(metric('Collected history · deduplicated tokens',a.hasConsumptionData?fmt(a.total.total):'Unknown','Includes only attributed records and designated legacy history'),metric('Estimated API list-price value',money(a.apiValue),`USD · table checked ${a.pricesCheckedOn}`),metric('Unpriced tokens',a.hasConsumptionData?fmt(a.unpricedTokens):'Unknown','Not included in the price estimate'));content.append(totals);
const tokenChart=chartBase('Token history · last 30 local days');const days=new Map();const cutoff=+new Date(dashboard.now)-30*86400000;
a.tokens.filter(t=>+new Date(t.time)>=cutoff).forEach(t=>{const key=shortDate(t.time,a.account.timeZone);days.set(key,(days.get(key)||0)+t.counts.total);});
const rows=[...days];const max=Math.max(1,...rows.map(r=>r[1]));rows.forEach(([day,value],i)=>{const width=480/Math.max(1,rows.length);const bar=svgNode('rect',{x:40+i*width,y:190-value/max*155,width:Math.max(1,width-4),height:value/max*155,class:'bar'});bar.append(svgNode('title',{},`${day}: ${fmt(value)} tokens`));tokenChart.svg.append(bar);if(i%Math.ceil(rows.length/6)===0)tokenChart.svg.append(svgNode('text',{x:40+i*width,y:215},day));});
if(!rows.length)tokenChart.box.append(el('p','No attributed token history reported yet.','muted'));
content.append(disclosure('Token history and API value',tokenChart.box));
content.append(disclosure(`Session consumption · ${a.sessions.length} identified sessions`,table(['Session id','Tokens'],a.sessions.slice(0,50).map(s=>[s.id,fmt(s.tokens.total)]))));
n.append(content);return n;
}
function windowCard(v,zone) {
const w=v.window,n=el('section',null,'window'),heading=el('div',null,'window-title');
const state=v.stale?'Stale':({Ahead:'Ahead of sustainable pace',Behind:'Below sustainable pace',OnTrack:'Within pace alert threshold',Unknown:'Pace unknown'}[v.pace.state]||'Unknown');
heading.append(el('h3',w.label),el('span',state,`badge ${v.stale||v.pace.state==='Ahead'?'warning':''}`));n.append(heading);
const verdict=v.stale?'Waiting for fresh allowance data':v.useAtReset==null?'Forecast needs more elapsed time or reset data':v.useAtReset>100?'At this average rate, you will run out before reset.':'At this average rate, your allowance will last until reset.';
n.append(el('p',verdict,`verdict ${v.useAtReset>100?'warning':''}`));
const m=el('div',null,'metrics');m.append(metric('Remaining now',pct(100-w.usedPercent),`${pct(w.usedPercent)} used · measured ${date(w.sampleTime,zone)}`),metric('Remaining at reset · projected',v.remainingAtReset==null?'Unknown':pct(Math.max(0,v.remainingAtReset)),v.useAtReset>100?`${pct(v.useAtReset-100)} over allowance at this rate`:'Constant average rate, not guaranteed'),metric('Estimated exhaustion',v.pace.projection?date(v.pace.projection,zone):'—',v.pace.projection?'Before reset at the average rate':'No predicted exhaustion / insufficient data'),metric('Allowance resets',date(w.resetsAt,zone),`${v.pace.delta==null?'Unknown':fmt(v.pace.delta)} percentage points versus even pace`));n.append(m);
const grid=el('div',null,'chart-grid');grid.append(burnChart(v,zone));const side=el('div');const days=v.analysis?.days;
const budget=el('div',null,'budget');budget.append(el('h3',`Today’s budget: ${pct(days?.todayBudget)}`),el('p',`Used today: ${pct(days?.today)} (${days?.todayOrigin??'unknown'}). Budget baseline: ${days?.budgetOrigin??'unknown'}.`),el('p',`Later daily budget: ${pct(days?.laterBudget)} per full day; partial days use their actual share.`));side.append(budget);
side.append(el('h3','Recent rate · last 24 hours'),el('p',v.recent?`${fmt(v.recent.percentPerDay)} percentage points/day → ${pct(v.recent.useAtReset)} used at reset. ${v.recent.reachesLimit?'Exhaustion '+date(v.recent.reachesLimit,zone):'No exhaustion predicted.'}`:'Needs at least 3 hours of consistent samples in this reset instance.','muted'),el('p','Average and recent rates are separate estimates. Early forecasts can move sharply. Reset boundaries and partial days follow the provider’s actual window.','muted'));grid.append(side);n.append(grid);
if(days)n.append(disclosure('Daily use and remaining daily plan',table(['Local day','Used','Even pace','Daily budget','Origin'],days.current.map(d=>[shortDate(d.start,zone)+(d.isToday?' · today':''),pct(d.used),pct(d.evenPace),pct(d.budget),d.origin+(d.budgetOrigin?` / budget ${d.budgetOrigin}`:'')]))));
if(v.resets)n.append(disclosure(`Observed reset history · ${v.resets.totals.instances} windows · ${v.resets.totals.early} early resets`,table(['Start','End / reset','Final use','Tokens','API value','Reset'],v.resets.instances.map(r=>[date(r.start,zone),date(r.end,zone),r.running?'Running':pct(r.final?.used),fmt(r.tokens?.total),r.apiValue==null?'Unknown':`≈ $${fmt(r.apiValue)}`,r.early?'Early':'Scheduled']))));
return n;
}
function renderMachines() {
$('machine-list').replaceChildren(...dashboard.machines.map(m=>{
const n=el('article',null,'machine');n.append(el('h3',m.label),el('span',m.online?'● Online':'○ Offline',`status ${m.online?'':'offline'}`),el('p',`${m.osUser} · last seen ${date(m.seenAt)}`,'muted'));
m.bindings.forEach(b=>{const p=m.profiles.find(p=>p.id===b.id),a=dashboard.accounts.find(a=>a.account.id===b.accountId)?.account,c=m.consumption.find(c=>c.profileId===b.id);const row=el('div',null,'profile');row.append(el('strong',`${a?.provider??''} · ${b.id}`),el('p',`Expected: ${a?.expectedEmail??'Unknown'}`),el('p',`${p?.auth.state??'Not reported'} · actual: ${p?.auth.email??'Unknown'} · checked ${date(p?.auth.checkedAt)}`),el('p',p?.collectionError??p?.auth.reason??'Start the worker to report this profile.'),el('p',`Identified local consumption: ${fmt(c?.tokens?.total)} tokens · ${c?.sessions??0} sessions. Shared copies may appear on other machines; do not sum these totals.`));
const button=el('button','Log in / renew');button.disabled=!m.online;button.addEventListener('click',()=>startLogin(m,b,a).catch(error));row.append(button);n.append(row);});return n;
}));
}
async function startLogin(machine,binding,account) {
login=await api('/api/logins',{machineId:machine.id,profileId:binding.id});$('login-target').textContent=`${machine.label} → OS user ${machine.osUser} → profile ${binding.id} → ${account?.expectedEmail}`;
$('login-error').textContent='';$('code').value='';$('login-dialog').showModal();renderLogin();clearInterval(loginTimer);loginTimer=setInterval(pollLogin,1500);
}
function renderLogin() {
$('login-state').textContent=`${login.state} · attempt expires ${date(login.expiresAt)}${login.email?' · CLI reports '+login.email:''}`;
$('auth-link').hidden=!login.url;if(login.url)$('auth-link').href=login.url;else $('auth-link').removeAttribute('href');
$('device-code').hidden=!login.deviceCode;$('device-code').textContent=login.deviceCode?`Device code: ${login.deviceCode}`:'';
$('code-form').hidden=login.state!=='WaitingForCode';$('cancel-login').disabled=['Succeeded','Failed','Cancelled','TimedOut','AccountMismatch','IdentityUnknown','WorkerRestarted'].includes(login.state);
if($('cancel-login').disabled){clearInterval(loginTimer);load().catch(error);}
}
async function pollLogin(){try{login=await api(`/api/logins/${login.id}`);renderLogin();}catch(e){$('login-error').textContent=e.message;}}
$('signin-form').addEventListener('submit',async e=>{e.preventDefault();try{const r=await api('/session',{key:$('key').value});$('key').value='';csrf=r.csrf;await load();}catch(e){error(e);}});
$('refresh').addEventListener('click',()=>load().catch(error));
$('logout').addEventListener('click',async()=>{try{await api('/api/logout',{});csrf=null;$('signin').hidden=false;$('dashboard').hidden=true;$('logout').hidden=true;}catch(e){error(e);}});
$('code-form').addEventListener('submit',async e=>{e.preventDefault();const response=$('code').value;$('code').value='';try{await api(`/api/logins/${login.id}/response`,{response});$('code-form').hidden=true;}catch(e){$('login-error').textContent=e.message;}});
$('cancel-login').addEventListener('click',async()=>{try{await api(`/api/logins/${login.id}/cancel`,{});await pollLogin();}catch(e){$('login-error').textContent=e.message;}});
$('close-login').addEventListener('click',()=>{$('login-dialog').close();clearInterval(loginTimer);});
$('login-dialog').addEventListener('close',()=>clearInterval(loginTimer));
api('/api/session').then(s=>{csrf=s.csrf;return load();}).catch(()=>{});
setInterval(()=>{if(csrf&&!document.hidden)load().catch(error);},30000);
+18
View File
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>FinalToken · Weekly outlook</title><link rel="stylesheet" href="/style.css"><script src="/app.js" defer></script></head>
<body>
<header><a class="brand" href="/">F<span>FinalToken</span></a><span class="tag">YOUR WEEK, IN PERSPECTIVE</span><button id="logout" hidden>Sign out</button></header>
<main>
<section id="signin" class="signin"><p class="eyebrow">SELF-HOSTED / PRIVATE</p><h1>Make the week<br>work for you.</h1><p>Know whether your current usage will last until your allowance resets.</p><form id="signin-form"><label for="key">Dashboard access key</label><input id="key" type="password" autocomplete="current-password" required maxlength="512"><button class="primary">Open dashboard</button></form><p class="muted">Provider credentials stay with the official CLI on each machine.</p></section>
<section id="dashboard" hidden>
<div class="intro"><div><p class="eyebrow">WEEKLY OUTLOOK</p><h1>Will your allowance last?</h1><p>Measured limits. Your actual reset. FinalToken’s sustainability analysis.</p></div><div class="updated"><span id="updated">Waiting for data</span><button id="refresh">Refresh view</button></div></div>
<nav aria-label="Dashboard sections"><a href="#accounts">Account outlook</a><a href="#machines">Machines & logins</a></nav>
<div id="accounts"></div>
<section class="machines-section" id="machines"><div class="section-heading"><div><p class="eyebrow">CONNECTED ENVIRONMENTS</p><h2>Machines & official CLI logins</h2></div><p>Login responses travel to the selected profile.<br>Credentials remain on that machine.</p></div><div id="machine-list" class="machine-grid"></div></section>
<footer>Constant-rate projections are estimates, not guaranteed capacity. API list-price value is not your subscription allowance. Working-hour patterns are not modelled.</footer>
</section>
<p id="error" role="alert" hidden></p>
</main>
<dialog id="login-dialog" aria-labelledby="login-title"><div class="dialog-heading"><h2 id="login-title">Official CLI login</h2><button id="close-login" aria-label="Close login dialog">×</button></div><p id="login-target"></p><p class="muted">Use the intended provider account. A different account is reported as a mismatch; FinalToken will not silently reassign its history.</p><p id="login-state" role="status"></p><a id="auth-link" target="_blank" rel="noopener noreferrer" hidden>Open official authorization page ↗</a><p id="device-code" hidden></p><form id="code-form" hidden><label for="code">Authorization code shown by Claude</label><input id="code" autocomplete="off" spellcheck="false" maxlength="2048" required><button class="primary">Send once to this CLI</button></form><p id="login-error" role="alert"></p><p class="muted">No automatic remote localhost callback is assumed. If your CLI cannot accept the manual code through stdin, cancel and log in in that machine’s terminal.</p><button id="cancel-login">Cancel login</button></dialog>
</body></html>
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
# Worker
Outbound authenticated HTTP only. Runs as its configured OS user; profile paths and CLI commands come from local configuration. No arbitrary remote commands, credential-file reads or inference. Persist metadata before scan cursors. See D14 and docs/web-dashboard.md.
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><AssemblyName>finaltoken-worker</AssemblyName></PropertyGroup>
<ItemGroup><ProjectReference Include="../FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
</Project>
+70
View File
@@ -0,0 +1,70 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using FinalToken.Core;
using FinalToken.Fleet;
if (args.Length != 1) { Console.Error.WriteLine("Usage: finaltoken-worker <worker.json>"); return 2; }
try
{
var config = JsonSerializer.Deserialize(File.ReadAllText(args[0]), FleetJsonContext.Default.WorkerConfig)
?? throw new InvalidDataException("Missing worker configuration.");
if (!FleetValidation.Identifier(config.MachineId) || config.Profiles is not { Count: > 0 } ||
config.Profiles.Select(p => p.Id).Distinct().Count() != config.Profiles.Count ||
config.Profiles.Any(p => !FleetValidation.Identifier(p.Id) || !Enum.IsDefined(p.Provider) ||
string.IsNullOrWhiteSpace(p.ExpectedEmail) || !Path.IsPathFullyQualified(p.ConfigDirectory) || !Path.IsPathFullyQualified(p.DataDirectory)))
throw new InvalidDataException("Invalid worker profile configuration.");
if (!FleetValidation.TryHttpOrigin(config.ServerUrl, out var uri))
throw new InvalidDataException("Server URL must be an HTTP or HTTPS origin without credentials or a path.");
if (config.Profiles.Select(p => Path.GetFullPath(p.ConfigDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count ||
config.Profiles.Select(p => Path.GetFullPath(p.DataDirectory)).Distinct(OperatingSystem.IsWindows() ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal).Count() != config.Profiles.Count)
throw new InvalidDataException("Each profile requires separate config and data directories.");
Directory.CreateDirectory(config.StateDirectory);
using var workerLock = StoreLock.TryAcquire(config.StateDirectory) ?? throw new InvalidDataException("Another worker owns this state directory.");
var key = Environment.GetEnvironmentVariable("FINALTOKEN_WORKER_KEY");
if (key is not { Length: >= 32 }) throw new InvalidDataException("FINALTOKEN_WORKER_KEY must contain at least 32 characters.");
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { BaseAddress = uri, Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
http.DefaultRequestHeaders.Add("X-FinalToken-Machine", config.MachineId);
using var stop = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Cancel(); };
var boot = Guid.NewGuid().ToString("N");
var collectors = config.Profiles.Select(p => new ProfileCollector(p, config.StateDirectory)).ToArray();
await using var logins = new WorkerLogins(config.Profiles);
var profiles = config.Profiles.Select(p => new ProfileReport(p.Id, p.Provider,
new("Unknown", null, DateTimeOffset.UtcNow, "First collection pending."), new(), [], [], [])).ToArray();
Task<ProfileReport[]>? collection = null;
var nextCollection = DateTimeOffset.MinValue;
Console.WriteLine("FinalToken worker started. Only fixed metadata status is logged.");
while (!stop.IsCancellationRequested)
{
try
{
if (collection is { IsCompleted: true })
{
profiles = await collection; collection = null; nextCollection = DateTimeOffset.UtcNow.AddSeconds(60);
}
if (collection is null && DateTimeOffset.UtcNow >= nextCollection &&
!logins.Updates.Any(u => u.State is "Starting" or "WaitingForBrowser" or "WaitingForCode" or "Verifying"))
collection = Task.WhenAll(collectors.Select(c => c.CollectAsync(stop.Token)));
var report = new WorkerReport(config.MachineId, Environment.UserName, boot, DateTimeOffset.UtcNow, profiles, logins.Updates);
using var response = await http.PostAsJsonAsync("/worker/report", report, FleetJsonContext.Default.WorkerReport, stop.Token);
response.EnsureSuccessStatusCode();
var reply = await response.Content.ReadFromJsonAsync(FleetJsonContext.Default.WorkerReply, stop.Token)
?? throw new InvalidDataException("Empty server response.");
if (collection is not null && reply.Commands.Any(c => !c.Cancel))
{
// Finish metadata work before starting/feeding a login in the same CLI profile.
profiles = await collection; collection = null; nextCollection = DateTimeOffset.UtcNow.AddSeconds(60);
}
await logins.ApplyAsync(reply, stop.Token);
if (logins.TakeIdentityChanges()) nextCollection = DateTimeOffset.MinValue;
}
catch (OperationCanceledException) when (stop.IsCancellationRequested) { break; }
catch (Exception) { Console.Error.WriteLine("Worker exchange failed; retaining local metadata and retrying."); }
try { await Task.Delay(TimeSpan.FromSeconds(3), stop.Token); } catch (OperationCanceledException) { break; }
}
if (collection is not null) try { await collection; } catch (OperationCanceledException) { }
return 0;
}
catch (Exception) { Console.Error.WriteLine("Worker stopped. Check configuration, local file access and CLI installation. Secret details are not logged."); return 1; }
+1
View File
@@ -5,3 +5,4 @@ View-model tests use public Core queries. Headless tests run on a dedicated UI t
Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside Skia and HarfBuzz, exercise settings and popup actions, and save PNG screenshots outside
the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path. the repo at ../runs/shots/app. FINALTOKEN_SCREENSHOT_DIR overrides that path.
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping. Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
Pin panel clocks and HistoryStore retention clocks to fixture time. Reuse FixedClock for fixed-date tests.
+62 -6
View File
@@ -5,13 +5,67 @@ namespace FinalToken.App.Tests;
public sealed class FormattingTests public sealed class FormattingTests
{ {
[Theory]
[InlineData(6000000000, "6 B")]
[InlineData(2000000000, "2 B")]
[InlineData(1500000000, "1,5 B")]
[InlineData(600000000, "600 M")]
[InlineData(82500, "82,5 K")]
[InlineData(0, "0")]
public void AxisNumbersDropTrailingZerosWithoutChangingCompactValues(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE");
Assert.Equal(expected, Display.Axis(value));
Assert.Equal("2,00 B", Display.Compact(2000000000));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(292950000, "293 M")]
[InlineData(2300000000, "2,30 B")]
[InlineData(966690000, "967 M")]
[InlineData(82500, "82,5 K")]
[InlineData(999950, "1,00 M")]
[InlineData(0, "0")]
public void CompactNumbersUseThreeSignificantDigits(double value, string expected)
{
var previous = CultureInfo.CurrentCulture;
try { CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de-DE"); Assert.Equal(expected, Display.Compact(value)); }
finally { CultureInfo.CurrentCulture = previous; }
}
[Theory]
[InlineData(FinalToken.Core.PaceState.Ahead, true)]
[InlineData(FinalToken.Core.PaceState.OnTrack, false)]
[InlineData(FinalToken.Core.PaceState.Behind, false)]
[InlineData(FinalToken.Core.PaceState.Unknown, false)]
public void ForecastWarningFollowsState(FinalToken.Core.PaceState state, bool warning)
{
var text = Display.Forecast(new(2026, 10, 18, 14, 43, 0, TimeSpan.Zero), state, new FixedClock());
Assert.Equal(warning, text.Contains('⚠'));
Assert.StartsWith(warning ? "⚠ 100 % on " : "At this pace 100 % on ", text);
}
[Theory]
[InlineData(1)]
[InlineData(1.25)]
[InlineData(2)]
public void DenseBarEdgesMeetOnPhysicalPixelsWithoutGaps(double scaling)
{
var first = UsageChart.BarBounds(50.13, 100, 3.17, 40, scaling);
var next = UsageChart.BarBounds(53.30, 100, 3.17, 40, scaling);
Assert.Equal(first.Right, next.Left, 6);
Assert.Equal(Math.Round(first.Left * scaling), first.Left * scaling, 6);
Assert.Equal(Math.Round(first.Right * scaling), first.Right * scaling, 6);
}
[Fact] [Fact]
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate() public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
{ {
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone); var day = FinalToken.Core.CalendarDays.Start(new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero), zone);
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1))); Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1))); Assert.Equal(day.DateTime.ToString("d"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
} }
[Theory] [Theory]
[InlineData(null)] [InlineData(null)]
@@ -63,9 +117,11 @@ public sealed class FormattingTests
Assert.Equal([0d], UsageChart.AxisTicks(0, true)); Assert.Equal([0d], UsageChart.AxisTicks(0, true));
} }
private sealed class FixedClock : TimeProvider }
{
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero); internal sealed class FixedClock(DateTimeOffset? now = null) : TimeProvider
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture"); {
} public DateTimeOffset UtcNow { get; set; } = now ?? new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero);
public override DateTimeOffset GetUtcNow() => UtcNow;
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
} }
+359 -15
View File
@@ -1,5 +1,6 @@
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Headless; using Avalonia.Headless;
using Avalonia.Interactivity; using Avalonia.Interactivity;
using Avalonia.Media.Imaging; using Avalonia.Media.Imaging;
@@ -29,23 +30,350 @@ public sealed class HeadlessTests
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app"); var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
Directory.CreateDirectory(shots); Directory.CreateDirectory(shots);
var model = FakeData.Model(); var model = FakeData.Model();
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 }; var clock = new FixedClock(model.Snapshot!.MadeAt);
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Resources["SystemAccentColor"] = Avalonia.Media.Colors.Red;
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png"); panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title); Assert.Equal($"FinalToken {typeof(Program).Assembly.GetName().Version!.ToString(3)}", panel.Title);
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude"); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day"); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Tokens per day");
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray(); Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "●" && t.Foreground?.ToString() == "#ffeb6834");
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2; Assert.All(panel.GetVisualDescendants().OfType<ProgressBar>(), bar => Assert.True(bar.Bounds.Width <= 140, $"Share bar width {bar.Bounds.Width}"));
Assert.Single(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Current session");
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("At this pace 100 % on ", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<WrapPanel>(), p => p.Name == "CompositionLegend");
var codexTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(codexTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains('⚠') == true || t.Foreground?.ToString() == "#ffd03b3b");
var withCache = panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value));
panel.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Include cache reads").IsChecked = false;
Dispatcher.UIThread.RunJobs();
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == Display.Compact(61000000));
Assert.True(panel.GetVisualDescendants().OfType<UsageChart>().Where(c => !c.Percent).Sum(c => c.Values.Sum(v => v.Value)) < withCache);
model.IncludeCacheReads = true; Dispatcher.UIThread.RunJobs();
var originalSnapshot = model.Snapshot!;
var originalHistory = model.History;
var claude = originalSnapshot.Providers.Single(p => p.Provider == Provider.Claude);
var week = claude.Windows.Single(w => w.Window.Id == "week");
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude
? p with { Windows = p.Windows.Append(week with { Window = week.Window with { Id = "fable", Label = "Week · Fable" } }).ToArray() } : p).ToArray() };
model.History = originalHistory with { Details = originalHistory.Details.Append(originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week") with { Id = "fable" }).ToArray() };
Dispatcher.UIThread.RunJobs();
panel.GetVisualDescendants().OfType<ComboBox>().Single().SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Claude · Week · Fable");
var wheelSelector = panel.GetVisualDescendants().OfType<ComboBox>().Single();
var wheelViewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
Dispatcher.UIThread.RunJobs(); using (panel.CaptureRenderedFrame()) { }
var maximumOffset = wheelViewport.Extent.Height - wheelViewport.Viewport.Height;
const double scrollRoom = 80;
Assert.True(maximumOffset > scrollRoom * 2);
var selectorTop = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y + wheelViewport.Offset.Y;
// BringIntoView can leave offset zero with Linux fonts. Centre the selector with room both ways.
var centredOffset = selectorTop - (wheelViewport.Viewport.Height - wheelSelector.Bounds.Height) / 2;
wheelViewport.Offset = new Vector(0, Math.Clamp(centredOffset, scrollRoom, maximumOffset - scrollRoom));
Dispatcher.UIThread.RunJobs(); wheelSelector.Focus();
foreach (var direction in new[] { 1, -1 })
{
using (panel.CaptureRenderedFrame()) { }
var selectorY = wheelSelector.TranslatePoint(default, wheelViewport)!.Value.Y;
Assert.InRange(selectorY, 0, wheelViewport.Viewport.Height - wheelSelector.Bounds.Height);
var beforeWheel = wheelViewport.Offset.Y;
Assert.InRange(beforeWheel, 1, maximumOffset - 1);
panel.MouseWheel(wheelSelector.TranslatePoint(new Point(20, 16), panel)!.Value, new Vector(0, direction));
Dispatcher.UIThread.RunJobs();
Assert.Equal(1, wheelSelector.SelectedIndex);
Assert.True(direction > 0 ? wheelViewport.Offset.Y < beforeWheel : wheelViewport.Offset.Y > beforeWheel,
$"Wheel {direction}: before={beforeWheel}, after={wheelViewport.Offset.Y}");
}
foreach (var segment in panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b.Classes.Contains("segment")))
{
segment.Focus(); var rangeBefore = model.Range; var providerBefore = model.ProviderFilter;
panel.MouseWheel(segment.TranslatePoint(new Point(8, 8), panel)!.Value, new Vector(0, -1));
Assert.Equal(rangeBefore, model.Range); Assert.Equal(providerBefore, model.ProviderFilter);
}
wheelViewport.Offset = default;
model.History = originalHistory;
model.Snapshot = originalSnapshot with { Providers = originalSnapshot.Providers.Select(p => p.Provider == Provider.Claude ? p with { Windows = [] } : p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
model.Snapshot = originalSnapshot; Dispatcher.UIThread.RunJobs();
var filters = panel.GetVisualDescendants().OfType<ToggleButton>().Where(b => b is not CheckBox).ToArray();
filters[4].IsChecked = true; filters[7].IsChecked = true;
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter); Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
filters[0].SelectedIndex = 1; filters[1].SelectedIndex = 0; filters[1].IsChecked = true; filters[5].IsChecked = true;
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png"); panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.png"); panel.Close(); foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
var stem = $"panel-{width}x{height}-{theme.ToString().ToLowerInvariant()}";
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(panel, stem + "-limits.png");
var selected = panel.GetVisualDescendants().OfType<ToggleButton>().First(b => b.Classes.Contains("segment") && b.IsChecked == true);
Assert.Equal(theme == ThemeVariant.Dark ? "#ff383835" : "#ffe1e0d9", selected.Background?.ToString());
Assert.Equal(Avalonia.Media.FontWeight.SemiBold, selected.FontWeight);
selected.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", selected.BorderBrush?.ToString());
var neutralCheck = panel.GetVisualDescendants().OfType<NeutralCheckBox>().Single();
neutralCheck.Focus(Avalonia.Input.NavigationMethod.Tab); Dispatcher.UIThread.RunJobs();
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", neutralCheck.BorderBrush?.ToString());
Assert.True(neutralCheck.MarkVisible);
var glyph = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "NeutralCheckGlyph");
Assert.Equal(theme == ThemeVariant.Dark ? "#fff0efec" : "#ff0b0b0b", glyph.Foreground?.ToString());
Assert.Equal(56, panel.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "PanelHeader").Bounds.Height);
if (width == 1500)
{
var sessionTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-session");
var weekTile = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var codexLimit = panel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(sessionTile.Bounds.Y, weekTile.Bounds.Y); Assert.Equal(weekTile.Bounds.Y, codexLimit.Bounds.Y);
Assert.True(sessionTile.Bounds.Height < weekTile.Bounds.Height);
}
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens"), ("windows", "Window charts"), ("breakdown", "Breakdown") })
{
var text = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
var position = text.TranslatePoint(default, viewport)!.Value;
viewport.Offset = new Vector(0, viewport.Offset.Y + position.Y - 16);
Save(panel, stem + "-" + name + ".png");
if (name == "breakdown")
{
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show all 110").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Save(panel, stem + "-breakdown-expanded.png");
Assert.Contains(panel.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Show top 8");
panel.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Show top 8").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
}
}
var prior = viewport.Offset;
model.Snapshot = model.Snapshot! with { MadeAt = clock.GetUtcNow() }; Dispatcher.UIThread.RunJobs();
Assert.Equal(prior, viewport.Offset);
}
var budgetModel = FakeData.BudgetModel();
var budgetSnapshot = budgetModel.Snapshot!;
var budgetClock = new FixedClock(budgetSnapshot.MadeAt);
var budgetPanel = new PanelWindow(budgetModel, () => { }, () => { }, () => { }, () => { }, budgetClock) { Width = 1280, Height = 1000 };
budgetPanel.Show(); Dispatcher.UIThread.RunJobs();
string[] Rows(Provider provider, string id = "week") => ((StackPanel)budgetPanel.GetVisualDescendants().OfType<Border>()
.Single(b => b.Name == $"LimitTile-{provider}-{id}").Child!).Children.Select(c => c.Name!).ToArray();
string[] longRows = ["Title", "Percent", "Used", "Pace", "Reset", "Forecast", "Recent", "Today", "Plan"];
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Limit week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Calendar week");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since Mon 00:00");
var tokenTiles = budgetPanel.GetVisualDescendants().OfType<StackPanel>().Where(p => p.Name?.StartsWith("TokenTile-", StringComparison.Ordinal) == true).ToArray();
Assert.All(tokenTiles, tile => Assert.Equal(tokenTiles[0].Bounds.Height, tile.Bounds.Height));
var limitTokens = tokenTiles.Single(t => t.Name == "TokenTile-Claude-Limit-week");
Assert.Contains(limitTokens.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "since " + TimeZoneInfo.ConvertTime(budgetSnapshot.Providers[0].WeekStart, budgetClock.LocalTimeZone).ToString("ddd HH:mm"));
Assert.Contains("Limit week", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
Assert.Contains("since ", Assert.IsType<DataTooltip>(ToolTip.GetTip(limitTokens)).Title);
foreach (var dayChart in budgetPanel.GetVisualDescendants().OfType<DailyLimitChart>())
{
Assert.Contains("from " + Display.Time(budgetSnapshot.Providers[0].WeekStart, budgetClock), dayChart.AxisLabels[0]);
Assert.Contains("reset " + Display.Time(budgetSnapshot.Providers[0].WeekStart.AddDays(7), budgetClock), dayChart.AxisLabels[^1]);
}
var partialDay = budgetModel.History.Details[0].Days!.Current[0];
var partialTip = DataTooltip.Day(partialDay);
Assert.Contains(partialTip.Rows, r => r.Label == "Share");
Assert.Contains(partialTip.Rows, r => r.Label == "Even pace");
Assert.Contains(partialTip.Rows, r => r.Label == "Budget");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
budgetPanel.RequestedThemeVariant = theme;
var viewport = budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(budgetPanel, $"budget-1280x1000-{theme}-limits.png");
foreach (var (name, target) in new[] { ("week", "Week use per day"), ("tokens", "Tokens") })
{
var heading = budgetPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == target);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(budgetPanel, $"budget-1280x1000-{theme}-{name}.png");
}
}
budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p => p.Provider == Provider.Codex
? p with { Windows = p.Windows.Select(w => w with { Window = w.Window with { SampleTime = budgetClock.GetUtcNow().AddMinutes(-15) } }).ToArray() }
: p).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
var staleWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-week");
var freshWeek = budgetPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Claude-week");
var staleUsed = staleWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used");
Assert.Equal("used · ⚠ sample 15 min old", staleUsed.Text);
Assert.Equal(12, staleUsed.FontSize); Assert.Equal("#ff898781", staleUsed.Foreground?.ToString());
Assert.Equal("used", freshWeek.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Name == "Used").Text);
budgetPanel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
SaveThemes(budgetPanel, "budget-stale-1280x1000");
budgetModel.History = new([], [], [], [], []);
budgetModel.Snapshot = budgetSnapshot with { Providers = budgetSnapshot.Providers.Select(p =>
{
var w = p.Windows[0].Window with { UsedPercent = 1, ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddDays(7).AddHours(-1) : null };
var shortWindow = w with { Id = "session", Label = "Session", Length = TimeSpan.FromHours(5),
ResetsAt = p.Provider == Provider.Claude ? budgetClock.GetUtcNow().AddHours(5).AddMinutes(-1) : null };
return p with { Windows = [new(w, Pace.Calculate(w, budgetClock.GetUtcNow())), new(shortWindow, Pace.Calculate(shortWindow, budgetClock.GetUtcNow()))] };
}).ToArray() };
Dispatcher.UIThread.RunJobs();
Assert.Equal(longRows, Rows(Provider.Claude)); Assert.Equal(longRows, Rows(Provider.Codex));
Assert.Equal(longRows.Take(7), Rows(Provider.Claude, "session"));
Assert.Equal(Rows(Provider.Claude, "session"), Rows(Provider.Codex, "session"));
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "No forecast: pace unknown");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Recent rate needs 3 h of samples");
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Recent rate from ", StringComparison.Ordinal) == true);
Assert.Contains(budgetPanel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Today · collecting a day baseline");
budgetPanel.Close();
var forecastModel = FakeData.ForecastModel();
var forecastClock = new FixedClock(forecastModel.Snapshot!.MadeAt);
var forecastPanel = new PanelWindow(forecastModel, () => { }, () => { }, () => { }, () => { }, forecastClock);
forecastPanel.Show(); Dispatcher.UIThread.RunJobs();
var aheadTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-primary");
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("100 % on ") == true);
Assert.Contains(aheadTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "⚠ ");
Assert.NotNull(forecastModel.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast);
var secondary = forecastModel.Snapshot!.Providers[0].Windows.Single(w => w.Window.Id == "secondary");
var forecastStart = Pace.ForecastStartsAt(secondary.Window)!.Value;
foreach (var (renderTime, waiting) in new[] { (forecastStart.AddTicks(-1), true), (forecastStart, false),
(forecastStart.AddTicks(1), false), (secondary.Window.ResetsAt!.Value, false), (secondary.Window.ResetsAt.Value.AddDays(365), false) })
{
forecastClock.UtcNow = renderTime;
forecastPanel.RenderModel(); Dispatcher.UIThread.RunJobs();
var tile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.Equal(waiting, tile.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.StartsWith("Forecast from ") == true));
var reset = Display.Projection(secondary.Window.ResetsAt!.Value, forecastClock);
Assert.Contains(tile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Resets in ") == true && t.Text.EndsWith(reset, StringComparison.Ordinal));
var burnUp = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().Last();
Assert.Equal(waiting, burnUp.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.StartsWith("Forecast from ") == true));
}
forecastClock.UtcNow = forecastModel.Snapshot.MadeAt;
forecastPanel.RenderModel(); Dispatcher.UIThread.RunJobs();
var waitingTile = forecastPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
var note = Assert.Single(waitingTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.StartsWith("Forecast from ") == true).Text;
Assert.Contains(forecastPanel.GetVisualDescendants().OfType<BurnUpChart>(), c => c.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text == note));
var aheadWindow = forecastModel.Snapshot!.Providers[0].Windows[0];
var earlyAlert = new PopupDecider().Observe(aheadWindow.Window, aheadWindow.Pace, new Settings());
Assert.NotNull(earlyAlert);
var earlyPopup = PopupWindow.Pace(earlyAlert, () => { }); earlyPopup.Show();
Assert.Contains(earlyPopup.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("⚠ 100 % on ") == true);
earlyPopup.Close();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
forecastPanel.Width = 1280; forecastPanel.Height = 900; forecastPanel.RequestedThemeVariant = theme;
var viewport = forecastPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(forecastPanel, $"forecast-1280x900-{theme}-limits.png");
var heading = forecastPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(forecastPanel, $"forecast-1280x900-{theme}-windows.png");
var charts = forecastPanel.GetVisualDescendants().OfType<BurnUpChart>().ToArray();
Assert.Equal(2, charts.Length);
Assert.True(DrawsForecast(charts[0])); Assert.False(DrawsForecast(charts[1]));
}
forecastPanel.Close();
var earlyModel = FakeData.EarlyResetModel();
var earlyPanel = new PanelWindow(earlyModel, () => { }, () => { }, () => { }, () => { }, new FixedClock(earlyModel.Snapshot!.MadeAt));
earlyPanel.Show();
var earlyTile = earlyPanel.GetVisualDescendants().OfType<Border>().Single(b => b.Name == "LimitTile-Codex-secondary");
Assert.DoesNotContain(earlyTile.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("at reset") == true || t.Text?.Contains("100 % on") == true || t.Text?.StartsWith("Last ") == true);
Assert.Null(Assert.Single(earlyModel.History.Limits).Forecast);
Assert.All(Assert.Single(earlyModel.History.Limits).Analysis!.Past, instance => Assert.True(instance.End <= earlyModel.Snapshot!.MadeAt));
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
earlyPanel.Width = width; earlyPanel.Height = height; earlyPanel.RequestedThemeVariant = theme;
var viewport = earlyPanel.GetVisualDescendants().OfType<ScrollViewer>().First(); viewport.Offset = default;
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-limits.png");
var heading = earlyPanel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Window charts");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(earlyPanel, $"panel-{width}x{height}-{theme}-early-windows.png");
}
earlyPanel.Close();
panel.Width = 1000; panel.Height = 900;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default; Save(panel, "panel-1000x900-light.png");
panel.Width = 1500; panel.Height = 1000;
model.History = originalHistory with { Details = originalHistory.Details.Select(d => d.Provider == Provider.Claude && d.Days is { } days
? d with { Days = days with { Current = days.Current.Select(day => day with { Used = null }).ToArray(), Today = null } } : d).ToArray() };
Dispatcher.UIThread.RunJobs(); Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().First(t => t.Text == "Week use per day");
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
Save(panel, $"panel-{width}x{height}-{theme}-collecting-days.png");
}
model.History = originalHistory;
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var weekData = originalHistory.Details.Single(d => d.Provider == Provider.Claude && d.Id == "week").Days!;
Assert.Contains(weekData.Current, d => d.Origin == UseOrigin.Estimated);
var future = DataTooltip.Day(new(clock.GetLocalNow().AddDays(1), clock.GetLocalNow().AddDays(2), null, 42, false, true));
Assert.DoesNotContain(future.Rows, row => row.Label == "Cumulative");
var types = new (string Name, DataTooltip Tip)[]
{
("day-estimated", DataTooltip.Day(weekData.Current.First(d => d.Origin == UseOrigin.Estimated))),
("day-measured", DataTooltip.Day(weekData.Current.Last(d => d.Used is not null && d.Origin == UseOrigin.Measured))),
("future-day", future),
("project", DataTooltip.Tokens("D:/Projects/Customer/Workspace/Project-with-a-long-name", new(100000000, 1900000000, 10000000, 53670717, 1234567, 2063670717))),
("tile", (DataTooltip)ToolTip.GetTip(panel.GetVisualDescendants().OfType<Border>().First(b => b.Name == "LimitTile-Claude-week"))!),
("tokens", DataTooltip.Tokens("Claude - Calendar week", originalSnapshot.Providers[0].Week)),
};
var limit = originalHistory.Limits.Single(l => l.Provider == Provider.Claude && l.Window!.Window.Id == "week");
CaptureChartTip("burnup", new BurnUpChart(limit, clock), new Point(240, 100));
CaptureChartTip("past-instance", new InstancePeaks(limit.Analysis!.Past, Provider.Claude, clock), new Point(30, 30));
CaptureChartTip("past-limit-reached", new InstancePeaks(limit.Analysis!.Past, Provider.Claude, clock), new Point(600, 30));
CaptureChartTip("hourly", new UsageChart { Values = originalHistory.Hourly }, new Point(60, 170));
CaptureChartTip("daily", new UsageChart { Values = originalHistory.Daily, Interval = TimeSpan.FromDays(1) }, new Point(60, 170));
CaptureChartTip("composition", new CompositionBar(originalSnapshot.Providers[0].Week, Provider.Claude, true) { Height = 8 }, new Point(100, 4));
void CaptureChartTip(string name, Control chartControl, Point hover)
{
var window = new Window { Width = 740, Height = 600, RequestedThemeVariant = theme }; Ui.Theme(window);
var content = Ui.Stack(Ui.Text(name, 20), chartControl); content.Margin = new Thickness(24); window.Content = content;
window.Show(); Dispatcher.UIThread.RunJobs(); using (window.CaptureRenderedFrame()) { }
window.MouseMove(chartControl.TranslatePoint(hover, window)!.Value);
var actualTip = Assert.IsType<DataTooltip>(ToolTip.GetTip(chartControl));
window.MouseMove(new Point(0, 0)); ToolTip.SetIsOpen(chartControl, false);
content.Children.Add(new DataTooltip(actualTip.Title, actualTip.Rows.ToArray()));
Save(window, $"tooltip-{name}-{theme}.png"); window.Close();
}
foreach (var (name, tip) in types)
{
var tooltipWindow = new Window { Width = 620, Height = 300, RequestedThemeVariant = theme };
Ui.Theme(tooltipWindow); tooltipWindow.Content = new Border { Child = tip, Padding = new Thickness(24), VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center };
tooltipWindow.Show(); Save(tooltipWindow, $"tooltip-{name}-{theme}.png"); tooltipWindow.Close();
}
}
model.Snapshot = FakeData.Snapshot(clock.GetUtcNow(), true);
Dispatcher.UIThread.RunJobs(); panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, "panel-unavailable.png");
foreach (var (width, height) in new[] { (1280, 900), (1500, 1000) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.Width = width; panel.Height = height; panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
Save(panel, $"panel-{width}x{height}-{theme}-unavailable.png");
}
model.Diagnostics = [new(clock.GetUtcNow(), Provider.Claude, "fixture", "Probe timed out. Last good sample retained.")];
Dispatcher.UIThread.RunJobs(); var expander = panel.GetVisualDescendants().OfType<Expander>().Single();
expander.BringIntoView(); Save(panel, "panel-diagnostics-collapsed.png");
expander.IsExpanded = true; panel.UpdateLayout();
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = new Vector(0, 100000);
Save(panel, "panel-diagnostics-expanded.png"); panel.Close();
string? folder = null; var quitCalls = 0; var saveCalls = 0;
var actions = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => { saveCalls++; return Task.CompletedTask; }, () => quitCalls++, path => folder = path);
actions.Show();
void ClickSettings(string text) => actions.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == text).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
ClickSettings("Open folder"); Assert.Equal(DataPaths.DataDirectory, folder);
ClickSettings("Quit FinalToken"); Assert.Equal(1, quitCalls);
ClickSettings("Cancel"); Assert.False(actions.IsVisible); Assert.Equal(0, saveCalls);
Settings? saved = null; Settings? saved = null;
var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" }; var initial = new Settings { StartWithOs = true, StreamDeckInstallMode = InstallMode.Automatic, DismissedPluginVersion = "0.9" };
var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }) { Height = 1600 }; var settings = new SettingsWindow(initial, new(PluginInstallState.Outdated, "1.0", "0.9"), value => { saved = value; return Task.CompletedTask; }, () => { });
settings.Show(); Save(settings, "settings.png"); settings.Show(); Save(settings, "settings.png");
var providerNames = settings.GetVisualDescendants().OfType<CheckBox>().Select(c => c.Name).ToArray();
Assert.Equal(providerNames.Length, providerNames.Distinct().Count());
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme;
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
viewport.Offset = default; Save(settings, $"settings-{theme}-general.png");
viewport.Offset = new Vector(0, 10000); Save(settings, $"settings-{theme}-providers.png");
}
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25; var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
settings.GetVisualDescendants().OfType<CheckBox>().First().IsChecked = false; settings.GetVisualDescendants().OfType<CheckBox>().Single(c => c.Content as string == "Ahead popups").IsChecked = false;
settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture"; settings.GetVisualDescendants().OfType<TextBox>().Single(t => t.Name == "ClaudeCliPath").Text = "claude-fixture";
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs); Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs);
@@ -62,14 +390,14 @@ public sealed class HeadlessTests
Assert.Null(cancellationFailure); Assert.Null(cancellationFailure);
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close(); Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
var opened = 0; var opened = 0;
var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++); var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, clock.GetUtcNow().AddHours(1)), () => opened++);
ahead.Show(); Save(ahead, "popup-ahead.png"); Assert.False(ahead.ShowActivated); ahead.Show(); SaveThemes(ahead, "popup-ahead"); Assert.False(ahead.ShowActivated);
ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible); ahead.MouseDown(new Point(100, 60), Avalonia.Input.MouseButton.Left); Assert.Equal(1, opened); Assert.False(ahead.IsVisible);
var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { }); var behind = PopupWindow.Pace(new(Provider.Codex, "primary", "Primary", PaceState.Behind, -18, null), () => { });
behind.Show(); Save(behind, "popup-behind.png"); behind.Close(); behind.Show(); SaveThemes(behind, "popup-behind"); behind.Close();
var installed = 0; var dismissed = 0; var installed = 0; var dismissed = 0;
var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++); var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++);
ask.Show(); Save(ask, "popup-streamdeck-ask.png"); ask.Show(); SaveThemes(ask, "popup-streamdeck-ask");
ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); ask.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Not now").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.Equal(0, installed); Assert.Equal(1, dismissed); Assert.Equal(0, installed); Assert.Equal(1, dismissed);
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++); var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
@@ -80,11 +408,11 @@ public sealed class HeadlessTests
var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { }); var first = PopupWindow.Pace(new(Provider.Claude, "a", "Session", PaceState.Ahead, 20, null), () => { });
var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { }); var second = PopupWindow.Pace(new(Provider.Codex, "b", "Week", PaceState.Behind, -20, null), () => { });
stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y); stack.Show(first); stack.Show(second); Assert.True(second.Position.Y < first.Position.Y);
var chart = new UsageChart { Values = [new(DateTimeOffset.UtcNow, "Exact", 123456)] }; var chart = new UsageChart { Values = [new(clock.GetUtcNow(), "Exact", 123456)] };
var chartWindow = new Window { Content = chart, Width = 400, Height = 180 }; var chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
chartWindow.Show(); chartWindow.Show();
using (chartWindow.CaptureRenderedFrame()) { } using (chartWindow.CaptureRenderedFrame()) { }
chartWindow.MouseMove(new Point(65, 80)); chartWindow.MouseMove(new Point(200, 100));
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close(); Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
var polishShots = shots; var polishShots = shots;
Directory.CreateDirectory(polishShots); Directory.CreateDirectory(polishShots);
@@ -102,11 +430,27 @@ public sealed class HeadlessTests
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light }; Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png"); dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
dailyWindow.MouseMove(new Point(90, 150)); dailyWindow.MouseMove(new Point(90, 150));
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close(); Assert.Contains(day.DateTime.ToString("d"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
popupClock.Fire(); Dispatcher.UIThread.RunJobs(); popupClock.Fire(); Dispatcher.UIThread.RunJobs();
Assert.False(first.IsVisible); Assert.False(second.IsVisible); Assert.False(first.IsVisible); Assert.False(second.IsVisible);
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed)); Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
ResetViews.Verify((window, name) => Save(window, name));
HiddenWindowViews.Verify((window, name) => Save(window, name));
completion.SetResult(); completion.SetResult();
void SaveThemes(Window window, string stem)
{
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{ window.RequestedThemeVariant = theme; Save(window, stem + "-" + theme + ".png"); }
}
bool DrawsForecast(BurnUpChart chart)
{
var drawing = new Avalonia.Media.DrawingGroup();
using (var context = drawing.Open()) chart.Render(context);
return HasForecast(drawing);
static bool HasForecast(Avalonia.Media.DrawingGroup group) => group.Children.Any(d =>
d is Avalonia.Media.GeometryDrawing { Pen.DashStyle.Dashes: { } dashes } && dashes.SequenceEqual(new double[] { 1, 3 }) ||
d is Avalonia.Media.DrawingGroup nested && HasForecast(nested));
}
void Save(Window window, string name, string? destination = null) void Save(Window window, string name, string? destination = null)
{ {
Dispatcher.UIThread.RunJobs(); Dispatcher.UIThread.RunJobs();
@@ -121,7 +465,7 @@ public sealed class HeadlessTests
thread.Start(); await completion.Task; thread.Join(); thread.Start(); await completion.Task; thread.Join();
} }
public sealed class TestApplication : Application public sealed class TestApplication : Application
{ public override void Initialize() => Styles.Add(new FluentTheme()); } { public override void Initialize() => Styles.Add(Ui.NeutralTheme()); }
private sealed class PopupClock : TimeProvider private sealed class PopupClock : TimeProvider
{ {
public List<PopupTimer> Timers { get; } = []; public List<PopupTimer> Timers { get; } = [];
@@ -0,0 +1,107 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using FinalToken.Core.StreamDeck;
using Xunit;
namespace FinalToken.App.Tests;
internal static class HiddenWindowViews
{
// Called by the shared headless fixture on its dedicated UI thread.
public static void Verify(Action<Window, string> save)
{
var clock = new FixedClock();
var now = clock.GetUtcNow();
var all = new LimitWindow(Provider.Claude, "week (all models)", "Current week (all models)", 60,
now.AddDays(3), TimeSpan.FromDays(7), now, "fixture");
var fable = all with { Id = "week (fable)", Label = "Current week (Fable)", UsedPercent = 30 };
var codex = all with { Provider = Provider.Codex, Id = "codex:primary", Label = "Week", UsedPercent = 40 };
var session = new HiddenLimitWindow("session", TimeSpan.FromHours(5), "Current session");
var snapshot = new Snapshot { MadeAt = now, RefreshInterval = TimeSpan.FromMinutes(1), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [View(all), View(fable)], new(Total: 100), null, new(Total: 500), now.AddDays(-4), all.Id),
new(Provider.Codex, ProviderStatus.Available, null, [View(codex)], new(Total: 200), null, new(Total: 800), now.AddDays(-4), codex.Id)] };
var initial = new Settings { Claude = new() { HiddenWindows = [HiddenLimitWindow.For(fable), session] },
Codex = new() { HiddenWindows = [HiddenLimitWindow.For(codex with { Id = "codex:secondary" })] } };
Settings? saved = null;
var settings = new SettingsWindow(initial, new(PluginInstallState.NoHostFound), value => { saved = value; return Task.CompletedTask; }, snapshot: snapshot);
settings.Show(); Dispatcher.UIThread.RunJobs();
Assert.NotNull(settings.Icon);
var choices = settings.GetVisualDescendants().OfType<NeutralCheckBox>().Where(c => c.Content is string text && text.StartsWith("Show ", StringComparison.Ordinal)).ToArray();
Assert.Equal(["Show Current week (all models)", "Show Current week (Fable)", "Show Current session", "Show Week"], choices.Select(c => c.Content as string));
Assert.True(choices[0].IsChecked); Assert.All(choices.Skip(1), c => Assert.False(c.IsChecked));
var viewport = settings.GetVisualDescendants().OfType<ScrollViewer>().First();
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
settings.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var title = settings.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Providers");
viewport.Offset = new Vector(0, viewport.Offset.Y + title.TranslatePoint(default, viewport)!.Value.Y - 16);
save(settings, $"hidden-settings-providers-{theme}.png");
}
choices[0].IsChecked = false; choices[1].IsChecked = true; choices[2].IsChecked = true;
settings.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Assert.NotNull(saved);
Assert.Equal(HiddenLimitWindow.For(all), Assert.Single(saved.Claude.HiddenWindows));
Assert.True(saved.Codex.IsHidden(codex));
Assert.Equal(2, initial.Claude.HiddenWindows.Count); // Cancel/save must not mutate the caller's value.
var emptySettings = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => Task.CompletedTask);
emptySettings.Show(); Dispatcher.UIThread.RunJobs();
Assert.Equal(2, emptySettings.GetVisualDescendants().OfType<TextBlock>().Count(t => t.Text == "No known limit windows"));
emptySettings.Close();
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-hidden", Guid.NewGuid().ToString("N")), new(), clock);
foreach (var window in new[] { all, fable, codex })
store.AddLimits([window with { SampleTime = now.AddHours(-30), UsedPercent = 10 }, window]);
var model = new PanelViewModel { Snapshot = snapshot,
History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Show(); Dispatcher.UIThread.RunJobs();
Assert.NotNull(panel.Icon); Assert.Equal(3, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ComboBox>().Count());
// Select Fable in both selectors before hiding it, exercising stale selection/history retirement.
foreach (var selector in panel.GetVisualDescendants().OfType<ComboBox>()) selector.SelectedIndex = 1;
var hidden = new Settings { Claude = initial.Claude };
model.ApplySnapshot(snapshot, hidden); Dispatcher.UIThread.RunJobs();
VerifyNoFable(); // Applies at once, even while the replacement history is pending.
model.History = PanelViewModel.QueryHistory(store, model.Snapshot!, HistoryRange.Days7, null, now);
Dispatcher.UIThread.RunJobs(); VerifyNoFable();
Assert.Equal(2, model.History.Limits.Count); Assert.Equal(2, model.History.Resets.Count); Assert.Equal(2, model.History.Details.Count);
Assert.Equal(snapshot.Providers[0].Week, model.Snapshot!.Providers[0].Week);
Assert.Equal(snapshot.Providers[0].WeekStart, model.Snapshot.Providers[0].WeekStart);
Assert.Equal(all.Id, model.Snapshot.Providers[0].WeekWindow);
Assert.Equal(2, snapshot.Providers[0].Windows.Count);
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.RequestedThemeVariant = theme;
panel.GetVisualDescendants().OfType<ScrollViewer>().First().Offset = default;
save(panel, $"hidden-panel-top-{theme}.png");
}
model.ApplySnapshot(snapshot, hidden with { Claude = new() { HiddenWindows = [HiddenLimitWindow.For(all), HiddenLimitWindow.For(fable)] } });
Dispatcher.UIThread.RunJobs();
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<Border>(), b => b.Name?.StartsWith("LimitTile-Claude-", StringComparison.Ordinal) == true);
Assert.Single(panel.GetVisualDescendants().OfType<BurnUpChart>());
Assert.Single(panel.GetVisualDescendants().OfType<DailyLimitChart>());
Assert.Single(panel.GetVisualDescendants().OfType<ResetCard>());
model.ApplySnapshot(snapshot, new());
model.History = PanelViewModel.QueryHistory(store, model.Snapshot!, HistoryRange.Days7, null, now);
Dispatcher.UIThread.RunJobs();
Assert.Equal(3, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ComboBox>().Count());
panel.Close();
WindowSnapshot View(LimitWindow w) => new(w, Pace.Calculate(w, now));
void VerifyNoFable()
{
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text?.Contains("Fable", StringComparison.Ordinal) == true);
Assert.DoesNotContain(panel.GetVisualDescendants().OfType<Border>(), b => b.Name == "LimitTile-Claude-week (fable)");
Assert.Contains(panel.GetVisualDescendants().OfType<Border>(), b => b.Name == "LimitTile-Claude-week (all models)");
Assert.Empty(panel.GetVisualDescendants().OfType<ComboBox>());
Assert.Equal(2, panel.GetVisualDescendants().OfType<BurnUpChart>().Count());
Assert.Equal(2, panel.GetVisualDescendants().OfType<ResetCard>().Count());
}
}
}
+171
View File
@@ -0,0 +1,171 @@
using System.Globalization;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
public sealed class ResetTests
{
[Fact] public void HistoryQueriesOnlyLongWindowsAndFollowsProviderAndRange()
{
var fixture = ResetFixture.Create();
var all = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now);
Assert.Equal(3, all.Resets.Count);
Assert.All(all.Resets, r => Assert.True(r.Window.Length > TimeSpan.FromDays(1)));
var filtered = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
Assert.Equal(2, filtered.Resets.Count); Assert.All(filtered.Resets, r => Assert.Equal(Provider.Codex, r.Window.Provider));
var recent = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.Hours24, Provider.Codex, fixture.Now);
var week = recent.Resets.Single(r => r.Window.Id == "codex:primary");
Assert.True(week.Instances.Count < filtered.Resets[0].Instances.Count);
Assert.Contains(week.Instances, r => r.Start < fixture.Now.AddHours(-24) && r.End > fixture.Now.AddHours(-24));
Assert.Equal(10, filtered.Resets[0].Instances.Count);
}
[Fact] public void BurnUpQueriesReadTheSeriesAcrossCodexSlotsAndExcludeShortWindows()
{
var fixture = ResetFixture.Create();
var history = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, Provider.Codex, fixture.Now);
var week = history.Limits.Single(l => l.Window!.Window.Id == "codex:primary" && l.Window.Window.Length > TimeSpan.FromDays(1));
Assert.DoesNotContain(week.Values, v => v.Value == 99);
Assert.True(week.Values.Count > 10);
Assert.Equal(8, week.Analysis!.Past.Count);
}
[Theory]
[InlineData("de-DE", "≈ 4,5 limits", "≈ 94,1 %")]
[InlineData("en-US", "≈ 4.5 limits", "≈ 94.1 %")]
public void ResetFiguresFollowTheUsersCultureExceptUsd(string culture, string limits, string percent)
{
var previous = CultureInfo.CurrentCulture;
try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);
Assert.Equal("≈ $1,234", Display.Money(1234)); Assert.Equal("≈ $99.25", Display.Money(99.25m));
Assert.Equal("Unpriced", Display.Money(null)); Assert.Equal(limits, Display.Limits(450));
Assert.Equal(percent, Display.ResetPercent(94.1, UseOrigin.Estimated));
Assert.Equal(percent[2..], Display.ResetPercent(94.1, UseOrigin.Measured));
}
finally { CultureInfo.CurrentCulture = previous; }
}
[Fact] public void ResetDurationsCannotWrapInsideTheFigure()
{
Assert.Equal("0\u00a0min", Display.ResetDuration(TimeSpan.Zero));
Assert.Equal("39\u00a0d\u00a00\u00a0h", Display.ResetDuration(TimeSpan.FromDays(39)));
Assert.Equal("≈\u00a015,1\u00a0M\u00a0tokens", Display.ResetFigure("≈ 15,1 M tokens"));
}
[Fact] public void OverlappingSkippedSpansGetSeparateLanesInTimeOrder()
{
var fixture = ResetFixture.Overlapping();
var history = fixture.History.Resets[0];
var layout = ResetTimeline.CalculateLayout(history, fixture.Now);
Assert.Equal(5, history.Totals.Early);
Assert.True(history.Instances.Max(r => r.Start) - history.Instances.Min(r => r.Start) < TimeSpan.FromDays(10));
Assert.Equal(5, layout.LaneCount);
Assert.Equal([0, 1, 2, 3, 4], layout.Skipped.Select(s => s.Lane));
Assert.Equal(history.Instances.Where(r => r.Early).OrderBy(r => r.End), layout.Skipped.Select(s => s.Instance));
}
[Fact] public void SkippedSpansReuseTheFirstLaneAsSoonAsItIsFree()
{
var fixture = ResetFixture.Create();
var layout = ResetTimeline.CalculateLayout(fixture.History.Resets[0], fixture.Now);
Assert.Equal(4, layout.LaneCount);
Assert.Equal([0, 1, 0, 1, 2, 3, 0], layout.Skipped.Select(s => s.Lane));
Assert.Equal(layout.Skipped[2].Instance.Reset, layout.Skipped[^1].Instance.End);
foreach (var lane in layout.Skipped.GroupBy(s => s.Lane))
{
var rows = lane.Select(s => s.Instance).ToArray();
for (var i = 1; i < rows.Length; i++) Assert.True(rows[i - 1].Reset <= rows[i].End);
}
}
[Fact] public void TimelineEndsAtNowOrTheLastEarlyNominalResetAndExcludesTheRunningReset()
{
var running = ResetFixture.RunningOnly();
var history = running.History.Resets[0];
var layout = ResetTimeline.CalculateLayout(history, running.Now);
Assert.Equal(history.Instances[0].Start, layout.From);
Assert.Equal(running.Now, layout.To); Assert.Empty(layout.Skipped);
Assert.True(layout.To < history.Instances[0].Reset);
var early = ResetFixture.Overlapping();
history = early.History.Resets[0];
layout = ResetTimeline.CalculateLayout(history, early.Now);
Assert.Equal(history.Instances.Min(r => r.Start), layout.From);
Assert.Equal(history.Instances.Where(r => r.Early).Max(r => r.Reset), layout.To);
Assert.True(layout.To > early.Now); Assert.True(layout.To < history.Instances[0].Reset);
var later = early.Now.AddDays(30);
Assert.Equal(later, ResetTimeline.CalculateLayout(history, later).To);
var onTime = ResetFixture.OnTimeOnly();
history = onTime.History.Resets[0];
history = history with { Instances = history.Instances.Where(r => !r.Running).ToArray() };
Assert.Equal(onTime.Now, ResetTimeline.CalculateLayout(history, onTime.Now).To);
}
[Fact] public void EveryInstanceColumnSortsByItsUnderlyingValue()
{
var fixture = ResetFixture.Create();
var rows = fixture.History.Resets[0].Instances;
Assert.Equal(rows.OrderBy(r => r.Start), ResetTable.SortRows(rows, ResetColumn.Start, false));
Assert.Equal(rows.Max(r => r.Final.Used), ResetTable.SortRows(rows, ResetColumn.Final, true)[0].Final.Used);
Assert.Equal(rows.Max(r => r.Skipped), ResetTable.SortRows(rows, ResetColumn.Reset, true)[0].Skipped);
Assert.Equal(rows.Max(r => r.Duration), ResetTable.SortRows(rows, ResetColumn.Lasted, true)[0].Duration);
foreach (var column in Enum.GetValues<ResetColumn>())
{
var ascending = ResetTable.SortRows(rows, column, false); var descending = ResetTable.SortRows(rows, column, true);
Assert.Equal(rows.Count, ascending.Count); Assert.Equal(rows.Count, descending.Count);
}
}
}
internal sealed record ResetFixture(HistoryStore Store, Snapshot Snapshot, DateTimeOffset Now, HistoryView History)
{
public static ResetFixture Create()
=> Create([7, 1, 2, 7, 1, 2, 1, 1, 2]);
public static ResetFixture RunningOnly() => Create([]);
public static ResetFixture OnTimeOnly() => Create([7, 7]);
public static ResetFixture Overlapping() => Create([1, 1, 1, 1, 1]);
public static ResetFixture ManyModels()
{
var fixture = OnTimeOnly();
var start = fixture.History.Resets[0].Instances[1].Start;
string[] models = ["gpt-6-sol", "gpt-6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna", "gpt-5.4-mini"];
for (var i = 0; i < models.Length; i++)
{
var count = 2_000_123 - i * 200_001;
fixture.Store.Add(new(Provider.Codex, start.AddHours(2), models[i], "Fixture", new(Input: count, Total: count), "extra" + i));
}
return fixture with { History = PanelViewModel.QueryHistory(fixture.Store, fixture.Snapshot, HistoryRange.All, null, fixture.Now) };
}
private static ResetFixture Create(int[] durations)
{
var start = new DateTimeOffset(2026, 9, 12, 6, 0, 0, TimeSpan.Zero);
var now = start.AddDays(durations.Sum()).AddHours(12);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-resets", Guid.NewGuid().ToString("N")), new(), new FixedClock(now));
var currentStart = start; LimitWindow current = null!;
for (var i = 0; i <= durations.Length; i++)
{
var used = i == 2 ? 100 : i == 4 ? 4 : 20 + i * 7;
current = new(Provider.Codex, i < 4 ? "codex:secondary" : "codex:primary", "Week", used,
currentStart.AddDays(7), TimeSpan.FromDays(7), currentStart.AddHours(6), "fixture");
store.AddLimits([current with { SampleTime = currentStart.AddHours(1), UsedPercent = used / 2.0 }, current]);
store.AddLimits([current with { Id = "codex_bengalfox:secondary", Label = "Week (Bengalfox)", UsedPercent = 0 }]);
store.Add(new(Provider.Codex, currentStart.AddMinutes(30), "gpt-6.1-sol", "Fixture", new(10_000_000, 4_000_000, 0, 2_000_000, 300_000, 12_000_000), "a" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "gpt-6-astra", "Fixture", new(1_000_000, 200_000, 0, 2_000_000, 300_000, 3_000_000), "b" + i));
store.Add(new(Provider.Codex, currentStart.AddHours(2), "codex-auto-review", "Fixture", new(Input: 100_000, Total: 100_000), "c" + i));
if (i < durations.Length) currentStart = currentStart.AddDays(durations[i]);
}
var shortWindow = current with { Id = "codex:primary", Length = TimeSpan.FromHours(5), ResetsAt = now.AddHours(2), UsedPercent = 99, SampleTime = now.AddMinutes(-1), Label = "Session" };
store.AddLimits([shortWindow]);
var claude = current with { Provider = Provider.Claude, Id = "week", Label = "Week (all models)" };
var alternate = current with { Id = "codex_bengalfox:primary", Label = "Week (Bengalfox)", UsedPercent = 0 };
var snapshot = FakeData.Snapshot(now) with { Providers =
[new(Provider.Codex, ProviderStatus.Available, null, [new(current, Pace.Calculate(current, now)), new(alternate, Pace.Calculate(alternate, now)),
new(shortWindow, Pace.Calculate(shortWindow, now))], new(), new(), new()),
new(Provider.Claude, ProviderStatus.Available, null, [new(claude, Pace.Calculate(claude, now))], new(), null, new())] };
return new(store, snapshot, now, PanelViewModel.QueryHistory(store, snapshot, HistoryRange.All, null, now));
}
}
+214
View File
@@ -0,0 +1,214 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Interactivity;
using Avalonia.Styling;
using Avalonia.Threading;
using Avalonia.VisualTree;
using FinalToken.Core;
using Xunit;
namespace FinalToken.App.Tests;
internal static class ResetViews
{
public static void Verify(Action<Window, string> save)
{
VerifyEveryModelsTokensAndValue(save);
VerifyScenarios(save);
var fixture = ResetFixture.Create();
var clock = new FixedClock(fixture.Now);
var model = new PanelViewModel { Snapshot = fixture.Snapshot, History = fixture.History, Range = HistoryRange.All };
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }, clock);
panel.Show(); Dispatcher.UIThread.RunJobs();
var headings = panel.GetVisualDescendants().OfType<TextBlock>().Where(t => t.FontSize == 20).Select(t => t.Text).ToArray();
Assert.True(Array.IndexOf(headings, "Window charts") < Array.IndexOf(headings, "Resets"));
Assert.True(Array.IndexOf(headings, "Resets") < Array.IndexOf(headings, "Breakdown"));
var selector = panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector");
selector.SelectedIndex = 1;
Assert.Contains(panel.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Codex · Week (Bengalfox)");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now.AddMinutes(-1) }; Dispatcher.UIThread.RunJobs();
Assert.Equal(1, panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex);
panel.GetVisualDescendants().OfType<ComboBox>().Single(c => c.Name == "ResetWindowSelector").SelectedIndex = 0;
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
var card = panel.GetVisualDescendants().OfType<ResetCard>().First();
var table = card.GetVisualDescendants().OfType<ResetTable>().Single();
Grid Rows()
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
return table.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows");
}
void Click(string name)
{
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
table.GetVisualDescendants().OfType<Button>().Single(b => b.Name == name).RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
Dispatcher.UIThread.RunJobs();
using (panel.CaptureRenderedFrame()) { }
}
Assert.Equal(9, Rows().RowDefinitions.Count); // Header plus eight rows.
var cells = Rows().Children.OfType<TextBlock>().ToArray();
Assert.All(cells, text => Assert.IsType<DataTooltip>(ToolTip.GetTip(text)));
Assert.Contains(cells, t => t.Text == "Running");
Assert.Contains(cells, t => t.Text?.StartsWith("Early by ", StringComparison.Ordinal) == true);
Assert.Contains(cells, t => t.Text?.Contains("100 %", StringComparison.Ordinal) == true);
Click("ResetSortFinal");
Assert.StartsWith("≈ 100 %", Rows().Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 1 && Grid.GetColumn(t) == 4).Text);
Click("ResetExpand");
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(Rows().Children.OfType<TextBlock>(), t => t.Text == "On time");
model.Snapshot = model.Snapshot with { MadeAt = fixture.Now }; Dispatcher.UIThread.RunJobs();
table = panel.GetVisualDescendants().OfType<ResetCard>().First().GetVisualDescendants().OfType<ResetTable>().Single();
Assert.Equal(11, Rows().RowDefinitions.Count);
Assert.Contains(table.GetVisualDescendants().OfType<Button>(), b => b.Content as string == "Final (peak) ↓");
Click("ResetExpand");
Click("ResetSortStart");
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
panel.RequestedThemeVariant = theme; Dispatcher.UIThread.RunJobs();
var viewport = panel.GetVisualDescendants().OfType<ScrollViewer>().First();
var heading = panel.GetVisualDescendants().OfType<TextBlock>().Single(t => t.Text == "Resets" && t.FontSize == 20);
viewport.Offset = new Vector(0, viewport.Offset.Y + heading.TranslatePoint(default, viewport)!.Value.Y - 16);
save(panel, $"resets-panel-{theme}.png");
}
panel.Close();
var history = fixture.History.Resets[0];
foreach (var width in new[] { 1280, 1500 })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var content = new ResetCard(history, new(ResetColumn.Start), clock);
var window = new Window { Width = width, Height = 1030, Content = new Border { Padding = new Thickness(24),
Child = Ui.Stack(Ui.Text("Resets", 20), Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), content))) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show();
save(window, $"resets-{width}-{theme}.png");
var timeline = content.GetVisualDescendants().OfType<ResetTimeline>().Single();
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width / 2, 80), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
var histogram = content.GetVisualDescendants().OfType<ResetHistogram>().First();
window.MouseMove(histogram.TranslatePoint(new Point(40, 40), window)!.Value);
Assert.IsType<DataTooltip>(ToolTip.GetTip(histogram));
var tableTip = content.GetVisualDescendants().OfType<ResetTable>().Single().GetVisualDescendants().OfType<TextBlock>()
.Select(t => ToolTip.GetTip(t)).OfType<DataTooltip>().First();
Assert.Contains(tableTip.Rows, r => r.Label == "Unpriced tokens");
Assert.Contains(tableTip.Rows, r => r.Label == "Tokens per percent");
Assert.Contains(tableTip.Rows, r => r.Label == "Estimated figures");
var oldest = history.Instances[^1];
Assert.False(oldest.Early); Assert.False(oldest.Running);
window.Close();
}
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var tip = DataTooltip.Reset(history.Instances[1], clock);
var window = new Window { Width = 580, Height = 1120, Content = new Border { Child = tip, Padding = new Thickness(16) }, RequestedThemeVariant = theme };
Ui.Theme(window); window.Show(); save(window, $"resets-tooltip-{theme}.png"); window.Close();
}
}
private static void VerifyEveryModelsTokensAndValue(Action<Window, string> save)
{
var fixture = ResetFixture.ManyModels();
var history = fixture.History.Resets[0];
var row = history.Instances[1];
Assert.False(row.Running); Assert.Equal(9, row.Models.Count);
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
var window = new Window { Width = 1280, Height = 1030, RequestedThemeVariant = theme,
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
var cell = card.GetVisualDescendants().OfType<Grid>().Single(g => g.Name == "ResetRows")
.Children.OfType<TextBlock>().Single(t => Grid.GetRow(t) == 2 && Grid.GetColumn(t) == 0);
var tip = Assert.IsType<DataTooltip>(ToolTip.GetTip(cell));
foreach (var model in row.Models)
{
var detail = Assert.Single(tip.Rows, r => r.Label == model.Model);
Assert.Equal(DataTooltip.Count(model.Tokens.Total) + " · " + Display.Money(model.ApiValue), detail.Value);
}
Assert.Equal(row.Models.Select(m => m.Model), tip.Rows.Where(r => row.Models.Any(m => m.Model == r.Label)).Select(r => r.Label));
Assert.DoesNotContain(tip.Rows, r => r.Label == "Other models");
var pointer = cell.TranslatePoint(new Point(12, cell.Bounds.Height / 2), window)!.Value;
window.MouseMove(pointer); ToolTip.SetIsOpen(cell, true); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
Assert.True(ToolTip.GetIsOpen(cell)); Assert.True(tip.Bounds.Width > 320);
var bounds = new PixelRect(tip.PointToScreen(default), PixelSize.FromSize(tip.Bounds.Size, 1));
Assert.False(bounds.Contains(window.PointToScreen(pointer)));
Assert.True(window.Screens.ScreenFromWindow(window)!.WorkingArea.Contains(bounds), $"tooltip {bounds}");
save(window, $"resets-many-models-hover-{theme}.png");
ToolTip.SetIsOpen(cell, false); window.Close();
}
}
private static void VerifyScenarios(Action<Window, string> save)
{
foreach (var (name, fixture) in new[] { ("running-only", ResetFixture.RunningOnly()),
("on-time", ResetFixture.OnTimeOnly()), ("overlapping", ResetFixture.Overlapping()) })
foreach (var theme in new[] { ThemeVariant.Dark, ThemeVariant.Light })
{
var history = fixture.History.Resets[0];
var card = new ResetCard(history, new(ResetColumn.Start), new FixedClock(fixture.Now));
var window = new Window { Width = 1280, Height = 950, RequestedThemeVariant = theme,
Content = new Border { Padding = new Thickness(24), Child = Ui.Card(Ui.Stack(Ui.Text("Codex · Week", 15), card)) } };
Ui.Theme(window); window.Show(); Dispatcher.UIThread.RunJobs();
using (window.CaptureRenderedFrame()) { }
save(window, $"resets-{name}-{theme}.png");
TextBlock[] TileBlocks(string label) => card.GetVisualDescendants().OfType<StackPanel>()
.Select(s => s.Children.OfType<TextBlock>().ToArray())
.Single(blocks => blocks.Length == 3 && blocks[0].Text == label);
string[] Tile(string label) => TileBlocks(label).Select(t => t.Text!).ToArray();
Assert.Equal(history.Totals.Finished.ToString(), Tile("Resets")[1]);
var caption = history.Totals.Finished == 0 ? "none yet" : history.Totals.Early + "\u00a0early";
Assert.Equal(caption + " · 1\u00a0running", Tile("Resets")[2]);
var texts = card.GetVisualDescendants().OfType<TextBlock>().Select(t => t.Text).ToArray();
Assert.Contains("early resets " + history.Totals.Early + " of " + history.Totals.Finished,
texts.Single(t => t?.StartsWith("Median instance ", StringComparison.Ordinal) == true || t?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true));
if (history.Totals.Finished == 0)
{
Assert.Equal(["Unused", "—", "no finished instance"], Tile("Unused"));
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Unused")[1].Foreground?.ToString());
Assert.Contains(texts, text => text?.StartsWith("No finished instance yet", StringComparison.Ordinal) == true);
}
if (history.Totals.Early == 0)
{
Assert.Equal(["Gift", "—", "no early reset"], Tile("Gift"));
Assert.Equal(Ui.Colour("Muted", theme == ThemeVariant.Dark).ToString(), TileBlocks("Gift")[1].Foreground?.ToString());
Assert.Contains("No early resets in this range", texts);
Assert.Empty(card.GetVisualDescendants().OfType<ResetHistogram>());
}
else
{
Assert.Equal(2, card.GetVisualDescendants().OfType<ResetHistogram>().Count());
Assert.Contains(Display.ResetDuration(history.Totals.Skipped) + " skipped", Tile("Gift")[2]);
Assert.DoesNotContain("≈ ", Tile("Gift")[2]);
var timeline = card.GetVisualDescendants().OfType<ResetTimeline>().Single();
var layout = ResetTimeline.CalculateLayout(history, fixture.Now);
foreach (var skipped in layout.Skipped)
{
ToolTip.SetIsOpen(timeline, false);
window.MouseMove(new Point(4, 4)); Dispatcher.UIThread.RunJobs();
var mid = skipped.Instance.End + skipped.Instance.Skipped / 2;
var x = 42 + (mid - layout.From).TotalSeconds / (layout.To - layout.From).TotalSeconds * (timeline.Bounds.Width - 58);
var pointer = timeline.TranslatePoint(new Point(x, 181 + skipped.Lane * 10), window)!.Value;
window.MouseMove(pointer);
Assert.True(ToolTip.GetTip(timeline) is DataTooltip, $"{name} {theme}, lane {skipped.Lane}, timeline {timeline.Bounds}");
var tooltip = Assert.IsType<DataTooltip>(ToolTip.GetTip(timeline));
// The tall tooltip opens beside the pointer; over it, it would take the pointer from the timeline.
Assert.True(ToolTip.GetIsOpen(timeline));
Assert.True(tooltip.Bounds.Width > 320, $"tooltip width {tooltip.Bounds.Width}");
var tipBounds = new PixelRect(tooltip.PointToScreen(default), PixelSize.FromSize(tooltip.Bounds.Size, 1));
Assert.False(tipBounds.Contains(window.PointToScreen(pointer)), $"{name} {theme}, lane {skipped.Lane}, tooltip {tipBounds}, pointer {window.PointToScreen(pointer)}, placement {ToolTip.GetPlacement(timeline)}");
if (skipped == layout.Skipped[0] || skipped == layout.Skipped[^1]) save(window, $"resets-{name}-hover-lane{skipped.Lane}-{theme}.png");
Assert.Contains(tooltip.Rows, r => r.Label == "End" && r.Value == Display.Projection(skipped.Instance.End, new FixedClock(fixture.Now)));
}
ToolTip.SetIsOpen(timeline, false);
window.MouseMove(timeline.TranslatePoint(new Point(timeline.Bounds.Width - 10, 80), window)!.Value);
Assert.Null(ToolTip.GetTip(timeline));
window.MouseMove(new Point(4, 4));
}
window.Close();
}
}
}
+177 -12
View File
@@ -5,6 +5,70 @@ namespace FinalToken.App.Tests;
public sealed class ViewModelTests public sealed class ViewModelTests
{ {
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void HistoryForecastsUseTheSnapshotsConfiguredPace(double threshold, bool eligible)
{
var model = FakeData.ForecastModel(threshold, beforeStart: true);
Assert.Equal(eligible, model.History.Limits.Single(l => l.Window!.Window.Id == "primary").Forecast is not null);
Assert.Equal(eligible, model.History.Details.Single(d => d.Id == "primary").Recent is not null);
}
[Fact] public async Task RefreshIgnoresConcurrentRequestsAndClearsGuardAfterFailure()
{
var model = new PanelViewModel(); var completion = new TaskCompletionSource(); var calls = 0;
var first = model.RefreshAsync(() => { calls++; return completion.Task; });
Assert.True(model.Refreshing);
await model.RefreshAsync(() => { calls++; return Task.CompletedTask; });
Assert.Equal(1, calls); completion.SetResult(); await first; Assert.False(model.Refreshing);
await Assert.ThrowsAsync<IOException>(() => model.RefreshAsync(() => throw new IOException("fixture")));
Assert.False(model.Refreshing);
}
[Theory]
[InlineData(-1, "now")]
[InlineData(0, "now")]
[InlineData(59, "1 min")]
[InlineData(3600, "1 h 0 min")]
[InlineData(90061, "1 d 1 h")]
public void DurationUsesDaysHoursAndRoundedMinutes(int seconds, string expected)
=> Assert.Equal(expected, Display.Duration(TimeSpan.FromSeconds(seconds)));
[Theory]
[InlineData(PaceState.Ahead, "\u25b2 Ahead")]
[InlineData(PaceState.Behind, "\u25bc Behind")]
[InlineData(PaceState.OnTrack, "\u2713 On track")]
[InlineData(PaceState.Unknown, "? Pace unknown")]
public void StatusChipsAlwaysNameTheirState(PaceState state, string expected) => Assert.Equal(expected, Display.State(state));
[Fact] public void BreakdownSortingUsesTheSelectedNumericColumn()
{
BreakdownRow[] rows = [new("a", new(Input: 30, Output: 2, Total: 32), .4), new("b", new(Input: 10, Output: 40, Total: 50), .6)];
Assert.Equal("b", BreakdownTable.SortRows(rows, BreakdownColumn.Total, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Input, true).First().Name);
Assert.Equal("a", BreakdownTable.SortRows(rows, BreakdownColumn.Output, false).First().Name);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void ResetDriftKeepsChartContinuousAndRealResetAddsGap(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var window = new LimitWindow(Provider.Claude, "week", "Week", 60, now.AddDays(4), TimeSpan.FromDays(7), now.AddMinutes(-1), "fixture");
var first = window with { SampleTime = CalendarDays.Start(now).AddHours(-1), UsedPercent = 40, ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) };
store.AddLimits([first]);
store.AddLimits([window with { SampleTime = now.AddHours(-3), UsedPercent = 50, ResetsAt = window.ResetsAt!.Value.AddMinutes(-minutes) }]);
store.AddLimits([window]);
Snapshot SnapshotFor(LimitWindow w, DateTimeOffset time) => new() { MadeAt = time, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Claude, ProviderStatus.Available, null, [new(w, Pace.Calculate(w, time))], new(), null, new())] };
var view = PanelViewModel.QueryHistory(store, SnapshotFor(window, now), HistoryRange.All, null, now);
Assert.All(Assert.Single(view.Limits).Values, v => Assert.False(v.BreakBefore));
var detail = Assert.Single(view.Details);
Assert.Equal(first.SampleTime, detail.Since); Assert.Equal(20, detail.Days!.Today); Assert.NotNull(detail.Recent);
var next = window with { ResetsAt = window.ResetsAt!.Value.AddDays(7), SampleTime = now.AddDays(7).AddMinutes(-1), UsedPercent = 5 };
store.AddLimits([next]);
var nextView = PanelViewModel.QueryHistory(store, SnapshotFor(next, now.AddDays(7)), HistoryRange.All, null, now.AddDays(7));
Assert.Equal(1, Assert.Single(nextView.Limits).Values.Count(v => v.BreakBefore));
Assert.True(Assert.Single(nextView.Limits).Values[^1].BreakBefore);
}
[Theory] [Theory]
[InlineData(HistoryRange.Hours24, 1)] [InlineData(HistoryRange.Hours24, 1)]
[InlineData(HistoryRange.Days7, 7)] [InlineData(HistoryRange.Days7, 7)]
@@ -44,7 +108,7 @@ public sealed class ViewModelTests
[Fact] public void SelectedProviderDailySeriesRespectsPartialDays() [Fact] public void SelectedProviderDailySeriesRespectsPartialDays()
{ {
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog()); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
store.Add(new(Provider.Claude, now.AddHours(-26), "outside", "p", new(Total: 300), "outside")); store.Add(new(Provider.Claude, now.AddHours(-26), "outside", "p", new(Total: 300), "outside"));
store.Add(new(Provider.Claude, now.AddHours(-22), "inside", "p", new(Total: 100), "inside")); store.Add(new(Provider.Claude, now.AddHours(-22), "inside", "p", new(Total: 100), "inside"));
store.Add(new(Provider.Claude, now.AddHours(-3), "inside", "p", new(Total: 50), "today")); store.Add(new(Provider.Claude, now.AddHours(-3), "inside", "p", new(Total: 50), "today"));
@@ -55,6 +119,43 @@ public sealed class ViewModelTests
} }
[Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes() [Fact] public void DesktopEntryQuotesExecutableAndEscapesFieldCodes()
{ var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); } { var text = OsStartup.DesktopEntry("/opt/Final Token/100%/app"); Assert.Contains("Exec=\"/opt/Final Token/100%%/app\"", text); Assert.Contains("Terminal=false", text); }
[Fact] public void BreakdownQueryReturnsEveryRowAndItsShareWithoutPrebuildingOther()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
for (var i = 0; i < 110; i++) store.Add(new(Provider.Claude, now.AddHours(-1), "model", $"project-{i}", new(Total: i + 1), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal(110, view.Projects.Count); Assert.Equal("project-109", view.Projects[0].Name);
Assert.Equal("project-0", view.Projects[^1].Name); Assert.Equal(6105, view.Projects.Sum(r => r.Counts.Total));
Assert.Equal(1, view.Projects.Sum(r => r.Share), 8);
}
[Fact] public void FilteredModelSeriesUseSixAlphabeticSlotsAndOther()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
for (var i = 9; i >= 0; i--) store.Add(new(Provider.Claude, now.AddHours(-1), $"model-{i}", "p", new(CacheRead: 2, Total: 10), $"{i}"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, Provider.Claude, now);
Assert.Equal(7, view.Hourly.Count); Assert.Equal(40, view.Hourly.Single(p => p.Series == "Other").Value);
Assert.Equal(100, view.Hourly.Sum(p => p.Value)); Assert.Equal(20, view.Hourly.Sum(p => p.CacheRead));
Assert.Equal(view.Hourly.Select(p => p.Series).Order(), view.Daily.Select(p => p.Series).Order());
Assert.DoesNotContain(view.Hourly, p => p.Series == "model-6");
}
[Fact] public void ProjectNamesKeepTwoSegmentsAndDisambiguateCollisions()
{
var names = PanelWindow.ShortProjectNames(["D:/First/Shared/App", "D:/Second/Shared/App", "/work/Only/App", "Unknown"]);
Assert.Equal(["First/Shared/App", "Second/Shared/App", "Only/App", "Unknown"], names);
}
[Fact] public void ModelBreakdownKeepsActualProviderIdentityForDots()
{
var now = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
store.Add(new(Provider.Claude, now.AddHours(-1), "arbitrary-name", "p", new(Total: 10), "a"));
store.Add(new(Provider.Codex, now.AddHours(-1), "shared-name", "p", new(Total: 20), "b"));
store.Add(new(Provider.Claude, now.AddHours(-1), "shared-name", "p", new(Total: 30), "c"));
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Days7, null, now);
Assert.Equal([Provider.Claude], view.Models.Single(r => r.Name == "arbitrary-name").Providers);
Assert.Equal([Provider.Claude, Provider.Codex], view.Models.Single(r => r.Name == "shared-name").Providers);
}
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other")); [Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels() [Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
{ {
@@ -65,25 +166,89 @@ public sealed class ViewModelTests
internal static class FakeData internal static class FakeData
{ {
public static PanelViewModel ForecastModel(double threshold = 10, bool beforeStart = false)
{
var now = new DateTimeOffset(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
var ahead = new LimitWindow(Provider.Codex, "primary", "Week", 39,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), now, "fixture");
if (beforeStart) ahead = ahead with { Length = TimeSpan.FromDays(28), ResetsAt = now.AddDays(28).AddHours(-4) };
var early = ahead with { Id = "secondary", Length = TimeSpan.FromDays(7), Label = "Week · early on track", UsedPercent = 1, ResetsAt = now.AddDays(7).AddHours(-1) };
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
store.AddLimits([ahead with { SampleTime = now.AddHours(-4), UsedPercent = 20 }, ahead,
early with { SampleTime = now.AddHours(-1), UsedPercent = 0 }, early]);
var snapshot = Snapshot(now) with { Providers = [Snapshot(now).Providers[1] with
{ Windows = [new(ahead, Pace.Calculate(ahead, now, threshold)), new(early, Pace.Calculate(early, now, threshold))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new() public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
{ {
MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers = MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers =
[new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Current session", 68, now, 5, 3), Window(Provider.Claude, "week", "Current week", 32, now, 168, 48)], [new(Provider.Claude, ProviderStatus.Available, null, [Window(Provider.Claude, "session", "Session · 5 h", 12, now, 5, 1), Window(Provider.Claude, "week", "Week · all models", 98, now, 168, 24)],
new(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)), new(12000000, 218000000, 2000000, 47000000, 0, 279000000), new(4000000, 6000000, 1000000, 1600000, 0, 12600000), new(85000000, 1920000000, 16000000, 259000000, 0, 2280000000)),
new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null, new(Provider.Codex, unavailable ? ProviderStatus.Unavailable : ProviderStatus.Available, unavailable ? "CLI is not installed. Token history remains available." : null,
[Window(Provider.Codex, "primary", "Primary · 5 hours", 12, now, 5, 1), Window(Provider.Codex, "secondary", "Secondary · 7 days", 62, now, 168, 80)], [Window(Provider.Codex, "secondary", "Week", 86, now, 168, 24)],
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))] new(72000000, 42000000, 0, 8400000, 2100000, 80400000), null, new(340000000, 150000000, 0, 38000000, 11000000, 378000000))]
}; };
private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours) private static WindowSnapshot Window(Provider provider, string id, string label, double percent, DateTimeOffset now, int hours, int resetHours)
{ var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); } { var w = new LimitWindow(provider, id, label, percent, now.AddHours(resetHours), TimeSpan.FromHours(hours), now.AddMinutes(-3), "fixture"); return new(w, Pace.Calculate(w, now)); }
public static PanelViewModel BudgetModel()
{
var now = new FixedClock().GetUtcNow();
var clock = new FixedClock(now);
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, clock.LocalTimeZone.BaseUtcOffset);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-budget", Guid.NewGuid().ToString("N")), new DiagnosticLog(), clock);
var snapshot = Snapshot(now);
snapshot = snapshot with { Providers = snapshot.Providers.Select(p =>
{
var w = new LimitWindow(p.Provider, "week", "Week", p.Provider == Provider.Claude ? 40 : 32, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
store.AddLimits([w with { SampleTime = CalendarDays.Start(now, clock.LocalTimeZone), UsedPercent = 30 }, w]);
for (var i = 0; i < 4; i++)
store.Add(new(p.Provider, start.AddDays(i), "fixture", "Fixture/Project", new(Input: 100, Total: 100), $"{p.Provider}-{i}"));
return p with { Windows = [new(w, Pace.Calculate(w, now))], Session = null,
WeekStart = start, WeekWindow = p.Provider == Provider.Claude ? "week" : null };
}).ToArray() };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static PanelViewModel EarlyResetModel()
{
var now = new FixedClock().GetUtcNow();
var transition = now.AddHours(-1);
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-early", Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var snapshot = Snapshot(now);
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
var window = codex.Windows[0].Window with { UsedPercent = 2, ResetsAt = transition.AddDays(7), SampleTime = now };
var previous = window with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 40 };
store.AddLimits([previous, window with { SampleTime = transition, UsedPercent = 1 }, window]);
var start = previous.ResetsAt!.Value - previous.Length!.Value;
void Add(DateTimeOffset time, long input, string id) => store.Add(new(Provider.Codex, time, "gpt-6.1-sol", "Fixture/Project", new(Input: input, Total: input), id));
Add(start, 1000000, "a"); Add(previous.SampleTime.AddHours(1), 5000000, "b"); Add(transition, 100000, "c");
snapshot = snapshot with { Providers = [codex with { Windows = [new(window, Pace.Calculate(window, now))] }] };
return new() { Snapshot = snapshot, History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
}
public static PanelViewModel Model(bool unavailable = false) public static PanelViewModel Model(bool unavailable = false)
{ {
var now = DateTimeOffset.UtcNow; var now = new FixedClock().GetUtcNow();
var hourly = Enumerable.Range(0, 24).SelectMany(i => new[] { new ChartValue(now.AddHours(-24 + i), "Claude", 1000 + i * 210), new ChartValue(now.AddHours(-24 + i), "Codex", 2000 + (i % 5) * 800) }).ToArray(); var store = new HistoryStore(Path.Combine(Path.GetTempPath(), "finaltoken-fake", Guid.NewGuid().ToString("N")), new DiagnosticLog(), new FixedClock(now));
var daily = Enumerable.Range(0, 7).SelectMany(i => new[] { new ChartValue(now.AddDays(-7 + i), "Claude", 20000 + i * 2000), new ChartValue(now.AddDays(-7 + i), "Codex", 30000 + i * 5000) }).ToArray(); var snapshot = Snapshot(now, unavailable);
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily, foreach (var provider in snapshot.Providers)
[new("Claude · Current session", Enumerable.Range(0, 8).Select(i => new ChartValue(now.AddMinutes(-140 + i * 20), "session", i * 8 + 12, i * 6)).ToArray())], {
[new("claude-sonnet", new(Total: 221000), 0.37), new("gpt-6.1-sol", new(Total: 378000), 0.63)], [new("FinalToken", new(Total: 599000), 1)]), for (var i = 0; i < 336; i++)
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] }; {
var input = 1000000 + i * 10000; var cache = input * 8;
store.Add(new(provider.Provider, now.AddHours(-336 + i), provider.Provider == Provider.Claude ? "claude-fable" : "gpt-6.1-sol",
$"D:/Projects/Customer-{i % 110}/Workspace/Project-{i % 110}",
provider.Provider == Provider.Claude ? new(input, cache, 200000, 500000, 0, input + cache + 700000) : new(input + cache, cache, 0, 500000, 100000, input + cache + 500000), $"{provider.Provider}-{i}"));
}
foreach (var ws in provider.Windows)
{
var w = ws.Window; var start = w.ResetsAt!.Value - w.Length!.Value;
for (var i = provider.Provider == Provider.Claude && w.Length > TimeSpan.FromDays(1) ? (int)(now - start).TotalHours - 24 : 0; i <= (int)(now - start).TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 3 : 1)
store.AddLimits([w with { SampleTime = start.AddHours(i), UsedPercent = w.UsedPercent * i / (now - start).TotalHours }]);
var previousReset = start - (w.Length > TimeSpan.FromDays(1) ? TimeSpan.Zero : TimeSpan.FromHours(6));
for (var i = 0; i < (int)w.Length!.Value.TotalHours; i += w.Length > TimeSpan.FromDays(1) ? 6 : 1)
store.AddLimits([w with { ResetsAt = previousReset, SampleTime = previousReset - w.Length.Value + TimeSpan.FromHours(i), UsedPercent = 100.0 * i / w.Length.Value.TotalHours }]);
}
}
return new() { Snapshot = snapshot, Message = "Updated just now", History = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now) };
} }
} }
+18
View File
@@ -61,11 +61,29 @@ public class CliTests
Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, Assert.Equal(0, await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory,
path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), TestContext.Current.CancellationToken)); path => new(path, claudeDirectory: path, codexDirectory: path, cliDiscovery: (_, _) => new(null, "Fixture CLI missing.")), TestContext.Current.CancellationToken));
Assert.Contains("Tokens today: 0", output.ToString()); Assert.Contains("Tokens today: 0", output.ToString());
Assert.Contains("Calendar week: since ", output.ToString());
Assert.NotNull(SnapshotFile.Read(directory).Snapshot); Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
} }
finally { Directory.Delete(directory, true); } finally { Directory.Delete(directory, true); }
} }
[Fact] [Fact]
public async Task TextNamesLimitWeekAndItsStart()
{
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(directory);
try
{
using var storeLock = StoreLock.TryAcquire(directory);
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, "week")] }, TestContext.Current.CancellationToken);
using var output = new StringWriter(); using var error = new StringWriter();
Assert.Equal(0, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains($"Limit week: since {start:O} (week)", output.ToString());
}
finally { Directory.Delete(directory, true); }
}
[Fact]
public async Task BusyStoreWithoutSnapshotExitsOne() public async Task BusyStoreWithoutSnapshotExitsOne()
{ {
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N")); var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
@@ -0,0 +1,225 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class DayBudgetTests
{
private static readonly TimeZoneInfo Zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
private static readonly DateTimeOffset Start = new(2026, 10, 10, 22, 40, 0, TimeSpan.FromHours(2));
private static LimitWindow Week(DateTimeOffset now, double used = 30) => new(Provider.Codex, "week", "Week", used,
Start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
private static WindowDays Days(DateTimeOffset now, double used, params LimitWindow[] samples) =>
LimitAnalysis.Days(Week(now, used), samples, now, Zone)!;
[Fact] public void EightDatesHaveRealPartialSharesAndEvenPace()
{
var days = Days(Start.AddMinutes(20), 1);
Assert.Equal(8, days.Current.Count);
Assert.Equal(TimeSpan.FromMinutes(80), days.Current[0].Share);
Assert.Equal(TimeSpan.FromHours(22).Add(TimeSpan.FromMinutes(40)), days.Current[^1].Share);
Assert.Equal(TimeSpan.FromDays(7).Ticks, days.Current.Sum(d => d.Share.Ticks));
Assert.Equal(100, days.Current.Sum(d => d.EvenPace), 8);
Assert.Equal(100d * 80 / (7 * 24 * 60), days.Current[0].EvenPace, 8);
Assert.All(days.Current.Skip(1).SkipLast(1), d => Assert.Equal(TimeSpan.FromDays(1), d.Share));
}
[Theory]
[InlineData(3, 29, 23)]
[InlineData(10, 25, 25)]
public void DaylightSavingSharesUseActualHours(int month, int date, int hours)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
var day = CalendarDays.Start(new DateTime(2026, month, date), zone);
var now = day.AddHours(12);
var window = Week(now) with { ResetsAt = day.AddDays(3) };
var days = LimitAnalysis.Days(window, [window with { SampleTime = day, UsedPercent = 20 }], now, zone)!;
var today = Assert.Single(days.Current, d => d.IsToday);
Assert.Equal(hours, today.Share.TotalHours);
Assert.Equal(100d * hours / 168, today.EvenPace, 8);
Assert.Equal(80d * hours / 72, today.Budget!.Value, 8);
}
[Fact] public void FirstPartialDayBudgetHoldsWhileSpending()
{
var first = Days(Start.AddMinutes(10), .2);
var later = Days(Start.AddMinutes(50), .7);
Assert.Equal(first.Current[0].EvenPace, first.TodayBudget);
Assert.Equal(first.TodayBudget, later.TodayBudget);
Assert.Equal(first.LaterBudget, later.LaterBudget);
Assert.Equal(UseOrigin.Measured, first.BudgetOrigin);
Assert.Equal(100, first.Current.Sum(d => d.Budget ?? 0), 8);
}
[Fact] public void MeasuredBaselineKeepsTodayAndLaterPlanUntilTodayExceedsBudget()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var baseline = Week(day, 25);
var first = Days(day.AddHours(2), 26, baseline);
var within = Days(day.AddHours(12), 30, baseline);
var exceeded = Days(day.AddHours(16), 60, baseline);
var expected = 75 / (Start.AddDays(7) - day).TotalDays;
Assert.Equal(expected, first.TodayBudget!.Value, 8);
Assert.Equal(first.TodayBudget, within.TodayBudget);
Assert.Equal(first.TodayBudget, exceeded.TodayBudget);
Assert.Equal(first.LaterBudget, within.LaterBudget);
Assert.True(exceeded.LaterBudget < first.LaterBudget);
Assert.Equal(UseOrigin.Measured, within.BudgetOrigin);
Assert.All(within.Current.Where(d => !d.IsToday && !d.IsFuture), d => Assert.Null(d.Budget));
Assert.Equal(within.TodayBudget, Assert.Single(within.Current, d => d.IsToday).Budget);
Assert.Equal(100 - 25, within.Current.Sum(d => d.Budget ?? 0), 8);
Assert.Equal(0, Days(day.AddHours(17), 100, baseline).LaterBudget);
}
[Fact] public void TokenBaselineIsMarkedEstimated()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var now = day.AddHours(12); var window = Week(now, 40);
ModelTokenPoint[] tokens = [new(Start, "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(window, [], tokens, now, Zone)!.Days!;
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(80 / (window.ResetsAt!.Value - day).TotalDays, days.TodayBudget!.Value, 8);
}
[Fact] public void FirstSampleKeepsEstimatedBudgetStableWhenLaterUseHasNoLocalTokens()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2), 20);
var newest = Week(day.AddHours(12), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
var later = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
var expectedBudget = 90 / remainingDays;
Assert.Equal(18.202247191, expectedBudget, 8);
Assert.Equal(10, initial.Today); Assert.Equal(11, later.Today);
foreach (var days in new[] { initial, later })
{
Assert.Equal(10, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(expectedBudget, days.TodayBudget.Value, 8);
Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(UseOrigin.Estimated, days.TodayOrigin);
Assert.True(days.Today < days.TodayBudget);
Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin));
}
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void TokensAddedInFirstSampleHourDoNotMoveEstimatedBudgets()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2).AddMinutes(5), 20);
var newest = Week(day.AddHours(2).AddMinutes(30), 22);
// Hourly buckets for 100 input tokens at 23:30 and 02:01 local.
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(2), "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
ModelTokenPoint[] moreTokens = [.. tokens, new(day.AddHours(2), "fixture", new(Input: 100))];
var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
var expectedBudget = 80 / remainingDays;
Assert.Equal(10, initial.Today); Assert.Equal(22d * 200 / 300, later.Today!.Value, 8);
foreach (var days in new[] { initial, later })
{
Assert.Equal(20, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(expectedBudget, days.TodayBudget.Value, 8);
Assert.Equal(expectedBudget, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
Assert.Equal(UseOrigin.Estimated, days.TodayOrigin);
Assert.True(days.Today < days.TodayBudget);
Assert.All(days.Current.Where(d => d.IsToday || d.IsFuture), d => Assert.Equal(UseOrigin.Estimated, d.BudgetOrigin));
}
Assert.Equal(initial.TodayBudget, later.TodayBudget);
Assert.Equal(initial.LaterBudget, later.LaterBudget);
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void FirstSampleInFirstHourUsesItsPercentAsEstimatedBaseline()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddMinutes(5), 20);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day, "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, Zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8);
Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
}
[Fact] public void HalfHourZoneExcludesTheUtcHourContainingMidnightFromEstimatedBaseline()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+0530", TimeSpan.FromHours(5.5), "Fixture", "Fixture");
var day = CalendarDays.Start(new DateTime(2026, 10, 13), zone);
var firstHour = day.AddMinutes(-30);
var first = Week(day.AddMinutes(5), 20);
var newest = Week(day.AddMinutes(15), 22);
ModelTokenPoint[] tokens = [new(firstHour.AddHours(-1), "fixture", new(Input: 100)), new(firstHour, "fixture", new(Input: 100))];
var initial = LimitAnalysis.Analyze(first, [], tokens, first.SampleTime, zone)!.Days!;
ModelTokenPoint[] moreTokens = [.. tokens, new(firstHour, "fixture", new(Input: 100))];
var later = LimitAnalysis.Analyze(newest, [first], moreTokens, newest.SampleTime, zone)!.Days!;
var remainingDays = (first.ResetsAt!.Value - day).TotalDays;
foreach (var days in new[] { initial, later })
{
Assert.Equal(first.UsedPercent, 100 - days.TodayBudget!.Value * remainingDays, 8);
Assert.Equal(80 / remainingDays, days.TodayBudget.Value, 8);
Assert.Equal(80 / remainingDays, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Estimated, days.BudgetOrigin);
}
Assert.Equal(initial.TodayBudget, later.TodayBudget);
Assert.Equal(initial.LaterBudget, later.LaterBudget);
Assert.Equal(initial.Current.Select(d => d.Budget), later.Current.Select(d => d.Budget));
}
[Fact] public void NoWholeHourTokensBeforeFirstSampleLeavesBudgetUnknown()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2).AddMinutes(5), 20);
var newest = Week(day.AddHours(2).AddMinutes(30), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(2), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
Assert.NotNull(days.Today);
Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin);
Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); });
}
[Fact] public void FirstSampleWithoutTokensCannotCalibrateABudgetFromLaterTokens()
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var first = Week(day.AddHours(2), 20);
var newest = Week(day.AddHours(12), 22);
ModelTokenPoint[] tokens = [new(day.AddHours(3), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first], tokens, newest.SampleTime, Zone)!.Days!;
Assert.NotNull(days.Today);
Assert.Null(days.TodayBudget); Assert.Null(days.LaterBudget); Assert.Null(days.BudgetOrigin);
Assert.All(days.Current, d => { Assert.Null(d.Budget); Assert.Null(d.BudgetOrigin); });
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
public void MeasuredBaselineWinsOverFirstSampleTokenCalibration(int minutes)
{
var day = CalendarDays.Start(Start.AddDays(3), Zone);
var baseline = Week(day.AddMinutes(minutes), 25);
var first = Week(day.AddHours(2), 26);
var newest = Week(day.AddHours(12), 30);
ModelTokenPoint[] tokens = [new(day.AddHours(-1), "fixture", new(Input: 100)), new(day.AddHours(1), "fixture", new(Input: 100))];
var days = LimitAnalysis.Analyze(newest, [first, baseline, baseline with { SampleTime = day.AddHours(-1), UsedPercent = 20 }],
tokens, newest.SampleTime, Zone)!.Days!;
var expected = 75 / (newest.ResetsAt!.Value - day).TotalDays;
Assert.Equal(expected, days.TodayBudget!.Value, 8);
Assert.Equal(expected, days.LaterBudget!.Value, 8);
Assert.Equal(UseOrigin.Measured, days.BudgetOrigin);
Assert.Equal(UseOrigin.Measured, days.TodayOrigin);
Assert.Equal(5, days.Today);
}
[Fact] public void LastDayHasOnlyItsRemainingBudget()
{
var now = Start.AddDays(7).AddHours(-2);
var baseline = Week(CalendarDays.Start(now, Zone), 80);
var days = Days(now, 90, baseline);
Assert.Equal(20, days.TodayBudget);
Assert.Null(days.LaterBudget);
Assert.Equal(20, days.Current[^1].Budget);
Assert.DoesNotContain(days.Current, d => d.IsFuture);
}
[Fact] public void MissingBaselineAndExpiredResetHaveNoBudget()
{
var now = Start.AddDays(3);
var unknown = Days(now, 30);
Assert.Null(unknown.TodayBudget); Assert.Null(unknown.LaterBudget); Assert.Null(unknown.BudgetOrigin);
Assert.All(unknown.Current, d => Assert.Null(d.Budget));
var expired = Days(Start.AddDays(7), 90, Week(Start.AddDays(6), 80));
Assert.Null(expired.TodayBudget); Assert.Null(expired.LaterBudget);
Assert.All(expired.Current, d => Assert.Null(d.Budget));
}
}
@@ -0,0 +1,90 @@
using Xunit;
namespace FinalToken.Core.Tests;
public class EarlyForecastTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 15, 16, 45, 0, TimeSpan.Zero);
private static LimitWindow Week(double used = 39) => new(Provider.Codex, "primary", "Week", used,
new(2026, 10, 22, 6, 18, 0, TimeSpan.Zero), TimeSpan.FromDays(7), Now, "fixture");
[Fact] public void AheadCodexWeekProjectsEarly()
{
var window = Week(); var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.InRange(pace.ElapsedFraction!.Value, .061, .063);
Assert.NotNull(pace.Projection);
Assert.InRange(pace.Projection.Value, Now, window.ResetsAt!.Value);
}
[Fact] public void AheadCodexWeekHasAverageForecast() => Assert.NotNull(LimitAnalysis.AverageUseAtReset(Week(), Now));
[Fact] public void AheadCodexWeekHasRecentForecast()
{
var window = Week();
var recent = LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now);
Assert.NotNull(recent); Assert.NotNull(recent.ReachesLimit);
Assert.Equal(TimeSpan.FromHours(4), recent.Span);
}
[Fact] public void AheadCodexPopupIncludesProjection()
{
var window = Week();
var popup = new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings());
Assert.NotNull(popup); Assert.NotNull(popup.Projection);
}
[Fact] public void OnePercentOneHourIntoWeekDoesNotForecast()
{
var window = Week(1) with { ResetsAt = Now.AddDays(7).AddHours(-1) };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, Now).State);
Assert.Null(Pace.Calculate(window, Now).Projection);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, Now));
Assert.Null(LimitAnalysis.Recent(window, [], Now));
}
[Theory]
[InlineData(10, true)]
[InlineData(40, false)]
public void AllForecastsFollowConfiguredThreshold(double threshold, bool eligible)
{
var window = Week() with { Length = TimeSpan.FromDays(28), ResetsAt = Now.AddDays(28).AddHours(-4) }; var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(eligible, pace.State == PaceState.Ahead);
Assert.Equal(eligible, Pace.CanForecast(window, Now, threshold));
Assert.Equal(eligible, pace.Projection is not null);
Assert.Equal(eligible, LimitAnalysis.AverageUseAtReset(window, Now, pace) is not null);
Assert.Equal(eligible, LimitAnalysis.Recent(window,
[window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace) is not null);
}
[Fact] public void ExactlyAheadThresholdEnablesEarlyForecasts()
{
var window = Week(); var threshold = Pace.Calculate(window, Now).Delta!.Value;
var pace = Pace.Calculate(window, Now, threshold);
Assert.Equal(PaceState.Ahead, pace.State);
Assert.NotNull(pace.Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, Now, pace));
Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = Now.AddHours(-4), UsedPercent = 20 }], Now, pace));
}
[Fact] public void UnderPaceCodexAtSixPointFourPercentShowsUseAtReset()
{
var window = Week(4) with { ResetsAt = Now + TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 936 / 1000) };
var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.OnTrack, pace.State);
Assert.Null(pace.Projection);
Assert.Equal(62.5, LimitAnalysis.AverageUseAtReset(window, Now)!.Value, 8);
}
[Fact] public void ForecastStartIsTwoPercentIntoWindow()
{
var window = Week(1);
Assert.Equal(window.ResetsAt - TimeSpan.FromTicks(TimeSpan.FromDays(7).Ticks * 49 / 50), Pace.ForecastStartsAt(window));
Assert.Null(Pace.ForecastStartsAt(window with { Length = null }));
Assert.Null(Pace.ForecastStartsAt(window with { ResetsAt = null }));
Assert.Null(Pace.ForecastStartsAt(window with { Length = TimeSpan.Zero }));
var start = Pace.ForecastStartsAt(window)!.Value;
Assert.False(Pace.CanForecast(window, start.AddTicks(-1), 40));
Assert.True(Pace.CanForecast(window, start, 40));
}
}
@@ -0,0 +1,77 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class HiddenWindowTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 18, 12, 0, 0, TimeSpan.Zero);
private static LimitWindow Week => new(Provider.Codex, "codex:secondary", "Week", 80,
Now.AddDays(3.5), TimeSpan.FromDays(7), Now, "fixture");
[Fact]
public async Task HiddenWindowsRoundTripWithSeriesLengthAndAbsentLabel()
{
using var directory = new TestDirectory();
var settings = new Settings
{
Claude = new() { HiddenWindows = [new("week (fable)", TimeSpan.FromDays(7), "Current week (Fable)"), new("session", null, "Session")] },
Codex = new() { HiddenWindows = [HiddenLimitWindow.For(Week)] }
};
await SettingsFile.SaveAsync(directory.Path, settings, TestContext.Current.CancellationToken);
var diagnostics = new DiagnosticLog();
var loaded = SettingsFile.Load(directory.Path, diagnostics);
Assert.Equal(settings, loaded); Assert.Equal(settings.GetHashCode(), loaded.GetHashCode());
Assert.Equal(settings.Claude.HiddenWindows, loaded.Claude.HiddenWindows);
Assert.Equal(settings.Codex.HiddenWindows, loaded.Codex.HiddenWindows);
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void OldFileHidesNothing()
{
using var directory = new TestDirectory();
directory.Write("settings.json", """{"claude":{"enabled":true},"codex":{"popupAhead":false}}""");
var diagnostics = new DiagnosticLog();
var settings = SettingsFile.Load(directory.Path, diagnostics);
Assert.Empty(settings.Claude.HiddenWindows); Assert.Empty(settings.Codex.HiddenWindows);
Assert.False(settings.Codex.PopupAhead); Assert.False(settings.Codex.IsHidden(Week));
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void CodexWeekStaysHiddenAcrossSlotResetAndLabelChangesButNotLengthOrName()
{
var config = new ProviderSettings { HiddenWindows = [HiddenLimitWindow.For(Week)] };
Assert.True(config.IsHidden(Week));
Assert.True(config.IsHidden(Week with { Id = "codex:primary", ResetsAt = Now.AddDays(7), Label = "Renamed week" }));
Assert.False(config.IsHidden(Week with { Id = "codex:primary", Length = TimeSpan.FromHours(5) }));
Assert.False(config.IsHidden(Week with { Id = "other:secondary" }));
}
[Theory]
[InlineData(80)]
[InlineData(10)]
public void HiddenWindowHasNoAheadOrBehindPopupAcrossSlotMove(double used)
{
var window = Week with { UsedPercent = used, Id = "codex:primary" };
var pace = Pace.Calculate(window, Now);
Assert.NotNull(new PopupDecider().Observe(window, pace, new Settings()));
var settings = new Settings { Codex = new() { HiddenWindows = [HiddenLimitWindow.For(Week)] } };
Assert.Null(new PopupDecider().Observe(window, pace, settings));
Assert.NotNull(new PopupDecider().Observe(window with { Provider = Provider.Claude }, pace, settings));
}
[Theory]
[InlineData("null")]
[InlineData("[null]")]
[InlineData("[{\"name\":\"\",\"label\":\"Week\"}]")]
[InlineData("[{\"name\":\"week\",\"label\":\"Week\",\"length\":\"00:00:00\"}]")]
public void MalformedHiddenWindowsFallBackWithDiagnostic(string hidden)
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{\"claude\":{\"hiddenWindows\":" + hidden + "}}");
var diagnostics = new DiagnosticLog();
Assert.Empty(SettingsFile.Load(directory.Path, diagnostics).Claude.HiddenWindows);
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
}
@@ -0,0 +1,168 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class LimitAnalysisTests
{
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(double use = 60) => new(Provider.Claude, "week", "Week", use,
Now.AddDays(3.5), TimeSpan.FromDays(7), Now, "fixture");
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void MinuteDriftAcrossMidnightKeepsDaysRecentRateAndPreviousWeek(int minutes)
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
var w = Window() with { ResetsAt = new DateTimeOffset(2026, 10, 18, 20, 0, 0, TimeSpan.Zero) };
LimitWindow[] samples =
[
w with { SampleTime = Now.AddDays(-2).AddHours(9), UsedPercent = 30, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-15), UsedPercent = 40, ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes) },
w with { SampleTime = Now.AddHours(-6), UsedPercent = 50, ResetsAt = w.ResetsAt!.Value.AddMinutes(-minutes) },
w with { SampleTime = Now.AddDays(-3).AddHours(7), UsedPercent = 90, ResetsAt = w.ResetsAt!.Value.AddDays(-7) }
];
var days = LimitAnalysis.Days(w, samples, Now, zone)!;
Assert.Equal(20, days.Today);
Assert.Equal(20, Assert.Single(days.Current, d => d.IsToday).Used);
Assert.Equal(10, Assert.Single(days.Current, d => d.Start == CalendarDays.Start(Now.AddDays(-1), zone)).Used);
Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
var recent = LimitAnalysis.Recent(w, samples, Now);
Assert.NotNull(recent); Assert.Equal(20, recent.Increase); Assert.Equal(32, recent.PercentPerDay);
Assert.Equal(Now.AddDays(1.25), recent.ReachesLimit);
}
[Fact] public void RealWeekResetStartsAtZeroAndKeepsOldWeekSeparate()
{
var old = Window() with { UsedPercent = 90, SampleTime = Window().ResetsAt!.Value.AddHours(-3) };
var now = old.ResetsAt!.Value.AddHours(1);
var current = old with { ResetsAt = old.ResetsAt.Value.AddDays(7), SampleTime = now, UsedPercent = 5 };
var days = LimitAnalysis.Days(current, [old], now, TimeZoneInfo.Utc)!;
Assert.Equal(5, days.Today); Assert.Equal(90, days.Previous.Last(d => d.Cumulative is not null).Cumulative);
Assert.Null(LimitAnalysis.Recent(current, [old], now));
}
[Theory]
[InlineData(-900, true)]
[InlineData(900, true)]
[InlineData(-901, false)]
[InlineData(901, false)]
[InlineData(604800, false)]
public void InstanceToleranceIsInclusiveAndKeepsWindowAndProviderIdentity(int seconds, bool same)
{
var window = Window();
var other = window with { ResetsAt = window.ResetsAt!.Value.AddSeconds(seconds) };
Assert.Equal(same, LimitAnalysis.SameInstance(window, other));
Assert.Equal(same, LimitAnalysis.SameInstance(other, window));
Assert.False(LimitAnalysis.SameInstance(window, window with { Id = "session" }));
Assert.False(LimitAnalysis.SameInstance(window, window with { Provider = Provider.Codex }));
Assert.False(LimitAnalysis.SameInstance(window with { ResetsAt = null }, window with { ResetsAt = null }));
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void SessionRecentRateSurvivesMinuteDriftAcrossMidnight(int minutes)
{
var now = new DateTimeOffset(2026, 10, 14, 2, 0, 0, TimeSpan.Zero);
var session = new LimitWindow(Provider.Claude, "session", "Session", 30, now.AddHours(2), TimeSpan.FromHours(5), now, "fixture");
var samples = new[] { session with { UsedPercent = 0, SampleTime = now.AddHours(-3), ResetsAt = session.ResetsAt!.Value.AddMinutes(minutes) },
session with { UsedPercent = 10, SampleTime = now.AddHours(-2), ResetsAt = session.ResetsAt!.Value.AddMinutes(-minutes) } };
var recent = LimitAnalysis.Recent(session, samples, now);
Assert.NotNull(recent); Assert.Equal(240, recent.PercentPerDay); Assert.Equal(50, recent.UseAtReset);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void LateSampleDeduplicatesAgainstDriftingChronologicalNeighbour(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var window = Window();
store.AddLimits([window with { SampleTime = Now.AddHours(2) }]);
store.AddLimits([window with { SampleTime = Now.AddHours(1), UsedPercent = 50 }]);
store.AddLimits([window with { SampleTime = Now.AddMinutes(115), ResetsAt = window.ResetsAt!.Value.AddMinutes(minutes) }]);
Assert.Equal(2, store.LimitSamples(window.Provider, window.Id, Now, Now.AddHours(3)).Count);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void UnchangedDriftingResetKeepsHourlySamplingAndLatestMetadata(int minutes)
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog());
var w = Window();
store.AddLimits([w]);
var drifted = w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(minutes), SampleTime = Now.AddMinutes(5) };
store.AddLimits([drifted]);
Assert.Single(store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)));
Assert.Equal(drifted.ResetsAt, Assert.Single(store.LatestLimits(w.Provider)).ResetsAt);
store.AddLimits([drifted with { UsedPercent = 61, SampleTime = Now.AddMinutes(10) }]);
store.AddLimits([w with { ResetsAt = w.ResetsAt.Value.AddDays(7), SampleTime = Now.AddMinutes(15), UsedPercent = 61 }]);
Assert.Equal(3, store.LimitSamples(w.Provider, w.Id, Now.AddHours(-1), Now.AddHours(1)).Count);
}
[Fact] public void AverageAndRecentAreIndependent()
{
var w = Window();
Assert.Equal(120, LimitAnalysis.AverageUseAtReset(w, Now));
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-12), UsedPercent = 50 }], Now);
Assert.NotNull(recent); Assert.Equal(20, recent.PercentPerDay); Assert.Equal(130, recent.UseAtReset);
Assert.Equal(Now.AddDays(2), recent.ReachesLimit);
}
[Fact] public void RecentRequiresThreeHoursOfSameResetAndLast24Hours()
{
var w = Window();
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-2), UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), ResetsAt = Now, UsedPercent = 40 }], Now));
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-25), UsedPercent = 40 }], Now));
Assert.NotNull(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-3), UsedPercent = 40 }], Now));
}
[Fact] public void FlatRecentRateHasNoLimitDateAndDecreasingSamplesAreUnknown()
{
var w = Window();
var recent = LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4) }], Now);
Assert.NotNull(recent); Assert.Equal(60, recent.UseAtReset); Assert.Null(recent.ReachesLimit);
Assert.Null(LimitAnalysis.Recent(w, [w with { SampleTime = Now.AddHours(-4), UsedPercent = 70 }], Now));
}
[Fact] public void DaysUsePriorSampleAndKeepUnknownBaselinesUnknown()
{
var w = Window();
var days = LimitAnalysis.Days(w, [w with { SampleTime = Now.AddHours(-14), UsedPercent = 51 }], Now, TimeZoneInfo.Utc)!;
Assert.Equal(9, days.Today); Assert.Equal(100d / 7, days.EvenPace); Assert.Equal(49d / 4, days.TodayBudget);
Assert.Contains(days.Current, d => d.IsFuture && d.Used is null);
Assert.Contains(days.Current, d => d.Start == Now.AddHours(-36) && d.Used is null);
Assert.Null(LimitAnalysis.Days(w, [], Now, TimeZoneInfo.Utc)!.Today);
}
[Fact] public void FirstDayStartsAtZeroAndPreviousInstanceIsReturned()
{
var w = Window() with { ResetsAt = Now.AddDays(7).AddHours(-2) };
var previous = w with { ResetsAt = w.ResetsAt!.Value.AddDays(-7), SampleTime = Now.AddHours(-3), UsedPercent = 80 };
var days = LimitAnalysis.Days(w, [previous], Now, TimeZoneInfo.Utc)!;
Assert.Equal(60, days.Today); Assert.NotEmpty(days.Previous);
Assert.Null(LimitAnalysis.Days(w with { Length = TimeSpan.FromHours(5) }, [], Now));
}
[Theory]
[InlineData("Europe/Berlin", 2026, 3, 29, 23)]
[InlineData("Europe/Berlin", 2026, 10, 25, 25)]
[InlineData("America/Santiago", 2026, 9, 6, 23)]
public void DaysFollowCalendarIncludingMissingMidnight(string id, int year, int month, int day, int hours)
{
var zone = TimeZoneInfo.FindSystemTimeZoneById(id);
var start = CalendarDays.Start(new DateTime(year, month, day), zone);
var now = start.AddHours(12);
var w = Window() with { ResetsAt = start.AddDays(5), SampleTime = now };
var days = LimitAnalysis.Days(w, [w with { SampleTime = start.AddHours(-1), UsedPercent = 50 }], now, zone)!;
var today = Assert.Single(days.Current, d => d.IsToday);
Assert.Equal(hours, (today.End - today.Start).TotalHours); Assert.Equal(10, today.Used);
}
[Fact] public void ModelSeriesGroupsInOnePassAndMatchesTotals()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new DiagnosticLog(), new TestClock());
store.Add(new(Provider.Claude, Now.AddHours(-2), "a", "p", new(Total: 20), "a"));
store.Add(new(Provider.Claude, Now.AddHours(-2), "b", "p", new(Total: 30), "b"));
store.Add(new(Provider.Claude, Now.AddHours(-1), "a", "p", new(Total: 40), "c"));
store.Add(new(Provider.Codex, Now.AddHours(-1), "a", "p", new(Total: 900), "d"));
var points = store.TokenSeriesByModel(Provider.Claude, Now.AddDays(-1), Now, SeriesInterval.Day, TimeZoneInfo.Utc);
Assert.Equal(2, points.Count); Assert.Equal(90, points.Sum(p => p.Counts.Total));
Assert.Equal(60, points.Single(p => p.Model == "a").Counts.Total);
}
}
@@ -0,0 +1,128 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class LimitInstanceTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(DateTimeOffset start, TimeSpan length, DateTimeOffset sample, double used) =>
new(Provider.Codex, "window", "Window", used, start + length, length, sample, "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input) => new(time, "model", new(Input: input, Total: input));
private static LimitEstimate Analyze(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens, DateTimeOffset now) =>
LimitAnalysis.Analyze(current, samples, tokens, now, TimeZoneInfo.Utc)!;
[Fact] public void SessionGapKeepsTheReviewersMeasuredSessionAndItsOwnScale()
{
var length = TimeSpan.FromHours(5);
var current = Window(Day.AddHours(14), length, Day.AddHours(15), 50);
var previous = Window(Day.AddHours(3), length, Day.AddHours(7.5), 80);
var first = previous with { SampleTime = Day.AddHours(3.5), UsedPercent = 10 };
var result = Analyze(current, [previous, first],
[Token(Day.AddHours(3), 50), Token(Day.AddHours(7), 350), Token(Day.AddHours(9), 1000000), Token(Day.AddHours(14), 100)], current.SampleTime);
var past = Assert.Single(result.Past);
Assert.Equal(Day.AddHours(3), past.Start); Assert.Equal(Day.AddHours(8), past.End);
Assert.Equal(.2, past.Scale); Assert.Equal(80, past.Peak); Assert.Null(past.ReachedLimit);
Assert.Contains(new(first.SampleTime, 10, UseOrigin.Measured), past.Points);
Assert.Contains(new(previous.SampleTime, 80, UseOrigin.Measured), past.Points);
Assert.Equal(.5, result.Current.Scale);
}
[Fact] public void SeveralRealSessionsLeaveEveryGapUnassigned()
{
var length = TimeSpan.FromHours(5);
var current = Window(Day.AddHours(24), length, Day.AddHours(25), 50);
var previous = new[] { 0, 8, 16 }.Select((hour, i) => Window(Day.AddHours(hour), length, Day.AddHours(hour + 2), 20 * (i + 1))).ToArray();
var tokens = new[] { 0, 8, 16, 24 }.Select(hour => Token(Day.AddHours(hour), 100))
.Concat(new[] { 6, 14, 22 }.Select(hour => Token(Day.AddHours(hour), 1000000))).ToArray();
var result = Analyze(current, previous, tokens, current.SampleTime);
Assert.Equal(3, result.Past.Count);
for (var i = 0; i < 3; i++)
{
var sample = previous[2 - i]; var past = result.Past[i];
Assert.Equal(sample.ResetsAt!.Value - length, past.Start); Assert.Equal(sample.ResetsAt, past.End);
Assert.Equal(sample.UsedPercent, past.Peak); Assert.Equal(sample.UsedPercent / 100, past.Scale);
Assert.Contains(new(sample.SampleTime, sample.UsedPercent, UseOrigin.Measured), past.Points);
}
AssertNoOverlap(result);
}
[Theory]
[InlineData(5)]
[InlineData(168)]
public void EarlyCodexReplacementSplitsAtResetDerivedStartBeforeItsFirstSample(int hours)
{
var length = TimeSpan.FromHours(hours); var start = Day.AddHours(10);
var oldStart = hours == 5 ? start.AddHours(-3) : start.AddDays(-3);
var previous = Window(oldStart, length, oldStart.AddHours(2), 50);
var current = Window(start, length, start.AddHours(1.5), 40);
var first = current with { SampleTime = start.AddHours(1), UsedPercent = 20 };
var result = Analyze(current, [previous, first],
[Token(oldStart, 100), Token(start, 300), Token(start.AddHours(1), 200)], start.AddHours(2));
var past = Assert.Single(result.Past);
Assert.Equal(start, result.Current.Start); Assert.Equal(start, past.End);
Assert.Equal(oldStart, past.Start); Assert.Equal(.5, past.Scale); Assert.Equal(50, past.Peak);
Assert.Null(past.ReachedLimit); Assert.Equal(40d / 500, result.Current.Scale);
Assert.All(past.Points, p => Assert.True(p.Time <= start));
AssertNoOverlap(result);
}
[Fact] public void EarlierWeeksWithoutSamplesAreInferredInWholeNonOverlappingWindows()
{
var length = TimeSpan.FromDays(7); var current = Window(Day, length, Day.AddDays(2), 20);
var tokens = new[] { Token(Day, 100), Token(Day.AddDays(-7), 100), Token(Day.AddDays(-14), 200), Token(Day.AddDays(-21), 300) };
var result = Analyze(current, [], tokens, current.SampleTime);
Assert.Equal(3, result.Past.Count);
for (var i = 0; i < 3; i++)
{
var past = result.Past[i]; Assert.Equal(Day.AddDays(-7 * (i + 1)), past.Start);
Assert.Equal(past.Start + length, past.End); Assert.Equal(.2, past.Scale); Assert.Equal(20 * (i + 1), past.Peak);
Assert.All(past.Points.Skip(1), p => Assert.Equal(UseOrigin.Estimated, p.Origin));
}
AssertNoOverlap(result);
}
[Fact] public void ARealWeekBetweenInferredWeeksKeepsItsSamplesAndLeavesTheShortGapEmpty()
{
var length = TimeSpan.FromDays(7); var current = Window(Day, length, Day.AddDays(2), 20);
var start = Day.AddDays(-17); var previous = Window(start, length, start.AddDays(6), 60);
var first = previous with { SampleTime = start.AddHours(1), UsedPercent = 10 };
var result = Analyze(current, [first, previous],
[Token(Day, 100), Token(Day.AddDays(-7), 100), Token(start, 100), Token(start.AddDays(5), 100),
Token(start.AddDays(-7), 200), Token(previous.ResetsAt!.Value.AddDays(1), 1000000)], current.SampleTime);
Assert.Equal(3, result.Past.Count);
Assert.Equal(Day.AddDays(-7), result.Past[0].Start); Assert.Equal(20, result.Past[0].Peak);
var real = result.Past[1]; Assert.Equal(start, real.Start); Assert.Equal(previous.ResetsAt, real.End);
Assert.Equal(.3, real.Scale); Assert.Equal(60, real.Peak);
Assert.Contains(new(first.SampleTime, 10, UseOrigin.Measured), real.Points);
Assert.Contains(new(previous.SampleTime, 60, UseOrigin.Measured), real.Points);
Assert.Equal(start.AddDays(-7), result.Past[2].Start); Assert.Equal(.2, result.Past[2].Scale); Assert.Equal(40, result.Past[2].Peak);
AssertNoOverlap(result);
}
[Fact] public void AdjacentInferredWeeksAssignTheBoundaryHourOnlyToTheStartingWeek()
{
var start = Day.AddMinutes(13);
var current = Window(start, TimeSpan.FromDays(7), start.AddHours(2), 20);
var result = Analyze(current, [], [Token(Day, 100), Token(Day.AddDays(-7), 100)], current.SampleTime);
var past = Assert.Single(result.Past);
Assert.Equal(start.AddDays(-7), past.Start); Assert.Equal(20, past.Peak);
Assert.DoesNotContain(result.Past, p => p.Start == start.AddDays(-14));
AssertNoOverlap(result);
}
[Theory]
[InlineData(5)]
[InlineData(24)]
public void ADayOrShorterNeverInfersAnUnobservedWindow(int hours)
{
var length = TimeSpan.FromHours(hours); var current = Window(Day, length, Day.AddHours(1), 20);
var result = Analyze(current, [], [Token(Day, 100), Token(Day - length, 10000)], current.SampleTime);
Assert.Empty(result.Past);
}
private static void AssertNoOverlap(LimitEstimate result)
{
var spans = result.Past.Append(result.Current).OrderBy(p => p.Start).ToArray();
for (var i = 1; i < spans.Length; i++) Assert.True(spans[i - 1].End <= spans[i].Start);
}
}
+9
View File
@@ -29,6 +29,15 @@ public class PaceTests
[Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection); [Fact] public void ProjectionAfterResetIsHidden() => Assert.Null(Pace.Calculate(Window(10), Now).Projection);
[Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection); [Fact] public void ZeroElapsedDoesNotProject() => Assert.Null(Pace.Calculate(Window(50, 0), Now).Projection);
[Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection); [Fact] public void ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection);
[Fact] public void BelowAlertThresholdStillProjectsWithoutPopup()
{
var window = Window(55);
var pace = Pace.Calculate(window, Now);
Assert.Equal(PaceState.OnTrack, pace.State);
Assert.NotNull(pace.Projection);
Assert.True(pace.Projection < window.ResetsAt);
Assert.Null(new PopupDecider().Observe(window, pace, new Settings()));
}
[Fact] [Fact]
public void PopupHysteresisPreventsFlappingAndRearmsAfterClear() public void PopupHysteresisPreventsFlappingAndRearmsAfterClear()
@@ -5,6 +5,23 @@ namespace FinalToken.Core.Tests;
public sealed class PartialSettingsTests public sealed class PartialSettingsTests
{ {
[Fact]
public void MissingSettingsIsNormalFirstStart()
{
using var directory = new TestDirectory();
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Empty(diagnostics.Recent);
}
[Fact]
public void PresentMalformedSettingsIsDiagnostic()
{
using var directory = new TestDirectory();
directory.Write("settings.json", "{broken");
var diagnostics = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
}
[Theory] [Theory]
[InlineData("{}")] [InlineData("{}")]
[InlineData("{\"refreshInterval\":\"00:00:30\"}")] [InlineData("{\"refreshInterval\":\"00:00:30\"}")]
@@ -0,0 +1,32 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ResetBoundaryTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 15, 0, 0, 0, TimeSpan.Zero);
private static LimitWindow Window(DateTimeOffset start, DateTimeOffset sample, double used) =>
new(Provider.Codex, "codex:primary", "Session", used, start.AddHours(5), TimeSpan.FromHours(5), sample, "fixture");
[Fact] public void ResetHourBeforeAGapBelongsToTheEndingInstance()
{
var previous = Window(Day.AddHours(10).AddMinutes(13), Day.AddHours(14), 50);
var current = Window(Day.AddHours(20), Day.AddHours(21), 10);
ModelTokenPoint[] tokens = [new(Day.AddHours(10), "model", new(Input: 100, Total: 100)),
new(Day.AddHours(15), "model", new(Input: 50, Total: 50))];
var past = Assert.Single(LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!.Past);
Assert.Equal(75, past.Points.Last().Used);
Assert.Equal(UseOrigin.Estimated, past.Points.Last().Origin);
Assert.Equal(previous.ResetsAt, past.Points.Last().Time);
}
[Fact] public void EarlierSampleCannotPutAnInstanceAfterTheCurrentWindow()
{
var current = Window(Day.AddHours(10), Day.AddHours(12), 10);
var stale = Window(Day.AddHours(11), Day.AddHours(11.5), 90);
var result = LimitAnalysis.Analyze(current, [stale], [], current.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(current.ResetsAt, result.Current.End);
Assert.Equal(10, result.Current.Peak);
Assert.Empty(result.Past);
}
}
@@ -0,0 +1,232 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class ResetHistoryTests
{
private static readonly DateTimeOffset Day = new(2026, 10, 1, 0, 0, 0, TimeSpan.Zero);
private static readonly TimeSpan Week = TimeSpan.FromDays(7);
private static LimitWindow Window(DateTimeOffset start, double used = 50, double sampleHour = 1) =>
new(Provider.Codex, "codex:primary", "Week", used, start + Week, Week, start.AddHours(sampleHour), "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 1_000_000, string model = "gpt-6.1-sol") =>
new(time, model, new(Input: input, Total: input));
private static ResetHistory History(LimitWindow current, LimitWindow[] samples, ModelTokenPoint[] tokens,
DateTimeOffset? from = null, DateTimeOffset? now = null, TimeZoneInfo? zone = null) =>
LimitAnalysis.Resets(current, samples, tokens, from ?? DateTimeOffset.MinValue, now ?? current.SampleTime, zone ?? TimeZoneInfo.Utc);
[Fact] public void SeriesMergesCodexSlotsButSeparatesLengthsNamesAndProviders()
{
var week = Window(Day);
Assert.True(LimitAnalysis.SameInstance(week, week with { Id = "codex:secondary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Length = TimeSpan.FromHours(5) }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Id = "codex_bengalfox:primary" }));
Assert.False(LimitAnalysis.SameInstance(week, week with { Provider = Provider.Claude }));
var previous = Window(Day - Week, 30) with { Id = "codex:secondary" };
var wrong = previous with { Id = week.Id, Length = TimeSpan.FromHours(5), UsedPercent = 99 };
var other = previous with { Id = "codex_bengalfox:secondary", UsedPercent = 98 };
var analysis = LimitAnalysis.Analyze(week, [previous, wrong, other], [], week.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(30, Assert.Single(analysis.Past).Peak);
Assert.Equal(30, History(week, [previous, wrong, other], []).Instances[1].Final.Used);
Assert.Null(LimitAnalysis.Recent(week, [week with { Length = TimeSpan.FromHours(5), UsedPercent = 0, SampleTime = week.SampleTime.AddHours(-4) }], week.SampleTime));
}
[Fact] public void StoreSeriesQueryKeepsTheOriginalIdQueryWorking()
{
using var directory = new TestDirectory();
var store = new HistoryStore(directory.Path, new());
var week = Window(Day);
var moved = week with { Id = "codex:secondary", SampleTime = week.SampleTime.AddHours(-1) };
var shortWindow = week with { Length = TimeSpan.FromHours(5) };
store.AddLimits([moved, shortWindow, week]);
Assert.Equal(3, store.LimitSamples(Provider.Codex, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(week, Day, Day.AddDays(1)).Count);
Assert.Equal(2, store.LimitSamples(Provider.Codex, week.Id, Day, Day.AddDays(1)).Count);
}
[Theory]
[InlineData("claude-haiku-4-5")]
[InlineData("claude-haiku-4-5-20251001")]
public void PriceMatchesExactAndDatedModel(string model) => Assert.Equal(1, ApiPrices.Find(Provider.Claude, model)!.Input);
[Theory]
[InlineData("codex-auto-review")]
[InlineData("gpt-6.1-sol-latest")]
[InlineData("gpt-6.1-sol-20261301")]
[InlineData("gpt-6.1-sol-20261018-extra")]
[InlineData(null)]
public void UnknownModelHasNoValue(string? model) => Assert.Null(ApiPrices.Value(Provider.Codex, model, new(Input: 100)));
[Fact] public void ProviderValuesDoNotDoubleCountTokenSubsets()
{
var counts = new TokenCounts(1_000_000, 400_000, 200_000, 100_000, 80_000);
Assert.Equal(17.6m, ApiPrices.Value(Provider.Claude, "claude-fable-5-1", counts));
Assert.Equal(2.24m, ApiPrices.Value(Provider.Codex, "gpt-6.1-sol", counts));
Assert.Null(ApiPrices.Find(Provider.Claude, "gpt-6.1-sol"));
}
[Fact] public void OnTimeEarlyAndRunningInstancesHaveOwnValuesAndTotals()
{
var first = Window(Day, 40);
var second = Window(Day + Week, 50);
var current = Window(Day.AddDays(9), 20);
var history = History(current, [first, second], [Token(Day), Token(second.ResetsAt!.Value - Week), Token(Day.AddDays(9))]);
Assert.Equal(3, history.Instances.Count);
var running = history.Instances[0]; var early = history.Instances[1]; var onTime = history.Instances[2];
Assert.True(running.Running); Assert.Null(running.Unused); Assert.Null(running.Gift);
Assert.Equal(TimeSpan.FromHours(1), running.Duration); Assert.Equal(current.SampleTime, running.End);
Assert.False(onTime.Early); Assert.Equal(Week, onTime.Duration); Assert.Equal(60, onTime.Unused!.Percent);
Assert.True(early.Early); Assert.Equal(TimeSpan.FromDays(2), early.Duration); Assert.Equal(TimeSpan.FromDays(5), early.Skipped);
Assert.Equal(100d * 5 / 7, early.Gift!.Percent, 8); Assert.Equal(50, early.Unused!.Percent);
Assert.Equal(20_000, early.ValuePerPercent!.Tokens); Assert.Equal(.04m, early.ValuePerPercent.ApiValue);
Assert.Equal(PercentBasis.OwnInstance, early.ValuePerPercent.Basis);
Assert.Equal(1_000_000, early.Unused.Tokens); Assert.Equal(2m, early.Unused.ApiValue);
Assert.Equal(3, history.Totals.Instances); Assert.Equal(2, history.Totals.Finished); Assert.Equal(1, history.Totals.Early);
Assert.Equal(3_000_000, history.Totals.Tokens.Total); Assert.Equal(6m, history.Totals.ApiValue);
Assert.Equal(110, history.Totals.Unused.Percent); Assert.Equal(TimeSpan.FromDays(4.5), history.MedianDuration);
Assert.Equal(TimeSpan.FromDays(5), history.Totals.Skipped);
}
[Fact] public void RunningInstanceHasNoFinishedDurationOrResetValues()
{
var history = History(Window(Day), [], []);
Assert.True(Assert.Single(history.Instances).Running);
Assert.Equal(0, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Null(history.MedianDuration);
Assert.Null(history.Instances[0].Unused); Assert.Null(history.Instances[0].Gift);
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void OnTimeFinishedInstancesHaveNoEarlyResetAndExcludeRunningDurationFromMedian()
{
var history = History(Window(Day + Week * 2), [Window(Day), Window(Day + Week)], []);
Assert.Equal(2, history.Totals.Finished); Assert.Equal(0, history.Totals.Early);
Assert.Equal(Week, history.MedianDuration);
Assert.All(history.Instances.Where(r => !r.Running), row => Assert.NotNull(row.Unused));
Assert.All(history.Instances, row => Assert.Null(row.Gift));
Assert.All(history.EarlyByHour, count => Assert.Equal(0, count));
Assert.All(history.EarlyByWeekday, count => Assert.Equal(0, count));
}
[Fact] public void LowUseUsesMedianOfQualifyingListedInstances()
{
var first = Window(Day, 50); var second = Window(Day + Week, 25); var current = Window(Day + Week * 2, 4);
var result = History(current, [first, second], [Token(Day), Token(Day + Week), Token(Day + Week * 2)]);
var rate = result.Instances[0].ValuePerPercent!;
Assert.Equal(30_000, rate.Tokens); Assert.Equal(.06m, rate.ApiValue); Assert.Equal(PercentBasis.SeriesMedian, rate.Basis);
var onlyLow = History(current, [first, second], [Token(Day + Week * 2)], from: current.ResetsAt!.Value - Week);
Assert.Null(Assert.Single(onlyLow.Instances).ValuePerPercent);
}
[Fact] public void NoQualifyingInstanceKeepsOnlyUnusedAndGiftPercent()
{
var old = Window(Day, 4); var current = Window(Day.AddDays(2), 0);
var row = History(current, [old], []).Instances[1];
Assert.Null(row.ValuePerPercent); Assert.Equal(96, row.Unused!.Percent);
Assert.Null(row.Unused.Tokens); Assert.Null(row.Unused.ApiValue); Assert.Null(row.Gift!.Tokens);
}
[Fact] public void ReachedLimitAndTimeAtLimitReuseTheBurnUpIncludingEstimates()
{
var old = Window(Day, 50); var current = Window(Day + Week, 20);
var tokens = new[] { Token(Day), Token(Day.AddHours(2), 2_000_000), Token(Day + Week) };
var row = History(current, [old], tokens).Instances[1];
var analysis = LimitAnalysis.Analyze(current, [old], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
Assert.Equal(analysis.Past[0].Points, row.BurnUp.Points);
Assert.Equal(100, row.Peak); Assert.Equal(100, row.Final.Used); Assert.Equal(UseOrigin.Estimated, row.Final.Origin);
Assert.Equal(Day.AddHours(2.5), row.ReachedLimit);
Assert.Equal(Week - TimeSpan.FromHours(2.5), row.TimeAtLimit);
Assert.Equal(0, row.Unused!.Percent);
var measured = History(current, [old with { UsedPercent = 100 }], [Token(Day), Token(Day + Week)]).Instances[1];
Assert.Equal(old.SampleTime, measured.ReachedLimit); Assert.Equal(UseOrigin.Measured, measured.BurnUp.ReachedOrigin);
}
[Theory]
[InlineData(0, false)]
[InlineData(20, false)]
[InlineData(50, true)]
public void RealWeekKeepsItsEndHourOnlyWhenTheInferredSuccessorStartsInALaterHour(int gapMinutes, bool ownsEndHour)
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var currentStart = start + Week * 2 + TimeSpan.FromMinutes(gapMinutes);
var current = Window(currentStart, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(currentStart.AddMinutes(-currentStart.Minute), 100)];
var analysis = LimitAnalysis.Analyze(current, [previous], tokens, current.SampleTime, TimeZoneInfo.Utc)!;
var past = Assert.Single(analysis.Past, p => p.Start == start);
Assert.Equal(ownsEndHour ? 75 : 50, past.Points[^1].Used);
var history = History(current, [previous], tokens);
var row = Assert.Single(history.Instances, r => r.Start == start);
Assert.Equal(past.Points, row.BurnUp.Points);
Assert.Equal(ownsEndHour ? 150 : 100, row.Tokens.Total);
Assert.Equal(row.Tokens, Assert.Single(row.Models).Tokens);
Assert.Equal(previous.ResetsAt, row.End); Assert.False(row.Early);
Assert.Equal(2, history.Instances.Count);
}
[Fact] public void ResetHistoryUsesInferredSuccessorsBeyondTheEightPastChartInstances()
{
var start = Day.AddMinutes(13);
var previous = Window(start);
var current = Window(start + Week * 11, 20, 2);
ModelTokenPoint[] tokens = [Token(Day, 100), Token(Day + Week, 50), Token(Day + Week * 11, 100)];
var row = Assert.Single(History(current, [previous], tokens).Instances, r => r.Start == start);
Assert.Equal(100, row.Tokens.Total); Assert.Equal(50, row.Final.Used);
Assert.Equal(2, History(current, [previous], tokens).Instances.Count);
}
[Fact] public void FamilyFilterAndUnpricedModelsAreExplicit()
{
var current = Window(Day, 20) with { Provider = Provider.Claude, Id = "fable", Label = "Week (Fable)" };
var row = Assert.Single(History(current, [], [Token(Day, 100, "claude-fable-5"), Token(Day, 200, "claude-fable-new"),
Token(Day, 10_000, "claude-sonnet-5")]).Instances);
Assert.Equal(300, row.Tokens.Total); Assert.Equal(200, row.UnpricedTokens); Assert.Equal(.001m, row.ApiValue);
Assert.Equal(2, row.Models.Count);
var zero = Assert.Single(History(current with { UsedPercent = 0 }, [], [Token(Day, 100, "claude-sonnet-5")]).Instances);
Assert.Equal(0, zero.Tokens.Total); Assert.Null(zero.ApiValue); Assert.Null(zero.ValuePerPercent);
}
[Fact] public void RangeIncludesWholeOverlappingRealInstanceAndLeavesInferredOnesOut()
{
var old = Window(Day, 30); var current = Window(Day + Week * 2, 20);
var result = History(current, [old], [Token(Day), Token(Day + Week), Token(Day + Week * 2)], from: Day.AddDays(3));
Assert.Equal(2, result.Instances.Count); Assert.Equal(Day, result.Instances[1].Start);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.Single(History(current, [old], [], from: Day + Week).Instances);
Assert.Equal(old.SampleTime, result.FirstSample);
}
[Fact] public void JitterAndInterleavedOldRolloutAfterEarlyResetDoNotCreateAnotherInstance()
{
var transition = Day.AddHours(10).AddMinutes(48).AddSeconds(56);
var old = Window(Day.AddDays(-2), 90);
var current = Window(transition, 2);
var newFirst = current with { SampleTime = transition, UsedPercent = 0, ResetsAt = current.ResetsAt!.Value.AddSeconds(-11) };
var stale = old with { SampleTime = transition.AddSeconds(4), UsedPercent = 98, ResetsAt = old.ResetsAt!.Value.AddSeconds(9) };
var jitter = old with { SampleTime = old.SampleTime.AddHours(1), UsedPercent = 95, ResetsAt = old.ResetsAt.Value.AddSeconds(11) };
var result = History(current, [old, jitter, newFirst, stale], [Token(Day.AddDays(-2)), Token(Day.AddHours(10))]);
Assert.Equal(2, result.Instances.Count); Assert.Equal(95, result.Instances[1].Final.Used);
Assert.Equal(transition, result.Instances[1].End); Assert.Equal(1_000_000, result.Instances[0].Tokens.Total);
Assert.Equal(jitter.ResetsAt, result.Instances[1].Reset);
Assert.Equal(1_000_000, result.Instances[1].Tokens.Total);
Assert.DoesNotContain(result.Instances[1].BurnUp.Points, p => p.Used == 98);
}
[Fact] public void HistogramsUseLocalEndHourAndMondayBasedWeekday()
{
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +03", TimeSpan.FromHours(3), "Fixture", "Fixture");
var old = Window(Day); var transition = Day.AddDays(1).AddHours(22); // Saturday locally.
var result = History(Window(transition), [old], [], zone: zone);
Assert.Equal(1, result.EarlyByHour[1]); Assert.Equal(1, result.EarlyByHour.Sum());
Assert.Equal(1, result.EarlyByWeekday[5]); Assert.Equal(1, result.EarlyByWeekday.Sum());
}
[Theory]
[InlineData(15, false)]
[InlineData(16, true)]
public void EarlyThresholdIsStrictlyMoreThanFifteenMinutes(int minutes, bool early)
{
var old = Window(Day); var next = Window(Day + Week - TimeSpan.FromMinutes(minutes));
Assert.Equal(early, History(next, [old], []).Instances[1].Early);
}
}
+2 -2
View File
@@ -90,11 +90,11 @@ public class ReworkTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude()); var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
var log = new DiagnosticLog(); var log = new DiagnosticLog();
var store = new HistoryStore(directory.Path, log); var store = new HistoryStore(directory.Path, log, new TestClock());
var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await store.SaveAsync(TestContext.Current.CancellationToken); await store.SaveAsync(TestContext.Current.CancellationToken);
store = new(directory.Path, log); store = new(directory.Path, log, new TestClock());
scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path); scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None); using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
+7 -7
View File
@@ -10,14 +10,14 @@ public class StorageTests
{ {
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude()); var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude());
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex")); var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken); await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await history.SaveAsync(TestContext.Current.CancellationToken); await history.SaveAsync(TestContext.Current.CancellationToken);
history = new(directory.Path, new()); history = new(directory.Path, new(), new TestClock());
scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex")); scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken); await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken);
@@ -36,7 +36,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var fixture = Fixtures.Claude(); var fixture = Fixtures.Claude();
var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]); var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]);
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken); await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken);
@@ -79,7 +79,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude()); directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude());
var log = new DiagnosticLog(); var log = new DiagnosticLog();
var scanner = new IncrementalScanner(new(directory.Path, log), log, Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(new(directory.Path, log, new TestClock()), log, Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
Assert.Single(log.Recent); Assert.Single(log.Recent);
} }
@@ -89,7 +89,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\""); var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\"");
directory.Write("claude/projects/p/large.jsonl", line); directory.Write("claude/projects/p/large.jsonl", line);
var scanner = new IncrementalScanner(new(directory.Path, new()), new(), Path.Combine(directory.Path, "claude"), directory.Path); var scanner = new IncrementalScanner(new(directory.Path, new(), new TestClock()), new(), Path.Combine(directory.Path, "claude"), directory.Path);
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents); Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
} }
[Fact] [Fact]
@@ -123,7 +123,7 @@ public class StorageTests
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var log = new DiagnosticLog(); var log = new DiagnosticLog();
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log)); Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log));
Assert.Single(log.Recent); Assert.Empty(log.Recent);
var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } }; var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } };
await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken); await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(settings, SettingsFile.Load(directory.Path, new())); Assert.Equal(settings, SettingsFile.Load(directory.Path, new()));
@@ -159,7 +159,7 @@ public class StorageTests
public void QueriesAggregateByHourDayModelProjectAndLimitWindow() public void QueriesAggregateByHourDayModelProjectAndLimitWindow()
{ {
using var directory = new TestDirectory(); using var directory = new TestDirectory();
var history = new HistoryStore(directory.Path, new()); var history = new HistoryStore(directory.Path, new(), new TestClock());
var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero); var now = new DateTimeOffset(2026, 10, 14, 16, 30, 0, TimeSpan.Zero);
history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a")); history.Add(new(Provider.Claude, now.AddHours(-1), "a", "/one", new(Total: 10), "a"));
history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b")); history.Add(new(Provider.Claude, now, "b", "/two", new(Total: 20), "b"));
@@ -0,0 +1,161 @@
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class TokenEstimateTests
{
private static readonly DateTimeOffset Start = new(2026, 10, 8, 0, 0, 0, TimeSpan.Zero);
private static readonly DateTimeOffset Now = Start.AddDays(6).AddHours(12);
private static LimitWindow Window => new(Provider.Claude, "week", "Week · all models", 65, Start.AddDays(7), TimeSpan.FromDays(7), Now, "fixture");
private static ModelTokenPoint Token(DateTimeOffset time, long input = 100, string model = "claude-fable") => new(time, model, new(Input: input, Total: input));
private static ModelTokenPoint[] WeekTokens => Enumerable.Range(0, 6).Select(i => Token(Start.AddDays(i))).Append(Token(Start.AddDays(6), 50)).ToArray();
[Fact] public void ProviderWeightsDoNotDoubleCountCachedInputOrReasoning()
{
var counts = new TokenCounts(Input: 100, CacheRead: 40, CacheWrite: 20, Output: 10, ReasoningOutput: 8);
Assert.Equal(179, TokenWeights.Weighted(Provider.Claude, counts));
Assert.Equal(144, TokenWeights.Weighted(Provider.Codex, counts));
}
[Fact] public void NewestSampleCalibratesScaleAndDaysMixMeasuredAndEstimated()
{
var w = Window;
var baseline = w with { SampleTime = Start.AddDays(6), UsedPercent = 60 };
var result = LimitAnalysis.Analyze(w, [baseline], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Measured, result.Days.TodayOrigin);
Assert.Equal(10, result.Days.Current[0].Used); Assert.Equal(UseOrigin.Estimated, result.Days.Current[0].Origin);
Assert.Contains(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
Assert.Contains(result.Current.Points, p => p.Time == Now && p.Used == 65 && p.Origin == UseOrigin.Measured);
}
[Theory]
[InlineData(-1)]
[InlineData(1)]
public void DriftAndMissingBaselineFallBackToTokens(int drift)
{
var w = Window;
var result = LimitAnalysis.Analyze(w, [w with { ResetsAt = w.ResetsAt!.Value.AddMinutes(drift), SampleTime = Now.AddHours(-2), UsedPercent = 64 }], WeekTokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(5, result.Days!.Today); Assert.Equal(UseOrigin.Estimated, result.Days.TodayOrigin);
Assert.Contains(result.Current.Points, p => p.Used == 64 && p.Origin == UseOrigin.Measured);
Assert.Equal(.1, result.Current.Scale);
}
[Fact] public void FamilyWindowUsesOnlyMatchingModelsCaseInsensitively()
{
var w = Window with { Label = "Current week (FABLE)", UsedPercent = 50 };
var tokens = new[] { Token(Start, 100, "claude-fable-5"), Token(Start, 10000, "claude-sonnet"), Token(Start, 10000, "unrelated") };
Assert.Equal(.5, LimitAnalysis.Analyze(w, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
Assert.Equal(50d / 20100, LimitAnalysis.Analyze(w with { Label = "Week" }, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Theory]
[InlineData("Current week (Cedar)")]
[InlineData("Week \u00b7 Cedar")]
public void FamilyNamesAreNotLimitedToKnownModelNames(string label)
{
var window = Window with { Label = label, UsedPercent = 50 };
ModelTokenPoint[] tokens = [Token(Start, 100, "claude-CEDAR-7"), Token(Start, 10000, "claude-fable")];
Assert.Equal(.5, LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!.Current.Scale);
}
[Fact] public void FinishedInstancesUseOwnSampleOrCurrentScale()
{
var w = Window with { UsedPercent = 50 };
var tokens = new[] { Token(Start, 100), Token(Start.AddDays(-7), 100), Token(Start.AddDays(-14), 300) };
var previous = w with { ResetsAt = Start, SampleTime = Start.AddHours(-1), UsedPercent = 90 };
var result = LimitAnalysis.Analyze(w, [previous], tokens, Now, TimeZoneInfo.Utc)!;
Assert.Equal(.5, result.Current.Scale); Assert.Equal(.9, result.Past[0].Scale); Assert.Equal(90, result.Past[0].Peak);
Assert.Equal(.5, result.Past[1].Scale); Assert.Equal(100, result.Past[1].Peak); Assert.NotNull(result.Past[1].ReachedLimit);
Assert.All(result.Past[1].Points.Skip(1), p => Assert.Equal(UseOrigin.Estimated, p.Origin));
}
[Fact] public void ExpiredInstanceNeverConsumesTokensFromTheNextWindow()
{
var window = Window;
var afterReset = window.ResetsAt!.Value.AddHours(1);
var tokens = WeekTokens.Append(Token(afterReset, 1000000)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, afterReset.AddHours(1), TimeZoneInfo.Utc)!;
Assert.All(result.Current.Points, p => Assert.True(p.Time <= window.ResetsAt));
Assert.Equal(65, result.Current.Peak);
}
[Fact] public void NewTokensAfterTheLastSampleAddOnlyTheNewBucket()
{
var window = Window with { SampleTime = Now.AddMinutes(-30) };
var tokens = WeekTokens.Append(Token(Now, 100)).ToArray();
var result = LimitAnalysis.Analyze(window, [], tokens, Now.AddMinutes(30), TimeZoneInfo.Utc)!;
Assert.Equal(.1, result.Current.Scale);
Assert.Equal(75, result.Current.Points.Last().Used);
Assert.Equal(UseOrigin.Estimated, result.Current.Points.Last().Origin);
}
[Fact] public void EstimatesStopAtTheCrossingAndDailyUseCannotSpendTheLimitTwice()
{
var window = Window with { UsedPercent = 50 };
var pastStart = Start.AddDays(-7);
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 300), Token(pastStart.AddDays(1), 300)];
var result = LimitAnalysis.Analyze(window, [], tokens, Now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.Equal(100, past.Peak);
Assert.Equal(pastStart.AddMinutes(40), past.ReachedLimit);
Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.All(past.Points, p => Assert.InRange(p.Used, 0, 100));
Assert.Contains(past.Points, p => p.Time == past.ReachedLimit && p.Used == 100);
Assert.Equal(100, past.Days.Sum(d => d.Used ?? 0));
Assert.Equal(0, past.Days[1].Used);
}
[Fact] public void MeasuredSamplesRemainUnchangedWhenLaterEstimatesReachTheLimit()
{
var window = Window;
var pastStart = Start.AddDays(-7);
var measured = window with { ResetsAt = Start, SampleTime = pastStart.AddHours(2), UsedPercent = 10 };
ModelTokenPoint[] tokens = [Token(Start, 100), Token(pastStart, 100), Token(pastStart.AddDays(1), 10000)];
var past = LimitAnalysis.Analyze(window, [measured], tokens, Now, TimeZoneInfo.Utc)!.Past[0];
Assert.Equal(100, past.Peak); Assert.Equal(UseOrigin.Estimated, past.ReachedOrigin);
Assert.Equal(new(measured.SampleTime, 10, UseOrigin.Measured), past.Points.Single(p => p.Time == measured.SampleTime));
Assert.Equal(10, measured.UsedPercent);
Assert.Equal(pastStart.AddDays(1).AddMinutes(5.4), past.ReachedLimit);
Assert.All(past.Days, day => Assert.InRange(day.Used ?? 0, 0, 100));
Assert.Equal(100, past.Days.Sum(day => day.Used ?? 0));
}
[Fact] public void EarlyReplacementEndsThePreviousInstanceAndOwnsItsBoundaryHour()
{
var transition = new DateTimeOffset(2026, 10, 15, 8, 18, 0, TimeSpan.Zero);
var now = transition.AddHours(1);
var current = Window with { ResetsAt = transition.AddDays(7), SampleTime = now, UsedPercent = 2 };
var first = current with { SampleTime = transition, UsedPercent = 1 };
var previous = current with { ResetsAt = transition.AddDays(5), SampleTime = transition.AddDays(-1), UsedPercent = 20 };
var previousStart = previous.ResetsAt!.Value - previous.Length!.Value;
ModelTokenPoint[] tokens = [Token(previousStart, 100), Token(transition.AddMinutes(-18), 100), Token(transition.AddMinutes(42), 1000)];
var result = LimitAnalysis.Analyze(current, [previous, first], tokens, now, TimeZoneInfo.Utc)!;
var past = result.Past[0];
Assert.All(past.Points, p => Assert.True(p.Time <= transition));
Assert.All(past.Days, d => Assert.True(d.End <= transition));
Assert.Equal(transition, past.End);
Assert.Equal(previousStart, past.Start);
Assert.Equal(20, past.Points.Single(p => p.Time == previous.SampleTime).Used);
Assert.Equal(20, past.Peak);
Assert.Equal(2d / 1100, result.Current.Scale);
Assert.DoesNotContain(result.Past, p => p.Points.Any(v => v.Time > transition));
}
[Theory]
[InlineData(5)]
[InlineData(168)]
public void ForecastsBeginAtExactlyTwoPercentWithoutChangingState(int hours)
{
var start = Start; var length = TimeSpan.FromHours(hours);
var atThreshold = start + TimeSpan.FromTicks(length.Ticks / 50);
var before = atThreshold.AddTicks(-1);
var window = Window with { ResetsAt = start + length, Length = length, SampleTime = before, UsedPercent = 11 };
Assert.Equal(PaceState.OnTrack, Pace.Calculate(window, before).State);
var pace = Pace.Calculate(window, before);
Assert.Null(pace.Projection);
var popup = new PopupDecider().Observe(window, pace, new Settings());
Assert.Null(popup);
Assert.Null(LimitAnalysis.AverageUseAtReset(window, before));
Assert.Null(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], before));
window = window with { SampleTime = atThreshold };
Assert.NotNull(Pace.Calculate(window, atThreshold).Projection);
Assert.NotNull(LimitAnalysis.AverageUseAtReset(window, atThreshold));
if (hours == 168) Assert.NotNull(LimitAnalysis.Recent(window, [window with { SampleTime = start, UsedPercent = 0 }], atThreshold));
}
[Fact] public void NoTokensMeansNoEstimates()
{
var result = LimitAnalysis.Analyze(Window, [], [], Now, TimeZoneInfo.Utc)!;
Assert.Null(result.Current.Scale); Assert.Null(result.Days!.Today); Assert.Empty(result.Past);
Assert.DoesNotContain(result.Current.Points, p => p.Origin == UseOrigin.Estimated);
}
}
@@ -0,0 +1,59 @@
using System.Text.Json;
using Xunit;
namespace FinalToken.Core.Tests;
public sealed class WeekTotalsTests
{
[Theory]
[InlineData("limit", true)]
[InlineData("family", false)]
[InlineData("expired", false)]
[InlineData("missing", false)]
[InlineData("mixed", true)]
public async Task EngineSelectsProviderWeekOrCalendarFallback(string kind, bool limit)
{
using var directory = new TestDirectory();
var clock = new WeekClock(); var now = clock.GetUtcNow();
await using var engine = new RefreshEngine(directory.Path, clock, claudeDirectory: directory.Path, codexDirectory: directory.Path,
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
var week = new LimitWindow(Provider.Codex, "week", "Week", 30, start.AddDays(7), TimeSpan.FromDays(7), now, "fixture");
var family = week with { Id = "family", Label = "Week (Fable)", Length = TimeSpan.FromDays(8) };
engine.History.AddLimits(kind switch
{
"limit" => [week], "family" => [family], "expired" => [week with { ResetsAt = now.AddHours(-1) }],
"mixed" => [family, week, week with { Id = "short", Length = TimeSpan.FromDays(2) }], _ => []
});
foreach (var (time, count) in new[] { (now.AddDays(-5), 10), (now.AddDays(-3), 20), (now.AddDays(-1), 30) })
engine.History.Add(new(Provider.Codex, time, "fixture", "fixture", new(Total: count), count.ToString()));
var snapshot = await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken);
var provider = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
Assert.Equal(limit ? 50 : 30, provider.Week.Total);
Assert.Equal(limit ? start : new DateTimeOffset(2026, 10, 12, 0, 0, 0, TimeSpan.Zero), provider.WeekStart);
Assert.Equal(limit ? "week" : null, provider.WeekWindow);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void SourceGeneratedJsonReadsNewAndLegacyWeekFields(bool limit)
{
var start = new DateTimeOffset(2026, 10, 10, 22, 40, 0, TimeSpan.Zero);
var snapshot = new Snapshot { MadeAt = start.AddDays(2), RefreshInterval = TimeSpan.FromMinutes(1),
Providers = [new(Provider.Codex, ProviderStatus.Available, null, [], new(), null, new(Total: 30), start, limit ? "week" : null)] };
var json = JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot);
Assert.Contains("\"weekStart\"", json);
Assert.Equal(limit, json.Contains("\"weekWindow\"", StringComparison.Ordinal));
var provider = Assert.Single(JsonSerializer.Deserialize(json, CoreJsonContext.Default.Snapshot)!.Providers);
Assert.Equal(start, provider.WeekStart); Assert.Equal(limit ? "week" : null, provider.WeekWindow);
const string old = """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[{"provider":1,"status":0,"windows":[],"today":{},"session":null,"week":{"total":30}}]}""";
var legacy = JsonSerializer.Deserialize(old, CoreJsonContext.Default.Snapshot)!;
Assert.Equal(1, legacy.V); Assert.Equal(30, legacy.Providers[0].Week.Total);
Assert.Equal(default, legacy.Providers[0].WeekStart); Assert.Null(legacy.Providers[0].WeekWindow);
}
private sealed class WeekClock : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
public override TimeZoneInfo LocalTimeZone => TimeZoneInfo.Utc;
}
}
+2
View File
@@ -0,0 +1,2 @@
# Synthetic CLI
Only a deterministic provider-free test executable. Never point this at a real provider config directory. Emit fixed metadata and test URLs; do not call a network or handle actual provider credentials.
@@ -0,0 +1 @@
<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType></PropertyGroup></Project>
+54
View File
@@ -0,0 +1,54 @@
using System.Text.Json;
// Test-only CLI. identity.txt contains a synthetic email, never a provider credential.
var home=Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR") ?? Environment.GetEnvironmentVariable("CODEX_HOME");
if(home is null) return 2;
Directory.CreateDirectory(home);
var identity=Path.Combine(home,"identity.txt");
if(args is ["auth","login",..])
{
if(File.Exists(Path.Combine(home,"overflow-login")))
{
Console.Write(new string('x',128*1024));Console.Out.Flush();
_=Console.ReadLine();return 1;
}
Console.Write("https://claude.ai/oauth/authorize?state=fixture-state\nPaste code here if prompted: ");
Console.Out.Flush();
var response=Console.ReadLine();
if(response is not ("fixture-code#fixture-state" or "wrong-code#fixture-state")) return 1;
File.WriteAllText(identity,response.StartsWith("wrong",StringComparison.Ordinal)?"[email protected]":"[email protected]");
Console.WriteLine("Login successful");return 0;
}
if(args is ["auth","status",..])
{
if(!File.Exists(identity)){Console.WriteLine("{\"loggedIn\":false}");return 1;}
var email=File.ReadAllText(identity);
Console.WriteLine(email=="[email protected]"?"{\"loggedIn\":true,\"email\":\"[email protected]\"}":"{\"loggedIn\":true,\"email\":\"[email protected]\"}");return 0;
}
if(args is ["login","--device-auth"])
{
Console.WriteLine("\u001b[94mhttps://auth.openai.com/codex/device\u001b[0m\n\u001b[94mABCD-12345\u001b[0m");
while(!File.Exists(Path.Combine(home,"authorize-device")))await Task.Delay(50);
File.WriteAllText(identity,"[email protected]");return 0;
}
if(args is ["app-server"])
{
while(Console.ReadLine() is {} line)
{
using var json=JsonDocument.Parse(line);
var root=json.RootElement;
if(!root.TryGetProperty("id",out var id))continue;
var number=id.GetInt32();
var method=root.GetProperty("method").GetString();
if(method=="initialize")Console.WriteLine("{\"id\":1,\"result\":{}}");
else if(method=="account/read")
Console.WriteLine(File.Exists(identity)?"{\"id\":2,\"result\":{\"account\":{\"type\":\"chatgpt\",\"email\":\"[email protected]\"}}}":"{\"id\":2,\"result\":{\"account\":null}}");
else if(method=="account/rateLimits/read")
{
var reset=DateTimeOffset.UtcNow.AddDays(3).ToUnixTimeSeconds();
Console.WriteLine($"{{\"id\":{number},\"result\":{{\"rateLimits\":{{\"limitId\":\"codex\",\"secondary\":{{\"usedPercent\":65,\"windowDurationMins\":10080,\"resetsAt\":{reset}}}}}}}}}");
}
else return 2;
}
}
return 0;
+2
View File
@@ -0,0 +1,2 @@
# Fleet tests
Use synthetic metadata and fake CLI adapters. Cover account quota selection, source identity deduplication, reset forecasts, stale data, and session/profile login routing. No live provider credentials or login required.
@@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><IsTestProject>true</IsTestProject><UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner><TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport></PropertyGroup>
<ItemGroup><PackageReference Include="xunit.v3.aot.mtp-v2" /><ProjectReference Include="../../src/FinalToken.Fleet/FinalToken.Fleet.csproj" /></ItemGroup>
</Project>
+224
View File
@@ -0,0 +1,224 @@
using System.Text.Json;
using FinalToken.Core;
using FinalToken.Fleet;
using Xunit;
namespace FinalToken.Fleet.Tests;
public sealed class FleetTests
{
private static readonly DateTimeOffset Now = new(2026, 11, 14, 12, 0, 0, TimeSpan.Zero);
internal static ServerConfig Config(Provider provider = Provider.Claude) => new(
[new("personal", provider, "Personal", "[email protected]")],
[new("a", "Desktop", "tester", [new("main", "personal")]), new("b", "LXC", "tester", [new("main", "personal")])]);
internal static LimitWindow Week(double used = 60, DateTimeOffset? sample = null) => new(Provider.Claude, "week", "Week", used,
Now.AddDays(3.5), TimeSpan.FromDays(7), sample ?? Now, "fixture");
internal static ProfileReport Profile(IReadOnlyList<SourceUsage>? usage = null, IReadOnlyList<LimitWindow>? limits = null, Provider provider = Provider.Claude) =>
new("main", provider, new("Healthy", "[email protected]", Now, "CLI identity"), new(), usage ?? [], limits ?? [], [], DataEmail: "[email protected]");
internal static MachineState Machine(string id, ProfileReport profile, DateTimeOffset? seen = null, string boot = "boot") =>
new(id, seen ?? Now, new(id, "tester", boot, Now, [profile], []));
private static AccountView Analyze(ProfileReport a, ProfileReport? b = null, ServerConfig? config = null, DateTimeOffset? now = null) =>
FleetAnalysis.Build(config ?? Config(a.Provider), new(b is null ? [Machine("a", a)] : [Machine("a", a), Machine("b", b)]), now ?? Now).Accounts.Single();
[Fact] public void SameAccountQuotaIsNeverSummedAcrossMachines()
{
var a = Profile(limits: [Week(60)]); var b = Profile(limits: [Week(59, Now.AddMinutes(-1))]);
var view = Analyze(a, b);
Assert.Single(view.Windows); Assert.Equal(60, view.Windows[0].Window.UsedPercent);
Assert.Equal(120d, view.Windows[0].UseAtReset); Assert.Equal(-20d, view.Windows[0].RemainingAtReset);
Assert.Equal(Now.AddDays(7d / 3), view.Windows[0].Pace.Projection);
}
[Fact] public void ClaudeResponseIsCountedOnceAcrossMachinesAndRetries()
{
SourceUsage u = new("response-1", null, Now, "claude-opus-4-6", new(Input: 100, Total: 100));
var account = Analyze(Profile([u, u]), Profile([u]));
Assert.Equal(100, account.Total.Total); Assert.Equal(.0005m, account.ApiValue);
}
[Fact] public void CodexSessionCopiesUseOrderedCumulativeIncreases()
{
SourceUsage first = new("s:100", "s", Now.AddHours(-2), "gpt-5.4", new(Input: 100, Total: 100));
var second = first with { Key = "s:180", Time = Now.AddHours(-1), Counts = new(Input: 180, Total: 180) };
var view = Analyze(Profile([second, first], provider: Provider.Codex), Profile([first, second], provider: Provider.Codex));
Assert.Equal(180, view.Total.Total);
}
[Fact] public void CodexCounterResetDoesNotEraseLaterUsage()
{
SourceUsage first = new("one", "s", Now.AddHours(-3), "gpt-5.4", new(Input: 100, Total: 100));
var reset = first with { Key = "two", Time = Now.AddHours(-2), Counts = new(Input: 10, Total: 10) };
var next = first with { Key = "three", Time = Now.AddHours(-1), Counts = new(Input: 30, Total: 30) };
Assert.Equal(120, Analyze(Profile([first, reset, next], provider: Provider.Codex)).Total.Total);
}
[Fact] public void ConflictingResponseMetadataIsExcludedAndDiagnosed()
{
SourceUsage u = new("same", null, Now, null, new(Total: 10));
var view = Analyze(Profile([u]), Profile([u with { Counts = new(Total: 20) }]));
Assert.Equal(0, view.Total.Total); Assert.Contains(view.Warnings, w => w.Contains("Conflicting"));
}
[Fact] public void StaleQuotaDoesNotFabricateForecastOrZero()
{
var view = Analyze(Profile(limits: [Week(75, Now.AddHours(-1))]));
Assert.True(view.Windows[0].Stale); Assert.Equal(75, view.Windows[0].Window.UsedPercent);
Assert.Null(view.Windows[0].UseAtReset); Assert.Null(view.Windows[0].Analysis);
}
[Fact] public void ExpiredResetHasNoFutureProjection()
{
var view = Analyze(Profile(limits: [Week() with { ResetsAt = Now }]));
Assert.True(view.Windows[0].Stale); Assert.Null(view.Windows[0].Pace.Projection);
}
[Fact] public void EarlyForecastRemainsUnknownBelowEligibility()
{
var week = Week(1) with { ResetsAt = Now.AddDays(7).AddMinutes(-10) };
Assert.Null(Analyze(Profile(limits: [week])).Windows[0].UseAtReset);
}
[Fact] public void AheadEarlyWeekRetainsExistingD7Warning()
{
var week = Week(39) with { ResetsAt = Now.AddDays(7).AddHours(-10) };
var view = Analyze(Profile(limits: [week])).Windows[0];
Assert.Equal(PaceState.Ahead, view.Pace.State); Assert.NotNull(view.Pace.Projection);
}
[Fact] public void RecentForecastRequiresThreeHoursAndSameReset()
{
var week = Week(60);
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-3) }, week])).Windows[0];
Assert.NotNull(view.Recent); Assert.Equal(80, view.Recent.PercentPerDay);
var shortSpan = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = Now.AddHours(-2) }, week])).Windows[0];
Assert.Null(shortSpan.Recent);
}
[Fact] public void DailyBudgetAndPartialDaysComeFromExistingAnalysis()
{
var week = Week(); var midnight = new DateTimeOffset(2026, 11, 14, 0, 0, 0, TimeSpan.Zero);
var view = Analyze(Profile(limits: [week with { UsedPercent = 50, SampleTime = midnight }, week])).Windows[0];
Assert.NotNull(view.Analysis?.Days); Assert.Equal(12.5, view.Analysis.Days.TodayBudget);
Assert.Equal(10, view.Analysis.Days.Today); Assert.Equal(7, view.Analysis.Days.Current.Count);
}
[Fact] public void LoggedOutProfileRetainsAttributedHistoryAndWithholdsForecast()
{
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { Auth = new("Unavailable", null, Now, "Signed out") };
var view = Analyze(p); Assert.Equal(42, view.Total.Total); Assert.True(view.Windows[0].Stale);
}
[Fact] public void WrongAccountCannotContributeToConfiguredAccount()
{
var p = Profile([new("one", null, Now, null, new(Total: 42))], [Week()]) with { DataEmail = "[email protected]" };
var view = Analyze(p); Assert.Empty(view.Windows); Assert.Equal(0, view.Total.Total);
Assert.False(view.HasConsumptionData);
}
[Fact] public void UnknownModelsRemainUnpricedAndDoNotImplyAllowance()
{
var view = Analyze(Profile([new("one", null, Now, "unknown-model", new(Total: 42))]));
Assert.Null(view.ApiValue); Assert.Equal(42, view.UnpricedTokens); Assert.Empty(view.Windows);
}
[Fact] public void LegacyHistoryUsesOneSourceAndNonOverlappingCutoff()
{
var cutoff = Now.AddDays(-1); var cfg = Config();
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
var raw = new SourceUsage("one", null, cutoff, null, new(Total: 7));
var a = Profile([raw, raw with { Key = "old", Time = cutoff.AddHours(-1) }]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 100)), new(cutoff, null, new(Total: 999))] };
var b = Profile([raw]) with { LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 200))] };
Assert.Equal(107, Analyze(a,b,cfg).Total.Total);
}
[Theory]
[InlineData("[email protected]", Provider.Claude)]
[InlineData(null, Provider.Claude)]
[InlineData("[email protected]", Provider.Codex)]
public void LegacyHistoryMustBelongToTheConfiguredAccount(string? email, Provider provider)
{
var cutoff = Now.AddDays(-1); var cfg = Config();
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
var p = Profile(provider: provider) with { DataEmail = email,
LegacyTokens = [new(cutoff.AddHours(-1), "claude-opus-4-6", new(Input: 100, Total: 100))] };
var view = Analyze(p, config: cfg);
Assert.Equal(0, view.Total.Total); Assert.Empty(view.Tokens); Assert.Null(view.ApiValue);
Assert.False(view.HasConsumptionData);
Assert.Contains(view.Warnings, w => w.Contains("legacy", StringComparison.OrdinalIgnoreCase) &&
w.Contains("unverified", StringComparison.OrdinalIgnoreCase));
}
[Fact] public void LoggedOutLegacySourceRetainsPreviouslyVerifiedAttribution()
{
var cutoff = Now.AddDays(-1); var cfg = Config();
cfg = cfg with { Accounts = [cfg.Accounts[0] with { LegacyMachine = "a", LegacyProfile = "main", HistoryBefore = cutoff }] };
var p = Profile() with { Auth = new("Unavailable", null, Now, "Signed out"),
LegacyTokens = [new(cutoff.AddHours(-1), null, new(Total: 100))] };
Assert.Equal(100, Analyze(p, config: cfg).Total.Total);
}
[Fact] public void DashboardJsonRoundTripsWithoutReflection()
{
var view = FleetAnalysis.Build(Config(),new([Machine("a",Profile(limits:[Week()]))]),Now);
var json = JsonSerializer.Serialize(view,FleetJsonContext.Default.DashboardView);
Assert.Contains("useAtReset",json); Assert.Contains("Ahead",json);
Assert.NotNull(JsonSerializer.Deserialize(json,FleetJsonContext.Default.DashboardView));
}
[Fact] public async Task StorePersistsOfflineMetadataButNeverLoginPayloads()
{
var path = Path.Combine(Path.GetTempPath(), "finaltoken-fleet-" + Guid.NewGuid().ToString("N"));
try
{
var store = new FleetStore(path, Config()); var report = Machine("a",Profile()).Report with { Logins = [new("id","main","WaitingForCode","https://claude.ai/oauth/authorize?state=secret")] };
await store.AcceptAsync(report,"a",Now,TestContext.Current.CancellationToken);
Assert.DoesNotContain("secret",File.ReadAllText(Path.Combine(path,"fleet.json")));
var loaded = new FleetStore(path,Config()).Dashboard(Now.AddMinutes(2));
Assert.False(loaded.Machines[0].Online); Assert.NotNull(loaded.Machines[0].SeenAt);
}
finally { if(Directory.Exists(path)) Directory.Delete(path,true); }
}
[Fact] public void MachineUserAndProfileAreValidatedAtTrustBoundary()
{
var path=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); var store=new FleetStore(path,Config());
var report=Machine("a",Profile()).Report;
Assert.Throws<InvalidDataException>(()=>store.Validate(report,"b",Now));
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {OsUser="root"},"a",Now));
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Id="other"}]},"a",Now));
}
[Fact] public async Task EmptyRestartHeartbeatCannotErasePreviouslyAttributedHistory()
{
var path=Path.Combine(Path.GetTempPath(),"finaltoken-fleet-"+Guid.NewGuid().ToString("N"));
try
{
var store=new FleetStore(path,Config());
var original=Machine("a",Profile([new("one",null,Now,null,new(Total:42))],[Week()])).Report;
await store.AcceptAsync(original,"a",Now,TestContext.Current.CancellationToken);
var restart=original with {BootId="new",CollectedAt=Now.AddSeconds(1),Profiles=[Profile() with {DataEmail=null,Auth=new("Unknown",null,Now,"Starting")}]};
await store.AcceptAsync(restart,"a",Now.AddSeconds(1),TestContext.Current.CancellationToken);
var account=store.Dashboard(Now.AddSeconds(1)).Accounts.Single();
Assert.Equal(42,account.Total.Total);Assert.True(account.Windows.Single().Stale);
}
finally {if(Directory.Exists(path))Directory.Delete(path,true);}
}
[Fact] public void CodexLegacyCutoffMustRetainPreCutoffCumulativeBaseline()
{
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
SourceUsage old=new("old","session",cutoff.AddHours(-1),null,new(Total:100));
var next=old with {Key="next",Time=cutoff,Counts=new(Total:180)};
var p=Profile([old,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
Assert.Equal(180,Analyze(p,config:cfg).Total.Total);
}
[Fact] public void SharedResponseSessionAttributionDoesNotMultiplyAccountConsumption()
{
SourceUsage u=new("response","session-a",Now,null,new(Total:100));
var view=Analyze(Profile([u]),Profile([u with {Session="session-b"}]));
Assert.Equal(100,view.Total.Total);Assert.Single(view.Sessions);Assert.Equal(100,view.Sessions[0].Tokens.Total);
}
[Fact] public void DisabledProfileCannotPresentLiveForecast()
{
var settings=new Settings {Claude=new ProviderSettings {Enabled=false}};
var view=Analyze(Profile(limits:[Week()]) with {Settings=settings});
Assert.True(view.Windows.Single().Stale);Assert.Null(view.Windows.Single().UseAtReset);
}
[Fact] public void MissingCodexMigrationBaselineCannotDoubleChargeUnknownPreCutoffUsage()
{
var cutoff=Now.AddDays(-1);var cfg=Config(Provider.Codex);
cfg=cfg with {Accounts=[cfg.Accounts[0] with {LegacyMachine="a",LegacyProfile="main",HistoryBefore=cutoff}]};
SourceUsage first=new("first","session",cutoff,null,new(Total:180));
var next=first with {Key="next",Time=cutoff.AddHours(1),Counts=new(Total:200)};
var p=Profile([first,next],provider:Provider.Codex) with {LegacyTokens=[new(cutoff.AddHours(-1),null,new(Total:100))]};
var view=Analyze(p,config:cfg);
Assert.Equal(120,view.Total.Total);Assert.Contains(view.Warnings,w=>w.Contains("baseline"));
}
[Fact] public void MalformedNestedMetadataIsRejectedBeforePersistence()
{
var store=new FleetStore(Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")),Config());
var report=Machine("a",Profile()).Report;
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Profiles=[Profile() with {Auth=new("Healthy",null,Now,null!)}]},"a",Now));
Assert.Throws<InvalidDataException>(()=>store.Validate(report with {Logins=[null!]},"a",Now));
}
}

Some files were not shown because too many files have changed in this diff Show More