feat: add FinalToken v1 for Claude and Codex usage #2
@@ -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
|
||||||
@@ -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.
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
Closes #
|
||||||
|
|
||||||
|
## What and why
|
||||||
|
|
||||||
|
## Decisions
|
||||||
|
|
||||||
|
<!-- The recorded decisions (D…) this change implements or touches. -->
|
||||||
|
|
||||||
|
## How it was tested
|
||||||
|
|
||||||
|
<!-- Commands you ran, on which commit, with counts. Name anything you could not run. -->
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
artifacts/
|
||||||
|
**/bin/
|
||||||
|
**/obj/
|
||||||
|
.vs/
|
||||||
|
.idea/
|
||||||
|
*.user
|
||||||
|
*.suo
|
||||||
|
TestResults/
|
||||||
@@ -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 `<Project>.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/<user>`.
|
||||||
|
- 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 `<issue>-<slug>` from `origin/master`,
|
||||||
|
checked out at `../FinalToken-wt/<issue>-<slug>`.
|
||||||
|
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/<exact-model-id>` | 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 `<Version>` 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 `<Version>`; 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.
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<Version>1.0.1</Version>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<LangVersion>14</LangVersion>
|
||||||
|
<Nullable>enable</Nullable>
|
||||||
|
<ImplicitUsings>enable</ImplicitUsings>
|
||||||
|
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
<IsAotCompatible>true</IsAotCompatible>
|
||||||
|
<EnableTrimAnalyzer>true</EnableTrimAnalyzer>
|
||||||
|
<EnableAotAnalyzer>true</EnableAotAnalyzer>
|
||||||
|
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
|
||||||
|
<!-- D1: artifacts stay inside this worktree. -->
|
||||||
|
<BaseOutputPath>$(MSBuildThisFileDirectory)artifacts/bin/$(MSBuildProjectName)/</BaseOutputPath>
|
||||||
|
<BaseIntermediateOutputPath>$(MSBuildThisFileDirectory)artifacts/obj/$(MSBuildProjectName)/</BaseIntermediateOutputPath>
|
||||||
|
</PropertyGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<Project>
|
||||||
|
<PropertyGroup>
|
||||||
|
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageVersion Include="Avalonia.Desktop" Version="12.1.4" />
|
||||||
|
<PackageVersion Include="Avalonia.Themes.Fluent" Version="12.1.4" />
|
||||||
|
<PackageVersion Include="Avalonia.Headless" Version="12.1.4" />
|
||||||
|
<PackageVersion Include="CommunityToolkit.Mvvm" Version="8.4.2" />
|
||||||
|
<PackageVersion Include="xunit.v3.aot.mtp-v2" Version="4.0.2" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<Solution>
|
||||||
|
<Folder Name="/src/">
|
||||||
|
<Project Path="src/FinalToken.Core/FinalToken.Core.csproj" />
|
||||||
|
<Project Path="src/FinalToken.Cli/FinalToken.Cli.csproj" />
|
||||||
|
<Project Path="src/FinalToken.App/FinalToken.App.csproj" />
|
||||||
|
<Project Path="src/FinalToken.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||||
|
</Folder>
|
||||||
|
<Folder Name="/tests/">
|
||||||
|
<Project Path="tests/FinalToken.ProcessHost/FinalToken.ProcessHost.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.App.Tests/FinalToken.App.Tests.csproj" />
|
||||||
|
<Project Path="tests/FinalToken.StreamDeck.Tests/FinalToken.StreamDeck.Tests.csproj" />
|
||||||
|
</Folder>
|
||||||
|
</Solution>
|
||||||
@@ -1,2 +1,57 @@
|
|||||||
# FinalToken
|
# 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.
|
||||||
|
|
||||||
|
|||||||
@@ -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 #<N> 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/<N> | 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...<sha>`. 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 ^<old sha> ^origin/master <sha>`. 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 <N> <sha> <pass|fail> <file>`:
|
||||||
|
|
||||||
|
```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.
|
||||||
@@ -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 `<config>/projects/**/*.jsonl`, where `<config>` 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 `<home>/sessions/**/rollout-*.jsonl` and
|
||||||
|
`<home>/archived_sessions/**/rollout-*.jsonl`, where `<home>` 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 `<app directory>/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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"sdk": { "version": "10.0.100", "rollForward": "latestFeature" },
|
||||||
|
"test": { "runner": "Microsoft.Testing.Platform" }
|
||||||
|
}
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -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];
|
||||||
|
/// <summary>At most five ticks. Token steps are whole numbers rounded up to 1, 2 or 5 times a power of ten.</summary>
|
||||||
|
public static IReadOnlyList<double> 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<ChartValue> 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.##}%");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<Task> work)
|
||||||
|
{
|
||||||
|
try { await work(); }
|
||||||
|
catch (OperationCanceledException) { }
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
engine?.Diagnostics.Add(null, "host-operation", "A desktop operation failed.");
|
||||||
|
model.Message = "Operation failed. See diagnostics.";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
|
<AssemblyName>FinalToken</AssemblyName>
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Avalonia.Desktop" />
|
||||||
|
<PackageReference Include="Avalonia.Themes.Fluent" />
|
||||||
|
<PackageReference Include="CommunityToolkit.Mvvm" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<ChartValue> Values);
|
||||||
|
public sealed record HistoryView(IReadOnlyList<ChartValue> Hourly, IReadOnlyList<ChartValue> Daily,
|
||||||
|
IReadOnlyList<LimitChart> Limits, IReadOnlyList<BreakdownRow> Models, IReadOnlyList<BreakdownRow> 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<Diagnostic> 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<ChartValue> 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<ChartValue> 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<BreakdownRow> 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() };
|
||||||
|
}
|
||||||
@@ -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<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++);
|
||||||
|
label.Margin = new Thickness(0, 0, 14, 0); legend.Children.Add(label);
|
||||||
|
}
|
||||||
|
return legend;
|
||||||
|
}
|
||||||
|
private static Border Breakdown(string title, IReadOnlyList<BreakdownRow> 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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<TextBlock>()) 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<Button>() is null)
|
||||||
|
{ open(); Close(); e.Handled = true; }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
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.Projection is { } projection ? $" At this rate: 100% at {Display.Projection(projection)}." : ""), open, accent: PaceBar.Colour(alert.State));
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PopupStack(Action open, TimeProvider? clock = null) : IDisposable
|
||||||
|
{
|
||||||
|
private readonly List<PopupWindow> windows = [];
|
||||||
|
public void Pace(PopupEvent alert) => Show(PopupWindow.Pace(alert, open));
|
||||||
|
public void Show(PopupWindow window)
|
||||||
|
{
|
||||||
|
windows.Add(window);
|
||||||
|
window.Closed += (_, _) => { windows.Remove(window); Position(); };
|
||||||
|
window.Show(); Position();
|
||||||
|
// D8: timer callbacks are off the UI thread; closing always marshals back.
|
||||||
|
var timer = (clock ?? TimeProvider.System).CreateTimer(_ => Dispatcher.UIThread.Post(window.Close),
|
||||||
|
null, TimeSpan.FromSeconds(8), Timeout.InfiniteTimeSpan);
|
||||||
|
window.Closed += (_, _) => timer.Dispose();
|
||||||
|
}
|
||||||
|
private void Position()
|
||||||
|
{
|
||||||
|
var bottom = 0;
|
||||||
|
foreach (var window in windows)
|
||||||
|
{
|
||||||
|
var screen = window.Screens.Primary;
|
||||||
|
if (screen is null) continue;
|
||||||
|
var area = screen.WorkingArea; var scale = screen.Scaling;
|
||||||
|
bottom += (int)(window.Height * scale) + 12;
|
||||||
|
window.Position = new PixelPoint(area.Right - (int)(window.Width * scale) - 16, area.Bottom - bottom - 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public void Dispose() { foreach (var window in windows.ToArray()) window.Close(); }
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public static class Program
|
||||||
|
{
|
||||||
|
internal static RefreshEngine? Engine { get; private set; }
|
||||||
|
internal static string? StartupError { get; private set; }
|
||||||
|
[STAThread]
|
||||||
|
public static int Main(string[] args)
|
||||||
|
{
|
||||||
|
StoreLock? storeLock = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var directory = DataPaths.DataDirectory;
|
||||||
|
storeLock = StoreLock.TryAcquire(directory);
|
||||||
|
if (storeLock is null)
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows()) WindowsActivation.AllowRunningInstance();
|
||||||
|
ActivationFile.RequestAsync(directory).GetAwaiter().GetResult(); return 0;
|
||||||
|
}
|
||||||
|
try { Engine = new RefreshEngine(directory, appPath: Environment.ProcessPath); }
|
||||||
|
catch (InvalidDataException e) { StartupError = e.Message; }
|
||||||
|
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
|
||||||
|
return StartupError is null ? 0 : 1;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Engine?.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||||
|
storeLock?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// D8: Avalonia 12.1.4's platform detection selects X11 on Linux (XWayland).
|
||||||
|
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<DesktopApp>().UsePlatformDetect()
|
||||||
|
.With(new X11PlatformOptions()).LogToTrace();
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using FinalToken.Core.StreamDeck;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
public sealed class SettingsWindow : Window
|
||||||
|
{
|
||||||
|
public SettingsWindow(Settings initial, PluginInstallStatus status, Func<Settings, Task> save)
|
||||||
|
{
|
||||||
|
Title = "FinalToken settings"; Width = 620; Height = 800;
|
||||||
|
var body = Ui.Stack(Ui.Text("Settings", 26)); body.Margin = new Thickness(24);
|
||||||
|
var refresh = Number("Token refresh (seconds, 1–60)", (decimal)initial.RefreshInterval.TotalSeconds, 1, 60);
|
||||||
|
var probe = Number("Limit probe (minutes, 1–60)", (decimal)initial.ProbeInterval.TotalMinutes, 1, 60);
|
||||||
|
var threshold = Number("Pace threshold (points)", (decimal)initial.PaceThreshold, 0.1m, 100);
|
||||||
|
var ahead = Check("Ahead popups", initial.PopupAhead); var behind = Check("Behind popups", initial.PopupBehind);
|
||||||
|
var startup = Check("Start with the OS", initial.StartWithOs); var tray = Check("Close to tray", initial.CloseToTray);
|
||||||
|
var claude = ProviderControls("Claude", initial.Claude); var codex = ProviderControls("Codex", initial.Codex);
|
||||||
|
body.Children.Add(Ui.Text("Stream Deck", 19));
|
||||||
|
body.Children.Add(Ui.Text($"{status.State} · shipped {status.ShippedVersion ?? "none"} · installed {status.InstalledVersion ?? "none"}"));
|
||||||
|
var mode = new ComboBox { ItemsSource = new[] { "Off", "Ask", "Automatic" }, SelectedIndex = (int)initial.StreamDeckInstallMode };
|
||||||
|
body.Children.Add(mode);
|
||||||
|
body.Children.Add(Ui.Text("Dismissed plugin version (clear to ask again)"));
|
||||||
|
var dismissed = new TextBox { Text = initial.DismissedPluginVersion ?? "" }; body.Children.Add(dismissed);
|
||||||
|
var error = Ui.Text(""); body.Children.Add(error);
|
||||||
|
var button = new Button { Content = "Save", HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right };
|
||||||
|
button.Click += async (_, _) =>
|
||||||
|
{
|
||||||
|
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,
|
||||||
|
StartWithOs = startup.IsChecked == true, CloseToTray = tray.IsChecked == true, Claude = claude(), Codex = codex(),
|
||||||
|
StreamDeckInstallMode = (InstallMode)mode.SelectedIndex, DismissedPluginVersion = string.IsNullOrWhiteSpace(dismissed.Text) ? null : dismissed.Text.Trim() };
|
||||||
|
if (!value.IsValid) { error.Text = "Check the intervals and pace threshold."; return; }
|
||||||
|
button.IsEnabled = false;
|
||||||
|
try { await save(value); Close(); }
|
||||||
|
catch (OperationCanceledException) { error.Text = "Settings save was cancelled."; button.IsEnabled = true; }
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or InvalidOperationException or ArgumentException)
|
||||||
|
{ error.Text = "Could not apply settings: " + e.Message; button.IsEnabled = true; }
|
||||||
|
};
|
||||||
|
body.Children.Add(button); Content = new ScrollViewer { Content = body };
|
||||||
|
|
||||||
|
NumericUpDown Number(string label, decimal value, decimal min, decimal max)
|
||||||
|
{ 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)
|
||||||
|
{ var c = new CheckBox { Content = label, IsChecked = value }; body.Children.Add(c); return c; }
|
||||||
|
Func<ProviderSettings> ProviderControls(string name, ProviderSettings config)
|
||||||
|
{
|
||||||
|
body.Children.Add(Ui.Text(name, 19));
|
||||||
|
var enabled = Check("Enabled", config.Enabled); var popups = Check("Popups enabled", config.PopupsEnabled);
|
||||||
|
var pa = Check("Ahead", config.PopupAhead); var pb = Check("Behind", config.PopupBehind);
|
||||||
|
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() };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
using System.ComponentModel;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Runtime.Versioning;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
|
||||||
|
namespace FinalToken.App;
|
||||||
|
|
||||||
|
[SupportedOSPlatform("windows")]
|
||||||
|
internal static partial class WindowsActivation
|
||||||
|
{
|
||||||
|
public static void Activate(Window window)
|
||||||
|
{
|
||||||
|
if (window.TryGetPlatformHandle() is not { } platform) return;
|
||||||
|
var handle = platform.Handle;
|
||||||
|
if (SetForegroundWindow(handle) != 0) return;
|
||||||
|
var foreground = GetForegroundWindow();
|
||||||
|
if (foreground == 0) return;
|
||||||
|
var foregroundThread = GetWindowThreadProcessId(foreground, out _);
|
||||||
|
var ownThread = GetCurrentThreadId();
|
||||||
|
if (foregroundThread == ownThread || AttachThreadInput(ownThread, foregroundThread, 1) == 0) return;
|
||||||
|
try { SetForegroundWindow(handle); }
|
||||||
|
finally { AttachThreadInput(ownThread, foregroundThread, 0); }
|
||||||
|
}
|
||||||
|
// D8: a launcher transfers its foreground permission before the running app activates.
|
||||||
|
public static void AllowRunningInstance()
|
||||||
|
{
|
||||||
|
using var current = Process.GetCurrentProcess();
|
||||||
|
foreach (var candidate in Process.GetProcessesByName(current.ProcessName))
|
||||||
|
{
|
||||||
|
using (candidate)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (candidate.Id != current.Id && candidate.SessionId == current.SessionId &&
|
||||||
|
string.Equals(candidate.MainModule?.FileName, Environment.ProcessPath, StringComparison.OrdinalIgnoreCase))
|
||||||
|
AllowSetForegroundWindow(candidate.Id);
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is Win32Exception or InvalidOperationException) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[LibraryImport("user32.dll")]
|
||||||
|
private static partial int AllowSetForegroundWindow(int processId);
|
||||||
|
[LibraryImport("user32.dll")]
|
||||||
|
private static partial int SetForegroundWindow(nint window);
|
||||||
|
[LibraryImport("user32.dll")]
|
||||||
|
private static partial nint GetForegroundWindow();
|
||||||
|
[LibraryImport("user32.dll")]
|
||||||
|
private static partial uint GetWindowThreadProcessId(nint window, out uint processId);
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
private static partial uint GetCurrentThreadId();
|
||||||
|
[LibraryImport("user32.dll")]
|
||||||
|
private static partial int AttachThreadInput(uint first, uint second, int attach);
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# CLI
|
||||||
|
NativeAOT console host for D1, D5, D6 and D9. Exit codes: success 0, failure 1, usage 2.
|
||||||
|
Assembly/executable name is `finaltoken-cli` on every platform, beside the `FinalToken` app.
|
||||||
|
A busy store is read-only. Keep argument parsing in CliApplication for tests.
|
||||||
|
Pass no app path to RefreshEngine; preserve the desktop path from an existing snapshot.
|
||||||
|
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.Cli;
|
||||||
|
|
||||||
|
public static class CliApplication
|
||||||
|
{
|
||||||
|
public static async Task<int> RunAsync(string[] args, TextWriter output, TextWriter error,
|
||||||
|
string? dataDirectory = null, Func<string, RefreshEngine>? engineFactory = null, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (args.Length == 0 || args[0] != "status" || args.Skip(1).Any(a => a is not ("--json" or "--no-probe")) ||
|
||||||
|
args.Skip(1).Distinct().Count() != args.Length - 1)
|
||||||
|
{ await error.WriteLineAsync("Usage: finaltoken-cli status [--json] [--no-probe]"); return 2; }
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||||
|
using var storeLock = StoreLock.TryAcquire(directory);
|
||||||
|
Snapshot snapshot;
|
||||||
|
if (storeLock is null)
|
||||||
|
{
|
||||||
|
await error.WriteLineAsync("Store is in use; reading the existing snapshot without refreshing.");
|
||||||
|
var result = SnapshotFile.Read(directory);
|
||||||
|
if (result.Snapshot is not { } existing) { await error.WriteLineAsync(result.Error); return 1; }
|
||||||
|
if (result.IsStale) await error.WriteLineAsync("Snapshot is stale.");
|
||||||
|
snapshot = existing;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await using var engine = engineFactory?.Invoke(directory) ?? new RefreshEngine(directory);
|
||||||
|
snapshot = await engine.RefreshNowAsync(args.Contains("--no-probe"), cancellationToken);
|
||||||
|
foreach (var diagnostic in engine.RecentDiagnostics)
|
||||||
|
await error.WriteLineAsync($"{diagnostic.Code} (x{diagnostic.Count}, last {diagnostic.Time:O}): {diagnostic.Summary}");
|
||||||
|
}
|
||||||
|
if (args.Contains("--json")) await output.WriteLineAsync(JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot));
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await output.WriteLineAsync($"FinalToken {snapshot.MadeAt:O}");
|
||||||
|
foreach (var provider in snapshot.Providers)
|
||||||
|
{
|
||||||
|
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}");
|
||||||
|
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}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{ await error.WriteLineAsync("FinalToken could not complete the refresh or read the snapshot."); return 1; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<AssemblyName>finaltoken-cli</AssemblyName>
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
using FinalToken.Cli;
|
||||||
|
|
||||||
|
return await CliApplication.RunAsync(args, Console.Out, Console.Error);
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# Core
|
||||||
|
UI-free domain and file/CLI integration. Implements D1–D7, D9 and the D11 installer contract.
|
||||||
|
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
|
||||||
|
overwrite initializers for missing JSON members. Treat settings as values; update them with `with`.
|
||||||
|
Events from RefreshEngine run on a worker thread; UI hosts must marshal them.
|
||||||
|
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
|
||||||
|
|
||||||
|
## Host contract
|
||||||
|
|
||||||
|
- Acquire `StoreLock.TryAcquire(dataDirectory)` before creating a writing engine. A busy app calls
|
||||||
|
`ActivationFile.RequestAsync` and exits; a busy CLI uses `SnapshotFile.Read`.
|
||||||
|
- Construct `RefreshEngine`, subscribe to `SnapshotChanged`, `PopupRequested` and
|
||||||
|
`ActivationRequested`, then `StartAsync`. `StopAsync` cancels and waits. Dispose asynchronously.
|
||||||
|
The desktop host passes `appPath: Environment.ProcessPath`. Other hosts omit it to keep the
|
||||||
|
previous snapshot's desktop path. A missing path stays null in readers and writers (D9).
|
||||||
|
- Probes return a failed `ProbeResult` for process or protocol failures; shutdown cancellation
|
||||||
|
propagates. The background engine records other tick failures and retries without faulting its loop.
|
||||||
|
- Use `CurrentSnapshot`, `Settings`, `UpdateSettingsAsync`, `RefreshNowAsync` and
|
||||||
|
`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
|
||||||
|
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`.
|
||||||
|
Use `CalendarDays.NextStart` for daily query ends; adding 24 hours is wrong on DST days.
|
||||||
|
- `SnapshotFile.Read` returns a DTO, staleness and a metadata-only error. Serialize with
|
||||||
|
`CoreJsonContext.Default.Snapshot`. `WindowSnapshot.Window` holds the limit; `.Pace` holds D7.
|
||||||
|
- `StreamDeck/` contains `IPluginInstaller`, `PluginInstallStatus`, `InstallPolicy` and platform deployment.
|
||||||
|
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.
|
||||||
|
|
||||||
|
## Store persistence and scaling
|
||||||
|
|
||||||
|
- Refresh changes append as one durable, newline-terminated transaction to
|
||||||
|
`history.journal.jsonl`. Ignore a torn final line on load; reject a corrupt complete line.
|
||||||
|
Before another append, truncate the torn tail. Hosts still hold `StoreLock` (D5).
|
||||||
|
- At 8 MiB, compact committed changes into UTC monthly `history/yyyy-MM.json` files, then
|
||||||
|
atomically replace `history.state.json`, then reset the journal. Absolute bucket upserts,
|
||||||
|
exact sample sets and checkpoint sequences make interrupted compaction replay idempotent.
|
||||||
|
Ordinary idle saves write nothing. `CompactAsync` is an explicit maintenance operation.
|
||||||
|
- Keep three monthly partitions in memory. Bucket updates use keyed lookup. Journal overlays
|
||||||
|
are bounded by compaction; scanner/session metadata remains one entry per observed source or
|
||||||
|
session. Queries load only overlapping months and preserve their existing public signatures.
|
||||||
|
- Claude imports and response keys have a 60-day horizon, twice the default 30-day cleanup.
|
||||||
|
Keys expire daily; entries older than the horizon are ignored even after a key expires.
|
||||||
|
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.
|
||||||
|
- Store changed percent/reset samples and at most one unchanged sample per window per hour.
|
||||||
|
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
|
||||||
|
a per-window time index for ordered lookup.
|
||||||
|
Successful unchanged probes refresh the in-memory sample age without writing history before
|
||||||
|
that hourly point. The latest window set remains separate from the history samples.
|
||||||
|
- A scanner compares length, last-write time and creation time before opening a source file.
|
||||||
|
Unchanged files stay closed; changed files retain prefix/tail replacement checks. A replacement
|
||||||
|
that preserves all those metadata fields cannot be distinguished from an unchanged file.
|
||||||
|
- Readers of replaced files use `FileShare.ReadWrite | FileShare.Delete`. Atomic replacements
|
||||||
|
use `File.Replace` for existing targets and retry Windows sharing failures for at most 500 ms.
|
||||||
|
- Diagnostics fold by provider/code; `Count` is additive and `Time` is the latest occurrence.
|
||||||
|
Synthetic Claude entries are silent. No message text appears in a diagnostic or journal.
|
||||||
|
- ProcessRunner redirects all three handles, closes non-interactive stdin and sets explicit
|
||||||
|
UTF-8 encodings. A WinExe's default console encoding corrupts UTF-8 provider JSON (D3, D6).
|
||||||
|
`tests/FinalToken.ProcessHost` reproduces the missing-console case without a provider login.
|
||||||
|
- Claude usage prose is silent. Diagnose only malformed `Current ...` lines before the
|
||||||
|
contributing section, where parsing stops. No legacy development-store migration is supported.
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public static class AtomicFile
|
||||||
|
{
|
||||||
|
// D5: same-directory rename; a reader sees either complete version.
|
||||||
|
public static Task WriteAsync(string path, string contents, CancellationToken cancellationToken = default)
|
||||||
|
=> WriteAsync(path, contents, cancellationToken, TimeProvider.System);
|
||||||
|
public static async Task WriteAsync(string path, string contents, CancellationToken cancellationToken, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
|
||||||
|
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None,
|
||||||
|
4096, FileOptions.Asynchronous | FileOptions.WriteThrough))
|
||||||
|
{
|
||||||
|
await stream.WriteAsync(Encoding.UTF8.GetBytes(contents), cancellationToken).ConfigureAwait(false);
|
||||||
|
await stream.FlushAsync(cancellationToken).ConfigureAwait(false);
|
||||||
|
stream.Flush(true);
|
||||||
|
}
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
for (var attempt = 0; ; attempt++)
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(path)) File.Replace(temporary, path, null);
|
||||||
|
else File.Move(temporary, path);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (OperatingSystem.IsWindows() &&
|
||||||
|
e is IOException or UnauthorizedAccessException && (e.HResult & 0xffff) is 5 or 32 or 33)
|
||||||
|
{
|
||||||
|
// Windows can report ACCESS_DENIED for an open destination as well as SHARING_VIOLATION.
|
||||||
|
if (attempt == 10) throw new IOException("Atomic replacement remained blocked after 500 ms.", e);
|
||||||
|
await Task.Delay(TimeSpan.FromMilliseconds(50), timeProvider, cancellationToken).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally { if (File.Exists(temporary)) File.Delete(temporary); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The host must hold this for the entire lifetime of a writing HistoryStore/RefreshEngine (D5).</summary>
|
||||||
|
public sealed class StoreLock : IDisposable
|
||||||
|
{
|
||||||
|
private readonly FileStream stream;
|
||||||
|
private StoreLock(FileStream stream) => this.stream = stream;
|
||||||
|
public static StoreLock? TryAcquire(string directory)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try { return new(new FileStream(Path.Combine(directory, "store.lock"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)); }
|
||||||
|
catch (IOException) { return null; }
|
||||||
|
}
|
||||||
|
public void Dispose() => stream.Dispose();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class ActivationFile
|
||||||
|
{
|
||||||
|
public static Task RequestAsync(string directory, CancellationToken cancellationToken = default) =>
|
||||||
|
AtomicFile.WriteAsync(Path.Combine(directory, "activate.request"), Guid.NewGuid().ToString("N"), cancellationToken);
|
||||||
|
public static string? ReadRequest(string directory)
|
||||||
|
{
|
||||||
|
try { return SharedFile.ReadAllText(Path.Combine(directory, "activate.request")); }
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class SharedFile
|
||||||
|
{
|
||||||
|
public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read,
|
||||||
|
FileShare.ReadWrite | FileShare.Delete, 65536, FileOptions.SequentialScan);
|
||||||
|
public static string ReadAllText(string path)
|
||||||
|
{
|
||||||
|
using var stream = OpenRead(path);
|
||||||
|
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||||
|
return reader.ReadToEnd();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
/// <summary>Local calendar boundaries, including 23/25-hour days. Midnight overlaps choose
|
||||||
|
/// the earlier instant; midnight gaps start at the first valid local minute.</summary>
|
||||||
|
public static class CalendarDays
|
||||||
|
{
|
||||||
|
/// <summary>Start of a specified local calendar date; midnight gaps and overlaps follow the same policy as Start(instant).</summary>
|
||||||
|
public static DateTimeOffset Start(DateTime date, TimeZoneInfo? zone = null)
|
||||||
|
=> AtStart(DateTime.SpecifyKind(date.Date, DateTimeKind.Unspecified), zone ?? TimeZoneInfo.Local);
|
||||||
|
public static DateTimeOffset Start(DateTimeOffset instant, TimeZoneInfo? zone = null)
|
||||||
|
{
|
||||||
|
zone ??= TimeZoneInfo.Local;
|
||||||
|
return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date, zone);
|
||||||
|
}
|
||||||
|
public static DateTimeOffset NextStart(DateTimeOffset instant, TimeZoneInfo? zone = null)
|
||||||
|
{
|
||||||
|
zone ??= TimeZoneInfo.Local;
|
||||||
|
return AtStart(TimeZoneInfo.ConvertTime(instant, zone).Date.AddDays(1), zone);
|
||||||
|
}
|
||||||
|
private static DateTimeOffset AtStart(DateTime date, TimeZoneInfo zone)
|
||||||
|
{
|
||||||
|
while (zone.IsInvalidTime(date)) date = date.AddMinutes(1);
|
||||||
|
var offset = zone.IsAmbiguousTime(date) ? zone.GetAmbiguousTimeOffsets(date).Max() : zone.GetUtcOffset(date);
|
||||||
|
return new(date, offset);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
public static partial class ClaudeUsageParser
|
||||||
|
{
|
||||||
|
[GeneratedRegex(@"^Current (?<label>session|week \([^)]+\)): (?<used>\d+(?:\.\d+)?)% used\s*[·•]\s*resets (?<date>[A-Za-z]{3} \d{1,2}), (?<clock>\d{1,2}(?::\d{2})?[ap]m) \((?<zone>[^)]+)\)$", RegexOptions.CultureInvariant)]
|
||||||
|
private static partial Regex UsageLine();
|
||||||
|
|
||||||
|
public static IReadOnlyList<LimitWindow> ParseEnvelope(string json, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(json);
|
||||||
|
var root = document.RootElement;
|
||||||
|
if (root.Field("is_error").ValueKind != JsonValueKind.False || root.Field("num_turns").Integer() != 0 ||
|
||||||
|
root.Text("local_command") != "usage" || root.Text("result") is not { } text)
|
||||||
|
{ diagnostics.Add(Provider.Claude, "claude-envelope", "Usage command did not return a successful local result."); return []; }
|
||||||
|
return ParseText(text, sampleTime, diagnostics);
|
||||||
|
}
|
||||||
|
catch (JsonException) { diagnostics.Add(Provider.Claude, "claude-envelope", "Malformed usage response."); return []; }
|
||||||
|
}
|
||||||
|
public static IReadOnlyList<LimitWindow> ParseText(string text, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
List<LimitWindow> windows = [];
|
||||||
|
foreach (var raw in text.Split('\n'))
|
||||||
|
{
|
||||||
|
var line = raw.Trim();
|
||||||
|
if (line.StartsWith("What's contributing to your limits usage?", StringComparison.Ordinal)) break;
|
||||||
|
if (!line.StartsWith("Current ", StringComparison.Ordinal)) continue;
|
||||||
|
var match = UsageLine().Match(line);
|
||||||
|
if (!match.Success)
|
||||||
|
{ diagnostics.Add(Provider.Claude, "claude-usage-line", "Unknown usage line skipped."); continue; }
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var used = double.Parse(match.Groups["used"].Value, CultureInfo.InvariantCulture);
|
||||||
|
if (used is < 0 or > 100) throw new FormatException();
|
||||||
|
var label = match.Groups["label"].Value;
|
||||||
|
var length = label == "session" ? TimeSpan.FromHours(5) : TimeSpan.FromDays(7);
|
||||||
|
var zone = TimeZoneInfo.FindSystemTimeZoneById(match.Groups["zone"].Value);
|
||||||
|
var local = TimeZoneInfo.ConvertTime(sampleTime, zone);
|
||||||
|
DateTimeOffset? reset = null;
|
||||||
|
foreach (var year in new[] { local.Year, local.Year + 1 })
|
||||||
|
{
|
||||||
|
var date = DateTime.ParseExact($"{year} {match.Groups["date"].Value}, {match.Groups["clock"].Value}",
|
||||||
|
["yyyy MMM d, h:mmtt", "yyyy MMM d, htt"], CultureInfo.InvariantCulture, DateTimeStyles.None);
|
||||||
|
if (zone.IsInvalidTime(date) || zone.IsAmbiguousTime(date)) continue;
|
||||||
|
var candidate = new DateTimeOffset(TimeZoneInfo.ConvertTimeToUtc(date, zone));
|
||||||
|
if (candidate > sampleTime && candidate - sampleTime <= length) { reset = candidate; break; }
|
||||||
|
}
|
||||||
|
if (reset is null) throw new FormatException();
|
||||||
|
windows.Add(new(Provider.Claude, label.ToLowerInvariant(), "Current " + label, used, reset, length, sampleTime, "usage"));
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is FormatException or TimeZoneNotFoundException or InvalidTimeZoneException or ArgumentException)
|
||||||
|
{ diagnostics.Add(Provider.Claude, "claude-reset-parse", "Unknown or invalid usage reset skipped."); }
|
||||||
|
}
|
||||||
|
return windows;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
public sealed record ScanResult(int AddedEvents, IReadOnlyList<LimitWindow> CodexFallback,
|
||||||
|
int ClaudeAdded = 0, int CodexAdded = 0);
|
||||||
|
|
||||||
|
/// <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>
|
||||||
|
public sealed class IncrementalScanner(HistoryStore history, DiagnosticLog diagnostics,
|
||||||
|
string claudeDirectory, string codexDirectory)
|
||||||
|
{
|
||||||
|
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||||
|
public async Task<ScanResult> ScanAsync(CancellationToken cancellationToken = default,
|
||||||
|
bool claudeEnabled = true, bool codexEnabled = true)
|
||||||
|
{
|
||||||
|
var added = 0;
|
||||||
|
var claudeFiles = claudeEnabled ? FindFiles(Path.Combine(claudeDirectory, "projects"), "*.jsonl", Provider.Claude) : [];
|
||||||
|
foreach (var path in claudeFiles)
|
||||||
|
added += await ScanFileAsync(path, Provider.Claude, [], cancellationToken);
|
||||||
|
var claudeAdded = added;
|
||||||
|
var codexFiles = !codexEnabled ? [] : FindFiles(Path.Combine(codexDirectory, "sessions"), "rollout-*.jsonl", Provider.Codex)
|
||||||
|
.Concat(FindFiles(Path.Combine(codexDirectory, "archived_sessions"), "rollout-*.jsonl", Provider.Codex))
|
||||||
|
.OrderBy(File.GetLastWriteTimeUtc).ToArray();
|
||||||
|
// D4 fallback belongs to the newest rollout, even when it had no appended bytes this time.
|
||||||
|
var latest = codexFiles.LastOrDefault();
|
||||||
|
List<LimitWindow> fallback = [];
|
||||||
|
foreach (var path in codexFiles)
|
||||||
|
{
|
||||||
|
List<LimitWindow> limits = [];
|
||||||
|
added += await ScanFileAsync(path, Provider.Codex, limits, cancellationToken);
|
||||||
|
if (path == latest && limits.Count > 0) fallback = limits;
|
||||||
|
}
|
||||||
|
if (latest is not null && fallback.Count == 0) fallback = history.Cursor(latest).LatestLimits;
|
||||||
|
return new(added, fallback, claudeAdded, added - claudeAdded);
|
||||||
|
}
|
||||||
|
private IReadOnlyList<string> FindFiles(string directory, string pattern, Provider provider)
|
||||||
|
{
|
||||||
|
try { return Directory.Exists(directory) ? Directory.GetFiles(directory, pattern, SearchOption.AllDirectories) : []; }
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||||
|
{ diagnostics.Add(provider, "scan-directory", "Source directory cannot be enumerated."); return []; }
|
||||||
|
}
|
||||||
|
private async Task<int> ScanFileAsync(string path, Provider provider, List<LimitWindow> latestLimits, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
var info = new FileInfo(path);
|
||||||
|
var cursor = history.Cursor(path);
|
||||||
|
var length = info.Length;
|
||||||
|
var lastWrite = info.LastWriteTimeUtc.Ticks;
|
||||||
|
var creation = info.CreationTimeUtc.Ticks;
|
||||||
|
if (cursor.ObservedLength == length && cursor.LastWriteTicks == lastWrite && cursor.CreationTicks == creation)
|
||||||
|
return 0;
|
||||||
|
await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete,
|
||||||
|
65536, FileOptions.Asynchronous | FileOptions.SequentialScan);
|
||||||
|
if (stream.Length < cursor.Offset || cursor.CreationTicks != creation ||
|
||||||
|
cursor.PrefixHash != Fingerprint(stream, 0, cursor.PrefixLength) ||
|
||||||
|
cursor.TailHash != Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset)))
|
||||||
|
{
|
||||||
|
cursor.Offset = 0;
|
||||||
|
cursor.SessionId = Path.GetFileNameWithoutExtension(path);
|
||||||
|
cursor.Model = null;
|
||||||
|
cursor.Project = null;
|
||||||
|
cursor.LatestLimits = [];
|
||||||
|
}
|
||||||
|
var added = 0;
|
||||||
|
stream.Position = cursor.Offset;
|
||||||
|
var readBuffer = new byte[65536];
|
||||||
|
using var line = new MemoryStream();
|
||||||
|
var consumed = cursor.Offset;
|
||||||
|
int read;
|
||||||
|
while ((read = await stream.ReadAsync(readBuffer, cancellationToken)) > 0)
|
||||||
|
{
|
||||||
|
var start = 0;
|
||||||
|
while (start < read)
|
||||||
|
{
|
||||||
|
var newline = readBuffer.AsSpan(start, read - start).IndexOf((byte)'\n');
|
||||||
|
var segmentLength = newline < 0 ? read - start : newline;
|
||||||
|
line.Write(readBuffer.AsSpan(start, segmentLength));
|
||||||
|
consumed += segmentLength;
|
||||||
|
start += segmentLength;
|
||||||
|
if (newline < 0) break;
|
||||||
|
consumed++;
|
||||||
|
start++;
|
||||||
|
cancellationToken.ThrowIfCancellationRequested();
|
||||||
|
// Source entries can contain large tool results. An output-capture bound
|
||||||
|
// belongs to child processes, not to valid transcript records (D3).
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var text = StrictUtf8.GetString(line.GetBuffer(), 0, (int)line.Length).TrimEnd('\r');
|
||||||
|
if (text.Length > 0 && provider == Provider.Claude)
|
||||||
|
{
|
||||||
|
if (TranscriptParser.Parse(text, diagnostics) is { } usage && history.Add(usage)) added++;
|
||||||
|
}
|
||||||
|
else if (text.Length > 0)
|
||||||
|
{
|
||||||
|
var entry = RolloutParser.Parse(text, cursor, DateTimeOffset.UtcNow, diagnostics);
|
||||||
|
if (entry.CumulativeUsage is { } usage && history.AddCodex(cursor.SessionId!, usage)) added++;
|
||||||
|
if (entry.Limits.Count > 0)
|
||||||
|
{
|
||||||
|
latestLimits.Clear(); latestLimits.AddRange(entry.Limits);
|
||||||
|
cursor.LatestLimits = entry.Limits.ToList();
|
||||||
|
}
|
||||||
|
history.AddLimits(entry.Limits);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (DecoderFallbackException) { diagnostics.Add(provider, "scan-encoding", "Invalid UTF-8 source line skipped."); }
|
||||||
|
}
|
||||||
|
cursor.Offset = consumed;
|
||||||
|
line.SetLength(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor.CreationTicks = creation;
|
||||||
|
cursor.PrefixLength = (int)Math.Min(256, cursor.Offset);
|
||||||
|
cursor.PrefixHash = Fingerprint(stream, 0, cursor.PrefixLength);
|
||||||
|
cursor.TailHash = Fingerprint(stream, Math.Max(0, cursor.Offset - 256), (int)Math.Min(256, cursor.Offset));
|
||||||
|
cursor.ObservedLength = length;
|
||||||
|
cursor.LastWriteTicks = lastWrite;
|
||||||
|
history.CursorChanged(path);
|
||||||
|
return added;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
|
||||||
|
{ diagnostics.Add(provider, "scan-file", "Source file cannot be read."); return 0; }
|
||||||
|
}
|
||||||
|
private static string Fingerprint(FileStream stream, long offset, int length)
|
||||||
|
{
|
||||||
|
if (length == 0) return "";
|
||||||
|
stream.Position = offset;
|
||||||
|
var bytes = new byte[length];
|
||||||
|
var count = stream.ReadAtLeast(bytes, length, false);
|
||||||
|
return Convert.ToHexString(SHA256.HashData(bytes.AsSpan(0, count)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
internal static class JsonFields
|
||||||
|
{
|
||||||
|
public static JsonElement Field(this JsonElement element, string name) =>
|
||||||
|
element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) ? value : default;
|
||||||
|
public static string? Text(this JsonElement element) => element.ValueKind == JsonValueKind.String ? element.GetString() : null;
|
||||||
|
public static string? Text(this JsonElement element, string name) => element.Field(name).Text();
|
||||||
|
public static long? Integer(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetInt64(out var value) ? value : null;
|
||||||
|
public static double? Number(this JsonElement element) => element.ValueKind == JsonValueKind.Number && element.TryGetDouble(out var value) && double.IsFinite(value) ? value : null;
|
||||||
|
public static DateTimeOffset? Timestamp(this JsonElement element) => element.Text() is { } text &&
|
||||||
|
DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var time) ? time.ToUniversalTime() : null;
|
||||||
|
public static long Count(this JsonElement element, string name, bool required = false)
|
||||||
|
{
|
||||||
|
var field = element.Field(name);
|
||||||
|
if (!required && field.ValueKind == JsonValueKind.Undefined) return 0;
|
||||||
|
if (field.Integer() is not { } count || count is < 0 or > 1_000_000_000_000_000) throw new FormatException();
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
public static TokenCounts Counts(JsonElement usage, bool claude)
|
||||||
|
{
|
||||||
|
var input = usage.Count("input_tokens", true);
|
||||||
|
var output = usage.Count("output_tokens", true);
|
||||||
|
var read = usage.Count(claude ? "cache_read_input_tokens" : "cached_input_tokens");
|
||||||
|
var write = usage.Count(claude ? "cache_creation_input_tokens" : "cache_write_input_tokens");
|
||||||
|
var reasoning = claude ? 0 : usage.Count("reasoning_output_tokens");
|
||||||
|
return new(input, read, write, output, reasoning,
|
||||||
|
claude ? checked(input + output + read + write) : usage.Count("total_tokens", true));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
using FinalToken.Core.Processes;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
public sealed record ProbeResult(bool Success, IReadOnlyList<LimitWindow> Windows, string? Reason);
|
||||||
|
public sealed class LimitProbe(IProcessRunner runner, DiagnosticLog diagnostics, string dataDirectory)
|
||||||
|
{
|
||||||
|
public async Task<ProbeResult> RunAsync(Provider provider, CliCommand command, DateTimeOffset sampleTime, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await runner.RunAsync(new(command, provider == Provider.Claude
|
||||||
|
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : ["app-server"],
|
||||||
|
dataDirectory, TimeSpan.FromSeconds(60), provider == Provider.Codex), cancellationToken);
|
||||||
|
if (result.TimedOut || result.ExitCode != 0 || result.OutputTruncated)
|
||||||
|
{
|
||||||
|
var reason = result.TimedOut ? "Limit probe timed out." : "Limit probe failed or exceeded its output bound.";
|
||||||
|
diagnostics.Add(provider, result.TimedOut ? "probe-timeout" : "probe-failed", reason);
|
||||||
|
return new(false, [], reason);
|
||||||
|
}
|
||||||
|
var windows = provider == Provider.Claude ? ClaudeUsageParser.ParseEnvelope(result.Output, sampleTime, diagnostics)
|
||||||
|
: CodexLimitsParser.ParseResponse(result.Output, sampleTime, diagnostics);
|
||||||
|
if (windows.Count > 0) return new(true, windows, null);
|
||||||
|
diagnostics.Add(provider, "probe-no-limits", "No usable limit windows returned; CLI may be logged out.");
|
||||||
|
return new(false, [], "No usable limits returned; CLI may be logged out.");
|
||||||
|
}
|
||||||
|
catch (Exception) when (cancellationToken.IsCancellationRequested)
|
||||||
|
{ throw new OperationCanceledException(cancellationToken); }
|
||||||
|
// D2: a provider's process/protocol failure must not interrupt the other provider.
|
||||||
|
// Exception messages can contain child output; expose only fixed metadata.
|
||||||
|
catch (Exception)
|
||||||
|
{ diagnostics.Add(provider, "probe-failed", "CLI probe could not complete."); return new(false, [], "CLI probe could not complete."); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
public sealed record RolloutEntry(UsageEvent? CumulativeUsage, IReadOnlyList<LimitWindow> Limits);
|
||||||
|
|
||||||
|
public static class RolloutParser
|
||||||
|
{
|
||||||
|
public static RolloutEntry Parse(string line, ScanCursor cursor, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(line);
|
||||||
|
var root = document.RootElement;
|
||||||
|
var payload = root.Field("payload");
|
||||||
|
switch (root.Text("type"))
|
||||||
|
{
|
||||||
|
case "session_meta":
|
||||||
|
cursor.SessionId = payload.Text("id") ?? cursor.SessionId;
|
||||||
|
cursor.Project = payload.Text("cwd") ?? cursor.Project;
|
||||||
|
return new(null, []);
|
||||||
|
case "turn_context":
|
||||||
|
cursor.Model = payload.Text("model");
|
||||||
|
cursor.Project = payload.Text("cwd") ?? cursor.Project;
|
||||||
|
return new(null, []);
|
||||||
|
case "event_msg" when payload.Text("type") == "token_count":
|
||||||
|
if (root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
|
||||||
|
var limits = CodexLimitsParser.Parse(payload.Field("rate_limits"), time, "rollout", diagnostics);
|
||||||
|
if (payload.Field("info").ValueKind == JsonValueKind.Null) return new(null, limits);
|
||||||
|
var counts = JsonFields.Counts(payload.Field("info").Field("total_token_usage"), false);
|
||||||
|
return new(new(Provider.Codex, time, cursor.Model, cursor.Project, counts,
|
||||||
|
$"codex:{cursor.SessionId}:{counts.Total}"), limits);
|
||||||
|
default: return new(null, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
|
||||||
|
{ diagnostics.Add(Provider.Codex, "rollout-parse", "Malformed token count entry skipped."); return new(null, []); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class CodexLimitsParser
|
||||||
|
{
|
||||||
|
public static IReadOnlyList<LimitWindow> Parse(JsonElement value, DateTimeOffset sampleTime, string source, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
if (value.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) return [];
|
||||||
|
List<LimitWindow> windows = [];
|
||||||
|
var camel = source == "app-server";
|
||||||
|
var id = value.Text(camel ? "limitId" : "limit_id") ?? "codex";
|
||||||
|
foreach (var name in new[] { "primary", "secondary" })
|
||||||
|
{
|
||||||
|
var window = value.Field(name);
|
||||||
|
if (window.ValueKind is JsonValueKind.Null or JsonValueKind.Undefined) continue;
|
||||||
|
var used = window.Field(camel ? "usedPercent" : "used_percent").Number();
|
||||||
|
var minutesField = window.Field(camel ? "windowDurationMins" : "window_minutes");
|
||||||
|
var resetField = window.Field(camel ? "resetsAt" : "resets_at");
|
||||||
|
var minutes = minutesField.Integer();
|
||||||
|
var reset = resetField.Integer();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (used is not (>= 0 and <= 100) || minutes is <= 0 or > 525600 ||
|
||||||
|
(minutesField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && minutes is null) ||
|
||||||
|
(resetField.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined) && reset is null)) throw new FormatException();
|
||||||
|
var length = minutes is { } m ? TimeSpan.FromMinutes(m) : (TimeSpan?)null;
|
||||||
|
var resetsAt = reset is { } r ? DateTimeOffset.FromUnixTimeSeconds(r) : (DateTimeOffset?)null;
|
||||||
|
windows.Add(new(Provider.Codex, id + ":" + name,
|
||||||
|
length <= TimeSpan.FromHours(5) ? "Session" : length >= TimeSpan.FromDays(7) ? "Week" : name,
|
||||||
|
used.Value, resetsAt, length, sampleTime, source));
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is FormatException or ArgumentOutOfRangeException)
|
||||||
|
{ diagnostics.Add(Provider.Codex, "codex-limit-parse", "Malformed limit window skipped."); }
|
||||||
|
}
|
||||||
|
return windows;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IReadOnlyList<LimitWindow> ParseResponse(string line, DateTimeOffset sampleTime, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(line);
|
||||||
|
var result = document.RootElement.Field("result");
|
||||||
|
var buckets = result.Field("rateLimitsByLimitId");
|
||||||
|
if (buckets.ValueKind == JsonValueKind.Object)
|
||||||
|
return buckets.EnumerateObject().SelectMany(b => Parse(b.Value, sampleTime, "app-server", diagnostics)).ToArray();
|
||||||
|
return Parse(result.Field("rateLimits"), sampleTime, "app-server", diagnostics);
|
||||||
|
}
|
||||||
|
catch (JsonException) { diagnostics.Add(Provider.Codex, "codex-rpc-parse", "Malformed rate limit response."); return []; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Collectors;
|
||||||
|
|
||||||
|
public static class TranscriptParser
|
||||||
|
{
|
||||||
|
public static UsageEvent? Parse(string line, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(line);
|
||||||
|
var root = document.RootElement;
|
||||||
|
if (root.Text("type") != "assistant") return null;
|
||||||
|
var message = root.Field("message");
|
||||||
|
if (message.Text("model") == "<synthetic>") return null;
|
||||||
|
if (message.Field("usage").ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) return null;
|
||||||
|
var counts = JsonFields.Counts(message.Field("usage"), true);
|
||||||
|
if (root.Text("requestId") is not { Length: > 0 } && counts == new TokenCounts()) return null;
|
||||||
|
if (message.Text("id") is not { Length: > 0 } id || root.Text("requestId") is not { Length: > 0 } request ||
|
||||||
|
root.Field("timestamp").Timestamp() is not { } time) throw new FormatException();
|
||||||
|
// Length prefixes avoid collisions between ids that contain separators (D3).
|
||||||
|
return new(Provider.Claude, time, message.Text("model"), root.Text("cwd"),
|
||||||
|
counts, $"claude:{id.Length}:{id}{request.Length}:{request}");
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is JsonException or FormatException or OverflowException)
|
||||||
|
{ diagnostics.Add(Provider.Claude, "transcript-parse", "Malformed assistant usage entry skipped."); return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk" />
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
internal readonly record struct BucketKey(Provider Provider, DateTimeOffset Hour, string? Model, string? Project)
|
||||||
|
{
|
||||||
|
public static BucketKey For(TokenBucket bucket) => new(bucket.Provider, bucket.Hour, bucket.Model, bucket.Project);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HistoryPartition
|
||||||
|
{
|
||||||
|
public int V { get; set; } = 1;
|
||||||
|
public List<TokenBucket> Buckets { get; set; } = [];
|
||||||
|
public List<LimitWindow> Limits { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HistoryState
|
||||||
|
{
|
||||||
|
public int V { get; set; } = 1;
|
||||||
|
public long Sequence { get; set; }
|
||||||
|
public Dictionary<string, DateTimeOffset> ClaudeKeys { get; set; } = [];
|
||||||
|
public Dictionary<string, TokenCounts> CodexTotals { get; set; } = [];
|
||||||
|
public Dictionary<string, DateTimeOffset> CodexTimes { get; set; } = [];
|
||||||
|
public Dictionary<string, ScanCursor> Cursors { get; set; } = [];
|
||||||
|
public Dictionary<Provider, List<LimitWindow>> LatestWindows { get; set; } = [];
|
||||||
|
public Dictionary<string, LimitWindow> LastSamples { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HistoryTransaction
|
||||||
|
{
|
||||||
|
public int V { get; set; } = 1;
|
||||||
|
public long Sequence { get; set; }
|
||||||
|
public List<TokenBucket> Buckets { get; set; } = [];
|
||||||
|
public List<LimitWindow> Limits { get; set; } = [];
|
||||||
|
public Dictionary<string, DateTimeOffset> ClaudeKeys { get; set; } = [];
|
||||||
|
public List<string> ExpiredClaudeKeys { get; set; } = [];
|
||||||
|
public Dictionary<string, TokenCounts> CodexTotals { get; set; } = [];
|
||||||
|
public Dictionary<string, DateTimeOffset> CodexTimes { get; set; } = [];
|
||||||
|
public Dictionary<string, ScanCursor> Cursors { get; set; } = [];
|
||||||
|
public Dictionary<Provider, List<LimitWindow>> LatestWindows { get; set; } = [];
|
||||||
|
public Dictionary<string, LimitWindow> LastSamples { get; set; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class PartitionIndex
|
||||||
|
{
|
||||||
|
private readonly Dictionary<(Provider, string), SortedSet<LimitWindow>> windowSamples = [];
|
||||||
|
private static readonly IComparer<LimitWindow> SampleTimeComparer = Comparer<LimitWindow>.Create((a, b) => a.SampleTime.CompareTo(b.SampleTime));
|
||||||
|
public Dictionary<BucketKey, TokenBucket> Buckets { get; } = [];
|
||||||
|
public HashSet<LimitWindow> Limits { get; } = [];
|
||||||
|
public void Apply(HistoryPartition partition)
|
||||||
|
{
|
||||||
|
foreach (var bucket in partition.Buckets) Buckets[BucketKey.For(bucket)] = bucket;
|
||||||
|
foreach (var sample in partition.Limits) AddLimit(sample);
|
||||||
|
}
|
||||||
|
public void Apply(PartitionIndex other)
|
||||||
|
{
|
||||||
|
foreach (var (key, bucket) in other.Buckets) Buckets[key] = bucket;
|
||||||
|
foreach (var sample in other.Limits) AddLimit(sample);
|
||||||
|
}
|
||||||
|
public bool AddLimit(LimitWindow sample)
|
||||||
|
{
|
||||||
|
if (!Limits.Add(sample)) return false;
|
||||||
|
var key = (sample.Provider, sample.Id);
|
||||||
|
if (!windowSamples.TryGetValue(key, out var samples)) windowSamples[key] = samples = new(SampleTimeComparer);
|
||||||
|
samples.Add(sample);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
public LimitWindow? PreviousLimit(LimitWindow sample)
|
||||||
|
{
|
||||||
|
if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == 0) return null;
|
||||||
|
return samples.GetViewBetween(sample with { SampleTime = DateTimeOffset.MinValue },
|
||||||
|
sample with { SampleTime = new(sample.SampleTime.UtcTicks - 1, TimeSpan.Zero) }).Max;
|
||||||
|
}
|
||||||
|
public LimitWindow? NextLimit(LimitWindow sample)
|
||||||
|
{
|
||||||
|
if (!windowSamples.TryGetValue((sample.Provider, sample.Id), out var samples) || sample.SampleTime.UtcTicks == DateTimeOffset.MaxValue.UtcTicks) return null;
|
||||||
|
return samples.GetViewBetween(sample with { SampleTime = new(sample.SampleTime.UtcTicks + 1, TimeSpan.Zero) },
|
||||||
|
sample with { SampleTime = DateTimeOffset.MaxValue }).Min;
|
||||||
|
}
|
||||||
|
public HistoryPartition Export() => new() { Buckets = Buckets.Values.ToList(), Limits = Limits.ToList() };
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class HistoryJournal
|
||||||
|
{
|
||||||
|
/// <summary>Only newline-terminated records commit. Returns the byte position of the last complete record.
|
||||||
|
/// A corrupt completed record is an error; a torn final line is deliberately ignored.</summary>
|
||||||
|
public static long Read(string path, Action<HistoryTransaction> apply)
|
||||||
|
{
|
||||||
|
if (!File.Exists(path)) return 0;
|
||||||
|
using var stream = SharedFile.OpenRead(path);
|
||||||
|
using var line = new MemoryStream();
|
||||||
|
var buffer = new byte[65536];
|
||||||
|
long position = 0, committed = 0;
|
||||||
|
int count;
|
||||||
|
while ((count = stream.Read(buffer)) > 0)
|
||||||
|
{
|
||||||
|
var start = 0;
|
||||||
|
while (start < count)
|
||||||
|
{
|
||||||
|
var newline = buffer.AsSpan(start, count - start).IndexOf((byte)'\n');
|
||||||
|
var length = newline < 0 ? count - start : newline;
|
||||||
|
line.Write(buffer.AsSpan(start, length));
|
||||||
|
position += length;
|
||||||
|
start += length;
|
||||||
|
if (newline < 0) break;
|
||||||
|
var transaction = JsonSerializer.Deserialize(line.GetBuffer().AsSpan(0, (int)line.Length), CoreJsonContext.Default.HistoryTransaction)
|
||||||
|
?? throw new JsonException();
|
||||||
|
if (transaction.V != 1 || transaction.Sequence <= 0) throw new JsonException();
|
||||||
|
apply(transaction);
|
||||||
|
committed = ++position;
|
||||||
|
start++;
|
||||||
|
line.SetLength(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return committed;
|
||||||
|
}
|
||||||
|
public static long Append(string path, long committed, HistoryTransaction transaction, CancellationToken token)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
var bytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(transaction, CoreJsonContext.Default.HistoryTransaction) + "\n");
|
||||||
|
using var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read,
|
||||||
|
65536, FileOptions.WriteThrough);
|
||||||
|
// Repair a torn previous append before adding another record.
|
||||||
|
if (stream.Length != committed) stream.SetLength(committed);
|
||||||
|
stream.Position = committed;
|
||||||
|
stream.Write(bytes);
|
||||||
|
stream.Flush(true);
|
||||||
|
return stream.Position;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
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 TokenBreakdown(string? Name, TokenCounts Counts);
|
||||||
|
public enum SeriesInterval { Hour, Day }
|
||||||
|
|
||||||
|
public sealed class ScanCursor
|
||||||
|
{
|
||||||
|
public long Offset { get; set; }
|
||||||
|
public long CreationTicks { get; set; }
|
||||||
|
public string PrefixHash { get; set; } = "";
|
||||||
|
public int PrefixLength { get; set; }
|
||||||
|
public string TailHash { get; set; } = "";
|
||||||
|
public string? SessionId { get; set; }
|
||||||
|
public string? Model { get; set; }
|
||||||
|
public string? Project { get; set; }
|
||||||
|
public List<LimitWindow> LatestLimits { get; set; } = [];
|
||||||
|
public long ObservedLength { get; set; } = -1;
|
||||||
|
public long LastWriteTicks { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>UTC hourly storage; queries use [from,to), including whole boundary hours (D5).
|
||||||
|
/// Data partitions load on demand with a three-month cache; journal replay is bounded by compaction.
|
||||||
|
/// Claude imports and dedupe keys have a 60-day horizon, longer than the CLI's default 30-day cleanup.
|
||||||
|
/// Scanner/session metadata scales with the local source files, not with their token events.</summary>
|
||||||
|
public sealed class HistoryStore
|
||||||
|
{
|
||||||
|
public const int ClaudeRetentionDays = 60;
|
||||||
|
private const long CompactBytes = 8 * 1024 * 1024;
|
||||||
|
private readonly Lock gate = new();
|
||||||
|
private readonly string directory;
|
||||||
|
private readonly TimeProvider clock;
|
||||||
|
private readonly HistoryState state;
|
||||||
|
private readonly Dictionary<string, PartitionIndex> overlays = [];
|
||||||
|
private readonly Dictionary<string, PartitionIndex> pendingPartitions = [];
|
||||||
|
private readonly Dictionary<string, PartitionIndex> cache = [];
|
||||||
|
private readonly LinkedList<string> cacheOrder = [];
|
||||||
|
private readonly HashSet<string> months = [];
|
||||||
|
private HistoryTransaction pending = new();
|
||||||
|
private long journalBytes;
|
||||||
|
private DateTimeOffset prunedDay = DateTimeOffset.MinValue;
|
||||||
|
private string JournalPath => Path.Combine(directory, "history.journal.jsonl");
|
||||||
|
private string StatePath => Path.Combine(directory, "history.state.json");
|
||||||
|
private string PartitionPath(string month) => Path.Combine(directory, "history", month + ".json");
|
||||||
|
|
||||||
|
public HistoryStore(string directory, DiagnosticLog diagnostics) : this(directory, diagnostics, TimeProvider.System) { }
|
||||||
|
public HistoryStore(string directory, DiagnosticLog diagnostics, TimeProvider timeProvider)
|
||||||
|
{
|
||||||
|
this.directory = directory;
|
||||||
|
clock = timeProvider;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
state = File.Exists(StatePath) ? JsonSerializer.Deserialize(SharedFile.ReadAllText(StatePath),
|
||||||
|
CoreJsonContext.Default.HistoryState) ?? throw new JsonException() : new();
|
||||||
|
ValidateState(state);
|
||||||
|
if (Directory.Exists(Path.Combine(directory, "history")))
|
||||||
|
foreach (var path in Directory.GetFiles(Path.Combine(directory, "history"), "*.json"))
|
||||||
|
{
|
||||||
|
var month = Path.GetFileNameWithoutExtension(path);
|
||||||
|
if (!DateTime.TryParseExact(month, "yyyy-MM", CultureInfo.InvariantCulture, DateTimeStyles.None, out _))
|
||||||
|
throw new JsonException();
|
||||||
|
months.Add(month);
|
||||||
|
}
|
||||||
|
journalBytes = HistoryJournal.Read(JournalPath, ApplyTransaction);
|
||||||
|
PruneKeys();
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
||||||
|
{
|
||||||
|
diagnostics.Add(null, "history-invalid", "History cannot be loaded; refusing to overwrite it.");
|
||||||
|
throw new InvalidDataException("History cannot be loaded; restore or move the invalid history file.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal ScanCursor Cursor(string path)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
if (!state.Cursors.TryGetValue(path, out var cursor)) state.Cursors[path] = cursor = new();
|
||||||
|
return cursor;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
internal void CursorChanged(string path)
|
||||||
|
{
|
||||||
|
lock (gate) pending.Cursors[path] = CloneCursor(state.Cursors[path]);
|
||||||
|
}
|
||||||
|
private static ScanCursor CloneCursor(ScanCursor c) => new()
|
||||||
|
{
|
||||||
|
Offset = c.Offset, CreationTicks = c.CreationTicks, PrefixHash = c.PrefixHash,
|
||||||
|
PrefixLength = c.PrefixLength, TailHash = c.TailHash, SessionId = c.SessionId,
|
||||||
|
Model = c.Model, Project = c.Project, LatestLimits = c.LatestLimits.ToList(),
|
||||||
|
ObservedLength = c.ObservedLength, LastWriteTicks = c.LastWriteTicks
|
||||||
|
};
|
||||||
|
|
||||||
|
public bool Add(UsageEvent usage)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
PruneKeys();
|
||||||
|
if (usage.Provider == Provider.Claude && usage.Time < clock.GetUtcNow().AddDays(-ClaudeRetentionDays)) return false;
|
||||||
|
if (state.ClaudeKeys.ContainsKey(usage.DedupeKey)) return false;
|
||||||
|
AddBucket(usage);
|
||||||
|
state.ClaudeKeys[usage.DedupeKey] = usage.Time;
|
||||||
|
pending.ClaudeKeys[usage.DedupeKey] = usage.Time;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
internal bool AddCodex(string session, UsageEvent cumulative)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
var previous = state.CodexTotals.GetValueOrDefault(session);
|
||||||
|
var previousTime = state.CodexTimes.GetValueOrDefault(session, DateTimeOffset.MinValue);
|
||||||
|
// Archive copies and rescans replay earlier totals. A later counter reset is retained,
|
||||||
|
// so its subsequent increases still count, without keeping a key for every token event.
|
||||||
|
if (cumulative.Time < previousTime || cumulative.Time == previousTime && cumulative.Counts.Total <= previous.Total) return false;
|
||||||
|
var delta = cumulative.Counts.IncreaseFrom(previous);
|
||||||
|
if (delta.Total > 0) AddBucket(cumulative with { Counts = delta });
|
||||||
|
state.CodexTotals[session] = pending.CodexTotals[session] = cumulative.Counts;
|
||||||
|
state.CodexTimes[session] = pending.CodexTimes[session] = cumulative.Time;
|
||||||
|
return delta.Total > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void PruneKeys()
|
||||||
|
{
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
var day = new DateTimeOffset(now.UtcDateTime.Date, TimeSpan.Zero);
|
||||||
|
if (day == prunedDay) return;
|
||||||
|
prunedDay = day;
|
||||||
|
var cutoff = now.AddDays(-ClaudeRetentionDays);
|
||||||
|
foreach (var key in state.ClaudeKeys.Where(k => k.Value < cutoff).Select(k => k.Key).ToArray())
|
||||||
|
{
|
||||||
|
state.ClaudeKeys.Remove(key);
|
||||||
|
pending.ClaudeKeys.Remove(key);
|
||||||
|
pending.ExpiredClaudeKeys.Add(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void AddBucket(UsageEvent usage)
|
||||||
|
{
|
||||||
|
var bucket = new TokenBucket(usage.Provider, FloorHour(usage.Time), usage.Model, usage.Project, usage.Counts);
|
||||||
|
var key = BucketKey.For(bucket);
|
||||||
|
var month = Month(bucket.Hour);
|
||||||
|
var partition = GetPartition(month);
|
||||||
|
if (partition.Buckets.TryGetValue(key, out var previous)) bucket = bucket with { Counts = previous.Counts + usage.Counts };
|
||||||
|
partition.Buckets[key] = bucket;
|
||||||
|
PendingPartition(month).Buckets[key] = bucket;
|
||||||
|
}
|
||||||
|
public void AddLimits(IEnumerable<LimitWindow> windows)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
var batch = windows.ToArray();
|
||||||
|
HashSet<Provider> changedSets = [];
|
||||||
|
foreach (var group in batch.GroupBy(w => w.Provider))
|
||||||
|
{
|
||||||
|
var newest = group.Max(w => w.SampleTime);
|
||||||
|
if (!state.LatestWindows.TryGetValue(group.Key, out var old) || old.Count == 0 || newest >= old.Max(w => w.SampleTime))
|
||||||
|
{
|
||||||
|
var next = group.Where(w => w.SampleTime == newest).GroupBy(w => w.Id).Select(g => g.Last()).ToList();
|
||||||
|
if (old is null || !old.Select(WindowValue).SequenceEqual(next.Select(WindowValue))) changedSets.Add(group.Key);
|
||||||
|
state.LatestWindows[group.Key] = next;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (var window in batch)
|
||||||
|
{
|
||||||
|
var key = WindowKey(window);
|
||||||
|
var previous = state.LastSamples.GetValueOrDefault(key);
|
||||||
|
var month = Month(window.SampleTime);
|
||||||
|
var partition = GetPartition(month);
|
||||||
|
if (partition.Limits.Contains(window)) continue;
|
||||||
|
var chronologicalPrevious = previous;
|
||||||
|
LimitWindow? chronologicalNext = null;
|
||||||
|
if (previous is not null && window.SampleTime < previous.SampleTime)
|
||||||
|
{
|
||||||
|
chronologicalPrevious = partition.PreviousLimit(window);
|
||||||
|
if (chronologicalPrevious is null)
|
||||||
|
foreach (var earlier in months.Where(m => string.CompareOrdinal(m, month) < 0).OrderDescending())
|
||||||
|
if (GetPartition(earlier).PreviousLimit(window) is { } found) { chronologicalPrevious = found; break; }
|
||||||
|
chronologicalNext = partition.NextLimit(window);
|
||||||
|
if (chronologicalNext is null)
|
||||||
|
foreach (var later in months.Where(m => string.CompareOrdinal(m, month) > 0).Order())
|
||||||
|
if (GetPartition(later).NextLimit(window) is { } found) { chronologicalNext = found; break; }
|
||||||
|
}
|
||||||
|
if (chronologicalPrevious is not null && window.UsedPercent == chronologicalPrevious.UsedPercent &&
|
||||||
|
window.ResetsAt == chronologicalPrevious.ResetsAt &&
|
||||||
|
window.SampleTime - chronologicalPrevious.SampleTime < TimeSpan.FromHours(1)) continue;
|
||||||
|
if (chronologicalNext is not null && window.UsedPercent == chronologicalNext.UsedPercent &&
|
||||||
|
window.ResetsAt == chronologicalNext.ResetsAt &&
|
||||||
|
chronologicalNext.SampleTime - window.SampleTime < TimeSpan.FromHours(1)) continue;
|
||||||
|
if (previous is null || window.SampleTime >= previous.SampleTime)
|
||||||
|
state.LastSamples[key] = pending.LastSamples[key] = window;
|
||||||
|
changedSets.Add(window.Provider);
|
||||||
|
if (partition.AddLimit(window)) PendingPartition(month).Limits.Add(window);
|
||||||
|
}
|
||||||
|
foreach (var provider in changedSets) pending.LatestWindows[provider] = state.LatestWindows[provider];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static (string, string, double, DateTimeOffset?, TimeSpan?, string) WindowValue(LimitWindow window) =>
|
||||||
|
(window.Id, window.Label, window.UsedPercent, window.ResetsAt, window.Length, window.Source);
|
||||||
|
public IReadOnlyList<LimitWindow> LatestLimits(Provider provider)
|
||||||
|
{
|
||||||
|
lock (gate) return state.LatestWindows.GetValueOrDefault(provider, []).OrderBy(w => w.Length).ToArray();
|
||||||
|
}
|
||||||
|
public IReadOnlyList<LimitWindow> LimitSamples(Provider provider, string windowId, DateTimeOffset from, DateTimeOffset to)
|
||||||
|
{
|
||||||
|
lock (gate) return SelectMonths(from, to).SelectMany(m => GetPartition(m).Limits)
|
||||||
|
.Where(w => w.Provider == provider && w.Id == windowId && w.SampleTime >= from && w.SampleTime < to)
|
||||||
|
.OrderBy(w => w.SampleTime).ToArray();
|
||||||
|
}
|
||||||
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval)
|
||||||
|
=> TokenSeries(provider, from, to, interval, TimeZoneInfo.Local);
|
||||||
|
public IReadOnlyList<TokenPoint> TokenSeries(Provider provider, DateTimeOffset from, DateTimeOffset to, SeriesInterval interval,
|
||||||
|
TimeZoneInfo? zone)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
Dictionary<DateTimeOffset, TokenCounts> points = [];
|
||||||
|
foreach (var bucket in Range(provider, from, to))
|
||||||
|
{
|
||||||
|
var key = interval == SeriesInterval.Hour ? bucket.Hour : CalendarDays.Start(bucket.Hour, zone);
|
||||||
|
points[key] = points.GetValueOrDefault(key) + bucket.Counts;
|
||||||
|
}
|
||||||
|
return points.OrderBy(p => p.Key).Select(p => new TokenPoint(p.Key, p.Value)).ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public IReadOnlyList<TokenBreakdown> ByModel(Provider provider, DateTimeOffset from, DateTimeOffset to) => Breakdown(provider, from, to, true);
|
||||||
|
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)
|
||||||
|
{
|
||||||
|
lock (gate) return Range(provider, from, to).GroupBy(b => model ? b.Model : b.Project)
|
||||||
|
.Select(g => new TokenBreakdown(g.Key, Sum(g.Select(b => b.Counts)))).OrderByDescending(b => b.Counts.Total).ToArray();
|
||||||
|
}
|
||||||
|
public TokenCounts Total(Provider provider, DateTimeOffset from, DateTimeOffset to)
|
||||||
|
{ lock (gate) return Sum(Range(provider, from, to).Select(b => b.Counts)); }
|
||||||
|
public (TokenCounts Today, TokenCounts? Session, TokenCounts Week) Totals(Provider provider, DateTimeOffset now,
|
||||||
|
LimitWindow? session, TimeZoneInfo? zone = null)
|
||||||
|
{
|
||||||
|
zone ??= TimeZoneInfo.Local;
|
||||||
|
var local = TimeZoneInfo.ConvertTime(now, zone);
|
||||||
|
var today = local.Date;
|
||||||
|
var week = today.AddDays(-(((int)today.DayOfWeek + 6) % 7));
|
||||||
|
var todayUtc = CalendarDays.Start(today, zone);
|
||||||
|
var weekUtc = CalendarDays.Start(week, zone);
|
||||||
|
return (Total(provider, todayUtc, now), session is { ResetsAt: { } reset, Length: { } length } && reset > now
|
||||||
|
? Total(provider, reset - length, now) : null, Total(provider, weekUtc, now));
|
||||||
|
}
|
||||||
|
private IEnumerable<TokenBucket> Range(Provider provider, DateTimeOffset from, DateTimeOffset to) =>
|
||||||
|
SelectMonths(from, to).SelectMany(m => GetPartition(m).Buckets.Values)
|
||||||
|
.Where(b => b.Provider == provider && b.Hour >= FloorHour(from) && b.Hour < to);
|
||||||
|
private string[] SelectMonths(DateTimeOffset from, DateTimeOffset to) => to <= from ? [] :
|
||||||
|
months.Where(m => string.CompareOrdinal(m, Month(from)) >= 0 && string.CompareOrdinal(m, Month(to)) <= 0).Order().ToArray();
|
||||||
|
private static string Month(DateTimeOffset time) => time.UtcDateTime.ToString("yyyy-MM", CultureInfo.InvariantCulture);
|
||||||
|
private static string WindowKey(LimitWindow window) => ((int)window.Provider).ToString(CultureInfo.InvariantCulture) + ":" + window.Id;
|
||||||
|
private static DateTimeOffset FloorHour(DateTimeOffset time) => new(time.UtcTicks - time.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
|
||||||
|
private static TokenCounts Sum(IEnumerable<TokenCounts> values) => values.Aggregate(new TokenCounts(), (a, b) => a + b);
|
||||||
|
|
||||||
|
private PartitionIndex PendingPartition(string month)
|
||||||
|
{
|
||||||
|
months.Add(month);
|
||||||
|
if (!pendingPartitions.TryGetValue(month, out var partition)) pendingPartitions[month] = partition = new();
|
||||||
|
return partition;
|
||||||
|
}
|
||||||
|
private PartitionIndex GetPartition(string month)
|
||||||
|
{
|
||||||
|
if (!cache.TryGetValue(month, out var partition))
|
||||||
|
{
|
||||||
|
partition = new();
|
||||||
|
var path = PartitionPath(month);
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
var data = JsonSerializer.Deserialize(SharedFile.ReadAllText(path), CoreJsonContext.Default.HistoryPartition) ?? throw new JsonException();
|
||||||
|
if (data.V != 1 || data.Buckets is null || data.Limits is null) throw new JsonException();
|
||||||
|
partition.Apply(data);
|
||||||
|
}
|
||||||
|
if (overlays.TryGetValue(month, out var overlay)) partition.Apply(overlay);
|
||||||
|
if (pendingPartitions.TryGetValue(month, out var changes)) partition.Apply(changes);
|
||||||
|
cache[month] = partition;
|
||||||
|
while (cache.Count > 3)
|
||||||
|
{
|
||||||
|
var first = cacheOrder.First!.Value;
|
||||||
|
cacheOrder.RemoveFirst();
|
||||||
|
cache.Remove(first);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cacheOrder.Remove(month);
|
||||||
|
cacheOrder.AddLast(month);
|
||||||
|
return partition;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Task SaveAsync(CancellationToken cancellationToken = default) =>
|
||||||
|
Task.Run(() => Save(false, cancellationToken), cancellationToken);
|
||||||
|
/// <summary>Explicit bounded-journal maintenance; ordinary idle SaveAsync does no I/O.</summary>
|
||||||
|
public Task CompactAsync(CancellationToken cancellationToken = default) =>
|
||||||
|
Task.Run(() => Save(true, cancellationToken), cancellationToken);
|
||||||
|
private void Save(bool compact, CancellationToken token)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
PruneKeys();
|
||||||
|
pending.Buckets = pendingPartitions.Values.SelectMany(p => p.Buckets.Values).ToList();
|
||||||
|
pending.Limits = pendingPartitions.Values.SelectMany(p => p.Limits).ToList();
|
||||||
|
var changed = pending.Buckets.Count + pending.Limits.Count + pending.ClaudeKeys.Count +
|
||||||
|
pending.ExpiredClaudeKeys.Count + pending.CodexTotals.Count + pending.Cursors.Count +
|
||||||
|
pending.LatestWindows.Count + pending.LastSamples.Count > 0;
|
||||||
|
if (changed)
|
||||||
|
{
|
||||||
|
pending.Sequence = state.Sequence + 1;
|
||||||
|
journalBytes = HistoryJournal.Append(JournalPath, journalBytes, pending, token);
|
||||||
|
foreach (var (month, changes) in pendingPartitions)
|
||||||
|
{
|
||||||
|
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
|
||||||
|
overlay.Apply(changes);
|
||||||
|
}
|
||||||
|
state.Sequence = pending.Sequence;
|
||||||
|
pending = new();
|
||||||
|
pendingPartitions.Clear();
|
||||||
|
}
|
||||||
|
if ((changed && journalBytes >= CompactBytes || compact) && journalBytes > 0)
|
||||||
|
{
|
||||||
|
foreach (var month in overlays.Keys.ToArray())
|
||||||
|
{
|
||||||
|
token.ThrowIfCancellationRequested();
|
||||||
|
AtomicFile.WriteAsync(PartitionPath(month), JsonSerializer.Serialize(GetPartition(month).Export(),
|
||||||
|
CoreJsonContext.Default.HistoryPartition), token).GetAwaiter().GetResult();
|
||||||
|
}
|
||||||
|
// Checkpoint last. If interrupted, absolute bucket upserts and exact sample sets replay idempotently.
|
||||||
|
AtomicFile.WriteAsync(StatePath, JsonSerializer.Serialize(state, CoreJsonContext.Default.HistoryState), token).GetAwaiter().GetResult();
|
||||||
|
AtomicFile.WriteAsync(JournalPath, "", token).GetAwaiter().GetResult();
|
||||||
|
journalBytes = 0;
|
||||||
|
overlays.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void ApplyTransaction(HistoryTransaction transaction)
|
||||||
|
{
|
||||||
|
if (transaction.Sequence <= state.Sequence) return;
|
||||||
|
if (transaction.Sequence != state.Sequence + 1 || transaction.Buckets is null || transaction.Limits is null ||
|
||||||
|
transaction.ClaudeKeys is null || transaction.ExpiredClaudeKeys is null || transaction.CodexTotals is null ||
|
||||||
|
transaction.CodexTimes is null || transaction.Cursors is null || transaction.LatestWindows is null || transaction.LastSamples is null)
|
||||||
|
throw new JsonException();
|
||||||
|
foreach (var key in transaction.ExpiredClaudeKeys) state.ClaudeKeys.Remove(key);
|
||||||
|
foreach (var (key, value) in transaction.ClaudeKeys) state.ClaudeKeys[key] = value;
|
||||||
|
foreach (var (key, value) in transaction.CodexTotals) state.CodexTotals[key] = value;
|
||||||
|
foreach (var (key, value) in transaction.CodexTimes) state.CodexTimes[key] = value;
|
||||||
|
foreach (var (key, value) in transaction.Cursors) state.Cursors[key] = value;
|
||||||
|
foreach (var (key, value) in transaction.LatestWindows) state.LatestWindows[key] = value;
|
||||||
|
foreach (var (key, value) in transaction.LastSamples) state.LastSamples[key] = value;
|
||||||
|
foreach (var bucket in transaction.Buckets)
|
||||||
|
{
|
||||||
|
var month = Month(bucket.Hour);
|
||||||
|
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
|
||||||
|
overlay.Buckets[BucketKey.For(bucket)] = bucket;
|
||||||
|
months.Add(month);
|
||||||
|
}
|
||||||
|
foreach (var sample in transaction.Limits)
|
||||||
|
{
|
||||||
|
var month = Month(sample.SampleTime);
|
||||||
|
if (!overlays.TryGetValue(month, out var overlay)) overlays[month] = overlay = new();
|
||||||
|
overlay.Limits.Add(sample);
|
||||||
|
months.Add(month);
|
||||||
|
}
|
||||||
|
state.Sequence = transaction.Sequence;
|
||||||
|
}
|
||||||
|
private static void ValidateState(HistoryState value)
|
||||||
|
{
|
||||||
|
if (value.V != 1 || value.Sequence < 0 || value.ClaudeKeys is null || value.CodexTotals is null || value.CodexTimes is null ||
|
||||||
|
value.Cursors is null || value.LatestWindows is null || value.LastSamples is null) throw new JsonException();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
[JsonConverter(typeof(JsonStringEnumConverter<Provider>))]
|
||||||
|
public enum Provider { Claude, Codex }
|
||||||
|
[JsonConverter(typeof(JsonStringEnumConverter<ProviderStatus>))]
|
||||||
|
public enum ProviderStatus { Available, Unavailable, Disabled }
|
||||||
|
[JsonConverter(typeof(JsonStringEnumConverter<PaceState>))]
|
||||||
|
public enum PaceState { Unknown, OnTrack, Ahead, Behind }
|
||||||
|
[JsonConverter(typeof(JsonStringEnumConverter<InstallMode>))]
|
||||||
|
public enum InstallMode { Off, Ask, Automatic }
|
||||||
|
|
||||||
|
/// <summary>Cache read is a subset of input for Codex, but separate for Claude.
|
||||||
|
/// Reasoning is a subset of output. Total is provider-reported or computed by its parser.</summary>
|
||||||
|
public readonly record struct TokenCounts(long Input = 0, long CacheRead = 0, long CacheWrite = 0,
|
||||||
|
long Output = 0, long ReasoningOutput = 0, long Total = 0)
|
||||||
|
{
|
||||||
|
public static TokenCounts operator +(TokenCounts a, TokenCounts b) => new(
|
||||||
|
checked(a.Input + b.Input), checked(a.CacheRead + b.CacheRead), checked(a.CacheWrite + b.CacheWrite),
|
||||||
|
checked(a.Output + b.Output), checked(a.ReasoningOutput + b.ReasoningOutput), checked(a.Total + b.Total));
|
||||||
|
public TokenCounts IncreaseFrom(TokenCounts previous) => new(
|
||||||
|
Math.Max(0, Input - previous.Input), Math.Max(0, CacheRead - previous.CacheRead),
|
||||||
|
Math.Max(0, CacheWrite - previous.CacheWrite), Math.Max(0, Output - previous.Output),
|
||||||
|
Math.Max(0, ReasoningOutput - previous.ReasoningOutput), Math.Max(0, Total - previous.Total));
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record UsageEvent(Provider Provider, DateTimeOffset Time, string? Model, string? Project,
|
||||||
|
TokenCounts Counts, string DedupeKey);
|
||||||
|
public sealed record LimitWindow(Provider Provider, string Id, string Label, double UsedPercent,
|
||||||
|
DateTimeOffset? ResetsAt, TimeSpan? Length, DateTimeOffset SampleTime, string Source);
|
||||||
|
public sealed record PaceResult(PaceState State, double? ElapsedFraction = null, double? Delta = null,
|
||||||
|
DateTimeOffset? Projection = null);
|
||||||
|
public sealed record PopupEvent(Provider Provider, string WindowId, string Label, PaceState State,
|
||||||
|
double Delta, DateTimeOffset? Projection);
|
||||||
|
public sealed record Diagnostic(DateTimeOffset Time, Provider? Provider, string Code, string Summary)
|
||||||
|
{
|
||||||
|
public long Count { get; init; } = 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Bounded metadata-only diagnostics. Never pass parser input or process output here (D2).</summary>
|
||||||
|
public sealed class DiagnosticLog(TimeProvider? timeProvider = null, int capacity = 100)
|
||||||
|
{
|
||||||
|
private readonly Lock gate = new();
|
||||||
|
private readonly List<Diagnostic> entries = [];
|
||||||
|
public void Add(Provider? provider, string code, string summary)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
var time = (timeProvider ?? TimeProvider.System).GetUtcNow();
|
||||||
|
var index = entries.FindIndex(d => d.Provider == provider && d.Code == code);
|
||||||
|
if (index >= 0) entries[index] = entries[index] with { Time = time, Count = entries[index].Count + 1 };
|
||||||
|
else
|
||||||
|
{
|
||||||
|
entries.Add(new(time, provider, code, summary));
|
||||||
|
if (entries.Count > Math.Max(1, capacity)) entries.RemoveAt(0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public IReadOnlyList<Diagnostic> Recent { get { lock (gate) return entries.ToArray(); } }
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public static class Pace
|
||||||
|
{
|
||||||
|
// 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)
|
||||||
|
{
|
||||||
|
if (window.Length is not { Ticks: > 0 } length || window.ResetsAt is not { } reset ||
|
||||||
|
!double.IsFinite(window.UsedPercent) || window.UsedPercent is < 0 or > 100 ||
|
||||||
|
!double.IsFinite(threshold) || threshold <= 0)
|
||||||
|
return new(PaceState.Unknown);
|
||||||
|
var elapsed = Math.Clamp(1 - (reset - now).TotalSeconds / length.TotalSeconds, 0, 1);
|
||||||
|
var delta = window.UsedPercent - 100 * elapsed;
|
||||||
|
var state = delta >= threshold ? PaceState.Ahead :
|
||||||
|
delta <= -threshold && elapsed >= 0.5 ? PaceState.Behind : PaceState.OnTrack;
|
||||||
|
DateTimeOffset? projection = null;
|
||||||
|
if (state == PaceState.Ahead && window.UsedPercent > 0 && elapsed > 0)
|
||||||
|
{
|
||||||
|
var seconds = (100 - window.UsedPercent) * elapsed * length.TotalSeconds / window.UsedPercent;
|
||||||
|
if (seconds >= 0 && seconds < (reset - now).TotalSeconds) projection = now.AddSeconds(seconds);
|
||||||
|
}
|
||||||
|
return new(state, elapsed, delta, projection);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>D8: retains an alert until it clears its threshold by two points.
|
||||||
|
/// Observe is deterministic and has no side effects beyond its own state.</summary>
|
||||||
|
public sealed class PopupDecider
|
||||||
|
{
|
||||||
|
private readonly Dictionary<(Provider, string), PaceState> states = [];
|
||||||
|
public PopupEvent? Observe(LimitWindow window, PaceResult pace, Settings settings)
|
||||||
|
{
|
||||||
|
var key = (window.Provider, window.Id);
|
||||||
|
var previous = states.GetValueOrDefault(key, PaceState.Unknown);
|
||||||
|
var next = pace.State;
|
||||||
|
if (pace.Delta is { } delta && pace.State != PaceState.Unknown)
|
||||||
|
{
|
||||||
|
if (previous == PaceState.Ahead && delta > settings.PaceThreshold - 2) next = PaceState.Ahead;
|
||||||
|
if (previous == PaceState.Behind && delta < -settings.PaceThreshold + 2 && pace.ElapsedFraction >= 0.5)
|
||||||
|
next = PaceState.Behind;
|
||||||
|
}
|
||||||
|
states[key] = next;
|
||||||
|
if (previous == next || next is not (PaceState.Ahead or PaceState.Behind) ||
|
||||||
|
!settings.For(window.Provider).Enabled || !settings.For(window.Provider).PopupsEnabled ||
|
||||||
|
(next == PaceState.Ahead ? !settings.PopupAhead || !settings.For(window.Provider).PopupAhead :
|
||||||
|
!settings.PopupBehind || !settings.For(window.Provider).PopupBehind)) return null;
|
||||||
|
return new(window.Provider, window.Id, window.Label, next, pace.Delta!.Value, pace.Projection);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
namespace FinalToken.Core.Processes;
|
||||||
|
|
||||||
|
public sealed record CliCommand(string FileName, IReadOnlyList<string> PrefixArguments);
|
||||||
|
public sealed record CliDiscoveryResult(CliCommand? Command, string? Reason);
|
||||||
|
|
||||||
|
public static class CliDiscovery
|
||||||
|
{
|
||||||
|
public static CliDiscoveryResult Find(Provider provider, string? overridePath = null,
|
||||||
|
string? searchPath = null, bool? windows = null)
|
||||||
|
{
|
||||||
|
try { return FindCore(provider, overridePath, searchPath, windows); }
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
|
||||||
|
{ return new(null, "CLI path is invalid or cannot be inspected."); }
|
||||||
|
}
|
||||||
|
private static CliDiscoveryResult FindCore(Provider provider, string? overridePath,
|
||||||
|
string? searchPath, bool? windows)
|
||||||
|
{
|
||||||
|
var isWindows = windows ?? OperatingSystem.IsWindows();
|
||||||
|
var name = provider == Provider.Claude ? "claude" : "codex";
|
||||||
|
if (!string.IsNullOrWhiteSpace(overridePath)) return Resolve(Path.GetFullPath(overridePath), provider, isWindows, searchPath);
|
||||||
|
foreach (var directory in (searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
|
||||||
|
.Split(isWindows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries))
|
||||||
|
{
|
||||||
|
foreach (var suffix in isWindows ? new[] { ".exe", ".cmd", ".ps1", "" } : new[] { "" })
|
||||||
|
{
|
||||||
|
var candidate = Path.Combine(directory.Trim('"'), name + suffix);
|
||||||
|
if (File.Exists(candidate))
|
||||||
|
{
|
||||||
|
var resolved = Resolve(candidate, provider, isWindows, searchPath);
|
||||||
|
if (resolved.Command is not null) return resolved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new(null, $"{name} CLI was not found.");
|
||||||
|
}
|
||||||
|
private static CliDiscoveryResult Resolve(string path, Provider provider, bool windows, string? searchPath)
|
||||||
|
{
|
||||||
|
if (!File.Exists(path)) return new(null, "Configured CLI does not exist.");
|
||||||
|
var directory = Path.GetDirectoryName(path)!;
|
||||||
|
if (windows && Path.GetExtension(path).Equals(".exe", StringComparison.OrdinalIgnoreCase)) return new(new(path, []), null);
|
||||||
|
if (provider == Provider.Claude && windows)
|
||||||
|
{
|
||||||
|
var package = Path.Combine(directory, "node_modules", "@anthropic-ai", "claude-code");
|
||||||
|
// Current npm installs copy the platform binary here; older releases use cli.js.
|
||||||
|
var binary = Path.Combine(package, "bin", "claude.exe");
|
||||||
|
if (File.Exists(binary)) return new(new(binary, []), null);
|
||||||
|
var script = Path.Combine(package, "cli.js");
|
||||||
|
if (File.Exists(script) && FindNode(directory, searchPath, true) is { } node) return new(new(node, [script]), null);
|
||||||
|
}
|
||||||
|
if (provider == Provider.Codex)
|
||||||
|
{
|
||||||
|
var package = Path.Combine(directory, "node_modules", "@openai", "codex");
|
||||||
|
// Unix npm bin symlinks point into the package; resolve before looking for vendor/node.
|
||||||
|
var target = File.ResolveLinkTarget(path, true)?.FullName;
|
||||||
|
if (target is not null && Path.GetFileName(target) == "codex.js") package = Path.GetDirectoryName(Path.GetDirectoryName(target))!;
|
||||||
|
foreach (var vendorRoot in new[] { Path.Combine(package, "node_modules", "@openai", "codex-win32-x64", "vendor"), Path.Combine(package, "vendor") })
|
||||||
|
{
|
||||||
|
var binary = Path.Combine(vendorRoot, windows ? "x86_64-pc-windows-msvc" : "x86_64-unknown-linux-musl", "bin", windows ? "codex.exe" : "codex");
|
||||||
|
if (File.Exists(binary)) return new(new(binary, []), null);
|
||||||
|
}
|
||||||
|
var script = Path.Combine(package, "bin", "codex.js");
|
||||||
|
if (File.Exists(script) && FindNode(directory, searchPath, windows) is { } node) return new(new(node, [script]), null);
|
||||||
|
}
|
||||||
|
if (!windows)
|
||||||
|
{
|
||||||
|
using var file = File.OpenRead(path);
|
||||||
|
var bytes = new byte[128];
|
||||||
|
var count = file.Read(bytes);
|
||||||
|
var first = System.Text.Encoding.UTF8.GetString(bytes, 0, count).Split('\n')[0];
|
||||||
|
if (!first.StartsWith("#!", StringComparison.Ordinal)) return new(new(path, []), null);
|
||||||
|
if ((first == "#!/usr/bin/env node" || first == "#!/usr/bin/node") && FindNode(directory, searchPath, false) is { } node)
|
||||||
|
return new(new(node, [path]), null);
|
||||||
|
}
|
||||||
|
return new(null, "CLI wrapper has no supported native binary or Node runtime.");
|
||||||
|
}
|
||||||
|
private static string? FindNode(string directory, string? searchPath, bool windows)
|
||||||
|
{
|
||||||
|
foreach (var candidateDirectory in new[] { directory }.Concat((searchPath ?? Environment.GetEnvironmentVariable("PATH") ?? "")
|
||||||
|
.Split(windows ? ';' : ':', StringSplitOptions.RemoveEmptyEntries)))
|
||||||
|
{
|
||||||
|
var path = Path.Combine(candidateDirectory.Trim('"'), windows ? "node.exe" : "node");
|
||||||
|
if (File.Exists(path)) return path;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Processes;
|
||||||
|
|
||||||
|
public sealed record ProcessRequest(CliCommand Command, IReadOnlyList<string> Arguments, string WorkingDirectory,
|
||||||
|
TimeSpan Timeout, bool CodexRpc = false, int OutputLimit = 1024 * 1024);
|
||||||
|
public sealed record ProcessResult(int ExitCode, string Output, bool TimedOut = false, bool OutputTruncated = false);
|
||||||
|
public interface IProcessRunner
|
||||||
|
{
|
||||||
|
Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>No shell; bounded capture; cancellation/timeout kills and waits for the whole child tree (D6).</summary>
|
||||||
|
public sealed class ProcessRunner(TimeProvider? timeProvider = null) : IProcessRunner
|
||||||
|
{
|
||||||
|
public async Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
using var timeout = new CancellationTokenSource(request.Timeout, timeProvider ?? TimeProvider.System);
|
||||||
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeout.Token);
|
||||||
|
var token = linked.Token;
|
||||||
|
using var process = new Process { StartInfo = new()
|
||||||
|
{
|
||||||
|
FileName = request.Command.FileName, WorkingDirectory = request.WorkingDirectory,
|
||||||
|
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true, RedirectStandardInput = true,
|
||||||
|
// CLI JSON is UTF-8. A GUI host has no console code page; using its default
|
||||||
|
// encoding corrupts Unicode delimiters in Claude's local /usage result (D3).
|
||||||
|
StandardOutputEncoding = new UTF8Encoding(false), StandardErrorEncoding = new UTF8Encoding(false),
|
||||||
|
StandardInputEncoding = new UTF8Encoding(false)
|
||||||
|
} };
|
||||||
|
foreach (var argument in request.Command.PrefixArguments.Concat(request.Arguments)) process.StartInfo.ArgumentList.Add(argument);
|
||||||
|
process.Start();
|
||||||
|
// 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.
|
||||||
|
if (!request.CodexRpc) process.StandardInput.Close();
|
||||||
|
var stderr = CaptureAsync(process.StandardError, request.OutputLimit, token);
|
||||||
|
Task<(string Output, bool Truncated)>? stdout = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (request.CodexRpc)
|
||||||
|
{
|
||||||
|
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 process.StandardInput.WriteLineAsync("{\"method\":\"initialized\"}".AsMemory(), token);
|
||||||
|
await process.StandardInput.WriteLineAsync("{\"id\":2,\"method\":\"account/rateLimits/read\",\"params\":null}".AsMemory(), token);
|
||||||
|
var output = await ReadResponseAsync(process.StandardOutput, 2, request.OutputLimit, token);
|
||||||
|
Kill(process);
|
||||||
|
await process.WaitForExitAsync(CancellationToken.None);
|
||||||
|
await stderr;
|
||||||
|
return new(0, output);
|
||||||
|
}
|
||||||
|
stdout = CaptureAsync(process.StandardOutput, request.OutputLimit, token);
|
||||||
|
await process.WaitForExitAsync(token);
|
||||||
|
var captured = await stdout;
|
||||||
|
await stderr;
|
||||||
|
return new(process.ExitCode, captured.Output, false, captured.Truncated);
|
||||||
|
}
|
||||||
|
catch (OperationCanceledException) when (timeout.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
|
||||||
|
{ return new(-1, "", true); }
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Kill(process);
|
||||||
|
await process.WaitForExitAsync(CancellationToken.None);
|
||||||
|
// Observe capture cancellation/failure; process output is never logged.
|
||||||
|
try { await stderr; } catch (OperationCanceledException) { }
|
||||||
|
if (stdout is not null)
|
||||||
|
try { await stdout; } catch (OperationCanceledException) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private static void Kill(Process process)
|
||||||
|
{
|
||||||
|
try { if (!process.HasExited) process.Kill(true); }
|
||||||
|
catch (InvalidOperationException) { }
|
||||||
|
}
|
||||||
|
private static async Task<(string Output, bool Truncated)> CaptureAsync(StreamReader reader, int limit, CancellationToken token)
|
||||||
|
{
|
||||||
|
var output = new StringBuilder();
|
||||||
|
var buffer = new char[4096];
|
||||||
|
var truncated = false;
|
||||||
|
int read;
|
||||||
|
while ((read = await reader.ReadAsync(buffer, token)) > 0)
|
||||||
|
{
|
||||||
|
var keep = Math.Min(read, Math.Max(0, limit - output.Length));
|
||||||
|
output.Append(buffer, 0, keep);
|
||||||
|
truncated |= keep < read;
|
||||||
|
}
|
||||||
|
return (output.ToString(), truncated);
|
||||||
|
}
|
||||||
|
private static async Task<string> ReadResponseAsync(StreamReader reader, int id, int limit, CancellationToken token)
|
||||||
|
{
|
||||||
|
// Bound each line and total traffic, including unrelated notifications.
|
||||||
|
var line = new StringBuilder();
|
||||||
|
var one = new char[1];
|
||||||
|
var total = 0;
|
||||||
|
while (await reader.ReadAsync(one, token) > 0)
|
||||||
|
{
|
||||||
|
if (++total > limit) throw new InvalidDataException("RPC output exceeded its bound.");
|
||||||
|
if (one[0] != '\n') { line.Append(one[0]); continue; }
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var document = JsonDocument.Parse(line.ToString());
|
||||||
|
if (document.RootElement.TryGetProperty("id", out var value) && value.TryGetInt32(out var responseId) && responseId == id)
|
||||||
|
{
|
||||||
|
if (document.RootElement.TryGetProperty("error", out _)) throw new InvalidDataException("RPC request failed.");
|
||||||
|
return line.ToString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (JsonException) { }
|
||||||
|
line.Clear();
|
||||||
|
}
|
||||||
|
throw new InvalidDataException("RPC response was not returned.");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using FinalToken.Core.Processes;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
/// <summary>Shared app/CLI host (D6). Caller holds StoreLock. SnapshotChanged, PopupRequested,
|
||||||
|
/// ActivationRequested run on worker threads, never the caller's UI synchronization context.
|
||||||
|
/// UI hosts must marshal events. History query results are safe copies.</summary>
|
||||||
|
public sealed class RefreshEngine : IAsyncDisposable
|
||||||
|
{
|
||||||
|
private readonly SemaphoreSlim refreshGate = new(1, 1);
|
||||||
|
private readonly SemaphoreSlim lifecycleGate = new(1, 1);
|
||||||
|
private readonly string directory;
|
||||||
|
private readonly TimeProvider clock;
|
||||||
|
private readonly string? appPath;
|
||||||
|
private readonly IncrementalScanner scanner;
|
||||||
|
private readonly LimitProbe probe;
|
||||||
|
private readonly Func<Provider, string?, CliDiscoveryResult> discover;
|
||||||
|
private readonly PopupDecider popups = new();
|
||||||
|
private readonly Dictionary<Provider, DateTimeOffset> lastProbe = [];
|
||||||
|
private readonly Dictionary<Provider, (ProviderStatus Status, string? Reason)> statuses = [];
|
||||||
|
private readonly HashSet<Provider> pendingProbe = [];
|
||||||
|
private readonly List<FileSystemWatcher> watchers = [];
|
||||||
|
private CancellationTokenSource? lifetime = new();
|
||||||
|
private Task? loop;
|
||||||
|
private Snapshot? current;
|
||||||
|
private Settings settings;
|
||||||
|
private long changedTicks;
|
||||||
|
private DateTimeOffset lastRefresh = DateTimeOffset.MinValue;
|
||||||
|
private string? activation;
|
||||||
|
|
||||||
|
public RefreshEngine(string? dataDirectory = null, TimeProvider? timeProvider = null, IProcessRunner? processRunner = null,
|
||||||
|
string? claudeDirectory = null, string? codexDirectory = null,
|
||||||
|
Func<Provider, string?, CliDiscoveryResult>? cliDiscovery = null, string? appPath = null)
|
||||||
|
{
|
||||||
|
directory = dataDirectory ?? DataPaths.DataDirectory;
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
clock = timeProvider ?? TimeProvider.System;
|
||||||
|
Diagnostics = new(clock);
|
||||||
|
settings = SettingsFile.Load(directory, Diagnostics);
|
||||||
|
History = new(directory, Diagnostics, clock);
|
||||||
|
ClaudeDirectory = claudeDirectory ?? DataPaths.ClaudeDirectory;
|
||||||
|
CodexDirectory = codexDirectory ?? DataPaths.CodexDirectory;
|
||||||
|
scanner = new(History, Diagnostics, ClaudeDirectory, CodexDirectory);
|
||||||
|
probe = new(processRunner ?? new ProcessRunner(clock), Diagnostics, directory);
|
||||||
|
discover = cliDiscovery ?? ((provider, path) => CliDiscovery.Find(provider, path));
|
||||||
|
current = SnapshotFile.Read(directory, clock.GetUtcNow()).Snapshot;
|
||||||
|
this.appPath = appPath ?? current?.AppPath;
|
||||||
|
activation = ActivationFile.ReadRequest(directory);
|
||||||
|
}
|
||||||
|
public string DataDirectory => directory;
|
||||||
|
public string ClaudeDirectory { get; }
|
||||||
|
public string CodexDirectory { get; }
|
||||||
|
public Snapshot? CurrentSnapshot => Volatile.Read(ref current);
|
||||||
|
public Settings Settings => Volatile.Read(ref settings);
|
||||||
|
public HistoryStore History { get; }
|
||||||
|
public DiagnosticLog Diagnostics { get; }
|
||||||
|
public IReadOnlyList<Diagnostic> RecentDiagnostics => Diagnostics.Recent;
|
||||||
|
public event Action<Snapshot>? SnapshotChanged;
|
||||||
|
public event Action<PopupEvent>? PopupRequested;
|
||||||
|
public event Action? ActivationRequested;
|
||||||
|
|
||||||
|
public Task UpdateSettingsAsync(Settings value, CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||||
|
{
|
||||||
|
await refreshGate.WaitAsync(cancellationToken);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await SettingsFile.SaveAsync(directory, value, cancellationToken);
|
||||||
|
Volatile.Write(ref settings, value);
|
||||||
|
}
|
||||||
|
finally { refreshGate.Release(); }
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
public async Task StartAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await lifecycleGate.WaitAsync(cancellationToken);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (loop is not null) return;
|
||||||
|
lifetime ??= new();
|
||||||
|
foreach (var path in new[] { Path.Combine(ClaudeDirectory, "projects"), Path.Combine(CodexDirectory, "sessions"), Path.Combine(CodexDirectory, "archived_sessions") })
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(path)) continue;
|
||||||
|
var watcher = new FileSystemWatcher(path, "*.jsonl") { IncludeSubdirectories = true };
|
||||||
|
watcher.Changed += (_, _) => NotifySourceChanged();
|
||||||
|
watcher.Created += (_, _) => NotifySourceChanged();
|
||||||
|
watcher.Deleted += (_, _) => NotifySourceChanged();
|
||||||
|
watcher.Renamed += (_, _) => NotifySourceChanged();
|
||||||
|
watcher.Error += (_, _) => { Diagnostics.Add(null, "watcher", "File watcher failed; periodic scans continue."); NotifySourceChanged(); };
|
||||||
|
watcher.EnableRaisingEvents = true;
|
||||||
|
watchers.Add(watcher);
|
||||||
|
}
|
||||||
|
loop = Task.Run(() => RunLoopAsync(lifetime.Token), CancellationToken.None);
|
||||||
|
}
|
||||||
|
finally { lifecycleGate.Release(); }
|
||||||
|
}
|
||||||
|
public async Task StopAsync()
|
||||||
|
{
|
||||||
|
await lifecycleGate.WaitAsync();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var watcher in watchers) watcher.Dispose();
|
||||||
|
watchers.Clear();
|
||||||
|
if (lifetime is not null) await lifetime.CancelAsync();
|
||||||
|
if (loop is not null)
|
||||||
|
try { await loop; } catch (OperationCanceledException) { }
|
||||||
|
// Also wait for any manually requested refresh, which shares the lifetime token.
|
||||||
|
await refreshGate.WaitAsync();
|
||||||
|
refreshGate.Release();
|
||||||
|
lifetime?.Dispose();
|
||||||
|
lifetime = null;
|
||||||
|
loop = null;
|
||||||
|
}
|
||||||
|
finally { lifecycleGate.Release(); }
|
||||||
|
}
|
||||||
|
public void NotifySourceChanged() => Interlocked.Exchange(ref changedTicks, clock.GetUtcNow().UtcTicks);
|
||||||
|
|
||||||
|
public Task<Snapshot> RefreshNowAsync(bool noProbe = false, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
var shutdown = lifetime?.Token ?? CancellationToken.None;
|
||||||
|
return Task.Run(async () =>
|
||||||
|
{
|
||||||
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, shutdown);
|
||||||
|
return await RefreshAsync(noProbe, linked.Token);
|
||||||
|
}, cancellationToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One scheduler tick, also usable with a fake TimeProvider. Changes debounce for two seconds.</summary>
|
||||||
|
public Task TickAsync(CancellationToken cancellationToken = default) => Task.Run(async () =>
|
||||||
|
{
|
||||||
|
var request = ActivationFile.ReadRequest(directory);
|
||||||
|
if (request is not null && request != activation) { activation = request; Dispatch(ActivationRequested); }
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
var changes = Interlocked.Read(ref changedTicks);
|
||||||
|
if (now - lastRefresh >= Settings.RefreshInterval || changes > 0 && now.UtcTicks - changes >= TimeSpan.FromSeconds(2).Ticks)
|
||||||
|
{
|
||||||
|
Interlocked.CompareExchange(ref changedTicks, 0, changes);
|
||||||
|
await RefreshAsync(false, cancellationToken);
|
||||||
|
}
|
||||||
|
}, cancellationToken);
|
||||||
|
|
||||||
|
private async Task RunLoopAsync(CancellationToken token)
|
||||||
|
{
|
||||||
|
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1), clock);
|
||||||
|
do
|
||||||
|
{
|
||||||
|
try { await TickAsync(token); }
|
||||||
|
catch (OperationCanceledException) when (token.IsCancellationRequested) { throw; }
|
||||||
|
// D6: isolate a failed tick, including a malformed stored partition, and retry.
|
||||||
|
catch (Exception)
|
||||||
|
{ Diagnostics.Add(null, "refresh-failed", "Refresh failed; the scheduler will retry."); }
|
||||||
|
} while (await timer.WaitForNextTickAsync(token));
|
||||||
|
}
|
||||||
|
private async Task<Snapshot> RefreshAsync(bool noProbe, CancellationToken token)
|
||||||
|
{
|
||||||
|
await refreshGate.WaitAsync(token);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var config = Settings;
|
||||||
|
var scan = await scanner.ScanAsync(token, config.Claude.Enabled, config.Codex.Enabled);
|
||||||
|
if (scan.ClaudeAdded > 0) pendingProbe.Add(Provider.Claude);
|
||||||
|
if (scan.CodexAdded > 0) pendingProbe.Add(Provider.Codex);
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
List<ProviderSnapshot> providers = [];
|
||||||
|
List<PopupEvent> alerts = [];
|
||||||
|
foreach (var provider in new[] { Provider.Claude, Provider.Codex })
|
||||||
|
{
|
||||||
|
var providerSettings = config.For(provider);
|
||||||
|
if (!providerSettings.Enabled) statuses[provider] = (ProviderStatus.Disabled, "Disabled in settings.");
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var cli = discover(provider, providerSettings.CliPath);
|
||||||
|
if (cli.Command is null) statuses[provider] = (ProviderStatus.Unavailable, cli.Reason);
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (!statuses.ContainsKey(provider) || statuses[provider].Status == ProviderStatus.Disabled)
|
||||||
|
statuses[provider] = (ProviderStatus.Available, null);
|
||||||
|
var previousProbe = lastProbe.GetValueOrDefault(provider, DateTimeOffset.MinValue);
|
||||||
|
var since = now - previousProbe;
|
||||||
|
if (!noProbe && since >= TimeSpan.FromMinutes(1) && (since >= config.ProbeInterval || pendingProbe.Contains(provider)))
|
||||||
|
{
|
||||||
|
lastProbe[provider] = now;
|
||||||
|
pendingProbe.Remove(provider);
|
||||||
|
var result = await probe.RunAsync(provider, cli.Command, now, token);
|
||||||
|
if (result.Success)
|
||||||
|
{
|
||||||
|
History.AddLimits(result.Windows);
|
||||||
|
statuses[provider] = (ProviderStatus.Available, null);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
if (provider == Provider.Codex && scan.CodexFallback.Count > 0)
|
||||||
|
statuses[provider] = (ProviderStatus.Available, "Probe failed; using rollout limits.");
|
||||||
|
else statuses[provider] = (ProviderStatus.Unavailable, result.Reason);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var windows = History.LatestLimits(provider);
|
||||||
|
// 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 totals = History.Totals(provider, now, session);
|
||||||
|
var state = statuses[provider];
|
||||||
|
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));
|
||||||
|
foreach (var window in snapshots)
|
||||||
|
if (state.Status == ProviderStatus.Available && popups.Observe(window.Window, window.Pace, config) is { } alert)
|
||||||
|
alerts.Add(alert);
|
||||||
|
}
|
||||||
|
var snapshot = new Snapshot { MadeAt = clock.GetUtcNow(), RefreshInterval = config.RefreshInterval,
|
||||||
|
Providers = providers, AppPath = appPath };
|
||||||
|
await History.SaveAsync(token);
|
||||||
|
await SnapshotFile.WriteAsync(directory, snapshot, token);
|
||||||
|
Volatile.Write(ref current, snapshot);
|
||||||
|
lastRefresh = clock.GetUtcNow();
|
||||||
|
Dispatch(SnapshotChanged, snapshot);
|
||||||
|
foreach (var alert in alerts) Dispatch(PopupRequested, alert);
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
finally { refreshGate.Release(); }
|
||||||
|
}
|
||||||
|
private void Dispatch<T>(Action<T>? handlers, T value)
|
||||||
|
{
|
||||||
|
if (handlers is null) return;
|
||||||
|
foreach (var handler in handlers.GetInvocationList().Cast<Action<T>>())
|
||||||
|
try { handler(value); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
|
||||||
|
}
|
||||||
|
private void Dispatch(Action? handlers)
|
||||||
|
{
|
||||||
|
if (handlers is null) return;
|
||||||
|
foreach (var handler in handlers.GetInvocationList().Cast<Action>())
|
||||||
|
try { handler(); } catch (Exception) { Diagnostics.Add(null, "event-handler", "A host event handler failed."); }
|
||||||
|
}
|
||||||
|
public async ValueTask DisposeAsync() => await StopAsync();
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public sealed record ProviderSettings
|
||||||
|
{
|
||||||
|
// Setters let source-generated JSON construct defaults before assigning present properties.
|
||||||
|
public bool Enabled { get; set; } = true;
|
||||||
|
public bool PopupsEnabled { get; set; } = true;
|
||||||
|
public bool PopupAhead { get; set; } = true;
|
||||||
|
public bool PopupBehind { get; set; } = true;
|
||||||
|
public string? CliPath { get; set; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record Settings
|
||||||
|
{
|
||||||
|
// Preserve initializers when an older file lacks newly added properties (D5).
|
||||||
|
public TimeSpan RefreshInterval { get; set; } = TimeSpan.FromSeconds(60);
|
||||||
|
public TimeSpan ProbeInterval { get; set; } = TimeSpan.FromMinutes(5);
|
||||||
|
public double PaceThreshold { get; set; } = 10;
|
||||||
|
public bool PopupAhead { get; set; } = true;
|
||||||
|
public bool PopupBehind { get; set; } = true;
|
||||||
|
public InstallMode StreamDeckInstallMode { get; set; } = InstallMode.Ask;
|
||||||
|
public string? DismissedPluginVersion { get; set; }
|
||||||
|
public bool StartWithOs { get; set; }
|
||||||
|
public bool CloseToTray { get; set; } = true;
|
||||||
|
public ProviderSettings Claude { get; set; } = new();
|
||||||
|
public ProviderSettings Codex { get; set; } = new();
|
||||||
|
public ProviderSettings For(Provider provider) => provider == Provider.Claude ? Claude : Codex;
|
||||||
|
[System.Text.Json.Serialization.JsonIgnore]
|
||||||
|
public bool IsValid => RefreshInterval > TimeSpan.Zero && RefreshInterval <= TimeSpan.FromSeconds(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 &&
|
||||||
|
Enum.IsDefined(StreamDeckInstallMode);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class DataPaths
|
||||||
|
{
|
||||||
|
public static string DataDirectory => Environment.GetEnvironmentVariable("FINALTOKEN_DATA_DIR") is { Length: > 0 } path
|
||||||
|
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FinalToken");
|
||||||
|
public static string ClaudeDirectory => Environment.GetEnvironmentVariable("CLAUDE_CONFIG_DIR") is { Length: > 0 } path
|
||||||
|
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude");
|
||||||
|
public static string CodexDirectory => Environment.GetEnvironmentVariable("CODEX_HOME") is { Length: > 0 } path
|
||||||
|
? Path.GetFullPath(path) : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".codex");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class SettingsFile
|
||||||
|
{
|
||||||
|
public static Settings Load(string directory, DiagnosticLog diagnostics)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var value = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "settings.json")), CoreJsonContext.Default.Settings);
|
||||||
|
if (value is { IsValid: true }) return value;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException) { }
|
||||||
|
diagnostics.Add(null, "settings-defaults", "Settings missing or invalid; using defaults.");
|
||||||
|
return new();
|
||||||
|
}
|
||||||
|
public static Task SaveAsync(string directory, Settings settings, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (!settings.IsValid) throw new ArgumentException("Invalid settings.", nameof(settings));
|
||||||
|
return AtomicFile.WriteAsync(Path.Combine(directory, "settings.json"),
|
||||||
|
JsonSerializer.Serialize(settings, CoreJsonContext.Default.Settings), cancellationToken);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
|
||||||
|
namespace FinalToken.Core;
|
||||||
|
|
||||||
|
public sealed record WindowSnapshot(LimitWindow Window, PaceResult Pace)
|
||||||
|
{
|
||||||
|
public TimeSpan Age(DateTimeOffset now) => now - Window.SampleTime;
|
||||||
|
}
|
||||||
|
public sealed record ProviderSnapshot(Provider Provider, ProviderStatus Status, string? Reason,
|
||||||
|
IReadOnlyList<WindowSnapshot> Windows, TokenCounts Today, TokenCounts? Session, TokenCounts Week);
|
||||||
|
public sealed record Snapshot
|
||||||
|
{
|
||||||
|
// Keep this initializer for omitted properties in source-generated JSON (D9).
|
||||||
|
public int V { get; set; } = 1;
|
||||||
|
public required DateTimeOffset MadeAt { get; init; }
|
||||||
|
public required TimeSpan RefreshInterval { get; init; }
|
||||||
|
public string? AppPath { get; init; }
|
||||||
|
public required IReadOnlyList<ProviderSnapshot> Providers { get; init; }
|
||||||
|
}
|
||||||
|
public sealed record SnapshotReadResult(Snapshot? Snapshot, bool IsStale, string? Error);
|
||||||
|
|
||||||
|
public static class SnapshotFile
|
||||||
|
{
|
||||||
|
public static Task WriteAsync(string directory, Snapshot snapshot, CancellationToken cancellationToken = default) =>
|
||||||
|
AtomicFile.WriteAsync(Path.Combine(directory, "snapshot.json"),
|
||||||
|
JsonSerializer.Serialize(snapshot, CoreJsonContext.Default.Snapshot), cancellationToken);
|
||||||
|
public static SnapshotReadResult Read(string directory, DateTimeOffset? now = null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var snapshot = JsonSerializer.Deserialize(SharedFile.ReadAllText(Path.Combine(directory, "snapshot.json")), CoreJsonContext.Default.Snapshot);
|
||||||
|
if (snapshot is null || snapshot.V != 1 || snapshot.RefreshInterval <= TimeSpan.Zero || snapshot.Providers is null)
|
||||||
|
return new(null, true, "Snapshot schema is invalid or unsupported.");
|
||||||
|
var age = (now ?? DateTimeOffset.UtcNow) - snapshot.MadeAt;
|
||||||
|
return new(snapshot, age.TotalSeconds > snapshot.RefreshInterval.TotalSeconds * 3, null);
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException)
|
||||||
|
{ return new(null, true, "Snapshot is missing or invalid."); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, WriteIndented = false)]
|
||||||
|
[JsonSerializable(typeof(Snapshot))]
|
||||||
|
[JsonSerializable(typeof(Settings))]
|
||||||
|
[JsonSerializable(typeof(HistoryState))]
|
||||||
|
[JsonSerializable(typeof(HistoryPartition))]
|
||||||
|
[JsonSerializable(typeof(HistoryTransaction))]
|
||||||
|
public partial class CoreJsonContext : JsonSerializerContext;
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
namespace FinalToken.Core.StreamDeck;
|
||||||
|
|
||||||
|
public enum PluginInstallState { NoHostFound, NotInstalled, Outdated, UpToDate, NoShippedPlugin }
|
||||||
|
public sealed record PluginInstallStatus(PluginInstallState State, string? ShippedVersion = null, string? InstalledVersion = null);
|
||||||
|
public interface IPluginInstaller
|
||||||
|
{
|
||||||
|
Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default);
|
||||||
|
Task InstallOrUpdateAsync(CancellationToken cancellationToken = default);
|
||||||
|
}
|
||||||
|
public enum InstallAction { Nothing, Ask, Install }
|
||||||
|
public static class InstallPolicy
|
||||||
|
{
|
||||||
|
public static InstallAction Decide(InstallMode mode, PluginInstallStatus status, string? dismissedVersion) =>
|
||||||
|
status.State is not (PluginInstallState.NotInstalled or PluginInstallState.Outdated) || status.ShippedVersion is null
|
||||||
|
? InstallAction.Nothing : mode switch
|
||||||
|
{
|
||||||
|
InstallMode.Automatic => InstallAction.Install,
|
||||||
|
InstallMode.Ask when status.ShippedVersion != dismissedVersion => InstallAction.Ask,
|
||||||
|
_ => InstallAction.Nothing
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,202 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text.Json;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.StreamDeck;
|
||||||
|
|
||||||
|
public sealed record PluginHost(string PluginDirectory, string Executable, string ProcessName, IReadOnlyList<string>? Arguments = null, bool Flatpak = false);
|
||||||
|
public interface IHostProcesses
|
||||||
|
{
|
||||||
|
Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct);
|
||||||
|
Task StopAsync(PluginHost host, CancellationToken ct);
|
||||||
|
Task StartAsync(PluginHost host, CancellationToken ct);
|
||||||
|
}
|
||||||
|
public enum InstallOutcome { Installed, Updated, AlreadyCurrent, NoHost, NoShippedPlugin, RolledBack, Failed, HostStopped, HostRestarted, HostRestartFailed }
|
||||||
|
|
||||||
|
/// <summary>D11: stage beside the destination, stop only a running host, swap and restore on failure.</summary>
|
||||||
|
public sealed class PluginInstaller(string shippedDirectory, PluginHost? host, IHostProcesses? processes = null) : IPluginInstaller
|
||||||
|
{
|
||||||
|
public const string FolderName = "de.finalfactory.finaltoken.sdPlugin";
|
||||||
|
private readonly IHostProcesses processes = processes ?? new HostProcesses();
|
||||||
|
private readonly SemaphoreSlim gate = new(1, 1);
|
||||||
|
public event Action<InstallOutcome>? Outcome;
|
||||||
|
public static PluginInstaller CreateDefault(string? appDirectory = null) => new(
|
||||||
|
Path.Combine(appDirectory ?? AppContext.BaseDirectory, "streamdeck", FolderName), HostDiscovery.Find());
|
||||||
|
public Task<PluginInstallStatus> GetStatusAsync(CancellationToken cancellationToken = default) => Task.Run(() => Status(), cancellationToken);
|
||||||
|
private PluginInstallStatus Status()
|
||||||
|
{
|
||||||
|
if (host is null) return new(PluginInstallState.NoHostFound);
|
||||||
|
var shipped = ReadVersion(shippedDirectory);
|
||||||
|
if (shipped is null) return new(PluginInstallState.NoShippedPlugin);
|
||||||
|
var installedPath = Path.Combine(host.PluginDirectory, FolderName);
|
||||||
|
var installed = ReadVersion(installedPath);
|
||||||
|
return new(installed is null ? PluginInstallState.NotInstalled : installed >= shipped ? PluginInstallState.UpToDate : PluginInstallState.Outdated,
|
||||||
|
shipped.ToString(), installed?.ToString());
|
||||||
|
}
|
||||||
|
public async Task InstallOrUpdateAsync(CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
await gate.WaitAsync(cancellationToken);
|
||||||
|
try { await Task.Run(() => Install(cancellationToken), cancellationToken); }
|
||||||
|
finally { gate.Release(); }
|
||||||
|
}
|
||||||
|
private async Task Install(CancellationToken ct)
|
||||||
|
{
|
||||||
|
var status = Status();
|
||||||
|
if (status.State == PluginInstallState.NoHostFound) { Report(InstallOutcome.NoHost); return; }
|
||||||
|
if (status.State == PluginInstallState.NoShippedPlugin) { Report(InstallOutcome.NoShippedPlugin); throw new InvalidOperationException("Shipped plugin is missing or invalid."); }
|
||||||
|
if (status.State == PluginInstallState.UpToDate) { Report(InstallOutcome.AlreadyCurrent); return; }
|
||||||
|
var target = Path.Combine(host!.PluginDirectory, FolderName);
|
||||||
|
var suffix = Guid.NewGuid().ToString("N");
|
||||||
|
var staged = target + ".stage-" + suffix;
|
||||||
|
var backup = target + ".backup-" + suffix;
|
||||||
|
var movedOld = false;
|
||||||
|
var movedNew = false;
|
||||||
|
var restart = false;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(host.PluginDirectory);
|
||||||
|
Copy(shippedDirectory, staged, ct);
|
||||||
|
if (ReadVersion(staged)?.ToString() != status.ShippedVersion) throw new IOException("Staged plugin version changed.");
|
||||||
|
restart = await processes.IsRunningAsync(host, ct);
|
||||||
|
if (restart) { await processes.StopAsync(host, ct); Report(InstallOutcome.HostStopped); }
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
if (Directory.Exists(target)) { Directory.Move(target, backup); movedOld = true; }
|
||||||
|
Directory.Move(staged, target); movedNew = true;
|
||||||
|
if (restart) { await processes.StartAsync(host, CancellationToken.None); restart = false; Report(InstallOutcome.HostRestarted); }
|
||||||
|
Report(movedOld ? InstallOutcome.Updated : InstallOutcome.Installed);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (movedNew) Directory.Delete(target, true);
|
||||||
|
if (movedOld) Directory.Move(backup, target);
|
||||||
|
Report(movedOld || movedNew ? InstallOutcome.RolledBack : InstallOutcome.Failed);
|
||||||
|
}
|
||||||
|
catch { Report(InstallOutcome.Failed); throw; }
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (restart)
|
||||||
|
{
|
||||||
|
try { await processes.StartAsync(host, CancellationToken.None); Report(InstallOutcome.HostRestarted); }
|
||||||
|
catch { Report(InstallOutcome.HostRestartFailed); }
|
||||||
|
}
|
||||||
|
DeleteTemporary(staged);
|
||||||
|
// A backup left by a failed rollback must survive for recovery.
|
||||||
|
if (Directory.Exists(target) && ReadVersion(target)?.ToString() == status.ShippedVersion) DeleteTemporary(backup);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void Report(InstallOutcome outcome) => Outcome?.Invoke(outcome);
|
||||||
|
private static void DeleteTemporary(string path)
|
||||||
|
{
|
||||||
|
try { if (Directory.Exists(path)) Directory.Delete(path, true); }
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||||
|
}
|
||||||
|
private static void Copy(string source, string destination, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if ((File.GetAttributes(source) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported.");
|
||||||
|
Directory.CreateDirectory(destination);
|
||||||
|
foreach (var file in Directory.EnumerateFiles(source))
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
if ((File.GetAttributes(file) & FileAttributes.ReparsePoint) != 0) throw new IOException("Plugin links are unsupported.");
|
||||||
|
var copied = Path.Combine(destination, Path.GetFileName(file));
|
||||||
|
File.Copy(file, copied);
|
||||||
|
if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(copied, File.GetUnixFileMode(file));
|
||||||
|
}
|
||||||
|
foreach (var directory in Directory.EnumerateDirectories(source)) Copy(directory, Path.Combine(destination, Path.GetFileName(directory)), ct);
|
||||||
|
}
|
||||||
|
public static Version? ReadVersion(string directory)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var doc = JsonDocument.Parse(File.ReadAllText(Path.Combine(directory, "manifest.json")));
|
||||||
|
return doc.RootElement.TryGetProperty("Version", out var version) && version.ValueKind == JsonValueKind.String && Version.TryParse(version.GetString(), out var parsed) ? parsed : null;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException or JsonException or InvalidOperationException) { return null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class HostDiscovery
|
||||||
|
{
|
||||||
|
public const string FlatpakId = "me.amankhanna.opendeck";
|
||||||
|
public static PluginHost? Find()
|
||||||
|
{
|
||||||
|
if (OperatingSystem.IsWindows())
|
||||||
|
{
|
||||||
|
var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Elgato", "StreamDeck", "StreamDeck.exe");
|
||||||
|
// A running installation can be outside Program Files.
|
||||||
|
foreach (var process in Process.GetProcessesByName("StreamDeck"))
|
||||||
|
{
|
||||||
|
using (process)
|
||||||
|
{
|
||||||
|
try { executable = process.MainModule?.FileName ?? executable; }
|
||||||
|
catch (Exception e) when (e is System.ComponentModel.Win32Exception or InvalidOperationException) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return File.Exists(executable) ? new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Elgato", "StreamDeck", "Plugins"), executable, "StreamDeck") : null;
|
||||||
|
}
|
||||||
|
if (!OperatingSystem.IsLinux()) return null;
|
||||||
|
var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
||||||
|
var config = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(home, ".config");
|
||||||
|
var native = FindExecutable("opendeck");
|
||||||
|
if (native is not null) return new(Path.Combine(config, "opendeck", "plugins"), native, "opendeck");
|
||||||
|
var flatpak = FindExecutable("flatpak");
|
||||||
|
var installed = Directory.Exists(Path.Combine(home, ".local", "share", "flatpak", "app", FlatpakId)) ||
|
||||||
|
Directory.Exists(Path.Combine(Path.DirectorySeparatorChar.ToString(), "var", "lib", "flatpak", "app", FlatpakId));
|
||||||
|
return flatpak is not null && installed ? new(Path.Combine(home, ".var", "app", FlatpakId, "config", "opendeck", "plugins"), flatpak, "opendeck", ["run", FlatpakId], true) : null;
|
||||||
|
}
|
||||||
|
private static string? FindExecutable(string name) => (Environment.GetEnvironmentVariable("PATH") ?? "").Split(Path.PathSeparator)
|
||||||
|
.Where(Path.IsPathFullyQualified).Select(p => Path.Combine(p, name)).FirstOrDefault(File.Exists);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class HostProcesses : IHostProcesses
|
||||||
|
{
|
||||||
|
private static Process[] Matching(PluginHost host) => Process.GetProcessesByName(host.ProcessName);
|
||||||
|
public Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var processes = Matching(host);
|
||||||
|
foreach (var process in processes) process.Dispose();
|
||||||
|
return Task.FromResult(processes.Length > 0);
|
||||||
|
}
|
||||||
|
public async Task StopAsync(PluginHost host, CancellationToken ct)
|
||||||
|
{
|
||||||
|
if (host.Flatpak)
|
||||||
|
{
|
||||||
|
using var kill = Process.Start(new ProcessStartInfo(host.Executable) { UseShellExecute = false, ArgumentList = { "kill", HostDiscovery.FlatpakId } })
|
||||||
|
?? throw new IOException("Could not stop OpenDeck.");
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
timeout.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
try { await kill.WaitForExitAsync(timeout.Token); }
|
||||||
|
catch { if (!kill.HasExited) kill.Kill(true); throw; }
|
||||||
|
if (kill.ExitCode != 0) throw new IOException("OpenDeck stop failed.");
|
||||||
|
}
|
||||||
|
foreach (var process in Matching(host))
|
||||||
|
{
|
||||||
|
using (process)
|
||||||
|
{
|
||||||
|
if (process.HasExited) continue;
|
||||||
|
process.CloseMainWindow();
|
||||||
|
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||||
|
timeout.CancelAfter(TimeSpan.FromSeconds(5));
|
||||||
|
try { await process.WaitForExitAsync(timeout.Token); }
|
||||||
|
catch (OperationCanceledException)
|
||||||
|
{
|
||||||
|
if (!process.HasExited) process.Kill(true);
|
||||||
|
await process.WaitForExitAsync(CancellationToken.None);
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public Task StartAsync(PluginHost host, CancellationToken ct)
|
||||||
|
{
|
||||||
|
ct.ThrowIfCancellationRequested();
|
||||||
|
var start = new ProcessStartInfo(host.Executable) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(host.Executable)! };
|
||||||
|
foreach (var argument in host.Arguments ?? []) start.ArgumentList.Add(argument);
|
||||||
|
using var process = Process.Start(start) ?? throw new IOException("Could not start Stream Deck host.");
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Stream Deck
|
||||||
|
D10 native SDK-v2 plugin. Read snapshots using SnapshotFile (D9); use Core DTOs.
|
||||||
|
Keep file IO off the socket owner loop. Never reconnect after the host closes the socket.
|
||||||
|
Protocol DTOs use PluginJsonContext. Assets and the local inspector live in plugin/.
|
||||||
|
Directory.Build.props is the release version source. tools/publish.py stamps the published manifest;
|
||||||
|
the repository manifest is an asset template, not the shipped version.
|
||||||
|
Core/StreamDeck owns D11 deployment with injectable host process control.
|
||||||
|
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<PublishAot>true</PublishAot>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup><ProjectReference Include="../FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||||
|
<ItemGroup><Content Include="plugin/**/*" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="Never" /></ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Threading.Channels;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using FinalToken.StreamDeck;
|
||||||
|
|
||||||
|
var registration = Registration.Parse(args);
|
||||||
|
if (registration is null) return 2;
|
||||||
|
using var stop = new CancellationTokenSource();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var socket = new ClientWebSocket();
|
||||||
|
await socket.ConnectAsync(new Uri($"ws://127.0.0.1:{registration.Port}"), stop.Token);
|
||||||
|
var transport = new PluginSocket(socket);
|
||||||
|
var session = new PluginSession(transport, PluginSession.LaunchAppAsync);
|
||||||
|
await session.RegisterAsync(registration, stop.Token);
|
||||||
|
await RollingLog.WriteAsync("registered");
|
||||||
|
// D9: file IO runs on a separate worker; all state and WebSocket sends have one owner.
|
||||||
|
var updates = Channel.CreateBounded<SnapshotReadResult>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropOldest });
|
||||||
|
var poll = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
|
||||||
|
do { updates.Writer.TryWrite(SnapshotFile.Read(DataPaths.DataDirectory)); }
|
||||||
|
while (await timer.WaitForNextTickAsync(stop.Token));
|
||||||
|
});
|
||||||
|
var incoming = session.ReceiveAsync(stop.Token);
|
||||||
|
var update = updates.Reader.ReadAsync(stop.Token).AsTask();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var ready = await Task.WhenAny(incoming, update);
|
||||||
|
if (ready == incoming)
|
||||||
|
{
|
||||||
|
var json = await incoming;
|
||||||
|
if (json is null) break;
|
||||||
|
await session.HandleAsync(json, DateTimeOffset.UtcNow, stop.Token);
|
||||||
|
incoming = session.ReceiveAsync(stop.Token);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
await session.UpdateAsync(await update, DateTimeOffset.UtcNow, stop.Token);
|
||||||
|
update = updates.Reader.ReadAsync(stop.Token).AsTask();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await stop.CancelAsync();
|
||||||
|
try { await poll; } catch (OperationCanceledException) { }
|
||||||
|
try { await incoming; } catch (Exception e) when (e is OperationCanceledException or WebSocketException) { }
|
||||||
|
}
|
||||||
|
if (socket.State == WebSocketState.CloseReceived)
|
||||||
|
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None);
|
||||||
|
await RollingLog.WriteAsync(session.ConnectionEndCode);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is WebSocketException or IOException or OperationCanceledException or UnauthorizedAccessException)
|
||||||
|
{
|
||||||
|
await stop.CancelAsync();
|
||||||
|
await RollingLog.WriteAsync("connection-ended");
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class RollingLog
|
||||||
|
{
|
||||||
|
public static async Task WriteAsync(string code)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var path = Path.Combine(DataPaths.DataDirectory, "streamdeck.log");
|
||||||
|
var previous = File.Exists(path) ? await File.ReadAllTextAsync(path) : "";
|
||||||
|
var lines = previous.Split('\n', StringSplitOptions.RemoveEmptyEntries).TakeLast(199);
|
||||||
|
await AtomicFile.WriteAsync(path, string.Join('\n', lines) + $"\n{DateTimeOffset.UtcNow:O} {code}\n");
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or UnauthorizedAccessException) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net.WebSockets;
|
||||||
|
using System.Text;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.StreamDeck;
|
||||||
|
|
||||||
|
public sealed record Registration(int Port, string Uuid, string Event)
|
||||||
|
{
|
||||||
|
public static Registration? Parse(string[] args)
|
||||||
|
{
|
||||||
|
var values = new Dictionary<string, string>();
|
||||||
|
for (var i = 0; i + 1 < args.Length; i += 2) values[args[i]] = args[i + 1];
|
||||||
|
return values.TryGetValue("-port", out var port) && int.TryParse(port, out var number) && number is > 0 and <= 65535 &&
|
||||||
|
values.TryGetValue("-pluginUUID", out var uuid) && uuid.Length > 0 &&
|
||||||
|
values.TryGetValue("-registerEvent", out var evt) && evt == "registerPlugin" && values.ContainsKey("-info") ? new(number, uuid, evt) : null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public sealed record Command(string Event, string? Context = null, string? Uuid = null, string? Action = null, JsonElement? Payload = null);
|
||||||
|
public sealed record ImagePayload(string Image, int Target = 0);
|
||||||
|
public sealed record TitlePayload(string Title, int Target = 0);
|
||||||
|
public sealed record InspectorPayload(StatSettings Settings, WindowOption[] Windows);
|
||||||
|
public sealed record WindowOption(string Id, string Label);
|
||||||
|
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
|
||||||
|
[JsonSerializable(typeof(Command))]
|
||||||
|
[JsonSerializable(typeof(ImagePayload))]
|
||||||
|
[JsonSerializable(typeof(TitlePayload))]
|
||||||
|
[JsonSerializable(typeof(StatSettings))]
|
||||||
|
[JsonSerializable(typeof(InspectorPayload))]
|
||||||
|
public partial class PluginJsonContext : JsonSerializerContext;
|
||||||
|
|
||||||
|
public interface IPluginSocket
|
||||||
|
{
|
||||||
|
Task SendAsync(string json, CancellationToken cancellationToken);
|
||||||
|
Task<string?> ReceiveAsync(CancellationToken cancellationToken);
|
||||||
|
}
|
||||||
|
public sealed class PluginSocket(ClientWebSocket socket) : IPluginSocket
|
||||||
|
{
|
||||||
|
public async Task SendAsync(string json, CancellationToken cancellationToken) =>
|
||||||
|
await socket.SendAsync(Encoding.UTF8.GetBytes(json), WebSocketMessageType.Text, true, cancellationToken);
|
||||||
|
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
var buffer = new byte[8192];
|
||||||
|
using var message = new MemoryStream();
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
var result = await socket.ReceiveAsync(buffer.AsMemory(), cancellationToken);
|
||||||
|
if (result.MessageType == WebSocketMessageType.Close) return null;
|
||||||
|
if (result.MessageType != WebSocketMessageType.Text || message.Length + result.Count > 1_048_576)
|
||||||
|
throw new InvalidDataException("Invalid host frame.");
|
||||||
|
message.Write(buffer, 0, result.Count);
|
||||||
|
if (result.EndOfMessage) return Encoding.UTF8.GetString(message.ToArray());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class PluginSession(IPluginSocket socket, Func<string?, Task<bool>> launch)
|
||||||
|
{
|
||||||
|
public string ConnectionEndCode { get; private set; } = "host-closed";
|
||||||
|
public async Task<string?> ReceiveAsync(CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
try { return await socket.ReceiveAsync(cancellationToken); }
|
||||||
|
catch (InvalidDataException) { ConnectionEndCode = "connection-ended"; return null; }
|
||||||
|
}
|
||||||
|
public const string Action = "de.finalfactory.finaltoken.stat";
|
||||||
|
private readonly Dictionary<string, StatSettings> keys = [];
|
||||||
|
private readonly Dictionary<string, string> images = [];
|
||||||
|
private SnapshotReadResult read = new(null, true, null);
|
||||||
|
public Task RegisterAsync(Registration registration, CancellationToken ct = default) => Send(new(registration.Event, Uuid: registration.Uuid), ct);
|
||||||
|
public async Task UpdateAsync(SnapshotReadResult snapshot, DateTimeOffset now, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
read = StatRenderer.Validate(snapshot);
|
||||||
|
foreach (var (context, settings) in keys) await Draw(context, settings, now, ct);
|
||||||
|
}
|
||||||
|
public async Task HandleAsync(string json, DateTimeOffset now, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
var root = doc.RootElement;
|
||||||
|
if (root.ValueKind != JsonValueKind.Object || !root.TryGetProperty("event", out var evt) || evt.ValueKind != JsonValueKind.String) return;
|
||||||
|
if (evt.GetString() == "systemDidWakeUp") { images.Clear(); await UpdateAsync(read, now, ct); return; }
|
||||||
|
if (!root.TryGetProperty("context", out var ctx) || ctx.ValueKind != JsonValueKind.String || ctx.GetString() is not { Length: > 0 } context) return;
|
||||||
|
if (root.TryGetProperty("action", out var action) && action.GetString() != Action) return;
|
||||||
|
root.TryGetProperty("payload", out var payload);
|
||||||
|
switch (evt.GetString())
|
||||||
|
{
|
||||||
|
case "willDisappear": keys.Remove(context); images.Remove(context); break;
|
||||||
|
case "willAppear":
|
||||||
|
case "didReceiveSettings":
|
||||||
|
var settings = ReadSettings(payload);
|
||||||
|
if (settings is null) return;
|
||||||
|
keys[context] = settings;
|
||||||
|
await Draw(context, settings, now, ct);
|
||||||
|
break;
|
||||||
|
case "keyDown":
|
||||||
|
if (!await launch(read.Snapshot?.AppPath)) await Send(new("showAlert", context), ct);
|
||||||
|
break;
|
||||||
|
case "sendToPlugin":
|
||||||
|
if (payload.ValueKind == JsonValueKind.Object && payload.TryGetProperty("settings", out _))
|
||||||
|
{
|
||||||
|
var updated = ReadSettings(payload);
|
||||||
|
if (updated is null) return;
|
||||||
|
keys[context] = updated;
|
||||||
|
await Send(new("setSettings", context, Payload: JsonSerializer.SerializeToElement(updated, PluginJsonContext.Default.StatSettings)), ct);
|
||||||
|
await Draw(context, updated, now, ct);
|
||||||
|
}
|
||||||
|
await Inspector(context, ct);
|
||||||
|
break;
|
||||||
|
case "propertyInspectorDidAppear": await Inspector(context, ct); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is JsonException or InvalidOperationException or ArgumentException) { }
|
||||||
|
}
|
||||||
|
private static StatSettings? ReadSettings(JsonElement payload)
|
||||||
|
{
|
||||||
|
if (payload.ValueKind != JsonValueKind.Object || !payload.TryGetProperty("settings", out var element)) return new();
|
||||||
|
var settings = element.Deserialize(PluginJsonContext.Default.StatSettings);
|
||||||
|
return settings is { IsValid: true } ? settings : null;
|
||||||
|
}
|
||||||
|
private Task Inspector(string context, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var settings = keys.GetValueOrDefault(context) ?? new();
|
||||||
|
var windows = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider)?.Windows
|
||||||
|
.Select(w => new WindowOption(w.Window.Id, w.Window.Label)).ToArray() ?? [];
|
||||||
|
return Send(new("sendToPropertyInspector", context, Action: Action,
|
||||||
|
Payload: JsonSerializer.SerializeToElement(new InspectorPayload(settings, windows), PluginJsonContext.Default.InspectorPayload)), ct);
|
||||||
|
}
|
||||||
|
private async Task Draw(string context, StatSettings settings, DateTimeOffset now, CancellationToken ct)
|
||||||
|
{
|
||||||
|
var svg = StatRenderer.Render(read, settings, now);
|
||||||
|
if (images.GetValueOrDefault(context) == svg) return;
|
||||||
|
await Send(new("setTitle", context, Payload: JsonSerializer.SerializeToElement(new TitlePayload(""), PluginJsonContext.Default.TitlePayload)), ct);
|
||||||
|
await Send(new("setImage", context, Payload: JsonSerializer.SerializeToElement(new ImagePayload("data:image/svg+xml;base64," + Convert.ToBase64String(Encoding.UTF8.GetBytes(svg))), PluginJsonContext.Default.ImagePayload)), ct);
|
||||||
|
images[context] = svg;
|
||||||
|
}
|
||||||
|
private Task Send(Command command, CancellationToken ct) => socket.SendAsync(JsonSerializer.Serialize(command, PluginJsonContext.Default.Command), ct);
|
||||||
|
public static Task<bool> LaunchAppAsync(string? path) => Task.Run(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (path is null || !Path.IsPathFullyQualified(path) || !File.Exists(path)) return false;
|
||||||
|
using var process = Process.Start(new ProcessStartInfo(path) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(path)! });
|
||||||
|
return process is not null;
|
||||||
|
}
|
||||||
|
catch (Exception e) when (e is IOException or System.ComponentModel.Win32Exception or InvalidOperationException) { return false; }
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
# Stream Deck plugin
|
||||||
|
|
||||||
|
D10 uses a native SDK-v2 WebSocket connection. There is one owner for key state and socket sends;
|
||||||
|
a separate worker polls the D9 Core reader every two seconds. Closing the connection exits.
|
||||||
|
Only changed SVGs are sent. The bounded log is `streamdeck.log` in FinalToken's data directory.
|
||||||
|
|
||||||
|
Protocol sources checked on 2026-10-14:
|
||||||
|
|
||||||
|
- [Elgato Plugin WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/plugin/)
|
||||||
|
— registration arguments, key/settings/wake events and drawing commands.
|
||||||
|
- [Elgato Property Inspector WebSocket API](https://docs.elgato.com/streamdeck/sdk/references/websocket/ui/)
|
||||||
|
— inspector registration and messages.
|
||||||
|
- [Elgato Manifest](https://docs.elgato.com/streamdeck/sdk/references/manifest/)
|
||||||
|
— native entry points, SDK version, actions and resources.
|
||||||
|
- [OpenDeck README](https://github.com/aberja/opendeck)
|
||||||
|
— native plugins and host installation.
|
||||||
|
- [OpenDeck manifest parser](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/manifest.rs)
|
||||||
|
— `CodePathLin`.
|
||||||
|
- [OpenDeck plugin lifecycle](https://github.com/aberja/opendeck/blob/main/src-tauri/src/plugins/mod.rs)
|
||||||
|
and [shared paths](https://github.com/aberja/opendeck/blob/main/src-tauri/src/shared.rs)
|
||||||
|
— `app_config_dir()/plugins`; Tauri identifier `opendeck`.
|
||||||
|
- [OpenDeck installation script](https://github.com/aberja/opendeck/blob/main/install_opendeck.sh)
|
||||||
|
— executable `opendeck`, Flatpak ID `me.amankhanna.opendeck`.
|
||||||
|
|
||||||
|
The D11 installer discovers Windows Stream Deck, Linux native OpenDeck and Flatpak OpenDeck.
|
||||||
|
Linux locations are `$XDG_CONFIG_HOME/opendeck/plugins` (default `~/.config/opendeck/plugins`)
|
||||||
|
and `~/.var/app/me.amankhanna.opendeck/config/opendeck/plugins`.
|
||||||
|
Deployment stages in a sibling folder, swaps with a backup and rolls back on failure.
|
||||||
|
`PluginInstaller.CreateDefault()` is the app entry point; `Outcome` reports installation steps.
|
||||||
|
The interface and install policy remain compatible with the original Core contract.
|
||||||
|
|
||||||
|
`python -B tools/publish.py win-x64` builds the app, CLI and plugin into one folder and ZIP.
|
||||||
|
The CLI is named `finaltoken-cli` on every platform (`finaltoken-cli.exe` on Windows),
|
||||||
|
beside the desktop app. Publish a Linux RID on Linux;
|
||||||
|
the .NET NativeAOT toolchain does not support cross-OS compilation.
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using System.Security;
|
||||||
|
using FinalToken.Core;
|
||||||
|
|
||||||
|
namespace FinalToken.StreamDeck;
|
||||||
|
|
||||||
|
public enum Metric { SessionPercent, WeekPercent, PaceDelta, TimeToReset, TokensToday, TokensWeek }
|
||||||
|
public sealed record StatSettings(string Provider = "Claude", string Metric = "SessionPercent", string Window = "")
|
||||||
|
{
|
||||||
|
public bool IsValid => Enum.TryParse<Core.Provider>(Provider, out var p) && Enum.IsDefined(p) &&
|
||||||
|
Enum.TryParse<StreamDeck.Metric>(Metric, out var m) && Enum.IsDefined(m) && Window is not null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class StatRenderer
|
||||||
|
{
|
||||||
|
public static WindowSnapshot? SelectWindow(ProviderSnapshot provider, StatSettings settings)
|
||||||
|
{
|
||||||
|
if (settings.Window.Length > 0) return provider.Windows.FirstOrDefault(w => w.Window.Id == settings.Window);
|
||||||
|
if (settings.Metric is "PaceDelta" or "TimeToReset")
|
||||||
|
return provider.Windows.FirstOrDefault(w => w.Window.Length is { } length && length < TimeSpan.FromDays(1)) ?? provider.Windows.FirstOrDefault();
|
||||||
|
var week = settings.Metric is "WeekPercent";
|
||||||
|
return provider.Windows.FirstOrDefault(w => week ? w.Window.Length >= TimeSpan.FromDays(1) :
|
||||||
|
w.Window.Length is { } length && length < TimeSpan.FromDays(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string Render(SnapshotReadResult read, StatSettings settings, DateTimeOffset now)
|
||||||
|
{
|
||||||
|
read = Validate(read);
|
||||||
|
var provider = read.Snapshot?.Providers.FirstOrDefault(p => p.Provider.ToString() == settings.Provider);
|
||||||
|
var offline = read.IsStale || provider is null;
|
||||||
|
var window = provider is null ? null : SelectWindow(provider, settings);
|
||||||
|
var metric = Enum.TryParse<Metric>(settings.Metric, out var parsed) ? parsed : Metric.SessionPercent;
|
||||||
|
var state = offline ? PaceState.Unknown : window?.Pace.State ?? PaceState.Unknown;
|
||||||
|
var color = state switch { PaceState.Ahead => "#ef6461", PaceState.Behind => "#69a7ff", PaceState.OnTrack => "#58d6a0", _ => "#a0a7b4" };
|
||||||
|
var label = metric switch { Metric.SessionPercent => "SESSION", Metric.WeekPercent => "WEEK", Metric.PaceDelta => "PACE", Metric.TimeToReset => "RESET", Metric.TokensToday => "TODAY", _ => "WEEK TOKENS" };
|
||||||
|
var value = offline ? "offline" : metric switch
|
||||||
|
{
|
||||||
|
Metric.TokensToday => Compact(provider!.Today.Total),
|
||||||
|
Metric.TokensWeek => Compact(provider!.Week.Total),
|
||||||
|
Metric.PaceDelta => window?.Pace.Delta is { } delta ? delta.ToString("+0;-0;0", CultureInfo.InvariantCulture) + "pp" : "—",
|
||||||
|
Metric.TimeToReset => window?.Window.ResetsAt is { } reset ? Duration(reset - now) : "—",
|
||||||
|
_ => window is null ? "—" : window.Window.UsedPercent.ToString("0", CultureInfo.InvariantCulture) + "%"
|
||||||
|
};
|
||||||
|
var bar = "";
|
||||||
|
if (!offline && window is not null && metric is Metric.SessionPercent or Metric.WeekPercent)
|
||||||
|
{
|
||||||
|
var width = Math.Clamp(window.Window.UsedPercent, 0, 100) * .6;
|
||||||
|
bar = FormattableString.Invariant($"<rect x='6' y='59' width='60' height='5' rx='2' fill='#343b48'/><rect x='6' y='59' width='{width:0.##}' height='5' rx='2' fill='{color}'/>");
|
||||||
|
if (window.Pace.ElapsedFraction is { } e)
|
||||||
|
bar += FormattableString.Invariant($"<path d='M{6 + Math.Clamp(e, 0, 1) * 60:0.##} 56v11' stroke='white' stroke-width='2'/>");
|
||||||
|
}
|
||||||
|
return $"<svg xmlns='http://www.w3.org/2000/svg' width='72' height='72' viewBox='0 0 72 72'><rect width='72' height='72' rx='8' fill='#151a23'/><text x='36' y='13' text-anchor='middle' font-family='Arial,sans-serif' font-size='9' fill='#c4cbd6'>{SecurityElement.Escape(settings.Provider)}</text><text x='36' y='25' text-anchor='middle' font-family='Arial,sans-serif' font-size='8' fill='#c4cbd6'>{label}</text><text x='36' y='48' text-anchor='middle' font-family='Arial,sans-serif' font-weight='bold' font-size='{(value.Length > 6 ? 14 : 20)}' fill='{color}'>{value}</text>{bar}</svg>";
|
||||||
|
}
|
||||||
|
// The reader rejects unsupported schemas; nested data is still an external trust boundary (D9).
|
||||||
|
public static SnapshotReadResult Validate(SnapshotReadResult read)
|
||||||
|
{
|
||||||
|
if (read.Snapshot is not { } snapshot) return new(null, true, read.Error);
|
||||||
|
if (snapshot.Providers is null || snapshot.Providers.Any(p => p is null || !Enum.IsDefined(p.Provider) || p.Windows is null ||
|
||||||
|
p.Windows.Any(w => w is null || w.Window is null || w.Pace is null || w.Window.Id is null || w.Window.Label is null ||
|
||||||
|
!double.IsFinite(w.Window.UsedPercent) || w.Window.UsedPercent is < 0 or > 100 ||
|
||||||
|
w.Pace.ElapsedFraction is { } e && !double.IsFinite(e) || w.Pace.Delta is { } d && !double.IsFinite(d))))
|
||||||
|
return new(null, true, "Invalid snapshot content.");
|
||||||
|
return read;
|
||||||
|
}
|
||||||
|
private static string Compact(long value) => value >= 1_000_000 ? (value / 1_000_000d).ToString("0.#", CultureInfo.InvariantCulture) + "M" :
|
||||||
|
value >= 1_000 ? (value / 1_000d).ToString("0.#", CultureInfo.InvariantCulture) + "k" : value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
private static string Duration(TimeSpan time) => time <= TimeSpan.Zero ? "0m" : time.TotalDays >= 1 ? $"{(int)time.TotalDays}d {time.Hours}h" :
|
||||||
|
time.TotalHours >= 1 ? $"{(int)time.TotalHours}h {time.Minutes}m" : $"{Math.Ceiling(time.TotalMinutes):0}m";
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72" viewBox="0 0 72 72"><rect width="72" height="72" rx="12" fill="#151a23"/><path d="M18 18h38v8H27v9h24v8H27v13h-9z" fill="#58d6a0"/></svg>
|
||||||
|
After Width: | Height: | Size: 201 B |
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="72" height="72"><rect width="72" height="72" rx="8" fill="#151a23"/><text x="36" y="29" text-anchor="middle" font-family="Arial" font-size="10" fill="#c4cbd6">FinalToken</text><text x="36" y="49" text-anchor="middle" font-family="Arial" font-size="16" fill="#a0a7b4">offline</text></svg>
|
||||||
|
After Width: | Height: | Size: 335 B |
@@ -0,0 +1,5 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><link rel="stylesheet" href="style.css"><title>FinalToken Stat</title></head>
|
||||||
|
<body><label>Provider<select id="provider"><option>Claude</option><option>Codex</option></select></label>
|
||||||
|
<label>Metric<select id="metric"><option value="SessionPercent">Session percent</option><option value="WeekPercent">Week percent</option><option value="PaceDelta">Pace delta</option><option value="TimeToReset">Time to reset</option><option value="TokensToday">Tokens today</option><option value="TokensWeek">Tokens this week</option></select></label>
|
||||||
|
<label>Window<select id="window"><option value="">Automatic</option></select></label><p>Press the key to open FinalToken. Keep FinalToken running to refresh stats.</p><script src="inspector.js"></script></body></html>
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
'use strict';
|
||||||
|
let connection, context;
|
||||||
|
const provider = document.getElementById('provider'), metric = document.getElementById('metric'), windowSelect = document.getElementById('window');
|
||||||
|
function apply(settings) {
|
||||||
|
provider.value = settings.provider || 'Claude'; metric.value = settings.metric || 'SessionPercent';
|
||||||
|
if (!Array.from(windowSelect.options).some(o => o.value === settings.window) && settings.window) windowSelect.add(new Option(settings.window, settings.window));
|
||||||
|
windowSelect.value = settings.window || '';
|
||||||
|
}
|
||||||
|
function send(payload) { if (connection && connection.readyState === WebSocket.OPEN) connection.send(JSON.stringify({event:'sendToPlugin',action:'de.finalfactory.finaltoken.stat',context,payload})); }
|
||||||
|
window.connectElgatoStreamDeckSocket = (port, uuid, event, info, actionInfo) => {
|
||||||
|
const action = JSON.parse(actionInfo); context = action.context; apply(action.payload.settings || {});
|
||||||
|
connection = new WebSocket(`ws://127.0.0.1:${port}`);
|
||||||
|
connection.onopen = () => { connection.send(JSON.stringify({event,uuid})); send({request:'windows'}); };
|
||||||
|
connection.onmessage = message => {
|
||||||
|
const data = JSON.parse(message.data);
|
||||||
|
if (data.event === 'didReceiveSettings') apply(data.payload.settings);
|
||||||
|
if (data.event === 'sendToPropertyInspector') {
|
||||||
|
windowSelect.replaceChildren(new Option('Automatic', ''));
|
||||||
|
for (const item of data.payload.windows || []) windowSelect.add(new Option(item.label, item.id));
|
||||||
|
apply(data.payload.settings);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
for (const element of [provider,metric,windowSelect]) element.addEventListener('change', () => {
|
||||||
|
if (element === provider) windowSelect.value = '';
|
||||||
|
send({settings:{provider:provider.value,metric:metric.value,window:windowSelect.value}});
|
||||||
|
});
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
:root{color-scheme:dark}body{margin:16px 12px;background:#2d2d2d;color:#d8d8d8;font:12px Arial,sans-serif}label{display:grid;grid-template-columns:72px 1fr;align-items:center;gap:8px;margin-bottom:12px}select{min-width:0;background:#3d3d3d;color:#eee;border:1px solid #555;border-radius:3px;padding:6px}select:focus{outline:1px solid #2ea8ff}p{line-height:1.5;color:#aaa}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
{
|
||||||
|
"UUID": "de.finalfactory.finaltoken",
|
||||||
|
"Name": "FinalToken",
|
||||||
|
"Author": "Final Factory",
|
||||||
|
"Description": "Claude and Codex usage from FinalToken.",
|
||||||
|
"Version": "1.0.0.1",
|
||||||
|
"SDKVersion": 2,
|
||||||
|
"CodePathWin": "FinalToken.StreamDeck.exe",
|
||||||
|
"CodePathLin": "FinalToken.StreamDeck",
|
||||||
|
"Icon": "images/icon",
|
||||||
|
"Category": "FinalToken",
|
||||||
|
"CategoryIcon": "images/icon",
|
||||||
|
"PropertyInspectorPath": "inspector/index.html",
|
||||||
|
"Software": { "MinimumVersion": "7.0" },
|
||||||
|
"OS": [ { "Platform": "windows", "MinimumVersion": "10" }, { "Platform": "linux", "MinimumVersion": "0" } ],
|
||||||
|
"Actions": [ {
|
||||||
|
"UUID": "de.finalfactory.finaltoken.stat",
|
||||||
|
"Name": "Stat",
|
||||||
|
"Tooltip": "Show usage. Press to open FinalToken.",
|
||||||
|
"Icon": "images/icon",
|
||||||
|
"SupportedInMultiActions": false,
|
||||||
|
"States": [ { "Image": "images/key", "ShowTitle": false } ]
|
||||||
|
} ]
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# App tests
|
||||||
|
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||||
|
Run `dotnet test --project tests/FinalToken.App.Tests -c Release` from the root.
|
||||||
|
View-model tests use public Core queries. Headless tests run on a dedicated UI thread with
|
||||||
|
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.
|
||||||
|
Popup expiry uses an injected TimeProvider; fire timers and pump the dispatcher instead of sleeping.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<IsTestProject>true</IsTestProject>
|
||||||
|
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||||
|
<TestingPlatformDotnetTestSupport>true</TestingPlatformDotnetTestSupport>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Avalonia.Headless" />
|
||||||
|
<PackageReference Include="xunit.v3.aot.mtp-v2" />
|
||||||
|
<ProjectReference Include="../../src/FinalToken.App/FinalToken.App.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
using System.Globalization;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.App.Tests;
|
||||||
|
|
||||||
|
public sealed class FormattingTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void DailyChartLabelAndTooltipUseTheBucketsLocalDate()
|
||||||
|
{
|
||||||
|
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);
|
||||||
|
Assert.Equal("10-14", Display.ChartDateLabel(day, TimeSpan.FromDays(1)));
|
||||||
|
Assert.Equal(day.DateTime.ToString("g"), Display.ChartTimestamp(day, TimeSpan.FromDays(1)));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(null)]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("custom-config")]
|
||||||
|
public void LinuxAutostartHonorsConfigHome(string? configHome)
|
||||||
|
{
|
||||||
|
var home = Path.Combine(Path.GetTempPath(), "fixture-home");
|
||||||
|
var config = string.IsNullOrEmpty(configHome) ? null : Path.Combine(Path.GetTempPath(), configHome);
|
||||||
|
Assert.Equal(Path.Combine(config ?? Path.Combine(home, ".config"), "autostart", "finaltoken.desktop"), OsStartup.LinuxAutostartPath(config, home));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("de-DE")]
|
||||||
|
[InlineData("en-US")]
|
||||||
|
public void FutureProjectionIncludesLocalDateInUsersCulture(string culture)
|
||||||
|
{
|
||||||
|
var clock = new FixedClock();
|
||||||
|
var projection = new DateTimeOffset(2026, 10, 16, 6, 24, 0, TimeSpan.Zero);
|
||||||
|
var userCulture = CultureInfo.GetCultureInfo(culture);
|
||||||
|
Assert.Equal(new DateTime(2026, 10, 16, 8, 24, 0).ToString("g", userCulture), Display.Projection(projection, clock, userCulture));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void TodaysProjectionUsesLocalTimeOnly()
|
||||||
|
{
|
||||||
|
Assert.Equal("23:24", Display.Projection(new(2026, 10, 14, 21, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ProjectionDateChangesAtLocalMidnight()
|
||||||
|
{
|
||||||
|
Assert.Equal("15.10.2026 00:24", Display.Projection(new(2026, 10, 14, 22, 24, 0, TimeSpan.Zero), new FixedClock(), CultureInfo.GetCultureInfo("de-DE")));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, new double[] { 0 })]
|
||||||
|
[InlineData(1, new double[] { 0, 1 })]
|
||||||
|
[InlineData(2, new double[] { 0, 1, 2 })]
|
||||||
|
[InlineData(3, new double[] { 0, 1, 2, 3 })]
|
||||||
|
public void SmallChartTicksAreDistinctIntegers(double maximum, double[] expected)
|
||||||
|
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
|
||||||
|
[Theory]
|
||||||
|
[InlineData(5, new double[] { 0, 2, 4, 6 })]
|
||||||
|
[InlineData(17, new double[] { 0, 5, 10, 15, 20 })]
|
||||||
|
[InlineData(123456, new double[] { 0, 50000, 100000, 150000 })]
|
||||||
|
public void LargerChartTicksUseRoundedStepsAndCoverMaximum(double maximum, double[] expected)
|
||||||
|
=> Assert.Equal(expected, UsageChart.AxisTicks(maximum));
|
||||||
|
[Fact]
|
||||||
|
public void PercentTicksKeepQuarterMarksAndEmptyPercentChartHasOnlyZero()
|
||||||
|
{
|
||||||
|
Assert.Equal([0d, 25, 50, 75, 100], UsageChart.AxisTicks(3, 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);
|
||||||
|
public override TimeZoneInfo LocalTimeZone { get; } = TimeZoneInfo.CreateCustomTimeZone("Fixture+02", TimeSpan.FromHours(2), "Fixture", "Fixture");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
using Avalonia;
|
||||||
|
using Avalonia.Controls;
|
||||||
|
using Avalonia.Headless;
|
||||||
|
using Avalonia.Interactivity;
|
||||||
|
using Avalonia.Media.Imaging;
|
||||||
|
using Avalonia.Styling;
|
||||||
|
using Avalonia.Themes.Fluent;
|
||||||
|
using Avalonia.Threading;
|
||||||
|
using Avalonia.VisualTree;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using FinalToken.Core.StreamDeck;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.App.Tests;
|
||||||
|
|
||||||
|
public sealed class HeadlessTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ViewsRenderAndInteractionsApplySettingsAndPopupActions()
|
||||||
|
{
|
||||||
|
var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
AppBuilder.Configure<TestApplication>().UseSkia().UseHarfBuzz().UseHeadless(new() { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
||||||
|
var root = new DirectoryInfo(AppContext.BaseDirectory);
|
||||||
|
while (root.Parent is not null && !File.Exists(Path.Combine(root.FullName, "FinalToken.slnx"))) root = root.Parent;
|
||||||
|
var shots = Environment.GetEnvironmentVariable("FINALTOKEN_SCREENSHOT_DIR") ?? Path.Combine(root.Parent!.FullName, "runs", "shots", "app");
|
||||||
|
Directory.CreateDirectory(shots);
|
||||||
|
var model = FakeData.Model();
|
||||||
|
var panel = new PanelWindow(model, () => { }, () => { }, () => { }, () => { }) { Height = 2450 };
|
||||||
|
panel.RequestedThemeVariant = ThemeVariant.Light; panel.Show(); Save(panel, "panel-light.png");
|
||||||
|
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 == "Tokens per day");
|
||||||
|
var filters = panel.GetVisualDescendants().OfType<ComboBox>().ToArray();
|
||||||
|
filters[0].SelectedIndex = 4; filters[1].SelectedIndex = 2;
|
||||||
|
Assert.Equal(HistoryRange.All, model.Range); Assert.Equal(Provider.Codex, model.ProviderFilter);
|
||||||
|
filters[0].SelectedIndex = 1; filters[1].SelectedIndex = 0;
|
||||||
|
panel.RequestedThemeVariant = ThemeVariant.Dark; Save(panel, "panel-dark.png");
|
||||||
|
model.Snapshot = FakeData.Snapshot(DateTimeOffset.UtcNow, true); Save(panel, "panel-unavailable.png"); panel.Close();
|
||||||
|
Settings? saved = null;
|
||||||
|
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 };
|
||||||
|
settings.Show(); Save(settings, "settings.png");
|
||||||
|
var refresh = settings.GetVisualDescendants().OfType<NumericUpDown>().First(); refresh.Value = 25;
|
||||||
|
settings.GetVisualDescendants().OfType<CheckBox>().First().IsChecked = false;
|
||||||
|
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));
|
||||||
|
Assert.NotNull(saved); Assert.Equal(TimeSpan.FromSeconds(25), saved.RefreshInterval); Assert.True(saved.StartWithOs);
|
||||||
|
Assert.Equal(initial.Claude with { CliPath = "claude-fixture" }, saved.Claude); Assert.False(saved.PopupAhead); Assert.Equal("0.9", saved.DismissedPluginVersion);
|
||||||
|
Exception? cancellationFailure = null;
|
||||||
|
void CatchCancellation(object? sender, DispatcherUnhandledExceptionEventArgs e)
|
||||||
|
{ cancellationFailure = e.Exception; e.Handled = true; }
|
||||||
|
Dispatcher.UIThread.UnhandledException += CatchCancellation;
|
||||||
|
var cancelled = new SettingsWindow(new(), new(PluginInstallState.NoHostFound), _ => Task.FromException(new OperationCanceledException()));
|
||||||
|
cancelled.Show();
|
||||||
|
cancelled.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Save").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
Dispatcher.UIThread.UnhandledException -= CatchCancellation;
|
||||||
|
Assert.Null(cancellationFailure);
|
||||||
|
Assert.Contains(cancelled.GetVisualDescendants().OfType<TextBlock>(), t => t.Text == "Settings save was cancelled."); cancelled.Close();
|
||||||
|
var opened = 0;
|
||||||
|
var ahead = PopupWindow.Pace(new(Provider.Claude, "session", "Session", PaceState.Ahead, 22, DateTimeOffset.UtcNow.AddHours(1)), () => opened++);
|
||||||
|
ahead.Show(); Save(ahead, "popup-ahead.png"); Assert.False(ahead.ShowActivated);
|
||||||
|
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), () => { });
|
||||||
|
behind.Show(); Save(behind, "popup-behind.png"); behind.Close();
|
||||||
|
var installed = 0; var dismissed = 0;
|
||||||
|
var ask = new PopupWindow("Stream Deck plugin", "Version 1.0 is ready.", () => { }, "Install", () => installed++, () => dismissed++);
|
||||||
|
ask.Show(); Save(ask, "popup-streamdeck-ask.png");
|
||||||
|
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);
|
||||||
|
var install = new PopupWindow("Stream Deck plugin", "Update ready", () => { }, "Update", () => installed++);
|
||||||
|
install.Show(); install.GetVisualDescendants().OfType<Button>().Single(b => b.Content as string == "Update").RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
|
||||||
|
Assert.Equal(1, installed);
|
||||||
|
var popupClock = new PopupClock();
|
||||||
|
using var stack = new PopupStack(() => { }, popupClock);
|
||||||
|
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), () => { });
|
||||||
|
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 chartWindow = new Window { Content = chart, Width = 400, Height = 180 };
|
||||||
|
chartWindow.Show();
|
||||||
|
using (chartWindow.CaptureRenderedFrame()) { }
|
||||||
|
chartWindow.MouseMove(new Point(65, 80));
|
||||||
|
Assert.Contains(123456.ToString("N0"), ToolTip.GetTip(chart)?.ToString()); chartWindow.Close();
|
||||||
|
var polishShots = shots;
|
||||||
|
Directory.CreateDirectory(polishShots);
|
||||||
|
var emptyChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart())), Width = 620, Height = 260,
|
||||||
|
RequestedThemeVariant = ThemeVariant.Light };
|
||||||
|
emptyChart.Show(); Save(emptyChart, "chart-empty.png", polishShots); emptyChart.Close();
|
||||||
|
var time = new DateTimeOffset(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
var smallChart = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per hour", 19), new UsageChart
|
||||||
|
{ Values = [new(time, "Claude", 1), new(time.AddHours(1), "Claude", 2), new(time.AddHours(2), "Claude", 3)] })),
|
||||||
|
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
|
||||||
|
smallChart.Show(); Save(smallChart, "chart-max-3.png", polishShots); smallChart.Close();
|
||||||
|
var day = new DateTimeOffset(2026, 10, 14, 0, 0, 0, TimeSpan.FromHours(2));
|
||||||
|
var daily = new UsageChart { Interval = TimeSpan.FromDays(1), Values = [new(day, "Claude", 3), new(day.AddDays(1), "Claude", 2)] };
|
||||||
|
var dailyWindow = new Window { Content = Ui.Card(Ui.Stack(Ui.Text("Tokens per day", 19), daily)),
|
||||||
|
Width = 620, Height = 260, RequestedThemeVariant = ThemeVariant.Light };
|
||||||
|
dailyWindow.Show(); Save(dailyWindow, "chart-local-day.png");
|
||||||
|
dailyWindow.MouseMove(new Point(90, 150));
|
||||||
|
Assert.Contains(day.DateTime.ToString("g"), ToolTip.GetTip(daily)?.ToString()); dailyWindow.Close();
|
||||||
|
popupClock.Fire(); Dispatcher.UIThread.RunJobs();
|
||||||
|
Assert.False(first.IsVisible); Assert.False(second.IsVisible);
|
||||||
|
Assert.All(popupClock.Timers, timer => Assert.True(timer.Disposed));
|
||||||
|
completion.SetResult();
|
||||||
|
void Save(Window window, string name, string? destination = null)
|
||||||
|
{
|
||||||
|
Dispatcher.UIThread.RunJobs();
|
||||||
|
using var bitmap = window.CaptureRenderedFrame(); Assert.NotNull(bitmap);
|
||||||
|
using var output = File.Create(Path.Combine(destination ?? shots, name)); bitmap.Save(output, PngBitmapEncoderOptions.Default);
|
||||||
|
Assert.True(output.Length > 2000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception e) { completion.SetException(e); }
|
||||||
|
});
|
||||||
|
if (OperatingSystem.IsWindows()) thread.SetApartmentState(ApartmentState.STA);
|
||||||
|
thread.Start(); await completion.Task; thread.Join();
|
||||||
|
}
|
||||||
|
public sealed class TestApplication : Application
|
||||||
|
{ public override void Initialize() => Styles.Add(new FluentTheme()); }
|
||||||
|
private sealed class PopupClock : TimeProvider
|
||||||
|
{
|
||||||
|
public List<PopupTimer> Timers { get; } = [];
|
||||||
|
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||||
|
{
|
||||||
|
Assert.Equal(TimeSpan.FromSeconds(8), dueTime);
|
||||||
|
Assert.Equal(Timeout.InfiniteTimeSpan, period);
|
||||||
|
var timer = new PopupTimer(callback, state); Timers.Add(timer); return timer;
|
||||||
|
}
|
||||||
|
public void Fire() { foreach (var timer in Timers.Where(t => !t.Disposed)) timer.Fire(); }
|
||||||
|
}
|
||||||
|
private sealed class PopupTimer(TimerCallback callback, object? state) : ITimer
|
||||||
|
{
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
public void Fire() => callback(state);
|
||||||
|
public bool Change(TimeSpan dueTime, TimeSpan period) => throw new NotSupportedException();
|
||||||
|
public void Dispose() => Disposed = true;
|
||||||
|
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
using FinalToken.Core;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.App.Tests;
|
||||||
|
|
||||||
|
public sealed class ViewModelTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData(HistoryRange.Hours24, 1)]
|
||||||
|
[InlineData(HistoryRange.Days7, 7)]
|
||||||
|
[InlineData(HistoryRange.Days30, 30)]
|
||||||
|
[InlineData(HistoryRange.Days90, 90)]
|
||||||
|
public void RangeUsesRequestedDuration(HistoryRange range, int days)
|
||||||
|
{ var now = DateTimeOffset.UtcNow; Assert.Equal(now.AddDays(-days), PanelViewModel.RangeStart(range, now)); }
|
||||||
|
[Fact] public void AllRangeIncludesOldHistory() => Assert.Equal(DateTimeOffset.MinValue, PanelViewModel.RangeStart(HistoryRange.All, DateTimeOffset.UtcNow));
|
||||||
|
[Fact] public void UnknownSessionIsNotDisplayedAsZero() => Assert.Contains("Unavailable", Display.Tokens(null));
|
||||||
|
[Fact] public void PropertiesNotify()
|
||||||
|
{
|
||||||
|
var vm = new PanelViewModel(); var notified = new List<string?>(); vm.PropertyChanged += (_, e) => notified.Add(e.PropertyName);
|
||||||
|
vm.ProviderFilter = Provider.Codex; vm.Range = HistoryRange.Days30;
|
||||||
|
Assert.Contains(nameof(vm.ProviderFilter), notified); Assert.Contains(nameof(vm.Range), notified);
|
||||||
|
}
|
||||||
|
[Fact] public void HistoryFiltersProvidersAndGroupsModelsWithoutDoubleCounting()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-app-tests", Guid.NewGuid().ToString("N"));
|
||||||
|
var store = new HistoryStore(directory, new DiagnosticLog()); var now = DateTimeOffset.UtcNow;
|
||||||
|
store.Add(new(Provider.Claude, now.AddHours(-2), "a", "project", new(Total: 30), "1"));
|
||||||
|
store.Add(new(Provider.Claude, now.AddHours(-2), "b", "project", new(Total: 70), "2"));
|
||||||
|
store.Add(new(Provider.Codex, now.AddHours(-2), "b", "other", new(Total: 100), "3"));
|
||||||
|
var snapshot = FakeData.Snapshot(now);
|
||||||
|
var all = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, null, now);
|
||||||
|
Assert.Equal(200, all.Hourly.Sum(p => p.Value)); Assert.Equal(200, all.Daily.Sum(p => p.Value));
|
||||||
|
Assert.Equal(1, all.Models.Sum(m => m.Share), 6);
|
||||||
|
var filtered = PanelViewModel.QueryHistory(store, snapshot, HistoryRange.Days7, Provider.Claude, now);
|
||||||
|
Assert.Equal(100, filtered.Hourly.Sum(p => p.Value)); Assert.Equal(2, filtered.Hourly.Count);
|
||||||
|
Assert.Single(filtered.Projects); Assert.Equal(1, filtered.Projects[0].Share);
|
||||||
|
}
|
||||||
|
[Fact] public void EmptyHistoryHasNoInventedData()
|
||||||
|
{
|
||||||
|
var store = new HistoryStore(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")), new DiagnosticLog());
|
||||||
|
var history = PanelViewModel.QueryHistory(store, FakeData.Snapshot(DateTimeOffset.UtcNow), HistoryRange.All, null, DateTimeOffset.UtcNow);
|
||||||
|
Assert.Empty(history.Hourly); Assert.Empty(history.Models); Assert.Empty(history.Projects);
|
||||||
|
}
|
||||||
|
[Fact] public void SelectedProviderDailySeriesRespectsPartialDays()
|
||||||
|
{
|
||||||
|
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());
|
||||||
|
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(-3), "inside", "p", new(Total: 50), "today"));
|
||||||
|
var view = PanelViewModel.QueryHistory(store, FakeData.Snapshot(now), HistoryRange.Hours24, Provider.Claude, now);
|
||||||
|
Assert.Equal(150, view.Hourly.Sum(v => v.Value));
|
||||||
|
Assert.Equal(150, view.Daily.Sum(v => v.Value));
|
||||||
|
Assert.DoesNotContain(view.Daily, v => v.Series == "outside");
|
||||||
|
}
|
||||||
|
[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); }
|
||||||
|
[Fact] public void DesktopEntryRejectsInjectedLine() => Assert.Throws<ArgumentException>(() => OsStartup.DesktopEntry("/app\nExec=other"));
|
||||||
|
[Fact] public void DesktopEntryEscapesCommandCharactersAtBothParsingLevels()
|
||||||
|
{
|
||||||
|
var entry = OsStartup.DesktopEntry("/opt/a\"$`\\file");
|
||||||
|
Assert.Contains("a\\\\\"\\\\$\\\\`\\\\\\\\file", entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class FakeData
|
||||||
|
{
|
||||||
|
public static Snapshot Snapshot(DateTimeOffset now, bool unavailable = false) => new()
|
||||||
|
{
|
||||||
|
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(12000, 18000, 2000, 4200, 0, 36200), new(4000, 6000, 1000, 1600, 0, 12600), new(85000, 92000, 16000, 28000, 0, 221000)),
|
||||||
|
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)],
|
||||||
|
new(72000, 42000, 0, 8400, 2100, 80400), new(23000, 10000, 0, 3200, 700, 26200), new(340000, 150000, 0, 38000, 11000, 378000))]
|
||||||
|
};
|
||||||
|
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)); }
|
||||||
|
public static PanelViewModel Model(bool unavailable = false)
|
||||||
|
{
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
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 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();
|
||||||
|
return new() { Snapshot = Snapshot(now, unavailable), Message = "Updated just now · local CLI data", History = new(hourly, daily,
|
||||||
|
[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)]),
|
||||||
|
Diagnostics = [new(now.AddMinutes(-4), Provider.Claude, "sample-age", "Latest limit sample is three minutes old.")] };
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Cli tests
|
||||||
|
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||||
|
Run `dotnet test --project tests/FinalToken.Cli.Tests -c Release` from the root.
|
||||||
|
Cover behavior and failure boundaries, not implementation details.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
using FinalToken.Cli;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Cli.Tests;
|
||||||
|
|
||||||
|
public class CliTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task UnexpectedRefreshFailureReturnsOneWithoutExceptionText()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var output = new StringWriter(); using var error = new StringWriter();
|
||||||
|
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory,
|
||||||
|
_ => throw new System.Text.Json.JsonException("synthetic private input"), TestContext.Current.CancellationToken));
|
||||||
|
Assert.Contains("could not complete", error.ToString()); Assert.DoesNotContain("synthetic private", error.ToString());
|
||||||
|
}
|
||||||
|
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("")]
|
||||||
|
[InlineData("unknown")]
|
||||||
|
[InlineData("status --unknown")]
|
||||||
|
[InlineData("status --json --json")]
|
||||||
|
public async Task InvalidUsageExitsTwo(string command)
|
||||||
|
{
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
Assert.Equal(2, await CliApplication.RunAsync(command.Split(' ', StringSplitOptions.RemoveEmptyEntries), output, error, cancellationToken: TestContext.Current.CancellationToken));
|
||||||
|
Assert.Contains("Usage: finaltoken-cli status", error.ToString());
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task BusyStoreReadsExistingSnapshotAndDoesNotRefresh()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var storeLock = StoreLock.TryAcquire(directory);
|
||||||
|
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] }, TestContext.Current.CancellationToken);
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
Assert.Equal(0, await CliApplication.RunAsync(["status", "--json"], output, error, directory,
|
||||||
|
_ => throw new InvalidOperationException("Must not create a writing engine."), TestContext.Current.CancellationToken));
|
||||||
|
Assert.Contains("\"v\":1", output.ToString());
|
||||||
|
Assert.Contains("Store is in use", error.ToString());
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task StatusNoProbeWritesSnapshotAndText()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
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));
|
||||||
|
Assert.Contains("Tokens today: 0", output.ToString());
|
||||||
|
Assert.NotNull(SnapshotFile.Read(directory).Snapshot);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task BusyStoreWithoutSnapshotExitsOne()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var storeLock = StoreLock.TryAcquire(directory);
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
Assert.Equal(1, await CliApplication.RunAsync(["status"], output, error, directory, cancellationToken: TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task PrintsFoldedDiagnosticCountAndLastTime()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
var result = await CliApplication.RunAsync(["status", "--no-probe"], output, error, directory, path =>
|
||||||
|
{
|
||||||
|
var engine = new RefreshEngine(path, claudeDirectory: path, codexDirectory: path,
|
||||||
|
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
|
||||||
|
for (var i = 0; i < 20; i++) engine.Diagnostics.Add(Provider.Claude, "fixture-parse", "Malformed usage.");
|
||||||
|
return engine;
|
||||||
|
}, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(0, result);
|
||||||
|
Assert.Contains("fixture-parse (x20, last ", error.ToString());
|
||||||
|
Assert.Equal(1, error.ToString().Split('\n').Count(line => line.StartsWith("fixture-parse", StringComparison.Ordinal)));
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task StatusKeepsExistingDesktopPath()
|
||||||
|
{
|
||||||
|
var directory = Path.Combine(Path.GetTempPath(), "finaltoken-cli-" + Guid.NewGuid().ToString("N"));
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await SnapshotFile.WriteAsync(directory, new Snapshot { MadeAt = DateTimeOffset.UtcNow,
|
||||||
|
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [], AppPath = "desktop.exe" }, TestContext.Current.CancellationToken);
|
||||||
|
using var output = new StringWriter();
|
||||||
|
using var error = new StringWriter();
|
||||||
|
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));
|
||||||
|
Assert.Equal("desktop.exe", SnapshotFile.Read(directory).Snapshot!.AppPath);
|
||||||
|
}
|
||||||
|
finally { Directory.Delete(directory, true); }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<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.Cli/FinalToken.Cli.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Core tests
|
||||||
|
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||||
|
Run `dotnet test --project tests/FinalToken.Core.Tests -c Release` from the root.
|
||||||
|
Cover behavior and failure boundaries, not implementation details.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using FinalToken.Core.StreamDeck;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class DiscoveryAndPolicyTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public void WindowsClaudeNpmShimResolvesInstalledNativeBinary()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
|
||||||
|
var binary = directory.Write("node_modules/@anthropic-ai/claude-code/bin/claude.exe", "fixture native");
|
||||||
|
Assert.Equal(binary, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command?.FileName);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void WindowsClaudeNpmShimFallsBackToLegacyCliScriptWithoutShell()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory(); directory.Write("claude.cmd", "fixture");
|
||||||
|
var script = directory.Write("node_modules/@anthropic-ai/claude-code/cli.js", "fixture script");
|
||||||
|
var node = directory.Write("node.exe", "fixture node");
|
||||||
|
var command = CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command;
|
||||||
|
Assert.NotNull(command); Assert.Equal(node, command.FileName); Assert.Equal([script], command.PrefixArguments);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void FindsNativeWindowsAndHonorsOverride()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("claude.exe", "fixture");
|
||||||
|
Assert.Equal(path, CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command!.FileName);
|
||||||
|
Assert.Null(CliDiscovery.Find(Provider.Claude, Path.Combine(directory.Path, "missing.exe"), windows: true).Command);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ResolvesWindowsCodexNpmNativeBinaryWithoutShell()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("codex.cmd", "fixture");
|
||||||
|
var binary = directory.Write("node_modules/@openai/codex/node_modules/@openai/codex-win32-x64/vendor/x86_64-pc-windows-msvc/bin/codex.exe", "fixture");
|
||||||
|
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command!.FileName);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ResolvesWindowsNpmNodeFallback()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("codex.cmd", "fixture");
|
||||||
|
var script = directory.Write("node_modules/@openai/codex/bin/codex.js", "fixture");
|
||||||
|
var node = directory.Write("node.exe", "fixture");
|
||||||
|
var command = CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command;
|
||||||
|
Assert.NotNull(command);
|
||||||
|
Assert.Equal(node, command.FileName);
|
||||||
|
Assert.Equal(script, Assert.Single(command.PrefixArguments));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void LinuxNativeAndNodeShebangWork()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var binary = directory.Write("codex", "ELF fixture");
|
||||||
|
Assert.Equal(binary, CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command!.FileName);
|
||||||
|
directory.Write("codex", "#!/usr/bin/env node\nfixture");
|
||||||
|
var node = directory.Write("node", "fixture");
|
||||||
|
var command = CliDiscovery.Find(Provider.Codex, overridePath: binary, searchPath: directory.Path, windows: false).Command;
|
||||||
|
Assert.Equal(node, command!.FileName);
|
||||||
|
Assert.Equal(binary, Assert.Single(command.PrefixArguments));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void MissingCliAndUnsupportedWrapperAreUnavailable()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
Assert.Null(CliDiscovery.Find(Provider.Claude, searchPath: directory.Path, windows: true).Command);
|
||||||
|
directory.Write("codex.cmd", "fixture");
|
||||||
|
Assert.Null(CliDiscovery.Find(Provider.Codex, searchPath: directory.Path, windows: true).Command);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void InvalidOverrideBecomesUnavailableInsteadOfStoppingRefresh()
|
||||||
|
{
|
||||||
|
Assert.Null(CliDiscovery.Find(Provider.Claude, "invalid\0path", windows: true).Command);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(InstallMode.Off, PluginInstallState.NotInstalled, InstallAction.Nothing)]
|
||||||
|
[InlineData(InstallMode.Ask, PluginInstallState.NotInstalled, InstallAction.Ask)]
|
||||||
|
[InlineData(InstallMode.Automatic, PluginInstallState.Outdated, InstallAction.Install)]
|
||||||
|
[InlineData(InstallMode.Automatic, PluginInstallState.NoHostFound, InstallAction.Nothing)]
|
||||||
|
[InlineData(InstallMode.Automatic, PluginInstallState.NoShippedPlugin, InstallAction.Nothing)]
|
||||||
|
[InlineData(InstallMode.Automatic, PluginInstallState.UpToDate, InstallAction.Nothing)]
|
||||||
|
public void InstallPolicyHonorsModeAndStatus(InstallMode mode, PluginInstallState state, InstallAction expected) =>
|
||||||
|
Assert.Equal(expected, InstallPolicy.Decide(mode, new(state, "1.0", "0.9"), null));
|
||||||
|
[Fact] public void AskHonorsDismissedVersion() => Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1.0"), "1.0"));
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class EngineTests
|
||||||
|
{
|
||||||
|
private static RefreshEngine Engine(TestDirectory directory, TestClock clock, FakeRunner runner) =>
|
||||||
|
new(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"),
|
||||||
|
(_, _) => new(new("fixture.exe", []), null));
|
||||||
|
[Fact]
|
||||||
|
public async Task SchedulerDebouncesChangesAndRunsPeriodicScansWithoutOverprobing()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
var snapshots = 0;
|
||||||
|
engine.SnapshotChanged += _ => snapshots++;
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(2, runner.Requests.Count);
|
||||||
|
engine.NotifySourceChanged();
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(1));
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, snapshots);
|
||||||
|
engine.NotifySourceChanged();
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(1));
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, snapshots);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(1));
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(2, snapshots);
|
||||||
|
Assert.Equal(2, runner.Requests.Count);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(1));
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(3, snapshots);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(4));
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(4, runner.Requests.Count);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task TokensTriggerProbeWithOneMinuteThrottlePerProvider()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
var path = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(30));
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(2, runner.Requests.Count);
|
||||||
|
await File.AppendAllTextAsync(path, Fixtures.Claude("b"), TestContext.Current.CancellationToken);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(30));
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(3, runner.Requests.Count);
|
||||||
|
Assert.False(runner.Requests[^1].CodexRpc);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ThrottledTokenProbeRemainsPendingWithoutAnotherTokenEvent()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(30));
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(2, runner.Requests.Count);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(30));
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(3, runner.Requests.Count);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task FailedProbeKeepsLastGoodSampleWithItsAge()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
var original = engine.CurrentSnapshot!.Providers[0].Windows[0].Window;
|
||||||
|
runner.Handler = (_, _) => Task.FromResult(new ProcessResult(-1, "", TimedOut: true));
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(original, snapshot.Providers[0].Windows[0].Window);
|
||||||
|
Assert.Equal(TimeSpan.FromMinutes(5), snapshot.Providers[0].Windows[0].Age(clock.GetUtcNow()));
|
||||||
|
Assert.Equal(ProviderStatus.Unavailable, snapshot.Providers[0].Status);
|
||||||
|
Assert.Contains(engine.RecentDiagnostics, d => d.Code == "probe-timeout");
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task StopCancelsAndWaitsForRunningProbe()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var started = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
var stopped = false;
|
||||||
|
var runner = new FakeRunner { Handler = async (_, token) =>
|
||||||
|
{
|
||||||
|
started.SetResult();
|
||||||
|
try { await Task.Delay(Timeout.InfiniteTimeSpan, token); }
|
||||||
|
finally { stopped = true; }
|
||||||
|
return new(0, "");
|
||||||
|
} };
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
await engine.StartAsync(TestContext.Current.CancellationToken);
|
||||||
|
await started.Task.WaitAsync(TestContext.Current.CancellationToken);
|
||||||
|
await engine.StopAsync();
|
||||||
|
Assert.True(stopped);
|
||||||
|
Assert.Null(engine.CurrentSnapshot);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task NoProbeAndDisabledProvidersNeverStartProcesses()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
await using var engine = Engine(directory, clock, runner);
|
||||||
|
await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Empty(runner.Requests);
|
||||||
|
await engine.UpdateSettingsAsync(new Settings { Claude = new() { Enabled = false }, Codex = new() { Enabled = false } }, TestContext.Current.CancellationToken);
|
||||||
|
var snapshot = await engine.RefreshNowAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Empty(runner.Requests);
|
||||||
|
Assert.All(snapshot.Providers, p => Assert.Equal(ProviderStatus.Disabled, p.Status));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ActivationIsRaisedOncePerRequestAndEventsRunOffCallerContext()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
await using var engine = Engine(directory, new(), new());
|
||||||
|
var activations = 0;
|
||||||
|
var context = new SynchronizationContext();
|
||||||
|
var previousContext = SynchronizationContext.Current;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
SynchronizationContext.SetSynchronizationContext(context);
|
||||||
|
engine.ActivationRequested += () => { Assert.NotSame(context, SynchronizationContext.Current); activations++; };
|
||||||
|
await ActivationFile.RequestAsync(directory.Path, TestContext.Current.CancellationToken);
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
await engine.TickAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, activations);
|
||||||
|
}
|
||||||
|
finally { SynchronizationContext.SetSynchronizationContext(previousContext); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ProbeUsesExactClaudeArgumentsWorkingDirectoryAndTimeout()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var runner = new FakeRunner();
|
||||||
|
var probe = new LimitProbe(runner, new(), directory.Path);
|
||||||
|
var result = await probe.RunAsync(Provider.Claude, new("fixture", []), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
|
||||||
|
Assert.True(result.Success);
|
||||||
|
var request = Assert.Single(runner.Requests);
|
||||||
|
Assert.Equal(["-p", "/usage", "--output-format", "json", "--no-session-persistence"], request.Arguments);
|
||||||
|
Assert.Equal(directory.Path, request.WorkingDirectory);
|
||||||
|
Assert.Equal(TimeSpan.FromSeconds(60), request.Timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
<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.Core/FinalToken.Core.csproj" />
|
||||||
|
<ProjectReference Include="../FinalToken.ProcessHost/FinalToken.ProcessHost.csproj" ReferenceOutputAssembly="false" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Target Name="CopyProcessHost" AfterTargets="Build">
|
||||||
|
<ItemGroup>
|
||||||
|
<ProcessHostFiles Include="$(MSBuildThisFileDirectory)../../artifacts/bin/FinalToken.ProcessHost/$(Configuration)/$(TargetFramework)/*" />
|
||||||
|
</ItemGroup>
|
||||||
|
<Copy SourceFiles="@(ProcessHostFiles)" DestinationFolder="$(OutDir)ProcessHost" SkipUnchangedFiles="true" />
|
||||||
|
</Target>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.Text.Json;
|
||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class IntegrationTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task GuiHostProbeReceivesValidStandardHandlesWithoutConsole()
|
||||||
|
=> await RunGuiProbe("--handles-probe");
|
||||||
|
[Fact]
|
||||||
|
public async Task GuiHostDecodesUtf8ProviderJsonWithoutConsoleCodePage()
|
||||||
|
=> await RunGuiProbe("--utf8-probe");
|
||||||
|
private static async Task RunGuiProbe(string mode)
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows()) return;
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var reportPath = Path.Combine(directory.Path, "report.json");
|
||||||
|
using var process = new Process { StartInfo = new()
|
||||||
|
{
|
||||||
|
FileName = Path.Combine(AppContext.BaseDirectory, "ProcessHost", "FinalToken.ProcessHost.exe"),
|
||||||
|
UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = directory.Path
|
||||||
|
} };
|
||||||
|
process.StartInfo.ArgumentList.Add(mode);
|
||||||
|
process.StartInfo.ArgumentList.Add(reportPath);
|
||||||
|
process.Start();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await process.WaitForExitAsync(TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromSeconds(90), TestContext.Current.CancellationToken);
|
||||||
|
using var report = JsonDocument.Parse(File.ReadAllText(reportPath));
|
||||||
|
Assert.False(report.RootElement.GetProperty("HostHasConsole").GetBoolean());
|
||||||
|
Assert.False(report.RootElement.GetProperty("HostInputValid").GetBoolean());
|
||||||
|
Assert.Equal(0, process.ExitCode);
|
||||||
|
}
|
||||||
|
finally { if (!process.HasExited) process.Kill(true); }
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void UsageProseAndContributingSectionAreSilent()
|
||||||
|
{
|
||||||
|
const string text = """
|
||||||
|
You are currently using your subscription to power your Claude Code usage
|
||||||
|
|
||||||
|
Current session: 4% used · resets Oct 14, 11:30pm (Europe/Berlin)
|
||||||
|
Current week (all models): 67% used · resets Oct 18, 8pm (Europe/Berlin)
|
||||||
|
Current week (Fable): 0% used · resets Oct 18, 8pm (Europe/Berlin)
|
||||||
|
|
||||||
|
What's contributing to your limits usage?
|
||||||
|
Usage across Claude Code and Claude contributes to your limits.
|
||||||
|
Sessions and conversations share your subscription allowance.
|
||||||
|
Learn more about how usage is calculated.
|
||||||
|
Current example: this prose is not a limit window
|
||||||
|
""";
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
Assert.Equal(3, ClaudeUsageParser.ParseText(text, new(2026, 10, 14, 18, 0, 0, TimeSpan.Zero), log).Count);
|
||||||
|
Assert.Empty(log.Recent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task MissingSnapshotAppPathDoesNotDefaultToReadersExecutable()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("snapshot.json", """{"v":1,"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}""");
|
||||||
|
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot!.AppPath);
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
|
||||||
|
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
|
||||||
|
Assert.Null((await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task UnspecifiedHostAppPathPreservesExistingDesktopPath()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "desktop.exe", MadeAt = DateTimeOffset.UtcNow,
|
||||||
|
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken);
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
|
||||||
|
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."));
|
||||||
|
Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void DaysFollowLocalCalendarInsteadOfUtcMidnight()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var first = new DateTimeOffset(2026, 10, 14, 23, 0, 0, TimeSpan.Zero);
|
||||||
|
store.Add(new(Provider.Codex, first, "model", "project", new(Total: 10), "one"));
|
||||||
|
store.Add(new(Provider.Codex, first.AddHours(1), "model", "project", new(Total: 20), "two"));
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("Fixture +02", TimeSpan.FromHours(2), "Fixture", "Fixture");
|
||||||
|
var day = Assert.Single(store.TokenSeries(Provider.Codex, first, first.AddHours(2), SeriesInterval.Day, zone));
|
||||||
|
Assert.Equal(30, day.Counts.Total);
|
||||||
|
Assert.Equal(new DateTimeOffset(2026, 10, 15, 0, 0, 0, TimeSpan.FromHours(2)), day.Time);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("2026-03-29", 23)]
|
||||||
|
[InlineData("2026-10-25", 25)]
|
||||||
|
public void LocalDaySeriesIncludesEveryHourAcrossDst(string localDate, int hours)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var zone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Berlin");
|
||||||
|
var date = DateTime.ParseExact(localDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
var start = new DateTimeOffset(date, zone.GetUtcOffset(date));
|
||||||
|
var end = CalendarDays.NextStart(start, zone);
|
||||||
|
Assert.Equal(TimeSpan.FromHours(hours), end - start);
|
||||||
|
for (var i = 0; i < hours; i++)
|
||||||
|
store.Add(new(Provider.Codex, start.AddHours(i), "model", "project", new(Total: 1), "hour-" + i));
|
||||||
|
var day = Assert.Single(store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Day, zone));
|
||||||
|
Assert.Equal(hours, day.Counts.Total);
|
||||||
|
Assert.Equal(start, day.Time);
|
||||||
|
Assert.Equal(hours, store.TokenSeries(Provider.Codex, start, end, SeriesInterval.Hour, zone).Count);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ExplicitDesktopPathOverridesPriorSnapshotPath()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
await SnapshotFile.WriteAsync(directory.Path, new Snapshot { AppPath = "old.exe", MadeAt = DateTimeOffset.UtcNow,
|
||||||
|
RefreshInterval = TimeSpan.FromMinutes(1), Providers = [] }, TestContext.Current.CancellationToken);
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, claudeDirectory: directory.Path, codexDirectory: directory.Path,
|
||||||
|
cliDiscovery: (_, _) => new(null, "Fixture CLI missing."), appPath: "desktop.exe");
|
||||||
|
Assert.Equal("desktop.exe", (await engine.RefreshNowAsync(true, TestContext.Current.CancellationToken)).AppPath);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class PaceTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||||
|
private static LimitWindow Window(double used, double elapsed = 0.5) => new(Provider.Claude, "session", "Session",
|
||||||
|
used, Now + TimeSpan.FromHours(5 * (1 - elapsed)), TimeSpan.FromHours(5), Now, "fixture");
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData(0, 0, PaceState.OnTrack)]
|
||||||
|
[InlineData(0, 0.5, PaceState.Behind)]
|
||||||
|
[InlineData(60, 0.5, PaceState.Ahead)]
|
||||||
|
[InlineData(50, 0.5, PaceState.OnTrack)]
|
||||||
|
[InlineData(10, 0.4, PaceState.OnTrack)]
|
||||||
|
[InlineData(0, 1.2, PaceState.Behind)]
|
||||||
|
public void CalculatesStates(double used, double elapsed, PaceState expected) =>
|
||||||
|
Assert.Equal(expected, Pace.Calculate(Window(used, elapsed), Now).State);
|
||||||
|
[Fact] public void ClampsElapsedAfterReset() => Assert.Equal(1, Pace.Calculate(Window(50, 2), Now).ElapsedFraction);
|
||||||
|
[Fact] public void MissingLengthIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { Length = null }, Now).State);
|
||||||
|
[Fact] public void MissingResetIsUnknown() => Assert.Equal(PaceState.Unknown, Pace.Calculate(Window(40) with { ResetsAt = null }, Now).State);
|
||||||
|
[Fact] public void AheadProjectionPrecedesReset()
|
||||||
|
{
|
||||||
|
var window = Window(80);
|
||||||
|
Assert.Equal(Now.AddMinutes(37.5), Pace.Calculate(window, Now).Projection);
|
||||||
|
Assert.True(Pace.Calculate(window, Now).Projection < window.ResetsAt);
|
||||||
|
}
|
||||||
|
[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 ZeroUsageDoesNotProject() => Assert.Null(Pace.Calculate(Window(0), Now).Projection);
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void PopupHysteresisPreventsFlappingAndRearmsAfterClear()
|
||||||
|
{
|
||||||
|
var machine = new PopupDecider();
|
||||||
|
var settings = new Settings();
|
||||||
|
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(59), Pace.Calculate(Window(59), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(57), Pace.Calculate(Window(57), Now), settings));
|
||||||
|
Assert.NotNull(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void BehindHasHysteresisAndIndependentProviderState()
|
||||||
|
{
|
||||||
|
var machine = new PopupDecider();
|
||||||
|
var settings = new Settings();
|
||||||
|
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(41), Pace.Calculate(Window(41), Now), settings));
|
||||||
|
Assert.NotNull(machine.Observe(Window(40) with { Provider = Provider.Codex }, Pace.Calculate(Window(40), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(43), Pace.Calculate(Window(43), Now), settings));
|
||||||
|
Assert.NotNull(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void PopupHonorsProviderAndStateSettings()
|
||||||
|
{
|
||||||
|
var window = Window(60);
|
||||||
|
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { PopupAhead = false }));
|
||||||
|
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { PopupsEnabled = false } }));
|
||||||
|
Assert.Null(new PopupDecider().Observe(window, Pace.Calculate(window, Now), new Settings { Claude = new() { Enabled = false } }));
|
||||||
|
Assert.Null(new PopupDecider().Observe(Window(40), Pace.Calculate(Window(40), Now), new Settings { PopupBehind = false }));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ProviderStateTogglesDoNotDisableOtherProviders()
|
||||||
|
{
|
||||||
|
var settings = new Settings { Claude = new() { PopupAhead = false, PopupBehind = false } };
|
||||||
|
var machine = new PopupDecider();
|
||||||
|
Assert.Null(machine.Observe(Window(60), Pace.Calculate(Window(60), Now), settings));
|
||||||
|
Assert.Null(machine.Observe(Window(40), Pace.Calculate(Window(40), Now), settings));
|
||||||
|
Assert.NotNull(machine.Observe(Window(60) with { Provider = Provider.Codex }, Pace.Calculate(Window(60), Now), settings));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class ParserTests
|
||||||
|
{
|
||||||
|
private static readonly DateTimeOffset Now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||||
|
[Fact]
|
||||||
|
public void TranscriptReturnsOnlyMetadataAndCorrectCacheTotal()
|
||||||
|
{
|
||||||
|
var usage = TranscriptParser.Parse(Fixtures.Claude(), new());
|
||||||
|
Assert.NotNull(usage);
|
||||||
|
Assert.Equal(new TokenCounts(10, 3, 4, 2, 0, 19), usage.Counts);
|
||||||
|
Assert.Equal("fixture-model", usage.Model);
|
||||||
|
Assert.Equal("/project", usage.Project);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{")]
|
||||||
|
[InlineData("[]")]
|
||||||
|
[InlineData("null")]
|
||||||
|
[InlineData("{\"type\":\"assistant\",\"message\":{\"usage\":{\"input_tokens\":-1}}}")]
|
||||||
|
public void TranscriptMalformedInputDoesNotThrow(string line) => Assert.Null(TranscriptParser.Parse(line, new()));
|
||||||
|
[Fact]
|
||||||
|
public void TranscriptMalformedUsageReportsDiagnostic()
|
||||||
|
{
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
Assert.Null(TranscriptParser.Parse(Fixtures.Claude().Replace("\"input_tokens\":10", "\"input_tokens\":-1"), diagnostics));
|
||||||
|
Assert.Single(diagnostics.Recent);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)", 5, 17, 30)]
|
||||||
|
[InlineData("Current week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)", 168, 18, 0)]
|
||||||
|
[InlineData("Current week (Fable): 0% used • resets Oct 18, 8:00pm (Europe/Berlin)", 168, 18, 0)]
|
||||||
|
public void ClaudeUsageParsesKnownFormatsAndIanaZone(string line, int hours, int resetHour, int resetMinute)
|
||||||
|
{
|
||||||
|
var window = Assert.Single(ClaudeUsageParser.ParseText(line, Now, new()));
|
||||||
|
Assert.Equal(TimeSpan.FromHours(hours), window.Length);
|
||||||
|
Assert.Equal(resetHour, window.ResetsAt!.Value.Hour);
|
||||||
|
Assert.Equal(resetMinute, window.ResetsAt.Value.Minute);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ClaudeInfersNewYearWithinWindow()
|
||||||
|
{
|
||||||
|
var windows = ClaudeUsageParser.ParseText("Current week (all models): 10% used · resets Jan 2, 8pm (Europe/Berlin)",
|
||||||
|
new(2026, 12, 31, 16, 0, 0, TimeSpan.Zero), new());
|
||||||
|
Assert.Equal(2027, Assert.Single(windows).ResetsAt!.Value.Year);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Current session: 101% used · resets Oct 14, 7:30pm (Europe/Berlin)")]
|
||||||
|
[InlineData("Current session: 10% used · resets Oct 14, 7:30pm (Unknown/Zone)")]
|
||||||
|
[InlineData("Current session: 10% used · resets Oct 18, 8pm (Europe/Berlin)")]
|
||||||
|
[InlineData("Current session: 10% used · resets Oct 14, 3pm (Europe/Berlin)")]
|
||||||
|
[InlineData("Current session: unknown format")]
|
||||||
|
public void ClaudeUnknownFormatsBecomeDiagnostics(string line)
|
||||||
|
{
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
Assert.Empty(ClaudeUsageParser.ParseText(line, Now, diagnostics));
|
||||||
|
Assert.Single(diagnostics.Recent);
|
||||||
|
}
|
||||||
|
[Fact] public void ClaudeEnvelopeIsLocalAndZeroTurns() => Assert.Equal(2, ClaudeUsageParser.ParseEnvelope(Fixtures.ClaudeEnvelope, Now, new()).Count);
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{")]
|
||||||
|
[InlineData("{\"is_error\":true}")]
|
||||||
|
[InlineData("{\"local_command\":\"usage\",\"num_turns\":1,\"is_error\":false,\"result\":\"x\"}")]
|
||||||
|
public void ClaudeRejectsInvalidEnvelope(string json) => Assert.Empty(ClaudeUsageParser.ParseEnvelope(json, Now, new()));
|
||||||
|
[Fact]
|
||||||
|
public void RolloutTracksModelAndProjectAndCumulativeCounts()
|
||||||
|
{
|
||||||
|
var cursor = new ScanCursor();
|
||||||
|
foreach (var line in Fixtures.Meta.Split('\n', StringSplitOptions.RemoveEmptyEntries)) RolloutParser.Parse(line, cursor, Now, new());
|
||||||
|
var entry = RolloutParser.Parse(Fixtures.Codex(10), cursor, Now, new());
|
||||||
|
Assert.Equal("session-1", cursor.SessionId);
|
||||||
|
Assert.Equal("fixture-model", entry.CumulativeUsage!.Model);
|
||||||
|
Assert.Equal(12, entry.CumulativeUsage.Counts.Total);
|
||||||
|
Assert.Equal("codex:primary", Assert.Single(entry.Limits).Id);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{")]
|
||||||
|
[InlineData("null")]
|
||||||
|
[InlineData("[]")]
|
||||||
|
[InlineData("{\"type\":\"event_msg\",\"payload\":{\"type\":\"token_count\"}}")]
|
||||||
|
public void RolloutMalformedInputIsTotal(string line) => Assert.Null(RolloutParser.Parse(line, new(), Now, new()).CumulativeUsage);
|
||||||
|
[Fact]
|
||||||
|
public void CodexReadsSchemaCamelCaseResponse()
|
||||||
|
{
|
||||||
|
var window = Assert.Single(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse, Now, new()));
|
||||||
|
Assert.Equal(24, window.UsedPercent);
|
||||||
|
Assert.Equal(TimeSpan.FromDays(7), window.Length);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void CodexReadsMultipleBuckets()
|
||||||
|
{
|
||||||
|
var json = "{\"result\":{\"rateLimitsByLimitId\":{\"a\":{\"limitId\":\"a\",\"primary\":{\"usedPercent\":1}},\"b\":{\"limitId\":\"b\",\"secondary\":{\"usedPercent\":2}}}}}";
|
||||||
|
var windows = CodexLimitsParser.ParseResponse(json, Now, new());
|
||||||
|
Assert.Equal(2, windows.Count);
|
||||||
|
Assert.All(windows, w => Assert.Null(w.Length));
|
||||||
|
}
|
||||||
|
[Fact] public void CodexRejectsInvalidWindow() => Assert.Empty(CodexLimitsParser.ParseResponse(Fixtures.CodexResponse.Replace("\"usedPercent\":24", "\"usedPercent\":-1"), Now, new()));
|
||||||
|
[Fact] public void DiagnosticsAreBoundedAndExcludeInput()
|
||||||
|
{
|
||||||
|
var diagnostics = new DiagnosticLog(capacity: 2);
|
||||||
|
for (var i = 0; i < 4; i++) TranscriptParser.Parse("private fixture text", diagnostics);
|
||||||
|
Assert.Equal(4, Assert.Single(diagnostics.Recent).Count);
|
||||||
|
Assert.All(diagnostics.Recent, d => Assert.DoesNotContain("private fixture", d.Summary));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class PartialSettingsTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{}")]
|
||||||
|
[InlineData("{\"refreshInterval\":\"00:00:30\"}")]
|
||||||
|
[InlineData("{\"claude\":{\"enabled\":false},\"codex\":{\"cliPath\":\"fixture\"}}")]
|
||||||
|
[InlineData("{\"claude\":{},\"codex\":{\"popupBehind\":false}}")]
|
||||||
|
[InlineData("{\"refreshInterval\":\"00:00:30\",\"future\":123,\"claude\":{\"popupAhead\":false,\"future\":{}}}")]
|
||||||
|
public void PartialFilesKeepValuesAndDefaultAbsentProperties(string json)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("settings.json", json);
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
var settings = SettingsFile.Load(directory.Path, diagnostics);
|
||||||
|
var expected = new Settings();
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
if (doc.RootElement.TryGetProperty("refreshInterval", out _)) expected = expected with { RefreshInterval = TimeSpan.FromSeconds(30) };
|
||||||
|
if (json.Contains("\"enabled\":false")) expected = expected with { Claude = expected.Claude with { Enabled = false } };
|
||||||
|
if (json.Contains("\"cliPath\"")) expected = expected with { Codex = expected.Codex with { CliPath = "fixture" } };
|
||||||
|
if (json.Contains("\"popupAhead\":false")) expected = expected with { Claude = expected.Claude with { PopupAhead = false } };
|
||||||
|
if (json.Contains("\"popupBehind\":false")) expected = expected with { Codex = expected.Codex with { PopupBehind = false } };
|
||||||
|
Assert.Equal(expected, settings);
|
||||||
|
Assert.Empty(diagnostics.Recent);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("\"Automatic\"", InstallMode.Automatic)]
|
||||||
|
[InlineData("\"Ask\"", InstallMode.Ask)]
|
||||||
|
[InlineData("\"Off\"", InstallMode.Off)]
|
||||||
|
[InlineData("2", InstallMode.Automatic)]
|
||||||
|
public void InstallModeAcceptsNamesAndExistingNumericFiles(string value, InstallMode expected)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("settings.json", "{\"streamDeckInstallMode\":" + value + "}");
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
Assert.Equal(new Settings { StreamDeckInstallMode = expected }, SettingsFile.Load(directory.Path, diagnostics));
|
||||||
|
Assert.Empty(diagnostics.Recent);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("\"probeInterval\":\"00:00:10\"")]
|
||||||
|
[InlineData("\"paceThreshold\":0")]
|
||||||
|
[InlineData("\"probeInterval\":\"invalid\"")]
|
||||||
|
[InlineData("\"streamDeckInstallMode\":99")]
|
||||||
|
[InlineData("\"streamDeckInstallMode\":\"Unknown\"")]
|
||||||
|
[InlineData("\"claude\":null")]
|
||||||
|
[InlineData("\"codex\":{\"enabled\":\"invalid\"}")]
|
||||||
|
public void OneInvalidPropertyStillFallsBackForWholeFile(string invalid)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("settings.json", "{\"refreshInterval\":\"00:00:30\"," + invalid + "}");
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, diagnostics));
|
||||||
|
Assert.Equal("settings-defaults", Assert.Single(diagnostics.Recent).Code);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void SnapshotKeepsOptionalVersionInitializer()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("snapshot.json", """{"madeAt":"2026-10-14T16:00:00Z","refreshInterval":"00:01:00","providers":[]}""");
|
||||||
|
var snapshot = SnapshotFile.Read(directory.Path).Snapshot;
|
||||||
|
Assert.NotNull(snapshot); Assert.Equal(1, snapshot.V); Assert.Null(snapshot.AppPath);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{\"v\":1,\"refreshInterval\":\"00:01:00\",\"providers\":[]}")]
|
||||||
|
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"providers\":[]}")]
|
||||||
|
[InlineData("{\"v\":1,\"madeAt\":\"2026-10-14T16:00:00Z\",\"refreshInterval\":\"00:01:00\"}")]
|
||||||
|
public void SnapshotStillRejectsMissingRequiredFields(string json)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("snapshot.json", json);
|
||||||
|
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void HistoryTypesKeepDefaultsForAbsentProperties()
|
||||||
|
{
|
||||||
|
var state = JsonSerializer.Deserialize("{\"sequence\":2}", CoreJsonContext.Default.HistoryState)!;
|
||||||
|
Assert.Equal(1, state.V); Assert.Equal(2, state.Sequence);
|
||||||
|
Assert.Empty(state.ClaudeKeys); Assert.Empty(state.CodexTotals); Assert.Empty(state.CodexTimes);
|
||||||
|
Assert.Empty(state.Cursors); Assert.Empty(state.LatestWindows); Assert.Empty(state.LastSamples);
|
||||||
|
var partition = JsonSerializer.Deserialize("{}", CoreJsonContext.Default.HistoryPartition)!;
|
||||||
|
Assert.Equal(1, partition.V); Assert.Empty(partition.Buckets); Assert.Empty(partition.Limits);
|
||||||
|
var transaction = JsonSerializer.Deserialize("{\"sequence\":3}", CoreJsonContext.Default.HistoryTransaction)!;
|
||||||
|
Assert.Equal(1, transaction.V); Assert.Equal(3, transaction.Sequence);
|
||||||
|
Assert.Empty(transaction.Buckets); Assert.Empty(transaction.Limits); Assert.Empty(transaction.ClaudeKeys);
|
||||||
|
Assert.Empty(transaction.ExpiredClaudeKeys); Assert.Empty(transaction.CodexTotals); Assert.Empty(transaction.CodexTimes);
|
||||||
|
Assert.Empty(transaction.Cursors); Assert.Empty(transaction.LatestWindows); Assert.Empty(transaction.LastSamples);
|
||||||
|
state = JsonSerializer.Deserialize("{\"cursors\":{\"fixture\":{\"model\":\"fixture\"}}}", CoreJsonContext.Default.HistoryState)!;
|
||||||
|
Assert.Equal(-1, state.Cursors["fixture"].ObservedLength); Assert.Equal("", state.Cursors["fixture"].PrefixHash);
|
||||||
|
Assert.Empty(state.Cursors["fixture"].LatestLimits);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class ProcessTests
|
||||||
|
{
|
||||||
|
private static ProcessRequest LongProcess(string directory) => OperatingSystem.IsWindows()
|
||||||
|
? new(new(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "ping.exe"), []), ["-n", "30", "127.0.0.1"], directory, TimeSpan.FromSeconds(60))
|
||||||
|
: new(new("sleep", []), ["30"], directory, TimeSpan.FromSeconds(60));
|
||||||
|
[Fact]
|
||||||
|
public async Task FakeClockTimeoutTerminatesChild()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var task = new ProcessRunner(clock).RunAsync(LongProcess(directory.Path), TestContext.Current.CancellationToken);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(61));
|
||||||
|
Assert.True((await task).TimedOut);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CancellationTerminatesAndWaitsForChild()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using var cancelled = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
var task = new ProcessRunner().RunAsync(LongProcess(directory.Path), cancelled.Token);
|
||||||
|
await cancelled.CancelAsync();
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => task);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CaptureIsBoundedWithoutBlockingTheChild()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var result = await new ProcessRunner().RunAsync(new(new("dotnet", []), ["--info"], directory.Path,
|
||||||
|
TimeSpan.FromSeconds(60), OutputLimit: 50), TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(0, result.ExitCode);
|
||||||
|
Assert.Equal(50, result.Output.Length);
|
||||||
|
Assert.True(result.OutputTruncated);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Threading.Channels;
|
||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class ReviewRegressionTests
|
||||||
|
{
|
||||||
|
private static CliCommand Child(string mode) => new(Path.Combine(AppContext.BaseDirectory, "ProcessHost",
|
||||||
|
OperatingSystem.IsWindows() ? "FinalToken.ProcessHost.exe" : "FinalToken.ProcessHost"), [mode]);
|
||||||
|
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--rpc-success", true)]
|
||||||
|
[InlineData("--rpc-error", false)]
|
||||||
|
[InlineData("--rpc-init-error", false)]
|
||||||
|
[InlineData("--rpc-eof", false)]
|
||||||
|
[InlineData("--rpc-garbage", false)]
|
||||||
|
[InlineData("--rpc-shape", false)]
|
||||||
|
[InlineData("--rpc-bound", false)]
|
||||||
|
public async Task RpcChildFailuresBecomeFailedProbes(string mode, bool success)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
var probe = new LimitProbe(new ProcessRunner(), log, directory.Path);
|
||||||
|
var result = await probe.RunAsync(Provider.Codex, Child(mode), new TestClock().GetUtcNow(), TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(success, result.Success);
|
||||||
|
if (!success) { Assert.Empty(result.Windows); Assert.NotNull(result.Reason); Assert.NotEmpty(log.Recent); }
|
||||||
|
else Assert.Single(result.Windows);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("--rpc-error", false)]
|
||||||
|
[InlineData("--rpc-eof", false)]
|
||||||
|
[InlineData("--rpc-garbage", false)]
|
||||||
|
[InlineData("--rpc-error", true)]
|
||||||
|
public async Task EngineKeepsUpdatingClaudeWhenCodexFails(string mode, bool fallback)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var runner = new FakeRunner { Handler = (request, token) => request.CodexRpc
|
||||||
|
? new ProcessRunner().RunAsync(request, token) : Task.FromResult(new ProcessResult(0, Fixtures.ClaudeEnvelope)) };
|
||||||
|
if (fallback) directory.Write("codex/sessions/rollout-fixture.jsonl", Fixtures.Meta + Fixtures.Codex(10));
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, clock, runner, Path.Combine(directory.Path, "claude"),
|
||||||
|
Path.Combine(directory.Path, "codex"), (provider, _) => new(provider == Provider.Codex ? Child(mode) : new("fixture", []), null));
|
||||||
|
var snapshots = Channel.CreateUnbounded<Snapshot>(); engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
await engine.StartAsync(deadline.Token);
|
||||||
|
var initial = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
var first = initial.Providers.Single(p => p.Provider == Provider.Claude).Windows[0].Window.SampleTime;
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
var snapshot = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
var claude = snapshot.Providers.Single(p => p.Provider == Provider.Claude);
|
||||||
|
Assert.Equal(ProviderStatus.Available, claude.Status); Assert.True(claude.Windows[0].Window.SampleTime > first);
|
||||||
|
var codex = snapshot.Providers.Single(p => p.Provider == Provider.Codex);
|
||||||
|
Assert.Equal(fallback ? ProviderStatus.Available : ProviderStatus.Unavailable, codex.Status);
|
||||||
|
if (fallback) Assert.Contains("rollout", codex.Reason); else Assert.Empty(codex.Windows);
|
||||||
|
await engine.StopAsync();
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task BackgroundLoopRecoversAfterCorruptMonthAndStopsCleanly()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var bad = directory.Write("history/2026-10.json", "{");
|
||||||
|
var clock = new TestClock();
|
||||||
|
await using var engine = new RefreshEngine(directory.Path, clock, new FakeRunner(), directory.Path, directory.Path, (_, _) => new(new("fixture", []), null));
|
||||||
|
var snapshots = Channel.CreateUnbounded<Snapshot>();
|
||||||
|
engine.SnapshotChanged += value => snapshots.Writer.TryWrite(value);
|
||||||
|
await engine.StartAsync(TestContext.Current.CancellationToken);
|
||||||
|
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||||
|
deadline.CancelAfter(TimeSpan.FromSeconds(15));
|
||||||
|
while (!engine.RecentDiagnostics.Any(d => d.Code == "refresh-failed")) await Task.Delay(10, deadline.Token);
|
||||||
|
await File.WriteAllTextAsync(bad, "{\"v\":1,\"buckets\":[],\"limits\":[]}", deadline.Token);
|
||||||
|
clock.Advance(TimeSpan.FromSeconds(1));
|
||||||
|
var first = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(5));
|
||||||
|
var second = await snapshots.Reader.ReadAsync(deadline.Token);
|
||||||
|
Assert.True(second.MadeAt > first.MadeAt);
|
||||||
|
await engine.StopAsync();
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ProbeDoesNotSwallowShutdownCancellation()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using var stop = new CancellationTokenSource(); stop.Cancel();
|
||||||
|
var runner = new FakeRunner { Handler = (_, token) => Task.FromCanceled<ProcessResult>(token) };
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
|
||||||
|
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ShutdownWinsWhenAProcessFailureRacesCancellation()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using var stop = new CancellationTokenSource();
|
||||||
|
var runner = new FakeRunner { Handler = (_, _) => { stop.Cancel(); throw new InvalidDataException("synthetic failure during shutdown"); } };
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => new LimitProbe(runner, new(), directory.Path)
|
||||||
|
.RunAsync(Provider.Codex, Child("--rpc-error"), DateTimeOffset.UtcNow, stop.Token));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("Africa/Cairo", "2026-04-24")]
|
||||||
|
[InlineData("America/Santiago", "2026-09-06")]
|
||||||
|
[InlineData("Asia/Beirut", "2026-03-29")]
|
||||||
|
public void TotalsSurviveMissingLocalMidnight(string zoneId, string dateText)
|
||||||
|
{
|
||||||
|
var zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
|
||||||
|
var date = DateTime.ParseExact(dateText, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
Assert.True(zone.IsInvalidTime(date));
|
||||||
|
VerifyTotals(zone, date);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void WeekCanStartOnAMondayWithNoMidnight()
|
||||||
|
{
|
||||||
|
var rule = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(new(2026, 1, 1), new(2026, 12, 31), TimeSpan.FromHours(1),
|
||||||
|
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 3, 30),
|
||||||
|
TimeZoneInfo.TransitionTime.CreateFixedDateRule(new(1, 1, 1), 10, 1));
|
||||||
|
var zone = TimeZoneInfo.CreateCustomTimeZone("Monday gap", TimeSpan.Zero, "Monday gap", "standard", "summer", [rule]);
|
||||||
|
VerifyTotals(zone, new(2026, 3, 30));
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var monday = new DateTimeOffset(2026, 3, 30, 1, 0, 0, TimeSpan.FromHours(1));
|
||||||
|
store.Add(new(Provider.Codex, monday.AddHours(-1), null, null, new(Total: 7), "before-week"));
|
||||||
|
store.Add(new(Provider.Codex, monday, null, null, new(Total: 11), "in-week"));
|
||||||
|
var wednesday = new DateTimeOffset(2026, 4, 1, 12, 0, 0, TimeSpan.FromHours(1));
|
||||||
|
store.Add(new(Provider.Codex, wednesday.AddHours(-1), null, null, new(Total: 13), "today"));
|
||||||
|
var totals = store.Totals(Provider.Codex, wednesday, null, zone);
|
||||||
|
Assert.Equal(13, totals.Today.Total); Assert.Equal(24, totals.Week.Total);
|
||||||
|
}
|
||||||
|
private static void VerifyTotals(TimeZoneInfo zone, DateTime date)
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var first = new DateTimeOffset(date.AddHours(1), zone.GetUtcOffset(date.AddHours(1)));
|
||||||
|
var now = first.AddHours(10);
|
||||||
|
store.Add(new(Provider.Codex, first.AddHours(-1), null, null, new(Total: 7), "before"));
|
||||||
|
store.Add(new(Provider.Codex, first, null, null, new(Total: 11), "inside"));
|
||||||
|
var totals = store.Totals(Provider.Codex, now, null, zone);
|
||||||
|
Assert.Equal(11, totals.Today.Total);
|
||||||
|
Assert.Equal(date.DayOfWeek == DayOfWeek.Monday ? 11 : 18, totals.Week.Total);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class ReworkTests
|
||||||
|
{
|
||||||
|
[Theory]
|
||||||
|
[InlineData("<synthetic>", 10)]
|
||||||
|
[InlineData("fixture-model", 0)]
|
||||||
|
public void SyntheticAndUnrequestedZeroUsageAreSilent(string model, int input)
|
||||||
|
{
|
||||||
|
var line = """{"type":"assistant","message":{"model":"@model","usage":{"input_tokens":@input,"output_tokens":0}}}"""
|
||||||
|
.Replace("@model", model).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture));
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
Assert.Null(TranscriptParser.Parse(line, log));
|
||||||
|
Assert.Empty(log.Recent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task IdleSaveDoesNotRewriteAnyHistoryFile()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
store.Add(new(Provider.Claude, DateTimeOffset.UtcNow, "model", "project", new(Total: 10), "key"));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var before = Directory.GetFiles(directory.Path, "*", SearchOption.AllDirectories)
|
||||||
|
.ToDictionary(p => p, p => (File.GetLastWriteTimeUtc(p), new FileInfo(p).Length));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.All(before, p => Assert.Equal(p.Value, (File.GetLastWriteTimeUtc(p.Key), new FileInfo(p.Key).Length)));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void UnchangedLimitsAreSampledAtMostHourly()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "fixture");
|
||||||
|
store.AddLimits([window]);
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddHours(1) }]);
|
||||||
|
Assert.Equal(2, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count);
|
||||||
|
store.AddLimits([window with { UsedPercent = 11, SampleTime = now.AddHours(1).AddMinutes(1) }]);
|
||||||
|
Assert.Equal(3, store.LimitSamples(Provider.Claude, "session", now.AddSeconds(-1), now.AddHours(2)).Count);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task AtomicReplaceSucceedsWhileDeleteSharingReaderRemainsOpen()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("shared.json", "old");
|
||||||
|
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||||
|
await AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("new", File.ReadAllText(path));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task SharingViolationRetriesAndFailsWithinBound()
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows()) return;
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("blocked.json", "old");
|
||||||
|
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||||
|
var clock = new TestClock();
|
||||||
|
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
|
||||||
|
for (var attempt = 0; attempt < 10; attempt++)
|
||||||
|
{
|
||||||
|
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.False(write.IsCompleted);
|
||||||
|
clock.Advance(TimeSpan.FromMilliseconds(50));
|
||||||
|
}
|
||||||
|
await Assert.ThrowsAsync<IOException>(() => write);
|
||||||
|
Assert.Equal("old", File.ReadAllText(path));
|
||||||
|
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void FoldedDiagnosticPreservesOtherProblemsAndTracksLastOccurrence()
|
||||||
|
{
|
||||||
|
var clock = new TestClock();
|
||||||
|
var log = new DiagnosticLog(clock, 2);
|
||||||
|
log.Add(Provider.Claude, "parse", "Malformed usage.");
|
||||||
|
log.Add(Provider.Codex, "timeout", "Probe timed out.");
|
||||||
|
clock.Advance(TimeSpan.FromMinutes(1));
|
||||||
|
for (var i = 0; i < 20; i++) log.Add(Provider.Claude, "parse", "Malformed usage.");
|
||||||
|
Assert.Equal(2, log.Recent.Count);
|
||||||
|
var folded = Assert.Single(log.Recent, d => d.Provider == Provider.Claude);
|
||||||
|
Assert.Equal(21, folded.Count);
|
||||||
|
Assert.Equal(clock.GetUtcNow(), folded.Time);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task UnchangedSourceIsNotOpenedEvenAfterRestart()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var source = directory.Write("claude/projects/p/a.jsonl", Fixtures.Claude());
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
var store = new HistoryStore(directory.Path, log);
|
||||||
|
var scanner = new IncrementalScanner(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
store = new(directory.Path, log);
|
||||||
|
scanner = new(store, log, Path.Combine(directory.Path, "claude"), directory.Path);
|
||||||
|
using var exclusive = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.None);
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
Assert.Empty(log.Recent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task TornJournalTailIsIgnoredAndRepairedBeforeNextAppend()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 10), "one"));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var path = Path.Combine(directory.Path, "history.journal.jsonl");
|
||||||
|
await File.AppendAllTextAsync(path, "{\"v\":1,\"sequence\":2", TestContext.Current.CancellationToken);
|
||||||
|
store = new(directory.Path, new());
|
||||||
|
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 7), "two"));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
store = new(directory.Path, new());
|
||||||
|
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CompactionAndReplayPreserveBucketsKeysAndLimitSets()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one");
|
||||||
|
store.Add(usage);
|
||||||
|
store.AddLimits([new(Provider.Claude, "session", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture")]);
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var committed = File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl"));
|
||||||
|
await store.CompactAsync(TestContext.Current.CancellationToken);
|
||||||
|
// Simulate interruption after checkpoint replacement but before journal reset.
|
||||||
|
directory.Write("history.journal.jsonl", committed);
|
||||||
|
store = new(directory.Path, new());
|
||||||
|
Assert.False(store.Add(usage));
|
||||||
|
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
Assert.Single(store.LimitSamples(Provider.Claude, "session", now.AddHours(-1), now.AddHours(1)));
|
||||||
|
store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) });
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
store = new(directory.Path, new());
|
||||||
|
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task ExpiredClaudeKeysCannotRecountOldResumedEntries()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var clock = new TestClock();
|
||||||
|
var now = clock.GetUtcNow();
|
||||||
|
var store = new HistoryStore(directory.Path, new(), clock);
|
||||||
|
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "key");
|
||||||
|
Assert.True(store.Add(usage));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
clock.Advance(TimeSpan.FromDays(61));
|
||||||
|
store = new(directory.Path, new(), clock);
|
||||||
|
Assert.False(store.Add(usage));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
await store.CompactAsync(TestContext.Current.CancellationToken);
|
||||||
|
var stateJson = File.ReadAllText(Path.Combine(directory.Path, "history.state.json"));
|
||||||
|
Assert.Contains("\"claudeKeys\":{}", stateJson);
|
||||||
|
Assert.Equal(10, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task SmallUpdateAppendsOnlyItsChanges()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
for (var i = 0; i < 1000; i++) store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "key-" + i));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var path = Path.Combine(directory.Path, "history.journal.jsonl");
|
||||||
|
var before = new FileInfo(path).Length;
|
||||||
|
store.Add(new(Provider.Claude, now, "m", "p", new(Total: 1), "new-key"));
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var increase = new FileInfo(path).Length - before;
|
||||||
|
Assert.InRange(increase, 1, 2048);
|
||||||
|
Assert.True(increase < before / 10);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task UnchangedProbeRefreshesSnapshotAgeWithoutWritingHistoryBeforeHourlySample()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var window = new LimitWindow(Provider.Claude, "session", "Session", 10, now.AddHours(3), TimeSpan.FromHours(5), now, "usage");
|
||||||
|
store.AddLimits([window]);
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var journal = new FileInfo(Path.Combine(directory.Path, "history.journal.jsonl"));
|
||||||
|
var length = journal.Length;
|
||||||
|
var time = journal.LastWriteTimeUtc;
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
journal.Refresh();
|
||||||
|
Assert.Equal(length, journal.Length);
|
||||||
|
Assert.Equal(time, journal.LastWriteTimeUtc);
|
||||||
|
Assert.Equal(now.AddMinutes(5), Assert.Single(store.LatestLimits(Provider.Claude)).SampleTime);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task SharingViolationRetriesUntilReaderReleasesItsHandle()
|
||||||
|
{
|
||||||
|
if (!OperatingSystem.IsWindows()) return;
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("briefly-blocked.json", "old");
|
||||||
|
using var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
|
||||||
|
var clock = new TestClock();
|
||||||
|
var write = AtomicFile.WriteAsync(path, "new", TestContext.Current.CancellationToken, clock);
|
||||||
|
Assert.Equal(TimeSpan.FromMilliseconds(50), await clock.NextTimerAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.False(write.IsCompleted);
|
||||||
|
reader.Dispose();
|
||||||
|
clock.Advance(TimeSpan.FromMilliseconds(50));
|
||||||
|
await write;
|
||||||
|
Assert.Equal("new", File.ReadAllText(path));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task PartiallyWrittenCompactionReplaysAbsoluteBucketUpserts()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var hour = new DateTimeOffset(now.UtcTicks - now.UtcTicks % TimeSpan.TicksPerHour, TimeSpan.Zero);
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var usage = new UsageEvent(Provider.Claude, now, "m", "p", new(Total: 10), "one");
|
||||||
|
store.Add(usage);
|
||||||
|
await store.CompactAsync(TestContext.Current.CancellationToken);
|
||||||
|
store.Add(usage with { DedupeKey = "two", Counts = new(Total: 7) });
|
||||||
|
await store.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
var month = now.UtcDateTime.ToString("yyyy-MM", System.Globalization.CultureInfo.InvariantCulture);
|
||||||
|
var partition = new HistoryPartition { Buckets = [new(Provider.Claude, hour, "m", "p", new(Total: 17))] };
|
||||||
|
directory.Write("history/" + month + ".json", System.Text.Json.JsonSerializer.Serialize(partition, CoreJsonContext.Default.HistoryPartition));
|
||||||
|
store = new(directory.Path, new());
|
||||||
|
Assert.Equal(17, store.Total(Provider.Claude, now.AddHours(-1), now.AddHours(1)).Total);
|
||||||
|
Assert.False(store.Add(usage with { DedupeKey = "two" }));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void CompletedCorruptJournalRecordIsRejected()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("history.journal.jsonl", "{\n");
|
||||||
|
Assert.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
|
||||||
|
Assert.Equal("{\n", File.ReadAllText(Path.Combine(directory.Path, "history.journal.jsonl")));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void LateHistoricalLimitSamplesAreNotLostBehindNewerWindows()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var window = new LimitWindow(Provider.Codex, "primary", "Session", 10, now.AddHours(5), TimeSpan.FromHours(5), now, "rollout");
|
||||||
|
store.AddLimits([window with { UsedPercent = 30, SampleTime = now.AddHours(3) }]);
|
||||||
|
store.AddLimits([window]);
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddMinutes(5) }]);
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddHours(1) }]);
|
||||||
|
Assert.Equal(3, store.LimitSamples(Provider.Codex, "primary", now.AddSeconds(-1), now.AddHours(4)).Count);
|
||||||
|
Assert.Equal(30, Assert.Single(store.LatestLimits(Provider.Codex)).UsedPercent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void LateUnchangedSampleCannotDuplicateHourlyPointAcrossMonthBoundary()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var store = new HistoryStore(directory.Path, new());
|
||||||
|
var now = new DateTimeOffset(2026, 10, 1, 0, 10, 0, TimeSpan.Zero);
|
||||||
|
var window = new LimitWindow(Provider.Codex, "primary", "Week", 10, now.AddDays(5), TimeSpan.FromDays(7), now, "rollout");
|
||||||
|
store.AddLimits([window]);
|
||||||
|
store.AddLimits([window with { SampleTime = now.AddMinutes(-30) }]);
|
||||||
|
Assert.Single(store.LimitSamples(Provider.Codex, "primary", now.AddHours(-1), now.AddHours(1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public class StorageTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task TranscriptAppendShrinkReplaceAndRestartDoNotDoubleCount()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var source = directory.Write("claude/projects/p/session.jsonl", Fixtures.Claude());
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
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(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await File.AppendAllTextAsync(source, Fixtures.Claude("b"), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await history.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
history = new(directory.Path, new());
|
||||||
|
scanner = new(history, new(), Path.Combine(directory.Path, "claude"), Path.Combine(directory.Path, "codex"));
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await File.WriteAllTextAsync(source, Fixtures.Claude(), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
var previousWrite = File.GetLastWriteTimeUtc(source);
|
||||||
|
await File.WriteAllTextAsync(source, Fixtures.Claude("c"), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
File.SetLastWriteTimeUtc(source, previousWrite.AddSeconds(1));
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
directory.Write("claude/projects/other/copied.jsonl", Fixtures.Claude("b"));
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
Assert.Equal(57, history.Total(Provider.Claude, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task IncompleteLineIsReadOnlyWhenCompleted()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var fixture = Fixtures.Claude();
|
||||||
|
var source = directory.Write("claude/projects/p/session.jsonl", fixture[..30]);
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
var scanner = new IncrementalScanner(history, new(), Path.Combine(directory.Path, "claude"), directory.Path);
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await File.AppendAllTextAsync(source, fixture[30..], cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CodexCountsIncreasesAndDeduplicatesArchivedCopyAcrossRestart()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var first = Fixtures.Meta + Fixtures.Codex(10);
|
||||||
|
var source = directory.Write("codex/sessions/rollout-a.jsonl", first);
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
await File.AppendAllTextAsync(source, Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"), cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||||
|
await history.SaveAsync(TestContext.Current.CancellationToken);
|
||||||
|
history = new(directory.Path, new());
|
||||||
|
scanner = new(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||||
|
directory.Write("codex/archived_sessions/rollout-a.jsonl", await File.ReadAllTextAsync(source, cancellationToken: TestContext.Current.CancellationToken));
|
||||||
|
Assert.Equal(0, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
Assert.Single((await scanner.ScanAsync(TestContext.Current.CancellationToken)).CodexFallback);
|
||||||
|
Assert.Equal(22, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CodexHandlesCumulativeCounterResetWithoutLosingLaterIncrease()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("codex/sessions/rollout-a.jsonl", Fixtures.Meta + Fixtures.Codex(100) +
|
||||||
|
Fixtures.Codex(10, "2026-10-14T16:01:00Z") + Fixtures.Codex(20, "2026-10-14T16:02:00Z"));
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
var scanner = new IncrementalScanner(history, new(), directory.Path, Path.Combine(directory.Path, "codex"));
|
||||||
|
await scanner.ScanAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(112, history.Total(Provider.Codex, DateTimeOffset.MinValue, DateTimeOffset.MaxValue).Total);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task MalformedLineDoesNotStopValidLaterEntry()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
directory.Write("claude/projects/p/a.jsonl", "{\n" + Fixtures.Claude());
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
var scanner = new IncrementalScanner(new(directory.Path, log), log, Path.Combine(directory.Path, "claude"), directory.Path);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
Assert.Single(log.Recent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task LargeValidEntryStillCountsUsage()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var line = Fixtures.Claude().Replace("{\"type\"", "{\"padding\":\"" + new string('x', 4 * 1024 * 1024) + "\",\"type\"");
|
||||||
|
directory.Write("claude/projects/p/large.jsonl", line);
|
||||||
|
var scanner = new IncrementalScanner(new(directory.Path, new()), new(), Path.Combine(directory.Path, "claude"), directory.Path);
|
||||||
|
Assert.Equal(1, (await scanner.ScanAsync(TestContext.Current.CancellationToken)).AddedEvents);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void LockIsExclusiveAndCanBeReacquired()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
using (var first = StoreLock.TryAcquire(directory.Path))
|
||||||
|
{
|
||||||
|
Assert.NotNull(first);
|
||||||
|
Assert.Null(StoreLock.TryAcquire(directory.Path));
|
||||||
|
}
|
||||||
|
using var second = StoreLock.TryAcquire(directory.Path);
|
||||||
|
Assert.NotNull(second);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task AtomicWritesReplaceAndCancellationPreservesPriorVersion()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("a.json", "old");
|
||||||
|
await AtomicFile.WriteAsync(path, "new", cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
|
||||||
|
using var cancellation = new CancellationTokenSource();
|
||||||
|
cancellation.Cancel();
|
||||||
|
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AtomicFile.WriteAsync(path, "lost", cancellation.Token));
|
||||||
|
Assert.Equal("new", await File.ReadAllTextAsync(path, cancellationToken: TestContext.Current.CancellationToken));
|
||||||
|
Assert.Empty(Directory.GetFiles(directory.Path, "*.tmp"));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task SettingsRoundTripAndInvalidFallback()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var log = new DiagnosticLog();
|
||||||
|
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, log));
|
||||||
|
Assert.Single(log.Recent);
|
||||||
|
var settings = new Settings { StreamDeckInstallMode = InstallMode.Automatic, Claude = new() { Enabled = false } };
|
||||||
|
await SettingsFile.SaveAsync(directory.Path, settings, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(settings, SettingsFile.Load(directory.Path, new()));
|
||||||
|
directory.Write("settings.json", "{\"probeInterval\":\"00:00:10\"}");
|
||||||
|
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
|
||||||
|
directory.Write("settings.json", "{");
|
||||||
|
Assert.Equal(new Settings(), SettingsFile.Load(directory.Path, new()));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task SnapshotRoundTripAndThreeIntervalStaleness()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
var snapshot = new Snapshot { MadeAt = now, RefreshInterval = TimeSpan.FromSeconds(60), Providers = [] };
|
||||||
|
await SnapshotFile.WriteAsync(directory.Path, snapshot, cancellationToken: TestContext.Current.CancellationToken);
|
||||||
|
var fresh = SnapshotFile.Read(directory.Path, now.AddSeconds(180));
|
||||||
|
Assert.False(fresh.IsStale);
|
||||||
|
Assert.Equal(now, fresh.Snapshot!.MadeAt);
|
||||||
|
Assert.Null(fresh.Snapshot.AppPath);
|
||||||
|
Assert.True(SnapshotFile.Read(directory.Path, now.AddSeconds(181)).IsStale);
|
||||||
|
directory.Write("snapshot.json", "{\"v\":2}");
|
||||||
|
Assert.Null(SnapshotFile.Read(directory.Path).Snapshot);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void CorruptHistoryIsNotSilentlyOverwritten()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var path = directory.Write("history.state.json", "{");
|
||||||
|
Assert.Throws<InvalidDataException>(() => new HistoryStore(directory.Path, new()));
|
||||||
|
Assert.Equal("{", File.ReadAllText(path));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void QueriesAggregateByHourDayModelProjectAndLimitWindow()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
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, "b", "/two", new(Total: 20), "b"));
|
||||||
|
history.Add(new(Provider.Codex, now, "b", "/two", new(Total: 99), "c"));
|
||||||
|
var window = new LimitWindow(Provider.Claude, "session", "Session", 20, now.AddHours(1), TimeSpan.FromHours(5), now, "fixture");
|
||||||
|
history.AddLimits([window]);
|
||||||
|
Assert.Equal(2, history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Hour).Count);
|
||||||
|
Assert.Equal(30, Assert.Single(history.TokenSeries(Provider.Claude, now.AddHours(-2), now.AddHours(1), SeriesInterval.Day)).Counts.Total);
|
||||||
|
Assert.Equal("b", history.ByModel(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
|
||||||
|
Assert.Equal("/two", history.ByProject(Provider.Claude, now.AddHours(-2), now.AddHours(1))[0].Name);
|
||||||
|
Assert.Single(history.LimitSamples(Provider.Claude, "session", now, now.AddHours(1)));
|
||||||
|
var totals = history.Totals(Provider.Claude, now, window, TimeZoneInfo.Utc);
|
||||||
|
Assert.Equal(30, totals.Today.Total);
|
||||||
|
Assert.Equal(30, totals.Session!.Value.Total);
|
||||||
|
Assert.Equal(30, totals.Week.Total);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public void LatestLimitSetDoesNotRetainWindowsRemovedByProvider()
|
||||||
|
{
|
||||||
|
using var directory = new TestDirectory();
|
||||||
|
var history = new HistoryStore(directory.Path, new());
|
||||||
|
var now = DateTimeOffset.UtcNow;
|
||||||
|
history.AddLimits([new(Provider.Codex, "codex:primary", "Session", 10, now.AddHours(1), TimeSpan.FromHours(5), now, "rollout"),
|
||||||
|
new(Provider.Codex, "codex:secondary", "Week", 20, now.AddDays(1), TimeSpan.FromDays(7), now, "rollout")]);
|
||||||
|
history.AddLimits([new(Provider.Codex, "codex:primary", "Week", 24, now.AddDays(5), TimeSpan.FromDays(7), now.AddMinutes(1), "app-server")]);
|
||||||
|
Assert.Single(history.LatestLimits(Provider.Codex));
|
||||||
|
Assert.Equal(2, history.LimitSamples(Provider.Codex, "codex:primary", now.AddMinutes(-1), now.AddMinutes(2)).Count);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
using FinalToken.Core.StreamDeck;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests.StreamDeck;
|
||||||
|
|
||||||
|
public sealed class InstallerTests : IDisposable
|
||||||
|
{
|
||||||
|
private readonly string root = Path.Combine(Path.GetTempPath(), "finaltoken-installer-" + Guid.NewGuid().ToString("N"));
|
||||||
|
private string Shipped => Path.Combine(root, "shipped");
|
||||||
|
private string Plugins => Path.Combine(root, "plugins");
|
||||||
|
private string Installed => Path.Combine(Plugins, PluginInstaller.FolderName);
|
||||||
|
public InstallerTests() => Write(Shipped, "1.0.0.0", "new");
|
||||||
|
[Fact]
|
||||||
|
public async Task ReleasePluginReportsOldDevelopmentCopyAsOutdated()
|
||||||
|
{
|
||||||
|
var shipped = Environment.GetEnvironmentVariable("FINALTOKEN_TEST_SHIPPED_PLUGIN");
|
||||||
|
if (shipped is null)
|
||||||
|
{
|
||||||
|
Write(Shipped, typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), "new");
|
||||||
|
shipped = Shipped;
|
||||||
|
}
|
||||||
|
Write(Installed, "1.0.0.1", "old development copy");
|
||||||
|
var process = new FakeProcesses();
|
||||||
|
var installer = new PluginInstaller(shipped, new(Plugins, "fake", "fake"), process);
|
||||||
|
var status = await installer.GetStatusAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(PluginInstallState.Outdated, status.State);
|
||||||
|
Assert.Equal(typeof(PluginInstaller).Assembly.GetName().Version!.ToString(), status.ShippedVersion);
|
||||||
|
Assert.Equal("1.0.0.1", status.InstalledVersion);
|
||||||
|
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task FreshInstallDoesNotStartStoppedHost()
|
||||||
|
{
|
||||||
|
var process = new FakeProcesses();
|
||||||
|
var installer = Create(process);
|
||||||
|
Assert.Equal(PluginInstallState.NotInstalled, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||||
|
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||||
|
Assert.Equal(PluginInstallState.UpToDate, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||||
|
Assert.Equal(0, process.Stops); Assert.Equal(0, process.Starts);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task UpdateStopsAndRestartsRunningHost()
|
||||||
|
{
|
||||||
|
Write(Installed, "0.9.0.0", "old");
|
||||||
|
var process = new FakeProcesses { Running = true };
|
||||||
|
var installer = Create(process);
|
||||||
|
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
|
||||||
|
Assert.Equal(PluginInstallState.Outdated, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||||
|
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("new", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||||
|
Assert.Equal(1, process.Stops); Assert.Equal(1, process.Starts);
|
||||||
|
Assert.Contains(InstallOutcome.Updated, outcomes);
|
||||||
|
Assert.Single(Directory.GetDirectories(Plugins));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task CurrentAndNewerVersionsAreNotReplaced()
|
||||||
|
{
|
||||||
|
Write(Installed, "2.0.0.0", "newer");
|
||||||
|
var process = new FakeProcesses { Running = true };
|
||||||
|
await Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("newer", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||||
|
Assert.Equal(0, process.Stops);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task RestartFailureRollsBackAndRestartsOldPlugin()
|
||||||
|
{
|
||||||
|
Write(Installed, "0.9.0.0", "old");
|
||||||
|
var process = new FakeProcesses { Running = true, FailFirstStart = true };
|
||||||
|
var installer = Create(process);
|
||||||
|
var outcomes = new List<InstallOutcome>(); installer.Outcome += outcomes.Add;
|
||||||
|
await Assert.ThrowsAsync<IOException>(() => installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||||
|
Assert.Equal(2, process.Starts);
|
||||||
|
Assert.Contains(InstallOutcome.RolledBack, outcomes);
|
||||||
|
Assert.Single(Directory.GetDirectories(Plugins));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task NoHostAndMissingShippedPluginHaveExplicitStatus()
|
||||||
|
{
|
||||||
|
var installer = new PluginInstaller(Shipped, null);
|
||||||
|
Assert.Equal(PluginInstallState.NoHostFound, (await installer.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||||
|
await installer.InstallOrUpdateAsync(TestContext.Current.CancellationToken);
|
||||||
|
var missing = new PluginInstaller(Path.Combine(root, "missing"), new(Plugins, "fake", "fake"));
|
||||||
|
Assert.Equal(PluginInstallState.NoShippedPlugin, (await missing.GetStatusAsync(TestContext.Current.CancellationToken)).State);
|
||||||
|
await Assert.ThrowsAsync<InvalidOperationException>(() => missing.InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task StopFailureKeepsOldFolderAndAttemptsRestart()
|
||||||
|
{
|
||||||
|
Write(Installed, "0.9.0.0", "old");
|
||||||
|
var process = new FakeProcesses { Running = true, FailStop = true };
|
||||||
|
await Assert.ThrowsAsync<IOException>(() => Create(process).InstallOrUpdateAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.Equal("old", File.ReadAllText(Path.Combine(Installed, "binary")));
|
||||||
|
Assert.Equal(1, process.Starts);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(InstallMode.Off, InstallAction.Nothing)]
|
||||||
|
[InlineData(InstallMode.Ask, InstallAction.Ask)]
|
||||||
|
[InlineData(InstallMode.Automatic, InstallAction.Install)]
|
||||||
|
public void PolicyHonorsInstallMode(InstallMode mode, InstallAction expected) =>
|
||||||
|
Assert.Equal(expected, InstallPolicy.Decide(mode, new(PluginInstallState.NotInstalled, "1"), null));
|
||||||
|
[Fact]
|
||||||
|
public void PolicyHonorsDismissedVersionAndUnavailableHost()
|
||||||
|
{
|
||||||
|
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Ask, new(PluginInstallState.Outdated, "1"), "1"));
|
||||||
|
Assert.Equal(InstallAction.Nothing, InstallPolicy.Decide(InstallMode.Automatic, new(PluginInstallState.NoHostFound), null));
|
||||||
|
}
|
||||||
|
private PluginInstaller Create(FakeProcesses process) => new(Shipped, new(Plugins, "fake", "fake"), process);
|
||||||
|
private static void Write(string directory, string version, string binary)
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(directory);
|
||||||
|
File.WriteAllText(Path.Combine(directory, "manifest.json"), "{\"Version\":\"" + version + "\"}");
|
||||||
|
File.WriteAllText(Path.Combine(directory, "binary"), binary);
|
||||||
|
}
|
||||||
|
public void Dispose() { if (Directory.Exists(root)) Directory.Delete(root, true); }
|
||||||
|
private sealed class FakeProcesses : IHostProcesses
|
||||||
|
{
|
||||||
|
public bool Running { get; init; }
|
||||||
|
public bool FailFirstStart { get; init; }
|
||||||
|
public bool FailStop { get; init; }
|
||||||
|
public int Stops { get; private set; }
|
||||||
|
public int Starts { get; private set; }
|
||||||
|
public Task<bool> IsRunningAsync(PluginHost host, CancellationToken ct) => Task.FromResult(Running);
|
||||||
|
public Task StopAsync(PluginHost host, CancellationToken ct) { Stops++; if (FailStop) throw new IOException("stop failed"); return Task.CompletedTask; }
|
||||||
|
public Task StartAsync(PluginHost host, CancellationToken ct) { Starts++; if (FailFirstStart && Starts == 1) throw new IOException("start failed"); return Task.CompletedTask; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
using FinalToken.Core.Processes;
|
||||||
|
using System.Threading.Channels;
|
||||||
|
|
||||||
|
namespace FinalToken.Core.Tests;
|
||||||
|
|
||||||
|
public sealed class TestDirectory : IDisposable
|
||||||
|
{
|
||||||
|
public string Path { get; } = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "finaltoken-test-" + Guid.NewGuid().ToString("N"));
|
||||||
|
public TestDirectory() => Directory.CreateDirectory(Path);
|
||||||
|
public string Write(string relative, string contents)
|
||||||
|
{
|
||||||
|
var path = System.IO.Path.GetFullPath(System.IO.Path.Combine(Path, relative));
|
||||||
|
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
|
||||||
|
File.WriteAllText(path, contents);
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
public void Dispose() => Directory.Delete(Path, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class TestClock : TimeProvider
|
||||||
|
{
|
||||||
|
private readonly Channel<TimeSpan> scheduled = Channel.CreateUnbounded<TimeSpan>();
|
||||||
|
public ValueTask<TimeSpan> NextTimerAsync(CancellationToken cancellationToken) => scheduled.Reader.ReadAsync(cancellationToken);
|
||||||
|
private readonly Lock gate = new();
|
||||||
|
private DateTimeOffset now = new(2026, 10, 14, 16, 0, 0, TimeSpan.Zero);
|
||||||
|
private readonly List<TestTimer> timers = [];
|
||||||
|
public override DateTimeOffset GetUtcNow() { lock (gate) return now; }
|
||||||
|
public void Advance(TimeSpan amount)
|
||||||
|
{
|
||||||
|
List<TestTimer> due;
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
now += amount;
|
||||||
|
due = timers.Where(t => t.Next <= now && !t.Disposed).ToList();
|
||||||
|
foreach (var timer in due) timer.Next = timer.Period > TimeSpan.Zero ? now + timer.Period : DateTimeOffset.MaxValue;
|
||||||
|
}
|
||||||
|
foreach (var timer in due) timer.Callback(timer.State);
|
||||||
|
}
|
||||||
|
public override ITimer CreateTimer(TimerCallback callback, object? state, TimeSpan dueTime, TimeSpan period)
|
||||||
|
{
|
||||||
|
lock (gate)
|
||||||
|
{
|
||||||
|
var timer = new TestTimer(this, callback, state, period);
|
||||||
|
timer.Change(dueTime, period);
|
||||||
|
timers.Add(timer);
|
||||||
|
scheduled.Writer.TryWrite(dueTime);
|
||||||
|
return timer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private sealed class TestTimer(TestClock owner, TimerCallback callback, object? state, TimeSpan period) : ITimer
|
||||||
|
{
|
||||||
|
public TimerCallback Callback { get; } = callback;
|
||||||
|
public object? State { get; } = state;
|
||||||
|
public TimeSpan Period { get; private set; } = period;
|
||||||
|
public DateTimeOffset Next { get; set; }
|
||||||
|
public bool Disposed { get; private set; }
|
||||||
|
public bool Change(TimeSpan dueTime, TimeSpan newPeriod)
|
||||||
|
{
|
||||||
|
lock (owner.gate)
|
||||||
|
{
|
||||||
|
if (Disposed) return false;
|
||||||
|
Period = newPeriod;
|
||||||
|
Next = dueTime == Timeout.InfiniteTimeSpan ? DateTimeOffset.MaxValue : owner.now + dueTime;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public void Dispose() { lock (owner.gate) Disposed = true; }
|
||||||
|
public ValueTask DisposeAsync() { Dispose(); return ValueTask.CompletedTask; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed class FakeRunner : IProcessRunner
|
||||||
|
{
|
||||||
|
public List<ProcessRequest> Requests { get; } = [];
|
||||||
|
public Func<ProcessRequest, CancellationToken, Task<ProcessResult>>? Handler { get; set; }
|
||||||
|
public Task<ProcessResult> RunAsync(ProcessRequest request, CancellationToken cancellationToken)
|
||||||
|
{
|
||||||
|
Requests.Add(request);
|
||||||
|
return Handler?.Invoke(request, cancellationToken) ?? Task.FromResult(new ProcessResult(0,
|
||||||
|
request.CodexRpc ? Fixtures.CodexResponse : Fixtures.ClaudeEnvelope));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static class Fixtures
|
||||||
|
{
|
||||||
|
public const string ClaudeEnvelope = "{\"local_command\":\"usage\",\"num_turns\":0,\"is_error\":false,\"result\":\"Current session: 28% used · resets Oct 14, 7:30pm (Europe/Berlin)\\nCurrent week (all models): 66% used · resets Oct 18, 8pm (Europe/Berlin)\"}";
|
||||||
|
public const string CodexResponse = "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531},\"secondary\":null}}}";
|
||||||
|
public static string Claude(string id = "a", string request = "r", int input = 10, string time = "2026-10-14T16:00:00Z") =>
|
||||||
|
"""{"type":"assistant","timestamp":"@time","cwd":"/project","requestId":"@request","message":{"id":"@id","model":"fixture-model","usage":{"input_tokens":@input,"output_tokens":2,"cache_read_input_tokens":3,"cache_creation_input_tokens":4}}}"""
|
||||||
|
.Replace("@time", time).Replace("@request", request).Replace("@id", id).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
|
||||||
|
public const string Meta = "{\"type\":\"session_meta\",\"payload\":{\"id\":\"session-1\",\"cwd\":\"/project\"}}\n{\"type\":\"turn_context\",\"payload\":{\"model\":\"fixture-model\"}}\n";
|
||||||
|
public static string Codex(int input, string time = "2026-10-14T16:00:00Z") =>
|
||||||
|
"""{"type":"event_msg","timestamp":"@time","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":@input,"cached_input_tokens":0,"output_tokens":2,"reasoning_output_tokens":1,"total_tokens":@total}},"rate_limits":{"limit_id":"codex","primary":{"used_percent":24,"window_minutes":10080,"resets_at":1792479531},"secondary":null}}}"""
|
||||||
|
.Replace("@time", time).Replace("@input", input.ToString(System.Globalization.CultureInfo.InvariantCulture)).Replace("@total", (input + 2).ToString(System.Globalization.CultureInfo.InvariantCulture)) + "\n";
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# Process probe host
|
||||||
|
Windows GUI-subsystem regression helper for D6. It deliberately has no console or standard
|
||||||
|
handles, then runs Core's ProcessRunner. Child modes check handles and synthetic UTF-8 JSON. The optional
|
||||||
|
live Claude mode keeps provider output in memory and writes only diagnostic metadata.
|
||||||
|
No provider text or real transcript fixtures belong here. JSON uses source generation.
|
||||||
|
Built with Core tests; run `dotnet test --project tests/FinalToken.Core.Tests -c Release`.
|
||||||
|
Portable `--rpc-*` modes provide synthetic app-server exchanges, errors, EOF and malformed output.
|
||||||
|
The `app-server` mode returns an RPC error for published-CLI checks; it never contacts a provider.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
<PropertyGroup>
|
||||||
|
<OutputType>WinExe</OutputType>
|
||||||
|
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||||
|
</PropertyGroup>
|
||||||
|
<ItemGroup><ProjectReference Include="../../src/FinalToken.Core/FinalToken.Core.csproj" /></ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
using System.Runtime.InteropServices;
|
||||||
|
using System.Text.Json;
|
||||||
|
using System.Text.Json.Serialization;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using FinalToken.Core.Collectors;
|
||||||
|
using FinalToken.Core.Processes;
|
||||||
|
|
||||||
|
namespace FinalToken.ProcessHost;
|
||||||
|
|
||||||
|
public static class Program
|
||||||
|
{
|
||||||
|
public static async Task<int> Main(string[] args)
|
||||||
|
{
|
||||||
|
if (args.FirstOrDefault() is { } mode && (mode.StartsWith("--rpc-", StringComparison.Ordinal) || mode == "app-server"))
|
||||||
|
return await RpcAsync(mode == "app-server" ? "--rpc-error" : mode);
|
||||||
|
if (!OperatingSystem.IsWindows()) return 0;
|
||||||
|
if (args is ["--handles"])
|
||||||
|
return new[] { -10, -11, -12 }.All(id => Native.GetFileType(Native.GetStdHandle(id)) != 0) ? 0 : 17;
|
||||||
|
if (args is ["--utf8"])
|
||||||
|
{
|
||||||
|
await Console.OpenStandardOutput().WriteAsync(System.Text.Encoding.UTF8.GetBytes("{\"marker\":\"· •\"}"));
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (args.Length < 2) return 2;
|
||||||
|
Native.FreeConsole();
|
||||||
|
foreach (var id in new[] { -10, -11, -12 }) Native.SetStdHandle(id, 0);
|
||||||
|
var report = new ProbeReport { HostHasConsole = Native.GetConsoleWindow() != 0,
|
||||||
|
HostInputValid = Native.GetFileType(Native.GetStdHandle(-10)) != 0, OutputCodePage = Console.OutputEncoding.CodePage };
|
||||||
|
var live = args[0] == "--claude";
|
||||||
|
var utf8 = args[0] == "--utf8-probe";
|
||||||
|
var cli = live ? CliDiscovery.Find(Provider.Claude).Command : new CliCommand(Environment.ProcessPath!, []);
|
||||||
|
if (cli is null) return 3;
|
||||||
|
var result = await new ProcessRunner().RunAsync(new(cli, live
|
||||||
|
? ["-p", "/usage", "--output-format", "json", "--no-session-persistence"] : utf8 ? ["--utf8"] : ["--handles"],
|
||||||
|
Path.GetDirectoryName(Path.GetFullPath(args[1]))!, TimeSpan.FromSeconds(60)), CancellationToken.None);
|
||||||
|
report = report with { ExitCode = result.ExitCode, TimedOut = result.TimedOut,
|
||||||
|
Utf8Matched = utf8 && result.Output == "{\"marker\":\"· •\"}" };
|
||||||
|
if (live)
|
||||||
|
{
|
||||||
|
var diagnostics = new DiagnosticLog();
|
||||||
|
var windows = ClaudeUsageParser.ParseEnvelope(result.Output, DateTimeOffset.UtcNow, diagnostics);
|
||||||
|
report = report with { WindowCount = windows.Count, DiagnosticCodes = diagnostics.Recent.Select(d => d.Code).ToArray() };
|
||||||
|
}
|
||||||
|
await AtomicFile.WriteAsync(args[1], JsonSerializer.Serialize(report, ProbeJsonContext.Default.ProbeReport));
|
||||||
|
return live ? report.WindowCount > 0 ? 0 : 18 : utf8 ? report.Utf8Matched ? 0 : 19 : result.ExitCode;
|
||||||
|
}
|
||||||
|
private static async Task<int> RpcAsync(string mode)
|
||||||
|
{
|
||||||
|
Console.InputEncoding = System.Text.Encoding.UTF8;
|
||||||
|
Console.OutputEncoding = new System.Text.UTF8Encoding(false);
|
||||||
|
if (mode == "--rpc-eof") return 0;
|
||||||
|
var initialize = await Console.In.ReadLineAsync();
|
||||||
|
using var first = JsonDocument.Parse(initialize ?? "null");
|
||||||
|
if (first.RootElement.GetProperty("method").GetString() != "initialize") return 20;
|
||||||
|
if (mode == "--rpc-init-error") { await Console.Out.WriteLineAsync("{\"id\":1,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}"); return 0; }
|
||||||
|
await Console.Out.WriteLineAsync("{\"id\":1,\"result\":{}}");
|
||||||
|
using var initialized = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||||
|
using var request = JsonDocument.Parse(await Console.In.ReadLineAsync() ?? "null");
|
||||||
|
if (initialized.RootElement.GetProperty("method").GetString() != "initialized" ||
|
||||||
|
request.RootElement.GetProperty("method").GetString() != "account/rateLimits/read") return 21;
|
||||||
|
await Console.Out.WriteLineAsync("{\"method\":\"syntheticNotification\"}");
|
||||||
|
var response = mode switch
|
||||||
|
{
|
||||||
|
"--rpc-error" => "{\"id\":2,\"error\":{\"code\":-1,\"message\":\"synthetic error\"}}",
|
||||||
|
"--rpc-garbage" => "not JSON",
|
||||||
|
"--rpc-shape" => "[]",
|
||||||
|
"--rpc-bound" => new string('x', 1024 * 1024 + 1),
|
||||||
|
_ => "{\"id\":2,\"result\":{\"rateLimits\":{\"limitId\":\"codex\",\"primary\":{\"usedPercent\":24,\"windowDurationMins\":10080,\"resetsAt\":1792479531}}}}"
|
||||||
|
};
|
||||||
|
await Console.Out.WriteLineAsync(response);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public sealed record ProbeReport
|
||||||
|
{
|
||||||
|
public bool HostHasConsole { get; init; }
|
||||||
|
public bool HostInputValid { get; init; }
|
||||||
|
public int ExitCode { get; init; }
|
||||||
|
public bool TimedOut { get; init; }
|
||||||
|
public int WindowCount { get; init; }
|
||||||
|
public int OutputCodePage { get; init; }
|
||||||
|
public bool Utf8Matched { get; init; }
|
||||||
|
public string[] DiagnosticCodes { get; init; } = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
[JsonSerializable(typeof(ProbeReport))]
|
||||||
|
internal partial class ProbeJsonContext : JsonSerializerContext;
|
||||||
|
|
||||||
|
internal static partial class Native
|
||||||
|
{
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
internal static partial nint GetStdHandle(int id);
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
internal static partial uint GetFileType(nint handle);
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
internal static partial bool SetStdHandle(int id, nint handle);
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
[return: MarshalAs(UnmanagedType.Bool)]
|
||||||
|
internal static partial bool FreeConsole();
|
||||||
|
[LibraryImport("kernel32.dll")]
|
||||||
|
internal static partial nint GetConsoleWindow();
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# StreamDeck tests
|
||||||
|
Hand-written fixtures only. xUnit v3 AOT with Microsoft.Testing.Platform.
|
||||||
|
Run `dotnet test --project tests/FinalToken.StreamDeck.Tests -c Release` from the root.
|
||||||
|
Use fake sockets and synthetic snapshots for protocol, settings and key rendering checks.
|
||||||
|
Manifest tests read the copied plugin assets. Never require a running Stream Deck host.
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@AGENTS.md
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<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.StreamDeck/FinalToken.StreamDeck.csproj" />
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
using System.Text.Json;
|
||||||
|
using System.Xml.Linq;
|
||||||
|
using FinalToken.Core;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace FinalToken.StreamDeck.Tests;
|
||||||
|
|
||||||
|
public sealed class PluginTests
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task InvalidHostFrameEndsConnectionWithoutLoggingFrameText()
|
||||||
|
{
|
||||||
|
var socket = new FakeSocket { ReceiveFailure = new InvalidDataException("synthetic private frame") };
|
||||||
|
var session = new PluginSession(socket, _ => Task.FromResult(false));
|
||||||
|
Assert.Null(await session.ReceiveAsync(TestContext.Current.CancellationToken));
|
||||||
|
Assert.Equal("connection-ended", session.ConnectionEndCode);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("{}", "Claude", "SessionPercent", "")]
|
||||||
|
[InlineData("{\"provider\":\"Codex\"}", "Codex", "SessionPercent", "")]
|
||||||
|
[InlineData("{\"metric\":\"TokensToday\",\"future\":1}", "Claude", "TokensToday", "")]
|
||||||
|
public void PartialStatSettingsKeepConstructorDefaults(string json, string provider, string metric, string window)
|
||||||
|
{
|
||||||
|
var settings = JsonSerializer.Deserialize(json, PluginJsonContext.Default.StatSettings)!;
|
||||||
|
Assert.Equal(new StatSettings(provider, metric, window), settings);
|
||||||
|
Assert.True(settings.IsValid);
|
||||||
|
}
|
||||||
|
private static readonly DateTimeOffset Now = new(2026, 10, 14, 12, 0, 0, TimeSpan.Zero);
|
||||||
|
private static Snapshot Snapshot(PaceState state = PaceState.Ahead) => new()
|
||||||
|
{
|
||||||
|
MadeAt = Now, RefreshInterval = TimeSpan.FromMinutes(1), AppPath = "app.exe",
|
||||||
|
Providers = [new(Provider.Claude, ProviderStatus.Available, null,
|
||||||
|
[new(new(Provider.Claude, "session", "Session", 65, Now.AddHours(2), TimeSpan.FromHours(5), Now, "test"), new(state, .6, 5)),
|
||||||
|
new(new(Provider.Claude, "week", "Week", 42, Now.AddDays(2), TimeSpan.FromDays(7), Now, "test"), new(state, .5, -8))],
|
||||||
|
new(Total: 12345), null, new(Total: 2345678))]
|
||||||
|
};
|
||||||
|
[Fact]
|
||||||
|
public async Task RegistersAndSettingsRoundTripWithDeduplicatedDrawing()
|
||||||
|
{
|
||||||
|
var socket = new FakeSocket();
|
||||||
|
var session = new PluginSession(socket, _ => Task.FromResult(true));
|
||||||
|
await session.RegisterAsync(new(1234, "registration-id", "registerPlugin"), TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("registerPlugin", Read(socket.Sent[0], "event"));
|
||||||
|
Assert.Equal("registration-id", Read(socket.Sent[0], "uuid"));
|
||||||
|
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||||
|
await session.HandleAsync("""{"event":"willAppear","action":"de.finalfactory.finaltoken.stat","context":"key","payload":{"settings":{}}}""", Now, TestContext.Current.CancellationToken);
|
||||||
|
var count = socket.Sent.Count;
|
||||||
|
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(count, socket.Sent.Count);
|
||||||
|
await session.HandleAsync("""{"event":"sendToPlugin","context":"key","payload":{"settings":{"provider":"Claude","metric":"TokensWeek","window":"week"}}}""", Now, TestContext.Current.CancellationToken);
|
||||||
|
using var settings = JsonDocument.Parse(socket.Sent.Single(s => Read(s, "event") == "setSettings"));
|
||||||
|
Assert.Equal("TokensWeek", settings.RootElement.GetProperty("payload").GetProperty("metric").GetString());
|
||||||
|
Assert.Equal("sendToPropertyInspector", Read(socket.Sent[^1], "event"));
|
||||||
|
await session.HandleAsync("""{"event":"willDisappear","context":"key"}""", Now, TestContext.Current.CancellationToken);
|
||||||
|
count = socket.Sent.Count;
|
||||||
|
await session.UpdateAsync(new(null, true, null), Now, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal(count, socket.Sent.Count);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(true)]
|
||||||
|
[InlineData(false)]
|
||||||
|
public async Task KeyPressLaunchesSnapshotAppAndAlertsFailure(bool success)
|
||||||
|
{
|
||||||
|
string? path = null;
|
||||||
|
var socket = new FakeSocket();
|
||||||
|
var session = new PluginSession(socket, value => { path = value; return Task.FromResult(success); });
|
||||||
|
await session.UpdateAsync(new(Snapshot(), false, null), Now, TestContext.Current.CancellationToken);
|
||||||
|
await session.HandleAsync("""{"event":"keyDown","context":"key"}""", Now, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Equal("app.exe", path);
|
||||||
|
Assert.Equal(success ? 0 : 1, socket.Sent.Count);
|
||||||
|
if (!success) Assert.Equal("showAlert", Read(socket.Sent[0], "event"));
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData("SessionPercent", "65%")]
|
||||||
|
[InlineData("WeekPercent", "42%")]
|
||||||
|
[InlineData("PaceDelta", "+5pp")]
|
||||||
|
[InlineData("TimeToReset", "2h 0m")]
|
||||||
|
[InlineData("TokensToday", "12.3k")]
|
||||||
|
[InlineData("TokensWeek", "2.3M")]
|
||||||
|
public void RendersEveryMetric(string metric, string value)
|
||||||
|
{
|
||||||
|
var svg = StatRenderer.Render(new(Snapshot(), false, null), new(Metric: metric), Now);
|
||||||
|
Assert.Contains(value, svg);
|
||||||
|
Assert.Equal("svg", XDocument.Parse(svg).Root!.Name.LocalName);
|
||||||
|
}
|
||||||
|
[Theory]
|
||||||
|
[InlineData(PaceState.Ahead, "#ef6461")]
|
||||||
|
[InlineData(PaceState.Behind, "#69a7ff")]
|
||||||
|
[InlineData(PaceState.OnTrack, "#58d6a0")]
|
||||||
|
[InlineData(PaceState.Unknown, "#a0a7b4")]
|
||||||
|
public void RendersPaceColorAndMarker(PaceState state, string color)
|
||||||
|
{
|
||||||
|
var svg = StatRenderer.Render(new(Snapshot(state), false, null), new(), Now);
|
||||||
|
Assert.Contains(color, svg);
|
||||||
|
Assert.Contains("M42 56v11", svg);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void StaleMissingAndUnknownWindowAreExplicit()
|
||||||
|
{
|
||||||
|
Assert.Contains("offline", StatRenderer.Render(new(Snapshot(), true, null), new(), Now));
|
||||||
|
Assert.Contains("offline", StatRenderer.Render(new(null, true, null), new(), Now));
|
||||||
|
Assert.Contains("—", StatRenderer.Render(new(Snapshot(), false, null), new(Window: "removed"), Now));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void NullNestedSnapshotContentShowsOffline()
|
||||||
|
{
|
||||||
|
var snapshot = Snapshot() with { Providers = [new(Provider.Claude, ProviderStatus.Available, null, null!, new(), null, new())] };
|
||||||
|
Assert.Contains("offline", StatRenderer.Render(new(snapshot, false, null), new(), Now));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void PaceAndResetUseAvailableWeekWhenNoSessionExists()
|
||||||
|
{
|
||||||
|
var provider = Snapshot().Providers[0];
|
||||||
|
provider = provider with { Windows = [provider.Windows[1]] };
|
||||||
|
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "PaceDelta"))?.Window.Id);
|
||||||
|
Assert.Equal("week", StatRenderer.SelectWindow(provider, new(Metric: "TimeToReset"))?.Window.Id);
|
||||||
|
Assert.Null(StatRenderer.SelectWindow(provider, new()));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public async Task MalformedAndInvalidSettingsDoNotChangeKeys()
|
||||||
|
{
|
||||||
|
var socket = new FakeSocket();
|
||||||
|
var session = new PluginSession(socket, _ => Task.FromResult(false));
|
||||||
|
foreach (var json in new[] { "{", "[]", "null", """{"event":"willAppear","context":"key","payload":{"settings":{"provider":"Unknown"}}}""" })
|
||||||
|
await session.HandleAsync(json, Now, TestContext.Current.CancellationToken);
|
||||||
|
Assert.Empty(socket.Sent);
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void RegistrationValidatesArguments()
|
||||||
|
{
|
||||||
|
Assert.NotNull(Registration.Parse(["-port", "1234", "-pluginUUID", "x", "-registerEvent", "registerPlugin", "-info", "{}"]));
|
||||||
|
Assert.Null(Registration.Parse(["-port", "0"]));
|
||||||
|
}
|
||||||
|
[Fact]
|
||||||
|
public void ManifestHasExpectedContractAndLocalAssets()
|
||||||
|
{
|
||||||
|
var folder = Path.Combine(AppContext.BaseDirectory, "plugin");
|
||||||
|
using var manifest = JsonDocument.Parse(File.ReadAllText(Path.Combine(folder, "manifest.json")));
|
||||||
|
var root = manifest.RootElement;
|
||||||
|
Assert.Equal(2, root.GetProperty("SDKVersion").GetInt32());
|
||||||
|
Assert.Equal("de.finalfactory.finaltoken", root.GetProperty("UUID").GetString());
|
||||||
|
Assert.Equal("FinalToken.StreamDeck.exe", root.GetProperty("CodePathWin").GetString());
|
||||||
|
Assert.Equal("FinalToken.StreamDeck", root.GetProperty("CodePathLin").GetString());
|
||||||
|
Assert.True(Version.TryParse(root.GetProperty("Version").GetString(), out _));
|
||||||
|
Assert.Single(root.GetProperty("Actions").EnumerateArray());
|
||||||
|
Assert.Equal(PluginSession.Action, root.GetProperty("Actions")[0].GetProperty("UUID").GetString());
|
||||||
|
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("PropertyInspectorPath").GetString()!)));
|
||||||
|
Assert.True(File.Exists(Path.Combine(folder, root.GetProperty("Icon").GetString()! + ".svg")));
|
||||||
|
}
|
||||||
|
private static string? Read(string json, string property)
|
||||||
|
{
|
||||||
|
using var doc = JsonDocument.Parse(json);
|
||||||
|
return doc.RootElement.GetProperty(property).GetString();
|
||||||
|
}
|
||||||
|
private sealed class FakeSocket : IPluginSocket
|
||||||
|
{
|
||||||
|
public Exception? ReceiveFailure { get; init; }
|
||||||
|
public List<string> Sent { get; } = [];
|
||||||
|
public Task SendAsync(string json, CancellationToken cancellationToken) { Sent.Add(json); return Task.CompletedTask; }
|
||||||
|
public Task<string?> ReceiveAsync(CancellationToken cancellationToken) => ReceiveFailure is { } error
|
||||||
|
? Task.FromException<string?>(error) : Task.FromResult<string?>(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user