@arhen/pi-senja 1.5.1 → 1.5.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/README.md CHANGED
@@ -12,7 +12,7 @@ Forked from [pi-haiku](https://github.com/nnocte/pi-haiku) **0.2.0** by **nocte*
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
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
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.
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
+ - **Tool activity** — A call shows `preparing…` without a timer while Pi receives its arguments. Pi’s execution-start event switches the row to `running 0s`; writing the script does not count. Expanded results keep Pi’s own reported duration. Confirmed interruptions show `cancelled` before execution, or `cancelled · 8s` after it starts, without counting as failures.
16
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.
17
17
  - **Goal notices** — a `goal-ui` status starts as one clickable row. Open it for the original notice, including its objective, usage and commands.
18
18
  - **Quiet tool text** — action labels such as `Ran` use muted teal (`#7daea3`) to distinguish tools from assistant prose. Tool names following a verb and tool output use the foreground beige (`fg0`) rather than loud accents, keeping panels calm against their tint.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arhen/pi-senja",
3
- "version": "1.5.1",
3
+ "version": "1.5.3",
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",
@@ -0,0 +1,69 @@
1
+ import { constants } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { type ExtensionAPI, generateDiffString } from "@earendil-works/pi-coding-agent";
7
+
8
+ export function countDiff(diff: string) {
9
+ return { added: diff.match(/^\+/gm)?.length ?? 0, removed: diff.match(/^-/gm)?.length ?? 0 };
10
+ }
11
+
12
+ const lines = (s: string) => (s.match(/\n/g)?.length ?? 0) + Number(!!s && !s.endsWith("\n"));
13
+
14
+ export function trackWrites(pi: ExtensionAPI, enabled = () => true) {
15
+ type Entry = { path: string; overlap?: boolean; counts?: ReturnType<typeof countDiff> };
16
+ const pending = new Map<string, Entry>();
17
+ pi.on("tool_call", async (event, ctx) => {
18
+ if (!enabled() || event.toolName !== "write" || event.parentToolCallId) return;
19
+ const { path, content } = event.input;
20
+ if (typeof path !== "string" || typeof content !== "string" || content.includes("\0")) return;
21
+ if (!pi.getAllTools().some((tool) => tool.name === "write" && tool.sourceInfo?.path === "builtin:write")) return;
22
+ try {
23
+ const raw = path.replace(/^@/, "").replace(/[\u00a0\u2000-\u200a\u202f\u205f\u3000]/g, " ");
24
+ const target = resolve(
25
+ ctx.cwd,
26
+ raw.startsWith("file://") ? fileURLToPath(raw) : raw.replace(/^~(?=\/|$)/, homedir()),
27
+ );
28
+ const entry: Entry = { path: target };
29
+ for (const other of pending.values()) {
30
+ if (other.path === target) other.overlap = entry.overlap = true;
31
+ }
32
+ pending.set(event.toolCallId, entry);
33
+ if (entry.overlap) return;
34
+ let before = "";
35
+ try {
36
+ const file = await open(target, constants.O_RDONLY | constants.O_NONBLOCK);
37
+ try {
38
+ const stat = await file.stat();
39
+ if (!stat.isFile() || stat.size > 512 * 1024) return;
40
+ const bytes = Buffer.alloc(stat.size + 1);
41
+ const { bytesRead } = await file.read(bytes);
42
+ if (bytesRead !== stat.size) return;
43
+ before = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, bytesRead));
44
+ } finally {
45
+ await file.close();
46
+ }
47
+ } catch (err) {
48
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") return;
49
+ }
50
+ if (before.includes("\0")) return;
51
+ if (before === content) entry.counts = { added: 0, removed: 0 };
52
+ else if (!before || !content) entry.counts = { added: lines(content), removed: lines(before) };
53
+ else {
54
+ // ponytail: skip expensive whole-file rewrites; move larger diffs to a worker if needed.
55
+ if (content.length > 512 * 1024 || (before + content).split("\n", 2049).length > 2048) return;
56
+ entry.counts = countDiff(generateDiffString(before, content).diff);
57
+ }
58
+ } catch {
59
+ // Optional display metadata must never block the write.
60
+ }
61
+ });
62
+ pi.on("tool_result", (event) => {
63
+ const entry = pending.get(event.toolCallId);
64
+ pending.delete(event.toolCallId);
65
+ if (event.toolName === "write" && !event.isError && entry?.counts && !entry.overlap && event.details == null)
66
+ return { details: { senjaCounts: entry.counts } };
67
+ });
68
+ pi.on("agent_end", () => pending.clear());
69
+ }
package/src/index.ts CHANGED
@@ -21,6 +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 { trackWrites } from "./diff-counts.ts";
24
25
  import { createTranscriptView, formatDuration, installToolGroups } from "./tool-groups.ts";
25
26
 
26
27
  // ── Visual primitives ────────────────────────────────────────────────────────
@@ -382,6 +383,7 @@ export default function (pi: ExtensionAPI) {
382
383
  let renderHandle: RenderHandle | undefined;
383
384
  let disposeFooter: (() => void) | undefined;
384
385
  let enabled = true;
386
+ trackWrites(pi, () => enabled);
385
387
  const starts = new Map<string, number>();
386
388
  const cancelled = new Map<string, number | undefined>();
387
389
  function startCall(id: string) {
@@ -393,11 +395,6 @@ export default function (pi: ExtensionAPI) {
393
395
  cancelled.set(id, start === undefined ? undefined : performance.now() - start);
394
396
  starts.delete(id);
395
397
  }
396
- pi.on("message_update", ({ assistantMessageEvent: update }, ctx) => {
397
- if (ctx.mode !== "tui" || !("contentIndex" in update)) return;
398
- const block = update.partial.content[update.contentIndex];
399
- if (block?.type === "toolCall" && block.name && block.id) startCall(block.id);
400
- });
401
398
  pi.on("message_end", ({ message }, ctx) => {
402
399
  if (ctx.mode !== "tui" || message.role !== "assistant" || message.stopReason !== "aborted") return;
403
400
  for (const block of message.content) {
@@ -423,7 +420,8 @@ export default function (pi: ExtensionAPI) {
423
420
  const guide =
424
421
  "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
422
  const unsubscribeTranscript = pi.events.on("pi:transcript-renderer", (accept) => {
426
- if (enabled && typeof accept === "function") accept({ mount: createTranscriptView, codemodeGuide: guide });
423
+ if (enabled && typeof accept === "function")
424
+ accept({ mount: createTranscriptView, codemodeGuide: guide, trackWrites });
427
425
  });
428
426
  pi.on("before_agent_start", (event, ctx) => {
429
427
  if (!enabled || ctx.mode !== "tui" || !event.systemPromptOptions?.selectedTools.includes("codemode")) return;
@@ -23,9 +23,12 @@ import {
23
23
  wrapTextWithAnsi,
24
24
  } from "@earendil-works/pi-tui";
25
25
 
26
+ import { countDiff } from "./diff-counts.ts";
27
+
26
28
  type ToolRow = Component & {
27
29
  toolName: string;
28
30
  toolCallId: string;
31
+ executionStarted?: boolean;
29
32
  args?: Record<string, unknown>;
30
33
  isPartial: boolean;
31
34
  expanded: boolean;
@@ -33,7 +36,7 @@ type ToolRow = Component & {
33
36
  result?: {
34
37
  isError: boolean;
35
38
  durationMs?: number;
36
- details?: { diff?: string };
39
+ details?: { diff?: string; senjaCounts?: ReturnType<typeof countDiff> };
37
40
  content?: { type: string; text?: string }[];
38
41
  };
39
42
  setExpanded(value: boolean): void;
@@ -497,6 +500,7 @@ export function createTranscriptView(
497
500
  let animation: ReturnType<typeof setInterval> | undefined;
498
501
  let pressed: Component | undefined;
499
502
  let settle: ReturnType<typeof setTimeout> | undefined;
503
+ const editCounts = new WeakMap<object, ReturnType<typeof countDiff>>();
500
504
  const calls = new WeakMap<
501
505
  Component,
502
506
  {
@@ -624,9 +628,10 @@ export function createTranscriptView(
624
628
  const [, subject] = describe(tool);
625
629
  const start = tool.isPartial ? starts?.get(tool.toolCallId) : undefined;
626
630
  const error = tool.result?.isError && (cancelled?.has(tool.toolCallId) ? "cancelled" : "failed");
627
- const state = error || (!tool.isPartial ? "" : name ? "running" : "preparing…");
631
+ const running = start !== undefined || tool.executionStarted;
632
+ const state = error || (!tool.isPartial ? "" : running ? "running" : "preparing…");
628
633
  const duration =
629
- state === "cancelled" ? (cancelled?.get(tool.toolCallId) ?? tool.result?.durationMs) : undefined;
634
+ state === "cancelled" ? (tool.result?.durationMs ?? cancelled?.get(tool.toolCallId)) : undefined;
630
635
  const elapsed = start === undefined ? "" : formatDuration(performance.now() - start);
631
636
  const regions = before.get(tool);
632
637
  const rowWidth = name === "codemode" ? width : Math.max(1, Math.floor(width * 0.6));
@@ -641,7 +646,13 @@ export function createTranscriptView(
641
646
  }
642
647
  const active = motion && tool.isPartial && !error && width > 1;
643
648
  animating ||= active || !!elapsed;
644
- const labelKey = `${revision}:${width}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
649
+ const result = !tool.isPartial && !error ? tool.result : undefined;
650
+ let counts = name === "write" ? result?.details?.senjaCounts : undefined;
651
+ if (name === "edit" && result && typeof result.details?.diff === "string") {
652
+ counts = editCounts.get(result) ?? countDiff(result.details.diff);
653
+ editCounts.set(result, counts);
654
+ }
655
+ const labelKey = `${counts?.added}:${counts?.removed}:${revision}:${width}:${grouped}:${last}:${open}:${state}:${elapsed}:${duration ?? ""}:${active ? frame : 0}:${subject}`;
645
656
  if (labelKey !== call.labelKey) {
646
657
  call.labelKey = labelKey;
647
658
  const available = rowWidth - branch.length - 2;
@@ -656,9 +667,20 @@ export function createTranscriptView(
656
667
  const icon = theme.fg("muted", open ? "▾" : "▸");
657
668
  const status = suffix.length < available ? theme.fg(state === "failed" ? "error" : "muted", suffix) : "";
658
669
  const label = theme.fg("dim", subject || summary(name));
659
- const caption = grouped ? label : !name ? " •" : subject ? `${heading()} ${label}` : heading();
660
- const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(status)), "…");
661
- const line = `${script}${status} ${icon}`;
670
+ const title = () =>
671
+ state === "preparing…" ? ` ${theme.fg("warning", "•")} ${theme.fg("toolTitle", summary(name))}` : heading();
672
+ const caption = grouped ? label : !name ? " •" : subject ? `${title()} ${label}` : title();
673
+ const stats =
674
+ counts &&
675
+ Number.isSafeInteger(counts.added) &&
676
+ counts.added >= 0 &&
677
+ Number.isSafeInteger(counts.removed) &&
678
+ counts.removed >= 0
679
+ ? ` ${theme.fg("toolDiffAdded", `+${counts.added}`)} ${theme.fg("toolDiffRemoved", `-${counts.removed}`)}`
680
+ : "";
681
+ const tail = stats && visibleWidth(stats) + (grouped ? 1 : 9) <= available ? stats : status;
682
+ const script = truncateToWidth(caption, Math.max(0, available - visibleWidth(tail)), "…");
683
+ const line = `${script}${tail} ${icon}`;
662
684
  call.label.setText(rowWidth <= 1 ? icon : theme.fg("dim", branch) + (active ? shimmer(line, frame) : line));
663
685
  }
664
686
  rows.push(call.row);