@0xkahi/pi-qol 1.3.0 → 1.4.1

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 (41) hide show
  1. package/README.md +24 -10
  2. package/assets/config.schema.json +5 -0
  3. package/package.json +4 -4
  4. package/src/extensions/context-view/capture.ts +74 -35
  5. package/src/extensions/context-view/codemap.md +24 -16
  6. package/src/extensions/context-view/constants.ts +3 -0
  7. package/src/extensions/context-view/context-view-controller.ts +47 -13
  8. package/src/extensions/context-view/index.ts +25 -9
  9. package/src/extensions/context-view/measure.ts +2 -1
  10. package/src/extensions/context-view/model.ts +44 -3
  11. package/src/extensions/context-view/presentation.ts +6 -0
  12. package/src/extensions/context-view/prompt-additions.ts +5 -3
  13. package/src/extensions/context-view/ui/codemap.md +60 -93
  14. package/src/extensions/context-view/ui/context-view-dialog.ts +14 -7
  15. package/src/extensions/context-view/ui/copy.ts +42 -0
  16. package/src/extensions/context-view/ui/highlight.ts +91 -0
  17. package/src/extensions/context-view/ui/injections-model.ts +52 -0
  18. package/src/extensions/context-view/ui/injections-view.ts +124 -27
  19. package/src/extensions/context-view/ui/search.ts +28 -0
  20. package/src/extensions/context-view/ui/searchable-preview.ts +175 -0
  21. package/src/extensions/context-view/ui/usage-block-layer.ts +18 -7
  22. package/src/extensions/context-view/ui/usage-view.ts +57 -24
  23. package/src/extensions/custom-footer/footer-component.ts +1 -1
  24. package/src/extensions/model-select/codemap.md +1 -1
  25. package/src/libs/modal/README.md +13 -6
  26. package/src/libs/modal/codemap.md +6 -6
  27. package/src/libs/modal/index.ts +1 -1
  28. package/src/libs/modal/modal-dialog.ts +44 -3
  29. package/src/libs/modal/preview-layer.ts +3 -3
  30. package/src/libs/modal/sectioned-modal.ts +3 -3
  31. package/src/libs/modal/types.ts +11 -0
  32. package/src/libs/subscription-usage/codemap.md +4 -3
  33. package/src/libs/subscription-usage/credential-resolver.ts +12 -4
  34. package/src/libs/subscription-usage/index.ts +1 -0
  35. package/src/libs/subscription-usage/provider-color.ts +1 -0
  36. package/src/libs/subscription-usage/strategy/opencode-go-usage.strategy.ts +45 -0
  37. package/src/libs/subscription-usage/subscription-usage-api.util.ts +4 -1
  38. package/src/libs/subscription-usage/subscription-usage-cache.ts +11 -1
  39. package/src/schemas/context-view.config.schema.ts +2 -0
  40. package/src/extensions/context-view/ui/wheel-preview-layer.ts +0 -104
  41. package/src/extensions/context-view/ui/wheel.ts +0 -66
@@ -5,10 +5,62 @@
5
5
  * the shared modal library; terminal sanitizers live in `../text` and are
6
6
  * re-exported here for callers that reached them through this module.
7
7
  */
8
+ import type { Theme } from '@earendil-works/pi-coding-agent';
8
9
  import type { InitialSnapshot, InjectionItem } from '../model';
10
+ import { normalizePreviewText } from '../text';
11
+ import { expandJsonSpan } from './json-preview';
12
+ import { findMatches, normalizeSearchText } from './search';
13
+ import { previewBodyLines } from './section-preview';
9
14
 
10
15
  export { normalizeInlineText, normalizePreviewText } from '../text';
11
16
 
17
+ export type InjectionFilterMode = 'name' | 'content';
18
+
19
+ export interface InjectionFilterResult {
20
+ readonly snapshot: InitialSnapshot;
21
+ readonly empty: boolean;
22
+ }
23
+
24
+ // The section renderer only uses these two theme operations. Keeping them
25
+ // transparent reuses its exact heading/reference/JSON derivation without ANSI.
26
+ const plainTheme = { fg: (_color: string, text: string) => text, bold: (text: string) => text } as Theme;
27
+
28
+ /** Unwrapped text shown by the Injections preview (including expanded JSON). */
29
+ export function injectionPreviewText(item: InjectionItem): string {
30
+ return previewBodyLines(
31
+ plainTheme,
32
+ item,
33
+ Number.MAX_SAFE_INTEGER,
34
+ (text, span) => normalizePreviewText(expandJsonSpan(text, span)).split('\n'),
35
+ item.label,
36
+ ).join('\n');
37
+ }
38
+
39
+ /** Preserve original estimates; prune only visibility, never mutate the capture. */
40
+ export function filterInjections(snapshot: InitialSnapshot, query: string, mode: InjectionFilterMode): InjectionFilterResult {
41
+ if (normalizeSearchText(query) === '') return { snapshot, empty: snapshot.groups.every(group => group.items.length === 0) };
42
+ const matches = (text: string) => findMatches(text, query, mode === 'content').length > 0;
43
+ const filterItem = (item: InjectionItem): InjectionItem | undefined => {
44
+ const matched = matches(mode === 'name' ? item.label : injectionPreviewText(item));
45
+ if (mode === 'name' && matched) return item;
46
+ const children = (item.children ?? []).flatMap(child => {
47
+ const kept = filterItem(child);
48
+ return kept === undefined ? [] : [kept];
49
+ });
50
+ if (!matched && children.length === 0) return undefined;
51
+ return { ...item, ...(item.children === undefined ? {} : { children }) };
52
+ };
53
+ const groups = snapshot.groups.flatMap(group => {
54
+ if (mode === 'name' && matches(group.source.label)) return [group];
55
+ const items = group.items.flatMap(item => {
56
+ const kept = filterItem(item);
57
+ return kept === undefined ? [] : [kept];
58
+ });
59
+ return items.length === 0 ? [] : [{ ...group, items }];
60
+ });
61
+ return { snapshot: { ...snapshot, groups }, empty: groups.length === 0 };
62
+ }
63
+
12
64
  /** One flattened list row derived from the snapshot hierarchy. */
13
65
  export type InjectionRow =
14
66
  | {
@@ -6,11 +6,10 @@
6
6
  * by the shared modal library; this tab owns only its content.
7
7
  */
8
8
  import type { Theme } from '@earendil-works/pi-coding-agent';
9
- import { visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
9
+ import { Input, Key, matchesKey, type TuiMouseEvent, type TuiMouseEventResult, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
10
10
 
11
11
  import {
12
12
  BODY_INDENT,
13
- calculateViewport,
14
13
  fitLine,
15
14
  type Hint,
16
15
  ListNavigator,
@@ -21,12 +20,20 @@ import {
21
20
  wrapDescriptionLines,
22
21
  } from '../../../libs/modal';
23
22
  import type { InitialSnapshot, InjectionItem } from '../model';
24
- import { buildInjectionRows, collectItemsById, type InjectionRow, normalizeInlineText, normalizePreviewText } from './injections-model';
23
+ import { type CopyServices, copyWithNotice } from './copy';
24
+ import {
25
+ buildInjectionRows,
26
+ collectItemsById,
27
+ filterInjections,
28
+ type InjectionFilterMode,
29
+ type InjectionRow,
30
+ normalizeInlineText,
31
+ normalizePreviewText,
32
+ } from './injections-model';
25
33
  import { expandJsonSpan } from './json-preview';
26
34
  import { type ContextMarker, droppedMarker, markerLegendLines, movedMarker } from './markers';
35
+ import { SearchablePreview } from './searchable-preview';
27
36
  import { previewBodyLines, previewLegendLines } from './section-preview';
28
- import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
29
- import { WheelPreviewLayer } from './wheel-preview-layer';
30
37
 
31
38
  const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
32
39
  const CURSOR_COLUMN_WIDTH = 2;
@@ -48,22 +55,33 @@ interface InjectionColumns {
48
55
  /** Stateful Injections tab retained by the Context View dialog. */
49
56
  export class InjectionsView implements ModalTab {
50
57
  private readonly theme: Theme;
51
- private readonly rows: InjectionRow[];
58
+ private rows: InjectionRow[];
52
59
  private readonly navigator: ListNavigator;
53
60
  private readonly itemsById: Map<string, InjectionItem>;
54
61
  private readonly cache = new RenderCache();
55
- private readonly wheelScrollLines: number;
62
+ private readonly snapshot: InitialSnapshot;
63
+ private filtered: InitialSnapshot;
64
+ private readonly filterInput = new Input({ prompt: '' });
65
+ private filterMode: InjectionFilterMode = 'name';
66
+ private editing = false;
67
+ private query = '';
68
+ private empty = false;
56
69
  private context: ModalTabContext | undefined;
57
70
  private previewItem: InjectionItem | undefined;
58
71
  private previewLines: string[] | undefined;
59
72
  private previewWrapWidth: number | undefined;
60
73
 
61
- public constructor(theme: Theme, input: InjectionsViewInput, wheelScrollLines: number = DEFAULT_WHEEL_SCROLL_LINES) {
74
+ public constructor(
75
+ theme: Theme,
76
+ input: InjectionsViewInput,
77
+ private readonly copy: CopyServices,
78
+ ) {
62
79
  this.theme = theme;
63
80
  this.rows = buildInjectionRows(input.snapshot);
64
81
  this.navigator = new ListNavigator(this.rows.length, 1, this.rows.length - 2);
65
82
  this.itemsById = collectItemsById(input.snapshot);
66
- this.wheelScrollLines = wheelScrollLines;
83
+ this.snapshot = input.snapshot;
84
+ this.filtered = input.snapshot;
67
85
  }
68
86
 
69
87
  public get label(): string {
@@ -74,14 +92,88 @@ export class InjectionsView implements ModalTab {
74
92
  this.context = context;
75
93
  }
76
94
 
95
+ public capturesInput(): boolean {
96
+ return this.editing;
97
+ }
98
+
77
99
  public hints(): Hint[] {
78
- return [['Enter', 'Preview']];
100
+ return this.editing
101
+ ? [
102
+ ['Tab/Shift+Tab', 'Mode'],
103
+ ['Enter', 'Confirm'],
104
+ ['Esc', 'Clear'],
105
+ ]
106
+ : [
107
+ ['Enter', 'Preview'],
108
+ ['/', 'Filter'],
109
+ ['y', 'Copy'],
110
+ ];
79
111
  }
80
112
 
81
- /** One wheel notch steps the selection one row, like a single step key. */
82
113
  public handleInput(data: string): void {
83
- const wheel = parseWheelDirection(data);
84
- if (wheel !== undefined && this.navigator.moveBy(wheel)) this.cache.clear();
114
+ if (this.editing) {
115
+ if (matchesKey(data, Key.escape)) {
116
+ this.editing = false;
117
+ this.filterInput.focused = false;
118
+ this.query = '';
119
+ this.filterInput.setValue('');
120
+ } else if (matchesKey(data, Key.enter)) {
121
+ this.editing = false;
122
+ this.filterInput.focused = false;
123
+ this.cache.clear();
124
+ return;
125
+ } else if (matchesKey(data, Key.tab) || matchesKey(data, Key.shift('tab'))) {
126
+ this.filterMode = this.filterMode === 'name' ? 'content' : 'name';
127
+ } else {
128
+ this.filterInput.handleInput(data);
129
+ this.query = this.filterInput.getValue();
130
+ }
131
+ this.refreshFilter();
132
+ } else if (data === '/') {
133
+ this.editing = true;
134
+ this.filterInput.focused = true;
135
+ this.filterInput.setValue(this.query);
136
+ this.cache.clear();
137
+ } else if (data === 'y') {
138
+ void copyWithNotice(this.copy, this.selectedCopyText());
139
+ }
140
+ }
141
+
142
+ public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
143
+ if (event.type !== 'wheel') return undefined;
144
+ if (this.navigator.moveBy(event.wheelDelta ?? 0)) this.cache.clear();
145
+ return { handled: true };
146
+ }
147
+
148
+ private refreshFilter(): void {
149
+ const result = filterInjections(this.snapshot, this.query, this.filterMode);
150
+ this.filtered = result.snapshot;
151
+ this.empty = result.empty;
152
+ this.rows = result.empty ? [] : buildInjectionRows(result.snapshot);
153
+ this.navigator.setRowCount(this.rows.length, Math.max(0, this.rows.length - 2));
154
+ this.navigator.moveTo(0);
155
+ this.cache.clear();
156
+ }
157
+
158
+ private selectedCopyText(): string {
159
+ const row = this.rows[this.navigator.selected];
160
+ if (row?.kind === 'item') return this.itemsById.get(row.itemId)?.text ?? '';
161
+ if (row?.kind !== 'group') return '';
162
+ // Source labels need not be unique, so identify the group by its row order.
163
+ const ordinal = this.rows.slice(0, this.navigator.selected).filter(entry => entry.kind === 'group').length;
164
+ const group = this.filtered.groups[ordinal];
165
+ const intact = (item: InjectionItem): boolean => {
166
+ const original = this.itemsById.get(item.id);
167
+ return (item.children?.length ?? 0) === (original?.children?.length ?? 0) && (item.children ?? []).every(intact);
168
+ };
169
+ const visibleText = (item: InjectionItem): string => {
170
+ // Aggregate text includes its children. Keep its exact raw payload when
171
+ // the subtree is intact; reconstruct only pruned aggregates so copying
172
+ // a filtered group cannot leak a hidden sibling's content.
173
+ if (item.children?.length && !intact(item)) return item.children.map(visibleText).join('\n\n');
174
+ return item.text;
175
+ };
176
+ return group?.items.map(visibleText).join('\n\n') ?? '';
85
177
  }
86
178
 
87
179
  /** Apply semantic movement in the hierarchy, or open an item preview. */
@@ -108,21 +200,25 @@ export class InjectionsView implements ModalTab {
108
200
  const cached = this.cache.read(width, height);
109
201
  if (cached !== undefined) return cached;
110
202
 
111
- const terminalRows = height ?? this.rows.length + 10;
203
+ const terminalRows = Math.max(0, height ?? 24);
112
204
  const headerLines = this.headerLines(width);
113
205
  const descriptionLines = this.descriptionLines(width);
114
- const viewport = calculateViewport(this.rows.length, terminalRows, headerLines.length + descriptionLines.length + 2);
115
- this.navigator.setVisibleCount(viewport.visibleCount);
116
-
206
+ const filtering = this.editing || this.query.trim() !== '';
207
+ // Scroll and legend rows are accounted for even when blank. Filtering
208
+ // borrows one row from the padded list, never from the modal's height.
209
+ const fixed = headerLines.length + descriptionLines.length + 3 + (filtering ? 1 : 0);
210
+ const visibleCount = Math.max(0, terminalRows - fixed);
211
+ this.navigator.setVisibleCount(visibleCount);
212
+ const listLines = this.empty ? ['No contributions match'] : this.listLines(width).slice(0, visibleCount);
117
213
  const lines: string[] = [...headerLines, ''];
118
- const listLines = this.listLines(width);
119
- lines.push(...listLines);
120
- if (viewport.showScroll) lines.push(this.scrollLine(width));
121
- const paddingCount = viewport.visibleCount - listLines.length;
122
- for (let pad = 0; pad < paddingCount; pad++) lines.push('');
123
- lines.push('', ...descriptionLines);
124
-
125
- return this.cache.write(width, height, lines);
214
+ if (filtering) {
215
+ const prefix = `Filter (${this.filterMode === 'name' ? 'Name' : 'Content'}): `;
216
+ lines.push(prefix + (this.editing ? (this.filterInput.render(Math.max(1, width - prefix.length))[0] ?? '') : this.query));
217
+ }
218
+ for (let index = 0; index < visibleCount; index++) lines.push(listLines[index] ?? '');
219
+ lines.push(this.scrollLine(width), '', ...descriptionLines);
220
+ const padded = Array.from({ length: terminalRows }, (_, index) => this.fit(lines[index] ?? '', width));
221
+ return this.cache.write(width, height, padded);
126
222
  }
127
223
 
128
224
  public invalidate(): void {
@@ -144,12 +240,13 @@ export class InjectionsView implements ModalTab {
144
240
  const source = normalizeInlineText(item.source.label);
145
241
  const marker = item.moved === true ? movedMarker(this.theme) : '';
146
242
  this.context?.pushLayer(
147
- new WheelPreviewLayer(this.theme, {
243
+ new SearchablePreview(this.theme, {
148
244
  title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(item.label))),
149
245
  meta: () => this.theme.fg('muted', `${source} · ${item.tokens.toLocaleString('en-US')} tokens`) + marker,
150
246
  body: width => this.getPreviewLines(width, item),
151
247
  description: (width, layerHeight) => this.previewLegendLines(width, layerHeight, item),
152
- wheelScrollLines: this.wheelScrollLines,
248
+ copy: this.copy,
249
+ copyText: () => item.text,
153
250
  }),
154
251
  );
155
252
  }
@@ -0,0 +1,28 @@
1
+ /** Literal, case-insensitive matching shared by filters and rendered-line search. */
2
+ export interface MatchRange {
3
+ /** UTF-16 offsets in the searched (optionally whitespace-normalized) text. */
4
+ readonly start: number;
5
+ readonly end: number;
6
+ }
7
+
8
+ export function normalizeSearchText(text: string): string {
9
+ return text.replace(/\s+/gu, ' ').trim();
10
+ }
11
+
12
+ /** Empty queries have no pattern and never produce zero-length matches. */
13
+ export function buildSearchPattern(query: string): RegExp | undefined {
14
+ const normalized = normalizeSearchText(query);
15
+ return normalized === '' ? undefined : new RegExp(normalized.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'giu');
16
+ }
17
+
18
+ export function findMatches(text: string, query: string | RegExp, collapseWhitespace = false): MatchRange[] {
19
+ const pattern = typeof query === 'string' ? buildSearchPattern(query) : new RegExp(query.source, 'giu');
20
+ if (pattern === undefined) return [];
21
+ const searched = collapseWhitespace ? normalizeSearchText(text) : text;
22
+ return [...searched.matchAll(pattern)]
23
+ .filter(match => match[0].length > 0)
24
+ .map(match => ({
25
+ start: match.index,
26
+ end: match.index + match[0].length,
27
+ }));
28
+ }
@@ -0,0 +1,175 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { Input, Key, matchesKey, stripTerminalSequences, type TuiMouseEvent, type TuiMouseEventResult } from '@earendil-works/pi-tui';
3
+ import { BODY_INDENT, fitLine, type Hint, type ModalLayer, type NavigationAction, PreviewScroller, spreadLine } from '../../../libs/modal';
4
+ import { type CopyServices, copyWithNotice } from './copy';
5
+ import { highlightLine, matchColumns } from './highlight';
6
+ import { findMatches, type MatchRange, normalizeSearchText } from './search';
7
+
8
+ export interface SearchablePreviewOptions {
9
+ title: string | (() => string);
10
+ meta?: string | (() => string);
11
+ body: (width: number) => string[];
12
+ description?: (width: number, height: number | undefined) => string[];
13
+ hints?: () => Hint[];
14
+ copy: CopyServices;
15
+ /** Full raw content, not the rendered or searched lines. */
16
+ copyText: () => string;
17
+ }
18
+
19
+ interface LineMatch extends MatchRange {
20
+ readonly line: number;
21
+ }
22
+
23
+ /** Scroll-only preview with captured query editing and search on rendered lines. */
24
+ export class SearchablePreview implements ModalLayer {
25
+ private readonly scroller = new PreviewScroller();
26
+ private readonly input = new Input({ prompt: '' });
27
+ private editing = false;
28
+ private query = '';
29
+ private body: string[] = [];
30
+ private matches: LineMatch[] = [];
31
+ private current = -1;
32
+ private width: number | undefined;
33
+
34
+ public constructor(
35
+ private readonly theme: Theme,
36
+ private readonly options: SearchablePreviewOptions,
37
+ ) {}
38
+
39
+ public capturesInput(): boolean {
40
+ return this.editing;
41
+ }
42
+
43
+ public hints(): Hint[] {
44
+ return this.editing
45
+ ? [
46
+ ['Enter', 'Confirm'],
47
+ ['Esc', 'Clear'],
48
+ ]
49
+ : [...(this.options.hints?.() ?? []), ['/', 'Search'], ['n/N', 'Next/Previous'], ['y', 'Copy']];
50
+ }
51
+
52
+ public handleInput(data: string): void {
53
+ if (this.editing) {
54
+ if (matchesKey(data, Key.escape)) {
55
+ this.editing = false;
56
+ this.input.focused = false;
57
+ this.query = '';
58
+ this.input.setValue('');
59
+ this.rebuildMatches(false);
60
+ } else if (matchesKey(data, Key.enter)) {
61
+ this.editing = false;
62
+ this.input.focused = false;
63
+ } else {
64
+ this.input.handleInput(data);
65
+ this.query = this.input.getValue();
66
+ this.rebuildMatches(false);
67
+ }
68
+ return;
69
+ }
70
+ if (data === '/') {
71
+ this.editing = true;
72
+ this.input.focused = true;
73
+ this.input.setValue(this.query);
74
+ } else if ((data === 'n' || data === 'N') && this.matches.length > 0) {
75
+ this.current = (this.current + (data === 'n' ? 1 : -1) + this.matches.length) % this.matches.length;
76
+ this.revealCurrent();
77
+ } else if (data === 'y') {
78
+ void copyWithNotice(this.options.copy, this.options.copyText());
79
+ }
80
+ }
81
+
82
+ public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
83
+ if (event.type !== 'wheel') return undefined;
84
+ this.scroller.scrollBy(event.wheelDelta ?? 0);
85
+ return { handled: true };
86
+ }
87
+
88
+ public handleNavigation(action: NavigationAction): void {
89
+ switch (action) {
90
+ case 'step-back':
91
+ this.scroller.scrollBy(-1);
92
+ break;
93
+ case 'step-forward':
94
+ this.scroller.scrollBy(1);
95
+ break;
96
+ case 'page-back':
97
+ this.scroller.page(-1);
98
+ break;
99
+ case 'page-forward':
100
+ this.scroller.page(1);
101
+ break;
102
+ case 'first':
103
+ this.scroller.scrollTo(0);
104
+ break;
105
+ case 'last':
106
+ this.scroller.scrollTo(this.scroller.maxOffset);
107
+ break;
108
+ }
109
+ }
110
+
111
+ public render(width: number, height: number | undefined): string[] {
112
+ const rows = Math.max(0, height ?? 24);
113
+ this.body = this.options.body(width);
114
+ const description = this.options.description?.(width, height) ?? [];
115
+ // Always reserve search and scroll rows, even when inactive, so typing or
116
+ // reaching the end never changes the viewport height or scroll position.
117
+ const footer = description.length > 0 ? ['', ...description] : [];
118
+ const visible = Math.max(0, rows - 4 - footer.length);
119
+ this.scroller.setExtent(this.body.length, visible);
120
+ if (width !== this.width) {
121
+ const preserve = this.width !== undefined;
122
+ this.width = width;
123
+ this.rebuildMatches(preserve);
124
+ } else {
125
+ this.rebuildMatches(true, false);
126
+ }
127
+ const title = typeof this.options.title === 'function' ? this.options.title() : this.options.title;
128
+ const meta = typeof this.options.meta === 'function' ? this.options.meta() : (this.options.meta ?? '');
129
+ const lines = [spreadLine(title, meta, width), ''];
130
+ for (let index = this.scroller.offset; index < this.scroller.offset + visible; index++) {
131
+ const lineMatches = this.matches.map((match, matchIndex) => ({ match, matchIndex })).filter(({ match }) => match.line === index);
132
+ lines.push(
133
+ highlightLine(
134
+ this.body[index] ?? '',
135
+ lineMatches.map(({ match, matchIndex }) => ({
136
+ ...matchColumns(stripTerminalSequences(this.body[index] ?? ''), match),
137
+ current: matchIndex === this.current,
138
+ })),
139
+ ),
140
+ );
141
+ }
142
+ lines.push(this.scroller.hasOverflow ? this.theme.fg('dim', `${BODY_INDENT}(${this.scroller.visibleEnd}/${this.body.length})`) : '');
143
+ const active = this.editing || normalizeSearchText(this.query) !== '';
144
+ const count = this.matches.length === 0 ? 'no matches' : `${this.current + 1}/${this.matches.length}`;
145
+ const prefix = `Search: `;
146
+ const suffix = ` · ${count}`;
147
+ lines.push(
148
+ active
149
+ ? `${prefix}${this.editing ? (this.input.render(Math.max(1, width - prefix.length - suffix.length))[0] ?? '') : this.query}${suffix}`
150
+ : '',
151
+ );
152
+ lines.push(...footer);
153
+ return Array.from({ length: rows }, (_, index) => fitLine(lines[index] ?? '', width));
154
+ }
155
+
156
+ private rebuildMatches(preserve: boolean, reveal = true): void {
157
+ const previous = this.current;
158
+ this.matches = this.body.flatMap((line, index) =>
159
+ findMatches(stripTerminalSequences(line), this.query).map(match => ({ ...match, line: index })),
160
+ );
161
+ this.current =
162
+ this.matches.length === 0
163
+ ? -1
164
+ : preserve
165
+ ? Math.min(Math.max(0, previous), this.matches.length - 1)
166
+ : this.matches.findIndex(match => match.line >= this.scroller.offset);
167
+ if (this.current === -1 && this.matches.length > 0) this.current = 0;
168
+ if (reveal) this.revealCurrent();
169
+ }
170
+
171
+ private revealCurrent(): void {
172
+ const match = this.matches[this.current];
173
+ if (match !== undefined) this.scroller.scrollTo(match.line);
174
+ }
175
+ }
@@ -1,15 +1,17 @@
1
1
  /** Selectable chronological Usage preview layer with height-bounded entry excerpts. */
2
2
  import type { Theme } from '@earendil-works/pi-coding-agent';
3
+ import { matchesKey, type TuiMouseEvent, type TuiMouseEventResult } from '@earendil-works/pi-tui';
3
4
 
4
5
  import { BODY_INDENT, calculateViewport, fitLine, type Hint, type ModalLayer, type NavigationAction, spreadLine } from '../../../libs/modal';
5
6
  import type { UsagePreviewEntry } from '../model';
7
+ import { type CopyServices, copyWithNotice } from './copy';
6
8
  import { BlockNavigator, layoutPreviewBlocks, type PreviewLayout } from './usage-preview';
7
- import { parseWheelDirection } from './wheel';
8
9
 
9
10
  const MAX_EXCERPT_LINES = 20;
10
11
  const MIN_EXCERPT_LINES = 2;
11
12
 
12
13
  export interface UsageBlockLayerOptions {
14
+ readonly copy?: CopyServices;
13
15
  readonly title: string | (() => string);
14
16
  readonly meta?: string | (() => string);
15
17
  readonly entries: readonly UsagePreviewEntry[];
@@ -37,15 +39,24 @@ export class UsageBlockLayer implements ModalLayer {
37
39
 
38
40
  public hints(): Hint[] {
39
41
  const selected = this.blocks[this.navigator.selected];
40
- return selected?.truncated === true ? [['Enter', 'View Content']] : [];
42
+ return [...(selected?.truncated === true ? [['Enter', 'View Content'] as const] : []), ['y', 'Copy']];
41
43
  }
42
44
 
43
- /** One wheel notch steps one block; navigation is supplied as semantic actions by the modal shell. */
45
+ /** Search stays unbound in the block stream; full-content previews own search. */
44
46
  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();
47
+ if (matchesKey(data, 'y') && this.options.copy !== undefined) {
48
+ void copyWithNotice(this.options.copy, this.options.entries[this.navigator.selected]?.text ?? '');
49
+ }
50
+ }
51
+
52
+ public handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
53
+ if (event.type !== 'wheel') return undefined;
54
+ const delta = event.wheelDelta ?? 0;
55
+ for (let step = 0; step < Math.abs(delta); step++) {
56
+ const changed = delta < 0 ? this.navigator.stepBack() : this.navigator.stepForward();
57
+ if (!changed) break;
58
+ }
59
+ return { handled: true };
49
60
  }
50
61
 
51
62
  public handleNavigation(action: NavigationAction): void {