@0xkahi/pi-qol 0.1.1 → 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.
- package/README.md +13 -0
- package/assets/config.schema.json +12 -0
- package/package.json +4 -4
- package/src/codemap.md +26 -16
- package/src/config-loader.ts +4 -0
- package/src/constants.ts +1 -0
- package/src/extensions/auto-session-name/codemap.md +17 -12
- package/src/extensions/auto-session-name/title-generator.ts +1 -1
- package/src/extensions/codemap.md +173 -13
- package/src/extensions/context-view/capture.ts +394 -0
- package/src/extensions/context-view/codemap.md +213 -0
- package/src/extensions/context-view/constants.ts +4 -0
- package/src/extensions/context-view/context-view-controller.ts +67 -0
- package/src/extensions/context-view/index.ts +120 -0
- package/src/extensions/context-view/measure.ts +307 -0
- package/src/extensions/context-view/model.ts +207 -0
- package/src/extensions/context-view/ui/codemap.md +82 -0
- package/src/extensions/context-view/ui/context-view-dialog.ts +59 -0
- package/src/extensions/context-view/ui/injections-model.ts +118 -0
- package/src/extensions/context-view/ui/injections-view.ts +264 -0
- package/src/extensions/context-view/ui/skill-preview.ts +82 -0
- package/src/extensions/context-view/ui/usage-map.ts +133 -0
- package/src/extensions/context-view/ui/usage-view.ts +613 -0
- package/src/extensions/context-view/usage.ts +432 -0
- package/src/extensions/model-select/codemap.md +34 -17
- package/src/extensions/model-select/model-select-dialog.ts +85 -324
- package/src/index.ts +2 -0
- package/src/libs/codemap.md +8 -1
- package/src/libs/modal/README.md +212 -0
- package/src/libs/modal/codemap.md +34 -0
- package/src/libs/modal/index.ts +29 -0
- package/src/libs/modal/list-navigator.ts +167 -0
- package/src/libs/modal/modal-dialog.ts +297 -0
- package/src/libs/modal/navigation/pi-scheme.ts +33 -0
- package/src/libs/modal/navigation/vim-scheme.ts +56 -0
- package/src/libs/modal/preview-layer.ts +87 -0
- package/src/libs/modal/render-cache.ts +33 -0
- package/src/libs/modal/tab-strip.ts +87 -0
- package/src/libs/modal/tabs/list-tab.ts +159 -0
- package/src/libs/modal/text.ts +88 -0
- package/src/libs/modal/types.ts +70 -0
- package/src/schemas/codemap.md +100 -18
- package/src/schemas/config.schema.ts +3 -0
- package/src/schemas/context-view.config.schema.ts +13 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
|
|
2
|
+
/**
|
|
3
|
+
* Semantic data model shared by capture, measurement, and UI. Pure types —
|
|
4
|
+
* no pi access. Hierarchy and provenance live in typed fields; UI code must
|
|
5
|
+
* never parse labels to recover source, kind, or parent/child relationships.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const PI_SOURCE_ID = 'pi';
|
|
9
|
+
export const AGGREGATE_SOURCE_ID = 'aggregate:extensions';
|
|
10
|
+
|
|
11
|
+
/** What produced the captured snapshot. */
|
|
12
|
+
export type CaptureOrigin = 'real-turn' | 'synthetic-probe';
|
|
13
|
+
|
|
14
|
+
/** The frozen lifecycle phase represented by the v0.2.0 injection model. */
|
|
15
|
+
export type InjectionPhase = 'initial';
|
|
16
|
+
|
|
17
|
+
/** What kind of context data an injection item is. */
|
|
18
|
+
export type InjectionKind = 'base-prompt' | 'append-prompt' | 'context-file' | 'skills' | 'tool' | 'prompt-addition' | 'message';
|
|
19
|
+
|
|
20
|
+
/** Who contributed one or more injection items. */
|
|
21
|
+
export interface InjectionSource {
|
|
22
|
+
/** Stable internal id, namespaced by source kind. */
|
|
23
|
+
readonly id: string;
|
|
24
|
+
/** Human-readable group label. */
|
|
25
|
+
readonly label: string;
|
|
26
|
+
/** True for pi-native components. */
|
|
27
|
+
readonly native: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** One measured context injection. */
|
|
31
|
+
export interface InjectionItem {
|
|
32
|
+
/** Stable id, unique within a snapshot. */
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly phase: InjectionPhase;
|
|
35
|
+
readonly kind: InjectionKind;
|
|
36
|
+
readonly source: InjectionSource;
|
|
37
|
+
/** Human-readable item label without embedded hierarchy or source. */
|
|
38
|
+
readonly label: string;
|
|
39
|
+
readonly chars: number;
|
|
40
|
+
/** Estimated tokens (chars/4 heuristic unless measured as a message). */
|
|
41
|
+
readonly tokens: number;
|
|
42
|
+
/** Raw injected text for preview. Process-local; never log or persist. */
|
|
43
|
+
readonly text: string;
|
|
44
|
+
/** True when a message exists only in the transformed provider context, not the session branch. */
|
|
45
|
+
readonly contextOnly?: boolean;
|
|
46
|
+
/** Constituent sub-items (e.g. individual built-in tools or skills), largest first. */
|
|
47
|
+
readonly children?: readonly InjectionItem[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Items of one source, with a precomputed total. */
|
|
51
|
+
export interface InjectionGroup {
|
|
52
|
+
readonly source: InjectionSource;
|
|
53
|
+
readonly items: readonly InjectionItem[];
|
|
54
|
+
readonly totalTokens: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The frozen Initial snapshot presented by the Injections view. */
|
|
58
|
+
export interface InitialSnapshot {
|
|
59
|
+
readonly origin: CaptureOrigin;
|
|
60
|
+
readonly capturedAt: Date;
|
|
61
|
+
readonly groups: readonly InjectionGroup[];
|
|
62
|
+
readonly totalTokens: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** How an invisible reasoning-token estimate was derived without retaining raw signature bytes. */
|
|
66
|
+
export interface InvisibleReasoningEstimate {
|
|
67
|
+
/** Invisible-token estimate; signature-size proxies are not added to category totals. */
|
|
68
|
+
readonly tokens: number;
|
|
69
|
+
/** Whether the estimate came from a provider usage breakdown or opaque signature length. */
|
|
70
|
+
readonly basis: 'provider-reported' | 'signature-proxy';
|
|
71
|
+
/** Whether the message carries an opaque replay signature. */
|
|
72
|
+
readonly encoded: boolean;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** One estimated usage category, optionally with a constituent breakdown. */
|
|
76
|
+
export interface UsageCategory {
|
|
77
|
+
/** Stable id, unique within a usage snapshot level. */
|
|
78
|
+
readonly id: string;
|
|
79
|
+
readonly label: string;
|
|
80
|
+
/** Estimated tokens (chars/4 heuristic unless provider-reported reasoning is available). */
|
|
81
|
+
readonly tokens: number;
|
|
82
|
+
/** Breakdown of the parent (e.g. per tool or per customType), not additional totals. */
|
|
83
|
+
readonly children?: readonly UsageCategory[];
|
|
84
|
+
/** Content entries backing the category preview; leaves only. */
|
|
85
|
+
readonly entries?: readonly UsagePreviewEntry[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** One content entry shown in a Usage category preview. */
|
|
89
|
+
export interface UsagePreviewEntry {
|
|
90
|
+
/** Message time (epoch ms); absent for Initial-snapshot components. */
|
|
91
|
+
readonly timestamp?: number;
|
|
92
|
+
/** Bracket header cells, e.g. ["assistant", "read"] or ["code-style"]. */
|
|
93
|
+
readonly breadcrumb: readonly string[];
|
|
94
|
+
/** Tokens this entry contributes to its category, including any counted invisible reasoning. */
|
|
95
|
+
readonly tokens: number;
|
|
96
|
+
/** Visible-text share shown before invisible reasoning metadata. */
|
|
97
|
+
readonly visibleTokens?: number;
|
|
98
|
+
/** Message-level invisible reasoning metadata, attached once without retaining raw signature bytes. */
|
|
99
|
+
readonly invisibleReasoning?: InvisibleReasoningEstimate;
|
|
100
|
+
/** Raw content for preview. Process-local; never log or persist. */
|
|
101
|
+
readonly text: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Pi-reported usage; tokens/percent are omitted when unknown (e.g. right after compaction). */
|
|
105
|
+
export interface ReportedContextUsage {
|
|
106
|
+
readonly tokens?: number;
|
|
107
|
+
readonly contextWindow: number;
|
|
108
|
+
readonly percent?: number;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** On-demand estimated context composition presented by the Usage view. */
|
|
112
|
+
export interface ContextUsageSnapshot {
|
|
113
|
+
readonly computedAt: Date;
|
|
114
|
+
readonly modelLabel?: string;
|
|
115
|
+
readonly reported?: ReportedContextUsage;
|
|
116
|
+
readonly categories: readonly UsageCategory[];
|
|
117
|
+
/** Sum of the top-level category estimates. */
|
|
118
|
+
readonly estimatedTokens: number;
|
|
119
|
+
/** Auto-compaction reserve (settings `reserveTokens`); absent when auto-compaction is disabled. */
|
|
120
|
+
readonly autoCompactReserveTokens?: number;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Group measured items by source. Pi-native components come first, extension
|
|
125
|
+
* sources follow by total size, and the unattributable aggregate comes last.
|
|
126
|
+
* Items inside each group follow a fixed semantic order (base prompt, tools,
|
|
127
|
+
* skills, then everything else by size). Returned objects own all nested data;
|
|
128
|
+
* later mutation of the input cannot change the groups.
|
|
129
|
+
*/
|
|
130
|
+
export function groupInjections(items: readonly InjectionItem[]): InjectionGroup[] {
|
|
131
|
+
const groups = new Map<string, MutableGroup>();
|
|
132
|
+
for (const input of items) {
|
|
133
|
+
const item = copyItem(input);
|
|
134
|
+
let group = groups.get(item.source.id);
|
|
135
|
+
if (group === undefined) {
|
|
136
|
+
group = { source: item.source, items: [], totalTokens: 0 };
|
|
137
|
+
groups.set(item.source.id, group);
|
|
138
|
+
}
|
|
139
|
+
group.items.push(item);
|
|
140
|
+
group.totalTokens += item.tokens;
|
|
141
|
+
}
|
|
142
|
+
for (const group of groups.values()) {
|
|
143
|
+
group.items.sort(compareItems);
|
|
144
|
+
}
|
|
145
|
+
return [...groups.values()].sort(compareGroups);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Build an owned Initial snapshot from measured items. */
|
|
149
|
+
export function buildSnapshot(items: readonly InjectionItem[], origin: CaptureOrigin, capturedAt: Date): InitialSnapshot {
|
|
150
|
+
const groups = groupInjections(items);
|
|
151
|
+
return {
|
|
152
|
+
origin,
|
|
153
|
+
capturedAt: new Date(capturedAt),
|
|
154
|
+
groups,
|
|
155
|
+
totalTokens: groups.reduce((sum, group) => sum + group.totalTokens, 0),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Internal accumulator for groupInjections before freezing into InjectionGroup. */
|
|
160
|
+
interface MutableGroup {
|
|
161
|
+
source: InjectionSource;
|
|
162
|
+
items: InjectionItem[];
|
|
163
|
+
totalTokens: number;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Owned copy of an item, including its nested source and children. */
|
|
167
|
+
function copyItem(item: InjectionItem): InjectionItem {
|
|
168
|
+
return {
|
|
169
|
+
...item,
|
|
170
|
+
source: { ...item.source },
|
|
171
|
+
children: item.children?.map(child => copyItem(child)),
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Order items within a group: base/appended prompt first, then built-in tools,
|
|
177
|
+
* other tools, skills, and finally everything else by size descending.
|
|
178
|
+
*/
|
|
179
|
+
function compareItems(a: InjectionItem, b: InjectionItem): number {
|
|
180
|
+
const rankDelta = itemRank(a) - itemRank(b);
|
|
181
|
+
if (rankDelta !== 0) return rankDelta;
|
|
182
|
+
return b.tokens - a.tokens;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Fixed display rank by kind; built-in tools precede other tools. */
|
|
186
|
+
function itemRank(item: InjectionItem): number {
|
|
187
|
+
switch (item.kind) {
|
|
188
|
+
case 'base-prompt':
|
|
189
|
+
case 'append-prompt':
|
|
190
|
+
return 0;
|
|
191
|
+
case 'tool':
|
|
192
|
+
return item.id === 'tool:builtin' ? 1 : 2;
|
|
193
|
+
case 'skills':
|
|
194
|
+
return 3;
|
|
195
|
+
default:
|
|
196
|
+
return 4;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Order groups: pi-native first, then extensions by size, aggregate last. */
|
|
201
|
+
function compareGroups(a: InjectionGroup, b: InjectionGroup): number {
|
|
202
|
+
if (a.source.native !== b.source.native) return a.source.native ? -1 : 1;
|
|
203
|
+
const aAggregate = a.source.id === AGGREGATE_SOURCE_ID;
|
|
204
|
+
const bAggregate = b.source.id === AGGREGATE_SOURCE_ID;
|
|
205
|
+
if (aAggregate !== bAggregate) return aAggregate ? 1 : -1;
|
|
206
|
+
return b.totalTokens - a.totalTokens;
|
|
207
|
+
}
|
|
@@ -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.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { KeybindingsManager, Theme } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import type { Component, Focusable, TUI } from '@earendil-works/pi-tui';
|
|
3
|
+
import { ModalDialog, VimNavigationScheme } from '../../../libs/modal';
|
|
4
|
+
import type { ContextUsageSnapshot, InitialSnapshot } from '../model';
|
|
5
|
+
import { InjectionsView } from './injections-view';
|
|
6
|
+
import { UsageView } from './usage-view';
|
|
7
|
+
|
|
8
|
+
export type ContextViewTab = 'usage' | 'injections';
|
|
9
|
+
|
|
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
|
+
*/
|
|
22
|
+
export class ContextViewDialog implements Component, Focusable {
|
|
23
|
+
private readonly dialog: ModalDialog<undefined>;
|
|
24
|
+
|
|
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
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get focused(): boolean {
|
|
37
|
+
return this.dialog.focused;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
set focused(value: boolean) {
|
|
41
|
+
this.dialog.focused = value;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
get activeTab(): ContextViewTab {
|
|
45
|
+
return this.dialog.activeIndex === 0 ? 'usage' : 'injections';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
invalidate(): void {
|
|
49
|
+
this.dialog.invalidate();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
handleInput(data: string): void {
|
|
53
|
+
this.dialog.handleInput(data);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
render(width: number): string[] {
|
|
57
|
+
return this.dialog.render(width);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
|
|
2
|
+
/**
|
|
3
|
+
* Pure presentation model for the Injections view: flattened rows and
|
|
4
|
+
* text sanitizers. No pi or TUI access — unit-testable. List navigation
|
|
5
|
+
* and preview scrolling live in the shared modal library.
|
|
6
|
+
*/
|
|
7
|
+
import type { InitialSnapshot, InjectionItem } from '../model';
|
|
8
|
+
|
|
9
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
|
|
10
|
+
const TERMINAL_STRING_SEQUENCE = /(?:\u001B[\]PX^_]|[\u0090\u0098\u009D\u009E\u009F])[\s\S]*?(?:\u0007|\u001B\\|\u009C)/g;
|
|
11
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
|
|
12
|
+
const TERMINAL_CSI_SEQUENCE = /(?:\u001B\[|\u009B)[\u0030-\u003F]*[\u0020-\u002F]*[\u0040-\u007E]/g;
|
|
13
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
|
|
14
|
+
const TERMINAL_ESCAPE_SEQUENCE = /\u001B[\u0020-\u002F]*[\u0030-\u007E]/g;
|
|
15
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
|
|
16
|
+
const TERMINAL_CONTROL_CHARACTER = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
|
|
17
|
+
|
|
18
|
+
/** One flattened list row derived from the snapshot hierarchy. */
|
|
19
|
+
export type InjectionRow =
|
|
20
|
+
| {
|
|
21
|
+
readonly kind: 'group';
|
|
22
|
+
readonly label: string;
|
|
23
|
+
readonly tokens: number;
|
|
24
|
+
readonly depth: 0;
|
|
25
|
+
}
|
|
26
|
+
| {
|
|
27
|
+
readonly kind: 'item';
|
|
28
|
+
readonly label: string;
|
|
29
|
+
readonly tokens: number;
|
|
30
|
+
/** One for items and two for constituent sub-items. */
|
|
31
|
+
readonly depth: 1 | 2;
|
|
32
|
+
/** Whether this row is the final sibling at its depth. */
|
|
33
|
+
readonly isLast: boolean;
|
|
34
|
+
/** Whether a depth-two row's parent has a following sibling. */
|
|
35
|
+
readonly parentContinues?: boolean;
|
|
36
|
+
/** Stable preview target id from the snapshot. */
|
|
37
|
+
readonly itemId: string;
|
|
38
|
+
}
|
|
39
|
+
| {
|
|
40
|
+
readonly kind: 'separator';
|
|
41
|
+
readonly label: '';
|
|
42
|
+
readonly tokens: 0;
|
|
43
|
+
readonly depth: 0;
|
|
44
|
+
}
|
|
45
|
+
| {
|
|
46
|
+
readonly kind: 'total';
|
|
47
|
+
readonly label: 'TOTAL';
|
|
48
|
+
readonly tokens: number;
|
|
49
|
+
readonly depth: 0;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/** Index snapshot items (including sub-items) by id for preview lookup. */
|
|
53
|
+
export function collectItemsById(snapshot: InitialSnapshot): Map<string, InjectionItem> {
|
|
54
|
+
const items = new Map<string, InjectionItem>();
|
|
55
|
+
for (const group of snapshot.groups) {
|
|
56
|
+
for (const item of group.items) {
|
|
57
|
+
items.set(item.id, item);
|
|
58
|
+
for (const child of item.children ?? []) items.set(child.id, child);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return items;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Normalize whitespace and remove terminal control sequences from raw preview text. */
|
|
65
|
+
export function normalizePreviewText(text: string): string {
|
|
66
|
+
return text
|
|
67
|
+
.replaceAll('\r\n', '\n')
|
|
68
|
+
.replaceAll('\r', '\n')
|
|
69
|
+
.replaceAll('\t', ' ')
|
|
70
|
+
.replace(TERMINAL_STRING_SEQUENCE, '')
|
|
71
|
+
.replace(TERMINAL_CSI_SEQUENCE, '')
|
|
72
|
+
.replace(TERMINAL_ESCAPE_SEQUENCE, '')
|
|
73
|
+
.replace(TERMINAL_CONTROL_CHARACTER, '');
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Sanitize dynamic text for one terminal line and collapse embedded whitespace. */
|
|
77
|
+
export function normalizeInlineText(text: string): string {
|
|
78
|
+
return normalizePreviewText(text).replace(/\s+/g, ' ').trim();
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Flatten snapshot groups into rows separated from the non-selectable Initial total. */
|
|
82
|
+
export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
|
|
83
|
+
const rows: InjectionRow[] = [];
|
|
84
|
+
for (const group of snapshot.groups) {
|
|
85
|
+
rows.push({
|
|
86
|
+
kind: 'group',
|
|
87
|
+
label: group.source.label,
|
|
88
|
+
tokens: group.totalTokens,
|
|
89
|
+
depth: 0,
|
|
90
|
+
});
|
|
91
|
+
group.items.forEach((item, itemIndex) => {
|
|
92
|
+
const isLastItem = itemIndex === group.items.length - 1;
|
|
93
|
+
rows.push({
|
|
94
|
+
kind: 'item',
|
|
95
|
+
label: item.label,
|
|
96
|
+
tokens: item.tokens,
|
|
97
|
+
depth: 1,
|
|
98
|
+
isLast: isLastItem,
|
|
99
|
+
itemId: item.id,
|
|
100
|
+
});
|
|
101
|
+
const children = item.children ?? [];
|
|
102
|
+
children.forEach((child, childIndex) => {
|
|
103
|
+
rows.push({
|
|
104
|
+
kind: 'item',
|
|
105
|
+
label: child.label,
|
|
106
|
+
tokens: child.tokens,
|
|
107
|
+
depth: 2,
|
|
108
|
+
isLast: childIndex === children.length - 1,
|
|
109
|
+
parentContinues: !isLastItem,
|
|
110
|
+
itemId: child.id,
|
|
111
|
+
});
|
|
112
|
+
});
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
rows.push({ kind: 'separator', label: '', tokens: 0, depth: 0 });
|
|
116
|
+
rows.push({ kind: 'total', label: 'TOTAL', tokens: snapshot.totalTokens, depth: 0 });
|
|
117
|
+
return rows;
|
|
118
|
+
}
|