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.

feat(mobile): echo keys locally, cut keyframes and re-renders

tonyc6296c4b6b04
diff --git a/mobile/lib/daemons/daemon_face.dart b/mobile/lib/daemons/daemon_face.dart
index 4bffb2317..55ab8cb84 100644
--- a/mobile/lib/daemons/daemon_face.dart
+++ b/mobile/lib/daemons/daemon_face.dart
@@ -304,6 +304,15 @@ class DaemonFace extends ChangeNotifier {
_update();
return;
}
+ // ⚠️ **Nothing it watches moved: no redraw.** This is asked on every tick of the app's
+ // notifier (`DaemonHostState._sync`) — an agent synced anywhere, a pane attaching — and it
+ // redrew the chip in the terminal's header each time, under somebody typing. Only what it
+ // watches decides what it shows; the rest of its motion runs on its own timers.
+ if (setEquals(before.needs, next.needs) &&
+ setEquals(before.working, next.working) &&
+ setEquals(before.failing, next.failing)) {
+ return;
+ }
final newNeed = next.needs.difference(before.needs).isNotEmpty;
final newFail = next.failing.difference(before.failing).isNotEmpty;
final finished = before.working.difference(next.working).isNotEmpty;
diff --git a/mobile/lib/logging/install.dart b/mobile/lib/logging/install.dart
index aec08d2c5..1da1172e6 100644
--- a/mobile/lib/logging/install.dart
+++ b/mobile/lib/logging/install.dart
@@ -5,6 +5,7 @@ import 'debug_surface.dart';
import 'log_file.dart';
import 'log_stream.dart';
import 'log_stream_sinks.dart';
+import 'typing_trace.dart';
/// Base name of the per-day file under `~/.harness/logs`.
const String kAppLogBase = 'app';
@@ -35,6 +36,8 @@ void installFileLogs() {
onDetach: () => daily.flush(durable: true),
);
final file = FileAppLog(daily);
+ // The typing trace — nothing unless the build asked for it (`typing_trace.dart`).
+ installTypingTrace();
if (!kDebugSurfaceEnabled) {
appLog = file;
return;
diff --git a/mobile/lib/logging/typing_trace.dart b/mobile/lib/logging/typing_trace.dart
new file mode 100644
index 000000000..ce8c5fe01
--- /dev/null
+++ b/mobile/lib/logging/typing_trace.dart
@@ -0,0 +1,103 @@
+import 'dart:async';
+
+import 'package:flutter/scheduler.dart';
+import 'package:xterm/utils.dart' show xtermInputTrace;
+
+import 'app_log.dart';
+
+/// The typing trace: typing into a terminal on a phone, traced key by key — and the costs around
+/// it (Find opening, switching agent). Built in only when asked for:
+///
+/// ```
+/// flutter run --profile --dart-define=HARNESS_TYPING_TRACE=true
+/// ```
+///
+/// Every step a keystroke takes is written to the app log under `type`, stamped with a millisecond
+/// clock (`t=`): the keyboard's edit (`ime ←`), what of it reached the terminal (`ime → pty`,
+/// `view insert`), what went to the machine (`pty in`, `pty sent`), what came back (`out`), what it
+/// cost to draw (`paint`, `frame SLOW`), and everything that can lose or delay a keystroke on the
+/// way — a dropped send, a resync, a keyframe swapping the terminal, the keyboard's buffer being
+/// reset. How to read it: `.claude/autonomous-harness-mobile-performance.vi.md`.
+///
+/// ⚠️ **Off unless asked for, and it has to stay that way.** The trace carries the tail of what was
+/// typed — passwords typed at a prompt included — so a build that ships must never have it on.
+/// `const`, so every call site guarded by it compiles away when it is off.
+const bool kTypingTrace = bool.fromEnvironment('HARNESS_TYPING_TRACE');
+
+final Stopwatch _clock = Stopwatch()..start();
+
+/// The trace clock, in milliseconds.
+int typingNowMs() => _clock.elapsedMilliseconds;
+
+/// When something was last typed — what [typingNote] and the frame and counter reports stay on
+/// for, for [_window] after.
+int _lastTypedMs = -1 << 30;
+const _window = 3000;
+
+bool get _typing => typingNowMs() - _lastTypedMs < _window;
+
+/// Something typed, or on its way to the machine: always written, and it opens the window.
+void typingTrace(String message) {
+ if (!kTypingTrace) return;
+ _lastTypedMs = typingNowMs();
+ _write(message);
+}
+
+/// Something that can lose or delay a keystroke — a resync, a keyframe, a reset: always written.
+void typingEvent(String message) {
+ if (kTypingTrace) _write(message);
+}
+
+/// Something that happens all the time — output arriving, a paint: written only while somebody is
+/// typing, so an agent streaming on its own does not fill the log.
+void typingNote(String message) {
+ if (kTypingTrace && _typing) _write(message);
+}
+
+void _write(String message) =>
+ appLog.debug('type', 't=${typingNowMs()} $message');
+
+final Map<String, int> _counts = {};
+Timer? _countsTimer;
+
+/// One more [what] — a notify, a rebuild — reported as a count per second while somebody is
+/// typing.
+void typingCount(String what) {
+ if (!kTypingTrace || !_typing) return;
+ _counts.update(what, (count) => count + 1, ifAbsent: () => 1);
+ _countsTimer ??= Timer(const Duration(seconds: 1), _flushCounts);
+}
+
+void _flushCounts() {
+ _countsTimer = null;
+ if (_counts.isEmpty) return;
+ final counts = _counts.entries
+ .map((entry) => '${entry.key}=${entry.value}')
+ .join(' ');
+ _counts.clear();
+ _write('counts/1s $counts');
+}
+
+/// Hooks the trace up: xterm's input path, and the frame timings. Called once, from
+/// `installFileLogs`.
+void installTypingTrace() {
+ if (!kTypingTrace) return;
+ xtermInputTrace = (message) =>
+ message.startsWith('paint') ? typingNote(message) : typingTrace(message);
+ SchedulerBinding.instance.addTimingsCallback(_frames);
+}
+
+/// Frames slower than one at 60 Hz while somebody types — on which thread the time went.
+void _frames(List<FrameTiming> timings) {
+ if (!_typing) return;
+ for (final timing in timings) {
+ final build = timing.buildDuration.inMicroseconds / 1000;
+ final raster = timing.rasterDuration.inMicroseconds / 1000;
+ if (build < 16 && raster < 16) continue;
+ _write(
+ 'frame SLOW build=${build.toStringAsFixed(1)}ms'
+ ' raster=${raster.toStringAsFixed(1)}ms'
+ ' total=${(timing.totalSpan.inMicroseconds / 1000).toStringAsFixed(1)}ms',
+ );
+ }
+}
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dart
index b945c32c2..aa185f6d1 100644
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart' show ValueListenable;
import 'package:flutter/material.dart';
import 'package:harness_mobile/logging/startup_trace.dart';
+import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -200,6 +201,9 @@ class _AgentHomeState extends State<AgentHome> {
final requested = widget.openAgent?.value;
// Null is the shell resetting before it writes, not a request.
if (requested == null) return;
+ if (kTypingTrace) {
+ typingEvent('switch: agent ${_shortId(requested.agentId)} asked for');
+ }
setState(() {
_welcome = false;
_requestedAgent = requested;
@@ -682,6 +686,7 @@ class _AgentHomeState extends State<AgentHome> {
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.notifier,
builder: (context, _) {
+ if (kTypingTrace) typingCount('home.build');
AppTheme.watch(context);
// Signed in from a scanned "Add phone" QR: once its computer is here and locked, pair with
// the QR's code — no password. See `welcome/connect_code.dart`.
@@ -803,6 +808,9 @@ class _AgentHomeState extends State<AgentHome> {
// (see [_target]) — not the agent on screen — so assigning it every build would quietly undo
// every swipe the pager reported, one frame after it reported it.
if (_neighboursFor != chosen) {
+ if (kTypingTrace) {
+ typingEvent('switch: pager built for ${_shortId(chosen.agentId)}');
+ }
_neighboursFor = chosen;
_neighbours = AgentSwipeList(group.entries);
_showing = chosen;
@@ -862,6 +870,9 @@ class _AgentHomeState extends State<AgentHome> {
/// Bumped whenever the pager is thrown away and rebuilt, and part of its key.
int _pagerGeneration = 0;
+ /// Enough of an agent id to tell agents apart in the typing trace.
+ static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;
+
/// The agent on screen was deleted while the pager's OPENING agent still exists: rebuild.
///
/// ⚠️ **The pager is keyed by the agent it opened on, so it survives anything short of that
diff --git a/mobile/lib/phone/daemon_scope.dart b/mobile/lib/phone/daemon_scope.dart
index 5feee7cf2..a2c6e06f8 100644
--- a/mobile/lib/phone/daemon_scope.dart
+++ b/mobile/lib/phone/daemon_scope.dart
@@ -5,6 +5,7 @@ import 'package:flutter/widgets.dart';
import 'package:harness_mobile/daemons/daemon_face.dart';
import 'package:harness_mobile/daemons/daemon_lines.dart';
import 'package:harness_mobile/daemons/zoo_client.dart';
+import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'agent_index.dart';
@@ -141,6 +142,7 @@ class DaemonHostState extends State<DaemonHost> with WidgetsBindingObserver {
void _sync() {
if (!mounted) return;
+ final took = kTypingTrace ? (Stopwatch()..start()) : null;
final seen = observeDaemon(
app,
onScreen: {for (final q in _onScreen.values) q.key: (who: q.who, q: q.q)},
@@ -152,6 +154,11 @@ class DaemonHostState extends State<DaemonHost> with WidgetsBindingObserver {
if (app.stateOf(machine.machineId)?.nodeOnline == true)
machine.machineId,
]);
+ if (took != null && took.elapsedMicroseconds >= 2000) {
+ typingEvent(
+ 'listener daemon: ${(took.elapsedMicroseconds / 1000).toStringAsFixed(1)}ms',
+ );
+ }
}
/// A terminal page read a question dialog off its own screen, or saw it go
diff --git a/mobile/lib/phone/phone_search_catalog.dart b/mobile/lib/phone/phone_search_catalog.dart
index 99bfa648a..d4be4f8af 100644
--- a/mobile/lib/phone/phone_search_catalog.dart
+++ b/mobile/lib/phone/phone_search_catalog.dart
@@ -29,6 +29,18 @@ String phoneAgentId(String machineId, String agentId) =>
/// the [MachineState] they hold, so `working` and `4m` stay current without the
/// catalog being rebuilt — and the ranking no longer depends on them at all.
class PhoneSearchCatalogCache {
+ /// The cache [notifier]'s search boxes share.
+ ///
+ /// ⚠️ **One per notifier, not one per box.** Find is opened and closed all day, and a cache
+ /// that lived and died with each box built the account's catalog afresh on every opening —
+ /// every agent's strings normalized, on the frame the sheet starts to slide up — for a fleet
+ /// that had not changed since the last time. Shared, an opening reads the catalog the last one
+ /// left, and rebuilds only what [read] finds changed. The rows are ranked against the live
+ /// state on every filter either way, as they always were while one box stayed open.
+ static PhoneSearchCatalogCache of(AppNotifier notifier) =>
+ _shared[notifier] ??= PhoneSearchCatalogCache();
+ static final _shared = Expando<PhoneSearchCatalogCache>();
+
List<Object?>? _presentation;
List<PhoneDestination> _entries = const [];
diff --git a/mobile/lib/phone/phone_search_controller.dart b/mobile/lib/phone/phone_search_controller.dart
index eb0f6bc09..3f1d7bb8f 100644
--- a/mobile/lib/phone/phone_search_controller.dart
+++ b/mobile/lib/phone/phone_search_controller.dart
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:harness_mobile/core/phone_search_history.dart';
+import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/external_session.dart';
import 'package:harness_mobile/state/search_when.dart';
@@ -44,6 +45,7 @@ class PhoneSearchController extends ChangeNotifier {
this.commands,
this.modes = true,
}) {
+ final built = kTypingTrace ? (Stopwatch()..start()) : null;
_catalog = _cache.read(notifier);
_content = SessionContentSearch(
machines: () => notifier.searchableMachineIds,
@@ -53,6 +55,12 @@ class PhoneSearchController extends ChangeNotifier {
_filter();
notifier.addListener(_rebuild);
notifier.sessionPreviews.addListener(_previewChanged);
+ if (built != null) {
+ typingEvent(
+ 'find search ready in ${built.elapsedMilliseconds}ms'
+ ' · ${_catalog.length} catalog rows, ${rows.length} shown',
+ );
+ }
}
final AppNotifier notifier;
@@ -72,7 +80,7 @@ class PhoneSearchController extends ChangeNotifier {
/// typed. The modes were the desktop's command palette carried over.
final bool modes;
- final _cache = PhoneSearchCatalogCache();
+ PhoneSearchCatalogCache get _cache => PhoneSearchCatalogCache.of(notifier);
/// What every machine's session index found for the query — see [contentHitFor].
late final SessionContentSearch _content;
@@ -302,15 +310,24 @@ class PhoneSearchController extends ChangeNotifier {
};
void _rebuild() {
+ final took = kTypingTrace ? (Stopwatch()..start()) : null;
final next = _cache.read(notifier);
// Nothing about the fleet changed shape, so the rows cannot have either —
// and re-ranking would hand the list a new set of objects to rebuild from
// for no reason. What the rows SAY still updates: they read their machine
// live, and the preview store has its own path in.
if (identical(next, _catalog)) return;
+ final catalogMs = took?.elapsedMicroseconds;
_catalog = next;
_filter();
_scheduleNotify();
+ if (took != null && took.elapsedMicroseconds >= 2000) {
+ typingEvent(
+ 'listener find: catalog ${(catalogMs! / 1000).toStringAsFixed(1)}ms,'
+ ' filter ${((took.elapsedMicroseconds - catalogMs) / 1000).toStringAsFixed(1)}ms'
+ ' · ${_catalog.length} rows, query "${matchQuery.length} chars"',
+ );
+ }
}
/// Content landing can add or remove a match, but must never shuffle the rows
diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dart
index 5ce98b191..2a2937436 100644
--- a/mobile/lib/phone/phone_search_results.dart
+++ b/mobile/lib/phone/phone_search_results.dart
@@ -52,8 +52,13 @@ class PhoneSearchResults extends StatefulWidget {
this.onOpen,
this.showing,
this.onNewHarness,
+ this.opening,
});
+ /// The sheet this list slides up in, while it does: the machines are reached once it is up
+ /// rather than during the slide. Null — a page of its own — reaches after the first frame.
+ final Animation<double>? opening;
+
/// Find's `+ New Harness` row — with a project's machine and folder when the query matched one
/// (`+ New Harness in api`). Null leaves the row out.
final void Function(({String machineId, String folder, String label})? place)?
@@ -143,8 +148,21 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
//
// ⚠️ After the frame, not in it: reaching can notify synchronously, and a notify while this
// list is being mounted marks the page above it dirty mid-build.
+ //
+ // ⚠️ **And not while the sheet is still sliding up.** Reaching releases the launch's held
+ // machines and dials every machine whose list is not current — a token, an end-to-end session
+ // and a socket each, all on this thread — and every answer redraws. Started on the first
+ // frame, that work landed in the middle of the slide, and the slide stuttered (frames of
+ // 300–900ms measured in a debug build, 2026-10-05). The rows already on screen are the lists
+ // the phone has; the reach only adds to them, a few hundred milliseconds later.
WidgetsBinding.instance.addPostFrameCallback((_) {
- if (mounted) unawaited(notifier.reachAllMachines());
+ if (!mounted) return;
+ final opening = widget.opening;
+ if (opening == null || opening.status == AnimationStatus.completed) {
+ unawaited(notifier.reachAllMachines());
+ return;
+ }
+ _opening = opening..addStatusListener(_reachOnceOpen);
});
// ⚠️ **No `agent_recent` reads from Find, not on open and not per row (owner, 2026-10-01).**
// Each row used to ask for its session's last words as it was built, so opening Find — or
@@ -154,6 +172,29 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
// the live events and from whatever the agents list read. See `AppNotifier.sessionPreviews`.
}
+ /// The sheet still sliding up, waited on before the machines are reached — see [initState].
+ Animation<double>? _opening;
+
+ /// Only `completed` ends the wait: a sheet dragged by a finger passes through every other
+ /// status on its way up, and one closed again before it was up takes this list — and the
+ /// listener, in [dispose] — down with it.
+ void _reachOnceOpen(AnimationStatus status) {
+ if (status != AnimationStatus.completed) return;
+ _stopWaiting();
+ if (mounted) unawaited(widget.notifier.reachAllMachines());
+ }
+
+ void _stopWaiting() {
+ _opening?.removeStatusListener(_reachOnceOpen);
+ _opening = null;
+ }
+
+ @override
+ void dispose() {
+ _stopWaiting();
+ super.dispose();
+ }
+
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: _changes,
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index bad03460d..75e1a6d5f 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -17,6 +17,7 @@ import 'package:flutter/semantics.dart'
import 'package:xterm/xterm.dart' show Terminal, TerminalKey, TerminalStyle;
import 'package:harness_mobile/logging/app_log.dart';
+import 'package:harness_mobile/logging/typing_trace.dart';
import 'package:harness_mobile/core/models.dart'
show Agent, AgentProject, ConnectionStatus;
import 'package:harness_mobile/shared/theme/app_theme.dart';
@@ -751,7 +752,14 @@ class _TerminalPageState extends State<TerminalPage>
/// session for themselves.
void _onNotifier() {
if (!mounted) return;
+ final took = kTypingTrace ? (Stopwatch()..start()) : null;
final facts = _readFacts();
+ if (took != null && took.elapsedMicroseconds >= 2000) {
+ typingEvent(
+ 'listener page: facts read in'
+ ' ${(took.elapsedMicroseconds / 1000).toStringAsFixed(1)}ms',
+ );
+ }
// The session has just started taking input: a question read before it
// could has its raise decided now. See [_raiseForQuestion].
final accepts = facts.session?.acceptsInput ?? false;
@@ -760,12 +768,14 @@ class _TerminalPageState extends State<TerminalPage>
if (accepts) _raiseForQuestion();
}
if (facts == _facts) return;
+ if (kTypingTrace) typingCount('page.rebuild(facts)');
setState(() => _facts = facts);
}
@override
void initState() {
super.initState();
+ if (kTypingTrace) typingEvent('switch: terminal page mounted');
WidgetsBinding.instance.addObserver(this);
_lifecycle =
WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;
@@ -1734,6 +1744,7 @@ class _TerminalPageState extends State<TerminalPage>
// against is what THIS build saw — see [_onNotifier]. Not the voice
// controller: what the mic hears repaints the floating mic and its pill,
// which listen for themselves, and never rebuilds the terminal under them.
+ if (kTypingTrace) typingCount('page.build');
_facts = _readFacts();
AppTheme.watch(context);
// Before anything is laid out: if the key bar is about to open or shut,
@@ -3492,6 +3503,7 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
/// it is compared first.
void _output() {
if (!mounted || _anchor() == _drawnFor) return;
+ if (kTypingTrace) typingCount('anchor.rebuild');
_changed();
}
diff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dart
index 2bec1d66e..f0401c865 100644
--- a/mobile/lib/phone/terminal_search.dart
+++ b/mobile/lib/phone/terminal_search.dart
@@ -520,6 +520,7 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay>
notifier: widget.notifier,
controller: _search,
showing: widget.showing,
+ opening: widget.animation,
onOpen: _close,
onNewHarness: newAgent == null
? null
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index b80353397..ca39e569c 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -34,6 +34,7 @@ import '../core/project_history.dart';
import '../core/retry.dart';
import '../logging/app_log.dart';
import '../logging/startup_trace.dart';
+import '../logging/typing_trace.dart';
import '../notify/agent_announcer.dart';
import '../notify/done_notice.dart';
import '../notify/system_notices.dart';
@@ -1756,6 +1757,7 @@ class AppNotifier extends ChangeNotifier {
unawaited(cliLogin.logout());
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
+ _relaySaid.clear();
_forgetLaunchHold();
// Tiles go, the saved layout stays: signing out and back in is the same
// person at the same desk, and the file is only read once machines exist.
@@ -2234,6 +2236,7 @@ class AppNotifier extends ChangeNotifier {
if (machine.terminalCapabilityUnanswered) {
unawaited(_loadTerminalCapabilities(machine, connection, revision));
}
+ final handling = kTypingTrace ? (Stopwatch()..start()) : null;
final rawAgents = response['agents'] as List<dynamic>? ?? const [];
final agents = rawAgents
.map((item) => Agent.fromJson(item as Map<String, dynamic>))
@@ -2244,7 +2247,15 @@ class AppNotifier extends ChangeNotifier {
!machine.agentsFromCache) {
machine.agentsListedAt = DateTime.now();
}
- if (agentsEqual(machine.agents, agents)) return;
+ if (agentsEqual(machine.agents, agents)) {
+ if (handling != null) {
+ typingEvent(
+ 'agents sync: ${agents.length} unchanged · parsed and compared on this'
+ ' thread in ${handling.elapsedMilliseconds}ms',
+ );
+ }
+ return;
+ }
// The machine's own list for the next launch too: what changed reached this phone without a
// push (one sent while the socket was away). A harness added or gone goes out soon, the rest
// with the app leaving the screen — see [_saveMachineCacheSoon].
@@ -2262,6 +2273,12 @@ class AppNotifier extends ChangeNotifier {
}
_replaceAgents(machine, agents);
notifyListeners();
+ if (handling != null) {
+ typingEvent(
+ 'agents sync: ${agents.length} changed · parsed, replaced and redrawn on'
+ ' this thread in ${handling.elapsedMilliseconds}ms',
+ );
+ }
} on WsRequestTimeout {
if (!_machineWorkCurrent(machine, revision)) return;
final missed = (_agentSyncTimeouts[machineId] ?? 0) + 1;
@@ -4430,10 +4447,12 @@ class AppNotifier extends ChangeNotifier {
return true;
}
- void _renameAgent(MachineState machine, String agentId, String name) {
+ /// False when it changed nothing — no such agent, no name, or the name it already has.
+ bool _renameAgent(MachineState machine, String agentId, String name) {
final index = machine.agents.indexWhere((agent) => agent.id == agentId);
- if (index == -1 || name.trim().isEmpty) return;
+ if (index == -1 || name.trim().isEmpty) return false;
final cleanName = name.trim();
+ if (machine.agents[index].name == cleanName) return false;
machine.agents = [...machine.agents]
..[index] = machine.agents[index].copyWith(name: cleanName);
// Written with the rest when the app leaves the screen — see [_keepMachineCache].
@@ -4442,6 +4461,7 @@ class AppNotifier extends ChangeNotifier {
if (pane.agentId != agentId) continue;
pane.session?.renameAgent(cleanName);
}
+ return true;
}
Future<void> _removeAgent(MachineState machine, String agentId) async {
@@ -4669,6 +4689,7 @@ class AppNotifier extends ChangeNotifier {
// The same guard [_canFetchPreview] uses, and for the same reason: `_conn`
// would build one out of a null pool.
if (_disposed || (_pool == null && connectionForTest == null)) return;
+ final reaching = kTypingTrace ? (Stopwatch()..start()) : null;
// Somebody is looking for a session, on any machine: the launch's hold is over — see
// [_launchMachineId]. Before the reloads below, so the held ones dial with the rest.
_releaseHeldMachines('search opened', atOnce: true);
@@ -4676,12 +4697,19 @@ class AppNotifier extends ChangeNotifier {
final asking = <String>[];
var current = 0;
var locked = 0;
+ var off = 0;
for (final machine in machines) {
final state = machineStates[machine.machineId];
if (state != null && state.needsLink) {
locked++;
} else if (state != null && _listStillCurrent(state, now)) {
current++;
+ } else if (_relaySaysOffline(machine.machineId, now)) {
+ // ⚠️ **Not dialled: the relay has just said it is off**, and a dial would only hear that
+ // again — a token, an end-to-end session and a socket for each, all on this thread while
+ // Find draws itself (four of them measured under a 936ms frame, 2026-10-05). Its list
+ // stays the one the phone has; once the relay says it is back, the next Find asks it.
+ off++;
} else {
asking.add(machine.machineId);
}
@@ -4689,11 +4717,18 @@ class AppNotifier extends ChangeNotifier {
appLog.info(
'search',
'Find asks ${asking.length} machine(s) for their lists · '
- '$current current already, $locked waiting for a password',
+ '$current current already, $locked waiting for a password, $off offline',
);
- await Future.wait([
+ final reloads = Future.wait([
for (final machineId in asking) reloadMachineData(machineId),
]);
+ if (reaching != null) {
+ typingEvent(
+ 'find reach: ${asking.length} asked, $off offline skipped'
+ ' — ${reaching.elapsedMilliseconds}ms on this thread before the replies',
+ );
+ }
+ await reloads;
}
/// Whether [state]'s list was answered over the socket it is on now, recently enough that the
@@ -6110,14 +6145,33 @@ class AppNotifier extends ChangeNotifier {
/// everything would change what every machine's row says on a feed nothing here was built on.
void _wakeMachinesBackOnline(Object? statuses) {
if (statuses is! List) return;
+ final now = DateTime.now();
for (final status in statuses) {
- if (status is! Map || status['online'] != true) continue;
+ if (status is! Map) continue;
final machineId = status['machineId'];
if (machineId is! String || machineId.isEmpty) continue;
- _pool?[machineId]?.wake('the relay says it is online');
+ final online = status['online'] == true;
+ _relaySaid[machineId] = (online: online, at: now);
+ if (online) _pool?[machineId]?.wake('the relay says it is online');
}
}
+ /// What `machines_status` last said of each machine, and when — read by [reachAllMachines], and
+ /// by nothing else (see [_wakeMachinesBackOnline] for why it is not the machine's status).
+ final Map<String, ({bool online, DateTime at})> _relaySaid = {};
+
+ /// How long the relay's "offline" stands for [reachAllMachines]. It says so again as it changes,
+ /// so this is only the bound on trusting a word that may have gone unrepeated.
+ static const _relayOfflineStands = Duration(minutes: 2);
+
+ /// Whether the relay said, a moment ago, that [machineId] is off — so there is nothing to dial.
+ bool _relaySaysOffline(String machineId, DateTime now) {
+ final said = _relaySaid[machineId];
+ return said != null &&
+ !said.online &&
+ now.difference(said.at) < _relayOfflineStands;
+ }
+
Future<void> _recoverPendingAgent(
MachineState machine,
String agentId,
@@ -6563,6 +6617,7 @@ class AppNotifier extends ChangeNotifier {
if (_disposed || !allPanes.contains(pane) || pane.session != null) return;
final wantedAgentId = pane.agentId;
if (wantedAgentId == null) return;
+ if (kTypingTrace) typingEvent('switch: attaching a session to the pane');
final machine = machineStates[pane.machineId];
if (machine == null) return;
if (machine.nodeOnline == false) return;
@@ -7267,7 +7322,10 @@ class AppNotifier extends ChangeNotifier {
final agentId = _eventAgentId(machine, event, payload);
final name = payload['name'];
if (agentId != null && name is String) {
- _renameAgent(machine, agentId, name);
+ // ⚠️ **No redraw for a name it already has.** A machine coming back online re-sends
+ // `agent_renamed` for every agent it holds — eighty in one second, measured — and each
+ // one redrew every screen.
+ if (!_renameAgent(machine, agentId, name)) return;
} else {
unawaited(_loadMachineData(machine, force: true));
}
@@ -7456,7 +7514,19 @@ class AppNotifier extends ChangeNotifier {
@override
void notifyListeners() {
_seeWatchedAgent();
+ if (!kTypingTrace) {
+ super.notifyListeners();
+ return;
+ }
+ typingCount('app.notify');
+ // What every listener does with the tick, right here on this thread — the builds come later,
+ // in the frame (`frame SLOW`).
+ final listening = Stopwatch()..start();
super.notifyListeners();
+ final took = listening.elapsedMicroseconds / 1000;
+ if (took >= 4) {
+ typingEvent('notify: listeners took ${took.toStringAsFixed(1)}ms');
+ }
}
/// [agent] on [machine], as a notice names it.
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 5a5544866..e5c6c086f 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -4,9 +4,11 @@ import 'dart:io';
import 'dart:math';
import 'package:flutter/foundation.dart';
+import 'package:xterm/utils.dart' show traceText;
import 'package:xterm/xterm.dart';
import '../core/crash_log.dart';
+import '../logging/typing_trace.dart';
import 'control_chord.dart';
import 'keyframe_write.dart';
import 'screen_snapshot.dart';
@@ -263,6 +265,27 @@ class TerminalSession extends ChangeNotifier {
String? _openRequestId;
int? _expectedSeq;
+ /// For the typing trace (`typing_trace.dart`, off unless built in): when input last went out, on
+ /// the trace clock, for an echo's latency; and the status last traced.
+ int _lastInputSentMs = -1 << 30;
+ TerminalSessionStatus? _tracedStatus;
+
+ /// For the typing trace: input sends queued and not finished, and when the last one finished.
+ int _sendsInFlight = 0;
+ int _sendsIdleSinceMs = 0;
+
+ @override
+ void notifyListeners() {
+ if (kTypingTrace && status != _tracedStatus) {
+ typingEvent(
+ 'session ${_tracedStatus?.name ?? '-'} → ${status.name}'
+ '${errorCode == null ? '' : ' ($errorCode)'}',
+ );
+ _tracedStatus = status;
+ }
+ super.notifyListeners();
+ }
+
/// Frames dropped in a row as already drawn — see [_alreadyDrawn].
int _staleInARow = 0;
@@ -342,6 +365,16 @@ class TerminalSession extends ChangeNotifier {
/// or frames accepted since would be re-sent under numbers already used.
int? _lastRealignedTo;
int _resizeSeq = 0;
+
+ /// The size the last `terminal_resize` asked for, and when — until a keyframe of that size
+ /// answers it. See [_answerOnItsWay].
+ ({int cols, int rows, DateTime at})? _resizeAsked;
+
+ /// Asks for the size again if the keyframe [_answerOnItsWay] waited for never came.
+ Timer? _resizeAnswerTimer;
+
+ /// How long a resize's own keyframe may take before a keyframe of another size is believed.
+ static const _resizeAnswerWait = Duration(milliseconds: 1500);
bool _resyncRequested = false;
int _resyncAttempts = 0;
int _autoReopenAttempts = 0;
@@ -491,6 +524,7 @@ class TerminalSession extends ChangeNotifier {
_inputSeq = 0;
_lastRealignedTo = null;
_resizeSeq = 0;
+ _resizeAsked = null;
_utf8Tail = const [];
_remoteCursorVisible = true;
_cursorBlinkPhaseVisible = true;
@@ -945,6 +979,12 @@ class TerminalSession extends ChangeNotifier {
return;
}
if (frame.kind == TerminalBinaryKind.keyframe) {
+ if (kTypingTrace) {
+ typingEvent(
+ 'out KEYFRAME seq=${frame.seq} ${frame.cols}×${frame.rows}'
+ ' ${bytes.length}B (status=${status.name}) — replaces the terminal',
+ );
+ }
await _applyKeyframe(frame, bytes, generation);
return;
}
@@ -962,13 +1002,38 @@ class TerminalSession extends ChangeNotifier {
}
if (frame.kind != TerminalBinaryKind.output ||
status == TerminalSessionStatus.resyncing) {
+ if (kTypingTrace && frame.kind == TerminalBinaryKind.output) {
+ typingEvent(
+ 'out seq=${frame.seq} ${bytes.length}B DROPPED — resyncing',
+ );
+ }
+ return;
+ }
+ if (_alreadyDrawn(frame)) {
+ if (kTypingTrace) {
+ typingEvent(
+ 'out seq=${frame.seq} ${bytes.length}B DROPPED — already drawn'
+ ' (expected $_expectedSeq)',
+ );
+ }
return;
}
- if (_alreadyDrawn(frame)) return;
if (_expectedSeq == null || frame.seq != _expectedSeq) {
+ if (kTypingTrace) {
+ typingEvent(
+ 'out seq=${frame.seq} GAP (expected $_expectedSeq) → resync',
+ );
+ }
await _requestResync('TERMINAL_SEQUENCE_GAP');
return;
}
+ if (kTypingTrace) {
+ final since = typingNowMs() - _lastInputSentMs;
+ typingNote(
+ 'out seq=${frame.seq} ${bytes.length}B'
+ '${since < 5000 ? ' +${since}ms after the last send' : ''}',
+ );
+ }
if (!_writeBytes(bytes)) {
await _requestResync('TERMINAL_OUTPUT_DECODE_FAILED');
return;
@@ -1184,11 +1249,76 @@ class TerminalSession extends ChangeNotifier {
_pendingCols = measured.cols;
_pendingRows = measured.rows;
}
+ // Asked first, and always: a keyframe that answers the resize out is what clears it.
+ if (_answerOnItsWay()) return;
if (_pendingCols != null && _pendingRows != null) {
unawaited(_flushResize());
}
}
+ /// Whether the keyframe just drawn predates the resize still out — the size it asked for is still
+ /// the one wanted, and that resize's own keyframe is on its way ([_resizeStillComing]).
+ ///
+ /// ⚠️ **Not asked again, which is what this used to do.** The machine answers a resize with a
+ /// keyframe, but one it had already put on the wire at the OLD size lands first. Read as the
+ /// size having slipped, it sent the same resize again — and got a third keyframe for it. Every
+ /// keyboard raised was measured at three keyframes and two resizes (2026-10-05): three times the
+ /// emulator replaced and the screen parsed and drawn whole, the keyboard's buffer emptied each
+ /// time, right as somebody starts typing.
+ bool _answerOnItsWay() {
+ final asked = _resizeAsked;
+ if (asked == null) return false;
+ if (asked.cols == cols && asked.rows == rows) {
+ // This keyframe IS the answer.
+ _resizeAsked = null;
+ _resizeAnswerTimer?.cancel();
+ _resizeAnswerTimer = null;
+ return false;
+ }
+ final pendingCols = _pendingCols, pendingRows = _pendingRows;
+ if (pendingCols == null ||
+ pendingRows == null ||
+ !_resizeStillComing(pendingCols, pendingRows)) {
+ return false;
+ }
+ if (kTypingTrace) {
+ typingEvent(
+ 'resize: keyframe ${cols}x$rows predates the ${asked.cols}x${asked.rows}'
+ ' still coming — not asked again',
+ );
+ }
+ _pendingCols = null;
+ _pendingRows = null;
+ return true;
+ }
+
+ /// Whether a resize to [nextCols]×[nextRows] is out already and its keyframe not overdue — and so
+ /// not to be asked for again ([_answerOnItsWay]; and in [_flushResize], for the emulator laid out
+ /// at a stale keyframe's size resizing itself back). Held for [_resizeAnswerWait] at most: an
+ /// answer that never comes is asked for again then.
+ bool _resizeStillComing(int nextCols, int nextRows) {
+ final asked = _resizeAsked;
+ if (asked == null || asked.cols != nextCols || asked.rows != nextRows) {
+ return false;
+ }
+ final waited = DateTime.now().difference(asked.at);
+ if (waited >= _resizeAnswerWait) return false;
+ if (_resizeAnswerTimer == null) {
+ final generation = _generation;
+ _resizeAnswerTimer = Timer(_resizeAnswerWait - waited, () {
+ _resizeAnswerTimer = null;
+ if (!_isCurrent(generation) || _resizeAsked == null) return;
+ _resizeAsked = null;
+ final measured = _measuredViewport;
+ if (measured == null) return;
+ _pendingCols = measured.cols;
+ _pendingRows = measured.rows;
+ unawaited(_flushResize());
+ });
+ }
+ return true;
+ }
+
List<int> _prepareKeyframeBytes(Uint8List bytes) {
if (engineId != 'grok') return bytes;
@@ -1478,6 +1608,14 @@ class TerminalSession extends ChangeNotifier {
}
void _onTerminalOutput(String data) {
+ if (kTypingTrace && data.isNotEmpty) {
+ typingTrace(
+ acceptsInput
+ ? 'pty in "${traceText(data)}"'
+ : 'pty in DROPPED — not taking input (status=${status.name}'
+ ' stream=${streamId != null} watching=$watching) "${traceText(data)}"',
+ );
+ }
if (!acceptsInput || data.isEmpty) return;
data = _spendArmedControl(data);
final origin = _swarmInput ? inputTabId : null;
@@ -1525,6 +1663,12 @@ class TerminalSession extends ChangeNotifier {
_inputTimer?.cancel();
_inputTimer = null;
if (!acceptsInput || _inputBytes.isEmpty) {
+ if (kTypingTrace && _inputBytes.isNotEmpty) {
+ typingTrace(
+ 'pty flush DROPPED ${_inputBytes.length}B — not taking input'
+ ' (status=${status.name})',
+ );
+ }
_inputBytes.clear();
return;
}
@@ -1533,14 +1677,36 @@ class TerminalSession extends ChangeNotifier {
_inputBytes.clear();
_lastInputFlushAt = DateTime.now();
final currentStreamId = streamId;
- if (currentStreamId == null) return;
+ if (currentStreamId == null) {
+ if (kTypingTrace) {
+ typingTrace('pty flush DROPPED ${bytes.length}B — no stream');
+ }
+ return;
+ }
final generation = _generation;
+ final flushedAt = kTypingTrace ? typingNowMs() : 0;
+ final queuedBehind = _sendsInFlight;
+ final idleFor = typingNowMs() - _sendsIdleSinceMs;
+ if (kTypingTrace) _sendsInFlight++;
final queued = _inputSendTail.then((_) async {
if (!_isCurrent(generation) ||
!acceptsInput ||
streamId != currentStreamId) {
+ if (kTypingTrace) {
+ typingTrace(
+ 'pty send DROPPED ${bytes.length}B — the stream moved on while it'
+ ' queued (status=${status.name})',
+ );
+ }
return;
}
+ if (kTypingTrace && typingNowMs() - flushedAt >= 3) {
+ typingTrace(
+ 'pty send waited ${typingNowMs() - flushedAt}ms — $queuedBehind send(s)'
+ ' were in flight when it was queued'
+ '${queuedBehind == 0 ? ', the line idle for ${idleFor}ms' : ''}',
+ );
+ }
// Numbered HERE, on the tail, not when the flush was asked for. A frame
// the guard above drops — the session went `resyncing` while an earlier
// send was still in flight — must not consume a seq: the daemon wants
@@ -1570,7 +1736,15 @@ class TerminalSession extends ChangeNotifier {
bytes: Uint8List.fromList(bytes.sublist(offset, end)),
compressed: false,
);
+ final sendStarted = kTypingTrace ? typingNowMs() : 0;
final sent = await sendBinary(frame);
+ if (kTypingTrace) {
+ _lastInputSentMs = typingNowMs();
+ typingTrace(
+ 'pty sent seq=${frame.seq} ${frame.bytes.length}B ok=$sent'
+ ' in ${typingNowMs() - sendStarted}ms via=${linkMode ?? '?'}',
+ );
+ }
if (!_isCurrent(generation)) return;
if (!sent) {
transportLost('Terminal input was not sent');
@@ -1578,9 +1752,17 @@ class TerminalSession extends ChangeNotifier {
}
}
});
- _inputSendTail = queued.catchError((_) {
- if (_isCurrent(generation)) transportLost('Terminal input was not sent');
- });
+ _inputSendTail = queued
+ .catchError((_) {
+ if (_isCurrent(generation)) {
+ transportLost('Terminal input was not sent');
+ }
+ })
+ .whenComplete(() {
+ if (!kTypingTrace) return;
+ _sendsInFlight--;
+ _sendsIdleSinceMs = typingNowMs();
+ });
await _inputSendTail;
}
@@ -1637,10 +1819,13 @@ class TerminalSession extends ChangeNotifier {
_pendingCols = null;
_pendingRows = null;
if (nextCols == cols && nextRows == rows) return;
+ if (_resizeStillComing(nextCols, nextRows)) return;
cols = nextCols;
rows = nextRows;
_lastResizeFlushAt = DateTime.now();
+ _resizeAsked = (cols: cols, rows: rows, at: _lastResizeFlushAt!);
final generation = _generation;
+ if (kTypingTrace) typingEvent('resize → $cols×$rows');
final sent = await send('terminal_resize', {
'streamId': streamId,
'resizeSeq': _resizeSeq++,
@@ -1731,6 +1916,12 @@ class TerminalSession extends ChangeNotifier {
}
Future<void> _requestResync(String reason) async {
+ if (kTypingTrace) {
+ typingEvent(
+ 'RESYNC asked: $reason (status=${status.name}'
+ ' pending input ${_inputBytes.length}B dropped)',
+ );
+ }
if (streamId == null) {
_fail(reason, null);
return;
@@ -1959,6 +2150,8 @@ class TerminalSession extends ChangeNotifier {
_inputTimer = null;
_resizeTimer?.cancel();
_resizeTimer = null;
+ _resizeAnswerTimer?.cancel();
+ _resizeAnswerTimer = null;
_resyncTimer?.cancel();
_resyncTimer = null;
_scrollTimer?.cancel();
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index a87494dc9..16aa29fb6 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -10,6 +10,7 @@ import 'package:flutter/services.dart';
import 'package:xterm/xterm.dart';
import '../clipboard/native_clipboard.dart';
+import '../logging/typing_trace.dart';
import '../state/app_state.dart';
import '../terminal/terminal_snapshot.dart';
@@ -460,6 +461,7 @@ class _TerminalPanelState extends State<TerminalPanel>
void _syncTerminal(Terminal terminal) {
if (identical(_viewTerminal, terminal)) return;
+ if (kTypingTrace) typingEvent('panel view → the new terminal');
final previous = _viewTerminal.buffer;
final next = terminal.buffer;
@@ -528,6 +530,7 @@ class _TerminalPanelState extends State<TerminalPanel>
}
void _handleFocusChange() {
+ if (kTypingTrace) typingEvent('panel focus=${_focusNode.hasFocus}');
if (_focusNode.hasFocus) widget.session.inputTabId = widget.tabId;
_syncCursorBlink();
}
@@ -545,6 +548,9 @@ class _TerminalPanelState extends State<TerminalPanel>
(!navigating && (!widget.focused || !widget.visible))) {
return false;
}
+ if (kTypingTrace) {
+ typingEvent('panel claims the keyboard (navigating=$navigating)');
+ }
view.requestKeyboard();
return true;
}
@@ -1570,6 +1576,7 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
Widget build(BuildContext context) {
+ if (kTypingTrace) typingCount('panel.build');
grid.AppTheme.watch(context);
final session = widget.session;
_syncTerminal(session.terminal);
@@ -1616,6 +1623,16 @@ class _TerminalPanelState extends State<TerminalPanel>
// (cb47ba35 → TestFlight build 11), which is why
// test/terminal_panel_backspace_test.dart pins it.
deleteDetection: true,
+ // This view is only ever handed the next screen of its
+ // own session — a keyframe — since another session gets
+ // a view of its own (a fresh `_terminalViewKey`): what
+ // the keyboard holds is still the line being typed.
+ keepsInputAcrossTerminals: true,
+ // What is typed shows at once, ahead of the machine's echo a
+ // round trip away (owner's call, 2026-10-05) — only once this
+ // terminal has been seen echoing, so a password prompt
+ // shows nothing. See xterm's `TerminalView.predictsEcho`.
+ predictsEcho: true,
theme: terminalScreenThemeFor(
grid.AppTheme.palette.value,
terminalThemeStore.value,
diff --git a/mobile/third_party/xterm/lib/src/terminal_view.dart b/mobile/third_party/xterm/lib/src/terminal_view.dart
index c6a7904f6..2f212f49e 100644
--- a/mobile/third_party/xterm/lib/src/terminal_view.dart
+++ b/mobile/third_party/xterm/lib/src/terminal_view.dart
@@ -21,6 +21,10 @@ import 'package:xterm/src/ui/shortcut/shortcuts.dart';
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 'package:xterm/src/utils/input_trace.dart';
+import 'package:xterm/src/utils/unicode_v11.dart';
class TerminalView extends StatefulWidget {
const TerminalView(
@@ -61,6 +65,8 @@ class TerminalView extends StatefulWidget {
this.altBufferScrollPaced = false,
this.altBufferScrollAnimated = false,
this.onAltBufferScrollShift,
+ this.keepsInputAcrossTerminals = false,
+ this.predictsEcho = false,
});
/// The underlying terminal that this widget renders.
@@ -214,6 +220,26 @@ class TerminalView extends StatefulWidget {
/// as a scroll and jumped. For measuring; nothing depends on it.
final void Function(int rows)? onAltBufferScrollShift;
+ /// AUTONOMOUS PATCH: the keyboard's buffer — and what it is composing — is
+ /// kept when [terminal] is replaced, for an embedder that replaces it only
+ /// with the next screen of the SAME stream (a keyframe), and gives another
+ /// stream a view of its own.
+ ///
+ /// ⚠️ Emptied there, it was emptied under somebody typing: every keyframe —
+ /// one ends each keyboard raised — reset the buffer while the keyboard could
+ /// still have an edit on its way, which was then read against the emptied
+ /// buffer and typed what was already typed a second time. False keeps
+ /// upstream's reset, for a view that is handed another stream's terminal.
+ final bool keepsInputAcrossTerminals;
+
+ /// AUTONOMOUS PATCH: what is typed is drawn at the cursor at once, faint,
+ /// until the terminal's own echo of it arrives — a remote program's echo is a
+ /// round trip away, 50–120ms measured on a phone, and the keys look dead until
+ /// then. Drawn over the screen only: nothing is written to the emulator and
+ /// nothing extra is sent. See [TerminalViewState._predictEcho] for when a key
+ /// is predicted at all.
+ final bool predictsEcho;
+
@override
State<TerminalView> createState() => TerminalViewState();
}
@@ -233,6 +259,30 @@ class TerminalViewState extends State<TerminalView> {
int _composingBacktrackCells = 0;
+ // ── AUTONOMOUS PATCH: local echo — see [TerminalView.predictsEcho] ──────────
+
+ /// What is drawn ahead of the echo: typed, sent, not yet echoed.
+ String _predicted = '';
+
+ /// 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;
+
+ /// Where the cursor rested after the last echo: the input point. A key typed
+ /// with the cursor anywhere else — a program mid-redraw, output streaming —
+ /// is not predicted, since the echo will not land at the cursor.
+ ({int x, int y})? _inputPoint;
+
+ /// Whether this terminal has been seen to echo what is typed. Off at first,
+ /// and off again after a key whose echo never came (a password prompt): only
+ /// a key seen echoed turns prediction back on.
+ bool _echoes = false;
+
+ Timer? _echoTimeout;
+
+ /// How long a key's echo may take before it is taken not to be coming.
+ static const _echoWait = Duration(milliseconds: 400);
+
late TerminalController _controller;
late ScrollController _scrollController;
@@ -262,18 +312,27 @@ class TerminalViewState extends State<TerminalView> {
@override
void didUpdateWidget(TerminalView oldWidget) {
if (!identical(oldWidget.terminal, widget.terminal)) {
+ inputTrace(
+ () => 'view terminal SWAPPED (composing "${_composingText ?? ''}")'
+ '${widget.keepsInputAcrossTerminals ? ' → input kept' : ' → IME reset after frame'}',
+ );
oldWidget.terminal.removeListener(_onTerminalChanged);
widget.terminal.addListener(_onTerminalChanged);
- // A marked string is owned by the old native input session. TerminalView
- // states are reused while switching agents, so never carry that overlay
- // or editing buffer into the newly selected terminal.
- _composingText = null;
- _composingBacktrackCells = 0;
- final currentTerminal = widget.terminal;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- if (!mounted || !identical(widget.terminal, currentTerminal)) return;
- _customTextEditKey.currentState?.resetEditingState();
- });
+ // A new screen: nothing predicted on the old one is where it was drawn.
+ _dropPrediction();
+ _inputPoint = null;
+ if (!widget.keepsInputAcrossTerminals) {
+ // A marked string is owned by the old native input session. TerminalView
+ // states are reused while switching agents, so never carry that overlay
+ // or editing buffer into the newly selected terminal.
+ _composingText = null;
+ _composingBacktrackCells = 0;
+ final currentTerminal = widget.terminal;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted || !identical(widget.terminal, currentTerminal)) return;
+ _customTextEditKey.currentState?.resetEditingState();
+ });
+ }
}
if (oldWidget.focusNode != widget.focusNode) {
if (oldWidget.focusNode == null) {
@@ -299,6 +358,7 @@ class TerminalViewState extends State<TerminalView> {
@override
void dispose() {
+ _echoTimeout?.cancel();
widget.terminal.removeListener(_onTerminalChanged);
if (widget.focusNode == null) {
_focusNode.dispose();
@@ -368,6 +428,8 @@ class TerminalViewState extends State<TerminalView> {
onContentInserted: widget.onContentInserted,
onInsert: _onInsert,
onDelete: (count) {
+ inputTrace(() => 'view delete ×$count');
+ _restartPrediction();
_scrollToBottom();
for (var index = 0; index < count; index++) {
widget.terminal.keyInput(TerminalKey.backspace);
@@ -375,6 +437,7 @@ class TerminalViewState extends State<TerminalView> {
},
onComposing: _onComposing,
onAction: (action) {
+ _restartPrediction();
_scrollToBottom();
if (action == TextInputAction.done ||
action == TextInputAction.newline) {
@@ -516,15 +579,24 @@ class TerminalViewState extends State<TerminalView> {
// generate hardware key events. So we need first try to send the key
// as a hardware key event. If it fails, then we send it as a text input.
final consumed = key == null ? false : widget.terminal.keyInput(key);
+ inputTrace(
+ () =>
+ 'view insert "${traceText(text)}" as ${consumed ? 'key $key' : 'text'}',
+ );
if (!consumed) {
widget.terminal.textInput(text);
+ _predictEcho(text);
+ } else {
+ _restartPrediction();
}
_scrollToBottom();
}
void _onComposing(String? text, int backtrackCells) {
+ // A pre-edit is drawn at the cursor too, and owns it while it lasts.
+ if (text != null) _dropPrediction();
if (text != null && _terminalAlreadyEchoes(text)) {
text = null;
backtrackCells = 0;
@@ -553,6 +625,7 @@ class TerminalViewState extends State<TerminalView> {
}
void _onTerminalChanged() {
+ if (mounted) _followEcho();
final text = _composingText;
if (!mounted || text == null || !_terminalAlreadyEchoes(text)) return;
setState(() {
@@ -561,6 +634,146 @@ class TerminalViewState extends State<TerminalView> {
});
}
+ /// AUTONOMOUS PATCH: [text] just went to the terminal — drawn at the cursor
+ /// ahead of its echo, when one is expected there. See [TerminalView.predictsEcho].
+ ///
+ /// ⚠️ **Only where the echo will land, and only once one has been seen.**
+ /// Every key is a probe ([_echoFrom]): its echo arriving — the cursor moving
+ /// on along its line — is what turns prediction on ([_echoes]), and a key
+ /// whose echo never comes ([_echoWait]) turns it off, which is what keeps a
+ /// password prompt from showing what is typed into it. And a key is drawn
+ /// only with the cursor resting where the last echo left it ([_inputPoint]):
+ /// a program redrawing or streaming output moves the cursor about, and a
+ /// guess drawn there would be drawn in the wrong place.
+ void _predictEcho(String text) {
+ if (!widget.predictsEcho) return;
+ if (!_echoable(text) || _composingText != null) {
+ _dropPrediction();
+ return;
+ }
+ final now = _cursorMark();
+ _echoFrom ??= now;
+ final at = _inputPoint;
+ if (_echoes &&
+ at != null &&
+ at.x == now.x &&
+ at.y == now.y &&
+ now.x + _cells(_predicted + text) <= widget.terminal.viewWidth) {
+ _setPredicted(_predicted + text);
+ 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})',
+ );
+ }
+ _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.
+ 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 (now.y == from.y && now.x > from.x) {
+ _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;
+ } else {
+ _echoFrom = now;
+ }
+ return;
+ }
+ // The cursor went elsewhere, or its line was redrawn without it moving on:
+ // the screen is the truth now.
+ _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.
+ void _echoNeverCame() {
+ inputTrace(
+ () => 'echo never came within ${_echoWait.inMilliseconds}ms — off');
+ _echoTimeout = null;
+ _echoes = false;
+ _dropPrediction();
+ }
+
+ /// 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
+ /// it. A Telex word arrives as deletes and the word retyped, and drawn at once
+ /// the new word sat after the old one until the deletes were echoed; and
+ /// after Enter the cursor may be at a password prompt.
+ void _restartPrediction() {
+ _dropPrediction();
+ _inputPoint = null;
+ }
+
+ void _dropPrediction() {
+ _echoTimeout?.cancel();
+ _echoTimeout = null;
+ _echoFrom = null;
+ if (_predicted.isNotEmpty) _setPredicted('');
+ }
+
+ void _setPredicted(String text) {
+ _predicted = text;
+ final render = _viewportKey.currentContext?.findRenderObject();
+ if (render is RenderTerminal) render.predictedText = text;
+ }
+
+ ({int x, int y, int version}) _cursorMark() {
+ final buffer = widget.terminal.buffer;
+ final y = buffer.absoluteCursorY;
+ final lines = buffer.lines;
+ final version = y >= 0 && y < lines.length ? lines[y].paintVersion : -1;
+ return (x: buffer.cursorX, y: y, version: version);
+ }
+
+ /// Whether a terminal echoes [text] as it is: printable characters taking a
+ /// cell or two each.
+ static bool _echoable(String text) {
+ if (text.isEmpty) return false;
+ for (final rune in text.runes) {
+ if (rune < 0x20 || rune == 0x7f || unicodeV11.wcwidth(rune) <= 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ static int _cells(String text) {
+ var cells = 0;
+ for (final rune in text.runes) {
+ final width = unicodeV11.wcwidth(rune);
+ if (width > 0) cells += width;
+ }
+ return cells;
+ }
+
+ /// [text] without the characters filling its first [cells] cells.
+ static String _afterCells(String text, int cells) {
+ var used = 0;
+ var index = 0;
+ final runes = text.runes.toList();
+ while (index < runes.length && used < cells) {
+ final width = unicodeV11.wcwidth(runes[index]);
+ used += width > 0 ? width : 0;
+ index++;
+ }
+ return String.fromCharCodes(runes.skip(index));
+ }
+
@visibleForTesting
String? get debugComposingText => _composingText;
@@ -683,6 +896,7 @@ class TerminalViewState extends State<TerminalView> {
);
if (handled) {
+ _restartPrediction();
_scrollToBottom();
if (key == TerminalKey.enter) {
_customTextEditKey.currentState?.resetEditingState();
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 72cfca79d..5f4ca118a 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
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
+import 'package:xterm/src/utils/input_trace.dart';
import 'package:xterm/src/utils/unicode_v11.dart';
class CustomTextEdit extends StatefulWidget {
@@ -135,6 +136,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
}
void setEditingState(TextEditingValue value) {
+ inputTrace(() => 'ime set by embedder "${traceText(value.text)}"');
_settleRewrite();
_cancelPendingDeletes();
_currentEditingState = value;
@@ -146,6 +148,13 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
/// It intentionally stays intact between ordinary key presses: Vietnamese
/// Telex needs the preceding `u` available to convert it into `ư`.
void resetEditingState() {
+ if (xtermInputTrace != null) {
+ final from = traceCaller();
+ inputTrace(
+ () =>
+ 'ime RESET buffer (had "${traceText(_currentEditingState.text)}") ← $from',
+ );
+ }
// What the keyboard was rewriting reaches the terminal before the buffer is emptied under it.
_settleRewrite();
_cancelPendingDeletes();
@@ -174,6 +183,10 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) {
_settleRewrite();
+ inputTrace(
+ () => 'key ${event.runtimeType} ${event.logicalKey.keyLabel}'
+ ' composing=${!_currentEditingState.composing.isCollapsed}',
+ );
if (_currentEditingState.composing.isCollapsed) {
if (_isBufferBackspace(event)) {
_cancelPendingDeletes();
@@ -217,6 +230,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
}
void _openOrCloseInputConnectionIfNeeded() {
+ inputTrace(() => 'ime focus=${widget.focusNode.hasFocus}');
if (widget.focusNode.hasFocus && widget.focusNode.consumeKeyboardToken()) {
_openInputConnection();
} else if (!widget.focusNode.hasFocus) {
@@ -285,6 +299,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
);
_connection = TextInput.attach(this, config);
+ inputTrace(() => 'ime ATTACH input connection');
_connection!.show();
@@ -296,6 +311,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
void _closeInputConnectionIfNeeded() {
if (_connection != null && _connection!.attached) {
+ inputTrace(() => 'ime CLOSE input connection');
_connection!.close();
_connection = null;
}
@@ -353,7 +369,16 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void updateEditingValue(TextEditingValue value) {
- if (_consumeActionEcho(value)) return;
+ inputTrace(
+ () => 'ime ← "${traceText(value.text)}" len=${value.text.length}'
+ ' comp=${value.composing.start}..${value.composing.end}'
+ ' sel=${value.selection.baseOffset}..${value.selection.extentOffset}'
+ ' mirror=${_terminalText.length}',
+ );
+ if (_consumeActionEcho(value)) {
+ inputTrace(() => 'ime dropped: the newline echo of an action');
+ return;
+ }
if (_holdRewrite(value)) return;
_applyEditingValue(
value,
@@ -365,10 +390,37 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
/// [_holdRewrite] — and fires once it has gone quiet ([_settleRewrite]).
Timer? _rewriteSettle;
- /// How long the keyboard must go quiet before a rewrite counts as done. Its
- /// steps arrive a millisecond or two apart; a person's next key is a hundred
- /// or more behind.
- static const _rewriteQuiet = Duration(milliseconds: 30);
+ /// How long the keyboard must go quiet before a rewrite counts as done: three
+ /// times the longest pause seen between two steps of one ([_rewriteGap]),
+ /// within [_rewriteQuietMin]..[_rewriteQuietMax] — and the most until a few
+ /// rewrites have been timed.
+ ///
+ /// ⚠️ **Measured, not guessed, and only ever lengthened.** Every key typed
+ /// inside a word waits this long, so it should be as short as the keyboard
+ /// allows; but settling before the keyboard is done brings back the bug the
+ /// hold exists for (see [_holdRewrite]). Its steps arrive a millisecond or
+ /// two apart on a phone, and a person's next key is a hundred or more behind,
+ /// so the margin is wide either way; the longest pause seen stands for the
+ /// rest of the run.
+ static Duration get _rewriteQuiet {
+ if (_rewritesTimed < 3) return _rewriteQuietMax;
+ final quiet = _rewriteGap * 3;
+ if (quiet < _rewriteQuietMin) return _rewriteQuietMin;
+ if (quiet > _rewriteQuietMax) return _rewriteQuietMax;
+ return quiet;
+ }
+
+ static const _rewriteQuietMin = Duration(milliseconds: 16);
+ static const _rewriteQuietMax = Duration(milliseconds: 30);
+
+ /// The longest pause seen between two steps of one rewrite, over every
+ /// rewrite this run — and how many rewrites have been timed.
+ static Duration _rewriteGap = Duration.zero;
+ static int _rewritesTimed = 0;
+ static final _rewriteClock = Stopwatch()..start();
+
+ /// When the rewrite being held last moved, on [_rewriteClock].
+ Duration _rewriteStepAt = Duration.zero;
/// AUTONOMOUS PATCH: holds back the steps of a word the keyboard is
/// rewriting, so only where it ends up reaches the terminal.
@@ -396,19 +448,41 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
bool _holdRewrite(TextEditingValue value) {
final holding = _rewriteSettle != null;
if (!holding) {
+ // ⚠️ **Two code units or more: a Backspace is not a rewrite.** iOS deletes
+ // the same way — the character before the caret selected, then removed —
+ // and a delete held for the quiet was 16ms on every Backspace (measured
+ // on a phone, 2026-10-05). A rewrite always selects the word WITH the
+ // space before it, so never less than two.
+ final selection = value.selection;
final startsRewrite = _composesThroughSoftwareKeyboard &&
value.composing.isCollapsed &&
- !value.selection.isCollapsed &&
+ selection.end - selection.start >= 2 &&
value.text == _currentEditingState.text &&
value.text == _terminalText;
if (!startsRewrite) return false;
}
_currentEditingState = value;
+ final now = _rewriteClock.elapsed;
+ if (holding && now - _rewriteStepAt > _rewriteGap) {
+ _rewriteGap = now - _rewriteStepAt;
+ }
+ _rewriteStepAt = now;
_rewriteSettle?.cancel();
- _rewriteSettle = Timer(_rewriteQuiet, _settleRewrite);
+ _rewriteSettle = Timer(_rewriteQuiet, _rewriteWentQuiet);
+ inputTrace(
+ () => 'ime held: the keyboard is rewriting'
+ ' (quiet ${_rewriteQuiet.inMilliseconds}ms,'
+ ' longest step gap ${(_rewriteGap.inMicroseconds / 1000).toStringAsFixed(1)}ms)',
+ );
return true;
}
+ /// The keyboard went quiet: the rewrite is done, and timed.
+ void _rewriteWentQuiet() {
+ _rewritesTimed++;
+ _settleRewrite();
+ }
+
/// The rewrite [_holdRewrite] is holding, applied now: the terminal goes from
/// what it has to what the buffer ended on, in one edit. Nothing without one.
void _settleRewrite() {
@@ -417,6 +491,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
timer.cancel();
_rewriteSettle = null;
final value = _currentEditingState;
+ inputTrace(() => 'ime settled on "${traceText(value.text)}"');
_applyEditingValue(value, hasTextMutation: value.text != _terminalText);
}
@@ -470,6 +545,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
return;
}
+ inputTrace(() => 'ime composing "${traceText(composingText)}"');
widget.onComposing(
composingText,
_composingBacktrackCells(_currentEditingState.composing.start),
@@ -486,6 +562,10 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
void _syncTerminalText(String value) {
final edit = _TextEdit.between(_terminalText, value);
+ inputTrace(
+ () => 'ime → pty del=${edit.removed.runes.length}'
+ ' ins="${traceText(edit.inserted)}"',
+ );
if (edit.removed.isNotEmpty) {
widget.onDelete(edit.removed.runes.length);
}
@@ -515,6 +595,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void performAction(TextInputAction action) {
+ inputTrace(() => 'ime action $action');
// The line goes as the keyboard ended it, before the action acts on it.
_settleRewrite();
// Captured before the handler runs: it is what the pty has been sent, and
@@ -525,6 +606,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void performSelector(String selectorName) {
+ inputTrace(() => 'ime selector $selectorName');
_settleRewrite();
if (!selectorName.startsWith('deleteBackward')) return;
@@ -624,7 +706,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void connectionClosed() {
- // print('connectionClosed');
+ inputTrace(() => 'ime connection CLOSED by the platform');
}
@override
diff --git a/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart b/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart
index cbffd0877..7ef753511 100644
--- a/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart
+++ b/mobile/third_party/xterm/lib/src/ui/line_picture_cache.dart
@@ -27,12 +27,17 @@ class LinePictureCache {
/// Least recently drawn first.
final _pictures = LinkedHashMap<BufferLine, _LinePicture>.identity();
+ /// How many lines have been recorded afresh, ever — for a trace to tell a
+ /// paint that replayed from one that drew.
+ int recorded = 0;
+
/// Draws [line] with its top-left at [offset]: its recording while that still
/// shows the line, else a fresh one.
void draw(Canvas canvas, Offset offset, BufferLine line) {
var entry = _pictures.remove(line);
if (entry == null || entry.version != line.paintVersion) {
entry?.picture.dispose();
+ recorded++;
final recorder = PictureRecorder();
_paint(Canvas(recorder), Offset.zero, line);
entry = _LinePicture(recorder.endRecording(), line.paintVersion);
diff --git a/mobile/third_party/xterm/lib/src/ui/painter.dart b/mobile/third_party/xterm/lib/src/ui/painter.dart
index 5489c14ff..c7186c02c 100644
--- a/mobile/third_party/xterm/lib/src/ui/painter.dart
+++ b/mobile/third_party/xterm/lib/src/ui/painter.dart
@@ -171,6 +171,9 @@ class TerminalPainter {
void paintLineCached(Canvas canvas, Offset offset, BufferLine line) =>
_linePictures.draw(canvas, offset, line);
+ /// How many lines [paintLineCached] has drawn afresh rather than replayed.
+ int get linesRecorded => _linePictures.recorded;
+
/// AUTONOMOUS PATCH: [line]'s last recording, handed over to the caller if it
/// still shows [version] — see [LinePictureCache.take].
Picture? takeLinePicture(BufferLine line, int version) =>
diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dart
index 0d8894d67..3d25734d0 100644
--- a/mobile/third_party/xterm/lib/src/ui/render.dart
+++ b/mobile/third_party/xterm/lib/src/ui/render.dart
@@ -16,6 +16,8 @@ import 'package:xterm/src/ui/selection_mode.dart';
import 'package:xterm/src/ui/terminal_size.dart';
import 'package:xterm/src/ui/terminal_text_style.dart';
import 'package:xterm/src/ui/terminal_theme.dart';
+import 'package:xterm/src/utils/input_trace.dart';
+import 'package:xterm/src/utils/unicode_v11.dart';
typedef EditableRectCallback = void Function(Rect rect, Rect caretRect);
@@ -70,6 +72,8 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
}
_terminal = terminal;
_reportedViewportSize = null;
+ _predictedText = '';
+ _predictedCells = 0;
// The recorded lines are the old emulator's: none of them is drawn again.
_painter.clearLinePictures();
_remoteScroll?.reset();
@@ -200,6 +204,23 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
markNeedsPaint();
}
+ /// AUTONOMOUS PATCH: what is typed and not yet echoed, drawn faint at the
+ /// cursor — `TerminalView.predictsEcho`. Set by the view directly rather than
+ /// through a rebuild: it changes with every key and every echo.
+ String _predictedText = '';
+ int _predictedCells = 0;
+ set predictedText(String value) {
+ if (value == _predictedText) return;
+ _predictedText = value;
+ var cells = 0;
+ for (final rune in value.runes) {
+ final width = unicodeV11.wcwidth(rune);
+ if (width > 0) cells += width;
+ }
+ _predictedCells = cells;
+ markNeedsPaint();
+ }
+
/// AUTONOMOUS PATCH: the screen's pixels per logical pixel — the grid each
/// line's top is placed on, see [_snapLineTop].
double _devicePixelRatio;
@@ -603,7 +624,22 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
@override
void paint(PaintingContext context, Offset offset) {
- _paint(context, offset);
+ if (xtermInputTrace == null) {
+ _paint(context, offset);
+ } else {
+ final recordedBefore = _painter.linesRecorded;
+ final watch = Stopwatch()..start();
+ _paint(context, offset);
+ final micros = watch.elapsedMicroseconds;
+ final redrawn = _painter.linesRecorded - recordedBefore;
+ if (redrawn > 0 || micros > 4000) {
+ inputTrace(
+ () => 'paint ${(micros / 1000).toStringAsFixed(1)}ms'
+ ' redrawn=$redrawn cursor=${_terminal.buffer.cursorX},'
+ '${_terminal.buffer.absoluteCursorY}',
+ );
+ }
+ }
context.setWillChangeHint();
}
@@ -663,14 +699,23 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
? offset + cursorOffset.translate(0, slide.offset)
: offset + cursorOffset;
+ final predicting = !_isComposingText && _predictedText.isNotEmpty;
if (_isComposingText) {
_paintComposingText(canvas, cursorAt);
+ } else if (predicting) {
+ _paintPredictedText(canvas, cursorAt);
}
if (_shouldShowCursor) {
_painter.paintCursor(
canvas,
- cursorAt,
+ // Past what is drawn ahead of the echo, where the echo will leave it.
+ predicting
+ ? cursorAt.translate(
+ _predictedCells * _painter.cellSize.width,
+ 0,
+ )
+ : cursorAt,
cursorType: _cursorType,
hasFocus: _focusNode.hasFocus,
);
@@ -807,6 +852,30 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
textPainter.dispose();
}
+ /// AUTONOMOUS PATCH: [_predictedText] at [offset], the cursor — in the
+ /// cursor's colour, faint, over the cells it will be echoed into.
+ void _paintPredictedText(Canvas canvas, Offset offset) {
+ final color = _painter.resolveForegroundColor(_terminal.cursor.foreground);
+ final style = _painter.textStyle.toTextStyle(
+ color: color.withAlpha((color.a * 255 * 0.55).round()),
+ backgroundColor: _painter.theme.background,
+ underline: false,
+ );
+ final textPainter = TextPainter(
+ text: TextSpan(
+ text: _predictedText,
+ style: style.copyWith(
+ decoration: TextDecoration.none,
+ decorationColor: const Color(0x00000000),
+ ),
+ ),
+ textDirection: TextDirection.ltr,
+ textScaler: _painter.textScaler,
+ )..layout(maxWidth: (size.width - offset.dx).clamp(0.0, size.width));
+ textPainter.paint(canvas, offset);
+ textPainter.dispose();
+ }
+
void _paintSelection(
Canvas canvas,
Offset offset,
diff --git a/mobile/third_party/xterm/lib/src/utils/input_trace.dart b/mobile/third_party/xterm/lib/src/utils/input_trace.dart
new file mode 100644
index 000000000..8d7b06923
--- /dev/null
+++ b/mobile/third_party/xterm/lib/src/utils/input_trace.dart
@@ -0,0 +1,44 @@
+/// AUTONOMOUS PATCH: where the input path tells an embedder what it did — each
+/// edit the keyboard sent, what of it reached the terminal, the keyboard's
+/// buffer being reset, an echo predicted, a paint's cost — for the embedder's
+/// log. Null, the default, says nothing and costs a null check; the app sets it
+/// only in a build that asks for its typing trace.
+void Function(String message)? xtermInputTrace;
+
+/// [message] for [xtermInputTrace], built only when somebody listens.
+void inputTrace(String Function() message) {
+ final trace = xtermInputTrace;
+ if (trace != null) trace(message());
+}
+
+/// [text] for a trace line: its last [max] characters, control characters
+/// spelled out so a line of the log stays one line.
+String traceText(String text, {int max = 32}) {
+ final tail = text.length <= max ? text : text.substring(text.length - max);
+ final out = StringBuffer(text.length > max ? '…' : '');
+ for (final unit in tail.codeUnits) {
+ if (unit == 0x0d) {
+ out.write(r'\r');
+ } else if (unit == 0x0a) {
+ out.write(r'\n');
+ } else if (unit == 0x1b) {
+ out.write(r'\e');
+ } else if (unit < 0x20 || unit == 0x7f) {
+ out.write('\\x${unit.toRadixString(16).padLeft(2, '0')}');
+ } else {
+ out.writeCharCode(unit);
+ }
+ }
+ return out.toString();
+}
+
+/// Where [inputTrace] was called from, two frames up — for the calls that
+/// matter by who made them (the keyboard's buffer being reset).
+String traceCaller() {
+ final frames = StackTrace.current.toString().split('\n');
+ return frames
+ .skip(2)
+ .take(2)
+ .map((frame) => frame.replaceFirst(RegExp(r'^#\d+\s+'), '').trim())
+ .join(' ← ');
+}
diff --git a/mobile/third_party/xterm/lib/utils.dart b/mobile/third_party/xterm/lib/utils.dart
index 74c0abac3..c7d076d93 100644
--- a/mobile/third_party/xterm/lib/utils.dart
+++ b/mobile/third_party/xterm/lib/utils.dart
@@ -1,2 +1,3 @@
export 'src/utils/debugger.dart';
export 'src/utils/debugger_view.dart';
+export 'src/utils/input_trace.dart';