@pi-kaush/pi-content-layout 0.1.1 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ - Restyle user-run bash blocks (`!` commands) with the submitted-prompt rail
6
+ shell: Pi's green top/bottom rules are replaced by the dark surface with a
7
+ left rail, command first and output below. The rail stays `bashMode` green
8
+ while running and on success, turns `error` red on a non-zero exit and
9
+ `warning` yellow when cancelled, and stays dim for `!!` commands excluded
10
+ from context.
11
+
5
12
  - Pad submitted message text two columns right of the accent rail (one extra leading space inside the body) for more breathing room in the chat log.
6
13
  - Paint the active editor surface and submitted message body with a fixed
7
14
  `#071312` background (`PROMPT_SURFACE_BG`) instead of the theme's `selectedBg`
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # pi-content-layout
2
2
 
3
- A small Pi extension that insets the main conversation, renders the active editor as a full-width dark surface, and gives submitted prompts a compact rail shell.
3
+ A small Pi extension that insets the main conversation, renders the active editor as a full-width dark surface, and gives submitted prompts and user-run bash blocks a compact rail shell.
4
4
 
5
5
  ```text
6
6
  Assistant output
@@ -15,10 +15,19 @@ Submitted prompt
15
15
  ▎ darker background
16
16
  ▎ prompt text darker background
17
17
  ▎ darker background
18
+
19
+ User bash (`!` command, failed)
20
+ ▎ darker background, red rail
21
+ ▎ $ ls ~/matrxi darker background
22
+ ▎ ls: /Users/kg/matrxi: No such file or directory
23
+ ▎ (exit 1) darker background
24
+ ▎ darker background
18
25
  ```
19
26
 
20
27
  Assistant and submitted-message content keep the two-column outer inset. The active prompt intentionally ignores that inset: its darker background fills the terminal width, with no rail, one extra layout column on each side of Pi's configured editor padding, and one background-colored row above and below the content. Real scroll indicators replace the corresponding padding row when needed. The submitted prompt remains unchanged: it keeps Pi's message padding and the thin rail outside its darker body. Autocomplete stays outside the active surface.
21
28
 
29
+ User-run bash blocks (`!` commands) trade Pi's green top/bottom rules for the same rail shell as the submitted prompt, command first and output below. The rail keeps the usual green while running and on success, turns red on a non-zero exit, yellow when cancelled, and stays dim for `!!` commands excluded from context.
30
+
22
31
  ## Install
23
32
 
24
33
  ```json
@@ -34,8 +43,9 @@ The package is not published while its version is `0.0.0`; use the repository pa
34
43
  The active editor surface and submitted message body paint with a fixed
35
44
  near-black `#071312` background (`PROMPT_SURFACE_BG`) so both user-input
36
45
  surfaces stay identical; the theme's `selectedBg` token continues to serve
37
- selections and dialogs. The extension consumes two theme tokens: `accent`
38
- for the submitted-prompt rail and `muted` for the editor scroll hints.
46
+ selections and dialogs. The extension consumes theme tokens for its rails and hints: `accent`
47
+ for the submitted-prompt rail, `muted` for the editor scroll hints, and
48
+ `bashMode` / `error` / `warning` / `dim` for the user-bash rail.
39
49
 
40
50
  Themes control colors, while this extension controls width and component
41
51
  shape; a theme cannot provide the layout itself.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-kaush/pi-content-layout",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Inset Pi's conversation surface and style active and submitted prompts as matching blocks.",
5
5
  "license": "MIT",
6
6
  "author": "Kaushik Gopal",
package/src/index.ts CHANGED
@@ -1,12 +1,19 @@
1
1
  import {
2
2
  AssistantMessageComponent,
3
+ BashExecutionComponent,
3
4
  CustomEditor,
4
5
  type ExtensionAPI,
5
6
  type KeybindingsManager,
6
7
  type Theme,
7
8
  UserMessageComponent,
8
9
  } from "@earendil-works/pi-coding-agent";
9
- import type { EditorComponent, EditorTheme, TUI } from "@earendil-works/pi-tui";
10
+ import {
11
+ type EditorComponent,
12
+ type EditorTheme,
13
+ Loader,
14
+ type TUI,
15
+ visibleWidth,
16
+ } from "@earendil-works/pi-tui";
10
17
  import {
11
18
  chatContainerHooks,
12
19
  runChatContainerHooks,
@@ -14,7 +21,9 @@ import {
14
21
  import {
15
22
  contentInset,
16
23
  insetLines,
24
+ PROMPT_RAIL,
17
25
  renderActiveEditor,
26
+ renderBashBlockLines,
18
27
  renderSubmittedUserLines,
19
28
  } from "./render.ts";
20
29
 
@@ -25,6 +34,12 @@ const USER_RENDER_PATCH = Symbol.for("kg.pi.contentLayout.userRender.v1");
25
34
  const SYSTEM_CONTAINER_RENDER_PATCH = Symbol.for(
26
35
  "kg.pi.contentLayout.systemContainerRender.v1",
27
36
  );
37
+ const STATUS_LOADER_RENDER_PATCH = Symbol.for(
38
+ "kg.pi.contentLayout.statusLoaderRender.v1",
39
+ );
40
+ const BASH_EXECUTION_RENDER_PATCH = Symbol.for(
41
+ "kg.pi.contentLayout.bashExecutionRender.v1",
42
+ );
28
43
 
29
44
  type EditorFactory = (
30
45
  tui: TUI,
@@ -49,10 +64,58 @@ type NativeTextRow = RenderRow & {
49
64
  customBgFn?: unknown;
50
65
  };
51
66
 
67
+ type LoaderRow = RenderRow & {
68
+ kind?: unknown;
69
+ paddingX?: unknown;
70
+ };
71
+
72
+ type BashExecutionRow = RenderRow & {
73
+ status?: unknown;
74
+ };
75
+
52
76
  type RenderPatchState = {
53
77
  originalRender: (this: RenderRow, width: number) => string[];
54
78
  patchedRender: (this: RenderRow, width: number) => string[];
55
79
  owners: Map<object, ThemeGetter>;
80
+ cache: WeakMap<object, RenderCacheEntry>;
81
+ };
82
+
83
+ type RenderCacheEntry = {
84
+ width: number;
85
+ src: string[];
86
+ lines: string[];
87
+ };
88
+
89
+ // ==================================================================
90
+ // Render memoization — PLEASE DO NOT REMOVE OR "SIMPLIFY" THIS CACHE.
91
+ // ==================================================================
92
+ //
93
+ // Pi's TUI re-renders the ENTIRE transcript on every keystroke (the frame
94
+ // walk is O(session) in pi-tui 0.84.x; upstream viewport-windowing work is
95
+ // not merged yet). Components normally stay fast because leaf components
96
+ // reuse cached line strings until their content changes. This package,
97
+ // however, decorates message lines AFTER rendering — building brand-new
98
+ // strings (insets, rails, backgrounds) for every line of every message on
99
+ // every frame. Measured on a ~1,000-message session that cost ~90 ms per
100
+ // keystroke and made the input box visibly lag as sessions grew.
101
+ //
102
+ // The cache below makes decoration cost O(changed messages) instead of
103
+ // O(all messages): decorators compare the freshly rendered source lines
104
+ // against the lines they decorated last frame BY IDENTITY (=== per element)
105
+ // and reuse the decorated output when nothing changed. Identity comparison
106
+ // is what makes the cache self-invalidating across every change path —
107
+ // streaming chunks, content edits, theme switches — because all of those
108
+ // regenerate the source strings upstream of us. This is why there is no
109
+ // explicit invalidate wiring here: partial invalidation would be worse than
110
+ // none, and identity checks can never miss a real change.
111
+ //
112
+ // If typing ever gets slow again in long sessions, suspect this cache first.
113
+ // ==================================================================
114
+ type RenderMemo = {
115
+ /** Decorated lines from the last frame, when `src` is unchanged. */
116
+ hit(src: string[]): string[] | undefined;
117
+ /** Record decorated output keyed by the source lines that produced it. */
118
+ store(src: string[], out: string[]): void;
56
119
  };
57
120
 
58
121
  type RenderDecorator = (
@@ -60,6 +123,7 @@ type RenderDecorator = (
60
123
  row: RenderRow,
61
124
  width: number,
62
125
  theme: Theme,
126
+ memo: RenderMemo,
63
127
  ) => string[];
64
128
 
65
129
  type PatchableRenderPrototype = RenderRow &
@@ -87,14 +151,32 @@ function installRenderPatch(
87
151
  const state = {} as RenderPatchState;
88
152
  state.originalRender = prototype.render;
89
153
  state.owners = new Map([[owner, getTheme]]);
154
+ state.cache = new WeakMap();
90
155
  state.patchedRender = function renderWithContentLayout(
91
156
  this: RenderRow,
92
157
  width: number,
93
158
  ): string[] {
94
159
  const theme = currentTheme(state);
95
160
  if (!theme) return state.originalRender.call(this, width);
161
+ // See the memoization block above RenderMemo: decorators get a memo
162
+ // bound to this row + width so unchanged rows skip string building.
163
+ const entry = state.cache.get(this);
164
+ const memo: RenderMemo = {
165
+ hit: (src: string[]): string[] | undefined => {
166
+ if (!entry || entry.width !== width) return undefined;
167
+ const prev = entry.src;
168
+ if (prev.length !== src.length) return undefined;
169
+ for (let i = 0; i < src.length; i++) {
170
+ if (prev[i] !== src[i]) return undefined;
171
+ }
172
+ return entry.lines;
173
+ },
174
+ store: (src: string[], out: string[]): void => {
175
+ state.cache.set(this, { width, src, lines: out });
176
+ },
177
+ };
96
178
  try {
97
- return decorate(state.originalRender, this, width, theme);
179
+ return decorate(state.originalRender, this, width, theme, memo);
98
180
  } catch {
99
181
  return state.originalRender.call(this, width);
100
182
  }
@@ -131,6 +213,8 @@ function assistantDecorator(
131
213
  original: RenderPatchState["originalRender"],
132
214
  row: RenderRow,
133
215
  width: number,
216
+ _theme: Theme,
217
+ memo: RenderMemo,
134
218
  ): string[] {
135
219
  const nativeInset = Math.max(
136
220
  0,
@@ -139,7 +223,11 @@ function assistantDecorator(
139
223
  const inset = Math.max(0, contentInset(width) - nativeInset);
140
224
  if (inset === 0) return original.call(row, width);
141
225
  const lines = original.call(row, Math.max(1, width - inset * 2));
142
- return insetLines(lines, width, inset);
226
+ const cached = memo.hit(lines);
227
+ if (cached) return cached;
228
+ const decorated = insetLines(lines, width, inset);
229
+ memo.store(lines, decorated);
230
+ return decorated;
143
231
  }
144
232
 
145
233
  function isChatMessageChild(child: unknown): boolean {
@@ -212,10 +300,31 @@ function systemTextHook(
212
300
  };
213
301
  }
214
302
 
303
+ // Status indicators (Working/Retry/Compaction/BranchSummary) sit in a
304
+ // sibling container that the chat-child hooks never see, so they need their
305
+ // own inset to line up with the chat content. StatusIndicator marks Loader
306
+ // subclasses with a `kind`; bare Loaders inside tool boxes keep native
307
+ // layout.
308
+ function statusLoaderDecorator(
309
+ original: RenderPatchState["originalRender"],
310
+ row: RenderRow,
311
+ width: number,
312
+ ): string[] {
313
+ if (typeof (row as LoaderRow).kind !== "string")
314
+ return original.call(row, width);
315
+ const nativeInset = Math.max(0, Number((row as LoaderRow).paddingX) || 0);
316
+ const inset = Math.max(0, contentInset(width) - nativeInset);
317
+ if (inset === 0) return original.call(row, width);
318
+ const lines = original.call(row, Math.max(1, width - inset * 2));
319
+ return insetLines(lines, width, inset);
320
+ }
321
+
215
322
  function systemContainerDecorator(
216
323
  original: RenderPatchState["originalRender"],
217
324
  row: RenderRow,
218
325
  width: number,
326
+ _theme: Theme,
327
+ memo: RenderMemo,
219
328
  ): string[] {
220
329
  const restore = runChatContainerHooks(
221
330
  row,
@@ -223,23 +332,64 @@ function systemContainerDecorator(
223
332
  width,
224
333
  );
225
334
  try {
226
- return original.call(row, width);
335
+ const lines = original.call(row, width);
336
+ // Decoration happens inside the children during the original call, so
337
+ // the decorated output IS the source output; cache it the same way so
338
+ // downstream containers reuse the array instead of re-concatenating.
339
+ const cached = memo.hit(lines);
340
+ if (cached) return cached;
341
+ memo.store(lines, lines);
342
+ return lines;
227
343
  } finally {
228
344
  restore();
229
345
  }
230
346
  }
231
347
 
348
+ // User-run bash blocks (`!` commands) take the submitted-prompt shell: the
349
+ // native green rules are replaced by the rail and dark surface, with the rail
350
+ // recolored from the command's outcome (green normally, red on a non-zero
351
+ // exit, yellow when cancelled).
352
+ function bashExecutionDecorator(
353
+ original: RenderPatchState["originalRender"],
354
+ row: RenderRow,
355
+ width: number,
356
+ theme: Theme,
357
+ memo: RenderMemo,
358
+ ): string[] {
359
+ const inset = contentInset(width);
360
+ const bodyWidth = width - inset * 2 - visibleWidth(PROMPT_RAIL);
361
+ if (inset === 0 || bodyWidth < 8) return original.call(row, width);
362
+ const lines = original.call(row, Math.max(1, bodyWidth));
363
+ const cached = memo.hit(lines);
364
+ if (cached) return cached;
365
+ const status = (row as BashExecutionRow).status;
366
+ const decorated = renderBashBlockLines(
367
+ lines,
368
+ width,
369
+ theme,
370
+ typeof status === "string" ? status : undefined,
371
+ inset,
372
+ );
373
+ memo.store(lines, decorated);
374
+ return decorated;
375
+ }
376
+
232
377
  function userDecorator(
233
378
  original: RenderPatchState["originalRender"],
234
379
  row: RenderRow,
235
380
  width: number,
236
381
  theme: Theme,
382
+ memo: RenderMemo,
237
383
  ): string[] {
238
384
  const inset = contentInset(width);
239
385
  const bodyWidth = width - inset * 2 - 1;
240
386
  if (inset === 0 || bodyWidth < 1) return original.call(row, width);
241
387
  const lines = original.call(row, bodyWidth);
242
- return renderSubmittedUserLines(lines, width, theme, inset);
388
+ const cached = memo.hit(lines);
389
+ if (cached) return cached;
390
+ const decorated = renderSubmittedUserLines(lines, width, theme, inset);
391
+ memo.store(lines, decorated);
392
+ return decorated;
243
393
  }
244
394
 
245
395
  function decorateEditor(
@@ -275,6 +425,8 @@ export default function contentLayout(pi: ExtensionAPI): void {
275
425
  let assistantPatch: RenderPatchState | undefined;
276
426
  let userPatch: RenderPatchState | undefined;
277
427
  let systemContainerPatch: RenderPatchState | undefined;
428
+ let statusLoaderPatch: RenderPatchState | undefined;
429
+ let bashExecutionPatch: RenderPatchState | undefined;
278
430
  let editorRegistration:
279
431
  | {
280
432
  factory: EditorFactory;
@@ -317,6 +469,20 @@ export default function contentLayout(pi: ExtensionAPI): void {
317
469
  getTheme,
318
470
  systemContainerDecorator,
319
471
  );
472
+ statusLoaderPatch = installRenderPatch(
473
+ Loader.prototype as unknown as PatchableRenderPrototype,
474
+ STATUS_LOADER_RENDER_PATCH,
475
+ owner,
476
+ getTheme,
477
+ statusLoaderDecorator,
478
+ );
479
+ bashExecutionPatch = installRenderPatch(
480
+ BashExecutionComponent.prototype as unknown as PatchableRenderPrototype,
481
+ BASH_EXECUTION_RENDER_PATCH,
482
+ owner,
483
+ getTheme,
484
+ bashExecutionDecorator,
485
+ );
320
486
 
321
487
  const previous = ctx.ui.getEditorComponent() as EditorFactory | undefined;
322
488
  const factory: EditorFactory = (tui, editorTheme, keybindings) => {
@@ -359,9 +525,23 @@ export default function contentLayout(pi: ExtensionAPI): void {
359
525
  owner,
360
526
  systemContainerPatch,
361
527
  );
528
+ uninstallRenderPatch(
529
+ Loader.prototype as unknown as PatchableRenderPrototype,
530
+ STATUS_LOADER_RENDER_PATCH,
531
+ owner,
532
+ statusLoaderPatch,
533
+ );
534
+ uninstallRenderPatch(
535
+ BashExecutionComponent.prototype as unknown as PatchableRenderPrototype,
536
+ BASH_EXECUTION_RENDER_PATCH,
537
+ owner,
538
+ bashExecutionPatch,
539
+ );
362
540
  assistantPatch = undefined;
363
541
  userPatch = undefined;
364
542
  systemContainerPatch = undefined;
543
+ statusLoaderPatch = undefined;
544
+ bashExecutionPatch = undefined;
365
545
  activeTheme = undefined;
366
546
  });
367
547
  }
package/src/render.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { Theme } from "@earendil-works/pi-coding-agent";
1
+ import type { Theme, ThemeColor } from "@earendil-works/pi-coding-agent";
2
2
  import type { EditorComponent } from "@earendil-works/pi-tui";
3
3
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
4
4
 
@@ -196,6 +196,7 @@ export function renderSubmittedUserLines(
196
196
  width: number,
197
197
  theme: Theme,
198
198
  inset = contentInset(width),
199
+ railColor: ThemeColor = "accent",
199
200
  ): string[] {
200
201
  const blockWidth = width - inset * 2;
201
202
  if (inset === 0 || blockWidth <= visibleWidth(PROMPT_RAIL)) {
@@ -207,7 +208,7 @@ export function renderSubmittedUserLines(
207
208
  return lines.map((line) => {
208
209
  const { controls, content } = splitLeadingSemanticControls(line);
209
210
  const recolored = replaceBackground(content, PROMPT_SURFACE_BG);
210
- const rail = theme.fg("accent", PROMPT_RAIL);
211
+ const rail = theme.fg(railColor, PROMPT_RAIL);
211
212
  // One extra leading space inside the body, so submitted text sits two
212
213
  // columns right of the rail instead of one.
213
214
  const body = paintBackground(
@@ -218,3 +219,62 @@ export function renderSubmittedUserLines(
218
219
  return `${controls}${margin}${rail}${body}${margin}`;
219
220
  });
220
221
  }
222
+
223
+ const RULE_LINE_RE = /^─+$/;
224
+
225
+ function isRuleLine(line: string | undefined): line is string {
226
+ return line !== undefined && RULE_LINE_RE.test(stripDisplayAnsi(line).trim());
227
+ }
228
+
229
+ // `!!` commands draw their rules dim instead of bashMode green, but the
230
+ // component does not store that flag, so sniff the top rule's color to keep
231
+ // the rail consistent with the framing it replaces.
232
+ function sniffsDimRule(rule: string, theme: Theme): boolean {
233
+ const prefixOf = (colored: string) => colored.slice(0, colored.indexOf("─"));
234
+ const dimPrefix = prefixOf(theme.fg("dim", "─"));
235
+ return (
236
+ dimPrefix.length > 0 &&
237
+ dimPrefix !== prefixOf(theme.fg("bashMode", "─")) &&
238
+ rule.startsWith(dimPrefix)
239
+ );
240
+ }
241
+
242
+ // Rail tone for a user bash block: failures read red and cancellations
243
+ // yellow, matching the block's status text; anything else keeps the green
244
+ // the rules used (dim for `!!` commands).
245
+ export function bashBlockRailColor(
246
+ status: string | undefined,
247
+ topRule: string | undefined,
248
+ theme: Theme,
249
+ ): ThemeColor {
250
+ if (status === "error") return "error";
251
+ if (status === "cancelled") return "warning";
252
+ if (topRule !== undefined && sniffsDimRule(topRule, theme)) return "dim";
253
+ return "bashMode";
254
+ }
255
+
256
+ // Reshapes BashExecutionComponent output into the submitted-prompt shell: the
257
+ // leading spacer stays outside the block, the top/bottom rules are dropped,
258
+ // and the remaining lines get one blank padded row at each end plus the rail
259
+ // and dark surface.
260
+ export function renderBashBlockLines(
261
+ lines: string[],
262
+ width: number,
263
+ theme: Theme,
264
+ status: string | undefined,
265
+ inset = contentInset(width),
266
+ ): string[] {
267
+ const [spacer, ...rest] = lines;
268
+ const topRule = isRuleLine(rest[0]) ? rest[0] : undefined;
269
+ const inner = topRule !== undefined ? rest.slice(1) : rest.slice();
270
+ if (isRuleLine(inner[inner.length - 1])) inner.pop();
271
+ const railColor = bashBlockRailColor(status, topRule, theme);
272
+ const block = renderSubmittedUserLines(
273
+ ["", ...inner, ""],
274
+ width,
275
+ theme,
276
+ inset,
277
+ railColor,
278
+ );
279
+ return [fitLine(spacer ?? "", width), ...block];
280
+ }