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): faster terminal typing over P2P

tony2c9c8a8af3a0
diff --git a/mobile/lib/p2p/terminal_p2p_plugin.dart b/mobile/lib/p2p/terminal_p2p_plugin.dart
index 6c2de2da1..1237aa578 100644
--- a/mobile/lib/p2p/terminal_p2p_plugin.dart
+++ b/mobile/lib/p2p/terminal_p2p_plugin.dart
@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:typed_data';
import 'package:harness_mobile/logging/app_log.dart';
+import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/terminal/terminal_binary.dart';
import 'package:harness_mobile/ws/terminal_transport_plugin.dart';
@@ -141,9 +142,9 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
/// lived. Rare while an open waited for the channel; routine once it stopped waiting
/// ([prepareOpen]), because the launch's first open and the channel now come up side by side.
///
- /// After the first keyframe and not at `terminal_ready`: the migration's first phase is a resync
- /// whose ANSWERING keyframe is what [observeWsBinary] takes as "drained, flip now" — started
- /// before the open's own keyframe, that keyframe would be taken for the answer.
+ /// After the first keyframe and not at `terminal_ready`: the machine skips a resync that lands
+ /// while the open's own keyframe is still being taken, and the move is then confirmed only by the
+ /// stream's next frame — as late as its 5 s sync.
final _promoteAfterFirstFrame = <String>{};
/// streamId → when its migration to p2p started.
@@ -227,9 +228,19 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
bool _p2pEligible = false;
/// Whether the first negotiation has been started — by the first terminal to open
- /// ([prepareOpen]). Every later one is [_scheduleRetry]'s, budget and all.
+ /// ([prepareOpen]), or to come up ([_startForFirstTerminal]). Every later one is
+ /// [_scheduleRetry]'s, budget and all.
bool _p2pStarted = false;
+ /// Starts this connection's channel for its first terminal — see [onSessionReady]. Once only: a
+ /// channel that failed or was demoted since is [_scheduleRetry]'s to bring back.
+ void _startForFirstTerminal(String why) {
+ if (!_p2pEligible || _p2pStarted) return;
+ _p2pStarted = true;
+ _log('starting · $why');
+ _startP2p();
+ }
+
@override
void onSessionReady() {
if (_disposed) return;
@@ -487,16 +498,9 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
final firstKeyframe =
header.kind == TerminalBinaryKind.keyframe &&
_promoteAfterFirstFrame.remove(streamId);
- if (header.kind == TerminalBinaryKind.keyframe &&
- _migrating.containsKey(streamId) &&
- !_p2pStreams.contains(streamId)) {
- // Phase 1 of a live migration completing: the responder's reply to our WS-side
- // resync proves it has drained this stream as of now — safe to trigger phase 2.
- await _commitMigration(streamId);
- } else if (_p2pStreams.contains(streamId) &&
- !_migrating.containsKey(streamId)) {
- // Suppressed while migrating: during phase 2 the responder may still emit
- // relay-routed output until ITS flip lands, and that is not p2p breaking.
+ if (_p2pStreams.contains(streamId) && !_migrating.containsKey(streamId)) {
+ // Suppressed while migrating: the responder may still emit relay-routed output
+ // until ITS flip lands, and that is not p2p breaking.
// Nor after it, for what the relay was already carrying — see [_lateOnRelay].
if (_lateOnRelay(streamId, localFrame)) return;
await _demote('relay_binary_received');
@@ -507,6 +511,10 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
}
void _handleP2pData(Object data) {
+ // When the channel handed the frame over, against when its turn in the inbound line came — the
+ // two halves of a move that took ~1 s with the machine's keyframe sent 0.13 s after the channel
+ // opened (iPhone 14, 2026-10-19).
+ final arrivedMs = kTypingTrace ? typingNowMs() : 0;
host.enqueueInbound(() async {
if (_disposed) return;
if (data is String) {
@@ -519,6 +527,7 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
}
final type = wrapped['type'];
if (type is! String || !terminalP2pUpTypes.contains(type)) return;
+ if (kTypingTrace) _traceP2pIn(type, '', null, arrivedMs);
final clear = host.codec.decodeFrame(wrapped);
if (clear == null) return;
final plain = <String, dynamic>{
@@ -546,6 +555,14 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
return;
}
final streamId = header.streamId;
+ if (kTypingTrace) {
+ _traceP2pIn(
+ header.kind.name,
+ streamId,
+ peekTerminalLocalSeq(local),
+ arrivedMs,
+ );
+ }
// The first numbered frame the channel brings for this stream: the line below which a relay
// frame is a late one — see [_lateOnRelay].
if (!_p2pFloor.containsKey(streamId)) {
@@ -567,6 +584,23 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
});
}
+ /// One frame off the channel: how long it waited in the inbound line behind what came before it.
+ /// Every keyframe and every frame of a stream still moving is said; other frames only when they
+ /// waited, and only while somebody types.
+ void _traceP2pIn(String kind, String streamId, int? seq, int arrivedMs) {
+ final waited = typingNowMs() - arrivedMs;
+ final moving = streamId.isNotEmpty && _migrating.containsKey(streamId);
+ final line =
+ 'p2p in $kind${streamId.isEmpty ? '' : ' stream=${_short(streamId)}'}'
+ '${seq == null ? '' : ' seq=$seq'} arrived t=$arrivedMs, waited ${waited}ms in the inbound line'
+ '${moving ? ' (stream still moving)' : ''}';
+ if (moving || kind == 'keyframe') {
+ typingEvent(line);
+ } else if (waited >= 10) {
+ typingNote(line);
+ }
+ }
+
Future<void> _noteTerminalResponse(
Map<String, dynamic> plain,
_Wire wire,
@@ -589,6 +623,13 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
requestId.isNotEmpty &&
streamId.isNotEmpty) {
_streams.add(streamId);
+ // ⚠️ **The open that never asked (2026-10-19).** A terminal reopened as the socket comes back —
+ // a resume after a while in the background — is sent before the session is ready, and the
+ // socket skips [prepareOpen] for a frame that cannot go yet. Its channel then never started:
+ // a Galaxy S23 on 4G typed 26s over the relay (~160ms an echo) after a resume, until opening
+ // another agent's terminal started one. Started here instead, the stream rides the relay
+ // meanwhile and moves over once the channel is up, as any open made before it does.
+ _startForFirstTerminal('first terminal on this machine, opened before the session was up');
final openedOnChannel = _pendingOpens.remove(requestId);
if (openedOnChannel && wire == _Wire.p2p) {
_p2pStreams.add(streamId);
@@ -648,21 +689,15 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
/// 2500ms, the channel taking 1.7–2.8s to connect); without the wait, 3.5s.
///
/// What it costs instead: the first seconds of a stream ride the relay — a relay round trip per
- /// keystroke and relay bandwidth — and each such stream is moved over with two resyncs, which
- /// the terminal takes as two keyframes. Both are cheaper than a blank screen.
+ /// keystroke and relay bandwidth — and each such stream is moved over with a resync, which the
+ /// terminal takes as one more keyframe ([_promote]). Both are cheaper than a blank screen.
///
/// Nothing is reported to the backend for it (it used to send `open_wait_elapsed`): no wait ran
/// out, and the channel's own outcome is still reported when it lands or gives up.
@override
Future<bool> prepareOpen(String requestId) async {
if (_disposed) return false;
- // The connection's first terminal is what starts its channel — see [onSessionReady]. Once
- // only: a channel that failed or was demoted since is [_scheduleRetry]'s to bring back.
- if (_p2pEligible && !_p2pStarted) {
- _p2pStarted = true;
- _log('starting · first terminal on this machine');
- _startP2p();
- }
+ _startForFirstTerminal('first terminal on this machine');
final link = _link;
if (link == null || _policy == null || !link.isReady) return false;
_pendingOpens.add(requestId);
@@ -804,20 +839,30 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
_scheduleRetry();
}
- /// Migrate every stream already open on this connection onto p2p, in two phases
- /// that both reuse `terminal_resync`: (1) here, over the wire the stream is on now
- /// (the relay) — a drain barrier the responder answers with a fresh keyframe over
- /// that same path; (2) [_commitMigration], once that keyframe arrives, a second
- /// resync over p2p, which is what makes the responder flip its routing too.
+ /// Migrate every stream already open on this connection onto p2p — see [_promote].
void _promoteOpenStreams() {
for (final streamId in _streams) {
_promote(streamId);
}
}
- /// Phase 1 of moving one relay stream onto the channel: a resync over the socket, whose answering
- /// keyframe [observeWsBinary] then commits. A stream already on the channel, or already on its
- /// way, is left alone.
+ /// Moves one relay stream onto the channel: a `terminal_resync` over the channel itself, which
+ /// makes the responder route the stream's output there and answer with a keyframe on it. The
+ /// stream's own frames ride the channel from the moment it is sent ([sendJson]); the move is
+ /// confirmed by the first frame the channel brings for it ([_confirmMigration]). A stream already
+ /// on the channel, or already on its way, is left alone.
+ ///
+ /// ⚠️ **One resync, not two (2026-10-19).** A first resync went over the relay as a drain barrier,
+ /// and only its answering keyframe sent this one: every move cost a relay round trip (~0.4–0.7 s
+ /// of typing over the relay) and one more keyframe, which replaces the whole terminal — three
+ /// keyframes for each terminal opened while the channel came up (iPhone 14, 2026-10-19). Nothing
+ /// needs the barrier: a relay frame still on its way after the move is told apart by number
+ /// ([_lateOnRelay]), the machine orders the two wires' frames by their seal counters, and its input
+ /// queue puts a keystroke that took the faster wire back behind the one still on the relay. Both
+ /// came with this change's CLI (`fix/cli-terminal-input-latency`). A machine older than that has
+ /// neither, and is no worse off than with the barrier, which never covered that window either: a
+ /// relay frame sealed before the move and landing after it demotes the stream there, and a
+ /// keystroke that overtook one is refused once and realigned (`TERMINAL_INPUT_INVALID`).
///
/// Either way it no longer waits in [_promoteAfterFirstFrame]: that is a stream's one attempt,
/// and a stream walked here has had it — a migration that then goes unanswered is swept
@@ -829,11 +874,13 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
}
_migrating[streamId] = _now();
_log('migrate · start stream=${_short(streamId)}');
+ // A failure here abandons THIS stream's move only, never the channel: [sendJson] takes it off
+ // [_migrating] and the stream stays on the relay.
unawaited(
host.send({
'type': 'terminal_resync',
'payload': {'streamId': streamId},
- }),
+ }, force: TransportVia.plugin),
);
}
@@ -906,20 +953,6 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
static String _short(String streamId) =>
streamId.length > 8 ? streamId.substring(0, 8) : streamId;
- Future<void> _commitMigration(String streamId) async {
- final link = _link;
- if (link == null || !link.isReady) {
- _migrating.remove(streamId);
- return;
- }
- // [_migrating] is deliberately NOT cleared here — only once a p2p-delivered frame
- // for this stream actually arrives, the real proof the responder flipped.
- await host.send({
- 'type': 'terminal_resync',
- 'payload': {'streamId': streamId},
- }, force: TransportVia.plugin);
- }
-
void _sweepMigrations() {
if (_migrating.isEmpty) return;
final cutoff = _now().subtract(_migrationTtl);
diff --git a/mobile/lib/p2p/webrtc_terminal_p2p_link.dart b/mobile/lib/p2p/webrtc_terminal_p2p_link.dart
index 95420c5df..d4143e098 100644
--- a/mobile/lib/p2p/webrtc_terminal_p2p_link.dart
+++ b/mobile/lib/p2p/webrtc_terminal_p2p_link.dart
@@ -28,7 +28,14 @@ const _maxMessageSize = 512 * 1024;
/// (or relay) candidate is in, plus a moment for the other interfaces to report,
/// and at the cap regardless. Whatever gathers after that trickles.
const _gatherCap = Duration(seconds: 3);
-const _gatherSettleAfterReflexive = Duration(milliseconds: 500);
+
+/// ⚠️ **100 ms, down from 500 (2026-10-19).** The channel only comes up after the offer goes, and
+/// until then a terminal's keys ride the relay: on an iPhone 14 the offer left at +592 ms, 500 of them
+/// this wait, of a ~1.5 s setup. The wait buys nothing the connection needs — host candidates are in
+/// the SDP from the start, and every candidate found after the offer still reaches the responder,
+/// held until its answer and then trickled (`_lateCandidates`).
+@visibleForTesting
+const gatherSettleAfterReflexive = Duration(milliseconds: 100);
class WebRtcTerminalP2pLinkFactory implements TerminalP2pLinkFactory {
const WebRtcTerminalP2pLinkFactory();
@@ -187,7 +194,7 @@ class WebRtcTerminalP2pLink implements TerminalP2pLink {
final how = await Future.any<String>([
_gathered!.future.then((_) => 'gathered'),
_reflexive!.future
- .then((_) => Future<void>.delayed(_gatherSettleAfterReflexive))
+ .then((_) => Future<void>.delayed(gatherSettleAfterReflexive))
.then((_) => 'gathered-enough'),
]).timeout(_gatherCap, onTimeout: () => 'gather-capped');
if (_pc != pc || _finished) return;
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index ef434f7b4..962f6cfca 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -1075,9 +1075,22 @@ class TerminalSession extends ChangeNotifier {
_quietBeats = 0;
_lastHeardOnStream = DateTime.now();
final generation = _generation;
+ // How long the frame waited behind the ones before it to be drawn: a keyframe that reached this
+ // session 0.64 s late was drawn 0.37 s later still (iPhone 14, 2026-10-19).
+ final queuedMs = kTypingTrace ? typingNowMs() : 0;
_renderTail = _renderTail
.then((_) async {
if (!_isCurrent(generation) || frame.streamId != streamId) return;
+ if (kTypingTrace) {
+ final waited = typingNowMs() - queuedMs;
+ final line =
+ 'render ${frame.kind.name} seq=${frame.seq} waited ${waited}ms behind earlier frames';
+ if (frame.kind == TerminalBinaryKind.keyframe) {
+ typingEvent(line);
+ } else if (waited >= 10) {
+ typingNote(line);
+ }
+ }
final bytes = _decodeBinaryBytes(frame);
if (bytes == null) {
await _requestResync('TERMINAL_BINARY_DECODE_FAILED');
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 1e1b43b40..301f88d4d 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -9,6 +9,7 @@ import 'package:web_socket_channel/web_socket_channel.dart';
import '../logging/app_log.dart';
import '../logging/redact.dart';
import '../logging/startup_trace.dart';
+import '../logging/typing_trace.dart';
import '../core/models.dart';
import '../core/test_run.dart';
import 'relay_codec.dart';
@@ -507,6 +508,20 @@ class WsConn {
return decoded is Map<String, dynamic> ? decoded : null;
}
+ /// A relay frame's turn in the inbound line, against when the socket handed it over: said when it
+ /// waited (or [always]), and only while somebody types — the channel's frames share this line
+ /// (`TerminalTransportHost.enqueueInbound`), so a wait here is a wait for the terminal too.
+ static void _traceInbound(String what, int arrivedMs, {bool always = false}) {
+ final waited = typingNowMs() - arrivedMs;
+ final line =
+ 'ws in $what arrived t=$arrivedMs, waited ${waited}ms in the inbound line';
+ if (always) {
+ typingEvent(line);
+ } else if (waited >= 10) {
+ typingNote(line);
+ }
+ }
+
static String _typeOf(Map<String, dynamic> message) =>
message['type'] is String ? message['type'] as String : '?';
@@ -515,12 +530,16 @@ class WsConn {
void _onRaw(dynamic raw) {
final codec = _codec;
+ // When the socket handed the frame over, against when its turn in the inbound line came — see
+ // [_traceInbound].
+ final arrivedMs = kTypingTrace ? typingNowMs() : 0;
if (raw is List<int>) {
// The socket already hands over a Uint8List; copying it cost one allocation per chunk of
// terminal output, for nothing.
final bytes = raw is Uint8List ? raw : Uint8List.fromList(raw);
_inboundTail = _inboundTail
.then((_) async {
+ if (kTypingTrace) _traceInbound('binary', arrivedMs);
final local = codec == null ? bytes : codec.decodeBinary(bytes);
if (local == null) return;
// Every relay binary frame is sealed by the machine — see [lastHeardFromMachineAt].
@@ -542,8 +561,16 @@ class WsConn {
raw is String &&
raw.length >= _decodeOffThreadFrom &&
!kUnderTest) {
+ if (kTypingTrace) {
+ typingEvent(
+ 'ws in large frame ${(raw.length / 1024).round()}KB arrived t=$arrivedMs',
+ );
+ }
_inboundTail = _inboundTail
.then((_) async {
+ if (kTypingTrace) {
+ _traceInbound('large frame', arrivedMs, always: true);
+ }
final clock = Stopwatch()..start();
final message = await _decodeOffThread(raw);
if (message == null) return;
@@ -569,7 +596,10 @@ class WsConn {
}
if (codec != null) {
_inboundTail = _inboundTail
- .then((_) => _onRelayFrame(codec, message))
+ .then((_) {
+ if (kTypingTrace) _traceInbound(_typeOf(message), arrivedMs);
+ return _onRelayFrame(codec, message);
+ })
.catchError((_) {
// Keep the FIFO alive: a frame that will not open is dropped, never dispatched.
});
diff --git a/mobile/test/p2p/terminal_p2p_plugin_test.dart b/mobile/test/p2p/terminal_p2p_plugin_test.dart
index 47bb1a2e1..a0006ba42 100644
--- a/mobile/test/p2p/terminal_p2p_plugin_test.dart
+++ b/mobile/test/p2p/terminal_p2p_plugin_test.dart
@@ -43,6 +43,70 @@ void main() {
b.plugin.dispose();
});
+ test(
+ 'a terminal opened before the session was up starts it once it comes up, and moves onto it',
+ () {
+ fakeAsync((async) {
+ // A resume after a while in the background: the socket comes back and the terminal is
+ // reopened before the session is ready, so its open never asked (`prepareOpen`). A Galaxy
+ // S23 on 4G typed 26s over the relay like that (2026-10-19).
+ final b = bootPlugin(async: async, firstTerminal: false);
+ expect(b.links.created, isEmpty);
+ b.host.receiveWs(ready(streamA, 'r0'));
+ flush(async);
+ expect(b.links.created, hasLength(1));
+ expect(b.links.last.started, isTrue);
+ expect(b.host.dispatched.last, linkMode(streamA, 'relay'));
+ // Once only: the next terminal finds it started.
+ b.host.receiveWs(ready(streamB, 'r1'));
+ flush(async);
+ expect(b.links.created, hasLength(1));
+ // Up: the stream moves over with one resync over the channel, as any open made before
+ // the channel was does.
+ b.links.last.open();
+ flush(async);
+ expect(b.host.wsTypes, isNot(contains('terminal_resync')));
+ expect(
+ b.links.last.sent
+ .map((f) => jsonDecode(f as String)['type'])
+ .toList(),
+ ['terminal_resync', 'terminal_resync'],
+ );
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test('a terminal coming up never restarts a channel that gave up', () {
+ fakeAsync((async) {
+ // Bringing one back is the retry's, budget and all.
+ final b = bootPlugin(async: async);
+ b.links.last.failNegotiation('peer_failed');
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r0'));
+ flush(async);
+ expect(b.links.created, hasLength(1));
+ async.elapse(const Duration(seconds: 60));
+ expect(b.links.created, hasLength(2));
+ b.plugin.dispose();
+ });
+ });
+
+ test('a terminal coming up starts nothing where p2p is off', () {
+ fakeAsync((async) {
+ for (final b in [
+ bootPlugin(async: async, policy: null, firstTerminal: false),
+ bootPlugin(async: async, peerVersion: 0, firstTerminal: false),
+ ]) {
+ b.host.receiveWs(ready(streamA, 'r0'));
+ flush(async);
+ expect(b.links.created, isEmpty);
+ b.plugin.dispose();
+ }
+ });
+ });
+
test(
'signals go out sealed over the socket, answers reach the link',
() async {
@@ -330,7 +394,7 @@ void main() {
group('live migration', () {
test(
- 'a stream opened on the socket moves to the channel in two phases',
+ 'a stream opened on the socket moves to the channel with one resync, over the channel',
() {
fakeAsync((async) {
final b = bootPlugin(async: async);
@@ -344,30 +408,30 @@ void main() {
b.host.sends.clear();
b.host.wsFrames.clear();
- // Phase 1: the channel opens → a resync over the socket.
+ // The channel opens → ONE resync, over the channel itself. A first one over the
+ // socket cost a relay round trip and one more keyframe (iPhone 14, 2026-10-19).
b.links.last.open();
flush(async);
- expect(b.host.wsTypes, ['terminal_resync']);
- expect(b.links.last.sent, isEmpty);
- // Meanwhile relay output for it is NOT read as a broken channel.
- b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
- flush(async);
- expect(b.links.last.stopped, isFalse);
-
- // Phase 2: the keyframe answering it → a resync over the channel.
- b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
- flush(async);
+ expect(b.host.wsTypes, isNot(contains('terminal_resync')));
expect(b.links.last.sent, hasLength(1));
expect(
jsonDecode(b.links.last.sent.single as String)['type'],
'terminal_resync',
);
expect(b.plugin.linkModeFor(streamA), 'p2p');
- // Still suppressed until a channel-delivered frame proves the flip…
+ // The stream's own frames take the channel from now on.
+ b.host.sendTerminalBinary(htrl(TerminalBinaryKind.input, streamA));
+ flush(async);
+ expect(b.host.wsBinary, isEmpty);
+ expect(b.links.last.sent, hasLength(2));
+ // Relay output still on its way, a keyframe included, is not a broken channel —
+ // and does not start the move over.
b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
flush(async);
expect(b.links.last.stopped, isFalse);
- // …which re-arms the ordinary rule.
+ expect(b.links.last.sent, hasLength(2), reason: 'no second resync');
+ // A channel-delivered frame proves the flip and re-arms the ordinary rule.
b.links.last.receive(htrl(TerminalBinaryKind.output, streamA));
flush(async);
b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
@@ -378,27 +442,68 @@ void main() {
},
);
- test('a migration nobody answers is swept after 30s', () {
- fakeAsync((async) {
- final b = bootPlugin(async: async);
- b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
- async.elapse(const Duration(milliseconds: 1500));
- flush(async);
- b.host.receiveWs(ready(streamA, 'r1'));
- flush(async);
- b.links.last.open();
- flush(async);
- async.elapse(const Duration(seconds: 41));
- // No longer migrating: the keyframe now is just a keyframe.
- b.links.last.sent.clear();
- b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
- flush(async);
- expect(b.links.last.sent, isEmpty);
- b.plugin.dispose();
- });
- });
+ test(
+ 'a stream that comes up on the socket after the channel moves at its first keyframe',
+ () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ // Opened before the channel was up, answered after it came up.
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ flush(async);
+ b.links.last.open();
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ expect(
+ b.links.last.sent,
+ isEmpty,
+ reason: 'not while the open\'s own keyframe is being taken',
+ );
+ b.host.wsFrames.clear();
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
+ flush(async);
+ expect(b.host.wsTypes, isNot(contains('terminal_resync')));
+ expect(
+ b.links.last.sent.map(
+ (frame) => jsonDecode(frame as String)['type'],
+ ),
+ ['terminal_resync'],
+ );
+ expect(b.plugin.linkModeFor(streamA), 'p2p');
+ b.plugin.dispose();
+ });
+ },
+ );
+
+ test(
+ 'a move nobody answers is swept after 30s, and the ordinary rule applies again',
+ () {
+ fakeAsync((async) {
+ final b = bootPlugin(async: async);
+ b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
+ async.elapse(const Duration(milliseconds: 1500));
+ flush(async);
+ b.host.receiveWs(ready(streamA, 'r1'));
+ flush(async);
+ b.links.last.open();
+ flush(async);
+ // In flight: relay output is the responder not having flipped yet.
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopped, isFalse);
+ async.elapse(const Duration(seconds: 41));
+ // Swept: the channel took the resync and never carried the stream — broken, so the
+ // next relay frame demotes it, which resyncs every stream over the socket.
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopReason, 'relay_binary_received');
+ expect(b.host.wsTypes, contains('terminal_resync'));
+ b.plugin.dispose();
+ });
+ },
+ );
- test('phase 2 failing abandons only that stream', () {
+ test('a move the channel refuses abandons only that stream', () {
fakeAsync((async) {
final b = bootPlugin(async: async);
b.host.sendTerminalFrame('terminal_open', {'requestId': 'r1'});
@@ -406,19 +511,21 @@ void main() {
flush(async);
b.host.receiveWs(ready(streamA, 'r1'));
flush(async);
- b.links.last.open();
- flush(async);
- b.links.last.acceptSends = false;
b.host.wsFrames.clear();
- b.host.receiveWsBinary(htrl(TerminalBinaryKind.keyframe, streamA));
+ b.links.last.acceptSends = false;
+ b.links.last.open();
flush(async);
expect(
- b.host.wsFrames,
- isEmpty,
+ b.host.wsTypes,
+ isNot(contains('terminal_resync')),
reason: 'never falls back to the socket',
);
expect(b.links.last.stopped, isFalse);
expect(b.plugin.linkModeFor(streamA), 'relay');
+ // Its relay output is just its output.
+ b.host.receiveWsBinary(htrl(TerminalBinaryKind.output, streamA));
+ flush(async);
+ expect(b.links.last.stopped, isFalse);
b.plugin.dispose();
});
});
diff --git a/mobile/test/p2p/webrtc_link_test.dart b/mobile/test/p2p/webrtc_link_test.dart
index 2c10f6865..f3add721d 100644
--- a/mobile/test/p2p/webrtc_link_test.dart
+++ b/mobile/test/p2p/webrtc_link_test.dart
@@ -176,6 +176,31 @@ void main() {
expect(link.isReady, isFalse);
});
+ test('the offer leaves a short settle after the first reflexive candidate', () async {
+ // A terminal's keys ride the relay until the channel is up, and the channel only follows the
+ // offer: the settle was 500 ms of a ~1.5 s setup on an iPhone 14 (2026-10-19).
+ final link = newLink();
+ link.start();
+ await eventually(() => webrtc.named('setLocalDescription').isNotEmpty);
+ await settle();
+ final found = Stopwatch()..start();
+ await webrtc.candidate(
+ 'candidate:2 1 udp 1686052607 203.0.113.9 50001 typ srflx raddr 0.0.0.0 rport 0',
+ );
+ expect(
+ await eventually(
+ () => log.of('p2p_offer').isNotEmpty,
+ within: const Duration(seconds: 2),
+ ),
+ isTrue,
+ );
+ expect(found.elapsed, greaterThanOrEqualTo(gatherSettleAfterReflexive));
+ // Wall-clock, so only far from the 3s cap; the settle itself is pinned below.
+ expect(found.elapsed, lessThan(const Duration(seconds: 1)));
+ expect(gatherSettleAfterReflexive, const Duration(milliseconds: 100));
+ expect(link.isReady, isFalse);
+ });
+
test('with nothing reflexive, it goes at the cap anyway', () async {
final link = newLink();
link.start();
diff --git a/mobile/test/terminal_local_echo_test.dart b/mobile/test/terminal_local_echo_test.dart
new file mode 100644
index 000000000..4adfc33ed
--- /dev/null
+++ b/mobile/test/terminal_local_echo_test.dart
@@ -0,0 +1,432 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:xterm/xterm.dart';
+
+/// Local echo (`TerminalView.predictsEcho`): what is typed is drawn faint at the
+/// cursor before the machine echoes it back — but only where that echo will
+/// land, only once the terminal has been seen to echo, and never into a prompt
+/// that does not echo (a password). A key the screen cannot vouch for is simply
+/// not drawn: drawing nothing is always safe, drawing the wrong thing is not.
+void main() {
+ /// The phone's terminal: delete detection on, local echo on, a prompt drawn.
+ Future<({Terminal terminal, List<String> sent, _Keyboard keyboard})> open(
+ WidgetTester tester,
+ ) async {
+ final terminal = Terminal(maxLines: 200, reflowEnabled: false)
+ ..resize(80, 12);
+ final sent = <String>[];
+ terminal.onOutput = sent.add;
+ terminal.write('> ');
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: SizedBox(
+ width: 400,
+ height: 320,
+ child: TerminalView(
+ terminal,
+ autofocus: true,
+ deleteDetection: true,
+ predictsEcho: true,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ expect(tester.testTextInput.hasAnyClients, isTrue);
+ return (terminal: terminal, sent: sent, keyboard: _Keyboard(tester));
+ }
+
+ String drawn(WidgetTester tester) =>
+ tester.state<TerminalViewState>(find.byType(TerminalView)).debugPredictedText;
+
+ /// The machine echoing [text] back, as a terminal does: written at the cursor.
+ Future<void> echo(WidgetTester tester, Terminal terminal, String text) async {
+ terminal.write(text);
+ await tester.pump();
+ }
+
+ /// A terminal already seen echoing, with `ab` typed and echoed.
+ Future<({Terminal terminal, List<String> sent, _Keyboard keyboard})> echoing(
+ WidgetTester tester,
+ ) async {
+ final t = await open(tester);
+ await t.keyboard.type('a');
+ await echo(tester, t.terminal, 'a');
+ await t.keyboard.type('b');
+ await echo(tester, t.terminal, 'b');
+ t.sent.clear();
+ return t;
+ }
+
+ testWidgets(
+ 'draws nothing until the terminal is seen echoing, then draws each key ahead of its echo',
+ (tester) async {
+ final t = await open(tester);
+ await t.keyboard.type('h');
+ expect(t.sent, ['h']);
+ expect(drawn(tester), '', reason: 'nothing seen echoing yet');
+ await echo(tester, t.terminal, 'h');
+ await t.keyboard.type('i');
+ expect(drawn(tester), 'i');
+ await echo(tester, t.terminal, 'i');
+ expect(drawn(tester), '');
+ },
+ );
+
+ testWidgets(
+ 'a guess whose echo never comes is taken down, and nothing more is guessed',
+ (tester) async {
+ // A password prompt that appeared in place: the typed key must not stay
+ // on the screen, and the next one must not be drawn at all.
+ final t = await echoing(tester);
+ await t.keyboard.type('x');
+ expect(drawn(tester), 'x');
+ await tester.pump(const Duration(milliseconds: 450));
+ expect(drawn(tester), '');
+ await t.keyboard.type('y');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+
+ testWidgets(
+ 'output that is not what was typed turns guessing off until a key is seen echoed',
+ (tester) async {
+ // The cursor moving on is not an echo by itself: only the typed text
+ // drawn back is.
+ final t = await echoing(tester);
+ await t.keyboard.type('q');
+ await echo(tester, t.terminal, 'Z');
+ expect(drawn(tester), '');
+ await t.keyboard.type('r');
+ expect(drawn(tester), '', reason: 'guessing is off');
+ await echo(tester, t.terminal, 'r');
+ await t.keyboard.type('s');
+ expect(drawn(tester), 's');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+
+ testWidgets(
+ 'a space the program moves past instead of printing is still its echo',
+ (tester) async {
+ // A TUI may draw a typed blank by moving the cursor over it.
+ final t = await echoing(tester);
+ await t.keyboard.type(' ');
+ await t.keyboard.type('x');
+ await echo(tester, t.terminal, '\x1b[C');
+ expect(drawn(tester), 'x');
+ await echo(tester, t.terminal, 'x');
+ expect(drawn(tester), '');
+ },
+ );
+
+ group('password prompts', () {
+ testWidgets('one that masks each key with * never has a key drawn', (
+ tester,
+ ) async {
+ // `gh auth login`'s token, sudo with pwfeedback: keys typed faster than
+ // the first * came back were drawn the moment it did (review, 2026-10-19).
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\nToken: ');
+ await t.keyboard.type('s');
+ await t.keyboard.type('e');
+ await t.keyboard.type('c');
+ expect(drawn(tester), '');
+ await echo(tester, t.terminal, '*');
+ expect(drawn(tester), '');
+ await echo(tester, t.terminal, '**');
+ expect(drawn(tester), '');
+ // A delete there is no probe: the next key is not drawn at once either.
+ await t.keyboard.backspace();
+ await echo(tester, t.terminal, '\b \b');
+ await t.keyboard.type('x');
+ expect(drawn(tester), '');
+ await echo(tester, t.terminal, '*');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ });
+
+ testWidgets(
+ 'output moving the cursor at one that does not echo draws nothing',
+ (tester) async {
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\nPassword: ');
+ for (final c in 'secret'.split('')) {
+ await t.keyboard.type(c);
+ await tester.pump(const Duration(milliseconds: 300));
+ }
+ await echo(tester, t.terminal, ' ');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+
+ testWidgets(
+ 'one that does not echo is found out while somebody keeps typing into it',
+ (tester) async {
+ // Each key used to restart the wait for an echo, so typing steadily
+ // kept guessing on over the whole password — and one character of
+ // output that happened to match its first key drew all the rest.
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\nPassword: ');
+ for (var i = 0; i < 8; i++) {
+ await t.keyboard.type('a');
+ await tester.pump(const Duration(milliseconds: 300));
+ }
+ await echo(tester, t.terminal, 'a');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+ });
+
+ testWidgets('a key typed while the cursor is elsewhere is not drawn', (
+ tester,
+ ) async {
+ // Output streaming or a program redrawing moves the cursor about: a guess
+ // drawn there would be drawn in the wrong place.
+ final t = await echoing(tester);
+ await echo(tester, t.terminal, '\x1b[6;10H');
+ await t.keyboard.type('z');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ });
+
+ group('after a delete', () {
+ testWidgets('the next key is drawn at once once the delete is echoed', (
+ tester,
+ ) async {
+ // 12 of 52 keys not drawn came right after a delete (iPhone 14,
+ // 2026-10-19): the input point was forgotten with it, and the next key had
+ // to wait for its own echo.
+ final t = await echoing(tester);
+ await t.keyboard.backspace();
+ expect(t.sent, ['\x7f']);
+ await echo(tester, t.terminal, '\b \b');
+ await t.keyboard.type('c');
+ expect(drawn(tester), 'c');
+ });
+
+ testWidgets('a delete whose echo never comes leaves guessing on', (
+ tester,
+ ) async {
+ // Nothing to delete: the program echoes nothing, and that is no reason to
+ // stop drawing ahead.
+ final t = await echoing(tester);
+ await t.keyboard.backspace();
+ await tester.pump(const Duration(seconds: 3));
+ await t.keyboard.type('q');
+ expect(drawn(tester), '', reason: 'where it lands is not known yet');
+ await echo(tester, t.terminal, 'q');
+ await t.keyboard.type('r');
+ expect(drawn(tester), 'r');
+ });
+
+ /// `z中` typed and echoed, then two deletes sent before either echo came:
+ /// the wide character's comes back first.
+ Future<({Terminal terminal, List<String> sent, _Keyboard keyboard})>
+ heldBackspace(WidgetTester tester) async {
+ final t = await echoing(tester);
+ await t.keyboard.type('z');
+ await echo(tester, t.terminal, 'z');
+ await t.keyboard.type('中');
+ await echo(tester, t.terminal, '中');
+ await t.keyboard.backspace();
+ await t.keyboard.backspace();
+ expect(t.sent.where((s) => s == '\x7f'), hasLength(2));
+ return t;
+ }
+
+ testWidgets(
+ 'deletes sent faster than their echo are all waited for, wide ones too',
+ (tester) async {
+ // A held backspace: each delete used to start the probe over, which
+ // ended at the first echo with the cursor still to step back (review,
+ // 2026-10-19).
+ final t = await heldBackspace(tester);
+ await echo(tester, t.terminal, '\b\b \b\b');
+ await echo(tester, t.terminal, '\b \b');
+ await t.keyboard.type('c');
+ expect(drawn(tester), 'c');
+ await echo(tester, t.terminal, 'c');
+ expect(drawn(tester), '');
+ },
+ );
+
+ testWidgets('a key typed before the last delete is echoed is not drawn', (
+ tester,
+ ) async {
+ // Drawn after the first echo, it sat where the cursor would not be once
+ // the second delete came back.
+ final t = await heldBackspace(tester);
+ await echo(tester, t.terminal, '\b\b \b\b');
+ await t.keyboard.type('c');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ });
+
+ testWidgets('a wide character deleted puts the input point two cells back', (
+ tester,
+ ) async {
+ final t = await echoing(tester);
+ await t.keyboard.type('中');
+ await echo(tester, t.terminal, '中');
+ await t.keyboard.backspace();
+ await echo(tester, t.terminal, '\b\b \b\b');
+ await t.keyboard.type('c');
+ expect(drawn(tester), 'c');
+ await echo(tester, t.terminal, 'c');
+ expect(drawn(tester), '');
+ });
+
+ testWidgets('a word retyped right after its deletes is never drawn ahead', (
+ tester,
+ ) async {
+ // Telex turns `duoc` into `được` as three deletes and the letters
+ // retyped, all at once: where they land depends on the deletes' echo.
+ final t = await echoing(tester);
+ await t.keyboard.type('duoc');
+ for (final c in 'duoc'.split('')) {
+ await echo(tester, t.terminal, c);
+ }
+ t.sent.clear();
+ await t.keyboard.replaceTail(3, 'ược');
+ expect(t.sent, ['\x7f', '\x7f', '\x7f', 'ược']);
+ expect(drawn(tester), '');
+ await echo(tester, t.terminal, '\b\b\bược');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ });
+ });
+
+ group('after Enter', () {
+ testWidgets(
+ 'keys typed before the first echo comes back are drawn as soon as it does',
+ (tester) async {
+ // 16 of 52 keys not drawn were typed faster than the first echo came
+ // back after the input point was lost: each was a probe of its own, and
+ // none was drawn even once one echo had shown where they land.
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\n> ');
+ await t.keyboard.type('x');
+ await t.keyboard.type('y');
+ await t.keyboard.type('z');
+ expect(drawn(tester), '');
+ await echo(tester, t.terminal, 'x');
+ expect(drawn(tester), 'yz');
+ await echo(tester, t.terminal, 'yz');
+ expect(drawn(tester), '');
+ },
+ );
+
+ testWidgets(
+ 'an echo slow to come back with nothing drawn keeps guessing on',
+ (tester) async {
+ // Claude Code starting a turn echoes the first key late: 9 of 19 keys
+ // not drawn because guessing had been turned off came right after Enter.
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\n> ');
+ await t.keyboard.type('a');
+ await t.keyboard.type('b');
+ await tester.pump(const Duration(milliseconds: 600));
+ await echo(tester, t.terminal, 'a');
+ expect(drawn(tester), 'b');
+ await echo(tester, t.terminal, 'b');
+ await t.keyboard.type('c');
+ expect(drawn(tester), 'c');
+ },
+ );
+
+ testWidgets(
+ 'a key drawn once a slow first echo came is taken down at the short wait',
+ (tester) async {
+ // The longer wait is for an echo with nothing drawn ahead of it; a guess
+ // on screen gets the short one, or a prompt that stopped echoing would
+ // show it for 1.6s.
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\n> ');
+ await t.keyboard.type('a');
+ await t.keyboard.type('b');
+ await tester.pump(const Duration(milliseconds: 600));
+ await echo(tester, t.terminal, 'a');
+ expect(drawn(tester), 'b');
+ await tester.pump(const Duration(milliseconds: 450));
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+
+ testWidgets(
+ 'a prompt that never echoes is never drawn into, however long it waits',
+ (tester) async {
+ // After Enter, a password prompt: nothing typed into it is ever drawn.
+ final t = await echoing(tester);
+ await t.keyboard.enter();
+ await echo(tester, t.terminal, '\r\nPassword: ');
+ for (final c in 'secret'.split('')) {
+ await t.keyboard.type(c);
+ expect(drawn(tester), '');
+ }
+ await tester.pump(const Duration(seconds: 3));
+ await t.keyboard.type('!');
+ expect(drawn(tester), '');
+ await tester.pump(const Duration(seconds: 3));
+ },
+ );
+ });
+}
+
+/// The software keyboard's own buffer, as UIKit holds it: the terminal's two
+/// padding spaces, then what was typed on this line.
+class _Keyboard {
+ _Keyboard(this.tester);
+
+ final WidgetTester tester;
+ String _buffer = ' ';
+
+ Future<void> type(String text) async {
+ for (final rune in text.runes) {
+ _buffer += String.fromCharCode(rune);
+ await _send();
+ }
+ }
+
+ /// Return: the terminal hands the keyboard back its padding a moment later
+ /// (`resetEditingState`), and the keyboard's buffer starts over from it.
+ Future<void> enter() async {
+ await tester.testTextInput.receiveAction(TextInputAction.newline);
+ await tester.pump(const Duration(milliseconds: 20));
+ _buffer = ' ';
+ }
+
+ Future<void> backspace() async {
+ _buffer = _buffer.substring(0, _buffer.length - 1);
+ await _send();
+ }
+
+ /// The keyboard rewriting the last [count] characters of its buffer as
+ /// [text] in one edit — what Telex does to a word.
+ Future<void> replaceTail(int count, String text) async {
+ _buffer = _buffer.substring(0, _buffer.length - count) + text;
+ await _send();
+ }
+
+ Future<void> _send() async {
+ tester.testTextInput.updateEditingValue(
+ TextEditingValue(
+ text: _buffer,
+ selection: TextSelection.collapsed(offset: _buffer.length),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+}
diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dart
index fa471ad8c..bba9b65f2 100644
--- a/mobile/third_party/xterm/lib/src/terminal_view.dart
+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart
@@ -23,6 +23,7 @@ import 'package:xterm/src/ui/terminal_text_style.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
import 'package:xterm/src/ui/themes.dart';
import 'dart:async';
+import 'dart:math' show max, min;
import 'package:xterm/src/utils/input_trace.dart';
import 'package:xterm/src/utils/unicode_v11.dart';
@@ -286,9 +287,24 @@ class TerminalViewState extends State<TerminalView> {
// ── AUTONOMOUS PATCH: local echo — see [TerminalView.predictsEcho] ──────────
- /// What is drawn ahead of the echo: typed, sent, not yet echoed.
+ /// What is drawn ahead of the echo: [_pending], once the cursor rests at the
+ /// input point; nothing otherwise.
String _predicted = '';
+ /// Every key typed and sent since the last one seen echoed, drawn or not. One
+ /// typed while the input point was not known (just after Enter or a delete)
+ /// waits here, and is drawn the moment the first echo shows where it lands —
+ /// keys typed faster than the echo came back used to be lost to prediction
+ /// one after another (16 of 52 misses, iPhone 14, 2026-10-19).
+ String _pending = '';
+
+ /// Deletes sent and not yet echoed: while set, [_echoFrom] waits for the
+ /// cursor to step back along its line, which is the input point again.
+ int _pendingDeletes = 0;
+
+ /// The wait for a key's echo was extended once already — see [_echoNeverCame].
+ bool _waitedLonger = false;
+
/// Where the cursor was, and its line's [BufferLine.paintVersion], when the
/// oldest key not yet echoed went out. Null while nothing is awaited.
({int x, int y, int version})? _echoFrom;
@@ -308,6 +324,10 @@ class TerminalViewState extends State<TerminalView> {
/// How long a key's echo may take before it is taken not to be coming.
static const _echoWait = Duration(milliseconds: 400);
+ /// How much longer an echo is waited for when nothing was drawn ahead of it —
+ /// see [_echoNeverCame].
+ static const _lateEchoWait = Duration(milliseconds: 1600);
+
late TerminalController _controller;
late ScrollController _scrollController;
@@ -479,7 +499,7 @@ class TerminalViewState extends State<TerminalView> {
onInsert: _onInsert,
onDelete: (count) {
inputTrace(() => 'view delete ×$count');
- _restartPrediction();
+ _probeDelete(count);
_scrollToBottom();
for (var index = 0; index < count; index++) {
widget.terminal.keyInput(TerminalKey.backspace);
@@ -701,45 +721,104 @@ class TerminalViewState extends State<TerminalView> {
_dropPrediction();
return;
}
+ if (_pendingDeletes > 0) {
+ // A word retyped right after its deletes (Telex turns `duoc` into
+ // `được` that way): where its echo lands depends on the deletes', which
+ // have not come back. Nothing of it is drawn, and it is no probe either.
+ _restartPrediction();
+ inputTrace(() => 'echo not predicted (a word rewritten)');
+ return;
+ }
final now = _cursorMark();
_echoFrom ??= now;
+ _pending += text;
+ _drawPending(now);
+ if (_predicted.isEmpty) {
+ final at = _inputPoint;
+ inputTrace(
+ () => 'echo not predicted (seen echoing=$_echoes,'
+ ' at input point=${at != null && at.x == now.x && at.y == now.y})',
+ );
+ }
+ // ⚠️ From the oldest key not yet echoed, not restarted by each new one: restarted, a prompt
+ // that never echoes was never found out while somebody kept typing into it, and prediction
+ // stayed on over the whole password (review, 2026-10-19). An echo arriving restarts it.
+ _echoTimeout ??= Timer(_echoWait, _echoNeverCame);
+ }
+
+ /// Draws all of [_pending] at the cursor — only with the cursor resting at the
+ /// input point, a terminal seen echoing, and room left on the line.
+ void _drawPending(({int x, int y, int version}) now) {
final at = _inputPoint;
- if (_echoes &&
+ if (_pending.isNotEmpty &&
+ _echoes &&
at != null &&
at.x == now.x &&
at.y == now.y &&
- now.x + _cells(_predicted + text) <= widget.terminal.viewWidth) {
- _setPredicted(_predicted + text);
+ now.x + _cells(_pending) <= widget.terminal.viewWidth) {
+ _setPredicted(_pending);
inputTrace(() => 'echo predicted "${traceText(_predicted)}"');
- } else {
- inputTrace(
- () => 'echo not predicted (seen echoing=$_echoes,'
- ' at input point=${at != null && at.x == now.x && at.y == now.y})',
- );
+ } else if (_predicted.isNotEmpty) {
+ _setPredicted('');
}
- _echoTimeout?.cancel();
- _echoTimeout = Timer(_echoWait, _echoNeverCame);
}
/// The terminal changed: an echo arriving takes the keys it drew off the
- /// prediction; anything else at the cursor takes the prediction down.
+ /// prediction, and shows where the rest lands; deletes echoed show where the
+ /// input point now is; anything else at the cursor takes the prediction down.
void _followEcho() {
final from = _echoFrom;
if (from == null) return;
final now = _cursorMark();
// Nothing at the cursor yet — a blink, a redraw elsewhere on the screen.
if (now == from) return;
+ if (_pendingDeletes > 0) {
+ if (now.y == from.y && now.x < from.x) {
+ // The deletes are echoed: where the cursor stepped back to is the input
+ // point, and the next key is drawn at once rather than waiting for its
+ // own echo (12 of 52 misses came right after a delete, 2026-10-19).
+ // Counted in cells, as [_probeDelete] measured them.
+ _pendingDeletes = max(0, _pendingDeletes - (from.x - now.x));
+ _inputPoint = (x: now.x, y: now.y);
+ inputTrace(() => 'echo after a delete: input point back at ${now.x}');
+ if (_pendingDeletes > 0) {
+ _echoFrom = now;
+ } else {
+ _dropPrediction();
+ }
+ return;
+ }
+ _dropPrediction();
+ return;
+ }
if (now.y == from.y && now.x > from.x) {
+ // ⚠️ **An echo is what was typed, drawn back.** The cursor moving on is not
+ // enough: a prompt that masks what is typed (`*` for each key: sudo with
+ // pwfeedback, `gh auth login`'s token) moves it just the same, and taking
+ // that for an echo drew the rest of the password ahead of it (review,
+ // 2026-10-19). Anything else at the cursor turns prediction off until a key
+ // IS seen echoed. A password starting with the very character its prompt
+ // masks with is the one case this cannot tell apart.
+ if (!_shows(from, now.x, _pending)) {
+ inputTrace(() => 'echo not what was typed — off');
+ _echoes = false;
+ _restartPrediction();
+ return;
+ }
_echoes = true;
_inputPoint = (x: now.x, y: now.y);
- final rest = _afterCells(_predicted, now.x - from.x);
- _setPredicted(rest);
- if (rest.isEmpty) {
- _echoFrom = null;
- _echoTimeout?.cancel();
- _echoTimeout = null;
+ _pending = _afterCells(_pending, now.x - from.x);
+ if (_pending.isEmpty) {
+ _dropPrediction();
} else {
_echoFrom = now;
+ _drawPending(now);
+ // The next key's echo gets a wait of its own, from now: what is drawn
+ // must not outstay an echo that does not come by the longer wait a slow
+ // first echo was given.
+ _waitedLonger = false;
+ _echoTimeout?.cancel();
+ _echoTimeout = Timer(_echoWait, _echoNeverCame);
}
return;
}
@@ -748,16 +827,82 @@ class TerminalViewState extends State<TerminalView> {
_dropPrediction();
}
- /// A key's echo did not come: not a terminal that echoes what is typed into
- /// it right now — a password prompt, or a program not reading.
+ /// A key's echo did not come in [_echoWait].
+ ///
+ /// A guess drawn on screen whose echo never came is a terminal not echoing
+ /// what is typed right now — a password prompt — and turns prediction off
+ /// until a key is seen echoed again. That is what this wait is for, so it
+ /// stays short. With nothing drawn ahead of it the echo costs no safety, and a
+ /// program can be slow to echo the first key after Enter (Claude Code
+ /// starting a turn: 9 of 19 such misses came right after Enter, 2026-10-19):
+ /// it is waited for [_lateEchoWait] longer, prediction staying on, so that the
+ /// echo, when it comes, still shows where the next keys land. Deletes whose
+ /// echo never came — nothing to delete — just stop being waited for.
void _echoNeverCame() {
- inputTrace(
- () => 'echo never came within ${_echoWait.inMilliseconds}ms — off');
_echoTimeout = null;
+ if (_pendingDeletes > 0) {
+ _dropPrediction();
+ return;
+ }
+ if (_predicted.isEmpty && _echoes && !_waitedLonger && _echoFrom != null) {
+ _waitedLonger = true;
+ inputTrace(() =>
+ 'echo slow, nothing drawn — waiting ${_lateEchoWait.inMilliseconds}ms more');
+ _echoTimeout = Timer(_lateEchoWait, _echoNeverCame);
+ return;
+ }
+ inputTrace(() => 'echo never came — off');
_echoes = false;
_dropPrediction();
}
+ /// AUTONOMOUS PATCH: [count] deletes just went out. What was drawn goes, and
+ /// so does the input point — but the deletes are a probe of their own: once
+ /// their echo steps the cursor back along its line, the input point is where
+ /// it rests ([_followEcho]).
+ void _probeDelete(int count) {
+ // Deletes sent before the earlier ones were echoed (a held backspace) step
+ // on from where those leave the cursor; started over, the probe ended at
+ // the first echo, with the cursor still to step back.
+ final awaited = _pendingDeletes;
+ final from = _echoFrom;
+ _restartPrediction();
+ if (!widget.predictsEcho || !_echoes || count <= 0) return;
+ if (awaited > 0 && from != null) {
+ _pendingDeletes = awaited + _cellsBefore(from.x - awaited, count);
+ _echoFrom = from;
+ } else {
+ _echoFrom = _cursorMark();
+ _pendingDeletes = _cellsBefore(_echoFrom!.x, count);
+ }
+ _echoTimeout = Timer(_echoWait, _echoNeverCame);
+ }
+
+ /// How far back [count] deletes step the cursor from column [fromX]: the
+ /// cells of the last [count] characters before it on the cursor's line, two
+ /// for a wide one. Counted as one each, a wide character's delete ended the
+ /// probe a delete early, and the next key was drawn a cell off (review,
+ /// 2026-10-19).
+ int _cellsBefore(int fromX, int count) {
+ final buffer = widget.terminal.buffer;
+ final y = buffer.absoluteCursorY;
+ if (y < 0 || y >= buffer.lines.length) return count;
+ final line = buffer.lines[y];
+ var x = min(max(fromX, 0), line.length);
+ var cells = 0;
+ var deletes = 0;
+ for (; deletes < count && x > 0; deletes++) {
+ final wide =
+ x >= 2 && line.getCodePoint(x - 1) == 0 && line.getWidth(x - 2) == 2;
+ final step = wide ? 2 : 1;
+ x -= step;
+ cells += step;
+ }
+ // Deletes past the start of the line step nothing back on it; they are
+ // still waited for, so that nothing is drawn before their echo has settled.
+ return cells + (count - deletes);
+ }
+
/// A key that moves the cursor or the line rather than adding to it — a
/// delete, Enter, an arrow: what is drawn goes, and so does the input point,
/// so the next key waits for its own echo before anything is drawn ahead of
@@ -773,6 +918,9 @@ class TerminalViewState extends State<TerminalView> {
_echoTimeout?.cancel();
_echoTimeout = null;
_echoFrom = null;
+ _pending = '';
+ _pendingDeletes = 0;
+ _waitedLonger = false;
if (_predicted.isNotEmpty) _setPredicted('');
}
@@ -802,6 +950,25 @@ class TerminalViewState extends State<TerminalView> {
return true;
}
+ /// Whether the cells from [from] up to [toX] on its line show [typed] — as
+ /// much of it as fills them, and nothing else. A cell never written stands for
+ /// a typed space: a TUI may move the cursor past a blank instead of printing it.
+ bool _shows(({int x, int y, int version}) from, int toX, String typed) {
+ final lines = widget.terminal.buffer.lines;
+ if (from.y < 0 || from.y >= lines.length) return false;
+ final line = lines[from.y];
+ var x = from.x;
+ for (final rune in typed.runes) {
+ if (x >= toX) break;
+ if (x >= line.length) return false;
+ final cell = line.getCodePoint(x);
+ if (cell != rune && !(rune == 0x20 && cell == 0)) return false;
+ final width = unicodeV11.wcwidth(rune);
+ x += width > 0 ? width : 1;
+ }
+ return x == toX;
+ }
+
static int _cells(String text) {
var cells = 0;
for (final rune in text.runes) {
@@ -827,6 +994,10 @@ class TerminalViewState extends State<TerminalView> {
@visibleForTesting
String? get debugComposingText => _composingText;
+ /// AUTONOMOUS PATCH: what is drawn at the cursor ahead of its echo.
+ @visibleForTesting
+ String get debugPredictedText => _predicted;
+
/// Live input-client composition, independent of its visual preview (which
/// may already match echoed terminal cells). Workspace shortcuts must let
/// the IME finish its marked text before claiming a key.