fix(web): move chat metrics into top-bar information panel

This commit is contained in:
2026-10-21 11:01:22 +01:00
parent de987555e9
commit b9ace1db62
9 changed files with 187 additions and 21 deletions
+41 -4
View File
@@ -16,13 +16,15 @@ ${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"].
<script type="module">
import { createChatView } from '/src/views/chat.js';
import { newChatThread } from '/src/chat.js';
import { createModalController } from '/src/modal.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 rt={state,modal:createModalController(),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;
window.busyHeader=()=>{const thread=state.chatThreads.get(id);state.chatThreads.set(id,{...thread,hasMore:true,permission:{session_id:id,request_id:'fixture-approval',action:'shell',resources:['echo fixture'],message:'Fixture approval'}});paint();};
paint();
</script>`;
const server=createServer(async(req,res)=>{try{
@@ -37,19 +39,34 @@ const known={scope:"session",total_tokens:132408,context_tokens:42000,context_wi
try {
browser=await launchChrome();
const page=await browser.openPage(`http://127.0.0.1:${server.address().port}/`);
await page.waitForSelector('#chatUsageMetrics');
await page.waitForSelector('#chatUsageInfo');
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);
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageMetrics').length"),0,'metrics must not consume transcript space by default');
let height=await page.evaluate("document.querySelector('#chatTranscript').getBoundingClientRect().height");
await page.evaluate("usage({scope:'session'})");
await page.screenshot(resolve(out,`usage-collapsed-${width}.png`));
const button=await page.evaluate("(()=>{const b=document.querySelector('#chatUsageInfo').getBoundingClientRect(),bar=document.querySelector('.chat-bar').getBoundingClientRect();return{right:b.right,barRight:bar.right,width:b.width,height:b.height};})()");
assert.ok(button.width>=44&&button.height>=44&&Math.abs(button.right-button.barRight)<=2);
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
assert.deepEqual(await values(),Array(4).fill('Unavailable'));
await page.screenshot(resolve(out,`usage-unavailable-${width}.png`));
await page.pressKey('Escape');
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')");
height=await page.evaluate("document.querySelector('#chatTranscript').getBoundingClientRect().height");
await page.evaluate(`usage(${JSON.stringify(known)})`);
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageMetrics').length"),0,'hidden stats still update without mounting a rail');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.evaluate("window.savedClose=document.querySelector('.chat-usage-info-close')");
await page.pressKey('Tab');
assert.equal(await page.evaluate('document.activeElement===savedClose'),true,'keyboard focus stays in the Info panel');
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')");
await page.evaluate(`usage(${JSON.stringify({...known,total_tokens:132409})})`);
const intact=await page.evaluate("savedInput===document.querySelector('#chatInput')&&savedClose===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("document.querySelector('#chatTranscript').getBoundingClientRect().height"),height,'the overlay must not shrink the conversation');
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);
@@ -62,11 +79,31 @@ try {
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.pressKey('Escape');
assert.equal(await page.evaluate("document.activeElement.id"),'chatUsageInfo');
assert.equal(await page.evaluate("document.querySelector('#chatUsageInfo').getAttribute('aria-expanded')"),'false');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.evaluate('history.back()');
await page.evaluate('new Promise(r=>setTimeout(r,100))');
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
assert.equal(await page.evaluate("document.querySelector('#chatUsageInfo').getAttribute('aria-expanded')"),'false');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
await page.click('.chat-usage-info-close');
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
}
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.');
await page.click('#chatUsageInfo');await page.waitForSelector('#chatUsageInfoPanel');
assert.equal(await page.evaluate("document.querySelector('.chat-usage-info-panel').getBoundingClientRect().right<=innerWidth"),true);
await page.screenshot(resolve(out,'usage-info-short-viewport-390.png'));
await page.evaluate("document.querySelector('#chatUsageInfoPanel').click()");
assert.equal(await page.evaluate("document.querySelectorAll('#chatUsageInfoPanel').length"),0);
await page.resize(390,844);await page.evaluate('busyHeader()');
const crowded=await page.evaluate("(()=>{const b=document.querySelector('#chatUsageInfo').getBoundingClientRect(),bar=document.querySelector('.chat-bar').getBoundingClientRect();return Math.abs(b.right-bar.right)<=2&&document.documentElement.scrollWidth<=innerWidth;})()");
assert.equal(crowded,true,'Info remains top-right with history and approval controls');
await page.screenshot(resolve(out,'usage-info-crowded-mobile-toolbar.png'));
console.log('PASS: metrics are hidden behind a top-right Info button, update live in a non-reflowing panel, preserve draft/cursor/transcript, and close via Escape, browser Back and backdrop with correct focus/state.');
} finally {await browser?.close();await new Promise(r=>server.close(r));}
+14
View File
@@ -221,6 +221,20 @@ function panelWith(document_, ...controls) {
return panel;
}
test("modal lifecycle cleanup runs once for direct close, closeAll and render-managed disappearance", () => {
const {document_,controller}=harness();
const closed=[];
controller.open("info",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("info")});
assert.equal(controller.close("info"),true);
assert.equal(controller.close("info"),false);
controller.open("again",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("again")});
controller.closeAll();
controller.stage("rendered",panelWith(document_,button(document_,"Close")),{history:false,onClosed:()=>closed.push("rendered")});
controller.reconcile();controller.reconcile();
assert.deepEqual(closed,["info","again","rendered"]);
assert.deepEqual(controller.stackIds(),[]);
});
test("focusable discovery keeps DOM order and excludes every unreachable form", () => {
const document_ = new FakeDocument();
const panel = new FakeElement("div", document_);
+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-v12", "pipelines-shell-v13", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
caches: { keys: async () => ["pipelines-shell-v13", "pipelines-shell-v14", "unrelated-user-cache"], delete: async (key) => deleted.push(key) },
});
handlers.get("activate")({ waitUntil: (promise) => { activation = promise; } });
await activation;
assert.deepEqual(deleted, ["pipelines-shell-v12"]);
assert.deepEqual(deleted, ["pipelines-shell-v13"]);
});