From 077afeea2f7500f091dfc8e237a2401c4d503c8c Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Thu, 29 Oct 2026 22:01:34 -0400 Subject: [PATCH 1/3] =?UTF-8?q?=E2=9C=A8=20dashboard:=20running-cost=20til?= =?UTF-8?q?e=20rotates=20hour=20/=20today=20/=20week=20/=20month?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Overview RUNNING tile now rotates its cost window every ~4s (this hour → today → this week → this month) with a quiet vertical crossfade of only the amount+window phrase. Agent count stays fixed, width is reserved for the widest phrase (nowrap + ellipsis fallback), prefers-reduced-motion swaps instantly, rotation pauses on hover or while the tab is hidden and resumes in step, and the tooltip lists all four values. Server side, /api/status.fleetRun gains dayUSD / weekUSD / monthUSD / windowsPriced, aggregated from the existing cost ledger (UTC day, ISO week, calendar month) plus the live tail since the last snapshot. Fixes #15614 Signed-off-by: Andrew Anderson --- changelog.d/added-15614-running-cost-rotor.md | 1 + .../api-reference/health-status-events.md | 2 +- src/docs/dashboard-sections.md | 2 +- src/pkg/dashboard/fleet_cost_rotor.test.js | 165 ++++++++++++++++++ src/pkg/dashboard/fleet_cost_windows.go | 101 +++++++++++ src/pkg/dashboard/fleet_cost_windows_test.go | 85 +++++++++ src/pkg/dashboard/run_meter.go | 23 ++- src/pkg/dashboard/server.go | 1 + src/pkg/dashboard/static-src/css/governor.css | 14 ++ src/pkg/dashboard/static-src/js/agent-now.js | 76 +++++++- src/pkg/dashboard/static/index.html | 90 +++++++++- .../webstatic/fleet_run_stat_test.go | 2 +- 12 files changed, 550 insertions(+), 12 deletions(-) create mode 100644 changelog.d/added-15614-running-cost-rotor.md create mode 100644 src/pkg/dashboard/fleet_cost_rotor.test.js create mode 100644 src/pkg/dashboard/fleet_cost_windows.go create mode 100644 src/pkg/dashboard/fleet_cost_windows_test.go diff --git a/changelog.d/added-15614-running-cost-rotor.md b/changelog.d/added-15614-running-cost-rotor.md new file mode 100644 index 0000000000..3ebf47ef8a --- /dev/null +++ b/changelog.d/added-15614-running-cost-rotor.md @@ -0,0 +1 @@ +- The dashboard's RUNNING tile now rotates its fleet spend through `$X this hour` → `$Y today` → `$Z this week` → `$W this month` (~4 s each, a quiet vertical crossfade of just the amount and window, agent count fixed, width reserved so the tile never wraps; pauses on hover and while the tab is hidden, instant under reduced motion, hover lists all four), and `/api/status.fleetRun` gains `dayUSD`, `weekUSD`, `monthUSD`, `windowsPriced` summed from the cost ledger over the UTC day, ISO week and calendar month (#15614). diff --git a/src/docs/api-reference/health-status-events.md b/src/docs/api-reference/health-status-events.md index 434f07f22b..1862db1c57 100644 --- a/src/docs/api-reference/health-status-events.md +++ b/src/docs/api-reference/health-status-events.md @@ -12,7 +12,7 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `GET` | `/api/health/deep` | Public | Deep health probe | `pkg/dashboard/server.go:1607` | | `GET` | `/api/livez` | Public | Kubernetes liveness probe | `pkg/dashboard/server.go:1608` | | `GET` | `/metrics` | Registered only when `HIVE_METRICS_ENABLED`; requires `Authorization: ****** (403 if the token is unset) | Prometheus metrics | `pkg/dashboard/server.go:1614` | -| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced}` is the governor strip's `running N · $X this hour` figure; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1619` | +| `GET` | `/api/status` | Dashboard auth/session | Dashboard aggregate status; `labelPresets[]` (`{key,label,description,labels[],states[]}`) lists the built-in label-filter presets for the Projects cards, led by `needs-human` whose `labels[]` are the effective hard-suppress labels plus `needs-signal`, the hold labels, `stage/071-needs-author` and the reporter-trust awaiting label (#12172); accepts `?fields=a,b` for top-level selection and `?omit=repos` to drop heavy sections, and honors `Accept-Encoding: gzip`; `agents[]` includes busy-pane visibility fields (`kicksUndeliverable`, `busySince`, `lastTranscriptActivity`, `condition`, `conditionMessage`) when a Working pane cannot accept kicks; a working agent also carries `agents[].run` — the live per-run line (#14576): `{since, elapsedS, costUSD, tokens, priced, tests, filesChanged}`, the estimated spend/tokens since the kick was delivered (`lastKickAt`, falling back to `busySince`) (delta of the token collector's per-agent cumulative figure; `priced:false` when the agent has none yet), the last visible test-runner result (`pass`/`fail`/empty) and the last `N files changed` git summary (`-1` when none) parsed from the captured pane; top-level `fleetRun` `{running, hourUSD, hourPriced, dayUSD, weekUSD, monthUSD, windowsPriced}` is the governor strip's rotating `running N · $X this hour / today / this week / this month` figure (#15614) — the hour is the rise since the top of the clock hour, the wider windows are the daily cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC plus the rise since the ledger's last snapshot, `windowsPriced:false` when there is no ledger yet; `sla` (fleet) and `repos[].sla` (per repo) carry the Delivery SLA block derived from the lifecycle timeline with no extra GitHub calls: `windows.{7d,30d}.{open_to_triage,triage_to_start,start_to_pr,pr_to_merge,open_to_merge}` as `{p50_h,p95_h,n}` (hours, nearest-rank), `history[]` of up to 30 daily buckets `{day,start_to_pr_p50,pr_to_merge_p50,open_to_merge_p50,n_started,n_pr,n_merged}` persisted under `/data/sla-history.json`, `stale_in_progress[]` (`{number,repo,started_at,age_h,agent}` — issues carrying `hive/in-progress` longer than the agent claim TTL with no linked PR), `stale_count`, `merged_7d`, `claim_ttl_s` and, on the fleet block, the effective `targets` (`start_to_pr_h`, `pr_to_merge_h`, `open_to_merge_h`); `staleSince` and `repos[].countsStale` / `countsStaleSince` mark totals served from last-good figures — the previous enumeration (#13382) or the ForgeState cache's last-good counts (#13376); `ci_failure_signals` `{count, last, kicks, unmatched}` is the webhook CI-failure signal store — distinct red (repo, head, check) signals retained, the most recent one `{repo, number, head_sha, check, conclusion, details_url, agent, at}`, webhook-triggered kicks/nudges since boot, and failure deliveries whose head matched no open PR; `hotspots` `{count, actionable, filed}` is the merge-hotspot advisor's one-line summary (files at/above the thresholds, those with a split recommendation, those with a modularize issue filed), absent when the advisor is not wired — details on `GET /api/hotspots`; `writeback.dedupe` `{enabled, dedupe_same_item, dedupe_burst, rate_capped, hourly_cap, burst_items, burst_window_s, same_item_ttl_s}` is the write-back gate's content layer — the effective `writeback.dedupe.*` settings and the last-hour counts of writes held as `duplicate`, `burst` and `rate-capped` (each also listed under `GET /api/writeback/suppressed`) | `pkg/dashboard/server.go:1619` | | `GET` | `/api/status/summary` | Dashboard auth/session | Compact agent/governor/budget status summary for pollers; honors `Accept-Encoding: gzip` | `pkg/dashboard/server.go:1620` | | `GET` | `/api/overview/issues.csv` | Dashboard auth/session | Cached Overview issue-band export as browser-compatible CSV; filters `band`, `repo`/`repos`, `stale`, and `held` are ANDed. | `pkg/dashboard/server.go:1621` | | `GET` | `/api/overview/issues.json` | Dashboard auth/session | Cached Overview issue-band export as typed JSON with `bands[]` metadata and row fields matching the CSV columns. | `pkg/dashboard/server.go:1622` | diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index f0cc5fe321..c31505cd27 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -108,7 +108,7 @@ How busy Hive thinks your projects are right now, and how often it wakes its wor - The Governor picks a mode by comparing the amount of actionable work with three thresholds. Actionable work is work Hive could do now, with nothing waiting on a person. - The **actionable issues** and **actionable PRs** tiles use the same count as the Overview's Actionable now tile. The two always agree. - The **hold** list names every held item. Held means someone parked it with a hold label. -- The compact strip at the top of the Agents view also shows **running** — how many workers are mid-round right now, and the estimated spend the whole fleet has accrued in the current clock hour (`3 · $1.20 this hour`). The hour figure is the rise in the cumulative estimate since the top of the hour; `$–` means the hive has not yet taken a reading this hour. +- The compact strip at the top of the Agents view and the Governor grid also show **running** — how many workers are mid-round right now, and the fleet's estimated spend, which rotates through four windows every ~4 seconds: `3 · $1.20 this hour` → `$9.80 today` → `$41 this week` → `$130 this month`. The worker count stays fixed; only the amount and window phrase crossfade, the tile reserves the width of its widest phrase so nothing shifts or wraps, the rotation pauses while you hover (the hover lists all four values) or while the tab is hidden, and it swaps instantly when your system asks for reduced motion. The hour figure is the rise in the cumulative estimate since the top of the hour; today / this week / this month are the cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st of the month 00:00 UTC, plus the rise since the ledger's last reading. `$–` means the hive has not yet taken a reading for that window. - The **cadence table** shows, for each worker, how often it runs in each mode. Continuous means it runs again as soon as it finishes. - The **budget** shows how much of the AI spending allowance for the current period has been used. - The **next kick** estimate follows the eval tick, which is longer while GitHub webhooks are trusted (`/api/status.webhooks.mode` reads `webhook`) and drops back to `governor.eval_interval_s` when they degrade (`polling`). How that decision is made is in [webhooks.md](webhooks.md#fallback-when-webhooks-degrade). diff --git a/src/pkg/dashboard/fleet_cost_rotor.test.js b/src/pkg/dashboard/fleet_cost_rotor.test.js new file mode 100644 index 0000000000..854cf85616 --- /dev/null +++ b/src/pkg/dashboard/fleet_cost_rotor.test.js @@ -0,0 +1,165 @@ +// The RUNNING tile's cost rotor (#15614): "$X this hour" → "$Y today" → +// "$Z this week" → "$W this month", ~4s each, pausing while hovered or +// hidden, instant under prefers-reduced-motion, never a second line. The +// rotor block is lifted straight out of index.html so this runs against the +// shipped source. +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); + +const html = fs.readFileSync(path.join(__dirname, 'static', 'index.html'), 'utf8'); + +function pick(re, what) { + const m = html.match(re); + assert.ok(m, what + ' not found in index.html'); + return m[0]; +} + +const rotorSrc = pick(/\/\/ --- fleet cost rotor \(begin\) ---[\s\S]*?\/\/ --- fleet cost rotor \(end\) ---/, 'fleet cost rotor block'); +const statSrc = pick(/function fleetRunStatHtml\(\) \{[\s\S]*?\n \}\n/, 'fleetRunStatHtml'); +const stripSrc = pick(/function fleetRunStripHtml\(\) \{[\s\S]*?\n \}\n/, 'fleetRunStripHtml'); + +// Minimal DOM stand-in: one rotor whose phrases are plain objects with a +// classList, plus a document with fake timers and a visibility flag. +function makeEnv({ reducedMotion = false } = {}) { + const timers = []; + let now = 0; + const phrases = []; + const makePhrase = (key, cur) => { + const cls = new Set(cur ? ['fcr-phrase', 'is-cur'] : ['fcr-phrase']); + const attrs = cur ? {} : { 'aria-hidden': 'true' }; + return { + key, + classList: { + toggle(c, on) { if (on) cls.add(c); else cls.delete(c); }, + contains: c => cls.has(c), + }, + setAttribute(k, v) { attrs[k] = v; }, + removeAttribute(k) { delete attrs[k]; }, + attrs, + }; + }; + const rotor = { querySelectorAll: sel => { assert.strictEqual(sel, '.fcr-phrase'); return phrases; } }; + const listeners = {}; + const document = { + hidden: false, + querySelectorAll: sel => { assert.strictEqual(sel, '[data-fleet-cost-rotor]'); return [rotor]; }, + addEventListener: (ev, fn) => { listeners[ev] = fn; }, + }; + const window = { + _lastStatus: { fleetRun: { running: 3, hourUSD: 53.91, hourPriced: true, dayUSD: 120.5, weekUSD: 410, monthUSD: 1234.56, windowsPriced: true } }, + matchMedia: q => ({ matches: reducedMotion && q === '(prefers-reduced-motion: reduce)' }), + }; + const setInterval = (fn, ms) => { const t = { fn, ms, next: now + ms }; timers.push(t); return t; }; + const advance = ms => { + const until = now + ms; + for (;;) { + const due = timers.filter(t => t.next <= until).sort((a, b) => a.next - b.next)[0]; + if (!due) break; + now = due.next; due.next += due.ms; due.fn(); + } + now = until; + }; + const fmtUSD = n => '$' + Number(n).toFixed(2); + const esc = s => String(s).replace(/&/g, '&').replace(/ m[1]); + keys.forEach((k, i) => phrases.push(makePhrase(k, i === api._fleetCost.idx))); + const current = () => phrases.filter(p => p.classList.contains('is-cur')).map(p => p.key); + const outgoing = () => phrases.filter(p => p.classList.contains('is-out')).map(p => p.key); + return { api, rendered, phrases, document, window, listeners, timers, advance, current, outgoing }; +} + +test('rotates hour → today → week → month → hour with a ~4s dwell', () => { + const env = makeEnv(); + assert.strictEqual(env.api.FLEET_COST_DWELL_MS, 4000); + assert.strictEqual(env.timers.length, 1, 'one interval timer, started on first render'); + assert.deepStrictEqual(env.current(), ['hour']); + env.advance(3999); + assert.deepStrictEqual(env.current(), ['hour'], 'no change before the dwell elapses'); + env.advance(1); + assert.deepStrictEqual(env.current(), ['day']); + assert.deepStrictEqual(env.outgoing(), ['hour'], 'outgoing phrase slides out'); + env.advance(4000); + assert.deepStrictEqual(env.current(), ['week']); + env.advance(4000); + assert.deepStrictEqual(env.current(), ['month']); + env.advance(4000); + assert.deepStrictEqual(env.current(), ['hour'], 'wraps around'); + assert.deepStrictEqual(env.outgoing(), ['month']); + // Exactly one phrase is exposed to assistive tech at any time. + assert.strictEqual(env.phrases.filter(p => !p.attrs['aria-hidden']).length, 1); +}); + +test('second render after a status poll keeps the current window', () => { + const env = makeEnv(); + env.advance(8000); + assert.deepStrictEqual(env.current(), ['week']); + const again = env.api.fleetRunStatHtml(); + assert.match(again, /class="fcr-phrase is-cur" data-fleet-cost-window="week"/); + assert.strictEqual(env.timers.length, 1, 'repaint does not start a second timer'); + // The strip twin shares the index. + assert.match(env.api.fleetRunStripHtml(), /class="fcr-phrase is-cur" data-fleet-cost-window="week"/); +}); + +test('pauses while hovered or hidden and resumes in step', () => { + const env = makeEnv(); + const host = { closest: sel => (sel === '[data-fleet-cost-host]' ? host : null) }; + const elsewhere = { closest: () => null }; + env.listeners.pointerover({ target: host }); + env.advance(12000); + assert.deepStrictEqual(env.current(), ['hour'], 'hover holds the phrase'); + env.listeners.pointerout({ relatedTarget: elsewhere }); + env.advance(4000); + assert.deepStrictEqual(env.current(), ['day'], 'one step after leaving, not three'); + env.document.hidden = true; + env.advance(8000); + assert.deepStrictEqual(env.current(), ['day'], 'hidden document holds the phrase'); + env.document.hidden = false; + env.advance(4000); + assert.deepStrictEqual(env.current(), ['week']); +}); + +test('prefers-reduced-motion swaps instantly with no outgoing phrase', () => { + const env = makeEnv({ reducedMotion: true }); + env.advance(4000); + assert.deepStrictEqual(env.current(), ['day']); + assert.deepStrictEqual(env.outgoing(), [], 'no slide-out class under reduced motion'); + assert.match(html, /@media \(prefers-reduced-motion: reduce\) \{\s*\.fleet-cost-rotor \.fcr-phrase \{ transition: none;/); +}); + +test('markup: fixed agent count, four phrases in one rotor, tooltip lists all four', () => { + const env = makeEnv(); + const r = env.rendered; + assert.match(r, /3 · <\/span>this hour today this week this month p.text); + assert.deepStrictEqual(unpriced, ['$1.00 this hour', '$– today', '$– this week', '$– this month']); +}); + +test('never a second line: nowrap + ellipsis on the tile, phrases share one grid area', () => { + const css = html.match(/]*>([\s\S]*?)<\/style>/)[1]; + assert.match(css, /\.fleet-run-stat \.val, \.fleet-run-stat \.gm-val \{ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; \}/); + assert.match(css, /\.fleet-cost-rotor \{ display: inline-grid; grid-template-areas: 'phrase';/); + assert.match(css, /\.fleet-cost-rotor \.fcr-phrase \{ grid-area: phrase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;/); + // Amber/text tokens only in the rotor rules — no raw colours. + const rotorCss = css.match(/\.fleet-run-stat[\s\S]*?prefers-reduced-motion: reduce\) \{[\s\S]*?\}\s*\}/)[0]; + assert.doesNotMatch(rotorCss, /#[0-9a-fA-F]{3,8}\b|rgba?\(|hsla?\(/); + assert.match(rotorCss, /var\(--amber\)/); + assert.match(rotorCss, /var\(--text\)/); + assert.doesNotMatch(makeEnv().rendered, /
0 && r.Day < today { + days[r.Day] = r.USD + } + } + return days +} + +// fleetCostWindowSum sums the ledger days from start (inclusive, a UTC day +// boundary) through today. +func fleetCostWindowSum(days map[string]float64, start, now time.Time) float64 { + today := now.UTC().Format(costRollupDayLayout) + var sum float64 + for d := start; ; d = d.AddDate(0, 0, 1) { + key := d.Format(costRollupDayLayout) + if key > today { + break + } + sum += days[key] + } + return sum +} + +// fleetCostWindows fills f's day/week/month figures from the ledger and the +// live cumulative total. tail is the rise since the ring's last snapshot +// (the spend the ledger has not folded yet); each window is also floored at +// the hour figure, since the hour is inside every window. +func fleetCostWindows(f FrontendFleetRun, hist []CostHistoryEntry, rollups []CostDailyRollup, liveTotal float64, liveSeen bool, now time.Time) FrontendFleetRun { + if len(hist) == 0 && len(rollups) == 0 { + return f + } + var tail float64 + if liveSeen && len(hist) > 0 && liveTotal > hist[len(hist)-1].USD { + tail = liveTotal - hist[len(hist)-1].USD + } + days := fleetCostLedgerDays(hist, rollups, now) + dayStart, weekStart, monthStart := fleetCostWindowStarts(now) + window := func(start time.Time) float64 { + v := fleetCostWindowSum(days, start, now) + tail + if f.HourPriced && v < f.HourUSD { + v = f.HourUSD + } + return v + } + f.DayUSD = window(dayStart) + f.WeekUSD = window(weekStart) + f.MonthUSD = window(monthStart) + f.WindowsPriced = true + return f +} + +// attachFleetCostWindows is the Server-side step: the status builders are +// free functions without the ledger, so the windows are added when the +// snapshot is published. +func (s *Server) attachFleetCostWindows(status *StatusPayload, now time.Time) { + if status == nil { + return + } + total, seen := defaultRunMeter.latestTotal() + status.FleetRun = fleetCostWindows(status.FleetRun, s.CostHistory(), s.CostDailyRollups(), total, seen, now) +} diff --git a/src/pkg/dashboard/fleet_cost_windows_test.go b/src/pkg/dashboard/fleet_cost_windows_test.go new file mode 100644 index 0000000000..f58672bc3a --- /dev/null +++ b/src/pkg/dashboard/fleet_cost_windows_test.go @@ -0,0 +1,85 @@ +package dashboard + +import ( + "math" + "testing" + "time" +) + +func TestFleetCostWindowStarts(t *testing.T) { + // Sunday 2026-11-01 13:00 UTC: ISO week began Monday 2026-10-26, the + // month began that same day at 00:00, the day at 00:00 Nov 1. + now := time.Date(2026, 11, 1, 13, 0, 0, 0, time.UTC) + day, week, month := fleetCostWindowStarts(now) + if want := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC); !day.Equal(want) { + t.Fatalf("day start %v, want %v", day, want) + } + if want := time.Date(2026, 10, 26, 0, 0, 0, 0, time.UTC); !week.Equal(want) { + t.Fatalf("week start %v, want %v", week, want) + } + if want := time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC); !month.Equal(want) { + t.Fatalf("month start %v, want %v", month, want) + } + // A Monday in a non-UTC zone still resolves to the UTC Monday. + mon := time.Date(2026, 10, 26, 1, 0, 0, 0, time.FixedZone("plus3", 3*3600)) // Sunday 22:00 UTC + _, week, _ = fleetCostWindowStarts(mon) + if want := time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC); !week.Equal(want) { + t.Fatalf("week start across zone %v, want %v", week, want) + } +} + +func TestFleetCostWindowsSumsLedgerAndLiveTail(t *testing.T) { + now := time.Date(2026, 11, 1, 13, 0, 0, 0, time.UTC) // Sunday; week = Oct 26..Nov 1 + ms := func(t time.Time) int64 { return t.UnixMilli() } + // Ring: a snapshot late on Oct 31 at $100, then two today at $104 and $110. + hist := []CostHistoryEntry{ + {Timestamp: ms(time.Date(2026, 10, 31, 23, 50, 0, 0, time.UTC)), USD: 100}, + {Timestamp: ms(time.Date(2026, 11, 1, 0, 10, 0, 0, time.UTC)), USD: 104}, + {Timestamp: ms(time.Date(2026, 11, 1, 12, 55, 0, 0, time.UTC)), USD: 110}, + } + // Stored complete days: three in the ISO week, one before it, and one + // from the previous month inside the week (Oct 26..31). + rollups := []CostDailyRollup{ + {Day: "2026-10-20", USD: 50, Samples: 10}, + {Day: "2026-10-26", USD: 7, Samples: 10}, + {Day: "2026-10-30", USD: 3, Samples: 10}, + {Day: "2026-10-31", USD: 5, Samples: 10}, + {Day: "2026-11-01", USD: 999, Samples: 10}, // today: incomplete, must be ignored + } + f := FrontendFleetRun{Running: 3, HourUSD: 2, HourPriced: true} + got := fleetCostWindows(f, hist, rollups, 111.5, true, now) + if !got.WindowsPriced { + t.Fatal("windows should be priced with a ledger present") + } + // Today from the fold: (104-100)+(110-104)=10, live tail 111.5-110=1.5. + if want := 11.5; math.Abs(got.DayUSD-want) > 1e-9 { + t.Fatalf("day %.2f want %.2f", got.DayUSD, want) + } + // Week adds Oct 26, 30, 31 stored days (7+3+5); Oct 20 is outside. + if want := 11.5 + 15; math.Abs(got.WeekUSD-want) > 1e-9 { + t.Fatalf("week %.2f want %.2f", got.WeekUSD, want) + } + // Month is November only: same as today. Week > month is legitimate. + if want := 11.5; math.Abs(got.MonthUSD-want) > 1e-9 { + t.Fatalf("month %.2f want %.2f", got.MonthUSD, want) + } + if got.HourUSD != 2 || got.Running != 3 { + t.Fatal("hour figure and running count must pass through untouched") + } +} + +func TestFleetCostWindowsFloorAtHourAndUnpricedWithoutLedger(t *testing.T) { + now := time.Date(2026, 10, 29, 10, 0, 0, 0, time.UTC) + f := FrontendFleetRun{HourUSD: 4, HourPriced: true} + got := fleetCostWindows(f, nil, nil, 4, true, now) + if got.WindowsPriced || got.DayUSD != 0 { + t.Fatalf("no ledger must leave the windows unpriced: %+v", got) + } + // A ring whose last snapshot predates the hour's rise: the hour figure + // is inside every window, so no window may read below it. + hist := []CostHistoryEntry{{Timestamp: now.Add(-2 * time.Hour).UnixMilli(), USD: 50}} + got = fleetCostWindows(f, hist, nil, 50, true, now) + if !got.WindowsPriced || got.DayUSD != 4 || got.WeekUSD != 4 || got.MonthUSD != 4 { + t.Fatalf("windows should floor at the hour figure: %+v", got) + } +} diff --git a/src/pkg/dashboard/run_meter.go b/src/pkg/dashboard/run_meter.go index 44d2994a42..e0cdbcc328 100644 --- a/src/pkg/dashboard/run_meter.go +++ b/src/pkg/dashboard/run_meter.go @@ -44,13 +44,26 @@ type FrontendAgentRun struct { } // FrontendFleetRun is the governor-strip fleet figure: how many agents are -// mid-kick and the estimated spend accrued in the current clock hour. +// mid-kick and the estimated spend accrued in the current clock hour, plus +// the wider windows the tile rotates through (hivecommons/hive#15614). type FrontendFleetRun struct { Running int `json:"running"` HourUSD float64 `json:"hourUSD"` // HourPriced is false until the meter has observed a cumulative total // in the current hour, i.e. when HourUSD would be a guess. HourPriced bool `json:"hourPriced"` + // DayUSD / WeekUSD / MonthUSD are the estimated $ spent since the start + // of the current UTC calendar day, ISO week (Monday 00:00 UTC) and + // calendar month (1st 00:00 UTC): the daily cost ledger summed over the + // window plus the live rise since its last snapshot (fleetCostWindows). + // They are attached by the Server, not the run meter, and are only + // meaningful when WindowsPriced is true. + DayUSD float64 `json:"dayUSD"` + WeekUSD float64 `json:"weekUSD"` + MonthUSD float64 `json:"monthUSD"` + // WindowsPriced is false when there is no cost ledger (no snapshot and + // no daily rollup) to sum, i.e. when the wider windows would be a guess. + WindowsPriced bool `json:"windowsPriced"` } type runBaseline struct { @@ -166,6 +179,14 @@ func (m *runMeter) fleet(running int) FrontendFleetRun { return f } +// latestTotal is the most recent cumulative estimated total the meter has +// observed, and whether it has observed one at all. +func (m *runMeter) latestTotal() (float64, bool) { + m.mu.Lock() + defer m.mu.Unlock() + return m.hourTotal, m.hourSeen +} + func modelCostTokens(mc tokens.ModelCost) int64 { return mc.Input + mc.Output + mc.CacheRead + mc.CacheCreate } diff --git a/src/pkg/dashboard/server.go b/src/pkg/dashboard/server.go index d5494a1cc2..8c783ee2d8 100644 --- a/src/pkg/dashboard/server.go +++ b/src/pkg/dashboard/server.go @@ -2649,6 +2649,7 @@ func (s *Server) UpdateStatusIfFresh(status *StatusPayload, buildEpoch uint64) b } status.ContributorPool = s.BuildContributorPoolStatus() status.Swarm = s.SwarmSnapshot() + s.attachFleetCostWindows(status, time.Now()) s.githubAppMu.RLock() status.GitHubAppRequired = s.githubAppRequired diff --git a/src/pkg/dashboard/static-src/css/governor.css b/src/pkg/dashboard/static-src/css/governor.css index f577bb51d2..a939df328c 100644 --- a/src/pkg/dashboard/static-src/css/governor.css +++ b/src/pkg/dashboard/static-src/css/governor.css @@ -16,6 +16,20 @@ /* planning-alert: plans awaiting human review — amber, to draw the eye like the "N Issues" / on-hold indicators. */ .gov-stat .val.planning-alert { color: var(--yellow); } + /* RUNNING tile cost rotor (#15614): the four window phrases share one + grid cell, so the tile is always as wide as its widest phrase and the + amount + window crossfades in place while the agent count stays put. + nowrap + ellipsis is the fallback when the tile is narrower still. */ + .fleet-run-stat .val, .fleet-run-stat .gm-val { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } + .fleet-run-count { color: var(--text); } + .fleet-cost-rotor { display: inline-grid; grid-template-areas: 'phrase'; vertical-align: bottom; max-width: 100%; overflow: hidden; color: var(--text); } + .fleet-cost-rotor .fcr-phrase { grid-area: phrase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; opacity: 0; transform: translateY(0.5em); transition: opacity 360ms ease, transform 360ms ease; pointer-events: none; } + .fleet-cost-rotor .fcr-phrase.is-cur { opacity: 1; transform: translateY(0); } + .fleet-cost-rotor .fcr-phrase.is-out { opacity: 0; transform: translateY(-0.5em); } + .fleet-cost-rotor .fcr-window { color: var(--amber); font-weight: 600; } + @media (prefers-reduced-motion: reduce) { + .fleet-cost-rotor .fcr-phrase { transition: none; transform: none; } + } .governor-subsection { margin: var(--sp-5) 0 0; } .governor-subsection .section-body { overflow: hidden; } .gov-pr-models-subheader { width: 100%; display: grid !important; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: var(--sp-3); cursor: pointer; user-select: none; } diff --git a/src/pkg/dashboard/static-src/js/agent-now.js b/src/pkg/dashboard/static-src/js/agent-now.js index 9203feab21..74dcd223bf 100644 --- a/src/pkg/dashboard/static-src/js/agent-now.js +++ b/src/pkg/dashboard/static-src/js/agent-now.js @@ -252,6 +252,74 @@ ? `${r.filesChanged} file${r.filesChanged === 1 ? '' : 's'}` : '– files'; return `
${cost}${sep}${toks}${sep}${fmtRunElapsed(r.elapsedS)}${sep}${tests}${sep}${files}
`; } + // --- fleet cost rotor (begin) --- + // The RUNNING tile rotates its cost window — this hour → today → this + // week → this month — one phrase at a time (#15614). The agent count + // stays put; only the amount + window phrase crossfades. All four + // phrases are rendered into the same grid cell so the tile is always as + // wide as its widest phrase and never shifts or wraps. The rotation + // index is module state so a status repaint keeps the current phrase. + const FLEET_COST_WINDOWS = [ + { key: 'hour', label: 'this hour', usd: 'hourUSD', priced: 'hourPriced' }, + { key: 'day', label: 'today', usd: 'dayUSD', priced: 'windowsPriced' }, + { key: 'week', label: 'this week', usd: 'weekUSD', priced: 'windowsPriced' }, + { key: 'month', label: 'this month', usd: 'monthUSD', priced: 'windowsPriced' }, + ]; + const FLEET_COST_DWELL_MS = 4000; + const FLEET_COST_WINDOWS_HELP = 'today / this week / this month are the cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC, plus the rise since its last reading.'; + const _fleetCost = { idx: 0, timer: null, hover: false }; + function fleetCostPhrases(f) { + return FLEET_COST_WINDOWS.map(w => { + const amount = f && f[w.priced] ? fmtUSD(f[w.usd] || 0) : '$–'; + return { key: w.key, label: w.label, amount, text: `${amount} ${w.label}` }; + }); + } + function fleetCostTooltipLines(f) { + return fleetCostPhrases(f).map(p => p.text).join(' · '); + } + function fleetCostReducedMotion() { + return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches); + } + function fleetCostRotorHtml(f) { + const phrases = fleetCostPhrases(f); + const idx = _fleetCost.idx % phrases.length; + const spans = phrases.map((p, i) => ``).join(''); + return `${spans}`; + } + // fleetCostApply moves one rotor from prevIdx to idx. Under reduced + // motion the outgoing phrase is never marked, so the swap is instant. + function fleetCostApply(el, prevIdx, idx) { + const reduced = fleetCostReducedMotion(); + el.querySelectorAll('.fcr-phrase').forEach((p, i) => { + const cur = i === idx; + p.classList.toggle('is-cur', cur); + p.classList.toggle('is-out', !reduced && i === prevIdx && !cur); + if (cur) p.removeAttribute('aria-hidden'); else p.setAttribute('aria-hidden', 'true'); + }); + } + function fleetCostPaused() { + return _fleetCost.hover || document.hidden === true; + } + // fleetCostTick advances every rotor on the page by one window; while + // hovered or hidden it leaves the index alone so the cadence resumes in + // step instead of jumping. + function fleetCostTick() { + if (fleetCostPaused()) return; + const prev = _fleetCost.idx; + _fleetCost.idx = (prev + 1) % FLEET_COST_WINDOWS.length; + document.querySelectorAll('[data-fleet-cost-rotor]').forEach(el => fleetCostApply(el, prev, _fleetCost.idx)); + } + function fleetCostHostOf(node) { + return node && node.closest ? node.closest('[data-fleet-cost-host]') : null; + } + function fleetCostRotorStart() { + if (_fleetCost.timer) return; + _fleetCost.timer = setInterval(fleetCostTick, FLEET_COST_DWELL_MS); + document.addEventListener('pointerover', e => { _fleetCost.hover = !!fleetCostHostOf(e.target); }); + document.addEventListener('pointerout', e => { _fleetCost.hover = !!fleetCostHostOf(e.relatedTarget); }); + } + // --- fleet cost rotor (end) --- + // fleetRunStatHtml is the Governor-section twin of fleetRunStripHtml: the // compact strip it first landed in is display:none while the full // Governor section stays visible in focus mode, so without this stat the @@ -259,14 +327,14 @@ function fleetRunStatHtml() { const f = window._lastStatus?.fleetRun; if (!f) return ''; - const hour = f.hourPriced ? fmtUSD(f.hourUSD || 0) : '$–'; - return `
running
${f.running || 0} · ${hour} this hour
`; + fleetCostRotorStart(); + return `
running
${f.running || 0} · ${fleetCostRotorHtml(f)}
`; } function fleetRunStripHtml() { const f = window._lastStatus?.fleetRun; if (!f) return ''; - const hour = f.hourPriced ? fmtUSD(f.hourUSD || 0) : '$–'; - return `
running${f.running || 0} · ${hour} this hour
`; + fleetCostRotorStart(); + return `
running${f.running || 0} · ${fleetCostRotorHtml(f)}
`; } // Repaints every "Now:" line in place so "ago" keeps counting up (and diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 6bd6826f9f..58de26dd01 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -2233,6 +2233,20 @@ /* planning-alert: plans awaiting human review — amber, to draw the eye like the "N Issues" / on-hold indicators. */ .gov-stat .val.planning-alert { color: var(--yellow); } + /* RUNNING tile cost rotor (#15614): the four window phrases share one + grid cell, so the tile is always as wide as its widest phrase and the + amount + window crossfades in place while the agent count stays put. + nowrap + ellipsis is the fallback when the tile is narrower still. */ + .fleet-run-stat .val, .fleet-run-stat .gm-val { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } + .fleet-run-count { color: var(--text); } + .fleet-cost-rotor { display: inline-grid; grid-template-areas: 'phrase'; vertical-align: bottom; max-width: 100%; overflow: hidden; color: var(--text); } + .fleet-cost-rotor .fcr-phrase { grid-area: phrase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; opacity: 0; transform: translateY(0.5em); transition: opacity 360ms ease, transform 360ms ease; pointer-events: none; } + .fleet-cost-rotor .fcr-phrase.is-cur { opacity: 1; transform: translateY(0); } + .fleet-cost-rotor .fcr-phrase.is-out { opacity: 0; transform: translateY(-0.5em); } + .fleet-cost-rotor .fcr-window { color: var(--amber); font-weight: 600; } + @media (prefers-reduced-motion: reduce) { + .fleet-cost-rotor .fcr-phrase { transition: none; transform: none; } + } .governor-subsection { margin: var(--sp-5) 0 0; } .governor-subsection .section-body { overflow: hidden; } .gov-pr-models-subheader { width: 100%; display: grid !important; grid-template-columns: auto minmax(0, 1fr) auto auto; align-items: center; gap: var(--sp-3); cursor: pointer; user-select: none; } @@ -14150,6 +14164,74 @@

Where to get help

? `${r.filesChanged} file${r.filesChanged === 1 ? '' : 's'}` : '– files'; return `
${cost}${sep}${toks}${sep}${fmtRunElapsed(r.elapsedS)}${sep}${tests}${sep}${files}
`; } + // --- fleet cost rotor (begin) --- + // The RUNNING tile rotates its cost window — this hour → today → this + // week → this month — one phrase at a time (#15614). The agent count + // stays put; only the amount + window phrase crossfades. All four + // phrases are rendered into the same grid cell so the tile is always as + // wide as its widest phrase and never shifts or wraps. The rotation + // index is module state so a status repaint keeps the current phrase. + const FLEET_COST_WINDOWS = [ + { key: 'hour', label: 'this hour', usd: 'hourUSD', priced: 'hourPriced' }, + { key: 'day', label: 'today', usd: 'dayUSD', priced: 'windowsPriced' }, + { key: 'week', label: 'this week', usd: 'weekUSD', priced: 'windowsPriced' }, + { key: 'month', label: 'this month', usd: 'monthUSD', priced: 'windowsPriced' }, + ]; + const FLEET_COST_DWELL_MS = 4000; + const FLEET_COST_WINDOWS_HELP = 'today / this week / this month are the cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC, plus the rise since its last reading.'; + const _fleetCost = { idx: 0, timer: null, hover: false }; + function fleetCostPhrases(f) { + return FLEET_COST_WINDOWS.map(w => { + const amount = f && f[w.priced] ? fmtUSD(f[w.usd] || 0) : '$–'; + return { key: w.key, label: w.label, amount, text: `${amount} ${w.label}` }; + }); + } + function fleetCostTooltipLines(f) { + return fleetCostPhrases(f).map(p => p.text).join(' · '); + } + function fleetCostReducedMotion() { + return !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches); + } + function fleetCostRotorHtml(f) { + const phrases = fleetCostPhrases(f); + const idx = _fleetCost.idx % phrases.length; + const spans = phrases.map((p, i) => ``).join(''); + return `${spans}`; + } + // fleetCostApply moves one rotor from prevIdx to idx. Under reduced + // motion the outgoing phrase is never marked, so the swap is instant. + function fleetCostApply(el, prevIdx, idx) { + const reduced = fleetCostReducedMotion(); + el.querySelectorAll('.fcr-phrase').forEach((p, i) => { + const cur = i === idx; + p.classList.toggle('is-cur', cur); + p.classList.toggle('is-out', !reduced && i === prevIdx && !cur); + if (cur) p.removeAttribute('aria-hidden'); else p.setAttribute('aria-hidden', 'true'); + }); + } + function fleetCostPaused() { + return _fleetCost.hover || document.hidden === true; + } + // fleetCostTick advances every rotor on the page by one window; while + // hovered or hidden it leaves the index alone so the cadence resumes in + // step instead of jumping. + function fleetCostTick() { + if (fleetCostPaused()) return; + const prev = _fleetCost.idx; + _fleetCost.idx = (prev + 1) % FLEET_COST_WINDOWS.length; + document.querySelectorAll('[data-fleet-cost-rotor]').forEach(el => fleetCostApply(el, prev, _fleetCost.idx)); + } + function fleetCostHostOf(node) { + return node && node.closest ? node.closest('[data-fleet-cost-host]') : null; + } + function fleetCostRotorStart() { + if (_fleetCost.timer) return; + _fleetCost.timer = setInterval(fleetCostTick, FLEET_COST_DWELL_MS); + document.addEventListener('pointerover', e => { _fleetCost.hover = !!fleetCostHostOf(e.target); }); + document.addEventListener('pointerout', e => { _fleetCost.hover = !!fleetCostHostOf(e.relatedTarget); }); + } + // --- fleet cost rotor (end) --- + // fleetRunStatHtml is the Governor-section twin of fleetRunStripHtml: the // compact strip it first landed in is display:none while the full // Governor section stays visible in focus mode, so without this stat the @@ -14157,14 +14239,14 @@

Where to get help

function fleetRunStatHtml() { const f = window._lastStatus?.fleetRun; if (!f) return ''; - const hour = f.hourPriced ? fmtUSD(f.hourUSD || 0) : '$–'; - return `
running
${f.running || 0} · ${hour} this hour
`; + fleetCostRotorStart(); + return `
running
${f.running || 0} · ${fleetCostRotorHtml(f)}
`; } function fleetRunStripHtml() { const f = window._lastStatus?.fleetRun; if (!f) return ''; - const hour = f.hourPriced ? fmtUSD(f.hourUSD || 0) : '$–'; - return `
running${f.running || 0} · ${hour} this hour
`; + fleetCostRotorStart(); + return `
running${f.running || 0} · ${fleetCostRotorHtml(f)}
`; } // Repaints every "Now:" line in place so "ago" keeps counting up (and diff --git a/src/pkg/dashboard/webstatic/fleet_run_stat_test.go b/src/pkg/dashboard/webstatic/fleet_run_stat_test.go index 5768c77f68..40cf9540d0 100644 --- a/src/pkg/dashboard/webstatic/fleet_run_stat_test.go +++ b/src/pkg/dashboard/webstatic/fleet_run_stat_test.go @@ -27,7 +27,7 @@ func TestFleetRunFigureIsInVisibleGovernorGrid(t *testing.T) { if !strings.Contains(html[grid:grid+end], "${fleetRunStatHtml()}") { t.Fatal("fleetRunStatHtml() is not rendered inside the Governor gov-grid") } - if !strings.Contains(html, `id="gov-fleet-run"`) || !strings.Contains(html, `class="gov-stat" title="RUNNING`) { + if !strings.Contains(html, `id="gov-fleet-run"`) || !strings.Contains(html, `class="gov-stat fleet-run-stat" data-fleet-cost-host title="RUNNING`) { t.Fatal("fleet run gov-stat markup missing") } } From 7478af4ab285eee524bc1c925457974cc278c766 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Thu, 29 Oct 2026 22:13:47 -0400 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=8C=B1=20dashboard:=20rename=20fleet?= =?UTF-8?q?=20cost=20window=20files=20(avoid=20=5Fwindows=20GOOS=20suffix)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Andrew Anderson --- src/pkg/dashboard/{fleet_cost_windows.go => fleet_cost_spans.go} | 0 .../{fleet_cost_windows_test.go => fleet_cost_spans_test.go} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename src/pkg/dashboard/{fleet_cost_windows.go => fleet_cost_spans.go} (100%) rename src/pkg/dashboard/{fleet_cost_windows_test.go => fleet_cost_spans_test.go} (100%) diff --git a/src/pkg/dashboard/fleet_cost_windows.go b/src/pkg/dashboard/fleet_cost_spans.go similarity index 100% rename from src/pkg/dashboard/fleet_cost_windows.go rename to src/pkg/dashboard/fleet_cost_spans.go diff --git a/src/pkg/dashboard/fleet_cost_windows_test.go b/src/pkg/dashboard/fleet_cost_spans_test.go similarity index 100% rename from src/pkg/dashboard/fleet_cost_windows_test.go rename to src/pkg/dashboard/fleet_cost_spans_test.go From 6f7060fbf93c6ec857e336d3dfd8de77076de840 Mon Sep 17 00:00:00 2001 From: Andrew Anderson Date: Thu, 29 Oct 2026 22:27:54 -0400 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=8C=B1=20dashboard:=20fleet=20cost=20?= =?UTF-8?q?rotor=20rides=20the=20shared=20interval=20registry?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TestNavbarUpgradeBeeDoesNotAddBareSetInterval caps bare setInterval( calls in static/index.html; use dashboardSetInterval (paused while the tab is hidden) and hold its visibilitychange re-fire so the rotation resumes in step. Signed-off-by: Andrew Anderson --- src/pkg/dashboard/fleet_cost_rotor.test.js | 15 +++++++++++++-- src/pkg/dashboard/static-src/js/agent-now.js | 14 +++++++++++--- src/pkg/dashboard/static/index.html | 14 +++++++++++--- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/src/pkg/dashboard/fleet_cost_rotor.test.js b/src/pkg/dashboard/fleet_cost_rotor.test.js index 854cf85616..7f47941e6e 100644 --- a/src/pkg/dashboard/fleet_cost_rotor.test.js +++ b/src/pkg/dashboard/fleet_cost_rotor.test.js @@ -63,10 +63,12 @@ function makeEnv({ reducedMotion = false } = {}) { }; const fmtUSD = n => '$' + Number(n).toFixed(2); const esc = s => String(s).replace(/&/g, '&').replace(/ { assert.strictEqual(key, 'fleetCostRotor'); return setInterval(fn, ms); }; + const api = new Function('window', 'document', 'dashboardSetInterval', 'fmtUSD', 'esc', rotorSrc + '\n' + statSrc + '\n' + stripSrc + '\nreturn { FLEET_COST_WINDOWS, FLEET_COST_DWELL_MS, _fleetCost, fleetCostPhrases, fleetCostRotorHtml, fleetCostTick, fleetRunStatHtml, fleetRunStripHtml, fleetCostTooltipLines };' - )(window, document, setInterval, fmtUSD, esc); + )(window, document, dashboardSetInterval, fmtUSD, esc); + api._fleetCost.clock = () => now; // Seed the fake phrases from the rendered markup so the DOM matches it. const rendered = api.fleetRunStatHtml(); const keys = [...rendered.matchAll(/data-fleet-cost-window="(\w+)"/g)].map(m => m[1]); @@ -124,6 +126,15 @@ test('pauses while hovered or hidden and resumes in step', () => { env.document.hidden = false; env.advance(4000); assert.deepStrictEqual(env.current(), ['week']); + // A brief hide: the interval registry re-fires the tick on + // visibilitychange, which must not cut the current dwell short. + env.document.hidden = true; + env.advance(1000); + env.document.hidden = false; + env.api.fleetCostTick(); + assert.deepStrictEqual(env.current(), ['week'], 'early re-fire after a short hide is held'); + env.advance(3000); + assert.deepStrictEqual(env.current(), ['month'], 'next step lands on the original cadence'); }); test('prefers-reduced-motion swaps instantly with no outgoing phrase', () => { diff --git a/src/pkg/dashboard/static-src/js/agent-now.js b/src/pkg/dashboard/static-src/js/agent-now.js index 74dcd223bf..727149e3de 100644 --- a/src/pkg/dashboard/static-src/js/agent-now.js +++ b/src/pkg/dashboard/static-src/js/agent-now.js @@ -267,7 +267,7 @@ ]; const FLEET_COST_DWELL_MS = 4000; const FLEET_COST_WINDOWS_HELP = 'today / this week / this month are the cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC, plus the rise since its last reading.'; - const _fleetCost = { idx: 0, timer: null, hover: false }; + const _fleetCost = { idx: 0, started: false, hover: false, lastAdvance: -Infinity, clock: () => Date.now() }; function fleetCostPhrases(f) { return FLEET_COST_WINDOWS.map(w => { const amount = f && f[w.priced] ? fmtUSD(f[w.usd] || 0) : '$–'; @@ -305,6 +305,11 @@ // step instead of jumping. function fleetCostTick() { if (fleetCostPaused()) return; + // dashboardSetInterval re-fires the callback the moment the tab is + // visible again; hold that early call so the cadence resumes in step. + const t = _fleetCost.clock(); + if (t - _fleetCost.lastAdvance < FLEET_COST_DWELL_MS / 2) return; + _fleetCost.lastAdvance = t; const prev = _fleetCost.idx; _fleetCost.idx = (prev + 1) % FLEET_COST_WINDOWS.length; document.querySelectorAll('[data-fleet-cost-rotor]').forEach(el => fleetCostApply(el, prev, _fleetCost.idx)); @@ -312,9 +317,12 @@ function fleetCostHostOf(node) { return node && node.closest ? node.closest('[data-fleet-cost-host]') : null; } + // The rotor rides the shared dashboard interval registry (paused while + // the tab is hidden) rather than adding a bare setInterval. function fleetCostRotorStart() { - if (_fleetCost.timer) return; - _fleetCost.timer = setInterval(fleetCostTick, FLEET_COST_DWELL_MS); + if (_fleetCost.started) return; + _fleetCost.started = true; + dashboardSetInterval('fleetCostRotor', fleetCostTick, FLEET_COST_DWELL_MS); document.addEventListener('pointerover', e => { _fleetCost.hover = !!fleetCostHostOf(e.target); }); document.addEventListener('pointerout', e => { _fleetCost.hover = !!fleetCostHostOf(e.relatedTarget); }); } diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 58de26dd01..35e8625792 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -14179,7 +14179,7 @@

Where to get help

]; const FLEET_COST_DWELL_MS = 4000; const FLEET_COST_WINDOWS_HELP = 'today / this week / this month are the cost ledger summed from 00:00 UTC today, Monday 00:00 UTC (ISO week) and the 1st 00:00 UTC, plus the rise since its last reading.'; - const _fleetCost = { idx: 0, timer: null, hover: false }; + const _fleetCost = { idx: 0, started: false, hover: false, lastAdvance: -Infinity, clock: () => Date.now() }; function fleetCostPhrases(f) { return FLEET_COST_WINDOWS.map(w => { const amount = f && f[w.priced] ? fmtUSD(f[w.usd] || 0) : '$–'; @@ -14217,6 +14217,11 @@

Where to get help

// step instead of jumping. function fleetCostTick() { if (fleetCostPaused()) return; + // dashboardSetInterval re-fires the callback the moment the tab is + // visible again; hold that early call so the cadence resumes in step. + const t = _fleetCost.clock(); + if (t - _fleetCost.lastAdvance < FLEET_COST_DWELL_MS / 2) return; + _fleetCost.lastAdvance = t; const prev = _fleetCost.idx; _fleetCost.idx = (prev + 1) % FLEET_COST_WINDOWS.length; document.querySelectorAll('[data-fleet-cost-rotor]').forEach(el => fleetCostApply(el, prev, _fleetCost.idx)); @@ -14224,9 +14229,12 @@

Where to get help

function fleetCostHostOf(node) { return node && node.closest ? node.closest('[data-fleet-cost-host]') : null; } + // The rotor rides the shared dashboard interval registry (paused while + // the tab is hidden) rather than adding a bare setInterval. function fleetCostRotorStart() { - if (_fleetCost.timer) return; - _fleetCost.timer = setInterval(fleetCostTick, FLEET_COST_DWELL_MS); + if (_fleetCost.started) return; + _fleetCost.started = true; + dashboardSetInterval('fleetCostRotor', fleetCostTick, FLEET_COST_DWELL_MS); document.addEventListener('pointerover', e => { _fleetCost.hover = !!fleetCostHostOf(e.target); }); document.addEventListener('pointerout', e => { _fleetCost.hover = !!fleetCostHostOf(e.relatedTarget); }); }