From 7287ba35c93ac9240c46126ea9852517d7c037dd Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 7 Nov 2026 23:46:02 +0000 Subject: [PATCH] Refresh runs from nested wire events and foreground resume --- app/lib/application/pipelines_app.dart | 6 +- .../runtime/attention_controller.dart | 1 + app/lib/features/runs/domain/run_events.dart | 7 ++ app/lib/features/runs/screen.dart | 11 +-- app/lib/features/runs/ui/runs_controller.dart | 4 +- app/notes/runs-live-refresh.md | 39 +++++++++ .../app_lifecycle_reconnect_test.dart | 80 ++++++++++++++----- .../runtime/attention_controller_test.dart | 59 ++++++++------ .../runs/ui/runs_controller_test.dart | 61 ++++++++++++++ .../features/runs/ui/runs_screen_test.dart | 38 +++++++++ app/tool/search_selection_probe_entry.dart | 27 ++++++- 11 files changed, 274 insertions(+), 59 deletions(-) create mode 100644 app/notes/runs-live-refresh.md diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 2b3701bb..df666c97 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -292,15 +292,15 @@ class _PipelinesAppState extends State } if (connection != ConnectionKind.connected) return; - // A return to the foreground refreshes only the visible list. Detail routes - // (including pipeline definitions and run visits) keep their current data. + // Foreground return refreshes the visible Runs list and selected detail. + // Pipeline definitions retain their current data while being inspected. if (_delegate.hasTransientRoute || _isEditingText) return; final route = _delegate.route; if (route.kind == AppRouteKind.pipelines && route.pipelineId == null && route.stageKey == null) { setState(() => _pipelinesRefresh++); - } else if (route.kind == AppRouteKind.runs && route.runId == null) { + } else if (route.kind == AppRouteKind.runs) { setState(() => _runsRefresh++); } } diff --git a/app/lib/features/attention/runtime/attention_controller.dart b/app/lib/features/attention/runtime/attention_controller.dart index 697152ba..b73af2ec 100644 --- a/app/lib/features/attention/runtime/attention_controller.dart +++ b/app/lib/features/attention/runtime/attention_controller.dart @@ -130,6 +130,7 @@ class AttentionController extends ChangeNotifier { /// identity never emits. void observeFrame(JsonMap frame) { if (_disposed) return; + frame = runEventPayload(frame); final transition = _detector.observe(frame, dismissed: _dismissed); if (transition != null) _transitions.add(transition); final folded = foldRunEvent(_rows, frame); diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index d24917aa..2e066781 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -1,6 +1,13 @@ import '../../../core/api_gateway.dart'; import 'run_step_evidence.dart'; +/// ApiGateway preserves wire envelopes; callers may also supply an extracted +/// delta. Return the payload intact so sparse and future fields survive. +JsonMap runEventPayload(JsonMap frame) { + final event = frame['run_event']; + return event is JsonMap ? event : frame; +} + const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'}; bool isTerminalRunStatus(dynamic status) => diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 0cbea267..dddf8a1d 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -156,15 +156,12 @@ class _RunsScreenState extends State { } } } - if (widget.syncToken != oldWidget.syncToken) { + // Both reconnect and foreground/launch invalidation refresh the retained + // selection as well as the list. Coalesce tokens delivered in one rebuild. + if (widget.syncToken != oldWidget.syncToken || + widget.listRefreshToken != oldWidget.listRefreshToken) { controller.resync(); } - // A launch accepted on another destination invalidates the list only. The - // route change below selects the returned run separately, so this is the - // one fresh server read that makes the new row appear. - if (widget.listRefreshToken != oldWidget.listRefreshToken) { - controller.load(); - } if (widget.initialRunId != oldWidget.initialRunId) { final id = widget.initialRunId; if (id == null) { diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index e12c8c8a..99a5b8e7 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -65,7 +65,7 @@ class RunsController extends ChangeNotifier { _subscription = frames.listen((frame) { switch (frame['type']) { case 'run_event': - _event(frame); + _event(runEventPayload(frame)); case 'runs_removed': // Another client deleted these runs. removeRuns(removedRunIds(frame)); @@ -97,7 +97,7 @@ class RunsController extends ChangeNotifier { if (initialId != null) await select(initialId); } - /// Re-reads the list and the open detail after the socket was replaced. + /// Re-reads the list and open detail after reconnect or foreground return. /// /// The selection is kept, so a reconnect refreshes in place instead of /// discarding the detail the operator had open. diff --git a/app/notes/runs-live-refresh.md b/app/notes/runs-live-refresh.md new file mode 100644 index 00000000..3ba5bd43 --- /dev/null +++ b/app/notes/runs-live-refresh.md @@ -0,0 +1,39 @@ +# Runs live refresh (run 276) + +The shared transport forwards raw envelopes. A read-only subscription to the +existing local server for run 276 returned `type: run_event` with the summary +nested under `run_event`, followed by the `subscribe` acknowledgement. Runs and +attention previously treated the outer envelope as a delta. Existing controller +fixtures used extracted deltas, so they missed the production shape. + +`runEventPayload` now extracts the payload unchanged at both consumers. Sparse +fields and future fields are not reconstructed or dropped by extraction; existing +folding, generation ownership, deletion tombstones, filters and debouncing remain +in charge. Real-envelope tests cover a new row, progress, completion detail refresh, +and attention transition deduplication. No polling or new subscriptions were added. + +Foreground return also skipped open run routes, and a list invalidation refreshed +only the list. Runs routes now invalidate on resume and the retained screen resyncs +both list and selected detail. Simultaneous connection/refresh tokens coalesce to +one resync. Editing/transient-route guards remain. The app lifecycle regression +starts at an actual run URL and completes the initial requests before resuming. + +Focused watchdog: 53 passed across runs controller/screen, app lifecycle/session, +and attention controller. Analyzer clean. Logs: `/tmp/memwatch/out.J0eKmT` and +`/var/folders/jp/q0qvjyg54fl_c5vhhk1ylz2m0000gn/T/flutter-analyze.k496jJ`. +The subsequent controller-only rerun passed 18 tests and also exercises the +completion evidence fetch (`/tmp/memwatch/out.L2WhC1`). +No real runs were started or changed; the inspection socket was closed. No server +restart, commit, deploy, or pipeline definition change. No rendered capture here; +the manager owns consolidated browser verification and delivery. The failed first +implementation stage recorded a partial file capture; these direct edits are the +actual source evidence for recovery, not a claim that its capture became complete. + +## Isolated release acceptance + +Rebased the focused source delta on 8e041af6 in a separate release worktree, +preserving the original edits. The current candidate passed 47 focused tests +(`/tmp/memwatch/out.tMxVnO`) and analysis (`flutter-analyze.0FMxzq`). +The full-app capture fixture adds opt-in `liveRun=1`: run 7 starts running, +then a server-shaped nested completion envelope arrives seven seconds after +list subscription. This changes fixture data only, with no live run mutations. diff --git a/app/test/application/app_lifecycle_reconnect_test.dart b/app/test/application/app_lifecycle_reconnect_test.dart index 45bea855..8a59339c 100644 --- a/app/test/application/app_lifecycle_reconnect_test.dart +++ b/app/test/application/app_lifecycle_reconnect_test.dart @@ -225,25 +225,67 @@ void main() { await tester.pump(); }); - testWidgets('foreground resume does not refresh an open run detail', ( - tester, - ) async { - final channel = FakeChannel()..readyCompleter.complete(); - final provider = routeProvider(); - final client = PipelinesClient(channelFactory: (_) => channel); - await pumpApp(tester, provider: provider, client: client); - await replyPipelines(tester, channel, PipelineFixture()); - provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri.parse('/runs/1')), - type: RouteInformationReportingType.navigate, - ); - await tester.pump(); - final before = countType(channel, 'list_runs'); + testWidgets( + 'foreground resume refreshes an open run detail without navigation', + (tester) async { + final channel = FakeChannel()..readyCompleter.complete(); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')), + ); + addTearDown(provider.dispose); + final client = PipelinesClient(channelFactory: (_) => channel); + await pumpApp(tester, provider: provider, client: client); + await waitForRequest(tester, channel, 'list_runs'); + final initialList = pipelineRequest(channel, 'list_runs')!; + channel.incoming.add( + jsonEncode({ + 'id': initialList['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'title': 'Live run', 'status': 'running'}, + ], + }), + ); + await waitForRequest(tester, channel, 'get_run'); + final initialDetail = pipelineRequest(channel, 'get_run')!; + channel.incoming.add( + jsonEncode({ + 'id': initialDetail['id'], + 'type': 'run', + 'run_detail': {'id': 1, 'title': 'Live run', 'status': 'running'}, + }), + ); + await tester.pump(); + final before = countType(channel, 'list_runs'); - await resume(tester); + await resume(tester); - expect(countType(channel, 'list_runs'), before); - await tester.pumpWidget(const SizedBox.shrink()); - await tester.pump(); - }); + expect(countType(channel, 'list_runs'), before + 1); + final refreshedList = await waitForLaterRequest( + tester, + channel, + 'list_runs', + initialList['id'] as String, + ); + channel.incoming.add( + jsonEncode({ + 'id': refreshedList['id'], + 'type': 'runs', + 'runs': [ + {'id': 1, 'title': 'Live run', 'status': 'succeeded'}, + ], + }), + ); + final refreshedDetail = await waitForLaterRequest( + tester, + channel, + 'get_run', + initialDetail['id'] as String, + ); + expect(refreshedDetail['run_id'], 1); + expect(countType(channel, 'subscribe'), 1); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + }, + ); } diff --git a/app/test/features/attention/runtime/attention_controller_test.dart b/app/test/features/attention/runtime/attention_controller_test.dart index adcbd87d..13bd8b4f 100644 --- a/app/test/features/attention/runtime/attention_controller_test.dart +++ b/app/test/features/attention/runtime/attention_controller_test.dart @@ -157,35 +157,42 @@ void main() { }); group('pushed frames and reconnect', () { - test('a live frame that becomes failed appears without a reload', () async { - final controller = _controller(MemoryAttentionStore()); - addTearDown(controller.dispose); - await controller.load(); - controller.seedRows([_run(1, 'running')]); - expect(controller.entries, isEmpty); + test( + 'wire envelopes update attention and deduplicate transitions', + () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'running')]); + expect(controller.entries, isEmpty); - controller.observeFrame({ - 'type': 'run_event', - 'run_id': 1, - 'status': 'failed', - 'diagnostic': 'Stage 4 failed', - 'finished_at': _at(const Duration(minutes: 1)), - }); + controller.observeFrame({ + 'type': 'run_event', + 'run_event': { + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + 'finished_at': _at(const Duration(minutes: 1)), + }, + }); - expect(controller.entries.map((entry) => entry.key), ['1:Failed']); - expect(controller.entries.single.detail, 'Stage 4 failed'); - expect(controller.transitions.map((item) => item.key), ['1:Failed']); + expect(controller.entries.map((entry) => entry.key), ['1:Failed']); + expect(controller.entries.single.detail, 'Stage 4 failed'); + expect(controller.transitions.map((item) => item.key), ['1:Failed']); - // The same state again is not a new transition. - controller.observeFrame({ - 'type': 'run_event', - 'run_id': 1, - 'status': 'failed', - 'diagnostic': 'Stage 4 failed', - }); - expect(controller.entries, hasLength(1)); - expect(controller.transitions, hasLength(1)); - }); + // The same state again is not a new transition. + controller.observeFrame({ + 'type': 'run_event', + 'run_event': { + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + }, + }); + expect(controller.entries, hasLength(1)); + expect(controller.transitions, hasLength(1)); + }, + ); test('a live frame for a new run can create its own summary', () async { final controller = _controller(MemoryAttentionStore()); diff --git a/app/test/features/runs/ui/runs_controller_test.dart b/app/test/features/runs/ui/runs_controller_test.dart index 463af923..6de73f8f 100644 --- a/app/test/features/runs/ui/runs_controller_test.dart +++ b/app/test/features/runs/ui/runs_controller_test.dart @@ -46,6 +46,67 @@ void main() { gateway.framesController.close(); }); + test( + 'wire envelopes update new rows, progress and selected completion', + () async { + controller.listen(gateway.frames); + final load = controller.load(); + gateway.listReply(0, [ + {'id': 1, 'pipeline_id': 7, 'name': 'test', 'status': 'running'}, + ]); + await load; + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.setPipeline(7); + controller.setQuery('test'); + void event(JsonMap value) => gateway.framesController.add({ + 'type': 'run_event', + 'run_event': value, + }); + event({ + 'run_id': 2, + 'pipeline_id': 7, + 'name': 'test new', + 'status': 'running', + 'completed_steps': 0, + }); + event({'run_id': 1, 'status': 'running', 'completed_steps': 3}); + await Future.delayed(Duration.zero); + expect(controller.runs, hasLength(2)); + expect( + controller.runs.firstWhere((run) => run['id'] == 1)['completed_steps'], + 3, + ); + expect(controller.detail?['completed_steps'], 3); + event({'run_id': 1, 'status': 'succeeded', 'completed_steps': 4}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + expect( + controller.runs.firstWhere((run) => run['id'] == 1)['status'], + 'succeeded', + ); + expect(controller.selectedRunId, 1); + expect(controller.pipelineId, 7); + expect(controller.query, 'test'); + expect( + gateway.listCalls, + 1, + reason: 'valid deltas require no list reload', + ); + await Future.delayed(const Duration(milliseconds: 180)); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, { + 'id': 1, + 'status': 'succeeded', + 'completed_steps': 4, + 'summary': 'Fresh completion evidence', + }); + await Future.delayed(Duration.zero); + expect(controller.detail?['summary'], 'Fresh completion evidence'); + }, + ); + test('late selection response cannot replace latest selection', () async { final first = controller.select(1); final second = controller.select(2); diff --git a/app/test/features/runs/ui/runs_screen_test.dart b/app/test/features/runs/ui/runs_screen_test.dart index 9761a61f..60483824 100644 --- a/app/test/features/runs/ui/runs_screen_test.dart +++ b/app/test/features/runs/ui/runs_screen_test.dart @@ -53,6 +53,7 @@ Widget _materialScreen( int? initialRunId, int? initialPipelineId, int syncToken = 0, + int listRefreshToken = 0, ValueChanged? onRunSelected, ValueChanged? onBack, ValueChanged? onPipelineFilterChanged, @@ -63,6 +64,7 @@ Widget _materialScreen( initialRunId: initialRunId, initialPipelineId: initialPipelineId, syncToken: syncToken, + listRefreshToken: listRefreshToken, onRunSelected: onRunSelected, onBack: onBack, onPipelineFilterChanged: onPipelineFilterChanged, @@ -307,6 +309,42 @@ void main() { expect(find.byKey(const ValueKey('run-row-1')), findsOneWidget); }); + for (final reconnect in [false, true]) { + testWidgets('foreground refresh resyncs detail (reconnect: $reconnect)', ( + tester, + ) async { + await tester.pumpWidget(_materialScreen(gateway, initialRunId: 2)); + await _mountList(tester, gateway); + gateway.replyDetail(2, 0, {'id': 2, 'title': 'Beta run'}); + await tester.pump(); + await tester.pumpWidget( + _materialScreen( + gateway, + initialRunId: 2, + syncToken: reconnect ? 1 : 0, + listRefreshToken: 1, + ), + ); + expect( + gateway.listRequests, + hasLength(2), + reason: 'simultaneous reconnect and foreground refresh coalesce', + ); + gateway.replyList(1, _runs); + await tester.pump(); + expect(gateway.detailRequests[2], hasLength(2)); + expect( + runDetailText('Beta run'), + findsOneWidget, + reason: 'the selected detail remains visible during refresh', + ); + gateway.replyDetail(2, 1, {'id': 2, 'title': 'Fresh detail'}); + await tester.pump(); + await tester.pump(); + expect(runDetailText('Fresh detail'), findsOneWidget); + }); + } + testWidgets( 'wide Cupertino host keeps list and detail bars while pending', (tester) async { diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 1ac3c700..7be1acfc 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -47,7 +47,7 @@ JsonMap probeRunDetail() => { 'id': 7, 'title': 'Release train run', 'name': 'release-train', - 'status': 'succeeded', + 'status': _liveRunStatus ?? 'succeeded', 'created_at': '2026-10-20T08:12:00Z', 'finished_at': '2026-10-20T08:42:00Z', 'workspace': '/srv/probe/release', @@ -150,6 +150,7 @@ int _fillerStepCount = 0; /// `?running=1`: run 8 executes, started 3m 50s before the page loaded, so a /// capture shows its duration ticking. Absent by default. DateTime? _runningSince; +String? _liveRunStatus; /// `?html=1` adds `release-dashboard.html` to run 7's build visit; the capture /// serves its bytes from the build directory (see notes/artifact-fullscreen.md). @@ -213,7 +214,7 @@ List probeRuns() => [ 'id': 7, 'title': 'Release train run', 'name': 'release-train', - 'status': 'succeeded', + 'status': _liveRunStatus ?? 'succeeded', 'created_at': '2026-10-20T08:12:00Z', 'finished_at': '2026-10-20T08:42:00Z', 'pipeline_id': 24, @@ -627,6 +628,7 @@ class _FixtureChannel implements WebSocketChannel { _FixtureChannel(); final _incoming = StreamController(); + Timer? _runCompletion; late final _FixtureSink _sink = _FixtureSink(this); @override @@ -651,6 +653,25 @@ class _FixtureChannel implements WebSocketChannel { if (data is! String) return; final decoded = jsonDecode(data); if (decoded is! Map) return; + if (_liveRunStatus == 'running' && decoded['type'] == 'list_runs') { + _runCompletion ??= Timer(const Duration(seconds: 7), () { + _liveRunStatus = 'succeeded'; + if (!_incoming.isClosed) { + _incoming.add( + jsonEncode({ + 'type': 'run_event', + 'run_event': { + 'run_id': 7, + 'status': 'succeeded', + 'executing': false, + 'completed_steps': 3, + 'finished_at': '2026-10-20T08:42:00Z', + }, + }), + ); + } + }); + } final reply = probeReply(decoded); final followUps = perfChatFollowUps(decoded); final subscribe = decoded['chat_subscribe']; @@ -673,6 +694,7 @@ class _FixtureChannel implements WebSocketChannel { } Future close() async { + _runCompletion?.cancel(); if (!_incoming.isClosed) await _incoming.close(); } @@ -734,6 +756,7 @@ Future main() async { AnimationSpeedController.instance.restore(), ]); final params = fixtureParams(); + if (params['liveRun'] == '1') _liveRunStatus = 'running'; installHostProbes(params); // `?connect=1` (native only) opens the real launch flow with no saved // server, so the Connect screen can be reviewed without any server.