Skip to content

Latest commit

 

History

History
428 lines (354 loc) · 20.6 KB

configuration.md

File metadata and controls

428 lines (354 loc) · 20.6 KB

Configuration

The trayapp reads a single YAML file at startup, resolved by config.ResolveConfigPath through the same directory chain as the prices.yaml override — in order: the directory containing trayapp.exe, the current working directory, %APPDATA%\usage_dashboard\, then ~/.config/usage-dashboard/. The schema is defined in internal/config/config.go; the keys below mirror that struct exactly. Values shown are the defaults Load applies when the field is absent — an empty file produces a fully-functional config.

First-run materialization

When no config.yaml exists anywhere in the chain, the trayapp writes one into the per-user config dir — config.UserConfigDir(): %APPDATA%\usage_dashboard\ on Windows, ~/.config/usage-dashboard/ elsewhere — from the embedded sample (repo-root config.sample.yaml, wired in via config_embed.go exactly like the price table) and loads it. The sample keeps the slack-activation profiles active — they're the setting users actually tune — and every other key commented out at its default, so the materialized file is behavior-neutral until edited. config_sample_test.go pins that neutrality: the sample must load to the same effective config as no file at all. A user's config.yaml is never overwritten or reconciled afterward, and the repo .gitignore excludes it so git pull deployments (pullrun.bat) never conflict with local edits. Because it is where uplink.token goes, the materialized file is created private to the user (mode 0600, and 0700 for a config dir created along with it; on Windows these modes have no effect). Existing files and directories keep their modes. Materialization failure (e.g. the config dir not writable) is non-fatal: the app logs a warning and runs on built-in defaults, exactly as it did before the file existed.

The target is deliberately not the executable's own directory. For a go installed binary that is GOBIN (~/go/bin) — a tool directory that should not accumulate application state and is not always writable. Because ResolveConfigPath still probes the exe dir first, a config.yaml sitting in a build checkout continues to take precedence, so the build-and-run-from-checkout workflow is unaffected.

database:
  # Absent or empty means "resolve automatically" — see "Database location"
  # below. An explicit value here is used as written.
  path: ""

http:
  port: 27812                       # must be 1-65535, else startup fails
  bind:
    - 0.0.0.0
    # Every interface by default; callers not on loopback must present the
    # access token — see docs/architecture.md "Network and security".
    # Listing specific addresses instead narrows the listener to them plus
    # 127.0.0.1 and any auto-detected Docker/WSL adapter IPs.

claude:
  projects_dir: "~/.claude/projects"   # %USERPROFILE%\.claude\projects on Windows
  # Root of the desktop app's Cowork ("local agent mode") session tree.
  # Each Cowork session nests its own private .claude home several levels
  # under this root, so a second tailer walks it recursively. Default
  # resolves to %APPDATA%\Claude\local-agent-mode-sessions on Windows;
  # empty (e.g. APPDATA unset) disables this second tailer.
  cowork_sessions_dir: "%APPDATA%\\Claude\\local-agent-mode-sessions"

# Price table used to compute cost_usd_equivalent when the source did not
# report it. See docs/data-model.md "Cost source" and "Price table
# resolution" below. Default is empty: the embedded built-in table is used
# unless a local prices.yaml override or this explicit path is present.
pricing:
  table_path: ""

tailer:
  poll_interval_ms: 1000

slack:
  baseline_max_age_seconds: 480     # baseline freshness gate (8 min)
  # Slack-activation profiles: [time_pct, remaining_pct] points, see
  # "Slack activation profiles" below. Absent (the default) means
  # "synthesize from the scalar thresholds beneath" — the values shown
  # here are that synthesis, i.e. the same behavior spelled out.
  session_profile:
    - [0, 98]
    - [52, 98]
    - [100, 50]
  weekly_profile:
    - [0, 80]
    - [30, 80]
    - [100, 10]
  session_surplus_threshold: 0.50   # profile-synthesis input (see below)
  weekly_surplus_threshold: 0.10    #   "
  session_absolute_threshold: 0.98  #   "
  weekly_absolute_threshold: 0.80   #   "

retention:                           # 0 keeps rows forever; negative is rejected
  parse_errors_days: 30
  slack_samples_days: 90

enable_slack_sampling: false        # writes to slack_samples on every /slack hit

logging:
  level: info
  file: ""                          # empty -> resolved; see "Log destination"

Log destination

logging.file is resolved by resolveLogFile in cmd/trayapp/logdest.go:

  1. A non-empty logging.file is used as written — an explicit setting is an instruction, not a hint.
  2. Otherwise, if a console is attached, logs go to stderr. This is the build-from-checkout case: the operator is watching the terminal, and diverting to a file would hide output they asked to see.
  3. Otherwise, logs go to a rotating trayapp.log in config.UserDataDir(), beside the database.

Rung three exists because a release binary is linked with -H=windowsgui (see the Makefile release target) and therefore has no console at all. Every write to stderr is silently discarded, so an unconfigured headless build would run blind — which is precisely how a startup failure such as an unopenable database becomes unreportable. consoleAttached decides this by calling GetConsoleWindow, which returns NULL for a process with no console; off Windows it is hardcoded true, since stderr there is always a real descriptor whether it is a terminal, a pipe, or captured by systemd.

The log sits in UserDataDir rather than UserConfigDir because it is mutable state, not configuration — on Windows that means Local, never the roaming profile.

A failure that stops startup (a config.yaml that does not load, an unopenable database, an unusable http.bind) is written to stderr and, when no console is attached, also to that log: through slog once the log is open, otherwise appended to the data-dir trayapp.log directly. So a headless build that never shows its icon still says why in trayapp.log, even when the failure is in the config that would have named a different log file.

If the rotating log cannot be renamed aside (on Windows, another process holding it open without delete sharing — a second instance, a log viewer), it is copied to .1 and truncated in place instead, with a warning at the top of the fresh file, so the size cap still holds.

Database location

database.path defaults to empty, not to a filename. config.Load leaves it that way on purpose and cmd/trayapp then calls config.ResolveDBPath, which picks, in order:

  1. $USAGE_DASHBOARD_DB, used verbatim — the explicit override.
  2. An existing usage.db in the current working directory. This is the build-from-checkout workflow: the exe runs from the repo root with its database beside it. Honoring an existing file means installing a newer binary never strands accumulated history in the old location. A directory named usage.db does not count.
  3. config.UserDataDir()/usage.db — the installed case: %LOCALAPPDATA%\usage_dashboard\usage.db on Windows, ~/.local/share/usage-dashboard/usage.db elsewhere.

Cases 2 and 3 always yield an absolute path, and cmd/trayapp MkdirAlls the parent directory before opening.

Local rather than Roaming on Windows is deliberate: a roaming profile would sync a live SQLite file and its -wal/-shm sidecars between machines. That is also why the data dir is separate from UserConfigDir() — configuration may roam with the user, a database must not.

Historically the default was the bare relative string "usage.db", applied in Load itself. That shadowed ResolveDBPath entirely — the caller only consults it when the path is empty — and pinned the database to whatever directory the process happened to start in. A go installed binary launched from a shell sitting in C:\Windows\system32 therefore tried to create its database there and failed with unable to open database file (14) (SQLITE_CANTOPEN). The MkdirAll guard did not catch it, because filepath.Dir("usage.db") is ".", which always exists.

Price table resolution

The model price table that computes cost_usd_equivalent (see docs/data-model.md "Cost source") is resolved at startup by ingest.ResolvePriceTable, which walks a precedence chain so a usable table is always available with zero configuration:

  1. Explicit pricing.table_path. If set and the file exists, it is loaded and wins. A malformed file here is fatal (the error is surfaced and cost computation is disabled) so a broken override is never silently masked. If the path is set but the file is missing, that is not fatal: a warning is logged and resolution falls through to steps 2–3. This is a deliberate choice — a stale or mistyped config path degrades to the built-in default rather than leaving cost uncomputed.
  2. Local prices.yaml override. With no explicit path (the default), the first prices.yaml found in these directories is loaded — in order: the directory containing trayapp.exe, the current working directory, %APPDATA%\usage_dashboard\, then ~/.config/usage-dashboard/. This is the no-rebuild override hook: drop a prices.yaml next to the exe to change rates.
  3. Embedded default. If nothing above matches, the canonical prices.yaml embedded in the binary at build time (repo-root prices.yaml, wired in via prices_embed.go) is parsed. This always succeeds.

The search order is defined by config.PriceTableSearchDirs. To update the built-in rates, edit the repo-root prices.yaml and rebuild.

Slack activation profiles

session_profile and weekly_profile define when the headroom gates pass, as piecewise-linear boundaries in the same coordinates as the dashboard burn-down charts:

  • Each point is [time_pct, remaining_pct]: at time_pct percent of the window elapsed, slack is available while the percent of quota remaining is at or above remaining_pct.
  • Between points the boundary interpolates linearly; before the first and after the last point it extends flat at that point's remaining_pct.
  • Validation (at load, fatal on failure): every point has exactly two values, both in [0, 100], with time_pct strictly increasing. An explicitly empty list is rejected; omit the key instead.
  • The weekly profile also gates the "Fable" weekly sub-row when the usage page reports one — the two rows share a window, so they share a boundary.
  • The dashboard's green slack zone is drawn from the same server-reported points (/api/dashboard/state → slack_profiles), so the chart and the gate cannot disagree.

The implementation is slack.Profile in internal/slack/profile.go; gate semantics and the full gate list live in docs/slack-indicator.md.

Legacy scalar thresholds

When a profile key is absent, it is synthesized from the four scalar thresholds (slack.SynthesizeProfile), reproducing the original two-leg gate exactly: pass when slack_fraction >= *_surplus_threshold (pace leg) OR percent_used <= 100 * (1 - *_absolute_threshold) (absolute-floor leg). In boundary form that is a flat floor at 100 * absolute until the pace line 100 * (1 + surplus) - elapsed_pct dips below it, then the pace line — which is exactly the default profiles shown in the YAML block above.

Scalar conventions (all fractions in [0, 1] of the full quota):

  • *_absolute_threshold: 1.0 disables the absolute branch (the floor sits at 100% remaining, reachable only at exactly-untouched quota).
  • *_absolute_threshold: 0.0 collapses the gate to "always pass".

A configured profile takes precedence; the scalars are then ignored.

The session headroom gate also has a disjunct independent of any threshold or profile — "session window absent entirely" — which short-circuits to true when there is no active session window. See docs/no-active-session.md for the wiring.

OAuth usage polling

oauth_usage reads the account's quota percentages straight from Anthropic's API using the access token Claude Code already stores, instead of waiting for the userscript to see the claude.ai usage page.

oauth_usage:
  enabled: false
  poll_interval_seconds: 180
  credentials_path: ""
  refresh_with_claude: false
  claude_path: ""

Off by default. It makes scheduled requests to Anthropic's API, which is not behavior an existing install should acquire merely by upgrading.

Enabling it does not disable the userscript. Both may run; their snapshots are tagged with different sources (oauth vs userscript) so the two can be compared rather than silently merged.

poll_interval_seconds is floored at 30, and the floor is enforced only when enabled — a stale value left behind in a disabled block should not block startup, since nothing polls. A value below the floor fails at load with the key named, rather than becoming a stream of requests at an undocumented endpoint. The 180-second default is deliberately unhurried: the figures move in whole percentage points.

credentials_path empty means "resolve the standard location", which honors CLAUDE_CONFIG_DIR and otherwise uses ~/.claude/.credentials.json. A literal default here would shadow that environment variable. The file is re-read on every poll, because Claude Code rewrites it when it rotates the token.

The access token lives about 8 hours and is refreshed only when Claude Code itself runs, so a machine idle overnight sees this source report temporarily unavailable until the next session — not a parse error, and no restart needed to recover. See docs/data-sources.md "Tier 2b" for why the poller does not refresh the token itself.

refresh_with_claude: true closes that gap by running claude -p /usage when the token is found stale; launching Claude Code refreshes the token. It takes effect only when enabled is also true. claude_path names the executable; empty means claude on PATH. The rules:

  • One attempt per stale episode. The attempt disarms the refresh, and only a successful poll re-arms it. A refresh that does not help (claude missing, logged out, or it simply did not rotate the token) is therefore not repeated at every interval. The source waits until the token recovers some other way, typically the user's next Claude Code session, and the next time it goes stale it gets one more try.
  • Only a stale credential triggers it: an expired token, a 401, or a missing credentials file or token. A server error or network failure does not, and does not spend the attempt.
  • Bounded. An attempt that runs past two minutes is killed. After every attempt the poll is retried straight away rather than an interval later, even when the command exited with an error: whether it worked is judged by re-reading the credential, so a run that rotated the token and then failed still recovers the source.
  • It runs with the per-user data dir as its working directory, so the transcript Claude Code writes lands in a project of its own. On Windows it runs with no console window.
  • Restarting the trayapp re-arms it, so each start can spend one attempt.

GET /api/oauth/status reports refresh_enabled, refresh_armed, last_refresh_attempt and last_refresh_error.

Uplink

uplink.url turns this trayapp into a sending instance: it forwards the usage events it records to another trayapp's POST /log. The motivating case is a VM running Claude Code against the same Anthropic account as the host — without forwarding, the host's event stream under-counts relative to the quota percentages the userscript scrapes, because Anthropic bills both against one account while only one machine records the tokens.

uplink:
  url: "http://192.168.56.1:27812"
  token: "<paste from the receiver's tray menu>"

Empty url (the default) disables forwarding. A host-role trayapp never sets it.

token is the receiver's access token, sent as a bearer token on every forwarded request. The receiver refuses any caller not on its loopback without it, so in practice every uplink needs it. Copy it on the receiving host from the tray menu, "Copy access token". Surrounding whitespace is trimmed. An empty token with a non-empty url is a startup warning, not an error.

When the receiver answers 401 — typically because its token was rotated — the sender holds its cursor and logs peer rejected the access token on each tick. Nothing is skipped: once token is updated and the sender restarted, the backlog drains.

The value is a base URL — scheme plus host plus optional port, with no path, query, or fragment. The forwarder appends endpoint paths itself. A malformed value is rejected at load rather than at first use: a typo that merely stopped forwarding would surface days later as a hole in the receiving host's data, long after the cause was out of mind.

What crosses the wire:

  • Events only. Quota snapshots are not forwarded — a VM has no browser on claude.ai, and percent-of-quota is the receiver's business anyway.
  • Tokens and model, not cost. The receiver prices events from its own prices.yaml, so a stale price table on the sender cannot skew the combined numbers.
  • Only events carrying both session_id and message_id. Those are the columns the receiver's uniqueness constraint covers, so they are the only ones where re-sending is provably safe.

Delivery is at-least-once and idempotent. The sender keeps a per-URL cursor (uplink_cursor) over usage_events.id and re-sends from it after a restart or an outage; duplicates collide on the receiver's UNIQUE(session_id, message_id) and are discarded with a duplicate flag rather than an error. Keying the cursor by URL means retargeting the uplink re-sends the backlog to the new receiver, which is what you want — the new receiver has none of it.

On the receiving host

The receiver needs no config at all: it binds every interface by default, and the sender's uplink.url may name it by IP address or by machine name (the Host check applies only to loopback callers). A receiver whose http.bind lists specific addresses must include one the sender can reach, such as the host's address on the VM's adapter (e.g. 192.168.56.1).

The access token lives in auth_token in the per-user data dir (%LOCALAPPDATA%\usage_dashboard\ on Windows), generated on first start. The tray menu copies it or rotates it; rotation refuses the old token from the next request on, without a restart. See docs/architecture.md, "Network and security".

Prefer a host-only adapter to a bridged one. The token keeps other machines on a shared LAN from writing to /log, but the traffic is plain HTTP, so a bridged adapter still exposes it to anyone watching that network.

The receiver clamps occurred_at on inbound events to a bounded window around its own clock and rejects anything outside it, mirroring the existing snapshot-timestamp validation. This is a backstop against a sender whose clock has jumped — a VM's clock after suspend/resume is the common case. Within the bound, skew is not corrected; see docs/design-decisions.md.

Path placeholders

%APPDATA%, %LOCALAPPDATA%, %USERPROFILE%, and %HOME% placeholders are expanded inside database.path, claude.projects_dir, claude.cowork_sessions_dir, pricing.table_path, logging.file, oauth_usage.credentials_path and oauth_usage.claude_path at load time. Placeholder names match case-insensitively, as Windows environment variable names do, so %LocalAppData% works too. When the underlying environment variable is unset (typical on Linux), the loader falls back to the user's home directory so cross-platform configs stay testable.

claude.projects_dir additionally expands a leading ~/ (or ~\ on Windows) to the user's home directory.

Reload semantics

The file is read once at start. Changes require a restart — there is no SIGHUP reload and no in-process reload trigger. This is Windows-first and the simplification is worth it; the YAML is short and changes are infrequent.

The slack-signal pause flag is not part of this file. Pause is a transient operator override toggled from the tray menu and held only in memory; see docs/design-decisions.md for the rationale and docs/slack-indicator.md for the gate.

Sources of truth

  • The Go struct in internal/config/config.go is authoritative for shape and defaults. If this document drifts from it, the struct wins.
  • Threshold meanings (the slack: block) are documented in docs/slack-indicator.md.
  • Path placeholder expansion lives in internal/config/config.go's expandPlaceholders / expandHome.