mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-21 04:12:08 +03:00
feat(desktop): show session tokens and cost on the session view (#53785)
Co-authored-by: LukeParkerDev <10430890+Hona@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
46e4695b96
commit
7b33bcea4e
@@ -29,6 +29,7 @@ import type {
|
||||
SessionMessageAssistantText,
|
||||
SessionMessageAssistantTool,
|
||||
SessionInfo,
|
||||
SessionListInput,
|
||||
SessionInboxInfo,
|
||||
SessionInboxCompaction,
|
||||
ShellInfo,
|
||||
@@ -204,6 +205,8 @@ function createSync() {
|
||||
}
|
||||
}
|
||||
|
||||
const CHILD_PAGE = 200
|
||||
|
||||
export function createData(config: CreateDataInput) {
|
||||
const api = config.api
|
||||
let disposed = false
|
||||
@@ -499,6 +502,16 @@ export function createData(config: CreateDataInput) {
|
||||
return created
|
||||
}
|
||||
|
||||
// Every direct subagent, not only the server's default first page, so a root's family cost
|
||||
// counts all of them. Pages stay newest first, the order the family index has always used.
|
||||
async function listChildren(input: SessionListInput): Promise<SessionInfo[]> {
|
||||
const page = await api().session.list(input)
|
||||
|
||||
if (page.data.length < CHILD_PAGE || !page.cursor.next) return page.data
|
||||
|
||||
return [...page.data, ...(await listChildren({ cursor: page.cursor.next, limit: CHILD_PAGE }))]
|
||||
}
|
||||
|
||||
// Walk parentID upward through loaded session info to the family root. When a
|
||||
// parent's info is missing, that missing ID is the furthest-known ancestor and
|
||||
// is returned so orphan subtrees group under it until the parent arrives. A
|
||||
@@ -1619,11 +1632,7 @@ export function createData(config: CreateDataInput) {
|
||||
return sync.run(options?.children ? `session.family:${sessionID}` : `session:${sessionID}`, async () => {
|
||||
const [info, children] = await Promise.all([
|
||||
api().session.get({ sessionID }),
|
||||
options?.children
|
||||
? api()
|
||||
.session.list({ parentID: sessionID, order: "desc" })
|
||||
.then((response) => response.data)
|
||||
: [],
|
||||
options?.children ? listChildren({ parentID: sessionID, order: "desc", limit: CHILD_PAGE }) : [],
|
||||
])
|
||||
const sessions = [info, ...children]
|
||||
batch(() => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export * from "./data"
|
||||
export * from "./connection"
|
||||
export * from "./pty"
|
||||
export * from "./usage"
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { SessionMessageAssistant, SessionMessageInfo } from "../promise"
|
||||
|
||||
/**
|
||||
* The assistant step whose tokens fill the context window now: the latest one after the last completed
|
||||
* compaction and before the revert boundary. Every client shows context usage from this step, so the TUI
|
||||
* and the desktop app agree on it.
|
||||
*/
|
||||
export function lastAssistantWithUsage(messages: ReadonlyArray<SessionMessageInfo>, boundary?: string) {
|
||||
const boundaryIndex = boundary ? messages.findIndex((message) => message.id === boundary) : -1
|
||||
|
||||
if (boundary && boundaryIndex === -1) return undefined
|
||||
const end = boundaryIndex === -1 ? messages.length : boundaryIndex
|
||||
|
||||
const compactionIndex = messages.findLastIndex(
|
||||
(message, index) => message.type === "compaction" && message.status === "completed" && index < end,
|
||||
)
|
||||
|
||||
return messages.findLast(
|
||||
(message, index): message is SessionMessageAssistant & { tokens: NonNullable<SessionMessageAssistant["tokens"]> } =>
|
||||
message.type === "assistant" && message.tokens !== undefined && index > compactionIndex && index < end,
|
||||
)
|
||||
}
|
||||
@@ -52,6 +52,47 @@ test("uses the configured initial window and retains normal cursor page sizes",
|
||||
}
|
||||
})
|
||||
|
||||
test("counts every subagent page in a root session's cost", async () => {
|
||||
const child = (index: number): SessionInfo => ({
|
||||
...session(0),
|
||||
id: `ses_child_${index}`,
|
||||
parentID: "ses_root",
|
||||
cost: 1,
|
||||
})
|
||||
const requests: string[] = []
|
||||
const api = OpenCode.make({
|
||||
baseUrl: "http://opencode.local",
|
||||
fetch: async (input, init) => {
|
||||
const url = new URL((input instanceof Request ? input : new Request(input, init)).url)
|
||||
requests.push(`${url.pathname}?${url.searchParams}`)
|
||||
|
||||
if (url.pathname === "/api/session/ses_root") return Response.json({ data: { ...session(0), id: "ses_root", cost: 0.5 } })
|
||||
|
||||
if (url.searchParams.get("cursor") === "page_2")
|
||||
return Response.json({ data: Array.from({ length: 50 }, (_, index) => child(200 + index)), cursor: { next: "page_3" } })
|
||||
|
||||
return Response.json({ data: Array.from({ length: 200 }, (_, index) => child(index)), cursor: { next: "page_2" } })
|
||||
},
|
||||
})
|
||||
const setup = createRoot((dispose) => ({
|
||||
data: createData({ api: () => api, directory: "/project", event: { on: () => () => {}, listen: () => () => {} } }),
|
||||
dispose,
|
||||
}))
|
||||
|
||||
try {
|
||||
await setup.data.session.sync("ses_root", { children: true })
|
||||
expect(setup.data.session.family("ses_root")).toHaveLength(251)
|
||||
expect(setup.data.session.cost("ses_root")).toBe(250.5)
|
||||
expect(requests.toSorted()).toEqual([
|
||||
"/api/session/ses_root?",
|
||||
"/api/session?limit=200&cursor=page_2",
|
||||
"/api/session?limit=200&order=desc&parentID=ses_root",
|
||||
])
|
||||
} finally {
|
||||
setup.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps the previous model in a live variant notice until the projected message arrives", async () => {
|
||||
const projected = Promise.withResolvers<void>()
|
||||
const previous = { providerID: "provider", id: "model", variant: "high" }
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { SessionMessageInfo } from "../src/promise"
|
||||
import { lastAssistantWithUsage } from "../src/solid/usage"
|
||||
|
||||
const assistant = (id: string, input: number): SessionMessageInfo => ({
|
||||
id,
|
||||
type: "assistant",
|
||||
agent: "build",
|
||||
model: { id: "model", providerID: "provider" },
|
||||
content: [],
|
||||
tokens: { input, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
|
||||
time: { created: 0 },
|
||||
})
|
||||
|
||||
describe("lastAssistantWithUsage", () => {
|
||||
test("tracks usage across undo and redo boundaries", () => {
|
||||
const messages = [assistant("msg_z", 10), assistant("msg_a", 30)]
|
||||
|
||||
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
|
||||
expect(lastAssistantWithUsage(messages, "msg_a")?.tokens.input).toBe(10)
|
||||
expect(lastAssistantWithUsage(messages, "msg_missing")).toBeUndefined()
|
||||
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(30)
|
||||
})
|
||||
|
||||
test("resets usage at completed compaction until the next assistant reports it", () => {
|
||||
const compaction: SessionMessageInfo = {
|
||||
id: "msg_compaction",
|
||||
type: "compaction",
|
||||
status: "completed",
|
||||
reason: "manual",
|
||||
summary: "Current state",
|
||||
recent: "",
|
||||
time: { created: 0 },
|
||||
}
|
||||
|
||||
const messages = [assistant("msg_before", 30), compaction]
|
||||
|
||||
expect(lastAssistantWithUsage(messages)).toBeUndefined()
|
||||
|
||||
messages.push(assistant("msg_after", 5))
|
||||
expect(lastAssistantWithUsage(messages)?.tokens.input).toBe(5)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user