Files
pipelines/app/lib/features/runs/ui/run_detail_tabs.dart
T
alan 5425001d82 Send artifacts, runs and pipelines to a new or existing chat
One picker offers a new chat (the saved Open in chat harness and model)
or any open chat. An existing chat gets the reference appended to its
draft and focused, never sent. Artifacts gain the action in their viewer
and gallery; the run and pipeline item becomes Send to chat.
2026-11-13 18:43:14 +00:00

548 lines
21 KiB
Dart

import 'dart:async';
import '../../../ui/adaptive/floating_bar_layout.dart';
import '../../../ui/adaptive/segmented_bar.dart';
import '../../../ui/adaptive/top_glass_strip.dart';
import '../../../ui/motion/fade_through_stack.dart';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../graph/widgets/run_graph_view.dart';
import '../../artifacts/ui/artifact_gallery_action.dart';
import '../../artifacts/ui/artifact_gallery_page.dart';
import '../../artifacts/domain/artifact_chat_context.dart';
import '../../changes/changes.dart';
import 'run_changes_action.dart';
import 'run_detail_content.dart';
import 'run_graph_preview.dart';
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_wide_chrome.dart';
import 'run_detail_visit_facts.dart';
import 'run_search_selection.dart';
/// The least height the selected tab keeps for its own content.
///
/// A header and tab strip that would leave the tab less than this may scroll
/// instead, so scaled title text or a short window cannot squeeze the Graph
/// canvas away. The Graph view's own legend is one wrapped row pair; this
/// reserve keeps its bounded canvas positive at 320px with 2x text.
const double kRunDetailMinContentHeight = 240;
/// The run detail's tabbed body: the selected tab fills the detail and
/// scrolls behind the top bar, the host-built header (a glass strip just
/// under the bar) and the floating tab bar.
///
/// 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 that visit's pane opens. A
/// node with no recorded visit reports nothing, so no visit is invented.
class RunDetailTabs extends StatefulWidget {
const RunDetailTabs({
super.key,
required this.run,
required this.header,
required this.copying,
required this.copyStatus,
required this.onCopy,
required this.gateway,
required this.onRunChanged,
required this.configuredEndpoint,
this.initialStageKey,
this.initialVisit,
this.onSendToChat,
});
final JsonMap run;
/// The host's own header: status, the run actions and notices. It floats
/// outside the tab body, so switching tabs never drops an action.
final Widget header;
final bool copying;
final String? copyStatus;
final VoidCallback onCopy;
/// The shared gateway and accepted-detail fold used by the visit session's
/// export-only repair. Tabs never open their own socket.
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// The configured server origin used to resolve a recorded session export
/// through the landed safe-link helper. Blank leaves relative urls unresolved.
final String configuredEndpoint;
/// The stage a `/runs/:id/stage/:key` route names, or null for the plain
/// detail. It selects a recorded visit; a declared but unvisited stage only
/// selects its graph node, so no visit is ever invented.
final String? initialStageKey;
/// The zero-based index among [initialStageKey]'s recorded visits. Null opens
/// the stage's latest visit, exactly as a Graph node click does.
final int? initialVisit;
final void Function(String draft)? onSendToChat;
@override
State<RunDetailTabs> createState() => _RunDetailTabsState();
}
class _RunDetailTabsState extends State<RunDetailTabs> {
RunDetailTab _tab = RunDetailTab.summary;
String? _selectedStage;
int? _selectedVisit;
/// The visit whose page is open, and the live run that page follows.
int? _shownVisit;
Route<void>? _visitRoute;
late final ValueNotifier<JsonMap> _liveRun = ValueNotifier(widget.run);
/// The Summary's collapsible Input and Output sections. Output starts open
/// and Input starts closed; the operator may close either for this view. A
/// search text hit expands the one its recorded field names, exactly as the
/// browser opens the matching Summary section. The detail owns them so the
/// tab body stays a presentation widget.
final _inputSection = ExpansibleController();
final _outputSection = ExpansibleController()..expand();
/// The search request last applied by this detail, so a rebuild of the same
/// request never reopens a pane the operator closed in the meantime.
RunSearchSelection? _appliedSearchSelection;
/// The artifact a search hit asked the Artifacts tab to open, until it has.
String? _searchArtifactUrl;
@override
void initState() {
super.initState();
_applyInitialVisit();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_applySearchSelection();
}
/// The Summary's default sections: Input closed, Output open.
void _resetSummarySections() {
_inputSection.collapse();
_outputSection.expand();
}
@override
void dispose() {
_inputSection.dispose();
_outputSection.dispose();
_liveRun.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant RunDetailTabs oldWidget) {
super.didUpdateWidget(oldWidget);
_liveRun.value = widget.run;
final sameRun = '${widget.run['id']}' == '${oldWidget.run['id']}';
final sameTarget =
widget.initialStageKey == oldWidget.initialStageKey &&
widget.initialVisit == oldWidget.initialVisit;
// A different run is a different detail: its visits and graph do not carry
// the previous run's selection.
if (!sameRun) {
_tab = RunDetailTab.summary;
_selectedStage = null;
_selectedVisit = null;
_resetSummarySections();
_applyInitialVisit();
} else if (!sameTarget) {
// A route that names another stage or visit is applied to the same run.
// Rebuilds from a live refresh keep the operator's own selection.
_applyInitialVisit();
}
}
/// Opens the visit a route names, without presenting any visit the run did
/// not record.
///
/// A route with a stage key and no visit opens that stage's latest recorded
/// visit, the same visit a Graph node click opens. A valid index selects that
/// visit among the stage's own visits; an out-of-range index is clamped to the
/// stage's last recorded visit, as the web client does, so the address bar and
/// the pane never disagree about which visit is real. A declared but
/// unvisited stage selects its Graph node only.
void _applyInitialVisit() {
final stageKey = widget.initialStageKey;
if (stageKey == null || stageKey.isEmpty) {
_selectedStage = null;
_selectedVisit = null;
return;
}
final index = routeDetailVisitIndex(
widget.run['steps'],
stageKey,
widget.initialVisit,
);
if (index != null) {
_selectedStage = stageKey;
_selectedVisit = index;
_tab = RunDetailTab.timeline;
return;
}
_selectedVisit = null;
// The key is not a recorded visit. Only a stage the pinned graph actually
// declares can be selected; anything else leaves the plain detail intact.
if (detailVisitHasDefinition(detailGraph(widget.run), stageKey)) {
// The Summary's graph preview shows the selected stage.
_selectedStage = stageKey;
_tab = RunDetailTab.summary;
} else {
_selectedStage = null;
}
}
/// Selects the Summary section or recorded visit a search result names.
///
/// The request is applied once per loaded run and is consumed afterwards. A
/// retired or unknown field still selects the plain Summary, exactly as the
/// browser's `searchFieldTab` does, and a visit the run did not record falls
/// back to the plain Summary, so no stale hit leaves an unrelated pane open.
void _applySearchSelection() {
final scope = RunSearchSelectionScope.maybeOf(context);
final selection = scope?.selection;
if (scope == null || selection == null) {
_appliedSearchSelection = null;
return;
}
if (selection == _appliedSearchSelection) return;
final id = widget.run['id'];
if (id is! num || id.toInt() != selection.runId) return;
_appliedSearchSelection = selection;
_selectSearchTarget(resolveRunSearchSelection(selection, widget.run));
final consumed = scope.onConsumed;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) consumed();
});
}
void _selectSearchTarget(RunSearchTarget target) {
switch (target) {
case RunSummaryTarget(:final section):
_tab = RunDetailTab.summary;
_selectedStage = null;
_selectedVisit = null;
switch (section) {
case RunSummarySection.input:
_inputSection.expand();
case RunSummarySection.output:
_outputSection.expand();
case null:
// A hit that names no section must not leave a previously toggled
// one in a state the operator did not open; the Summary returns to
// its default sections.
_resetSummarySections();
}
case RunVisitTarget(:final stageKey, :final timelineIndex):
if (detailVisitStepAt(widget.run, timelineIndex) == null) return;
_selectedStage = stageKey;
_selectedVisit = timelineIndex;
_tab = RunDetailTab.timeline;
case RunArtifactTarget(:final url):
_selectedStage = null;
_selectedVisit = null;
if (!_tabsFor(widget.run).contains(RunDetailTab.artifacts)) {
// A run with no recorded steps has no gallery to open it in.
_tab = RunDetailTab.summary;
WidgetsBinding.instance.addPostFrameCallback(
(_) => mounted ? _showSearchArtifactMissingNotice() : null,
);
return;
}
// The gallery opens it as if tapped there: highlighted, scrolled into
// view and in the viewer, so Back returns to the Artifacts tab.
_tab = RunDetailTab.artifacts;
_searchArtifactUrl = url;
}
}
/// The Artifacts tab handled the search request: it opened the artifact, or
/// found no recorded file with that URL.
void _searchArtifactHandled(bool found) {
if (!mounted) return;
setState(() => _searchArtifactUrl = null);
if (!found) _showSearchArtifactMissingNotice();
}
void _showSearchArtifactMissingNotice() {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
const SnackBar(content: Text('That artifact is no longer available.')),
);
}
/// 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 index = latestDetailVisitIndex(widget.run['steps'], stageKey);
if (index == null) return;
setState(() {
_selectedStage = stageKey;
_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);
}
/// Brings the open visit page in line with the selection after this frame:
/// a cleared selection closes it, another visit replaces it.
void _syncVisitPage() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || _selectedVisit == _shownVisit) return;
final open = _visitRoute;
if (open != null) {
_shownVisit = null;
_visitRoute = null;
if (open.isActive) Navigator.of(context).removeRoute(open);
}
final index = _selectedVisit;
if (index != null) _pushVisit(index);
});
}
/// Opens [index]'s visit as its own page. The page follows the live run, so
/// a visit still running keeps updating; leaving it returns to the timeline.
Future<void> _pushVisit(int index) async {
_shownVisit = index;
Widget page(BuildContext pageContext) => ValueListenableBuilder<JsonMap>(
valueListenable: _liveRun,
builder: (context, run, _) {
final visits = detailTimeline(run['steps']);
final step = detailVisitStepAt(run, index);
final pane = index < visits.length && step != null
? RunVisitPane(
run: run,
visit: visits[index],
visitIndex: index,
step: step,
runSteps: detailRunSteps(run),
gateway: widget.gateway,
onRunChanged: widget.onRunChanged,
configuredEndpoint: widget.configuredEndpoint,
onSendToChat: widget.onSendToChat,
onClose: () => Navigator.of(pageContext).pop(),
)
: const Center(child: Text('This visit is no longer recorded.'));
// The bar names the stage over its visit and run, so the body
// repeats neither; the sections scroll behind it.
final known = index < visits.length;
final bar = SegmentedBar(
leading: SegmentedBackButton(
key: const Key('run-visit-back'),
onPressed: () => Navigator.of(pageContext).pop(),
),
title: known ? visits[index].stage : detailTitle(run),
titleKey: const Key('run-visit-title'),
subtitle: known ? runVisitSubtitle(run, visits[index]) : null,
);
final body = SafeArea(top: false, bottom: false, child: pane);
return Scaffold(extendBodyBehindAppBar: true, appBar: bar, body: body);
},
);
final route = MaterialPageRoute<void>(builder: page);
_visitRoute = route;
await Navigator.of(context).push<void>(route);
// Only the page the operator left clears the selection; one replaced by
// another selection has already handed over.
if (!mounted || _visitRoute != route) return;
setState(() {
_visitRoute = null;
_shownVisit = null;
_selectedVisit = null;
});
}
/// Artifacts once the run has recorded steps; Changes once it has stopped
/// executing, since a snapshot would not follow live captures.
List<RunDetailTab> _tabsFor(JsonMap run) => [
for (final tab in renderedRunDetailTabs)
if (switch (tab) {
RunDetailTab.artifacts => showRunArtifactsAction(run),
RunDetailTab.changes => showRunChangesAction(run),
_ => true,
})
tab,
];
@override
Widget build(BuildContext context) {
// A selected visit opens on its own page; the tab keeps the list.
if (_selectedVisit != _shownVisit) {
_syncVisitPage();
}
final tabs = _tabsFor(widget.run);
// A tab the run no longer offers falls back to Summary.
final shown = tabs.contains(_tab) || !renderedRunDetailTabs.contains(_tab)
? _tab
: RunDetailTab.summary;
final edge = PageTabsEdge.of(context);
return LayoutBuilder(
builder: (context, constraints) {
final headerLimit = _headerLimit(constraints);
final header = ConstrainedBox(
constraints: BoxConstraints(maxHeight: headerLimit),
child: SingleChildScrollView(
key: ValueKey('run-detail-header-${widget.run['id']}'),
child: widget.header,
),
);
final tabStrip = RunDetailTabStrip(
tabs: tabs,
edge: edge,
selected: shown,
onSelected: (tab) => setState(() => _tab = tab),
);
final body = FadeThroughStack(
key: ValueKey('run-detail-body-${widget.run['id']}'),
index: tabs.indexOf(shown),
lazy: true,
children: [for (final tab in tabs) _body(tab)],
);
if (edge == FloatingBarEdge.top &&
constraints.maxWidth >= kRunDetailWideChromeMinWidth) {
// Beside a list the tabs and the header share one row under the
// pane's bar, so only that row (not a header strip over a tabs
// strip) sits above the tab's content.
return FloatingBarOverlay(
edge: FloatingBarEdge.top,
bar: RunDetailWideChrome(tabs: tabStrip, header: header),
child: body,
);
}
// The header (status, actions, notices) is a glass strip floating
// just under the top bar, so every tab scrolls behind both and pads
// its first item clear of them at rest. Below it, the tabs float over
// the bottom of the tab (on a page and beside a list alike), and
// the tab learns their height as its padding on that edge too. Every
// tab gets the whole height: the scrolling tabs own their content and
// the Graph tab fills the slot, so its canvas is never asked for an
// unbounded extent.
return FloatingBarOverlay(
edge: FloatingBarEdge.top,
bar: TopGlassStrip(
key: const Key('run-detail-header'),
padding: const EdgeInsets.symmetric(vertical: 4),
child: header,
),
child: FloatingBarOverlay(edge: edge, bar: tabStrip, child: body),
);
},
);
}
Widget _body(RunDetailTab tab) {
switch (tab) {
case RunDetailTab.summary:
return runDetailSummaryTab(
context: context,
run: widget.run,
copying: widget.copying,
copyStatus: widget.copyStatus,
onCopy: widget.onCopy,
inputController: _inputSection,
outputController: _outputSection,
graphPreview: RunGraphPreview(
graph: detailGraph(widget.run),
run: widget.run,
selectedStage: _selectedStage,
onStageSelected: _openStage,
),
);
case RunDetailTab.graph:
// A canvas with its own overlay controls starts below the header.
return BelowTopBar(
child: RunGraphView(
key: const Key('run-detail-graph'),
graph: detailGraph(widget.run),
run: widget.run,
selectedStage: _selectedStage,
onStageSelected: _openStage,
),
);
case RunDetailTab.input:
return runDetailFieldTab(
tabKey: 'input',
value: widget.run['input'],
empty: 'No input recorded.',
);
case RunDetailTab.output:
return runDetailFieldTab(
tabKey: 'output',
value: widget.run['output'],
empty: 'No output recorded.',
);
case RunDetailTab.artifacts:
return ArtifactGalleryPage(
key: ValueKey('run-detail-artifacts-${widget.run['id']}'),
steps: runDetailArtifactSteps(widget.run),
executing: runDetailExecuting(widget.run),
configuredEndpoint: widget.configuredEndpoint,
embedded: true,
openArtifactUrl: _searchArtifactUrl,
onOpenArtifactHandled: _searchArtifactHandled,
artifactChatContext: ArtifactChatContext(
runId: '${widget.run['id'] ?? ''}',
runTitle: '${widget.run['title'] ?? widget.run['name'] ?? ''}',
pipelineName: '${widget.run['name'] ?? ''}',
pipelineVersion: widget.run['version'] is num
? (widget.run['version'] as num).toInt().toString()
: null,
configuredEndpoint: widget.configuredEndpoint,
),
onSendToChat: widget.onSendToChat,
);
case RunDetailTab.changes:
final viewer = ChangesViewer(
key: ValueKey('run-detail-changes-${widget.run['id']}'),
steps: runDetailChangeSteps(widget.run),
// The tab is the run's final changes; each visit's own are in its
// timeline detail.
showSummary: true,
finalOnly: true,
);
// Its summary heads the tab, so the tab starts below a pane's top tabs.
return BelowTopBar(child: viewer);
case RunDetailTab.timeline:
final visits = detailTimeline(widget.run['steps']);
final index = _selectedVisit;
return RunTimelineList(
visits: visits,
selectedSequence: index != null && index >= 0 && index < visits.length
? visits[index].sequence
: null,
onSelected: _openVisit,
);
}
}
/// The header keeps its natural height while at least
/// [kRunDetailMinContentHeight] remains for the tab, and never more than the
/// detail itself; past that it scrolls.
double _headerLimit(BoxConstraints constraints) {
if (!constraints.hasBoundedHeight) return double.infinity;
final height = constraints.maxHeight;
// Below twice the reserve the two shares meet at 40%, so the header stays
// reachable even when the detail is shorter than the reserve itself.
final floorShare = height * 0.4;
final reserve = height - kRunDetailMinContentHeight;
return math.max(floorShare, reserve).clamp(0.0, height);
}
}