Skip to content

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.

Transfer keyboard input immediately during navigation

deec35e298ffc73
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index ea9953652..c19a50219 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -569,12 +569,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (_dialogOpen || _spokenPaletteOpen || !mounted) return;
_closeSearch();
_dialogOpen = true;
+ // The route must not restore an old terminal while the destination changes
+ // behind a dialog. Return input explicitly when that dialog finishes.
+ _canvasFocus.descendantsAreFocusable = false;
if (_native) _syncNative();
try {
await action();
} finally {
_dialogOpen = false;
- if (_native && mounted) _syncNative();
+ if (mounted) {
+ _canvasFocus.descendantsAreFocusable = _search == null;
+ if (_search == null &&
+ ModalRoute.of(context)?.isCurrent != false &&
+ app.focusedPane?.session?.focusInput() != true) {
+ _shellFocus.requestFocus();
+ }
+ if (_native) _syncNative();
+ }
}
if (restoreEntry) await _ensureEmptyEntry();
}
diff --git a/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dart
index e67957a99..12b7c5618 100644
--- a/desktop/lib/terminal/terminal_session.dart
+++ b/desktop/lib/terminal/terminal_session.dart
@@ -1112,6 +1112,8 @@ class TerminalSession extends ChangeNotifier {
void find(TerminalFindAction action) => _viewport?.find(action);
+ bool focusInput() => _viewport?.focusInput() ?? false;
+
/// Coalescing windows for the two things the user drives directly.
///
/// Both are leading + trailing: act on the first event, batch the rest. A flat trailing debounce
diff --git a/desktop/lib/terminal/terminal_viewport.dart b/desktop/lib/terminal/terminal_viewport.dart
index d883d8578..639a7f912 100644
--- a/desktop/lib/terminal/terminal_viewport.dart
+++ b/desktop/lib/terminal/terminal_viewport.dart
@@ -11,4 +11,8 @@ abstract interface class TerminalViewport {
/// 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/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 0b5c7b35e..1c2f83937 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -227,17 +227,34 @@ class _SwarmCanvas extends StatefulWidget {
class _SwarmCanvasState extends State<_SwarmCanvas> {
final _scroll = ScrollController(keepScrollOffset: false);
final _offsets = <String, double>{};
+ final _inputLayers = <int, GlobalKey<_PaneLayerState>>{};
+ final _idleFocus = FocusNode(
+ debugLabel: 'Swarm navigation',
+ skipTraversal: true,
+ );
+ late Object _lastInputDestination;
final _resizeFocus = FocusNode(debugLabel: 'Resize focused agent');
final _resizeHelp = OverlayPortalController();
- late int _resizeRequest = widget.notifier.paneResizeRequest;
- late String _activeId = widget.notifier.activeSwarmId;
- late int _focusRequest = widget.notifier.paneFocusRequest;
+ late int _resizeRequest;
+ late String _activeId;
+ late int _focusRequest;
Size? _viewportSize;
bool _focusRevealPending = false;
+ Object get _inputDestination => (
+ widget.notifier.activeSwarmId,
+ widget.notifier.focusedPaneId,
+ widget.notifier.paneFocusRequest,
+ widget.notifier.zoomedPaneId,
+ );
+
@override
void initState() {
super.initState();
+ _lastInputDestination = _inputDestination;
+ _resizeRequest = widget.notifier.paneResizeRequest;
+ _activeId = widget.notifier.activeSwarmId;
+ _focusRequest = widget.notifier.paneFocusRequest;
widget.notifier.addListener(_onAppChanged);
terminalFontStore.addListener(_onFontChanged);
}
@@ -251,12 +268,18 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
_offsets.clear();
_activeId = widget.notifier.activeSwarmId;
_focusRequest = widget.notifier.paneFocusRequest;
+ _resizeRequest = widget.notifier.paneResizeRequest;
+ _lastInputDestination = _inputDestination;
if (_scroll.hasClients) _scroll.jumpTo(0);
}
}
void _onAppChanged() {
final app = widget.notifier;
+ if (_lastInputDestination != _inputDestination) {
+ _lastInputDestination = _inputDestination;
+ _syncInputFocus();
+ }
if (_resizeRequest != app.paneResizeRequest) {
_resizeRequest = app.paneResizeRequest;
_resizeFocus.requestFocus();
@@ -280,6 +303,28 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
setState(() {});
}
+ void _syncInputFocus() {
+ final app = widget.notifier;
+ final visible = {
+ for (final pane in app.panes)
+ if (app.zoomedPaneId == null || pane.id == app.zoomedPaneId) pane.id,
+ };
+ // Exclude the outgoing views and enable the destination's existing focus
+ // tree now. Painting/layout still happens in the normal scheduled frame.
+ for (final entry in _inputLayers.entries) {
+ entry.value.currentState?.prepareInput(visible.contains(entry.key));
+ }
+ if (!_idleFocus.canRequestFocus ||
+ ModalRoute.of(context)?.isCurrent == false) {
+ return;
+ }
+ if (app.focusedPane?.session?.focusInput() != true) {
+ // Blank pages and not-yet-mounted destinations must release the old
+ // terminal's text client immediately, without focusing welcome search.
+ _idleFocus.requestFocus();
+ }
+ }
+
void _revealFocusedPane({bool correctingLayout = false}) {
final viewport = _viewportSize;
if (viewport == null || !_scroll.hasClients) return;
@@ -325,6 +370,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
widget.notifier.removeListener(_onAppChanged);
terminalFontStore.removeListener(_onFontChanged);
_resizeFocus.dispose();
+ _idleFocus.dispose();
_scroll.dispose();
super.dispose();
}
@@ -418,50 +464,61 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
for (var i = 0; i < visible.length; i++)
visible[i].id: layout.rectangles[i],
};
+ final retainedIds = app.allPanes.map((pane) => pane.id).toSet();
+ _inputLayers.removeWhere((id, _) => !retainedIds.contains(id));
// The scroll view stays mounted even when content fits. Its maximum
// extent is then zero; keeping its ancestry is what avoids grafting.
- return SingleChildScrollView(
- controller: _scroll,
- child: SizedBox(
- width: constraints.maxWidth,
- height: layout.height,
- child: Stack(
- children: [
- if (visible.isEmpty)
- Positioned.fill(
- child: widget.empty ?? _EmptyGrid(notifier: app),
- ),
- for (final pane in app.allPanes)
- if (rectangles.containsKey(pane.id) ||
- pane.lastViewSize != null)
- Positioned.fromRect(
- key: ValueKey(pane.id),
- rect:
- rectangles[pane.id] ?? Offset.zero & pane.lastViewSize!,
- child: _PaneLayer(
- session: pane.session,
- visible: rectangles.containsKey(pane.id),
- presentation: _presentation(
- pane,
- rectangles.containsKey(pane.id),
- ),
- child: _PaneCell(
- key: pane.cellKey,
- notifier: app,
- pane: pane,
- dragging: widget.dragging,
+ return Focus(
+ focusNode: _idleFocus,
+ includeSemantics: false,
+ child: SingleChildScrollView(
+ controller: _scroll,
+ child: SizedBox(
+ width: constraints.maxWidth,
+ height: layout.height,
+ child: Stack(
+ children: [
+ if (visible.isEmpty)
+ Positioned.fill(
+ child: widget.empty ?? _EmptyGrid(notifier: app),
+ ),
+ for (final pane in app.allPanes)
+ if (rectangles.containsKey(pane.id) ||
+ pane.lastViewSize != null)
+ Positioned.fromRect(
+ key: ValueKey(pane.id),
+ rect:
+ rectangles[pane.id] ??
+ Offset.zero & pane.lastViewSize!,
+ child: _PaneLayer(
+ key: _inputLayers.putIfAbsent(
+ pane.id,
+ () => GlobalKey<_PaneLayerState>(),
+ ),
+ session: pane.session,
visible: rectangles.containsKey(pane.id),
- swarmMode: true,
- onSplit: widget.onSplit,
+ presentation: _presentation(
+ pane,
+ rectangles.containsKey(pane.id),
+ ),
+ child: _PaneCell(
+ key: pane.cellKey,
+ notifier: app,
+ pane: pane,
+ dragging: widget.dragging,
+ visible: rectangles.containsKey(pane.id),
+ swarmMode: true,
+ onSplit: widget.onSplit,
+ ),
),
),
+ if (app.zoomedPaneId == null &&
+ layout.arrangement?.dividers.isNotEmpty == true)
+ Positioned.fill(
+ child: _resizeLayer(layout, constraints.biggest),
),
- if (app.zoomedPaneId == null &&
- layout.arrangement?.dividers.isNotEmpty == true)
- Positioned.fill(
- child: _resizeLayer(layout, constraints.biggest),
- ),
- ],
+ ],
+ ),
),
),
);
@@ -631,6 +688,7 @@ class _SwarmGeometry {
/// update a replaced session; showing it applies fresh machine/agent metadata.
class _PaneLayer extends StatefulWidget {
const _PaneLayer({
+ super.key,
required this.session,
required this.visible,
required this.presentation,
@@ -647,11 +705,24 @@ class _PaneLayer extends StatefulWidget {
}
class _PaneLayerState extends State<_PaneLayer> {
+ final _focus = FocusNode(canRequestFocus: false, skipTraversal: true);
late Widget _layer = _buildLayer();
+ @override
+ void initState() {
+ super.initState();
+ prepareInput(widget.visible);
+ }
+
+ void prepareInput(bool visible) {
+ _focus.descendantsAreFocusable = visible;
+ _focus.descendantsAreTraversable = visible;
+ }
+
@override
void didUpdateWidget(_PaneLayer oldWidget) {
super.didUpdateWidget(oldWidget);
+ prepareInput(widget.visible);
if (oldWidget.visible != widget.visible ||
oldWidget.presentation != widget.presentation ||
!identical(oldWidget.session, widget.session)) {
@@ -662,11 +733,21 @@ class _PaneLayerState extends State<_PaneLayer> {
@override
Widget build(BuildContext context) => _layer;
+ @override
+ void dispose() {
+ _focus.dispose();
+ super.dispose();
+ }
+
Widget _buildLayer() => Offstage(
offstage: !widget.visible,
child: TickerMode(
enabled: widget.visible,
- child: ExcludeFocus(excluding: !widget.visible, child: widget.child),
+ child: Focus.withExternalFocusNode(
+ focusNode: _focus,
+ includeSemantics: false,
+ child: widget.child,
+ ),
),
);
}
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index f92251b8d..c284f8812 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -335,7 +335,7 @@ class _TerminalPanelState extends State<TerminalPanel>
// 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 (!mounted || !widget.focused || !_showsComposer) return;
+ if (!_canClaimInput || !widget.focused || !_showsComposer) return;
if (widget.readOnly || !widget.session.acceptsInput) return;
_composerFocus.requestFocus();
});
@@ -463,7 +463,7 @@ class _TerminalPanelState extends State<TerminalPanel>
}
}
- /// Re-establishes the native text-input connection after a rail selection.
+ /// Re-establishes the native text-input connection on pane activation.
///
/// Replacing an agent remounts TerminalView but deliberately keeps this
/// FocusNode. A plain requestFocus is a no-op when that node already owns
@@ -471,24 +471,48 @@ class _TerminalPanelState extends State<TerminalPanel>
/// the terminal. TerminalView.requestKeyboard handles both cases: it moves
/// focus when needed, or opens the connection immediately when focus stayed
/// on this tile. That is essential for ordinary keys and IMEs alike.
- void _claimFocus(TerminalViewState view) {
- if (!mounted || !widget.focused || !widget.visible) return;
+ bool _claimFocus(TerminalViewState view, {bool navigating = false}) {
+ if (!_canClaimInput ||
+ (!navigating && (!widget.focused || !widget.visible))) {
+ return false;
+ }
if (_find != null) {
- _findBarKey.currentState?.focusSearch(selectAll: false);
- return;
+ final bar = _findBarKey.currentState;
+ if (bar == null) return false;
+ bar.focusSearch(selectAll: false);
+ return true;
}
- if (_composerFocus.hasFocus) return;
+ 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) {
+ if (widget.session.acceptsInput && _composerFocus.canRequestFocus) {
_composerFocus.requestFocus();
- } else {
- _composerFocusPending = true;
+ return true;
}
- return;
+ _composerFocusPending = true;
+ return false;
}
view.requestKeyboard();
+ return true;
+ }
+
+ bool get _canClaimInput =>
+ mounted &&
+ _focusNode.canRequestFocus &&
+ ModalRoute.of(context)?.isCurrent != false;
+
+ @override
+ bool focusInput() {
+ // The model has already selected this retained view, but widget visibility
+ // and focus flags will not catch up until the canvas's next frame.
+ if (!_canClaimInput ||
+ !identical(widget.notifier.focusedPane?.session, widget.session)) {
+ return false;
+ }
+ final view = _laidOutTerminalView();
+ if (view == null) return false;
+ return _claimFocus(view, navigating: true);
}
void _claimFocusAfterFrame() {
diff --git a/desktop/test/swarm_immediate_input_test.dart b/desktop/test/swarm_immediate_input_test.dart
new file mode 100644
index 000000000..3d86463e4
--- /dev/null
+++ b/desktop/test/swarm_immediate_input_test.dart
@@ -0,0 +1,300 @@
+import 'dart:convert';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/terminal/terminal_binary.dart';
+import 'package:harness/terminal/terminal_session.dart';
+import 'package:harness/widgets/terminal_composer.dart';
+import 'package:xterm/xterm.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap;
+import 'keymap_runtime_test.dart' show mount, native, nativeChannel;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+import 'terminal_find_test.dart' show findField, finishFind, output;
+
+Future<void> command(
+ WidgetTester tester,
+ LogicalKeyboardKey key, {
+ bool shift = false,
+}) async {
+ await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft);
+ if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyEvent(key);
+ if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
+ await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft);
+}
+
+void main() {
+ for (final nativeEntry in [false, true]) {
+ for (final action in [
+ 'pane',
+ 'zoomed pane',
+ 'waiting composer',
+ 'tab',
+ 'close pane',
+ 'close tab',
+ 'new tab',
+ ]) {
+ testWidgets(
+ '$action owns immediate input before a frame (native=$nativeEntry)',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final keymap = MemoryKeymap();
+ final firstInput = <TerminalBinaryFrame>[];
+ final secondInput = <TerminalBinaryFrame>[];
+ final first = app.adoptSessionForTest(terminal('a0', firstInput));
+ if (action == 'waiting composer') {
+ first.session!.status = TerminalSessionStatus.opening;
+ app.toggleComposer(first.id);
+ }
+ final firstTab = app.activeSwarmId;
+ final separateTabs = action == 'tab' || action == 'close tab';
+ if (separateTabs) app.newSwarm();
+ final second = app.adoptSessionForTest(terminal('a1', secondInput));
+ final secondTab = app.activeSwarmId;
+ if (nativeEntry) {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ (_) async => null,
+ );
+ }
+ try {
+ await mount(tester, app, keymap, native: nativeEntry);
+ if (action == 'zoomed pane') {
+ app.toggleZoomPane();
+ await tester.pump();
+ }
+ if (separateTabs) {
+ app.selectSwarm(firstTab);
+ await tester.pump();
+ app.selectSwarm(secondTab);
+ await tester.pump();
+ }
+ expect(app.focusedPane, same(second));
+ final before = tester
+ .stateList<TerminalViewState>(
+ find.byType(TerminalView, skipOffstage: false),
+ )
+ .map((state) => state.renderTerminal)
+ .toList();
+ final (commandId, key) = switch (action) {
+ 'pane' || 'zoomed pane' || 'waiting composer' => (
+ 'pane.focus_left',
+ LogicalKeyboardKey.arrowLeft,
+ ),
+ 'tab' => ('swarm.select_1', LogicalKeyboardKey.digit1),
+ 'close pane' => ('pane.close', LogicalKeyboardKey.keyW),
+ 'close tab' => ('swarm.close', LogicalKeyboardKey.keyW),
+ _ => ('swarm.new', LogicalKeyboardKey.keyT),
+ };
+ if (nativeEntry) {
+ await native(tester, 'keymapCommand', {'command': commandId});
+ } else {
+ await command(tester, key, shift: action == 'close pane');
+ }
+ // Both events arrive before the canvas updates its widgets.
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ if (tester.testTextInput.hasAnyClients) {
+ tester.testTextInput.enterText('next');
+ }
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(secondInput, isEmpty, reason: 'The old agent owns no input');
+ if (action == 'new tab') {
+ expect(app.panes, isEmpty);
+ expect(firstInput, isEmpty);
+ expect(
+ tester
+ .widget<TextField>(
+ find.byKey(const ValueKey('harness-start-search')),
+ )
+ .focusNode!
+ .hasFocus,
+ isFalse,
+ );
+ } else if (action == 'waiting composer') {
+ expect(app.focusedPane, same(first));
+ expect(firstInput, isEmpty);
+ await output(first.session!, 0, 'ready\r\n', keyframe: true);
+ await tester.pump();
+ final composer = find.descendant(
+ of: find.byType(TerminalComposer),
+ matching: find.byType(TextField),
+ );
+ expect(
+ tester.widget<TextField>(composer).focusNode!.hasFocus,
+ isTrue,
+ );
+ tester.testTextInput.enterText('Ready to continue');
+ await tester.pump();
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ 'Ready to continue',
+ );
+ expect(firstInput, isEmpty);
+ } else {
+ expect(app.focusedPane, same(first));
+ expect(firstInput.expand((frame) => frame.bytes).toList(), [
+ 27,
+ 91,
+ 68,
+ ...utf8.encode('next'),
+ ]);
+ expect(
+ tester
+ .stateList<TerminalViewState>(
+ find.byType(TerminalView, skipOffstage: false),
+ )
+ .map((state) => state.renderTerminal),
+ everyElement(isIn(before)),
+ reason: 'Navigation retains existing terminal renderers',
+ );
+ }
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ keymap.dispose();
+ if (nativeEntry) {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ nativeChannel,
+ null,
+ );
+ }
+ }
+ },
+ );
+ }
+ }
+
+ for (final editor in ['composer', 'Find']) {
+ testWidgets(
+ 'returning to $editor preserves its draft and immediate input',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final keymap = MemoryKeymap();
+ final input = <TerminalBinaryFrame>[];
+ final first = app.adoptSessionForTest(terminal('a0', input));
+ app.adoptSessionForTest(terminal('a1', input));
+ app.focusPane(first.id);
+ if (editor == 'composer') app.toggleComposer(first.id);
+ try {
+ await mount(tester, app, keymap);
+ if (editor == 'Find') {
+ await command(tester, LogicalKeyboardKey.keyF);
+ await tester.pump();
+ }
+ final field = editor == 'Find'
+ ? findField
+ : find.descendant(
+ of: find.byType(TerminalComposer),
+ matching: find.byType(TextField),
+ );
+ await tester.enterText(field, 'draft');
+ if (editor == 'Find') await finishFind(tester);
+ final controller = tester.widget<TextField>(field).controller!;
+ final focus = tester.widget<TextField>(field).focusNode!;
+ await command(tester, LogicalKeyboardKey.arrowRight);
+ await tester.pump();
+ await command(tester, LogicalKeyboardKey.arrowLeft);
+ expect(focus.hasFocus, isTrue);
+ expect(controller.text, 'draft');
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ expect(
+ controller.selection,
+ const TextSelection.collapsed(offset: 4),
+ );
+ const editing = TextEditingValue(
+ text: 'draft 日本',
+ selection: TextSelection.collapsed(offset: 8),
+ composing: TextRange(start: 6, end: 8),
+ );
+ tester.testTextInput.updateEditingValue(editing);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(controller.value, editing);
+ expect(focus.hasFocus, isTrue);
+ expect(input, isEmpty);
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ keymap.dispose();
+ }
+ },
+ );
+ }
+
+ for (final change in ['destination', 'waiting composer']) {
+ testWidgets('a background $change cannot take a dialog editor', (
+ tester,
+ ) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final keymap = MemoryKeymap();
+ final input = <TerminalBinaryFrame>[];
+ final first = app.adoptSessionForTest(terminal('a0', input));
+ final secondSession = terminal('a1', input);
+ final second = app.adoptSessionForTest(secondSession);
+ if (change == 'waiting composer') {
+ secondSession.status = TerminalSessionStatus.opening;
+ app.toggleComposer(second.id);
+ }
+ try {
+ await mount(tester, app, keymap);
+ await command(tester, LogicalKeyboardKey.keyR, shift: true);
+ await tester.pumpAndSettle();
+ final field = tester.widget<TextField>(
+ find.descendant(
+ of: find.byType(AlertDialog),
+ matching: find.byType(TextField),
+ ),
+ );
+ expect(field.focusNode!.hasFocus, isTrue);
+ if (change == 'waiting composer') {
+ await output(secondSession, 0, 'ready\r\n', keyframe: true);
+ expect(secondSession.acceptsInput, isTrue);
+ } else {
+ app.focusPane(first.id);
+ }
+ await tester.idle();
+ tester.testTextInput.enterText('Still editing');
+ await tester.pump();
+ expect(field.focusNode!.hasFocus, isTrue);
+ expect(field.controller!.text, 'Still editing');
+ expect(input, isEmpty);
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ expect(
+ app.focusedPane,
+ same(change == 'waiting composer' ? second : first),
+ );
+ if (change == 'waiting composer') {
+ final composer = find.descendant(
+ of: find.byType(TerminalComposer),
+ matching: find.byType(TextField),
+ );
+ expect(
+ tester.widget<TextField>(composer).focusNode!.hasFocus,
+ isTrue,
+ );
+ tester.testTextInput.enterText('Continue here');
+ await tester.pumpAndSettle();
+ expect(
+ tester.widget<TextField>(composer).controller!.text,
+ 'Continue here',
+ );
+ expect(input, isEmpty);
+ } else {
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(input.single.streamId, first.session!.streamId);
+ await tester.pumpAndSettle();
+ }
+ } finally {
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ keymap.dispose();
+ }
+ });
+ }
+}
diff --git a/docs/harness-agent-first-tabs.md b/docs/harness-agent-first-tabs.md
index 953a4ee34..ccfac30af 100644
--- a/docs/harness-agent-first-tabs.md
+++ b/docs/harness-agent-first-tabs.md
@@ -97,6 +97,16 @@ pane when switching away and back. Closing views
keeps agent runtimes alive. Stored layout formats and internal command IDs remain
compatible.
+Switching between panes or tabs, closing them, or moving between zoomed panes
+transfers keyboard and text input to the ready retained view before the next
+rendered frame. Its existing terminal, composer or
+Find field receives the next key with its draft and selection intact. Blank
+pages release the previous terminal immediately and leave welcome search
+unfocused. A connecting composer releases the old input connection and receives
+focus once ready. Dialogs keep input while background destinations or connection
+state change; dismissal returns it to the current destination without restoring an
+older agent's focus.
+
## Pane chrome
The left side contains only the agent icon and session name. The right side
diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.md
index 6f7c3c863..b3843bcb5 100644
--- a/docs/harness-v2-performance.md
+++ b/docs/harness-v2-performance.md
@@ -12,6 +12,43 @@ It prints `SWARM_BENCH` JSON records. Its filename deliberately does not end in
## Current continuation benchmark (2026-09-14)
+### Immediate keyboard ownership during navigation
+
+Ten current-main regressions reproduced physical keys reaching the previous
+agent after pane/tab navigation, or being dropped after closing a pane/tab.
+Committed text followed the stale input connection too. Creating a blank tab
+also left the previous agent able to receive input before the next frame.
+The before-fix run uses online synthetic machines and both the keyboard and
+actual incoming native command handler:
+`/private/tmp/harness-navigation-input-before.log`.
+
+The canvas now enables the destination's retained focus tree and requests its
+existing input view immediately when the model changes. Blank, unmounted or
+not-yet-ready input views release the previous terminal to the workspace scope.
+No event replay, forced frame, new session or renderer reconstruction is introduced.
+Zoomed panes, retained Find/composer drafts, selection and composition follow
+the same ownership transition. Existing heartbeats and dial scrolling still
+cause zero workspace builds or irrelevant terminal JSON dispatches. Two additional
+cases caught a still-connecting composer leaving the old input owner active;
+it now releases that owner and takes focus only once ready. Reproduction:
+`/private/tmp/harness-navigation-pending-before.log`.
+
+Dialog coverage also reproduced delayed terminal/composer focus taking over
+Rename while a destination changed or an agent became ready. The canvas is now
+excluded from focus while a dialog owns input and explicitly returns it to the
+current destination on dismissal. Deferred viewport/composer callbacks respect
+that boundary. The composer-readiness reproduction is in
+`/private/tmp/harness-navigation-composer-before.log`.
+
+The 18 transition cases cover keyboard/native entry, zoom, waiting input,
+editor drafts/composition, background changes and immediate dialog return.
+All **1,461 desktop checks** pass, with one optional CLI-media placeholder
+skipped, in `/private/tmp/harness-navigation-input-full.log`.
+Six changed source/test files analyze cleanly in
+`/private/tmp/harness-navigation-input-analyze.log`.
+These are input-routing, retention and deterministic-work checks; they do not
+measure native event-to-display latency or qualify live native IME behavior.
+
### Find takes input before its first frame
The first-frame opening checks reproduced text and Escape reaching the agent