Skip to content

Commit 7b33bce

Browse files
usrnk1Hona
andauthored
feat(desktop): show session tokens and cost on the session view (anomalyco#53785)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
1 parent 46e4695 commit 7b33bce

11 files changed

Lines changed: 263 additions & 77 deletions

File tree

‎packages/app/e2e/regression/review.spec.ts‎

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ test("open file tab browses, searches, and tracks missing files", async ({ page
145145
const panel = page.locator("#review-panel")
146146
const sidebar = panel.locator('[data-slot="session-review-v2-sidebar"]')
147147
const sidebarToggle = panel.getByRole("button", { name: "Toggle file tree" })
148-
const contextButton = page.getByRole("button", { name: "View context usage" })
148+
const contextButton = page.getByRole("button", { name: "Toggle session context" })
149149
const openFile = panel.getByRole("button", { name: "Open file" })
150150
const tab = (name: string) => panel.getByRole("tab", { name, exact: true })
151151
await contextButton.click()
@@ -311,7 +311,7 @@ test("context closes the side region only when its button opened it", async ({ p
311311
})
312312
const panel = page.locator("#review-panel")
313313
const toggle = page.getByRole("button", { name: "Toggle review", exact: true })
314-
const contextButton = page.getByRole("button", { name: "View context usage" })
314+
const contextButton = page.getByRole("button", { name: "Toggle session context" })
315315
const context = panel.getByRole("tab", { name: "Context", exact: true })
316316

317317
await contextButton.click()
@@ -335,6 +335,83 @@ test("context closes the side region only when its button opened it", async ({ p
335335
await expect(panel.locator("#session-side-panel-review-tab")).toHaveAttribute("aria-selected", "true")
336336
})
337337

338+
test("context hides free-model cost but keeps paid-model zero cost", async ({ page }) => {
339+
const cases = [
340+
{ id: "ses_context_free", title: "Free model", model: "free", cost: 0, usage: false, text: "0" },
341+
{ id: "ses_context_paid", title: "Paid model", model: "paid", cost: 0, usage: false, text: "0·$0.00" },
342+
{ id: "ses_context_used", title: "Paid usage", model: "paid", cost: 1.25, usage: true, text: "2k·$1.25" },
343+
{ id: "ses_context_free_used", title: "Free usage", model: "free", cost: 0, usage: true, text: "2k" },
344+
{ id: "ses_context_mixed", title: "Previously paid", model: "free", cost: 1.25, usage: true, text: "2k·$1.25" },
345+
{ id: "ses_context_unknown", title: "Unknown pricing", model: "missing", cost: 0, usage: false, text: "0·$0.00" },
346+
{ id: "ses_context_output", title: "Output pricing", model: "output", cost: 0, usage: false, text: "0·$0.00" },
347+
// The root's model is free, but its subagent spent on a paid model: the family total shows.
348+
{ id: "ses_context_family", title: "Paid subagent", model: "free", cost: 0, usage: true, text: "2k·$1.25" },
349+
// A completed compaction resets the context until the next reply reports usage, as in the TUI.
350+
{ id: "ses_context_compacted", title: "Compacted", model: "paid", cost: 1.25, usage: true, text: "0·$1.25" },
351+
]
352+
353+
await openSession(page, {
354+
name: "ContextPricing",
355+
provider: provider(
356+
{ id: "free", name: "Free", cost: { input: 0, output: 0 } },
357+
{ id: "paid", name: "Paid", cost: { input: 1, output: 3 } },
358+
{ id: "output", name: "Output", cost: { input: 0, output: 1 } },
359+
),
360+
sessions: [
361+
...cases.map((item) => ({
362+
id: item.id,
363+
title: item.title,
364+
model: { id: item.model, providerID: "opencode" },
365+
cost: item.cost,
366+
})),
367+
{
368+
id: "ses_context_family_child",
369+
parentID: "ses_context_family",
370+
title: "Subagent run",
371+
model: { id: "paid", providerID: "opencode" },
372+
cost: 1.25,
373+
},
374+
],
375+
pageMessages: (id) => ({
376+
items: cases.flatMap((item): SessionMessageInfo[] =>
377+
item.id === id && item.usage
378+
? [
379+
{
380+
id: `msg_${item.id}`,
381+
type: "assistant",
382+
agent: "build",
383+
model: { id: item.model, providerID: "opencode" },
384+
tokens: { input: 1500, output: 500, reasoning: 0, cache: { read: 0, write: 0 } },
385+
content: [{ type: "text", text: "Done." }],
386+
time: { created: 1, completed: 2 },
387+
},
388+
...(item.id === "ses_context_compacted"
389+
? [
390+
{
391+
id: `msg_${item.id}_compaction`,
392+
type: "compaction" as const,
393+
status: "completed" as const,
394+
reason: "manual" as const,
395+
summary: "Current state",
396+
recent: "",
397+
time: { created: 3 },
398+
},
399+
]
400+
: []),
401+
]
402+
: [],
403+
),
404+
}),
405+
})
406+
const button = page.getByRole("button", { name: "Toggle session context", exact: true })
407+
408+
for (const item of cases) {
409+
await page.locator("[data-titlebar-tab-slot]", { hasText: item.title }).click()
410+
await expectSessionTitle(page, item.title)
411+
await expect(button).toHaveText(item.text)
412+
}
413+
})
414+
338415
test("file tree expands Windows paths and scrolls long names in both directions", async ({ page }) => {
339416
const directory = "C:/OpenCode/OpenFileExpand"
340417
const longFilename = "a-very-long-file-name-that-must-overflow-the-file-sidebar-instead-of-being-truncated.ts"
@@ -864,7 +941,7 @@ test("restores review state and the side-panel tab per session", async ({ page }
864941
await page.getByRole("option", { name: "Branch changes" }).click()
865942
await page.getByRole("button", { name: "beta.ts" }).click()
866943
await selectedFile("beta.ts")
867-
await page.getByRole("button", { name: "View context usage" }).click()
944+
await page.getByRole("button", { name: "Toggle session context" }).click()
868945
await selectedTab("Context")
869946

870947
await switchSession("Gamma review state")

‎packages/client/src/solid/data.ts‎

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import type {
2929
SessionMessageAssistantText,
3030
SessionMessageAssistantTool,
3131
SessionInfo,
32+
SessionListInput,
3233
SessionInboxInfo,
3334
SessionInboxCompaction,
3435
ShellInfo,
@@ -204,6 +205,8 @@ function createSync() {
204205
}
205206
}
206207

208+
const CHILD_PAGE = 200
209+
207210
export function createData(config: CreateDataInput) {
208211
const api = config.api
209212
let disposed = false
@@ -499,6 +502,16 @@ export function createData(config: CreateDataInput) {
499502
return created
500503
}
501504

505+
// Every direct subagent, not only the server's default first page, so a root's family cost
506+
// counts all of them. Pages stay newest first, the order the family index has always used.
507+
async function listChildren(input: SessionListInput): Promise<SessionInfo[]> {
508+
const page = await api().session.list(input)
509+
510+
if (page.data.length < CHILD_PAGE || !page.cursor.next) return page.data
511+
512+
return [...page.data, ...(await listChildren({ cursor: page.cursor.next, limit: CHILD_PAGE }))]
513+
}
514+
502515
// Walk parentID upward through loaded session info to the family root. When a
503516
// parent's info is missing, that missing ID is the furthest-known ancestor and
504517
// is returned so orphan subtrees group under it until the parent arrives. A
@@ -1619,11 +1632,7 @@ export function createData(config: CreateDataInput) {
16191632
return sync.run(options?.children ? `session.family:${sessionID}` : `session:${sessionID}`, async () => {
16201633
const [info, children] = await Promise.all([
16211634
api().session.get({ sessionID }),
1622-
options?.children
1623-
? api()
1624-
.session.list({ parentID: sessionID, order: "desc" })
1625-
.then((response) => response.data)
1626-
: [],
1635+
options?.children ? listChildren({ parentID: sessionID, order: "desc", limit: CHILD_PAGE }) : [],
16271636
])
16281637
const sessions = [info, ...children]
16291638
batch(() => {

‎packages/client/src/solid/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export * from "./data"
22
export * from "./connection"
33
export * from "./pty"
4+
export * from "./usage"

‎packages/client/src/solid/usage.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import type { SessionMessageAssistant, SessionMessageInfo } from "../promise"
2+
3+
/**
4+
* The assistant step whose tokens fill the context window now: the latest one after the last completed
5+
* compaction and before the revert boundary. Every client shows context usage from this step, so the TUI
6+
* and the desktop app agree on it.
7+
*/
8+
export function lastAssistantWithUsage(messages: ReadonlyArray<SessionMessageInfo>, boundary?: string) {
9+
const boundaryIndex = boundary ? messages.findIndex((message) => message.id === boundary) : -1
10+
11+
if (boundary && boundaryIndex === -1) return undefined
12+
const end = boundaryIndex === -1 ? messages.length : boundaryIndex
13+
14+
const compactionIndex = messages.findLastIndex(
15+
(message, index) => message.type === "compaction" && message.status === "completed" && index < end,
16+
)
17+
18+
return messages.findLast(
19+
(message, index): message is SessionMessageAssistant & { tokens: NonNullable<SessionMessageAssistant["tokens"]> } =>
20+
message.type === "assistant" && message.tokens !== undefined && index > compactionIndex && index < end,
21+
)
22+
}

‎packages/client/test/solid-data.test.ts‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,47 @@ test("uses the configured initial window and retains normal cursor page sizes",
5252
}
5353
})
5454

55+
test("counts every subagent page in a root session's cost", async () => {
56+
const child = (index: number): SessionInfo => ({
57+
...session(0),
58+
id: `ses_child_${index}`,
59+
parentID: "ses_root",
60+
cost: 1,
61+
})
62+
const requests: string[] = []
63+
const api = OpenCode.make({
64+
baseUrl: "http://opencode.local",
65+
fetch: async (input, init) => {
66+
const url = new URL((input instanceof Request ? input : new Request(input, init)).url)
67+
requests.push(`${url.pathname}?${url.searchParams}`)
68+
69+
if (url.pathname === "/api/session/ses_root") return Response.json({ data: { ...session(0), id: "ses_root", cost: 0.5 } })
70+
71+
if (url.searchParams.get("cursor") === "page_2")
72+
return Response.json({ data: Array.from({ length: 50 }, (_, index) => child(200 + index)), cursor: { next: "page_3" } })
73+
74+
return Response.json({ data: Array.from({ length: 200 }, (_, index) => child(index)), cursor: { next: "page_2" } })
75+
},
76+
})
77+
const setup = createRoot((dispose) => ({
78+
data: createData({ api: () => api, directory: "/project", event: { on: () => () => {}, listen: () => () => {} } }),
79+
dispose,
80+
}))
81+
82+
try {
83+
await setup.data.session.sync("ses_root", { children: true })
84+
expect(setup.data.session.family("ses_root")).toHaveLength(251)
85+
expect(setup.data.session.cost("ses_root")).toBe(250.5)
86+
expect(requests.toSorted()).toEqual([
87+
"/api/session/ses_root?",
88+
"/api/session?limit=200&cursor=page_2",
89+
"/api/session?limit=200&order=desc&parentID=ses_root",
90+
])
91+
} finally {
92+
setup.dispose()
93+
}
94+
})
95+
5596
test("keeps the previous model in a live variant notice until the projected message arrives", async () => {
5697
const projected = Promise.withResolvers<void>()
5798
const previous = { providerID: "provider", id: "model", variant: "high" }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { describe, expect, test } from "bun:test"
2+
import type { SessionMessageInfo } from "../src/promise"
3+
import { lastAssistantWithUsage } from "../src/solid/usage"
4+
5+
const assistant = (id: string, input: number): SessionMessageInfo => ({
6+
id,
7+
type: "assistant",
8+
agent: "build",
9+
model: { id: "model", providerID: "provider" },
10+
content: [],
11+
tokens: { input, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
12+
time: { created: 0 },
13+
})
14+
15+
describe("lastAssistantWithUsage", () => {
16+
test("tracks usage across undo and redo boundaries", () => {
17+
const messages = [assistant("msg_z", 10), assistant("msg_a", 30)]
18+
19+
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
20+
expect(lastAssistantWithUsage(messages, "msg_a")?.tokens.input).toBe(10)
21+
expect(lastAssistantWithUsage(messages, "msg_missing")).toBeUndefined()
22+
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
23+
})
24+
25+
test("resets usage at completed compaction until the next assistant reports it", () => {
26+
const compaction: SessionMessageInfo = {
27+
id: "msg_compaction",
28+
type: "compaction",
29+
status: "completed",
30+
reason: "manual",
31+
summary: "Current state",
32+
recent: "",
33+
time: { created: 0 },
34+
}
35+
36+
const messages = [assistant("msg_before", 30), compaction]
37+
38+
expect(lastAssistantWithUsage(messages)).toBeUndefined()
39+
40+
messages.push(assistant("msg_after", 5))
41+
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(5)
42+
})
43+
})

‎packages/gui-extensions/src/context/i18n/en.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ export default {
55
"usage.usage": "Context",
66
"usage.cost": "Cost",
77
"usage.view": "View context usage",
8+
"usage.toggle": "Toggle session context",
89
"systemPrompt.title": "System Prompt",
910
"rawMessages.title": "Raw messages",
1011
"export.session": "Export session",

0 commit comments

Comments
 (0)