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.

fix(mobile): smoother terminal, working Backspace, resilient reconnects

Dev jacob6e088bfad908
diff --git a/mobile/lib/core/last_opened_agent.dart b/mobile/lib/core/last_opened_agent.dart
index df45f838d..c5c4951b1 100644
--- a/mobile/lib/core/last_opened_agent.dart
+++ b/mobile/lib/core/last_opened_agent.dart
@@ -2,6 +2,8 @@ import 'dart:convert';
import 'local_key_value_store.dart';
+/// One agent, named by the machine it runs on — what a relaunch reopens, a pager page shows, and
+/// every pane it opens is about.
typedef AgentRef = ({String machineId, String agentId});
/// The agent the phone had on screen, so a relaunch can put the person back on it.
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dart
index 11ec08d08..a0bef83f5 100644
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@ -10,6 +10,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
import 'agent_swipe.dart';
+import 'agent_swipe_list.dart';
import 'agents_page.dart' show openNewAgent;
import 'machines_tab.dart';
import 'phone_fab.dart';
diff --git a/mobile/lib/phone/agent_neighbour_warmer.dart b/mobile/lib/phone/agent_neighbour_warmer.dart
index 9c3280b0a..8d87a4504 100644
--- a/mobile/lib/phone/agent_neighbour_warmer.dart
+++ b/mobile/lib/phone/agent_neighbour_warmer.dart
@@ -3,9 +3,7 @@ import 'dart:async';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
-import 'agent_swipe.dart';
-
-typedef AgentRef = ({String machineId, String agentId});
+import 'agent_swipe_list.dart';
/// Opens the agents one swipe either side of the one on screen, and closes the ones further out.
///
diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dart
index 2219d9f7e..8a3306a15 100644
--- a/mobile/lib/phone/agent_swipe.dart
+++ b/mobile/lib/phone/agent_swipe.dart
@@ -4,55 +4,11 @@ import 'package:flutter/material.dart';
import 'package:harness_mobile/state/app_state.dart';
-import 'agent_index.dart';
import 'agent_neighbour_warmer.dart';
+import 'agent_swipe_list.dart';
import 'terminal_page.dart';
import 'voice_input_controller.dart';
-/// The agents a terminal page can swipe between, in the order the list drew them.
-///
-/// A SNAPSHOT, taken when the page opens. The Agents tab sorts partly on state that moves by itself
-/// — an idle agent that starts working sorts upward — so a pager recomputing this list would
-/// renumber its own pages under the finger: the page to the right could become a different agent
-/// between one swipe and the next, for a reason nothing on screen explains.
-///
-/// Only entries that can actually be opened are kept. A row with no terminal does nothing when
-/// tapped in the list, and a page for it would be a screen of "Attaching…" that never resolves —
-/// worse mid-swipe than in a list, where at least the row is still readable.
-class AgentSwipeList {
- AgentSwipeList(List<AgentEntry> entries)
- : entries = [
- for (final entry in entries)
- if (entry.agent.terminalAvailable) entry,
- ];
-
- final List<AgentEntry> entries;
-
- bool get isEmpty => entries.isEmpty;
-
- /// Whether the pager wraps around — past the last agent is the first one again.
- ///
- /// Needs at least TWO agents, and that is not a formality. With one, every page of an endless
- /// pager is the same agent: the screen would take a swipe, move, and land on what it just left,
- /// which reads as the gesture having failed rather than as a list with one thing in it. One agent
- /// gets one page and no swipe at all.
- bool get wraps => entries.length > 1;
-
- /// Where an agent sits in the snapshot, or null if it is not in it.
- ///
- /// Used once, to find the page to open on: the tapped row may be a "Waiting for you" row, an
- /// agent with no terminal may have been dropped by the constructor above, and neither the list's
- /// index nor the row's position can be assumed to survive either.
- int? indexOf(String machineId, String agentId) {
- for (final (index, entry) in entries.indexed) {
- if (entry.machineId == machineId && entry.agent.id == agentId) {
- return index;
- }
- }
- return null;
- }
-}
-
/// One agent's terminal, with the agents beside it a swipe away.
///
/// ⚠️ **The pager holds the route, and [TerminalPage] no longer does.** The page draws one agent's
@@ -90,7 +46,7 @@ class AgentSwipeHost extends StatefulWidget {
/// whenever the account's state moves, so a host still naming the agent this opened on would snap
/// the screen back to it mid-session. Every pushed pager is popped rather than rebuilt around a
/// different agent, and passes null.
- final ValueChanged<({String machineId, String agentId})>? onAgentChanged;
+ final ValueChanged<AgentRef>? onAgentChanged;
@override
State<AgentSwipeHost> createState() => _AgentSwipeHostState();
@@ -117,7 +73,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
/// is on screen decides who may hold the keyboard, and which AGENT is on screen decides which pane
/// [_detachAll] spares on the way out. A page number cannot answer the second — the agent it names
/// has panes attached under other page numbers too.
- late ({String machineId, String agentId}) _current = (
+ late AgentRef _current = (
machineId: widget.machineId,
agentId: widget.agentId,
);
@@ -132,7 +88,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
/// Recorded rather than recomputed: by the time this page is disposed the list may have moved on,
/// and the panes to close are the ones actually opened, not the ones a fresh list would name.
/// [_warmer] adds to it and prunes it as the pager moves — see [AgentNeighbourWarmer].
- final Set<({String machineId, String agentId})> _attached = {};
+ final Set<AgentRef> _attached = {};
/// Opens the agents either side of the one on screen once it is live. Null for a pager with nothing
/// to swipe to.
@@ -248,8 +204,15 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
//
// [ScrollStartNotification] is the first frame of the finger's movement,
// which is the moment the person has shown they are leaving this terminal.
+ //
+ // ⚠️ **Depth 0 only — the pager's own drag.** The terminal inside each page
+ // is a vertical [Scrollable] whose notifications bubble through here too;
+ // taken for a swipe, reading back through the scrollback put the keyboard
+ // away, and with no keyboard up it left the next one raised ignored until it
+ // had come and gone once.
return NotificationListener<ScrollStartNotification>(
- onNotification: (_) {
+ onNotification: (notification) {
+ if (notification.depth != 0) return false;
dismissKeyboardForSwipe();
// Let it bubble: the pager's own scroll machinery is listening too.
return false;
diff --git a/mobile/lib/phone/agent_swipe_list.dart b/mobile/lib/phone/agent_swipe_list.dart
new file mode 100644
index 000000000..85d212300
--- /dev/null
+++ b/mobile/lib/phone/agent_swipe_list.dart
@@ -0,0 +1,47 @@
+import 'agent_index.dart';
+
+export 'package:harness_mobile/core/last_opened_agent.dart' show AgentRef;
+
+/// The agents a terminal page can swipe between, in the order the list drew them.
+///
+/// A SNAPSHOT, taken when the page opens. The Agents tab sorts partly on state that moves by itself
+/// — an idle agent that starts working sorts upward — so a pager recomputing this list would
+/// renumber its own pages under the finger: the page to the right could become a different agent
+/// between one swipe and the next, for a reason nothing on screen explains.
+///
+/// Only entries that can actually be opened are kept. A row with no terminal does nothing when
+/// tapped in the list, and a page for it would be a screen of "Attaching…" that never resolves —
+/// worse mid-swipe than in a list, where at least the row is still readable.
+class AgentSwipeList {
+ AgentSwipeList(List<AgentEntry> entries)
+ : entries = [
+ for (final entry in entries)
+ if (entry.agent.terminalAvailable) entry,
+ ];
+
+ final List<AgentEntry> entries;
+
+ bool get isEmpty => entries.isEmpty;
+
+ /// Whether the pager wraps around — past the last agent is the first one again.
+ ///
+ /// Needs at least TWO agents, and that is not a formality. With one, every page of an endless
+ /// pager is the same agent: the screen would take a swipe, move, and land on what it just left,
+ /// which reads as the gesture having failed rather than as a list with one thing in it. One agent
+ /// gets one page and no swipe at all.
+ bool get wraps => entries.length > 1;
+
+ /// Where an agent sits in the snapshot, or null if it is not in it.
+ ///
+ /// Used once, to find the page to open on: the tapped row may be a "Waiting for you" row, an
+ /// agent with no terminal may have been dropped by the constructor above, and neither the list's
+ /// index nor the row's position can be assumed to survive either.
+ int? indexOf(String machineId, String agentId) {
+ for (final (index, entry) in entries.indexed) {
+ if (entry.machineId == machineId && entry.agent.id == agentId) {
+ return index;
+ }
+ }
+ return null;
+ }
+}
diff --git a/mobile/lib/phone/phone_navigation.dart b/mobile/lib/phone/phone_navigation.dart
index 08708505f..d8e33e981 100644
--- a/mobile/lib/phone/phone_navigation.dart
+++ b/mobile/lib/phone/phone_navigation.dart
@@ -6,6 +6,7 @@ import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
import 'agent_swipe.dart';
+import 'agent_swipe_list.dart';
import 'agents_page.dart';
import 'link_page.dart';
import 'machine_swipe.dart';
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index af1031ab2..61868e3d8 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -65,9 +65,9 @@ class TerminalPage extends StatefulWidget {
/// two mounted pages both passing `focused: true` race for the software keyboard, and the winner
/// can be the page off-screen. What gets typed then reaches an agent nobody is looking at.
///
- /// It also drives the panel's `visible`, which is what releases focus and stops the renderer and
- /// the auto-resize for a page that has slid away — three terminals all resizing themselves to the
- /// layout would send SIGWINCH to three remote shells at once.
+ /// It also drives the panel's `visible`, which is what releases focus and stops the auto-resize for
+ /// a page that has slid away — three terminals all resizing themselves to the layout would send
+ /// SIGWINCH to three remote shells at once.
final bool isActive;
@override
@@ -124,9 +124,13 @@ void resetKeyboardSession() {
/// its own: the inset is still falling, and the metrics ticks of that fall put
/// it back. [_keyboardDismissing] is what makes the clear stick until the
/// platform agrees.
+///
+/// ⚠️ Held off only when a keyboard is actually up. With none, no inset ever
+/// falls to zero to end the hold-off, and it would swallow the rise of the next
+/// keyboard summoned — which the page would then not know it owns.
void dismissKeyboardForSwipe() {
+ _keyboardDismissing = _keyboardDismissing || _keyboardIsUp;
_keyboardIsUp = false;
- _keyboardDismissing = true;
FocusManager.instance.primaryFocus?.unfocus();
}
@@ -164,8 +168,8 @@ class _TerminalPageState extends State<TerminalPage>
bool _keyboardUp = false;
/// Whether the keyboard is mid-animation, and so the pane's height is still
- /// changing frame by frame. Handed to [TerminalPanel.settling], which freezes
- /// the renderer and the auto-resize until this clears.
+ /// changing frame by frame. Handed to [TerminalPanel.settling], which holds
+ /// the remote resize until this clears.
bool _keyboardSettling = false;
/// Whether a hold in progress on the mic has been dragged off it, so letting
@@ -221,17 +225,19 @@ class _TerminalPageState extends State<TerminalPage>
/// only a stream of [didChangeMetrics] ticks — so the end is detected by the
/// inset going quiet. The window is a little longer than one frame at 60Hz so
/// a slow frame mid-animation does not read as the end of it.
- double? _lastInset;
+ ///
+ /// Starts at zero: see [didChangeMetrics] for why an unknown inset is taken
+ /// for a keyboard that is down.
+ double _lastInset = 0;
Timer? _settleTimer;
static const _settleWindow = Duration(milliseconds: 80);
- /// Stops the settle watch, leaving the renderer live.
+ /// Stops the settle watch, leaving the remote resize live.
///
/// ⚠️ Called from [dispose], so it must not touch [setState].
void _cancelSettle() {
_settleTimer?.cancel();
_settleTimer = null;
- _lastInset = null;
}
@override
@@ -240,11 +246,10 @@ class _TerminalPageState extends State<TerminalPage>
WidgetsBinding.instance.addObserver(this);
}
- /// Releases the freeze when this page is parked mid-animation.
+ /// Releases the resize hold when this page is parked mid-animation.
///
- /// A settle that never ends would otherwise be waiting on [didChangeMetrics]
- /// ticks that only the page ON SCREEN gets, and the pane would come back from
- /// the pager with its renderer still gated.
+ /// A settle left running would end on a page that is no longer on screen, and
+ /// the pane would come back from the pager still holding its resize.
@override
void didUpdateWidget(TerminalPage oldWidget) {
super.didUpdateWidget(oldWidget);
@@ -445,12 +450,15 @@ class _TerminalPageState extends State<TerminalPage>
// so the ticks this page gets for everything else — a rotation, a status
// bar resizing — never freeze a pane whose height is not moving.
//
- // The very first tick is deliberately not a move: `_lastInset` starts null
- // and only seeds the baseline, so arriving on this page cannot begin a
- // settle of its own.
+ // ⚠️ The baseline starts at zero, a keyboard that is DOWN. The first tick a
+ // page ever sees is almost always the keyboard's first frame on its way up,
+ // and taking that tick as a mere baseline let the pane resize the remote
+ // shell at the half-risen height before the settle began — two SIGWINCHes
+ // and two redraws for one keyboard. A page arriving under a keyboard already
+ // up costs one needless 80ms hold, and nothing else.
final previous = _lastInset;
_lastInset = inset;
- if (previous != null && inset != previous) {
+ if (inset != previous) {
_settleTimer?.cancel();
_settleTimer = Timer(_settleWindow, () {
_settleTimer = null;
@@ -699,7 +707,13 @@ class _TerminalPageState extends State<TerminalPage>
// moves this pane's height: the header slides
// OVER the terminal rather than out of its
// column — see [_SlideAway].
- settling: _keyboardSettling,
+ //
+ // ⚠️ Held for as long as search is open, too:
+ // its keyboard is typing a query over a faded
+ // terminal, and resizing the agent's shell for
+ // it redrew the whole TUI on the way in and
+ // again on the way out.
+ settling: _keyboardSettling || _searching,
// ⚠️ The tap is taken in the panel, not by a
// `Listener` over it. xterm's own `_onTapDown`
// calls `requestKeyboard()`, so anything that
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 8bbf45721..fda425fb7 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -8,6 +8,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../analytics/analytics.dart';
import '../api/api_client.dart';
+import '../viewer/direct_auth_api.dart';
import '../viewer/sign_in_browser.dart';
import '../viewer/viewer_services.dart';
import '../auth/auth_session.dart';
@@ -1369,7 +1370,12 @@ class AppNotifier extends ChangeNotifier {
/// Publish the selected pane to the existing local CLI connection. The CLI
/// shares this focus with paired devices and the dial; terminal attachments
/// and operating-system window activation do not define the selected agent.
+ ///
+ /// ⚠️ **Never from a viewer.** Only the CLI's loopback server reads these (`localWsServer.ts`); a
+ /// viewer's socket is the relay, where nothing does — and the type is not in `encryptedDownTypes`,
+ /// so every swipe sent the agent id past the backend in the clear for no one to read.
void _announceAppFocus() {
+ if (viewer != null) return;
final pane = focusedPane;
final machineId = pane?.agentId == null ? null : pane?.machineId;
final previousMachineId = _announcedFocusMachineId;
@@ -1408,9 +1414,11 @@ class AppNotifier extends ChangeNotifier {
/// The dial belongs to whichever daemon owns the cable, and only a complete
/// roster lets that one judge; the others store a list they never use, which
/// costs nothing and saves the window from having to know which is which.
+ ///
+ /// Never from a viewer, for [_announceAppFocus]'s reasons — and these carry swarm names too.
void _announceOpenPanesToDial() {
final pool = _pool;
- if (pool == null) return;
+ if (pool == null || viewer != null) return;
final agentIds = <String>[for (final pane in panes) ?pane.agentId];
// The swarms travel with the tiles: the dial names the one on screen above the agent and offers
// the others, and a pick there comes back as `dial_swarm`. Names and member ids only — the layout
@@ -2531,7 +2539,9 @@ class AppNotifier extends ChangeNotifier {
'This machine is no longer linked. Link it again to reconnect.',
);
notifyListeners();
- _startLinkRetry(machineId);
+ // ⚠️ Not a viewer's. Its links change only through its own password form, which reconnects
+ // when it lands — polling cannot fix what only that form can, and each round redrew the app.
+ if (viewer == null) _startLinkRetry(machineId);
}
void _ensurePool() {
@@ -2545,7 +2555,14 @@ class AppNotifier extends ChangeNotifier {
accessTokenProvider: (force, failedToken) async {
final directAuth = viewer?.auth;
if (directAuth != null) {
- return directAuth.accessToken(force: force, failedToken: failedToken);
+ // Only a session that is gone for good may sign the person out — see
+ // [WsCredentialRevoked]. An outage fails the refresh too, and is retried.
+ return directAuth
+ .accessToken(force: force, failedToken: failedToken)
+ .onError<DirectAuthException>(
+ (error, _) => throw WsCredentialRevoked(error.message),
+ test: (error) => error.signedOut,
+ );
}
final fixture = localManualFixture;
if (fixture != null) return fixture.apiKey;
@@ -5667,6 +5684,11 @@ class AppNotifier extends ChangeNotifier {
}
}
break;
+ // ⚠️ Everything else changed nothing here, so it must not redraw. The machine streams every
+ // agent's live chat — `text_delta`, `tool_start`, … — down this socket, several per second
+ // per agent, and each one used to rebuild every screen listening to this notifier.
+ default:
+ return;
}
notifyListeners();
}
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 2b276e911..5503e65f9 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -7,6 +7,7 @@ import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../clipboard/native_clipboard.dart';
+import '../core/host_platform.dart';
import '../state/app_state.dart';
import 'agent_drag.dart';
@@ -1395,6 +1396,14 @@ class _TerminalPanelState extends State<TerminalPanel>
focusNode: _focusNode,
autofocus: widget.focused && !showComposer,
readOnly: widget.readOnly || !session.acceptsInput,
+ // iOS answers Backspace over an empty native buffer
+ // with nothing at all (`deleteBackward` in
+ // FlutterTextInputPlugin.mm), so a line the keyboard
+ // did not type — a voice transcript, a recalled
+ // command — could not be rubbed out. xterm keeps a
+ // padding for Backspace to eat instead — see
+ // test/terminal_ime_input_test.dart.
+ deleteDetection: isMobileHost,
theme: terminalThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 6a5e2cc21..34b9e5623 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -16,6 +16,21 @@ typedef AccessTokenProvider = Future<String> Function(
String? failedToken,
);
+/// Thrown by an [AccessTokenProvider] when the session is gone for good — the refresh token was
+/// refused, or there never was one. Only this signs the person out.
+///
+/// ⚠️ Anything else a provider throws is taken for a blip and retried. A refresh that never reached
+/// the server says nothing about the session, and a sign-out cannot be undone by the network
+/// coming back.
+class WsCredentialRevoked implements Exception {
+ const WsCredentialRevoked(this.message);
+
+ final String message;
+
+ @override
+ String toString() => message;
+}
+
enum WsTransportKind { cloudE2ee, localPlaintext }
/// A `request()` call got no reply within its timeout — distinct from other request-level errors
@@ -114,6 +129,12 @@ class WsConn {
Timer? _reconnectTimer;
String? _tokenUsed;
bool _forceRelayReconnect = false;
+
+ /// How long a dial may take to open before it counts as failed. Without one, a socket dialled
+ /// into a network that swallows packets waits out the OS's own TCP timeout — over a minute on
+ /// iOS — with the machine showing "reconnecting" the whole time.
+ static const _dialTimeout = Duration(seconds: 15);
+
final _pending = <String, _PendingRpc>{};
final _readinessWaiters = <Completer<void>>{};
final _queue = <Map<String, dynamic>>[];
@@ -178,6 +199,7 @@ class WsConn {
if (_closing || _connecting) return;
_connecting = true;
_ready = false;
+ WebSocketChannel? dialing;
onStatus(
_attempt == 0
? ConnectionStatus.connecting
@@ -221,11 +243,11 @@ class WsConn {
},
);
}
- final channel = isLocal
+ final channel = dialing = isLocal
? WebSocketChannel.connect(uri)
: WebSocketChannel.connect(uri, protocols: [token!]);
_channel = channel;
- await channel.ready;
+ await channel.ready.timeout(_dialTimeout);
if (_closing || !identical(_channel, channel)) {
await channel.sink.close();
return;
@@ -245,13 +267,36 @@ class WsConn {
if (isLocal && forceRelayReconnect) 'forceReconnect': true,
},
});
+ } on WsCredentialRevoked catch (error) {
+ _signOut(error.message);
} catch (_) {
+ _abandonDial(dialing);
if (!_closing) _scheduleReconnect();
} finally {
_connecting = false;
}
}
+ /// Lets go of a channel whose dial failed.
+ ///
+ /// ⚠️ Left in place, it reads as a live socket: [reconnectNow] skips a connection that has one,
+ /// so the app coming back to the foreground would wait out the whole backoff — up to 30s — rather
+ /// than dial.
+ void _abandonDial(WebSocketChannel? channel) {
+ if (channel == null || !identical(_channel, channel)) return;
+ _channel = null;
+ final sub = _sub;
+ _sub = null;
+ unawaited(sub?.cancel());
+ unawaited(channel.sink.close().catchError((Object _) {}));
+ }
+
+ void _signOut(String message) {
+ _closing = true;
+ onStatus(ConnectionStatus.disconnected);
+ onAuthFailure(message);
+ }
+
void _onRaw(dynamic raw) {
final codec = _codec;
if (raw is List<int>) {
@@ -410,7 +455,7 @@ class WsConn {
return;
}
final eventType = message['type'];
- if (eventType is String && _worthLogging(eventType)) {
+ if (eventType is String && worthLogging(eventType)) {
appLog.debug('ws', '↓ $eventType ${summariseForLog(payload)}');
}
await onEvent({...message, 'payload': payload});
@@ -440,9 +485,26 @@ class WsConn {
'dial_focus',
'ping',
'pong',
+ // Every agent's live chat, pushed to every client selecting the machine
+ // (`SessionEvent`/`LiveEvent` in cli/src/lib/normalize.ts). It is what the
+ // person typed and what the agent answered — prompts, tool input and
+ // output, even pasted images — and it streams several frames a second per
+ // agent, each one a synchronous flushed write on the UI thread.
+ 'user_message',
+ 'thinking_delta',
+ 'thinking_title',
+ 'text_delta',
+ 'tool_start',
+ 'tool_end',
+ 'context_compact',
+ 'done',
+ 'turn_started',
+ 'turn_heartbeat',
+ 'subagent_finished',
};
- static bool _worthLogging(String type) => !_unlogged.contains(type);
+ @visibleForTesting
+ static bool worthLogging(String type) => !_unlogged.contains(type);
Future<Map<String, dynamic>> request(
String type, {
@@ -462,7 +524,7 @@ class WsConn {
}
});
_pending[requestId] = _PendingRpc(completer, timer);
- if (_worthLogging(type)) {
+ if (worthLogging(type)) {
appLog.debug('ws', '→ $type ${summariseForLog(payload)}');
// A second listener on the same future purely to record how it ended. It
// handles its own error, so the caller's handling is unchanged and nothing
@@ -695,9 +757,7 @@ class WsConn {
return;
}
if (code == 4403) {
- _closing = true;
- onStatus(ConnectionStatus.disconnected);
- onAuthFailure('SSO environment does not match this backend');
+ _signOut('SSO environment does not match this backend');
return;
}
_scheduleReconnect();
@@ -707,12 +767,15 @@ class WsConn {
onStatus(ConnectionStatus.reconnecting);
try {
await accessTokenProvider(true, _tokenUsed);
- if (!_closing) await connect();
+ } on WsCredentialRevoked {
+ _signOut('Your SSO session expired. Please sign in again.');
+ return;
} catch (_) {
- _closing = true;
- onStatus(ConnectionStatus.disconnected);
- onAuthFailure('Your SSO session expired. Please sign in again.');
+ // The token is still stale, so the next dial refreshes again on its own.
+ _scheduleReconnect();
+ return;
}
+ if (!_closing) await connect();
}
void _scheduleReconnect() {
diff --git a/mobile/test/agent_pager_fixture.dart b/mobile/test/agent_pager_fixture.dart
new file mode 100644
index 000000000..d3a7d5a92
--- /dev/null
+++ b/mobile/test/agent_pager_fixture.dart
@@ -0,0 +1,129 @@
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/agent_index.dart';
+import 'package:harness_mobile/phone/agent_swipe_list.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+import 'package:harness_mobile/viewer/viewer_key_store.dart';
+import 'package:harness_mobile/viewer/viewer_services.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+import 'voice_fakes.dart';
+
+/// A machine that accepts every terminal frame and remembers what it was sent.
+class PagerConn extends WsConn {
+ PagerConn()
+ : super(
+ wsBaseUrl: 'ws://fixture.invalid',
+ autonomousEnv: 'test',
+ machineId: 'm',
+ accessTokenProvider: (_, _) async => '',
+ onAuthFailure: (_) {},
+ onEvent: (_) {},
+ onStatus: (_) {},
+ );
+
+ final List<(String, Map<String, dynamic>)> frames = [];
+
+ List<Map<String, dynamic>> get opens => [
+ for (final (type, payload) in frames)
+ if (type == 'terminal_open') payload,
+ ];
+
+ @override
+ Future<bool> sendTerminalFrame(
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ frames.add((type, payload));
+ return true;
+ }
+
+ @override
+ Future<Map<String, dynamic>> request(
+ String type, {
+ Map<String, dynamic> payload = const {},
+ Duration timeout = const Duration(seconds: 20),
+ }) async => {};
+}
+
+const pagerAgentIds = ['a', 'b', 'c', 'd'];
+
+/// One machine `m` running [pagerAgentIds], reached through [conn] — as a phone reaches it when
+/// [viewer], with no CLI and nothing written to disk.
+AppNotifier pagerApp(
+ PagerConn conn, {
+ bool online = true,
+ bool viewer = false,
+}) {
+ final session = AuthSession();
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: session,
+ configStore: null,
+ connectionForTest: (_) => conn,
+ viewer: viewer
+ ? ViewerServices(
+ config: AppConfig.dev,
+ session: session,
+ keys: ViewerKeyStore(storage: MemoryKeyValueStore()),
+ )
+ : null,
+ );
+ const machine = Machine(
+ machineId: 'm',
+ authMode: MachineAuthMode.remote,
+ name: 'Test host',
+ );
+ app.machines = [machine];
+ app.machineStates['m'] = MachineState(machine)
+ ..nodeOnline = online
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..terminalCapabilityAvailable = true
+ ..activeAgentId = 'a'
+ ..agents = [
+ for (final id in pagerAgentIds)
+ Agent(
+ id: id,
+ name: id,
+ engine: 'claude',
+ project: const AgentProject(name: 'work', cwd: '/work'),
+ terminalAvailable: true,
+ ),
+ ];
+ return app;
+}
+
+/// Every agent on `m`, in order, as the pager swipes through them.
+AgentSwipeList pagerList(AppNotifier app) => AgentSwipeList([
+ for (final agent in app.stateOf('m')!.agents)
+ AgentEntry(machine: app.stateOf('m')!, agent: agent),
+]);
+
+/// The agent on screen, live at a phone's size.
+TerminalSession liveAgent(AppNotifier app, String agentId) {
+ final session = TerminalSession(
+ machineId: 'm',
+ agentId: agentId,
+ agentName: agentId,
+ engineId: 'claude',
+ send: (_, _) async => true,
+ sendBinary: (_) async => true,
+ );
+ app.adoptSessionForTest(session);
+ goLive(session);
+ return session;
+}
+
+/// What a keyframe arriving does to a session, without a machine to send one: controlling, at the
+/// phone's size, and the notifier told — which is the signal the pager waits on.
+void goLive(TerminalSession session) {
+ session
+ ..status = TerminalSessionStatus.controlling
+ ..streamId = 'stream-${session.agentId}'
+ ..cols = 46
+ ..rows = 38
+ ..renameAgent('${session.agentName} (live)');
+}
diff --git a/mobile/test/agent_preattach_test.dart b/mobile/test/agent_preattach_test.dart
index 574c4216f..ea4fbc1ca 100644
--- a/mobile/test/agent_preattach_test.dart
+++ b/mobile/test/agent_preattach_test.dart
@@ -1,119 +1,18 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
-import 'package:harness_mobile/auth/auth_session.dart';
-import 'package:harness_mobile/core/config.dart';
-import 'package:harness_mobile/core/models.dart';
-import 'package:harness_mobile/phone/agent_index.dart';
import 'package:harness_mobile/phone/agent_neighbour_warmer.dart';
import 'package:harness_mobile/phone/agent_swipe.dart';
import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/terminal/terminal_session.dart';
-import 'package:harness_mobile/ws/ws_conn.dart';
-
-/// A machine that accepts every terminal frame and remembers what it was sent.
-class _Conn extends WsConn {
- _Conn()
- : super(
- wsBaseUrl: 'ws://fixture.invalid',
- autonomousEnv: 'test',
- machineId: 'm',
- accessTokenProvider: (_, _) async => '',
- onAuthFailure: (_) {},
- onEvent: (_) {},
- onStatus: (_) {},
- );
-
- final List<(String, Map<String, dynamic>)> frames = [];
-
- List<Map<String, dynamic>> get opens => [
- for (final (type, payload) in frames)
- if (type == 'terminal_open') payload,
- ];
-
- @override
- Future<bool> sendTerminalFrame(
- String type,
- Map<String, dynamic> payload,
- ) async {
- frames.add((type, payload));
- return true;
- }
-
- @override
- Future<Map<String, dynamic>> request(
- String type, {
- Map<String, dynamic> payload = const {},
- Duration timeout = const Duration(seconds: 20),
- }) async => {};
-}
-const _agentIds = ['a', 'b', 'c', 'd'];
-
-AppNotifier _app(_Conn conn, {bool online = true}) {
- final app = AppNotifier(
- config: AppConfig.dev,
- authSession: AuthSession(),
- configStore: null,
- connectionForTest: (_) => conn,
- );
- const machine = Machine(
- machineId: 'm',
- authMode: MachineAuthMode.remote,
- name: 'Test host',
- );
- app.machines = [machine];
- app.machineStates['m'] = MachineState(machine)
- ..nodeOnline = online
- ..connectionStatus = ConnectionStatus.connected
- ..agentLoadStatus = AgentLoadStatus.loaded
- ..terminalCapabilityAvailable = true
- ..activeAgentId = 'a'
- ..agents = [
- for (final id in _agentIds)
- Agent(
- id: id,
- name: id,
- engine: 'claude',
- project: const AgentProject(name: 'work', cwd: '/work'),
- terminalAvailable: true,
- ),
- ];
- return app;
-}
-
-/// The agent on screen, live at a phone's size.
-TerminalSession _live(AppNotifier app, String agentId) {
- final session = TerminalSession(
- machineId: 'm',
- agentId: agentId,
- agentName: agentId,
- engineId: 'claude',
- send: (_, _) async => true,
- sendBinary: (_) async => true,
- );
- app.adoptSessionForTest(session);
- _goLive(session);
- return session;
-}
-
-/// What a keyframe arriving does to a session, without a machine to send one: controlling, at the
-/// phone's size, and the notifier told — which is the signal the pager waits on.
-void _goLive(TerminalSession session) {
- session
- ..status = TerminalSessionStatus.controlling
- ..streamId = 'stream-${session.agentId}'
- ..cols = 46
- ..rows = 38
- ..renameAgent('${session.agentName} (live)');
-}
+import 'agent_pager_fixture.dart';
void main() {
group('preattachAgent', () {
test('opens the stream at the size given, and selects nothing', () async {
- final conn = _Conn();
- final app = _app(conn);
+ final conn = PagerConn();
+ final app = pagerApp(conn);
addTearDown(app.dispose);
- _live(app, 'a');
+ liveAgent(app, 'a');
final focused = app.focusedPaneId;
await app.preattachAgent('m', 'b', cols: 46, rows: 38);
@@ -131,8 +30,8 @@ void main() {
});
test('a pane already streaming is left alone', () async {
- final conn = _Conn();
- final app = _app(conn);
+ final conn = PagerConn();
+ final app = pagerApp(conn);
addTearDown(app.dispose);
await app.preattachAgent('m', 'b', cols: 46, rows: 38);
@@ -142,8 +41,8 @@ void main() {
});
test('an agent that cannot be attached gets no pane', () async {
- final conn = _Conn();
- final app = _app(conn, online: false);
+ final conn = PagerConn();
+ final app = pagerApp(conn, online: false);
addTearDown(app.dispose);
await app.preattachAgent('m', 'b', cols: 46, rows: 38);
@@ -154,15 +53,12 @@ void main() {
});
group('the pager', () {
- Future<(AppNotifier, _Conn)> pumpPager(WidgetTester tester) async {
- final conn = _Conn();
- final app = _app(conn);
+ Future<(AppNotifier, PagerConn)> pumpPager(WidgetTester tester) async {
+ final conn = PagerConn();
+ final app = pagerApp(conn);
addTearDown(app.dispose);
- final list = AgentSwipeList([
- for (final agent in app.stateOf('m')!.agents)
- AgentEntry(machine: app.stateOf('m')!, agent: agent),
- ]);
- _live(app, 'b');
+ final list = pagerList(app);
+ liveAgent(app, 'b');
await tester.pumpWidget(
MaterialApp(
home: AgentSwipeHost(
@@ -206,7 +102,7 @@ void main() {
await tester.fling(find.byType(PageView), const Offset(-400, 0), 1000);
await tester.pumpAndSettle();
// c was warmed; its keyframe lands.
- _goLive(app.paneOfAgent('m', 'c')!.session!);
+ goLive(app.paneOfAgent('m', 'c')!.session!);
await tester.pump(AgentNeighbourWarmer.delay);
await tester.pump();
diff --git a/mobile/test/agent_swipe_keyboard_test.dart b/mobile/test/agent_swipe_keyboard_test.dart
new file mode 100644
index 000000000..66ab502bd
--- /dev/null
+++ b/mobile/test/agent_swipe_keyboard_test.dart
@@ -0,0 +1,72 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/phone/agent_swipe.dart';
+import 'package:xterm/xterm.dart';
+
+import 'agent_pager_fixture.dart';
+
+/// The pager puts the keyboard away for a swipe between agents — and for nothing else.
+void main() {
+ bool terminalHasFocus(WidgetTester tester) =>
+ tester.binding.focusManager.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<TerminalView>() !=
+ null;
+
+ Future<void> pumpPager(WidgetTester tester) async {
+ final conn = PagerConn();
+ final app = pagerApp(conn);
+ addTearDown(app.dispose);
+ final session = liveAgent(app, 'b');
+ for (var line = 0; line < 400; line++) {
+ session.terminal.write('output line $line\r\n');
+ }
+ await tester.pumpWidget(
+ MaterialApp(
+ home: AgentSwipeHost(
+ notifier: app,
+ machineId: 'm',
+ agentId: 'b',
+ neighbours: pagerList(app),
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ /// The software keyboard sliding up, as the platform reports it.
+ Future<void> raiseKeyboard(WidgetTester tester) async {
+ tester.view.viewInsets = const FakeViewPadding(bottom: 900);
+ addTearDown(tester.view.resetViewInsets);
+ await tester.pump();
+ await tester.pump();
+ }
+
+ testWidgets('reading back through the scrollback leaves the keyboard up', (
+ tester,
+ ) async {
+ await pumpPager(tester);
+ await raiseKeyboard(tester);
+ expect(terminalHasFocus(tester), isTrue);
+
+ await tester.drag(find.byType(TerminalView), const Offset(0, 300));
+ await tester.pump(const Duration(milliseconds: 500));
+
+ expect(
+ terminalHasFocus(tester),
+ isTrue,
+ reason: 'the terminal\'s own scroll is not a swipe to another agent',
+ );
+ });
+
+ testWidgets('a swipe with no keyboard up does not swallow the next one', (
+ tester,
+ ) async {
+ await pumpPager(tester);
+
+ await tester.fling(find.byType(PageView), const Offset(-400, 0), 1000);
+ await tester.pumpAndSettle();
+ await raiseKeyboard(tester);
+
+ expect(terminalHasFocus(tester), isTrue);
+ });
+}
diff --git a/mobile/test/app_state_events_test.dart b/mobile/test/app_state_events_test.dart
new file mode 100644
index 000000000..4d7c722a4
--- /dev/null
+++ b/mobile/test/app_state_events_test.dart
@@ -0,0 +1,61 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'agent_pager_fixture.dart';
+
+/// What a machine's pushes do to the screens listening to the app.
+void main() {
+ test('live chat the app does not read redraws nothing', () async {
+ final app = pagerApp(PagerConn());
+ addTearDown(app.dispose);
+ var redraws = 0;
+ app.addListener(() => redraws++);
+
+ for (final type in ['text_delta', 'tool_start', 'tool_end']) {
+ await app.handleEventForTest('m', {
+ 'type': type,
+ 'agentId': 'a',
+ 'payload': {'content': 'streaming'},
+ });
+ }
+
+ expect(redraws, 0);
+ });
+
+ test('a push the app does read still redraws', () async {
+ final app = pagerApp(PagerConn());
+ addTearDown(app.dispose);
+ var redraws = 0;
+ app.addListener(() => redraws++);
+
+ await app.handleEventForTest('m', {
+ 'type': 'turn_ended',
+ 'agentId': 'a',
+ 'payload': <String, dynamic>{},
+ });
+
+ expect(redraws, 1);
+ });
+
+ test('a phone tells no machine which agent it is looking at', () async {
+ for (final viewer in [false, true]) {
+ final app = pagerApp(PagerConn(), viewer: viewer);
+ addTearDown(app.dispose);
+ final announced = <String?>[];
+ app.focusFrameSenderForTest = (_, agentId) async {
+ announced.add(agentId);
+ return true;
+ };
+ liveAgent(app, 'b');
+
+ app.focusPane(app.paneOfAgent('m', 'b')!.id);
+
+ expect(
+ announced,
+ viewer ? isEmpty : ['b'],
+ reason: viewer
+ ? 'only the CLI\'s loopback reads app_focus; the relay carries it in the clear'
+ : 'a desktop still drives the dial',
+ );
+ }
+ });
+}
diff --git a/mobile/test/terminal_ime_input_test.dart b/mobile/test/terminal_ime_input_test.dart
index 3af83c695..a4c67d56e 100644
--- a/mobile/test/terminal_ime_input_test.dart
+++ b/mobile/test/terminal_ime_input_test.dart
@@ -11,14 +11,22 @@ void main() {
Terminal newTerminal() =>
Terminal(maxLines: 200, reflowEnabled: false)..resize(80, 12);
- Future<void> pumpTerminal(WidgetTester tester, Terminal terminal) async {
+ Future<void> pumpTerminal(
+ WidgetTester tester,
+ Terminal terminal, {
+ bool deleteDetection = false,
+ }) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SizedBox(
width: 400,
height: 320,
- child: TerminalView(terminal, autofocus: true),
+ child: TerminalView(
+ terminal,
+ autofocus: true,
+ deleteDetection: deleteDetection,
+ ),
),
),
),
@@ -127,6 +135,74 @@ void main() {
variant: TargetPlatformVariant.only(TargetPlatform.iOS),
);
+ group('with delete detection, as a phone runs it', () {
+ /// What UIKit's `deleteBackward` does to the buffer it holds: one character
+ /// fewer, and NOTHING at all once the buffer is empty.
+ Future<void> deleteBackward(WidgetTester tester) async {
+ final text = tester.testTextInput.editingState!['text'] as String;
+ if (text.isEmpty) return;
+ final left = text.substring(0, text.length - 1);
+ tester.testTextInput.updateEditingValue(
+ TextEditingValue(
+ text: left,
+ selection: TextSelection.collapsed(offset: left.length),
+ ),
+ );
+ await tester.pump();
+ }
+
+ testWidgets('Backspace keeps rubbing out a line the keyboard never typed', (
+ tester,
+ ) async {
+ final terminal = newTerminal();
+ final outbound = <String>[];
+ terminal.onOutput = outbound.add;
+ await pumpTerminal(tester, terminal, deleteDetection: true);
+
+ // A voice transcript sits in the prompt; the native buffer knows
+ // nothing of it.
+ for (var press = 0; press < 5; press++) {
+ await deleteBackward(tester);
+ }
+
+ expect(outbound, List.filled(5, '\x7f'));
+ }, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
+
+ testWidgets(
+ 'Return submits once when iOS appends its newline to the padding',
+ (tester) async {
+ final terminal = newTerminal();
+ final outbound = <String>[];
+ terminal.onOutput = outbound.add;
+ await pumpTerminal(tester, terminal, deleteDetection: true);
+
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: ' hi',
+ selection: TextSelection.collapsed(offset: 4),
+ ),
+ );
+ await tester.pump();
+ outbound.clear();
+
+ await tester.testTextInput.receiveAction(TextInputAction.newline);
+ await tester.pump();
+ // The race's other winner: the reset landed first, so the newline
+ // arrives on the padding rather than on the line.
+ tester.testTextInput.updateEditingValue(
+ const TextEditingValue(
+ text: ' \n',
+ selection: TextSelection.collapsed(offset: 3),
+ ),
+ );
+ await tester.pump();
+
+ expect(outbound, ['\r']);
+ },
+ variant: TargetPlatformVariant.only(TargetPlatform.iOS),
+ );
+ });
+
testWidgets(
'Telex sends the composed word, not the letters it was typed from',
(tester) async {
diff --git a/mobile/test/terminal_page_header_fold_test.dart b/mobile/test/terminal_page_header_fold_test.dart
index bf37656ac..01e089167 100644
--- a/mobile/test/terminal_page_header_fold_test.dart
+++ b/mobile/test/terminal_page_header_fold_test.dart
@@ -96,4 +96,76 @@ void main() {
await tester.pump(const Duration(seconds: 1));
expect(resizes, isEmpty);
});
+
+ testWidgets('the keyboard search raises leaves the terminal its size', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ resizes.clear();
+
+ await tester.tap(find.text(TerminalHeader.searchHint));
+ await tester.pump();
+ // The search field's keyboard slides up, and the page shrinks above it.
+ tester.view.viewInsets = const FakeViewPadding(bottom: 900);
+ addTearDown(tester.view.resetViewInsets);
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 1));
+
+ // The terminal is faded behind the search screen: resizing the agent's shell
+ // for a keyboard that is typing a query redraws its whole TUI for nothing,
+ // and again when the search closes.
+ expect(resizes, isEmpty);
+ });
+
+ testWidgets('the first keyboard up resizes the terminal once, when it lands', (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ resizes.clear();
+
+ // The keyboard's slide, frame by frame — with REAL time between the frames,
+ // as a phone has: the session sends a resize straight away once the last
+ // one is 50ms of wall clock old, and fake time never gets it there.
+ for (final inset in const [300.0, 600.0, 900.0]) {
+ await tester.runAsync(
+ () => Future<void>.delayed(const Duration(milliseconds: 60)),
+ );
+ tester.view.viewInsets = FakeViewPadding(bottom: inset);
+ await tester.pump(const Duration(milliseconds: 16));
+ }
+ await tester.pump(const Duration(seconds: 1));
+
+ // One SIGWINCH at the final height — not a first one at whatever height the
+ // slide's opening frame happened to have.
+ expect(resizes, hasLength(1));
+
+ // Down again and settled inside the test, so no resize is left in flight
+ // when the view is reset for the next one.
+ tester.view.resetViewInsets();
+ await tester.pump();
+ await tester.pump(const Duration(seconds: 1));
+ // The settle's end lays the terminal out on the frame above; its resize
+ // coalesces for one more beat.
+ await tester.pump(const Duration(milliseconds: 100));
+ });
}
diff --git a/mobile/test/terminal_painter_test.dart b/mobile/test/terminal_painter_test.dart
new file mode 100644
index 000000000..91821f9d8
--- /dev/null
+++ b/mobile/test/terminal_painter_test.dart
@@ -0,0 +1,46 @@
+import 'dart:ui';
+
+import 'package:flutter/painting.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/xterm.dart';
+// The painter is xterm's own, vendored and patched here (third_party/xterm,
+// README.autonomous.md) — not API the package offers.
+// ignore: implementation_imports
+import 'package:xterm/src/ui/painter.dart';
+
+/// A canvas that counts the glyphs it is asked to draw.
+class _GlyphCounter implements Canvas {
+ int glyphs = 0;
+
+ @override
+ void drawParagraph(Paragraph paragraph, Offset offset) => glyphs++;
+
+ @override
+ void drawRect(Rect rect, Paint paint) {}
+
+ @override
+ dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
+}
+
+/// Every frame paints every cell on screen, so what a cell costs is paid ~2,000
+/// times a frame on a phone.
+void main() {
+ int glyphsDrawnFor(String output) {
+ final terminal = Terminal()..write(output);
+ final canvas = _GlyphCounter();
+ TerminalPainter(
+ theme: TerminalThemes.defaultTheme,
+ textStyle: const TerminalStyle(),
+ textScaler: TextScaler.noScaling,
+ ).paintLine(canvas, Offset.zero, terminal.buffer.lines[0]);
+ return canvas.glyphs;
+ }
+
+ test('a space costs no glyph', () {
+ expect(glyphsDrawnFor('a b '), 2);
+ });
+
+ test('an underlined space still draws its underline', () {
+ expect(glyphsDrawnFor('\x1b[4m \x1b[0m'), 1);
+ });
+}
diff --git a/mobile/test/ws_log_filter_test.dart b/mobile/test/ws_log_filter_test.dart
new file mode 100644
index 000000000..7529558d3
--- /dev/null
+++ b/mobile/test/ws_log_filter_test.dart
@@ -0,0 +1,32 @@
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/ws/ws_conn.dart';
+
+/// What the socket writes to the app's log file — every line a synchronous,
+/// flushed write on the UI thread.
+void main() {
+ test('an agent\'s live chat never reaches the log', () {
+ // `SessionEvent`/`LiveEvent` in cli/src/lib/normalize.ts: the words typed
+ // and answered, streamed several frames a second.
+ for (final type in const [
+ 'user_message',
+ 'thinking_delta',
+ 'thinking_title',
+ 'text_delta',
+ 'tool_start',
+ 'tool_end',
+ 'context_compact',
+ 'done',
+ 'turn_started',
+ 'turn_heartbeat',
+ 'subagent_finished',
+ ]) {
+ expect(WsConn.worthLogging(type), isFalse, reason: type);
+ }
+ });
+
+ test('the frames a log is read for still are', () {
+ for (final type in const ['node_status', 'agent_created', 'turn_ended']) {
+ expect(WsConn.worthLogging(type), isTrue, reason: type);
+ }
+ });
+}
diff --git a/mobile/test/ws_resume_test.dart b/mobile/test/ws_resume_test.dart
index 3bca60414..cccc70f7f 100644
--- a/mobile/test/ws_resume_test.dart
+++ b/mobile/test/ws_resume_test.dart
@@ -16,13 +16,19 @@ class _Hub {
final List<WebSocket> live = [];
int opened = 0;
+ /// Answers every dial with a 404 rather than an upgrade — a dial that fails.
+ bool refuse = false;
+
+ /// Closes the next socket opened with this code the moment it opens.
+ int? closeNextWith;
+
int get port => server.port;
static Future<_Hub> start() async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
final hub = _Hub._(server);
server.listen((request) async {
- if (!WebSocketTransformer.isUpgradeRequest(request)) {
+ if (hub.refuse || !WebSocketTransformer.isUpgradeRequest(request)) {
request.response.statusCode = 404;
await request.response.close();
return;
@@ -33,6 +39,12 @@ class _Hub {
protocols.isNotEmpty ? protocols.first : null,
);
hub.opened++;
+ final closeWith = hub.closeNextWith;
+ if (closeWith != null) {
+ hub.closeNextWith = null;
+ await ws.close(closeWith);
+ return;
+ }
hub.live.add(ws);
// Whatever the client says, this hub only counts connections.
ws.listen((_) {}, onDone: () => hub.live.remove(ws));
@@ -54,20 +66,22 @@ class _Hub {
void main() {
late _Hub hub;
final statuses = <ConnectionStatus>[];
+ final signOuts = <String>[];
setUp(() async {
hub = await _Hub.start();
statuses.clear();
+ signOuts.clear();
});
tearDown(() async => hub.stop());
- WsConn newConn() => WsConn(
+ WsConn newConn({AccessTokenProvider? tokens}) => WsConn(
wsBaseUrl: 'ws://127.0.0.1:${hub.port}',
autonomousEnv: 'test',
machineId: 'm',
- accessTokenProvider: (_, _) async => 'token',
- onAuthFailure: (_) {},
+ accessTokenProvider: tokens ?? (_, _) async => 'token',
+ onAuthFailure: signOuts.add,
onEvent: (_) {},
onStatus: statuses.add,
);
@@ -137,6 +151,50 @@ void main() {
},
);
+ test('a dial that failed does not hold up the next one', () async {
+ hub.refuse = true;
+ final conn = newConn();
+ addTearDown(conn.close);
+ await conn.connect();
+ hub.refuse = false;
+
+ // Back in front of somebody, on a network that works now.
+ conn.reconnectNow();
+
+ // Well inside the one-second backoff the failed dial armed.
+ expect(
+ await opensReach(1, within: const Duration(milliseconds: 350)),
+ isTrue,
+ );
+ });
+
+ test('a token refresh that cannot reach the server is retried', () async {
+ hub.closeNextWith = 4401;
+ final conn = newConn(
+ tokens: (force, _) async =>
+ force ? throw StateError('network unreachable') : 'token',
+ );
+ addTearDown(conn.close);
+ await conn.connect();
+
+ expect(await opensReach(2, within: const Duration(seconds: 3)), isTrue);
+ expect(signOuts, isEmpty, reason: 'an outage is not a dead session');
+ });
+
+ test('a session that is gone for good signs out', () async {
+ hub.closeNextWith = 4401;
+ final conn = newConn(
+ tokens: (force, _) async =>
+ force ? throw const WsCredentialRevoked('revoked') : 'token',
+ );
+ addTearDown(conn.close);
+ await conn.connect();
+ await Future<void>.delayed(const Duration(milliseconds: 300));
+
+ expect(signOuts, hasLength(1));
+ expect(conn.isClosed, isTrue);
+ });
+
test('a connection somebody closed stays closed', () async {
final conn = newConn();
await conn.connect();
diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.md
index f0fdd2c02..977881b9f 100644
--- a/mobile/third_party/xterm/README.autonomous.md
+++ b/mobile/third_party/xterm/README.autonomous.md
@@ -192,3 +192,23 @@ it if one is dropped.
gets the same single delete through the usual sync. An empty buffer still
sends it straight on; Ctrl/Alt/Meta+Backspace and desktop platforms are
untouched.
+
+13. **Delete detection survives a kept buffer**
+ (`lib/src/ui/custom_text_edit.dart`). iOS answers Backspace over an empty
+ native buffer with nothing at all (`deleteBackward` in
+ `FlutterTextInputPlugin.mm`), so the phone turns `deleteDetection` on and
+ Backspace eats a two-space padding instead. Upstream reset the buffer after
+ every edit, which refilled it; this copy keeps the buffer between keys for
+ Telex (note 12's neighbour), so two Backspaces into a line the keyboard
+ never typed — a voice transcript, a recalled command — spent the padding and
+ Backspace went dead. The buffer is now reset whenever the padding has been
+ eaten into, and the Return echo of note 11 also matches a newline appended
+ to the padding. Regression: `mobile/test/terminal_ime_input_test.dart`.
+
+14. **A plain space paints nothing** (`lib/src/ui/painter.dart`). Every frame
+ paints every cell on screen, one `drawParagraph` per cell, and a TUI's
+ screen is mostly spaces — padding, box interiors, the tail of every short
+ line. A space has no ink (its colour is the background pass's), so it now
+ returns before the hash, the cache lookup and the draw. An underlined
+ space still draws, through the existing U+00A0 substitution. Regression:
+ `mobile/test/terminal_painter_test.dart`.
diff --git a/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
index e0f7b329c..40b4419fe 100644
--- a/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
+++ b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
@@ -365,7 +365,11 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
if (submitted == null) return false;
// The newline either lands on the buffer the action was performed on, or
// after this side's reset has already emptied it — whichever wins the race.
- if (value.text != '$submitted\n' && value.text != '\n') return false;
+ // "Emptied" is the delete-detection padding when that is on.
+ if (value.text != '$submitted\n' &&
+ value.text != '${_initEditingState.text}\n') {
+ return false;
+ }
_connection?.setEditingState(_currentEditingState);
return true;
}
@@ -422,6 +426,13 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
widget.onInsert(edit.inserted);
}
_terminalText = value;
+ // ⚠️ The padding is spent one space per Backspace past the typed text, and
+ // the buffer is kept between keys (Telex needs it), so nothing else puts it
+ // back: two deletes into a line the keyboard never typed — a voice
+ // transcript, a recalled command — and Backspace goes dead again.
+ if (widget.deleteDetection && !value.startsWith(_initEditingState.text)) {
+ resetEditingState();
+ }
}
int _composingBacktrackCells(int composingStart) {
diff --git a/mobile/third_party/xterm/lib/src/ui/painter.dart b/mobile/third_party/xterm/lib/src/ui/painter.dart
index bc45fa21c..f93550569 100644
--- a/mobile/third_party/xterm/lib/src/ui/painter.dart
+++ b/mobile/third_party/xterm/lib/src/ui/painter.dart
@@ -184,6 +184,11 @@ class TerminalPainter {
void paintCellForeground(Canvas canvas, Offset offset, CellData cellData) {
final charCode = cellData.content & CellContent.codepointMask;
if (charCode == 0) return;
+ // A plain space has no ink — its colour is [paintCellBackground]'s — and a
+ // TUI's screen is mostly spaces: padding, box interiors, the tail of every
+ // short line. Each one was still a hash, a cache lookup and a
+ // `drawParagraph`, every frame. Only an underlined space draws (see below).
+ if (charCode == 0x20 && cellData.flags & CellFlags.underline == 0) return;
final cacheKey = cellData.getHash() ^ _textScaler.hashCode;
var paragraph = _paragraphCache.getLayoutFromCache(cacheKey);