@arhen/pi-senja 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -10,7 +10,8 @@ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte*
10
10
  - **A header** with shortcuts grouped by control, models, view, and input.
11
11
  - **A footer** with location, Git branch, session name, provider, model, thinking effort (including `max`), context bar, token usage, latest cache-hit rate, cost, OAuth subscription marker, and extension statuses.
12
12
  - **Flat tool output** — image captions, command results, and errors sit on the terminal background. Only source and diff lines get a quiet editor surface (Senja warm grey `#32302f`). Status dots and failure labels carry the state; user messages retain their own background.
13
- - **Grouped tool calls** — a single call stays on one line, e.g. `• write example.ts ▸`. Tool-call summaries can use the full pane width. Long titles truncate on one line, leaving room for the status and arrow. For runs longer than ten, the heading counts every call and failure, but only the latest ten calls are listed. Click **Show all** to reveal earlier calls above those ten, or **Show less** to fold history again. The control briefly brightens without scrolling through intermediate layouts (`REDUCE_MOTION=1` disables the feedback). Image reads keep Pi’s native inline image or text fallback, without a code gutter. Two or more consecutive calls to the same tool share a fixed heading, e.g. `• Ran codemode ×4 · 1 failed`. Each call occupies one tree line: `├─ script ▸` or `└─ script · failed ▸`. Click the line to open its indented native panel. The muted trailing icon changes to `▾`. Calls start collapsed by default. While running, the label has a subtle moving highlight without changing the row height (`REDUCE_MOTION=1` or `NO_COLOR=1` disables it). Click a call to open or close it at any time; partial output, success, and failure update its status without changing your choice. Expanded panels omit repeated titles and number script or file source lines (read offsets and native diff numbering are preserved). A text read opens to five wrapped lines; click its “more lines” hint to see the full read result. Image reads are not clipped. Opening a codemode row shows Pi’s native preview: at most five wrapped output lines. Click the result to see it in full; click it again to return to the preview. The row arrow closes the panel. Numbered source has a shaded row of padding above and below. Nested calls, output, and timing align with the script text, without an inner border. Pi’s tool expansion shortcut (default `Ctrl+O`) toggles all calls. Collapsed thinking is marked with a single-cell outline bulb (Nerd Font) beside `Thinking…` while streaming and `Thought` afterward. Inside a tool group, the bulb sits after the tree guide. Click the label to replace it with Pi’s thinking text without an icon, or the text to fold it back. A thinking-only turn between matching tools stays above the next call’s tree branch; elsewhere it stays in transcript order. Final replies have no marker. Parallel calls share the row once. Thinking follows its call through **Show all / Show less** and does not count toward the ten calls. A different tool or assistant prose starts a new group.
13
+ - **Grouped tool calls** — a single call stays on one line, e.g. `• Write example.ts ▸`. Codemode summaries can use the full pane width; all other tool summaries use at most 60% of the pane. Long titles truncate on one line, leaving room for the status and arrow. For runs longer than ten, the heading counts every call and failure, but only the latest ten calls are listed. Click **Show all** to reveal earlier calls above those ten, or **Show less** to fold history again. The control briefly brightens without scrolling through intermediate layouts (`REDUCE_MOTION=1` disables the feedback). Image reads keep Pi’s native inline image or text fallback, without a code gutter. Two or more consecutive calls to the same tool share a fixed heading, e.g. `• Ran codemode ×4 · 1 failed`. Each call occupies one tree line: `├─ script ▸` or `└─ script · failed ▸`. Click the line to open its indented native panel. The muted trailing icon changes to `▾`. Calls start collapsed by default. While running, the label has a subtle moving highlight without changing the row height (`REDUCE_MOTION=1` or `NO_COLOR=1` disables it). Click a call to open or close it at any time; partial output, success, and failure update its status without changing your choice. Expanded panels omit repeated titles and number script or file source lines (read offsets and native diff numbering are preserved). A text read opens to five wrapped lines; click its “more lines” hint to see the full read result. Image reads are not clipped. Opening a codemode row shows Pi’s native preview: at most five wrapped output lines. Click the result to see it in full; click it again to return to the preview. The row arrow closes the panel. Numbered source has a shaded row of padding above and below. Nested calls, output, and timing align with the script text, without an inner border. Pi’s tool expansion shortcut (default `Ctrl+O`) toggles all calls. Collapsed thinking is marked with a single-cell outline bulb (Nerd Font) beside `Thinking…` while streaming and `Thought` afterward. Inside a tool group, the bulb sits after the tree guide. Click the label to replace it with Pi’s thinking text without an icon, or the text to fold it back. A thinking-only turn between matching tools stays above the next call’s tree branch; elsewhere it stays in transcript order. Final replies have no marker. Parallel calls share the row once. Thinking follows its call through **Show all / Show less** and does not count toward the ten calls. A different tool or assistant prose starts a new group.
14
+ - **Shared transcript renderer** — compatible subagent views use the same renderer as the leader when Senja is enabled. Other Pi extensions can synchronously discover it via `pi.events.emit("pi:transcript-renderer", provider => { … })`. Mount with `provider.mount(chatContainer, tui, theme, starts?, cancelled?)`, render and send clicks to its `root`, and call `dispose()` when the view closes. The optional maps use tool call IDs and monotonic milliseconds (starts or frozen durations). With no provider, render the native container. This is opt-in for custom views; non-transcript panels are unchanged.
14
15
  - **Tool activity** — An unnamed call shows `preparing…`. As soon as Pi names it, the row shows `running`, even while the model writes the script. The timer starts at the first named call update and keeps counting through execution (`running 1m 30s`). Confirmed interruptions freeze that total (`cancelled · 8s`) without counting as failures.
15
16
  - **Codemode intent titles** — Senja asks the agent to put a short plan in a leading `// @title: Find the goal notice renderer` comment (after an optional `// @options:` line). The row displays that plan; expand it for the actual script and results. Untitled calls keep their script preview.
16
17
  - **Goal notices** — a `goal-ui` status starts as one clickable row. Open it for the original notice, including its objective, usage and commands.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arhen/pi-senja",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "Senja Gruvbox Material theme with Haiku's structured header, footer, and live timer for Pi.",
5
5
  "license": "MIT",
6
6
  "author": "arhen",
package/src/index.ts CHANGED
@@ -21,7 +21,7 @@ import type { ExtensionAPI, ExtensionContext, Theme, ThemeColor } from "@earendi
21
21
  import { VERSION } from "@earendil-works/pi-coding-agent";
22
22
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
23
23
 
24
- import { formatDuration, installToolGroups } from "./tool-groups.ts";
24
+ import { createTranscriptView, formatDuration, installToolGroups } from "./tool-groups.ts";
25
25
 
26
26
  // ── Visual primitives ────────────────────────────────────────────────────────
27
27
 
@@ -420,10 +420,13 @@ export default function (pi: ExtensionAPI) {
420
420
  const speedTiers = new Map<string, SpeedTier | null>();
421
421
  const unverifiedTiers = new Set<string>();
422
422
 
423
+ const guide =
424
+ "Start each codemode script with a // @title: comment describing its planned action in a short verb phrase (e.g. // @title: Find the goal notice renderer). If using // @options:, put the title on the next line.";
425
+ const unsubscribeTranscript = pi.events.on("pi:transcript-renderer", (accept) => {
426
+ if (enabled && typeof accept === "function") accept({ mount: createTranscriptView, codemodeGuide: guide });
427
+ });
423
428
  pi.on("before_agent_start", (event, ctx) => {
424
429
  if (!enabled || ctx.mode !== "tui" || !event.systemPromptOptions?.selectedTools.includes("codemode")) return;
425
- const guide =
426
- "Start each codemode script with a // @title: comment describing its planned action in a short verb phrase (e.g. // @title: Find the goal notice renderer). If using // @options:, put the title on the next line.";
427
430
  const { promptGuidelines } = event.systemPromptOptions;
428
431
  if (!promptGuidelines.includes(guide)) promptGuidelines.push(guide);
429
432
  });
@@ -851,6 +854,7 @@ export default function (pi: ExtensionAPI) {
851
854
  pi.on("session_shutdown", () => {
852
855
  starts.clear();
853
856
  cancelled.clear();
857
+ unsubscribeTranscript();
854
858
  unsubscribeMode();
855
859
  modeWorkingMessage = undefined;
856
860
  clearWorkingTimers();
@@ -30,7 +30,12 @@ type ToolRow = Component & {
30
30
  isPartial: boolean;
31
31
  expanded: boolean;
32
32
  outputPad?: number;
33
- result?: { isError: boolean; durationMs?: number; content?: { type: string; text?: string }[] };
33
+ result?: {
34
+ isError: boolean;
35
+ durationMs?: number;
36
+ details?: { diff?: string };
37
+ content?: { type: string; text?: string }[];
38
+ };
34
39
  setExpanded(value: boolean): void;
35
40
  };
36
41
 
@@ -235,19 +240,23 @@ function indentedDetails(
235
240
  tool.toolName === "codemode" && codeEnd > top ? gutter : Math.max(0, innerPad - (tool.outputPad ?? 1));
236
241
  const resultIndent = " ".repeat(outputGutter);
237
242
  const fills = (["toolPendingBg", "toolSuccessBg", "toolErrorBg"] as const).map((role) => theme.getBgAnsi(role));
243
+ const diff =
244
+ tool.toolName === "edit" &&
245
+ !tool.result?.isError &&
246
+ !!(tool.result?.details?.diff || Reflect.get(tool, "rendererState")?.callComponent?.preview?.diff);
247
+ const surface = (text: string) => theme.bg("toolSuccessBg", text.replace(/\x1b\[(?:0?|49)m/g, "$&" + fills[1]));
238
248
  const body = lines.slice(top, displayEnd).map((line, i) => {
239
249
  // Graphics sequences and their reserved rows belong to Pi's image renderer.
240
250
  if (image && (!line.trim() || line.includes("\x1b_G") || line.includes("\x1b]1337;File="))) return guide + line;
241
251
  let content = i === 0 && labelEnd ? sliceByColumn(line, labelEnd, contentWidth) : line;
242
252
  for (const fill of fills) if (fill) content = content.replaceAll(fill, "");
243
253
  const code = top + i < codeEnd;
244
- const diff = tool.toolName === "edit" && !tool.result?.isError && /^\s*[+-]?\s*\d+\s/.test(plain(content));
245
254
  if (!code && !diff) return guide + resultIndent + content;
246
255
  const number = numbers.get(top + i);
247
256
  const cell = number && gutter ? ` ${theme.fg("dim", number.padStart(digits))} ` : " ".repeat(gutter);
248
- return guide + theme.bg("toolSuccessBg", cell + content);
257
+ return guide + surface(cell + content);
249
258
  });
250
- editorRows = codeEnd - top;
259
+ editorRows = diff ? body.length : codeEnd - top;
251
260
  padTop = !image && (editorRows || body.length > 1) ? 1 : 0;
252
261
  padBottom = !image && body.length > 1 && editorRows !== body.length ? 1 : 0;
253
262
  if (padBottom) body.push(guide);
@@ -352,6 +361,30 @@ export function installToolGroups(
352
361
  const [header, resources, chat] = document.children;
353
362
  if (!(header instanceof Container && resources instanceof Container && chat instanceof Container)) return;
354
363
 
364
+ const mounted = createTranscriptView(chat, tui, theme, starts, cancelled, () => {
365
+ const viewport =
366
+ "getPrimaryScrollView" in tui && typeof tui.getPrimaryScrollView === "function"
367
+ ? tui.getPrimaryScrollView()
368
+ : undefined;
369
+ viewport?.scrollTo(viewport.scrollTop, { disableFollow: true });
370
+ });
371
+ document.children[2] = mounted.root;
372
+ return {
373
+ dispose() {
374
+ mounted.dispose();
375
+ if (document.children[2] === mounted.root) document.children[2] = chat;
376
+ },
377
+ };
378
+ }
379
+
380
+ export function createTranscriptView(
381
+ chat: Container,
382
+ tui: TUI,
383
+ theme: Theme,
384
+ starts?: ReadonlyMap<string, number>,
385
+ cancelled?: ReadonlyMap<string, number | undefined>,
386
+ holdScroll?: () => void,
387
+ ) {
355
388
  const blockGap = new Spacer(1);
356
389
  const branchGap: Component = {
357
390
  render: (width) => [width >= 8 ? theme.fg("dim", " │") : ""],
@@ -398,6 +431,64 @@ export function installToolGroups(
398
431
  const previews = new WeakSet<Component>();
399
432
  type Thought = ReturnType<typeof thinkingRow>;
400
433
  const originals = new WeakMap<Component, MouseRegion>();
434
+ const styledMarkdown = new WeakSet<Markdown>();
435
+ function styleFences(part: Markdown) {
436
+ if (styledMarkdown.has(part) || Object.hasOwn(part, "renderToken")) return;
437
+ const native = Reflect.get(part, "renderToken");
438
+ if (typeof native !== "function") return;
439
+ // ponytail: Pi has no block renderer hook; override this instance only while its native token method exists.
440
+ Reflect.set(
441
+ part,
442
+ "renderToken",
443
+ (token: { type: string; text: string; lang?: string; raw?: string }, width: number, ...rest: unknown[]) => {
444
+ if (token.type !== "code" || !/^ {0,3}(?:`{3,}|~{3,})/.test(token.raw ?? "") || width < 1)
445
+ return native.call(part, token, width, ...rest);
446
+ const source = stripTerminalSequences(token.text)
447
+ .replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, "")
448
+ .replace(/\t/g, " ")
449
+ .split("\n");
450
+ const lang = summary(token.lang).split(" ")[0] || "code";
451
+ const framed = width >= 24;
452
+ const rim = framed ? 2 : 0;
453
+ const pad = width >= 8 ? 2 : 0;
454
+ const inner = Math.min(
455
+ width - 2 * (pad + rim),
456
+ source.reduce((n, s) => Math.max(n, visibleWidth(s)), Math.max(18, visibleWidth(lang) + 12)),
457
+ );
458
+ const matte = (length: number) => {
459
+ const space = " ".repeat(length);
460
+ return theme.colors
461
+ ? theme.style(space, { bg: theme.colors.customMessageLabel })
462
+ : theme.bg("customMessageBg", space);
463
+ };
464
+ const edge = matte(rim);
465
+ const line = (text: string) =>
466
+ edge +
467
+ theme.bg(
468
+ "toolSuccessBg",
469
+ " ".repeat(pad) + text + " ".repeat(Math.max(0, inner + pad - visibleWidth(text))),
470
+ ) +
471
+ edge;
472
+ const cap = matte(inner + 2 * (pad + rim));
473
+ const dots = framed
474
+ ? [theme.fg("error", "●"), theme.fg("warning", "●"), theme.fg("success", "●")].join(" ")
475
+ : "";
476
+ const label = truncateToWidth(lang, inner - visibleWidth(dots), "…");
477
+ const gap = Math.max(0, Math.floor((inner - visibleWidth(label)) / 2) - visibleWidth(dots));
478
+ const lines = [line(dots + " ".repeat(gap) + theme.fg("muted", label)), line("")];
479
+ if (framed) lines.unshift(cap);
480
+ for (const logical of source) {
481
+ for (const row of wrapTextWithAnsi(logical, inner)) lines.push(line(theme.fg("text", row)));
482
+ }
483
+ lines.push(line(""));
484
+ if (framed) lines.push(cap);
485
+ if (rest[0] && rest[0] !== "space") lines.push("");
486
+ return lines;
487
+ },
488
+ );
489
+ styledMarkdown.add(part);
490
+ part.invalidate();
491
+ }
401
492
  function styleThoughts(message: AssistantMessageComponent): Thought[] | undefined {
402
493
  const [content] = message.children;
403
494
  if (message.children.length !== 1 || !(content instanceof Container)) return;
@@ -405,6 +496,7 @@ export function installToolGroups(
405
496
  let onlyThoughts = true;
406
497
  for (const [i, part] of content.children.entries()) {
407
498
  if (part instanceof Spacer) continue;
499
+ if (part instanceof Markdown) styleFences(part);
408
500
  const region = originals.get(part) ?? part;
409
501
  const child = region instanceof MouseRegion ? Reflect.get(region, "child") : undefined;
410
502
  if (!(region instanceof MouseRegion) || !(child instanceof Text || child instanceof Markdown)) {
@@ -447,10 +539,7 @@ export function installToolGroups(
447
539
  if (showAll.has(first)) showAll.delete(first);
448
540
  else {
449
541
  showAll.add(first);
450
- if ("getPrimaryScrollView" in tui && typeof tui.getPrimaryScrollView === "function") {
451
- const viewport = tui.getPrimaryScrollView();
452
- viewport?.scrollTo(viewport.scrollTop, { disableFollow: true });
453
- }
542
+ holdScroll?.();
454
543
  }
455
544
  if (motion) {
456
545
  clearTimeout(settle);
@@ -514,7 +603,7 @@ export function installToolGroups(
514
603
  const settled = interrupted ? "muted" : "success";
515
604
  const role = failed ? "error" : run.some((tool) => tool.isPartial) ? "warning" : settled;
516
605
  const dot = theme.fg(role, "•");
517
- const action = theme.bold(theme.fg("customMessageLabel", verb || summary(name)));
606
+ const action = theme.bold(theme.fg("customMessageLabel", verb || (name === "edit" ? "Edit" : "Write")));
518
607
  return ` ${dot} ${action}${verb ? ` ${theme.fg("toolTitle", summary(name))}` : ""}`;
519
608
  };
520
609
  rows.push(blockGap);
@@ -567,7 +656,8 @@ export function installToolGroups(
567
656
  state === "cancelled" ? (cancelled?.get(tool.toolCallId) ?? tool.result?.durationMs) : undefined;
568
657
  const elapsed = start === undefined ? "" : formatDuration(performance.now() - start);
569
658
  const regions = before.get(tool);
570
- const branch = grouped && width >= 9 ? (last ? " └─ " : " ├─ ") : "";
659
+ const rowWidth = name === "codemode" ? width : Math.max(1, Math.floor(width * 0.6));
660
+ const branch = grouped && rowWidth >= 9 ? (last ? " └─ " : " ├─ ") : "";
571
661
  const guide = width < 8 ? "" : !grouped ? " " : last ? " " : " │ ";
572
662
  if (regions) {
573
663
  for (const row of regions) {
@@ -581,7 +671,7 @@ export function installToolGroups(
581
671
  const labelKey = `${revision}:${width}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
582
672
  if (labelKey !== call.labelKey) {
583
673
  call.labelKey = labelKey;
584
- const available = width - branch.length - 2;
674
+ const available = rowWidth - branch.length - 2;
585
675
  let suffix = state ? ` · ${state}` : "";
586
676
  if (duration !== undefined) {
587
677
  const timed = `${suffix} · ${formatDuration(duration)}`;
@@ -596,7 +686,7 @@ export function installToolGroups(
596
686
  const caption = grouped ? label : !name ? " •" : subject ? `${heading()} ${label}` : heading();
597
687
  const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(status)), "…");
598
688
  const line = `${script}${status} ${icon}`;
599
- call.label.setText(width <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
689
+ call.label.setText(rowWidth <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
600
690
  }
601
691
  rows.push(call.row);
602
692
  if (open) {
@@ -659,8 +749,8 @@ export function installToolGroups(
659
749
  view.children = rows;
660
750
  return render(width);
661
751
  };
662
- document.children[2] = view;
663
752
  return {
753
+ root: view,
664
754
  dispose() {
665
755
  clearInterval(animation);
666
756
  clearTimeout(settle);
@@ -669,12 +759,15 @@ export function installToolGroups(
669
759
  const [content] = message.children;
670
760
  if (content instanceof Container) {
671
761
  for (const [i, part] of content.children.entries()) {
762
+ if (part instanceof Markdown && styledMarkdown.has(part)) {
763
+ Reflect.deleteProperty(part, "renderToken");
764
+ part.invalidate();
765
+ }
672
766
  const original = originals.get(part);
673
767
  if (original) content.children[i] = original;
674
768
  }
675
769
  }
676
770
  }
677
- if (document.children[2] === view) document.children[2] = chat;
678
771
  },
679
772
  };
680
773
  }