diff --git a/app/PARITY.md b/app/PARITY.md index 831e6d56..46f3fc27 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -34,12 +34,12 @@ or scratch servers only, never real operator sessions/runs/workflows. | Retry/restart | Preview controls in the run detail | accepted new-run navigation, stale/refusal handling verified in the app | | Human decisions | Preview waiting card/native prompt/exact accepted reply | attention/action URL entry; no production decision answered during tests | | Run graph | Preview: Graph tab with legend, recorded-stage selection, canvas pan/zoom and an expanded view | live activity pulse | -| Timeline/recorded visit pane | Preview: selection opens the recorded facts with Input/Output/Artifacts/Session/Definition sections and exact absence wording | per-visit session-repair choices (separate row) | +| Timeline/recorded visit pane | Preview: selection opens the recorded facts with Input/Output/Artifacts/Session/Definition sections and exact absence wording | full per-visit session-repair choices (separate row); the export-only retry lives in Session | | Changes/diffs | Preview via run detail | settled-run aggregate gate, recorded file/diff/close/back verified in the real app; per-visit capture entry and paging remain | | Artifact groups | Preview: recorded groups in run detail, per-visit drill-down, turn documents (input/memory/output, session.html) in the run gallery | video/HTML preview remains external-only | | Artifact preview | Preview: image + markdown/text in-app through the chat renderer, paging, honest unsupported/external/HTTP states | video and HTML remain external-only | | Artifact actions | Preview: external Open, Copy link, download and native share carry the recorded name/MIME bytes; progress, cancel, HTTP failure and unsupported-share states | OS share/download on Android/iOS remain unverified until the final build | -| Session audit/export repair facts | Source: the visit Session section reports the recorded export state (complete, partial, missing, skipped, repair, or the server's verbatim unknown word), the recorded reason for a present export, and read-only repair attempt/option labels; `session.html` opens externally | publish a preview of these captures; the `repair_session_export` action and per-visit repair choices | +| Session audit/export repair facts | Source: the visit Session section reports the recorded export state (complete, partial, missing, skipped, repair, or the server's verbatim unknown word), the recorded reason for a present export, read-only repair attempt/option labels, and the export-only `repair_session_export` control for incomplete evidence; `session.html` opens externally | publish a preview of these captures, with rendered evidence of the control; full per-visit repair choices | | Chat session management | Preview list + open session; shared create/rename/star/close/reopen with server-refreshed rows and full-width row refusals; local hide/undo and this device's read watermark (open rows only; a closed row never shows `New`) | dismissible web action-failed report (refusals stay under their row until the next accepted action), web `Open` badge and active/deep-linked read suppression, live `New` marks from pushed chat events, hide closing an already-open conversation, create dialog in the shell, editable create title (the web fixes `New chat`) | | Chat history/live transport | Preview: `/chat` list and `/chat/:id` history, paging, live failure notice | run-detail-style reconnect verification in the real app, then composer integration | | Chat message surfaces | Preview: formatted assistant markdown (safe links/headings/lists/tables/fences), user text exact, disclosures plain | exact attachments, unknown-part rendering beyond retained placeholders | diff --git a/app/lib/features/runs/actions/session_export_repair_action.dart b/app/lib/features/runs/actions/session_export_repair_action.dart new file mode 100644 index 00000000..70fc59d6 --- /dev/null +++ b/app/lib/features/runs/actions/session_export_repair_action.dart @@ -0,0 +1,140 @@ +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('session-export-repair'); +const sessionExportRepairErrorKey = ValueKey( + '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 onRepaired; + + @override + State createState() => + _SessionExportRepairActionState(); +} + +class _SessionExportRepairActionState extends State { + 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 _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), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart index 6341a81f..a9430e03 100644 --- a/app/lib/features/runs/data/runs_repository.dart +++ b/app/lib/features/runs/data/runs_repository.dart @@ -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 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 retryRun( num id, { required String requestKey, diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index ea4f80b4..072195cc 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -20,6 +20,8 @@ Widget buildCupertinoRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required ApiGateway gateway, + required ValueChanged onRunChanged, required String configuredEndpoint, String? initialStageKey, int? initialVisit, @@ -31,6 +33,8 @@ Widget buildCupertinoRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + gateway: gateway, + onRunChanged: onRunChanged, configuredEndpoint: configuredEndpoint, initialStageKey: initialStageKey, initialVisit: initialVisit, diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 34bbca4e..d61c2d09 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -20,6 +20,8 @@ Widget buildMaterialRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required ApiGateway gateway, + required ValueChanged onRunChanged, required String configuredEndpoint, String? initialStageKey, int? initialVisit, @@ -31,6 +33,8 @@ Widget buildMaterialRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + gateway: gateway, + onRunChanged: onRunChanged, configuredEndpoint: configuredEndpoint, initialStageKey: initialStageKey, initialVisit: initialVisit, diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index cc03c320..65ca3c4e 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -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, this.initialStageKey, this.initialVisit, @@ -52,6 +54,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 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; @@ -244,6 +251,8 @@ class _RunDetailTabsState extends State { visitIndex: index, step: step, runSteps: detailRunSteps(widget.run), + gateway: widget.gateway, + onRunChanged: widget.onRunChanged, configuredEndpoint: widget.configuredEndpoint, cupertino: widget.cupertino, onClose: _closeVisit, diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index b5988b90..c1bcaea1 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -72,6 +72,8 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: true), + gateway: widget.gateway, + onRunChanged: widget.controller.acceptRunDetail, configuredEndpoint: endpoint, initialStageKey: widget.initialStageKey, initialVisit: widget.initialVisit, @@ -86,6 +88,8 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: false), + gateway: widget.gateway, + onRunChanged: widget.controller.acceptRunDetail, configuredEndpoint: endpoint, initialStageKey: widget.initialStageKey, initialVisit: widget.initialVisit, diff --git a/app/lib/features/runs/ui/run_detail_visit.dart b/app/lib/features/runs/ui/run_detail_visit.dart index 70602816..7510f250 100644 --- a/app/lib/features/runs/ui/run_detail_visit.dart +++ b/app/lib/features/runs/ui/run_detail_visit.dart @@ -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 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 onRunChanged; + final String configuredEndpoint; final bool cupertino; final VoidCallback onClose; @@ -106,6 +114,8 @@ class _RunVisitPaneState extends State { visitIndex: widget.visitIndex, stageKey: widget.visit.stage, runSteps: widget.runSteps, + gateway: widget.gateway, + onRunChanged: widget.onRunChanged, configuredEndpoint: widget.configuredEndpoint, cupertino: widget.cupertino, ), diff --git a/app/lib/features/runs/ui/run_detail_visit_export.dart b/app/lib/features/runs/ui/run_detail_visit_export.dart index 7b3731a1..f3960bb7 100644 --- a/app/lib/features/runs/ui/run_detail_visit_export.dart +++ b/app/lib/features/runs/ui/run_detail_visit_export.dart @@ -108,6 +108,28 @@ String? detailVisitSessionIdentity(JsonMap step) { return evidence == null ? null : recordedText(evidence['session_id']); } +/// The session identity the web client requires before it offers an +/// export-only repair: the visit's own `session_id` or its original +/// `session_export.session_id`. A repair attempt's identity is not enough, and +/// neither is an identity read only from that repair, exactly as the web's +/// availability check does not widen the case. +String? detailVisitRepairIdentity(JsonMap step) { + final direct = recordedText(step['session_id']); + if (direct != null) return direct; + final original = step['session_export']; + return original is Map ? recordedText(original['session_id']) : null; +} + +/// Whether the web audit pane offers the export-only repair for a document it +/// can open: only when recorded evidence is incomplete or truncated. +/// +/// A legacy `session.html` selected by the no-evidence fallback has nothing to +/// compare and gets no control. A `complete` status without the server's +/// verified evidence stays [VisitSessionExportState.partial] here, so it keeps +/// the control; that is this client's deliberate, stricter rule. +bool visitSessionExportNeedsRepair(VisitSessionExport export) => + export.truncated || (export.status != null && !export.isComplete); + /// The visit's recorded export document, or null when no recorded export name /// is present in the inventory. /// diff --git a/app/lib/features/runs/ui/run_detail_visit_sections.dart b/app/lib/features/runs/ui/run_detail_visit_sections.dart index 7f3e0321..24465a0d 100644 --- a/app/lib/features/runs/ui/run_detail_visit_sections.dart +++ b/app/lib/features/runs/ui/run_detail_visit_sections.dart @@ -88,6 +88,8 @@ Widget runVisitSectionBody({ required int visitIndex, required String stageKey, required List runSteps, + required ApiGateway gateway, + required ValueChanged 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: diff --git a/app/lib/features/runs/ui/run_detail_visit_session.dart b/app/lib/features/runs/ui/run_detail_visit_session.dart index 838feaec..e6793cfe 100644 --- a/app/lib/features/runs/ui/run_detail_visit_session.dart +++ b/app/lib/features/runs/ui/run_detail_visit_session.dart @@ -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,29 @@ 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 incomplete or truncated 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; a legacy `session.html` +/// with no recorded evidence offers no control, exactly as the web does. 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 onRunChanged; final String configuredEndpoint; final ArtifactExternalOpen openExternal; @@ -57,6 +69,8 @@ class _RunVisitSessionState extends State { : 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 +98,7 @@ class _RunVisitSessionState extends State { const Text(visitSessionEndpointMissing) else _openButton(export.artifact, resolved), + ?repair, if (_status != null) Padding( padding: const EdgeInsets.only(top: 8), @@ -130,8 +145,39 @@ class _RunVisitSessionState extends State { ); } - /// 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 + /// evidence is incomplete or truncated (or which has no openable document at + /// all). A legacy `session.html` chosen only by the no-evidence fallback has + /// no evidence to repair and keeps the web's absence of the control. 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) return null; + if (detailVisitRepairIdentity(widget.step) == null) return null; + final export = session.export; + if (export != null && !visitSessionExportNeedsRepair(export)) 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 _repairFacts(List repairs) { final facts = []; for (var index = 0; index < repairs.length; index += 1) { diff --git a/app/notes/R4-session-export.md b/app/notes/R4-session-export.md index c0389e27..6fbc0e30 100644 --- a/app/notes/R4-session-export.md +++ b/app/notes/R4-session-export.md @@ -21,7 +21,8 @@ Completeness is not inferred: it requires `status == "complete"`, positive `messages` and `html_bytes`, no truncation and no diagnostic. A complete status without that evidence is `partial`; a legacy `session.html` with no evidence is `unknown`, never `complete`. Repairs are shown even when the main export is -complete. No `repair_session_export` request is sent or advertised. +complete. This slice sent no request; the export-only `repair_session_export` +control landed later (see `notes/session-export-repair.md`). ## Review fixes (visit 2) @@ -143,8 +144,9 @@ narrow-layout constraint recorded in `notes/R4-visit.md`, not new to this change remains portable (Material/Cupertino theme roles and plain text layout only). - No authenticated server or production run was touched; fixtures only. The preview is not published to 8096. -- `repair_session_export` remains unwired, and the repair-option label remains - inert text by design. +- The export-only `repair_session_export` control landed later and is described + in `notes/session-export-repair.md`; full per-visit repair choices remain + unwired, and the repair-option label remains inert text by design. - Artifact matching still selects by recorded name only, as it did before this change; web additionally filters repairs by session/backend/directory and checks `size_bytes == html_bytes`. Inherited, not changed here. diff --git a/app/notes/session-export-repair.md b/app/notes/session-export-repair.md new file mode 100644 index 00000000..6ec354a4 --- /dev/null +++ b/app/notes/session-export-repair.md @@ -0,0 +1,79 @@ +# Visit Session export-only repair + +## Delivered + +The Timeline visit pane's Session section offers the web client's export-only +session repair for that exact visit: + +- **Control** — `Retry export only` in a native `TextButton` (Material) or + `CupertinoButton` (Cupertino); `Exporting…` while the request is pending. + Disabled while the visit/run is active or a request is pending, so one + choice sends one request. +- **Request** — `RunsRepository.repairSessionExport` sends + `repair_session_export` with exactly `run_id` and the visit's recorded + `export_sequence` and requires `run_detail` in the reply, matching + `web/src/repository.js` and the Go protocol. No choice id is invented: the + visit's own recorded sequence is the choice. +- **Reply** — the accepted run detail is folded through + `RunsController.acceptRunDetail`, so the pane re-reads the recorded + repair/export facts. Nothing is mutated optimistically. +- **Refusal** — the server's reason is shown verbatim beside the unchanged + recorded state; the control remains available and no success word appears. +- **Scope of state** — in-flight/refusal state is per `run:sequence`; + changing visits clears it and a late reply for another visit is ignored. + +## Availability rule (recorded decision) + +The web inserts the control in two places of `auditSession` +(`web/src/views/runDetail.js:361-388`): when there is no openable artifact at +all, and when recorded evidence exists with a non-complete status or a +truncated document. The app now mirrors that: + +- no document at all plus the web's identity (`step.session_id` or + `step.session_export.session_id`) and a positive sequence → offered; +- present document → offered only when + `visitSessionExportNeedsRepair(export)` is true (truncated, or a recorded + status that is not verified complete); +- a legacy `session.html` selected only by the no-evidence fallback → **not** + offered, matching the web (nothing to compare, and the server's ownership + join would likely refuse it). + +Deliberate difference from the web, preserved: this client treats a recorded +`complete` status without the server's positive `messages`/`html_bytes`, +untruncated and diagnostic-free evidence as `partial`, so that document keeps +the control. The app does not widen identity to an id read only from repair +evidence; the web does not either. + +## Review fixes (visit 2) + +- Suppressed the control for the legacy no-evidence `session.html` and added + Material/Cupertino regression coverage. +- Fixed the two analyzer findings: `?repair,` null-aware element and a private + test helper. +- `dart format` applied to the changed files. +- Updated `PARITY.md` and `notes/R4-session-export.md`, which still said the + command was unwired. +- Added coverage for active/`waiting` gating, complete-export suppression, + visit-change state clearing, the Cupertino control and "no other request". + +## Known nonblocking gaps + +- In-flight state is widget-local: leaving the Session section and returning + before the reply allows a second tap. The web keeps a page-level `run:seq` + pending set. The normal live path still converges through the server's + `session_export_updated` event and the scheduled `get_run`. +- A reply completing after the pane unmounts is dropped; the same server event + re-reads the run. +- Artifact matching is by name only, ignoring `size_bytes == html_bytes` and + repair session/backend/directory filters (documented in + `notes/R4-session-export.md`). Inherited. +- Full per-visit repair choices remain unwired. + +## Verification + +- `flutter analyze` — No issues found. +- `flutter test test/features/runs` — 212 passed. +- `flutter test` — 1335 passed. +- `flutter build web` — built. +- No browser interaction/capture, Android/iOS build or device check was run. + Mobile remains unverified. diff --git a/app/test/features/runs/ui/run_detail_visit_session_export_test.dart b/app/test/features/runs/ui/run_detail_visit_session_export_test.dart index 5aded8ec..c95b5dca 100644 --- a/app/test/features/runs/ui/run_detail_visit_session_export_test.dart +++ b/app/test/features/runs/ui/run_detail_visit_session_export_test.dart @@ -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 pumpSessionExport(WidgetTester tester, JsonMap step) => @@ -11,7 +12,10 @@ Future 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', ), ), diff --git a/app/test/features/runs/ui/run_detail_visit_session_test.dart b/app/test/features/runs/ui/run_detail_visit_session_test.dart index c5ba50fc..079f5eb3 100644 --- a/app/test/features/runs/ui/run_detail_visit_session_test.dart +++ b/app/test/features/runs/ui/run_detail_visit_session_test.dart @@ -19,6 +19,8 @@ void main() { expect(find.text('sess-1'), findsOneWidget); expect(find.text('Open session.html'), findsOneWidget); + // No recorded export evidence, so the web offers no export-only repair. + expect(find.text('Retry export only'), findsNothing); expect( find.textContaining('not available in the artifact inventory'), findsNothing, @@ -69,7 +71,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: '', + ), ), ), ); @@ -79,6 +87,8 @@ void main() { findsOneWidget, ); expect(find.textContaining('Open '), findsNothing); + // No openable document at all is the web's other repair branch. + expect(find.text('Retry export only'), findsOneWidget); step['session_export'] = { 'html': 'session.html', @@ -88,7 +98,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 +124,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 +150,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, ), diff --git a/app/test/features/runs/ui/run_detail_visit_support.dart b/app/test/features/runs/ui/run_detail_visit_support.dart index 04759aaa..f894a016 100644 --- a/app/test/features/runs/ui/run_detail_visit_support.dart +++ b/app/test/features/runs/ui/run_detail_visit_support.dart @@ -82,6 +82,14 @@ JsonMap visitRunFixture({ JsonMap firstVisitStep(JsonMap run) => (run['steps'] as List).first as Map; +/// The run that owns [step], for direct session-pane pumps outside the detail. +JsonMap visitRunFor(JsonMap step, {String status = 'succeeded'}) => + { + 'id': 77, + 'status': status, + 'steps': [step], + }; + Future openVisit( WidgetTester tester, RunDetailTestPlatform platform, { diff --git a/app/test/features/runs/ui/run_detail_visit_test.dart b/app/test/features/runs/ui/run_detail_visit_test.dart index c91dc1f8..f8a84128 100644 --- a/app/test/features/runs/ui/run_detail_visit_test.dart +++ b/app/test/features/runs/ui/run_detail_visit_test.dart @@ -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: '', + ), ), ), ); diff --git a/app/test/features/runs/ui/run_session_repair_action_test.dart b/app/test/features/runs/ui/run_session_repair_action_test.dart new file mode 100644 index 00000000..3d05e399 --- /dev/null +++ b/app/test/features/runs/ui/run_session_repair_action_test.dart @@ -0,0 +1,271 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +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 Function(String type, JsonMap fields); + +class _RepairGateway implements ApiGateway { + _RepairGateway(this.handler); + + final _RepairHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.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'] = { + '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'] = [ + { + 'html': 'session-repair-1.html', + 'status': 'complete', + 'messages': 3, + 'html_bytes': 900, + }, + ]; + (step['artifacts'] as List).add({ + '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 + void didUpdateWidget(covariant _SessionHost oldWidget) { + super.didUpdateWidget(oldWidget); + // A test that swaps the recorded run must show the new visit, exactly as + // the detail does when the operator selects another one. + if (!identical(widget.run, oldWidget.run)) _run = widget.run; + } + + @override + Widget build(BuildContext context) => RunVisitSession( + run: _run, + step: firstVisitStep(_run), + gateway: widget.gateway, + onRunChanged: (detail) => setState(() => _run = detail), + configuredEndpoint: 'ws://example.test/connect', + ); +} + +Future _pumpSession( + WidgetTester tester, + _RepairGateway gateway, { + JsonMap? run, + bool cupertino = false, +}) { + final host = _SessionHost(run: run ?? partialRun(), gateway: gateway); + return tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: host)), + ) + : MaterialApp(home: Scaffold(body: host)), + ); +} + +TextButton _materialButton(WidgetTester tester) => tester.widget( + find.widgetWithText(TextButton, 'Retry export only'), +); + +void main() { + testWidgets('sends the recorded run and visit exactly once', (tester) async { + final reply = Completer(); + 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}); + // Nothing but the one repair request is sent. + expect(gateway.calls.map((call) => call.type), ['repair_session_export']); + // 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.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); + }); + + testWidgets('a legacy session.html with no recorded evidence keeps no ' + 'control', (tester) async { + final gateway = _RepairGateway( + (_, _) => Future.error(StateError('unexpected')), + ); + final run = partialRun(); + firstVisitStep(run).remove('session_export'); + await _pumpSession(tester, gateway, run: run); + + // The document still opens, but there is no evidence to repair. + expect(find.text('Open session.html'), findsOneWidget); + expect(find.text('Retry export only'), findsNothing); + expect(gateway.calls, isEmpty); + }); + + testWidgets('a verified complete export offers no repair', (tester) async { + final gateway = _RepairGateway( + (_, _) => Future.error(StateError('unexpected')), + ); + await _pumpSession(tester, gateway, run: visitRunFixture()); + + expect(find.text('complete'), findsOneWidget); + expect(find.text('Retry export only'), findsNothing); + }); + + testWidgets('the control is disabled while the visit or run is active', ( + tester, + ) async { + final gateway = _RepairGateway( + (_, _) => Future.error(StateError('unexpected')), + ); + + final active = partialRun(); + firstVisitStep(active)['agent_active'] = true; + await _pumpSession(tester, gateway, run: active); + expect(find.text('Retry export only'), findsOneWidget); + expect(_materialButton(tester).onPressed, isNull); + + final waiting = partialRun(); + waiting['status'] = 'waiting'; + waiting['export_pending_sequence'] = 2; + await _pumpSession(tester, gateway, run: waiting); + expect(_materialButton(tester).onPressed, isNull); + + // The same wait allows the repair when this visit's export is the pending + // one, exactly as the web client's availability check does. + waiting['export_pending_sequence'] = 1; + await _pumpSession(tester, gateway, run: waiting); + expect(_materialButton(tester).onPressed, isNotNull); + }); + + testWidgets('changing visits clears a pending repair and its reply', ( + tester, + ) async { + final first = Completer(); + final second = Completer(); + final gateway = _RepairGateway( + (_, fields) => + fields['export_sequence'] == 1 ? first.future : second.future, + ); + await _pumpSession(tester, gateway); + + await tester.tap(find.text('Retry export only')); + await tester.pump(); + expect(find.text('Exporting…'), findsOneWidget); + + final next = partialRun(); + firstVisitStep(next)['sequence'] = 2; + await _pumpSession(tester, gateway, run: next); + expect(find.text('Retry export only'), findsOneWidget); + expect(find.text('Exporting…'), findsNothing); + + await tester.tap(find.text('Retry export only')); + await tester.pump(); + expect(gateway.repairs.map((call) => call.fields['export_sequence']), [ + 1, + 2, + ]); + + // The first visit's late reply is not folded into the second visit. + first.complete({'run_detail': repairedRun()}); + await tester.pump(); + expect(find.text('repair'), findsNothing); + expect(find.text('partial'), findsOneWidget); + }); + + testWidgets('the Cupertino host uses a native Cupertino button', ( + tester, + ) async { + final gateway = _RepairGateway( + (_, _) => Future.error(StateError('unexpected')), + ); + await _pumpSession(tester, gateway, cupertino: true); + + expect( + find.widgetWithText(CupertinoButton, 'Retry export only'), + findsOneWidget, + ); + expect(find.widgetWithText(TextButton, 'Retry export only'), findsNothing); + }); +}