The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Reduce terminal link hit-testing stalls (#554)
Dee1aca855fa78b
diff --git a/desktop/integration_test/native_terminal_links_e2e_test.dart b/desktop/integration_test/native_terminal_links_e2e_test.dartnew file mode 100644index 000000000..3e37cfebc--- /dev/null+++ b/desktop/integration_test/native_terminal_links_e2e_test.dart@@ -0,0 +1,17 @@+import 'package:harness/core/test_run.dart';+import 'package:integration_test/integration_test.dart';++import '../test/terminal_link_gesture_test.dart' as gestures;+import '../test/terminal_panel_links_test.dart' as links;++/// Exercise the production TerminalPanel in the native renderer. These tests+/// inject Flutter pointer/key events; file reads, downloads and URL launches+/// are fakes. They do not verify physical AppKit modifier-key delivery.+void main() {+ if (!kUnderTest) {+ throw StateError('Native terminal link fixtures require FLUTTER_TEST=1');+ }+ IntegrationTestWidgetsFlutterBinding.ensureInitialized();+ gestures.main();+ links.main();+}diff --git a/desktop/lib/terminal/terminal_links.dart b/desktop/lib/terminal/terminal_links.dartindex 20685c82a..b67b3ae2f 100644--- a/desktop/lib/terminal/terminal_links.dart+++ b/desktop/lib/terminal/terminal_links.dart@@ -1,4 +1,4 @@-import 'package:xterm/xterm.dart';+import 'package:xterm/core.dart';const _mediaExtensions =r'png|jpe?g|gif|webp|avif|heic|heif|bmp|tiff?|svg|ico|'@@ -18,9 +18,17 @@ final _absoluteMedia = RegExp(caseSensitive: false,);final _relativeMedia = RegExp(- r'''[^\s<>`"'()\[\]]+\.(?:''' ++ // Start once per token, rather than retrying every suffix of a long token+ // with no media extension. The delimiter is outside the captured target.+ r'''(?:^|[\s<>`"'()\[\]])([^\s<>`"'()\[\]]+\.(?:''' +_mediaExtensions +- r''')(?=$|[\s)\]}>.,;:!?])''',+ r'''))(?=$|[\s)\]}>.,;:!?])''',+ caseSensitive: false,+);+// Both bare-path patterns require this suffix and boundary. Reject ordinary+// text before their permissive path bodies backtrack over every token prefix.+final _bareMediaSuffix = RegExp(+ r'\.(?:' + _mediaExtensions + r')(?=$|[\s)\]}>.,;:!?])',caseSensitive: false,);@@ -54,17 +62,23 @@ String _trimWebPunctuation(String target) {/// Finds only the target under the pointer. No file IO or scan of scrollback./// Markdown labels and quoted paths retain spaces; bare URLs retain queries.-String? terminalLinkInText(String text, int offset) {+String? terminalLinkInText(String text, int offset) =>+ _terminalLinkInText(text, offset, null);++String? _terminalLinkInText(String text, int offset, _LinkLookup? lookup) {if (offset < 0 || offset >= text.length) return null;- for (final match in _markdownLink.allMatches(text)) {+ Iterable<RegExpMatch> matches(RegExp pattern) =>+ lookup?.matches(pattern, text) ?? pattern.allMatches(text);+ bool isTarget(String target) => lookup?.isTarget(target) ?? _isTarget(target);+ for (final match in matches(_markdownLink)) {if (offset < match.start || offset >= match.end) continue;var target = match[1]!;if (target.startsWith('<') && target.endsWith('>')) {target = target.substring(1, target.length - 1);}- return _isTarget(target) ? target : null;+ return isTarget(target) ? target : null;}- for (final match in _quotedTarget.allMatches(text)) {+ for (final match in matches(_quotedTarget)) {if (offset < match.start || offset >= match.end) continue;final target = [match[1],@@ -72,20 +86,21 @@ String? terminalLinkInText(String text, int offset) {match[3],match[4],].whereType<String>().single;- if (_isTarget(target)) return target;+ if (isTarget(target)) return target;}- for (final match in _webTarget.allMatches(text)) {+ for (final match in matches(_webTarget)) {if (offset < match.start || offset >= match.end) continue;- final target = _trimWebPunctuation(match[0]!);- return offset < match.start + target.length && _isTarget(target)+ final target = lookup?.trimWeb(match[0]!) ?? _trimWebPunctuation(match[0]!);+ return offset < match.start + target.length && isTarget(target)? target: null;}+ if (!_bareMediaSuffix.hasMatch(text)) return null;for (final pattern in [_absoluteMedia, _relativeMedia]) {- for (final match in pattern.allMatches(text)) {- final target = match.groupCount == 0 ? match[0]! : match[1]!;+ for (final match in matches(pattern)) {+ final target = match[1]!;final start = match.end - target.length;- if (offset >= start && offset < match.end && _isTarget(target)) {+ if (offset >= start && offset < match.end && isTarget(target)) {return target;}}@@ -105,12 +120,30 @@ class _LogicalLine {/// UTF-16 offset of the target cell in [text], when the cell is on this line.final int? offset;+ /// Retained only while walking one hover underline, never between events.+ final List<List<int>>? cellOffsets;+const _LogicalLine(this.firstRow,this.lastRow,this.text,this.styles,- this.offset,+ this.offset, {+ this.cellOffsets,+ });++ _LogicalLine at(CellOffset cell) => _LogicalLine(+ firstRow,+ lastRow,+ text,+ styles,+ cell.y >= firstRow &&+ cell.y <= lastRow &&+ cell.x >= 0 &&+ cell.x < cellOffsets![cell.y - firstRow].length+ ? cellOffsets![cell.y - firstRow][cell.x]+ : null,+ cellOffsets: cellOffsets,);int get leadingBlanks => text.length - text.trimLeft().length;@@ -119,6 +152,88 @@ class _LogicalLine {int get lastVisible => text.trimRight().length - 1;}+/// Replay only the matches previously needed, advancing the source lazily.+class _CachedPatternMatches {+ _CachedPatternMatches(Iterable<RegExpMatch> source)+ : _remaining = source.iterator;++ Iterator<RegExpMatch>? _remaining;+ final _seen = <RegExpMatch>[];++ Iterable<RegExpMatch> get values sync* {+ var index = 0;+ while (true) {+ if (index < _seen.length) {+ yield _seen[index++];+ } else if (_remaining?.moveNext() == true) {+ _seen.add(_remaining!.current);+ } else {+ _remaining = null;+ return;+ }+ }+ }+}++/// One synchronous extent lookup may test hundreds of neighboring cells in+/// the same text. Share its immutable line reconstruction and pattern matches.+/// The object is discarded before returning: output, resize, buffer switches,+/// and OSC 8 updates are always read afresh on the next pointer event.+class _LinkLookup {+ _LinkLookup(this.terminal);++ final Terminal terminal;+ final _lines = <int, _LogicalLine?>{};+ final _matches = <(RegExp, String), _CachedPatternMatches>{};+ final _targets = <String, bool>{};+ final _trimmedWeb = <String, String>{};+ final _urlCuts = <String, int?>{};+ final _boxCuts = <int, bool>{};+ final _tokens = <String, ({int length, bool single, bool continues})>{};++ _LogicalLine? line(int row, CellOffset cell) {+ if (_lines.containsKey(row)) return _lines[row]?.at(cell);+ final line = _logicalLine(terminal, row, cell, retainOffsets: true);+ _lines[row] = line;+ if (line != null) {+ for (var y = line.firstRow; y <= line.lastRow; y++) {+ _lines[y] = line;+ }+ }+ return line;+ }++ // Retain the original short-circuiting: a match under the pointer does not+ // require parsing every later link or malformed fragment on the same line.+ Iterable<RegExpMatch> matches(RegExp pattern, String text) =>+ _matches.putIfAbsent((+ pattern,+ text,+ ), () => _CachedPatternMatches(pattern.allMatches(text))).values;++ bool isTarget(String target) =>+ _targets.putIfAbsent(target, () => _isTarget(target));++ String trimWeb(String target) =>+ _trimmedWeb.putIfAbsent(target, () => _trimWebPunctuation(target));++ int? urlCutAt(String text) =>+ _urlCuts.putIfAbsent(text, () => _urlCutAt(text));++ bool cutAtBoxWidth(_LogicalLine line) =>+ _boxCuts.putIfAbsent(line.lastRow, () => _cutAtBoxWidth(terminal, line));++ ({int length, bool single, bool continues}) tokens(_LogicalLine line) =>+ _tokens.putIfAbsent(+ line.text,+ () => (+ length: _tokenLength(line),+ single: _singleToken(line),+ continues: _continuesUrl(line),+ ),+ );+}+/// What makes a run of cells read as one thing: its colour and whether it is/// underlined. Claude Code paints an address bright blue and carries that/// paint onto the row it cut the address across, while the words around it@@ -133,7 +248,12 @@ bool _underlined(int styleKey) => styleKey & 1 != 0;/// mapping cell columns to UTF-16 offsets (wide CJK and emoji are not one code/// unit). The bound also keeps malformed/unbroken output cheap during mouse/// hover. [cell] is the pointer, whose offset is reported when it lands here.-_LogicalLine? _logicalLine(Terminal terminal, int y, CellOffset cell) {+_LogicalLine? _logicalLine(+ Terminal terminal,+ int y,+ CellOffset cell, {+ bool retainOffsets = false,+}) {final lines = terminal.buffer.lines;var start = y;var end = y;@@ -147,12 +267,16 @@ _LogicalLine? _logicalLine(Terminal terminal, int y, CellOffset cell) {}final text = StringBuffer();final styles = <int>[];+ final cellOffsets = retainOffsets ? <List<int>>[] : null;int? offset;for (var row = start; row <= end; row++) {final line = lines[row];+ final rowOffsets = retainOffsets ? <int>[] : null;+ if (rowOffsets != null) cellOffsets!.add(rowOffsets);var previousOffset = text.length;for (var x = 0; x < line.length; x++) {final continuation = x > 0 && line.getWidth(x - 1) == 2;+ rowOffsets?.add(continuation ? previousOffset : text.length);if (cell.y == row && cell.x == x) {offset = continuation ? previousOffset : text.length;}@@ -167,7 +291,14 @@ _LogicalLine? _logicalLine(Terminal terminal, int y, CellOffset cell) {}}}- return _LogicalLine(start, end, text.toString(), styles, offset);+ return _LogicalLine(+ start,+ end,+ text.toString(),+ styles,+ offset,+ cellOffsets: cellOffsets,+ );}/// Columns up to the last cell that is neither empty nor a space — the width@@ -297,9 +428,15 @@ int? _urlCutAt(String text) {/// row that opens in plain text is the next sentence, however wide the row/// above was. An address in the same paint as its sentence has only the box/// width to go on.-bool _cutThroughout(Terminal terminal, List<_LogicalLine> joined) {+bool _cutThroughout(+ Terminal terminal,+ List<_LogicalLine> joined,+ _LinkLookup? lookup,+) {final head = joined.first;- final urlStart = _urlCutAt(head.text);+ final urlStart = lookup != null+ ? lookup.urlCutAt(head.text)+ : _urlCutAt(head.text);if (urlStart == null) return false;final urlStyle = head.styles[head.lastVisible];var before = urlStart - 1;@@ -312,7 +449,8 @@ bool _cutThroughout(Terminal terminal, List<_LogicalLine> joined) {for (var i = 0; i + 1 < joined.length; i++) {final cut = painted? _paintContinues(joined[i], joined[i + 1])- : _cutAtBoxWidth(terminal, joined[i]);+ : (lookup?.cutAtBoxWidth(joined[i]) ??+ _cutAtBoxWidth(terminal, joined[i]));if (!cut) return false;}return true;@@ -328,7 +466,14 @@ bool _cutThroughout(Terminal terminal, List<_LogicalLine> joined) {/// `hard: true`) does. A terminal soft wrap is already joined by/// [_logicalLine]; this is the break it cannot see, and it is inferred: from/// the paint on the address when there is any, else from the row's width.-String? terminalLinkAt(Terminal terminal, CellOffset cell) {+String? terminalLinkAt(Terminal terminal, CellOffset cell) =>+ _terminalLinkAt(terminal, cell, null);++String? _terminalLinkAt(+ Terminal terminal,+ CellOffset cell,+ _LinkLookup? lookup,+) {final lines = terminal.buffer.lines;if (cell.y < 0 ||cell.y >= lines.length ||@@ -348,41 +493,53 @@ String? terminalLinkAt(Terminal terminal, CellOffset cell) {return hyperlink;}}- final own = _logicalLine(terminal, cell.y, cell);+ _LogicalLine? lineAt(int row) => lookup != null+ ? lookup.line(row, cell)+ : _logicalLine(terminal, row, cell);+ int? urlCutAt(String text) =>+ lookup != null ? lookup.urlCutAt(text) : _urlCutAt(text);+ bool cutAtBoxWidth(_LogicalLine line) =>+ lookup?.cutAtBoxWidth(line) ?? _cutAtBoxWidth(terminal, line);+ bool singleToken(_LogicalLine line) =>+ lookup?.tokens(line).single ?? _singleToken(line);+ bool continuesUrl(_LogicalLine line) =>+ lookup?.tokens(line).continues ?? _continuesUrl(line);+ final own = lineAt(cell.y);if (own == null || own.offset == null) return null;- final single = terminalLinkInText(own.text, own.offset!);+ final single = _terminalLinkInText(own.text, own.offset!, lookup);// Which way the rest of the address lies is read off the pointer: on the// row's opening token it may be a carried tail, so look above; on an// address the row breaks off in, look below. A row that is one token from// indent to end may be the middle of one, and is followed both ways.bool mayJoin(_LogicalLine a, _LogicalLine b) =>- _continuesUrl(b) &&- (_paintContinues(a, b) || _cutAtBoxWidth(terminal, a));+ continuesUrl(b) && (_paintContinues(a, b) || cutAtBoxWidth(a));final joined = [own];final at = own.offset!;- final cutAt = _urlCutAt(own.text);+ final cutAt = urlCutAt(own.text);final onOpeningToken =- at >= own.leadingBlanks && at < own.leadingBlanks + _tokenLength(own);- if (onOpeningToken && _continuesUrl(own)) {+ at >= own.leadingBlanks &&+ at <+ own.leadingBlanks + (lookup?.tokens(own).length ?? _tokenLength(own));+ if (onOpeningToken && continuesUrl(own)) {while (joined.first.firstRow > 0 && joined.length < _hardWrapRows) {- final previous = _logicalLine(terminal, joined.first.firstRow - 1, cell);+ final previous = lineAt(joined.first.firstRow - 1);if (previous == null || !mayJoin(previous, joined.first)) break;// Above a carried row sits either the row the address starts on or// another row of nothing but address; anything else ends the search.- final head = _urlCutAt(previous.text) != null;- if (!head && !_singleToken(previous)) break;+ final head = urlCutAt(previous.text) != null;+ if (!head && !singleToken(previous)) break;joined.insert(0, previous);if (head) break;}}- if ((cutAt != null && at >= cutAt) || _singleToken(own)) {+ if ((cutAt != null && at >= cutAt) || singleToken(own)) {while (joined.last.lastRow + 1 < lines.length) {- final next = _logicalLine(terminal, joined.last.lastRow + 1, cell);+ final next = lineAt(joined.last.lastRow + 1);if (next == null ||!mayJoin(joined.last, next) ||- _urlCutAt(_splice(joined, null)?.$1 ?? '') == null) {+ urlCutAt(_splice(joined, null)?.$1 ?? '') == null) {break;}// Past the bound the address is unknowable, and a fragment of it would@@ -390,16 +547,18 @@ String? terminalLinkAt(Terminal terminal, CellOffset cell) {if (joined.length >= _hardWrapRows) return null;joined.add(next);// The row the address ends on has words after it; nothing follows.- if (!_singleToken(next)) break;+ if (!singleToken(next)) break;}}- if (joined.length == 1 || !_cutThroughout(terminal, joined)) return single;+ if (joined.length == 1 || !_cutThroughout(terminal, joined, lookup)) {+ return single;+ }final spliced = _splice(joined, own);if (spliced == null) return single;final (text, offset) = spliced;if (offset == null) return single;- final target = terminalLinkInText(text, offset);+ final target = _terminalLinkInText(text, offset, lookup);if (target == null) return single;final scheme = Uri.tryParse(target)?.scheme;return scheme == 'http' || scheme == 'https' ? target : single;@@ -421,9 +580,10 @@ List<TerminalLinkSpan> terminalLinkSpans(final lines = terminal.buffer.lines;if (cell.y < 0 || cell.y >= lines.length) return const [];final osc8 = lines[cell.y].getHyperlink(cell.x) == target;+ final lookup = osc8 ? null : _LinkLookup(terminal);bool hit(int x, int y) => osc8? lines[y].getHyperlink(x) == target- : terminalLinkAt(terminal, CellOffset(x, y)) == target;+ : _terminalLinkAt(terminal, CellOffset(x, y), lookup) == target;TerminalLinkSpan? walk(int y, int x) {if (y < 0 || y >= lines.length || x < 0 || !hit(x, y)) return null;final width = lines[y].length;diff --git a/desktop/test/benchmarks/terminal_links_benchmark.dart b/desktop/test/benchmarks/terminal_links_benchmark.dartnew file mode 100644index 000000000..a09349e1a--- /dev/null+++ b/desktop/test/benchmarks/terminal_links_benchmark.dart@@ -0,0 +1,7 @@+import 'package:flutter_test/flutter_test.dart';++import '../../tool/terminal_links_benchmark.dart' as benchmark;++void main() {+ test('terminal link hit-testing benchmark', benchmark.runLinkBenchmark);+}diff --git a/desktop/test/bios_navigation_test.dart b/desktop/test/bios_navigation_test.dartindex ed7871162..02cf2c854 100644--- a/desktop/test/bios_navigation_test.dart+++ b/desktop/test/bios_navigation_test.dart@@ -11,130 +11,133 @@ void main() {'Open Harness sorts by activity as it opened, and keeps that order while open',(tester) async {final app = createApp();- addTearDown(app.dispose);- app.machineStates['m']!.agents = [- for (final (id, hour) in [- ('a1', 10),- ('a10', 12),- ('a11', 11),- ('a12', null),- ])- Agent(- id: id,- sessionId: 'session-$id',- name: 'Agent ${id.substring(1)}',- engine: 'codex',- terminalAvailable: true,- lastActivityAt: hour == null- ? null- : DateTime.utc(2026, 9, 23, hour),- ),- ];- final recent = [- agentDestinationId('m', 'a1'),- agentDestinationId('m', 'a12'),- agentDestinationId('m', 'a10'),- ];- final search = SwarmSearchController(- app,- recent,- adding: true,- offersCreate: true,- activityFirst: true,- placement: HarnessPlacement.newTab,- );- addTearDown(search.dispose);- expect(search.setupLayout, isTrue);- expect(search.rows.first.isCreate, isTrue);- expect(search.rows.skip(1).map((row) => row.agentId), [- 'a10',- 'a11',- 'a1',- 'a12',- ]);- search.setQuery('Agent 1');- // The harness named exactly that leads; the rest keep activity order.- expect(- search.rows.where((row) => !row.isCreate).map((row) => row.agentId),- ['a1', 'a10', 'a11', 'a12'],- );+ try {+ app.machineStates['m']!.agents = [+ for (final (id, hour) in [+ ('a1', 10),+ ('a10', 12),+ ('a11', 11),+ ('a12', null),+ ])+ Agent(+ id: id,+ sessionId: 'session-$id',+ name: 'Agent ${id.substring(1)}',+ engine: 'codex',+ terminalAvailable: true,+ lastActivityAt: hour == null+ ? null+ : DateTime.utc(2026, 9, 23, hour),+ ),+ ];+ final recent = [+ agentDestinationId('m', 'a1'),+ agentDestinationId('m', 'a12'),+ agentDestinationId('m', 'a10'),+ ];+ final search = SwarmSearchController(+ app,+ recent,+ adding: true,+ offersCreate: true,+ activityFirst: true,+ placement: HarnessPlacement.newTab,+ );+ addTearDown(search.dispose);+ expect(search.setupLayout, isTrue);+ expect(search.rows.first.isCreate, isTrue);+ expect(search.rows.skip(1).map((row) => row.agentId), [+ 'a10',+ 'a11',+ 'a1',+ 'a12',+ ]);+ search.setQuery('Agent 1');+ // The harness named exactly that leads; the rest keep activity order.+ expect(+ search.rows.where((row) => !row.isCreate).map((row) => row.agentId),+ ['a1', 'a10', 'a11', 'a12'],+ );- final ordinary = SwarmSearchController(app, recent, adding: true);- addTearDown(ordinary.dispose);- ordinary.setQuery('Agent 1');- expect(ordinary.setupLayout, isFalse);- expect(ordinary.rows.first.agentId, 'a1');+ final ordinary = SwarmSearchController(app, recent, adding: true);+ addTearDown(ordinary.dispose);+ ordinary.setQuery('Agent 1');+ expect(ordinary.setupLayout, isFalse);+ expect(ordinary.rows.first.agentId, 'a1');- final selected = search.selected!.id;- await app.handleEventForTest('m', {- 'type': 'agent_synced',- 'payload': {- 'agent': {- 'id': 'a1',- 'sessionId': 'session-a1',- 'name': 'Agent 1',- 'engine': 'codex',- 'terminal': {'available': true},- 'updatedAt': '2026-09-23T12:00:30Z',- },- },- });- // Agent 1 just worked, but the open list does not move under the cursor.- expect(search.rows.first.isCreate, isTrue);- expect(search.rows.skip(1).map((row) => row.agentId), [- 'a1',- 'a10',- 'a11',- 'a12',- ]);- expect(search.selected!.id, selected);- search.setQuery('');- expect(search.rows.skip(1).map((row) => row.agentId), [- 'a10',- 'a11',- 'a1',- 'a12',- ]);- // The next opening reads activity afresh.- final reopened = SwarmSearchController(- app,- recent,- adding: true,- offersCreate: true,- activityFirst: true,- placement: HarnessPlacement.newTab,- );- addTearDown(reopened.dispose);- expect(reopened.rows.skip(1).map((row) => row.agentId), [- 'a1',- 'a10',- 'a11',- 'a12',- ]);-- search.setQuery('retry-safe');- expect(search.rows.every((row) => row.isCreate), isTrue);- Future<void> response(String id) async {+ final selected = search.selected!.id;await app.handleEventForTest('m', {- 'type': 'text_delta',+ 'type': 'agent_synced','payload': {- 'agentId': id,- 'sessionId': 'session-$id',- 'content': 'The operation is now retry-safe.',+ 'agent': {+ 'id': 'a1',+ 'sessionId': 'session-a1',+ 'name': 'Agent 1',+ 'engine': 'codex',+ 'terminal': {'available': true},+ 'updatedAt': '2026-09-23T12:00:30Z',+ },},});- await tester.pump(const Duration(milliseconds: 80));- }+ // Agent 1 just worked, but the open list does not move under the cursor.+ expect(search.rows.first.isCreate, isTrue);+ expect(search.rows.skip(1).map((row) => row.agentId), [+ 'a1',+ 'a10',+ 'a11',+ 'a12',+ ]);+ expect(search.selected!.id, selected);+ search.setQuery('');+ expect(search.rows.skip(1).map((row) => row.agentId), [+ 'a10',+ 'a11',+ 'a1',+ 'a12',+ ]);+ // The next opening reads activity afresh.+ final reopened = SwarmSearchController(+ app,+ recent,+ adding: true,+ offersCreate: true,+ activityFirst: true,+ placement: HarnessPlacement.newTab,+ );+ addTearDown(reopened.dispose);+ expect(reopened.rows.skip(1).map((row) => row.agentId), [+ 'a1',+ 'a10',+ 'a11',+ 'a12',+ ]);- await response('a11');- search.move(1);- expect(search.selected!.agentId, 'a11');- await response('a1');- // Found now too, in the order this opening listed them.- expect(search.rows.skip(1).map((row) => row.agentId), ['a11', 'a1']);- expect(search.selected!.agentId, 'a11');- search.setQuery('>');- expect(search.setupLayout, isTrue);+ search.setQuery('retry-safe');+ expect(search.rows.every((row) => row.isCreate), isTrue);+ Future<void> response(String id) async {+ await app.handleEventForTest('m', {+ 'type': 'text_delta',+ 'payload': {+ 'agentId': id,+ 'sessionId': 'session-$id',+ 'content': 'The operation is now retry-safe.',+ },+ });+ await tester.pump(const Duration(milliseconds: 80));+ }++ await response('a11');+ search.move(1);+ expect(search.selected!.agentId, 'a11');+ await response('a1');+ // Found now too, in the order this opening listed them.+ expect(search.rows.skip(1).map((row) => row.agentId), ['a11', 'a1']);+ expect(search.selected!.agentId, 'a11');+ search.setQuery('>');+ expect(search.setupLayout, isTrue);+ } finally {+ app.dispose();+ }},);diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dartindex b050c5c0d..35b387404 100644--- a/desktop/test/search_workspace_test.dart+++ b/desktop/test/search_workspace_test.dart@@ -76,7 +76,7 @@ void main() {expect(input, isEmpty);}- await checkHints('Search harnesses · ⌘P', 'Explore Harness Store · ⌘S');+ await checkHints('Open Harness · ⌘P', 'Explore Harness Store · ⌘S');map.apply('''{"bindings":[{"keys":"cmd+p","command":null},{"keys":"cmd+s","command":null},@@ -84,16 +84,13 @@ void main() {{"keys":"cmd+shift+s","command":"app.store"}]}''');await tester.pump();- await checkHints(- 'Search harnesses · ⌘K',- 'Explore Harness Store · ⇧⌘S',- );+ await checkHints('Open Harness · ⌘K', 'Explore Harness Store · ⇧⌘S');map.apply('''{"bindings":[{"keys":"cmd+p","command":null},{"keys":"cmd+s","command":null}]}''');await tester.pump();- await checkHints('Search harnesses', 'Explore Harness Store');+ await checkHints('Open Harness', 'Explore Harness Store');await mouse.removePointer();await tester.pumpWidget(const SizedBox());app.dispose();diff --git a/desktop/test/terminal_links_test.dart b/desktop/test/terminal_links_test.dartindex eaadf1186..f27eae56c 100644--- a/desktop/test/terminal_links_test.dart+++ b/desktop/test/terminal_links_test.dart@@ -109,6 +109,126 @@ void main() {);});+ test(+ 'bare media suffix precheck keeps every supported extension and boundary',+ () {+ for (final extension in [+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'webp',+ 'avif',+ 'heic',+ 'heif',+ 'bmp',+ 'tif',+ 'tiff',+ 'svg',+ 'ico',+ 'mp4',+ 'm4v',+ 'mov',+ 'webm',+ 'mkv',+ 'avi',+ 'mpg',+ 'mpeg',+ 'ogv',+ '3gp',+ ]) {+ for (final suffix in [+ '',+ ' ',+ ')',+ ']',+ '}',+ '>',+ '.',+ ',',+ ';',+ ':',+ '!',+ '?',+ ]) {+ final path = '/tmp/preview.${extension.toUpperCase()}';+ expect(terminalLinkInText('Saved $path$suffix', 9), path);+ }+ }+ expect(terminalLinkInText('/tmp/not.pngz', 5), isNull);+ expect(terminalLinkInText('a' * 2048, 1024), isNull);+ },+ );++ test('underline includes both cells of wide glyphs across soft wraps', () {+ const target = '/tmp/图😀.png';+ final terminal = Terminal()..resize(10, 4);+ terminal.write('`$target`');+ for (final cell in [+ const CellOffset(6, 0),+ const CellOffset(7, 0),+ const CellOffset(8, 0),+ const CellOffset(9, 0),+ const CellOffset(2, 1),+ ]) {+ expect(terminalLinkSpans(terminal, cell, target), [+ (row: 0, start: 0, end: 9),+ (row: 1, start: 0, end: 4),+ ], reason: '$cell');+ }+ });++ test('relative paths keep their token boundaries and adjacent matches', () {+ const text = 'a.png)b.jpg]c.gif>d.mp4 prefix=one.png';+ for (final path in ['a.png', 'b.jpg', 'c.gif', 'd.mp4', 'prefix=one.png']) {+ expect(terminalLinkInText(text, text.indexOf(path)), path);+ }+ for (final delimiter in [')', ']', '>']) {+ expect(terminalLinkInText(text, text.indexOf(delimiter)), isNull);+ }+ final adjacent = '${'a' * 2048} image.png';+ expect(terminalLinkInText(adjacent, 1024), isNull);+ expect(terminalLinkInText(adjacent, 2052), 'image.png');+ expect(terminalLinkInText('command:one.png', 10), isNull);+ });++ test('equal URLs separated by text retain separate underline extents', () {+ const target = 'https://e.co';+ final terminal = Terminal()..resize(60, 4);+ terminal.write('$target | $target');+ expect(terminalLinkSpans(terminal, const CellOffset(2, 0), target), [+ (row: 0, start: 0, end: 11),+ ]);+ expect(terminalLinkSpans(terminal, const CellOffset(17, 0), target), [+ (row: 0, start: 15, end: 26),+ ]);+ });++ test(+ 'extent memoization never survives output or alternate-buffer changes',+ () {+ const first = 'https://one.example';+ const second = '/tmp/two.png';+ const cell = CellOffset(3, 0);+ final terminal = Terminal()..resize(60, 4);+ terminal.write(first);+ expect(terminalLinkSpans(terminal, cell, first), [+ (row: 0, start: 0, end: first.length - 1),+ ]);+ terminal.write('\r\x1b[2K$second');+ expect(terminalLinkSpans(terminal, cell, first), isEmpty);+ expect(terminalLinkSpans(terminal, cell, second), [+ (row: 0, start: 0, end: second.length - 1),+ ]);+ terminal.write('\x1b[?1049hplain');+ expect(terminalLinkSpans(terminal, cell, second), isEmpty);+ terminal.write('\x1b[?1049l');+ expect(terminalLinkSpans(terminal, cell, second), [+ (row: 0, start: 0, end: second.length - 1),+ ]);+ },+ );+group('OSC 8 hyperlinks', () {// Claude Code's table cell for `[!125](…/merge_requests/125)`, as tmux// hands it over: the label is shown, the address rides in OSC 8.@@ -191,6 +311,37 @@ void main() {return terminal;}+ for (final (style, indent) in [('4', ''), ('94', ' ')]) {+ test('joins a standalone painted URL without a label (SGR $style)', () {+ const head = 'https://example.com/';+ const tail = 'path/image.png';+ final terminal = ink([+ 'A wider unrelated tool heading precedes the URL',+ '$indent\x1b[${style}m$head\x1b[0m',+ '$indent\x1b[${style}m$tail\x1b[0m',+ 'The next sentence is ordinary output.',+ ], width: 60);+ const target = '$head$tail';+ for (final row in [1, 2]) {+ final cell = CellOffset(indent.length + 3, row);+ expect(terminalLinkAt(terminal, cell), target);+ expect(terminalLinkSpans(terminal, cell, target), [+ (+ row: 1,+ start: indent.length,+ end: indent.length + head.length - 1,+ ),+ (+ row: 2,+ start: indent.length,+ end: indent.length + tail.length - 1,+ ),+ ]);+ }+ expect(terminalLinkAt(terminal, const CellOffset(3, 3)), isNull);+ });+ }+test('spans every row of a cut URL for the hover underline', () {final terminal = ink([' Command Code here: https://commandc',diff --git a/desktop/test/workspace_event_isolation_test.dart b/desktop/test/workspace_event_isolation_test.dartindex 9e329201d..6a69e6368 100644--- a/desktop/test/workspace_event_isolation_test.dart+++ b/desktop/test/workspace_event_isolation_test.dart@@ -149,17 +149,33 @@ void main() {}testWidgets(- 'quiet heartbeats renew the watchdog and expiry still publishes',+ 'fresh heartbeat evidence renews the watchdog without workspace redraws',(tester) async {final app = createApp();addTearDown(app.dispose);var notifications = 0;app.addListener(() => notifications++);- await _event(app, 'turn_heartbeat', {'agentId': 'a0'});+ await _event(app, 'turn_heartbeat', {+ 'agentId': 'a0',+ 'activity': {+ 'state': 'working',+ 'epoch': 'fixture-daemon',+ 'revision': 1,+ 'validForMs': 12000,+ },+ });expect(app.agentIsProcessing('m', 'a0'), isTrue);expect(notifications, 1);await tester.pump(const Duration(seconds: 8));- await _event(app, 'turn_heartbeat', {'agentId': 'a0'});+ await _event(app, 'turn_heartbeat', {+ 'agentId': 'a0',+ 'activity': {+ 'state': 'working',+ 'epoch': 'fixture-daemon',+ 'revision': 2,+ 'validForMs': 12000,+ },+ });await tester.pump(const Duration(seconds: 8));expect(app.agentIsProcessing('m', 'a0'), isTrue);expect(notifications, 1);diff --git a/desktop/tool/benchmark_terminal_links.py b/desktop/tool/benchmark_terminal_links.pynew file mode 100644index 000000000..8961737fd--- /dev/null+++ b/desktop/tool/benchmark_terminal_links.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Compare a Git baseline and working-tree link matcher in one Dart process."""+import argparse+import hashlib+import json+import os+from pathlib import Path+import subprocess+import tempfile++parser = argparse.ArgumentParser(description=__doc__)+parser.add_argument('--flutter', required=True, type=Path)+parser.add_argument('--baseline', required=True)+parser.add_argument('--output', required=True, type=Path)+parser.add_argument('--aot', action='store_true', help='Compile both matchers into one native Dart executable')+args = parser.parse_args()+desktop = Path(__file__).resolve().parents[1]+source = desktop / 'lib/terminal/terminal_links.dart'+output = args.output.resolve()+if output.exists():+ parser.error('Output already exists')+revision = subprocess.check_output(+ ['git', 'rev-parse', '--verify', f'{args.baseline}^{{commit}}'],+ cwd=desktop, text=True,+).strip()+baseline = subprocess.check_output(+ ['git', 'show', f'{revision}:desktop/lib/terminal/terminal_links.dart'],+ cwd=desktop,+)+candidate = source.read_bytes()+fixture = desktop / 'tool/terminal_links_benchmark.dart'+fixture_source = fixture.read_bytes()+with tempfile.TemporaryDirectory(prefix='harness-terminal-links-') as temp:+ root = Path(temp)+ # Only the import changes: core.dart exports the same terminal types,+ # without pulling Flutter UI into this headless benchmark executable.+ adapted_baseline = baseline.replace(+ b"import 'package:xterm/xterm.dart';",+ b"import 'package:xterm/core.dart';",+ )+ (root / 'before.dart').write_bytes(adapted_baseline)+ (root / 'comparison_test.dart').write_text(+ "import 'before.dart' as before;\n"+ f"import '{fixture.as_uri()}' as fixture;\n"+ 'void main() => fixture.runLinkBenchmark(implementations: [\n'+ " fixture.LinkImplementation('baseline', before.terminalLinkInText,\n"+ ' before.terminalLinkAt, before.terminalLinkSpans),\n'+ ' fixture.currentLinks,\n'+ ']);\n'+ )+ env = dict(os.environ, HARNESS_LINK_BENCH_OUTPUT=str(output))+ dart = str(args.flutter / 'bin/cache/dart-sdk/bin/dart')+ packages = str(desktop / '.dart_tool/package_config.json')+ if args.aot:+ executable = root / 'comparison'+ subprocess.run([+ dart, 'compile', 'exe', f'--packages={packages}',+ str(root / 'comparison_test.dart'), '-o', str(executable),+ ], cwd=desktop, check=True)+ command = [str(executable)]+ else:+ command = [dart, f'--packages={packages}', str(root / 'comparison_test.dart')]+ subprocess.run(command, cwd=desktop, env=env, check=True)+if source.read_bytes() != candidate:+ raise RuntimeError('Candidate source changed during the comparison')+if fixture.read_bytes() != fixture_source:+ raise RuntimeError('Benchmark source changed during the comparison')+result = json.loads(output.read_text())+result['boundary'] = f"headless Dart {'AOT' if args.aot else 'JIT'} synchronous hit-testing elapsed time"+result['source'] = {+ 'baselineCommit': revision,+ 'baselineSha256': hashlib.sha256(baseline).hexdigest(),+ 'baselineImportAdaptation': 'xterm.dart umbrella export replaced with core.dart; no executable baseline code changes',+ 'adaptedBaselineSha256': hashlib.sha256(adapted_baseline).hexdigest(),+ 'candidateSha256': hashlib.sha256(candidate).hexdigest(),+ 'fixtureSha256': hashlib.sha256(fixture_source).hexdigest(),+ 'dependencies': 'Both implementations use current-worktree Flutter/xterm dependencies',+}+output.write_text(json.dumps(result, indent=2) + '\n')diff --git a/desktop/tool/terminal_links_benchmark.dart b/desktop/tool/terminal_links_benchmark.dartnew file mode 100644index 000000000..4cf79d6b0--- /dev/null+++ b/desktop/tool/terminal_links_benchmark.dart@@ -0,0 +1,242 @@+// Synchronous link hit-testing only. Excludes terminal rendering, pointer+// dispatch, network access, and whole-app CPU or battery consumption.+import 'dart:convert';+import 'dart:io';+import 'dart:math';++import 'package:collection/collection.dart';+import 'package:harness/terminal/terminal_links.dart';+import 'package:xterm/core.dart';++class LinkImplementation {+ const LinkImplementation(this.name, this.inText, this.at, this.spans);+ final String name;+ final String? Function(String, int) inText;+ final String? Function(Terminal, CellOffset) at;+ final List<TerminalLinkSpan> Function(Terminal, CellOffset, String) spans;+}++const currentLinks = LinkImplementation(+ 'candidate',+ terminalLinkInText,+ terminalLinkAt,+ terminalLinkSpans,+);++void main() => runLinkBenchmark();++void checkEqual(Object? actual, Object? expected, {String? reason}) {+ if (!const DeepCollectionEquality().equals(actual, expected)) {+ throw StateError(+ '${reason ?? 'Link validation failed'}: $actual != $expected',+ );+ }+}++void runChecked(String name, void Function() run) {+ run();+ stdout.writeln('LINK_BENCH_CHECK passed: $name');+}++void runLinkBenchmark({+ List<LinkImplementation> implementations = const [currentLinks],+}) {+ final equivalence = <String, int>{};+ if (implementations.length == 2) {+ runChecked(+ 'matches reference targets and extents through output and resize',+ () {+ final random = Random(551551);+ const fragments = [+ 'ordinary_text',+ 'a.png',+ '/tmp/My image.PNG',+ '~/out/video.mp4',+ 'https://example.com/a_(b)?x=1',+ 'https://example.com/a.',+ '[Image](/tmp/image.webp)',+ '[no](command:run.png)',+ '`/tmp/ảnh 🖼️.png`',+ '<https://example.com/x>',+ '图 😀',+ '[',+ ']',+ '(',+ ')',+ '.',+ '/',+ ' ',+ '\t',+ 'javascript:alert(1)',+ 'https://bad[',+ 'clip.movz',+ ];+ final before = implementations.first;+ final after = implementations.last;+ var textChecks = 0, cellChecks = 0, spanChecks = 0;+ for (var sample = 0; sample < 400; sample++) {+ final text = List.generate(+ 2 + random.nextInt(6),+ (_) => fragments[random.nextInt(fragments.length)],+ ).join(' ');+ for (var at = -1; at <= text.length; at += 7) {+ checkEqual(+ after.inText(text, at),+ before.inText(text, at),+ reason: 'text sample $sample, offset $at: $text',+ );+ textChecks++;+ }+ final terminal = Terminal(maxLines: 100)+ ..resize([12, 20, 44, 120][random.nextInt(4)], 12);+ terminal.write(sample.isEven ? '\x1b[94m$text\x1b[0m' : text);+ for (var revision = 0; revision < 2; revision++) {+ final lines = terminal.buffer.lines;+ for (var point = 0; point < 8; point++) {+ final row = random.nextInt(lines.length);+ final cell = CellOffset(random.nextInt(lines[row].length), row);+ final target = before.at(terminal, cell);+ checkEqual(+ after.at(terminal, cell),+ target,+ reason: 'cell sample $sample revision $revision at $cell',+ );+ cellChecks++;+ if (target != null) {+ checkEqual(+ after.spans(terminal, cell, target),+ before.spans(terminal, cell, target),+ reason: 'extent sample $sample revision $revision at $cell',+ );+ spanChecks++;+ }+ }+ terminal.write(+ '\r\x1b[2K\x1b]8;;https://example.com/changed\x1b\\new link\x1b]8;;\x1b\\',+ );+ terminal.resize(24 + random.nextInt(80), 12);+ }+ }+ equivalence.addAll({+ 'textChecks': textChecks,+ 'cellChecks': cellChecks,+ 'spanChecks': spanChecks,+ 'seed': 551551,+ 'fixtures': 400,+ });+ stdout.writeln('TERMINAL_LINK_EQUIVALENCE ${jsonEncode(equivalence)}');+ },+ );+ }+ runChecked('terminal link hit-testing benchmark', () {+ final results = <Map<String, Object>>[];++ void measure(+ String name,+ void Function(LinkImplementation) operation, {+ int batch = 10,+ }) {+ // Alternate implementations within every sample to reduce ordering bias.+ for (var i = 0; i < 20; i++) {+ for (final implementation in implementations) {+ operation(implementation);+ }+ }+ final samples = {+ for (final implementation in implementations)+ implementation.name: <double>[],+ };+ for (var i = 0; i < 30; i++) {+ for (final implementation+ in i.isEven ? implementations : implementations.reversed) {+ final watch = Stopwatch()..start();+ for (var j = 0; j < batch; j++) {+ operation(implementation);+ }+ watch.stop();+ samples[implementation.name]!.add(watch.elapsedMicroseconds / batch);+ }+ }+ for (final entry in samples.entries) {+ final sorted = entry.value.toList()..sort();+ final result = <String, Object>{+ 'case': name,+ 'implementation': entry.key,+ 'batch': batch,+ 'samplesMicrosPerOperation': entry.value,+ 'medianMicros': sorted[sorted.length ~/ 2],+ 'p95Micros': sorted[(sorted.length * .95).ceil() - 1],+ };+ results.add(result);+ stdout.writeln('TERMINAL_LINK_BENCH ${jsonEncode(result)}');+ }+ }++ for (final length in [80, 512, 2048]) {+ final text = 'a' * length;+ checkEqual(terminalLinkInText(text, length ~/ 2), null);+ measure('plain_token_$length', (implementation) {+ if (implementation.inText(text, length ~/ 2) != null) {+ throw StateError('Ordinary text became a link');+ }+ });+ }++ final adjacent = '${'a' * 2048} image.png';+ for (final implementation in implementations) {+ checkEqual(implementation.inText(adjacent, 1024), null);+ checkEqual(implementation.inText(adjacent, 2052), 'image.png');+ }+ measure('plain_token_beside_media_2048', (implementation) {+ if (implementation.inText(adjacent, 1024) != null) {+ throw StateError('Ordinary neighboring text became a link');+ }+ });++ for (final length in [40, 160, 1000]) {+ final target = 'https://example.com/${'a' * length}';+ final terminal = Terminal()..resize(120, 20);+ terminal.write(target);+ const cell = CellOffset(10, 0);+ checkEqual(terminalLinkAt(terminal, cell), target);+ final expectedSpans = [+ for (var offset = 0; offset < target.length; offset += 120)+ (+ row: offset ~/ 120,+ start: 0,+ end: (target.length - offset - 1).clamp(0, 119),+ ),+ ];+ checkEqual(terminalLinkSpans(terminal, cell, target), expectedSpans);+ measure('url_lookup_$length', (implementation) {+ if (implementation.at(terminal, cell) != target) {+ throw StateError('Incorrect URL');+ }+ });+ measure('url_extent_$length', (implementation) {+ final spans = implementation.spans(terminal, cell, target);+ if (spans.length != expectedSpans.length ||+ spans.last != expectedSpans.last) {+ throw StateError('Incorrect URL extent');+ }+ }, batch: length == 1000 ? 1 : 5);+ }++ final output = Platform.environment['HARNESS_LINK_BENCH_OUTPUT'];+ if (output != null) {+ final file = File(output);+ if (file.existsSync()) throw StateError('Output already exists: $output');+ file.writeAsStringSync(+ const JsonEncoder.withIndent(' ').convert({+ 'schema': 1,+ 'recordedAt': DateTime.now().toUtc().toIso8601String(),+ 'boundary': 'headless synchronous hit-testing elapsed time; runtime supplied by comparison runner',+ 'dartVersion': Platform.version,+ 'operatingSystem': Platform.operatingSystem,+ 'equivalence': equivalence,+ 'results': results,+ }),+ );+ }+ });+}diff --git a/docs/performance/2026-10-01-terminal-link-hit-testing.json b/docs/performance/2026-10-01-terminal-link-hit-testing.jsonnew file mode 100644index 000000000..b1b827426--- /dev/null+++ b/docs/performance/2026-10-01-terminal-link-hit-testing.json@@ -0,0 +1,831 @@+{+ "schema": 1,+ "recordedAt": "2026-10-01T15:28:05.944348Z",+ "boundary": "headless Dart AOT synchronous hit-testing elapsed time",+ "dartVersion": "3.13.2 (stable) (Tue Aug 25 01:01:12 2026 -0700) on \"macos_arm64\"",+ "operatingSystem": "macos",+ "equivalence": {+ "textChecks": 3468,+ "cellChecks": 6400,+ "spanChecks": 505,+ "seed": 551551,+ "fixtures": 400+ },+ "results": [+ {+ "case": "plain_token_80",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 86.3,+ 80.8,+ 77.2,+ 71.0,+ 73.9,+ 73.7,+ 73.1,+ 77.9,+ 74.0,+ 77.0,+ 78.7,+ 74.5,+ 74.1,+ 74.2,+ 73.3,+ 73.6,+ 73.6,+ 74.4,+ 74.4,+ 73.4,+ 75.4,+ 77.7,+ 75.9,+ 78.7,+ 91.1,+ 90.5,+ 88.9,+ 89.2,+ 90.2,+ 88.8+ ],+ "medianMicros": 75.9,+ "p95Micros": 90.5+ },+ {+ "case": "plain_token_80",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 4.0,+ 4.1,+ 3.7,+ 3.6,+ 3.8,+ 3.8,+ 4.5,+ 3.7,+ 4.2,+ 3.8,+ 3.9,+ 3.9,+ 3.9,+ 3.8,+ 3.8,+ 3.8,+ 3.8,+ 3.9,+ 3.8,+ 3.8,+ 3.9,+ 3.9,+ 3.8,+ 4.2,+ 4.8,+ 4.3,+ 4.6,+ 4.5,+ 4.8,+ 4.5+ ],+ "medianMicros": 3.9,+ "p95Micros": 4.8+ },+ {+ "case": "plain_token_512",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 2761.2,+ 2751.8,+ 2766.3,+ 2819.5,+ 2804.4,+ 2749.9,+ 2746.0,+ 2740.4,+ 2775.3,+ 3080.4,+ 2686.6,+ 2650.4,+ 2653.5,+ 2697.9,+ 2742.8,+ 2724.8,+ 2696.7,+ 2736.6,+ 2787.3,+ 2797.2,+ 2762.0,+ 2716.7,+ 2729.3,+ 2796.0,+ 2719.4,+ 2721.7,+ 2807.7,+ 2712.2,+ 2729.5,+ 2758.4+ ],+ "medianMicros": 2746.0,+ "p95Micros": 2819.5+ },+ {+ "case": "plain_token_512",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 22.2,+ 22.3,+ 22.0,+ 23.3,+ 22.2,+ 22.1,+ 23.3,+ 22.7,+ 23.1,+ 22.7,+ 21.8,+ 21.7,+ 21.8,+ 21.7,+ 23.2,+ 22.9,+ 22.1,+ 22.0,+ 22.1,+ 22.1,+ 22.5,+ 22.1,+ 23.7,+ 22.9,+ 21.9,+ 21.7,+ 22.2,+ 21.7,+ 22.1,+ 22.1+ ],+ "medianMicros": 22.1,+ "p95Micros": 23.3+ },+ {+ "case": "plain_token_2048",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 43857.5,+ 43193.6,+ 43293.4,+ 43792.5,+ 43962.3,+ 44588.5,+ 44606.6,+ 45614.4,+ 44867.6,+ 44848.7,+ 44627.7,+ 44662.5,+ 44149.8,+ 43194.4,+ 43614.2,+ 43400.3,+ 43060.1,+ 43876.9,+ 44945.2,+ 43813.1,+ 43772.6,+ 43732.0,+ 43055.1,+ 42865.5,+ 43507.8,+ 43026.2,+ 43214.9,+ 43280.7,+ 43361.3,+ 43634.4+ ],+ "medianMicros": 43772.6,+ "p95Micros": 44945.2+ },+ {+ "case": "plain_token_2048",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 87.8,+ 88.2,+ 89.0,+ 94.4,+ 86.1,+ 85.8,+ 88.6,+ 88.9,+ 92.7,+ 92.3,+ 89.9,+ 88.8,+ 89.3,+ 90.5,+ 85.9,+ 85.8,+ 86.9,+ 86.6,+ 85.9,+ 86.4,+ 88.9,+ 87.6,+ 87.1,+ 86.3,+ 86.1,+ 85.7,+ 86.6,+ 89.2,+ 91.9,+ 91.1+ ],+ "medianMicros": 88.2,+ "p95Micros": 92.7+ },+ {+ "case": "plain_token_beside_media_2048",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 43618.7,+ 43503.3,+ 43452.6,+ 43352.6,+ 43338.8,+ 43406.6,+ 43354.2,+ 43430.4,+ 43590.0,+ 44019.5,+ 43284.1,+ 43068.9,+ 43003.7,+ 43132.4,+ 43555.2,+ 43316.7,+ 43273.8,+ 42980.8,+ 43691.2,+ 43374.4,+ 44274.3,+ 44087.2,+ 44038.8,+ 43800.6,+ 44229.5,+ 44185.5,+ 43882.8,+ 43378.2,+ 43963.9,+ 43651.7+ ],+ "medianMicros": 43503.3,+ "p95Micros": 44229.5+ },+ {+ "case": "plain_token_beside_media_2048",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 202.9,+ 196.7,+ 204.0,+ 197.7,+ 195.9,+ 208.0,+ 199.2,+ 202.0,+ 199.0,+ 196.1,+ 199.6,+ 198.4,+ 197.7,+ 194.4,+ 203.9,+ 208.2,+ 198.6,+ 195.5,+ 204.3,+ 204.6,+ 205.5,+ 202.6,+ 199.3,+ 193.6,+ 195.5,+ 193.2,+ 199.8,+ 197.4,+ 213.2,+ 198.5+ ],+ "medianMicros": 199.2,+ "p95Micros": 208.2+ },+ {+ "case": "url_lookup_40",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 15.1,+ 14.8,+ 14.9,+ 14.8,+ 14.7,+ 14.9,+ 14.7,+ 14.9,+ 14.9,+ 14.9,+ 14.9,+ 14.9,+ 14.9,+ 14.8,+ 14.7,+ 14.8,+ 14.9,+ 14.9,+ 14.9,+ 24.9,+ 14.8,+ 15.1,+ 15.2,+ 15.6,+ 15.3,+ 16.0,+ 15.9,+ 15.0,+ 16.5,+ 15.8+ ],+ "medianMicros": 14.9,+ "p95Micros": 16.5+ },+ {+ "case": "url_lookup_40",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 15.2,+ 15.2,+ 15.3,+ 15.2,+ 15.2,+ 15.1,+ 15.1,+ 24.7,+ 15.2,+ 15.2,+ 15.1,+ 15.2,+ 15.1,+ 14.9,+ 15.0,+ 14.9,+ 15.3,+ 15.2,+ 15.2,+ 15.3,+ 14.9,+ 14.2,+ 15.4,+ 18.3,+ 15.7,+ 15.2,+ 16.0,+ 15.1,+ 15.3,+ 16.3+ ],+ "medianMicros": 15.2,+ "p95Micros": 18.3+ },+ {+ "case": "url_extent_40",+ "implementation": "baseline",+ "batch": 5,+ "samplesMicrosPerOperation": [+ 996.0,+ 976.2,+ 994.4,+ 1004.8,+ 1023.6,+ 1004.8,+ 1023.2,+ 1043.0,+ 1034.4,+ 1035.4,+ 1031.0,+ 990.8,+ 987.2,+ 1011.2,+ 997.0,+ 990.0,+ 989.0,+ 996.0,+ 1008.2,+ 1005.6,+ 990.0,+ 995.8,+ 993.0,+ 1001.4,+ 1029.0,+ 1026.0,+ 1003.4,+ 1014.8,+ 1009.6,+ 989.0+ ],+ "medianMicros": 1004.8,+ "p95Micros": 1035.4+ },+ {+ "case": "url_extent_40",+ "implementation": "candidate",+ "batch": 5,+ "samplesMicrosPerOperation": [+ 77.4,+ 70.2,+ 65.0,+ 78.8,+ 66.4,+ 76.0,+ 66.2,+ 77.6,+ 71.4,+ 84.8,+ 70.0,+ 75.0,+ 70.0,+ 69.2,+ 65.8,+ 64.2,+ 65.4,+ 64.6,+ 66.0,+ 64.0,+ 74.6,+ 64.2,+ 76.6,+ 64.0,+ 81.4,+ 69.0,+ 88.6,+ 65.8,+ 75.6,+ 66.6+ ],+ "medianMicros": 70.0,+ "p95Micros": 84.8+ },+ {+ "case": "url_lookup_160",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 32.7,+ 33.7,+ 32.8,+ 33.7,+ 35.9,+ 35.3,+ 37.5,+ 33.1,+ 33.2,+ 32.1,+ 32.8,+ 34.4,+ 34.0,+ 33.6,+ 32.5,+ 33.3,+ 35.3,+ 34.4,+ 34.8,+ 32.3,+ 32.1,+ 32.5,+ 33.0,+ 34.1,+ 34.7,+ 35.6,+ 32.3,+ 33.1,+ 33.1,+ 32.5+ ],+ "medianMicros": 33.3,+ "p95Micros": 35.9+ },+ {+ "case": "url_lookup_160",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 34.2,+ 32.9,+ 34.1,+ 33.0,+ 33.0,+ 34.5,+ 33.6,+ 34.6,+ 38.9,+ 36.4,+ 34.8,+ 36.1,+ 33.7,+ 35.4,+ 34.5,+ 34.2,+ 34.1,+ 33.7,+ 39.9,+ 33.3,+ 32.7,+ 33.0,+ 34.2,+ 34.3,+ 34.5,+ 34.8,+ 33.8,+ 35.7,+ 39.7,+ 35.1+ ],+ "medianMicros": 34.3,+ "p95Micros": 39.7+ },+ {+ "case": "url_extent_160",+ "implementation": "baseline",+ "batch": 5,+ "samplesMicrosPerOperation": [+ 6419.6,+ 6475.0,+ 6385.0,+ 6435.2,+ 6411.6,+ 6479.6,+ 6560.2,+ 6523.2,+ 6556.6,+ 6524.2,+ 6506.2,+ 6488.6,+ 6583.2,+ 6477.6,+ 6497.4,+ 6526.8,+ 6566.0,+ 6467.0,+ 6484.6,+ 6436.6,+ 6477.0,+ 6489.6,+ 6559.4,+ 6587.4,+ 6577.0,+ 6640.8,+ 6544.8,+ 6677.0,+ 6578.0,+ 6464.2+ ],+ "medianMicros": 6506.2,+ "p95Micros": 6640.8+ },+ {+ "case": "url_extent_160",+ "implementation": "candidate",+ "batch": 5,+ "samplesMicrosPerOperation": [+ 251.4,+ 234.6,+ 242.6,+ 243.6,+ 243.4,+ 236.4,+ 241.4,+ 236.6,+ 245.0,+ 246.8,+ 236.0,+ 239.2,+ 246.0,+ 242.8,+ 240.8,+ 236.6,+ 241.8,+ 239.4,+ 241.2,+ 245.6,+ 235.6,+ 237.8,+ 240.4,+ 244.4,+ 252.6,+ 247.2,+ 252.2,+ 258.4,+ 244.8,+ 241.0+ ],+ "medianMicros": 242.6,+ "p95Micros": 252.6+ },+ {+ "case": "url_lookup_1000",+ "implementation": "baseline",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 159.5,+ 174.7,+ 165.6,+ 166.8,+ 161.5,+ 154.7,+ 167.0,+ 159.5,+ 160.5,+ 161.3,+ 163.9,+ 163.0,+ 158.1,+ 162.7,+ 157.2,+ 165.2,+ 161.5,+ 169.7,+ 165.8,+ 162.9,+ 169.8,+ 164.8,+ 173.1,+ 163.0,+ 158.6,+ 158.1,+ 158.5,+ 155.0,+ 157.3,+ 168.5+ ],+ "medianMicros": 162.9,+ "p95Micros": 173.1+ },+ {+ "case": "url_lookup_1000",+ "implementation": "candidate",+ "batch": 10,+ "samplesMicrosPerOperation": [+ 158.4,+ 163.7,+ 153.6,+ 157.9,+ 165.5,+ 158.5,+ 165.1,+ 159.5,+ 163.5,+ 165.1,+ 169.5,+ 165.0,+ 161.6,+ 172.6,+ 160.7,+ 172.1,+ 164.2,+ 163.5,+ 167.2,+ 164.3,+ 157.8,+ 165.9,+ 165.0,+ 165.7,+ 170.2,+ 163.4,+ 163.8,+ 167.5,+ 156.4,+ 167.0+ ],+ "medianMicros": 164.3,+ "p95Micros": 172.1+ },+ {+ "case": "url_extent_1000",+ "implementation": "baseline",+ "batch": 1,+ "samplesMicrosPerOperation": [+ 176086.0,+ 174871.0,+ 173381.0,+ 173966.0,+ 175729.0,+ 173025.0,+ 175295.0,+ 175418.0,+ 175668.0,+ 175619.0,+ 177409.0,+ 176379.0,+ 176949.0,+ 177221.0,+ 177737.0,+ 176847.0,+ 176213.0,+ 173921.0,+ 175321.0,+ 176332.0,+ 174974.0,+ 173199.0,+ 174993.0,+ 178355.0,+ 178022.0,+ 176205.0,+ 176657.0,+ 176151.0,+ 175577.0,+ 174445.0+ ],+ "medianMicros": 175729.0,+ "p95Micros": 178022.0+ },+ {+ "case": "url_extent_1000",+ "implementation": "candidate",+ "batch": 1,+ "samplesMicrosPerOperation": [+ 3065.0,+ 3086.0,+ 3076.0,+ 3010.0,+ 3057.0,+ 3037.0,+ 3148.0,+ 3073.0,+ 3061.0,+ 3062.0,+ 3100.0,+ 3093.0,+ 3688.0,+ 3347.0,+ 3133.0,+ 3130.0,+ 3069.0,+ 3038.0,+ 3128.0,+ 3101.0,+ 3028.0,+ 3051.0,+ 3115.0,+ 3069.0,+ 3207.0,+ 3112.0,+ 3160.0,+ 3060.0,+ 3102.0,+ 2975.0+ ],+ "medianMicros": 3086.0,+ "p95Micros": 3347.0+ }+ ],+ "source": {+ "baselineCommit": "1e9352c802209b4bade25b6f9e729af9748c464c",+ "baselineSha256": "cae0591f368bf0d2c479fc782cbc1124bb80c985740f493451ae3f5060968367",+ "baselineImportAdaptation": "xterm.dart umbrella export replaced with core.dart; no executable baseline code changes",+ "adaptedBaselineSha256": "999f66427551b496bd59d9f6537cea75c812d5653d553e418c31784fd523c9f0",+ "candidateSha256": "b3c46e4f7569b1cab5b375d21783b2cbc67b4fb98cf5eceac6afe7294b265bb9",+ "fixtureSha256": "358260c894526e6ff9b6b3910ffff2e9ad9540175e884f7501ff57fe9395c1ad",+ "dependencies": "Both implementations use current-worktree Flutter/xterm dependencies"+ },+ "validation": {+ "fullDesktopTests": {+ "passed": 5246,+ "skipped": 15,+ "productionMatcherUnchangedSinceRun": true+ },+ "focusedMatcherAndPanelTests": {+ "passed": 70,+ "lineCoverage": {+ "linesFound": 297,+ "linesHit": 297+ }+ },+ "nativeRendererTests": {+ "passed": 19,+ "platform": "macOS ARM64 Debug",+ "input": "Flutter-dispatched pointer and keyboard events",+ "externalActions": "fake"+ },+ "baselineEquivalentChecks": 10373,+ "analysis": {+ "changedDartFilesIssues": 0,+ "fullProjectInfoFindings": 14,+ "sameAsUnchangedBaseline": true+ }+ }+}diff --git a/docs/performance/2026-10-01-terminal-link-hit-testing.md b/docs/performance/2026-10-01-terminal-link-hit-testing.mdnew file mode 100644index 000000000..624050111--- /dev/null+++ b/docs/performance/2026-10-01-terminal-link-hit-testing.md@@ -0,0 +1,106 @@+# Terminal link hit-testing — October 1, 2026++Long terminal text could stall pointer handling: detecting an ordinary 2,048-character+token took about 44 ms, and finding the underline cells for a 1,020-character URL+took about 176 ms. Both are synchronous work on the Dart UI isolate.++The matcher now rejects text without a supported media suffix before searching+for bare paths, starts relative-path matching once per token, and reuses line+reconstruction, regex matches and target validation while finding one underline.+The temporary lookup is discarded before returning. Output, terminal resizing,+alternate buffers and OSC 8 changes are read afresh on the next pointer event.+Pattern iteration remains lazy so a match does not require parsing later text.++## Paired measurements++Baseline: `1e9352c802209b4bade25b6f9e729af9748c464c`. Both implementations were+compiled into one ARM64 Dart AOT executable with Flutter 3.47.2 / Dart 3.13.2+and the same in-tree xterm. The baseline's only adaptation was importing+`xterm/core.dart` instead of the Flutter umbrella export; its executable matcher+code was unchanged. The [raw results](2026-10-01-terminal-link-hit-testing.json)+include exact source hashes, every observation and environment metadata.++These are **synchronous component elapsed times**, not whole-app CPU, native+pointer latency, GPU presentation or battery measurements. Each case used+20 warmups and 30 observations, alternating which implementation ran first.+Our build/test jobs had completed before this run; ordinary workstation activity+was not disabled. Earlier exploratory runs overlapped validation and are not+used for the table.++| Operation | Baseline median | Optimized median | Time reduction |+| --- | ---: | ---: | ---: |+| Reject plain token, 80 characters | 75.9 µs | 3.9 µs | 94.9% |+| Reject plain token, 512 characters | 2,746.0 µs | 22.1 µs | 99.2% |+| Reject plain token, 2,048 characters | 43,772.6 µs | 88.2 µs | 99.8% |+| Reject that token beside `image.png` | 43,503.3 µs | 199.2 µs | 99.5% |+| Underline extent, 60-character URL | 1,004.8 µs | 70.0 µs | 93.0% |+| Underline extent, 180-character URL | 6,506.2 µs | 242.6 µs | 96.3% |+| Underline extent, 1,020-character URL | 175,729.0 µs | 3,086.0 µs | 98.2% |++Single-cell URL lookup does not use the extent cache. Its medians were+14.9 → 15.2 µs, 33.3 → 34.3 µs and 162.9 → 164.3 µs for those URL lengths;+this run does not show a speedup for that operation. The benchmark uses a+120-column terminal. It does not establish an improvement for every possible+terminal width or output pattern.++## Correctness and validation++The paired comparison passed 10,373 checks over 400 seeded fixtures:+3,468 text offsets, 6,400 terminal cells and 505 underline extents. Cases include+Markdown, quoted media paths, Unicode, punctuation, malformed/unsupported+targets, streamed replacement text, OSC 8 links and resizing. Seed: `551551`.+Focused regression tests cover long neighboring tokens, wide-cell mapping,+disjoint identical links and cache freshness after terminal mutation.++The first full desktop run passed 5,242 tests, skipped 15 and failed four.+All four failures reproduced in an isolated copy of unchanged main: two+tooltip expectations still used “Search harnesses,” one test left activity+timers alive until after widget invariants, and one expected legacy heartbeat+packets to renew indefinitely. Updated fixtures use current “Open Harness”+wording, dispose the notifier inside the test body, and send fresh activity+evidence when testing renewal. The corrected files and existing legacy-heartbeat+safety tests passed all 16 tests. No production activity behavior was changed.++Full-project analysis reported 14 informational lints, all also present on the+unchanged baseline; none is in the optimized matcher or its new benchmark.+Analysis of all eight changed/new Dart entry points reported no issues.++The corrected full suite passed **5,246 tests, with 15 skipped**. A subsequent+coverage run found two previously unexercised lines in standalone painted URL+handling. Adding underlined and indented-colored URL cases, with unrelated prose+before and after the link, brought the focused matcher/panel run to **70 passing+tests and 297/297 executable matcher lines covered**. Only tests changed after+the full-suite run; the production matcher stayed byte-identical. Line coverage+does not establish complete branch or end-to-end coverage.++The new `integration_test/native_terminal_links_e2e_test.dart` also passed all+**19 tests** in an isolated macOS ARM64 Debug app. It runs the existing terminal+gesture/panel scenarios in the native renderer: modifier-click, ordinary mouse+reports, selection, hover updates after output/session changes, wrapped URLs,+missing files, and cancelled/failed previews. Input is dispatched through Flutter;+file reads, downloads, and URL launches are fake. Physical AppKit modifier delivery+and actual external applications are outside that check. `flutter test` in this+SDK does not support `--release`; the AOT timing comparison is separate.++A disposable Release build was also checked through native app controls: long+ASCII URL entry stayed in the selected pane, tab round trips returned to the same+zoomed pane, and neighboring panes retained their contents. An earlier apparent+tab/body mismatch was not reproduced in the freshly launched build; its root+cause was not established, so this is not claimed as a fix for that observation.+The fixture's lifecycle diagnostics and native test log are retained with the+local validation artifacts. No installed app or live user session was restarted.++## Reproduce++From the repository root, with desktop dependencies resolved:++```sh+python3 desktop/tool/benchmark_terminal_links.py \+ --flutter /path/to/flutter-3.47.2 \+ --baseline 1e9352c802209b4bade25b6f9e729af9748c464c \+ --aot --output /tmp/terminal-link-comparison.json+```++Use a new output path for every run. The runner rejects an existing output and+checks that the candidate source and fixture did not change during measurement.+This component result does not establish a 100× reduction in app resources.