Token history is kept per hour, and the hour that holds the day's first sample keeps growing after it, so use in that hour still moved the budget (second review of #15). The developer chose another round with this rule on 2026-10-18. Refs #13
326 lines
22 KiB
Markdown
326 lines
22 KiB
Markdown
# 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.
|
||
- **Forecasts.** At the average rate so far, the use at reset is `u / e` (for `e > 0`). Whenever
|
||
that passes 100 % (that is, `d > 0`, whatever the threshold), the time of reaching 100 %,
|
||
`t + (100 − u) · e·W / u`, is shown; it always comes before `r`. A second forecast uses the
|
||
recent rate: the rise of `u` over the window's samples from the last 24 h, when they span at
|
||
least 3 h. It is shown beside the average forecast, never instead of it. Forecasts start once
|
||
2 % of the window has passed (6 min of a session, about 3 h 22 min of a week), or as soon as
|
||
the window is ahead. Before either, a few minutes of use already "reach" 100 % within days,
|
||
which is noise. Early forecasts are rough and firm up as the window goes on. Until forecasts
|
||
start, the tile and the window chart say when they will.
|
||
- **Window instance.** The samples of one window whose reset times lie within 15 minutes of each
|
||
other. Claude reports resets to the minute and drifts by a minute between probes ("8pm", then
|
||
"7:59pm"), so exact equality would split one week. A reset starts a new instance at 0 %.
|
||
- **Days of a long window.** For a window longer than a day: today's use is `u` now minus `u` at
|
||
the local start of today (the last sample of the same instance at or before it, or 0 when the
|
||
instance began today). The use of each local day of the instance is computed the same way.
|
||
A day's share is the time of that day inside the instance. A 7-day instance that resets at
|
||
another time than midnight touches 8 local dates; the first and the last have shorter shares,
|
||
and both are shown. The even pace of a day is `100 · share / W`. The daily budget plans the
|
||
rest of the instance from the start of today. With `s` the local start of today, or the
|
||
instance start when that is later, and `u₀` the use at `s`, today's budget is
|
||
`(100 − u₀) · today's share / (r − s)`; use during the day does not change it. A later day's
|
||
budget is `(100 − max(u, u₀ + today's budget)) · its share / (r − end of today)`, so later days
|
||
lose budget only once today's use passes today's budget. `u₀` is measured, or estimated as
|
||
below and then marked. An estimated `u₀` takes `k` from the first sample at or after `s`, not
|
||
the newest, and counts only the whole hours before that sample's hour, so later samples and
|
||
tokens do not move it. Without `u₀` there is no budget.
|
||
- **Estimates from tokens.** Where samples do not cover a span, its use is estimated from the
|
||
token history. Tokens are weighted by the provider's API price ratios: Claude input 1,
|
||
output 5, cache write 1.25, cache read 0.1; Codex uncached input 1, cached input 0.1,
|
||
output 8. A window whose label names a model family ("Fable") counts only that family's
|
||
models; any other window counts all of the provider's models. Because an instance starts at
|
||
0 %, the scale `k = u / (weighted tokens from the instance start to the sample)` turns weighted
|
||
tokens into percent of the limit; the newest sample gives `k`. A day, or a stretch of the
|
||
window chart, then uses samples where they exist at both ends, and `k` × its weighted tokens
|
||
where they do not. A finished instance uses its own last sample for `k` when it has one, else
|
||
the current `k`. Estimates are always marked as estimates and never exceed 100 %: a limit that
|
||
is reached stops use, so an estimate that would pass it shows "limit reached (estimated)" at
|
||
the time it crosses. No tokens in the instance means no estimate. Instance boundaries come from
|
||
resets: an instance starts at its reset minus its length, and ends at its reset or at the next
|
||
instance's start, whichever comes first (Codex can start a new window early). Spans between
|
||
instances (a session window opens only with the next message) belong to none. A past instance
|
||
with samples is always the real one; an instance is only inferred where no samples exist, by
|
||
stepping back one window length, and never overlaps a real one. Windows of a day or shorter are
|
||
never inferred, since a session starts with whatever message comes next. Past instances are
|
||
labelled with their real start and end.
|
||
|
||
A window without a known length or reset has no pace; FinalToken never guesses one; an estimate
|
||
is a marked calculation from measured tokens, not a guess.
|
||
|
||
**Why.** R5. A straight line from the window's start to its reset is a pace the user can check
|
||
by hand. A user over pace by less than the threshold still runs out before the reset, so the
|
||
date shows from the first point over pace. The day figures answer "how much of the week did I
|
||
use today" and "how much may I use per day from now on" (developer feedback, 2026-10-14). A
|
||
budget computed from `u` and the time now fell with every use, even within the day's plan, and
|
||
held a partial first day to a full day's pace; a budget set at the start of the day can be
|
||
compared with the day's bar (developer feedback, 2026-10-18). An estimated `u₀` with the newest
|
||
`k` moved whenever use from the web or another device changed the scale, and the budget moved
|
||
with it; the token hour that holds the first sample keeps growing after it.
|
||
Measured samples alone left the day chart empty until the app had run for a whole week, while the
|
||
token history already covers it; the estimate fills it at once and agrees with the measured use
|
||
of the instance by construction (developer feedback, 2026-10-15). A window that is ahead early is
|
||
no noise: a Codex week at 39 % ten hours after its reset reaches 100 % within a day, and that is
|
||
the warning the user needs (developer feedback, 2026-10-15). Starting at 10 % hid every forecast
|
||
for the first 17 h of a week, and Codex weeks that reset early spent much of their time there;
|
||
the developer prefers a rough forecast that firms up with data (developer feedback, 2026-10-18).
|
||
|
||
**Gives up.** Weekday and working-hour patterns. Forecasts assume a constant rate; early in a
|
||
window, a burst that puts it ahead gives a reach date that a quiet hour moves out again, and in
|
||
the first hours a forecast can move by days.
|
||
Measured day figures are only as fine as the samples (D5 keeps one per hour while the value
|
||
stands still). Estimates miss use from other devices and from claude.ai or the web, which
|
||
counts against the limit but leaves no local tokens; they also miss changes in model mix within
|
||
an instance and any weighting the provider applies beyond the price ratios. An estimated `u₀`
|
||
keeps the first sample's scale for the whole day, even when later samples would estimate it
|
||
better, and overstates `u₀` by the use in that sample's hour before the sample.
|
||
|
||
## D8 — Desktop app
|
||
|
||
**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.
|
||
- **Panel (R4).** It leads with one tile per limit window: used percent, pace, the forecasts of
|
||
[D7](#d7--pace) and, for windows longer than a day, today's use and the daily budget. Tiles of
|
||
one window kind show the same rows in the same order; a value that is not known yet shows a
|
||
muted placeholder that says why or from when. Then follow the per-day use of the long
|
||
windows, with each day's even pace and budget for its share and the instance start and reset
|
||
marked on the first and last day; token totals for today, the current session and the week of
|
||
[D9](#d9--the-snapshot-file-is-the-apps-only-output-to-other-processes), each saying since
|
||
when; charts, one window chart per limit
|
||
window, and the top entries by model and by project, with the rest folded into an expandable
|
||
"Other". A window chart is a burn-up of one instance from its start to its reset: the used
|
||
percent as a line (measured, or estimated before the first sample), the even-pace diagonal
|
||
from 0 % to 100 %, the forecast to the reset and the previous instance faintly behind, with no
|
||
point markers; under it, the peak each past instance reached. Tooltips are one component: a
|
||
title and a label/value grid. Diagnostics are collapsed. Provider colours are fixed (Claude orange, Codex blue, validated for colour vision
|
||
deficiency on both themes). Pace states use status colours with an icon and a label, never
|
||
colour alone.
|
||
- **Popups (R5).** A small borderless, topmost window that does not take focus, at the
|
||
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, with the
|
||
week's start and the id of the limit window it follows (`weekStart`, `weekWindow`). The week is
|
||
the current instance of the provider's weekly limit: its longest window over a day whose label
|
||
names no model family. Without one, it is the local calendar week from Monday, and `weekWindow`
|
||
is absent. The DTOs and their source-generated JSON context live in `FinalToken.Core`, shared by
|
||
the app, the CLI and the Stream Deck plugin. 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. Beside the limit tiles, "this week" reads as the limit's week, not the
|
||
calendar week (developer feedback, 2026-10-18).
|
||
|
||
**Gives up.** Updates faster than the reader's poll interval.
|
||
|
||
## 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.
|