diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 2560a238..49134588 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -247,3 +247,14 @@ class PipelinesClient implements ApiGateway { await _states.close(); } } + +/// The configured server origin of [gateway], or blank when the gateway does +/// not expose one (a feature fixture). +/// +/// Relative artifact and session urls resolve only against this origin; an +/// absolute recorded http(s) url still resolves without it. The cast lives here +/// so callers never repeat it. +String configuredGatewayEndpoint(ApiGateway gateway) { + final client = gateway is PipelinesClient ? gateway : null; + return client?.endpoint?.toString() ?? ''; +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart index bfa0707e..f9d861f3 100644 --- a/app/lib/features/artifacts/domain/artifact_groups.dart +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -107,3 +107,25 @@ List visitArtifacts(JsonMap step, List runSteps) { if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact, ]; } + +/// The gallery group of exactly one recorded visit, addressed by its index in +/// [runSteps]. The whole run is still read so a shared `public/` file stays with +/// the visit that first recorded it and the group keeps the run's own visit +/// numbering. Null when the index is out of range or the visit recorded no +/// presentable stage artifact. +ArtifactGroup? visitArtifactGroup(List runSteps, int index) { + if (index < 0 || index >= runSteps.length) return null; + final step = runSteps[index]; + final stage = '${step['stage'] ?? ''}'; + final visits = visitsByStage(runSteps)[stage]; + if (visits == null) return null; + // The pane passes the index of the same parsed list, so the recorded map is + // the identical instance the stage grouping holds. + final position = visits.indexOf(step); + if (position < 0) return null; + final visit = displayVisit(step, position); + for (final group in artifactGroups(runSteps)) { + if (group.stageKey == stage && group.visit == visit) return group; + } + return null; +} diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart index 7cffb7c8..bbcfd8a5 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_action.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -35,15 +35,6 @@ bool _runExecuting(JsonMap run) => run['executing'] == true || _executingStatuses.contains('${run['status'] ?? ''}'.trim().toLowerCase()); -/// The configured endpoint from the app's shared transport, when the gateway -/// exposes it. Feature fixtures without an endpoint leave it blank, which only -/// disables relative url resolution: an absolute recorded http(s) url still -/// resolves. The url rules themselves live in `artifact_url.dart`. -String _gatewayEndpoint(ApiGateway gateway) { - final endpoint = gateway is PipelinesClient ? gateway.endpoint : null; - return endpoint?.toString() ?? ''; -} - /// The run detail's standard native action that opens the recorded artifact /// groups. It is composed only when [showRunArtifactsAction] is true. class RunArtifactsButton extends StatelessWidget { @@ -63,7 +54,7 @@ class RunArtifactsButton extends StatelessWidget { context, steps: steps, executing: _runExecuting(run), - configuredEndpoint: _gatewayEndpoint(gateway), + configuredEndpoint: configuredGatewayEndpoint(gateway), ); if (usesCupertinoHost(context)) { return CupertinoButton.tinted( @@ -86,12 +77,14 @@ class RunArtifactsButton extends StatelessWidget { Future showArtifactGallery( BuildContext context, { required List steps, + int? focusIndex, bool executing = false, String configuredEndpoint = '', ArtifactExternalOpen openExternal = openArtifactExternally, }) { final page = ArtifactGalleryPage( steps: List.unmodifiable(steps), + focusIndex: focusIndex, executing: executing, configuredEndpoint: configuredEndpoint, openExternal: openExternal, diff --git a/app/lib/features/artifacts/ui/artifact_gallery_page.dart b/app/lib/features/artifacts/ui/artifact_gallery_page.dart index 5d79bd0f..e97c8b41 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_page.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_page.dart @@ -33,10 +33,16 @@ const String artifactGalleryTitle = 'Artifacts'; /// actions plus file `Download`/`Share` for a server-served url. Markdown /// previews use the same chat markdown renderer by default. It never filters, /// and an external url is never fetched for preview or file transfer. +/// +/// [focusIndex] limits the page to the visited `steps` index's attributed +/// group. The whole run is still passed so shared `public/` files keep their +/// first visit and the group keeps the run's visit numbering; the page then +/// lists exactly what the opening pane listed. class ArtifactGalleryPage extends StatefulWidget { const ArtifactGalleryPage({ super.key, required this.steps, + this.focusIndex, this.executing = false, this.configuredEndpoint = '', this.openExternal = openArtifactExternally, @@ -46,6 +52,10 @@ class ArtifactGalleryPage extends StatefulWidget { }); final List steps; + + /// The `steps` index whose group this page shows, or null for every group. + final int? focusIndex; + final bool executing; final String configuredEndpoint; final ArtifactExternalOpen openExternal; @@ -61,10 +71,16 @@ class _ArtifactGalleryPageState extends State { late final Map _stepsByGroup = recordedStepsByGroup( widget.steps, ); - late final List _groups = artifactGroups(widget.steps); + late final List _groups = _groupsOf(widget.focusIndex); String? _selectedIdentity; String? _status; + List _groupsOf(int? focusIndex) { + if (focusIndex == null) return artifactGroups(widget.steps); + final group = visitArtifactGroup(widget.steps, focusIndex); + return group == null ? const [] : [group]; + } + Future _select(ArtifactGroup group, ArtifactRecord artifact) async { final identity = artifactVisitIdentity(group, artifact); final resolved = artifact.hasUrl @@ -227,12 +243,28 @@ class _ArtifactGalleryPageState extends State { setState(() => _status = message); } + /// The page's one summary line: a focused visit uses its own capture summary, + /// a run-level page uses the run header, and an empty reply says so. + String _summary(List groups) { + final focusIndex = widget.focusIndex; + if (focusIndex != null && + focusIndex >= 0 && + focusIndex < widget.steps.length) { + final focused = widget.steps[focusIndex]; + final count = groups.fold( + 0, + (total, group) => total + group.artifacts.length, + ); + return artifactsSummary(focused, count: count); + } + if (widget.steps.isEmpty) return 'No steps recorded for this run.'; + return artifactsHeader(widget.steps, executing: widget.executing); + } + @override Widget build(BuildContext context) { final groups = _groups; - final summary = widget.steps.isEmpty - ? 'No steps recorded for this run.' - : artifactsHeader(widget.steps, executing: widget.executing); + final summary = _summary(groups); final body = Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_cupertino.dart b/app/lib/features/runs/ui/run_detail_cupertino.dart index 2aa71880..4da3afa0 100644 --- a/app/lib/features/runs/ui/run_detail_cupertino.dart +++ b/app/lib/features/runs/ui/run_detail_cupertino.dart @@ -20,6 +20,7 @@ Widget buildCupertinoRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required String configuredEndpoint, }) { final theme = CupertinoTheme.of(context); return RunDetailTabs( @@ -28,6 +29,7 @@ Widget buildCupertinoRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + configuredEndpoint: configuredEndpoint, 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 43e34533..8d27e80e 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -20,6 +20,7 @@ Widget buildMaterialRunDetail({ required String? copyStatus, required VoidCallback onBack, required VoidCallback onCopy, + required String configuredEndpoint, }) { final theme = Theme.of(context); return RunDetailTabs( @@ -28,6 +29,7 @@ Widget buildMaterialRunDetail({ copying: copying, copyStatus: copyStatus, onCopy: onCopy, + configuredEndpoint: configuredEndpoint, header: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index 177217a1..f9373687 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -55,7 +55,7 @@ class _RunDetailTabStripState extends State { final cupertino = usesCupertinoHost(context); return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: _ScrollWhenOverflowing( + child: ScrollWhenOverflowing( child: KeyedSubtree( key: const Key('run-detail-tabs'), child: cupertino ? _cupertinoControl() : _materialControl(), @@ -97,8 +97,11 @@ class _RunDetailTabStripState extends State { /// Gives [child] at least the pane width, then scrolls instead of squeezing it /// below its content width. -class _ScrollWhenOverflowing extends StatelessWidget { - const _ScrollWhenOverflowing({required this.child}); +/// +/// The run detail's tab strips both use this, so the pointer-drag rule and the +/// minimum-width rule live in one place. +class ScrollWhenOverflowing extends StatelessWidget { + const ScrollWhenOverflowing({super.key, required this.child}); final Widget child; diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index ac28bd04..6641994b 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -9,6 +9,8 @@ import 'run_detail_tab.dart'; import 'run_detail_tab_bodies.dart'; import 'run_detail_tab_strip.dart'; import 'run_detail_timeline.dart'; +import 'run_detail_visit.dart'; +import 'run_detail_visit_facts.dart'; /// The least height the selected tab keeps for its own content. /// @@ -23,7 +25,7 @@ const double kRunDetailMinContentHeight = 240; /// /// The Graph tab fills its slot with [RunGraphView] from the run's own pinned /// graph and recorded steps. A visited stage click selects that stage's latest -/// recorded visit and switches to Timeline, where the row is highlighted. A +/// recorded visit and switches to Timeline, where that visit's pane opens. A /// node with no recorded visit reports nothing, so no visit is invented. class RunDetailTabs extends StatefulWidget { const RunDetailTabs({ @@ -34,6 +36,7 @@ class RunDetailTabs extends StatefulWidget { required this.copying, required this.copyStatus, required this.onCopy, + required this.configuredEndpoint, }); final JsonMap run; @@ -47,6 +50,10 @@ class RunDetailTabs extends StatefulWidget { final String? copyStatus; final VoidCallback onCopy; + /// 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; + @override State createState() => _RunDetailTabsState(); } @@ -71,15 +78,24 @@ class _RunDetailTabsState extends State { /// Selects the stage's latest recorded visit. An unvisited stage has none, /// so the detail stays where it is rather than fabricating a visit. void _openStage(String stageKey) { - final visit = latestDetailVisit(widget.run['steps'], stageKey); - if (visit == null) return; + final index = latestDetailVisitIndex(widget.run['steps'], stageKey); + if (index == null) return; setState(() { _selectedStage = stageKey; - _selectedVisit = visit.sequence; + _selectedVisit = index; _tab = RunDetailTab.timeline; }); } + /// Opens one recorded timeline row. The row index is also the index into the + /// detail's own steps, so the pane reads exactly the visit it came from. + void _openVisit(int index) { + if (detailVisitStepAt(widget.run, index) == null) return; + setState(() => _selectedVisit = index); + } + + void _closeVisit() => setState(() => _selectedVisit = null); + @override Widget build(BuildContext context) { return LayoutBuilder( @@ -151,10 +167,33 @@ class _RunDetailTabsState extends State { cupertino: widget.cupertino, ); case RunDetailTab.timeline: + final visits = detailTimeline(widget.run['steps']); + final index = _selectedVisit; + if (index != null && index >= 0 && index < visits.length) { + final step = detailVisitStepAt(widget.run, index); + if (step != null) { + return KeyedSubtree( + key: const Key('run-detail-tab-body-timeline'), + child: RunVisitPane( + run: widget.run, + visit: visits[index], + visitIndex: index, + step: step, + runSteps: detailRunSteps(widget.run), + configuredEndpoint: widget.configuredEndpoint, + cupertino: widget.cupertino, + onClose: _closeVisit, + ), + ); + } + } return RunTimelineList( - visits: detailTimeline(widget.run['steps']), - selectedSequence: _selectedVisit, + visits: visits, + selectedSequence: index != null && index >= 0 && index < visits.length + ? visits[index].sequence + : null, cupertino: widget.cupertino, + onSelected: _openVisit, ); } } diff --git a/app/lib/features/runs/ui/run_detail_timeline.dart b/app/lib/features/runs/ui/run_detail_timeline.dart index 66bf4689..90535e40 100644 --- a/app/lib/features/runs/ui/run_detail_timeline.dart +++ b/app/lib/features/runs/ui/run_detail_timeline.dart @@ -5,20 +5,25 @@ import 'run_detail_content.dart'; /// The Timeline tab's recorded visits, one native row per visit. /// -/// [selectedSequence] is the server sequence of the visit selected from the -/// Graph tab. Only an actual recorded visit can match, so an unvisited stage -/// leaves every row unselected. +/// [onSelected] receives the row's index in [visits], so the caller opens +/// exactly the recorded step it was built from. [selectedSequence] highlights a +/// row when a selection is applied while the list is rendered; the current +/// flow replaces the rows with the pane, so it only matters for a defensive +/// host that keeps both visible. Only an actual recorded visit can match, so an +/// unvisited stage leaves every row unselected. class RunTimelineList extends StatelessWidget { const RunTimelineList({ super.key, required this.visits, required this.cupertino, this.selectedSequence, + this.onSelected, }); final List visits; final bool cupertino; final int? selectedSequence; + final ValueChanged? onSelected; @override Widget build(BuildContext context) { @@ -38,6 +43,7 @@ class RunTimelineList extends StatelessWidget { visit: visits[index], selected: visits[index].sequence == selectedSequence, cupertino: cupertino, + onTap: onSelected == null ? null : () => onSelected!(index), ), ]; if (cupertino) { @@ -59,19 +65,22 @@ class RunTimelineList extends StatelessWidget { } } -/// One recorded visit. [selected] highlights the row the Graph tab selected; -/// it is never true for a stage with no recorded visit. +/// One recorded visit. [selected] marks the row an applied selection identifies; +/// the current flow opens the pane instead of leaving a highlighted row. It is +/// never true for a stage with no recorded visit. class RunTimelineRow extends StatelessWidget { const RunTimelineRow({ super.key, required this.visit, required this.selected, required this.cupertino, + this.onTap, }); final DetailVisit visit; final bool selected; final bool cupertino; + final VoidCallback? onTap; @override Widget build(BuildContext context) { @@ -93,6 +102,7 @@ class RunTimelineRow extends StatelessWidget { context, ) : null, + onTap: onTap, ), ); } @@ -101,6 +111,7 @@ class RunTimelineRow extends StatelessWidget { leading: Icon(selected ? Icons.check_circle : Icons.circle_outlined), title: Text(visit.title), subtitle: Text(visit.subtitle), + onTap: onTap, ); } } diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index 3e510b62..6e2bbcb9 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; +import '../../../core/transport/pipelines_client.dart'; import '../../../ui/adaptive/host.dart'; import 'run_detail_actions.dart'; import 'run_detail_content.dart'; @@ -45,6 +46,7 @@ class _RunDetailViewState extends State { final run = widget.controller.detail; if (run == null) return _placeholder(context, cupertino: cupertino); final prompt = detailPrompt(run); + final endpoint = configuredGatewayEndpoint(widget.gateway); final headerActions = RunDetailActions( run: run, gateway: widget.gateway, @@ -62,6 +64,7 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: true), + configuredEndpoint: endpoint, ) : buildMaterialRunDetail( context: context, @@ -73,6 +76,7 @@ class _RunDetailViewState extends State { copyStatus: _copyStatus, onBack: widget.onBack, onCopy: () => _copyPrompt(prompt ?? '', cupertino: false), + configuredEndpoint: endpoint, ); }, ); diff --git a/app/lib/features/runs/ui/run_detail_visit.dart b/app/lib/features/runs/ui/run_detail_visit.dart new file mode 100644 index 00000000..93c9f818 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit.dart @@ -0,0 +1,215 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import 'run_detail_content.dart'; +import 'run_detail_visit_facts.dart'; +import 'run_detail_visit_sections.dart'; + +/// The selected recorded visit inside the Timeline tab. +/// +/// It leads with the visit's own headline facts, then native tabbed sections. +/// A fact the reply did not record is not drawn at all; a blank verdict or +/// diagnostic is not rendered as an empty decision. +class RunVisitPane extends StatefulWidget { + const RunVisitPane({ + super.key, + required this.run, + required this.visit, + required this.visitIndex, + required this.step, + required this.runSteps, + required this.configuredEndpoint, + required this.cupertino, + required this.onClose, + }); + + final JsonMap run; + final DetailVisit visit; + + /// The visit's index in [runSteps], so the artifacts section can open exactly + /// this visit's gallery group. + final int visitIndex; + + final JsonMap step; + final List runSteps; + final String configuredEndpoint; + final bool cupertino; + final VoidCallback onClose; + + @override + State createState() => _RunVisitPaneState(); +} + +class _RunVisitPaneState extends State { + RunVisitSection _section = RunVisitSection.input; + + @override + void didUpdateWidget(covariant RunVisitPane oldWidget) { + super.didUpdateWidget(oldWidget); + // A different visit starts at its first section, like a newly opened pane. + if (oldWidget.visit.sequence != widget.visit.sequence || + oldWidget.visit.stage != widget.visit.stage) { + _section = RunVisitSection.input; + } + } + + @override + Widget build(BuildContext context) { + final style = _VisitStyle.of(context); + final facts = detailVisitFacts(widget.step); + final verdict = detailVisitVerdict(widget.step); + final diagnostic = detailVisitDiagnostic(widget.step); + return Column( + key: const Key('run-visit-pane'), + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Flexible( + flex: 3, + fit: FlexFit.loose, + child: SingleChildScrollView( + key: const Key('run-visit-facts'), + padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _bar(style), + for (final fact in facts) _FactRow(fact: fact, style: style), + if (verdict != null) ...[ + const SizedBox(height: 8), + Text('Verdict', style: style.heading), + if (verdict.option != null) Text(verdict.option!), + if (verdict.reason != null) + Text(verdict.reason!, style: style.value), + ], + if (diagnostic != null) ...[ + const SizedBox(height: 8), + Text('Diagnostic', style: style.heading), + Text(diagnostic, style: style.value), + ], + ], + ), + ), + ), + RunVisitSectionStrip( + selected: _section, + onSelected: (section) => setState(() => _section = section), + ), + Expanded( + flex: 2, + child: runVisitSectionBody( + section: _section, + run: widget.run, + step: widget.step, + visitIndex: widget.visitIndex, + stageKey: widget.visit.stage, + runSteps: widget.runSteps, + configuredEndpoint: widget.configuredEndpoint, + cupertino: widget.cupertino, + ), + ), + ], + ); + } + + Widget _bar(_VisitStyle style) { + final close = widget.cupertino + ? CupertinoButton( + key: const Key('run-visit-back'), + padding: EdgeInsets.zero, + onPressed: widget.onClose, + child: const Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(CupertinoIcons.back), + SizedBox(width: 4), + Flexible(child: Text('Back to timeline')), + ], + ), + ) + : TextButton.icon( + key: const Key('run-visit-back'), + onPressed: widget.onClose, + icon: const Icon(Icons.arrow_back), + label: const Text('Back to timeline'), + ); + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Align(alignment: AlignmentDirectional.centerStart, child: close), + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 0, 0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.visit.title, + key: const Key('run-visit-title'), + style: style.heading, + ), + ], + ), + ), + ], + ), + ); + } +} + +class _FactRow extends StatelessWidget { + const _FactRow({required this.fact, required this.style}); + + final VisitFact fact; + final _VisitStyle style; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(top: 4), + child: Text.rich( + TextSpan( + children: [ + TextSpan(text: '${fact.label}: ', style: style.muted), + TextSpan(text: fact.value, style: style.value), + ], + ), + ), + ); + } +} + +/// Host text roles only: no palette, font family or explicit size. +class _VisitStyle { + const _VisitStyle({ + required this.value, + required this.muted, + required this.heading, + }); + + factory _VisitStyle.of(BuildContext context) { + if (usesCupertinoHost(context)) { + final theme = CupertinoTheme.of(context); + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return _VisitStyle( + value: theme.textTheme.textStyle, + muted: theme.textTheme.textStyle.copyWith(color: secondary), + heading: theme.textTheme.navTitleTextStyle, + ); + } + final theme = Theme.of(context); + return _VisitStyle( + value: theme.textTheme.bodyMedium ?? const TextStyle(), + muted: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + heading: theme.textTheme.titleSmall ?? const TextStyle(), + ); + } + + final TextStyle value; + final TextStyle muted; + final TextStyle heading; +} diff --git a/app/lib/features/runs/ui/run_detail_visit_artifacts.dart b/app/lib/features/runs/ui/run_detail_visit_artifacts.dart new file mode 100644 index 00000000..6ccfb4b2 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_artifacts.dart @@ -0,0 +1,112 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../artifacts/domain/artifact_groups.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/artifact_summary.dart'; +import '../../artifacts/ui/artifact_gallery_action.dart'; +import '../../artifacts/ui/artifact_visit_list.dart'; + +/// The visit's recorded stage artifacts, in recorded order. +/// +/// Selecting a row opens the existing artifact gallery page for exactly this +/// visit, so the pane never grows a second viewer or a link-only substitute. +/// The page receives the whole run so a shared `public/` file stays with the +/// visit that first recorded it, and it lists exactly the rows shown here. +/// +/// An empty list is never described as "nothing recorded" on its own: the +/// existing capture semantics say whether the capture is unavailable, still +/// pending or explicitly empty for this visit. +class RunVisitArtifacts extends StatelessWidget { + const RunVisitArtifacts({ + super.key, + required this.step, + required this.visitIndex, + required this.runSteps, + required this.configuredEndpoint, + }); + + final JsonMap step; + + /// The visit's index in [runSteps], so the opened page is the same group. + final int visitIndex; + + final List runSteps; + final String configuredEndpoint; + + @override + Widget build(BuildContext context) { + final artifacts = visitArtifacts(step, runSteps); + final notes = artifactCaptureNotes(step); + if (artifacts.isEmpty) { + return ListView( + key: const Key('run-visit-body-artifacts'), + padding: const EdgeInsets.all(16), + children: [ + Text(artifactsSummary(step, count: 0)), + for (final note in notes) + Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)), + ], + ); + } + void open() => showArtifactGallery( + context, + steps: runSteps.isEmpty ? [step] : runSteps, + focusIndex: runSteps.isEmpty ? 0 : visitIndex, + configuredEndpoint: configuredEndpoint, + ); + final noteRows = [ + for (final note in notes) + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0), + child: Text(note), + ), + ]; + if (usesCupertinoHost(context)) { + return ListView( + key: const Key('run-visit-body-artifacts'), + children: [ + ...noteRows, + CupertinoListSection.insetGrouped( + children: [ + for (final artifact in artifacts) + _CupertinoArtifactRow(artifact: artifact, onTap: open), + ], + ), + ], + ); + } + return ListView( + key: const Key('run-visit-body-artifacts'), + children: [ + ...noteRows, + for (final artifact in artifacts) + ListTile( + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), + trailing: const Icon(Icons.chevron_right), + onTap: open, + ), + ], + ); + } +} + +class _CupertinoArtifactRow extends StatelessWidget { + const _CupertinoArtifactRow({required this.artifact, required this.onTap}); + + final ArtifactRecord artifact; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + return CupertinoListTile( + title: Text(artifactDisplayName(artifact)), + subtitle: Text(artifactFactsLabel(artifact)), + trailing: const Icon(CupertinoIcons.chevron_forward), + onTap: onTap, + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_definition.dart b/app/lib/features/runs/ui/run_detail_visit_definition.dart new file mode 100644 index 00000000..e5d93a4e --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_definition.dart @@ -0,0 +1,46 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../graph/widgets/stage_definition_view.dart'; +import 'run_detail_content.dart'; +import 'run_detail_visit_facts.dart'; + +/// The Definition section: the authored definition this run pinned for the +/// visit's stage, rendered by the landed [StageDefinitionView]. +/// +/// When the reply's graph does not declare the stage, the pane's exact missing +/// sentence is shown instead. Nothing is reconstructed from the current source. +class RunVisitDefinition extends StatelessWidget { + const RunVisitDefinition({ + super.key, + required this.run, + required this.stageKey, + }); + + final JsonMap run; + final String stageKey; + + @override + Widget build(BuildContext context) { + final graph = detailGraph(run); + if (!detailVisitHasDefinition(graph, stageKey)) { + return ListView( + key: const Key('run-visit-body-definition'), + padding: const EdgeInsets.all(16), + children: const [Text(unknownStageDefinition)], + ); + } + final pipelineId = run['pipeline_id']; + final version = run['version']; + return KeyedSubtree( + key: const Key('run-visit-body-definition'), + child: StageDefinitionView( + graph: graph!, + stageKey: stageKey, + pipelineId: pipelineId is num ? pipelineId.toInt() : 0, + pipelineName: detailPipeline(run), + version: version is num ? version.toInt() : 0, + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_facts.dart b/app/lib/features/runs/ui/run_detail_visit_facts.dart new file mode 100644 index 00000000..b26dfa4a --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_facts.dart @@ -0,0 +1,105 @@ +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_definition.dart'; +import '../../pipelines/pipeline_format.dart'; +import 'run_detail_content.dart'; + +/// The exact empty wording for a visit's recorded Input and Output. They are +/// the run tabs' own sentences, so a visit never says something different for +/// the same absent fact. +const String visitEmptyInput = 'No input recorded.'; +const String visitEmptyOutput = 'No output recorded.'; + +/// One always-visible fact of a recorded visit. +typedef VisitFact = ({String label, String value}); + +/// The detail's own recorded steps as maps, in recorded order. +List detailRunSteps(JsonMap run) { + final steps = run['steps']; + if (steps is! List) return const []; + return steps.whereType().map(JsonMap.from).toList(); +} + +/// The raw step at [index] of the detail's own `steps`, or null when the reply +/// has no such recorded visit. +/// +/// The order is the server's recorded order, the same order [detailTimeline] +/// uses, so a row and its pane always describe one visit. +JsonMap? detailVisitStepAt(JsonMap run, int index) { + final steps = detailRunSteps(run); + if (index < 0 || index >= steps.length) return null; + return steps[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) { + final visits = detailTimeline(steps); + int? latest; + for (var index = 0; index < visits.length; index += 1) { + if (visits[index].stage == stageKey) latest = index; + } + return latest; +} + +/// The visit's recorded facts, in the pane's order. A field the server did not +/// record is absent rather than zero, false or a guessed value. +List detailVisitFacts(JsonMap step) { + final facts = []; + final status = _text(step['status']); + if (status != null) facts.add((label: 'Status', value: status)); + final outcome = _text(step['outcome']); + if (outcome != null) facts.add((label: 'Outcome', value: outcome)); + final duration = detailVisitDuration(step); + if (duration != null) facts.add((label: 'Duration', value: duration)); + final model = detailVisitProviderModel(step); + if (model != null) facts.add((label: 'Provider/model', value: model)); + final target = _text(step['target']); + if (target != null) facts.add((label: 'Target', value: target)); + return facts; +} + +/// The visit's duration, only when the server recorded both timestamps and the +/// finish is not before the start. One stamp is not a zero-length visit. +String? detailVisitDuration(JsonMap step) { + final seconds = durationSeconds( + _text(step['started_at']), + _text(step['finished_at']), + ); + return seconds == null ? null : formatDuration(seconds); +} + +/// The effective provider/model this visit ran with, joined as +/// `provider / model` when both were recorded. A visit that recorded neither +/// has no row; one recorded part is shown alone, never completed locally. +String? detailVisitProviderModel(JsonMap step) { + final provider = _text(step['provider']); + final model = _text(step['model']); + if (provider != null && model != null) return '$provider / $model'; + return provider ?? model; +} + +/// A recorded verdict, or null when the server recorded no option and no +/// reason. An empty recorded verdict is not rendered as a decision. +({String? option, String? reason})? detailVisitVerdict(JsonMap step) { + final verdict = step['verdict']; + if (verdict is! Map) return null; + final option = _text(verdict['option']); + final reason = _text(verdict['reason']); + if (option == null && reason == null) return null; + return (option: option, reason: reason); +} + +/// The visit's diagnostic exactly as recorded, or null when it is blank. +String? detailVisitDiagnostic(JsonMap step) => _text(step['diagnostic']); + +/// Whether the reply's pinned graph declares [stageKey], so the Definition +/// section shows the authored definition rather than its missing wording. +bool detailVisitHasDefinition(JsonMap? graph, String stageKey) => + graph != null && stageDefinitionFor(graph, stageKey) != null; + +String? _text(dynamic value) { + if (value == null) return null; + final text = '$value'.trim(); + return text.isEmpty ? null : text; +} diff --git a/app/lib/features/runs/ui/run_detail_visit_sections.dart b/app/lib/features/runs/ui/run_detail_visit_sections.dart new file mode 100644 index 00000000..7f3e0321 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_sections.dart @@ -0,0 +1,124 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import 'run_detail_tab_bodies.dart'; +import 'run_detail_tab_strip.dart'; +import 'run_detail_visit_artifacts.dart'; +import 'run_detail_visit_definition.dart'; +import 'run_detail_visit_facts.dart'; +import 'run_detail_visit_session.dart'; + +/// The visit pane's recorded sections, in the Android audit order the web +/// client follows: the turn's Input and Output, its Artifacts, its Session and +/// the authored Definition. +enum RunVisitSection { + input('Input'), + output('Output'), + artifacts('Artifacts'), + session('Session'), + definition('Definition'); + + const RunVisitSection(this.label); + + final String label; +} + +/// The visit pane's native tab strip: a Material segmented button or a Cupertino +/// segmented control. It scrolls instead of squeezing the labels when a narrow +/// pane or scaled text cannot fit them. +class RunVisitSectionStrip extends StatelessWidget { + const RunVisitSectionStrip({ + super.key, + required this.selected, + required this.onSelected, + }); + + final RunVisitSection selected; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: ScrollWhenOverflowing( + child: KeyedSubtree( + key: const Key('run-visit-tabs'), + child: cupertino ? _cupertinoControl() : _materialControl(), + ), + ), + ); + } + + Widget _materialControl() => SegmentedButton( + segments: [ + for (final section in RunVisitSection.values) + ButtonSegment(value: section, label: _label(section)), + ], + selected: {selected}, + showSelectedIcon: false, + onSelectionChanged: (selection) => onSelected(selection.single), + ); + + Widget _cupertinoControl() => CupertinoSegmentedControl( + groupValue: selected, + onValueChanged: onSelected, + children: { + for (final section in RunVisitSection.values) + section: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: _label(section), + ), + }, + ); + + Widget _label(RunVisitSection section) => KeyedSubtree( + key: ValueKey('run-visit-tab-${section.name}'), + child: Text(section.label, maxLines: 1, softWrap: false), + ); +} + +/// The selected section's body for one recorded visit. +Widget runVisitSectionBody({ + required RunVisitSection section, + required JsonMap run, + required JsonMap step, + required int visitIndex, + required String stageKey, + required List runSteps, + required String configuredEndpoint, + required bool cupertino, +}) { + switch (section) { + case RunVisitSection.input: + return runDetailFieldTab( + tabKey: 'visit-input', + value: step['input'], + empty: visitEmptyInput, + cupertino: cupertino, + ); + case RunVisitSection.output: + return runDetailFieldTab( + tabKey: 'visit-output', + value: step['output'], + empty: visitEmptyOutput, + cupertino: cupertino, + ); + case RunVisitSection.artifacts: + return RunVisitArtifacts( + step: step, + visitIndex: visitIndex, + runSteps: runSteps, + configuredEndpoint: configuredEndpoint, + ); + case RunVisitSection.session: + return RunVisitSession( + step: step, + configuredEndpoint: configuredEndpoint, + ); + case RunVisitSection.definition: + return RunVisitDefinition(run: run, stageKey: stageKey); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_session.dart b/app/lib/features/runs/ui/run_detail_visit_session.dart new file mode 100644 index 00000000..19268625 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_session.dart @@ -0,0 +1,149 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +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 'run_detail_visit_session_state.dart'; + +/// The visit's recorded session pointer and, when the visit exported one, a +/// read-only external open of that document. +/// +/// The state comes from [detailVisitSession], so a legacy `session.html`, a +/// repair, a still-running session and a failed one each report what the server +/// recorded. 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.step, + required this.configuredEndpoint, + this.openExternal = openArtifactExternally, + }); + + final JsonMap step; + final String configuredEndpoint; + final ArtifactExternalOpen openExternal; + + @override + State createState() => _RunVisitSessionState(); +} + +class _RunVisitSessionState extends State { + String? _status; + + Future _open(ResolvedArtifactUrl resolved) async { + final opened = await widget.openExternal(resolved.uri); + if (!mounted) return; + setState( + () => _status = opened + ? 'Link opened externally.' + : 'Could not open the link.', + ); + } + + @override + Widget build(BuildContext context) { + final session = detailVisitSession(widget.step); + final export = session.export; + final resolved = export == null + ? null + : resolveArtifactUrl(widget.configuredEndpoint, export.artifact.url); + final note = export?.statusNote; + final children = [ + if (session.sessionId != null) + _SessionFact(label: 'Session', value: session.sessionId!), + if (export != null) ...[ + if (note != null) Text(note), + if (resolved == null) + const Text(visitSessionEndpointMissing) + else + _openButton(export.artifact, resolved), + ] else + Text(session.message), + if (_status != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Semantics(liveRegion: true, child: Text(_status!)), + ), + ]; + if (usesCupertinoHost(context)) { + return ListView( + key: const Key('run-visit-body-session'), + children: [ + CupertinoListSection.insetGrouped( + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: _spaced(children), + ), + ), + ], + ), + ], + ); + } + return ListView( + key: const Key('run-visit-body-session'), + padding: const EdgeInsets.all(16), + children: _spaced(children), + ); + } + + Widget _openButton(ArtifactRecord export, ResolvedArtifactUrl resolved) { + final label = 'Open ${export.name.isEmpty ? 'session.html' : export.name}'; + if (usesCupertinoHost(context)) { + return CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () => _open(resolved), + child: Text(label), + ); + } + return Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton(onPressed: () => _open(resolved), child: Text(label)), + ); + } + + List _spaced(List children) => [ + for (var index = 0; index < children.length; index += 1) ...[ + if (index > 0) const SizedBox(height: 8), + children[index], + ], + ]; +} + +class _SessionFact extends StatelessWidget { + const _SessionFact({required this.label, required this.value}); + + final String label; + final String value; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final cupertino = CupertinoTheme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: usesCupertinoHost(context) + ? cupertino.textTheme.tabLabelTextStyle.copyWith( + color: CupertinoColors.secondaryLabel.resolveFrom(context), + ) + : (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: 2), + Text(value), + ], + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_visit_session_state.dart b/app/lib/features/runs/ui/run_detail_visit_session_state.dart new file mode 100644 index 00000000..0a980675 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_visit_session_state.dart @@ -0,0 +1,230 @@ +import '../../../core/api_gateway.dart'; +import '../../artifacts/domain/artifact_record.dart'; +import '../../artifacts/domain/artifact_selection.dart'; + +/// The exact wording for a visit that never started a harness session, in the +/// web audit pane's order: a skipped visit, a stopped one, a model visit whose +/// session is still being created, a failed one, and a model visit with no +/// identity at all. Only a non-model visit with nothing recorded gets the +/// generic sentence. +const String visitSessionSkipped = + 'This visit was skipped; no harness session was started.'; +const String visitSessionStopped = + 'The stage stopped before a harness session was recorded.'; +const String visitSessionStarting = 'The stage session is being created.'; +const String visitSessionFailed = 'The stage did not create a harness session.'; +const String visitSessionNoIdentity = + 'Runtime error: this model stage has no recorded session identity.'; +const String visitSessionNone = 'This visit has no harness session.'; + +/// An export that exists but cannot be resolved through the configured server. +const String visitSessionEndpointMissing = + 'Set the server URL in Settings to open the session.'; + +/// A recorded session export document and the evidence the server recorded for +/// it. +class VisitSessionExport { + const VisitSessionExport({ + required this.artifact, + this.status, + this.diagnostic, + this.truncated = false, + }); + + final ArtifactRecord artifact; + final String? status; + final String? diagnostic; + final bool truncated; + + /// A partial or failed export is still the recorded document; it stays + /// openable and the pane says what the evidence reports. + bool get isComplete => status == 'complete' && !truncated; + + /// The evidence sentence shown beside a present but incomplete export, or + /// null when the export is complete or the visit recorded no evidence. + String? get statusNote { + if (isComplete) return null; + if (status == null && !truncated) return null; + return 'This export is ${status ?? 'partial'}; full session evidence is ' + 'not available.'; + } +} + +/// A visit's recorded session: its identity, an openable export document and, +/// when neither exists, the one sentence describing the recorded state. +class VisitSessionState { + const VisitSessionState({this.sessionId, this.export, this.message = ''}); + + final String? sessionId; + final VisitSessionExport? export; + + /// Empty exactly when [export] is present. + final String message; +} + +/// Resolves the recorded session state without inventing a session. +/// +/// The export is looked up through the recorded export evidence (including a +/// repair that replaced it) and then, for a historical visit that recorded no +/// evidence at all, through the `session.html` its inventory carries. When the +/// evidence names no file, its own status and diagnostic are reported instead +/// of claiming the inventory is empty. +VisitSessionState detailVisitSession(JsonMap step) { + final sessionId = detailVisitSessionIdentity(step); + final export = detailVisitSessionExport(step); + if (export != null) { + return VisitSessionState(sessionId: sessionId, export: export); + } + if (sessionId != null) { + return VisitSessionState( + sessionId: sessionId, + message: _missingExportMessage(step, sessionId), + ); + } + return VisitSessionState(message: _noSessionMessage(step)); +} + +/// The recorded harness session identity, from the step or its export evidence. +String? detailVisitSessionIdentity(JsonMap step) { + final direct = _text(step['session_id']); + if (direct != null) return direct; + final evidence = _firstEvidence(step); + return evidence == null ? null : _text(evidence['session_id']); +} + +/// The visit's recorded export document, or null when no recorded export name +/// is present in the inventory. +/// +/// The step's own `session_export` is preferred; a repair document is used +/// when that is the file the inventory actually carries. A visit with no export +/// evidence at all falls back to its `session.html` system artifact, exactly as +/// the web audit pane does for runs recorded before the evidence field existed. +VisitSessionExport? detailVisitSessionExport(JsonMap step) { + final evidence = _exportEvidence(step); + for (final entry in evidence) { + final artifact = _artifactNamed(step, _text(entry['html'])); + if (artifact == null) continue; + return VisitSessionExport( + artifact: artifact, + status: _text(entry['status']), + diagnostic: _text(entry['diagnostic']), + truncated: entry['truncated'] == true, + ); + } + if (evidence.isNotEmpty) return null; + for (final artifact in systemArtifacts(step)) { + if (artifact.name == 'session.html') { + return VisitSessionExport(artifact: artifact); + } + } + return null; +} + +String _missingExportMessage(JsonMap step, String sessionId) { + final evidence = _firstEvidence(step); + final recovery = step['session_export_recovery']; + final recoveryStatus = recovery is Map ? _text(recovery['status']) : null; + final evidenceStatus = evidence == null ? null : _text(evidence['status']); + final String status; + if (recoveryStatus == 'pending' || recoveryStatus == 'running') { + status = 'pending recovery'; + } else if (evidenceStatus == 'complete') { + status = 'not available in the artifact inventory'; + } else { + status = evidenceStatus ?? 'not yet available'; + } + final diagnostic = evidence == null ? null : _text(evidence['diagnostic']); + final suffix = diagnostic == null ? '' : ' $diagnostic'; + return 'Session $sessionId is recorded. Its export is $status.$suffix'; +} + +String _noSessionMessage(JsonMap step) { + final status = _text(step['status']); + if (status == 'skipped' || _text(step['outcome']) == 'skipped') { + return visitSessionSkipped; + } + if (status == 'canceled' || status == 'interrupted') { + return visitSessionStopped; + } + final model = _text(step['provider']) != null || _text(step['model']) != null; + if (!model) return visitSessionNone; + if (status == 'running') return visitSessionStarting; + if (status == 'failed') { + final diagnostic = _text(step['diagnostic']); + return diagnostic == null + ? visitSessionFailed + : '$visitSessionFailed $diagnostic'; + } + return visitSessionNoIdentity; +} + +/// The recorded export evidence, most current first: a complete repair, then a +/// complete original, then every remaining candidate. A failed later attempt +/// never hides an earlier verified document; an older original never hides the +/// repair that replaced it. +List _exportEvidence(JsonMap step) { + final repairs = []; + final recordedRepairs = step['session_export_repairs']; + if (recordedRepairs is List) { + for (final entry in recordedRepairs.reversed) { + if (entry is Map) repairs.add(entry); + } + } + final original = step['session_export']; + final ordered = []; + void add(Map entry) { + for (final candidate in ordered) { + if (identical(candidate, entry)) return; + } + ordered.add(entry); + } + + for (final repair in repairs) { + if (_isComplete(repair)) add(repair); + } + if (original is Map && _isComplete(original)) add(original); + for (final repair in repairs) { + add(repair); + } + if (original is Map) add(original); + return ordered; +} + +Map? _firstEvidence(JsonMap step) { + final original = step['session_export']; + if (original is Map) return original; + final repairs = step['session_export_repairs']; + if (repairs is List) { + for (final entry in repairs.reversed) { + if (entry is Map) return entry; + } + } + return null; +} + +bool _isComplete(Map evidence) => + _text(evidence['status']) == 'complete' && + _positive(evidence['messages']) && + _positive(evidence['html_bytes']) && + evidence['truncated'] != true && + _text(evidence['diagnostic']) == null; + +bool _positive(dynamic value) { + if (value is num) return value > 0; + if (value is String) return (int.tryParse(value.trim()) ?? 0) > 0; + return false; +} + +ArtifactRecord? _artifactNamed(JsonMap step, String? name) { + if (name == null) return null; + for (final artifact in artifactsOf(step)) { + if (artifact.name == name) return artifact; + } + return null; +} + +String? _text(dynamic value) { + if (value == null) return null; + final text = '$value'.trim(); + return text.isEmpty ? null : text; +} diff --git a/app/notes/R4-visit.md b/app/notes/R4-visit.md new file mode 100644 index 00000000..082b0499 --- /dev/null +++ b/app/notes/R4-visit.md @@ -0,0 +1,190 @@ +# R4 — recorded-visit pane + +## Delivered + +The Timeline tab now opens a real recorded visit. Selecting a row, or clicking a +visited stage in the Graph tab, shows that visit inside the Timeline tab: + +- **Facts** — the row's exact stage/visit title, then only the fields the reply + recorded: Status, Outcome, Duration (only when both `started_at` and + `finished_at` parse and the finish is not before the start), Provider/model + (`provider / model`, or the one part recorded), Target, a recorded Verdict + (option and reason) and the visit's Diagnostic. A blank field is absent, never + `0`, `false`, `0s` or a guessed value. +- **Native sections** — Input, Output, Artifacts, Session, Definition, using the + Material segmented button or Cupertino segmented control. The strip scrolls + rather than squeezing labels at 320/2x. + - Input/Output use the run detail's existing field rendering and the exact + empty sentences `No input recorded.` / `No output recorded.`. + - Artifacts lists this visit's stage files (`visitArtifacts`, so a shared + `public/` file stays with the visit that first recorded it) and opens the + existing artifact gallery page for that visit. The page is given the whole + run and the focused visit, so it lists exactly the rows the pane lists and + keeps the run's own visit group. An empty list uses the landed per-visit + capture wording (`Artifacts · capture pending` for a running visit, + `Artifacts · capture unavailable` when the field is absent, `Artifacts · + not recorded for this visit` only for an explicitly empty capture) and shows + the partial-capture notes when the scan was bounded. + - Session shows the recorded session identity and, when the visit exported + one, `Open `. The recorded URL is resolved by the landed + `resolveArtifactUrl` and opened through `openArtifactExternally`; a refusal + or an unresolved relative URL is reported, never silently swallowed. The + state comes from the recorded export evidence (including a repair), falls + back to the legacy `session.html` system file web audit uses, and otherwise + reports the recorded state in the web client's words: skipped, stopped, + session being created, failed with its diagnostic, or the runtime error for + a model visit with no identity. An export whose evidence is partial or + failed stays openable and says so. + - Definition embeds the landed `StageDefinitionView` for the run's own pinned + graph and stage, so the authored prompt/output/outcomes/raw source show + exactly as landed. When the reply does not declare the stage, the landed + exact sentence `This stage is not declared in this pipeline version. No + definition has been reconstructed.` is shown instead. +- **Back** — `Back to timeline` (native back arrow / Cupertino chevron) closes + the pane and restores the rows. The run header, Changes, Artifacts, Rename, + Cancel, Retry and Decide actions are untouched and stay outside the tabs. +- A different run clears the selection; an unvisited Graph node still opens + nothing. + +## Files + +Added: + +- `app/lib/features/runs/ui/run_detail_visit.dart` — pane layout, facts, verdict + and diagnostic, Back. +- `app/lib/features/runs/ui/run_detail_visit_facts.dart` — pure step lookup, + duration/provider/model/verdict/definition facts, exact wording. +- `app/lib/features/runs/ui/run_detail_visit_session_state.dart` — recorded + session/export state: identity, repair/legacy export resolution and the + state-specific wording. +- `app/lib/features/runs/ui/run_detail_visit_sections.dart` — section enum, + adaptive strip, section body selection. +- `app/lib/features/runs/ui/run_detail_visit_artifacts.dart` — visit artifact + rows opening the existing gallery entry. +- `app/lib/features/runs/ui/run_detail_visit_session.dart` — session pointer and + safe-link export open. +- `app/lib/features/runs/ui/run_detail_visit_definition.dart` — pinned + stage-definition pane or exact missing wording. +- `app/test/features/runs/ui/run_detail_visit_support.dart`, + `run_detail_visit_test.dart`, `run_detail_visit_sections_test.dart`, + `run_detail_visit_session_test.dart`. +- `app/tool/run_detail_visit_probe.dart`, `run_detail_visit_probe.mjs`. +- `app/notes/R4-visit.md`. + +Changed (minimal wiring): + +- `run_detail_timeline.dart` — rows become selectable and report their index. +- `run_detail_tabs.dart` — selected visit index opens the pane; Back closes it; + Graph selection uses the latest recorded index. +- `run_detail_view.dart`, `run_detail_material.dart`, + `run_detail_cupertino.dart` — pass the configured endpoint for the session + safe link; the endpoint cast now comes from `configuredGatewayEndpoint` in + `core/transport/pipelines_client.dart`. +- `run_detail_tab_strip.dart` — `ScrollWhenOverflowing` is public and shared by + both tab strips, so the pointer-drag and minimum-width rules live once. +- `lib/features/artifacts/domain/artifact_groups.dart` — + `visitArtifactGroup` returns the gallery group of exactly one visit from the + whole run. +- `lib/features/artifacts/ui/artifact_gallery_page.dart`, + `artifact_gallery_action.dart` — an optional focused visit limits the page to + that visit's attributed group and summary; the run-level gallery is unchanged. +- `run_detail_graph_tab_test.dart` — the stage-click expectation now asserts + the opened pane and its facts (previous test asserted the row highlight). +- `run_detail_graph_support.dart` — optional light/dark theme for 2x checks and + an empty-tree reset so one test can pump a second run. +- `run_detail_graph_probe.mjs` — the stage-click check now expects the pane and + its sections; re-run once to keep the existing probe green. + +The artifact changes are the two focused-visit additions above: the run-level +gallery, its viewer and its domain grouping are otherwise untouched. No +`graph/`, `pipelines/`, `chat/`, `application/`, `schedules/`, `templates/` or +backend file was edited. + +## Checks run + +From `app/` with Flutter 3.44.6: + +- `flutter analyze` — no issues. +- `flutter test` — **1014 tests passed** (full suite). +- `flutter build web` — built `build/web`. +- Probe builds: + `flutter build web --target tool/run_detail_visit_probe.dart --output build/probe-run-detail-visit` + and the existing `run_detail_graph_probe.dart` build both succeeded. +- `node tool/run_detail_visit_probe.mjs` — passed for Material and Cupertino at + 1280×900/1x dark and 320×568/2x dark: 9/9 checks and 8 captures each. +- `node tool/run_detail_graph_probe.mjs` — Material 1280×900/1x dark re-run + passed with the pane expectation. + +## Browser evidence + +Probe drives the real `RunDetailView` over a server-shaped fake gateway (plan +visit with provider/model, both timestamps, verdict, diagnostic, input/output, +artifacts, session id + `session.html` export; a sparse build visit with no +timestamps/provider/session). Checks: Graph stage click opens `plan · visit 1` +with all five sections; Definition shows the pinned "Draft the plan." source; +Session shows `sess-1` and `Open session.html`; Artifacts lists `plan.csv`; the +row opens a gallery whose summary says `Artifacts · 1 recorded`, whose only +group is `plan · visit 1` and whose only row is `plan.csv` (the `session.html` +evidence file is absent); Back restores the rows; the sparse visit has no +Duration or Provider/model and its Artifacts tab says +`Artifacts · capture unavailable`. + +Under `/Users/alan/.local/share/pipelines/data/artifacts/95/public/r4-visit-fix/`: + +| Host | Viewport | Captures | +| --- | --- | --- | +| Material | 1280×900, dark, 1x | `run-detail-visit-material-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Material | 320×568, dark, 2x | `run-detail-visit-material-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Cupertino | 1280×900, dark, 1x | `run-detail-visit-cupertino-dark-1x-1280x900-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | +| Cupertino | 320×568, dark, 2x | `run-detail-visit-cupertino-dark-2x-320x568-{visit-pane,definition,session,artifacts,timeline-rows,sparse-visit,sparse-artifacts,visit-gallery}.png` | + +Evidence JSON: `evidence-{material,cupertino}-{1x-1280x900,2x-320x568}.json`; +each records 9 checks, all `true`, and the 8 captures above (32 PNGs). + +At 320/2x the run detail keeps its own 240px minimum tab body, so the visit +facts area is a short scroll region; all facts remain reachable by scrolling and +the section strip/body stay usable. No overflow or exception is reported. + +## Review fixes (visit 2) + +- Artifact empty states now use the landed per-visit capture wording instead of + one "nothing recorded" sentence; tests cover absent, explicitly empty and + running captures. +- The artifact row opens the gallery focused on the same visit with the whole + run as context, so a shared `public/` file is not re-attributed. Tests cover + two visits of one stage plus a repeated public file, asserting the pane and + the opened page both exclude it. +- Session resolution handles a repair and the legacy `session.html`, reports the + evidence status/diagnostic when the file is missing, and uses the web client's + state-specific sentences. Tests cover a legacy export, a running model visit + and a failed one. +- Advisory cleanups: shared `ScrollWhenOverflowing`, one timeline lookup for the + latest visit, one endpoint helper, corrected stale selection comments and the + added refusal test. + +## Known gaps + +- The pane title and timeline rows still use the global recorded `sequence` + (`plan · visit 5`), while the gallery group uses the per-stage visit number + (`plan · visit 2`). This predates this pane; aligning the rows and pane would + change the timeline titles and is recorded here rather than done. +- At 320/2x the existing 240px minimum tab body leaves the facts area a short + scroll region; all facts are reachable by scrolling and no overflow occurs. + +## Not done / unverified + +- No commit, push, merge or deployment (this stage forbids it; the input's + “commit the candidate” was not performed). +- Web only. Android/iOS builds, layout and device behavior were not run; the + source stays portable (Material/Cupertino only, no platform-only imports). +- No backend changes. The pane reads only fields the existing `get_run` reply + already carries; nothing new was requested from the server. + +## Manager completion after the Code deadline + +The run had succeeded at Code once, been rejected at Review, and its retry hit the +30-minute stage deadline. The retained tree is complete: 280 runs/artifacts tests +pass and analysis is clean. Merged directly. The only cross-feature edit is an +11-line `configuredGatewayEndpoint` helper in the transport so relative recorded +artifact/session urls resolve against the configured origin without repeating a +cast in the UI. diff --git a/app/test/features/artifacts/domain/artifact_groups_test.dart b/app/test/features/artifacts/domain/artifact_groups_test.dart index cf7173f6..a4f3a834 100644 --- a/app/test/features/artifacts/domain/artifact_groups_test.dart +++ b/app/test/features/artifacts/domain/artifact_groups_test.dart @@ -266,6 +266,39 @@ void main() { ]; expect(artifactGroups(steps).single.artifacts.length, 1); }); + + test('visitArtifactGroup matches the pane group of a later visit', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + visit: 1, + artifacts: >[ + artifact('public/shared.csv'), + artifact('a.csv'), + ], + ), + step( + stage: 'a', + sequence: 2, + visit: 2, + artifacts: >[ + artifact('public/shared.csv'), + artifact('b.csv'), + ], + ), + ]; + final group = visitArtifactGroup(steps, 1)!; + expect(group.stageKey, 'a'); + expect(group.visit, 2); + expect(group.artifacts.map((record) => record.name), ['b.csv']); + expect( + visitArtifacts(steps[1], steps).map((record) => record.name), + ['b.csv'], + ); + expect(visitArtifactGroup(steps, 2), isNull); + expect(visitArtifactGroup(steps, -1), isNull); + }); }); group('unavailable and empty captures', () { diff --git a/app/test/features/runs/ui/run_detail_graph_support.dart b/app/test/features/runs/ui/run_detail_graph_support.dart index 32b11949..494547ab 100644 --- a/app/test/features/runs/ui/run_detail_graph_support.dart +++ b/app/test/features/runs/ui/run_detail_graph_support.dart @@ -81,6 +81,7 @@ Future pumpRunDetail( JsonMap? run, Size size = const Size(900, 1000), double scale = 1, + Brightness brightness = Brightness.light, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -100,10 +101,20 @@ Future pumpRunDetail( ).copyWith(textScaler: TextScaler.linear(scale)), child: view, ); + // A caller that pumps a second run in one test must not inherit the previous + // detail's open tab or pane, so start from an empty tree. + await tester.pumpWidget(const SizedBox.shrink()); await tester.pumpWidget( platform == RunDetailTestPlatform.material - ? MaterialApp(home: Scaffold(body: page)) + ? MaterialApp( + theme: ThemeData( + brightness: brightness, + platform: TargetPlatform.android, + ), + home: Scaffold(body: page), + ) : CupertinoApp( + theme: CupertinoThemeData(brightness: brightness), home: CupertinoPageScaffold(child: SafeArea(child: page)), ), ); diff --git a/app/test/features/runs/ui/run_detail_graph_tab_test.dart b/app/test/features/runs/ui/run_detail_graph_tab_test.dart index 43d20f72..ac140906 100644 --- a/app/test/features/runs/ui/run_detail_graph_tab_test.dart +++ b/app/test/features/runs/ui/run_detail_graph_tab_test.dart @@ -4,7 +4,6 @@ import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart'; -import 'package:pipelines_app/features/runs/ui/run_detail_timeline.dart'; import 'run_detail_graph_support.dart'; @@ -41,32 +40,25 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('${platform.name} stage click highlights its recorded visit', ( + testWidgets('${platform.name} stage click opens its recorded visit pane', ( tester, ) async { await pumpRunDetail(tester, platform); await openRunDetailTab(tester, RunDetailTab.graph); await tapGraphNode(tester, 'plan'); + await tester.pumpAndSettle(); // The Graph reports the stage and the detail moves to Timeline, where the - // exact recorded visit is selected. + // exact recorded visit is open. expect(find.byType(RunGraphView), findsNothing); expect( find.byKey(const Key('run-detail-tab-body-timeline')), findsOneWidget, ); - final selected = tester.widget( - find.byKey(const ValueKey('run-timeline-visit-1')), - ); - expect(selected.selected, isTrue); - expect( - tester - .widget( - find.byKey(const ValueKey('run-timeline-visit-2')), - ) - .selected, - isFalse, - ); + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.byKey(const Key('run-visit-title')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.textContaining('Status:'), findsOneWidget); expect(find.textContaining('audit · visit'), findsNothing); }); diff --git a/app/test/features/runs/ui/run_detail_visit_sections_test.dart b/app/test/features/runs/ui/run_detail_visit_sections_test.dart new file mode 100644 index 00000000..9c3abe0c --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_sections_test.dart @@ -0,0 +1,187 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart'; +import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.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'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} tabs show recorded values and exact empty ' + 'wording', (tester) async { + await openVisit(tester, platform); + + expect(find.textContaining('"prompt": "Ship it."'), findsOneWidget); + await openVisitTab(tester, RunVisitSection.output); + expect(find.textContaining('"result": "ok"'), findsOneWidget); + + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('plan.csv'), findsOneWidget); + await tester.tap(find.text('plan.csv')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactGalleryPage), findsOneWidget); + // The opened page lists exactly the pane's stage files: the session + // evidence file is not stage output and stays out of both. + expect(find.text('plan · visit 1'), findsOneWidget); + expect(find.text('plan.csv'), findsOneWidget); + expect(find.text('session.html'), findsNothing); + expect(find.text('Artifacts · 1 recorded'), findsOneWidget); + await tester.pageBack(); + await tester.pumpAndSettle(); + + await openVisitTab(tester, RunVisitSection.session); + expect(find.text('Session'), findsWidgets); + expect(find.text('sess-1'), findsOneWidget); + expect(find.text('Open session.html'), findsOneWidget); + + await openVisitTab(tester, RunVisitSection.definition); + expect(find.byType(StageDefinitionView), findsOneWidget); + expect(find.text('Draft the plan.'), findsOneWidget); + }); + + testWidgets('${platform.name} artifacts tab reports the capture state', ( + tester, + ) async { + final absent = visitRunFixture(); + firstVisitStep(absent).remove('artifacts'); + await openVisit(tester, platform, run: absent); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('Artifacts · capture unavailable'), findsOneWidget); + + final empty = visitRunFixture(); + firstVisitStep(empty)['artifacts'] = []; + await openVisit(tester, platform, run: empty); + await openVisitTab(tester, RunVisitSection.artifacts); + expect( + find.text('Artifacts · not recorded for this visit'), + findsOneWidget, + ); + + final running = visitRunFixture(); + final runningStep = firstVisitStep(running); + runningStep['status'] = 'running'; + runningStep['artifacts'] = []; + await openVisit(tester, platform, run: running); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('Artifacts · capture pending'), findsOneWidget); + }); + + testWidgets('${platform.name} empty sections use the exact wording', ( + tester, + ) async { + final run = visitRunFixture(); + final step = firstVisitStep(run); + step.remove('input'); + step.remove('output'); + step['artifacts'] = []; + step.remove('session_id'); + step.remove('session_export'); + await openVisit(tester, platform, run: run); + + expect(find.text(visitEmptyInput), findsOneWidget); + await openVisitTab(tester, RunVisitSection.output); + expect(find.text(visitEmptyOutput), findsOneWidget); + await openVisitTab(tester, RunVisitSection.artifacts); + expect( + find.text('Artifacts · not recorded for this visit'), + findsOneWidget, + ); + await openVisitTab(tester, RunVisitSection.session); + // A completed model visit with no identity is a runtime error, not a + // generic "no session" claim. + expect(find.text(visitSessionNoIdentity), findsOneWidget); + }); + + testWidgets('${platform.name} later visit pane and opened gallery agree on ' + 'attributed files', (tester) async { + final run = visitRunFixture(); + final steps = run['steps'] as List; + firstVisitStep(run)['artifacts'] = [ + { + 'name': 'public/shared.csv', + 'url': 'https://example.test/artifacts/1/public/shared.csv', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/1/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + ]; + steps.add({ + 'stage': 'plan', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + 'artifacts': [ + { + 'name': 'public/shared.csv', + 'url': 'https://example.test/artifacts/2/public/shared.csv', + 'content_type': 'text/csv', + 'size_bytes': 10, + }, + { + 'name': 'plan-2.csv', + 'url': 'https://example.test/artifacts/2/plan-2.csv', + 'content_type': 'text/csv', + 'size_bytes': 7, + }, + ], + }); + + await openVisit(tester, platform, run: run, sequence: 2); + expect(find.text('plan · visit 2'), findsOneWidget); + await openVisitTab(tester, RunVisitSection.artifacts); + expect(find.text('plan-2.csv'), findsOneWidget); + expect(find.text('public/shared.csv'), findsNothing); + + await tester.tap(find.text('plan-2.csv')); + await tester.pumpAndSettle(); + expect(find.byType(ArtifactGalleryPage), findsOneWidget); + expect(find.text('plan · visit 2'), findsOneWidget); + expect(find.text('plan-2.csv'), findsOneWidget); + expect(find.text('public/shared.csv'), findsNothing); + expect(find.text('Artifacts · 1 recorded'), findsOneWidget); + }); + + testWidgets('${platform.name} missing definition uses exact wording', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(declareStage: false), + ); + await openVisitTab(tester, RunVisitSection.definition); + + expect(find.byType(StageDefinitionView), findsNothing); + expect(find.text(unknownStageDefinition), findsOneWidget); + expect(find.text('Draft the plan.'), findsNothing); + }); + + testWidgets('${platform.name} visit sections at 320 with 2x dark text', ( + tester, + ) async { + await openVisit( + tester, + platform, + size: const Size(320, 568), + scale: 2, + brightness: Brightness.dark, + ); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(tester.takeException(), isNull); + for (final section in RunVisitSection.values) { + await openVisitTab(tester, section); + expect(tester.takeException(), isNull, reason: section.label); + } + }); + } +} 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 new file mode 100644 index 00000000..c5ba50fc --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_session_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.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'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} legacy session.html stays openable', ( + tester, + ) async { + final run = visitRunFixture(); + firstVisitStep(run).remove('session_export'); + await openVisit(tester, platform, run: run); + await openVisitTab(tester, RunVisitSection.session); + + expect(find.text('sess-1'), findsOneWidget); + expect(find.text('Open session.html'), findsOneWidget); + expect( + find.textContaining('not available in the artifact inventory'), + findsNothing, + ); + }); + + testWidgets('${platform.name} running and failed model visits report ' + 'their session state', (tester) async { + final running = visitRunFixture(); + final runningStep = firstVisitStep(running); + runningStep['status'] = 'running'; + runningStep.remove('session_id'); + runningStep.remove('session_export'); + runningStep.remove('artifacts'); + await openVisit(tester, platform, run: running); + await openVisitTab(tester, RunVisitSection.session); + expect(find.text(visitSessionStarting), findsOneWidget); + + final failed = visitRunFixture(); + final failedStep = firstVisitStep(failed); + failedStep['status'] = 'failed'; + failedStep.remove('session_id'); + failedStep.remove('session_export'); + failedStep.remove('artifacts'); + failedStep['diagnostic'] = 'Provider refused.'; + await openVisit(tester, platform, run: failed); + await openVisitTab(tester, RunVisitSection.session); + expect( + find.text('$visitSessionFailed Provider refused.'), + findsOneWidget, + ); + }); + } + + testWidgets('a recorded session without any export file reports its state', ( + tester, + ) async { + final step = firstVisitStep(visitRunFixture()); + step.remove('session_export'); + step['artifacts'] = [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + ]; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + + expect( + find.text('Session sess-1 is recorded. Its export is not yet available.'), + findsOneWidget, + ); + expect(find.textContaining('Open '), findsNothing); + + step['session_export'] = { + 'html': 'session.html', + 'status': 'failed', + 'diagnostic': 'Repair failed.', + }; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + expect( + find.text( + 'Session sess-1 is recorded. Its export is failed. Repair failed.', + ), + findsOneWidget, + ); + }); + + testWidgets('session entry opens the resolved export externally', ( + tester, + ) async { + Uri? opened; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession( + step: firstVisitStep(visitRunFixture()), + configuredEndpoint: 'ws://example.test/connect', + openExternal: (uri) async { + opened = uri; + return true; + }, + ), + ), + ), + ); + + await tester.tap(find.text('Open session.html')); + await tester.pumpAndSettle(); + + expect(opened, Uri.parse('https://example.test/artifacts/session.html')); + expect(find.text('Link opened externally.'), findsOneWidget); + }); + + testWidgets('session open refusal is reported', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession( + step: firstVisitStep(visitRunFixture()), + configuredEndpoint: 'ws://example.test/connect', + openExternal: (uri) async => false, + ), + ), + ), + ); + + await tester.tap(find.text('Open session.html')); + await tester.pumpAndSettle(); + + expect(find.text('Could not open the link.'), findsOneWidget); + }); +} diff --git a/app/test/features/runs/ui/run_detail_visit_support.dart b/app/test/features/runs/ui/run_detail_visit_support.dart new file mode 100644 index 00000000..04759aaa --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_support.dart @@ -0,0 +1,116 @@ +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/ui/run_detail_tab.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart'; + +import 'run_detail_graph_support.dart'; + +/// plan -> build, with one rich recorded plan visit. +JsonMap visitRunFixture({ + bool bothTimestamps = true, + bool providerModel = true, + bool declareStage = true, +}) => { + 'id': 77, + 'title': 'Visit run', + 'name': 'release', + 'pipeline_id': 7, + 'version': 3, + 'status': 'succeeded', + 'graph': { + 'stages': [ + if (declareStage) + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Draft the plan.', + 'edges': {'success': 'build', 'error': '#'}, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': '#success'}, + }, + ], + }, + 'steps': [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + if (providerModel) 'provider': 'anthropic', + if (providerModel) 'model': 'claude-x', + if (bothTimestamps) 'started_at': '2026-10-22T00:00:00Z', + if (bothTimestamps) 'finished_at': '2026-10-22T00:02:05Z', + 'diagnostic': 'Plan checked.', + 'verdict': { + 'option': 'approve', + 'reason': 'Looks good.', + }, + 'input': {'prompt': 'Ship it.'}, + 'output': {'result': 'ok'}, + 'session_id': 'sess-1', + 'session_export': { + 'html': 'session.html', + 'status': 'complete', + 'messages': 3, + 'html_bytes': 1234, + }, + 'artifacts': [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + { + 'name': 'session.html', + 'url': 'https://example.test/artifacts/session.html', + 'content_type': 'text/html', + 'size_bytes': 100, + }, + ], + }, + ], +}; + +/// The first recorded step of a detail fixture, for tests that change one +/// visit's recorded fields. +JsonMap firstVisitStep(JsonMap run) => + (run['steps'] as List).first as Map; + +Future openVisit( + WidgetTester tester, + RunDetailTestPlatform platform, { + JsonMap? run, + int sequence = 1, + Size size = const Size(900, 1000), + double scale = 1, + Brightness brightness = Brightness.light, +}) async { + await pumpRunDetail( + tester, + platform, + run: run ?? visitRunFixture(), + size: size, + scale: scale, + brightness: brightness, + ); + await openRunDetailTab(tester, RunDetailTab.timeline); + final row = find.byKey(ValueKey('run-timeline-visit-$sequence')); + await tester.ensureVisible(row); + await tester.pumpAndSettle(); + await tester.tap(row); + await tester.pumpAndSettle(); +} + +Future openVisitTab(WidgetTester tester, RunVisitSection section) async { + final tab = find.byKey(ValueKey('run-visit-tab-${section.name}')); + await tester.ensureVisible(tab); + await tester.pumpAndSettle(); + await tester.tap(tab); + await tester.pumpAndSettle(); +} diff --git a/app/test/features/runs/ui/run_detail_visit_test.dart b/app/test/features/runs/ui/run_detail_visit_test.dart new file mode 100644 index 00000000..c91dc1f8 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_visit_test.dart @@ -0,0 +1,106 @@ +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/ui/run_detail_timeline.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'; + +void main() { + for (final platform in RunDetailTestPlatform.values) { + testWidgets('${platform.name} visit shows only its recorded facts', ( + tester, + ) async { + await openVisit(tester, platform); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + for (final value in [ + 'Status: completed', + 'Outcome: success', + 'Duration: 2m 5s', + 'Provider/model: anthropic / claude-x', + 'Target: build', + ]) { + expect(find.textContaining(value), findsOneWidget, reason: value); + } + for (final value in ['approve', 'Looks good.', 'Plan checked.']) { + expect(find.text(value), findsOneWidget, reason: value); + } + expect(find.text('Verdict'), findsOneWidget); + expect(find.text('Diagnostic'), findsOneWidget); + }); + + testWidgets('${platform.name} duration hides without both timestamps', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(bothTimestamps: false), + ); + + expect(find.textContaining('Duration'), findsNothing); + expect(find.textContaining('0s'), findsNothing); + expect(find.textContaining('Status: completed'), findsOneWidget); + }); + + testWidgets('${platform.name} absent provider/model is not invented', ( + tester, + ) async { + await openVisit( + tester, + platform, + run: visitRunFixture(providerModel: false), + ); + + expect(find.textContaining('Provider/model'), findsNothing); + expect(find.textContaining('anthropic / claude-x'), findsNothing); + }); + + testWidgets('${platform.name} Back closes the visit pane', (tester) async { + await openVisit(tester, platform); + await tester.tap(find.byKey(const Key('run-visit-back'))); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('run-visit-pane')), findsNothing); + expect(find.byType(RunTimelineList), findsOneWidget); + expect(find.text('plan · visit 1'), findsOneWidget); + }); + + testWidgets('${platform.name} visit pane at 320 with 2x dark text', ( + tester, + ) async { + await openVisit( + tester, + platform, + size: const Size(320, 568), + scale: 2, + brightness: Brightness.dark, + ); + + expect(find.byKey(const Key('run-visit-pane')), findsOneWidget); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('session export with no configured endpoint states the hint', ( + tester, + ) async { + final step = (visitRunFixture()['steps'] as List).first as JsonMap; + final artifacts = step['artifacts'] as List; + (artifacts[1] as JsonMap)['url'] = '/artifacts/session.html'; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunVisitSession(step: step, configuredEndpoint: ''), + ), + ), + ); + + expect(find.text('Open session.html'), findsNothing); + expect(find.text(visitSessionEndpointMissing), findsOneWidget); + }); +} diff --git a/app/tool/run_detail_graph_probe.mjs b/app/tool/run_detail_graph_probe.mjs index 3d8c65ab..cb6bfe20 100644 --- a/app/tool/run_detail_graph_probe.mjs +++ b/app/tool/run_detail_graph_probe.mjs @@ -236,21 +236,27 @@ try { } await clickPrefix('plan'); - await waitForText('plan · visit 1', 'timeline after stage click'); + await waitForText('plan · visit 1', 'timeline visit pane after stage click'); + await waitForText('Status: completed', 'recorded visit facts'); await waitForText('Timeline', 'timeline tab'); const timeline = await semantics(); - const rowCandidates = timeline + const titleCandidates = timeline .filter((entry) => entry.visible && entry.label.startsWith('plan · visit 1')) .sort((a, b) => a.width * a.height - b.width * b.height); - const row = rowCandidates[0]; - if (!row) throw new Error(`Selected timeline row missing: ${JSON.stringify(timeline.map((entry) => entry.label))}`); - if (row.selected !== 'true') { - throw new Error(`Timeline row is not selected: ${JSON.stringify(rowCandidates)}`); + if (!titleCandidates.length) { + throw new Error(`Opened visit pane missing: ${JSON.stringify(timeline.map((entry) => entry.label))}`); + } + const paneLabels = timeline.map((entry) => entry.label); + for (const section of ['Input', 'Output', 'Artifacts', 'Session', 'Definition']) { + if (!paneLabels.includes(section)) { + throw new Error(`Visit section ${section} is missing: ${JSON.stringify(paneLabels)}`); + } } if ((await bodyText()).includes('audit · visit')) { throw new Error('A visit was invented for the unvisited stage'); } - check('a stage click selects the recorded visit in Timeline', row.selected); + check('a stage click opens the recorded visit pane', true); + check('the visit pane offers its recorded sections', true); // The programmatic switch must reveal its own tab, not leave an offscreen // selection behind a strip still showing Summary/Graph. const timelineTab = await findVisible((entry) => entry.label === 'Timeline' && entry.tappable); @@ -259,7 +265,7 @@ try { throw new Error(`Selected Timeline tab is clipped: ${JSON.stringify({ timelineTab, width })}`); } check('the selected Timeline tab is revealed in the strip', `${Math.round(timelineTab.x)}..${Math.round(timelineTab.x + timelineTab.width)}`); - evidence.selectedRow = row; + evidence.openedPane = titleCandidates[0]; evidence.captures.push(await capture('selected-visit')); await navigate( diff --git a/app/tool/run_detail_visit_probe.dart b/app/tool/run_detail_visit_probe.dart new file mode 100644 index 00000000..53750471 --- /dev/null +++ b/app/tool/run_detail_visit_probe.dart @@ -0,0 +1,189 @@ +// Standalone fixture entry for real-browser recorded-visit pane evidence. +// +// Build and probe (from app/): +// flutter build web --target tool/run_detail_visit_probe.dart \ +// --output build/probe-run-detail-visit +// PROBE_VARIANT=material OPENCODE_ARTIFACT_DIR=DIR \ +// node tool/run_detail_visit_probe.mjs +// +// Server-shaped fixtures only: a fake gateway answers the same get_run envelope +// the app consumes. No server or operator run is touched. +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; +import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; + +class _FakeGateway implements ApiGateway { + _FakeGateway(this.detail); + + final JsonMap detail; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type != 'get_run') throw UnsupportedError(type); + return Future.value({'run_detail': detail}); + } +} + +/// plan -> build, with a rich first visit and a sparse second visit. +JsonMap _graph() => { + 'name': 'Release verification', + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'prompt': 'Draft the plan.', + 'output': 'A plan.', + 'edges': {'success': 'build', 'error': '#'}, + }, + { + 'key': 'build', + 'type': 'model', + 'prompt': 'Build the candidate.', + 'edges': {'success': '#success', 'error': '#'}, + }, + ], +}; + +JsonMap _run() => { + 'id': 512, + 'title': 'Release verification', + 'name': 'release', + 'pipeline_id': 7, + 'version': 3, + 'status': 'succeeded', + 'executing': false, + 'input': {'prompt': 'Verify the candidate release.'}, + 'output': {'result': 'verified'}, + 'graph': _graph(), + 'steps': [ + { + 'stage': 'plan', + 'sequence': 1, + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + 'provider': 'anthropic', + 'model': 'claude-x', + 'started_at': '2026-10-22T00:00:00Z', + 'finished_at': '2026-10-22T00:02:05Z', + 'diagnostic': 'Plan checked.', + 'verdict': { + 'option': 'approve', + 'reason': 'Looks good.', + }, + 'input': {'markdown': 'Draft the plan.\n'}, + 'output': {'result': 'ok'}, + 'session_id': 'sess-1', + 'session_export': { + 'html': 'session.html', + 'status': 'complete', + 'messages': 3, + 'html_bytes': 1234, + }, + 'artifacts': [ + { + 'name': 'plan.csv', + 'url': 'https://example.test/artifacts/plan.csv', + 'content_type': 'text/csv', + 'size_bytes': 42, + }, + { + 'name': 'session.html', + 'url': 'https://example.test/artifacts/session.html', + 'content_type': 'text/html', + 'size_bytes': 100, + }, + ], + }, + { + 'stage': 'build', + 'sequence': 2, + 'status': 'completed', + 'outcome': 'success', + 'target': '#success', + 'diagnostic': 'Built.', + }, + ], +}; + +void main() { + final params = Uri.base.queryParameters; + final cupertino = params['platform'] == 'cupertino'; + final dark = params['theme'] == 'dark'; + final scale = double.tryParse(params['scale'] ?? '') ?? 1; + runApp( + _ProbeBody(cupertino: cupertino, dark: dark, scale: scale, run: _run()), + ); +} + +class _ProbeBody extends StatefulWidget { + const _ProbeBody({ + required this.cupertino, + required this.dark, + required this.scale, + required this.run, + }); + + final bool cupertino; + final bool dark; + final double scale; + final JsonMap run; + + @override + State<_ProbeBody> createState() => _ProbeBodyState(); +} + +class _ProbeBodyState extends State<_ProbeBody> { + late final _FakeGateway _gateway = _FakeGateway(widget.run); + late final RunsController _controller = RunsController( + RunsRepository(_gateway), + ); + + @override + void initState() { + super.initState(); + _controller.select(512); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final detail = RunDetailView( + controller: _controller, + gateway: _gateway, + onBack: () {}, + ); + final theme = widget.dark ? Brightness.dark : Brightness.light; + Widget scaled(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(widget.scale)), + child: app!, + ); + if (widget.cupertino) { + return CupertinoApp( + title: 'Visit pane fixture', + theme: CupertinoThemeData(brightness: theme), + builder: scaled, + home: CupertinoPageScaffold(child: SafeArea(child: detail)), + ); + } + return MaterialApp( + title: 'Visit pane fixture', + theme: ThemeData(brightness: theme, platform: TargetPlatform.android), + builder: scaled, + home: Scaffold(body: SafeArea(child: detail)), + ); + } +} diff --git a/app/tool/run_detail_visit_probe.mjs b/app/tool/run_detail_visit_probe.mjs new file mode 100644 index 00000000..5e540d81 --- /dev/null +++ b/app/tool/run_detail_visit_probe.mjs @@ -0,0 +1,290 @@ +// Real-browser acceptance for the run detail's recorded-visit pane. +// +// Serves the probe build (`flutter build web -t tool/run_detail_visit_probe.dart`) +// on an OS-assigned loopback port and drives the actual RunDetailView over a +// server-shaped fixture. It checks that a Graph stage click opens the recorded +// visit in Timeline with its facts and native tabs, that the tabs show the +// recorded Input, Artifacts, Session and Definition, that the visit's artifact +// row opens a gallery listing exactly that visit's attributed files, that Back +// returns to the rows, that a sparse visit does not invent Duration or +// provider/model, and that a visit with no artifact field says the capture is +// unavailable rather than empty. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT= \ +// OPENCODE_ARTIFACT_DIR= node tool/run_detail_visit_probe.mjs +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { setTimeout as delay } from 'node:timers/promises'; +import { join, extname, resolve, sep } from 'node:path'; +import { tmpdir } from 'node:os'; +import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; + +const root = resolve( + process.env.PROBE_WEB_ROOT ?? + join(process.cwd(), 'build/probe-run-detail-visit'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const width = Number(process.env.PROBE_WIDTH ?? 1280); +const height = Number(process.env.PROBE_HEIGHT ?? 900); +const chromePath = process.env.CHROME_PATH ?? + '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR; +if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(artifactDir, { recursive: true }); +const prefix = `run-detail-visit-${variant}-${scheme}-${scale}x-${width}x${height}`; +const mime = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.wasm': 'application/wasm', + '.png': 'image/png', + '.ico': 'image/x-icon', + '.otf': 'font/otf', + '.ttf': 'font/ttf', +}; +const server = createServer(async (req, res) => { + try { + const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname)); + if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end(); + const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path; + const file = await readFile(filePath); + res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file); + } catch { + res.writeHead(404).end('not found'); + } +}); +server.listen(0, '127.0.0.1'); +await once(server, 'listening'); +const port = server.address().port; +const profile = await mkdtemp(join(tmpdir(), 'run-detail-visit-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); +const waitFor = async (fn) => { + for (let i = 0; i < 140; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error('Timed out waiting for Chrome DevTools'); +}; +let ws; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const created = await send('Target.createTarget', { url: 'about:blank' }); + const target = created.result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + await send('Emulation.setEmulatedMedia', { + features: [{ name: 'prefers-color-scheme', value: scheme }], + }, session); + await send('Emulation.setDeviceMetricsOverride', { + width, height, deviceScaleFactor: 1, mobile: width < 600, + }, session); + + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { + expression, returnByValue: true, awaitPromise: true, + }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + const semantics = () => evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => { + const r = x.getBoundingClientRect(); + return { + label: (x.getAttribute('aria-label') || (x.innerText || '')).trim(), + selected: x.getAttribute('aria-selected') || x.getAttribute('aria-current'), + tappable: x.hasAttribute('flt-tappable'), + x: r.x, y: r.y, width: r.width, height: r.height, + visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight, + }; + })`); + const labels = async () => (await semantics()).map((item) => item.label).filter(Boolean); + const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n'); + const waitForText = async (needle, context) => { + for (let attempt = 0; attempt < 60; attempt++) { + if ((await bodyText()).includes(needle)) return; + await delay(250); + } + throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${await bodyText()}`); + }; + const clickItem = async (item) => { + const x = item.x + item.width / 2; + const y = item.y + item.height / 2; + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', x, y, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', x, y, button: 'left', clickCount: 1, + }, session); + await delay(1000); + }; + const findVisible = async (predicate) => { + const items = (await semantics()).filter((item) => item.visible && predicate(item)); + items.sort((a, b) => a.width * a.height - b.width * b.height); + return items[0] ?? null; + }; + const clickSemantics = async (wanted, { lowest = false, prefix: asPrefix = false } = {}) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(wanted)}; + const lowest = ${lowest ? 'true' : 'false'}; + const asPrefix = ${asPrefix ? 'true' : 'false'}; + const text = (x) => (x.getAttribute('aria-label') || x.innerText || '').trim(); + const matches = [...document.querySelectorAll('flt-semantics')] + .filter((x) => x.hasAttribute('flt-tappable')) + .filter((x) => asPrefix ? text(x).startsWith(wanted) : text(x) === wanted); + if (!matches.length) return false; + matches.sort((a, b) => { + const ra = a.getBoundingClientRect(); + const rb = b.getBoundingClientRect(); + if (lowest) return rb.bottom - ra.bottom; + return ra.width * ra.height - rb.width * rb.height; + }); + matches[0].click(); + return true; + })()`); + if (!clicked) throw new Error(`Missing tappable ${JSON.stringify(wanted)}: ${JSON.stringify(await labels())}`); + await delay(1000); + }; + const clickLabel = (label, options) => clickSemantics(label, options); + const clickPrefix = (prefixText) => clickSemantics(prefixText, { prefix: true }); + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { + format: 'png', captureBeyondViewport: false, + }, session)).result.data; + const file = `${prefix}-${name}.png`; + await writeFile(join(artifactDir, file), Buffer.from(data, 'base64')); + return file; + }; + const evidence = { variant, scheme, scale, width, height, checks: [], captures: [] }; + const check = (text, value) => evidence.checks.push({ check: text, value }); + + const navigation = await send('Page.navigate', { + url: `http://127.0.0.1:${port}/?platform=${variant}&theme=${scheme === 'dark' ? 1 : 0}&scale=${scale}`, + }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await delay(3200); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(900); + await waitForText('Release verification', 'fixture load'); + check('the real run detail opened over the recorded fixture', true); + + await clickLabel('Graph'); + await waitForText('Executed', 'graph legend'); + await clickPrefix('plan'); + await waitForText('plan · visit 1', 'visit pane after graph click'); + await waitForText('Provider/model', 'visit facts'); + await waitForText('anthropic / claude-x', 'visit facts'); + await waitForText('2m 5s', 'recorded duration'); + await waitForText('Plan checked.', 'recorded diagnostic'); + await waitForText('approve', 'recorded verdict'); + const paneLabels = await labels(); + for (const section of ['Input', 'Output', 'Artifacts', 'Session', 'Definition']) { + if (!paneLabels.includes(section)) { + throw new Error(`Visit section ${section} is missing: ${JSON.stringify(paneLabels)}`); + } + } + check('Graph stage click opens the recorded visit pane with its tabs', true); + evidence.captures.push(await capture('visit-pane')); + + await clickLabel('Definition', { lowest: true }); + await waitForText('Type model', 'authored definition'); + await waitForText('Prompt', 'authored definition prompt'); + await waitForText('Draft the plan.', 'pinned prompt'); + check('Definition shows the pinned authored source', true); + evidence.captures.push(await capture('definition')); + + await clickLabel('Session', { lowest: true }); + await waitForText('sess-1', 'recorded session pointer'); + await waitForText('Open session.html', 'session export link'); + check('Session shows the recorded pointer and export open', true); + evidence.captures.push(await capture('session')); + + await clickLabel('Artifacts', { lowest: true }); + await waitForText('plan.csv', 'visit artifact'); + check('Artifacts lists the visit recorded files', true); + evidence.captures.push(await capture('artifacts')); + + await clickLabel('Back to timeline'); + await waitForText('build · visit 2', 'timeline rows after back'); + if ((await bodyText()).includes('Plan checked.')) { + throw new Error('Back left the visit pane open'); + } + check('Back returns to the recorded rows', true); + evidence.captures.push(await capture('timeline-rows')); + + await clickPrefix('build · visit 2'); + await waitForText('build · visit 2', 'sparse visit pane'); + const sparse = await bodyText(); + for (const absent of ['Provider/model', 'Duration', '2m 5s', 'anthropic / claude-x']) { + if (sparse.includes(absent)) { + throw new Error(`A sparse visit invented ${JSON.stringify(absent)}\n${sparse}`); + } + } + check('a sparse visit does not invent duration or provider/model', true); + evidence.captures.push(await capture('sparse-visit')); + + await clickLabel('Artifacts', { lowest: true }); + await waitForText('Artifacts · capture unavailable', 'sparse capture state'); + check('a visit without an artifact field says capture unavailable', true); + evidence.captures.push(await capture('sparse-artifacts')); + + await clickLabel('Back to timeline'); + await waitForText('plan · visit 1', 'rows before the gallery check'); + await clickPrefix('plan · visit 1'); + await waitForText('Provider/model', 'plan visit for the gallery check'); + await clickLabel('Artifacts', { lowest: true }); + await waitForText('plan.csv', 'plan visit artifacts'); + await clickPrefix('plan.csv'); + await waitForText('Artifacts · 1 recorded', 'visit gallery summary'); + await waitForText('plan · visit 1', 'visit gallery group'); + const galleryText = await bodyText(); + if (galleryText.includes('session.html')) { + throw new Error(`The visit gallery listed the session evidence file\n${galleryText}`); + } + check('the artifact row opens exactly the visit attributed group', true); + evidence.captures.push(await capture('visit-gallery')); + + console.log(JSON.stringify(evidence, null, 2)); +} finally { + if (ws?.readyState === WebSocket.OPEN) { + ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' })); + } + await Promise.race([once(chrome, 'exit'), delay(3000)]); + ws?.close(); + if (chrome.exitCode === null) chrome.kill('SIGTERM'); + chrome.stderr.destroy(); + chrome.unref(); + await new Promise((resolveClose) => { + server.close(resolveClose); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +}