pi-stereo-view 0.1.23 → 0.1.25

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/layout.ts CHANGED
@@ -2,12 +2,13 @@ import { setImmediate } from "node:timers/promises";
2
2
  import type { Theme, ToolInfo } from "@earendil-works/pi-coding-agent";
3
3
  import {
4
4
  Container, HStack, isViewportTUI, mixColors, MouseRegion, rgbColor, ScrollView, Text, truncateToWidth, visibleWidth, VStack,
5
- type Color, type Component, type ScrollViewOptions, type StackChild, type TUI, type TuiMouseEvent,
5
+ type Color, type Component, type RgbColor, type ScrollViewOptions, type StackChild, type TUI, type TuiMouseEvent,
6
6
  } from "@earendil-works/pi-tui";
7
- import { NativeDocument, type Pane } from "./native.ts";
7
+ import { NativeDocument, type DocumentTurns, type Pane } from "./native.ts";
8
+ import { parseHex, turnColor, pointerMotionAvailable, type TurnMix } from "./turns.ts";
8
9
  import { NativeContentIndex } from "./content.ts";
9
10
  import { NestedCalls } from "./nested-calls.ts";
10
- import type { Preferences } from "./preferences.ts";
11
+ import type { TurnMarkSetting, Preferences } from "./preferences.ts";
11
12
  import type { TranscriptTimestamps } from "./timestamps.ts";
12
13
  import { PANEL_SEARCH_ROWS, PanelSearch, PanelSearchShortcut, type SearchHit } from "./search.ts";
13
14
  import { SplitSurface } from "./surface.ts";
@@ -239,6 +240,14 @@ export class TranscriptLayout {
239
240
  private automaticHeight = MIN_ROWS;
240
241
  private readonly rejectedRoots = new WeakSet<Component>();
241
242
  private rebuild = (): void => {};
243
+ private index?: NativeContentIndex;
244
+ /** The turn under the pointer; a pointer move collects the turn its document reports. */
245
+ private hoverAct?: number;
246
+ private moving?: { turn: number };
247
+ /** The terminal's reported background, which turn colors are mixed into. */
248
+ private terminalBackground?: RgbColor;
249
+ /** Set by `markTerminalStarted()`; terminal queries wait for it. */
250
+ private terminalStarted = false;
242
251
 
243
252
  constructor(
244
253
  readonly preferences: Preferences,
@@ -369,15 +378,33 @@ export class TranscriptLayout {
369
378
  const showTimestamps = (): boolean => this.preferences.showTimestamps;
370
379
  const showCopyButtons = (): boolean => this.preferences.showCopyButtons;
371
380
  const index = new NativeContentIndex(document, this.nested, () => this.preferences.nestedTree);
381
+ this.index = index;
382
+ // With turns off, every turn setting keeps its value but nothing marks, highlights or jumps.
383
+ const on = (): boolean => this.preferences.turns;
384
+ const turns: DocumentTurns = {
385
+ clock: () => on() && this.preferences.turnClock,
386
+ stripe: () => on() ? this.preferences.turnStripe : "off",
387
+ background: () => on() && this.preferences.turnBackground,
388
+ separator: () => on() && this.preferences.turnSeparator,
389
+ mix: () => this.turnMix(),
390
+ color: (turn, layers) => turnColor(this.theme(), turn, this.terminalBackground, this.turnMix(), layers),
391
+ hovered: () => this.hoverEnabled() ? this.hoverAct : undefined,
392
+ hover: turn => { if (this.moving) this.moving.turn = turn; },
393
+ goTo: () => on() ? this.preferences.goTo : "off",
394
+ jump: (from, source) => {
395
+ void this.goTo(from, source).catch(error => this.warn("Could not open the other panel: " + String(error)));
396
+ },
397
+ };
372
398
  const activityDocument = new NativeDocument(document, "activity", this.timestamps, this.theme, timestampGutter, showTimestamps,
373
399
  () => this.activate("activity"), false, index, this.copy, showCopyButtons,
374
400
  () => ({ compact: this.preferences.compactTools, group: this.preferences.groupTools }), this.getTools,
375
401
  () => { if (this.activity) this.activity.scrollTo(this.activity.scrollTop, { disableFollow: true }); }, () => this.preferences.buttonStyle, {
376
402
  enabled: () => this.preferences.streamTools, delay: () => this.preferences.streamDelay * 1000,
377
403
  changed: () => this.host?.requestRender(),
378
- });
404
+ }, turns);
379
405
  const chatDocument = new NativeDocument(document, "chat", this.timestamps, this.theme, timestampGutter, showTimestamps,
380
- () => this.activate("chat"), false, index, this.copy, showCopyButtons, undefined, undefined, undefined, () => this.preferences.buttonStyle);
406
+ () => this.activate("chat"), false, index, this.copy, showCopyButtons, undefined, undefined, undefined, () => this.preferences.buttonStyle,
407
+ undefined, turns);
381
408
  this.documents = { activity: activityDocument, chat: chatDocument };
382
409
  this.disposeDocuments = () => {
383
410
  activityDocument.dispose();
@@ -628,6 +655,15 @@ export class TranscriptLayout {
628
655
  return pane === "chat" ? this.chat : pane === "activity" ? this.activity : undefined;
629
656
  },
630
657
  failed: error => this.fail(error),
658
+ pointer: {
659
+ start: () => { this.moving = { turn: 0 }; },
660
+ end: () => {
661
+ const turn = this.moving?.turn ?? 0;
662
+ this.moving = undefined;
663
+ this.setHover(turn);
664
+ },
665
+ leave: () => this.setHover(0),
666
+ },
631
667
  });
632
668
  surface.setModels([columns, rows, activityPane, chatPane]);
633
669
  this.surface = surface;
@@ -665,6 +701,66 @@ export class TranscriptLayout {
665
701
  this.mounted = mounted;
666
702
  host.setLayoutRoot(mounted);
667
703
  host.requestRender();
704
+ if (this.terminalStarted) this.queryBackground(host);
705
+ }
706
+
707
+ /**
708
+ * Pi's terminal has started, so terminal queries can be sent. An early layout mounts before that start, and a
709
+ * query sent then answers ahead of Pi's own start queries: Pi takes that answer for its own and misses the
710
+ * terminal's support for program status (OSC 7501) and keyboard protocols.
711
+ */
712
+ markTerminalStarted(): void {
713
+ this.terminalStarted = true;
714
+ if (this.host) this.queryBackground(this.host);
715
+ }
716
+
717
+ /** Ask the terminal for its background once; turn colors use a guess from the theme until it answers. */
718
+ private queryBackground(host: NativeTui): void {
719
+ if (this.terminalBackground || typeof host.queryTerminalColors !== "function") return;
720
+ void host.queryTerminalColors({ timeoutMs: 1000 }).then(colors => {
721
+ if (!colors.background || this.host !== host) return;
722
+ this.terminalBackground = colors.background;
723
+ host.requestRender();
724
+ }, () => {});
725
+ }
726
+
727
+ /** Pi reports pointer motion for hover only outside terminal multiplexers and with its mouse support on. */
728
+ hoverAvailable(): boolean {
729
+ return pointerMotionAvailable(this.host);
730
+ }
731
+
732
+ /** Hover highlighting is on, with turns, and the terminal reports pointer motion. */
733
+ private hoverEnabled(): boolean {
734
+ return this.preferences.turns && this.preferences.turnHover && this.hoverAvailable();
735
+ }
736
+
737
+ /** Highlight another turn; pointer moves within one turn render nothing. */
738
+ private setHover(turn: number): void {
739
+ const next = turn || undefined;
740
+ if (next === this.hoverAct) return;
741
+ this.hoverAct = next;
742
+ if (this.hoverEnabled()) this.host?.requestRender();
743
+ }
744
+
745
+ /** Scroll the other panel to the same point of history as a block, returning from a zoomed panel first. */
746
+ async goTo(from: Pane, source: Component): Promise<void> {
747
+ const target = this.index?.counterpart(source, from);
748
+ if (!target || !this.searchPane()) return;
749
+ const pane: Pane = from === "chat" ? "activity" : "chat";
750
+ if (this.preferences.zoom) {
751
+ this.preferences.zoom = null;
752
+ this.changed(false);
753
+ // The restored panel needs a layout pass for its viewport.
754
+ await setImmediate();
755
+ }
756
+ const document = this.documents?.[pane];
757
+ const view = pane === "chat" ? this.chat : this.activity;
758
+ if (!document || !view || !this.searchPane()) return;
759
+ this.activate(pane);
760
+ const row = document.locate(target);
761
+ if (row === undefined) return;
762
+ view.scrollTo(Math.max(0, row - 1), { disableFollow: true });
763
+ this.host?.requestRender();
668
764
  }
669
765
 
670
766
  private activate(pane: Pane): void {
@@ -798,6 +894,31 @@ export class TranscriptLayout {
798
894
  if (persist) this.save();
799
895
  }
800
896
 
897
+ /** The turn marks' mix strengths, as the palette reads them. */
898
+ private turnMix(): TurnMix {
899
+ const { turnClockMix: clock, turnStripeMix: stripe, turnBackgroundMix: background, turnHoverMix: hover, turnHoverColor } = this.preferences;
900
+ // One hover color for every turn, or each turn's own hue.
901
+ return { clock, stripe, background, hover, hoverColor: parseHex(turnHoverColor) };
902
+ }
903
+
904
+ /** Turn the whole turn feature on or off, or change one of its marks or strengths. */
905
+ setTurnMark<Key extends TurnMarkSetting>(key: Key, value: Preferences[Key]): void {
906
+ this.preferences[key] = value;
907
+ this.changed();
908
+ }
909
+
910
+ /** Highlight the turn under the pointer in both panels. */
911
+ setTurnHover(hover: boolean): void {
912
+ this.preferences.turnHover = hover;
913
+ this.changed();
914
+ }
915
+
916
+ /** Open the other panel from a block's clock, its button, both or neither. */
917
+ setGoTo(goTo: Preferences["goTo"]): void {
918
+ this.preferences.goTo = goTo;
919
+ this.changed();
920
+ }
921
+
801
922
  /** Show or hide clock rows without changing their recorded source times. */
802
923
  setTimestamps(show: boolean): void {
803
924
  this.preferences.showTimestamps = show;
@@ -944,6 +1065,9 @@ export class TranscriptLayout {
944
1065
  this.activity = undefined;
945
1066
  this.chat = undefined;
946
1067
  this.documents = undefined;
1068
+ this.index = undefined;
1069
+ this.hoverAct = undefined;
1070
+ this.moving = undefined;
947
1071
  this.drag = undefined;
948
1072
  this.rebuild = () => {};
949
1073
  }
@@ -0,0 +1,20 @@
1
+ import type { Component, Container, TuiMouseEvent } from "@earendil-works/pi-tui";
2
+
3
+ export type Dispatched = NonNullable<ReturnType<Container["handleMouse"]>>;
4
+
5
+ /** Forward a local event to a real component, preserving Pi's capture and focus targets. */
6
+ export function dispatchMouseEvent(component: Component, event: TuiMouseEvent): Dispatched | undefined {
7
+ const result = component.handleMouse?.(event);
8
+ if (!result) return undefined;
9
+ if ("target" in result) {
10
+ const forwarded = result as Dispatched;
11
+ return forwarded.focus && component.handleInput ? { ...forwarded, focusTarget: component } : forwarded;
12
+ }
13
+ if (!result.handled && !result.capture && !result.focus) return undefined;
14
+ return {
15
+ ...result, handled: true, ...(result.focus ? { focusTarget: component } : {}),
16
+ target: {
17
+ component, originX: event.screenX - event.x, originY: event.screenY - event.y, width: event.width, height: event.height,
18
+ },
19
+ };
20
+ }
package/src/native.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Theme, ToolInfo } from "@earendil-works/pi-coding-agent";
2
- import { Container, Spacer, Text, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
2
+ import { Container, Spacer, stripTerminalSequences, Text, type Color, type Component, type TuiMouseEvent } from "@earendil-works/pi-tui";
3
3
  import { searchText, type SearchEntry, type SearchHit } from "./search.ts";
4
4
  import { highlightSearchRows, searchHitRow, type SearchClock } from "./search-highlight.ts";
5
5
  import { CompactMessage, type TranscriptTimestamps } from "./timestamps.ts";
@@ -11,8 +11,33 @@ import { toolGroups, groupSummary, type ToolGroup } from "./tool-groups.ts";
11
11
  import { ToolIndent } from "./tool-indent.ts";
12
12
  import { NestedTree, type NativeTreeBody } from "./nested-tree.ts";
13
13
  import { pushShellInputs, sameValues } from "./render-cache.ts";
14
+ import { decorateLine, decorateLines, type TurnColor, type TurnLayers, type TurnMix } from "./turns.ts";
15
+ import type { TurnStripe, GoTo } from "./preferences.ts";
16
+ import { dispatchMouseEvent } from "./mouse-dispatch.ts";
14
17
  export type { Pane } from "./content.ts";
15
18
 
19
+ /** Turn marks, hover and Go to, shared by both panels through the split layout. */
20
+ export interface DocumentTurns {
21
+ /** Whether each block's clock gets its turn's background. */
22
+ clock(): boolean;
23
+ stripe(): TurnStripe;
24
+ /** Whether default cells of every block get their turn's background. */
25
+ background(): boolean;
26
+ /** Whether a rule marks the first block of each turn. */
27
+ separator(): boolean;
28
+ /** How strongly each mark mixes its turn's hue into the background. */
29
+ mix(): TurnMix;
30
+ /** The colors of a turn, mixed into the terminal background; none before the first turn. */
31
+ color(turn: number, layers?: TurnLayers): TurnColor | undefined;
32
+ /** The turn under the pointer, while hover highlighting is on and available. */
33
+ hovered(): number | undefined;
34
+ /** Report the turn under the pointer during a pointer move; 0 for a block before the first turn. */
35
+ hover(turn: number): void;
36
+ goTo(): GoTo;
37
+ /** Open the same point of history in the other panel. */
38
+ jump(from: Pane, source: Component): void;
39
+ }
40
+
16
41
  /** Decorate one selected block without changing native text or mouse coordinates. */
17
42
  class SearchHighlight implements Component {
18
43
  private cache?: { lines: string[]; result: string[]; width: number; query: string; hit: SearchHit; revision: number };
@@ -59,11 +84,26 @@ const FULL_TOOLS: ToolDisplay = { compact: false, group: false };
59
84
 
60
85
  /** Time per frame for measuring offscreen entries that are new, changed or stale. */
61
86
  const LAZY_BUDGET_MS = 4;
87
+
88
+ /** A rule in a turn's color in place of the blank row between the previous turn and the turn's first block in a panel. */
89
+ class TurnRule implements Component {
90
+ constructor(private readonly color: () => string | undefined) {}
91
+ render(width: number): string[] {
92
+ const color = this.color();
93
+ const rule = "─".repeat(Math.max(0, width));
94
+ return [color ? color + rule + "\x1b[39m" : rule];
95
+ }
96
+ invalidate(): void {}
97
+ }
98
+
62
99
  /** Offscreen entries checked for native changes per frame, in rotation. */
63
100
  const SWEEP_ENTRIES = 64;
64
101
 
65
102
  /** One projected entry's rows, the components that produced them, and the inputs they depend on. */
66
103
  interface Segment {
104
+ source: Component;
105
+ /** The entry's turn when the segment was last placed, so pointer moves need not read the index. */
106
+ turn: number;
67
107
  components: Component[];
68
108
  heights: number[];
69
109
  lines: string[];
@@ -73,6 +113,8 @@ interface Segment {
73
113
  estimate: boolean;
74
114
  visibleIn: boolean;
75
115
  toolRunIn: boolean;
116
+ /** The turn above the separator rule this segment starts with; undefined without one. */
117
+ ruleIn?: number;
76
118
  visibleOut: boolean;
77
119
  toolRunOut: boolean;
78
120
  /** Cheap fingerprint of native state, compared while the entry stays offscreen. */
@@ -130,7 +172,17 @@ export class NativeDocument extends Container {
130
172
  private searchQuery = "";
131
173
  private highlightRevision = 0;
132
174
  private highlights = new WeakMap<Component, SearchHighlight>();
175
+ /** One separator rule per turn; it reads the turn's current color when it renders. */
176
+ private readonly rules = new Map<number, TurnRule>();
133
177
  private lastWidth = 1;
178
+ /** Width of the last render, including the turn stripe. */
179
+ private lastOuter = 1;
180
+ /** Columns the turn stripe takes before the content. */
181
+ private inset = 0;
182
+ /** Measure every entry on the next render, to locate a block for Go to. */
183
+ private measureAll = false;
184
+ /** Every block's turn, read once at the start of the current render. */
185
+ private renderActs?: ReadonlyMap<Component, number>;
134
186
  private frameActive = false;
135
187
  private frameWidth?: number;
136
188
  private frameLines?: string[];
@@ -171,6 +223,7 @@ export class NativeDocument extends Container {
171
223
  private readonly beforeExpand: () => void = () => {},
172
224
  private readonly buttonStyle: () => "icons" | "text" = () => "text",
173
225
  private readonly streaming?: { enabled(): boolean; delay(): number; changed(): void },
226
+ private readonly turns?: DocumentTurns,
174
227
  ) {
175
228
  super();
176
229
  if (streaming) this.streamer = new ToolStreaming(() => streaming.delay(), () => streaming.changed());
@@ -304,7 +357,7 @@ export class NativeDocument extends Container {
304
357
  searchRow(hit: SearchHit): number | undefined {
305
358
  // Async regex can complete between paints. Measure this document at its last
306
359
  // allocated width instead of assuming requestRender already emitted a frame.
307
- if (this.searchAnchor === hit && this.frameWidth === undefined) this.render(this.lastWidth);
360
+ if (this.searchAnchor === hit && this.frameWidth === undefined) this.render(this.lastOuter);
308
361
  const block = this.positions.get(hit.entry.source);
309
362
  if (!block) return undefined;
310
363
  if (block.excerptRow !== undefined) return block.excerptRow;
@@ -327,8 +380,15 @@ export class NativeDocument extends Container {
327
380
  override handleMouse(event: TuiMouseEvent): ReturnType<Container["handleMouse"]> {
328
381
  if (event.type === "wheel" || (event.type === "press" && event.button === "left")) this.interact();
329
382
  const built = this.built;
330
- if (!built || event.y < 0) return undefined;
331
- // Find the entry under the pointer, then route like a container of that entry's components.
383
+ if (!built || event.y < 0) {
384
+ if (event.type === "move") this.turns?.hover(0);
385
+ return undefined;
386
+ }
387
+ if (this.inset) {
388
+ if (event.x < this.inset && event.type !== "move") return undefined;
389
+ event = { ...event, x: event.x - this.inset, width: Math.max(0, event.width - this.inset) };
390
+ }
391
+ // Find the painted entry under the pointer without asking Pi to lay it out again.
332
392
  let low = 0;
333
393
  let high = built.order.length - 1;
334
394
  while (low < high) {
@@ -337,13 +397,72 @@ export class NativeDocument extends Container {
337
397
  }
338
398
  const segment = built.order[low];
339
399
  const row = event.y - (built.rows[low] ?? 0);
400
+ if (event.type === "move") {
401
+ // A separator stands between turns, so pointing at it highlights neither.
402
+ const separator = segment?.components[0] instanceof TurnRule && row < segment.heights[0];
403
+ const turn = !segment || row >= segment.lines.length || separator ? 0 : segment.turn;
404
+ this.turns?.hover(turn);
405
+ }
340
406
  if (!segment || segment.estimate || row >= segment.lines.length) return undefined;
341
- const entry = {
342
- children: segment.components,
343
- mouseLayout: { width: event.width, children: segment.components.map((component, index) => ({ component, height: segment.heights[index] })) },
344
- };
345
- return Container.prototype.handleMouse.call(entry, { ...event, y: row, height: segment.lines.length });
407
+ let childY = 0;
408
+ for (let index = 0; index < segment.components.length; index++) {
409
+ const height = segment.heights[index];
410
+ if (row < childY + height) {
411
+ return dispatchMouseEvent(segment.components[index], { ...event, y: row - childY, height });
412
+ }
413
+ childY += height;
414
+ }
415
+ return undefined;
416
+ }
417
+ /**
418
+ * The turn color behind a block's clock, when clock marks are on. Blocks render inside this document's render, so the turns it
419
+ * read are current; reading the index per block would verify the whole history per block outside a frame.
420
+ */
421
+ private clockBackground(source: Component): Color | undefined {
422
+ if (!this.turns?.clock()) return undefined;
423
+ const turn = this.renderActs?.get(source) ?? 0;
424
+ return this.turns.color(turn, this.layers(turn))?.clock;
425
+ }
426
+ /** The layers under a turn's clocks, stripes and rules in this frame: its background, and hover while pointed at. */
427
+ private layers(turn: number): TurnLayers {
428
+ return { background: this.turns?.background() === true, hover: turn > 0 && this.turns?.hovered() === turn };
429
+ }
430
+ /** Decorate a separator's row: it stands between turns, so it takes no background or hover layer of either. */
431
+ private separatorRows(rows: readonly string[], turn: number,
432
+ mark: (marks: TurnColor | undefined, fill: string | undefined) => string): string[] {
433
+ const marks = this.turns?.color(turn);
434
+ return rows.map(row => decorateLine(row, undefined, mark(marks, undefined)));
435
+ }
436
+ private goToClock(): boolean {
437
+ const goTo = this.turns?.goTo();
438
+ return goTo === "clock" || goTo === "both";
346
439
  }
440
+ /** Clicking a compact row's clock opens its point of history in the other panel. */
441
+ private clockJump(source: Component): (() => void) | undefined {
442
+ return this.goToClock() ? () => this.turns?.jump(this.pane, source) : undefined;
443
+ }
444
+
445
+ /**
446
+ * The first row of a block in this panel, measured from every entry. A block hidden in a closed group or shown
447
+ * inside its owner's tree resolves to the nearest shown row above it.
448
+ */
449
+ locate(source: Component): number | undefined {
450
+ if (this.disposed) return undefined;
451
+ this.measureAll = true;
452
+ this.frameWidth = undefined;
453
+ try { this.render(this.lastOuter); } finally { this.measureAll = false; }
454
+ const entries = this.index.entries(this.pane);
455
+ for (let index = entries.findIndex(entry => entry.source === source); index >= 0; index--) {
456
+ const segment = this.segments.get(entries[index].source);
457
+ if (segment?.build !== this.buildId || !segment.lines.length) continue;
458
+ // Start at the block's first visible row, after its separator.
459
+ let row = 0;
460
+ while (row < segment.lines.length - 1 && !stripTerminalSequences(segment.lines[row]).trim()) row++;
461
+ return segment.start + row;
462
+ }
463
+ return undefined;
464
+ }
465
+
347
466
  private toolOpen(source: Component): boolean {
348
467
  return this.openTools.has(source) || this.searchTool === source;
349
468
  }
@@ -359,6 +478,8 @@ export class NativeDocument extends Container {
359
478
  }, this.theme, {
360
479
  clock: () => this.showTimestamps() ? this.timestamps.label(entry.source) : "",
361
480
  gutter: this.timestampGutter,
481
+ clockBackground: () => this.clockBackground(entry.source),
482
+ clockAction: () => this.clockJump(entry.source),
362
483
  expanded: () => this.toolOpen(entry.source),
363
484
  toggle: () => {
364
485
  if (!this.index.contains(entry.source, this.pane)) return;
@@ -387,6 +508,8 @@ export class NativeDocument extends Container {
387
508
  count: () => this.groups.get(source)!.calls.length,
388
509
  clock: () => this.showTimestamps() ? this.timestamps.label(source) : "",
389
510
  gutter: this.timestampGutter,
511
+ clockBackground: () => this.clockBackground(source),
512
+ clockAction: () => this.clockJump(source),
390
513
  expanded: () => this.groupOpen(this.groups.get(source)!),
391
514
  toggle: () => {
392
515
  const current = this.groups.get(source);
@@ -412,6 +535,10 @@ export class NativeDocument extends Container {
412
535
  this.copy ? () => this.copyBlock(component) : undefined, this.showCopy, this.buttonStyle, () => {
413
536
  // Nested panels render inside their owner's segment.
414
537
  this.dirty.add(component).add(entry.owner);
538
+ }, () => this.clockBackground(component), {
539
+ clock: () => this.goToClock(),
540
+ button: () => { const goTo = this.turns?.goTo(); return goTo === "button" || goTo === "both"; },
541
+ go: () => this.turns?.jump(this.pane, component),
415
542
  });
416
543
  this.stamped.set(routed, stamped);
417
544
  }
@@ -504,8 +631,20 @@ export class NativeDocument extends Container {
504
631
  return trees;
505
632
  }
506
633
 
507
- override render(width: number): string[] {
508
- if (this.frameActive && this.frameWidth === width && this.frameLines) return this.frameLines;
634
+ override render(outer: number): string[] {
635
+ if (this.frameActive && this.frameWidth === outer && this.frameLines) return this.frameLines;
636
+ const stripe = this.turns?.stripe() ?? "off";
637
+ const tint = this.turns?.background() === true;
638
+ const separator = this.turns?.separator() === true;
639
+ // The turn stripe takes the first column; native blocks render beside it.
640
+ const inset = stripe !== "off" && outer > 1 ? 1 : 0;
641
+ const width = outer - inset;
642
+ this.inset = inset;
643
+ this.lastOuter = outer;
644
+ const theme = this.theme();
645
+ const hovered = this.turns?.hovered();
646
+ const turns = this.turns ? this.index.turnMap() : undefined;
647
+ this.renderActs = turns;
509
648
  const chat = this.source.children[2] as Container;
510
649
  this.timestamps.prepare(chat.children);
511
650
  this.lastWidth = width;
@@ -528,11 +667,14 @@ export class NativeDocument extends Container {
528
667
  this.searchTool = searched?.owner;
529
668
  const entries = this.index.entries(this.pane);
530
669
  const trees = this.treesFor(entries);
531
- const view = locateMatch ? undefined : this.viewport?.();
670
+ const view = locateMatch || this.measureAll ? undefined : this.viewport?.();
532
671
  // The first frame and search measure every entry; later frames reuse offscreen rows.
533
672
  const virtual = view !== undefined && view.height > 0 && this.built !== undefined;
534
- const presentation = [this.theme(), display.compact, display.group, this.index.nestedTrees(), this.streamActive, this.showTimestamps(),
535
- this.showCopy(), this.buttonStyle(), this.timestampGutter(), this.invalidations];
673
+ const mix = this.turns?.mix();
674
+ const hoverColor = mix?.hoverColor && `${mix.hoverColor.r},${mix.hoverColor.g},${mix.hoverColor.b}`;
675
+ const presentation = [theme, stripe, tint, separator, this.turns?.clock(), mix?.clock, mix?.stripe, mix?.background, mix?.hover, hoverColor,
676
+ display.compact, display.group, this.index.nestedTrees(), this.streamActive, this.showTimestamps(),
677
+ this.showCopy(), this.buttonStyle(), this.turns?.goTo(), this.timestampGutter(), this.invalidations];
536
678
  if (!sameValues(presentation, this.presentation)) {
537
679
  this.presentation = presentation;
538
680
  this.epoch++;
@@ -553,13 +695,24 @@ export class NativeDocument extends Container {
553
695
  const top = virtual && !view.following ? view.top : 0;
554
696
  let shift = 0;
555
697
  let pending = false;
698
+ let lastAct = 0;
556
699
  const order: Segment[] = [];
557
- const renderEntry = (entry: ContentEntry, rowed: boolean, tree: NestedTree | undefined): Segment => {
700
+ // `rule` is the turn above the separator this entry starts with, when it starts one.
701
+ const renderEntry = (entry: ContentEntry, rowed: boolean, tree: NestedTree | undefined, turn: number, rule: number | undefined): Segment => {
558
702
  const component = entry.source;
559
703
  const routed = entry.component;
560
704
  const result: Component[] = [];
561
705
  const visibleIn = visibleBlock;
562
706
  const toolRunIn = toolRun;
707
+ if (rule !== undefined) {
708
+ let turnRule = this.rules.get(turn);
709
+ // The rule stands between turns, outside the layers of either: hover and backgrounds leave it unchanged.
710
+ if (!turnRule) this.rules.set(turn, turnRule = new TurnRule(() => this.turns?.color(turn)?.line));
711
+ result.push(turnRule);
712
+ // The rule takes the place of the blank row that separates blocks, so the block below adds none.
713
+ toolRun = false;
714
+ visibleBlock = false;
715
+ }
563
716
  let clock: SearchClock | undefined;
564
717
  let nativeBody = true;
565
718
  let bodyDepth = 0;
@@ -596,7 +749,8 @@ export class NativeDocument extends Container {
596
749
  visibleBlock = true;
597
750
  } else if (nativeBody && !entry.compact) {
598
751
  toolRun = false;
599
- result.push(...entry.spacing, routed);
752
+ // Pi's own spacing separates this block from the one above; a rule already does.
753
+ result.push(...(rule === undefined ? entry.spacing : []), routed);
600
754
  } else if (nativeBody) {
601
755
  if (!rowed) toolRun = false;
602
756
  const stamped = this.nativeBlock(entry);
@@ -637,8 +791,16 @@ export class NativeDocument extends Container {
637
791
  const heights: number[] = [];
638
792
  // Copy rows: native renderers may reuse and later mutate their row arrays.
639
793
  const lines: string[] = [];
794
+ const color = turn && (inset || tint || hovered === turn) ? this.turns?.color(turn, { background: tint, hover: hovered === turn }) : undefined;
795
+ const background = color?.fill;
796
+ // A line stripe draws on the block's layers; a block stripe is a layer of its own.
797
+ const mark = (marks: TurnColor | undefined, fill: string | undefined): string =>
798
+ !inset ? "" : !marks ? " " : stripe === "line" ? (fill ?? "") + marks.line + "│\x1b[39m" : marks.stripe + " \x1b[49m";
799
+ const prefix = mark(color, background);
640
800
  for (const child of result) {
641
- const childLines = child.render(width);
801
+ const childLines = child instanceof TurnRule && rule !== undefined
802
+ ? this.separatorRows(child.render(width), turn, mark)
803
+ : decorateLines(child.render(width), background, prefix);
642
804
  heights.push(childLines.length);
643
805
  for (const line of childLines) lines.push(line);
644
806
  }
@@ -646,15 +808,15 @@ export class NativeDocument extends Container {
646
808
  this.fingerprint(entry, rowed, tree, print);
647
809
  let segment = this.segments.get(component);
648
810
  if (!segment) {
649
- segment = { components: result, heights, lines, width, epoch: this.epoch, estimate: false, visibleIn, toolRunIn,
650
- visibleOut: visibleBlock, toolRunOut: toolRun, print, start: row, build };
811
+ segment = { source: component, turn, components: result, heights, lines, width, epoch: this.epoch, estimate: false, visibleIn, toolRunIn,
812
+ ruleIn: rule, visibleOut: visibleBlock, toolRunOut: toolRun, print, start: row, build };
651
813
  this.segments.set(component, segment);
652
814
  return segment;
653
815
  }
654
816
  // Keep unchanged arrays, so the document can reuse the rows before the first changed entry.
655
817
  if (segment.estimate || !sameValues(segment.lines, lines)) segment.lines = lines;
656
818
  if (!sameValues(segment.components, result)) segment.components = result;
657
- Object.assign(segment, { heights, width, epoch: this.epoch, estimate: false, visibleIn, toolRunIn,
819
+ Object.assign(segment, { heights, width, epoch: this.epoch, estimate: false, visibleIn, toolRunIn, ruleIn: rule,
658
820
  visibleOut: visibleBlock, toolRunOut: toolRun, print });
659
821
  return segment;
660
822
  };
@@ -664,6 +826,9 @@ export class NativeDocument extends Container {
664
826
  const component = entry.source;
665
827
  const rowed = display.compact && entry.kind === "tool" && !this.live(entry.owner);
666
828
  const tree = trees.get(component);
829
+ const turn = turns?.get(component) ?? 0;
830
+ // A rule marks where a new turn starts in this panel, below other content.
831
+ const rule = separator && turn > 0 && turn !== lastAct && visibleBlock ? lastAct : undefined;
667
832
  let segment = this.segments.get(component);
668
833
  const previous = segment?.build === build - 1 ? { start: segment.start, height: segment.lines.length } : undefined;
669
834
  let render = !virtual;
@@ -675,7 +840,7 @@ export class NativeDocument extends Container {
675
840
  if (hot) render = true;
676
841
  else {
677
842
  const measured = segment !== undefined && !segment.estimate && segment.width === width && segment.epoch === this.epoch &&
678
- segment.visibleIn === visibleBlock && segment.toolRunIn === toolRun;
843
+ segment.visibleIn === visibleBlock && segment.toolRunIn === toolRun && segment.ruleIn === rule;
679
844
  // Offscreen changes are invisible until the entry nears the viewport, where it renders anyway.
680
845
  // Check a rotating slice per frame so heights converge without reading every entry each frame.
681
846
  const swept = this.dirty.delete(component) ||
@@ -692,12 +857,12 @@ export class NativeDocument extends Container {
692
857
  }
693
858
  if (render) {
694
859
  this.dirty.delete(component);
695
- segment = renderEntry(entry, rowed, tree);
860
+ segment = renderEntry(entry, rowed, tree, turn, rule);
696
861
  }
697
862
  else {
698
863
  if (!segment) {
699
- segment = { components: [], heights: [], lines: blankLines(1), width, epoch: -1, estimate: true, visibleIn: visibleBlock,
700
- toolRunIn: toolRun, visibleOut: visibleBlock, toolRunOut: toolRun, print: [], start: row, build };
864
+ segment = { source: component, turn: 0, components: [], heights: [], lines: blankLines(1), width, epoch: -1, estimate: true, visibleIn: visibleBlock,
865
+ toolRunIn: toolRun, ruleIn: undefined, visibleOut: visibleBlock, toolRunOut: toolRun, print: [], start: row, build };
701
866
  this.segments.set(component, segment);
702
867
  } else if (segment.width !== width && !segment.estimate) {
703
868
  // Rows at another width would overflow the panel; keep only the height until measured.
@@ -713,6 +878,8 @@ export class NativeDocument extends Container {
713
878
  if (virtual && !view.following && previous && previous.start + previous.height <= top) shift += segment.lines.length - previous.height;
714
879
  segment.start = row;
715
880
  segment.build = build;
881
+ segment.turn = turn;
882
+ if (segment.lines.length) lastAct = turn;
716
883
  order.push(segment);
717
884
  row += segment.lines.length;
718
885
  }
@@ -721,6 +888,9 @@ export class NativeDocument extends Container {
721
888
  this.segmentsFor = entries;
722
889
  for (const [source, segment] of this.segments) if (segment.build !== build) this.segments.delete(source);
723
890
  for (const source of this.dirty) if (!this.segments.has(source)) this.dirty.delete(source);
891
+ // Separators of turns that left the history (a new session, compaction) are not needed any more.
892
+ const present = new Set(order.map(segment => segment.turn));
893
+ for (const turn of this.rules.keys()) if (!present.has(turn)) this.rules.delete(turn);
724
894
  }
725
895
  if (virtual && !view.following) this.scrollShift += shift;
726
896
  let lines = built.document;
@@ -731,7 +901,7 @@ export class NativeDocument extends Container {
731
901
  children = [...children, new Spacer(1)];
732
902
  }
733
903
  this.children = children;
734
- this.frameWidth = width;
904
+ this.frameWidth = outer;
735
905
  this.frameLines = lines;
736
906
  if (pending) this.scheduleFollowUp();
737
907
  return lines;