@0xkahi/pi-qol 0.1.1 → 1.0.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/README.md +13 -0
- package/assets/config.schema.json +12 -0
- package/package.json +4 -4
- package/src/codemap.md +3 -2
- package/src/config-loader.ts +4 -0
- package/src/constants.ts +1 -0
- package/src/extensions/auto-session-name/title-generator.ts +1 -1
- package/src/extensions/codemap.md +9 -2
- package/src/extensions/context-view/capture.ts +394 -0
- package/src/extensions/context-view/codemap.md +28 -0
- package/src/extensions/context-view/constants.ts +4 -0
- package/src/extensions/context-view/context-view-controller.ts +67 -0
- package/src/extensions/context-view/index.ts +120 -0
- package/src/extensions/context-view/measure.ts +307 -0
- package/src/extensions/context-view/model.ts +207 -0
- package/src/extensions/context-view/ui/context-view-dialog.ts +81 -0
- package/src/extensions/context-view/ui/injections-model.ts +257 -0
- package/src/extensions/context-view/ui/injections-view.ts +396 -0
- package/src/extensions/context-view/ui/layout.ts +88 -0
- package/src/extensions/context-view/ui/navigation.ts +37 -0
- package/src/extensions/context-view/ui/skill-preview.ts +82 -0
- package/src/extensions/context-view/ui/usage-map.ts +133 -0
- package/src/extensions/context-view/ui/usage-view.ts +734 -0
- package/src/extensions/context-view/usage.ts +432 -0
- package/src/index.ts +2 -0
- package/src/schemas/codemap.md +2 -2
- package/src/schemas/config.schema.ts +3 -0
- package/src/schemas/context-view.config.schema.ts +13 -0
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
/** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
|
|
2
|
+
/**
|
|
3
|
+
* Focused `/context usage` view: estimated context composition with a
|
|
4
|
+
* proportional context-window map, pi-reported metadata, selectable category
|
|
5
|
+
* rows, and an Enter-opened chronological content preview.
|
|
6
|
+
*/
|
|
7
|
+
import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
|
|
8
|
+
import { Key, matchesKey, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
|
|
9
|
+
|
|
10
|
+
import type { ContextUsageSnapshot, UsageCategory, UsagePreviewEntry } from '../model';
|
|
11
|
+
import { collectPreviewEntries } from '../usage';
|
|
12
|
+
import { ListNavigator, normalizeInlineText, normalizePreviewText, PreviewScroller } from './injections-model';
|
|
13
|
+
import {
|
|
14
|
+
BODY_INDENT,
|
|
15
|
+
calculateViewport,
|
|
16
|
+
DEFAULT_TERMINAL_ROWS,
|
|
17
|
+
fitLine,
|
|
18
|
+
fitToTerminalHeight,
|
|
19
|
+
hintRow,
|
|
20
|
+
normalizeTerminalRows,
|
|
21
|
+
STEP_KEY_HINT,
|
|
22
|
+
spreadLine,
|
|
23
|
+
wrapDescriptionLines,
|
|
24
|
+
} from './layout';
|
|
25
|
+
import type { NavigationAction } from './navigation';
|
|
26
|
+
import { splitSkillPreview } from './skill-preview';
|
|
27
|
+
import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
|
|
28
|
+
|
|
29
|
+
const USAGE_DESCRIPTION =
|
|
30
|
+
'Estimated context for the next model request. ' + "Token counts are approximate and may differ from the provider's estimate.";
|
|
31
|
+
const INVISIBLE_REASONING_DESCRIPTION =
|
|
32
|
+
'Entry headers read: [DD-MM-YYYY] [assistant] visible + Reasoning ≈invisible (≈total). ' +
|
|
33
|
+
'≈ is a provider-reported count; ~ is a rough approximation when no breakdown ' +
|
|
34
|
+
'is reported and excluded from category totals. ' +
|
|
35
|
+
'Encoded replaces Reasoning when the provider replays encrypted reasoning with its message.';
|
|
36
|
+
const USAGE_TAIL_FIXED_LINE_COUNT = 5;
|
|
37
|
+
const DETAIL_CATEGORY_HEADER_LINE_COUNT = 1;
|
|
38
|
+
const PREVIEW_FIXED_LINE_COUNT = 8;
|
|
39
|
+
const PREVIEW_ENTRY_MAX_LINES = 20;
|
|
40
|
+
const CURSOR_COLUMN_WIDTH = 2;
|
|
41
|
+
const MAX_LEGEND_VALUE_COLUMN = 32;
|
|
42
|
+
const LEGEND_VALUE_GAP = 2;
|
|
43
|
+
const LEGEND_LEADER_GAP = 4;
|
|
44
|
+
const MAP_SIDE_BY_SIDE_MIN_WIDTH = 52;
|
|
45
|
+
const SPACED_MAP_MIN_WIDTH = 72;
|
|
46
|
+
const MAP_COLUMN_GAP = 2;
|
|
47
|
+
const SPACED_MAP_COLUMN_GAP = 3;
|
|
48
|
+
const FULL_CELL = '■';
|
|
49
|
+
const PARTIAL_CELL = '◧';
|
|
50
|
+
const COMPACTED_CELL = '▦';
|
|
51
|
+
const BUFFER_CELL = '⛝';
|
|
52
|
+
const FREE_CELL = '⛶';
|
|
53
|
+
const BREAKDOWN_MARKER = '•';
|
|
54
|
+
|
|
55
|
+
/** Everything the Usage view renders, classified once when the view opens. */
|
|
56
|
+
export interface UsageViewInput {
|
|
57
|
+
readonly usage: ContextUsageSnapshot;
|
|
58
|
+
readonly degradedReason?: string;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** View-local denominator selected for the context map. */
|
|
62
|
+
type UsageMapScale = 'window' | 'fit';
|
|
63
|
+
|
|
64
|
+
interface CategoryLegendRow {
|
|
65
|
+
readonly type: 'category';
|
|
66
|
+
readonly category: UsageCategory;
|
|
67
|
+
readonly depth: number;
|
|
68
|
+
readonly rootId: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
interface BufferLegendRow {
|
|
72
|
+
readonly type: 'buffer';
|
|
73
|
+
readonly tokens: number;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
interface FreeLegendRow {
|
|
77
|
+
readonly type: 'free';
|
|
78
|
+
readonly tokens: number;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
type LegendRow = CategoryLegendRow | BufferLegendRow | FreeLegendRow;
|
|
82
|
+
|
|
83
|
+
interface LegendColumns {
|
|
84
|
+
readonly value: number;
|
|
85
|
+
readonly tokenWidth: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Stateful Usage tab retained by ContextViewDialog. */
|
|
89
|
+
export class UsageView {
|
|
90
|
+
private readonly theme: Theme;
|
|
91
|
+
private readonly input: UsageViewInput;
|
|
92
|
+
private readonly done: (result: undefined) => void;
|
|
93
|
+
private readonly getTerminalRows: () => number;
|
|
94
|
+
private readonly usage: ContextUsageSnapshot;
|
|
95
|
+
private readonly legendRows: readonly LegendRow[];
|
|
96
|
+
private readonly navigator: ListNavigator;
|
|
97
|
+
private readonly previewScroller = new PreviewScroller();
|
|
98
|
+
private readonly fitMapScale: number | undefined;
|
|
99
|
+
private mapScale: UsageMapScale = 'window';
|
|
100
|
+
private currentWidth: number | undefined;
|
|
101
|
+
private previewRow: CategoryLegendRow | undefined;
|
|
102
|
+
private cachedPreviewEntries: readonly UsagePreviewEntry[] | undefined;
|
|
103
|
+
private previewLines: string[] | undefined;
|
|
104
|
+
private previewWrapWidth: number | undefined;
|
|
105
|
+
private cachedWidth: number | undefined;
|
|
106
|
+
private cachedTerminalRows: number | undefined;
|
|
107
|
+
private cachedLines: string[] | undefined;
|
|
108
|
+
|
|
109
|
+
/** Create a view over one precomputed usage snapshot. */
|
|
110
|
+
public constructor(
|
|
111
|
+
theme: Theme,
|
|
112
|
+
input: UsageViewInput,
|
|
113
|
+
done: (result: undefined) => void,
|
|
114
|
+
getTerminalRows: () => number = () => process.stdout.rows ?? DEFAULT_TERMINAL_ROWS,
|
|
115
|
+
) {
|
|
116
|
+
this.theme = theme;
|
|
117
|
+
this.input = input;
|
|
118
|
+
this.done = done;
|
|
119
|
+
this.getTerminalRows = getTerminalRows;
|
|
120
|
+
this.usage = input.usage;
|
|
121
|
+
this.fitMapScale = calculateFitMapScale(this.usage);
|
|
122
|
+
this.legendRows = this.buildLegendRows();
|
|
123
|
+
// The trailing buffer/free block has no preview: it scrolls with the list but is never selectable.
|
|
124
|
+
const selectableCount = this.legendRows.filter(row => row.type === 'category').length;
|
|
125
|
+
this.navigator = new ListNavigator(this.legendRows.length, 1, selectableCount);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Handle category navigation, preview opening, and close keys. */
|
|
129
|
+
public handleInput(data: string): void {
|
|
130
|
+
if (this.previewRow !== undefined) {
|
|
131
|
+
this.handlePreviewInput(data);
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
if (matchesKey(data, Key.escape) || data === 'q') {
|
|
135
|
+
this.done(undefined);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
if (matchesKey(data, 'z')) {
|
|
139
|
+
this.toggleMapScale();
|
|
140
|
+
} else if (matchesKey(data, Key.enter)) {
|
|
141
|
+
this.openPreview();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Apply semantic movement in either the category list or its preview. */
|
|
146
|
+
public handleNavigation(action: NavigationAction): void {
|
|
147
|
+
if (this.previewRow !== undefined) {
|
|
148
|
+
const changed =
|
|
149
|
+
action === 'step-back'
|
|
150
|
+
? this.previewScroller.scrollBy(-1)
|
|
151
|
+
: action === 'step-forward'
|
|
152
|
+
? this.previewScroller.scrollBy(1)
|
|
153
|
+
: action === 'page-back'
|
|
154
|
+
? this.previewScroller.page(-1)
|
|
155
|
+
: action === 'page-forward'
|
|
156
|
+
? this.previewScroller.page(1)
|
|
157
|
+
: action === 'first'
|
|
158
|
+
? this.previewScroller.scrollTo(0)
|
|
159
|
+
: this.previewScroller.scrollTo(this.previewScroller.maxOffset);
|
|
160
|
+
if (changed) this.clearCache();
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const changed =
|
|
165
|
+
action === 'step-back'
|
|
166
|
+
? this.navigator.moveBy(-1)
|
|
167
|
+
: action === 'step-forward'
|
|
168
|
+
? this.navigator.moveBy(1)
|
|
169
|
+
: action === 'page-back'
|
|
170
|
+
? this.navigator.page(-1)
|
|
171
|
+
: action === 'page-forward'
|
|
172
|
+
? this.navigator.page(1)
|
|
173
|
+
: action === 'first'
|
|
174
|
+
? this.navigator.moveTo(0)
|
|
175
|
+
: this.navigator.moveTo(this.legendRows.length - 1);
|
|
176
|
+
if (changed) this.clearCache();
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Render a cached tab frame for the current width and overlay height. */
|
|
180
|
+
public render(width: number): string[] {
|
|
181
|
+
this.currentWidth = width;
|
|
182
|
+
const terminalRows = normalizeTerminalRows(this.getTerminalRows());
|
|
183
|
+
if (this.cachedLines !== undefined && this.cachedWidth === width && this.cachedTerminalRows === terminalRows) {
|
|
184
|
+
return this.cachedLines;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const lines =
|
|
188
|
+
this.previewRow === undefined ? this.renderDashboard(width, terminalRows) : this.renderPreview(width, terminalRows, this.previewRow);
|
|
189
|
+
this.cachedWidth = width;
|
|
190
|
+
this.cachedTerminalRows = terminalRows;
|
|
191
|
+
this.cachedLines = lines;
|
|
192
|
+
return lines;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Invalidate theme-dependent rendered output. */
|
|
196
|
+
public invalidate(): void {
|
|
197
|
+
this.previewLines = undefined;
|
|
198
|
+
this.previewWrapWidth = undefined;
|
|
199
|
+
this.clearCache();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// === Dashboard mode ===
|
|
203
|
+
|
|
204
|
+
/** Full map/legend frame with navigation hints. */
|
|
205
|
+
private renderDashboard(width: number, terminalRows: number): string[] {
|
|
206
|
+
const theme = this.theme;
|
|
207
|
+
const border = theme.fg('border', '─'.repeat(Math.max(1, width)));
|
|
208
|
+
const prefix = [border, '', ...this.headerLines(width), '', ...this.degradedWarningLines(width)];
|
|
209
|
+
const descriptionLines = wrapDescriptionLines(theme, USAGE_DESCRIPTION, 'dim', width);
|
|
210
|
+
const availableDashboardRows = Math.max(1, terminalRows - prefix.length - USAGE_TAIL_FIXED_LINE_COUNT - descriptionLines.length);
|
|
211
|
+
const dashboard = this.dashboardLines(width, availableDashboardRows).slice(0, availableDashboardRows);
|
|
212
|
+
while (dashboard.length < availableDashboardRows) dashboard.push('');
|
|
213
|
+
const tail = ['', ...descriptionLines, '', this.fit(hintRow(theme, this.dashboardHints(width)), width), '', border];
|
|
214
|
+
return fitToTerminalHeight([...prefix, ...dashboard, ...tail], terminalRows, border);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Accent title with responsive model, zoom label, and true-window usage metadata. */
|
|
218
|
+
private headerLines(width: number): string[] {
|
|
219
|
+
const theme = this.theme;
|
|
220
|
+
const title = theme.fg('accent', theme.bold('Context Usage'));
|
|
221
|
+
const summary = this.reportedSummary();
|
|
222
|
+
if (width < MAP_SIDE_BY_SIDE_MIN_WIDTH) {
|
|
223
|
+
return [this.fit(title, width), '', this.fit(summary, width)];
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const normalizedModel = normalizeInlineText(this.usage.modelLabel ?? '');
|
|
227
|
+
const separator = theme.fg('dim', ' · ');
|
|
228
|
+
const fullMetadata = normalizedModel === '' ? summary : `${theme.fg('muted', normalizedModel)}${separator}${summary}`;
|
|
229
|
+
const zoomLabel = this.zoomLabel(width);
|
|
230
|
+
if (zoomLabel !== undefined) {
|
|
231
|
+
const titleWithZoom = `${title}${separator}${zoomLabel}`;
|
|
232
|
+
if (visibleWidth(titleWithZoom) + 1 + visibleWidth(fullMetadata) <= width) {
|
|
233
|
+
return [spreadLine(titleWithZoom, fullMetadata, width)];
|
|
234
|
+
}
|
|
235
|
+
if (visibleWidth(titleWithZoom) + 1 + visibleWidth(summary) <= width) {
|
|
236
|
+
return [spreadLine(titleWithZoom, summary, width)];
|
|
237
|
+
}
|
|
238
|
+
if (visibleWidth(title) + 1 + visibleWidth(summary) <= width) {
|
|
239
|
+
return [spreadLine(title, summary, width), '', this.fit(zoomLabel, width)];
|
|
240
|
+
}
|
|
241
|
+
return [this.fit(title, width), '', this.fit(zoomLabel, width), '', this.fit(summary, width)];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
if (visibleWidth(title) + 1 + visibleWidth(fullMetadata) <= width) {
|
|
245
|
+
return [spreadLine(title, fullMetadata, width)];
|
|
246
|
+
}
|
|
247
|
+
if (visibleWidth(title) + 1 + visibleWidth(summary) <= width) {
|
|
248
|
+
return [spreadLine(title, summary, width)];
|
|
249
|
+
}
|
|
250
|
+
return [this.fit(title, width), '', this.fit(summary, width)];
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Toggle the view-local map denominator when the binding is currently visible. */
|
|
254
|
+
private toggleMapScale(): void {
|
|
255
|
+
if (!this.canToggleMapScale(this.currentWidth)) return;
|
|
256
|
+
this.mapScale = this.mapScale === 'window' ? 'fit' : 'window';
|
|
257
|
+
this.clearCache();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Whether zoom can help and its binding is visible at this width. */
|
|
261
|
+
private canToggleMapScale(width: number | undefined): boolean {
|
|
262
|
+
const contextWindow = this.usage.reported?.contextWindow;
|
|
263
|
+
return (
|
|
264
|
+
width !== undefined &&
|
|
265
|
+
width >= MAP_SIDE_BY_SIDE_MIN_WIDTH &&
|
|
266
|
+
contextWindow !== undefined &&
|
|
267
|
+
this.fitMapScale !== undefined &&
|
|
268
|
+
this.fitMapScale < contextWindow
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The active Fit label, omitted together with its map and binding. */
|
|
273
|
+
private zoomLabel(width: number): string | undefined {
|
|
274
|
+
const contextWindow = this.usage.reported?.contextWindow;
|
|
275
|
+
if (this.mapScale !== 'fit' || !this.canToggleMapScale(width) || contextWindow === undefined || this.fitMapScale === undefined) return undefined;
|
|
276
|
+
return this.theme.fg('mdHeading', `Zoom ${formatTokens(contextWindow)} → ${formatTokens(this.fitMapScale)}`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Dashboard hints with Zoom immediately before Close when the binding is active. */
|
|
280
|
+
private dashboardHints(width: number): Array<readonly [string, string]> {
|
|
281
|
+
const hints: Array<readonly [string, string]> = [
|
|
282
|
+
[STEP_KEY_HINT, 'Navigate'],
|
|
283
|
+
['Ctrl+u/d', 'Page'],
|
|
284
|
+
['gg/G', 'Bounds'],
|
|
285
|
+
['Enter', 'Preview'],
|
|
286
|
+
];
|
|
287
|
+
if (this.canToggleMapScale(width)) hints.push(['Z', 'Zoom']);
|
|
288
|
+
hints.push(['Esc', 'Close']);
|
|
289
|
+
return hints;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Render the map and legend side by side, or only details when width/window data is insufficient. */
|
|
293
|
+
private dashboardLines(width: number, rows: number): string[] {
|
|
294
|
+
const scaleTokens = this.mapScale === 'fit' ? this.fitMapScale : undefined;
|
|
295
|
+
const map = buildUsageMap(this.usage, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, scaleTokens);
|
|
296
|
+
if (map === undefined || width < MAP_SIDE_BY_SIDE_MIN_WIDTH) {
|
|
297
|
+
return this.detailLines(width, rows, false).map(line => this.fit(line, width));
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const spaced = width >= SPACED_MAP_MIN_WIDTH;
|
|
301
|
+
const separator = spaced ? ' ' : '';
|
|
302
|
+
const mapLines = Array.from({ length: map.rows }, (_, row) => {
|
|
303
|
+
const start = row * map.columns;
|
|
304
|
+
const cells = map.cells.slice(start, start + map.columns);
|
|
305
|
+
return `${BODY_INDENT}${cells.map(cell => this.mapCell(cell)).join(separator)}`;
|
|
306
|
+
});
|
|
307
|
+
const mapWidth = BODY_INDENT.length + map.columns + (spaced ? map.columns - 1 : 0);
|
|
308
|
+
const gap = spaced ? SPACED_MAP_COLUMN_GAP : MAP_COLUMN_GAP;
|
|
309
|
+
const detailWidth = Math.max(1, width - mapWidth - gap);
|
|
310
|
+
const details = this.detailLines(detailWidth, rows, true);
|
|
311
|
+
const lineCount = Math.max(mapLines.length, details.length);
|
|
312
|
+
return Array.from({ length: lineCount }, (_, index) => {
|
|
313
|
+
const mapLine = mapLines[index] ?? ' '.repeat(mapWidth);
|
|
314
|
+
const detail = this.fit(details[index] ?? '', detailWidth);
|
|
315
|
+
return this.fit(`${mapLine}${' '.repeat(gap)}${detail}`, width);
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Map-fill key, category heading, selectable category legend viewport, and scroll counter. */
|
|
320
|
+
private detailLines(width: number, rows: number, includeMapKey: boolean): string[] {
|
|
321
|
+
const theme = this.theme;
|
|
322
|
+
const showMapKey = includeMapKey && rows >= 4;
|
|
323
|
+
const headerLineCount = DETAIL_CATEGORY_HEADER_LINE_COUNT + (showMapKey ? 2 : 0);
|
|
324
|
+
// The counter sits below the last legend row, so it consumes one of the available rows.
|
|
325
|
+
const viewport = calculateViewport(this.legendRows.length, rows, headerLineCount);
|
|
326
|
+
this.navigator.setVisibleCount(viewport.visibleCount);
|
|
327
|
+
|
|
328
|
+
const heading = theme.fg('mdHeading', theme.bold('Category:'));
|
|
329
|
+
const rowWidth = Math.max(1, width - CURSOR_COLUMN_WIDTH);
|
|
330
|
+
const columns = this.legendColumns(rowWidth);
|
|
331
|
+
const visibleRows: string[] = [];
|
|
332
|
+
const start = this.navigator.offset;
|
|
333
|
+
for (let index = start; index < start + this.navigator.windowSize; index++) {
|
|
334
|
+
const row = this.legendRows[index];
|
|
335
|
+
if (row === undefined) break;
|
|
336
|
+
const selected = index === this.navigator.selected;
|
|
337
|
+
// The cursor stays in one fixed column at the start of the legend.
|
|
338
|
+
const cursor = selected ? theme.fg('accent', '→ ') : ' ';
|
|
339
|
+
visibleRows.push(this.fit(`${cursor}${this.legendLine(row, columns, rowWidth, selected)}`, width));
|
|
340
|
+
}
|
|
341
|
+
const counterLines = viewport.showScroll
|
|
342
|
+
? [this.fit(theme.fg('dim', `${BODY_INDENT}(${this.navigator.visibleEnd}/${this.legendRows.length})`), width)]
|
|
343
|
+
: [];
|
|
344
|
+
return [...(showMapKey ? [this.mapKeyLine(width), ''] : []), heading, ...visibleRows, ...counterLines].slice(0, rows);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Explain only the map's full and partial occupancy glyphs. */
|
|
348
|
+
private mapKeyLine(width: number): string {
|
|
349
|
+
const theme = this.theme;
|
|
350
|
+
const heading = theme.fg('mdHeading', theme.bold('Map:'));
|
|
351
|
+
const separator = theme.fg('dim', ' · ');
|
|
352
|
+
const full = `${theme.fg('text', FULL_CELL)}${theme.fg('muted', ' Full')}`;
|
|
353
|
+
const partial = `${theme.fg('text', PARTIAL_CELL)}${theme.fg('muted', ' Part')}`;
|
|
354
|
+
return this.fit(`${heading} ${full}${separator}${partial}`, width);
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Pi-reported usage/window metadata, with a marked estimate when current usage is unknown. */
|
|
358
|
+
private reportedSummary(): string {
|
|
359
|
+
const reported = this.usage.reported;
|
|
360
|
+
if (reported === undefined) return this.theme.fg('muted', 'Context usage unavailable.');
|
|
361
|
+
const contextWindow = formatTokens(reported.contextWindow);
|
|
362
|
+
if (reported.tokens === undefined) {
|
|
363
|
+
const percent = formatPercent(this.usage.estimatedTokens / reported.contextWindow);
|
|
364
|
+
return this.theme.fg('text', `≈${formatTokens(this.usage.estimatedTokens)}/${contextWindow} (${percent})`);
|
|
365
|
+
}
|
|
366
|
+
const percent = reported.percent === undefined ? '' : ` (${formatPercent(reported.percent / 100)})`;
|
|
367
|
+
return this.theme.fg('text', `${formatTokens(reported.tokens)}/${contextWindow}${percent}`);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* All legend rows: top-level categories, Tool Output children, then the
|
|
372
|
+
* non-selectable auto-compact buffer and free space.
|
|
373
|
+
*/
|
|
374
|
+
private buildLegendRows(): LegendRow[] {
|
|
375
|
+
const rows: LegendRow[] = buildCategoryLegendRows(this.usage.categories);
|
|
376
|
+
const bufferTokens = this.bufferTokens();
|
|
377
|
+
if (bufferTokens > 0) rows.push({ type: 'buffer', tokens: bufferTokens });
|
|
378
|
+
const freeTokens = this.freeSpaceTokens();
|
|
379
|
+
if (freeTokens !== undefined) rows.push({ type: 'free', tokens: freeTokens });
|
|
380
|
+
return rows;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Tokens auto-compaction keeps unoccupied; zero when disabled or without a context window. */
|
|
384
|
+
private bufferTokens(): number {
|
|
385
|
+
const contextWindow = this.usage.reported?.contextWindow;
|
|
386
|
+
const reserve = this.usage.autoCompactReserveTokens;
|
|
387
|
+
if (contextWindow === undefined || contextWindow <= 0 || reserve === undefined) return 0;
|
|
388
|
+
return Math.min(reserve, Math.max(0, contextWindow - this.usage.estimatedTokens));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Estimated remaining space before the buffer, or undefined without a usable context window. */
|
|
392
|
+
private freeSpaceTokens(): number | undefined {
|
|
393
|
+
const contextWindow = this.usage.reported?.contextWindow;
|
|
394
|
+
if (contextWindow === undefined || contextWindow <= 0) return undefined;
|
|
395
|
+
return Math.max(0, contextWindow - this.usage.estimatedTokens - this.bufferTokens());
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** Earliest shared token column plus the width needed to align percentages. */
|
|
399
|
+
private legendColumns(width: number): LegendColumns {
|
|
400
|
+
const rows = this.legendRows;
|
|
401
|
+
const labelWidth = Math.max(1, ...rows.map(row => this.plainLegendLabel(row).length));
|
|
402
|
+
const tokenWidth = Math.max(1, ...rows.map(row => formatTokens(legendTokens(row)).length));
|
|
403
|
+
const percentWidth = Math.max(0, ...rows.map(row => this.plainLegendPercent(legendTokens(row)).length));
|
|
404
|
+
const rightWidth = tokenWidth + (percentWidth > 0 ? LEGEND_VALUE_GAP + percentWidth : 0);
|
|
405
|
+
const idealValue = Math.min(MAX_LEGEND_VALUE_COLUMN, labelWidth + LEGEND_LEADER_GAP);
|
|
406
|
+
return {
|
|
407
|
+
value: Math.max(1, Math.min(idealValue, width - rightWidth)),
|
|
408
|
+
tokenWidth,
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** One aligned hierarchy row with dim leaders and independent token/percentage columns. */
|
|
413
|
+
private legendLine(row: LegendRow, columns: LegendColumns, width: number, selected: boolean): string {
|
|
414
|
+
const labelWidth = Math.max(1, columns.value - 1);
|
|
415
|
+
const left = fitLine(this.styledLegendLabel(row, selected), labelWidth);
|
|
416
|
+
const leader = this.legendLeader(columns.value - visibleWidth(left));
|
|
417
|
+
const tokens = formatTokens(legendTokens(row));
|
|
418
|
+
const valueColor = selected ? 'accent' : row.type === 'category' && row.depth > 1 ? 'dim' : 'muted';
|
|
419
|
+
const tokenPadding = ' '.repeat(Math.max(0, columns.tokenWidth - tokens.length));
|
|
420
|
+
const percent = this.plainLegendPercent(legendTokens(row));
|
|
421
|
+
const percentPart = percent === '' ? '' : `${' '.repeat(LEGEND_VALUE_GAP)}${this.theme.fg(selected ? 'accent' : 'dim', percent)}`;
|
|
422
|
+
return fitLine(`${left}${leader}${this.theme.fg(valueColor, tokens)}${tokenPadding}${percentPart}`, width);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Fill a label/value gap with dim dots, retaining spaces at both ends. */
|
|
426
|
+
private legendLeader(width: number): string {
|
|
427
|
+
if (width < 3) return ' '.repeat(Math.max(0, width));
|
|
428
|
+
return ` ${this.theme.fg('dim', '.'.repeat(width - 2))} `;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** Unstyled hierarchy label used to choose the shared value column. */
|
|
432
|
+
private plainLegendLabel(row: LegendRow): string {
|
|
433
|
+
if (row.type === 'buffer') return `${BUFFER_CELL} Auto-Compact Buffer`;
|
|
434
|
+
if (row.type === 'free') return `${FREE_CELL} Free Space`;
|
|
435
|
+
const indent = ' '.repeat(row.depth);
|
|
436
|
+
return `${indent}${categoryMarker(row.category.id, row.depth)} ${normalizeInlineText(row.category.label)}`;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** Themed hierarchy label; the marker keeps its map color even when selected. */
|
|
440
|
+
private styledLegendLabel(row: LegendRow, selected: boolean): string {
|
|
441
|
+
if (row.type === 'buffer') {
|
|
442
|
+
return `${this.theme.fg('dim', BUFFER_CELL)} ${this.theme.fg('text', 'Auto-Compact Buffer')}`;
|
|
443
|
+
}
|
|
444
|
+
if (row.type === 'free') {
|
|
445
|
+
return `${this.theme.fg('dim', FREE_CELL)} ${this.theme.fg(selected ? 'accent' : 'text', 'Free Space')}`;
|
|
446
|
+
}
|
|
447
|
+
const indent = ' '.repeat(row.depth);
|
|
448
|
+
const color = categoryColor(row.rootId);
|
|
449
|
+
const marker = this.theme.fg(color, categoryMarker(row.category.id, row.depth));
|
|
450
|
+
const labelColor = selected ? 'accent' : row.depth === 0 ? 'text' : row.depth === 1 ? 'muted' : 'dim';
|
|
451
|
+
return `${indent}${marker} ${this.theme.fg(labelColor, normalizeInlineText(row.category.label))}`;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Percentage text used by the independently aligned rightmost column. */
|
|
455
|
+
private plainLegendPercent(tokens: number): string {
|
|
456
|
+
const contextWindow = this.usage.reported?.contextWindow;
|
|
457
|
+
if (contextWindow === undefined || contextWindow <= 0) return '';
|
|
458
|
+
return formatPercent(tokens / contextWindow);
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** Colored occupied/partial/buffer/free glyph for one map cell. */
|
|
462
|
+
private mapCell(cell: UsageMapCell): string {
|
|
463
|
+
if (cell.fill === 'buffer') return this.theme.fg('dim', BUFFER_CELL);
|
|
464
|
+
if (cell.fill === 'free') return this.theme.fg('dim', FREE_CELL);
|
|
465
|
+
const glyph = cell.categoryId === 'compacted-data' ? COMPACTED_CELL : cell.fill === 'full' ? FULL_CELL : PARTIAL_CELL;
|
|
466
|
+
return this.theme.fg(categoryColor(cell.categoryId), glyph);
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Wrapped degraded-capture warning placed above the dashboard. */
|
|
470
|
+
private degradedWarningLines(width: number): string[] {
|
|
471
|
+
if (this.input.degradedReason === undefined) return [];
|
|
472
|
+
const reason = normalizeInlineText(this.input.degradedReason);
|
|
473
|
+
return wrapTextWithAnsi(this.theme.fg('warning', `${BODY_INDENT}${reason}`), width);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// === Preview mode ===
|
|
477
|
+
|
|
478
|
+
/** Preview scrolling and return-to-list keys. */
|
|
479
|
+
private handlePreviewInput(data: string): void {
|
|
480
|
+
if (matchesKey(data, Key.escape) || data === 'q') {
|
|
481
|
+
this.closePreview();
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** Open the selected category's content preview; free space has no preview. */
|
|
487
|
+
private openPreview(): void {
|
|
488
|
+
const row = this.legendRows[this.navigator.selected];
|
|
489
|
+
if (row === undefined || row.type !== 'category') return;
|
|
490
|
+
this.previewRow = row;
|
|
491
|
+
this.cachedPreviewEntries = undefined;
|
|
492
|
+
this.previewLines = undefined;
|
|
493
|
+
this.previewWrapWidth = undefined;
|
|
494
|
+
this.previewScroller.reset();
|
|
495
|
+
this.clearCache();
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Return to the list with the same selected row. */
|
|
499
|
+
private closePreview(): void {
|
|
500
|
+
this.previewRow = undefined;
|
|
501
|
+
this.cachedPreviewEntries = undefined;
|
|
502
|
+
this.previewLines = undefined;
|
|
503
|
+
this.previewWrapWidth = undefined;
|
|
504
|
+
this.clearCache();
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** Scrollable chronological content stream for one category. */
|
|
508
|
+
private renderPreview(width: number, terminalRows: number, row: CategoryLegendRow): string[] {
|
|
509
|
+
const theme = this.theme;
|
|
510
|
+
const border = theme.fg('border', '─'.repeat(Math.max(1, width)));
|
|
511
|
+
const body = this.previewBodyLines(width, row);
|
|
512
|
+
const descriptionLines = this.previewDescriptionLines(width, row);
|
|
513
|
+
const descriptionLineCount = descriptionLines.length === 0 ? 0 : descriptionLines.length + 1;
|
|
514
|
+
const viewport = calculateViewport(body.length, terminalRows, PREVIEW_FIXED_LINE_COUNT, descriptionLineCount);
|
|
515
|
+
this.previewScroller.setExtent(body.length, viewport.visibleCount);
|
|
516
|
+
|
|
517
|
+
const lines: string[] = [border, ''];
|
|
518
|
+
const title = theme.fg('accent', theme.bold(normalizeInlineText(row.category.label)));
|
|
519
|
+
const percent = this.plainLegendPercent(row.category.tokens);
|
|
520
|
+
const meta = theme.fg('muted', `${formatTokens(row.category.tokens)}${percent === '' ? '' : ` · ${percent}`} `);
|
|
521
|
+
lines.push(spreadLine(title, meta, width));
|
|
522
|
+
lines.push('');
|
|
523
|
+
|
|
524
|
+
const start = this.previewScroller.offset;
|
|
525
|
+
for (let index = start; index < start + viewport.visibleCount; index++) {
|
|
526
|
+
lines.push(body[index] ?? '');
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
if (viewport.showScroll) {
|
|
530
|
+
lines.push(this.fit(theme.fg('dim', `${BODY_INDENT}(${this.previewScroller.visibleEnd}/${body.length})`), width));
|
|
531
|
+
}
|
|
532
|
+
if (descriptionLines.length > 0) lines.push('', ...descriptionLines);
|
|
533
|
+
lines.push('');
|
|
534
|
+
lines.push(
|
|
535
|
+
this.fit(
|
|
536
|
+
hintRow(theme, [
|
|
537
|
+
[STEP_KEY_HINT, 'Scroll'],
|
|
538
|
+
['Ctrl+u/d', 'Page'],
|
|
539
|
+
['gg/G', 'Bounds'],
|
|
540
|
+
['Esc', 'Back'],
|
|
541
|
+
]),
|
|
542
|
+
width,
|
|
543
|
+
),
|
|
544
|
+
);
|
|
545
|
+
lines.push('', border);
|
|
546
|
+
return fitToTerminalHeight(lines, terminalRows, border);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Cached wrapped entry stream: bracket headers plus capped sanitized content. */
|
|
550
|
+
private previewBodyLines(width: number, row: CategoryLegendRow): string[] {
|
|
551
|
+
const wrapWidth = Math.max(10, width - BODY_INDENT.length * 2 - 1);
|
|
552
|
+
if (this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) return this.previewLines;
|
|
553
|
+
const entries = this.previewEntries(row);
|
|
554
|
+
const compactSkills = row.rootId === 'user-messages';
|
|
555
|
+
const lines =
|
|
556
|
+
entries.length === 0
|
|
557
|
+
? [this.fit(this.theme.fg('muted', `${BODY_INDENT}No content captured for this category.`), width)]
|
|
558
|
+
: entries.flatMap((entry, index) => [
|
|
559
|
+
...(index === 0 ? [] : ['']),
|
|
560
|
+
this.fit(`${BODY_INDENT}${this.entryHeader(entry)}`, width),
|
|
561
|
+
...this.entryContentLines(entry, wrapWidth, compactSkills),
|
|
562
|
+
]);
|
|
563
|
+
this.previewLines = lines;
|
|
564
|
+
this.previewWrapWidth = wrapWidth;
|
|
565
|
+
return lines;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Collect and cache the immutable entries shared by preview body and description rendering. */
|
|
569
|
+
private previewEntries(row: CategoryLegendRow): readonly UsagePreviewEntry[] {
|
|
570
|
+
this.cachedPreviewEntries ??= collectPreviewEntries(row.category);
|
|
571
|
+
return this.cachedPreviewEntries;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** Bracketed entry header: dim datetime, breadcrumbs, visible tokens, and optional invisible reasoning. */
|
|
575
|
+
private entryHeader(entry: UsagePreviewEntry): string {
|
|
576
|
+
const theme = this.theme;
|
|
577
|
+
const cells: string[] = [];
|
|
578
|
+
if (entry.timestamp !== undefined) {
|
|
579
|
+
cells.push(theme.fg('dim', `[${formatEntryTimestamp(entry.timestamp)}]`));
|
|
580
|
+
}
|
|
581
|
+
entry.breadcrumb.forEach((cell, index) => {
|
|
582
|
+
const color: ThemeColor = index === 0 ? 'mdHeading' : 'muted';
|
|
583
|
+
cells.push(`${theme.fg('dim', '[')}${theme.fg(color, normalizeInlineText(cell))}${theme.fg('dim', ']')}`);
|
|
584
|
+
});
|
|
585
|
+
cells.push(theme.fg('dim', formatTokens(entry.visibleTokens ?? entry.tokens)));
|
|
586
|
+
if (entry.invisibleReasoning !== undefined) {
|
|
587
|
+
const { tokens, basis, encoded } = entry.invisibleReasoning;
|
|
588
|
+
const marker = basis === 'provider-reported' ? '≈' : '~';
|
|
589
|
+
const label = encoded ? 'Encoded' : 'Reasoning';
|
|
590
|
+
const total = (entry.visibleTokens ?? entry.tokens) + tokens;
|
|
591
|
+
cells.push(theme.fg('dim', `+ ${label} ${marker}${formatTokens(tokens)} (${marker}${formatTokens(total)})`));
|
|
592
|
+
}
|
|
593
|
+
return cells.join(' ');
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
/** Fixed explanation shown only when the thinking preview contains invisible-reasoning metadata. */
|
|
597
|
+
private previewDescriptionLines(width: number, row: CategoryLegendRow): string[] {
|
|
598
|
+
if (row.rootId !== 'agent-thinking-messages') return [];
|
|
599
|
+
const hasInvisibleReasoning = this.previewEntries(row).some(entry => entry.invisibleReasoning !== undefined);
|
|
600
|
+
return hasInvisibleReasoning ? wrapDescriptionLines(this.theme, INVISIBLE_REASONING_DESCRIPTION, 'dim', width) : [];
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/** Sanitized, wrapped, per-entry-capped content lines indented under the header. */
|
|
604
|
+
private entryContentLines(entry: UsagePreviewEntry, wrapWidth: number, compactSkills: boolean): string[] {
|
|
605
|
+
const indent = BODY_INDENT.repeat(2);
|
|
606
|
+
const lines: string[] = [];
|
|
607
|
+
let hidden = 0;
|
|
608
|
+
for (const paragraph of this.entryPreviewText(entry.text, compactSkills).split('\n')) {
|
|
609
|
+
const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
|
|
610
|
+
const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
|
|
611
|
+
for (const line of paragraphLines) {
|
|
612
|
+
if (lines.length < PREVIEW_ENTRY_MAX_LINES) lines.push(line === '' ? '' : `${indent}${line}`);
|
|
613
|
+
else hidden++;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
if (hidden === 0) return lines;
|
|
617
|
+
return [...lines, `${indent}${this.theme.fg('dim', `… +${hidden} lines`)}`];
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
/** Sanitize raw entry text and replace complete attached skills with pi-colored badges. */
|
|
621
|
+
private entryPreviewText(text: string, compactSkills: boolean): string {
|
|
622
|
+
const sanitized = normalizePreviewText(text);
|
|
623
|
+
if (!compactSkills) return sanitized;
|
|
624
|
+
return splitSkillPreview(sanitized)
|
|
625
|
+
.map(segment => (segment.type === 'text' ? segment.text : this.skillBadge(segment.name)))
|
|
626
|
+
.join('');
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** Render the same collapsed skill label/name colors used by pi's transcript component. */
|
|
630
|
+
private skillBadge(name: string): string {
|
|
631
|
+
const label = this.theme.fg('customMessageLabel', this.theme.bold('[skill]'));
|
|
632
|
+
const safeName = normalizeInlineText(name);
|
|
633
|
+
if (safeName === '') return label;
|
|
634
|
+
return `${label} ${this.theme.fg('customMessageText', safeName)}`;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Truncate one rendered line to the supplied width. */
|
|
638
|
+
private fit(line: string, width: number): string {
|
|
639
|
+
return fitLine(line, width);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/** Clear render-cache keys after data, theme, or input changes. */
|
|
643
|
+
private clearCache(): void {
|
|
644
|
+
this.cachedWidth = undefined;
|
|
645
|
+
this.cachedTerminalRows = undefined;
|
|
646
|
+
this.cachedLines = undefined;
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
/** Show top-level categories plus Tool Output's direct per-tool breakdown. */
|
|
651
|
+
function buildCategoryLegendRows(categories: readonly UsageCategory[]): CategoryLegendRow[] {
|
|
652
|
+
const rows: CategoryLegendRow[] = [];
|
|
653
|
+
for (const category of categories) {
|
|
654
|
+
rows.push({ type: 'category', category, depth: 0, rootId: category.id });
|
|
655
|
+
if (category.id !== 'tool-output') continue;
|
|
656
|
+
for (const child of category.children ?? []) {
|
|
657
|
+
rows.push({ type: 'category', category: child, depth: 1, rootId: category.id });
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
return rows;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
/** Entry-header datetime: DD-MM-YYYY HH:MM:SS in local time. */
|
|
664
|
+
function formatEntryTimestamp(timestamp: number): string {
|
|
665
|
+
const date = new Date(timestamp);
|
|
666
|
+
const pad = (value: number) => `${value}`.padStart(2, '0');
|
|
667
|
+
return (
|
|
668
|
+
`${pad(date.getDate())}-${pad(date.getMonth() + 1)}-${date.getFullYear()}` +
|
|
669
|
+
` ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/** Marker distinguishing top-level occupancy, compacted data, and nested breakdowns. */
|
|
674
|
+
function categoryMarker(categoryId: string, depth: number): string {
|
|
675
|
+
if (depth > 0) return BREAKDOWN_MARKER;
|
|
676
|
+
return categoryId === 'compacted-data' ? COMPACTED_CELL : FULL_CELL;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
/** Token estimate carried by category, buffer, or free-space legend rows. */
|
|
680
|
+
function legendTokens(row: LegendRow): number {
|
|
681
|
+
return row.type === 'category' ? row.category.tokens : row.tokens;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** Stable semantic theme color for one category across map cells and legend markers. */
|
|
685
|
+
function categoryColor(categoryId: string | undefined): ThemeColor {
|
|
686
|
+
switch (categoryId) {
|
|
687
|
+
case 'system-prompt':
|
|
688
|
+
case 'system-tools':
|
|
689
|
+
return 'mdHeading';
|
|
690
|
+
case 'custom-tools':
|
|
691
|
+
return 'accent';
|
|
692
|
+
case 'mcp-tools':
|
|
693
|
+
return 'mdLink';
|
|
694
|
+
case 'context-files':
|
|
695
|
+
return 'mdCodeBlock';
|
|
696
|
+
case 'skills':
|
|
697
|
+
return 'customMessageLabel';
|
|
698
|
+
case 'user-messages':
|
|
699
|
+
return 'syntaxString';
|
|
700
|
+
case 'agent-text-messages':
|
|
701
|
+
return 'syntaxFunction';
|
|
702
|
+
case 'agent-thinking-messages':
|
|
703
|
+
return 'thinkingXhigh';
|
|
704
|
+
case 'agent-tool-call-messages':
|
|
705
|
+
return 'syntaxKeyword';
|
|
706
|
+
case 'tool-output':
|
|
707
|
+
return 'toolOutput';
|
|
708
|
+
case 'extension-messages':
|
|
709
|
+
return 'syntaxType';
|
|
710
|
+
case 'compacted-data':
|
|
711
|
+
return 'thinkingHigh';
|
|
712
|
+
default:
|
|
713
|
+
return 'muted';
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Compact token count: 951, 3.7k, 43.8k, 1M. */
|
|
718
|
+
export function formatTokens(tokens: number): string {
|
|
719
|
+
if (tokens < 1_000) return `${tokens}`;
|
|
720
|
+
if (tokens < 1_000_000) return `${trimTrailingZero((tokens / 1_000).toFixed(1))}k`;
|
|
721
|
+
return `${trimTrailingZero((tokens / 1_000_000).toFixed(1))}M`;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** Percentage with one decimal below 10%: 0.4%, 4.2%, 96%. */
|
|
725
|
+
export function formatPercent(ratio: number): string {
|
|
726
|
+
const percent = ratio * 100;
|
|
727
|
+
if (percent >= 10) return `${Math.round(percent)}%`;
|
|
728
|
+
return `${trimTrailingZero(percent.toFixed(1))}%`;
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
/** Drop a redundant ".0" fraction from a fixed-point rendering. */
|
|
732
|
+
function trimTrailingZero(value: string): string {
|
|
733
|
+
return value.endsWith('.0') ? value.slice(0, -2) : value;
|
|
734
|
+
}
|