Skip to content

Commit 4cce730

Browse files
committed
feat(es-app): collapse provider accounting by default (anomalyco#157)
1 parent 3847c63 commit 4cce730

5 files changed

Lines changed: 165 additions & 12 deletions

File tree

‎packages/es-app/src/components/context-viz.tsx‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -96,18 +96,30 @@ export function CompositionDots(props: { slices: CompositionSlice[] }) {
9696
)
9797
}
9898

99-
export function ProviderAccounting(props: { tokens: TokenCounts | null | undefined; compact?: boolean }) {
100-
const rows = () => props.tokens ? [
101-
{ label: "cache read", value: props.tokens.cache?.read ?? 0 },
102-
{ label: "cache write", value: props.tokens.cache?.write ?? 0 },
103-
{ label: "uncached input", value: props.tokens.input },
104-
{ label: "generated output", value: props.tokens.output },
105-
{ label: "reasoning", value: props.tokens.reasoning },
106-
] : []
99+
const accountingRows = (tokens: TokenCounts | null | undefined) => tokens ? [
100+
{ label: "cache read", value: tokens.cache?.read ?? 0 },
101+
{ label: "cache write", value: tokens.cache?.write ?? 0 },
102+
{ label: "uncached input", value: tokens.input },
103+
{ label: "generated output", value: tokens.output },
104+
{ label: "reasoning", value: tokens.reasoning },
105+
] : []
106+
107+
// one-line gist for a collapsed disclosure: the dominant class plus generated output
108+
export const accountingGist = (tokens: TokenCounts | null | undefined) => {
109+
const rows = accountingRows(tokens)
110+
const total = rows.reduce((sum, row) => sum + row.value, 0)
111+
if (!total) return "provider usage unknown"
112+
const top = rows.slice(0, 3).reduce((best, row) => row.value > best.value ? row : best)
113+
const output = rows.find((row) => row.label === "generated output")!
114+
return `${top.label} ${Math.round((top.value / total) * 100)}% · output ${output.value.toLocaleString()}`
115+
}
116+
117+
export function ProviderAccounting(props: { tokens: TokenCounts | null | undefined; compact?: boolean; heading?: boolean }) {
118+
const rows = () => accountingRows(props.tokens)
107119
const total = () => rows().reduce((sum, row) => sum + row.value, 0)
108120
return (
109121
<div class="ctx-accounting">
110-
<div class="ctx-subheading">provider accounting · exact latest turn</div>
122+
<Show when={props.heading !== false}><div class="ctx-subheading">provider accounting · exact latest turn</div></Show>
111123
<Show when={total() > 0} fallback={<div class="ctx-caption">provider usage unknown</div>}>
112124
<ul class="ctx-provider" aria-label="exact latest-turn provider token accounting">
113125
<For each={rows().filter((row) => !props.compact || row.value > 0)}>{(row) => (

‎packages/es-app/src/components/session-info.tsx‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* Right panel on the session page: identity, spend, editspace joins (lane,
22
* tickets, PRs via the dashboard's thread model), tracker tickets and docs
33
* this session references, and links shared in the conversation. */
4-
import { createEffect, createMemo, createResource, For, Show } from "solid-js"
4+
import { createEffect, createMemo, createResource, createSignal, For, Show } from "solid-js"
55
import { A } from "@solidjs/router"
66
import type { Message, Part, Session } from "@opencode-ai/sdk/v2"
77
import { es, type IssueRow } from "../api"
@@ -15,7 +15,7 @@ import { prFromHref } from "../pr-matching"
1515
import { linkUrl } from "../link-url"
1616
import { compactTokens, contextUsage, countCompletedTurns, latestCompletedTurn, usageLevel, type ProviderList } from "../context-usage"
1717
import { compositionSlices, estimateComposition } from "../context-composition"
18-
import { CompositionBar, ProviderAccounting } from "./context-viz"
18+
import { accountingGist, CompositionBar, ProviderAccounting } from "./context-viz"
1919
import { prDetail, requestPrDetails } from "../pr-details"
2020

2121
const URL_RE = /https?:\/\/[^\s)\]}"'`>]+/g
@@ -32,6 +32,14 @@ const compact = (n?: number) => {
3232

3333
const home = (p: string) => p.replace(/^\/Users\/[^/]+/, "~")
3434

35+
// per-client memory of the provider-accounting disclosure; collapsed unless the user opened it
36+
const ACCOUNTING_KEY = "es-app-ctx-accounting-open"
37+
const [accountingOpen, setAccountingOpenRaw] = createSignal(localStorage.getItem(ACCOUNTING_KEY) === "1")
38+
const setAccountingOpen = (open: boolean) => {
39+
localStorage.setItem(ACCOUNTING_KEY, open ? "1" : "0")
40+
setAccountingOpenRaw(open)
41+
}
42+
3543
export default function SessionInfo(props: {
3644
sessionID: string
3745
session?: Session
@@ -348,7 +356,17 @@ function SessionInfoBody(props: {
348356
</>
349357
)}</Show>
350358
</div>
351-
<ProviderAccounting tokens={usage() ? latestTurn()?.tokens : null} />
359+
{/* exact per-class counts collapse by default: cache read is usually ~100% and the
360+
* five-row table otherwise dominates the panel; the gist keeps the key numbers visible */}
361+
<details class="ctx-accounting-disclosure" open={accountingOpen()}>
362+
{/* drive the state ourselves so persistence is synchronous with the click/Enter, not the queued toggle event */}
363+
<summary aria-label="exact latest-turn provider accounting"
364+
onClick={(event) => { event.preventDefault(); setAccountingOpen(!accountingOpen()) }}>
365+
<span class="ctx-subheading">provider accounting</span>
366+
<span class="ctx-gist mono" dir="ltr">{usage() ? accountingGist(latestTurn()?.tokens) : "unknown"}</span>
367+
</summary>
368+
<ProviderAccounting tokens={usage() ? latestTurn()?.tokens : null} heading={false} />
369+
</details>
352370
<div class="ctx-subheading">estimated visible content</div>
353371
<Show when={slices().length} fallback={<div class="ctx-caption">visible estimate unknown or empty</div>}>
354372
<CompositionBar slices={slices()} />

‎packages/es-app/src/index.css‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -535,6 +535,16 @@ main { max-width: 1400px; margin: 0 auto; padding: 0 20px 40px; }
535535
.ctx-exact .ctx-exact-meta { color: var(--subtext0); font-size: 11px; }
536536
.ctx-subheading { font-size: 11px; font-weight: 600; color: var(--subtext1); margin-block: 5px 2px; }
537537
.ctx-accounting { margin-block: 5px; }
538+
.ctx-accounting-disclosure { margin-block: 5px; }
539+
.ctx-accounting-disclosure > summary { display: flex; flex-wrap: wrap; align-items: baseline; gap: 2px 6px; cursor: pointer; list-style: none; min-width: 0; }
540+
.ctx-accounting-disclosure > summary::-webkit-details-marker { display: none; }
541+
.ctx-accounting-disclosure > summary::before { content: "▸"; color: var(--overlay1); font-size: 10px; flex: none; }
542+
.ctx-accounting-disclosure[open] > summary::before { content: "▾"; }
543+
.ctx-accounting-disclosure > summary .ctx-subheading { margin-block: 0; flex: none; }
544+
.ctx-accounting-disclosure > summary:hover .ctx-subheading { color: var(--text); }
545+
.ctx-accounting-disclosure > summary:focus-visible { outline: 1px solid var(--lavender); outline-offset: 2px; }
546+
.ctx-gist { font-size: 10.5px; color: var(--subtext0); min-width: 0; overflow-wrap: anywhere; }
547+
.ctx-accounting-disclosure .ctx-accounting { margin-block: 3px 0; padding-inline-start: 12px; }
538548
.ctx-provider { list-style: none; margin: 0 0 3px; padding: 0; display: grid; gap: 1px; }
539549
.ctx-provider li { display: grid; grid-template-columns: minmax(0, 1fr) auto 3em; gap: 6px; font-size: 11px; align-items: baseline; }
540550
.ctx-provider .mono { text-align: end; font-variant-numeric: tabular-nums; }
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
// #157: the exact latest-turn provider accounting rows collapse by default in
2+
// the right panel behind a one-line gist; the exact context percentage and the
3+
// estimated visible-content bar stay visible; the toggle is remembered per client.
4+
import { createRequire } from "node:module"
5+
import { mkdtemp, rm } from "node:fs/promises"
6+
import { tmpdir } from "node:os"
7+
import path from "node:path"
8+
import { startPanelPreview } from "./composer-panel-preview.mjs"
9+
import { directory } from "./composer-fixture.mjs"
10+
11+
const { chromium, _electron, expect } = createRequire(new URL("../../app/package.json", import.meta.url))("@playwright/test")
12+
const preview = await startPanelPreview()
13+
const fixture = preview.fixture
14+
fixture.messages[1].info.time.completed = 3
15+
fixture.messages[1].info.tokens = { input: 3, output: 608, reasoning: 46, cache: { read: 471919, write: 491 } }
16+
fixture.messagesB = [
17+
{ info: { id: "b_1", sessionID: "ses_b", role: "user", agent: "build", model: { providerID: "fixture", modelID: "test" }, time: { created: 1 } },
18+
parts: [{ id: "bp_1", messageID: "b_1", sessionID: "ses_b", type: "text", text: "hello" }] },
19+
{ info: { id: "b_2", sessionID: "ses_b", role: "assistant", agent: "build", providerID: "fixture", modelID: "test", parentID: "b_1",
20+
path: { cwd: directory, root: directory }, cost: 0, tokens: { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } }, time: { created: 2, completed: 3 } },
21+
parts: [{ id: "bp_2", messageID: "b_2", sessionID: "ses_b", type: "text", text: "hi" }] },
22+
]
23+
const providers = { providers: [{ id: "fixture", models: { test: { id: "test", limit: { context: 500000 } } } }], default: {} }
24+
const profile = process.env.ES_DESKTOP_EXECUTABLE ? await mkdtemp(path.join(tmpdir(), "context-accounting-")) : undefined
25+
const app = profile ? await _electron.launch({ executablePath: process.env.ES_DESKTOP_EXECUTABLE,
26+
env: { ...process.env, ELECTRON_RUN_AS_NODE: "", ES_DESKTOP_USER_DATA: profile, ES_DESKTOP_RENDERER: "",
27+
OPENCODE_URL: fixture.url, ES_DASHBOARD_URL: fixture.url, OPENCODE_SERVER_PASSWORD: "" } }) : undefined
28+
const browser = app ? undefined : await chromium.launch({ channel: "chrome", headless: true })
29+
const page = app ? await app.firstWindow() : await browser.newPage({ viewport: { width: 1440, height: 900 } })
30+
if (app) {
31+
await page.waitForURL("http://127.0.0.1:*/")
32+
preview.origin = new URL(page.url()).origin
33+
preview.url = `${preview.origin}/session/ses_a?directory=${encodeURIComponent(directory)}`
34+
}
35+
await page.context().route("**/*", (route) => new URL(route.request().url()).origin === preview.origin ? route.continue() : route.abort())
36+
await page.route("**/config/providers*", (route) => route.fulfill({ json: providers }))
37+
const panel = page.locator(".session-info")
38+
const disclosure = panel.locator(".ctx-accounting-disclosure")
39+
const summary = disclosure.locator("> summary")
40+
const rows = panel.locator(".ctx-provider li")
41+
const shot = async (name) => { if (process.env.CONTEXT_ACCOUNTING_SHOTS) await page.screenshot({ path: `${process.env.CONTEXT_ACCOUNTING_SHOTS}-${name}.png` }) }
42+
try {
43+
await page.goto(preview.url, { waitUntil: "domcontentloaded" })
44+
// exact percent, bar and legend remain visible while the rows are collapsed
45+
await expect(panel.locator(".ctx-exact")).toContainText("473k / 500k (95%)")
46+
await expect(panel.locator(".ctx-exact.high")).toHaveCount(1)
47+
await expect(panel.locator(".ctx-bar")).toBeVisible()
48+
await expect(panel.locator(".ctx-legend li", { hasText: "assistant text" })).toBeVisible()
49+
await expect(disclosure).not.toHaveAttribute("open")
50+
await expect(summary).toHaveAttribute("aria-label", "exact latest-turn provider accounting")
51+
await expect(summary.locator(".ctx-gist")).toHaveText("cache read 100% · output 608")
52+
await expect(panel.locator(".ctx-provider")).not.toBeVisible()
53+
expect(await panel.evaluate((el) => el.innerText.includes("471,919"))).toBe(false)
54+
const collapsedHeight = await panel.locator("[data-section='context']").evaluate((el) => el.getBoundingClientRect().height)
55+
await shot("collapsed")
56+
57+
// keyboard expand reveals every exact class with numeric and percentage detail
58+
await summary.focus()
59+
await page.keyboard.press("Enter")
60+
await expect(disclosure).toHaveAttribute("open", "")
61+
await expect(rows).toHaveCount(5)
62+
await expect(rows.filter({ hasText: "cache read" })).toContainText("471,919")
63+
await expect(rows.filter({ hasText: "cache read" })).toContainText("100%")
64+
await expect(rows.filter({ hasText: "cache write" })).toContainText("491")
65+
await expect(rows.filter({ hasText: "uncached input" })).toContainText("3")
66+
await expect(rows.filter({ hasText: "generated output" })).toContainText("608")
67+
await expect(rows.filter({ hasText: "reasoning" })).toContainText("46")
68+
await expect(rows.filter({ hasText: "cache read" }).locator(".mono").first()).toHaveAttribute("title", "471,919 tokens")
69+
await expect(panel.locator(".ctx-accounting .ctx-caption")).toContainText("provider accounting classes, not content sources")
70+
expect(await panel.locator("[data-section='context']").evaluate((el) => el.getBoundingClientRect().height)).toBeGreaterThan(collapsedHeight + 40)
71+
await shot("expanded")
72+
73+
// the open state persists per client across reload and across sessions
74+
await page.reload({ waitUntil: "domcontentloaded" })
75+
await expect(disclosure).toHaveAttribute("open", "")
76+
await expect(rows.filter({ hasText: "cache read" })).toBeVisible()
77+
expect(await page.evaluate(() => localStorage.getItem("es-app-ctx-accounting-open"))).toBe("1")
78+
await summary.click()
79+
await expect(disclosure).not.toHaveAttribute("open")
80+
await page.reload({ waitUntil: "domcontentloaded" })
81+
await expect(disclosure).not.toHaveAttribute("open")
82+
await expect(summary.locator(".ctx-gist")).toHaveText("cache read 100% · output 608")
83+
84+
// unknown usage: gist says so, no fabricated rows
85+
await page.goto(`${preview.origin}/session/ses_b?directory=${encodeURIComponent(directory)}`, { waitUntil: "domcontentloaded" })
86+
await expect(panel.locator(".ctx-exact")).toContainText("latest turn context unknown")
87+
await expect(summary.locator(".ctx-gist")).toHaveText("unknown")
88+
await summary.click()
89+
await expect(panel.locator(".ctx-accounting .ctx-caption")).toHaveText("provider usage unknown")
90+
await expect(rows).toHaveCount(0)
91+
await summary.click()
92+
await expect(disclosure).not.toHaveAttribute("open")
93+
94+
// mobile + RTL: gist stays on one line without horizontal overflow
95+
await page.goto(preview.url, { waitUntil: "domcontentloaded" })
96+
await page.setViewportSize({ width: 390, height: 844 })
97+
await page.evaluate(() => { document.documentElement.dir = "rtl" })
98+
await expect(summary.locator(".ctx-gist")).toBeVisible()
99+
expect(await panel.evaluate((el) => el.scrollWidth <= el.clientWidth + 1)).toBe(true)
100+
await shot("mobile-rtl")
101+
102+
expect(fixture.calls.filter((call) => !["GET", "HEAD", "OPTIONS"].includes(call.method))).toEqual([])
103+
console.log(`PASS context accounting ${app ? "native" : "browser"}: collapsed by default with gist, exact percent/bar/legend visible, keyboard expand with exact rows, persisted toggle, unknown handling, mobile RTL, zero mutations`)
104+
} finally {
105+
await app?.close()
106+
await browser?.close()
107+
await preview.close()
108+
if (profile) await rm(profile, { recursive: true, force: true })
109+
}

‎packages/es-app/test/session-peek.browser.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,10 @@ try {
5757
await page.goto(preview.url)
5858
await expect(page.locator(".session-info [data-section='context']")).toContainText("1 completed")
5959
await expect(page.locator(".session-info .ctx-exact")).toContainText("473k / 500k (95%)")
60+
// #157: exact per-class rows sit behind a collapsed disclosure whose gist stays visible
61+
await expect(page.locator(".session-info .ctx-accounting-disclosure > summary .ctx-gist")).toHaveText("cache read 100% · output 608")
62+
await expect(page.locator(".session-info .ctx-provider")).not.toBeVisible()
63+
await page.locator(".session-info .ctx-accounting-disclosure > summary").click()
6064
await expect(page.locator(".session-info .ctx-provider li", { hasText: "cache read" })).toContainText("471,919")
6165
await expect(page.locator(".session-info .ctx-provider li", { hasText: "uncached input" })).toContainText("3")
6266
await expect(page.locator(".session-info .ctx-provider li", { hasText: "cache write" })).toContainText("491")

0 commit comments

Comments
 (0)