From 22a721a6c17492a7811467a62a10946168904a3e Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 12:47:01 +0200 Subject: [PATCH 1/9] =?UTF-8?q?Studio:=20Run=20cost's=20calibration=20tria?= =?UTF-8?q?l=20=E2=80=94=20$0.41=20per=205-hour=20percent=20on=20Max=20(#1?= =?UTF-8?q?058)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Five First map drafts on Sonnet 5.5 cost $2.49 API price and moved the 5-hour window 24% to 30%; the week stayed at 64%. /usage spends no tokens on a -p run, names no plan, and /status is unavailable there. Co-Authored-By: Claude Opus 5.5 --- docs/studio/research/run-cost.md | 136 ++++++++++++++++++ .../tests/fixtures/usage/subscriber-max.jsonl | 3 + 2 files changed, 139 insertions(+) create mode 100644 docs/studio/research/run-cost.md create mode 100644 server/tests/fixtures/usage/subscriber-max.jsonl diff --git a/docs/studio/research/run-cost.md b/docs/studio/research/run-cost.md new file mode 100644 index 00000000..3f39f0dd --- /dev/null +++ b/docs/studio/research/run-cost.md @@ -0,0 +1,136 @@ +# Run cost: dollars per percent of a plan's windows + +The calibration trial of spec #1056 (ticket #1058), run on 2 December 2026 on Daniel's account. Question: how many API-price dollars (the CLI's `total_cost_usd`) make one percent of a Claude plan's 5-hour window and of its week? Run cost's estimates and actual figures rest on this factor (#1056, "The calibration trial comes first"). + +Every claim is marked **verified** (with the command output or file that settled it) or **unverified**. No credential or token file was read. The raw run (every `claude -p` result, the `/usage` and `/status` outputs, the script and its log) is in `local-evidence/2026-12-02-run-cost-trial/` on Daniel's machine. + +## Result + +| | Factor | Plan | How settled | +|---|---|---|---| +| 5-hour window | **$0.41 per percent** (range $0.36–0.50) | Max | measured: $2.49 over 6 points | +| Week | **about $2.9 per percent** (at least $2.5) | Max | lower bound measured; value derived, see "The week" | + +From the published ratios (#1056, "The plan"): Pro's percent is a fifth of Max's dollars ($0.08 per 5-hour percent, about $0.58 per weekly percent); Ultra has no 5-hour window, and its weekly percent is twice Max's dollars (about $5.8). + +Measured on: Max (Daniel's answer; `/usage` does not name the plan, see fact 2), Claude Code 2.1.331, every run on `claude-sonnet-5-5`, the CLI's default model (verified: each result's `modelUsage` names only that model, and the stream's `init` line says `"model":"claude-sonnet-5-5"`). + +## Method + +`run-cost-trial.sh` (in the evidence folder), with every other Claude session idle, this one included: + +1. Clones of chery-platform at `124ebdb` and observability-sdk at `7894bdf`, made from Daniel's checkouts into the scratchpad. +2. `/usage` and `/status` sent through `claude -p`, twice back to back, at 10:25:03Z and 10:25:11Z. +3. Five First map drafts, with the 2026-11-27 trial's prompts, skeletons and runner flags (`local-evidence/2026-11-27-onboarding-grilling/trial/`, `scripts/run.sh`): chery three times (4 writers in parallel, then the reviewer), observability-sdk twice (1 writer, then the reviewer). 10:25:19Z to 10:36:18Z. +4. `/usage` right after (10:36:18Z) and 3 minutes later (10:39:26Z). + +Every run used the runner's flags minus the sandbox settings: `--restricted --safe-mode --strict-mcp-config --permission-mode dontAsk --permission-prompts none --tools Read,Glob,Grep`, API key variables removed, `PLOTKEEPER_INTERNAL=1`, on the CLI login. + +## The runs + +All 19 runs ended `success` (verified, each result's `subtype`). + +| Draft | Parts | Runs (session ids) | Cost | Per part | +|---|---|---|---|---| +| chery 1 | 15 | writers `ee8d24c1` $0.148, `12ca069c` $0.146, `c1c969ed` $0.074, `45b29a8a` $0.122; reviewer `58a2852b` $0.392 | $0.883 | $0.059 | +| chery 2 | 15 | writers `3e8d403b` $0.106, `1132a07b` $0.084, `43bdce90` $0.044, `03b20141` $0.053; reviewer `d48c2ba0` $0.343 | $0.630 | $0.042 | +| chery 3 | 15 | writers `e812caac` $0.103, `2c0f3eae` $0.079, `0b8f5c3c` $0.050, `bd18ebce` $0.084; reviewer `8cffa07d` $0.322 | $0.639 | $0.043 | +| observability-sdk 1 | 5 | writer `cc489dbe` $0.091; reviewer `c506da08` $0.123 | $0.214 | $0.043 | +| observability-sdk 2 | 5 | writer `ff26cc77` $0.068; reviewer `44f8f3b0` $0.055 | $0.123 | $0.025 | +| **Total** | | 19 runs | **$2.489** | | + +On Sonnet a chery draft cost $0.63–0.88, against $2.17 on Opus in the 2026-11-27 trial (its `README.md`, Results). + +## The 5-hour window + +`/usage`'s `session` row (verified, the stream's `usage_report.rate_limits.limits[]`): + +| Read | Time | `session` | `weekly_all` | +|---|---|---|---| +| before-1 | 10:25:03Z | 24 | 64 | +| before-2 | 10:25:11Z | 24 | 64 | +| after-1 | 10:36:18Z | 29 | 64 | +| after-2 | 10:39:26Z | 30 | 64 | + +The share rose 6 points, 24 to 30, of which 1 point arrived in the 3 minutes after the last run, when nothing ran. That reads as the meter lagging the runs, so after-2 is the end reading: $2.489 / 6 = **$0.41 per percent**. + +Uncertainty: the percentages are whole numbers, so the true rise is between 5 and 7 points, which puts the factor between $0.36 and $0.50. A session Daniel could not keep idle (another device, claude.ai) would add points the runs did not spend, so the factor leans low. One trial, one model. + +## The week + +`weekly_all` stayed at 64 through the trial, so the runs' $2.49 moved the week by less than one point: the weekly factor is **at least $2.5 per percent** (verified, table above). A value needs a batch about ten times larger. + +Until a larger trial runs, the value is derived from the ratio of the two windows in the old status-line snapshots (`local-evidence/2026-12-02-first-map-depth/reports/research-cost.md`, section 4): about $8 per weekly percent against $1.0–1.3 per 5-hour percent, a ratio of 6 to 8. Seven times $0.41 gives **about $2.9 per weekly percent**, inside the measured bound (unverified as a measurement; low–medium confidence). + +## What the factor depends on + +The old snapshots, mostly on Opus 5.5, gave $1.0–1.3 per 5-hour percent; this trial, all on Sonnet 5.5, gives $0.41. If both are right, a plan's percent is not a fixed number of API-price dollars across models: Opus's dollars buy more of the window than Sonnet's (unverified; the snapshot method smears cost across windows and assumed Max). Background runs run on the CLI's default model unless `backgroundRuns.model` says otherwise, and the run record's `model` field (#1056, "The run record") keeps which one ran. The factor here is Sonnet's. + +## The three open facts + +### 1. `claude -p "/usage"` spends no model tokens (verified) + +Each of the eight `/usage` reads ran as a local command: the result has `"local_command":"usage"`, `"num_turns":0`, `"duration_api_ms":0`, `"total_cost_usd":0` and zero input and output tokens, and the assistant line's message has `"model":""` (`usage/before-1-usage.json`, `usage/*-usage.stream.jsonl`). Each took 3–4 s. + +`/usage` gives its figures on a `-p` run only with `--output-format stream-json --verbose`: the assistant line carries `usage_report` (shape below). With `--output-format json` the result holds only the text ("Current session: 24% used · resets Dec 2 at 2:10pm …"), with no `usage_report`. + +So the spec's fallback (status line only) is not needed. + +### 2. Neither `/usage` nor `/status` names the plan (verified) + +`/usage`'s text says only "You are currently using your subscription to power your Claude Code usage", and `usage_report` has no plan field: its keys are `session` (this run's own totals) and `rate_limits` (`limits[]` and `extra_usage`). `/status` on a `-p` run answers "/status isn't available in this environment." (`usage/before-1-status.json`). + +What can be read instead: + +- **Subscription or API key.** The stream's `init` line has `apiKeySource`, `"none"` on the CLI login. The text's first line says "using your subscription". +- **Ultra.** A `session` row is present on Max; the spec reads weekly rows with no `session` row as Ultra (not produced by this trial). +- **Pro or Max.** Nothing tells them apart. `extra_usage.monthly_limit` is 1000 here, which is a spending cap Daniel set, not the plan. The spec's guess from the change around the first runs stands. + +### 3. How often the plan-limit request may be made (verified in part) + +The trial sent eight `/usage` requests in 14 minutes (two per read: stream-json and json). None failed or said it fell back to cached bars. The two reads 8 s apart returned the same `resets_at` to the microsecond (`2026-12-02T12:10:00.015059+00:00`), so the second was served from the first's fetch; the reads 3 minutes apart and after the runs each returned new microseconds (`.286838`, `.426517`), so they were fresh. The limit that triggers the 60-minute cached fallback (https://code.claude.com/docs/en/costs, "When the usage request fails") was not reached, so its size is unknown (unverified). The spec's rule, at most one `/usage` per run and at most one in 10 minutes, stays well under the rate seen here. + +A reading right after a run can lag it by a point (the 5-hour window above). A before/after pair should read "after" a few minutes after the run ends, or accept the lag in its uncertainty. + +## The `usage_report` shape + +Captured from a Max subscriber, `server/tests/fixtures/usage/subscriber-max.jsonl` (the after-2 read; the `init` line cut to its type, session, model, permission mode, `apiKeySource` and version, the text cut before its "What's contributing to your usage?" section, and the result's `credential_expires_at` timestamp removed): + +```json +"usage_report": { + "session": { "total_cost_usd": 0, "total_api_duration_ms": 0, "total_duration_ms": 2616, "total_lines_added": 0, "total_lines_removed": 0, "model_usage": {} }, + "rate_limits": { + "limits": [ + { "kind": "session", "group": "session", "percent": 30, "resets_at": "2026-12-02T12:10:00.426517+00:00", "scope": null, "severity": "normal", "is_active": false }, + { "kind": "weekly_all", "group": "weekly", "percent": 64, "resets_at": "2026-12-07T03:00:00.426538+00:00", "scope": null, "severity": "normal", "is_active": true }, + { "kind": "weekly_scoped", "group": "weekly", "percent": 0, "resets_at": "2026-12-07T03:00:00+00:00", "scope": { "model": { "display_name": "Fable" }, "surface": null }, "severity": "normal", "is_active": false } + ], + "extra_usage": { "is_enabled": false, "monthly_limit": 1000, "used_credits": 0, "utilization": 0, "currency": "USD" } + } +} +``` + +`percent` is a whole number and `resets_at` an ISO time, not the status line's epoch seconds. + +Shapes the trial could not produce, which the plan-detection ticket (#1061) writes by hand from the documented `SDKUsageReport` (https://code.claude.com/docs/en/agent-sdk/typescript.md): + +- **Ultra:** `weekly_all` (and `weekly_scoped`) rows with no `session` row. +- **API key:** no `rate_limits`, and `apiKeySource` other than `"none"`. +- **`null` report:** `"usage_report": null`, when the OAuth token lacks the `user:profile` scope. + +## The trial's figures for the cost estimate + +Under 3 records of a kind, the estimate uses these (#1056, "The cost estimate"). All are API price on Sonnet 5.5 unless said otherwise. + +| Kind | Unit | Range | Source | +|---|---|---|---| +| `first-map` | a part | $0.034–0.051 | this trial, the five drafts' per-part figures ($0.025–0.059) | +| `map-review` | a run | $0.35–0.82 | the 26 costed `map-review` lines in Daniel's `background-runs.jsonl` (median $0.41; model not recorded, mostly the Opus-default era) | +| `back-law` | a run | $0.32–0.39 | no run of the kind recorded; the lowest and highest of this trial's three chery reviewer runs, a read-heavy single run, as a stand-in (unverified as Back a law's cost) | +| `micro-world` | a run | $0.32–0.39 | no run of the kind recorded; the same stand-in (unverified) | + +The quartiles of `first-map` are of the five per-part figures (0.025, 0.042, 0.043, 0.043, 0.059) by the exclusive method (Python's `statistics.quantiles` default). Daniel's 20 costed `first-map` lines (quartiles $0.11–0.23 per run, all on `dsh`) have no `units`, so they give no per-part figure. + +## Re-running + +The factor drifts when Anthropic changes limits, and the hover shows its date. To re-run: the evidence folder's `run-cost-trial.sh`, in a quiet hour; for the weekly factor, about ten times the batch (some 50 drafts, about $25 API price), or the five drafts on Opus to measure the model's effect. diff --git a/server/tests/fixtures/usage/subscriber-max.jsonl b/server/tests/fixtures/usage/subscriber-max.jsonl new file mode 100644 index 00000000..00885d70 --- /dev/null +++ b/server/tests/fixtures/usage/subscriber-max.jsonl @@ -0,0 +1,3 @@ +{"type": "system", "subtype": "init", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "model": "claude-sonnet-5-5", "permissionMode": "dontAsk", "apiKeySource": "none", "claude_code_version": "2.1.331"} +{"type": "assistant", "message": {"diagnostics": null, "id": "dfee10ca-9e6e-48f9-83db-e07472057190", "container": null, "model": "", "role": "assistant", "stop_details": null, "stop_reason": "end_turn", "stop_sequence": null, "type": "message", "usage": {"output_tokens_details": null, "input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": null, "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": null, "iterations": null, "speed": null, "fallback_credit": null}, "content": [{"type": "text", "text": "You are currently using your subscription to power your Claude Code usage\n\nCurrent session: 30% used · resets Dec 2 at 2:10pm (Asia/Jerusalem)\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)"}], "context_management": null}, "parent_tool_use_id": null, "local_command_source": "You are currently using your subscription to power your Claude Code usage\n\nCurrent session: 30% used · resets Dec 2 at 2:10pm (Asia/Jerusalem)\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "uuid": "cccb4457-0fed-47e2-8ed2-e0da59915d8d", "timestamp": "2026-12-02T10:39:29.472Z", "usage_report": {"session": {"total_cost_usd": 0, "total_api_duration_ms": 0, "total_duration_ms": 2616, "total_lines_added": 0, "total_lines_removed": 0, "model_usage": {}}, "rate_limits": {"limits": [{"kind": "session", "group": "session", "percent": 30, "resets_at": "2026-12-02T12:10:00.426517+00:00", "scope": null, "severity": "normal", "is_active": false}, {"kind": "weekly_all", "group": "weekly", "percent": 64, "resets_at": "2026-12-07T03:00:00.426538+00:00", "scope": null, "severity": "normal", "is_active": true}, {"kind": "weekly_scoped", "group": "weekly", "percent": 0, "resets_at": "2026-12-07T03:00:00+00:00", "scope": {"model": {"display_name": "Fable"}, "surface": null}, "severity": "normal", "is_active": false}], "extra_usage": {"is_enabled": false, "monthly_limit": 1000, "used_credits": 0, "utilization": 0, "currency": "USD"}}}, "local_command_run": {"command": "usage", "args": ""}} +{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "total_cost_usd": 0, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": "", "iterations": [], "speed": "standard", "fallback_credit": null}, "modelUsage": {}, "permission_denials": [], "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "safety_stops": 0, "subtype": "success", "result": "You are currently using your subscription to power your Claude Code usage\n\nCurrent session: 30% used · resets Dec 2 at 2:10pm (Asia/Jerusalem)\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)", "local_command": "usage", "type": "result", "duration_ms": 2494, "uuid": "314939b2-c5ea-4f13-93cf-0ff11e34f476", "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": {}} From 6296379057e4e2a4c3e4c81f2db927522f9ef2eb Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 13:01:45 +0200 Subject: [PATCH 2/9] Studio: the run cost engine, estimates, actuals and the 7-day total in the plan's unit (#1059) Co-Authored-By: Claude Opus 5.5 --- server/src/lib.rs | 1 + server/src/run_cost.rs | 229 +++++++++++++++++++++++++++++++++++++++ server/tests/run_cost.rs | 225 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 455 insertions(+) create mode 100644 server/src/run_cost.rs create mode 100644 server/tests/run_cost.rs diff --git a/server/src/lib.rs b/server/src/lib.rs index 4ef227ed..ebcd47cc 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -54,6 +54,7 @@ pub mod prs; pub mod ratify; mod read_loop; mod records; +pub mod run_cost; pub mod runner; pub mod session_view; pub mod settings; diff --git a/server/src/run_cost.rs b/server/src/run_cost.rs new file mode 100644 index 00000000..a4ad1a22 --- /dev/null +++ b/server/src/run_cost.rs @@ -0,0 +1,229 @@ +//! Run cost's engine (spec danielrispler/plotkeeper#1056, ticket #1059): what a background run costs, in the plan's unit. +//! A pure module with no I/O. The estimate comes from recorded costs (the last 20 of a kind, their quartiles), or from the +//! calibration trial's figures when fewer than 3 are recorded; an actual figure and the 7-day total are recorded costs +//! turned into the plan's share of its windows with the trial's factor. The page only formats what this returns. + +use crate::runner::Kind; + +/// The calibration trial's factors (`docs/studio/research/run-cost.md`), in API-price dollars per percent of a window. +pub struct Factors { + /// The day the trial ran. + pub date: &'static str, + /// The plan it measured on. + pub plan: PlanKind, + /// The model every run used. + pub model: &'static str, + /// The 19 runs' session ids (their first 8 characters). + pub run_ids: &'static [&'static str], + /// Dollars per percent of the 5-hour window, on Max. + pub five_hour_per_percent: f64, + /// Dollars per percent of the week, on Max (derived, not measured: the trial gave a lower bound of $2.5). + pub weekly_per_percent: f64, +} + +pub const FACTORS: Factors = Factors { + date: "2026-12-02", + plan: PlanKind::Max, + model: "claude-sonnet-5-5", + run_ids: &[ + "ee8d24c1", "12ca069c", "c1c969ed", "45b29a8a", "58a2852b", "3e8d403b", "1132a07b", + "43bdce90", "03b20141", "d48c2ba0", "e812caac", "2c0f3eae", "0b8f5c3c", "bd18ebce", + "8cffa07d", "cc489dbe", "c506da08", "ff26cc77", "44f8f3b0", + ], + five_hour_per_percent: 0.41, + weekly_per_percent: 2.9, +}; + +/// Pro's percent is this fraction of Max's dollars. +const PRO_RATIO: f64 = 0.2; +/// Ultra's weekly percent is this many times Max's dollars. +const ULTRA_WEEKLY_RATIO: f64 = 2.0; +/// Records an estimate needs before it stops using the trial's figures. +const MIN_RECORDS: usize = 3; +/// Records an estimate reads, the newest. +const LAST_RECORDS: usize = 20; +const WEEK_MS: u64 = 7 * 86_400_000; + +/// The plan the figures are turned into. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PlanKind { + Pro, + Max, + Ultra, + /// An API key: dollars. + Api, + /// Not known: dollars, labelled as API price. + Unknown, +} + +/// What a run record gives the engine. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Record { + pub kind: Kind, + /// The parts a First map run covered; a First map record without it gives no per-part figure. + pub units: Option, + /// In dollars; none when the run reported no cost. + pub cost: Option, + /// When the run ended, in epoch milliseconds. + pub at_ms: u64, +} + +/// A figure in the plan's unit, in percent or dollars. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Shown { + /// A subscriber's shares; Ultra has no 5-hour window. + Share { + five_hour: Option, + weekly: f64, + }, + Dollars(f64), + ApiPrice(f64), +} + +/// The 25th to the 75th percentile of a run's cost. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct Estimate { + pub low: Shown, + pub high: Shown, +} + +/// Turns API-price dollars into the plan's unit. +pub fn convert(plan: PlanKind, dollars: f64) -> Shown { + let max = (FACTORS.five_hour_per_percent, FACTORS.weekly_per_percent); + match plan { + PlanKind::Max => Shown::Share { + five_hour: Some(dollars / max.0), + weekly: dollars / max.1, + }, + PlanKind::Pro => Shown::Share { + five_hour: Some(dollars / (max.0 * PRO_RATIO)), + weekly: dollars / (max.1 * PRO_RATIO), + }, + PlanKind::Ultra => Shown::Share { + five_hour: None, + weekly: dollars / (max.1 * ULTRA_WEEKLY_RATIO), + }, + PlanKind::Api => Shown::Dollars(dollars), + PlanKind::Unknown => Shown::ApiPrice(dollars), + } +} + +/// A run's recorded cost in the plan's unit; none when it reported none. +pub fn actual(plan: PlanKind, cost: Option) -> Option { + cost.map(|c| convert(plan, c)) +} + +/// The recorded costs of the last 7 days, all kinds and projects, dismissed runs included; none when they sum to nothing. +pub fn total(records: &[Record], now_ms: u64, plan: PlanKind) -> Option { + let sum: f64 = records + .iter() + .filter(|r| r.at_ms >= now_ms.saturating_sub(WEEK_MS)) + .filter_map(|r| r.cost) + .sum(); + (sum > 0.0).then(|| convert(plan, sum)) +} + +/// What `units` of a kind cost: First map's units are parts, every other kind's are runs. +pub fn estimate(records: &[Record], kind: Kind, units: u32, plan: PlanKind) -> Estimate { + let mut of_kind: Vec<&Record> = records + .iter() + .filter(|r| r.kind == kind && r.cost.is_some()) + .filter(|r| kind != Kind::FirstMap || r.units.is_some_and(|u| u > 0)) + .collect(); + of_kind.sort_by_key(|r| r.at_ms); + let start = of_kind.len().saturating_sub(LAST_RECORDS); + let mut per_unit: Vec = of_kind[start..] + .iter() + .map(|r| r.cost.unwrap_or(0.0) / f64::from(r.units.unwrap_or(1).max(1))) + .collect(); + let (low, high) = if per_unit.len() < MIN_RECORDS { + trial_range(kind) + } else { + per_unit.sort_by(f64::total_cmp); + (quantile(&per_unit, 1), quantile(&per_unit, 3)) + }; + let units = f64::from(units); + Estimate { + low: convert(plan, low * units), + high: convert(plan, high * units), + } +} + +/// The trial's per-unit dollars (`docs/studio/research/run-cost.md`, "The trial's figures for the cost estimate"). +fn trial_range(kind: Kind) -> (f64, f64) { + match kind { + Kind::FirstMap => (0.034, 0.051), + Kind::MapReview => (0.35, 0.82), + Kind::BackLaw | Kind::MicroWorld => (0.32, 0.39), + } +} + +/// The exclusive method (Python's `statistics.quantiles` default) over sorted values: the `quarters`/4 quantile. +fn quantile(sorted: &[f64], quarters: usize) -> f64 { + let n = sorted.len(); + let (whole, rest) = (quarters * (n + 1) / 4, quarters * (n + 1) % 4); + if whole < 1 { + return sorted[0]; + } + if whole >= n { + return sorted[n - 1]; + } + sorted[whole - 1] + (rest as f64 / 4.0) * (sorted[whole] - sorted[whole - 1]) +} + +/// A percent range: "under 1%" when it all is, "up to about N%" when only its low end is, else "about N%" or "about A–B%". +fn percents(low: f64, high: f64) -> String { + let (a, b) = (low.round(), high.round()); + if high < 1.0 { + "under 1%".to_string() + } else if low < 1.0 { + format!("up to about {b}%") + } else if a == b { + format!("about {a}%") + } else { + format!("about {a}–{b}%") + } +} + +fn dollars(low: f64, high: f64) -> String { + let (a, b) = (format!("${low:.2}"), format!("${high:.2}")); + if a == b { a } else { format!("{a}–{b}") } +} + +fn text(low: Shown, high: Shown) -> String { + match (low, high) { + ( + Shown::Share { + five_hour: fl, + weekly: wl, + }, + Shown::Share { + five_hour: fh, + weekly: wh, + }, + ) => { + let week = format!("{} of the week", percents(wl, wh)); + match (fl, fh) { + (Some(l), Some(h)) => format!("{} of the 5-hour window, {week}", percents(l, h)), + _ => week, + } + } + (Shown::Dollars(l), Shown::Dollars(h)) => dollars(l, h), + (Shown::ApiPrice(l), Shown::ApiPrice(h)) => format!("{} API price", dollars(l, h)), + _ => String::new(), + } +} + +impl Shown { + /// The words for the figure, such as "about 3% of the 5-hour window, under 1% of the week" or "$0.41 API price". + pub fn text(&self) -> String { + text(*self, *self) + } +} + +impl Estimate { + /// The words for the range, in the same form as [`Shown::text`]. + pub fn text(&self) -> String { + text(self.low, self.high) + } +} diff --git a/server/tests/run_cost.rs b/server/tests/run_cost.rs new file mode 100644 index 00000000..a404c2cd --- /dev/null +++ b/server/tests/run_cost.rs @@ -0,0 +1,225 @@ +//! Run cost's engine (spec #1056, ticket #1059): the unit conversion, the estimate from records and the 7-day total, as +//! tables over the module's public functions. Whether the factors are right is the trial's to say, not a test's. + +use studio_server::run_cost::{PlanKind, Record, actual, convert, estimate, total}; +use studio_server::runner::Kind; + +const DAY: u64 = 86_400_000; + +fn rec(kind: Kind, units: Option, cost: Option, at_ms: u64) -> Record { + Record { + kind, + units, + cost, + at_ms, + } +} + +#[test] +fn dollars_become_the_plans_unit() { + // (plan, dollars, text). Max: $0.41 per 5-hour percent, $2.9 per weekly percent. Pro: a fifth of Max's dollars per + // percent. Ultra: no 5-hour window, a weekly percent of twice Max's dollars. + let rows = [ + ( + PlanKind::Max, + 0.41, + "about 1% of the 5-hour window, under 1% of the week", + ), + ( + PlanKind::Max, + 4.10, + "about 10% of the 5-hour window, about 1% of the week", + ), + ( + PlanKind::Pro, + 0.41, + "about 5% of the 5-hour window, under 1% of the week", + ), + ( + PlanKind::Pro, + 0.82, + "about 10% of the 5-hour window, about 1% of the week", + ), + (PlanKind::Ultra, 5.80, "about 1% of the week"), + (PlanKind::Ultra, 0.41, "under 1% of the week"), + (PlanKind::Api, 0.41, "$0.41"), + (PlanKind::Unknown, 0.41, "$0.41 API price"), + ]; + for (plan, dollars, text) in rows { + assert_eq!(convert(plan, dollars).text(), text, "{plan:?} {dollars}"); + } + assert_eq!(actual(PlanKind::Api, Some(1.234)).unwrap().text(), "$1.23"); + assert_eq!(actual(PlanKind::Max, None), None); +} + +#[allow( + clippy::too_many_lines, + clippy::type_complexity, + reason = "one table with a row for each rule of the estimate" +)] +#[test] +fn the_estimate_comes_from_recent_records_or_the_trials_figures() { + let many = |kind, units, costs: &[f64]| -> Vec { + costs + .iter() + .enumerate() + .map(|(i, c)| rec(kind, units, Some(*c), i as u64 + 1)) + .collect() + }; + // 22 map reviews: the two oldest are far off and fall outside the last 20. + let mut twenty_two = many(Kind::MapReview, None, &[100.0, 100.0]); + twenty_two.extend( + many(Kind::MapReview, None, &[0.5; 20]) + .into_iter() + .map(|mut r| { + r.at_ms += 10; + r + }), + ); + let mut mixed = many(Kind::MapReview, None, &[0.2, 0.4, 0.6, 0.8]); + mixed.push(rec(Kind::MapReview, None, None, 9)); // no cost: not a record of the kind's cost + mixed.extend(many(Kind::BackLaw, None, &[50.0, 50.0, 50.0])); // another kind + + // (name, records, kind, units, plan, text) + let rows: Vec<(&str, Vec, Kind, u32, PlanKind, &str)> = vec![ + ( + "first map: quartiles of the per-part costs, times the parts", + many(Kind::FirstMap, Some(10), &[0.25, 0.42, 0.43, 0.43, 0.59]), + Kind::FirstMap, + 20, + PlanKind::Api, + "$0.67–$1.02", + ), + ( + "first map lines without units fall back to the trial", + many(Kind::FirstMap, None, &[0.5; 6]), + Kind::FirstMap, + 10, + PlanKind::Api, + "$0.34–$0.51", + ), + ( + "other kinds are per run, quartiles of the costs", + mixed, + Kind::MapReview, + 1, + PlanKind::Api, + "$0.25–$0.75", + ), + ( + "only the last 20 records count", + twenty_two, + Kind::MapReview, + 1, + PlanKind::Api, + "$0.50", + ), + ( + "map review with no records: the trial", + vec![], + Kind::MapReview, + 1, + PlanKind::Api, + "$0.35–$0.82", + ), + ( + "two back-law records are too few", + many(Kind::BackLaw, None, &[9.0, 9.0]), + Kind::BackLaw, + 1, + PlanKind::Api, + "$0.32–$0.39", + ), + ( + "micro-world with no records: the trial, times the runs, an unknown plan", + vec![], + Kind::MicroWorld, + 2, + PlanKind::Unknown, + "$0.64–$0.78 API price", + ), + ( + "Max has both windows", + vec![], + Kind::BackLaw, + 10, + PlanKind::Max, + "about 8–10% of the 5-hour window, about 1% of the week", + ), + ( + "Pro: a low weekly share reads as up to", + vec![], + Kind::MapReview, + 1, + PlanKind::Pro, + "about 4–10% of the 5-hour window, up to about 1% of the week", + ), + ( + "Ultra has no 5-hour share", + vec![], + Kind::BackLaw, + 100, + PlanKind::Ultra, + "about 6–7% of the week", + ), + ( + "a share under 1%", + many(Kind::MapReview, None, &[0.001; 3]), + Kind::MapReview, + 1, + PlanKind::Max, + "under 1% of the 5-hour window, under 1% of the week", + ), + ]; + for (name, records, kind, units, plan, text) in rows { + assert_eq!(estimate(&records, kind, units, plan).text(), text, "{name}"); + } +} + +#[test] +fn the_total_sums_the_last_seven_days() { + let now = 20 * DAY; + // Every project and dismissed runs are in the records alike: only the cost and the time decide. + let rows: Vec<(&str, Vec, Option<&str>)> = vec![ + ("no records", vec![], None), + ( + "every kind inside the week adds up", + vec![ + rec(Kind::FirstMap, Some(5), Some(0.5), now - DAY), + rec(Kind::BackLaw, None, Some(0.25), now - 6 * DAY), + rec(Kind::MicroWorld, None, Some(0.75), now), + ], + Some("$1.50"), + ), + ( + "a record older than 7 days is left out", + vec![ + rec(Kind::MapReview, None, Some(0.5), now - 7 * DAY - 1), + rec(Kind::MapReview, None, Some(0.25), now - 7 * DAY), + ], + Some("$0.25"), + ), + ( + "a missing cost adds nothing", + vec![ + rec(Kind::MapReview, None, None, now - DAY), + rec(Kind::MapReview, None, Some(0.5), now - DAY), + ], + Some("$0.50"), + ), + ( + "only missing costs: nothing to show", + vec![rec(Kind::MapReview, None, None, now - DAY)], + None, + ), + ]; + for (name, records, text) in rows { + let shown = total(&records, now, PlanKind::Api); + assert_eq!(shown.map(|s| s.text()).as_deref(), text, "{name}"); + } + let week = [rec(Kind::MapReview, None, Some(5.8), now)]; + assert_eq!( + total(&week, now, PlanKind::Ultra).unwrap().text(), + "about 1% of the week" + ); +} From 059af986f8c66f8d6f3f48f1735332e61e12b5b3 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 13:20:17 +0200 Subject: [PATCH 3/9] Studio: the run record and the views carry each run's cost (#1060) background-runs.jsonl's line gains optional units, model and subject; a view finds its runs' cost by subject once they are dismissed. settings.json gains plan {kind, confirmed}, unknown when unset or malformed. Estimates ride on the views with run buttons, actual costs on the views that keep a run's answer and on the runs list's rows, and the 7-day total on the list. Co-Authored-By: Claude Opus 5.5 --- server/examples/sandbox_gate.rs | 2 + server/src/api.rs | 3 +- server/src/back_a_law.rs | 11 ++ server/src/map.rs | 4 + server/src/map_draft.rs | 41 ++++++++ server/src/map_review.rs | 17 ++++ server/src/map_scan.rs | 29 +++++- server/src/micro_worlds.rs | 18 ++++ server/src/run_cost.rs | 33 +++++- server/src/runner.rs | 155 +++++++++++++++++++++++++++-- server/src/settings.rs | 16 +++ server/src/settings/tests.rs | 49 +++++++++ server/tests/back_a_law.rs | 9 +- server/tests/map_draft.rs | 50 ++++++++++ server/tests/map_review.rs | 21 +++- server/tests/micro_worlds.rs | 13 ++- server/tests/runner.rs | 171 +++++++++++++++++++++++++++----- server/tests/wire.rs | 33 ++++++ ui/settings.ts | 19 +++- ui/tests/settings.test.mjs | 22 ++++ ui/types.ts | 38 +++++-- 21 files changed, 703 insertions(+), 51 deletions(-) diff --git a/server/examples/sandbox_gate.rs b/server/examples/sandbox_gate.rs index 86c59ad6..1ac82b19 100644 --- a/server/examples/sandbox_gate.rs +++ b/server/examples/sandbox_gate.rs @@ -873,6 +873,8 @@ fn main() -> Result<(), String> { folder: work.clone(), prompt: p.prompt.clone(), limits: Limits::of(p.kind), + units: None, + subject: None, }) .map_err(|r| format!("{}: refused: {}", p.name, r.line))?; eprintln!("started {} as {id}", p.name); diff --git a/server/src/api.rs b/server/src/api.rs index b1daff4f..a6cffce3 100644 --- a/server/src/api.rs +++ b/server/src/api.rs @@ -170,8 +170,9 @@ pub fn call(app: &Arc, page: &dyn Page, name: &str, args: Value) -> Result< "turn_reply" => out(crate::turn_reply(app, arg(a, "id")?, arg(a, "index")?)), "agent_summary" => out(crate::agent_summary(app, arg(a, "agent_id")?)), "map_state" => res(crate::map_state(arc, arg(a, "project")?, arg(a, "fetch")?)), - "map_scan" => res(crate::map_scan::map_scan(arg(a, "project")?)), + "map_scan" => res(crate::map_scan::map_scan(&app.runner, arg(a, "project")?)), "map_scan_edit" => res(crate::map_scan::map_scan_edit( + &app.runner, arg(a, "project")?, arg(a, "map")?, arg(a, "edit")?, diff --git a/server/src/back_a_law.rs b/server/src/back_a_law.rs index f50ff82c..ced052bb 100644 --- a/server/src/back_a_law.rs +++ b/server/src/back_a_law.rs @@ -189,6 +189,9 @@ pub struct LawPatch { /// The PR whose brief's Guard with a law started the run (#401). #[serde(default)] pub guards: Option, + /// What its run cost, read from the run's record as the map is drawn: never kept in the patch's file. + #[serde(default, skip_deserializing, skip_serializing_if = "Option::is_none")] + pub cost: Option, } /// A new law (#401): its id, the part it is on and its sentence. The writer drafts one from a PR's facts; only the one Daniel @@ -536,6 +539,8 @@ impl LawRuns { folder: work, prompt, limits: Limits::of(Kind::BackLaw), + units: None, + subject: Some(law), }; Ok(match self.runner.submit(request) { Ok(id) => Started::Run { id }, @@ -565,6 +570,11 @@ impl LawRuns { .filter(|p| p.project == project), ); patches.sort_by(|a, b| (a.at, &a.id).cmp(&(b.at, &b.id))); + // A patch keeps its run's id, so its cost is found by that id on the run's record. + let costs = self.runner.costs(); + for patch in &mut patches { + patch.cost = costs.of_run(&patch.id); + } patches } @@ -766,6 +776,7 @@ impl LawRuns { url: None, text: asked.new.as_ref().map(|new| new.text.clone()), guards: asked.guards, + cost: None, }; // The proof is written down as it starts, so a start after plotkeeper stopped in it says so. let folder = self.config.data.join(PATCHES); diff --git a/server/src/map.rs b/server/src/map.rs index 703f09fb..23a80c00 100644 --- a/server/src/map.rs +++ b/server/src/map.rs @@ -108,6 +108,8 @@ pub struct MapState { pub micro_worlds: crate::micro_worlds::WorldsState, /// The patches of the project's back a law runs: being proven, rejected, or proven and kept (`back_a_law.rs`). pub law_patches: Vec, + /// What Back a law, Back this law or Start the run is estimated to cost (`run_cost.rs`). + pub law_estimate: Option, } /// Daniel's choices for one project, kept in the data folder: a saved `(x, y)` per part, actor or zone id, a tier per part id @@ -324,6 +326,7 @@ fn read_from(repo: &Path, pending: impl FnOnce(&str) -> Option) -> MapS pre_flight: None, micro_worlds: crate::micro_worlds::WorldsState::default(), law_patches: Vec::new(), + law_estimate: None, }; let Ok(main) = studio_workbench::main_checkout(repo) else { state.status = Status::NotGit; @@ -599,6 +602,7 @@ pub fn map_state(project: String, fetch: bool, app: &Arc) -> Result< state.pre_flight = crate::pre_flight::current(&project); state.micro_worlds = app.worlds.state(&project, state.commit.as_deref()); state.law_patches = app.laws.patches(&project); + state.law_estimate = Some(app.runner.costs().estimate(crate::runner::Kind::BackLaw, 1)); Ok(state) } diff --git a/server/src/map_draft.rs b/server/src/map_draft.rs index e11072db..b2c0067b 100644 --- a/server/src/map_draft.rs +++ b/server/src/map_draft.rs @@ -217,6 +217,8 @@ pub struct GroupView { pub redraft: bool, /// A redraft set aside: it failed, or the person undid it. pub undone: bool, + /// What Retry is estimated to cost, for a group that failed; none for any other. + pub estimate: Option, } /// A part whose redraft its reviewer supported: its purpose before, and why it was flagged. @@ -255,6 +257,9 @@ pub struct MapDraftView { /// Why Open a draft PR is muted once Accept unlocks: `gh` is missing or not logged in. None while Accept is locked, or when it is /// not muted. pub pr_muted: Option, + /// What the draft's runs cost together, writers, reviewers, redrafts and retries, found by the draft's id on their records once + /// they are dismissed; none while none recorded a cost. + pub cost: Option, } /// One row of Apply (`map_draft_place`): `files` in no part, given to the part `part`, or kept off the map when it is none. @@ -464,15 +469,20 @@ impl MapDrafts { let groups = group_parts(&sized); let ignored = ignored_of(&map); let mut requests = Vec::new(); + // The draft's id, which its runs' records keep: its batch's, the first run's id ([`Runner::submit_batch`]). + let mut id = None; for parts in &groups { let folder = runner.new_folder()?; fill(root, &head, &folder, &skeleton)?; + let id = id.get_or_insert_with(|| run_id(&folder)).clone(); requests.push(Request { kind: Kind::FirstMap, project: main.clone(), folder, prompt: writer_prompt(parts, &ignored, None), limits: Limits::of(Kind::FirstMap), + units: units_of(parts), + subject: id, }); } let ids = runner @@ -538,6 +548,7 @@ impl MapDrafts { fn read_view(&self, main: &str) -> Option { let draft = self.read(main)?; + let costs = self.runner().ok().map(|runner| runner.costs()); let (map, verdicts) = shown_map(&draft)?; // A list git cannot give leaves none loose here; Accept's own check still refuses the map. let loose = skeleton_of(&draft.skeleton) @@ -561,6 +572,17 @@ impl MapDrafts { why: group.why.clone(), redraft: group.redraft, undone: group.undone, + estimate: costs + .as_ref() + .filter(|_| { + matches!( + group.state, + GroupState::WriterFailed | GroupState::ReviewerFailed + ) + }) + .map(|costs| { + costs.estimate(Kind::FirstMap, units_of(&group.parts).unwrap_or(1)) + }), }) .collect(), verdicts, @@ -578,6 +600,9 @@ impl MapDrafts { .display() .to_string(), pr_muted: None, + cost: costs + .zip(draft.batch.as_deref()) + .and_then(|(costs, id)| costs.spent(Kind::FirstMap, main, id)), }) } @@ -596,6 +621,7 @@ impl MapDrafts { result: String::new(), denials: Vec::new(), cost: None, + model: None, exit: None, }, true, @@ -709,6 +735,8 @@ impl MapDrafts { folder, prompt: map_review::prompt(&items, Wording::DRAFT), limits: Limits::of(Kind::FirstMap), + units: units_of(&draft.groups[at].parts), + subject: draft.batch.clone(), }, ) })(); @@ -787,6 +815,8 @@ impl MapDrafts { folder, prompt, limits: Limits::of(Kind::FirstMap), + units: units_of(&group.parts), + subject: draft.batch.clone(), }, ) } @@ -1461,6 +1491,17 @@ fn unwritten_why(group: &Group) -> Option { Some(format!("The writer left {named} unwritten: retry it")) } +/// The id of the run whose working folder is `folder`, as [`Runner::new_folder`] names it: `//work`. +fn run_id(folder: &Path) -> Option { + let dir = folder.parent()?; + Some(dir.file_name()?.to_string_lossy().into_owned()) +} + +/// The units a group's run records: its parts, none for the zone group's. +fn units_of(parts: &[String]) -> Option { + u32::try_from(parts.len()).ok().filter(|n| *n > 0) +} + /// Fails `group` at `state` with `why`. A redraft that fails is set aside: the part's text stands as it was, and Accept does not /// wait for it. fn fail(group: &mut Group, state: GroupState, why: String) { diff --git a/server/src/map_review.rs b/server/src/map_review.rs index faecce0f..da0d4d5b 100644 --- a/server/src/map_review.rs +++ b/server/src/map_review.rs @@ -378,6 +378,11 @@ fn text_of(change: &MapItem) -> Vec { items } +/// The subject a review's runs record (`runner.rs`, [`Request`]): its PR and head. +fn subject(pr: u64, head: &str) -> String { + format!("{pr}@{head}") +} + /// FNV-1a of `text`, in hex (`records::fnv1a`). pub(crate) fn hash(text: &str) -> String { format!("{:016x}", crate::records::fnv1a(text)) @@ -435,6 +440,11 @@ pub struct ReviewView { /// shows of its review only a failure, with "Run again", and the flags not decided: no "Reviewing map text…", no count and no /// "Review map text" (spec #687, "What the page reads"). pub changed: bool, + /// What the head's review runs cost together, found by the PR and head on their records once they are dismissed; none while + /// none recorded a cost. + pub cost: Option, + /// What "Review map text" or "Run again" is estimated to cost. + pub estimate: Option, } /// A flagged still-true item (spec #687): its verdict, and its name and text as the head's map has them. @@ -889,6 +899,8 @@ impl MapReviews { folder, prompt: prompt(missing, Wording::REVIEW), limits: Limits::of(Kind::MapReview), + units: None, + subject: Some(subject(pr, head)), }) .map_err(|refusal| refusal.line) } @@ -958,6 +970,7 @@ impl MapReviews { if !changed && state != ReviewState::Failed && still_true.is_empty() { return None; } + let costs = self.runner.upgrade().map(|runner| runner.costs()); Some(ReviewView { head: head.to_string(), state, @@ -968,6 +981,10 @@ impl MapReviews { left_out, still_true, changed, + cost: costs + .as_ref() + .and_then(|costs| costs.spent(Kind::MapReview, project, &subject(pr, head))), + estimate: costs.map(|costs| costs.estimate(Kind::MapReview, 1)), }) } diff --git a/server/src/map_scan.rs b/server/src/map_scan.rs index efe7cea0..c0a9aa99 100644 --- a/server/src/map_scan.rs +++ b/server/src/map_scan.rs @@ -29,6 +29,8 @@ pub struct MapScan { pub splits: BTreeMap>, /// The zones the edit removed because fewer than two parts were left in them (#855); none for the scan. pub dissolved: Vec, + /// What Draft the map is estimated to cost for the skeleton's parts, its reviewers and redrafts included (`run_cost.rs`). + pub estimate: Option, } /// A zone an edit removed (`MapScan.dissolved` in `ui/types.ts`): its name, and how many parts were left in it, one or none. @@ -60,10 +62,28 @@ pub enum Edit { } /// `map_scan_edit`: the skeleton `map` the page holds with `edit` made, and the scan screen for it, its lines computed again. -pub fn map_scan_edit(project: String, map: String, edit: Edit) -> Result { +pub fn map_scan_edit( + runner: &crate::runner::Runner, + project: String, + map: String, + edit: Edit, +) -> Result { let shell = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into()); let claude = studio_understanding::find(shell.as_ref(), "claude").is_some(); - edit_of(Path::new(&project), &map, edit, claude) + edit_of(Path::new(&project), &map, edit, claude).map(|scan| estimated(runner, scan)) +} + +/// `scan` with Draft the map's estimate for its parts. +fn estimated(runner: &crate::runner::Runner, scan: MapScan) -> MapScan { + let parts = u32::try_from(scan.files.len()).unwrap_or(u32::MAX); + MapScan { + estimate: Some( + runner + .costs() + .estimate(crate::runner::Kind::FirstMap, parts), + ), + ..scan + } } /// The skeleton `map` of the main checkout of `repo` with `edit` made, and its scan screen. The parts' paths stay apart (none inside @@ -522,10 +542,10 @@ fn split_of(map: &Value, id: &str, files: &[String]) -> Option<(Vec, Vec } /// `map_scan`: the scan of `project`'s main checkout, and whether the runner would find `claude`. -pub fn map_scan(project: String) -> Result { +pub fn map_scan(runner: &crate::runner::Runner, project: String) -> Result { let shell = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into()); let claude = studio_understanding::find(shell.as_ref(), "claude").is_some(); - scan_of(Path::new(&project), claude) + scan_of(Path::new(&project), claude).map(|scan| estimated(runner, scan)) } /// The scan of the main checkout of `repo`, with `claude` as found: the skeleton gets the edges `check_text` computes on it as @@ -615,6 +635,7 @@ fn screen_of( splits, map: map.to_string(), dissolved: Vec::new(), + estimate: None, } } diff --git a/server/src/micro_worlds.rs b/server/src/micro_worlds.rs index 3cdd3247..65581f92 100644 --- a/server/src/micro_worlds.rs +++ b/server/src/micro_worlds.rs @@ -321,6 +321,9 @@ pub struct View { pub line: Option, /// The prompt to copy, once it failed. pub prompt: Option, + /// What the runs that built it at its commit cost together, a rewrite and a failed try included, found by its key and commit on + /// their records; none while none recorded a cost. + pub cost: Option, } /// A project's micro-worlds on the map, and whether a run can build one (`microWorlds.dshVisual` is set). @@ -328,6 +331,8 @@ pub struct View { pub struct WorldsState { pub on: bool, pub worlds: BTreeMap, + /// What "Explore this", Rebuild or Try again is estimated to cost. + pub estimate: Option, } /// What "Explore this" did: started a run, or gave the prompt to copy and why. @@ -348,6 +353,12 @@ pub struct MicroWorlds { me: Weak, } +/// The subject a world's runs record (`runner.rs`, [`Request`]): its key and the commit they build at, so a rebuild at a new commit +/// counts apart. +fn subject(record: &Record) -> String { + format!("{}@{}", record.key, record.commit) +} + fn hex(text: &str) -> String { text.bytes().map(|b| format!("{b:02x}")).collect() } @@ -485,6 +496,8 @@ impl MicroWorlds { folder: folder.clone(), prompt: run_prompt(&topic, failure), limits: Limits::of(Kind::MicroWorld), + units: None, + subject: Some(subject(&record)), }) .map_err(|refusal| refusal.line)?; Ok::<_, String>((id, folder)) @@ -637,6 +650,7 @@ impl MicroWorlds { /// `project`'s micro-worlds as the map shows them, out of date against `current`, the map's commit now. pub fn state(&self, project: &str, current: Option<&str>) -> WorldsState { + let costs = self.runner.upgrade().map(|runner| runner.costs()); let worlds = self.store.records(project).into_iter().map(|record| { let page = self.page_file(project, &record.key).exists(); let stale = page @@ -652,12 +666,16 @@ impl MicroWorlds { stale, line: record.why.clone(), prompt: (record.phase == Phase::Failed).then(|| record.prompt.clone()), + cost: costs + .as_ref() + .and_then(|costs| costs.spent(Kind::MicroWorld, project, &subject(&record))), }; (record.key, view) }); WorldsState { on: self.scripts().is_some(), worlds: worlds.collect(), + estimate: costs.map(|costs| costs.estimate(Kind::MicroWorld, 1)), } } diff --git a/server/src/run_cost.rs b/server/src/run_cost.rs index a4ad1a22..f0472e01 100644 --- a/server/src/run_cost.rs +++ b/server/src/run_cost.rs @@ -4,6 +4,7 @@ //! turned into the plan's share of its windows with the trial's factor. The page only formats what this returns. use crate::runner::Kind; +use serde::{Deserialize, Serialize}; /// The calibration trial's factors (`docs/studio/research/run-cost.md`), in API-price dollars per percent of a window. pub struct Factors { @@ -44,8 +45,9 @@ const MIN_RECORDS: usize = 3; const LAST_RECORDS: usize = 20; const WEEK_MS: u64 = 7 * 86_400_000; -/// The plan the figures are turned into. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +/// The plan the figures are turned into, as `settings.json`'s `plan.kind` names it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] pub enum PlanKind { Pro, Max, @@ -53,6 +55,7 @@ pub enum PlanKind { /// An API key: dollars. Api, /// Not known: dollars, labelled as API price. + #[default] Unknown, } @@ -87,6 +90,32 @@ pub struct Estimate { pub high: Shown, } +/// A figure as the page shows it (`Figure` in `ui/types.ts`): its words, and for a share the day the trial measured the factor it +/// rests on, for the hover to say. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Figure { + pub text: String, + pub measured: Option, +} + +impl From for Figure { + fn from(shown: Shown) -> Figure { + Figure { + text: shown.text(), + measured: matches!(shown, Shown::Share { .. }).then(|| FACTORS.date.to_string()), + } + } +} + +impl From for Figure { + fn from(estimate: Estimate) -> Figure { + Figure { + text: estimate.text(), + measured: matches!(estimate.low, Shown::Share { .. }).then(|| FACTORS.date.to_string()), + } + } +} + /// Turns API-price dollars into the plan's unit. pub fn convert(plan: PlanKind, dollars: f64) -> Shown { let max = (FACTORS.five_hour_per_percent, FACTORS.weekly_per_percent); diff --git a/server/src/runner.rs b/server/src/runner.rs index 65aedcf8..49341078 100644 --- a/server/src/runner.rs +++ b/server/src/runner.rs @@ -19,6 +19,7 @@ //! [`Runner::resume`]. use crate::records::Notice; +use crate::run_cost::{self, Figure, PlanKind}; use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, @@ -125,6 +126,12 @@ pub struct Request { pub folder: PathBuf, pub prompt: String, pub limits: Limits, + /// The parts a First map writer or reviewer group covers, kept on the run's record for the per-part estimate; none for + /// every other run. + pub units: Option, + /// The key of the view that keeps the run's answer (a Map draft's id, a review's PR and head, a law's id, a micro-world's + /// key and commit), kept on the run's record so the view finds the run's cost once the run is dismissed. + pub subject: Option, } /// The command the launcher starts for a run, with what it adds to and takes from plotkeeper's own environment. @@ -496,6 +503,8 @@ pub struct Outcome { pub denials: Vec, /// In US dollars, as the harness reports it. pub cost: Option, + /// The model that cost the most in the result's `modelUsage`; none when it gave none. + pub model: Option, /// The harness's exit code; none when it was stopped, died or never started. pub exit: Option, } @@ -508,6 +517,7 @@ impl Outcome { result, denials: Vec::new(), cost: None, + model: None, exit: None, } } @@ -537,6 +547,8 @@ pub struct RunView { pub denials: Vec, /// The fallback: the run's prompt, for Daniel to paste into his own agent, on every end but a clean one. pub prompt: Option, + /// An ended run's recorded cost in the plan's unit (`run_cost.rs`); none while it runs, and when it reported none. + pub cost: Option
, } /// A project's runs, in the order they were asked for, and the one line that says why every queue is paused. @@ -544,6 +556,8 @@ pub struct RunView { pub struct Runs { pub paused: Option, pub runs: Vec, + /// What every run of the last 7 days cost, all projects, dismissed runs included; none when that is nothing. + pub total: Option
, } /// Why a run did not start, and the prompt to copy instead. @@ -553,6 +567,82 @@ pub struct Refusal { pub prompt: String, } +/// One line of the record of runs, `background-runs.jsonl`. `units`, `model` and `subject` are from #1060: a line from before +/// has none, and a field a run has none of is left out. +#[derive(Debug, Serialize, Deserialize)] +struct Line { + /// Unix seconds. + at: u64, + id: String, + kind: Kind, + project: String, + /// How the run ended, or `cancelled`. + outcome: serde_json::Value, + #[serde(default)] + denials: Vec, + #[serde(default)] + cost: Option, + #[serde(default)] + duration_ms: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + units: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + subject: Option, +} + +/// The record of runs and the plan, read once ([`Runner::costs`]), for the cost figures the views carry (spec #1056): an +/// estimate before a run, what a view's runs cost, and the 7-day total. +pub struct Costs { + lines: Vec, + plan: PlanKind, + now_ms: u64, +} + +impl Costs { + fn records(&self) -> Vec { + let record = |line: &Line| run_cost::Record { + kind: line.kind, + units: line.units, + cost: line.cost, + at_ms: line.at.saturating_mul(1000), + }; + self.lines.iter().map(record).collect() + } + + /// What `units` of `kind` are estimated to cost: parts for First map, runs for every other kind. + pub fn estimate(&self, kind: Kind, units: u32) -> Figure { + run_cost::estimate(&self.records(), kind, units, self.plan).into() + } + + /// `cost` in the plan's unit; none when it is none. + pub fn actual(&self, cost: Option) -> Option
{ + run_cost::actual(self.plan, cost).map(Figure::from) + } + + /// What `project`'s runs of `kind` for `subject` cost together, dismissed or not; none when none recorded a cost. + pub fn spent(&self, kind: Kind, project: &str, subject: &str) -> Option
{ + let costs = self + .lines + .iter() + .filter(|line| line.kind == kind && line.project == project) + .filter(|line| line.subject.as_deref() == Some(subject)) + .filter_map(|line| line.cost); + self.actual(costs.reduce(|a, b| a + b)) + } + + /// What run `id` cost, by its record; none when it recorded none. + pub fn of_run(&self, id: &str) -> Option
{ + self.actual(self.lines.iter().find(|line| line.id == id)?.cost) + } + + /// What every run of the last 7 days cost, all projects, dismissed runs included; none when that is nothing. + pub fn total(&self) -> Option
{ + run_cost::total(&self.records(), self.now_ms, self.plan).map(Figure::from) + } +} + /// Where the runner keeps its things and what it starts. pub struct Config { /// plotkeeper's data folder: a run may not read it, and the record of runs is kept in it. @@ -610,6 +700,11 @@ struct Stored { /// What the run warns of, read when it was submitted ([`Harness::warning`]); a run from before #774 has none. #[serde(default, skip_serializing_if = "Option::is_none")] warning: Option, + /// The request's units and subject, for its record; a run from before #1060 has none. + #[serde(default, skip_serializing_if = "Option::is_none")] + units: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + subject: Option, } /// What the launcher reads of `run.json`: only what it runs, so a run of a kind this build does not know still keeps its @@ -1078,6 +1173,7 @@ struct Printed { /// It says the run is an error, by `is_error` or by a `subtype` that names one, such as `error_max_turns`. is_error: bool, cost: Option, + model: Option, denials: Vec, } @@ -1095,6 +1191,7 @@ fn read_result(stdout: &str) -> Printed { result: stdout.trim().to_string(), is_error: false, cost: None, + model: None, denials: Vec::new(), }; }; @@ -1114,6 +1211,14 @@ fn read_result(stdout: &str) -> Printed { ) }); let subtype = result["subtype"].as_str().unwrap_or_default(); + // The model that cost the most, the first named when none says its cost. + let mut models: Vec<(&String, f64)> = result["modelUsage"] + .as_object() + .into_iter() + .flatten() + .map(|(model, usage)| (model, usage["costUSD"].as_f64().unwrap_or(0.0))) + .collect(); + models.sort_by(|a, b| b.1.total_cmp(&a.1)); Printed { result: result["result"] .as_str() @@ -1122,6 +1227,7 @@ fn read_result(stdout: &str) -> Printed { .to_string(), is_error: result["is_error"].as_bool().unwrap_or(false) || subtype.starts_with("error"), cost: result["total_cost_usd"].as_f64(), + model: models.first().map(|(model, _)| (*model).clone()), denials: denials.collect(), } } @@ -1146,6 +1252,7 @@ fn read_outcome(dir: &Path) -> (Outcome, Option) { result, is_error, cost, + model, denials, } = read_result(&text(STDOUT)); let errors = text(STDERR); @@ -1180,6 +1287,7 @@ fn read_outcome(dir: &Path) -> (Outcome, Option) { }, denials, cost, + model, exit: status.exit, } }; @@ -1496,6 +1604,8 @@ impl Runner { command, batch, warning, + units: request.units, + subject: request.subject.clone(), }; write_json(&dir.join(RUN), &stored) .map_err(|e| refuse(format!("the run could not be saved: {e}")))?; @@ -1784,7 +1894,8 @@ impl Runner { end } - /// Appends one line to the record of runs: kind, project, outcome, denials, cost and duration. `outcome` is how the + /// Appends one line to the record of runs: kind, project, outcome, denials, cost, duration, and the units, model and + /// subject a run has. `outcome` is how the /// run ended, or `cancelled`; `of` is what an ended run gave back. fn record( &self, @@ -1793,16 +1904,20 @@ impl Runner { of: Option<&Outcome>, duration_ms: u64, ) { - let line = serde_json::json!({ - "at": millis() / 1000, - "id": stored.id, - "kind": stored.kind, - "project": stored.project, - "outcome": outcome, - "denials": of.map_or(&[][..], |of| &of.denials), - "cost": of.and_then(|of| of.cost), - "duration_ms": duration_ms, - }); + let line = serde_json::to_string(&Line { + at: millis() / 1000, + id: stored.id.clone(), + kind: stored.kind, + project: stored.project.clone(), + outcome, + denials: of.map_or_else(Vec::new, |of| of.denials.clone()), + cost: of.and_then(|of| of.cost), + duration_ms, + units: stored.units, + model: of.and_then(|of| of.model.clone()), + subject: stored.subject.clone(), + }) + .unwrap_or_default(); let appended = fs::create_dir_all(&self.config.data).and_then(|()| { let mut file = OpenOptions::new() .create(true) @@ -2087,6 +2202,7 @@ impl Runner { /// `project`'s runs as the map shows them, and the pause line. pub fn runs(&self, project: &str) -> Runs { + let costs = self.costs(); let state = self.state(); let runs = state .runs @@ -2113,11 +2229,28 @@ impl Runner { prompt: outcome .filter(|outcome| outcome.end != End::Done) .map(|_| stored.prompt.clone()), + cost: outcome.and_then(|outcome| costs.actual(outcome.cost)), } }); Runs { paused: state.paused.map(|why| why.line().to_string()), runs: runs.collect(), + total: costs.total(), + } + } + + /// The record of runs and the plan `settings.json` names, read now, for the views' cost figures. + pub fn costs(&self) -> Costs { + let text = fs::read_to_string(&self.config.settings).unwrap_or_default(); + let lines = fs::read_to_string(self.config.data.join(RECORDS)).unwrap_or_default(); + Costs { + // A line this build cannot read, such as a kind it does not know, is left out. + lines: lines + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(), + plan: crate::settings::plan_in(&text).kind, + now_ms: millis(), } } diff --git a/server/src/settings.rs b/server/src/settings.rs index a2e4d5a4..57acbd17 100644 --- a/server/src/settings.rs +++ b/server/src/settings.rs @@ -458,6 +458,22 @@ pub fn run_settings_in(text: &str, project: &str) -> RunSettings { } } +/// The plan run cost's figures are turned into (spec #1056, "The plan"): `settings.json`'s `plan`, whose `confirmed` says Daniel +/// confirmed or picked it rather than detection guessing it. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +pub struct Plan { + pub kind: crate::run_cost::PlanKind, + #[serde(default)] + pub confirmed: bool, +} + +/// `plan` in `settings.json`'s `text`: unknown and not confirmed when it is unset or malformed, as the page reports it +/// (`ui/settings.ts`). +pub fn plan_in(text: &str) -> Plan { + let json: serde_json::Value = serde_json::from_str(&plain_json(text)).unwrap_or_default(); + serde_json::from_value(json["plan"].clone()).unwrap_or_default() +} + /// `microWorlds.dshVisual` in `settings.json`'s `text`: the folder that holds dsh-visual's `build.py` and `verify.mjs`, which /// a micro-world's host check runs (#399), a leading `~/` read as `home`. None when it is unset, empty or not a string: then /// "Explore this" offers only the prompt to copy. diff --git a/server/src/settings/tests.rs b/server/src/settings/tests.rs index eda52e6b..906de37f 100644 --- a/server/src/settings/tests.rs +++ b/server/src/settings/tests.rs @@ -53,6 +53,55 @@ fn micro_worlds_read_dsh_visuals_folder_with_the_home_folder_for_a_tilde() { } } +#[test] +fn the_plan_is_unknown_until_settings_name_one_and_a_malformed_one_reads_as_unknown() { + use crate::run_cost::PlanKind; + let plan = |kind, confirmed| super::Plan { kind, confirmed }; + let rows = [ + // Unset, and a file that does not parse. + (r#"{}"#, plan(PlanKind::Unknown, false)), + ("{ broken", plan(PlanKind::Unknown, false)), + // Each kind, detected (confirmed missing reads as not confirmed) or confirmed. + ( + r#"{ "plan": { "kind": "pro" } }"#, + plan(PlanKind::Pro, false), + ), + ( + r#"{ "plan": { "kind": "max", "confirmed": false } }"#, + plan(PlanKind::Max, false), + ), + ( + r#"{ "plan": { "kind": "ultra", "confirmed": true }, }"#, + plan(PlanKind::Ultra, true), + ), + ( + r#"{ "plan": { "kind": "api", "confirmed": true } }"#, + plan(PlanKind::Api, true), + ), + ( + r#"{ "plan": { "kind": "unknown", "confirmed": true } }"#, + plan(PlanKind::Unknown, true), + ), + // Malformed: unknown and not confirmed. + (r#"{ "plan": "max" }"#, plan(PlanKind::Unknown, false)), + ( + r#"{ "plan": { "kind": "gold", "confirmed": true } }"#, + plan(PlanKind::Unknown, false), + ), + ( + r#"{ "plan": { "confirmed": true } }"#, + plan(PlanKind::Unknown, false), + ), + ( + r#"{ "plan": { "kind": "max", "confirmed": "yes" } }"#, + plan(PlanKind::Unknown, false), + ), + ]; + for (text, want) in rows { + assert_eq!(super::plan_in(text), want, "{text}"); + } +} + #[test] fn the_explanations_switch_writes_its_one_key_and_keeps_the_rest() { let home = tempfile::tempdir().unwrap(); diff --git a/server/tests/back_a_law.rs b/server/tests/back_a_law.rs index 926faec8..8f101f00 100644 --- a/server/tests/back_a_law.rs +++ b/server/tests/back_a_law.rs @@ -86,7 +86,7 @@ git add tests/add.test.mjs system-map.json "# ); const PLANT: &str = "echo 'export const add = (a, b) => a - b;' > src/add.mjs\n"; -const DONE: &str = r#"echo '{"type":"result","subtype":"success","is_error":false,"result":"Backed.","permission_denials":[]}'"#; +const DONE: &str = r#"echo '{"type":"result","subtype":"success","is_error":false,"result":"Backed.","permission_denials":[],"total_cost_usd":0.3}'"#; struct Bench { /// Daniel's repository, a clone of `origin` on a branch of his own. @@ -344,6 +344,13 @@ fn a_well_formed_run_is_proven_and_stored_and_the_repository_is_untouched() { .join(format!("{id}.json")); assert!(stored.exists()); assert!(!bench.work(&id).exists(), "the clone is removed"); + // The patch carries its run's cost, read from the run's record and never kept in the patch's file (#1060). + assert_eq!( + patch.cost.map(|cost| cost.text).as_deref(), + Some("$0.30 API price") + ); + let kept = fs::read_to_string(&stored).unwrap(); + assert!(!kept.contains("cost"), "{kept}"); // Daniel's repository: its branches, its git data and its files, byte for byte. assert_eq!(snapshot(&bench.repo), before); assert_eq!(git(&bench.repo, &["branch", "--show-current"]), "mine"); diff --git a/server/tests/map_draft.rs b/server/tests/map_draft.rs index 65db258d..7e31356a 100644 --- a/server/tests/map_draft.rs +++ b/server/tests/map_draft.rs @@ -386,6 +386,15 @@ impl Bench { self.pending().with_file_name(format!("{name}.json")) } + /// The record of runs, a line each. + fn records(&self) -> Vec { + fs::read_to_string(self.root().join("data/background-runs.jsonl")) + .unwrap_or_default() + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect() + } + /// Where the map waiting on a draft PR is kept, as the Map view reads it. fn pending(&self) -> PathBuf { studio_server::map::pending_file(&self.main()).unwrap() @@ -782,6 +791,26 @@ fn the_groups_land_in_order_and_each_reviewer_checks_its_groups_purposes_alone() assert_eq!(view.verdicts["c"].why, "c is contradicted."); // The ended runs are dismissed: their folders held only a copy of the repository. assert!(bench.runner.runs(&bench.main()).runs.is_empty()); + // Their cost is still found, by the draft's id on their records: 7 runs at $0.10, in API price while no plan is set + // (#1060). Each records the parts its group covered; the zone run and its reviewer cover none. + assert_eq!( + view.cost.as_ref().map(|cost| cost.text.as_str()), + Some("$0.70 API price") + ); + let records = bench.records(); + assert_eq!(records.len(), 7, "{records:?}"); + assert!( + records + .iter() + .all(|r| r["subject"] == records[0]["subject"] && r["subject"].is_string()), + "{records:?}" + ); + let mut units: Vec> = records.iter().map(|r| r["units"].as_u64()).collect(); + units.sort_unstable(); + assert_eq!( + units, + [None, None, Some(1), Some(1), Some(1), Some(2), Some(2)] + ); // An edit shows over the writers' text, and is kept. let edit = Edit { @@ -814,6 +843,10 @@ fn the_groups_land_in_order_and_each_reviewer_checks_its_groups_purposes_alone() } #[test] +#[allow( + clippy::too_many_lines, + reason = "one failed group followed from its failure, with its Retry estimate, through its retry" +)] fn a_failed_group_is_kept_apart_and_retried_alone() { let bench = bench(); // The first writer answers no JSON; the second group's reviewer cannot start, its launcher gone by then. @@ -840,6 +873,21 @@ fn a_failed_group_is_kept_apart_and_retried_alone() { why.starts_with("The reviewer failed: the launcher") && why.contains("did not start"), "{why}" ); + // Each failed group carries what its Retry is estimated to cost, by its parts: with under 3 First map records, from the + // trial's $0.034–0.051 a part (#1060). The waiting zone group has none. + let estimates: Vec> = view + .groups + .iter() + .map(|group| group.estimate.as_ref().map(|e| e.text.as_str())) + .collect(); + assert_eq!( + estimates, + [ + Some("$0.03–$0.05 API price"), + Some("$0.07–$0.10 API price"), + None + ] + ); // The rest stand: the second group's text shows. The zone run waits for the failed writer group. assert_eq!(purpose_of(&view, "b"), "b does its job."); assert!(!view.ready); @@ -1127,6 +1175,8 @@ fn discard_mid_batch_stops_every_run_frees_the_slot_and_deletes_the_draft() { folder: bench.runner.new_folder().unwrap(), prompt: "later".into(), limits: Limits::of(Kind::FirstMap), + units: None, + subject: None, }) .unwrap(); let state = |id: &str| { diff --git a/server/tests/map_review.rs b/server/tests/map_review.rs index 93e92a49..18924990 100644 --- a/server/tests/map_review.rs +++ b/server/tests/map_review.rs @@ -212,7 +212,7 @@ impl Bench { } fn answer_raw(&self, result: &str) { - let out = serde_json::json!({ "type": "result", "subtype": "success", "is_error": false, "result": result }); + let out = serde_json::json!({ "type": "result", "subtype": "success", "is_error": false, "result": result, "total_cost_usd": 0.42 }); fs::write(self.root().join("answer.json"), out.to_string()).unwrap(); } @@ -934,12 +934,31 @@ fn a_finished_reviews_run_is_dismissed_once_its_answer_is_kept() { let bench = bench(); bench.author("daniel"); bench.all_supported(); + // On Max, a run's cost is a share of the plan's windows (#1060). + fs::write( + bench.root().join("data/settings.json"), + r#"{ "plan": { "kind": "max", "confirmed": true } }"#, + ) + .unwrap(); let head = bench.first_head(); bench.reviews.brief_stored(&bench.project(), 7, &head); assert_eq!(bench.settled(&head).state, ReviewState::Done); until(&bench, "the run was never dismissed", || { bench.runner.runs(&bench.project()).runs.is_empty() }); + // The view still finds the run's cost, by the PR and head on its record, with the day the factor was measured; and Run + // again's estimate, from the trial's figures with no review recorded before. + let view = bench.reviews.view(&bench.project(), 7, &head).unwrap(); + let cost = view.cost.unwrap(); + assert_eq!( + cost.text, + "about 1% of the 5-hour window, under 1% of the week" + ); + assert_eq!(cost.measured.as_deref(), Some("2026-12-02")); + assert_eq!( + view.estimate.map(|e| e.text).as_deref(), + Some("up to about 2% of the 5-hour window, under 1% of the week") + ); let folders: Vec = fs::read_dir(bench.root().join("runs")) .unwrap() .map(|entry| entry.unwrap().path()) diff --git a/server/tests/micro_worlds.rs b/server/tests/micro_worlds.rs index b10f0304..7feafa0d 100644 --- a/server/tests/micro_worlds.rs +++ b/server/tests/micro_worlds.rs @@ -36,6 +36,9 @@ fn writes(page: &str) -> String { format!("printf '%s' '{quoted}' > .micro-world/template.html") } +/// The harness's result, costing $0.20. +const COSTS: &str = r#"echo '{"type":"result","subtype":"success","is_error":false,"result":"Built.","total_cost_usd":0.2}'"#; + const GOOD: &str = "World

the turn's journey

"; const BAD: &str = "

VERIFY-FAIL

"; @@ -310,8 +313,9 @@ fn the_api_serves_only_a_stored_checked_page() { #[test] fn a_failing_page_is_rewritten_once_with_what_failed() { // The first run writes a failing page; the rewrite, which finds it and is told what failed, writes a good one. + // Each run costs $0.20. let script = format!( - "if [ -e .micro-world/template.html ] && printf '%s' \"$PROMPT\" | grep -q 'no horizontal overflow'; then {}; else {}; fi", + "if [ -e .micro-world/template.html ] && printf '%s' \"$PROMPT\" | grep -q 'no horizontal overflow'; then {}; else {}; fi; {COSTS}", writes(GOOD), writes(BAD) ); @@ -324,6 +328,13 @@ fn a_failing_page_is_rewritten_once_with_what_failed() { 2, "one run and one rewrite" ); + // The world's row carries what the run and its rewrite cost together, and Explore this its estimate (#1060). + assert_eq!( + view.cost.map(|cost| cost.text).as_deref(), + Some("$0.40 API price") + ); + let state = bench.worlds.state(&bench.project(), Some(&bench.head())); + assert!(state.estimate.is_some(), "{state:?}"); } #[test] diff --git a/server/tests/runner.rs b/server/tests/runner.rs index a5377e55..606dd893 100644 --- a/server/tests/runner.rs +++ b/server/tests/runner.rs @@ -127,6 +127,8 @@ impl Bench { folder: self.runner.new_folder().unwrap(), prompt: script.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, } } @@ -714,34 +716,125 @@ fn a_kind_with_no_shell_reads_and_writes_only_where_it_may() { #[test] fn a_run_ends_with_its_result_cost_and_exit_and_appends_a_record() { + // (units, subject, the result's `modelUsage`, the record's units, model and subject). The model is the one that cost the + // most; a run that gives none of them records none (#1060). + let rows = [ + (None, None, None, None, None, None), + ( + Some(4), + Some("draft-1"), + Some(r#"{"claude-haiku-5":{"costUSD":0.02},"claude-sonnet-5-5":{"costUSD":0.4}}"#), + Some(4), + Some("claude-sonnet-5-5"), + Some("draft-1"), + ), + ( + None, + Some("7@abc"), + Some(r#"{"claude-opus-5-5":{"inputTokens":3}}"#), + None, + Some("claude-opus-5-5"), + Some("7@abc"), + ), + ]; + for (units, subject, usage, want_units, want_model, want_subject) in rows { + let bench = bench(); + let usage = usage.map_or(String::new(), |usage| format!(r#","modelUsage":{usage}"#)); + let script = says(&format!( + r#"{{"type":"result","subtype":"success","is_error":false,"result":"The law is backed.","total_cost_usd":0.42,"permission_denials":[]{usage}}}"# + )); + let id = bench + .runner + .submit(Request { + units, + subject: subject.map(str::to_string), + ..bench.request(PROJECT, &script) + }) + .unwrap(); + bench.until(ended(&id)); + let outcome = bench.runner.outcome(&id).unwrap(); + assert_eq!(outcome.end, End::Done); + assert_eq!(outcome.result, "The law is backed."); + assert_eq!(outcome.cost, Some(0.42)); + assert_eq!(outcome.exit, Some(0)); + assert!(outcome.denials.is_empty()); + // A clean success offers no prompt to copy; its row carries its cost, in API price while no plan is set. + let view = bench.runner.runs(PROJECT).runs.remove(0); + assert_eq!((view.outcome, view.prompt), (Some(End::Done), None)); + assert_eq!( + view.cost.map(|cost| cost.text).as_deref(), + Some("$0.42 API price") + ); + + let records = bench.records(); + assert_eq!(records.len(), 1); + let record = &records[0]; + assert_eq!(record["id"], id.as_str()); + assert_eq!(record["kind"], "back-law"); + assert_eq!(record["project"], PROJECT); + assert_eq!(record["outcome"], "done"); + assert_eq!(record["denials"], serde_json::json!([])); + assert_eq!(record["cost"], 0.42); + assert!( + record["duration_ms"].is_u64() && record["at"].is_u64(), + "{record}" + ); + assert_eq!(record["units"].as_u64(), want_units, "{record}"); + assert_eq!(record["model"].as_str(), want_model, "{record}"); + assert_eq!(record["subject"].as_str(), want_subject, "{record}"); + // A field the run has none of is left out, so a line reads as the build before wrote it. + for field in ["units", "model", "subject"] { + assert_eq!( + record.get(field).is_some(), + !record[field].is_null(), + "{record}" + ); + } + } +} + +#[test] +fn the_runs_total_is_the_last_7_days_of_every_project_old_lines_and_dismissed_runs_included() { let bench = bench(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + // Lines a build before #1060 wrote, with no units, model or subject: another project's run of yesterday, a run of 8 days + // ago, and a cancelled run that recorded no cost. + let line = |at: u64, project: &str, outcome: &str, cost: &str| { + format!( + r#"{{"at":{at},"cost":{cost},"denials":[],"duration_ms":5,"id":"r{at}","kind":"first-map","outcome":"{outcome}","project":"{project}"}}"# + ) + }; + let old = [ + line(now - 86_400, "/p/other", "done", "0.3"), + line(now - 8 * 86_400, PROJECT, "done", "5.0"), + line(now - 60, PROJECT, "cancelled", "null"), + ]; + fs::write( + bench.dir.path().join("data/background-runs.jsonl"), + old.join("\n") + "\n", + ) + .unwrap(); + let total = || bench.runner.runs(PROJECT).total.map(|total| total.text); + // With no run listed, the total still says what the week spent. + assert!(bench.runner.runs(PROJECT).runs.is_empty()); + assert_eq!(total().as_deref(), Some("$0.30 API price")); + // A run that ends and is dismissed still counts. let id = bench.run(&says( - r#"{"type":"result","subtype":"success","is_error":false,"result":"The law is backed.","total_cost_usd":0.42,"permission_denials":[]}"#, + r#"{"type":"result","subtype":"success","is_error":false,"result":"Done.","total_cost_usd":0.42}"#, )); bench.until(ended(&id)); - let outcome = bench.runner.outcome(&id).unwrap(); - assert_eq!(outcome.end, End::Done); - assert_eq!(outcome.result, "The law is backed."); - assert_eq!(outcome.cost, Some(0.42)); - assert_eq!(outcome.exit, Some(0)); - assert!(outcome.denials.is_empty()); - // A clean success offers no prompt to copy. - let view = bench.runner.runs(PROJECT).runs.remove(0); - assert_eq!((view.outcome, view.prompt), (Some(End::Done), None)); - - let records = bench.records(); - assert_eq!(records.len(), 1); - let record = &records[0]; - assert_eq!(record["id"], id.as_str()); - assert_eq!(record["kind"], "back-law"); - assert_eq!(record["project"], PROJECT); - assert_eq!(record["outcome"], "done"); - assert_eq!(record["denials"], serde_json::json!([])); - assert_eq!(record["cost"], 0.42); - assert!( - record["duration_ms"].is_u64() && record["at"].is_u64(), - "{record}" + bench.runner.cancel(&id).unwrap(); + assert!(bench.runner.runs(PROJECT).runs.is_empty()); + assert_eq!(total().as_deref(), Some("$0.72 API price")); + // The plan `settings.json` names turns it into its unit: dollars for an API key. + settings( + bench.dir.path(), + r#"{ "checks": { "/p/app": ["cargo test"] }, "plan": { "kind": "api", "confirmed": true } }"#, ); + assert_eq!(total().as_deref(), Some("$0.72")); } #[test] @@ -808,6 +901,8 @@ fn a_run_that_cannot_start_is_refused_with_the_prompt_to_copy() { folder: folder.clone(), prompt: "Back the law".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap_err(); assert!( @@ -832,6 +927,8 @@ fn a_run_that_cannot_start_is_refused_with_the_prompt_to_copy() { folder: runner.new_folder().unwrap(), prompt: "Back the law".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap_err(); assert!(refused.line.contains("codex"), "{}", refused.line); @@ -1212,6 +1309,8 @@ fn a_restart_mid_batch_finds_every_run_of_it_and_leaves_no_slot_held() { folder: runner.new_folder().unwrap(), prompt: script.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }; let batch = runner .submit_batch(vec![ @@ -1267,6 +1366,8 @@ fn request_in(runner: &Runner, script: &str) -> Request { folder: runner.new_folder().unwrap(), prompt: script.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, } } @@ -1349,6 +1450,8 @@ fn a_run_survives_a_restart_and_is_picked_up() { folder: folder.clone(), prompt: waits("picked up"), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap(); let queued = runner @@ -1358,6 +1461,8 @@ fn a_run_survives_a_restart_and_is_picked_up() { folder: runner.new_folder().unwrap(), prompt: "echo queued ran".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap(); until(&runner, &changes, |r| { @@ -1414,6 +1519,8 @@ fn a_run_on_an_ungated_claude_code_starts_and_warns_while_queued_running_ended_a folder, prompt: prompt.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }; let running = runner .submit(request(folder.clone(), &waits("ran"))) @@ -1821,6 +1928,8 @@ fn a_check_or_setup_past_the_runs_limit_leaves_no_process_behind() { folder: runner.new_folder().unwrap(), prompt: "touch ran".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }; request.limits.timeout = Duration::from_secs(1); let id = runner.submit(request).unwrap(); @@ -1974,6 +2083,8 @@ fn submitting_a_runs_folder_twice_is_refused_and_leaves_the_run_alone() { folder: folder.clone(), prompt: "echo twice".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }; assert!(bench.runner.submit(again).is_err()); assert!( @@ -1993,6 +2104,8 @@ fn submitting_a_runs_folder_twice_is_refused_and_leaves_the_run_alone() { folder: outside.clone(), prompt: "echo stray".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }; assert!(bench.runner.submit(stray).is_err()); assert!(outside.exists()); @@ -2023,6 +2136,8 @@ fn a_launcher_that_does_not_start_fails_the_run_once_and_frees_the_queue() { folder: runner.new_folder().unwrap(), prompt: script.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap() }; @@ -2064,6 +2179,8 @@ fn submit(runner: &Runner, project: &str, script: &str) -> String { folder: runner.new_folder().unwrap(), prompt: script.into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap() } @@ -2158,6 +2275,8 @@ fn a_refusal_never_removes_a_folder_that_is_not_a_new_runs() { folder: beside.clone(), prompt: "echo no".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }); assert!(refused.is_err()); assert!(beside.exists() && runs.exists()); @@ -2313,6 +2432,8 @@ fn every_module_that_listens_is_told_a_runs_end_once_also_at_a_pick_up_and_past_ folder: folder.clone(), prompt: "echo done".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap(); let end = told.recv_timeout(Duration::from_secs(30)).unwrap(); @@ -2337,6 +2458,8 @@ fn every_module_that_listens_is_told_a_runs_end_once_also_at_a_pick_up_and_past_ folder: runner.new_folder().unwrap(), prompt: "echo batch".into(), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }]) .unwrap(); let later = submit(&runner, PROJECT, "echo later"); @@ -2356,6 +2479,8 @@ fn every_module_that_listens_is_told_a_runs_end_once_also_at_a_pick_up_and_past_ folder: waiting.clone(), prompt: waits("later"), limits: Limits::of(Kind::BackLaw), + units: None, + subject: None, }) .unwrap(); drop((runner, told, other)); diff --git a/server/tests/wire.rs b/server/tests/wire.rs index 94645002..c484b8cc 100644 --- a/server/tests/wire.rs +++ b/server/tests/wire.rs @@ -17,12 +17,21 @@ use studio_server::{ pr_briefs::BriefInfo, prs::Ready, ratify::Pending, + run_cost::Figure, runner::{End, Kind, RunState, RunView, Runs}, staleness::{Activity, Staleness, Touch}, }; const COMMIT: &str = "0123456789abcdef0123456789abcdef01234567"; +/// A cost figure (#1060): a share with the day its factor was measured, or dollars with none. +fn figure(text: &str, share: bool) -> Figure { + Figure { + text: text.into(), + measured: share.then(|| "2026-12-02".into()), + } +} + fn outline() -> studio_server::part_catch_ups::Outline { studio_server::part_catch_ups::Outline { title: "Store writes go atomic".into(), @@ -240,6 +249,7 @@ fn empty(status: Status) -> MapState { pre_flight: None, micro_worlds: WorldsState::default(), law_patches: Vec::new(), + law_estimate: None, } } @@ -251,6 +261,7 @@ fn worlds() -> WorldsState { stale, line: failed.then(|| "verify.mjs failed:\nFAIL no horizontal overflow @390/light".into()), prompt: failed.then(|| "In the repository at /repo, build a micro-world".into()), + cost: (!failed).then(|| figure("$0.40 API price", false)), }; WorldsState { on: true, @@ -265,6 +276,7 @@ fn worlds() -> WorldsState { view(Phase::Failed, false, false, true), ), ]), + estimate: Some(figure("$0.32–$0.39 API price", false)), } } @@ -284,6 +296,7 @@ fn law_patches() -> Vec { url: None, text: None, guards: None, + cost: None, }; vec![ patch("19a2f-1", PatchState::Proving, None), @@ -300,6 +313,7 @@ fn law_patches() -> Vec { passed: "PASS [ 0.01s] studio-core::it order::events_apply_in_order".into(), failed: "FAIL [ 0.01s] studio-core::it order::events_apply_in_order".into(), }), + cost: Some(figure("$0.30", false)), ..patch("19a2f-3", PatchState::Proven, None) }, patch("19a2f-5", PatchState::OutOfDate, None), @@ -329,6 +343,7 @@ fn runs() -> Runs { warning: None, denials: outcome.map_or_else(Vec::new, |_| vec!["Bash: git push".into()]), prompt: outcome.map(|_| "Write a test that backs the law.".into()), + cost: outcome.map(|_| figure("about 1% of the 5-hour window, under 1% of the week", true)), }; let ends = [ End::Done, @@ -359,6 +374,7 @@ fn runs() -> Runs { Runs { paused: Some("Claude hit its usage or rate limit".into()), runs: list, + total: Some(figure("about 4% of the week", true)), } } @@ -413,6 +429,7 @@ fn the_wire_samples_of_the_map_view_are_written_for_tsc() { }), micro_worlds: worlds(), law_patches: law_patches(), + law_estimate: Some(figure("$0.32–$0.39 API price", false)), ..empty(Status::Loaded) }), )); @@ -1082,6 +1099,14 @@ fn the_wire_samples_of_the_map_replies_are_written_for_tsc() { decided: false, }], changed: true, + cost: Some(figure( + "about 1% of the 5-hour window, under 1% of the week", + true, + )), + estimate: Some(figure( + "up to about 2% of the 5-hour window, under 1% of the week", + true, + )), }), ), ( @@ -1096,6 +1121,8 @@ fn the_wire_samples_of_the_map_replies_are_written_for_tsc() { left_out: 1, still_true: vec![], changed: true, + cost: None, + estimate: None, }), ), ( @@ -1277,6 +1304,7 @@ fn the_wire_samples_of_the_map_replies_are_written_for_tsc() { json(studio_server::map_draft::MapDraftView { ready: true, pr_muted: Some("GitHub's CLI, `gh`, was not found".into()), + cost: Some(figure("$0.70", false)), ..map_draft() }), ), @@ -1320,6 +1348,7 @@ fn the_wire_samples_of_the_map_replies_are_written_for_tsc() { name: "Web".into(), left: 1, }], + estimate: Some(figure("$0.07–$0.10 API price", false)), }), ), ("ScanEdit", fold.clone()), @@ -1504,6 +1533,8 @@ fn map_draft() -> studio_server::map_draft::MapDraftView { why: why.map(Into::into), redraft, undone: redraft && state == GroupState::ReviewerFailed, + estimate: matches!(state, GroupState::WriterFailed | GroupState::ReviewerFailed) + .then(|| figure("$0.03–$0.05 API price", false)), }; MapDraftView { map: r#"{"version":2,"parts":[],"links":[]}"#.into(), @@ -1530,6 +1561,7 @@ fn map_draft() -> studio_server::map_draft::MapDraftView { why: None, redraft: false, undone: false, + estimate: None, }, ], verdicts: BTreeMap::from([( @@ -1560,6 +1592,7 @@ fn map_draft() -> studio_server::map_draft::MapDraftView { ready: false, path: "/w/app/system-map.json".into(), pr_muted: None, + cost: None, } } diff --git a/ui/settings.ts b/ui/settings.ts index 6ba602c4..d93155bd 100644 --- a/ui/settings.ts +++ b/ui/settings.ts @@ -5,7 +5,7 @@ import { messageOf } from "./dom.js"; import { isOpenFilesIn, OPEN_FILES_IN_VALUES } from "./switchboard.js"; -import type { OpenFilesIn, SettingsFiles, WriterKind } from "./types.js"; +import type { OpenFilesIn, Plan, SettingsFiles, WriterKind } from "./types.js"; /** An action, or an action with its argument, as Zed writes `["terminal::SendText", "\u0001"]`. */ export type Binding = string | [string, string]; @@ -31,6 +31,8 @@ export interface Settings { tips: boolean; // The editor Open in editor uses (spec #873): "auto" takes the one that is running. openFilesIn: OpenFilesIn; + // The plan run cost's figures are turned into (spec #1056), and whether Daniel confirmed or picked it; the server reads it too. + plan: Plan; } /** Both settings files, parsed: the settings and keymap in effect. */ @@ -62,6 +64,19 @@ function openFilesIn(value: unknown, report: (line: string) => void): OpenFilesI return undefined; } +const planKinds: readonly Plan["kind"][] = ["pro", "max", "ultra", "api", "unknown"]; +// The plan the file names, or undefined, reporting a value that is not one, as the server reads it as unknown (`settings::plan_in`). +function plan(value: unknown, report: (line: string) => void): Plan | undefined { + if (value === undefined) return undefined; + if (isObject(value)) { + const kind = planKinds.find((k) => k === value.kind); + const confirmed = value.confirmed ?? false; + if (kind && typeof confirmed === "boolean") return { kind, confirmed }; + } + report('plan: expected { "kind": "pro", "max", "ultra", "api" or "unknown", "confirmed": a boolean }'); + return undefined; +} + const defaultSettings: Settings = { // Haiku at its default effort (danielrispler/Falinks#517, decision 14). summaries: { model: "haiku", effort: "", on_open: false, writer: "claude" }, @@ -69,6 +84,7 @@ const defaultSettings: Settings = { explanations: true, tips: true, openFilesIn: "auto", + plan: { kind: "unknown", confirmed: false }, }; /** The page's platform: "mac" takes Cmd shortcuts, shown as macOS glyphs; "linux", any other, takes Ctrl (spec #510, #705). */ @@ -177,6 +193,7 @@ function readSettings(json: unknown, report: Report): Settings { explanations: pick("explanations", json.explanations, d.explanations), tips: pick("tips", json.tips, d.tips), openFilesIn: openFilesIn(json.openFilesIn, report) ?? d.openFilesIn, + plan: plan(json.plan, report) ?? d.plan, }; } diff --git a/ui/tests/settings.test.mjs b/ui/tests/settings.test.mjs index 5c9f7e71..bd2fe843 100644 --- a/ui/tests/settings.test.mjs +++ b/ui/tests/settings.test.mjs @@ -187,6 +187,28 @@ test("openFilesIn is auto by default, the file's value when it is one of the edi } }); +test("plan is unknown and not confirmed by default, the file's kind and confirmed, and a malformed one reads as unknown and is reported (#1060)", () => { + const read = (plan) => reload(initial, { settings: plan === undefined ? null : `{ "plan": ${JSON.stringify(plan)} }`, keymap: null }); + const unknown = { kind: "unknown", confirmed: false }; + for (const [given, want, errors] of [ + [undefined, unknown, 0], + [{ kind: "pro" }, { kind: "pro", confirmed: false }, 0], + [{ kind: "max", confirmed: false }, { kind: "max", confirmed: false }, 0], + [{ kind: "ultra", confirmed: true }, { kind: "ultra", confirmed: true }, 0], + [{ kind: "api", confirmed: true }, { kind: "api", confirmed: true }, 0], + [{ kind: "unknown", confirmed: true }, { kind: "unknown", confirmed: true }, 0], + ["max", unknown, 1], + [{ kind: "gold", confirmed: true }, unknown, 1], + [{ confirmed: true }, unknown, 1], + [{ kind: "max", confirmed: "yes" }, unknown, 1], + ]) { + const loaded = read(given); + assert.deepEqual(loaded.settings.plan, want, JSON.stringify(given)); + assert.equal(loaded.errors.length, errors, JSON.stringify(given)); + if (errors) assert.match(loaded.errors[0], /plan: expected \{ "kind": "pro", "max", "ultra", "api" or "unknown", "confirmed": a boolean \}/, JSON.stringify(given)); + } +}); + const descend = (node, found = []) => { found.push(node); for (const child of node.childNodes ?? []) descend(child, found); diff --git a/ui/types.ts b/ui/types.ts index 31bba6bc..47e45499 100644 --- a/ui/types.ts +++ b/ui/types.ts @@ -518,13 +518,31 @@ export type MapState = { // The patches of the project's back a law runs (`back_a_law.rs`, #398): being proven, rejected with why, or proven with the test patch // and the proof; a past payload has none. law_patches?: LawPatch[]; + // What Back a law, Back this law or Start the run is estimated to cost (#1060); a past payload has none. + law_estimate?: Figure | null; }; +/** + * A run cost figure (`run_cost.rs`, spec #1056): its words, such as "about 1% of the 5-hour window, under 1% of the week" or "$0.41 API + * price", and for a share the day the trial measured the factor it rests on, for its hover; null for dollars. + */ +export type Figure = { text: string; measured: string | null }; +/** `settings.json`'s `plan` (spec #1056, "The plan"): the plan's kind, and whether Daniel confirmed or picked it rather than detection. */ +export type Plan = { kind: "pro" | "max" | "ultra" | "api" | "unknown"; confirmed: boolean }; /** * A micro-world as the map shows it: `building` while its run is queued, running or checked, `ready` with a checked page, `failed` with why * (`line`) and the prompt to copy. `page`: a checked page is stored to open; `stale`: a part on it changed since it was built. */ -export type MicroWorldView = { phase: "building" | "ready" | "failed"; page: boolean; stale: boolean; line: string | null; prompt: string | null }; -export type MicroWorlds = { on: boolean; worlds: Record }; +export type MicroWorldView = { + phase: "building" | "ready" | "failed"; + page: boolean; + stale: boolean; + line: string | null; + prompt: string | null; + // What the runs that built it at its commit cost together (#1060); null when none recorded a cost, absent in a past payload. + cost?: Figure | null; +}; +// `estimate`: what Explore this, Rebuild or Try again is estimated to cost (#1060). +export type MicroWorlds = { on: boolean; worlds: Record; estimate?: Figure | null }; /** What "Explore this" did: started a run, or gave the prompt to copy and why. */ export type Explored = { started: boolean; line: string | null; prompt: string | null }; /** @@ -546,6 +564,8 @@ export type LawPatch = { // A new law's sentence as Daniel confirmed it, and the PR whose Guard with a law started the run (#401). text?: string | null; guards?: number | null; + // What its run cost (#1060); absent when it recorded none. + cost?: Figure | null; }; /** What Open draft PR did: a draft PR opened, or the patch no longer applies to the default branch. */ export type LawPatchOpened = { kind: "pr"; number: number; url: string } | { kind: "out-of-date" }; @@ -600,8 +620,9 @@ export type Expected = { expected: string[]; touched: string[] }; // it was asked for, started or ended, by its state. An ended run says how it ended in `line`, lists the tool calls it was denied, and // carries its `prompt` to copy on every end but a clean one. `paused` is why every queue waits, null while they run. type RunEnd = "done" | "denied" | "failed" | "timed-out" | "died" | "setup-failed" | "not-logged-in" | "rate-limited"; -export type RunView = { id: string; kind: "back-law" | "micro-world" | "map-review" | "first-map"; state: "queued" | "running" | "ended"; at: number; outcome: RunEnd | null; line: string | null; warning?: string | null; denials: string[]; prompt: string | null }; -export type Runs = { paused: string | null; runs: RunView[] }; +export type RunView = { id: string; kind: "back-law" | "micro-world" | "map-review" | "first-map"; state: "queued" | "running" | "ended"; at: number; outcome: RunEnd | null; line: string | null; warning?: string | null; denials: string[]; prompt: string | null; cost?: Figure | null }; +// `total`: what every run of the last 7 days cost, all projects, dismissed runs included; null when that is nothing (#1060). +export type Runs = { paused: string | null; runs: RunView[]; total?: Figure | null }; /** Ratifying (`ratify.rs`): an item of a PR is a map change (kind part, zone, actor, link, law or flow) or a decision the agent declared. */ export type PendingItem = { pr: number; kind: string; id: string }; // `evidence` (#499): on a link the PR adds, the import sites behind it, stored on its brief when it was written, read at `head`. @@ -639,7 +660,7 @@ export type MapReviewFlag = { id: string; verdict: "overreach" | "contradicted" // `items`, `checked` and `flagged` are of changed items only; `still_true` holds the flagged still-true items, never a supported one. A // head whose only items are still-true ones is null but when its review failed or has a flag; its `changed` is false, and the page shows // of it only a failure, with "Run again", and the flags not decided. -export type MapReview = { head: string; state: "idle" | "reviewing" | "done" | "failed"; items: MapReviewItem[]; checked: number; flagged: number; line: string | null; left_out: number; still_true: MapReviewFlag[]; changed: boolean }; +export type MapReview = { head: string; state: "idle" | "reviewing" | "done" | "failed"; items: MapReviewItem[]; checked: number; flagged: number; line: string | null; left_out: number; still_true: MapReviewFlag[]; changed: boolean; cost?: Figure | null; estimate?: Figure | null }; // What a ready PR's brief is doing (`pr_briefs.rs`): a newer head was pushed (stale), being written now, and the chapters' titles, or the one story's. // `note` (#477, part B): why the brief at this head is what it is after a push: the read carried over, or it was rewritten. // `since` (#497): the title of the "Since you read" story stored for this head, which the tray opens first; `since_chapters`, its chapters' titles when it has more than one, one tray row each. @@ -777,6 +798,8 @@ export type MapScan = { loose_tests: string[]; splits: Record; dissolved: { name: string; left: number }[]; + // What Draft the map is estimated to cost for the skeleton's parts, its reviewers and redrafts included (#1060). + estimate?: Figure | null; }; /** @@ -805,7 +828,8 @@ export type ScanEdit = export type MapDraftState = "waiting" | "writing" | "checking" | "done" | "writer-failed" | "reviewer-failed"; export type MapDraft = { map: string; - groups: { parts: string[]; zones: string[]; state: MapDraftState; why: string | null; redraft: boolean; undone: boolean }[]; + // `estimate`: what a failed group's Retry is estimated to cost (#1060). + groups: { parts: string[]; zones: string[]; state: MapDraftState; why: string | null; redraft: boolean; undone: boolean; estimate?: Figure | null }[]; verdicts: Record; rewritten: Record; settled: string[]; @@ -814,6 +838,8 @@ export type MapDraft = { ready: boolean; path: string; pr_muted: string | null; + // What the draft's runs cost together, writers, reviewers, redrafts and retries (#1060); null while none recorded a cost. + cost?: Figure | null; }; /** * What Accept's Write did (`Accepted` in `server/src/map_draft.rs`, #764): wrote the map to `path`, uncommitted, or wrote nothing since a file From 04dd2c68cc973b5e6faa70a465fd9963c2c5ca81 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 13:31:35 +0200 Subject: [PATCH 4/9] Studio: every run button shows its cost estimate, and every run its actual cost (#1063) Draft the map, Back a law, Back this law, Start the run, Explore this, Rebuild, Try again, Review map text, Run again and Retry show the view's estimate; the Map draft's status line, Ratify's review line, the patch review, a micro-world's row and each ended run show what it took, and the runs list's head the 7-day total, drawn even with no run listed. Hovers say where each figure comes from. Co-Authored-By: Claude Opus 5.5 --- scripts/snap/fixtures-brief.ts | 6 ++++- scripts/snap/fixtures-map.ts | 19 ++++++++++++++ scripts/snap/fixtures-runs.ts | 37 ++++++++++++++++++++++++++ scripts/snap/fixtures.ts | 10 ++++++-- ui/map-draft.ts | 6 +++++ ui/map-ratify.ts | 6 +++++ ui/map-runs.ts | 15 +++++++---- ui/map-scan.ts | 12 ++++++--- ui/map-sheet.ts | 2 +- ui/micro-world.ts | 21 ++++++++++----- ui/patch-review.ts | 47 ++++++++++++++++++++++------------ ui/run-cost.ts | 23 +++++++++++++++++ ui/style.css | 6 +++-- ui/tests/map-ratify.test.mjs | 13 ++++++++++ ui/tests/map-runs.test.mjs | 32 +++++++++++++++++++++++ ui/tests/map.test.mjs | 10 ++++++++ ui/tests/micro-world.test.mjs | 18 +++++++++++++ ui/tests/patch-review.test.mjs | 20 +++++++++++++++ 18 files changed, 265 insertions(+), 38 deletions(-) create mode 100644 ui/run-cost.ts diff --git a/scripts/snap/fixtures-brief.ts b/scripts/snap/fixtures-brief.ts index d639bce0..580c17d3 100644 --- a/scripts/snap/fixtures-brief.ts +++ b/scripts/snap/fixtures-brief.ts @@ -718,7 +718,8 @@ const guardedBrief = (): BriefView => { const view = briefOf(storySteps()); return { ...view, brief: { ...view.brief, guard: { parts: ["core", "shell"] } } }; }; -export const mapBriefGuard = (confirm: boolean): Fixture => ({ +const guardEstimate = { text: "about 1–3% of the 5-hour window", measured: "2026-12-01" }; +export const mapBriefGuard = (confirm: boolean, estimate = false): Fixture => ({ ...mapBrief(guardedBrief(), 4, ` const row = document.querySelector("#map-brief .guard-row"); if (!row) return log("snap:fail the brief has no Guard with a law row"); @@ -727,6 +728,8 @@ export const mapBriefGuard = (confirm: boolean): Fixture => ({ if (laws !== "core-order,shell-notice,shell-ordered") log("snap:fail the guard's laws: " + laws); if (row.querySelectorAll(".guard-law button").length !== 2) log("snap:fail Back this law belongs on the two laws on trust"); if (!row.textContent.includes("Proving the patch")) log("snap:fail the new law's run does not say where it stands"); + const costs = [...row.querySelectorAll(".run-cost")].map((node) => node.textContent); + if (JSON.stringify(costs) !== JSON.stringify(${estimate} ? ["Costs about 1–3% of the 5-hour window", "Costs about 1–3% of the 5-hour window"] : [])) log("snap:fail the estimates beside Back this law: " + JSON.stringify(costs)); const add = [...row.querySelectorAll("button")].find((b) => b.textContent === "Add a new law"); if (!add) return log("snap:fail no Add a new law"); if (${confirm}) { @@ -743,6 +746,7 @@ export const mapBriefGuard = (confirm: boolean): Fixture => ({ fog: { shell: "thick", understanding: "thin" }, ready: [{ number: 334, title: "PR briefs on the map", head: "b".repeat(40), brief: { stale: false, writing: false, chapters: ["PR briefs on the map"], quiet: false } }], law_patches: [{ id: "19a2f-11", project: "/w/plotkeeper", law: "shell-ordered", state: "proving", line: null, at: runAt, diff: null, proof: null, text: "The shell reads the log in order.", guards: 334 }], + ...(estimate ? { law_estimate: guardEstimate } : {}), }), snapDone: "guard ok", }); diff --git a/scripts/snap/fixtures-map.ts b/scripts/snap/fixtures-map.ts index 5fce9a0f..a8c2ce41 100644 --- a/scripts/snap/fixtures-map.ts +++ b/scripts/snap/fixtures-map.ts @@ -1315,6 +1315,15 @@ export const mapScan = (): Fixture => frame("with the Adjust drawer open"); checkColours("with the Adjust drawer open"); log("base ok");`, { map_state: mapState({ status: "none", source: null, from: null }), map_scan: mapScanOf() }); +/** Draft the map's card shows what the run is estimated to cost under its time hint (spec #1056); without claude it shows none. */ +export const mapScanCost = (): Fixture => + mapBaseOf(` + const screen = document.querySelector("#map .map-scan"); + const lines = [...(screen?.querySelectorAll(".map-scan-draft .map-scan-time") ?? [])].map((node) => node.textContent); + if (JSON.stringify(lines) !== JSON.stringify(["Recommended · about 1 minute", "Costs about 2–4% of the 5-hour window, under 1% of the week"])) return log("snap:fail the card's lines: " + JSON.stringify(lines)); + frame("with Draft the map's estimate"); + checkColours("with Draft the map's estimate"); + log("base ok");`, { map_state: mapState({ status: "none", source: null, from: null }), map_scan: mapScanOf({ estimate: { text: "about 2–4% of the 5-hour window, under 1% of the week", measured: "2026-12-01" } }) }); // The base scan with App merged into Lib: Lib holds both folders, and Cli's line to Lib is the one left. const mergedScan = (() => { const map = JSON.parse(mapScanOf().map); @@ -2144,6 +2153,16 @@ export const mapDraftAccept = (): Fixture => frame("with Accept's ways out"); checkColours("with Accept's ways out"); log("base ok");`, { map_state: mapState({ status: "none", source: null, from: null }), map_draft: reviewDraft }); +/** The Map draft's status line says what the draft's runs took once it is ready (spec #1056), and says nothing while it is not. */ +export const mapDraftCost = (): Fixture => + mapBaseOf(` + const status = document.querySelector('#map .map-drafting [data-key="draft status"]'); + const took = status?.querySelector(".run-cost"); + if (took?.textContent !== "Took about 3% of the 5-hour window") log("snap:fail the status line's cost: " + status?.textContent); + if (took && !document.getElementById(took.getAttribute("data-hint") ?? "")?.textContent.includes("measured on 2026-12-01")) log("snap:fail the hover does not say where the figure comes from"); + frame("with what the draft took"); + checkColours("with what the draft took"); + log("base ok");`, { map_state: mapState({ status: "none", source: null, from: null }), map_draft: { ...reviewDraft, cost: { text: "about 3% of the 5-hour window", measured: "2026-12-01" } } }); // Why Open a draft PR is muted when `gh` is not logged in, as the server says it. const ghLoggedOut = "`gh` is not logged in: run `gh auth login` to open a draft PR, or write the file instead"; /** Open a draft PR muted with its reason when `gh` is not logged in (#753, story 27): a press sends nothing, and Write stays the way out. */ diff --git a/scripts/snap/fixtures-runs.ts b/scripts/snap/fixtures-runs.ts index 6d5bccc9..6aa53cc9 100644 --- a/scripts/snap/fixtures-runs.ts +++ b/scripts/snap/fixtures-runs.ts @@ -544,3 +544,40 @@ export const mapPreFlightPick = (): Fixture => ({ snapDone: "dark page ok", contrast: true, }); + +const share = (words: string) => ({ text: words, measured: "2026-12-01" }); +/** + * The runs list's costs (spec #1056): the 7-day total in its head, and each ended row's actual cost, a run that recorded none showing nothing. + */ +export const mapRunsCost = (): Fixture => + mapOpened(` + const rows = [...document.querySelectorAll("#map-runs .run-row")]; + const total = document.querySelector("#map-runs .runs-total"); + if (total?.textContent !== "Last 7 days, all projects: about 4% of the week") log("snap:fail the total says " + total?.textContent); + if (document.querySelector("#map-runs .side-title")?.nextElementSibling !== total) log("snap:fail the total is not under the title"); + const spent = rows.map((row) => row.querySelector(".run-cost")?.textContent ?? ""); + if (JSON.stringify(spent) !== JSON.stringify(["", "Took about 2% of the 5-hour window, under 1% of the week", ""])) log("snap:fail the rows' costs: " + JSON.stringify(spent)); + log("runs cost ok");`, { + map_state: mapState({ + runs: { + paused: null, + total: share("about 4% of the week"), + runs: [ + { id: "19a2f-1", kind: "back-law", state: "running", at: runAt, outcome: null, line: null, denials: [], prompt: null }, + { id: "19a2f-0", kind: "back-law", state: "ended", at: runAt, outcome: "done", line: "Proven: a test for core-order", denials: [], prompt: null, cost: share("about 2% of the 5-hour window, under 1% of the week") }, + { id: "19a2f-4", kind: "micro-world", state: "ended", at: runAt, outcome: "died", line: "The run died", denials: [], prompt: "Build a micro-world.", cost: null }, + ], + }, + }), + snapDone: "runs cost ok", + }); +/** With no run listed and the total not zero, the list still draws its head with the total (spec #1056, story 10). */ +export const mapRunsTotal = (): Fixture => + mapOpened(` + if (document.querySelectorAll("#map-runs .run-row").length) return log("snap:fail a run is listed"); + const total = document.querySelector("#map-runs .runs-total"); + if (total?.textContent !== "Last 7 days, all projects: under 1% of the week") log("snap:fail the total says " + total?.textContent); + log("runs total ok");`, { + map_state: mapState({ runs: { paused: null, runs: [], total: share("under 1% of the week") } }), + snapDone: "runs total ok", + }); diff --git a/scripts/snap/fixtures.ts b/scripts/snap/fixtures.ts index 467a8581..d545c017 100644 --- a/scripts/snap/fixtures.ts +++ b/scripts/snap/fixtures.ts @@ -7,11 +7,11 @@ import type { Fixture } from "./base.ts"; import { railFixtures } from "./rail-fixtures.ts"; import { list, withSaved } from "./fixtures-shared.ts"; import { alerts, listEmpty, listUnread, listUnreadHealed, cutText, cutTextStill, hints, installHint, listClearLanded, listHeld, listHints, listNarrow, listSecondLines, logDone, logFixture, logos, noticeErrors, notRecording, paletteFocus, paletteOpen, portLine, projectChevron, projectMenuScript, projectsSaved, railJumpHerdr, recording, skipLink, snapFrames, snapRealKeys, storeMoved, streamAboutFailed, streamRefused, streamRestarted, streamRetrying, toastKeys, whatsNewToast, listEsc, listEscNarrow, longNameDialogs, longNameDialogsPhone, permissionCommand, renameCap, topBarNarrow, topBarPhone, topBarSmall } from "./fixtures-page.ts"; -import { mapBadgeList, mapNowSubagents, mapBase, mapCheckout, mapDefaultNoBanner, mapNotGit, mapBriefPairLight, mapBriefSwitch, mapBroken, mapBusy, mapCalm, mapCamera, mapDotsOrder, mapDotsRetry, mapEmpty, mapFog, mapFogPlates, mapFresh, mapGlassMotion, mapGoneFocus, mapHeaderDot, mapMarkHints, mapScan, mapScanIgnore, mapScanMerge, mapScanGive, mapScanNoClaude, mapScanSwitch, mapScanZone, mapScanDissolved, mapScanDissolvedNone, mapDraftSteps, mapDrafting, mapDraftReview, mapDraftRound, mapDraftZoneSteps, mapDraftZoneFailed, mapDraftAccept, mapDraftPr, mapDraftPrMuted, mapDraftLoose, mapDraftReplace, mapDraftWrite, mapKeepCurrent, mapPendingClosed, mapPendingOpen, mapPendingSteps, mapPartKeys, mapPartRedraw, mapSheetFocus, mapProjectGone, mapProjectRemoved, mapRefresher, mapPurposeWhole, mapSheetLongName, mapCaughtUp, mapCatchUpOlder, mapReview, mapScrubbed, mapSmallGaps, mapSpotlight, mapStale, mapSwitchSavesViews, mapTalksTo, mapZones, mapZoneMarks, mapZoneOpen, mapPlanLight, mapZoneSheet, mapZoneSheetNarrow, mapDiffZones, mapUnread, mapHistoryUnread, mapBadgeSwitch } from "./fixtures-map.ts"; +import { mapBadgeList, mapNowSubagents, mapBase, mapCheckout, mapDefaultNoBanner, mapNotGit, mapBriefPairLight, mapBriefSwitch, mapBroken, mapBusy, mapCalm, mapCamera, mapDotsOrder, mapDotsRetry, mapEmpty, mapFog, mapFogPlates, mapFresh, mapGlassMotion, mapGoneFocus, mapHeaderDot, mapMarkHints, mapScan, mapScanIgnore, mapScanMerge, mapScanGive, mapScanCost, mapScanNoClaude, mapScanSwitch, mapScanZone, mapScanDissolved, mapScanDissolvedNone, mapDraftSteps, mapDrafting, mapDraftReview, mapDraftRound, mapDraftZoneSteps, mapDraftZoneFailed, mapDraftAccept, mapDraftCost, mapDraftPr, mapDraftPrMuted, mapDraftLoose, mapDraftReplace, mapDraftWrite, mapKeepCurrent, mapPendingClosed, mapPendingOpen, mapPendingSteps, mapPartKeys, mapPartRedraw, mapSheetFocus, mapProjectGone, mapProjectRemoved, mapRefresher, mapPurposeWhole, mapSheetLongName, mapCaughtUp, mapCatchUpOlder, mapReview, mapScrubbed, mapSmallGaps, mapSpotlight, mapStale, mapSwitchSavesViews, mapTalksTo, mapZones, mapZoneMarks, mapZoneOpen, mapPlanLight, mapZoneSheet, mapZoneSheetNarrow, mapDiffZones, mapUnread, mapHistoryUnread, mapBadgeSwitch } from "./fixtures-map.ts"; import { readmeFixtures } from "./fixtures-readme.ts"; import { readmeBriefFixtures } from "./fixtures-readme-brief.ts"; import { mapFootprint, mapLatePlace, mapPanelBrief, mapPanelDiff, mapNotPlacedHint, mapPanelFieldHints, mapPanelFocus, mapPanelHead, mapPanelHistory, mapPanelLine2, mapPanelNoSession, mapPanelPeel, mapPanelMenuEsc, mapPanelChangeEsc, mapPanelLightDismiss, mapListFold, mapPanelSettings, mapPanelStory, mapPanelToggle, mapSheetClose, mapSheetExplained, mapSheetHere, mapSheetHolds, mapSheetKeptWidth, mapSheetResizeRedraw, mapSheetScrollShort, mapSheetStill, mapSheetUnratified, mapSheetWidth, mapToastBeside, mapTurnLight, mapPanelPatched, mapPanelAskStays, mapPanelBriefFoot, mapPrPanel, mapPrPanelPlaying, mapPrPanelRatify, mapPrPanelRewriting, mapPrPanelWriting, panelCaughtUp, panelExpanded, panelNeedsYou, panelFirstOpen, panelNoTrees, panelReplay, panelRunning, panelWhy, panelYourTurn } from "./fixtures-panel.ts"; -import { mapBackLaw, mapMicroWorld, mapMicroWorldBuilding, mapPreFlight, mapPreFlightOutside, mapPreFlightOutsideKept, mapPreFlightPalette, mapPreFlightPick, mapPreFlightStatus, mapRuns, mapRunsAnnounced, mapRunsBesideSheet, mapRunsPaused, mapTray, mapTrayAfterPush, mapPreFlightIssuesFailed } from "./fixtures-runs.ts"; +import { mapBackLaw, mapMicroWorld, mapMicroWorldBuilding, mapPreFlight, mapPreFlightOutside, mapPreFlightOutsideKept, mapPreFlightPalette, mapPreFlightPick, mapPreFlightStatus, mapRuns, mapRunsAnnounced, mapRunsBesideSheet, mapRunsCost, mapRunsPaused, mapRunsTotal, mapTray, mapTrayAfterPush, mapPreFlightIssuesFailed } from "./fixtures-runs.ts"; import { mapBriefAlsoGroups, mapBriefAnnounce, mapBriefBar, mapBriefBold, mapBriefBoldUnpaired, mapBriefChapterLast, mapBriefChapterMid, mapBriefChapters, mapBriefCopied, mapBriefCopyByHand, mapBriefExplainBack, mapBriefExplained, mapBriefFigure, mapBriefGuard, mapBriefHeights, mapBriefMapCheck, mapBriefNoFacts, mapBriefReview, mapBriefStillTrue, mapBriefNoStaleBase, mapBriefOrderRight, mapBriefOrderSlots, mapBriefOrderWrong, mapBriefOverturn, mapBriefPartialFacts, mapBriefPick, mapBriefRatify, mapBriefRatifyDetail, mapBriefRatifyEvidence, mapBriefShort, mapBriefSince, mapBriefStaleBase, mapBriefStart, mapBriefStepCode, mapBriefStory, mapBriefTall, mapBriefTaller, mapBriefTallScroll, mapBriefUnconfirmed, mapBriefWhy, mapBriefWhyDecision, mapBriefWriting, mapCatchUp, mapCatchUpBold, mapCatchUpCard, mapCatchUpStage, mapCatchUpSummarising, mapCatchUpWriting, mapDiffClosed, mapDiffLitGhost, mapDiffRatifyLit, mapDiffRemoval, mapDiffRemovalBrief, mapDiffSplit, mapDiffSplitBrief, listBriefMark, railBriefReady } from "./fixtures-brief.ts"; import { writersBriefsNeedClaude, writersFailed, writersKeyError, writersTestUnrun, writersUnread, writersKeyNotSet, writersKeySet, writersList, writersOpenAI, writersPassed, writersSecretService } from "./fixtures-writers.ts"; @@ -99,6 +99,9 @@ export const fixtures = { mapMicroWorld, mapMicroWorldBuilding, mapRunsPaused, + // Run cost (spec #1056): the list with figures and its head with only the total, Draft the map's estimate, the Map draft's spent line and a brief's Back this law estimate. + mapRunsCost, + mapRunsTotal, mapRunsAnnounced, mapRunsBesideSheet, mapBackLaw, @@ -152,6 +155,7 @@ export const fixtures = { mapBriefStillTrueAlone: () => mapBriefStillTrue("alone"), mapBriefGuard: () => mapBriefGuard(false), mapBriefGuardConfirm: () => mapBriefGuard(true), + mapBriefGuardCost: () => mapBriefGuard(false, true), mapBriefBar, mapBriefExplainBack: () => mapBriefExplainBack(false), mapBriefExplainBackDone: () => mapBriefExplainBack(true), @@ -329,6 +333,7 @@ export const fixtures = { mapScanGive, mapScanGiveNarrow: mapScanGive, mapScanNoClaude, + mapScanCost, mapScanSwitch, // Zones on the scan screen (spec #855): the open frame with Split's hints and Back to one part, and the line when an edit removes a zone, // with one part left or none. @@ -346,6 +351,7 @@ export const fixtures = { mapDraftZoneSteps, mapDraftZoneFailed, mapDraftAccept, + mapDraftCost, mapDraftAcceptNarrow: mapDraftAccept, mapDraftReplace, mapDraftWrite, diff --git a/ui/map-draft.ts b/ui/map-draft.ts index 5d9b672c..18aea970 100644 --- a/ui/map-draft.ts +++ b/ui/map-draft.ts @@ -17,6 +17,7 @@ import { availability, confirmed, hint, isUnavailable, patch, pressable, text } from "./dom.js"; import { draftProgress, draftStep, type DraftStage, type LooseArea, looseAreas, type MapDoc, own, parseMap, partStage, type Tier, type Zone, zoneOf } from "./map-model.js"; import { plateCanvas } from "./map-scan.js"; +import { estimateLine, spentLine } from "./run-cost.js"; import { counts, duration } from "./times.js"; import type { MapDraft, MapState } from "./types.js"; @@ -292,6 +293,8 @@ function failedOf(draft: MapDraft, doc: Doc, acts: DraftActs): HTMLElement[] { const again = group.state === "writer-failed" ? "Run the zones' writer again; the parts stay as they are" : "Check the zones again; their text stays as it is"; hint(retry, zones ? again : "Run this group again; the other parts stay as they are"); row.append(line, retry); + const costs = estimateLine(group.estimate); + if (costs) row.append(costs); return [row]; }); } @@ -341,6 +344,9 @@ function headOf(draft: MapDraft, doc: Doc, key: string, now: number): HTMLElemen if (left) status.append(text("span", left, "map-drafting-eta")); const step = stepOf(draft, doc, key, now); if (step) status.append(step); + // What its runs took together, once the draft is ready (#1056). + const took = draft.ready ? spentLine(draft.cost, "map-drafting-cost", "span") : null; + if (took) status.append(took); const title = text("h2", folder.slice(folder.lastIndexOf("/") + 1) || folder, "pr-title"); title.setAttribute("translate", "no"); head.append(text("p", "Map draft", "pr-eyebrow"), title, status); diff --git a/ui/map-ratify.ts b/ui/map-ratify.ts index e5c00b68..3a5b22a1 100644 --- a/ui/map-ratify.ts +++ b/ui/map-ratify.ts @@ -7,6 +7,7 @@ import { failure, hint, invoke, pressable, promptBox, sayAction, text } from "./ import { currentMap } from "./map.js"; import { openDrawer } from "./map-drawer.js"; import { copyOverturn, decideWith, detailLines, evidenceLine, mapCheckLine, noteFor, overturnPrompt, overturnReport, reviewLine, siteDrawer, sitesDrawer, type Overturned } from "./ratify.js"; +import { costLine, spentLine } from "./run-cost.js"; import { logStop } from "./stop-rules.js"; import type { ImportSite, LinkSites, MapReview, RatifyRow } from "./types.js"; @@ -213,6 +214,9 @@ export function mapReviewNode(review: MapReview | null, start: () => Promise Promise { const waits = runs?.paused ? "Queued, paused" : run.id === next ? "Queued, next" : "Queued"; const note = run.state === "ended" ? (run.line ?? "Ended") : run.state === "running" ? `Running since ${clock(run.at)}` : waits; - return { id: run.id, state: run.state, title: kindWords[run.kind] ?? run.kind, note, warning: run.warning ?? null, action: run.state === "ended" ? "Dismiss" : "Cancel", denials: run.denials ?? [], prompt: run.prompt ?? null }; + return { id: run.id, state: run.state, title: kindWords[run.kind] ?? run.kind, note, warning: run.warning ?? null, action: run.state === "ended" ? "Dismiss" : "Cancel", denials: run.denials ?? [], prompt: run.prompt ?? null, cost: run.state === "ended" ? (run.cost ?? null) : null }; }); } @@ -66,6 +67,8 @@ function rowNode(row: RunRow, act: RunActs, note: CopyNote | null): HTMLElement node.dataset.state = row.state; const actions = text("span", "", "run-actions"); node.append(text("span", row.title, "run-title"), text("span", row.note, "run-note")); + const spent = spentLine(row.cost); + if (spent) node.append(spent); // A warning is part of the row in every state, drawn anew with it, so it is plain text and never live (#774). if (row.warning !== null) node.append(text("p", row.warning, "run-warning")); if (row.denials.length) { @@ -117,8 +120,10 @@ const pauseWords = (runs: Runs | null | undefined) => (runs?.paused == null ? "" export function runsNodes(runs: Runs | null | undefined, act: RunActs, note: CopyNote | null = null): HTMLElement[] { const rows = runRows(runs); const paused = runs?.paused ?? null; - if (!rows.length && paused === null) return []; - const nodes = [text("h3", "Background runs", "side-title")]; + const total = costLine(runs?.total, "Last 7 days, all projects:", "runs-total"); + if (!rows.length && paused === null && !total) return []; + const nodes: HTMLElement[] = [text("h3", "Background runs", "side-title")]; + if (total) nodes.push(total); if (paused !== null) { const indicator = text("p", "", "runs-paused"); indicator.append(text("span", pauseWords(runs)), button("Resume", "Start the queued runs again", act.resume)); diff --git a/ui/map-scan.ts b/ui/map-scan.ts index e55d4689..371a7806 100644 --- a/ui/map-scan.ts +++ b/ui/map-scan.ts @@ -12,7 +12,8 @@ import { availability, closeButton, hint, isUnavailable, patch, pressable, svg, import { fitCamera } from "./map-camera.js"; import { counted, draftTime, frameSize, ignoredFolders, languagesLine, looseAreas, type LooseArea, type MapDoc, openAt, own, parseMap, placement, type Point, type Size, plateSize, rimPoint, rolledLines, scanPrompt, zoneGrid, zoneOf } from "./map-model.js"; import { copyButton } from "./copy-button.js"; -import type { MapScan, MapState, ScanEdit } from "./types.js"; +import { estimateLine } from "./run-cost.js"; +import type { Figure, MapScan, MapState, ScanEdit } from "./types.js"; type Doc = Extract; type Part = Doc["parts"][number]; @@ -254,7 +255,7 @@ function drawCanvas(doc: Doc, scan: MapScan, acts: ScanActs): HTMLElement { // Draft the map, its time hint, and why it is muted when `claude` was not found; it starts the drafting run (#762) with the skeleton // (#763), and says why when the server refused it. -function draftBlock(parts: number, claude: boolean, acts: ScanActs): HTMLElement { +export function draftBlock(parts: number, claude: boolean, acts: ScanActs, estimate?: Figure | null): HTMLElement { const block = text("div", "", "map-scan-draft"); block.dataset.key = "scan draft"; const button = pressable(text("button", "Draft the map", "btn primary"), null, () => { @@ -265,6 +266,9 @@ function draftBlock(parts: number, claude: boolean, acts: ScanActs): HTMLElement availability(button, "Name and describe these parts with Claude Code, in the background, on your Claude Code plan; nothing is written until you accept", why); block.append(button); if (claude) block.append(text("p", `Recommended · ${draftTime(parts).toLowerCase()}`, "map-scan-time")); + // What the run is estimated to cost, redrafts and reviewers included (#1056), under the time hint. + const costs = estimateLine(estimate, "map-scan-time"); + if (claude && costs) block.append(costs); if (why) block.append(text("p", why, "map-scan-why")); if (acts.refused) { const refused = text("p", `Draft the map did not start: ${acts.refused}`, "map-scan-why"); @@ -497,10 +501,10 @@ function panelOf(state: MapState, doc: Doc, scan: MapScan, acts: ScanActs): HTML links.dataset.key = "scan links"; if (scan.claude) { links.append(adjust, own); - panel.append(draftBlock(count, true, acts), links); + panel.append(draftBlock(count, true, acts, scan.estimate), links); } else { links.append(adjust); - panel.append(own, draftBlock(count, false, acts), links); + panel.append(own, draftBlock(count, false, acts, scan.estimate), links); } panel.append(drawer(id("adjust"), "Adjust parts", adjustBody(state, doc, scan, acts)), drawer(id("own"), "Use your own agent", [promptBlock(scan.map, true)])); return panel; diff --git a/ui/map-sheet.ts b/ui/map-sheet.ts index 64798465..f3188fb6 100644 --- a/ui/map-sheet.ts +++ b/ui/map-sheet.ts @@ -374,7 +374,7 @@ function lawsBody(view: MapView, part: string, sheet: Sheet, unratified: Unratif acts.append(proof); } // A law on trust offers Back a law, or shows where its run's patch stands (#398). Of now only. - if (law.backing === "trust" && !view.scrub) acts.append(...lawActionNodes(lawAction(law.id, view.state.law_patches), patchActs)); + if (law.backing === "trust" && !view.scrub) acts.append(...lawActionNodes(lawAction(law.id, view.state.law_patches), patchActs, "Back a law", view.state.law_estimate)); const pr = unratified.laws.get(law.id); if (pr !== undefined) { row.classList.add("unratified"); diff --git a/ui/micro-world.ts b/ui/micro-world.ts index fe7a5773..326de105 100644 --- a/ui/micro-world.ts +++ b/ui/micro-world.ts @@ -11,7 +11,8 @@ import { onDraw, registerLayer, reloadMap, shownProject } from "./map.js"; import { copyOverturn, overturnReport } from "./ratify.js"; import { logStop } from "./stop-rules.js"; import { holdsFocus, overlayFocus } from "./overlay-focus.js"; -import type { MicroWorldView, MicroWorlds } from "./types.js"; +import { costLine, spentLine } from "./run-cost.js"; +import type { Figure, MicroWorldView, MicroWorlds } from "./types.js"; /** What a world's row offers: its words, and what a click does; `act` null is a word with no click, such as "Building…". */ export type Offer = { label: string; title: string; act: "explore" | "open" | "copy" | null }; @@ -61,7 +62,13 @@ export function exploreNode(worlds: MicroWorlds | null | undefined, key: string, if (offer.act === "copy") return () => act.copy(world?.prompt ?? ""); return offer.act ? act[offer.act] : null; }; - node.append(...exploreOffers(worlds, key).map((offer) => button(offer.label, offer.title, click(offer)))); + const offers = exploreOffers(worlds, key); + node.append(...offers.map((offer) => button(offer.label, offer.title, click(offer)))); + // Every offer that starts a run shares one estimate; the copy of a prompt starts none (#1056). + const costs = worlds?.on && offers.some((offer) => offer.act === "explore") ? costLine(worlds.estimate, "Costs", "micro-world-cost", "span") : null; + if (costs) node.append(costs); + const took = spentLine(world?.cost, "micro-world-cost", "span"); + if (took) node.append(took); if (world?.page && world.stale) node.append(text("span", staleWords, "micro-world-stale")); if (world?.phase === "failed" && world.line) node.append(text("p", world.line, "micro-world-why")); return node; @@ -82,10 +89,12 @@ export function frameNode(html: string): HTMLElement { } /** The overlay's nodes: the head with the world's name, "may be out of date" with Rebuild, and its ×; then the frame. */ -export function worldNodes(name: string, html: string, world: MicroWorldView | undefined, act: WorldActs): [HTMLElement, HTMLElement] { +export function worldNodes(name: string, html: string, world: MicroWorldView | undefined, act: WorldActs, estimate?: Figure | null): [HTMLElement, HTMLElement] { const head = text("div", "", "micro-world-head"); head.append(text("h2", name, "micro-world-title")); if (world?.stale) head.append(text("span", staleWords, "micro-world-stale"), button("Rebuild", "Build it again from the code as it is now", act.rebuild)); + const costs = world?.stale ? costLine(estimate, "Costs", "micro-world-cost", "span") : null; + if (costs) head.append(costs); // A corner closer is ×, as the sheet's and the panel's (#571, spec #1035). head.append(closeButton("Close the micro-world", act.close)); return [head, frameNode(html)]; @@ -97,8 +106,8 @@ let shown: Shown | null = null; const overlay = () => element("map-micro-world"); /** Draws the world into `box`, the overlay; a box that already shows the same page keeps its frame and gets a new head alone. */ -export function paintWorld(box: HTMLElement, name: string, html: string, world: MicroWorldView | undefined, act: WorldActs) { - const [head, frame] = worldNodes(name, html, world, act); +export function paintWorld(box: HTMLElement, name: string, html: string, world: MicroWorldView | undefined, act: WorldActs, estimate?: Figure | null) { + const [head, frame] = worldNodes(name, html, world, act, estimate); const [shownHead, shownFrame] = box.children; if (shownHead && shownFrame?.getAttribute("srcdoc") === html) box.replaceChild(head, shownHead); else box.replaceChildren(head, frame); @@ -119,7 +128,7 @@ function paint(worlds?: MicroWorlds) { now.explore(); }, close, - }); + }, worlds?.estimate); box.hidden = false; overlayFocus("micro-world", box, `${now.project} ${now.key}`); } diff --git a/ui/patch-review.ts b/ui/patch-review.ts index 6d8fe6ed..d12aa945 100644 --- a/ui/patch-review.ts +++ b/ui/patch-review.ts @@ -19,7 +19,8 @@ import { logStop } from "./stop-rules.js"; import { holdsFocus, overlayFocus } from "./overlay-focus.js"; import type { MapView } from "./map.js"; import type { Law } from "./map-model.js"; -import type { BackLawStarted, Guard, LawPatch, LawPatchOpened, NewLaw } from "./types.js"; +import { costLine, estimateLine, spentLine } from "./run-cost.js"; +import type { BackLawStarted, Figure, Guard, LawPatch, LawPatchOpened, NewLaw } from "./types.js"; /** * What a law's row offers: a new run, a patch being proven, a rejected one (its first line), a proven one to review, one whose draft PR @@ -78,8 +79,12 @@ const button = (words: string, title: string, click: () => void, kind = "quiet") * The nodes of a law's action, for its row in the part's sheet. `again` is the words of the button that starts a run; none for a new law, * which the map does not have to back. */ -export function lawActionNodes(action: LawAction, act: Pick, again: string | null = "Back a law"): HTMLElement[] { - const start = () => (again === null ? [] : [button(again, "Start a background run that writes a test for this law, then prove it here", () => act.start(action.law))]); +export function lawActionNodes(action: LawAction, act: Pick, again: string | null = "Back a law", estimate?: Figure | null): HTMLElement[] { + const start = () => { + if (again === null) return []; + const costs = costLine(estimate, "Costs", "law-patch-note", "span"); + return [button(again, "Start a background run that writes a test for this law, then prove it here", () => act.start(action.law)), ...(costs ? [costs] : [])]; + }; switch (action.kind) { case "start": return start(); @@ -121,6 +126,7 @@ export function reviewNodes(patch: LawPatch, law: string, act: Pick node !== null), ...(proof ? [text("p", `The new test: ${proof.test} in ${proof.file}`, "patch-test")] : []), text("h3", "The test patch", "patch-heading"), diff, @@ -258,14 +264,14 @@ export type GuardActs = Pick & { ba * The guard's row: each on-trust law with Back this law (or where its patch stands), each new law with where its patch stands, and Add a * new law. `patches` are the project's, for the state of each law's newest one. */ -export function guardNodes(offer: GuardOffer, patches: LawPatch[] | null | undefined, act: GuardActs, adding: HTMLElement[] | null = null): HTMLElement { +export function guardNodes(offer: GuardOffer, patches: LawPatch[] | null | undefined, act: GuardActs, adding: HTMLElement[] | null = null, estimate?: Figure | null): HTMLElement { const row = text("div", "", "guard-row"); row.append(text("p", "Guard with a law", "guard-title"), text("p", "Back a law on trust of a part it touched, or add a new one.", "brief-quiet")); const list = text("ul", "", "guard-laws"); for (const law of offer.back) { const item = text("li", "", "guard-law"); item.dataset.law = law.id; - item.append(text("span", law.text, "guard-text"), ...lawActionNodes(lawAction(law.id, patches), { ...act, start: act.back }, "Back this law")); + item.append(text("span", law.text, "guard-text"), ...lawActionNodes(lawAction(law.id, patches), { ...act, start: act.back }, "Back this law", estimate)); list.append(item); } for (const patch of offer.added) { @@ -285,7 +291,7 @@ export function guardNodes(offer: GuardOffer, patches: LawPatch[] | null | undef * touched, and Start the run with what the fields hold, which are kept in `draft` as he types. `line` says why the writer gave no draft, so * he writes the law himself. */ -export function confirmNodes(draft: NewLaw | null, parts: { id: string; name: string }[], line: string | null, act: { start: (law: NewLaw) => void; cancel: () => void }): HTMLElement[] { +export function confirmNodes(draft: NewLaw | null, parts: { id: string; name: string }[], line: string | null, act: { start: (law: NewLaw) => void; cancel: () => void }, estimate?: Figure | null): HTMLElement[] { const cancel = button("Cancel", "Leave the new law", act.cancel); if (!draft) return [text("p", "Drafting the law…", "brief-quiet guard-drafting"), cancel]; const box = text("div", "", "guard-confirm"); @@ -318,6 +324,7 @@ export function confirmNodes(draft: NewLaw | null, parts: { id: string; name: st const foot = text("div", "", "guard-foot"); foot.append( button("Start the run", "Start a background run that adds this law, as written here, with its test", () => act.start({ id: id.value.trim(), on: part.value, text: sentence.value.trim() }), "primary"), + ...[estimateLine(estimate, "brief-quiet")].filter((node) => node !== null), cancel, ); box.append(text("p", "Confirm or edit the law. Only what you confirm here reaches the run.", "brief-quiet"), part, id, sentence, foot); @@ -353,17 +360,23 @@ export function guardRow(view: MapView, pr: number, guard: Guard, redraw: () => const parts = guard.parts.map((id) => ({ id, name: view.doc.parts.find((p) => p.id === id)?.name ?? id })); const asking = mine() ? confirming : null; const adding = asking - ? confirmNodes(asking.draft, parts, asking.line, { - start: (law) => { - confirming = null; - redraw(); - invoke("new_law", { project, law, guards: pr }).then(started).catch(failure("new_law", "error")); - }, - cancel: () => { - confirming = null; - redraw(); + ? confirmNodes( + asking.draft, + parts, + asking.line, + { + start: (law) => { + confirming = null; + redraw(); + invoke("new_law", { project, law, guards: pr }).then(started).catch(failure("new_law", "error")); + }, + cancel: () => { + confirming = null; + redraw(); + }, }, - }) + view.state.law_estimate, + ) : null; - return guardNodes(guardOffer(guard, pr, view.doc.laws, view.state.law_patches), view.state.law_patches, act, adding); + return guardNodes(guardOffer(guard, pr, view.doc.laws, view.state.law_patches), view.state.law_patches, act, adding, view.state.law_estimate); } diff --git a/ui/run-cost.ts b/ui/run-cost.ts new file mode 100644 index 00000000..11ebd367 --- /dev/null +++ b/ui/run-cost.ts @@ -0,0 +1,23 @@ +// A run's cost on the page (spec #1056, "Where the figures show"): the server works the figures out (`server/src/run_cost.rs`), so the page +// only puts words round them and says in the hover where a figure comes from. A missing figure draws nothing, never a zero. + +import { hint, text } from "./dom.js"; +import type { Figure } from "./types.js"; + +/** Where a figure comes from: a share rests on a factor measured on `measured`; dollars are the run's API price as recorded. */ +const costHover = (figure: Figure): string => + figure.measured === null + ? "The run's API price, as the claude CLI recorded it." + : `API price of the run, turned into your plan's share by a factor measured on ${figure.measured}; Anthropic does not publish plan sizes.`; + +/** One line with a figure after `lead` and its hover, in the time hint's style; null when the view carries no figure. */ +export function costLine(figure: Figure | null | undefined, lead: string, className = "", tag: "p" | "span" = "p"): HTMLElement | null { + if (!figure) return null; + return hint(text(tag, `${lead} ${figure.text}`, `run-cost ${className}`.trim()), costHover(figure)); +} + +/** What a button's run is estimated to cost: "Costs about 1–3% of the 5-hour window". */ +export const estimateLine = (figure: Figure | null | undefined, className = "") => costLine(figure, "Costs", className); + +/** What a run took: "Took about 2% of the 5-hour window". */ +export const spentLine = (figure: Figure | null | undefined, className = "", tag: "p" | "span" = "p") => costLine(figure, "Took", className, tag); diff --git a/ui/style.css b/ui/style.css index 59197574..a517095a 100644 --- a/ui/style.css +++ b/ui/style.css @@ -1077,7 +1077,8 @@ button.tray-row { display: block; width: 100%; font: inherit; color: inherit; te .run-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; column-gap: var(--sp-3); align-items: baseline; padding: var(--sp-3); border-radius: var(--radius); } .run-title { font-weight: 500; } .run-row[data-state="queued"] .run-title { color: var(--muted); } -.run-note, .run-warning, .run-denials, .run-copied, .run-row .ratify-prompt { grid-column: 1 / -1; } +.run-note, .run-cost, .run-warning, .run-denials, .run-copied, .run-row .ratify-prompt { grid-column: 1 / -1; } +.run-cost { margin: 0; font-size: var(--size-xs); color: var(--muted); } .run-note, .run-warning, .run-denials, .run-copied, .runs-paused { font-size: var(--size-xs); color: var(--faint); } .run-denials { margin: var(--sp-2) 0 0; padding-inline-start: var(--sp-5); font-family: var(--mono); overflow-wrap: anywhere; } .run-copied { margin: var(--sp-2) 0 0; } @@ -1259,7 +1260,8 @@ body.panel-open .map-empty { inset-inline-start: calc(var(--inset) + var(--panel @keyframes seg-creep-write { from { transform: scaleX(0); } } @keyframes seg-creep-check { from { transform: scaleX(0); } } @keyframes seg-shimmer { to { background-position: -200% 0; } } -.map-drafting-failed { display: flex; align-items: start; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border-radius: var(--radius-small); background: var(--needs-you-bg); } +.map-drafting-failed .run-cost { flex-basis: 100%; } +.map-drafting-failed { display: flex; flex-wrap: wrap; align-items: start; justify-content: space-between; gap: var(--sp-3); padding: var(--sp-3) var(--sp-4); border-radius: var(--radius-small); background: var(--needs-you-bg); } .map-drafting-part { display: flex; flex-direction: column; } @media (prefers-reduced-motion: reduce) { .map-drafting-seg, .map-drafting-seg::before { animation: none; } .map-drafting-seg::before { transform: scaleX(.5); } } /* A part opens and closes from its header, its marker right before its name (the accordion guide). */ diff --git a/ui/tests/map-ratify.test.mjs b/ui/tests/map-ratify.test.mjs index e96d324a..06fa0918 100644 --- a/ui/tests/map-ratify.test.mjs +++ b/ui/tests/map-ratify.test.mjs @@ -145,3 +145,16 @@ test("the review's line says each state at Ratify's head, and its button starts await later(10); assert.equal(retry.disabled, false); }); + +test("the review's line shows what its run took, and Review map text and Run again show the estimate (#1056)", () => { + const figure = (words) => ({ text: words, measured: "2026-12-01" }); + const costWords = (node) => node.find("span").filter((each) => /\brun-cost\b/.test(each.className)).map((each) => each.text); + const estimate = figure("about 1% of the 5-hour window"); + const done = /** @type {any} */ (mapReviewNode(review("done", { checked: 5, flagged: 2, cost: figure("under 1% of the week") }), async () => {})); + assert.deepEqual(costWords(done), ["Took under 1% of the week"]); + const idle = /** @type {any} */ (mapReviewNode(review("idle", { estimate }), async () => {})); + assert.deepEqual(costWords(idle), ["Costs about 1% of the 5-hour window"], "Review map text"); + const failed = /** @type {any} */ (mapReviewNode(review("failed", { line: "timed out", estimate, cost: null }), async () => {})); + assert.deepEqual(costWords(failed), ["Costs about 1% of the 5-hour window"], "Run again, and a missing cost shows nothing"); + assert.deepEqual(costWords(/** @type {any} */ (mapReviewNode(review("idle"), async () => {}))), [], "no figures, no lines"); +}); diff --git a/ui/tests/map-runs.test.mjs b/ui/tests/map-runs.test.mjs index a827aaa5..c0596fe6 100644 --- a/ui/tests/map-runs.test.mjs +++ b/ui/tests/map-runs.test.mjs @@ -6,6 +6,7 @@ import { El, fakeDocument } from "./dom.mjs"; globalThis.document = fakeDocument({ body: new El("body") }); const { paintRuns, runRows, runsNodes: drawnRuns } = await import("../../dist/map-runs.js"); +const { hintOf } = await import("../../dist/dom.js"); // The runs' nodes, which here are the stand-in DOM's, whose fields the tests read. /** @type {(...args: Parameters) => any[]} */ const runsNodes = (...args) => drawnRuns(...args); @@ -269,3 +270,34 @@ test("a second click within the delay drops the first click's words, so only the await later(); assert.equal(live.text, "second"); }); + +// The words a hover holds: the hint a node names. +const hoverOf = (node) => hintOf(node)?.textContent; +const figure = (words, measured = "2026-12-01") => ({ text: words, measured }); +const costNodes = (node) => all(node).filter((each) => /\brun-cost\b/.test(each.className ?? "")); + +test("each ended row shows its actual cost, a run with none shows nothing, and the hover says where the figure comes from (#1056)", () => { + const nodes = runsNodes({ paused: null, runs: [ended("a", "done", "Done", { cost: figure("about 2% of the 5-hour window, under 1% of the week") }), ended("b", "failed", "Failed"), ended("c", "failed", "Failed", { cost: null }), run("d", "running")] }, acts([])); + const rows = nodes.filter((node) => node.dataset?.run); + assert.deepEqual(rows.map((row) => costNodes(row).map((cost) => cost.text)), [["Took about 2% of the 5-hour window, under 1% of the week"], [], [], []]); + assert.equal(hoverOf(costNodes(rows[0])[0]), "API price of the run, turned into your plan's share by a factor measured on 2026-12-01; Anthropic does not publish plan sizes."); + const dollars = runsNodes({ paused: null, runs: [ended("e", "done", "Done", { cost: { text: "$0.41 API price", measured: null } })] }, acts([])).find((node) => node.dataset?.run); + assert.equal(costNodes(dollars)[0].text, "Took $0.41 API price"); + assert.equal(hoverOf(costNodes(dollars)[0]), "The run's API price, as the claude CLI recorded it."); +}); + +test("the head shows the 7-day total with no run listed, follows the total while the list is open, and leaves with a total of nothing (#1056)", () => { + const box = new El("section"); + const head = () => costNodes(box).map((node) => node.text); + paintRuns(box, { paused: null, runs: [], total: figure("about 4% of the week") }, acts([])); + assert.deepEqual(head(), ["Last 7 days, all projects: about 4% of the week"]); + assert.equal(hoverOf(costNodes(box)[0]), "API price of the run, turned into your plan's share by a factor measured on 2026-12-01; Anthropic does not publish plan sizes."); + paintRuns(box, { paused: null, runs: [], total: figure("about 5% of the week") }, acts([])); + assert.deepEqual(head(), ["Last 7 days, all projects: about 5% of the week"], "the list drew the new total while open"); + paintRuns(box, { paused: null, runs: [run("a", "running")], total: figure("about 5% of the week") }, acts([])); + assert.deepEqual(head(), ["Last 7 days, all projects: about 5% of the week"], "beside a run, still one head"); + paintRuns(box, { paused: null, runs: [], total: null }, acts([])); + assert.deepEqual(box.childNodes, [], "a total of nothing and no run draws nothing"); + paintRuns(box, { paused: null, runs: [] }, acts([])); + assert.deepEqual(box.childNodes, []); +}); diff --git a/ui/tests/map.test.mjs b/ui/tests/map.test.mjs index f8bbd84a..3a083569 100644 --- a/ui/tests/map.test.mjs +++ b/ui/tests/map.test.mjs @@ -863,3 +863,13 @@ test("a click closes the open panel unless it lands in the panel or in what work ]; for (const [name, panel, moved, inside, closes] of rows) assert.equal(press(panel, moved, ...inside), closes, name); }); + +test("Draft the map shows its estimate under the time hint, and none without one or without claude (#1056)", async () => { + const { draftBlock } = await import("../../dist/map-scan.js"); + const figure = (words) => ({ text: words, measured: "2026-12-01" }); + const costWords = (node) => node.find("p").filter((each) => /\brun-cost\b/.test(each.className)).map((each) => each.text); + const acts = { edit() {}, redraw() {}, note: null, draft() {}, refused: null }; + assert.deepEqual(costWords(draftBlock(10, true, acts, figure("about 2–4% of the 5-hour window"))), ["Costs about 2–4% of the 5-hour window"]); + assert.deepEqual(costWords(draftBlock(10, true, acts)), [], "no estimate, no line"); + assert.deepEqual(costWords(draftBlock(10, false, acts, figure("about 2–4%"))), [], "without claude there is no run"); +}); diff --git a/ui/tests/micro-world.test.mjs b/ui/tests/micro-world.test.mjs index f4be299b..aa4af3be 100644 --- a/ui/tests/micro-world.test.mjs +++ b/ui/tests/micro-world.test.mjs @@ -120,3 +120,21 @@ test("a copy says its line once, in the page's action region; the row's note is assert.deepEqual(statuses(document.body), [live]); assert.equal(live.text, "Copy this prompt and paste it into your agent"); }); + +const figure = (words) => ({ text: words, measured: "2026-12-01" }); +const costWords = (nodes) => [...new Set(nodes.flatMap((node) => [node, ...node.find("span")]))].filter((node) => /\brun-cost\b/.test(node.className ?? "")).map((node) => node.text); + +test("every offer that starts a run shows the estimate, and a world shows what its runs cost (#1056)", () => { + const estimate = figure("about 1% of the 5-hour window"); + const withEstimate = (entries) => ({ ...worlds(true, entries), estimate }); + assert.deepEqual(costWords([exploreNode(withEstimate({}), "flow:turn", { explore() {}, open() {}, copy() {} })]), ["Costs about 1% of the 5-hour window"], "Explore this"); + const stale = withEstimate({ "flow:turn": view("ready", { page: true, stale: true }) }); + assert.deepEqual(costWords([exploreNode(stale, "flow:turn", { explore() {}, open() {}, copy() {} })]), ["Costs about 1% of the 5-hour window"], "Rebuild"); + const failed = withEstimate({ "flow:turn": view("failed", { line: "no", prompt: "p", cost: figure("under 1% of the week") }) }); + assert.deepEqual(costWords([exploreNode(failed, "flow:turn", { explore() {}, open() {}, copy() {} })]), ["Costs about 1% of the 5-hour window", "Took under 1% of the week"], "Try again, and the failed run's cost"); + assert.deepEqual(costWords([exploreNode(withEstimate({ "flow:turn": view("building") }), "flow:turn", { explore() {}, open() {}, copy() {} })]), [], "a building world starts nothing"); + assert.deepEqual(costWords([exploreNode({ ...worlds(false), estimate }, "flow:turn", { explore() {}, open() {}, copy() {} })]), [], "Copy prompt starts no run"); + assert.deepEqual(costWords([exploreNode(worlds(true, { "flow:turn": view("ready", { page: true }) }), "flow:turn", { explore() {}, open() {}, copy() {} })]), [], "no figures, no lines"); + const [head] = worldNodes("A turn", "

x

", view("ready", { page: true, stale: true }), { rebuild() {}, close() {} }, estimate); + assert.deepEqual(costWords([head]), ["Costs about 1% of the 5-hour window"], "the overlay's Rebuild"); +}); diff --git a/ui/tests/patch-review.test.mjs b/ui/tests/patch-review.test.mjs index 7dd08584..f47f58bb 100644 --- a/ui/tests/patch-review.test.mjs +++ b/ui/tests/patch-review.test.mjs @@ -233,3 +233,23 @@ test("each output scrolls on its own, so it takes focus with the name of its hea assert.deepEqual(outputs.map((output) => output.getAttribute("aria-label")), outputs.map((output) => nodes[nodes.indexOf(output) - 1].text)); assert.deepEqual(outputs.map((output) => output.getAttribute("aria-label")), ["With the test alone, the checks pass", "With the plant, the new test fails"]); }); + +// A figure as the server sends it, and the words of the line beside a button that carry one. +const figure = (words) => ({ text: words, measured: "2026-12-01" }); +const costs = (nodes) => [...new Set(nodes.flatMap((node) => [node, ...node.find("span"), ...node.find("p")]))].filter((node) => /\brun-cost\b/.test(node.className ?? "")).map((node) => node.text); + +test("Back a law, Back this law and Start the run show the estimate beside them, and the patch review what its run took (#1056)", () => { + const estimate = figure("about 1–3% of the 5-hour window"); + assert.deepEqual(costs(lawActionNodes(lawAction("core-order", []), acts([]), "Back a law", estimate)), ["Costs about 1–3% of the 5-hour window"]); + assert.deepEqual(costs(lawActionNodes(lawAction("core-order", []), acts([]), "Back a law")), [], "no estimate, no line"); + assert.deepEqual(costs(lawActionNodes(lawAction("core-order", [patch("x", "proven", { law: "core-order" })]), acts([]), "Back a law", estimate)), [], "Review the patch starts no run"); + const rejected = lawActionNodes(lawAction("core-order", [patch("x", "rejected", { line: "no" })]), acts([]), "Back a law", estimate); + assert.deepEqual(costs(rejected), ["Costs about 1–3% of the 5-hour window"], "a rejected law's Back a law is another run"); + const offer = guardOffer({ parts: ["core"] }, 7, laws, []); + assert.deepEqual(costs([guardNodes(offer, [], guardActs([]), null, estimate)]), offer.back.map(() => "Costs about 1–3% of the 5-hour window"), "beside each Back this law"); + const confirm = confirmNodes({ id: "a-b", on: "core", text: "x" }, [{ id: "core", name: "Core" }], null, { start: () => {}, cancel: () => {} }, estimate); + assert.deepEqual(costs(confirm), ["Costs about 1–3% of the 5-hour window"]); + assert.deepEqual(costs(confirmNodes({ id: "a-b", on: "core", text: "x" }, [{ id: "core", name: "Core" }], null, { start: () => {}, cancel: () => {} })), []); + assert.deepEqual(costs(reviewNodes(proven(), "Events apply in order.", acts([]))), []); + assert.deepEqual(costs(reviewNodes({ ...proven(), cost: figure("about 2% of the 5-hour window") }, "Events apply in order.", acts([]))), ["Took about 2% of the 5-hour window"]); +}); From a006f5916177e1480b8633b7af2585580b86e7c3 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 13:39:11 +0200 Subject: [PATCH 5/9] Studio: plotkeeper detects your Claude plan (#1061) `plotkeeper statusline` saves the plan's four numbers (the 5-hour and weekly percentages and their reset times) in `plan-limits.json` in the data folder, replaced on each call that carries `rate_limits`. Plan detection (`plan.rs`) reads them when they are under a minute old, else `claude -p /usage` with `--output-format stream-json --verbose`, only alongside background runs (a before/after pair around the runs since the runner was idle, at most one pair every 10 minutes) and on Detect again; never on a timer or page open. An API key and Ultra settle from one reading; Pro or Max is guessed from the first three pairs against the trial's factor. Detection writes `plan` with `confirmed: false` and never over a confirmed plan. New commands: `set_plan` (Change and Confirm) and `detect_plan` (Detect again). Co-Authored-By: Claude Opus 5.5 --- server/src/api.rs | 5 + server/src/bin/plotkeeper.rs | 10 +- server/src/lib.rs | 5 + server/src/plan.rs | 386 ++++++++++++++++++ server/src/run_cost.rs | 2 +- server/src/runner.rs | 25 ++ server/src/settings.rs | 67 ++- server/src/settings/tests.rs | 95 +++++ server/src/statusline.rs | 72 +++- server/tests/fixtures/usage/api-key.jsonl | 3 + server/tests/fixtures/usage/null-report.jsonl | 3 + .../fixtures/usage/subscriber-ultra.jsonl | 3 + server/tests/plan.rs | 301 ++++++++++++++ server/tests/runner.rs | 14 + server/tests/statusline.rs | 69 +++- server/tests/wire.rs | 24 +- system-map.json | 3 + ui/types.ts | 9 + 18 files changed, 1073 insertions(+), 23 deletions(-) create mode 100644 server/src/plan.rs create mode 100644 server/tests/fixtures/usage/api-key.jsonl create mode 100644 server/tests/fixtures/usage/null-report.jsonl create mode 100644 server/tests/fixtures/usage/subscriber-ultra.jsonl create mode 100644 server/tests/plan.rs diff --git a/server/src/api.rs b/server/src/api.rs index a6cffce3..69f38157 100644 --- a/server/src/api.rs +++ b/server/src/api.rs @@ -488,6 +488,11 @@ pub fn call(app: &Arc, page: &dyn Page, name: &str, args: Value) -> Result< arg(a, "expected")?, arg(a, "value")?, )), + "set_plan" => res(crate::settings::save_plan( + arg(a, "expected")?, + arg(a, "kind")?, + )), + "detect_plan" => out(app.plan.detect_again()), "refresh_landed_tasks" => done!(crate::refresh_landed_tasks(arc)), "page_focus" => { page.focus(arg(a, "focused")?); diff --git a/server/src/bin/plotkeeper.rs b/server/src/bin/plotkeeper.rs index 6a4e6a81..88d3a0a1 100644 --- a/server/src/bin/plotkeeper.rs +++ b/server/src/bin/plotkeeper.rs @@ -142,15 +142,15 @@ fn main() -> ExitCode { // `--yes` is for scripts: install never asks, as running it is the consent. ["install"] | ["install", "--yes"] => return wire("install", &home), ["uninstall"] => return wire("uninstall", &home), - // Claude Code's status line (spec #873): its JSON on stdin, one link to the page on stdout. + // Claude Code's status line (spec #873): its JSON on stdin, one link to the page on stdout, and the plan's numbers saved. ["statusline"] => { let mut input = String::new(); // An unreadable stdin reads as no session: the link still goes to the page. std::io::Read::read_to_string(&mut std::io::stdin(), &mut input).ok(); - print!( - "{}", - studio_server::statusline::line(&input, &studio_hook::data_dir(&home)) - ); + let data = studio_hook::data_dir(&home); + // The plan's four numbers, for plan detection (spec #1056). + studio_server::statusline::save_limits(&input, &data); + print!("{}", studio_server::statusline::line(&input, &data)); return ExitCode::SUCCESS; } // The checker's own `check`, which `system-map check` also runs, and the free scan; its other commands stay its own. diff --git a/server/src/lib.rs b/server/src/lib.rs index ebcd47cc..2ceda726 100644 --- a/server/src/lib.rs +++ b/server/src/lib.rs @@ -47,6 +47,7 @@ pub mod map_scan; pub mod micro_worlds; pub mod part_catch_ups; pub mod part_lines; +pub mod plan; pub mod pr_briefs; pub mod pre_flight; pub mod projects; @@ -166,6 +167,8 @@ pub struct App { pub reviews: Arc, /// First map's Map drafts (`map_draft.rs`): their writers and reviewers, and what they gave, kept per project. pub drafts: Arc, + /// Plan detection (`plan.rs`, spec #1056): reads alongside the background runs and on Detect again. + pub plan: Arc, /// The map items each landed commit changed (`ratify::changes_of`). changes: ratify::ChangesCache, /// Each project's part births (`staleness::births`). @@ -385,6 +388,8 @@ impl App { list_changed: AtomicBool::new(false), keys: Arc::new(settings::MemoryKeys::default()), key_set: Mutex::new(Vec::new()), + // Made after every other module, so it is told of a run's end last: a run one joins then keeps its pair open. + plan: plan::Detector::watching(data, &runner), runner, worlds, laws, diff --git a/server/src/plan.rs b/server/src/plan.rs new file mode 100644 index 00000000..3345e3d6 --- /dev/null +++ b/server/src/plan.rs @@ -0,0 +1,386 @@ +//! Plan detection (spec danielrispler/plotkeeper#1056, "The plan"; ticket #1061): which plan run cost's figures are turned +//! into, written to `settings.json` as `plan` with `confirmed: false` and never over a confirmed plan. +//! +//! - **Readings.** The status line's numbers (`statusline.rs`) when it saved a 5-hour window in the last minute, which costs +//! nothing; else `claude -p /usage`, which spends no tokens and gives its figures only as `stream-json` with `--verbose` +//! (`docs/studio/research/run-cost.md`). The status line is read only for a 5-hour window: Claude Code sends `rate_limits` +//! only after a session's first answer and drops a window once it resets, so a missing one proves nothing. +//! - **When.** Only alongside the background runs: a "before" reading when a run is queued while none was queued or running, +//! and an "after" one when the last of the runs since ends, at most one such pair at a time and one every 10 minutes; and on +//! Detect again. Never on a timer and never on page open, so opening the page spends nothing (`docs/studio/settings.md`). +//! Nothing is read while the plan is confirmed or already detected. +//! - **What.** An API key and Ultra are settled by one reading. Pro or Max is guessed from the first three pairs: the runs' +//! API price over the points the 5-hour window moved, against the trial's factor ([`guess`]). The samples live in memory, +//! so a restart starts them over. + +use crate::{ + run_cost::{FACTORS, PRO_RATIO, PlanKind}, + runner::Runner, + settings::{Plan, detected_plan_in, plan_in}, +}; +use serde::Serialize; +use std::{ + path::{Path, PathBuf}, + process::Command, + sync::{Arc, Mutex, Weak}, + thread, + time::{Duration, Instant}, +}; + +/// How long a `/usage` read may take; the trial's took 3–4 s. +const USAGE_LIMIT: Duration = Duration::from_secs(30); +/// A status line saved within this long is read instead of `/usage`. +const FRESH: Duration = Duration::from_secs(60); +/// The pairs Pro or Max is guessed from. +const PAIRS: usize = 3; + +/// What a `/usage` reading says of the plan. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Usage { + /// An API key: no plan limits. + Api, + /// Weekly limits with no 5-hour window. + Ultra, + /// Pro or Max, with how much of the 5-hour window is used, in percent. + Subscriber { five_hour: f64 }, + /// Nothing to go on. + Unknown, +} + +/// What `claude -p /usage --output-format stream-json --verbose` printed, read (`docs/studio/research/run-cost.md`, "The +/// `usage_report` shape"). The `init` line's `apiKeySource` other than `"none"`, or a report with no `rate_limits`, is an API +/// key; a `session` row is Pro or Max; weekly rows with no `session` row are Ultra. A `null` report, as when the login's token +/// lacks the `user:profile` scope, or output that is not the stream, is nothing to go on. +pub fn read_usage(stream: &str) -> Usage { + let lines: Vec = stream + .lines() + .filter_map(|line| serde_json::from_str(line).ok()) + .collect(); + let key_source = lines.iter().find_map(|line| line["apiKeySource"].as_str()); + if key_source.is_some_and(|source| source != "none") { + return Usage::Api; + } + let Some(report) = lines + .iter() + .find_map(|line| line.get("usage_report").filter(|r| r.is_object())) + else { + return Usage::Unknown; + }; + let Some(limits) = report.get("rate_limits").filter(|l| l.is_object()) else { + return Usage::Api; + }; + let rows = limits["limits"].as_array().map_or(&[][..], Vec::as_slice); + let session = rows.iter().find(|row| row["kind"] == "session"); + if let Some(session) = session { + return session["percent"] + .as_f64() + .map_or(Usage::Unknown, |five_hour| Usage::Subscriber { five_hour }); + } + if rows.iter().any(|row| row["group"] == "weekly") { + return Usage::Ultra; + } + Usage::Unknown +} + +/// Where detection reads and writes, and what it runs. +pub struct Config { + /// `settings.json`, which holds `plan`. + pub settings: PathBuf, + /// The data folder, where the status line saves its numbers. + pub data: PathBuf, + /// The `claude` to send `/usage` to; none: the login shell's, found at each read. + pub claude: Option, + /// The least time between two pairs' starts: 10 minutes in plotkeeper. + pub between_pairs: Duration, +} + +/// What Detect again found (`Detected` in `ui/types.ts`): the plan `settings.json` names after it, a line saying what was +/// found, and the file's new text when the plan changed. +#[derive(Debug, Serialize)] +pub struct Detected { + pub plan: Plan, + pub line: String, + pub settings: Option, +} + +/// The before/after readings around the runs since the runner was last idle. +struct Pair { + id: u64, + /// The 5-hour window's percent before; none until the reading answers. + before: Option, + /// The API price of the runs that ended since. + cost: f64, +} + +#[derive(Default)] +struct State { + pair: Option, + /// When the last pair started. + started: Option, + pairs: u64, + /// Each pair's points moved and API price. + samples: Vec<(f64, f64)>, +} + +/// Detects the plan alongside the background runs ([`Detector::watch`]) and on Detect again. +pub struct Detector { + config: Config, + state: Mutex, +} + +impl Detector { + pub fn new(config: Config) -> Arc { + Arc::new(Detector { + config, + state: Mutex::default(), + }) + } + + fn state(&self) -> std::sync::MutexGuard<'_, State> { + self.state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Detection in plotkeeper's data folder `data`, reading alongside `runner`'s runs ([`Detector::watch`]). + pub fn watching(data: &Path, runner: &Arc) -> Arc { + let detector = Detector::new(Config { + settings: data.join("settings.json"), + data: data.to_path_buf(), + claude: None, + between_pairs: Duration::from_secs(600), + }); + detector.watch(runner); + detector + } + + /// Reads alongside `runner`'s runs: told when it goes busy and of each end, after every other module, so a run another + /// module joins on an end keeps the pair open. Each reading runs on a thread of its own, so no run waits on it. + pub fn watch(self: &Arc, runner: &Arc) { + let me = Arc::downgrade(self); + runner.on_busy(move |_| { + if let Some(me) = me.upgrade() { + thread::spawn(move || me.run_started()); + } + }); + let (me, watched): (Weak, Weak) = + (Arc::downgrade(self), Arc::downgrade(runner)); + runner.on_end(move |ended| { + let (Some(me), Some(runner)) = (me.upgrade(), watched.upgrade()) else { + return; + }; + let cost = runner.outcome(&ended.id).and_then(|outcome| outcome.cost); + if let Some(pair) = me.add(cost, !runner.busy()) { + thread::spawn(move || me.close(pair)); + } + }); + } + + /// Whether detection still reads: the plan is neither confirmed nor detected. + fn wanted(&self) -> bool { + let text = std::fs::read_to_string(&self.config.settings).unwrap_or_default(); + plan_in(&text) == Plan::default() + } + + /// A run was queued while none was queued or running: opens a pair with the "before" reading, unless one is open, one + /// started within `between_pairs`, or detection reads no more. + pub fn run_started(&self) { + if !self.wanted() { + return; + } + let id = { + let mut state = self.state(); + let recent = state + .started + .is_some_and(|at| at.elapsed() < self.config.between_pairs); + if state.pair.is_some() || recent { + return; + } + state.pairs += 1; + state.started = Some(Instant::now()); + state.pair = Some(Pair { + id: state.pairs, + before: None, + cost: 0.0, + }); + state.pairs + }; + let usage = self.reading(); + let mut state = self.state(); + let Some(pair) = state.pair.as_mut().filter(|pair| pair.id == id) else { + return; + }; + if let Ok(Usage::Subscriber { five_hour }) = usage { + pair.before = Some(five_hour); + return; + } + state.pair = None; + drop(state); + if let Ok(usage) = usage { + self.decide(usage).ok(); + } + } + + /// A run that cost `cost` ended, and the runner is `idle` now: the "after" reading closes the pair. + pub fn run_ended(&self, cost: Option, idle: bool) { + if let Some(pair) = self.add(cost, idle) { + self.close(pair); + } + } + + /// Adds `cost` to the open pair, and takes the pair when the runner is `idle`. + fn add(&self, cost: Option, idle: bool) -> Option { + let mut state = self.state(); + let pair = state.pair.as_mut()?; + pair.cost += cost.unwrap_or(0.0); + if idle { state.pair.take() } else { None } + } + + /// The "after" reading of `pair`, kept as a sample when the window moved forward under a cost; none for a pair whose + /// "before" never answered or whose runs cost nothing. + fn close(&self, pair: Pair) { + let Some(before) = pair.before else { return }; + if pair.cost <= 0.0 || !self.wanted() { + return; + } + let Ok(usage) = self.reading() else { return }; + if let Usage::Subscriber { five_hour } = usage + && five_hour >= before + { + self.state().samples.push((five_hour - before, pair.cost)); + } + self.decide(usage).ok(); + } + + /// Detect again: one reading, now, and what it found; nothing while the plan is confirmed. + pub fn detect_again(&self) -> Detected { + let text = std::fs::read_to_string(&self.config.settings).unwrap_or_default(); + let plan = plan_in(&text); + if plan.confirmed { + return Detected { + plan, + line: "Your plan is confirmed; detection leaves it.".into(), + settings: None, + }; + } + let (line, settings) = match self.reading() { + Err(why) => (format!("/usage could not be read: {why}"), None), + Ok(usage) => { + let written = self.decide(usage); + let plan = + plan_in(&std::fs::read_to_string(&self.config.settings).unwrap_or_default()); + let line = match (usage, plan.kind) { + (Usage::Api, _) => "Found an API key.".into(), + (Usage::Ultra, _) => "Found Ultra: weekly limits, no 5-hour window.".into(), + (Usage::Subscriber { .. }, PlanKind::Pro | PlanKind::Max) => format!( + "Found a subscription; {} is guessed from your runs.", + if plan.kind == PlanKind::Pro { "Pro" } else { "Max" } + ), + (Usage::Subscriber { .. }, _) => { + "Found a subscription; Pro or Max is guessed from your next background runs." + .into() + } + (Usage::Unknown, _) => "/usage named no plan limits.".into(), + }; + match written { + Ok(written) => (line, written), + Err(why) => (format!("{line} The plan could not be saved: {why}"), None), + } + } + }; + let plan = plan_in(&std::fs::read_to_string(&self.config.settings).unwrap_or_default()); + Detected { + plan, + line, + settings, + } + } + + /// Writes what `usage` and the samples say, unconfirmed: an API key or Ultra; for a subscriber, Pro or Max once guessed, + /// a detected Pro or Max kept, and unknown over anything else detected. The new text when it wrote. + fn decide(&self, usage: Usage) -> Result, String> { + let text = std::fs::read_to_string(&self.config.settings).unwrap_or_default(); + let now = plan_in(&text).kind; + let kind = match usage { + Usage::Api => PlanKind::Api, + Usage::Ultra => PlanKind::Ultra, + Usage::Unknown => return Ok(None), + Usage::Subscriber { .. } if matches!(now, PlanKind::Pro | PlanKind::Max) => { + return Ok(None); + } + Usage::Subscriber { .. } => guess(&self.state().samples).unwrap_or(PlanKind::Unknown), + }; + let written = detected_plan_in(&self.config.settings, kind); + if let Err(why) = &written { + log::warn!("plan detection: the plan could not be saved: {why}"); + } + written + } + + /// One reading: the status line's, when it saved a 5-hour window within the last minute, else `/usage`'s. + fn reading(&self) -> Result { + let fresh = crate::statusline::limits(&self.config.data) + .filter(|(_, age)| *age < FRESH) + .and_then(|(limits, _)| limits.five_hour); + if let Some(window) = fresh { + return Ok(Usage::Subscriber { + five_hour: window.used_percentage, + }); + } + let read = self.usage(); + if let Err(why) = &read { + log::warn!("plan detection: /usage could not be read: {why}"); + } + read + } + + /// `claude -p /usage`, as background runs run `claude`: on the login, with the API key variables removed, out of the + /// hook's record, in an empty folder of its own. + fn usage(&self) -> Result { + let program = match &self.config.claude { + Some(program) => program.clone(), + None => { + let shell = std::env::var_os("SHELL").unwrap_or_else(|| "/bin/sh".into()); + studio_understanding::find(shell.as_ref(), "claude") + .ok_or("`claude` was not found")? + } + }; + let folder = tempfile::tempdir().map_err(|e| e.to_string())?; + let mut command = Command::new(program); + command + .args([ + "-p", + "/usage", + "--output-format", + "stream-json", + "--verbose", + ]) + .current_dir(folder.path()) + .env("PLOTKEEPER_INTERNAL", "1") + .env_remove("ANTHROPIC_API_KEY") + .env_remove("ANTHROPIC_AUTH_TOKEN"); + // Its exit status, never what it printed, which the log would keep. + let output = + studio_workbench::run::run_until(&mut command, USAGE_LIMIT).map_err(|e| match e { + studio_workbench::run::RunError::Failed(output) => { + format!("`claude` exited with {}", output.status) + } + other => other.to_string(), + })?; + Ok(read_usage(&String::from_utf8_lossy(&output.stdout))) + } +} + +/// Pro or Max from the first three samples, none before: their API price over the points the 5-hour window moved, Max when +/// it is nearer Max's factor than Pro's, a fifth of it, by ratio (above their geometric mean). A window that did not move is Max. +fn guess(samples: &[(f64, f64)]) -> Option { + let first = samples.get(..PAIRS)?; + let points: f64 = first.iter().map(|(points, _)| points).sum(); + let cost: f64 = first.iter().map(|(_, cost)| cost).sum(); + let between = FACTORS.five_hour_per_percent * PRO_RATIO.sqrt(); + Some(if points <= 0.0 || cost / points >= between { + PlanKind::Max + } else { + PlanKind::Pro + }) +} diff --git a/server/src/run_cost.rs b/server/src/run_cost.rs index f0472e01..12258bdc 100644 --- a/server/src/run_cost.rs +++ b/server/src/run_cost.rs @@ -36,7 +36,7 @@ pub const FACTORS: Factors = Factors { }; /// Pro's percent is this fraction of Max's dollars. -const PRO_RATIO: f64 = 0.2; +pub const PRO_RATIO: f64 = 0.2; /// Ultra's weekly percent is this many times Max's dollars. const ULTRA_WEEKLY_RATIO: f64 = 2.0; /// Records an estimate needs before it stops using the trial's figures. diff --git a/server/src/runner.rs b/server/src/runner.rs index 49341078..b2045d82 100644 --- a/server/src/runner.rs +++ b/server/src/runner.rs @@ -1395,6 +1395,8 @@ pub struct Runner { config: Config, state: Mutex, changed: Notice, + /// What is told when a run is queued while none was queued or running ([`Runner::on_busy`]). + went_busy: Notice, /// What is told of a run's end, one per module that listens ([`Runner::on_end`]). ended: Mutex>, /// For the threads that wait on a run's end: a runner that is gone is told nothing. @@ -1409,6 +1411,7 @@ impl Runner { config, state: Mutex::default(), changed: Notice::default(), + went_busy: Notice::default(), ended: Mutex::default(), me: me.clone(), ids: AtomicU64::new(0), @@ -1427,6 +1430,24 @@ impl Runner { /// start or is cancelled is told on a thread of its own, so a module that holds its own lock across a submission or a /// Cancel is never called back on that thread. While the end of a batch's run is told, the batch keeps its project's slot, /// so a run joined to it then ([`Runner::join`]) starts at once, ahead of a request queued behind the batch. + /// Sets what is told, with the run's project, when a run is queued while no run was queued or running; the first call + /// wins. Told with the runner's lock let go, on the submitting thread: plan detection's "before" reading (`plan.rs`). + pub fn on_busy(&self, busy: impl Fn(&str) + Send + Sync + 'static) { + self.went_busy.set(busy); + } + + /// Whether any run is queued or running. + pub fn busy(&self) -> bool { + Self::any_unended(&self.state()) + } + + fn any_unended(state: &State) -> bool { + state + .runs + .iter() + .any(|run| matches!(run.phase, Phase::Queued | Phase::Running { .. })) + } + pub fn on_end(&self, ended: impl Fn(Ended) + Send + Sync + 'static) { self.ended .lock() @@ -1531,12 +1552,16 @@ impl Runner { let mut projects: Vec = runs.iter().map(|stored| stored.project.clone()).collect(); projects.dedup(); let mut state = self.state(); + let was_idle = !Self::any_unended(&state); state.runs.extend(runs.into_iter().map(|stored| Run { stored, phase: Phase::Queued, })); self.advance(&mut state); drop(state); + if let (true, Some(project)) = (was_idle, projects.first()) { + self.went_busy.tell(project); + } projects.iter().for_each(|project| self.tell(project)); ids } diff --git a/server/src/settings.rs b/server/src/settings.rs index 57acbd17..5bd316f3 100644 --- a/server/src/settings.rs +++ b/server/src/settings.rs @@ -460,7 +460,7 @@ pub fn run_settings_in(text: &str, project: &str) -> RunSettings { /// The plan run cost's figures are turned into (spec #1056, "The plan"): `settings.json`'s `plan`, whose `confirmed` says Daniel /// confirmed or picked it rather than detection guessing it. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Deserialize)] +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Plan { pub kind: crate::run_cost::PlanKind, #[serde(default)] @@ -474,6 +474,71 @@ pub fn plan_in(text: &str) -> Plan { serde_json::from_value(json["plan"].clone()).unwrap_or_default() } +/// Saves Daniel's plan (spec #1056, "The plan"): Change writes his pick, Confirm the detected kind, each as `plan` with +/// `confirmed: true`, which detection never writes over. `expected` is the text the page last read. Returns the new text. +pub fn save_plan( + expected: Option, + kind: crate::run_cost::PlanKind, +) -> Result { + let [settings, _] = paths().ok_or("no home folder")?; + let _one_at_a_time = WRITING + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + save_plan_in(&settings, expected.as_deref(), kind) +} + +fn save_plan_in( + settings: &Path, + expected: Option<&str>, + kind: crate::run_cost::PlanKind, +) -> Result { + write_plan(settings, expected, kind, true) +} + +/// `plan` as `{ kind, confirmed }`, one key at a time, as `edit_text` writes only plain values. +fn write_plan( + settings: &Path, + expected: Option<&str>, + kind: crate::run_cost::PlanKind, + confirmed: bool, +) -> Result { + let key = |leaf: &str| vec!["plan".to_string(), leaf.to_string()]; + let text = write_in( + settings, + expected, + &key("kind"), + Some(&serde_json::json!(kind)), + )?; + write_in( + settings, + Some(&text), + &key("confirmed"), + Some(&serde_json::json!(confirmed)), + ) +} + +/// Detection's write (`plan.rs`): the plan it found, as `plan` with `confirmed: false`, in the `settings.json` at `settings`, +/// under the one lock of the page's writes. Never over a confirmed plan, and nothing when the file already names what it found: +/// then none. Otherwise the new text. +pub fn detected_plan_in( + settings: &Path, + kind: crate::run_cost::PlanKind, +) -> Result, String> { + let _one_at_a_time = WRITING + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let text = match fs::read_to_string(settings) { + Ok(text) => text, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(), + Err(e) => return Err(e.to_string()), + }; + let plan = plan_in(&text); + if plan.confirmed || plan.kind == kind { + return Ok(None); + } + write_plan(settings, Some(&text), kind, false).map(Some) +} + /// `microWorlds.dshVisual` in `settings.json`'s `text`: the folder that holds dsh-visual's `build.py` and `verify.mjs`, which /// a micro-world's host check runs (#399), a leading `~/` read as `home`. None when it is unset, empty or not a string: then /// "Explore this" offers only the prompt to copy. diff --git a/server/src/settings/tests.rs b/server/src/settings/tests.rs index 906de37f..8cfbc40b 100644 --- a/server/src/settings/tests.rs +++ b/server/src/settings/tests.rs @@ -102,6 +102,101 @@ fn the_plan_is_unknown_until_settings_name_one_and_a_malformed_one_reads_as_unkn } } +#[test] +fn a_picked_plan_is_confirmed_and_a_detected_one_never_goes_over_a_confirmed_one() { + use crate::run_cost::PlanKind::{Api, Max, Pro, Ultra, Unknown}; + let plan = |kind, confirmed| super::Plan { kind, confirmed }; + let home = tempfile::tempdir().unwrap(); + let file = home.path().join("settings.json"); + let mine = |plan: &str| format!("{{ // mine\n {plan}\n}}"); + // (the file before, none for no file; Daniel's pick or detection's find; the plan read back; whether the file changed) + let rows = [ + (None, Ok(Pro), plan(Pro, true), true), + // Confirm: the detected kind, picked. + ( + Some(mine(r#""plan": { "kind": "max", "confirmed": false }"#)), + Ok(Max), + plan(Max, true), + true, + ), + ( + Some(mine(r#""plan": { "kind": "ultra", "confirmed": true }"#)), + Ok(Api), + plan(Api, true), + true, + ), + // Detection writes its find unconfirmed, over nothing or over its own earlier find. + (None, Err(Max), plan(Max, false), true), + ( + Some(mine(r#""plan": { "kind": "max", "confirmed": false }"#)), + Err(Pro), + plan(Pro, false), + true, + ), + ( + Some(mine(r#""plan": { "kind": "api", "confirmed": false }"#)), + Err(Unknown), + plan(Unknown, false), + true, + ), + // Never over a confirmed plan, and nothing when it finds what is there. + ( + Some(mine(r#""plan": { "kind": "ultra", "confirmed": true }"#)), + Err(Api), + plan(Ultra, true), + false, + ), + ( + Some(mine(r#""plan": { "kind": "unknown", "confirmed": true }"#)), + Err(Max), + plan(Unknown, true), + false, + ), + ( + Some(mine(r#""explanations": true"#)), + Err(Unknown), + plan(Unknown, false), + false, + ), + ( + Some(mine(r#""plan": { "kind": "pro", "confirmed": false }"#)), + Err(Pro), + plan(Pro, false), + false, + ), + ]; + for (before, write, want, changed) in rows { + std::fs::remove_file(&file).ok(); + if let Some(before) = &before { + std::fs::write(&file, before).unwrap(); + } + let wrote = match write { + Ok(pick) => Some(super::save_plan_in(&file, before.as_deref(), pick).unwrap()), + Err(found) => super::detected_plan_in(&file, found).unwrap(), + }; + let after = std::fs::read_to_string(&file).unwrap_or_default(); + // The file holds what was returned, and the plan reads back as the build before this one reads it (`plan_in`, #1060). + assert_eq!( + super::plan_in(&after), + want, + "{before:?} {write:?}: {after}" + ); + assert_eq!(wrote.is_some(), changed, "{before:?} {write:?}"); + assert_eq!( + after != before.clone().unwrap_or_default(), + changed, + "{before:?} {write:?}" + ); + if let Some(wrote) = wrote { + assert_eq!(wrote, after); + assert_eq!(after.contains("// mine"), before.is_some(), "{after}"); + } + } + // A page that read an older text is refused. + std::fs::write(&file, "{}").unwrap(); + assert!(super::save_plan_in(&file, Some("{ }"), Pro).is_err()); +} + #[test] fn the_explanations_switch_writes_its_one_key_and_keeps_the_rest() { let home = tempfile::tempdir().unwrap(); diff --git a/server/src/statusline.rs b/server/src/statusline.rs index 3653a409..aed6b9aa 100644 --- a/server/src/statusline.rs +++ b/server/src/statusline.rs @@ -1,8 +1,16 @@ //! `plotkeeper statusline` (spec #873, ticket #884): Claude Code runs it as its status line and hands it a JSON object on //! stdin. It prints one OSC 8 link, labelled "plotkeeper", to the page's view of that session. It makes no network call: the //! port comes from the running file, else the default. +//! +//! It also saves the plan's four numbers (spec #1056, "The plan"; ticket #1061): the 5-hour and weekly percentages and their +//! reset times, from the JSON's `rate_limits`, in `plan-limits.json` in the data folder, replaced on each call that has them. +//! Nothing else of the JSON is saved: no session id, no cost, no context size. Plan detection (`plan.rs`) reads them. -use std::path::Path; +use serde::{Deserialize, Serialize}; +use std::{ + path::Path, + time::{Duration, SystemTime}, +}; use crate::{lock, web::DEFAULT_PORT}; @@ -23,3 +31,65 @@ pub fn line(input: &str, data: &Path) -> String { let fragment = session.map_or_else(String::new, |id| format!("#session={id}")); format!("\x1b]8;;http://127.0.0.1:{port}/{fragment}\x1b\\plotkeeper\x1b]8;;\x1b\\\n") } + +/// The file in the data folder that holds the plan's four numbers. +pub const LIMITS: &str = "plan-limits.json"; + +/// One window of the plan's limits, as the status line names it: how much of it is used, in percent, and when it resets, in +/// Unix seconds. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct Window { + pub used_percentage: f64, + pub resets_at: u64, +} + +/// The plan's four numbers: the 5-hour window and the week, each absent when the status line had none. +#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct Limits { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub five_hour: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seven_day: Option, +} + +/// Saves the plan's four numbers from the status-line JSON `input` in the data folder `data`, written beside the file and +/// renamed over it; a data folder plotkeeper never made is left unmade. A call whose `rate_limits` has neither window leaves the file as it was: Claude Code sends `rate_limits` only to +/// a subscriber, and only after a session's first answer, so its absence is no reading. A failed write is let go: the status +/// line still prints its link. +pub fn save_limits(input: &str, data: &Path) { + let Ok(json) = serde_json::from_str::(input) else { + return; + }; + let window = |name: &str| { + let window = &json["rate_limits"][name]; + Some(Window { + used_percentage: window["used_percentage"].as_f64()?, + resets_at: window["resets_at"].as_u64()?, + }) + }; + let limits = Limits { + five_hour: window("five_hour"), + seven_day: window("seven_day"), + }; + if limits == Limits::default() { + return; + } + let temp = data.join(format!("{LIMITS}.{}.tmp", std::process::id())); + let written = std::fs::write(&temp, serde_json::to_string(&limits).unwrap_or_default()) + .and_then(|()| std::fs::rename(&temp, data.join(LIMITS))); + if written.is_err() { + std::fs::remove_file(&temp).ok(); + } +} + +/// The plan's four numbers saved in `data`, with how long ago they were saved; none when no status line saved any, or the file +/// does not read. +pub fn limits(data: &Path) -> Option<(Limits, Duration)> { + let file = data.join(LIMITS); + let age = std::fs::metadata(&file) + .and_then(|meta| meta.modified()) + .ok() + .map(|at| SystemTime::now().duration_since(at).unwrap_or_default())?; + let limits = serde_json::from_str(&std::fs::read_to_string(&file).ok()?).ok()?; + Some((limits, age)) +} diff --git a/server/tests/fixtures/usage/api-key.jsonl b/server/tests/fixtures/usage/api-key.jsonl new file mode 100644 index 00000000..75fa195e --- /dev/null +++ b/server/tests/fixtures/usage/api-key.jsonl @@ -0,0 +1,3 @@ +{"type": "system", "subtype": "init", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "model": "claude-sonnet-5-5", "permissionMode": "dontAsk", "apiKeySource": "ANTHROPIC_API_KEY", "claude_code_version": "2.1.331"} +{"type": "assistant", "message": {"diagnostics": null, "id": "dfee10ca-9e6e-48f9-83db-e07472057190", "container": null, "model": "", "role": "assistant", "stop_details": null, "stop_reason": "end_turn", "stop_sequence": null, "type": "message", "usage": {"output_tokens_details": null, "input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": null, "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": null, "iterations": null, "speed": null, "fallback_credit": null}, "content": [{"type": "text", "text": "You are currently using an API key to power your Claude Code usage"}], "context_management": null}, "parent_tool_use_id": null, "local_command_source": "You are currently using an API key to power your Claude Code usage", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "uuid": "cccb4457-0fed-47e2-8ed2-e0da59915d8d", "timestamp": "2026-12-02T10:39:29.472Z", "usage_report": {"session": {"total_cost_usd": 0, "total_api_duration_ms": 0, "total_duration_ms": 2616, "total_lines_added": 0, "total_lines_removed": 0, "model_usage": {}}}, "local_command_run": {"command": "usage", "args": ""}} +{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "total_cost_usd": 0, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": "", "iterations": [], "speed": "standard", "fallback_credit": null}, "modelUsage": {}, "permission_denials": [], "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "safety_stops": 0, "subtype": "success", "result": "You are currently using an API key to power your Claude Code usage", "local_command": "usage", "type": "result", "duration_ms": 2494, "uuid": "314939b2-c5ea-4f13-93cf-0ff11e34f476", "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": {}} diff --git a/server/tests/fixtures/usage/null-report.jsonl b/server/tests/fixtures/usage/null-report.jsonl new file mode 100644 index 00000000..b8ed6ba3 --- /dev/null +++ b/server/tests/fixtures/usage/null-report.jsonl @@ -0,0 +1,3 @@ +{"type": "system", "subtype": "init", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "model": "claude-sonnet-5-5", "permissionMode": "dontAsk", "apiKeySource": "none", "claude_code_version": "2.1.331"} +{"type": "assistant", "message": {"diagnostics": null, "id": "dfee10ca-9e6e-48f9-83db-e07472057190", "container": null, "model": "", "role": "assistant", "stop_details": null, "stop_reason": "end_turn", "stop_sequence": null, "type": "message", "usage": {"output_tokens_details": null, "input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": null, "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": null, "iterations": null, "speed": null, "fallback_credit": null}, "content": [{"type": "text", "text": "You are currently using your subscription to power your Claude Code usage"}], "context_management": null}, "parent_tool_use_id": null, "local_command_source": "You are currently using your subscription to power your Claude Code usage", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "uuid": "cccb4457-0fed-47e2-8ed2-e0da59915d8d", "timestamp": "2026-12-02T10:39:29.472Z", "usage_report": null, "local_command_run": {"command": "usage", "args": ""}} +{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "total_cost_usd": 0, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": "", "iterations": [], "speed": "standard", "fallback_credit": null}, "modelUsage": {}, "permission_denials": [], "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "safety_stops": 0, "subtype": "success", "result": "You are currently using your subscription to power your Claude Code usage", "local_command": "usage", "type": "result", "duration_ms": 2494, "uuid": "314939b2-c5ea-4f13-93cf-0ff11e34f476", "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": {}} diff --git a/server/tests/fixtures/usage/subscriber-ultra.jsonl b/server/tests/fixtures/usage/subscriber-ultra.jsonl new file mode 100644 index 00000000..e424b5d9 --- /dev/null +++ b/server/tests/fixtures/usage/subscriber-ultra.jsonl @@ -0,0 +1,3 @@ +{"type": "system", "subtype": "init", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "model": "claude-sonnet-5-5", "permissionMode": "dontAsk", "apiKeySource": "none", "claude_code_version": "2.1.331"} +{"type": "assistant", "message": {"diagnostics": null, "id": "dfee10ca-9e6e-48f9-83db-e07472057190", "container": null, "model": "", "role": "assistant", "stop_details": null, "stop_reason": "end_turn", "stop_sequence": null, "type": "message", "usage": {"output_tokens_details": null, "input_tokens": 0, "output_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": null, "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": null, "iterations": null, "speed": null, "fallback_credit": null}, "content": [{"type": "text", "text": "You are currently using your subscription to power your Claude Code usage\n\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)"}], "context_management": null}, "parent_tool_use_id": null, "local_command_source": "You are currently using your subscription to power your Claude Code usage\n\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)", "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "uuid": "cccb4457-0fed-47e2-8ed2-e0da59915d8d", "timestamp": "2026-12-02T10:39:29.472Z", "usage_report": {"session": {"total_cost_usd": 0, "total_api_duration_ms": 0, "total_duration_ms": 2616, "total_lines_added": 0, "total_lines_removed": 0, "model_usage": {}}, "rate_limits": {"limits": [{"kind": "weekly_all", "group": "weekly", "percent": 64, "resets_at": "2026-12-07T03:00:00.426538+00:00", "scope": null, "severity": "normal", "is_active": true}, {"kind": "weekly_scoped", "group": "weekly", "percent": 0, "resets_at": "2026-12-07T03:00:00+00:00", "scope": {"model": {"display_name": "Fable"}, "surface": null}, "severity": "normal", "is_active": false}], "extra_usage": {"is_enabled": false, "monthly_limit": 1000, "used_credits": 0, "utilization": 0, "currency": "USD"}}}, "local_command_run": {"command": "usage", "args": ""}} +{"is_error": false, "duration_api_ms": 0, "num_turns": 0, "stop_reason": null, "session_id": "5d7d94b3-9eec-4be4-8391-9a83c305390c", "total_cost_usd": 0, "usage": {"output_tokens_details": {"thinking_tokens": 0}, "input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0, "server_tool_use": {"web_search_requests": 0, "web_fetch_requests": 0}, "service_tier": "standard", "cache_creation": {"ephemeral_1h_input_tokens": 0, "ephemeral_5m_input_tokens": 0}, "inference_geo": "", "iterations": [], "speed": "standard", "fallback_credit": null}, "modelUsage": {}, "permission_denials": [], "fast_mode_state": "off", "fast_mode_disabled_reason": "sdk_opt_in_required", "subagent_stats": {"spawned": 0, "requested": {"background": 0, "foreground": 0, "unset": 0}, "started_in_background": 0, "max_depth": 0, "spawned_by_subagents": 0, "completed": 0, "failed": 0, "killed": {"parent": 0, "user": 0, "system": 0}, "refused": {"depth_limit": 0, "concurrency_limit": 0, "budget": 0}, "by_type": {}}, "safety_stops": 0, "subtype": "success", "result": "You are currently using your subscription to power your Claude Code usage\n\nCurrent week (all models): 64% used · resets Dec 7 at 5am (Asia/Jerusalem)\nCurrent week (Fable): 0% used · resets Dec 7 at 5am (Asia/Jerusalem)", "local_command": "usage", "type": "result", "duration_ms": 2494, "uuid": "314939b2-c5ea-4f13-93cf-0ff11e34f476", "queued_turn_count": 0, "result_index": 0, "model_usage_since_last_result": {}} diff --git a/server/tests/plan.rs b/server/tests/plan.rs new file mode 100644 index 00000000..5679d57f --- /dev/null +++ b/server/tests/plan.rs @@ -0,0 +1,301 @@ +//! Plan detection (spec #1056, "The plan"; ticket #1061): `/usage`'s stream read, and when detection reads and what it writes. + +use std::{ + path::{Path, PathBuf}, + sync::Arc, + time::Duration, +}; +use studio_server::{ + plan::{Config, Detector, Usage, read_usage}, + run_cost::PlanKind, + runner::{self, Harness, HarnessCommand, Runner}, + settings::{Plan, plan_in}, +}; +use studio_test_support::fake::{self, Behaviour}; + +const FIXTURES: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/usage"); + +fn fixture(name: &str) -> String { + std::fs::read_to_string(format!("{FIXTURES}/{name}")).unwrap() +} + +#[test] +fn usage_reads_the_plan_from_the_report_and_the_key_source() { + let init = + |source: &str| format!(r#"{{"type":"system","subtype":"init","apiKeySource":"{source}"}}"#); + let report = |report: &str| format!(r#"{{"type":"assistant","usage_report":{report}}}"#); + let rows = [ + // The trial's capture, from Max: the session row's percent. + ( + fixture("subscriber-max.jsonl"), + Usage::Subscriber { five_hour: 30.0 }, + ), + // Written from the documented shape: weekly rows with no session row; no `rate_limits` and a key source; a `null` + // report, as when the login's token lacks the `user:profile` scope. + (fixture("subscriber-ultra.jsonl"), Usage::Ultra), + (fixture("api-key.jsonl"), Usage::Api), + (fixture("null-report.jsonl"), Usage::Unknown), + // Either sign of an API key is enough: no `rate_limits` on the subscription login, or a key source with limits. + ( + format!("{}\n{}", init("none"), report(r#"{"session":{}}"#)), + Usage::Api, + ), + ( + format!( + "{}\n{}", + init("apiKeyHelper"), + report( + r#"{"rate_limits":{"limits":[{"kind":"session","group":"session","percent":3}]}}"# + ) + ), + Usage::Api, + ), + // Limits with no row to go on, no report at all, and output that is not the stream. + ( + format!( + "{}\n{}", + init("none"), + report(r#"{"rate_limits":{"limits":[]}}"#) + ), + Usage::Unknown, + ), + (init("none"), Usage::Unknown), + ("Error: not logged in".to_string(), Usage::Unknown), + (String::new(), Usage::Unknown), + ]; + for (stream, want) in rows { + assert_eq!(read_usage(&stream), want, "{stream}"); + } +} + +/// A detector over a fresh data folder whose `settings.json` holds `settings`, with a fake `claude` that records its calls and +/// prints `stream`, and pairs at most once in `between_pairs`. +struct Bench { + detector: Arc, + claude: PathBuf, + dir: tempfile::TempDir, +} + +fn bench(settings: &str, stream: &str, between_pairs: Duration) -> Bench { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("settings.json"), settings).unwrap(); + let claude = fake::fake(dir.path(), "claude", &said(stream)); + let detector = Detector::new(Config { + settings: dir.path().join("settings.json"), + data: dir.path().to_path_buf(), + claude: Some(claude.clone()), + between_pairs, + }); + Bench { + detector, + claude, + dir, + } +} + +fn said(stream: &str) -> Behaviour { + Behaviour { + stdout: stream.into(), + record: true, + ..Behaviour::default() + } +} + +/// `/usage` from a Max subscriber whose 5-hour window is `percent` used: the trial's capture, with its percent changed. +fn max_at(percent: u32) -> String { + fixture("subscriber-max.jsonl").replace(r#""percent": 30"#, &format!(r#""percent": {percent}"#)) +} + +impl Bench { + fn calls(&self) -> usize { + fake::calls(&self.claude).len() + } + + fn settings(&self) -> String { + std::fs::read_to_string(self.dir.path().join("settings.json")).unwrap() + } + + fn plan(&self) -> Plan { + plan_in(&self.settings()) + } + + /// `/usage` prints `stream` from now on. + fn says(&self, stream: &str) { + fake::fake(self.dir.path(), "claude", &said(stream)); + } +} + +const TEN_MINUTES: Duration = Duration::from_secs(600); +const UNSET: &str = "{ // mine\n}"; + +#[test] +fn detection_never_writes_over_a_confirmed_plan_nor_reads_for_one() { + let confirmed = r#"{ "plan": { "kind": "max", "confirmed": true } }"#; + for stream in [ + fixture("api-key.jsonl"), + fixture("subscriber-ultra.jsonl"), + max_at(10), + ] { + let bench = bench(confirmed, &stream, Duration::ZERO); + for _ in 0..3 { + bench.detector.run_started(); + bench.detector.run_ended(Some(0.4), true); + } + let detected = bench.detector.detect_again(); + assert_eq!(bench.settings(), confirmed); + assert_eq!( + detected.plan, + Plan { + kind: PlanKind::Max, + confirmed: true + } + ); + assert_eq!(detected.settings, None); + assert_eq!(bench.calls(), 0, "a confirmed plan needs no reading"); + } +} + +/// A harness that builds no command: the runner here only answers what the page reads. +struct NoHarness; + +impl Harness for NoHarness { + fn command(&self, _: &runner::Plan) -> Result { + Err("no harness".into()) + } +} + +fn runner_in(dir: &Path) -> Arc { + Runner::new(runner::Config { + data: dir.to_path_buf(), + runs: dir.join("runs"), + settings: dir.join("settings.json"), + launcher: dir.join("no-launcher"), + harness: Arc::new(NoHarness), + }) +} + +#[test] +fn usage_is_read_only_around_runs_once_a_pair_and_on_detect_again_never_on_page_open() { + let bench = bench(UNSET, &max_at(24), TEN_MINUTES); + // plotkeeper starts, and the page opens and reads the runs, their costs and the settings: no `claude` call. + let runner = runner_in(bench.dir.path()); + bench.detector.watch(&runner); + runner.runs("/p/app"); + runner.costs().total(); + bench.settings(); + assert_eq!(bench.calls(), 0); + + // A run starts while none ran: the "before" reading, sent as the trial found it gives its figures. + bench.detector.run_started(); + assert_eq!(bench.calls(), 1); + let call = &fake::calls(&bench.claude)[0]; + assert_eq!( + call.args, + [ + "-p", + "/usage", + "--output-format", + "stream-json", + "--verbose" + ] + ); + assert_eq!( + call.env.get("PLOTKEEPER_INTERNAL").map(String::as_str), + Some("1") + ); + // More runs start and end while the pair is open; none reads. + bench.detector.run_started(); + bench.detector.run_ended(Some(0.2), false); + assert_eq!(bench.calls(), 1); + // The last one ends: the "after" reading. + bench.says(&max_at(25)); + bench.detector.run_ended(Some(0.2), true); + assert_eq!(bench.calls(), 2); + // A run within 10 minutes of the pair's start reads nothing. + bench.detector.run_started(); + bench.detector.run_ended(Some(0.2), true); + assert_eq!(bench.calls(), 2); + // Detect again sends one. + bench.detector.detect_again(); + assert_eq!(bench.calls(), 3); + // A status line that saved the numbers just now is read instead of `/usage`. + std::fs::write( + bench.dir.path().join("plan-limits.json"), + r#"{"five_hour":{"used_percentage":26.0,"resets_at":1738425600}}"#, + ) + .unwrap(); + bench.detector.detect_again(); + assert_eq!(bench.calls(), 3); + assert_eq!( + bench.plan(), + Plan::default(), + "Pro or Max waits for three runs" + ); +} + +#[test] +fn detection_writes_what_it_finds_unconfirmed() { + use PlanKind::{Api, Max, Pro, Ultra, Unknown}; + // (what `/usage` says at each pair's before and after reading, with the runs' cost between; the plan written) + // Each pair's "before" and "after" `/usage` output, and the runs' API price between. + type Pairs = Vec<(String, String, f64)>; + let pairs = |pairs: &[(u32, u32, f64)]| -> Pairs { + pairs + .iter() + .map(|&(a, b, cost)| (max_at(a), max_at(b), cost)) + .collect() + }; + let api = fixture("api-key.jsonl"); + let rows: Vec<(Pairs, PlanKind)> = vec![ + // One reading settles an API key or Ultra. + (vec![(api.clone(), api, 0.0)], Api), + ( + vec![(fixture("subscriber-ultra.jsonl"), String::new(), 0.0)], + Ultra, + ), + // Nothing to go on writes nothing. + ( + vec![(fixture("null-report.jsonl"), String::new(), 0.0)], + Unknown, + ), + // Three runs whose cost moved the 5-hour window about as much as Max's factor says ($0.41 a point): Max. + ( + pairs(&[(24, 25, 0.45), (25, 26, 0.38), (26, 27, 0.50)]), + Max, + ), + // A window that did not move at all is Max too: Pro's moves five times as far. + ( + pairs(&[(24, 24, 0.20), (24, 24, 0.15), (24, 25, 0.30)]), + Max, + ), + // About Pro's factor ($0.08 a point): Pro. + ( + pairs(&[(10, 15, 0.40), (15, 19, 0.35), (19, 25, 0.45)]), + Pro, + ), + // Two runs are not enough, and a window that reset between, or a pair with no cost, is no sample. + (pairs(&[(24, 25, 0.45), (25, 26, 0.38)]), Unknown), + ( + pairs(&[(24, 25, 0.45), (25, 26, 0.38), (90, 2, 0.4), (26, 27, 0.0)]), + Unknown, + ), + ]; + for (pairs, want) in rows { + let bench = bench(UNSET, "", Duration::ZERO); + for (before, after, cost) in &pairs { + bench.says(before); + bench.detector.run_started(); + bench.says(after); + bench.detector.run_ended(Some(*cost), true); + } + assert_eq!( + bench.plan(), + Plan { + kind: want, + confirmed: false + }, + "{want:?}" + ); + assert!(bench.settings().contains("// mine"), "{}", bench.settings()); + } +} diff --git a/server/tests/runner.rs b/server/tests/runner.rs index 606dd893..70772616 100644 --- a/server/tests/runner.rs +++ b/server/tests/runner.rs @@ -999,7 +999,15 @@ fn checks_and_setup_are_read_fresh_for_each_run_and_a_project_with_none_is_refus #[test] fn one_run_at_a_time_per_project_and_the_queue_runs_in_order() { + use std::sync::atomic::{AtomicUsize, Ordering}; let bench = bench(); + // The runner says when a run is queued while none was queued or running (#1061: plan detection's "before" reading). + let busy = Arc::new(AtomicUsize::new(0)); + let told = busy.clone(); + bench.runner.on_busy(move |_| { + told.fetch_add(1, Ordering::SeqCst); + }); + assert!(!bench.runner.busy()); let first = bench.run(&waits("first")); let second = bench.run(&waits("second")); let third = bench.run("echo third"); @@ -1010,6 +1018,8 @@ fn one_run_at_a_time_per_project_and_the_queue_runs_in_order() { }); assert_eq!(bench.state(&second), Some(RunState::Queued)); assert_eq!(bench.state(&third), Some(RunState::Queued)); + assert!(bench.runner.busy()); + assert_eq!(busy.load(Ordering::SeqCst), 1, "told once for four runs"); let listed: Vec = bench .runner .runs(PROJECT) @@ -1028,6 +1038,10 @@ fn one_run_at_a_time_per_project_and_the_queue_runs_in_order() { fs::write(bench.folder(&other).join("work/go"), "").unwrap(); bench.until(ended(&other)); assert_eq!(bench.runner.outcome(&second).unwrap().result, "second"); + assert!(!bench.runner.busy()); + let fourth = bench.run("echo fourth"); + assert_eq!(busy.load(Ordering::SeqCst), 2, "told again once idle"); + bench.until(ended(&fourth)); } #[test] diff --git a/server/tests/statusline.rs b/server/tests/statusline.rs index 2d27fef2..b832fd5e 100644 --- a/server/tests/statusline.rs +++ b/server/tests/statusline.rs @@ -1,4 +1,5 @@ -//! `plotkeeper statusline` (spec #873, ticket #884): Claude Code's status-line JSON on stdin, one OSC 8 link on stdout. +//! `plotkeeper statusline` (spec #873, ticket #884): Claude Code's status-line JSON on stdin, one OSC 8 link on stdout, and +//! (spec #1056, ticket #1061) the plan's four numbers saved in the data folder. mod isolated_home; @@ -7,15 +8,22 @@ use std::{ process::{Command, Stdio}, }; -/// What `plotkeeper statusline` prints for `stdin`, in a home folder whose data folder holds `running` as its running file. -fn statusline(running: Option<&str>, stdin: &str) -> String { +/// The file the status line saves the plan's numbers in. +const LIMITS: &str = "plan-limits.json"; + +/// What `plotkeeper statusline` prints for `stdin`, and the numbers file it leaves, in a home folder whose data folder holds +/// `running` as its running file and `saved` as its numbers file. +fn statusline(running: Option<&str>, saved: Option<&str>, stdin: &str) -> (String, Option) { isolated_home::set(); let home = tempfile::tempdir().unwrap(); + let data = studio_hook::data_dir(home.path()); + std::fs::create_dir_all(&data).unwrap(); if let Some(running) = running { - let data = studio_hook::data_dir(home.path()); - std::fs::create_dir_all(&data).unwrap(); std::fs::write(data.join("plotkeeper.running.json"), running).unwrap(); } + if let Some(saved) = saved { + std::fs::write(data.join(LIMITS), saved).unwrap(); + } let mut child = Command::new(env!("CARGO_BIN_EXE_plotkeeper")) .arg("statusline") .env("HOME", home.path()) @@ -32,7 +40,8 @@ fn statusline(running: Option<&str>, stdin: &str) -> String { .unwrap(); let out = child.wait_with_output().unwrap(); assert!(out.status.success(), "{out:?}"); - String::from_utf8(out.stdout).unwrap() + let left = std::fs::read_to_string(data.join(LIMITS)).ok(); + (String::from_utf8(out.stdout).unwrap(), left) } fn link(port: u16, session: &str) -> String { @@ -40,14 +49,48 @@ fn link(port: u16, session: &str) -> String { } #[test] -fn prints_one_link_to_the_session_on_the_running_port_or_the_default() { +fn prints_one_link_to_the_session_and_saves_only_the_plans_four_numbers() { let json = r#"{"session_id":"abc-123","model":{"display_name":"Opus"}}"#; let running = r#"{"port":51234,"token":"t","version":"1"}"#; - // The token stays out of the link; with no running file the default port serves. - for (running, stdin, want) in [ - (Some(running), json, link(51234, "abc-123")), - (None, json, link(47800, "abc-123")), - ] { - assert_eq!(statusline(running, stdin), want); + // Everything a status line gets beside the limits: none of it is saved. + let limited = r#"{"session_id":"abc-123","cost":{"total_cost_usd":1.25},"context_window":{"used_percentage":8}, + "rate_limits":{"five_hour":{"used_percentage":23.5,"resets_at":1738425600}, + "seven_day":{"used_percentage":41.2,"resets_at":1738857600}, + "spend_limit":{"used_percentage":62.8,"resets_at":1740787200}}}"#; + let weekly_only = r#"{"session_id":"abc-123","rate_limits":{"seven_day":{"used_percentage":12,"resets_at":1738857600}}}"#; + let old = r#"{"five_hour":{"used_percentage":1.0,"resets_at":1}}"#; + let numbers = |text: &Option| { + text.as_deref() + .map(|t| serde_json::from_str::(t).unwrap()) + }; + let rows = [ + // The token stays out of the link; with no running file the default port serves. No limits, nothing saved. + (Some(running), None, json, link(51234, "abc-123"), None), + (None, None, json, link(47800, "abc-123"), None), + // The four numbers replace what was saved; the cost, context, spend limit and session id are not saved. + ( + None, + Some(old), + limited, + link(47800, "abc-123"), + Some( + r#"{"five_hour":{"used_percentage":23.5,"resets_at":1738425600},"seven_day":{"used_percentage":41.2,"resets_at":1738857600}}"#, + ), + ), + // A window that is absent is left out. + ( + None, + None, + weekly_only, + link(47800, "abc-123"), + Some(r#"{"seven_day":{"used_percentage":12.0,"resets_at":1738857600}}"#), + ), + // A call with no `rate_limits`, as a session's before its first answer, leaves the saved numbers as they were. + (None, Some(old), json, link(47800, "abc-123"), Some(old)), + ]; + for (running, saved, stdin, want, left) in rows { + let (printed, file) = statusline(running, saved, stdin); + assert_eq!(printed, want, "{stdin}"); + assert_eq!(numbers(&file), numbers(&left.map(String::from)), "{stdin}"); } } diff --git a/server/tests/wire.rs b/server/tests/wire.rs index c484b8cc..6833f04b 100644 --- a/server/tests/wire.rs +++ b/server/tests/wire.rs @@ -477,7 +477,7 @@ fn the_wire_samples_of_the_map_view_are_written_for_tsc() { // @law: wire-types-agree #[test] fn the_wire_samples_of_the_writer_section_are_written_for_tsc() { - use studio_server::{WriterTest, Writers}; + use studio_server::{WriterTest, Writers, plan::Detected, run_cost::PlanKind, settings::Plan}; let mut writers = studio_understanding::found_writers(std::path::Path::new("/no/login-shell")); writers[3].found = true; let samples: Vec = vec![ @@ -508,11 +508,31 @@ fn the_wire_samples_of_the_writer_section_are_written_for_tsc() { settings: None, }), ), + // Detect again's reply (#1061): a plan it wrote, and one it left. + ( + "Detected", + json(Detected { + plan: Plan { + kind: PlanKind::Api, + confirmed: false, + }, + line: "Found an API key.".into(), + settings: Some(r#"{ "plan": { "kind": "api", "confirmed": false } }"#.into()), + }), + ), + ( + "Detected", + json(Detected { + plan: Plan::default(), + line: "/usage named no plan limits.".into(), + settings: None, + }), + ), ]; write( env!("CARGO_MANIFEST_DIR"), "server-writers", - &["Writers", "WriterTest"], + &["Writers", "WriterTest", "Detected"], &samples, ); } diff --git a/system-map.json b/system-map.json index d472a9d7..f64c0ea3 100644 --- a/system-map.json +++ b/system-map.json @@ -48,6 +48,7 @@ { "name": "The read loop", "text": "Follows the event log, sends what changed (the list, the brief, notices, settings) to the page, removes the asks the terminal answered.", "paths": ["server/src/read_loop.rs", "server/src/asks.rs"] }, { "name": "Settings and projects", "text": "The writer, its API keys in plotkeeper's own Keychain entries (the Secret Service's on Linux), the settings and the saved project list.", "paths": ["server/src/settings.rs", "server/src/settings/", "server/src/projects.rs", "server/src/projects/"] }, { "name": "The switchboard", "text": "Jump raises a terminal; Open in editor opens a file inside its checkout; Send types into a Herdr.app session past a guard. Fixed programs.", "paths": ["server/src/switchboard.rs"] }, + { "name": "Run cost and the plan", "text": "A run's cost in the plan's unit; `plotkeeper statusline` saves the plan's four numbers, and detection reads them or `/usage` beside a run.", "paths": ["server/src/run_cost.rs", "server/src/statusline.rs", "server/src/plan.rs"] }, { "name": "The programs", "text": "`plotkeeper`, which starts the server, adds its folder's repository and opens the page on it, and `plotkeeper-run`, one run's launcher.", "paths": ["server/src/bin/plotkeeper.rs", "server/src/bin/plotkeeper-run.rs"] } ], "tier": "core", "zone": "server-crate", "paths": ["server/"] @@ -206,6 +207,8 @@ "reason": "The runner starts headless agent runs, such as back a law and micro-worlds, in a sandbox." }, { "id": "install-agents", "from": "install", "to": "agents", "kind": "spawn", "reason": "Install runs each agent's own install command, such as `claude plugin` or `qwen extensions`." }, + { "id": "server-agents", "from": "server", "to": "agents", "kind": "spawn", + "reason": "Plan detection sends `/usage` through `claude -p` beside a background run and on Detect again, never on page open." }, { "id": "server-apps", "from": "server", "to": "apps", "kind": "spawn", "reason": "The switchboard raises a terminal app with `open` and Herdr's command, opens a file in an editor, and types a reply with `hc send`." }, { "id": "workbench-agents", "from": "workbench", "to": "agents", "kind": "spawn", diff --git a/ui/types.ts b/ui/types.ts index 47e45499..ee2f8b2e 100644 --- a/ui/types.ts +++ b/ui/types.ts @@ -528,6 +528,11 @@ export type MapState = { export type Figure = { text: string; measured: string | null }; /** `settings.json`'s `plan` (spec #1056, "The plan"): the plan's kind, and whether Daniel confirmed or picked it rather than detection. */ export type Plan = { kind: "pro" | "max" | "ultra" | "api" | "unknown"; confirmed: boolean }; +/** + * What Detect again found (`plan.rs`, #1061): the plan `settings.json` names after it, a line saying what was found, and the file's new + * text when the plan changed, null when it did not. + */ +export type Detected = { plan: Plan; line: string; settings: string | null }; /** * A micro-world as the map shows it: `building` while its run is queued, running or checked, `ready` with a checked page, `failed` with why * (`line`) and the prompt to copy. `page`: a checked page is stored to open; `stale`: a part on it changed since it was built. @@ -1076,6 +1081,10 @@ export interface Commands { set_api_key: { args: { writer: WriterKind; key?: string | null; baseUrl?: string | null } & Expecting; reply: string | null }; set_explanations: { args: { on: boolean } & Expecting; reply: string }; set_open_files_in: { args: { value: OpenFilesIn } & Expecting; reply: string }; + // Change and Confirm (spec #1056, "The plan"): the plan picked, saved confirmed; the reply is the new text, as a save's. + set_plan: { args: { kind: Plan["kind"] } & Expecting; reply: string }; + // Detect again: one reading now, and what it found (#1061). + detect_plan: { args: None; reply: Detected }; settings_files: { args: None; reply: SettingsFiles }; store_notice: { args: None; reply: string | null }; subagent_log: { args: { session: string; agentId: string; offset: number }; reply: SubagentLog | null }; From beba4a0446c45aaaf636c591c4c08de30cfa78b4 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 13:57:14 +0200 Subject: [PATCH 6/9] Studio: the snap base answers set_plan and detect_plan (#1061) Co-Authored-By: Claude Opus 5.5 --- scripts/snap/base.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/snap/base.ts b/scripts/snap/base.ts index b58de42c..d948ab8e 100644 --- a/scripts/snap/base.ts +++ b/scripts/snap/base.ts @@ -108,6 +108,8 @@ export const base = { set_api_key: null, set_explanations: "{}", set_open_files_in: '{ "openFilesIn": "auto" }', + set_plan: '{ "plan": { "kind": "max", "confirmed": true } }', + detect_plan: { plan: { kind: "unknown", confirmed: false }, line: "/usage named no plan limits.", settings: null }, open_in_editor: "main", send_guard: { passes: true, reason: null }, issue_title: { title: "", url: "" }, From 90cbba5158e7b0772ef3ff141a5284b4b1c82be8 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 14:18:47 +0200 Subject: [PATCH 7/9] Studio: Settings shows the detected plan to confirm or change (#1064) Co-Authored-By: Claude Opus 5.5 --- scripts/snap/fixtures-writers.ts | 28 +++++++++++++ scripts/snap/fixtures.ts | 4 +- ui/main.ts | 1 + ui/style.css | 1 + ui/tests/writers.test.mjs | 15 ++++++- ui/writers.ts | 68 ++++++++++++++++++++++++++++++-- 6 files changed, 111 insertions(+), 6 deletions(-) diff --git a/scripts/snap/fixtures-writers.ts b/scripts/snap/fixtures-writers.ts index 5fe4e9f6..b2d54672 100644 --- a/scripts/snap/fixtures-writers.ts +++ b/scripts/snap/fixtures-writers.ts @@ -172,3 +172,31 @@ export const writersSecretService = () => if (error?.textContent !== "No secret store on this machine; install a keyring and libsecret-tools, or pick a CLI writer.") return log("snap:fail no store error: " + error?.textContent); ${writerStatusAfter("pick a CLI writer")} ${confirmFirst(`document.getElementById("writer-key-remove").click()`, "remove_api_key", "Remove key", ["Secret Service"])}`); +/** The plan row (spec #1056, #1064), detected and not yet confirmed: it says so, and Confirm turns it to confirmed in place. */ +export const writersPlanDetected = () => + writersOpen({ + writers: { writers: [claudeWriter, agyWriter], summaries_on: true, briefs: true, keys: [], base_url: null, key_store: "the macOS Keychain" }, + settings_files: { settings: '{ "plan": { "kind": "max", "confirmed": false } }', keymap: null }, + set_plan: '{ "plan": { "kind": "max", "confirmed": true } }', + }, ` + const state = () => document.getElementById("writer-plan-state")?.textContent; + if (state() !== "Plan: Max, detected, not confirmed.") return log("snap:fail the plan row says " + state()); + const options = [...document.querySelectorAll("#writer-plan-pick option")].map((o) => o.textContent).join(); + if (options !== "Pro,Max,Ultra,API key,not known") log("snap:fail the plan's choices: " + options); + if (!document.getElementById("writer-plan-detect")) log("snap:fail no Detect again"); + document.getElementById("writer-plan-confirm").click(); + await wait(300); + if (state() !== "Plan: Max, confirmed.") log("snap:fail Confirm did not turn the row to confirmed: " + state()); + if (document.getElementById("writer-plan-confirm")) log("snap:fail Confirm stays after it was pressed");`); +/** The plan row confirmed: no Confirm; Detect again shows what it found, and Change picks another plan. */ +export const writersPlanConfirmed = () => + writersOpen({ + writers: { writers: [claudeWriter, agyWriter], summaries_on: true, briefs: true, keys: [], base_url: null, key_store: "the macOS Keychain" }, + settings_files: { settings: '{ "plan": { "kind": "pro", "confirmed": true } }', keymap: null }, + detect_plan: { plan: { kind: "pro", confirmed: true }, line: "/usage says the Pro plan; your confirmed plan is kept.", settings: null }, + }, ` + if (document.getElementById("writer-plan-state")?.textContent !== "Plan: Pro, confirmed.") return log("snap:fail the plan row says " + document.getElementById("writer-plan-state")?.textContent); + if (document.getElementById("writer-plan-confirm")) log("snap:fail Confirm shown for a confirmed plan"); + document.getElementById("writer-plan-detect").click(); + await wait(300); + if (!document.getElementById("writer-plan-said")?.textContent.includes("/usage says the Pro plan")) log("snap:fail Detect again's line is not shown: " + document.getElementById("writer-plan-said")?.textContent);`); diff --git a/scripts/snap/fixtures.ts b/scripts/snap/fixtures.ts index d545c017..fa4a63a5 100644 --- a/scripts/snap/fixtures.ts +++ b/scripts/snap/fixtures.ts @@ -13,7 +13,7 @@ import { readmeBriefFixtures } from "./fixtures-readme-brief.ts"; import { mapFootprint, mapLatePlace, mapPanelBrief, mapPanelDiff, mapNotPlacedHint, mapPanelFieldHints, mapPanelFocus, mapPanelHead, mapPanelHistory, mapPanelLine2, mapPanelNoSession, mapPanelPeel, mapPanelMenuEsc, mapPanelChangeEsc, mapPanelLightDismiss, mapListFold, mapPanelSettings, mapPanelStory, mapPanelToggle, mapSheetClose, mapSheetExplained, mapSheetHere, mapSheetHolds, mapSheetKeptWidth, mapSheetResizeRedraw, mapSheetScrollShort, mapSheetStill, mapSheetUnratified, mapSheetWidth, mapToastBeside, mapTurnLight, mapPanelPatched, mapPanelAskStays, mapPanelBriefFoot, mapPrPanel, mapPrPanelPlaying, mapPrPanelRatify, mapPrPanelRewriting, mapPrPanelWriting, panelCaughtUp, panelExpanded, panelNeedsYou, panelFirstOpen, panelNoTrees, panelReplay, panelRunning, panelWhy, panelYourTurn } from "./fixtures-panel.ts"; import { mapBackLaw, mapMicroWorld, mapMicroWorldBuilding, mapPreFlight, mapPreFlightOutside, mapPreFlightOutsideKept, mapPreFlightPalette, mapPreFlightPick, mapPreFlightStatus, mapRuns, mapRunsAnnounced, mapRunsBesideSheet, mapRunsCost, mapRunsPaused, mapRunsTotal, mapTray, mapTrayAfterPush, mapPreFlightIssuesFailed } from "./fixtures-runs.ts"; import { mapBriefAlsoGroups, mapBriefAnnounce, mapBriefBar, mapBriefBold, mapBriefBoldUnpaired, mapBriefChapterLast, mapBriefChapterMid, mapBriefChapters, mapBriefCopied, mapBriefCopyByHand, mapBriefExplainBack, mapBriefExplained, mapBriefFigure, mapBriefGuard, mapBriefHeights, mapBriefMapCheck, mapBriefNoFacts, mapBriefReview, mapBriefStillTrue, mapBriefNoStaleBase, mapBriefOrderRight, mapBriefOrderSlots, mapBriefOrderWrong, mapBriefOverturn, mapBriefPartialFacts, mapBriefPick, mapBriefRatify, mapBriefRatifyDetail, mapBriefRatifyEvidence, mapBriefShort, mapBriefSince, mapBriefStaleBase, mapBriefStart, mapBriefStepCode, mapBriefStory, mapBriefTall, mapBriefTaller, mapBriefTallScroll, mapBriefUnconfirmed, mapBriefWhy, mapBriefWhyDecision, mapBriefWriting, mapCatchUp, mapCatchUpBold, mapCatchUpCard, mapCatchUpStage, mapCatchUpSummarising, mapCatchUpWriting, mapDiffClosed, mapDiffLitGhost, mapDiffRatifyLit, mapDiffRemoval, mapDiffRemovalBrief, mapDiffSplit, mapDiffSplitBrief, listBriefMark, railBriefReady } from "./fixtures-brief.ts"; -import { writersBriefsNeedClaude, writersFailed, writersKeyError, writersTestUnrun, writersUnread, writersKeyNotSet, writersKeySet, writersList, writersOpenAI, writersPassed, writersSecretService } from "./fixtures-writers.ts"; +import { writersBriefsNeedClaude, writersFailed, writersKeyError, writersTestUnrun, writersUnread, writersKeyNotSet, writersKeySet, writersList, writersOpenAI, writersPassed, writersPlanConfirmed, writersPlanDetected, writersSecretService } from "./fixtures-writers.ts"; export const fixtures = { ...railFixtures, @@ -76,6 +76,8 @@ export const fixtures = { writersSecretService, writersUnread, writersTestUnrun, + writersPlanDetected, + writersPlanConfirmed, listUnread, listUnreadHealed, listEmpty, diff --git a/ui/main.ts b/ui/main.ts index 74cf3365..846a81e4 100644 --- a/ui/main.ts +++ b/ui/main.ts @@ -448,6 +448,7 @@ window.addEventListener("focus", checkWired); startWriters({ summaries: () => studio.files.settings.summaries, openFilesIn: () => studio.files.settings.openFilesIn, + plan: () => studio.files.settings.plan, texts: () => studio.texts, saved: (settings) => applySettings({ settings, keymap: studio.texts.keymap }), gate: (gated) => editNotice((text) => withGateNotice(text, gated)), diff --git a/ui/style.css b/ui/style.css index a517095a..bd40ae0a 100644 --- a/ui/style.css +++ b/ui/style.css @@ -107,6 +107,7 @@ body[data-layout="focus"] .list { visibility: hidden; } .writers .writer-test { align-self: flex-start; } .writer-key { display: flex; gap: var(--sp-3); } .writer-key input { flex: 1; min-width: 0; font-size: var(--size-small); } +.writer-key select { font-size: var(--size-small); } .switchboard { margin-top: var(--sp-6); } .switchboard-said { align-self: center; font-size: var(--size-small); color: var(--muted); } .switchboard-title { margin: 0; font-size: var(--size-small); font-weight: 500; } diff --git a/ui/tests/writers.test.mjs b/ui/tests/writers.test.mjs index 0f69181a..410dda82 100644 --- a/ui/tests/writers.test.mjs +++ b/ui/tests/writers.test.mjs @@ -3,7 +3,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; import { fakeDocument, Field, tauri } from "./dom.mjs"; -import { briefsLine, choiceOptions, keyLine, keySet, preset, testLine } from "../../dist/writers.js"; +import { planLine, briefsLine, choiceOptions, keyLine, keySet, preset, testLine } from "../../dist/writers.js"; const claude = (found) => ({ kind: "claude", name: "Claude", found, models: ["haiku", "sonnet", "opus", "fable"], efforts: ["", "low", "medium", "high"] }); const agy = (found) => ({ kind: "agy", name: "agy", found, models: ["gemini-4-neon-low", "gemini-4-neon-high"], efforts: [] }); @@ -147,7 +147,7 @@ async function section(reply) { /** @type {import("../../dist/types.js").WriterKind} */ const kind = "claude"; const settings = { model: "haiku", effort: "", on_open: false, writer: kind }; - startWriters({ summaries: () => settings, gate() {}, saved() {}, openFilesIn: () => "auto", texts: () => ({ settings: "{}", keymap: null }) }); + startWriters({ summaries: () => settings, gate() {}, plan: () => ({ kind: "unknown", confirmed: false }), saved() {}, openFilesIn: () => "auto", texts: () => ({ settings: "{}", keymap: null }) }); const box = new Field("div"); writersIn(box); return { box, calls, confirm: () => form.onsubmit({ submitter: { value: "confirm" } }), dialog }; @@ -197,3 +197,14 @@ for (const [name, why, down] of unrun) { assert.match(under(box, "p", "writer-key-error")?.text ?? "", new RegExp(`could not be removed.*${why}`)); }); } + +test("the plan row says the plan, and that it is detected until confirmed", () => { + const rows = [ + [{ kind: "max", confirmed: false }, "Plan: Max, detected, not confirmed."], + [{ kind: "max", confirmed: true }, "Plan: Max, confirmed."], + [{ kind: "api", confirmed: true }, "Plan: API key, confirmed."], + [{ kind: "unknown", confirmed: false }, "Plan: not known, not confirmed."], + [{ kind: "unknown", confirmed: true }, "Plan: not known, confirmed."], + ]; + for (const [plan, line] of rows) assert.equal(planLine(plan), line); +}); diff --git a/ui/writers.ts b/ui/writers.ts index f9b36365..f71812dc 100644 --- a/ui/writers.ts +++ b/ui/writers.ts @@ -12,7 +12,7 @@ import { confirmed, drawWithStatus, failure, hint, invoke, messageOf, pressable, statusLine, text } from "./dom.js"; import { type SwitchboardHooks, switchboardSection } from "./switchboard.js"; import type { Settings } from "./settings.js"; -import type { Writers, WriterKind, WriterTest } from "./types.js"; +import type { Plan, Writers, WriterKind, WriterTest } from "./types.js"; export type Choice = { writer: WriterKind; model: string; effort: string }; @@ -64,6 +64,12 @@ export function preset(list: Writers, now: Settings["summaries"]): Choice { export const testLine = (test: WriterTest): { passed: boolean; text: string } => test.outcome === "passed" ? { passed: true, text: test.line } : { passed: false, text: `Failed: ${test.line}` }; +const planNames: Record = { pro: "Pro", max: "Max", ultra: "Ultra", api: "API key", unknown: "not known" }; +const planPicks: Plan["kind"][] = ["pro", "max", "ultra", "api", "unknown"]; + +/** The plan row's line: the plan, and whether detection named it or Daniel confirmed it (spec #1056, "The plan"). */ +export const planLine = (plan: Plan): string => `Plan: ${planNames[plan.kind]}, ${plan.confirmed ? "confirmed" : `${plan.kind === "unknown" ? "" : "detected, "}not confirmed`}.`; + export const briefsLine = (list: Writers): string | null => list.briefs ? null : "PR briefs need Claude: they are written by `claude`, which was not found, whatever writer is picked here. Install Claude Code and restart plotkeeper."; @@ -74,6 +80,9 @@ let outcome: WriterTest | null = null; let testing = false; // Whether the first read of the list failed: the section then says so, with Try again, in place of its rows. let unread = false; +// The plan row's last words: what Detect again found, or why a press failed. +let planSaid = ""; +let planFailed = false; // Each key row's last refusal, such as a pasted text that is no key. const keyErrors: Partial> = {}; @@ -108,6 +117,8 @@ export type Hooks = SwitchboardHooks & { summaries: () => Settings["summaries"]; // The gate in the writer's notice line, shown or cleared; clearing it keeps a writer's failure notice. gate: (gated: boolean) => void; + // The plan in `settings.json`, which run costs are figured on (spec #1056). + plan: () => Plan; }; function draw(panel: HTMLElement, hooks: Hooks) { @@ -158,7 +169,7 @@ function draw(panel: HTMLElement, hooks: Hooks) { } else if (!known.summaries_on) { nodes.push(text("p", "Summaries are off until a writer passes Test.", "writer-outcome")); } - nodes.push(...keyRow(panel, hooks, known), ...openaiRow(panel, hooks, known)); + nodes.push(...keyRow(panel, hooks, known), ...openaiRow(panel, hooks, known), ...planRow(panel, hooks)); const briefs = briefsLine(known); if (briefs) { const shown = text("p", briefs, "writer-briefs"); @@ -166,7 +177,7 @@ function draw(panel: HTMLElement, hooks: Hooks) { nodes.push(shown); } // The Test's outcome and the keys' errors are said in the section's one status region (#456, #452's review). - const said = [outcome ? testLine(outcome).text : "", keyErrors.anthropic ?? "", keyErrors.openai ?? ""].filter(Boolean).join(" "); + const said = [outcome ? testLine(outcome).text : "", keyErrors.anthropic ?? "", keyErrors.openai ?? "", planSaid].filter(Boolean).join(" "); drawWithStatus(panel, nodes, said); } @@ -223,6 +234,57 @@ function keyRow(panel: HTMLElement, hooks: Hooks, known: Writers): HTMLElement[] return nodes; } +// The plan row (spec #1056, ticket #1064): the plan, marked detected until confirmed, with Confirm, Change and Detect again. A reply that +// changed the settings applies as a passed Test's save does. +function planRow(panel: HTMLElement, hooks: Hooks): HTMLElement[] { + const plan = hooks.plan(); + const done = (said: string, failed: boolean, settings: string | null) => { + if (settings !== null) hooks.saved(settings); + planSaid = said; + planFailed = failed; + draw(panel, hooks); + }; + const set = (kind: Plan["kind"]) => + invoke("set_plan", { kind, expected: hooks.texts().settings }) + .then((settings) => done("", false, settings)) + .catch((e: unknown) => { + done(`The plan could not be saved: ${messageOf(e)}`, true, null); + failure("set_plan")(e); + }); + const state = text("p", planLine(plan), "writer-hint"); + state.id = "writer-plan-state"; + const pick = select("writer-plan-pick", "Change the plan the run costs are figured on", + planPicks.map((kind) => ({ value: kind, label: planNames[kind] })), plan.kind, (value) => void set(value as Plan["kind"])); + pick.setAttribute("aria-label", "Change plan"); + const detect = pressable(text("button", "Detect again", "btn small"), null); + detect.id = "writer-plan-detect"; + hint(detect, "Ask Claude Code for the plan it is on, and show what it says"); + detect.addEventListener("click", () => { + invoke("detect_plan") + .then((found) => done(found.line, false, found.settings)) + .catch((e: unknown) => { + done(`The plan could not be detected: ${messageOf(e)}`, true, null); + failure("detect_plan")(e); + }); + }); + const row = text("div", "", "writer-key"); + if (!plan.confirmed) { + const confirm = pressable(text("button", "Confirm", "btn small"), null); + confirm.id = "writer-plan-confirm"; + hint(confirm, "Keep this plan; detection then no longer changes it"); + confirm.addEventListener("click", () => void set(plan.kind)); + row.append(confirm); + } + row.append(pick, detect); + const nodes = [state, row]; + if (planSaid) { + const shown = text("p", planSaid, `writer-outcome${planFailed ? " failed" : ""}`); + shown.id = "writer-plan-said"; + nodes.push(shown); + } + return nodes; +} + // A key's error, tied to the `fields` it is about (#456); the section's status region says it. function keyError(words: string, id: string, fields: HTMLElement[]): HTMLElement { const shown = text("p", words, "writer-outcome failed"); From 7aa4ddf78dbcdc0fd8fa1b0a1327edd9c9896fc9 Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 14:25:08 +0200 Subject: [PATCH 8/9] Studio: type the plan row test's cases (#1064) Co-Authored-By: Claude Opus 5.5 --- ui/tests/writers.test.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/ui/tests/writers.test.mjs b/ui/tests/writers.test.mjs index 410dda82..429a900c 100644 --- a/ui/tests/writers.test.mjs +++ b/ui/tests/writers.test.mjs @@ -199,6 +199,7 @@ for (const [name, why, down] of unrun) { } test("the plan row says the plan, and that it is detected until confirmed", () => { + /** @type {[import("../../dist/types.js").Plan, string][]} */ const rows = [ [{ kind: "max", confirmed: false }, "Plan: Max, detected, not confirmed."], [{ kind: "max", confirmed: true }, "Plan: Max, confirmed."], From 4656158af8e9bdb9d732335203bb4703d01640ac Mon Sep 17 00:00:00 2001 From: Daniel Rispler Date: Wed, 2 Dec 2026 14:31:26 +0200 Subject: [PATCH 9/9] Studio: Run cost's docs and glossary (#1065) Co-Authored-By: Claude Opus 5.5 --- docs/studio/CONTEXT.md | 8 ++++++++ docs/studio/behaviour/background-runs.md | 18 +++++++++++++++++- docs/studio/behaviour/storage.md | 4 ++++ docs/studio/settings.md | 10 +++++++++- 4 files changed, 38 insertions(+), 2 deletions(-) diff --git a/docs/studio/CONTEXT.md b/docs/studio/CONTEXT.md index b2043cc7..f028bdf1 100644 --- a/docs/studio/CONTEXT.md +++ b/docs/studio/CONTEXT.md @@ -395,6 +395,10 @@ _Avoid_: Session, job, a check sent to the background (a check an agent backgrou The read-only **Background run** that checks the map text a PR added or changed (parts' names, purposes and captions, held items, link reasons and law texts) against the PR's code, and keeps a verdict per item. Its flags show on Ratify's rows and never block. Distinct from the **Claim check**, which checks a **PR brief** against its facts. _Avoid_: Map lint, map check (the check of ownership, imports and laws), fact check +**Run cost**: +What a **Background run** takes: its API price, and for a subscriber the share of the plan's 5-hour and weekly limits it is estimated to use. It shows twice: as an estimate before the click, a range ("about 1-3% of the 5-hour window") from the last 20 recorded runs of the kind, or from the calibration trial's figures while fewer than 3 are recorded; and as the actual cost after it, where the run's result shows and on its row in the Background runs list, with the last 7 days' total, all projects, on the list's head. An Ultra subscriber sees weekly shares only, an API-key user dollars, and a plan not known dollars labelled "API price". A share rests on a factor the trial measured on one plan, so it always says "about" and its hover names the date; the factor is no plan size, which Anthropic does not publish. It brings back one reading of the retired **Plan usage** (the subscription's two windows), for runs only: plotkeeper reads the plan's numbers to turn a run's price into a share, and shows no plan limit of its own. [Background runs](behaviour/background-runs.md#cost) has the rules. +_Avoid_: Estimate (a session's remaining-time range, only a run's cost before its click is an estimate of a cost), usage, quota + **Micro-world**: A small interactive page, built by a **Background run** from the project's real code, that lets Daniel play with one mechanism: a flow of a part's **Refresher**, or the parts a step of a **PR brief** lights. plotkeeper checks the page before keeping it and shows it walled off from everything else it serves. _Avoid_: Demo, simulation, explainer (an explainer is the dsh-visual page of a diff) @@ -440,6 +444,10 @@ _Avoid_: Edge (a computed edge) **Link kind**: What joins a link's ends: `import`, a code dependency the extractors can prove, or one of the run-time kinds no extractor sees, `http`, `spawn` and `file`. +**Run-time link**: +A **link** of a kind no extractor sees: `http`, `spawn` or `file`. Each carries a reason, which `import` links do not. Drafting new ones is a later spec's (danielrispler/plotkeeper#935). +_Avoid_: Link reason (the text a run-time link carries), dynamic link + **Read part**: A part at least one of whose files a named extractor reads. The link check compares links with computed edges only between read parts. diff --git a/docs/studio/behaviour/background-runs.md b/docs/studio/behaviour/background-runs.md index d7b55e2e..21d41ff0 100644 --- a/docs/studio/behaviour/background-runs.md +++ b/docs/studio/behaviour/background-runs.md @@ -103,7 +103,23 @@ A **batch** is several runs asked for as one request (`Runner::submit_batch`), s A run ends as one of: finished; finished with tool calls denied; failed; stopped at its limit; died; setup failed; not logged in; rate limited. A run that exits 0 with denials in its result is reported with them, never as a clean success. A result that says it is an error, by `is_error` or by a `subtype` such as `error_max_turns`, is a failure whatever the exit code, and so is a run whose result or error output shows the sandbox failing (`sandbox_apply: Operation not permitted` or `Sandbox is required but`). A result that only names the settings does not match. Only a failed run's words are read for a login or a limit, with the writer's own word list, so a good result that mentions a rate limit pauses nothing; a failed run that only mentions one does pause, which costs one Resume. -Each run appends one line to `background-runs.jsonl` in the data folder: the time, its id, kind, project, outcome, denials, cost and duration. A cancelled run is recorded as `cancelled`. +Each run appends one line to `background-runs.jsonl` in the data folder: the time, its id, kind, project, outcome, denials, cost and duration, and three optional fields (spec #1056, #1060), left out when a run has none, so a line from before them still reads: + +- `units`: the parts a First map writer or reviewer group covered; no other kind has it. A First map line with no `units` gives no per-part figure. +- `model`: the model that cost the most in the result's `modelUsage`. +- `subject`: the key of the view that keeps the run's answer, so the view finds its runs' cost after the run is dismissed: a First map draft's id (its redrafts and retries use it too), a review's `@`, a law's id, a micro-world's `@`. + +A cancelled run is recorded as `cancelled`. + +## Cost + +Every run has a **run cost** (spec #1056): an estimate before the click and an actual figure after. The server works the figures out from `background-runs.jsonl` and `settings.json`'s `plan` (`server/src/run_cost.rs`) and sends them with the views; the page only puts words round them (`ui/run-cost.ts`), in the time hint's style where the button has one. A figure is in the plan's unit: for Pro and Max, shares of the 5-hour window and of the week ("about 1-3% of the 5-hour window, under 1% of the week"); for Ultra, the week alone; for an API key, dollars; for a plan not known (nothing detected and none picked, or Don't know), dollars labelled "API price". A share under 1% says "under 1%", never "0%". A share carries "about", and its hover says it is the run's API price turned into the plan's share by a factor measured on a date; dollars say the price is as `claude` recorded it. How the plan is known is in [Settings](../settings.md). + +**The estimate.** Beside every button that starts a run: Draft the map, its failed group's Retry, Back a law and Back this law, Guard with a law's Start the run, Explore this, a micro-world's Rebuild and Try again, and Review map text and Run again. It is a range, the 25th to the 75th percentile of the cost per unit of the last 20 recorded runs of the kind that have a cost, all projects, times the units. For First map the unit is a part and the units are the skeleton's (a group's, for its Retry), so a larger repository shows more, and the estimate includes the reviewers and the redrafts the draft starts on its own; for every other kind the unit is a run. With fewer than 3 such records, the estimate comes from the calibration trial's figures (`run_cost.rs`, from [`research/run-cost.md`](../research/run-cost.md)), so the first click is never blind. + +**The actual cost.** A run's recorded cost, in the plan's unit, with the same factor; a run that recorded none (cancelled before it answered, died) shows none, never zero. Map text review and First map runs are dismissed as soon as their answers are kept, so their cost shows on the view that keeps the answer, found by `subject`: the Map draft panel's line once the draft is ready (the sum over the draft's runs), the review's line in Ratify, Back a law's patch review and a micro-world's row. Every ended run still listed shows its cost on its row. + +**The total.** The Background runs list's head shows "Last 7 days, all projects:" and the sum of every recorded cost of the last 7 days, all kinds and projects, dismissed runs included, since they spent. It shows even when no run is listed, as long as the total is not zero. ## Fallback diff --git a/docs/studio/behaviour/storage.md b/docs/studio/behaviour/storage.md index 820b2258..ce1be993 100644 --- a/docs/studio/behaviour/storage.md +++ b/docs/studio/behaviour/storage.md @@ -42,6 +42,10 @@ The app also keeps `roots.json` beside the log: the git worktree root of each fo The desktop app ran the sessions it started with `workbench/statusline.sh` as their status line, which saved Claude Code's status line stdin, with the plan's usage and the context window's size, as `usage/.json` beside the event log, mode 0600 in a folder of mode 0700. Sessions are started by hand now, so none saves one, and plotkeeper reads none (#416); the scripts and their reader are in `archive/workbench/`. Old snapshots stay in `usage/` until you remove the folder. +## The status line saves the plan's numbers + +`plotkeeper statusline` (spec #1056, ticket #1061) saves four numbers from Claude Code's status-line JSON, in `plan-limits.json` in the data folder: the 5-hour and the weekly window's `used_percentage` and `resets_at`, from `rate_limits`. A window the JSON lacks is left out. It writes beside the file and renames over it, replacing the file on each call that has a window, and a call with neither (an API key's, or a subscriber's session before its first answer) leaves the file as it was. Nothing else of the JSON is saved: no session id, no cost, no context size, which the retired snapshots above held (this reverses part of #416 for those four numbers only). A failed write is let go and the status line still prints its link; a data folder plotkeeper never made is left unmade. [Plan detection](../settings.md) reads the file, which is useful for 60 seconds after it is written. + ## The card store `cards-v2.json` beside the event log holds the cards written before cards were retired (danielrispler/plotkeeper#348). No build writes one now, and the file still loads, with each card's change (`request.change`), its base, its prompt, its worker, its `summary` and `architecture`, and its record: your guess, flags, rating, taps, the check's result and the longer explanation you asked for. A store from before quizzes (danielrispler/Falinks#375) loads with no quiz, one from before briefs (danielrispler/Falinks#377) with no summary and no prompt, and a card stored without `request.change` with none. Nothing shows these cards; the studio reads them for the session's row line and for "Design so far", which may cite one. A missing store starts empty. diff --git a/docs/studio/settings.md b/docs/studio/settings.md index 9ff86649..a041cd6b 100644 --- a/docs/studio/settings.md +++ b/docs/studio/settings.md @@ -58,13 +58,21 @@ An older file's `zoom`, `terminal`, `sounds`, `doctor`, `editor` and `repository **`openFilesIn`** (spec #873, ticket #882) is read by the server from the file at each Open in editor. `auto` takes the first of Zed, Cursor, VS Code and a JetBrains IDE (IntelliJ IDEA, PyCharm, WebStorm, GoLand, RustRover, CLion, PhpStorm, Rider, RubyMine, DataGrip, DataSpell: the IDEs a session's terminal can be in) that is running (in the process list, `ps`) and whose command-line tool can run; else the first whose tool can run; else the URL scheme of the first installed as an app (`zed://`, `cursor://`, `vscode://`, through `open`); else "No editor found: choose one in Settings, Open files in". On macOS a tool can run when it is in its app bundle, in `/Applications` or `~/Applications` (Zed's `Contents/MacOS/cli`, Cursor's and VS Code's `Contents/Resources/app/bin/cursor` and `code`, a JetBrains IDE's launcher in `Contents/MacOS/`), or on `PATH` (`zed`, `cursor`, `code`, `idea`, …), the bundle first, since a shell alias on `PATH` is not a file. On Linux only the tools on `PATH` count, a running editor is found by its process name, and an installed app by its desktop file (`dev.zed.Zed.desktop`, `cursor.desktop`, `code.desktop`), opened through `xdg-open`. A forced editor is used alone, with the same fallback to its URL scheme, and says " wasn't found: choose another in Settings, Open files in" when it has neither. The tool gets the file and its line: Zed `:`, VS Code and Cursor `-g :`, a JetBrains IDE `--line `, and starts detached, so plotkeeper never waits on the editor. +**The plan row** (spec #1056, tickets #1061 and #1064). Under the OpenAI row, it names the plan [run costs](behaviour/background-runs.md#cost) are figured on: "Plan: Max, detected, not confirmed." or "Plan: Pro, confirmed.", and "Plan: not known, not confirmed." when nothing is known. The plan is `settings.json`'s `plan`, `{ "kind": "pro" | "max" | "ultra" | "api" | "unknown", "confirmed": bool }`; unset it reads as unknown and not confirmed, and costs show as dollars labelled "API price". Until it is confirmed every share says it is detected, not confirmed. The row has three controls: + +- **Confirm**, shown while the plan is not confirmed: keeps the detected plan with `confirmed: true`. +- **Change**, a select of Pro, Max, Ultra, API key and not known: writes the pick with `confirmed: true`. A pick wins over detection until it is changed. +- **Detect again**: one reading now, and a line saying what it found ("Found an API key.", "Found Ultra: weekly limits, no 5-hour window.", "Found a subscription; Max is guessed from your runs.", "/usage named no plan limits."). It does nothing to a confirmed plan. + +Detection writes the plan with `confirmed: false`, never over a confirmed one, and (`server/src/plan.rs`) only while the plan is still unset: once it has detected one, only Detect again reads again. It reads the status line's numbers when the status line saved a 5-hour window within the last minute (see below), which costs nothing, else sends `/usage` through `claude -p` (no model tokens). No `rate_limits` is an API key, weekly rows with no session row are Ultra, and a session row is a subscription. Nothing names Pro or Max, so while the plan is unset detection reads right before and right after a run Daniel started (at most one such pair at a time and one every 10 minutes), and guesses Max or Pro from the first three pairs: the runs' API price over the points the 5-hour window moved, against the trial's factor. Another session spending at the same time skews it, so the guess is never shown as confirmed. Nothing reads on a timer or when the page opens, so opening the page still spends nothing. + ## The Switchboard section Under the writer section (spec #873, ticket #884), the Switchboard section has two parts. **Open files in.** A select: Automatic, Zed, Cursor, VS Code or JetBrains IDE. Choosing one asks the server's `set_open_files_in`, which saves `openFilesIn` (see above); the select shows the saved value, and follows a save made elsewhere. -**Claude Code status line.** The section shows the snippet `"statusLine": { "type": "command", "command": "plotkeeper statusline" }` with a Copy button. Paste it into Claude Code's `settings.json` yourself: plotkeeper never opens Claude Code's settings (law `install-never-opens-claude-settings`), and `plotkeeper install` does not add it. It is for Claude Code only, and it replaces a status line you already have; to keep yours, call both from one script. `plotkeeper statusline` reads the status-line JSON Claude Code sends on stdin and prints one link, labelled "plotkeeper" (an OSC 8 hyperlink), to `http://127.0.0.1:/#session=`, which opens the page on that session. The port is the running plotkeeper's, from `plotkeeper.running.json` in the data folder, else 47800; it makes no network call. A `session_id` that is missing or holds anything but letters, digits, `-` and `_` leaves the link on the page alone. +**Claude Code status line.** The section shows the snippet `"statusLine": { "type": "command", "command": "plotkeeper statusline" }` with a Copy button. Paste it into Claude Code's `settings.json` yourself: plotkeeper never opens Claude Code's settings (law `install-never-opens-claude-settings`), and `plotkeeper install` does not add it. It is for Claude Code only, and it replaces a status line you already have; to keep yours, call both from one script. `plotkeeper statusline` reads the status-line JSON Claude Code sends on stdin and prints one link, labelled "plotkeeper" (an OSC 8 hyperlink), to `http://127.0.0.1:/#session=`, which opens the page on that session. The port is the running plotkeeper's, from `plotkeeper.running.json` in the data folder, else 47800; it makes no network call. A `session_id` that is missing or holds anything but letters, digits, `-` and `_` leaves the link on the page alone. For a subscriber it also saves the plan's four numbers for plan detection (the plan row, above): the 5-hour and weekly windows' `used_percentage` and `resets_at`, from the JSON's `rate_limits` (see [Storage](behaviour/storage.md#the-status-line-saves-the-plans-numbers)). `keymap.json` is Zed's array of contexts: `Workspace` for the page and `List` for the session list while it has focus.