A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
add fullscreen touch interactions and clickable links (#2430)
ktb6fb298501c6
diff --git a/packages/coding-agent/.changes/eng-6201-touch-features.md b/packages/coding-agent/.changes/eng-6201-touch-features.mdnew file mode 100644index 0000000000..69c94d8d2f--- /dev/null+++ b/packages/coding-agent/.changes/eng-6201-touch-features.md@@ -0,0 +1 @@+- Made the collapsed summary/header rows clickable in fullscreen chats: tools and IPython cells, agent messages, refinement and compaction/branch summaries, skill and injected-prompt cards, bash and shell blocks (including inside side-question popups), collapsible errors, startup resource sections, and custom messages toggle only the clicked item; Ctrl+O still resets all conversation detail globally.diff --git a/packages/coding-agent/src/modes/interactive/components/agent-message.ts b/packages/coding-agent/src/modes/interactive/components/agent-message.tsindex e171d9ba82..628c3e91a9 100644--- a/packages/coding-agent/src/modes/interactive/components/agent-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/agent-message.ts@@ -62,6 +62,18 @@ export class AgentMessageComponent extends Container {override render(width: number): string[] {const lines = super.render(width);const leadingSpace = this.shouldAddLeadingSpace?.(this.expanded) ?? true;+ this.clickRegions =+ lines.length > 0+ ? [+ {+ line: leadingSpace ? 1 : 0,+ col: 0,+ width,+ height: this.header.render(width).length,+ onClick: () => this.setExpanded(!this.expanded),+ },+ ]+ : [];return leadingSpace ? ["", ...lines] : lines;}diff --git a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts b/packages/coding-agent/src/modes/interactive/components/bash-execution.tsindex 27f2561d62..ad26cb486d 100644--- a/packages/coding-agent/src/modes/interactive/components/bash-execution.ts+++ b/packages/coding-agent/src/modes/interactive/components/bash-execution.ts@@ -1,4 +1,4 @@-import { Container, Loader, Spacer, Text, type TUI } from "@earendil-works/pi-tui";+import { Clickable, Container, Loader, Spacer, Text, type TUI } from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import {DEFAULT_MAX_BYTES,@@ -41,8 +41,9 @@ export class BashExecutionComponent extends Container {this.contentContainer = new Container();this.addChild(this.contentContainer);- const header = new Text(theme.fg(colorKey, `$ ${command}`), 1, 0);- this.contentContainer.addChild(header);+ this.contentContainer.addChild(+ new Clickable(new Text(theme.fg(colorKey, `$ ${command}`), 1, 0), () => this.setExpanded(!this.expanded)),+ );this.loader = new Loader(ui,@@ -127,8 +128,11 @@ export class BashExecutionComponent extends Container {this.contentContainer.clear();- const header = new Text(theme.fg("bashMode", `$ ${this.command}`), 1, 0);- this.contentContainer.addChild(header);+ this.contentContainer.addChild(+ new Clickable(new Text(theme.fg("bashMode", `$ ${this.command}`), 1, 0), () =>+ this.setExpanded(!this.expanded),+ ),+ );if (availableLines.length > 0) {if (this.expanded) {diff --git a/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts b/packages/coding-agent/src/modes/interactive/components/branch-summary-message.tsindex 1aa49bb7a8..301ecc224a 100644--- a/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/branch-summary-message.ts@@ -1,4 +1,4 @@-import { Box, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";+import { Box, Clickable, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";import type { BranchSummaryMessage } from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";import { expandCollapseHint } from "./keybinding-hints.js";@@ -33,7 +33,7 @@ export class BranchSummaryMessageComponent extends Box {this.clear();const label = theme.fg("customMessageLabel", `\x1b[1m[branch]\x1b[22m`);- this.addChild(new Text(label, 0, 0));+ this.addChild(new Clickable(new Text(label, 0, 0), () => this.setExpanded(!this.expanded)));this.addChild(new Spacer(1));if (this.expanded) {@@ -45,10 +45,13 @@ export class BranchSummaryMessageComponent extends Box {);} else {this.addChild(- new Text(- `${theme.fg("customMessageText", "Branch summary")} ${expandCollapseHint("app.tools.expand", false)}`,- 0,- 0,+ new Clickable(+ new Text(+ `${theme.fg("customMessageText", "Branch summary")} ${expandCollapseHint("app.tools.expand", false)}`,+ 0,+ 0,+ ),+ () => this.setExpanded(!this.expanded),),);}diff --git a/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts b/packages/coding-agent/src/modes/interactive/components/collapsible-error.tsindex 247b260e5f..84ab5a4b30 100644--- a/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts+++ b/packages/coding-agent/src/modes/interactive/components/collapsible-error.ts@@ -1,4 +1,10 @@-import { type Component, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";+import {+ type ClickRegion,+ type Component,+ truncateToWidth,+ visibleWidth,+ wrapTextWithAnsi,+} from "@earendil-works/pi-tui";import stripAnsi from "strip-ansi";import { theme } from "../theme/theme.js";import { expandCollapseHint } from "./keybinding-hints.js";@@ -77,6 +83,7 @@ export function shouldCollapseErrorDetails(text: string): boolean {export class CollapsibleErrorComponent implements Component {private expanded: boolean;+ private clickRegions: ClickRegion[] = [];constructor(private readonly options: CollapsibleErrorOptions) {this.expanded = options.expanded ?? false;@@ -90,20 +97,30 @@ export class CollapsibleErrorComponent implements Component {// Render output is derived from constructor options and expansion state.}+ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;+ }+render(width: number): string[] {const text = normalizeErrorDetails(this.options.text);if (!text) {+ this.clickRegions = [];return [];}const collapsible = this.options.forceCollapse ?? shouldCollapseErrorDetails(text);if (!collapsible || this.expanded) {+ this.clickRegions = [{ line: 0, col: 0, width, height: 1, onClick: () => this.setExpanded(!this.expanded) }];return this.renderText(text, width);}const summary = normalizeErrorDetails(this.options.summary ?? summarizeErrorDetails(text));const inlineHint = `${summary} ${expandCollapseHint("app.tools.expand", false)}`;- return this.renderText(inlineHint, width, "error");+ const lines = this.renderText(inlineHint, width, "error");+ this.clickRegions = [+ { line: 0, col: 0, width, height: lines.length, onClick: () => this.setExpanded(!this.expanded) },+ ];+ return lines;}private renderText(text: string, width: number, color: "error" | "muted" = "error"): string[] {diff --git a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.tsindex cdeb3bf9d0..5609493576 100644--- a/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/compaction-summary-message.ts@@ -1,4 +1,4 @@-import { Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";+import { Clickable, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";import type { CompactionSummaryMessage } from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";import { ExpandableEventMessage } from "./expandable-event-message.js";@@ -15,7 +15,11 @@ export class CompactionSummaryMessageComponent extends ExpandableEventMessage {protected updateDisplay(): void {this.clear();- this.addChild(new Text(theme.fg("refinementHeader", "◆ Context compacted"), 1, 0));+ this.addChild(+ new Clickable(new Text(theme.fg("refinementHeader", "◆ Context compacted"), 1, 0), () =>+ this.toggleExpanded(),+ ),+ );const summary = this.message.summary.trim()? this.message.summary: "No summary was recorded for this compaction.";diff --git a/packages/coding-agent/src/modes/interactive/components/custom-editor.ts b/packages/coding-agent/src/modes/interactive/components/custom-editor.tsindex 13e318471a..c682032957 100644--- a/packages/coding-agent/src/modes/interactive/components/custom-editor.ts+++ b/packages/coding-agent/src/modes/interactive/components/custom-editor.ts@@ -140,6 +140,10 @@ export class CustomEditor extends Editor {this.actionHandlers.set(action, handler);}+ protected override getContentLineOffset(): number {+ return this.getHeaderLine?.() !== undefined ? 2 : 0;+ }+override render(width: number): string[] {const commandMatch = COMMAND_TOKEN_PATTERN.exec(this.getLines()[0] ?? "");const isArgumentCommandLine = commandMatch !== null && this.isArgumentCommand(commandMatch[2]!);diff --git a/packages/coding-agent/src/modes/interactive/components/custom-message.ts b/packages/coding-agent/src/modes/interactive/components/custom-message.tsindex a6840c347b..6ca67d8ce2 100644--- a/packages/coding-agent/src/modes/interactive/components/custom-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/custom-message.ts@@ -1,6 +1,6 @@import type { TextContent } from "@earendil-works/pi-ai";import type { Component } from "@earendil-works/pi-tui";-import { Box, Container, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";+import { Box, Clickable, Container, Markdown, type MarkdownTheme, Spacer, Text } from "@earendil-works/pi-tui";import type { MessageRenderer } from "../../../core/extensions/types.js";import type { CustomMessage } from "../../../core/messages.js";import { getMarkdownTheme, theme } from "../theme/theme.js";@@ -66,7 +66,7 @@ export class CustomMessageComponent extends Container {this.box.clear();const label = theme.fg("customMessageLabel", `\x1b[1m[${this.message.customType}]\x1b[22m`);- this.box.addChild(new Text(label, 0, 0));+ this.box.addChild(new Clickable(new Text(label, 0, 0), () => this.setExpanded(!this._expanded)));this.box.addChild(new Spacer(1));let text: string;diff --git a/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts b/packages/coding-agent/src/modes/interactive/components/expandable-event-message.tsindex e632a4eed8..db50bddd8e 100644--- a/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/expandable-event-message.ts@@ -1,4 +1,4 @@-import { type Component, Container, Text, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";+import { Clickable, type Component, Container, Text, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";import { type ThemeColor, theme } from "../theme/theme.js";class EventSummary implements Component {@@ -34,13 +34,17 @@ export abstract class ExpandableEventMessage extends Container {this.updateDisplay();}+ toggleExpanded(): void {+ this.setExpanded(!this.expanded);+ }+override invalidate(): void {super.invalidate();this.updateDisplay();}protected addSummary(summary: string, metadata?: string, color: ThemeColor = "customMessageText"): void {- this.addChild(new EventSummary(summary, this.expanded, color));+ this.addChild(new Clickable(new EventSummary(summary, this.expanded, color), () => this.toggleExpanded()));if (metadata) this.addChild(new Text(theme.fg("dim", metadata), 1, 0));}diff --git a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.tsindex a639f930b3..786153dac7 100644--- a/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/injected-prompt-message.ts@@ -1,5 +1,6 @@import type { AgentMessage } from "@earendil-works/pi-agent-core";import {+ Clickable,Container,Markdown,type MarkdownTheme,@@ -121,7 +122,7 @@ export class InjectedPromptMessageComponent extends Container {return;}this.header.setText(this.headerText());- this.content.addChild(this.header);+ this.content.addChild(new Clickable(this.header, () => this.setExpanded(!this.expanded)));if (this.expanded && this.message.customType !== IPYTHON_STATE_RESTORED_CUSTOM_TYPE) {this.content.addChild(new Markdown(readCustomText(this.message), 1, 0, this.markdownTheme, {diff --git a/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts b/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.tsindex 350df9b0f1..856ff97bdf 100644--- a/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/refinement-outcome-message.ts@@ -1,4 +1,4 @@-import { type Component, Spacer, Text } from "@earendil-works/pi-tui";+import { Clickable, type Component, Spacer, Text } from "@earendil-works/pi-tui";import type { RefinementOutcomeMessage } from "../../../core/messages.js";import type { AppliedRefinementEdit, HarnessEntry } from "../../../core/refinement/refinement.js";import { generateDiffString } from "../../../core/tools/edit-diff.js";@@ -195,7 +195,9 @@ export class RefinementOutcomeMessageComponent extends ExpandableEventMessage {this.addChild(new Spacer(1));const outcome = refinementHeader(this.message);const header = outcome.startsWith("Harness refined ·") ? "Harness refined" : outcome;- this.addChild(new Text(theme.fg("refinementHeader", `◆ ${header}`), 1, 0));+ this.addChild(+ new Clickable(new Text(theme.fg("refinementHeader", `◆ ${header}`), 1, 0), () => this.toggleExpanded()),+ );this.addSummary(summary.trim() || "No summary was recorded for this harness change.",undefined,diff --git a/packages/coding-agent/src/modes/interactive/components/shell-completion.ts b/packages/coding-agent/src/modes/interactive/components/shell-completion.tsindex 69b20dced0..fc47d8b3cb 100644--- a/packages/coding-agent/src/modes/interactive/components/shell-completion.ts+++ b/packages/coding-agent/src/modes/interactive/components/shell-completion.ts@@ -1,4 +1,4 @@-import type { Component } from "@earendil-works/pi-tui";+import type { ClickRegion, Component } from "@earendil-works/pi-tui";import { Text, truncateToWidth } from "@earendil-works/pi-tui";import {ASYNC_BASH_COMPLETION_CUSTOM_TYPE,@@ -112,6 +112,7 @@ export function shellCompletionLabel(completion: ShellCompletion | undefined): sexport class ShellCompletionComponent implements Component {private expanded = false;+ private clickRegions: ClickRegion[] = [];constructor(private readonly message: CustomMessage,private attached = false,@@ -127,8 +128,14 @@ export class ShellCompletionComponent implements Component {return !this.attached || this.expanded;}invalidate(): void {}+ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;+ }render(width: number): string[] {- if (this.attached && !this.expanded) return [];+ if (this.attached && !this.expanded) {+ this.clickRegions = [];+ return [];+ }const completion = readShellCompletion(this.message);const color = completion?.details.exitCode ? "error" : "muted";const label = shellCompletionLabel(completion);@@ -137,6 +144,9 @@ export class ShellCompletionComponent implements Component {: `${completion?.details.exitCode ? "✗" : "✓"} ${label}`;const header = truncateToWidth(theme.fg(color, ` ${heading}`), width, "");const leadingSpace = this.options.shouldAddLeadingSpace?.(this.expanded) ?? this.expanded;+ this.clickRegions = [+ { line: leadingSpace ? 1 : 0, col: 0, width, height: 1, onClick: () => this.setExpanded(!this.expanded) },+ ];if (!this.expanded) return leadingSpace ? ["", header] : [header];const raw = completion? shellCompletionText(completion)diff --git a/packages/coding-agent/src/modes/interactive/components/side-question.ts b/packages/coding-agent/src/modes/interactive/components/side-question.tsindex 8a3689002a..b35f52cf62 100644--- a/packages/coding-agent/src/modes/interactive/components/side-question.ts+++ b/packages/coding-agent/src/modes/interactive/components/side-question.ts@@ -1,4 +1,4 @@-import { Box, type Component, Markdown, Text, visibleWidth } from "@earendil-works/pi-tui";+import { Box, type ClickRegion, type Component, Markdown, Text, visibleWidth } from "@earendil-works/pi-tui";import type { AgentConnectionSideQuestionEvent } from "../../agent-connection/types.js";import { getMarkdownTheme, theme } from "../theme/theme.js";@@ -21,6 +21,7 @@ export class SideQuestionComponent implements Component {private readonly paddingX: number;private readonly entries: (SideQuestionTurnState | SideQuestionBashState)[] = [];private expanded = false;+ private clickRegions: ClickRegion[] = [];constructor(event: AgentConnectionSideQuestionEvent, paddingX = 2) {this.paddingX = Math.max(2, paddingX);@@ -89,9 +90,14 @@ export class SideQuestionComponent implements Component {}}+ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;+ }+render(width: number): string[] {const blank = " ".repeat(Math.max(1, width));const lines: string[] = [];+ const clickRegions: ClickRegion[] = [];const pushSurfaced = (raw: string[]) => {for (const line of raw) {lines.push(this.applySurface(line, width));@@ -101,7 +107,11 @@ export class SideQuestionComponent implements Component {pushSurfaced([blank]);for (const entry of this.entries) {if (entry.kind === "bash") {+ const lineOffset = lines.length;pushSurfaced([...entry.component.render(width), blank]);+ for (const region of entry.component.getClickRegions?.() ?? []) {+ clickRegions.push({ ...region, line: region.line + lineOffset });+ }continue;}if (entry.questionBubble) {@@ -118,6 +128,7 @@ export class SideQuestionComponent implements Component {pushSurfaced([blank, ...this.renderAnswer(entry, width), blank]);}pushSurfaced([...this.renderHint(width), blank]);+ this.clickRegions = clickRegions;return lines;}diff --git a/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts b/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.tsindex fab70367ec..59f442a83c 100644--- a/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts+++ b/packages/coding-agent/src/modes/interactive/components/skill-invocation-message.ts@@ -1,4 +1,4 @@-import { Markdown, type MarkdownTheme, Text } from "@earendil-works/pi-tui";+import { Clickable, Markdown, type MarkdownTheme, Text } from "@earendil-works/pi-tui";import type { ParsedSkillBlock } from "../../../core/skill-blocks.js";import { getMarkdownTheme, theme } from "../theme/theme.js";import { customMessageLabel, ExpandableCustomMessageBox } from "./expandable-custom-message.js";@@ -16,9 +16,10 @@ export class SkillInvocationMessageComponent extends ExpandableCustomMessageBoxprotected updateDisplay(): void {this.clear();+ const toggle = () => this.setExpanded(!this.expanded);if (this.expanded) {- this.addChild(new Text(customMessageLabel("skill"), 0, 0));+ this.addChild(new Clickable(new Text(customMessageLabel("skill"), 0, 0), toggle));const header = `**${this.skillBlock.name}**\n\n`;this.addChild(new Markdown(header + this.skillBlock.content, 0, 0, this.markdownTheme, {@@ -30,7 +31,7 @@ export class SkillInvocationMessageComponent extends ExpandableCustomMessageBox`${customMessageLabel("skill")} ` +theme.fg("customMessageText", this.skillBlock.name) +` ${expandCollapseHint("app.tools.expand", false)}`;- this.addChild(new Text(line, 0, 0));+ this.addChild(new Clickable(new Text(line, 0, 0), toggle));}}}diff --git a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts b/packages/coding-agent/src/modes/interactive/components/tool-execution.tsindex 0620350179..0dc3e2c2b9 100644--- a/packages/coding-agent/src/modes/interactive/components/tool-execution.ts+++ b/packages/coding-agent/src/modes/interactive/components/tool-execution.ts@@ -368,6 +368,7 @@ export class ToolExecutionComponent extends Container {override render(width: number): string[] {if (this.hideComponent) {+ this.clickRegions = [];return [];}// Refresh the animated glyph without rebuilding the whole panel, for as long@@ -376,9 +377,19 @@ export class ToolExecutionComponent extends Container {this.contentPanel.setHeader(this.panelHeader());}const lines = super.render(width);- return this.expanded && this.shouldUseIpythonRenderer() && this.shouldAddLeadingSpace?.()- ? ["", ...lines]- : lines;+ // The header row toggles only this component: panel header line for the+ // default shell, the fixed summary line for self-rendered ipython cells.+ // That ipython shell prepends a blank row, so aggregated child regions+ // shift with it.+ const leadingBlank = this.expanded && this.shouldUseIpythonRenderer() && this.shouldAddLeadingSpace?.() ? 1 : 0;+ this.clickRegions =+ lines.length > 0+ ? [+ ...this.clickRegions.map((region) => ({ ...region, line: region.line + leadingBlank })),+ { line: leadingBlank, col: 0, width, height: 1, onClick: () => this.setExpanded(!this.expanded) },+ ]+ : [];+ return leadingBlank ? ["", ...lines] : lines;}private isStatusAnimating(): boolean {diff --git a/packages/coding-agent/src/modes/interactive/components/tool-panel.ts b/packages/coding-agent/src/modes/interactive/components/tool-panel.tsindex 1a120e8a94..1463c34729 100644--- a/packages/coding-agent/src/modes/interactive/components/tool-panel.ts+++ b/packages/coding-agent/src/modes/interactive/components/tool-panel.ts@@ -1,4 +1,4 @@-import { type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";+import { type ClickRegion, type Component, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";import { theme } from "../theme/theme.js";export const TOOL_PANEL_PADDING_X = 2;@@ -30,6 +30,7 @@ export function toolPanelLine(line: string, width: number): string {export class ToolPanel implements Component {private children: Component[] = [];private header = "";+ private clickRegions: ClickRegion[] = [];private cache?: {width: number;header: string;@@ -50,6 +51,11 @@ export class ToolPanel implements Component {clear(): void {this.children = [];this.cache = undefined;+ this.clickRegions = [];+ }++ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;}invalidate(): void {@@ -61,9 +67,20 @@ export class ToolPanel implements Component {render(width: number): string[] {const childLines: string[] = [];+ const clickRegions: ClickRegion[] = [];for (const child of this.children) {+ const lineOffset = childLines.length;childLines.push(...child.render(toolPanelContentWidth(width)));+ for (const region of child.getClickRegions?.() ?? []) {+ clickRegions.push({+ ...region,+ // Child rows start below the header and separator rows.+ line: region.line + lineOffset + 2,+ col: region.col + TOOL_PANEL_PADDING_X,+ });+ }}+ this.clickRegions = clickRegions;// The background sample detects theme changes that don't go through// invalidate().diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.tsindex d3c70ded7b..b76588bcde 100644--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts@@ -27,6 +27,7 @@ import type {SlashCommand,} from "@earendil-works/pi-tui";import {+ type ClickRegion,CombinedAutocompleteProvider,type Component,Container,@@ -392,6 +393,9 @@ function hasEditDiffsExpansion(obj: unknown): obj is EditDiffsExpandable {}class ExpandableText extends Text implements Expandable {+ private expandedState: boolean;+ private clickRegions: ClickRegion[] = [];+constructor(private readonly getCollapsedText: () => string,private readonly getExpandedText: () => string,@@ -400,11 +404,26 @@ class ExpandableText extends Text implements Expandable {paddingY = 0,) {super(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);+ this.expandedState = expanded;}setExpanded(expanded: boolean): void {+ this.expandedState = expanded;this.setText(expanded ? this.getExpandedText() : this.getCollapsedText());}++ override render(width: number): string[] {+ const lines = super.render(width);+ this.clickRegions =+ lines.length > 0+ ? [{ line: 0, col: 0, width, height: 1, onClick: () => this.setExpanded(!this.expandedState) }]+ : [];+ return lines;+ }++ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;+ }}export function formatSplashCwd(cwd: string): string {diff --git a/packages/coding-agent/test/conversation-click-regions.test.ts b/packages/coding-agent/test/conversation-click-regions.test.tsnew file mode 100644index 0000000000..5290010325--- /dev/null+++ b/packages/coding-agent/test/conversation-click-regions.test.ts@@ -0,0 +1,107 @@+import { type ClickRegion, Container, setKeybindings, type TUI, visibleWidth } from "@earendil-works/pi-tui";+import stripAnsi from "strip-ansi";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { KeybindingsManager } from "../src/core/keybindings.js";+import { createCompactionSummaryMessage } from "../src/core/messages.js";+import { CollapsibleErrorComponent } from "../src/modes/interactive/components/collapsible-error.js";+import { CompactionSummaryMessageComponent } from "../src/modes/interactive/components/compaction-summary-message.js";+import { CustomEditor } from "../src/modes/interactive/components/custom-editor.js";+import { ToolExecutionComponent } from "../src/modes/interactive/components/tool-execution.js";+import { TOOL_PANEL_PADDING_X, ToolPanel } from "../src/modes/interactive/components/tool-panel.js";+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";+import { getEditorTheme, initTheme } from "../src/modes/interactive/theme/theme.js";++const mockTui = { requestRender: vi.fn(), setFocus: vi.fn(), terminal: { rows: 24 } } as unknown as TUI;+function regionFor(lines: string[], regions: ReadonlyArray<ClickRegion>, needle: string): ClickRegion {+ const region = regions.find((region) => stripAnsi(lines[region.line] ?? "").includes(needle));+ expect(region, `region for ${needle}`).toBeDefined();+ return region!;+}+describe("conversation click regions", () => {+ beforeEach(() => {+ initTheme("dark");+ setKeybindings(new KeybindingsManager());+ vi.clearAllMocks();+ });++ test("a summary-row click toggles only that item and Ctrl+O resets all detail globally", () => {+ const tool = new ToolExecutionComponent("read", "call-1", { path: "/tmp/x" }, {}, undefined, mockTui, "/tmp");+ tool.markExecutionStarted();+ tool.setArgsComplete();+ tool.updateResult({+ content: [{ type: "text", text: Array.from({ length: 10 }, (_, i) => `out ${i}`).join("\n") }],+ isError: false,+ });+ const compaction = new CompactionSummaryMessageComponent(+ createCompactionSummaryMessage("Retained the current task.", 100, "2026-09-16"),+ );+ const chat = new Container();+ chat.addChild(tool);+ chat.addChild(compaction);++ const collapsedTool = tool.render(80).join("\n");+ const collapsedCompaction = compaction.render(80).join("\n");+ const lines = chat.render(80);+ const regions = chat.getClickRegions();+ const toolRegion = regionFor(lines, regions, "read");+ const compactionRegion = regionFor(lines, regions, "Retained the current task.");++ toolRegion.onClick({ row: 0, col: 0 });+ expect(tool.render(80).join("\n")).toContain("out 9");+ expect(compaction.render(80).join("\n")).toBe(collapsedCompaction);+ compactionRegion.onClick({ row: 0, col: 0 });+ expect(compaction.render(80).join("\n")).not.toBe(collapsedCompaction);+ const mode = Object.assign(Object.create(InteractiveMode.prototype), {+ chatContainer: chat,+ pendingBashComponents: [],+ toolOutputExpanded: false,+ editDiffsExpanded: false,+ hideThinkingBlock: true,+ ui: { isFullscreen: () => true, requestRender: vi.fn() },+ });+ Reflect.get(InteractiveMode.prototype, "applyChatExpansion").call(mode);+ expect(tool.render(80).join("\n")).toBe(collapsedTool);+ expect(compaction.render(80).join("\n")).toBe(collapsedCompaction);+ });+ test("ToolPanel offsets child regions past its header and separator rows", () => {+ const calls: { row: number; col: number }[] = [];+ const panel = new ToolPanel();+ panel.addChild({+ render: () => ["body"],+ invalidate: () => {},+ getClickRegions: () => [{ line: 0, col: 0, width: 5, height: 1, onClick: (p) => calls.push(p) }],+ });+ expect(panel.render(40)).toHaveLength(3);+ const regions = panel.getClickRegions();+ expect(regions).toHaveLength(1);+ expect(regions[0]!.line).toBe(2);+ expect(regions[0]!.col).toBe(TOOL_PANEL_PADDING_X);+ regions[0]!.onClick({ row: 0, col: 1 });+ expect(calls).toEqual([{ row: 0, col: 1 }]);+ });++ test.each([+ [8, 5],+ [0, 1],+ ])("editor col %i places the cursor at text col %i through header rows and hidden prefixes", (col, textCol) => {+ const editor = new CustomEditor(mockTui, getEditorTheme(), new KeybindingsManager(), { promptPrefix: "> " });+ editor.getHeaderLine = () => "context: /tmp";+ editor.setText("!echo hi");+ const lines = editor.render(40);+ const regions = editor.getClickRegions();+ expect(regions).toHaveLength(1);+ expect(regions[0]!.line).toBe(3);+ expect(lines.length).toBeGreaterThan(regions[0]!.line);+ regions[0]!.onClick({ row: 0, col });+ expect(editor.getCursor()).toEqual({ line: 0, col: textCol });+ expect(mockTui.setFocus).toHaveBeenCalledWith(editor);+ for (const line of lines) expect(visibleWidth(line)).toBeLessThanOrEqual(40);+ });++ test("wrapped collapsed errors expose every summary row", () => {+ const error = new CollapsibleErrorComponent({ text: "first\nsecond", summary: "a summary long enough to wrap" });+ const lines = error.render(12);+ expect(lines.length).toBeGreaterThan(1);+ expect(error.getClickRegions()[0]!.height).toBe(lines.length);+ });+});diff --git a/packages/coding-agent/test/event-row-hierarchy.test.ts b/packages/coding-agent/test/event-row-hierarchy.test.tsindex 91556fef88..43b47d2dad 100644--- a/packages/coding-agent/test/event-row-hierarchy.test.ts+++ b/packages/coding-agent/test/event-row-hierarchy.test.ts@@ -61,8 +61,9 @@ describe("conversation event row hierarchy", () => {const component = new AgentMessageComponent(message);component.setExpanded(true);- const raw = component.render(100).join("\n");+ const raw = component.render(30).join("\n");+ expect(component.getClickRegions()[0]?.height).toBeGreaterThan(1);expect(raw).toContain(theme.fg("muted", "Agent message received"));expect(raw).toContain(theme.fg("dim", "from parent Planner"));expect(raw).toContain(theme.fg("customMessageText", "Review shard seven."));diff --git a/packages/tui/.changes/eng-6201-touch-features.md b/packages/tui/.changes/eng-6201-touch-features.mdnew file mode 100644index 0000000000..0bcf24a293--- /dev/null+++ b/packages/tui/.changes/eng-6201-touch-features.md@@ -0,0 +1,3 @@+- Added render-time click regions to the TUI: components expose them after render, containers aggregate them, and the fullscreen viewport projects them through the pinned header, scrolling transcript, clipped dock, and overlays (painted overlay pixels block click-through, and regions clipped at a viewport edge stay clickable on their visible rows). A clean unmodified left press/release pair dispatches the click; drag selection, shift/alt/ctrl clicks, and OSC-8 hyperlinks keep precedence, and fullscreen mouse stays opt-in.+- Editor clicks now focus the editor and place the cursor from the authoritative rendered layout, handling wrapped lines, editor scroll, prompt and padding offsets, the CustomEditor header row, hidden `!`/`!!` prefixes, wide graphemes, and atomic paste/image markers.+- Made Markdown link labels clickable in fullscreen while retaining visible URL fallbacks for terminals without native hyperlink support.diff --git a/packages/tui/src/click-regions.ts b/packages/tui/src/click-regions.tsnew file mode 100644index 0000000000..e83fad02b3--- /dev/null+++ b/packages/tui/src/click-regions.ts@@ -0,0 +1,26 @@+/**+ * Click regions: components record them during render() in their own+ * render-output coordinates; containers aggregate them with line offsets+ * and the fullscreen viewport projects them onto screen rows.+ */++/** Position of a click relative to the clicked region's top-left cell. */+export interface ClickPosition {+ /** Zero-based row within the region. */+ row: number;+ /** Zero-based column within the region. */+ col: number;+}++/** A rectangular clickable area produced by a component render. */+export interface ClickRegion {+ /** Zero-based line of the region's top row within the component's rendered output. */+ line: number;+ /** Zero-based visible column of the region's left edge. */+ col: number;+ /** Region width in visible columns. */+ width: number;+ /** Region height in rows. */+ height: number;+ onClick: (position: ClickPosition) => void;+}diff --git a/packages/tui/src/components/box.ts b/packages/tui/src/components/box.tsindex 7badbcd657..0cfefd09c9 100644--- a/packages/tui/src/components/box.ts+++ b/packages/tui/src/components/box.ts@@ -1,3 +1,4 @@+import type { ClickRegion } from "../click-regions.js";import type { TableCellSelectionRegion } from "../selection-metadata.js";import type { Component } from "../tui.js";import { applyBackgroundToLine, visibleWidth } from "../utils.js";@@ -10,6 +11,10 @@ type RenderCache = {selectionRegions: TableCellSelectionRegion[];};+type ClickCache = {+ clickRegions: ClickRegion[];+};+/*** Box component - a container that applies padding and background to all children*/@@ -20,6 +25,7 @@ export class Box implements Component {private bgFn?: (text: string) => string;private cache?: RenderCache;+ private clickCache?: ClickCache;constructor(paddingX = 1, paddingY = 1, bgFn?: (text: string) => string) {this.paddingX = paddingX;@@ -52,6 +58,7 @@ export class Box implements Component {private invalidateCache(): void {this.cache = undefined;+ this.clickCache = undefined;}private matchCache(width: number, childLines: string[], bgSample: string | undefined): boolean {@@ -75,6 +82,7 @@ export class Box implements Component {render(width: number): string[] {if (this.children.length === 0) {this.cache = undefined;+ this.clickCache = { clickRegions: [] };return [];}@@ -83,6 +91,7 @@ export class Box implements Component {const childLines: string[] = [];const selectionRegions: TableCellSelectionRegion[] = [];+ const clickRegions: ClickRegion[] = [];for (const child of this.children) {const lineOffset = childLines.length;const lines = child.render(contentWidth);@@ -97,6 +106,13 @@ export class Box implements Component {tableRight: region.tableRight + this.paddingX,});}+ for (const region of child.getClickRegions?.() ?? []) {+ clickRegions.push({+ ...region,+ line: region.line + lineOffset + this.paddingY,+ col: region.col + this.paddingX,+ });+ }for (const line of lines) {childLines.push(leftPad + line);}@@ -104,8 +120,10 @@ export class Box implements Component {if (childLines.length === 0) {this.cache = undefined;+ this.clickCache = { clickRegions: [] };return [];}+ this.clickCache = { clickRegions };const bgSample = this.bgFn ? this.bgFn("test") : undefined;@@ -137,6 +155,10 @@ export class Box implements Component {return this.cache?.selectionRegions ?? [];}+ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickCache?.clickRegions ?? [];+ }+private applyBg(line: string, width: number): string {const visLen = visibleWidth(line);const padNeeded = Math.max(0, width - visLen);diff --git a/packages/tui/src/components/clickable.ts b/packages/tui/src/components/clickable.tsnew file mode 100644index 0000000000..d2cefda6d7--- /dev/null+++ b/packages/tui/src/components/clickable.ts@@ -0,0 +1,28 @@+import type { ClickPosition, ClickRegion } from "../click-regions.js";+import type { Component } from "../tui.js";++/**+ * Wraps a component and turns its rendered rows into a single click region.+ */+export class Clickable implements Component {+ private regions: ClickRegion[] = [];++ constructor(+ private readonly child: Component,+ private readonly onClick: (position: ClickPosition) => void,+ ) {}++ invalidate(): void {+ this.child.invalidate?.();+ }++ render(width: number): string[] {+ const lines = this.child.render(width);+ this.regions = lines.length > 0 ? [{ line: 0, col: 0, width, height: lines.length, onClick: this.onClick }] : [];+ return lines;+ }++ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.regions;+ }+}diff --git a/packages/tui/src/components/editor.ts b/packages/tui/src/components/editor.tsindex 01910d7a68..d3e447783e 100644--- a/packages/tui/src/components/editor.ts+++ b/packages/tui/src/components/editor.ts@@ -1,4 +1,5 @@import type { AutocompleteProvider, AutocompleteSuggestions } from "../autocomplete.js";+import type { ClickPosition, ClickRegion } from "../click-regions.js";import type { EditorPasteSnapshot } from "../editor-component.js";import { getKeybindings } from "../keybindings.js";import { decodePrintableKey, matchesKey } from "../keys.js";@@ -266,6 +267,16 @@ export class Editor implements Component, Focusable {private scrollOffset: number = 0;+ // Layout snapshot from the last render, the authority for click mapping.+ private clickLayout: {+ width: number;+ paddingX: number;+ promptPrefixWidth: number;+ layoutLines: LayoutLine[];+ scrollOffset: number;+ visibleCount: number;+ } | null = null;+public borderColor: (str: string) => string;public backgroundColor: ((str: string) => string) | undefined;public autocompleteBackgroundColor: ((str: string) => string) | undefined;@@ -550,6 +561,14 @@ export class Editor implements Component, Focusable {this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxScrollOffset));const visibleLines = layoutLines.slice(this.scrollOffset, this.scrollOffset + maxVisibleLines);+ this.clickLayout = {+ width,+ paddingX,+ promptPrefixWidth,+ layoutLines,+ scrollOffset: this.scrollOffset,+ visibleCount: visibleLines.length,+ };const result: string[] = [];const leftPadding = " ".repeat(paddingX);@@ -648,6 +667,81 @@ export class Editor implements Component, Focusable {return result;}+ /**+ * Rows a subclass inserts between the top border and the first content+ * line (e.g. a header block), so click regions match the final output.+ */+ protected getContentLineOffset(): number {+ return 0;+ }++ /** One region covering the visible content rows; the layout maps clicks. */+ getClickRegions(): ReadonlyArray<ClickRegion> {+ const layout = this.clickLayout;+ if (!layout || layout.visibleCount === 0 || layout.width <= 0) return [];+ return [+ {+ line: 1 + this.getContentLineOffset(),+ col: 0,+ width: layout.width,+ height: layout.visibleCount,+ onClick: (position) => this.placeCursorFromClick(position),+ },+ ];+ }++ /** Focus the editor and place the cursor at the clicked cell of the last layout. */+ private placeCursorFromClick(position: ClickPosition): void {+ const layout = this.clickLayout;+ if (!layout) return;+ const layoutLine = layout.layoutLines[layout.scrollOffset + position.row];+ if (!layoutLine) return;+ // Column relative to the start of the line's text.+ const rel = Math.max(0, position.col - (layout.paddingX + layout.promptPrefixWidth));+ // Walk the source line's marker-aware graphemes covering this visual+ // chunk, so an atomic marker force-split across wrapped rows keeps its+ // boundaries. A click past the midpoint of a segment (wide cell,+ // paste/image marker) lands after it, before it otherwise.+ const sourceLine = this.state.lines[layoutLine.sourceLine] || "";+ const from = layoutLine.sourceStart;+ const to = from + layoutLine.text.length;+ let chunkCol = 0;+ let placed = to;+ for (const seg of this.segment(sourceLine)) {+ const segEnd = seg.index + seg.segment.length;+ if (segEnd <= from) continue;+ if (seg.index >= to) break;+ const sliceStart = Math.max(seg.index, from);+ const inChunkWidth = visibleWidth(sourceLine.slice(sliceStart, Math.min(segEnd, to)));+ if (chunkCol + inChunkWidth > rel) {+ const withinSegment =+ (sliceStart > seg.index ? visibleWidth(sourceLine.slice(seg.index, sliceStart)) : 0) + (rel - chunkCol);+ placed = 2 * withinSegment >= visibleWidth(seg.segment) ? segEnd : seg.index;+ break;+ }+ chunkCol += inChunkWidth;+ }+ // A click past the chunk's text (right padding) leaves the chunk-end+ // offset, which can sit inside a marker split across rows.+ placed = this.snapCursorOffset(sourceLine, placed);+ this.tui.setFocus(this);+ this.lastAction = null;+ this.state.cursorLine = layoutLine.sourceLine;+ this.setCursorCol(placed);+ }++ /** Snap an offset sitting inside an atomic segment to its nearest boundary. */+ private snapCursorOffset(line: string, offset: number): number {+ for (const seg of this.segment(line)) {+ const segEnd = seg.index + seg.segment.length;+ if (seg.index >= offset) break;+ if (offset < segEnd) {+ return 2 * (offset - seg.index) >= seg.segment.length ? segEnd : seg.index;+ }+ }+ return offset;+ }+private renderAutocompleteOverlay(width: number): string[] {if (!(this.autocompleteState && this.autocompleteList)) return [];diff --git a/packages/tui/src/components/markdown.ts b/packages/tui/src/components/markdown.tsindex cf69195241..e31fa4eb72 100644--- a/packages/tui/src/components/markdown.ts+++ b/packages/tui/src/components/markdown.ts@@ -614,27 +614,24 @@ export class Markdown implements Component {case "link": {const linkText = this.renderInlineTokens(token.tokens || [], resolvedStyleContext);const styledLink = this.theme.link(this.theme.underline(linkText));+ // A Windows drive letter is a file path, not a URL scheme.+ const target = token.href.replace(/^([a-z]:[\\/])/i, "file:///$1");+ const href =+ !target.startsWith("#") &&+ (this.options.baseUrl || target !== token.href) &&+ URL.canParse(target, this.options.baseUrl)+ ? new URL(target, this.options.baseUrl).href+ : target;+ const linkedText = hyperlink(styledLink, href);if (getCapabilities().hyperlinks) {- // A Windows drive letter is a file path, not a URL scheme.- const target = token.href.replace(/^([a-z]:[\\/])/i, "file:///$1");- const href =- !target.startsWith("#") &&- (this.options.baseUrl || target !== token.href) &&- URL.canParse(target, this.options.baseUrl)- ? new URL(target, this.options.baseUrl).href- : target;- // OSC 8: render as a clickable hyperlink. The URL is not printed inline,- // so we always show only the link text regardless of whether it matches href.- result += hyperlink(styledLink, href) + stylePrefix;+ result += linkedText + stylePrefix;} else {- // Compare raw token.text (not styled) against href for the equality check.- // For mailto: links strip the prefix (autolinked emails use text="[email protected]"- // but href="mailto:[email protected]").+ // Keep the visible URL fallback while letting fullscreen hit testing open the label.const hrefForComparison = token.href.startsWith("mailto:") ? token.href.slice(7) : token.href;if (token.text === token.href || token.text === hrefForComparison) {- result += styledLink + stylePrefix;+ result += linkedText + stylePrefix;} else {- result += styledLink + this.theme.linkUrl(` (${token.href})`) + stylePrefix;+ result += linkedText + this.theme.linkUrl(` (${token.href})`) + stylePrefix;}}break;diff --git a/packages/tui/src/fullscreen.ts b/packages/tui/src/fullscreen.tsindex d184d56e96..07feef3e07 100644--- a/packages/tui/src/fullscreen.ts+++ b/packages/tui/src/fullscreen.ts@@ -5,6 +5,7 @@* scroll position is application state, not terminal scrollback.*/+import type { ClickRegion } from "./click-regions.js";import type { TableCellSelectionRegion } from "./selection-metadata.js";import { isImageLine } from "./terminal-image.js";import { sliceByColumn, stripAnsi, urlAtColumn, visibleWidth } from "./utils.js";@@ -40,6 +41,33 @@ interface FrameSelectionRegion {width: number;}+/**+ * A click region projected onto visible frame rows. The hit rect may be+ * narrower than `region` when overlay pixels cover it or the region is+ * clipped at a viewport edge; click positions stay relative to `anchor`,+ * the frame row of the region's top line even when that row is clipped away.+ */+export interface FrameClickTarget {+ /** Frame row this target occupies. */+ row: number;+ col: number;+ width: number;+ anchor: number;+ region: ClickRegion;+}++/** Visible frame rows of a projected region: hit rows plus the position anchor. */+export interface ProjectedRegionRows {+ anchor: number;+ from: number;+ count: number;+}++/** A region projected onto the frame: the region plus its visible hit rows. */+export interface FrameClickEntry extends ProjectedRegionRows {+ region: ClickRegion;+}+interface ColumnSpan {from: number;to: number;@@ -80,6 +108,10 @@ export class FullscreenViewport {private lastMaxScroll = 0;private lastWindowHeight = 0;private lastHeaderHeight = 0;+ private lastHeaderLines = 0;+ private lastDockLines = 0;+ private lastDockHeight = 0;+ private frameClickTargets: FrameClickTarget[] = [];private lastTranscript: string[] = [];private lastFrame: string[] = [];private lastFrameVisibleStart = 0;@@ -130,6 +162,9 @@ export class FullscreenViewport {this.lastMaxScroll = maxScroll;this.lastWindowHeight = windowHeight;this.lastHeaderHeight = headerLines.length;+ this.lastHeaderLines = (header ?? []).length;+ this.lastDockLines = dock.length;+ this.lastDockHeight = dockLines.length;this.lastTranscript = transcript;this.tableCellSelectionRegions = tableCellSelectionRegions;@@ -144,6 +179,97 @@ export class FullscreenViewport {return [...headerLines, ...window, ...dockLines];}+ /**+ * Intersect [line, line+height) with the visible frame rows [firstFrameRow,+ * firstFrameRow+frameRowCount). `anchor` keeps the frame row of the+ * region's top line even when it is clipped away, so click positions stay+ * relative to the region, not to the visible slice.+ */+ private projectRows(+ line: number,+ height: number,+ firstFrameRow: number,+ frameRowCount: number,+ frameRowOfLine: (line: number) => number,+ ): ProjectedRegionRows | null {+ const anchor = frameRowOfLine(line);+ const from = Math.max(anchor, firstFrameRow);+ const end = Math.min(anchor + Math.max(1, height), firstFrameRow + frameRowCount);+ return end > from ? { anchor, from, count: end - from } : null;+ }++ /** Project a header region; the header keeps its bottom rows when clipped. */+ projectHeaderRegion(line: number, height: number): ProjectedRegionRows | null {+ const start = Math.max(0, this.lastHeaderLines - this.lastHeaderHeight);+ return this.projectRows(line, height, 0, this.lastHeaderHeight, (row) => row - start);+ }++ /** Project a transcript region onto the visible window rows. */+ projectTranscriptRegion(line: number, height: number): ProjectedRegionRows | null {+ const base = this.lastHeaderHeight - this.scrollTop;+ return this.projectRows(line, height, this.lastHeaderHeight, this.lastWindowHeight, (row) => base + row);+ }++ /** Project a dock region; the dock keeps its bottom rows when clipped. */+ projectDockRegion(line: number, height: number): ProjectedRegionRows | null {+ const start = Math.max(0, this.lastDockLines - this.lastDockHeight);+ const base = this.lastHeaderHeight + this.lastWindowHeight;+ return this.projectRows(line, height, base, this.lastDockHeight, (row) => base + row - start);+ }++ /** Replace the click targets with regions projected onto visible frame rows. */+ setFrameClickRegions(entries: ReadonlyArray<FrameClickEntry>): void {+ const targets: FrameClickTarget[] = [];+ for (const { region, anchor, from, count } of entries) {+ for (let row = from; row < from + count; row++) {+ targets.push({ row, col: region.col, width: region.width, anchor, region });+ }+ }+ this.frameClickTargets = targets;+ }++ /** Register an overlay region at its composited frame position, clipped to visible rows. */+ addFrameClickEntry(entry: FrameClickEntry): void {+ for (let row = entry.from; row < entry.from + entry.count; row++) {+ this.frameClickTargets.push({+ row,+ col: entry.region.col,+ width: entry.region.width,+ anchor: entry.anchor,+ region: entry.region,+ });+ }+ }++ /** Drop click coverage under pixels painted over the frame (overlays, follow hint). */+ subtractFrameClickCoverage(line: number, startCol: number, endCol: number): void {+ for (let i = this.frameClickTargets.length - 1; i >= 0; i--) {+ const target = this.frameClickTargets[i]!;+ if (target.row !== line) continue;+ const targetEnd = target.col + target.width;+ if (endCol <= target.col || startCol >= targetEnd) continue;+ const fragments: FrameClickTarget[] = [];+ if (target.col < startCol) {+ fragments.push({ ...target, col: target.col, width: startCol - target.col });+ }+ if (endCol < targetEnd) {+ fragments.push({ ...target, col: endCol, width: targetEnd - endCol });+ }+ this.frameClickTargets.splice(i, 1, ...fragments);+ }+ }++ /** Click target covering a screen position in the last composed frame, or null. */+ clickTargetAt(screenRow: number, screenCol: number): FrameClickTarget | null {+ if (screenRow < 0 || screenCol < 0) return null;+ for (const target of this.frameClickTargets) {+ if (target.row === screenRow && screenCol >= target.col && screenCol < target.col + target.width) {+ return target;+ }+ }+ return null;+ }+private orderedSelection(): { start: SelectionPoint; end: SelectionPoint } | null {const a = this.selectionAnchor;const b = this.selectionHead;diff --git a/packages/tui/src/index.ts b/packages/tui/src/index.tsindex 37430472f1..8ba8df0b31 100644--- a/packages/tui/src/index.ts+++ b/packages/tui/src/index.ts@@ -5,8 +5,10 @@ export {CombinedAutocompleteProvider,type SlashCommand,} from "./autocomplete.js";+export type { ClickPosition, ClickRegion } from "./click-regions.js";export { Box } from "./components/box.js";export { CancellableLoader } from "./components/cancellable-loader.js";+export { Clickable } from "./components/clickable.js";export { Editor, type EditorOptions, type EditorTheme } from "./components/editor.js";export { Image, type ImageOptions, type ImageTheme } from "./components/image.js";export { Input } from "./components/input.js";diff --git a/packages/tui/src/tui.ts b/packages/tui/src/tui.tsindex ce0f412c6b..e97f76f991 100644--- a/packages/tui/src/tui.ts+++ b/packages/tui/src/tui.ts@@ -7,8 +7,16 @@ import * as fs from "node:fs";import * as os from "node:os";import * as path from "node:path";import { performance } from "node:perf_hooks";+import type { ClickRegion } from "./click-regions.js";import { withFullscreenImageFallback } from "./components/image.js";-import { FullscreenViewport, type ScrollInfo, type SelectionScrollDirection } from "./fullscreen.js";+import {+ type FrameClickEntry,+ type FrameClickTarget,+ FullscreenViewport,+ type ProjectedRegionRows,+ type ScrollInfo,+ type SelectionScrollDirection,+} from "./fullscreen.js";import { getKeybindings } from "./keybindings.js";import { isKeyRelease, matchesKey } from "./keys.js";import { isMouseSequence, isWheelDown, isWheelUp, MOUSE_BUTTON_LEFT, parseSgrMouseEvent } from "./mouse.js";@@ -60,6 +68,12 @@ export interface Component {getSelectionRegions?(): ReadonlyArray<TableCellSelectionRegion>;+ /**+ * Click regions produced by the last render() call, in the component's own+ * render-output coordinates. Containers aggregate them with line offsets.+ */+ getClickRegions?(): ReadonlyArray<ClickRegion>;+/*** Optional handler for keyboard input when component has focus*/@@ -247,10 +261,12 @@ export interface OverlayHandle {export class Container implements Component {children: Component[] = [];private selectionRegions: TableCellSelectionRegion[] = [];+ protected clickRegions: ClickRegion[] = [];addChild(component: Component): void {this.children.push(component);this.selectionRegions = [];+ this.clickRegions = [];}removeChild(component: Component): void {@@ -258,12 +274,14 @@ export class Container implements Component {if (index !== -1) {this.children.splice(index, 1);this.selectionRegions = [];+ this.clickRegions = [];}}clear(): void {this.children = [];this.selectionRegions = [];+ this.clickRegions = [];}invalidate(): void {@@ -276,6 +294,7 @@ export class Container implements Component {render(width: number): string[] {const lines: string[] = [];const selectionRegions: TableCellSelectionRegion[] = [];+ const clickRegions: ClickRegion[] = [];for (const child of this.children) {const lineOffset = lines.length;const childLines = child.render(width);@@ -287,17 +306,25 @@ export class Container implements Component {tableBottom: region.tableBottom + lineOffset,});}+ for (const region of child.getClickRegions?.() ?? []) {+ clickRegions.push({ ...region, line: region.line + lineOffset });+ }for (const line of childLines) {lines.push(line);}}this.selectionRegions = selectionRegions;+ this.clickRegions = clickRegions;return lines;}getSelectionRegions(): ReadonlyArray<TableCellSelectionRegion> {return this.selectionRegions;}++ getClickRegions(): ReadonlyArray<ClickRegion> {+ return this.clickRegions;+ }}/**@@ -333,6 +360,7 @@ export class TUI extends Container {private stopped = false;private fullscreenLeftMouseDragged = false;private fullscreenPressedHyperlink: string | null = null;+ private fullscreenPressedClick: FrameClickTarget | null = null;private overlaySelectionRegions: FrameSelectionRegion[] = [];// While set, doRender paints fixed frames via the viewport; the inline@@ -559,6 +587,7 @@ export class TUI extends Container {this.stopSelectionAutoScroll();this.fullscreenLeftMouseDragged = false;this.fullscreenPressedHyperlink = null;+ this.fullscreenPressedClick = null;this.fullscreen?.viewport.clearSelection();} else if (this.isFullscreenOverlayFocused()) {this.stopSelectionAutoScroll();@@ -685,6 +714,7 @@ export class TUI extends Container {if (this.fullscreen) return;this.fullscreenLeftMouseDragged = false;this.fullscreenPressedHyperlink = null;+ this.fullscreenPressedClick = null;this.fullscreen = {viewport: new FullscreenViewport(),scroll: options.scroll,@@ -941,6 +971,12 @@ export class TUI extends Container {this.fullscreenLeftMouseDragged = event.motion;if (!event.motion) {this.fullscreenPressedHyperlink = fullscreen.viewport.hyperlinkAt(event.y - 1, event.x - 1);+ // Hyperlinks win over component regions at the press position;+ // shift/alt/ctrl clicks stay selection-only.+ this.fullscreenPressedClick =+ !event.shift && !event.alt && !event.ctrl && !this.fullscreenPressedHyperlink+ ? fullscreen.viewport.clickTargetAt(event.y - 1, event.x - 1)+ : null;}}if (event && !overlayFocused) {@@ -971,7 +1007,11 @@ export class TUI extends Container {viewport.clearSelection();if (event.button === MOUSE_BUTTON_LEFT && !event.motion && !leftReleaseWasDrag) {const url = this.fullscreenPressedHyperlink ?? viewport.hyperlinkAt(event.y - 1, event.x - 1);- if (url) this.openHyperlink(url);+ if (url) {+ this.openHyperlink(url);+ } else if (!event.shift && !event.alt && !event.ctrl) {+ this.dispatchFullscreenClick(event.y - 1, event.x - 1);+ }}}} else if (event && overlayFocused) {@@ -993,13 +1033,18 @@ export class TUI extends Container {viewport.clearSelection();if (event.button === MOUSE_BUTTON_LEFT && !event.motion && !leftReleaseWasDrag) {const url = this.fullscreenPressedHyperlink ?? viewport.hyperlinkAt(event.y - 1, event.x - 1);- if (url) this.openHyperlink(url);+ if (url) {+ this.openHyperlink(url);+ } else if (!event.shift && !event.alt && !event.ctrl) {+ this.dispatchFullscreenClick(event.y - 1, event.x - 1);+ }}}}if (event?.button === MOUSE_BUTTON_LEFT && !event.press) {this.fullscreenLeftMouseDragged = false;this.fullscreenPressedHyperlink = null;+ this.fullscreenPressedClick = null;}return true;}@@ -1027,6 +1072,15 @@ export class TUI extends Container {return false;}+ /** Fire the region pressed without dragging, when the release lands inside it. */+ private dispatchFullscreenClick(row: number, col: number): void {+ const pressed = this.fullscreenPressedClick;+ if (!pressed) return;+ if (row !== pressed.row || col < pressed.col || col >= pressed.col + pressed.width) return;+ pressed.region.onClick({ row: row - pressed.anchor, col: col - pressed.region.col });+ this.requestRender();+ }+private consumeCellSizeResponse(data: string): boolean {// Response format: ESC [ 6 ; height ; width tconst match = data.match(/^\x1b\[6;(\d+);(\d+)t$/);@@ -1293,6 +1347,30 @@ export class TUI extends Container {if (span) {overlaySelectionRegions.push({ line: idx, col: col + span.from, width: span.to - span.from });}+ // Painted overlay pixels swallow clicks aimed at content+ // beneath. Click targets are screen-relative, so an+ // over-tall overlay must subtract from the on-screen row.+ const screenRow = idx - viewportStart;+ if (this.fullscreen && screenRow >= 0 && screenRow < termHeight) {+ this.fullscreen.viewport.subtractFrameClickCoverage(screenRow, col, col + w);+ }+ }+ }+ if (!aboveMarker) {+ for (const region of component.getClickRegions?.() ?? []) {+ if (region.line >= overlayLines.length) continue;+ const height = Math.min(region.height, overlayLines.length - region.line);+ const screenTop = overlayStart + row + region.line - viewportStart;+ const from = Math.max(screenTop, 0);+ const to = Math.min(screenTop + height, termHeight);+ if (to > from) {+ this.fullscreen?.viewport.addFrameClickEntry({+ region: { ...region, col: col + region.col },+ anchor: screenTop,+ from,+ count: to - from,+ });+ }}}}@@ -1492,6 +1570,9 @@ export class TUI extends Container {const transcript: string[] = [];const selectionRegions: TableCellSelectionRegion[] = [];+ const transcriptClickRegions: ClickRegion[] = [];+ let dockClickRegions: ClickRegion[] = [];+ let headerClickRegions: ClickRegion[] = [];const dock = withFullscreenImageFallback(() => {for (const component of fullscreen.scroll) {const lineOffset = transcript.length;@@ -1504,13 +1585,42 @@ export class TUI extends Container {tableBottom: region.tableBottom + lineOffset,});}+ for (const region of component.getClickRegions?.() ?? []) {+ transcriptClickRegions.push({ ...region, line: region.line + lineOffset });+ }transcript.push(...componentLines);}- return fullscreen.dock.render(width);+ const dockLines = fullscreen.dock.render(width);+ dockClickRegions = [...(fullscreen.dock.getClickRegions?.() ?? [])];+ return dockLines;+ });+ const header = withFullscreenImageFallback(() => {+ const headerLines = fullscreen.pin?.render(width) ?? [];+ headerClickRegions = [...(fullscreen.pin?.getClickRegions?.() ?? [])];+ return headerLines;});- const header = withFullscreenImageFallback(() => fullscreen.pin?.render(width) ?? []);let frame = fullscreen.viewport.composeFrame(transcript, dock, height, selectionRegions, header);+ // Project component-space regions onto visible frame rows through the+ // same header/window/dock layout composeFrame just established. Regions+ // clipped at a viewport edge keep only their visible rows, and click+ // positions stay relative to the region's top even when clipped away.+ const frameClickEntries: FrameClickEntry[] = [];+ const projectRegions = (+ regions: ReadonlyArray<ClickRegion>,+ project: (line: number, height: number) => ProjectedRegionRows | null,+ ): void => {+ for (const region of regions) {+ const rows = project(region.line, region.height);+ if (rows) frameClickEntries.push({ region, ...rows });+ }+ };+ projectRegions(headerClickRegions, (line, height) => fullscreen.viewport.projectHeaderRegion(line, height));+ projectRegions(transcriptClickRegions, (line, height) =>+ fullscreen.viewport.projectTranscriptRegion(line, height),+ );+ projectRegions(dockClickRegions, (line, height) => fullscreen.viewport.projectDockRegion(line, height));+ fullscreen.viewport.setFrameClickRegions(frameClickEntries);this.overlaySelectionRegions.push(...this.createDockSelectionRegions(frame,@@ -1529,6 +1639,7 @@ export class TUI extends Container {if (row >= 0 && row < frame.length && labelWidth <= width) {const col = Math.floor((width - labelWidth) / 2);frame[row] = this.compositeLineAt(frame[row], `\x1b[7m${label}\x1b[27m`, col, labelWidth, width);+ fullscreen.viewport.subtractFrameClickCoverage(row, col, col + labelWidth);}}if (this.overlayStack.length > 0) {diff --git a/packages/tui/test/click-regions.test.ts b/packages/tui/test/click-regions.test.tsnew file mode 100644index 0000000000..35910672f3--- /dev/null+++ b/packages/tui/test/click-regions.test.ts@@ -0,0 +1,192 @@+import assert from "node:assert";+import { describe, it } from "node:test";+import type { ClickPosition, ClickRegion } from "../src/click-regions.js";+import { Box } from "../src/components/box.js";+import { Editor } from "../src/components/editor.js";+import { hyperlink } from "../src/terminal-image.js";+import { type Component, Container, type FullscreenOptions, TUI } from "../src/tui.js";+import { defaultEditorTheme } from "./test-themes.js";+import { VirtualTerminal } from "./virtual-terminal.js";++const numbered = (count: number, prefix = "row") => Array.from({ length: count }, (_, i) => `${prefix} ${i}`);+type Recorder = (position: ClickPosition) => void;++const region = (handler: Recorder, count: number, line: number, col: number, width = 10, height = 1) => {+ const rendered = numbered(count);+ let regions: ClickRegion[] = [];+ return {+ rendered,+ render: () => {+ regions = rendered.length > line ? [{ line, col, width, height, onClick: handler }] : [];+ return rendered;+ },+ invalidate: () => {},+ getClickRegions: () => regions,+ };+};+const plain = (lines: string[]): Component => ({ render: () => lines, invalidate: () => {} });+const chatSession = (rec: Recorder) => ({ scroll: [region(rec, 20, 15, 5)], dock: plain(["> prompt"]) });++async function withFullscreen<T extends FullscreenOptions>(+ build: (tui: TUI) => T,+ test: (+ ctx: T & { terminal: VirtualTerminal; tui: TUI; click: (x: number, y: number) => Promise<void> },+ ) => Promise<void>,+): Promise<void> {+ const terminal = new VirtualTerminal(40, 10);+ const tui = new TUI(terminal);+ tui.start();+ const spec = build(tui);+ tui.enterFullscreen(spec);+ await terminal.waitForRender();+ const click = async (x: number, y: number) => {+ terminal.sendInput(`\x1b[<0;${x};${y}M`);+ terminal.sendInput(`\x1b[<0;${x};${y}m`);+ await terminal.waitForRender();+ };+ try {+ await test({ ...spec, terminal, tui, click });+ } finally {+ tui.stop();+ }+}++describe("fullscreen click regions", () => {+ it("dispatches region clicks at region-relative positions, prefers hyperlinks, and ignores mouse-disabled sessions", async () => {+ const calls: ClickPosition[] = [];+ const urls: string[] = [];+ const rec = (p: ClickPosition) => calls.push(p);+ const prompt = plain(["> prompt"]);+ const footer = plain(["> prompt", "footer"]);+ const chatLines = plain(numbered(6, "chat"));+ const hyperlinkLayout = (tui: TUI) => {+ const chat = region(rec, 20, 15, 5);+ chat.rendered[15] = hyperlink("open docs", "https://example.com/docs");+ tui.onOpenUrl = (url) => urls.push(url);+ return { scroll: [chat], dock: prompt };+ };+ for (const {+ layout,+ click: [x, y, row, col],+ mouseOff,+ urls: opened,+ } of [+ { layout: () => ({ ...chatSession(rec), dock: footer }), click: [8, 4, 0, 2] },+ { layout: () => ({ scroll: [chatLines], dock: prompt, pin: region(rec, 1, 0, 2) }), click: [3, 1, 0, 0] },+ { layout: () => ({ ...chatSession(rec), mouse: false }), click: [8, 5, 0, 0], mouseOff: true },+ { layout: hyperlinkLayout, click: [8, 5, 0, 0], urls: ["https://example.com/docs"] },+ ]) {+ calls.length = 0;+ await withFullscreen<FullscreenOptions>(layout, async ({ terminal, click }) => {+ if (mouseOff) assert.strictEqual(terminal.mouseTrackingActive, false);+ await click(x, y);+ });+ assert.deepStrictEqual(calls, mouseOff || opened ? [] : [{ row, col }]);+ if (opened) assert.deepStrictEqual(urls, opened);+ }+ });++ it("re-maps regions after scrolling and ignores drags, mismatched releases, non-left and modified clicks", async () => {+ const calls: ClickPosition[] = [];+ await withFullscreen(+ () => chatSession((p) => calls.push(p)),+ async ({ terminal, click }) => {+ for (const inputs of [+ ["\x1b[<0;8;5M", "\x1b[<32;9;5M", "\x1b[<0;9;5m"],+ ["\x1b[<0;8;5M", "\x1b[<0;8;2m"],+ ["\x1b[<2;8;5M", "\x1b[<2;8;5m"],+ ["\x1b[<4;8;5M", "\x1b[<4;8;5m"],+ ]) {+ for (const input of inputs) terminal.sendInput(input);+ await terminal.waitForRender();+ }+ terminal.sendInput("\x1b[<64;5;5M");+ await terminal.waitForRender();+ await click(8, 5);+ await click(8, 8);+ },+ );+ assert.deepStrictEqual(calls, [{ row: 0, col: 2 }]);+ });++ it("drops dock regions clipped away and keeps the visible ones", async () => {+ const top: ClickPosition[] = [];+ const bottom: ClickPosition[] = [];+ const dock = new Container();+ dock.addChild(region((p) => top.push(p), 1, 0, 0));+ dock.addChild(plain(numbered(6, "mid")));+ dock.addChild(region((p) => bottom.push(p), 1, 0, 3));+ await withFullscreen(+ () => ({ scroll: [plain(numbered(6, "chat"))], dock }),+ async ({ click }) => {+ await click(4, 4);+ await click(5, 10);+ },+ );+ assert.deepStrictEqual(top, []);+ assert.deepStrictEqual(bottom, [{ row: 0, col: 1 }]);+ });++ it("blocks covered regions, dispatches overlay regions, and clips them to the rows actually rendered", async () => {+ for (const { covered, overlay, maxHeight, clicks, expected } of [+ { covered: true, overlay: [12, 0, 4, 10, 1], clicks: [7, 4, 7, 1], expected: [{ row: 0, col: 2 }] },+ { overlay: [5, 0, 0, 10, 5], maxHeight: 4, clicks: [5, 5, 5, 1], expected: [{ row: 0, col: 4 }] },+ ]) {+ const baseCalls: ClickPosition[] = [];+ const overlayCalls: ClickPosition[] = [];+ const [count, line, col, width, height] = overlay;+ const overlayComponent = region((p) => overlayCalls.push(p), count, line, col, width, height);+ await withFullscreen(+ () =>+ covered+ ? { ...chatSession((p) => baseCalls.push(p)), dock: plain(["> prompt", "footer"]) }+ : { scroll: [plain(numbered(20))], dock: plain(["> prompt", "footer"]) },+ async ({ terminal, tui, click }) => {+ tui.showOverlay(overlayComponent, { width: 20, anchor: "top-left", nonCapturing: true, maxHeight });+ await terminal.waitForRender();+ for (let i = 0; i < clicks.length; i += 2) await click(clicks[i]!, clicks[i + 1]!);+ },+ );+ assert.deepStrictEqual(baseCalls, [], "covered base regions never fire");+ assert.deepStrictEqual(overlayCalls, expected);+ }+ });++ it("places the editor cursor through real dock clicks, including where the dock clips top rows", async () => {+ for (const { text, footer, clicks } of [+ { text: "hello world", footer: false, clicks: [7, 9, 0, 6] },+ { text: "alpha\nbeta\ngamma\ndelta\nepsilon", footer: true, clicks: [3, 4, 1, 2, 2, 6, 3, 1, 3, 9, 3, 1] },+ ]) {+ await withFullscreen(+ (tui) => {+ const editor = new Editor(tui, defaultEditorTheme);+ editor.setText(text);+ const dock = new Container();+ dock.addChild(editor);+ if (footer) dock.addChild(plain(["foot a", "foot b"]));+ return { scroll: [plain(numbered(20))], dock, editor };+ },+ async ({ editor, click }) => {+ for (let i = 0; i < clicks.length; i += 4) {+ await click(clicks[i]!, clicks[i + 1]!);+ assert.deepStrictEqual(editor.getCursor(), { line: clicks[i + 2]!, col: clicks[i + 3]! });+ }+ assert.strictEqual(editor.focused, true);+ },+ );+ }+ });++ it("drops Box click regions when a child later renders empty", () => {+ const calls: ClickPosition[] = [];+ const child = region((p) => calls.push(p), 1, 0, 0);+ const box = new Box(1, 1);+ box.addChild(child);+ assert.ok(box.render(20).length > 0);+ assert.strictEqual(box.getClickRegions().length, 1);+ child.rendered.length = 0;+ assert.deepStrictEqual(box.render(20), []);+ assert.strictEqual(box.getClickRegions().length, 0);+ assert.deepStrictEqual(calls, []);+ });+});diff --git a/packages/tui/test/editor-click.test.ts b/packages/tui/test/editor-click.test.tsnew file mode 100644index 0000000000..05e3a41d70--- /dev/null+++ b/packages/tui/test/editor-click.test.ts@@ -0,0 +1,75 @@+import assert from "node:assert";+import { describe, it } from "node:test";+import { Editor } from "../src/components/editor.js";+import { TUI } from "../src/tui.js";+import { defaultEditorTheme } from "./test-themes.js";+import { VirtualTerminal } from "./virtual-terminal.js";++type Region = ReturnType<Editor["getClickRegions"]>[number];+type Cursor = ReturnType<Editor["getCursor"]>;+const makeEditor = (width = 40) => new Editor(new TUI(new VirtualTerminal(width, 24)), defaultEditorTheme);+const singleRegion = (editor: Editor) => {+ const regions = editor.getClickRegions();+ assert.strictEqual(regions.length, 1);+ return regions[0]!;+};+const click = (editor: Editor, region: Region, row: number, col: number, expected: Cursor, message?: string) => {+ region.onClick({ row, col });+ assert.deepStrictEqual(editor.getCursor(), expected, message);+};+describe("editor click regions", () => {+ it("maps region clicks to logical cursor positions and focuses the editor", () => {+ const cases: {+ width: number;+ text: string;+ check?: (lines: string[], region: Region) => void;+ clicks: number[];+ }[] = [+ { width: 40, text: "hello world", clicks: [0, 4, 0, 4] },+ {+ width: 10,+ text: "aaaa bbbb cccc dddd",+ check: (lines, region) => assert.ok(lines.length > 3 && region.line === 1, "text wraps after the prefix"),+ clicks: [0, 0, 0, 0, 1, 2, 0, 7, 2, 3, 0, 13],+ },+ { width: 40, text: "a\u{1F389}b", clicks: [0, 1, 0, 1, 0, 2, 0, 3] },+ {+ width: 40,+ text: Array.from({ length: 10 }, (_, i) => `line ${i}`).join("\n"),+ check: (_lines, region) => assert.strictEqual(region.height, 7, "only the visible slice is clickable"),+ clicks: [0, 0, 3, 0, 5, 2, 8, 2],+ },+ ];+ for (const { width, text, check, clicks } of cases) {+ const editor = makeEditor(width);+ editor.setText(text);+ const lines = editor.render(width);+ const region = singleRegion(editor);+ check?.(lines, region);+ assert.strictEqual(editor.focused, false, "editor starts unfocused");+ for (let i = 0; i < clicks.length; i += 4)+ click(editor, region, clicks[i]!, clicks[i + 1]!, { line: clicks[i + 2]!, col: clicks[i + 3]! });+ assert.strictEqual(editor.focused, true, "clicking focuses the editor");+ }+ });+ it("snaps clicks inside an atomic paste marker to its boundary, split or not", () => {+ const editor = makeEditor();+ editor.handleInput(`\x1b[200~${Array.from({ length: 15 }, (_, i) => `line ${i}`).join("\n")}\x1b[201~`);+ assert.strictEqual(editor.getText(), "[paste #1 +15 lines]");+ editor.render(40);+ const whole = singleRegion(editor);+ click(editor, whole, 0, 9, { line: 0, col: 0 }, "left half lands before");+ click(editor, whole, 0, 10, { line: 0, col: 20 }, "right half lands after");+ editor.render(12); // narrow width force-splits the marker across two rows+ const split = singleRegion(editor);+ assert.strictEqual(split.height, 2, "marker wraps onto two visual rows");+ click(editor, split, 0, 9, { line: 0, col: 0 }, "first chunk lands before");+ click(editor, split, 1, 0, { line: 0, col: 20 }, "continuation chunk lands after");+ split.onClick({ row: 0, col: 11 });+ const { line, col } = editor.getCursor();+ assert.ok(+ line === 0 && (col === 0 || col === 20),+ `padding click lands on a marker boundary, not mid-marker (got ${col})`,+ );+ });+});diff --git a/packages/tui/test/markdown.test.ts b/packages/tui/test/markdown.test.tsindex c12413680b..a8f46778ab 100644--- a/packages/tui/test/markdown.test.ts+++ b/packages/tui/test/markdown.test.ts@@ -5,15 +5,12 @@ import { Chalk } from "chalk";import { Markdown } from "../src/components/markdown.js";import { resetCapabilitiesCache, setCapabilities } from "../src/terminal-image.js";import { TUI } from "../src/tui.js";+import { hyperlinkAtColumn, stripAnsi } from "../src/utils.js";import { defaultMarkdownTheme } from "./test-themes.js";import { VirtualTerminal } from "./virtual-terminal.js";const chalk = new Chalk({ level: 3 });-function stripAnsi(line: string): string {- return line.replace(/\x1b\[[0-9;]*m/g, "");-}-function render(text: string, width = 80, paddingX = 0): string[] {return new Markdown(text, paddingX, 0, defaultMarkdownTheme).render(width);}@@ -33,6 +30,19 @@ function getCellUnderline(terminal: VirtualTerminal, row: number, col: number):}describe("Markdown component", () => {+ it("keeps labeled links clickable when the visible URL fallback is shown (ENG-6126)", () => {+ setCapabilities({ images: null, trueColor: false, hyperlinks: false });+ try {+ const url = "https://www.google.com";+ const line = render(`[Google](${url})`)[0]!;++ assert.strictEqual(hyperlinkAtColumn(line, 0), url);+ assert.strictEqual(stripAnsi(line).trimEnd(), `Google (${url})`);+ } finally {+ resetCapabilitiesCache();+ }+ });+describe("Table layout", () => {const table = (header: string, separator: string, ...rows: string[]) => [header, separator, ...rows].join("\n");const longWord = "superlongword";