Files
pipelines/app/lib/features/artifacts/ui/artifact_gallery_page.dart
T
alan 57f5219628 Artifacts: runner-internal turn files move to a Debugging files group
Each recorded artifact now carries a server group (deliverable or debug).
public/ files are deliverables; input/memory/history/output.md, session
exports and private/ scratch are debugging files. The app's Artifacts tab
lists deliverables and the Debug toggle reveals a separate Debugging files
group (older servers fall back to the filename rule); the TUI lists
deliverables first and marks debug rows; artifact search excludes debug
files unless include_debug / --debug-files is set.
2026-11-04 17:43:47 +00:00

643 lines
22 KiB
Dart

import '../../../ui/adaptive/segmented_bar.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import '../../graph/domain/stage_visits.dart';
import '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_capture.dart';
import '../domain/artifact_document.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/artifact_selection.dart';
import '../domain/artifact_summary.dart';
import '../domain/artifact_url.dart';
import 'artifact_external_open.dart';
import 'artifact_selection_facts.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_viewer_page.dart';
import 'artifact_visit_list.dart';
/// The gallery page title.
const String artifactGalleryTitle = 'Artifacts';
/// A read-only page of recorded stage/visit artifact groups.
///
/// Selection uses [artifactVisitIdentity], so the same filename in two visits
/// stays two distinct selections. Selecting a viewer artifact with a resolved
/// url opens the native [ArtifactViewerPage] (an external origin is marked and
/// never fetched); any other selection opens a native dialog with the recorded
/// name, MIME and size, the visit's capture facts and, only when the recorded
/// url resolves through [resolveArtifactUrl], native `Open` and `Copy link`
/// 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,
this.fetch = fetchArtifact,
this.markdownBuilder = chatMarkdownText,
this.fileBridge = const ArtifactFileBridge(),
this.embedded = false,
this.initiallyCollapsed = false,
this.openArtifactUrl,
this.onOpenArtifactHandled,
});
final List<JsonMap> 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;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
final ArtifactFileBridge fileBridge;
/// True inside the run detail's Artifacts tab: the list without its own
/// page bar, since the detail already names the run.
final bool embedded;
/// Run artifact views opt into collapsed groups; standalone gallery pages
/// preserve their established open layout.
final bool initiallyCollapsed;
/// A recorded artifact URL to open as if tapped here (a search hit): it is
/// selected, scrolled into view and opened in the viewer. The page reports
/// [onOpenArtifactHandled] with whether its groups record that URL.
final String? openArtifactUrl;
final ValueChanged<bool>? onOpenArtifactHandled;
@override
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
}
class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
late final Map<String, JsonMap> _stepsByGroup = recordedStepsByGroup(
widget.steps,
);
late final List<ArtifactGroup> _groups = _groupsOf(widget.focusIndex);
String? _selectedIdentity;
String? _status;
bool _showTurnDocuments = false;
/// The requested artifact the list is scrolling to before it opens.
({ArtifactGroup group, ArtifactRecord artifact})? _opening;
@override
void initState() {
super.initState();
_requestOpen(widget.openArtifactUrl);
}
@override
void didUpdateWidget(covariant ArtifactGalleryPage oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.openArtifactUrl != oldWidget.openArtifactUrl) {
_requestOpen(widget.openArtifactUrl);
}
}
/// Finds [url] among every recorded group, turn documents included, and
/// lets the list reveal it; [_revealed] then opens it.
void _requestOpen(String? url) {
if (url == null) return;
for (final group in _groups) {
for (final document in group.documents) {
final record = document.record;
if (record == null || record.url != url) continue;
// A debugging file is listed only while the debug toggle shows them.
_showTurnDocuments = true;
_opening = (group: group, artifact: record);
}
for (final artifact in group.artifacts) {
if (artifact.url == url) _opening = (group: group, artifact: artifact);
}
final opening = _opening;
if (opening != null) {
_selectedIdentity = artifactVisitIdentity(group, opening.artifact);
return;
}
}
final handled = widget.onOpenArtifactHandled;
WidgetsBinding.instance.addPostFrameCallback((_) => handled?.call(false));
}
void _revealed() {
final opening = _opening;
if (!mounted || opening == null) return;
setState(() => _opening = null);
widget.onOpenArtifactHandled?.call(true);
_select(opening.group, opening.artifact);
}
List<ArtifactGroup> _groupsOf(int? focusIndex) {
final allGroups = _withRepairDocuments(galleryGroups(widget.steps));
if (focusIndex == null) return allGroups;
if (focusIndex < 0 || focusIndex >= widget.steps.length) {
return const <ArtifactGroup>[];
}
final step = widget.steps[focusIndex];
final stageKey = '${step['stage'] ?? ''}';
final visits = visitsByStage(widget.steps)[stageKey];
if (visits == null) return const <ArtifactGroup>[];
final visitIndex = visits.indexOf(step);
if (visitIndex < 0) return const <ArtifactGroup>[];
final visit = displayVisit(step, visitIndex);
// Find the enriched gallery group directly rather than deriving it from the
// generated-artifact-only group. This retains document-only visits, including
// session.html, in the per-stage Artifacts section.
return [
for (final group in allGroups)
if (group.stageKey == stageKey && group.visit == visit) group,
];
}
/// Repaired session exports are also turn-owned debugging evidence, despite
/// living outside the four named document slots.
List<ArtifactGroup> _withRepairDocuments(List<ArtifactGroup> groups) {
final enriched = [
for (final group in groups)
ArtifactGroup(
stageKey: group.stageKey,
visit: group.visit,
artifacts: group.artifacts,
documents: [
...group.documents,
for (final artifact in systemArtifacts(
_stepsByGroup[artifactGroupKey(group.stageKey, group.visit)] ??
const <String, dynamic>{},
))
if (!group.documents.any(
(document) =>
document.record?.url == artifact.url &&
document.record?.name == artifact.name,
))
ArtifactDocument(
name: artifact.name,
record: artifact,
absence: '',
),
],
),
];
final keys = {
for (final group in enriched)
artifactGroupKey(group.stageKey, group.visit),
};
// `galleryGroups` intentionally only creates document-only groups for the
// four standard slots. A repair can be the only recorded evidence, so give
// it the same reachable secondary section.
for (final entry in visitsByStage(widget.steps).entries) {
for (var index = 0; index < entry.value.length; index += 1) {
final step = entry.value[index];
final visit = displayVisit(step, index);
final key = artifactGroupKey(entry.key, visit);
if (keys.contains(key)) continue;
final documents = systemArtifacts(step);
if (documents.isEmpty) continue;
enriched.add(
ArtifactGroup(
stageKey: entry.key,
visit: visit,
artifacts: const <ArtifactRecord>[],
documents: [
for (final artifact in documents)
ArtifactDocument(
name: artifact.name,
record: artifact,
absence: '',
),
],
),
);
}
}
return enriched;
}
Future<void> _select(ArtifactGroup group, ArtifactRecord artifact) async {
final identity = artifactVisitIdentity(group, artifact);
final resolved = artifact.hasUrl
? resolveArtifactUrl(widget.configuredEndpoint, artifact.url)
: null;
final externalOnly = artifact.name == sessionExportDocumentName;
setState(() {
_selectedIdentity = identity;
_status = null;
});
if (!externalOnly &&
resolved != null &&
isViewerArtifact(artifact.contentType, artifact.name)) {
await _openViewer(group, artifact);
return;
}
await _showSelected(group, artifact, resolved);
}
Future<void> _openViewer(
ArtifactGroup selectedGroup,
ArtifactRecord artifact,
) async {
final identity = artifactVisitIdentity(selectedGroup, artifact);
final isDocument = selectedGroup.documents.any(
(document) =>
document.record?.url == artifact.url &&
document.record?.name == artifact.name,
);
final viewerGroups = isDocument
? [
for (final group in _groups)
ArtifactGroup(
stageKey: group.stageKey,
visit: group.visit,
artifacts: [
for (final document in group.documents) ?document.record,
],
),
]
// A stage artifact pages through what the list shows: turn
// documents only while Debug reveals them.
: _showTurnDocuments
? _groups
: [
for (final group in _groups)
if (group.artifacts.isNotEmpty)
ArtifactGroup(
stageKey: group.stageKey,
visit: group.visit,
artifacts: group.artifacts,
),
];
final previousFocus = FocusManager.instance.primaryFocus;
await Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: viewerGroups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
fileBridge: widget.fileBridge,
),
)
: MaterialPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: viewerGroups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
fileBridge: widget.fileBridge,
),
),
);
if (!mounted) return;
if (previousFocus != null && previousFocus.canRequestFocus) {
previousFocus.requestFocus();
}
}
Future<void> _showSelected(
ArtifactGroup group,
ArtifactRecord artifact,
ResolvedArtifactUrl? resolved,
) {
final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)];
final facts = ArtifactSelectionFacts(
group: group,
artifact: artifact,
step: step,
resolved: resolved,
);
final content = Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
facts,
if (resolved != null && !resolved.external) ...[
const SizedBox(height: 12),
ArtifactFileActions(
key: ValueKey<String>(
'artifact-files-${artifactVisitIdentity(group, artifact)}',
),
artifact: artifact,
resolved: resolved,
fetch: widget.fetch,
bridge: widget.fileBridge,
),
],
],
);
if (usesCupertinoHost(context)) {
return showCupertinoDialog<void>(
context: context,
builder: (dialogContext) => CupertinoAlertDialog(
title: Text(artifactDisplayName(artifact)),
content: content,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Close'),
),
if (resolved != null)
CupertinoDialogAction(
onPressed: () => _copyLink(resolved, dialogContext),
child: const Text('Copy link'),
),
if (resolved != null)
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open in browser'),
),
],
),
);
}
return showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(artifactDisplayName(artifact)),
content: SingleChildScrollView(child: content),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Close'),
),
if (resolved != null)
TextButton(
onPressed: () => _copyLink(resolved, dialogContext),
child: const Text('Copy link'),
),
if (resolved != null)
TextButton(
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open in browser'),
),
],
),
);
}
Future<void> _open(
ResolvedArtifactUrl resolved,
BuildContext dialogContext,
) async {
Navigator.of(dialogContext).pop();
final opened = await widget.openExternal(resolved.uri);
if (!mounted) return;
setState(
() => _status = opened
? 'Link opened externally.'
: 'Could not open the link.',
);
}
Future<void> _copyLink(
ResolvedArtifactUrl resolved,
BuildContext dialogContext,
) async {
Navigator.of(dialogContext).pop();
String message;
try {
await Clipboard.setData(ClipboardData(text: resolved.url));
message = 'Link copied.';
} catch (_) {
message = 'Could not copy link.';
}
if (!mounted) return;
setState(() => _status = message);
}
/// The step a focused page shows, or null when the page covers the whole run.
///
/// [focusIndex] comes from the opening visit pane, so it is validated once
/// here rather than in each of the summary, notes and group builders.
JsonMap? get _focusedStep {
final focusIndex = widget.focusIndex;
if (focusIndex == null ||
focusIndex < 0 ||
focusIndex >= widget.steps.length) {
return null;
}
return widget.steps[focusIndex];
}
/// 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<ArtifactGroup> groups) {
final focused = _focusedStep;
if (focused != null) {
final count = groups.fold<int>(
0,
(total, group) => total + group.artifacts.length,
);
if (count == 0 && groups.any((group) => group.documents.isNotEmpty)) {
return 'No artifacts recorded for this visit.';
}
return artifactsSummary(focused, count: count);
}
if (widget.steps.isEmpty) return 'No steps recorded for this run.';
final count = groups.fold<int>(
0,
(total, group) => total + group.artifacts.length,
);
if (count == 0) {
if (widget.executing) return 'Artifacts · capture pending';
if (widget.steps.any(
(step) => !ArtifactCapture.fromStep(step).isAvailable,
)) {
return 'Artifacts · capture unavailable';
}
return 'No artifacts recorded for this run.';
}
var label = '${count == 1 ? 'Artifact' : 'Artifacts'} · $count recorded';
if (widget.steps.any((step) => ArtifactCapture.fromStep(step).isPartial)) {
label += ' · partial capture';
}
return label;
}
/// The partial-capture notes shown under the page's summary.
///
/// A focused visit states its own capture facts, matching the web client's
/// per-visit artifact section. The run-wide page keeps each visit's recorded
/// wording and names the visit it belongs to, because the same count means
/// different files in a different visit. Complete captures add nothing.
List<String> _captureNotes() {
final focused = _focusedStep;
if (focused != null) return artifactCaptureNotes(focused);
return <String>[
for (final group in _groups)
for (final note in artifactCaptureNotes(
_stepsByGroup[artifactGroupKey(group.stageKey, group.visit)] ??
const <String, dynamic>{},
))
'${artifactGroupLabel(group)} · $note',
];
}
/// The compact page header: the recorded count on one line, then the visit's
/// capture notes in the host's secondary label style, then any transient
/// status.
///
/// The header is handed to [ArtifactVisitList] as its leading child, so a run
/// with many partial visits — or a focused visit at large text — scrolls with
/// the artifacts instead of taking height from them. It is content-driven:
/// one line per recorded fact, never clamped or shortened.
Widget _header(BuildContext context, String summary, {Widget? action}) {
final notes = _captureNotes();
final cupertino = usesCupertinoHost(context);
final textStyle = cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium ?? const TextStyle();
final headingStyle = cupertino
? textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(context).textTheme.titleSmall;
final noteStyle = textStyle.copyWith(
color: cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant,
);
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(
child: Semantics(
container: true,
header: true,
child: Text(summary, style: headingStyle),
),
),
?action,
],
),
for (final note in notes)
Padding(
padding: const EdgeInsets.only(top: 2),
child: Text(note, style: noteStyle),
),
if (_status != null)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Semantics(liveRegion: true, child: Text(_status!)),
),
],
),
);
}
Widget _debugToggle(BuildContext context) {
final showing = _showTurnDocuments;
final label = showing ? 'Hide debugging files' : 'Show debugging files';
// Cupertino's bundled icon font has no bug glyph; retain the universally
// recognisable Material bug icon inside its native Cupertino button.
final icon = showing ? Icons.bug_report : Icons.bug_report_outlined;
void onPressed() => setState(() => _showTurnDocuments = !showing);
final button = usesCupertinoHost(context)
? CupertinoButton(
key: const Key('artifact-debug-toggle'),
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Icon(icon),
)
: IconButton(
key: const Key('artifact-debug-toggle'),
isSelected: showing,
tooltip: label,
onPressed: onPressed,
icon: Icon(icon),
);
final semanticButton = Semantics(
label: label,
button: true,
toggled: showing,
child: button,
);
return usesCupertinoHost(context)
? Tooltip(message: label, child: semanticButton)
: semanticButton;
}
@override
Widget build(BuildContext context) {
final groups = _groups;
final visibleGroups = [
for (final group in groups)
if (group.artifacts.isNotEmpty ||
(_showTurnDocuments && group.documents.isNotEmpty))
group,
];
final header = _header(
context,
_summary(groups),
action: widget.embedded ? _debugToggle(context) : null,
);
// Header, status and rows share one scroll view: the page never splits a
// fixed header from a shrinking list, so a long header always stays usable.
final body = visibleGroups.isEmpty
? ListView(children: [header])
: ArtifactVisitList(
header: header,
groups: visibleGroups,
selectedIdentity: _selectedIdentity,
onSelected: _select,
configuredEndpoint: widget.configuredEndpoint,
fetch: widget.fetch,
initiallyCollapsed: widget.initiallyCollapsed,
showTurnDocuments: _showTurnDocuments,
revealIdentity: _opening == null ? null : _selectedIdentity,
onRevealed: _revealed,
);
if (widget.embedded) return body;
if (usesCupertinoHost(context)) {
// Flat sections on the page colour, as in the run and stage details;
// their pinned headings take the same colour.
return CupertinoPageScaffold(
navigationBar: SegmentedBar(
cupertino: true,
title: artifactGalleryTitle,
actions: [_debugToggle(context)],
),
child: SafeArea(top: false, bottom: false, child: body),
);
}
return Scaffold(
extendBodyBehindAppBar: true,
appBar: SegmentedBar(
cupertino: false,
title: artifactGalleryTitle,
actions: [_debugToggle(context)],
),
body: SafeArea(top: false, bottom: false, child: body),
);
}
}