diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 1de6fa02..1aeca3ff 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -637,6 +637,9 @@ class _PipelinesAppState extends State 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. diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 576b81d1..38b79431 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -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.broadcast(); final _states = StreamController.broadcast(); final Map> _pending = {}; @@ -39,6 +57,17 @@ class PipelinesClient implements ApiGateway { ConnectionState _state = const ConnectionState(ConnectionKind.idle); Future _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 get frames => _frames.stream; Stream 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( @@ -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) 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 disconnect() async { _manual = true; _reconnect?.cancel(); + _stopWatching(); final generation = ++_generation; _cancelOpening(); final channel = _channel; diff --git a/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart b/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart index 7d817239..ec49885e 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_cursor_blink.dart @@ -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 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(); } } diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view.dart b/app/lib/features/chat/shell/chat_shell_terminal_view.dart index 289100de..97daae85 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view.dart @@ -78,7 +78,6 @@ class ChatShellTerminalView extends StatefulWidget { class _ChatShellTerminalViewState extends State with - SingleTickerProviderStateMixin, ChatShellTerminalFindHost, ChatShellTerminalFeatures { @override diff --git a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart index a50679aa..5987a389 100644 --- a/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart +++ b/app/lib/features/chat/shell/chat_shell_terminal_view_features.dart @@ -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 - on State, TickerProvider, ChatShellTerminalFindHost { + on State, ChatShellTerminalFindHost { ScrollController get scroll; GlobalKey get viewKey; @@ -44,7 +44,7 @@ mixin ChatShellTerminalFeatures view: viewKey, ); hover = ChatShellLinkHover(_terminal, viewKey); - blink = ChatShellCursorBlink(this); + blink = ChatShellCursorBlink(); _guard = ChatShellSelectionGuard(_terminal, controller); scroll.addListener(hover.refresh); _terminal.addListener(_terminalChanged); diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart b/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart index a591b402..1be18f44 100644 --- a/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart +++ b/app/lib/features/chat/ui/transcript/chat_markdown_cache.dart @@ -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.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) { diff --git a/app/notes/perf-hangs-idle.md b/app/notes/perf-hangs-idle.md new file mode 100644 index 00000000..160c5a44 --- /dev/null +++ b/app/notes/perf-hangs-idle.md @@ -0,0 +1,61 @@ +# Hangs, idle frames and long-session memory + +Operator report: the web app sometimes hangs until it is reopened, and +animations sometimes feel slow. The app stays open all day. + +## Causes and fixes + +- **Hang: a dead socket blocks every request in turn (confirmed in code and + tests).** Requests go out one at a time; each waits for the previous + reply, and the server answers them in order on one lane. A socket that + outlived a laptop sleep or a network change usually still looks open: the + browser is not told until TCP gives up, which can take minutes. Each queued + request then waited its own 30 s timeout, one after another, and nothing + replaced the socket. Reopening the page was the only fix. + `PipelinesClient` (`lib/core/transport/pipelines_client.dart`) now: + - replaces the socket when a request times out and nothing arrived while it + waited, or when two requests in a row time out (a stuck request lane). + Queued requests fail at once and the fresh connection resubscribes as on + any reconnect; + - sends a `ping` probe outside the queue with the first request after 30 s + of quiet (wall clock, so a sleep counts) and when the app returns to the + foreground (`pipelines_app.dart`). If it hears nothing within 10 s, it + replaces the socket. No standing timer is used. + `replaceSilentSocket: false` keeps the old behaviour for widget-test fakes + that answer nothing. +- **Idle frames: the terminal's blinking cursor ran a Ticker (confirmed in + code and a widget test).** While a focused terminal showed a blinking cursor + (DECSCUSR 1/3/5), the page asked for a frame on every vsync, all day. + `ChatShellCursorBlink` now flips the phase with a 530 ms timer: one frame + per phase. +- **Markdown cache flushing (confirmed in a unit test).** Every streamed delta + cached its intermediate text, so one long reply filled the 1M-character + budget and evicted every finished answer. Those answers were then parsed + again on scroll. A text that extends the newest entry now replaces it. + +## Measurements + +`tool/perf/idle_session_bench.mjs` (new) runs on the profile full-app fixture +in headless Chromium with CPU raster (no GPU). It counts +`requestAnimationFrame` calls while the page is idle. `--session N` simulates +a long session: open 6 rich chats (one streaming each round), the terminal +panel, Runs, Pipelines and Search. After each round it forces a GC and reports +the heap. `--census` diffs heap snapshots by constructor. + +- Idle frames in 5 s (before = after; the blink case is covered by the widget + test): Runs 0, run detail 0, Pipelines 0, Settings 0, a rich 80-message chat + 0, chat plus terminal panel 0. A chat with a running turn or a running chat + in the list animates by design (running border, spinners). +- Heap over 10 rounds: 47.5 MB at round 1, 57.2 MB at round 10, with growth + slowing. A snapshot diff between rounds 2 and 8 shows +4.6 MB of V8 compiled + code and engine-native memory. Dart objects grew by a few KB: 35 cached + images (bounded ImageCache), about 70 markdown blocks and a few hundred map + cells. No unbounded Dart-side growth was found. +- Markdown parse of a 30 KB reply: about 2 ms on the VM. Incremental parsing + is not justified. + +## Left open (suspected, not measured) + +- A large `chat_messages` page (200 messages with tool output) is decoded on + the main thread. No evidence yet that it exceeds a frame budget; a web + worker is not justified without a real-page measurement. diff --git a/app/test/application/chat_registration_test.dart b/app/test/application/chat_registration_test.dart index 5aeb072c..29185cab 100644 --- a/app/test/application/chat_registration_test.dart +++ b/app/test/application/chat_registration_test.dart @@ -302,7 +302,10 @@ void main() { addTearDown(tester.view.resetDevicePixelRatio); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')), ); @@ -410,7 +413,10 @@ void main() { addTearDown(tester.view.resetDevicePixelRatio); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/old')), ); @@ -492,7 +498,10 @@ void main() { addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), ); @@ -702,7 +711,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), ); @@ -784,7 +796,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), ); @@ -839,7 +854,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), ); @@ -908,7 +926,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/a')), ); @@ -957,7 +978,10 @@ void main() { tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/chat')), ); diff --git a/app/test/application/run_tab_indicators_test.dart b/app/test/application/run_tab_indicators_test.dart index 95dd86ad..28a7e028 100644 --- a/app/test/application/run_tab_indicators_test.dart +++ b/app/test/application/run_tab_indicators_test.dart @@ -15,7 +15,10 @@ void main() { ) async { SharedPreferences.setMockInitialValues({}); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/runs')), ); diff --git a/app/test/application/settings_page_test.dart b/app/test/application/settings_page_test.dart index b0caf754..df7f724d 100644 --- a/app/test/application/settings_page_test.dart +++ b/app/test/application/settings_page_test.dart @@ -37,7 +37,10 @@ void main() { PipelinesApp( androidSupported: false, server: webServer(), - client: PipelinesClient(channelFactory: (_) => channel), + client: PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ), routeInformationProvider: provider, ), ); diff --git a/app/test/application/tab_location_navigation_test.dart b/app/test/application/tab_location_navigation_test.dart index 206d1469..a7c84841 100644 --- a/app/test/application/tab_location_navigation_test.dart +++ b/app/test/application/tab_location_navigation_test.dart @@ -31,7 +31,10 @@ mount( tester.view.devicePixelRatio = 1; addTearDown(tester.view.reset); final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse(route)), ); diff --git a/app/test/application/templates_behind_bar_test.dart b/app/test/application/templates_behind_bar_test.dart index 1ed93027..dd49e232 100644 --- a/app/test/application/templates_behind_bar_test.dart +++ b/app/test/application/templates_behind_bar_test.dart @@ -16,7 +16,10 @@ import 'templates_wiring_test.dart' show pumpApp, readTemplates; void main() { testWidgets('the gallery and detail scroll behind the bar', (tester) async { final channel = FakeChannel()..readyCompleter.complete(); - final client = PipelinesClient(channelFactory: (_) => channel); + final client = PipelinesClient( + replaceSilentSocket: false, + channelFactory: (_) => channel, + ); final provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation(uri: Uri.parse('/pipelines')), ); diff --git a/app/test/application/templates_wiring_test.dart b/app/test/application/templates_wiring_test.dart index 20bf9c87..aedbdbe7 100644 --- a/app/test/application/templates_wiring_test.dart +++ b/app/test/application/templates_wiring_test.dart @@ -135,6 +135,7 @@ void main() { final channel = FakeChannel()..readyCompleter.complete(); var sockets = 0; final client = PipelinesClient( + replaceSilentSocket: false, channelFactory: (_) { sockets++; return channel; @@ -229,6 +230,7 @@ void main() { final channel = FakeChannel()..readyCompleter.complete(); var sockets = 0; final client = PipelinesClient( + replaceSilentSocket: false, channelFactory: (_) { sockets++; return channel; diff --git a/app/test/core/transport/client_regression_test.dart b/app/test/core/transport/client_regression_test.dart index 2409ac5b..015cb6aa 100644 --- a/app/test/core/transport/client_regression_test.dart +++ b/app/test/core/transport/client_regression_test.dart @@ -14,6 +14,10 @@ void reply(FakeChannel channel, {int index = 0, String type = 'pong'}) => jsonEncode({'id': sent(channel, index)['id'], 'type': type}), ); +extension on T { + void let(void Function(T) f) => f(this); +} + void main() { test( 'requests serialize through replies, errors do not poison queue', @@ -51,14 +55,126 @@ void main() { requestTimeout: const Duration(milliseconds: 10), ); await client.connect(Uri.parse('ws://example.test')); - await expectLater(client.call('ping'), throwsA(isA())); - final late = client.frames.first; + final call = client.call('ping'); + await flush(); + // The socket is alive (a pushed frame arrives while the call waits), + // so its first timeout keeps it. + channel.incoming.add(jsonEncode({'type': 'run_event'})); + await expectLater(call, throwsA(isA())); + expect(client.state.kind, ConnectionKind.connected); + final late = client.frames.firstWhere((f) => f['type'] == 'pong'); reply(channel); expect((await late)['type'], 'pong'); await client.dispose(); }, ); + test('a timeout on a silent socket replaces it and fails the queue at once ' + 'instead of timing out each queued request in turn', () async { + final channels = []; + final client = PipelinesClient( + channelFactory: (_) => + (FakeChannel()..readyCompleter.complete())..let(channels.add), + requestTimeout: const Duration(milliseconds: 20), + backoffBase: const Duration(milliseconds: 5), + ); + await client.connect(Uri.parse('ws://example.test')); + final first = client.call('ping'); + final queued = client.call('list_runs'); + final reconnected = client.states + .where((s) => s.kind == ConnectionKind.connected) + .first; + final clock = Stopwatch()..start(); + await expectLater(first, throwsA(isA())); + await expectLater(queued, throwsStateError); + expect(clock.elapsedMilliseconds, lessThan(200)); + await reconnected.timeout(const Duration(seconds: 2)); + expect(channels, hasLength(2)); + expect(channels.first.outgoing, hasLength(1)); + await client.dispose(); + }); + + test('a second timeout in a row replaces a socket that still pushes ' + 'frames: its request lane is stuck', () async { + final channels = []; + final client = PipelinesClient( + channelFactory: (_) => + (FakeChannel()..readyCompleter.complete())..let(channels.add), + requestTimeout: const Duration(milliseconds: 20), + backoffBase: const Duration(milliseconds: 5), + ); + await client.connect(Uri.parse('ws://example.test')); + for (var i = 0; i < 2; i++) { + final call = client.call('ping'); + await flush(); + channels.first.incoming.add(jsonEncode({'type': 'run_event'})); + await expectLater(call, throwsA(isA())); + if (i == 0) expect(client.state.kind, ConnectionKind.connected); + } + await client.states + .where((s) => s.kind == ConnectionKind.connected) + .first + .timeout(const Duration(seconds: 2)); + expect(channels, hasLength(2)); + await client.dispose(); + }); + + test( + 'the first request after a quiet spell is preceded by a probe', + () async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient( + channelFactory: (_) => channel, + quietProbeAfter: const Duration(milliseconds: 20), + probeTimeout: const Duration(seconds: 5), + ); + await client.connect(Uri.parse('ws://example.test')); + final first = client.call('list_runs'); + await flush(); + expect(channel.outgoing, hasLength(1), reason: 'not quiet yet'); + reply(channel, type: 'runs'); + await first; + await Future.delayed(const Duration(milliseconds: 40)); + final second = client.call('list_runs'); + await flush(); + expect(sent(channel, 1)['type'], 'ping'); + expect(sent(channel, 2)['type'], 'list_runs'); + reply(channel, index: 2, type: 'runs'); + await second; + await client.dispose(); + }, + ); + + test( + 'a probe keeps a socket that answers and replaces one that does not', + () async { + final channels = []; + final client = PipelinesClient( + channelFactory: (_) => + (FakeChannel()..readyCompleter.complete())..let(channels.add), + probeTimeout: const Duration(milliseconds: 20), + backoffBase: const Duration(milliseconds: 5), + ); + final frames = >[]; + client.frames.listen(frames.add); + await client.connect(Uri.parse('ws://example.test')); + client.probe(); + final probe = sent(channels.first); + expect(probe['type'], 'ping'); + reply(channels.first); + await Future.delayed(const Duration(milliseconds: 40)); + expect(channels, hasLength(1)); + expect(frames, isEmpty, reason: 'the probe reply is not a frame'); + client.probe(); + await client.states + .where((s) => s.kind == ConnectionKind.connected) + .first + .timeout(const Duration(seconds: 2)); + expect(channels, hasLength(2)); + await client.dispose(); + }, + ); + test( 'replacement fails queued calls rather than sending on new socket', () async { diff --git a/app/test/features/chat/conversation/chat_row_widgets_test.dart b/app/test/features/chat/conversation/chat_row_widgets_test.dart index 93065079..1a1bd533 100644 --- a/app/test/features/chat/conversation/chat_row_widgets_test.dart +++ b/app/test/features/chat/conversation/chat_row_widgets_test.dart @@ -67,4 +67,19 @@ void main() { cache.blocksFor(long); expect(cache.parses, 6); }); + + test('ChatMarkdownCache holds one entry for a streamed reply, so finished ' + 'answers are not evicted by its intermediate texts', () { + final cache = ChatMarkdownCache(maxEntries: 4, maxChars: 5000); + final finished = cache.blocksFor('# Finished answer'); + var streamed = ''; + for (var delta = 0; delta < 200; delta++) { + streamed += 'word$delta '; + cache.blocksFor(streamed); + } + expect(cache.blocksFor('# Finished answer'), same(finished)); + final parses = cache.parses; + cache.blocksFor(streamed); + expect(cache.parses, parses, reason: 'the final text stays cached'); + }); } diff --git a/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart b/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart index 7100a2f7..155896ff 100644 --- a/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart +++ b/app/test/features/chat/shell/chat_shell_terminal_feedback_test.dart @@ -22,16 +22,22 @@ void main() { expect(shown(tester, harness), isTrue); await tester.pump(_phase + const Duration(milliseconds: 10)); expect(shown(tester, harness), isFalse); + // Between phase flips nothing asks for a frame: one frame per phase, + // not one per vsync. + expect(tester.binding.hasScheduledFrame, isFalse); await tester.pump(_phase); expect(shown(tester, harness), isTrue); + expect(tester.binding.hasScheduledFrame, isFalse); // Output shows it again and restarts the phase. await tester.pump(_phase); expect(shown(tester, harness), isFalse); await harness.write(tester, 'x'); expect(shown(tester, harness), isTrue); - // Unfocused: steady, and the ticker stopped. + // Unfocused: steady, and the blink stopped (the unfocused cursor's + // own repaint is the last frame). harness.view(tester).focusNode!.unfocus(); await tester.pump(); + await tester.pump(_phase * 2); expect(shown(tester, harness), isTrue); expect(tester.binding.hasScheduledFrame, isFalse); }); diff --git a/app/tool/perf/idle_session_bench.mjs b/app/tool/perf/idle_session_bench.mjs new file mode 100644 index 00000000..0b3dfa19 --- /dev/null +++ b/app/tool/perf/idle_session_bench.mjs @@ -0,0 +1,193 @@ +#!/usr/bin/env node +// Idle and long-session bench over the full-app fixture +// (tool/search_selection_probe_entry.dart; a `--profile` build keeps names). +// +// For each idle scenario it loads a route, lets it settle, then counts the +// animation frames the page asks for (wrapped `requestAnimationFrame`) over +// `--idle` seconds with nothing changing: an idle app should ask for none. +// +// `--session N` then simulates a long day in one page: N rounds of opening +// each fixture chat (history pushState + popstate, as the app's own path +// routing does on Back/Forward), letting live replies stream, visiting Runs, +// Pipelines and Search, and opening the terminal panel. After every round it +// forces a GC and reports the used JS heap, the long tasks (>50 ms) and the +// longest task seen, so growth over the session shows as a trend. +// +// node tool/perf/idle_session_bench.mjs --build build/probe-app \ +// [--idle 5] [--session 6] [--gpu] [--only 'name;name'] [--stacks] +// +// Headless Chrome without --gpu rasterises on the CPU (CanvasKit). +import { parseArgs } from 'node:util'; +import { setTimeout as delay } from 'node:timers/promises'; +import { openBrowser } from '../capture/browser.mjs'; +import { serveBuild } from '../capture/serve.mjs'; + +const { values: opts } = parseArgs({ + options: { + build: { type: 'string' }, idle: { type: 'string', default: '5' }, + session: { type: 'string', default: '0' }, gpu: { type: 'boolean' }, + only: { type: 'string' }, census: { type: 'boolean' }, stacks: { type: 'boolean' }, size: { type: 'string', default: '1280x800' }, + }, +}); +if (!opts.build) throw new Error('usage: --build '); + +const CHATS = 6; +const base = { chats: String(CHATS), header: '1', rich: '1', msgs: '80,30' }; +const IDLE = [ + { name: 'runs list', route: '/runs', q: {} }, + { name: 'run detail', route: '/runs/7', q: {} }, + { name: 'pipelines', route: '/pipelines', q: {} }, + { name: 'chat (rich, 80 msgs)', route: '/chat/perf-chat-0', q: base }, + { name: 'chat after live reply', route: '/chat/perf-chat-0', q: { ...base, live: '40' }, wait: 7000 }, + { name: 'chat + terminal panel', route: '/chat/perf-chat-0', q: { ...base, terminals: '1' }, keys: ['Alt+t'] }, + { name: 'chat list running', route: '/chat/perf-chat-1', q: { ...base, activity: '1' } }, + { name: 'settings', route: '/settings', q: {} }, +]; + +const INSTRUMENT = ` + (() => { + const raf = window.requestAnimationFrame.bind(window); + window.__raf = 0; + window.__stacks = {}; + window.requestAnimationFrame = (cb) => { + window.__raf++; + if (window.__trace) { const k = (new Error().stack || '').split(String.fromCharCode(10)).slice(2, 14).join(String.fromCharCode(10)); window.__stacks[k] = (window.__stacks[k] || 0) + 1; } + return raf(cb); + }; + window.__long = []; + try { + new PerformanceObserver((list) => { + for (const e of list.getEntries()) window.__long.push(Math.round(e.duration)); + }).observe({ type: 'longtask', buffered: true }); + } catch (_) {} + })();`; + +const server = await serveBuild(opts.build); +const browser = await openBrowser({ gpu: Boolean(opts.gpu) }); +const { send, on } = browser; +const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; +const errors = []; +on('Runtime.exceptionThrown', (p) => errors.push(String(p.exceptionDetails?.exception?.description ?? p.exceptionDetails?.text).slice(0, 200))); + +const MODIFIERS = { Alt: 1, Control: 2, Meta: 4, Shift: 8 }; +async function key(chord) { + const parts = chord.split('+'); + const name = parts.pop(); + const modifiers = parts.reduce((bits, part) => bits | MODIFIERS[part], 0); + const code = /^[a-z]$/i.test(name) ? `Key${name.toUpperCase()}` : name; + const k = { modifiers, key: name, code, windowsVirtualKeyCode: name.toUpperCase().charCodeAt(0) }; + for (const part of parts) await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: part, code: `${part}Left`, modifiers }); + await send('Input.dispatchKeyEvent', { type: 'rawKeyDown', ...k }); + await send('Input.dispatchKeyEvent', { type: 'keyUp', ...k }); + for (const part of parts) await send('Input.dispatchKeyEvent', { type: 'keyUp', key: part, code: `${part}Left`, modifiers: 0 }); +} + +function url(route, q) { + const u = new URL('/', server.origin); + u.searchParams.set('route', route); + u.searchParams.set('theme', 'light'); + for (const [k, v] of Object.entries(q)) u.searchParams.set(k, v); + return u.href; +} +async function load(route, q) { + await send('Page.navigate', { url: url(route, q) }); + for (let i = 0; i < 200; i++) { + if (await evaluate('!!document.querySelector("flutter-view, flt-glass-pane")')) break; + await delay(50); + } + await delay(2500); +} +async function idleFrames(seconds) { + await evaluate('window.__raf = 0'); + await delay(seconds * 1000); + return evaluate('window.__raf'); +} +async function heapMb() { + await send('HeapProfiler.collectGarbage'); + await delay(300); + await send('HeapProfiler.collectGarbage'); + const { usedSize } = await send('Runtime.getHeapUsage'); + return Math.round(usedSize / 1e5) / 10; +} +// Object counts by constructor name from a heap snapshot (after a GC). +async function census() { + let chunks = ''; + const off = on('HeapProfiler.addHeapSnapshotChunk', (p) => { chunks += p.chunk; }); + await send('HeapProfiler.collectGarbage'); + await send('HeapProfiler.takeHeapSnapshot', { reportProgress: false }); + off?.(); + const snap = JSON.parse(chunks); + const f = snap.snapshot.meta.node_fields; + const stride = f.length, iName = f.indexOf('name'), iSize = f.indexOf('self_size'), iType = f.indexOf('type'); + const types = snap.snapshot.meta.node_types[0]; + const counts = new Map(); + for (let i = 0; i < snap.nodes.length; i += stride) { + const type = types[snap.nodes[i + iType]]; + const name = type === 'object' ? snap.strings[snap.nodes[i + iName]] : `(${type})`; + const c = counts.get(name) ?? [0, 0]; + c[0]++; c[1] += snap.nodes[i + iSize]; + counts.set(name, c); + } + return counts; +} +let lastCensus = null; +const go = (route) => evaluate(`history.pushState(null, '', ${JSON.stringify(route)}); dispatchEvent(new PopStateEvent('popstate', { state: null })); true`); + +try { + await send('Page.enable'); + await send('Runtime.enable'); + await send('HeapProfiler.enable'); + await send('Page.addScriptToEvaluateOnNewDocument', { source: INSTRUMENT }); + await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] }); + const [w, h] = opts.size.split('x').map(Number); + await send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: false }); + const only = opts.only?.split(';'); + for (const s of IDLE.filter((s) => !only || only.includes(s.name))) { + await load(s.route, s.q); + for (const k of s.keys ?? []) { await key(k); await delay(1200); } + if (s.wait) await delay(s.wait); + await delay(1500); + if (opts.stacks) await evaluate('window.__stacks = {}; window.__trace = true'); + const n = await idleFrames(Number(opts.idle)); + console.log(`idle ${s.name.padEnd(26)} frames requested in ${opts.idle}s: ${n}`); + if (opts.stacks && n > 0) { + const stacks = await evaluate('window.__trace = false; Object.entries(window.__stacks).sort((a, b) => b[1] - a[1]).slice(0, 3)'); + for (const [stack, count] of stacks) console.log(` ${count}x\n${stack}`); + } + } + const rounds = Number(opts.session); + if (rounds > 0) { + await load('/chat/perf-chat-0', { ...base, live: '60', terminals: '1' }); + await evaluate('window.__long = []'); + console.log(`session start heap ${await heapMb()} MB`); + for (let r = 1; r <= rounds; r++) { + const t0 = Date.now(); + for (let c = 0; c < CHATS; c++) { + await go(`/chat/perf-chat-${c}`); + await delay(c === r % CHATS ? 7500 : 900); + } + await key('Alt+t'); await delay(800); + for (const route of ['/runs', '/runs/7', '/pipelines', '/search', '/chat/perf-chat-0']) { + await go(route); await delay(900); + } + await key('Alt+t'); await delay(800); + const long = await evaluate('window.__long.splice(0)'); + const idle = await idleFrames(3); + if (opts.census && (r === 2 || r === rounds)) { + const now = await census(); + if (lastCensus) { + const grown = [...now].map(([k, [n, b]]) => [k, n - (lastCensus.get(k)?.[0] ?? 0), b - (lastCensus.get(k)?.[1] ?? 0)]) + .sort((a, b) => b[2] - a[2]).slice(0, 25); + console.log(`census growth rounds 2..${r} (name, count, bytes):`); + for (const g of grown) console.log(` ${g[0].slice(0, 60)} ${g[1]} ${g[2]}`); + } + lastCensus = now; + } + console.log(`round ${r}: heap ${await heapMb()} MB, long tasks ${long.length} (max ${Math.max(0, ...long)} ms), idle frames/3s ${idle}, ${Math.round((Date.now() - t0) / 1000)} s`); + } + } + if (errors.length) console.log('page errors (first 5):', [...new Set(errors)].slice(0, 5)); +} finally { + await browser.close().catch(() => {}); + await server.close(); +}