feat(app): send the recorded session export-only repair

This commit is contained in:
2026-10-22 10:12:45 +01:00
parent 7aa7007aee
commit d78712aa77
14 changed files with 441 additions and 9 deletions
@@ -0,0 +1,143 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/error_reason.dart';
import '../../../ui/adaptive/host.dart';
import '../data/runs_repository.dart';
/// The browser client's export-only repair wording, kept verbatim.
const sessionExportRepairLabel = 'Retry export only';
const sessionExportRepairBusyLabel = 'Exporting…';
const sessionExportRepairHelp =
'Read the exact recorded session again. Does not rerun the stage or its '
'tools.';
/// Stable test/semantics keys shared by the action and its refusal.
const sessionExportRepairKey = ValueKey<String>('session-export-repair');
const sessionExportRepairErrorKey = ValueKey<String>(
'session-export-repair-error',
);
/// The server's refusal, verbatim. Only a blank error gets a generic sentence,
/// so a refused repair never looks like a completed one.
String describeSessionExportRepairError(Object error) => describeErrorReason(
error,
fallback: 'The server did not repair the session export.',
);
/// Reads one recorded visit's exact session again through the web client's
/// `repair_session_export` request (`run_id`, `export_sequence`).
///
/// The control is disabled while the visit is active or the request is in
/// flight, so one choice sends one request. The recorded export state is not
/// changed locally: only the server's reply, delivered through [onRepaired], is
/// shown next. A refusal stays visible beside the unchanged state and never
/// claims success.
class SessionExportRepairAction extends StatefulWidget {
const SessionExportRepairAction({
super.key,
required this.runId,
required this.sequence,
required this.gateway,
required this.running,
required this.onRepaired,
});
final num runId;
/// The visit's own recorded sequence, exactly as it is sent on the wire.
final int sequence;
final ApiGateway gateway;
/// True while the step or run is active, so reading its session is unsafe.
final bool running;
/// Receives the server's whole run detail; nothing is inferred from a reply
/// without one.
final ValueChanged<JsonMap> onRepaired;
@override
State<SessionExportRepairAction> createState() =>
_SessionExportRepairActionState();
}
class _SessionExportRepairActionState extends State<SessionExportRepairAction> {
bool _sending = false;
String? _refusal;
@override
void didUpdateWidget(covariant SessionExportRepairAction oldWidget) {
super.didUpdateWidget(oldWidget);
// A reply or refusal belongs to the visit it was sent for, never to the
// visit the pane happens to show next.
if (oldWidget.runId != widget.runId ||
oldWidget.sequence != widget.sequence) {
_sending = false;
_refusal = null;
}
}
bool _owns(num runId, int sequence) =>
mounted && widget.runId == runId && widget.sequence == sequence;
Future<void> _send() async {
if (_sending || widget.running) return;
final runId = widget.runId;
final sequence = widget.sequence;
setState(() {
_sending = true;
_refusal = null;
});
try {
final detail = await RunsRepository(
widget.gateway,
).repairSessionExport(runId, sequence);
if (!_owns(runId, sequence)) return;
widget.onRepaired(detail);
} catch (error) {
if (!_owns(runId, sequence)) return;
setState(() => _refusal = describeSessionExportRepairError(error));
} finally {
if (_owns(runId, sequence)) setState(() => _sending = false);
}
}
@override
Widget build(BuildContext context) {
final enabled = !_sending && !widget.running;
final label = _sending
? sessionExportRepairBusyLabel
: sessionExportRepairLabel;
final cupertino = usesCupertinoHost(context);
final button = cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: enabled ? _send : null,
child: Text(label),
)
: TextButton(
onPressed: enabled ? _send : null,
child: Text(label),
);
return Column(
key: sessionExportRepairKey,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (cupertino)
button
else
Tooltip(message: sessionExportRepairHelp, child: button),
if (_refusal != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Semantics(
liveRegion: true,
child: Text(_refusal!, key: sessionExportRepairErrorKey),
),
),
],
);
}
}
@@ -41,6 +41,26 @@ class RunsRepository {
'run_detail',
);
/// Reads the exact recorded visit again; it never reruns its stage or tools.
///
/// The body is the web client's `repair_session_export` request: the run and
/// the recorded export sequence only. The reply is the whole run detail, so
/// the caller can show exactly what the server recorded next.
Future<JsonMap> repairSessionExport(num id, int sequence) async {
if (id is! int || id < 1 || sequence < 1) {
throw const RunsRepositoryException(
'An exact run and visit are required.',
);
}
return _required(
await _gateway.call('repair_session_export', {
'run_id': id,
'export_sequence': sequence,
}),
'run_detail',
);
}
Future<JsonMap> retryRun(
num id, {
required String requestKey,
@@ -20,6 +20,8 @@ Widget buildCupertinoRunDetail({
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
}) {
final theme = CupertinoTheme.of(context);
@@ -29,6 +31,8 @@ Widget buildCupertinoRunDetail({
copying: copying,
copyStatus: copyStatus,
onCopy: onCopy,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
header: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -20,6 +20,8 @@ Widget buildMaterialRunDetail({
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
}) {
final theme = Theme.of(context);
@@ -29,6 +31,8 @@ Widget buildMaterialRunDetail({
copying: copying,
copyStatus: copyStatus,
onCopy: onCopy,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
header: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -36,6 +36,8 @@ class RunDetailTabs extends StatefulWidget {
required this.copying,
required this.copyStatus,
required this.onCopy,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
});
@@ -50,6 +52,11 @@ class RunDetailTabs extends StatefulWidget {
final String? copyStatus;
final VoidCallback onCopy;
/// The shared gateway and accepted-detail fold used by the visit session's
/// export-only repair. Tabs never open their own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// The configured server origin used to resolve a recorded session export
/// through the landed safe-link helper. Blank leaves relative urls unresolved.
final String configuredEndpoint;
@@ -180,6 +187,8 @@ class _RunDetailTabsState extends State<RunDetailTabs> {
visitIndex: index,
step: step,
runSteps: detailRunSteps(widget.run),
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
cupertino: widget.cupertino,
onClose: _closeVisit,
@@ -64,6 +64,8 @@ class _RunDetailViewState extends State<RunDetailView> {
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
configuredEndpoint: endpoint,
)
: buildMaterialRunDetail(
@@ -76,6 +78,8 @@ class _RunDetailViewState extends State<RunDetailView> {
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
configuredEndpoint: endpoint,
);
},
@@ -21,6 +21,8 @@ class RunVisitPane extends StatefulWidget {
required this.visitIndex,
required this.step,
required this.runSteps,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
required this.cupertino,
required this.onClose,
@@ -35,6 +37,12 @@ class RunVisitPane extends StatefulWidget {
final JsonMap step;
final List<JsonMap> runSteps;
/// The app's shared gateway and the accepted-detail fold for the session's
/// export-only repair. The visit never opens its own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
final String configuredEndpoint;
final bool cupertino;
final VoidCallback onClose;
@@ -106,6 +114,8 @@ class _RunVisitPaneState extends State<RunVisitPane> {
visitIndex: widget.visitIndex,
stageKey: widget.visit.stage,
runSteps: widget.runSteps,
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
cupertino: widget.cupertino,
),
@@ -88,6 +88,8 @@ Widget runVisitSectionBody({
required int visitIndex,
required String stageKey,
required List<JsonMap> runSteps,
required ApiGateway gateway,
required ValueChanged<JsonMap> onRunChanged,
required String configuredEndpoint,
required bool cupertino,
}) {
@@ -115,7 +117,10 @@ Widget runVisitSectionBody({
);
case RunVisitSection.session:
return RunVisitSession(
run: run,
step: step,
gateway: gateway,
onRunChanged: onRunChanged,
configuredEndpoint: configuredEndpoint,
);
case RunVisitSection.definition:
@@ -6,6 +6,8 @@ import '../../../ui/adaptive/host.dart';
import '../../artifacts/domain/artifact_record.dart';
import '../../artifacts/domain/artifact_url.dart';
import '../../artifacts/ui/artifact_external_open.dart';
import '../actions/session_export_repair_action.dart';
import 'run_detail_visit_recorded.dart';
import 'run_detail_visit_session_state.dart';
/// The visit's recorded session pointer, its recorded export state and, when
@@ -15,19 +17,28 @@ import 'run_detail_visit_session_state.dart';
/// repair, a still-running session and a failed one each report what the server
/// recorded. Complete, partial, missing, skipped, repair and unrecognised
/// states each keep the server's own word and diagnostic; recorded repair
/// attempts and their open-option labels are shown read-only and make no
/// request. The open goes through the landed safe-link helper: the recorded url
/// is resolved by [resolveArtifactUrl] and passed to [openArtifactExternally]
/// without being fetched, rewritten or previewed. A refusal is reported.
/// attempts and their open-option labels stay read-only. An export whose
/// recorded evidence is not complete offers the web client's export-only
/// repair, which sends that exact visit's recorded sequence and keeps this
/// recorded state until the server replies. The open goes through the landed
/// safe-link helper: the recorded url is resolved by [resolveArtifactUrl] and
/// passed to [openArtifactExternally] without being fetched, rewritten or
/// previewed. A refusal is reported.
class RunVisitSession extends StatefulWidget {
const RunVisitSession({
super.key,
required this.run,
required this.step,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
this.openExternal = openArtifactExternally,
});
final JsonMap run;
final JsonMap step;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
final String configuredEndpoint;
final ArtifactExternalOpen openExternal;
@@ -57,6 +68,8 @@ class _RunVisitSessionState extends State<RunVisitSession> {
: resolveArtifactUrl(widget.configuredEndpoint, export.artifact.url);
final note = export?.statusNote;
final fact = session.exportFact;
final sequence = recordedCount(widget.step['sequence']);
final repair = _repairAction(session, sequence);
final showReason =
export != null &&
fact?.reason != null &&
@@ -84,6 +97,7 @@ class _RunVisitSessionState extends State<RunVisitSession> {
const Text(visitSessionEndpointMissing)
else
_openButton(export.artifact, resolved),
if (repair != null) repair,
if (_status != null)
Padding(
padding: const EdgeInsets.only(top: 8),
@@ -130,8 +144,36 @@ class _RunVisitSessionState extends State<RunVisitSession> {
);
}
/// Recorded repair attempts, in the pane's own fact rows. Nothing here is a
/// control: the repair request belongs to its own action and is not wired.
/// The export-only repair option: offered only for a visit whose recorded
/// session identity and sequence can be read again, and whose recorded export
/// is not already verified complete. The visit's own recorded sequence is
/// sent, never a guessed one.
Widget? _repairAction(VisitSessionState session, int sequence) {
final runId = recordedCount(widget.run['id']);
if (runId < 1 || sequence < 1 || session.sessionId == null) return null;
final export = session.export;
if (export != null && export.isComplete) return null;
final status = recordedText(widget.step['status']);
final runStatus = recordedText(widget.run['status']);
final pending = recordedCount(widget.run['export_pending_sequence']);
final running =
widget.step['agent_active'] == true ||
status == 'running' ||
status == 'queued' ||
runStatus == 'running' ||
runStatus == 'queued' ||
(runStatus == 'waiting' && pending != sequence);
return SessionExportRepairAction(
runId: runId,
sequence: sequence,
gateway: widget.gateway,
running: running,
onRepaired: widget.onRunChanged,
);
}
/// Recorded repair attempts, in the pane's own fact rows. These labels stay
/// read-only; the request is made only by [SessionExportRepairAction].
List<Widget> _repairFacts(List<VisitSessionRepair> repairs) {
final facts = <Widget>[];
for (var index = 0; index < repairs.length; index += 1) {
@@ -4,6 +4,7 @@ import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
import 'run_detail_graph_support.dart';
import 'run_detail_visit_support.dart';
Future<void> pumpSessionExport(WidgetTester tester, JsonMap step) =>
@@ -11,7 +12,10 @@ Future<void> pumpSessionExport(WidgetTester tester, JsonMap step) =>
MaterialApp(
home: Scaffold(
body: RunVisitSession(
run: visitRunFor(step),
step: step,
gateway: RunDetailFakeGateway(visitRunFor(step)),
onRunChanged: (_) {},
configuredEndpoint: 'ws://example.test/connect',
),
),
@@ -69,7 +69,13 @@ void main() {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
body: RunVisitSession(
run: visitRunFor(step),
step: step,
gateway: RunDetailFakeGateway(visitRunFor(step)),
onRunChanged: (_) {},
configuredEndpoint: '',
),
),
),
);
@@ -88,7 +94,13 @@ void main() {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
body: RunVisitSession(
run: visitRunFor(step),
step: step,
gateway: RunDetailFakeGateway(visitRunFor(step)),
onRunChanged: (_) {},
configuredEndpoint: '',
),
),
),
);
@@ -108,7 +120,10 @@ void main() {
MaterialApp(
home: Scaffold(
body: RunVisitSession(
run: visitRunFixture(),
step: firstVisitStep(visitRunFixture()),
gateway: RunDetailFakeGateway(visitRunFixture()),
onRunChanged: (_) {},
configuredEndpoint: 'ws://example.test/connect',
openExternal: (uri) async {
opened = uri;
@@ -131,7 +146,10 @@ void main() {
MaterialApp(
home: Scaffold(
body: RunVisitSession(
run: visitRunFixture(),
step: firstVisitStep(visitRunFixture()),
gateway: RunDetailFakeGateway(visitRunFixture()),
onRunChanged: (_) {},
configuredEndpoint: 'ws://example.test/connect',
openExternal: (uri) async => false,
),
@@ -82,6 +82,14 @@ JsonMap visitRunFixture({
JsonMap firstVisitStep(JsonMap run) =>
(run['steps'] as List).first as Map<String, dynamic>;
/// The run that owns [step], for direct session-pane pumps outside the detail.
JsonMap visitRunFor(JsonMap step, {String status = 'succeeded'}) =>
<String, dynamic>{
'id': 77,
'status': status,
'steps': <dynamic>[step],
};
Future<void> openVisit(
WidgetTester tester,
RunDetailTestPlatform platform, {
@@ -95,7 +95,13 @@ void main() {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
body: RunVisitSession(
run: visitRunFor(step),
step: step,
gateway: RunDetailFakeGateway(visitRunFor(step)),
onRunChanged: (_) {},
configuredEndpoint: '',
),
),
),
);
@@ -0,0 +1,155 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/runs/actions/session_export_repair_action.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart';
import 'run_detail_visit_support.dart';
typedef _RepairHandler =
Future<JsonMap> Function(String type, JsonMap fields);
class _RepairGateway implements ApiGateway {
_RepairGateway(this.handler);
final _RepairHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final copy = Map<String, dynamic>.from(fields);
calls.add((type: type, fields: copy));
return handler(type, copy);
}
Iterable<({String type, JsonMap fields})> get repairs =>
calls.where((call) => call.type == 'repair_session_export');
}
/// A recorded visit whose export failed, so the repair option is offered.
JsonMap partialRun() {
final run = visitRunFixture();
final step = firstVisitStep(run);
step['session_export'] = <String, dynamic>{
'html': 'session.html',
'status': 'failed',
'messages': 0,
'diagnostic': 'The first export failed.',
};
return run;
}
/// A reply whose recorded repair is verified complete and openable.
JsonMap repairedRun() {
final run = visitRunFixture();
final step = firstVisitStep(run);
step['session_export_repairs'] = <dynamic>[
<String, dynamic>{
'html': 'session-repair-1.html',
'status': 'complete',
'messages': 3,
'html_bytes': 900,
},
];
(step['artifacts'] as List).add(<String, dynamic>{
'name': 'session-repair-1.html',
'url': 'https://example.test/artifacts/session-repair-1.html',
'content_type': 'text/html',
'size_bytes': 900,
});
return run;
}
class _SessionHost extends StatefulWidget {
const _SessionHost({required this.run, required this.gateway});
final JsonMap run;
final _RepairGateway gateway;
@override
State<_SessionHost> createState() => _SessionHostState();
}
class _SessionHostState extends State<_SessionHost> {
late JsonMap _run = widget.run;
@override
Widget build(BuildContext context) => Scaffold(
body: RunVisitSession(
run: _run,
step: firstVisitStep(_run),
gateway: widget.gateway,
onRunChanged: (detail) => setState(() => _run = detail),
configuredEndpoint: 'ws://example.test/connect',
),
);
}
Future<void> pumpSession(
WidgetTester tester,
_RepairGateway gateway, {
JsonMap? run,
}) => tester.pumpWidget(
MaterialApp(
home: _SessionHost(run: run ?? partialRun(), gateway: gateway),
),
);
void main() {
testWidgets('sends the recorded run and visit exactly once', (tester) async {
final reply = Completer<JsonMap>();
final gateway = _RepairGateway((_, _) => reply.future);
await pumpSession(tester, gateway);
expect(find.text('Retry export only'), findsOneWidget);
await tester.tap(find.text('Retry export only'));
await tester.pump();
expect(gateway.repairs, hasLength(1));
expect(gateway.repairs.single.fields, {
'run_id': 77,
'export_sequence': 1,
});
// The recorded export state is kept until the server replies.
expect(find.text('partial'), findsOneWidget);
expect(find.text('complete'), findsNothing);
expect(find.text('Exporting…'), findsOneWidget);
await tester.tap(find.text('Exporting…'), warnIfMissed: false);
await tester.pump();
expect(gateway.repairs, hasLength(1));
reply.complete({'run_detail': repairedRun()});
await tester.pumpAndSettle();
// The accepted reply names the verified repair the pane must now show.
expect(find.text('repair'), findsOneWidget);
expect(find.text('complete · 3 messages.'), findsOneWidget);
expect(find.text('Open session-repair-1.html'), findsOneWidget);
expect(find.text('Retry export only'), findsNothing);
});
testWidgets('a refusal is shown and the recorded state is unchanged', (
tester,
) async {
final gateway = _RepairGateway(
(_, _) => Future<JsonMap>.error(StateError('The session is gone.')),
);
await pumpSession(tester, gateway);
await tester.tap(find.text('Retry export only'));
await tester.pumpAndSettle();
expect(find.byKey(sessionExportRepairErrorKey), findsOneWidget);
expect(find.text('The session is gone.'), findsOneWidget);
expect(find.text('partial'), findsOneWidget);
expect(find.text('complete'), findsNothing);
// The option is still available: a refusal is not a success.
expect(find.text('Retry export only'), findsOneWidget);
});
}