Refresh runs from nested wire events and foreground resume

This commit is contained in:
2026-11-07 23:46:02 +00:00
parent 8e041af6ad
commit 7287ba35c9
11 changed files with 274 additions and 59 deletions
+3 -3
View File
@@ -292,15 +292,15 @@ class _PipelinesAppState extends State<PipelinesApp>
} }
if (connection != ConnectionKind.connected) return; if (connection != ConnectionKind.connected) return;
// A return to the foreground refreshes only the visible list. Detail routes // Foreground return refreshes the visible Runs list and selected detail.
// (including pipeline definitions and run visits) keep their current data. // Pipeline definitions retain their current data while being inspected.
if (_delegate.hasTransientRoute || _isEditingText) return; if (_delegate.hasTransientRoute || _isEditingText) return;
final route = _delegate.route; final route = _delegate.route;
if (route.kind == AppRouteKind.pipelines && if (route.kind == AppRouteKind.pipelines &&
route.pipelineId == null && route.pipelineId == null &&
route.stageKey == null) { route.stageKey == null) {
setState(() => _pipelinesRefresh++); setState(() => _pipelinesRefresh++);
} else if (route.kind == AppRouteKind.runs && route.runId == null) { } else if (route.kind == AppRouteKind.runs) {
setState(() => _runsRefresh++); setState(() => _runsRefresh++);
} }
} }
@@ -130,6 +130,7 @@ class AttentionController extends ChangeNotifier {
/// identity never emits. /// identity never emits.
void observeFrame(JsonMap frame) { void observeFrame(JsonMap frame) {
if (_disposed) return; if (_disposed) return;
frame = runEventPayload(frame);
final transition = _detector.observe(frame, dismissed: _dismissed); final transition = _detector.observe(frame, dismissed: _dismissed);
if (transition != null) _transitions.add(transition); if (transition != null) _transitions.add(transition);
final folded = foldRunEvent(_rows, frame); final folded = foldRunEvent(_rows, frame);
@@ -1,6 +1,13 @@
import '../../../core/api_gateway.dart'; import '../../../core/api_gateway.dart';
import 'run_step_evidence.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'}; const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
bool isTerminalRunStatus(dynamic status) => bool isTerminalRunStatus(dynamic status) =>
+4 -7
View File
@@ -156,15 +156,12 @@ class _RunsScreenState extends State<RunsScreen> {
} }
} }
} }
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(); 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) { if (widget.initialRunId != oldWidget.initialRunId) {
final id = widget.initialRunId; final id = widget.initialRunId;
if (id == null) { if (id == null) {
@@ -65,7 +65,7 @@ class RunsController extends ChangeNotifier {
_subscription = frames.listen((frame) { _subscription = frames.listen((frame) {
switch (frame['type']) { switch (frame['type']) {
case 'run_event': case 'run_event':
_event(frame); _event(runEventPayload(frame));
case 'runs_removed': case 'runs_removed':
// Another client deleted these runs. // Another client deleted these runs.
removeRuns(removedRunIds(frame)); removeRuns(removedRunIds(frame));
@@ -97,7 +97,7 @@ class RunsController extends ChangeNotifier {
if (initialId != null) await select(initialId); 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 /// The selection is kept, so a reconnect refreshes in place instead of
/// discarding the detail the operator had open. /// discarding the detail the operator had open.
+39
View File
@@ -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.
@@ -225,25 +225,67 @@ void main() {
await tester.pump(); await tester.pump();
}); });
testWidgets('foreground resume does not refresh an open run detail', ( testWidgets(
tester, 'foreground resume refreshes an open run detail without navigation',
) async { (tester) async {
final channel = FakeChannel()..readyCompleter.complete(); final channel = FakeChannel()..readyCompleter.complete();
final provider = routeProvider(); final provider = PlatformRouteInformationProvider(
final client = PipelinesClient(channelFactory: (_) => channel); initialRouteInformation: RouteInformation(uri: Uri.parse('/runs/1')),
await pumpApp(tester, provider: provider, client: client); );
await replyPipelines(tester, channel, PipelineFixture()); addTearDown(provider.dispose);
provider.routerReportsNewRouteInformation( final client = PipelinesClient(channelFactory: (_) => channel);
RouteInformation(uri: Uri.parse('/runs/1')), await pumpApp(tester, provider: provider, client: client);
type: RouteInformationReportingType.navigate, await waitForRequest(tester, channel, 'list_runs');
); final initialList = pipelineRequest(channel, 'list_runs')!;
await tester.pump(); channel.incoming.add(
final before = countType(channel, 'list_runs'); 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); expect(countType(channel, 'list_runs'), before + 1);
await tester.pumpWidget(const SizedBox.shrink()); final refreshedList = await waitForLaterRequest(
await tester.pump(); 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();
},
);
} }
@@ -157,35 +157,42 @@ void main() {
}); });
group('pushed frames and reconnect', () { group('pushed frames and reconnect', () {
test('a live frame that becomes failed appears without a reload', () async { test(
final controller = _controller(MemoryAttentionStore()); 'wire envelopes update attention and deduplicate transitions',
addTearDown(controller.dispose); () async {
await controller.load(); final controller = _controller(MemoryAttentionStore());
controller.seedRows([_run(1, 'running')]); addTearDown(controller.dispose);
expect(controller.entries, isEmpty); await controller.load();
controller.seedRows([_run(1, 'running')]);
expect(controller.entries, isEmpty);
controller.observeFrame({ controller.observeFrame({
'type': 'run_event', 'type': 'run_event',
'run_id': 1, 'run_event': {
'status': 'failed', 'run_id': 1,
'diagnostic': 'Stage 4 failed', 'status': 'failed',
'finished_at': _at(const Duration(minutes: 1)), 'diagnostic': 'Stage 4 failed',
}); 'finished_at': _at(const Duration(minutes: 1)),
},
});
expect(controller.entries.map((entry) => entry.key), ['1:Failed']); expect(controller.entries.map((entry) => entry.key), ['1:Failed']);
expect(controller.entries.single.detail, 'Stage 4 failed'); expect(controller.entries.single.detail, 'Stage 4 failed');
expect(controller.transitions.map((item) => item.key), ['1:Failed']); expect(controller.transitions.map((item) => item.key), ['1:Failed']);
// The same state again is not a new transition. // The same state again is not a new transition.
controller.observeFrame({ controller.observeFrame({
'type': 'run_event', 'type': 'run_event',
'run_id': 1, 'run_event': {
'status': 'failed', 'run_id': 1,
'diagnostic': 'Stage 4 failed', 'status': 'failed',
}); 'diagnostic': 'Stage 4 failed',
expect(controller.entries, hasLength(1)); },
expect(controller.transitions, hasLength(1)); });
}); expect(controller.entries, hasLength(1));
expect(controller.transitions, hasLength(1));
},
);
test('a live frame for a new run can create its own summary', () async { test('a live frame for a new run can create its own summary', () async {
final controller = _controller(MemoryAttentionStore()); final controller = _controller(MemoryAttentionStore());
@@ -46,6 +46,67 @@ void main() {
gateway.framesController.close(); 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<void>.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<void>.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<void>.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<void>.delayed(Duration.zero);
expect(controller.detail?['summary'], 'Fresh completion evidence');
},
);
test('late selection response cannot replace latest selection', () async { test('late selection response cannot replace latest selection', () async {
final first = controller.select(1); final first = controller.select(1);
final second = controller.select(2); final second = controller.select(2);
@@ -53,6 +53,7 @@ Widget _materialScreen(
int? initialRunId, int? initialRunId,
int? initialPipelineId, int? initialPipelineId,
int syncToken = 0, int syncToken = 0,
int listRefreshToken = 0,
ValueChanged<int>? onRunSelected, ValueChanged<int>? onRunSelected,
ValueChanged<int?>? onBack, ValueChanged<int?>? onBack,
ValueChanged<int?>? onPipelineFilterChanged, ValueChanged<int?>? onPipelineFilterChanged,
@@ -63,6 +64,7 @@ Widget _materialScreen(
initialRunId: initialRunId, initialRunId: initialRunId,
initialPipelineId: initialPipelineId, initialPipelineId: initialPipelineId,
syncToken: syncToken, syncToken: syncToken,
listRefreshToken: listRefreshToken,
onRunSelected: onRunSelected, onRunSelected: onRunSelected,
onBack: onBack, onBack: onBack,
onPipelineFilterChanged: onPipelineFilterChanged, onPipelineFilterChanged: onPipelineFilterChanged,
@@ -307,6 +309,42 @@ void main() {
expect(find.byKey(const ValueKey('run-row-1')), findsOneWidget); 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( testWidgets(
'wide Cupertino host keeps list and detail bars while pending', 'wide Cupertino host keeps list and detail bars while pending',
(tester) async { (tester) async {
+25 -2
View File
@@ -47,7 +47,7 @@ JsonMap probeRunDetail() => {
'id': 7, 'id': 7,
'title': 'Release train run', 'title': 'Release train run',
'name': 'release-train', 'name': 'release-train',
'status': 'succeeded', 'status': _liveRunStatus ?? 'succeeded',
'created_at': '2026-10-20T08:12:00Z', 'created_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:42:00Z', 'finished_at': '2026-10-20T08:42:00Z',
'workspace': '/srv/probe/release', '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 /// `?running=1`: run 8 executes, started 3m 50s before the page loaded, so a
/// capture shows its duration ticking. Absent by default. /// capture shows its duration ticking. Absent by default.
DateTime? _runningSince; DateTime? _runningSince;
String? _liveRunStatus;
/// `?html=1` adds `release-dashboard.html` to run 7's build visit; the capture /// `?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). /// serves its bytes from the build directory (see notes/artifact-fullscreen.md).
@@ -213,7 +214,7 @@ List<JsonMap> probeRuns() => [
'id': 7, 'id': 7,
'title': 'Release train run', 'title': 'Release train run',
'name': 'release-train', 'name': 'release-train',
'status': 'succeeded', 'status': _liveRunStatus ?? 'succeeded',
'created_at': '2026-10-20T08:12:00Z', 'created_at': '2026-10-20T08:12:00Z',
'finished_at': '2026-10-20T08:42:00Z', 'finished_at': '2026-10-20T08:42:00Z',
'pipeline_id': 24, 'pipeline_id': 24,
@@ -627,6 +628,7 @@ class _FixtureChannel implements WebSocketChannel {
_FixtureChannel(); _FixtureChannel();
final _incoming = StreamController<dynamic>(); final _incoming = StreamController<dynamic>();
Timer? _runCompletion;
late final _FixtureSink _sink = _FixtureSink(this); late final _FixtureSink _sink = _FixtureSink(this);
@override @override
@@ -651,6 +653,25 @@ class _FixtureChannel implements WebSocketChannel {
if (data is! String) return; if (data is! String) return;
final decoded = jsonDecode(data); final decoded = jsonDecode(data);
if (decoded is! Map<String, dynamic>) return; if (decoded is! Map<String, dynamic>) 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 reply = probeReply(decoded);
final followUps = perfChatFollowUps(decoded); final followUps = perfChatFollowUps(decoded);
final subscribe = decoded['chat_subscribe']; final subscribe = decoded['chat_subscribe'];
@@ -673,6 +694,7 @@ class _FixtureChannel implements WebSocketChannel {
} }
Future<void> close() async { Future<void> close() async {
_runCompletion?.cancel();
if (!_incoming.isClosed) await _incoming.close(); if (!_incoming.isClosed) await _incoming.close();
} }
@@ -734,6 +756,7 @@ Future<void> main() async {
AnimationSpeedController.instance.restore(), AnimationSpeedController.instance.restore(),
]); ]);
final params = fixtureParams(); final params = fixtureParams();
if (params['liveRun'] == '1') _liveRunStatus = 'running';
installHostProbes(params); installHostProbes(params);
// `?connect=1` (native only) opens the real launch flow with no saved // `?connect=1` (native only) opens the real launch flow with no saved
// server, so the Connect screen can be reviewed without any server. // server, so the Connect screen can be reviewed without any server.