diff --git a/web/PARITY.md b/web/PARITY.md index d6e4c7c4..0fc520e1 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -8,6 +8,25 @@ test, or a code change without a capture, is `partial` at best. Status legend: `todo` · `partial` (some of it works) · `done` (working + captured). +### Chat metrics behind Info (2026-10-21) + +The four usage/performance values now live in an explicit **Chat information** +panel, opened by the always-visible Info button at the far right of the chat's +top bar. The permanent metric rail is removed on mobile and desktop. The panel +overlays rather than shrinking the conversation, still receives live numeric +updates, and keeps unknowns distinct from reported zeros. + +`test/chat-usage-browser.mjs` verifies collapsed/open/unknown/partial/zero states +at 390/420/1100px and a short viewport; metrics arriving while closed remain +available on open. It checks unchanged transcript height/DOM, preserved draft and +selection, trapped panel focus, return focus, Escape, browser Back, Close and +backdrop dismissal, accurate expanded state, and the crowded mobile toolbar with +both history and approval controls. Captures: approved OpenCode +temporary `chat-info-captures/`. A modal lifecycle cleanup hook also handles +programmatic closure without leaving stale Info state. Shell cache is v14. +This supersedes the permanent-header-rail placement described in the earlier +usage entry below; the native metrics protocol/accounting is unchanged. + ### Run graph opens recorded visits (2026-10-21) Run-graph stage clicks now call the same visit-pane action as Timeline, selecting diff --git a/web/README.md b/web/README.md index 7fed3218..2cc55db6 100644 --- a/web/README.md +++ b/web/README.md @@ -9,8 +9,9 @@ what is done; this file covers how to run, test and verify it. framework, no bundler, no build step, no npm install. - **Browser-native transport.** The page opens one `WebSocket` to `/connect`, matched by request id, with the same server-URL rules as the Android client. -- **Reported chat metrics.** Output tokens/sec, total tokens, context usage/window, - and reported USD cost stay visible above the transcript. Unreported metrics are +- **Reported chat metrics.** The top-right **Chat information** button opens + output tokens/sec, total tokens, context usage/window and reported USD cost + without taking space from the conversation. Unreported metrics are unavailable, not zero or a subscription-price estimate. - **Verified in a real browser.** UI claims are backed by PNGs captured from headless Chrome against a live server (`test/ui-smoke.mjs`); a unit test alone diff --git a/web/chat.css b/web/chat.css index 0f1535ef..5674d063 100644 --- a/web/chat.css +++ b/web/chat.css @@ -494,15 +494,62 @@ button.chat-star.starred { color: var(--color-accent); } .chat-compaction-break { flex-basis: 100%; height: 0; } .chat-compaction-status { color: var(--accent); } -/* Native usage snapshots sit outside the transcript scroller. Streaming stats - patch only this rail, never the focused composer or its selection. */ +/* Usage is opt-in behind the top-right Info control, never a permanent rail + taking height from mobile conversations. Native updates patch only its dl. */ +.chat-usage-info-button { + flex: none; + width: 44px; + height: 44px; + min-width: 44px; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; +} +.chat-usage-info-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 19px; + height: 19px; + border: 1.5px solid currentColor; + border-radius: 50%; + font-size: 13px; + font-weight: 600; + line-height: 1; +} +.chat-usage-info-overlay { position: fixed; inset: 0; z-index: 40; background: rgba(0, 0, 0, 0.18); } +.chat-usage-info-panel { + --chat-info-y: clamp(12px, var(--chat-info-top, 72px), max(12px, calc(100dvh - 180px))); + position: absolute; + top: var(--chat-info-y); + right: 12px; + width: min(360px, calc(100vw - 24px)); + max-height: calc(100dvh - 12px - var(--chat-info-y)); + overflow-y: auto; + overscroll-behavior: contain; + padding: 16px; + border: 1px solid var(--border); + border-radius: var(--radius-card); + background: var(--surface-2); + box-shadow: 0 12px 36px rgba(0, 0, 0, 0.4); +} +.chat-usage-info-heading { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; } +.chat-usage-info-heading h2 { margin: 0; font-size: 15px; } +.chat-usage-info-close { min-height: 44px; } +.chat-usage-info-note { margin: 14px 0 0; font-size: 12px; line-height: 1.5; } +@media (max-width: 600px) { + .chat-bar:has(.chat-load-older):has(.chat-approval-jump) { flex-wrap: wrap; } + .chat-bar:has(.chat-load-older):has(.chat-approval-jump) .chat-bar-lead { order: 1; flex-basis: calc(100% - 44px - var(--space-s)); } + .chat-bar:has(.chat-load-older):has(.chat-approval-jump) .chat-usage-info-button { order: 2; } + .chat-bar:has(.chat-load-older):has(.chat-approval-jump) .chat-load-older { order: 3; } + .chat-bar:has(.chat-load-older):has(.chat-approval-jump) .chat-approval-jump { order: 4; } +} .chat-usage-metrics { display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); - gap: 8px 16px; - margin: 0 0 10px; - padding: 6px 2px 10px; - border-bottom: 1px solid var(--border); + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 14px 16px; + margin: 0; } .chat-usage-metric { min-width: 0; } .chat-usage-metric dt { color: var(--muted); font-size: 11px; } @@ -514,9 +561,6 @@ button.chat-star.starred { color: var(--color-accent); } overflow-wrap: anywhere; } .chat-usage-metric[data-available="false"] dd { color: var(--muted); } -@media (max-width: 600px) { - .chat-usage-metrics { grid-template-columns: repeat(2, minmax(0, 1fr)); } -} .chat-jump { position: absolute; right: 14px; bottom: 14px; border-color: var(--accent); color: var(--accent); } diff --git a/web/src/modal.js b/web/src/modal.js index 13a3d718..243faea1 100644 --- a/web/src/modal.js +++ b/web/src/modal.js @@ -516,6 +516,9 @@ export function createModalController(options = {}) { const wasTop = index === stack.length - 1; stack.splice(index, 1); if (entry.panel?.parentElement) entry.panel.remove(); + // Lifecycle cleanup also runs for browser Back and programmatic closeAll, + // not just the owner's Escape/backdrop request handler. + entry.options?.onClosed?.(); if (wasTop) { const next = top(); if (next) setLowerInert(next, false); diff --git a/web/src/views/chat.js b/web/src/views/chat.js index 0d24a06f..51eaab61 100644 --- a/web/src/views/chat.js +++ b/web/src/views/chat.js @@ -755,7 +755,7 @@ function refreshChatTranscript(sessionId) { const bar = document.querySelector(".chat-bar"); const jump = bar?.querySelector(".chat-approval-jump"); const jumpLabel=chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question"; - if (awaiting && bar && !jump) bar.append(approvalJumpButton(jumpLabel)); + if (awaiting && bar && !jump) bar.insertBefore(approvalJumpButton(jumpLabel), bar.querySelector("#chatUsageInfo")); else if (awaiting && jump) jump.textContent=jumpLabel; else if (!awaiting) jump?.remove(); captureChatPosition(); @@ -2491,8 +2491,46 @@ function refreshChatUsageMetrics(sessionId, thread) { if (metrics?.dataset.session === sessionId) metrics.replaceWith(renderChatUsageMetrics(thread, sessionId)); } +let usageInfoSessionId = null; +function openChatUsageInfo(sessionId, trigger) { + if (modal.isOpen("chat-usage-info")) { + modal.close("chat-usage-info"); + return; + } + usageInfoSessionId = sessionId; + trigger.setAttribute("aria-expanded", "true"); + const close = () => modal.close("chat-usage-info"); + const overlay = h("div", { + class: "chat-usage-info-overlay", + id: "chatUsageInfoPanel", + role: "dialog", + "aria-modal": "true", + "aria-label": "Chat information", + }); + const panel = h("div", { class: "chat-usage-info-panel" }); + panel.style.setProperty("--chat-info-top", `${trigger.getBoundingClientRect().bottom + 8}px`); + panel.append(h("div", { class: "chat-usage-info-heading" }, + h("h2", { text: "Chat information" }), + h("button", { class: "ghost chat-usage-info-close", type: "button", text: "Close", onclick: close }), + )); + panel.append(renderChatUsageMetrics(state.chatThreads.get(sessionId), sessionId)); + panel.append(h("p", { class: "muted chat-usage-info-note", text: "Last reported by the harness. Unavailable values are not estimated." })); + overlay.append(panel); + overlay.addEventListener("click", (event) => { if (event.target === overlay) close(); }); + modal.open("chat-usage-info", overlay, { + trigger, + onClose: close, + onClosed: () => { + usageInfoSessionId = null; + document.getElementById("chatUsageInfo")?.setAttribute("aria-expanded", "false"); + }, + fallbackSelectors: ["#chatUsageInfo", "#chatInput", "#detailTitle"], + }); +} + /** The active conversation: identity, context, transcript and its controls. */ function renderChatConversation() { + if (usageInfoSessionId && usageInfoSessionId !== state.chatActiveId) modal.close("chat-usage-info"); const pane = h("div", { class: "detail chat-detail" }); if (!state.chatActiveId) { pane.append(chatEmpty(SELECT_CHAT_HINT)); @@ -2552,6 +2590,17 @@ function renderChatConversation() { // brings its card (the transcript's last item) into view — the one scroll path, // so a pending request is reached the same way new content is. if (awaiting) bar.append(approvalJumpButton(chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question")); + bar.append(h("button", { + id: "chatUsageInfo", + class: "ghost chat-usage-info-button", + type: "button", + title: "Chat information", + "aria-label": "Chat information", + "aria-haspopup": "dialog", + "aria-controls": "chatUsageInfoPanel", + "aria-expanded": String(usageInfoSessionId === state.chatActiveId && modal?.isOpen?.("chat-usage-info") === true), + onclick: (event) => openChatUsageInfo(state.chatActiveId, event.currentTarget), + }, h("span", { class: "chat-usage-info-icon", "aria-hidden": "true", text: "i" }))); pane.append(bar); const modelButton = effective ? renderChatModelButton(effective) : null; if (modelButton) { @@ -2559,7 +2608,6 @@ function renderChatConversation() { context.append(modelButton); pane.append(context); } - pane.append(renderChatUsageMetrics(thread, state.chatActiveId)); // The background-tasks bar (C11) sits above the transcript, outside the // scroller so the C14 scroll positions are untouched. It is present only while diff --git a/web/sw.js b/web/sw.js index 630db632..1e4b03c6 100644 --- a/web/sw.js +++ b/web/sw.js @@ -1,7 +1,7 @@ // A shell cache for an installed Pipelines app. The API (the WebSocket proxy and // artifact files) is never cached; static files prefer the network and fall back // to the last good copy so an installed app still opens when the server is away. -const CACHE = "pipelines-shell-v13"; +const CACHE = "pipelines-shell-v14"; const SHELL = ["/", "/index.html", "/manifest.webmanifest", "/favicon.svg"]; self.addEventListener("install", (event) => { diff --git a/web/test/chat-usage-browser.mjs b/web/test/chat-usage-browser.mjs index d377b787..9862ad18 100644 --- a/web/test/chat-usage-browser.mjs +++ b/web/test/chat-usage-browser.mjs @@ -16,13 +16,15 @@ ${["design/tokens/tokens","base","shell","lists","run-detail","chat","dialogs"]. `; 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));} diff --git a/web/test/modal.test.mjs b/web/test/modal.test.mjs index ca99f48b..fb1ba228 100644 --- a/web/test/modal.test.mjs +++ b/web/test/modal.test.mjs @@ -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_); diff --git a/web/test/serviceWorker.test.mjs b/web/test/serviceWorker.test.mjs index c70fb0f4..711b4839 100644 --- a/web/test/serviceWorker.test.mjs +++ b/web/test/serviceWorker.test.mjs @@ -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"]); });