diff --git a/CHANGELOG.md b/CHANGELOG.md index 33cbdb5..1660043 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,12 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- `cotel --backfill-cost` (dry run) and `--backfill-cost-apply` recompute `cost_usd` for every span of a priced model from its stored token counts at today's rates, revived from the closed PR #67 as reviewed there (FLO-551/552). Spans with an unknown or empty model are counted and left alone; `daily_usage` is not touched, because a day rolled up after the backfill derives its cost from the corrected spans. The apply needs the database to itself, so it runs while the server is stopped; the dry run restores the newest snapshot into a throwaway file instead of copying a live one. README → Maintenance commands has both procedures for the current compose deploy, with `--entrypoint` set so a one-off does not start a second Cloudflare tunnel connector - A synthetic reproducer for the ART-index corruption that took production down in September 2026: `TestARTIndexSurvivesAddedColumnAndBulkReplace` in `internal/storage/art_repro_test.go`, built from the schema with no production bytes — every value is derived from the row number, so it carries no user id, session id or span attribute that belonged to anyone. It rebuilds the trigger rather than a statement from it: `spans` as it stood at schema version 2 — without `user_id`, and *with* the mid-table `duration_ms` generated column, so that the one ALTER production ran on a long-lived filled table (v9 → v10, six weeks before the abort) runs here too instead of passing over a column the fixture never had, and so the indexes are built over the logical/physical column skew they were built over in production — with that era's three ART indexes, filled across the 30-day retention boundary; `storage.Open` then runs the real `schema.sql`, which adds `user_id VARCHAR` to the filled indexed table and puts `idx_spans_user_id` on that added column; a bulk `UPDATE` writes the column, cotel's own retention roll-up supplies the large replace transaction (the `INSERT INTO daily_usage` and the `DELETE FROM spans` are one transaction, so it is the real mutation and not an imitation); then checkpoint, close, reopen, checkpoint, ingest more, repeat. The repetition is the point — the damage accumulates and production ran for weeks after its migration before an open aborted — and so is the restart: this class of fault is only ever reported by the checkpoint that folds the index or the open that reads it back. Each pass asserts that `duration_ms` was there before the migration and is gone after it (a `DROP COLUMN IF EXISTS` that no-ops must not be able to come back unnoticed), that the reopen succeeds, that both checkpoints fold — a present-but-empty `.wal` counts as folded, so an engine that truncates rather than unlinks is not reported as this defect — that all four indexes survive, that a bare `user_id = ` folded into the scan agrees with the same predicate wrapped in an expression, which is not, and that re-inserting a stored `span_id` is still rejected while an unused one is accepted. The last two are the silent form of the damage: a wrong answer rather than an error. They are phrased that way because no `SELECT` over `spans` is planned as an ART index scan on this engine — measured, including on the primary key and on a textbook unique match with the thresholds raised — so an “indexed probe agrees with an unindexed probe” assertion would have been two sequential scans agreeing; the pushdown pair is what [ADR-0013](docs/decisions/0013-spans-has-no-derived-columns.md)'s wrong answers actually came out of, and unique-constraint enforcement is the one path that provably traverses an ART index. It runs in the ordinary test set rather than behind a build tag, because the moment it most needs to run is a driver or engine bump and that is exactly when an optional test is forgotten; `COTEL_ART_REPRO_SPANS` and `COTEL_ART_REPRO_CYCLES` scale it past the defaults (20 000 spans, 2 cycles, 4.1 s). Against the engine the tree links today — `duckdb-go/v2 v2.10506.0`, `SELECT version()` → `v1.5.6` — it did **not** reproduce, at the defaults or at 200 000 spans over 6 cycles. That measures the half of the forensic volume's release condition that was previously unevaluable, and measures it negative rather than exonerating: upstream reports the same class of fault on 1.5.5 against a ~19 GB database, the file that was damaged here took weeks of ingest to get there, and two clean runs at our scale are not absence ([docs/operations/duckdb-recovery.md](docs/operations/duckdb-recovery.md)) ### Changed +- **Users are now actors, down to the schema** ([ADR-0027](docs/decisions/0027-users-become-actors.md)). What a token belongs to was never only a person: production holds one person, one host and fifteen Paperclip agents. Schema v11 renames the `users` table to `actors` and `spans.user_id` / `daily_usage.user_id` to `actor_id`; the API moves to `/api/v1/actors`, `?actor_id=` and `actors_count`; the dashboard's Users page becomes Actors at `/actors`; export archives become `format_version` 2. The rename runs in Go before `schema.sql`, because a rename cannot be idempotent in SQL and `CREATE TABLE IF NOT EXISTS actors` would otherwise create an empty twin beside the populated table; it checks the catalog per step, drops and lets `schema.sql` recreate the `spans` indexes (DuckDB will not ALTER an indexed table), commits as one transaction, and refuses to start if both tables exist. Requests using the old names keep working - `/api/v1/users`, `?user_id=`, `mode=user_only|user_and_history`, the `/users` dashboard URLs, and v1 export archives - but **response bodies use the new field names only**, and **an older binary cannot open a migrated file without losing its tokens**: rolling back across v11 means restoring a pre-v11 snapshot - `docker compose build` tags its result `cotel-local:latest` instead of `ghcr.io/flopsstuff/cotel:latest`. Compose treats `image:` next to `build:` as the name to tag the local build with, so the published name was being reused for an artifact that never came from the registry: on the production host — where the deploy is `docker compose build --pull` followed by `up -d`, and `--pull` refreshes the Dockerfile's base images rather than the app image — `Image=ghcr.io/flopsstuff/cotel:latest` named a locally built binary, and built-here and pulled-from-registry were the same string. Three things follow from splitting them. You can read which artifact a host is running off the name. The thing the release pipeline publishes, and which `release.yml` moves only on an explicit dispatch, is no longer shadowed by every merge to `main`. And `docker pull ghcr.io/flopsstuff/cotel:latest` on the production host stops being able to swap the running service's binary at its next restart for content no deploy step validated — it now lands on a name nothing there runs. Production still *builds* its image, deliberately: a pull-only production would mean a merge to `main` no longer changes production, which is a separate decision from this cleanup and would need its own ADR. The operations pages name both images where the distinction matters — the recovery procedure's "match the CLI to the version linked into cotel" step asks `cotel-local:latest` on a host that builds its own image — and they also record that `ghcr.io/flopsstuff/cotel:latest` is now a multi-arch index whose `linux/arm64` entry runs natively on a Pi or Apple Silicon, so the documented `docker run --entrypoint /usr/local/bin/cotel … --db-query` and `--db-import` commands are honest on arm64 without a local build ([docs/operations/duckdb-recovery.md](docs/operations/duckdb-recovery.md), [docs/operations/duckdb-snapshots.md](docs/operations/duckdb-snapshots.md)) ### Fixed +- Spans from the Claude 5.5 / 5.2 generation are priced. From 2026-11-07 every span from `claude-opus-5-5`, `claude-fable-5-2` and `claude-haiku-5-5` was stored with `cost_usd` unset because the price table did not know them, so the dashboard showed $0 for a week of real traffic. Adds Opus 5.5 ($4/$20), Sonnet 5.5 ($2/$10), Haiku 5.5 ($0.10/$0.50; its $0.50/$2.50 rate for prompts over 100K tokens is not modelled, since a span does not say which tier billed it), Fable and Mythos 5.2 ($8/$40) and 5.1 ($10/$50), with the published cache-read rates where they depart from 0.1 x input. Sonnet 5 moves from $3/$15 to the $2/$10 Anthropic still publishes. `pricing.Known` tells an unpriced model from a priced span that costs zero. Already-stored spans keep their unset cost until `--backfill-cost-apply` runs - The Deploy workflow stops asking the production host's GUI keychain for credentials it does not hold, and stops being able to hold the deploy queue indefinitely when something does hang. `docker compose build --pull` makes buildkit resolve the Dockerfile frontend and the base images, which makes the docker CLI consult the credential store named in the host's `~/.docker/config.json`. On the production runner that store is `desktop`, whose helper is tied to the logged-in GUI session: spawned from the runner's launchd session it blocks in `open(2)` and never returns, buildkit re-spawns it on every retry, and a single hung call also stalls image resolution for any other build on that host (measured: a hand build from an interactive shell, normally 2.6 s, sat 4 min behind one). Nothing in the run log said so, because the hang lands before the first layer and the step's last line is the frontend resolve. The same helper call from an interactive shell on the same host answers in milliseconds, so both the hosted-runner smoke build and a hand build on the deploy host passed throughout. The job now builds against a copy of the config carrying the host's contexts and CLI plugins but no credential store at all, which is faithful to what the host actually has: its `auths` map is empty, and registry auth, if it is ever needed there, belongs in an explicit `docker login` with a repository secret rather than in one person's keychain. The deploy job also gains `timeout-minutes: 20`. The first wedge ran for nine hours and, because `deploy-main` has `cancel-in-progress: false`, every push behind it sat `pending` with no job at all, which is indistinguishable from an idle queue: production kept serving a build five days old, the next runtime fix would silently not have shipped, and no run ever went red to say so. A hung build now fails loudly and releases the group instead. ## [0.4.0] - 2026-10-13 diff --git a/README.md b/README.md index 38927b2..436a94c 100644 --- a/README.md +++ b/README.md @@ -8,13 +8,13 @@ One Docker container. OTLP ingest on `:4318`, interactive analytics dashboard on ## What you get -- **Overview dashboard** — one range switcher in the header (All / Year / Month / Week / Day, default 30 days) that every figure on the page obeys: the KPI cards for sessions, users, total cost and token counts, and the Span activity / Users / Spans & cost / Tools / Models / Sessions blocks below them. The Span activity grid is a GitHub-style block of cells counting spans, and the range picks how much time a cell is — a day over a year, four hours over a month, an hour over a week, ten minutes over a day. The Spans & cost block charts spans and spend together on one field — spans in blue against the left axis, cost in amber against the right — so a spend spike lands under the activity that caused it. The Users block ranks your top 5 principals by spend in the selected range. Arriving with `?user_id=` scopes the whole page to one user, with a chip in the header to clear it -- **Sessions** — live table of every Claude Code session with user, model, duration, cost, and status (OK / ERROR); search by user and click any user to filter the table to their sessions +- **Overview dashboard** — one range switcher in the header (All / Year / Month / Week / Day, default 30 days) that every figure on the page obeys: the KPI cards for sessions, actors, total cost and token counts, and the Span activity / Actors / Spans & cost / Tools / Models / Sessions blocks below them. The Span activity grid is a GitHub-style block of cells counting spans, and the range picks how much time a cell is — a day over a year, four hours over a month, an hour over a week, ten minutes over a day. The Spans & cost block charts spans and spend together on one field — spans in blue against the left axis, cost in amber against the right — so a spend spike lands under the activity that caused it. The Actors block ranks your top 5 principals by spend in the selected range. Arriving with `?actor_id=` scopes the whole page to one actor, with a chip in the header to clear it +- **Sessions** — live table of every Claude Code session with actor, model, duration, cost, and status (OK / ERROR); search by actor and click any actor to filter the table to their sessions - **History** — time-series and daily-activity heatmaps for sessions and token spend over time. The day, week and month series keep charting after retention has rolled raw spans into daily totals; the hourly series and both heatmaps need a per-span timestamp, so they cover raw days only and say from when - **Costs** — cumulative spend chart + breakdown table by model - **Tools** — call counts, average duration, and error rate per tool (`Bash`, `Read`, `Edit`, …), scoped to a range switcher (All / Year / Month / Week / Day, default 30 days), plus a per-command breakdown of `Bash` calls - **Models** — token and cost breakdown across all Claude model variants -- **Users** — one sortable, searchable list with per-user cost and sessions scoped to a range switcher (All / Year / Month / Week / Day, default 30 days); click any row for that user's page — token, rotate, delete, and links into their activity and sessions +- **Actors** — one sortable, searchable list with per-actor cost and sessions scoped to a range switcher (All / Year / Month / Week / Day, default 30 days); click any row for that actor's page — token, rotate, delete, and links into their activity and sessions - **Setup** — step-by-step onboarding guide with copy-paste `settings.json` snippets pre-filled with your ingest URL and token - **Export / Import** — download all data as a versioned ZIP/CSV archive; restore it on a fresh instance - **Cloudflare Tunnel** — publish cotel over HTTPS with a single env var; bearer-token auth for OTLP, Zero Trust for the dashboard @@ -25,8 +25,8 @@ Every screenshot here is one instance seeded with synthetic telemetry — see [D | | | |:--|:--| -| **Sessions** — every session with its user, model, tokens, cost and OK / ERROR status
![Sessions](docs/assets/dashboard-sessions.png) | **Costs** — daily spend and cost by model across the window you pick
![Costs](docs/assets/dashboard-costs.png) | -| **Users** — cost and session count per principal for the selected range
![Users](docs/assets/dashboard-users.png) | **Tools** — call count, average duration and error rate per tool
![Tools](docs/assets/dashboard-tools.png) | +| **Sessions** — every session with its actor, model, tokens, cost and OK / ERROR status
![Sessions](docs/assets/dashboard-sessions.png) | **Costs** — daily spend and cost by model across the window you pick
![Costs](docs/assets/dashboard-costs.png) | +| **Actors** — cost and session count per actor (person, agent or host) for the selected range
![Actors](docs/assets/dashboard-actors.png) | **Tools** — call count, average duration and error rate per tool
![Tools](docs/assets/dashboard-tools.png) | ## Quick start @@ -46,7 +46,7 @@ Open **http://localhost:8080** → **Setup** for the guided onboarding. ## Demo data An empty cotel shows empty charts, which makes it hard to judge. `scripts/seed-demo.py` -fills a throwaway instance with a synthetic team — seven users, three models, 90 days +fills a throwaway instance with a synthetic team — seven actors, three models, 90 days of sessions and tool calls — over the real OTLP endpoint, so what you see is what ingest actually produces: @@ -55,7 +55,7 @@ python3 scripts/seed-demo.py --dash-url http://localhost:8080 \ --ingest-url http://localhost:4318 ``` -It only creates users and ingests spans; it never deletes. Point it at an instance +It only creates actors and ingests spans; it never deletes. Point it at an instance you are willing to throw away, not at one holding real telemetry. The screenshots in this README come from exactly this seed — the recipe is in [docs/operations/screenshots.md](docs/operations/screenshots.md). @@ -78,19 +78,19 @@ Add to your `~/.claude/settings.json`: Restart Claude Code. Telemetry starts flowing immediately. -## Users and authentication +## Actors and authentication -cotel ships with token-based authentication for OTLP ingest. Tokens are tied to named users. +cotel ships with token-based authentication for OTLP ingest. Tokens are tied to named **actors**: whoever sends telemetry, whether a person, an AI agent or a host. -Open the dashboard → **Users** (people icon in the sidebar) → **Add user**. Give the user a name (e.g. the machine or agent name sending telemetry) and copy the token from the banner. The token is retrievable any time from that user's page (click the row); rotating or deleting a user revokes its token immediately. +Open the dashboard → **Actors** (people icon in the sidebar) → **Add actor**. Give the actor a name (e.g. the machine or agent name sending telemetry) and copy the token from the banner. The token is retrievable any time from that actor's page (click the row); rotating or deleting an actor revokes its token immediately. By default, cotel accepts spans without an `Authorization` header (allow-anonymous mode). To enforce strict auth: open **Setup** → **Settings** tab → disable **Allow anonymous OTLP**. Requests without a valid token then receive `401 Unauthorized`. -See **[docs/operations/users-and-auth.md](docs/operations/users-and-auth.md)** for the full guide: multi-user setup, token rotation, and security considerations. +See **[docs/operations/actors-and-auth.md](docs/operations/actors-and-auth.md)** for the full guide: one token per sender, token rotation, and security considerations. ## Publishing with Cloudflare -Use [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) to expose cotel over HTTPS without opening inbound ports. The dashboard is protected by Cloudflare Zero Trust; OTLP ingest is protected by a bearer token you create in the cotel Users page. +Use [Cloudflare Tunnel](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/) to expose cotel over HTTPS without opening inbound ports. The dashboard is protected by Cloudflare Zero Trust; OTLP ingest is protected by a bearer token you create in the cotel Actors page. ### Prerequisites @@ -137,7 +137,7 @@ No `-p` flags are needed — Cloudflare Tunnel uses outbound connections only. ### 5. Create an agent token -Open your dashboard URL (e.g. `https://cotel.yourdomain.com`), go to **Users** in the sidebar, and click **Add user**. Give it a name (e.g. the agent's hostname or machine name) and copy the token. +Open your dashboard URL (e.g. `https://cotel.yourdomain.com`), go to **Actors** in the sidebar, and click **Add actor**. Give it a name (e.g. the agent's hostname or machine name) and copy the token. ### 6. Configure Claude Code @@ -158,7 +158,7 @@ Add to your `~/.claude/settings.json`: Replace `cotel-ingest.yourdomain.com` with your actual OTLP hostname, and `cotel_` with the token you copied above. Restart Claude Code to apply the changes. -> **Token enforcement:** cotel accepts anonymous spans until the first user with a token is created. Once any token exists, every OTLP request must carry a valid `Authorization: Bearer cotel_...` header — unless you explicitly re-enable Allow anonymous OTLP in Setup → Settings. +> **Token enforcement:** cotel accepts anonymous spans until the first actor with a token is created. Once any token exists, every OTLP request must carry a valid `Authorization: Bearer cotel_...` header — unless you explicitly re-enable Allow anonymous OTLP in Setup → Settings. ## Ports @@ -553,6 +553,54 @@ from the network at startup instead of bundling it). | `COTEL_ART_REPRO_CYCLES` | `2` | Read by the ART-corruption reproducer test, not by the binary: how many replace-transaction-then-restart cycles it runs. The damage accumulates across cycles, so this is the other knob to raise. | | `COTEL_DATA_VOLUME` | `cotel-data-repaired-20261004` | Read by `docker-compose.yml`, not by the binary: the Docker volume mounted at `/data`. Point it at a restored copy to bring an instance up *without* writing to the volume being restored from — Docker has no `volume rename`, so the only other way to serve repaired data under the expected name is to overwrite the damaged original, which is also the forensic evidence. The default is a restored copy, not the `cotel_cotel-data` name compose derives by itself: that volume holds a database the binary can no longer open and is kept untouched as evidence. A fresh install that has neither volume gets the default created empty, which is correct. | +## Maintenance commands + +### Cost backfill + +When the pricing table gains a model or corrects a rate after spans were already ingested, those +spans keep the `cost_usd` they were stored with (unset for a model the table did not know). +`--backfill-cost` recomputes `cost_usd` from each span's stored token counts at today's rates. + +> **The running server holds an exclusive DuckDB lock.** No second process can open +> `/data/cotel.duckdb` while the container is up, not even read-only (`Could not set lock on file +> ... Conflicting lock is held`), so neither command can be run with `docker exec` against the live +> file. The dry run reads a database restored from the newest snapshot (no downtime); the apply runs +> against the volume while the server is stopped (brief downtime). + +Both one-offs below pass `--entrypoint /usr/local/bin/cotel` (or `sh`) so the image entrypoint +does not start a second Cloudflare tunnel connector next to the server's, and `--no-deps` so nothing +else is started. + +**Step 1 - dry run against the newest snapshot (no writes, no downtime):** + +```bash +# Snapshot paths are absolute; pick the newest directory under /snapshots. +docker compose run --rm --no-deps -e COTEL_DB_PATH=/tmp/dry.duckdb --entrypoint sh cotel -c \ + 'cotel --db-import "$(ls -d /snapshots/20* | tail -1)" && cotel --backfill-cost' +``` + +It prints a per-model table of old and new cost and the total delta. Spans with an unknown or empty +model are counted separately and left untouched. The snapshot is up to `COTEL_SNAPSHOT_INTERVAL` +old, so the totals are an estimate of what the apply will do. + +**Step 2 - apply (after reviewing the dry run):** + +```bash +docker compose stop cotel +docker compose run --rm --no-deps --entrypoint /usr/local/bin/cotel cotel --backfill-cost-apply +docker compose start cotel +``` + +It updates `cost_usd` on every span of a priced model. It is idempotent: cost is recomputed from the +stored token counts, not scaled, so a second run changes nothing. + +> **Scope - `spans` only.** `daily_usage` is not touched. The retention roll-up derives +> `total_cost_usd` as `SUM(spans.cost_usd)`, so a day rolled up *after* the backfill is correct by +> construction. A day already rolled up keeps the cost it was rolled up with: roll-ups written +> before schema v8 kept no cache-token totals, and on real traffic cache tokens outnumber input and +> output ~156:1, so a recompute from the stored counters would understate the cost. Run the backfill +> before the affected days leave the raw window (`COTEL_RETENTION_RAW_DAYS`, 30 days by default). + ## Architecture ``` diff --git a/cmd/cotel/main.go b/cmd/cotel/main.go index 9d89363..9d86835 100644 --- a/cmd/cotel/main.go +++ b/cmd/cotel/main.go @@ -31,6 +31,8 @@ func main() { dbQuery := flag.String("db-query", "", "run SQL query against DuckDB, print first column of first row, and exit") dbImport := flag.String("db-import", "", "restore COTEL_DB_PATH from the snapshot directory given, verify it against the snapshot manifest, and exit; the target database file must be empty or absent") healthcheck := flag.Bool("healthcheck", false, "probe the local dashboard /healthz and exit 0 (ready) or 1; used by the container HEALTHCHECK") + backfillCost := flag.Bool("backfill-cost", false, "dry-run: show what recalculating cost_usd from stored token counts would change (no writes), then exit") + backfillCostApply := flag.Bool("backfill-cost-apply", false, "recalculate cost_usd for all spans of priced models from their stored token counts, then exit") flag.Parse() dbPath := env("COTEL_DB_PATH", "/data/cotel.duckdb") @@ -67,6 +69,12 @@ func main() { return } + // The backfill needs the database file to itself (DuckDB has one writer), so + // like --db-import it runs before the listeners bind and exits afterwards. + if *backfillCost || *backfillCostApply { + os.Exit(runBackfill(dbPath, *backfillCostApply)) + } + // Bind BEFORE storage.Open: WAL replay + schema migration can block for // minutes on a large DB, and a bound port answering a retryable 503 keeps // OTLP clients retrying where a connection reset would drop their spans. @@ -122,7 +130,7 @@ func main() { ingestMux.Handle("/v1/traces", auth.Middleware(db, ingest.New(db))) ro := db.ReadOnly() - apiHandler := api.New(ro).SetPublicIngestURL(parsePublicIngestURL(os.Getenv("COTEL_PUBLIC_INGEST_URL"))).SetUserStore(db) + apiHandler := api.New(ro).SetPublicIngestURL(parsePublicIngestURL(os.Getenv("COTEL_PUBLIC_INGEST_URL"))).SetActorStore(db) dashMux := http.NewServeMux() dashMux.Handle("/api/v1/export", auth.Middleware(db, export.NewHandler(db))) dashMux.Handle("/api/v1/import", auth.Middleware(db, importpkg.NewHandler(db))) @@ -151,6 +159,57 @@ func main() { os.Exit(code) } +// runBackfill opens the database, recomputes cost_usd and prints a per-model +// report. apply=false is a dry run that writes nothing. +func runBackfill(dbPath string, apply bool) int { + db, err := storage.Open(dbPath) + if err != nil { + log.Printf("open storage: %v", err) + return 1 + } + defer db.Close() + + var rep storage.BackfillReport + if apply { + fmt.Println("=== APPLYING cost_usd backfill ===") + rep, err = db.BackfillCostUSD() + } else { + fmt.Println("=== DRY RUN (no writes) - pass --backfill-cost-apply to apply ===") + rep, err = db.DryRunBackfill() + } + if err != nil { + log.Printf("backfill: %v", err) + return 1 + } + printBackfillReport(rep, apply) + return 0 +} + +// printBackfillReport prints a BackfillReport to stdout. +func printBackfillReport(rep storage.BackfillReport, applied bool) { + verb := "would change" + if applied { + verb = "changed" + } + fmt.Printf("\n%-35s %8s %12s %12s %12s\n", + "model", "spans", "old_cost_usd", "new_cost_usd", "delta_usd") + fmt.Println(strings.Repeat("-", 87)) + for _, row := range rep.ModelRows { + fmt.Printf("%-35s %8d %12.4f %12.4f %+12.4f\n", + row.Model, row.SpanCount, row.OldCostUSD, row.NewCostUSD, row.DeltaUSD) + } + fmt.Println(strings.Repeat("-", 87)) + fmt.Printf("total delta_usd: %+.4f (spans that %s: %d)\n", + rep.TotalDeltaUSD, verb, rep.SpansToUpdate) + if rep.UnknownModel > 0 { + fmt.Printf("unknown model (skipped): %d spans\n", rep.UnknownModel) + } + if rep.EmptyModel > 0 { + fmt.Printf("empty/null model (skipped): %d spans\n", rep.EmptyModel) + } + fmt.Println() +} + // shutdownCheckpointTimeout bounds a CHECKPOINT so a stuck fold cannot hang // the process. On shutdown it stays inside the container stop grace period // (docker-compose stop_grace_period); on startup it keeps a wedged fold from diff --git a/docs/.vitepress/config.js b/docs/.vitepress/config.js index 0b568c6..4627518 100644 --- a/docs/.vitepress/config.js +++ b/docs/.vitepress/config.js @@ -25,7 +25,7 @@ export default defineConfig({ { text: 'Operations', items: [ - { text: 'Users and Authentication', link: '/operations/users-and-auth' }, + { text: 'Actors and Authentication', link: '/operations/actors-and-auth' }, { text: 'JSON API Reference', link: '/operations/api-reference' }, { text: 'Cloudflare Tunnel — Token Mode', link: '/operations/cloudflare-tunnel-remote' }, { text: 'Cloudflare Tunnel — Local Config', link: '/operations/cloudflare-tunnel-local' }, @@ -67,6 +67,7 @@ export default defineConfig({ { text: 'ADR-0024 - Off-Host Snapshot Copy is a Pi-Side Pull', link: '/decisions/0024-off-host-snapshot-copy-pi-pull' }, { text: 'ADR-0025 - Best-Effort Ingest Watcher in Actions', link: '/decisions/0025-best-effort-ingest-watcher-in-actions' }, { text: 'ADR-0026 - The Deploy Host Asks /healthz on a Schedule', link: '/decisions/0026-scheduled-loopback-probe-with-a-pager' }, + { text: 'ADR-0027 - Users Become Actors', link: '/decisions/0027-users-become-actors' }, ], }, ], diff --git a/docs/assets/dashboard-users.png b/docs/assets/dashboard-actors.png similarity index 100% rename from docs/assets/dashboard-users.png rename to docs/assets/dashboard-actors.png diff --git a/docs/decisions/0008-per-agent-telemetry-identity.md b/docs/decisions/0008-per-agent-telemetry-identity.md index 3532166..f62e747 100644 --- a/docs/decisions/0008-per-agent-telemetry-identity.md +++ b/docs/decisions/0008-per-agent-telemetry-identity.md @@ -113,6 +113,6 @@ Tracked as a child rollout issue of FLO-486. - FLO-486 (this), FLO-485 (root-cause investigation) - `docs/operations/agent-identity.md` — the per-agent identity scheme (git + cotel) -- `docs/operations/users-and-auth.md` — cotel users & tokens +- `docs/operations/actors-and-auth.md` — cotel users & tokens - ADR-0004 — Multi-User Separation - `scripts/agent-set-cotel-token.sh`, `scripts/agent-set-git-identity.sh` diff --git a/docs/decisions/0027-users-become-actors.md b/docs/decisions/0027-users-become-actors.md new file mode 100644 index 0000000..93673a7 --- /dev/null +++ b/docs/decisions/0027-users-become-actors.md @@ -0,0 +1,81 @@ +# ADR 0027 — Users become actors, down to the schema + +**Date:** 2026-11-15 +**Status:** Accepted +**Deciders:** Flop (board) + +--- + +## Context + +cotel attributes every span to whoever owns the bearer token it arrived with. +Since ADR-0004 that owner has been called a **user**: the `users` table, the +`spans.user_id` and `daily_usage.user_id` columns, `/api/v1/users`, the Users +page. + +What production actually holds is not users. On 2026-11-15 the list was one +person (`flop`), a host (`rpi5`) and fifteen Paperclip agents (Daedalus, Clio, +Wayland, ...), each with its own token since ADR-0008. "User" describes the +smallest group there and misleads about the rest: an agent is not someone who +signs in, and "Add user" reads as an access-control action when it only mints an +ingest identity. + +## Decision + +The entity is an **actor**: whoever sends telemetry, whether a person, an AI +agent or a host. The rename goes all the way down, so the code, the API, the +database and the UI use one word: + +| Layer | Before | After | +|---|---|---| +| Table | `users` | `actors` | +| Attribution column | `spans.user_id`, `daily_usage.user_id` | `actor_id` | +| Index | `idx_spans_user_id` | `idx_spans_actor_id` | +| API | `/api/v1/users`, `?user_id=`, `users_count`, `mode=user_only` | `/api/v1/actors`, `?actor_id=`, `actors_count`, `mode=actor_only` | +| Export format | v1, column `user_id` | v2, column `actor_id` at the same offset | +| UI | Users page, `/users` | Actors page, `/actors` | + +The column still holds the actor's **name**, as `user_id` did; only the name of +the column changes. + +### How the schema moves (v10 → v11) + +A rename cannot be written idempotently in SQL, and `schema.sql` is re-applied +whenever its hash changes (ADR-0010). Left in that file, the rename would fail on +every re-apply after the first; worse, `CREATE TABLE IF NOT EXISTS actors` and +`ADD COLUMN IF NOT EXISTS actor_id` would quietly create an empty table and an +empty column next to the populated originals. So `migrateUsersToActors` in +`internal/storage/duckdb.go` runs **before** `schema.sql`: + +- it reads the catalog and renames only what still carries the old name, so a + fresh database, a migrated one and a re-apply are all no-ops; +- it drops the secondary indexes on `spans` first, because DuckDB refuses to + ALTER a table an index depends on, and `schema.sql` recreates them right + after, as it already does for the v9 → v10 change (ADR-0013); +- all steps commit in one transaction; +- if both `users` and `actors` exist it refuses to start rather than guess which + one holds the real tokens. + +It is tested against a database built from a frozen copy of the v10 +`schema.sql` (`internal/storage/testdata/schema_v10.sql`). + +### Compatibility kept + +- `/api/v1/users[/...]`, `?user_id=` and `mode=user_only|user_and_history` are + accepted as aliases. Response bodies use the new field names only. +- `/users` and `/users/:id` in the dashboard redirect to `/actors`. +- The importer reads both v1 (`user_id`) and v2 (`actor_id`) export files. +- A snapshot taken before v11 restores as it was written (`--db-import` checks + its own table list) and is migrated by the next open. + +## Consequences + +- **Breaking for API consumers that read fields:** `users_count` and `user_id` + in responses are now `actors_count` and `actor_id`. Requests keep working. +- **Export files are format v2.** A v2 file cannot be imported by a cotel older + than this change. +- **No rollback across v11 without a restore.** An older binary opening a + migrated file finds no `users` table and creates an empty one, so every token + stops authenticating. Rolling back means restoring a pre-v11 snapshot. +- The ADRs and incident write-ups written before this change keep the old names; + they describe the schema as it was. diff --git a/docs/decisions/index.md b/docs/decisions/index.md index 2534b04..6a394df 100644 --- a/docs/decisions/index.md +++ b/docs/decisions/index.md @@ -34,3 +34,4 @@ New ADRs go in this directory as `NNNN-short-title.md`, numbered sequentially. | [ADR-0024](./0024-off-host-snapshot-copy-pi-pull) | The off-host copy is a Pi-side pull, and it cannot be an rsync of the volume | Rescinded by the owner 2026-10-19 | | [ADR-0025](./0025-best-effort-ingest-watcher-in-actions) | cotel is watched by a best-effort ingest probe in GitHub Actions | Accepted | | [ADR-0026](./0026-scheduled-loopback-probe-with-a-pager) | The deploy host asks `/healthz` on a schedule, and it pages | Accepted | +| [ADR-0027](./0027-users-become-actors) | Users become actors, down to the schema | Accepted | diff --git a/docs/design/pages.md b/docs/design/pages.md index 1565f08..06e678b 100644 --- a/docs/design/pages.md +++ b/docs/design/pages.md @@ -96,7 +96,7 @@ These are rendered by a shared `` component that wraps every page's | Region | Component | Field | Source | Format | |---|---|---|---|---| | KPI row | `` | Sessions | `GET /overview → total_sessions` | Integer | -| KPI row | `` | Active Users | `GET /overview → users_count` | Integer — principals with usage in the range, not the registered-user total the Users page lists | +| KPI row | `` | Active Actors | `GET /overview → actors_count` | Integer — actors with usage in the range, not the registered total the Actors page lists | | KPI row | `` | Total Cost | `GET /overview → total_cost_usd` | `$0.00` | | KPI row | `` | Input Tokens | `GET /overview → total_input_tokens` | `1.2M`, `890K`, `12.4K` | | KPI row | `` | Output Tokens | `GET /overview → total_output_tokens` | Same | @@ -130,9 +130,9 @@ a "View all" link to its full page, in this order: `Day`. Cells outside the queried window — the leading edge, and the rest of today — are drawn as an outline, never as an empty cell ([ADR-0016](../decisions/0016-overview-activity-grid.md)). -2. **Users** — top 5 by spend in the range. Hidden while the page is scoped to a - single user via `?user_id=`, where a top-5-users table would be the one panel - on the page not answering for that user. +2. **Actors** — top 5 by spend in the range. Hidden while the page is scoped to a + single actor via `?actor_id=`, where a top-5-actors table would be the one panel + on the page not answering for that actor. 3. **Spans & cost** — spans as a filled area against the left axis and cost as a line against the right, from one `/history` call. `hour` granularity on the `Day` range, `day` otherwise; links to both full pages @@ -144,7 +144,7 @@ a "View all" link to its full page, in this order: The header carries one `` bound to `RANGE_OPTIONS` and persisted in the `cotel_overview_range` cookie — its own key, so changing the -range here does not move the Users or Tools page. KPI labels take their suffix +range here does not move the Actors or Tools page. KPI labels take their suffix from `RANGE_SUFFIX` (`All` renders none) ([ADR-0014](../decisions/0014-overview-single-range-selector.md)). diff --git a/docs/operations/users-and-auth.md b/docs/operations/actors-and-auth.md similarity index 61% rename from docs/operations/users-and-auth.md rename to docs/operations/actors-and-auth.md index f692068..42b5079 100644 --- a/docs/operations/users-and-auth.md +++ b/docs/operations/actors-and-auth.md @@ -1,57 +1,57 @@ -# Users and Authentication +# Actors and Authentication -cotel ties OTLP ingest to named users. Each user has a bearer token; spans ingested with that token are attributed to that user across the dashboard. This guide covers creating and managing users, configuring Claude Code to send an authenticated token, the allow-anonymous toggle, and what happens when strict auth is enforced. +cotel ties OTLP ingest to named **actors**: whoever sends telemetry, whether a person, an AI agent or a host. Each actor has a bearer token; spans ingested with that token are attributed to that actor across the dashboard. This guide covers creating and managing actors, configuring Claude Code to send an authenticated token, the allow-anonymous toggle, and what happens when strict auth is enforced. ## Concepts | Term | Meaning | |---|---| -| **User** | A named principal — typically a machine, agent, or developer sending telemetry | -| **Token** | A `cotel_<64 hex chars>` bearer token bound to one user | -| **Allow-anonymous** | When on (default), spans without a token are accepted and shown without a user label | +| **Actor** | A named sender of telemetry — a developer, an AI agent or a machine. Called a *user* before schema v11 ([ADR-0027](../decisions/0027-users-become-actors.md)) | +| **Token** | A `cotel_<64 hex chars>` bearer token bound to one actor | +| **Allow-anonymous** | When on (default), spans without a token are accepted and shown without an actor label | Tokens are plain bearer strings stored in the database. They are always retrievable from the dashboard — rotating a token replaces it with a new one and immediately revokes the old one. ## Dashboard walkthrough -### The Users list +### The Actors list -Click the **people icon** in the left sidebar. The Users page is a single list with one row per user (plus an **Anonymous** row when unattributed spans exist). Columns: +Click the **people icon** in the left sidebar. The Actors page is a single list with one row per actor (plus an **Anonymous** row when unattributed spans exist). Columns: | Column | Meaning | |---|---| -| **Name** | The user's display name | +| **Name** | The actor's display name | | **Cost** | Spend within the selected range | | **Sessions** | Distinct sessions within the selected range | -| **Created** | When the user was created (all-time) | +| **Created** | When the actor was created (all-time) | | **Last seen** | Most recent span (all-time) | -There is no token column and no per-row buttons — a row is a single click through to that user's own page. +There is no token column and no per-row buttons — a row is a single click through to that actor's own page. -**Range switcher.** A segmented control above the list scopes **Cost** and **Sessions** to a rolling window — All / Year / Month / Week / Day, defaulting to **Month** (last 30 days). The two columns it governs show the active window in their headers (e.g. `Cost (30d)`). Created and Last seen are always all-time. Your choice is remembered between visits via the `cotel_users_range` cookie. +**Range switcher.** A segmented control above the list scopes **Cost** and **Sessions** to a rolling window — All / Year / Month / Week / Day, defaulting to **Month** (last 30 days). The two columns it governs show the active window in their headers (e.g. `Cost (30d)`). Created and Last seen are always all-time. Your choice is remembered between visits via the `cotel_actors_range` cookie. -**Sorting, search, pagination.** Every column header sorts the *entire* user set (not just the visible page) through the API; click again to flip direction. The search box filters by name. The list pages at 50 rows; controls appear only when there are more. +**Sorting, search, pagination.** Every column header sorts the *entire* actor set (not just the visible page) through the API; click again to flip direction. The search box filters by name. The list pages at 50 rows; controls appear only when there are more. -### Creating a user +### Creating an actor -1. Click **Add user** (top-right of the page). +1. Click **Add actor** (top-right of the page). 2. Enter a display name — use something that identifies the sender, such as a machine hostname, agent name, or developer alias (e.g. `alice`, `prod-box`, `ci-runner`). 3. Click **Create**. -A banner appears showing the new user's token. Copy it now — you will paste it into Claude Code settings in the next step. You can retrieve the token again any time from the user's page. +A banner appears showing the new actor's token. Copy it now — you will paste it into Claude Code settings in the next step. You can retrieve the token again any time from the actor's page. -### The per-user page +### The per-actor page -Click any row to open `/users/`. This page shows the user's name, their range-scoped **Cost** and **Sessions** (with the same range switcher as the list), all-time **Created** and **Last seen**, and the actions: +Click any row to open `/actors/` (the old `/users/` links redirect there). This page shows the actor's name, their range-scoped **Cost** and **Sessions** (with the same range switcher as the list), all-time **Created** and **Last seen**, and the actions: - **Token** with a copy button — the full `cotel_…` string, retrievable any time. - **Rotate token** — generates a new token and immediately revokes the old one. Any Claude Code instance using the old token will start receiving `401 Unauthorized` until updated. Copy the new token and update `OTEL_EXPORTER_OTLP_HEADERS` in every `settings.json` that used the old one. -- **Delete user** — opens a modal with two choices: *Delete user only* (revokes the token; history stays attributed to the name and is reversible by re-creating the user) or *Delete user + history* (permanently removes the user and all their telemetry; type the name to confirm). After deletion you return to the list. -- **View activity** and **View sessions** — jump to the dashboard and Sessions views filtered to this user. +- **Delete actor** — opens a modal with two choices: *Delete actor only* (revokes the token; history stays attributed to the name and is reversible by re-creating the actor) or *Delete actor + history* (permanently removes the actor and all their telemetry; type the name to confirm). After deletion you return to the list. +- **View activity** and **View sessions** — jump to the dashboard and Sessions views filtered to this actor. -### The Anonymous user +### The Anonymous actor -Unattributed spans (ingested with allow-anonymous on) roll up under a synthetic **Anonymous** row that sorts and pages inline with real users. Its per-user page has no token and no rotate — only **Delete anonymous data** (permanently removes all unattributed spans) alongside the activity and sessions links. +Unattributed spans (ingested with allow-anonymous on) roll up under a synthetic **Anonymous** row that sorts and pages inline with real actors. Its per-actor page has no token and no rotate — only **Delete anonymous data** (permanently removes all unattributed spans) alongside the activity and sessions links. ## Configuring Claude Code @@ -74,7 +74,7 @@ Replace `cotel_` with the token you copied from the dashboard. Resta ### Multiple machines or agents -Create a separate user for each sender — one per developer or machine. Each instance gets its own `settings.json` entry with its own `OTEL_EXPORTER_OTLP_HEADERS` value. Spans appear with the corresponding user label in the dashboard. +Create a separate actor for each sender — one per developer or machine. Each instance gets its own `settings.json` entry with its own `OTEL_EXPORTER_OTLP_HEADERS` value. Spans appear with the corresponding actor label in the dashboard. ### Remote ingest (Cloudflare Tunnel) @@ -93,24 +93,24 @@ The **Allow anonymous OTLP** toggle lives in **Setup** → **Settings** tab. | State | Behaviour | |---|---| -| **On** (default) | OTLP requests without a valid `Authorization` header are accepted; spans are stored with no user attribution | +| **On** (default) | OTLP requests without a valid `Authorization` header are accepted; spans are stored with no actor attribution | | **Off** | Every OTLP request must present `Authorization: Bearer cotel_`; requests without a valid token receive `401 Unauthorized` | ### When to keep allow-anonymous on -- Single-user local setup where token management adds friction. -- Initial evaluation — start collecting spans immediately, add users later. +- A single-person local setup where token management adds friction. +- Initial evaluation — start collecting spans immediately, add actors later. - Migrating from a token-less setup: leave anonymous on until all senders are updated. ### When to disable allow-anonymous -- Multi-user environments where per-user cost attribution must be accurate. +- Multi-actor environments where per-actor cost attribution must be accurate. - Public ingest endpoints (e.g. exposed via Cloudflare Tunnel) where unauthenticated writes from the internet must be blocked. - Compliance or audit requirements where all ingest must be attributable. ### Disabling allow-anonymous -1. Create at least one user (see above) so at least one valid token exists. +1. Create at least one actor (see above) so at least one valid token exists. 2. Configure all senders with their token before flipping the toggle. 3. Open **Setup** → **Settings** tab → disable **Allow anonymous OTLP**. 4. Verify with `curl`: @@ -147,11 +147,11 @@ Content-Type: application/json Claude Code's OTel SDK logs a warning and drops the trace batch. No spans are stored. -**Recovery:** copy the correct token from the Users page and update `OTEL_EXPORTER_OTLP_HEADERS` in `settings.json`, then restart Claude Code. +**Recovery:** copy the correct token from the Actors page and update `OTEL_EXPORTER_OTLP_HEADERS` in `settings.json`, then restart Claude Code. ## Token security -User tokens are 32-byte cryptographically random values encoded as lowercase hex, prefixed with `cotel_`. They are stored as **plaintext** in the database and are always accessible from the dashboard — you can retrieve a token any time without needing to save it at creation. +Actor tokens are 32-byte cryptographically random values encoded as lowercase hex, prefixed with `cotel_`. They are stored as **plaintext** in the database and are always accessible from the dashboard — you can retrieve a token any time without needing to save it at creation. > **Note:** An older `api_tokens` table (pre-FLO-88) stored hashed tokens for dashboard API auth. That table is kept in the schema for upgrade safety but is no longer used for authentication. @@ -166,6 +166,7 @@ Because tokens are stored in plaintext, anyone with filesystem access to the Duc ## References - [ADR-0004 — Multi-User Separation](../decisions/0004-multi-user-separation.md) +- [ADR-0027 — Users Become Actors](../decisions/0027-users-become-actors.md) - [ADR-0006 — Cloudflare Tunnel + Token Auth](../decisions/0006-cloudflare-tunnel-and-token-auth.md) - [Cloudflare Tunnel — Token Mode](./cloudflare-tunnel-remote.md) - [Cloudflare Tunnel — Local Config](./cloudflare-tunnel-local.md) diff --git a/docs/operations/agent-identity.md b/docs/operations/agent-identity.md index 3e71bb4..ffd6413 100644 --- a/docs/operations/agent-identity.md +++ b/docs/operations/agent-identity.md @@ -122,7 +122,7 @@ gh pr create --title "..." --body $'...\n\nAgent: Wayland' --label agent:wayland ## 4. Telemetry (OTEL) identity Each local agent reports its Claude Code telemetry to cotel under its **own** -ingest token, so the dashboard's **Users** view separates agents instead of +ingest token, so the dashboard's **Actors** view separates agents instead of merging them into one bucket. The token is injected exactly like the `GIT_*` vars — through the agent's Paperclip `adapterConfig.env`: @@ -201,8 +201,8 @@ fights the server for the DuckDB lock. ssh robmini 'curl -s "http://localhost:8080/api/v1/sessions?limit=500"' ``` -Group the result by `user_id`: every agent that has run inside the retention -window should appear under its own name. A `user_id` missing entirely means its +Group the result by `actor_id`: every agent that has run inside the retention +window should appear under its own name. An `actor_id` missing entirely means its runs never exported — check the environment's `env_vars` first (the whole fleet is dark) and the agent's own header second (only that agent is dark). Spans that carry an endpoint but no valid header are rejected at ingest, so a diff --git a/docs/operations/api-reference.md b/docs/operations/api-reference.md index 92695b7..743493e 100644 --- a/docs/operations/api-reference.md +++ b/docs/operations/api-reference.md @@ -6,7 +6,7 @@ default) and returns `application/json`. ## The list-query contract -`GET /users`, `GET /tools` and `GET /bash-commands` share one set of query +`GET /actors`, `GET /tools` and `GET /bash-commands` share one set of query parameters. They behave identically across the three endpoints, so learning it once is enough ([ADR-0011](../decisions/0011-users-list-ranged-stats-and-server-side-sort.md), [ADR-0012](../decisions/0012-tools-list-ranged-stats-and-server-side-sort.md)). @@ -40,7 +40,7 @@ so a client can render its controls from the response alone. accept the same `range` parameter, with the same five keys, the same rolling-window semantics and the same fall-back-don't-`400` rule ([ADR-0014](../decisions/0014-overview-single-range-selector.md)). Each echoes -back the `range` it used. All five also accept `user_id`, which composes with +back the `range` it used. All five also accept `actor_id`, which composes with `range` rather than overriding it. **Defaults preserve each endpoint's previous behaviour rather than converging on @@ -55,7 +55,7 @@ one value:** | `GET /models` | `all` | Same | Every additive figure — cost, token totals, span and session counts, distinct -users, per-model and per-tool totals — is answered from the union of raw `spans` +actors, per-model and per-tool totals — is answered from the union of raw `spans` and the `daily_usage` roll-up, split at the earliest surviving raw day. `year` and `all` therefore keep answering after retention has deleted the raw spans, instead of silently repeating the `month` figure. @@ -77,9 +77,9 @@ Two consequences are worth knowing: `/overview` is unaffected — `daily_usage` carries `session_id`, so counting distinct sessions across the union is exact. -`GET /overview`'s `users_count` counts the distinct principals active in the +`GET /overview`'s `actors_count` counts the distinct principals active in the range, with all unattributed spans counting as the single `__anonymous__` -principal the users list shows. +principal the actors list shows. ## `GET /history` @@ -90,7 +90,7 @@ Activity over time, bucketed at the requested `granularity`. | `granularity` | `10m` \| `hour` \| `4h` \| `day` \| `week` \| `month` | `day` | Bucket width for `buckets` and `by_model`; an unrecognised value falls back to `day` | | `range` | `all` \| `year` \| `month` \| `week` \| `day` | `month` | Rolling window, as above | | `from`, `to` | `YYYY-MM-DD` | — | Explicit bounds; when either is present they win and `range` echoes `null` | -| `user_id` | user id \| `__anonymous__` | — | Scopes every figure to one principal | +| `actor_id` | actor name \| `__anonymous__` | — | Scopes every figure to one principal | ```json { @@ -151,8 +151,8 @@ One row per tool, with call volume, average duration and error rate. | `fail_count` | Number of failed calls | | `fail_rate` | Percentage of calls that failed | -Also accepts `user_id` to scope every figure to one user; the value -`__anonymous__` selects spans ingested without a user. +Also accepts `actor_id` to scope every figure to one actor; the value +`__anonymous__` selects spans ingested without an actor. ```json { @@ -201,7 +201,7 @@ producers that do send a `command` attribute; cotel's ingest is generic. | `fail_count` | Number of failed calls | | `fail_rate` | Percentage of calls that failed | -`q` matches on the command text. `user_id` works as above. +`q` matches on the command text. `actor_id` works as above. This endpoint is computed from raw spans alone. A command string is unbounded, so the roll-up deliberately carries no command dimension — giving it one would grow @@ -225,9 +225,9 @@ the aggregate table with every distinct command per day. It therefore accepts } ``` -## `GET /users` +## `GET /actors` -One row per user, plus a synthetic `__anonymous__` row when unattributed spans +One row per actor, plus a synthetic `__anonymous__` row when unattributed spans exist. `cost` and `sessions` are range-scoped; `created_at` and `last_seen` are always all-time. @@ -236,12 +236,17 @@ always all-time. | `name` | Display name | | `cost` (default) | Spend in the selected range | | `sessions` | Distinct sessions in the selected range | -| `created_at` | When the user was created | +| `created_at` | When the actor was created | | `last_seen` | Most recent span | -Its rows are returned under `users` rather than `items`. `GET /users/{id}` -returns one user in the same shape and accepts `range`. See -[Users and Authentication](./users-and-auth.md) for the management endpoints +`/actors` was `/users` before schema v11 ([ADR-0027](../decisions/0027-users-become-actors.md)). +The old path, the `user_id` filter and `mode=user_only|user_and_history` on +delete are still accepted as aliases; response bodies use the new names only +(`actors`, `actor_id`, `actors_count`). + +Its rows are returned under `actors` rather than `items`. `GET /actors/{id}` +returns one actor in the same shape and accepts `range`. See +[Actors and Authentication](./actors-and-auth.md) for the management endpoints (create, rotate, delete). ## `GET /health` diff --git a/docs/operations/duckdb-recovery.md b/docs/operations/duckdb-recovery.md index d969497..6ba7209 100644 --- a/docs/operations/duckdb-recovery.md +++ b/docs/operations/duckdb-recovery.md @@ -135,16 +135,20 @@ The four secondary indexes on `spans` are plain ART indexes and carry no data of DROP INDEX IF EXISTS idx_spans_session_id; DROP INDEX IF EXISTS idx_spans_start_time; DROP INDEX IF EXISTS idx_spans_name; -DROP INDEX IF EXISTS idx_spans_user_id; +DROP INDEX IF EXISTS idx_spans_actor_id; CREATE INDEX idx_spans_session_id ON spans(session_id); CREATE INDEX idx_spans_start_time ON spans(start_time); CREATE INDEX idx_spans_name ON spans(name); -CREATE INDEX idx_spans_user_id ON spans(user_id); +CREATE INDEX idx_spans_actor_id ON spans(actor_id); FORCE CHECKPOINT; ``` +On a file older than schema v11 the fourth index is `idx_spans_user_id` on +`spans(user_id)` ([ADR-0027](../decisions/0027-users-become-actors.md)); check +with `SELECT max(version) FROM schema_version` and use the names that file has. + These are the same index definitions as `internal/storage/schema.sql`; if that file has moved on, take them from there rather than from this page. `FORCE CHECKPOINT` at the end is what matters: it folds the rebuilt indexes into the main file and is the step that fails loudly if the damage is deeper than the indexes. diff --git a/docs/operations/duckdb-snapshots.md b/docs/operations/duckdb-snapshots.md index eafa151..2cedeab 100644 --- a/docs/operations/duckdb-snapshots.md +++ b/docs/operations/duckdb-snapshots.md @@ -18,7 +18,7 @@ directory per snapshot into `COTEL_SNAPSHOT_DIR`: ``` /snapshots/2026-10-06T12-00-00Z/ schema.sql load.sql - spans.parquet daily_usage.parquet users.parquet + spans.parquet daily_usage.parquet actors.parquet api_tokens.parquet settings.parquet schema_version.parquet snapshot.json ``` @@ -263,8 +263,8 @@ untracked `COTEL_DATA_VOLUME` on the command line is forgotten by the next ## A snapshot carries the same secrets as the database -`users.token` holds ingest tokens in plaintext by design -([Users and Authentication](./users-and-auth)), so every snapshot carries a copy +`actors.token` (`users.token` before schema v11) holds ingest tokens in plaintext by design +([Actors and Authentication](./actors-and-auth)), so every snapshot carries a copy of every agent's token. Treat the snapshots volume exactly like the data volume: it is not a file to hand around, and an off-host copy of it is an off-host copy of the credentials. diff --git a/docs/operations/export-import.md b/docs/operations/export-import.md index 149dc1a..93b3804 100644 --- a/docs/operations/export-import.md +++ b/docs/operations/export-import.md @@ -20,7 +20,7 @@ cotel can export its full dataset as a ZIP archive and reimport it into any cote ## API reference -Both endpoints require a valid `Authorization: Bearer cotel_` header when anonymous mode is disabled (the default when at least one user token has been created). If anonymous mode is enabled (`allow_anonymous=true`) and no token is set on the request, the endpoints are still accessible. +Both endpoints require a valid `Authorization: Bearer cotel_` header when anonymous mode is disabled (the default when at least one actor token has been created). If anonymous mode is enabled (`allow_anonymous=true`) and no token is set on the request, the endpoints are still accessible. ### Export — `GET /api/v1/export` @@ -70,7 +70,7 @@ Maximum upload size: **101 MB** (compressed). Uncompressed content must be ≤ 1 { "spans_imported": 1234, "daily_usage_imported": 42, - "format_version": 1, + "format_version": 2, "warnings": [] } ``` @@ -97,7 +97,7 @@ A cotel export ZIP always contains the following entries: |---|---|---| | `manifest.json` | Yes | Archive metadata (version, period, row counts) | | `spans.csv` | When raw span data exists | One row per OTLP span | -| `daily_usage.csv` | When aggregated data exists | One row per (day, session, model, user) bucket | +| `daily_usage.csv` | When aggregated data exists | One row per (day, session, model, actor) bucket | **Size limits:** ≤ 100 MB uncompressed total; ≤ 5 ZIP entries. @@ -105,7 +105,7 @@ A cotel export ZIP always contains the following entries: ```json { - "format_version": 1, + "format_version": 2, "cotel_version": "0.1.0", "export_at": "2026-05-10T10:00:00Z", "period": "month", @@ -124,17 +124,17 @@ A cotel export ZIP always contains the following entries: } ``` -`format_version` is an integer that cotel increments only on breaking schema changes. The current version is `1`. +`format_version` is an integer that cotel increments only on breaking schema changes. The current version is `2`: it renamed the attribution column `user_id` to `actor_id` in both tables, at the same position ([ADR-0027](../decisions/0027-users-become-actors.md)). Version 1 archives still import; their `user_id` column is read as `actor_id`. ### spans.csv columns -`span_id`, `trace_id`, `parent_span_id`, `service_name`, `name`, `start_time`, `end_time`, `duration_ms`, `session_id`, `model`, `tool_name`, `user_id`, `status_code`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `cost_usd`, `attributes`, `resource_attrs`, `ingested_at` +`span_id`, `trace_id`, `parent_span_id`, `service_name`, `name`, `start_time`, `end_time`, `duration_ms`, `session_id`, `model`, `tool_name`, `actor_id`, `status_code`, `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `cost_usd`, `attributes`, `resource_attrs`, `ingested_at` Times are in RFC 3339 Nano format. NULL values are stored as empty strings. ### daily_usage.csv columns -`day`, `session_id`, `model`, `tool_name`, `user_id`, `span_count`, `total_input_tokens`, `total_output_tokens`, `total_cost_usd` +`day`, `session_id`, `model`, `tool_name`, `actor_id`, `span_count`, `total_input_tokens`, `total_output_tokens`, `total_cost_usd` `day` is in `YYYY-MM-DD` format (UTC). diff --git a/frontend/src/api/index.ts b/frontend/src/api/index.ts index 6d2973b..0a890af 100644 --- a/frontend/src/api/index.ts +++ b/frontend/src/api/index.ts @@ -9,7 +9,7 @@ export const fetcher = (url: string) => export interface OverviewResponse { range: string sessions_count: number - users_count: number + actors_count: number total_cost_usd: number total_input_tokens: number total_output_tokens: number @@ -21,7 +21,7 @@ export interface OverviewResponse { export interface SessionItem { session_id: string - user_id: string + actor_id: string first_seen: string last_seen: string model: string @@ -95,7 +95,7 @@ export interface BashCommandItem { } // ListParams is the range/search/sort/paging contract the tools and -// bash-commands lists share with the users list (ADR-0011, ADR-0012). +// bash-commands lists share with the actors list (ADR-0011, ADR-0012). export interface ListParams { range: string q?: string @@ -103,7 +103,7 @@ export interface ListParams { order: string page: number limit: number - user_id?: string + actor_id?: string } export type ToolsParams = ListParams @@ -140,7 +140,7 @@ function listQuery(p: ListParams): string { limit: String(p.limit), }) if (p.q) qs.set('q', p.q) - if (p.user_id) qs.set('user_id', p.user_id) + if (p.actor_id) qs.set('actor_id', p.actor_id) return qs.toString() } @@ -152,8 +152,8 @@ export interface ModelItem { total_output_tokens: number } -export interface UserRow { - user_id: string +export interface ActorRow { + actor_id: string is_default: boolean sessions: number total_cost_usd: number @@ -163,12 +163,12 @@ export interface UserRow { last_seen: string } -export interface UsersResponse { - items: UserRow[] +export interface ActorsResponse { + items: ActorRow[] } -// New user management types -export interface User { +// New actor management types +export interface Actor { id: string name: string token: string @@ -178,12 +178,12 @@ export interface User { last_seen: string | null } -export interface UsersListResponse { - users: User[] +export interface ActorsListResponse { + actors: Actor[] } -export interface UsersPageResponse { - users: User[] +export interface ActorsPageResponse { + actors: Actor[] total: number page: number limit: number @@ -192,7 +192,7 @@ export interface UsersPageResponse { order: string } -export interface UsersPageParams { +export interface ActorsPageParams { range: string q?: string sort: string @@ -205,12 +205,12 @@ export interface SettingsResponse { allow_anonymous: boolean } -// useUsers fetches every user unpaginated (limit=0) — used by the UserSearch typeahead. -export function useUsers() { - return useSWR('/api/v1/users', fetcher) +// useActors fetches every actor unpaginated (limit=0) — used by the ActorSearch typeahead. +export function useActors() { + return useSWR('/api/v1/actors', fetcher) } -export function useUsersPage(params: UsersPageParams) { +export function useActorsPage(params: ActorsPageParams) { const qs = new URLSearchParams({ range: params.range, sort: params.sort, @@ -219,20 +219,20 @@ export function useUsersPage(params: UsersPageParams) { limit: String(params.limit), }) if (params.q) qs.set('q', params.q) - return useSWR(`/api/v1/users?${qs.toString()}`, fetcher, { keepPreviousData: true }) + return useSWR(`/api/v1/actors?${qs.toString()}`, fetcher, { keepPreviousData: true }) } -export function useUser(id: string | undefined, range: string) { +export function useActor(id: string | undefined, range: string) { const qs = new URLSearchParams({ range }) - return useSWR(id ? `/api/v1/users/${encodeURIComponent(id)}?${qs.toString()}` : null, fetcher) + return useSWR(id ? `/api/v1/actors/${encodeURIComponent(id)}?${qs.toString()}` : null, fetcher) } export function useSettings() { return useSWR('/api/v1/settings', fetcher) } -export async function createUser(name: string): Promise { - const res = await fetch('/api/v1/users', { +export async function createActor(name: string): Promise { + const res = await fetch('/api/v1/actors', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name }), @@ -244,8 +244,8 @@ export async function createUser(name: string): Promise { return res.json() } -export async function rotateUserToken(id: string): Promise { - const res = await fetch(`/api/v1/users/${id}/rotate-token`, { method: 'POST' }) +export async function rotateActorToken(id: string): Promise { + const res = await fetch(`/api/v1/actors/${id}/rotate-token`, { method: 'POST' }) if (!res.ok) { const text = await res.text().catch(() => res.statusText) throw new Error(text || `${res.status}`) @@ -253,10 +253,10 @@ export async function rotateUserToken(id: string): Promise { return res.json() } -export type DeleteMode = 'user_only' | 'user_and_history' +export type DeleteMode = 'actor_only' | 'actor_and_history' -export async function deleteUser(id: string, mode?: DeleteMode): Promise { - const url = mode ? `/api/v1/users/${id}?mode=${mode}` : `/api/v1/users/${id}` +export async function deleteActor(id: string, mode?: DeleteMode): Promise { + const url = mode ? `/api/v1/actors/${id}?mode=${mode}` : `/api/v1/actors/${id}` const res = await fetch(url, { method: 'DELETE' }) if (!res.ok && res.status !== 204) { const text = await res.text().catch(() => res.statusText) @@ -280,9 +280,9 @@ export async function updateSettings(settings: Partial): Promi // The four hooks below take range last and omit the parameter when it is // undefined, so a caller that does not pass one keeps the server-side default // for that endpoint (ADR-0014). -export function useOverview(refreshInterval = 30_000, userId?: string, range?: string) { +export function useOverview(refreshInterval = 30_000, actorId?: string, range?: string) { const params = new URLSearchParams() - if (userId) params.set('user_id', userId) + if (actorId) params.set('actor_id', actorId) if (range) params.set('range', range) const qs = params.toString() return useSWR(`/api/v1/overview${qs ? `?${qs}` : ''}`, fetcher, { @@ -296,11 +296,11 @@ export function useSessions( limit = 50, sort = 'start_time', order = 'desc', - userId?: string, + actorId?: string, range?: string, ) { const params = new URLSearchParams({ page: String(page), limit: String(limit), sort, order }) - if (userId) params.set('user_id', userId) + if (actorId) params.set('actor_id', actorId) if (range) params.set('range', range) return useSWR(`/api/v1/sessions?${params.toString()}`, fetcher, { keepPreviousData: true, @@ -311,11 +311,11 @@ export function useSession(id: string) { return useSWR(id ? `/api/v1/sessions/${id}` : null, fetcher) } -export function useCosts(from?: string, to?: string, userId?: string, range?: string) { +export function useCosts(from?: string, to?: string, actorId?: string, range?: string) { const params = new URLSearchParams() if (from) params.set('from', from) if (to) params.set('to', to) - if (userId) params.set('user_id', userId) + if (actorId) params.set('actor_id', actorId) if (range) params.set('range', range) const qs = params.toString() return useSWR(`/api/v1/costs${qs ? `?${qs}` : ''}`, fetcher, { @@ -338,9 +338,9 @@ export interface ModelsResponse { range: string } -export function useModels(userId?: string, range?: string) { +export function useModels(actorId?: string, range?: string) { const params = new URLSearchParams() - if (userId) params.set('user_id', userId) + if (actorId) params.set('actor_id', actorId) if (range) params.set('range', range) const qs = params.toString() return useSWR(`/api/v1/models${qs ? `?${qs}` : ''}`, fetcher, { @@ -387,13 +387,13 @@ export function useHistory( granularity: string, from?: string, to?: string, - userId?: string, + actorId?: string, range?: string, ) { const params = new URLSearchParams({ granularity }) if (from) params.set('from', from) if (to) params.set('to', to) - if (userId) params.set('user_id', userId) + if (actorId) params.set('actor_id', actorId) if (range) params.set('range', range) return useSWR(`/api/v1/history?${params.toString()}`, fetcher, { keepPreviousData: true, diff --git a/frontend/src/components/DeleteUserModal.module.css b/frontend/src/components/DeleteActorModal.module.css similarity index 100% rename from frontend/src/components/DeleteUserModal.module.css rename to frontend/src/components/DeleteActorModal.module.css diff --git a/frontend/src/components/DeleteUserModal.tsx b/frontend/src/components/DeleteActorModal.tsx similarity index 60% rename from frontend/src/components/DeleteUserModal.tsx rename to frontend/src/components/DeleteActorModal.tsx index d4b104d..018a649 100644 --- a/frontend/src/components/DeleteUserModal.tsx +++ b/frontend/src/components/DeleteActorModal.tsx @@ -1,15 +1,15 @@ import { useState, useEffect, useRef } from 'react' -import { deleteUser } from '../api' -import type { User, DeleteMode } from '../api' -import styles from './DeleteUserModal.module.css' +import { deleteActor } from '../api' +import type { Actor, DeleteMode } from '../api' +import styles from './DeleteActorModal.module.css' -interface DeleteUserModalProps { - user: User +interface DeleteActorModalProps { + actor: Actor onClose: () => void onDeleted: (mode: DeleteMode) => void } -export function DeleteUserModal({ user, onClose, onDeleted }: DeleteUserModalProps) { +export function DeleteActorModal({ actor, onClose, onDeleted }: DeleteActorModalProps) { const [mode, setMode] = useState(null) const [confirmText, setConfirmText] = useState('') const [loading, setLoading] = useState(false) @@ -25,8 +25,8 @@ export function DeleteUserModal({ user, onClose, onDeleted }: DeleteUserModalPro return () => document.removeEventListener('keydown', onKey) }, [onClose]) - const modeAReady = mode === 'user_only' - const modeBReady = mode === 'user_and_history' && confirmText === user.name + const modeAReady = mode === 'actor_only' + const modeBReady = mode === 'actor_and_history' && confirmText === actor.name const canSubmit = modeAReady || modeBReady const handleSubmit = async () => { @@ -34,7 +34,7 @@ export function DeleteUserModal({ user, onClose, onDeleted }: DeleteUserModalPro setLoading(true) setError(null) try { - await deleteUser(user.id, mode) + await deleteActor(actor.id, mode) onDeleted(mode) } catch (err) { setError(err instanceof Error ? err.message : 'Delete failed') @@ -44,60 +44,60 @@ export function DeleteUserModal({ user, onClose, onDeleted }: DeleteUserModalPro const handleModeChange = (next: DeleteMode) => { setMode(next) - if (next !== 'user_and_history') setConfirmText('') + if (next !== 'actor_and_history') setConfirmText('') setError(null) } - const confirmLabel = mode === 'user_and_history' ? 'Permanently delete' : 'Delete user' + const confirmLabel = mode === 'actor_and_history' ? 'Permanently delete' : 'Delete actor' return (
e.target === e.currentTarget && onClose()}>
-

Delete user

+

Delete actor

- You are about to delete {user.name}. Choose what to delete: + You are about to delete {actor.name}. Choose what to delete:

handleModeChange('user_only')} - onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && handleModeChange('user_only')} + className={`${styles.radioCard} ${mode === 'actor_only' ? styles.radioCardSelectedA : ''}`} + onClick={() => handleModeChange('actor_only')} + onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && handleModeChange('actor_only')} >
- {mode === 'user_only' ? '●' : '○'} - Delete user only + {mode === 'actor_only' ? '●' : '○'} + Delete actor only

- Revokes {user.name}'s login access. All session history and telemetry stays attributed to {user.name}. Reversible by re-creating a user with the same name. + Revokes {actor.name}'s login access. All session history and telemetry stays attributed to {actor.name}. Reversible by re-creating an actor with the same name.

handleModeChange('user_and_history')} - onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && handleModeChange('user_and_history')} + className={`${styles.radioCard} ${mode === 'actor_and_history' ? styles.radioCardSelectedB : ''}`} + onClick={() => handleModeChange('actor_and_history')} + onKeyDown={(e) => (e.key === ' ' || e.key === 'Enter') && handleModeChange('actor_and_history')} >
- {mode === 'user_and_history' ? '●' : '○'} - Delete user + history + {mode === 'actor_and_history' ? '●' : '○'} + Delete actor + history ⚠ Permanent

- Revokes access and permanently removes {user.name} and all their telemetry. This cannot be undone. + Revokes access and permanently removes {actor.name} and all their telemetry. This cannot be undone.

- {mode === 'user_and_history' && ( + {mode === 'actor_and_history' && (
- + ) : ( )}
{showDelete && !isAnon && ( - setShowDelete(false)} onDeleted={() => { setShowDelete(false) - navigate('/users') + navigate('/actors') }} /> )} diff --git a/frontend/src/pages/Users.module.css b/frontend/src/pages/Actors.module.css similarity index 99% rename from frontend/src/pages/Users.module.css rename to frontend/src/pages/Actors.module.css index bf5866f..34bc940 100644 --- a/frontend/src/pages/Users.module.css +++ b/frontend/src/pages/Actors.module.css @@ -22,7 +22,7 @@ margin-bottom: var(--space-2); } -/* New user token banner */ +/* New actor token banner */ .newTokenBanner { background: var(--color-surface); border: 1px solid var(--color-accent); @@ -139,12 +139,12 @@ vertical-align: middle; } -.userName { +.actorName { font-weight: 500; color: var(--color-text-1); } -.userNameAnon { +.actorNameAnon { font-weight: 500; color: var(--color-text-2); font-style: italic; diff --git a/frontend/src/pages/Users.tsx b/frontend/src/pages/Actors.tsx similarity index 77% rename from frontend/src/pages/Users.tsx rename to frontend/src/pages/Actors.tsx index ea6bbb1..20ce6d3 100644 --- a/frontend/src/pages/Users.tsx +++ b/frontend/src/pages/Actors.tsx @@ -1,20 +1,20 @@ import { useState, useCallback, useEffect } from 'react' import { useNavigate } from 'react-router-dom' import { Copy, Check, Plus, Search, ChevronLeft, ChevronRight } from 'lucide-react' -import { useUsersPage, createUser } from '../api' -import type { User } from '../api' +import { useActorsPage, createActor } from '../api' +import type { Actor } from '../api' import { DataTable, EmptyState, ErrorState, LoadingSkeleton, SegmentedControl } from '../components' import type { Column, SortState } from '../components' import { RANGE_OPTIONS, RANGE_SUFFIX, useRangeCookie } from '../lib/range' -import styles from './Users.module.css' +import styles from './Actors.module.css' const ANON_ID = '__anonymous__' const PAGE_SIZE = 50 -const RANGE_COOKIE = 'cotel_users_range' +const RANGE_COOKIE = 'cotel_actors_range' type SortKey = 'name' | 'cost' | 'sessions' | 'created_at' | 'last_seen' -interface UserVM { +interface ActorVM { id: string name: string cost: number @@ -24,7 +24,7 @@ interface UserVM { isAnon: boolean } -function AddUserModal({ onClose, onCreated }: { onClose: () => void; onCreated: (u: User) => void }) { +function AddActorModal({ onClose, onCreated }: { onClose: () => void; onCreated: (u: Actor) => void }) { const [name, setName] = useState('') const [loading, setLoading] = useState(false) const [error, setError] = useState(null) @@ -36,7 +36,7 @@ function AddUserModal({ onClose, onCreated }: { onClose: () => void; onCreated: setLoading(true) setError(null) try { - const u = await createUser(trimmed) + const u = await createActor(trimmed) onCreated(u) } catch (err) { setError(err instanceof Error ? err.message : 'Create failed') @@ -48,7 +48,7 @@ function AddUserModal({ onClose, onCreated }: { onClose: () => void; onCreated: return (
e.target === e.currentTarget && onClose()}>
-

Add user

+

Add actor

void; onCreated: ) } -function NewTokenBanner({ user, onDismiss }: { user: User; onDismiss: () => void }) { +function NewTokenBanner({ actor, onDismiss }: { actor: Actor; onDismiss: () => void }) { const [copied, setCopied] = useState(false) const copy = useCallback(async () => { - await navigator.clipboard.writeText(user.token) + await navigator.clipboard.writeText(actor.token) setCopied(true) setTimeout(() => setCopied(false), 2000) - }, [user.token]) + }, [actor.token]) return (
- User {user.name} created — copy your token + Actor {actor.name} created — copy your token
- {user.token} + {actor.token}

- Set OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer {user.token} in your Claude Code settings. + Set OTEL_EXPORTER_OTLP_HEADERS=Authorization=Bearer {actor.token} in your Claude Code settings.

) } -export default function Users() { +export default function Actors() { const navigate = useNavigate() const [range, setRange] = useRangeCookie(RANGE_COOKIE) @@ -109,7 +109,7 @@ export default function Users() { const [q, setQ] = useState('') const [showAdd, setShowAdd] = useState(false) - const [newUser, setNewUser] = useState(null) + const [newActor, setNewActor] = useState(null) // Debounce the search box into the server-side q parameter. useEffect(() => { @@ -120,7 +120,7 @@ export default function Users() { return () => clearTimeout(t) }, [search]) - const { data, error, isLoading, mutate } = useUsersPage({ + const { data, error, isLoading, mutate } = useActorsPage({ range, q: q || undefined, sort, @@ -130,7 +130,7 @@ export default function Users() { }) const total = data?.total ?? 0 - const rows: UserVM[] = (data?.users ?? []).map((u) => ({ + const rows: ActorVM[] = (data?.actors ?? []).map((u) => ({ id: u.id, name: u.name, cost: u.cost, @@ -148,25 +148,25 @@ export default function Users() { setPage(1) } - const handleSortChange = (next: NonNullable>) => { + const handleSortChange = (next: NonNullable>) => { setSort(next.key as SortKey) setOrder(next.dir) setPage(1) } - const handleCreated = (u: User) => { + const handleCreated = (u: Actor) => { setShowAdd(false) - setNewUser(u) + setNewActor(u) mutate() } - const columns: Column[] = [ + const columns: Column[] = [ { key: 'name', label: 'Name', sortable: true, render: (_v, row) => ( - {row.name} + {row.name} ), }, { @@ -206,7 +206,7 @@ export default function Users() { return (
-

Users

+

Actors

@@ -229,11 +229,11 @@ export default function Users() { />
- {newUser && setNewUser(null)} />} + {newActor && setNewActor(null)} />} {isLoading ? ( @@ -241,21 +241,21 @@ export default function Users() { ) : total === 0 ? ( q ? ( -
No users match "{q}"
+
No actors match "{q}"
) : ( ) ) : ( <> - + columns={columns} rows={rows} - sort={{ key: sort as keyof UserVM, dir: order }} + sort={{ key: sort as keyof ActorVM, dir: order }} onSortChange={handleSortChange} - onRowClick={(row) => navigate(`/users/${encodeURIComponent(row.id)}`)} + onRowClick={(row) => navigate(`/actors/${encodeURIComponent(row.id)}`)} /> {total > PAGE_SIZE && ( @@ -280,7 +280,7 @@ export default function Users() { )} - {showAdd && setShowAdd(false)} onCreated={handleCreated} />} + {showAdd && setShowAdd(false)} onCreated={handleCreated} />}
) } diff --git a/frontend/src/pages/Costs.module.css b/frontend/src/pages/Costs.module.css index c608636..6a270fa 100644 --- a/frontend/src/pages/Costs.module.css +++ b/frontend/src/pages/Costs.module.css @@ -14,7 +14,7 @@ margin-bottom: var(--space-2); } -.userChip { +.actorChip { display: inline-flex; align-items: center; gap: 4px; diff --git a/frontend/src/pages/Costs.tsx b/frontend/src/pages/Costs.tsx index 3c6eeb1..7b19fe4 100644 --- a/frontend/src/pages/Costs.tsx +++ b/frontend/src/pages/Costs.tsx @@ -24,15 +24,15 @@ export default function Costs() { const [from, setFrom] = useState(daysAgo(30)) const [to, setTo] = useState(today()) const [searchParams, setSearchParams] = useSearchParams() - const userId = searchParams.get('user_id') ?? undefined - const { data, error, isLoading } = useCosts(from, to, userId) + const actorId = searchParams.get('actor_id') ?? undefined + const { data, error, isLoading } = useCosts(from, to, actorId) const totalCost = data?.by_model.reduce((s, m) => s + m.cost_usd, 0) ?? 0 - function clearUserFilter() { + function clearActorFilter() { setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.delete('user_id') + next.delete('actor_id') return next }) } @@ -42,9 +42,9 @@ export default function Costs() {

Costs

- {userId && ( - )}
diff --git a/frontend/src/pages/History.module.css b/frontend/src/pages/History.module.css index 680d7f7..ede0381 100644 --- a/frontend/src/pages/History.module.css +++ b/frontend/src/pages/History.module.css @@ -14,7 +14,7 @@ margin-bottom: var(--space-2); } -.userChip { +.actorChip { display: inline-flex; align-items: center; gap: 4px; diff --git a/frontend/src/pages/History.tsx b/frontend/src/pages/History.tsx index d53304f..1104733 100644 --- a/frontend/src/pages/History.tsx +++ b/frontend/src/pages/History.tsx @@ -308,13 +308,13 @@ export default function History() { const [to, setTo] = useState(today()) const [activePreset, setActivePreset] = useState('30d') const [searchParams, setSearchParams] = useSearchParams() - const userId = searchParams.get('user_id') ?? undefined - const { data, error, isLoading } = useHistory(gran, from, to, userId) + const actorId = searchParams.get('actor_id') ?? undefined + const { data, error, isLoading } = useHistory(gran, from, to, actorId) - function clearUserFilter() { + function clearActorFilter() { setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.delete('user_id') + next.delete('actor_id') return next }) } @@ -338,9 +338,9 @@ export default function History() {

History

- {userId && ( - )}
diff --git a/frontend/src/pages/Models.module.css b/frontend/src/pages/Models.module.css index fdaa931..18383f4 100644 --- a/frontend/src/pages/Models.module.css +++ b/frontend/src/pages/Models.module.css @@ -12,7 +12,7 @@ color: var(--color-text-1); } -.userChip { +.actorChip { display: inline-flex; align-items: center; gap: 4px; diff --git a/frontend/src/pages/Models.tsx b/frontend/src/pages/Models.tsx index 0816bf5..6cd72c5 100644 --- a/frontend/src/pages/Models.tsx +++ b/frontend/src/pages/Models.tsx @@ -7,13 +7,13 @@ import styles from './Models.module.css' export default function Models() { const [searchParams, setSearchParams] = useSearchParams() - const userId = searchParams.get('user_id') ?? undefined - const { data, error, isLoading } = useModels(userId) + const actorId = searchParams.get('actor_id') ?? undefined + const { data, error, isLoading } = useModels(actorId) - function clearUserFilter() { + function clearActorFilter() { setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.delete('user_id') + next.delete('actor_id') return next }) } @@ -29,9 +29,9 @@ export default function Models() {

Models

- {userId && ( - )}
diff --git a/frontend/src/pages/Overview.module.css b/frontend/src/pages/Overview.module.css index 148062b..edcf722 100644 --- a/frontend/src/pages/Overview.module.css +++ b/frontend/src/pages/Overview.module.css @@ -18,7 +18,7 @@ gap: var(--space-4); } -.userChip { +.actorChip { display: inline-flex; align-items: center; gap: 4px; @@ -95,7 +95,7 @@ color: var(--color-accent); } -.anonUser { +.anonActor { color: var(--color-text-2); font-style: italic; } diff --git a/frontend/src/pages/Overview.tsx b/frontend/src/pages/Overview.tsx index 8e7d88c..b44323a 100644 --- a/frontend/src/pages/Overview.tsx +++ b/frontend/src/pages/Overview.tsx @@ -5,9 +5,9 @@ import { XAxis, YAxis, Tooltip, ResponsiveContainer, } from 'recharts' import { - useOverview, useSessions, useHistory, useTools, useModels, useUsersPage, + useOverview, useSessions, useHistory, useTools, useModels, useActorsPage, } from '../api' -import type { SessionItem, ToolItem, ModelItem, User } from '../api' +import type { SessionItem, ToolItem, ModelItem, Actor } from '../api' import { KpiCard, DataTable, EmptyState, ErrorState, RefreshIndicator, SegmentedControl, KpiSkeleton, ChartSkeleton, LoadingSkeleton, sessionStatusBadge, failRateBadge, ChartTooltip, @@ -23,7 +23,7 @@ const ANON_ID = '__anonymous__' interface SectionProps { range: RangeKey - userId?: string + actorId?: string } function fmtTokens(n: number): string { @@ -38,9 +38,9 @@ function formatDay(iso: string): string { // ---- Compact section components ---- -function UsersSection({ range }: { range: RangeKey }) { +function ActorsSection({ range }: { range: RangeKey }) { const navigate = useNavigate() - const { data, isLoading, error } = useUsersPage({ + const { data, isLoading, error } = useActorsPage({ range, sort: 'cost', order: 'desc', @@ -50,17 +50,17 @@ function UsersSection({ range }: { range: RangeKey }) { if (isLoading && !data) return if (error) return - if (!data || data.users.length === 0) - return + if (!data || data.actors.length === 0) + return return ( - + columns={[ { key: 'name', label: 'Name', render: (v, row) => ( - {String(v)} + {String(v)} ), }, { key: 'cost', label: 'Cost', render: (v) => `$${Number(v).toFixed(2)}` }, @@ -71,8 +71,8 @@ function UsersSection({ range }: { range: RangeKey }) { render: (v) => (v ? new Date(String(v)).toLocaleString() : '—'), }, ]} - rows={data.users} - onRowClick={(row) => navigate(`/users/${encodeURIComponent(row.id)}`)} + rows={data.actors} + onRowClick={(row) => navigate(`/actors/${encodeURIComponent(row.id)}`)} /> ) } @@ -81,12 +81,12 @@ function UsersSection({ range }: { range: RangeKey }) { // days over a year, ten minutes over a day. On the year and all ranges that is // the same request ActivitySection already makes, and SWR serves both from one // fetch. -function ActivityGridSection({ range, userId }: SectionProps) { +function ActivityGridSection({ range, actorId }: SectionProps) { const { data, isLoading, error } = useHistory( GRID_GRANULARITY[range], undefined, undefined, - userId, + actorId, range, ) @@ -109,15 +109,15 @@ function ActivityGridSection({ range, userId }: SectionProps) { } // Spans and cost share the history buckets, so the two series are bucketed, -// windowed and user-filtered identically — a client-side join of /history with +// windowed and actor-filtered identically — a client-side join of /history with // /costs could not guarantee that. They carry different units, so each keeps its // own axis and the legend names the side it reads against. -function ActivitySection({ range, userId }: SectionProps) { +function ActivitySection({ range, actorId }: SectionProps) { const { data, isLoading, error } = useHistory( range === 'day' ? 'hour' : 'day', undefined, undefined, - userId, + actorId, range, ) @@ -211,14 +211,14 @@ function ActivitySection({ range, userId }: SectionProps) { ) } -function ToolsSection({ range, userId }: SectionProps) { +function ToolsSection({ range, actorId }: SectionProps) { const { data, isLoading, error } = useTools({ range, sort: 'calls', order: 'desc', page: 1, limit: 5, - user_id: userId, + actor_id: actorId, }) if (isLoading && !data) return @@ -249,8 +249,8 @@ function ToolsSection({ range, userId }: SectionProps) { ) } -function ModelsSection({ range, userId }: SectionProps) { - const { data, isLoading, error } = useModels(userId, range) +function ModelsSection({ range, actorId }: SectionProps) { + const { data, isLoading, error } = useModels(actorId, range) const rows = useMemo(() => { if (!data) return [] @@ -305,9 +305,9 @@ function ModelsSection({ range, userId }: SectionProps) { ) } -function SessionsSection({ range, userId }: SectionProps) { +function SessionsSection({ range, actorId }: SectionProps) { const navigate = useNavigate() - const { data, isLoading, error } = useSessions(1, 5, 'start_time', 'desc', userId, range) + const { data, isLoading, error } = useSessions(1, 5, 'start_time', 'desc', actorId, range) if (isLoading && !data) return if (error) return @@ -328,10 +328,10 @@ function SessionsSection({ range, userId }: SectionProps) { ), }, { - key: 'user_id', - label: 'User', + key: 'actor_id', + label: 'Actor', render: (v) => - v ? String(v) : anonymous, + v ? String(v) : anonymous, }, { key: 'first_seen', @@ -369,19 +369,19 @@ function SessionsSection({ range, userId }: SectionProps) { export default function Overview() { const [paused, setPaused] = useState(false) const [searchParams, setSearchParams] = useSearchParams() - const userId = searchParams.get('user_id') ?? undefined + const actorId = searchParams.get('actor_id') ?? undefined const [range, setRange] = useRangeCookie(RANGE_COOKIE) - const { data, error, isLoading, isValidating, mutate } = useOverview(paused ? 0 : 30_000, userId, range) + const { data, error, isLoading, isValidating, mutate } = useOverview(paused ? 0 : 30_000, actorId, range) - const userParam = userId ? `?user_id=${encodeURIComponent(userId)}` : '' + const actorParam = actorId ? `?actor_id=${encodeURIComponent(actorId)}` : '' const suffix = RANGE_SUFFIX[range] const scoped = (label: string) => (suffix ? `${label} (${suffix})` : label) - const clearUserFilter = () => + const clearActorFilter = () => setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.delete('user_id') + next.delete('actor_id') return next }) @@ -390,9 +390,9 @@ export default function Overview() {

Overview

- {userId && ( - )}
@@ -421,43 +421,43 @@ export default function Overview() { ) : data ? (
- +
) : null} - - + + - {!userId && ( - - + {!actorId && ( + + )} - + - - + + - - + + - - + +
) diff --git a/frontend/src/pages/Sessions.module.css b/frontend/src/pages/Sessions.module.css index 19ffdbc..456586e 100644 --- a/frontend/src/pages/Sessions.module.css +++ b/frontend/src/pages/Sessions.module.css @@ -12,7 +12,7 @@ color: var(--color-text-1); } -.userChip { +.actorChip { display: inline-flex; align-items: center; gap: 4px; @@ -85,7 +85,7 @@ color: var(--color-accent); } -.userLink { +.actorLink { background: none; border: none; padding: 0; @@ -96,11 +96,11 @@ text-align: left; } -.userLink:hover { +.actorLink:hover { text-decoration: underline; } -.anonUser { +.anonActor { color: var(--color-text-2); font-style: italic; } diff --git a/frontend/src/pages/Sessions.tsx b/frontend/src/pages/Sessions.tsx index 191f789..353414b 100644 --- a/frontend/src/pages/Sessions.tsx +++ b/frontend/src/pages/Sessions.tsx @@ -11,21 +11,21 @@ export default function Sessions() { const [statusFilter, setStatusFilter] = useState<'all' | 'ok' | 'error'>('all') const navigate = useNavigate() const [searchParams, setSearchParams] = useSearchParams() - const userId = searchParams.get('user_id') ?? undefined - const { data, error, isLoading } = useSessions(page, 50, 'start_time', 'desc', userId) + const actorId = searchParams.get('actor_id') ?? undefined + const { data, error, isLoading } = useSessions(page, 50, 'start_time', 'desc', actorId) - function clearUserFilter() { + function clearActorFilter() { setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.delete('user_id') + next.delete('actor_id') return next }) } - function applyUserFilter(uid: string) { + function applyActorFilter(uid: string) { setSearchParams((prev) => { const next = new URLSearchParams(prev) - next.set('user_id', uid) + next.set('actor_id', uid) return next }) setPage(1) @@ -36,7 +36,7 @@ export default function Sessions() { const needle = search.toLowerCase() return data.items.filter( (s) => - (search === '' || (s.user_id ?? '').toLowerCase().includes(needle)) && + (search === '' || (s.actor_id ?? '').toLowerCase().includes(needle)) && (statusFilter === 'all' || s.status === statusFilter), ) }, [data, search, statusFilter]) @@ -47,9 +47,9 @@ export default function Sessions() {

Sessions

- {userId && ( - )}
@@ -57,7 +57,7 @@ export default function Sessions() {
{ setSearch(e.target.value); setPage(1) }} /> @@ -99,20 +99,20 @@ export default function Sessions() { ), }, { - key: 'user_id', - label: 'User', + key: 'actor_id', + label: 'Actor', sortable: true, render: (v) => v ? ( ) : ( - anonymous + anonymous ), }, { diff --git a/frontend/src/pages/Setup.tsx b/frontend/src/pages/Setup.tsx index e7e5c6b..f7a4a6a 100644 --- a/frontend/src/pages/Setup.tsx +++ b/frontend/src/pages/Setup.tsx @@ -169,11 +169,11 @@ function GettingStartedTab() {
    -
  1. Go to Users and click Add user.
  2. +
  3. Go to Actors and click Add actor.
  4. Copy the generated token.
  5. Add to Claude Code settings:
@@ -182,7 +182,7 @@ function GettingStartedTab() {
{OTLP_HEADERS_SNIPPET}

- Replace YOUR_TOKEN_HERE with the token shown after user creation. + Replace YOUR_TOKEN_HERE with the token shown after the actor is created.

To block unauthenticated sends, open the{' '} @@ -497,8 +497,8 @@ function SettingsTab() {

Allow anonymous OTLP
- When enabled, spans without an Authorization header are accepted and attributed to no user. - Disable to require every OTLP sender to present a valid user token. + When enabled, spans without an Authorization header are accepted and attributed to no actor. + Disable to require every OTLP sender to present a valid actor token.