@0xkahi/pi-qol 1.0.5 → 1.1.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.
Files changed (33) hide show
  1. package/README.md +35 -5
  2. package/assets/config.schema.json +18 -3
  3. package/package.json +5 -5
  4. package/src/constants.ts +1 -0
  5. package/src/extensions/context-view/capture.ts +311 -83
  6. package/src/extensions/context-view/codemap.md +111 -48
  7. package/src/extensions/context-view/context-view-controller.ts +65 -27
  8. package/src/extensions/context-view/index.ts +22 -6
  9. package/src/extensions/context-view/measure.ts +713 -78
  10. package/src/extensions/context-view/model.ts +132 -14
  11. package/src/extensions/context-view/probe-token.ts +28 -0
  12. package/src/extensions/context-view/prompt-additions.ts +174 -0
  13. package/src/extensions/context-view/prompt-blocks.ts +204 -0
  14. package/src/extensions/context-view/settings.ts +43 -0
  15. package/src/extensions/context-view/text.ts +48 -0
  16. package/src/extensions/context-view/transcript.ts +62 -0
  17. package/src/extensions/context-view/ui/codemap.md +28 -13
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +6 -1
  19. package/src/extensions/context-view/ui/injections-model.ts +13 -28
  20. package/src/extensions/context-view/ui/injections-view.ts +82 -21
  21. package/src/extensions/context-view/ui/json-preview.ts +41 -0
  22. package/src/extensions/context-view/ui/markers.ts +96 -0
  23. package/src/extensions/context-view/ui/section-preview.ts +188 -10
  24. package/src/extensions/context-view/ui/usage-block-layer.ts +9 -4
  25. package/src/extensions/context-view/ui/usage-view.ts +70 -17
  26. package/src/extensions/context-view/ui/wheel-preview-layer.ts +104 -0
  27. package/src/extensions/context-view/ui/wheel.ts +66 -0
  28. package/src/extensions/context-view/usage.ts +64 -26
  29. package/src/extensions/custom-footer/agent-display-state.ts +60 -0
  30. package/src/extensions/custom-footer/footer-component.ts +22 -0
  31. package/src/extensions/custom-footer/index.ts +17 -1
  32. package/src/extensions/custom-footer/types.ts +3 -1
  33. package/src/schemas/custom-footer-config.schema.ts +11 -0
@@ -1,29 +1,207 @@
1
- /** Shared rendering for preview content split into labeled measured sections. */
1
+ /**
2
+ * Shared preview body rendering for content that carries labeled parts, e.g. a
3
+ * tool's prompt snippet, guideline bullets, and definition. Both the Injections
4
+ * item preview and the Usage block stream present those parts the same way:
5
+ * a bold subheader with its token share above each part. Pure string logic.
6
+ */
2
7
  import type { Theme } from '@earendil-works/pi-coding-agent';
3
8
  import { wrapTextWithAnsi } from '@earendil-works/pi-tui';
4
- import { BODY_INDENT } from '../../../libs/modal';
5
- import type { InjectionSection } from '../model';
6
- import { normalizeInlineText } from './injections-model';
7
9
 
10
+ import { BODY_INDENT, calculateViewport } from '../../../libs/modal';
11
+ import type { InjectedReference, InjectionSection, JsonSpan } from '../model';
12
+ import { normalizeInlineText, normalizePreviewText } from '../text';
13
+ import { shiftJsonSpan } from './json-preview';
14
+ import { type ContextMarker, droppedMarker, guessMarker, markerLegendLines, movedMarker } from './markers';
15
+
16
+ /**
17
+ * Arrow introducing a restored line's source label. Non-breaking spaces bind
18
+ * the preceding word, arrow, and label into one wrapping unit. Units wider
19
+ * than the content width still hard-wrap, possibly just after the arrow.
20
+ */
21
+ const SOURCE_ARROW = '\u00A0<-\u00A0';
22
+ /** Keep a normal block's worth of content visible before making room for its explanation. */
23
+ const DESCRIPTION_MIN_CONTENT_ROWS = 22;
24
+
25
+ /** Raw preview content plus the labeled parts it decomposes into, when known. */
8
26
  export interface SectionedContent {
9
27
  readonly text: string;
28
+ readonly jsonSpan?: JsonSpan;
10
29
  readonly sections?: readonly InjectionSection[];
30
+ readonly injectedReferences?: readonly InjectedReference[];
31
+ /** True when a `--system-prompt` replacement dropped this content; it reads 0 tokens. */
32
+ readonly dropped?: boolean;
33
+ /** True when an extension moved this content out of the region pi renders it into. */
34
+ readonly moved?: boolean;
35
+ }
36
+
37
+ /** Space shared by uncapped preview content, its counter, and the marker legend. */
38
+ export interface PreviewDescriptionLayout {
39
+ readonly width: number;
40
+ /** Rows left after the view's fixed frame, before the description and counter. */
41
+ readonly availableRows: number;
42
+ /** Wrapped content rows, including entry headers/separators but never the footer. */
43
+ readonly contentLineCount: number;
11
44
  }
12
45
 
13
- export function previewBodyLines(theme: Theme, content: SectionedContent, wrapWidth: number, wrapText: (text: string) => string[]): string[] {
46
+ /**
47
+ * One fixed legend for the markers a preview shows, never part of its raw
48
+ * content. Collapse it whole when fewer than `DESCRIPTION_MIN_CONTENT_ROWS`
49
+ * content rows would remain, or when a shorter preview would no longer fit in
50
+ * full. Uncapped line counts keep the collapse decision independent of the
51
+ * Usage cap it helps determine.
52
+ */
53
+ export function previewLegendLines(theme: Theme, contents: readonly SectionedContent[], layout: PreviewDescriptionLayout): string[] {
54
+ const markers = previewMarkers(contents);
55
+ if (markers.length === 0) return [];
56
+ const lines = markerLegendLines(theme, markers, layout.width);
57
+ const availableRows = layout.availableRows - descriptionBlockRows(lines);
58
+ const viewport = calculateViewport(layout.contentLineCount, availableRows, 0);
59
+ const floor = Math.min(DESCRIPTION_MIN_CONTENT_ROWS, layout.contentLineCount);
60
+ return availableRows >= floor && viewport.visibleCount >= floor ? lines : [];
61
+ }
62
+
63
+ /**
64
+ * Preview body lines for one item or entry: labeled parts under their
65
+ * subheaders, or the raw text when no breakdown exists. The caller supplies
66
+ * `wrapText` so each view keeps its own sanitizing, wrapping, indentation, and
67
+ * choice of whether the marked JSON run is expanded at this level, and
68
+ * `heading` so an undivided body can drop a line the heading already shows.
69
+ */
70
+ export function previewBodyLines(
71
+ theme: Theme,
72
+ content: SectionedContent,
73
+ wrapWidth: number,
74
+ wrapText: (text: string, jsonSpan: JsonSpan | undefined) => string[],
75
+ heading?: string,
76
+ ): string[] {
14
77
  const sections = content.sections ?? [];
15
- if (sections.length === 0) return wrapText(content.text);
78
+ if (sections.length === 0) return contentBodyLines(theme, content, wrapWidth, wrapText, heading);
16
79
  const lines: string[] = [];
17
80
  for (const section of sections) {
18
- if (lines.length > 0) lines.push('');
81
+ if (lines.length > 0) {
82
+ // Captured trailing whitespace must not add to the subsection separator
83
+ while (lines.length > 0 && normalizeInlineText(lines[lines.length - 1] ?? '') === '') lines.pop();
84
+ lines.push('', '');
85
+ }
19
86
  lines.push(...sectionHeaderLines(theme, section, wrapWidth));
20
- lines.push(...wrapText(section.text.replace(/^\n+/, '')));
87
+ lines.push(...contentBodyLines(theme, section, wrapWidth, wrapText, section.label));
21
88
  }
22
89
  return lines;
23
90
  }
24
91
 
92
+ /**
93
+ * Markers one preview renders: restored lines and their inferred owners come
94
+ * from reference metadata, while state markers follow the subheaders and
95
+ * metadata rows that show them, whether or not that part carries references.
96
+ */
97
+ function previewMarkers(contents: readonly SectionedContent[]): ContextMarker[] {
98
+ const referenced = contents.flatMap(content => referenceParts(content)).filter(hasInjectedReferences);
99
+ const marked = contents.flatMap(content => [content, ...(content.sections ?? [])]);
100
+ const markers: ContextMarker[] = [];
101
+ if (referenced.length > 0) markers.push('highlighted');
102
+ if (referenced.some(hasGuessedReferences)) markers.push('guess');
103
+ if (marked.some(part => part.dropped === true)) markers.push('dropped');
104
+ if (marked.some(part => part.moved === true)) markers.push('moved');
105
+ return markers;
106
+ }
107
+
108
+ /** Only metadata on rendered body parts triggers the footer, never a text or label match. */
109
+ function hasInjectedReferences(part: SectionedContent): boolean {
110
+ return (part.injectedReferences?.length ?? 0) > 0;
111
+ }
112
+
113
+ /** Whether a rendered reference names an inferred owner needing the extra caveat. */
114
+ function hasGuessedReferences(part: SectionedContent): boolean {
115
+ return part.injectedReferences?.some(reference => reference.attribution === 'guess') === true;
116
+ }
117
+
118
+ /** Body parts carrying reference metadata: the item's sections, or the item itself. */
119
+ function referenceParts(content: SectionedContent): readonly SectionedContent[] {
120
+ return content.sections?.length ? content.sections : [content];
121
+ }
122
+
123
+ /** Render referenced prompt lines locally; other content keeps the caller's JSON/skill transformations. */
124
+ function contentBodyLines(
125
+ theme: Theme,
126
+ content: SectionedContent,
127
+ wrapWidth: number,
128
+ wrapText: (text: string, jsonSpan: JsonSpan | undefined) => string[],
129
+ heading: string | undefined,
130
+ ): string[] {
131
+ const references = content.injectedReferences ?? [];
132
+ if (references.length === 0) return bodyLines(content.text, content.jsonSpan, heading, wrapText);
133
+ let text = '';
134
+ let offset = 0;
135
+ for (const reference of references) {
136
+ text += normalizePreviewText(content.text.slice(offset, reference.offset));
137
+ // A part that opens with a reference drops its captured lead, as plain text does.
138
+ const line = text.length === 0 ? reference.text.replace(/^\n+/, '') : reference.text;
139
+ text += theme.fg('syntaxNumber', normalizePreviewText(line));
140
+ text += theme.fg('borderMuted', SOURCE_ARROW);
141
+ text += theme.fg('mdLink', normalizeInlineText(reference.source.label));
142
+ if (reference.tool !== undefined) {
143
+ text += theme.fg('mdLinkUrl', `:${normalizeInlineText(reference.tool)}`);
144
+ }
145
+ if (reference.attribution === 'guess') text += guessMarker(theme);
146
+ offset = reference.offset;
147
+ }
148
+ text += normalizePreviewText(content.text.slice(offset));
149
+ const body = withoutRepeatedHeading(text.replace(/^\n+/, ''), heading);
150
+ return wrapTextWithAnsi(body, wrapWidth).map(line => (line === '' ? '' : `${BODY_INDENT}${line}`));
151
+ }
152
+
153
+ /**
154
+ * One body part, wrapped after dropping the lead its heading already carries:
155
+ * the newline that separated a carved prompt line, and a first line repeating
156
+ * the heading itself, as a skill block opens with its own name.
157
+ */
158
+ function bodyLines(
159
+ text: string,
160
+ jsonSpan: JsonSpan | undefined,
161
+ heading: string | undefined,
162
+ wrapText: (text: string, jsonSpan: JsonSpan | undefined) => string[],
163
+ ): string[] {
164
+ const body = withoutRepeatedHeading(text.replace(/^\n+/, ''), heading);
165
+ return wrapText(body, shiftJsonSpan(jsonSpan, text.length - body.length));
166
+ }
167
+
168
+ /**
169
+ * Text without a first line that only repeats the heading rendered above it.
170
+ * The dropped line stays part of the estimate; it is redundant on screen only.
171
+ */
172
+ function withoutRepeatedHeading(text: string, heading: string | undefined): string {
173
+ if (heading === undefined) return text;
174
+ const lineEnd = text.indexOf('\n');
175
+ if (lineEnd === -1 || headingKey(text.slice(0, lineEnd)) !== headingKey(heading)) return text;
176
+ return text.slice(lineEnd + 1);
177
+ }
178
+
179
+ /**
180
+ * Comparable form of a heading or a first content line: case and a trailing
181
+ * colon carry no information here, so pi's own block headers ("Available
182
+ * tools:", "Guidelines:") read as repeats of the part labels above them.
183
+ */
184
+ function headingKey(text: string): string {
185
+ return text.trim().replace(/:$/, '').toLowerCase();
186
+ }
187
+
188
+ /**
189
+ * Bold subheader naming one part and its share of the parent estimate. Parts use
190
+ * `syntaxKeyword` rather than the usual `mdHeading` subheader color, because they
191
+ * nest under item and entry headings that already carry `mdHeading`.
192
+ */
25
193
  function sectionHeaderLines(theme: Theme, section: InjectionSection, wrapWidth: number): string[] {
26
- const label = theme.fg('syntaxFunction', theme.bold(normalizeInlineText(section.label)));
194
+ const label = theme.fg('syntaxKeyword', theme.bold(normalizeInlineText(section.label)));
27
195
  const tokens = theme.fg('muted', ` · ${section.tokens.toLocaleString('en-US')} tokens`);
28
- return wrapTextWithAnsi(`${label}${tokens}`, wrapWidth).map(line => `${BODY_INDENT}${line}`);
196
+ const marker = section.dropped === true ? droppedMarker(theme) : section.moved === true ? movedMarker(theme) : '';
197
+ return wrapTextWithAnsi(`${label}${tokens}${marker}`, wrapWidth).map(line => `${BODY_INDENT}${line}`);
198
+ }
199
+
200
+ /**
201
+ * Rows a description block occupies, including the blank row above it; zero
202
+ * when collapsed. A description is the least important block on a frame, so
203
+ * each view drops the whole block once its own content threshold is reached.
204
+ */
205
+ function descriptionBlockRows(lines: readonly string[]): number {
206
+ return lines.length === 0 ? 0 : lines.length + 1;
29
207
  }
@@ -4,6 +4,7 @@ import type { Theme } from '@earendil-works/pi-coding-agent';
4
4
  import { BODY_INDENT, calculateViewport, fitLine, type Hint, type ModalLayer, type NavigationAction, spreadLine } from '../../../libs/modal';
5
5
  import type { UsagePreviewEntry } from '../model';
6
6
  import { BlockNavigator, layoutPreviewBlocks, type PreviewLayout } from './usage-preview';
7
+ import { parseWheelDirection } from './wheel';
7
8
 
8
9
  const MAX_EXCERPT_LINES = 20;
9
10
  const MIN_EXCERPT_LINES = 2;
@@ -14,7 +15,7 @@ export interface UsageBlockLayerOptions {
14
15
  readonly entries: readonly UsagePreviewEntry[];
15
16
  readonly entryHeader: (entry: UsagePreviewEntry) => string;
16
17
  readonly entryBody: (entry: UsagePreviewEntry, width: number) => string[];
17
- readonly description?: (width: number) => string[];
18
+ readonly description?: (width: number, height: number | undefined) => string[];
18
19
  readonly openFullContent: (entry: UsagePreviewEntry) => void;
19
20
  }
20
21
 
@@ -39,8 +40,12 @@ export class UsageBlockLayer implements ModalLayer {
39
40
  return selected?.truncated === true ? [['Enter', 'View Content']] : [];
40
41
  }
41
42
 
42
- public handleInput(_data: string): void {
43
- // Navigation is supplied as semantic actions by the modal shell.
43
+ /** One wheel notch steps one block; navigation is supplied as semantic actions by the modal shell. */
44
+ public handleInput(data: string): void {
45
+ const wheel = parseWheelDirection(data);
46
+ if (wheel === undefined) return;
47
+ if (wheel < 0) this.navigator.stepBack();
48
+ else this.navigator.stepForward();
44
49
  }
45
50
 
46
51
  public handleNavigation(action: NavigationAction): void {
@@ -73,7 +78,7 @@ export class UsageBlockLayer implements ModalLayer {
73
78
  }
74
79
 
75
80
  public render(width: number, height: number | undefined): string[] {
76
- const description = this.options.description?.(width) ?? [];
81
+ const description = this.options.description?.(width, height) ?? [];
77
82
  // Reserve one row for the overflow counter whenever the stream needs it;
78
83
  // an unused row is preferable to clipping a pinned description.
79
84
  const fixedLineCount = 3 + (description.length > 0 ? description.length + 1 : 0);
@@ -18,18 +18,20 @@ import {
18
18
  type ModalTab,
19
19
  type ModalTabContext,
20
20
  type NavigationAction,
21
- PreviewLayer,
22
21
  RenderCache,
23
22
  spreadLine,
24
23
  wrapDescriptionLines,
25
24
  } from '../../../libs/modal';
26
- import type { ContextUsageSnapshot, UsageCategory, UsagePreviewEntry } from '../model';
25
+ import type { ContextUsageSnapshot, JsonSpan, UsageCategory, UsagePreviewEntry } from '../model';
27
26
  import { collectPreviewEntries } from '../usage';
28
27
  import { normalizeInlineText, normalizePreviewText } from './injections-model';
29
- import { previewBodyLines } from './section-preview';
28
+ import { expandJsonSpan } from './json-preview';
29
+ import { previewBodyLines, previewLegendLines } from './section-preview';
30
30
  import { splitSkillPreview } from './skill-preview';
31
31
  import { UsageBlockLayer } from './usage-block-layer';
32
32
  import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
33
+ import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
34
+ import { WheelPreviewLayer } from './wheel-preview-layer';
33
35
 
34
36
  const USAGE_DESCRIPTION =
35
37
  'Estimated context for the next model request. ' + "Token counts are approximate and may differ from the provider's estimate.";
@@ -53,6 +55,8 @@ const COMPACTED_CELL = '▦';
53
55
  const BUFFER_CELL = '⛝';
54
56
  const FREE_CELL = '⛶';
55
57
  const BREAKDOWN_MARKER = '•';
58
+ /** Title and its trailing blank row the full-content wheel layer spends outside its body. */
59
+ const FULL_CONTENT_FIXED_LINE_COUNT = 2;
56
60
 
57
61
  /** Everything the Usage view renders, classified once when the view opens. */
58
62
  export interface UsageViewInput {
@@ -94,14 +98,16 @@ export class UsageView implements ModalTab {
94
98
  private readonly navigator: ListNavigator;
95
99
  private readonly cache = new RenderCache();
96
100
  private readonly fitMapScale: number | undefined;
101
+ private readonly wheelScrollLines: number;
97
102
  private context: ModalTabContext | undefined;
98
103
  private mapScale: UsageMapScale = 'window';
99
104
  private currentWidth: number | undefined;
100
105
 
101
106
  /** Create a view over one precomputed usage snapshot. */
102
- public constructor(theme: Theme, input: UsageViewInput) {
107
+ public constructor(theme: Theme, input: UsageViewInput, wheelScrollLines: number = DEFAULT_WHEEL_SCROLL_LINES) {
103
108
  this.theme = theme;
104
109
  this.usage = input.usage;
110
+ this.wheelScrollLines = wheelScrollLines;
105
111
  this.legendRows = this.buildLegendRows();
106
112
  const selectableCount = this.legendRows.filter(row => row.type === 'category').length;
107
113
  this.navigator = new ListNavigator(this.legendRows.length, 1, selectableCount);
@@ -122,8 +128,13 @@ export class UsageView implements ModalTab {
122
128
  return hints;
123
129
  }
124
130
 
125
- /** Handle the view-local map-zoom key; navigation arrives as actions. */
131
+ /** Handle the view-local map-zoom key; navigation arrives as actions and wheel steps the list. */
126
132
  public handleInput(data: string): void {
133
+ const wheel = parseWheelDirection(data);
134
+ if (wheel !== undefined) {
135
+ if (this.navigator.moveBy(wheel)) this.cache.clear();
136
+ return;
137
+ }
127
138
  if (matchesKey(data, 'z')) this.toggleMapScale();
128
139
  }
129
140
 
@@ -425,7 +436,7 @@ export class UsageView implements ModalTab {
425
436
  entries,
426
437
  entryHeader: entry => this.entryHeader(entry),
427
438
  entryBody: (entry, width) => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 1), compactSkills),
428
- description: width => this.previewDescriptionLines(width, row, entries),
439
+ description: (width, height) => this.previewDescriptionLines(width, height, row, entries),
429
440
  openFullContent: entry => this.openFullContent(row, entry, compactSkills),
430
441
  }),
431
442
  );
@@ -435,15 +446,30 @@ export class UsageView implements ModalTab {
435
446
  private openFullContent(row: CategoryLegendRow, entry: UsagePreviewEntry, compactSkills: boolean): void {
436
447
  const breadcrumb = entry.breadcrumb.map(normalizeInlineText).filter(Boolean).join(' / ');
437
448
  this.context?.pushLayer(
438
- new PreviewLayer(this.theme, {
449
+ new WheelPreviewLayer(this.theme, {
439
450
  title: () => this.theme.fg('accent', this.theme.bold(breadcrumb || normalizeInlineText(row.category.label))),
440
451
  meta: () => this.theme.fg('muted', formatTokens(entry.tokens)),
441
452
  // Match the block stream's two-column selection gutter so its hidden-line count stays exact.
442
453
  body: width => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 3), compactSkills),
454
+ description: (width, height) => this.fullContentLegendLines(width, height, entry, compactSkills),
455
+ wheelScrollLines: this.wheelScrollLines,
443
456
  }),
444
457
  );
445
458
  }
446
459
 
460
+ /**
461
+ * Marker legend for one block's full content, sized against the rows its own
462
+ * body leaves below the layer frame (mirrors the block stream's legend).
463
+ */
464
+ private fullContentLegendLines(width: number, height: number | undefined, entry: UsagePreviewEntry, compactSkills: boolean): string[] {
465
+ const wrapWidth = Math.max(10, width - BODY_INDENT.length * 2 - 3);
466
+ return previewLegendLines(this.theme, [entry], {
467
+ width,
468
+ availableRows: Math.max(1, (height ?? 24) - FULL_CONTENT_FIXED_LINE_COUNT),
469
+ contentLineCount: Math.max(1, this.entryContentLines(entry, wrapWidth, compactSkills).length),
470
+ });
471
+ }
472
+
447
473
  /** Bracketed entry header: dim datetime, breadcrumbs, visible tokens, and optional invisible reasoning. */
448
474
  private entryHeader(entry: UsagePreviewEntry): string {
449
475
  const theme = this.theme;
@@ -452,8 +478,10 @@ export class UsageView implements ModalTab {
452
478
  cells.push(theme.fg('dim', `[${formatEntryTimestamp(entry.timestamp)}]`));
453
479
  }
454
480
  entry.breadcrumb.forEach((cell, index) => {
455
- const color: ThemeColor = index === 0 ? 'mdHeading' : 'muted';
456
- cells.push(`${theme.fg('dim', '[')}${theme.fg(color, normalizeInlineText(cell))}${theme.fg('dim', ']')}`);
481
+ const lead = index === 0;
482
+ const color: ThemeColor = lead ? 'mdHeading' : 'muted';
483
+ const name = normalizeInlineText(cell);
484
+ cells.push(`${theme.fg('dim', '[')}${theme.fg(color, lead ? theme.bold(name) : name)}${theme.fg('dim', ']')}`);
457
485
  });
458
486
  cells.push(theme.fg('dim', formatTokens(entry.visibleTokens ?? entry.tokens)));
459
487
  if (entry.invisibleReasoning !== undefined) {
@@ -466,26 +494,51 @@ export class UsageView implements ModalTab {
466
494
  return cells.join(' ');
467
495
  }
468
496
 
469
- /** Fixed explanation shown only when the thinking preview contains invisible-reasoning metadata. */
470
- private previewDescriptionLines(width: number, row: CategoryLegendRow, entries: readonly UsagePreviewEntry[]): string[] {
471
- if (row.rootId !== 'agent-thinking-messages') return [];
472
- const hasInvisibleReasoning = entries.some(entry => entry.invisibleReasoning !== undefined);
473
- return hasInvisibleReasoning ? wrapDescriptionLines(this.theme, INVISIBLE_REASONING_DESCRIPTION, 'dim', width) : [];
497
+ /**
498
+ * Marker legend for a category preview, or the fixed reasoning notation when
499
+ * the thinking category carries invisible-reasoning metadata.
500
+ */
501
+ private previewDescriptionLines(
502
+ width: number,
503
+ height: number | undefined,
504
+ row: CategoryLegendRow,
505
+ entries: readonly UsagePreviewEntry[],
506
+ ): string[] {
507
+ if (row.rootId === 'agent-thinking-messages') {
508
+ const hasInvisibleReasoning = entries.some(entry => entry.invisibleReasoning !== undefined);
509
+ return hasInvisibleReasoning ? wrapDescriptionLines(this.theme, INVISIBLE_REASONING_DESCRIPTION, 'dim', width) : [];
510
+ }
511
+ return previewLegendLines(this.theme, entries, {
512
+ width,
513
+ availableRows: Math.max(1, (height ?? 24) - 3),
514
+ contentLineCount: this.previewContentLineCount(width, row, entries),
515
+ });
516
+ }
517
+
518
+ /** Uncapped content rows the block stream would occupy, used only to size the legend. */
519
+ private previewContentLineCount(width: number, row: CategoryLegendRow, entries: readonly UsagePreviewEntry[]): number {
520
+ // The block stream hands entry bodies a bodyWidth already reduced by its two-column gutter.
521
+ const wrapWidth = Math.max(10, width - 2 - BODY_INDENT.length * 2 - 1);
522
+ const compactSkills = row.rootId === 'user-messages';
523
+ return Math.max(
524
+ 1,
525
+ entries.reduce((total, entry) => total + this.entryContentLines(entry, wrapWidth, compactSkills).length + 2, -1),
526
+ );
474
527
  }
475
528
 
476
529
  /** Sanitized, wrapped, per-entry-capped content lines indented under the header. */
477
530
  private entryContentLines(entry: UsagePreviewEntry, wrapWidth: number, compactSkills: boolean): string[] {
478
531
  const indent = BODY_INDENT.repeat(2);
479
- const wrapText = (text: string): string[] => {
532
+ const wrapText = (text: string, jsonSpan: JsonSpan | undefined): string[] => {
480
533
  const lines: string[] = [];
481
- for (const paragraph of this.entryPreviewText(text, compactSkills).split('\n')) {
534
+ for (const paragraph of this.entryPreviewText(expandJsonSpan(text, jsonSpan), compactSkills).split('\n')) {
482
535
  const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
483
536
  const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
484
537
  for (const line of paragraphLines) lines.push(line === '' ? '' : `${indent}${line}`);
485
538
  }
486
539
  return lines;
487
540
  };
488
- return previewBodyLines(this.theme, entry, wrapWidth, wrapText);
541
+ return previewBodyLines(this.theme, entry, wrapWidth, wrapText, entry.breadcrumb.at(-1));
489
542
  }
490
543
 
491
544
  /** Sanitize raw entry text and replace complete attached skills with pi-colored badges. */
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Context View preview layer with mouse-wheel support.
3
+ *
4
+ * The shared modal `PreviewLayer` is scroll-only through semantic navigation
5
+ * actions; the Context View adds opt-in wheel scrolling on top, since pi
6
+ * forwards wheel reports only to a focused overlay and never consumes them
7
+ * itself. This layer mirrors the shared preview frame while stepping its own
8
+ * `PreviewScroller` on a wheel notch.
9
+ */
10
+ import type { Theme } from '@earendil-works/pi-coding-agent';
11
+
12
+ import {
13
+ BODY_INDENT,
14
+ calculateViewport,
15
+ fitLine,
16
+ type Hint,
17
+ type ModalLayer,
18
+ type NavigationAction,
19
+ PreviewScroller,
20
+ spreadLine,
21
+ } from '../../../libs/modal';
22
+ import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
23
+
24
+ export interface WheelPreviewLayerOptions {
25
+ /** Styled title rendered on the left of the header line. */
26
+ title: string | (() => string);
27
+ /** Muted metadata rendered right-aligned beside the title. */
28
+ meta?: string | (() => string);
29
+ /** Body lines for the given width; wrapping is the caller's concern. */
30
+ body: (width: number) => string[];
31
+ /** Optional fixed description lines pinned below the body, given the layer's width and height. */
32
+ description?: (width: number, height: number | undefined) => string[];
33
+ /** Layer-specific hints appended after the navigation scheme's hints. */
34
+ hints?: () => Hint[];
35
+ /** Lines one wheel notch scrolls; defaults to the project fallback. */
36
+ wheelScrollLines?: number;
37
+ }
38
+
39
+ export class WheelPreviewLayer implements ModalLayer {
40
+ private readonly scroller = new PreviewScroller();
41
+
42
+ public constructor(
43
+ private readonly theme: Theme,
44
+ private readonly options: WheelPreviewLayerOptions,
45
+ ) {}
46
+
47
+ public hints(): Hint[] {
48
+ return this.options.hints?.() ?? [];
49
+ }
50
+
51
+ /** Scroll one wheel notch; every other raw key is ignored by the preview. */
52
+ public handleInput(data: string): void {
53
+ const wheel = parseWheelDirection(data);
54
+ if (wheel === undefined) return;
55
+ this.scroller.scrollBy(wheel * (this.options.wheelScrollLines ?? DEFAULT_WHEEL_SCROLL_LINES));
56
+ }
57
+
58
+ public handleNavigation(action: NavigationAction): void {
59
+ switch (action) {
60
+ case 'step-back':
61
+ this.scroller.scrollBy(-1);
62
+ break;
63
+ case 'step-forward':
64
+ this.scroller.scrollBy(1);
65
+ break;
66
+ case 'page-back':
67
+ this.scroller.page(-1);
68
+ break;
69
+ case 'page-forward':
70
+ this.scroller.page(1);
71
+ break;
72
+ case 'first':
73
+ this.scroller.scrollTo(0);
74
+ break;
75
+ case 'last':
76
+ this.scroller.scrollTo(this.scroller.maxOffset);
77
+ break;
78
+ }
79
+ }
80
+
81
+ public render(width: number, height: number | undefined): string[] {
82
+ const body = this.options.body(width);
83
+ const description = this.options.description?.(width, height) ?? [];
84
+ // title + blank, plus blank + description when present
85
+ const fixedLineCount = 2 + (description.length > 0 ? description.length + 1 : 0);
86
+ const viewport = calculateViewport(body.length, height ?? body.length + fixedLineCount, fixedLineCount);
87
+ this.scroller.setExtent(body.length, viewport.visibleCount);
88
+
89
+ const title = typeof this.options.title === 'function' ? this.options.title() : this.options.title;
90
+ const metaOption = this.options.meta;
91
+ const meta = typeof metaOption === 'function' ? metaOption() : (metaOption ?? '');
92
+
93
+ const lines: string[] = [spreadLine(title, meta, width), ''];
94
+ const start = this.scroller.offset;
95
+ for (let index = start; index < start + viewport.visibleCount; index++) {
96
+ lines.push(body[index] ?? '');
97
+ }
98
+ if (viewport.showScroll) {
99
+ lines.push(fitLine(this.theme.fg('dim', `${BODY_INDENT}(${this.scroller.visibleEnd}/${body.length})`), width));
100
+ }
101
+ if (description.length > 0) lines.push('', ...description);
102
+ return lines;
103
+ }
104
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Mouse-wheel input shared by the Usage and Injections views.
3
+ *
4
+ * Pi enables mouse reporting only in fullscreen (alt-screen) mode, where its
5
+ * viewport forwards wheel reports to the focused overlay instead of consuming
6
+ * them. In regular mode the terminal keeps the wheel for its own scrollback and
7
+ * no report ever reaches a view, so the parser simply never matches there.
8
+ */
9
+ import type { TUI } from '@earendil-works/pi-tui';
10
+
11
+ /** Lines one notch scrolls when the TUI exposes no step of its own. */
12
+ export const DEFAULT_WHEEL_SCROLL_LINES = 3;
13
+
14
+ /** SGR wheel report: `ESC [ < button ; column ; row` closed by `M` or `m`. */
15
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: wheel reports begin with the escape byte.
16
+ const SGR_WHEEL_PATTERN = /^\x1b\[<(\d+);\d+;\d+[Mm]$/;
17
+
18
+ /** Legacy X10 wheel report: `ESC [ M` plus offset-encoded button, column, and row bytes. */
19
+ const X10_PREFIX = '\x1b[M';
20
+ const X10_LENGTH = 6;
21
+ const X10_BUTTON_INDEX = 3;
22
+ const X10_BYTE_OFFSET = 32;
23
+
24
+ /** Wheel reports set this button bit; the low two bits then carry axis and direction. */
25
+ const WHEEL_BUTTON_BIT = 64;
26
+ const DIRECTION_MASK = 3;
27
+
28
+ /** One notch backwards (up) or forwards (down). */
29
+ export type WheelDirection = -1 | 1;
30
+
31
+ /**
32
+ * Vertical wheel direction encoded in one input chunk, or undefined for every
33
+ * other input, including horizontal notches. Modifier bits are ignored, so a
34
+ * modified notch scrolls like a plain one, as it does in pi's own viewport.
35
+ */
36
+ export function parseWheelDirection(data: string): WheelDirection | undefined {
37
+ const sgrButton = SGR_WHEEL_PATTERN.exec(data)?.[1];
38
+ if (sgrButton !== undefined) return decodeWheelButton(Number.parseInt(sgrButton, 10));
39
+ if (data.length === X10_LENGTH && data.startsWith(X10_PREFIX)) {
40
+ return decodeWheelButton(data.charCodeAt(X10_BUTTON_INDEX) - X10_BYTE_OFFSET);
41
+ }
42
+ return undefined;
43
+ }
44
+
45
+ /**
46
+ * Lines one notch scrolls in the surrounding TUI.
47
+ *
48
+ * `TuiAltScreen` keeps its `wheelScrollLines` option private and pi never
49
+ * surfaces it, so read it defensively: honoring the real step keeps previews
50
+ * consistent with the transcript viewport, while any pi that hides, renames, or
51
+ * never had the field falls back to the default instead of a contradicting step.
52
+ */
53
+ export function readWheelScrollLines(tui: TUI): number {
54
+ const lines = (tui as { readonly wheelScrollLines?: unknown }).wheelScrollLines;
55
+ if (typeof lines !== 'number' || !Number.isFinite(lines)) return DEFAULT_WHEEL_SCROLL_LINES;
56
+ return Math.max(1, Math.floor(lines));
57
+ }
58
+
59
+ /** Decode one button code, rejecting non-wheel buttons and the horizontal axis. */
60
+ function decodeWheelButton(button: number): WheelDirection | undefined {
61
+ if ((button & WHEEL_BUTTON_BIT) === 0) return undefined;
62
+ const direction = button & DIRECTION_MASK;
63
+ if (direction === 0) return -1;
64
+ if (direction === 1) return 1;
65
+ return undefined;
66
+ }