@0xkahi/pi-qol 1.4.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 (31) hide show
  1. package/README.md +11 -2
  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/libs/modal/README.md +9 -3
  24. package/src/libs/modal/codemap.md +5 -5
  25. package/src/libs/modal/index.ts +1 -1
  26. package/src/libs/modal/modal-dialog.ts +44 -3
  27. package/src/libs/modal/preview-layer.ts +3 -3
  28. package/src/libs/modal/types.ts +11 -0
  29. package/src/schemas/context-view.config.schema.ts +2 -0
  30. package/src/extensions/context-view/ui/wheel-preview-layer.ts +0 -104
  31. package/src/extensions/context-view/ui/wheel.ts +0 -66
@@ -11,6 +11,7 @@ import {
11
11
  } from './capture';
12
12
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
13
13
  import { prepareContextViewData } from './context-view-controller';
14
+ import { canPresent } from './presentation';
14
15
  import { readProbeToken } from './probe-token';
15
16
  import { ContextViewDialog } from './ui/context-view-dialog';
16
17
 
@@ -19,6 +20,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
19
20
  const probe = new SilentProbeState();
20
21
  const compaction = new CompactionState();
21
22
  let persistedIdentityCount = 0;
23
+ let skipCurrentCapture = false;
22
24
  let latestCtx: ExtensionContext = deps.initialCtx;
23
25
  const enabled = () => deps.config.isEnabled('context_view');
24
26
 
@@ -37,7 +39,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
37
39
  persistedIdentityCount = identities.length;
38
40
  };
39
41
  const openContextView = async (ctx: ExtensionContext) => {
40
- const data = await prepareContextViewData(pi, ctx, capture, probe, compaction);
42
+ const data = await prepareContextViewData(pi, ctx, capture, probe, compaction, { autoProbing: deps.config.getContextView().auto_probing });
41
43
  const config = deps.config.getContextView();
42
44
  await presentModal(
43
45
  ctx.ui,
@@ -61,12 +63,19 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
61
63
  if (!enabled()) return;
62
64
  // Reset text earlier input transforms added to our own synthetic prompt:
63
65
  // the probe carries no instructions, and its run is identified by token.
64
- if (event.text === '' || !probe.isProbeInput(event.source, readProbeToken())) return undefined;
66
+ const wasRunning = probe.isCurrentRun;
67
+ const claimed = probe.isProbeInput(event.source, readProbeToken(), event.streamingBehavior);
68
+ if (wasRunning && !probe.isCurrentRun) skipCurrentCapture = true;
69
+ if (!claimed || event.text === '') return undefined;
65
70
  return { action: 'transform', text: '' } as const;
66
71
  });
67
- pi.on('before_agent_start', event => {
68
- if (!enabled()) return;
69
- probe.beginRun(readProbeToken());
72
+ pi.on('before_agent_start', (event, ctx) => {
73
+ if (!enabled() || !canPresent(ctx)) return;
74
+ const token = readProbeToken();
75
+ const pending = probe.isPending || probe.isCurrentRun;
76
+ const claimed = probe.beginRun(token, event.messageType);
77
+ skipCurrentCapture = !claimed && (pending || probe.ownsAttemptToken(token));
78
+ if (skipCurrentCapture) return;
70
79
  // The chained prompt here already carries additions from extensions loaded
71
80
  // earlier; anything the context event adds came from extensions after us.
72
81
  capture.prepare(event.systemPromptOptions, event.systemPrompt);
@@ -79,12 +88,20 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
79
88
  });
80
89
  pi.on('message_end', event => {
81
90
  if (!enabled()) return;
91
+ if (event.message.role === 'assistant') probe.recordMessage(event.message);
82
92
  const message = probe.sanitizeMessage(event.message);
83
93
  return message === undefined ? undefined : { message };
84
94
  });
85
- pi.on('context', (event, ctx) => {
95
+ pi.on('context', event => {
86
96
  if (!enabled()) return;
87
97
  const messages = probe.filterMessages(event.messages);
98
+ return messages === event.messages ? undefined : { messages };
99
+ });
100
+ pi.on('context_with_system', (event, ctx) => {
101
+ if (!enabled() || !canPresent(ctx) || skipCurrentCapture) return;
102
+ const filtered = probe.filterMessages(event.messages);
103
+ // Pi's leading complete prompt is already counted by analyzeSystemPrompt.
104
+ const messages = filtered[0]?.role === 'system' ? filtered.slice(1) : filtered;
88
105
  capture.finalize(() => ({
89
106
  systemPrompt: ctx.getSystemPrompt(),
90
107
  messages,
@@ -94,7 +111,6 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
94
111
  promptSources: collectPromptSources(pi.getAllTools(), pi.getCommands()),
95
112
  origin: probe.isCurrentRun ? 'synthetic-probe' : 'real-turn',
96
113
  }));
97
- return messages === event.messages ? undefined : { messages };
98
114
  });
99
115
  pi.on('agent_settled', (_event, ctx) => {
100
116
  if (!enabled() || !probe.isCurrentRun) return;
@@ -122,7 +138,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
122
138
  ctx.ui.notify('/context-view accepts no arguments.', 'error');
123
139
  return;
124
140
  }
125
- if (ctx.mode !== 'tui') {
141
+ if (!canPresent(ctx)) {
126
142
  ctx.ui.notify('/context-view requires TUI mode.', 'warning');
127
143
  return;
128
144
  }
@@ -131,7 +147,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
131
147
  });
132
148
 
133
149
  pi.events.on(PI_VIM_KEY_EVENT_ID, () => {
134
- if (!enabled() || latestCtx.mode !== 'tui') return;
150
+ if (!enabled() || !canPresent(latestCtx)) return;
135
151
  void openContextView(latestCtx).catch(error => {
136
152
  latestCtx.ui.notify(`Failed to open Context View: ${error instanceof Error ? error.message : String(error)}`, 'error');
137
153
  });
@@ -107,6 +107,7 @@ export interface ToolSlice {
107
107
  guidelines: string[];
108
108
  /** Provenance, e.g. "builtin" or "npm:pi-web-providers". */
109
109
  source: string;
110
+ path?: string;
110
111
  }
111
112
 
112
113
  /**
@@ -392,7 +393,7 @@ function measureTools(
392
393
  }
393
394
  const owner: InjectedOwner = {
394
395
  itemId: `tool:${tool.source}:${tool.name}`,
395
- source: extensionSource(tool.source),
396
+ source: extensionSource(tool.source, tool.path),
396
397
  tool: tool.name,
397
398
  };
398
399
  collectDroppedReferences(dropped, droppedLines, owner);
@@ -21,10 +21,21 @@ export const AGGREGATE_SOURCE: InjectionSource = {
21
21
  };
22
22
 
23
23
  /** Injection source for one non-builtin provenance string, e.g. `npm:pi-web-providers`. */
24
- export function extensionSource(source: string): InjectionSource {
24
+ export function extensionSource(source: string, path?: string): InjectionSource {
25
+ if (path && /^(local|auto|cli)$/.test(source)) {
26
+ return { id: `tool-source:${source}:${path}`, label: sourcePathParts(path).join('/'), native: false, path };
27
+ }
25
28
  return { id: `tool-source:${source}`, label: source, native: false };
26
29
  }
27
30
 
31
+ function sourcePathParts(path: string): string[] {
32
+ return path
33
+ .replaceAll('\\', '/')
34
+ .replace(/\/index\.(ts|js)$/, '')
35
+ .split('/')
36
+ .filter(Boolean);
37
+ }
38
+
28
39
  /** Shared name of pi's own prompt; Usage and Injections must present it identically. */
29
40
  export const SYSTEM_PROMPT_LABEL = 'System Prompt';
30
41
 
@@ -54,6 +65,8 @@ export interface InjectionSource {
54
65
  readonly label: string;
55
66
  /** True for pi-native components. */
56
67
  readonly native: boolean;
68
+ /** Only path-loaded extensions participate in per-snapshot suffix labels. */
69
+ readonly path?: string;
57
70
  }
58
71
 
59
72
  /** Half-open `[start, end)` character range within captured text. */
@@ -238,8 +251,36 @@ export interface ContextUsageSnapshot {
238
251
  */
239
252
  export function groupInjections(items: readonly InjectionItem[]): InjectionGroup[] {
240
253
  const groups = new Map<string, MutableGroup>();
241
- for (const input of items) {
242
- const item = copyItem(input);
254
+ const owned = items.map(copyItem);
255
+ const sources = new Map<string, InjectionSource>();
256
+ const visit = (item: InjectionItem, apply: (source: InjectionSource) => InjectionSource): InjectionItem => ({
257
+ ...item,
258
+ source: apply(item.source),
259
+ injectedReferences: item.injectedReferences?.map(ref => ({ ...ref, source: apply(ref.source) })),
260
+ sections: item.sections?.map(section => ({
261
+ ...section,
262
+ injectedReferences: section.injectedReferences?.map(ref => ({ ...ref, source: apply(ref.source) })),
263
+ })),
264
+ children: item.children?.map(child => visit(child, apply)),
265
+ });
266
+ for (const item of owned)
267
+ visit(item, source => {
268
+ sources.set(source.id, source);
269
+ return source;
270
+ });
271
+ const paths = [...new Set([...sources.values()].flatMap(source => (source.path ? [source.path] : [])))];
272
+ const labels = new Map(
273
+ paths.map(path => {
274
+ const parts = sourcePathParts(path);
275
+ for (let length = 1; length <= parts.length; length++) {
276
+ const suffix = parts.slice(-length).join('/');
277
+ if (paths.every(other => other === path || sourcePathParts(other).slice(-length).join('/') !== suffix)) return [path, suffix];
278
+ }
279
+ return [path, path];
280
+ }),
281
+ );
282
+ for (const input of owned) {
283
+ const item = visit(input, source => (source.path ? { ...source, label: labels.get(source.path) ?? source.label } : source));
243
284
  let group = groups.get(item.source.id);
244
285
  if (group === undefined) {
245
286
  group = { source: item.source, items: [], totalTokens: 0 };
@@ -0,0 +1,6 @@
1
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+
3
+ /** Context View only captures and probes where it can actually be displayed. */
4
+ export function canPresent(ctx: Pick<ExtensionContext, 'mode' | 'hasUI'>): boolean {
5
+ return ctx.mode === 'tui' && ctx.hasUI;
6
+ }
@@ -115,11 +115,13 @@ function guessOwner(text: string, sources: readonly PromptSourceSlice[]): Prompt
115
115
  (packageName !== undefined && containsPackage(normalized, packageName)) ||
116
116
  (/^(npm:|git:|https?:\/\/|ssh:\/\/)/.test(source.source) && containsPackage(normalized, source.source))
117
117
  )
118
- matches.add(source.source);
118
+ matches.add(extensionSource(source.source, source.path).id);
119
119
  }
120
120
  const [match] = matches;
121
121
  if (matches.size !== 1 || match === undefined) return { source: AGGREGATE_SOURCE };
122
- return { source: extensionSource(match), tool: guessTool(normalized, sources, match) };
122
+ const owner = sources.find(source => extensionSource(source.source, source.path).id === match);
123
+ if (!owner) return { source: AGGREGATE_SOURCE };
124
+ return { source: extensionSource(owner.source, owner.path), tool: guessTool(normalized, sources, match) };
123
125
  }
124
126
 
125
127
  /**
@@ -131,7 +133,7 @@ function guessOwner(text: string, sources: readonly PromptSourceSlice[]): Prompt
131
133
  function guessTool(text: string, sources: readonly PromptSourceSlice[], owner: string): string | undefined {
132
134
  const matches = new Set<string>();
133
135
  for (const source of sources) {
134
- if (source.source !== owner) continue;
136
+ if (extensionSource(source.source, source.path).id !== owner) continue;
135
137
  for (const name of source.names ?? []) {
136
138
  if (name.length >= MIN_NAME_LENGTH && containsName(text, name)) matches.add(name);
137
139
  }
@@ -2,96 +2,63 @@
2
2
 
3
3
  ## Responsibility
4
4
 
5
- This folder contains the TUI components for the Context View feature. It renders a half-height modal dialog, mounted inline by default or as a centered overlay, with two tabs: **Usage** and **Injections**. Usage visualizes the estimated context-window composition with a proportional map, a selectable category legend, and a chronological content preview per category. Injections lists the hierarchical Initial snapshot of prompt/tool/context-file/skills injections with a per-item text preview. The modules are pure UI helpers: they do not call the Pi API directly and only depend on the shared `model.ts` types and the `@earendil-works/pi-tui` / `@earendil-works/pi-coding-agent` theme interfaces.
6
-
7
- All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, preview layers, dismissal ordering, height bounding, and the help footer — is owned by the shared modal library (`src/libs/modal/`). This folder keeps only Context View content: the two tab strategies and their bespoke rendering.
8
-
9
- ## Component/Model Structure
10
-
11
- - `context-view-dialog.ts` — thin wrapper configuring a `ModalDialog` (presenter-resolved frame, Vim navigation scheme, half-height bound, degraded-reason notice) with the Usage and Injections tabs. Reads the host wheel step via `readWheelScrollLines(tui)` and threads it into both tabs so their wheel-aware preview layers match the transcript viewport (block streams still step one block per notch). Keeps the `Component`/`Focusable` surface and the `activeTab` accessor.
12
- - `usage-view.ts` — the Usage tab (`ModalTab`). Stateful class that renders the context map, category legend, and zoom; category previews are pushed as wheel-aware block layers. Uses `UsageMap`, `LegendRow`, `UsageMapScale`, `ListNavigator`, `RenderCache`, and `previewBodyLines`/`previewLegendLines` from the section preview.
13
- - `injections-view.ts` — the Injections tab (`ModalTab`). Stateful class that renders the hierarchical list of Initial snapshot rows, dropped/moved row markers, and the marker legend; item previews are pushed as wheel-aware layers. Uses `InjectionRow`, `previewBodyLines`/`previewLegendLines`, and the modal library's `ListNavigator`/`RenderCache`.
14
- - `injections-model.ts` — pure presentation model for injections: flattens `InitialSnapshot` into `InjectionRow[]` (carrying dropped/moved state), maps items by id. Terminal sanitizers are re-exported from `../text`. (`ListNavigator`/`PreviewScroller` live in the modal library.)
15
- - `section-preview.ts` — section-aware preview rendering: `previewBodyLines` renders labeled parts with token subheaders, dropped/moved markers, repeated-heading trimming, and restored injected references; `previewLegendLines` collapses one fixed marker legend to the rows a frame can spare.
16
- - `markers.ts` — fixed-color state markers (`droppedMarker`, `movedMarker`, `guessMarker`) and the ordered, deduplicated bullet legend (`markerLegendLines`).
17
- - `json-preview.ts` — preview-only JSON run expansion (`expandJsonSpan`) and span re-anchoring (`shiftJsonSpan`).
18
- - `wheel.ts` — SGR/X10 mouse-wheel report parsing (`parseWheelDirection`) and the defensive TUI step read (`readWheelScrollLines`).
19
- - `wheel-preview-layer.ts` — preview layer mirroring the shared frame while accepting wheel notches; honors the host wheel step passed by the dialog.
20
- - `usage-block-layer.ts` — selectable chronological Usage block stream with per-block caps and wheel stepping.
21
- - `usage-preview.ts` — pure block geometry and `BlockNavigator` selection/scroll state for the Usage preview.
22
- - `usage-map.ts` — pure map model: `UsageMap` and `UsageMapCell` plus `buildUsageMap` / `calculateFitMapScale` for the 14×14 proportional grid.
23
- - `skill-preview.ts` — pure text splitter: `splitSkillPreview` recognizes complete `<skill name="...">...</skill>` wrappers and emits `SkillPreviewSegment[]`.
24
-
25
- ## Design Patterns
26
-
27
- - **Shell + tab strategy**: `ContextViewDialog` is a `ModalDialog` configuration; the views implement `ModalTab` (`label`, `render(width, height)`, `handleInput`, `handleNavigation`, `hints`, `attach`, `invalidate`) and never touch framing, tab cycling, or dismissal.
28
- - **Per-tab preview layers**: Enter pushes a layer onto the tab's shell-managed layer stack via `ModalTabContext.pushLayer`. Esc pops the layer before closing the dialog; tab switching works with layers open and each tab keeps its own stack. Context View layers are wheel-aware (`wheel-preview-layer.ts`, `usage-block-layer.ts`), unlike the shared scroll-only `PreviewLayer`.
29
- - **Stateful retained tabs**: the dialog constructs both tabs once; each preserves selection, scroll, zoom, and layer state across switches; `invalidate()` clears caches when the theme changes.
30
- - **Render caching**: both views cache rendered lines via the modal library's `RenderCache`, keyed by `width` and content `height`; the cache clears on selection, navigation, or zoom changes.
31
- - **Pure model + view split**: `injections-model.ts`, `usage-map.ts`, `usage-preview.ts`, `markers.ts`, `json-preview.ts`, `wheel.ts`, and `skill-preview.ts` contain no Pi or TUI access and are unit-testable; the views own only rendering logic.
32
- - **Semantic navigation**: the dialog's `VimNavigationScheme` maps keys to `NavigationAction`s (`step-*`, `page-*`, `first`, `last`, `confirm`, `dismiss`); tabs receive actions via `handleNavigation` and only raw, unmapped keys (Usage's `z` zoom, wheel reports) via `handleInput`.
33
-
34
- ## Rendering/Input/Data Flow
35
-
36
- 1. Opening: `index.ts` calls `prepareContextViewData`, then `presentModal(...)` creates a `ContextViewDialog` with `usage`, `initial`, optional `degradedReason`, and the frame resolved from `context_view.layout`.
37
- 2. The presenter configures mounting and frame from `context_view.layout`; the dialog configures `ModalDialog` with `height: 'half'`, `VimNavigationScheme`, the degraded reason as a warning notice, and both tabs.
38
- 3. On each render cycle the shell renders the frame, tab strip, notices, the active tab's content region (exact bounded height), and the help footer composed of scheme hints, active tab/layer hints, and universal hints.
39
- 4. Input: the shell handles `Tab`/`Shift+Tab` cycling first, then the Vim scheme. `dismiss` pops the active tab's top layer or closes the dialog; other actions go to the top layer, else the active tab; unmapped raw keys go to the layer or tab.
40
- 5. Tabs handle list navigation, preview opening (confirm action), and view-local keys. After handling, `tui.requestRender()` is called by the shell.
41
- 6. Data stays process-local: raw text used in previews comes from `InjectionItem.text` and `UsagePreviewEntry.text`, both declared as never-logged / never-persisted in `model.ts`.
42
-
43
- ## Usage Tab Behavior
44
-
45
- - `UsageView` receives a `ContextUsageSnapshot`.
46
- - **Dashboard**: renders a header, a 14×14 proportional map, a selectable category legend, and a description within the shell-provided content height. At narrow widths the map is hidden; at ≥52 columns it appears beside the legend; at ≥72 columns cells are spaced.
47
- - **Map cells**: `full` (■), `partial` (◧), `compacted-data` (▦), `buffer` (⛝), `free` (⛶). Compacted data uses its own glyph; all other categories use full/partial based on overlap.
48
- - **Legend**: top-level categories plus one level of children under `tool-output` (per-tool breakdown). Buffer and free rows are shown when applicable but are not selectable.
49
- - **Zoom**: pressing `z` toggles `UsageMapScale` between `window` and `fit`. Fit adds 15% headroom, rounded up to two significant digits, capped by the context window and floored at 10,000 tokens. Zoom only works when the active width supports the side-by-side map and the fit scale is smaller than the window. The `Z Zoom` hint appears only when active.
50
- - **Summary header**: shows model label, reported tokens / context window, and reported percentage. When provider tokens are unknown, it shows estimated tokens and a computed percentage.
51
- - **Preview**: Enter on a category pushes a wheel-aware block stream (`UsageBlockLayer`) of chronological `UsagePreviewEntry` blocks. Body content is section-aware (`previewBodyLines`): labeled parts carry token subheaders, dropped/moved markers, repeated-heading trimming, restored injected references with their source/tool/guess attribution, and expanded JSON runs. Entry headers bold the lead breadcrumb cell. Headers show `[DD-MM-YYYY HH:MM:SS]`, breadcrumbs, visible tokens, and optional invisible-reasoning metadata (`≈` provider-reported, `~` signature proxy, `Encoded` when a replay signature is present). A fixed description about reasoning markers is shown only for `agent-thinking-messages` categories that contain invisible reasoning; other categories show the collapsed marker legend. The full-content layer expands JSON too, accepts wheel notches at the host step, and repeats the same marker legend when its body leaves room.
52
- - **Hints**: the shell footer shows scheme movement keys (`↑↓/jk` Navigate, `Ctrl+u/d` Page, `gg/G` Bounds), tab hints (`Enter` Preview, `Z` Zoom when active), and universal hints (`Tab` Switch, `Esc` Close/`Back`).
53
-
54
- ## Injections Tab Behavior
55
-
56
- - `InjectionsView` receives an `InitialSnapshot`.
57
- - **List**: `injections-model.ts` flattens snapshot groups into `InjectionRow` of kind `group`, `item` (depth 1 or 2), `separator`, and `total`. Groups are source-level rows; depth-2 items are child constituents (e.g. individual built-in tools or skills). Only item rows are selectable and previewable.
58
- - **Tree rendering**: items render with `├─ ` / `└─ ` prefixes and ancestor `│ ` continuation markers.
59
- - **Value column**: the token-value column is aligned across the whole list based on the widest visible label and the widest token value.
60
- - **Header**: shows `Context Injections · [INITIAL]`; a Runtime label is reserved for future work but currently hidden.
61
- - **Degraded indicator**: when a degraded reason is present, the shell renders it as a warning notice below the tab strip (unified with the Usage tab).
62
- - **Preview**: Enter on an item pushes a wheel-aware layer showing the item label, source, and token count; the body is section-aware (`previewBodyLines`) and wrapped with `BODY_INDENT`, expanding marked JSON runs and restoring attributed references, with the collapsed marker legend below. Rows carrying dropped/moved content show a state marker after their estimate, and the list description explains exactly those markers.
63
- - **Hints**: same shell-composed footer as Usage.
64
-
65
- ## Skill Preview Behavior
66
-
67
- - `usage-view.ts` compacts skill wrappers in user-messages preview content by setting `compactSkills = true` for `user-messages` category entries.
68
- - `skill-preview.ts` splits text on line-delimited `<skill name="...">` and `</skill>` tags. Only complete wrappers (matching opening and closing on the same boundary, with no other skill opening tag between them) are emitted as `SkillPreviewSegment` of type `skill`. Malformed or unclosed wrappers remain as `text` segments.
69
- - `UsageView.skillBadge` renders a skill segment as a colored badge: `[skill]` in `customMessageLabel` and the name in `customMessageText`. This matches the colors used by Pi's transcript component for skill attachments.
70
- - Non-user-messages categories keep skills inline as raw text (no compact badges).
71
-
72
- ## Integration Points
73
-
74
- - **Entry**: `index.ts` calls `openContextView`, which uses the shared `presentModal` helper to instantiate and mount `ContextViewDialog` in the configured layout.
75
- - **Modal library**: `src/libs/modal/` supplies `ModalDialog`, `VimNavigationScheme`, `ModalTab`/`ModalTabContext` contracts, `ListNavigator`, `PreviewScroller`, `PreviewLayer`, `RenderCache`, and layout/text helpers (`BODY_INDENT`, `calculateViewport`, `fitLine`, `spreadLine`, `wrapDescriptionLines`). The Context View adds wheel-aware layers in this folder rather than editing the shared library.
76
- - **Sanitizers**: `normalizePreviewText`/`normalizeInlineText` live in `../text`; `injections-model.ts` re-exports them for callers that import them there.
77
- - **Data contract**: `ContextViewData` from `context-view-controller.ts` supplies `{ initial, usage, degradedReason }`; the dialog maps `degradedReason` to the shell notices slot.
78
- - **Usage data source**: `usage.ts` produces `ContextUsageSnapshot` via `computeUsage`, which merges the frozen `InitialSnapshot` with live session messages and reported provider usage. `usage.ts` also provides `collectPreviewEntries`, which `UsageView` uses to flatten a category's chronological entries.
79
- - **Theme**: views receive a `Theme` from the Pi TUI and use semantic colors (`accent`, `muted`, `dim`, `text`, `warning`, `mdHeading`, `mdLink`, `mdCodeBlock`, `syntaxString`, `syntaxFunction`, `syntaxKeyword`, `syntaxType`, `thinkingHigh`, `thinkingXhigh`, `toolOutput`, `customMessageLabel`, `customMessageText`, `border`).
80
- - **Height contract**: the shell bounds the dialog to half the terminal height and hands each tab an exact content height to fill.
81
- - **Process-local content**: preview text and injection text are not sanitized for persistence (control sequences are stripped for terminal display only). This matches the parent `model.ts` constraint that raw content must never be logged or serialized.
82
-
83
- ## Files
84
-
85
- - `context-view-dialog.ts`: `ModalDialog` configuration (Vim scheme, half-height, notices) and the `activeTab` accessor.
86
- - `usage-view.ts`: Usage tab — dashboard, map, legend, zoom, category preview layers, reasoning description, marker legend.
87
- - `injections-view.ts`: Injections tab — hierarchy list with state markers, marker legend, item preview layer.
88
- - `injections-model.ts`: row flattening (dropped/moved aware), item indexing; sanitizer re-exports.
89
- - `section-preview.ts`: section-aware preview bodies and marker legends.
90
- - `markers.ts`: state markers and ordered legend bullets.
91
- - `json-preview.ts`: JSON run expansion and span shifting.
92
- - `wheel.ts`: wheel-report parsing and TUI step read.
93
- - `wheel-preview-layer.ts`: wheel-aware preview layer.
94
- - `usage-block-layer.ts`: chronological Usage block stream with caps and wheel stepping.
95
- - `usage-preview.ts`: block geometry and navigation state.
96
- - `usage-map.ts`: 14×14 proportional grid and Fit-scale calculation.
97
- - `skill-preview.ts`: skill wrapper splitting for compact badge rendering.
5
+ Context View's retained Usage and Injections tabs and their preview layers. The shared modal library owns framing, tab/layer stacks, Vim navigation, raw input capture, normalized mouse forwarding, notices, and half-terminal-height bounding. The presenter selects inline (default) or centered overlay layout. Raw captured content stays process-local and is never logged or persisted; only display strings are terminal-sanitized.
6
+
7
+ ## Module Roles
8
+
9
+ - `context-view-dialog.ts` — configures `ModalDialog` with Usage first, both retained tabs, Vim navigation, half-height bound, and the degraded-capture warning. Wires clipboard services to shell notices and forwards `handleMouse` to the shell.
10
+ - `usage-view.ts` — context summary, proportional map, selectable category legend, map zoom (`z`), percentage basis (`p`), category copy (`y`), and chronological category previews.
11
+ - `injections-view.ts` — hierarchical Initial snapshot, dropped/moved markers, Name/Content filter, item/group copy, and injection previews. Uses an exact padded content height; prompt/status, legend, and scroll rows are budgeted rather than appended conditionally.
12
+ - `injections-model.ts` — pure hierarchy flattening, item indexing, and `filterInjections`. Name matches retain their subtree; Content matches preview text including expanded JSON; ancestors of matches survive. Terminal sanitizers are re-exported from `../text`.
13
+ - `searchable-preview.ts` — scroll-only injection and complete-content layer with captured search editing, match count, current-match navigation, raw-content copy, and wheel handling. Reserves search/scroll rows to keep height stable; width changes recompute matches on rewrapped lines while preserving the current index where possible.
14
+ - `search.ts` — literal case-insensitive matching and match ranges. Query whitespace is collapsed/trimmed and regex syntax escaped; content filtering also collapses target whitespace.
15
+ - `highlight.ts` — ANSI-safe highlighting at visible-column offsets, with a distinct current-match style.
16
+ - `copy.ts` — `copyText`/`copyWithNotice` use Pi's clipboard helper (injectable for tests), normalize CRLF, trim leading newlines/trailing whitespace, and report success (3 seconds), empty content, or failure (5 seconds) through the shell footer notice.
17
+ - `usage-block-layer.ts` — selectable chronological blocks with height-dependent excerpt caps, `y` full-block copy, and Enter to open complete content only when truncated. `/` is deliberately unbound here.
18
+ - `usage-preview.ts` — pure block geometry and `BlockNavigator` selection/scroll state.
19
+ - `usage-map.ts` — pure 14×14 proportional map and fit-scale computation.
20
+ - `section-preview.ts` — section-aware body rendering and collapsed marker legends: token subheaders, repeated-heading trimming, dropped/moved markers, and restored attributed references.
21
+ - `json-preview.ts` — preview-only JSON expansion and span re-anchoring.
22
+ - `markers.ts` — fixed-color dropped/moved/guess markers and deduplicated legend.
23
+ - `skill-preview.ts` — recognizes complete line-delimited skill wrappers; malformed wrappers remain text. Usage user-message previews compact wrappers to Pi-colored skill badges; other categories preserve inline text.
24
+
25
+ `wheel.ts` (SGR/X10 parsing and host step lookup) and `wheel-preview-layer.ts` were removed. Wheel input now arrives through `handleMouse(event)` on Usage, Injections, block streams, and searchable previews. Only `type === 'wheel'` is handled; `wheelDelta` already includes host scroll step/acceleration and is not rescaled. Lists move selection, streams step blocks, and previews scroll lines, returning `{ handled: true }`; other mouse events return `undefined`.
26
+
27
+ ## Input and Layer Flow
28
+
29
+ 1. `prepareContextViewData` supplies `{ initial, usage, degradedReason }`; `presentModal` mounts the dialog in the configured layout.
30
+ 2. The shell renders frame, tab strip, persistent notices, an exact-height content region, and footer hints (or a transient copy notice).
31
+ 3. If the top layer, otherwise active tab, reports `capturesInput()`, raw input bypasses tab cycling and Vim mapping, and its editing hints replace normal hints.
32
+ 4. Otherwise Tab/Shift+Tab cycles tabs, the Vim scheme maps `j/k`, arrows, `Ctrl+u/d`, `gg/G`, Enter and Esc/`q`, and unmapped keys reach the target. Dismiss pops a layer before closing. Each tab retains selection, scroll, and its layer stack across switches.
33
+ 5. Mouse events are forwarded to the same target's optional `handleMouse` by the shell. Views do not parse terminal mouse escape sequences.
34
+
35
+ ## Injections Behavior
36
+
37
+ - `[INITIAL]` is the only phase shown; Runtime remains hidden. Rows are source groups, nested items, separators, and a non-selectable total. Group rows can be selected for copy; only items open previews.
38
+ - Tree glyphs and a shared token-value column preserve alignment. Dropped/moved rows carry markers and a matching legend.
39
+ - `/` enters filter editing. Tab/Shift+Tab toggles Name/Content mode, Enter confirms, and Esc clears while editing. Outside editing Esc is shell dismissal; use `/` then Esc to clear an applied filter. Refresh selects the first visible row, or clears selection for no matches.
40
+ - Editing/applied filters reserve one prompt/status row within the fixed list viewport; short/no-match lists are padded.
41
+ - Enter opens `SearchablePreview` with sectioned text, JSON expansion, restored prompt references, and the marker legend.
42
+ - `y` copies a selected item's raw text or a group's filter-visible content, joined with blank lines. Pruned aggregate subtrees are reconstructed so hidden siblings do not leak into group copy.
43
+
44
+ ## Usage Behavior
45
+
46
+ - Summary shows reported tokens/window and percentage, or estimates when provider tokens are unknown. The summary percentage always uses the window.
47
+ - The 14×14 map is hidden below 52 columns, side-by-side at 52+, and spaced at 72+. Cells represent full/partial occupancy, compacted data, buffer, and free space. Tool Output includes one level of child categories.
48
+ - `z` toggles window/fit map scale only when supported by the width and a smaller fit scale exists. Fit uses 15% headroom, rounded to two significant digits, capped by the window and floored at 10,000 tokens.
49
+ - `p` independently toggles legend percentages between `window` (default per dialog, reported context-window denominator) and `used` (`estimatedTokens`, the sum of estimated categories). It is enabled when either denominator is positive. Used mode shows percentages only for category rows, not buffer/free; the heading names the basis.
50
+ - Enter on a category opens chronological `UsageBlockLayer` entries, with section-aware excerpts, timestamps, breadcrumbs, token counts, and optional invisible-reasoning metadata. Truncated blocks open a complete-content `SearchablePreview`; that layer expands JSON and retains marker descriptions.
51
+ - `y` copies a category's complete entries in chronological order or the selected block's full raw text. Buffer/free have no copy payload.
52
+
53
+ ## Preview Search and Clipboard
54
+
55
+ - `/` edits search in injection and complete-content previews. Search runs on rendered lines with ANSI stripped, not across wraps. Enter confirms; `n`/`N` moves next/previous with wrap-around after confirmation. Esc clears while editing; otherwise it goes back. Typing reveals the first match at/after the current top line, wrapping to the first if needed.
56
+ - Highlights preserve existing ANSI styles; a reserved status row shows current/total or “no matches”.
57
+ - `y` copies the preview's entire raw content, never highlighted/rendered lines. Clipboard support depends on Pi's terminal/host facility; empty content and failures display a notice instead of throwing from the view.
58
+
59
+ ## Integration and Constraints
60
+
61
+ - Models: `../model.ts` supplies `InitialSnapshot`, `InjectionItem`, `ContextUsageSnapshot`, and `UsagePreviewEntry`; `../usage.ts` supplies chronological `collectPreviewEntries`.
62
+ - Shared modal: `ModalDialog`, `ModalTab`/`ModalLayer` input capture and mouse contracts, `ListNavigator`, `PreviewScroller`, `RenderCache`, layout helpers, and Vim scheme. Cached tab renders clear on navigation, filtering, percentage/zoom changes, or invalidation.
63
+ - Theme/host: Pi theme colors and pi-tui input, wrapping, width, and normalized mouse types. Clipboard access is isolated in `copy.ts`; the other UI modules do not invoke extension lifecycle APIs.
64
+ - Raw preview and injection text must not be logged or serialized. Terminal sanitization is for display only; clipboard targets use captured text with copy normalization.
@@ -1,10 +1,10 @@
1
1
  import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
- import type { Component, Focusable, TUI } from '@earendil-works/pi-tui';
2
+ import type { Component, Focusable, TUI, TuiMouseEvent, TuiMouseEventResult } from '@earendil-works/pi-tui';
3
3
  import { ModalDialog, type ModalFrame, VimNavigationScheme } from '../../../libs/modal';
4
4
  import type { ContextUsageSnapshot, InitialSnapshot } from '../model';
5
+ import type { Clipboard, CopyServices } from './copy';
5
6
  import { InjectionsView } from './injections-view';
6
7
  import { UsageView } from './usage-view';
7
- import { readWheelScrollLines } from './wheel';
8
8
 
9
9
  export type ContextViewTab = 'usage' | 'injections';
10
10
 
@@ -30,13 +30,16 @@ export class ContextViewDialog implements Component, Focusable {
30
30
  input: ContextViewDialogInput,
31
31
  done: (result: undefined) => void,
32
32
  frame: ModalFrame = 'inline',
33
+ clipboard?: Clipboard,
33
34
  ) {
34
- const wheelScrollLines = readWheelScrollLines(tui);
35
+ // Views report copy results through the dialog's footer notice; the
36
+ // dialog is assigned below, before any view can handle input.
37
+ const copy: CopyServices = {
38
+ notices: { showNotice: (text, tone, ttlMs) => this.dialog.showNotice(text, tone, ttlMs) },
39
+ clipboard,
40
+ };
35
41
  this.dialog = new ModalDialog<undefined>(tui, theme, keybindings, {
36
- tabs: [
37
- new UsageView(theme, { usage: input.usage }, wheelScrollLines),
38
- new InjectionsView(theme, { snapshot: input.initial }, wheelScrollLines),
39
- ],
42
+ tabs: [new UsageView(theme, { usage: input.usage }, copy), new InjectionsView(theme, { snapshot: input.initial }, copy)],
40
43
  navigation: new VimNavigationScheme(),
41
44
  frame,
42
45
  height: 'half',
@@ -66,6 +69,10 @@ export class ContextViewDialog implements Component, Focusable {
66
69
  this.dialog.handleInput(data);
67
70
  }
68
71
 
72
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
73
+ return this.dialog.handleMouse(event);
74
+ }
75
+
69
76
  render(width: number): string[] {
70
77
  return this.dialog.render(width);
71
78
  }
@@ -0,0 +1,42 @@
1
+ import { copyToClipboard } from '@earendil-works/pi-coding-agent';
2
+ import type { ModalNoticeTone } from '../../../libs/modal/types';
3
+
4
+ export interface CopyNotice {
5
+ readonly text: string;
6
+ readonly tone: ModalNoticeTone;
7
+ readonly ttlMs: number;
8
+ }
9
+
10
+ export interface NoticeTarget {
11
+ showNotice(text: string, tone: ModalNoticeTone, ttlMs: number): void;
12
+ }
13
+
14
+ export type Clipboard = (text: string) => void | Promise<void>;
15
+
16
+ /** Copy wiring handed to Context View tabs and layers by the dialog. */
17
+ export interface CopyServices {
18
+ readonly notices: NoticeTarget;
19
+ readonly clipboard?: Clipboard;
20
+ }
21
+
22
+ /** Copy `text` and report the outcome through `services.notices`. */
23
+ export async function copyWithNotice(services: CopyServices, text: string): Promise<void> {
24
+ showCopyNotice(services.notices, await copyText(text, services.clipboard));
25
+ }
26
+
27
+ /** Copy raw captured content, never terminal-rendered lines. */
28
+ export async function copyText(text: string, clipboard: Clipboard = copyToClipboard): Promise<CopyNotice> {
29
+ const normalized = text.replace(/\r\n/g, '\n').replace(/^\n+/, '').trimEnd();
30
+ if (normalized === '') return { text: 'Nothing to copy', tone: 'warning', ttlMs: 5000 };
31
+ try {
32
+ await clipboard(normalized);
33
+ return { text: `Copied ${normalized.length.toLocaleString('en-US')} characters`, tone: 'success', ttlMs: 3000 };
34
+ } catch (error) {
35
+ return { text: `Copy failed: ${error instanceof Error ? error.message : String(error)}`, tone: 'error', ttlMs: 5000 };
36
+ }
37
+ }
38
+
39
+ /** Apply a completed copy result to a modal or a view's notice adapter. */
40
+ export function showCopyNotice(target: NoticeTarget, notice: CopyNotice): void {
41
+ target.showNotice(notice.text, notice.tone, notice.ttlMs);
42
+ }
@@ -0,0 +1,91 @@
1
+ import { visibleWidth } from '@earendil-works/pi-tui';
2
+ import type { MatchRange } from './search';
3
+
4
+ /** Column ranges, not UTF-16 offsets. End is exclusive. */
5
+ export interface HighlightRange extends MatchRange {
6
+ readonly current?: boolean;
7
+ }
8
+
9
+ export const MATCH_SGR = '\u001b[43;30m';
10
+ export const CURRENT_MATCH_SGR = '\u001b[45;97;1m';
11
+ const RESET = '\u001b[0m';
12
+ const segmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
13
+
14
+ /** Convert search's UTF-16 offsets on an ANSI-stripped line to terminal columns. */
15
+ export function matchColumns(text: string, range: MatchRange): MatchRange {
16
+ return { start: visibleWidth(text.slice(0, range.start)), end: visibleWidth(text.slice(0, range.end)) };
17
+ }
18
+
19
+ /**
20
+ * Insert highlights without losing surrounding SGR styles. Unknown escape or
21
+ * control sequences and ranges splitting a wide glyph fail closed: return the
22
+ * original line. Replaying prior SGRs restores even nested/reset color state.
23
+ */
24
+ export function highlightLine(line: string, ranges: readonly HighlightRange[], currentIndex = -1): string {
25
+ if (ranges.length === 0) return line;
26
+ const tokens: { text: string; column: number; width: number; sgr: boolean }[] = [];
27
+ let column = 0;
28
+ for (let offset = 0; offset < line.length; ) {
29
+ if (line[offset] === '\u001b') {
30
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: deliberately parse terminal SGR escapes.
31
+ const sgr = /^\u001b\[[0-9;:]*m/.exec(line.slice(offset))?.[0];
32
+ if (sgr === undefined) return line;
33
+ tokens.push({ text: sgr, column, width: 0, sgr: true });
34
+ offset += sgr.length;
35
+ } else {
36
+ const end = line.indexOf('\u001b', offset);
37
+ const plain = line.slice(offset, end === -1 ? line.length : end);
38
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: reject terminal controls before inserting highlights.
39
+ if (/[\u0000-\u001f\u007f-\u009f]/u.test(plain)) return line;
40
+ for (const { segment } of segmenter.segment(plain)) {
41
+ const width = visibleWidth(segment);
42
+ tokens.push({ text: segment, column, width, sgr: false });
43
+ column += width;
44
+ }
45
+ offset += plain.length;
46
+ }
47
+ }
48
+ const boundaries = new Set([0, column, ...tokens.filter(token => !token.sgr).map(token => token.column)]);
49
+ const sorted = ranges
50
+ .map((range, index) => ({ ...range, current: range.current === true || index === currentIndex }))
51
+ .sort((a, b) => a.start - b.start);
52
+ if (
53
+ sorted.some(
54
+ (range, index) =>
55
+ !Number.isInteger(range.start) ||
56
+ !Number.isInteger(range.end) ||
57
+ range.start < 0 ||
58
+ range.end <= range.start ||
59
+ !boundaries.has(range.start) ||
60
+ !boundaries.has(range.end) ||
61
+ (index > 0 && range.start < (sorted[index - 1]?.end ?? 0)),
62
+ )
63
+ )
64
+ return line;
65
+
66
+ let output = '';
67
+ let history = '';
68
+ let active: (typeof sorted)[number] | undefined;
69
+ let index = 0;
70
+ for (const token of tokens) {
71
+ if (active !== undefined && token.column >= active.end) {
72
+ output += RESET + history;
73
+ active = undefined;
74
+ index++;
75
+ }
76
+ if (token.sgr) {
77
+ history += token.text;
78
+ output += token.text;
79
+ if (active !== undefined) output += active.current ? CURRENT_MATCH_SGR : MATCH_SGR;
80
+ continue;
81
+ }
82
+ const next = sorted[index];
83
+ if (active === undefined && next !== undefined && token.column === next.start) {
84
+ active = next;
85
+ output += active.current ? CURRENT_MATCH_SGR : MATCH_SGR;
86
+ }
87
+ output += token.text;
88
+ }
89
+ if (active !== undefined) output += RESET + history;
90
+ return output;
91
+ }