@0xkahi/pi-qol 1.0.0 → 1.0.2

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 (35) hide show
  1. package/README.md +4 -2
  2. package/assets/config.schema.json +10 -1
  3. package/package.json +1 -1
  4. package/src/codemap.md +25 -16
  5. package/src/extensions/auto-session-name/codemap.md +17 -12
  6. package/src/extensions/codemap.md +166 -13
  7. package/src/extensions/context-view/codemap.md +201 -16
  8. package/src/extensions/context-view/index.ts +7 -1
  9. package/src/extensions/context-view/ui/codemap.md +82 -0
  10. package/src/extensions/context-view/ui/context-view-dialog.ts +37 -51
  11. package/src/extensions/context-view/ui/injections-model.ts +2 -141
  12. package/src/extensions/context-view/ui/injections-view.ts +63 -195
  13. package/src/extensions/context-view/ui/usage-view.ts +68 -189
  14. package/src/extensions/model-select/codemap.md +34 -17
  15. package/src/extensions/model-select/index.ts +6 -13
  16. package/src/extensions/model-select/model-select-dialog.ts +85 -324
  17. package/src/extensions/model-select/types.ts +2 -2
  18. package/src/libs/codemap.md +8 -1
  19. package/src/libs/modal/README.md +223 -0
  20. package/src/libs/modal/codemap.md +35 -0
  21. package/src/libs/modal/index.ts +30 -0
  22. package/src/libs/modal/list-navigator.ts +167 -0
  23. package/src/libs/modal/modal-dialog.ts +297 -0
  24. package/src/libs/modal/navigation/pi-scheme.ts +33 -0
  25. package/src/libs/modal/navigation/vim-scheme.ts +56 -0
  26. package/src/libs/modal/presenter.ts +38 -0
  27. package/src/libs/modal/preview-layer.ts +87 -0
  28. package/src/libs/modal/render-cache.ts +33 -0
  29. package/src/libs/modal/tab-strip.ts +87 -0
  30. package/src/libs/modal/tabs/list-tab.ts +159 -0
  31. package/src/{extensions/context-view/ui/layout.ts → libs/modal/text.ts} +15 -15
  32. package/src/libs/modal/types.ts +70 -0
  33. package/src/schemas/codemap.md +101 -18
  34. package/src/schemas/context-view.config.schema.ts +5 -0
  35. package/src/extensions/context-view/ui/navigation.ts +0 -37
@@ -2,27 +2,212 @@
2
2
 
3
3
  ## Responsibility
4
4
 
5
- Provides optional inspection of model-context occupancy and initial context injections. It is disabled by default and lazily registers capture, command, and Vim-event integration only after an enabled session starts.
5
+ Provides optional, TUI-only inspection of model-context occupancy and Initial-phase context injections. Disabled by default; lazily registered only after a session starts with `context_view` enabled. The interface defaults to inline presentation and can be configured as a centered overlay. Two inspection surfaces are exposed:
6
6
 
7
- ## Architecture
7
+ - `/context-view` command (registered as `context-view`).
8
+ - `pi.vimKeys.event:pi-qol.context_view` Vim event (defined in `constants.ts` and `src/constants.ts`).
8
9
 
9
- - `index.ts`: registration, lifecycle hooks, synthetic-probe filtering/persistence, `/context-view`, and `pi.vimKeys.event:pi-qol.context_view`.
10
- - `capture.ts`: owned prompt inputs, capture-once snapshot state, active tools, context-only messages, and single-attempt probe state.
11
- - `context-view-controller.ts`: shared command/event data preparation and degraded native fallback.
12
- - `model.ts`, `measure.ts`, `usage.ts`: pure semantic models, prompt/tool measurement, and usage classification.
13
- - `ui/context-view-dialog.ts`: bounded half-height inline shell, visible Usage/Injections tabs, tab state retention, and global input routing.
14
- - `ui/usage-view.ts`, `ui/injections-view.ts`: stateful child views and previews.
15
- - `ui/navigation.ts`: shared `j/k`, arrows, `Ctrl+u/d`, `gg/G` semantics; PageUp/PageDown/Home/End are intentionally ignored.
16
- - Other `ui/` modules provide map, layout, hierarchy, scrolling, sanitization, and skill-preview helpers.
10
+ All captured prompt, tool, skill, context-file, and message content remains process-local and must never be logged or serialized. Only synthetic probe `role + timestamp` identities may be persisted.
11
+
12
+ ## Architecture & Design Patterns
13
+
14
+ - **Pure semantic model / pure functions**: `model.ts`, `measure.ts`, `usage.ts`, `ui/injections-model.ts`, `ui/usage-map.ts`, `ui/layout.ts`, `ui/skill-preview.ts` contain no pi or TUI API access and are independently unit-testable.
15
+ - **State machines**: `InitialCaptureState` (capture-once) and `SilentProbeState` (single probe lifecycle) in `capture.ts` own explicit phases and transitions.
16
+ - **Controller / data preparation**: `context-view-controller.ts` isolates the command/UI data path from the event-driven capture path.
17
+ - **Stateful UI shell with stateful child tabs**: `ContextViewDialog` (shell) retains `UsageView` and `InjectionsView` instances; navigation is shared via `VimNavigation`. The shared modal presenter coordinates its semantic layout with the shell frame and host mounting.
18
+ - **Event-driven registration**: `index.ts` hooks into `ExtensionAPI` events and only performs work when `config.isEnabled('context_view')` returns true.
19
+ - **Sanitize-before-persist**: `SilentProbeState` records only `role` and `timestamp` for synthetic messages; raw content is discarded.
20
+
21
+ ## Module Roles
22
+
23
+ ### `model.ts` — Semantic model
24
+
25
+ Pure types shared by capture, measurement, and UI.
26
+
27
+ - `InjectionItem`, `InjectionGroup`, `InitialSnapshot`: Initial-phase context decomposition.
28
+ - `UsageCategory`, `UsagePreviewEntry`, `ContextUsageSnapshot`: Usage-view composition.
29
+ - `ReportedContextUsage`, `InvisibleReasoningEstimate`: pi-reported usage metadata and reasoning-token estimates.
30
+ - `groupInjections()` / `buildSnapshot()`: group items by source with deterministic ordering (pi-native first, then extensions by size, aggregate last); items are copied to prevent later mutation.
31
+
32
+ ### `measure.ts` — Prompt/tool measurement
33
+
34
+ Pure measurement of the captured system prompt.
35
+
36
+ - `analyzeSystemPrompt()`: splits the rendered system prompt into `base-prompt`, `append-prompt`, `context-file`, `skills`, `tool`, `prompt-addition` items.
37
+ - `measureTools()`: per-tool definitions plus prompt snippets/guidelines carved from base prompt; built-in tools collapse into one aggregate pi-native item.
38
+ - `measureContextFiles()`: extracts `<project_instructions>` file content without XML scaffolding.
39
+ - `measureSkills()`: extracts `<available_skills>` section and each configured skill.
40
+ - `measureAppendedPrompt()`: identifies `--append-system-prompt` text.
41
+ - Uses a `Span` carving model to avoid double-counting base-prompt content; footer detection (`Current working directory: <cwd>`) separates pi base prompt from extension additions.
42
+
43
+ ### `capture.ts` — Capture-once state + silent probe
44
+
45
+ Stateful capture and the single allowed silent probe.
46
+
47
+ - `InitialCaptureState`: owns `prepare()` (every `before_agent_start`) and `finalize()` (first eligible `context` event). `snapshot` is frozen after the first successful finalization; `promptOptions` is kept current for the controller fallback.
48
+ - `SilentProbeState`: manages the probe lifecycle (`idle → waiting → running → settled/failed`) and records synthetic message identities by `role + timestamp`. Restores persisted identities from `pi-context-view:probe-identities` custom session entries. Sanitizes aborted assistant messages into successful stop messages so the transcript does not show an operation-aborted row.
49
+ - `measureInjectedMessages()`: diff the live provider `messages` against the session-branch baseline to identify context-only messages and custom messages.
50
+ - `buildNativeSnapshot()`: view-local pi-native snapshot without freezing the main capture state.
51
+ - `mergeContextOnlyMessages()`: overlays context-only messages from a frozen Initial snapshot onto the current snapshot.
52
+
53
+ ### `usage.ts` — Usage classification
54
+
55
+ Pure composition of the Usage view.
56
+
57
+ - `computeUsage()`: combines the frozen/captured snapshot with live filtered messages and reported usage into `ContextUsageSnapshot`.
58
+ - `classifyPromptCategories()`: maps snapshot items into System Prompt, System Tools, Custom Tools, MCP Tools, Memory (AGENTS.md), Skills.
59
+ - `classifyMessages()`: categorizes live messages into User Messages, Agent Text Messages, Agent Thinking Messages, Agent Tool Calls, Tool Output, Extension Messages, Compacted Data; handles invisible reasoning via `InvisibleReasoningEstimate` (provider-reported or signature-proxy).
60
+ - `collectPreviewEntries()`: flattens a category for chronological preview rendering.
61
+ - `toReportedUsage()`: converts pi's `ContextUsage` into the view model.
62
+
63
+ ### `context-view-controller.ts` — Data preparation
64
+
65
+ Command/event data preparation and degraded native fallback.
66
+
67
+ - `prepareContextViewData()`: waits for the agent to be idle, triggers the silent probe if no Initial snapshot exists, builds a current native snapshot from `getSystemPromptOptions()` / `getSystemPrompt()`, merges context-only messages, and computes usage.
68
+ - Returns `ContextViewData` with `initial`, `usage`, and optional `degradedReason`.
69
+
70
+ ### `index.ts` — Registration, lifecycle, persistence
71
+
72
+ Wires the extension into `ExtensionAPI`.
73
+
74
+ - `registerContextView()`: lazy registration on the first enabled `session_start`.
75
+ - `activateContextView()`: installs event handlers, restores/persists probe identities, and registers the command and Vim event.
76
+ - Event handlers:
77
+ - `session_start`: tracks latest context, restores probe identities.
78
+ - `input`: observes empty extension inputs for the probe.
79
+ - `before_agent_start`: begins probe run, prepares capture options.
80
+ - `turn_start`: aborts real turn when the probe owns the run.
81
+ - `message_start`: records probe message identities.
82
+ - `message_end`: sanitizes aborted probe assistant messages.
83
+ - `context`: filters probe messages, finalizes the Initial snapshot.
84
+ - `agent_settled`: settles probe and persists new identities.
85
+ - `session_shutdown`: fails probe and persists identities.
86
+ - Command handler validates enabled flag, no arguments, and TUI mode before opening the dialog.
87
+ - Vim event handler opens the dialog from the latest context.
88
+
89
+ ### `constants.ts`
90
+
91
+ - `COMMAND_NAME = 'context-view'`.
92
+ - `PI_VIM_KEY_EVENT_ID`: shared Vim event id helper.
93
+
94
+ ## UI Roles
95
+
96
+ ### `ui/context-view-dialog.ts`
97
+
98
+ Bounded half-height shell with configurable inline or overlay presentation.
99
+
100
+ - `ContextViewDialog`: implements `Component` and `Focusable` by wrapping a `ModalDialog` from the shared modal library (`src/libs/modal/`), configured with the presenter-resolved inline/bordered frame, Vim navigation scheme, half-height bound, and the degraded reason as a shell notice.
101
+ - `Tab`/`Shift+Tab` switches between `usage` and `injections`; both tab instances are retained so each preserves its scroll/selection/preview-layer state.
102
+ - Vim keys (`j/k`, arrows, `Ctrl+u/d`, `gg/G`, Enter, Esc/`q`) are parsed by the library's `VimNavigationScheme`; unhandled input goes to the active tab.
103
+ - Height is bounded to half the terminal by the shell in both layouts.
104
+
105
+ ### `ui/usage-view.ts`
106
+
107
+ Stateful Usage tab (`ModalTab`).
108
+
109
+ - Renders a proportional 14×14 context-window map (`UsageMap`), category legend, and reported/estimated summary within the shell-provided content height.
110
+ - Map scale toggles between `window` (reported context window) and `fit` (115% headroom, rounded to 2 significant digits) with `z` when applicable.
111
+ - Preview (Enter) pushes a `PreviewLayer` showing chronological content entries for the selected category; scrolling/paging/bounds are handled by the layer via shell navigation actions.
112
+ - Handles invisible-reasoning metadata display in Agent Thinking Messages.
113
+ - Caches rendered output via the library's `RenderCache` and invalidates on theme/selection/scroll changes.
114
+
115
+ ### `ui/injections-view.ts`
116
+
117
+ Stateful Injections tab (`ModalTab`).
118
+
119
+ - Renders the hierarchical Initial snapshot: groups (source), items, sub-items (children), and a non-selectable TOTAL row.
120
+ - Preview (Enter) pushes a `PreviewLayer` showing the raw text of the selected injection item.
121
+ - Tree rendering uses `├─`/`└─`/`│` prefixes and a stable shared value column.
122
+ - Currently only the `[INITIAL]` tab is rendered; `[Runtime]` is intentionally hidden until implemented.
123
+
124
+ ### `ui/injections-model.ts`
125
+
126
+ Pure presentation model for Injections.
127
+
128
+ - `InjectionRow`: flattened row types (`group`, `item`, `separator`, `total`).
129
+ - `buildInjectionRows()`: flattens `InitialSnapshot` into rows.
130
+ - `collectItemsById()`: indexes items (including children) for preview lookup.
131
+ - `normalizePreviewText()` / `normalizeInlineText()`: sanitize terminal escape sequences and collapse whitespace.
132
+ - `ListNavigator`/`PreviewScroller` moved to the shared modal library (`src/libs/modal/list-navigator.ts`).
133
+
134
+ ### `ui/usage-map.ts`
135
+
136
+ Pure 14×14 proportional map model.
137
+
138
+ - `buildUsageMap()`: assigns cells to categories by largest overlap; fills `full`, `partial`, `buffer`, or `free`.
139
+ - `calculateFitMapScale()`: computes a Fit denominator with 115% headroom, capped at the reported context window and floored at 10,000 tokens.
140
+
141
+ ### Shared modal library
142
+
143
+ `ui/navigation.ts` and `ui/layout.ts` were absorbed into `src/libs/modal/`:
144
+
145
+ - `VimNavigationScheme` (`navigation/vim-scheme.ts`): maps `j/k`, arrows, `Ctrl+u/d`, `gg`, `G`, Enter, Esc/`q` into `NavigationAction`s; `PageUp`/`PageDown`/`Home`/`End` are intentionally swallowed.
146
+ - `text.ts`: `calculateViewport()`, `fitToTerminalHeight()`, `fitLine()`, `spreadLine()`, `hintRow()`, `wrapDescriptionLines()`, `STEP_KEY_HINT`, `BODY_INDENT`.
147
+
148
+ ### `ui/skill-preview.ts`
149
+
150
+ Preview-only recognition of pi `<skill name="...">` wrappers.
151
+
152
+ - `splitSkillPreview()`: splits user-message text into `text` and `skill` segments so the UI can render compact skill badges.
17
153
 
18
154
  ## Data Flow
19
155
 
20
- 1. Enabled `session_start` lazily installs the feature and restores persisted role/timestamp probe identities.
21
- 2. `before_agent_start` owns structured prompt options; `context` freezes the first eligible provider snapshot.
22
- 3. Opening before capture attempts one silent empty probe; exact synthetic messages are aborted, sanitized, filtered, and persisted by identity only.
23
- 4. The controller combines the initial snapshot, current native prompt/tool data, filtered session messages, and reported usage.
24
- 5. `ContextViewDialog` opens Usage-first as an inline component bounded to 50% of terminal height and preserves both child states while tabs switch.
156
+ 1. `registerContextView()` waits for the first enabled `session_start`, then calls `activateContextView()`.
157
+ 2. `activateContextView()` restores any persisted probe identities from custom session entries.
158
+ 3. On `before_agent_start`, `capture.prepare()` saves owned prompt options; `probe.beginRun()` checks whether the empty input is an extension-originated probe.
159
+ 4. On `context`, `probe.filterMessages()` removes synthetic probe messages; the remaining messages are diffed against the session baseline to identify context-only injections; `capture.finalize()` freezes the Initial snapshot.
160
+ 5. On `agent_settled`, the probe is settled and new identities are persisted to `pi-context-view:probe-identities`.
161
+ 6. When the user invokes `/context-view` or the Vim event, `prepareContextViewData()`:
162
+ - waits for agent idle;
163
+ - triggers a silent probe if no Initial snapshot exists;
164
+ - builds a current native snapshot from live prompt/tool data;
165
+ - merges context-only messages from the fallback snapshot;
166
+ - computes the usage snapshot and opens `ContextViewDialog`.
167
+ 7. The shared modal presenter opens `ContextViewDialog` using `context_view.layout`; the dialog starts on Usage, remains bounded to half terminal height, and routes input to the active tab while retaining both tab states.
168
+
169
+ ## State Transitions
170
+
171
+ ### InitialCaptureState
172
+
173
+ - `prepare(options)` → stores `latestOptions` and `pendingPreparation` (only until snapshot frozen).
174
+ - `finalize(input)` → if `initialSnapshot` is undefined, builds and freezes it; subsequent calls return the same snapshot.
175
+
176
+ ### SilentProbeState
177
+
178
+ - `start()` → `idle → waiting`; creates a timeout; returns the existing completion on re-entry.
179
+ - `observeInput(extension, '')` → sets `inputObserved`.
180
+ - `beginRun('')` with `inputObserved` → `waiting → running` (or `*-after-timeout` if timeout already fired).
181
+ - `recordMessage()` / `sanitizeAssistant()` → records identities and replaces aborted assistant messages.
182
+ - `settle(captured)` → `running → settled`.
183
+ - `fail(reason)` → any pending phase → `failed`.
184
+ - Identities are persisted only after settlement or shutdown.
185
+
186
+ ### ContextViewDialog
187
+
188
+ - `usage ↔ injections` via `Tab`/`Shift+Tab`, including while a preview layer is open.
189
+ - The active tab handles selection and scroll via navigation actions; Enter pushes a preview layer.
190
+ - `Esc`/`q` pops the active tab's preview layer first, then closes the dialog.
191
+
192
+ ## Integration Points
193
+
194
+ - **Config**: `config-loader.isEnabled('context_view')` gates activation and command use; `config-loader.getContextView().layout` selects inline or overlay presentation (default `inline`).
195
+ - **ExtensionAPI**: `pi.on(...)`, `pi.registerCommand(...)`, `pi.events.on(...)`, `pi.appendEntry(...)`, `pi.getAllTools()`, `pi.getActiveTools()`, `pi.sendUserMessage('')`.
196
+ - **ExtensionContext**: `ctx.ui.custom<void>()`, `ctx.ui.notify()`, `ctx.abort()`, `ctx.getSystemPrompt()`, `ctx.getSystemPromptOptions()`, `ctx.getContextUsage()`, `ctx.waitForIdle()`, `ctx.mode`, `ctx.model`, `ctx.modelRegistry.hasConfiguredAuth()`, `ctx.sessionManager.getEntries()`, `ctx.sessionManager.getLeafId()`.
197
+ - **TUI**: `TUI`, `Theme`, `KeybindingsManager`, `Component`, `Focusable`, `Key`, `matchesKey`, `visibleWidth`, `wrapTextWithAnsi`.
198
+ - **Modal library**: `src/libs/modal/` (`ModalDialog`, `VimNavigationScheme`, `ModalTab`, `PreviewLayer`, `ListNavigator`, `RenderCache`, text/layout helpers).
199
+ - **Pi constants**: `piVimKeyEventId()` from `src/constants.ts`.
200
+ - **Custom session entry**: `pi-context-view:probe-identities` for cross-runtime identity persistence.
201
+
202
+ ## Child Map
203
+
204
+ - See [`ui/codemap.md`](ui/codemap.md) for a detailed map of the Usage and Injections view internals, navigation, and rendering utilities.
25
205
 
26
206
  ## Constraints
27
207
 
28
- Captured prompt, tool, skill, context-file, and message content remains process-local and must never be logged or serialized. Only synthetic probe role/timestamp identities may be persisted.
208
+ - Captured prompt, tool, skill, context-file, and message content stays process-local and must never be logged or serialized.
209
+ - Only synthetic probe `role + timestamp` identities may be persisted.
210
+ - The silent probe is limited to one attempt per session; it aborts the real turn and cleans up the transcript.
211
+ - The view requires TUI mode; it warns in non-TUI modes.
212
+ - The command accepts no arguments.
213
+ - `PageUp`/`PageDown`/`Home`/`End` are intentionally replaced by Vim bindings.
@@ -1,5 +1,6 @@
1
1
  import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
+ import { presentModal } from '../../libs/modal';
3
4
  import { InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
4
5
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
5
6
  import { prepareContextViewData } from './context-view-controller';
@@ -28,7 +29,12 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
28
29
  };
29
30
  const openContextView = async (ctx: ExtensionContext) => {
30
31
  const data = await prepareContextViewData(pi, ctx, capture, probe);
31
- await ctx.ui.custom<void>((tui, theme, keybindings, done) => new ContextViewDialog(tui, theme, keybindings, data, done));
32
+ const config = deps.config.getContextView();
33
+ await presentModal(
34
+ ctx.ui,
35
+ config.layout,
36
+ (tui, theme, keybindings, done, frame) => new ContextViewDialog(tui, theme, keybindings, data, done, frame),
37
+ );
32
38
  };
33
39
 
34
40
  restoreProbeIdentities(deps.initialCtx);
@@ -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 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. 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 `presentModal(...)` creates a `ContextViewDialog` with `usage`, `initial`, optional `degradedReason`, and the frame resolved from `context_view.layout`.
30
+ 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.
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 the shared `presentModal` helper to instantiate and mount `ContextViewDialog` in the configured layout.
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,67 @@
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, type ModalFrame, 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
25
  constructor(
19
- private readonly tui: TUI,
20
- private readonly theme: Theme,
21
- _keybindings: KeybindingsManager,
22
- input: { usage: ContextUsageSnapshot; initial: InitialSnapshot; degradedReason?: string },
26
+ tui: TUI,
27
+ theme: Theme,
28
+ keybindings: KeybindingsManager,
29
+ input: ContextViewDialogInput,
23
30
  done: (result: undefined) => void,
31
+ frame: ModalFrame = 'inline',
24
32
  ) {
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);
33
+ this.dialog = new ModalDialog<undefined>(tui, theme, keybindings, {
34
+ tabs: [new UsageView(theme, { usage: input.usage }), new InjectionsView(theme, { snapshot: input.initial })],
35
+ navigation: new VimNavigationScheme(),
36
+ frame,
37
+ height: 'half',
38
+ notices: input.degradedReason === undefined ? [] : [input.degradedReason],
39
+ cancelValue: undefined,
40
+ onComplete: done,
41
+ });
28
42
  }
29
43
 
30
44
  get focused(): boolean {
31
- return this._focused;
45
+ return this.dialog.focused;
32
46
  }
33
47
 
34
- get activeTab(): ContextViewTab {
35
- return this.active;
48
+ set focused(value: boolean) {
49
+ this.dialog.focused = value;
36
50
  }
37
51
 
38
- set focused(value: boolean) {
39
- this._focused = value;
52
+ get activeTab(): ContextViewTab {
53
+ return this.dialog.activeIndex === 0 ? 'usage' : 'injections';
40
54
  }
41
55
 
42
56
  invalidate(): void {
43
- this.usage.invalidate();
44
- this.injections.invalidate();
57
+ this.dialog.invalidate();
45
58
  }
46
59
 
47
60
  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();
61
+ this.dialog.handleInput(data);
58
62
  }
59
63
 
60
64
  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;
65
+ return this.dialog.render(width);
80
66
  }
81
67
  }
@@ -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
- }