@bismawy/pi-arnative 0.11.1 → 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.
@@ -192,9 +192,9 @@ if (UserMessageComponent?.prototype?.render || AssistantMessageComponent?.protot
192
192
  // First text line that is neither an OSC zone nor a thinking header
193
193
  let targetIdx = -1;
194
194
  for (let i = 0; i < lines.length; i++) {
195
- const cleaned = lines[i].replace(/^(\x1b\]133;[A-Z]\x07)+/, "").trim();
196
- // Never paste onto the "Thinking..." line
197
- if (cleaned.length > 0 && !/^thinking\b/i.test(cleaned)) {
195
+ const plain = stripAnsi(lines[i].replace(/^(\x1b\]133;[A-Z]\x07)+/, "")).trim();
196
+ // Never paste onto the hidden thinking line: `Thinking...` while it streams, `Thought for 3s` once it ends (plain or with the \uec21 icon)
197
+ if (plain.length > 0 && !/^(?:\uec21\s+)?(?:thinking|thought for)\b/i.test(plain)) {
198
198
  targetIdx = i;
199
199
  break;
200
200
  }
@@ -41,6 +41,11 @@ import {
41
41
  /** pi widget key; the extension owns it, so a reload replaces its own box. */
42
42
  export const TODO_WIDGET_KEY = "arnative-todos";
43
43
 
44
+ /** Delay before holding a `↑`/`↓ n more` row starts repeating, so a normal click scrolls once. */
45
+ const HOLD_DELAY_MS = 250;
46
+ /** Step interval while holding a `↑`/`↓ n more` counter row. */
47
+ const HOLD_REPEAT_MS = 90;
48
+
44
49
  const STORE_KEY = Symbol.for("pi-arnative.todos.widget");
45
50
 
46
51
  interface WidgetStore {
@@ -282,6 +287,21 @@ function refresh(ctx: ExtensionContext, force = false): void {
282
287
  let layout: ReturnType<typeof todoLayout> = { lines: [], up: null, down: null };
283
288
  /** Cells of the hint in the drawn box: the only place a press expands or folds it. */
284
289
  let spans: TextSpan[] = [];
290
+ /** Swallows the follow-up release/click after a press on the hint or a counter, because
291
+ * the re-render between press and click can remove `↑ 1 more` / `↓ 1 more` at that row. */
292
+ let swallowClick = false;
293
+ let holdDelay: ReturnType<typeof setTimeout> | undefined;
294
+ let holdRepeat: ReturnType<typeof setInterval> | undefined;
295
+ const stopHold = (): void => {
296
+ if (holdDelay) {
297
+ clearTimeout(holdDelay);
298
+ holdDelay = undefined;
299
+ }
300
+ if (holdRepeat) {
301
+ clearInterval(holdRepeat);
302
+ holdRepeat = undefined;
303
+ }
304
+ };
285
305
  /** Move the five-row window by `delta` rows and repaint. `top` stays absolute, so the
286
306
  * window parks at the end of the list instead of drifting. */
287
307
  const scroll = (delta: number): void => {
@@ -289,6 +309,31 @@ function refresh(ctx: ExtensionContext, force = false): void {
289
309
  s.top = start + delta;
290
310
  s.tui?.requestRender(true);
291
311
  };
312
+ const startHold = (delta: -1 | 1): void => {
313
+ stopHold();
314
+ const step = (): void => {
315
+ if (!s.expanded) {
316
+ stopHold();
317
+ return;
318
+ }
319
+ const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
320
+ if ((delta < 0 && win.above <= 0) || (delta > 0 && win.below <= 0)) {
321
+ stopHold();
322
+ return;
323
+ }
324
+ scroll(delta);
325
+ };
326
+ holdDelay = setTimeout(() => {
327
+ holdDelay = undefined;
328
+ step();
329
+ if (s.expanded && holdRepeat === undefined) {
330
+ const win = todoWindow(s.state, listRowsFor(process.stdout.rows), s.top);
331
+ if ((delta < 0 && win.above > 0) || (delta > 0 && win.below > 0)) {
332
+ holdRepeat = setInterval(step, HOLD_REPEAT_MS);
333
+ }
334
+ }
335
+ }, HOLD_DELAY_MS);
336
+ };
292
337
  return {
293
338
  render: (width: number): string[] => {
294
339
  // The live theme, so a theme switch repaints without re-registering.
@@ -308,15 +353,38 @@ function refresh(ctx: ExtensionContext, force = false): void {
308
353
  // the task names stay selectable and copyable. The work is done on the press: pi
309
354
  // only synthesizes a click when the pointer did not move at all.
310
355
  handleMouse: (event: TuiMouseEvent) => {
311
- if (event.button !== "left" || event.y >= height) return undefined;
356
+ if (event.button !== "left") return undefined;
357
+ if (event.type === "press") {
358
+ stopHold();
359
+ swallowClick = false;
360
+ }
361
+ if (swallowClick && event.type !== "press") {
362
+ if (event.type === "release" || event.type === "click") stopHold();
363
+ if (event.type === "click") swallowClick = false;
364
+ return { handled: true, render: false };
365
+ }
366
+ if (event.y >= height) return undefined;
312
367
  const onHint = inSpans(spans, event.y, event.x);
313
368
  const onCounter = event.y === layout.up || event.y === layout.down;
314
- if (!onHint && !onCounter) return undefined;
369
+ if (!onHint && !onCounter) {
370
+ if (event.type === "click" && (event.clickCount ?? 1) === 1) {
371
+ s.expanded = !s.expanded;
372
+ s.top = null;
373
+ if (allDone(s.state) && !s.expanded) scheduleHide(ctx, s);
374
+ else cancelHide(s);
375
+ s.tui?.requestRender(true);
376
+ return { handled: true, render: true };
377
+ }
378
+ return undefined;
379
+ }
315
380
  // The press already did it, so the release and the click that may follow are
316
381
  // swallowed: toggling again on the click would undo the press.
317
382
  if (event.type !== "press") return { handled: true, render: false };
383
+ swallowClick = true;
318
384
  if (onCounter) {
319
- scroll(event.y === layout.up ? -1 : 1);
385
+ const delta: -1 | 1 = event.y === layout.up ? -1 : 1;
386
+ scroll(delta);
387
+ startHold(delta);
320
388
  return { handled: true, render: true };
321
389
  }
322
390
  s.expanded = !s.expanded;
@@ -326,7 +394,9 @@ function refresh(ctx: ExtensionContext, force = false): void {
326
394
  s.tui?.requestRender(true);
327
395
  return { handled: true, render: true };
328
396
  },
329
- dispose: (): void => {},
397
+ dispose: (): void => {
398
+ stopHold();
399
+ },
330
400
  };
331
401
  },
332
402
  { placement: "aboveEditor" },
@@ -39,7 +39,7 @@ import {
39
39
  import { Markdown, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
40
40
  import { homedir } from "node:os";
41
41
  import { inSpans, renderBoxLines as box, type TextSpan, textSpans } from "../lib/box.ts";
42
- import { stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
42
+ import { getActiveTheme, stripAnsi, softSecondaryOf } from "../lib/ansi.ts";
43
43
  import { actionWord } from "../lib/todos.ts";
44
44
  import { assert, isMain } from "../lib/check.ts";
45
45
  import { markPatched, originalOf } from "../lib/patch.ts";
@@ -275,9 +275,89 @@ export function stripEdgesKeepingImages(lines: string[]): string[] {
275
275
  // target: every other cell of the box keeps pi's text selection, so the output stays
276
276
  // copyable. Recomputed on every render, because the label moves with the width and the key.
277
277
  const HINT_SPANS = Symbol.for("pi-arnative.toolBoxHintSpans");
278
+ const SCROLL_OFFSET = Symbol.for("pi-arnative.toolBoxScrollOffset");
279
+ const SCROLL_UP_SPANS = Symbol.for("pi-arnative.toolBoxScrollUpSpans");
280
+ const SCROLL_DOWN_SPANS = Symbol.for("pi-arnative.toolBoxScrollDownSpans");
281
+ const SCROLL_META = Symbol.for("pi-arnative.toolBoxScrollMeta");
278
282
  // A press already toggled this box; the release and the synthesized click that follow it
279
283
  // must not toggle it a second time.
280
284
  const PRESS_TOGGLED = Symbol.for("pi-arnative.toolBoxPressToggled");
285
+ const STRIPPED_BOX = Symbol.for("pi-arnative.toolBoxStripped");
286
+
287
+ export function expandedBoxBodyLimit(rows = process.stdout.rows || 28): number {
288
+ return Math.min(12, Math.max(6, Math.floor(rows * 0.35)));
289
+ }
290
+
291
+ function boxTokenPaint(tokens: readonly string[]): (text: string) => string {
292
+ const th = getActiveTheme<{ fg?(c: string, t: string): string }>();
293
+ if (!th?.fg) return (s) => s;
294
+ for (const token of tokens) {
295
+ try {
296
+ const probe = th.fg(token, "x");
297
+ if (typeof probe === "string" && probe.includes("x")) return (s) => th.fg!(token, s);
298
+ } catch {
299
+ // try next token
300
+ }
301
+ }
302
+ return (s) => s;
303
+ }
304
+
305
+ export function paintScrollEdge(
306
+ edgeLine: string,
307
+ leftCorner: string,
308
+ rightCorner: string,
309
+ label: string,
310
+ width: number,
311
+ borderPaint: (text: string) => string,
312
+ primaryPaint: (text: string) => string,
313
+ ): string {
314
+ const inner = width - 2;
315
+ const labelW = visibleWidth(label);
316
+ if (inner < labelW + 4) return edgeLine;
317
+ const bgOpen = edgeLine.match(/^(\x1b\[48;[0-9;]*m)+/)?.[0] ?? "";
318
+ const bgClose = bgOpen ? "\x1b[49m" : "";
319
+ const totalDashes = inner - (labelW + 2);
320
+ const leftDashes = Math.floor(totalDashes / 2);
321
+ const rightDashes = totalDashes - leftDashes;
322
+ const content = `${borderPaint(`${leftCorner}${"\u2500".repeat(leftDashes)} `)}${primaryPaint(label)}${borderPaint(` ${"\u2500".repeat(rightDashes)}${rightCorner}`)}`;
323
+ return `${bgOpen}${content}${bgClose}`;
324
+ }
325
+
326
+ export function capExpandedToolBox(
327
+ drawn: string[],
328
+ scrollOffset: number,
329
+ maxBody: number,
330
+ width: number,
331
+ borderPaint: (text: string) => string,
332
+ primaryPaint: (text: string) => string,
333
+ ): { lines: string[]; maxOffset: number; aboveLabel: string; belowLabel: string; botRow: number } {
334
+ if (drawn.length < 4 || !stripAnsi(drawn[0] ?? "").trimStart().startsWith("\u256d")) {
335
+ return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
336
+ }
337
+ let botIdx = -1;
338
+ for (let i = drawn.length - 1; i >= 2; i--) {
339
+ const p = stripAnsi(drawn[i]!).trim();
340
+ if (p.startsWith("\u2570") && p.endsWith("\u256f")) {
341
+ botIdx = i;
342
+ break;
343
+ }
344
+ }
345
+ if (botIdx < 3) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: -1 };
346
+ const body = drawn.slice(2, botIdx);
347
+ if (body.length <= maxBody) return { lines: drawn, maxOffset: 0, aboveLabel: "", belowLabel: "", botRow: botIdx };
348
+
349
+ const maxOffset = body.length - maxBody;
350
+ const offset = Math.max(0, Math.min(scrollOffset, maxOffset));
351
+ const visible = body.slice(offset, offset + maxBody);
352
+ const above = offset;
353
+ const below = body.length - (offset + visible.length);
354
+ const aboveLabel = above > 0 ? `\u2191 ${above} more` : "";
355
+ const belowLabel = below > 0 ? `\u2193 ${below} more` : "";
356
+ const top = aboveLabel ? paintScrollEdge(drawn[0]!, "\u256d", "\u256e", aboveLabel, width, borderPaint, primaryPaint) : drawn[0]!;
357
+ const bot = belowLabel ? paintScrollEdge(drawn[botIdx]!, "\u2570", "\u256f", belowLabel, width, borderPaint, primaryPaint) : drawn[botIdx]!;
358
+ const lines = [top, drawn[1]!, ...visible, bot, ...drawn.slice(botIdx + 1)];
359
+ return { lines, maxOffset, aboveLabel, belowLabel, botRow: 2 + visible.length };
360
+ }
281
361
 
282
362
  // The patches below reinstall on every module load (pi's /reload re-evaluates the
283
363
  // extension in the same process), so a UI fix applies without restarting pi; see
@@ -288,7 +368,32 @@ if (ToolExecutionComponent?.prototype?.render) {
288
368
  proto.render = markPatched(function (this: any, width: number): string[] {
289
369
  const lines = origRender.call(this, width);
290
370
  const stripped = OWN_BOX.has(this.toolName) || boxTheirRenderers(this) || !hasOwnRendererDef(this);
291
- const drawn = stripped ? stripEdgesKeepingImages(lines) : lines;
371
+ this[STRIPPED_BOX] = stripped;
372
+ let drawn = stripped ? stripEdgesKeepingImages(lines) : lines;
373
+ if (stripped && this.expanded) {
374
+ const maxBody = expandedBoxBodyLimit();
375
+ const capped = capExpandedToolBox(
376
+ drawn,
377
+ Number(this[SCROLL_OFFSET] ?? 0),
378
+ maxBody,
379
+ width,
380
+ boxTokenPaint(["dim"]),
381
+ boxTokenPaint(["mdHeading", "accent"]),
382
+ );
383
+ drawn = capped.lines;
384
+ this[SCROLL_OFFSET] = Math.max(0, Math.min(Number(this[SCROLL_OFFSET] ?? 0), capped.maxOffset));
385
+ this[SCROLL_META] = { maxOffset: capped.maxOffset, step: Math.max(1, Math.floor(maxBody / 2)) };
386
+ this[SCROLL_UP_SPANS] = capped.aboveLabel ? textSpans([drawn[0]!], capped.aboveLabel) : [];
387
+ this[SCROLL_DOWN_SPANS] =
388
+ capped.belowLabel && capped.botRow >= 0
389
+ ? textSpans([drawn[capped.botRow]!], capped.belowLabel).map((s) => ({ ...s, row: capped.botRow }))
390
+ : [];
391
+ } else {
392
+ this[SCROLL_OFFSET] = 0;
393
+ this[SCROLL_UP_SPANS] = [];
394
+ this[SCROLL_DOWN_SPANS] = [];
395
+ this[SCROLL_META] = undefined;
396
+ }
292
397
  // Only a box this module laid out is measured here; a renderer pi owns keeps pi's
293
398
  // own mouse path, since its row offsets come from a layout it did not show us.
294
399
  // Title rows only (frame + title): a [show] inside the output must not become a button.
@@ -298,30 +403,58 @@ if (ToolExecutionComponent?.prototype?.render) {
298
403
  return drawn;
299
404
  });
300
405
 
301
- // Click to expand, on the hint text alone. pi toggles on the "click" it synthesizes from
302
- // a press and a release at the same cell, so a one-cell drift made the hint look inert,
303
- // and the stripped row above the box left its top border dead. A left press on the hint
304
- // toggles at once and the release plus the click that follow are swallowed; the click
305
- // clears the flag, not the release, or that click would toggle the box back. Any other
306
- // cell is left to pi: a press there starts a selection, so the output can be copied.
406
+ // Click to expand/collapse or scroll, on the hint/more text alone. pi toggles on the
407
+ // "click" it synthesizes from a press and a release at the same cell, so a one-cell
408
+ // drift made the hint look inert, and the stripped row above the box left its top
409
+ // border dead. A left press on the button acts at once and the release plus the click
410
+ // that follow are swallowed; the click clears the flag, not the release, or that click
411
+ // would trigger twice. Any other cell is left to pi: a press there starts a selection,
412
+ // so the output can be copied.
307
413
  const origMouse = originalOf<(this: any, event: any) => any>(proto, "handleMouse");
308
414
  proto.handleMouse = markPatched(function (this: any, event: any): any {
309
415
  const onHint = (this[HINT_SPANS] as TextSpan[] | undefined)?.length
310
416
  ? inSpans(this[HINT_SPANS] as TextSpan[], event.y, event.x)
311
417
  : false;
312
- if (onHint && event.type === "press" && event.button === "left") {
418
+ const onUp = (this[SCROLL_UP_SPANS] as TextSpan[] | undefined)?.length
419
+ ? inSpans(this[SCROLL_UP_SPANS] as TextSpan[], event.y, event.x)
420
+ : false;
421
+ const onDown = (this[SCROLL_DOWN_SPANS] as TextSpan[] | undefined)?.length
422
+ ? inSpans(this[SCROLL_DOWN_SPANS] as TextSpan[], event.y, event.x)
423
+ : false;
424
+ if ((onHint || onUp || onDown) && event.type === "press" && event.button === "left") {
313
425
  // A child of the box (an image preview) keeps its own press.
314
426
  const childHit = origMouse.call(this, event);
315
427
  if (childHit) return childHit;
316
- if (!this.result) return undefined;
317
- this.setExpanded(!this.expanded);
428
+ if (onHint) {
429
+ if (!this.result) return undefined;
430
+ this.setExpanded(!this.expanded);
431
+ this[PRESS_TOGGLED] = true;
432
+ return { handled: true, render: true };
433
+ }
434
+ const meta = (this[SCROLL_META] as { maxOffset: number; step: number } | undefined) ?? { maxOffset: 0, step: 6 };
435
+ const cur = Number(this[SCROLL_OFFSET] ?? 0);
436
+ const next = Math.max(0, Math.min(meta.maxOffset, cur + (onUp ? -meta.step : meta.step)));
437
+ this[SCROLL_OFFSET] = next;
318
438
  this[PRESS_TOGGLED] = true;
439
+ this.ui?.requestRender?.();
319
440
  return { handled: true, render: true };
320
441
  }
321
442
  if (this[PRESS_TOGGLED] && (event.type === "release" || event.type === "click")) {
322
443
  if (event.type === "click") this[PRESS_TOGGLED] = false;
323
444
  return { handled: true, render: false };
324
445
  }
446
+ if (
447
+ this[STRIPPED_BOX] &&
448
+ this.result &&
449
+ event.type === "click" &&
450
+ event.button === "left"
451
+ ) {
452
+ if ((event.clickCount ?? 1) !== 1) return undefined;
453
+ const origHit = origMouse.call(this, event);
454
+ if (origHit) return origHit;
455
+ this.setExpanded(!this.expanded);
456
+ return { handled: true, render: true };
457
+ }
325
458
  return origMouse.call(this, event);
326
459
  });
327
460
  }
@@ -1682,13 +1815,64 @@ if (isMain(import.meta.url)) {
1682
1815
  assert(box.expanded === false, "mouse: the swallowed click does not reopen it");
1683
1816
  }
1684
1817
  {
1685
- // Every cell off the hint stays with pi, which is what keeps the output copyable.
1818
+ // Every cell off the hint keeps press uncaptured for text selection, while a plain
1819
+ // single click anywhere on the box still toggles expand/collapse.
1686
1820
  const box = mouseBox();
1687
1821
  const taken = mouse(box, "press", 2, 6);
1688
1822
  assert(taken === undefined && box.expanded === false, "mouse: a press off the hint is left to pi (text selection)");
1689
1823
  mouse(box, "move", 2, 14);
1690
1824
  mouse(box, "release", 2, 14);
1691
1825
  assert(box.expanded === false, "mouse: a drag over the output does not expand the box");
1826
+ click(box, 1, 6);
1827
+ assert(box.expanded === true, "mouse: single click on box title text expands without blocking drag select");
1828
+ click(box, 0, 6);
1829
+ assert(box.expanded === false, "mouse: single click on top border collapses without blocking drag select");
1830
+ box.handleMouse({
1831
+ type: "click",
1832
+ button: "left",
1833
+ x: 6,
1834
+ y: 2,
1835
+ screenX: 6,
1836
+ screenY: 2,
1837
+ width: 60,
1838
+ height: (box.render(60) as string[]).length,
1839
+ clickCount: 2,
1840
+ shift: false,
1841
+ alt: false,
1842
+ ctrl: false,
1843
+ });
1844
+ assert(box.expanded === false, "mouse: double-click selection does not toggle box");
1845
+ }
1846
+ {
1847
+ // Expanded long output caps body height and offers clickable primary ↑/↓ N more borders.
1848
+ const prevRows = process.stdout.rows;
1849
+ Object.defineProperty(process.stdout, "rows", { value: 28, configurable: true });
1850
+ try {
1851
+ const maxBody = expandedBoxBodyLimit(28);
1852
+ assert(maxBody === 9, "expanded body viewport adapts cleanly (9 rows at 28-line terminal)");
1853
+ const longText = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join("\n");
1854
+ const longBox: any = new ToolExecutionComponent("bash", "9", { command: "seq 20" }, {}, {}, { requestRender() {} }, cwd);
1855
+ longBox.updateResult({ content: [{ type: "text", text: longText }], details: {} }, false);
1856
+ longBox.setExpanded(true);
1857
+ const topView = (longBox.render(60) as string[]).map(stripAnsi);
1858
+ assert(topView.length === maxBody + 3, `expanded long box caps height to ${maxBody + 3} lines`);
1859
+ assert(!topView[0]!.includes("↑") && topView[topView.length - 1]!.includes("↓ 12 more"), "top of expanded box shows only ↓ N more");
1860
+ const [downBtn] = textSpans(longBox.render(60) as string[], "↓ 12 more");
1861
+ assert(downBtn !== undefined, "↓ N more is clickable on bottom border");
1862
+ click(longBox, downBtn!.row, downBtn!.start);
1863
+ const midView = (longBox.render(60) as string[]).map(stripAnsi);
1864
+ assert(midView[0]!.includes("↑ 4 more") && midView[midView.length - 1]!.includes("↓ 8 more"), "clicking ↓ N more scrolls body down");
1865
+ assert(midView.some((l) => l.includes("line 4")) && !midView.some((l) => l.includes("󱞩 line 1")), "scrolled viewport hides scrolled-past rows");
1866
+ const [upBtn] = textSpans(longBox.render(60) as string[], "↑ 4 more");
1867
+ assert(upBtn !== undefined, "↑ N more is clickable on top border");
1868
+ click(longBox, upBtn!.row, upBtn!.start);
1869
+ const backView = (longBox.render(60) as string[]).map(stripAnsi);
1870
+ assert(!backView[0]!.includes("↑") && backView.some((l) => l.includes("line 1")), "clicking ↑ N more scrolls back to top");
1871
+ const edge = paintScrollEdge("\x1b[48;2;10;20;30m\x1b[2m╭──────────╮\x1b[39m\x1b[49m", "\u256d", "\u256e", "\u2191 1 more", 24, (t) => `<bdr>${t}</bdr>`, (t) => `<pri>${t}</pri>`);
1872
+ assert(edge.startsWith("\x1b[48;2;10;20;30m") && edge.endsWith("\x1b[49m") && edge.includes("<pri>↑ 1 more</pri>"), "scroll edge preserves background and paints N more in primary");
1873
+ } finally {
1874
+ Object.defineProperty(process.stdout, "rows", { value: prevRows, configurable: true });
1875
+ }
1692
1876
  }
1693
1877
 
1694
1878
  // Capped timings map self-check