Files
pipelines/app/lib/features/artifacts/ui/artifact_gallery_page.dart
T

407 lines
14 KiB
Dart

import '../../../ui/theme/app_theme.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 '../actions/artifact_file_actions.dart';
import '../actions/artifact_file_bridge.dart';
import '../domain/artifact_document.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.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,
});
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;
@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;
List<ArtifactGroup> _groupsOf(int? focusIndex) {
if (focusIndex == null) return galleryGroups(widget.steps);
final group = visitArtifactGroup(widget.steps, focusIndex);
if (group == null) return const <ArtifactGroup>[];
// The visit pane sees the same document-enriched group the gallery shows for
// that visit, not only its recorded files.
for (final enriched in galleryGroups(widget.steps)) {
if (enriched.stageKey == group.stageKey &&
enriched.visit == group.visit) {
// The visit pane's own Session section opens session.html, so the
// per-visit Artifacts drill-down keeps only stage output and the other
// turn documents; the run-wide gallery still shows every document.
final documents = enriched.documents
.where((doc) => doc.record?.name != sessionExportDocumentName)
.toList(growable: false);
return <ArtifactGroup>[
ArtifactGroup(
stageKey: enriched.stageKey,
visit: enriched.visit,
artifacts: enriched.artifacts,
documents: documents,
),
];
}
}
return <ArtifactGroup>[group];
}
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(identity);
return;
}
await _showSelected(group, artifact, resolved);
}
Future<void> _openViewer(String identity) async {
final previousFocus = FocusManager.instance.primaryFocus;
await Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: _groups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
fileBridge: widget.fileBridge,
),
)
: MaterialPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: _groups,
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'),
),
],
),
);
}
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'),
),
],
),
);
}
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,
);
return artifactsSummary(focused, count: count);
}
if (widget.steps.isEmpty) return 'No steps recorded for this run.';
return artifactsHeader(widget.steps, executing: widget.executing);
}
/// 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) {
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: [
Semantics(
container: true,
header: true,
child: Text(summary, style: headingStyle),
),
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!)),
),
],
),
);
}
@override
Widget build(BuildContext context) {
final groups = _groups;
final header = _header(context, _summary(groups));
// 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 = groups.isEmpty
? ListView(children: [header])
: ArtifactVisitList(
header: header,
groups: groups,
selectedIdentity: _selectedIdentity,
onSelected: _select,
configuredEndpoint: widget.configuredEndpoint,
fetch: widget.fetch,
);
if (widget.embedded) return body;
if (usesCupertinoHost(context)) {
return CupertinoPageScaffold(
// Sections paint the grouped background; the page must match it or a
// white seam shows below the last section in light mode.
backgroundColor: AppColors.groupedBackground,
navigationBar: const CupertinoNavigationBar(
middle: Text(artifactGalleryTitle),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(title: const Text(artifactGalleryTitle)),
body: SafeArea(top: false, child: body),
);
}
}