@0xkahi/pi-qol 1.0.4 → 1.0.5

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0xkahi/pi-qol",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "quality of life pi extensions",
5
5
  "type": "module",
6
6
  "keywords": [
@@ -43,9 +43,9 @@
43
43
  "@earendil-works/pi-tui": "*"
44
44
  },
45
45
  "devDependencies": {
46
- "@earendil-works/pi-ai": "^0.84.0",
47
- "@earendil-works/pi-coding-agent": "^0.84.0",
48
- "@earendil-works/pi-tui": "^0.84.0",
46
+ "@earendil-works/pi-ai": "^0.84.3",
47
+ "@earendil-works/pi-coding-agent": "^0.84.3",
48
+ "@earendil-works/pi-tui": "^0.84.3",
49
49
  "@biomejs/biome": "^2.4.15",
50
50
  "@changesets/cli": "^2.31.0",
51
51
  "@types/node": "^24.0.0",
@@ -13,6 +13,7 @@ import { AGGREGATE_SOURCE_ID, buildSnapshot, type CaptureOrigin, type InitialSna
13
13
  export const PROBE_IDENTITIES_CUSTOM_TYPE = 'pi-context-view:probe-identities';
14
14
 
15
15
  const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
16
+ const SETUP_ABORT_ERROR_MESSAGE = 'This operation was aborted';
16
17
  const AGGREGATE_SOURCE: InjectionSource = {
17
18
  id: AGGREGATE_SOURCE_ID,
18
19
  label: 'extensions (aggregate)',
@@ -97,10 +98,11 @@ export class InitialCaptureState {
97
98
  * Freeze the Initial snapshot from the first context event. Returns the
98
99
  * existing snapshot on repeat calls, or undefined when `prepare()` never ran.
99
100
  */
100
- public finalize(input: CaptureFinalization): InitialSnapshot | undefined {
101
+ public finalize(buildInput: CaptureFinalization | (() => CaptureFinalization)): InitialSnapshot | undefined {
101
102
  if (this.initialSnapshot !== undefined) return this.initialSnapshot;
102
103
  if (this.pendingPreparation === undefined) return undefined;
103
104
 
105
+ const input = typeof buildInput === 'function' ? buildInput() : buildInput;
104
106
  const preparation = this.pendingPreparation;
105
107
  const tools = captureActiveTools(input.allTools, input.activeToolNames, {
106
108
  toolSnippets: preparation.toolSnippets,
@@ -115,6 +117,33 @@ export class InitialCaptureState {
115
117
  }
116
118
  }
117
119
 
120
+ /** Track the currently active session compaction without retaining stale signals. */
121
+ export class CompactionState {
122
+ private currentSignal: AbortSignal | undefined;
123
+
124
+ public get isActive(): boolean {
125
+ return this.currentSignal !== undefined && !this.currentSignal.aborted;
126
+ }
127
+
128
+ /** Begin tracking a live compaction signal; already-aborted signals are ignored. */
129
+ public begin(signal: AbortSignal): void {
130
+ if (signal.aborted) return;
131
+ this.currentSignal = signal;
132
+ signal.addEventListener(
133
+ 'abort',
134
+ () => {
135
+ if (this.currentSignal === signal) this.currentSignal = undefined;
136
+ },
137
+ { once: true },
138
+ );
139
+ }
140
+
141
+ /** Finish either a successful or failed compaction lifecycle. */
142
+ public finish(): void {
143
+ this.currentSignal = undefined;
144
+ }
145
+ }
146
+
118
147
  /**
119
148
  * State for one on-demand silent probe. It owns the timeout and exact synthetic
120
149
  * message identities, but leaves pi API calls and UI restoration to index.ts.
@@ -200,10 +229,10 @@ export class SilentProbeState {
200
229
  * so pi does not render an "Operation aborted" transcript row.
201
230
  */
202
231
  public sanitizeAssistant(message: ContextEvent['messages'][number]): ContextEvent['messages'][number] | undefined {
203
- if (!this.isCurrentRun || message.role !== 'assistant' || message.stopReason !== 'aborted') {
204
- return undefined;
205
- }
206
- this.recordMessage(message);
232
+ const expectedAbort =
233
+ message.role === 'assistant' &&
234
+ (message.stopReason === 'aborted' || (message.stopReason === 'error' && message.errorMessage === SETUP_ABORT_ERROR_MESSAGE));
235
+ if (!this.isCurrentRun || !expectedAbort) return undefined;
207
236
  const identity = { role: 'assistant', timestamp: message.timestamp } satisfies SyntheticMessageIdentity;
208
237
  if (!this.identities.has(identityKey(identity))) return undefined;
209
238
  return { ...message, content: [], stopReason: 'stop', errorMessage: undefined };
@@ -1,5 +1,5 @@
1
- import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
- import { buildNativeSnapshot, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
1
+ import { buildSessionContext, type ExtensionAPI, type ExtensionContext, SettingsManager } from '@earendil-works/pi-coding-agent';
2
+ import { buildNativeSnapshot, type CompactionState, type InitialCaptureState, mergeContextOnlyMessages, type SilentProbeState } from './capture';
3
3
  import type { ContextUsageSnapshot, InitialSnapshot } from './model';
4
4
  import { computeUsage, toReportedUsage } from './usage';
5
5
 
@@ -14,32 +14,53 @@ type PromptContext = ExtensionContext & {
14
14
  waitForIdle?: () => Promise<void>;
15
15
  };
16
16
 
17
+ interface ContextViewDependencies {
18
+ readAutoCompactReserveTokens?: (ctx: PromptContext) => number | undefined;
19
+ }
20
+
21
+ /** Read Pi's effective merged compaction reserve; optional settings never block the view. */
22
+ export function readAutoCompactReserveTokens(ctx: PromptContext): number | undefined {
23
+ try {
24
+ const settings = SettingsManager.create(ctx.cwd, undefined, { projectTrusted: ctx.isProjectTrusted() });
25
+ if (!settings.getCompactionEnabled()) return undefined;
26
+ return settings.getCompactionReserveTokens();
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+
17
32
  /** Prepare Context View data without requiring command-only APIs for event callers. */
18
33
  export async function prepareContextViewData(
19
34
  pi: ExtensionAPI,
20
35
  ctx: PromptContext,
21
36
  capture: InitialCaptureState,
22
37
  probe: SilentProbeState,
38
+ compaction: CompactionState,
39
+ dependencies: ContextViewDependencies = {},
23
40
  ): Promise<ContextViewData> {
24
41
  if (ctx.waitForIdle) await ctx.waitForIdle();
25
42
  let initial = capture.snapshot;
26
43
  let degradedReason: string | undefined;
27
44
 
28
45
  if (!initial) {
29
- const attempt = probe.start();
30
- if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
31
- try {
32
- pi.sendUserMessage('');
33
- } catch (error) {
34
- probe.fail(error instanceof Error ? error.message : String(error));
46
+ if (compaction.isActive) {
47
+ degradedReason = 'Silent probe unavailable: context compaction is in progress. Extension additions were not observed.';
48
+ } else {
49
+ const attempt = probe.start();
50
+ if (attempt.started && ctx.model && ctx.modelRegistry.hasConfiguredAuth(ctx.model)) {
51
+ try {
52
+ pi.sendUserMessage('');
53
+ } catch (error) {
54
+ probe.fail(error instanceof Error ? error.message : String(error));
55
+ }
56
+ } else if (attempt.started) {
57
+ probe.fail('Silent probe unavailable: no authenticated model is selected.');
35
58
  }
36
- } else if (attempt.started) {
37
- probe.fail('Silent probe unavailable: no authenticated model is selected.');
59
+ const outcome = await attempt.completion;
60
+ initial = capture.snapshot;
61
+ if (!initial)
62
+ degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
38
63
  }
39
- const outcome = await attempt.completion;
40
- initial = capture.snapshot;
41
- if (!initial)
42
- degradedReason = `${outcome.status === 'failed' ? outcome.reason : 'Silent probe did not capture Initial.'} Extension additions were not observed.`;
43
64
  }
44
65
 
45
66
  const options = capture.promptOptions ?? ctx.getSystemPromptOptions?.();
@@ -54,6 +75,7 @@ export async function prepareContextViewData(
54
75
  });
55
76
  const fallback = initial ?? current;
56
77
  const messages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
78
+ const reserveReader = dependencies.readAutoCompactReserveTokens ?? readAutoCompactReserveTokens;
57
79
  return {
58
80
  initial: fallback,
59
81
  degradedReason,
@@ -62,6 +84,7 @@ export async function prepareContextViewData(
62
84
  messages,
63
85
  reported: toReportedUsage(ctx.getContextUsage()),
64
86
  modelLabel: ctx.model?.id,
87
+ autoCompactReserveTokens: reserveReader(ctx),
65
88
  }),
66
89
  };
67
90
  }
@@ -1,7 +1,7 @@
1
1
  import { buildSessionContext, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
2
  import type { ConfigLoader } from '../../config-loader';
3
3
  import { presentModal } from '../../libs/modal';
4
- import { InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
4
+ import { CompactionState, InitialCaptureState, PROBE_IDENTITIES_CUSTOM_TYPE, parsePersistedIdentities, SilentProbeState } from './capture';
5
5
  import { COMMAND_NAME, PI_VIM_KEY_EVENT_ID } from './constants';
6
6
  import { prepareContextViewData } from './context-view-controller';
7
7
  import { ContextViewDialog } from './ui/context-view-dialog';
@@ -9,6 +9,7 @@ import { ContextViewDialog } from './ui/context-view-dialog';
9
9
  function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; initialCtx: ExtensionContext }): void {
10
10
  const capture = new InitialCaptureState();
11
11
  const probe = new SilentProbeState();
12
+ const compaction = new CompactionState();
12
13
  let persistedIdentityCount = 0;
13
14
  let latestCtx: ExtensionContext = deps.initialCtx;
14
15
  const enabled = () => deps.config.isEnabled('context_view');
@@ -28,7 +29,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
28
29
  persistedIdentityCount = identities.length;
29
30
  };
30
31
  const openContextView = async (ctx: ExtensionContext) => {
31
- const data = await prepareContextViewData(pi, ctx, capture, probe);
32
+ const data = await prepareContextViewData(pi, ctx, capture, probe, compaction);
32
33
  const config = deps.config.getContextView();
33
34
  await presentModal(
34
35
  ctx.ui,
@@ -40,8 +41,14 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
40
41
  restoreProbeIdentities(deps.initialCtx);
41
42
  pi.on('session_start', (_event, ctx) => {
42
43
  latestCtx = ctx;
44
+ compaction.finish();
43
45
  if (enabled()) restoreProbeIdentities(ctx);
44
46
  });
47
+ pi.on('session_before_compact', event => {
48
+ if (enabled()) compaction.begin(event.signal);
49
+ });
50
+ pi.on('session_compact', () => compaction.finish());
51
+ pi.on('session_compact_failed', () => compaction.finish());
45
52
  pi.on('input', event => {
46
53
  if (enabled()) probe.observeInput(event.source, event.text);
47
54
  });
@@ -64,15 +71,14 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
64
71
  pi.on('context', (event, ctx) => {
65
72
  if (!enabled()) return;
66
73
  const messages = probe.filterMessages(event.messages);
67
- const baselineMessages = probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages);
68
- capture.finalize({
74
+ capture.finalize(() => ({
69
75
  systemPrompt: ctx.getSystemPrompt(),
70
76
  messages,
71
- baselineMessages,
77
+ baselineMessages: probe.filterMessages(buildSessionContext(ctx.sessionManager.getEntries(), ctx.sessionManager.getLeafId()).messages),
72
78
  allTools: pi.getAllTools(),
73
79
  activeToolNames: pi.getActiveTools(),
74
80
  origin: probe.isCurrentRun ? 'synthetic-probe' : 'real-turn',
75
- });
81
+ }));
76
82
  return messages === event.messages ? undefined : { messages };
77
83
  });
78
84
  pi.on('agent_settled', (_event, ctx) => {
@@ -82,6 +88,7 @@ function activateContextView(pi: ExtensionAPI, deps: { config: ConfigLoader; ini
82
88
  persistProbeIdentities();
83
89
  });
84
90
  pi.on('session_shutdown', () => {
91
+ compaction.finish();
85
92
  if (!enabled()) return;
86
93
  persistProbeIdentities();
87
94
  probe.fail('Session ended before the silent probe completed.');
@@ -12,7 +12,7 @@
12
12
  * optionally preceded by a "Current date" line (pi 0.80)
13
13
  * → anything after that footer was appended by before_agent_start handlers.
14
14
  */
15
- import { AGGREGATE_SOURCE_ID, type InjectionItem, type InjectionKind, type InjectionSource, PI_SOURCE_ID } from './model';
15
+ import { AGGREGATE_SOURCE_ID, type InjectionItem, type InjectionKind, type InjectionSection, type InjectionSource, PI_SOURCE_ID } from './model';
16
16
 
17
17
  const PI_SOURCE: InjectionSource = { id: PI_SOURCE_ID, label: 'pi', native: true };
18
18
  const AGGREGATE_SOURCE: InjectionSource = {
@@ -87,7 +87,11 @@ export function analyzeSystemPrompt(systemPrompt: string, options: PromptOptions
87
87
 
88
88
  /** Same chars/4 heuristic pi's estimateTokens uses for text content. */
89
89
  export function textTokens(text: string): number {
90
- return Math.ceil(text.length / 4);
90
+ return charTokens(text.length);
91
+ }
92
+
93
+ function charTokens(chars: number): number {
94
+ return Math.ceil(chars / 4);
91
95
  }
92
96
 
93
97
  /**
@@ -96,30 +100,18 @@ export function textTokens(text: string): number {
96
100
  * tools collapse into one aggregate pi-native item.
97
101
  */
98
102
  function measureTools(base: string, tools: ToolSlice[], items: InjectionItem[], carvedSpans: Span[]): void {
103
+ const carver = createPromptCarver(base, carvedSpans);
104
+ const claimedGuidelines = new Set(piOwnedGuidelines(tools));
99
105
  const builtinChildren: InjectionItem[] = [];
100
106
  for (const tool of tools) {
101
- const definition = `${tool.name}: ${tool.description}\n${tool.parametersJson}`;
107
+ const ownedGuidelines = claimGuidelines(tool, claimedGuidelines);
108
+ const definition: SectionDraft = { label: 'Definition', text: `${tool.name}: ${tool.description}\n${tool.parametersJson}` };
102
109
  if (tool.source === 'builtin') {
103
- builtinChildren.push(createItem(`tool:builtin:${tool.name}`, 'tool', PI_SOURCE, tool.name, definition));
110
+ builtinChildren.push(createToolItem(`tool:builtin:${tool.name}`, PI_SOURCE, tool.name, [definition]));
104
111
  continue;
105
112
  }
106
- let promptText = '';
107
- if (tool.snippet !== undefined) {
108
- const span = findExactSpan(base, `\n- ${tool.name}: ${tool.snippet}`);
109
- if (span !== undefined) {
110
- promptText += base.slice(span.start, span.end);
111
- carvedSpans.push(span);
112
- }
113
- }
114
- for (const guideline of tool.guidelines) {
115
- const span = findExactSpan(base, `\n- ${guideline.trim()}`);
116
- if (span !== undefined) {
117
- promptText += base.slice(span.start, span.end);
118
- carvedSpans.push(span);
119
- }
120
- }
121
- const source = extensionSource(tool.source);
122
- items.push(createItem(`tool:${tool.source}:${tool.name}`, 'tool', source, tool.name, promptText + definition));
113
+ const sections = [...carveToolPromptSections(carver, tool, ownedGuidelines), definition];
114
+ items.push(createToolItem(`tool:${tool.source}:${tool.name}`, extensionSource(tool.source), tool.name, sections));
123
115
  }
124
116
  if (builtinChildren.length > 0) {
125
117
  builtinChildren.sort((a, b) => b.tokens - a.tokens);
@@ -134,6 +126,74 @@ function measureTools(base: string, tools: ToolSlice[], items: InjectionItem[],
134
126
  }
135
127
  }
136
128
 
129
+ interface SectionDraft {
130
+ readonly label: string;
131
+ readonly text: string;
132
+ }
133
+
134
+ function carveToolPromptSections(carver: PromptCarver, tool: ToolSlice, ownedGuidelines: string[]): SectionDraft[] {
135
+ const sections: SectionDraft[] = [];
136
+ const snippet = tool.snippet === undefined ? undefined : carveBlockLine(carver, carver.toolsBlock, `\n- ${tool.name}: ${tool.snippet}`);
137
+ if (snippet !== undefined) sections.push({ label: 'Prompt Snippet', text: snippet });
138
+ let bullets = '';
139
+ for (const guideline of ownedGuidelines) bullets += carveBlockLine(carver, carver.guidelinesBlock, `\n- ${guideline}`) ?? '';
140
+ if (bullets.length > 0) sections.push({ label: 'Guidelines', text: bullets });
141
+ return sections;
142
+ }
143
+
144
+ interface PromptCarver {
145
+ readonly base: string;
146
+ readonly toolsBlock: Span | undefined;
147
+ readonly guidelinesBlock: Span | undefined;
148
+ readonly carvedSpans: Span[];
149
+ }
150
+
151
+ function createPromptCarver(base: string, carvedSpans: Span[]): PromptCarver {
152
+ return {
153
+ base,
154
+ toolsBlock: findBulletBlock(base, '\nAvailable tools:\n'),
155
+ guidelinesBlock: findBulletBlock(base, '\nGuidelines:\n'),
156
+ carvedSpans,
157
+ };
158
+ }
159
+
160
+ function findBulletBlock(text: string, header: string): Span | undefined {
161
+ const headerStart = text.indexOf(header);
162
+ if (headerStart === -1) return undefined;
163
+ const start = headerStart + header.length - 1;
164
+ const blank = text.indexOf('\n\n', start);
165
+ return { start, end: blank === -1 ? text.length : blank };
166
+ }
167
+
168
+ function carveBlockLine(carver: PromptCarver, block: Span | undefined, line: string): string | undefined {
169
+ if (block === undefined) return undefined;
170
+ const start = carver.base.indexOf(line, block.start);
171
+ if (start === -1 || start + line.length > block.end) return undefined;
172
+ const span = { start, end: start + line.length };
173
+ carver.carvedSpans.push(span);
174
+ return carver.base.slice(span.start, span.end);
175
+ }
176
+
177
+ function piOwnedGuidelines(tools: ToolSlice[]): string[] {
178
+ const names = new Set(tools.map(tool => tool.name));
179
+ const shellOnly = (names.has('bash') || names.has('powershell')) && !names.has('grep') && !names.has('find') && !names.has('ls');
180
+ if (!shellOnly) return [];
181
+ if (names.has('bash') && names.has('powershell')) return ['Use bash or PowerShell for file operations like listing, searching, and finding files'];
182
+ if (names.has('powershell')) return ['Use PowerShell for file operations like listing, searching, and finding files'];
183
+ return ['Use bash for file operations like ls, rg, find'];
184
+ }
185
+
186
+ function claimGuidelines(tool: ToolSlice, claimed: Set<string>): string[] {
187
+ const owned: string[] = [];
188
+ for (const guideline of tool.guidelines) {
189
+ const text = guideline.trim();
190
+ if (text.length === 0 || claimed.has(text)) continue;
191
+ claimed.add(text);
192
+ owned.push(text);
193
+ }
194
+ return owned;
195
+ }
196
+
137
197
  /** Measure context-file contents without counting pi's XML transport scaffolding. */
138
198
  function measureContextFiles(base: string, options: PromptOptionsSlice, items: InjectionItem[], carvedSpans: Span[]): void {
139
199
  const sectionSpan = findContextSectionSpan(base);
@@ -187,6 +247,25 @@ function createItem(id: string, kind: InjectionKind, source: InjectionSource, la
187
247
  };
188
248
  }
189
249
 
250
+ /** Build a tool item whose text is exactly the concatenation of its sections. */
251
+ function createToolItem(id: string, source: InjectionSource, label: string, sections: SectionDraft[]): InjectionItem {
252
+ const text = sections.map(section => section.text).join('');
253
+ return { ...createItem(id, 'tool', source, label, text), sections: allocateSectionTokens(sections) };
254
+ }
255
+
256
+ /** Allocate cumulative token deltas so rounded sections reconcile exactly. */
257
+ function allocateSectionTokens(sections: SectionDraft[]): InjectionSection[] {
258
+ let chars = 0;
259
+ let allocated = 0;
260
+ return sections.map(section => {
261
+ chars += section.text.length;
262
+ const cumulative = charTokens(chars);
263
+ const tokens = cumulative - allocated;
264
+ allocated = cumulative;
265
+ return { ...section, tokens };
266
+ });
267
+ }
268
+
190
269
  /** Build an aggregate whose totals exactly reconcile with its child items. */
191
270
  function createAggregateItem(id: string, kind: InjectionKind, source: InjectionSource, label: string, children: InjectionItem[]): InjectionItem {
192
271
  return {
@@ -253,12 +332,6 @@ function findBasePromptFooter(systemPrompt: string, cwd: string): Span | undefin
253
332
  return undefined;
254
333
  }
255
334
 
256
- /** Span of the first exact occurrence of needle, or undefined. */
257
- function findExactSpan(haystack: string, needle: string): Span | undefined {
258
- const start = haystack.indexOf(needle);
259
- return start === -1 ? undefined : { start, end: start + needle.length };
260
- }
261
-
262
335
  /** Span of pi's complete project-context transport section. */
263
336
  function findContextSectionSpan(systemPrompt: string): Span | undefined {
264
337
  return findDelimitedSpan(systemPrompt, '<project_context>', '</project_context>');
@@ -27,6 +27,14 @@ export interface InjectionSource {
27
27
  readonly native: boolean;
28
28
  }
29
29
 
30
+ /** One labeled part of an item's raw text, used only to shape its preview. */
31
+ export interface InjectionSection {
32
+ readonly label: string;
33
+ readonly text: string;
34
+ /** Share of the parent estimate; sections sum exactly to the item total. */
35
+ readonly tokens: number;
36
+ }
37
+
30
38
  /** One measured context injection. */
31
39
  export interface InjectionItem {
32
40
  /** Stable id, unique within a snapshot. */
@@ -41,6 +49,8 @@ export interface InjectionItem {
41
49
  readonly tokens: number;
42
50
  /** Raw injected text for preview. Process-local; never log or persist. */
43
51
  readonly text: string;
52
+ /** Labeled parts of `text`; never additional tokens. */
53
+ readonly sections?: readonly InjectionSection[];
44
54
  /** True when a message exists only in the transformed provider context, not the session branch. */
45
55
  readonly contextOnly?: boolean;
46
56
  /** Constituent sub-items (e.g. individual built-in tools or skills), largest first. */
@@ -99,6 +109,8 @@ export interface UsagePreviewEntry {
99
109
  readonly invisibleReasoning?: InvisibleReasoningEstimate;
100
110
  /** Raw content for preview. Process-local; never log or persist. */
101
111
  readonly text: string;
112
+ /** Labeled parts carried from a measured snapshot item. */
113
+ readonly sections?: readonly InjectionSection[];
102
114
  }
103
115
 
104
116
  /** Pi-reported usage; tokens/percent are omitted when unknown (e.g. right after compaction). */
@@ -168,6 +180,7 @@ function copyItem(item: InjectionItem): InjectionItem {
168
180
  return {
169
181
  ...item,
170
182
  source: { ...item.source },
183
+ sections: item.sections?.map(section => ({ ...section })),
171
184
  children: item.children?.map(child => copyItem(child)),
172
185
  };
173
186
  }
@@ -23,6 +23,7 @@ import {
23
23
  } from '../../../libs/modal';
24
24
  import type { InitialSnapshot, InjectionItem } from '../model';
25
25
  import { buildInjectionRows, collectItemsById, type InjectionRow, normalizeInlineText, normalizePreviewText } from './injections-model';
26
+ import { previewBodyLines } from './section-preview';
26
27
 
27
28
  const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
28
29
  const CURSOR_COLUMN_WIDTH = 2;
@@ -146,19 +147,18 @@ export class InjectionsView implements ModalTab {
146
147
  if (this.previewItem === item && this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) {
147
148
  return this.previewLines;
148
149
  }
149
- const text = normalizePreviewText(item.text);
150
- const lines: string[] = [];
151
- for (const paragraph of text.split('\n')) {
152
- const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
153
- if (wrapped.length === 0) {
154
- lines.push('');
155
- continue;
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
156
  }
157
- for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
158
- }
159
- this.previewLines = lines;
157
+ return lines;
158
+ };
159
+ this.previewLines = previewBodyLines(this.theme, item, wrapWidth, wrapText);
160
160
  this.previewWrapWidth = wrapWidth;
161
- return lines;
161
+ return this.previewLines;
162
162
  }
163
163
 
164
164
  // === List rendering ===
@@ -0,0 +1,29 @@
1
+ /** Shared rendering for preview content split into labeled measured sections. */
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+ import { wrapTextWithAnsi } from '@earendil-works/pi-tui';
4
+ import { BODY_INDENT } from '../../../libs/modal';
5
+ import type { InjectionSection } from '../model';
6
+ import { normalizeInlineText } from './injections-model';
7
+
8
+ export interface SectionedContent {
9
+ readonly text: string;
10
+ readonly sections?: readonly InjectionSection[];
11
+ }
12
+
13
+ export function previewBodyLines(theme: Theme, content: SectionedContent, wrapWidth: number, wrapText: (text: string) => string[]): string[] {
14
+ const sections = content.sections ?? [];
15
+ if (sections.length === 0) return wrapText(content.text);
16
+ const lines: string[] = [];
17
+ for (const section of sections) {
18
+ if (lines.length > 0) lines.push('');
19
+ lines.push(...sectionHeaderLines(theme, section, wrapWidth));
20
+ lines.push(...wrapText(section.text.replace(/^\n+/, '')));
21
+ }
22
+ return lines;
23
+ }
24
+
25
+ function sectionHeaderLines(theme: Theme, section: InjectionSection, wrapWidth: number): string[] {
26
+ const label = theme.fg('syntaxFunction', theme.bold(normalizeInlineText(section.label)));
27
+ const tokens = theme.fg('muted', ` · ${section.tokens.toLocaleString('en-US')} tokens`);
28
+ return wrapTextWithAnsi(`${label}${tokens}`, wrapWidth).map(line => `${BODY_INDENT}${line}`);
29
+ }
@@ -0,0 +1,139 @@
1
+ /** Selectable chronological Usage preview layer with height-bounded entry excerpts. */
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+
4
+ import { BODY_INDENT, calculateViewport, fitLine, type Hint, type ModalLayer, type NavigationAction, spreadLine } from '../../../libs/modal';
5
+ import type { UsagePreviewEntry } from '../model';
6
+ import { BlockNavigator, layoutPreviewBlocks, type PreviewLayout } from './usage-preview';
7
+
8
+ const MAX_EXCERPT_LINES = 20;
9
+ const MIN_EXCERPT_LINES = 2;
10
+
11
+ export interface UsageBlockLayerOptions {
12
+ readonly title: string | (() => string);
13
+ readonly meta?: string | (() => string);
14
+ readonly entries: readonly UsagePreviewEntry[];
15
+ readonly entryHeader: (entry: UsagePreviewEntry) => string;
16
+ readonly entryBody: (entry: UsagePreviewEntry, width: number) => string[];
17
+ readonly description?: (width: number) => string[];
18
+ readonly openFullContent: (entry: UsagePreviewEntry) => void;
19
+ }
20
+
21
+ interface RenderedBlock {
22
+ readonly lines: readonly string[];
23
+ readonly truncated: boolean;
24
+ }
25
+
26
+ export class UsageBlockLayer implements ModalLayer {
27
+ private readonly navigator = new BlockNavigator();
28
+ private blocks: readonly RenderedBlock[] = [];
29
+ private layout: PreviewLayout = layoutPreviewBlocks([]);
30
+ private cacheKey: string | undefined;
31
+
32
+ public constructor(
33
+ private readonly theme: Theme,
34
+ private readonly options: UsageBlockLayerOptions,
35
+ ) {}
36
+
37
+ public hints(): Hint[] {
38
+ const selected = this.blocks[this.navigator.selected];
39
+ return selected?.truncated === true ? [['Enter', 'View Content']] : [];
40
+ }
41
+
42
+ public handleInput(_data: string): void {
43
+ // Navigation is supplied as semantic actions by the modal shell.
44
+ }
45
+
46
+ public handleNavigation(action: NavigationAction): void {
47
+ switch (action) {
48
+ case 'step-back':
49
+ this.navigator.stepBack();
50
+ break;
51
+ case 'step-forward':
52
+ this.navigator.stepForward();
53
+ break;
54
+ case 'page-back':
55
+ this.navigator.page(-1);
56
+ break;
57
+ case 'page-forward':
58
+ this.navigator.page(1);
59
+ break;
60
+ case 'first':
61
+ this.navigator.moveToFirst();
62
+ break;
63
+ case 'last':
64
+ this.navigator.moveToLast();
65
+ break;
66
+ case 'confirm': {
67
+ if (this.blocks[this.navigator.selected]?.truncated !== true) return;
68
+ const entry = this.options.entries[this.navigator.selected];
69
+ if (entry !== undefined) this.options.openFullContent(entry);
70
+ break;
71
+ }
72
+ }
73
+ }
74
+
75
+ public render(width: number, height: number | undefined): string[] {
76
+ const description = this.options.description?.(width) ?? [];
77
+ // Reserve one row for the overflow counter whenever the stream needs it;
78
+ // an unused row is preferable to clipping a pinned description.
79
+ const fixedLineCount = 3 + (description.length > 0 ? description.length + 1 : 0);
80
+ const available = Math.max(1, (height ?? 20) - fixedLineCount);
81
+ const excerptCap = Math.max(MIN_EXCERPT_LINES, Math.min(MAX_EXCERPT_LINES, Math.floor((available - 3) / 2)));
82
+ this.buildBlocks(width, excerptCap);
83
+
84
+ const viewport = calculateViewport(this.layout.lines.length, height ?? this.layout.lines.length + fixedLineCount, fixedLineCount);
85
+ this.navigator.setExtent(this.layout, viewport.visibleCount);
86
+ const title = typeof this.options.title === 'function' ? this.options.title() : this.options.title;
87
+ const metaOption = this.options.meta;
88
+ const meta = typeof metaOption === 'function' ? metaOption() : (metaOption ?? '');
89
+ const lines = [spreadLine(title, meta, width), ''];
90
+
91
+ if (this.blocks.length === 0) {
92
+ lines.push(fitLine(this.theme.fg('muted', `${BODY_INDENT}No content captured for this category.`), width));
93
+ } else {
94
+ for (let index = this.navigator.offset; index < this.navigator.offset + viewport.visibleCount; index++) {
95
+ const ref = this.layout.lines[index];
96
+ if (ref === undefined) {
97
+ lines.push('');
98
+ continue;
99
+ }
100
+ const block = this.blocks[ref.blockIndex];
101
+ const line = block?.lines[ref.lineIndex] ?? '';
102
+ const cursor = ref.lineIndex === 0 && ref.blockIndex === this.navigator.selected ? this.theme.fg('accent', '→ ') : ' ';
103
+ lines.push(fitLine(`${cursor}${line}`, width));
104
+ }
105
+ }
106
+ if (viewport.showScroll) {
107
+ lines.push(
108
+ fitLine(
109
+ this.theme.fg(
110
+ 'dim',
111
+ `${BODY_INDENT}(${Math.min(this.layout.lines.length, this.navigator.offset + viewport.visibleCount)}/${this.layout.lines.length})`,
112
+ ),
113
+ width,
114
+ ),
115
+ );
116
+ }
117
+ if (description.length > 0) lines.push('', ...description);
118
+ return lines;
119
+ }
120
+
121
+ public invalidate(): void {
122
+ this.cacheKey = undefined;
123
+ }
124
+
125
+ private buildBlocks(width: number, excerptCap: number): void {
126
+ const bodyWidth = Math.max(10, width - 2);
127
+ const key = `${bodyWidth}:${excerptCap}`;
128
+ if (this.cacheKey === key) return;
129
+ this.blocks = this.options.entries.map(entry => {
130
+ const body = this.options.entryBody(entry, bodyWidth);
131
+ const truncated = body.length > excerptCap;
132
+ const visible = truncated ? body.slice(0, excerptCap) : body;
133
+ const marker = truncated ? [`${BODY_INDENT}${this.theme.fg('dim', `… +${body.length - visible.length} lines`)}`] : [];
134
+ return { lines: [this.options.entryHeader(entry), ...visible, ...marker], truncated };
135
+ });
136
+ this.layout = layoutPreviewBlocks(this.blocks.map(block => block.lines.length));
137
+ this.cacheKey = key;
138
+ }
139
+ }
@@ -26,6 +26,8 @@ export interface UsageMap {
26
26
  readonly columns: number;
27
27
  readonly rows: number;
28
28
  readonly cells: readonly UsageMapCell[];
29
+ /** Approximate token span represented by one cell at the active scale. */
30
+ readonly blockTokens: number;
29
31
  }
30
32
 
31
33
  interface MapSegment {
@@ -75,7 +77,7 @@ export function buildUsageMap(
75
77
  const bufferStart = ((contextWindow - bufferTokens) / mapScale) * cellCount;
76
78
  const segments = createSegments(usage, estimatedTotal, occupiedCells);
77
79
  const cells = Array.from({ length: cellCount }, (_, index) => createCell(index, occupiedCells, bufferStart, segments));
78
- return { columns: Math.floor(columns), rows: Math.floor(rows), cells };
80
+ return { columns: Math.floor(columns), rows: Math.floor(rows), cells, blockTokens: mapScale / cellCount };
79
81
  }
80
82
 
81
83
  /** Scale estimated category shares into the occupied map range. */
@@ -0,0 +1,148 @@
1
+ /** Pure geometry and navigation state for chronological Usage entry blocks. */
2
+ export interface PreviewBlockExtent {
3
+ readonly start: number;
4
+ readonly height: number;
5
+ }
6
+
7
+ export interface PreviewLineRef {
8
+ readonly blockIndex: number;
9
+ readonly lineIndex: number;
10
+ }
11
+
12
+ export interface PreviewLayout {
13
+ readonly extents: readonly PreviewBlockExtent[];
14
+ readonly lines: ReadonlyArray<PreviewLineRef | undefined>;
15
+ }
16
+
17
+ /** Stack block heights into one line stream separated by a blank row. */
18
+ export function layoutPreviewBlocks(heights: readonly number[]): PreviewLayout {
19
+ const extents: PreviewBlockExtent[] = [];
20
+ const lines: Array<PreviewLineRef | undefined> = [];
21
+ for (const [blockIndex, height] of heights.entries()) {
22
+ if (blockIndex > 0) lines.push(undefined);
23
+ extents.push({ start: lines.length, height });
24
+ for (let lineIndex = 0; lineIndex < height; lineIndex++) lines.push({ blockIndex, lineIndex });
25
+ }
26
+ return { extents, lines };
27
+ }
28
+
29
+ export class BlockNavigator {
30
+ private extents: readonly PreviewBlockExtent[] = [];
31
+ private lineCount = 0;
32
+ private visibleCount = 1;
33
+ private selectedIndex = 0;
34
+ private offsetValue = 0;
35
+
36
+ public get selected(): number {
37
+ return this.selectedIndex;
38
+ }
39
+ public get blockCount(): number {
40
+ return this.extents.length;
41
+ }
42
+ public get offset(): number {
43
+ return this.offsetValue;
44
+ }
45
+ public get maxOffset(): number {
46
+ return Math.max(0, this.lineCount - this.visibleCount);
47
+ }
48
+
49
+ public setExtent(layout: PreviewLayout, visibleCount: number): void {
50
+ this.extents = layout.extents;
51
+ this.lineCount = layout.lines.length;
52
+ this.visibleCount = Math.max(1, visibleCount);
53
+ this.selectedIndex = clamp(this.selectedIndex, this.extents.length - 1);
54
+ this.offsetValue = clamp(this.offsetValue, this.maxOffset);
55
+ if (!this.isSelectionAnchored()) this.revealSelected();
56
+ }
57
+
58
+ public stepBack(): boolean {
59
+ const block = this.extents[this.selectedIndex];
60
+ if (block === undefined) return false;
61
+ if (block.start < this.offsetValue) return this.scrollTo(this.offsetValue - 1);
62
+ return this.selectBlock(this.selectedIndex - 1, -1);
63
+ }
64
+
65
+ public stepForward(): boolean {
66
+ const block = this.extents[this.selectedIndex];
67
+ if (block === undefined) return false;
68
+ if (block.start + block.height > this.offsetValue + this.visibleCount) return this.scrollTo(this.offsetValue + 1);
69
+ return this.selectBlock(this.selectedIndex + 1, 1);
70
+ }
71
+
72
+ public page(direction: -1 | 1): boolean {
73
+ if (this.extents.length === 0) return false;
74
+ const offset = clamp(this.offsetValue + direction * this.visibleCount, this.maxOffset);
75
+ if (offset === this.offsetValue) return this.moveTo(direction < 0 ? 0 : this.extents.length - 1, offset);
76
+ return this.moveTo(this.firstVisibleBlock(offset), offset);
77
+ }
78
+
79
+ public moveToFirst(): boolean {
80
+ return this.moveTo(0, 0);
81
+ }
82
+ public moveToLast(): boolean {
83
+ return this.moveTo(this.extents.length - 1, this.maxOffset);
84
+ }
85
+ public reset(): void {
86
+ this.selectedIndex = 0;
87
+ this.offsetValue = 0;
88
+ }
89
+
90
+ private selectBlock(index: number, direction: -1 | 1): boolean {
91
+ if (index < 0 || index >= this.extents.length || index === this.selectedIndex) return false;
92
+ this.selectedIndex = index;
93
+ this.revealSelected(direction);
94
+ return true;
95
+ }
96
+
97
+ private scrollTo(offset: number): boolean {
98
+ const next = clamp(offset, this.maxOffset);
99
+ if (next === this.offsetValue) return false;
100
+ this.offsetValue = next;
101
+ return true;
102
+ }
103
+
104
+ private moveTo(index: number, offset: number): boolean {
105
+ const nextIndex = clamp(index, this.extents.length - 1);
106
+ const nextOffset = clamp(offset, this.maxOffset);
107
+ if (nextIndex === this.selectedIndex && nextOffset === this.offsetValue) return false;
108
+ this.selectedIndex = nextIndex;
109
+ this.offsetValue = nextOffset;
110
+ return true;
111
+ }
112
+
113
+ private isSelectionAnchored(): boolean {
114
+ const block = this.extents[this.selectedIndex];
115
+ if (block === undefined) return true;
116
+ const end = block.start + block.height;
117
+ if (block.height <= this.visibleCount) return block.start >= this.offsetValue && end <= this.offsetValue + this.visibleCount;
118
+ return block.start < this.offsetValue + this.visibleCount && end > this.offsetValue;
119
+ }
120
+
121
+ private revealSelected(direction?: -1 | 1): void {
122
+ const block = this.extents[this.selectedIndex];
123
+ if (block === undefined) return;
124
+ const end = block.start + block.height;
125
+ if (block.height > this.visibleCount) {
126
+ if (direction === -1) this.scrollTo(end - this.visibleCount);
127
+ else if (direction === 1 || !this.isSelectionAnchored()) this.scrollTo(block.start);
128
+ return;
129
+ }
130
+ if (block.start < this.offsetValue) this.scrollTo(block.start);
131
+ else if (end > this.offsetValue + this.visibleCount) this.scrollTo(end - this.visibleCount);
132
+ }
133
+
134
+ private firstVisibleBlock(offset: number): number {
135
+ const end = offset + this.visibleCount;
136
+ let firstIntersecting: number | undefined;
137
+ for (const [index, block] of this.extents.entries()) {
138
+ const blockEnd = block.start + block.height;
139
+ if (block.start >= offset && blockEnd <= end) return index;
140
+ if (firstIntersecting === undefined && block.start < end && blockEnd > offset) firstIntersecting = index;
141
+ }
142
+ return firstIntersecting ?? this.selectedIndex;
143
+ }
144
+ }
145
+
146
+ function clamp(value: number, max: number): number {
147
+ return Math.max(0, Math.min(max, value));
148
+ }
@@ -26,7 +26,9 @@ import {
26
26
  import type { ContextUsageSnapshot, UsageCategory, UsagePreviewEntry } from '../model';
27
27
  import { collectPreviewEntries } from '../usage';
28
28
  import { normalizeInlineText, normalizePreviewText } from './injections-model';
29
+ import { previewBodyLines } from './section-preview';
29
30
  import { splitSkillPreview } from './skill-preview';
31
+ import { UsageBlockLayer } from './usage-block-layer';
30
32
  import { buildUsageMap, calculateFitMapScale, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, type UsageMapCell } from './usage-map';
31
33
 
32
34
  const USAGE_DESCRIPTION =
@@ -36,7 +38,6 @@ const INVISIBLE_REASONING_DESCRIPTION =
36
38
  '≈ is a provider-reported count; ~ is a rough approximation when no breakdown ' +
37
39
  'is reported and excluded from category totals. ' +
38
40
  'Encoded replaces Reasoning when the provider replays encrypted reasoning with its message.';
39
- const PREVIEW_ENTRY_MAX_LINES = 20;
40
41
  const DETAIL_CATEGORY_HEADER_LINE_COUNT = 1;
41
42
  const CURSOR_COLUMN_WIDTH = 2;
42
43
  const MAX_LEGEND_VALUE_COLUMN = 32;
@@ -96,9 +97,6 @@ export class UsageView implements ModalTab {
96
97
  private context: ModalTabContext | undefined;
97
98
  private mapScale: UsageMapScale = 'window';
98
99
  private currentWidth: number | undefined;
99
- private cachedPreviewEntries: readonly UsagePreviewEntry[] | undefined;
100
- private previewLines: string[] | undefined;
101
- private previewWrapWidth: number | undefined;
102
100
 
103
101
  /** Create a view over one precomputed usage snapshot. */
104
102
  public constructor(theme: Theme, input: UsageViewInput) {
@@ -167,8 +165,6 @@ export class UsageView implements ModalTab {
167
165
 
168
166
  /** Invalidate theme-dependent rendered output. */
169
167
  public invalidate(): void {
170
- this.previewLines = undefined;
171
- this.previewWrapWidth = undefined;
172
168
  this.cache.clear();
173
169
  }
174
170
 
@@ -239,7 +235,7 @@ export class UsageView implements ModalTab {
239
235
  const scaleTokens = this.mapScale === 'fit' ? this.fitMapScale : undefined;
240
236
  const map = buildUsageMap(this.usage, DEFAULT_MAP_COLUMNS, DEFAULT_MAP_ROWS, scaleTokens);
241
237
  if (map === undefined || width < MAP_SIDE_BY_SIDE_MIN_WIDTH) {
242
- return this.detailLines(width, rows, false).map(line => this.fit(line, width));
238
+ return this.detailLines(width, rows).map(line => this.fit(line, width));
243
239
  }
244
240
 
245
241
  const spaced = width >= SPACED_MAP_MIN_WIDTH;
@@ -252,7 +248,7 @@ export class UsageView implements ModalTab {
252
248
  const mapWidth = BODY_INDENT.length + map.columns + (spaced ? map.columns - 1 : 0);
253
249
  const gap = spaced ? SPACED_MAP_COLUMN_GAP : MAP_COLUMN_GAP;
254
250
  const detailWidth = Math.max(1, width - mapWidth - gap);
255
- const details = this.detailLines(detailWidth, rows, true);
251
+ const details = this.detailLines(detailWidth, rows, map.blockTokens, map.cells.length);
256
252
  const lineCount = Math.max(mapLines.length, details.length);
257
253
  return Array.from({ length: lineCount }, (_, index) => {
258
254
  const mapLine = mapLines[index] ?? ' '.repeat(mapWidth);
@@ -262,10 +258,10 @@ export class UsageView implements ModalTab {
262
258
  }
263
259
 
264
260
  /** Map-fill key, category heading, selectable category legend viewport, and scroll counter. */
265
- private detailLines(width: number, rows: number, includeMapKey: boolean): string[] {
261
+ private detailLines(width: number, rows: number, blockTokens?: number, cellCount?: number): string[] {
266
262
  const theme = this.theme;
267
- const showMapKey = includeMapKey && rows >= 4;
268
- const headerLineCount = DETAIL_CATEGORY_HEADER_LINE_COUNT + (showMapKey ? 2 : 0);
263
+ const mapKey = blockTokens === undefined || cellCount === undefined ? [] : this.mapKeyLines(width, rows, blockTokens, cellCount);
264
+ const headerLineCount = DETAIL_CATEGORY_HEADER_LINE_COUNT + mapKey.length;
269
265
  // The counter sits below the last legend row, so it consumes one of the available rows.
270
266
  const viewport = calculateViewport(this.legendRows.length, rows, headerLineCount);
271
267
  this.navigator.setVisibleCount(viewport.visibleCount);
@@ -286,17 +282,19 @@ export class UsageView implements ModalTab {
286
282
  const counterLines = viewport.showScroll
287
283
  ? [this.fit(theme.fg('dim', `${BODY_INDENT}(${this.navigator.visibleEnd}/${this.legendRows.length})`), width)]
288
284
  : [];
289
- return [...(showMapKey ? [this.mapKeyLine(width), ''] : []), heading, ...visibleRows, ...counterLines].slice(0, rows);
285
+ return [...mapKey, heading, ...visibleRows, ...counterLines].slice(0, rows);
290
286
  }
291
287
 
292
- /** Explain only the map's full and partial occupancy glyphs. */
293
- private mapKeyLine(width: number): string {
288
+ /** Explain map occupancy and the active token/share scale responsively. */
289
+ private mapKeyLines(width: number, rows: number, blockTokens: number, cellCount: number): string[] {
294
290
  const theme = this.theme;
295
291
  const heading = theme.fg('mdHeading', theme.bold('Map:'));
296
292
  const separator = theme.fg('dim', ' · ');
297
293
  const full = `${theme.fg('text', FULL_CELL)}${theme.fg('muted', ' Full')}`;
298
294
  const partial = `${theme.fg('text', PARTIAL_CELL)}${theme.fg('muted', ' Part')}`;
299
- return this.fit(`${heading} ${full}${separator}${partial}`, width);
295
+ const size = theme.fg('muted', `${formatTokens(Math.round(blockTokens))}/cell (${formatPercent(1 / cellCount)} of map)`);
296
+ if (rows < 5) return [this.fit(`${heading} ${size}`, width), ''];
297
+ return [this.fit(`${heading} ${full}${separator}${partial}`, width), this.fit(`${theme.fg('mdHeading', 'Block Size:')} ${size}`, width), ''];
300
298
  }
301
299
 
302
300
  /** Pi-reported usage/window metadata, with a marked estimate when current usage is unknown. */
@@ -413,48 +411,37 @@ export class UsageView implements ModalTab {
413
411
 
414
412
  // === Preview ===
415
413
 
416
- /** Open the selected category's content preview as a shell-managed layer. */
414
+ /** Open the selected category as a selectable chronological block stream. */
417
415
  private openPreview(): void {
418
416
  const row = this.legendRows[this.navigator.selected];
419
417
  if (row === undefined || row.type !== 'category') return;
420
- this.cachedPreviewEntries = undefined;
421
- this.previewLines = undefined;
422
- this.previewWrapWidth = undefined;
423
-
418
+ const entries = collectPreviewEntries(row.category);
419
+ const compactSkills = row.rootId === 'user-messages';
424
420
  const percent = this.plainLegendPercent(row.category.tokens);
425
421
  this.context?.pushLayer(
426
- new PreviewLayer(this.theme, {
422
+ new UsageBlockLayer(this.theme, {
427
423
  title: () => this.theme.fg('accent', this.theme.bold(normalizeInlineText(row.category.label))),
428
424
  meta: () => this.theme.fg('muted', `${formatTokens(row.category.tokens)}${percent === '' ? '' : ` · ${percent}`}`),
429
- body: width => this.previewBodyLines(width, row),
430
- description: width => this.previewDescriptionLines(width, row),
425
+ entries,
426
+ entryHeader: entry => this.entryHeader(entry),
427
+ entryBody: (entry, width) => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 1), compactSkills),
428
+ description: width => this.previewDescriptionLines(width, row, entries),
429
+ openFullContent: entry => this.openFullContent(row, entry, compactSkills),
431
430
  }),
432
431
  );
433
432
  }
434
433
 
435
- /** Cached wrapped entry stream: bracket headers plus capped sanitized content. */
436
- private previewBodyLines(width: number, row: CategoryLegendRow): string[] {
437
- const wrapWidth = Math.max(10, width - BODY_INDENT.length * 2 - 1);
438
- if (this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) return this.previewLines;
439
- const entries = this.previewEntries(row);
440
- const compactSkills = row.rootId === 'user-messages';
441
- const lines =
442
- entries.length === 0
443
- ? [this.fit(this.theme.fg('muted', `${BODY_INDENT}No content captured for this category.`), width)]
444
- : entries.flatMap((entry, index) => [
445
- ...(index === 0 ? [] : ['']),
446
- this.fit(`${BODY_INDENT}${this.entryHeader(entry)}`, width),
447
- ...this.entryContentLines(entry, wrapWidth, compactSkills),
448
- ]);
449
- this.previewLines = lines;
450
- this.previewWrapWidth = wrapWidth;
451
- return lines;
452
- }
453
-
454
- /** Collect and cache the immutable entries shared by preview body and description rendering. */
455
- private previewEntries(row: CategoryLegendRow): readonly UsagePreviewEntry[] {
456
- this.cachedPreviewEntries ??= collectPreviewEntries(row.category);
457
- return this.cachedPreviewEntries;
434
+ /** Push an uncapped scrollable view for one truncated block. */
435
+ private openFullContent(row: CategoryLegendRow, entry: UsagePreviewEntry, compactSkills: boolean): void {
436
+ const breadcrumb = entry.breadcrumb.map(normalizeInlineText).filter(Boolean).join(' / ');
437
+ this.context?.pushLayer(
438
+ new PreviewLayer(this.theme, {
439
+ title: () => this.theme.fg('accent', this.theme.bold(breadcrumb || normalizeInlineText(row.category.label))),
440
+ meta: () => this.theme.fg('muted', formatTokens(entry.tokens)),
441
+ // Match the block stream's two-column selection gutter so its hidden-line count stays exact.
442
+ body: width => this.entryContentLines(entry, Math.max(10, width - BODY_INDENT.length * 2 - 3), compactSkills),
443
+ }),
444
+ );
458
445
  }
459
446
 
460
447
  /** Bracketed entry header: dim datetime, breadcrumbs, visible tokens, and optional invisible reasoning. */
@@ -480,27 +467,25 @@ export class UsageView implements ModalTab {
480
467
  }
481
468
 
482
469
  /** Fixed explanation shown only when the thinking preview contains invisible-reasoning metadata. */
483
- private previewDescriptionLines(width: number, row: CategoryLegendRow): string[] {
470
+ private previewDescriptionLines(width: number, row: CategoryLegendRow, entries: readonly UsagePreviewEntry[]): string[] {
484
471
  if (row.rootId !== 'agent-thinking-messages') return [];
485
- const hasInvisibleReasoning = this.previewEntries(row).some(entry => entry.invisibleReasoning !== undefined);
472
+ const hasInvisibleReasoning = entries.some(entry => entry.invisibleReasoning !== undefined);
486
473
  return hasInvisibleReasoning ? wrapDescriptionLines(this.theme, INVISIBLE_REASONING_DESCRIPTION, 'dim', width) : [];
487
474
  }
488
475
 
489
476
  /** Sanitized, wrapped, per-entry-capped content lines indented under the header. */
490
477
  private entryContentLines(entry: UsagePreviewEntry, wrapWidth: number, compactSkills: boolean): string[] {
491
478
  const indent = BODY_INDENT.repeat(2);
492
- const lines: string[] = [];
493
- let hidden = 0;
494
- for (const paragraph of this.entryPreviewText(entry.text, compactSkills).split('\n')) {
495
- const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
496
- const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
497
- for (const line of paragraphLines) {
498
- if (lines.length < PREVIEW_ENTRY_MAX_LINES) lines.push(line === '' ? '' : `${indent}${line}`);
499
- else hidden++;
479
+ const wrapText = (text: string): string[] => {
480
+ const lines: string[] = [];
481
+ for (const paragraph of this.entryPreviewText(text, compactSkills).split('\n')) {
482
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
483
+ const paragraphLines = wrapped.length === 0 ? [''] : wrapped;
484
+ for (const line of paragraphLines) lines.push(line === '' ? '' : `${indent}${line}`);
500
485
  }
501
- }
502
- if (hidden === 0) return lines;
503
- return [...lines, `${indent}${this.theme.fg('dim', `… +${hidden} lines`)}`];
486
+ return lines;
487
+ };
488
+ return previewBodyLines(this.theme, entry, wrapWidth, wrapText);
504
489
  }
505
490
 
506
491
  /** Sanitize raw entry text and replace complete attached skills with pi-colored badges. */
@@ -253,7 +253,7 @@ function leafFromItem(item: InjectionItem): UsageCategory {
253
253
  id: `item:${item.id}`,
254
254
  label: item.label,
255
255
  tokens: item.tokens,
256
- entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text }],
256
+ entries: [{ breadcrumb: [item.label], tokens: item.tokens, text: item.text, sections: item.sections?.map(section => ({ ...section })) }],
257
257
  };
258
258
  }
259
259