@0xkahi/pi-qol 1.0.4 → 1.0.6

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.
@@ -0,0 +1,139 @@
1
+ /** Selectable chronological Usage preview layer with height-bounded entry excerpts. */
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+
4
+ import { BODY_INDENT, calculateViewport, fitLine, type Hint, type ModalLayer, type NavigationAction, spreadLine } from '../../../libs/modal';
5
+ import type { UsagePreviewEntry } from '../model';
6
+ import { BlockNavigator, layoutPreviewBlocks, type PreviewLayout } from './usage-preview';
7
+
8
+ const MAX_EXCERPT_LINES = 20;
9
+ const MIN_EXCERPT_LINES = 2;
10
+
11
+ export interface UsageBlockLayerOptions {
12
+ readonly title: string | (() => string);
13
+ readonly meta?: string | (() => string);
14
+ readonly entries: readonly UsagePreviewEntry[];
15
+ readonly entryHeader: (entry: UsagePreviewEntry) => string;
16
+ readonly entryBody: (entry: UsagePreviewEntry, width: number) => string[];
17
+ readonly description?: (width: number) => string[];
18
+ readonly openFullContent: (entry: UsagePreviewEntry) => void;
19
+ }
20
+
21
+ interface RenderedBlock {
22
+ readonly lines: readonly string[];
23
+ readonly truncated: boolean;
24
+ }
25
+
26
+ export class UsageBlockLayer implements ModalLayer {
27
+ private readonly navigator = new BlockNavigator();
28
+ private blocks: readonly RenderedBlock[] = [];
29
+ private layout: PreviewLayout = layoutPreviewBlocks([]);
30
+ private cacheKey: string | undefined;
31
+
32
+ public constructor(
33
+ private readonly theme: Theme,
34
+ private readonly options: UsageBlockLayerOptions,
35
+ ) {}
36
+
37
+ public hints(): Hint[] {
38
+ const selected = this.blocks[this.navigator.selected];
39
+ return selected?.truncated === true ? [['Enter', 'View Content']] : [];
40
+ }
41
+
42
+ public handleInput(_data: string): void {
43
+ // Navigation is supplied as semantic actions by the modal shell.
44
+ }
45
+
46
+ public handleNavigation(action: NavigationAction): void {
47
+ switch (action) {
48
+ case 'step-back':
49
+ this.navigator.stepBack();
50
+ break;
51
+ case 'step-forward':
52
+ this.navigator.stepForward();
53
+ break;
54
+ case 'page-back':
55
+ this.navigator.page(-1);
56
+ break;
57
+ case 'page-forward':
58
+ this.navigator.page(1);
59
+ break;
60
+ case 'first':
61
+ this.navigator.moveToFirst();
62
+ break;
63
+ case 'last':
64
+ this.navigator.moveToLast();
65
+ break;
66
+ case 'confirm': {
67
+ if (this.blocks[this.navigator.selected]?.truncated !== true) return;
68
+ const entry = this.options.entries[this.navigator.selected];
69
+ if (entry !== undefined) this.options.openFullContent(entry);
70
+ break;
71
+ }
72
+ }
73
+ }
74
+
75
+ public render(width: number, height: number | undefined): string[] {
76
+ const description = this.options.description?.(width) ?? [];
77
+ // Reserve one row for the overflow counter whenever the stream needs it;
78
+ // an unused row is preferable to clipping a pinned description.
79
+ const fixedLineCount = 3 + (description.length > 0 ? description.length + 1 : 0);
80
+ const available = Math.max(1, (height ?? 20) - fixedLineCount);
81
+ const excerptCap = Math.max(MIN_EXCERPT_LINES, Math.min(MAX_EXCERPT_LINES, Math.floor((available - 3) / 2)));
82
+ this.buildBlocks(width, excerptCap);
83
+
84
+ const viewport = calculateViewport(this.layout.lines.length, height ?? this.layout.lines.length + fixedLineCount, fixedLineCount);
85
+ this.navigator.setExtent(this.layout, viewport.visibleCount);
86
+ const title = typeof this.options.title === 'function' ? this.options.title() : this.options.title;
87
+ const metaOption = this.options.meta;
88
+ const meta = typeof metaOption === 'function' ? metaOption() : (metaOption ?? '');
89
+ const lines = [spreadLine(title, meta, width), ''];
90
+
91
+ if (this.blocks.length === 0) {
92
+ lines.push(fitLine(this.theme.fg('muted', `${BODY_INDENT}No content captured for this category.`), width));
93
+ } else {
94
+ for (let index = this.navigator.offset; index < this.navigator.offset + viewport.visibleCount; index++) {
95
+ const ref = this.layout.lines[index];
96
+ if (ref === undefined) {
97
+ lines.push('');
98
+ continue;
99
+ }
100
+ const block = this.blocks[ref.blockIndex];
101
+ const line = block?.lines[ref.lineIndex] ?? '';
102
+ const cursor = ref.lineIndex === 0 && ref.blockIndex === this.navigator.selected ? this.theme.fg('accent', '→ ') : ' ';
103
+ lines.push(fitLine(`${cursor}${line}`, width));
104
+ }
105
+ }
106
+ if (viewport.showScroll) {
107
+ lines.push(
108
+ fitLine(
109
+ this.theme.fg(
110
+ 'dim',
111
+ `${BODY_INDENT}(${Math.min(this.layout.lines.length, this.navigator.offset + viewport.visibleCount)}/${this.layout.lines.length})`,
112
+ ),
113
+ width,
114
+ ),
115
+ );
116
+ }
117
+ if (description.length > 0) lines.push('', ...description);
118
+ return lines;
119
+ }
120
+
121
+ public invalidate(): void {
122
+ this.cacheKey = undefined;
123
+ }
124
+
125
+ private buildBlocks(width: number, excerptCap: number): void {
126
+ const bodyWidth = Math.max(10, width - 2);
127
+ const key = `${bodyWidth}:${excerptCap}`;
128
+ if (this.cacheKey === key) return;
129
+ this.blocks = this.options.entries.map(entry => {
130
+ const body = this.options.entryBody(entry, bodyWidth);
131
+ const truncated = body.length > excerptCap;
132
+ const visible = truncated ? body.slice(0, excerptCap) : body;
133
+ const marker = truncated ? [`${BODY_INDENT}${this.theme.fg('dim', `… +${body.length - visible.length} lines`)}`] : [];
134
+ return { lines: [this.options.entryHeader(entry), ...visible, ...marker], truncated };
135
+ });
136
+ this.layout = layoutPreviewBlocks(this.blocks.map(block => block.lines.length));
137
+ this.cacheKey = key;
138
+ }
139
+ }
@@ -26,6 +26,8 @@ export interface UsageMap {
26
26
  readonly columns: number;
27
27
  readonly rows: number;
28
28
  readonly cells: readonly UsageMapCell[];
29
+ /** Approximate token span represented by one cell at the active scale. */
30
+ readonly blockTokens: number;
29
31
  }
30
32
 
31
33
  interface MapSegment {
@@ -75,7 +77,7 @@ export function buildUsageMap(
75
77
  const bufferStart = ((contextWindow - bufferTokens) / mapScale) * cellCount;
76
78
  const segments = createSegments(usage, estimatedTotal, occupiedCells);
77
79
  const cells = Array.from({ length: cellCount }, (_, index) => createCell(index, occupiedCells, bufferStart, segments));
78
- return { columns: Math.floor(columns), rows: Math.floor(rows), cells };
80
+ return { columns: Math.floor(columns), rows: Math.floor(rows), cells, blockTokens: mapScale / cellCount };
79
81
  }
80
82
 
81
83
  /** Scale estimated category shares into the occupied map range. */
@@ -0,0 +1,148 @@
1
+ /** Pure geometry and navigation state for chronological Usage entry blocks. */
2
+ export interface PreviewBlockExtent {
3
+ readonly start: number;
4
+ readonly height: number;
5
+ }
6
+
7
+ export interface PreviewLineRef {
8
+ readonly blockIndex: number;
9
+ readonly lineIndex: number;
10
+ }
11
+
12
+ export interface PreviewLayout {
13
+ readonly extents: readonly PreviewBlockExtent[];
14
+ readonly lines: ReadonlyArray<PreviewLineRef | undefined>;
15
+ }
16
+
17
+ /** Stack block heights into one line stream separated by a blank row. */
18
+ export function layoutPreviewBlocks(heights: readonly number[]): PreviewLayout {
19
+ const extents: PreviewBlockExtent[] = [];
20
+ const lines: Array<PreviewLineRef | undefined> = [];
21
+ for (const [blockIndex, height] of heights.entries()) {
22
+ if (blockIndex > 0) lines.push(undefined);
23
+ extents.push({ start: lines.length, height });
24
+ for (let lineIndex = 0; lineIndex < height; lineIndex++) lines.push({ blockIndex, lineIndex });
25
+ }
26
+ return { extents, lines };
27
+ }
28
+
29
+ export class BlockNavigator {
30
+ private extents: readonly PreviewBlockExtent[] = [];
31
+ private lineCount = 0;
32
+ private visibleCount = 1;
33
+ private selectedIndex = 0;
34
+ private offsetValue = 0;
35
+
36
+ public get selected(): number {
37
+ return this.selectedIndex;
38
+ }
39
+ public get blockCount(): number {
40
+ return this.extents.length;
41
+ }
42
+ public get offset(): number {
43
+ return this.offsetValue;
44
+ }
45
+ public get maxOffset(): number {
46
+ return Math.max(0, this.lineCount - this.visibleCount);
47
+ }
48
+
49
+ public setExtent(layout: PreviewLayout, visibleCount: number): void {
50
+ this.extents = layout.extents;
51
+ this.lineCount = layout.lines.length;
52
+ this.visibleCount = Math.max(1, visibleCount);
53
+ this.selectedIndex = clamp(this.selectedIndex, this.extents.length - 1);
54
+ this.offsetValue = clamp(this.offsetValue, this.maxOffset);
55
+ if (!this.isSelectionAnchored()) this.revealSelected();
56
+ }
57
+
58
+ public stepBack(): boolean {
59
+ const block = this.extents[this.selectedIndex];
60
+ if (block === undefined) return false;
61
+ if (block.start < this.offsetValue) return this.scrollTo(this.offsetValue - 1);
62
+ return this.selectBlock(this.selectedIndex - 1, -1);
63
+ }
64
+
65
+ public stepForward(): boolean {
66
+ const block = this.extents[this.selectedIndex];
67
+ if (block === undefined) return false;
68
+ if (block.start + block.height > this.offsetValue + this.visibleCount) return this.scrollTo(this.offsetValue + 1);
69
+ return this.selectBlock(this.selectedIndex + 1, 1);
70
+ }
71
+
72
+ public page(direction: -1 | 1): boolean {
73
+ if (this.extents.length === 0) return false;
74
+ const offset = clamp(this.offsetValue + direction * this.visibleCount, this.maxOffset);
75
+ if (offset === this.offsetValue) return this.moveTo(direction < 0 ? 0 : this.extents.length - 1, offset);
76
+ return this.moveTo(this.firstVisibleBlock(offset), offset);
77
+ }
78
+
79
+ public moveToFirst(): boolean {
80
+ return this.moveTo(0, 0);
81
+ }
82
+ public moveToLast(): boolean {
83
+ return this.moveTo(this.extents.length - 1, this.maxOffset);
84
+ }
85
+ public reset(): void {
86
+ this.selectedIndex = 0;
87
+ this.offsetValue = 0;
88
+ }
89
+
90
+ private selectBlock(index: number, direction: -1 | 1): boolean {
91
+ if (index < 0 || index >= this.extents.length || index === this.selectedIndex) return false;
92
+ this.selectedIndex = index;
93
+ this.revealSelected(direction);
94
+ return true;
95
+ }
96
+
97
+ private scrollTo(offset: number): boolean {
98
+ const next = clamp(offset, this.maxOffset);
99
+ if (next === this.offsetValue) return false;
100
+ this.offsetValue = next;
101
+ return true;
102
+ }
103
+
104
+ private moveTo(index: number, offset: number): boolean {
105
+ const nextIndex = clamp(index, this.extents.length - 1);
106
+ const nextOffset = clamp(offset, this.maxOffset);
107
+ if (nextIndex === this.selectedIndex && nextOffset === this.offsetValue) return false;
108
+ this.selectedIndex = nextIndex;
109
+ this.offsetValue = nextOffset;
110
+ return true;
111
+ }
112
+
113
+ private isSelectionAnchored(): boolean {
114
+ const block = this.extents[this.selectedIndex];
115
+ if (block === undefined) return true;
116
+ const end = block.start + block.height;
117
+ if (block.height <= this.visibleCount) return block.start >= this.offsetValue && end <= this.offsetValue + this.visibleCount;
118
+ return block.start < this.offsetValue + this.visibleCount && end > this.offsetValue;
119
+ }
120
+
121
+ private revealSelected(direction?: -1 | 1): void {
122
+ const block = this.extents[this.selectedIndex];
123
+ if (block === undefined) return;
124
+ const end = block.start + block.height;
125
+ if (block.height > this.visibleCount) {
126
+ if (direction === -1) this.scrollTo(end - this.visibleCount);
127
+ else if (direction === 1 || !this.isSelectionAnchored()) this.scrollTo(block.start);
128
+ return;
129
+ }
130
+ if (block.start < this.offsetValue) this.scrollTo(block.start);
131
+ else if (end > this.offsetValue + this.visibleCount) this.scrollTo(end - this.visibleCount);
132
+ }
133
+
134
+ private firstVisibleBlock(offset: number): number {
135
+ const end = offset + this.visibleCount;
136
+ let firstIntersecting: number | undefined;
137
+ for (const [index, block] of this.extents.entries()) {
138
+ const blockEnd = block.start + block.height;
139
+ if (block.start >= offset && blockEnd <= end) return index;
140
+ if (firstIntersecting === undefined && block.start < end && blockEnd > offset) firstIntersecting = index;
141
+ }
142
+ return firstIntersecting ?? this.selectedIndex;
143
+ }
144
+ }
145
+
146
+ function clamp(value: number, max: number): number {
147
+ return Math.max(0, Math.min(max, value));
148
+ }
@@ -26,7 +26,9 @@ import {
26
26
  import type { ContextUsageSnapshot, UsageCategory, UsagePreviewEntry } from '../model';
27
27
  import { collectPreviewEntries } from '../usage';
28
28
  import { normalizeInlineText, normalizePreviewText } from './injections-model';
29
+ import { previewBodyLines } from './section-preview';
29
30
  import { splitSkillPreview } from './skill-preview';
31
+ import { UsageBlockLayer } from './usage-block-layer';
30
32
  import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
31
33
 
32
34
  const USAGE_DESCRIPTION =
@@ -36,7 +38,6 @@ const INVISIBLE_REASONING_DESCRIPTION =
36
38
  '≈ is a provider-reported count; ~ is a rough approximation when no breakdown ' +
37
39
  'is reported and excluded from category totals. ' +
38
40
  'Encoded replaces Reasoning when the provider replays encrypted reasoning with its message.';
39
- const PREVIEW_ENTRY_MAX_LINES = 20;
40
41
  const DETAIL_CATEGORY_HEADER_LINE_COUNT = 1;
41
42
  const CURSOR_COLUMN_WIDTH = 2;
42
43
  const MAX_LEGEND_VALUE_COLUMN = 32;
@@ -96,9 +97,6 @@ export class UsageView implements ModalTab {
96
97
  private context: ModalTabContext | undefined;
97
98
  private mapScale: UsageMapScale = 'window';
98
99
  private currentWidth: number | undefined;
99
- private cachedPreviewEntries: readonly UsagePreviewEntry[] | undefined;
100
- private previewLines: string[] | undefined;
101
- private previewWrapWidth: number | undefined;
102
100
 
103
101
  /** Create a view over one precomputed usage snapshot. */
104
102
  public constructor(theme: Theme, input: UsageViewInput) {
@@ -167,8 +165,6 @@ export class UsageView implements ModalTab {
167
165
 
168
166
  /** Invalidate theme-dependent rendered output. */
169
167
  public invalidate(): void {
170
- this.previewLines = undefined;
171
- this.previewWrapWidth = undefined;
172
168
  this.cache.clear();
173
169
  }
174
170
 
@@ -239,7 +235,7 @@ export class UsageView implements ModalTab {
239
235
  const scaleTokens = this.mapScale === 'fit' ? this.fitMapScale : undefined;
240
236
  const map = buildUsageMap(this.usage, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, scaleTokens);
241
237
  if (map === undefined || width < MAP_SIDE_BY_SIDE_MIN_WIDTH) {
242
- return this.detailLines(width, rows, false).map(line => this.fit(line, width));
238
+ return this.detailLines(width, rows).map(line => this.fit(line, width));
243
239
  }
244
240
 
245
241
  const spaced = width >= SPACED_MAP_MIN_WIDTH;
@@ -252,7 +248,7 @@ export class UsageView implements ModalTab {
252
248
  const mapWidth = BODY_INDENT.length + map.columns + (spaced ? map.columns - 1 : 0);
253
249
  const gap = spaced ? SPACED_MAP_COLUMN_GAP : MAP_COLUMN_GAP;
254
250
  const detailWidth = Math.max(1, width - mapWidth - gap);
255
- const details = this.detailLines(detailWidth, rows, true);
251
+ const details = this.detailLines(detailWidth, rows, map.blockTokens, map.cells.length);
256
252
  const lineCount = Math.max(mapLines.length, details.length);
257
253
  return Array.from({ length: lineCount }, (_, index) => {
258
254
  const mapLine = mapLines[index] ?? ' '.repeat(mapWidth);
@@ -262,10 +258,10 @@ export class UsageView implements ModalTab {
262
258
  }
263
259
 
264
260
  /** Map-fill key, category heading, selectable category legend viewport, and scroll counter. */
265
- private detailLines(width: number, rows: number, includeMapKey: boolean): string[] {
261
+ private detailLines(width: number, rows: number, blockTokens?: number, cellCount?: number): string[] {
266
262
  const theme = this.theme;
267
- const showMapKey = includeMapKey && rows >= 4;
268
- const headerLineCount = DETAIL_CATEGORY_HEADER_LINE_COUNT + (showMapKey ? 2 : 0);
263
+ const mapKey = blockTokens === undefined || cellCount === undefined ? [] : this.mapKeyLines(width, rows, blockTokens, cellCount);
264
+ const headerLineCount = DETAIL_CATEGORY_HEADER_LINE_COUNT + mapKey.length;
269
265
  // The counter sits below the last legend row, so it consumes one of the available rows.
270
266
  const viewport = calculateViewport(this.legendRows.length, rows, headerLineCount);
271
267
  this.navigator.setVisibleCount(viewport.visibleCount);
@@ -286,17 +282,19 @@ export class UsageView implements ModalTab {
286
282
  const counterLines = viewport.showScroll
287
283
  ? [this.fit(theme.fg('dim', `${BODY_INDENT}(${this.navigator.visibleEnd}/${this.legendRows.length})`), width)]
288
284
  : [];
289
- return [...(showMapKey ? [this.mapKeyLine(width), ''] : []), heading, ...visibleRows, ...counterLines].slice(0, rows);
285
+ return [...mapKey, heading, ...visibleRows, ...counterLines].slice(0, rows);
290
286
  }
291
287
 
292
- /** Explain only the map's full and partial occupancy glyphs. */
293
- private mapKeyLine(width: number): string {
288
+ /** Explain map occupancy and the active token/share scale responsively. */
289
+ private mapKeyLines(width: number, rows: number, blockTokens: number, cellCount: number): string[] {
294
290
  const theme = this.theme;
295
291
  const heading = theme.fg('mdHeading', theme.bold('Map:'));
296
292
  const separator = theme.fg('dim', ' · ');
297
293
  const full = `${theme.fg('text', FULL_CELL)}${theme.fg('muted', ' Full')}`;
298
294
  const partial = `${theme.fg('text', PARTIAL_CELL)}${theme.fg('muted', ' Part')}`;
299
- return this.fit(`${heading} ${full}${separator}${partial}`, width);
295
+ const size = theme.fg('muted', `${formatTokens(Math.round(blockTokens))}/cell (${formatPercent(1 / cellCount)} of map)`);
296
+ if (rows < 5) return [this.fit(`${heading} ${size}`, width), ''];
297
+ return [this.fit(`${heading} ${full}${separator}${partial}`, width), this.fit(`${theme.fg('mdHeading', 'Block Size:')} ${size}`, width), ''];
300
298
  }
301
299
 
302
300
  /** Pi-reported usage/window metadata, with a marked estimate when current usage is unknown. */
@@ -413,48 +411,37 @@ export class UsageView implements ModalTab {
413
411
 
414
412
  // === Preview ===
415
413
 
416
- /** Open the selected category's content preview as a shell-managed layer. */
414
+ /** Open the selected category as a selectable chronological block stream. */
417
415
  private openPreview(): void {
418
416
  const row = this.legendRows[this.navigator.selected];
419
417
  if (row === undefined || row.type !== 'category') return;
420
- this.cachedPreviewEntries = undefined;
421
- this.previewLines = undefined;
422
- this.previewWrapWidth = undefined;
423
-
418
+ const entries = collectPreviewEntries(row.category);
419
+ const compactSkills = row.rootId === 'user-messages';
424
420
  const percent = this.plainLegendPercent(row.category.tokens);
425
421
  this.context?.pushLayer(
426
- new PreviewLayer(this.theme, {
422
+ new UsageBlockLayer(this.theme, {
427
423
  title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(row.category.label))),
428
424
  meta: () => this.theme.fg('muted', `${formatTokens(row.category.tokens)}${percent === '' ? '' : ` · ${percent}`}`),
429
- body: width => this.previewBodyLines(width, row),
430
- description: width => this.previewDescriptionLines(width, row),
425
+ entries,
426
+ entryHeader: entry => this.entryHeader(entry),
427
+ entryBody: (entry, width) => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 1), compactSkills),
428
+ description: width => this.previewDescriptionLines(width, row, entries),
429
+ openFullContent: entry => this.openFullContent(row, entry, compactSkills),
431
430
  }),
432
431
  );
433
432
  }
434
433
 
435
- /** Cached wrapped entry stream: bracket headers plus capped sanitized content. */
436
- private previewBodyLines(width: number, row: CategoryLegendRow): string[] {
437
- const wrapWidth = Math.max(10, width - BODY_INDENT.length * 2 - 1);
438
- if (this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) return this.previewLines;
439
- const entries = this.previewEntries(row);
440
- const compactSkills = row.rootId === 'user-messages';
441
- const lines =
442
- entries.length === 0
443
- ? [this.fit(this.theme.fg('muted', `${BODY_INDENT}No content captured for this category.`), width)]
444
- : entries.flatMap((entry, index) => [
445
- ...(index === 0 ? [] : ['']),
446
- this.fit(`${BODY_INDENT}${this.entryHeader(entry)}`, width),
447
- ...this.entryContentLines(entry, wrapWidth, compactSkills),
448
- ]);
449
- this.previewLines = lines;
450
- this.previewWrapWidth = wrapWidth;
451
- return lines;
452
- }
453
-
454
- /** Collect and cache the immutable entries shared by preview body and description rendering. */
455
- private previewEntries(row: CategoryLegendRow): readonly UsagePreviewEntry[] {
456
- this.cachedPreviewEntries ??= collectPreviewEntries(row.category);
457
- return this.cachedPreviewEntries;
434
+ /** Push an uncapped scrollable view for one truncated block. */
435
+ private openFullContent(row: CategoryLegendRow, entry: UsagePreviewEntry, compactSkills: boolean): void {
436
+ const breadcrumb = entry.breadcrumb.map(normalizeInlineText).filter(Boolean).join(' / ');
437
+ this.context?.pushLayer(
438
+ new PreviewLayer(this.theme, {
439
+ title: () => this.theme.fg('accent', this.theme.bold(breadcrumb || normalizeInlineText(row.category.label))),
440
+ meta: () => this.theme.fg('muted', formatTokens(entry.tokens)),
441
+ // Match the block stream's two-column selection gutter so its hidden-line count stays exact.
442
+ body: width => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 3), compactSkills),
443
+ }),
444
+ );
458
445
  }
459
446
 
460
447
  /** Bracketed entry header: dim datetime, breadcrumbs, visible tokens, and optional invisible reasoning. */
@@ -480,27 +467,25 @@ export class UsageView implements ModalTab {
480
467
  }
481
468
 
482
469
  /** Fixed explanation shown only when the thinking preview contains invisible-reasoning metadata. */
483
- private previewDescriptionLines(width: number, row: CategoryLegendRow): string[] {
470
+ private previewDescriptionLines(width: number, row: CategoryLegendRow, entries: readonly UsagePreviewEntry[]): string[] {
484
471
  if (row.rootId !== 'agent-thinking-messages') return [];
485
- const hasInvisibleReasoning = this.previewEntries(row).some(entry => entry.invisibleReasoning !== undefined);
472
+ const hasInvisibleReasoning = entries.some(entry => entry.invisibleReasoning !== undefined);
486
473
  return hasInvisibleReasoning ? wrapDescriptionLines(this.theme, INVISIBLE_REASONING_DESCRIPTION, 'dim', width) : [];
487
474
  }
488
475
 
489
476
  /** Sanitized, wrapped, per-entry-capped content lines indented under the header. */
490
477
  private entryContentLines(entry: UsagePreviewEntry, wrapWidth: number, compactSkills: boolean): string[] {
491
478
  const indent = BODY_INDENT.repeat(2);
492
- const lines: string[] = [];
493
- let hidden = 0;
494
- for (const paragraph of this.entryPreviewText(entry.text, compactSkills).split('\n')) {
495
- const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
496
- const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
497
- for (const line of paragraphLines) {
498
- if (lines.length < PREVIEW_ENTRY_MAX_LINES) lines.push(line === '' ? '' : `${indent}${line}`);
499
- else hidden++;
479
+ const wrapText = (text: string): string[] => {
480
+ const lines: string[] = [];
481
+ for (const paragraph of this.entryPreviewText(text, compactSkills).split('\n')) {
482
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
483
+ const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
484
+ for (const line of paragraphLines) lines.push(line === '' ? '' : `${indent}${line}`);
500
485
  }
501
- }
502
- if (hidden === 0) return lines;
503
- return [...lines, `${indent}${this.theme.fg('dim', `… +${hidden} lines`)}`];
486
+ return lines;
487
+ };
488
+ return previewBodyLines(this.theme, entry, wrapWidth, wrapText);
504
489
  }
505
490
 
506
491
  /** Sanitize raw entry text and replace complete attached skills with pi-colored badges. */
@@ -253,7 +253,7 @@ function leafFromItem(item: InjectionItem): UsageCategory {
253
253
  id: `item:${item.id}`,
254
254
  label: item.label,
255
255
  tokens: item.tokens,
256
- entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text }],
256
+ entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text, sections: item.sections?.map(section => ({ ...section })) }],
257
257
  };
258
258
  }
259
259
 
@@ -0,0 +1,60 @@
1
+ import { sliceByColumn, stripTerminalSequences, visibleWidth } from '@earendil-works/pi-tui';
2
+ import { COLOR_HEX_REGEX } from '../../constants';
3
+
4
+ const MAX_AGENT_NAME_WIDTH = 10;
5
+
6
+ function normalizeAgentName(value: string): string {
7
+ const sanitized = stripTerminalSequences(value)
8
+ .replace(/\p{Cc}/gu, '')
9
+ .trim();
10
+ return visibleWidth(sanitized) > MAX_AGENT_NAME_WIDTH ? `${sliceByColumn(sanitized, 0, MAX_AGENT_NAME_WIDTH, true)}...` : sanitized;
11
+ }
12
+
13
+ export type AgentDisplay = {
14
+ name: string;
15
+ eventColor?: string;
16
+ };
17
+
18
+ export class AgentDisplayState {
19
+ private current: AgentDisplay;
20
+ private readonly listeners = new Set<() => void>();
21
+
22
+ constructor(defaultName: string) {
23
+ this.current = { name: normalizeAgentName(defaultName) };
24
+ }
25
+
26
+ snapshot(): Readonly<AgentDisplay> {
27
+ return this.current;
28
+ }
29
+
30
+ reset(defaultName: string): void {
31
+ this.current = { name: normalizeAgentName(defaultName) };
32
+ this.notify();
33
+ }
34
+
35
+ update(payload: unknown): boolean {
36
+ if (!payload || typeof payload !== 'object') return false;
37
+
38
+ const { agentName, color } = payload as Record<string, unknown>;
39
+ if (typeof agentName !== 'string') return false;
40
+
41
+ const name = normalizeAgentName(agentName);
42
+ if (!name) return false;
43
+
44
+ this.current = {
45
+ name,
46
+ eventColor: typeof color === 'string' && COLOR_HEX_REGEX.test(color) ? color : undefined,
47
+ };
48
+ this.notify();
49
+ return true;
50
+ }
51
+
52
+ onChange(listener: () => void): () => void {
53
+ this.listeners.add(listener);
54
+ return () => this.listeners.delete(listener);
55
+ }
56
+
57
+ private notify(): void {
58
+ for (const listener of this.listeners) listener();
59
+ }
60
+ }
@@ -18,6 +18,7 @@ function sanitizeStatusText(text: string): string {
18
18
  export class CustomFooterComponent implements Component {
19
19
  private readonly usageManager: SubscriptionUsageManager;
20
20
  private readonly unsubscribeBranch: () => void;
21
+ private readonly unsubscribeAgentDisplay: () => void;
21
22
  private restoredDefaultFooter = false;
22
23
  private disposed = false;
23
24
 
@@ -26,6 +27,9 @@ export class CustomFooterComponent implements Component {
26
27
  if (!this.disposed) deps.tui.requestRender();
27
28
  });
28
29
  this.unsubscribeBranch = deps.footerData.onBranchChange(() => deps.tui.requestRender());
30
+ this.unsubscribeAgentDisplay = deps.agentDisplayState.onChange(() => {
31
+ if (!this.disposed) deps.tui.requestRender();
32
+ });
29
33
  }
30
34
 
31
35
  invalidate(): void {
@@ -35,6 +39,7 @@ export class CustomFooterComponent implements Component {
35
39
  dispose(): void {
36
40
  this.disposed = true;
37
41
  this.unsubscribeBranch();
42
+ this.unsubscribeAgentDisplay();
38
43
  }
39
44
 
40
45
  render(width: number): string[] {
@@ -84,9 +89,26 @@ export class CustomFooterComponent implements Component {
84
89
  line = this.deps.theme.fg('dim', rawLine);
85
90
  }
86
91
 
92
+ if (config.display.agentName) {
93
+ line = `${this.renderAgentBadge(config)} ${line}`;
94
+ }
95
+
87
96
  return truncateToWidth(line, width, this.deps.theme.fg('dim', '...'));
88
97
  }
89
98
 
99
+ private renderAgentBadge(config: CustomFooterConfig): string {
100
+ const agentDisplay = this.deps.agentDisplayState.snapshot();
101
+ const badgeText = ` ${agentDisplay.name} `;
102
+ const color = agentDisplay.eventColor ?? config.colors.agentName;
103
+ if (color) {
104
+ return dye
105
+ .colorize({ fg: dye.hex(color) })
106
+ .bold()
107
+ .inverse(badgeText);
108
+ }
109
+ return dye.inverse(dye.bold(this.deps.theme.fg('accent', badgeText)));
110
+ }
111
+
90
112
  private renderStatsLine(width: number, config: CustomFooterConfig): string {
91
113
  const model = this.deps.ctx.model;
92
114
  const usingSubscription = model ? this.deps.ctx.modelRegistry.isUsingOAuth(model) : false;
@@ -1,17 +1,33 @@
1
1
  import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
+ import { SET_AGENT_NAME_EVENT_ID } from '../../constants';
4
+ import { AgentDisplayState } from './agent-display-state';
3
5
  import { CustomFooterComponent } from './footer-component';
4
6
 
5
7
  export function registerCustomFooter(pi: ExtensionAPI, deps: { config: ConfigLoader }): void {
6
8
  let installed = false;
9
+ const agentDisplayState = new AgentDisplayState('DEFAULT');
10
+
11
+ pi.events.on(SET_AGENT_NAME_EVENT_ID, payload => {
12
+ agentDisplayState.update(payload);
13
+ });
7
14
 
8
15
  pi.on('session_start', (_event, ctx) => {
16
+ agentDisplayState.reset(deps.config.getCustomFooter().defaultAgentName);
9
17
  if (!deps.config.isEnabled('custom_footer')) return;
10
18
  if (installed) return;
11
19
 
12
20
  ctx.ui.setFooter(
13
21
  (tui, theme, footerData) =>
14
- new CustomFooterComponent({ tui, theme, footerData, ctx, config: deps.config, getThinkingLevel: () => pi.getThinkingLevel() }),
22
+ new CustomFooterComponent({
23
+ tui,
24
+ theme,
25
+ footerData,
26
+ ctx,
27
+ config: deps.config,
28
+ agentDisplayState,
29
+ getThinkingLevel: () => pi.getThinkingLevel(),
30
+ }),
15
31
  );
16
32
  installed = true;
17
33
  });