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