// lib/tui-panel.ts — the `session.panel` component (BreakdownPanel). // // No JSX and no `@jsxImportSource` pragma anywhere in this file: see the long // explanation at the top of lib/tui-h.ts. Every dynamic prop is a getter, which // is exactly what the Solid compiler would have emitted for `prop={expr}`. import { usePlugin } from "@opencode/plugin/tui" import { createMemo, Show } from "solid-js" import { mkdirSync, writeFileSync } from "node:fs" import { tmpdir } from "node:os" import { basename, join } from "node:path" import type { StateEntry } from "./tui-data.js" import { collectFamily, fit, fmt, num, panelLayout, splitFamily, sumCtx, toolOutEntries, updatedCell, familyTail } from "./tui-data.js" import { token } from "./tui-theme.js" import { c as comp, h } from "./tui-h.ts" import { buildRedactedPayload, contributorLine, exportFileName, measureContributors, panelDenom, panelRole, safeText, } from "./contributors.js" // Mirrors the Contributor shape produced by measureContributors() // (lib/contributors.js). type Contributor = { kind: string ref: string chars: number tokensEstimate: number tool: string preview: string } // Host-owned session.panel input ({ name, sessionID, width, presentation, // focused, focus(), close(), toggleFullscreen() }). Typed structurally instead // of imported so this file stays independent of the host type package; the host // resolves the panel API at runtime. type PanelInput = { readonly name: string readonly sessionID: string readonly width: number readonly presentation: "panel" | "fullscreen" readonly focused: boolean readonly focus: () => void readonly close: () => void readonly toggleFullscreen: () => void } // The TUI message data API is optional across host versions. Log a single hint // (never once per poll) when it is unavailable and hide the whole section. let warnedMessagesUnavailable = false // Cheap change detector for the live message list. The host hands back a fresh // array on every poll, so identity cannot be used as a memo key, while walking // the whole list (per-character estimates + JSON.stringify of tool args) once // per 1000 ms tick is exactly the cost we want to avoid. Length + last message // id + created stamp + last message payload size covers appends, streaming and // tool completion; an in-place edit of an OLDER message lands one tick later, // when the tail changes. Known blind spot by design: the size is a SUM, so a // same-length substitution inside the last message is not detected. function listSignature(list: unknown[]): string { const n = list.length if (n === 0) return "0" const last: unknown = list[n - 1] if (last == null || typeof last !== "object") return `${n}:?` const rec = last as Record const id = typeof rec.id === "string" ? rec.id : "" const time = rec.time const created = time != null && typeof time === "object" ? String((time as Record).created ?? "") : "" let size = typeof rec.text === "string" ? rec.text.length : 0 const parts: unknown[] = Array.isArray(rec.content) ? rec.content : [] for (const raw of parts) { if (raw == null || typeof raw !== "object") continue const part = raw as Record if (typeof part.text === "string") { size += part.text.length continue } const state = part.state if (state == null || typeof state !== "object") continue const st = state as Record if (typeof st.input === "string") size += st.input.length else if (st.input != null) { try { size += JSON.stringify(st.input).length } catch { /* unstringifiable input contributes no size */ } } // Tool RESULTS matter as much as args: measureContributors reads // state.content, and a call that finishes between two ticks changes nothing // else on the message. Without this the measured section would freeze for // the whole remainder of the turn. const content = st.content if (typeof content === "string") { size += content.length } else if (Array.isArray(content)) { for (const rawItem of content) { if (rawItem == null || typeof rawItem !== "object") continue const item = rawItem as Record if (typeof item.text === "string") { size += item.text.length } else { // Non-text parts (e.g. file refs with long/base64 URIs) are not // measured by measureContributors, so their marker is enough: never // JSON.stringify a potentially megabyte-sized reference per tick. size += 1 } } } // Status transitions (pending -> completed/error) are cheap and always // accompany a visible change. if (typeof st.status === "string") size += st.status.length } return `${n}:${id}:${created}:${size}` } // Panel column layout lives in lib/tui-data.js (pure math) so the unit harness // can regression-test that the row never grows past the panel width (T42 in // test/prepublish.mjs). // Dollar formatting for the cost column: compact, always `$`-prefixed, `-` // when the host data layer has no cost for the session. function money(n: number | null): string { if (n == null || !Number.isFinite(n)) return "-" const a = Math.abs(n) if (a >= 1000) return `$${(n / 1000).toFixed(1)}k` if (a >= 100) return `$${n.toFixed(1)}` return `$${n.toFixed(2)}` } // The topmost ancestor of the panel's session: `/cx` opened from a subagent // session view must show the WHOLE family (rooted at the main session), not // just the child subtree. Walks parentID upward over the snapshot; `seen` // guards against parentID loops. function resolveRoot( snapshot: Record, sessionID: string, ): string { let current = sessionID const seen = new Set([current]) for (;;) { const entry = Object.prototype.hasOwnProperty.call(snapshot, current) ? snapshot[current] : undefined const parent = entry?.parentID if ( !parent || typeof parent !== "string" || !Object.prototype.hasOwnProperty.call(snapshot, parent) || seen.has(parent) ) { break } seen.add(parent) current = parent } return current } // Full session panel: header + one row per session in the family (root plus // subagent descendants). It reads the same state.json bridge as the sidebar via // the shared 1 s tick, so both surfaces refresh on ONE poll. The family is // rooted at the panel session's TOPMOST ancestor, so opening the panel from a // subagent view shows the whole family. `cx` opens the panel (registered from // the "app" slot in tui.ts; also reachable from the command palette, since // subagent views have no prompt input). export function BreakdownPanel(props: { panel: PanelInput snapshot: () => Record refresh: () => void }) { const context = usePlugin() const base = () => token(context?.theme?.text?.base, "white") const muted = () => token(context?.theme?.text?.muted, base()) // The host session data layer, re-read per call: individual accessors // (family/get/status/cost) are optional across host versions and every use // site guards them separately. const dataApiSession = () => context?.data?.session // Set while the picker dialog is on screen: the panel-local `s` key must not // re-trigger the picker (a printable key typed into the dialog search would // otherwise stack dialogs — the guard is belt-and-braces for hosts where the // panel keeps focus while a dialog is open). let pickerOpen = false // Per-session cost from the host data layer (read under the shared poll tick, // so it refreshes reactively). For a ROOT session the host AGGREGATES the // whole family; for a child it is that session's own cost — exactly the // per-subagent spend visibility the community asked for (upstream #45417). // Guarded: older hosts may not expose the accessor. const costOf = (sessionID: string | undefined): number | null => { if (!sessionID) return null try { const cost = context?.data?.session?.cost?.(sessionID) return typeof cost === "number" && Number.isFinite(cost) ? cost : null } catch { return null } } // Panel-local keys. The layer is owned by this component and disposed with it. // mode "global" + an explicit focused check is the portable fallback when no // target renderable is available: the keys act only while the panel owns input. // The capability guard keeps an older host (no keymap API) from throwing. const keymap = context?.keymap if (keymap && typeof keymap.layer === "function") { keymap.layer(() => ({ mode: "global", priority: -1, commands: [ { id: "context-indicator.breakdown.close", title: "Close the context breakdown panel", bind: "escape", enabled: () => props.panel.focused, run: () => { if (props.panel.focused) props.panel.close() }, }, { id: "context-indicator.breakdown.refresh", title: "Refresh the context breakdown panel", bind: "r", enabled: () => props.panel.focused, run: () => { if (props.panel.focused) props.refresh() }, }, { id: "context-indicator.breakdown.export", title: "Export a redacted breakdown snapshot", bind: "e", enabled: () => props.panel.focused, run: () => { if (props.panel.focused) exportRedacted() }, }, { id: "context-indicator.breakdown.pick", title: "Pick a family session", bind: "s", enabled: () => props.panel.focused && !pickerOpen, run: () => { if (props.panel.focused && !pickerOpen) openPicker() }, }, ], })) } // One snapshot read per poll tick (props.snapshot tracks the shared tick), so // the memo recomputes together with the sidebar instead of polling separately. // The family is rooted at the topmost ancestor (resolveRoot): from a subagent // view the whole family is shown, not just the child subtree. const data = createMemo(() => { const snap = props.snapshot() const rootID = resolveRoot(snap, props.panel.sessionID) return { root: snap[rootID], rows: collectFamily(snap, rootID), } }) // Live message list from the TUI data layer (in-process, no LLM call). The // shared `props.snapshot()` tick is read FIRST so this re-reads every poll. // `available: false` means the API is absent/errored -> the WHOLE measured // section is hidden (and a one-time hint was logged). const messages = createMemo<{ available: boolean; list: unknown[] }>(() => { props.snapshot() try { const api = context?.data?.session?.message if (!api || typeof api.list !== "function") { if (!warnedMessagesUnavailable) { warnedMessagesUnavailable = true console.error( "[context-indicator] TUI message data API unavailable; " + "measured contributors section hidden", ) } return { available: false, list: [] } } const v = api.list(props.panel.sessionID) return { available: true, list: Array.isArray(v) ? v : [] } } catch { if (!warnedMessagesUnavailable) { warnedMessagesUnavailable = true console.error( "[context-indicator] TUI message read failed; " + "measured contributors section hidden", ) } return { available: false, list: [] } } }) // Memo for the measured contributors section: the signature/key pair keeps // the expensive walk out of the per-tick path (see listSignature). let contributorKey: string | null = null let contributorValue: Contributor[] = [] const contributors = createMemo(() => { const m = messages() if (!m.available) { contributorKey = null contributorValue = [] return contributorValue } // Re-measure ONLY when the message list actually changed. The host rebuilds // the array (and `props.snapshot()` ticks) every second, so keying on array // identity would re-walk every message — per-character token estimates plus // JSON.stringify of tool args — once per tick on the render thread. let key: string try { key = listSignature(m.list) } catch { key = "" } if (key && key === contributorKey) return contributorValue try { contributorValue = measureContributors(m.list) contributorKey = key || contributorKey } catch { // Transient failure: leave the key unset so the next tick retries. contributorValue = [] contributorKey = null } return contributorValue }) // Redacted export (key `e`). No message text, no full session id, no tool // output content ever leaves this function. Never throws: a failure logs and // shows an error toast instead. function exportRedacted(): void { let exportedName: string | null = null try { const now = new Date() const name = exportFileName(props.panel.sessionID, now) const payload = buildRedactedPayload({ sessionID: props.panel.sessionID, root: data().root, rows: data().rows, contributors: contributors(), now, panelDenom, panelRole, num, }) const dir = join(tmpdir(), "opencode-context-indicator", "exports") const file = join(dir, name) mkdirSync(dir, { recursive: true }) writeFileSync(file, JSON.stringify(payload, null, 2), "utf8") exportedName = basename(file) } catch (err) { console.error("[context-indicator] redacted export failed:", err) try { context?.ui?.toast?.show({ message: "redacted export failed", variant: "error", }) } catch { /* toast is best-effort */ } return } // Outside the write try: a toast failure must not report the export as // failed when the file is already on disk. try { context?.ui?.toast?.show({ message: `exported ${exportedName}`, variant: "success", }) } catch { /* toast is best-effort */ } } // Navigate to a family session: root sessions focus their tab (tab-aware, // opens one when needed); child sessions navigate the route directly (tabs // are root-session scoped). Falls back with a toast when the host exposes // neither mechanism. function navigateTo(sessionID: string): void { try { const ui = context?.ui // Child detection is three-sourced: the host session info, OUR snapshot // (state.json parentID), and the host root() accessor — get() alone can // miss a session that has not been synced into the client store yet, and // tabs.focus() on a child ID would target the wrong (root) tab. let isChild = false try { const info = context?.data?.session?.get?.(sessionID) isChild = !!( info && typeof info === "object" && (info as Record).parentID ) } catch { /* other sources below */ } if (!isChild) { const snapParent = props.snapshot()[sessionID]?.parentID if (typeof snapParent === "string" && snapParent.length > 0) isChild = true } if (!isChild && typeof context?.data?.session?.root === "function") { try { if (context.data.session.root(sessionID) !== sessionID) isChild = true } catch { /* treat as root */ } } if (!isChild && ui?.tabs && typeof ui.tabs.focus === "function") { if (ui.tabs.focus(sessionID)) return } if (ui?.router && typeof ui.router.navigate === "function") { ui.router.navigate({ type: "session", sessionID }) return } try { context?.ui?.toast?.show({ message: "session navigation not supported by this host", variant: "warning", }) } catch { /* toast is best-effort */ } } catch (err) { console.error("[context-indicator] session navigation failed:", err) } } // Family-session picker (key `s`): a select dialog over the host data layer's // family rooted at the TOPMOST ancestor (matches the table; authoritative — // includes registered sessions that never served a step; falls back to our // state.json walk), searchable by title/model, each option carrying its own // cost and a running marker. Enter navigates. function openPicker(): void { if (pickerOpen) return const dialog = context?.ui?.dialog if (!dialog || typeof dialog.select !== "function") { try { context?.ui?.toast?.show({ message: "session picker requires opencode 2.0.23+", variant: "warning", }) } catch { /* toast is best-effort */ } return } const rootID = resolveRoot(props.snapshot(), props.panel.sessionID) let ids: string[] = [] try { const family = dataApiSession()?.family?.(rootID) if (Array.isArray(family)) ids = family.filter((id) => typeof id === "string") } catch { ids = [] } if (ids.length === 0) { // Host family unavailable: fall back to our state.json family walk. ids = collectFamily(props.snapshot(), rootID) .map((e) => e.sessionID) .filter((id): id is string => typeof id === "string" && id.length > 0) } const labels = new Map() const options = ids.map((id) => { let title = "(untitled)" let model = "" let running = false try { const info = dataApiSession()?.get?.(id) if (info && typeof info === "object") { const raw = info as Record title = safeText(raw.title) || title const m = raw.model as { modelID?: unknown } | string | undefined model = typeof m === "string" ? safeText(m) : m && typeof m.modelID === "string" ? safeText(m.modelID) : "" running = dataApiSession()?.status?.(id) === "running" } } catch { /* defensive: host data layers may lack get/status */ } if (!model) { const fromSnapshot = props.snapshot()[id]?.model if (typeof fromSnapshot === "string" && fromSnapshot !== "unknown") model = safeText(fromSnapshot) } const parts = [model, title, money(costOf(id))] if (running) parts.push("running") const label = parts.filter((p) => p.length > 0).join(" · ") labels.set(id, label) return { title: label, value: id } }) if (options.length <= 1) { try { context?.ui?.toast?.show({ message: "no other family sessions", variant: "info", }) } catch { /* toast is best-effort */ } return } pickerOpen = true try { void dialog .select({ title: "Family sessions", options, search: (query, opts) => { const q = query.trim().toLowerCase() if (!q) return opts return opts.filter((o) => (labels.get(o.value) ?? o.title).toLowerCase().includes(q)) }, }) .then((picked) => { pickerOpen = false if (typeof picked === "string" && picked.length > 0) navigateTo(picked) }) .catch(() => { pickerOpen = false /* dialog settle races are host-managed; nothing to recover */ }) } catch (err) { pickerOpen = false console.error("[context-indicator] session picker failed:", err) } } const header = (): string => { const r = data().root if (!r) return "Context breakdown" const model = safeText(r.model && r.model !== "unknown" ? r.model : "model?") const ctx = fmt(num(r.ctx)) const d = panelDenom(r) const base = d > 0 ? `Context breakdown \u2014 ${model} ${ctx}/${fmt(d)} (${Math.round( (num(r.ctx) / d) * 100, )}%)` : `Context breakdown \u2014 ${model} ${ctx}` return r.compactStale === true ? `${base} (stale — compacted)` : base } const layout = (): { roleW: number modelW: number ctxW: number costW: number updW: number gutter: string } => panelLayout(props.panel.width) const columns = (): string => { const L = layout() return ( fit("role", L.roleW) + L.gutter + fit("model", L.modelW) + L.gutter + fit("ctx", L.ctxW) + L.gutter + fit("cost", L.costW) + L.gutter + "updated" ) } const row = (e: StateEntry, isMain: boolean): string => { const model = safeText(e.model && e.model !== "unknown" ? e.model : "model?") const d = panelDenom(e) const ctx = d > 0 ? `${fmt(num(e.ctx))} (${Math.round((num(e.ctx) / d) * 100)}%)` : fmt(num(e.ctx)) const L = layout() return ( fit(panelRole(e, isMain), L.roleW) + L.gutter + fit(model, L.modelW) + L.gutter + fit(ctx, L.ctxW) + L.gutter + fit(money(costOf(e.sessionID)), L.costW) + L.gutter + updatedCell(e.updatedAt, e.compactStale === true, L.updW) ) } // Whole family: every session's own context usage added up. Each session has // its OWN window, so this is a total of tokens used, not one window's fill. // Kept short: the worst case the panel can show (4-digit session count, a // millions-scale sum) is 56 columns at the default 60; fmt() switches to M // above a million, so the line cannot grow past that. const totalLine = (): string => `family total ${fmt(sumCtx(data().rows))} across ${data().rows.length} sessions (sum of windows)` // Hidden rows still count in the family total (sumCtx); the tail keeps the // list honest by showing what the hidden rows add up to. const split = () => splitFamily(data().rows) // One compact line: the main session's tool results split by tool name // (server-side aggregate; the per-call "largest contributors" block above is // the measured, client-side view). const byToolLine = (): string => { const all = data().root?.toolOutByTool const entries = toolOutEntries(all, 5) if (entries.length === 0) return "" const total = all && typeof all === "object" ? Object.values(all).filter((v) => num(v) > 0).length : 0 const parts = entries.map(([name, val]) => `${safeText(name)} ${fmt(val)} tokens`) if (total > entries.length) parts.push(`+${total - entries.length} more`) return parts.join(" \u00b7 ") } // Muted / highlighted single-line text node. The content accessor is read // inside the getter, so the node updates in place on every poll instead of // being recreated (same semantics as `{expr}` in JSX). const mutedText = (value: () => string) => h("text", { get fg() { return muted() }, get children() { return value() }, }) const baseText = (value: () => string) => h("text", { get fg() { return base() }, get children() { return value() }, }) const compactLine = (): string => " compact at " + fmt(num(data().root?.usable)) + (num(data().root?.reserve) > 0 ? " (" + fmt(num(data().root?.reserve)) + " reserve)" : "") const cacheLine = (): string => " prompt cache r " + fmt(num(data().root?.cacheRead)) + " / w " + fmt(num(data().root?.cacheWrite)) + " (provider-reported)" const reclaimLine = (): string => " reclaim ~" + fmt(num(data().root?.reclaim?.tokens)) + " redundant tool output (" + num(data().root?.reclaim?.count) + " dup)" return h("box", { flexDirection: "column", get children() { return [ baseText(() => header()), comp(Show, { get when() { return data().root }, get fallback() { return mutedText(() => " no data yet") }, get children() { return [ comp(Show, { get when() { // Above the table: a family can hold hundreds of sessions, and // a total below the last row is a total nobody ever sees. return data().rows.length > 1 }, get children() { return mutedText(() => totalLine()) }, }), mutedText(() => columns()), // split() is a memo keyed on data().rows; call it once and reuse. (() => { const s = split() return [ s.root ? mutedText(() => row(s.root!, true)) : null, ...s.shown.map((e) => mutedText(() => row(e, false))), s.hidden.length === 0 ? null : mutedText(() => familyTail(s.hidden, sumCtx(data().rows)).text), ] })(), comp(Show, { get when() { return data().rows.some((e) => e.compactStale === true) }, get children() { return mutedText(() => " * stale - compacted") }, }), comp(Show, { get when() { return (data().root?.usable ?? 0) > 0 }, get children() { return mutedText(() => compactLine()) }, }), comp(Show, { get when() { return ( num(data().root?.cacheRead) > 0 || num(data().root?.cacheWrite) > 0 ) }, get children() { return mutedText(() => cacheLine()) }, }), comp(Show, { get when() { return num(data().root?.reclaim?.tokens) > 0 }, get children() { return mutedText(() => reclaimLine()) }, }), comp(Show, { get when() { return messages().available }, get children() { return [ baseText(() => "largest contributors (measured)"), comp(Show, { get when() { return contributors().length > 0 }, get fallback() { return mutedText(() => " no messages yet") }, get children() { return contributors() .slice(0, 5) .map((contributor, i) => mutedText(() => contributorLine(contributor, i + 1)), ) }, }), mutedText( () => "measured != server categories: contributors attribute " + "outputs per tool call; the server's toolOut category " + "only totals them", ), ] }, }), comp(Show, { get when() { return byToolLine().length > 0 }, get children() { return [ baseText(() => "tool results by tool"), mutedText(() => byToolLine()), ] }, }), ] }, }), ] }, }) }