Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/added-15614-running-cost-rotor.md
Original file line number Diff line number Diff line change
@@ -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).
2 changes: 1 addition & 1 deletion src/docs/api-reference/health-status-events.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
2 changes: 1 addition & 1 deletion src/docs/dashboard-sections.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
176 changes: 176 additions & 0 deletions src/pkg/dashboard/fleet_cost_rotor.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
// 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, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
const dashboardSetInterval = (key, fn, ms) => { 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, 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]);
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']);
// 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', () => {
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, /<span class="fleet-run-count">3 · <\/span><span class="fleet-cost-rotor" data-fleet-cost-rotor/);
assert.strictEqual((r.match(/class="fcr-phrase/g) || []).length, 4);
assert.strictEqual((r.match(/data-fleet-cost-rotor/g) || []).length, 1, 'all phrases share one rotor cell');
assert.match(r, /\$53\.91<\/span> <span class="fcr-window">this hour</);
assert.match(r, /\$120\.50<\/span> <span class="fcr-window">today</);
assert.match(r, /\$410\.00<\/span> <span class="fcr-window">this week</);
assert.match(r, /\$1234\.56<\/span> <span class="fcr-window">this month</);
assert.strictEqual(env.api.fleetCostTooltipLines(env.window._lastStatus.fleetRun), '$53.91 this hour · $120.50 today · $410.00 this week · $1234.56 this month');
assert.match(r, /title="RUNNING[^"]*\$53\.91 this hour · \$120\.50 today · \$410\.00 this week · \$1234\.56 this month/);
// Unpriced windows read "$–" rather than a guess.
const unpriced = env.api.fleetCostPhrases({ hourUSD: 1, hourPriced: true, windowsPriced: false }).map(p => 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(/<style\b[^>]*>([\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, /<br/);
});
Loading
Loading