merge(app): land retry wiring in the native run detail

Conflicts: app/lib/features/runs/ui/run_detail_actions.dart.
Keep main's recorded-artifacts action and the retry branch's spaced,
render-gated Wrap: Rename, Retry, Cancel, then Recorded artifacts.
This commit is contained in:
2026-10-21 22:52:00 +01:00
56 changed files with 8712 additions and 69 deletions
@@ -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,194 @@
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_record.dart';
import '../domain/artifact_summary.dart';
import '../domain/artifact_url.dart';
import 'artifact_external_open.dart';
import 'artifact_selection_facts.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 row 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 previews, downloads, shares or filters.
class ArtifactGalleryPage extends StatefulWidget {
const ArtifactGalleryPage({
super.key,
required this.steps,
this.executing = false,
this.configuredEndpoint = '',
this.openExternal = openArtifactExternally,
});
final List<JsonMap> steps;
final bool executing;
final String configuredEndpoint;
final ArtifactExternalOpen openExternal;
@override
State<ArtifactGalleryPage> createState() => _ArtifactGalleryPageState();
}
class _ArtifactGalleryPageState extends State<ArtifactGalleryPage> {
late final Map<String, JsonMap> _stepsByGroup = recordedStepsByGroup(
widget.steps,
);
String? _selectedIdentity;
String? _status;
void _select(ArtifactGroup group, ArtifactRecord artifact) {
setState(() {
_selectedIdentity = artifactVisitIdentity(group, artifact);
_status = null;
});
_showSelected(group, artifact);
}
Future<void> _showSelected(ArtifactGroup group, ArtifactRecord artifact) {
final step = _stepsByGroup[artifactGroupKey(group.stageKey, group.visit)];
final resolved = artifact.hasUrl
? resolveArtifactUrl(widget.configuredEndpoint, artifact.url)
: null;
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 = artifactGroups(widget.steps);
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.'),
],
],
);
}
}
@@ -22,6 +22,25 @@ String artifactVisitIdentity(ArtifactGroup group, ArtifactRecord artifact) {
return '${group.stageKey}\u0000${group.visit}\u0000$recorded';
}
/// 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.
///
/// Each group shows its recorded stage and visit, and each row its recorded
@@ -60,7 +79,7 @@ class ArtifactVisitList extends StatelessWidget {
header: Semantics(
container: true,
header: true,
child: Text(_groupLabel(group)),
child: Text(artifactGroupLabel(group)),
),
hasLeading: false,
children: [
@@ -85,7 +104,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 +127,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 +145,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 +181,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,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;
}
@@ -1,6 +1,7 @@
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';
@@ -58,6 +59,8 @@ class RunDetailActions extends StatelessWidget {
gateway: gateway,
onRunChanged: onRunChanged,
),
if (showRunArtifactsAction(run))
RunArtifactsButton(run: run, gateway: gateway),
],
),
RunDecisionNotice(run: run, gateway: gateway, onRunChanged: onRunChanged),
@@ -0,0 +1,191 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
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)) {
// The host's own secondary-label style; no invented point size.
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return (theme.textTheme.bodySmall ?? const TextStyle()).copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
/// The host's semantic error colour, never a form-specific palette.
TextStyle scheduleEditorErrorStyle(BuildContext context) {
if (usesCupertinoHost(context)) {
return CupertinoTheme.of(context).textTheme.textStyle.copyWith(
color: CupertinoColors.systemRed.resolveFrom(context),
);
}
return TextStyle(color: Theme.of(context).colorScheme.error);
}
/// A wrapping label above its control, with optional helper and field error.
///
/// The browser puts the label in a sibling span, so a native floating label
/// would invent different words and truncate at large text sizes.
class ScheduleEditorField extends StatelessWidget {
const ScheduleEditorField({
super.key,
required this.label,
required this.child,
this.helper,
this.error,
});
final String label;
final Widget child;
final String? helper;
final String? error;
@override
Widget build(BuildContext context) {
final labelStyle = usesCupertinoHost(context)
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.bodyMedium;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(label, style: labelStyle),
const SizedBox(height: 6),
child,
if (helper case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
),
if (error case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorErrorStyle(context)),
),
],
);
}
}
/// One-line or multiline text input in the host's native field style.
class ScheduleEditorTextField extends StatelessWidget {
const ScheduleEditorTextField({
super.key,
required this.label,
required this.controller,
required this.onChanged,
this.fieldKey,
this.keyboardType,
this.minLines = 1,
this.maxLines = 1,
this.enabled = true,
this.helper,
this.error,
this.textInputAction,
});
final String label;
final TextEditingController controller;
final ValueChanged<String> onChanged;
final Key? fieldKey;
final TextInputType? keyboardType;
final int? minLines;
final int? maxLines;
final bool enabled;
final String? helper;
final String? error;
final TextInputAction? textInputAction;
@override
Widget build(BuildContext context) {
final field = usesCupertinoHost(context)
? CupertinoTextField(
key: fieldKey,
controller: controller,
enabled: enabled,
keyboardType: keyboardType,
minLines: minLines,
maxLines: maxLines,
textInputAction: textInputAction,
onChanged: onChanged,
)
: TextField(
key: fieldKey,
controller: controller,
enabled: enabled,
keyboardType: keyboardType,
minLines: minLines,
maxLines: maxLines,
textInputAction: textInputAction,
onChanged: onChanged,
);
return MergeSemantics(
child: ScheduleEditorField(
label: label,
helper: helper,
error: error,
child: field,
),
);
}
}
/// A native switch with a wrapping label and an explanatory helper.
class ScheduleEditorSwitchField extends StatelessWidget {
const ScheduleEditorSwitchField({
super.key,
required this.label,
required this.value,
required this.onChanged,
this.helper,
this.enabled = true,
this.switchKey,
});
final String label;
final bool value;
final ValueChanged<bool> onChanged;
final String? helper;
final bool enabled;
final Key? switchKey;
@override
Widget build(BuildContext context) {
final control = usesCupertinoHost(context)
? CupertinoSwitch(
key: switchKey,
value: value,
onChanged: enabled ? onChanged : null,
)
: Switch(
key: switchKey,
value: value,
onChanged: enabled ? onChanged : null,
);
return MergeSemantics(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(child: Text(label)),
const SizedBox(width: 12),
control,
],
),
if (helper case final text?)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(text, style: scheduleEditorSecondaryStyle(context)),
),
],
),
);
}
}
@@ -0,0 +1,234 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/editor/schedule_draft.dart';
import '../../domain/schedule_rule.dart';
import 'schedule_editor_form_body.dart';
import 'schedule_editor_wording.dart';
/// The server's refusal, verbatim, plus the browser's preservation promise.
String scheduleEditorRefusal(Object error) {
final reason = '$error'.trim();
return '${reason.isEmpty ? 'The schedule was not saved.' : reason} '
'$scheduleEditorDraftPreserved';
}
/// One native form over a landed [ScheduleDraft].
///
/// The form owns only editable controls: it mutates the draft on submit, asks
/// the draft to validate and assemble the exact record, and calls [onSubmit]
/// only with a non-null record. It never talks to a repository, route or
/// scheduler, and an async refusal leaves every typed value in place.
class ScheduleEditorForm extends StatefulWidget {
const ScheduleEditorForm({
super.key,
required this.draft,
required this.onSubmit,
this.onCancel,
this.title,
});
final ScheduleDraft draft;
final Future<void> Function(JsonMap record) onSubmit;
final VoidCallback? onCancel;
final String? title;
@override
State<ScheduleEditorForm> createState() => _ScheduleEditorFormState();
}
class _ScheduleEditorFormState extends State<ScheduleEditorForm> {
late final TextEditingController _name;
late final TextEditingController _prompt;
late final TextEditingController _version;
late final TextEditingController _workspace;
late final TextEditingController _every;
late final TextEditingController _times;
late final TextEditingController _timezone;
late ScheduleTimerMode _mode;
late List<String> _days;
late bool _enabled;
late String _notifyMode;
Map<String, String> _errors = const {};
String? _refusal;
bool _sending = false;
@override
void initState() {
super.initState();
final draft = widget.draft;
_name = TextEditingController(text: draft.name);
_prompt = TextEditingController(text: draft.prompt);
_version = TextEditingController(text: draft.version);
_workspace = TextEditingController(text: draft.workspace);
_every = TextEditingController(text: draft.every);
_times = TextEditingController(text: draft.times);
_timezone = TextEditingController(text: draft.timezone);
_mode = draft.mode;
_days = [...draft.days];
_enabled = draft.enabled;
_notifyMode = draft.notifyMode;
}
@override
void dispose() {
for (final controller in [
_name,
_prompt,
_version,
_workspace,
_every,
_times,
_timezone,
]) {
controller.dispose();
}
super.dispose();
}
String get _heading =>
widget.title ??
(widget.draft.source == null
? scheduleEditorAddTitle
: scheduleEditorEditTitle);
void _clearError(String field) {
if (!_errors.containsKey(field)) return;
setState(() => _errors = {..._errors}..remove(field));
}
void _applyToDraft() {
widget.draft
..name = _name.text
..prompt = _prompt.text
..version = _version.text
..workspace = _workspace.text
..enabled = _enabled
..mode = _mode
..every = _every.text
..times = _times.text
..days = [
for (final day in scheduleDays)
if (_days.contains(day)) day,
]
..timezone = _timezone.text
..notifyMode = _notifyMode;
}
Future<void> _submit() async {
if (_sending) return;
setState(() => _refusal = null);
_applyToDraft();
final result = widget.draft.build();
if (!result.isValid) {
setState(() => _errors = result.errors);
return;
}
setState(() {
_errors = const {};
_sending = true;
});
try {
await widget.onSubmit(result.record!);
} catch (error) {
if (!mounted) return;
setState(() {
_sending = false;
_refusal = scheduleEditorRefusal(error);
});
return;
}
if (mounted) setState(() => _sending = false);
}
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
return ScheduleEditorFormBody(
heading: _heading,
name: _name,
prompt: _prompt,
version: _version,
workspace: _workspace,
every: _every,
times: _times,
timezone: _timezone,
mode: _mode,
days: _days,
enabled: _enabled,
notifyMode: _notifyMode,
errors: _errors,
sending: _sending,
refusal: _refusal,
onModeChanged: (mode) => setState(() {
_mode = mode;
_errors = {..._errors}
..remove('every')
..remove('times');
}),
onDayToggled: (day) => setState(() {
_days = [..._days];
_days.contains(day) ? _days.remove(day) : _days.add(day);
_errors = {..._errors}..remove('days');
}),
onEnabledChanged: (enabled) => setState(() => _enabled = enabled),
onNotifyChanged: (mode) => setState(() {
_notifyMode = mode;
_errors = {..._errors}..remove('notifyMode');
}),
onEdited: _clearError,
actions: Wrap(
alignment: WrapAlignment.end,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 12,
runSpacing: 8,
children: [
if (widget.onCancel != null)
_cancelButton(cupertino)
else
const SizedBox.shrink(),
_saveButton(cupertino),
],
),
);
}
Widget _cancelButton(bool cupertino) {
final onPressed = _sending ? null : widget.onCancel;
if (cupertino) {
return CupertinoButton(
key: scheduleEditorCancelKey,
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Text(scheduleEditorCancelLabel),
);
}
return TextButton(
key: scheduleEditorCancelKey,
onPressed: onPressed,
child: const Text(scheduleEditorCancelLabel),
);
}
Widget _saveButton(bool cupertino) {
final label = Text(
_sending ? scheduleEditorSendingLabel : scheduleEditorSubmitLabel,
);
final onPressed = _sending ? null : _submit;
if (cupertino) {
return CupertinoButton.filled(
key: scheduleEditorSubmitKey,
onPressed: onPressed,
child: label,
);
}
return FilledButton(
key: scheduleEditorSubmitKey,
onPressed: onPressed,
child: label,
);
}
}
@@ -0,0 +1,229 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/editor/schedule_draft.dart';
import 'schedule_editor_fields.dart';
import 'schedule_editor_selectors.dart';
import 'schedule_editor_wording.dart';
/// The visible schedule editor column: native fields, field errors and the
/// Cancel/Save actions. State stays in `ScheduleEditorForm`; this widget only
/// renders the values and forwards edits.
class ScheduleEditorFormBody extends StatelessWidget {
const ScheduleEditorFormBody({
super.key,
required this.heading,
required this.name,
required this.prompt,
required this.version,
required this.workspace,
required this.every,
required this.times,
required this.timezone,
required this.mode,
required this.days,
required this.enabled,
required this.notifyMode,
required this.errors,
required this.sending,
this.refusal,
required this.onModeChanged,
required this.onDayToggled,
required this.onEnabledChanged,
required this.onNotifyChanged,
required this.onEdited,
required this.actions,
});
final String heading;
final TextEditingController name;
final TextEditingController prompt;
final TextEditingController version;
final TextEditingController workspace;
final TextEditingController every;
final TextEditingController times;
final TextEditingController timezone;
final ScheduleTimerMode mode;
final List<String> days;
final bool enabled;
final String notifyMode;
final Map<String, String> errors;
final bool sending;
final String? refusal;
final ValueChanged<ScheduleTimerMode> onModeChanged;
final ValueChanged<String> onDayToggled;
final ValueChanged<bool> onEnabledChanged;
final ValueChanged<String> onNotifyChanged;
final ValueChanged<String> onEdited;
final Widget actions;
static const _gap = SizedBox(height: 16);
static const _timerOptions = [
ScheduleEditorChoice(ScheduleTimerMode.interval, 'Interval'),
ScheduleEditorChoice(ScheduleTimerMode.clock, 'Clock times'),
];
List<ScheduleEditorChoice<String>> get _notifyOptions {
const values = ['auto', 'on', 'off'];
return [
if (!values.contains(notifyMode))
ScheduleEditorChoice(notifyMode, notifyMode),
for (final value in values) ScheduleEditorChoice(value, value),
];
}
Widget _textField({
required Key key,
required String label,
required TextEditingController controller,
required String field,
String? error,
int minLines = 1,
int? maxLines = 1,
TextInputType? keyboardType,
TextInputAction? textInputAction,
}) => ScheduleEditorTextField(
fieldKey: key,
label: label,
controller: controller,
enabled: !sending,
minLines: minLines,
maxLines: maxLines,
keyboardType: keyboardType,
textInputAction: textInputAction,
error: error,
onChanged: (_) => onEdited(field),
);
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final titleStyle = cupertino
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
: Theme.of(context).textTheme.titleLarge;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(heading, style: titleStyle),
const SizedBox(height: 8),
Text(scheduleEditorNote, style: scheduleEditorSecondaryStyle(context)),
_gap,
_textField(
key: scheduleEditorNameKey,
label: scheduleEditorNameLabel,
controller: name,
field: 'name',
error: errors['name'],
textInputAction: TextInputAction.next,
),
_gap,
_textField(
key: scheduleEditorPromptKey,
label: scheduleEditorPromptLabel,
controller: prompt,
field: 'prompt',
error: errors['prompt'],
minLines: 3,
maxLines: null,
keyboardType: TextInputType.multiline,
),
_gap,
_textField(
key: scheduleEditorVersionKey,
label: scheduleEditorVersionLabel,
controller: version,
field: 'version',
error: errors['version'],
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
),
_gap,
_textField(
key: scheduleEditorWorkspaceKey,
label: scheduleEditorWorkspaceLabel,
controller: workspace,
field: 'workspace',
error: errors['workspace'],
textInputAction: TextInputAction.next,
),
_gap,
ScheduleEditorChoiceField<ScheduleTimerMode>(
fieldKey: scheduleEditorTimerKey,
label: scheduleEditorTimerLabel,
value: mode,
options: _timerOptions,
enabled: !sending,
onChanged: onModeChanged,
),
_gap,
if (mode == ScheduleTimerMode.interval)
_textField(
key: scheduleEditorEveryKey,
label: scheduleEditorEveryLabel,
controller: every,
field: 'every',
error: errors['every'],
)
else
_textField(
key: scheduleEditorTimesKey,
label: scheduleEditorTimesLabel,
controller: times,
field: 'times',
error: errors['times'],
),
_gap,
ScheduleEditorDaysField(
label: scheduleEditorDaysLabel,
days: days,
enabled: !sending,
error: errors['days'],
onToggle: onDayToggled,
),
_gap,
_textField(
key: scheduleEditorTimezoneKey,
label: scheduleEditorTimezoneLabel,
controller: timezone,
field: 'timezone',
error: errors['timezone'],
),
_gap,
ScheduleEditorSwitchField(
switchKey: scheduleEditorEnabledKey,
label: scheduleEditorEnabledLabel,
helper: scheduleEditorEnabledNote,
value: enabled,
enabled: !sending,
onChanged: onEnabledChanged,
),
_gap,
ScheduleEditorChoiceField<String>(
fieldKey: scheduleEditorNotifyKey,
label: scheduleEditorNotificationsLabel,
value: notifyMode,
options: _notifyOptions,
enabled: !sending,
error: errors['notifyMode'],
onChanged: onNotifyChanged,
),
if (refusal ?? errors['record'] ?? errors['pipelineId']
case final error?) ...[
_gap,
Semantics(
liveRegion: true,
child: Text(
error,
key: scheduleEditorErrorKey,
style: scheduleEditorErrorStyle(context),
),
),
],
_gap,
actions,
],
);
}
}
@@ -0,0 +1,200 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../ui/adaptive/host.dart';
import '../../domain/schedule_rule.dart';
import 'schedule_editor_fields.dart';
/// Day checkbox keys, shared with tests and the browser fixture.
ValueKey<String> scheduleEditorDayKey(String day) =>
ValueKey<String>('schedule-editor-day-$day');
/// One option of a [ScheduleEditorChoiceField].
class ScheduleEditorChoice<T> {
const ScheduleEditorChoice(this.value, this.label);
final T value;
final String label;
}
/// A native drop-down on Material and a native action sheet on Cupertino.
class ScheduleEditorChoiceField<T> extends StatelessWidget {
const ScheduleEditorChoiceField({
super.key,
required this.label,
required this.value,
required this.options,
required this.onChanged,
this.enabled = true,
this.helper,
this.error,
this.fieldKey,
});
final String label;
final T value;
final List<ScheduleEditorChoice<T>> options;
final ValueChanged<T> onChanged;
final bool enabled;
final String? helper;
final String? error;
final Key? fieldKey;
String get _selectedLabel {
for (final option in options) {
if (option.value == value) return option.label;
}
return '';
}
Future<void> _choose(BuildContext context) async {
final chosen = await showCupertinoModalPopup<T>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(label),
actions: [
for (final option in options)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, option.value),
child: Text(option.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (chosen != null) onChanged(chosen);
}
@override
Widget build(BuildContext context) {
final control = usesCupertinoHost(context)
? CupertinoButton(
key: fieldKey,
padding: EdgeInsets.zero,
onPressed: enabled ? () => _choose(context) : null,
child: Row(
children: [
Expanded(child: Text(_selectedLabel)),
const Icon(CupertinoIcons.chevron_down),
],
),
)
: DropdownButtonFormField<T>(
key: fieldKey,
initialValue: value,
isExpanded: true,
items: [
for (final option in options)
DropdownMenuItem<T>(
value: option.value,
child: Text(option.label),
),
],
onChanged: enabled
? (chosen) {
if (chosen != null) onChanged(chosen);
}
: null,
);
return MergeSemantics(
child: ScheduleEditorField(
label: label,
helper: helper,
error: error,
child: control,
),
);
}
}
/// Weekday checkboxes in a wrapping row; no selection means every day.
class ScheduleEditorDaysField extends StatelessWidget {
const ScheduleEditorDaysField({
super.key,
required this.label,
required this.days,
required this.onToggle,
this.enabled = true,
this.error,
});
final String label;
final List<String> days;
final ValueChanged<String> onToggle;
final bool enabled;
final String? error;
@override
Widget build(BuildContext context) {
return ScheduleEditorField(
label: label,
error: error,
child: Wrap(
spacing: 12,
runSpacing: 8,
children: [
for (final day in scheduleDays)
_DayToggle(
day: day,
selected: days.contains(day),
enabled: enabled,
onTap: () => onToggle(day),
),
],
),
);
}
}
class _DayToggle extends StatelessWidget {
const _DayToggle({
required this.day,
required this.selected,
required this.enabled,
required this.onTap,
});
final String day;
final bool selected;
final bool enabled;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final cupertino = usesCupertinoHost(context);
final checkbox = cupertino
? CupertinoCheckbox(
key: scheduleEditorDayKey(day),
value: selected,
onChanged: enabled ? (_) => onTap() : null,
)
: Checkbox(
key: scheduleEditorDayKey(day),
value: selected,
onChanged: enabled ? (_) => onTap() : null,
);
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [checkbox, const SizedBox(width: 4), Text(day)],
),
);
return MergeSemantics(
child: cupertino
? GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: enabled ? onTap : null,
child: content,
)
: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: enabled ? onTap : null,
child: content,
),
);
}
}
@@ -0,0 +1,45 @@
import 'package:flutter/widgets.dart';
/// Browser wording and stable keys for the saved-schedule editor, kept
/// verbatim from `web/src/views/schedules.js`.
const scheduleEditorAddTitle = 'Add schedule';
const scheduleEditorEditTitle = 'Edit schedule';
const scheduleEditorNote =
'Future runs only; does not publish or change the workflow. '
'Saving does not start a run.';
const scheduleEditorNameLabel = 'Name';
const scheduleEditorPromptLabel = 'Prompt';
const scheduleEditorVersionLabel = 'Pinned version';
const scheduleEditorWorkspaceLabel = 'Server workspace';
const scheduleEditorTimerLabel = 'Timer';
const scheduleEditorEveryLabel = 'Interval (at least 1m)';
const scheduleEditorTimesLabel = 'Clock times (24h, comma separated)';
const scheduleEditorDaysLabel = 'Weekdays (none means every day)';
const scheduleEditorTimezoneLabel = 'Timezone (blank uses server timezone)';
const scheduleEditorEnabledLabel = 'Enabled';
const scheduleEditorEnabledNote =
'Enabled schedules start future runs automatically, including model '
'usage and the workflow’s permitted tools.';
const scheduleEditorNotificationsLabel = 'Notifications';
const scheduleEditorSubmitLabel = 'Save schedule';
const scheduleEditorSendingLabel = 'Saving…';
const scheduleEditorCancelLabel = 'Cancel';
const scheduleEditorDraftPreserved =
'Your draft is preserved. If this schedule changed elsewhere, reopen it '
'before retrying.';
const scheduleEditorNameKey = ValueKey<String>('schedule-editor-name');
const scheduleEditorPromptKey = ValueKey<String>('schedule-editor-prompt');
const scheduleEditorVersionKey = ValueKey<String>('schedule-editor-version');
const scheduleEditorWorkspaceKey = ValueKey<String>(
'schedule-editor-workspace',
);
const scheduleEditorTimerKey = ValueKey<String>('schedule-editor-timer');
const scheduleEditorEveryKey = ValueKey<String>('schedule-editor-every');
const scheduleEditorTimesKey = ValueKey<String>('schedule-editor-times');
const scheduleEditorTimezoneKey = ValueKey<String>('schedule-editor-timezone');
const scheduleEditorEnabledKey = ValueKey<String>('schedule-editor-enabled');
const scheduleEditorNotifyKey = ValueKey<String>('schedule-editor-notify');
const scheduleEditorSubmitKey = ValueKey<String>('schedule-editor-submit');
const scheduleEditorCancelKey = ValueKey<String>('schedule-editor-cancel');
const scheduleEditorErrorKey = ValueKey<String>('schedule-editor-error');
@@ -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),
);
}
}