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
refactor(mobile): TerminalPanel without the desktop tile's chrome
deede697badba9b
diff --git a/mobile/integration_test/perf/scenarios.dart b/mobile/integration_test/perf/scenarios.dartindex 8dbe7aff4..3235edd60 100644--- a/mobile/integration_test/perf/scenarios.dart+++ b/mobile/integration_test/perf/scenarios.dart@@ -892,7 +892,6 @@ class PerfSuite {notifier: fixture.notifier,session: _terminalA.session,focused: false,- showHeader: false,),),),diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dartindex 7be281744..f9eb6a762 100644--- a/mobile/lib/app_shell.dart+++ b/mobile/lib/app_shell.dart@@ -156,11 +156,10 @@ class HarnessApp extends StatelessWidget {// is applied exactly once. Ship one without the other and a 19px setting// gives 19px-tall buttons wrapped around 13pt labels.//- // ⚠️ The terminal is fenced out of this at five seams — see- // `terminal_panel.dart`, `terminal_composer.dart`, `engine_identity.dart`- // and `terminal_section.dart`, and the regression test in- // `test/terminal_ui_scale_isolation_test.dart`. The terminal keeps its own- // font settings because its type is a grid a remote program draws into.+ // ⚠️ The terminal is fenced out of this — see `terminal_panel.dart`+ // (`textScaler: TextScaler.noScaling`) and `engine_identity.dart`. The+ // terminal keeps its own font settings because its type is a grid a remote+ // program draws into.//// Outermost inside `builder`, with `_GridTokenScope` inside it: the clamp// has to be an ancestor of everything that lays out text, while the scopediff --git a/mobile/lib/phone/agent_context_line.dart b/mobile/lib/phone/agent_context_line.dartindex 325ed6299..bbdad5764 100644--- a/mobile/lib/phone/agent_context_line.dart+++ b/mobile/lib/phone/agent_context_line.dart@@ -7,9 +7,8 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';/// Where an agent IS: the folder it was started in, the branch that folder is on, and the machine/// running it — `autonomous-harness · ⑂ main · MacBookPro2021.local`.///-/// The same three facts, in the same order, as the desktop's pane header-/// (`widgets/terminal_pane_header.dart`), so an agent recognised on one screen is recognised on the-/// other. A name alone stops identifying anything the moment somebody has two `main` agents, which+/// The same three facts, in the same order, as the desktop's pane header, so an agent recognised+/// on one screen is recognised on the other. A name alone stops identifying anything the moment somebody has two `main` agents, which/// on a phone — where the Agents tab mixes every machine into one list — happens immediately.////// ⚠️ **Two flexible halves, not one line of text.** A phone row leaves this about 240pt, and thediff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dartindex 7a60318f7..f458dd03e 100644--- a/mobile/lib/phone/terminal_page.dart+++ b/mobile/lib/phone/terminal_page.dart@@ -1858,7 +1858,6 @@ class _TerminalPageState extends State<TerminalPage>),),onLineTap: _onLineTap,- showHeader: false,// tmux's copy-mode position while// reading back — see [_CopyModePosition].scrollback: _scrollback,diff --git a/mobile/lib/shared/theme/appearance_prefs_store.dart b/mobile/lib/shared/theme/appearance_prefs_store.dartindex 18d94af35..b09ce454e 100644--- a/mobile/lib/shared/theme/appearance_prefs_store.dart+++ b/mobile/lib/shared/theme/appearance_prefs_store.dart@@ -10,9 +10,8 @@ import 'color_palette.dart';/// This does not change the terminal's type. The terminal renders a grid a remote/// program draws into, so it keeps its own face and its own size in/// [TerminalFontStore], reached from Settings ▸ Terminal — and the app's UI-/// scale is fenced out of it at five seams (see the notes in-/// `terminal_panel.dart` and `terminal_composer.dart`, and the regression test-/// in `test/terminal_ui_scale_isolation_test.dart`).+/// scale is fenced out of it (see the note at `textScaler` in+/// `terminal_panel.dart`).@immutableclass AppearancePrefs {const AppearancePrefs({diff --git a/mobile/lib/terminal/terminal_search.dart b/mobile/lib/terminal/terminal_search.dartdeleted file mode 100644index d12cd006d..000000000--- a/mobile/lib/terminal/terminal_search.dart+++ /dev/null@@ -1,448 +0,0 @@-import 'dart:async';-import 'dart:collection';-import 'dart:typed_data';--import 'package:flutter/foundation.dart';-import 'package:xterm/xterm.dart';--/// An on-demand index of the current terminal buffer. It never reads a file,-/// queries a daemon, or sends input. Unchanged rows keep their decoded text;-/// long scans yield to the event loop, and only the selected hit owns an anchor.-class TerminalSearch extends ChangeNotifier {- TerminalSearch(this.terminal, {CellOffset? origin}) {- _origin = origin;- }-- final Terminal terminal;- String _query = '';- bool _caseSensitive = false;- bool _enabled = true;- bool _disposed = false;- bool _listening = false;- bool _running = false;- bool _dirty = false;- int _generation = 0;- int _indexedGeneration = -1;- int _pendingStep = 0;- Timer? _timer;- Timer? _yieldTimer;- Completer<void>? _yieldResume;- Completer<void>? _settled;- Buffer? _buffer;- CellOffset? _origin;- CellAnchor? _selectionAnchor;- Map<BufferLine, _SearchLine> _lines = HashMap.identity();- Map<BufferLine, _SearchGroup> _cache = HashMap.identity();- List<_SearchGroup> _groups = [];- int _count = 0;- int _selected = -1;- _SearchGroup? _selectedGroup;- int _selectedInGroup = 0;-- String get query => _query;- bool get caseSensitive => _caseSensitive;- bool get searching => _running || _dirty || _timer != null;- bool get hasSnapshot =>- _indexedGeneration == _generation && identical(_buffer, terminal.buffer);- int get count => _count;- int get selected => _selected;- Future<void> get settled => _settled?.future ?? Future.value();-- BufferRangeLine? get match =>- identical(_buffer, terminal.buffer) && _selectedGroup?.valid == true- ? _selectedGroup!.rangeAt(_selectedInGroup)- : null;-- void setQuery(String value, {bool? caseSensitive}) {- final sensitive = caseSensitive ?? _caseSensitive;- if (_query == value && _caseSensitive == sensitive) return;- _query = value;- _caseSensitive = sensitive;- _generation++;- _pendingStep = 0;- _clearResults();- _listen(_enabled && _query.isNotEmpty);- if (_query.isEmpty) {- _releaseIndex();- } else {- _request();- }- notifyListeners();- }-- /// Hidden/covered find bars retain only their query and selected location.- /// Returning rebuilds from current output instead of indexing hidden traffic.- void setEnabled(bool value) {- if (_enabled == value || _disposed) return;- _enabled = value;- _generation++;- _listen(value && _query.isNotEmpty);- if (value) {- _request();- } else {- _releaseIndex();- }- }-- void _listen(bool value) {- if (_listening == value) return;- _listening = value;- if (value) {- terminal.addListener(_onOutput);- terminal.addResizeListener(_onResize);- } else {- terminal.removeListener(_onOutput);- terminal.removeResizeListener(_onResize);- }- }-- void _onOutput() {- _request();- // Output can replace the active buffer or overwrite a highlighted row.- // Let the view remove an invalid highlight before its next paint.- notifyListeners();- }-- // Resize runs during renderer layout. Defer UI notifications to the scan's- // event-loop turn so reflow never calls setState during layout.- void _onResize() => _request();-- void _request() {- if (_disposed || !_enabled || _query.isEmpty) return;- _dirty = true;- _settled ??= Completer<void>();- if (!_running) _timer ??= Timer(Duration.zero, () => unawaited(_scan()));- }-- Future<void> _scan() async {- _timer = null;- if (_disposed || !_enabled || _query.isEmpty) return;- _running = true;- _dirty = false;- final generation = _generation;- final buffer = terminal.buffer;- final query = _query;- final sensitive = _caseSensitive;- final pattern = RegExp(- RegExp.escape(query),- caseSensitive: sensitive,- unicode: true,- );- final source = [- for (var i = 0; i < buffer.lines.length; i++) buffer.lines[i],- ];- final lines = HashMap<BufferLine, _SearchLine>.identity();- final cache = HashMap<BufferLine, _SearchGroup>.identity();- final groups = <_SearchGroup>[];- var logical = <_SearchLine>[];- final slice = Stopwatch()..start();- try {- for (var i = 0; i < source.length; i++) {- final line = source[i];- final cached = _lines[line];- final snapshot = cached != null && cached.valid- ? cached- : _SearchLine(line);- lines[line] = snapshot;- logical.add(snapshot);- if (i + 1 == source.length || !source[i + 1].isWrapped) {- final first = logical.first.line;- final previous = _cache[first];- final _SearchGroup group;- if (previous != null && previous.reuses(logical, query, sensitive)) {- group = previous;- } else {- final text = logical.length == 1- ? logical.single.text- : logical.map((line) => line.text).join();- final checkpoints = <int>[];- var hits = 0;- for (final hit in pattern.allMatches(text)) {- if (hits % _SearchGroup.stride == 0) checkpoints.add(hit.start);- hits++;- if (hits % 128 == 0 && slice.elapsedMicroseconds >= 1500) {- await _yieldScan();- if (_disposed || generation != _generation || !_enabled) return;- slice.reset();- }- }- group = _SearchGroup(- logical,- query,- sensitive,- pattern,- text,- Uint32List.fromList(checkpoints),- hits,- );- }- cache[first] = group;- if (group.count > 0 && group.valid) groups.add(group);- logical = [];- }- if (slice.elapsedMicroseconds >= 1500) {- await _yieldScan();- if (_disposed || generation != _generation || !_enabled) return;- slice.reset();- }- }- if (_disposed || generation != _generation || !_enabled) return;- _lines = lines;- _cache = cache;- _buffer = buffer;- _indexedGeneration = generation;- _groups = groups.where((group) => group.valid).toList(growable: false);- _count = _groups.fold(0, (count, group) => count + group.count);- final origin = _selectionAnchor?.attached == true- ? _selectionAnchor!.offset- : _origin;- var index = 0;- var found = false;- if (origin != null) {- for (final group in _groups) {- if (group.lines.last.line.index < origin.y) {- index += group.count;- continue;- }- final hit = group.indexAtOrAfter(origin);- index += hit;- if (hit < group.count) {- found = true;- break;- }- }- }- _select(_count == 0 ? -1 : ((found ? index : 0) + _pendingStep) % _count);- _pendingStep = 0;- } finally {- _running = false;- if (!_disposed) {- if (_dirty && _enabled && _query.isNotEmpty) {- _request();- } else {- _settled?.complete();- _settled = null;- }- notifyListeners();- }- }- }-- void step(int delta) {- if (_query.isEmpty || !_enabled) return;- if (searching && !hasSnapshot) {- _pendingStep += delta;- return;- }- if (_count == 0) return;- final target = (_selected + delta) % _count;- var index = target;- for (final group in _groups) {- if (index < group.count) {- if (!group.valid) {- _pendingStep += delta;- _request();- return;- }- break;- }- index -= group.count;- }- _select(target);- notifyListeners();- }-- void _select(int index) {- _selected = index;- _selectedGroup = null;- if (index < 0) return;- for (final group in _groups) {- if (index >= group.count) {- index -= group.count;- continue;- }- _selectedGroup = group;- _selectedInGroup = index;- final range = match;- if (range != null) {- _selectionAnchor?.dispose();- _selectionAnchor = terminal.buffer.createAnchorFromOffset(range.begin);- _origin = range.begin;- }- break;- }- }-- void _clearResults() {- _groups = [];- _count = 0;- _selected = -1;- _selectedGroup = null;- }-- Future<void> _yieldScan() {- final resume = Completer<void>();- _yieldResume = resume;- _yieldTimer = Timer(Duration.zero, () {- _yieldTimer = null;- _yieldResume = null;- resume.complete();- });- return resume.future;- }-- void _releaseIndex() {- _yieldTimer?.cancel();- _yieldTimer = null;- final resume = _yieldResume;- _yieldResume = null;- resume?.complete();- _timer?.cancel();- _timer = null;- _dirty = false;- _lines.clear();- _cache.clear();- _clearResults();- if (!_running) {- _settled?.complete();- _settled = null;- }- }-- @override- void dispose() {- _disposed = true;- _generation++;- _listen(false);- _releaseIndex();- _selectionAnchor?.dispose();- _selectionAnchor = null;- _settled?.complete();- _settled = null;- super.dispose();- }-}--class _SearchLine {- _SearchLine(this.line)- : version = line.textVersion,- wrapped = line.isWrapped,- text = line.getText();- final BufferLine line;- final int version;- final bool wrapped;- final String text;- bool get valid =>- line.attached && line.textVersion == version && line.isWrapped == wrapped;-- int cellAt(int offset) {- if (offset <= 0) return 0;- var chars = 0;- var end = 0;- for (var x = 0; x < line.length; x++) {- final code = line.getCodePoint(x);- if (code == 0 && x > 0 && line.getWidth(x - 1) == 2) continue;- chars += code > 0xffff ? 2 : 1;- end = x + (line.getWidth(x) > 1 ? line.getWidth(x) : 1);- if (chars >= offset) break;- }- return end;- }-}--class _SearchGroup {- _SearchGroup(- this.lines,- this.query,- this.sensitive,- this.pattern,- this.text,- this.checkpoints,- this.count,- ) {- var offset = 0;- starts = [- for (final line in lines) (offset += line.text.length) - line.text.length,- ];- }- // One integer per 64 matches, rather than a range/anchor for every character- // in a very repetitive log. Selecting a hit examines at most 64 candidates.- static const stride = 64;- final List<_SearchLine> lines;- final String query;- final bool sensitive;- final RegExp pattern;- final String text;- final Uint32List checkpoints;- final int count;- late final List<int> starts;- bool get valid {- for (var i = 0; i < lines.length; i++) {- if (!lines[i].valid ||- (i > 0 && lines[i].line.index != lines[i - 1].line.index + 1)) {- return false;- }- }- return true;- }-- bool reuses(List<_SearchLine> other, String value, bool caseSensitive) =>- query == value && sensitive == caseSensitive && listEquals(lines, other);-- int indexAtOrAfter(CellOffset origin) {- var row = 0;- while (row < lines.length && lines[row].line.index < origin.y) {- row++;- }- if (row == lines.length) return count;- final textOffset =- starts[row] +- (lines[row].line.index == origin.y- ? lines[row].line.getText(0, origin.x).length- : 0);- var low = 0;- var high = checkpoints.length - 1;- while (low < high) {- final middle = (low + high + 1) ~/ 2;- if (checkpoints[middle] <= textOffset) {- low = middle;- } else {- high = middle - 1;- }- }- var index = low * stride;- for (final hit in pattern.allMatches(text, checkpoints[low])) {- if (hit.start >= textOffset) return index;- index++;- }- return count;- }-- BufferRangeLine rangeAt(int index) {- final hit = pattern- .allMatches(text, checkpoints[index ~/ stride])- .skip(index % stride)- .first;- return BufferRangeLine(- _cellAt(hit.start, end: false),- _cellAt(hit.end, end: true),- );- }-- CellOffset _cellAt(int offset, {required bool end}) {- var low = 0;- var high = lines.length - 1;- while (low < high) {- final middle = (low + high + 1) ~/ 2;- if (starts[middle] < offset || (!end && starts[middle] == offset)) {- low = middle;- } else {- high = middle - 1;- }- }- return CellOffset(- lines[low].cellAt(offset - starts[low]),- lines[low].line.index,- );- }-}diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dartindex 64fe826cd..082d8e3cd 100644--- a/mobile/lib/terminal/terminal_session.dart+++ b/mobile/lib/terminal/terminal_session.dart@@ -1389,8 +1389,6 @@ class TerminalSession extends ChangeNotifier {_viewport?.scroll(phase, dy, velocity);}- void find(TerminalFindAction action) => _viewport?.find(action);-bool focusInput() => _viewport?.focusInput() ?? false;/// Coalescing windows for the two things the user drives directly.diff --git a/mobile/lib/terminal/terminal_viewport.dart b/mobile/lib/terminal/terminal_viewport.dartindex 7b7b83c5c..a6963835e 100644--- a/mobile/lib/terminal/terminal_viewport.dart+++ b/mobile/lib/terminal/terminal_viewport.dart@@ -1,7 +1,5 @@/// Local UI boundary for controls that operate on the rendered terminal but/// do not travel to the remote tmux pane.-enum TerminalFindAction { open, next, previous }-abstract interface class TerminalViewport {/// One report from the hardware dial.///@@ -9,9 +7,6 @@ abstract interface class TerminalViewport {/// pixels and [velocity] is glass pixels per second at release.void scroll(int phase, int dy, int velocity);- /// Opens or steps through local terminal output without sending a key.- void find(TerminalFindAction action);-/// Claims an already mounted editor before navigation's next rendered frame./// False means the destination has no ready input view yet.bool focusInput();diff --git a/mobile/lib/widgets/agent_drag.dart b/mobile/lib/widgets/agent_drag.dartdeleted file mode 100644index ed208c4ef..000000000--- a/mobile/lib/widgets/agent_drag.dart+++ /dev/null@@ -1,94 +0,0 @@-import 'package:flutter/material.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';--/// An agent in flight between the rail and the grid.-class AgentDragRef {- const AgentDragRef({- required this.machineId,- required this.agentId,- required this.name,- });-- final String machineId;- final String agentId;- final String name;-}--/// A PANE in flight between two grid slots.-///-/// A type of its own rather than a flag on [AgentDragRef], because the two-/// drags mean opposite things at the same drop point: a rail row landing on a-/// tile REPLACES what that tile shows, a pane landing on it SWAPS the two.-/// `DragTarget<T>` already separates them by generic, so each target only ever-/// sees the payload it knows what to do with, and neither has to ask what kind-/// of drag is in flight.-class PaneDragRef {- const PaneDragRef({required this.paneId});-- final int paneId;-}--/// Everything the header needs to drag its own pane: what to say it is, and-/// where to photograph it from.-///-/// The key is not part of [PaneDragRef] because that is the PAYLOAD — it-/// crosses to the drop target, where a key into the source tile means nothing.-class PaneDragHandle {- const PaneDragHandle({required this.ref, required this.size});-- final PaneDragRef ref;-- /// The tile's size, so the ghost comes out the shape of the pane it carries.- ///- /// Passed IN from a LayoutBuilder rather than read off a render object: the- /// header builds this during a build, and `RenderBox.size` throws there.- final Size size;-}--/// Whether a rail row is currently being dragged, readable by the grid.--///-/// A [ValueNotifier] beside the widgets rather than a field on AppNotifier: it-/// describes a hand on a mouse for the length of one gesture, and nothing about-/// machines, agents or sessions. Putting it in the domain state would mean every-/// listener of that state rebuilding on mouse-down, and would outlive the-/// gesture in a place where later readers would reasonably expect it to mean-/// something.-///-/// The grid watches it to reveal the empty slot: an "add a tile" cell that is-/// always on screen would permanently halve a single terminal to advertise a-/// feature, so it appears when there is something to drop into it and goes away-/// again afterwards.-final agentDrag = ValueNotifier<AgentDragRef?>(null);--/// Whether a pane is currently being dragged by its header, readable by the grid.-///-/// Kept apart from [agentDrag] for the same reason [PaneDragRef] is a separate-/// type: the two drags are live at different times and the grid reveals-/// different things for each — an agent drag offers an empty slot to open into,-/// a pane drag offers the other tiles to trade places with.-final paneDragging = ValueNotifier<PaneDragRef?>(null);--class PaneCloseButton extends StatelessWidget {- const PaneCloseButton({super.key, required this.onPressed});-- final VoidCallback onPressed;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return Tooltip(- message: 'Close pane',- child: IconButton(- onPressed: onPressed,- icon: Icon(Icons.close, size: 15, color: AppColors.muted),- splashRadius: 13,- constraints: const BoxConstraints.tightFor(width: 26, height: 26),- padding: EdgeInsets.zero,- visualDensity: VisualDensity.compact,- ),- );- }-}diff --git a/mobile/lib/widgets/pane_header_actions.dart b/mobile/lib/widgets/pane_header_actions.dartdeleted file mode 100644index 8e3f18762..000000000--- a/mobile/lib/widgets/pane_header_actions.dart+++ /dev/null@@ -1,155 +0,0 @@-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';--/// Direct pane controls, in a stable order even when an action is unavailable.-class PaneHeaderActions extends StatelessWidget {- const PaneHeaderActions({- super.key,- required this.name,- required this.zoomed,- this.onZoom,- this.onDelete,- this.onClose,- this.onToggleComposer,- this.composerVisible = false,- this.details,- });-- final String name;- final bool zoomed, composerVisible;- final VoidCallback? onZoom, onDelete, onClose, onToggleComposer;-- /// Folder, branch and machine share the controls' space while idle. Both- /// layers keep their size so hovering never changes the title's width.- final Widget? details;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);-- Widget action(String tooltip, IconData icon, VoidCallback? callback) =>- IconButton(- tooltip: tooltip,- onPressed: callback,- icon: Icon(icon, size: 16),- style: ButtonStyle(- fixedSize: const WidgetStatePropertyAll(Size(28, 28)),- minimumSize: const WidgetStatePropertyAll(Size(28, 28)),- padding: const WidgetStatePropertyAll(EdgeInsets.zero),- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- visualDensity: VisualDensity.standard,- shape: WidgetStatePropertyAll(- RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),- ),- foregroundColor: WidgetStateProperty.resolveWith((states) {- if (states.contains(WidgetState.disabled)) {- return grid.AppPalette.textFaint;- }- if (states.contains(WidgetState.hovered) ||- states.contains(WidgetState.focused)) {- return AppColors.text;- }- return AppColors.mutedStrong.withValues(alpha: .8);- }),- overlayColor: WidgetStatePropertyAll(grid.AppSurface.hoverFill),- ),- );-- final visible = _PaneHeaderVisibility.of(context);- final controls = IgnorePointer(- ignoring: !visible,- child: AnimatedOpacity(- opacity: visible ? 1 : 0,- alwaysIncludeSemantics: true,- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : const Duration(milliseconds: 100),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (onToggleComposer != null) ...[- action(- composerVisible- ? 'Hide message composer'- : 'Show message composer',- LucideIcons.keyboard,- onToggleComposer,- ),- const SizedBox(width: 2),- ],- action(- zoomed ? 'Restore panes' : 'Zoom $name',- zoomed ? LucideIcons.minimize : LucideIcons.maximize,- onZoom,- ),- const SizedBox(width: 2),- action('Delete Harness', LucideIcons.trash2, onDelete),- const SizedBox(width: 2),- action('Close pane', LucideIcons.x, onClose),- ],- ),- ),- );- if (details == null) return controls;- return Stack(- alignment: Alignment.centerRight,- children: [- IgnorePointer(- ignoring: visible,- child: AnimatedOpacity(- key: const ValueKey('pane-header-details'),- opacity: visible ? 0 : 1,- duration: MediaQuery.disableAnimationsOf(context)- ? Duration.zero- : const Duration(milliseconds: 100),- child: ExcludeSemantics(excluding: visible, child: details!),- ),- ),- controls,- ],- );- }-}--/// Only header controls depend on this hover state, so the terminal and title-/// are retained as the pointer crosses the bar. Keyboard focus reveals them too.-class PaneHeaderHover extends StatefulWidget {- const PaneHeaderHover({super.key, required this.child});- final Widget child;- @override- State<PaneHeaderHover> createState() => _PaneHeaderHoverState();-}--class _PaneHeaderHoverState extends State<PaneHeaderHover> {- bool _hovered = false, _focused = false;- @override- Widget build(BuildContext context) => MouseRegion(- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- child: Focus(- canRequestFocus: false,- includeSemantics: false,- onFocusChange: (value) => setState(() => _focused = value),- child: _PaneHeaderVisibility(- visible: _hovered || _focused,- child: widget.child,- ),- ),- );-}--class _PaneHeaderVisibility extends InheritedWidget {- const _PaneHeaderVisibility({required this.visible, required super.child});- final bool visible;- static bool of(BuildContext context) =>- context- .dependOnInheritedWidgetOfExactType<_PaneHeaderVisibility>()- ?.visible ??- true;- @override- bool updateShouldNotify(_PaneHeaderVisibility oldWidget) =>- visible != oldWidget.visible;-}diff --git a/mobile/lib/widgets/terminal_composer.dart b/mobile/lib/widgets/terminal_composer.dartdeleted file mode 100644index ff075eefe..000000000--- a/mobile/lib/widgets/terminal_composer.dart+++ /dev/null@@ -1,360 +0,0 @@-import 'dart:async';--import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';-import '../terminal/terminal_font_store.dart';-import '../terminal/terminal_session.dart';--/// A textbox under a terminal that sends its whole contents at once.-///-/// It exists for remote machines, where typing straight into the pane charges a network round trip-/// per keystroke. Here the typing is local and free; only the finished message crosses the wire —-/// as one batch, followed by Enter.-///-/// Focusing the terminal itself is untouched: that path stays per-keystroke, which is what anyone-/// driving a full-screen TUI needs.-class TerminalComposer extends StatefulWidget {- const TerminalComposer({- super.key,- required this.session,- required this.focusNode,- this.inputEnabled = true,- });-- final TerminalSession session;- final FocusNode focusNode;- final bool inputEnabled;-- @override- State<TerminalComposer> createState() => _TerminalComposerState();-}--class _TerminalComposerState extends State<TerminalComposer> {- final TextEditingController _controller = TextEditingController();-- @override- void initState() {- super.initState();- widget.session.addListener(_onSessionChanged);- widget.focusNode.addListener(_onFocusChanged);- terminalFontStore.addListener(_onFontChanged);- }-- @override- void didUpdateWidget(TerminalComposer oldWidget) {- super.didUpdateWidget(oldWidget);- if (!identical(oldWidget.session, widget.session)) {- oldWidget.session.removeListener(_onSessionChanged);- widget.session.addListener(_onSessionChanged);- // The tile was pointed at another agent. Whatever was half-typed was meant for the previous- // one, and silently sending it to its replacement would be worse than losing it.- _controller.clear();- }- if (!identical(oldWidget.focusNode, widget.focusNode)) {- oldWidget.focusNode.removeListener(_onFocusChanged);- widget.focusNode.addListener(_onFocusChanged);- }- }-- @override- void dispose() {- widget.session.removeListener(_onSessionChanged);- widget.focusNode.removeListener(_onFocusChanged);- terminalFontStore.removeListener(_onFontChanged);- _controller.dispose();- super.dispose();- }-- /// Enabled-ness follows the stream's status, so a rebuild is needed when it moves.- void _onSessionChanged() {- if (mounted) setState(() {});- }-- /// Keeps this box's face in step with the terminal above it — see the `style:` comment below.- void _onFontChanged() {- if (mounted) setState(() {});- }-- /// The composer is the primary input on a remote terminal. Its surface stays- /// visible at rest, then the rim and prompt glyph take the accent when the- /// keyboard lands here so the destination of typing is unmistakable.- void _onFocusChanged() {- if (mounted) setState(() {});- }-- /// Guards the settle window inside [TerminalSession.sendComposerText]: the body is already in- /// the pane while we wait to submit it, so a second Enter arriving in that window would type- /// the next message into the middle of the one being sent.- bool _sending = false;-- Future<void> _submit() async {- if (_sending || !widget.inputEnabled || !widget.session.acceptsInput) {- return;- }- final text = _controller.text;- if (text.isEmpty) return;- _sending = true;- try {- if (!await widget.session.sendComposerText(text)) return;- _controller.clear();- } finally {- _sending = false;- }- }-- /// Breaks the line at the caret, for ⌥⏎.- ///- /// Written into the controller rather than left to the field, which is what Shift+Enter does:- /// AppKit turns ⌥⏎ into `insertNewlineIgnoringFieldEditor:`, a selector Flutter's text input- /// client does not answer, so passing the key through would drop it on the floor. Doing it here- /// also makes the behaviour the same on every platform the app builds for.- void _insertNewline() {- final value = _controller.value;- final selection = value.selection;- if (!selection.isValid) {- // No caret to speak of (the field has never been placed in). Append.- _controller.value = TextEditingValue(- text: '${value.text}\n',- selection: TextSelection.collapsed(offset: value.text.length + 1),- );- return;- }- _controller.value = TextEditingValue(- text:- '${selection.textBefore(value.text)}\n'- '${selection.textAfter(value.text)}',- selection: TextSelection.collapsed(offset: selection.start + 1),- );- }-- /// Enter sends; ⌥⏎ and Shift+Enter compose another line.- ///- /// ⌥⏎ is the one the muscle memory comes with — it is how Claude Code and Codex take a second- /// line at their own prompts, and it is what the shortcuts sheet promises for a pane- /// (`kTerminalOwnedKeys`). The composer is the same prompt wearing a Flutter field, so it has to- /// answer the same key. Shift+Enter is left to the field, which inserts for it natively.- ///- /// `TextField.onSubmitted` cannot do this — it never fires for a multi-line field.- KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {- if (event is! KeyDownEvent && event is! KeyRepeatEvent) {- return KeyEventResult.ignored;- }- final isEnter =- event.logicalKey == LogicalKeyboardKey.enter ||- event.logicalKey == LogicalKeyboardKey.numpadEnter;- if (!isEnter) return KeyEventResult.ignored;- if (HardwareKeyboard.instance.isAltPressed) {- _insertNewline();- return KeyEventResult.handled;- }- if (HardwareKeyboard.instance.isShiftPressed) return KeyEventResult.ignored;- unawaited(_submit());- return KeyEventResult.handled;- }-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final enabled = widget.inputEnabled && widget.session.acceptsInput;- final focused = widget.focusNode.hasFocus;- final terminalStyle = terminalFontStore.value;- // No top border of its own: [ComposerGrip] is the line between this and the terminal.- return Padding(- padding: const EdgeInsets.fromLTRB(12, 6, 12, 12),- // ⚠️ The composer belongs to the TERMINAL, not to the app's chrome, so it is held out of- // the app-wide UI text scale twice over — once for its TYPE here, and once for its BOX- // below. Both are needed, and for different reasons.- //- // This half keeps everything inside the surface at the terminal's own size: the typed text,- // the hint, and the `›`. What is typed here lands over there, so it has to look like it.- child: MediaQuery.withNoTextScaling(- child: AnimatedContainer(- key: const ValueKey('terminal-composer-surface'),- duration: const Duration(milliseconds: 140),- curve: Curves.easeOut,- constraints: const BoxConstraints(minHeight: 48),- decoration: BoxDecoration(- color: enabled- ? grid.AppGlass.surfaceFill- : grid.AppGlass.surfaceFill.withValues(alpha: 0.66),- borderRadius: BorderRadius.circular(10),- border: Border.all(- color: focused- ? grid.AppPalette.accentOnSurface- : grid.AppGlass.lift,- width: focused ? 1.5 : 1,- ),- boxShadow: focused- ? grid.AppSurface.composerShadow- : grid.AppGlass.shadow,- ),- child: Focus(- onKeyEvent: _onKeyEvent,- child: Row(- children: [- Padding(- padding: const EdgeInsets.only(left: 14, right: 10),- child: AnimatedDefaultTextStyle(- key: const ValueKey('terminal-composer-prompt-style'),- duration: const Duration(milliseconds: 140),- curve: Curves.easeOut,- style: terminalStyle- .toTextStyle(- color: focused- ? grid.AppPalette.accentOnSurface- : grid.AppPalette.textSecondary,- bold: true,- )- .copyWith(letterSpacing: 0),- child: const Text(- '›',- key: ValueKey('terminal-composer-prompt'),- ),- ),- ),- Expanded(- child: Shortcuts(- // Terminal-style line editing: readline's Ctrl+W/Ctrl+U are missing from- // Flutter's own default text-editing shortcuts on every platform, unlike- // Option/Cmd+Backspace and Ctrl+A/E, which the field already gets for free.- shortcuts: const <ShortcutActivator, Intent>{- SingleActivator(LogicalKeyboardKey.keyW, control: true):- DeleteToNextWordBoundaryIntent(forward: false),- SingleActivator(LogicalKeyboardKey.keyU, control: true):- DeleteToLineBreakIntent(forward: false),- },- child: TextField(- controller: _controller,- focusNode: widget.focusNode,- enabled: enabled,- minLines: 1,- maxLines: 6,- // The message is going to a terminal, so it is shown in the terminal's own face:- // what is typed here should look like what will land over there.- style: terminalStyle- .toTextStyle(color: grid.AppPalette.textPrimary)- .copyWith(letterSpacing: 0),- textInputAction: TextInputAction.newline,- keyboardType: TextInputType.multiline,- decoration: InputDecoration(- isDense: true,- filled: false,- // ⚠️ THE BOX, unpinned from the theme — and `withNoTextScaling` above does- // NOT reach it. `inputDecorationTheme` gives every field a minimum of- // `AppControl.heightFieldScaled` and a padding multiplied by- // `AppFont.uiScale` — a plain static, not a MediaQuery, so no scaling scope- // can hold it back. Left inherited, raising the UI size grows this field- // (36 → 48.9 at the top of the range) past the surface's own 48, which- // shrinks the Expanded holding the terminal, which drops a row, which sends a- // `terminal_resize` to the remote agent. The composer only appears for REMOTE- // machines, so that is the only case where it would ever have bitten.- //- // The surface above owns this box's height now, so the field asks for no- // minimum of its own — and `contentPadding` below is stated rather than- // inherited for the same reason. Measured by- // `terminal_ui_scale_isolation_test.dart`.- constraints: const BoxConstraints(minHeight: 0),- hintText: enabled- ? 'Message agent… · ↵ send'- : 'Connecting to terminal…',- // InputDecorator merges this with the app-wide field hint- // style. Set tracking explicitly so the UI-control font's- // letter spacing cannot leak into terminal typography.- hintStyle: terminalStyle- .toTextStyle(- color: enabled- ? grid.AppPalette.textSecondary- : grid.AppPalette.textFaint,- )- .copyWith(letterSpacing: 0),- contentPadding: const EdgeInsets.fromLTRB(- 0,- 12,- 14,- 12,- ),- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- disabledBorder: InputBorder.none,- ),- ),- ),- ),- ],- ),- ),- ),- ),- );- }-}--/// The handle that opens and closes the composer, sitting on the line between the terminal and the-/// box it controls.-///-/// It deliberately lives OUTSIDE [TerminalComposer]: a control kept inside would vanish along with-/// the thing it hides, leaving no way back. On the divider it also keeps ONE fixed position in both-/// states — the target never moves, so closing and reopening is the same click twice.-class ComposerGrip extends StatelessWidget {- const ComposerGrip({- super.key,- required this.expanded,- required this.onPressed,- });-- final bool expanded;- final VoidCallback onPressed;-- /// Tall enough to take a click, short enough that a collapsed pane gives the terminal back- /// essentially every row the box was using.- static const double height = 16;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- return SizedBox(- height: height,- child: Stack(- alignment: Alignment.center,- children: [- Container(height: 1, color: AppColors.border),- Tooltip(- message: expanded ? 'Hide the send box' : 'Show the send box',- child: Material(- color: grid.AppPalette.windowBg,- // `borderStrong`, not `border`: the faint one is a SEPARATOR token, sized to be- // findable at a seam the eye is already on. This rim has to hold a shape against- // terminal output, which is what the stronger hairline exists for.- shape: StadiumBorder(- side: BorderSide(color: AppColors.borderStrong),- ),- clipBehavior: Clip.antiAlias,- child: InkWell(- onTap: onPressed,- child: SizedBox(- width: 40,- height: height,- child: Icon(- expanded- ? LucideIcons.chevronDown300- : LucideIcons.chevronUp300,- size: 12,- // One step up from the faint ink this started on, in both directions at once:- // the token resolves lighter on dark and darker on light, so the glyph gains- // contrast against the pane either way instead of only one of them.- color: AppColors.mutedStrong,- ),- ),- ),- ),- ),- ],- ),- );- }-}diff --git a/mobile/lib/widgets/terminal_find_bar.dart b/mobile/lib/widgets/terminal_find_bar.dartdeleted file mode 100644index c155dbde3..000000000--- a/mobile/lib/widgets/terminal_find_bar.dart+++ /dev/null@@ -1,312 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';--import '../terminal/terminal_search.dart';--class TerminalFindBar extends StatefulWidget {- const TerminalFindBar({- super.key,- required this.search,- required this.onQuery,- required this.onStep,- required this.onClose,- required this.onFocus,- this.initialQuery = '',- this.initialCaseSensitive = false,- this.readOnly = false,- });-- /// Null while the focused pane keeps its input ready without a search index.- final TerminalSearch? search;- final String initialQuery;- final bool initialCaseSensitive;- final void Function(String query, bool caseSensitive) onQuery;- final ValueChanged<int> onStep;- final VoidCallback onClose;- final VoidCallback onFocus;- final bool readOnly;-- @override- State<TerminalFindBar> createState() => TerminalFindBarState();-}--class TerminalFindBarState extends State<TerminalFindBar> {- static final _idle = Listenable.merge(const []);- final _scope = FocusScopeNode(debugLabel: 'Terminal Find');- final _focus = FocusNode(debugLabel: 'Find in terminal');- late final _text = TextEditingController(- text: widget.search?.query ?? widget.initialQuery,- );- // Keys can arrive before the widget receives the newly opened search.- TerminalSearch? _activeSearch;-- @override- void initState() {- super.initState();- _activeSearch = widget.search;- _setActive(widget.search != null);- _focus.addListener(_onFocus);- WidgetsBinding.instance.addPostFrameCallback((_) {- if (mounted && widget.search != null) focusSearch();- });- }-- @override- void didUpdateWidget(TerminalFindBar oldWidget) {- super.didUpdateWidget(oldWidget);- _activeSearch = widget.search;- _setActive(widget.search != null);- if (widget.search == null && _text.text != widget.initialQuery) {- _text.text = widget.initialQuery;- }- }-- void _setActive(bool active) {- _scope.canRequestFocus = active;- _scope.descendantsAreFocusable = active;- _scope.descendantsAreTraversable = active;- }-- void releaseSearchFocus() {- _activeSearch = null;- _setActive(false);- }-- void _onFocus() {- if (_focus.hasFocus) widget.onFocus();- }-- void focusSearch({bool selectAll = true, TerminalSearch? search}) {- _activeSearch = search ?? widget.search ?? _activeSearch;- _setActive(true);- _focus.requestFocus();- if (selectAll) {- _text.selection = TextSelection(- baseOffset: 0,- extentOffset: _text.text.length,- );- }- }-- KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {- if (event is! KeyDownEvent && event is! KeyRepeatEvent) {- return KeyEventResult.ignored;- }- final keyboard = HardwareKeyboard.instance;- if (keyboard.isMetaPressed ||- keyboard.isControlPressed ||- keyboard.isAltPressed) {- return KeyEventResult.ignored;- }- final enter =- event.logicalKey == LogicalKeyboardKey.enter ||- event.logicalKey == LogicalKeyboardKey.numpadEnter;- final escape =- event.logicalKey == LogicalKeyboardKey.escape &&- !keyboard.isShiftPressed;- if (!enter && !escape) return KeyEventResult.ignored;- final composing = _text.value.composing;- if (composing.isValid && !composing.isCollapsed) {- // Let the platform commit/cancel composition without a later shortcut- // submitting the editor or closing Find instead.- return KeyEventResult.skipRemainingHandlers;- }- if (escape) {- widget.onClose();- } else {- widget.onStep(keyboard.isShiftPressed ? -1 : 1);- }- return KeyEventResult.handled;- }-- @override- void dispose() {- _focus.removeListener(_onFocus);- _focus.dispose();- _scope.dispose();- _text.dispose();- super.dispose();- }-- @override- Widget build(BuildContext context) => FocusScope(- node: _scope,- onKeyEvent: _onKeyEvent,- child: Material(- color: const Color(0xff272727),- shape: RoundedRectangleBorder(- borderRadius: BorderRadius.circular(8),- side: const BorderSide(color: Colors.white24),- ),- child: Padding(- padding: const EdgeInsets.only(left: 10, right: 4, top: 2, bottom: 2),- child: ListenableBuilder(- listenable: widget.search ?? _idle,- // Live output and result navigation update the controls, not the- // editor. Keep its widget stable while the search index refreshes.- child: Expanded(- key: const ValueKey('terminal-find-editor'),- child: TextField(- controller: _text,- focusNode: _focus,- autofocus: widget.search != null,- textAlignVertical: TextAlignVertical.center,- style: const TextStyle(- fontSize: 13,- height: 1,- color: Colors.white,- ),- decoration: const InputDecoration(- hintText: 'Find in terminal…',- hintStyle: TextStyle(color: Colors.white54),- isDense: true,- isCollapsed: true,- constraints: BoxConstraints(),- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- filled: false,- contentPadding: EdgeInsets.zero,- ),- onChanged: (value) => widget.onQuery(- value,- _activeSearch?.caseSensitive ?? widget.initialCaseSensitive,- ),- ),- ),- builder: (context, editor) {- final search = widget.search;- final query = search?.query ?? '';- final searching = search?.searching ?? false;- final hasSnapshot = search?.hasSnapshot ?? false;- final count = search?.count ?? 0;- final selected = (search?.selected ?? -1) + 1;- final sensitive =- search?.caseSensitive ?? widget.initialCaseSensitive;- final status = query.isEmpty- ? ''- : searching && !hasSnapshot- ? '…'- : '$selected/$count';- Widget button(- String label,- Widget icon,- VoidCallback? action, {- bool selected = false,- }) => SizedBox(- width: 28,- height: 30,- child: IconButton(- tooltip: label,- onPressed: action,- isSelected: selected,- constraints: const BoxConstraints.tightFor(- width: 28,- height: 30,- ),- padding: EdgeInsets.zero,- visualDensity: VisualDensity.compact,- iconSize: 17,- color: selected ? Colors.white : Colors.white60,- icon: icon,- ),- );- return Row(- children: [- if (widget.readOnly) ...[- const Tooltip(- message: 'This terminal is read only',- child: Icon(- Icons.lock_outline,- size: 14,- color: Colors.white54,- ),- ),- const SizedBox(width: 6),- ],- editor!,- const SizedBox(width: 6),- Semantics(- liveRegion: true,- label: searching && !hasSnapshot- ? 'Searching terminal'- : query.isEmpty- ? 'Find in terminal'- : count == 0- ? 'No matches'- : 'Match $selected of $count',- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 56),- child: ExcludeSemantics(- child: Text(- status,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontSize: 11,- height: 1,- color: count == 0 && query.isNotEmpty && !searching- ? const Color(0xffffb4a9)- : Colors.white54,- ),- ),- ),- ),- ),- const SizedBox(width: 4),- button(- 'Match case',- Text(- 'Aa',- style: TextStyle(- fontSize: 12,- height: 1,- color: sensitive ? Colors.white : Colors.white54,- fontWeight: sensitive- ? FontWeight.w700- : FontWeight.normal,- ),- ),- () {- widget.onQuery(- _text.text,- !(_activeSearch?.caseSensitive ??- widget.initialCaseSensitive),- );- _focus.requestFocus();- },- selected: sensitive,- ),- button(- 'Previous match (⇧⌘G)',- const Icon(Icons.keyboard_arrow_up),- count > 0- ? () {- widget.onStep(-1);- _focus.requestFocus();- }- : null,- ),- button(- 'Next match (⌘G)',- const Icon(Icons.keyboard_arrow_down),- count > 0- ? () {- widget.onStep(1);- _focus.requestFocus();- }- : null,- ),- button(- 'Close find (Esc)',- const Icon(Icons.close),- widget.onClose,- ),- ],- );- },- ),- ),- ),- );-}diff --git a/mobile/lib/widgets/terminal_pane_badges.dart b/mobile/lib/widgets/terminal_pane_badges.dartindex ee4717b8e..4383f856a 100644--- a/mobile/lib/widgets/terminal_pane_badges.dart+++ b/mobile/lib/widgets/terminal_pane_badges.dart@@ -1,45 +1,8 @@import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';import '../shared/theme/app_theme.dart' as grid;import '../theme/app_theme.dart';-/// The pane header's transport badge: a compact topology for the path carrying terminal bytes.-///-/// The three shapes describe one hop, an intermediate hop, and a central server respectively. That-/// makes the modes distinguishable without colour while keeping the badge small enough for a four-pane-/// layout. The wire name `relay` still means the backend WebSocket; only its human-facing label is WS.-class LinkModeMark extends StatelessWidget {- final String mode;-- const LinkModeMark({super.key, required this.mode});-- @override- Widget build(BuildContext context) {- final (icon, color, label) = switch (mode) {- 'p2p' => (- LucideIcons.link2,- AppColors.success,- 'P2P · Direct peer connection',- ),- 'turn' => (- LucideIcons.waypoints,- AppColors.warning,- 'TURN · Via Cloudflare relay',- ),- _ => (- LucideIcons.server,- AppColors.mutedStrong,- 'WS · Via Harness WebSocket relay',- ),- };- return Tooltip(- message: label,- child: Icon(icon, size: 14, color: color, semanticLabel: label),- );- }-}-/// Image/file transfer progress with a cancel action, kept in the pane's corner.class TransferProgressBadge extends StatelessWidget {final String label;@@ -113,22 +76,3 @@ class TransferProgressBadge extends StatelessWidget {);}}--/// The whole tile, carried under the cursor.-///-/// ⚠️ THIS IS DRAWN, NOT PHOTOGRAPHED, AND THE PHOTOGRAPH IS WHY. The obvious-/// way to carry "the whole pane" is RepaintBoundary.toImage() on press — and it-/// FROZE THE APP. That call is a GPU readback on the raster thread, and the-/// raster thread in this app is never idle: every pane holds a terminal that-/// repaints on its own, so asking it to stop and hand a surface back on every-/// pointer-down deadlocked the window. It is not a tuning problem; there is-/// nothing to tune down to.-///-/// So the ghost is built from what is already known — the pane's measured size-/// and its own header — and the body is a plain surface rather than a copy of-/// the scrollback. It reads as the tile because it is tile-SHAPED and carries-/// the tile's name, which is what the eye is following.-///-/// See-through on purpose: a full-size opaque copy sits exactly over the tile-/// being aimed at and hides the "Swap with this pane" highlight that says the-/// drop will land.diff --git a/mobile/lib/widgets/terminal_pane_header.dart b/mobile/lib/widgets/terminal_pane_header.dartdeleted file mode 100644index d327b02d0..000000000--- a/mobile/lib/widgets/terminal_pane_header.dart+++ /dev/null@@ -1,433 +0,0 @@-import 'dart:async';-import 'dart:math' as math;--import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../state/app_state.dart';-import '../terminal/terminal_session.dart';-import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';-import 'agent_drag.dart';-import 'engine_identity.dart';-import 'pane_header_actions.dart';-import 'rename_agent_dialog.dart';-import 'terminal_pane_badges.dart';--/// Horizontal inset shared by the header strip and the Find row that replaces-/// it, so the two line up when Find swaps in.-const double stripPadding = 14;--typedef TerminalNotice = ({String label, String detail, IconData icon});--class TerminalPaneHeader extends StatelessWidget {- final AppNotifier notifier;- final TerminalSession session;- final TerminalNotice? notice;- final bool readOnly;- final VoidCallback? onClose;-- /// Ends the agent (with a confirmation), as the rail's row menu does. Null- /// where the pane cannot name a live agent to end.- final VoidCallback? onDelete;- final bool compact;- final VoidCallback? onToggleZoom;- final bool zoomed;- final VoidCallback? onToggleComposer;- final bool composerVisible;-- /// This strip's drag gesture, or null when there is nothing to drag.- ///- /// Null with a SINGLE pane, and then the strip is inert on purpose: there is- /// no other tile to trade places with, so a drag would have no meaning to- /// give it. It used to move the WINDOW here (window_manager's- /// DragToMoveArea, left over from hiding the title bar) — but once AppKit's- /// `startDragging` takes a gesture it keeps it, so the two meanings cannot- /// share one drag. The window is moved from HarnessTopBar now.- final PaneDragHandle? paneDrag;-- const TerminalPaneHeader({- super.key,- required this.notifier,- required this.session,- this.notice,- this.readOnly = false,- this.onClose,- this.onDelete,- this.compact = false,- this.onToggleZoom,- this.zoomed = false,- this.paneDrag,- this.onToggleComposer,- this.composerVisible = false,- });-- @override- Widget build(BuildContext context) {- // A WATCHER renders the terminal without holding it (see [TerminalSession.watching]), and its- // status is `controlling` — so every switch below has to ask about it FIRST, or it reads as a- // pane that takes typing when it does not.- final watching = session.watching;- final color = watching- ? AppColors.warning- : switch (session.status) {- TerminalSessionStatus.controlling => AppColors.success,- TerminalSessionStatus.opening ||- TerminalSessionStatus.resyncing => AppColors.warning,- TerminalSessionStatus.takenOver => AppColors.warning,- TerminalSessionStatus.error => AppColors.danger,- TerminalSessionStatus.closed => AppColors.mutedStrong,- };- final profile = notifier- .stateOf(session.machineId)- ?.agents- .where((agent) => agent.id == session.agentId)- .firstOrNull- ?.codexHome;- final status =- notice ??- (watching- ? (- label: 'Take control',- icon: Icons.lock_outline,- detail: 'Read only: another app controls this terminal. Take control moves input ownership to this app.',- )- : null) ??- switch (session.status) {- TerminalSessionStatus.controlling => null,- TerminalSessionStatus.opening => (- label: 'Connecting',- icon: Icons.sync,- detail:- 'Connecting to this terminal. Retained output is read only.',- ),- TerminalSessionStatus.resyncing => (- label: 'Restoring',- icon: Icons.sync,- detail: 'Restoring this terminal. Retained output is read only.',- ),- TerminalSessionStatus.takenOver => (- label: 'Take control',- icon: Icons.lock_outline,- detail:- 'Read only: ${session.takenOverBy?.name ?? 'another app'} controls this terminal. Take control moves input ownership to this app.',- ),- TerminalSessionStatus.error || TerminalSessionStatus.closed => (- label: 'Reconnect',- icon: Icons.refresh,- detail:- session.errorMessage ??- session.errorCode ??- 'This stream is closed. Retained output is read only.',- ),- };- final canReconnect =- notice == null &&- !readOnly &&- (watching ||- session.status == TerminalSessionStatus.error ||- session.status == TerminalSessionStatus.closed ||- session.status == TerminalSessionStatus.takenOver);- final machine = notifier.stateOf(session.machineId);- final agent = machine?.agents- .where((a) => a.id == session.agentId)- .firstOrNull;- final project = agent == null ? null : machine?.projectOf(agent);- final machineName = machine?.machine.displayName ?? session.machineId;- final folder = project?.label;- final branch = project?.shownBranch;- final identityDetail = [- session.agentName,- machineName,- if (project != null) project.cwd,- ?project?.branchDetail,- if (profile != null) 'Codex profile: $profile',- 'Double-click to rename',- ].join('\n');- final remoteComposer = machine != null && !machine.isLocalMachine- ? onToggleComposer- : null;- final actionsWidth = remoteComposer == null ? 88.0 : 118.0;- final details = [?folder, ?branch, machineName];- final branchIndex = branch == null ? null : (folder == null ? 0 : 1);- final strip = PaneHeaderHover(- child: SizedBox(- height: compact ? 38 : 46,- child: Padding(- padding: const EdgeInsets.symmetric(horizontal: stripPadding),- child: LayoutBuilder(- builder: (context, constraints) => Row(- children: [- EngineMark(engine: session.engineId, size: 17),- const SizedBox(width: 10),- Expanded(- child: Tooltip(- message: identityDetail,- waitDuration: const Duration(milliseconds: 700),- child: GestureDetector(- behavior: HitTestBehavior.opaque,- onDoubleTap: () => unawaited(- showAgentRenameDialog(- context,- notifier,- session.machineId,- session.agentId,- session.agentName,- ),- ),- child: Text(- session.agentName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- color: AppColors.text,- fontFamily: AppFonts.sans,- fontSize: 13,- fontWeight: FontWeight.w600,- ),- ),- ),- ),- ),- const SizedBox(width: 8),- if (status != null)- ConstrainedBox(- constraints: BoxConstraints(- maxWidth: math.max(- 0,- math.min(- constraints.maxWidth * .3,- constraints.maxWidth - actionsWidth - 110,- ),- ),- ),- child: Align(- alignment: Alignment.centerRight,- child: Tooltip(- message: status.detail,- child: TextButton(- onPressed: canReconnect- // Opening it again is the claim — see- // [AppNotifier.selectAgent].- ? () => notifier.selectAgent(- session.machineId,- session.agentId,- )- : null,- style: TextButton.styleFrom(- foregroundColor: color,- disabledForegroundColor: AppColors.textSoft,- minimumSize: Size.zero,- tapTargetSize: MaterialTapTargetSize.shrinkWrap,- padding: const EdgeInsets.symmetric(- horizontal: 6,- vertical: 4,- ),- ),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- Icon(status.icon, size: 14),- const SizedBox(width: 6),- Flexible(- child: Text(- status.label,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: const TextStyle(fontSize: 11),- ),- ),- ],- ),- ),- ),- ),- )- else if (!compact)- Padding(- padding: const EdgeInsets.all(4),- child: Icon(Icons.circle, size: 8, color: color),- ),- // Which of the three paths carries this pane's bytes. Absent for a local machine's own- // terminal, which has no such distinction and so gets no badge.- //- // The wire word and the word a person reads differ for the middle state, deliberately:- // the CLI sends 'turn' (it is a TURN allocation) but both middle and last are relays to- // a reader, so they read as "relay" and "ws". 'relay' on the wire kept its original- // meaning — the backend WebSocket — so an older CLI is never mislabelled.- if (!compact && session.linkMode != null)- Padding(- padding: const EdgeInsets.symmetric(horizontal: 2),- child: LinkModeMark(mode: session.linkMode!),- ),- ConstrainedBox(- constraints: BoxConstraints(- maxWidth: math.max(- actionsWidth,- constraints.maxWidth * (status == null ? .55 : .3),- ),- ),- child: PaneHeaderActions(- name: session.agentName,- zoomed: zoomed,- onZoom: onToggleZoom,- onDelete: onDelete,- onClose: onClose,- onToggleComposer: remoteComposer,- composerVisible: composerVisible,- details: Tooltip(- message: [- if (project != null) project.cwd,- ?project?.branchDetail,- machineName,- ].join('\n'),- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- for (var i = 0; i < details.length; i++) ...[- if (i > 0)- Text(- ' • ',- style: TextStyle(- fontSize: 10,- color: AppColors.mutedStrong,- ),- ),- Flexible(- child: Row(- mainAxisSize: MainAxisSize.min,- children: [- if (i == branchIndex) ...[- Icon(- LucideIcons.gitBranch300,- size: 12,- color: AppColors.mutedStrong,- ),- const SizedBox(width: 4),- ],- Flexible(- child: Text(- details[i],- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: TextStyle(- fontFamily: AppFonts.sans,- fontSize: 12,- color: AppColors.mutedStrong,- ),- ),- ),- ],- ),- ),- ],- ],- ),- ),- ),- ),- ],- ),- ),- ),- ),- );- final handle = paneDrag;- if (handle == null) return strip;-- return Draggable<PaneDragRef>(- data: handle.ref,- // The grip is kept where the hand took it, so the ghost stays under the- // cursor at the same spot on the header it was picked up by.- dragAnchorStrategy: childDragAnchorStrategy,- onDragStarted: () => paneDragging.value = handle.ref,- onDragEnd: (_) => paneDragging.value = null,- onDraggableCanceled: (_, _) => paneDragging.value = null,- feedback: _PaneGhost(session: session, size: handle.size, header: strip),-- // The header itself does NOT change — the whole tile fades instead, in- // _PaneCell, so what dims is the thing that is moving rather than one- // strip of it.- child: strip,- );- }-}--/// The whole tile, carried under the cursor.-///-/// ⚠️ THIS IS DRAWN, NOT PHOTOGRAPHED, AND THE PHOTOGRAPH IS WHY. The obvious-/// way to carry "the whole pane" is RepaintBoundary.toImage() on press — and it-/// FROZE THE APP. That call is a GPU readback on the raster thread, and the-/// raster thread in this app is never idle: every pane holds a terminal that-/// repaints on its own, so asking it to stop and hand a surface back on every-/// pointer-down deadlocked the window. It is not a tuning problem; there is-/// nothing to tune down to.-///-/// So the ghost is built from what is already known — the pane's measured size-/// and its own header — and the body is a plain surface rather than a copy of-/// the scrollback. It reads as the tile because it is tile-SHAPED and carries-/// the tile's name, which is what the eye is following.-///-/// See-through on purpose: a full-size opaque copy sits exactly over the tile-/// being aimed at and hides the "Swap with this pane" highlight that says the-/// drop will land.-class _PaneGhost extends StatelessWidget {- const _PaneGhost({- required this.session,- required this.size,- required this.header,- });-- final TerminalSession session;-- /// The tile's size, handed down from the grid's LayoutBuilder.- final Size size;-- final Widget header;-- @override- Widget build(BuildContext context) {- grid.AppTheme.watch(context);- final tile = size;- return Material(- color: Colors.transparent,- child: Opacity(- opacity: 0.75,- child: Container(- width: tile.width,- height: tile.height,- decoration: BoxDecoration(- color: grid.AppPalette.windowBg,- border: Border.all(color: AppColors.accent, width: 1.5),- boxShadow: [- BoxShadow(- color: Colors.black.withValues(alpha: 0.45),- blurRadius: 24,- offset: const Offset(0, 10),- ),- ],- ),- child: Column(- children: [- header,- Divider(height: 1, color: AppColors.border),- Expanded(- child: Center(- child: Text(- session.agentName,- style: TextStyle(- color: AppColors.mutedStrong,- fontFamily: AppFonts.sans,- fontSize: 15,- fontWeight: FontWeight.w600,- ),- ),- ),- ),- ],- ),- ),- ),- );- }-}diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex e47f12b06..9fb127283 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -9,12 +9,8 @@ import 'package:xterm/xterm.dart';import '../clipboard/native_clipboard.dart';import '../state/app_state.dart';-import 'agent_drag.dart';-import 'terminal_composer.dart';import '../shortcuts/app_keymap.dart';import '../shortcuts/keymap.dart';-import 'terminal_find_bar.dart';-import '../terminal/terminal_search.dart';import '../terminal/terminal_snapshot.dart';import '../terminal/terminal_binary.dart';import '../terminal/terminal_font_store.dart';@@ -28,32 +24,20 @@ import '../terminal/terminal_theme.dart';import '../terminal/terminal_theme_store.dart';import '../terminal/terminal_viewport.dart';import '../shared/theme/app_theme.dart' as grid;-import '../theme/app_theme.dart';import 'terminal_pane_badges.dart';-import 'terminal_pane_header.dart';--// The header strip, its drag ghost and the small badges are presentation that-// only changes when its inputs do; they live in `terminal_pane_header.dart` and-// `terminal_pane_badges.dart`. Re-exported so this file stays the one import a-// pane needs.-export 'terminal_pane_header.dart' show TerminalNotice, TerminalPaneHeader;+/// One agent's terminal: xterm, its input, its scrollback and its links.+///+/// ⚠️ **No tile chrome.** The desktop's copy of this widget also draws a pane's header strip —+/// engine, title, status, pin, close, drag handle — with a Find bar in it, and a composer box under+/// the terminal. None of that has a copy here: the phone names the agent in its own title over the+/// page (`phone/terminal_title.dart`), has no tile to close, zoom or drag, and types into the+/// terminal itself.class TerminalPanel extends StatefulWidget {final AppNotifier notifier;final TerminalSession session;- /// Takes this tile off the grid. Null when the terminal is the whole window,- /// where there is nothing to close it back to.- final VoidCallback? onClose;- final VoidCallback? onDelete;-- final VoidCallback? onToggleZoom;- final bool zoomed;-- /// This native terminal took the keyboard, so its grid tile becomes focused.- final VoidCallback? onRendererFocus;-- /// Only the focused grid tile may claim keyboard focus on mount/rebuild.+ /// Only the focused page may claim keyboard focus on mount/rebuild.final bool focused;final bool visible;@@ -77,21 +61,6 @@ class TerminalPanel extends StatefulWidget {/// closed the same loop but froze the output for the whole slide as well —/// see [_TerminalPanelState._live].final bool settling;- final Size? viewportSize;-- /// A shared terminal can move to another harness without being remounted.- final (String, int)? paneLocation;- final (int, int, int?)? layoutRequest;- final bool compactHeader;-- /// The tile's own header strip — engine, title, status, pin, close — and- /// whether it is built at all. False on the phone, where [PhoneHeader] already- /// names the agent above this panel, there is no tile to pin, close or drag,- /// and the pane takes the full remaining height (`phone/terminal_page.dart`- /// in the mobile package). Find has no way in there — every- /// [TerminalFindAction] caller lives in the desktop screens — so the row's- /// Find overlay goes with it.- final bool showHeader;final int focusRequest;/// Where the reader is while scrolled up in the history — tmux's copy-mode position,@@ -121,18 +90,6 @@ class TerminalPanel extends StatefulWidget {/// when the host took it: on the phone, an answer's own line while a question is open.final bool Function(String line)? onLineTap;- /// Whether this tile's composer textbox is showing. Only consulted for a remote machine.- final bool composerVisible;- final bool readOnly;- final TerminalNotice? notice;-- /// Flips [composerVisible]. Null where there is no composer to toggle.- final VoidCallback? onToggleComposer;-- /// Lets the header be dragged to trade places with another tile. Null when- /// this is the only tile — see [TerminalPaneHeader.paneDrag].- final PaneDragHandle? paneDrag;-/// Test seam for OS actions; normal panes use the platform launcher.final TerminalLinkOpener? linkOpener;final RemoteMediaDownloader? mediaDownloader;@@ -144,26 +101,11 @@ class TerminalPanel extends StatefulWidget {required this.focused,this.visible = true,this.settling = false,- this.viewportSize,- this.paneLocation,- this.layoutRequest,- this.compactHeader = false,- this.showHeader = true,this.focusRequest = 0,this.scrollback,this.jumpToEndRequest = 0,this.onInputTap,this.onLineTap,- this.composerVisible = false,- this.readOnly = false,- this.notice,- this.onToggleComposer,- this.onClose,- this.onDelete,- this.onToggleZoom,- this.zoomed = false,- this.onRendererFocus,- this.paneDrag,this.linkOpener,this.mediaDownloader,});@@ -184,21 +126,6 @@ class _TerminalPanelState extends State<TerminalPanel>keepScrollOffset: false,);final FocusNode _focusNode = FocusNode();- final FocusNode _composerFocus = FocusNode();- final _findBarKey = GlobalKey<TerminalFindBarState>();- TerminalSearch? _find;- String _lastFindQuery = '';- bool _lastFindCaseSensitive = false;- CellAnchor? _lastFindAnchor;- Buffer? _lastFindBuffer;- TerminalHighlight? _findHighlight;- Buffer? _findPaintedBuffer;- BufferRangeLine? _findPaintedRange;- Buffer? _findOriginBuffer;- CellAnchor? _findOriginLine;- double _findOriginFraction = 0;- bool _findOriginAtEnd = false;- bool _findRevealPending = false;late Terminal _viewTerminal;late GlobalKey<TerminalViewState> _terminalViewKey;Timer? _dialInertiaTimer;@@ -239,8 +166,6 @@ class _TerminalPanelState extends State<TerminalPanel>bool _observingLinkModifiers = false;late final RemoteMediaDownloader _mediaDownloader;MediaDownloadCancellation? _previewCancellation;- Object? _headerPresentation;- Widget? _header;@overridevoid initState() {@@ -252,7 +177,6 @@ class _TerminalPanelState extends State<TerminalPanel>_linkOpener = widget.linkOpener ?? TerminalLinkOpener();_mediaDownloader = widget.mediaDownloader ?? RemoteMediaDownloader();_focusNode.addListener(_handleFocusChange);- _composerFocus.addListener(_handleComposerFocusChange);WidgetsBinding.instance.addObserver(this);widget.session.attachViewport(this);widget.session.addListener(_onSessionChanged);@@ -301,9 +225,6 @@ class _TerminalPanelState extends State<TerminalPanel>super.didUpdateWidget(oldWidget);if (oldWidget.jumpToEndRequest != widget.jumpToEndRequest) _jumpToEnd();if (!identical(oldWidget.session, widget.session)) {- _closeFind(restore: false, focus: false, rebuild: false);- _clearLastFind();- _lastFindQuery = '';_previewCancellation?.cancel();_previewProgress.value = null;oldWidget.session.setCursorBlinkPhase(true);@@ -320,7 +241,6 @@ class _TerminalPanelState extends State<TerminalPanel>(_) => scrollback.value = null,);}- _composerFocusPending = false;_cancelDialInertia();_controller.clearSelection();_viewTerminal.removeListener(_scheduleLinkRefresh);@@ -338,50 +258,32 @@ class _TerminalPanelState extends State<TerminalPanel>if (oldWidget.visible && !widget.visible) {_rememberFollowTail();_focusNode.unfocus();- _composerFocus.unfocus();_cancelDialInertia();_linkPointerPosition = null;_hoveredLink.value = null;_pressedLink = null;_observeLinkModifiers(false);}- if (widget.visible &&- (!oldWidget.visible || oldWidget.paneLocation != widget.paneLocation)) {- _afterTerminalMounted();- }+ if (widget.visible && !oldWidget.visible) _afterTerminalMounted();// The keyboard has finished moving and the pane's height is final. Measure// it once and ask the shell for that size — the single SIGWINCH this whole// gate exists to reduce the animation to.//// `claimFocus: false` on purpose: the keyboard is already up, or already// gone, and whoever owns the caret decided that. Re-claiming here would- // pull it back from the composer, or summon the keyboard again just as the- // user finished dismissing it.+ // summon the keyboard again just as the user finished dismissing it.if (oldWidget.settling && !widget.settling && widget.visible) {_afterTerminalMounted(claimFocus: false);}- if (oldWidget.viewportSize != widget.viewportSize ||- oldWidget.layoutRequest != widget.layoutRequest) {- // Geometry can change while a resize handle or another control owns- // the keyboard. Refresh the viewport without claiming input ownership.- _afterTerminalMounted(claimFocus: false);- }if (widget.focused &&(!oldWidget.focused || oldWidget.focusRequest != widget.focusRequest)) {_claimFocusAfterFrame();}- // Showing or hiding the box changes how many rows the terminal has. Re-measure so the remote- // grid is resized to what is actually on screen.- if (oldWidget.composerVisible != widget.composerVisible) {- _afterTerminalMounted();- }_syncCursorBlink();}@overridevoid dispose() {- _closeFind(restore: false, focus: false, rebuild: false);- _clearLastFind();WidgetsBinding.instance.removeObserver(this);_tickerMode?.removeListener(_syncCursorBlink);_previewCancellation?.cancel();@@ -397,27 +299,15 @@ class _TerminalPanelState extends State<TerminalPanel>_cancelDialInertia();_cursorBlinkTimer?.cancel();_focusNode.removeListener(_handleFocusChange);- _composerFocus.removeListener(_handleComposerFocusChange);_controller.dispose();_scrollController.dispose();_focusNode.dispose();- _composerFocus.dispose();_hoveredLink.dispose();_linkModifierDown.dispose();_previewProgress.dispose();super.dispose();}- /// Whether this pane shows the composer.- ///- /// Only a machine reached over the network charges a round trip per keystroke, so only it gets- /// the box — typing into a local pane already costs well under a millisecond and it would be- /// dead weight across the bottom.- ///- /// The test is `isLocalMachine`, NOT `isRemote`: the app only ever lists machines whose authMode- /// is `remote` (see the filter in `_loadMachines`), so `isRemote` is true for every pane,- /// including this very computer. What separates them is whether the machine's computerId is this- /// one, which is what puts it on the loopback transport./// Whether the renderer may resize the remote shell to this view's height,/// and run the cursor clock.///@@ -434,16 +324,6 @@ class _TerminalPanelState extends State<TerminalPanel>/// stopped the output dead for the whole keyboard slide.bool get _live => widget.visible && !widget.settling;- bool get _showsComposer {- final machineState = widget.notifier.stateOf(widget.session.machineId);- return machineState?.isLocalMachine != true && widget.composerVisible;- }-- /// The composer refuses focus while it is disabled, which it is until the stream goes live. When- /// a selection lands on a still-attaching agent, the claim is parked here and made again from- /// [_onSessionChanged] the moment it starts accepting input.- bool _composerFocusPending = false;-void _onSessionChanged() {if (!mounted) return;_syncCursorBlink();@@ -474,22 +354,6 @@ class _TerminalPanelState extends State<TerminalPanel>}});}- if (!_composerFocusPending) return;- if (!widget.focused || !_showsComposer) {- _composerFocusPending = false;- return;- }- if (widget.readOnly || !widget.session.acceptsInput) return;- _composerFocusPending = false;- // Deferred a frame on purpose. This panel registers its session listener before the composer- // registers its own (a parent's initState runs first), so at this instant the field is still- // built as disabled — and a disabled field REFUSES focus. Claiming after the frame the- // composer rebuilds in is what makes the claim actually land.- WidgetsBinding.instance.addPostFrameCallback((_) {- if (!_canClaimInput || !widget.focused || !_showsComposer) return;- if (widget.readOnly || !widget.session.acceptsInput) return;- _composerFocus.requestFocus();- });}/// The vendored renderer already treats a changed `textStyle` as a full re-layout — see@@ -521,29 +385,16 @@ class _TerminalPanelState extends State<TerminalPanel>? position.pixels / lineHeight - viewportRow!: 0.0;final atEnd = _followTail || position == null;- final originRow = _findOriginLine?.attached == true- ? _findOriginLine!.y- : null;- final originFraction = _findOriginFraction;- final originAtEnd = _findOriginAtEnd;- final match =- _find?.match?.begin ??- (_lastFindAnchor?.attached == true ? _lastFindAnchor!.offset : null);final selection = _controller.selection;final selectedText = selection == null ? null : previous.getText(selection);final locations = remapTerminalRows(previous, next, [if (!atEnd) ?viewportRow,- ?originRow,- ?match?.y,?selection?.begin.y,?selection?.end.y,]);int row(int old) => locations[old] ?? old.clamp(0, next.lines.length - 1);CellOffset location(CellOffset old) =>CellOffset(old.x.clamp(0, terminal.viewWidth - 1), row(old.y));- final wasFinding = _find != null;- _closeFind(restore: false, focus: false, rebuild: false);- _clearLastFind();// Selection anchors belong to a specific circular buffer. Detach them// before the TerminalView starts laying out the replacement terminal._controller.clearSelection();@@ -567,10 +418,6 @@ class _TerminalPanelState extends State<TerminalPanel>(row(viewportRow) + viewportFraction) * lineHeight,);}- if (match != null) {- _lastFindBuffer = next;- _lastFindAnchor = next.createAnchorFromOffset(location(match));- }if (selection != null &&locations.containsKey(selection.begin.y) &&locations.containsKey(selection.end.y)) {@@ -584,35 +431,11 @@ class _TerminalPanelState extends State<TerminalPanel>);}}- if (wasFinding) {- _findOriginBuffer = next;- _findOriginAtEnd = originAtEnd;- _findOriginFraction = originFraction;- if (originRow != null) {- _findOriginLine = next.createAnchor(0, row(originRow));- }- _findRevealPending = true;- _find = TerminalSearch(- terminal,- origin: match == null ? null : location(match),- )..addListener(_onFindChanged);- _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);- }_followTail = atEnd;_afterTerminalMounted(scrollToEnd: atEnd);}- /// Typing in the composer focuses the tile, exactly like clicking into the terminal does.- void _handleComposerFocusChange() {- if (_composerFocus.hasFocus) widget.onRendererFocus?.call();- }-- void _handleFocusChange() {- _syncCursorBlink();- if (_focusNode.hasFocus) {- widget.onRendererFocus?.call();- }- }+ void _handleFocusChange() => _syncCursorBlink();/// Re-establishes the native text-input connection on pane activation.///@@ -627,23 +450,6 @@ class _TerminalPanelState extends State<TerminalPanel>(!navigating && (!widget.focused || !widget.visible))) {return false;}- if (_find != null) {- final bar = _findBarKey.currentState;- if (bar == null) return false;- bar.focusSearch(selectAll: false);- return true;- }- if (_composerFocus.hasFocus) return true;- // On a remote pane the box gets the caret, not the terminal. Landing in the terminal would- // hand the user the per-keystroke path by default — the exact cost the box exists to avoid.- if (_showsComposer && !widget.readOnly) {- if (widget.session.acceptsInput && _composerFocus.canRequestFocus) {- _composerFocus.requestFocus();- return true;- }- _composerFocusPending = true;- return false;- }view.requestKeyboard();return true;}@@ -682,19 +488,11 @@ class _TerminalPanelState extends State<TerminalPanel>/// ticker mode without rebuilding the subtree when a route covers it.void _syncCursorBlink() {final lifecycle = WidgetsBinding.instance.lifecycleState;- final findEnabled =- mounted &&- widget.visible &&- (_tickerMode?.value.enabled ?? false) &&- (lifecycle == null || lifecycle == AppLifecycleState.resumed);- _find?.setEnabled(findEnabled);- if (!findEnabled) _clearFindHighlight();final enabled =mounted &&// `_live`, not `visible`: a cursor phase is a markNeedsPaint on the// terminal, and nothing should repaint it while the keyboard slides._live &&- !widget.readOnly &&_focusNode.hasFocus &&widget.session.acceptsInput &&(_tickerMode?.value.enabled ?? false) &&@@ -788,8 +586,8 @@ class _TerminalPanelState extends State<TerminalPanel>int retries = 2,}) {// Request alignment before this frame's layout, so even a retained pane's- // first visible paint uses its new size. Keep Find's explicit location.- if (scrollToEnd && _find == null) {+ // first visible paint uses its new size.+ if (scrollToEnd) {_cancelDialInertia();_followTail = true;_laidOutTerminalView()?.scrollToBottom();@@ -832,179 +630,12 @@ class _TerminalPanelState extends State<TerminalPanel>renderSize.height ~/ cellSize.height,);}- if (scrollToEnd && _followTail && _find == null) {- view.scrollToBottom();- }- // Never over the composer: a rebuild that re-focuses this tile while someone is typing into- // the box would pull the caret out from under them mid-sentence.+ if (scrollToEnd && _followTail) view.scrollToBottom();if (claimFocus) _claimFocus(view);- if (_find != null) _onFindChanged();if (_linkPointerPosition != null) _hoverLink(_linkPointerPosition);});}- @override- void find(TerminalFindAction action) {- if (!mounted || !widget.visible || !widget.focused) return;- final wasClosed = _find == null;- if (wasClosed) {- final view = _laidOutTerminalView();- if (view == null || !_scrollController.hasClients) return;- final position = _scrollController.position;- final height = view.renderTerminal.lineHeight;- final row = (position.pixels / height).floor().clamp(- 0,- _viewTerminal.buffer.lines.length - 1,- );- _findOriginBuffer = _viewTerminal.buffer;- _findOriginLine = _findOriginBuffer!.createAnchor(0, row);- _findOriginFraction = position.pixels / height - row;- _findOriginAtEnd = position.maxScrollExtent - position.pixels < 1;- var origin = CellOffset(0, row);- if (action != TerminalFindAction.open &&- _lastFindAnchor?.attached == true &&- identical(_lastFindBuffer, _viewTerminal.buffer)) {- final last = _lastFindAnchor!.offset;- origin = CellOffset(- last.x + (action == TerminalFindAction.next ? 1 : 0),- last.y,- );- }- _find = TerminalSearch(_viewTerminal, origin: origin)- ..addListener(_onFindChanged);- _findRevealPending = true;- _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);- _findBarKey.currentState?.focusSearch(search: _find);- setState(() {});- } else if (action == TerminalFindAction.open) {- _findBarKey.currentState?.focusSearch();- }- if (action != TerminalFindAction.open &&- !(wasClosed && action == TerminalFindAction.next)) {- _stepFind(action == TerminalFindAction.next ? 1 : -1);- }- }-- void _queryFind(String query, bool caseSensitive) {- _lastFindQuery = query;- _lastFindCaseSensitive = caseSensitive;- _findRevealPending = true;- _find?.setQuery(query, caseSensitive: caseSensitive);- }-- void _stepFind(int delta) {- _findRevealPending = true;- _find?.step(delta);- }-- void _onFindChanged() {- final search = _find;- if (!mounted || search == null || !widget.visible) return;- final range = search.match;- if (range != _findPaintedRange ||- !identical(_findPaintedBuffer, _viewTerminal.buffer)) {- _clearFindHighlight();- if (range != null) {- _findPaintedBuffer = _viewTerminal.buffer;- _findPaintedRange = range;- _findHighlight = _controller.highlight(- p1: _viewTerminal.buffer.createAnchorFromOffset(range.begin),- p2: _viewTerminal.buffer.createAnchorFromOffset(range.end),- color: const Color(0x99cf8e25),- );- }- }- if (_findRevealPending && search.hasSnapshot && range != null) {- final render = _laidOutTerminalView()?.renderTerminal;- if (render == null || !_scrollController.hasClients) return;- _findRevealPending = false;- final position = _scrollController.position;- final top = range.begin.y * render.lineHeight + 10;- final bottom = (range.end.y + 1) * render.lineHeight + 10;- final safeTop = position.pixels + 10;- final safeBottom = position.pixels + position.viewportDimension - 10;- final offset = top < safeTop- ? top - 10- : bottom > safeBottom- ? bottom - position.viewportDimension + 10- : position.pixels;- final target = offset.clamp(- position.minScrollExtent,- position.maxScrollExtent,- );- if (target != position.pixels) position.jumpTo(target);- }- }-- void _clearFindHighlight() {- final highlight = _findHighlight;- _findHighlight = null;- _findPaintedBuffer = null;- _findPaintedRange = null;- if (highlight == null) return;- highlight.dispose();- highlight.p1.dispose();- highlight.p2.dispose();- }-- void _clearLastFind() {- _lastFindAnchor?.dispose();- _lastFindAnchor = null;- _lastFindBuffer = null;- }-- void _closeFind({- bool restore = true,- bool focus = true,- bool rebuild = true,- }) {- final search = _find;- if (search == null) return;- final match = search.match;- if (match != null) {- _clearLastFind();- _lastFindAnchor = _viewTerminal.buffer.createAnchorFromOffset(- match.begin,- );- _lastFindBuffer = _viewTerminal.buffer;- }- _find = null;- _findBarKey.currentState?.releaseSearchFocus();- search.removeListener(_onFindChanged);- search.dispose();- _clearFindHighlight();- if (restore &&- identical(_findOriginBuffer, _viewTerminal.buffer) &&- _scrollController.hasClients) {- final height = _laidOutTerminalView()?.renderTerminal.lineHeight;- final position = _scrollController.position;- if (height != null) {- final offset = _findOriginAtEnd- ? position.maxScrollExtent- : _findOriginLine?.attached == true- ? (_findOriginLine!.y + _findOriginFraction) * height- : 0.0;- position.jumpTo(- offset.clamp(position.minScrollExtent, position.maxScrollExtent),- );- }- }- _findOriginLine?.dispose();- _findOriginLine = null;- _findOriginBuffer = null;- if (rebuild && mounted) setState(() {});- if (focus) {- // The retained terminal is already mounted. Return its input connection- // now: the next key can arrive before Find's removal is painted.- final view = _laidOutTerminalView();- if (view != null) {- _claimFocus(view);- } else {- _claimFocusAfterFrame();- }- }- }-@overridevoid scroll(int phase, int dy, int velocity) {if (phase == 0) _cancelDialInertia();@@ -1123,7 +754,7 @@ class _TerminalPanelState extends State<TerminalPanel>void _onContentInserted(KeyboardInsertedContent content) {final bytes = content.data;if (bytes == null || bytes.isEmpty) return;- if (widget.readOnly || !widget.session.acceptsInput) return;+ if (!widget.session.acceptsInput) return;if (bytes.length > terminalLocalImagePasteMaxPayloadBytes) return;final machine = widget.notifier.stateOf(widget.session.machineId);if (machine == null || !machine.terminalImagePasteAvailable) return;@@ -1131,7 +762,7 @@ class _TerminalPanelState extends State<TerminalPanel>}Future<void> _paste() async {- if (widget.readOnly || !widget.session.acceptsInput) return;+ if (!widget.session.acceptsInput) return;final text = (await Clipboard.getData(Clipboard.kTextPlain))?.text;if (text != null && text.isNotEmpty) {// A binary TerminalBinaryKind.paste frame rides the same AEAD channel as every other terminal@@ -1255,7 +886,7 @@ class _TerminalPanelState extends State<TerminalPanel>void _publishScrollback(ScrollPosition position) {final scrollback = widget.scrollback;if (scrollback == null) return;- if (_followTail || _find != null) {+ if (_followTail) {scrollback.value = null;return;}@@ -1437,9 +1068,6 @@ class _TerminalPanelState extends State<TerminalPanel>grid.AppTheme.watch(context);final session = widget.session;_syncTerminal(session.terminal);- final machineState = widget.notifier.stateOf(session.machineId);- final remote = machineState != null && !machineState.isLocalMachine;- final showComposer = _showsComposer;return KeymapRegion(contextKind: KeymapContext.terminal,composing: () =>@@ -1449,80 +1077,6 @@ class _TerminalPanelState extends State<TerminalPanel>color: grid.AppPalette.windowBg,child: Column(children: [- if (widget.showHeader)- Stack(- children: [- Visibility(- visible: _find == null,- maintainSize: true,- maintainAnimation: true,- maintainState: true,- child: _buildHeader(context),- ),- // Attach the focused pane's input before Find is requested.- // Hidden/unfocused panes need no dormant editor or index.- if (_find != null || (widget.visible && widget.focused))- Positioned.fill(- child: Offstage(- offstage: _find == null,- child: LayoutBuilder(- builder: (context, constraints) => Row(- children: [- if (constraints.maxWidth > 520)- Expanded(- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: stripPadding,- ),- child: Text(- session.agentName,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: const TextStyle(- fontSize: 13,- color: Colors.white70,- ),- ),- ),- )- else- const Spacer(),- SizedBox(- width: math.min(constraints.maxWidth, 380),-- child: Padding(- padding: const EdgeInsets.symmetric(- horizontal: 6,- vertical: 4,- ),- child: TerminalFindBar(- key: _findBarKey,- search: _find,- initialQuery: _lastFindQuery,- initialCaseSensitive:- _lastFindCaseSensitive,- readOnly:- widget.readOnly ||- !session.acceptsInput,- onQuery: _queryFind,- onStep: _stepFind,- onClose: _closeFind,- onFocus: () =>- widget.onRendererFocus?.call(),- ),- ),- ),- ],- ),- ),- ),- ),- ],- ),-- // Goes with the row above it: the phone draws its own rule under- // [PhoneHeader], and keeping this one would stack two.- if (widget.showHeader) Divider(height: 1, color: AppColors.border),Expanded(child: Stack(children: [@@ -1542,8 +1096,8 @@ class _TerminalPanelState extends State<TerminalPanel>resizeBuffer: false,scrollController: _scrollController,focusNode: _focusNode,- autofocus: widget.focused && !showComposer,- readOnly: widget.readOnly || !session.acceptsInput,+ autofocus: widget.focused,+ readOnly: !session.acceptsInput,// iOS answers Backspace over an empty native buffer// with nothing at all (`deleteBackward` in// FlutterTextInputPlugin.mm), so a line the keyboard@@ -1650,86 +1204,11 @@ class _TerminalPanelState extends State<TerminalPanel>],),),- // The grip is shown whether or not the box is: collapsed, it is the only way back.- if (!widget.compactHeader &&- remote &&- widget.onToggleComposer != null)- ComposerGrip(- expanded: widget.composerVisible,- onPressed: widget.onToggleComposer!,- ),- if (showComposer)- TerminalComposer(- session: session,- focusNode: _composerFocus,- inputEnabled: !widget.readOnly,- ),],),),);}-- /// Visibility and focus affect the renderer, not its title and controls.- /// Retain that subtree until its presentation changes. Callback wrappers- /// resolve the current widget so cached controls never retain an old action.- Widget _buildHeader(BuildContext context) {- final session = widget.session;- final machine = widget.notifier.stateOf(session.machineId);- final agent = machine?.agents- .where((a) => a.id == session.agentId)- .firstOrNull;- final presentation = (- theme: Theme.of(context),- brightness: grid.AppTheme.brightness.value,- fontFamily: AppFonts.sans,- notifier: widget.notifier,- session: session,- name: session.agentName,- status: session.status,- notice: widget.notice,- readOnly: widget.readOnly,- error: session.errorMessage ?? session.errorCode,- link: session.linkMode,- machine: machine?.machine,- local: machine?.isLocalMachine,- agent: agent,- project: agent == null ? null : machine?.projectOf(agent),- compact: widget.compactHeader,- close: widget.onClose != null,- delete: widget.onDelete != null,- composer: widget.composerVisible,- toggleComposer: widget.onToggleComposer != null,- zoomed: widget.zoomed,- zoom: widget.onToggleZoom != null,- dragId: widget.paneDrag?.ref.paneId,- dragSize: widget.paneDrag?.size,- );- if (_headerPresentation != presentation) {- _headerPresentation = presentation;- _header = TerminalPaneHeader(- notifier: widget.notifier,- session: session,- notice: widget.notice,- readOnly: widget.readOnly,- compact: widget.compactHeader,- zoomed: widget.zoomed,- onToggleZoom: widget.onToggleZoom == null- ? null- : () => widget.onToggleZoom?.call(),- onClose: widget.onClose == null ? null : () => widget.onClose?.call(),- onDelete: widget.onDelete == null- ? null- : () => widget.onDelete?.call(),- composerVisible: widget.composerVisible,- onToggleComposer: widget.onToggleComposer == null- ? null- : () => widget.onToggleComposer?.call(),- paneDrag: widget.paneDrag,- );- }- return _header!;- }}/// The "⌘-click to open" hint, and the click cursor that goes with it.diff --git a/mobile/test/terminal_panel_backspace_test.dart b/mobile/test/terminal_panel_backspace_test.dartindex 1e9d6ae7f..8663446c2 100644--- a/mobile/test/terminal_panel_backspace_test.dart+++ b/mobile/test/terminal_panel_backspace_test.dart@@ -49,7 +49,6 @@ void main() {notifier: notifier,session: session,focused: false,- showHeader: false,),),),diff --git a/mobile/test/terminal_panel_input_tap_test.dart b/mobile/test/terminal_panel_input_tap_test.dartindex e53741e3d..aa29cbbe4 100644--- a/mobile/test/terminal_panel_input_tap_test.dart+++ b/mobile/test/terminal_panel_input_tap_test.dart@@ -42,7 +42,6 @@ void main() {notifier: notifier,session: session,focused: false,- showHeader: false,onInputTap: onInputTap,),),diff --git a/mobile/test/terminal_panel_render_test.dart b/mobile/test/terminal_panel_render_test.dartindex 3de28a851..40698234c 100644--- a/mobile/test/terminal_panel_render_test.dart+++ b/mobile/test/terminal_panel_render_test.dart@@ -58,7 +58,6 @@ void main() {focused: false,visible: visible,settling: settling,- showHeader: false,),),),