Skip to content

Commit b1bcc8a

Browse files
committed
fix(tui): correct cost estimate tiers and subagent scope
1 parent 29cb79c commit b1bcc8a

6 files changed

Lines changed: 236 additions & 98 deletions

File tree

‎packages/tui/src/feature-plugins/prompt/footer.tsx‎

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,16 @@ export function PromptFooter(props: {
4646
)
4747
const cost = props.context.data.session.cost(props.sessionID)
4848
const estimate = enabled()
49-
? costEstimate(
50-
props.context.data.session
51-
.family(props.sessionID)
52-
.map((id) => props.context.data.session.get(id))
53-
.filter((info) => info !== undefined),
49+
? (costEstimate(
50+
session.parentID
51+
? [session]
52+
: props.context.data.session
53+
.family(props.sessionID)
54+
.map((id) => props.context.data.session.get(id))
55+
.filter((info) => info !== undefined),
5456
props.context.data.location.model.list(session.location),
55-
)
57+
(id) => props.context.data.session.message.list(id),
58+
) ?? 0)
5659
: 0
5760
return [
5861
usage ? formatContextUsage(usage.tokens, usage.percent) : undefined,

‎packages/tui/src/feature-plugins/sidebar/context.tsx‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,20 @@ export function SidebarContext(props: { context: Plugin.Context; sessionID: stri
2121

2222
const estimate = createMemo(() => {
2323
if (!enabled()) return 0
24+
const info = session()
25+
if (!info) return 0
2426
const data = props.context.data.session
25-
const models = props.context.data.location.model.list(session()?.location)
26-
return costEstimate(
27-
data.family(props.sessionID).map((id) => data.get(id)).filter((info) => info !== undefined),
28-
models,
27+
return (
28+
costEstimate(
29+
info.parentID
30+
? [info]
31+
: data
32+
.family(props.sessionID)
33+
.map((id) => data.get(id))
34+
.filter((info) => info !== undefined),
35+
props.context.data.location.model.list(info.location),
36+
(id) => data.message.list(id),
37+
) ?? 0
2938
)
3039
})
3140

‎packages/tui/src/util/session.ts‎

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { ModelInfo, SessionInfo, SessionMessageInfo } from "@opencode/client"
22
import { lastAssistantWithUsage } from "@opencode/client/solid"
3+
import { TokenUsage } from "@opencode/schema/token-usage"
34
import { Locale } from "./locale"
45

56
type SessionNode = {
@@ -65,32 +66,38 @@ export function formatContextUsage(tokens: number, percent?: number) {
6566
return percent === undefined ? value : `${value} (${percent}%)`
6667
}
6768

68-
/**
69-
* What the family's recorded tokens would cost at catalog prices. What an endpoint reported stays
70-
* authoritative (a reported zero is intentional, e.g. subscription billing), so this only fills the
71-
* display gap for sessions whose recorded cost is 0. Tokens price at each session's latest model.
72-
*/
73-
export function costEstimate(sessions: ReadonlyArray<SessionInfo>, models: ReadonlyArray<ModelInfo> | undefined) {
74-
return sessions.reduce((total, session) => {
69+
export function costEstimate(
70+
sessions: ReadonlyArray<SessionInfo>,
71+
models: ReadonlyArray<ModelInfo> | undefined,
72+
messages: (sessionID: string) => ReadonlyArray<SessionMessageInfo>,
73+
) {
74+
return sessions.reduce<number | undefined>((total, session) => {
75+
if (total === undefined) return
7576
const model = models?.find(
7677
(candidate) =>
7778
session.model && candidate.providerID === session.model.providerID && candidate.id === session.model.id,
7879
)
7980
if (!model) return total
80-
const tokens = session.tokens
81-
const context = tokens.input + tokens.cache.read + tokens.cache.write
82-
const tier = model.cost
83-
.filter((cost) => cost.tier?.type === "context" && context > cost.tier.size)
84-
.toSorted((a, b) => (b.tier?.size ?? 0) - (a.tier?.size ?? 0))[0]
85-
const rate = tier ?? model.cost.find((cost) => cost.tier === undefined)
86-
if (!rate) return total
87-
return (
88-
total +
89-
(tokens.input * rate.input +
90-
(tokens.output + tokens.reasoning) * rate.output +
91-
tokens.cache.read * rate.cache.read +
92-
tokens.cache.write * rate.cache.write) /
93-
1_000_000
94-
)
81+
const usages = model.cost.some((cost) => cost.tier !== undefined)
82+
? messages(session.id).flatMap((message) => ("tokens" in message && message.tokens ? [message.tokens] : []))
83+
: [session.tokens]
84+
// Lifetime totals cannot select per-call tiers. Paginated or unloaded history must not produce a partial estimate.
85+
if (usages.reduce((sum, tokens) => sum + TokenUsage.total(tokens), 0) !== TokenUsage.total(session.tokens)) return
86+
return usages.reduce((sum, tokens) => {
87+
const context = tokens.input + tokens.cache.read + tokens.cache.write
88+
const tier = model.cost
89+
.filter((cost) => cost.tier?.type === "context" && context > cost.tier.size)
90+
.toSorted((a, b) => (b.tier?.size ?? 0) - (a.tier?.size ?? 0))[0]
91+
const rate = tier ?? model.cost.find((cost) => cost.tier === undefined)
92+
if (!rate) return sum
93+
return (
94+
sum +
95+
(tokens.input * rate.input +
96+
(tokens.output + tokens.reasoning) * rate.output +
97+
tokens.cache.read * rate.cache.read +
98+
tokens.cache.write * rate.cache.write) /
99+
1_000_000
100+
)
101+
}, total)
95102
}, 0)
96103
}

‎packages/tui/test/feature-plugins/prompt-footer.test.tsx‎

Lines changed: 61 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -151,50 +151,67 @@ test("prompt footer can hide details", async () => {
151151
}
152152
})
153153

154-
test("prompt footer estimates spend from catalog prices when the provider reports $0", async () => {
155-
const color = RGBA.fromInts(200, 200, 200)
156-
const context = {
157-
location: { directory: "/workspace" },
158-
theme: { text: { base: color, muted: color } },
159-
keymap: { shortcuts: () => [] },
160-
data: {
161-
session: {
162-
family: () => ["session"],
163-
status: () => "idle",
164-
get: () => ({
165-
id: "session",
166-
location: { directory: "/workspace" },
167-
model: { providerID: "provider", id: "model" },
168-
tokens: { input: 1_000_000, output: 100_000, reasoning: 0, cache: { read: 2_000_000, write: 0 } },
169-
cost: 0,
170-
}),
171-
cost: () => 0,
172-
message: { list: () => [] },
173-
},
174-
shell: { list: () => [] },
175-
location: {
176-
model: {
177-
list: () => [{ providerID: "provider", id: "model", cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 0 } }] }],
154+
test.each([
155+
{ sessionID: "session", input: 500_000, expected: "≈ $12.60" },
156+
{ sessionID: "child", input: 500_000, expected: "≈ $1.50" },
157+
{ sessionID: "child", input: 0, expected: undefined },
158+
])(
159+
"prompt footer estimates $sessionID spend with $input child input tokens",
160+
async ({ sessionID, input, expected }) => {
161+
const color = RGBA.fromInts(200, 200, 200)
162+
const context = {
163+
location: { directory: "/workspace" },
164+
theme: { text: { base: color, muted: color } },
165+
keymap: { shortcuts: () => [] },
166+
data: {
167+
session: {
168+
family: () => ["session", "child", "sibling"],
169+
status: () => "idle",
170+
get: (id: string) => ({
171+
id,
172+
parentID: id === "session" ? undefined : "session",
173+
location: { directory: "/workspace" },
174+
model: { providerID: "provider", id: "model" },
175+
tokens:
176+
id === "session"
177+
? { input: 1_000_000, output: 100_000, reasoning: 0, cache: { read: 2_000_000, write: 0 } }
178+
: { input: id === "child" ? input : 2_000_000, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
179+
cost: 0,
180+
}),
181+
cost: () => 0,
182+
message: { list: () => [] },
183+
},
184+
shell: { list: () => [] },
185+
location: {
186+
model: {
187+
list: () => [
188+
{ providerID: "provider", id: "model", cost: [{ input: 3, output: 15, cache: { read: 0.3, write: 0 } }] },
189+
],
190+
},
178191
},
179192
},
180-
},
181-
} as unknown as Context
182-
const app = await testRender(
183-
() => (
184-
<ConfigProvider config={createTuiResolvedConfig({ experimental: { "cost-estimate": true } })}>
185-
<PromptFooter context={context} sessionID="session" mode="normal" showDetails={true} />
186-
</ConfigProvider>
187-
),
188-
{
189-
width: 80,
190-
height: 1,
191-
},
192-
)
193+
} as unknown as Context
194+
const app = await testRender(
195+
() => (
196+
<ConfigProvider config={createTuiResolvedConfig({ experimental: { "cost-estimate": true } })}>
197+
<PromptFooter context={context} sessionID={sessionID} mode="normal" showDetails={true} />
198+
</ConfigProvider>
199+
),
200+
{
201+
width: 80,
202+
height: 1,
203+
},
204+
)
193205

194-
try {
195-
await app.renderOnce()
196-
expect(app.captureCharFrame()).toContain("≈ $5.10")
197-
} finally {
198-
app.renderer.destroy()
199-
}
200-
})
206+
try {
207+
await app.renderOnce()
208+
if (expected === undefined) {
209+
expect(app.captureCharFrame()).not.toContain("≈")
210+
return
211+
}
212+
expect(app.captureCharFrame()).toContain(expected)
213+
} finally {
214+
app.renderer.destroy()
215+
}
216+
},
217+
)

‎packages/tui/test/feature-plugins/sidebar-context.test.tsx‎

Lines changed: 69 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { expect, test } from "bun:test"
33
import { RGBA } from "@opentui/core"
44
import { testRender } from "@opentui/solid"
55
import type { Context } from "@opencode/plugin/tui/context"
6+
import type { ModelInfo } from "@opencode/client"
67
import { ConfigProvider } from "../../src/config"
78
import { createTuiResolvedConfig } from "../fixture/tui-runtime"
89
import { SidebarContext } from "../../src/feature-plugins/sidebar/context"
@@ -16,8 +17,9 @@ function usage(input: number, output = 0, read = 0) {
1617
function context(options?: {
1718
cost?: number
1819
tokens?: number
19-
family?: Array<{ model?: { providerID: string; id: string }; tokens?: ReturnType<typeof usage> }>
20-
pricing?: typeof pricing
20+
steps?: Array<ReturnType<typeof usage>>
21+
family?: Array<{ parentID?: string; model?: { providerID: string; id: string }; tokens?: ReturnType<typeof usage> }>
22+
pricing?: ModelInfo["cost"]
2123
experiment?: boolean
2224
}) {
2325
const color = RGBA.fromInts(200, 200, 200)
@@ -29,44 +31,38 @@ function context(options?: {
2931
get: (id: string) => {
3032
if (!family) return { location: { directory: "/workspace" } }
3133
const index = id === "session" ? 0 : Number(id.replace("child-", ""))
32-
return family[index]
34+
return { ...family[index], id, location: { directory: "/workspace" } }
3335
},
3436
family: () => family?.map((_, index) => (index === 0 ? "session" : `child-${index}`)) ?? [],
3537
cost: () => options?.cost ?? 0,
3638
message: {
3739
list: () =>
38-
options?.tokens
39-
? [
40-
{
41-
id: "message",
42-
type: "assistant",
43-
model: { providerID: "provider", id: "model" },
44-
tokens: {
45-
input: options.tokens,
46-
output: 0,
47-
reasoning: 0,
48-
cache: { read: 0, write: 0 },
49-
},
50-
},
51-
]
52-
: [],
40+
(options?.steps ?? (options?.tokens ? [usage(options.tokens)] : [])).map((tokens, index) => ({
41+
id: `message-${index}`,
42+
type: "assistant",
43+
model: { providerID: "provider", id: "model" },
44+
tokens,
45+
})),
5346
},
5447
},
5548
location: {
5649
model: {
57-
list: () => (options?.pricing ? [{ providerID: "provider", id: "model", cost: options.pricing }] : []),
50+
list: () =>
51+
options?.pricing
52+
? [{ providerID: "provider", id: "model", cost: options.pricing, limit: { context: 0 } }]
53+
: [],
5854
},
5955
},
6056
},
6157
experiment: options?.experiment,
6258
}
6359
}
6460

65-
async function render(raw: ReturnType<typeof context>, width = 42) {
61+
async function render(raw: ReturnType<typeof context>, width = 42, sessionID = "session") {
6662
const app = await testRender(
6763
() => (
6864
<ConfigProvider config={createTuiResolvedConfig({ experimental: { "cost-estimate": raw.experiment === true } })}>
69-
<SidebarContext context={raw as unknown as Context} sessionID="session" />
65+
<SidebarContext context={raw as unknown as Context} sessionID={sessionID} />
7066
</ConfigProvider>
7167
),
7268
{ width, height: 8 },
@@ -139,6 +135,58 @@ test("sidebar keeps the reported cost over the estimate", async () => {
139135
}
140136
})
141137

138+
test.each([true, false])("sidebar uses per-call tiers only with complete history: %s", async (complete) => {
139+
const app = await render(
140+
context({
141+
experiment: true,
142+
family: [{ model: { providerID: "provider", id: "model" }, tokens: usage(300_000, 20_000) }],
143+
steps: complete ? [usage(150_000, 10_000), usage(150_000, 10_000)] : [usage(150_000, 10_000)],
144+
pricing: [
145+
...pricing,
146+
{ tier: { type: "context", size: 200_000 }, input: 6, output: 22.5, cache: { read: 0.6, write: 0 } },
147+
],
148+
}),
149+
)
150+
151+
try {
152+
await app.renderOnce()
153+
if (!complete) {
154+
expect(app.captureCharFrame()).not.toContain("spent")
155+
return
156+
}
157+
expect(app.captureCharFrame()).toContain("≈ $1.20 spent")
158+
} finally {
159+
app.renderer.destroy()
160+
}
161+
})
162+
163+
test.each([0, 500_000])("sidebar estimates only the selected child's %i input tokens", async (input) => {
164+
const app = await render(
165+
context({
166+
experiment: true,
167+
family: [
168+
{ model: { providerID: "provider", id: "model" }, tokens: usage(1_000_000) },
169+
{ parentID: "session", model: { providerID: "provider", id: "model" }, tokens: usage(input) },
170+
{ parentID: "session", model: { providerID: "provider", id: "model" }, tokens: usage(2_000_000) },
171+
],
172+
pricing,
173+
}),
174+
42,
175+
"child-1",
176+
)
177+
178+
try {
179+
await app.renderOnce()
180+
if (input === 0) {
181+
expect(app.captureCharFrame()).not.toContain("spent")
182+
return
183+
}
184+
expect(app.captureCharFrame()).toContain("≈ $1.50 spent")
185+
} finally {
186+
app.renderer.destroy()
187+
}
188+
})
189+
142190
test("sidebar hides the estimate while the experiment is off", async () => {
143191
const app = await render(
144192
context({

0 commit comments

Comments
 (0)