Merge branch 'main' into flutter/chat-markdown

This commit is contained in:
2026-10-21 23:34:35 +01:00
91 changed files with 12318 additions and 149 deletions
+32 -6
View File
@@ -10,7 +10,7 @@ enum AppRouteKind { pipelines, runs, chat, settings }
/// malformed path resolves to the default Pipelines list instead of throwing.
/// The serialiser is its inverse for every route the app can produce.
class AppRoute {
const AppRoute(this.kind, {this.runId});
const AppRoute(this.kind, {this.runId, this.chatSessionId});
static const pipelines = AppRoute(AppRouteKind.pipelines);
static const runs = AppRoute(AppRouteKind.runs);
@@ -19,16 +19,27 @@ class AppRoute {
static const run = _RunRouteFactory();
/// One chat session, or the chat list when [id] is not a session id.
static AppRoute chatSession(String id) => isChatSessionId(id)
? AppRoute(AppRouteKind.chat, chatSessionId: id)
: chat;
final AppRouteKind kind;
/// The run shown by the Runs destination, or null for the list.
final int? runId;
/// The chat session shown by the Chat destination, or null for the list.
final String? chatSessionId;
/// The path the app writes into history for this route.
String get path => switch (kind) {
AppRouteKind.pipelines => '/pipelines',
AppRouteKind.runs => runId == null ? '/runs' : '/runs/$runId',
AppRouteKind.chat => '/chat',
AppRouteKind.chat =>
chatSessionId == null || !isChatSessionId(chatSessionId!)
? '/chat'
: '/chat/${Uri.encodeComponent(chatSessionId!)}',
AppRouteKind.settings => '/settings',
};
@@ -65,6 +76,7 @@ class AppRoute {
'runs' when segments.length == 1 => runs,
'runs' when segments.length == 2 => _runRoute(segments[1]),
'chat' when segments.length == 1 => chat,
'chat' when segments.length == 2 => _chatRoute(segments[1]),
'settings' when segments.length == 1 => settings,
_ => pipelines,
};
@@ -77,12 +89,26 @@ class AppRoute {
return AppRoute(AppRouteKind.runs, runId: id);
}
@override
bool operator ==(Object other) =>
other is AppRoute && other.kind == kind && other.runId == runId;
/// A chat session id is nonempty, bounded and URL-safe, matching the web
/// parser. Anything else is malformed rather than a stale session the
/// destination has to guess about.
static bool isChatSessionId(String value) =>
value.isNotEmpty &&
value.length <= 200 &&
RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value);
static AppRoute _chatRoute(String value) =>
isChatSessionId(value) ? chatSession(value) : pipelines;
@override
int get hashCode => Object.hash(kind, runId);
bool operator ==(Object other) =>
other is AppRoute &&
other.kind == kind &&
other.runId == runId &&
other.chatSessionId == chatSessionId;
@override
int get hashCode => Object.hash(kind, runId, chatSessionId);
@override
String toString() => path;
+13 -3
View File
@@ -27,6 +27,7 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
AppRouterDelegate({
required this.builder,
required this.onPopToRuns,
required this.onPopToChat,
required this.cupertino,
AppRoute initial = AppRoute.pipelines,
}) : _route = initial;
@@ -36,6 +37,9 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
/// Called when a system Back belongs to the Runs detail, not the app stack.
final VoidCallback onPopToRuns;
/// Called when a system Back belongs to one chat session.
final VoidCallback onPopToChat;
final bool cupertino;
final _navigatorKey = GlobalKey<NavigatorState>();
@@ -81,9 +85,15 @@ class AppRouterDelegate extends RouterDelegate<AppRoute> with ChangeNotifier {
@override
Future<bool> popRoute() async {
if (_route.runId == null) return false;
onPopToRuns();
return true;
if (_route.runId != null) {
onPopToRuns();
return true;
}
if (_route.chatSessionId != null) {
onPopToChat();
return true;
}
return false;
}
/// Records a user move; the Router turns the new configuration into a
+69
View File
@@ -0,0 +1,69 @@
import 'package:flutter/material.dart';
import '../features/chat/screen.dart';
import '../ui/adaptive/host.dart';
import 'app_session.dart';
import 'connection_status.dart';
import 'server_endpoint.dart';
/// The Chat destination: the shared session list and one read-only thread.
///
/// Before the shared socket accepts its first connection nothing is requested,
/// so an offline launch cannot look like an empty chat list. After that the
/// screen stays mounted through drops; a reconnect advances [syncToken] so the
/// open conversation re-subscribes and re-reads without losing its selection.
class ChatDestination extends StatelessWidget {
const ChatDestination({
super.key,
required this.session,
required this.server,
this.initialSessionId,
this.onSessionSelected,
this.onBack,
});
final AppSession session;
final ServerEndpoint server;
final String? initialSessionId;
final ValueChanged<String>? onSessionSelected;
final VoidCallback? onBack;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: session,
builder: (context, _) {
final cupertino = usesCupertinoHost(context);
if ((server.requiresConfiguration || server.error != null) &&
session.endpoint == null) {
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
);
}
if (!session.everConnected) {
if (session.connected) return _chatScreen();
return ConnectionGate(
session: session,
server: server,
cupertino: cupertino,
);
}
return Column(
children: [
if (!session.connected)
ConnectionBanner(session: session, cupertino: cupertino),
Expanded(child: _chatScreen()),
],
);
},
);
Widget _chatScreen() => ChatScreen(
gateway: session.gateway,
initialSessionId: initialSessionId,
syncToken: session.connectionEpoch,
onSessionSelected: onSessionSelected,
onBack: onBack,
);
}
+9
View File
@@ -11,6 +11,7 @@ import 'app.dart';
import 'app_route.dart';
import 'app_router.dart';
import 'app_session.dart';
import 'chat_destination.dart';
import 'pipelines_destination.dart';
import 'runs_destination.dart';
import 'server_endpoint.dart';
@@ -71,6 +72,7 @@ class _PipelinesAppState extends State<PipelinesApp> {
initial: initial,
cupertino: _cupertino,
onPopToRuns: () => _delegate.goTo(AppRoute.runs),
onPopToChat: () => _delegate.goTo(AppRoute.chat),
builder: _buildShell,
);
_config = RouterConfig<AppRoute>(
@@ -110,6 +112,13 @@ class _PipelinesAppState extends State<PipelinesApp> {
onRunSelected: (id) => _delegate.goTo(AppRoute.run(id)),
onBack: () => _delegate.goTo(AppRoute.runs),
),
AppDestination.chat: (_) => ChatDestination(
session: _session,
server: widget.server,
initialSessionId: route.chatSessionId,
onSessionSelected: (id) => _delegate.goTo(AppRoute.chatSession(id)),
onBack: () => _delegate.goTo(AppRoute.chat),
),
AppDestination.settings: (_) => SettingsScreen(
client: _session.client,
initialEndpoint: _session.endpoint,
@@ -196,13 +196,17 @@ bool isMarkdownArtifact(String contentType, String name) {
return _markdownExtensions.contains(_extensionOf(name));
}
/// Whether an artifact opens inside the full-screen viewer: images, videos, and
/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays
/// an external file because those are evidence, not prose.
/// Whether an artifact opens inside the viewer: images, videos, markdown/text
/// documents and any recorded `text/plain` file. The viewer draws text/plain as
/// selectable text; a CSV, source file or spreadsheet with its own type stays an
/// external file because it is evidence, not prose. Videos are pageable but the
/// viewer reports that it cannot draw them rather than faking a player.
bool isViewerArtifact(String contentType, String name) {
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
return true;
}
final mime = contentType.split(';').first.trim().toLowerCase();
if (mime == 'text/plain') return true;
return artifactKind(contentType, name) == ArtifactKind.document &&
isMarkdownArtifact(contentType, name);
}
@@ -0,0 +1,118 @@
import 'artifact_kind.dart';
import 'artifact_record.dart';
import 'artifact_url.dart';
/// What the in-app viewer can do with one recorded artifact.
enum ArtifactPreviewKind {
image,
text,
markdown,
/// A recorded file the viewer cannot draw (video, CSV, archives, ...).
unsupported,
/// No safe same-origin url to fetch: absent, unsafe or another origin.
unavailable,
}
/// One artifact's preview decision: the safe resolved url, the content kind and
/// the exact wording for a state that cannot be previewed.
///
/// An external url is deliberately [ArtifactPreviewKind.unavailable]: the viewer
/// never fetches another origin, so a recorded url on a different host is marked
/// instead of being requested with the app's credentials. [canFetch] is the one
/// gate the viewer's fetch consults.
class ArtifactPreviewPlan {
const ArtifactPreviewPlan({
required this.kind,
required this.resolved,
required this.message,
});
final ArtifactPreviewKind kind;
final ResolvedArtifactUrl? resolved;
/// The explicit reason a non-previewable artifact is not drawn; empty for an
/// image, text or markdown document that may be fetched.
final String message;
bool get canFetch =>
resolved != null &&
resolved!.external == false &&
(kind == ArtifactPreviewKind.image ||
kind == ArtifactPreviewKind.text ||
kind == ArtifactPreviewKind.markdown);
}
const String artifactPreviewNoUrl = 'No artifact URL recorded.';
const String artifactPreviewUnsafeUrl =
'The recorded artifact URL cannot be opened safely.';
const String artifactPreviewExternalUrl =
'This artifact is hosted on another origin and is not previewed here.';
/// Classifies [artifact] against the configured server origin.
///
/// Images are drawn from the resolved bytes; `text/plain` is selectable text; a
/// `.md`/`.markdown` name or `text/markdown` is handed to the injected markdown
/// builder. Everything else is explicitly unsupported rather than faked.
ArtifactPreviewPlan planArtifactPreview({
required ArtifactRecord artifact,
required String configuredEndpoint,
}) {
if (!artifact.hasUrl) {
return const ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: null,
message: artifactPreviewNoUrl,
);
}
final resolved = resolveArtifactUrl(configuredEndpoint, artifact.url);
if (resolved == null) {
return const ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: null,
message: artifactPreviewUnsafeUrl,
);
}
if (resolved.external) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unavailable,
resolved: resolved,
message: artifactPreviewExternalUrl,
);
}
final mime = artifact.contentType.split(';').first.trim().toLowerCase();
if (isImageContentType(mime)) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.image,
resolved: resolved,
message: '',
);
}
if (mime == 'text/markdown' || _isMarkdownName(artifact.name)) {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.markdown,
resolved: resolved,
message: '',
);
}
if (mime == 'text/plain') {
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.text,
resolved: resolved,
message: '',
);
}
return ArtifactPreviewPlan(
kind: ArtifactPreviewKind.unsupported,
resolved: resolved,
message: 'This file type cannot be previewed here.',
);
}
bool _isMarkdownName(String name) {
final dot = name.lastIndexOf('.');
if (dot == -1) return false;
final extension = name.substring(dot + 1).toLowerCase();
return extension == 'md' || extension == 'markdown';
}
@@ -7,24 +7,34 @@ import 'artifact_record.dart';
/// a visit-scoped key so two url-less records never collapse into one page.
class PagedArtifact {
const PagedArtifact({
required this.stageKey,
required this.visit,
required this.group,
required this.artifact,
required this.pageIndex,
});
final String stageKey;
final int visit;
final ArtifactGroup group;
final ArtifactRecord artifact;
/// Position in the filtered page list.
final int pageIndex;
String get stageKey => group.stageKey;
int get visit => group.visit;
String get identity => artifact.hasUrl
? artifact.url
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
}
/// The gallery row identity of [artifact] inside [group], shared by the row
/// list and the viewer so selecting a row opens exactly that page. The recorded
/// visit is part of the key, so two visits that recorded the same name stay
/// distinct even when their recorded urls match.
String artifactVisitIdentityOf(ArtifactGroup group, ArtifactRecord artifact) {
final recorded = artifact.hasUrl ? artifact.url : artifact.name;
return '${group.stageKey}\u0000${group.visit}\u0000$recorded';
}
/// The artifacts the viewer can page through, in gallery order: group by group,
/// each group's images, videos and markdown/text documents in recorded order.
/// Other artifacts open externally and are not part of this list. Pure: it only
@@ -36,8 +46,7 @@ List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
pages.add(
PagedArtifact(
stageKey: group.stageKey,
visit: group.visit,
group: group,
artifact: artifact,
pageIndex: pages.length,
),
@@ -0,0 +1,14 @@
import '../domain/artifact_url.dart';
import 'artifact_external_open_stub.dart'
if (dart.library.js_interop) 'artifact_external_open_web.dart'
as impl;
/// Opens an already validated artifact url with the host's external handler.
///
/// The url must come from [resolveArtifactUrl]; this capability never resolves,
/// rewrites, fetches or previews it. Returns whether the host accepted the
/// request, so a refusal is reported instead of being silently swallowed.
typedef ArtifactExternalOpen = Future<bool> Function(Uri uri);
Future<bool> openArtifactExternally(Uri uri) =>
impl.openArtifactExternally(uri);
@@ -0,0 +1,6 @@
/// Non-web fallback for external artifact urls.
///
/// A native launcher needs a platform plugin that this slice does not depend
/// on, so a non-web host reports the refusal instead of pretending to open the
/// link. The page surfaces that message to the operator.
Future<bool> openArtifactExternally(Uri uri) async => false;
@@ -0,0 +1,20 @@
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
/// Web external open: a new browser tab. The url is already validated by
/// [resolveArtifactUrl]; it is passed through unchanged and never fetched.
///
/// `window.open` is reached through `js_interop` rather than `dart:html`, so the
/// same source compiles for both the JavaScript and WebAssembly web targets.
Future<bool> openArtifactExternally(Uri uri) async {
try {
final opened = globalContext.callMethod(
'open'.toJS,
uri.toString().toJS,
'_blank'.toJS,
);
return opened.isDefinedAndNotNull;
} catch (_) {
return false;
}
}
@@ -0,0 +1,104 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../core/transport/pipelines_client.dart';
import '../../../ui/adaptive/host.dart';
import 'artifact_external_open.dart';
import 'artifact_gallery_page.dart';
/// The run detail's action label key, so a host can find the one action.
const ValueKey<String> runArtifactsButtonKey = ValueKey<String>(
'run-detail-artifacts',
);
const Set<String> _executingStatuses = {'queued', 'running', 'waiting'};
/// The detail's `steps` exactly as returned by the server. The pushed page
/// snapshots the returned list once, so it never re-derives on each rebuild.
List<JsonMap> runDetailArtifactSteps(JsonMap run) {
final steps = run['steps'];
if (steps is List<JsonMap>) return steps;
if (steps is List) return steps.cast<JsonMap>();
return const <JsonMap>[];
}
/// Whether the run detail offers the gallery action at all: only once the
/// loaded detail actually carries steps. A run with no steps has nothing to
/// list, so the action is absent rather than opening a page that says so.
bool showRunArtifactsAction(JsonMap run) =>
runDetailArtifactSteps(run).isNotEmpty;
/// Whether the run is still executing, so the page can say capture pending
/// instead of claiming nothing was recorded.
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 {
const RunArtifactsButton({
super.key,
required this.run,
required this.gateway,
});
final JsonMap run;
final ApiGateway gateway;
@override
Widget build(BuildContext context) {
final steps = runDetailArtifactSteps(run);
void open() => showArtifactGallery(
context,
steps: steps,
executing: _runExecuting(run),
configuredEndpoint: _gatewayEndpoint(gateway),
);
if (usesCupertinoHost(context)) {
return CupertinoButton.tinted(
key: runArtifactsButtonKey,
onPressed: open,
child: const Text(artifactGalleryTitle),
);
}
return FilledButton.tonalIcon(
key: runArtifactsButtonKey,
onPressed: open,
icon: const Icon(Icons.inventory_2_outlined),
label: const Text(artifactGalleryTitle),
);
}
}
/// Opens the recorded artifact groups on a native page. The steps are
/// snapshotted once; the page never re-fetches or re-derives them.
Future<void> showArtifactGallery(
BuildContext context, {
required List<JsonMap> steps,
bool executing = false,
String configuredEndpoint = '',
ArtifactExternalOpen openExternal = openArtifactExternally,
}) {
final page = ArtifactGalleryPage(
steps: List<JsonMap>.unmodifiable(steps),
executing: executing,
configuredEndpoint: configuredEndpoint,
openExternal: openExternal,
);
return Navigator.of(context).push<void>(
usesCupertinoHost(context)
? CupertinoPageRoute<void>(builder: (_) => page)
: MaterialPageRoute<void>(builder: (_) => page),
);
}
@@ -0,0 +1,246 @@
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 '../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. It never downloads, shares or filters.
class ArtifactGalleryPage extends StatefulWidget {
const ArtifactGalleryPage({
super.key,
required this.steps,
this.executing = false,
this.configuredEndpoint = '',
this.openExternal = openArtifactExternally,
this.fetch = fetchArtifact,
this.markdownBuilder = defaultArtifactMarkdown,
});
final List<JsonMap> steps;
final bool executing;
final String configuredEndpoint;
final ArtifactExternalOpen openExternal;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
@override
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
}
class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
late final Map<String, JsonMap> _stepsByGroup = recordedStepsByGroup(
widget.steps,
);
late final List<ArtifactGroup> _groups = artifactGroups(widget.steps);
String? _selectedIdentity;
String? _status;
Future<void> _select(ArtifactGroup group, ArtifactRecord artifact) async {
final identity = artifactVisitIdentity(group, artifact);
final resolved = artifact.hasUrl
? resolveArtifactUrl(widget.configuredEndpoint, artifact.url)
: null;
setState(() {
_selectedIdentity = identity;
_status = null;
});
if (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,
),
)
: MaterialPageRoute<void>(
builder: (_) => ArtifactViewerPage(
groups: _groups,
selectedIdentity: identity,
configuredEndpoint: widget.configuredEndpoint,
openExternal: widget.openExternal,
fetch: widget.fetch,
markdownBuilder: widget.markdownBuilder,
),
),
);
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,
);
if (usesCupertinoHost(context)) {
return showCupertinoDialog<void>(
context: context,
builder: (dialogContext) => CupertinoAlertDialog(
title: Text(artifactDisplayName(artifact)),
content: facts,
actions: [
if (resolved != null)
CupertinoDialogAction(
isDefaultAction: true,
onPressed: () => _open(resolved, dialogContext),
child: const Text('Open'),
),
if (resolved != null)
CupertinoDialogAction(
onPressed: () => _copyLink(resolved, dialogContext),
child: const Text('Copy link'),
),
CupertinoDialogAction(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Close'),
),
],
),
);
}
return showDialog<void>(
context: context,
builder: (dialogContext) => AlertDialog(
title: Text(artifactDisplayName(artifact)),
content: SingleChildScrollView(child: facts),
actions: [
if (resolved != null)
TextButton(
onPressed: () => _copyLink(resolved, dialogContext),
child: const Text('Copy link'),
),
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(),
child: const Text('Close'),
),
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);
}
@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 body = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
child: Text(summary),
),
if (_status != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
child: Semantics(liveRegion: true, child: Text(_status!)),
),
if (groups.isNotEmpty)
Expanded(
child: ArtifactVisitList(
groups: groups,
selectedIdentity: _selectedIdentity,
onSelected: _select,
),
),
],
);
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: CupertinoColors.systemGroupedBackground,
navigationBar: const CupertinoNavigationBar(
middle: Text(artifactGalleryTitle),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(title: const Text(artifactGalleryTitle)),
body: SafeArea(top: false, child: body),
);
}
}
@@ -0,0 +1,71 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_visits.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_record.dart';
import '../domain/artifact_summary.dart';
import '../domain/artifact_url.dart';
import 'artifact_visit_list.dart';
/// The key one recorded group maps to, used only to find its step.
String artifactGroupKey(String stageKey, int visit) => '$stageKey\u0000$visit';
/// Each recorded group's step, keyed by stage and display visit, so a selected
/// row can show its own visit's capture facts. Derives the same grouping the
/// gallery uses; an absent key yields null rather than a fabricated capture.
Map<String, JsonMap> recordedStepsByGroup(List<JsonMap> steps) {
final result = <String, JsonMap>{};
for (final entry in visitsByStage(steps).entries) {
for (var index = 0; index < entry.value.length; index += 1) {
final step = entry.value[index];
result[artifactGroupKey(entry.key, displayVisit(step, index))] = step;
}
}
return result;
}
/// The recorded facts of one selected artifact: name, MIME/size, its visit's
/// capture summary and notes, and the url state. Nothing is inferred.
class ArtifactSelectionFacts extends StatelessWidget {
const ArtifactSelectionFacts({
super.key,
required this.group,
required this.artifact,
required this.step,
required this.resolved,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final JsonMap? step;
final ResolvedArtifactUrl? resolved;
@override
Widget build(BuildContext context) {
final recordedStep = step;
final url = resolved;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(artifactFactsLabel(artifact)),
const SizedBox(height: 8),
Text(artifactGroupLabel(group)),
if (recordedStep != null) ...[
const SizedBox(height: 8),
Text(artifactsSummary(recordedStep, count: group.artifacts.length)),
for (final note in artifactCaptureNotes(recordedStep))
Padding(padding: const EdgeInsets.only(top: 4), child: Text(note)),
],
if (!artifact.hasUrl) ...[
const SizedBox(height: 8),
const Text('No artifact URL recorded.'),
] else if (url == null) ...[
const SizedBox(height: 8),
const Text('The recorded artifact URL cannot be opened safely.'),
],
],
);
}
}
@@ -0,0 +1,210 @@
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_selection_facts.dart';
import 'artifact_viewer_content.dart';
/// One viewer page: the recorded facts, position, live status, preview surface,
/// external actions and paging controls.
///
/// It is stateless so the page owns loading, fetch generations and focus; this
/// surface only draws the current page and reports the operator's intent.
class ArtifactViewerBody extends StatelessWidget {
const ArtifactViewerBody({
super.key,
required this.page,
required this.plan,
required this.index,
required this.count,
required this.loading,
required this.markdownBuilder,
required this.onPrevious,
required this.onNext,
required this.onOpen,
required this.onCopy,
this.text,
this.bytes,
this.error,
this.status,
});
final PagedArtifact page;
final ArtifactPreviewPlan plan;
final int index;
final int count;
final bool loading;
final ArtifactMarkdownBuilder markdownBuilder;
final VoidCallback onPrevious;
final VoidCallback onNext;
final VoidCallback onOpen;
final VoidCallback onCopy;
final String? text;
final Uint8List? bytes;
final String? error;
final String? status;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 12, 16, 4),
child: ArtifactSelectionFacts(
group: page.group,
artifact: page.artifact,
step: null,
resolved: plan.resolved,
),
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 16, 4),
child: Text(
artifactViewerPositionLabel(
index,
count,
page.artifact.contentType,
),
),
),
if (status != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 4),
child: Semantics(liveRegion: true, child: Text(status!)),
),
Expanded(
child: ArtifactPreviewBody(
plan: plan,
loading: loading,
markdownBuilder: markdownBuilder,
text: text,
bytes: bytes,
error: error,
),
),
if (plan.resolved != null)
_Actions(resolved: plan.resolved!, onOpen: onOpen, onCopy: onCopy),
_Pager(
index: index,
count: count,
onPrevious: onPrevious,
onNext: onNext,
),
],
);
}
}
class _Actions extends StatelessWidget {
const _Actions({
required this.resolved,
required this.onOpen,
required this.onCopy,
});
final ResolvedArtifactUrl resolved;
final VoidCallback onOpen;
final VoidCallback onCopy;
@override
Widget build(BuildContext context) {
if (usesCupertinoHost(context)) {
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
children: [
CupertinoButton(onPressed: onOpen, child: const Text('Open')),
CupertinoButton(onPressed: onCopy, child: const Text('Copy link')),
],
),
);
}
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.center,
spacing: 8,
children: [
TextButton.icon(
onPressed: onOpen,
icon: const Icon(Icons.open_in_new),
label: const Text('Open'),
),
TextButton.icon(
onPressed: onCopy,
icon: const Icon(Icons.content_copy),
label: const Text('Copy link'),
),
],
),
);
}
}
class _Pager extends StatelessWidget {
const _Pager({
required this.index,
required this.count,
required this.onPrevious,
required this.onNext,
});
final int index;
final int count;
final VoidCallback onPrevious;
final VoidCallback onNext;
@override
Widget build(BuildContext context) {
if (count <= 1) return const SizedBox.shrink();
final hasPrevious = pagedIndex(index, -1, count) != index;
final hasNext = pagedIndex(index, 1, count) != index;
if (usesCupertinoHost(context)) {
return SafeArea(
top: false,
child: Wrap(
alignment: WrapAlignment.spaceBetween,
children: [
CupertinoButton(
onPressed: hasPrevious ? onPrevious : null,
child: const Text('Previous artifact'),
),
CupertinoButton(
onPressed: hasNext ? onNext : null,
child: const Text('Next artifact'),
),
],
),
);
}
return SafeArea(
top: false,
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
TextButton.icon(
onPressed: hasPrevious ? onPrevious : null,
icon: const Icon(Icons.arrow_back),
label: const Text('Previous artifact'),
),
TextButton.icon(
onPressed: hasNext ? onNext : null,
icon: const Icon(Icons.arrow_forward),
label: const Text('Next artifact'),
),
],
),
),
);
}
}
@@ -0,0 +1,122 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../domain/artifact_preview.dart';
/// Renders fetched markdown text for the viewer. The gallery's default builder
/// returns plain selectable text, so the viewer is honest before the markdown
/// lane supplies a real renderer.
typedef ArtifactMarkdownBuilder = Widget Function(String text);
Widget defaultArtifactMarkdown(String text) => SelectableText(text);
/// The viewer's preview surface for one page.
///
/// It draws only what was actually fetched: image bytes as an [Image], text as
/// selectable text, markdown through [markdownBuilder], and an explicit message
/// for unsupported/unavailable pages. It never substitutes a placeholder that
/// looks like a preview.
class ArtifactPreviewBody extends StatelessWidget {
const ArtifactPreviewBody({
super.key,
required this.plan,
required this.loading,
required this.markdownBuilder,
this.text,
this.bytes,
this.error,
});
final ArtifactPreviewPlan plan;
final bool loading;
final ArtifactMarkdownBuilder markdownBuilder;
final String? text;
final Uint8List? bytes;
final String? error;
@override
Widget build(BuildContext context) {
if (plan.kind == ArtifactPreviewKind.unavailable ||
plan.kind == ArtifactPreviewKind.unsupported) {
return _Message(plan.message);
}
if (loading) {
return const _Loading();
}
if (error != null) {
return _Message(error!);
}
switch (plan.kind) {
case ArtifactPreviewKind.image:
final data = bytes;
if (data == null) return const _Message('The image is empty.');
return Center(
child: Image.memory(
data,
fit: BoxFit.contain,
errorBuilder: (_, _, _) =>
const _Message('The image could not be decoded.'),
),
);
case ArtifactPreviewKind.text:
return _ScrollingText(child: SelectableText(text ?? ''));
case ArtifactPreviewKind.markdown:
return _ScrollingText(child: markdownBuilder(text ?? ''));
case ArtifactPreviewKind.unsupported:
case ArtifactPreviewKind.unavailable:
return const SizedBox.shrink();
}
}
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(),
const SizedBox(height: 12),
Text(
'Loading preview…',
style: Theme.of(context).textTheme.bodyMedium,
),
],
),
);
}
}
class _ScrollingText extends StatelessWidget {
const _ScrollingText({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 16),
child: child,
);
}
}
class _Message extends StatelessWidget {
const _Message(this.message);
final String message;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(16),
child: Text(message, textAlign: TextAlign.center),
),
);
}
}
@@ -0,0 +1,35 @@
import 'dart:typed_data';
import 'artifact_viewer_fetch_stub.dart'
if (dart.library.js_interop) 'artifact_viewer_fetch_web.dart'
as impl;
/// One artifact fetch result: the status the server answered and the bytes.
class ArtifactFetchResult {
const ArtifactFetchResult({required this.status, required this.bytes});
final int status;
final Uint8List bytes;
bool get ok => status >= 200 && status < 300;
}
/// A fetch that did not reach an HTTP response (network, TLS, blocked, ...).
class ArtifactFetchException implements Exception {
const ArtifactFetchException(this.message);
final String message;
@override
String toString() => message;
}
/// Fetches an already resolved same-origin artifact.
///
/// The viewer only calls this for [planArtifactPreview]'s safe local urls; the
/// platform implementation sends no credentials to a different origin.
typedef ArtifactFetch = Future<ArtifactFetchResult> Function(Uri uri);
/// The host fetch used when a caller does not inject one. Web uses `fetch` with
/// same-origin credentials; native uses an HttpClient with no stored cookies.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) => impl.fetchArtifact(uri);
@@ -0,0 +1,29 @@
import 'dart:io';
import 'dart:typed_data';
import 'artifact_viewer_fetch.dart';
/// Native fetch for an already resolved same-origin artifact.
///
/// No cookie jar, authorization header or userinfo is attached, redirects are
/// not followed across origins, and the caller only passes safe local urls.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) async {
final client = HttpClient()..connectionTimeout = const Duration(seconds: 15);
try {
final request = await client.getUrl(uri);
request.followRedirects = false;
final response = await request.close();
final bytes = BytesBuilder(copy: false);
await for (final chunk in response) {
bytes.add(chunk);
}
return ArtifactFetchResult(
status: response.statusCode,
bytes: bytes.takeBytes(),
);
} on IOException catch (error) {
throw ArtifactFetchException('$error');
} finally {
client.close(force: true);
}
}
@@ -0,0 +1,37 @@
import 'dart:js_interop';
import 'artifact_viewer_fetch.dart';
@JS('fetch')
external JSPromise<_FetchResponse> _fetch(JSString input, _FetchInit init);
extension type _FetchInit._(JSObject _) implements JSObject {
external factory _FetchInit({JSString credentials});
}
extension type _FetchResponse._(JSObject _) implements JSObject {
external int get status;
external JSPromise<JSArrayBuffer> arrayBuffer();
}
/// Web fetch for an already resolved same-origin artifact.
///
/// `credentials: 'same-origin'` attaches the browser's credentials only to this
/// server's origin; the viewer never asks for another origin. The status is
/// returned verbatim so a failed preview can report the HTTP failure.
Future<ArtifactFetchResult> fetchArtifact(Uri uri) async {
try {
final response = await _fetch(
uri.toString().toJS,
_FetchInit(credentials: 'same-origin'.toJS),
).toDart;
final buffer = await response.arrayBuffer().toDart;
return ArtifactFetchResult(
status: response.status,
bytes: buffer.toDart.asUint8List(),
);
} catch (error) {
throw ArtifactFetchException('$error');
}
}
@@ -0,0 +1,250 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_preview.dart';
import '../domain/artifact_url.dart';
import '../domain/gallery_navigation.dart';
import 'artifact_external_open.dart';
import 'artifact_viewer_body.dart';
import 'artifact_viewer_content.dart';
import 'artifact_viewer_fetch.dart';
import 'artifact_visit_list.dart';
/// The full-screen viewer's title, matching the web client's wording.
const String artifactViewerTitle = 'Artifact viewer';
/// One artifact of a recorded visit, previewed in-app.
///
/// Images are drawn from bytes fetched from the already-resolved safe url, a
/// `text/plain` artifact is selectable text, and a `.md`/`.markdown` or
/// `text/markdown` artifact is handed to [markdownBuilder]. The selected page
/// keeps its recorded facts visible and offers the existing external Open and
/// Copy link actions. Previous/Next walk the same filtered list the gallery
/// draws and stop at both ends; closing returns to the gallery row.
///
/// Nothing is ever drawn for an external, unsafe or unsupported url: the viewer
/// reports the exact state instead. External urls are never fetched.
class ArtifactViewerPage extends StatefulWidget {
const ArtifactViewerPage({
super.key,
required this.groups,
required this.selectedIdentity,
this.configuredEndpoint = '',
this.fetch = fetchArtifact,
this.markdownBuilder = defaultArtifactMarkdown,
this.openExternal = openArtifactExternally,
});
final List<ArtifactGroup> groups;
/// [artifactVisitIdentityOf] of the row the operator selected.
final String selectedIdentity;
final String configuredEndpoint;
final ArtifactFetch fetch;
final ArtifactMarkdownBuilder markdownBuilder;
final ArtifactExternalOpen openExternal;
@override
State<ArtifactViewerPage> createState() => _ArtifactViewerPageState();
}
class _FetchedPreview {
const _FetchedPreview({this.text, this.bytes});
final String? text;
final Uint8List? bytes;
}
class _ArtifactViewerPageState extends State<ArtifactViewerPage> {
late final List<PagedArtifact> _pages = pagedArtifacts(widget.groups);
final Map<String, _FetchedPreview> _cache = <String, _FetchedPreview>{};
late int _index = _initialIndex();
int _generation = 0;
bool _loading = false;
String? _error;
_FetchedPreview? _fetched;
String? _status;
int _initialIndex() {
final found = _pages.indexWhere(
(page) =>
artifactVisitIdentityOf(page.group, page.artifact) ==
widget.selectedIdentity,
);
return found < 0 ? 0 : found;
}
PagedArtifact? get _page => _index < _pages.length ? _pages[_index] : null;
ArtifactPreviewPlan? get _plan {
final page = _page;
if (page == null) return null;
return planArtifactPreview(
artifact: page.artifact,
configuredEndpoint: widget.configuredEndpoint,
);
}
@override
void initState() {
super.initState();
_beginLoad(initial: true);
}
void _beginLoad({bool initial = false}) {
final generation = ++_generation;
final plan = _plan;
if (plan == null || !plan.canFetch) {
void clear() {
_loading = false;
_error = null;
_fetched = null;
}
if (initial) {
clear();
} else {
setState(clear);
}
return;
}
final key = plan.resolved!.url;
final cached = _cache[key];
if (cached != null) {
void apply() {
_loading = false;
_error = null;
_fetched = cached;
}
if (initial) {
apply();
} else {
setState(apply);
}
return;
}
void start() {
_loading = true;
_error = null;
_fetched = null;
}
if (initial) {
start();
} else {
setState(start);
}
widget
.fetch(plan.resolved!.uri)
.then(
(result) {
if (!mounted || generation != _generation) return;
if (!result.ok) {
setState(() {
_loading = false;
_error = 'The server answered ${result.status}.';
});
return;
}
final fetched = _decode(plan.kind, result.bytes);
_cache[key] = fetched;
setState(() {
_loading = false;
_fetched = fetched;
});
},
onError: (Object error) {
if (!mounted || generation != _generation) return;
setState(() {
_loading = false;
_error = 'Could not load preview: $error';
});
},
);
}
static _FetchedPreview _decode(ArtifactPreviewKind kind, Uint8List bytes) {
if (kind == ArtifactPreviewKind.image) {
return _FetchedPreview(bytes: bytes);
}
return _FetchedPreview(text: utf8.decode(bytes, allowMalformed: true));
}
void _step(int delta) {
final next = pagedIndex(_index, delta, _pages.length);
if (next == _index) return;
setState(() {
_index = next;
_status = null;
});
_beginLoad();
}
Future<void> _open(ResolvedArtifactUrl resolved) async {
final opened = await widget.openExternal(resolved.uri);
if (!mounted) return;
setState(
() =>
_status = opened ? 'Link opened externally.' : 'Could not open link.',
);
}
Future<void> _copy(ResolvedArtifactUrl resolved) async {
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);
}
@override
Widget build(BuildContext context) {
final page = _page;
final plan = _plan;
final title = page == null
? artifactViewerTitle
: artifactDisplayName(page.artifact);
final body = page == null || plan == null
? const Center(child: Text('No previewable artifacts recorded.'))
: ArtifactViewerBody(
page: page,
plan: plan,
index: _index,
count: _pages.length,
loading: _loading,
markdownBuilder: widget.markdownBuilder,
text: _fetched?.text,
bytes: _fetched?.bytes,
error: _error,
status: _status,
onPrevious: () => _step(-1),
onNext: () => _step(1),
onOpen: plan.resolved == null ? () {} : () => _open(plan.resolved!),
onCopy: plan.resolved == null ? () {} : () => _copy(plan.resolved!),
);
if (usesCupertinoHost(context)) {
return CupertinoPageScaffold(
backgroundColor: CupertinoColors.systemGroupedBackground,
navigationBar: CupertinoNavigationBar(
middle: Text(title, overflow: TextOverflow.ellipsis),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(title: Text(title, overflow: TextOverflow.ellipsis)),
body: SafeArea(top: false, child: body),
);
}
}
@@ -5,6 +5,7 @@ import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.dart';
import '../domain/gallery_navigation.dart';
/// A selection callback carrying the recorded group and the exact record the
/// operator chose, so the visit is never lost when two groups share a name.
@@ -17,9 +18,26 @@ typedef ArtifactSelected =
/// The recorded stage visit is part of the key, so two visits that both
/// recorded `result.csv` stay distinct even when their urls are identical.
/// A filename alone is never an identity.
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) {
final recorded = artifact.hasUrl ? artifact.url : artifact.name;
return '${group.stageKey}\u0000${group.visit}\u0000$recorded';
String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) =>
artifactVisitIdentityOf(group, artifact);
/// The recorded group heading, matching the web client's group vocabulary.
String artifactGroupLabel(ArtifactGroup group) =>
'${group.stageKey} · visit ${group.visit}';
/// The displayed artifact name: a missing server name stays explicit.
String artifactDisplayName(ArtifactRecord artifact) =>
artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name;
/// The recorded MIME and byte size, never inferred from the name.
///
/// The value and its unit are joined by a non-breaking space so a narrow row
/// never wraps `120.6` away from `KiB`.
String artifactFactsLabel(ArtifactRecord artifact) {
final type = artifact.contentType.split(';').first.trim();
final mime = type.isEmpty ? 'type not recorded' : type;
final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0');
return '$mime · $size';
}
/// A read-only, selectable list of recorded artifact groups.
@@ -60,7 +78,7 @@ class ArtifactVisitList extends StatelessWidget {
header: Semantics(
container: true,
header: true,
child: Text(_groupLabel(group)),
child: Text(artifactGroupLabel(group)),
),
hasLeading: false,
children: [
@@ -85,7 +103,7 @@ class ArtifactVisitList extends StatelessWidget {
child: Semantics(
container: true,
header: true,
child: Text(_groupLabel(group)),
child: Text(artifactGroupLabel(group)),
),
),
for (var index = 0; index < group.artifacts.length; index += 1)
@@ -108,25 +126,6 @@ class ArtifactVisitList extends StatelessWidget {
ValueKey<String>('${artifactVisitIdentity(group, artifact)}\u0000$index');
}
/// The recorded group heading, matching the web client's group vocabulary.
String _groupLabel(ArtifactGroup group) =>
'${group.stageKey} · visit ${group.visit}';
/// The displayed artifact name: a missing server name stays explicit.
String _displayName(ArtifactRecord artifact) =>
artifact.name.isEmpty ? '(unnamed artifact)' : artifact.name;
/// The recorded MIME and byte size, never inferred from the name.
///
/// The value and its unit are joined by a non-breaking space so a narrow row
/// never wraps `120.6` away from `KiB`.
String _facts(ArtifactRecord artifact) {
final type = artifact.contentType.split(';').first.trim();
final mime = type.isEmpty ? 'type not recorded' : type;
final size = humanBytes(artifact.sizeBytes).replaceFirst(' ', '\u00a0');
return '$mime · $size';
}
class _MaterialRow extends StatelessWidget {
const _MaterialRow({
super.key,
@@ -145,8 +144,8 @@ class _MaterialRow extends StatelessWidget {
Widget build(BuildContext context) {
return ListTile(
selected: selected,
title: Text(_displayName(artifact)),
subtitle: Text(_facts(artifact)),
title: Text(artifactDisplayName(artifact)),
subtitle: Text(artifactFactsLabel(artifact)),
trailing: selected ? const Icon(Icons.check) : null,
onTap: onSelected == null ? null : () => onSelected!(group, artifact),
);
@@ -181,8 +180,8 @@ class _CupertinoRow extends StatelessWidget {
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_displayName(artifact)),
Text(_facts(artifact), style: factsStyle),
Text(artifactDisplayName(artifact)),
Text(artifactFactsLabel(artifact), style: factsStyle),
],
),
),
@@ -0,0 +1,246 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
/// The two things the attention surface ranks, most important first. The rank
/// orders the list; the wire name is what a dismissal identity is keyed by.
///
/// This mirrors the browser's pure `web/src/attention.js` model: only a run
/// parked on a person ([AttentionKind.decision]) and a failed run
/// ([AttentionKind.failed]) need the operator. A waiting run that is really an
/// audit/export handoff asks nobody, so it is excluded by [attentionKindForRun].
enum AttentionKind {
decision(0, 'Decision'),
failed(1, 'Failed');
const AttentionKind(this.rank, this.wireName);
final int rank;
/// The spelling used in a persisted `{runId}:{kind}` identity.
final String wireName;
}
/// This client's own storage key, namespaced like the rest of the app
/// (`pipelines.next.*`). The identity format matches the browser's, but a
/// dismissal set is deliberately not shared with the legacy web app: the two
/// clients must never rewrite each other's local state on a shared origin.
const attentionStorageKey = 'pipelines.next.attention.v1';
/// The run id a summary or pushed frame carries, or null when it is malformed.
/// The server ids are positive integers; anything else cannot identify an entry.
int? attentionRunId(dynamic value) {
final id = value is num
? (value.isFinite ? value.toInt() : null)
: int.tryParse('${value ?? ''}'.trim());
return id != null && id > 0 ? id : null;
}
/// The attention kind a server status word maps to. Only the server's own
/// `waiting` and `failed` words qualify; queued, running, succeeded, canceled,
/// interrupted and unknown words ask nobody. A waiting run's *reason* is
/// checked by [attentionKindForRun], because the status word alone cannot tell a
/// human decision from an export handoff.
AttentionKind? attentionKindOf(dynamic status) {
switch (_word(status)) {
case 'waiting':
return AttentionKind.decision;
case 'failed':
return AttentionKind.failed;
default:
return null;
}
}
/// The attention kind a complete run summary maps to, or null when it asks
/// nobody.
///
/// A `waiting` run is listed only when it is actually waiting on a person. It is
/// not a Decision when the server recorded a session audit/export handoff
/// (`export_pending_sequence > 0`), so a machine export wait never reaches the
/// operator's "Needs you" list.
///
/// `resource_wait` is deliberately not consulted, matching `web/src/attention.js`
/// and the Android client: it was retired server-side, and a stale value carried
/// onto a waiting run must not hide a genuine human decision.
AttentionKind? attentionKindForRun(JsonMap run) {
final kind = attentionKindOf(run['status']);
if (kind != AttentionKind.decision) return kind;
if (_positive(run['export_pending_sequence'])) return null;
return kind;
}
/// The identity of one run+kind entry; the unit an explicit dismissal removes.
String attentionKey(int runId, AttentionKind kind) => '$runId:${kind.wireName}';
/// What one entry asks of the operator, in the operator's words. A failed run
/// shows the server's own diagnostic when it recorded one.
String attentionDetail(AttentionKind kind, JsonMap run) {
if (kind == AttentionKind.decision) return 'Waiting for your decision';
final diagnostic = '${run['diagnostic'] ?? ''}'.trim();
return diagnostic.isNotEmpty ? diagnostic : 'Run failed';
}
/// The one-line secondary text for a row: `{pipeline} · {detail}`.
String attentionRowDescription(AttentionEntry entry) =>
'${entry.pipeline} · ${entry.detail}';
/// The bell action's accessible name: the bare `Notifications` when nothing
/// needs the operator, else the count.
String attentionBadgeLabel(int count) =>
count > 0 ? 'Notifications, $count needing attention' : 'Notifications';
/// One run that needs the operator.
///
/// The original summary map is kept whole, so fields this model does not read —
/// or fields a newer server adds — remain available to the caller unchanged.
/// Only [attentionEntryFor] constructs an entry, so [runId] is always a validated
/// positive server id rather than a getter that could throw.
class AttentionEntry {
const AttentionEntry._({
required this.run,
required this.kind,
required this.runId,
});
final JsonMap run;
final AttentionKind kind;
final int runId;
String get pipeline => '${run['name'] ?? ''}';
String get detail => attentionDetail(kind, run);
String get key => attentionKey(runId, kind);
/// The trimmed title else the pipeline label.
String get label {
final title = '${run['title'] ?? ''}'.trim();
return title.isNotEmpty ? title : pipeline;
}
/// The run's own recency, used only for ordering equal kinds newest-first.
/// A finished run is ordered by `finished_at`; a still-waiting one by its
/// creation time.
String get recency {
final finished = '${run['finished_at'] ?? ''}';
return finished.trim().isNotEmpty ? finished : '${run['created_at'] ?? ''}';
}
}
/// The entry for one qualifying run, or null when it asks nobody.
AttentionEntry? attentionEntryFor(JsonMap run) {
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
final kind = attentionKindForRun(run);
if (runId == null || kind == null) return null;
return AttentionEntry._(run: run, kind: kind, runId: runId);
}
/// The start of the operator's local day. "Needs you" is a to-do list for what
/// changed now, so callers pass this as [attentionEntries]' `since`; yesterday's
/// failures are history, not a badge that follows every device for ever. Inject
/// [now] for a deterministic test; production callers pass nothing.
DateTime startOfLocalDay({DateTime? now}) {
final local = (now ?? DateTime.now()).toLocal();
return DateTime(local.year, local.month, local.day);
}
/// The ordered attention list: one entry per qualifying run, minus any identity
/// the operator explicitly dismissed and minus work older than [since].
///
/// Order matches the browser: kind rank (Decision before Failed), then recency
/// descending (the server's timestamp text, `finished_at` else `created_at`),
/// then run id descending so equal rows never reshuffle between reads.
///
/// [since] is the local-day cutoff ([startOfLocalDay]) the bell, the sheet and
/// Clear all pass. As in `web/src/attention.js`, the cutoff applies only when the
/// entry's recency parses as a timestamp; a blank or unreadable recency is kept.
/// A null or epoch-zero cutoff shows everything.
List<AttentionEntry> attentionEntries(
Iterable<JsonMap>? runs, {
Set<String> dismissed = const {},
DateTime? since,
}) {
final entries = <AttentionEntry>[];
for (final run in runs ?? const <JsonMap>[]) {
final entry = attentionEntryFor(run);
if (entry == null || dismissed.contains(entry.key)) continue;
if (since != null &&
since.millisecondsSinceEpoch > 0 &&
_before(entry.recency, since)) {
continue;
}
entries.add(entry);
}
entries.sort((a, b) {
final rank = a.kind.rank.compareTo(b.kind.rank);
if (rank != 0) return rank;
final recency = b.recency.compareTo(a.recency);
return recency != 0 ? recency : b.runId.compareTo(a.runId);
});
return entries;
}
/// Captures what the surface showed when it opened. Clear all acts on this
/// snapshot, so an entry that arrives later is not silently removed.
List<AttentionEntry> attentionDismissalSnapshot(
Iterable<AttentionEntry> entries,
) => List<AttentionEntry>.unmodifiable(entries);
/// Adds one identity, ignoring a blank or already-present key.
Set<String> attentionDismiss(Set<String> dismissed, String key) {
final next = {...dismissed};
if (key.trim().isNotEmpty) next.add(key);
return next;
}
/// Unions exactly the snapshot's identities. Entries that arrived after the
/// snapshot was taken are left alone.
Set<String> attentionDismissAll(
Set<String> dismissed,
Iterable<AttentionEntry> snapshot,
) {
final next = {...dismissed};
for (final entry in snapshot) {
next.add(entry.key);
}
return next;
}
/// The one-line JSON a dismissed set is stored as: a sorted array of strings, so
/// an unchanged set always encodes to the same bytes.
String encodeAttentionDismissals(Set<String> dismissed) {
final keys = dismissed.where((key) => key.isNotEmpty).toList()..sort();
return jsonEncode(keys);
}
/// Decodes a stored value into a dismissed set. Total: blank text, unreadable
/// JSON, a non-array value and non-string members all decode to the members we
/// can read, and a malformed value never throws.
Set<String> decodeAttentionDismissals(String? stored) {
final text = (stored ?? '').trim();
if (text.isEmpty) return <String>{};
dynamic parsed;
try {
parsed = jsonDecode(text);
} catch (_) {
return <String>{};
}
if (parsed is! List) return <String>{};
return {
for (final value in parsed)
if (value is String && value.isNotEmpty) value,
};
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
bool _positive(dynamic value) {
final number = value is num ? value : num.tryParse('${value ?? ''}'.trim());
return (number ?? 0) > 0;
}
/// True only when [recency] is a readable timestamp before [cutoff]. An
/// unparseable or blank timestamp is not filtered out, matching the browser.
bool _before(String recency, DateTime cutoff) {
final at = DateTime.tryParse(recency.trim());
return at != null && at.isBefore(cutoff);
}
@@ -0,0 +1,136 @@
import '../../../core/api_gateway.dart';
import 'attention_models.dart';
/// One newly-entered attention state: a run that has just become failed or has
/// just become a human decision. The entry carries the whole current summary, so
/// its wording and unknown fields match what the surface would show.
class AttentionTransition {
const AttentionTransition(this.entry);
final AttentionEntry entry;
int get runId => entry.runId;
AttentionKind get kind => entry.kind;
String get key => entry.key;
JsonMap get run => entry.run;
}
/// Tracks the last status seen for each run and emits only a genuine transition
/// *into* a qualifying state.
///
/// - [seed] records the authoritative list (the initial `list_runs` read or a
/// `subscribe` snapshot) without emitting anything, so a run that was already
/// failed/waiting before this client looked never announces itself.
/// - [beginSeed]/[endSeed] bracket a reconnect's pushed snapshot: frames seen
/// while seeding update the baseline but raise nothing, so a gap can never
/// manufacture a transition.
/// - [observe] emits only when a known run's status changes into `failed` or a
/// human `waiting`. A duplicate frame, an unchanged qualifying state, an
/// unknown/nonqualifying status and a first-seen run all return null.
/// - A run+kind key is forgotten when the run leaves that qualifying state (or
/// enters the other kind), so a genuinely new transition can fire once more;
/// the same transition can never repeat.
/// - [resetForReconnect] drops the status baseline but keeps the emitted keys.
/// The following [reseed] establishes the new baseline without emitting, so a
/// disconnect cannot produce a delayed notification for a state the operator
/// already saw.
class AttentionTransitionDetector {
final Map<int, String> _lastStatus = {};
final Set<String> _emitted = {};
bool _seeding = false;
/// Records [runs] as the baseline without emitting. Keys that still qualify
/// are kept so a reconnect cannot repeat them; keys whose run disappeared from
/// the read are kept too, because an absent run tells us nothing.
void seed(Iterable<JsonMap>? runs) {
final statuses = <int, String>{};
final kinds = <int, AttentionKind?>{};
for (final run in runs ?? const <JsonMap>[]) {
final runId = attentionRunId(run['run_id']) ?? attentionRunId(run['id']);
if (runId == null) continue;
statuses[runId] = _word(run['status']);
kinds[runId] = attentionKindForRun(run);
}
_lastStatus
..clear()
..addAll(statuses);
for (final key in [..._emitted]) {
final split = key.lastIndexOf(':');
if (split <= 0) continue;
final runId = attentionRunId(key.substring(0, split));
if (runId == null || !statuses.containsKey(runId)) continue;
final kind = kinds[runId];
if (kind == null || key != attentionKey(runId, kind)) {
_emitted.remove(key);
}
}
}
/// Replaces the baseline for a reconnect. Emitted keys survive: a transition
/// swallowed by the gap is not replayed after the socket returns.
void reseed(Iterable<JsonMap>? runs) {
_lastStatus.clear();
_seeding = false;
seed(runs);
}
/// Drops the status baseline but keeps this session's emitted keys. Call
/// before the next [seed] when the connection is lost.
void resetForReconnect() {
_lastStatus.clear();
_seeding = false;
}
void beginSeed() => _seeding = true;
void endSeed() => _seeding = false;
/// Observes one pushed `run_event` summary/frame. Returns the transition only
/// when this run enters a qualifying state; [dismissed] identities are marked
/// seen but do not emit.
AttentionTransition? observe(
JsonMap frame, {
Set<String> dismissed = const {},
}) {
final runId =
attentionRunId(frame['run_id']) ?? attentionRunId(frame['id']);
final status = _word(frame['status']);
if (runId == null || status.isEmpty) return null;
final previous = _lastStatus[runId];
_lastStatus[runId] = status;
final kind = attentionKindForRun(frame);
if (kind == null) {
_forget(runId);
return null;
}
for (final other in AttentionKind.values) {
if (other != kind) _emitted.remove(attentionKey(runId, other));
}
if (_seeding) return null;
final key = attentionKey(runId, kind);
if (previous == null || previous == status) return null;
final entry = attentionEntryFor(frame);
if (entry == null) return null;
_emitted.add(key);
if (dismissed.contains(key)) return null;
return AttentionTransition(entry);
}
/// A copy of the run+kind identities raised in this session.
Set<String> get emittedKeys => {..._emitted};
/// The last status recorded for [runId], or null for a run never seen.
String? statusOf(int runId) => _lastStatus[runId];
void _forget(int runId) {
for (final kind in AttentionKind.values) {
_emitted.remove(attentionKey(runId, kind));
}
}
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
@@ -0,0 +1,73 @@
import '../../../core/api_gateway.dart';
/// Stable widget-key strings for transcript rows while history grows at both
/// ends.
///
/// A folded assistant turn has no stable message boundary: `Load older` can
/// prepend messages into the turn (changing its first id) and a live frame can
/// append a message (changing its last id). Deriving the row key from either
/// boundary remounts the row and resets every native disclosure in it, which
/// moved an open reasoning block to another answer or closed it.
///
/// So the first sighting of a turn assigns a synthetic key, and later calls
/// carry that key forward while the turn still contains any message it held
/// before. Rows without a message id fall back to their position: they have no
/// identity that survives a prepend.
class ChatRowKeys {
final Map<String, String> _byMessageId = {};
int _serial = 0;
/// One key per row, in row order. Call once per build.
List<String> forRows(List<JsonMap> rows) {
final nextByMessageId = <String, String>{};
final used = <String>{};
final keys = <String>[];
for (var index = 0; index < rows.length; index++) {
final row = rows[index];
final kind = '${row['kind'] ?? ''}';
final ids = _messageIds(row);
String? key;
for (final id in ids) {
final held = _byMessageId[id];
if (held != null) {
key = held;
break;
}
}
if (key == null) {
// A row with no id has no identity that survives a prepend, so it
// follows its position, as a plain indexed list would. Every other new
// row gets a key no older row can generate.
key = ids.isEmpty
? 'chat-row-$kind-index-$index'
: 'chat-row-$kind-${_serial++}';
used.add(key);
} else if (!used.add(key)) {
// Defensive: a held key is only reused once even if input unexpectedly
// splits one turn into two rows; duplicate widget keys would throw.
key = 'chat-row-$kind-${_serial++}';
used.add(key);
}
keys.add(key);
for (final id in ids) {
nextByMessageId[id] = key;
}
}
_byMessageId
..clear()
..addAll(nextByMessageId);
return keys;
}
static List<String> _messageIds(JsonMap row) {
final listed = row['messageIds'];
if (listed is List) {
return listed
.map((id) => '$id'.trim())
.where((id) => id.isNotEmpty)
.toList();
}
final key = '${row['key'] ?? ''}'.trim();
return key.isEmpty ? const [] : [key];
}
}
@@ -0,0 +1,195 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/chat_transcript.dart';
import '../ui/sessions/chat_adaptive.dart';
import '../ui/transcript/chat_message_view.dart';
import 'chat_row_keys.dart';
import 'chat_thread_controller.dart';
/// One read-only conversation: the controller's transcript in the order the
/// server reports it, rendered by the existing [ChatMessageView].
///
/// History and live-subscription failures are separate notices: readable stored
/// history must never hide a refused live watch. The shell owns the navigation
/// bar, so this view adds only its own Back control and content.
class ChatThreadView extends StatefulWidget {
const ChatThreadView({
super.key,
required this.gateway,
required this.sessionId,
required this.onBack,
this.title = '',
this.syncToken = 0,
});
final ApiGateway gateway;
final String sessionId;
final VoidCallback onBack;
/// The list row's title when this visit knows it; a deep link may not.
final String title;
/// Advances when the shared socket is replaced, keeping this selection.
final int syncToken;
@override
State<ChatThreadView> createState() => _ChatThreadViewState();
}
class _ChatThreadViewState extends State<ChatThreadView> {
late ChatThreadController _controller = _attach();
late ChatRowKeys _rowKeys = ChatRowKeys();
ChatThreadController _attach() =>
ChatThreadController(widget.gateway, widget.sessionId)..load();
@override
void didUpdateWidget(covariant ChatThreadView oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway ||
oldWidget.sessionId != widget.sessionId) {
_controller.dispose();
_controller = _attach();
_rowKeys = ChatRowKeys();
} else if (oldWidget.syncToken != widget.syncToken) {
unawaited(_controller.resync());
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final rows = transcriptRows(_controller.messages);
// Older pages prepend messages and a live frame can append one, so a
// folded assistant turn's first message id is not a stable identity.
// ChatRowKeys carries a turn's key forward while it still holds any of
// its previous messages, keeping the element (and its open disclosures)
// across paging and streaming.
final keys = _rowKeys.forRows(rows);
final initialLoad = !_controller.loaded && _controller.loading;
return ListView(
key: ValueKey<String>('chat-thread-${widget.sessionId}'),
padding: const EdgeInsets.symmetric(vertical: 8),
children: [
Padding(
key: const Key('chat-thread-header'),
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 16, 4),
child: Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
_backButton(cupertino),
if (widget.title.trim().isNotEmpty)
Text(
widget.title.trim(),
style: cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleLarge,
),
],
),
),
if (initialLoad)
Padding(
key: const Key('chat-thread-loading'),
padding: const EdgeInsets.all(16),
child: Center(
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
),
),
if (_controller.hasMore)
Padding(
key: const Key('chat-load-older'),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
)
: TextButton(
onPressed: _controller.loading
? null
: _controller.loadOlder,
child: const Text('Load older'),
),
),
),
if (_controller.error != null)
ChatErrorNotice(
key: const Key('chat-history-error'),
message: 'Chat history unavailable\n${_controller.error}',
onRetry: _controller.load,
),
if (_controller.subscriptionError != null)
ChatErrorNotice(
key: const Key('chat-live-error'),
message:
'Live updates unavailable\n${_controller.subscriptionError}',
onRetry: _controller.resync,
),
if (_controller.loaded && rows.isEmpty && _controller.error == null)
const Padding(
key: Key('chat-thread-empty'),
padding: EdgeInsets.all(16),
child: Text('No messages in this chat yet.'),
),
for (var index = 0; index < rows.length; index++)
Padding(
key: ValueKey<String>(keys[index]),
padding: const EdgeInsets.symmetric(horizontal: 16),
child: ChatMessageView(row: rows[index]),
),
if (_controller.running)
Padding(
key: const Key('chat-running'),
padding: const EdgeInsets.all(16),
child: Semantics(
liveRegion: true,
child: const Text('Assistant is responding…'),
),
),
],
);
},
);
Widget _backButton(bool cupertino) => cupertino
? CupertinoButton(
padding: const EdgeInsetsDirectional.fromSTEB(8, 0, 8, 0),
onPressed: widget.onBack,
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(CupertinoIcons.back),
SizedBox(width: 4),
Text('Back'),
],
),
)
: TextButton.icon(
onPressed: widget.onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to chats'),
);
}
@@ -34,25 +34,36 @@ JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
/// Consecutive assistant messages form one answer turn. All part fields (also
/// future/unknown protocol types) are preserved in original order.
///
/// `key` is the turn's first assistant message id, which is only a display
/// anchor: paging an older assistant message into the turn changes it, so widget
/// identity uses `messageIds`. That list carries every message the folded turn
/// currently holds so the view can keep the same row element while the turn
/// grows at either end.
List<JsonMap> transcriptRows(List<JsonMap> messages) {
final rows = <JsonMap>[];
String? key;
final ids = <String>[];
final parts = <JsonMap>[];
void flush() {
if (key != null && parts.isNotEmpty) {
rows.add({
'kind': 'assistant',
'key': key,
'messageIds': List<String>.of(ids),
'parts': List<JsonMap>.of(parts),
});
}
key = null;
ids.clear();
parts.clear();
}
for (final message in messages) {
if (message['role'] == 'assistant') {
key ??= '${message['id'] ?? ''}';
final id = '${message['id'] ?? ''}'.trim();
key ??= id;
if (id.isNotEmpty) ids.add(id);
for (final part in (message['parts'] as List? ?? const [])) {
if (part is Map) parts.add(Map<String, dynamic>.from(part));
}
+99
View File
@@ -0,0 +1,99 @@
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'conversation/chat_thread_view.dart';
import 'ui/sessions/chat_sessions_screen.dart';
/// The Chat destination's list/detail switch.
///
/// The route names the open session, so a row tap, a deep link and Back all
/// navigate through the same value. The session list stays mounted (offstage)
/// while a conversation is open, so returning to it keeps its rows and query.
/// The shell owns the app bar; this screen adds no second one.
class ChatScreen extends StatefulWidget {
const ChatScreen({
super.key,
required this.gateway,
this.initialSessionId,
this.syncToken = 0,
this.onSessionSelected,
this.onBack,
});
final ApiGateway gateway;
/// The chat session the current route names, or null for the list.
final String? initialSessionId;
/// Advances when the shared socket is replaced. The open conversation
/// re-subscribes and re-reads in place, so its selection survives.
final int syncToken;
final ValueChanged<String>? onSessionSelected;
final VoidCallback? onBack;
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
/// Rows opened in this visit, used only for the native title. A deep link has
/// no title until the list loads, and this screen waits for no list request.
final Map<String, String> _titles = {};
String? _standaloneSelection;
String? get _selected {
final routed = widget.initialSessionId;
if (routed != null && routed.isNotEmpty) return routed;
return _standaloneSelection;
}
void _open(JsonMap session) {
final id = '${session['id'] ?? ''}';
if (id.isEmpty) return;
final title = '${session['title'] ?? ''}'.trim();
if (title.isNotEmpty) _titles[id] = title;
final select = widget.onSessionSelected;
if (select != null) {
select(id);
} else {
setState(() => _standaloneSelection = id);
}
}
void _back() {
final back = widget.onBack;
if (back != null) {
back();
} else {
setState(() => _standaloneSelection = null);
}
}
@override
Widget build(BuildContext context) {
final selected = _selected;
return Stack(
children: [
Offstage(
offstage: selected != null,
child: ChatSessionsScreen(
gateway: widget.gateway,
embedded: true,
syncToken: widget.syncToken,
onOpen: _open,
),
),
if (selected != null)
ChatThreadView(
key: ValueKey<String>('chat-session-$selected'),
gateway: widget.gateway,
sessionId: selected,
title: _titles[selected] ?? '',
syncToken: widget.syncToken,
onBack: _back,
),
],
);
}
}
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
@@ -16,10 +18,19 @@ class ChatSessionsScreen extends StatefulWidget {
super.key,
required this.gateway,
required this.onOpen,
this.embedded = false,
this.syncToken = 0,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
/// True under the application shell, which owns the single navigation bar.
final bool embedded;
/// Advances when the shared socket is replaced; sessions created, renamed or
/// closed elsewhere during the gap must not stay invisible until Refresh.
final int syncToken;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
@@ -35,6 +46,8 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.replaceRepository(ChatRepository(widget.gateway));
} else if (oldWidget.syncToken != widget.syncToken) {
unawaited(_controller.refresh());
}
}
@@ -115,53 +128,38 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
],
);
if (widget.embedded) {
return Column(
children: [
Align(
alignment: AlignmentDirectional.centerEnd,
child: Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Row(
mainAxisSize: MainAxisSize.min,
children: _actions(),
),
),
),
Expanded(child: body),
],
);
}
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Chats'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
ChatBarAction(
key: const Key('chat-new-chat'),
label: 'New chat',
onPressed: _newChat,
materialIcon: Icons.add,
cupertinoIcon: CupertinoIcons.add,
),
ChatBarAction(
key: const Key('chat-refresh'),
label: 'Refresh',
onPressed: _controller.refresh,
materialIcon: Icons.refresh,
cupertinoIcon: CupertinoIcons.refresh,
),
],
children: _actions(),
),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Chats'),
actions: [
ChatBarAction(
key: const Key('chat-new-chat'),
label: 'New chat',
onPressed: _newChat,
materialIcon: Icons.add,
cupertinoIcon: CupertinoIcons.add,
),
ChatBarAction(
key: const Key('chat-refresh'),
label: 'Refresh',
onPressed: _controller.refresh,
materialIcon: Icons.refresh,
cupertinoIcon: CupertinoIcons.refresh,
),
],
),
appBar: AppBar(title: const Text('Chats'), actions: _actions()),
body: body,
floatingActionButton: FloatingActionButton.extended(
key: const Key('chat-new-chat-fab'),
@@ -173,4 +171,21 @@ class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
},
);
}
List<Widget> _actions() => [
ChatBarAction(
key: const Key('chat-new-chat'),
label: 'New chat',
onPressed: _newChat,
materialIcon: Icons.add,
cupertinoIcon: CupertinoIcons.add,
),
ChatBarAction(
key: const Key('chat-refresh'),
label: 'Refresh',
onPressed: _controller.refresh,
materialIcon: Icons.refresh,
cupertinoIcon: CupertinoIcons.refresh,
),
];
}
@@ -92,13 +92,34 @@ class ChatMessageView extends StatelessWidget {
List<Widget> _agentParts(BuildContext context) {
final widgets = <Widget>[];
for (final part in _partsOf(row)) {
final parts = _partsOf(row);
final seen = <String, int>{};
for (var index = 0; index < parts.length; index++) {
final part = parts[index];
final widget = _agentPart(context, part);
if (widget != null) widgets.add(widget);
if (widget == null) continue;
// Part identity, not position, so an older assistant message that folds
// into the same turn can prepend its parts without moving an open
// disclosure. The enclosing row's identity is carried by ChatRowKeys; a
// part with no server id still falls back to its position.
widgets.add(
KeyedSubtree(key: _partKey(part, index, seen), child: widget),
);
}
return widgets;
}
/// The server's part id when there is one, else this part's position. A
/// repeated identity gets an ordinal so two sibling keys never collide.
Key _partKey(JsonMap part, int index, Map<String, int> seen) {
final type = '${part['type'] ?? ''}';
final id = '${part['id'] ?? ''}'.trim();
final base = id.isEmpty ? 'index-$index' : '$type:$id';
final ordinal = (seen[base] ?? 0) + 1;
seen[base] = ordinal;
return ValueKey<String>('chat-part-$base-$ordinal');
}
/// One agent part, or null when a known part has nothing to draw. The web's
/// `partRendering` hides blank text/reasoning too, so a blank known part must
/// not fall through to the unknown-part disclosure.
@@ -0,0 +1,212 @@
import 'graph_definition.dart';
import 'graph_protocol.dart';
/// The read-only definition of one declared stage, as field rows.
///
/// Mirrors `stageDefinitionFields`/`terminalFields` from `web/src/graph.js`:
/// the same labels, the same order, and the same rule that blank fields are
/// omitted rather than shown as an empty row. Pure data only: nothing here
/// reads run visits, so a definition can be inspected without claiming that a
/// stage executed.
class StageDefinitionField {
const StageDefinitionField(this.label, this.value, {this.block = false});
final String label;
final String value;
/// Multi-line content (prompt, output, outcomes, tools, memory, routes).
final bool block;
}
/// The one stage declaration [key] names, or null when this version does not
/// declare it.
///
/// The last declaration wins, matching the web pane's `new Map(stages)`.
Map<String, dynamic>? stageDefinitionFor(dynamic graph, String key) {
final stages = graph is Map ? graph['stages'] : null;
if (stages is! List) return null;
Map<String, dynamic>? found;
for (final stage in stages) {
if (stage is Map && _text(stage['key']) == key) {
found = Map<String, dynamic>.from(stage);
}
}
return found;
}
/// A stage's effective type: a blank/absent type reads `model`, exactly as
/// `effectiveStageType` in `web/src/templates.js`.
String effectiveStageType(dynamic type) {
final text = _text(type);
return text.trim().isEmpty ? 'model' : text;
}
/// A config key's display label (`configLabel` in `web/src/graph.js`).
String stageConfigLabel(String key) {
switch (key) {
case 'provider':
return 'Provider';
case 'model':
return 'Model';
case 'retries':
return 'Retries';
case 'timeout':
return 'Timeout';
case 'budget_usd':
return 'Budget (USD)';
case 'budget_tokens':
return 'Budget (tokens)';
case 'harness':
return 'Harness';
default:
return key;
}
}
/// The definition fields of one stage declaration, in the web pane's order.
///
/// Only non-blank fields are emitted. Unknown keys are deliberately not
/// interpreted here; the pane keeps the stage's raw JSON so they stay visible.
List<StageDefinitionField> stageDefinitionFields(dynamic stage) {
if (stage is! Map) return const <StageDefinitionField>[];
final fields = <StageDefinitionField>[
StageDefinitionField('Type', effectiveStageType(stage['type'])),
];
final prompt = _text(stage['prompt']);
if (prompt.trim().isNotEmpty) {
fields.add(StageDefinitionField('Prompt', prompt, block: true));
}
final output = _text(stage['output']);
if (output.trim().isNotEmpty) {
fields.add(StageDefinitionField('Output', output, block: true));
}
final edges = stage['edges'];
final outcomes = <String>[];
for (final outcome in stageOutcomes(stage)) {
final raw = edges is Map ? edges[outcome] : null;
final target = resolveTarget(outcome, raw == null ? '' : _text(raw)) ?? '';
final suffix = isTerminalTarget(target) ? ' (terminal)' : '';
outcomes.add('$outcome \u2192 ${nodeLabel(target)}$suffix');
}
if (outcomes.isNotEmpty) {
fields.add(
StageDefinitionField('Outcomes', outcomes.join('\n'), block: true),
);
}
final configs = stage['configs'];
if (configs is Map) {
final entries = configs.entries.toList()
..sort((a, b) => _text(a.key).compareTo(_text(b.key)));
for (final entry in entries) {
final value = _text(entry.value);
if (entry.value == null || value.trim().isEmpty) continue;
fields.add(
StageDefinitionField(stageConfigLabel(_text(entry.key)), value),
);
}
}
final blocks = stage['blocks'];
if (blocks is Map) {
final tools = blocks['tools'];
final text = _text(tools);
if (tools != null && text.trim().isNotEmpty) {
fields.add(StageDefinitionField('Tools', text, block: true));
}
}
final limits = stage['limits'];
if (limits is Map) {
final maxVisits = limits['max_visits'];
final visits = maxVisits is num
? maxVisits
: num.tryParse(_text(maxVisits));
if (visits != null && visits > 0) {
fields.add(StageDefinitionField('Max visits', _text(maxVisits)));
}
final on = _items(limits['on']);
if (on.isNotEmpty) {
fields.add(StageDefinitionField('Limit on', on.join(', ')));
}
}
final memory = stage['memory'];
if (memory is Map && memory.isNotEmpty) {
fields.add(
StageDefinitionField(
'Memory',
[
for (final entry in memory.entries)
'${_text(entry.key)}: ${_text(entry.value)}',
].join('\n'),
block: true,
),
);
}
final notify = stage['notify'];
if (notify is Map) {
final on = _items(notify['on']);
if (on.isNotEmpty) {
fields.add(StageDefinitionField('Notify on', on.join(', ')));
}
final destination = _text(notify['destination']);
if (destination.trim().isNotEmpty) {
fields.add(StageDefinitionField('Notify destination', destination));
}
final artifacts = _items(notify['artifacts']);
if (artifacts.isNotEmpty) {
fields.add(
StageDefinitionField('Notify artifacts', artifacts.join(', ')),
);
}
}
return fields;
}
/// A terminal pane's fields: the declared routes into that target.
///
/// A terminal is part of the definition, not evidence that a run reached it.
List<StageDefinitionField> terminalDefinitionFields(dynamic graph, String key) {
final lines = <String>[
for (final edge in graphEdges(graph))
if (edge.target == key)
'${edge.source} \u00b7 ${edge.label} \u2192 ${nodeLabel(key)}',
];
return lines.isEmpty
? const <StageDefinitionField>[]
: <StageDefinitionField>[
StageDefinitionField(
'Incoming routes',
lines.join('\n'),
block: true,
),
];
}
List<String> _items(dynamic value) {
if (value is! List) return const <String>[];
return <String>[for (final item in value) _text(item)];
}
/// Web `String(value)` for the values the definition fields carry. Numbers
/// that are integral render without a trailing `.0`, as JavaScript does; a
/// complex value stays visible but its exact shape is preserved by the raw
/// JSON section instead.
String _text(dynamic value) {
if (value == null) return '';
if (value is String) return value;
if (value is num) {
if (value.isFinite &&
value == value.roundToDouble() &&
value.abs() < 1e21) {
return value.toInt().toString();
}
return value.toString();
}
return value.toString();
}
@@ -0,0 +1,241 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/graph_protocol.dart';
import '../domain/stage_definition.dart';
/// Wording for a stage that this pinned definition does not declare.
const String unknownStageDefinition =
'This stage is not declared in this pipeline version. '
'No definition has been reconstructed.';
/// The web pane's message when a node has no recorded stage or incoming routes.
const String noStageDefinitionDetails = 'No details recorded for this node.';
/// Terminals are definition targets; this pane never presents one as evidence.
const String terminalDefinitionNote =
'Success and Failure are definition targets, not recorded visits. '
'This pane shows where the definition routes.';
/// The raw section's heading: unknown stage fields stay visible and selectable.
const String rawStageDefinitionTitle = 'Raw stage definition';
/// A read-only native view of one stage's declared definition.
///
/// [graph] is the graph pinned for exactly [pipelineId]/[version] and
/// [stageKey] is a node key (a stage or `#success`/`#failure`). Nothing is
/// fetched and no run visit is read, so the pane cannot imply that the stage
/// executed. Unknown stage declarations get an explicit missing state; every
/// declared stage also keeps its exact JSON below the structured fields.
class StageDefinitionView extends StatelessWidget {
const StageDefinitionView({
super.key,
required this.graph,
required this.stageKey,
required this.pipelineId,
required this.pipelineName,
required this.version,
});
final JsonMap graph;
final String stageKey;
final int pipelineId;
final String pipelineName;
final int version;
String get _identity =>
'${pipelineName.isEmpty ? 'Pipeline' : pipelineName} \u00b7 v$version';
@override
Widget build(BuildContext context) {
final style = _StageDefinitionStyle.of(context);
final stage = stageDefinitionFor(graph, stageKey);
final terminal = isTerminalTarget(stageKey);
final fields = stage != null
? stageDefinitionFields(stage)
: terminal
? terminalDefinitionFields(graph, stageKey)
: const <StageDefinitionField>[];
return ListView(
padding: const EdgeInsets.all(16),
children: [
Text(_identity, style: style.muted),
const SizedBox(height: 16),
if (stage == null && !terminal)
Text(unknownStageDefinition, style: style.value)
else ...[
if (terminal) ...[
Text(terminalDefinitionNote, style: style.muted),
const SizedBox(height: 16),
],
for (final field in fields)
_StageDefinitionFieldView(field: field, style: style),
if (terminal && fields.isEmpty)
Text(noStageDefinitionDetails, style: style.muted),
if (stage != null) ...[
const SizedBox(height: 8),
Text(rawStageDefinitionTitle, style: style.heading),
const SizedBox(height: 8),
_SelectableDefinitionText(
value: const JsonEncoder.withIndent(' ').convert(stage),
style: style.value,
),
],
],
],
);
}
}
/// Opens the platform's native full-screen stage-definition page.
///
/// The page owns the single navigation bar and its standard back control; the
/// caller only supplies the pinned graph and identity. This is the hook the
/// pipeline graph uses when a node is selected.
Future<void> openStageDefinition(
BuildContext context, {
required JsonMap graph,
required String stageKey,
required int pipelineId,
required String pipelineName,
required int version,
}) {
final view = StageDefinitionView(
graph: graph,
stageKey: stageKey,
pipelineId: pipelineId,
pipelineName: pipelineName,
version: version,
);
final settings = RouteSettings(
name: 'stage-definition/$pipelineId/$version/$stageKey',
);
// A terminal is a definition target, not its protocol key: the web pane
// titles it with `nodeDisplayLabel` (`Failure`/`Success`).
final title = '${nodeDisplayLabel(stageKey)} definition';
final route = usesCupertinoHost(context)
? CupertinoPageRoute<void>(
settings: settings,
builder: (_) => CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text(title)),
child: SafeArea(child: view),
),
)
: MaterialPageRoute<void>(
settings: settings,
builder: (_) => Scaffold(
appBar: AppBar(title: Text(title)),
body: SafeArea(child: view),
),
);
return Navigator.of(context).push(route);
}
/// One labelled field: a compact row for scalars, a selectable block when the
/// value is multi-line authored text.
class _StageDefinitionFieldView extends StatelessWidget {
const _StageDefinitionFieldView({required this.field, required this.style});
final StageDefinitionField field;
final _StageDefinitionStyle style;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(field.label, style: style.label),
const SizedBox(height: 4),
if (field.block)
_SelectableDefinitionText(value: field.value, style: style.value)
else
Text(field.value, style: style.value),
],
),
);
}
}
/// Authored definition text in the host's selectable body.
///
/// The semantic leaf carries the exact value: Flutter web maps a
/// [SelectableText] to an empty read-only field, so without this a screen
/// reader (and a browser check) sees only its label. The child keeps native
/// pointer selection and the host's system typography.
///
/// The strut is derived from that same host style and forced, so a glyph the
/// host font lacks (the outcomes arrow `→` is one example) cannot pull in a
/// fallback font with taller metrics and double-space only that block. It is
/// the host's own line metrics, not a font override or a fixed height.
class _SelectableDefinitionText extends StatelessWidget {
const _SelectableDefinitionText({required this.value, required this.style});
final String value;
final TextStyle style;
@override
Widget build(BuildContext context) {
return Semantics(
label: value,
child: ExcludeSemantics(
child: SelectableText(
value,
style: style,
strutStyle: StrutStyle.fromTextStyle(style, forceStrutHeight: true),
),
),
);
}
}
/// Host text roles only: no palette, font family or explicit size.
class _StageDefinitionStyle {
const _StageDefinitionStyle({
required this.label,
required this.value,
required this.muted,
required this.heading,
});
factory _StageDefinitionStyle.of(BuildContext context) {
if (usesCupertinoHost(context)) {
final theme = CupertinoTheme.of(context);
final secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
return _StageDefinitionStyle(
label: theme.textTheme.tabLabelTextStyle.copyWith(color: secondary),
// SelectableText needs a style it can merge into the default text
// style; Cupertino's textStyle is a complete style with `inherit: false`
// and no baseline.
value: theme.textTheme.textStyle.copyWith(inherit: true),
muted: theme.textTheme.textStyle.copyWith(
inherit: true,
color: secondary,
),
heading: theme.textTheme.navTitleTextStyle,
);
}
final theme = Theme.of(context);
return _StageDefinitionStyle(
label: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
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 label;
final TextStyle value;
final TextStyle muted;
final TextStyle heading;
}
@@ -22,12 +22,20 @@ class RetryRunAction extends StatefulWidget {
required this.run,
required this.gateway,
required this.onRunChanged,
this.onRunOpened,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// Receives the id the accepted server reply names for the new retry run.
///
/// The reply is first delivered through [onRunChanged] like every other
/// accepted detail. This callback then opens that run; it is never called
/// with a guessed id, and a reply without a usable id changes no selection.
final ValueChanged<num>? onRunOpened;
@override
State<RetryRunAction> createState() => _RetryRunActionState();
}
@@ -70,7 +78,11 @@ class _RetryRunActionState extends State<RetryRunAction> {
mode: intent.mode.wireMode,
);
if (!mounted) return null;
if (_owns(id)) widget.onRunChanged(run);
if (_owns(id)) {
widget.onRunChanged(run);
final opened = retryRunId(run);
if (opened != null && opened != id) widget.onRunOpened?.call(opened);
}
return null;
} catch (error) {
return ActionRefusal(
@@ -20,10 +20,16 @@ class RetryIntent {
final String requestKey;
}
/// The entropy bound for a fresh key.
///
/// Written as a literal: on the web a bitwise `1 << 32` wraps to 0, which makes
/// `Random.nextInt` reject every retry with a `RangeError`.
const _entropyBound = 0x100000000;
/// A fresh `request_key` for one retry intent. The server requires one and caps
/// it at 128 characters; this stays well inside that bound and unique per call.
String newRetryRequestKey(num runId, {DateTime? now, int? random}) {
final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch;
final entropy = random ?? Random().nextInt(1 << 32);
final entropy = random ?? Random().nextInt(_entropyBound);
return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}';
}
+1
View File
@@ -111,6 +111,7 @@ class _RunsScreenState extends State<RunsScreen> {
controller: controller,
gateway: widget.gateway,
onBack: _back,
onRunOpened: _select,
),
],
);
@@ -1,7 +1,11 @@
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../../artifacts/ui/artifact_gallery_action.dart';
import '../actions/cancel_eligibility.dart';
import '../actions/cancel_run_action.dart';
import '../actions/retry_action.dart';
import '../actions/retry_eligibility.dart';
import '../actions/title_action.dart';
import 'run_decision_notice.dart';
@@ -13,29 +17,50 @@ class RunDetailActions extends StatelessWidget {
required this.run,
required this.gateway,
required this.onRunChanged,
this.onRunOpened,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// Opens the new run named by an accepted retry reply; see [RetryRunAction].
final ValueChanged<num>? onRunOpened;
@override
Widget build(BuildContext context) => Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Standard native spacing keeps adjacent outlines and fills distinct.
// Only actions that render are included: a hidden zero-size child still
// consumes Wrap spacing and would double the visible gap.
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
RunTitleAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
CancelRunAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
if (runTitleId(run) != null)
RunTitleAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
if (retryRunId(run) != null && canRetryRun(run))
RetryRunAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
onRunOpened: onRunOpened,
),
if (cancelRunId(run) != null && canCancelRun(run))
CancelRunAction(
run: run,
gateway: gateway,
onRunChanged: onRunChanged,
),
if (showRunArtifactsAction(run))
RunArtifactsButton(run: run, gateway: gateway),
],
),
RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged),
@@ -16,6 +16,7 @@ class RunDetailView extends StatefulWidget {
required this.controller,
required this.gateway,
required this.onBack,
this.onRunOpened,
});
final RunsController controller;
@@ -24,6 +25,10 @@ class RunDetailView extends StatefulWidget {
final ApiGateway gateway;
final VoidCallback onBack;
/// Opens the run named by an accepted retry reply, so the host route follows
/// the server-identified new run. Null keeps the detail on the retried run.
final ValueChanged<num>? onRunOpened;
@override
State<RunDetailView> createState() => _RunDetailViewState();
}
@@ -44,6 +49,7 @@ class _RunDetailViewState extends State<RunDetailView> {
run: run,
gateway: widget.gateway,
onRunChanged: widget.controller.acceptRunDetail,
onRunOpened: widget.onRunOpened,
);
return cupertino
? buildCupertinoRunDetail(
@@ -6,8 +6,8 @@ import '../../../../ui/adaptive/host.dart';
/// Secondary text under a field, using the host's own colours and text theme.
TextStyle scheduleEditorSecondaryStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
// The host's own secondary-label style; no invented point size.
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
@@ -80,28 +80,22 @@ class ScheduleListRow extends StatelessWidget {
Text(value, style: _metaStyle(context));
TextStyle? _titleStyle(BuildContext context) => cupertino
? CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(fontWeight: FontWeight.w600)
: Theme.of(
context,
).textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600);
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleMedium;
TextStyle? _bodyStyle(BuildContext context) =>
cupertino ? CupertinoTheme.of(context).textTheme.textStyle : null;
TextStyle? _metaStyle(BuildContext context) => cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
color: _secondaryColor(context),
)
? CupertinoTheme.of(
context,
).textTheme.tabLabelTextStyle.copyWith(color: _secondaryColor(context))
: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: _secondaryColor(context));
TextStyle? _statusStyle(BuildContext context) => _metaStyle(
context,
)?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600);
TextStyle? _statusStyle(BuildContext context) =>
_metaStyle(context)?.copyWith(color: _statusColor(context));
Color _secondaryColor(BuildContext context) => cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
@@ -169,8 +169,7 @@ class ScheduleListToolbar extends StatelessWidget {
}
TextStyle? _metaStyle(BuildContext context) => cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
? CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
)
: Theme.of(context).textTheme.bodySmall?.copyWith(
+7 -4
View File
@@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../ui/adaptive/host.dart';
import 'data/search_repository.dart';
import 'domain/search_controller.dart';
import 'domain/search_models.dart';
@@ -100,12 +101,14 @@ class _SearchScreenState extends State<SearchScreen> {
@override
Widget build(BuildContext context) {
// Follow the actual host app class first: a CupertinoApp supplies no
// Material theme, so reading only the platform would pick Material controls
// inside a Cupertino host on macOS/iOS.
final cupertino =
widget.cupertino ??
switch (Theme.of(context).platform) {
TargetPlatform.iOS || TargetPlatform.macOS => true,
_ => false,
};
(usesCupertinoHost(context) ||
Theme.of(context).platform == TargetPlatform.iOS ||
Theme.of(context).platform == TargetPlatform.macOS);
return cupertino ? _cupertinoScreen() : _materialScreen();
}
+208
View File
@@ -0,0 +1,208 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import '../../ui/adaptive/host.dart';
import 'data/template_repository.dart';
import 'domain/template_entry.dart';
import 'ui/template_create_dialog.dart';
import 'ui/template_detail.dart';
import 'ui/template_gallery.dart';
import 'ui/templates_failure.dart';
import 'ui/templates_frame.dart';
export 'ui/template_detail.dart'
show
templateCreateActionKey,
templateDetailKey,
templateSourceKey,
templateSourceLabel;
export 'ui/template_gallery.dart'
show
templateRowKey,
templatesEmptyKey,
templatesGalleryKey,
templatesLoadingKey;
export 'ui/templates_failure.dart'
show
templatesBannerRetryKey,
templatesErrorBannerKey,
templatesErrorKey,
templatesRetryKey;
export 'ui/templates_frame.dart' show templatesBackKey, templatesRefreshKey;
/// The reusable Templates gallery: the server's actual catalogue, one selected
/// template's metadata and verbatim selectable source, and the existing native
/// create-only prompt.
///
/// Loading and selecting only read. The single create action calls
/// [showTemplateCreateDialog] unchanged, so validate-then-submit semantics stay
/// there; an accepted `detail` is forwarded once through [onCreated]. Nothing
/// here publishes, runs, schedules or overwrites a pipeline.
///
/// Standalone use keeps this screen's own native app bar with Back and Refresh.
/// A shell that already owns navigation passes [embedded], which drops the bar
/// and keeps Back inside the detail and Refresh at the top of the body.
class TemplatesScreen extends StatefulWidget {
const TemplatesScreen({
super.key,
required this.gateway,
this.embedded = false,
this.onCreated,
});
final ApiGateway gateway;
final bool embedded;
final ValueChanged<JsonMap>? onCreated;
@override
State<TemplatesScreen> createState() => _TemplatesScreenState();
}
class _TemplatesScreenState extends State<TemplatesScreen> {
late TemplateRepository _repository = TemplateRepository(widget.gateway);
List<TemplateEntry> _templates = const [];
bool _loading = true;
bool _loaded = false;
String? _error;
String? _selectedKey;
int _generation = 0;
@override
void initState() {
super.initState();
unawaited(_load());
}
@override
void didUpdateWidget(TemplatesScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway == widget.gateway) return;
// A different gateway is a different server: never keep this one's rows or
// selection while the replacement is read.
_repository = TemplateRepository(widget.gateway);
_templates = const [];
_loaded = false;
_selectedKey = null;
unawaited(_load());
}
bool _owns(int generation) => mounted && generation == _generation;
Future<void> _load() async {
final generation = ++_generation;
setState(() {
_loading = true;
_error = null;
});
try {
final templates = await _repository.listTemplates();
if (!_owns(generation)) return;
setState(() {
_templates = templates;
_loaded = true;
_loading = false;
final selected = _selectedKey;
if (selected != null &&
!templates.any((entry) => entry.key == selected)) {
_selectedKey = null;
}
});
} catch (error) {
if (!_owns(generation)) return;
setState(() {
_loading = false;
_error = _describe(error);
});
}
}
String _describe(Object error) {
final text = error is TemplateRepositoryException
? error.message
: '$error';
final message = text.trim();
if (message.isEmpty) return 'The templates could not be loaded.';
return message.startsWith('Exception: ') ? message.substring(11) : message;
}
TemplateEntry? get _selected {
for (final entry in _templates) {
if (entry.key == _selectedKey) return entry;
}
return null;
}
void _open(String key) => setState(() => _selectedKey = key);
void _back() => setState(() => _selectedKey = null);
void _openCreate(TemplateEntry template) {
unawaited(
showTemplateCreateDialog(
context: context,
template: template,
repository: _repository,
cupertino: usesCupertinoHost(context),
onCreated: (detail) => widget.onCreated?.call(detail),
),
);
}
@override
Widget build(BuildContext context) {
final selected = _selected;
final body = selected == null
? TemplateGallery(
templates: _templates,
loaded: _loaded,
loading: _loading,
error: _error,
onRetry: () => unawaited(_load()),
onOpen: _open,
)
: TemplateDetail(
entry: selected,
showBack: widget.embedded,
onBack: _back,
onCreate: () => _openCreate(selected),
);
final framed = TemplatesFrame(
body: _withFailure(context, body),
embedded: widget.embedded,
canGoBack: selected != null,
refreshing: _loading,
onBack: _back,
onRefresh: () => unawaited(_load()),
);
if (widget.embedded) return framed;
// A selected template is this screen's own page: native back returns to
// the gallery instead of leaving the destination.
return PopScope(
canPop: selected == null,
onPopInvokedWithResult: (didPop, _) {
if (!didPop && _selectedKey != null) _back();
},
child: framed,
);
}
/// A refused refresh stays visible above whichever body is current, so an
/// open template never hides a failed read. The rows and selection are kept.
Widget _withFailure(BuildContext context, Widget body) {
final error = _error;
if (error == null || !_loaded) return body;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TemplatesFailureBanner(
message: error,
retrying: _loading,
onRetry: () => unawaited(_load()),
),
Expanded(child: body),
],
);
}
}
@@ -0,0 +1,168 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/template_entry.dart';
/// Browser wording for the gallery and the selected template, kept verbatim.
const templateSourceLabel = 'Definition source';
const templateIncludesScheduleLabel = 'Includes a schedule';
const templateCreateActionLabel = 'Create pipeline from this template';
const templateDetailKey = ValueKey<String>('template-detail');
const templateSourceKey = ValueKey<String>('template-source');
const templateCreateActionKey = ValueKey<String>('template-create-action');
const templateDetailBackKey = ValueKey<String>('template-detail-back');
/// A gallery card's name: a blank name is the explicit unnamed placeholder.
String templateGalleryName(TemplateEntry entry) {
final name = entry.name.trim();
return name.isEmpty ? '(unnamed template)' : entry.name;
}
/// A detail's heading: a blank name falls back to the template's key.
String templateDetailName(TemplateEntry entry) {
final name = entry.name.trim();
return name.isEmpty ? entry.key : entry.name;
}
/// One template's metadata and its complete, selectable definition source.
///
/// Selecting and reading a template sends nothing. The one action opens the
/// existing create-only prompt through [onCreate]; this view never submits,
/// runs or schedules anything itself.
class TemplateDetail extends StatelessWidget {
const TemplateDetail({
super.key,
required this.entry,
required this.showBack,
required this.onBack,
required this.onCreate,
});
final TemplateEntry entry;
/// True under a shell/app bar that does not own a back control for this page.
final bool showBack;
final VoidCallback onBack;
final VoidCallback onCreate;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return ListView(
key: templateDetailKey,
padding: const EdgeInsets.only(bottom: 24),
children: [
if (showBack) _backRow(context, cupertino),
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_createButton(context, cupertino),
const SizedBox(height: 12),
Text(
templateDetailName(entry),
style: templateTitleStyle(context),
),
if (entry.description.trim().isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(entry.description),
),
const SizedBox(height: 16),
Text('Key', style: templateMutedStyle(context)),
SelectableText(entry.key, style: templateBodyStyle(context)),
if (entry.scheduled)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(templateIncludesScheduleLabel),
),
const SizedBox(height: 20),
Text(templateSourceLabel, style: templateSectionStyle(context)),
const SizedBox(height: 8),
// The server's source, byte-for-byte: no trim, re-indent or
// re-encoding, so selecting it copies exactly what was received.
SelectableText(
entry.source,
key: templateSourceKey,
style: templateBodyStyle(context),
),
],
),
),
],
);
}
Widget _createButton(BuildContext context, bool cupertino) {
if (cupertino) {
return CupertinoButton.filled(
key: templateCreateActionKey,
onPressed: onCreate,
child: const Text(templateCreateActionLabel),
);
}
return FilledButton(
key: templateCreateActionKey,
onPressed: onCreate,
child: const Text(templateCreateActionLabel),
);
}
Widget _backRow(BuildContext context, bool cupertino) {
final back = cupertino
? CupertinoButton(
key: templateDetailBackKey,
padding: EdgeInsets.zero,
onPressed: onBack,
child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'),
)
: BackButton(key: templateDetailBackKey, onPressed: onBack);
return Padding(
padding: const EdgeInsets.fromLTRB(4, 4, 16, 0),
child: Row(
children: [
back,
const SizedBox(width: 4),
Expanded(
child: Text('Templates', style: templateSectionStyle(context)),
),
],
),
);
}
}
TextStyle? templateTitleStyle(BuildContext context) =>
usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
: Theme.of(context).textTheme.headlineSmall;
TextStyle? templateSectionStyle(BuildContext context) =>
usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleMedium;
TextStyle? templateBodyStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
// SelectableText needs an explicit baseline when it inherits no style.
return CupertinoTheme.of(
context,
).textTheme.textStyle.copyWith(inherit: true);
}
return Theme.of(context).textTheme.bodyMedium;
}
TextStyle? templateMutedStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
@@ -0,0 +1,138 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/template_entry.dart';
import 'template_detail.dart';
import 'templates_failure.dart';
const templatesGalleryKey = ValueKey<String>('template-gallery');
const templatesLoadingKey = ValueKey<String>('templates-loading');
const templatesEmptyKey = ValueKey<String>('templates-empty');
const _loadingLabel = 'Loading templates';
const _loadingMessage = 'Loading templates…';
const _emptyMessage = 'No templates are available on this server.';
Key templateRowKey(String key) => ValueKey<String>('template-row-$key');
/// The gallery's truthful states and native catalogue rows.
///
/// It owns no requests: loading, failure and the actual rows all come from the
/// screen, so opening a row only selects an already-read template.
class TemplateGallery extends StatelessWidget {
const TemplateGallery({
super.key,
required this.templates,
required this.loaded,
required this.loading,
required this.error,
required this.onRetry,
required this.onOpen,
});
final List<TemplateEntry> templates;
final bool loaded;
final bool loading;
final String? error;
final VoidCallback onRetry;
final ValueChanged<String> onOpen;
@override
Widget build(BuildContext context) => _body(context);
Widget _body(BuildContext context) {
if (!loaded) {
if (error != null) {
return TemplatesFailureState(
message: error!,
retrying: loading,
onRetry: onRetry,
);
}
return _loadingState(context);
}
if (templates.isEmpty) return _emptyState(context);
return usesCupertinoHost(context)
? _cupertinoList(context)
: _materialList(context);
}
Widget _loadingState(BuildContext context) {
return Center(
key: templatesLoadingKey,
child: Semantics(
liveRegion: true,
label: _loadingLabel,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
usesCupertinoHost(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
const SizedBox(height: 12),
const Text(_loadingMessage),
],
),
),
);
}
Widget _emptyState(BuildContext context) {
return Center(
key: templatesEmptyKey,
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(_emptyMessage, style: templateMutedStyle(context)),
),
);
}
Widget _materialList(BuildContext context) {
return ListView.separated(
key: templatesGalleryKey,
itemCount: templates.length,
separatorBuilder: (_, _) => const Divider(height: 1),
itemBuilder: (context, index) {
final entry = templates[index];
return ListTile(
key: templateRowKey(entry.key),
title: Text(templateGalleryName(entry)),
subtitle: entry.description.trim().isEmpty
? null
: Text(entry.description),
trailing: const Icon(Icons.chevron_right),
onTap: () => onOpen(entry.key),
);
},
);
}
Widget _cupertinoList(BuildContext context) {
return ListView(
key: templatesGalleryKey,
children: [
CupertinoListSection.insetGrouped(
children: [
for (final entry in templates)
CupertinoListTile(
key: templateRowKey(entry.key),
title: _cupertinoText(templateGalleryName(entry)),
subtitle: entry.description.trim().isEmpty
? null
: _cupertinoText(entry.description),
trailing: const CupertinoListTileChevron(),
onTap: () => onOpen(entry.key),
),
],
),
],
);
}
/// The native tile is single-line by default. Let its content wrap at larger
/// text sizes instead of ellipsizing a template's own name; the row grows
/// with the content and nothing else about the tile is restyled.
Widget _cupertinoText(String text) =>
DefaultTextStyle.merge(maxLines: 3, child: Text(text));
}
@@ -0,0 +1,118 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
const templatesErrorKey = ValueKey<String>('templates-error');
const templatesRetryKey = ValueKey<String>('templates-retry');
const templatesErrorBannerKey = ValueKey<String>('templates-error-banner');
const templatesBannerRetryKey = ValueKey<String>('templates-banner-retry');
/// A refusal for a catalogue that never loaded: the whole body is the failure.
class TemplatesFailureState extends StatelessWidget {
const TemplatesFailureState({
super.key,
required this.message,
required this.retrying,
required this.onRetry,
});
final String message;
final bool retrying;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Center(
key: templatesErrorKey,
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Semantics(
liveRegion: true,
child: Text(message, textAlign: TextAlign.center),
),
const SizedBox(height: 8),
_retryButton(
context,
buttonKey: templatesRetryKey,
retrying: retrying,
onRetry: onRetry,
),
],
),
),
);
}
}
/// A refused refresh, shown above whichever body stays visible.
///
/// The screen renders this above both the catalogue and an open template, so a
/// failed refresh can never be silent while a template is selected.
class TemplatesFailureBanner extends StatelessWidget {
const TemplatesFailureBanner({
super.key,
required this.message,
required this.retrying,
required this.onRetry,
});
final String message;
final bool retrying;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
return Padding(
key: templatesErrorBannerKey,
padding: const EdgeInsets.fromLTRB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Semantics(
liveRegion: true,
child: Text(
message,
style: TextStyle(
color: usesCupertinoHost(context)
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
),
),
),
_retryButton(
context,
buttonKey: templatesBannerRetryKey,
retrying: retrying,
onRetry: onRetry,
),
],
),
);
}
}
Widget _retryButton(
BuildContext context, {
required Key buttonKey,
required bool retrying,
required VoidCallback onRetry,
}) {
final onPressed = retrying ? null : onRetry;
if (usesCupertinoHost(context)) {
return CupertinoButton(
key: buttonKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Text('Retry'),
);
}
return TextButton(
key: buttonKey,
onPressed: onPressed,
child: const Text('Retry'),
);
}
@@ -0,0 +1,104 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
const templatesRefreshKey = ValueKey<String>('templates-refresh');
const templatesBackKey = ValueKey<String>('templates-back');
/// The screen's native chrome.
///
/// Standalone use keeps the host's own app bar with Back and Refresh. A shell
/// that already owns navigation passes [embedded], which drops the bar and
/// keeps Refresh at the top of the body.
class TemplatesFrame extends StatelessWidget {
const TemplatesFrame({
super.key,
required this.body,
required this.embedded,
required this.canGoBack,
required this.refreshing,
required this.onBack,
required this.onRefresh,
});
final Widget body;
final bool embedded;
final bool canGoBack;
final bool refreshing;
final VoidCallback onBack;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
if (embedded) return _embedded(context);
return usesCupertinoHost(context)
? _cupertino(context)
: _material(context);
}
Widget _embedded(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Align(
alignment: AlignmentDirectional.centerEnd,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: _refreshButton(context),
),
),
Expanded(child: body),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
leading: canGoBack
? CupertinoButton(
key: templatesBackKey,
padding: EdgeInsets.zero,
onPressed: onBack,
child: const Icon(CupertinoIcons.back, semanticLabel: 'Back'),
)
: null,
middle: const Text('Templates'),
trailing: _refreshButton(context),
),
child: SafeArea(child: body),
);
}
Widget _material(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Templates'),
leading: canGoBack
? BackButton(key: templatesBackKey, onPressed: onBack)
: null,
actions: [_refreshButton(context)],
),
body: SafeArea(child: body),
);
}
Widget _refreshButton(BuildContext context) {
final onPressed = refreshing ? null : onRefresh;
if (usesCupertinoHost(context)) {
return CupertinoButton(
key: templatesRefreshKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.refresh, semanticLabel: 'Refresh'),
);
}
return IconButton(
key: templatesRefreshKey,
tooltip: 'Refresh',
onPressed: onPressed,
icon: const Icon(Icons.refresh),
);
}
}