@0xkahi/pi-qol 1.0.0 → 1.0.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.
@@ -0,0 +1,82 @@
1
+ # src/extensions/context-view/ui/
2
+
3
+ ## Responsibility
4
+
5
+ This folder contains the TUI components for the Context View feature. It renders an inline, half-height modal dialog 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` (Vim navigation scheme, half-height bound, degraded-reason notice) with the Usage and Injections tabs. 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 `PreviewLayer`s. Uses `UsageMap`, `LegendRow`, `UsageMapScale`, `ListNavigator`, and `RenderCache` from the modal library.
13
+ - `injections-view.ts` — the Injections tab (`ModalTab`). Stateful class that renders the hierarchical list of Initial snapshot rows; item previews are pushed as `PreviewLayer`s. Uses `InjectionRow` and the modal library's `ListNavigator`/`RenderCache`.
14
+ - `injections-model.ts` — pure presentation model for injections: flattens `InitialSnapshot` into `InjectionRow[]`, maps items by id, and normalizes preview text. (`ListNavigator`/`PreviewScroller` moved to the modal library.)
15
+ - `usage-map.ts` — pure map model: `UsageMap` and `UsageMapCell` plus `buildUsageMap` / `calculateFitMapScale` for the 14×14 proportional grid.
16
+ - `skill-preview.ts` — pure text splitter: `splitSkillPreview` recognizes complete `<skill name="...">...</skill>` wrappers and emits `SkillPreviewSegment[]`.
17
+
18
+ ## Design Patterns
19
+
20
+ - **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.
21
+ - **Per-tab preview layers**: Enter pushes a `PreviewLayer` 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.
22
+ - **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.
23
+ - **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.
24
+ - **Pure model + view split**: `injections-model.ts`, `usage-map.ts`, and `skill-preview.ts` contain no Pi or TUI access and are unit-testable; the views own only rendering logic.
25
+ - **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) via `handleInput`.
26
+
27
+ ## Rendering/Input/Data Flow
28
+
29
+ 1. Opening: `index.ts` calls `prepareContextViewData`, then `ctx.ui.custom(...)` to create a `ContextViewDialog` with `usage`, `initial`, and optional `degradedReason`.
30
+ 2. The dialog configures `ModalDialog` with `height: 'half'`, `VimNavigationScheme`, the degraded reason as a warning notice, and both tabs.
31
+ 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.
32
+ 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.
33
+ 5. Tabs handle list navigation, preview opening (confirm action), and view-local keys. After handling, `tui.requestRender()` is called by the shell.
34
+ 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`.
35
+
36
+ ## Usage Tab Behavior
37
+
38
+ - `UsageView` receives a `ContextUsageSnapshot`.
39
+ - **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.
40
+ - **Map cells**: `full` (■), `partial` (◧), `compacted-data` (▦), `buffer` (⛝), `free` (⛶). Compacted data uses its own glyph; all other categories use full/partial based on overlap.
41
+ - **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.
42
+ - **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.
43
+ - **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.
44
+ - **Preview**: Enter on a category pushes a `PreviewLayer` with a chronological list of `UsagePreviewEntry` lines. 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.
45
+ - **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`).
46
+
47
+ ## Injections Tab Behavior
48
+
49
+ - `InjectionsView` receives an `InitialSnapshot`.
50
+ - **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.
51
+ - **Tree rendering**: items render with `├─ ` / `└─ ` prefixes and ancestor `│ ` continuation markers.
52
+ - **Value column**: the token-value column is aligned across the whole list based on the widest visible label and the widest token value.
53
+ - **Header**: shows `Context Injections · [INITIAL]`; a Runtime label is reserved for future work but currently hidden.
54
+ - **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).
55
+ - **Preview**: Enter on an item pushes a `PreviewLayer` showing the item label, source, and token count; the body is wrapped and indented with `BODY_INDENT`.
56
+ - **Hints**: same shell-composed footer as Usage.
57
+
58
+ ## Skill Preview Behavior
59
+
60
+ - `usage-view.ts` compacts skill wrappers in user-messages preview content by setting `compactSkills = true` for `user-messages` category entries.
61
+ - `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.
62
+ - `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.
63
+ - Non-user-messages categories keep skills inline as raw text (no compact badges).
64
+
65
+ ## Integration Points
66
+
67
+ - **Entry**: `index.ts` calls `openContextView`, which uses `ctx.ui.custom<void>` to instantiate `ContextViewDialog`. This attaches the dialog to the Pi TUI.
68
+ - **Modal library**: `src/libs/modal/` supplies `ModalDialog`, `VimNavigationScheme`, `ModalTab`/`ModalTabContext` contracts, `ListNavigator`, `PreviewLayer`, `RenderCache`, and layout/text helpers (`BODY_INDENT`, `calculateViewport`, `fitLine`, `spreadLine`, `wrapDescriptionLines`).
69
+ - **Data contract**: `ContextViewData` from `context-view-controller.ts` supplies `{ initial, usage, degradedReason }`; the dialog maps `degradedReason` to the shell notices slot.
70
+ - **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.
71
+ - **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`).
72
+ - **Height contract**: the shell bounds the dialog to half the terminal height and hands each tab an exact content height to fill.
73
+ - **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.
74
+
75
+ ## Files
76
+
77
+ - `context-view-dialog.ts`: `ModalDialog` configuration (Vim scheme, half-height, notices) and the `activeTab` accessor.
78
+ - `usage-view.ts`: Usage tab — dashboard, map, legend, zoom, category preview layer, reasoning description.
79
+ - `injections-view.ts`: Injections tab — hierarchy list, item preview layer.
80
+ - `injections-model.ts`: row flattening, item indexing, text normalization.
81
+ - `usage-map.ts`: 14×14 proportional grid and Fit-scale calculation.
82
+ - `skill-preview.ts`: skill wrapper splitting for compact badge rendering.
@@ -1,81 +1,59 @@
1
1
  import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
2
- import { type Component, type Focusable, Key, matchesKey, type TUI, truncateToWidth } from '@earendil-works/pi-tui';
2
+ import type { Component, Focusable, TUI } from '@earendil-works/pi-tui';
3
+ import { ModalDialog, VimNavigationScheme } from '../../../libs/modal';
3
4
  import type { ContextUsageSnapshot, InitialSnapshot } from '../model';
4
5
  import { InjectionsView } from './injections-view';
5
- import { VimNavigation } from './navigation';
6
6
  import { UsageView } from './usage-view';
7
7
 
8
8
  export type ContextViewTab = 'usage' | 'injections';
9
9
 
10
- /** One half-height Context View shell that retains both child-tab states. */
10
+ export interface ContextViewDialogInput {
11
+ usage: ContextUsageSnapshot;
12
+ initial: InitialSnapshot;
13
+ degradedReason?: string;
14
+ }
15
+
16
+ /**
17
+ * Bounded half-height Context View shell: a `ModalDialog` configured with
18
+ * Vim navigation, the Usage and Injections tabs, and the degraded-capture
19
+ * notice. Both tab instances are retained so each preserves its scroll,
20
+ * selection, zoom, and preview-layer state across tab switches.
21
+ */
11
22
  export class ContextViewDialog implements Component, Focusable {
12
- private readonly usage: UsageView;
13
- private readonly injections: InjectionsView;
14
- private readonly navigation = new VimNavigation();
15
- private active: ContextViewTab = 'usage';
16
- private _focused = false;
23
+ private readonly dialog: ModalDialog<undefined>;
17
24
 
18
- constructor(
19
- private readonly tui: TUI,
20
- private readonly theme: Theme,
21
- _keybindings: KeybindingsManager,
22
- input: { usage: ContextUsageSnapshot; initial: InitialSnapshot; degradedReason?: string },
23
- done: (result: undefined) => void,
24
- ) {
25
- const getRows = () => Math.max(1, Math.floor(tui.terminal.rows / 2) - 1);
26
- this.usage = new UsageView(this.theme, { usage: input.usage, degradedReason: input.degradedReason }, done, getRows);
27
- this.injections = new InjectionsView(this.theme, { snapshot: input.initial, degradedReason: input.degradedReason }, done, getRows);
25
+ constructor(tui: TUI, theme: Theme, keybindings: KeybindingsManager, input: ContextViewDialogInput, done: (result: undefined) => void) {
26
+ this.dialog = new ModalDialog<undefined>(tui, theme, keybindings, {
27
+ tabs: [new UsageView(theme, { usage: input.usage }), new InjectionsView(theme, { snapshot: input.initial })],
28
+ navigation: new VimNavigationScheme(),
29
+ height: 'half',
30
+ notices: input.degradedReason === undefined ? [] : [input.degradedReason],
31
+ cancelValue: undefined,
32
+ onComplete: done,
33
+ });
28
34
  }
29
35
 
30
36
  get focused(): boolean {
31
- return this._focused;
37
+ return this.dialog.focused;
32
38
  }
33
39
 
34
- get activeTab(): ContextViewTab {
35
- return this.active;
40
+ set focused(value: boolean) {
41
+ this.dialog.focused = value;
36
42
  }
37
43
 
38
- set focused(value: boolean) {
39
- this._focused = value;
44
+ get activeTab(): ContextViewTab {
45
+ return this.dialog.activeIndex === 0 ? 'usage' : 'injections';
40
46
  }
41
47
 
42
48
  invalidate(): void {
43
- this.usage.invalidate();
44
- this.injections.invalidate();
49
+ this.dialog.invalidate();
45
50
  }
46
51
 
47
52
  handleInput(data: string): void {
48
- if (matchesKey(data, Key.tab)) {
49
- this.switchTab(1);
50
- } else if (matchesKey(data, Key.shift('tab'))) {
51
- this.switchTab(-1);
52
- } else {
53
- const navigation = this.navigation.consume(data);
54
- if (navigation.action) this.child().handleNavigation(navigation.action);
55
- else if (!navigation.handled) this.child().handleInput(data);
56
- }
57
- this.tui.requestRender();
53
+ this.dialog.handleInput(data);
58
54
  }
59
55
 
60
56
  render(width: number): string[] {
61
- const lines = this.child().render(width);
62
- const tabLine = this.renderTabs(width);
63
- return lines.length === 0 ? [tabLine] : [lines[0] ?? '', tabLine, ...lines.slice(1)];
64
- }
65
-
66
- private switchTab(_direction: -1 | 1): void {
67
- this.active = this.active === 'usage' ? 'injections' : 'usage';
68
- this.navigation.reset();
69
- }
70
-
71
- private renderTabs(width: number): string {
72
- const usage = this.active === 'usage' ? this.theme.fg('accent', this.theme.bold('[Usage]')) : this.theme.fg('muted', '[Usage]');
73
- const injections =
74
- this.active === 'injections' ? this.theme.fg('accent', this.theme.bold('[Injections]')) : this.theme.fg('muted', '[Injections]');
75
- return truncateToWidth(` ${usage} ${injections}`, Math.max(1, width), '');
76
- }
77
-
78
- private child(): UsageView | InjectionsView {
79
- return this.active === 'usage' ? this.usage : this.injections;
57
+ return this.dialog.render(width);
80
58
  }
81
59
  }
@@ -1,7 +1,8 @@
1
1
  /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
2
  /**
3
3
  * Pure presentation model for the Injections view: flattened rows and
4
- * list navigation/scrolling state. No pi or TUI access — unit-testable.
4
+ * text sanitizers. No pi or TUI access — unit-testable. List navigation
5
+ * and preview scrolling live in the shared modal library.
5
6
  */
6
7
  import type { InitialSnapshot, InjectionItem } from '../model';
7
8
 
@@ -115,143 +116,3 @@ export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
115
116
  rows.push({ kind: 'total', label: 'TOTAL', tokens: snapshot.totalTokens, depth: 0 });
116
117
  return rows;
117
118
  }
118
-
119
- /**
120
- * Selection and scroll-window state over fixed rows. A trailing summary can
121
- * participate in scrolling without being included in selection navigation.
122
- */
123
- export class ListNavigator {
124
- private readonly rowCount: number;
125
- private readonly selectableRowCount: number;
126
- private visibleCount: number;
127
- private selectedIndex = 0;
128
- private scrollOffset = 0;
129
-
130
- public constructor(rowCount: number, visibleCount: number, selectableRowCount = rowCount) {
131
- this.rowCount = Math.max(0, rowCount);
132
- this.selectableRowCount = Math.min(this.rowCount, Math.max(0, selectableRowCount));
133
- this.visibleCount = Math.max(1, visibleCount);
134
- }
135
-
136
- public get selected(): number {
137
- return this.selectedIndex;
138
- }
139
-
140
- public get selectedOrdinal(): number {
141
- return this.selectedIndex;
142
- }
143
-
144
- public get selectableCount(): number {
145
- return this.selectableRowCount;
146
- }
147
-
148
- public get offset(): number {
149
- return this.scrollOffset;
150
- }
151
-
152
- public get windowSize(): number {
153
- return Math.min(this.visibleCount, this.rowCount);
154
- }
155
-
156
- /** One-based final row currently visible, suitable for a scroll counter. */
157
- public get visibleEnd(): number {
158
- return Math.min(this.rowCount, this.scrollOffset + this.windowSize);
159
- }
160
-
161
- public get hasOverflow(): boolean {
162
- return this.rowCount > this.visibleCount;
163
- }
164
-
165
- public setVisibleCount(count: number): void {
166
- this.visibleCount = Math.max(1, count);
167
- this.ensureVisible();
168
- }
169
-
170
- public moveBy(delta: number): boolean {
171
- return this.moveTo(this.selectedIndex + delta);
172
- }
173
-
174
- public moveTo(index: number): boolean {
175
- if (this.selectableRowCount === 0) return false;
176
- const next = Math.min(this.selectableRowCount - 1, Math.max(0, index));
177
- if (next === this.selectedIndex) return false;
178
- this.selectedIndex = next;
179
- this.ensureVisible();
180
- return true;
181
- }
182
-
183
- public page(direction: -1 | 1): boolean {
184
- return this.moveBy(direction * Math.max(1, this.visibleCount - 1));
185
- }
186
-
187
- private ensureVisible(): void {
188
- const maxOffset = Math.max(0, this.rowCount - this.visibleCount);
189
- if (this.selectedIndex < this.scrollOffset) {
190
- this.scrollOffset = this.selectedIndex;
191
- } else if (this.selectedIndex >= this.scrollOffset + this.visibleCount) {
192
- this.scrollOffset = this.selectedIndex - this.visibleCount + 1;
193
- }
194
-
195
- const trailingRows = this.rowCount - this.selectedIndex - 1;
196
- if (this.selectedIndex === this.selectableRowCount - 1 && trailingRows < this.visibleCount) {
197
- this.scrollOffset = maxOffset;
198
- }
199
- this.scrollOffset = Math.min(maxOffset, Math.max(0, this.scrollOffset));
200
- }
201
- }
202
-
203
- /**
204
- * Scroll-only window over wrapped preview lines. Extent is re-declared each
205
- * render (wrapping depends on width); the offset is clamped to stay valid.
206
- */
207
- export class PreviewScroller {
208
- private lineCount = 0;
209
- private visibleCount = 1;
210
- private offsetValue = 0;
211
-
212
- public get offset(): number {
213
- return this.offsetValue;
214
- }
215
-
216
- public get windowSize(): number {
217
- return Math.min(this.visibleCount, this.lineCount);
218
- }
219
-
220
- /** One-based final line currently visible, suitable for a progress counter. */
221
- public get visibleEnd(): number {
222
- return Math.min(this.lineCount, this.offsetValue + this.windowSize);
223
- }
224
-
225
- public get hasOverflow(): boolean {
226
- return this.lineCount > this.visibleCount;
227
- }
228
-
229
- public get maxOffset(): number {
230
- return Math.max(0, this.lineCount - this.visibleCount);
231
- }
232
-
233
- public setExtent(lineCount: number, visibleCount: number): void {
234
- this.lineCount = Math.max(0, lineCount);
235
- this.visibleCount = Math.max(1, visibleCount);
236
- this.offsetValue = Math.min(this.maxOffset, this.offsetValue);
237
- }
238
-
239
- public scrollBy(delta: number): boolean {
240
- return this.scrollTo(this.offsetValue + delta);
241
- }
242
-
243
- public scrollTo(offset: number): boolean {
244
- const next = Math.min(this.maxOffset, Math.max(0, offset));
245
- if (next === this.offsetValue) return false;
246
- this.offsetValue = next;
247
- return true;
248
- }
249
-
250
- public page(direction: -1 | 1): boolean {
251
- return this.scrollBy(direction * Math.max(1, this.visibleCount - 1));
252
- }
253
-
254
- public reset(): void {
255
- this.offsetValue = 0;
256
- }
257
- }