@hncode/hncode 0.7.8 → 0.8.1

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/src/tui.js CHANGED
@@ -22,6 +22,111 @@ import {
22
22
  } from './colors.js';
23
23
  import { copyText, readText, warmClipboard, readClipboardContentAsync, readClipboardTextOnly, imageUrlFromClipboardText, cleanupPastedImages, stopClipboardHelper } from './clipboard.js';
24
24
  import { visualWidth, estimateTokens, estimateTokensFloat, estimateMessagesTokens, estimateMessageTokens, messageTokens, expandTabs } from './term.js';
25
+ // The extracted modules are pulled in as NAMESPACES and unpacked into local bindings. That way adding a helper to
26
+ // one of them is a one-line change there, rather than an edit to a long named-import list that silently leaves a
27
+ // name out and fails at runtime with "X is not defined".
28
+ import * as text from './text.js';
29
+ import * as anim from './animate.js';
30
+ import * as comp from './composer.js';
31
+ import * as diffMod from './diff.js';
32
+
33
+ const {
34
+ ESC, stripAnsi, sanitizeText, tailChars, LIVE_OUTPUT_MAX_CHARS,
35
+ visualCol, col, fitAnsi, wrapWords,
36
+ } = text;
37
+ const {
38
+ SPINNER, REDUCED_MOTION_DOT, REDUCED_MOTION_CYCLE_MS, SPIN_PLACEHOLDER,
39
+ reducedMotionOn, spinnerFrame, sweepSettle, sweepPulse,
40
+ LIGHT_FRACTION, SPIN_TICK_MS, lightWidth, TAIL_CHARS, ANIM_FPS, FRAME_MS,
41
+ STEP_MS, TOOL_STEP_MS, ENTRY_EXIT_CHARS, lightMargin, crossMs, REST_MS, cycleMs,
42
+ lightOrigin, lightAt, shimmerText, STEP_CHARS, SWEEP_TICKS, SWEEP_TRAVEL_PAD, bandCharsFor, framesPerChar,
43
+ } = anim;
44
+ const {
45
+ composerInput, pasteMarker, PASTE_MARKER_RE, expandPastes, highlightPasteMarkers,
46
+ pasteMarkerIdAt, expandPasteMarkerAt, highlightSelection, adjacentPasteMarker,
47
+ } = comp;
48
+ const {
49
+ DIFF_CONTEXT_LINES, paintCode, alignLines, elideContext, editDiffRows, lineDiff,
50
+ } = diffMod;
51
+
52
+ // RE-EXPORTED SO THE SPLIT IS INVISIBLE TO CALLERS.
53
+ //
54
+ // These names were `export function` declarations in this file until they moved into the modules above. Anything that
55
+ // imported them from here — tests, the SDK's target list, a plugin — must keep working, so the same names are surfaced
56
+ // again from their new home. Adding a helper to one of those modules does NOT need a line here; this list only has to
57
+ // cover what used to be public.
58
+ export {
59
+ DIFF_CONTEXT_LINES, paintCode, alignLines, elideContext, editDiffRows, lineDiff,
60
+ } from './diff.js';
61
+ export {
62
+ composerInput, pasteMarker, PASTE_MARKER_RE, expandPastes, highlightPasteMarkers,
63
+ pasteMarkerIdAt, expandPasteMarkerAt, highlightSelection, adjacentPasteMarker,
64
+ } from './composer.js';
65
+ export {
66
+ SPINNER, REDUCED_MOTION_DOT, REDUCED_MOTION_CYCLE_MS, SPIN_PLACEHOLDER,
67
+ reducedMotionOn, spinnerFrame, sweepSettle, sweepPulse,
68
+ LIGHT_FRACTION, SPIN_TICK_MS, lightWidth, TAIL_CHARS, ANIM_FPS, FRAME_MS,
69
+ STEP_MS, TOOL_STEP_MS, ENTRY_EXIT_CHARS, lightMargin, crossMs, REST_MS, cycleMs,
70
+ lightOrigin, lightAt, shimmerText, STEP_CHARS, SWEEP_TICKS, bandCharsFor, framesPerChar,
71
+ } from './animate.js';
72
+ export {
73
+ ESC, stripAnsi, sanitizeText, tailChars, LIVE_OUTPUT_MAX_CHARS,
74
+ visualCol, col, fitAnsi, wrapWords, expandTabs,
75
+ } from './text.js';
76
+
77
+ import * as md from './markdown.js';
78
+
79
+ const {
80
+ MD_RENDER_VERSION, renderMdIncremental, splitBlocks, renderMdText, renderTable,
81
+ markdownLineToRows, mathImageCapable, MATH_INK, mathCellHeight, mathBlockRows,
82
+ stripMathDelimiters, placeTex, looksLikeInlineMath, inlineMarkdown,
83
+ } = md;
84
+
85
+ export {
86
+ MD_RENDER_VERSION, renderMdIncremental, splitBlocks, renderMdText, renderTable,
87
+ markdownLineToRows, mathImageCapable, MATH_INK, mathCellHeight, mathBlockRows,
88
+ stripMathDelimiters, placeTex, looksLikeInlineMath, inlineMarkdown,
89
+ } from './markdown.js';
90
+
91
+ import * as toolLine from './tool-line.js';
92
+
93
+ const { msgColorFor, keyArgument, formatToolLine } = toolLine;
94
+
95
+ export { msgColorFor, keyArgument, formatToolLine } from './tool-line.js';
96
+
97
+ import * as panelMod from './panels.js';
98
+
99
+ const {
100
+ TODO_MAX_VISIBLE, QUEUE_MAX_VISIBLE, selectVisibleTodos, todoRow, todosAllComplete,
101
+ todoListFinished, todoRowCount, todoPanelHeight, renderTodoPanel,
102
+ queueRowCount, queuePanelHeight, renderQueuePanel,
103
+ renderTitleBar, titleRowsNeeded, titleRowCount,
104
+ } = panelMod;
105
+
106
+ export {
107
+ TODO_MAX_VISIBLE, QUEUE_MAX_VISIBLE, selectVisibleTodos, todoRow, todosAllComplete,
108
+ todoListFinished, todoRowCount, todoPanelHeight, renderTodoPanel,
109
+ queueRowCount, queuePanelHeight, renderQueuePanel,
110
+ renderTitleBar, titleRowsNeeded, titleRowCount,
111
+ } from './panels.js';
112
+
113
+ import { planRows, bgTaskRows } from './rows-plan-bg.js';
114
+ import { compactionRows, thinkingRows } from './rows-status.js';
115
+ import { toolResultRows } from './rows-tool-result.js';
116
+
117
+ import * as fmt from './format.js';
118
+
119
+ const {
120
+ trimDecimal, scaleUnit, fmtTokens, fmtCount, moneyAmount, formatCost, sparkChart,
121
+ usagePercent, fmtDuration, fmtTokensShort, proseSummary, elapsedTail, justify,
122
+ stallIntensity, STALL_AFTER_MS, STALL_FADE_MS,
123
+ } = fmt;
124
+
125
+ export {
126
+ trimDecimal, scaleUnit, fmtTokens, fmtCount, moneyAmount, formatCost, sparkChart,
127
+ usagePercent, fmtDuration, fmtTokensShort, proseSummary, elapsedTail, justify,
128
+ stallIntensity, STALL_AFTER_MS, STALL_FADE_MS,
129
+ } from './format.js';
25
130
  import { highlightLine, langForPath } from './highlight.js';
26
131
  // The picker is composited onto the frame as a cell layer rather than assigned over
27
132
  // it (see src/cell-buffer.js), so the transcript BESIDE the card survives.
@@ -116,7 +221,6 @@ import { killLspClientsSync } from './tools/diagnostics.js';
116
221
  import { startControlServer } from './ci.js';
117
222
  import { attachToDaemon } from './web-daemon-client.js';
118
223
 
119
- const ESC = '\x1b';
120
224
  const VERSION = localVersion();
121
225
 
122
226
  // Well-known base URLs for catalog providers that do not publish an `api` field
@@ -553,519 +657,6 @@ const MAX_PICKER = 200; // max picker list rows shown at once
553
657
  // which costs one layout pass instead of permanent memory.
554
658
  const CACHE_KEEP = 300;
555
659
  const TIP_INTERVAL = 15000;
556
- // Braille spinner frames for the "Working" indicator (orange).
557
- const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
558
- // The REDUCED-MOTION spinner: a single dot that breathes on a slow cycle, rather
559
- // than a rotating glyph. Claude Code does this (`REDUCED_MOTION_CYCLE_MS = 2000`,
560
- // "1s visible, 1s dim") and the reasoning is worth keeping: a fully static glyph
561
- // reads as "hung", so the slow brightness change is what says "still working"
562
- // without any motion. Two seconds is slow enough not to draw the eye.
563
- const REDUCED_MOTION_DOT = '●';
564
- const REDUCED_MOTION_CYCLE_MS = 2000;
565
- // Stand-in for the LIVE spinner glyph inside a CACHED row. A pending thinking
566
- // block must not be re-wrapped by the 80ms spin tick (see renderChatLines), so
567
- // its preview is cached with this sentinel and the real frame is substituted in
568
- // afterwards. It occupies 0 columns, so the swap never disturbs the layout.
569
- const SPIN_PLACEHOLDER = '\u0000';
570
-
571
- /** Is reduced motion on for this session? Read from config, or the env override. */
572
- export function reducedMotionOn(state) {
573
- if (!state) return false;
574
- if (state.reducedMotion !== undefined) return !!state.reducedMotion;
575
- const env = process.env.HNCODE_REDUCED_MOTION;
576
- if (env !== undefined) return /^(1|true|yes|on)$/i.test(env);
577
- return !!(state.cfg && state.cfg.reducedMotion);
578
- }
579
-
580
- /**
581
- * The frames a SPINNER-style animation shows: { glyph, dim }.
582
- *
583
- * In normal mode the glyph rotates and is never dim. In reduced motion the glyph is
584
- * a constant dot whose brightness flips once per second — the same 2-second cycle
585
- * Claude uses. Returning both pieces means every caller (the Working row, a pending
586
- * tool, a thinking preview) gets the same treatment from one place.
587
- */
588
- export function spinnerFrame(state, tick) {
589
- if (reducedMotionOn(state)) {
590
- const t = tick !== undefined ? tick : (state && state.spin) || 0;
591
- return { glyph: REDUCED_MOTION_DOT, dim: Math.floor(t / (REDUCED_MOTION_CYCLE_MS / 80)) % 2 === 1 };
592
- }
593
- const n = SPINNER.length;
594
- const i = ((tick !== undefined ? tick : (state && state.spin) || 0) % n + n) % n;
595
- return { glyph: SPINNER[i], dim: false };
596
- }
597
-
598
- /**
599
- * A sweep that SETTLES: a character the band has passed stays at 1.
600
- *
601
- * This is the shape the Working row's colour phase needs, and the two previous
602
- * attempts both got it wrong by reusing a travelling PULSE:
603
- *
604
- * * the original `(head - charAt) / BAND` ramps DOWN as the head passes, so a
605
- * character lit up and then went DARK again — the phrase never became orange;
606
- * * the cosine `0.5 * (1 + cos(PI * d / half))` is a bell centred on the band, so
607
- * every character dimmed again once the band left it. Measured over one colour
608
- * phase it animated `[ ] -> [ :#@#: ] -> [ :#] -> [ ]`: a light sweeping across
609
- * and leaving nothing behind.
610
- *
611
- * The convention that fixes it, stated once here:
612
- *
613
- * `dist >= 0` the band is past this character -> 1 (settled)
614
- * `-half < dist < 0` the band is on it -> ramp 0 -> 1
615
- * `dist <= -half` not reached yet -> 0
616
- *
617
- * `dist` is `head - position`, so a LARGER `dist` means "further behind the head".
618
- * `edge` shapes only the transition band:
619
- * `cosine` — a raised cosine, so both ends of the ramp are gentle;
620
- * `linear` — a straight ramp, sharpest at the settle point.
621
- */
622
- export function sweepSettle(dist, half, edge = 'cosine') {
623
- const h = Math.max(1e-6, half);
624
- if (dist >= 0) return 1; // passed: stays lit
625
- if (dist <= -h) return 0; // not yet reached
626
- const x = (dist + h) / h; // 0 at the far edge, 1 at the settle point
627
- return edge === 'linear' ? x : 0.5 * (1 - Math.cos(Math.PI * x));
628
- }
629
-
630
- /**
631
- * A sweep that PASSES: a character lights up under the band and returns to 0 after it.
632
- *
633
- * The counterpart to `sweepSettle`, and the difference is the whole point:
634
- *
635
- * sweepSettle a character the band has passed STAYS at 1 — paint being laid down
636
- * sweepPulse a character returns to 0 once the band leaves — a light moving over
637
- *
638
- * `half` is the HALF-width of the light, so `2 * half` is its full width, and `flat` is the half-width
639
- * of its FULLY LIT CORE. The shape is:
640
- *
641
- * |dist| <= flat the core, at 1
642
- * flat < |dist| < half a shoulder, falling from 1 to 0
643
- *
644
- * Both outer ends reach 0, which is what makes the light arrive and leave without a seam. `flat = 0`
645
- * ramps across the whole width and leaves a single bright point in the middle; `flat = half` is a solid
646
- * block with no fade at all.
647
- *
648
- * `dist` is `head - position`, the same convention `sweepSettle` uses.
649
- */
650
- export function sweepPulse(dist, half, edge = 'cosine', flat = 0) {
651
- const h = Math.max(1e-6, half);
652
- if (dist <= -h || dist >= h) return 0; // outside the light
653
- // A FLAT CORE: the middle `2 * flat` of the light is fully lit, and the cosine shapes only the
654
- // shoulders either side of it. `flat` is a half-width, so `flat = h` is the old behaviour — a ramp
655
- // across the whole light with a single bright point in the middle.
656
- const core = Math.max(0, Math.min(h, flat));
657
- const a = Math.abs(dist);
658
- if (a <= core) return 1;
659
- const x = (a - core) / (h - core); // 0 where the core ends, 1 at the outer edge
660
- if (edge === 'linear') return 1 - x;
661
- return 0.5 * (1 + Math.cos(Math.PI * x)); // raised cosine from 1 down to 0
662
- }
663
-
664
- /**
665
- * The geometry of a passing light, shared by the Working row and the Using row.
666
- *
667
- * Both rows show the same gesture — a light running left to right, then a pause — so the numbers live
668
- * here rather than being repeated at each row and drifting apart.
669
- *
670
- * The light is a QUARTER OF THE ROW at full brightness, with a cosine fade either side, and it scales
671
- * with the text: `Working...` is ten characters, so its core is two; a 60-character line gets fifteen.
672
- *
673
- * It crosses in a fixed `CROSS_MS` whatever the row, so a long line is swept faster — see that constant
674
- * for why, and for what it costs.
675
- */
676
-
677
- /**
678
- * The light's CORE width as a fraction of the row, floored to one character.
679
- *
680
- * Claude Code's shimmer has no core at all — a single index is bright. The floor of 1 is the same idea: a
681
- * glint is a point travelling along the row, not a wash sweeping over it. It stops at one rather than
682
- * shrinking to zero because a two-character row still needs something to see.
683
- */
684
- export const LIGHT_FRACTION = 1 / 4;
685
-
686
- /**
687
- * Milliseconds per unit of `state.spin`.
688
- *
689
- * The spinner advances `spin` every 80ms (see the spinTimer in startTUI). The light's geometry is in
690
- * real time, so a caller holding only a tick count needs this to convert — named here so the two
691
- * cannot drift apart silently: the timer and this constant describe the same interval.
692
- */
693
- export const SPIN_TICK_MS = 80;
694
-
695
- /**
696
- * The light's FULLY LIT CORE, in characters: a quarter of the row, rounded down.
697
- *
698
- * Rounding down is deliberate: `Working...` is ten characters, so its core is two. Rounding up would make
699
- * it grow on rows where it should not, and a fractional width is something no terminal draws.
700
- *
701
- * The floor of 2 keeps a short row visible — a three-character row would otherwise round to one, and a
702
- * one-character core with a fade either side is a lit cell that barely registers.
703
- *
704
- * This is the core, NOT the total extent: `TAIL_CHARS` of cosine fade is added either side of it.
705
- */
706
- export function lightWidth(n) {
707
- return Math.max(2, Math.floor(n * LIGHT_FRACTION));
708
- }
709
- /**
710
- * The fade either side of the core, in characters.
711
- * TWO, not one: a band of one character is wide enough in truecolor but vanishes under 256 colours, where
712
- * the light has only two indices and a single lit cell is a blink. Two keeps the sweep legible in both
713
- * palettes: the peak moves one letter at a time, and the row reads as a lamp travelling rather than as a
714
- * single pixel flashing.
715
- */
716
- export const TAIL_CHARS = 4;
717
-
718
-
719
- /**
720
- * The light's half-width, INCLUDING the fade. This is the extent `lightAt` sweeps.
721
- *
722
- * THE TAILS ARE CAPPED so the light stays narrower than the row: the total is held to `n - 1`, which
723
- * keeps at least one dark column at each end. Those dark columns are what make the light read as an
724
- * object with edges instead of as a row that brightens and dims.
725
- *
726
- * The CORE gives way first — `coreHalf` shrinks with the cap — because the fade is what makes the light
727
- * arrive and leave smoothly, and a short row needs that more than it needs a wide middle.
728
- */
729
- function totalHalf(n) {
730
- const want = lightWidth(n) + 2 * TAIL_CHARS;
731
- const capped = Math.min(want, Math.max(2, n - 1));
732
- return capped / 2;
733
- }
734
-
735
- /** The half-width of the fully lit core, for `sweepPulse`'s `flat` parameter. */
736
- function coreHalf(n) {
737
- // Never wider than the light itself, and never more than half the total: `sweepPulse` requires it.
738
- return Math.min(lightWidth(n), totalHalf(n) * 2) / 2;
739
- }
740
-
741
- /**
742
- * The animation's frame rate: 30fps, the whole program's rate for animated rows.
743
- *
744
- * Rendering one frame measures 0.17ms, so a much higher rate is physically possible — the earlier tick
745
- * ran at 60fps — but the light's smoothness is not the only cost: every animated row redraws, and the
746
- * rate is a choice about the whole UI rather than about this one light.
747
- *
748
- * At 30fps a frame is 33ms, which is what makes the crossing in `CROSS_MS` six frames long.
749
- */
750
- export const ANIM_FPS = 30;
751
- export const FRAME_MS = 1000 / ANIM_FPS;
752
-
753
- /**
754
- * How long one step of the light lasts, in milliseconds.
755
- *
756
- * FIXED at 80ms — fast enough that a sweep reads as motion, slow enough that the eye is not chasing it.
757
- *
758
- * It followed the output rate for a while. That was tried and dropped: a model writing slowly got a
759
- * sweep so slow it looked stuck, a fast one got a blur, and the same row changed pace between turns for
760
- * no reason the reader could see. One rate is calmer and predictable, which is what an ambient
761
- * indicator needs to be.
762
- */
763
- export const STEP_MS = 65;
764
-
765
- /**
766
- * The step for a TOOL name, slower than the Working row's.
767
- *
768
- * A tool name is short — `Read` is four characters — so at the Working row's rate the light crosses it in
769
- * 560ms and the row is dark for the rest of the cycle. On screen that reads as a single flash, not as
770
- * movement. 150ms per character gives a four-character name a 1.4s round: slow enough to follow, still
771
- * obviously running.
772
- */
773
- const TOOL_STEP_MS = 150;
774
-
775
- /**
776
- * How long the light stays on one character, from how fast tokens are arriving.
777
- *
778
- * `tps` is output tokens per second for the step in flight. A fast stream should look fast — the row
779
- * keeping a leisurely 50ms step while tokens pour in reads as the animation lagging behind the text it
780
- * is supposed to accompany.
781
- *
782
- * The clamp is the important half. Under about 10 tok/s the model is thinking more than writing and the
783
- * sweep slows down so it does not look frantic over a trickle; above about 80 tok/s it is a wall of text
784
- * and the light moves quickly but never strobes. 28ms is just under a 33ms render frame, so a step is
785
- * always painted at least once; 200ms is slow enough to read as deliberate without looking stuck.
786
- */
787
-
788
-
789
-
790
-
791
- /**
792
- * How far outside the row the light starts and ends, in characters.
793
- *
794
- * TEN, exactly as Claude Code's `messageWidth + 20` splits into ten either side. This is what sets the
795
- * pace of a round: a 10-character row travels 30 cells, so a round is 1500ms — the same as Claude Code.
796
- *
797
- * A shorter margin made the sweep finish sooner and read as a twitch. It must not be shorter than the
798
- * light's own half-width either, or the light would still be lighting the last characters when the round
799
- * ended; `lightMargin` takes the larger of the two.
800
- */
801
- const ENTRY_EXIT_CHARS = 10;
802
- /**
803
- * The margin for a row of `n` characters: the target ten, or the light's half-width if that is larger —
804
- * but CAPPED so the light reaches the text in reasonable time.
805
- *
806
- * Ten cells either side is what makes the timing match Claude Code on a long row. On a SHORT row it is
807
- * most of the cycle: `Edit` is four characters, so the travel is 24 cells and the light spends the first
808
- * 500ms still outside the text, showing nothing. A row that looks frozen for half a second and then
809
- * blinks once reads as broken, which is exactly how the Using row was reported.
810
- *
811
- * The cap is `n + 4` per side at most, so a short row spends a few steps entering rather than ten, and a
812
- * long row is unchanged.
813
- */
814
- function lightMargin(n) {
815
- const half = totalHalf(Math.max(1, n));
816
- return Math.max(1, Math.min(ENTRY_EXIT_CHARS, Math.max(half, Math.ceil(Math.max(1, n) / 4))));
817
- }
818
-
819
- /**
820
- * The crossing time for a row of `count` characters — ONE FULL ROUND, entry and exit included.
821
- *
822
- * `(count + 2 * lightMargin(count)) * stepMs * SWEEP_TICKS / 10`. The light is over the visible text for only
823
- * `count * stepMs` of it; the rest is the entry and exit runs, which is what keeps the sweep from snapping on
824
- * and off.
825
- *
826
- * `SWEEP_TICKS` IS THE RESOLUTION KNOB. At the old value of 10 a ten-character row crossed in 1235ms — about
827
- * 19 frames at 65ms — and the light traversed its own five-character band in a third of that, so each glyph
828
- * took only five distinct brightness values and the fade read as a five-step ramp. Every doubling of the tick
829
- * count doubles the frames each glyph is under the light, which is the only way to make the fade finer without
830
- * changing its shape or its speed across the row.
831
- */
832
- export function crossMs(count, stepMs = STEP_MS) {
833
- const cells = Math.max(1, count) + 2 * lightMargin(count);
834
- return cells * stepMs * (SWEEP_TICKS / 10);
835
- }
836
-
837
- /**
838
- * The rest between rounds, in milliseconds.
839
- *
840
- * NOT zero. With `REST_MS = 0` the sweep wrapped straight back to the start the instant it left the right
841
- * edge, so the row went from "light on the last letter" to "light on nothing" to "light on the first
842
- * letter" within two frames — which reads as the animation resetting rather than restarting.
843
- *
844
- * Claude Code can use zero because its entry run is ten cells: the light is already off the row for a
845
- * second before it comes back. Ours enters from three cells away, too short to cover the wrap.
846
- */
847
- export const REST_MS = 300;
848
-
849
- /**
850
- * The full cycle for a row: one crossing, then the rest.
851
- *
852
- * `count` enters into it: a longer row has more characters to light, so its cycle is longer. It used to be
853
- * constant, because a fixed-time crossing spread itself over however many cells there happened to be.
854
- */
855
- export function cycleMs(count, stepMs = STEP_MS) {
856
- return crossMs(count, stepMs) + REST_MS;
857
- }
858
-
859
- /**
860
- * The wall-clock time the light's animation began, for a row anchored at this tick.
861
- *
862
- * `spin` advances every SPIN_TICK_MS while the render path redraws far more often, so a phase taken
863
- * straight from the tick count steps in 80ms jumps. Converting the anchor ONCE to a wall-clock origin
864
- * lets every later frame measure real elapsed time instead.
865
- *
866
- * The store is MODULE-LEVEL, and deliberately not a field on `state`. The caller for a pending tool
867
- * row is `formatToolLine`, a module-level function with no access to `state` — reading it there threw
868
- * "state is not defined" and took the whole TUI down through the unhandledRejection handler. The key
869
- * is the anchor tick, so a new turn gets a new origin.
870
- */
871
- const lightOrigins = new Map();
872
- /**
873
- * @param {string} key identifies the animation — `tool:12`, `work:12` — so two rows anchored on
874
- * the same tick keep separate origins.
875
- * @param {number} anchor the tick the animation began on.
876
- * @param {number} now the tick it is being drawn at.
877
- *
878
- * `key` and `anchor` are separate arguments on purpose. An earlier version took only the anchor and
879
- * derived the key from it, so a caller passing an already-prefixed `tool:0` produced
880
- * `(0 - 'tool:0') * 80` — arithmetic on a string, which is NaN. The origin then became NaN, every
881
- * colour became `38;5;NaN`, and the terminal drew the row in the default colour: a silent failure
882
- * that looked like the animation simply not running.
883
- */
884
- function lightOrigin(key, anchor, now) {
885
- let origin = lightOrigins.get(key);
886
- if (origin === undefined) {
887
- // THE ORIGIN IS "NOW", NOT BACK-DATED FROM THE TICK COUNT.
888
- //
889
- // This used to be `Date.now() - (now - anchor) * SPIN_TICK_MS`, so a row that began mid-animation
890
- // picked up the phase its anchor implied. That is wrong for this row: the first frame it is DRAWN is
891
- // not the tick its anchor was set on — the start animation runs first, several ticks earlier. Back-
892
- // dating by that gap made the sweep begin part-way across, so the light appeared to jump forward and
893
- // then restart from the left.
894
- //
895
- // Starting at "now" means a new animation always begins at the left edge.
896
- //
897
- // `anchor` and `now` stay in the signature because callers pass them and the shape is part of the
898
- // contract; the phase no longer depends on their difference.
899
- void anchor;
900
- void now;
901
- origin = Date.now();
902
- if (!Number.isFinite(origin)) origin = Date.now();
903
- // EVICT THE OLDEST, never clear the map.
904
- //
905
- // This used to be `if (size > 32) clear()`. The anchor changes every turn and for every restored tool
906
- // row, so the map filled quickly — and clearing it dropped the origin of the row currently on screen,
907
- // which was then recreated with a FRESH timestamp. The light restarted from the left edge whenever the
908
- // table filled, roughly once a second: the sweep looked cut off mid-stroke rather than moving.
909
- //
910
- // A Map iterates in insertion order, so the first key is the least recently added — exactly the entry
911
- // no row is asking about any more.
912
- if (lightOrigins.size > 64) {
913
- const oldest = lightOrigins.keys().next().value;
914
- lightOrigins.delete(oldest);
915
- }
916
- lightOrigins.set(key, origin);
917
- }
918
- return origin;
919
- }
920
-
921
- /**
922
- * How lit one character is, given its index and the row length.
923
- *
924
- * Returns 0..1. The position arrives as an INDEX and the row length rather than a pre-divided
925
- * fraction, because the light's width is itself a fraction of the row — both are then in the same
926
- * unit of "characters", so the light cannot be scaled twice by accident.
927
- *
928
- * `phaseMs` is MILLISECONDS within the cycle, not a tick count.
929
- *
930
- * Time is the right unit because the light's smoothness depends on how far it moves per RENDERED
931
- * frame, and the frame rate is not the caller's 80ms spinner tick. Stepping by that tick means the
932
- * crossing has to finish in a whole number of 80ms frames, so keeping each step small enough to look
933
- * smooth forced a many-second crossing on a long row — measured, 12 seconds for 60 characters, and
934
- * 1.9 seconds for `Working...`. Taking milliseconds decouples the two: the caller may redraw as often
935
- * as it likes, and the light's speed is stated directly rather than implied by a frame count.
936
- */
937
- export function lightAt(phaseMs, index, count, edge = 'cosine', stepMs = STEP_MS) {
938
- const n = Math.max(1, count);
939
- // Two widths, and the distinction is the shape of the light: `half` is the OUTER edge (core plus the
940
- // fade either side) and `core` is the part that stays at full brightness.
941
- const half = totalHalf(n);
942
- const core = coreHalf(n);
943
- // The character's centre, in characters from the start of the row. Measuring against the left edge
944
- // would make the light peak BETWEEN characters, so each would flash at less than full strength.
945
- const centre = index + 0.5;
946
- // The centre crosses from fully off the left of the row to fully off its right, so the light slides
947
- // in and out rather than popping into existence on the first character.
948
- //
949
- // THE REST HALF NEEDS NO SPECIAL CASE. Past the crossing the progress exceeds 1 and the head travels
950
- // further past the row's right edge — where `sweepPulse` is already 0 — so the light is dark by the
951
- // same arithmetic that makes it leave. A guard was written for this and then removed after 9450
952
- // (phase, character) combinations showed it never once changed a value.
953
- // THE HEAD IS CLAUDE CODE'S `glimmerIndex`, cell for cell, and the run matches its `messageWidth + 20`.
954
- //
955
- // Ten cells of margin at each end is what makes the timing match: a 10-character row takes 30 steps, so
956
- // 1500ms a round — the same as Claude Code. An earlier version used the light's own half-width as the
957
- // margin, which was tighter and faster, and read as a twitch rather than a sweep.
958
- //
959
- // The margin is `max(10, half)`: ten is the target, but the light must clear its own width or it would
960
- // still be lighting the last characters when the round ended — the failure the half-width version was
961
- // written to fix, and which a flat ten reintroduces on a wide band.
962
- const margin = lightMargin(n);
963
- const travel = n + 2 * margin;
964
- // THE HEAD IS CONTINUOUS, NOT QUANTISED TO WHOLE STEPS.
965
- //
966
- // `Math.floor` here rounded the head to the last whole tick, so on a 65ms frame a ten-character row offered
967
- // the light about twenty distinct positions and each glyph saw five brightness values — a five-step ramp
968
- // where the eye can see twenty. The position is a FLOAT now: the pulse is already continuous in `dist`, so
969
- // every frame lands the light somewhere between two cells and the fade is as fine as the frame rate allows.
970
- // `STEP_CHARS` still scales how far one step moves, which is a shape decision, not a resolution one.
971
- const progress = Math.max(0, Math.min(1, phaseMs / crossMs(n, stepMs)));
972
- const head = (-margin + progress * travel) * STEP_CHARS;
973
- // `edge` shapes the shoulder: a raised cosine leaves its outer end gentle, a linear one is sharpest
974
- // where it meets the core. It arrives as a PARAMETER rather than being read from config, because this
975
- // is a module-level function and the TUI state lives inside startTUI's closure — the trap that once
976
- // made a pending tool row throw a ReferenceError and take the whole TUI down with it.
977
- return sweepPulse(head - centre, half, edge, core);
978
- }
979
-
980
- /**
981
- * Paint `text` with the travelling light already mixed into each glyph.
982
- *
983
- * ONE FUNCTION FOR BOTH ANIMATED ROWS — the Working row and a pending tool's "Using <Tool>" — because they
984
- * were two hand-written copies of the same loop. That is how they drifted: the Working row passed `busy` to
985
- * `lightAt` and the tool row did not, so one stepped at 50ms/cell inside a 1050ms cycle while the other
986
- * stepped at 200ms/cell inside a 4050ms cycle. The slow row could not finish before its own modulus
987
- * wrapped, which is why its light only ever reached the fourth letter before restarting.
988
- *
989
- * Everything about the light is decided here — the rate, the shoulder shape, the band width — so a change to
990
- * the animation lands on both rows at once.
991
- *
992
- * @param {string} text the row's text
993
- * @param {number} phaseMs milliseconds into the cycle
994
- * @param {number[]} base resting colour, [r, g, b]
995
- * @param {number[]} glint the colour the light lifts the text toward
996
- * @param {string} edge shoulder shape: 'cosine' (default) or 'linear'
997
- * @returns {string} ANSI, ready to splice into a row
998
- */
999
- function shimmerText(text, phaseMs, base, glint, edge = 'cosine', stepMs = STEP_MS) {
1000
- const s = String(text == null ? '' : text);
1001
- const n = s.length;
1002
- if (!n) return '';
1003
- const out = [];
1004
- for (let i = 0; i < n; i++) {
1005
- const t = Math.max(0, Math.min(1, lightAt(phaseMs, i, n, edge, stepMs)));
1006
- const r = Math.round(base[0] + (glint[0] - base[0]) * t);
1007
- const g = Math.round(base[1] + (glint[1] - base[1]) * t);
1008
- const b = Math.round(base[2] + (glint[2] - base[2]) * t);
1009
- out.push(col(s[i], lerpColor(r, g, b, r, g, b, 0)));
1010
- }
1011
- return out.join('');
1012
- }
1013
- // How far the light advances in one step, in characters.
1014
- //
1015
- // One character per step is the most literal reading of "move by letters", and it is the right shape:
1016
- // the light lands on a glyph, lights it and its neighbours, then moves to the next. A larger step would
1017
- // move in pairs, which reads as a coarser crawl without looking any more deliberate.
1018
- export const STEP_CHARS = 1;
1019
-
1020
-
1021
- // ---------------------------------------------------------------------------
1022
- // Sweep parameters — ONE set of numbers for every animated row
1023
- // ---------------------------------------------------------------------------
1024
- // The parameter that decides whether a sweep reads as a GRADIENT or as a SNAP is
1025
- // frames-per-character: how many 80ms ticks a character spends crossing the band.
1026
- //
1027
- // framesPerChar = BAND * ticks / travel (BAND = bandChars / n)
1028
- //
1029
- // With the old `travel = 1 + 2*BAND` this approached `ticks / 2` as the band grew, so
1030
- // the half-sweep's tick count ALONE capped the smoothness: the previous values (band
1031
- // 3.3 chars, 6 ticks) gave 1.20 frames per character, meaning each character changed
1032
- // colour inside a single frame — a snap, not a fade. The comment claiming "a 3-char
1033
- // band gives each char ~3 frames" was simply wrong.
1034
- //
1035
- // The geometry also wasted margin at both ends: the head only has to run from the far
1036
- // edge of the band to the settle point, i.e. `travel = 1 + BAND`, not `1 + 2*BAND`.
1037
- // Correcting that buys ~25% more frames for free, because the extra was spent sweeping
1038
- // through empty space before and after the row.
1039
- // FRAMES PER CHARACTER IS THE SMOOTHNESS. With `STEP_MS = 65` and a band of `n/2`, the light spends
1040
- // `BAND * ticks / (1 + BAND)` frames on each character; at 10 ticks that is 3.3, so a glyph took only three
1041
- // or four distinct brightness values and the fade read as a step. Doubling the tick count doubles that to
1042
- // 6.7 — the light still crosses in the same ORDER, it just takes twice as long to do it, which is the only
1043
- // way to buy resolution without changing the shape.
1044
- export const SWEEP_TICKS = 20; // ticks per half-sweep (1.3s at 65ms, so a 2.6s cycle)
1045
- const SWEEP_TRAVEL_PAD = 1; // head runs from -BAND to 1
1046
-
1047
- /**
1048
- * Band width in characters, scaled to the row so every row is equally smooth.
1049
- *
1050
- * HALF THE ROW, with a floor of 3 characters. Because the band is then always `n/2`,
1051
- * `BAND = 0.5` for every row of 6+ characters, so frames-per-character — and therefore
1052
- * the visual smoothness — is the SAME for a 6-char tool name and a 60-char phrase.
1053
- *
1054
- * An earlier version capped the band at 6 characters, which made BAND shrink as the row
1055
- * grew: a 30-char row got 1.67 frames per character and snapped, so the cap defeated the
1056
- * very scaling it was part of. The floor matters for very short rows, where half the row
1057
- * would be a 2-char band — a flash rather than a sweep.
1058
- */
1059
- export function bandCharsFor(n) {
1060
- return Math.max(3, n / 2);
1061
- }
1062
-
1063
- /** Frames each character spends inside the band — the smoothness measure. */
1064
- export function framesPerChar(n, ticks = SWEEP_TICKS) {
1065
- const BAND = bandCharsFor(n) / n;
1066
- return (BAND * ticks) / (1 + BAND * SWEEP_TRAVEL_PAD);
1067
- }
1068
-
1069
660
  // How long a foreground Bash command runs before its card advertises Ctrl+B, and
1070
661
  // the hint text itself. Mirrors kimi-code's tool-call card (DETACH_HINT_*).
1071
662
  const DETACH_HINT_DELAY_MS = 10_000;
@@ -1322,66 +913,7 @@ const WORKING_MESSAGES = [
1322
913
  ];
1323
914
 
1324
915
  // ---- ANSI helpers ----
1325
- function stripAnsi(s) {
1326
- return String(s)
1327
- .replace(/\x1b\[[0-9;?]*[a-zA-Z]/g, '')
1328
- .replace(/\x1b\[[0-9;?]* [a-zA-Z]/g, '')
1329
- .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
1330
- }
1331
-
1332
- // Make UNTRUSTED text safe to paint: file contents from Read, command output from
1333
- // Bash, diff bodies, tool arguments.
1334
- //
1335
- // The goal is to keep the content as ORIGINAL as possible while stopping the
1336
- // terminal from OBEYING it. Only the ESC byte is rewritten — every following byte
1337
- // (the `[31m`, the `[10;20H` parameters) is shown verbatim, so nothing is lost:
1338
- //
1339
- // file contains: ESC [ 3 1 m E R R O R ESC [ 0 m
1340
- // screen shows : ^[ [ 3 1 m E R R O R ^[ [ 0 m
1341
- //
1342
- // A terminal cannot act on a sequence whose ESC has been split into `^[`, so:
1343
- // * `ESC[31m` no longer recolours half the transcript
1344
- // * `ESC[0m` no longer resets the row's styling mid-line
1345
- // * `ESC[10;20H` / `ESC[2J` no longer move the cursor or clear the screen
1346
- //
1347
- // `^[` is the same convention `cat -v`, `less` and `bat` use for ESC, so it reads
1348
- // as "there is an escape here" rather than as content. Tab is kept (the renderer
1349
- // expands it) and newlines are the caller's business; only the dangerous C0
1350
- // controls are defanged, and they are shown as their caret form so they remain
1351
- // visible instead of silently vanishing.
1352
- export function sanitizeText(s) {
1353
- return String(s == null ? '' : s)
1354
- // ESC -> "^[" . The rest of the sequence is untouched.
1355
- .replace(/\x1b/g, '^[')
1356
- // A bare BEL/BS/VT/FF would still be interpreted by some terminals.
1357
- .replace(/\x07/g, '^G')
1358
- .replace(/\x08/g, '^H')
1359
- .replace(/[\x0b\x0c]/g, ' ')
1360
- // Drop NUL and the remaining C0 controls (they have no visible form).
1361
- .replace(/[\x00-\x06\x0e-\x1f\x7f]/g, '');
1362
- }
1363
-
1364
- /**
1365
- * How much of a running command's output to KEEP, not just display.
1366
- *
1367
- * This string is mirrored into the hub row (and so into the SSE patch the
1368
- * browser applies on every frame), which means an unbounded buffer grows the
1369
- * terminal's row, the hub's row and the browser's copy at the same time. Only
1370
- * the tail is ever drawn, so only the tail is worth holding.
1371
- */
1372
- export const LIVE_OUTPUT_MAX_CHARS = 64 * 1024;
1373
-
1374
- /** The last `max` CHARACTERS of `s`, cut on a line boundary so the tail never
1375
- starts mid-line. */
1376
- export function tailChars(s, max) {
1377
- const str = String(s == null ? '' : s);
1378
- if (str.length <= max) return str;
1379
- const cut = str.slice(str.length - max);
1380
- const nl = cut.indexOf('\n');
1381
- return nl >= 0 ? cut.slice(nl + 1) : cut;
1382
- }
1383
916
 
1384
- function visualCol(s) { return visualWidth(stripAnsi(String(s))); }
1385
917
  // The width the category strip wants if it is not wrapped: `Categories: ` plus every label,
1386
918
  // joined by a space. Used to size the picker card, so a strip that FITS stays on one line.
1387
919
  function catStripWidth(b) {
@@ -1399,8 +931,6 @@ function catStripWidth(b) {
1399
931
  return n;
1400
932
  }
1401
933
 
1402
- function col(text, c) { return c + String(text) + C.reset; }
1403
-
1404
934
  // A message the USER actually typed, as opposed to one the harness injected with
1405
935
  // role 'user'. `beginTurn` (file-history) runs once per real prompt, and /undo's
1406
936
  // picker lists them, so both must agree on what counts. Harness notes are marked
@@ -1415,81 +945,6 @@ export function isRealUserPrompt(m) {
1415
945
  return true;
1416
946
  }
1417
947
 
1418
- function fitAnsi(s, w) {
1419
- const str = String(s);
1420
- const v = visualCol(str);
1421
- if (v < w) return str + ' '.repeat(w - v);
1422
- if (v === w) return str;
1423
- let out = '';
1424
- let n = 0;
1425
- let i = 0;
1426
- while (i < str.length) {
1427
- if (str[i] === ESC) {
1428
- const m = /^\x1b\[[0-9;?]*[a-zA-Z]/.exec(str.slice(i))
1429
- || /^\x1b\[[0-9;?]* [a-zA-Z]/.exec(str.slice(i))
1430
- || /^\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/.exec(str.slice(i));
1431
- if (m) { out += m[0]; i += m[0].length; continue; }
1432
- }
1433
- const cp = str.codePointAt(i);
1434
- const ch = String.fromCodePoint(cp);
1435
- const cw = visualWidth(ch);
1436
- if (n + cw > w) break;
1437
- n += cw;
1438
- out += ch;
1439
- i += cp > 0xffff ? 2 : 1;
1440
- }
1441
- if (n < w) out += ' '.repeat(w - n);
1442
- return out;
1443
- }
1444
-
1445
- function wrapWords(str, width) {
1446
- width = Math.max(1, width | 0);
1447
- const out = [];
1448
- let line = '';
1449
- // Running width of `line`. It used to be recomputed with
1450
- // `visualCol(line + ' ' + w)` on EVERY word, which is O(line) per word and so
1451
- // O(n²) per paragraph — a single long line (a streamed paragraph, a wide table
1452
- // row) cost ~46ms at 20KB and froze the UI on every markdown chunk. Widths are
1453
- // additive for the plain text this receives (no ANSI is present until
1454
- // inlineMarkdown runs later), so accumulate instead of re-measuring.
1455
- let lineW = 0;
1456
- // Expand tabs first: visualCol counts '\t' as 0 columns but the terminal
1457
- // advances to the next tab stop, which made the row wider than computed and
1458
- // wrapped it onto the following line.
1459
- const words = expandTabs(str).split(' ');
1460
- for (const w of words) {
1461
- const wW = visualCol(w);
1462
- // A word longer than the line must be hard-split. This MUST measure visual
1463
- // columns (not string length): CJK characters occupy two cells, so slicing
1464
- // by `.length` would emit lines twice as wide as the box and the terminal
1465
- // would wrap them onto the next row, corrupting the layout.
1466
- if (wW > width) {
1467
- if (line) { out.push(line); line = ''; lineW = 0; }
1468
- let chunk = '';
1469
- let cw = 0;
1470
- for (const ch of w) {
1471
- const chw = visualCol(ch);
1472
- if (cw + chw > width) { out.push(chunk); chunk = ''; cw = 0; }
1473
- chunk += ch; cw += chw;
1474
- }
1475
- if (chunk) { line = chunk; lineW = cw; }
1476
- continue;
1477
- }
1478
- const sep = line ? 1 : 0; // the single space we would add
1479
- if (lineW + sep + wW <= width) {
1480
- line = line ? line + ' ' + w : w;
1481
- lineW += sep + wW;
1482
- } else {
1483
- if (line) out.push(line);
1484
- line = w;
1485
- lineW = wW;
1486
- }
1487
- }
1488
- if (line) out.push(line);
1489
- else if (out.length === 0) out.push('');
1490
- return out;
1491
- }
1492
-
1493
948
  // Extract a (possibly still-streaming) JSON string value by key from a partial
1494
949
  // JSON document. Used to show a Write's `content` as it arrives; returns '' when
1495
950
  // the value hasn't started or is incomplete enough that decoding fails.
@@ -1526,191 +981,7 @@ export function extractJsonString(json, key) {
1526
981
  return out;
1527
982
  }
1528
983
 
1529
- // Line diff for the Edit tool, rendered as a unified diff with context:
1530
- // <n> unchanged line (dim)
1531
- // <n> - removed line
1532
- // <n> + added line
1533
- //
1534
- // FIVE unchanged lines are kept on each side of a change so the edit can be LOCATED in the file.
1535
- // Three was too few to place a change among near-identical neighbours — several small functions,
1536
- // or two `}` a couple of rows apart, look the same inside a three-row window — and the rows just
1537
- // past the window are exactly what a reader uses to tell one site from another.
1538
- const DIFF_CONTEXT_LINES = 5;
1539
-
1540
- // Syntax foreground is applied inside the row's diff background. Every token reset must restore that background,
1541
- // otherwise the first run of each coloured line paints on the page instead of the change wash.
1542
- /**
1543
- * Syntax-colour a line, inside a background, and report whether the row ended inside a comment.
1544
- *
1545
- * The comment state is carried across rows: a block comment that opens on one row and closes on the next left the
1546
- * second row looking like ordinary code, and `extends` and `const` inside a comment were coloured as keywords.
1547
- *
1548
- * @param {string} text The row.
1549
- * @param {object} lang The language entry, or null.
1550
- * @param {string} bg The background colour, or '' for none.
1551
- * @param {boolean} [inComment] Whether the previous row ended inside a block comment.
1552
- * @returns {{text: string, inComment: boolean}}
1553
- */
1554
- function paintCode(text, lang, bg, inComment = false) {
1555
- const result = lang ? highlightLine(text, lang, inComment) : { text: String(text), inComment: false };
1556
- const raw = result.text;
1557
- if (!bg) return result;
1558
- // THE BACKGROUND GOES ON BEFORE ANY TOKEN COLOUR AND COMES BACK AFTER EVERY RESET.
1559
- //
1560
- // Prefixing only after `\x1b[0m` left the run of text BEFORE the first token uncoloured — a comment line has its
1561
- // whole body inside one token, so it drew with no wash at all while the code below it was washed, and the block
1562
- // looked striped. Seeding the background at the front covers that first run; the replacement covers every run
1563
- // after it, because each token closes with a reset that would otherwise drop back to the page background.
1564
- // ESC[39m, NOT ESC[0m: a bare reset clears the background too, and the row's wash must survive past the last
1565
- // token. The final glyph is still inside the coloured run, so nothing is left over to clear.
1566
- return { text: bg + raw.replace(/\x1b\[0m/g, `\x1b[0m${bg}`) + '\x1b[39m', inComment: result.inComment };
1567
- }
1568
-
1569
- /**
1570
- * Rows for an Edit, from the tool's own diff payload.
1571
- *
1572
- * The tool KNOWS what it replaced, so there is nothing to infer: the surrounding lines it reports
1573
- * are context, its `old` is what went, its `new` is what arrived. Running the spliced text through
1574
- * `lineDiff`'s LCS instead made it MIS-READ them — a context block prepended to the old text and
1575
- * appended to the new has a different shape on each side, so the LCS paired the wrong lines and
1576
- * rendered five unchanged context rows as `-`/`+` pairs.
1577
- *
1578
- * Rows are numbered from the real file: `before` carries its own line numbers, and the change
1579
- * starts at `startLine`.
1580
- */
1581
- export function editDiffRows(diff) {
1582
- if (!diff || typeof diff.old !== 'string' || typeof diff.new !== 'string') return [];
1583
- // An empty string is ZERO lines: `''.split('\n')` is `['']`, which would draw a phantom blank row.
1584
- // An empty side is ZERO lines and a trailing newline is not a line: `''.split('\n')` is `['']`,
1585
- // which drew a phantom blank row, and `'a\n'` split to `['a', '']`, which drew one past the end.
1586
- const split = (s) => {
1587
- const t = String(s).replace(/\r\n/g, '\n').replace(/\n$/, '');
1588
- return t === '' ? [] : t.split('\n');
1589
- };
1590
- const ctx = diff.context || {};
1591
- const before = Array.isArray(ctx.before) ? ctx.before : [];
1592
- const after = Array.isArray(ctx.after) ? ctx.after : [];
1593
- const startLine = Number(diff.startLine) > 0 ? Number(diff.startLine) : 1;
1594
-
1595
- // AN EDIT THAT CHANGED ONE LINE SHOWS ONE LINE CHANGED.
1596
- //
1597
- // This used to emit every old line as `del` and every new line as `add`, so replacing three lines whose last
1598
- // one changed produced three deletions and three additions — the two identical lines scrolled past as noise
1599
- // and the one real change was buried. Aligning the two sides and emitting the unchanged pairs as CONTEXT is
1600
- // what a diff is.
1601
- const oldLines = split(diff.old);
1602
- const newLines = split(diff.new);
1603
-
1604
- const out = [];
1605
- for (const c of before) out.push({ type: 'ctx', text: String(c.text), no: c.n });
1606
- let oldNo = startLine;
1607
- let newNo = startLine;
1608
- const steps = alignLines(oldLines, newLines);
1609
- for (let k = 0; k < steps.length; k++) {
1610
- const step = steps[k];
1611
- if (step.op === 'same') { out.push({ type: 'ctx', text: oldLines[step.a], no: newNo }); oldNo++; newNo++; continue; }
1612
- if (step.op === 'del') { out.push({ type: 'del', text: oldLines[step.a], no: oldNo++ }); continue; }
1613
- out.push({ type: 'add', text: newLines[step.b], no: newNo++ });
1614
- }
1615
- for (const c of after) out.push({ type: 'ctx', text: String(c.text), no: c.n });
1616
- // THE LANGUAGE TRAVELS WITH THE ROWS. The renderer draws a diff several layers away from the tool call, with no
1617
- // path of its own, so resolving the highlighter here — from the diff's own `path` — is the only place that still
1618
- // knows what file this is.
1619
- const lang = diff.path ? langForPath(diff.path) : null;
1620
- if (lang) for (const r of out) r.lang = lang;
1621
- return elideContext(out);
1622
- }
1623
-
1624
- /**
1625
- * Align two line arrays into `same` / `del` / `add` steps (longest common subsequence).
1626
- *
1627
- * The table is O(n*m), which is right for the block an edit replaces — a handful of lines — and wrong for a
1628
- * whole file. Past LCS_MAX_LINES on either side it falls back to "everything replaced", which is exactly what
1629
- * the old code always did, so a pathological case is no worse than before and the common one is much better.
1630
- *
1631
- * @param {string[]} a Old lines.
1632
- * @param {string[]} b New lines.
1633
- * @returns {Array<{op:'same'|'del'|'add', a:number, b:number}>}
1634
- */
1635
- function alignLines(a, b) {
1636
- const n = a.length;
1637
- const m = b.length;
1638
- const MAX = 400;
1639
- const all = () => [
1640
- ...a.map((_, i) => ({ op: 'del', a: i, b: 0 })),
1641
- ...b.map((_, j) => ({ op: 'add', a: 0, b: j })),
1642
- ];
1643
- if (n * m > MAX * MAX) return all();
1644
-
1645
- // `dp[i][j]` is the LCS length of a[i..] against b[j..], filled from the bottom right.
1646
- const dp = Array.from({ length: n + 1 }, () => new Uint32Array(m + 1));
1647
- for (let i = n - 1; i >= 0; i--) {
1648
- for (let j = m - 1; j >= 0; j--) {
1649
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
1650
- }
1651
- }
1652
- const steps = [];
1653
- let i = 0;
1654
- let j = 0;
1655
- while (i < n && j < m) {
1656
- if (a[i] === b[j]) { steps.push({ op: 'same', a: i, b: j }); i++; j++; }
1657
- else if (dp[i + 1][j] >= dp[i][j + 1]) { steps.push({ op: 'del', a: i, b: j }); i++; }
1658
- else { steps.push({ op: 'add', a: i, b: j }); j++; }
1659
- }
1660
- while (i < n) { steps.push({ op: 'del', a: i, b: j }); i++; }
1661
- while (j < m) { steps.push({ op: 'add', a: i, b: j }); j++; }
1662
- return steps;
1663
- }
1664
-
1665
- /**
1666
- * Drop context rows further than DIFF_CONTEXT_LINES from any change, one `gap` per run.
1667
- *
1668
- * Shared by both diff builders so a change can never be shown with one amount of surrounding
1669
- * context in the model's tool result and another on screen.
1670
- */
1671
- function elideContext(raw) {
1672
- const isChange = (k) => raw[k] && raw[k].type !== 'ctx';
1673
- const out = [];
1674
- for (let k = 0; k < raw.length; k++) {
1675
- if (raw[k].type !== 'ctx') { out.push(raw[k]); continue; }
1676
- // Distance to the NEAREST change on either side; keep when within the window.
1677
- let dist = Infinity;
1678
- for (let t = k - 1; t >= 0 && t >= k - DIFF_CONTEXT_LINES; t--) { if (isChange(t)) { dist = Math.min(dist, k - t); break; } }
1679
- for (let t = k + 1; t < raw.length && t <= k + DIFF_CONTEXT_LINES; t++) { if (isChange(t)) { dist = Math.min(dist, t - k); break; } }
1680
- if (dist <= DIFF_CONTEXT_LINES) { out.push(raw[k]); continue; }
1681
- // Elide this context row, marking the gap once.
1682
- if (out.length && out[out.length - 1].type !== 'gap') out.push({ type: 'gap' });
1683
- }
1684
- return out;
1685
- }
1686
-
1687
- export function lineDiff(oldStr, newStr, startLine = 1) {
1688
- const a = String(oldStr == null ? '' : oldStr).replace(/\r\n/g, '\n').split('\n');
1689
- const b = String(newStr == null ? '' : newStr).replace(/\r\n/g, '\n').split('\n');
1690
- // LCS table (inputs are edit snippets, so sizes stay small).
1691
- const n = a.length, m = b.length;
1692
- const dp = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1));
1693
- for (let i = n - 1; i >= 0; i--) {
1694
- for (let j = m - 1; j >= 0; j--) {
1695
- dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
1696
- }
1697
- }
1698
- const raw = [];
1699
- let i = 0, j = 0;
1700
- // Line numbers as they appear in the real file (startLine = first old line).
1701
- let oldNo = startLine, newNo = startLine;
1702
- while (i < n && j < m) {
1703
- if (a[i] === b[j]) { raw.push({ type: 'ctx', text: a[i], no: oldNo }); i++; j++; oldNo++; newNo++; }
1704
- else if (dp[i + 1][j] >= dp[i][j + 1]) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
1705
- else { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
1706
- }
1707
- while (i < n) { raw.push({ type: 'del', text: a[i], no: oldNo }); i++; oldNo++; }
1708
- while (j < m) { raw.push({ type: 'add', text: b[j], no: newNo }); j++; newNo++; }
1709
- // Same window rule as `editDiffRows`, from the one helper: a change must never be shown with a
1710
- // different amount of surrounding context on screen and in the model's tool result.
1711
- return elideContext(raw);
1712
- }
1713
-
984
+ // (Diff construction and its syntax colouring live in src/diff.js.)
1714
985
  // Word-wrap a string that may contain ANSI colour codes, measuring VISIBLE
1715
986
  // width only. Escape sequences are carried over to the line they belong to.
1716
987
  function wrapAnsiWords(str, width) {
@@ -1809,157 +1080,7 @@ function wrapWithOffsets(text, width) {
1809
1080
  // - the caret never has to step over a marker it is not editing
1810
1081
  // - submit never has to strip anything
1811
1082
  // The mode ends on Esc/Backspace while the buffer is empty, or on submit.
1812
- export function composerInput(state) {
1813
- const shell = state.inputMode === 'bash';
1814
- return { text: state.input || '', caret: state.caret || 0, prefix: shell ? '! ' : '> ' };
1815
- }
1816
-
1817
- // Marker text for a collapsed paste. Only a multi-line TEXT paste collapses; an
1818
- // IMAGE always collapses (its payload is a temp file path, which should never be
1819
- // shown as if the user typed it).
1820
- // text, multi-line : [paste #1 +12 lines]
1821
- // text, one line : [paste #1 1 lines]
1822
- // image : [paste #1 image]
1823
- // The `image` form keeps the same `paste #N` prefix on purpose: expandPastes,
1824
- // highlightPasteMarkers and adjacentPasteMarker all key off it, so images get the
1825
- // chip styling and atomic caret/delete behaviour for free.
1826
- export function pasteMarker(id, lineCount, kind = 'paste') {
1827
- if (kind === 'image') return `[paste #${id} image]`;
1828
- return lineCount > 1 ? `[paste #${id} +${lineCount} lines]` : `[paste #${id} ${lineCount} lines]`;
1829
- }
1830
- // The tail of any collapsed-paste marker: `+L lines`, `L lines`, or `image`.
1831
- const PASTE_MARKER_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/g;
1832
-
1833
- // Expand every `[paste #N …]` marker in `text` back to its real content.
1834
- export function expandPastes(text, pastes) {
1835
- if (!pastes || !text || !text.includes('[paste #')) return text;
1836
- return text.replace(PASTE_MARKER_RE, (whole, id) => {
1837
- const entry = pastes.get(Number(id));
1838
- return entry ? entry.text : whole;
1839
- });
1840
- }
1841
-
1842
- // Wrap each collapsed-paste marker in the composer row with a selection background
1843
- // so it renders as one block chip (foreground preserved). Non-marker text is left
1844
- // untouched.
1845
- //
1846
- // The chip ends with `C.bgReset` (ESC[49m), NOT `C.reset` (ESC[0m). A bare reset clears EVERY
1847
- // style, so it also wiped the foreground the composer had already applied to the text AFTER the
1848
- // chip — the rest of the line came out in the terminal's default grey instead of the prompt's
1849
- // colour. `highlightSelection` below documents this exact hazard; this function was missing it.
1850
- //
1851
- // `hoverId` is the paste number the pointer is over, when it is over one. That chip keeps its
1852
- // `surface` is the background the CALLER is about to paint under this row, or '' when the row has none. The
1853
- // chip's own fill ends with a background reset, which would otherwise drop the rest of the row to the terminal
1854
- // default; re-asserting the caller's surface right after keeps the row whole.
1855
- export function highlightPasteMarkers(row, hoverId = null, surface = C.bg) {
1856
- const s = String(row);
1857
- if (!s.includes('[paste #')) return s;
1858
- // `C.bgReset` alone drops the rest of the row to the terminal's default background, because the caller has not
1859
- // applied the surface yet. Re-asserting it right after the reset keeps the chip a chip and leaves the row whole.
1860
- return s.replace(PASTE_MARKER_RE, (m, id) => {
1861
- const after = C.bgReset + surface;
1862
- if (Number(id) === hoverId) return C.hover + C.selBg + m + after;
1863
- return C.selBg + m + after;
1864
- });
1865
- }
1866
- /**
1867
- * Which paste number, if any, occupies this input index. Returns null when none does.
1868
- * Which paste number, if any, occupies this input index. Returns null when none does.
1869
- *
1870
- * The companion to `expandPasteMarkerAt`: that one acts on the chip under the pointer, this one merely
1871
- * names it so the row can be drawn differently. Both need the same bounds, and a chip is inclusive of its
1872
- * end because the caret index rounds to the position after the last character.
1873
- */
1874
- export function pasteMarkerIdAt(input, idx) {
1875
- const cur = String(input == null ? '' : input);
1876
- if (!cur.includes('[paste #')) return null;
1877
- for (const m of cur.matchAll(PASTE_MARKER_RE)) {
1878
- const at = m.index;
1879
- if (idx >= at && idx <= at + m[0].length) return Number(m[1]);
1880
- }
1881
- return null;
1882
- }
1883
-
1884
-
1885
- /**
1886
- * Expand the collapsed paste the caret index lands on, in place. Returns true when one was expanded.
1887
- *
1888
- * Takes the ALREADY-CONVERTED index. An earlier version took the row and column and called
1889
- * `composerTextIndexAt` itself, which subtracts the row's prefix width — but the caller had already
1890
- * subtracted it, so every click landed two columns to the left of where the pointer was and a click on
1891
- * the chip's first character expanded nothing.
1892
- *
1893
- * `state.pastes` keeps its entry: `expandPastes` is a no-op for text with no marker, so leaving it costs
1894
- * nothing, and dropping it would break a later marker that still refers to the same paste.
1895
- */
1896
- export function expandPasteMarkerAt(state, idx) {
1897
- const cur = state.input || '';
1898
- if (!cur.includes('[paste #')) return false;
1899
-
1900
- for (const m of cur.matchAll(PASTE_MARKER_RE)) {
1901
- const at = m.index;
1902
- const end = at + m[0].length;
1903
- // The caret index is where the click landed, and clicking any character of the chip targets it —
1904
- // including the character after the last one, which is where a click on the closing bracket rounds to.
1905
- if (idx < at || idx > end) continue;
1906
- const entry = state.pastes && state.pastes.get(Number(m[1]));
1907
- if (!entry) return false;
1908
- state.input = cur.slice(0, at) + entry.text + cur.slice(end);
1909
- // The caret goes AFTER the expanded text, so the next keystroke continues where it ends rather than
1910
- // landing in the middle of the paste the user just revealed.
1911
- state.caret = at + entry.text.length;
1912
- state.composerSel = null;
1913
- refreshMenu(state);
1914
- return true;
1915
- }
1916
- return false;
1917
- }
1918
-
1919
- // Apply selection background to the text portion of a composer row.
1920
- // `text` is the visible text on this row (after the prefix), `textStart`
1921
- // is the character offset of `text[0]` in the full input string, and
1922
- // `[selAnchor, selHead]` is the selection range in the full input.
1923
- export function highlightSelection(text, textStart, selAnchor, selHead) {
1924
- if (!text) return text;
1925
- const a = Math.min(selAnchor, selHead);
1926
- const h = Math.max(selAnchor, selHead);
1927
- let out = '';
1928
- let inSel = false;
1929
- for (let i = 0; i < text.length; i++) {
1930
- const globalIdx = textStart + i;
1931
- const want = globalIdx >= a && globalIdx < h;
1932
- // Selection only changes the BACKGROUND; the foreground keeps its own colour.
1933
- // Leaving the selection resets just the background (bgReset = ESC[49m), NOT the
1934
- // whole style — a bare reset would also kill the foreground, so a cyan/white
1935
- // run after the highlight reverted to grey.
1936
- if (want && !inSel) { out += C.selBg; inSel = true; }
1937
- else if (!want && inSel) { out += C.bgReset; inSel = false; }
1938
- out += text[i];
1939
- }
1940
- if (inSel) out += C.reset;
1941
- return out;
1942
- }
1943
-
1944
- // The composer treats a collapsed-paste marker as ONE atomic unit: moving the
1945
- // caret across it jumps over the whole marker, and deleting it removes the entire
1946
- // marker. `dir` = -1 (look left of the caret) or +1 (right). Covers both the text
1947
- // (`+L lines`) and image (`image`) forms.
1948
- const MARKER_LEFT_RE = /\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]$/;
1949
- const MARKER_RIGHT_RE = /^\[paste #(\d+) (?:\+\d+ lines|\d+ lines|image)\]/;
1950
- export function adjacentPasteMarker(text, caret, dir) {
1951
- const s = String(text || '');
1952
- const c = Math.max(0, Math.min(s.length, caret));
1953
- if (dir < 0) {
1954
- const m = MARKER_LEFT_RE.exec(s.slice(0, c));
1955
- if (m) return { start: c - m[0].length, end: c, id: Number(m[1]) };
1956
- } else {
1957
- const m = MARKER_RIGHT_RE.exec(s.slice(c));
1958
- if (m) return { start: c, end: c + m[0].length, id: Number(m[1]) };
1959
- }
1960
- return null;
1961
- }
1962
-
1083
+ // (The composer's own helpers live in src/composer.js.)
1963
1084
  // Apply the hover highlight to the visible columns [col0, col1) of an ANSI row.
1964
1085
  // The highlight is an explicit bright style (C.hover), and it is RE-APPLIED
1965
1086
  // after every escape sequence inside the span: a row is built from several
@@ -2178,296 +1299,35 @@ export function failureReason(text, toolName) {
2178
1299
  return line;
2179
1300
  }
2180
1301
 
2181
- function msgColorFor(role, text) {
2182
- // 'rich' output (e.g. /context, /usage panels) carries its OWN ANSI colours — do
2183
- // not wrap it in a single role colour, or the whole panel comes out one shade.
2184
- if (role === 'rich') return '';
2185
- if (role === 'system' && typeof text === 'string' && text.startsWith('[turn took')) return C.gray;
2186
- // System/status lines are NEUTRAL grey, not the brand teal: the deep teal showed
2187
- // up on every command result and one-line notice, and at that frequency it read
2188
- // as noise. Grey keeps them quiet; the accents stay for user/tool/working rows.
2189
- if (role === 'system') return C.gray;
2190
- if (role === 'user') return C.cyan;
2191
- if (role === 'bash') return C.shellMode; // ! shell-mode echo: violet, like kimi
2192
- if (role === 'warn') return C.orange; // unfinished-turn warning
2193
- if (role === 'queued') return C.gray; // pending, not yet sent
2194
- if (role === 'steer') return C.yellow; // injected into the running turn
2195
- if (role === 'tool') return C.blue;
2196
- if (role === 'tool_result') return C.gray;
2197
- if (role === 'skill') return C.blue;
2198
- if (role === 'image') return C.gray; // the row names a file, it is not prose
2199
- // Default foreground color based on theme
2200
- return C.fg;
2201
- }
1302
+ // (The tool line and the per-role colour live in src/tool-line.js.)
2202
1303
 
2203
- // ---- tool call display: "Using Name (keyArg)" / "Used Name (keyArg) ----
2204
- // Mirrors kimi-code's extractKeyArgument: pick the one argument that best
2205
- // identifies the call, so a tool line reads `Using Read (src/tui.js)`.
2206
- const KEY_ARG = {
2207
- Bash: ['command'],
2208
- Read: ['path', 'file_path'],
2209
- Write: ['path', 'file_path'],
2210
- Edit: ['path', 'file_path'],
2211
- Grep: ['pattern'],
2212
- Glob: ['pattern'],
2213
- FileLines: ['path', 'file_path'],
2214
- FetchURL: ['url'],
2215
- WebSearch: ['query'],
2216
- Agent: ['description', 'prompt'],
2217
- TaskOutput: ['task_id'],
2218
- TaskStop: ['task_id'],
2219
- };
2220
- const MAX_ARG = 60;
2221
- /**
2222
- * The one argument worth showing next to a tool's name. `expanded` lifts the length cut.
2223
- *
2224
- * The cut exists so the single `● Used Bash (…)` row stays readable: a `node -e "…"` one-liner is
2225
- * routinely hundreds of characters, and printing it whole wrapped the row across the screen for
2226
- * every call. Ctrl+O is the escape hatch — whoever expands tool output to read it wants to see the
2227
- * command they are reading the output OF, and the command is what they asked for in the first place.
2228
- */
2229
- function keyArgument(name, args, workspace, expanded = false) {
2230
- if (!args || typeof args !== 'object') return '';
2231
- const keys = KEY_ARG[name] || Object.keys(args);
2232
- // Expanded: the whole value, with newlines kept, so a multi-line script shows as the lines it was
2233
- // written as rather than being flattened to its first line.
2234
- if (expanded) {
2235
- for (const k of keys) {
2236
- const v = args[k];
2237
- if (typeof v !== 'string' || !v.length) continue;
2238
- const full = sanitizeText(v).replace(/\r\n/g, '\n');
2239
- return (k === 'path' || k === 'file_path') ? full.replace(/\\/g, '/') : full;
2240
- }
2241
- return '';
2242
- }
2243
- for (const k of keys) {
2244
- const v = args[k];
2245
- if (typeof v !== 'string' || !v.length) continue;
2246
- // Neutralise escapes BEFORE measuring: sanitizeText turns ESC into the two
2247
- // visible characters `^[`, so truncating first and sanitizing after made a
2248
- // long command (a `node -e "…"` one-liner is the usual case) come out `+1`
2249
- // column wider than MAX_ARG — and a trailing ESC cut at the boundary left the
2250
- // row ending in a bare `^` instead of a proper `…`.
2251
- // A multi-line value shows its first line, an ELLIPSIS, and then the count of what was left.
2252
- //
2253
- // The ellipsis and the count say different things and both are wanted: the mark shows that the
2254
- // text was cut at all, and the count says how much is missing. Printing only the count reads as
2255
- // if the command ended there, and only the mark leaves the reader guessing by how much.
2256
- const valueLines = sanitizeText(v).replace(/\r\n/g, '\n').split('\n');
2257
- // A trailing blank line is not extra content: a command ending in a newline — how a heredoc is
2258
- // usually written — split into a final empty element, and counting it claimed `(+1 line)` for a
2259
- // command that had no second line at all.
2260
- while (valueLines.length > 1 && valueLines[valueLines.length - 1].trim() === '') valueLines.pop();
2261
- let text = valueLines[0];
2262
- const rest = valueLines.length > 1 ? valueLines.length - 1 : 0;
2263
- if (text.length > MAX_ARG) {
2264
- text = (k === 'path' || k === 'file_path')
2265
- ? '…' + text.slice(text.length - (MAX_ARG - 1))
2266
- : text.slice(0, MAX_ARG - 1) + '…';
2267
- } else if (rest) {
2268
- // Make room for the marker before adding it, so the row never overflows: the count is dropped
2269
- // first because the ellipsis already carries the important half of the message.
2270
- const withCount = `… (+${rest} line${rest === 1 ? '' : 's'})`;
2271
- text += text.length + withCount.length <= MAX_ARG
2272
- ? withCount
2273
- : '…';
2274
- }
2275
- // Display paths with forward slashes (consistent across platforms).
2276
- if (k === 'path' || k === 'file_path') text = text.replace(/\\/g, '/');
2277
- return text;
2278
- }
2279
- return '';
2280
- }
2281
- export function formatToolLine(msg, workspace, spin, pulseStart, shimmerEdge, expanded = false, reducedMotion = false, width = 0) {
2282
- const name = msg.toolName || '';
2283
- const arg = keyArgument(name, msg.toolArgs, workspace, expanded);
2284
- const verb = msg.pending ? 'Using' : 'Used';
2285
- // Pending tool calls have a sweep animation (like "Working...")
2286
- // Once the tool finishes (pending=false) the name shows in plain cyan.
2287
- let nameDisplay;
2288
- if (msg.pending) {
2289
- // A light flashes across the tool name roughly once a second: the name stays plain
2290
- // cyan, and a lamp slightly whiter than cyan runs over it from left to right.
2291
- //
2292
- // This replaces a two-phase colour sweep (cyan → pale cyan → back, then cyan →
2293
- // cyan-blue → back) whose band was half the row wide. That band left every character
2294
- // changed colour behind it, so the name ended up entirely pale or entirely blue — a
2295
- // wash rather than a highlight, and on a long tool name the moving edge was hard to
2296
- // see at all because so much of the row was lit at once.
2297
- //
2298
- // The light is now a QUARTER of a character wide, which is what makes it read as a
2299
- // glint travelling along the name rather than a region changing colour.
2300
- //
2301
- // Phase is measured from the tick the row began on, so a spinner already running does
2302
- // not drop the light into the middle of its travel.
2303
- //
2304
- // `??`, NOT `||`: `pulseStart` is legitimately 0 at the START of a turn (that is where
2305
- // the spinner begins), and `0 || spin` evaluates to `spin`, making `spin - spin === 0`
2306
- // forever — the light would then sit still instead of moving. Only `null`/`undefined`
2307
- // mean "no anchor yet".
2308
- // The phase comes from a WALL CLOCK, not from the tick count.
2309
- //
2310
- // That is what makes the light smooth. The spinner advances `spin` every 80ms while the render path
2311
- // redraws far more often, so a phase derived from `spin` steps in 80ms jumps however often it is
2312
- // redrawn — which is exactly the per-cell hopping this replaced. The tick count still says WHERE the
2313
- // animation began (a spinner already running must not drop the light into mid-travel); it is turned
2314
- // once into a wall-clock origin that later frames measure against.
2315
- //
2316
- // The origin is held in a module-level WeakMap keyed by nothing but the anchor, rather than on
2317
- // `state`. This function is module-level and `state` lives inside startTUI's closure: reading it
2318
- // here threw "state is not defined" the moment a pending tool row painted, surfaced as an
2319
- // unhandledRejection that exited the whole TUI. The origin is the only per-row animation state, and
2320
- // it belongs to the module for exactly that reason.
2321
- //
2322
- // `??`, NOT `||`: tick 0 is a legitimate anchor, and `0 || spin` would collapse the elapsed time to
2323
- // zero so the light never moved at all.
2324
- const anchorSpin = pulseStart ?? spin;
2325
- // THE KEY IS THE ROW'S OWN IDENTITY, and nothing else.
2326
- //
2327
- // It used to carry `anchorSpin` as well, on the reasoning that the same message re-animated on a new
2328
- // tick should get a new origin. The opposite happened: `anchorSpin` is `pulseStart ?? spin`, and when
2329
- // the caller passes no `pulseStart` it IS the tick counter — it changes every 80ms, so every frame
2330
- // built a new key, `lightOrigin` created a fresh origin for it, and `elapsedMs` stayed at 0. The light
2331
- // sat still, except for the one frame after the row content changed and the message object was
2332
- // replaced.
2333
- //
2334
- // A row animates from the moment it appears until it stops being pending, and its id is stable across
2335
- // that whole life: one origin, and elapsed grows from there.
2336
- const rowKey = msg && (msg.id || msg.toolId) ? `tool:${msg.id || msg.toolId}` : `tool:${name}`;
2337
- const elapsedMs = Math.max(0, Date.now() - lightOrigin(rowKey, anchorSpin, spin));
2338
- // ONE shimmer for both rows — see `shimmerText`.
2339
- const phaseMs = elapsedMs % cycleMs(name.length, TOOL_STEP_MS);
1304
+ // (The title strip, the todo panel and the queue pane live in src/panels.js.)
2340
1305
 
2341
- // The same restraint as the Working row's glint: the light is the base colour with a small lift in
2342
- // the SAME hue, not a jump to white. `[150, 255, 255]` against `[0, 215, 255]` read as "the name is
2343
- // now pale" — a state change — where this reads as a sheen passing over it.
2344
- const BASE = [0, 215, 255]; // cyan: the name's resting colour
2345
- const GLINT = [110, 240, 255]; // the same hue, a shade brighter
2346
-
2347
- // The same setting the Working row honours: a pending tool's name is decoration too.
2348
- if (reducedMotion) {
2349
- nameDisplay = col(name, C.cyan);
2350
- } else {
2351
- nameDisplay = shimmerText(name, phaseMs, BASE, GLINT, shimmerEdge || 'cosine', TOOL_STEP_MS);
2352
- }
2353
- } else {
2354
- // Non-pending: show in plain cyan
2355
- nameDisplay = col(name, C.cyan);
2356
- }
2357
- // Show streamed size for Write tool
2358
- let sizeStr = '';
2359
- if (name === 'Write' && typeof msg.streamContent === 'string' && msg.streamContent.length) {
2360
- const bytes = Buffer.byteLength(msg.streamContent, 'utf8');
2361
- sizeStr = bytes >= 1048576 ? ` ${(bytes / 1048576).toFixed(1)}MB`
2362
- : bytes >= 1024 ? ` ${(bytes / 1024).toFixed(1)}KB`
2363
- : ` ${bytes}B`;
2364
- }
2365
- // Show +xx -xx diff counts for Edit tool when done. The diff itself is rendered
2366
- // under the `↳` receipt, so prefer the counts the tool_result handler copied over.
2367
- let diffStr = '';
2368
- const edDiff = (Array.isArray(msg.diff) && msg.diff.length) ? msg.diff : msg._diffCounts;
2369
- if (name === 'Edit' && !msg.pending && Array.isArray(edDiff) && edDiff.length) {
2370
- const adds = edDiff.filter((d) => d.type === 'add').length;
2371
- const deletes = edDiff.filter((d) => d.type === 'del').length;
2372
- if (adds || deletes) {
2373
- diffStr = ' ' + (adds ? col(`+${adds}`, C.green) : '') + ' ' + (deletes ? col(`-${deletes}`, C.red) : '');
2374
- }
2375
- }
2376
- // COLORED PER LINE, not around the whole string.
2377
- //
2378
- // `col(text)` writes one escape pair around everything, so a multi-line argument — exactly what Ctrl+O
2379
- // reveals, the body of a script — had its colour open on line 1 and, after the newline, no colour at all:
2380
- // the terminal's reset made every line below the first render in the DEFAULT foreground, one shade
2381
- // brighter than the grey the parentheses were given. Splitting on the newline and colouring each piece
2382
- // keeps the whole block the same grey. The parentheses still wrap the WHOLE value, so a multi-line script
2383
- // reads as one bracketed argument rather than as several.
2384
- let argText = '';
2385
- if (arg) {
2386
- const lines = `${arg}`.split('\n');
2387
- const painted = lines.map((l, i) => col(
2388
- (i === 0 ? '(' : '') + l + (i === lines.length - 1 ? ')' : ''),
2389
- C.gray,
2390
- ));
2391
- argText = ' ' + painted.join('\n');
2392
- }
2393
- return col(verb, C.white) + ' ' + nameDisplay + argText + col(sizeStr, C.gray) + diffStr;
2394
- }
2395
-
2396
- // ---- live TODO panel (kimi-code's todo-panel) ----
2397
- // Renders above the input box: a rule, a "Todo" heading, up to 5 rows, and a
2398
- // "+N more · ctrl+t to expand" hint. Ctrl+T expands the full list.
2399
- const TODO_MAX_VISIBLE = 5;
2400
-
2401
- /**
2402
- * The first `max` entries, in the order they were written.
2403
- *
2404
- * This used to RANK: in-progress first, then one done item, then pending. On a status change the panel therefore
2405
- * reshuffled — the item being worked on jumped to the top and a finished one followed it — and the list stopped
2406
- * describing the order the work was planned in. A task list is a sequence; a view that reorders it is showing
2407
- * something other than what was written.
2408
- *
2409
- * `counts` still reports what the window is hiding, so the "+N more" hint stays informative.
2410
- */
2411
- export function selectVisibleTodos(todos, max = TODO_MAX_VISIBLE) {
2412
- const list = Array.isArray(todos) ? todos : [];
2413
- const limit = Number.isFinite(max) ? Math.max(0, Math.round(max)) : TODO_MAX_VISIBLE;
2414
- if (list.length <= limit) return { rows: list, hidden: 0, counts: {} };
2415
- const rows = list.slice(0, limit);
2416
- const counts = { done: 0, in_progress: 0, pending: 0 };
2417
- for (let i = limit; i < list.length; i++) {
2418
- const s = list[i] && list[i].status;
2419
- counts[s] = (counts[s] || 0) + 1;
2420
- }
2421
- return { rows, hidden: list.length - rows.length, counts };
2422
- }
2423
-
2424
- function todoRow(todo, w) {
2425
- const mark = todo.status === 'in_progress' ? col('●', C.cyan + C.bold)
2426
- : todo.status === 'done' ? col('✓', C.green)
2427
- : col('○', C.gray);
2428
- const title = todo.status === 'in_progress' ? col(todo.title, C.white + C.bold)
2429
- : todo.status === 'done' ? col(todo.title, C.gray)
2430
- : col(todo.title, C.white);
2431
- return ' ' + mark + ' ' + fitAnsi(title, Math.max(1, w - 4));
2432
- }
2433
-
2434
- // The unselected completion row, and its match. Fixed light greys rather than theme entries: the theme grey is
2435
- // tuned to sit quiet against the page, and at menu size it read as disabled rather than as a list to choose from.
2436
- const MATCH_BASE = '\x1b[38;2;153;153;153m'; // #999999
1306
+ // The unselected completion row, and its match. Fixed light greys rather than theme entries: the theme grey is tuned
1307
+ // to sit quiet against the page, and at menu size it read as disabled rather than as a list to choose from.
1308
+ const MATCH_BASE = '\x1b[38;2;153;153;153m'; // #999999
2437
1309
  const MATCH_HIT = '\x1b[38;2;173;173;173m\x1b[1m'; // #adadad, bold
2438
1310
 
2439
1311
  /**
2440
1312
  * A completion row with every occurrence of the typed text picked out.
2441
1313
  *
2442
- * THE MATCH IS POSITIONAL, NOT A PREFIX. `/he` lights the `he` in `/help`, the `he` in `/theme` and every `he` in
2443
- * either description, because a user typing `he` is looking for those LETTERS — a command must not be excluded from
2444
- * the highlight just because it does not begin with them.
1314
+ * THE MATCH IS POSITIONAL, NOT A PREFIX. `/he` lights the `he` in `/help`, the `he` in `/theme` and every `he` in either
1315
+ * description, because a user typing `he` is looking for those LETTERS — a command must not be excluded from the
1316
+ * highlight just because it does not begin with them.
2445
1317
  *
2446
1318
  * THE BASE COLOUR CARRIES THE SELECTION STATE, and the match is that same colour in BOLD:
2447
1319
  *
2448
1320
  * selected theme cyan + bold cyan match
2449
1321
  * unselected #999999 + #adadad bold match
2450
1322
  *
2451
- * The hue never changes, so a row's identity does not move when the cursor leaves it — only the weight does. A
2452
- * separate colour for the match made an unselected row's highlight the brightest thing in the menu, which pulled
2453
- * the eye to rows the cursor was not on.
2454
- *
2455
- * @param {string} text The command name or description.
2456
- * @param {string} query What the user has typed, lower-case, without the leading slash.
2457
- * @param {boolean} selected Whether this is the cursor row.
2458
- * @returns {string} The text with ANSI codes inserted.
1323
+ * The hue never changes, so a row's identity does not move when the cursor leaves it — only the weight does.
2459
1324
  */
2460
- function highlightMatches(text, query, selected) {
1325
+ export function highlightMatches(text, query, selected) {
2461
1326
  const src = String(text);
2462
- // The unselected pair is a fixed light grey rather than the theme grey, which is too dark to read comfortably at
2463
- // this size: #999999 for the row and #adadad for its match are two steps a reader can tell apart, without either
2464
- // being brighter than the selected row.
2465
1327
  const base = selected ? C.cyan : MATCH_BASE;
2466
1328
  if (!query) return col(src, base);
2467
1329
  const q = query.toLowerCase();
2468
1330
  const lower = src.toLowerCase();
2469
- // The match is the SAME hue, in bold: the colour identifies the row and the weight identifies the match, so a
2470
- // row does not change colour when the cursor leaves it.
2471
1331
  const hit = selected ? (C.cyan + C.bold) : MATCH_HIT;
2472
1332
  let out = '';
2473
1333
  let at = 0;
@@ -2483,221 +1343,6 @@ function highlightMatches(text, query, selected) {
2483
1343
  return out;
2484
1344
  }
2485
1345
 
2486
- // `hoverTop` / `dragTop` drive the top rule's hover and press colours: that rule
2487
- // is a drag handle for resizing the panel.
2488
- /**
2489
- * The title strip along the top of the screen.
2490
- *
2491
- * `maxRows` is how many rows of name to show. A name that fits on one row uses one; a longer one WRAPS, and the
2492
- * rows it needs are reserved for it — a terminal is narrow, and cutting a session name to its first forty
2493
- * characters loses the part that told them apart. The last visible row ends in `…` when the name continues below.
2494
- *
2495
- * `state.titleRows` is the height the user dragged the rule to. `0` or unset means "as many as the name needs,
2496
- * up to the room available", which is what a fresh session wants.
2497
- *
2498
- * The rule is always the LAST row, so it is always in the same place to grab.
2499
- */
2500
- function renderTitleBar(state, w, hover, maxRows) {
2501
- const title = String(state.sessionTitle || '').trim();
2502
- // A NAMELESS SESSION IS NOT A BLANK BAND. `Untitled` says the strip is there and can be clicked; an empty row
2503
- // reads as a rendering gap.
2504
- const label = title || 'Untitled';
2505
- const out = [];
2506
- // ONE LEADING SPACE, matching the transcript's own left margin so the name lines up with the messages below.
2507
- const PAD = ' ';
2508
- const room = Math.max(1, w - PAD.length);
2509
- const rows = Math.max(1, Math.round(maxRows) || 1);
2510
- // Wrap the name to the width, keeping ANSI out of it — the colour is applied per row below.
2511
- const wrapped = wrapWords(label, room);
2512
- const shownRows = wrapped.slice(0, rows);
2513
- // A name with more rows than the band can show ends in `…` on its last visible row.
2514
- const more = wrapped.length > shownRows.length;
2515
- // THE PLACEHOLDER IS THE SAME COLOUR AS A REAL NAME. It used to be `C.muted`, which made a fresh session's band
2516
- // look disabled — as if the strip were not there to be clicked. The word already says the session has no name;
2517
- // dimming it as well says something different and wrong.
2518
- const textColor = hover ? C.heading : C.cyan;
2519
- const ruleColor = hover ? C.cyan : C.border;
2520
- for (let i = 0; i < shownRows.length; i++) {
2521
- let line = shownRows[i];
2522
- if (i === shownRows.length - 1 && more) {
2523
- // Trim one column so the ellipsis fits inside the width instead of pushing the row over.
2524
- line = fitAnsi(line, room - 1).trimEnd() + '…';
2525
- }
2526
- out.push(fitAnsi(PAD + col(line, textColor + C.bold), w));
2527
- }
2528
- out.push(col('─'.repeat(w), ruleColor));
2529
- return out;
2530
- }
2531
-
2532
- /** How many rows the title needs at this width, ignoring any drag. */
2533
- function titleRowsNeeded(state, w) {
2534
- const title = String(state.sessionTitle || '').trim() || 'Untitled';
2535
- const room = Math.max(1, w - 1);
2536
- return Math.max(1, wrapWords(title, room).length);
2537
- }
2538
-
2539
- /**
2540
- * Name rows currently shown: the dragged height when set, otherwise as many as the name needs.
2541
- *
2542
- * The band is `titleRowCount` name rows plus the rule. Reading it from `state.titleRows` rather than from the
2543
- * frame keeps the drag arithmetic independent of what was last painted.
2544
- */
2545
- function titleRowCount(state) {
2546
- const need = titleRowsNeeded(state, state.cols || process.stdout.columns || 80);
2547
- const set = Math.round(Number(state.titleRows) || 0);
2548
- return set > 0 ? Math.min(set, need) : need;
2549
- }
2550
-
2551
- function renderTodoPanel(state, w, hoverTop, dragTop) {
2552
- const todos = state.todos || [];
2553
- if (!todos.length) return [];
2554
- // A finished list draws NOTHING, matching `todoPanelHeight` returning 0 for the same state. Both ask
2555
- // the same question, so the reserved height and the drawn rows cannot disagree — a mismatch would
2556
- // shift every row below the panel.
2557
- if (todoListFinished(state)) return [];
2558
- const out = [];
2559
- const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
2560
- out.push(col('─'.repeat(w), ruleColor));
2561
- out.push(col(' Todo', C.cyan + C.bold));
2562
- const want = todoRowCount(state);
2563
- // CREATION ORDER, ALWAYS.
2564
- //
2565
- // The panel used to draw `selectVisibleTodos` first — which ranks in-progress ahead of pending and pulls done
2566
- // items up — and then top up from the original list. The result read as a reshuffle on every status change: the
2567
- // item being worked on jumped to the top and a finished one followed it, so the list no longer described the
2568
- // order the work was planned in. A task list is a SEQUENCE; showing it in a different sequence than it was
2569
- // written in is what made it hard to follow.
2570
- //
2571
- // Which rows fit is still the panel's decision — it takes the first `want` in order.
2572
- const rows = todos.slice(0, want);
2573
- for (const t of rows) out.push(todoRow(t, w));
2574
- const hidden = todos.length - rows.length;
2575
- if (hidden > 0) {
2576
- const counts = { done: 0, in_progress: 0, pending: 0 };
2577
- for (const t of todos) if (!rows.includes(t)) counts[t.status] = (counts[t.status] || 0) + 1;
2578
- const dist = [['done', 'done'], ['in_progress', 'in progress'], ['pending', 'pending']]
2579
- .filter(([k]) => counts[k] > 0).map(([k, label]) => `${counts[k]} ${label}`).join(', ');
2580
- // The hint appears exactly when rows are hidden — which is exactly when Ctrl+T
2581
- // is useful — so this is where the key has to be discoverable.
2582
- out.push(col(` … +${hidden} more${dist ? ` (${dist})` : ''} · ctrl+t to expand · drag the top rule to resize`, C.gray));
2583
- }
2584
- return out;
2585
- }
2586
-
2587
- // --- queue pane (kimi-code's QueuePane) -------------------------------------
2588
- // One rule line, one line per queued message, one dim hint line. Queued input is
2589
- // held while the agent is streaming and is injected by Ctrl-S (or by the agent
2590
- // itself at the next tool boundary).
2591
- // Supports auto-collapse and drag-to-resize like the todo panel.
2592
- const QUEUE_MAX_VISIBLE = 5;
2593
- function renderQueuePanel(state, w, hoverTop, dragTop) {
2594
- const queued = state.queued || [];
2595
- if (!queued.length) return [];
2596
-
2597
- const out = [];
2598
- const ruleColor = dragTop ? C.scrollThumbActive : (hoverTop ? C.hover : C.border);
2599
- out.push(col('─'.repeat(w), ruleColor));
2600
- out.push(col(' Queue', C.cyan + C.bold));
2601
-
2602
- const want = queueRowCount(state);
2603
- const rows = queued.slice(0, want);
2604
- for (const text of rows) {
2605
- // Collapse to a single line, like kimi's queue pane does.
2606
- const single = String(text).replace(/\s+/g, ' ').trim();
2607
- out.push(col(' ', C.cyan) + col('> ', C.cyan) + col(fitAnsi(single, Math.max(1, w - 6)), C.white));
2608
- }
2609
-
2610
- const hidden = queued.length - rows.length;
2611
- if (hidden > 0) {
2612
- const hint = state.running
2613
- ? `… +${hidden} more · ↑ to edit · ctrl-s to steer immediately · drag top rule to resize`
2614
- : `… +${hidden} more · ↑ to edit · will send now · drag top rule to resize`;
2615
- out.push(col(' ' + hint, C.gray));
2616
- } else {
2617
- const hint = state.running ? '↑ to edit · ctrl-s to steer immediately' : '↑ to edit · will send now';
2618
- out.push(col(' ' + hint, C.gray));
2619
- }
2620
-
2621
- return out;
2622
- }
2623
-
2624
- // How many queue ROWS the panel shows.
2625
- // * `state.queueRows` (set by dragging the top rule) wins when present;
2626
- // * otherwise show all items up to QUEUE_MAX_VISIBLE.
2627
- // Always clamped to [1, queued.length]: at least ONE row, never more than exist.
2628
- export function queueRowCount(state) {
2629
- const queued = state.queued || [];
2630
- if (!queued.length) return 0;
2631
- const manual = state.queueRows;
2632
- let rows;
2633
- if (typeof manual === 'number' && Number.isFinite(manual)) {
2634
- rows = Math.round(manual);
2635
- } else {
2636
- rows = Math.min(queued.length, QUEUE_MAX_VISIBLE);
2637
- }
2638
- return Math.max(1, Math.min(queued.length, rows));
2639
- }
2640
-
2641
- // Height (in rows) the queue panel will occupy, for layout math.
2642
- export function queuePanelHeight(state) {
2643
- const queued = state.queued || [];
2644
- if (!queued.length) return 0;
2645
- const rows = queueRowCount(state);
2646
- const extra = queued.length > rows ? 1 : 0; // the "… +N more" hint
2647
- return 2 + rows + extra; // rule + heading + rows (+ hint)
2648
- }
2649
-
2650
- // How many todo ROWS the panel shows.
2651
- // * `state.todoRows` (set by dragging the top rule) wins when present;
2652
- // * otherwise the automatic heuristic (selectVisibleTodos) decides.
2653
- // Always clamped to [1, todos.length]: at least ONE row, never more than exist.
2654
- /**
2655
- * Is this list FINISHED — every item done, and at least one item?
2656
- *
2657
- * A finished list is DROPPED, not merely hidden: it has stopped being a list of what is left to do, so
2658
- * the data goes as well as the panel. Hiding alone left the array to be persisted with the session and
2659
- * handed back to the model as `cfg.todoState`, which is a finished plan being described as current work.
2660
- *
2661
- * `every` on an EMPTY array is true, so the length check is load-bearing: this must not fire for "no
2662
- * todos", which is a different state with its own handling everywhere else.
2663
- */
2664
- export function todosAllComplete(list) {
2665
- const todos = Array.isArray(list) ? list : [];
2666
- return todos.length > 0 && todos.every((t) => t && t.status === 'done');
2667
- }
2668
-
2669
- /** The same question, asked of a TUI state object rather than a bare array. */
2670
- export function todoListFinished(state) {
2671
- return todosAllComplete(state && state.todos);
2672
- }
2673
-
2674
- export function todoRowCount(state) {
2675
- const todos = state.todos || [];
2676
- if (!todos.length) return 0;
2677
- // A finished list has no rows: see `todoListFinished`.
2678
- if (todoListFinished(state)) return 0;
2679
- const manual = state.todoRows;
2680
- let rows;
2681
- if (typeof manual === 'number' && Number.isFinite(manual)) {
2682
- rows = Math.round(manual);
2683
- } else {
2684
- rows = state.todosExpanded ? todos.length : selectVisibleTodos(todos).rows.length;
2685
- }
2686
- return Math.max(1, Math.min(todos.length, rows));
2687
- }
2688
-
2689
- // Height (in rows) the todo panel will occupy, for layout math.
2690
- export function todoPanelHeight(state) {
2691
- const todos = state.todos || [];
2692
- if (!todos.length) return 0;
2693
- // Zero once everything is done, so the chrome shrinks by the panel's whole height rather than leaving
2694
- // a blank gap where it used to be. Both this and the renderer ask the same predicate, so the reserved
2695
- // height and the drawn rows cannot disagree — a mismatch there shifts every row below.
2696
- if (todoListFinished(state)) return 0;
2697
- const rows = todoRowCount(state);
2698
- const extra = todos.length > rows ? 1 : 0; // the "… +N more" hint
2699
- return 2 + rows + extra; // rule + heading + rows (+ hint)
2700
- }
2701
1346
 
2702
1347
  // Render one chat message into display lines.
2703
1348
  // Returns { lines: [{text, ind, color}] } (ind = indent string for continuation).
@@ -2809,6 +1454,20 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
2809
1454
  }
2810
1455
  }
2811
1456
 
1457
+ // THE HINT IS ALWAYS THERE WHILE THE COMMAND RUNS, and it is grey.
1458
+ //
1459
+ // Always, because nothing here can tell a command that waits for input from one that is merely slow: the
1460
+ // output-shape guess does not hold (a Python `input()` prompt ends in a newline like any other line), and
1461
+ // the OS exposes no portable "blocked in read". A line that is true either way — this key sends what you
1462
+ // type to the command — is the honest form, and grey keeps it a footnote rather than a warning.
1463
+ if (msg.pending && msg.toolName === 'Bash') {
1464
+ const stdinHintW = Math.max(1, width - visualCol(' '));
1465
+ out.push({
1466
+ text: C.termBg + fitAnsi(col('Ctrl+G: send a line to this command', C.gray), stdinHintW) + C.bgReset,
1467
+ ind: ' ', raw: true,
1468
+ });
1469
+ }
1470
+
2812
1471
  // Ctrl+B detach hint (mirrors kimi-code). A foreground Bash/Agent call that
2813
1472
  // has been running a while advertises the shortcut that moves it to the
2814
1473
  // background; the hint disappears the moment the result lands. Bash waits
@@ -2873,428 +1532,40 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
2873
1532
  }
2874
1533
  const painted = paintCode(ln, writeLang, '', writeInComment);
2875
1534
  writeInComment = painted.inComment;
2876
- const writeRow = (col(num + ' ', C.white) + fitAnsi(painted.text, room)).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
2877
- out.push({ text: C.codeBg + writeRow + C.bgReset, ind: i === 0 ? '↳ ' : indent, raw: true });
2878
- });
2879
- const shown = Math.min(lines.length, MAX);
2880
- if (totalLines > shown) out.push({ text: col(`… ${totalLines - shown} more lines, ctrl+o to expand`, C.gray), ind: indent, raw: true });
2881
- }
2882
-
2883
- // The Edit diff is NOT drawn here: it rides on the tool_result message and is
2884
-
2885
- // The Edit diff is NOT drawn here: it rides on the tool_result message and is
2886
- // rendered BELOW the `↳` receipt (see the tool_result branch). Drawing it here
2887
- // put it between the `● Used Edit` status bullet and the receipt.
2888
- return out;
2889
- }
2890
- // A PLAN block (Plan mode): the model's <|plan|>…</|plan|> body, rendered as a
2891
- // single-column TABLE — the same ╭─┬─╮ / ├─┼─┤ / ╰─┴─╯ vocabulary the Markdown
2892
- // table renderer uses, so a plan reads as structured data rather than as prose
2893
- // or as a second composer box.
2894
- if (msg.role === 'plan') {
2895
- // `width` is the transcript's inner width (the caller already removed the
2896
- // one-column margin); the wrapped user boxes land at `width - 2`.
2897
- const tableW = Math.max(12, width - 2);
2898
- // Body rows.
2899
- // NOTE: rows must be {text, ind, raw} OBJECTS — messageLines' contract. Pushing
2900
- // plain strings here made rowToLine read `undefined` and the whole block rendered as
2901
- // blank lines.
2902
- const out = [];
2903
- const bar = (ch) => col(ch, C.border);
2904
- const inner = Math.max(1, tableW - 2);
2905
- const full = (l, r) => bar(l + '─'.repeat(inner) + r);
2906
- // Header: the table's single column is captioned "Plan".
2907
- out.push({ text: full('╭', '╮'), ind: '', raw: true });
2908
- out.push({ text: bar('│') + fitAnsi(col(' Plan', C.cyan + C.bold), inner) + bar('│'), ind: '', raw: true });
2909
- out.push({ text: bar('├' + '─'.repeat(inner) + '┤'), ind: '', raw: true });
2910
- const lines = String(msg.text || '').replace(/\r\n/g, '\n').split('\n');
2911
- while (lines.length && lines[lines.length - 1].trim() === '') lines.pop();
2912
- const textW = Math.max(1, inner - 2);
2913
- for (const raw of lines) {
2914
- if (raw.trim() === '') {
2915
- out.push({ text: bar('│') + ' '.repeat(inner) + bar('│'), ind: '', raw: true });
2916
- continue;
2917
- }
2918
- // Headings are emphasised; everything else renders as Markdown body text so
2919
- // **bold**, `code` and bullets work.
2920
- const isHead = /^\s*#{1,6}\s/.test(raw);
2921
- const shown = isHead ? raw.replace(/^\s*#{1,6}\s*/, '') : raw;
2922
- for (const r of renderMdText(shown, textW, isHead ? (C.cyan + C.bold) : C.white, C.cyan)) {
2923
- out.push({ text: bar('│') + ' ' + fitAnsi(r, textW) + ' ' + bar('│'), ind: '', raw: true });
2924
- }
2925
- }
2926
- out.push({ text: full('╰', '╯'), ind: '', raw: true });
2927
- return out;
2928
- }
2929
-
2930
- // A BACKGROUND TASK lifecycle card (kimi-style):
2931
- // ● agent task completed in background (review the diff)
2932
- // ✗ bash task failed in background (npm test · exit 1)
2933
- // The bullet is `●` normally and `✗` for a failure; the colour follows the
2934
- // phase. The task's conclusion sits underneath, indented, and is capped like
2935
- // a tool result so one chatty subagent cannot flood the transcript.
2936
- if (msg.role === 'bg_task') {
2937
- const card = msg.card || { phase: 'completed', headline: 'background task finished', detail: undefined };
2938
- const tone = card.phase === 'started' ? C.cyan : card.phase === 'completed' ? C.green : C.red;
2939
- const bullet = card.phase === 'failed' ? '✗ ' : '● ';
2940
- const out = [];
2941
- const detail = card.detail ? col(` (${card.detail})`, C.gray) : '';
2942
- out.push({ text: col(bullet, tone) + col(card.headline, tone) + detail, ind: '', raw: true });
2943
- const body = String(msg.text || '').trim();
2944
- if (body) {
2945
- const indent = ' ';
2946
- const avail = Math.max(1, width - visualCol(indent));
2947
- const lines = body.replace(/\r\n/g, '\n').split('\n');
2948
- // No cap once expanded. 200 was a silent ceiling: a long result stopped there with a hint telling
2949
- // the user to press the key they had already pressed.
2950
- const MAX = expanded ? lines.length : 6;
2951
- for (const ln of lines.slice(0, MAX)) {
2952
- for (const w of (ln === '' ? [''] : wrapWords(ln, avail))) {
2953
- out.push({ text: col(w, C.gray), ind: indent, raw: true });
2954
- }
2955
- }
2956
- if (lines.length > MAX) {
2957
- // Only reachable while COLLAPSED: expanded, `MAX` is the whole list and this cannot fire.
2958
- out.push({ text: col(`… ${lines.length - MAX} more lines, ctrl+o to expand`, C.gray), ind: indent, raw: true });
2959
- }
2960
- }
2961
- return out;
2962
- }
2963
-
2964
- // Tool output: a single "↳ " marker on the first line, then the output
2965
- // indented by 2 columns. Long output is capped (kimi caps result previews
2966
- // too) so one command cannot flood the whole transcript.
2967
- if (msg.role === 'tool_result') {
2968
- // The marker sits in the SAME COLUMN as the tool bullet `●` (rendered as
2969
- // '● ', i.e. columns 0-1), so `↳ ` starts at column 0 and the output text
2970
- // is indented to the tool text column. ONE `↳` per result, however many
2971
- // lines it has.
2972
- const pre = '↳ ';
2973
- const cont = ' ';
2974
- const bodyW = Math.max(1, width - visualCol(cont));
2975
- // Strip escapes BEFORE splitting: a file or a command can emit raw SGR /
2976
- // cursor codes, and letting them through made the terminal OBEY them —
2977
- // recolouring the transcript, resetting styles mid-row, moving the cursor or
2978
- // clearing the screen over the composer.
2979
- const rawLines = sanitizeText(msg.text).replace(/\r\n/g, '\n').split('\n');
2980
- // A TAB counts as ZERO columns in our width maths but advances to the next tab stop in a real terminal.
2981
- // A row containing one was therefore padded short and the terminal kept the old frame's glyphs in the gap —
2982
- // the "residue" under tool output. Read rows are the exception: their first tab is the line-number separator
2983
- // and is handled in the Read branch below, where the CONTENT half is expanded too.
2984
- if (!msg.readPath) for (let k = 0; k < rawLines.length; k++) rawLines[k] = expandTabs(rawLines[k]);
2985
- // Trim blank lines at BOTH ends: commands typically emit a trailing
2986
- // newline, and some tools emit a leading one. A stray blank line would
2987
- // render as a lone "↳ " with no content.
2988
- while (rawLines.length && rawLines[0].trim() === '') rawLines.shift();
2989
- while (rawLines.length && rawLines[rawLines.length - 1].trim() === '') rawLines.pop();
2990
- const MAX_RESULT_LINES = expanded ? Infinity : 12;
2991
- // The exit-code line is bookkeeping for the AGENT (it stays in the tool
2992
- // result the model receives) and is NEVER shown to the user — success or
2993
- // failure. A failure is already legible from the RED result text below.
2994
- // `[error: …]` is kept: it carries the message, not just a code.
2995
- const visible = rawLines.filter((ln) => !/^\[exit code:/.test(ln.trim()));
2996
- const failed = msg.failed === true;
2997
- // A silent Bash keeps the ONE empty output row it had while running. Only Bash has this special area: an empty
2998
- // Read/Grep result must not grow a phantom line merely because the command itself printed nothing.
2999
- const shown = visible.length ? visible.slice(0, MAX_RESULT_LINES) : (msg.toolName === 'Bash' ? [''] : []);
3000
-
3001
- // ---- DISPLAY ORDER -----------------------------------------------------
3002
- // The row reads as a block under the tool line, with ONE `↳` marker:
3003
- // ● Used Edit (a.js) +1 -1 <- status bullet
3004
- // ↳ 3 - old line <- `↳` rides the FIRST body row
3005
- // 3 + new line
3006
- // Edited a.js: replaced 1 occurrence(s). <- receipt LAST
3007
- // For an Edit the DIFF is the body (and carries the marker); the receipt text
3008
- // moves to the bottom. For every other tool the tool output IS the body, so
3009
- // the marker sits on its first line, exactly as before.
3010
- const diffRows = [];
3011
- const receiptRows = [];
3012
- const hasDiff = Array.isArray(msg.diff); // empty array => receipt-only (Write)
3013
-
3014
- if (hasDiff) {
3015
- // Same collapse rule as the tool output and thinking blocks above: a short
3016
- // preview by default, everything once Ctrl+O expands. 16 rows (not 12)
3017
- // because a change renders as a PAIR: `- old` then `+ new`.
3018
- const MAX = expanded ? Infinity : 16;
3019
- // Show the unified diff WITH context rows (ctx = dim, marked by a space in
3020
- // the sign column) so a change is not two orphaned blocks; `gap` rows mark
3021
- // where unchanged lines were elided.
3022
- const total = msg.diff.length;
3023
- const wNo = Math.max(1, ...msg.diff.map((d) => String(d.no || 0).length));
3024
- // THE COMMENT STATE TRAVELS BETWEEN THE ROWS of one diff, so a block comment that opens on a context row and
3025
- // closes on a changed one stays grey across both.
3026
- let inComment = false;
3027
- let emitted = 0;
3028
- for (const d of msg.diff) {
3029
- if (emitted >= MAX) break;
3030
- if (d.type === 'gap') {
3031
- diffRows.push({ text: col(' ⋮', C.gray), ind: cont, raw: true });
3032
- emitted++;
3033
- continue;
3034
- }
3035
- const no = String(d.no || 0).padStart(wNo);
3036
- const mark = d.type === 'add' ? '+' : d.type === 'del' ? '-' : ' ';
3037
- // TABS ARE EXPANDED FIRST: `visualCol` counts one as zero columns, so an indented row measured short
3038
- // and its background stopped before the right edge — the strip of page colour seen on Go diffs.
3039
- const text = expandTabs(sanitizeText(d.text));
3040
-
3041
- // The sign, line number and content share the line's addition/deletion background; syntax highlighting
3042
- // changes only the foreground. The wash runs to the right edge so adjacent changed rows read as one block.
3043
- const isAdd = d.type === 'add';
3044
- const isDel = d.type === 'del';
3045
- const lineBg = isAdd ? C.diffAddBg : isDel ? C.diffDelBg : '';
3046
- const fg = isAdd ? C.diffAddFg : isDel ? C.diffDelFg : C.white;
3047
- const lead = col(`${no} ${mark} `, lineBg ? fg + lineBg : fg);
3048
-
3049
- if (!lineBg) {
3050
- // CONTEXT LINES ARE CODE TOO. They are the most of a diff and the part a reader scans to place the
3051
- // the change, so they get the same highlighter, on the CODE SURFACE rather than the raw page — a changed
3052
- // block sits on one recessed field. The +/- rows around it keep their green/red wash.
3053
- const ctxPainted = paintCode(text, d.lang, '', inComment);
3054
- inComment = ctxPainted.inComment;
3055
- const ctxRow = (lead + ctxPainted.text).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
3056
- diffRows.push({ text: C.codeBg + fitAnsi(ctxRow, bodyW) + C.bgReset, ind: cont, raw: true });
3057
- emitted++;
3058
- continue;
3059
- }
3060
-
3061
- // Keep only the line-level addition/deletion wash and syntax foreground. Positional word pairing can
3062
- // highlight the wrong token when lines are reordered or punctuation changes, so no word tint is applied.
3063
- const painted = paintCode(text, d.lang, lineBg, inComment);
3064
- inComment = painted.inComment;
3065
- const used = visualCol(`${no} ${mark} `) + visualCol(painted.text);
3066
- const pad = ' '.repeat(Math.max(0, bodyW - used));
3067
- // The padding is INSIDE the wash, so it must not end with a bare reset: `col()` closes with ESC[0m, which
3068
- // would drop the background on the last column and leave a strip of page colour at the right edge.
3069
- diffRows.push({ text: lead + painted.text + lineBg + pad + '\x1b[39m', ind: cont, raw: true });
3070
- emitted++;
3071
- }
3072
- if (total > emitted) {
3073
- diffRows.push({
3074
- text: col(`… (${total - emitted} more lines, ctrl+o to expand)`, C.gray),
3075
- ind: cont, raw: true,
3076
- });
3077
- }
3078
- if (total === 0) diffRows.push({ text: col('(no changes)', C.gray), ind: cont, raw: true });
3079
- // The receipt: one line per source line of the tool's own message.
3080
- for (const ln of shown) {
3081
- const color = failed ? C.red : C.gray;
3082
- for (const t of (ln === '' ? [''] : wrapWords(ln, bodyW))) {
3083
- receiptRows.push({ text: t, ind: cont, color });
3084
- }
3085
- }
3086
- } else {
3087
- // No diff: the tool's own output is the body.
3088
- //
3089
- // A READ RESULT IS SOURCE CODE, so its numbered lines are syntax-coloured — the file's own language, carried
3090
- // on the message by the tool_result handler, which is the last place that still knows the path. The header
3091
- // and any error keep the plain grey: those are the tool's own words, not the file's.
3092
- //
3093
- // The comment state travels between the rows, so a block comment that opens on one line and closes on the
3094
- // next stays grey all the way down.
3095
- const readLang = msg.readPath ? langForPath(msg.readPath) : null;
3096
- // THE GUTTER IS ONE WIDTH FOR THE WHOLE BLOCK. The tool sends `N<TAB>text`, and the tab is what used to
3097
- // place the code — so `1` and `10` started their text at different columns once the tab was expanded.
3098
- // Padding the NUMBER to the widest one in this block keeps the digits left-aligned and the code aligned
3099
- // under itself.
3100
- const numW = shown.reduce((w, ln) => {
3101
- const m = /^(\d+)\t/.exec(ln);
3102
- return m ? Math.max(w, m[1].length) : w;
3103
- }, 0);
3104
- let inComment = false;
3105
- shown.forEach((ln, idx) => {
3106
- const isErr = /^\[error:/.test(ln.trim());
3107
- // A failed run is red throughout so it cannot be skimmed past.
3108
- const color = isErr ? C.red : (failed ? C.red : C.gray);
3109
- // `N<TAB>text` is the Read tool's own line format; only those rows are file content.
3110
- const numbered = readLang && !isErr ? /^(\d+)\t([\s\S]*)$/.exec(ln) : null;
3111
- if (numbered) {
3112
- // `wrapAnsiWords` measures VISIBLE columns, so the colour codes do not count towards the wrap.
3113
- // THE FILE'S OWN INDENTATION IS OFTEN TABS. Left as tabs, `visualCol` counted them as zero columns
3114
- // while the terminal advanced to the next stop: the row was padded short and the previous frame's
3115
- // glyphs stayed visible behind it. Expand before measuring, but keep the first tab as the separator
3116
- // — the regex above already split on it.
3117
- // tell the highlighter the first visible row is a comment — it coloured `of`, `switch`, `from` in a JSDoc
3118
- // paragraph as keywords. A row that is plainly part of a block comment (` * …`, an opening `/**`, or the
3119
- // closing `*/`) is painted as a comment on its own merits; the opener also seeds the rows that follow.
3120
- const content = expandTabs(numbered[2]);
3121
- const isBlockCommentRow = /^\s*(?:\/\*|\*|\*\/|\*\*)/.test(content);
3122
- const painted = paintCode(content, readLang, '', inComment || isBlockCommentRow);
3123
- if (/\/\*/.test(content) && !/\*\//.test(content)) inComment = true;
3124
- else if (/\*\//.test(content)) inComment = false;
3125
- // THE SEPARATOR IS A TAB, AND `visualCol` COUNTS A TAB AS ZERO COLUMNS. A terminal advances it to the
3126
- // next stop, so the row was measured several columns short, the terminal wrapped it itself, and the tail
3127
- // advances it to the next stop, so the row measured short and the terminal wrapped it itself. The
3128
- // THE SEPARATOR IS TWO SPACES, NOT A TAB: `visualCol` counts a tab as zero columns while a terminal
3129
- const text = `${col(numbered[1].padStart(numW), C.white)} ${painted.text}`;
3130
- // A Read row is TRUNCATED, not wrapped. `wrapAnsiWords` used to fold an overlong line onto a second
3131
- // row, and that second row — padded to full width by the frame, without a line number — was exactly
3132
- // what a differential painter could not reconcile with the previous frame: the leftover glyphs stayed
3133
- // under it as residue. One source line is one display row.
3134
- //
3135
- // THE CODE SURFACE: the whole row sits on `codeBg`, one step off the page. The number keeps its grey,
3136
- // the content keeps its syntax colours, and the wash reaches the right edge. Diff `+`/`-` rows are
3137
- // NOT affected — they keep their green/red.
3138
- //
3139
- // The background has to survive the row's own resets: every syntax token closes with `ESC[0m`, and the
3140
- // padding `fitAnsi` adds sits AFTER the last one. Re-asserting after each reset — the same trick
3141
- // `paintCode` uses for a diff wash — keeps the surface on the padding too, so the block reads solid.
3142
- const surfaced = text.replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
3143
- diffRows.push({ text: C.codeBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 ? pre : cont, raw: true });
3144
- return;
3145
- }
3146
- const wrapped = ln === '' ? [''] : wrapWords(ln, bodyW);
3147
- // BASH OUTPUT SITS ON THE TERMINAL SURFACE, like text inside a real terminal emulator: the darkest recess
3148
- // on screen. Other tools keep the plain page background, so a command's output reads as "a terminal ran
3149
- // this" rather than as an ordinary result. The row keeps its grey text and the surface survives its own
3150
- // resets the same way the code surface does.
3151
- const termSurface = msg.toolName === 'Bash' || msg.toolName === 'Shell';
3152
- wrapped.forEach((t, i) => {
3153
- if (termSurface) {
3154
- const surfaced = t.replace(/\x1b\[0m/g, `\x1b[0m${C.termBg}`);
3155
- diffRows.push({ text: C.termBg + fitAnsi(surfaced, bodyW) + C.bgReset, ind: idx === 0 && i === 0 ? pre : cont, raw: true });
3156
- } else {
3157
- diffRows.push({ text: t, ind: idx === 0 && i === 0 ? pre : cont, color });
3158
- }
3159
- });
1535
+ const writeRow = (col(num + ' ', C.white) + fitAnsi(painted.text, room)).replace(/\x1b\[0m/g, `\x1b[0m${C.codeBg}`);
1536
+ out.push({ text: C.codeBg + writeRow + C.bgReset, ind: i === 0 ? '↳ ' : indent, raw: true });
3160
1537
  });
3161
- if (visible.length > MAX_RESULT_LINES) {
3162
- // The hint says HOW to see the rest. It used to read only "… N more lines", so a truncated result gave
3163
- // the user no way to know Ctrl+O would reveal it — the key existed and was undiscoverable from the one
3164
- // place that needed it. Only reachable while COLLAPSED: expanded, `MAX_RESULT_LINES` is Infinity.
3165
- diffRows.push({
3166
- text: `… ${visible.length - MAX_RESULT_LINES} more lines, ctrl+o to expand`,
3167
- ind: cont,
3168
- color: failed ? C.red : C.gray,
3169
- });
3170
- }
1538
+ const shown = Math.min(lines.length, MAX);
1539
+ if (totalLines > shown) out.push({ text: col(`… ${totalLines - shown} more lines, ctrl+o to expand`, C.gray), ind: indent, raw: true });
3171
1540
  }
3172
1541
 
3173
- const out = [];
3174
- for (const r of diffRows) out.push(r);
3175
- for (const r of receiptRows) out.push(r);
3176
- // Put the `↳` on the FIRST rendered row (diff or output) — never on the
3177
- // receipt, which now sits last.
3178
- if (out.length && out[0].ind === cont && Array.isArray(msg.diff) && msg.diff.length > 0) {
3179
- out[0] = { ...out[0], ind: pre };
3180
- }
3181
- // The TOOL ROW may already have drawn this result's body — a Write streams the
3182
- // file's content up there ("↳ 1 line one …") — in which case the receipt below is
3183
- // the whole result and must NOT open a second `↳` block:
3184
- // ● Used Write (a.txt) 1.3KB
3185
- // ↳ 1 <content> <- the body, marked on the tool row
3186
- // ↳ File written: a.txt (1372 bytes) <- the stray second `↳`, now plain
3187
- // One body, one marker. `bodyOnToolRow` is set by the tool_result handler, which
3188
- // is the only place that knows whether the tool row had content to show.
3189
- if (msg.bodyOnToolRow && out.length && out[0].ind === pre) {
3190
- out[0] = { ...out[0], ind: cont };
3191
- }
3192
- // Nothing to show (empty output) -> render no row at all rather than a
3193
- // dangling "↳ ".
3194
- return out;
3195
- // Nothing to show (empty output) -> render no row at all rather than a
3196
- // dangling "↳ ".
3197
- return out;
3198
- }
1542
+ // The Edit diff is NOT drawn here: it rides on the tool_result message and is
3199
1543
 
3200
- // Compaction block, matching kimi-code's CompactionComponent:
3201
- // running -> blinking bullet + "Compacting context…" (+ optional instruction)
3202
- // done -> solid green bullet + "Compaction complete (X → Y tokens)"
3203
- // + " (Ctrl-O to show/hide compaction summary)"
3204
- // cancelled -> warning bullet + "Compaction cancelled"
3205
- // Expanded state is the SHARED Ctrl+O one, so one key reveals tool output and
3206
- // compaction summaries alike.
3207
- if (msg.role === 'compaction') {
3208
- const INDENT = ' ';
3209
- const done = msg.phase === 'done';
3210
- const canceled = msg.phase === 'cancelled';
3211
- const bulletColor = done ? C.green : canceled ? C.yellow : C.white;
3212
- // Blink off `spin` — the same monotonic tick the tool-call bullets use. It has
3213
- // to be a STATE-driven phase, NOT `Date.now()`: the render cache is validated
3214
- // against `spinKey`, so a clock-derived phase changes without invalidating the
3215
- // cache and the bullet renders once and then freezes.
3216
- const on = ((spin || 0) >> 3) % 2 === 0;
3217
- const bullet = (!done && !canceled && !on) ? ' ' : col('● ', bulletColor);
3218
- let head;
3219
- if (done) {
3220
- const detail = (msg.tokensBefore != null && msg.tokensAfter != null)
3221
- ? col(` (${fmtTokens(msg.tokensBefore)} → ${fmtTokens(msg.tokensAfter)} tokens)`, C.gray) : '';
3222
- const hint = (msg.text || '').trim()
3223
- ? col(` (Ctrl-O to ${expanded ? 'hide' : 'show'} compaction summary)`, C.gray) : '';
3224
- head = bullet + col('Compaction complete', C.green + C.bold) + detail + hint;
3225
- } else if (canceled) {
3226
- head = bullet + col('Compaction cancelled', C.yellow + C.bold)
3227
- + (msg.reason ? col(' (' + msg.reason + ')', C.gray) : '');
3228
- } else {
3229
- head = bullet + col('Compacting context…', C.cyan + C.bold);
3230
- }
3231
- const out = [{ text: head, ind: '', raw: true }];
3232
- if (msg.instruction) {
3233
- out.push({ text: INDENT + col(String(msg.instruction), C.gray), ind: INDENT, raw: true });
3234
- }
3235
- if (done && expanded && (msg.text || '').trim()) {
3236
- const bodyW = Math.max(1, width - visualCol(INDENT));
3237
- for (const ln of String(msg.text).replace(/\r\n/g, '\n').split('\n')) {
3238
- if (ln === '') { out.push({ text: '', ind: INDENT, raw: true }); continue; }
3239
- for (const w of wrapWords(ln, bodyW)) {
3240
- out.push({ text: INDENT + col(w, C.gray), ind: INDENT, raw: true });
3241
- }
3242
- }
3243
- }
1544
+ // The Edit diff is NOT drawn here: it rides on the tool_result message and is
1545
+ // rendered BELOW the `↳` receipt (see the tool_result branch). Drawing it here
1546
+ // put it between the `● Used Edit` status bullet and the receipt.
3244
1547
  return out;
3245
1548
  }
1549
+ // A PLAN block (Plan mode): the model's <|plan|>…</|plan|> body, rendered as a
1550
+ // single-column TABLE — the same ╭─┬─╮ / ├─┼─┤ / ╰─┴─╯ vocabulary the Markdown
1551
+ // table renderer uses, so a plan reads as structured data rather than as prose
1552
+ // or as a second composer box.
1553
+ if (msg.role === 'plan') return planRows(msg, width);
3246
1554
 
3247
- // Reasoning ("thinking") block, matching kimi-code's ThinkingComponent:
3248
- // live -> "<spinner> thinking…" then the LAST 2 content lines, indented
3249
- // finalized -> "● " marker on the first line, up to 2 preview lines, then a
3250
- // "… (N more lines)" hint
3251
- // All of it is dim text.
3252
- if (msg.role === 'thinking') {
3253
- const INDENT = ' ';
3254
- const bodyW = Math.max(1, width - visualCol(INDENT));
3255
- const contentLines = [];
3256
- for (const ln of String(msg.text || '').replace(/\r\n/g, '\n').split('\n')) {
3257
- if (ln === '') { contentLines.push(''); continue; }
3258
- for (const w of wrapWords(ln, bodyW)) contentLines.push(w);
3259
- }
3260
- // AN EMPTY REASONING BLOCK DRAWS NOTHING.
3261
- //
3262
- // A model may emit a `think` event with no text, and the block that spans a tool
3263
- // call can be left with nothing in it — the tool boundary finalises the block, so
3264
- // when the model reasons again it opens a NEW one. Either way the old code drew a
3265
- // bare `●` row (or a lone "thinking…" spinner), which reads as a rendering bug:
3266
- // there is no thought to show.
3267
- //
3268
- // Only the RENDERING is suppressed. The block stays in `state.chat`, so the next
3269
- // `think` event APPENDS to it rather than opening another one — the state machine
3270
- // (and the row cache that keys on it) is unchanged, and a block that later
3271
- // receives text appears with its full content.
3272
- if (!contentLines.some((l) => l.trim() !== '')) return [];
3273
- const PREVIEW = expanded ? Infinity : 2;
3274
- // The reasoning BODY is italic; the "thinking…" label and the "N more lines"
3275
- // hint are NOT. Closed with endItalic rather than reset, so the row keeps the
3276
- // dim gray it is drawn in.
3277
- const it = (s) => (s === '' ? s : C.italic + s + C.endItalic);
3278
- const out = [];
3279
- if (msg.pending) {
3280
- // The spinner frame is NOT baked in here: a glyph that changes every 80ms
3281
- // tick would invalidate this row's cache and re-wrap the whole reasoning
3282
- // block each time (measured ~44ms/frame vs ~6ms warm), which is what made
3283
- // long thinking look laggy while ordinary streamed text stayed smooth.
3284
- // renderChatLines substitutes the live frame outside the cache instead.
3285
- out.push({ text: SPIN_PLACEHOLDER + ' thinking…', ind: '', color: C.gray });
3286
- const vis = contentLines.length > PREVIEW ? contentLines.slice(-PREVIEW) : contentLines;
3287
- for (const l of vis) out.push({ text: it(l), ind: INDENT, color: C.gray });
3288
- } else {
3289
- const shown = contentLines.slice(0, PREVIEW);
3290
- shown.forEach((l, i) => out.push({ text: it(l), ind: i === 0 ? '● ' : INDENT, color: C.gray }));
3291
- if (contentLines.length > PREVIEW) {
3292
- out.push({ text: `… (${contentLines.length - PREVIEW} more lines, ctrl+o to expand)`, ind: INDENT, color: C.gray });
3293
- }
3294
- }
3295
- return out;
3296
- }
1555
+ // A BACKGROUND TASK lifecycle card (kimi-style).
1556
+ if (msg.role === 'bg_task') return bgTaskRows(msg, width, expanded);
3297
1557
 
1558
+ // Tool output: a single "↳ " marker on the first line, then the output
1559
+ // indented by 2 columns. Long output is capped (kimi caps result previews
1560
+ // too) so one command cannot flood the whole transcript.
1561
+ if (msg.role === 'tool_result') return toolResultRows(msg, width, expanded);
1562
+
1563
+ // Compaction block. Expanded state is the SHARED Ctrl+O one, so one key reveals tool output and compaction summaries
1564
+ // alike.
1565
+ if (msg.role === 'compaction') return compactionRows(msg, width, expanded, spin);
1566
+
1567
+ // Reasoning ("thinking") block. All of it is dim text.
1568
+ if (msg.role === 'thinking') return thinkingRows(msg, width, expanded);
3298
1569
 
3299
1570
 
3300
1571
  let icon = '';
@@ -3445,575 +1716,8 @@ function messageLines(msg, width, workspace, expanded, spin, pulseStart, rawMode
3445
1716
  return lines;
3446
1717
  }
3447
1718
 
3448
- // Block-level Markdown renderer. Produces pre-styled rows (each carries its own
3449
- // ANSI). Supports: headings, thematic breaks, blockquotes, unordered/ordered and
3450
- // INCREMENTAL markdown for a STREAMING assistant message.
3451
- //
3452
- // While a reply streams, `msg.text` grows every frame, and re-parsing the WHOLE
3453
- // accumulated text each time measured 5ms/frame at 10 KB and ~20ms at 50 KB — a
3454
- // visible stall at the 80ms tick ("the spinner freezes while it types").
3455
- //
3456
- // The unit of reuse is a top-level BLOCK: a run of lines up to the next blank line
3457
- // that is not inside a code fence, with the blank lines attached to the FOLLOWING
3458
- // block. Rendering block-by-block and concatenating produces byte-identical output
3459
- // to rendering the whole document (verified across headings, lists, fenced code,
3460
- // multiple fences, and consecutive blank lines), which is what makes the cache
3461
- // safe. Only the LAST block can still be growing, so only it is re-rendered.
3462
- //
3463
- // (An earlier attempt cut the text at a blank line and rendered head/tail
3464
- // separately. That is NOT equivalent — a trailing blank line contributes a row on
3465
- // its own but acts as a separator inside the whole document — so the two renders
3466
- // disagreed by a row. Blocks avoid the problem entirely.)
3467
- /**
3468
- * Version of the markdown renderer, part of the incremental cache key.
3469
- *
3470
- * That cache is validated on the INPUT — text, width, colours — which cannot see that the renderer
3471
- * itself now produces different rows for the same input. A session that cached a block before a fence
3472
- * type learned to draw kept showing the old output, so the change looked like it had not shipped.
3473
- * Bump this whenever what `renderMdText` produces for the same input changes.
3474
- */
3475
- const MD_RENDER_VERSION = 7; // 7: an image row carries the TeX that produced it
3476
-
3477
- export function renderMdIncremental(msg, text, width, fg, codeFg) {
3478
- const src = text.replace(/\r\n/g, '\n');
3479
- let c = msg._mdCache;
3480
- // Layout identity: same width/colours and the same text. Comparing the text (not
3481
- // just its length) is required — a same-length replacement must re-render.
3482
- if (c && c.v === MD_RENDER_VERSION && c.width === width && c.fg === fg && c.codeFg === codeFg && c.text === src) {
3483
- return { headRows: c.headRows, tailRows: c.tailRows, headCut: c.headCut };
3484
- }
3485
- if (!c || c.v !== MD_RENDER_VERSION || c.width !== width || c.fg !== fg || c.codeFg !== codeFg) {
3486
- c = msg._mdCache = { v: MD_RENDER_VERSION, width, fg, codeFg };
3487
- }
3488
-
3489
- const parts = splitBlocks(src);
3490
- // A block is final once a LATER block exists; the last one is still growing.
3491
- const headCount = Math.max(0, parts.length - 1);
3492
- // THE CACHED BLOCKS BELONG TO A VERSION OF THE RENDERER. Without that check a request for the same text,
3493
- // width and colours reuses rows produced by an OLDER renderer: the fast path above rejects them on `c.v`,
3494
- // but it leaves `c` untouched (its width and colours still match), and this reuse test then finds the block
3495
- // texts identical and hands back the old rows. That is why an image row kept arriving without the TeX it
3496
- // was made from after the field was added.
3497
- const canReuse = c.v === MD_RENDER_VERSION
3498
- && Array.isArray(c.blocks)
3499
- && Array.isArray(c.blockTexts)
3500
- && c.blockTexts.length >= headCount
3501
- && parts.length >= headCount
3502
- && c.blockTexts.slice(0, headCount).every((t, i) => t === parts[i]);
3503
-
3504
- const blocks = canReuse ? c.blocks.slice(0, headCount) : parts.slice(0, headCount).map((b) => renderMdText(b, width, fg, codeFg));
3505
- const headRows = [];
3506
- for (const b of blocks) for (const r of b) headRows.push(r);
3507
- const tailRows = renderMdText(parts.length ? parts[parts.length - 1] : '', width, fg, codeFg);
3508
- const headCut = parts.length > 1 ? parts.slice(0, headCount).join('\n').length : 0;
3509
-
3510
- msg._mdCache = {
3511
- v: MD_RENDER_VERSION,
3512
- text: src, width, fg, codeFg,
3513
- blocks, blockTexts: parts.slice(0, headCount),
3514
- headRows, tailRows, headCut,
3515
- };
3516
- return { headRows, tailRows, headCut };
3517
- }
3518
-
3519
- // Split at blank lines OUTSIDE a fence. The blank line(s) begin the NEXT block, so
3520
- // every block renders the same whether or not later blocks exist — that is the
3521
- // property the incremental cache depends on.
3522
- export function splitBlocks(src) {
3523
- if (src === '') return [''];
3524
- const lines = src.split('\n');
3525
- const out = [];
3526
- let cur = [];
3527
- let fence = false;
3528
- for (const ln of lines) {
3529
- const isFence = /^\s*(```+|~~~+)/.test(ln);
3530
- const blank = ln.trim() === '';
3531
- if (blank && !fence) {
3532
- if (cur.length) { out.push(cur); cur = []; }
3533
- cur.push(ln);
3534
- continue;
3535
- }
3536
- if (isFence) fence = !fence;
3537
- cur.push(ln);
3538
- }
3539
- if (cur.length) out.push(cur);
3540
- return out.map((b) => b.join('\n'));
3541
- }
3542
-
3543
- export function renderMdText(text, width, fg, codeFg) {
3544
- const src = String(text).replace(/\r\n/g, '\n');
3545
- const para = src.split('\n');
3546
- const out = [];
3547
- let i = 0;
3548
- const isTableSep = (l) => /^\s*\|?\s*:?-{2,}.*\|/.test(l) || /^\s*\|[-: ]+\|/.test(l);
3549
- const splitCells = (l) => {
3550
- const s = l.trim().replace(/^\|/, '').replace(/\|$/, '');
3551
- return s.split('|').map((c) => c.trim());
3552
- };
3553
-
3554
- while (i < para.length) {
3555
- let line = para[i];
3556
- const t = line.replace(/\s+$/, '');
3557
- // DISPLAY MATH: `$$ ... $$` and `\[ ... \]`.
3558
- //
3559
- // A fence is what a model writes when it wants a code block, but a formula usually arrives as `$$`.
3560
- // It is laid out here as the formula it describes — stacked fractions, limits above a sum — and its
3561
- // source is what remains when the subset cannot express it, exactly as a math fence behaves.
3562
- // The opener has to start the line and the closer has to end one, so `cost is $$x$$ total` stays prose
3563
- // and is handled as inline math by the line renderer below.
3564
- const mathOpen = /^\s*(\$\$|\\\[)/.exec(t);
3565
- if (mathOpen) {
3566
- const open = mathOpen[1];
3567
- const close = open === '$$' ? '$$' : '\\]';
3568
- const after = t.slice(mathOpen.index + mathOpen[0].length);
3569
- let body = null;
3570
- let used = 0;
3571
- let closed = true;
3572
- // One-line form: `$$x = 1$$` with nothing but whitespace after the closer.
3573
- const oneLine = after.indexOf(close);
3574
- if (oneLine >= 0 && after.slice(oneLine + close.length).trim() === '') {
3575
- body = after.slice(0, oneLine);
3576
- used = 1;
3577
- } else if (after.trim() === '') {
3578
- // Multi-line form: everything up to the line that ends with the closer.
3579
- const collected = [];
3580
- let k = i + 1;
3581
- let found = false;
3582
- while (k < para.length) {
3583
- const cl = para[k].replace(/\s+$/, '');
3584
- if (cl.trimEnd().endsWith(close)) {
3585
- collected.push(cl.slice(0, cl.lastIndexOf(close)));
3586
- k++;
3587
- found = true;
3588
- break;
3589
- }
3590
- collected.push(para[k]);
3591
- k++;
3592
- }
3593
- body = collected.join('\n');
3594
- used = k - i;
3595
- // Still streaming: no closer yet, so the body is prose plus half a formula.
3596
- closed = found;
3597
- }
3598
- if (body !== null && closed) {
3599
- i += used;
3600
- // Same three fallbacks as a math fence: bitmap, Unicode layout, then the source.
3601
- const rows = mathBlockRows(body, width, true);
3602
- if (rows) {
3603
- out.push(...rows);
3604
- } else {
3605
- // Unsupported: show the TeX so the reader still gets the formula's meaning.
3606
- for (const l of body.split('\n')) out.push(col(' ' + l.slice(0, Math.max(1, width - 2)), C.white));
3607
- }
3608
- continue;
3609
- }
3610
- }
3611
- // Fenced code block. Rendered with a rule ABOVE (labelled with the language)
3612
- // and a matching full-width rule BELOW, so the block is visibly delimited.
3613
- const fm = /^\s*(`{3,}|~{3,})\s*(\S*)/.exec(t);
3614
- if (fm) {
3615
- const lang = fm[2] || '';
3616
- i++;
3617
- const buf = [];
3618
- const fenceChar = fm[1][0];
3619
- const fenceLen = fm[1].length;
3620
- const isCloser = (s) => {
3621
- const m = /^\s*(`{3,}|~{3,})\s*$/.exec(s);
3622
- return !!m && m[1][0] === fenceChar && m[1].length >= fenceLen;
3623
- };
3624
- while (i < para.length && !isCloser(para[i])) { buf.push(para[i]); i++; }
3625
- // Whether the closing fence was actually reached: an open fence means the text is still streaming.
3626
- const fenceClosed = i < para.length;
3627
- i++; // closing fence (no-op when the fence is still open)
3628
- const rule = (s) => col(s, C.gray);
3629
- // MATH FENCES ARE TYPESET. A `latex`/`tex`/`math` fence is TeX, not code: it is drawn as the formula
3630
- // it describes, and when the terminal speaks an image protocol it is drawn as a TYPESET BITMAP rather
3631
- // than as flattened Unicode — the same pipeline dsh-tui uses, with STIX Two Math.
3632
- //
3633
- // Three fallbacks, in order, and each one keeps the formula: the bitmap; the Unicode layout when the
3634
- // picture cannot be placed (no protocol, no cell size, too wide, too tall); the SOURCE when the subset
3635
- // cannot express the TeX at all.
3636
- if (/^(latex|tex|math)$/i.test(lang)) {
3637
- const tex = buf.join('\n').trim();
3638
- const rendered = mathBlockRows(tex, width, fenceClosed);
3639
- if (rendered) {
3640
- out.push(...rendered);
3641
- continue;
3642
- }
3643
- // Falls through to the plain code block: the source is all we have.
3644
- }
3645
- if (/^mermaid$/i.test(lang)) {
3646
- const src = buf.join('\n');
3647
- let art = null;
3648
- try { art = renderMermaid(src); } catch { art = null; }
3649
- // Wider than the panel: the frame is the honest answer, since truncating art
3650
- // would cut a box in half rather than say the diagram does not fit.
3651
- if (art && art.width <= width) {
3652
- // `styled` keeps the role of every span, so the frame stays dim and the
3653
- // connectors cyan instead of the whole diagram arriving as plain white text.
3654
- const coloured = mermaidAnsi(art);
3655
- for (const l of coloured) out.push(l);
3656
- continue;
3657
- }
3658
- try {
3659
- for (const l of mermaidSourceBox(src, width).plain) out.push(col(l, C.white));
3660
- continue;
3661
- } catch { /* fall through to the plain code block */ }
3662
- }
3663
- // Opening rule: `─ <lang> ` then `─` padding out to the FULL width.
3664
- // (The old version subtracted 4 and was 2 columns short of the panel.)
3665
- if (lang) {
3666
- const head = `\u2500 ${lang} `;
3667
- out.push(rule(head + '─'.repeat(Math.max(1, width - visualCol(head)))));
3668
- } else {
3669
- out.push(rule('─'.repeat(Math.max(1, width))));
3670
- }
3671
- // Fenced code block CONTENT is plain body text — render it in the
3672
- // default terminal colour (white), not the theme's cyan. The cyan is
3673
- // reserved for UI chrome and the language label; a large code block in
3674
- // cyan reads as "everything is the theme colour".
3675
- for (const cl of buf) out.push(col(cl.slice(0, width), C.white));
3676
- // Closing rule, matching the opening one.
3677
- out.push(rule('─'.repeat(Math.max(1, width))));
3678
- continue;
3679
- }
3680
- // Table: a header line followed by a separator line
3681
- if (t.includes('|') && i + 1 < para.length && isTableSep(para[i + 1])) {
3682
- const header = splitCells(t);
3683
- const sep = splitCells(para[i + 1]);
3684
- const body = [];
3685
- i += 2;
3686
- while (i < para.length && para[i].trim().includes('|') && !isTableSep(para[i])) { body.push(splitCells(para[i])); i++; }
3687
- renderTable(out, header, body, sep.length, width, fg);
3688
- continue;
3689
- }
3690
- // Fall through to single-line renderer
3691
- const rows = markdownLineToRows(t, width, fg, codeFg, false);
3692
- out.push(...rows);
3693
- i++;
3694
- }
3695
- return out;
3696
- }
3697
-
3698
- // Render a Markdown table as aligned columns. Header bolded, rows readable.
3699
- function renderTable(out, header, body, colCount, width, fg) {
3700
- const cols = Math.max(header.length, colCount, ...body.map((r) => r.length));
3701
- const B = C.border;
3702
- const val = (r, c) => (r && r[c] !== undefined ? String(r[c]) : '');
3703
- // Per-column natural width (visual columns), reserving 2 padding each side.
3704
- const natural = Array.from({ length: cols }, (_, c) => {
3705
- let m = 0;
3706
- const consider = (v) => { m = Math.max(m, visualCol(v)); };
3707
- consider(val(header, c));
3708
- for (const r of body) consider(val(r, c));
3709
- return m;
3710
- });
3711
- // Cap total table width to the available width (minus borders).
3712
- const availInner = Math.max(cols, width - (cols + 1));
3713
- const totalNatural = natural.reduce((a, b) => a + 2 + b, 0);
3714
- let widths;
3715
- if (totalNatural <= availInner) {
3716
- widths = natural;
3717
- } else {
3718
- // Scale down proportionally, but never below MIN_COL. A column squeezed to 1 is a column whose content is
3719
- // unreadable, so the shrink stops at a width a word can still use and the ROW grows taller instead.
3720
- const MIN_COL = 4;
3721
- const over = totalNatural - availInner;
3722
- const surplus = natural.reduce((a, b) => a + (b > MIN_COL ? b - MIN_COL : 0), 0);
3723
- widths = natural.map((n) => {
3724
- const shrink = over > 0 && surplus > 0 ? Math.round((Math.max(0, n - MIN_COL)) * (over / surplus)) : 0;
3725
- return Math.max(Math.min(MIN_COL, n), n - shrink);
3726
- });
3727
- }
3728
- // WRAP, DO NOT TRUNCATE. A cell whose text does not fit its column used to be emitted at full length, which
3729
- // pushed every border after it to the right and broke the table's alignment for the rest of the row. The
3730
- // row now grows taller: each cell is wrapped to its column, and every line is padded to the same width.
3731
- const wrapCell = (text, w) => {
3732
- if (!text) return [''];
3733
- return wrapWords(text, Math.max(1, w));
3734
- };
3735
- // A cell renders its INLINE MARKDOWN (bold, code, links) — a table of `**name**` and `\`value\`` used to show
3736
- // the asterisks and backticks verbatim, which is not what the author wrote.
3737
- const styled = (text, w, bold) => {
3738
- const plain = wrapCell(text, w);
3739
- const paint = bold ? C.white + C.bold : C.gray;
3740
- return plain.map((line) => {
3741
- // Render the markdown FIRST, then pad the RESULT.
3742
- //
3743
- // The pad has to be measured on what the cell will actually PRINT, not on the source: `` `--verbose` ``
3744
- // is 11 characters of source but 9 on screen once the backticks become a colour, so padding by the source
3745
- // width left the column short by two and every border after it moved left.
3746
- const md = inlineMarkdown(line, C.gray, bold ? C.white : C.gray);
3747
- const printed = visualCol(String(md).replace(/\x1b\[[0-9;]*m/g, ''));
3748
- const pad = Math.max(0, w - printed);
3749
- return col(' ', paint) + col(md, paint) + col(' '.repeat(pad) + ' ', paint);
3750
- });
3751
- };
3752
- const rule = (left, mid, right) => col(left + widths.map((w) => '─'.repeat(w + 2)).join(mid) + right, B);
3753
- // One logical row, as several physical lines when any cell wraps.
3754
- const oneRow = (cells, bold) => {
3755
- const rendered = [];
3756
- for (let c = 0; c < cols; c++) rendered.push(styled(val(cells, c), widths[c], bold));
3757
- const height = Math.max(1, ...rendered.map((r) => r.length));
3758
- for (let line = 0; line < height; line++) {
3759
- const parts = rendered.map((r, c) => (r[line] !== undefined
3760
- ? r[line]
3761
- : col(' ' + ' '.repeat(widths[c]) + ' ', bold ? C.white + C.bold : C.gray)));
3762
- out.push(col('│', B) + parts.join(col('│', B)) + col('│', B));
3763
- }
3764
- };
3765
- out.push(rule('╭', '┬', '╮'));
3766
- oneRow(header, true);
3767
- out.push(rule('├', '┼', '┤'));
3768
- for (const r of body) oneRow(r, false);
3769
- out.push(rule('╰', '┴', '╯'));
3770
- }
3771
- function markdownLineToRows(line, width, fg, codeFg, isContinuation) {
3772
- const out = [];
3773
- const t = line.replace(/\s+$/, '');
3774
-
3775
- // Headings: `# Title`
3776
- let m = /^(\s*)(#{1,6})\s+(.*)$/.exec(t);
3777
- if (m && !isContinuation) {
3778
- const hashCount = m[2].length;
3779
- // h1 is bold white, h2 is plain white, h3+ is gray. Only h1 carries BOLD.
3780
- const size = hashCount === 1 ? C.white + C.bold : hashCount === 2 ? C.white : C.gray;
3781
- for (const w of wrapWords(m[3], width)) {
3782
- out.push(col(w, size));
3783
- }
3784
- return out;
3785
- }
3786
- // Thematic break
3787
- if (/^\s*(-{3,}|\*{3,}|_{3,})$/.test(t)) {
3788
- out.push(col('─'.repeat(Math.min(width, Math.max(8, width))), C.gray));
3789
- return out;
3790
- }
3791
- // Blockquote
3792
- //
3793
- // THE RULE AND THE TEXT ARE DIFFERENT COLOURS. The rule takes the theme colour, so a quote reads as a distinct
3794
- // block in the transcript; the text takes the comment grey, so quoted material is visibly not the reply's own
3795
- // voice. Colouring both the same made a quote indistinguishable from an indented paragraph.
3796
- if (/^\s*>\s?/.test(t)) {
3797
- const content = t.replace(/^\s*>\s?/, '');
3798
- for (const w of wrapWords(content, Math.max(1, width - 2))) {
3799
- out.push(col('▍ ', C.cyan) + col(w, C.comment));
3800
- }
3801
- return out;
3802
- }
3803
- // Unordered/ordered list — bold the bullet, keep content plain. Also handles
3804
- // task checkboxes `- [ ] xxx` / `- [x] xxx`.
3805
- {
3806
- const task = /^(\s*)([-*+]\s+)?\[( |x|X)\]\s+(.*)$/.exec(t);
3807
- if (task && !isContinuation) {
3808
- const checked = task[3] !== ' ';
3809
- const box = checked ? col('✓', C.green) : col('○', C.gray);
3810
- const content = col(' ' + inlineMarkdown(task[4], codeFg, fg), fg);
3811
- for (const w of wrapWords(task[4], Math.max(1, width - 4))) {
3812
- out.push(col(' ', C.gray) + box + (w === task[4] ? content : col(' ' + w, fg)));
3813
- }
3814
- return out;
3815
- }
3816
- const li = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/.exec(t);
3817
- if (li && !isContinuation) {
3818
- const isOrdered = /^\d/.test(li[2]);
3819
- const bullet = isOrdered ? col(li[2], C.cyan) : col('•', C.cyan);
3820
- const pad = isOrdered ? ' '.repeat(visualCol(li[2])) + ' ' : ' ';
3821
- let first = true;
3822
- for (const w of wrapWords(inlineMarkdown(li[3], codeFg, fg), Math.max(1, width - 2))) {
3823
- out.push((first ? col('', C.gray) + bullet + ' ' : col(pad, C.gray)) + col(w, fg));
3824
- first = false;
3825
- }
3826
- return out;
3827
- }
3828
- }
3829
- // Inline styles: **bold**, *italic*, `code`, [text](url), $math$
3830
- if (/[*`\[$]|\\\(/.test(t)) {
3831
- for (const w of wrapWords(t, width)) out.push(col(inlineMarkdown(w, codeFg, fg), fg));
3832
- return out;
3833
- }
3834
- // Plain - apply default foreground color
3835
- for (const w of wrapWords(t, width)) out.push(col(w, fg));
3836
- return out;
3837
- }
3838
-
3839
- /**
3840
- * Whether the terminal can receive a formula as a picture.
3841
- *
3842
- * Both halves are required: a protocol the terminal reported (Sixel today) and a cell size it reported
3843
- * (XTWINOPS 16). Without the cell size the picture would be measured in guessed cells, which is what put a
3844
- * formula on the wrong rows before — so a missing cell size falls back to text rather than guess.
3845
- */
3846
- function mathImageCapable() {
3847
- const caps = terminalCaps();
3848
- if (!caps) return null;
3849
- // KITTY FIRST. A terminal that speaks both (Kitty can be built with Sixel support) handles Kitty far
3850
- // better: the pixels are uploaded once and every later frame is a placement, while a Sixel has to be
3851
- // retransmitted and moves the cursor when it is drawn.
3852
- const protocol = caps.kittyGraphics
3853
- ? 'kitty'
3854
- : (Array.isArray(caps.extensions) && caps.extensions.includes('sixel') ? 'sixel' : null);
3855
- if (!protocol) return null;
3856
- const cell = caps.cell && caps.cell.w > 0 && caps.cell.h > 0 ? caps.cell : null;
3857
- return cell ? { protocol, cell } : null;
3858
- }
3859
-
3860
- /** Ink colour for a typeset formula: the body text colour, so a picture sits in the text rather than beside it. */
3861
- const MATH_INK = { r: 220, g: 220, b: 220 };
3862
-
3863
- /**
3864
- * The terminal's cell height in pixels, for cropping a picture that straddles the top of the window.
3865
- *
3866
- * A crop has to convert CELL ROWS to six-pixel BANDS; without the cell height the two units get confused and
3867
- * the image is drawn from the wrong point in its own payload. 20 is the conventional monospace cell height and
3868
- * matches the fallback `src/tex/` uses when the terminal never answers XTWINOPS 16.
3869
- *
3870
- * @returns {number}
3871
- */
3872
- function mathCellHeight() {
3873
- const caps = terminalCaps();
3874
- const cell = caps && caps.cell;
3875
- return cell && cell.h > 0 ? cell.h : 20;
3876
- }
3877
-
3878
- /**
3879
- * Rows for one display formula: a typeset bitmap when the terminal can show one, the Unicode layout when it
3880
- * cannot, and nothing when the TeX is outside the subset (the caller then shows the source).
3881
- *
3882
- * @param {string} tex TeX without delimiters.
3883
- * @param {number} width Columns available.
3884
- * @param {boolean} closed The closing delimiter arrived. A formula still streaming keeps to the text form: a
3885
- * picture of half a formula is worse than the TeX of half a formula.
3886
- * @returns {string[]|null}
3887
- */
3888
- function mathBlockRows(tex, width, closed) {
3889
- const src = stripMathDelimiters(tex);
3890
- if (!src) return null;
3891
- // A picture sits where the text form does: one column of indent, and no wider than the panel.
3892
- const room = Math.max(8, width - 2);
3893
- if (closed) {
3894
- const placed = placeTex(src, room);
3895
- if (placed) return placed;
3896
- }
3897
- const rendered = renderLatex(src, { display: true });
3898
- if (rendered === undefined) return null;
3899
- return rendered
3900
- .split('\n')
3901
- .map((l) => col(l.slice(0, width), C.white));
3902
- }
3903
-
3904
- /**
3905
- * Remove the delimiters a formula may still be wrapped in.
3906
- *
3907
- * A `$$…$$` block and a ```latex fence both reach the typesetter, and the fence's content may carry the
3908
- * delimiters too — a model writes the fence around `$$…$$` often enough that it is the common case, not the
3909
- * odd one. Typesetting the delimiters along with the formula draws them as glyphs inside the picture, which
3910
- * is what a literal `$$` in the middle of an integral looks like.
3911
- *
3912
- * Only a delimiter that spans the WHOLE body is removed: a `$$` in the middle is TeX the author meant, and
3913
- * stripping it would change the formula. The loop runs because a doubled wrapper (`\n$$\n…\n$$\n` inside a
3914
- * fence) leaves one pair behind after the first pass.
3915
- *
3916
- * @param {string} tex
3917
- * @returns {string}
3918
- */
3919
- function stripMathDelimiters(tex) {
3920
- let s = String(tex || '').trim();
3921
- for (;;) {
3922
- const before = s;
3923
- if (s.startsWith('$$') && s.endsWith('$$') && s.length > 4) {
3924
- s = s.slice(2, -2).trim();
3925
- } else if (s.startsWith('\\[') && s.endsWith('\\]') && s.length > 4) {
3926
- s = s.slice(2, -2).trim();
3927
- } else if (s.startsWith('\\(') && s.endsWith('\\)') && s.length > 4) {
3928
- s = s.slice(2, -2).trim();
3929
- }
3930
- if (s === before) return s;
3931
- }
3932
- }
3933
-
3934
-
3935
- /**
3936
- * Typeset a formula into a frame row, or null when it cannot be placed as a picture here.
3937
- *
3938
- * The picture is one row of TEXT plus a payload: the row is the sentinel `image-row.js` understands, the
3939
- * rows below it are blank, and the frame writer turns them into a cursor move and a Sixel sequence. Every
3940
- * reason to decline is a reason the caller already has a text fallback for, so this never throws.
3941
- *
3942
- * @param {string} tex
3943
- * @param {number} room Columns the picture may occupy.
3944
- */
3945
- function placeTex(tex, room) {
3946
- const capable = mathImageCapable();
3947
- if (!capable) return null;
3948
- try {
3949
- // Measured first, because laying out is what rejects TeX outside the subset: a raster would be paid for
3950
- // and then thrown away.
3951
- const measured = measureTex(tex, { cell: capable.cell });
3952
- if (!measured || measured.columns > room || measured.rows > TEX_MAX_ROWS) return null;
3953
- const image = encodeTexImage(tex, { protocol: capable.protocol, cell: capable.cell, colour: MATH_INK });
3954
- if (!image) return null;
3955
- // THE SOURCE TRAVELS WITH THE ROW. A picture that straddles the top of the window has to be redrawn from
3956
- // its first VISIBLE row, and only the TeX can produce that raster: cropping the encoded payload can only
3957
- // land on a six-pixel band boundary, which leaves up to a quarter of a cell of the formula above the
3958
- // window and makes it slide as the view scrolls. `paintCellFrame` reads this back and re-renders with
3959
- // `skipTop` when a picture needs cropping.
3960
- const rows = [encodeImageRowHelper(image.sequence, image.rows, image.columns, tex)];
3961
- for (let r = 1; r < image.rows; r++) rows.push('');
3962
- return rows;
3963
- } catch {
3964
- // A bitmap that cannot be drawn is a reason to show text, never a reason to lose the frame.
3965
- return null;
3966
- }
3967
- }
3968
-
3969
- /**
3970
- * Whether a `$...$` body is a formula rather than prose.
3971
- *
3972
- * Prices, shell variables and identifiers all use `$`: `costs $5 and $10`, `$HOME`, `${VAR}`. A body that
3973
- * starts or ends with a space, is a bare number or an all-caps word is prose, and so is one with no TeX
3974
- * command and no operator in it — `vitamin $C$` stays text while `$x^2$` becomes a formula.
3975
- */
3976
- function looksLikeInlineMath(body) {
3977
- if (/^\s/.test(body) || /\s$/.test(body)) return false;
3978
- if (body.startsWith('{') || body.includes('`')) return false;
3979
- if (/^\d+([.,]\d+)?$/.test(body)) return false;
3980
- if (/^[A-Z][A-Z0-9_]*$/.test(body)) return false;
3981
- return /\\[A-Za-z]+|[=+\-*/<>^_]/.test(body) || (/^[A-Za-z]$/.test(body));
3982
- }
3983
-
3984
- // Apply inline markdown to a single line: `code`, **bold**, *italic*, ~~strike~~,
3985
- // [text](url). Order matters so inner tokens are handled safely.
3986
- // `base` is the surrounding foreground colour; every inline style re-asserts it
3987
- // after its own reset, otherwise the bare `\e[0m` would cancel the base colour
3988
- // for the REST of the line (plain text after a **bold** run used to lose its
3989
- // colour and fall back to the terminal default).
3990
- function inlineMarkdown(s, codeFg, base) {
3991
- const fb = base || '';
3992
- let r = s;
3993
- // Inline code first so it is not mangled by * [] ~.
3994
- r = r.replace(/`([^`]+)`/g, (_, c) => col(c, codeFg) + fb);
3995
- // INLINE MATH. After the code spans, so a formula inside backticks stays code, and before emphasis, so
3996
- // `*` and `_` inside TeX cannot turn into italics. `\(...\)` is the other inline form models use.
3997
- r = r.replace(/\$([^$\n]+?)\$|\\\(([^\n]+?)\\\)/g, (m, dollar, paren) => {
3998
- const tex = dollar !== undefined ? dollar : paren;
3999
- // A price or a shell variable is not math: `$5 and $10`, `$HOME`, `${VAR}`.
4000
- if (dollar !== undefined && !looksLikeInlineMath(tex)) return m;
4001
- const out = renderLatex(tex, { display: false });
4002
- // Unsupported or multi-line: the source stands, because inline math sits inside wrapped prose.
4003
- if (out === undefined || out.includes('\n')) return m;
4004
- return out;
4005
- });
4006
- // Bold
4007
- r = r.replace(/\*\*([^*]+)\*\*/g, (_, c) => C.bold + c + C.reset + fb);
4008
- // Strikethrough
4009
- r = r.replace(/~~([^~]+)~~/g, (_, c) => '\x1b[9m' + c + '\x1b[29m');
4010
- // Italic
4011
- r = r.replace(/(^|[^*])\*([^*\s][^*]*?)\*(?!\*)/g, (_, pre, c) => pre + '\x1b[3m' + c + '\x1b[23m');
4012
- // Links: [text](url) -> text (cyan); autolink bare http(s) urls
4013
- r = r.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_, txt) => col(txt, C.cyan) + fb);
4014
- r = r.replace(/(^|\s)(https?:\/\/[^\s]+)/g, (_, pre, url) => pre + col(url, C.cyan));
4015
- return r;
4016
- }
1719
+ // Block-level Markdown rendering lives in src/markdown.js: headings, rules, quotes, lists, tables, fenced code, math
1720
+ // fences and the incremental block cache.
4017
1721
 
4018
1722
  // Flatten chat buffer into visible colored lines.
4019
1723
  // Render the chat to display lines. Each message caches its rendered rows keyed
@@ -4839,143 +2543,6 @@ function modeLabel(mode) {
4839
2543
  return 'Ask';
4840
2544
  }
4841
2545
 
4842
- function trimDecimal(v) {
4843
- const s = v.toFixed(1);
4844
- return s.endsWith('.0') ? s.slice(0, -2) : s;
4845
- }
4846
-
4847
- // Token counts use DECIMAL units, the same ones `fmtTokensShort` uses for the working row.
4848
- //
4849
- // This was 1024-based, on the reasoning that a context size is a power of two, so 262144 would read
4850
- // as "256k" rather than "262.1k". Two things outweighed that:
4851
- //
4852
- // * TOKENS ARE NOT BYTES. Dividing by 1024 turns a count of 97000 tokens into "94.7k", which is
4853
- // simply wrong — and the context window is not the only figure here, since /ctx and /usage also
4854
- // report live counts that are not powers of two.
4855
- // * IT DISAGREED WITH ITSELF ON SCREEN. The working row divided by 1000 and this divided by 1024,
4856
- // so one frame showed "97k" for the turn and "94.7k" for the context it was using.
4857
- //
4858
- // A model's window is advertised in decimal terms anyway (200k, 128k), so nothing is lost at the
4859
- // size that matters. Suffixes are K/M/B/T, with only the kilo left lower-case.
4860
- function fmtTokens(n) {
4861
- const v = Math.max(0, Math.floor(Number(n) || 0));
4862
- if (!Number.isFinite(v)) return '0';
4863
- const units = [
4864
- { at: 1e12, suffix: 'T' },
4865
- { at: 1e9, suffix: 'B' },
4866
- { at: 1e6, suffix: 'M' },
4867
- { at: 1e3, suffix: 'k' },
4868
- ];
4869
- for (let i = 0; i < units.length; i++) {
4870
- const u = units[i];
4871
- if (v < u.at) continue;
4872
- // The SAME scaling rule as `fmtTokensShort`, including the whole-number threshold: a tenth is
4873
- // information at `1.2k` and noise at `262.1k`. Sharing the rule is what keeps one frame from
4874
- // showing `262.1k` for the context and `262k` for the turn that filled it.
4875
- const shown = scaleUnit(v / u.at);
4876
- // Rounding can reach the next unit (`999999` is `1000k`, which is `1m`).
4877
- if (Number(shown) >= 1000 && i > 0) return scaleUnit(v / units[i - 1].at) + units[i - 1].suffix;
4878
- return shown + u.suffix;
4879
- }
4880
- return String(v);
4881
- }
4882
-
4883
- /**
4884
- * One unit's worth of a count: `1.2`, `97`, `262`.
4885
- *
4886
- * One decimal below 100, whole numbers at and above it. Used by every token formatter so the same
4887
- * quantity cannot read two ways on one screen.
4888
- */
4889
- function scaleUnit(v) {
4890
- if (v < 100) return v.toFixed(1).replace(/\.0$/, '');
4891
- const r = Math.round(v);
4892
- // A value that ROUNDS to the whole number keeps its decimal: 1048576/1e6 is 1.048576, and printing `1` put it
4893
- // in the same bucket as a plain million. `v === r` is the exact case.
4894
- if (r >= 100 && Math.abs(v - r) <= 0.5) return String(r);
4895
- return v.toFixed(1).replace(/\.0$/, '');
4896
- }
4897
-
4898
- // Thousands separators for a plain count. fmtTokens rounds to k/M, which is right
4899
- // for a context gauge but wrong for a token BILL: "1.5M input tokens" hides
4900
- // whether that is 1.45M or 1.54M, and the cost readout next to it is precise.
4901
- function fmtCount(n) {
4902
- const v = Number(n);
4903
- if (!Number.isFinite(v)) return '0';
4904
- return Math.round(v).toLocaleString('en-US');
4905
- }
4906
-
4907
- // A money amount, at a precision that stays readable across five orders of
4908
- // magnitude: a single cheap request is fractions of a cent, a long session is
4909
- // dollars. A bare `0.00` for a real cost is the failure to avoid, so anything
4910
- // non-zero under a cent keeps its decimals rather than rounding away. The symbol
4911
- // is the caller's business — the status row puts it AFTER the number.
4912
- function moneyAmount(v, currency = 'USD') {
4913
- const n = Number(v);
4914
- if (!Number.isFinite(n)) return 'n/a';
4915
- // CNY is about 7x USD, so the same amount crosses these thresholds one step
4916
- // sooner; scaling the comparison keeps both currencies at the same precision.
4917
- const scale = currency === 'CNY' ? 7 : 1;
4918
- if (n === 0) return '0.00';
4919
- if (n * scale < 0.01) return n.toFixed(5);
4920
- if (n * scale < 1) return n.toFixed(4);
4921
- return n.toFixed(2);
4922
- }
4923
-
4924
- /**
4925
-
4926
- /**
4927
- * `$12.34` / `¥86.51` — the amount with its symbol in front, for a panel line
4928
- * where there is room to spell the currency out too.
4929
- */
4930
- function formatCost(amount, currency = 'USD') {
4931
- const n = Number(amount);
4932
- if (!Number.isFinite(n)) return 'unknown';
4933
- return `${currency === 'CNY' ? '¥' : '$'}${moneyAmount(n, currency)}`;
4934
- }
4935
-
4936
- // A tiny ASCII line chart for a numeric series (context growth over steps).
4937
- // Renders `height` rows; each column is one sample, scaled to the series max.
4938
- // No dependency — Claude Code pulls in `asciichart`, we do not need it.
4939
- function sparkChart(values, width, height) {
4940
- const series = (values || []).filter((v) => Number.isFinite(v));
4941
- if (series.length < 2) return [];
4942
- // Downsample to `width` columns by taking evenly spaced samples.
4943
- const cols = Math.min(width, series.length);
4944
- const sampled = [];
4945
- for (let i = 0; i < cols; i++) {
4946
- sampled.push(series[Math.round(i / (cols - 1) * (series.length - 1))]);
4947
- }
4948
- const max = Math.max(...sampled, 1);
4949
- const min = Math.min(...sampled, 0);
4950
- const span = Math.max(1, max - min);
4951
- const rows = [];
4952
- const BLOCK = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
4953
- // Single-row sparkline.
4954
- if (height <= 1) {
4955
- rows.push(sampled.map((v) => BLOCK[Math.min(8, Math.round((v - min) / span * 8))]).join(''));
4956
- return rows;
4957
- }
4958
- for (let r = height - 1; r >= 0; r--) {
4959
- let line = '';
4960
- for (const v of sampled) {
4961
- const level = (v - min) / span * (height - 1);
4962
- line += level >= r ? '█' : ' ';
4963
- }
4964
- rows.push(line);
4965
- }
4966
- return rows;
4967
- }
4968
-
4969
- // Usage as a whole-number percentage of `max`, ceiled so any non-zero usage
4970
- // shows at least 1%, clamped to [0, 100]. A non-positive or non-finite `max`
4971
- // reports 0.
4972
- function usagePercent(used, max) {
4973
- // `used` can be undefined on a session resumed before any usage was recorded. Without this guard the
4974
- // division produced NaN and the row printed `NaN%` where it should have printed `0%`.
4975
- if (!Number.isFinite(used)) return 0;
4976
- if (!Number.isFinite(max) || max <= 0) return 0;
4977
- return Math.min(100, Math.max(0, Math.ceil((used / max) * 100)));
4978
- }
4979
2546
 
4980
2547
  // The session's spend, cached on `state` for the status bar. Called wherever its
4981
2548
  // inputs change — a usage event, a model switch, a resume, /new, a currency
@@ -5018,151 +2585,7 @@ export function costCurrency(cfg) {
5018
2585
  return normalizeCurrency(raw) || 'USD';
5019
2586
  }
5020
2587
 
5021
- // Human-readable elapsed duration, omitting zero leading units:
5022
- // 1y 1mon 1d 1h 1min 1s / 2y 2mon 2d 2h 2min 2s
5023
- // Units are NEVER pluralised with a trailing "s": the old code rendered 5
5024
- // minutes as "5ms", which reads as 5 MILLISECONDS (and 2 hours as "2hs").
5025
- // Minutes are "m", so months use "mon" to stay unambiguous.
5026
- function fmtDuration(ms) {
5027
- ms = Math.max(0, Math.floor(ms));
5028
- const sec = Math.floor(ms / 1000) % 60;
5029
- const min = Math.floor(ms / 60000) % 60;
5030
- const hour = Math.floor(ms / 3600000) % 24;
5031
- const day = Math.floor(ms / 86400000) % 30;
5032
- const mon = Math.floor(ms / 2592000000) % 12;
5033
- const year = Math.floor(ms / 31536000000);
5034
- const parts = [];
5035
- if (year) parts.push(year + 'y');
5036
- if (mon) parts.push(mon + 'mon');
5037
- if (day) parts.push(day + 'd');
5038
- if (hour) parts.push(hour + 'h');
5039
- if (min) parts.push(min + 'm');
5040
- // Seconds are always shown (at least "0s").
5041
- parts.push(sec + 's');
5042
- return parts.join(' ');
5043
- }
5044
-
5045
- // The turn's output tokens as `50k`, `1.2k`, `999`, or '' when nothing has arrived yet.
5046
- // Singular only at exactly 1, which is the one count small enough to read as a word.
5047
- function fmtTokensShort(n) {
5048
- const v = Math.max(0, Math.floor(Number(n) || 0));
5049
- if (v < 1000) return `${v} token${v === 1 ? '' : 's'}`;
5050
- // The same rule `Intl` compact notation applies, and the same one Claude Code shows, so a figure
5051
- // read in one tool is not read differently in the other:
5052
- //
5053
- // 1200 -> 1.2k one decimal while it carries information
5054
- // 9999 -> 10k compact rounds here, so the decimal falls away on its own
5055
- // 12400 -> 12.4k STILL one decimal — whole thousands would lose the 400
5056
- // 1234567 -> 1.2M and each thousand-group gets its own unit
5057
- //
5058
- // This used to switch to whole thousands at 10k and had no unit above `k`, so 1.2M read as
5059
- // `1235k`. `m` is not a rounding nicety: `1235k` makes the reader count digits to see the size.
5060
- const units = [
5061
- { at: 1e12, suffix: 'T' },
5062
- { at: 1e9, suffix: 'B' },
5063
- { at: 1e6, suffix: 'M' },
5064
- { at: 1e3, suffix: 'k' },
5065
- ];
5066
- for (let i = 0; i < units.length; i++) {
5067
- const u = units[i];
5068
- if (v < u.at) continue;
5069
- const scaled = v / u.at;
5070
- // One decimal, dropped when it is a zero — the shape `Intl` compact gives (`1k`, not `1.0k`),
5071
- // so 1000 and 1000000 do not read as `1.0k` and `1.0m`.
5072
- const shown = scaled < 100 ? scaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(scaled));
5073
- // ROUNDING CAN REACH THE NEXT UNIT. 999999 is 999.999k, which rounds to `1000k`, and `1000k`
5074
- // is `1m` — showing the first makes the reader convert a unit themselves. Step up once when the
5075
- // rounded value has hit the next threshold; `units` is ordered largest-first, so `i - 1` is it.
5076
- if (Number(shown) >= 1000 && i > 0) {
5077
- const up = units[i - 1];
5078
- const upScaled = v / up.at;
5079
- const upShown = upScaled < 100 ? upScaled.toFixed(1).replace(/\.0$/, '') : String(Math.round(upScaled));
5080
- return `${upShown}${up.suffix} tokens`;
5081
- }
5082
- return `${shown}${u.suffix} tokens`;
5083
- }
5084
- return `${v} tokens`;
5085
- }
5086
- // The elapsed-and-tokens tail WITHOUT brackets, e.g. `6m 44s | 9.1k tokens`.
5087
- //
5088
- // The brackets belong to the caller, because the two rows want them in different places:
5089
- // Accelerating... [6m 44s | 9.1k tokens] the live row wraps the TAIL
5090
- // [turn took 6m 44s | 9.1k tokens] the settled row wraps word AND tail
5091
- // Putting them here produced `[turn took [6m 44s | …]` on the settled row.
5092
- //
5093
- // The token count is always present, `0 tokens` included: an absent counter and a zero one
5094
- // look identical to the user, and appearing partway through a turn makes the row jump width
5095
- // under the eye.
5096
- /**
5097
- * A prose setting as one short cell, for a list that has room for about forty characters.
5098
- *
5099
- * A truncated paragraph fills that space with text nobody can read and pushes the label out of
5100
- * line with every other row; the size is the fact worth showing at a glance.
5101
- */
5102
- function proseSummary(value) {
5103
- const text = String(value == null ? '' : value);
5104
- if (!text.trim()) return '(unset)';
5105
- if (text === '(unset)') return text; // already a placeholder, not prose
5106
- const lines = text.split(/\r?\n/);
5107
- const first = lines[0].trim();
5108
- // One short line with no newline fits as-is — that IS the whole value.
5109
- if (lines.length === 1 && first.length <= 32) return first;
5110
- return `${lines.length} line${lines.length === 1 ? '' : 's'}, ${text.length} chars`;
5111
- }
5112
-
5113
- /**
5114
- * The `[2s | ↓40]` tail shown at the end of the Working row.
5115
- *
5116
- * The arrow says which direction the count is: tokens this turn has RECEIVED, as opposed to the context
5117
- * gauge, which also counts what has been sent.
5118
- */
5119
- function elapsedTail(ms, tokens) {
5120
- // The token count is shown FROM THE FIRST FRAME, with a downward arrow to say what it is: what the
5121
- // turn has received. It used to be hidden for thirty seconds, on the theory that a small number is
5122
- // noise on a short turn — but the row is the only place that number exists, and a count that appears
5123
- // partway through reads as something that just started rather than as a running total.
5124
- return `${fmtDuration(ms)} | ↓ ${fmtTokensShort(tokens)}`;
5125
- }
5126
-
5127
- /**
5128
- * Has the turn gone quiet, and how much should that show?
5129
- *
5130
- * A turn that produces no tokens for a few seconds is either thinking, waiting on a tool, or stuck — and
5131
- * from outside those look identical. The one case that matters is the last: a request that hangs leaves
5132
- * the row cheerfully spinning forever with no way to tell it apart from a long answer.
5133
- *
5134
- * Mirrors Claude Code's `useStalledAnimation`: AFTER 3s with no new output, fade toward the warning colour
5135
- * over another 2s, and NEVER while a tool is running — a `npm install` that takes a minute is working, not
5136
- * stalled, and flashing red at it would train the user to ignore the signal.
5137
- *
5138
- * Returns 0 while healthy and 1 at full stall, so the caller can interpolate rather than switch abruptly.
5139
- */
5140
- const STALL_AFTER_MS = 3000;
5141
- const STALL_FADE_MS = 2000;
5142
-
5143
- function stallIntensity({ sinceLastTokenMs, hasActiveTools }) {
5144
- if (hasActiveTools) return 0;
5145
- const quiet = Number(sinceLastTokenMs) || 0;
5146
- if (quiet <= STALL_AFTER_MS) return 0;
5147
- return Math.min((quiet - STALL_AFTER_MS) / STALL_FADE_MS, 1);
5148
- }
5149
-
5150
- // Left/right justify: left text, then padding, then right text flush to `w`.
5151
- // ANSI codes are ignored for width so colored segments still align exactly.
5152
- // When both don't fit, the LEFT is preserved and the RIGHT (tip) is truncated.
5153
- function justify(left, right, w) {
5154
- const lw = visualCol(left);
5155
- const rw = visualCol(right);
5156
- if (left && right) {
5157
- if (lw + rw + 1 <= w) return left + ' '.repeat(w - lw - rw) + right;
5158
- const room = w - lw - 1;
5159
- if (room > 0) return left + ' ' + fitAnsi(right, room);
5160
- return fitAnsi(left, w);
5161
- }
5162
- if (!left) return ' '.repeat(Math.max(0, w - rw)) + right;
5163
- if (!right) return left + ' '.repeat(Math.max(0, w - lw));
5164
- return fitAnsi(left, w);
5165
- }
2588
+ // (Number, money and time formatting live in src/format.js.)
5166
2589
 
5167
2590
  // Height of the composer box (top border + content rows + bottom border).
5168
2591
  export function composerHeight(state, cols) {
@@ -5431,23 +2854,25 @@ function applySelectionToRow(lines, idx, sel, w) {
5431
2854
  function highlightAnsiRange(row, c0, c1, w) {
5432
2855
  const s = String(row);
5433
2856
  const cells = parseCells(s);
5434
- // The SGR for the background each column was drawn with, or '' when the row has none there.
2857
+ // The background in force BEFORE the selection, so ending it can put that back instead of ESC[49m (which
2858
+ // means "the terminal default" and shows through on any row painted on a surface of its own).
5435
2859
  const ownBg = cells.map((_, c) => {
5436
2860
  const rgb = cellBg(cells, c);
5437
2861
  return rgb ? `\x1b[48;2;${rgb[0]};${rgb[1]};${rgb[2]}m` : '';
5438
2862
  });
5439
- // The theme's selection colour, read from the SGR rather than hardcoded: a light theme has a pale one.
5440
2863
  const m = /48;2;(\d+);(\d+);(\d+)/.exec(C.selBg);
5441
2864
  const selRgb = m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
5442
2865
  // The SELECTION WINS. A hint of the row's own wash stays in the mix so a selected deletion still reads as a
5443
2866
  // deletion, but nine parts selection to one part row — an earlier three-parts-row blend left the diff colour
5444
2867
  // dominating and the selected range looked like an unselected diff with a tint.
5445
- const selectedBg = (col) => {
5446
- const rgb = cellBg(cells, col);
5447
- if (!rgb || !selRgb) return C.selBg;
5448
- const mix = (a, b) => Math.round(a * 0.9 + b * 0.1);
5449
- return `\x1b[48;2;${mix(selRgb[0], rgb[0])};${mix(selRgb[1], rgb[1])};${mix(selRgb[2], rgb[2])}m`;
5450
- };
2868
+ // ONE COLOUR. A blend with the row's own wash kept a selected deletion looking like a deletion, but on a diff
2869
+ // it made the selected run indistinguishable from the added rows beside it — a selection is a state and has to
2870
+ // be unmistakable.
2871
+ const selectedBg = () => C.selBg;
2872
+ // One past the last cell holding anything but a space. The frame pads every row to full width for the page
2873
+ // colour, and those padding cells are not content — a drag reaching into them must not paint them as selected.
2874
+ let contentEnd = 0;
2875
+ for (let k = 0; k < cells.length; k++) if (cells[k].ch !== ' ' && cells[k].ch !== '') contentEnd = k + 1;
5451
2876
  const lo = Math.max(c0, 1);
5452
2877
  let out = '';
5453
2878
  let col = 0;
@@ -5465,8 +2890,10 @@ function highlightAnsiRange(row, c0, c1, w) {
5465
2890
  // after each `ESC[0m`. Those SGRs arrive here as ordinary escapes, not resets, so leaving them untouched
5466
2891
  // let the diff colour overwrite the selection mid-run. Inside the selection, ANY background escape that
5467
2892
  // follows is replaced by the selected one; outside it, only a reset needs the row's own wash restored.
5468
- const isBg = /^\x1b\[48;/.test(esc[0]);
5469
- if (inSel && (isBg || esc[0] === '\x1b[0m' || esc[0] === '\x1b[m')) out += selectedBg(col);
2893
+ // A background SGR, a full reset, or a background-only reset (`ESC[49m`) all destroy the selection's
2894
+ // fill; each has to be answered with the selected colour again.
2895
+ const isBg = /^\x1b\[48;|^\x1b\[49m$/.test(esc[0]);
2896
+ if (inSel && (isBg || esc[0] === '\x1b[0m' || esc[0] === '\x1b[m')) out += selectedBg();
5470
2897
  else if (!inSel && (esc[0] === '\x1b[0m' || esc[0] === '\x1b[m')) out += ownBg[col] || '';
5471
2898
  i += esc[0].length;
5472
2899
  continue;
@@ -5476,13 +2903,17 @@ function highlightAnsiRange(row, c0, c1, w) {
5476
2903
  const cp = s.codePointAt(i);
5477
2904
  const ch = String.fromCodePoint(cp);
5478
2905
  const cw = visualWidth(ch);
5479
- const want = col >= lo && col < c1;
2906
+ const want = col >= lo && col < c1 && col < contentEnd;
5480
2907
 
5481
- if (want && !inSel) { out += selectedBg(col); inSel = true; }
2908
+ if (want && !inSel) { out += selectedBg(); inSel = true; }
5482
2909
  else if (!want && inSel) {
5483
- // RESTORE the row's own background, not ESC[49m: a diff row is red or green all the way to the right edge,
5484
- // and clearing the background there left a strip of page colour in the middle of the wash.
5485
- out += ownBg[col] || C.bgReset;
2910
+ // FALL BACK TO THE PAGE COLOUR, NOT TO ESC[49m.
2911
+ //
2912
+ // `ownBg[col]` is the fill that cell carried, and for a plain sentence it is EMPTY — the page colour is applied
2913
+ // later, by `composeFrame`. The old `|| C.bgReset` therefore fired on every ordinary row, and `ESC[49m` hands
2914
+ // the background back to the TERMINAL, so everything after the selection on that line showed the terminal's
2915
+ // own colour instead of the theme's page.
2916
+ out += ownBg[col] || C.bg;
5486
2917
  inSel = false;
5487
2918
  }
5488
2919
 
@@ -7501,7 +4932,9 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
7501
4932
  // A SEPARATOR BETWEEN THE TRANSCRIPT AND THE INPUT. With the border gone, the last line of the conversation sat
7502
4933
  // directly on top of the composer, and a paragraph against a grey block reads as one crowded mass. One faint
7503
4934
  // rule says "the conversation ends here" without drawing a frame.
7504
- lines.push(col('─'.repeat(w), C.border));
4935
+ // In a mode that sends the line somewhere other than the model, the rules carry the mode colour.
4936
+ const ruleCol = state.stdinMode ? C.orange : (state.inputMode === 'bash' ? C.shellMode : C.border);
4937
+ lines.push(col('─'.repeat(w), ruleCol));
7505
4938
  composerFirstRow = lines.length;
7506
4939
  // THE COMPOSER SPANS THE FULL WIDTH. It used to keep the transcript's 1-column left margin so its walls
7507
4940
  // lined up with a sent user message's box; with no walls there is nothing to line up, and a filled surface
@@ -7534,7 +4967,9 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
7534
4967
  : textPart;
7535
4968
  // The `!` (shell mode) prefix is BOLD: it is a mode marker, not punctuation, and it should out-weigh
7536
4969
  // the `>` prompt glyph at a glance.
7537
- const preCol = state.inputMode === 'bash' ? (C.shellMode + C.bold) : C.cyan;
4970
+ const preCol = state.stdinMode ? (C.orange + C.bold)
4971
+ : state.inputMode === 'bash' ? (C.shellMode + C.bold)
4972
+ : C.cyan;
7538
4973
  rowAnsi = ' ' + col(pre, preCol) + C.white
7539
4974
  + fitAnsi(highlighted, Math.max(1, textW - visualCol(pre))) + ' ';
7540
4975
  } else {
@@ -7555,7 +4990,7 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
7555
4990
  }
7556
4991
  // AND THE RULE UNDER IT, mirroring the one above: the input is bounded by two faint rules, so it reads as a
7557
4992
  // field between the conversation and the status line rather than as a block touching both.
7558
- lines.push(col('─'.repeat(w), C.border));
4993
+ lines.push(col('─'.repeat(w), ruleCol));
7559
4994
  }
7560
4995
 
7561
4996
  // NO LEFT MARGIN: the menu's rule sits in column 0, aligned with the composer's own edge, instead of one
@@ -7970,7 +5405,7 @@ const queueH = takeover ? 0 : queuePanelHeight(state);
7970
5405
  let padded = lines.map((l) => {
7971
5406
  if (isImageRow(l)) return l; // a bitmap payload is not text; a trailing background would corrupt it
7972
5407
  const base = fitAnsi(l, w).replace(/\x1b\[0m/g, `\x1b[0m${C.bg}`);
7973
- return C.bg + base + C.bgReset;
5408
+ return C.bg + base;
7974
5409
  });
7975
5410
  // Mixin seam: beforeRender - plugins may rewrite the painted lines. Runs before the
7976
5411
  // ANSI string is built so the change actually reaches the screen.
@@ -15479,6 +12914,13 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
15479
12914
  // tool, not the tool's own duration.
15480
12915
  state.hasActiveTools = false;
15481
12916
  state.lastTokenAt = Date.now();
12917
+ // The command stdin mode pointed at has finished. Staying in it would swallow the next typed line into a
12918
+ // dead pipe.
12919
+ if (state.stdinMode) {
12920
+ state.stdinMode = false;
12921
+ for (const m of state.chat || []) if (m._stdinMode) m._stdinMode = false;
12922
+ viewCur.note('Command finished — input goes to the model again');
12923
+ }
15482
12924
  const entry = [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending && m.id === e.id)
15483
12925
  || [...state.chat].reverse().find((m) => m.role === 'tool' && m.pending && m.toolName === e.name);
15484
12926
  // A failed run must be visible on the TOOL line too: the status bullet
@@ -15486,6 +12928,9 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
15486
12928
  const failedRun = isFailureResult(e.content, e.name);
15487
12929
  if (entry) {
15488
12930
  entry.pending = false; entry.id = undefined; entry.failed = failedRun;
12931
+ // HOW LONG THE CALL TOOK, stamped where it becomes knowable. The pair `startAt`/`endedAt` is what the tool
12932
+ // line renders as `(10m 1s)` next to the name; a resumed session carries both back.
12933
+ entry.endedAt = Date.now();
15489
12934
  // The AUTHORITATIVE diff comes from the tool itself (`editDiff`): it
15490
12935
  // knows the text it really replaced, so this is the only source that
15491
12936
  // covers line-range edits. Fall back to the provisional diff built
@@ -18500,7 +15945,7 @@ export async function startTUI(opts) {
18500
15945
  // runs at submit either way, so the text that is SENT is identical.
18501
15946
  if (t && t.ctrl) {
18502
15947
  // `idx` is already the input index, so the helper does not convert again — see its comment.
18503
- const expanded = expandPasteMarkerAt(state, idx);
15948
+ const expanded = expandPasteMarkerAt(state, idx, () => refreshMenu(state));
18504
15949
  if (expanded) { renderFrame(); return true; }
18505
15950
  }
18506
15951
 
@@ -20000,6 +17445,25 @@ export async function startTUI(opts) {
20000
17445
  return;
20001
17446
  }
20002
17447
 
17448
+ if (t.key === 'c-g') {
17449
+ // ANSWER A PROMPT. A foreground command reads from a pipe now; this points the composer at it. A TOGGLE,
17450
+ // because the composer has to go back to the model when the answer is done.
17451
+ const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
17452
+ if (!fg || typeof fg.write !== 'function') {
17453
+ notice('Nothing is waiting for input — no command is running in the foreground', 'error');
17454
+ renderFrame();
17455
+ return;
17456
+ }
17457
+ state.stdinMode = state.stdinMode ? false : true;
17458
+ // The renderer is module-level and cannot read `state`, so the mode rides on the RUNNING Bash message.
17459
+ for (const m of state.chat || []) if (m.role === 'tool' && m.toolName === 'Bash' && m.pending) m._stdinMode = state.stdinMode;
17460
+ notice(state.stdinMode
17461
+ ? 'Input goes to the running command (Ctrl+G to stop)'
17462
+ : 'Input goes back to the model', 'info');
17463
+ renderFrame();
17464
+ return;
17465
+ }
17466
+
20003
17467
  if (t.key === 'c-s' && !state.editor) {
20004
17468
  steerAll();
20005
17469
  return;
@@ -21139,6 +18603,24 @@ function wheelStep(state, family) {
21139
18603
  // Shell passthrough. The MODE is authoritative (the `!` never entered the
21140
18604
  // buffer); a leading `!` in the text is still honoured so a pasted line like
21141
18605
  // `!git status` behaves the same as typing it.
18606
+ // STDIN MODE WRITES TO THE COMMAND. Checked first: a line typed at a prompt belongs to that prompt even if
18607
+ // it looks like a slash command.
18608
+ if (state.stdinMode) {
18609
+ const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
18610
+ if (fg && typeof fg.write === 'function' && fg.write(text + '\n')) {
18611
+ // Not echoed: the command's own output is the record of what it received.
18612
+ state.input = '';
18613
+ state.caret = 0;
18614
+ renderFrame();
18615
+ return;
18616
+ }
18617
+ // The command is gone; the write reported failure, so the line was NOT delivered.
18618
+ state.stdinMode = false;
18619
+ for (const m of state.chat || []) if (m._stdinMode) m._stdinMode = false;
18620
+ notice('That command has finished — input goes to the model again', 'error');
18621
+ renderFrame();
18622
+ return;
18623
+ }
21142
18624
  if (state.inputMode === 'bash' || text.startsWith('!')) {
21143
18625
  const cmd = text.replace(/^!+/, '').trim();
21144
18626
  state.inputMode = 'prompt'; // one command per activation, like kimi
@@ -21370,6 +18852,27 @@ function wheelStep(state, family) {
21370
18852
  if (!c) throw new Error('empty command');
21371
18853
  await runShellCommand(c);
21372
18854
  };
18855
+ // ANSWER A RUNNING COMMAND FROM THE BROWSER.
18856
+ //
18857
+ // The terminal has Ctrl+G for this; the web UI had no equivalent, so a command that prompted was simply stuck
18858
+ // for anyone watching in a browser. Both go through the SAME foreground hook, so the two front ends cannot
18859
+ // disagree about which process a line is going to.
18860
+ hub.actions.stdinLine = async (line) => {
18861
+ const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
18862
+ if (!fg || typeof fg.write !== 'function') throw new Error('no command is running in the foreground');
18863
+ if (!fg.write(String(line == null ? '' : line) + '\n')) throw new Error('the command has finished');
18864
+ };
18865
+ // Move the running command to the background. Ctrl+B's equivalent.
18866
+ hub.actions.detach = async () => {
18867
+ const fg = state.agent && state.agent.ctx && state.agent.ctx._foreground;
18868
+ if (!fg || typeof fg.detach !== 'function') throw new Error('nothing to background');
18869
+ const id = fg.detach();
18870
+ if (!id) throw new Error('the command has finished');
18871
+ try { state.agent.ctx._foreground = null; } catch { /* the agent may already be gone */ }
18872
+ notice(`Moved to background: ${id}`, 'info');
18873
+ renderFrame();
18874
+ return id;
18875
+ };
21373
18876
  // The two handshakes the agent blocks on. Resolving these from the browser is
21374
18877
  // what lets a phone answer an approval the terminal is showing.
21375
18878
  hub.actions.approve = async (id, ok) => {