opencode-model-costs 0.0.0-stage → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tui.tsx ADDED
@@ -0,0 +1,898 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import { Plugin } from "@opencode/plugin/tui"
3
+ import { CliRenderEvents, InputRenderable, type KeyEvent } from "@opentui/core"
4
+ import { Show, createEffect, createMemo, createSignal, getOwner, onCleanup } from "solid-js"
5
+ import type { Context as TuiContext } from "@opencode/plugin/tui/context"
6
+ import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
7
+ import {
8
+ type CostData,
9
+ type CostTier,
10
+ type ModelRow,
11
+ fetchCostData,
12
+ findRow,
13
+ fitDialogSize,
14
+ fitsDialogWidth,
15
+ fmtBadge,
16
+ fmtK,
17
+ fmtMoney,
18
+ fmtRates,
19
+ switchSessionModel,
20
+ } from "./costs"
21
+
22
+ // ---------------------------------------------------------------------------
23
+ // Table dialog — line model
24
+ // ---------------------------------------------------------------------------
25
+
26
+ /** Two-plus spaces between columns; money columns are right-aligned. */
27
+ const GAP = " "
28
+ /** Rows visible in the dialog's list before it scrolls. */
29
+ const MAX_VIEWPORT_ROWS = 18
30
+
31
+ /** One display line of the dialog list. */
32
+ type LineData =
33
+ | { kind: "header" }
34
+ | { kind: "rule" }
35
+ | { kind: "spacer" }
36
+ | { kind: "provider"; name: string }
37
+ | { kind: "model"; row: ModelRow }
38
+ | { kind: "tier"; row: ModelRow; tier: CostTier; index: number }
39
+
40
+ interface ColumnWidths {
41
+ model: number
42
+ money: [number, number, number, number]
43
+ /** 0 when no line has a context value — the column is dropped then. */
44
+ ctx: number
45
+ /** Full rendered line width, including gaps (the header rule's length). */
46
+ total: number
47
+ }
48
+
49
+ /** The row supports more fields than the published type lists; optional access keeps older hosts happy. */
50
+ type CurrentModel = { providerID?: string; modelID?: string }
51
+
52
+ type SetComposerModel = (row: ModelRow) => void
53
+ const HOME = Symbol("home")
54
+ type SwitchTarget = string | typeof HOME
55
+
56
+ /** OpenCode 2.3.2 keeps the native model setter in its Solid local context. */
57
+ function findComposerModelSetter(): SetComposerModel | undefined {
58
+ const contexts = getOwner()?.context
59
+ if (!contexts) return undefined
60
+
61
+ for (const key of Object.getOwnPropertySymbols(contexts)) {
62
+ const model = contexts[key]?.model
63
+ if (
64
+ typeof model?.set === "function" &&
65
+ typeof model?.selection === "function" &&
66
+ typeof model?.trackSessionCommit === "function"
67
+ ) {
68
+ return (row) => model.set({ providerID: row.providerID, modelID: row.modelID })
69
+ }
70
+ }
71
+ return undefined
72
+ }
73
+
74
+ interface Palette {
75
+ muted?: string
76
+ accent?: string
77
+ /** Search-input caret color (theme form-field focused text). */
78
+ cursor?: string
79
+ /** Focused search-input text (theme form-field base text). */
80
+ inputText?: string
81
+ }
82
+
83
+ const MONEY_HEADERS: [string, string, string, string] = ["in", "out", "read", "write"]
84
+ const MONEY_BLANKS: [string, string, string, string] = ["", "", "", ""]
85
+
86
+ /** The four money cells of a line: rates for models ("—" when not set), blanks for every other line. */
87
+ function moneyFor(line: LineData): [string, string, string, string] {
88
+ if (line.kind === "model") return moneyValues(line.row.tiers[0])
89
+ if (line.kind === "tier") return moneyValues(line.tier)
90
+ return MONEY_BLANKS
91
+ }
92
+
93
+ /** "in $6 · out $22 · cache read $0.55 · cache write $5.5" as four column values ("—" when absent). */
94
+ function moneyValues(tier: CostTier | undefined): [string, string, string, string] {
95
+ if (!tier) return ["—", "—", "—", "—"]
96
+ return [fmtMoney(tier.input), fmtMoney(tier.output), fmtMoney(tier.cache?.read), fmtMoney(tier.cache?.write)]
97
+ }
98
+
99
+ /** The model-column text of a line. */
100
+ function modelCell(line: LineData): string {
101
+ if (line.kind === "header") return "model"
102
+ if (line.kind === "provider") return line.name
103
+ if (line.kind === "tier") {
104
+ const size = line.tier.tier?.size
105
+ return size && size > 0 ? `↳ over ${fmtK(size)} ctx` : `↳ tier ${line.index + 1}`
106
+ }
107
+ if (line.kind === "model") {
108
+ const threshold = line.row.tiers[0]?.tier?.size
109
+ return threshold ? `${line.row.modelID} · over ${fmtK(threshold)} ctx` : line.row.modelID
110
+ }
111
+ return ""
112
+ }
113
+
114
+ /** The ctx-column text of a line (context limit of base model rows only). */
115
+ function ctxCell(line: LineData): string {
116
+ if (line.kind !== "model") return ""
117
+ return line.row.contextLimit && line.row.contextLimit > 0 ? fmtK(line.row.contextLimit) : ""
118
+ }
119
+
120
+ /** Provider section rows + model rows + extra-tier sub-rows, in dialog order. */
121
+ function buildLines(rows: readonly ModelRow[]): LineData[] {
122
+ const lines: LineData[] = [{ kind: "header" }, { kind: "rule" }, { kind: "spacer" }]
123
+ let lastProvider: string | undefined
124
+ for (const row of rows) {
125
+ if (row.providerID !== lastProvider) {
126
+ if (lastProvider !== undefined) lines.push({ kind: "spacer" })
127
+ lines.push({ kind: "provider", name: row.providerName })
128
+ lastProvider = row.providerID
129
+ }
130
+ lines.push({ kind: "model", row })
131
+ lines.push(...tierLines(row))
132
+ }
133
+ return lines
134
+ }
135
+
136
+ /** Column widths fitted to the longest cell of each column (headers included). */
137
+ function computeWidths(lines: readonly LineData[]): ColumnWidths {
138
+ const money: [number, number, number, number] = MONEY_HEADERS.map((header) => header.length) as [
139
+ number,
140
+ number,
141
+ number,
142
+ number,
143
+ ]
144
+ let model = "model".length
145
+ let ctx = "ctx".length
146
+ let ctxUsed = false
147
+ for (const line of lines) {
148
+ model = Math.max(model, modelCell(line).length)
149
+ for (const [index, value] of moneyFor(line).entries()) money[index] = Math.max(money[index], value.length)
150
+ const cell = ctxCell(line)
151
+ if (cell) {
152
+ ctx = Math.max(ctx, cell.length)
153
+ ctxUsed = true
154
+ }
155
+ }
156
+ // No line carries a context value — the column is dropped to save width.
157
+ if (!ctxUsed) ctx = 0
158
+ const total =
159
+ 2 + model + money.reduce((sum, width) => sum + GAP.length + width, 0) + (ctx > 0 ? GAP.length + ctx : 0)
160
+ return { model, money, ctx, total }
161
+ }
162
+
163
+ /** Extra pricing tiers of a model as sub-lines. */
164
+ function tierLines(row: ModelRow): LineData[] {
165
+ return row.tiers
166
+ .slice(1)
167
+ .map((tier, index) => ({ kind: "tier" as const, row, tier, index: index + 1 }))
168
+ }
169
+
170
+ /**
171
+ * The padded text of one line. `selected` highlights the model line and its
172
+ * tier sub-lines; `current` marks the session's active model.
173
+ */
174
+ function lineText(
175
+ line: LineData,
176
+ widths: ColumnWidths,
177
+ state: { selected: boolean; current: CurrentModel | undefined },
178
+ ): string {
179
+ if (line.kind === "rule") return "─".repeat(widths.total)
180
+ if (line.kind === "spacer") return ""
181
+
182
+ const isHeader = line.kind === "header"
183
+ const marker =
184
+ line.kind === "model"
185
+ ? state.selected
186
+ ? "▶"
187
+ : line.row.isDefault
188
+ ? "★"
189
+ : isCurrent(line.row, state.current)
190
+ ? "●"
191
+ : " "
192
+ : line.kind === "tier"
193
+ ? state.selected
194
+ ? "▶"
195
+ : " "
196
+ : " "
197
+ const cells = [`${marker} ${modelCell(line).padEnd(widths.model)}`]
198
+ const money = isHeader ? MONEY_HEADERS : moneyFor(line)
199
+ for (const [index, value] of money.entries()) cells.push(GAP + value.padStart(widths.money[index]))
200
+ if (widths.ctx > 0) cells.push(GAP + (isHeader ? "ctx" : ctxCell(line)).padStart(widths.ctx))
201
+ return cells.join("")
202
+ }
203
+
204
+ function isCurrent(row: ModelRow, current: CurrentModel | undefined): boolean {
205
+ return !!current && row.providerID === current.providerID && row.modelID === current.modelID
206
+ }
207
+
208
+ /** Indexes into `lines` that the cursor can rest on (model rows only). */
209
+ function selectableIndexes(lines: readonly LineData[]): number[] {
210
+ return lines.map((line, index) => (line.kind === "model" ? index : -1)).filter((index) => index >= 0)
211
+ }
212
+
213
+ /** The visible table after a type-to-filter query: base rows + their tier sub-rows, grouped by provider. */
214
+ type FilteredTable = {
215
+ lines: LineData[]
216
+ selectable: number[]
217
+ }
218
+
219
+ /** Case-insensitive substring match against every model identity the user could type. */
220
+ function matchesQuery(row: ModelRow, needle: string): boolean {
221
+ return (
222
+ row.modelID.toLowerCase().includes(needle) ||
223
+ row.modelName?.toLowerCase().includes(needle) === true ||
224
+ row.providerID.toLowerCase().includes(needle) ||
225
+ row.providerName.toLowerCase().includes(needle)
226
+ )
227
+ }
228
+
229
+ /**
230
+ * Applies the search query to the static line list: an empty query returns all
231
+ * lines; otherwise only matching model rows survive (with their tier sub-rows
232
+ * and a single provider section row per provider, rebuilding the same
233
+ * header/rule/spacer structure as `buildLines`).
234
+ */
235
+ function filterLines(lines: readonly LineData[], query: string): FilteredTable {
236
+ const needle = query.trim().toLowerCase()
237
+ if (!needle) return { lines: [...lines], selectable: selectableIndexes(lines) }
238
+ const out: LineData[] = [{ kind: "header" }, { kind: "rule" }, { kind: "spacer" }]
239
+ const selectable: number[] = []
240
+ let lastProvider: string | undefined
241
+ for (const line of lines) {
242
+ if (line.kind !== "model" || !matchesQuery(line.row, needle)) continue
243
+ if (line.row.providerID !== lastProvider) {
244
+ if (lastProvider !== undefined) out.push({ kind: "spacer" })
245
+ out.push({ kind: "provider", name: line.row.providerName })
246
+ lastProvider = line.row.providerID
247
+ }
248
+ selectable.push(out.length)
249
+ out.push(line)
250
+ out.push(...tierLines(line.row))
251
+ }
252
+ return { lines: out, selectable }
253
+ }
254
+
255
+ export default Plugin.define({
256
+ id: "opencode-model-costs.tui",
257
+ setup(context) {
258
+ const [data, setData] = createSignal<CostData>({ rows: [], hasAuthoredConfig: false })
259
+ let disposed = false
260
+ let refreshID = 0
261
+ let opening = false
262
+ const footer = context.options?.footer !== false
263
+
264
+ const refresh = async (): Promise<CostData> => {
265
+ const id = ++refreshID
266
+ const result = await fetchCostData(context.client, context.location).catch(() => ({
267
+ rows: [], hasAuthoredConfig: false, configUnavailable: true,
268
+ }))
269
+ if (!disposed && id === refreshID) setData(result)
270
+ return result
271
+ }
272
+ if (footer) void refresh()
273
+
274
+ let stopConfigChanged: (() => void) | undefined
275
+ try {
276
+ stopConfigChanged = context.data.on("config.updated", () => {
277
+ if (footer) void refresh()
278
+ })
279
+ } catch {
280
+ // Event type unavailable on this server — the command always reads fresh data anyway.
281
+ }
282
+
283
+ const unregisterSlot = footer ? context.ui.slot?.({
284
+ append: "prompt.footer.status",
285
+ render: () => <CostBadge context={context} data={data} />,
286
+ }) : undefined
287
+
288
+ const resolveSwitchTarget = (): SwitchTarget | undefined => {
289
+ const route = context.ui.router?.current?.() as
290
+ | { type?: string; sessionID?: string; name?: string; params?: { sessionID?: string } }
291
+ | undefined
292
+ if (route?.type === "home" || route?.name === "home") return HOME
293
+ if (route?.type === "session" && typeof route?.sessionID === "string" && route.sessionID) {
294
+ return route.sessionID
295
+ }
296
+ // Transitional/alternative route shape.
297
+ if (route?.name === "session" && typeof route?.params?.sessionID === "string" && route.params.sessionID) {
298
+ return route.params.sessionID
299
+ }
300
+ return undefined
301
+ }
302
+
303
+ /**
304
+ * Refreshes the session's info after a switch. The TUI only applies
305
+ * `session.model.selected` when the session row is already in its local
306
+ * store — which, for a session that has not been prompted yet, may not be
307
+ * loaded, so the switch event can be dropped client-side and the composer
308
+ * keeps the old model. Re-reading the session makes the durable model (and
309
+ * with it the badge and the effort options) visible immediately.
310
+ */
311
+ const refreshSessionInfo = async (sessionID: string) => {
312
+ try {
313
+ context.data.session?.invalidate?.(sessionID)
314
+ await context.data.session?.sync?.(sessionID)
315
+ } catch {
316
+ // Best-effort: the switch itself already succeeded; the composer reflects the durable model on its next read.
317
+ }
318
+ }
319
+
320
+ const applyRow = async (
321
+ row: ModelRow,
322
+ target: SwitchTarget,
323
+ setComposerModel: SetComposerModel | undefined,
324
+ variant?: string,
325
+ ) => {
326
+ if (disposed || resolveSwitchTarget() !== target) return
327
+ const model = `${row.providerID}/${row.modelID}`
328
+ const selection = variant ? `${model}#${variant}` : model
329
+ try {
330
+ if (target !== HOME) {
331
+ await switchSessionModel(context.client, target, row, variant)
332
+ await refreshSessionInfo(target)
333
+ }
334
+ if (disposed || resolveSwitchTarget() !== target) return
335
+ const modelUI = context.ui.model
336
+ const hasVariant = (current: { variant?: string } | undefined) =>
337
+ (current?.variant ?? "default") === (variant ?? "default")
338
+ const matchesSelection = () => {
339
+ const current = modelUI?.current?.()
340
+ return isCurrent(row, current) && hasVariant(current)
341
+ }
342
+ if (typeof modelUI?.current === "function" && !matchesSelection()) {
343
+ // A native picker draft can take precedence over the synced session model.
344
+ try {
345
+ if (!isCurrent(row, modelUI.current())) setComposerModel?.(row)
346
+ const current = modelUI.current()
347
+ if (isCurrent(row, current) && !hasVariant(current)) modelUI.variant?.set?.(variant)
348
+ } catch {
349
+ // The native picker is still available if the host's local context changed.
350
+ }
351
+ }
352
+ if (!matchesSelection() && (target === HOME || typeof modelUI?.current === "function")) {
353
+ const openPicker = await context.ui.dialog.confirm({
354
+ title: "Composer model still needs updating",
355
+ message: [
356
+ target === HOME
357
+ ? "OpenCode could not update the model for the next prompt."
358
+ : `The session saved ${selection}, but the prompt still has a different selection.`,
359
+ `Choose ${model} in /models${row.variantIDs.length ? ` and select ${variant ?? "Default"} effort` : ""}.`,
360
+ ].join(" "),
361
+ label: { confirm: "Open model picker", cancel: "Close" },
362
+ })
363
+ if (openPicker && !disposed && resolveSwitchTarget() === target) {
364
+ context.keymap?.dispatch?.("model.list")
365
+ }
366
+ return
367
+ }
368
+
369
+ context.ui.toast.show({
370
+ title: target === HOME ? "Model selected" : "Model switched",
371
+ message: target === HOME ? `Selected ${selection} for the next prompt` : `Switched to ${selection}`,
372
+ variant: "success",
373
+ })
374
+ } catch (error) {
375
+ if (disposed) return
376
+ context.ui.toast.show({
377
+ title: "Model switch failed",
378
+ message: error instanceof Error ? error.message : String(error),
379
+ variant: "error",
380
+ })
381
+ }
382
+ }
383
+
384
+ // Handlers of the open dialog; the component reads the same cursor state.
385
+ let dialogControls:
386
+ | {
387
+ move(delta: number): void
388
+ page(direction: number): void
389
+ first(): void
390
+ last(): void
391
+ confirm(): void
392
+ query(next: string): void
393
+ close(): void
394
+ }
395
+ | undefined
396
+
397
+ const inspectRow = async (
398
+ row: ModelRow,
399
+ target: SwitchTarget | undefined,
400
+ setComposerModel: SetComposerModel | undefined,
401
+ ) => {
402
+ const lines = row.tiers.map((tier) =>
403
+ `${tier.tier ? `Over ${fmtK(tier.tier.size)} context` : "Base"}: ${fmtRates(tier)}`,
404
+ )
405
+ const source = row.tiers.length === 0 ? "Rates unavailable" : row.costFromConfig ? "Config override" : "Catalog rate"
406
+ const message = [
407
+ `${source} · USD per million tokens`,
408
+ ...lines,
409
+ row.contextLimit ? `Context limit: ${fmtK(row.contextLimit)} tokens` : undefined,
410
+ ].filter(Boolean).join("\n")
411
+ const title = `${row.providerID}/${row.modelID}`
412
+ if (target !== undefined && resolveSwitchTarget() === target) {
413
+ const confirmed = await context.ui.dialog.confirm({
414
+ title,
415
+ message,
416
+ label: { confirm: row.variantIDs.length ? "Choose reasoning effort" : "Switch to this model", cancel: "Close" },
417
+ })
418
+ if (!confirmed || disposed || resolveSwitchTarget() !== target) return
419
+ if (row.variantIDs.length === 0) {
420
+ await applyRow(row, target, setComposerModel)
421
+ return
422
+ }
423
+ const picked = await context.ui.dialog.select<{ variant?: string }>({
424
+ title: "Reasoning effort · " + row.modelID,
425
+ options: [
426
+ { title: "Default", value: {} },
427
+ ...row.variantIDs.map((variant) => ({ title: variant, value: { variant } })),
428
+ ],
429
+ })
430
+ if (picked) await applyRow(row, target, setComposerModel, picked.variant)
431
+ } else {
432
+ await context.ui.dialog.alert({ title, message })
433
+ }
434
+ }
435
+
436
+ const showSelectDialog = async (rows: readonly ModelRow[], target: SwitchTarget | undefined) => {
437
+ let setComposerModel: SetComposerModel | undefined
438
+ const picked = await context.ui.dialog.select({
439
+ title: "Model costs · in/out $/1M",
440
+ options: rows.map((row) => {
441
+ const base = row.tiers.find((tier) => !tier.tier)
442
+ return {
443
+ title: row.modelID,
444
+ description: base ? `${fmtMoney(base.input)}/${fmtMoney(base.output)}` : row.tiers.length ? "Tiered" : "—",
445
+ category: row.providerName,
446
+ value: row,
447
+ }
448
+ }),
449
+ search: (query, options) => {
450
+ setComposerModel ??= findComposerModelSetter()
451
+ return options.filter(({ value }) => matchesQuery(value, query.trim().toLowerCase()))
452
+ },
453
+ })
454
+ if (picked && !disposed) await inspectRow(picked, target, setComposerModel)
455
+ }
456
+
457
+ /** The custom table dialog: `ui.dialog.show` + padded text rows. */
458
+ const showTableDialog = (rows: readonly ModelRow[], target: SwitchTarget | undefined) => {
459
+ const lines = buildLines(rows)
460
+ const selectable = selectableIndexes(lines)
461
+ if (selectable.length === 0) {
462
+ context.ui.toast.show({
463
+ title: "Model costs",
464
+ message: "No models found in the configured providers.",
465
+ variant: "warning",
466
+ })
467
+ return
468
+ }
469
+
470
+ const theme = context.theme as unknown as
471
+ | {
472
+ text?: {
473
+ muted?: string
474
+ base?: string
475
+ formfield?: { selected?: string; focused?: string; base?: string }
476
+ }
477
+ primary?: string
478
+ current?: { textMuted?: string; primary?: string }
479
+ }
480
+ | undefined
481
+ const palette: Palette = {
482
+ muted: theme?.text?.muted ?? theme?.current?.textMuted,
483
+ accent: theme?.primary ?? theme?.current?.primary ?? "#7aa2f7",
484
+ cursor: theme?.text?.formfield?.focused ?? theme?.text?.formfield?.selected ?? theme?.text?.muted ?? theme?.current?.textMuted,
485
+ inputText: theme?.text?.formfield?.base ?? theme?.text?.muted,
486
+ }
487
+
488
+ const widths = computeWidths(lines)
489
+ const contentWidth = widths.total
490
+ if (!fitsDialogWidth(contentWidth, context.renderer?.width ?? 0)) return false
491
+ const totalLines = lines.length
492
+ const viewportRows = Math.max(1, Math.min(totalLines, MAX_VIEWPORT_ROWS, (context.renderer?.height ?? 30) - 14))
493
+
494
+ // The cursor and search-query state live here (outside the component) so
495
+ // the key handlers and the rendered list share it. Plain signals need no
496
+ // owner. Typing filters the table in place (`filterLines`); the cursor
497
+ // restarts at the first match.
498
+ const [selectedPos, setSelectedPos] = createSignal(0)
499
+ const [query, setQuery] = createSignal("")
500
+ const [filtered, setFiltered] = createSignal<FilteredTable>({ lines, selectable })
501
+ // The component owns the scroll window and registers this setter, so a
502
+ // filter change can jump the list back to its top.
503
+ let setViewportTop: ((top: number) => void) | undefined
504
+ const clampPos = (position: number) => {
505
+ const count = filtered().selectable.length
506
+ if (count === 0) return 0
507
+ return Math.min(count - 1, Math.max(0, position))
508
+ }
509
+ const applyQuery = (next: string) => {
510
+ setQuery(next)
511
+ setFiltered(filterLines(lines, next))
512
+ setSelectedPos(0)
513
+ setViewportTop?.(0)
514
+ }
515
+
516
+ let setComposerModel: SetComposerModel | undefined
517
+ let popMode: (() => void) | undefined
518
+ let open = true
519
+
520
+ const close = () => {
521
+ if (!open) return
522
+ open = false
523
+ dialogControls = undefined
524
+ try {
525
+ context.ui.dialog.clear()
526
+ } catch {}
527
+ try {
528
+ popMode?.()
529
+ } catch {}
530
+ popMode = undefined
531
+ }
532
+
533
+ dialogControls = {
534
+ move: (delta) => setSelectedPos(clampPos(selectedPos() + delta)),
535
+ page: (direction) => setSelectedPos(clampPos(selectedPos() + direction * viewportRows)),
536
+ first: () => setSelectedPos(0),
537
+ last: () => setSelectedPos(Math.max(0, filtered().selectable.length - 1)),
538
+ confirm: () => {
539
+ const current = filtered()
540
+ const line = current.lines[current.selectable[selectedPos()]]
541
+ if (line?.kind !== "model") return
542
+ close()
543
+ opening = true
544
+ void inspectRow(line.row, target, setComposerModel).catch(() => {
545
+ if (!disposed) context.ui.toast.show({ message: "Could not open model details.", variant: "error" })
546
+ }).finally(() => { opening = false })
547
+ },
548
+ query: applyQuery,
549
+ close,
550
+ }
551
+
552
+ try {
553
+ // Exclusive input mode while the dialog is open: host bindings stop
554
+ // acting on keys meant for the dialog (renderer-level useKeyboard in
555
+ // the component still receives them).
556
+ const pushed = context.keymap?.mode?.push?.(DIALOG_MODE)
557
+ if (typeof pushed === "function") popMode = pushed
558
+ } catch {
559
+ // Mode push unavailable — keys may then leak to the host input; the
560
+ // dialog still works and closes.
561
+ }
562
+
563
+ // render() must produce the JSX when the host mounts it — inside the
564
+ // host's reactive/render context — so the rows get a parent renderable.
565
+ // Pre-creating the element here would mount nothing.
566
+ context.ui.dialog.show(
567
+ () => {
568
+ setComposerModel = findComposerModelSetter()
569
+ return (
570
+ <CostsTable
571
+ table={filtered}
572
+ query={query}
573
+ total={selectable.length}
574
+ widths={widths}
575
+ palette={palette}
576
+ contentWidth={contentWidth}
577
+ viewportRows={viewportRows}
578
+ registerViewportTop={(setter) => {
579
+ setViewportTop = setter
580
+ }}
581
+ selected={selectedPos}
582
+ current={() => (context.ui?.model?.current?.() as CurrentModel | undefined) ?? undefined}
583
+ controls={dialogControls!}
584
+ onClosed={close}
585
+ />
586
+ )
587
+ },
588
+ close,
589
+ )
590
+ context.ui.dialog.set?.({ size: fitDialogSize([" ".repeat(contentWidth)]) })
591
+ return true
592
+ }
593
+
594
+ const closeTable = () => dialogControls?.close()
595
+
596
+ const showCostsDialog = async () => {
597
+ if (opening || dialogControls) return
598
+ opening = true
599
+ const target = resolveSwitchTarget()
600
+ try {
601
+ const { rows, configUnavailable, providerPricesUnavailable } = await refresh()
602
+ if (disposed) return
603
+ if (configUnavailable || rows.length === 0) {
604
+ await context.ui.dialog.alert({
605
+ title: "Model costs",
606
+ message: configUnavailable
607
+ ? "Could not read OpenCode configuration. Reopen Model costs to retry."
608
+ : providerPricesUnavailable ? "Could not load configured providers. Reopen Model costs to retry."
609
+ : "No models found in the configured providers.",
610
+ })
611
+ return
612
+ }
613
+ if (typeof context.ui.dialog.show === "function") {
614
+ try {
615
+ if (showTableDialog(rows, target)) return
616
+ } catch {
617
+ closeTable()
618
+ }
619
+ }
620
+ await showSelectDialog(rows, target)
621
+ } finally {
622
+ opening = false
623
+ }
624
+ }
625
+
626
+ context.keymap?.layer?.(() => ({
627
+ mode: "global",
628
+ commands: [
629
+ {
630
+ id: "opencode-model-costs.show",
631
+ title: "Show model costs",
632
+ group: "Model costs",
633
+ palette: true,
634
+ slash: { name: "models-cost" },
635
+ run: () => showCostsDialog(),
636
+ },
637
+ ],
638
+ }))
639
+
640
+ return () => {
641
+ disposed = true
642
+ try {
643
+ dialogControls?.close()
644
+ } catch {}
645
+ try {
646
+ stopConfigChanged?.()
647
+ } catch {}
648
+ try {
649
+ ;(unregisterSlot as unknown as (() => void) | undefined)?.()
650
+ } catch {}
651
+ }
652
+ },
653
+ })
654
+
655
+ /** Exclusive keymap mode name pushed while the table dialog is open. */
656
+ const DIALOG_MODE = "opencode-model-costs.table"
657
+
658
+ /**
659
+ * The table dialog's content. Rendered by the host inside its dialog layer
660
+ * (so the rows get a parent renderable), which is why the JSX is produced
661
+ * lazily by the `render()` callback. The cursor and search-query state come in
662
+ * as props; keys are read at the renderer level with `useKeyboard`. Unmounting
663
+ * it (host close, escape through the host's own chrome) signals `onClosed`.
664
+ */
665
+ function CostsTable(props: {
666
+ table: () => FilteredTable
667
+ query: () => string
668
+ /** Number of models with no filter applied — the "of N" denominator. */
669
+ total: number
670
+ widths: ColumnWidths
671
+ palette: Palette
672
+ contentWidth: number
673
+ viewportRows: number
674
+ registerViewportTop(setter: (top: number) => void): void
675
+ selected: () => number
676
+ current: () => CurrentModel | undefined
677
+ controls: {
678
+ move(delta: number): void
679
+ page(direction: number): void
680
+ first(): void
681
+ last(): void
682
+ confirm(): void
683
+ query(next: string): void
684
+ close(): void
685
+ }
686
+ onClosed: () => void
687
+ }) {
688
+ // Renderer-level keys: no keymap-bind parsing, works regardless of focus.
689
+ // These run before the focused search input's native handler, so handled
690
+ // keys preventDefault and navigation wins; every other key (typing,
691
+ // backspace, caret movement) falls through to the input.
692
+ let input: InputRenderable | undefined
693
+ useKeyboard((event: KeyEvent) => {
694
+ if (event.eventType === "release") return
695
+ switch (event.name) {
696
+ case "up":
697
+ event.preventDefault()
698
+ props.controls.move(-1)
699
+ break
700
+ case "down":
701
+ event.preventDefault()
702
+ props.controls.move(1)
703
+ break
704
+ case "pageup":
705
+ event.preventDefault()
706
+ props.controls.page(-1)
707
+ break
708
+ case "pagedown":
709
+ event.preventDefault()
710
+ props.controls.page(1)
711
+ break
712
+ case "home":
713
+ event.preventDefault()
714
+ props.controls.first()
715
+ break
716
+ case "end":
717
+ event.preventDefault()
718
+ props.controls.last()
719
+ break
720
+ case "enter":
721
+ case "return":
722
+ event.preventDefault()
723
+ props.controls.confirm()
724
+ break
725
+ case "escape":
726
+ event.preventDefault()
727
+ if (props.query()) {
728
+ if (input) input.value = ""
729
+ props.controls.query("")
730
+ } else {
731
+ props.controls.close()
732
+ }
733
+ break
734
+ }
735
+ })
736
+
737
+ // Sliding window over the lines; scrolls to keep the cursor visible.
738
+ const [top, setTop] = createSignal(0)
739
+ props.registerViewportTop(setTop)
740
+ createEffect(() => {
741
+ const table = props.table()
742
+ const line = table.selectable[props.selected()]
743
+ const maxTop = Math.max(0, table.lines.length - props.viewportRows)
744
+ const currentTop = top()
745
+ let next = currentTop
746
+ if (line < currentTop) next = line
747
+ else if (line >= currentTop + props.viewportRows) next = line - props.viewportRows + 1
748
+ setTop(Math.min(Math.max(0, next), maxTop))
749
+ })
750
+
751
+ const selectedLine = () => props.table().selectable[props.selected()]
752
+ const isSelected = (index: number): boolean => {
753
+ const base = selectedLine()
754
+ if (base === undefined) return false
755
+ const line = props.table().lines[index]
756
+ if (line === undefined) return false
757
+ if (line.kind === "model") return index === base
758
+ if (line.kind === "tier") {
759
+ const baseLine = props.table().lines[base]
760
+ return baseLine?.kind === "model" && baseLine.row === line.row
761
+ }
762
+ return false
763
+ }
764
+
765
+ const colorOf = (line: LineData, selected: boolean): string | undefined => {
766
+ if (selected) return props.palette.accent
767
+ if (line.kind === "header" || line.kind === "tier" || line.kind === "rule") return props.palette.muted
768
+ if (line.kind === "provider") return props.palette.accent
769
+ return undefined
770
+ }
771
+
772
+ const table = () => props.table()
773
+ const from = () => Math.min(top(), Math.max(0, table().lines.length - props.viewportRows))
774
+ const visible = () =>
775
+ table()
776
+ .lines.slice(from(), from() + props.viewportRows)
777
+ .map((line, offset) => {
778
+ const index = from() + offset
779
+ const selected = isSelected(index)
780
+ return (
781
+ <text fg={colorOf(line, selected)} wrapMode="none">
782
+ {lineText(line, props.widths, { selected, current: props.current() })}
783
+ </text>
784
+ )
785
+ })
786
+
787
+ onCleanup(props.onClosed)
788
+
789
+ const tableHeight = () => table().selectable.length ? Math.min(table().lines.length, props.viewportRows) : 1
790
+
791
+ return (
792
+ <box flexDirection="column" width="100%" alignItems="center" paddingTop={1} paddingBottom={2}>
793
+ <box flexDirection="column" width={props.contentWidth}>
794
+ <box flexDirection="row" columnGap={3} marginBottom={1}>
795
+ <input
796
+ flexGrow={1}
797
+ minWidth={0}
798
+ backgroundColor="transparent"
799
+ onInput={(value) => props.controls.query(value)}
800
+ placeholder="Search models"
801
+ placeholderColor={props.palette.muted}
802
+ cursorColor={props.palette.cursor ?? props.palette.accent}
803
+ cursorStyle={{ style: "block", blinking: true }}
804
+ focusedBackgroundColor="transparent"
805
+ focusedTextColor={props.palette.inputText ?? props.palette.accent}
806
+ ref={(renderable) => {
807
+ input = renderable
808
+ // Mount paints after the first frame; focus on the next tick so
809
+ // the input is ready for typing the moment the dialog appears.
810
+ setTimeout(() => {
811
+ if (!input || input.isDestroyed) return
812
+ input.focus()
813
+ }, 1)
814
+ }}
815
+ />
816
+ <text flexShrink={0} fg={props.palette.muted} wrapMode="none">
817
+ {props.query()
818
+ ? `${props.table().selectable.length} of ${props.total}`
819
+ : `${props.total} model${props.total === 1 ? "" : "s"}`}
820
+ </text>
821
+ </box>
822
+ <box flexDirection="column" height={tableHeight()} marginBottom={1}>
823
+ {table().selectable.length === 0 ? (
824
+ <text fg={props.palette.muted} wrapMode="none">
825
+ No matching models
826
+ </text>
827
+ ) : (
828
+ visible()
829
+ )}
830
+ </box>
831
+ <text fg={props.palette.muted} wrapMode="none">
832
+ {"↑↓ Move · Enter details · Esc close"}
833
+ </text>
834
+ <text fg={props.palette.muted} wrapMode="none">
835
+ {"USD / 1M tokens · ★ Default · ● Current"}
836
+ </text>
837
+ </box>
838
+ </box>
839
+ )
840
+ }
841
+
842
+ function CostBadge(props: { context: TuiContext; data: () => CostData }) {
843
+ const context = props.context
844
+ const dimensions = useTerminalDimensions()
845
+ const [footerWidth, setFooterWidth] = createSignal<number>()
846
+
847
+ // Read inside JSX so both the selected model and the config rows are reactive.
848
+ const badge = () => {
849
+ const rows = props.data().rows
850
+ const selected = context.ui?.model?.current?.() as
851
+ | { providerID?: string; modelID?: string; id?: string; provider?: { id?: string }; model?: { modelID?: string; id?: string } }
852
+ | undefined
853
+ const providerID = selected?.providerID ?? selected?.provider?.id
854
+ const modelID = selected?.modelID ?? selected?.id ?? selected?.model?.modelID ?? selected?.model?.id
855
+ // Without a routed model (no session started yet) the configured default
856
+ // is shown so its prices are visible from startup.
857
+ const row = providerID && modelID ? findRow(rows, providerID, modelID) : rows.find((entry) => entry.isDefault)
858
+ if (!row) return undefined
859
+ return fmtBadge(row, dimensions().width - 4) ? row : undefined
860
+ }
861
+
862
+ const color = () => context.theme?.text?.muted ?? context.theme?.current?.textMuted
863
+
864
+ const [offset, setOffset] = createSignal(0)
865
+
866
+ return (
867
+ <Show when={badge()}>
868
+ {(row) => (
869
+ <box
870
+ height={2}
871
+ minHeight={0}
872
+ flexShrink={0}
873
+ ref={(anchor) => {
874
+ // Reserve a second row without taking width from the host's status items.
875
+ // Align the badge to the footer's left edge when the slot moves.
876
+ const align = () => {
877
+ const footer = anchor.parent
878
+ if (!footer) return
879
+ setOffset(anchor.x - footer.x)
880
+ if (footer.width > 0) setFooterWidth(footer.width)
881
+ }
882
+ context.renderer.on(CliRenderEvents.FRAME, align)
883
+ onCleanup(() => {
884
+ context.renderer.off(CliRenderEvents.FRAME, align)
885
+ setFooterWidth(undefined)
886
+ })
887
+ }}
888
+ >
889
+ <box position="absolute" left={-offset()} top={1}>
890
+ <text fg={color()} wrapMode="none">
891
+ {fmtBadge(row(), Math.min(footerWidth() ?? Infinity, dimensions().width - 4))}
892
+ </text>
893
+ </box>
894
+ </box>
895
+ )}
896
+ </Show>
897
+ )
898
+ }