opencode-context-indicator 1.2.1 → 1.3.0
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/CHANGELOG.md +101 -0
- package/README.md +47 -14
- package/lib/tui-data.d.ts +45 -0
- package/lib/tui-data.js +165 -0
- package/lib/tui-panel.tsx +575 -0
- package/lib/tui-sidebar.tsx +72 -0
- package/lib/tui-theme.js +17 -0
- package/package.json +10 -6
- package/tui.tsx +57 -557
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-context-indicator",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Real-time OpenCode context-window usage indicator: per-category token breakdown written to a log file, plus an optional TUI sidebar. Dual V1 + V2 plugin entry.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
"lib/",
|
|
14
14
|
"tui.tsx",
|
|
15
15
|
"README.md",
|
|
16
|
+
"CHANGELOG.md",
|
|
16
17
|
"LICENSE"
|
|
17
18
|
],
|
|
18
19
|
"engines": {
|
|
@@ -56,19 +57,22 @@
|
|
|
56
57
|
}
|
|
57
58
|
},
|
|
58
59
|
"dependencies": {
|
|
59
|
-
"@opentui/solid": "0.5.
|
|
60
|
+
"@opentui/solid": "0.5.17"
|
|
60
61
|
},
|
|
61
62
|
"devDependencies": {
|
|
62
|
-
"@opencode/plugin": "
|
|
63
|
-
"@opentui/core": "0.5.
|
|
63
|
+
"@opencode/plugin": "2.0.26",
|
|
64
|
+
"@opentui/core": "0.5.17",
|
|
65
|
+
"@types/node": "26.6.3",
|
|
64
66
|
"esbuild": "^0.28.2",
|
|
65
67
|
"node-pty": "^1.1.0",
|
|
66
|
-
"solid-js": "^1.9.12"
|
|
68
|
+
"solid-js": "^1.9.12",
|
|
69
|
+
"typescript": "5.9.3"
|
|
67
70
|
},
|
|
68
71
|
"scripts": {
|
|
69
72
|
"test:prepublish": "node test/prepublish.mjs",
|
|
70
73
|
"test:e2e": "node test/e2e-tui.mjs --full",
|
|
71
|
-
"test:e2e:quick": "node test/e2e-tui.mjs --quick"
|
|
74
|
+
"test:e2e:quick": "node test/e2e-tui.mjs --quick",
|
|
75
|
+
"test:drift": "node test/drift-watch.mjs"
|
|
72
76
|
},
|
|
73
77
|
"prepublishOnly": "node test/prepublish.mjs && node test/e2e-tui.mjs --full"
|
|
74
78
|
}
|
package/tui.tsx
CHANGED
|
@@ -10,6 +10,17 @@
|
|
|
10
10
|
* must stay the very first line, before any import, and no other pragma-like
|
|
11
11
|
* token may appear in this file. See the OpenTUI Solid integration guide.
|
|
12
12
|
*
|
|
13
|
+
* This file is the ENTRY + setup wiring only. The components and the data layer
|
|
14
|
+
* live in lib/ (all of them are transformed by the host exactly like this file,
|
|
15
|
+
* because the Solid transform's sourceFilter covers every plugin file outside
|
|
16
|
+
* node_modules — see @opentui/solid/scripts/solid-plugin.js):
|
|
17
|
+
* - lib/tui-sidebar.tsx the `sidebar.content` slot component
|
|
18
|
+
* - lib/tui-panel.tsx the `session.panel` component (BreakdownPanel)
|
|
19
|
+
* - lib/tui-data.js state.json bridge, family walk, formatting helpers
|
|
20
|
+
* (+ lib/tui-data.d.ts for the shared types)
|
|
21
|
+
* - lib/tui-theme.js theme-token helper
|
|
22
|
+
* - lib/contributors.js measured-contributor computation + redacted export
|
|
23
|
+
*
|
|
13
24
|
* Exposed as the `./tui` package entry ("beside the main plugin for automatic
|
|
14
25
|
* loading"). OpenCode loads it only in the terminal TUI; it is NOT loaded in
|
|
15
26
|
* the Desktop app (Desktop exposes no TUI slot API). It renders the
|
|
@@ -22,12 +33,12 @@
|
|
|
22
33
|
* %TEMP%/opencode-context-indicator-state.json
|
|
23
34
|
* (see writeStateFile() in index.js) on every breakdown update. This module
|
|
24
35
|
* ONLY reads that file and re-polls it once per second; a missing or corrupt
|
|
25
|
-
* file renders "no data yet". The main plugin never imports
|
|
26
|
-
* absence of the OpenTUI peers cannot break the server/V1 path.
|
|
36
|
+
* file renders "no data yet". The main plugin never imports the TUI entry, so
|
|
37
|
+
* the absence of the OpenTUI peers cannot break the server/V1 path.
|
|
27
38
|
*
|
|
28
39
|
* Runtime requirements: @opentui/core and solid-js are optional peers resolved
|
|
29
40
|
* by OpenCode at runtime. @opentui/solid is a pinned direct dependency (exact
|
|
30
|
-
* 0.5.
|
|
41
|
+
* 0.5.17): OpenCode's TUI loader does not expose a host instance of it, so for
|
|
31
42
|
* npm-installed plugins the JSX pragma would otherwise fail to resolve
|
|
32
43
|
* `@opentui/solid/jsx-runtime` (upstream opencode issue #33884).
|
|
33
44
|
*
|
|
@@ -40,566 +51,21 @@
|
|
|
40
51
|
* `file://` from a path outside any `node_modules` for the live surfaces (see
|
|
41
52
|
* README → "Live sidebar").
|
|
42
53
|
*/
|
|
43
|
-
import {Plugin
|
|
44
|
-
import {
|
|
45
|
-
import
|
|
46
|
-
import {
|
|
47
|
-
import {
|
|
48
|
-
import {
|
|
49
|
-
import {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
ref: string
|
|
53
|
-
chars: number
|
|
54
|
-
tokensEstimate: number
|
|
55
|
-
tool: string
|
|
56
|
-
preview: string
|
|
57
|
-
}
|
|
58
|
-
import {
|
|
59
|
-
safeText,
|
|
60
|
-
measureContributors,
|
|
61
|
-
contributorLine,
|
|
62
|
-
exportFileName,
|
|
63
|
-
buildRedactedPayload,
|
|
64
|
-
panelDenom,
|
|
65
|
-
panelRole,
|
|
66
|
-
} from "./lib/contributors.js"
|
|
67
|
-
|
|
68
|
-
const STATE_FILE =
|
|
69
|
-
process.env.OPENCODE_CONTEXT_INDICATOR_STATE_FILE ||
|
|
70
|
-
join(tmpdir(), "opencode-context-indicator-state.json")
|
|
71
|
-
const POLL_MS = 1000
|
|
72
|
-
const LABEL_WIDTH = 12
|
|
54
|
+
import { Plugin } from "@opencode/plugin/tui"
|
|
55
|
+
import { createSignal, Show } from "solid-js"
|
|
56
|
+
import { mkdirSync, writeFileSync } from "node:fs"
|
|
57
|
+
import { tmpdir } from "node:os"
|
|
58
|
+
import { join } from "node:path"
|
|
59
|
+
import type { StateEntry } from "./lib/tui-data.js"
|
|
60
|
+
import { isNodeModulesInstall, POLL_MS, readSnapshot } from "./lib/tui-data.js"
|
|
61
|
+
import { Sidebar } from "./lib/tui-sidebar"
|
|
62
|
+
import { BreakdownPanel } from "./lib/tui-panel"
|
|
73
63
|
|
|
74
64
|
// Session-panel contribution name. Session-panel names are shared selection
|
|
75
65
|
// values (not registered claims), so it MUST be plugin-prefixed to avoid
|
|
76
66
|
// colliding with another plugin's panel.
|
|
77
67
|
const PANEL_NAME = "context-indicator.breakdown"
|
|
78
68
|
|
|
79
|
-
// True when this module was loaded from an npm install, i.e. its own file path
|
|
80
|
-
// contains a `node_modules` segment (OpenCode's TUI loader skips the host Solid
|
|
81
|
-
// transform for such paths → slots mount once but never live-update; see the
|
|
82
|
-
// Graceful mode note above). Normalised to forward slashes for Windows paths.
|
|
83
|
-
function isNodeModulesInstall(): boolean {
|
|
84
|
-
try {
|
|
85
|
-
const selfPath = fileURLToPath(import.meta.url).replace(/\\/g, "/").toLowerCase()
|
|
86
|
-
return selfPath.includes("/node_modules/")
|
|
87
|
-
} catch {
|
|
88
|
-
return false
|
|
89
|
-
}
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
type Categories = {
|
|
93
|
-
user?: number
|
|
94
|
-
assistant?: number
|
|
95
|
-
reasoning?: number
|
|
96
|
-
toolArgs?: number
|
|
97
|
-
system?: number | null
|
|
98
|
-
toolSchemas?: number | null
|
|
99
|
-
other?: number
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
type StateEntry = {
|
|
103
|
-
sessionID?: string
|
|
104
|
-
parentID?: string | null
|
|
105
|
-
role?: string
|
|
106
|
-
agent?: string | null
|
|
107
|
-
model?: string
|
|
108
|
-
providerID?: string
|
|
109
|
-
ctx?: number
|
|
110
|
-
input?: number
|
|
111
|
-
usable?: number | null
|
|
112
|
-
reserve?: number | null
|
|
113
|
-
limit?: number | null
|
|
114
|
-
reasoning?: number
|
|
115
|
-
categories?: Categories
|
|
116
|
-
updatedAt?: string
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
function fmt(n: number): string {
|
|
120
|
-
if (!Number.isFinite(n)) return "0"
|
|
121
|
-
return n >= 1000 ? `${(n / 1000).toFixed(1)}k` : String(Math.round(n))
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function num(v: unknown): number {
|
|
125
|
-
return typeof v === "number" && Number.isFinite(v) ? v : 0
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
// Theme tokens are OpenTUI RGBA values (see ResolvedTheme.text.base/.muted);
|
|
129
|
-
// pass them straight to the renderer. Fall back to a named color when a token
|
|
130
|
-
// is absent so an unexpected theme shape can never blank the sidebar.
|
|
131
|
-
// `fg` on <text> is typed as OpenTUI's ColorInput (= string | RGBA); using the
|
|
132
|
-
// same alias keeps the JSX assignment type-correct instead of a loose `object`.
|
|
133
|
-
type Fg = ColorInput
|
|
134
|
-
function token(v: unknown, fallback: Fg): Fg {
|
|
135
|
-
return v && typeof v === "object" ? (v as Fg) : fallback
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// Reserved object keys must never be treated as session ids: state.json is
|
|
139
|
-
// untrusted input (mirrors isSafeSessionKey() in lib/estimate.js).
|
|
140
|
-
function isSafeKey(k: string): boolean {
|
|
141
|
-
return k !== "__proto__" && k !== "constructor" && k !== "prototype"
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// Whole state.json snapshot ({ sessionID: entry }) or {} on any error. The
|
|
145
|
-
// sidebar resolves one entry from it and the breakdown panel walks the
|
|
146
|
-
// parentID family over it. Never throws — a missing / empty / corrupt
|
|
147
|
-
// file simply yields {}.
|
|
148
|
-
function readSnapshot(): Record<string, StateEntry> {
|
|
149
|
-
try {
|
|
150
|
-
const raw = readFileSync(STATE_FILE, "utf8")
|
|
151
|
-
const all = JSON.parse(raw) as Record<string, StateEntry>
|
|
152
|
-
if (!all || typeof all !== "object" || Array.isArray(all)) return {}
|
|
153
|
-
// Rebuild into a fresh plain object: drops prototype-poisoning keys
|
|
154
|
-
// (__proto__ / constructor / prototype) and non-object entries in one pass.
|
|
155
|
-
const clean: Record<string, StateEntry> = {}
|
|
156
|
-
for (const [k, v] of Object.entries(all)) {
|
|
157
|
-
if (isSafeKey(k) && v && typeof v === "object") clean[k] = v
|
|
158
|
-
}
|
|
159
|
-
return clean
|
|
160
|
-
} catch {
|
|
161
|
-
return {}
|
|
162
|
-
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// True when an entry carries no measured tokens at all (a registered session
|
|
166
|
-
// that never served a step). Mirrors isEmptyStateEntry() in lib/commands.js:
|
|
167
|
-
// `categories` is always persisted, so the emptiness test SUMS its fields —
|
|
168
|
-
// a missing categories object is not the only trigger. `system` / `toolSchemas`
|
|
169
|
-
// may legitimately be null, hence the num() coercion.
|
|
170
|
-
function isEmptyEntry(e: StateEntry | undefined): boolean {
|
|
171
|
-
const c = e?.categories
|
|
172
|
-
const sum =
|
|
173
|
-
num(c?.user) +
|
|
174
|
-
num(c?.assistant) +
|
|
175
|
-
num(c?.reasoning) +
|
|
176
|
-
num(c?.toolArgs) +
|
|
177
|
-
num(c?.system) +
|
|
178
|
-
num(c?.toolSchemas) +
|
|
179
|
-
num(c?.other)
|
|
180
|
-
return sum === 0 && num(e?.ctx) === 0 && num(e?.input) === 0
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// The panel row set: the root entry (panel.sessionID) plus every entry whose
|
|
184
|
-
// parentID chain reaches it, breadth-first. A small local walk over the snapshot
|
|
185
|
-
// — the server's collectDescendantSessionIDs lives in lib/commands.js and is NOT
|
|
186
|
-
// imported here (tui.tsx stays independent of the server code by design). A
|
|
187
|
-
// phantom node (no tokens, see isEmptyEntry) is not emitted, but traversal still
|
|
188
|
-
// descends through it so real grandchildren behind it are found. `seen` guards
|
|
189
|
-
// against cycles (parentID loops) and double-listing.
|
|
190
|
-
function collectFamily(
|
|
191
|
-
snapshot: Record<string, StateEntry>,
|
|
192
|
-
rootID: string,
|
|
193
|
-
): StateEntry[] {
|
|
194
|
-
const out: StateEntry[] = []
|
|
195
|
-
const root = snapshot[rootID]
|
|
196
|
-
if (root && typeof root === "object") out.push(root)
|
|
197
|
-
const seen = new Set<string>([rootID])
|
|
198
|
-
const queue: string[] = [rootID]
|
|
199
|
-
// Index the snapshot by parentID once (O(n)) instead of an O(n) scan per node.
|
|
200
|
-
const byParent = new Map<string, string[]>()
|
|
201
|
-
for (const [id, e] of Object.entries(snapshot)) {
|
|
202
|
-
const pid = e?.parentID
|
|
203
|
-
if (!pid || typeof pid !== "string") continue
|
|
204
|
-
const kids = byParent.get(pid)
|
|
205
|
-
if (kids) kids.push(id)
|
|
206
|
-
else byParent.set(pid, [id])
|
|
207
|
-
}
|
|
208
|
-
while (queue.length > 0) {
|
|
209
|
-
const cur = queue.shift() as string
|
|
210
|
-
const kids = byParent.get(cur)
|
|
211
|
-
if (!kids) continue
|
|
212
|
-
for (const id of kids) {
|
|
213
|
-
if (!id || seen.has(id)) continue
|
|
214
|
-
seen.add(id)
|
|
215
|
-
const e = snapshot[id]
|
|
216
|
-
if (e && !isEmptyEntry(e)) out.push(e)
|
|
217
|
-
queue.push(id) // descend through phantom parents too
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
return out
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
function updatedAt(iso: string | undefined): string {
|
|
224
|
-
if (!iso) return "?"
|
|
225
|
-
try {
|
|
226
|
-
const d = new Date(iso)
|
|
227
|
-
return Number.isNaN(d.getTime()) ? "?" : d.toLocaleTimeString()
|
|
228
|
-
} catch {
|
|
229
|
-
return "?"
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// Code-point-safe column fit: truncate on code points (never splitting a
|
|
234
|
-
// surrogate pair at a column boundary), mark a truncated cell with a trailing
|
|
235
|
-
// "~" so clipping is VISIBLE (a silently clipped cell reads as two columns
|
|
236
|
-
// colliding), then pad to the column width.
|
|
237
|
-
function fit(s: string, w: number): string {
|
|
238
|
-
const cps = Array.from(s)
|
|
239
|
-
if (cps.length > w) return `${cps.slice(0, Math.max(0, w - 1)).join("")}~`
|
|
240
|
-
return s.padEnd(w)
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// ---------------------------------------------------------------------------
|
|
244
|
-
// Measured contributors (TUI-only). The TUI data layer already holds the
|
|
245
|
-
// session's live message list in-process, so the panel can char-count each
|
|
246
|
-
// message part WITHOUT an LLM call and WITHOUT shipping message text anywhere.
|
|
247
|
-
// Only the char count, the message ordinal and a kind string leave
|
|
248
|
-
// measureContributors(); message text is read, measured and discarded. Tool
|
|
249
|
-
// RESULT outputs are counted here — the server's state.json categories never
|
|
250
|
-
// see them — which is what makes the residual `other` explicable.
|
|
251
|
-
// ---------------------------------------------------------------------------
|
|
252
|
-
|
|
253
|
-
// The TUI message data API is optional across host versions. Log a single hint
|
|
254
|
-
// (never once per poll) when it is unavailable and hide the whole section.
|
|
255
|
-
let warnedMessagesUnavailable = false
|
|
256
|
-
|
|
257
|
-
function Sidebar(props: { entry: () => StateEntry | null }) {
|
|
258
|
-
const context = usePlugin()
|
|
259
|
-
const base = () => token(context?.theme?.text?.base, "white")
|
|
260
|
-
const muted = () => token(context?.theme?.text?.muted, base())
|
|
261
|
-
|
|
262
|
-
const e = () => props.entry()
|
|
263
|
-
|
|
264
|
-
const denom = (): number | null => {
|
|
265
|
-
const x = e()
|
|
266
|
-
const d = x?.usable ?? x?.limit
|
|
267
|
-
return typeof d === "number" && d > 0 ? d : null
|
|
268
|
-
}
|
|
269
|
-
const pct = (v: number): string => {
|
|
270
|
-
const d = denom()
|
|
271
|
-
return d ? `${Math.round((v / d) * 100)}%` : ""
|
|
272
|
-
}
|
|
273
|
-
const line = (label: string, v: unknown): string => {
|
|
274
|
-
const n = num(v)
|
|
275
|
-
const l = (label + " ".repeat(LABEL_WIDTH)).slice(0, LABEL_WIDTH)
|
|
276
|
-
const p = pct(n)
|
|
277
|
-
return `${l}${fmt(n).padStart(7)}${p ? ` ${p.padStart(4)}` : ""}`
|
|
278
|
-
}
|
|
279
|
-
const header = (): string => {
|
|
280
|
-
const x = e()
|
|
281
|
-
if (!x) return ""
|
|
282
|
-
const d = denom()
|
|
283
|
-
return `${x.model ?? "?"} · ${fmt(num(x.ctx))}${
|
|
284
|
-
d ? ` / ${fmt(d)}` : ""
|
|
285
|
-
}${d ? ` (${pct(num(x.ctx))})` : ""}`
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
return (
|
|
289
|
-
<box flexDirection="column">
|
|
290
|
-
<text fg={base()}>{"Context"}</text>
|
|
291
|
-
<Show when={e()} fallback={<text fg={muted()}>{" no data yet"}</text>}>
|
|
292
|
-
<text fg={base()}>{header()}</text>
|
|
293
|
-
<text fg={muted()}>{line("user", e()?.categories?.user)}</text>
|
|
294
|
-
<text fg={muted()}>{line("assistant", e()?.categories?.assistant)}</text>
|
|
295
|
-
<text fg={muted()}>{line("reasoning", e()?.categories?.reasoning)}</text>
|
|
296
|
-
<text fg={muted()}>{line("tool args", e()?.categories?.toolArgs)}</text>
|
|
297
|
-
<text fg={muted()}>
|
|
298
|
-
{e()?.categories?.system == null
|
|
299
|
-
? `${"system".padEnd(LABEL_WIDTH)} n/a`
|
|
300
|
-
: line("system", e()?.categories?.system)}
|
|
301
|
-
</text>
|
|
302
|
-
<text fg={muted()}>
|
|
303
|
-
{e()?.categories?.toolSchemas == null
|
|
304
|
-
? `${"tool schemas".padEnd(LABEL_WIDTH)} n/a`
|
|
305
|
-
: line("tool schemas", e()?.categories?.toolSchemas)}
|
|
306
|
-
</text>
|
|
307
|
-
<text fg={muted()}>{line("other", e()?.categories?.other)}</text>
|
|
308
|
-
<text fg={muted()}>{`updated ${updatedAt(e()?.updatedAt)}`}</text>
|
|
309
|
-
</Show>
|
|
310
|
-
</box>
|
|
311
|
-
)
|
|
312
|
-
}
|
|
313
|
-
|
|
314
|
-
// Host-owned session.panel input ({ name, sessionID, width, presentation,
|
|
315
|
-
// focused, focus(), close(), toggleFullscreen() }). Typed structurally instead
|
|
316
|
-
// of imported so this file stays independent of the host type package; the host
|
|
317
|
-
// resolves the panel API at runtime.
|
|
318
|
-
type PanelInput = {
|
|
319
|
-
readonly name: string
|
|
320
|
-
readonly sessionID: string
|
|
321
|
-
readonly width: number
|
|
322
|
-
readonly presentation: "panel" | "fullscreen"
|
|
323
|
-
readonly focused: boolean
|
|
324
|
-
readonly focus: () => void
|
|
325
|
-
readonly close: () => void
|
|
326
|
-
readonly toggleFullscreen: () => void
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// Panel column layout (monospace), derived from the host-provided panel width
|
|
330
|
-
// so cells never collide on narrow terminals. Gaps between columns keep a
|
|
331
|
-
// truncated cell visually separated from its neighbour.
|
|
332
|
-
const GUTTER = 2
|
|
333
|
-
const CTX_WIDTH = 12
|
|
334
|
-
|
|
335
|
-
function panelLayout(panelWidth: number): {
|
|
336
|
-
roleW: number
|
|
337
|
-
modelW: number
|
|
338
|
-
ctxW: number
|
|
339
|
-
updW: number
|
|
340
|
-
gutter: string
|
|
341
|
-
} {
|
|
342
|
-
const w = num(panelWidth) > 0 ? num(panelWidth) : 60
|
|
343
|
-
const ctxW = CTX_WIDTH
|
|
344
|
-
const updW = Math.max(5, Math.min(8, w - ctxW - 3 * GUTTER - 24))
|
|
345
|
-
const roleW = Math.max(12, Math.min(20, Math.floor(w * 0.3)))
|
|
346
|
-
const modelW = Math.max(10, w - roleW - ctxW - updW - 3 * GUTTER)
|
|
347
|
-
return { roleW, modelW, ctxW, updW, gutter: " ".repeat(GUTTER) }
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
// Full session panel: header + one row per session in the family (root plus
|
|
351
|
-
// subagent descendants). It reads the same state.json bridge as the sidebar via
|
|
352
|
-
// the shared 1 s tick, so both surfaces refresh on ONE poll. `panel.sessionID`
|
|
353
|
-
// selects the root; `cx` opens the panel (registered from the "app" slot below).
|
|
354
|
-
function BreakdownPanel(props: {
|
|
355
|
-
panel: PanelInput
|
|
356
|
-
snapshot: () => Record<string, StateEntry>
|
|
357
|
-
refresh: () => void
|
|
358
|
-
}) {
|
|
359
|
-
const context = usePlugin()
|
|
360
|
-
const base = () => token(context?.theme?.text?.base, "white")
|
|
361
|
-
const muted = () => token(context?.theme?.text?.muted, base())
|
|
362
|
-
|
|
363
|
-
// Panel-local keys. The layer is owned by this component and disposed with it.
|
|
364
|
-
// mode "global" + an explicit focused check is the portable fallback when no
|
|
365
|
-
// target renderable is available: the keys act only while the panel owns input.
|
|
366
|
-
// The capability guard keeps an older host (no keymap API) from throwing.
|
|
367
|
-
const keymap = context?.keymap
|
|
368
|
-
if (keymap && typeof keymap.layer === "function") {
|
|
369
|
-
keymap.layer(() => ({
|
|
370
|
-
mode: "global",
|
|
371
|
-
priority: -1,
|
|
372
|
-
commands: [
|
|
373
|
-
{
|
|
374
|
-
id: "context-indicator.breakdown.close",
|
|
375
|
-
title: "Close the context breakdown panel",
|
|
376
|
-
bind: "escape",
|
|
377
|
-
enabled: () => props.panel.focused,
|
|
378
|
-
run: () => {
|
|
379
|
-
if (props.panel.focused) props.panel.close()
|
|
380
|
-
},
|
|
381
|
-
},
|
|
382
|
-
{
|
|
383
|
-
id: "context-indicator.breakdown.refresh",
|
|
384
|
-
title: "Refresh the context breakdown panel",
|
|
385
|
-
bind: "r",
|
|
386
|
-
enabled: () => props.panel.focused,
|
|
387
|
-
run: () => {
|
|
388
|
-
if (props.panel.focused) props.refresh()
|
|
389
|
-
},
|
|
390
|
-
},
|
|
391
|
-
{
|
|
392
|
-
id: "context-indicator.breakdown.export",
|
|
393
|
-
title: "Export a redacted breakdown snapshot",
|
|
394
|
-
bind: "e",
|
|
395
|
-
enabled: () => props.panel.focused,
|
|
396
|
-
run: () => {
|
|
397
|
-
if (props.panel.focused) exportRedacted()
|
|
398
|
-
},
|
|
399
|
-
},
|
|
400
|
-
],
|
|
401
|
-
}))
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
// One snapshot read per poll tick (props.snapshot tracks the shared tick), so
|
|
405
|
-
// the memo recomputes together with the sidebar instead of polling separately.
|
|
406
|
-
const data = createMemo(() => {
|
|
407
|
-
const snap = props.snapshot()
|
|
408
|
-
return {
|
|
409
|
-
root: snap[props.panel.sessionID],
|
|
410
|
-
rows: collectFamily(snap, props.panel.sessionID),
|
|
411
|
-
}
|
|
412
|
-
})
|
|
413
|
-
|
|
414
|
-
// Live message list from the TUI data layer (in-process, no LLM call). The
|
|
415
|
-
// shared `props.snapshot()` tick is read FIRST so this re-reads every poll.
|
|
416
|
-
// `available: false` means the API is absent/errored -> the WHOLE measured
|
|
417
|
-
// section is hidden (and a one-time hint was logged).
|
|
418
|
-
const messages = createMemo<{ available: boolean; list: unknown[] }>(() => {
|
|
419
|
-
props.snapshot()
|
|
420
|
-
try {
|
|
421
|
-
const api = context?.data?.session?.message
|
|
422
|
-
if (!api || typeof api.list !== "function") {
|
|
423
|
-
if (!warnedMessagesUnavailable) {
|
|
424
|
-
warnedMessagesUnavailable = true
|
|
425
|
-
console.error(
|
|
426
|
-
"[context-indicator] TUI message data API unavailable; " +
|
|
427
|
-
"measured contributors section hidden",
|
|
428
|
-
)
|
|
429
|
-
}
|
|
430
|
-
return { available: false, list: [] }
|
|
431
|
-
}
|
|
432
|
-
const v = api.list(props.panel.sessionID)
|
|
433
|
-
return { available: true, list: Array.isArray(v) ? v : [] }
|
|
434
|
-
} catch {
|
|
435
|
-
if (!warnedMessagesUnavailable) {
|
|
436
|
-
warnedMessagesUnavailable = true
|
|
437
|
-
console.error(
|
|
438
|
-
"[context-indicator] TUI message read failed; " +
|
|
439
|
-
"measured contributors section hidden",
|
|
440
|
-
)
|
|
441
|
-
}
|
|
442
|
-
return { available: false, list: [] }
|
|
443
|
-
}
|
|
444
|
-
})
|
|
445
|
-
|
|
446
|
-
const contributors = createMemo<Contributor[]>(() => {
|
|
447
|
-
const m = messages()
|
|
448
|
-
if (!m.available) return []
|
|
449
|
-
try {
|
|
450
|
-
return measureContributors(m.list)
|
|
451
|
-
} catch {
|
|
452
|
-
return []
|
|
453
|
-
}
|
|
454
|
-
})
|
|
455
|
-
|
|
456
|
-
// Redacted export (key `e`). No message text, no full session id, no tool
|
|
457
|
-
// output content ever leaves this function. Never throws: a failure logs and
|
|
458
|
-
// shows an error toast instead.
|
|
459
|
-
function exportRedacted(): void {
|
|
460
|
-
let exportedName: string | null = null
|
|
461
|
-
try {
|
|
462
|
-
const now = new Date()
|
|
463
|
-
const name = exportFileName(props.panel.sessionID, now)
|
|
464
|
-
const payload = buildRedactedPayload({
|
|
465
|
-
sessionID: props.panel.sessionID,
|
|
466
|
-
root: data().root,
|
|
467
|
-
rows: data().rows,
|
|
468
|
-
contributors: contributors(),
|
|
469
|
-
now,
|
|
470
|
-
panelDenom,
|
|
471
|
-
panelRole,
|
|
472
|
-
num,
|
|
473
|
-
})
|
|
474
|
-
const dir = join(tmpdir(), "opencode-context-indicator", "exports")
|
|
475
|
-
const file = join(dir, name)
|
|
476
|
-
mkdirSync(dir, { recursive: true })
|
|
477
|
-
writeFileSync(file, JSON.stringify(payload, null, 2), "utf8")
|
|
478
|
-
exportedName = basename(file)
|
|
479
|
-
} catch (err) {
|
|
480
|
-
console.error("[context-indicator] redacted export failed:", err)
|
|
481
|
-
try {
|
|
482
|
-
context?.ui?.toast?.show({
|
|
483
|
-
message: "redacted export failed",
|
|
484
|
-
variant: "error",
|
|
485
|
-
})
|
|
486
|
-
} catch {
|
|
487
|
-
/* toast is best-effort */
|
|
488
|
-
}
|
|
489
|
-
return
|
|
490
|
-
}
|
|
491
|
-
// Outside the write try: a toast failure must not report the export as
|
|
492
|
-
// failed when the file is already on disk.
|
|
493
|
-
try {
|
|
494
|
-
context?.ui?.toast?.show({
|
|
495
|
-
message: `exported ${exportedName}`,
|
|
496
|
-
variant: "success",
|
|
497
|
-
})
|
|
498
|
-
} catch {
|
|
499
|
-
/* toast is best-effort */
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
const header = (): string => {
|
|
504
|
-
const r = data().root
|
|
505
|
-
if (!r) return "Context breakdown"
|
|
506
|
-
const model = safeText(r.model && r.model !== "unknown" ? r.model : "model?")
|
|
507
|
-
const ctx = fmt(num(r.ctx))
|
|
508
|
-
const d = panelDenom(r)
|
|
509
|
-
return d > 0
|
|
510
|
-
? `Context breakdown \u2014 ${model} ${ctx}/${fmt(d)} (${Math.round(
|
|
511
|
-
(num(r.ctx) / d) * 100,
|
|
512
|
-
)}%)`
|
|
513
|
-
: `Context breakdown \u2014 ${model} ${ctx}`
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
const layout = (): {
|
|
517
|
-
roleW: number
|
|
518
|
-
modelW: number
|
|
519
|
-
ctxW: number
|
|
520
|
-
updW: number
|
|
521
|
-
gutter: string
|
|
522
|
-
} => panelLayout(props.panel.width)
|
|
523
|
-
|
|
524
|
-
const columns = (): string => {
|
|
525
|
-
const L = layout()
|
|
526
|
-
return (
|
|
527
|
-
fit("role", L.roleW) +
|
|
528
|
-
L.gutter +
|
|
529
|
-
fit("model", L.modelW) +
|
|
530
|
-
L.gutter +
|
|
531
|
-
fit("ctx", L.ctxW) +
|
|
532
|
-
L.gutter +
|
|
533
|
-
"updated"
|
|
534
|
-
)
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
const row = (e: StateEntry, isMain: boolean): string => {
|
|
538
|
-
const model = safeText(e.model && e.model !== "unknown" ? e.model : "model?")
|
|
539
|
-
const d = panelDenom(e)
|
|
540
|
-
const ctx =
|
|
541
|
-
d > 0
|
|
542
|
-
? `${fmt(num(e.ctx))} (${Math.round((num(e.ctx) / d) * 100)}%)`
|
|
543
|
-
: fmt(num(e.ctx))
|
|
544
|
-
const L = layout()
|
|
545
|
-
return (
|
|
546
|
-
fit(panelRole(e, isMain), L.roleW) +
|
|
547
|
-
L.gutter +
|
|
548
|
-
fit(model, L.modelW) +
|
|
549
|
-
L.gutter +
|
|
550
|
-
fit(ctx, L.ctxW) +
|
|
551
|
-
L.gutter +
|
|
552
|
-
updatedAt(e.updatedAt)
|
|
553
|
-
)
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
return (
|
|
557
|
-
<box flexDirection="column">
|
|
558
|
-
<text fg={base()}>{header()}</text>
|
|
559
|
-
<Show
|
|
560
|
-
when={data().root}
|
|
561
|
-
fallback={<text fg={muted()}>{" no data yet"}</text>}
|
|
562
|
-
>
|
|
563
|
-
<text fg={muted()}>{columns()}</text>
|
|
564
|
-
{data().rows.map((e, i) => (
|
|
565
|
-
<text fg={muted()}>{row(e, i === 0)}</text>
|
|
566
|
-
))}
|
|
567
|
-
<Show
|
|
568
|
-
when={
|
|
569
|
-
(data().root?.usable ?? 0) > 0
|
|
570
|
-
}
|
|
571
|
-
>
|
|
572
|
-
<text fg={muted()}>
|
|
573
|
-
{" compact at " +
|
|
574
|
-
fmt(num(data().root?.usable)) +
|
|
575
|
-
(num(data().root?.reserve) > 0
|
|
576
|
-
? " (" + fmt(num(data().root?.reserve)) + " reserve)"
|
|
577
|
-
: "")}
|
|
578
|
-
</text>
|
|
579
|
-
</Show>
|
|
580
|
-
<Show when={messages().available}>
|
|
581
|
-
<text fg={base()}>{"largest contributors (measured)"}</text>
|
|
582
|
-
<Show
|
|
583
|
-
when={contributors().length > 0}
|
|
584
|
-
fallback={<text fg={muted()}>{" no messages yet"}</text>}
|
|
585
|
-
>
|
|
586
|
-
{contributors()
|
|
587
|
-
.slice(0, 5)
|
|
588
|
-
.map((c, i) => (
|
|
589
|
-
<text fg={muted()}>{contributorLine(c, i + 1)}</text>
|
|
590
|
-
))}
|
|
591
|
-
</Show>
|
|
592
|
-
<text fg={muted()}>
|
|
593
|
-
{
|
|
594
|
-
"measured != server categories (tool outputs counted here; server categories exclude them)"
|
|
595
|
-
}
|
|
596
|
-
</text>
|
|
597
|
-
</Show>
|
|
598
|
-
</Show>
|
|
599
|
-
</box>
|
|
600
|
-
)
|
|
601
|
-
}
|
|
602
|
-
|
|
603
69
|
export default Plugin.define({
|
|
604
70
|
id: "context-indicator.tui",
|
|
605
71
|
setup(context) {
|
|
@@ -672,6 +138,15 @@ export default Plugin.define({
|
|
|
672
138
|
id: "context-indicator.breakdown",
|
|
673
139
|
title: "Context breakdown panel",
|
|
674
140
|
slash: { name: "cx" },
|
|
141
|
+
// Palette-visible AND directly bound: subagent session views
|
|
142
|
+
// force the composer into its "subagents" tab, which pushes
|
|
143
|
+
// keymap mode "composer" — the base-mode palette binding
|
|
144
|
+
// (ctrl+p) is inert there and there is no prompt to type /cx.
|
|
145
|
+
// A bind on this mode:"global" layer fires in every mode
|
|
146
|
+
// (leader matches <leader>b "toggle sidebar"; f4 as a direct
|
|
147
|
+
// single-chord fallback).
|
|
148
|
+
palette: true,
|
|
149
|
+
bind: "<leader>c,f4",
|
|
675
150
|
run: () => {
|
|
676
151
|
const panelApi = context?.ui?.panel
|
|
677
152
|
if (panelApi && typeof panelApi.open === "function") {
|
|
@@ -686,6 +161,31 @@ export default Plugin.define({
|
|
|
686
161
|
},
|
|
687
162
|
})
|
|
688
163
|
|
|
164
|
+
// One-time live-surface marker. The e2e Check A asserts this line from the
|
|
165
|
+
// isolated instance's private log: it proves the ./tui entry not only
|
|
166
|
+
// loaded but REGISTERED its surfaces — a host-transform failure of this
|
|
167
|
+
// file would otherwise die silently between "loading plugin" and here.
|
|
168
|
+
console.log(
|
|
169
|
+
"[context-indicator] live TUI surfaces registered (sidebar + session.panel + keymap)",
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
// E2E instrumentation (only when test/e2e-tui.mjs sets the marker env):
|
|
173
|
+
// same proof as the console line above, but via a FILE — the TUI captures
|
|
174
|
+
// console output, so the log channel cannot carry it. Production runs
|
|
175
|
+
// never set the env and never write the stamp.
|
|
176
|
+
if (process.env.OPENCODE_CONTEXT_INDICATOR_TUI_MARKER) {
|
|
177
|
+
try {
|
|
178
|
+
mkdirSync(join(tmpdir(), "opencode-context-indicator"), { recursive: true })
|
|
179
|
+
writeFileSync(
|
|
180
|
+
join(tmpdir(), "opencode-context-indicator", "tui-live.stamp"),
|
|
181
|
+
new Date().toISOString(),
|
|
182
|
+
"utf8",
|
|
183
|
+
)
|
|
184
|
+
} catch {
|
|
185
|
+
/* marker is best-effort test instrumentation */
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
689
189
|
return () => {
|
|
690
190
|
clearInterval(timer)
|
|
691
191
|
for (const unregister of [
|