App: replace a silent socket instead of hanging; blink the terminal cursor on a timer; keep one markdown cache entry per streamed reply

A socket that outlived a sleep or network change looked open, so every
queued request waited its own 30 s timeout behind the last until the page
was reopened. The client now replaces a socket whose request times out
unheard (or after two timeouts in a row), and probes it with a ping after
a quiet spell or on returning to the foreground.

The terminal's blinking cursor ran a Ticker (a frame every vsync); a 530 ms
timer now flips it. Streamed deltas no longer flood the markdown cache and
evict finished answers.

Adds tool/perf/idle_session_bench.mjs (idle frames, long-session heap,
snapshot census) and notes/perf-hangs-idle.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 20:47:22 +00:00
parent 23d8658e80
commit 2889d59119
17 changed files with 589 additions and 47 deletions
+3
View File
@@ -637,6 +637,9 @@ class _PipelinesAppState extends State<PipelinesApp>
return;
}
if (connection != ConnectionKind.connected) return;
// A socket that looks open may have died while the app was away (a
// laptop's sleep): a ping that hears nothing replaces it.
_session.client.probe();
// Foreground return refreshes the visible Runs list and selected detail.
// Pipeline definitions retain their current data while being inspected.
@@ -20,10 +20,28 @@ class PipelinesClient implements ApiGateway {
this.connectionTimeout = const Duration(seconds: 5),
this.backoffBase = const Duration(seconds: 1),
this.backoffMax = const Duration(seconds: 30),
this.probeTimeout = const Duration(seconds: 10),
this.quietProbeAfter = const Duration(seconds: 30),
this.replaceSilentSocket = true,
}) : _factory = channelFactory ?? connectPipelinesChannel;
final ChannelFactory _factory;
final Duration requestTimeout, connectionTimeout, backoffBase, backoffMax;
/// How long a liveness probe ([probe]) waits to hear anything at all from
/// the server before the socket is treated as dead and replaced.
final Duration probeTimeout;
/// A request sent after the socket has been quiet this long (wall clock,
/// so a laptop's sleep counts) is accompanied by a [probe]. A socket that
/// outlived a sleep often looks open but is dead: nothing tells the
/// browser until it gives up retransmitting, minutes later.
final Duration quietProbeAfter;
/// Whether a socket that leaves requests or a probe unheard is replaced
/// (see [_timedOut] and [probe]). Off only for fixtures whose fake server
/// deliberately answers nothing.
final bool replaceSilentSocket;
final _frames = StreamController<JsonMap>.broadcast();
final _states = StreamController<ConnectionState>.broadcast();
final Map<String, Completer<JsonMap>> _pending = {};
@@ -39,6 +57,17 @@ class PipelinesClient implements ApiGateway {
ConnectionState _state = const ConnectionState(ConnectionKind.idle);
Future<void> _queue = Future.value();
/// Monotonic time, and when the socket last delivered anything.
final Stopwatch _clock = Stopwatch()..start();
Duration _heardAt = Duration.zero;
/// Requests in a row that timed out on this socket.
int _timeouts = 0;
Timer? _probe;
/// Wall-clock time of the socket's last traffic either way.
DateTime _lastTraffic = DateTime.now();
@override
Stream<JsonMap> get frames => _frames.stream;
Stream<ConnectionState> get states => _states.stream;
@@ -108,6 +137,9 @@ class PipelinesClient implements ApiGateway {
]).timeout(connectionTimeout);
if (generation != _generation) return;
_attempt = 0;
_timeouts = 0;
_heardAt = _clock.elapsed;
_lastTraffic = DateTime.now();
_setState(const ConnectionState(ConnectionKind.connected));
} catch (error) {
if (generation == _generation) _closed(error.toString());
@@ -187,8 +219,10 @@ class PipelinesClient implements ApiGateway {
result.completeError(const NotConnectedError());
return;
}
_probeIfQuiet();
final id = 'flutter-${++_sequence}';
_pending[id] = result;
final sentAt = _clock.elapsed;
final timer = Timer(requestTimeout, () {
if (_pending.remove(id) != null) {
result.completeError(
@@ -196,6 +230,7 @@ class PipelinesClient implements ApiGateway {
'request timed out after ${requestTimeout.inMilliseconds}ms',
),
);
_timedOut(generation, sentAt);
}
});
result.future.then<void>(
@@ -220,7 +255,69 @@ class PipelinesClient implements ApiGateway {
return id;
}
/// A request went unanswered. Requests are answered in order on the
/// server's request lane, so every later request would wait out its own
/// timeout behind it, one after another: the app hangs until reopened.
/// When the socket stayed silent the whole time (dead after a sleep or a
/// network change), or a second request in a row timed out (the lane is
/// stuck), the socket is replaced: queued requests fail at once and a
/// fresh connection resubscribes.
void _timedOut(int generation, Duration sentAt) {
if (generation != _generation || _disposed || _manual) return;
if (!replaceSilentSocket) return;
_timeouts++;
final silent = _heardAt <= sentAt;
if (silent || _timeouts >= 2) {
_closed(
silent ? 'No reply from the server' : 'The server stopped replying',
);
}
}
/// Checks that the open socket still reaches the server: a ping is sent
/// outside the request queue, and if nothing at all arrives within
/// [probeTimeout] the socket is replaced. Call it when the app returns to
/// the foreground; the client also sends one with the first request after
/// a quiet spell.
void probe() {
final channel = _channel;
if (channel == null ||
!replaceSilentSocket ||
_state.kind != ConnectionKind.connected ||
_probe != null) {
return;
}
final generation = _generation;
final sentAt = _clock.elapsed;
try {
channel.sink.add(
jsonEncode({'type': 'ping', 'id': 'flutter-probe-${++_sequence}'}),
);
} catch (_) {
// A failed write surfaces through the socket's own error path.
}
_probe = Timer(probeTimeout, () {
_probe = null;
if (generation != _generation || _disposed || _manual) return;
if (_heardAt <= sentAt) _closed('No reply from the server');
});
}
void _probeIfQuiet() {
final now = DateTime.now();
final quiet = now.difference(_lastTraffic);
_lastTraffic = now;
if (quiet > quietProbeAfter) probe();
}
void _stopWatching() {
_probe?.cancel();
_probe = null;
}
void _onMessage(dynamic data) {
_heardAt = _clock.elapsed;
_lastTraffic = DateTime.now();
if (data is! String) return;
final Object? decoded;
try {
@@ -231,8 +328,10 @@ class PipelinesClient implements ApiGateway {
if (decoded is! Map<String, dynamic>) return;
final message = decoded;
final id = message['id'];
if (id is String && id.startsWith('flutter-probe-')) return;
final pending = id is String ? _pending.remove(id) : null;
if (pending != null) {
_timeouts = 0;
if (message['type'] == 'error') {
final reason = '${message['error'] ?? ''}'.trim();
pending.completeError(
@@ -259,6 +358,7 @@ class PipelinesClient implements ApiGateway {
void _closed(String reason) {
_generation++;
_stopWatching();
_cancelOpening();
final channel = _channel;
final subscription = _subscription;
@@ -293,6 +393,7 @@ class PipelinesClient implements ApiGateway {
Future<void> disconnect() async {
_manual = true;
_reconnect?.cancel();
_stopWatching();
final generation = ++_generation;
_cancelOpening();
final channel = _channel;
@@ -1,58 +1,56 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
/// How long a blinking cursor stays shown, then hidden (xterm's 600 ms is
/// close; most terminals use about half a second).
const Duration chatShellCursorBlinkPhase = Duration(milliseconds: 530);
/// The blink of a cursor the program asked to blink (DECSCUSR 1, 3 or 5).
/// It runs on a [Ticker] only while [update] says to blink: the terminal
/// is focused, the shape blinks and motion is not reduced. Otherwise the
/// cursor is steady ([visible] stays true), so an unfocused terminal or a
/// test schedules nothing. Typing or output shows it again at once
/// ([restart]), as terminals do.
/// It runs only while [update] says to blink: the terminal is focused, the
/// shape blinks and motion is not reduced. Otherwise the cursor is steady
/// ([visible] stays true), so an unfocused terminal or a test schedules
/// nothing. Typing or output shows it again at once ([restart]), as
/// terminals do.
///
/// A timer flips the phase, so a blinking cursor costs one frame per phase
/// rather than a ticker's frame on every vsync of an otherwise idle page.
class ChatShellCursorBlink {
ChatShellCursorBlink(TickerProvider vsync) {
_ticker = vsync.createTicker(_tick);
}
late final Ticker _ticker;
Duration _now = Duration.zero;
Duration _since = Duration.zero;
Timer? _timer;
/// Whether the cursor is drawn in the current phase.
final ValueNotifier<bool> visible = ValueNotifier(true);
bool get blinking => _ticker.isActive;
bool get blinking => _timer != null;
void update({required bool blink}) {
if (blink == _ticker.isActive) return;
if (blink == blinking) return;
if (blink) {
_now = Duration.zero;
_since = Duration.zero;
_ticker.start();
_start();
} else {
_ticker.stop();
_timer?.cancel();
_timer = null;
}
visible.value = true;
}
/// Shows the cursor and starts the phase again.
void restart() {
_since = _now;
visible.value = true;
if (blinking) _start();
}
void _tick(Duration elapsed) {
_now = elapsed;
final phase =
(elapsed - _since).inMicroseconds ~/
chatShellCursorBlinkPhase.inMicroseconds;
visible.value = phase.isEven;
void _start() {
_timer?.cancel();
_timer = Timer.periodic(
chatShellCursorBlinkPhase,
(_) => visible.value = !visible.value,
);
}
void dispose() {
_ticker.dispose();
_timer?.cancel();
_timer = null;
visible.dispose();
}
}
@@ -78,7 +78,6 @@ class ChatShellTerminalView extends StatefulWidget {
class _ChatShellTerminalViewState extends State<ChatShellTerminalView>
with
SingleTickerProviderStateMixin,
ChatShellTerminalFindHost<ChatShellTerminalView>,
ChatShellTerminalFeatures<ChatShellTerminalView> {
@override
@@ -18,7 +18,7 @@ import 'chat_shell_terminal_shortcuts.dart';
/// [ChatShellTerminalFindHost]). The view supplies its emulator's parts and
/// calls [initFeatures] and [disposeFeatures].
mixin ChatShellTerminalFeatures<T extends StatefulWidget>
on State<T>, TickerProvider, ChatShellTerminalFindHost<T> {
on State<T>, ChatShellTerminalFindHost<T> {
ScrollController get scroll;
GlobalKey<TerminalViewState> get viewKey;
@@ -44,7 +44,7 @@ mixin ChatShellTerminalFeatures<T extends StatefulWidget>
view: viewKey,
);
hover = ChatShellLinkHover(_terminal, viewKey);
blink = ChatShellCursorBlink(this);
blink = ChatShellCursorBlink();
_guard = ChatShellSelectionGuard(_terminal, controller);
scroll.addListener(hover.refresh);
_terminal.addListener(_terminalChanged);
@@ -7,8 +7,13 @@ import 'chat_markdown.dart';
/// A lazily built transcript disposes rows scrolled out of view, so scrolling
/// back would parse the same answer again. Blocks are immutable and depend on
/// the text alone, so one parse serves every later view of that text. Bounded
/// by entries and by held characters, evicting the least recently used first,
/// so a long streamed reply's intermediate texts cannot grow it without limit.
/// by entries and by held characters, evicting the least recently used first.
///
/// A streamed reply asks for a longer text on every delta. Each new text
/// replaces the newest entry when that entry is its prefix, so a reply holds
/// one entry while it streams instead of one per delta: its intermediate
/// texts would otherwise fill the character budget and evict every finished
/// answer, which then parse again when scrolled back into view.
class ChatMarkdownCache {
ChatMarkdownCache({this.maxEntries = 400, this.maxChars = 1000000});
@@ -28,6 +33,13 @@ class ChatMarkdownCache {
final blocks = List<MarkdownBlock>.unmodifiable(parseMarkdown(text));
parses++;
if (text.length > maxChars) return blocks;
if (_blocks.isNotEmpty) {
final newest = _blocks.keys.last;
if (newest.length < text.length && text.startsWith(newest)) {
_blocks.remove(newest);
_chars -= newest.length;
}
}
_blocks[text] = blocks;
_chars += text.length;
while (_blocks.length > maxEntries || _chars > maxChars) {