From f8afd11679dec7580ef9cfd858c23654c0cc8e88 Mon Sep 17 00:00:00 2001 From: Florian Schmidt Date: Wed, 14 Oct 2026 22:11:19 +0200 Subject: [PATCH] feat: add FinalToken v1 for Claude and Codex usage (#2) FinalToken v1: a NativeAOT tray app for Windows 11 and CachyOS that tracks Claude Code and Codex usage and limits through their CLIs only, with no provider sign-in and no tokens (R1-R7, D1-D11). - Core: incremental collectors for Claude transcripts and Codex rollouts, limit probes through `claude -p /usage` and `codex app-server`, a journaled history store, the refresh engine, pace and popup decisions, and the snapshot.json contract. - App (Avalonia): stats panel with limit bars, pace, projections, token totals, charts, limit history and breakdowns; tray, settings, non-activating pace popups, single-instance activation, start with the OS, and the Off/Ask/Automatic Stream Deck plugin install. - Stream Deck plugin (SDK v2, NativeAOT) for Elgato and OpenDeck. - finaltoken-cli, tools/publish.py, the documentation check and the agent review workflow. Closes #1 --- .agents/mind/gotchas.md | 6 + .agents/mind/index.md | 14 + .editorconfig | 16 + .gitea/pull_request_template.md | 11 + .gitignore | 8 + AGENTS.md | 141 +++++++ CLAUDE.md | 1 + Directory.Build.props | 18 + Directory.Packages.props | 12 + FinalToken.slnx | 15 + README.md | 55 +++ docs/agents/review.md | 70 ++++ docs/decisions.md | 239 +++++++++++ docs/requirements.md | 14 + global.json | 4 + src/FinalToken.App/AGENTS.md | 10 + src/FinalToken.App/CLAUDE.md | 1 + src/FinalToken.App/Charts.cs | 114 ++++++ src/FinalToken.App/DesktopApp.cs | 187 +++++++++ src/FinalToken.App/FinalToken.App.csproj | 15 + src/FinalToken.App/OsStartup.cs | 35 ++ src/FinalToken.App/PanelViewModel.cs | 88 +++++ src/FinalToken.App/PanelWindow.cs | 130 ++++++ src/FinalToken.App/Popups.cs | 71 ++++ src/FinalToken.App/Program.cs | 37 ++ src/FinalToken.App/SettingsWindow.cs | 58 +++ src/FinalToken.App/WindowsActivation.cs | 55 +++ src/FinalToken.Cli/AGENTS.md | 6 + src/FinalToken.Cli/CLAUDE.md | 1 + src/FinalToken.Cli/CliApplication.cs | 52 +++ src/FinalToken.Cli/FinalToken.Cli.csproj | 8 + src/FinalToken.Cli/Program.cs | 3 + src/FinalToken.Core/AGENTS.md | 64 +++ src/FinalToken.Core/AtomicFile.cs | 81 ++++ src/FinalToken.Core/CLAUDE.md | 1 + src/FinalToken.Core/CalendarDays.cs | 26 ++ .../Collectors/ClaudeUsageParser.cs | 61 +++ .../Collectors/IncrementalScanner.cs | 136 +++++++ src/FinalToken.Core/Collectors/JsonFields.cs | 33 ++ src/FinalToken.Core/Collectors/LimitProbe.cs | 34 ++ .../Collectors/RolloutParser.cs | 88 +++++ .../Collectors/TranscriptParser.cs | 28 ++ src/FinalToken.Core/FinalToken.Core.csproj | 1 + src/FinalToken.Core/HistoryPersistence.cs | 132 +++++++ src/FinalToken.Core/HistoryStore.cs | 372 ++++++++++++++++++ src/FinalToken.Core/Model.cs | 61 +++ src/FinalToken.Core/Pace.cs | 49 +++ src/FinalToken.Core/Processes/CliDiscovery.cs | 86 ++++ .../Processes/ProcessRunner.cs | 115 ++++++ src/FinalToken.Core/RefreshEngine.cs | 235 +++++++++++ src/FinalToken.Core/Settings.cs | 66 ++++ src/FinalToken.Core/Snapshot.cs | 49 +++ src/FinalToken.Core/StreamDeck/Installer.cs | 21 + .../StreamDeck/PluginInstaller.cs | 202 ++++++++++ src/FinalToken.StreamDeck/AGENTS.md | 8 + src/FinalToken.StreamDeck/CLAUDE.md | 1 + .../FinalToken.StreamDeck.csproj | 8 + src/FinalToken.StreamDeck/Program.cs | 77 ++++ src/FinalToken.StreamDeck/Protocol.cs | 150 +++++++ src/FinalToken.StreamDeck/README.md | 35 ++ src/FinalToken.StreamDeck/StatRenderer.cs | 69 ++++ .../plugin/images/icon.svg | 1 + .../plugin/images/key.svg | 1 + .../plugin/inspector/index.html | 5 + .../plugin/inspector/inspector.js | 27 ++ .../plugin/inspector/style.css | 1 + .../plugin/manifest.json | 24 ++ tests/FinalToken.App.Tests/AGENTS.md | 7 + tests/FinalToken.App.Tests/CLAUDE.md | 1 + .../FinalToken.App.Tests.csproj | 13 + tests/FinalToken.App.Tests/FormattingTests.cs | 71 ++++ tests/FinalToken.App.Tests/HeadlessTests.cs | 144 +++++++ tests/FinalToken.App.Tests/ViewModelTests.cs | 89 +++++ tests/FinalToken.Cli.Tests/AGENTS.md | 4 + tests/FinalToken.Cli.Tests/CLAUDE.md | 1 + tests/FinalToken.Cli.Tests/CliTests.cs | 122 ++++++ .../FinalToken.Cli.Tests.csproj | 12 + tests/FinalToken.Core.Tests/AGENTS.md | 4 + tests/FinalToken.Core.Tests/CLAUDE.md | 1 + .../DiscoveryAndPolicyTests.cs | 88 +++++ tests/FinalToken.Core.Tests/EngineTests.cs | 160 ++++++++ .../FinalToken.Core.Tests.csproj | 19 + .../FinalToken.Core.Tests/IntegrationTests.cs | 121 ++++++ tests/FinalToken.Core.Tests/PaceTests.cs | 73 ++++ tests/FinalToken.Core.Tests/ParserTests.cs | 107 +++++ .../PartialSettingsTests.cs | 95 +++++ tests/FinalToken.Core.Tests/ProcessTests.cs | 39 ++ .../ReviewRegressionTests.cs | 141 +++++++ tests/FinalToken.Core.Tests/ReworkTests.cs | 265 +++++++++++++ tests/FinalToken.Core.Tests/StorageTests.cs | 192 +++++++++ .../StreamDeck/InstallerTests.cs | 129 ++++++ tests/FinalToken.Core.Tests/TestSupport.cs | 95 +++++ tests/FinalToken.ProcessHost/AGENTS.md | 8 + tests/FinalToken.ProcessHost/CLAUDE.md | 1 + .../FinalToken.ProcessHost.csproj | 7 + tests/FinalToken.ProcessHost/Program.cs | 104 +++++ tests/FinalToken.StreamDeck.Tests/AGENTS.md | 5 + tests/FinalToken.StreamDeck.Tests/CLAUDE.md | 1 + .../FinalToken.StreamDeck.Tests.csproj | 12 + .../PluginTests.cs | 165 ++++++++ tools/agent-review.sh | 33 ++ tools/docs/check_docs.py | 127 ++++++ tools/docs/test_check_docs.py | 93 +++++ tools/gitea.sh | 82 ++++ tools/publish.py | 75 ++++ tools/test_publish.py | 34 ++ 106 files changed, 6583 insertions(+) create mode 100644 .agents/mind/gotchas.md create mode 100644 .agents/mind/index.md create mode 100644 .editorconfig create mode 100644 .gitea/pull_request_template.md create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 CLAUDE.md create mode 100644 Directory.Build.props create mode 100644 Directory.Packages.props create mode 100644 FinalToken.slnx create mode 100644 docs/agents/review.md create mode 100644 docs/decisions.md create mode 100644 docs/requirements.md create mode 100644 global.json create mode 100644 src/FinalToken.App/AGENTS.md create mode 100644 src/FinalToken.App/CLAUDE.md create mode 100644 src/FinalToken.App/Charts.cs create mode 100644 src/FinalToken.App/DesktopApp.cs create mode 100644 src/FinalToken.App/FinalToken.App.csproj create mode 100644 src/FinalToken.App/OsStartup.cs create mode 100644 src/FinalToken.App/PanelViewModel.cs create mode 100644 src/FinalToken.App/PanelWindow.cs create mode 100644 src/FinalToken.App/Popups.cs create mode 100644 src/FinalToken.App/Program.cs create mode 100644 src/FinalToken.App/SettingsWindow.cs create mode 100644 src/FinalToken.App/WindowsActivation.cs create mode 100644 src/FinalToken.Cli/AGENTS.md create mode 100644 src/FinalToken.Cli/CLAUDE.md create mode 100644 src/FinalToken.Cli/CliApplication.cs create mode 100644 src/FinalToken.Cli/FinalToken.Cli.csproj create mode 100644 src/FinalToken.Cli/Program.cs create mode 100644 src/FinalToken.Core/AGENTS.md create mode 100644 src/FinalToken.Core/AtomicFile.cs create mode 100644 src/FinalToken.Core/CLAUDE.md create mode 100644 src/FinalToken.Core/CalendarDays.cs create mode 100644 src/FinalToken.Core/Collectors/ClaudeUsageParser.cs create mode 100644 src/FinalToken.Core/Collectors/IncrementalScanner.cs create mode 100644 src/FinalToken.Core/Collectors/JsonFields.cs create mode 100644 src/FinalToken.Core/Collectors/LimitProbe.cs create mode 100644 src/FinalToken.Core/Collectors/RolloutParser.cs create mode 100644 src/FinalToken.Core/Collectors/TranscriptParser.cs create mode 100644 src/FinalToken.Core/FinalToken.Core.csproj create mode 100644 src/FinalToken.Core/HistoryPersistence.cs create mode 100644 src/FinalToken.Core/HistoryStore.cs create mode 100644 src/FinalToken.Core/Model.cs create mode 100644 src/FinalToken.Core/Pace.cs create mode 100644 src/FinalToken.Core/Processes/CliDiscovery.cs create mode 100644 src/FinalToken.Core/Processes/ProcessRunner.cs create mode 100644 src/FinalToken.Core/RefreshEngine.cs create mode 100644 src/FinalToken.Core/Settings.cs create mode 100644 src/FinalToken.Core/Snapshot.cs create mode 100644 src/FinalToken.Core/StreamDeck/Installer.cs create mode 100644 src/FinalToken.Core/StreamDeck/PluginInstaller.cs create mode 100644 src/FinalToken.StreamDeck/AGENTS.md create mode 100644 src/FinalToken.StreamDeck/CLAUDE.md create mode 100644 src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj create mode 100644 src/FinalToken.StreamDeck/Program.cs create mode 100644 src/FinalToken.StreamDeck/Protocol.cs create mode 100644 src/FinalToken.StreamDeck/README.md create mode 100644 src/FinalToken.StreamDeck/StatRenderer.cs create mode 100644 src/FinalToken.StreamDeck/plugin/images/icon.svg create mode 100644 src/FinalToken.StreamDeck/plugin/images/key.svg create mode 100644 src/FinalToken.StreamDeck/plugin/inspector/index.html create mode 100644 src/FinalToken.StreamDeck/plugin/inspector/inspector.js create mode 100644 src/FinalToken.StreamDeck/plugin/inspector/style.css create mode 100644 src/FinalToken.StreamDeck/plugin/manifest.json create mode 100644 tests/FinalToken.App.Tests/AGENTS.md create mode 100644 tests/FinalToken.App.Tests/CLAUDE.md create mode 100644 tests/FinalToken.App.Tests/FinalToken.App.Tests.csproj create mode 100644 tests/FinalToken.App.Tests/FormattingTests.cs create mode 100644 tests/FinalToken.App.Tests/HeadlessTests.cs create mode 100644 tests/FinalToken.App.Tests/ViewModelTests.cs create mode 100644 tests/FinalToken.Cli.Tests/AGENTS.md create mode 100644 tests/FinalToken.Cli.Tests/CLAUDE.md create mode 100644 tests/FinalToken.Cli.Tests/CliTests.cs create mode 100644 tests/FinalToken.Cli.Tests/FinalToken.Cli.Tests.csproj create mode 100644 tests/FinalToken.Core.Tests/AGENTS.md create mode 100644 tests/FinalToken.Core.Tests/CLAUDE.md create mode 100644 tests/FinalToken.Core.Tests/DiscoveryAndPolicyTests.cs create mode 100644 tests/FinalToken.Core.Tests/EngineTests.cs create mode 100644 tests/FinalToken.Core.Tests/FinalToken.Core.Tests.csproj create mode 100644 tests/FinalToken.Core.Tests/IntegrationTests.cs create mode 100644 tests/FinalToken.Core.Tests/PaceTests.cs create mode 100644 tests/FinalToken.Core.Tests/ParserTests.cs create mode 100644 tests/FinalToken.Core.Tests/PartialSettingsTests.cs create mode 100644 tests/FinalToken.Core.Tests/ProcessTests.cs create mode 100644 tests/FinalToken.Core.Tests/ReviewRegressionTests.cs create mode 100644 tests/FinalToken.Core.Tests/ReworkTests.cs create mode 100644 tests/FinalToken.Core.Tests/StorageTests.cs create mode 100644 tests/FinalToken.Core.Tests/StreamDeck/InstallerTests.cs create mode 100644 tests/FinalToken.Core.Tests/TestSupport.cs create mode 100644 tests/FinalToken.ProcessHost/AGENTS.md create mode 100644 tests/FinalToken.ProcessHost/CLAUDE.md create mode 100644 tests/FinalToken.ProcessHost/FinalToken.ProcessHost.csproj create mode 100644 tests/FinalToken.ProcessHost/Program.cs create mode 100644 tests/FinalToken.StreamDeck.Tests/AGENTS.md create mode 100644 tests/FinalToken.StreamDeck.Tests/CLAUDE.md create mode 100644 tests/FinalToken.StreamDeck.Tests/FinalToken.StreamDeck.Tests.csproj create mode 100644 tests/FinalToken.StreamDeck.Tests/PluginTests.cs create mode 100755 tools/agent-review.sh create mode 100755 tools/docs/check_docs.py create mode 100755 tools/docs/test_check_docs.py create mode 100755 tools/gitea.sh create mode 100755 tools/publish.py create mode 100644 tools/test_publish.py diff --git a/.agents/mind/gotchas.md b/.agents/mind/gotchas.md new file mode 100644 index 0000000..a36ec0e --- /dev/null +++ b/.agents/mind/gotchas.md @@ -0,0 +1,6 @@ +# Gotchas + +- [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. + +## Archive diff --git a/.agents/mind/index.md b/.agents/mind/index.md new file mode 100644 index 0000000..ddb8072 --- /dev/null +++ b/.agents/mind/index.md @@ -0,0 +1,14 @@ +# Project Mind — Index +> Always-loaded. Everything else is on-demand. Update TOC when files change. + +## Current Focus +- [2026-10-14] v1 on issue #1: Core collectors and store, Avalonia app, Stream Deck plugin. + +## Invariants +- No credential is ever read, stored or sent; providers are reached only through their CLIs (D2). +- 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). +- `snapshot.json` is the only interface between the app and other processes (D9). + +## Table of Contents +- `gotchas.md` — 2 entries — CLI probing pitfalls on this machine. diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..7b4cb48 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,16 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{json,xml,csproj,props,slnx}] +indent_size = 2 + +[*.cs] +csharp_style_namespace_declarations = file_scoped:warning +dotnet_sort_system_directives_first = true diff --git a/.gitea/pull_request_template.md b/.gitea/pull_request_template.md new file mode 100644 index 0000000..68d0ef5 --- /dev/null +++ b/.gitea/pull_request_template.md @@ -0,0 +1,11 @@ +Closes # + +## What and why + +## Decisions + + + +## How it was tested + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e2e04c --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +artifacts/ +**/bin/ +**/obj/ +.vs/ +.idea/ +*.user +*.suo +TestResults/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..2965975 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,141 @@ +# FinalToken + +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 +and the files they write. 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: +schmidt.florian (Gitea user name). + +## Sources of truth + +- `docs/requirements.md` holds the requirements, with stable IDs (`R1`). +- `docs/decisions.md` holds the **recorded decisions** (`D1`), each with why and what it gives + up. Read the ones for your area before working in it. Cite IDs in code comments, commits and + PRs rather than restating the text. +- Each project under `src/` and `tests/` has a short `AGENTS.md`. Read it before changing the + project. + +## Recorded decisions are binding + +Build what the decisions say. When a task conflicts with one, or one looks wrong, stop: comment on +the issue with the conflict and a proposal, add `status/needs-decision`, and leave the call to the +developer. A decision changes only through a PR that edits its text in `docs/decisions.md`, keeps +the decision, why and gives-up format, and carries the `type/decision` label. + +## Layout + +| Path | What it is | +|---|---| +| `src/FinalToken.Core` | No UI. Domain model, pace (D7), collectors (D3, D4), history store (D5), refresh scheduler (D6), snapshot contract (D9), settings, plugin installer (D11) | +| `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.StreamDeck` | Stream Deck plugin executable and its `.sdPlugin` assets (D10) | +| `tests/*` | One test project per tested project, named `.Tests` | +| `tools/` | Repository tools, listed under [Tools](#tools) | + +## Rules for code + +- Current C# 14 on .NET 10: file-scoped namespaces, primary constructors, collection expressions, + `required` and `init`, pattern matching, `System.Threading.Lock`. Nullable reference types on. +- NativeAOT-safe everywhere (D1): System.Text.Json source generation, Avalonia compiled bindings, + 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 + reason at that spot. +- Never touch credentials (D2): do not open credential files, environment secrets or keychains, + never log message text, and never call a provider's HTTP API. +- 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). +- Every file the app writes for itself is written atomically (D5). +- Paths come from `Environment.GetFolderPath`, `Path.Combine` and the environment overrides named + in D3 and D4, never from hard-coded drive letters or `/home/`. +- Parsers of CLI output and files are total: unknown or malformed input becomes a diagnostic, + never an exception that stops a refresh, and never a guessed value. +- A new package needs a justification in its PR and must be NativeAOT-compatible. Package + versions live in `Directory.Packages.props`. +- New behaviour has tests. Parser tests use small, hand-written fixtures under the test project; + never copy a real transcript or rollout into the repo. + +## Workflow + +1. **Issue first.** Find or create the Gitea issue at + `https://git.finalfactory.de/FinalFactory/FinalToken` and assign it to schmidt.florian. Put + the plan on the issue as a checklist and keep it current. Give it a `type/` label. Claim agent + work with the [active agent labels](#active-agent-labels). +2. **One branch per issue, in its own worktree:** branch `-` from `origin/master`, + checked out at `../FinalToken-wt/-`. +3. **Commit** with an `area: summary` subject (`docs:`, `tools:`, `core:`, `app:`, + `streamdeck:`, `cli:`), a body that says why, and `Refs #N`. Push after every commit. +4. **Open a PR** into `master` with a body that follows `.gitea/pull_request_template.md` and says + `Closes #N`. The PR title becomes the squash commit subject, so it follows the commit style. +5. **Review.** After the last push, start a fresh reviewer as described in + `docs/agents/review.md`. Fix blocking findings, push, and start a new review. +6. **Merge** with a squash merge once the review passes, then delete the branch and remove the + worktree. + +Codex workers use GPT-6.1 Sol, model ID `gpt-6.1-sol`. Never select GPT-6 Sol or `gpt-6-sol`. + +### Active agent labels + +| Label | Meaning | +|---|---| +| `status/in-progress` | At least one agent works on the issue now | +| `agent/florian` | The active agents work for schmidt.florian | +| `model/` | An active agent uses this exact model ID | + +- Add `status/in-progress`, `agent/florian` and each active model's label when work starts, and + post a claim comment with the models, their roles, the branch and the worktree. +- The coordinating agent keeps labels and comments current; workers report to it and do not edit + the issue. Remove a model label when its last agent stops, and all three kinds when none runs. +- Add and remove single labels. Never replace the issue's label list. + +### Workers + +The coordinating agent briefs workers, answers their questions and keeps the commits, pushes, +issue comments and the PR. Workers leave their changes uncommitted, end with a summary of the +commands they ran and their results, and list open questions under `QUESTIONS:`. Never let two +agents edit the same files at once. + +## When you are stuck + +- **Stop** when the same problem survives two attempts, or as soon as something proves + impossible. Comment on the issue with what you tried, what failed and what you need, and set + `status/blocked` or `status/needs-decision`. +- **The review loop has a limit:** after a PR's second failed review, the developer decides how + it goes on (`docs/agents/review.md`). + +## Building and testing + +Releasing: bump `` in `Directory.Build.props`, then publish; the tool stamps the plugin manifest. + +Run every command from the repository root. + +| Command | What it does | +|---|---| +| `dotnet build FinalToken.slnx -c Release` | Builds everything; any warning fails | +| `dotnet test --solution FinalToken.slnx -c Release` | Runs every test project | +| `python -B tools/docs/check_docs.py` | Checks that local links and anchors resolve, that each ID is defined once and that every cited ID exists | + +Every change runs the build, the affected tests and the documentation check. UI changes also need +a screenshot of each changed view: compiling is not working. + +## Tools + +- `tools/docs/check_docs.py`: the documentation check; its tests are + `python -B tools/docs/test_check_docs.py`. +- `tools/gitea.sh`: calls the Gitea API with the stored git credential or `GITEA_TOKEN`. +- `tools/agent-review.sh`: posts an agent review and sets the `agent-review` status; see + `docs/agents/review.md`. +- `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 + the plugin manifest's `Version` from ``; its test is `python -B tools/test_publish.py`. + +## Writing + +Docs, commit messages and PR bodies use plain, short sentences in the style of +`docs/decisions.md`. Link issues as +`[#1](https://git.finalfactory.de/FinalFactory/FinalToken/issues/1)`. + +## Shared memory + +Durable lessons (a gotcha, a convention, a command) go into this file, a project's `AGENTS.md` or +`.agents/mind/`, through a PR. Session state and handoffs go in issue comments. diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/Directory.Build.props b/Directory.Build.props new file mode 100644 index 0000000..aff0546 --- /dev/null +++ b/Directory.Build.props @@ -0,0 +1,18 @@ + + + 1.0.1 + net10.0 + 14 + enable + enable + true + true + true + true + true + false + + $(MSBuildThisFileDirectory)artifacts/bin/$(MSBuildProjectName)/ + $(MSBuildThisFileDirectory)artifacts/obj/$(MSBuildProjectName)/ + + diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 0000000..1aee77d --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,12 @@ + + + true + + + + + + + + + diff --git a/FinalToken.slnx b/FinalToken.slnx new file mode 100644 index 0000000..e9adc4d --- /dev/null +++ b/FinalToken.slnx @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/README.md b/README.md index 882ad03..f987c29 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,57 @@ # FinalToken +FinalToken is a tray app for Claude Code and Codex usage. It shows token history, provider limits, +and pace, warns when usage runs ahead of or behind a limit, and puts selected stats on Stream Deck +keys. Starting the app opens the 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 +files. It reads the installed CLIs' usage files and runs their local commands. It never calls a +provider's HTTP API itself. Missing or logged-out CLIs show as unavailable. + +## Requirements + +- Claude Code and/or Codex CLI installed and logged in through the CLI. Their paths can be + overridden in Settings. +- Windows 11, or Linux with X11 or XWayland. CachyOS with KDE Plasma uses XWayland. +- For keys: Stream Deck 7 on Windows, or OpenDeck on Linux. These are optional. + +## Install and use + +Extract the published ZIP to a folder and run `FinalToken.exe` on Windows or `FinalToken` on +Linux. Keep the `streamdeck` folder beside the app. Open, Refresh, Settings and Quit are in the +tray menu. Start with the OS is opt-in. + +Data lives in `%LOCALAPPDATA%\FinalToken` on Windows and `~/.local/share/FinalToken` on Linux. +`FINALTOKEN_DATA_DIR` overrides it. FinalToken keeps its own history after the CLIs remove their +files. A fresh install imports Claude entries from the last 60 days. `snapshot.json` is the +shared output for the plugin and CLI. + +Settings has three Stream Deck install modes: **Off**, **Ask** (default), and **Automatic**. +Ask offers Install or Update and Not now. Automatic installs or updates the shipped plugin when +a host is found; it stops and restarts a running host. Off installs nothing. +Add the plugin's **Stat** action to a key, then select a provider and metric in its inspector. +Pressing the key opens the app's panel; missing or stale data shows offline. + +## CLI + +Run `finaltoken-cli status [--json] [--no-probe]`. Use `./finaltoken-cli` on Linux or +`.\finaltoken-cli.exe` in PowerShell when running from the extracted folder. +It scans, probes limits and prints a snapshot. `--no-probe` reads usage files only. +When the app holds the store lock, the CLI reads its existing snapshot without refreshing. +Exit codes are 0 for success, 1 for failure and 2 for bad arguments. + +## Build from source + +Use .NET SDK 10.0.100 or newer within .NET 10, Python 3, and the target OS's NativeAOT C++ +toolchain. Run from the repository root, as described in [AGENTS.md](AGENTS.md): + +```text +dotnet build FinalToken.slnx -c Release +dotnet test --solution FinalToken.slnx -c Release +python -B tools/docs/check_docs.py +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, +then creates a ZIP beside the directory. Publish `win-x64` on Windows and `linux-x64` on Linux. + diff --git a/docs/agents/review.md b/docs/agents/review.md new file mode 100644 index 0000000..66b3284 --- /dev/null +++ b/docs/agents/review.md @@ -0,0 +1,70 @@ +# Agent review + +Every PR needs a passing review from a fresh agent session before it merges. The review sets the +`agent-review` commit status on the PR's head commit. A push after the review moves the head, so +the PR needs a new review. + +## Starting a review (author) + +After the last push, start a reviewer that has none of the work's context: a new agent session, or +a subagent whose whole prompt is `Review PR # of FinalFactory/FinalToken following +docs/agents/review.md`. Use a capable model at high effort. The PR body, the issue and the earlier +reviews on the PR explain the change; the reviewer gets no other briefing. + +## Reviewing (reviewer) + +1. Record the head commit you review: + `tools/gitea.sh GET /repos/FinalFactory/FinalToken/pulls/ | jq -r .head.sha`. +2. Read the PR, its linked issue, the root `AGENTS.md`, the `AGENTS.md` of every touched project, + the [requirements](../requirements.md) and the [recorded decisions](../decisions.md) the change + touches, and the earlier agent reviews on the PR. +3. Read the whole diff: `git fetch origin && git diff origin/master...`. On a re-review it is + context; step 5 says what can block. +4. Check out the head in a separate worktree and run the checks in + [AGENTS.md](../../AGENTS.md#building-and-testing) that the change affects, always including + `python -B tools/docs/check_docs.py`. +5. If the PR already has a failed agent review, this is a re-review. Check that each blocking + finding of the last failed review is fixed or answered. Then review only the author's commits + since the commit that review covered (named in its first line), leaving out what came in from + `master`: `git log -p --no-merges ^ ^origin/master `. Only these two can block. + Anything else you notice is a note, even a bug; the author decides whether to fix it in this + PR. A full pass in every round finds new problems each time, and the loop never ends. +6. Look for: + - **Spec**: it does what the issue asks and stays inside its scope. + - **Decisions**: it matches the recorded decisions, or the PR changes their text and carries + the `type/decision` label. + - **Correctness**: bugs, edge cases, error handling, concurrency, resource cleanup. + - **Rules**: the rules in `AGENTS.md` and in the touched projects' `AGENTS.md`. + - **Tests**: new behaviour has tests. + - **Docs**: docs and `AGENTS.md` files match the new behaviour, commands and decisions. +7. Decide the verdict. `fail` only for a blocking finding: a bug, missing behaviour the issue asks + for, code that breaks a recorded decision or a rule from step 6, missing tests for new + behaviour, or a failing check. A check or tool that misses some cases does not break the rule + it guards: name the gap as a note. Everything else is a note and the review passes. +8. Write the review to a file in this format, then post it with + `tools/agent-review.sh `: + + ```markdown + ## Blocking + + 1. `path:line`: what is wrong, why it matters, and the fix. + + ## Notes + + - `path:line`: the suggestion. + + ## Checked + + What you read and ran, on which commit. + ``` + +The reviewer reports and leaves the code to the author. + +## After a failed review (author) + +Fix each blocking finding, or answer it in a PR comment when it is wrong. Push, then start a new +fresh review. + +After the second failed review, stop. Comment on the issue with the open findings, add the +`status/needs-decision` label and leave it to a developer: merge anyway, allow more rounds, split +the PR or close it. diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 0000000..8f1ee8f --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,239 @@ +# Recorded decisions + +These bind. Each says what was decided, why, and what it gives up. A decision changes only through +a PR that edits its text here and carries the `type/decision` label. Code, commits and PRs cite +the IDs instead of restating the text. The requirements (R1 to R7) are in +[requirements.md](requirements.md). + +## 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 +`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 +package manager works too. Builds treat warnings as errors and run the trim and AOT analyzers. +JSON goes through System.Text.Json source generation only. Nothing uses reflection-driven +serialization, binding or loading, or runtime code generation. + +**Why.** R1. .NET 10 is the newest stable release on 2026-10-14; .NET 11 is not released yet. + +**Gives up.** .NET 11 preview features, and libraries that need reflection at run time. + +## D2 — The CLIs are the only interface to a provider + +**Decision.** FinalToken never reads, stores, logs or sends a credential (OAuth token, API key, +cookie). It never opens a provider login and 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 +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 +names, timestamps and project paths leave a parser; message text is never kept. A missing or +logged-out CLI makes its provider show "unavailable" with the reason, and the other provider keeps +working. + +**Why.** R2, R3. + +**Gives up.** Whatever the CLIs do not expose, and limit data while a CLI is not installed. + +## D3 — Claude data sources + +**Decision.** + +- **Tokens.** The transcripts `/projects/**/*.jsonl`, where `` is + `CLAUDE_CONFIG_DIR` or `~/.claude`. Each assistant entry gives `message.usage` (input, output, + cache creation and cache read tokens), `message.model`, `timestamp` and `cwd` (the project). + One API response can appear on several lines, and a resumed session copies earlier ones, so a + response counts once, keyed on `message.id` and `requestId`. +- **Limits.** `claude -p "/usage" --output-format json --no-session-persistence`, run with + FinalToken's data directory as the working directory. Claude Code answers it locally + (`num_turns` 0, cost 0) and `--no-session-persistence` keeps it out of the transcripts. The + `result` text holds lines such as + `Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)` and + `Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)`. Each becomes a + limit window: the session window is 5 h, a week window 7 d. Only lines that start with + `Current ` are limit lines; other prose is ignored and parsing stops at the "What's + contributing to your limits usage?" section. A limit line that does not parse is reported as a + diagnostic and skipped; the parser never guesses a value. + +**Why.** Claude Code has no machine-readable limit command, and `/usage` is the CLI's own view. +Claude Code deletes transcripts after `cleanupPeriodDays` (30 days by default), so history +comes from FinalToken's own store ([D5](#d5--own-history-store)), not from re-reading +transcripts. + +**Gives up.** Reset times are known only to the minute, and a Claude Code release can change the +text. Fixtures pin the known formats so a change fails visibly. + +## D4 — Codex data sources + +**Decision.** + +- **Tokens.** The rollouts `/sessions/**/rollout-*.jsonl` and + `/archived_sessions/**/rollout-*.jsonl`, where `` is `CODEX_HOME` or `~/.codex`. + `event_msg` entries of type `token_count` carry `info.total_token_usage` (input, cached input, + output and reasoning output tokens). A session's usage is the increase of that total between + consecutive events, so a repeated event adds nothing. The model comes from the latest + `turn_context` entry before the event. +- **Limits.** `codex app-server` over stdio JSON-RPC: `initialize`, then + `account/rateLimits/read`. The fallback is the latest `rate_limits` object in the newest + rollout: `primary` and `secondary` windows with `used_percent`, `window_minutes` and + `resets_at` in Unix seconds. + +**Why.** R2, R3. The app server is the CLI's machine interface, and the rollouts are written on +every turn. + +**Gives up.** The app server is marked experimental; the rollout fallback keeps limits working +when it changes. + +## D5 — Own history store + +**Decision.** FinalToken keeps its own history in its data directory, which is +`Environment.SpecialFolder.LocalApplicationData/FinalToken` (`%LOCALAPPDATA%\FinalToken` on +Windows, `~/.local/share/FinalToken` on Linux). It holds hourly token buckets per provider, model +and project, and limit samples (time, provider, window, used percent, reset). A sample is kept +when it differs from the window's previous one, and otherwise at most once an hour. Hours are +stored in UTC; day series, today and the week follow the local calendar day, including days of 23 +and 25 hours at daylight-saving changes. All files are JSON or JSON lines through +System.Text.Json source generation. There is no database dependency. + +- **Writing.** Each refresh that found something new appends one newline-terminated transaction + to a journal. A torn last line is ignored on load and cut off before the next append. When the + journal reaches 8 MiB, it is compacted into one file per month and a state checkpoint, each + written atomically (a temporary file in the same directory, then a replace), and the journal + starts empty. Transactions hold absolute values, so replaying them after an interrupted + compaction gives the same result. A refresh that found nothing new writes no history. +- **Reading.** Files that are replaced atomically (`snapshot.json`, settings, the month files, + the checkpoint, the activation request) are opened with read, write and delete sharing, and the + replace retries briefly, so a reader never makes a write fail on Windows. +- **Scanning.** For each source file the store remembers its length, its last write time and how + far it read. An unchanged file is not opened; otherwise only appended bytes are read. A file + that shrank or was replaced is read again from the start. +- **Counting once.** A response counts once across restarts, rescans and resumed sessions. Claude + responses are keyed on `message.id` and `requestId` (D3). Their keys are kept for 60 days, + twice Claude Code's default cleanup period, and Claude entries older than that are ignored. + Codex sessions keep their last cumulative total and its time (D4), so a replayed or archived + copy adds nothing. +- **One writer.** One process writes the store at a time, guarded by an exclusive lock file in + the data directory. While another process holds it, the CLI only reads the current + `snapshot.json` and says so. `FINALTOKEN_DATA_DIR` overrides the data directory, for tests and + parallel checks. + +**Why.** R4 needs history longer than the CLIs keep theirs ([D3](#d3--claude-data-sources)). A +file store has no native dependency to ship with NativeAOT. Rewriting all history on every +refresh wrote about 27 GB a day on the developer's machine; the journal makes writes follow new +data. + +**Gives up.** Ad-hoc queries, token history finer than an hour, limit samples finer than an hour +while the value does not change, and Claude history older than 60 days on a fresh install. + +## D6 — Refresh + +**Decision.** Token scans run when a watched source directory changes (debounced by 2 s) and at +least every 60 s. Limit probes ([D3](#d3--claude-data-sources), [D4](#d4--codex-data-sources)) +run every 5 min by default (configurable from 1 to 60 min), and also after new tokens arrive, +but at most once a minute per provider. Probes run one at a time per provider with a 60 s +timeout; a probe that times out has its process tree killed and counts as failed. A failed probe +keeps the last good sample and marks it with its age. Shutting down cancels the running work +and waits for it. Every child process gets its own standard input, output and error pipes, decoded +as UTF-8, because a GUI host has no console and no console code page; stdin is closed at once +unless the probe is the Codex RPC. + +**Why.** Limits change only when tokens are spent, and a probe starts a CLI process, so probing +follows token activity instead of a tight timer. + +**Gives up.** Limit changes caused by other devices or the web show up only at the next timed +probe. + +## D7 — Pace + +**Decision.** For a limit window with used percent `u`, length `W` and reset time `r`, at time `t`: + +- elapsed fraction `e = 1 − (r − t) / W`, clamped to 0..1 +- 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** + 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, + `t + (100 − u) · e·W / u`, shown only if it comes before `r`. + +A window without a known length or reset has no pace; FinalToken never guesses one. + +**Why.** R5. A straight line from the window's start to its reset is a pace the user can check +by hand. + +**Gives up.** Weekday and working-hour patterns. + +## D8 — Desktop app + +**Decision.** + +- **Toolkit.** Avalonia, the newest stable release that supports NativeAOT (checked on nuget.org + when the app is built), with the Fluent theme, compiled bindings only and CommunityToolkit.Mvvm + source generators. Charts are small custom controls drawn with Avalonia's `DrawingContext`; + there is no chart library. +- **Lifecycle.** One instance per user, guarded by the store's lock file + ([D5](#d5--own-history-store)). Starting it again writes an activation request file to the data + directory and exits; the running instance watches for it and brings its window to the front. + 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 + opt-in setting. +- **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 + 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 + hysteresis of 2 points so a value on the threshold cannot flap. Popups can be turned off per + provider and per state. +- **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. + +**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. + +**Gives up.** Native OS notification styling, and a native Wayland window. + +## D9 — The snapshot file is the app's only output to other processes + +**Decision.** After each refresh the app writes `snapshot.json` atomically to its data directory +([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 +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 +their source-generated JSON context live in `FinalToken.Core`, shared by the app, the CLI and the +Stream Deck plugin. Nothing listens on a socket or runs an HTTP server. A reader treats 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 +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 +restart of either side. + +**Gives up.** Updates faster than the reader's poll interval. + +## D10 — Stream Deck plugin + +**Decision.** The plugin's UUID is `de.finalfactory.finaltoken`, its folder +`de.finalfactory.finaltoken.sdPlugin`, its manifest SDK version 2. The plugin executable is C# +NativeAOT: `CodePathWin` for Elgato Stream Deck on Windows, and `CodePathLin` for OpenDeck on +Linux, since Elgato's software does not run there. It speaks the Stream Deck WebSocket protocol +itself through `System.Net.WebSockets`, without an SDK package. It reads `snapshot.json` +([D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes)) and draws each key as +an SVG image through `setImage`. One action, "Stat", has a property inspector (HTML in the +plugin folder) that picks the provider and the metric: session percent, week percent, pace +delta, time to reset, tokens today or tokens this week. The key's colour follows the pace state. +A key press opens the app's stats panel. A missing or stale snapshot shows "offline". + +**Why.** R6 and R1 with one language and one snapshot contract. + +**Gives up.** The helpers of Elgato's Node SDK, and marketplace distribution. + +## D11 — Plugin install and update + +**Decision.** A setting has three values: Off, Ask (the default) and Automatic. The app ships the +built plugin folder at `/streamdeck/de.finalfactory.finaltoken.sdPlugin`. On start +it compares the shipped manifest's `Version` with the installed plugin's. The install targets are +`%APPDATA%\Elgato\StreamDeck\Plugins\` on Windows and OpenDeck's plugin directory on Linux, +native or Flatpak. Ask shows a popup with Install (or Update) and Not now; Automatic installs +without asking. An install replaces the plugin folder. When the Stream Deck software is running, +the app stops it first and starts it again afterwards. Nothing is installed while the setting is +Off, or in Ask mode before the user presses Install. When no Stream Deck software is found, the +setting says so and nothing happens. + +**Why.** R7. + +**Gives up.** Elgato's double-click `.streamDeckPlugin` installer, which always asks. diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 0000000..03ec976 --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,14 @@ +# Requirements + +Set by schmidt.florian on 2026-10-14 ([#1](https://git.finalfactory.de/FinalFactory/FinalToken/issues/1)). +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. +- **R2** No sign-in to an AI provider inside the app and no API key or OAuth token. Data comes + through the providers' command-line tools. +- **R3** Supported providers: at least Codex and Claude. +- **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 + of a limit. +- **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. diff --git a/global.json b/global.json new file mode 100644 index 0000000..3a426e7 --- /dev/null +++ b/global.json @@ -0,0 +1,4 @@ +{ + "sdk": { "version": "10.0.100", "rollForward": "latestFeature" }, + "test": { "runner": "Microsoft.Testing.Platform" } +} diff --git a/src/FinalToken.App/AGENTS.md b/src/FinalToken.App/AGENTS.md new file mode 100644 index 0000000..6db63a2 --- /dev/null +++ b/src/FinalToken.App/AGENTS.md @@ -0,0 +1,10 @@ +# App +Avalonia 12 Fluent host (D8). Views are built in C# without reflection bindings. View-model +properties use CommunityToolkit.Mvvm source generators. Custom charts use DrawingContext. +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. +history queries run on worker threads and discard superseded results. Keep all writes atomic (D5). +Daily charts use local calendar boundaries; never assume a day lasts 24 hours. +Stream Deck policy and the real installer come through IPluginInstaller (D11). +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. diff --git a/src/FinalToken.App/CLAUDE.md b/src/FinalToken.App/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/src/FinalToken.App/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/src/FinalToken.App/Charts.cs b/src/FinalToken.App/Charts.cs new file mode 100644 index 0000000..dc6d9e2 --- /dev/null +++ b/src/FinalToken.App/Charts.cs @@ -0,0 +1,114 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Styling; +using FinalToken.Core; +using System.Globalization; + +namespace FinalToken.App; + +public sealed class UsageChart : Control +{ + private static readonly IBrush[] Palette = [Brush.Parse("#3878D4"), Brush.Parse("#B377D1"), Brush.Parse("#249A88"), Brush.Parse("#C98926")]; + public static IBrush SeriesColour(int index) => Palette[index % Palette.Length]; + /// At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten. + public static IReadOnlyList AxisTicks(double maximum, bool percent = false) + { + if (!double.IsFinite(maximum) || maximum <= 0) return [0]; + if (percent) return [0, 25, 50, 75, 100]; + var target = Math.Max(1, maximum / 4); + var magnitude = Math.Pow(10, Math.Floor(Math.Log10(target))); + var fraction = target / 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, intervals + 1).Select(i => i * step).ToArray(); + } + public IReadOnlyList Values { get; init; } = []; + public bool Percent { get; init; } + public TimeSpan Interval { get; init; } = TimeSpan.FromHours(1); + private readonly List<(Rect Rect, string Text)> hits = []; + public UsageChart() + { + Height = 180; + PointerMoved += (_, e) => ToolTip.SetTip(this, hits.LastOrDefault(h => h.Rect.Contains(e.GetPosition(this))).Text); + PointerExited += (_, _) => ToolTip.SetTip(this, null); + } + public override void Render(DrawingContext context) + { + base.Render(context); + hits.Clear(); + var ink = ActualThemeVariant == ThemeVariant.Dark ? Brushes.WhiteSmoke : Brushes.DarkSlateGray; + 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 ticks = AxisTicks(groups.Length == 0 ? 0 : Percent ? 100 : groups.Max(g => g.Sum(v => v.Value)), Percent); + var max = Math.Max(1, ticks[^1]); + foreach (var tick in ticks) + { + 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)); + 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}"; + 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; } + var series = Values.Select(v => v.Series).Distinct().ToArray(); + if (Percent) + { + 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)) + { + var point = Position(value, value.Value); + if (previous is { } p && !value.BreakBefore) + { + context.DrawLine(new Pen(Palette[0], 2), Position(p, p.Value), point); + 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.DrawEllipse(Palette[0], null, point, 3, 3); + 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")}")); + previous = value; + } + } + else + { + var duration = Math.Max(Interval.TotalSeconds, (groups[^1].Key - groups[0].Key).TotalSeconds + Interval.TotalSeconds); + var width = plot.Width * Interval.TotalSeconds / duration; + for (var i = 0; i < groups.Length; i++) + { + var bottom = plot.Bottom; + foreach (var value in groups[i]) + { + var height = value.Value / max * plot.Height; + var x = plot.Left + (groups[i].Key - groups[0].Key).TotalSeconds / duration * plot.Width; + var rect = new Rect(x + Math.Min(1, width / 8), bottom - height, Math.Max(0.5, width - Math.Min(2, width / 4)), height); + context.DrawRectangle(Palette[Array.IndexOf(series, value.Series) % Palette.Length], null, rect); + hits.Add((rect, $"{Display.ChartTimestamp(value.Time, Interval)} · {value.Series}: {value.Value:N0} tokens")); + bottom -= height; + } + } + } + Text(context, Display.ChartDateLabel(groups[0].Key, Interval), new(plot.Left, plot.Bottom + 8), ink); + Text(context, Display.ChartDateLabel(groups[^1].Key, Interval), new(Math.Max(plot.Left, plot.Right - 110), plot.Bottom + 8), ink); + ToolTip.SetShowDelay(this, 0); + } + 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 +{ + public static IBrush Colour(PaceState state) => Brush.Parse(state switch + { PaceState.Ahead => "#D98236", PaceState.Behind => "#3A8CCB", PaceState.OnTrack => "#279884", _ => "#8C95A3" }); + public override void Render(DrawingContext context) + { + base.Render(context); + context.DrawRectangle(Brush.Parse("#338795A5"), null, new Rect(Bounds.Size), 4, 4); + 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); + 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)); + ToolTip.SetTip(this, $"Used {window.Window.UsedPercent:0.##}% · expected {window.Pace.ElapsedFraction * 100:0.##}%"); + } +} diff --git a/src/FinalToken.App/DesktopApp.cs b/src/FinalToken.App/DesktopApp.cs new file mode 100644 index 0000000..26a30e1 --- /dev/null +++ b/src/FinalToken.App/DesktopApp.cs @@ -0,0 +1,187 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Themes.Fluent; +using Avalonia.Threading; +using FinalToken.Core; +using FinalToken.Core.StreamDeck; + +namespace FinalToken.App; + +public sealed class DesktopApp : Application +{ + private readonly PanelViewModel model = new(); + private IClassicDesktopStyleApplicationLifetime? desktop; + private PanelWindow? panel; + private PopupStack? popups; + private TrayIcon? tray; + private DispatcherTimer? ageTimer; + private SettingsWindow? settingsWindow; + private Task settingsSave = Task.CompletedTask; + private PopupWindow? pluginAsk; + private RefreshEngine? engine; + private readonly SemaphoreSlim pluginGate = new(1, 1); + private int historyRequest; + private bool quitting; + private PluginInstallStatus pluginStatus = new(PluginInstallState.NoHostFound); + public IPluginInstaller PluginInstaller { get; set; } = FinalToken.Core.StreamDeck.PluginInstaller.CreateDefault(); + public override void Initialize() => Styles.Add(new FluentTheme()); + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime) + { + desktop = lifetime; desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; + engine = Program.Engine; + if (Program.StartupError is { } error) + { + var window = new Window { Title = "FinalToken — history error", Width = 560, Height = 240, + Content = Ui.Card(Ui.Stack(Ui.Text("History cannot be loaded", 22), Ui.Text(error), Ui.Button("Quit", () => desktop.Shutdown(1)))) }; + desktop.MainWindow = window; window.Show(); + window.Closed += (_, _) => desktop.Shutdown(1); + } + else + { + panel = new PanelWindow(model, () => Run(Refresh), OpenSettings, () => Run(Quit), () => Run(LoadHistory)); + desktop.MainWindow = panel; popups = new(OpenPanel); + panel.Closing += (_, e) => { if (!quitting && engine?.Settings.CloseToTray != false) { e.Cancel = true; panel.Hide(); } else if (!quitting) { e.Cancel = true; Run(Quit); } }; + CreateTray(); panel.Show(); + 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.PopupRequested += alert => Dispatcher.UIThread.Post(() => { if (!quitting) popups.Pace(alert); }); + engine.ActivationRequested += () => Dispatcher.UIThread.Post(OpenPanel); + model.Snapshot = engine.CurrentSnapshot; + ageTimer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(30) }; + ageTimer.Tick += (_, _) => { if (panel.IsVisible) model.Diagnostics = engine.RecentDiagnostics; }; + ageTimer.Start(); + Run(Start); + } + } + desktop.ShutdownRequested += (_, e) => { if (!quitting && engine is not null) { e.Cancel = true; Run(Quit); } }; + } + base.OnFrameworkInitializationCompleted(); + } + private async Task Start() + { + await engine!.StartAsync(); + if (engine.Settings.StartWithOs) await OsStartup.ApplyAsync(true); + await CheckPlugin(); + } + private void CreateTray() + { + var menu = new NativeMenu(); + 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); } + using var bitmap = new RenderTargetBitmap(new PixelSize(32, 32)); + 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(); + TrayIcon.SetIcons(this, [tray]); + } + private void OpenPanel() + { + if (panel is null || quitting) return; + panel.Show(); panel.WindowState = WindowState.Normal; panel.Activate(); + if (OperatingSystem.IsWindows()) WindowsActivation.Activate(panel); + } + private Task Refresh() => engine is null ? Task.CompletedTask : engine.RefreshNowAsync(); + private async Task LoadHistory() + { + if (engine is null || model.Snapshot is not { } snapshot || quitting) return; + var request = ++historyRequest; var range = model.Range; var filter = model.ProviderFilter; + var history = await Task.Run(() => PanelViewModel.QueryHistory(engine.History, snapshot, range, filter, DateTimeOffset.UtcNow)); + if (request == historyRequest && !quitting) model.History = history; + } + private void OpenSettings() + { + if (engine is null) return; + if (settingsWindow is not null) { settingsWindow.Activate(); return; } + settingsWindow = new SettingsWindow(engine.Settings, pluginStatus, value => settingsSave = SaveSettings(value)); + settingsWindow.Closed += (_, _) => settingsWindow = null; + settingsWindow.Show(); + } + private async Task SaveSettings(Settings value) + { + if (engine is null || quitting) return; + var previous = engine.Settings; + await OsStartup.ApplyAsync(value.StartWithOs); + if (quitting) { await OsStartup.ApplyAsync(previous.StartWithOs); return; } + try { await engine.UpdateSettingsAsync(value); } + catch { await OsStartup.ApplyAsync(previous.StartWithOs); throw; } + if (quitting) return; + await CheckPlugin(); + if (!quitting) await engine.RefreshNowAsync(); + } + private async Task CheckPlugin() + { + if (engine is null || quitting) return; + await pluginGate.WaitAsync(); + try + { + if (quitting) return; + pluginAsk?.Close(); pluginAsk = null; + pluginStatus = await PluginInstaller.GetStatusAsync(); + var action = InstallPolicy.Decide(engine.Settings.StreamDeckInstallMode, pluginStatus, engine.Settings.DismissedPluginVersion); + if (action == InstallAction.Install) await InstallPlugin(); + else if (action == InstallAction.Ask) + { + var version = pluginStatus.ShippedVersion; + pluginAsk = new PopupWindow("Stream Deck plugin", $"Version {version} is ready.", OpenPanel, + pluginStatus.State == PluginInstallState.Outdated ? "Update" : "Install", () => Run(() => AcceptPlugin(version)), + () => Run(() => DismissPlugin(version))); + popups!.Show(pluginAsk); + } + } + finally { pluginGate.Release(); } + } + private async Task DismissPlugin(string? version) + { + await pluginGate.WaitAsync(); + try { if (!quitting && engine is not null) await engine.UpdateSettingsAsync(engine.Settings with { DismissedPluginVersion = version }); } + finally { pluginGate.Release(); } + } + private async Task AcceptPlugin(string? version) + { + await pluginGate.WaitAsync(); + try + { + if (quitting || engine?.Settings.StreamDeckInstallMode == InstallMode.Off) return; + var current = await PluginInstaller.GetStatusAsync(); + if (current.ShippedVersion == version && current.State is PluginInstallState.NotInstalled or PluginInstallState.Outdated) + await InstallPlugin(); + } + finally { pluginGate.Release(); } + } + private async Task InstallPlugin() + { + try { await PluginInstaller.InstallOrUpdateAsync(); pluginStatus = await PluginInstaller.GetStatusAsync(); if (!quitting) popups!.Show(new PopupWindow("Stream Deck", pluginStatus.State == PluginInstallState.UpToDate ? "Plugin installed successfully." : $"Plugin status: {pluginStatus.State}", OpenPanel)); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException) + { if (!quitting) popups!.Show(new PopupWindow("Stream Deck", "Install failed: " + e.Message, OpenPanel)); } + } + private async Task Quit() + { + if (quitting) return; quitting = true; + ageTimer?.Stop(); tray?.Dispose(); popups?.Dispose(); settingsWindow?.Close(); + var stopping = engine?.StopAsync() ?? Task.CompletedTask; + await pluginGate.WaitAsync(); pluginGate.Release(); + try { await settingsSave; } + catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException or OperationCanceledException) + { engine?.Diagnostics.Add(null, "settings-shutdown", "Settings could not finish applying before shutdown."); } + await stopping; + desktop?.Shutdown(); + } + private async void Run(Func work) + { + try { await work(); } + catch (OperationCanceledException) { } + catch (Exception) + { + engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed."); + model.Message = "Operation failed. See diagnostics."; + } + } +} diff --git a/src/FinalToken.App/FinalToken.App.csproj b/src/FinalToken.App/FinalToken.App.csproj new file mode 100644 index 0000000..9704ede --- /dev/null +++ b/src/FinalToken.App/FinalToken.App.csproj @@ -0,0 +1,15 @@ + + + WinExe + FinalToken + true + true + true + + + + + + + + diff --git a/src/FinalToken.App/OsStartup.cs b/src/FinalToken.App/OsStartup.cs new file mode 100644 index 0000000..7ed2f6e --- /dev/null +++ b/src/FinalToken.App/OsStartup.cs @@ -0,0 +1,35 @@ +using System.Runtime.Versioning; +using FinalToken.Core; +using Microsoft.Win32; + +namespace FinalToken.App; + +public static class OsStartup +{ + public static string LinuxAutostartPath(string? configHome, string userHome) + => Path.Combine(string.IsNullOrEmpty(configHome) ? Path.Combine(userHome, ".config") : configHome, "autostart", "finaltoken.desktop"); + public static async Task ApplyAsync(bool enabled, string? executable = null) + { + executable ??= Environment.ProcessPath ?? throw new InvalidOperationException("Executable path is unavailable."); + if (OperatingSystem.IsWindows()) { ApplyWindows(enabled, executable); return; } + if (!OperatingSystem.IsLinux()) return; + var path = LinuxAutostartPath(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"), + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); + if (!enabled) { if (File.Exists(path)) File.Delete(path); return; } + await AtomicFile.WriteAsync(path, DesktopEntry(executable)); + } + public static string DesktopEntry(string executable) + { + if (executable.IndexOfAny(['\r', '\n', '\0']) >= 0) throw new ArgumentException("Executable path contains invalid characters.", nameof(executable)); + var quoted = executable.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + .Replace("`", "\\`", StringComparison.Ordinal).Replace("$", "\\$", StringComparison.Ordinal).Replace("%", "%%", StringComparison.Ordinal); + var escaped = quoted.Replace("\\", "\\\\", StringComparison.Ordinal); + return $"[Desktop Entry]\nType=Application\nName=FinalToken\nExec=\"{escaped}\"\nTerminal=false\nX-GNOME-Autostart-enabled=true\n"; + } + [SupportedOSPlatform("windows")] + private static void ApplyWindows(bool enabled, string executable) + { + using var key = Registry.CurrentUser.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true); + if (enabled) key.SetValue("FinalToken", "\"" + executable + "\""); else key.DeleteValue("FinalToken", false); + } +} diff --git a/src/FinalToken.App/PanelViewModel.cs b/src/FinalToken.App/PanelViewModel.cs new file mode 100644 index 0000000..78bb63c --- /dev/null +++ b/src/FinalToken.App/PanelViewModel.cs @@ -0,0 +1,88 @@ +using CommunityToolkit.Mvvm.ComponentModel; +using FinalToken.Core; + +namespace FinalToken.App; + +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 BreakdownRow(string Name, TokenCounts Counts, double Share); +public sealed record LimitChart(string Label, IReadOnlyList Values); +public sealed record HistoryView(IReadOnlyList Hourly, IReadOnlyList Daily, + IReadOnlyList Limits, IReadOnlyList Models, IReadOnlyList Projects); + +public partial class PanelViewModel : ObservableObject +{ + [ObservableProperty] private Snapshot? snapshot; + [ObservableProperty] private HistoryRange range = HistoryRange.Days7; + [ObservableProperty] private Provider? providerFilter; + [ObservableProperty] private HistoryView history = new([], [], [], [], []); + [ObservableProperty] private IReadOnlyList diagnostics = []; + [ObservableProperty] private string message = "Reading local CLI data…"; + + public static DateTimeOffset RangeStart(HistoryRange range, DateTimeOffset now) => range switch + { + HistoryRange.Hours24 => now.AddHours(-24), HistoryRange.Days7 => now.AddDays(-7), + HistoryRange.Days30 => now.AddDays(-30), HistoryRange.Days90 => now.AddDays(-90), + _ => DateTimeOffset.MinValue + }; + + // D5: queries return copies; the caller runs this on a worker thread. + public static HistoryView QueryHistory(HistoryStore store, Snapshot snapshot, HistoryRange range, Provider? filter, DateTimeOffset now) + { + var from = RangeStart(range, now); + var providers = snapshot.Providers.Where(p => filter is null || p.Provider == filter).ToArray(); + var hourly = Series(SeriesInterval.Hour); + var daily = Series(SeriesInterval.Day); + var limits = providers.SelectMany(p => p.Windows.Select(w => + { + var samples = store.LimitSamples(p.Provider, w.Window.Id, from, now); + return new LimitChart($"{p.Provider} · {w.Window.Label}", samples.Select((s, i) => + new ChartValue(s.SampleTime, w.Window.Label, s.UsedPercent, + Pace.Calculate(s, s.SampleTime).ElapsedFraction * 100, + i > 0 && s.ResetsAt != samples[i - 1].ResetsAt)).ToArray()); + })).ToArray(); + return new(hourly, daily, limits, Breakdown(true), Breakdown(false)); + + IReadOnlyList Series(SeriesInterval interval) => providers.SelectMany(p => + 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 ModelsAtPoint(Provider provider, DateTimeOffset time, SeriesInterval interval) + { + var end = interval == SeriesInterval.Hour ? time.AddHours(1) : CalendarDays.NextStart(time); + return store.ByModel(provider, time < from ? from : time, end > now ? now : end) + .Select(m => new ChartValue(time, m.Name ?? "Unknown model", m.Counts.Total)); + } + IReadOnlyList Breakdown(bool models) + { + 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, + g.Aggregate(new TokenCounts(), (sum, r) => sum + r.Counts))).OrderByDescending(r => r.Counts.Total).ToArray(); + 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(); + } + } +} + +public static class Display +{ + public static string ChartDateLabel(DateTimeOffset time, TimeSpan interval) + => ChartTime(time, interval).ToString(interval >= TimeSpan.FromDays(1) ? "MM-dd" : "MM-dd HH:mm"); + public static string ChartTimestamp(DateTimeOffset time, TimeSpan interval) + => ChartTime(time, interval).ToString("g"); + private static DateTime ChartTime(DateTimeOffset time, TimeSpan interval) + => interval >= TimeSpan.FromDays(1) ? time.DateTime : time.LocalDateTime; + public static string Projection(DateTimeOffset projection, TimeProvider? clock = null, System.Globalization.CultureInfo? culture = null) + { + clock ??= TimeProvider.System; + var local = TimeZoneInfo.ConvertTime(projection, clock.LocalTimeZone); + return local.ToString(local.Date == clock.GetLocalNow().Date ? "t" : "g", + culture ?? System.Globalization.CultureInfo.CurrentCulture); + } + 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"; + 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}" + : "Unavailable — no known session window"; + public static string State(PaceState state) => state switch { PaceState.OnTrack => "On track", PaceState.Unknown => "Pace unknown", _ => state.ToString() }; +} diff --git a/src/FinalToken.App/PanelWindow.cs b/src/FinalToken.App/PanelWindow.cs new file mode 100644 index 0000000..7b8c87c --- /dev/null +++ b/src/FinalToken.App/PanelWindow.cs @@ -0,0 +1,130 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using FinalToken.Core; + +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 +{ + private readonly PanelViewModel model; + private readonly StackPanel body = new() { Spacing = 16, Margin = new Thickness(24) }; + public PanelWindow(PanelViewModel model, Action refresh, Action settings, Action quit, Action reload) + { + this.model = model; + Title = $"FinalToken {typeof(Program).Assembly.GetName().Version?.ToString(3)}"; Width = 1160; Height = 920; MinWidth = 720; MinHeight = 500; + var header = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; + header.Children.Add(Ui.Text("FinalToken", 28)); + header.Children.Add(Ui.Button("Refresh now", refresh)); + header.Children.Add(Ui.Button("Settings", settings)); + header.Children.Add(Ui.Button("Quit", quit)); + var range = new ComboBox { ItemsSource = new[] { "24 hours", "7 days", "30 days", "90 days", "All history" }, SelectedIndex = (int)model.Range, MinWidth = 150 }; + range.SelectionChanged += (_, _) => { model.Range = (HistoryRange)range.SelectedIndex; reload(); }; + var providers = new ComboBox { ItemsSource = new[] { "All providers", "Claude", "Codex" }, SelectedIndex = 0, MinWidth = 150 }; + providers.SelectionChanged += (_, _) => { model.ProviderFilter = providers.SelectedIndex == 0 ? null : (Provider)(providers.SelectedIndex - 1); reload(); }; + var filters = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; + filters.Children.Add(range); filters.Children.Add(providers); + var dock = new DockPanel { Margin = new Thickness(0, 18, 0, 0) }; + var top = Ui.Stack(header, filters); top.Margin = new Thickness(24, 0, 24, 0); + DockPanel.SetDock(top, Dock.Top); dock.Children.Add(top); + dock.Children.Add(new ScrollViewer { Content = body }); Content = dock; + model.PropertyChanged += (_, _) => RenderModel(); + RenderModel(); + } + public void RenderModel() + { + body.Children.Clear(); + body.Children.Add(Ui.Text(model.Message)); + if (model.Snapshot is { } snapshot) + { + foreach (var provider in snapshot.Providers.Where(p => model.ProviderFilter is null || p.Provider == model.ProviderFilter)) + { + var card = Ui.Stack(Ui.Text(provider.Provider.ToString(), 22), Ui.Text($"{provider.Status} {provider.Reason}")); + foreach (var window in provider.Windows) + { + var w = window.Window; var pace = window.Pace; + 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); + 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 h = model.History; + body.Children.Add(Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), Legend(h.Hourly), new UsageChart { Values = h.Hourly }))); + 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) }))); + foreach (var limit in h.Limits) + 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 }))); + body.Children.Add(Breakdown("By model", h.Models)); + body.Children.Add(Breakdown("By project", h.Projects)); + var diagnostics = Ui.Stack(Ui.Text("Recent diagnostics", 19)); + 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 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++); + label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label); + } + return legend; + } + private static Border Breakdown(string title, IReadOnlyList rows) + { + var table = Ui.Stack(Ui.Text(title, 19)); + var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("3*,1*,1*,1*,1*,1*,1*,1*"), MinWidth = 900 }; + 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; + AddRow([row.Name, c.Total.ToString("N0"), row.Share.ToString("P1"), c.Input.ToString("N0"), c.CacheRead.ToString("N0"), + c.CacheWrite.ToString("N0"), c.Output.ToString("N0"), c.ReasoningOutput.ToString("N0")], index++); + } + 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); + } + } + } +} diff --git a/src/FinalToken.App/Popups.cs b/src/FinalToken.App/Popups.cs new file mode 100644 index 0000000..f9f1970 --- /dev/null +++ b/src/FinalToken.App/Popups.cs @@ -0,0 +1,71 @@ +using Avalonia; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Threading; +using Avalonia.Styling; +using Avalonia.VisualTree; +using FinalToken.Core; + +namespace FinalToken.App; + +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) + { + Width = 380; Height = install is null ? 145 : 180; + RequestedThemeVariant = ThemeVariant.Dark; + WindowDecorations = WindowDecorations.None; CanResize = false; Topmost = true; ShowInTaskbar = false; ShowActivated = false; + var body = Ui.Stack(Ui.Text(title, 19), Ui.Text(message)); + if (install is not null) + { + var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 }; + actions.Children.Add(Ui.Button(installLabel ?? "Install", () => { install(); Close(); })); + actions.Children.Add(Ui.Button("Not now", () => { dismiss?.Invoke(); Close(); })); + body.Children.Add(actions); + } + var card = Ui.Card(body); card.Background = Brush.Parse("#202C40"); + body.Resources["TextControlForeground"] = Brushes.WhiteSmoke; + foreach (var text in body.Children.OfType()) text.Foreground = Brushes.WhiteSmoke; + ((TextBlock)body.Children[0]).Foreground = accent ?? Brushes.WhiteSmoke; + Content = card; + PointerPressed += (_, e) => + { + var source = e.Source as Control; + if (source is not Button && source?.FindAncestorOfType