feat(web): display reported chat throughput tokens context and cost

This commit is contained in:
2026-10-21 00:27:12 +01:00
parent 910028a75c
commit 0b8595f16e
12 changed files with 314 additions and 12 deletions
+72
View File
@@ -0,0 +1,72 @@
// Actual chat view/event handler with native-shaped usage fixtures. No backend
// connection, provider calls, production chats, or price estimates.
import assert from "node:assert/strict";
import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { resolve, extname, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { launchChrome } from "./browser.mjs";
const root=resolve(dirname(fileURLToPath(import.meta.url)),"..");
const out=resolve(process.argv[2]??"captures-chat-usage");
await mkdir(out,{recursive:true});
const html=`<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"].map(n=>`<link rel="stylesheet" href="/${n}.css">`).join("")}
<div class="app-root"><main class="workspace"><div class="pane-main"><div class="content" id="content"></div></div></main></div>
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread } from '/src/chat.js';
const id='scratch';
const state={view:'chat',chatActiveId:id,chatSessions:[{id,title:'Chat usage',backend:'opencode'}],chatOverrides:{},chatDrafts:{},chatThreads:new Map([[id,{...newChatThread(id),loaded:true,messages:[{id:'user',role:'user',parts:[{type:'text',text:'Inspect the results.'}]},{id:'assistant',role:'assistant',parts:[{type:'text',text:'Usage is reported by the harness, not inferred from this answer.'}]}]}]])};
const rt={state,repo:{},renderContent:()=>paint(),closeDetail:()=>{}};
const view=createChatView(rt);
window.paint=()=>document.querySelector('#content').replaceChildren(view.renderChatConversation());
window.usage=(snapshot)=>view.onChatEvent({session_id:id,kind:'usage',usage:snapshot});
window.messageCount=()=>state.chatThreads.get(id).messages.length;
paint();
</script>`;
const server=createServer(async(req,res)=>{try{
const path=new URL(req.url,"http://fixture").pathname;
if(path==="/"){res.setHeader("Content-Type","text/html");res.end(html);return;}
const file=resolve(root,`.${path}`);if(!file.startsWith(root+"/"))throw Error("outside fixture");
res.setHeader("Content-Type",extname(file)===".css"?"text/css":"text/javascript");res.end(await readFile(file));
}catch{res.writeHead(404);res.end();}});
await new Promise(r=>server.listen(0,"127.0.0.1",r));
let browser;
const known={scope:"session",total_tokens:132408,context_tokens:42000,context_window:200000,cost_usd:.1423,output_tokens_per_second:24.6,rate_basis:"generation"};
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatUsageMetrics');
const values=()=>page.evaluate("Array.from(document.querySelectorAll('#chatUsageMetrics dd'),node=>node.textContent)");
for(const width of [390,420,1100]) {
await page.resize(width,844);
await page.evaluate("usage({scope:'session'})");
assert.deepEqual(await values(),Array(4).fill('Unavailable'));
await page.screenshot(resolve(out,`usage-unavailable-${width}.png`));
await page.fill('#chatInput','Keep this draft and cursor.');
await page.evaluate("window.savedInput=document.querySelector('#chatInput');savedInput.focus();savedInput.setSelectionRange(5,10);window.savedTranscript=document.querySelector('#chatTranscript')");
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.deepEqual(await values(),['24.6 tok/s','132,408','42,000 / 200,000','$0.1423']);
const intact=await page.evaluate("savedInput===document.querySelector('#chatInput')&&savedInput===document.activeElement&&savedInput.value==='Keep this draft and cursor.'&&savedInput.selectionStart===5&&savedInput.selectionEnd===10&&savedTranscript===document.querySelector('#chatTranscript')");
assert.equal(intact,true,'usage updates must not repaint the composer/transcript');
assert.equal(await page.evaluate('messageCount()'),2);
assert.equal(await page.evaluate("document.querySelectorAll('#chatStop').length"),0,'usage must not start a turn');
assert.equal(await page.evaluate('document.documentElement.scrollWidth>innerWidth'),false);
await page.screenshot(resolve(out,`usage-reported-${width}.png`));
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.deepEqual(await values(),['24.6 tok/s','132,408','42,000 / 200,000','$0.1423']);
await page.evaluate("usage({scope:'session',total_tokens:140000,context_tokens:3000,context_window:1048576})");
assert.deepEqual(await values(),['Unavailable','140,000','3,000 / 1,048,576','Unavailable']);
await page.screenshot(resolve(out,`usage-partial-native-${width}.png`));
await page.evaluate("usage({scope:'session',total_tokens:0,context_tokens:0,context_window:200000,cost_usd:0,output_tokens_per_second:0})");
assert.deepEqual(await values(),['0 tok/s','0','0 / 200,000','$0.0000']);
await page.screenshot(resolve(out,`usage-reported-zero-${width}.png`));
}
await page.resize(390,500);
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.equal(await page.evaluate("document.querySelector('#chatComposer').getBoundingClientRect().bottom<=innerHeight"),true);
assert.equal(await page.evaluate('document.documentElement.scrollWidth>innerWidth'),false);
await page.screenshot(resolve(out,'usage-short-viewport-390.png'));
console.log('PASS: live metric rail, exact reported/unknown/zero states, no double counting or fake messages, mobile fit, and preserved composer focus/selection and transcript DOM.');
} finally {await browser?.close();await new Promise(r=>server.close(r));}
+1 -2
View File
@@ -1286,11 +1286,10 @@ test("step started runs the turn and step ended settles it", () => {
assert.equal(thread.lastDeltaAt, 0);
});
test("any frame clears the queued flag", () => {
test("turn-content frames clear the queued flag", () => {
for (const frame of [
evt("text", { message_id: "a1", part: { id: "p" }, delta: "x" }),
evt("step", { step: { status: "started" } }),
evt("usage", { usage: { input_tokens: 1 } }),
evt("shell", { shell: { id: "sh1", status: "running" } }),
]) {
const queued = { ...newChatThread("s1"), queued: true };
+69
View File
@@ -0,0 +1,69 @@
import test from "node:test";
import assert from "node:assert/strict";
import { chatUsageMetrics, normalizeChatUsage } from "../src/chatUsage.js";
import { newChatThread, applyChatEvent, settledThread, resumedThread, historyResync, queuedAfterFrame } from "../src/chat.js";
const snapshot = {scope:"session",total_tokens:132408,context_tokens:42000,context_window:200000,cost_usd:0.1423,output_tokens_per_second:24.6,rate_basis:"generation"};
const event = (usage) => ({session_id:"chat",kind:"usage",usage});
test("usage metrics format native counters without conflating context and processed totals", () => {
const rows=chatUsageMetrics(snapshot,"en-US");
assert.deepEqual(rows.map(row=>row.value),["24.6 tok/s","132,408","42,000 / 200,000","$0.1423"]);
assert.ok(rows.every(row=>row.available));
assert.match(rows[0].title,/native request-to-stream-completion/);
});
test("unreported values stay unavailable, including legacy zero or unsupported subscription costs", () => {
assert.ok(chatUsageMetrics(null).every(row=>row.value==="Unavailable"));
assert.ok(chatUsageMetrics({input_tokens:100,output_tokens:50,cost:0}).every(row=>!row.available));
const codex=chatUsageMetrics({scope:"session",total_tokens:1000,context_window:128000},"en-US");
assert.equal(codex[3].value,"Unavailable");
assert.equal(codex[2].value,"128,000 limit");
assert.equal(codex[0].value,"Unavailable");
});
test("reported zeros are not missing and tiny positive values are not displayed as zero", () => {
const zero=chatUsageMetrics({scope:"session",total_tokens:0,context_tokens:0,context_window:1000,cost_usd:0,output_tokens_per_second:0},"en-US");
assert.deepEqual(zero.map(row=>row.value),["0 tok/s","0","0 / 1,000","$0.0000"]);
const small=chatUsageMetrics({cost_usd:0.00000001,output_tokens_per_second:0.01},"en-US");
assert.equal(small[0].value,"<0.1 tok/s");
assert.equal(small[3].value,"<$0.000001");
});
test("invalid, fractional or unsafe counters are never turned into fabricated metrics", () => {
const invalid=normalizeChatUsage({scope:"session",total_tokens:1.5,context_tokens:-1,context_window:0,cost_usd:Infinity,output_tokens_per_second:"100"});
assert.ok(chatUsageMetrics(invalid).every(row=>!row.available));
assert.equal(normalizeChatUsage({total_tokens:Number.MAX_SAFE_INTEGER+1}),null);
assert.equal(normalizeChatUsage([]),null);
});
test("usage snapshots replace counters, preserve queue/turn state and do not create messages", () => {
const original={...newChatThread("chat"),queued:true};
const once=applyChatEvent(original,event(snapshot));
const twice=applyChatEvent(once,event(snapshot));
assert.equal(twice.usage.total_tokens,132408);
assert.equal(twice.queued,true);
assert.equal(twice.running,false);
assert.deepEqual(twice.messages,[]);
assert.equal(queuedAfterFrame(true,event(snapshot)),true);
const next=applyChatEvent(twice,event({...snapshot,total_tokens:133000,context_tokens:3000}));
assert.equal(next.usage.total_tokens,133000);
assert.equal(next.usage.context_tokens,3000);
assert.equal(applyChatEvent(next,{...event(snapshot),session_id:"other"}),next);
});
test("last reported metrics survive idle, history refresh and reconnect without being summed", () => {
const thread=applyChatEvent(newChatThread("chat"),event(snapshot));
for(const result of [settledThread(thread),resumedThread(thread),historyResync(thread,{messages:[]})]) {
assert.equal(result.usage.total_tokens,132408);
assert.equal(result.usage.cost_usd,0.1423);
}
const unknown=applyChatEvent(thread,event({scope:"session"}));
assert.ok(chatUsageMetrics(unknown.usage).every(row=>!row.available));
});
test("turn-wall-time averages are labeled rather than presented as pure model generation speed", () => {
const rate=chatUsageMetrics({...snapshot,rate_basis:"turn"})[0];
assert.equal(rate.label,"Avg output rate");
assert.match(rate.title,/including tools and waiting/);
});
+2 -2
View File
@@ -9,9 +9,9 @@ test("shell updates retain unrelated caches and the current app cache", async ()
let activation;
vm.runInNewContext(await readFile(new URL("../sw.js", import.meta.url), "utf8"), {
self: { addEventListener: (type, handler) => handlers.set(type, handler), clients: { claim: async () => {} } },
caches: { keys: async () => ["pipelines-shell-v10", "pipelines-shell-v11", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
caches: { keys: async () => ["pipelines-shell-v11", "pipelines-shell-v12", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
});
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
await activation;
assert.deepEqual(deleted, ["pipelines-shell-v10"]);
assert.deepEqual(deleted, ["pipelines-shell-v11"]);
});