diff --git a/app/PARITY.md b/app/PARITY.md index 831e6d56..92c870fe 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -23,36 +23,36 @@ or scratch servers only, never real operator sessions/runs/workflows. | --- | --- | --- | | Shared transport/settings connection | Preview | foreground recovery, persisted endpoint boot, protocol warning, complete refresh semantics | | Native shell/run URLs | Preview: full route vocabulary including pipeline/version/stage, template detail, run visit/stage and decide, runs pipeline filter; pipeline and template links open their detail | run visit/stage and decide destinations still open the run only; no native OS deep-link registration | -| Pipeline list/filter/sort/detail/source/versions | Preview | latest summary metadata/miniatures, pinned detail URLs | -| Definition graph | Source nodes/layout/routes/edges; active canvas71 | compose measured native nodes+labels, graph tab, pan/zoom, expanded view, definition stage pane | +| Pipeline list/filter/sort/detail/source/versions | Preview: recorded row metadata and miniature, pinned detail URLs, filter/sort | none outstanding on the list/detail read path | +| Definition graph | Preview: measured native canvas, pipeline Graph tab, pan/zoom, expanded view, stage definition pane, pipeline stage deep link | live activity pulse on the run graph (tracked below) | | Start a pipeline | Preview: native Run action, prompt/workspace/notify dialog, pinned run request, response-loss check/retry | Report format, recent-directory suggestions, pending intent across a reload | | Templates | Preview: gallery/detail/source, create-only dialog via Settings → Templates, list invalidated on create | run-detail template link, create refresh verified against a real server | | Runs list/filter/sort/live fold | Preview | full time/status/provenance filters, recency/day groups, shell live/attention state | -| Run detail/input/output/copy/metrics | Preview | latest summary tabs/fields and exact empty/unknown states | +| Run detail/input/output/copy/metrics | Preview: Summary recorded fields with exact unknown wording, Input/Output/Copy, metrics | verify the remaining server-shape variants against fixtures | | Rename run | Preview | verified exact accepted title fold; no live production mutation tested | | Cancel run | Preview | exact confirm/server-accepted detail+list fold; production cancellation not tested | | 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 | Preview: recorded export state/reason, repair request with one-shot submit and refusal, session.html external-only | rendered browser evidence for the repair 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 | -| Chat activity/reasoning/tools | Source raw fields only | one activity line, compaction, native reasoning/tools overlays, lifecycle/input/output/error/duration/edit diff | +| Chat activity/reasoning/tools | Preview: one activity line, expanded native overlay with lifecycle/input/output/error/duration/edit diff | compaction wording variants | | Chat composer | Preview: field, Send/Stop, persisted draft, queued/refusal lines; one verified send in the real app flow | attachments, paste and slash palette remain | -| Chat attachments | Source: bounded draft model (1 MiB) and a native host file picker seam | composer chips, base64 send payload, paste, history reconciliation | +| Chat attachments | Preview: host picker, bounded 1 MiB draft, composer chips with removal, base64 wire payload | paste, send wiring in the composer, history reconciliation | | Chat permissions/questions | Source: native approval/risk and question cards in the conversation view | authenticated smoke with a real pending approval/question; live multi-client resolution; no production decision sent | -| Chat model/Info/background tasks | Source request facade | current-model selection, numeric Info modal (unknown !=0), bounded running shell pages | -| Chat commands/notices/scroll | Missing | slash palette/actions, unknown-command send-as-message, dismissible local notices, saved scroll/follow intent | -| Saved schedule list | Preview: Settings row, /schedules route, read-only list with exact timer provenance and pipeline identity | row opening a pipeline lands on its Summary section; no editing from this list | +| Chat model/Info/background tasks | Source: numeric Info sheet (unknown != 0) landed | current-model selection, bounded background-task pages | +| Chat commands/notices/scroll | Source: dismissible local notices landed | slash palette/actions, unknown-command send-as-message, saved scroll/follow intent | +| Saved schedule list | Preview: Settings row, /schedules route, read-only list; a row opens the owning pipeline detail (Summary by default) | authenticated smoke | | Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route | | Search | Preview: exact target model and navigation to pipeline, pinned version, run and recorded stage; unresolvable hits stay read-only | field/artifact hits open the run (their pane selection is a later slice) | -| Needs you | Preview: runs-list bell/count from the same list rows, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification permission/transition notices, authenticated preview smoke | +| Needs you | Preview: runs-list bell/count, native sheet, dismiss/clear persistence, live fold, transition notifications, Settings permission tile | authenticated preview smoke | | Notifications | Preview: Settings permission tile over live platform state, transition-only dedupe, tap opens the run | background question notices; permission/browser smoke only in fixtures | | Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | diff --git a/app/lib/application/app_router.dart b/app/lib/application/app_router.dart index 27c6401a..a99d08df 100644 --- a/app/lib/application/app_router.dart +++ b/app/lib/application/app_router.dart @@ -11,13 +11,24 @@ class AppRouteParser extends RouteInformationParser { @override Future parseRouteInformation( RouteInformation routeInformation, - ) async => AppRoute.parse(routeInformation.uri.path); + ) async => AppRoute.parse(routeLocation(routeInformation.uri)); @override RouteInformation restoreRouteInformation(AppRoute configuration) => - RouteInformation(uri: Uri(path: configuration.path)); + // The route's path already carries its query (`?visit=N`, `?action=…`). + // Parsing it keeps that query a query instead of percent-encoding the + // `?` into the path, which would make a reload read one bogus key. + RouteInformation(uri: Uri.parse(configuration.path)); } +/// The app-relative location of [uri]: its path plus query, without origin. +/// +/// [AppRoute.parse] understands this form, so a browser location such as +/// `/runs/7/stage/plan?visit=1` keeps the query instead of losing it to +/// `Uri.path`. A fragment is not part of an app route. +String routeLocation(Uri uri) => + uri.hasQuery ? '${uri.path}?${uri.query}' : uri.path; + /// Owns the app's current route and builds the shell for it. /// /// Route changes made by the operator go through [goTo]; the Router reports @@ -217,10 +228,21 @@ class AppRouterDelegate extends RouterDelegate with ChangeNotifier { /// The location a web launch starts at, or the Pipelines list elsewhere. /// -/// Only the path is meaningful to [AppRouteParser]; the origin stays out of -/// route configuration so a serialised route is always app-relative. +/// The origin stays out of route configuration so a serialised route is always +/// app-relative, but the path and its query are both part of the route: a +/// launch at `/runs/7/stage/plan?visit=1` must open exactly that visit. RouteInformation initialRouteInformation() { if (!kIsWeb) return RouteInformation(uri: Uri(path: '/pipelines')); - final path = Uri.base.path; - return RouteInformation(uri: Uri(path: path.isEmpty ? '/' : path)); + return routeInformationForLocation(Uri.base); +} + +/// The app-relative route information for a browser [base] location. +/// +/// Exposed for the boot test: [Uri.base] cannot be changed inside a widget +/// test, so the web launch seam is exercised through this function. +@visibleForTesting +RouteInformation routeInformationForLocation(Uri base) { + final path = base.path.isEmpty ? '/' : base.path; + final query = base.hasQuery ? '?${base.query}' : ''; + return RouteInformation(uri: Uri.parse('$path$query')); } diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 462ba921..524dbf78 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -83,10 +83,13 @@ class _PipelinesAppState extends State { ); // A malformed or unknown boot path renders Pipelines, so make the address // bar agree with the rendered destination instead of showing a dead link. - final initial = AppRoute.parse(_provider.value.uri.path); - if (_provider.value.uri.path != initial.path) { + // The comparison includes the query: `?visit=N` is part of the route, while + // a dropped or unknown query is canonicalised away. + final location = routeLocation(_provider.value.uri); + final initial = AppRoute.parse(location); + if (location != initial.path) { _provider.routerReportsNewRouteInformation( - RouteInformation(uri: Uri(path: initial.path)), + RouteInformation(uri: Uri.parse(initial.path)), type: RouteInformationReportingType.neglect, ); } @@ -218,6 +221,8 @@ class _PipelinesAppState extends State { session: _session, server: widget.server, initialRunId: route.runId, + initialStageKey: route.stageKey, + initialVisit: route.visit, listRefreshToken: _runsRefresh, notifications: _notifications, onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)), diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index fdef966e..e5270d88 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -19,6 +19,8 @@ class RunsDestination extends StatelessWidget { required this.session, required this.server, this.initialRunId, + this.initialStageKey, + this.initialVisit, this.onRunSelected, this.onBack, this.listRefreshToken = 0, @@ -28,6 +30,13 @@ class RunsDestination extends StatelessWidget { final AppSession session; final ServerEndpoint server; final int? initialRunId; + + /// The stage key and optional visit a `/runs/:id/stage/:key[?visit=N]` route + /// names. They reach the detail only through [RunsScreen]; the destination + /// does not read the route itself. + final String? initialStageKey; + final int? initialVisit; + final ValueChanged? onRunSelected; final VoidCallback? onBack; @@ -73,6 +82,8 @@ class RunsDestination extends StatelessWidget { Widget _runsScreen() => RunsScreen( gateway: session.gateway, initialRunId: initialRunId, + initialStageKey: initialStageKey, + initialVisit: initialVisit, syncToken: session.connectionEpoch, listRefreshToken: listRefreshToken, notifications: notifications, diff --git a/app/lib/features/chat/conversation/chat_composer_bar.dart b/app/lib/features/chat/conversation/chat_composer_bar.dart index 11fc5d7a..6f646a7d 100644 --- a/app/lib/features/chat/conversation/chat_composer_bar.dart +++ b/app/lib/features/chat/conversation/chat_composer_bar.dart @@ -4,6 +4,8 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import '../domain/chat_attachment_draft.dart'; +import '../domain/chat_attachment_picker.dart'; import '../ui/sessions/chat_adaptive.dart'; import 'chat_composer_controller.dart'; @@ -14,6 +16,9 @@ const String chatComposerPlaceholder = 'Message the agent… or / for commands'; const String chatSendLabel = 'Send'; const String chatStopLabel = 'Stop'; +/// The attach control's accessible name, verbatim from the web composer. +const String chatAttachLabel = 'Attach file'; + /// Shown while the reply says this prompt waits behind the running turn. const String chatQueuedNotice = 'Queued — it will send when the current turn finishes.'; @@ -24,13 +29,15 @@ const String chatQueuedNotice = /// The field owns only its [TextEditingController] and focus; the durable draft /// text lives in the composer controller, so a live transcript rebuild never /// replaces the operator's caret. Enter inserts a newline and Ctrl/Cmd+Enter -/// sends the plain message. Attachments and the slash palette are not part of -/// this slice. +/// sends the plain message. Picked files are memory-only chips: their names are +/// shown with the host's own remove action and the bounded draft owns every +/// refusal. Sending does not yet carry attachments, and paste is not wired. class ChatComposerBar extends StatefulWidget { const ChatComposerBar({ super.key, required this.composer, required this.running, + this.picker, }); final ChatComposerController composer; @@ -38,6 +45,9 @@ class ChatComposerBar extends StatefulWidget { /// The thread controller's running bit; it alone decides Send versus Stop. final bool running; + /// The host picker seam; production uses [hostChatAttachmentPicker]. + final ChatAttachmentPicker? picker; + @override State createState() => _ChatComposerBarState(); } @@ -47,6 +57,10 @@ class _ChatComposerBarState extends State { text: widget.composer.draft, ); final FocusNode _focus = FocusNode(debugLabel: 'chat-composer'); + final ChatAttachmentDraft _attachments = ChatAttachmentDraft(); + String? _attachmentError; + + ChatAttachmentPicker get _picker => widget.picker ?? hostChatAttachmentPicker; @override void initState() { @@ -100,6 +114,37 @@ class _ChatComposerBarState extends State { _focus.requestFocus(); } + /// Adds the operator's explicit selection through the host seam. A dismissed + /// picker changes nothing; a bounded draft refusal is shown in its own words + /// while every attachment already in the draft stays. + Future _pickAttachments() async { + if (widget.composer.sending || !_picker.isSupported) return; + List? files; + try { + files = await _picker.pick(); + } catch (error) { + if (!mounted) return; + setState(() => _attachmentError = '$error'); + return; + } + if (!mounted || files == null) return; + final picked = files; + setState(() { + _attachmentError = null; + for (final file in picked) { + final refusal = _attachments.add(file.attachment); + if (refusal != null) _attachmentError = refusal.message; + } + }); + } + + void _removeAttachment(ChatAttachment attachment) { + setState(() { + _attachments.remove(attachment); + _attachmentError = null; + }); + } + @override void dispose() { widget.composer.removeListener(_syncDraft); @@ -126,6 +171,15 @@ class _ChatComposerBarState extends State { mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + if (!_attachments.isEmpty) _attachmentStrip(context, cupertino), + if (_attachmentError != null) + _notice( + context, + cupertino, + key: const Key('chat-composer-attachment-error'), + text: _attachmentError!, + failed: true, + ), if (composer.queued) _notice( context, @@ -144,6 +198,8 @@ class _ChatComposerBarState extends State { Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ + _attach(context, cupertino), + const SizedBox(width: 8), Expanded( child: Focus( canRequestFocus: false, @@ -164,6 +220,118 @@ class _ChatComposerBarState extends State { ); } + /// The attach control: a host button that opens the picker, disabled when the + /// host has no picker or one prompt is already awaiting its reply. + Widget _attach(BuildContext context, bool cupertino) { + final enabled = _picker.isSupported && !widget.composer.sending; + final onPressed = enabled ? () => unawaited(_pickAttachments()) : null; + if (cupertino) { + return Semantics( + label: chatAttachLabel, + button: true, + enabled: enabled, + child: ExcludeSemantics( + child: CupertinoButton( + key: const Key('chat-composer-attach'), + padding: EdgeInsets.zero, + onPressed: onPressed, + child: const Icon(CupertinoIcons.paperclip), + ), + ), + ); + } + return IconButton( + key: const Key('chat-composer-attach'), + tooltip: chatAttachLabel, + onPressed: onPressed, + icon: const Icon(Icons.attach_file), + ); + } + + /// The files attached to the next message. Each chip carries only the + /// operator's recorded name and a native remove action. + Widget _attachmentStrip(BuildContext context, bool cupertino) { + final attachments = _attachments.attachments; + return Padding( + key: const Key('chat-composer-attachments'), + padding: const EdgeInsetsDirectional.only(bottom: 8), + child: Wrap( + spacing: 8, + runSpacing: 4, + children: [ + for (var index = 0; index < attachments.length; index += 1) + if (cupertino) + _cupertinoChip(context, attachments[index], index) + else + _materialChip(attachments[index], index), + ], + ), + ); + } + + Widget _materialChip(ChatAttachment attachment, int index) => Chip( + key: ValueKey('chat-composer-attachment-$index'), + label: Text(attachment.name), + onDeleted: () => _removeAttachment(attachment), + deleteButtonTooltipMessage: 'Remove ${attachment.name}', + ); + + /// Cupertino has no chip control, so the host's capsule fill and its own + /// button carry the same name and remove action. + Widget _cupertinoChip( + BuildContext context, + ChatAttachment attachment, + int index, + ) { + return Semantics( + container: true, + explicitChildNodes: true, + child: DefaultTextStyle.merge( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: DecoratedBox( + key: ValueKey('chat-composer-attachment-$index'), + decoration: ShapeDecoration( + shape: const StadiumBorder(), + color: CupertinoColors.secondarySystemFill.resolveFrom(context), + ), + child: Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 4, 4, 4), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text(attachment.name, overflow: TextOverflow.ellipsis), + ), + const SizedBox(width: 4), + Semantics( + container: true, + button: true, + label: 'Remove ${attachment.name}', + onTap: () => _removeAttachment(attachment), + child: ExcludeSemantics( + child: CupertinoButton( + key: ValueKey( + 'chat-composer-attachment-remove-$index', + ), + padding: EdgeInsets.zero, + onPressed: () => _removeAttachment(attachment), + child: Icon( + CupertinoIcons.xmark_circle_fill, + color: CupertinoColors.secondaryLabel.resolveFrom( + context, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + } + Widget _field(bool cupertino) { final composer = widget.composer; void changed(String value) => unawaited(composer.setDraft(value)); @@ -191,6 +359,7 @@ class _ChatComposerBarState extends State { onChanged: changed, decoration: const InputDecoration( hintText: chatComposerPlaceholder, + hintMaxLines: 1, border: OutlineInputBorder(), ), ); diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index 198b6ca5..80209f06 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/chat_repository.dart'; +import '../domain/chat_sessions.dart'; import '../domain/chat_transcript.dart'; import 'chat_thread_cards.dart'; @@ -42,6 +43,7 @@ class ChatThreadController extends ChangeNotifier { bool _hasMore = false; String _cursor = ''; String _nativeTurnId = ''; + JsonMap? _usage; String? _error; bool _subscribed = false; @@ -59,6 +61,11 @@ class ChatThreadController extends ChangeNotifier { /// The server's opaque older-page cursor. Never interpreted, only passed back. String get cursor => _cursor; + + /// The latest recorded usage snapshot, or null before the harness reports. + /// Unknown fields stay null, so a viewer can distinguish them from zero. + JsonMap? get usage => _usage; + String? get error => _error; bool get subscribed => _subscribed; String? get subscriptionError => _subscriptionError; @@ -222,6 +229,16 @@ class ChatThreadController extends ChangeNotifier { unawaited(resync()); return; } + if (body['kind'] == 'usage') { + // Usage replaces the last snapshot and never adds a message, runs a turn + // or admits a queued prompt. An unusable snapshot keeps the previous + // recorded values instead of replacing them with fabricated zeros. + final usage = chatUsageSnapshot(body['usage']); + if (usage == null || !_reportedUsage(usage)) return; + _usage = usage; + _notify(); + return; + } if (body['kind'] == 'form') { final form = body['form']; if (form is! Map) return; @@ -240,6 +257,23 @@ class ChatThreadController extends ChangeNotifier { _notify(); } + /// Whether a normalized snapshot names a scope or carries a recorded fact. + /// A window of zero reports no usable limit, and a rate basis alone reports + /// no number at all, so neither counts as a fact on its own. + bool _reportedUsage(JsonMap usage) { + if ('${usage['scope'] ?? ''}'.isNotEmpty) return true; + if (usage['context_window'] is int && + (usage['context_window'] as int) > 0) { + return true; + } + return const [ + 'total_tokens', + 'context_tokens', + 'cost_usd', + 'output_tokens_per_second', + ].any((key) => usage[key] != null); + } + /// The pushed envelope body, or null for another message type. The server /// wraps `chat_event` in the typed envelope; domain code never sees the /// transport fields. diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 9e089695..33b2fa38 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -101,6 +101,34 @@ class _ChatThreadViewState extends State { }); } + /// Reports the harness's recorded usage. The standard sheet is dismissed the + /// platform's way (drag/barrier/Back, or a popup tap) and closes explicitly. + Future _openInfo() async { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + if (cupertino) { + await showCupertinoModalPopup( + context: context, + builder: (sheetContext) => Align( + alignment: Alignment.bottomCenter, + child: SafeArea( + child: CupertinoPopupSurface( + child: _ChatInfoSheet(controller: _controller), + ), + ), + ), + ); + return; + } + await showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + useSafeArea: true, + builder: (sheetContext) => _ChatInfoSheet(controller: _controller), + ); + } + /// Local turns whose authoritative copy is not in the held transcript yet. /// A live user frame or a history page that carries the same operation, /// native id or message id hides the local copy instead of drawing it twice. @@ -195,6 +223,13 @@ class _ChatThreadViewState extends State { ).textTheme.navTitleTextStyle : Theme.of(context).textTheme.titleLarge, ), + ChatBarAction( + key: const Key('chat-info'), + label: 'Chat information', + onPressed: _openInfo, + materialIcon: Icons.info_outline, + cupertinoIcon: CupertinoIcons.info, + ), ], ), ), @@ -312,6 +347,227 @@ class _ChatThreadViewState extends State { ); } +/// One reported usage metric: its web label, whether the harness reported it, +/// and the displayed value. Unavailable is a word, never a zero. +typedef _ChatInfoMetric = ({ + String key, + String label, + bool available, + String value, +}); + +const _chatInfoUnavailable = 'Unavailable'; + +/// The four chat usage facts in the web order and wording. +/// +/// Values come only from [ChatThreadController.usage]; a missing count, amount +/// or window is "Unavailable". A reported zero stays a reported zero, and the +/// context row keeps the web's partial forms when only one side was reported. +List<_ChatInfoMetric> _chatInfoMetrics(JsonMap? usage) { + final scope = '${usage?['scope'] ?? ''}'; + final basis = '${usage?['rate_basis'] ?? ''}'; + final rate = _chatInfoAmount(usage?['output_tokens_per_second']); + final total = _chatInfoCount(usage?['total_tokens']); + final used = _chatInfoCount(usage?['context_tokens']); + final reportedWindow = _chatInfoCount(usage?['context_window']); + // The web treats a zero context window as no reported limit. + final limit = reportedWindow != null && reportedWindow > 0 + ? reportedWindow + : null; + final cost = _chatInfoAmount(usage?['cost_usd']); + final context = used != null && limit != null + ? '${_chatInfoInteger(used)} / ${_chatInfoInteger(limit)}' + : limit != null + ? '${_chatInfoInteger(limit)} limit' + : used != null + ? '${_chatInfoInteger(used)} used' + : _chatInfoUnavailable; + return [ + ( + key: 'rate', + label: basis == 'turn' ? 'Avg output rate' : 'Output rate', + available: rate != null, + value: rate == null ? _chatInfoUnavailable : _chatInfoRate(rate), + ), + ( + key: 'tokens', + label: scope == 'turn' ? 'Turn tokens' : 'Total tokens', + available: total != null, + value: total == null ? _chatInfoUnavailable : _chatInfoInteger(total), + ), + ( + key: 'context', + label: 'Context', + available: used != null || limit != null, + value: context, + ), + ( + key: 'cost', + label: 'Reported cost', + available: cost != null, + value: cost == null ? _chatInfoUnavailable : _chatInfoDollars(cost), + ), + ]; +} + +int? _chatInfoCount(Object? value) => value is int && value >= 0 ? value : null; + +num? _chatInfoAmount(Object? value) => + value is num && value.isFinite && value >= 0 ? value : null; + +String _chatInfoInteger(int value) { + final digits = value.toString(); + final grouped = StringBuffer(); + for (var index = 0; index < digits.length; index++) { + if (index > 0 && (digits.length - index) % 3 == 0) grouped.write(','); + grouped.write(digits[index]); + } + return grouped.toString(); +} + +String _chatInfoRate(num value) { + final atMostOneDecimal = value.toStringAsFixed(1); + final number = atMostOneDecimal.endsWith('.0') + ? atMostOneDecimal.substring(0, atMostOneDecimal.length - 2) + : atMostOneDecimal; + return value > 0 && value < 0.1 ? '<0.1 tok/s' : '$number tok/s'; +} + +String _chatInfoDollars(num value) { + if (value > 0 && value < 0.000001) return '<\$0.000001'; + final fixed = value.toStringAsFixed(6); + final point = fixed.indexOf('.'); + var decimals = fixed.substring(point + 1); + while (decimals.length > 4 && decimals.endsWith('0')) { + decimals = decimals.substring(0, decimals.length - 1); + } + final whole = int.parse(fixed.substring(0, point)); + return '\$${_chatInfoInteger(whole)}.$decimals'; +} + +/// The "Chat information" panel. It rebuilds from the controller, so metrics +/// that arrive while it is open replace the displayed snapshot. +class _ChatInfoSheet extends StatelessWidget { + const _ChatInfoSheet({required this.controller}); + + final ChatThreadController controller; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + return AnimatedBuilder( + animation: controller, + builder: (context, _) { + final titleStyle = cupertino + ? CupertinoTheme.of(context).textTheme.navTitleTextStyle + : Theme.of(context).textTheme.titleLarge; + final content = Column( + key: const Key('chat-info-sheet'), + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 16, 4), + child: Row( + children: [ + Expanded( + child: Semantics( + header: true, + child: Text('Chat information', style: titleStyle), + ), + ), + if (cupertino) + CupertinoButton( + key: const Key('chat-info-close'), + padding: EdgeInsets.zero, + onPressed: () => Navigator.of(context).pop(), + child: const Text('Close'), + ) + else + TextButton( + key: const Key('chat-info-close'), + onPressed: () => Navigator.of(context).pop(), + child: const Text('Close'), + ), + ], + ), + ), + for (final metric in _chatInfoMetrics(controller.usage)) + _ChatInfoRow(metric: metric, cupertino: cupertino), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(24, 8, 24, 16), + child: Text( + 'Last reported by the harness. ' + 'Unavailable values are not estimated.', + style: + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall) + ?.copyWith( + color: cupertino + ? CupertinoColors.secondaryLabel.resolveFrom( + context, + ) + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ); + if (!cupertino) return SingleChildScrollView(child: content); + // A tall text scale must scroll inside the popup rather than push its + // heading off-screen. The height follows the viewport, not a fixed size. + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.8, + ), + child: SingleChildScrollView(child: content), + ); + }, + ); + } +} + +class _ChatInfoRow extends StatelessWidget { + const _ChatInfoRow({required this.metric, required this.cupertino}); + + final _ChatInfoMetric metric; + final bool cupertino; + + @override + Widget build(BuildContext context) { + final secondary = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + final labelStyle = + (cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodySmall) + ?.copyWith(color: secondary); + final valueStyle = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyLarge; + return Padding( + key: Key('chat-info-metric-${metric.key}'), + padding: const EdgeInsetsDirectional.fromSTEB(24, 6, 24, 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(metric.label, style: labelStyle), + Text( + metric.value, + key: Key('chat-info-value-${metric.key}'), + style: metric.available + ? valueStyle + : valueStyle?.copyWith(color: secondary), + ), + ], + ), + ); + } +} + /// One recorded activity line for a turn. /// /// The line is a summary of the recorded sequence. Its wording and state come 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/screen.dart b/app/lib/features/runs/screen.dart index 56dc70a7..e6ae2c14 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -19,6 +19,8 @@ class RunsScreen extends StatefulWidget { super.key, required this.gateway, this.initialRunId, + this.initialStageKey, + this.initialVisit, this.syncToken = 0, this.listRefreshToken = 0, this.onRunSelected, @@ -33,6 +35,11 @@ class RunsScreen extends StatefulWidget { /// The run the current route names, or null for the list. final int? initialRunId; + /// The recorded stage visit the route names inside [initialRunId]. The detail + /// applies it once per route target; the feature never invents a visit. + final String? initialStageKey; + final int? initialVisit; + /// Advances when the shared socket is replaced. The loaded screen refreshes /// in place instead of being remounted, so its selection survives. final int syncToken; @@ -143,6 +150,8 @@ class _RunsScreenState extends State { gateway: widget.gateway, onBack: _back, onRunOpened: _select, + initialStageKey: widget.initialStageKey, + initialVisit: widget.initialVisit, ), ], ); diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index 4da3afa0..072195cc 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -20,7 +20,11 @@ Widget buildCupertinoRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required ApiGateway gateway, + required ValueChanged onRunChanged, required String configuredEndpoint, + String? initialStageKey, + int? initialVisit, }) { final theme = CupertinoTheme.of(context); return RunDetailTabs( @@ -29,7 +33,11 @@ Widget buildCupertinoRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + gateway: gateway, + onRunChanged: onRunChanged, configuredEndpoint: configuredEndpoint, + initialStageKey: initialStageKey, + initialVisit: initialVisit, header: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index 8d27e80e..d61c2d09 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -20,7 +20,11 @@ Widget buildMaterialRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required ApiGateway gateway, + required ValueChanged onRunChanged, required String configuredEndpoint, + String? initialStageKey, + int? initialVisit, }) { final theme = Theme.of(context); return RunDetailTabs( @@ -29,7 +33,11 @@ Widget buildMaterialRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + gateway: gateway, + onRunChanged: onRunChanged, configuredEndpoint: configuredEndpoint, + initialStageKey: initialStageKey, + initialVisit: initialVisit, header: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 6641994b..65ca3c4e 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -36,7 +36,11 @@ 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, }); final JsonMap run; @@ -50,10 +54,24 @@ 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; + /// The stage a `/runs/:id/stage/:key` route names, or null for the plain + /// detail. It selects a recorded visit; a declared but unvisited stage only + /// selects its graph node, so no visit is ever invented. + final String? initialStageKey; + + /// The zero-based index among [initialStageKey]'s recorded visits. Null opens + /// the stage's latest visit, exactly as a Graph node click does. + final int? initialVisit; + @override State createState() => _RunDetailTabsState(); } @@ -63,15 +81,68 @@ class _RunDetailTabsState extends State { String? _selectedStage; int? _selectedVisit; + @override + void initState() { + super.initState(); + _applyInitialVisit(); + } + @override void didUpdateWidget(covariant RunDetailTabs oldWidget) { super.didUpdateWidget(oldWidget); + final sameRun = '${widget.run['id']}' == '${oldWidget.run['id']}'; + final sameTarget = + widget.initialStageKey == oldWidget.initialStageKey && + widget.initialVisit == oldWidget.initialVisit; // A different run is a different detail: its visits and graph do not carry // the previous run's selection. - if ('${widget.run['id']}' != '${oldWidget.run['id']}') { + if (!sameRun) { _tab = RunDetailTab.summary; _selectedStage = null; _selectedVisit = null; + _applyInitialVisit(); + } else if (!sameTarget) { + // A route that names another stage or visit is applied to the same run. + // Rebuilds from a live refresh keep the operator's own selection. + _applyInitialVisit(); + } + } + + /// Opens the visit a route names, without presenting any visit the run did + /// not record. + /// + /// A route with a stage key and no visit opens that stage's latest recorded + /// visit, the same visit a Graph node click opens. A valid index selects that + /// visit among the stage's own visits; an out-of-range index is clamped to the + /// stage's last recorded visit, as the web client does, so the address bar and + /// the pane never disagree about which visit is real. A declared but + /// unvisited stage selects its Graph node only. + void _applyInitialVisit() { + final stageKey = widget.initialStageKey; + if (stageKey == null || stageKey.isEmpty) { + _selectedStage = null; + _selectedVisit = null; + return; + } + final index = routeDetailVisitIndex( + widget.run['steps'], + stageKey, + widget.initialVisit, + ); + if (index != null) { + _selectedStage = stageKey; + _selectedVisit = index; + _tab = RunDetailTab.timeline; + return; + } + _selectedVisit = null; + // The key is not a recorded visit. Only a stage the pinned graph actually + // declares can be selected; anything else leaves the plain detail intact. + if (detailVisitHasDefinition(detailGraph(widget.run), stageKey)) { + _selectedStage = stageKey; + _tab = RunDetailTab.graph; + } else { + _selectedStage = null; } } @@ -180,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 6e2bbcb9..c1bcaea1 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -18,6 +18,8 @@ class RunDetailView extends StatefulWidget { required this.gateway, required this.onBack, this.onRunOpened, + this.initialStageKey, + this.initialVisit, }); final RunsController controller; @@ -30,6 +32,12 @@ class RunDetailView extends StatefulWidget { /// the server-identified new run. Null keeps the detail on the retried run. final ValueChanged? onRunOpened; + /// The route's stage and visit, forwarded to the tab body so a `/runs/:id/ + /// stage/:key[?visit=N]` deep link opens that recorded visit. Null is the + /// plain detail. + final String? initialStageKey; + final int? initialVisit; + @override State createState() => _RunDetailViewState(); } @@ -64,7 +72,11 @@ 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, ) : buildMaterialRunDetail( context: context, @@ -76,7 +88,11 @@ 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_facts.dart b/app/lib/features/runs/ui/run_detail_visit_facts.dart index b26dfa4a..a631d183 100644 --- a/app/lib/features/runs/ui/run_detail_visit_facts.dart +++ b/app/lib/features/runs/ui/run_detail_visit_facts.dart @@ -31,15 +31,41 @@ JsonMap? detailVisitStepAt(JsonMap run, int index) { } /// The row index of [stageKey]'s latest recorded visit, or null when the run -/// never recorded that stage. It reads the same ordered timeline the rows do, -/// so a Graph click opens exactly the row the operator would have selected. -int? latestDetailVisitIndex(dynamic steps, String stageKey) { +/// never recorded that stage. +/// +/// The order matches [routeDetailVisitIndex] and the web client's +/// `visitsByStage`: a stage's visits follow their recorded sequence, not their +/// position in the reply's step list. So a Graph click and `/runs/:id/stage/:key` +/// open the same visit even when the steps are not in sequence order. +int? latestDetailVisitIndex(dynamic steps, String stageKey) => + routeDetailVisitIndex(steps, stageKey, null); + +/// The timeline row index a route's [stageKey] and [visit] name, or null when +/// the run recorded no visit of that stage. +/// +/// A stage's visits follow their recorded sequence, as the web client's +/// `visitsByStage` does, so the same `?visit=N` selects the same visit in both +/// clients while equal sequences keep the timeline's own order. A null [visit] +/// is the stage's last recorded visit, the one a Graph node click opens; an +/// out-of-range index is clamped to that last visit, exactly as the web client +/// clamps it. Nothing is invented for a stage with no recorded visit. +int? routeDetailVisitIndex(dynamic steps, String stageKey, int? visit) { final visits = detailTimeline(steps); - int? latest; - for (var index = 0; index < visits.length; index += 1) { - if (visits[index].stage == stageKey) latest = index; - } - return latest; + final indices = [ + for (var index = 0; index < visits.length; index += 1) + if (visits[index].stage == stageKey) index, + ]; + if (indices.isEmpty) return null; + indices.sort((a, b) { + final bySequence = (visits[a].sequence ?? 0).compareTo( + visits[b].sequence ?? 0, + ); + return bySequence != 0 ? bySequence : a.compareTo(b); + }); + final wanted = visit == null + ? indices.length - 1 + : visit.clamp(0, indices.length - 1); + return indices[wanted]; } /// The visit's recorded facts, in the pane's order. A field the server did not 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/application/app_router_test.dart b/app/test/application/app_router_test.dart index 1c5c3731..d746433e 100644 --- a/app/test/application/app_router_test.dart +++ b/app/test/application/app_router_test.dart @@ -49,4 +49,55 @@ void main() { router.closeTemplates(); expect(router.route, AppRoute.settings); }); + + test('the parser keeps a query and restores it as a query', () async { + const parser = AppRouteParser(); + final route = await parser.parseRouteInformation( + RouteInformation(uri: Uri.parse('/runs/77/stage/plan?visit=1')), + ); + expect(route, AppRoute.run.stage(77, 'plan', visit: 1)); + + final restored = parser.restoreRouteInformation(route).uri; + expect(restored.path, '/runs/77/stage/plan'); + expect(restored.query, 'visit=1'); + expect(restored.toString(), '/runs/77/stage/plan?visit=1'); + // A reload or Back/Forward feeds the restored location straight back in. + expect(AppRoute.parse(restored.toString()), route); + }); + + test('every query route survives a restore and reparse', () { + const parser = AppRouteParser(); + for (final route in [ + AppRoute.runsForPipeline(7), + AppRoute.run.decide(3), + AppRoute.run.stage(3, 'plan', visit: 0), + AppRoute.run.stage(5, 'build ✓', visit: 4), + ]) { + final uri = parser.restoreRouteInformation(route).uri; + expect(uri.toString(), route.path, reason: route.path); + expect(uri.path, isNot(contains('%3F')), reason: route.path); + expect(AppRoute.parse(uri.toString()), route, reason: route.path); + } + }); + + test('a web launch keeps the path and its query', () { + final visit = routeInformationForLocation( + Uri.parse('https://example.test/runs/7/stage/plan?visit=2'), + ); + expect(visit.uri.toString(), '/runs/7/stage/plan?visit=2'); + expect(visit.uri.path, '/runs/7/stage/plan'); + expect(visit.uri.query, 'visit=2'); + + final decide = routeInformationForLocation( + Uri.parse('https://example.test/runs/9?action=decide'), + ); + expect(decide.uri.toString(), '/runs/9?action=decide'); + + expect( + routeInformationForLocation( + Uri.parse('https://example.test/'), + ).uri.toString(), + '/', + ); + }); } diff --git a/app/test/application/pipelines_app_test.dart b/app/test/application/pipelines_app_test.dart index 81e526d8..a9812d67 100644 --- a/app/test/application/pipelines_app_test.dart +++ b/app/test/application/pipelines_app_test.dart @@ -2,6 +2,8 @@ import 'dart:convert'; import 'package:flutter/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/app_route.dart'; +import 'package:pipelines_app/application/app_router.dart'; import 'package:pipelines_app/application/pipelines_app.dart'; import 'package:pipelines_app/application/server_endpoint.dart'; import 'package:pipelines_app/core/transport/pipelines_client.dart'; @@ -84,6 +86,57 @@ Future replyDetail( await tester.pump(); } +/// A run whose plan visits are deliberately not in sequence order, so a route +/// visit index must follow the recorded sequence, not the reply's row order. +Future replyVisitDetail( + WidgetTester tester, + FakeChannel channel, + num id, +) async { + for ( + var attempt = 0; + attempt < 40 && requestOf(channel, 'get_run') == null; + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 5)); + } + final request = requestOf(channel, 'get_run')!; + expect(request['run_id'], id); + channel.incoming.add( + jsonEncode({ + 'id': request['id'], + 'type': 'run', + 'run_detail': { + 'id': id, + 'title': 'Deep link run', + 'name': 'release', + 'status': 'succeeded', + 'graph': { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build'}, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': '#success'}, + }, + ], + }, + 'steps': [ + {'stage': 'plan', 'sequence': 5, 'status': 'completed'}, + {'stage': 'build', 'sequence': 2, 'status': 'completed'}, + {'stage': 'plan', 'sequence': 1, 'status': 'completed'}, + ], + }, + }), + ); + await tester.pump(); + await tester.pump(); +} + void main() { testWidgets('a /runs/1 boot link opens that run and Back returns to /runs', ( tester, @@ -195,4 +248,47 @@ void main() { await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); }); + + testWidgets('a queried stage boot link opens that exact recorded visit', ( + tester, + ) async { + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final provider = PlatformRouteInformationProvider( + initialRouteInformation: RouteInformation( + uri: Uri.parse('/runs/77/stage/plan?visit=0'), + ), + ); + addTearDown(provider.dispose); + + await pumpApp(tester, channel: channel, client: client, provider: provider); + await replyList( + tester, + channel, + runs: [ + {'id': 77, 'name': 'Deep link run', 'status': 'succeeded'}, + ], + ); + await replyVisitDetail(tester, channel, 77); + + // The query reached the detail: visit 0 is the earlier plan visit (seq 1), + // not the latest one the pane would show without a visit. + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.text('plan · visit 5'), findsNothing); + expect(provider.value.uri.toString(), '/runs/77/stage/plan?visit=0'); + + // A history entry the app itself writes is parsed back as a query, so + // Back/Forward (and a reload) open the visit instead of a bogus stage key. + final restored = const AppRouteParser() + .restoreRouteInformation(AppRoute.run.stage(77, 'plan', visit: 1)) + .uri; + expect(restored.toString(), '/runs/77/stage/plan?visit=1'); + await provider.didPushRouteInformation(RouteInformation(uri: restored)); + await tester.pump(); + await tester.pump(); + expect(find.text('plan · visit 5'), findsOneWidget); + expect(provider.value.uri.path, '/runs/77/stage/plan'); + expect(provider.value.uri.query, 'visit=1'); + }); } diff --git a/app/test/features/chat/conversation/chat_composer_attachment_test.dart b/app/test/features/chat/conversation/chat_composer_attachment_test.dart new file mode 100644 index 00000000..1ceef5fc --- /dev/null +++ b/app/test/features/chat/conversation/chat_composer_attachment_test.dart @@ -0,0 +1,246 @@ +import 'dart:async'; +import 'dart:typed_data'; + +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/chat/conversation/chat_composer_bar.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_composer_controller.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_draft.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attachment_picker.dart'; + +import 'chat_composer_bar_fixtures.dart'; + +/// A picker whose selections are supplied by the test, one call at a time. +class _FakePicker { + _FakePicker(this.results); + + final List?> results; + int calls = 0; + + ChatAttachmentPicker get picker => ChatAttachmentPicker( + select: () async { + calls += 1; + return results.isEmpty ? null : results.removeAt(0); + }, + ); +} + +ChatPickedFile _file(String name, {int size = 3, String mime = 'text/plain'}) => + ChatPickedFile(name: name, mime: mime, bytes: Uint8List(size)); + +Widget _host(Widget bar, {required bool cupertino}) => cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: bar)) + : materialHost(bar); + +void main() { + late ComposerBarGateway gateway; + late ChatComposerController composer; + late List controllers; + + setUp(() { + gateway = ComposerBarGateway(); + controllers = []; + }); + + /// Created inside the test body so the controller's futures belong to the + /// widget tester's clock rather than to `setUp`'s. + ChatComposerController newComposer() { + final controller = ChatComposerController( + gateway, + 's', + drafts: MemoryChatDraftStore(), + ); + controllers.add(controller); + composer = controller; + return controller; + } + + tearDown(() { + for (final controller in controllers) { + controller.dispose(); + } + gateway.close(); + }); + + Future pumpBar( + WidgetTester tester, { + ChatAttachmentPicker? picker, + bool cupertino = false, + }) async { + newComposer(); + await tester.pumpWidget( + _host( + ChatComposerBar(composer: composer, running: false, picker: picker), + cupertino: cupertino, + ), + ); + await tester.pump(); + } + + for (final cupertino in [false, true]) { + testWidgets('picking a file shows its recorded name and removes it ' + '(${cupertino ? 'cupertino' : 'material'})', (tester) async { + final fake = _FakePicker([ + [_file('notes.txt')], + ]); + await pumpBar(tester, picker: fake.picker, cupertino: cupertino); + + await tester.tap(find.byKey(const Key('chat-composer-attach'))); + await tester.pumpAndSettle(); + + expect(fake.calls, 1); + expect( + find.byKey(const Key('chat-composer-attachments')), + findsOneWidget, + ); + expect(find.text('notes.txt'), findsOneWidget); + + if (cupertino) { + await tester.tap( + find.byKey(const Key('chat-composer-attachment-remove-0')), + ); + } else { + await tester.tap(find.byTooltip('Remove notes.txt')); + } + await tester.pump(); + + expect(find.text('notes.txt'), findsNothing); + expect(find.byKey(const Key('chat-composer-attachments')), findsNothing); + }); + } + + testWidgets('a file over the draft budget shows the draft refusal line', ( + tester, + ) async { + final fake = _FakePicker([ + [ + _file( + 'huge.bin', + size: ChatAttachmentDraft.maxTotalBytes + 1, + mime: 'application/octet-stream', + ), + ], + ]); + await pumpBar(tester, picker: fake.picker); + + await tester.tap(find.byKey(const Key('chat-composer-attach'))); + await tester.pumpAndSettle(); + + expect( + find.text(ChatAttachmentRefusal.totalTooLarge.message), + findsOneWidget, + ); + expect(find.byKey(const Key('chat-composer-attachments')), findsNothing); + expect(find.text('huge.bin'), findsNothing); + }); + + testWidgets('attachments survive a normal parent rebuild', (tester) async { + newComposer(); + final fake = _FakePicker([ + [_file('keep me.pdf', mime: 'application/pdf')], + ]); + var rebuilt = false; + late StateSetter rebuild; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + rebuild = setState; + return ChatComposerBar( + composer: composer, + running: rebuilt, + picker: fake.picker, + ); + }, + ), + ), + ), + ); + await tester.pump(); + + await tester.tap(find.byKey(const Key('chat-composer-attach'))); + await tester.pumpAndSettle(); + expect(find.text('keep me.pdf'), findsOneWidget); + + rebuild(() => rebuilt = true); + await tester.pump(); + + expect(find.text('keep me.pdf'), findsOneWidget); + expect(find.byKey(const Key('chat-composer-attachments')), findsOneWidget); + }); + + testWidgets('the attach control is disabled while a prompt is in flight', ( + tester, + ) async { + final reply = Completer(); + gateway.prompt = (_, _) => reply.future; + final fake = _FakePicker([ + [_file('notes.txt')], + ]); + await pumpBar(tester, picker: fake.picker); + + IconButton attach() => tester.widget( + find.byKey(const Key('chat-composer-attach')), + ); + expect(attach().onPressed, isNotNull); + + await tester.enterText( + find.byKey(const Key('chat-composer-field')), + 'hello', + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('chat-composer-primary'))); + await tester.pumpAndSettle(); + + expect(attach().onPressed, isNull); + expect(gateway.promptBodies, hasLength(1)); + + reply.complete(const {}); + await tester.pumpAndSettle(); + expect(attach().onPressed, isNotNull); + }); + + testWidgets('the attach control is disabled without a host picker', ( + tester, + ) async { + await pumpBar(tester); + + final attach = tester.widget( + find.byKey(const Key('chat-composer-attach')), + ); + expect(attach.onPressed, isNull); + }); + + for (final cupertino in [false, true]) { + testWidgets('a long attachment name fits a narrow 2x composer ' + '(${cupertino ? 'cupertino' : 'material'})', (tester) async { + tester.view.physicalSize = const Size(640, 1200); + tester.view.devicePixelRatio = 2; + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + + final name = + 'a-very-long-recorded-attachment-name-that-must-not-overflow.pdf'; + final fake = _FakePicker([ + [_file(name)], + ]); + await pumpBar(tester, picker: fake.picker, cupertino: cupertino); + + await tester.tap(find.byKey(const Key('chat-composer-attach'))); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(find.text(name), findsOneWidget); + expect( + find.byKey(const Key('chat-composer-attachments')), + findsOneWidget, + ); + }); + } +} diff --git a/app/test/features/chat/conversation/chat_info_sheet_test.dart b/app/test/features/chat/conversation/chat_info_sheet_test.dart new file mode 100644 index 00000000..9c0b137b --- /dev/null +++ b/app/test/features/chat/conversation/chat_info_sheet_test.dart @@ -0,0 +1,178 @@ +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/chat/conversation/chat_thread_view.dart'; + +import 'chat_thread_fixtures.dart'; + +Widget _host(Widget child) => MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + home: Scaffold(body: child), +); + +Widget _cupertinoHost(Widget child) => CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold(child: child), +); + +JsonMap _usageFrame(JsonMap usage) => { + 'session_id': 's', + 'kind': 'usage', + 'usage': usage, +}; + +Future _thread( + WidgetTester tester, { + bool cupertino = false, +}) async { + final gateway = FakeChatGateway(); + addTearDown(gateway.close); + gateway.history = (_) async => chatPage([]); + final thread = ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + ); + await tester.pumpWidget(cupertino ? _cupertinoHost(thread) : _host(thread)); + await tester.pumpAndSettle(); + return gateway; +} + +Future _openInfo(WidgetTester tester) async { + await tester.tap(find.byKey(const Key('chat-info'))); + await tester.pumpAndSettle(); +} + +void main() { + testWidgets('reports the recorded facts with the web labels', (tester) async { + final gateway = await _thread(tester); + gateway.emitEvent( + _usageFrame({ + 'scope': 'session', + 'total_tokens': 132408, + 'context_tokens': 42000, + 'context_window': 200000, + 'cost_usd': 0.1423, + 'output_tokens_per_second': 24.6, + 'rate_basis': 'generation', + }), + ); + await tester.pump(); + + await _openInfo(tester); + + expect(find.text('Chat information'), findsOneWidget); + expect(find.text('Output rate'), findsOneWidget); + expect(find.text('24.6 tok/s'), findsOneWidget); + expect(find.text('Total tokens'), findsOneWidget); + expect(find.text('132,408'), findsOneWidget); + expect(find.text('Context'), findsOneWidget); + expect(find.text('42,000 / 200,000'), findsOneWidget); + expect(find.text('Reported cost'), findsOneWidget); + expect(find.text('\$0.1423'), findsOneWidget); + expect( + find.text( + 'Last reported by the harness. ' + 'Unavailable values are not estimated.', + ), + findsOneWidget, + ); + + // A snapshot that arrives while the panel is open replaces the shown one. + gateway.emitEvent( + _usageFrame({ + 'scope': 'turn', + 'total_tokens': 133000, + 'context_tokens': 3000, + 'context_window': 200000, + 'cost_usd': 0.2, + 'output_tokens_per_second': 10, + 'rate_basis': 'turn', + }), + ); + await tester.pumpAndSettle(); + + expect(find.text('Turn tokens'), findsOneWidget); + expect(find.text('133,000'), findsOneWidget); + expect(find.text('Avg output rate'), findsOneWidget); + expect(find.text('10 tok/s'), findsOneWidget); + }); + + testWidgets('unknown facts say Unavailable while reported zeros stay zero', ( + tester, + ) async { + final gateway = await _thread(tester); + gateway.emitEvent(_usageFrame({'scope': 'session'})); + await tester.pump(); + + await _openInfo(tester); + + expect(find.text('Unavailable'), findsNWidgets(4)); + expect(find.text('0'), findsNothing); + + await tester.tap(find.byKey(const Key('chat-info-close'))); + await tester.pumpAndSettle(); + + gateway.emitEvent( + _usageFrame({ + 'scope': 'session', + 'total_tokens': 0, + 'context_tokens': 0, + 'context_window': 1000, + 'cost_usd': 0, + 'output_tokens_per_second': 0, + }), + ); + await tester.pump(); + await _openInfo(tester); + + expect(find.text('Unavailable'), findsNothing); + expect(find.text('0 tok/s'), findsOneWidget); + expect(find.text('0'), findsOneWidget); + expect(find.text('0 / 1,000'), findsOneWidget); + expect(find.text('\$0.0000'), findsOneWidget); + }); + + testWidgets('the native sheet dismisses from Close and the barrier', ( + tester, + ) async { + final gateway = await _thread(tester); + gateway.emitEvent(_usageFrame({'scope': 'session', 'total_tokens': 5})); + await tester.pump(); + + await _openInfo(tester); + expect(find.byKey(const Key('chat-info-sheet')), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-info-close'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-info-sheet')), findsNothing); + expect(find.byKey(const Key('chat-info')), findsOneWidget); + + await _openInfo(tester); + expect(find.byKey(const Key('chat-info-sheet')), findsOneWidget); + + // The modal barrier above the sheet is the platform's dismiss target. + await tester.tapAt(const Offset(8, 8)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-info-sheet')), findsNothing); + expect(find.byKey(const Key('chat-info')), findsOneWidget); + }); + + testWidgets('the Cupertino host opens and closes the native popup', ( + tester, + ) async { + final gateway = await _thread(tester, cupertino: true); + gateway.emitEvent(_usageFrame({'scope': 'session', 'total_tokens': 42})); + await tester.pump(); + + await _openInfo(tester); + expect(find.text('Chat information'), findsOneWidget); + expect(find.text('42'), findsOneWidget); + + await tester.tap(find.byKey(const Key('chat-info-close'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-info-sheet')), findsNothing); + expect(find.byKey(const Key('chat-info')), findsOneWidget); + }); +} diff --git a/app/test/features/runs/ui/run_detail_deep_link_test.dart b/app/test/features/runs/ui/run_detail_deep_link_test.dart new file mode 100644 index 00000000..f85b7843 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_deep_link_test.dart @@ -0,0 +1,301 @@ +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/graph/widgets/run_graph_view.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +import 'run_detail_graph_support.dart'; + +/// plan -> build -> audit, with two recorded plan visits and one build visit. +/// +/// The steps are deliberately not in sequence order, so a stage visit index +/// must follow the visit's recorded sequence while the row index follows the +/// timeline's step order. +JsonMap deepLinkRunFixture() => { + 'id': 77, + 'title': 'Deep link run', + 'name': 'release', + 'status': 'succeeded', + 'input': {'prompt': 'ship it'}, + 'graph': { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build', 'error': '#'}, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': 'audit', 'error': '#'}, + }, + { + 'key': 'audit', + 'type': 'model', + 'edges': {'success': '#success'}, + }, + ], + }, + 'steps': [ + { + 'stage': 'plan', + 'sequence': 5, + 'status': 'completed', + 'outcome': 'success', + }, + { + 'stage': 'build', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + }, + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + }, + ], +}; + +Future pumpDeepLink( + WidgetTester tester, + RunDetailTestPlatform platform, { + String? stage, + int? visit, + JsonMap? run, +}) async { + tester.view.physicalSize = const Size(900, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = RunDetailFakeGateway(run ?? deepLinkRunFixture()); + final controller = RunsController(RunsRepository(gateway)); + addTearDown(controller.dispose); + await controller.select(77); + final view = RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + initialStageKey: stage, + initialVisit: visit, + ); + final page = MediaQuery( + data: MediaQueryData.fromView(tester.view), + child: view, + ); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpWidget( + platform == RunDetailTestPlatform.material + ? MaterialApp(home: Scaffold(body: page)) + : CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: page)), + ), + ); + await tester.pumpAndSettle(); +} + +/// The Runs screen's own request seam: a route-named run opens through the same +/// list-then-detail read the shell performs. +class _ScreenGateway implements ApiGateway { + final _frames = StreamController.broadcast(); + final listRequests = >[]; + final detailRequests = >[]; + + @override + Stream get frames => _frames.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'list_runs') { + listRequests.add(request); + } else if (type == 'get_run') { + detailRequests.add(request); + } else { + request.completeError(UnsupportedError(type)); + } + return request.future; + } + + void close() => _frames.close(); +} + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} stage visit opens that recorded visit', ( + tester, + ) async { + await pumpDeepLink(tester, platform, stage: 'plan', visit: 0); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.text('plan · visit 5'), findsNothing); + expect( + find.byKey(const Key('run-detail-tab-body-timeline')), + findsWidgets, + ); + }); + + testWidgets('${platform.name} unknown stage opens the plain detail', ( + tester, + ) async { + await pumpDeepLink(tester, platform, stage: 'missing', visit: 2); + + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + expect( + find.byKey(const Key('run-detail-tab-body-summary')), + findsOneWidget, + ); + expect(find.text('Deep link run'), findsOneWidget); + }); + + testWidgets('${platform.name} no stage key keeps the plain detail', ( + tester, + ) async { + await pumpDeepLink(tester, platform); + + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + expect( + find.byKey(const Key('run-detail-tab-body-summary')), + findsOneWidget, + ); + }); + } + + testWidgets('a stage key without a visit opens that stage latest visit', ( + tester, + ) async { + await pumpDeepLink(tester, RunDetailTestPlatform.material, stage: 'plan'); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 5'), findsOneWidget); + }); + + testWidgets('a Graph click opens the same latest visit as the stage route', ( + tester, + ) async { + await pumpDeepLink(tester, RunDetailTestPlatform.material); + await openRunDetailTab(tester, RunDetailTab.graph); + await tapGraphNode(tester, 'plan'); + await tester.pumpAndSettle(); + + // The web client's graph click takes the last visit in sequence order, not + // the last row in reply order, so both entry points agree. + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 5'), findsOneWidget); + }); + + testWidgets('an out-of-range visit is clamped to the stage last visit', ( + tester, + ) async { + await pumpDeepLink( + tester, + RunDetailTestPlatform.material, + stage: 'plan', + visit: 9, + ); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 5'), findsOneWidget); + }); + + testWidgets('a declared but unvisited stage selects its graph node', ( + tester, + ) async { + await pumpDeepLink(tester, RunDetailTestPlatform.material, stage: 'audit'); + + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + expect(find.byKey(const Key('run-detail-graph')), findsOneWidget); + final graph = tester.widget( + find.byKey(const Key('run-detail-graph')), + ); + expect(graph.selectedStage, 'audit'); + }); + + testWidgets('the Runs screen forwards the route stage and visit', ( + tester, + ) async { + final gateway = _ScreenGateway(); + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunsScreen( + gateway: gateway, + initialRunId: 77, + initialStageKey: 'plan', + initialVisit: 1, + ), + ), + ), + ); + await tester.pump(); + gateway.listRequests.single.complete({ + 'runs': [ + {'id': 77, 'title': 'Deep link run', 'status': 'succeeded'}, + ], + }); + await tester.pump(); + await tester.pump(); + gateway.detailRequests.single.complete({ + 'run_detail': deepLinkRunFixture(), + }); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 5'), findsOneWidget); + }); + + testWidgets('a route change applies its visit and a plain route closes it', ( + tester, + ) async { + tester.view.physicalSize = const Size(900, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = RunDetailFakeGateway(deepLinkRunFixture()); + final controller = RunsController(RunsRepository(gateway)); + addTearDown(controller.dispose); + await controller.select(77); + String? stage = 'plan'; + int? visit = 0; + late StateSetter rebuild; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + rebuild = setState; + return MediaQuery( + data: MediaQueryData.fromView(tester.view), + child: RunDetailView( + controller: controller, + gateway: gateway, + onBack: () {}, + initialStageKey: stage, + initialVisit: visit, + ), + ); + }, + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('plan · visit 1'), findsOneWidget); + + rebuild(() => visit = 1); + await tester.pumpAndSettle(); + expect(find.text('plan · visit 5'), findsOneWidget); + + rebuild(() => stage = null); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + }); +} 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); + }); +}