repositories / will

will

owned by bugabinga

Compare f0cdf8460805e319824104ad2dcf0ccc6124836a → HEAD

Semantics: changes introduced since merge base. Base f0cdf8460805, head f524f463be06.

Changed files (16)

+595 / −12 text lines

Diff layout

.ci/browser.kdl

Modified

+9 / −3 text lines

22// Requires playwright browsers in the job image; enable after the browser
33// runner image exists (Luci extension item, see deploy/contract.md).
44job "browser" {
5 image "docker.io/mcr.microsoft.com/playwright:v1.58.0-noble"
5 image "mcr.microsoft.com/playwright:v1.58.0-noble"
66 trigger {
77 push {
88 branch "trunk"
1010 include "src/service/**"
1111 }
1212 }
13 run "npm ci"
13 cache "npm" {
14 path ".npm-cache"
15 key {
16 file "package-lock.json"
17 }
18 }
19 run "export NPM_CONFIG_CACHE=\"$PWD/.npm-cache\""
20 run "npm ci --prefer-offline"
1421 run "npm run build"
15 run "npx playwright install --with-deps chromium"
1622 run "npm run test:browser"

.ci/canary.kdl

Modified

+8 / −1 text lines

33job "canary" {
44 image "docker.io/library/node:26-slim"
55 secret "ZAI_API_KEY" env="ZAI_API_KEY"
6 run "npm ci"
6 cache "npm" {
7 path ".npm-cache"
8 key {
9 file "package-lock.json"
10 }
11 }
12 run "export NPM_CONFIG_CACHE=\"$PWD/.npm-cache\""
13 run "npm ci --prefer-offline"
714 run "npm run canary"
815}

.ci/validate.kdl

Modified

+8 / −1 text lines

66 branch "feature/**"
77 }
88 }
9 run "npm ci"
9 cache "npm" {
10 path ".npm-cache"
11 key {
12 file "package-lock.json"
13 }
14 }
15 run "export NPM_CONFIG_CACHE=\"$PWD/.npm-cache\""
16 run "npm ci --prefer-offline"
1017 run "npm run check"
1118 run "npm test"
1219 run "npm run coverage"

src/agent/main.ts

Modified

+8 / −0 text lines

1919import { TelegramClient } from './telegram-client.ts'
2020import { createTelegramRuntime } from './telegram-runtime.ts'
2121import { createWillTools } from './tools.ts'
22import { sumAssistantUsage } from './usage.ts'
2223import { readWorktreeState, syncWorktree, type WorktreeStatus } from './worktree.ts'
2324import { ZaiRestClient } from './zai/client.ts'
2425import { createZaiTools } from './zai/tools.ts'
124125 const kind = e.type !== undefined ? PI_EVENT_KINDS[e.type] : undefined
125126 if (kind === undefined) return
126127 void audit(kind, event).then(() => undefined)
128 if (e.type === 'agent_end') {
129 // Derived cost-view rows: one per (wake, provider/model) (spec: tokens
130 // and projected cost surface). Raw events stay untouched.
131 for (const usage of sumAssistantUsage((event as { messages?: unknown }).messages)) {
132 void audit('turn_usage', usage).then(() => undefined)
133 }
134 }
127135 }
129137 let session: SessionPort

src/agent/runtime.int.test.ts

Modified

+15 / −6 text lines

2222const exec = promisify(execFile)
24/** committer identity and signing must not depend on the machine's global git config (CI has none) */
25const GIT_IDENTITY = ['-c', 'user.name=t', '-c', 'user.email=t@t', '-c', 'commit.gpgsign=false']
2427test('worktree: clone, ff-only when clean, preserved when dirty or ahead', async () => {
2528 const dir = await mkdtemp(join(tmpdir(), 'wt-'))
2629 const remote = join(dir, 'origin.git')
3033 await exec('git', ['clone', remote, seed])
3134 await writeFile(join(seed, 'a.txt'), 'one\n')
3235 await exec('git', ['add', '.'], { cwd: seed })
33 await exec('git', ['commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed })
36 await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed })
3437 await exec('git', ['push', 'origin', 'trunk'], { cwd: seed })
3639 const s1 = await syncWorktree(work, remote, 'trunk')
4043 // advance remote; clean worktree fast-forwards
4144 await writeFile(join(seed, 'a.txt'), 'two\n')
42 await exec('git', ['commit', '-am', 'two', '--author', 't <t@t>'], { cwd: seed })
45 await exec('git', [...GIT_IDENTITY, 'commit', '-am', 'two', '--author', 't <t@t>'], { cwd: seed })
4346 await exec('git', ['push', 'origin', 'trunk'], { cwd: seed })
4447 const s2 = await syncWorktree(work, remote, 'trunk')
4548 assert.equal(s2.fastForwarded, true)
4851 // dirty worktree: preserved, no ff, reported
4952 await writeFile(join(work, 'b.txt'), 'local\n')
5053 await writeFile(join(seed, 'a.txt'), 'three\n')
51 await exec('git', ['commit', '-am', 'three', '--author', 't <t@t>'], { cwd: seed })
54 await exec('git', [...GIT_IDENTITY, 'commit', '-am', 'three', '--author', 't <t@t>'], {
55 cwd: seed,
56 })
5257 await exec('git', ['push', 'origin', 'trunk'], { cwd: seed })
5358 const s3 = await syncWorktree(work, remote, 'trunk')
5459 assert.equal(s3.dirty, true)
5863 // ahead commits: diverged, preserved
5964 await exec('git', ['add', '.'], { cwd: work })
60 await exec('git', ['commit', '-m', 'local', '--author', 't <t@t>'], { cwd: work })
65 await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'local', '--author', 't <t@t>'], {
66 cwd: work,
67 })
6168 const s4 = await syncWorktree(work, remote, 'trunk')
6269 assert.equal(s4.diverged, true)
6370})
7178 await exec('git', ['clone', remote, seed])
7279 await writeFile(join(seed, 'a.txt'), 'one\n')
7380 await exec('git', ['add', '.'], { cwd: seed })
74 await exec('git', ['commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed })
81 await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'one', '--author', 't <t@t>'], { cwd: seed })
7582 await exec('git', ['push', 'origin', 'trunk'], { cwd: seed })
7683 await exec('git', ['clone', '--quiet', remote, work])
8390 // a local commit moves HEAD; the read reports it without merging origin
8491 await writeFile(join(work, 'b.txt'), 'local\n')
8592 await exec('git', ['add', '.'], { cwd: work })
86 await exec('git', ['commit', '-m', 'local', '--author', 't <t@t>'], { cwd: work })
93 await exec('git', [...GIT_IDENTITY, 'commit', '-m', 'local', '--author', 't <t@t>'], {
94 cwd: work,
95 })
8796 const s2 = await readWorktreeState(work)
8897 assert.equal(s2.head, (await head()).stdout.trim())
8998 assert.notEqual(s2.head, s1.head)

src/agent/usage.test.ts

Added
new file mode 100644

+49 / −0 text lines

1import assert from 'node:assert/strict'
2import { test } from 'node:test'
3import { sumAssistantUsage } from './usage.ts'
4
5const assistant = (model: string, usage: object, provider = 'zai') => ({
6 role: 'assistant',
7 provider,
8 model,
9 usage,
10})
12test('sums usage across assistant messages of one wake', () => {
13 const rows = sumAssistantUsage([
14 assistant('glm-5.3-flash', { input: 100, output: 50, cacheRead: 10, cacheWrite: 5 }),
15 { role: 'user', content: 'hi' },
16 assistant('glm-5.3-flash', { input: 200, output: 20 }),
17 ])
18 assert.deepEqual(rows, [
19 {
20 provider: 'zai',
21 model: 'glm-5.3-flash',
22 input: 300,
23 output: 70,
24 cacheRead: 10,
25 cacheWrite: 5,
26 responses: 2,
27 },
28 ])
29})
31test('splits by provider/model and tolerates junk', () => {
32 const rows = sumAssistantUsage([
33 assistant('glm-5.3-flash', { input: 1 }),
34 assistant('glm-5.3-hig', { input: 2 }, 'cloudflare-ai-gateway'),
35 assistant('glm-5.3-flash', { input: 'junk', output: null }),
36 { role: 'assistant', model: 'no-usage' },
37 'garbage',
38 42,
39 ])
40 assert.equal(rows.length, 2)
41 const flash = rows.find((r) => r.model === 'glm-5.3-flash')
42 assert.equal(flash?.input, 1)
43 assert.equal(flash?.responses, 2)
44})
46test('non-array input yields no rows', () => {
47 assert.deepEqual(sumAssistantUsage(undefined), [])
48 assert.deepEqual(sumAssistantUsage({ messages: [] }), [])
49})

src/agent/usage.ts

Added
new file mode 100644

+62 / −0 text lines

1/**
2 * Turn usage extraction (cost view spec): pi agent_end events carry every
3 * message; assistant messages embed provider usage. One derived audit event
4 * per (wake, provider/model) so the service can aggregate tokens and cost.
5 */
6
7export interface TurnUsage {
8 provider: string
9 model: string
10 input: number
11 output: number
12 cacheRead: number
13 cacheWrite: number
14 /** assistant responses aggregated into this row (one model call each) */
15 responses: number
16}
18interface UsageLike {
19 input?: unknown
20 output?: unknown
21 cacheRead?: unknown
22 cacheWrite?: unknown
23}
25interface AssistantLike {
26 role?: unknown
27 model?: unknown
28 provider?: unknown
29 usage?: unknown
30}
32const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
34export function sumAssistantUsage(messages: unknown): TurnUsage[] {
35 if (!Array.isArray(messages)) return []
36 const byKey = new Map<string, TurnUsage>()
37 for (const message of messages) {
38 const m = message as AssistantLike
39 if (m?.role !== 'assistant') continue
40 if (typeof m.usage !== 'object' || m.usage === null) continue
41 const u = m.usage as UsageLike
42 const model = typeof m.model === 'string' ? m.model : 'unknown'
43 const provider = typeof m.provider === 'string' ? m.provider : 'unknown'
44 const key = `${provider}/${model}`
45 const agg = byKey.get(key) ?? {
46 provider,
47 model,
48 input: 0,
49 output: 0,
50 cacheRead: 0,
51 cacheWrite: 0,
52 responses: 0,
53 }
54 agg.input += num(u.input)
55 agg.output += num(u.output)
56 agg.cacheRead += num(u.cacheRead)
57 agg.cacheWrite += num(u.cacheWrite)
58 agg.responses += 1
59 byKey.set(key, agg)
60 }
61 return [...byKey.values()]
62}

src/service/main.int.test.ts

Modified

+53 / −0 text lines

262262 await service.close()
263263 }
264264})
266test('usage view aggregates turn_usage rows into daily cost', async () => {
267 const { service, base, internal } = await startTestService()
268 try {
269 const ingest = (events: unknown[]) =>
270 fetch(internal('/v1/audit/ingest'), {
271 method: 'POST',
272 headers: { 'content-type': 'application/json' },
273 body: JSON.stringify({ events }),
274 })
275 const today = new Date().toISOString().slice(0, 11)
276 const res = await ingest([
277 {
278 id: 'u1',
279 ts: `${today}00:00:00Z`,
280 kind: 'turn_usage',
281 payload: {
282 provider: 'zai',
283 model: 'glm-5.3-flash',
284 input: 2_000_000,
285 output: 100_000,
286 cacheRead: 1_000_000,
287 cacheWrite: 0,
288 responses: 3,
289 },
290 },
291 {
292 id: 'u2',
293 ts: `${today}09:00:00Z`,
294 kind: 'turn_usage',
295 payload: { provider: 'other', model: 'mystery', input: 5, responses: 1 },
296 },
297 { id: 'u3', ts: new Date().toISOString(), kind: 'agent_end', payload: {} },
298 ])
299 assert.equal(res.status, 200)
301 const page = await fetch(base('/api/usage'))
302 assert.equal(page.status, 200)
303 const report = (await page.json()) as {
304 days: { date: string; input: number; responses: number; costUsd: number | null }[]
305 totals: { input: number; costUsd: number | null; responses: number }
306 projection: { todayUsd: number | null; projectedEomUsd: number | null }
307 }
308 assert.equal(report.days.length, 1)
309 assert.equal(report.days[0]?.input, 2_000_005)
310 assert.equal(report.days[0]?.responses, 4)
311 // one unpriced model among the day's rows => cost withheld for that day
312 assert.equal(report.days[0]?.costUsd, null)
313 assert.equal(report.projection.projectedEomUsd, null)
314 } finally {
315 await service.close()
316 }
317})

src/service/main.ts

Modified

+3 / −0 text lines

262262 lastStatus = await callOps<ServiceStatus>(worker, 'status')
263263 sendJson(res, 200, lastStatus)
264264 })
265 publicRouter.get('/api/usage', async (_req, res) => {
266 sendJson(res, 200, await callOps(worker, 'usage'))
267 })
265268 publicRouter.get('/api/docs', async (_req, res) => {
266269 const manifest = await readJsonFile(join(config.docsDist, 'manifest.json'))
267270 sendJson(res, 200, manifest)

src/service/ops.ts

Modified

+14 / −0 text lines

3232 segmentsOverlapping,
3333} from '../shared/retention.ts'
3434import { type Clock, nowIso } from '../shared/time.ts'
35import { aggregateTurnUsage, type UsageReport } from './usage.ts'
3637export interface OpsDirs {
3738 dataDir: string
845846 }
846847 },
849 async usage(): Promise<UsageReport> {
850 const rows = db
851 .prepare("SELECT ts, payload FROM audit_events WHERE kind = 'turn_usage' ORDER BY ts")
852 .all() as unknown as { ts: string; payload: string | null }[]
853 return aggregateTurnUsage(
854 rows.map((r) => ({
855 ts: r.ts,
856 payload: r.payload === null ? null : (safeParse(r.payload) ?? null),
857 })),
858 clock.now(),
859 )
860 },
848862 async status(): Promise<ServiceStatus> {
849863 const dbStat = await stat(join(dirs.dataDir, 'will.db'))
850864 let freeBytes = 0

src/service/usage.test.ts

Added
new file mode 100644

+82 / −0 text lines

1import assert from 'node:assert/strict'
2import { test } from 'node:test'
3import { aggregateTurnUsage, projectUsage } from './usage.ts'
4
5const row = (ts: string, over: object = {}) => ({
6 ts,
7 payload: {
8 provider: 'zai',
9 model: 'glm-5.3-flash',
10 input: 1_000_000,
11 output: 0,
12 cacheRead: 0,
13 cacheWrite: 0,
14 responses: 1,
15 ...over,
16 },
17})
19test('cost uses the price table per MTok', () => {
20 const report = aggregateTurnUsage([row('2026-09-21T10:00:00Z')], new Date('2026-09-21T18:00:00Z'))
21 // 1M input tokens at $0.15/MTok
22 assert.ok(Math.abs((report.days[0]?.costUsd ?? 0) - 0.15) < 1e-6)
23 assert.ok(Math.abs((report.totals.costUsd ?? 0) - 0.15) < 1e-6)
24})
26test('unknown model keeps tokens but marks cost unavailable', () => {
27 const report = aggregateTurnUsage(
28 [row('2026-09-21T10:00:00Z', { provider: 'x', model: 'y' })],
29 new Date('2026-09-21T18:00:00Z'),
30 )
31 assert.equal(report.days[0]?.input, 1_000_000)
32 assert.equal(report.days[0]?.costUsd, null)
33 assert.equal(report.totals.costUsd, null)
34 assert.equal(report.projection.projectedEomUsd, null)
35})
37test('days are grouped by UTC date and sorted ascending', () => {
38 const report = aggregateTurnUsage(
39 [row('2026-09-21T23:00:00Z'), row('2026-09-20T01:00:00Z'), row('2026-09-21T01:00:00Z')],
40 new Date('2026-09-21T18:00:00Z'),
41 )
42 assert.deepEqual(
43 report.days.map((d) => d.date),
44 ['2026-09-20', '2026-09-21'],
45 )
46 assert.equal(report.days[1]?.responses, 2)
47})
49test('projection extrapolates today across the remaining month', () => {
50 // at 18:00 UTC, 75% of the day elapsed; 1M input/day = $0.15/day rate
51 const days = [
52 {
53 date: '2026-09-20',
54 input: 1e6,
55 output: 0,
56 cacheRead: 0,
57 cacheWrite: 0,
58 responses: 1,
59 costUsd: 0.15,
60 },
61 {
62 date: '2026-09-21',
63 input: 1e6,
64 output: 0,
65 cacheRead: 0,
66 cacheWrite: 0,
67 responses: 1,
68 costUsd: 0.15,
69 },
70 ]
71 const p = projectUsage(days, new Date('2026-09-21T18:00:00Z'))
72 assert.ok(Math.abs((p.todayUsd ?? 0) - 0.2) < 1e-9) // 0.15 / 0.75
73 assert.ok(Math.abs((p.mtdUsd ?? 0) - 0.3) < 1e-9)
74 // 9.25 days remain until Oct 1 => 0.3 + 0.2 * 9.25
75 assert.ok(Math.abs((p.projectedEomUsd ?? 0) - 2.15) < 1e-9)
76})
78test('projection is null without a priced day today', () => {
79 const p = projectUsage([], new Date('2026-09-21T18:00:00Z'))
80 assert.equal(p.todayUsd, null)
81 assert.equal(p.projectedEomUsd, null)
82})

src/service/usage.ts

Added
new file mode 100644

+155 / −0 text lines

1/**
2 * Cost view math (read-only surface): prices come from the pi model catalog
3 * (zai coding endpoint) and every function here is pure so the projection is
4 * unit-testable without a database or a live clock.
5 */
6
7export interface TurnUsageRow {
8 ts: string
9 payload: unknown
10}
12export interface DayUsage {
13 date: string
14 input: number
15 output: number
16 cacheRead: number
17 cacheWrite: number
18 responses: number
19 /** USD; null when any contributing row used a model without a price entry */
20 costUsd: number | null
21}
23export interface UsageProjection {
24 todayUsd: number | null
25 mtdUsd: number | null
26 projectedEomUsd: number | null
27}
29export interface UsageReport {
30 days: DayUsage[]
31 totals: Omit<DayUsage, 'date'>
32 projection: UsageProjection
33}
35/** USD per MTok (input, output, cacheRead); cacheWrite unpriced (unbilled). */
36const PRICES_PER_MTOK: Record<string, { input: number; output: number; cacheRead: number }> = {
37 'zai/glm-5.3-flash': { input: 0.15, output: 0.5, cacheRead: 0.03 },
38}
40interface UsagePayload {
41 provider?: unknown
42 model?: unknown
43 input?: unknown
44 output?: unknown
45 cacheRead?: unknown
46 cacheWrite?: unknown
47 responses?: unknown
48}
50const num = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
52function costOfRow(payload: unknown): number | null {
53 const p = payload as UsagePayload
54 const provider = typeof p?.provider === 'string' ? p.provider : 'unknown'
55 const model = typeof p?.model === 'string' ? p.model : 'unknown'
56 const price = PRICES_PER_MTOK[`${provider}/${model}`]
57 if (price === undefined) return null
58 return (
59 (num(p?.input) * price.input +
60 num(p?.output) * price.output +
61 num(p?.cacheRead) * price.cacheRead) /
62 1e6
63 )
64}
66const dayKey = (ts: string): string => ts.slice(0, 10)
68const HOUR_MS = 3_600_000
69/** Floor on elapsed-day fraction so a just-past-midnight spike cannot explode the rate */
70const MIN_ELAPSED_FRACTION = 0.5 / 24
72export function projectUsage(days: DayUsage[], now: Date): UsageProjection {
73 const todayKey = now.toISOString().slice(0, 10)
74 const today = days.find((d) => d.date === todayKey)
75 if (today === undefined || today.costUsd === null) {
76 return { todayUsd: null, mtdUsd: null, projectedEomUsd: null }
77 }
78 const midnight = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())
79 const elapsed = Math.max((now.getTime() - midnight) / (24 * HOUR_MS), MIN_ELAPSED_FRACTION)
80 const todayRate = today.costUsd / elapsed
81 const month = todayKey.slice(0, 7)
82 const mtd = days
83 .filter((d) => d.date.slice(0, 7) === month && d.costUsd !== null)
84 .reduce((sum, d) => sum + (d.costUsd ?? 0), 0)
85 const monthEnd = Date.UTC(
86 now.getUTCFullYear(),
87 now.getUTCMonth() + 1,
88 1, // first day of next month == end of this one
89 )
90 const projectedEom = mtd + todayRate * ((monthEnd - now.getTime()) / (24 * HOUR_MS))
91 return { todayUsd: todayRate, mtdUsd: mtd, projectedEomUsd: projectedEom }
92}
94export function aggregateTurnUsage(rows: TurnUsageRow[], now: Date): UsageReport {
95 interface Acc extends Omit<DayUsage, 'costUsd'> {
96 priced: boolean
97 costUsd: number
98 }
99 const byDay = new Map<string, Acc>()
100 for (const row of rows) {
101 const p = row.payload as UsagePayload
102 const date = dayKey(typeof row.ts === 'string' ? row.ts : '')
103 const day = byDay.get(date) ?? {
104 date,
105 input: 0,
106 output: 0,
107 cacheRead: 0,
108 cacheWrite: 0,
109 responses: 0,
110 costUsd: 0,
111 priced: true,
112 }
113 day.input += num(p?.input)
114 day.output += num(p?.output)
115 day.cacheRead += num(p?.cacheRead)
116 day.cacheWrite += num(p?.cacheWrite)
117 day.responses += num(p?.responses)
118 const cost = costOfRow(row.payload)
119 if (cost === null) day.priced = false
120 else day.costUsd += cost
121 byDay.set(date, day)
122 }
123 const days = [...byDay.values()]
124 .map(({ priced, ...d }) => ({ ...d, costUsd: priced ? d.costUsd : null }))
125 .sort((a, b) => (a.date < b.date ? -1 : 1))
126 const totalsAcc = days.reduce(
127 (t, d) => ({
128 input: t.input + d.input,
129 output: t.output + d.output,
130 cacheRead: t.cacheRead + d.cacheRead,
131 cacheWrite: t.cacheWrite + d.cacheWrite,
132 responses: t.responses + d.responses,
133 costUsd: t.costUsd + (d.costUsd ?? 0),
134 unpriced: t.unpriced || d.costUsd === null,
135 }),
136 {
137 input: 0,
138 output: 0,
139 cacheRead: 0,
140 cacheWrite: 0,
141 responses: 0,
142 costUsd: 0,
143 unpriced: false,
144 },
145 )
146 const totals: UsageReport['totals'] = {
147 input: totalsAcc.input,
148 output: totalsAcc.output,
149 cacheRead: totalsAcc.cacheRead,
150 cacheWrite: totalsAcc.cacheWrite,
151 responses: totalsAcc.responses,
152 costUsd: totalsAcc.unpriced ? null : totalsAcc.costUsd,
153 }
154 return { days, totals, projection: projectUsage(days, now) }
155}

web/index.html

Modified

+20 / −0 text lines

4545 <section id="health" role="tabpanel" aria-labelledby="tab-health" tabindex="0" hidden>
4646 <h2>Health</h2>
4747 <dl id="health-facts"></dl>
48 <h3>Tokens &amp; cost</h3>
49 <div id="usage-projection" aria-live="polite"></div>
50 <div class="table-wrap">
51 <table id="usage-table">
52 <caption class="visually-hidden">Token usage and cost per day</caption>
53 <thead>
54 <tr>
55 <th scope="col">Day</th>
56 <th scope="col">In</th>
57 <th scope="col">Out</th>
58 <th scope="col">Cache read</th>
59 <th scope="col">Cache write</th>
60 <th scope="col">Responses</th>
61 <th scope="col">Cost&nbsp;(USD)</th>
62 </tr>
63 </thead>
64 <tbody id="usage-days"></tbody>
65 <tfoot id="usage-totals"></tfoot>
66 </table>
67 </div>
4868 </section>
4969 <section id="docs" role="tabpanel" aria-labelledby="tab-docs" tabindex="0" hidden>
5070 <h2>Docs</h2>

web/src/main.css

Modified

+36 / −0 text lines

278278 padding-right: 0.75rem;
279279 }
282/* usage table (health tab) */
283.table-wrap {
284 overflow-x: auto;
285}
287#usage-table {
288 border-collapse: collapse;
289 width: 100%;
290 font-variant-numeric: tabular-nums;
291}
293#usage-table th,
294#usage-table td {
295 border: 1px solid var(--line);
296 padding: 0.25rem 0.5rem;
297 text-align: right;
298}
300#usage-table th:first-child,
301#usage-table td:first-child {
302 text-align: left;
303}
305#usage-table tfoot td {
306 font-weight: 600;
307}
309.visually-hidden {
310 position: absolute;
311 width: 1px;
312 height: 1px;
313 overflow: hidden;
314 clip-path: inset(50%);
315 white-space: nowrap;
316}

web/src/main.ts

Modified

+70 / −1 text lines

214214 }
217const fmtUsd = (usd: number | null): string =>
218 usd === null ? 'n/a' : usd < 0.01 && usd > 0 ? `<$0.01` : `$${usd.toFixed(2)}`
219const fmtTok = (n: number): string =>
220 n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${(n / 1e3).toFixed(1)}k` : String(n)
222interface UsageReportRow {
223 days: {
224 date: string
225 input: number
226 output: number
227 cacheRead: number
228 cacheWrite: number
229 responses: number
230 costUsd: number | null
231 }[]
232 totals: {
233 input: number
234 output: number
235 cacheRead: number
236 cacheWrite: number
237 responses: number
238 costUsd: number | null
239 }
240 projection: { todayUsd: number | null; mtdUsd: number | null; projectedEomUsd: number | null }
241}
243async function loadUsage(): Promise<void> {
244 const res = await fetch('/api/usage')
245 const report = (await res.json()) as UsageReportRow
246 const body = $('#usage-days')
247 const foot = $('#usage-totals')
248 body.replaceChildren()
249 const row = (cells: string[]): HTMLTableRowElement => {
250 const tr = document.createElement('tr')
251 for (const c of cells) tr.append(el('td', {}, text(c)))
252 return tr
253 }
254 for (const d of [...report.days].reverse()) {
255 body.append(
256 row([
257 d.date,
258 fmtTok(d.input),
259 fmtTok(d.output),
260 fmtTok(d.cacheRead),
261 fmtTok(d.cacheWrite),
262 String(d.responses),
263 fmtUsd(d.costUsd),
264 ]),
265 )
266 }
267 foot.replaceChildren(
268 row([
269 'total',
270 fmtTok(report.totals.input),
271 fmtTok(report.totals.output),
272 fmtTok(report.totals.cacheRead),
273 fmtTok(report.totals.cacheWrite),
274 String(report.totals.responses),
275 fmtUsd(report.totals.costUsd),
276 ]),
277 )
278 const p = report.projection
279 $('#usage-projection').replaceChildren(
280 text(
281 `today ${fmtUsd(p.todayUsd)} · month-to-date ${fmtUsd(p.mtdUsd)} · projected end of month ${fmtUsd(p.projectedEomUsd)}`,
282 ),
283 )
284}
217286async function loadHealth(): Promise<void> {
218287 const res = await fetch('/api/status')
219288 const s = (await res.json()) as StatusRow
267336 chat: loadChat,
268337 media: loadMedia,
269338 deployments: loadDeployments,
270 health: loadHealth,
339 health: () => Promise.all([loadHealth(), loadUsage()]).then(() => undefined),
271340 docs: loadDocs,

web/tests/phenotype.spec.ts

Modified

+3 / −0 text lines

104104 await page.keyboard.press('Enter')
105105 await expect(page.getByRole('heading', { name: 'Health' })).toBeVisible()
106106 await expect(page.locator('#health-facts')).toContainText('storage')
107 // cost view: empty storage renders the zero table, not an error
108 await expect(page.locator('#usage-projection')).toContainText('today')
109 await expect(page.locator('#usage-totals')).toContainText('total')
107110})
109112test('skip link exists and docs view loads rendered markdown', async ({ page }) => {