@0xkahi/pi-qol 1.0.5 → 1.1.0

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 (33) hide show
  1. package/README.md +35 -5
  2. package/assets/config.schema.json +18 -3
  3. package/package.json +5 -5
  4. package/src/constants.ts +1 -0
  5. package/src/extensions/context-view/capture.ts +311 -83
  6. package/src/extensions/context-view/codemap.md +111 -48
  7. package/src/extensions/context-view/context-view-controller.ts +65 -27
  8. package/src/extensions/context-view/index.ts +22 -6
  9. package/src/extensions/context-view/measure.ts +713 -78
  10. package/src/extensions/context-view/model.ts +132 -14
  11. package/src/extensions/context-view/probe-token.ts +28 -0
  12. package/src/extensions/context-view/prompt-additions.ts +174 -0
  13. package/src/extensions/context-view/prompt-blocks.ts +204 -0
  14. package/src/extensions/context-view/settings.ts +43 -0
  15. package/src/extensions/context-view/text.ts +48 -0
  16. package/src/extensions/context-view/transcript.ts +62 -0
  17. package/src/extensions/context-view/ui/codemap.md +28 -13
  18. package/src/extensions/context-view/ui/context-view-dialog.ts +6 -1
  19. package/src/extensions/context-view/ui/injections-model.ts +13 -28
  20. package/src/extensions/context-view/ui/injections-view.ts +82 -21
  21. package/src/extensions/context-view/ui/json-preview.ts +41 -0
  22. package/src/extensions/context-view/ui/markers.ts +96 -0
  23. package/src/extensions/context-view/ui/section-preview.ts +188 -10
  24. package/src/extensions/context-view/ui/usage-block-layer.ts +9 -4
  25. package/src/extensions/context-view/ui/usage-view.ts +70 -17
  26. package/src/extensions/context-view/ui/wheel-preview-layer.ts +104 -0
  27. package/src/extensions/context-view/ui/wheel.ts +66 -0
  28. package/src/extensions/context-view/usage.ts +64 -26
  29. package/src/extensions/custom-footer/agent-display-state.ts +60 -0
  30. package/src/extensions/custom-footer/footer-component.ts +22 -0
  31. package/src/extensions/custom-footer/index.ts +17 -1
  32. package/src/extensions/custom-footer/types.ts +3 -1
  33. package/src/schemas/custom-footer-config.schema.ts +11 -0
@@ -0,0 +1,48 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Terminal sanitizers shared by command reporting and the views. Every string
4
+ * that reaches the terminal from outside this extension — captured content,
5
+ * configuration files, error messages — passes through here first.
6
+ */
7
+
8
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
9
+ const TERMINAL_STRING_START = /\u001B[\]PX^_]|[\u0090\u0098\u009D\u009E\u009F]/g;
10
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
11
+ const TERMINAL_STRING_END = /\u0007|\u001B\\|\u009C/g;
12
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
13
+ const TERMINAL_CSI_SEQUENCE = /(?:\u001B\[|\u009B)[\u0030-\u003F]*[\u0020-\u002F]*[\u0040-\u007E]/g;
14
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
15
+ const TERMINAL_ESCAPE_SEQUENCE = /\u001B[\u0020-\u002F]*[\u0030-\u007E]/g;
16
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: terminal sanitizer intentionally matches control bytes.
17
+ const TERMINAL_CONTROL_CHARACTER = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g;
18
+
19
+ /** Normalize whitespace and remove terminal control sequences from raw preview text. */
20
+ export function normalizePreviewText(text: string): string {
21
+ const normalized = text.replaceAll('\r\n', '\n').replaceAll('\r', '\n').replaceAll('\t', ' ');
22
+ return stripTerminalStrings(normalized)
23
+ .replace(TERMINAL_CSI_SEQUENCE, '')
24
+ .replace(TERMINAL_ESCAPE_SEQUENCE, '')
25
+ .replace(TERMINAL_CONTROL_CHARACTER, '');
26
+ }
27
+
28
+ /** Remove complete terminal strings without rescanning an unterminated suffix for every start. */
29
+ function stripTerminalStrings(text: string): string {
30
+ const parts: string[] = [];
31
+ let offset = 0;
32
+ TERMINAL_STRING_START.lastIndex = 0;
33
+ for (let start = TERMINAL_STRING_START.exec(text); start !== null; start = TERMINAL_STRING_START.exec(text)) {
34
+ TERMINAL_STRING_END.lastIndex = TERMINAL_STRING_START.lastIndex;
35
+ if (TERMINAL_STRING_END.exec(text) === null) break;
36
+ parts.push(text.slice(offset, start.index));
37
+ offset = TERMINAL_STRING_END.lastIndex;
38
+ TERMINAL_STRING_START.lastIndex = offset;
39
+ }
40
+ // Preserve an incomplete string for the existing escape/control sanitizers.
41
+ parts.push(text.slice(offset));
42
+ return parts.join('');
43
+ }
44
+
45
+ /** Sanitize dynamic text for one terminal line and collapse embedded whitespace. */
46
+ export function normalizeInlineText(text: string): string {
47
+ return normalizePreviewText(text).replace(/\s+/g, ' ').trim();
48
+ }
@@ -0,0 +1,62 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /** Process-local replay of Pi's transcript-backed prompt sections and tool declarations. */
3
+ import type { ContextEvent } from '@earendil-works/pi-coding-agent';
4
+
5
+ /** System-message shape supplied by Pi, with content and declaration patches. */
6
+ export type SystemMessage = Extract<ContextEvent['messages'][number], { role: 'system' }>;
7
+
8
+ /** Current prompt and tools after applying system messages in transcript order. */
9
+ export interface SystemState {
10
+ readonly content: string;
11
+ readonly sections: Record<string, string>;
12
+ readonly tools: NonNullable<SystemMessage['toolsAdded']>;
13
+ }
14
+
15
+ /**
16
+ * Replay Pi 0.86 semantics: content appends, sections patch by name (null deletes),
17
+ * removals precede additions, and replacing a name preserves its insertion order.
18
+ * Undefined means a legacy/empty transcript, not an explicitly empty system state.
19
+ */
20
+ export function replaySystemMessages(messages: readonly ContextEvent['messages'][number][]): SystemState | undefined {
21
+ const content: string[] = [];
22
+ const sections = new Map<string, string>();
23
+ const tools = new Map<string, NonNullable<SystemMessage['toolsAdded']>[number]>();
24
+ let found = false;
25
+ for (const message of messages) {
26
+ if (message.role !== 'system') continue;
27
+ found = true;
28
+ const text = systemContentText(message);
29
+ if (text.length > 0) content.push(text);
30
+ for (const [name, value] of Object.entries(message.sections ?? {})) {
31
+ if (value === null) sections.delete(name);
32
+ else sections.set(name, value);
33
+ }
34
+ for (const tool of message.toolsRemoved ?? []) tools.delete(tool.name);
35
+ for (const tool of message.toolsAdded ?? []) tools.set(tool.name, tool);
36
+ }
37
+ return found ? { content: content.join('\n\n'), sections: Object.fromEntries(sections), tools: [...tools.values()] } : undefined;
38
+ }
39
+
40
+ /** Content followed by non-deleted sections, matching Pi's complete-prompt rendering. */
41
+ export function systemMessageText(message: Pick<SystemMessage, 'content' | 'sections'>): string {
42
+ return [systemContentText(message), ...Object.values(message.sections ?? {})]
43
+ .filter((part): part is string => part !== null && part.length > 0)
44
+ .join('\n\n');
45
+ }
46
+
47
+ /** Copy only replay inputs; opaque text signatures and message-envelope metadata are not retained. */
48
+ export function copySystemMessage(message: SystemMessage): SystemMessage {
49
+ return {
50
+ role: 'system',
51
+ content: systemContentText(message),
52
+ sections: message.sections === undefined ? undefined : { ...message.sections },
53
+ toolsAdded: message.toolsAdded === undefined ? undefined : structuredClone(message.toolsAdded),
54
+ toolsRemoved: message.toolsRemoved?.map(tool => ({ name: tool.name })),
55
+ timestamp: message.timestamp,
56
+ };
57
+ }
58
+
59
+ /** Extract plain text without copying opaque text-block signatures. */
60
+ function systemContentText(message: Pick<SystemMessage, 'content'>): string {
61
+ return typeof message.content === 'string' ? message.content : message.content.map(block => block.text).join('\n');
62
+ }
@@ -8,21 +8,28 @@ All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, p
8
8
 
9
9
  ## Component/Model Structure
10
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.)
11
+ - `context-view-dialog.ts` — thin wrapper configuring a `ModalDialog` (presenter-resolved frame, Vim navigation scheme, half-height bound, degraded-reason notice) with the Usage and Injections tabs. Reads the host wheel step via `readWheelScrollLines(tui)` and threads it into both tabs so their wheel-aware preview layers match the transcript viewport (block streams still step one block per notch). Keeps the `Component`/`Focusable` surface and the `activeTab` accessor.
12
+ - `usage-view.ts` — the Usage tab (`ModalTab`). Stateful class that renders the context map, category legend, and zoom; category previews are pushed as wheel-aware block layers. Uses `UsageMap`, `LegendRow`, `UsageMapScale`, `ListNavigator`, `RenderCache`, and `previewBodyLines`/`previewLegendLines` from the section preview.
13
+ - `injections-view.ts` — the Injections tab (`ModalTab`). Stateful class that renders the hierarchical list of Initial snapshot rows, dropped/moved row markers, and the marker legend; item previews are pushed as wheel-aware layers. Uses `InjectionRow`, `previewBodyLines`/`previewLegendLines`, and the modal library's `ListNavigator`/`RenderCache`.
14
+ - `injections-model.ts` — pure presentation model for injections: flattens `InitialSnapshot` into `InjectionRow[]` (carrying dropped/moved state), maps items by id. Terminal sanitizers are re-exported from `../text`. (`ListNavigator`/`PreviewScroller` live in the modal library.)
15
+ - `section-preview.ts` — section-aware preview rendering: `previewBodyLines` renders labeled parts with token subheaders, dropped/moved markers, repeated-heading trimming, and restored injected references; `previewLegendLines` collapses one fixed marker legend to the rows a frame can spare.
16
+ - `markers.ts` — fixed-color state markers (`droppedMarker`, `movedMarker`, `guessMarker`) and the ordered, deduplicated bullet legend (`markerLegendLines`).
17
+ - `json-preview.ts` — preview-only JSON run expansion (`expandJsonSpan`) and span re-anchoring (`shiftJsonSpan`).
18
+ - `wheel.ts` — SGR/X10 mouse-wheel report parsing (`parseWheelDirection`) and the defensive TUI step read (`readWheelScrollLines`).
19
+ - `wheel-preview-layer.ts` — preview layer mirroring the shared frame while accepting wheel notches; honors the host wheel step passed by the dialog.
20
+ - `usage-block-layer.ts` — selectable chronological Usage block stream with per-block caps and wheel stepping.
21
+ - `usage-preview.ts` — pure block geometry and `BlockNavigator` selection/scroll state for the Usage preview.
15
22
  - `usage-map.ts` — pure map model: `UsageMap` and `UsageMapCell` plus `buildUsageMap` / `calculateFitMapScale` for the 14×14 proportional grid.
16
23
  - `skill-preview.ts` — pure text splitter: `splitSkillPreview` recognizes complete `<skill name="...">...</skill>` wrappers and emits `SkillPreviewSegment[]`.
17
24
 
18
25
  ## Design Patterns
19
26
 
20
27
  - **Shell + tab strategy**: `ContextViewDialog` is a `ModalDialog` configuration; the views implement `ModalTab` (`label`, `render(width, height)`, `handleInput`, `handleNavigation`, `hints`, `attach`, `invalidate`) and never touch framing, tab cycling, or dismissal.
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.
28
+ - **Per-tab preview layers**: Enter pushes a layer onto the tab's shell-managed layer stack via `ModalTabContext.pushLayer`. Esc pops the layer before closing the dialog; tab switching works with layers open and each tab keeps its own stack. Context View layers are wheel-aware (`wheel-preview-layer.ts`, `usage-block-layer.ts`), unlike the shared scroll-only `PreviewLayer`.
22
29
  - **Stateful retained tabs**: the dialog constructs both tabs once; each preserves selection, scroll, zoom, and layer state across switches; `invalidate()` clears caches when the theme changes.
23
30
  - **Render caching**: both views cache rendered lines via the modal library's `RenderCache`, keyed by `width` and content `height`; the cache clears on selection, navigation, or zoom changes.
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`.
31
+ - **Pure model + view split**: `injections-model.ts`, `usage-map.ts`, `usage-preview.ts`, `markers.ts`, `json-preview.ts`, `wheel.ts`, and `skill-preview.ts` contain no Pi or TUI access and are unit-testable; the views own only rendering logic.
32
+ - **Semantic navigation**: the dialog's `VimNavigationScheme` maps keys to `NavigationAction`s (`step-*`, `page-*`, `first`, `last`, `confirm`, `dismiss`); tabs receive actions via `handleNavigation` and only raw, unmapped keys (Usage's `z` zoom, wheel reports) via `handleInput`.
26
33
 
27
34
  ## Rendering/Input/Data Flow
28
35
 
@@ -41,7 +48,7 @@ All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, p
41
48
  - **Legend**: top-level categories plus one level of children under `tool-output` (per-tool breakdown). Buffer and free rows are shown when applicable but are not selectable.
42
49
  - **Zoom**: pressing `z` toggles `UsageMapScale` between `window` and `fit`. Fit adds 15% headroom, rounded up to two significant digits, capped by the context window and floored at 10,000 tokens. Zoom only works when the active width supports the side-by-side map and the fit scale is smaller than the window. The `Z Zoom` hint appears only when active.
43
50
  - **Summary header**: shows model label, reported tokens / context window, and reported percentage. When provider tokens are unknown, it shows estimated tokens and a computed percentage.
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.
51
+ - **Preview**: Enter on a category pushes a wheel-aware block stream (`UsageBlockLayer`) of chronological `UsagePreviewEntry` blocks. Body content is section-aware (`previewBodyLines`): labeled parts carry token subheaders, dropped/moved markers, repeated-heading trimming, restored injected references with their source/tool/guess attribution, and expanded JSON runs. Entry headers bold the lead breadcrumb cell. Headers show `[DD-MM-YYYY HH:MM:SS]`, breadcrumbs, visible tokens, and optional invisible-reasoning metadata (`≈` provider-reported, `~` signature proxy, `Encoded` when a replay signature is present). A fixed description about reasoning markers is shown only for `agent-thinking-messages` categories that contain invisible reasoning; other categories show the collapsed marker legend. The full-content layer expands JSON too, accepts wheel notches at the host step, and repeats the same marker legend when its body leaves room.
45
52
  - **Hints**: the shell footer shows scheme movement keys (`↑↓/jk` Navigate, `Ctrl+u/d` Page, `gg/G` Bounds), tab hints (`Enter` Preview, `Z` Zoom when active), and universal hints (`Tab` Switch, `Esc` Close/`Back`).
46
53
 
47
54
  ## Injections Tab Behavior
@@ -52,7 +59,7 @@ All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, p
52
59
  - **Value column**: the token-value column is aligned across the whole list based on the widest visible label and the widest token value.
53
60
  - **Header**: shows `Context Injections · [INITIAL]`; a Runtime label is reserved for future work but currently hidden.
54
61
  - **Degraded indicator**: when a degraded reason is present, the shell renders it as a warning notice below the tab strip (unified with the Usage tab).
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`.
62
+ - **Preview**: Enter on an item pushes a wheel-aware layer showing the item label, source, and token count; the body is section-aware (`previewBodyLines`) and wrapped with `BODY_INDENT`, expanding marked JSON runs and restoring attributed references, with the collapsed marker legend below. Rows carrying dropped/moved content show a state marker after their estimate, and the list description explains exactly those markers.
56
63
  - **Hints**: same shell-composed footer as Usage.
57
64
 
58
65
  ## Skill Preview Behavior
@@ -65,7 +72,8 @@ All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, p
65
72
  ## Integration Points
66
73
 
67
74
  - **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`).
75
+ - **Modal library**: `src/libs/modal/` supplies `ModalDialog`, `VimNavigationScheme`, `ModalTab`/`ModalTabContext` contracts, `ListNavigator`, `PreviewScroller`, `PreviewLayer`, `RenderCache`, and layout/text helpers (`BODY_INDENT`, `calculateViewport`, `fitLine`, `spreadLine`, `wrapDescriptionLines`). The Context View adds wheel-aware layers in this folder rather than editing the shared library.
76
+ - **Sanitizers**: `normalizePreviewText`/`normalizeInlineText` live in `../text`; `injections-model.ts` re-exports them for callers that import them there.
69
77
  - **Data contract**: `ContextViewData` from `context-view-controller.ts` supplies `{ initial, usage, degradedReason }`; the dialog maps `degradedReason` to the shell notices slot.
70
78
  - **Usage data source**: `usage.ts` produces `ContextUsageSnapshot` via `computeUsage`, which merges the frozen `InitialSnapshot` with live session messages and reported provider usage. `usage.ts` also provides `collectPreviewEntries`, which `UsageView` uses to flatten a category's chronological entries.
71
79
  - **Theme**: views receive a `Theme` from the Pi TUI and use semantic colors (`accent`, `muted`, `dim`, `text`, `warning`, `mdHeading`, `mdLink`, `mdCodeBlock`, `syntaxString`, `syntaxFunction`, `syntaxKeyword`, `syntaxType`, `thinkingHigh`, `thinkingXhigh`, `toolOutput`, `customMessageLabel`, `customMessageText`, `border`).
@@ -75,8 +83,15 @@ All modal plumbing — frame borders, tab strip, tab cycling, Vim key parsing, p
75
83
  ## Files
76
84
 
77
85
  - `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.
86
+ - `usage-view.ts`: Usage tab — dashboard, map, legend, zoom, category preview layers, reasoning description, marker legend.
87
+ - `injections-view.ts`: Injections tab — hierarchy list with state markers, marker legend, item preview layer.
88
+ - `injections-model.ts`: row flattening (dropped/moved aware), item indexing; sanitizer re-exports.
89
+ - `section-preview.ts`: section-aware preview bodies and marker legends.
90
+ - `markers.ts`: state markers and ordered legend bullets.
91
+ - `json-preview.ts`: JSON run expansion and span shifting.
92
+ - `wheel.ts`: wheel-report parsing and TUI step read.
93
+ - `wheel-preview-layer.ts`: wheel-aware preview layer.
94
+ - `usage-block-layer.ts`: chronological Usage block stream with caps and wheel stepping.
95
+ - `usage-preview.ts`: block geometry and navigation state.
81
96
  - `usage-map.ts`: 14×14 proportional grid and Fit-scale calculation.
82
97
  - `skill-preview.ts`: skill wrapper splitting for compact badge rendering.
@@ -4,6 +4,7 @@ import { ModalDialog, type ModalFrame, VimNavigationScheme } from '../../../libs
4
4
  import type { ContextUsageSnapshot, InitialSnapshot } from '../model';
5
5
  import { InjectionsView } from './injections-view';
6
6
  import { UsageView } from './usage-view';
7
+ import { readWheelScrollLines } from './wheel';
7
8
 
8
9
  export type ContextViewTab = 'usage' | 'injections';
9
10
 
@@ -30,8 +31,12 @@ export class ContextViewDialog implements Component, Focusable {
30
31
  done: (result: undefined) => void,
31
32
  frame: ModalFrame = 'inline',
32
33
  ) {
34
+ const wheelScrollLines = readWheelScrollLines(tui);
33
35
  this.dialog = new ModalDialog<undefined>(tui, theme, keybindings, {
34
- tabs: [new UsageView(theme, { usage: input.usage }), new InjectionsView(theme, { snapshot: input.initial })],
36
+ tabs: [
37
+ new UsageView(theme, { usage: input.usage }, wheelScrollLines),
38
+ new InjectionsView(theme, { snapshot: input.initial }, wheelScrollLines),
39
+ ],
35
40
  navigation: new VimNavigationScheme(),
36
41
  frame,
37
42
  height: 'half',
@@ -1,19 +1,13 @@
1
1
  /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
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.
3
+ * Pure presentation model for the Injections view: flattened rows. No pi or
4
+ * TUI access — unit-testable. List navigation and preview scrolling live in
5
+ * the shared modal library; terminal sanitizers live in `../text` and are
6
+ * re-exported here for callers that reached them through this module.
6
7
  */
7
8
  import type { InitialSnapshot, InjectionItem } from '../model';
8
9
 
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;
10
+ export { normalizeInlineText, normalizePreviewText } from '../text';
17
11
 
18
12
  /** One flattened list row derived from the snapshot hierarchy. */
19
13
  export type InjectionRow =
@@ -33,6 +27,10 @@ export type InjectionRow =
33
27
  readonly isLast: boolean;
34
28
  /** Whether a depth-two row's parent has a following sibling. */
35
29
  readonly parentContinues?: boolean;
30
+ /** Whether a `--system-prompt` replacement dropped this contribution. */
31
+ readonly dropped?: boolean;
32
+ /** Whether an extension moved this part out of the region pi renders it into. */
33
+ readonly moved?: boolean;
36
34
  /** Stable preview target id from the snapshot. */
37
35
  readonly itemId: string;
38
36
  }
@@ -61,23 +59,6 @@ export function collectItemsById(snapshot: InitialSnapshot): Map<string, Injecti
61
59
  return items;
62
60
  }
63
61
 
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
62
  /** Flatten snapshot groups into rows separated from the non-selectable Initial total. */
82
63
  export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
83
64
  const rows: InjectionRow[] = [];
@@ -96,6 +77,8 @@ export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
96
77
  tokens: item.tokens,
97
78
  depth: 1,
98
79
  isLast: isLastItem,
80
+ dropped: item.dropped,
81
+ moved: item.moved,
99
82
  itemId: item.id,
100
83
  });
101
84
  const children = item.children ?? [];
@@ -107,6 +90,8 @@ export function buildInjectionRows(snapshot: InitialSnapshot): InjectionRow[] {
107
90
  depth: 2,
108
91
  isLast: childIndex === children.length - 1,
109
92
  parentContinues: !isLastItem,
93
+ dropped: child.dropped,
94
+ moved: child.moved,
110
95
  itemId: child.id,
111
96
  });
112
97
  });
@@ -17,18 +17,23 @@ import {
17
17
  type ModalTab,
18
18
  type ModalTabContext,
19
19
  type NavigationAction,
20
- PreviewLayer,
21
20
  RenderCache,
22
21
  wrapDescriptionLines,
23
22
  } from '../../../libs/modal';
24
23
  import type { InitialSnapshot, InjectionItem } from '../model';
25
24
  import { buildInjectionRows, collectItemsById, type InjectionRow, normalizeInlineText, normalizePreviewText } from './injections-model';
26
- import { previewBodyLines } from './section-preview';
25
+ import { expandJsonSpan } from './json-preview';
26
+ import { type ContextMarker, droppedMarker, markerLegendLines, movedMarker } from './markers';
27
+ import { previewBodyLines, previewLegendLines } from './section-preview';
28
+ import { DEFAULT_WHEEL_SCROLL_LINES, parseWheelDirection } from './wheel';
29
+ import { WheelPreviewLayer } from './wheel-preview-layer';
27
30
 
28
31
  const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
29
32
  const CURSOR_COLUMN_WIDTH = 2;
30
33
  const MAX_TOKEN_VALUE_COLUMN = 54;
31
34
  const TOKEN_LEADER_GAP = 4;
35
+ /** Title + blank rows the wheel preview spends outside its body and legend. */
36
+ const PREVIEW_FIXED_LINE_COUNT = 2;
32
37
 
33
38
  /** Everything the Injections view renders. */
34
39
  export interface InjectionsViewInput {
@@ -47,16 +52,18 @@ export class InjectionsView implements ModalTab {
47
52
  private readonly navigator: ListNavigator;
48
53
  private readonly itemsById: Map<string, InjectionItem>;
49
54
  private readonly cache = new RenderCache();
55
+ private readonly wheelScrollLines: number;
50
56
  private context: ModalTabContext | undefined;
51
57
  private previewItem: InjectionItem | undefined;
52
58
  private previewLines: string[] | undefined;
53
59
  private previewWrapWidth: number | undefined;
54
60
 
55
- public constructor(theme: Theme, input: InjectionsViewInput) {
61
+ public constructor(theme: Theme, input: InjectionsViewInput, wheelScrollLines: number = DEFAULT_WHEEL_SCROLL_LINES) {
56
62
  this.theme = theme;
57
63
  this.rows = buildInjectionRows(input.snapshot);
58
64
  this.navigator = new ListNavigator(this.rows.length, 1, this.rows.length - 2);
59
65
  this.itemsById = collectItemsById(input.snapshot);
66
+ this.wheelScrollLines = wheelScrollLines;
60
67
  }
61
68
 
62
69
  public get label(): string {
@@ -71,8 +78,10 @@ export class InjectionsView implements ModalTab {
71
78
  return [['Enter', 'Preview']];
72
79
  }
73
80
 
74
- public handleInput(_data: string): void {
75
- // All Injections keys are semantic navigation actions handled by the shell.
81
+ /** One wheel notch steps the selection one row, like a single step key. */
82
+ public handleInput(data: string): void {
83
+ const wheel = parseWheelDirection(data);
84
+ if (wheel !== undefined && this.navigator.moveBy(wheel)) this.cache.clear();
76
85
  }
77
86
 
78
87
  /** Apply semantic movement in the hierarchy, or open an item preview. */
@@ -101,7 +110,7 @@ export class InjectionsView implements ModalTab {
101
110
 
102
111
  const terminalRows = height ?? this.rows.length + 10;
103
112
  const headerLines = this.headerLines(width);
104
- const descriptionLines = wrapDescriptionLines(this.theme, LIST_DESCRIPTION, 'dim', width);
113
+ const descriptionLines = this.descriptionLines(width);
105
114
  const viewport = calculateViewport(this.rows.length, terminalRows, headerLines.length + descriptionLines.length + 2);
106
115
  this.navigator.setVisibleCount(viewport.visibleCount);
107
116
 
@@ -133,32 +142,57 @@ export class InjectionsView implements ModalTab {
133
142
  this.previewWrapWidth = undefined;
134
143
 
135
144
  const source = normalizeInlineText(item.source.label);
145
+ const marker = item.moved === true ? movedMarker(this.theme) : '';
136
146
  this.context?.pushLayer(
137
- new PreviewLayer(this.theme, {
147
+ new WheelPreviewLayer(this.theme, {
138
148
  title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(item.label))),
139
- meta: () => this.theme.fg('muted', `${source} · ${item.tokens.toLocaleString('en-US')} tokens`),
149
+ meta: () => this.theme.fg('muted', `${source} · ${item.tokens.toLocaleString('en-US')} tokens`) + marker,
140
150
  body: width => this.getPreviewLines(width, item),
151
+ description: (width, layerHeight) => this.previewLegendLines(width, layerHeight, item),
152
+ wheelScrollLines: this.wheelScrollLines,
141
153
  }),
142
154
  );
143
155
  }
144
156
 
157
+ /** Fixed legend for the markers this item's preview renders, when content leaves room for it. */
158
+ private previewLegendLines(width: number, layerHeight: number | undefined, item: InjectionItem): string[] {
159
+ return previewLegendLines(this.theme, [item], {
160
+ width,
161
+ availableRows: Math.max(1, (layerHeight ?? 24) - PREVIEW_FIXED_LINE_COUNT),
162
+ contentLineCount: this.getPreviewLines(width, item).length,
163
+ });
164
+ }
165
+
145
166
  private getPreviewLines(width: number, item: InjectionItem): string[] {
146
167
  const wrapWidth = Math.max(10, width - BODY_INDENT.length - 1);
147
168
  if (this.previewItem === item && this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) {
148
169
  return this.previewLines;
149
170
  }
150
- const wrapText = (text: string): string[] => {
151
- const lines: string[] = [];
152
- for (const paragraph of normalizePreviewText(text).split('\n')) {
153
- const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
154
- if (wrapped.length === 0) lines.push('');
155
- else for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
156
- }
157
- return lines;
158
- };
159
- this.previewLines = previewBodyLines(this.theme, item, wrapWidth, wrapText);
171
+ // The item preview is the full-content level, so marked JSON expands here.
172
+ const lines = previewBodyLines(
173
+ this.theme,
174
+ item,
175
+ wrapWidth,
176
+ (text, jsonSpan) => this.wrappedTextLines(expandJsonSpan(text, jsonSpan), wrapWidth),
177
+ item.label,
178
+ );
179
+ this.previewLines = lines;
160
180
  this.previewWrapWidth = wrapWidth;
161
- return this.previewLines;
181
+ return lines;
182
+ }
183
+
184
+ /** Wrap sanitized text into indented preview lines, keeping blank lines. */
185
+ private wrappedTextLines(text: string, wrapWidth: number): string[] {
186
+ const lines: string[] = [];
187
+ for (const paragraph of normalizePreviewText(text).split('\n')) {
188
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
189
+ if (wrapped.length === 0) {
190
+ lines.push('');
191
+ continue;
192
+ }
193
+ for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
194
+ }
195
+ return lines;
162
196
  }
163
197
 
164
198
  // === List rendering ===
@@ -207,7 +241,7 @@ export class InjectionsView implements ModalTab {
207
241
  return { value: Math.max(1, Math.min(idealValue, width - tokenWidth)) };
208
242
  }
209
243
 
210
- /** One hierarchy row with dim leaders and a full token estimate when width permits. */
244
+ /** One hierarchy row with dim leaders, a full token estimate, and any state marker. */
211
245
  private injectionLine(
212
246
  row: Exclude<InjectionRow, { readonly kind: 'separator' }>,
213
247
  columns: InjectionColumns,
@@ -219,7 +253,15 @@ export class InjectionsView implements ModalTab {
219
253
  const leader = this.tokenLeader(columns.value - visibleWidth(left));
220
254
  const value = row.tokens.toLocaleString('en-US');
221
255
  const tokens = row.kind === 'total' ? this.theme.bold(this.theme.fg('text', value)) : this.theme.fg(selected ? 'accent' : 'muted', value);
222
- return fitLine(`${left}${leader}${tokens}`, width);
256
+ const line = `${left}${leader}${tokens}`;
257
+ return fitLine(`${line}${this.rowMarker(row, columns.value + value.length, width)}`, width);
258
+ }
259
+
260
+ /** State marker after the estimate, dropped whole rather than truncated when it does not fit. */
261
+ private rowMarker(row: Exclude<InjectionRow, { readonly kind: 'separator' }>, lineWidth: number, width: number): string {
262
+ if (row.kind !== 'item') return '';
263
+ const marker = row.dropped === true ? droppedMarker(this.theme) : row.moved === true ? movedMarker(this.theme) : '';
264
+ return lineWidth + visibleWidth(marker) <= width ? marker : '';
223
265
  }
224
266
 
225
267
  /** Fill a label/value gap with dim dots, retaining spaces at both ends. */
@@ -258,6 +300,25 @@ export class InjectionsView implements ModalTab {
258
300
  return this.fit(this.theme.fg('dim', `${BODY_INDENT}(${this.navigator.selectedOrdinal + 1}/${this.navigator.selectableCount})`), width);
259
301
  }
260
302
 
303
+ /**
304
+ * Wrapped dialog description: the list sentence and one legend bullet per
305
+ * marker the hierarchy rows show.
306
+ */
307
+ private descriptionLines(width: number): string[] {
308
+ const lines = wrapDescriptionLines(this.theme, LIST_DESCRIPTION, 'dim', width);
309
+ lines.push(...markerLegendLines(this.theme, this.rowMarkers(), width));
310
+ return lines;
311
+ }
312
+
313
+ /** Markers the hierarchy rows carry, whatever the current width leaves room to render. */
314
+ private rowMarkers(): ContextMarker[] {
315
+ const items = this.rows.filter(row => row.kind === 'item');
316
+ const markers: ContextMarker[] = [];
317
+ if (items.some(row => row.dropped === true)) markers.push('dropped');
318
+ if (items.some(row => row.moved === true)) markers.push('moved');
319
+ return markers;
320
+ }
321
+
261
322
  private fit(line: string, width: number): string {
262
323
  return fitLine(line, width);
263
324
  }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Preview-only expansion of the JSON runs the model marks structurally: a
3
+ * tool's parameter schema, tool-call arguments, and serialized message
4
+ * content. Every preview level expands them; the compact provider-bound form
5
+ * still backs every token estimate. Pure string logic — no pi or TUI access.
6
+ */
7
+ import type { JsonSpan } from '../model';
8
+
9
+ /** Spaces per nesting level, matching how tool schemas are usually authored. */
10
+ const JSON_INDENT = 2;
11
+
12
+ /**
13
+ * Text with its marked JSON run re-serialized across indented lines. Text
14
+ * without a span, and a span whose slice no longer parses, are returned
15
+ * unchanged, so a stale marker degrades to the captured form.
16
+ */
17
+ export function expandJsonSpan(text: string, span: JsonSpan | undefined): string {
18
+ if (span === undefined) return text;
19
+ const expanded = prettifyJson(text.slice(span.start, span.end));
20
+ if (expanded === undefined) return text;
21
+ return `${text.slice(0, span.start)}${expanded}${text.slice(span.end)}`;
22
+ }
23
+
24
+ /**
25
+ * Re-anchor a span after `removed` characters were dropped from the front of
26
+ * its text; undefined once the removal reaches into the JSON run itself.
27
+ */
28
+ export function shiftJsonSpan(span: JsonSpan | undefined, removed: number): JsonSpan | undefined {
29
+ if (span === undefined || removed === 0) return span;
30
+ if (removed > span.start) return undefined;
31
+ return { start: span.start - removed, end: span.end - removed };
32
+ }
33
+
34
+ /** Indented re-serialization of one JSON document, or undefined when the run does not parse. */
35
+ function prettifyJson(source: string): string | undefined {
36
+ try {
37
+ return JSON.stringify(JSON.parse(source), undefined, JSON_INDENT);
38
+ } catch {
39
+ return undefined;
40
+ }
41
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * State markers rendered after a token estimate, and the bullet legend that
3
+ * explains the ones a frame shows. Markers name how pi accounts for a part
4
+ * rather than a usage category, so their colors are fixed instead of
5
+ * configurable. Pure string logic shared by both views.
6
+ */
7
+ import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
8
+ import { wrapTextWithAnsi } from '@earendil-works/pi-tui';
9
+
10
+ import { BODY_INDENT, fitLine } from '../../../libs/modal';
11
+
12
+ /** Dim separator introducing a state marker after the estimate it explains. */
13
+ const MARKER_SEPARATOR = ' · ';
14
+
15
+ /** Markers a frame can show, in the fixed order their legend bullets render. */
16
+ const MARKER_ORDER = ['highlighted', 'guess', 'dropped', 'moved'] as const;
17
+
18
+ /** One marked state a description bullet explains. */
19
+ export type ContextMarker = (typeof MARKER_ORDER)[number];
20
+
21
+ /** Bullet marker and hanging indent of a legend entry, both two columns wide. */
22
+ const BULLET_MARKER = '- ';
23
+ const BULLET_INDENT = `${BODY_INDENT} `;
24
+
25
+ /** Keyword opening a legend bullet, its fixed color, and the sentence it heads. */
26
+ interface MarkerLegend {
27
+ readonly keyword: string;
28
+ readonly color: ThemeColor;
29
+ readonly explanation: string;
30
+ }
31
+
32
+ /** One fixed sentence per marker: each states its own accounting, independent of the others. */
33
+ const MARKER_LEGENDS: Record<ContextMarker, MarkerLegend> = {
34
+ highlighted: {
35
+ keyword: 'Highlighted',
36
+ // Restored extension lines carry this color, so the bullet opens in it too.
37
+ color: 'syntaxNumber',
38
+ explanation:
39
+ ' parts are injected by extensions into pi’s system prompt. They are excluded from the' +
40
+ ' System Prompt token count and included in the injecting extension’s count.',
41
+ },
42
+ guess: {
43
+ keyword: '(guess)',
44
+ color: 'dim',
45
+ explanation: ' sources are inferred from the injected text itself.',
46
+ },
47
+ dropped: {
48
+ keyword: 'Dropped',
49
+ color: 'toolDiffRemoved',
50
+ explanation: ' parts were replaced by a custom system prompt and are counted nowhere.',
51
+ },
52
+ moved: {
53
+ keyword: 'Moved',
54
+ color: 'warning',
55
+ explanation: ' blocks appear in a different position in the system prompt than usual.' + ' Their token counts are unchanged.',
56
+ },
57
+ };
58
+
59
+ /** Themed marker naming content pi never sent, for a preview subheader or a hierarchy row. */
60
+ export function droppedMarker(theme: Theme): string {
61
+ return stateMarker(theme, MARKER_LEGENDS.dropped);
62
+ }
63
+
64
+ /** Themed marker naming content pi sends from elsewhere in the prompt than it wrote it. */
65
+ export function movedMarker(theme: Theme): string {
66
+ return stateMarker(theme, MARKER_LEGENDS.moved);
67
+ }
68
+
69
+ /** Themed suffix naming an owner this extension inferred rather than one pi reported. */
70
+ export function guessMarker(theme: Theme): string {
71
+ const { color, keyword } = MARKER_LEGENDS.guess;
72
+ return theme.fg(color, ` ${keyword}`);
73
+ }
74
+
75
+ /**
76
+ * Description bullets explaining the markers one frame shows, in fixed order
77
+ * and without duplicates. Callers pass only the markers actually visible there,
78
+ * so a view never explains a state it does not render.
79
+ */
80
+ export function markerLegendLines(theme: Theme, markers: Iterable<ContextMarker>, width: number): string[] {
81
+ const shown = new Set(markers);
82
+ return MARKER_ORDER.filter(marker => shown.has(marker)).flatMap(marker => bulletLines(theme, MARKER_LEGENDS[marker], width));
83
+ }
84
+
85
+ /** Dim separator plus the keyword in the one fixed color its legend bullet also opens with. */
86
+ function stateMarker(theme: Theme, legend: MarkerLegend): string {
87
+ return `${theme.fg('dim', MARKER_SEPARATOR)}${theme.fg(legend.color, legend.keyword)}`;
88
+ }
89
+
90
+ /** One bullet: dim marker, keyword in the color it explains, dim sentence, hanging indent. */
91
+ function bulletLines(theme: Theme, legend: MarkerLegend, width: number): string[] {
92
+ const text = `${theme.fg(legend.color, legend.keyword)}${theme.fg('dim', legend.explanation)}`;
93
+ const wrapped = wrapTextWithAnsi(text, Math.max(1, width - BULLET_INDENT.length));
94
+ const lead = `${BODY_INDENT}${theme.fg('dim', BULLET_MARKER)}`;
95
+ return wrapped.map((line, index) => fitLine(`${index === 0 ? lead : BULLET_INDENT}${line}`, width));
96
+ }