@nandoblanco/opencode-local-tokens 0.0.0-stage → 0.1.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.ts ADDED
@@ -0,0 +1,919 @@
1
+ import type { TuiPluginContext } from "@opencode/plugin/tui";
2
+ import { prepareHandoff } from "./prepare-handoff.ts";
3
+ import { RGBA, TextAttributes } from "@opentui/core";
4
+ import {
5
+ createComponent,
6
+ createElement,
7
+ createTextNode,
8
+ effect,
9
+ insert,
10
+ insertNode,
11
+ setProp,
12
+ use,
13
+ } from "@opentui/solid";
14
+ import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show } from "solid-js";
15
+ import {
16
+ analyzeTokens,
17
+ billedTokens,
18
+ buildSessionHandoff,
19
+ CACHE_EXPIRING_IDLE_MS,
20
+ CACHE_HEAVY_CONTEXT_TOKENS,
21
+ CACHE_TTL_MS,
22
+ fmtNum,
23
+ getSessionStepStatus,
24
+ type MatchedSessionRow,
25
+ mutateSessionTag,
26
+ prewarmTokensCache,
27
+ type SessionStepStatus,
28
+ STEP_LIMIT_THRESHOLD,
29
+ STEP_WARNING_THRESHOLD,
30
+ totalTokensWithCache,
31
+ TOKEN_SORT_LABELS,
32
+ TOKEN_SORT_MODES,
33
+ type TokenSortMode,
34
+ } from "./tokens.ts";
35
+
36
+ function fmtDurationShort(ms: number): string {
37
+ if (!ms || ms <= 0) return "0s";
38
+ if (ms < 60_000) return `${Math.max(1, Math.ceil(ms / 1000))}s`;
39
+ if (ms < 3_600_000) {
40
+ const m = Math.floor(ms / 60_000);
41
+ const s = Math.floor((ms % 60_000) / 1000);
42
+ return s > 0 && m < 10 ? `${m}m ${s}s` : `${m}m`;
43
+ }
44
+ const h = Math.floor(ms / 3_600_000);
45
+ const m = Math.floor((ms % 3_600_000) / 60_000);
46
+ return m > 0 ? `${h}h ${m}m` : `${h}h`;
47
+ }
48
+
49
+ function el(tag: string, props: Record<string, any> | null, ...children: any[]) {
50
+ const node = createElement(tag);
51
+ if (props) {
52
+ for (const k of Object.keys(props)) {
53
+ if (k === "ref") {
54
+ use(props.ref, node);
55
+ continue;
56
+ }
57
+ const desc = Object.getOwnPropertyDescriptor(props, k);
58
+ if (desc?.get) {
59
+ effect(() => setProp(node, k, desc.get!()));
60
+ } else if (typeof props[k] === "function" && !k.startsWith("on") && k !== "renderBefore") {
61
+ effect(() => setProp(node, k, props[k]()));
62
+ } else {
63
+ setProp(node, k, props[k]);
64
+ }
65
+ }
66
+ }
67
+ for (const child of children) {
68
+ if (child === null || child === undefined || child === false) continue;
69
+ if (typeof child === "function") {
70
+ insert(node, child);
71
+ } else if (typeof child === "string" || typeof child === "number") {
72
+ insertNode(node, createTextNode(String(child)));
73
+ } else {
74
+ insertNode(node, child);
75
+ }
76
+ }
77
+ return node;
78
+ }
79
+
80
+ let activeContext: TuiPluginContext | null = null;
81
+
82
+ const FALLBACK_C = {
83
+ bg: RGBA.fromInts(16, 20, 28, 255),
84
+ cardBg: RGBA.fromInts(23, 29, 40, 255),
85
+ cardAlt: RGBA.fromInts(20, 25, 35, 255),
86
+ selectedBg: RGBA.fromInts(32, 46, 68, 255),
87
+ border: RGBA.fromInts(46, 58, 78, 255),
88
+ accent: RGBA.fromInts(88, 166, 255, 255),
89
+ good: RGBA.fromInts(63, 185, 80, 255),
90
+ warn: RGBA.fromInts(210, 153, 34, 255),
91
+ bad: RGBA.fromInts(248, 81, 73, 255),
92
+ text: RGBA.fromInts(230, 237, 243, 255),
93
+ muted: RGBA.fromInts(139, 148, 158, 255),
94
+ dim: RGBA.fromInts(88, 96, 105, 255),
95
+ };
96
+
97
+ function dialogSurface(): any {
98
+ try {
99
+ return activeContext?.theme?.surface("dialog");
100
+ } catch {
101
+ return undefined;
102
+ }
103
+ }
104
+
105
+ const C = {
106
+ bg: () => dialogSurface()?.background?.base ?? FALLBACK_C.bg,
107
+ cardBg: () =>
108
+ dialogSurface()?.background?.raised?.base ??
109
+ dialogSurface()?.background?.base ??
110
+ FALLBACK_C.cardBg,
111
+ cardAlt: () =>
112
+ dialogSurface()?.background?.raised?.base ??
113
+ dialogSurface()?.background?.base ??
114
+ FALLBACK_C.cardAlt,
115
+ selectedBg: () =>
116
+ dialogSurface()?.background?.action?.primary?.focused ?? FALLBACK_C.selectedBg,
117
+ selectedText: () =>
118
+ dialogSurface()?.text?.action?.primary?.focused ??
119
+ dialogSurface()?.text?.base ??
120
+ FALLBACK_C.accent,
121
+ border: () => dialogSurface()?.border?.base ?? FALLBACK_C.border,
122
+ accent: () => dialogSurface()?.text?.action?.primary?.base ?? FALLBACK_C.accent,
123
+ cyan: () => dialogSurface()?.text?.action?.primary?.base ?? FALLBACK_C.accent,
124
+ purple: () => dialogSurface()?.text?.action?.primary?.base ?? FALLBACK_C.accent,
125
+ good: () => dialogSurface()?.text?.feedback?.success?.base ?? FALLBACK_C.good,
126
+ warn: () => dialogSurface()?.text?.feedback?.warning?.base ?? FALLBACK_C.warn,
127
+ bad: () => dialogSurface()?.text?.feedback?.error?.base ?? FALLBACK_C.bad,
128
+ text: () => dialogSurface()?.text?.base ?? FALLBACK_C.text,
129
+ muted: () => dialogSurface()?.text?.muted ?? FALLBACK_C.muted,
130
+ dim: () => dialogSurface()?.text?.subtle ?? dialogSurface()?.text?.muted ?? FALLBACK_C.dim,
131
+ };
132
+
133
+ function statusColor(s: "good" | "warn" | "bad" | "neutral") {
134
+ if (s === "good") return C.good;
135
+ if (s === "warn") return C.warn;
136
+ if (s === "bad") return C.bad;
137
+ return C.accent;
138
+ }
139
+
140
+ function renderBar(pct: number, width = 18): { filled: string; empty: string } {
141
+ const clamped = Math.max(0, Math.min(100, pct));
142
+ const fillCount = Math.round((clamped / 100) * width);
143
+ return {
144
+ filled: "█".repeat(fillCount),
145
+ empty: "░".repeat(Math.max(0, width - fillCount)),
146
+ };
147
+ }
148
+
149
+ function fmtCompact(n: number) { return fmtNum(n); }
150
+ const [sharedStepStatus, setSharedStepStatus] = createSignal<SessionStepStatus | null>(null);
151
+ const warnedSessions = new Set<string>();
152
+ const promptedOverLimitTurnKeys = new Set<string>();
153
+
154
+ function getActiveTuiSessionId(context: TuiPluginContext): string | undefined {
155
+ try {
156
+ const route = context.ui.router.current();
157
+ if (route && route.type === "session" && typeof route.sessionID === "string") {
158
+ return route.sessionID;
159
+ }
160
+ } catch {}
161
+ return undefined;
162
+ }
163
+
164
+ async function runTuiSessionHandoff(context: TuiPluginContext, explicitSessionId?: string) {
165
+ const sid = explicitSessionId || getActiveTuiSessionId(context);
166
+ if (!sid) return;
167
+ try {
168
+ context.ui.toast.show({ title: "Preparing handoff with AI", message: "Saving a fresh checkpoint before export. This uses model tokens.", variant: "info", duration: 6000 });
169
+ await prepareHandoff(sid, context.client.session);
170
+ } catch (error) {
171
+ context.ui.toast.show({ title: "Handoff preparation failed", message: String(error), variant: "warning", duration: 6000 });
172
+ return;
173
+ }
174
+ const handoff = buildSessionHandoff(sid);
175
+ if (!handoff) {
176
+ context.ui.toast.show({
177
+ title: "Handoff unavailable",
178
+ message: "No active session found to generate a handoff.",
179
+ variant: "warning",
180
+ duration: 4000,
181
+ });
182
+ return;
183
+ }
184
+
185
+ context.ui.toast.show({
186
+ title: "Handoff checkpoint saved",
187
+ message: `Saved ${handoff.shortId} (${handoff.count} steps) → ${handoff.checkpointPath}`,
188
+ variant: "success",
189
+ duration: 6000,
190
+ });
191
+
192
+ try {
193
+ const created: any = await (context.client as any).session.create({
194
+ directory: handoff.directory || undefined,
195
+ title: `Handoff: ${handoff.title}`.slice(0, 80),
196
+ });
197
+ const newId = created?.id || created?.data?.id;
198
+ if (newId) {
199
+ context.ui.router.navigate({ type: "session", sessionID: newId });
200
+ try {
201
+ await (context.client as any).session.prompt({
202
+ sessionID: newId,
203
+ text: handoff.handoffPrompt,
204
+ });
205
+ } catch {}
206
+ }
207
+ } catch {}
208
+ }
209
+
210
+ async function checkSessionStepAlerts(context: TuiPluginContext, explicitSessionId?: string) {
211
+ const sid = explicitSessionId || getActiveTuiSessionId(context);
212
+ if (!sid) {
213
+ setSharedStepStatus(null);
214
+ return;
215
+ }
216
+ let st = getSessionStepStatus(sid);
217
+ if (st) {
218
+ try {
219
+ const models = await context.client.model.list({ location: { directory: st.directory } });
220
+ const capacities = Object.fromEntries(models.data.map(model => [`${model.providerID}/${model.id}`, model.limit.context]));
221
+ st = getSessionStepStatus(sid, { modelCapacities: capacities });
222
+ } catch {}
223
+ }
224
+ setSharedStepStatus(st);
225
+ }
226
+
227
+ function SessionStepComposerBanner(props: { context: TuiPluginContext; sessionID: string }) {
228
+ const [tuiNow, setTuiNow] = createSignal(Date.now());
229
+
230
+ onMount(() => {
231
+ checkSessionStepAlerts(props.context, props.sessionID);
232
+ const timer = setInterval(() => {
233
+ checkSessionStepAlerts(props.context, props.sessionID);
234
+ }, 2500);
235
+ const clock = setInterval(() => {
236
+ setTuiNow(Date.now());
237
+ }, 1000);
238
+ onCleanup(() => {
239
+ clearInterval(timer);
240
+ clearInterval(clock);
241
+ });
242
+ });
243
+
244
+ const info = createMemo(() => {
245
+ const st = sharedStepStatus();
246
+ if (!st || st.sessionId !== props.sessionID) return null;
247
+ if ((st.liveContextTokens ?? 0) < CACHE_HEAVY_CONTEXT_TOKENS) return null;
248
+ try {
249
+ if (props.context.data.session.status(st.sessionId) === "running") return null;
250
+ } catch {}
251
+ const refTime = st.lastReplyAt || st.timeUpdated || 0;
252
+ if (refTime <= 0) return null;
253
+ const ttlMs = st.cacheTtlMs || CACHE_TTL_MS;
254
+ const idleMs = Math.max(st.idleMs ?? 0, tuiNow() - refTime);
255
+ if (idleMs < CACHE_EXPIRING_IDLE_MS) return null;
256
+ const remMs = Math.max(0, ttlMs - idleMs);
257
+ const state: "expiring" | "expired" = idleMs >= ttlMs ? "expired" : "expiring";
258
+ return { st, idleMs, remMs, state };
259
+ });
260
+
261
+ return createComponent(Show, {
262
+ get when() {
263
+ return info();
264
+ },
265
+ children: (item: () => { st: SessionStepStatus; idleMs: number; remMs: number; state: "expiring" | "expired" }) =>
266
+ el(
267
+ "box",
268
+ {
269
+ flexDirection: "row",
270
+ justifyContent: "space-between",
271
+ paddingLeft: 1,
272
+ paddingRight: 1,
273
+ width: "100%",
274
+ get backgroundColor() {
275
+ return C.cardBg();
276
+ },
277
+ border: true,
278
+ get borderColor() {
279
+ return item().state === "expired" ? C.bad() : C.warn();
280
+ },
281
+ },
282
+ el(
283
+ "text",
284
+ {
285
+ get fg() {
286
+ return item().state === "expired" ? C.bad() : C.warn();
287
+ },
288
+ },
289
+ () =>
290
+ item().state === "expired"
291
+ ? `Prompt cache likely expired (idle ${fmtDurationShort(item().idleMs)} · ${item().st.statusReason}). Reply re-sends ${fmtNum(item().st.liveContextTokens)} uncached; consider /handoff.`
292
+ : `Prompt cache expiring (${fmtDurationShort(item().remMs)} left · ${item().st.statusReason}). Reply soon or run /handoff.`
293
+ ),
294
+ el("text", { fg: C.cyan }, "[/handoff]")
295
+ ),
296
+ });
297
+ }
298
+ function parseInlineTokensFilter(raw: string): {
299
+ query: string;
300
+ project: string;
301
+ model: string;
302
+ tag: string;
303
+ likedOnly: boolean;
304
+ } {
305
+ let project = "";
306
+ let model = "";
307
+ let tag = "";
308
+ let likedOnly = false;
309
+ const freeTerms: string[] = [];
310
+
311
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
312
+ for (const tok of tokens) {
313
+ const lower = tok.toLowerCase();
314
+ if (lower.startsWith("project:") || lower.startsWith("p:")) {
315
+ project = tok.slice(tok.indexOf(":") + 1);
316
+ } else if (lower.startsWith("model:") || lower.startsWith("m:")) {
317
+ model = tok.slice(tok.indexOf(":") + 1);
318
+ } else if (lower.startsWith("tag:") || lower.startsWith("t:") || lower.startsWith("#")) {
319
+ tag = tok.startsWith("#") ? tok.slice(1) : tok.slice(tok.indexOf(":") + 1);
320
+ } else if (lower === "liked:true" || lower === "liked" || lower === "*") {
321
+ likedOnly = true;
322
+ } else {
323
+ freeTerms.push(tok);
324
+ }
325
+ }
326
+ return {
327
+ query: freeTerms.join(" "),
328
+ project,
329
+ model,
330
+ tag,
331
+ likedOnly,
332
+ };
333
+ }
334
+
335
+ function TokensDialog(props: {
336
+ context: TuiPluginContext;
337
+ initialInput?: string;
338
+ onClose: () => void;
339
+ }) {
340
+ activeContext = props.context;
341
+ const [input, setInput] = createSignal(props.initialInput || "");
342
+ const [debouncedInput, setDebouncedInput] = createSignal(props.initialInput || "");
343
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
344
+ const [refreshTick, setRefreshTick] = createSignal(0);
345
+ const [sortMode, setSortMode] = createSignal<TokenSortMode>("relevance");
346
+ const [editing, setEditing] = createSignal<"sort" | "tag" | "untag" | null>(null);
347
+ const [sortIndex, setSortIndex] = createSignal(0);
348
+ const [tagInput, setTagInput] = createSignal("");
349
+ const [tagSession, setTagSession] = createSignal<MatchedSessionRow | null>(null);
350
+ const [feedback, setFeedback] = createSignal("");
351
+ const [actionError, setActionError] = createSignal(false);
352
+
353
+ let debounceTimer: ReturnType<typeof setTimeout> | null = null;
354
+ createEffect(() => {
355
+ const val = input();
356
+ if (debounceTimer) clearTimeout(debounceTimer);
357
+ if (!val) {
358
+ setDebouncedInput("");
359
+ return;
360
+ }
361
+ debounceTimer = setTimeout(() => {
362
+ setDebouncedInput(val);
363
+ }, 35);
364
+ });
365
+
366
+ const report = createMemo(() => {
367
+ refreshTick();
368
+ const parsed = parseInlineTokensFilter(debouncedInput());
369
+ try {
370
+ return analyzeTokens({
371
+ query: parsed.query,
372
+ project: parsed.project,
373
+ model: parsed.model,
374
+ tag: parsed.tag,
375
+ likedOnly: parsed.likedOnly,
376
+ sort: sortMode(),
377
+ limit: 80,
378
+ });
379
+ } catch {
380
+ return null;
381
+ }
382
+ });
383
+
384
+ createEffect(() => {
385
+ debouncedInput();
386
+ sortMode();
387
+ setSelectedIndex(0);
388
+ });
389
+
390
+ onMount(() => {
391
+ setTimeout(() => {
392
+ try {
393
+ prewarmTokensCache();
394
+ } catch {}
395
+ }, 10);
396
+ const keyInput = props.context.renderer.keyInput as any;
397
+ const handler = (key: any) => {
398
+ const rows = report()?.sessions || [];
399
+ const enter = key.name === "return" || key.name === "enter" || key.name === "kpenter";
400
+ if (editing()) {
401
+ key.preventDefault?.();
402
+ key.stopPropagation?.();
403
+ if (key.name === "escape") {
404
+ setEditing(null);
405
+ } else if (editing() === "sort") {
406
+ if (key.name === "down") setSortIndex((i) => (i + 1) % TOKEN_SORT_MODES.length);
407
+ else if (key.name === "up") setSortIndex((i) => (i + TOKEN_SORT_MODES.length - 1) % TOKEN_SORT_MODES.length);
408
+ else if (enter) {
409
+ setSortMode(TOKEN_SORT_MODES[sortIndex()]);
410
+ setEditing(null);
411
+ }
412
+ } else if (enter) {
413
+ const session = tagSession();
414
+ const value = tagInput().split(",").map((tag) => tag.trim().replace(/^#/, "")).filter(Boolean).join(",");
415
+ if (!value) {
416
+ setActionError(true);
417
+ setFeedback("Enter at least one tag. Separate multiple tags with commas.");
418
+ } else if (session) {
419
+ try {
420
+ mutateSessionTag(editing() as "tag" | "untag", session.id, value);
421
+ setFeedback(`${editing() === "tag" ? "Added" : "Removed"} tags: ${value}`);
422
+ setActionError(false);
423
+ setEditing(null);
424
+ setRefreshTick((t) => t + 1);
425
+ setSelectedIndex((i) => Math.max(0, Math.min(i, (report()?.sessions.length || 1) - 1)));
426
+ } catch (error) {
427
+ setActionError(true);
428
+ setFeedback(`Tags not saved: ${String(error)}`);
429
+ }
430
+ }
431
+ } else if (key.ctrl && key.name === "u") {
432
+ setTagInput("");
433
+ setFeedback("");
434
+ } else if (key.name === "backspace") {
435
+ setTagInput((value) => Array.from(value).slice(0, -1).join(""));
436
+ setFeedback("");
437
+ } else if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta && key.sequence.charCodeAt(0) >= 32) {
438
+ setTagInput((value) => value + key.sequence);
439
+ setFeedback("");
440
+ }
441
+ return;
442
+ }
443
+ if (key.ctrl && (key.name === "s" || key.name === "t" || key.name === "r")) {
444
+ key.preventDefault?.();
445
+ key.stopPropagation?.();
446
+ setFeedback("");
447
+ setActionError(false);
448
+ if (key.name === "s") {
449
+ setSortIndex(TOKEN_SORT_MODES.indexOf(sortMode()));
450
+ setEditing("sort");
451
+ } else {
452
+ const picked = rows[selectedIndex()];
453
+ if (picked) {
454
+ setTagSession(picked);
455
+ setTagInput("");
456
+ setEditing(key.name === "t" ? "tag" : "untag");
457
+ }
458
+ }
459
+ return;
460
+ }
461
+ if (key.name === "down" || (key.ctrl && key.name === "n")) {
462
+ key.preventDefault?.();
463
+ key.stopPropagation?.();
464
+ if (rows.length > 0) setSelectedIndex((i) => Math.min(rows.length - 1, i + 1));
465
+ } else if (key.name === "up" || (key.ctrl && key.name === "p")) {
466
+ key.preventDefault?.();
467
+ key.stopPropagation?.();
468
+ if (rows.length > 0) setSelectedIndex((i) => Math.max(0, i - 1));
469
+ } else if (key.name === "return" || key.name === "enter" || key.name === "kpenter") {
470
+ const picked = rows[selectedIndex()];
471
+ if (picked) {
472
+ key.preventDefault?.();
473
+ key.stopPropagation?.();
474
+ props.onClose();
475
+ props.context.ui.router.navigate({
476
+ type: "session",
477
+ sessionID: picked.id,
478
+ });
479
+ }
480
+ } else if (key.ctrl && key.name === "l") {
481
+ const picked = rows[selectedIndex()];
482
+ if (picked) {
483
+ key.preventDefault?.();
484
+ key.stopPropagation?.();
485
+ try {
486
+ mutateSessionTag(picked.liked ? "unlike" : "like", picked.id);
487
+ setRefreshTick((t) => t + 1);
488
+ } catch {}
489
+ }
490
+ } else if (key.ctrl && key.name === "u") {
491
+ key.preventDefault?.();
492
+ key.stopPropagation?.();
493
+ setInput("");
494
+ } else if (key.name === "backspace") {
495
+ key.preventDefault?.();
496
+ key.stopPropagation?.();
497
+ setInput((prev) => prev.slice(0, -1));
498
+ } else if (
499
+ key.sequence &&
500
+ key.sequence.length === 1 &&
501
+ !key.ctrl &&
502
+ !key.meta &&
503
+ key.sequence.charCodeAt(0) >= 32
504
+ ) {
505
+ key.preventDefault?.();
506
+ key.stopPropagation?.();
507
+ setInput((prev) => prev + key.sequence);
508
+ }
509
+ };
510
+ if (typeof keyInput.prependListener === "function") {
511
+ keyInput.prependListener("keypress", handler);
512
+ } else {
513
+ keyInput.on?.("keypress", handler);
514
+ }
515
+ onCleanup(() => {
516
+ if (typeof keyInput.removeListener === "function") {
517
+ keyInput.removeListener("keypress", handler);
518
+ } else {
519
+ keyInput.off?.("keypress", handler);
520
+ }
521
+ });
522
+ });
523
+
524
+ return el(
525
+ "box",
526
+ {
527
+ flexDirection: "column",
528
+ width: "100%",
529
+ backgroundColor: C.bg,
530
+ paddingLeft: 2,
531
+ paddingRight: 2,
532
+ paddingTop: 1,
533
+ paddingBottom: 1,
534
+ gap: 1,
535
+ },
536
+ el(
537
+ "box",
538
+ {
539
+ flexDirection: "row",
540
+ justifyContent: "space-between",
541
+ alignItems: "center",
542
+ gap: 2,
543
+ border: ["bottom"],
544
+ borderColor: C.border,
545
+ paddingBottom: 0,
546
+ flexShrink: 0,
547
+ width: "100%",
548
+ },
549
+ el("text", { fg: C.accent, wrapMode: "none", flexShrink: 0, attributes: TextAttributes.BOLD }, "opencode / tokens"),
550
+ el(
551
+ "text",
552
+ { fg: C.muted, wrapMode: "none", flexShrink: 1, minWidth: 0, truncate: true },
553
+ "[↑↓] select [Enter] open [^L] like [^U] clear [Esc] close"
554
+ )
555
+ ),
556
+ el(
557
+ "box",
558
+ {
559
+ flexDirection: "column",
560
+ justifyContent: "space-between",
561
+ backgroundColor: C.cardBg,
562
+ border: true,
563
+ borderColor: C.accent,
564
+ paddingLeft: 2,
565
+ paddingRight: 2,
566
+ paddingTop: 0,
567
+ paddingBottom: 0,
568
+ },
569
+ el(
570
+ "box",
571
+ {
572
+ flexDirection: "row",
573
+ gap: 1,
574
+ width: "100%",
575
+ },
576
+ el("text", { fg: C.cyan }, "Filter:"),
577
+ el(
578
+ "text",
579
+ {
580
+ flexGrow: 1,
581
+ flexShrink: 1,
582
+ minWidth: 0,
583
+ wrapMode: "none",
584
+ truncate: true,
585
+ get fg() {
586
+ return input() ? C.text() : C.dim();
587
+ },
588
+ },
589
+ () =>
590
+ input()
591
+ ? `${input()}█`
592
+ : "Search or filter..."
593
+ )
594
+ ),
595
+ el(
596
+ "text",
597
+ { fg: C.muted, wrapMode: "none", truncate: true },
598
+ () => `Sort: ${TOKEN_SORT_LABELS[sortMode()]} ^s add tags ^t remove tags ^r`
599
+ ),
600
+ el(
601
+ "box",
602
+ { flexDirection: "row" },
603
+ createComponent(Show, {
604
+ get when() {
605
+ return report();
606
+ },
607
+ children: (r: () => NonNullable<ReturnType<typeof report>>) =>
608
+ el(
609
+ "text",
610
+ { fg: C.good },
611
+ () =>
612
+ `${r().totalSessionsMatched} sessions · ${r().totals.turns.toLocaleString()} turns · Billed: ${fmtNum(
613
+ billedTokens(r().totals)
614
+ )} · w/Cache: ${fmtNum(totalTokensWithCache(r().totals))}`
615
+ ),
616
+ })
617
+ )
618
+ ),
619
+ createComponent(Show, {
620
+ get when() { return editing(); },
621
+ children: () => el(
622
+ "box",
623
+ { flexDirection: "column", border: true, borderColor: C.accent, paddingLeft: 1, paddingRight: 1 },
624
+ createComponent(Show, {
625
+ get when() { return editing() === "sort"; },
626
+ get fallback() {
627
+ return el(
628
+ "box",
629
+ { flexDirection: "column" },
630
+ el("text", { fg: C.accent, wrapMode: "none", truncate: true }, () => `${editing() === "tag" ? "Add" : "Remove"} tags: ${tagSession()?.smartTitle}`),
631
+ el("text", { fg: C.muted }, () => `Current: ${tagSession()?.tags.map((tag) => `#${tag}`).join(", ") || "none"}`),
632
+ el("text", { fg: C.text, wrapMode: "none", truncate: true }, () => `${tagInput() || "Comma-separated tags"}█`),
633
+ el("text", { fg: C.muted }, "[Enter] save [Esc] cancel [Ctrl+U] clear")
634
+ );
635
+ },
636
+ children: () => el(
637
+ "box",
638
+ { flexDirection: "column" },
639
+ el("text", { fg: C.accent }, "Sort sessions [↑↓] choose [Enter] apply [Esc] cancel"),
640
+ ...TOKEN_SORT_MODES.map((mode, index) => el(
641
+ "text",
642
+ { get fg() { return index === sortIndex() ? C.accent() : C.muted(); } },
643
+ () => `${index === sortIndex() ? "> " : " "}${TOKEN_SORT_LABELS[mode]}${mode === sortMode() ? " (active)" : ""}`
644
+ ))
645
+ ),
646
+ })
647
+ ),
648
+ }),
649
+ createComponent(Show, {
650
+ get when() { return feedback(); },
651
+ children: () => el("text", { get fg() { return actionError() ? C.bad() : C.good(); } }, feedback),
652
+ }),
653
+ el(
654
+ "box",
655
+ { flexDirection: "column", width: "100%" },
656
+ createComponent(Show, {
657
+ get when() {
658
+ return report();
659
+ },
660
+ children: (r: () => NonNullable<ReturnType<typeof report>>) =>
661
+ el(
662
+ "box",
663
+ {
664
+ flexDirection: "row",
665
+ gap: 2,
666
+ width: "100%",
667
+ },
668
+ el(
669
+ "box",
670
+ {
671
+ flexDirection: "column",
672
+ flexGrow: 1,
673
+ flexBasis: 0,
674
+ backgroundColor: C.cardAlt,
675
+ border: true,
676
+ borderColor: C.border,
677
+ paddingLeft: 2,
678
+ paddingRight: 2,
679
+ paddingTop: 0,
680
+ paddingBottom: 0,
681
+ },
682
+ el("text", { fg: C.purple }, "TOP MODELS (MATCHED SCOPE)"),
683
+ createComponent(For, {
684
+ get each() {
685
+ return r().sortedModels.slice(0, 5);
686
+ },
687
+ children: ([m, v]: [string, any]) => {
688
+ const grand = billedTokens(r().totals) || 1;
689
+ const pct = Math.round((v.total / grand) * 100);
690
+ return el(
691
+ "box",
692
+ {
693
+ flexDirection: "row",
694
+ justifyContent: "space-between",
695
+ gap: 1,
696
+ },
697
+ el("text", { fg: C.text, wrapMode: "none", flexShrink: 1, minWidth: 0, truncate: true }, m.slice(0, 32)),
698
+ el("text", { fg: C.cyan, wrapMode: "none", flexShrink: 0 }, `${fmtNum(v.total)} ${pct}% · ${v.turns} steps`)
699
+ );
700
+ },
701
+ })
702
+ ),
703
+ el(
704
+ "box",
705
+ {
706
+ flexDirection: "column",
707
+ flexGrow: 1,
708
+ flexBasis: 0,
709
+ backgroundColor: C.cardAlt,
710
+ border: true,
711
+ borderColor: C.border,
712
+ paddingLeft: 2,
713
+ paddingRight: 2,
714
+ paddingTop: 0,
715
+ paddingBottom: 0,
716
+ },
717
+ el("text", { fg: C.purple }, "TOP PROJECTS & TAGS"),
718
+ createComponent(For, {
719
+ get each() {
720
+ return r().sortedProjects.slice(0, 4);
721
+ },
722
+ children: ([proj, v]: [string, any]) =>
723
+ el(
724
+ "box",
725
+ {
726
+ flexDirection: "row",
727
+ justifyContent: "space-between",
728
+ gap: 1,
729
+ },
730
+ el("text", { fg: C.text, wrapMode: "none", flexShrink: 1, minWidth: 0, truncate: true }, proj.slice(0, 24)),
731
+ el("text", { fg: C.good, wrapMode: "none", flexShrink: 0 }, `${fmtNum(v.billed)} · ${v.sessions} sess`)
732
+ ),
733
+ }),
734
+ createComponent(For, {
735
+ get each() {
736
+ return r().topTags.slice(0, 4);
737
+ },
738
+ children: ([t, v]: [string, any]) =>
739
+ el(
740
+ "box",
741
+ { flexDirection: "row", justifyContent: "space-between", gap: 1 },
742
+ el("text", { fg: C.muted, wrapMode: "none", flexShrink: 1, minWidth: 0, truncate: true }, `#${t}`),
743
+ el("text", { fg: C.muted, wrapMode: "none", flexShrink: 0 }, fmtNum(v.billed))
744
+ ),
745
+ })
746
+ )
747
+ ),
748
+ })
749
+ ),
750
+ el(
751
+ "box",
752
+ {
753
+ flexDirection: "column",
754
+ backgroundColor: C.cardBg,
755
+ border: true,
756
+ borderColor: C.border,
757
+ paddingLeft: 2,
758
+ paddingRight: 2,
759
+ paddingTop: 0,
760
+ paddingBottom: 0,
761
+ },
762
+ el(
763
+ "box",
764
+ { flexDirection: "row", border: ["bottom"], borderColor: C.border },
765
+ el("text", { fg: C.muted, wrapMode: "none", truncate: true }, " ID".padEnd(13) + "Project".padEnd(21) + "Billed".padStart(9) + "w/Cache".padStart(10) + "Steps".padStart(7) + " Session Title & Tags")
766
+ ),
767
+ (() => {
768
+ const VIEWPORT = 8;
769
+ return el(
770
+ "box",
771
+ { flexDirection: "column", width: "100%" },
772
+ createComponent(Show, {
773
+ get when() {
774
+ return report()?.sessions.length;
775
+ },
776
+ get fallback() {
777
+ return el("text", { fg: C.dim }, "No sessions matched the current filter.");
778
+ },
779
+ get children() {
780
+ const rows = report()?.sessions || [];
781
+ const sel = selectedIndex();
782
+ const offset = Math.max(0, Math.min(sel - (VIEWPORT - 1), Math.max(0, rows.length - VIEWPORT)));
783
+ const visible = rows.slice(offset, offset + VIEWPORT);
784
+ return visible.map((s: MatchedSessionRow, vIdx: number) => {
785
+ const absIdx = offset + vIdx;
786
+ const isSel = absIdx === selectedIndex();
787
+ const stepsStr = s.turnScoped ? `${s.turns}/${s.totalSessionTurns}` : String(s.steps || s.turns);
788
+ const tagsPreview = s.tags.length
789
+ ? ` [${s.tags
790
+ .slice(0, 2)
791
+ .map((t) => `#${t}`)
792
+ .join(" ")}]`
793
+ : "";
794
+ const line =
795
+ `${s.liked ? "★ " : isSel ? "▸ " : " "}${s.shortId.padEnd(11)}` +
796
+ `${(s.project.length > 20 ? `…${s.project.slice(-19)}` : s.project).padEnd(21)}` +
797
+ `${fmtNum(billedTokens(s.tokens)).padStart(9)}` +
798
+ `${fmtNum(totalTokensWithCache(s.tokens)).padStart(10)}` +
799
+ `${stepsStr.padStart(7)}`;
800
+ return el(
801
+ "box",
802
+ {
803
+ flexDirection: "row",
804
+ width: "100%",
805
+ gap: 2,
806
+ get backgroundColor() {
807
+ return isSel ? C.selectedBg() : undefined;
808
+ },
809
+ onMouseOver: () => setSelectedIndex(absIdx),
810
+ },
811
+ el(
812
+ "text",
813
+ {
814
+ wrapMode: "none",
815
+ flexShrink: 0,
816
+ get fg() {
817
+ return isSel ? C.selectedText() : s.liked ? C.warn() : C.text();
818
+ },
819
+ },
820
+ line
821
+ ),
822
+ el(
823
+ "text",
824
+ {
825
+ wrapMode: "none",
826
+ flexShrink: 1,
827
+ minWidth: 0,
828
+ truncate: true,
829
+ get fg() {
830
+ return isSel ? C.selectedText() : s.liked ? C.warn() : C.text();
831
+ },
832
+ },
833
+ `${s.smartTitle}${tagsPreview}`
834
+ )
835
+ );
836
+ }).concat(
837
+ el(
838
+ "text",
839
+ { fg: C.dim },
840
+ rows.length > VIEWPORT
841
+ ? ` (${offset + 1}-${Math.min(offset + VIEWPORT, rows.length)} of ${rows.length}) [↑↓ scroll]`
842
+ : ""
843
+ )
844
+ );
845
+ },
846
+ })
847
+ );
848
+ })()
849
+ )
850
+ );
851
+ }
852
+
853
+ export const tui = {
854
+ id: "opencode-local-tokens",
855
+ async setup(context: TuiPluginContext) {
856
+ activeContext = context;
857
+
858
+ const openTokensDialog = (initialInput = "") => {
859
+ context.ui.dialog.show(
860
+ () =>
861
+ createComponent(TokensDialog, {
862
+ context,
863
+ initialInput,
864
+ onClose: () => context.ui.dialog.clear(),
865
+ }),
866
+ () => {}
867
+ );
868
+ context.ui.dialog.set({
869
+ size: "xlarge",
870
+ centered: true,
871
+ });
872
+ };
873
+ if (context.options.cacheAlerts === true) context.ui.slot({
874
+ before: "session.composer.top",
875
+ render(props: { sessionID: string }) {
876
+ return createComponent(SessionStepComposerBanner, {
877
+ context,
878
+ sessionID: props.sessionID,
879
+ });
880
+ },
881
+ });
882
+ context.ui.slot({
883
+ append: "app",
884
+ render() {
885
+ context.keymap.layer(() => ({
886
+ mode: "global",
887
+ priority: 10,
888
+ commands: [
889
+ {
890
+ id: "tokens.open",
891
+ title: "Token & Topic Analytics Explorer (/tokens)",
892
+ section: "System",
893
+ slash: {
894
+ name: "tokens",
895
+ },
896
+ run() {
897
+ openTokensDialog("");
898
+ },
899
+ },
900
+ {
901
+ id: "tokens.session.handoff",
902
+ title: "Save Session Handoff Checkpoint & Start Fresh Session (/handoff)",
903
+ section: "System",
904
+ slash: {
905
+ name: "handoff",
906
+ },
907
+ run() {
908
+ void runTuiSessionHandoff(context);
909
+ },
910
+ },
911
+ ],
912
+ }));
913
+ return null;
914
+ },
915
+ });
916
+ },
917
+ };
918
+
919
+ export default tui;