@bismawy/pi-arnative 0.11.0 → 0.12.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.
@@ -6,19 +6,23 @@
6
6
  * or "Pi (system)".
7
7
  */
8
8
  import type { AssistantMessage } from "@earendil-works/pi-ai";
9
- import { CustomEditor, FooterComponent, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+ import { CustomEditor, FooterComponent, InteractiveMode, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
10
10
  import { truncateToWidth, visibleWidth, type TuiMouseEvent } from "@earendil-works/pi-tui";
11
11
  import { execFile } from "node:child_process";
12
12
  import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
13
13
  import { tmpdir } from "node:os";
14
14
  import { dirname, join, resolve } from "node:path";
15
15
  import { softOf, softSecondaryOf, stripAnsi } from "../lib/ansi.ts";
16
+ import { inSpans, textSpans, type TextSpan } from "../lib/box.ts";
16
17
  import { assert, isMain } from "../lib/check.ts";
17
18
  import { capitalize, markedLabels, modelDisplayParts } from "../lib/format.ts";
18
19
  import { IS_WINDOWS_LIKE, SHORTCUT_RELOAD, SHORTCUT_TOGGLE_FOOTER } from "../lib/shortcuts.ts";
19
- import { markPatched, originalOf } from "../lib/patch.ts";
20
+ import { markPatched, originalOf, patchOnce } from "../lib/patch.ts";
20
21
  import { estimateCost, formatTokens, loadPriceTable, TOOL_PROVIDER, type PriceTable } from "../lib/usage-store.ts";
21
22
  import {
23
+ CHATBOX_DIALOG_KEY as CHATBOX_DIALOG_CONFIG_KEY,
24
+ CHATBOX_PRESET_KEY as CHATBOX_PRESET_CONFIG_KEY,
25
+ CHATBOX_PROMPT_KEY as CHATBOX_PROMPT_CONFIG_KEY,
22
26
  FOOTER_COST_KEY as FOOTER_COST_CONFIG_KEY,
23
27
  FOOTER_PRESET_KEY as FOOTER_PRESET_CONFIG_KEY,
24
28
  loadChoice,
@@ -39,6 +43,153 @@ import { spinnerPainter } from "../lib/spinner.ts";
39
43
  // in both — pi's `setEditorComponent()` would close the picker mid-preview). The picker
40
44
  // lives in arnative.ts, so the choice is shared through globalThis like the header preset.
41
45
  // Listed built-in-first: the `(Full)` suffix is rendered dim, so the plain row reads cleaner on top.
46
+ export const CHATBOX_PRESETS = ["Pi (system)", "Arnative"] as const;
47
+ export type ChatboxPreset = (typeof CHATBOX_PRESETS)[number];
48
+ export const DEFAULT_CHATBOX_PRESET: ChatboxPreset = "Arnative";
49
+ const CHATBOX_PRESET_KEY = Symbol.for("pi-arnative.chatboxPreset");
50
+
51
+ export const CHATBOX_PROMPTS = ["❯", ">", "›", "▸", "→", "\uf44f", "\udb82\udf79", "\uf51b", "\udb80\udf7d", "\uf120", "\uf489", "\udb80\udd7a"] as const;
52
+ export type ChatboxPrompt = (typeof CHATBOX_PROMPTS)[number];
53
+ export const DEFAULT_CHATBOX_PROMPT: ChatboxPrompt = "❯";
54
+ const CHATBOX_PROMPT_KEY = Symbol.for("pi-arnative.chatboxPrompt");
55
+
56
+ export const CHATBOX_DIALOGS = ["Left", "Center", "Right", "Inside", "Outside"] as const;
57
+ export type ChatboxDialog = (typeof CHATBOX_DIALOGS)[number];
58
+ export const DEFAULT_CHATBOX_DIALOG: ChatboxDialog = "Left";
59
+ const CHATBOX_DIALOG_KEY = Symbol.for("pi-arnative.chatboxDialog");
60
+
61
+ export const PROMPT_IDLE_MS = 3_000;
62
+ const PROMPT_TYPED_AT_KEY = Symbol.for("pi-arnative.promptTypedAt");
63
+ const PROMPT_IDLE_TIMER_KEY = Symbol.for("pi-arnative.promptIdleTimer");
64
+
65
+ export function activeChatboxPreset(): ChatboxPreset {
66
+ const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] ?? loadChoice(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS);
67
+ return CHATBOX_PRESETS.includes(stored as ChatboxPreset) ? (stored as ChatboxPreset) : DEFAULT_CHATBOX_PRESET;
68
+ }
69
+
70
+ export function setChatboxPreset(name: ChatboxPreset): void {
71
+ (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY] = name;
72
+ saveChoice(CHATBOX_PRESET_CONFIG_KEY, name);
73
+ poke();
74
+ }
75
+
76
+ export function activeChatboxPrompt(): ChatboxPrompt {
77
+ const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] ?? loadChoice(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS);
78
+ return CHATBOX_PROMPTS.includes(stored as ChatboxPrompt) ? (stored as ChatboxPrompt) : DEFAULT_CHATBOX_PROMPT;
79
+ }
80
+
81
+ export function setChatboxPrompt(prompt: ChatboxPrompt): void {
82
+ (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY] = prompt;
83
+ saveChoice(CHATBOX_PROMPT_CONFIG_KEY, prompt);
84
+ poke();
85
+ }
86
+
87
+ export function nextChatboxPrompt(current: ChatboxPrompt = activeChatboxPrompt()): ChatboxPrompt {
88
+ const idx = CHATBOX_PROMPTS.indexOf(current);
89
+ return CHATBOX_PROMPTS[(idx + 1) % CHATBOX_PROMPTS.length]!;
90
+ }
91
+
92
+ export function activeChatboxDialog(): ChatboxDialog {
93
+ const stored = (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] ?? loadChoice(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS);
94
+ return CHATBOX_DIALOGS.includes(stored as ChatboxDialog) ? (stored as ChatboxDialog) : DEFAULT_CHATBOX_DIALOG;
95
+ }
96
+
97
+ export function setChatboxDialog(dialog: ChatboxDialog): void {
98
+ (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY] = dialog;
99
+ saveChoice(CHATBOX_DIALOG_CONFIG_KEY, dialog);
100
+ poke();
101
+ }
102
+
103
+ export function nextChatboxDialog(current: ChatboxDialog = activeChatboxDialog()): ChatboxDialog {
104
+ const idx = CHATBOX_DIALOGS.indexOf(current);
105
+ return CHATBOX_DIALOGS[(idx + 1) % CHATBOX_DIALOGS.length]!;
106
+ }
107
+
108
+ export function isPromptActive(
109
+ now: number = Date.now(),
110
+ lastTyped: number = ((globalThis as Record<symbol, unknown>)[PROMPT_TYPED_AT_KEY] as number | undefined) ?? 0,
111
+ ): boolean {
112
+ return lastTyped > 0 && now - lastTyped <= PROMPT_IDLE_MS;
113
+ }
114
+
115
+ export function stopPromptIdle(): void {
116
+ const g = globalThis as Record<symbol, ReturnType<typeof setTimeout> | null | undefined>;
117
+ if (g[PROMPT_IDLE_TIMER_KEY]) clearTimeout(g[PROMPT_IDLE_TIMER_KEY]!);
118
+ g[PROMPT_IDLE_TIMER_KEY] = null;
119
+ }
120
+
121
+ export function markPromptTyped(now: number = Date.now()): void {
122
+ const g = globalThis as Record<symbol, unknown>;
123
+ g[PROMPT_TYPED_AT_KEY] = now;
124
+ stopPromptIdle();
125
+ const timer = setTimeout(() => {
126
+ g[PROMPT_IDLE_TIMER_KEY] = null;
127
+ poke();
128
+ }, PROMPT_IDLE_MS + 25);
129
+ timer.unref?.();
130
+ g[PROMPT_IDLE_TIMER_KEY] = timer;
131
+ poke();
132
+ }
133
+
134
+ export function chatboxPrimaryPaint(
135
+ th: { fg?(color: string, text: string): string } | null | undefined,
136
+ ): (text: string) => string {
137
+ if (!th?.fg) return (t) => t;
138
+ for (const token of ["mdHeading", "accent"]) {
139
+ try {
140
+ const probe = th.fg(token, "x");
141
+ if (typeof probe === "string" && probe.includes("x")) return (t) => th.fg!(token, t);
142
+ } catch {
143
+ // try next
144
+ }
145
+ }
146
+ return (t) => t;
147
+ }
148
+
149
+ export function isWideNerdPrompt(glyph: string): boolean {
150
+ const cp = glyph.codePointAt(0) ?? 0;
151
+ return (cp >= 0xe000 && cp <= 0xf8ff) || cp >= 0xf0000;
152
+ }
153
+
154
+ export function paintChatboxPrompt(
155
+ promptGlyph: string,
156
+ th: { fg?(color: string, text: string): string } | null | undefined,
157
+ active: boolean,
158
+ ): string {
159
+ const text = isWideNerdPrompt(promptGlyph) ? ` ${promptGlyph} ` : ` ${promptGlyph} `;
160
+ if (!th?.fg) return text;
161
+ try {
162
+ if (!active) return th.fg("dim", text);
163
+ return chatboxPrimaryPaint(th)(text);
164
+ } catch {
165
+ return text;
166
+ }
167
+ }
168
+
169
+ export function renderChatboxScrollBorder(
170
+ direction: "\u2191" | "\u2193",
171
+ hiddenLineCount: number,
172
+ width: number,
173
+ borderColor: (text: string) => string,
174
+ primaryColor: (text: string) => string,
175
+ ): string {
176
+ const availableWidth = Math.max(0, width);
177
+ if (hiddenLineCount <= 0) return borderColor("\u2500".repeat(availableWidth));
178
+ const core = `${direction} ${hiddenLineCount} more`;
179
+ const labelWidth = visibleWidth(core) + 2;
180
+ if (labelWidth + 2 <= availableWidth) {
181
+ const leftWidth = Math.floor((availableWidth - labelWidth) / 2);
182
+ const rightWidth = availableWidth - leftWidth - labelWidth;
183
+ return `${borderColor(`${"\u2500".repeat(leftWidth)} `)}${primaryColor(core)}${borderColor(` ${"\u2500".repeat(rightWidth)}`)}`;
184
+ }
185
+ const prefix = "\u2500\u2500\u2500 ";
186
+ const remaining = availableWidth - visibleWidth(prefix) - visibleWidth(core) - 1;
187
+ if (remaining >= 0) {
188
+ return `${borderColor(prefix)}${primaryColor(core)}${borderColor(` ${"\u2500".repeat(remaining)}`)}`;
189
+ }
190
+ return borderColor(".".repeat(Math.min(3, availableWidth)) + "\u2500".repeat(Math.max(0, availableWidth - 3)));
191
+ }
192
+
42
193
  export const FOOTER_PRESETS = ["Pi (system)", "Arnative (Full)", "Arnative (Minimal)"] as const;
43
194
  export type FooterPreset = (typeof FOOTER_PRESETS)[number];
44
195
  export const DEFAULT_FOOTER_PRESET: FooterPreset = "Arnative (Full)";
@@ -536,6 +687,19 @@ export function formatDuration(ms: number): string {
536
687
  // already rendered at width - 5 (2 sides + 3 prompt) and the border is patched with
537
688
  // dashes to match. `visible` = content line count (private `renderedVisibleLineCount`);
538
689
  // autocomplete lines stay outside the box. JetBrainsMono NF has the round glyphs.
690
+ export function renderChatboxLines(
691
+ preset: ChatboxPreset,
692
+ renderInner: (w: number) => string[],
693
+ width: number,
694
+ visible: number | undefined,
695
+ color: (text: string) => string,
696
+ prompt = " > ",
697
+ ): string[] {
698
+ const promptW = visibleWidth(prompt);
699
+ if (preset === "Pi (system)" || typeof visible !== "number" || width < promptW + 8) return renderInner(width);
700
+ return boxEditorLines(renderInner(width - (2 + promptW)), visible, color, prompt);
701
+ }
702
+
539
703
  export function boxEditorLines(
540
704
  lines: readonly string[],
541
705
  visible: number,
@@ -555,6 +719,204 @@ export function boxEditorLines(
555
719
  return out;
556
720
  }
557
721
 
722
+ function formatTopBorderDialog(
723
+ innerW: number,
724
+ hiddenLineCount: number,
725
+ dialog: "Left" | "Center" | "Right",
726
+ status: string,
727
+ spinnerOnly: string,
728
+ color: (text: string) => string,
729
+ primaryColor: (text: string) => string = (t) => t,
730
+ ): string {
731
+ const scrollCore = hiddenLineCount > 0 ? `\u2191 ${hiddenLineCount} more` : "";
732
+ const scrollW = scrollCore ? visibleWidth(scrollCore) + 2 : 0;
733
+ const scrollPainted = scrollCore ? `${color(" ")}${primaryColor(scrollCore)}${color(" ")}` : "";
734
+ const tryPlace = (label: string): string | null => {
735
+ const lw = visibleWidth(label);
736
+ if (lw === 0 || innerW < lw + 4) return null;
737
+ if (dialog === "Left") {
738
+ if (scrollW > 0) {
739
+ const centerStart = Math.floor((innerW - scrollW) / 2);
740
+ if (centerStart >= 4 + lw + 1) {
741
+ return `${color("\u2500\u2500 ")}${label}${color(` ${"\u2500".repeat(centerStart - (4 + lw))}`)}${scrollPainted}${color("\u2500".repeat(innerW - centerStart - scrollW))}`;
742
+ }
743
+ return null;
744
+ }
745
+ return color("\u2500\u2500 ") + label + color(` ${"\u2500".repeat(innerW - lw - 4)}`);
746
+ }
747
+ if (dialog === "Center") {
748
+ const leftD = Math.floor((innerW - lw - 2) / 2);
749
+ const rightD = innerW - lw - 2 - leftD;
750
+ if (scrollW > 0) {
751
+ const leftEnd = 2 + scrollW;
752
+ if (leftD >= leftEnd + 1) {
753
+ return `${color("\u2500\u2500")}${scrollPainted}${color(`${"\u2500".repeat(leftD - leftEnd)} `)}${label}${color(` ${"\u2500".repeat(rightD)}`)}`;
754
+ }
755
+ return null;
756
+ }
757
+ return color(`${"\u2500".repeat(leftD)} `) + label + color(` ${"\u2500".repeat(rightD)}`);
758
+ }
759
+ // Right
760
+ if (scrollW > 0) {
761
+ const centerStart = Math.floor((innerW - scrollW) / 2);
762
+ if (centerStart + scrollW + 1 <= innerW - lw - 4) {
763
+ return `${color("\u2500".repeat(centerStart))}${scrollPainted}${color(`${"\u2500".repeat(innerW - lw - 4 - centerStart - scrollW)} `)}${label}${color(" \u2500\u2500")}`;
764
+ }
765
+ return null;
766
+ }
767
+ return color(`${"\u2500".repeat(innerW - lw - 4)} `) + label + color(" \u2500\u2500");
768
+ };
769
+ const placed = tryPlace(status) ?? (spinnerOnly ? tryPlace(spinnerOnly) : null);
770
+ if (placed) return placed;
771
+ const fallback = spinnerOnly || status;
772
+ const fw = visibleWidth(fallback);
773
+ if (innerW >= fw + 4) {
774
+ if (dialog === "Right") return color(`${"\u2500".repeat(innerW - fw - 4)} `) + fallback + color(" \u2500\u2500");
775
+ if (dialog === "Center") {
776
+ const leftD = Math.floor((innerW - fw - 2) / 2);
777
+ return color(`${"\u2500".repeat(leftD)} `) + fallback + color(` ${"\u2500".repeat(innerW - fw - 2 - leftD)}`);
778
+ }
779
+ return color("\u2500\u2500 ") + fallback + color(` ${"\u2500".repeat(innerW - fw - 4)}`);
780
+ }
781
+ const sw = Math.min(fw, innerW);
782
+ const prefixW = dialog === "Right" ? Math.max(0, innerW - sw) : dialog === "Center" ? Math.max(0, Math.floor((innerW - sw) / 2)) : Math.min(2, Math.max(0, innerW - sw));
783
+ return color("\u2500".repeat(prefixW)) + truncateToWidth(fallback, sw, "") + color("\u2500".repeat(Math.max(0, innerW - prefixW - sw)));
784
+ }
785
+
786
+ /** Places the active working/status dialog relative to the chatbox per the user's Dialog preset. */
787
+ export function applyChatboxDialog(
788
+ lines: readonly string[],
789
+ boxed: boolean,
790
+ width: number,
791
+ hiddenLineCount: number,
792
+ dialog: ChatboxDialog,
793
+ status: string,
794
+ spinnerOnly: string,
795
+ color: (text: string) => string,
796
+ primaryColor: (text: string) => string = (t) => t,
797
+ ): string[] {
798
+ const sw = visibleWidth(status);
799
+ if (sw === 0 || lines.length === 0) return [...lines];
800
+ const out = [...lines];
801
+ // Outside renders onto the existing above-editor widget row (no extra line added here).
802
+ if (dialog === "Outside") return out;
803
+ if (dialog === "Inside") {
804
+ if (out.length < 2) return out;
805
+ const side = boxed ? color("\u2502") : "";
806
+ if (boxed && (!out[1]!.startsWith(side) || !out[1]!.endsWith(side))) return out;
807
+ const inner = boxed ? out[1]!.slice(side.length, out[1]!.length - side.length) : out[1]!;
808
+ const innerW = boxed ? width - 2 : width;
809
+ const trimmed = inner.replace(/ +$/, "");
810
+ const gap = innerW - visibleWidth(trimmed);
811
+ if (gap >= sw + 2) {
812
+ out[1] = side + trimmed + " ".repeat(gap - sw - 1) + status + " " + side;
813
+ } else if (innerW >= sw + 6) {
814
+ const kept = truncateToWidth(trimmed, innerW - sw - 2, "");
815
+ const pad = Math.max(1, innerW - visibleWidth(kept) - sw - 1);
816
+ out[1] = side + kept + " ".repeat(pad) + status + " " + side;
817
+ }
818
+ return out;
819
+ }
820
+ const innerW = boxed ? Math.max(1, width - 2) : width;
821
+ const topInner = formatTopBorderDialog(innerW, hiddenLineCount, dialog, status, spinnerOnly, color, primaryColor);
822
+ out[0] = boxed ? color("\u256d") + topInner + color("\u256e") : topInner;
823
+ return out;
824
+ }
825
+
826
+ /** Left-aligns the Outside dialog status in the above-editor slot with 1 blank line
827
+ * above and below so it never crowds adjacent messages, Todos, or the chatbox, while
828
+ * keeping inline notices beside it on the same row. */
829
+ export function overlayOutsideDialogOnWidgetLines(lines: readonly string[], width: number, status: string): string[] {
830
+ const sw = visibleWidth(status);
831
+ if (sw === 0) return [...lines];
832
+ const leftRow = truncateToWidth(` ${status}`, width, "");
833
+ if (lines.length === 0) return ["", leftRow, ""];
834
+ const out = [...lines];
835
+ const lastIdx = out.length - 1;
836
+ const last = out[lastIdx]!;
837
+ const plainLast = stripAnsi(last).trim();
838
+ if (plainLast.length === 0) {
839
+ return ["", leftRow, ""];
840
+ }
841
+ if (!/^[╭╰│]/.test(plainLast)) {
842
+ const trimmed = last.replace(/ +$/, "");
843
+ const rest = trimmed.startsWith(" ") ? trimmed : ` ${trimmed}`;
844
+ out[lastIdx] = truncateToWidth(` ${status} ${rest}`, width, "");
845
+ if (stripAnsi(out[0]!).trim().length > 0) out.unshift("");
846
+ out.push("");
847
+ return out;
848
+ }
849
+ const boxStart = out.findIndex((line) => /^[╭╰│]/.test(stripAnsi(line).trim()));
850
+ const prefix = out.slice(0, boxStart).filter((line) => stripAnsi(line).trim().length > 0);
851
+ const boxed = out.slice(boxStart);
852
+ return prefix.length > 0 ? ["", leftRow, "", ...prefix, "", ...boxed] : ["", leftRow, "", ...boxed];
853
+ }
854
+
855
+ const OUTSIDE_HOOK_KEY = Symbol.for("pi-arnative.outsideDialogHook");
856
+ const ABOVE_WRAPPED_KEY = Symbol.for("pi-arnative.aboveWidgetWrapped");
857
+
858
+ function installAboveEditorHook(widgetContainer: { render?: (w: number) => string[] } | undefined, mode: unknown): void {
859
+ if (!widgetContainer || typeof widgetContainer.render !== "function") return;
860
+ if ((widgetContainer as unknown as Record<symbol, boolean>)[ABOVE_WRAPPED_KEY]) return;
861
+ (widgetContainer as unknown as Record<symbol, boolean>)[ABOVE_WRAPPED_KEY] = true;
862
+ const origRender = widgetContainer.render;
863
+ widgetContainer.render = function (this: unknown, width: number): string[] {
864
+ if (activeChatboxPreset() === "Arnative") {
865
+ trimLeadingSpacerAboveWidget(this as { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> });
866
+ }
867
+ const lines = origRender.call(this, width);
868
+ try {
869
+ const hook = (globalThis as Record<symbol, ((l: string[], w: number, m: unknown) => string[]) | undefined>)[OUTSIDE_HOOK_KEY];
870
+ return hook ? hook(lines, width, mode) : lines;
871
+ } catch {
872
+ return lines;
873
+ }
874
+ };
875
+ }
876
+
877
+ export function trimLeadingSpacerAboveWidget(
878
+ widgetContainer: { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> } | undefined,
879
+ ): boolean {
880
+ const children = widgetContainer?.children;
881
+ if (!Array.isArray(children) || children.length === 0) return false;
882
+ if (children[0]?.constructor?.name !== "Spacer") return false;
883
+ children.shift();
884
+ return true;
885
+ }
886
+
887
+ if (InteractiveMode?.prototype) {
888
+ const modeProto = InteractiveMode.prototype as unknown as {
889
+ renderWidgetContainer?: (container: unknown, widgets: unknown, spacerWhenEmpty: boolean, leadingSpacer: boolean) => void;
890
+ showStatusIndicator?: (indicator: unknown) => void;
891
+ };
892
+ if (typeof modeProto.renderWidgetContainer === "function") {
893
+ patchOnce(modeProto, "renderWidgetContainer", (orig) => function (
894
+ this: any,
895
+ container: unknown,
896
+ widgets: unknown,
897
+ spacerWhenEmpty: boolean,
898
+ leadingSpacer: boolean,
899
+ ): void {
900
+ if (container && container === this.widgetContainerAbove) {
901
+ installAboveEditorHook(container as { render?: (w: number) => string[] }, this);
902
+ }
903
+ orig.call(this, container, widgets, spacerWhenEmpty, leadingSpacer);
904
+ if (container && container === this.widgetContainerAbove && activeChatboxPreset() === "Arnative") {
905
+ trimLeadingSpacerAboveWidget(container as { children?: Array<{ constructor?: { name?: string }; render?(w: number): string[] }> });
906
+ }
907
+ });
908
+ }
909
+ if (typeof modeProto.showStatusIndicator === "function") {
910
+ patchOnce(modeProto, "showStatusIndicator", (orig) => function (this: any, indicator: unknown): void {
911
+ installAboveEditorHook(this.widgetContainerAbove, this);
912
+ if (activeChatboxPreset() === "Arnative") {
913
+ trimLeadingSpacerAboveWidget(this.widgetContainerAbove);
914
+ }
915
+ orig.call(this, indicator);
916
+ });
917
+ }
918
+ }
919
+
558
920
  /**
559
921
  * The footer as a fixed 3-row grid. Row 1 pairs the head cells (cwd line, model);
560
922
  * rows 2-3 pair the wrapped left cells (extension status, mcp first) with the
@@ -888,9 +1250,12 @@ export function getUsage(
888
1250
  return parts.join(" ");
889
1251
  }
890
1252
 
1253
+ let editorTui: { requestRender?: () => void } | null = null;
1254
+
891
1255
  function poke(): void {
892
1256
  try {
893
- rerender?.();
1257
+ if (rerender) rerender();
1258
+ else editorTui?.requestRender?.();
894
1259
  } catch {
895
1260
  // ignore
896
1261
  }
@@ -1310,8 +1675,14 @@ export default function (pi: ExtensionAPI) {
1310
1675
  (globalThis as Record<symbol, (ctx: ExtensionContext) => void>)[FOOTER_REGISTRAR_KEY] = registerArnative;
1311
1676
  applyFooterPreset(ctx);
1312
1677
  class ArnativeEditor extends CustomEditor {
1678
+ private lastHiddenLineCount = 0;
1679
+ private lastBottomHiddenCount = 0;
1680
+ private topMoreSpans: TextSpan[] = [];
1681
+ private bottomMoreSpans: TextSpan[] = [];
1682
+
1313
1683
  constructor(tui: any, editorTheme: any, keybindings: any, options?: any) {
1314
1684
  super(tui, editorTheme, keybindings, { ...options, embedWorkingStatus: true });
1685
+ editorTui = tui;
1315
1686
  // Published so `/arnative` → Animations can repaint the live spinner without
1316
1687
  // waiting for the next session, and so workUI has a handle to the Loader.
1317
1688
  (globalThis as Record<symbol, any>)[EDITOR_KEY] = this;
@@ -1344,8 +1715,91 @@ export default function (pi: ExtensionAPI) {
1344
1715
  }
1345
1716
 
1346
1717
  renderTopBorder(width: number, hiddenLineCount: number): string {
1718
+ this.lastHiddenLineCount = hiddenLineCount;
1347
1719
  this.applyFixedIndicatorColors((this as any).workingStatusIndicator);
1348
- return super.renderTopBorder(width, hiddenLineCount);
1720
+ if (activeChatboxPreset() === "Arnative") {
1721
+ return renderChatboxScrollBorder(
1722
+ "\u2191",
1723
+ hiddenLineCount,
1724
+ width,
1725
+ (t) => this.borderColor(t),
1726
+ chatboxPrimaryPaint(this.getActiveTheme()),
1727
+ );
1728
+ }
1729
+ // Plain/scroll border only; render() positions the status dialog after boxing.
1730
+ const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
1731
+ renderTopBorder?: (w: number, h: number) => string;
1732
+ };
1733
+ if (typeof editorProto?.renderTopBorder === "function") {
1734
+ return editorProto.renderTopBorder.call(this, width, hiddenLineCount);
1735
+ }
1736
+ return this.borderColor("\u2500".repeat(width));
1737
+ }
1738
+
1739
+ renderBottomBorder(width: number, hiddenLineCount: number): string {
1740
+ this.lastBottomHiddenCount = hiddenLineCount;
1741
+ if (activeChatboxPreset() === "Arnative") {
1742
+ return renderChatboxScrollBorder(
1743
+ "\u2193",
1744
+ hiddenLineCount,
1745
+ width,
1746
+ (t) => this.borderColor(t),
1747
+ chatboxPrimaryPaint(this.getActiveTheme()),
1748
+ );
1749
+ }
1750
+ const editorProto = Object.getPrototypeOf(CustomEditor.prototype) as {
1751
+ renderBottomBorder?: (w: number, h: number) => string;
1752
+ };
1753
+ if (typeof editorProto?.renderBottomBorder === "function") {
1754
+ return editorProto.renderBottomBorder.call(this, width, hiddenLineCount);
1755
+ }
1756
+ return this.borderColor("\u2500".repeat(width));
1757
+ }
1758
+
1759
+ private scrollByBorderClick(direction: -1 | 1): void {
1760
+ const ed = this as unknown as {
1761
+ lastWidth?: number;
1762
+ scrollOffset?: number;
1763
+ renderedVisibleLineCount?: number;
1764
+ buildVisualLineMap?(w: number): unknown[];
1765
+ findCurrentVisualLine?(vls: unknown[]): number;
1766
+ moveToVisualLine?(vls: unknown[], cur: number, target: number): void;
1767
+ pageScroll?(dir: number): void;
1768
+ };
1769
+ if (
1770
+ typeof ed.buildVisualLineMap === "function" &&
1771
+ typeof ed.findCurrentVisualLine === "function" &&
1772
+ typeof ed.moveToVisualLine === "function"
1773
+ ) {
1774
+ const vls = ed.buildVisualLineMap(ed.lastWidth ?? 80);
1775
+ if (vls.length > 0) {
1776
+ const cur = ed.findCurrentVisualLine(vls);
1777
+ const vis = Math.max(1, ed.renderedVisibleLineCount ?? 5);
1778
+ const step = Math.max(1, Math.floor(vis / 2));
1779
+ const scrollOff = Math.max(0, ed.scrollOffset ?? 0);
1780
+ const target =
1781
+ direction < 0
1782
+ ? Math.max(0, scrollOff - step)
1783
+ : Math.min(vls.length - 1, scrollOff + vis - 1 + step);
1784
+ ed.moveToVisualLine(vls, cur, target);
1785
+ return;
1786
+ }
1787
+ }
1788
+ ed.pageScroll?.(direction);
1789
+ }
1790
+
1791
+ handleMouse(event: TuiMouseEvent) {
1792
+ if (activeChatboxPreset() === "Arnative" && event.type === "click" && event.button === "left") {
1793
+ if (inSpans(this.topMoreSpans, event.y, event.x)) {
1794
+ this.scrollByBorderClick(-1);
1795
+ return { handled: true, focus: true };
1796
+ }
1797
+ if (inSpans(this.bottomMoreSpans, event.y, event.x)) {
1798
+ this.scrollByBorderClick(1);
1799
+ return { handled: true, focus: true };
1800
+ }
1801
+ }
1802
+ return super.handleMouse(event);
1349
1803
  }
1350
1804
 
1351
1805
  handleInput(data: string) {
@@ -1356,24 +1810,58 @@ export default function (pi: ExtensionAPI) {
1356
1810
  }
1357
1811
  return;
1358
1812
  }
1813
+ if (!isPointerOrFocusInput(data)) markPromptTyped();
1359
1814
  super.handleInput(data);
1360
1815
  }
1361
1816
 
1362
1817
  render(width: number): string[] {
1363
- // The box eats 5 columns: 2 sides + the 3-column " > " prompt, so the
1818
+ const preset = activeChatboxPreset();
1819
+ const dialog = activeChatboxDialog();
1820
+ const indicator = (this as any).workingStatusIndicator as
1821
+ | { renderInBorder?(w: number): string; renderSpinnerInBorder?(w: number): string }
1822
+ | undefined;
1823
+ this.applyFixedIndicatorColors(indicator);
1824
+ // The box eats 5 columns: 2 sides + the 3-column prompt, so the
1364
1825
  // content is rendered 5 columns narrower.
1365
1826
  const visible = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount;
1366
- if (typeof visible !== "number" || width < 11) return super.render(width);
1367
- let prompt = " > ";
1368
- try {
1369
- prompt = this.getActiveTheme()?.fg("dim", prompt) ?? prompt;
1370
- } catch {
1371
- // theme not ready -> uncolored prompt
1372
- }
1373
- return boxEditorLines(super.render(width - 5), visible, (t) => this.borderColor(t), prompt);
1827
+ const prompt = paintChatboxPrompt(activeChatboxPrompt(), this.getActiveTheme(), isPromptActive());
1828
+ const promptW = visibleWidth(prompt);
1829
+ const lines = renderChatboxLines(preset, (w) => super.render(w), width, visible, (t) => this.borderColor(t), prompt);
1830
+ const boxed = preset === "Arnative" && typeof visible === "number" && width >= promptW + 8 && lines.length >= visible + 2;
1831
+ const statusMax = Math.max(1, width - (boxed ? promptW + 4 : 5));
1832
+ const status = indicator?.renderInBorder?.(statusMax) ?? "";
1833
+ const spinnerOnly = status ? (indicator?.renderSpinnerInBorder?.(width) ?? "") : "";
1834
+ const primary = chatboxPrimaryPaint(this.getActiveTheme());
1835
+ const out = applyChatboxDialog(lines, boxed, width, this.lastHiddenLineCount, dialog, status, spinnerOnly, (t) => this.borderColor(t), primary);
1836
+ const visNow = (this as unknown as { renderedVisibleLineCount?: number }).renderedVisibleLineCount ?? 0;
1837
+ this.topMoreSpans =
1838
+ this.lastHiddenLineCount > 0 && out.length > 0
1839
+ ? textSpans([out[0]!], `\u2191 ${this.lastHiddenLineCount} more`)
1840
+ : [];
1841
+ const botRow = visNow + 1;
1842
+ this.bottomMoreSpans =
1843
+ this.lastBottomHiddenCount > 0 && botRow < out.length
1844
+ ? textSpans([out[botRow]!], `\u2193 ${this.lastBottomHiddenCount} more`).map((s) => ({ ...s, row: botRow }))
1845
+ : [];
1846
+ return out;
1374
1847
  }
1375
1848
  }
1376
1849
  ctx.ui.setEditorComponent((tui, editorTheme, keybindings) => new ArnativeEditor(tui, editorTheme, keybindings));
1850
+ (globalThis as Record<symbol, unknown>)[OUTSIDE_HOOK_KEY] = (lines: string[], width: number, mode: any): string[] => {
1851
+ if (activeChatboxDialog() !== "Outside") return lines;
1852
+ const editor = (globalThis as Record<symbol, any>)[EDITOR_KEY] as
1853
+ | { workingStatusIndicator?: { renderInBorder?(w: number): string }; applyFixedIndicatorColors?: (ind: any) => void }
1854
+ | undefined;
1855
+ if (!editor || mode?.editor !== editor) return lines;
1856
+ const children = mode?.editorContainer?.children;
1857
+ if (Array.isArray(children) && !children.includes(editor)) return lines;
1858
+ const indicator = editor.workingStatusIndicator;
1859
+ if (!indicator) return lines;
1860
+ editor.applyFixedIndicatorColors?.(indicator);
1861
+ const status = indicator.renderInBorder?.(Math.max(1, width - 5)) ?? "";
1862
+ if (!status || visibleWidth(status) === 0) return lines;
1863
+ return overlayOutsideDialogOnWidgetLines(lines, width, status);
1864
+ };
1377
1865
  } catch {
1378
1866
  // fallback
1379
1867
  }
@@ -1483,7 +1971,10 @@ export default function (pi: ExtensionAPI) {
1483
1971
  usageScanLeaf = undefined;
1484
1972
  stopWorkingClock();
1485
1973
  stopIdleProbe();
1974
+ stopPromptIdle();
1486
1975
  stopClockTick();
1976
+ editorTui = null;
1977
+ (globalThis as Record<symbol, unknown>)[OUTSIDE_HOOK_KEY] = null;
1487
1978
  try {
1488
1979
  ctx.ui?.setWorkingIndicator?.();
1489
1980
  } catch {
@@ -1553,6 +2044,12 @@ if (isMain(import.meta.url)) {
1553
2044
  assert(visibleWidth(boxedDim[1]!) === visibleWidth(D) + 5, "ANSI (dim) prompt does not shift the width");
1554
2045
  assert(boxedDim[1]!.startsWith(`\u2502${dimP(" > ")}`), "dim prompt kept as-is");
1555
2046
 
2047
+ const widthsSeen: number[] = [];
2048
+ const piChatbox = renderChatboxLines("Pi (system)", (w) => (widthsSeen.push(w), [D, " hi ", D]), 16, 1, plain);
2049
+ assert(widthsSeen[0] === 16 && piChatbox[0] === D, "Pi (system) chatbox renders stock lines at full width");
2050
+ const arnativeChatbox = renderChatboxLines("Arnative", (w) => (widthsSeen.push(w), [D, " hi ", D]), 16, 1, plain);
2051
+ assert(widthsSeen[1] === 11 && arnativeChatbox[0]!.startsWith("\u256d"), "Arnative chatbox renders boxed lines at width - 5");
2052
+
1556
2053
  // Self-check: getToolWorkingMessage
1557
2054
  assert(getToolWorkingMessage("edit") === "Editing", "edit -> Editing");
1558
2055
  assert(getToolWorkingMessage("write") === "Writing", "write -> Writing");
@@ -1864,6 +2361,95 @@ if (isMain(import.meta.url)) {
1864
2361
  delete (globalThis as Record<symbol, unknown>)[FOOTER_PRESET_KEY];
1865
2362
  resetPresetCache();
1866
2363
  assert(activeFooterPreset() === "Pi (system)", "a restart reads the non-default footer preset back from disk");
2364
+
2365
+ // Chatbox presets & prompt arrows: Arnative + ❯ are the defaults; Pi (system) and prompt choice persist across restarts.
2366
+ assert(DEFAULT_CHATBOX_PRESET === "Arnative" && CHATBOX_PRESETS.join(" | ") === "Pi (system) | Arnative", "chatbox presets are Pi (system) then Arnative");
2367
+ assert(activeChatboxPreset() === "Arnative", "Arnative is the default chatbox preset");
2368
+ assert(DEFAULT_CHATBOX_PROMPT === "❯" && CHATBOX_PROMPTS[0] === "❯" && CHATBOX_PROMPTS.length === 12, "chatbox prompts default to ❯ with 12 choices");
2369
+ assert(CHATBOX_PROMPTS.every((g) => visibleWidth(g) === 1), "every chatbox prompt glyph is 1 cell wide");
2370
+ assert(nextChatboxPrompt("❯") === ">" && nextChatboxPrompt("\udb80\udd7a") === "❯", "nextChatboxPrompt cycles through every arrow and wraps");
2371
+ assert(DEFAULT_CHATBOX_DIALOG === "Left" && CHATBOX_DIALOGS.join(" | ") === "Left | Center | Right | Inside | Outside", "chatbox dialog defaults to Left with 5 positions");
2372
+ assert(nextChatboxDialog("Left") === "Center" && nextChatboxDialog("Outside") === "Left", "nextChatboxDialog cycles through every position and wraps");
2373
+ setChatboxPreset("Pi (system)");
2374
+ setChatboxPrompt("▸");
2375
+ setChatboxDialog("Outside");
2376
+ assert(loadChoice(CHATBOX_PRESET_CONFIG_KEY, CHATBOX_PRESETS) === "Pi (system)", "the chatbox preset is persisted to disk");
2377
+ assert(loadChoice(CHATBOX_PROMPT_CONFIG_KEY, CHATBOX_PROMPTS) === "▸", "the chatbox prompt is persisted to disk");
2378
+ assert(loadChoice(CHATBOX_DIALOG_CONFIG_KEY, CHATBOX_DIALOGS) === "Outside", "the chatbox dialog is persisted to disk");
2379
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY];
2380
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY];
2381
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY];
2382
+ resetPresetCache();
2383
+ assert(activeChatboxPreset() === "Pi (system)", "a restart reads the non-default chatbox preset back from disk");
2384
+ assert(activeChatboxPrompt() === "▸", "a restart reads the non-default chatbox prompt back from disk");
2385
+ assert(activeChatboxDialog() === "Outside", "a restart reads the non-default chatbox dialog back from disk");
2386
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_PRESET_KEY];
2387
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_PROMPT_KEY];
2388
+ delete (globalThis as Record<symbol, unknown>)[CHATBOX_DIALOG_KEY];
2389
+
2390
+ // Chatbox dialog placement: Left, Center, Right, Inside, and Outside keep exact box width.
2391
+ const dW = 36;
2392
+ const dBox = boxEditorLines(["\u2500".repeat(dW - 5), "hi" + " ".repeat(dW - 7), "\u2500".repeat(dW - 5)], 1, plain, " ❯ ");
2393
+ const dStatus = "Working (1s)";
2394
+ for (const pos of CHATBOX_DIALOGS) {
2395
+ const rendered = applyChatboxDialog(dBox, true, dW, 0, pos, dStatus, "*", plain);
2396
+ assert(rendered.every((r) => visibleWidth(r) <= dW), `dialog ${pos} never exceeds width`);
2397
+ if (pos === "Outside") {
2398
+ assert(rendered.length === dBox.length && rendered[0] === dBox[0], "Outside dialog leaves editor box unchanged");
2399
+ } else if (pos === "Inside") {
2400
+ assert(rendered.length === dBox.length && rendered[0] === dBox[0] && rendered[1]!.includes(dStatus) && rendered[1]!.endsWith("│"), "Inside dialog sits inside line 1 at the right corner");
2401
+ } else if (pos === "Left") {
2402
+ assert(rendered[0]!.startsWith("╭── Working (1s) ") && visibleWidth(rendered[0]!) === dW, "Left dialog sits on the left of the top border");
2403
+ } else if (pos === "Center") {
2404
+ const idx = rendered[0]!.indexOf(dStatus);
2405
+ assert(idx > 4 && idx < dW - dStatus.length - 4 && visibleWidth(rendered[0]!) === dW, "Center dialog sits centered on the top border");
2406
+ } else if (pos === "Right") {
2407
+ assert(rendered[0]!.endsWith(" Working (1s) ──╮") && visibleWidth(rendered[0]!) === dW, "Right dialog sits on the right of the top border");
2408
+ }
2409
+ }
2410
+ const outZero = overlayOutsideDialogOnWidgetLines([], dW, dStatus);
2411
+ assert(outZero.length === 3 && outZero[0] === "" && outZero[1] === ` ${dStatus}` && outZero[2] === "", "Outside dialog renders with 1 blank line above and below even when widgetContainerAbove is empty");
2412
+ const outEmpty = overlayOutsideDialogOnWidgetLines([""], dW, dStatus);
2413
+ assert(outEmpty.length === 3 && outEmpty[0] === "" && outEmpty[1] === ` ${dStatus}` && outEmpty[2] === "", "Outside dialog pads 1 blank line above and below when no widget is shown");
2414
+ const outNotice = overlayOutsideDialogOnWidgetLines(["", " \ueb1b Chatbox: Arnative."], 60, dStatus);
2415
+ assert(outNotice.length === 3 && outNotice[0] === "" && outNotice[1] === ` ${dStatus} \ueb1b Chatbox: Arnative.` && outNotice[2] === "", "Outside dialog sits on the left with the notice beside it and 1 blank line below");
2416
+ const outTodos = overlayOutsideDialogOnWidgetLines(["", "\u256d" + "\u2500".repeat(58) + "\u256e", "\u2570" + "\u2500".repeat(58) + "\u256f"], 60, dStatus);
2417
+ assert(outTodos.length === 5 && outTodos[0] === "" && outTodos[1] === ` ${dStatus}` && outTodos[2] === "" && outTodos[3]!.startsWith("\u256d"), "Outside dialog leaves 1 blank line above and below when Todos is visible");
2418
+ const fakeAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }, { render: () => ["\u256d\u2500\u256e", "\u2570\u2500\u256f"] }] };
2419
+ assert(trimLeadingSpacerAboveWidget(fakeAbove) === true && fakeAbove.children.length === 1, "leading Spacer above boxed widget (e.g. Todos) is trimmed cleanly");
2420
+ const fakePlainAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }, { render: () => ["plain status"] }] };
2421
+ assert(trimLeadingSpacerAboveWidget(fakePlainAbove) === true && fakePlainAbove.children.length === 1, "leading Spacer above notice widget is trimmed cleanly");
2422
+ const fakeEmptyAbove = { children: [{ constructor: { name: "Spacer" }, render: () => [""] }] };
2423
+ assert(trimLeadingSpacerAboveWidget(fakeEmptyAbove) === true && fakeEmptyAbove.children.length === 0, "leading Spacer when widgetContainerAbove is empty is trimmed cleanly");
2424
+
2425
+ const scrollBorder = renderChatboxScrollBorder("\u2191", 3, 24, (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
2426
+ assert(scrollBorder.includes("<pri>↑ 3 more</pri>") && visibleWidth(stripAnsi(scrollBorder.replace(/<\/?(bdr|pri)>/g, ""))) === 24, "chatbox scroll border paints N more in primary at exact width");
2427
+ const dialogWithScroll = applyChatboxDialog(dBox, true, dW, 2, "Left", dStatus, "*", (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
2428
+ assert(dialogWithScroll[0]!.includes("<pri>↑ 2 more</pri>"), "top border dialog keeps ↑ N more painted in primary");
2429
+
2430
+ // Prompt idle/active coloring: idle uses dim, active typing uses primary (mdHeading, accent fallback).
2431
+ assert(isPromptActive(10_000, 0) === false, "untyped prompt starts idle");
2432
+ assert(isPromptActive(10_000, 8_000) === true, "prompt stays active within 3s of typing");
2433
+ assert(isPromptActive(10_000, 7_000) === true, "prompt is still active at exact 3s boundary");
2434
+ assert(isPromptActive(10_001, 7_000) === false, "prompt turns idle past 3s without typing");
2435
+ const promptTheme = { fg: (c: string, t: string) => `<${c}>${t}</${c}>` };
2436
+ assert(paintChatboxPrompt("❯", promptTheme, false) === "<dim> ❯ </dim>", "idle prompt paints with dim");
2437
+ assert(paintChatboxPrompt("❯", promptTheme, true) === "<mdHeading> ❯ </mdHeading>", "active prompt paints with primary (mdHeading)");
2438
+ assert(paintChatboxPrompt("\udb80\udf7d", promptTheme, false) === "<dim> \udb80\udf7d </dim>", "Nerd Font PUA prompt gets 2 trailing spaces");
2439
+ const nerdBox = renderChatboxLines("Arnative", (w) => ["\u2500".repeat(w), "hi" + " ".repeat(w - 2), "\u2500".repeat(w)], 30, 1, (t) => t, " \udb80\udf7d ");
2440
+ assert(nerdBox.length === 3 && nerdBox.every((l) => visibleWidth(l) === 30) && nerdBox[1]!.startsWith("\u2502 \udb80\udf7d hi"), "4-col Nerd Font prompt preserves exact box width");
2441
+ const fallbackTheme = {
2442
+ fg: (c: string, t: string) => {
2443
+ if (c === "mdHeading") throw new Error("missing");
2444
+ return `<${c}>${t}</${c}>`;
2445
+ },
2446
+ };
2447
+ assert(paintChatboxPrompt("❯", fallbackTheme, true) === "<accent> ❯ </accent>", "active prompt falls back to accent when mdHeading is absent");
2448
+ markPromptTyped(Date.now());
2449
+ assert(isPromptActive() === true && (globalThis as Record<symbol, unknown>)[PROMPT_IDLE_TIMER_KEY] != null, "markPromptTyped activates prompt and arms idle timer");
2450
+ stopPromptIdle();
2451
+ assert((globalThis as Record<symbol, unknown>)[PROMPT_IDLE_TIMER_KEY] == null, "stopPromptIdle clears the prompt idle timer");
2452
+ delete (globalThis as Record<symbol, unknown>)[PROMPT_TYPED_AT_KEY];
1867
2453
  rmSync(presetFixture, { recursive: true, force: true });
1868
2454
  if (prevAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
1869
2455
  else process.env.PI_CODING_AGENT_DIR = prevAgentDir;