Merge branch 'main' into flutter/p1-pipelines

This commit is contained in:
2026-10-21 19:09:32 +01:00
304 changed files with 40777 additions and 159 deletions
@@ -0,0 +1,63 @@
import '../../../core/api_gateway.dart';
import 'artifact_record.dart';
/// Whether a step actually carried an artifact list.
///
/// An absent (or null) field means the capture is unavailable: an older step, a
/// running visit, or a reply that did not include the field. It must never be
/// reported as an empty capture. An explicitly recorded empty list is a known,
/// empty capture.
enum ArtifactCaptureAvailability { unavailable, recorded }
/// The recorded capture facts of one step: availability, files, and how many
/// files the bounded scan excluded or omitted. Pure: it reads the step and adds
/// no server call.
class ArtifactCapture {
const ArtifactCapture._({
required this.availability,
required this.artifacts,
required this.skipped,
required this.truncated,
});
factory ArtifactCapture.fromStep(JsonMap step) {
final value = step['artifacts'];
final available = step.containsKey('artifacts') && value is List;
final artifacts = available
? <ArtifactRecord>[
for (final item in value)
if (item is Map)
ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
]
: const <ArtifactRecord>[];
return ArtifactCapture._(
availability: available
? ArtifactCaptureAvailability.recorded
: ArtifactCaptureAvailability.unavailable,
artifacts: List<ArtifactRecord>.unmodifiable(artifacts),
skipped: _countOf(step['artifacts_skipped']),
truncated: _countOf(step['artifacts_truncated']),
);
}
final ArtifactCaptureAvailability availability;
/// Every recorded file, including utility and retired files.
final List<ArtifactRecord> artifacts;
/// Files excluded from the bounded per-step scan.
final int skipped;
/// Files omitted by the capture's total budget.
final int truncated;
bool get isAvailable => availability == ArtifactCaptureAvailability.recorded;
bool get isPartial => skipped > 0 || truncated > 0;
static int _countOf(dynamic value) {
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value.trim()) ?? 0;
return 0;
}
}
@@ -0,0 +1,109 @@
import '../../../core/api_gateway.dart';
import '../../graph/domain/stage_visits.dart';
import 'artifact_record.dart';
import 'artifact_selection.dart';
/// One gallery group: the stage-produced artifacts of a recorded stage visit.
class ArtifactGroup {
const ArtifactGroup({
required this.stageKey,
required this.visit,
required this.artifacts,
});
final String stageKey;
/// The display visit number: `control.visit` when positive, else the position
/// within the stage's ordered visits. Never a synthetic visit.
final int visit;
final List<ArtifactRecord> artifacts;
}
int _sequenceOf(JsonMap step) {
final sequence = step['sequence'];
return sequence is num ? sequence.toInt() : 0;
}
/// Sequence order with recorded order as the tie-break, matching the web
/// client's stable sort.
List<JsonMap> _orderedBySequence(List<JsonMap> steps) {
final indexed = <({int position, JsonMap step})>[
for (var index = 0; index < steps.length; index += 1)
(position: index, step: steps[index]),
];
indexed.sort((a, b) {
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
});
return <JsonMap>[for (final entry in indexed) entry.step];
}
/// Groups a run's stage artifacts by stage and recorded visit.
///
/// Stages keep first-appearance order and each stage's visits are ordered by
/// sequence. A shared `public/` file is attributed to the visit that first
/// recorded it, because the server records the whole public directory on every
/// model visit. Only visits with at least one presented stage artifact produce a
/// group, so an unavailable or empty capture never yields an empty group. An
/// artifact-less run yields an empty list rather than a fabricated stage.
List<ArtifactGroup> artifactGroups(List<JsonMap> steps) {
if (steps.isEmpty) return const <ArtifactGroup>[];
final attributed = <JsonMap, List<ArtifactRecord>>{};
final seenPublic = <String>{};
for (final recordedStep in _orderedBySequence(steps)) {
final repairs = repairArtifactNames(recordedStep);
final kept = <ArtifactRecord>[];
for (final artifact in stageArtifactsFrom(
artifactsOf(recordedStep),
repairs: repairs,
)) {
if (artifact.isPublicName) {
if (seenPublic.contains(artifact.name)) continue;
seenPublic.add(artifact.name);
}
kept.add(artifact);
}
attributed[recordedStep] = List<ArtifactRecord>.unmodifiable(kept);
}
final groups = <ArtifactGroup>[];
for (final entry in visitsByStage(steps).entries) {
final visits = entry.value;
for (var index = 0; index < visits.length; index += 1) {
final artifacts = attributed[visits[index]];
if (artifacts == null || artifacts.isEmpty) continue;
groups.add(
ArtifactGroup(
stageKey: entry.key,
visit: displayVisit(visits[index], index),
artifacts: artifacts,
),
);
}
}
return List<ArtifactGroup>.unmodifiable(groups);
}
/// One visit's stage artifacts, excluding shared public files that an earlier
/// visit already recorded. A repeated non-public name in a later visit stays
/// because it is a different recorded artifact, not the same shared file.
List<ArtifactRecord> visitArtifacts(JsonMap step, List<JsonMap> runSteps) {
final all = stageArtifacts(step);
if (runSteps.isEmpty) return all;
final seen = <String>{};
for (final candidate in _orderedBySequence(runSteps)) {
if (identical(candidate, step) ||
_sequenceOf(candidate) == _sequenceOf(step)) {
break;
}
for (final artifact in stageArtifacts(candidate)) {
if (artifact.isPublicName) seen.add(artifact.name);
}
}
return <ArtifactRecord>[
for (final artifact in all)
if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact,
];
}
@@ -0,0 +1,225 @@
/// What an artifact is from the gallery's point of view: the two media kinds it
/// previews and the file kinds it labels with a type word. Mirrors the web
/// client's `ArtifactKind` vocabulary.
enum ArtifactKind {
image,
video,
audio,
pdf,
json,
archive,
spreadsheet,
log,
code,
document,
other,
}
const Set<String> _archiveExtensions = <String>{
'zip',
'tar',
'gz',
'tgz',
'bz2',
'xz',
'rar',
'7z',
'jar',
'war',
};
const Set<String> _archiveMimes = <String>{
'application/zip',
'application/gzip',
'application/x-tar',
'application/x-7z-compressed',
'application/x-rar-compressed',
'application/java-archive',
};
const Set<String> _spreadsheetExtensions = <String>{
'csv',
'tsv',
'xls',
'xlsx',
'ods',
};
const Set<String> _spreadsheetMimes = <String>{
'text/csv',
'text/tab-separated-values',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
const Set<String> _codeExtensions = <String>{
'kt',
'kts',
'java',
'go',
'py',
'rb',
'php',
'rs',
'c',
'h',
'cc',
'cpp',
'hpp',
'cs',
'js',
'jsx',
'ts',
'tsx',
'mjs',
'cjs',
'swift',
'scala',
'sh',
'bash',
'zsh',
'fish',
'ps1',
'sql',
'yaml',
'yml',
'toml',
'ini',
'xml',
'gradle',
'properties',
'proto',
};
const Set<String> _codeMimes = <String>{
'application/xml',
'application/x-yaml',
'application/javascript',
'text/javascript',
'text/x-python',
'text/x-java-source',
'text/x-kotlin',
'application/x-sh',
'application/x-httpd-php',
'application/sql',
};
const Set<String> _documentExtensions = <String>{
'txt',
'md',
'markdown',
'rst',
'doc',
'docx',
'odt',
'rtf',
'html',
'htm',
};
const Set<String> _markdownExtensions = <String>{'md', 'markdown', 'txt'};
const Set<String> _documentMimes = <String>{
'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/rtf',
};
const Map<ArtifactKind, String> _kindLabels = <ArtifactKind, String>{
ArtifactKind.image: 'Image',
ArtifactKind.video: 'Video',
ArtifactKind.audio: 'Audio',
ArtifactKind.pdf: 'PDF',
ArtifactKind.json: 'JSON',
ArtifactKind.archive: 'Archive',
ArtifactKind.spreadsheet: 'Spreadsheet',
ArtifactKind.log: 'Log',
ArtifactKind.code: 'Code',
ArtifactKind.document: 'Document',
ArtifactKind.other: 'File',
};
/// Whether a recorded content type is an image the gallery previews.
bool isImageContentType(String contentType) => contentType.startsWith('image/');
/// Whether a recorded content type is a video; videos get a poster tile and are
/// never decoded inline or autoplayed.
bool isVideoContentType(String contentType) => contentType.startsWith('video/');
/// The lowercased extension of [name], or '' when it carries none.
String _extensionOf(String name) {
final dot = name.lastIndexOf('.');
return dot == -1 ? '' : name.substring(dot + 1).toLowerCase();
}
/// The gallery kind for a recorded content type and name.
///
/// Image and video come straight from the content type; the other kinds match
/// the normalised MIME first, then the name's extension. Pure and total: an
/// unknown type is [ArtifactKind.other], never a guess that changes an action.
ArtifactKind artifactKind(String contentType, String name) {
if (isImageContentType(contentType)) return ArtifactKind.image;
if (isVideoContentType(contentType)) return ArtifactKind.video;
final mime = contentType.split(';').first.trim().toLowerCase();
final ext = _extensionOf(name);
if (mime.startsWith('audio/')) return ArtifactKind.audio;
if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf;
if (mime.contains('json') || ext == 'json') return ArtifactKind.json;
if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) {
return ArtifactKind.archive;
}
if (_spreadsheetMimes.contains(mime) ||
_spreadsheetExtensions.contains(ext)) {
return ArtifactKind.spreadsheet;
}
if (ext == 'log') return ArtifactKind.log;
if (mime == 'text/html') return ArtifactKind.document;
if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) {
return ArtifactKind.code;
}
if (mime.startsWith('text/') ||
_documentMimes.contains(mime) ||
_documentExtensions.contains(ext)) {
return ArtifactKind.document;
}
return ArtifactKind.other;
}
/// The prose word naming [kind], so a type glyph never has to be read alone.
String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File';
/// Whether an artifact is text the viewer can render as markdown: `text/markdown`
/// or `text/plain` (parameters ignored), or an md/markdown/txt name.
bool isMarkdownArtifact(String contentType, String name) {
final mime = contentType.split(';').first.trim().toLowerCase();
if (mime == 'text/markdown' || mime == 'text/plain') return true;
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.
bool isViewerArtifact(String contentType, String name) {
if (isImageContentType(contentType) || isVideoContentType(contentType)) {
return true;
}
return artifactKind(contentType, name) == ArtifactKind.document &&
isMarkdownArtifact(contentType, name);
}
/// Human-readable byte size, matching the web client: whole bytes under 1 KiB,
/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB).
String humanBytes(num size) {
final value = size.truncate();
const unit = 1024;
if (value < unit) return '$value B';
var div = unit;
var exp = 0;
var scaled = value ~/ unit;
while (scaled >= unit) {
div *= unit;
exp++;
scaled ~/= unit;
}
return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB';
}
@@ -0,0 +1,85 @@
import '../../../core/api_gateway.dart';
/// The retired markdown session export file name. Nothing writes it any more,
/// but a run recorded before the HTML-only change still lists `session.md`: it
/// is dated evidence that is never presented beside `session.html`.
const String legacySessionMarkdownArtifact = 'session.md';
/// The files the turn protocol itself writes for every visit. They are audit
/// evidence, not stage output, so the artifact gallery lists stage files first
/// and keeps these for an audit/debug surface.
const List<String> systemArtifactNames = <String>[
'input.md',
'memory.md',
'output.md',
'session.html',
];
/// One recorded artifact of a stage visit.
///
/// The server is the authority: [name], [url], [contentType] and [sizeBytes]
/// are read verbatim and every other field is kept in [raw]. A record is never
/// inferred or completed locally; a missing url stays empty rather than being
/// fabricated from the name. Two records with the same name stay distinct
/// because only the recorded url identifies an artifact.
class ArtifactRecord {
const ArtifactRecord({
required this.name,
required this.url,
required this.contentType,
required this.sizeBytes,
required this.raw,
});
factory ArtifactRecord.fromJson(JsonMap json) {
final raw = _frozenMap(json);
return ArtifactRecord(
name: _text(raw['name']),
url: _text(raw['url']),
contentType: _text(raw['content_type']),
sizeBytes: _intOf(raw['size_bytes']),
raw: raw,
);
}
/// The recorded file name, including any `public/` prefix.
final String name;
/// The recorded artifact url exactly as the server sent it.
final String url;
/// The server-sniffed content type, possibly with parameters.
final String contentType;
/// The recorded byte size; 0 when the server recorded none.
final int sizeBytes;
/// Every field the server sent, including fields this slice does not model.
/// Deeply unmodifiable, so a view cannot mutate the server reply.
final JsonMap raw;
bool get hasUrl => url.trim().isNotEmpty;
bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact;
bool get isSystem => isSystemArtifactName(name);
bool get isPublicName => name.startsWith('public/');
static String _text(dynamic value) => value == null ? '' : '$value';
static int _intOf(dynamic value) {
if (value is num) return value.toInt();
if (value is String) return int.tryParse(value.trim()) ?? 0;
return 0;
}
static JsonMap _frozenMap(JsonMap json) => Map<String, dynamic>.unmodifiable(
json.map((key, value) => MapEntry(key, _frozen(value))),
);
static dynamic _frozen(dynamic value) {
if (value is Map) return _frozenMap(Map<String, dynamic>.from(value));
if (value is List) return List<dynamic>.unmodifiable(value.map(_frozen));
return value;
}
}
bool isSystemArtifactName(String name) => systemArtifactNames.contains(name);
@@ -0,0 +1,67 @@
import '../../../core/api_gateway.dart';
import 'artifact_record.dart';
/// Parses one step's recorded artifact list. An absent, null or malformed list
/// yields no records; the capture state (and its unavailable wording) is
/// reported by `artifact_capture.dart`, never treated as an empty capture here.
List<ArtifactRecord> artifactsOf(JsonMap step) {
final value = step['artifacts'];
if (value is! List) return const <ArtifactRecord>[];
return <ArtifactRecord>[
for (final item in value)
if (item is Map) ArtifactRecord.fromJson(Map<String, dynamic>.from(item)),
];
}
/// The html names a visit's session-export repairs produced.
Set<String> repairArtifactNames(JsonMap step) {
final value = step['session_export_repairs'];
if (value is! List) return const <String>{};
return <String>{
for (final entry in value)
if (entry is Map &&
entry['html'] is String &&
'${entry['html']}'.trim().isNotEmpty)
'${entry['html']}',
};
}
/// The artifacts of one visit as presented: the recorded files with the retired
/// markdown session export filtered out. Duplicate names are kept because an
/// artifact's identity is its recorded url, not its name.
List<ArtifactRecord> presentedArtifacts(Iterable<ArtifactRecord> artifacts) {
return <ArtifactRecord>[
for (final artifact in artifacts)
if (!artifact.isLegacySessionMarkdown) artifact,
];
}
/// A visit's stage-produced artifacts: everything except the turn-owned files
/// and repaired session exports. Order is preserved.
List<ArtifactRecord> stageArtifactsFrom(
Iterable<ArtifactRecord> artifacts, {
Set<String> repairs = const <String>{},
}) {
return <ArtifactRecord>[
for (final artifact in presentedArtifacts(artifacts))
if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact,
];
}
/// A visit's system files and repaired exports, in recorded order.
List<ArtifactRecord> systemArtifactsFrom(
Iterable<ArtifactRecord> artifacts, {
Set<String> repairs = const <String>{},
}) {
return <ArtifactRecord>[
for (final artifact in presentedArtifacts(artifacts))
if (artifact.isSystem || repairs.contains(artifact.name)) artifact,
];
}
/// Convenience for callers holding a raw step rather than parsed records.
List<ArtifactRecord> stageArtifacts(JsonMap step) =>
stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
List<ArtifactRecord> systemArtifacts(JsonMap step) =>
systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step));
@@ -0,0 +1,78 @@
import '../../../core/api_gateway.dart';
import 'artifact_capture.dart';
import 'artifact_groups.dart';
import 'artifact_selection.dart';
/// The "capture pending" wording shared by a running visit's summary and the
/// run-level empty state, so the two never spell it differently.
const String artifactCapturePending = 'capture pending';
/// The explicit message shown where the run's gallery would be when there are
/// no recorded artifacts. A running run says capture pending; a finished run
/// with available captures says plainly that nothing was recorded.
String artifactsEmptyMessage(bool executing) => executing
? 'Artifacts · $artifactCapturePending'
: 'No artifacts recorded for this run.';
/// The run summary's Artifacts section header.
///
/// The recorded count is exactly the number of tiles [artifactGroups] yields;
/// the title takes its singular form for one. A run whose capture is unavailable
/// says so instead of claiming that nothing was recorded. Partial capture is
/// flagged when any visit excluded or omitted files.
String artifactsHeader(List<JsonMap> steps, {required bool executing}) {
final recorded = artifactGroups(
steps,
).fold<int>(0, (sum, group) => sum + group.artifacts.length);
if (recorded == 0) {
if (executing) return artifactsEmptyMessage(true);
final unavailable = steps.any(
(step) => !ArtifactCapture.fromStep(step).isAvailable,
);
return unavailable
? 'Artifacts · capture unavailable'
: artifactsEmptyMessage(false);
}
final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial);
var label =
'${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded';
if (partial) label += ' · partial capture';
return label;
}
/// The per-visit artifacts label.
///
/// A running visit says capture pending. A finished visit whose capture field was
/// absent says capture unavailable rather than "not recorded"; only an explicitly
/// empty capture says "not recorded for this visit". Recorded counts exclude the
/// turn-owned files and the retired session markdown, so the words match tiles.
String artifactsSummary(JsonMap step, {int? count}) {
final capture = ArtifactCapture.fromStep(step);
final recorded = count ?? stageArtifacts(step).length;
if (recorded == 0) {
if (step['status'] == 'running') {
return 'Artifacts · $artifactCapturePending';
}
if (!capture.isAvailable) return 'Artifacts · capture unavailable';
return 'Artifacts · not recorded for this visit';
}
var label = 'Artifacts · $recorded recorded';
if (capture.isPartial) label += ' · partial capture';
return label;
}
/// The partial-capture notes, one line per non-zero count and nothing when the
/// capture was complete or had no presented files. An unavailable capture yields
/// no notes because there is no evidence to quantify.
List<String> artifactCaptureNotes(JsonMap step) {
final notes = <String>[];
if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes;
final capture = ArtifactCapture.fromStep(step);
if (capture.skipped > 0) {
notes.add('${capture.skipped} files excluded from artifact capture.');
}
if (capture.truncated > 0) {
notes.add('${capture.truncated} files omitted by artifact capture limits.');
}
return notes;
}
@@ -0,0 +1,78 @@
import '../../../core/transport/server_url.dart';
/// A validated artifact url plus whether it points outside the configured
/// server origin.
class ResolvedArtifactUrl {
const ResolvedArtifactUrl({required this.uri, required this.external});
final Uri uri;
/// True when the url's origin differs from the configured server origin (or
/// the configured origin is unusable). A future authenticated fetch must send
/// no cookies, authorization header or other server credentials for an
/// external url.
final bool external;
String get url => uri.toString();
}
const List<String> _unsafePrefixes = <String>['//', r'\\', r'\/', '/\\'];
/// Resolves a recorded artifact url for display and opening.
///
/// A server-relative path (`/artifacts/...`, or a path without the leading
/// slash) resolves against the configured websocket endpoint's http(s) origin,
/// dropping the endpoint path and query. An absolute http(s) url is preserved,
/// including its encoded path and query. Output is always http(s): protocol-
/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls
/// are rejected with null. A blank or invalid configured endpoint resolves no
/// relative path; it never invents a host.
ResolvedArtifactUrl? resolveArtifactUrl(
String configuredEndpoint,
String artifactUrl,
) {
final raw = artifactUrl.trim();
if (raw.isEmpty) return null;
for (final prefix in _unsafePrefixes) {
if (raw.startsWith(prefix)) return null;
}
final parsed = Uri.tryParse(raw);
if (parsed == null) return null;
final configured = _httpOrigin(configuredEndpoint);
if (parsed.hasScheme) {
final scheme = parsed.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (!parsed.hasAuthority || parsed.host.isEmpty) return null;
if (parsed.userInfo.isNotEmpty) return null;
return ResolvedArtifactUrl(
uri: parsed,
external: configured == null || parsed.origin != configured.origin,
);
}
if (configured == null) return null;
final relative = raw.startsWith('/') ? raw : '/$raw';
final resolved = Uri.tryParse('${configured.origin}$relative');
if (resolved == null) return null;
final scheme = resolved.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (!resolved.hasAuthority || resolved.host.isEmpty) return null;
if (resolved.userInfo.isNotEmpty) return null;
return ResolvedArtifactUrl(uri: resolved, external: false);
}
/// The http(s) origin of a configured websocket endpoint, or null when the
/// endpoint is blank, malformed, or not a ws/wss url.
Uri? _httpOrigin(String configuredEndpoint) {
try {
final endpoint = ServerUrl.validate(configuredEndpoint);
final http = Uri.parse(endpoint.httpUrl);
final scheme = http.scheme.toLowerCase();
if (scheme != 'http' && scheme != 'https') return null;
if (http.host.isEmpty) return null;
return Uri.parse(http.origin);
} on FormatException {
return null;
}
}
@@ -0,0 +1,76 @@
import 'artifact_groups.dart';
import 'artifact_kind.dart';
import 'artifact_record.dart';
/// One artifact in the viewer's filtered page list, with the stage visit it
/// belongs to. [identity] is the recorded url when there is one; otherwise it is
/// 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.artifact,
required this.pageIndex,
});
final String stageKey;
final int visit;
final ArtifactRecord artifact;
/// Position in the filtered page list.
final int pageIndex;
String get identity => artifact.hasUrl
? artifact.url
: '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}';
}
/// 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
/// filters and orders records the gallery already holds.
List<PagedArtifact> pagedArtifacts(List<ArtifactGroup> groups) {
final pages = <PagedArtifact>[];
for (final group in groups) {
for (final artifact in group.artifacts) {
if (!isViewerArtifact(artifact.contentType, artifact.name)) continue;
pages.add(
PagedArtifact(
stageKey: group.stageKey,
visit: group.visit,
artifact: artifact,
pageIndex: pages.length,
),
);
}
}
return List<PagedArtifact>.unmodifiable(pages);
}
/// Each page's recorded url mapped to its page index, so a tile and the viewer
/// derive from the same ordered list. The first occurrence of a url wins. A
/// record with no recorded url has no fetchable identity and is omitted.
Map<String, int> viewerIndexByUrl(List<ArtifactGroup> groups) {
final indices = <String, int>{};
for (final page in pagedArtifacts(groups)) {
if (!page.artifact.hasUrl) continue;
indices.putIfAbsent(page.artifact.url, () => page.pageIndex);
}
return indices;
}
/// Paging from [current] by [delta] within `count` pages, clamped at both ends
/// so a page never wraps and an empty list is index 0.
int pagedIndex(int current, int delta, int count) {
if (count <= 0) return 0;
final wanted = current + delta;
if (wanted < 0) return 0;
if (wanted >= count) return count - 1;
return wanted;
}
/// The viewer's position label, e.g. `2 of 5 · image/png`.
String artifactViewerPositionLabel(int index, int count, String contentType) {
final type = contentType.split(';').first.trim();
return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}';
}
@@ -0,0 +1,231 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/artifact_groups.dart';
import '../domain/artifact_kind.dart';
import '../domain/artifact_record.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.
typedef ArtifactSelected =
void Function(ArtifactGroup group, ArtifactRecord artifact);
/// The identity of [artifact] inside [group], for
/// [ArtifactVisitList.selectedIdentity].
///
/// 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';
}
/// A read-only, selectable list of recorded artifact groups.
///
/// Each group shows its recorded stage and visit, and each row its recorded
/// filename, content type and size. Rendering uses the host's own controls:
/// Material list tiles under [MaterialApp] and grouped Cupertino list sections
/// under [CupertinoApp]. It never resolves a url, opens a preview, downloads,
/// shares or filters; the only action is [onSelected].
class ArtifactVisitList extends StatelessWidget {
const ArtifactVisitList({
super.key,
required this.groups,
this.selectedIdentity,
this.onSelected,
});
final List<ArtifactGroup> groups;
/// [artifactVisitIdentity] of the selected artifact, or null for none.
final String? selectedIdentity;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
if (groups.isEmpty) {
return const _NoArtifacts();
}
if (usesCupertinoHost(context)) {
return ListView(
children: [
for (final group in groups)
CupertinoListSection.insetGrouped(
// `container` keeps the heading a separate semantics node. Without
// it the heading merges into the neighbouring row button, so it is
// not navigable as a heading and activating it selects the row.
header: Semantics(
container: true,
header: true,
child: Text(_groupLabel(group)),
),
hasLeading: false,
children: [
for (var index = 0; index < group.artifacts.length; index += 1)
_CupertinoRow(
key: _rowKey(group, group.artifacts[index], index),
group: group,
artifact: group.artifacts[index],
selected: _isSelected(group, group.artifacts[index]),
onSelected: onSelected,
),
],
),
],
);
}
return ListView(
children: [
for (final group in groups) ...<Widget>[
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 4),
child: Semantics(
container: true,
header: true,
child: Text(_groupLabel(group)),
),
),
for (var index = 0; index < group.artifacts.length; index += 1)
_MaterialRow(
key: _rowKey(group, group.artifacts[index], index),
group: group,
artifact: group.artifacts[index],
selected: _isSelected(group, group.artifacts[index]),
onSelected: onSelected,
),
],
],
);
}
bool _isSelected(ArtifactGroup group, ArtifactRecord artifact) =>
selectedIdentity == artifactVisitIdentity(group, artifact);
static Key _rowKey(ArtifactGroup group, ArtifactRecord artifact, int index) =>
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,
required this.group,
required this.artifact,
required this.selected,
required this.onSelected,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final bool selected;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
return ListTile(
selected: selected,
title: Text(_displayName(artifact)),
subtitle: Text(_facts(artifact)),
trailing: selected ? const Icon(Icons.check) : null,
onTap: onSelected == null ? null : () => onSelected!(group, artifact),
);
}
}
class _CupertinoRow extends StatelessWidget {
const _CupertinoRow({
super.key,
required this.group,
required this.artifact,
required this.selected,
required this.onSelected,
});
final ArtifactGroup group;
final ArtifactRecord artifact;
final bool selected;
final ArtifactSelected? onSelected;
@override
Widget build(BuildContext context) {
final textTheme = CupertinoTheme.of(context).textTheme;
final factsStyle = textTheme.textStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
final content = DefaultTextStyle.merge(
style: textTheme.textStyle,
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_displayName(artifact)),
Text(_facts(artifact), style: factsStyle),
],
),
),
if (selected) const Icon(CupertinoIcons.check_mark),
],
),
);
// `container` makes this row its own semantics node, so the section
// heading stays a separate header node and never covers the row.
return Semantics(
container: true,
selected: selected,
child: SizedBox(
width: double.infinity,
// A read-only row is not a button: a disabled CupertinoButton would
// still expose a button role to assistive technology.
child: onSelected == null
? Padding(
padding: kCupertinoButtonPadding[CupertinoButtonSize.large]!,
child: content,
)
: CupertinoButton(
alignment: AlignmentDirectional.centerStart,
onPressed: () => onSelected!(group, artifact),
child: content,
),
),
);
}
}
class _NoArtifacts extends StatelessWidget {
const _NoArtifacts();
@override
Widget build(BuildContext context) {
return ListView(
children: const [
Padding(
padding: EdgeInsets.all(16),
child: Text('No stage artifacts recorded.'),
),
],
);
}
}
+17
View File
@@ -0,0 +1,17 @@
/// Public API for the run Changes feature. Integration imports this barrel:
///
/// * [ChangesViewer] - the whole run, from `run detail['steps']`.
/// * [FileDiffViewer] and [showFileDiffViewer] - one recorded file.
/// * The pure domain models/parsers/wording for tests and other surfaces.
library;
export 'domain/change_capture.dart';
export 'domain/change_kind.dart';
export 'domain/change_wording.dart';
export 'domain/file_change.dart';
export 'domain/run_changes.dart';
export 'domain/unified_patch.dart';
export 'widgets/change_style.dart' show DiffForm, usesCupertino;
export 'widgets/changes_viewer.dart';
export 'widgets/file_diff_viewer.dart';
export 'widgets/patch_view.dart';
@@ -0,0 +1,145 @@
import '../../../core/api_gateway.dart';
import 'file_change.dart';
/// One step's recorded `file_changes` capture. A null capture on a
/// [StageCapture] means the step recorded no capture at all - it must never be
/// read as "the workspace was unchanged".
class ChangeCapture {
ChangeCapture({
required this.status,
this.scope = '',
required this.files,
this.skipped = 0,
this.omitted = 0,
this.diagnostic = '',
});
final String status;
final String scope;
final List<FileChange> files;
final int skipped;
final int omitted;
final String diagnostic;
String get _state => status.trim().toLowerCase();
bool get unavailable => _state == 'unavailable';
bool get partial => _state == 'partial';
bool get complete => _state == 'complete' || _state.isEmpty;
bool get hasFiles => files.isNotEmpty;
factory ChangeCapture.fromJson(JsonMap json) {
final rawFiles = json['files'];
final files = <FileChange>[];
if (rawFiles is List) {
for (final value in rawFiles) {
final file = FileChange.tryParse(value);
if (file != null) files.add(file);
}
}
return ChangeCapture(
status: '${json['status'] ?? ''}'.trim(),
scope: '${json['scope'] ?? ''}'.trim(),
files: List.unmodifiable(files),
skipped: _count(json['skipped']),
omitted: _count(json['omitted']),
diagnostic: '${json['diagnostic'] ?? ''}'.trim(),
);
}
}
/// The honest wording for a `file_changes` value that exists but is not an
/// object. Such a record is unreadable evidence, not an observed no-change.
const malformedCaptureDetail =
'The recorded change capture could not be read, so no changes can be '
'shown. This does not mean the workspace was unchanged.';
/// One stage visit and the capture it recorded, in run order. `capture == null`
/// is missing evidence, not an observed no-change.
class StageCapture {
const StageCapture({
required this.sequence,
required this.visit,
required this.stage,
required this.stepStatus,
required this.capture,
});
/// The run-wide step ordinal, used for ordering and widget keys.
final int sequence;
/// The display visit number within [stage]: the recorded `control.visit` when
/// positive, otherwise the visit's 1-based position in its stage. Mirrors the
/// web client's `displayVisit`; [sequence] is not the visit number.
final int visit;
final String stage;
final String stepStatus;
final ChangeCapture? capture;
bool get missing => capture == null;
/// Parses one step. [position] is the step's 1-based position among the
/// steps of its own stage, used when the step recorded no `control.visit`.
factory StageCapture.fromStep(JsonMap step, {int position = 1}) {
final raw = step['file_changes'];
return StageCapture(
sequence: _count(step['sequence']),
visit: _displayVisit(step, position),
stage: _stageName(step),
stepStatus: '${step['status'] ?? ''}'.trim(),
// A non-null but malformed value still records that a capture existed;
// only null is missing evidence. A value we cannot read is unavailable,
// never a fabricated empty capture that would claim "no changes".
capture: raw == null
? null
: raw is Map
? ChangeCapture.fromJson(Map<String, dynamic>.from(raw))
: ChangeCapture(
status: 'unavailable',
files: const [],
diagnostic: malformedCaptureDetail,
),
);
}
}
/// Groups a run's steps into stage/visit captures ordered by numeric sequence,
/// stable for ties. A step with a null `file_changes` still appears so its
/// missing evidence is visible next to the captures that did record.
List<StageCapture> stageCaptures(List<JsonMap> steps) {
final indexed = <({JsonMap step, int index})>[];
for (var i = 0; i < steps.length; i++) {
indexed.add((step: steps[i], index: i));
}
indexed.sort((a, b) {
final bySequence = _count(
a.step['sequence'],
).compareTo(_count(b.step['sequence']));
return bySequence != 0 ? bySequence : a.index.compareTo(b.index);
});
// The visit position is per stage, in the same sequence order (the web
// client's displayVisit), not the run-wide step ordinal.
final positions = <String, int>{};
final captures = <StageCapture>[];
for (final entry in indexed) {
final stage = _stageName(entry.step);
final position = (positions[stage] ?? 0) + 1;
positions[stage] = position;
captures.add(StageCapture.fromStep(entry.step, position: position));
}
return captures;
}
/// The recorded `control.visit` when positive, else the stage position.
int _displayVisit(JsonMap step, int position) {
final control = step['control'];
final recorded = control is Map ? control['visit'] : null;
if (recorded is num && recorded > 0) return recorded.toInt();
return position < 1 ? 1 : position;
}
String _stageName(JsonMap step) {
final name = '${step['stage'] ?? ''}'.trim();
return name.isEmpty ? 'stage' : name;
}
int _count(dynamic value) => value is num ? value.toInt() : 0;
@@ -0,0 +1,30 @@
/// The three recorded file-change kinds plus a safe fallback for future server
/// values. Ported from `web/src/changes.js` (and the Android client's
/// `ui/changes/RunChanges.kt`) so the Flutter client says the same words.
enum ChangeKind { added, modified, deleted, other }
/// Maps a server kind token to a [ChangeKind]. The token is trimmed and
/// lowercased; an unknown or blank token stays [ChangeKind.other] rather than
/// being guessed, so a future server value is shown read-only instead of
/// mislabelled.
ChangeKind changeKind(dynamic kind) =>
switch ('${kind ?? ''}'.trim().toLowerCase()) {
'added' => ChangeKind.added,
'modified' => ChangeKind.modified,
'deleted' => ChangeKind.deleted,
_ => ChangeKind.other,
};
/// The word a file's kind is named by in the list and the diff header.
String changeKindLabel(ChangeKind kind) => switch (kind) {
ChangeKind.added => 'added',
ChangeKind.modified => 'modified',
ChangeKind.deleted => 'deleted',
ChangeKind.other => 'changed',
};
/// The kind word as the viewer header shows it, first letter capitalised.
String changeKindTitle(ChangeKind kind) {
final label = changeKindLabel(kind);
return label.isEmpty ? label : label[0].toUpperCase() + label.substring(1);
}
@@ -0,0 +1,184 @@
import 'change_capture.dart';
import 'file_change.dart';
import 'run_changes.dart';
import 'unified_patch.dart';
/// The honest messages the viewer and its tests share. Spelled once, matching
/// the web client's `web/src/changes.js`.
const binaryDiffMessage =
'This is a binary file: the server recorded the change but has no textual '
'diff to show.';
const truncatedPatchNote =
'The server truncated this patch at its capture limit; the raw text is the '
'whole record.';
const noLineChangesMessage = 'no line changes recorded';
/// A step with no capture recorded no evidence; it does not prove the workspace
/// was unchanged.
const missingCaptureDetail =
'This visit recorded no change capture (a historical step, or a stage that '
'does not capture). That does not mean the workspace was unchanged.';
const pendingCaptureDetail =
'The capture runs after the stage finishes; nothing is recorded yet.';
const unavailableCaptureDetail =
'The workspace snapshot could not be compared, so no changes can be shown.';
const emptyCaptureDetail =
'The captured snapshots were identical: the workspace was unchanged.';
const partialCaptureDetail = 'Partial capture: some changes may be missing.';
/// The Changes section header's one-line summary: the observed file count, the
/// total `+N -M`, and the honest capture caveats.
String runChangesHeader(RunChanges changes) {
if (changes.unavailable) return 'Changes · capture unavailable';
if (changes.files.isEmpty) {
if (changes.pending) return 'Changes · capture pending';
if (changes.partial) return 'Changes · partial capture';
if (changes.stepsWithChanges == 0) {
return 'Changes · not recorded for this run';
}
if (changes.missingCaptures > 0) return 'Changes · capture incomplete';
return 'Changes · no changes observed';
}
final stat = changeStat(changes.added, changes.removed);
final count = changes.files.length;
final label = stat.isEmpty
? '$count ${count == 1 ? 'file' : 'files'} changed'
: '$count ${count == 1 ? 'file' : 'files'} changed · $stat';
if (changes.partial) return '$label · partial capture';
if (changes.missingCaptures > 0) return '$label · capture incomplete';
return label;
}
/// The honest one-line note under the header for a capture that is not
/// complete, or "" when it was.
String runChangesNote(RunChanges changes) {
if (changes.unavailable) {
return changes.diagnostic.isNotEmpty
? changes.diagnostic
: 'The workspace snapshot could not be compared; the changes below may '
'be incomplete.';
}
var out = '';
if (changes.partial) {
out = partialCaptureDetail;
final caveats = <String>[];
if (changes.skipped > 0) caveats.add('${changes.skipped} files skipped');
if (changes.omitted > 0) caveats.add('${changes.omitted} omitted');
final truncated = changes.files.where((file) => file.truncated).length;
if (truncated > 0) caveats.add('$truncated truncated');
if (caveats.isNotEmpty) out += ' (${caveats.join(', ')})';
if (changes.diagnostic.isNotEmpty) out += ' ${changes.diagnostic}';
}
if (changes.missingCaptures > 0) {
if (out.isNotEmpty) out += ' ';
out +=
'Missing capture: ${changes.missingCaptures} '
'${changes.missingCaptures == 1 ? 'stage did' : 'stages did'} not '
'record changes.';
}
return out.trim();
}
/// The file list's own summary line.
String changesListSummary(RunChanges changes) {
final count =
'${changes.files.length} '
'${changes.files.length == 1 ? 'file' : 'files'} changed';
final stat = changeStat(changes.added, changes.removed);
return stat.isEmpty ? count : '$count · $stat';
}
/// Why no change is listed: a pending capture, an unavailable one, a missing
/// capture or a recorded none.
String noChangeDetail(RunChanges changes) {
if (changes.pending) return pendingCaptureDetail;
if (changes.unavailable) return unavailableCaptureDetail;
if (changes.stepsWithChanges == 0) {
return 'This run recorded no change capture (a historical step, or a stage '
'that does not capture).';
}
return emptyCaptureDetail;
}
/// Why a file has no patch to render, in the entry's own recorded terms.
String patchUnavailableReason(FileChange file) {
if (file.truncated) {
return "The server truncated this file's patch at its capture limit; no "
'diff text was recorded.';
}
if (file.otherModeChange) {
return "Only the file's mode changed (${file.beforeMode ?? ''}→"
'${file.afterMode ?? ''}); the server recorded no text diff.';
}
return 'The server recorded this change without a patch.';
}
/// The tags shown beside a file row: traits that change how the entry must be
/// read, never a fabricated diff.
List<String> changeEntryTags(FileChange file) => file.tags;
/// The row's secondary line for an aggregated entry: which stage(s) changed it
/// and how to read it.
String changeRowMeta(FileChange file) {
var out = file.steps.isEmpty ? '' : 'changed by ${file.steps.join(' → ')}';
for (final tag in changeEntryTags(file)) {
out += '${out.isEmpty ? '' : ' · '}$tag';
}
if (file.modeChanged && !file.binary) {
out +=
'${out.isEmpty ? '' : ' · '}mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}';
}
return out;
}
/// A compact per-entry line for a file row: stat, tags and mode, or the honest
/// no-line-change note. Content-driven; no fixed cell widths.
String changeFileMeta(FileChange file) {
final parts = <String>[];
final stat = changeStat(file.added, file.removed);
if (stat.isNotEmpty) parts.add(stat);
parts.addAll(file.tags);
if (file.modeChanged && !file.binary) {
parts.add('mode ${file.beforeMode ?? ''}→${file.afterMode ?? ''}');
}
return parts.isEmpty ? noLineChangesMessage : parts.join(' · ');
}
/// A compact capture summary, e.g.
/// `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`.
/// Blank parts are omitted; an entirely blank capture renders as "".
String fileChangesSummary(ChangeCapture capture) {
var text = capture.status;
if (capture.files.isNotEmpty) {
if (text.isNotEmpty) text += ' ';
text += '(${capture.files.length} files)';
}
if (capture.skipped > 0) {
if (text.isNotEmpty) text += ', ';
text += '${capture.skipped} skipped';
}
if (capture.omitted > 0) {
if (text.isNotEmpty) text += ', ';
text += '${capture.omitted} omitted';
}
if (capture.diagnostic.isNotEmpty) {
if (text.isNotEmpty) text += ' · ';
text += capture.diagnostic;
}
return text;
}
/// Filters changed filenames by a case-insensitive substring, preserving the
/// recorded order. A blank query keeps every file.
List<FileChange> filterFileChanges(Iterable<FileChange> files, String query) {
final needle = query.trim().toLowerCase();
final all = files.toList(growable: false);
if (needle.isEmpty) return all;
return all
.where((file) => file.path.toLowerCase().contains(needle))
.toList(growable: false);
}
/// The `N of M` position label a viewer can show for its open file.
String changePositionLabel(int index, int count) => '${index + 1} of $count';
@@ -0,0 +1,117 @@
import '../../../core/api_gateway.dart';
import 'change_kind.dart';
import 'unified_patch.dart';
/// One recorded file change, as the server's `file_changes.files[]` entry
/// describes it. A null/blank [patch] is a recorded fact (binary, truncated or
/// no text diff), never an invented empty diff.
class FileChange {
FileChange({
required this.path,
required this.kind,
String? patch,
this.binary = false,
this.truncated = false,
String? beforeMode,
String? afterMode,
this.steps = const [],
ParsedPatch? parsedPatch,
}) : patch = _nonBlank(patch),
beforeMode = _nonBlank(beforeMode),
afterMode = _nonBlank(afterMode),
// Aggregate copies pass their already-parsed patch through instead of
// re-parsing the same recorded bytes for every stage that touched a path.
parsedPatch = parsedPatch ?? parseUnifiedPatch(patch);
final String path;
final ChangeKind kind;
/// The server's unified patch verbatim, or null when it recorded none. This
/// exact string is what Copy patch puts on the clipboard, including any
/// trailing newline or truncated final line.
final String? patch;
final bool binary;
final bool truncated;
final String? beforeMode;
final String? afterMode;
/// Stage names that recorded a change to this path, in run order and deduped.
/// Empty for a single recorded entry; filled by [runChanges] aggregation.
final List<String> steps;
final ParsedPatch parsedPatch;
int get added => parsedPatch.added;
int get removed => parsedPatch.removed;
/// True when a patch the operator can read is present.
bool get hasPatch => !binary && patch != null;
/// True when the recorded permissions differ.
bool get modeChanged =>
beforeMode != null && afterMode != null && beforeMode != afterMode;
/// True when the recorded permissions differ and no content change explains
/// it. The server records no text diff for a mode-only change.
bool get otherModeChange =>
modeChanged && !binary && added == 0 && removed == 0;
List<String> get tags => [
if (binary) 'binary',
if (truncated) 'truncated',
if (otherModeChange) 'mode change',
];
FileChange withSteps(List<String> value) => FileChange(
path: path,
kind: kind,
patch: patch,
binary: binary,
truncated: truncated,
beforeMode: beforeMode,
afterMode: afterMode,
steps: List.unmodifiable(value),
parsedPatch: parsedPatch,
);
/// Parses one server file entry; null when it has no usable path. The
/// capture owns the decision to skip such an entry, so it is never rendered
/// as an anonymous row.
static FileChange? tryParse(dynamic value) {
if (value is! Map) return null;
final json = Map<String, dynamic>.from(value);
final path = _text(json['path']);
if (path.trim().isEmpty) return null;
return FileChange(
path: path,
kind: changeKind(json['kind']),
patch: json['patch'] is String ? json['patch'] as String : null,
binary: json['binary'] == true,
truncated: json['truncated'] == true,
beforeMode: _textOrNull(json['before_mode']),
afterMode: _textOrNull(json['after_mode']),
);
}
/// Parses a required file entry. Integration code normally receives files
/// from [ChangeCapture] or [runChanges]; this constructor is for a viewer
/// opened directly with one recorded entry.
factory FileChange.fromJson(JsonMap json) {
final file = tryParse(json);
if (file == null) {
throw const FormatException('A recorded file change needs a path.');
}
return file;
}
}
/// A value kept as itself when present, else null (`?:` over nullable fields).
String? _textOrNull(dynamic value) => value == null ? null : '$value';
String _text(dynamic value) => '${value ?? ''}';
/// A string kept only when it has non-whitespace content.
String? _nonBlank(String? value) {
if (value == null) return null;
return value.trim().isEmpty ? null : value;
}
@@ -0,0 +1,59 @@
/// Patch value objects produced by the unified-patch parser. Kept separate from
/// the parser so widgets import the smallest model they need.
library;
enum ChangeLineKind { context, add, remove }
class PatchLine {
const PatchLine({
required this.kind,
required this.text,
required this.oldLine,
required this.newLine,
this.noNewlineMarker = false,
});
final ChangeLineKind kind;
final String text;
final int oldLine;
final int newLine;
/// A `\ No newline at end of file` marker: shown verbatim, never numbered.
final bool noNewlineMarker;
}
class PatchHunk {
const PatchHunk({
required this.header,
required this.oldStart,
required this.oldCount,
required this.newStart,
required this.newCount,
required this.lines,
});
final String header;
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
final List<PatchLine> lines;
}
class ParsedPatch {
const ParsedPatch({
required this.raw,
required this.headerLines,
required this.hunks,
required this.added,
required this.removed,
});
final String raw;
final List<String> headerLines;
final List<PatchHunk> hunks;
final int added;
final int removed;
bool get isEmpty => hunks.isEmpty;
}
@@ -0,0 +1,102 @@
import '../../../core/api_gateway.dart';
import 'change_capture.dart';
import 'file_change.dart';
/// The run-level final-state aggregate of recorded file captures. Ported from
/// `web/src/changes.js` `runChanges`:
///
/// * a null `file_changes` is missing evidence (pending while the step is
/// running/waiting), never "no changes";
/// * a present capture with no files is a real, observed no-change;
/// * a path recorded by several visits is one entry, in first-seen order, whose
/// per-file facts come from the last recorded visit (the run's final state);
/// * capture counters and caveats describe every contributing step.
class RunChanges {
const RunChanges({
required this.files,
required this.stepsWithChanges,
required this.stepsPending,
required this.added,
required this.removed,
required this.partial,
required this.unavailable,
required this.pending,
required this.missingCaptures,
required this.skipped,
required this.omitted,
required this.diagnostic,
});
final List<FileChange> files;
final int stepsWithChanges;
final int stepsPending;
final int added;
final int removed;
final bool partial;
final bool unavailable;
final bool pending;
final int missingCaptures;
final int skipped;
final int omitted;
final String diagnostic;
}
RunChanges runChanges(List<JsonMap> steps) =>
runChangesFor(stageCaptures(steps));
/// The same aggregate over already-derived [stageCaptures], so a caller that
/// shows both the summary and the sections parses each capture only once.
RunChanges runChangesFor(List<StageCapture> visits) {
final entries = <String, FileChange>{};
var stepsWithChanges = 0;
var stepsPending = 0;
var partial = false;
var unavailable = false;
var missingCaptures = 0;
var skipped = 0;
var omitted = 0;
var truncatedSeen = false;
final diagnostics = <String>{};
for (final visit in visits) {
final capture = visit.capture;
if (capture == null) {
final status = visit.stepStatus.trim().toLowerCase();
if (status == 'running' || status == 'waiting') {
stepsPending++;
} else {
missingCaptures++;
}
continue;
}
stepsWithChanges++;
if (capture.unavailable) unavailable = true;
if (capture.partial) partial = true;
if (capture.diagnostic.isNotEmpty) diagnostics.add(capture.diagnostic);
skipped += capture.skipped;
omitted += capture.omitted;
for (final file in capture.files) {
if (file.truncated) truncatedSeen = true;
final existing = entries[file.path];
final names = existing == null ? <String>[] : [...existing.steps];
if (!names.contains(visit.stage)) names.add(visit.stage);
entries[file.path] = file.withSteps(names);
}
}
final files = entries.values.toList(growable: false);
return RunChanges(
files: List.unmodifiable(files),
stepsWithChanges: stepsWithChanges,
stepsPending: stepsPending,
added: files.fold(0, (sum, file) => sum + file.added),
removed: files.fold(0, (sum, file) => sum + file.removed),
partial: partial || truncatedSeen || omitted > 0,
unavailable: unavailable,
pending: stepsWithChanges == 0 && stepsPending > 0,
missingCaptures: missingCaptures,
skipped: skipped,
omitted: omitted,
diagnostic: diagnostics.join(' '),
);
}
@@ -0,0 +1,239 @@
/// Parses a server-recorded unified patch into hunks, lines and the true
/// `+N -M` stat. Ported from `web/src/changes.js` so the Flutter viewer numbers
/// and groups lines exactly like the browser and Android clients.
///
/// The server builds these patches with the Go `internal/filediff` writer: a
/// standard `---`/`+++` header, optional metadata, `@@ -a,b +c,d @@` hunk
/// headers and a ` `/`+`/`-` body. Anything unrecognised before the first hunk
/// is carried verbatim in [ParsedPatch.headerLines]; a truncated tail or exotic
/// marker inside a hunk stays an unnumbered context line. The raw patch is
/// always retained byte-for-byte so Copy patch never rewrites the record.
library;
export 'patch_models.dart';
import 'patch_models.dart';
const _emptyPatch = ParsedPatch(
raw: '',
headerLines: [],
hunks: [],
added: 0,
removed: 0,
);
/// Parses a patch with the same total behaviour as the browser: a blank or
/// absent patch is an empty result, never a fabricated diff.
ParsedPatch parseUnifiedPatch(dynamic patch) {
final text = patch == null ? '' : '$patch';
if (text.trim().isEmpty) return _emptyPatch;
final headers = <String>[];
final hunks = <PatchHunk>[];
_HunkBuilder? current;
for (final line in text.split('\n')) {
final start = _parseHunkHeader(line);
if (start != null) {
if (current != null) hunks.add(current.build());
current = _HunkBuilder(line, start);
} else if (line.startsWith('--- ') || line.startsWith('+++ ')) {
// An aggregated entry can contain one complete patch per contributing
// stage. A new file header closes the preceding hunk instead of becoming
// an unnumbered context line inside it.
if (current != null) {
hunks.add(current.build());
current = null;
}
headers.add(line);
} else if (current == null) {
headers.add(line);
} else {
current.lines.add(current.parseBody(line));
}
}
if (current != null) hunks.add(current.build());
var added = 0;
var removed = 0;
for (final hunk in hunks) {
for (final line in hunk.lines) {
if (line.kind == ChangeLineKind.add) {
added++;
} else if (line.kind == ChangeLineKind.remove) {
removed++;
}
}
}
return ParsedPatch(
raw: text,
headerLines: headers,
hunks: hunks,
added: added,
removed: removed,
);
}
/// Mutable accumulator carrying the running old/new counters so each body line
/// is numbered in one pass.
class _HunkBuilder {
_HunkBuilder(this.header, _HunkStart start)
: oldStart = start.oldStart,
oldCount = start.oldCount,
newStart = start.newStart,
newCount = start.newCount,
oldLine = start.oldStart,
newLine = start.newStart;
final String header;
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
final List<PatchLine> lines = [];
int oldLine;
int newLine;
PatchHunk build() => PatchHunk(
header: header,
oldStart: oldStart,
oldCount: oldCount,
newStart: newStart,
newCount: newCount,
lines: List.unmodifiable(lines),
);
PatchLine parseBody(String line) {
if (line.startsWith('+')) {
return PatchLine(
kind: ChangeLineKind.add,
text: line.substring(1),
oldLine: 0,
newLine: newLine++,
);
}
if (line.startsWith('-')) {
return PatchLine(
kind: ChangeLineKind.remove,
text: line.substring(1),
oldLine: oldLine++,
newLine: 0,
);
}
if (line.startsWith('\\')) {
return PatchLine(
kind: ChangeLineKind.context,
text: line,
oldLine: 0,
newLine: 0,
noNewlineMarker: true,
);
}
if (line.startsWith(' ')) {
return PatchLine(
kind: ChangeLineKind.context,
text: line.substring(1),
oldLine: oldLine++,
newLine: newLine++,
);
}
if (line.isEmpty) {
return PatchLine(
kind: ChangeLineKind.context,
text: '',
oldLine: oldLine++,
newLine: newLine++,
);
}
// A truncated tail or an unexpected marker: keep the text, do not number it.
return PatchLine(
kind: ChangeLineKind.context,
text: line,
oldLine: 0,
newLine: 0,
);
}
}
class _HunkStart {
const _HunkStart(this.oldStart, this.oldCount, this.newStart, this.newCount);
final int oldStart;
final int oldCount;
final int newStart;
final int newCount;
}
_HunkStart? _parseHunkHeader(String line) {
if (!line.startsWith('@@')) return null;
final end = line.indexOf('@@', 2);
if (end < 0) return null;
final ranges = _tokenizeRanges(line.substring(2, end));
return ranges == null
? null
: _HunkStart(ranges[0], ranges[1], ranges[2], ranges[3]);
}
List<int>? _tokenizeRanges(String body) {
final plus = body.indexOf('+');
final old = plus == -1 ? body : body.substring(0, plus);
final next = plus == -1 ? '' : body.substring(plus + 1);
if (old.isEmpty || next.isEmpty) return null;
final oldRange = _parseRange(old);
if (oldRange == null) return null;
final newRange = _parseRange(next);
if (newRange == null) return null;
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
}
List<int>? _parseRange(String text) {
var trimmed = text.trim();
if (trimmed.startsWith('-') || trimmed.startsWith('+')) {
trimmed = trimmed.substring(1);
}
if (trimmed.isEmpty) return null;
final comma = trimmed.indexOf(',');
final startText = (comma == -1 ? trimmed : trimmed.substring(0, comma))
.trim();
final start = _intOrNull(startText);
if (start == null) return null;
final countText = (comma == -1 ? '' : trimmed.substring(comma + 1)).trim();
final count = countText.isEmpty ? 1 : _intOrNull(countText);
if (count == null) return null;
return [start, count];
}
int? _intOrNull(String text) =>
RegExp(r'^[+-]?\d+$').hasMatch(text) ? int.tryParse(text) : null;
/// The widest line number in a hunk, so its gutter lines up across every row.
int gutterWidth(PatchHunk hunk) {
var widest = 0;
for (final line in hunk.lines) {
if (line.oldLine > widest) widest = line.oldLine;
if (line.newLine > widest) widest = line.newLine;
}
return '${widest < 1 ? 1 : widest}'.length;
}
/// One gutter number padded to [width]; 0 means no number on that side.
String gutterText(int value, int width) =>
value > 0 ? '$value'.padLeft(width) : ' ' * width;
/// The gutter symbol one line kind is drawn with (`+`/`-`/space).
String diffLineSymbol(ChangeLineKind kind) => switch (kind) {
ChangeLineKind.add => '+',
ChangeLineKind.remove => '-',
ChangeLineKind.context => ' ',
};
/// The `+N -M` stat, or "" when both counts are zero. Shared by every renderer.
String changeStat(int added, int removed) {
var out = '';
if (added > 0) out += '+$added';
if (removed > 0) {
if (out.isNotEmpty) out += ' ';
out += '-$removed';
}
return out;
}
@@ -0,0 +1,238 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/change_capture.dart';
import '../domain/change_kind.dart';
import '../domain/change_wording.dart';
import '../domain/file_change.dart';
import 'change_style.dart';
/// One stage/visit capture: its honest status, scope, counters and diagnostic,
/// followed by the recorded file rows. Missing and unavailable captures are
/// shown as evidence gaps, never as an observed no-change.
class StageCaptureSection extends StatelessWidget {
const StageCaptureSection({
super.key,
required this.stage,
required this.query,
required this.onOpen,
});
final StageCapture stage;
final String query;
final ValueChanged<FileChange> onOpen;
@override
Widget build(BuildContext context) {
final capture = stage.capture;
final filtered = capture == null
? const <FileChange>[]
: filterFileChanges(capture.files, query);
// The aggregate trims and lowercases the status before testing it; do the
// same here so the section and the run header always agree.
final status = stage.stepStatus.trim().toLowerCase();
final pending =
capture == null && (status == 'running' || status == 'waiting');
final meta = [
'Visit ${stage.visit}',
if (stage.stepStatus.isNotEmpty) stage.stepStatus,
].join(' · ');
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(stage.stage, style: Theme.of(context).textTheme.titleMedium),
Text(meta, style: Theme.of(context).textTheme.bodySmall),
if (capture != null) ...[
Text(
fileChangesSummary(capture),
style: Theme.of(context).textTheme.bodySmall,
),
if (capture.scope.isNotEmpty)
Text(
'Scope: ${capture.scope}',
style: Theme.of(context).textTheme.bodySmall,
),
],
],
),
),
const Divider(height: 1),
if (capture == null)
_CaptureNote(
icon: _noteIcon(
context,
pending ? _NoteKind.pending : _NoteKind.missing,
),
title: pending ? 'Capture pending' : 'Capture unavailable',
detail: pending ? pendingCaptureDetail : missingCaptureDetail,
)
else if (capture.unavailable)
_CaptureNote(
icon: _noteIcon(context, _NoteKind.unavailable),
title: 'Capture unavailable',
detail: capture.diagnostic.isEmpty
? unavailableCaptureDetail
: capture.diagnostic,
)
else if (capture.files.isEmpty)
_CaptureNote(
icon: _noteIcon(
context,
capture.partial ? _NoteKind.partial : _NoteKind.empty,
),
title: capture.partial ? 'Partial capture' : 'No changes observed',
detail: capture.partial ? partialCaptureDetail : emptyCaptureDetail,
)
else if (filtered.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Text('No changed filenames match "$query".'),
)
else
for (final file in filtered)
_FileRow(
key: ValueKey('change-${stage.sequence}-${file.path}'),
file: file,
onOpen: onOpen,
),
],
);
}
}
class _FileRow extends StatelessWidget {
const _FileRow({super.key, required this.file, required this.onOpen});
final FileChange file;
final ValueChanged<FileChange> onOpen;
@override
Widget build(BuildContext context) {
final mono = nativeDiffText(DefaultTextStyle.of(context).style);
final cupertino = usesCupertino(context);
final leading = Icon(_kindIcon(context, file.kind));
final title = Text(file.path, style: mono);
final subtitle = Text(changeFileMeta(file));
final trailing = cupertino
? const CupertinoListTileChevron()
: const Icon(Icons.chevron_right);
return Semantics(
container: true,
button: true,
// Announce the visible kind and meta too; the row's icon and subtitle are
// excluded from the semantic tree by [excludeSemantics].
label:
'Open diff for ${file.path}. '
'${changeKindTitle(file.kind)} · ${changeFileMeta(file)}',
excludeSemantics: true,
onTap: () => onOpen(file),
child: cupertino
? CupertinoListTile(
leading: leading,
// A recorded path is the row's identity, so it wraps instead of
// being ellipsized to one line.
title: _unclampedText(title),
subtitle: _unclampedText(subtitle),
trailing: trailing,
onTap: () => onOpen(file),
)
: ListTile(
leading: leading,
title: title,
subtitle: subtitle,
trailing: trailing,
onTap: () => onOpen(file),
),
);
}
}
/// CupertinoListTile caps its title and subtitle at one ellipsized line through
/// the inherited [DefaultTextStyle]. Re-establish the ambient style without that
/// cap so a long recorded path stays readable; the tile keeps its native
/// padding, pressed state and chevron.
Widget _unclampedText(Widget child) {
return Builder(
builder: (context) {
final inherited = DefaultTextStyle.of(context);
return DefaultTextStyle(
style: inherited.style,
softWrap: true,
overflow: TextOverflow.visible,
textAlign: inherited.textAlign,
textWidthBasis: inherited.textWidthBasis,
textHeightBehavior: inherited.textHeightBehavior,
child: child,
);
},
);
}
class _CaptureNote extends StatelessWidget {
const _CaptureNote({
required this.icon,
required this.title,
required this.detail,
});
final IconData icon;
final String title;
final String detail;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(title, style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: 4),
Text(detail),
],
),
),
],
),
);
}
}
enum _NoteKind { missing, unavailable, empty, partial, pending }
IconData _noteIcon(BuildContext context, _NoteKind kind) {
final cupertino = usesCupertino(context);
return switch (kind) {
_NoteKind.missing || _NoteKind.unavailable =>
cupertino ? CupertinoIcons.exclamationmark_triangle : Icons.warning_amber,
_NoteKind.empty =>
cupertino ? CupertinoIcons.checkmark_circle : Icons.check_circle_outline,
_NoteKind.partial => cupertino ? CupertinoIcons.info : Icons.info_outline,
_NoteKind.pending => cupertino ? CupertinoIcons.clock : Icons.schedule,
};
}
IconData _kindIcon(BuildContext context, ChangeKind kind) {
final cupertino = usesCupertino(context);
return switch (kind) {
ChangeKind.added =>
cupertino ? CupertinoIcons.add_circled : Icons.add_circle_outline,
ChangeKind.deleted =>
cupertino ? CupertinoIcons.trash : Icons.delete_outline,
ChangeKind.modified =>
cupertino ? CupertinoIcons.pencil : Icons.edit_outlined,
ChangeKind.other =>
cupertino ? CupertinoIcons.doc : Icons.description_outlined,
};
}
@@ -0,0 +1,151 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/unified_patch.dart';
/// Which form of a recorded patch the viewer is showing.
enum DiffForm { rendered, raw }
/// The app's established platform switch: Material for Android/desktop/web,
/// Cupertino for iOS and macOS. Feature widgets stay portable across all three
/// targets instead of hard-coding one control set.
bool usesCupertino(BuildContext context) {
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
}
/// Patch text inherits the host's typography, including its font and scaler.
/// A diff is not an exception to the native-defaults requirement.
TextStyle nativeDiffText(TextStyle base) => base;
/// Native semantic colours, never a bespoke diff palette. The recorded +/-
/// markers carry meaning independently of colour. No background tint is added.
({Color text, Color? background}) diffLineColors(
BuildContext context,
ChangeLineKind kind,
) {
return switch (kind) {
ChangeLineKind.add => (
text: usesCupertino(context)
? CupertinoColors.systemGreen.resolveFrom(context)
: Theme.of(context).colorScheme.primary,
background: null,
),
ChangeLineKind.remove => (
text: usesCupertino(context)
? CupertinoColors.destructiveRed.resolveFrom(context)
: Theme.of(context).colorScheme.error,
background: null,
),
ChangeLineKind.context => (text: labelColor(context), background: null),
};
}
/// The plain body/label colour for non-diff text inside the viewer.
Color labelColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.label.resolveFrom(context)
: Theme.of(context).colorScheme.onSurface;
/// The muted colour for gutters, notes and secondary metadata.
Color mutedColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
/// The hunk header's fill.
Color hunkHeaderColor(BuildContext context) => usesCupertino(context)
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHighest;
/// The viewer's shared Rendered/Raw control: a native segmented control on each
/// platform, with the same two words the browser uses.
Widget diffFormControl(
BuildContext context, {
required DiffForm form,
required ValueChanged<DiffForm> onChanged,
}) {
if (usesCupertino(context)) {
return CupertinoSlidingSegmentedControl<DiffForm>(
groupValue: form,
onValueChanged: (value) {
if (value != null) onChanged(value);
},
children: const {
DiffForm.rendered: _SegmentLabel('Rendered'),
DiffForm.raw: _SegmentLabel('Raw patch'),
},
);
}
return SegmentedButton<DiffForm>(
segments: const [
ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')),
ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')),
],
selected: {form},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) onChanged(selection.first);
},
);
}
class _SegmentLabel extends StatelessWidget {
const _SegmentLabel(this.label);
final String label;
@override
Widget build(BuildContext context) =>
Padding(padding: const EdgeInsets.all(6), child: Text(label));
}
/// Copy the server's raw patch exactly as recorded. Disabled when the entry has
/// no readable patch, so the action never copies a fabricated empty diff.
Widget copyPatchControl(
BuildContext context, {
required bool enabled,
required bool copied,
required VoidCallback onPressed,
}) {
final label = copied ? 'Copied' : 'Copy patch';
if (usesCupertino(context)) {
return CupertinoButton(
padding: EdgeInsets.zero,
onPressed: enabled ? onPressed : null,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(CupertinoIcons.doc_on_doc),
const SizedBox(width: 8),
Text(label),
],
),
);
}
return TextButton.icon(
onPressed: enabled ? onPressed : null,
icon: const Icon(Icons.copy_all_outlined),
label: Text(label),
);
}
/// The standard close action, labelled exactly on both platforms.
Widget closeDiffControl(BuildContext context, VoidCallback onClose) {
if (usesCupertino(context)) {
return Semantics(
label: 'Close diff',
button: true,
excludeSemantics: true,
onTap: onClose,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onClose,
child: const Icon(CupertinoIcons.xmark),
),
);
}
return IconButton(
tooltip: 'Close diff',
onPressed: onClose,
icon: const Icon(Icons.close),
);
}
@@ -0,0 +1,189 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/change_capture.dart';
import '../domain/change_wording.dart';
import '../domain/run_changes.dart';
import 'capture_section.dart';
import 'change_style.dart';
import 'file_diff_viewer.dart';
/// The run's Changes surface: an honest final-state summary followed by one
/// section per stage/visit capture, with changed-filename filtering and the
/// reusable single-file diff viewer.
///
/// The viewer fills the available height, so give it a bounded parent (a
/// Scaffold body, tab body or Expanded child). It never opens its own socket or
/// requests data; the caller passes the run detail's `steps`.
class ChangesViewer extends StatefulWidget {
const ChangesViewer({super.key, required this.steps});
/// The run detail's steps exactly as the server returned them. Each step's
/// `file_changes` may be null (no capture), a complete/partial/unavailable
/// capture, or a capture with zero files (a recorded no-change).
///
/// Pass a stable list: the same instance until the server reply changes. The
/// captures and the summary are derived from it rather than on every rebuild.
final List<JsonMap> steps;
@override
State<ChangesViewer> createState() => _ChangesViewerState();
}
class _ChangesViewerState extends State<ChangesViewer> {
final _filter = TextEditingController();
late List<StageCapture> _captures;
late RunChanges _run;
@override
void initState() {
super.initState();
_derive();
}
@override
void didUpdateWidget(ChangesViewer oldWidget) {
super.didUpdateWidget(oldWidget);
// Filter keystrokes rebuild this widget with the same steps list; only a
// new server reply re-derives the captures and the aggregate.
if (!identical(oldWidget.steps, widget.steps)) _derive();
}
void _derive() {
_captures = stageCaptures(widget.steps);
_run = runChangesFor(_captures);
}
@override
void dispose() {
_filter.dispose();
super.dispose();
}
String get _query => _filter.text;
@override
Widget build(BuildContext context) {
final run = _run;
final captures = _captures;
final hasFiles = captures.any(
(visit) => visit.capture?.files.isNotEmpty ?? false,
);
final note = runChangesNote(run);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
runChangesHeader(run),
style: Theme.of(context).textTheme.titleMedium,
),
if (note.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(
note,
style: Theme.of(context).textTheme.bodySmall,
),
),
if (hasFiles)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'The summary counts each path once, as the last recorded '
'visit left it. Each stage/visit below lists what its own '
'capture recorded.',
style: Theme.of(context).textTheme.bodySmall,
),
),
],
),
),
if (hasFiles)
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: _filterField(context, run),
),
const Divider(height: 1),
Expanded(
child: captures.isEmpty
? SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Text(noChangeDetail(run)),
)
: ListView.builder(
itemCount: captures.length,
itemBuilder: (context, index) {
final visit = captures[index];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
StageCaptureSection(
stage: visit,
query: _query,
onOpen: (file) => showFileDiffViewer(context, file),
),
const Divider(height: 1),
],
);
},
),
),
],
);
}
Widget _filterField(BuildContext context, RunChanges run) {
final query = _query;
final matched = query.trim().isEmpty
? run.files.length
: filterFileChanges(run.files, query).length;
// The summary counts paths while the sections below list one row per stage
// visit, so the counter names what it actually counts.
final counter = query.trim().isEmpty
? ''
: '$matched of ${run.files.length} changed '
'${run.files.length == 1 ? 'path' : 'paths'} match';
final field = usesCupertino(context)
? CupertinoSearchTextField(
controller: _filter,
placeholder: 'Filter changed files',
onChanged: (_) => setState(() {}),
)
: TextField(
controller: _filter,
decoration: InputDecoration(
labelText: 'Filter changed files',
hintText: 'Filename contains…',
prefixIcon: const Icon(Icons.search),
suffixIcon: query.isEmpty
? null
: IconButton(
tooltip: 'Clear filter',
onPressed: () {
_filter.clear();
setState(() {});
},
icon: const Icon(Icons.clear),
),
),
onChanged: (_) => setState(() {}),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
field,
if (counter.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Text(counter, style: Theme.of(context).textTheme.bodySmall),
),
],
);
}
}
@@ -0,0 +1,254 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../domain/change_kind.dart';
import '../domain/change_wording.dart';
import '../domain/file_change.dart';
import '../domain/unified_patch.dart';
import 'change_style.dart';
import 'patch_view.dart';
/// The reusable viewer for one recorded file change: its kind, path, stat,
/// tags, the rendered or raw unified patch, Copy patch (the server's exact
/// bytes) and Close. Binary/truncated/mode-only/no-patch entries show an honest
/// reason instead of a fabricated diff.
class FileDiffViewer extends StatefulWidget {
const FileDiffViewer({super.key, required this.file, this.onClose});
final FileChange file;
/// Called by the Close control. Defaults to popping the enclosing route.
final VoidCallback? onClose;
@override
State<FileDiffViewer> createState() => _FileDiffViewerState();
}
class _FileDiffViewerState extends State<FileDiffViewer> {
DiffForm _form = DiffForm.rendered;
bool _copied = false;
Timer? _copyTimer;
@override
void dispose() {
_copyTimer?.cancel();
super.dispose();
}
void _close() {
final close = widget.onClose;
if (close != null) {
close();
} else {
Navigator.of(context).maybePop();
}
}
Future<void> _copy() async {
final patch = widget.file.patch;
if (patch == null) return;
await Clipboard.setData(ClipboardData(text: patch));
if (!mounted) return;
setState(() => _copied = true);
_copyTimer?.cancel();
_copyTimer = Timer(const Duration(seconds: 2), () {
if (mounted) setState(() => _copied = false);
});
}
@override
Widget build(BuildContext context) {
final file = widget.file;
final cupertino = usesCupertino(context);
final base = DefaultTextStyle.of(context).style;
final mono = nativeDiffText(base);
final stat = changeStat(file.added, file.removed);
final tags = changeEntryTags(file);
return ConstrainedBox(
key: const ValueKey('file-diff-viewer'),
constraints: BoxConstraints(
maxWidth: 900,
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Semantics(
container: true,
header: true,
excludeSemantics: true,
label: [
changeKindTitle(file.kind),
if (stat.isNotEmpty) stat,
if (tags.isNotEmpty) tags.join(' · '),
'for ${file.path}',
if (file.steps.isNotEmpty)
'changed by ${file.steps.join(' → ')}',
if (file.modeChanged && !file.binary)
'mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}',
].join(', '),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 12,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Text(
changeKindTitle(file.kind),
style: Theme.of(context).textTheme.titleMedium,
),
if (stat.isNotEmpty) Text(stat, style: mono),
if (tags.isNotEmpty)
Text(
tags.join(' · '),
style: Theme.of(context).textTheme.bodySmall,
),
],
),
const SizedBox(height: 4),
Text(file.path, style: mono),
if (file.steps.isNotEmpty)
Text(
'changed by ${file.steps.join(' → ')}',
style: Theme.of(context).textTheme.bodySmall,
),
if (file.modeChanged && !file.binary)
Text(
'mode ${file.beforeMode ?? ''}→'
'${file.afterMode ?? ''}',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
),
),
closeDiffControl(context, _close),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Wrap(
spacing: 8,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (file.hasPatch)
diffFormControl(
context,
form: _form,
onChanged: (value) => setState(() => _form = value),
),
copyPatchControl(
context,
enabled: file.hasPatch,
copied: _copied,
onPressed: _copy,
),
],
),
),
Divider(
height: 16,
color: cupertino
? CupertinoColors.separator.resolveFrom(context)
: Theme.of(context).dividerColor,
),
Flexible(child: _body(context, cupertino, mono)),
],
),
);
}
Widget _body(BuildContext context, bool cupertino, TextStyle mono) {
final file = widget.file;
if (file.binary) return _message(context, binaryDiffMessage);
if (!file.hasPatch) {
return _message(context, patchUnavailableReason(file));
}
if (_form == DiffForm.raw) {
return Semantics(
container: true,
label: 'Raw patch for ${file.path}',
value: file.patch,
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
child: SingleChildScrollView(
// Raw patch bytes are one line each: scroll them sideways like the
// web view instead of wrapping a continuation under a new line.
scrollDirection: Axis.horizontal,
child: ExcludeSemantics(
child: SelectionArea(
child: Text(
file.patch!,
style: mono,
softWrap: false,
overflow: TextOverflow.visible,
),
),
),
),
),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.only(bottom: 16),
child: PatchView(file: file),
);
}
Widget _message(BuildContext context, String text) {
return SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
child: Text(text),
);
}
}
/// Open [file] in the platform's standard modal: a Material dialog on
/// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS.
Future<void> showFileDiffViewer(BuildContext context, FileChange file) {
final cupertino = usesCupertino(context);
Widget buildDialog(BuildContext dialogContext) {
final viewer = FileDiffViewer(
file: file,
onClose: () => Navigator.of(dialogContext).pop(),
);
if (cupertino) {
// A popup surface spans the window unless it is inset; on a phone the
// screen edge would clip its native rounded corners.
final width = MediaQuery.sizeOf(dialogContext).width;
return Padding(
padding: EdgeInsets.symmetric(
horizontal: width < 600 ? 16 : 40,
vertical: 24,
),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 900),
child: CupertinoPopupSurface(child: SafeArea(child: viewer)),
),
),
);
}
return Dialog(child: SafeArea(child: viewer));
}
if (cupertino) {
return showCupertinoDialog<void>(context: context, builder: buildDialog);
}
return showDialog<void>(context: context, builder: buildDialog);
}
@@ -0,0 +1,193 @@
import 'package:flutter/material.dart';
import '../domain/change_wording.dart';
import '../domain/file_change.dart';
import '../domain/unified_patch.dart';
import 'change_style.dart';
/// The rendered reading of one recorded unified patch: each hunk's `@@` header,
/// the shared diff line language (`+`/`-`/space) and the old/new gutter numbers.
/// This is the only custom drawing in the feature; everything around it is a
/// standard platform control.
class PatchView extends StatelessWidget {
const PatchView({super.key, required this.file});
final FileChange file;
@override
Widget build(BuildContext context) {
final parsed = file.parsedPatch;
final base = nativeDiffText(DefaultTextStyle.of(context).style);
final stat = changeStat(parsed.added, parsed.removed);
return Semantics(
container: true,
label: 'Rendered diff for ${file.path}',
value: stat.isEmpty ? noLineChangesMessage : stat,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: ExcludeSemantics(
child: _StatLine(
added: parsed.added,
removed: parsed.removed,
base: base,
),
),
),
if (file.truncated)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Text(
truncatedPatchNote,
style: base.copyWith(color: mutedColor(context)),
),
),
// The web rendered view shows hunks, not the recorded `---`/`+++`
// file headers (they stay in the Raw view), so the dialog does not
// show a long header clipped at its edge.
for (final hunk in parsed.hunks) _HunkView(hunk: hunk),
],
),
);
}
}
/// `+N` in the add colour and `-M` in the remove colour, or the honest note when
/// the patch records no changed line.
class _StatLine extends StatelessWidget {
const _StatLine({
required this.added,
required this.removed,
required this.base,
});
final int added;
final int removed;
final TextStyle base;
@override
Widget build(BuildContext context) {
if (added == 0 && removed == 0) {
return Text(
noLineChangesMessage,
style: base.copyWith(color: mutedColor(context)),
);
}
return Text.rich(
TextSpan(
children: [
if (added > 0)
TextSpan(
text: '+$added',
style: base.copyWith(
color: diffLineColors(context, ChangeLineKind.add).text,
),
),
if (added > 0 && removed > 0) TextSpan(text: ' ', style: base),
if (removed > 0)
TextSpan(
text: '-$removed',
style: base.copyWith(
color: diffLineColors(context, ChangeLineKind.remove).text,
),
),
],
),
);
}
}
class _HunkView extends StatelessWidget {
const _HunkView({required this.hunk});
final PatchHunk hunk;
@override
Widget build(BuildContext context) {
final base = nativeDiffText(DefaultTextStyle.of(context).style);
final width = gutterWidth(hunk);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: hunkHeaderColor(context),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
child: Text(hunk.header, style: base),
),
LayoutBuilder(
builder: (context, constraints) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
// At least the dialog's width, so a short hunk still paints
// full-width bands; wider content scrolls sideways.
constraints: BoxConstraints(minWidth: constraints.maxWidth),
// The widest recorded line sets the hunk's content width, so
// every line tint is a full-width band instead of a bar as long
// as its own text.
child: IntrinsicWidth(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < hunk.lines.length; index++)
_LineRow(
key: ValueKey('diff-line-$index'),
line: hunk.lines[index],
width: width,
base: base,
),
],
),
),
),
);
},
),
],
);
}
}
class _LineRow extends StatelessWidget {
const _LineRow({
super.key,
required this.line,
required this.width,
required this.base,
});
final PatchLine line;
final int width;
final TextStyle base;
@override
Widget build(BuildContext context) {
final gutter = line.noNewlineMarker
? ' ' * (width * 2 + 1)
: '${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}';
final colors = diffLineColors(context, line.kind);
final content = '${diffLineSymbol(line.kind)} ${line.text}';
return Container(
color: colors.background,
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
child: Text.rich(
TextSpan(
children: [
TextSpan(
text: gutter,
style: base.copyWith(color: mutedColor(context)),
),
TextSpan(
text: content,
style: base.copyWith(color: colors.text),
),
],
),
softWrap: false,
overflow: TextOverflow.visible,
),
);
}
}
@@ -0,0 +1,215 @@
import '../../../core/api_gateway.dart';
const webChatClient = 'Web';
String nativeChatMessageId(String operationId) {
final compact = operationId.replaceAll(RegExp('[^A-Za-z0-9]'), '');
final capped = compact.length > 120 ? compact.substring(0, 120) : compact;
return capped.isEmpty ? '' : 'msg_$capped';
}
/// Chat wire adapter. ApiGateway supplies request ids and returns full envelopes.
class ChatRepository {
ChatRepository(this.gateway);
final ApiGateway gateway;
Future<List<JsonMap>> sessions() async =>
_maps((await gateway.call('chat_sessions'))['chat_sessions']);
Future<JsonMap> models(String sessionId) async {
final reply = await gateway.call('chat_models', {
'chat_query': {'session_id': sessionId},
});
final catalog = reply['chat_models'];
return catalog is Map ? Map<String, dynamic>.from(catalog) : {};
}
Future<JsonMap> selectModel(
String sessionId,
String provider,
String model,
) => gateway.call('chat_model', {
'chat_model': {
'session_id': sessionId,
'provider': provider,
'model': model,
},
});
Future<List<JsonMap>> shells(String sessionId) async => _maps(
(await gateway.call('chat_shells', {
'chat_query': {'session_id': sessionId},
}))['chat_shells'],
);
Future<List<String>> directories() async {
final value = (await gateway.call('chat_directories'))['chat_directories'];
if (value is! List) {
throw StateError('Server did not return chat directories.');
}
return value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
}
Future<List<String>> backends() async {
final value = (await gateway.call('chat_backends'))['chat_backends'];
if (value is! List) {
throw StateError('Server did not return chat backends.');
}
final result = value
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
if (result.isEmpty) throw StateError('Server returned no chat backends.');
return result;
}
Future<JsonMap> shellOutput(
String sessionId,
String shellId, {
int cursor = 0,
int limit = 65536,
}) => gateway.call('chat_shell_output', {
'chat_shell_output_query': {
'session_id': sessionId,
'shell_id': shellId,
'cursor': cursor,
'limit': limit,
},
});
Future<JsonMap> history(
String sessionId, {
int limit = 200,
String cursor = '',
}) async {
final reply = await gateway.call('chat_messages', {
'chat_query': {'session_id': sessionId, 'limit': limit, 'cursor': cursor},
});
final page = reply['chat_history'];
if (page is Map) {
return {
'messages': _maps(page['messages']),
'nextCursor': '${page['next_cursor'] ?? ''}',
'hasMore': page['has_more'] == true,
};
}
return {
'messages': _maps(reply['chat_messages']),
'nextCursor': '',
'hasMore': false,
};
}
Future<JsonMap> subscribe(String sessionId) =>
gateway.call('chat_subscribe', {
'chat_subscribe': {'session_id': sessionId},
});
Future<JsonMap> create({
required String title,
required String directory,
required String operationId,
String backend = 'opencode',
String instructions = '',
}) {
if (title.trim().isEmpty || directory.trim().isEmpty) {
throw ArgumentError('Enter a chat name and choose a directory.');
}
return gateway.call('chat_create', {
'chat_create': {
'title': title.trim(),
'directory': directory.trim(),
'operation_id': operationId,
if (backend.isNotEmpty && backend != 'opencode') 'backend': backend,
if (instructions.trim().isNotEmpty) 'instructions': instructions.trim(),
},
});
}
Future<JsonMap> rename(String sessionId, String title) =>
gateway.call('chat_rename', {
'chat_rename': {'session_id': sessionId, 'title': title.trim()},
});
Future<JsonMap> star(String sessionId, bool starred) =>
gateway.call('chat_star', {
'chat_query': {'session_id': sessionId, 'starred': starred},
});
Future<JsonMap> close(String sessionId) => gateway.call('chat_close', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> reopen(String sessionId) => gateway.call('chat_reopen', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> prompt(
String sessionId,
String text, {
required String operationId,
List<String> files = const [],
List<JsonMap> attachments = const [],
}) {
if (sessionId.trim().isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (text.trim().isEmpty) {
throw ArgumentError('Enter a message before sending.');
}
final body = <String, dynamic>{
'session_id': sessionId,
'text': text.trim(),
'operation_id': operationId,
'native_message_id': nativeChatMessageId(operationId),
};
if (files.isNotEmpty) body['files'] = files;
if (attachments.isNotEmpty) body['attachments'] = attachments;
return gateway.call('chat_prompt', {'chat_prompt': body});
}
Future<JsonMap> interrupt(String sessionId) =>
gateway.call('chat_interrupt', {
'chat_query': {'session_id': sessionId},
});
Future<JsonMap> answerForm(
String sessionId,
String formId,
JsonMap answers, {
String action = '',
}) => gateway.call('chat_answer', {
'chat_answer': {
'session_id': sessionId,
'form_id': formId,
'answers': answers,
if (action.isNotEmpty) 'action': action,
},
});
Future<JsonMap> replyPermission(
String sessionId,
String requestId,
String decision, {
String client = webChatClient,
String message = '',
}) {
if (sessionId.trim().isEmpty) {
throw ArgumentError('Select a chat session first.');
}
if (requestId.trim().isEmpty) {
throw ArgumentError('This approval request is no longer available.');
}
if (!const ['once', 'always', 'reject'].contains(decision.trim())) {
throw ArgumentError('Choose once, always or reject.');
}
return gateway.call('chat_reply', {
'chat_reply': {
'session_id': sessionId,
'request_id': requestId,
'decision': decision,
'client': client,
if (message.trim().isNotEmpty) 'message': message.trim(),
},
});
}
static List<JsonMap> _maps(Object? value) => (value as List? ?? const [])
.whereType<Map>()
.map((item) => Map<String, dynamic>.from(item))
.toList();
}
@@ -0,0 +1,64 @@
import '../../../core/api_gateway.dart';
/// Pure session-list operations. Unknown server fields remain on each row.
String chatSessionTitle(JsonMap session) {
final title = '${session['title'] ?? ''}';
if (title.trim().isNotEmpty) return title;
final id = '${session['id'] ?? ''}';
return id.isEmpty ? 'Untitled chat' : id.substring(0, id.length.clamp(0, 18));
}
List<JsonMap> filterChatSessions(List<JsonMap> sessions, String query) {
final needle = query.trim().toLowerCase();
if (needle.isEmpty) return sessions;
return sessions
.where(
(session) =>
'${chatSessionTitle(session)}\u0000${session['directory'] ?? ''}'
.toLowerCase()
.contains(needle),
)
.toList();
}
/// Directory groups retain server recency order, both within and between groups.
List<({String directory, List<JsonMap> sessions})> groupChatSessions(
List<JsonMap> sessions,
) {
final groups = <String, List<JsonMap>>{};
for (final session in sessions) {
groups.putIfAbsent('${session['directory'] ?? ''}', () => []).add(session);
}
return groups.entries
.map((entry) => (directory: entry.key, sessions: entry.value))
.toList();
}
String chatSessionActivity({required bool running, required bool unseen}) =>
running
? 'streaming'
: unseen
? 'new'
: 'idle';
/// Native reported values only; missing and invalid values remain unavailable.
JsonMap? chatUsageSnapshot(Object? value) {
if (value is! Map || value is List) return null;
final usage = Map<String, dynamic>.from(value);
final result = <String, dynamic>{};
for (final key in ['total_tokens', 'context_tokens', 'context_window']) {
final n = usage[key];
result[key] = n is int && n >= 0 ? n : null;
}
for (final key in ['cost_usd', 'output_tokens_per_second']) {
final n = usage[key];
result[key] = n is num && n.isFinite && n >= 0 ? n : null;
}
result['scope'] = ['session', 'turn'].contains(usage['scope'])
? usage['scope']
: '';
result['rate_basis'] = ['generation', 'turn'].contains(usage['rate_basis'])
? usage['rate_basis']
: '';
return result.values.any((v) => v != null && v != '') ? result : null;
}
@@ -0,0 +1,235 @@
import '../../../core/api_gateway.dart';
/// Merge chronological history pages by message id. Incoming authoritative
/// copies replace held copies without changing their order; cursor is opaque.
JsonMap mergeChatHistory(JsonMap previous, JsonMap page, {bool older = false}) {
final held = (previous['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final incoming = (page['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final latest = <Object, JsonMap>{};
for (final message in incoming) {
if (message['id'] != null) latest[message['id']] = message;
}
final combined = older ? [...incoming, ...held] : [...held, ...incoming];
final seen = <Object>{};
final messages = <JsonMap>[];
for (final message in combined) {
final id = message['id'];
if (id != null && !seen.add(id)) continue;
messages.add(id == null ? message : latest[id] ?? message);
}
return {
'messages': messages,
'nextCursor': '${page['nextCursor'] ?? ''}',
'hasMore': page['hasMore'] == true,
'loaded': true,
'loading': false,
};
}
/// Consecutive assistant messages form one answer turn. All part fields (also
/// future/unknown protocol types) are preserved in original order.
List<JsonMap> transcriptRows(List<JsonMap> messages) {
final rows = <JsonMap>[];
String? key;
final parts = <JsonMap>[];
void flush() {
if (key != null && parts.isNotEmpty) {
rows.add({
'kind': 'assistant',
'key': key,
'parts': List<JsonMap>.of(parts),
});
}
key = null;
parts.clear();
}
for (final message in messages) {
if (message['role'] == 'assistant') {
key ??= '${message['id'] ?? ''}';
for (final part in (message['parts'] as List? ?? const [])) {
if (part is Map) parts.add(Map<String, dynamic>.from(part));
}
} else {
flush();
rows.add({'kind': 'user', 'key': message['id'], 'message': message});
}
}
flush();
return rows;
}
/// Replace a local optimistic user row when its server echo identifies the
/// same operation/native message; otherwise append once by authoritative id.
List<JsonMap> reconcileChatUser(List<JsonMap> messages, JsonMap remote) {
final operation = remote['operation_id'];
final nativeId = remote['native_message_id'];
final id = remote['id'];
final index = messages.indexWhere(
(message) =>
(operation != null && message['operation_id'] == operation) ||
(nativeId != null && message['native_message_id'] == nativeId) ||
(id != null && message['id'] == id),
);
if (index < 0) return [...messages, remote];
final result = List<JsonMap>.of(messages);
result[index] = remote;
return result;
}
/// Fold a live chat frame into an immutable thread snapshot. Text and reasoning
/// deltas append by part id, tool snapshots merge without dropping prior fields,
/// and step frames update turn activity. Frames for another session are ignored.
JsonMap applyChatEvent(JsonMap thread, JsonMap frame) {
final session = thread['sessionId'];
if (session != null &&
frame['session_id'] != null &&
session != frame['session_id']) {
return thread;
}
final messages = (thread['messages'] as List? ?? const [])
.whereType<Map>()
.map((m) => Map<String, dynamic>.from(m))
.toList();
final kind = frame['kind'];
if (kind == 'user') {
final part = frame['part'];
final text = part is Map ? part['text'] : null;
final id = frame['message_id'];
if (text is! String ||
text.isEmpty ||
id == null ||
messages.any(
(m) =>
m['id'] == id ||
(frame['operation_id'] != null &&
m['operation_id'] == frame['operation_id']),
)) {
return thread;
}
messages.add({
'id': id,
'session_id': frame['session_id'],
'role': 'user',
'client': frame['client'],
'operation_id': frame['operation_id'],
'parts': [
{'type': 'text', 'text': text},
...(frame['attachments'] is List
? frame['attachments'] as List
: const []),
],
});
return {...thread, 'messages': messages};
}
if (kind == 'text' || kind == 'reasoning' || kind == 'tool') {
final incoming = frame['part'];
if (incoming is! Map || incoming['id'] == null) return thread;
final messageId = frame['message_id'];
var index = messages.indexWhere(
(m) => m['id'] == messageId && m['role'] == 'assistant',
);
if (index < 0) {
messages.add({
'id': messageId,
'session_id': frame['session_id'],
'role': 'assistant',
'parts': <JsonMap>[],
});
index = messages.length - 1;
}
final message = messages[index];
final parts = (message['parts'] as List? ?? const [])
.whereType<Map>()
.map((p) => Map<String, dynamic>.from(p))
.toList();
final partIndex = parts.indexWhere(
(p) => p['id'] == incoming['id'] && p['type'] == kind,
);
if (kind == 'text' || kind == 'reasoning') {
final delta = frame['delta'];
if (delta is! String || delta.isEmpty) return thread;
if (partIndex < 0) {
parts.add({'type': kind, 'id': incoming['id'], 'text': delta});
} else {
parts[partIndex] = {
...parts[partIndex],
'text': '${parts[partIndex]['text'] ?? ''}$delta',
};
}
} else if (partIndex < 0) {
parts.add(Map<String, dynamic>.from(incoming));
} else {
final merged = {
...parts[partIndex],
...Map<String, dynamic>.from(incoming),
};
if (parts[partIndex]['state'] is Map && incoming['state'] is Map) {
merged['state'] = {
...Map<String, dynamic>.from(parts[partIndex]['state'] as Map),
...Map<String, dynamic>.from(incoming['state'] as Map),
};
}
parts[partIndex] = merged;
}
messages[index] = {...message, 'parts': parts};
return {...thread, 'messages': messages, 'running': true};
}
if (kind == 'step' && frame['step'] is Map) {
final step = frame['step'] as Map;
if (step['intermediate'] == true) return thread;
return {
...thread,
'running': step['status'] != 'ended',
'nativeTurnId': step['status'] == 'ended'
? ''
: (step['turn_id'] ?? thread['nativeTurnId'] ?? ''),
};
}
return thread;
}
/// Queue serialized sends per session; operation ids survive retries/replays.
class QueuedChatSend {
QueuedChatSend({
required this.operationId,
required this.text,
this.files = const [],
});
final String operationId;
final String text;
final List<String> files;
/// Retry the same immutable intent with the same idempotency key.
QueuedChatSend retry() => QueuedChatSend(
operationId: operationId,
text: text,
files: List.unmodifiable(files),
);
}
class ChatSendQueue {
final Map<String, List<QueuedChatSend>> _sessions = {};
List<QueuedChatSend> forSession(String sessionId) =>
List.unmodifiable(_sessions[sessionId] ?? const []);
bool enqueue(String sessionId, QueuedChatSend send) {
final queue = _sessions.putIfAbsent(sessionId, () => []);
if (queue.any((item) => item.operationId == send.operationId)) return false;
queue.add(send);
return true;
}
QueuedChatSend? takeNext(String sessionId) {
final queue = _sessions[sessionId];
if (queue == null || queue.isEmpty) return null;
final result = queue.removeAt(0);
if (queue.isEmpty) _sessions.remove(sessionId);
return result;
}
}
@@ -0,0 +1 @@
export 'ui/sessions/chat_sessions_screen.dart';
@@ -0,0 +1,200 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
/// Which standard control family this screen renders.
enum ChatControlsStyle { material, cupertino }
/// Cupertino under a Cupertino app or an iOS/macOS Material theme, Material
/// everywhere else. The shell decides the app class, so a bare Cupertino app
/// never has to grow a Material ancestor just for this screen.
ChatControlsStyle chatControlsStyleOf(BuildContext context) {
if (context.findAncestorWidgetOfExactType<MaterialApp>() == null) {
return ChatControlsStyle.cupertino;
}
final platform = Theme.of(context).platform;
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS
? ChatControlsStyle.cupertino
: ChatControlsStyle.material;
}
class ChatBarAction extends StatelessWidget {
const ChatBarAction({
super.key,
required this.label,
required this.onPressed,
required this.materialIcon,
required this.cupertinoIcon,
});
final String label;
final VoidCallback onPressed;
final IconData materialIcon;
final IconData cupertinoIcon;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Icon(cupertinoIcon),
),
);
}
return IconButton(
tooltip: label,
onPressed: onPressed,
icon: Icon(materialIcon),
);
}
}
class ChatSearchField extends StatelessWidget {
const ChatSearchField({
super.key,
required this.controller,
required this.onChanged,
});
final TextEditingController controller;
final ValueChanged<String> onChanged;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Padding(
padding: const EdgeInsets.all(16),
child: CupertinoSearchTextField(
controller: controller,
placeholder: 'Search chats',
onChanged: onChanged,
),
);
}
return Padding(
padding: const EdgeInsets.all(16),
child: TextField(
controller: controller,
onChanged: onChanged,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
labelText: 'Search chats',
),
),
);
}
}
/// A grouped Cupertino card for a message that may wrap onto several lines.
///
/// [CupertinoListTile] forces its title to one ellipsised line, which cut long
/// no-match queries and server reasons. This layout keeps the native card but
/// lets the message wrap, with its action on a separate button below.
class ChatCupertinoMessage extends StatelessWidget {
const ChatCupertinoMessage({
super.key,
required this.message,
this.icon,
this.actionLabel,
this.onAction,
});
final String message;
final IconData? icon;
final String? actionLabel;
final VoidCallback? onAction;
@override
Widget build(BuildContext context) {
return Semantics(
container: true,
explicitChildNodes: true,
child: CupertinoListSection.insetGrouped(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (icon != null) ...[
Icon(
icon,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
),
const SizedBox(width: 12),
],
Expanded(
// Cupertino widgets normally supply their own text style.
// This card is also mounted under a bare MaterialApp (the
// iOS/macOS theme path), where Text would otherwise inherit
// MaterialApp's "missing Material" fallback style.
child: DefaultTextStyle.merge(
style: CupertinoTheme.of(context).textTheme.textStyle,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(message),
if (actionLabel != null && onAction != null)
Align(
alignment: AlignmentDirectional.centerStart,
child: CupertinoButton(
padding: const EdgeInsets.only(top: 8),
onPressed: onAction,
child: Text(actionLabel!),
),
),
],
),
),
),
],
),
),
],
),
);
}
}
class ChatErrorNotice extends StatelessWidget {
const ChatErrorNotice({
super.key,
required this.message,
required this.onRetry,
});
final String message;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return ChatCupertinoMessage(
message: message,
icon: CupertinoIcons.exclamationmark_circle,
actionLabel: 'Retry',
onAction: onRetry,
);
}
return MaterialBanner(
content: Text(message),
actions: [TextButton(onPressed: onRetry, child: const Text('Retry'))],
);
}
}
class ChatLoadingIndicator extends StatelessWidget {
const ChatLoadingIndicator({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
}
@@ -0,0 +1,185 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'chat_adaptive.dart';
/// The create dialog's server catalog area: loading, error with retry, the
/// empty-catalog message, or the two server-backed selectors.
class ChatCatalogFields extends StatelessWidget {
const ChatCatalogFields({
super.key,
required this.loading,
required this.error,
required this.directories,
required this.backends,
required this.directory,
required this.backend,
required this.onDirectory,
required this.onBackend,
required this.onRetry,
});
final bool loading;
final String? error;
final List<String> directories;
final List<String> backends;
final String? directory;
final String? backend;
final ValueChanged<String> onDirectory;
final ValueChanged<String> onBackend;
final VoidCallback onRetry;
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
if (loading) return const Text('Loading directories…');
if (error != null) {
return _message(cupertino, 'Unable to load chat options: $error');
}
if (directories.isEmpty || backends.isEmpty) {
return _message(
cupertino,
'The server has no chat directories or backends available.',
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cupertino)
CupertinoPickerField(
label: 'Server directory',
value: directory,
values: directories,
onSelected: onDirectory,
)
else
MaterialPickerField(
label: 'Server directory',
value: directory,
values: directories,
onSelected: onDirectory,
),
if (cupertino)
CupertinoPickerField(
label: 'Backend',
value: backend,
values: backends,
onSelected: onBackend,
)
else
MaterialPickerField(
label: 'Backend',
value: backend,
values: backends,
onSelected: onBackend,
),
],
);
}
Widget _message(bool cupertino, String text) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(text),
Align(
alignment: AlignmentDirectional.centerStart,
child: cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onRetry,
child: const Text('Retry'),
)
: TextButton(onPressed: onRetry, child: const Text('Retry')),
),
],
);
}
}
class MaterialPickerField extends StatelessWidget {
const MaterialPickerField({
super.key,
required this.label,
required this.value,
required this.values,
required this.onSelected,
});
final String label;
final String? value;
final List<String> values;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
return DropdownButtonFormField<String>(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
initialValue: value,
decoration: InputDecoration(labelText: label),
items: [
for (final item in values)
DropdownMenuItem(value: item, child: Text(item)),
],
onChanged: (item) {
if (item != null) onSelected(item);
},
);
}
}
class CupertinoPickerField extends StatelessWidget {
const CupertinoPickerField({
super.key,
required this.label,
required this.value,
required this.values,
required this.onSelected,
});
final String label;
final String? value;
final List<String> values;
final ValueChanged<String> onSelected;
Future<void> _choose(BuildContext context) async {
final choice = await showCupertinoModalPopup<String>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(label),
actions: [
for (final item in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, item),
child: Text(item),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (choice != null) onSelected(choice);
}
@override
Widget build(BuildContext context) {
return Semantics(
label: '$label: ${value ?? ''}',
button: true,
child: CupertinoButton(
key: Key('chat-create-${label.toLowerCase().replaceAll(' ', '-')}'),
padding: const EdgeInsets.symmetric(vertical: 4),
onPressed: () => _choose(context),
child: Row(
children: [
Expanded(child: Text('$label: ${value ?? ''}')),
const Icon(CupertinoIcons.chevron_down),
],
),
),
);
}
}
@@ -0,0 +1,97 @@
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_list_cupertino.dart';
import 'session_list_material.dart';
import 'session_row_style.dart';
typedef ChatSessionSection = ({String title, List<JsonMap> sessions});
/// Groups the visible sessions the way the server reports them.
class ChatSessionsBody extends StatelessWidget {
const ChatSessionsBody({
super.key,
required this.sessions,
required this.query,
required this.loading,
required this.error,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<JsonMap> sessions;
final String query;
final bool loading;
final String? error;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback onClearSearch;
@override
Widget build(BuildContext context) {
final visible = filterChatSessions(sessions, query);
final sections = <ChatSessionSection>[
if (visible.any((s) => s['starred'] == true && s['closed_at'] == null))
(
title: 'Starred',
sessions: visible
.where((s) => s['starred'] == true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['starred'] != true && s['closed_at'] == null))
(
title: 'Chats',
sessions: visible
.where((s) => s['starred'] != true && s['closed_at'] == null)
.toList(),
),
if (visible.any((s) => s['closed_at'] != null))
(
title: 'Closed',
sessions: visible.where((s) => s['closed_at'] != null).toList(),
),
];
final emptyMessage = sessions.isEmpty
? error == null
? 'No chat sessions on this server yet.'
: null
: 'No chats match "${query.trim()}".';
if (loading && sessions.isEmpty) return const ChatLoadingIndicator();
final clearSearch = query.trim().isEmpty ? null : onClearSearch;
final duplicateTitles = duplicateChatTitles(visible);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoSessionList(
sections: sections,
emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onClearSearch: clearSearch,
);
}
return MaterialSessionList(
sections: sections,
emptyMessage: visible.isEmpty ? emptyMessage : null,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
onClearSearch: clearSearch,
);
}
}
@@ -0,0 +1,111 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
/// Owns the session list, its refresh generation and the row actions.
///
/// A refresh that finishes after a newer one (or after the screen is gone) is
/// discarded, so a slow reply can never replace fresher state.
class ChatSessionsController extends ChangeNotifier {
ChatSessionsController(this.repository);
ChatRepository repository;
List<JsonMap> _sessions = const [];
String? _error;
bool _loading = true;
bool _disposed = false;
int _generation = 0;
List<JsonMap> get sessions => _sessions;
String? get error => _error;
bool get loading => _loading;
void replaceRepository(ChatRepository next) {
if (identical(next.gateway, repository.gateway)) return;
repository = next;
refresh();
}
Future<void> refresh() async {
if (_disposed) return;
final generation = ++_generation;
_loading = true;
_error = null;
_notify();
try {
final sessions = await repository.sessions();
if (generation != _generation) return;
_sessions = sessions;
_loading = false;
_notify();
} catch (error) {
if (generation != _generation) return;
_error = '$error';
_loading = false;
_notify();
}
}
Future<void> star(String sessionId, bool starred) =>
_mutate(() => repository.star(sessionId, starred));
Future<void> close(String sessionId) =>
_mutate(() => repository.close(sessionId));
Future<void> reopen(String sessionId) =>
_mutate(() => repository.reopen(sessionId));
Future<void> rename(String sessionId, String title) =>
_mutate(() => repository.rename(sessionId, title));
Future<JsonMap?> create({
required String title,
required String directory,
required String backend,
required String instructions,
required String operationId,
}) async {
try {
final reply = await repository.create(
title: title,
directory: directory,
backend: backend,
operationId: operationId,
instructions: instructions,
);
// Opening the created chat must not wait for the list refresh: the dialog
// has already closed, so a slow listing would look like a failed create.
unawaited(refresh());
final session = reply['chat_session'];
return session is Map ? Map<String, dynamic>.from(session) : null;
} catch (error) {
_error = '$error';
_notify();
return null;
}
}
Future<void> _mutate(Future<JsonMap> Function() action) async {
try {
await action();
await refresh();
} catch (error) {
_error = '$error';
_notify();
}
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_generation++;
super.dispose();
}
}
@@ -0,0 +1,176 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'chat_sessions_controller.dart';
import 'create_chat_dialog.dart';
import 'rename_chat_dialog.dart';
import 'session_actions.dart';
/// Browses server-owned sessions. Opening a row is read-only at this layer.
class ChatSessionsScreen extends StatefulWidget {
const ChatSessionsScreen({
super.key,
required this.gateway,
required this.onOpen,
});
final ApiGateway gateway;
final void Function(JsonMap session) onOpen;
@override
State<ChatSessionsScreen> createState() => _ChatSessionsScreenState();
}
class _ChatSessionsScreenState extends State<ChatSessionsScreen> {
late final ChatSessionsController _controller = ChatSessionsController(
ChatRepository(widget.gateway),
)..refresh();
final _search = TextEditingController();
@override
void didUpdateWidget(covariant ChatSessionsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.replaceRepository(ChatRepository(widget.gateway));
}
}
@override
void dispose() {
_controller.dispose();
_search.dispose();
super.dispose();
}
String _sessionId(JsonMap session) => '${session['id'] ?? ''}';
Future<void> _rename(JsonMap session) async {
final title = await showRenameChatDialog(context, session);
if (title == null || !mounted) return;
await _controller.rename(_sessionId(session), title);
}
Future<void> _close(JsonMap session) async {
if (!await confirmCloseChat(context, session)) return;
if (!mounted) return;
await _controller.close(_sessionId(session));
}
Future<void> _newChat() async {
final operationId = 'native-chat-${DateTime.now().microsecondsSinceEpoch}';
final draft = await showChatCreateDialog(
context,
repository: _controller.repository,
);
if (draft == null || !mounted) return;
final session = await _controller.create(
title: draft.title,
directory: draft.directory,
backend: draft.backend,
instructions: draft.instructions,
operationId: operationId,
);
if (session != null && mounted) widget.onOpen(session);
}
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: _controller,
builder: (context, _) {
final body = Column(
children: [
ChatSearchField(
controller: _search,
onChanged: (_) => setState(() {}),
),
if (_controller.error != null)
ChatErrorNotice(
message: _controller.error!,
onRetry: _controller.refresh,
),
Expanded(
child: ChatSessionsBody(
sessions: _controller.sessions,
query: _search.text,
loading: _controller.loading,
error: _controller.error,
onOpen: widget.onOpen,
onRename: _rename,
onClose: _close,
onReopen: (session) => _controller.reopen(_sessionId(session)),
onStar: (session) => _controller.star(
_sessionId(session),
session['starred'] != true,
),
onClearSearch: () {
_search.clear();
setState(() {});
},
),
),
],
);
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,
),
],
),
),
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,
),
],
),
body: body,
floatingActionButton: FloatingActionButton.extended(
key: const Key('chat-new-chat-fab'),
onPressed: _newChat,
icon: const Icon(Icons.add),
label: const Text('New chat'),
),
);
},
);
}
}
@@ -0,0 +1,222 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../data/chat_repository.dart';
import 'chat_adaptive.dart';
import 'chat_create_fields.dart';
class ChatDraft {
const ChatDraft({
required this.title,
required this.directory,
required this.backend,
required this.instructions,
});
final String title;
final String directory;
final String backend;
final String instructions;
}
Future<ChatDraft?> showChatCreateDialog(
BuildContext context, {
required ChatRepository repository,
}) {
final dialog = CreateChatDialog(repository: repository);
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<ChatDraft>(context: context, builder: (_) => dialog)
: showDialog<ChatDraft>(context: context, builder: (_) => dialog);
}
class CreateChatDialog extends StatefulWidget {
const CreateChatDialog({super.key, required this.repository});
final ChatRepository repository;
@override
State<CreateChatDialog> createState() => _CreateChatDialogState();
}
class _CreateChatDialogState extends State<CreateChatDialog> {
final _name = TextEditingController(text: 'New chat');
final _instructions = TextEditingController();
List<String> _directories = const [];
List<String> _backends = const [];
String? _directory;
String? _backend;
String? _catalogError;
String? _formError;
bool _loading = true;
int _attempt = 0;
@override
void initState() {
super.initState();
_loadCatalog();
}
@override
void dispose() {
_attempt++;
_name.dispose();
_instructions.dispose();
super.dispose();
}
Future<void> _loadCatalog() async {
final attempt = ++_attempt;
setState(() {
_loading = true;
_catalogError = null;
});
try {
final values = await Future.wait([
widget.repository.directories(),
widget.repository.backends(),
]);
if (!mounted || attempt != _attempt) return;
setState(() {
_directories = values[0];
_backends = values[1];
_directory = _directories.contains(_directory)
? _directory
: _directories.isEmpty
? null
: _directories.first;
_backend = _backends.contains(_backend)
? _backend
: _backends.isEmpty
? null
: _backends.first;
_loading = false;
});
} catch (error) {
if (!mounted || attempt != _attempt) return;
setState(() {
_catalogError = '$error';
_loading = false;
});
}
}
bool get _catalogReady =>
!_loading &&
_catalogError == null &&
_directories.isNotEmpty &&
_backends.isNotEmpty;
void _submit() {
if (!_catalogReady) return;
final title = _name.text.trim();
final directory = _directory ?? '';
if (title.isEmpty || directory.isEmpty) {
setState(() => _formError = 'Enter a name and server directory.');
return;
}
Navigator.pop(
context,
ChatDraft(
title: title,
directory: directory,
backend: _backend ?? '',
instructions: _instructions.text,
),
);
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
final content = SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (cupertino)
CupertinoTextField(
key: const Key('chat-create-name'),
controller: _name,
placeholder: 'Name',
)
else
TextField(
key: const Key('chat-create-name'),
controller: _name,
decoration: const InputDecoration(labelText: 'Name'),
),
const SizedBox(height: 12),
ChatCatalogFields(
loading: _loading,
error: _catalogError,
directories: _directories,
backends: _backends,
directory: _directory,
backend: _backend,
onDirectory: (value) => setState(() => _directory = value),
onBackend: (value) => setState(() => _backend = value),
onRetry: _loadCatalog,
),
if (_catalogReady) ...[
const SizedBox(height: 8),
const Text('New chats use the server default model.'),
],
const SizedBox(height: 12),
if (cupertino)
CupertinoTextField(
key: const Key('chat-create-instructions'),
controller: _instructions,
placeholder: 'Instructions',
minLines: 1,
maxLines: 3,
)
else
TextField(
key: const Key('chat-create-instructions'),
controller: _instructions,
decoration: const InputDecoration(labelText: 'Instructions'),
minLines: 1,
maxLines: 3,
),
if (_formError != null) ...[
const SizedBox(height: 8),
Text(_formError!),
],
],
),
);
if (cupertino) {
return CupertinoAlertDialog(
title: const Text('New chat'),
content: content,
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
return AlertDialog(
title: const Text('New chat'),
content: content,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: _catalogReady ? _submit : null,
child: const Text('Create'),
),
],
);
}
}
@@ -0,0 +1,107 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
/// Renames one session. Save is disabled while the trimmed name is blank,
/// matching the web dialog.
Future<String?> showRenameChatDialog(BuildContext context, JsonMap session) {
final dialog = _RenameChatDialog(initialTitle: chatSessionTitle(session));
return chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? showCupertinoDialog<String>(context: context, builder: (_) => dialog)
: showDialog<String>(context: context, builder: (_) => dialog);
}
class _RenameChatDialog extends StatefulWidget {
const _RenameChatDialog({required this.initialTitle});
final String initialTitle;
@override
State<_RenameChatDialog> createState() => _RenameChatDialogState();
}
class _RenameChatDialogState extends State<_RenameChatDialog> {
late final TextEditingController _title =
TextEditingController(text: widget.initialTitle)
..selection = TextSelection(
baseOffset: 0,
extentOffset: widget.initialTitle.length,
);
@override
void dispose() {
_title.dispose();
super.dispose();
}
void _save() {
final title = _title.text.trim();
if (title.isEmpty) return;
Navigator.pop(context, title);
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<TextEditingValue>(
valueListenable: _title,
builder: (context, value, _) {
final canSave = value.text.trim().isNotEmpty;
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return CupertinoAlertDialog(
title: const Text('Rename chat'),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
CupertinoTextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
placeholder: 'Name',
),
const SizedBox(height: 8),
const Text('This name is shared with every device.'),
],
),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
}
return AlertDialog(
title: const Text('Rename chat'),
content: TextField(
key: const Key('chat-rename-field'),
controller: _title,
autofocus: true,
decoration: const InputDecoration(
labelText: 'Name',
helperText: 'This name is shared with every device.',
helperMaxLines: 2,
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
FilledButton(
onPressed: canSave ? _save : null,
child: const Text('Save'),
),
],
);
},
);
}
}
@@ -0,0 +1,161 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'session_row_style.dart';
enum SessionAction { rename, close, reopen }
/// The close confirmation's body, matching the web client's explanation.
String closeChatConfirmation(String title) =>
'Closes "$title" and marks it closed on every device. '
'A turn that is running is stopped first. '
'Nothing is deleted — the chat and its history are kept, '
'and you can reopen it from the list.';
class SessionStarButton extends StatelessWidget {
const SessionStarButton({
super.key,
required this.session,
required this.onPressed,
});
final JsonMap session;
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
final starred = session['starred'] == true;
final label = starred ? 'Unstar chat' : 'Star chat';
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Icon(starred ? CupertinoIcons.star_fill : CupertinoIcons.star),
),
);
}
return IconButton(
tooltip: label,
onPressed: onPressed,
icon: Icon(starred ? Icons.star : Icons.star_border),
);
}
}
class SessionActionsButton extends StatelessWidget {
const SessionActionsButton({
super.key,
required this.session,
required this.onSelected,
this.duplicateTitles = const {},
});
final JsonMap session;
final ValueChanged<SessionAction> onSelected;
final Set<String> duplicateTitles;
@override
Widget build(BuildContext context) {
final label = sessionActionsLabel(session, duplicateTitles);
if (chatControlsStyleOf(context) == ChatControlsStyle.cupertino) {
return Semantics(
label: label,
button: true,
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _showSheet(context),
child: const Icon(CupertinoIcons.ellipsis),
),
);
}
return PopupMenuButton<SessionAction>(
tooltip: label,
onSelected: onSelected,
itemBuilder: (context) => _menuItems(session),
);
}
Future<void> _showSheet(BuildContext context) async {
final action = await showCupertinoModalPopup<SessionAction>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: Text(chatSessionTitle(session)),
actions: [
for (final item in _items(session))
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext, item.action),
child: Text(item.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(sheetContext),
child: const Text('Cancel'),
),
),
);
if (action != null && context.mounted) onSelected(action);
}
}
List<PopupMenuEntry<SessionAction>> _menuItems(JsonMap session) => [
for (final item in _items(session))
PopupMenuItem(value: item.action, child: Text(item.label)),
];
List<({SessionAction action, String label})> _items(JsonMap session) {
final isClosed = session['closed_at'] != null;
return [
(action: SessionAction.rename, label: 'Rename…'),
isClosed
? (action: SessionAction.reopen, label: 'Reopen')
: (action: SessionAction.close, label: 'Close chat…'),
];
}
Future<bool> confirmCloseChat(BuildContext context, JsonMap session) async {
final title = chatSessionTitle(session);
final body = closeChatConfirmation(title);
final confirmed = chatControlsStyleOf(context) == ChatControlsStyle.cupertino
? await showCupertinoDialog<bool>(
context: context,
builder: (context) => CupertinoAlertDialog(
title: const Text('Close chat?'),
content: Text(body),
actions: [
CupertinoDialogAction(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
CupertinoDialogAction(
isDestructiveAction: true,
onPressed: () => Navigator.pop(context, true),
child: const Text('Close chat'),
),
],
),
)
: await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('Close chat?'),
content: Text(body),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('Close chat'),
),
],
),
);
return confirmed == true;
}
@@ -0,0 +1,134 @@
import 'package:flutter/cupertino.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_adaptive.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
class CupertinoSessionList extends StatelessWidget {
const CupertinoSessionList({
super.key,
required this.sections,
required this.emptyMessage,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<ChatSessionSection> sections;
final String? emptyMessage;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback? onClearSearch;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.only(bottom: 24),
children: [
for (final section in sections) ..._section(section),
if (emptyMessage != null)
ChatCupertinoMessage(
message: emptyMessage!,
actionLabel: onClearSearch == null ? null : 'Clear search',
onAction: onClearSearch,
),
],
);
}
List<CupertinoListSection> _section(ChatSessionSection section) {
final groups = groupChatSessions(section.sessions);
return [
for (final group in groups)
CupertinoListSection.insetGrouped(
header: Text(
groups.length > 1
? '${section.title} · ${group.directory.isEmpty ? 'No directory' : group.directory}'
: section.title,
),
children: [
for (final session in group.sessions)
_CupertinoSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
),
];
}
}
class _CupertinoSessionRow extends StatelessWidget {
const _CupertinoSessionRow({
required this.session,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
});
final JsonMap session;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
return CupertinoListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionCupertinoIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
SessionStarButton(
key: Key('chat-star-$id'),
session: session,
onPressed: () => onStar(session),
),
SessionActionsButton(
key: Key('chat-actions-$id'),
session: session,
duplicateTitles: duplicateTitles,
onSelected: _select,
),
],
),
);
}
void _select(SessionAction action) {
switch (action) {
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
}
}
}
@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
import 'chat_sessions_body.dart';
import 'session_actions.dart';
import 'session_row_style.dart';
class MaterialSessionList extends StatelessWidget {
const MaterialSessionList({
super.key,
required this.sections,
required this.emptyMessage,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
required this.onClearSearch,
});
final List<ChatSessionSection> sections;
final String? emptyMessage;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
final VoidCallback? onClearSearch;
@override
Widget build(BuildContext context) {
return ListView(
children: [
for (final section in sections) _section(section),
if (emptyMessage != null)
ListTile(
title: Text(emptyMessage!),
trailing: onClearSearch == null
? null
: TextButton(
onPressed: onClearSearch,
child: const Text('Clear search'),
),
),
],
);
}
Widget _section(ChatSessionSection section) {
final groups = groupChatSessions(section.sessions);
return ExpansionTile(
title: Text(section.title),
initiallyExpanded: true,
children: [
for (final group in groups) ...[
if (groups.length > 1)
ListTile(
dense: true,
leading: const Icon(Icons.folder_outlined),
title: Text(
group.directory.isEmpty ? 'No directory' : group.directory,
),
),
for (final session in group.sessions)
_MaterialSessionRow(
session: session,
duplicateTitles: duplicateTitles,
onOpen: onOpen,
onRename: onRename,
onClose: onClose,
onReopen: onReopen,
onStar: onStar,
),
],
],
);
}
}
class _MaterialSessionRow extends StatelessWidget {
const _MaterialSessionRow({
required this.session,
required this.duplicateTitles,
required this.onOpen,
required this.onRename,
required this.onClose,
required this.onReopen,
required this.onStar,
});
final JsonMap session;
final Set<String> duplicateTitles;
final ValueChanged<JsonMap> onOpen;
final ValueChanged<JsonMap> onRename;
final ValueChanged<JsonMap> onClose;
final ValueChanged<JsonMap> onReopen;
final ValueChanged<JsonMap> onStar;
@override
Widget build(BuildContext context) {
final id = '${session['id'] ?? ''}';
return ListTile(
key: Key('chat-row-$id'),
leading: Icon(sessionMaterialIcon(session)),
title: Text(chatSessionTitle(session)),
subtitle: Text(sessionSubtitle(session)),
onTap: () => onOpen(session),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
SessionStarButton(
key: Key('chat-star-$id'),
session: session,
onPressed: () => onStar(session),
),
SessionActionsButton(
key: Key('chat-actions-$id'),
session: session,
duplicateTitles: duplicateTitles,
onSelected: (action) => _select(action),
),
],
),
);
}
void _select(SessionAction action) {
switch (action) {
case SessionAction.rename:
onRename(session);
case SessionAction.close:
onClose(session);
case SessionAction.reopen:
onReopen(session);
}
}
}
@@ -0,0 +1,51 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../../core/api_gateway.dart';
import '../../domain/chat_sessions.dart';
/// Titles shared by more than one visible session, so row action labels can
/// add the session id the way the web client does.
Set<String> duplicateChatTitles(Iterable<JsonMap> sessions) {
final seen = <String>{};
final duplicates = <String>{};
for (final session in sessions) {
final title = chatSessionTitle(session);
if (!seen.add(title)) duplicates.add(title);
}
return duplicates;
}
String sessionActionsLabel(JsonMap session, Set<String> duplicateTitles) {
final title = chatSessionTitle(session);
return duplicateTitles.contains(title)
? 'Chat actions for $title (${session['id'] ?? ''})'
: 'Chat actions for $title';
}
String sessionSubtitle(JsonMap session) {
final directory = '${session['directory'] ?? ''}';
switch (chatSessionActivity(
running: session['running'] == true,
unseen: session['unseen'] == true,
)) {
case 'streaming':
return '$directory · Streaming';
case 'new':
return '$directory · New';
default:
return directory;
}
}
IconData sessionMaterialIcon(JsonMap session) {
if (session['running'] == true) return Icons.sync;
if (session['starred'] == true) return Icons.star;
return Icons.chat_bubble_outline;
}
IconData sessionCupertinoIcon(JsonMap session) {
if (session['running'] == true) return CupertinoIcons.arrow_2_circlepath;
if (session['starred'] == true) return CupertinoIcons.star_fill;
return CupertinoIcons.chat_bubble;
}
@@ -0,0 +1,152 @@
import 'graph_protocol.dart';
/// The graph definition: nodes and edges declared by a pipeline, never the
/// evidence that a run executed them. Run evidence lives in
/// `run_graph_state.dart`; keeping the two shapes separate means a definition
/// can be drawn without claiming a visit happened.
///
/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel`
/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only.
/// Ordering priority: success first, error last, every other outcome
/// alphabetical in between (the web client's `outcomePriority`).
int _outcomePriority(String outcome) {
if (outcome == 'success') return 0;
if (outcome == 'error') return 2;
return 1;
}
/// A stage's edge outcomes in the app's one stable order.
List<String> stageOutcomes(dynamic stage) {
final edges = stage is Map ? stage['edges'] : null;
if (edges is! Map) return const <String>[];
final outcomes = edges.keys.map((key) => '$key').toList();
outcomes.sort((a, b) {
final priority = _outcomePriority(a) - _outcomePriority(b);
return priority != 0 ? priority : a.compareTo(b);
});
return outcomes;
}
/// The outcome label on an edge: `error*` for an implicit fallback error route.
String edgeLabel(dynamic stage, String outcome) {
final implicitFallback = stage is Map && stage['fallback_error'] == true;
return outcome == 'error' && implicitFallback ? 'error*' : outcome;
}
/// One declared edge, in stable definition order.
class GraphEdge {
const GraphEdge({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.label,
required this.fallback,
required this.knownTarget,
});
/// The 1-based id assigned in stable definition order (`Graph.edges()`).
final int id;
final String source;
final String outcome;
/// The resolved target: `#` has already become `#success`/`#failure`.
final String target;
final String label;
/// True only for the parser's implicit `error -> #failure` route.
final bool fallback;
/// True when [target] is a terminal or a stage declared in this graph.
///
/// An empty or unknown target is kept exactly as recorded, with this flag
/// false, so callers can show it honestly instead of inventing a node.
final bool knownTarget;
bool get isTerminal => isTerminalTarget(target);
}
/// One graph definition node: a declared stage, or a terminal the definition
/// routes to.
class GraphNode {
const GraphNode({required this.key, required this.terminal, this.stageIndex});
final String key;
final bool terminal;
/// The node's stage declaration index, or null for a terminal.
final int? stageIndex;
String get label => nodeDisplayLabel(key);
String get shortLabel => nodeLabel(key);
}
List<Map<String, dynamic>> _stages(dynamic graph) {
if (graph is! Map) return const <Map<String, dynamic>>[];
final stages = graph['stages'];
if (stages is! List) return const <Map<String, dynamic>>[];
return stages.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _stageKey(Map<String, dynamic> stage) => '${stage['key'] ?? ''}';
/// Every definition edge in stable id order.
///
/// Stages keep declaration order and each stage's outcomes use
/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge
/// value declares no edge and is skipped, while an empty or unknown target is
/// preserved with [GraphEdge.knownTarget] false.
List<GraphEdge> graphEdges(dynamic graph) {
final stages = _stages(graph);
final stageKeys = <String>{
for (final stage in stages)
if (_stageKey(stage).isNotEmpty) _stageKey(stage),
};
final result = <GraphEdge>[];
for (final stage in stages) {
final edges = stage['edges'];
if (edges is! Map) continue;
final source = _stageKey(stage);
for (final outcome in stageOutcomes(stage)) {
final raw = edges[outcome];
if (raw == null) continue;
final target = resolveTarget(outcome, '$raw') ?? '';
result.add(
GraphEdge(
id: result.length + 1,
source: source,
outcome: outcome,
target: target,
label: edgeLabel(stage, outcome),
fallback: outcome == 'error' && stage['fallback_error'] == true,
knownTarget: isTerminalTarget(target) || stageKeys.contains(target),
),
);
}
}
return result;
}
/// The definition's nodes in declaration order.
///
/// A stage key identifies one node even when it is declared twice; self edges
/// and loops therefore never duplicate identity. Terminal nodes are appended
/// failure first, then success, once any declared edge resolves to a terminal
/// (the same `hasTerminal` rule the web layout uses). They are still
/// definition nodes, not evidence that a run reached them.
List<GraphNode> graphNodes(dynamic graph) {
final stages = _stages(graph);
final seen = <String>{};
final nodes = <GraphNode>[];
for (var index = 0; index < stages.length; index += 1) {
final key = _stageKey(stages[index]);
if (key.isEmpty || !seen.add(key)) continue;
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index));
}
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
nodes.add(const GraphNode(key: failureEnd, terminal: true));
nodes.add(const GraphNode(key: successEnd, terminal: true));
}
return nodes;
}
@@ -0,0 +1,43 @@
/// Protocol terminal targets and the labels the graph uses for them.
///
/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`,
/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`.
/// Pure Dart: no Flutter imports and no layout or rendering decisions.
library;
/// The explicit success terminal (`Protocol.SUCCESS_END`).
const String successEnd = '#success';
/// The explicit failure terminal (`Protocol.FAILURE_END`).
const String failureEnd = '#failure';
/// True only for the two explicit terminal targets.
///
/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using
/// the outcome, exactly as the server and the web client do.
bool isTerminalTarget(String? target) =>
target == successEnd || target == failureEnd;
/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal.
///
/// Every other value is preserved verbatim, including an empty or unknown
/// stage key. A missing target stays null rather than becoming a terminal, so
/// a blank edge cannot fabricate a visit or a terminal node.
String? resolveTarget(String? outcome, String? target) {
if (target != '#') return target;
return outcome == 'error' ? failureEnd : successEnd;
}
/// A graph node title: a stage keeps its key, a terminal reads Success/Failure.
String nodeDisplayLabel(String? key) {
if (key == successEnd) return 'Success';
if (key == failureEnd) return 'Failure';
return key ?? '';
}
/// The TUI-mirroring label: terminal targets are all caps.
String nodeLabel(String? key) {
if (key == successEnd) return 'SUCCESS';
if (key == failureEnd) return 'FAILURE';
return key ?? '';
}
@@ -0,0 +1,124 @@
import 'graph_protocol.dart';
/// Which stages and routes a run actually recorded.
///
/// This is executed-route evidence, deliberately distinct from the graph
/// definition's nodes and edges. It mirrors `runGraphState` from
/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's
/// stage is visited once in first-appearance order, a step with a non-blank
/// outcome and target contributes one deduplicated `source\0outcome\0target`
/// route, and only a resolved terminal is added by its target. A non-terminal
/// target is not visited until a step lands on it.
///
/// The run map is the same detail produced by the runs feature; this helper
/// reads recorded steps and never folds live events a second time.
class RunGraphState {
RunGraphState({
required List<String> visitedStages,
required List<String> takenRoutes,
required this.currentStage,
required this.executing,
required this.currentStageStartedAt,
}) : visitedStages = List.unmodifiable(visitedStages),
takenRoutes = List.unmodifiable(takenRoutes);
/// Visited stage keys in first-appearance order, without duplicates.
final List<String> visitedStages;
/// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order.
final List<String> takenRoutes;
/// The run's current stage, else the last recorded visit's stage, else null.
final String? currentStage;
final bool executing;
/// The running visit's start for [currentStage], only while executing.
final String? currentStageStartedAt;
bool isStageVisited(String key) => visitedStages.contains(key);
/// True when a recorded visit took this definition route. The target is
/// resolved with the same `#` rule the definition edges use.
bool isRouteTaken(String source, String outcome, String target) {
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) return false;
return takenRoutes.contains('$source\u0000$outcome\u0000$resolved');
}
/// The active stage for a live run, else null. A finished run has none.
String? get activeStage {
if (!executing || currentStage == null || currentStage!.isEmpty) {
return null;
}
return currentStage;
}
}
List<Map<String, dynamic>> _steps(dynamic run) {
if (run is! Map) return const <Map<String, dynamic>>[];
final steps = run['steps'];
if (steps is! List) return const <Map<String, dynamic>>[];
return steps.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _text(dynamic value) => '${value ?? ''}';
/// Derives [RunGraphState] from one run detail map.
///
/// Missing or malformed steps yield no visits and no routes; nothing is
/// fabricated from a missing capture. Repeated visits stay one identity per
/// stage, and self edges or loops never recurse.
RunGraphState runGraphState(dynamic run) {
final steps = _steps(run);
final visitedStages = <String>[];
final seenStages = <String>{};
final takenRoutes = <String>[];
final seenRoutes = <String>{};
void visit(String? key) {
if (key == null || key.isEmpty || !seenStages.add(key)) return;
visitedStages.add(key);
}
for (final step in steps) {
final stage = _text(step['stage']);
if (stage.isNotEmpty) visit(stage);
final outcome = _text(step['outcome']);
final target = _text(step['target']);
if (outcome.trim().isEmpty || target.trim().isEmpty) continue;
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) continue;
final route = '$stage\u0000$outcome\u0000$resolved';
if (seenRoutes.add(route)) takenRoutes.add(route);
if (isTerminalTarget(resolved)) visit(resolved);
}
final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']);
final rawCurrent = _text(run is Map ? run['current_stage'] : null);
final currentStage = rawCurrent.trim().isNotEmpty
? rawCurrent
: (lastStage.trim().isNotEmpty ? lastStage : null);
final executing = run is Map && run['executing'] == true;
String? currentStageStartedAt;
if (executing && currentStage != null) {
for (var index = steps.length - 1; index >= 0; index -= 1) {
final step = steps[index];
if (_text(step['stage']) != currentStage) continue;
if (_text(step['status']) != 'running') continue;
final started = _text(step['started_at']);
if (started.trim().isNotEmpty) currentStageStartedAt = started;
break;
}
}
return RunGraphState(
visitedStages: visitedStages,
takenRoutes: takenRoutes,
currentStage: currentStage,
executing: executing,
currentStageStartedAt: currentStageStartedAt,
);
}
@@ -0,0 +1,107 @@
import '../../../core/api_gateway.dart';
/// Recorded stage-visit selection, matching the web client's timeline and
/// stage pane. Visits are ordered by their recorded sequence, never by the
/// order a caller happens to pass them in; repeated visits to one stage stay
/// separate entries. Pure data: no widgets, layout or coordinates.
int _sequenceOf(JsonMap step) {
final sequence = step['sequence'];
return sequence is num ? sequence.toInt() : 0;
}
int _positiveVisit(dynamic control) {
if (control is! Map) return 0;
final visit = control['visit'];
if (visit is num) return visit > 0 ? visit.toInt() : 0;
return int.tryParse('${visit ?? ''}') ?? 0;
}
/// The visit number a timeline row shows: the recorded `control.visit` when it
/// is positive, else the position within the stage's ordered visits.
int displayVisit(JsonMap step, int index) {
final recorded = _positiveVisit(step['control']);
return recorded > 0 ? recorded : index + 1;
}
/// Clamps a visit index into `[0, count)`; an empty list yields 0.
int clampVisitIndex(int index, int count) {
if (count <= 0) return 0;
if (index < 0) return 0;
return index >= count ? count - 1 : index;
}
List<JsonMap> _ordered(List<JsonMap> visits) {
final indexed = <({int position, JsonMap step})>[
for (var index = 0; index < visits.length; index += 1)
(position: index, step: visits[index]),
];
indexed.sort((a, b) {
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
});
return [for (final entry in indexed) entry.step];
}
/// Every stage's recorded visits, ordered by sequence.
///
/// The map keeps stage first-appearance order. Equal sequences keep their
/// recorded order (the web client's stable sort), and a stage with no recorded
/// visit is simply absent rather than present with a synthetic visit.
Map<String, List<JsonMap>> visitsByStage(List<JsonMap> steps) {
final grouped = <String, List<JsonMap>>{};
for (final step in steps) {
final stage = '${step['stage'] ?? ''}';
grouped.putIfAbsent(stage, () => <JsonMap>[]).add(step);
}
return <String, List<JsonMap>>{
for (final entry in grouped.entries) entry.key: _ordered(entry.value),
};
}
/// One selected stage visit. [step] is null when the stage has no recorded
/// visit, so callers cannot mistake an absent capture for an execution.
class StageVisitSelection {
const StageVisitSelection({
required this.stageKey,
required this.visits,
required this.index,
});
final String stageKey;
/// The stage's visits ordered by sequence.
final List<JsonMap> visits;
/// The clamped index into [visits]; 0 when there are none.
final int index;
bool get hasVisit => visits.isNotEmpty;
JsonMap? get step => hasVisit ? visits[index] : null;
int get visitNumber => step == null ? 0 : displayVisit(step!, index);
/// True when an explicit requested index was clamped, so a caller can
/// correct its route exactly as the web stage route does.
bool correctedRequest(int? requested) =>
requested != null && requested != index;
}
/// Selects a stage's visit exactly as the web stage pane does.
///
/// A null [visitIndex] means the stage's most recent recorded visit; an
/// out-of-range index is clamped to the last visit (negative values to the
/// first). A stage with no recorded visits returns [StageVisitSelection.step]
/// null instead of a fabricated visit.
StageVisitSelection selectStageVisit(
List<JsonMap> steps,
String stageKey, {
int? visitIndex,
}) {
final visits = visitsByStage(steps)[stageKey] ?? const <JsonMap>[];
final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1);
return StageVisitSelection(
stageKey: stageKey,
visits: visits,
index: clampVisitIndex(wanted, visits.length),
);
}
@@ -0,0 +1,142 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import 'graph_ranks.dart';
import 'layout_models.dart';
/// Places definition nodes in topological columns.
///
/// Nodes keep definition order inside a rank, each column is as wide as its
/// widest measured node, and columns are top-aligned. A node is centred in its
/// column, so heterogeneous widths and text-expanded heights stay separated by
/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap]
/// between ranks. Nothing is clipped to a fixed box: the supplied measured
/// width and height are used verbatim and the returned bounds include them.
///
/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose
/// source or target is not one of [nodes] are ignored, so an unknown target can
/// never invent a node. A measurement is required for every node; a missing one
/// is an error rather than a made-up size. Extra measurement entries are
/// ignored because they cannot become nodes.
GraphLayout layoutGraphNodes({
required List<GraphNode> nodes,
required List<GraphEdge> edges,
required Map<String, NodeExtent> extents,
required GraphLayoutConfig config,
}) {
_validateNodeKeys(nodes);
final ranks = assignGraphRanks(nodes, edges);
final measured = <String, NodeExtent>{};
final missing = <String>[];
for (final node in nodes) {
final extent = extents[node.key];
if (extent == null) {
missing.add(node.key);
} else {
measured[node.key] = extent;
}
}
if (missing.isNotEmpty) {
throw ArgumentError.value(
missing,
'extents',
'missing measured extents for graph nodes',
);
}
final columns = List<List<GraphNode>>.generate(
ranks.rankCount,
(_) => <GraphNode>[],
);
for (final node in nodes) {
columns[ranks.rankOf[node.key]!].add(node);
}
final columnWidths = <double>[
for (final column in columns)
column.fold<double>(
0,
(width, node) => math.max(width, measured[node.key]!.width),
),
];
final columnHeights = <double>[
for (final column in columns)
_columnHeight(column, measured, config.rowGap),
];
final columnX = <double>[];
var nextX = config.padding;
for (var rank = 0; rank < columns.length; rank += 1) {
columnX.add(nextX);
nextX += columnWidths[rank];
if (rank + 1 < columns.length) nextX += config.columnGap;
}
final boxes = <GraphNodeBox>[];
for (var rank = 0; rank < columns.length; rank += 1) {
var nextY = config.padding;
for (final node in columns[rank]) {
final extent = measured[node.key]!;
boxes.add(
GraphNodeBox(
key: node.key,
terminal: node.terminal,
stageIndex: node.stageIndex,
rank: rank,
x: columnX[rank] + (columnWidths[rank] - extent.width) / 2,
y: nextY,
width: extent.width,
height: extent.height,
),
);
nextY += extent.height + config.rowGap;
}
}
final width =
config.padding * 2 +
columnWidths.fold<double>(0, (sum, column) => sum + column) +
config.columnGap * math.max(0, columns.length - 1);
final height =
config.padding * 2 +
columnHeights.fold<double>(
0,
(tallest, column) => math.max(tallest, column),
);
return GraphLayout(
nodes: boxes,
width: width,
height: height,
rankCount: ranks.rankCount,
ranks: ranks.rankOf,
);
}
void _validateNodeKeys(List<GraphNode> nodes) {
final seen = <String>{};
for (final node in nodes) {
if (node.key.isEmpty) {
throw ArgumentError.value(
node.key,
'nodes',
'node key must not be empty',
);
}
if (!seen.add(node.key)) {
throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key');
}
}
}
double _columnHeight(
List<GraphNode> column,
Map<String, NodeExtent> measured,
double rowGap,
) {
if (column.isEmpty) return 0;
var height = 0.0;
for (final node in column) {
height += measured[node.key]!.height;
}
return height + rowGap * (column.length - 1);
}
@@ -0,0 +1,191 @@
import 'dart:collection';
import 'dart:math' as math;
import '../domain/graph_definition.dart';
/// Deterministic 0-based ranks for a graph definition's nodes.
///
/// Ranks come from the condensation DAG: every strongly connected component
/// shares one rank, and a component sits one past its deepest predecessor
/// (longest path). Self loops and cycles therefore stay finite, a cycle's
/// members do not drift apart, and disconnected nodes stay at rank 0. Edges
/// whose endpoints are not definition nodes are ignored: an unknown target
/// never invents a node.
class GraphRanks {
GraphRanks({
required Map<String, int> rankOf,
required this.rankCount,
required List<List<String>> components,
}) : rankOf = Map.unmodifiable(rankOf),
components = List.unmodifiable(<List<String>>[
for (final component in components) List.unmodifiable(component),
]);
/// Every definition key's rank, in definition order.
final Map<String, int> rankOf;
/// Number of distinct ranks, 0 for an empty node set.
final int rankCount;
/// Strongly connected components as keys, each sorted by definition order and
/// the list sorted by its first member.
final List<List<String>> components;
}
/// One DFS frame for the iterative Tarjan walk.
class _Frame {
_Frame(this.node);
final int node;
int nextChild = 0;
}
/// Assigns ranks to exactly the supplied [nodes].
///
/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are
/// harmless. The walk is iterative, so a deep chain cannot overflow the call
/// stack, and the work is linear in nodes plus edges.
GraphRanks assignGraphRanks(List<GraphNode> nodes, List<GraphEdge> edges) {
final indexOf = <String, int>{};
for (var index = 0; index < nodes.length; index += 1) {
indexOf[nodes[index].key] = index;
}
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
final seenPairs = <int>{};
for (final edge in edges) {
final source = indexOf[edge.source];
final target = indexOf[edge.target];
if (source == null || target == null) continue;
if (!seenPairs.add(source * nodes.length + target)) continue;
adjacency[source].add(target);
}
final components = _components(adjacency);
final componentOf = List<int>.filled(nodes.length, -1);
for (var component = 0; component < components.length; component += 1) {
for (final node in components[component]) {
componentOf[node] = component;
}
}
// Condensation edges and their indegrees.
final successors = List<Set<int>>.generate(components.length, (_) => <int>{});
final indegree = List<int>.filled(components.length, 0);
for (var source = 0; source < adjacency.length; source += 1) {
final from = componentOf[source];
for (final target in adjacency[source]) {
final to = componentOf[target];
if (from == to) continue;
if (successors[from].add(to)) indegree[to] += 1;
}
}
// Longest-path ranks over the condensation. Queue order only has to be a
// topological order; the resulting rank per component is unique.
final ranks = List<int>.filled(components.length, 0);
final ready = ListQueue<int>();
for (var component = 0; component < components.length; component += 1) {
if (indegree[component] == 0) ready.add(component);
}
var settled = 0;
while (ready.isNotEmpty) {
final component = ready.removeFirst();
settled += 1;
for (final next in successors[component]) {
ranks[next] = math.max(ranks[next], ranks[component] + 1);
indegree[next] -= 1;
if (indegree[next] == 0) ready.add(next);
}
}
if (settled != components.length) {
// The condensation cannot contain a cycle by construction; stop rather than
// return a silently truncated layout.
throw StateError('graph condensation was not acyclic');
}
final componentKeys = <List<String>>[
for (final component in components)
<String>[for (final node in component) nodes[node].key],
];
final componentOrder = <int>[
for (var component = 0; component < components.length; component += 1)
component,
]..sort((a, b) => components[a].first.compareTo(components[b].first));
final rankOf = <String, int>{};
var rankCount = 0;
for (var index = 0; index < nodes.length; index += 1) {
final rank = ranks[componentOf[index]];
rankOf[nodes[index].key] = rank;
if (rank + 1 > rankCount) rankCount = rank + 1;
}
return GraphRanks(
rankOf: rankOf,
rankCount: rankCount,
components: <List<String>>[
for (final component in componentOrder) componentKeys[component],
],
);
}
/// Tarjan's strongly connected components, emitted sinks first.
///
/// Iterative rather than recursive so a long chain cannot exhaust the stack.
/// Members are sorted by definition index, which keeps every output stable.
List<List<int>> _components(List<List<int>> adjacency) {
final discovery = List<int>.filled(adjacency.length, -1);
final low = List<int>.filled(adjacency.length, 0);
final onStack = List<bool>.filled(adjacency.length, false);
final stack = <int>[];
final components = <List<int>>[];
var nextDiscovery = 0;
for (var root = 0; root < adjacency.length; root += 1) {
if (discovery[root] != -1) continue;
discovery[root] = low[root] = nextDiscovery;
nextDiscovery += 1;
stack.add(root);
onStack[root] = true;
final callStack = <_Frame>[_Frame(root)];
while (callStack.isNotEmpty) {
final frame = callStack.last;
final node = frame.node;
if (frame.nextChild < adjacency[node].length) {
final child = adjacency[node][frame.nextChild];
frame.nextChild += 1;
if (discovery[child] == -1) {
discovery[child] = low[child] = nextDiscovery;
nextDiscovery += 1;
stack.add(child);
onStack[child] = true;
callStack.add(_Frame(child));
} else if (onStack[child]) {
low[node] = math.min(low[node], discovery[child]);
}
continue;
}
callStack.removeLast();
if (callStack.isNotEmpty) {
final parent = callStack.last.node;
low[parent] = math.min(low[parent], low[node]);
}
if (low[node] == discovery[node]) {
final component = <int>[];
while (stack.isNotEmpty) {
final member = stack.removeLast();
onStack[member] = false;
component.add(member);
if (member == node) break;
}
component.sort();
components.add(component);
}
}
}
return components;
}
@@ -0,0 +1,129 @@
/// Pure geometry for a workflow graph's node layout.
///
/// Every size and gap is supplied by the caller. The native renderer measures
/// each node after text layout (including the platform's text scaling), so this
/// library never assumes a node width, font, palette or device class.
///
/// No Flutter imports: rectangles are plain numbers so the same result can be
/// built into widgets, a canvas or a test fixture.
library;
void _requireFiniteNonNegative(String name, double value) {
if (!value.isFinite || value < 0) {
throw ArgumentError.value(value, name, 'must be finite and non-negative');
}
}
/// One caller-measured node extent, in logical pixels.
///
/// A width or height may be zero for an empty label; the layout still keeps the
/// node separate from its neighbours through the configured gaps.
class NodeExtent {
NodeExtent({required this.width, required this.height}) {
_requireFiniteNonNegative('width', width);
_requireFiniteNonNegative('height', height);
}
final double width;
final double height;
}
/// The gaps a caller reserves around measured nodes.
///
/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a
/// rank, and [padding] is the outer margin included in [GraphLayout] bounds.
class GraphLayoutConfig {
GraphLayoutConfig({
required this.columnGap,
required this.rowGap,
this.padding = 0,
}) {
_requireFiniteNonNegative('columnGap', columnGap);
_requireFiniteNonNegative('rowGap', rowGap);
_requireFiniteNonNegative('padding', padding);
}
final double columnGap;
final double rowGap;
final double padding;
}
/// One placed node.
///
/// [key], [terminal] and [stageIndex] are the definition node's own identity,
/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in
/// graph space and [rank] is its 0-based topological column.
class GraphNodeBox {
const GraphNodeBox({
required this.key,
required this.terminal,
required this.stageIndex,
required this.rank,
required this.x,
required this.y,
required this.width,
required this.height,
});
final String key;
final bool terminal;
final int? stageIndex;
final int rank;
final double x;
final double y;
final double width;
final double height;
double get right => x + width;
double get bottom => y + height;
@override
bool operator ==(Object other) =>
other is GraphNodeBox &&
other.key == key &&
other.terminal == terminal &&
other.stageIndex == stageIndex &&
other.rank == rank &&
other.x == x &&
other.y == y &&
other.width == width &&
other.height == height;
@override
int get hashCode =>
Object.hash(key, terminal, stageIndex, rank, x, y, width, height);
}
/// An immutable node layout: every placed box plus the total graph bounds.
///
/// [nodes] is ordered by rank first and definition order inside a rank; use
/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the
/// caller's padding; every box's [right] and [bottom] stay inside them.
/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the
/// number of columns (0 for an empty node set).
class GraphLayout {
GraphLayout({
required List<GraphNodeBox> nodes,
required this.width,
required this.height,
required this.rankCount,
required Map<String, int> ranks,
}) : nodes = List.unmodifiable(nodes),
ranks = Map.unmodifiable(ranks);
final List<GraphNodeBox> nodes;
final Map<String, int> ranks;
final double width;
final double height;
final int rankCount;
bool get isEmpty => nodes.isEmpty;
/// The placed box for [key], or null when the definition has no such node.
GraphNodeBox? nodeFor(String key) {
for (final node in nodes) {
if (node.key == key) return node;
}
return null;
}
}
@@ -0,0 +1,160 @@
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import '../routing/route_models.dart';
/// A passive canvas for already-routed graph edges.
///
/// Paints exactly the supplied [routes] at their graph coordinates on a
/// [canvasSize] canvas. The caller owns every measurement: routes come from the
/// routing library, and [color] plus [strokeWidth] come from its native theme.
/// No node is invented or resized and no layout runs here.
///
/// The layer is transparent to pointer input: it covers the canvas but never
/// takes a hit, so node buttons, labels and other siblings keep their own
/// gestures. Labels are composed separately as native widgets; this layer never
/// paints text and never handles pointer, focus or semantics input.
class GraphEdgeLayer extends StatelessWidget {
const GraphEdgeLayer({
super.key,
required this.routes,
required this.canvasSize,
required this.color,
required this.strokeWidth,
}) : assert(strokeWidth > 0);
/// Orthogonal routes in graph space, with each arrow entering its target port.
final List<EdgeRoute> routes;
/// The graph-space canvas the caller reserved for the drawing.
final Size canvasSize;
/// The caller's native edge/label color.
final Color color;
/// The caller's native stroke width; the arrow scales with it.
final double strokeWidth;
@override
Widget build(BuildContext context) {
return CustomPaint(
size: canvasSize,
painter: GraphEdgePainter(
routes: routes,
color: color,
strokeWidth: strokeWidth,
),
);
}
}
/// Paints [GraphEdgeLayer] routes as a polyline plus a filled direction arrow.
///
/// The painter is public so a renderer and its tests share the exact path and
/// arrow geometry. It clips to the size `CustomPaint` supplies and reports every
/// point as a miss, matching the layer's passive contract.
class GraphEdgePainter extends CustomPainter {
GraphEdgePainter({
required this.routes,
required this.color,
required this.strokeWidth,
}) : assert(strokeWidth > 0),
_line = Paint()
..color = color
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
_arrow = Paint()
..color = color
..style = PaintingStyle.fill;
final List<EdgeRoute> routes;
final Color color;
final double strokeWidth;
final Paint _line;
final Paint _arrow;
/// Arrow length and half base width, as multiples of the caller's stroke.
static const double _arrowLength = 6;
static const double _arrowHalfWidth = 2;
@override
void paint(Canvas canvas, Size size) {
if (routes.isEmpty) return;
canvas.save();
canvas.clipRect(Offset.zero & size);
for (final route in routes) {
if (route.points.length < 2) continue;
assert(
route.points.last == route.targetPort.point,
'EdgeRoute ${route.id} must end at its target port; the router '
'guarantees points.last == targetPort.point.',
);
canvas.drawPath(linePath(route), _line);
}
for (final route in routes) {
if (route.points.length < 2) continue;
canvas.drawPath(arrowPath(route), _arrow);
}
canvas.restore();
}
/// The orthogonally joined polyline for [route], in painter coordinates.
Path linePath(EdgeRoute route) {
final path = Path();
final points = route.points;
if (points.isEmpty) return path;
path.moveTo(points.first.x, points.first.y);
for (var index = 1; index < points.length; index += 1) {
path.lineTo(points[index].x, points[index].y);
}
return path;
}
/// A filled triangle whose tip is exactly [EdgeRoute.targetPort]. The
/// direction follows the route's last segment, so forward, backward,
/// same-rank and self-loop edges keep their honest arrival direction. A
/// degenerate tail falls back to the target port's inward normal.
Path arrowPath(EdgeRoute route) {
final points = route.points;
if (points.length < 2) return Path();
final tip = Offset(route.targetPort.point.x, route.targetPort.point.y);
final direction = _arrivalDirection(route);
final length = strokeWidth * _arrowLength;
final halfWidth = strokeWidth * _arrowHalfWidth;
final baseX = tip.dx - direction.dx * length;
final baseY = tip.dy - direction.dy * length;
final normalX = -direction.dy * halfWidth;
final normalY = direction.dx * halfWidth;
return Path()
..moveTo(tip.dx, tip.dy)
..lineTo(baseX + normalX, baseY + normalY)
..lineTo(baseX - normalX, baseY - normalY)
..close();
}
Offset _arrivalDirection(EdgeRoute route) {
final tip = route.targetPort.point;
for (var index = route.points.length - 1; index >= 0; index -= 1) {
final point = route.points[index];
final delta = Offset(tip.x - point.x, tip.y - point.y);
if (delta != Offset.zero) return delta / delta.distance;
}
return switch (route.targetPort.side) {
RoutePortSide.top => const Offset(0, 1),
RoutePortSide.right => const Offset(-1, 0),
RoutePortSide.bottom => const Offset(0, -1),
RoutePortSide.left => const Offset(1, 0),
};
}
/// The layer is passive: every point misses so siblings keep their gestures.
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(GraphEdgePainter oldDelegate) =>
oldDelegate.color != color ||
oldDelegate.strokeWidth != strokeWidth ||
!listEquals(oldDelegate.routes, routes);
}
@@ -0,0 +1,105 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// One vertical-corridor request from a wrapping route.
///
/// A route needs a track right of its source and a track beside its target;
/// both gaps are 0-based column gaps (`rankCount` is the right free gap).
class CorridorRequest {
const CorridorRequest({
required this.edgeId,
required this.sourceGap,
required this.targetGap,
});
final int edgeId;
final int sourceGap;
final int targetGap;
}
/// Assigned x coordinates for every wrapping route's two vertical tracks.
class CorridorPlan {
CorridorPlan({
required Map<int, double> sourceX,
required Map<int, double> targetX,
}) : sourceX = Map.unmodifiable(sourceX),
targetX = Map.unmodifiable(targetX);
final Map<int, double> sourceX;
final Map<int, double> targetX;
}
/// Spreads corridor requests across the free band of each column gap.
///
/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks
/// are distinct inside a gap; a narrow gap compresses the spacing instead of
/// pushing a corridor into a node column.
CorridorPlan planCorridors({
required GraphLayout layout,
required List<CorridorRequest> requests,
required RoutingConfig config,
}) {
final ordered = <CorridorRequest>[...requests]
..sort((a, b) => a.edgeId.compareTo(b.edgeId));
final slots = <int, List<_Slot>>{};
for (final request in ordered) {
slots
.putIfAbsent(request.sourceGap, () => <_Slot>[])
.add(_Slot(request.edgeId, source: true));
slots
.putIfAbsent(request.targetGap, () => <_Slot>[])
.add(_Slot(request.edgeId, source: false));
}
final gaps = ColumnGaps(
nodes: layout.nodes,
rankCount: layout.rankCount,
layoutWidth: layout.width,
);
final sourceX = <int, double>{};
final targetX = <int, double>{};
final gapKeys = slots.keys.toList()..sort();
for (final gapKey in gapKeys) {
final gapSlots = slots[gapKey]!;
final band = gaps.band(gapKey, config.nodeClearance);
final positions = _trackPositions(
band,
gapSlots.length,
config.corridorSpacing,
);
for (var index = 0; index < gapSlots.length; index += 1) {
if (gapSlots[index].source) {
sourceX[gapSlots[index].edgeId] = positions[index];
} else {
targetX[gapSlots[index].edgeId] = positions[index];
}
}
}
return CorridorPlan(sourceX: sourceX, targetX: targetX);
}
List<double> _trackPositions(GapBand band, int count, double spacing) {
if (count == 0) return const <double>[];
if (band.open) {
return <double>[
for (var index = 0; index < count; index += 1) band.lo + spacing * index,
];
}
final width = band.hi - band.lo;
if (count == 1) return <double>[(band.lo + band.hi) / 2];
if (width <= 0) return List<double>.filled(count, band.lo);
final step = math.min(spacing, width / (count - 1));
return <double>[
for (var index = 0; index < count; index += 1) band.lo + step * index,
];
}
class _Slot {
const _Slot(this.edgeId, {required this.source});
final int edgeId;
final bool source;
}
@@ -0,0 +1,175 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// Places one measured edge label without overlapping a node or another label.
///
/// Candidates are tried in a deterministic order: the midpoint of each
/// horizontal run (above, then below), then each vertical run (right, then
/// left), sliding along the run before giving up. A run too narrow for the
/// box pushes the label to a free shelf below the drawing, which expands the
/// routing bounds instead of covering a node.
EdgeLabelBox placeEdgeLabel({
required EdgeRoute route,
required LabelExtent extent,
required List<GraphNodeBox> nodes,
required List<EdgeLabelBox> placed,
required RoutingConfig config,
required double floorY,
}) {
final width = extent.width;
final height = extent.height;
for (final candidate in _candidates(route, width, height, config.labelGap)) {
final box = EdgeLabelBox(
edgeId: route.id,
x: candidate.x,
y: candidate.y,
width: width,
height: height,
);
if (_fits(box, nodes, placed, config)) return box;
}
// The fallback shelf is below every route and every existing label, so it
// cannot cover a node. Growing it down expands the returned bounds.
var top = math.max(
floorY,
placed.fold<double>(0, (bottom, box) => math.max(bottom, box.bottom)),
);
top += config.labelGap;
final centre = _routeCentreX(route);
final step = math.max(height + config.labelGap, 1.0);
for (var attempt = 0; attempt < 100000; attempt += 1) {
final x = math.max(0.0, centre - width / 2);
final box = EdgeLabelBox(
edgeId: route.id,
x: x,
y: top,
width: width,
height: height,
);
if (_fits(box, nodes, placed, config)) return box;
top += step;
}
// A zero-sized label cannot collide; this is unreachable for real extents.
return EdgeLabelBox(
edgeId: route.id,
x: math.max(0.0, centre - width / 2),
y: top,
width: width,
height: height,
);
}
bool _fits(
EdgeLabelBox box,
List<GraphNodeBox> nodes,
List<EdgeLabelBox> placed,
RoutingConfig config,
) {
if (box.x < 0 || box.y < 0) return false;
for (final node in nodes) {
if (boxIntersectsNode(
x: box.x,
y: box.y,
width: box.width,
height: box.height,
node: node,
gap: config.labelGap,
)) {
return false;
}
}
for (final other in placed) {
if (boxesOverlap(
ax: box.x,
ay: box.y,
aw: box.width,
ah: box.height,
bx: other.x,
by: other.y,
bw: other.width,
bh: other.height,
gap: config.labelGap,
)) {
return false;
}
}
return true;
}
List<_LabelCandidate> _candidates(
EdgeRoute route,
double width,
double height,
double gap,
) {
const fractions = <double>[0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92];
final horizontals = <_Run>[];
final verticals = <_Run>[];
for (var index = 1; index < route.points.length; index += 1) {
final a = route.points[index - 1];
final b = route.points[index];
if (a.y == b.y) {
horizontals.add(_Run(a, b, (b.x - a.x).abs(), index));
} else if (a.x == b.x) {
verticals.add(_Run(a, b, (b.y - a.y).abs(), index));
}
}
horizontals.sort((a, b) {
final length = b.length.compareTo(a.length);
return length != 0 ? length : a.order.compareTo(b.order);
});
verticals.sort((a, b) {
final length = b.length.compareTo(a.length);
return length != 0 ? length : a.order.compareTo(b.order);
});
final candidates = <_LabelCandidate>[];
for (final run in horizontals) {
for (final fraction in fractions) {
final x = run.a.x + (run.b.x - run.a.x) * fraction;
final left = x - width / 2;
candidates.add(_LabelCandidate(left, run.a.y - gap - height));
candidates.add(_LabelCandidate(left, run.a.y + gap));
}
}
for (final run in verticals) {
for (final fraction in fractions) {
final y = run.a.y + (run.b.y - run.a.y) * fraction;
final top = y - height / 2;
candidates.add(_LabelCandidate(run.a.x + gap, top));
candidates.add(_LabelCandidate(run.a.x - gap - width, top));
}
}
return candidates;
}
double _routeCentreX(EdgeRoute route) {
if (route.points.isEmpty) return 0;
var lo = route.points.first.x;
var hi = lo;
for (final point in route.points) {
lo = math.min(lo, point.x);
hi = math.max(hi, point.x);
}
return (lo + hi) / 2;
}
class _Run {
const _Run(this.a, this.b, this.length, this.order);
final RoutePoint a;
final RoutePoint b;
final double length;
final int order;
}
class _LabelCandidate {
const _LabelCandidate(this.x, this.y);
final double x;
final double y;
}
@@ -0,0 +1,265 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import '../layout/layout_models.dart';
import 'corridor_plan.dart';
import 'route_geometry.dart';
import 'route_models.dart';
/// One routed edge before labels and bounds are assembled.
///
/// Internal to the routing library: callers receive the immutable public
/// [EdgeRoute] instead.
class PlannedEdgeRoute {
PlannedEdgeRoute({
required this.edge,
required this.kind,
required this.straight,
required this.sourcePort,
required this.targetPort,
required List<RoutePoint> points,
}) : points = List.unmodifiable(points);
final GraphEdge edge;
final RouteKind kind;
final bool straight;
final RoutePort sourcePort;
final RoutePort targetPort;
final List<RoutePoint> points;
EdgeRoute toRoute() => EdgeRoute(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
label: edge.label,
fallback: edge.fallback,
kind: kind,
straight: straight,
sourcePort: sourcePort,
targetPort: targetPort,
points: points,
);
}
/// Plans orthogonal polylines for every edge whose endpoints have placed boxes.
///
/// [edges] must already be filtered to known endpoints and sorted by id. The
/// plan is deterministic: forward one-rank routes take a straight horizontal
/// run when the measured boxes and labels leave room, and every other route
/// gets a unique lane below the node grid plus vertical corridors inside the
/// column gaps. Corridors and lanes never enter a node column.
///
/// All horizontal stubs share one [AxisTrackAllocator], so two different edges
/// cannot occupy the same run in a column gap even when they touch different
/// nodes on the same row.
List<PlannedEdgeRoute> planEdgeRoutes({
required GraphLayout layout,
required List<GraphEdge> edges,
required double maxLabelHeight,
required RoutingConfig config,
}) {
if (edges.isEmpty) return const <PlannedEdgeRoute>[];
final nodes = <String, GraphNodeBox>{
for (final node in layout.nodes) node.key: node,
};
final kinds = <int, RouteKind>{};
for (final edge in edges) {
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
kinds[edge.id] = _kindFor(edge, source, target, layout);
}
final trackSpacing = math.max(
config.portSpacing,
maxLabelHeight + config.labelGap,
);
final runs = AxisTrackAllocator(trackSpacing);
final straightY = <int, double>{};
for (final edge in edges) {
if (kinds[edge.id] != RouteKind.forward) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
if (target.rank != source.rank + 1) continue;
if (target.x <= source.right) continue;
final sourceInset = portInset(source, config.portSpacing);
final targetInset = portInset(target, config.portSpacing);
final lo = math.max(source.y + sourceInset, target.y + targetInset);
final hi = math.min(
source.bottom - sourceInset,
target.bottom - targetInset,
);
if (hi <= lo) continue;
final y = runs.allocate(
desired: (lo + hi) / 2,
min: lo,
max: hi,
spanLo: source.right,
spanHi: target.x,
);
if (y != null) straightY[edge.id] = y;
}
final laneStep = math.max(
config.laneSpacing,
maxLabelHeight + config.labelGap,
);
final contentBottom = layout.nodes.fold<double>(
0,
(bottom, node) => math.max(bottom, node.bottom),
);
final wrapPlans = <_WrapPlan>[];
final corridorRequests = <CorridorRequest>[];
var laneIndex = 0;
for (final edge in edges) {
if (straightY.containsKey(edge.id)) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
final kind = kinds[edge.id]!;
final laneY =
contentBottom + config.nodeClearance + laneStep * (laneIndex + 1);
laneIndex += 1;
final sourceGap = (source.rank + 1).clamp(0, layout.rankCount);
final targetGap = kind == RouteKind.forward
? target.rank.clamp(0, layout.rankCount)
: (target.rank + 1).clamp(0, layout.rankCount);
corridorRequests.add(
CorridorRequest(
edgeId: edge.id,
sourceGap: sourceGap,
targetGap: targetGap,
),
);
wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY));
}
final corridors = planCorridors(
layout: layout,
requests: corridorRequests,
config: config,
);
final sourceTrackX = corridors.sourceX;
final targetTrackX = corridors.targetX;
final sourcePorts = <int, RoutePort>{};
final targetPorts = <int, RoutePort>{};
for (final edge in edges) {
final y = straightY[edge.id];
if (y == null) continue;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
sourcePorts[edge.id] = RoutePort(
side: RoutePortSide.right,
point: RoutePoint(source.right, y),
);
targetPorts[edge.id] = RoutePort(
side: RoutePortSide.left,
point: RoutePoint(target.x, y),
);
}
for (final plan in wrapPlans) {
final edge = plan.edge;
final source = nodes[edge.source]!;
final target = nodes[edge.target]!;
final sourceTrack = sourceTrackX[edge.id]!;
final targetTrack = targetTrackX[edge.id]!;
final sourceInset = portInset(source, config.portSpacing);
final targetInset = portInset(target, config.portSpacing);
final sourceY = runs.allocate(
desired: source.y + source.height / 2,
min: source.y + sourceInset,
max: source.bottom - sourceInset,
spanLo: source.right,
spanHi: sourceTrack,
);
final targetSide = plan.kind == RouteKind.forward
? RoutePortSide.left
: RoutePortSide.right;
final targetBorder = targetSide == RoutePortSide.left
? target.x
: target.right;
final targetY = runs.allocate(
desired: target.y + target.height / 2,
min: target.y + targetInset,
max: target.bottom - targetInset,
spanLo: math.min(targetBorder, targetTrack),
spanHi: math.max(targetBorder, targetTrack),
);
sourcePorts[edge.id] = RoutePort(
side: RoutePortSide.right,
point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2),
);
targetPorts[edge.id] = RoutePort(
side: targetSide,
point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2),
);
}
final planned = <int, PlannedEdgeRoute>{};
for (final edge in edges) {
final value = straightY[edge.id];
if (value != null) {
planned[edge.id] = PlannedEdgeRoute(
edge: edge,
kind: kinds[edge.id]!,
straight: true,
sourcePort: sourcePorts[edge.id]!,
targetPort: targetPorts[edge.id]!,
points: _collapse(<RoutePoint>[
sourcePorts[edge.id]!.point,
targetPorts[edge.id]!.point,
]),
);
}
}
for (final plan in wrapPlans) {
final sourceTrack = sourceTrackX[plan.edge.id]!;
final targetTrack = targetTrackX[plan.edge.id]!;
planned[plan.edge.id] = PlannedEdgeRoute(
edge: plan.edge,
kind: plan.kind,
straight: false,
sourcePort: sourcePorts[plan.edge.id]!,
targetPort: targetPorts[plan.edge.id]!,
points: _collapse(<RoutePoint>[
sourcePorts[plan.edge.id]!.point,
RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y),
RoutePoint(sourceTrack, plan.laneY),
RoutePoint(targetTrack, plan.laneY),
RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y),
targetPorts[plan.edge.id]!.point,
]),
);
}
return <PlannedEdgeRoute>[for (final edge in edges) planned[edge.id]!];
}
RouteKind _kindFor(
GraphEdge edge,
GraphNodeBox source,
GraphNodeBox target,
GraphLayout layout,
) {
if (edge.source == edge.target) return RouteKind.selfLoop;
final sourceRank = layout.ranks[edge.source] ?? source.rank;
final targetRank = layout.ranks[edge.target] ?? target.rank;
if (targetRank > sourceRank) return RouteKind.forward;
if (targetRank < sourceRank) return RouteKind.back;
return RouteKind.sameRank;
}
List<RoutePoint> _collapse(List<RoutePoint> points) {
final result = <RoutePoint>[];
for (final point in points) {
if (result.isEmpty || result.last != point) result.add(point);
}
return result;
}
class _WrapPlan {
_WrapPlan({required this.edge, required this.kind, required this.laneY});
final GraphEdge edge;
final RouteKind kind;
final double laneY;
}
@@ -0,0 +1,135 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import '../layout/layout_models.dart';
import 'edge_label_placement.dart';
import 'edge_route_planner.dart';
import 'route_models.dart';
/// Routes every definition edge that has a placed source and target.
///
/// The node boxes and ranks come from the landed [GraphLayout]; this function
/// never moves them, invents a node or assumes a node size. Callers supply one
/// measured [LabelExtent] for every routed edge, plus the clearances and lane
/// spacing in [RoutingConfig].
///
/// Edges with an unknown, empty or missing endpoint are returned in
/// [GraphRouting.skipped] with their definition identity intact. A routed edge
/// keeps its id, source, outcome, target, label and fallback flag. Results are
/// ordered by definition edge id and are stable for repeated input.
GraphRouting routeGraphEdges({
required GraphLayout layout,
required List<GraphEdge> edges,
required Map<int, LabelExtent> labelExtents,
required RoutingConfig config,
}) {
final ordered = <GraphEdge>[...edges]..sort((a, b) => a.id.compareTo(b.id));
final seenIds = <int>{};
for (final edge in ordered) {
if (!seenIds.add(edge.id)) {
throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id');
}
}
final nodes = <String, GraphNodeBox>{
for (final node in layout.nodes) node.key: node,
};
final routed = <GraphEdge>[];
final skipped = <RouteDiagnostic>[];
for (final edge in ordered) {
if (!nodes.containsKey(edge.source)) {
skipped.add(
RouteDiagnostic(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
reason: RouteSkipReason.unknownSource,
message: 'source "${edge.source}" has no placed node',
),
);
continue;
}
if (!edge.knownTarget || !nodes.containsKey(edge.target)) {
skipped.add(
RouteDiagnostic(
id: edge.id,
source: edge.source,
outcome: edge.outcome,
target: edge.target,
reason: RouteSkipReason.unknownTarget,
message: edge.target.isEmpty
? 'edge target is empty'
: 'target "${edge.target}" has no placed node',
),
);
continue;
}
routed.add(edge);
}
final missing = <int>[
for (final edge in routed)
if (!labelExtents.containsKey(edge.id)) edge.id,
];
if (missing.isNotEmpty) {
throw ArgumentError.value(
missing,
'labelExtents',
'missing measured label extents for routed edges',
);
}
var maxLabelHeight = 0.0;
for (final edge in routed) {
maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height);
}
final planned = planEdgeRoutes(
layout: layout,
edges: routed,
maxLabelHeight: maxLabelHeight,
config: config,
);
final routes = <EdgeRoute>[for (final plan in planned) plan.toRoute()];
var floorY = layout.height;
for (final route in routes) {
for (final point in route.points) {
floorY = math.max(floorY, point.y);
}
}
final labels = <EdgeLabelBox>[];
for (var index = 0; index < routes.length; index += 1) {
labels.add(
placeEdgeLabel(
route: routes[index],
extent: labelExtents[routes[index].id]!,
nodes: layout.nodes,
placed: labels,
config: config,
floorY: floorY,
),
);
}
var width = layout.width;
var height = layout.height;
for (final route in routes) {
for (final point in route.points) {
width = math.max(width, point.x);
height = math.max(height, point.y);
}
}
for (final label in labels) {
width = math.max(width, label.right);
height = math.max(height, label.bottom);
}
return GraphRouting(
routes: routes,
labels: labels,
skipped: skipped,
width: width + config.boundsPadding,
height: height + config.boundsPadding,
);
}
@@ -0,0 +1,175 @@
import 'dart:math' as math;
import '../layout/layout_models.dart';
/// Geometry helpers for deterministic orthogonal routing.
///
/// Everything here is plain numbers: no Flutter types, no drawing and no
/// assumed metrics. The helpers are internal to the routing library.
/// Reserves horizontal or vertical tracks without collinear overlap.
///
/// A track is a position on [axis] plus the interval it spans on the other
/// axis. Two tracks only conflict when both their positions and their spans
/// overlap, so a long cross lane and a short stub may share a coordinate when
/// their runs do not meet.
class AxisTrackAllocator {
AxisTrackAllocator(this.step);
final double step;
final List<_Track> _placed = <_Track>[];
/// The nearest free position to [desired], or null when none is found.
double? allocate({
required double desired,
required double min,
required double max,
required double spanLo,
required double spanHi,
}) {
if (max < min) return null;
final start = desired.clamp(min, max);
var spacing = step;
while (spacing > 0.0001) {
for (var attempt = 0; attempt <= 512; attempt += 1) {
final candidates = attempt == 0
? <double>[start]
: <double>[start + attempt * spacing, start - attempt * spacing];
for (final candidate in candidates) {
if (candidate < min || candidate > max) continue;
if (_isFree(candidate, spanLo, spanHi, spacing)) {
_placed.add(_Track(candidate, spanLo, spanHi));
return candidate;
}
}
}
spacing /= 2;
}
return null;
}
bool _isFree(double position, double spanLo, double spanHi, double spacing) {
for (final track in _placed) {
if ((track.position - position).abs() >= spacing) continue;
final overlaps = track.lo <= spanHi && spanLo <= track.hi;
if (overlaps) return false;
}
return true;
}
}
class _Track {
const _Track(this.position, this.lo, this.hi);
final double position;
final double lo;
final double hi;
}
/// The x band available for vertical corridors in each column gap.
///
/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the
/// last column. Left/right bounds come from the placed boxes themselves, so a
/// corridor never crosses a column, including heterogeneous node widths.
class ColumnGaps {
ColumnGaps({
required List<GraphNodeBox> nodes,
required this.rankCount,
required this.layoutWidth,
}) : _left = List<double>.filled(rankCount + 1, 0),
_right = List<double>.filled(rankCount + 1, layoutWidth) {
final rankRight = List<double>.filled(rankCount, 0);
final rankLeft = List<double>.filled(rankCount, layoutWidth);
for (final node in nodes) {
if (node.rank < 0 || node.rank >= rankCount) continue;
rankRight[node.rank] = math.max(rankRight[node.rank], node.right);
rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x);
}
var left = 0.0;
for (var rank = 0; rank < rankCount; rank += 1) {
_left[rank] = left;
left = math.max(left, rankRight[rank]);
}
_left[rankCount] = left;
var right = layoutWidth;
_right[rankCount] = right;
for (var rank = rankCount - 1; rank >= 0; rank -= 1) {
right = math.min(right, rankLeft[rank]);
_right[rank] = right;
}
}
final int rankCount;
final double layoutWidth;
final List<double> _left;
final List<double> _right;
/// The usable band in gap [index], inset by at most [clearance].
///
/// The rightmost gap is open-ended because a loop may expand the canvas;
/// every other gap is bounded by the neighbouring columns.
GapBand band(int index, double clearance) {
final gap = index.clamp(0, rankCount);
final left = _left[gap];
final right = _right[gap];
if (gap == rankCount) {
return GapBand(lo: left + clearance, hi: double.infinity, open: true);
}
if (gap == 0) {
return GapBand(
lo: double.negativeInfinity,
hi: right - clearance,
open: true,
);
}
final width = math.max(0.0, right - left);
final inset = math.min(clearance, width / 4);
return GapBand(lo: left + inset, hi: right - inset, open: false);
}
}
/// One usable corridor band.
class GapBand {
const GapBand({required this.lo, required this.hi, required this.open});
final double lo;
final double hi;
final bool open;
}
/// The inset a port keeps from a node corner.
double portInset(GraphNodeBox node, double portSpacing) =>
math.min(portSpacing / 2, node.height / 2);
/// True when an axis-aligned box overlaps [node], optionally inflated by [gap].
bool boxIntersectsNode({
required double x,
required double y,
required double width,
required double height,
required GraphNodeBox node,
double gap = 0,
}) {
return x < node.right + gap &&
x + width > node.x - gap &&
y < node.bottom + gap &&
y + height > node.y - gap;
}
/// True when two label-sized boxes overlap, optionally inflated by [gap].
bool boxesOverlap({
required double ax,
required double ay,
required double aw,
required double ah,
required double bx,
required double by,
required double bw,
required double bh,
double gap = 0,
}) {
return ax < bx + bw + gap &&
ax + aw + gap > bx &&
ay < by + bh + gap &&
ay + ah + gap > by;
}
@@ -0,0 +1,261 @@
/// Pure orthogonal geometry for a workflow graph's edges and labels.
///
/// The caller owns every measurement: node boxes come from the landed
/// `GraphLayout`, label extents are measured after text layout, and clearances
/// or spacings come from [RoutingConfig]. This library never assumes a font,
/// widget style, device class or CSS value, and it has no Flutter imports.
///
/// The same result can be built into a painter, native widgets or a test
/// fixture; no drawing decision lives here.
library;
export 'routing_inputs.dart';
/// One point on an orthogonal route, in graph space.
class RoutePoint {
const RoutePoint(this.x, this.y);
final double x;
final double y;
@override
bool operator ==(Object other) =>
other is RoutePoint && other.x == x && other.y == y;
@override
int get hashCode => Object.hash(x, y);
@override
String toString() => 'RoutePoint($x, $y)';
}
/// The border an edge leaves or enters through.
enum RoutePortSide { top, right, bottom, left }
/// A route endpoint on a node's border.
///
/// [side] is the edge's outward direction: a right port leaves to the right
/// (or enters from the right), a left port leaves to the left, and so on.
class RoutePort {
const RoutePort({required this.side, required this.point});
final RoutePortSide side;
final RoutePoint point;
@override
bool operator ==(Object other) =>
other is RoutePort && other.side == side && other.point == point;
@override
int get hashCode => Object.hash(side, point);
@override
String toString() => 'RoutePort($side, ${point.x}, ${point.y})';
}
/// How an edge relates to the layer it comes from.
enum RouteKind {
/// The target is in a later rank.
forward,
/// Both endpoints share a rank (a cycle or strongly connected component).
sameRank,
/// The target is in an earlier rank. Ranks from `assignGraphRanks` only
/// produce this for a caller-supplied layout; it is still routed honestly.
back,
/// The source and target are the same node.
selfLoop,
}
/// Why an edge has no route.
enum RouteSkipReason {
/// The source key has no placed node.
unknownSource,
/// The target key has no placed node, including an empty/unknown target.
unknownTarget,
}
/// One edge's deterministic orthogonal route.
///
/// [id], [source], [outcome], [target], [label] and [fallback] are copied from
/// the definition edge unchanged. [points] starts at [sourcePort] and ends at
/// [targetPort]; every consecutive pair shares one coordinate.
class EdgeRoute {
EdgeRoute({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.label,
required this.fallback,
required this.kind,
required this.straight,
required this.sourcePort,
required this.targetPort,
required List<RoutePoint> points,
}) : points = List.unmodifiable(points);
final int id;
final String source;
final String outcome;
final String target;
final String label;
final bool fallback;
final RouteKind kind;
/// True when the route is one straight horizontal segment.
final bool straight;
final RoutePort sourcePort;
final RoutePort targetPort;
final List<RoutePoint> points;
@override
bool operator ==(Object other) =>
other is EdgeRoute &&
other.id == id &&
other.source == source &&
other.outcome == outcome &&
other.target == target &&
other.label == label &&
other.fallback == fallback &&
other.kind == kind &&
other.straight == straight &&
other.sourcePort == sourcePort &&
other.targetPort == targetPort &&
_samePoints(other.points, points);
@override
int get hashCode => Object.hash(
id,
source,
outcome,
target,
label,
fallback,
kind,
straight,
sourcePort,
targetPort,
Object.hashAll(points),
);
}
/// One measured label box placed clear of node interiors.
class EdgeLabelBox {
const EdgeLabelBox({
required this.edgeId,
required this.x,
required this.y,
required this.width,
required this.height,
});
final int edgeId;
final double x;
final double y;
final double width;
final double height;
double get right => x + width;
double get bottom => y + height;
@override
bool operator ==(Object other) =>
other is EdgeLabelBox &&
other.edgeId == edgeId &&
other.x == x &&
other.y == y &&
other.width == width &&
other.height == height;
@override
int get hashCode => Object.hash(edgeId, x, y, width, height);
}
/// An edge the router deliberately did not draw.
///
/// The definition identity is preserved so a caller can present a diagnostic
/// instead of inventing a node, route or visit.
class RouteDiagnostic {
const RouteDiagnostic({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.reason,
required this.message,
});
final int id;
final String source;
final String outcome;
final String target;
final RouteSkipReason reason;
final String message;
@override
bool operator ==(Object other) =>
other is RouteDiagnostic &&
other.id == id &&
other.source == source &&
other.outcome == outcome &&
other.target == target &&
other.reason == reason &&
other.message == message;
@override
int get hashCode => Object.hash(id, source, outcome, target, reason, message);
}
/// The complete immutable routing result.
///
/// [width] and [height] include every route point and label box as well as the
/// landed layout bounds, so a loop that leaves the node grid expands the
/// returned box instead of being clipped. [routes] and [skipped] are ordered by
/// definition edge id; [labels] follows the same order.
class GraphRouting {
GraphRouting({
required List<EdgeRoute> routes,
required List<EdgeLabelBox> labels,
required List<RouteDiagnostic> skipped,
required this.width,
required this.height,
}) : routes = List.unmodifiable(routes),
labels = List.unmodifiable(labels),
skipped = List.unmodifiable(skipped);
final List<EdgeRoute> routes;
final List<EdgeLabelBox> labels;
final List<RouteDiagnostic> skipped;
final double width;
final double height;
bool get isEmpty => routes.isEmpty;
/// The route for [id], or null when that edge was skipped.
EdgeRoute? routeFor(int id) {
for (final route in routes) {
if (route.id == id) return route;
}
return null;
}
/// The label box for [id], or null when the edge was skipped.
EdgeLabelBox? labelFor(int id) {
for (final label in labels) {
if (label.edgeId == id) return label;
}
return null;
}
}
bool _samePoints(List<RoutePoint> a, List<RoutePoint> b) {
if (a.length != b.length) return false;
for (var index = 0; index < a.length; index += 1) {
if (a[index] != b[index]) return false;
}
return true;
}
@@ -0,0 +1,64 @@
/// Caller-supplied measurements and clearances for graph-edge routing.
///
/// No font, widget style, device class or CSS value is assumed: every size is
/// measured or chosen by the caller.
library;
void _requireFiniteNonNegative(String name, double value) {
if (!value.isFinite || value < 0) {
throw ArgumentError.value(value, name, 'must be finite and non-negative');
}
}
void _requireFinitePositive(String name, double value) {
if (!value.isFinite || value <= 0) {
throw ArgumentError.value(value, name, 'must be finite and positive');
}
}
/// A caller-measured edge label extent, in logical pixels.
class LabelExtent {
LabelExtent({required this.width, required this.height}) {
_requireFiniteNonNegative('width', width);
_requireFiniteNonNegative('height', height);
}
final double width;
final double height;
}
/// Clearances and spacings a caller reserves for edge geometry.
///
/// [nodeClearance] is the distance a lane or corridor keeps from every node
/// edge. [laneSpacing] separates the horizontal tracks used by wrapping
/// routes, [corridorSpacing] separates vertical tracks inside one column gap,
/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label
/// box off its wire; [boundsPadding] is added to the returned bounds.
///
/// The router may widen a lane step beyond [laneSpacing] when the measured
/// label heights need the room. Inside a narrow column gap it compresses
/// corridor or port spacing rather than routing a track into a node column.
class RoutingConfig {
RoutingConfig({
required this.nodeClearance,
required this.laneSpacing,
required this.corridorSpacing,
required this.portSpacing,
required this.labelGap,
this.boundsPadding = 0,
}) {
_requireFiniteNonNegative('nodeClearance', nodeClearance);
_requireFinitePositive('laneSpacing', laneSpacing);
_requireFinitePositive('corridorSpacing', corridorSpacing);
_requireFinitePositive('portSpacing', portSpacing);
_requireFiniteNonNegative('labelGap', labelGap);
_requireFiniteNonNegative('boundsPadding', boundsPadding);
}
final double nodeClearance;
final double laneSpacing;
final double corridorSpacing;
final double portSpacing;
final double labelGap;
final double boundsPadding;
}
@@ -0,0 +1,126 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/graph_definition.dart';
/// One content-sized stage node as an ordinary native control.
///
/// [node] is the definition identity. [recordedStatus] is executed evidence the
/// caller read from the run; it is shown verbatim and never derived here, so an
/// unvisited or terminal definition node cannot be presented as executed.
class GraphStageNode extends StatelessWidget {
const GraphStageNode({
super.key,
required this.node,
this.recordedStatus,
this.selected = false,
required this.onSelected,
});
final GraphNode node;
/// The run's recorded status word for this node, or null when none exists.
final String? recordedStatus;
/// Whether this definition node is the current graph selection.
final bool selected;
/// Reports [node.key] exactly as the definition recorded it.
final ValueChanged<String> onSelected;
/// Content inset shared by both hosts. It is spacing, not a size: the control
/// still takes its size from its label, and the inset keeps wrapped glyphs
/// clear of a rounded surface's corners.
static const EdgeInsets _contentPadding = EdgeInsets.all(16);
String? get _status {
final status = recordedStatus;
return status != null && status.trim().isNotEmpty ? status : null;
}
String get _label {
final status = _status;
return status == null ? node.label : '${node.label}\n$status';
}
@override
Widget build(BuildContext context) {
final content = ExcludeSemantics(child: _content());
void onPressed() => onSelected(node.key);
return MergeSemantics(
child: Semantics(
button: true,
selected: selected,
label: _label,
child: usesCupertinoHost(context)
? _cupertinoButton(onPressed, content)
: _materialCard(onPressed, content),
),
);
}
/// A stock card, not a stock button: Material's button shape is a stadium,
/// which assumes one line and cuts into a wrapped label's first and last
/// line. A card keeps the rounded-rectangle surface the web node uses, and
/// [selected] only chooses between two stock emphasis levels.
Widget _materialCard(VoidCallback onPressed, Widget content) {
final body = InkWell(
onTap: onPressed,
child: ConstrainedBox(
constraints: const BoxConstraints(minHeight: kMinInteractiveDimension),
child: Padding(
padding: _contentPadding,
child: Align(
alignment: AlignmentDirectional.centerStart,
widthFactor: 1,
heightFactor: 1,
child: content,
),
),
),
);
return selected
? Card.filled(
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: body,
)
: Card.outlined(
margin: EdgeInsets.zero,
clipBehavior: Clip.antiAlias,
child: body,
);
}
/// Tinted is Cupertino's stock low-emphasis surface, so an unselected node is
/// still a visible node body; filled raises the selected one.
Widget _cupertinoButton(VoidCallback onPressed, Widget content) => selected
? CupertinoButton.filled(onPressed: onPressed, child: content)
: CupertinoButton.tinted(onPressed: onPressed, child: content);
Widget _content() {
final status = _status;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(_breakable(node.label), softWrap: true),
if (status != null) Text(_breakable(status), softWrap: true),
],
);
}
/// The web node uses `overflow-wrap: anywhere`; Flutter text does not break a
/// long unbroken key, so the same invisible break opportunities are added.
/// The visible text and the semantics label stay unchanged.
String _breakable(String value) {
final buffer = StringBuffer();
for (final rune in value.runes) {
buffer
..writeCharCode(rune)
..write('\u200B');
}
return buffer.toString();
}
}
@@ -0,0 +1,18 @@
/// A refused operator action and, when one was started, the bounded re-read of
/// server truth that follows it.
///
/// The prompt shows [message] and allows dismissal immediately; it must never
/// wait for [stillPossible]. That future is only observed so a retry can be
/// ruled out once server truth arrives: `true` means the re-read found the run
/// still allows the action, `false` means it plainly does not, and `null` means
/// the re-read failed or was overtaken, leaving a deliberate retry possible.
class ActionRefusal {
const ActionRefusal(this.message, {this.stillPossible});
final String message;
final Future<bool?>? stillPossible;
}
/// Local guards, distinct from a server refusal; they never claim success.
const actionOptionRequired = 'Choose an option before continuing.';
const actionAlreadySending = 'That action is still being sent.';
@@ -0,0 +1,165 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'action_refusal.dart';
import 'cancel_wording.dart';
/// Sends the confirmed cancellation. Returns null once the server has accepted
/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt
/// then stays open with dismissal available immediately.
typedef CancelSubmit = Future<ActionRefusal?> Function();
/// Opens the native cancel confirmation for [runId].
///
/// Nothing is sent until the operator presses the confirm action, and the
/// dismiss action (`Keep`) only closes the prompt.
Future<void> showCancelRunPrompt({
required BuildContext context,
required num runId,
required bool cupertino,
required CancelSubmit onSubmit,
}) {
final prompt = _CancelPrompt(
runId: runId,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _CancelPrompt extends StatefulWidget {
const _CancelPrompt({
required this.runId,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final bool cupertino;
final CancelSubmit onSubmit;
@override
State<_CancelPrompt> createState() => _CancelPromptState();
}
class _CancelPromptState extends State<_CancelPrompt> {
bool _sending = false;
bool _checking = false;
bool _blocked = false;
String? _error;
void _keep() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _confirm() async {
if (_sending || _checking || _blocked) return;
setState(() {
_sending = true;
_error = null;
});
final refusal = await widget.onSubmit();
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
final check = refusal.stillPossible;
setState(() {
_sending = false;
_error = refusal.message;
_checking = check != null;
});
if (check == null) return;
bool? stillPossible;
try {
stillPossible = await check;
} catch (_) {
// The action reports re-read failures as null; never fabricate one here.
}
if (!mounted) return;
setState(() {
_checking = false;
_blocked = stillPossible == false;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
bool get _confirmDisabled => _sending || _checking || _blocked;
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: Text(cancelDialogTitle(widget.runId)),
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
actions: [
TextButton(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
FilledButton(
key: cancelConfirmKey,
onPressed: _confirmDisabled ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(cancelDialogTitle(widget.runId)),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
CupertinoDialogAction(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
CupertinoDialogAction(
key: cancelConfirmKey,
isDestructiveAction: true,
onPressed: _confirmDisabled ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _body({required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(cancelDialogMessage),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: cancelErrorKey, style: errorStyle),
),
],
);
}
}
@@ -0,0 +1,31 @@
import '../../../core/api_gateway.dart';
/// Whether the operator may cancel [run], matching `canCancel` in
/// `web/src/actions.js` exactly:
///
/// `(executing || (status == "waiting" && export_pending_sequence > 0)) &&
/// !cancel_requested && !cleanup_unconfirmed`
///
/// The status word alone is not enough: a stale `running` status without
/// `executing` is not cancellable, while a run waiting on a pending session
/// export is.
bool canCancelRun(JsonMap? run) {
if (run == null) return false;
final exportPending = _number(run['export_pending_sequence']);
return (run['executing'] == true ||
(run['status'] == 'waiting' && exportPending > 0)) &&
run['cancel_requested'] != true &&
run['cleanup_unconfirmed'] != true;
}
/// The run id used by the cancel request, or null for a malformed run.
num? cancelRunId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
/// `Number(value) > 0`, tolerating numeric strings as the browser does.
double _number(dynamic value) {
if (value is num) return value.toDouble();
return double.tryParse('${value ?? ''}'.trim()) ?? 0;
}
@@ -0,0 +1,119 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'action_refusal.dart';
import 'cancel_dialog.dart';
import 'cancel_eligibility.dart';
import 'cancel_wording.dart';
/// The run detail's deliberate cancel entry point.
///
/// Renders one native button only while [run] is cancellable under the browser
/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends
/// nothing; only the confirm action asks the server to stop the run. A refusal
/// is returned to the kept-open prompt immediately and the run is re-read
/// separately, so [onRunChanged] still receives server truth without locking
/// the prompt while that read is pending.
class CancelRunAction extends StatefulWidget {
const CancelRunAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<CancelRunAction> createState() => _CancelRunActionState();
}
class _CancelRunActionState extends State<CancelRunAction> {
bool _dialogOpen = false;
Future<bool?>? _resync;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = cancelRunId(widget.run);
if (id == null || !canCancelRun(widget.run) || _dialogOpen) return;
_dialogOpen = true;
try {
await showCancelRunPrompt(
context: context,
runId: id,
cupertino: _usesCupertino(context),
onSubmit: () => _submit(id),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<ActionRefusal?> _submit(num id) async {
final repository = RunsRepository(widget.gateway);
try {
final run = await repository.cancelRun(id);
if (!mounted) return null;
if (_owns(id)) widget.onRunChanged(run);
return null;
} catch (error) {
return ActionRefusal(
describeCancelError(error),
stillPossible: _resyncRun(id),
);
}
}
bool _owns(num id) => mounted && cancelRunId(widget.run) == id;
/// One bounded re-read per refusal. A refusal that arrives while a read is
/// already in flight observes that same read instead of starting another.
Future<bool?> _resyncRun(num id) {
return _resync ??= _readRun(id);
}
Future<bool?> _readRun(num id) async {
try {
final run = await RunsRepository(widget.gateway).getRun(id);
if (!_owns(id)) return null;
widget.onRunChanged(run);
return canCancelRun(run);
} catch (_) {
// Unknown server truth: keep the refusal and leave a deliberate retry.
return null;
} finally {
_resync = null;
}
}
@override
Widget build(BuildContext context) {
if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) {
return const SizedBox.shrink();
}
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
return FilledButton(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
}
@@ -0,0 +1,23 @@
import 'package:flutter/widgets.dart';
/// The browser client's cancel wording, kept verbatim.
const cancelActionLabel = 'Cancel run';
const cancelDialogMessage = 'This asks the server to stop the active run.';
const cancelConfirmLabel = 'Cancel run';
const cancelKeepLabel = 'Keep';
/// Stable test/semantics keys shared by the action and its prompt.
const cancelActionKey = ValueKey<String>('cancel-run-action');
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
const cancelErrorKey = ValueKey<String>('cancel-run-error');
/// The cancel dialog's title: `Cancel run {id}?`.
String cancelDialogTitle(num runId) => 'Cancel run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a cancellation that did not happen.
String describeCancelError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not cancel the run.' : message;
}
@@ -0,0 +1,176 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../domain/run_decisions.dart';
import '../domain/run_models.dart';
import 'action_refusal.dart';
import 'decision_dialog.dart';
import 'decision_wording.dart';
/// The run detail's deliberate human-decision entry point.
///
/// Renders one native button only while [run] is genuinely waiting on a person.
/// Nothing is sent until the operator opens the prompt, chooses an option and
/// presses Confirm; cancel, selection and optional feedback stay local. A
/// server refusal is shown verbatim in the prompt immediately, the draft is
/// preserved and the run is re-read separately so [onRunChanged] still receives
/// server truth without locking the prompt while that read is pending.
class HumanDecisionAction extends StatefulWidget {
const HumanDecisionAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
this.cupertino,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
/// Overrides the platform style; by default it follows the enclosing app.
final bool? cupertino;
@override
State<HumanDecisionAction> createState() => _HumanDecisionActionState();
}
class _HumanDecisionActionState extends State<HumanDecisionAction> {
PendingDecision? _pending;
bool _dialogOpen = false;
bool _sending = false;
Future<bool?>? _resync;
@override
void initState() {
super.initState();
_pending = pendingDecision(widget.run);
}
@override
void didUpdateWidget(covariant HumanDecisionAction oldWidget) {
super.didUpdateWidget(oldWidget);
_pending = pendingDecision(widget.run);
}
bool _usesCupertino(BuildContext context) {
if (widget.cupertino != null) return widget.cupertino!;
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final decision = _pending;
if (decision == null || _dialogOpen) return;
_dialogOpen = true;
try {
await showHumanDecisionPrompt(
context: context,
decision: decision,
cupertino: _usesCupertino(context),
onSubmit: (draft) => _submit(decision, draft),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<ActionRefusal?> _submit(
PendingDecision decision,
DecisionDraft draft,
) async {
final option = draft.selected?.trim() ?? '';
if (option.isEmpty) return const ActionRefusal(actionOptionRequired);
if (_sending) return const ActionRefusal(actionAlreadySending);
_sending = true;
final repository = RunsRepository(widget.gateway);
try {
final JsonMap run;
try {
run = await repository.decideRun(
decision.runId,
stage: decision.stageKey,
option: option,
feedback: draft.feedback,
);
} catch (error) {
return ActionRefusal(
_describe(error),
stillPossible: _resyncRun(decision),
);
}
if (!mounted) return null;
if (_owns(decision.runId)) {
setState(() => _pending = pendingDecision(run));
widget.onRunChanged(run);
}
return null;
} finally {
_sending = false;
}
}
bool _owns(num id) => mounted && widget.run['id'] == id;
/// One bounded re-read per refusal. A refusal that arrives while a read is
/// already in flight observes that same read instead of starting another.
Future<bool?> _resyncRun(PendingDecision decision) {
return _resync ??= _readRun(decision);
}
Future<bool?> _readRun(PendingDecision expected) async {
try {
final run = await RunsRepository(widget.gateway).getRun(expected.runId);
if (!_owns(expected.runId)) return null;
final next = pendingDecision(run);
setState(() => _pending = next);
widget.onRunChanged(run);
return _stillDecidable(next, expected);
} catch (_) {
// Unknown server truth: keep the refusal and leave a deliberate retry.
return null;
} finally {
_resync = null;
}
}
/// Whether the refreshed run offers the same decision the prompt is showing.
bool _stillDecidable(PendingDecision? next, PendingDecision expected) {
if (next == null ||
next.runId != expected.runId ||
next.stageKey != expected.stageKey) {
return false;
}
final keys = next.options.map((option) => option.key).toSet();
return expected.options.every((option) => keys.contains(option.key));
}
@override
Widget build(BuildContext context) {
final decision = _pending;
if (decision == null) return const SizedBox.shrink();
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: decisionActionKey,
onPressed: _open,
child: const Text(decisionActionLabel),
);
}
return FilledButton(
key: decisionActionKey,
onPressed: _open,
child: const Text(decisionActionLabel),
);
}
}
String _describe(Object error) {
final message = '$error';
return message.trim().isEmpty ? 'The server refused the decision.' : message;
}
@@ -0,0 +1,268 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/run_decisions.dart';
import '../domain/run_models.dart';
import 'action_refusal.dart';
import 'decision_wording.dart';
/// Sends the draft to the server. Returns null on success, or an
/// [ActionRefusal] with the server's words verbatim; the prompt stays open
/// with the draft intact and dismissal available immediately.
typedef DecisionSubmit = Future<ActionRefusal?> Function(DecisionDraft draft);
/// Opens the native decision prompt for [decision].
Future<void> showHumanDecisionPrompt({
required BuildContext context,
required PendingDecision decision,
required bool cupertino,
required DecisionSubmit onSubmit,
}) {
final prompt = _DecisionPrompt(
decision: decision,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _DecisionPrompt extends StatefulWidget {
const _DecisionPrompt({
required this.decision,
required this.cupertino,
required this.onSubmit,
});
final PendingDecision decision;
final bool cupertino;
final DecisionSubmit onSubmit;
@override
State<_DecisionPrompt> createState() => _DecisionPromptState();
}
class _DecisionPromptState extends State<_DecisionPrompt> {
DecisionDraft _draft = const DecisionDraft();
late final TextEditingController _feedback = TextEditingController();
bool _sending = false;
bool _checking = false;
bool _blocked = false;
String? _error;
@override
void dispose() {
_feedback.dispose();
super.dispose();
}
void _select(String option) {
if (_sending) return;
setState(() => _draft = _draft.select(option));
}
void _feedbackChanged(String value) => _draft = _draft.withFeedback(value);
void _cancel() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _confirm() async {
if (_sending || _checking || _blocked || !_draft.canSubmit) return;
setState(() {
_sending = true;
_error = null;
});
final refusal = await widget.onSubmit(_draft);
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
final check = refusal.stillPossible;
setState(() {
_sending = false;
_error = refusal.message;
_checking = check != null;
});
if (check == null) return;
bool? stillPossible;
try {
stillPossible = await check;
} catch (_) {
// The action reports re-read failures as null; never fabricate one here.
}
if (!mounted) return;
setState(() {
_checking = false;
_blocked = stillPossible == false;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
bool get _confirmDisabled => _sending || _checking || _blocked;
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: const Text(decisionWaitingTitle),
content: _body(
errorStyle: TextStyle(color: theme.colorScheme.error),
options: RadioGroup<String>(
groupValue: _draft.selected,
onChanged: (value) {
if (value != null) _select(value);
},
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final option in widget.decision.options)
RadioListTile<String>(
value: option.key,
enabled: !_sending,
title: Text(option.key),
subtitle: _target(option),
),
],
),
),
feedback: TextField(
key: decisionFeedbackKey,
controller: _feedback,
enabled: !_sending,
decoration: const InputDecoration(labelText: decisionFeedbackLabel),
textInputAction: TextInputAction.done,
onChanged: _feedbackChanged,
onSubmitted: (_) => _confirm(),
),
),
actions: [
TextButton(
onPressed: _sending ? null : _cancel,
child: const Text(decisionCancelLabel),
),
FilledButton(
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: const Text(decisionWaitingTitle),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
options: RadioGroup<String>(
groupValue: _draft.selected,
onChanged: (value) {
if (value != null) _select(value);
},
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final option in widget.decision.options)
CupertinoButton(
onPressed: _sending ? null : () => _select(option.key),
child: Row(
children: [
CupertinoRadio<String>(
value: option.key,
useCheckmarkStyle: true,
enabled: !_sending,
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(option.key),
if (_targetText(option) case final target?)
Text(target),
],
),
),
],
),
),
],
),
),
feedback: CupertinoTextField(
key: decisionFeedbackKey,
controller: _feedback,
enabled: !_sending,
placeholder: decisionFeedbackLabel,
textInputAction: TextInputAction.done,
onChanged: _feedbackChanged,
onSubmitted: (_) => _confirm(),
),
),
actions: [
CupertinoDialogAction(
onPressed: _sending ? null : _cancel,
child: const Text(decisionCancelLabel),
),
CupertinoDialogAction(
isDefaultAction: true,
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
),
],
);
}
Widget _body({
required TextStyle errorStyle,
required Widget options,
required Widget feedback,
}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(decisionMeta(widget.decision)),
if (widget.decision.instructions.trim().isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(widget.decision.instructions),
),
Padding(padding: const EdgeInsets.only(top: 8), child: options),
Padding(padding: const EdgeInsets.only(top: 8), child: feedback),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: decisionErrorKey, style: errorStyle),
),
],
);
}
Widget? _target(DecisionOption option) {
final text = _targetText(option);
return text == null ? null : Text(text);
}
String? _targetText(DecisionOption option) {
final text = decisionTargetText(option.target);
return text.isEmpty ? null : text;
}
}
@@ -0,0 +1,24 @@
import 'package:flutter/widgets.dart';
import '../domain/run_decisions.dart';
/// The browser client's decision wording, kept verbatim.
const decisionWaitingTitle = 'Waiting for your decision';
const decisionActionLabel = 'Decide';
const decisionFeedbackLabel = 'Feedback (optional)';
const decisionCancelLabel = 'Cancel';
const decisionConfirmLabel = 'Confirm decision';
const decisionSendingLabel = 'Sending…';
/// Stable test/semantics keys shared by the action and its prompt.
const decisionActionKey = ValueKey<String>('human-decision-action');
const decisionFeedbackKey = ValueKey<String>('human-decision-feedback');
const decisionErrorKey = ValueKey<String>('human-decision-error');
/// `{stage} · run {id} · {label}`, as the web decision card shows it.
String decisionMeta(PendingDecision decision) =>
'${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}';
/// The option's target line, `→ {target}`, or "" when no target was declared.
String decisionTargetText(String target) =>
target.trim().isEmpty ? '' : '→ $target';
@@ -0,0 +1,123 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'action_refusal.dart';
import 'retry_dialog.dart';
import 'retry_eligibility.dart';
import 'retry_intent.dart';
import 'retry_wording.dart';
/// The run detail's deliberate retry entry point.
///
/// Renders one native button only while [run] is a stopped `failed` run. Opening
/// the resume or restart confirmation sends nothing; only the confirm action
/// asks the server to retry. A refusal is returned to the kept-open prompt
/// immediately and the run is re-read separately, so [onRunChanged] still
/// receives server truth without locking the prompt while that read is pending.
class RetryRunAction extends StatefulWidget {
const RetryRunAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<RetryRunAction> createState() => _RetryRunActionState();
}
class _RetryRunActionState extends State<RetryRunAction> {
bool _dialogOpen = false;
Future<bool?>? _resync;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = retryRunId(widget.run);
if (id == null || !canRetryRun(widget.run) || _dialogOpen) return;
_dialogOpen = true;
try {
await showRetryRunPrompt(
context: context,
runId: id,
cupertino: _usesCupertino(context),
onSubmit: (intent) => _submit(id, intent),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<ActionRefusal?> _submit(num id, RetryIntent intent) async {
final repository = RunsRepository(widget.gateway);
try {
final run = await repository.retryRun(
id,
requestKey: intent.requestKey,
mode: intent.mode.wireMode,
);
if (!mounted) return null;
if (_owns(id)) widget.onRunChanged(run);
return null;
} catch (error) {
return ActionRefusal(
describeRetryError(error),
stillPossible: _resyncRun(id),
);
}
}
bool _owns(num id) => mounted && retryRunId(widget.run) == id;
/// One bounded re-read per refusal. A refusal that arrives while a read is
/// already in flight observes that same read instead of starting another.
Future<bool?> _resyncRun(num id) {
return _resync ??= _readRun(id);
}
Future<bool?> _readRun(num id) async {
try {
final run = await RunsRepository(widget.gateway).getRun(id);
if (!_owns(id)) return null;
widget.onRunChanged(run);
return canRetryRun(run);
} catch (_) {
// Unknown server truth: keep the refusal and leave a deliberate retry.
return null;
} finally {
_resync = null;
}
}
@override
Widget build(BuildContext context) {
if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) {
return const SizedBox.shrink();
}
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: retryActionKey,
onPressed: _open,
child: const Text(retryActionLabel),
);
}
return FilledButton(
key: retryActionKey,
onPressed: _open,
child: const Text(retryActionLabel),
);
}
}
@@ -0,0 +1,207 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'action_refusal.dart';
import 'retry_intent.dart';
import 'retry_wording.dart';
/// Sends the confirmed retry intent. Returns null once the server has accepted
/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt
/// then stays open with dismissal available immediately.
typedef RetrySubmit = Future<ActionRefusal?> Function(RetryIntent intent);
/// Opens the native retry confirmation for [runId].
///
/// The first confirmation offers resume (the default) and a secondary
/// `Restart from start` confirmation, exactly like the browser's retry dialog.
/// Nothing is sent until the operator presses a confirm action; `Keep` only
/// closes the prompt.
Future<void> showRetryRunPrompt({
required BuildContext context,
required num runId,
required bool cupertino,
required RetrySubmit onSubmit,
}) {
final prompt = _RetryPrompt(
runId: runId,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _RetryPrompt extends StatefulWidget {
const _RetryPrompt({
required this.runId,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final bool cupertino;
final RetrySubmit onSubmit;
@override
State<_RetryPrompt> createState() => _RetryPromptState();
}
class _RetryPromptState extends State<_RetryPrompt> {
RetryMode _mode = RetryMode.resume;
String? _requestKey;
bool _sending = false;
bool _checking = false;
bool _blocked = false;
bool _attempted = false;
String? _error;
void _keep() {
if (!_sending) Navigator.of(context).pop();
}
void _restart() {
if (_sending || _checking || _attempted) return;
setState(() {
_mode = RetryMode.restart;
_error = null;
});
}
Future<void> _confirm() async {
if (_sending || _checking || _blocked) return;
setState(() {
_sending = true;
_attempted = true;
_error = null;
});
final intent = RetryIntent(
mode: _mode,
requestKey: _requestKey ??= newRetryRequestKey(widget.runId),
);
final refusal = await widget.onSubmit(intent);
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
final check = refusal.stillPossible;
setState(() {
_sending = false;
_error = refusal.message;
_checking = check != null;
});
if (check == null) return;
bool? stillPossible;
try {
stillPossible = await check;
} catch (_) {
// The action reports re-read failures as null; never fabricate one here.
}
if (!mounted) return;
setState(() {
_checking = false;
_blocked = stillPossible == false;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
bool get _confirmDisabled => _sending || _checking || _blocked;
bool get _showRestart => _mode == RetryMode.resume && !_attempted;
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: Text(_dialogTitle),
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
actions: [
if (_showRestart)
TextButton(
key: retryRestartKey,
onPressed: _sending || _checking ? null : _restart,
child: const Text(restartConfirmLabel),
),
TextButton(
key: retryKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(retryKeepLabel),
),
FilledButton(
key: retryConfirmKey,
onPressed: _confirmDisabled ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(_dialogTitle),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
if (_showRestart)
CupertinoDialogAction(
key: retryRestartKey,
onPressed: _sending || _checking ? null : _restart,
child: const Text(restartConfirmLabel),
),
CupertinoDialogAction(
key: retryKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(retryKeepLabel),
),
CupertinoDialogAction(
key: retryConfirmKey,
isDestructiveAction: _mode == RetryMode.restart,
onPressed: _confirmDisabled ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
Widget _body({required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(_dialogMessage),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: retryErrorKey, style: errorStyle),
),
],
);
}
String get _dialogTitle => _mode == RetryMode.restart
? restartDialogTitle(widget.runId)
: retryDialogTitle(widget.runId);
String get _dialogMessage =>
_mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage;
String get _confirmLabel =>
_mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel;
}
@@ -0,0 +1,16 @@
import '../../../core/api_gateway.dart';
/// Whether the operator may retry [run], matching `canRetry` in
/// `web/src/actions.js` exactly: a loaded run that is not executing and whose
/// status is `failed`. A stale `failed` status while the run still executes is
/// not retryable.
bool canRetryRun(JsonMap? run) {
if (run == null) return false;
return run['executing'] != true && run['status'] == 'failed';
}
/// The run id used by the retry request, or null for a malformed run.
num? retryRunId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
@@ -0,0 +1,29 @@
import 'dart:math';
/// The two deliberate retry choices. `resume` is the server's default, so its
/// wire field is omitted; `restart` replays the whole pipeline.
enum RetryMode {
resume,
restart;
/// The `retry_mode` value to send, or null to let the server resume.
String? get wireMode => this == RetryMode.restart ? 'restart' : null;
}
/// One confirmed retry intent: the chosen mode plus the idempotency key that
/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the
/// server can dedupe it; a fresh deliberate intent uses a new key.
class RetryIntent {
const RetryIntent({required this.mode, required this.requestKey});
final RetryMode mode;
final String requestKey;
}
/// 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);
return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}';
}
@@ -0,0 +1,33 @@
import 'package:flutter/widgets.dart';
/// The browser client's retry wording, kept verbatim.
const retryActionLabel = 'Retry';
const retryDialogMessage =
'Only failed runs can be retried. The server starts a new run from the '
'same input.';
const retryConfirmLabel = 'Retry';
const restartDialogMessage =
'This replays the whole pipeline from the start instead of resuming the '
'failed stage.';
const restartConfirmLabel = 'Restart from start';
const retryKeepLabel = 'Keep';
/// Stable test/semantics keys shared by the action and its prompt.
const retryActionKey = ValueKey<String>('retry-run-action');
const retryKeepKey = ValueKey<String>('retry-run-keep');
const retryConfirmKey = ValueKey<String>('retry-run-confirm');
const retryRestartKey = ValueKey<String>('retry-run-restart');
const retryErrorKey = ValueKey<String>('retry-run-error');
/// The retry dialog's title: `Retry run {id}?`.
String retryDialogTitle(num runId) => 'Retry run $runId?';
/// The restart dialog's title: `Restart run {id}?`.
String restartDialogTitle(num runId) => 'Restart run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a retry that did not happen.
String describeRetryError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not retry the run.' : message;
}
@@ -0,0 +1,109 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'action_refusal.dart';
import 'title_dialog.dart';
import 'title_wording.dart';
/// The run detail's rename entry point, mirroring the browser's rename row.
///
/// The prompt starts with [run]'s stored title exactly as the server sent it
/// (never a prompt or output fallback). Typing and Cancel send nothing; only
/// Save sends `set_run_title` with the exact run id and title text. A refusal is
/// returned verbatim to the kept-open prompt, and only the server's returned
/// `run_detail` is delivered through [onRunChanged], once.
class RunTitleAction extends StatefulWidget {
const RunTitleAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<RunTitleAction> createState() => _RunTitleActionState();
}
class _RunTitleActionState extends State<RunTitleAction> {
bool _dialogOpen = false;
bool _saving = false;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = runTitleId(widget.run);
if (id == null || _dialogOpen) return;
_dialogOpen = true;
try {
await showRunTitlePrompt(
context: context,
runId: id,
initialTitle: storedRunTitle(widget.run),
cupertino: _usesCupertino(context),
onSubmit: (title) => _submit(id, title),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<ActionRefusal?> _submit(num id, String title) async {
if (_saving) return const ActionRefusal(actionAlreadySending);
_saving = true;
try {
final run = await RunsRepository(widget.gateway).setRunTitle(id, title);
if (!mounted) return null;
if (_owns(id)) widget.onRunChanged(run);
return null;
} catch (error) {
return ActionRefusal(describeTitleError(error));
} finally {
_saving = false;
}
}
bool _owns(num id) => mounted && runTitleId(widget.run) == id;
@override
Widget build(BuildContext context) {
if (runTitleId(widget.run) == null) return const SizedBox.shrink();
if (_usesCupertino(context)) {
return CupertinoButton(
key: runTitleActionKey,
onPressed: _open,
child: const Text(runTitleActionLabel),
);
}
return OutlinedButton(
key: runTitleActionKey,
onPressed: _open,
child: const Text(runTitleActionLabel),
);
}
}
/// The run id used by the rename request, or null for a malformed run.
num? runTitleId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
/// The run's stored title exactly as the browser reads it
/// (`String(d.title ?? "")`); never inferred from the prompt or output.
String storedRunTitle(JsonMap run) {
final title = run['title'];
return title == null ? '' : '$title';
}
@@ -0,0 +1,183 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'action_refusal.dart';
import 'title_wording.dart';
/// Sends the typed title. Returns null once the server has accepted it, or an
/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays
/// open with the typed title intact.
typedef TitleSubmit = Future<ActionRefusal?> Function(String title);
/// Opens the native rename prompt for [runId], seeded with the run's stored
/// [initialTitle].
///
/// Typing and the dismiss action send nothing; only Save sends the title. The
/// title is passed through exactly as typed, including surrounding whitespace,
/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether
/// a blank title is acceptable.
Future<void> showRunTitlePrompt({
required BuildContext context,
required num runId,
required String initialTitle,
required bool cupertino,
required TitleSubmit onSubmit,
}) {
final prompt = _TitlePrompt(
runId: runId,
initialTitle: initialTitle,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _TitlePrompt extends StatefulWidget {
const _TitlePrompt({
required this.runId,
required this.initialTitle,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final String initialTitle;
final bool cupertino;
final TitleSubmit onSubmit;
@override
State<_TitlePrompt> createState() => _TitlePromptState();
}
class _TitlePromptState extends State<_TitlePrompt> {
late final TextEditingController _title = TextEditingController(
text: widget.initialTitle,
);
bool _sending = false;
String? _error;
@override
void dispose() {
_title.dispose();
super.dispose();
}
void _cancel() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _save() async {
if (_sending) return;
setState(() {
_sending = true;
_error = null;
});
final refusal = await widget.onSubmit(_title.text);
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
setState(() {
_sending = false;
_error = refusal.message;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: const Text(runTitleDialogTitle),
content: _body(
field: TextField(
key: runTitleFieldKey,
controller: _title,
enabled: !_sending,
autofocus: true,
decoration: const InputDecoration(labelText: runTitleFieldLabel),
textInputAction: TextInputAction.done,
onSubmitted: (_) => _save(),
),
errorStyle: TextStyle(color: theme.colorScheme.error),
),
actions: [
TextButton(
key: runTitleCancelKey,
onPressed: _sending ? null : _cancel,
child: const Text(runTitleCancelLabel),
),
FilledButton(
key: runTitleSaveKey,
onPressed: _sending ? null : _save,
child: const Text(runTitleSaveLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: const Text(runTitleDialogTitle),
content: _body(
field: CupertinoTextField(
key: runTitleFieldKey,
controller: _title,
enabled: !_sending,
autofocus: true,
placeholder: runTitleFieldLabel,
textInputAction: TextInputAction.done,
onSubmitted: (_) => _save(),
),
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
CupertinoDialogAction(
key: runTitleCancelKey,
onPressed: _sending ? null : _cancel,
child: const Text(runTitleCancelLabel),
),
CupertinoDialogAction(
key: runTitleSaveKey,
isDefaultAction: true,
onPressed: _sending ? null : _save,
child: const Text(runTitleSaveLabel),
),
],
);
}
Widget _body({required Widget field, required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
field,
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: runTitleErrorKey, style: errorStyle),
),
],
);
}
}
@@ -0,0 +1,24 @@
import 'package:flutter/widgets.dart';
/// The browser client's rename wording, kept verbatim.
const runTitleActionLabel = 'Rename';
const runTitleDialogTitle = 'Rename';
const runTitleFieldLabel = 'Run title';
const runTitleSaveLabel = 'Save';
const runTitleCancelLabel = 'Cancel';
/// Stable test/semantics keys shared by the action and its prompt.
const runTitleActionKey = ValueKey<String>('rename-run-action');
const runTitleFieldKey = ValueKey<String>('rename-run-field');
const runTitleSaveKey = ValueKey<String>('rename-run-save');
const runTitleCancelKey = ValueKey<String>('rename-run-cancel');
const runTitleErrorKey = ValueKey<String>('rename-run-error');
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a rename that did not happen.
String describeTitleError(Object error) {
final message = '$error';
return message.trim().isEmpty
? 'The server did not rename the run.'
: message;
}
@@ -0,0 +1,105 @@
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
/// Protocol failure kept separate from transport errors; server error envelopes
/// are otherwise propagated unchanged by [ApiGateway].
class RunsRepositoryException implements Exception {
const RunsRepositoryException(this.message);
final String message;
@override
String toString() => message;
}
/// Run protocol requests over the application's shared gateway.
class RunsRepository {
RunsRepository(this._gateway);
final ApiGateway _gateway;
Future<RunListResult> listRuns() async {
final reply = await _gateway.call('list_runs');
final runs = reply['runs'];
return RunListResult(
runs is List
? runs
.whereType<Map>()
.map((r) => Map<String, dynamic>.from(r))
.toList()
: const [],
reply['usage'] is Map
? Map<String, dynamic>.from(reply['usage'] as Map)
: null,
);
}
Future<JsonMap> getRun(num id) async =>
_required(await _gateway.call('get_run', {'run_id': id}), 'run_detail');
Future<JsonMap> cancelRun(num id) async => _required(
await _gateway.call('cancel_run', {'run_id': id}),
'run_detail',
);
Future<JsonMap> retryRun(
num id, {
required String requestKey,
String? mode,
}) async {
final fields = <String, dynamic>{'run_id': id, 'request_key': requestKey};
if (mode == 'restart') fields['retry_mode'] = mode;
return _required(await _gateway.call('retry_run', fields), 'run_detail');
}
Future<JsonMap> decideRun(
num id, {
String? stage,
required String option,
String feedback = '',
}) async {
final selected = option.trim();
if (selected.isEmpty) {
throw const RunsRepositoryException(
'Choose an option before continuing.',
);
}
final fields = <String, dynamic>{'run_id': id, 'option': selected};
if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage;
if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim();
return _required(await _gateway.call('decide_run', fields), 'run_detail');
}
Future<JsonMap> setRunTitle(num id, String title) async => _required(
await _gateway.call('set_run_title', {'run_id': id, 'title': title}),
'run_detail',
);
Future<JsonMap> startRun({
required num pipelineId,
required num version,
required String prompt,
required String workspace,
required String requestKey,
String title = '',
String outputFormat = '',
String notifyMode = 'auto',
}) async {
final fields = <String, dynamic>{
'pipeline_id': pipelineId,
'version': version,
'request_key': requestKey,
'workspace': workspace.trim(),
'input': {'prompt': prompt},
};
if (title.trim().isNotEmpty) fields['title'] = title.trim();
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
final mode = notifyMode.trim().toLowerCase();
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
}
JsonMap _required(JsonMap reply, String key) {
final value = reply[key];
if (value is! Map) {
throw RunsRepositoryException('The server returned no $key.');
}
return Map<String, dynamic>.from(value);
}
}
@@ -0,0 +1,110 @@
import '../../../core/api_gateway.dart';
import 'run_models.dart';
class PendingDecision {
const PendingDecision({
required this.runId,
required this.runLabel,
required this.stageKey,
required this.instructions,
required this.options,
});
final num runId;
final String runLabel;
final String stageKey;
final String instructions;
final List<DecisionOption> options;
}
JsonMap? lastWaitingStep(List<dynamic> steps) {
for (final value in steps.reversed) {
if (value is Map && value['status'] == 'waiting') {
return Map<String, dynamic>.from(value);
}
}
return null;
}
String waitingPrompt(dynamic output) =>
output is Map && output['prompt'] is String
? output['prompt'] as String
: '';
List<String> waitingOptions(dynamic output) {
final options = output is Map ? output['options'] : null;
if (options is! List) return const [];
return options
.whereType<String>()
.where((entry) => entry.trim().isNotEmpty)
.toList();
}
List<String> humanOptions(dynamic edges) {
if (edges is! Map) return const [];
return edges.keys.map((key) => '$key').where((key) => key != 'error').toList()
..sort();
}
PendingDecision? pendingDecision(JsonMap? run) {
if (run == null ||
run['status'] != 'waiting' ||
_positive(run['export_pending_sequence'])) {
return null;
}
final steps = run['steps'] is List ? run['steps'] as List : const [];
final step = lastWaitingStep(steps);
final stage = _string(step?['stage']).trim().isNotEmpty
? _string(step?['stage'])
: _string(run['current_stage']);
if (stage.trim().isEmpty) return null;
JsonMap? declaration;
final graph = run['graph'];
final graphStages = graph is Map ? graph['stages'] : null;
if (graphStages is List) {
for (final value in graphStages.whereType<Map>()) {
if (value['key'] == stage) {
declaration = Map<String, dynamic>.from(value);
break;
}
}
}
if (declaration?['type'] != null && declaration!['type'] != 'human') {
return null;
}
final edges = declaration?['edges'];
final options = waitingOptions(step?['output']);
final keys = options.isNotEmpty ? options : humanOptions(edges);
if (keys.isEmpty) return null;
final instructions = waitingPrompt(step?['output']).trim().isNotEmpty
? waitingPrompt(step?['output'])
: _string(declaration?['prompt']);
return PendingDecision(
runId: run['id'] is num ? run['id'] as num : 0,
runLabel: runIdentity(run['title'], run['name']).label,
stageKey: stage,
instructions: instructions,
options: keys
.map(
(key) => DecisionOption(
key,
target: _targetLabel(key, edges is Map ? edges[key] : null),
),
)
.toList(),
);
}
String _targetLabel(String option, dynamic target) {
if (target == null || '$target'.trim().isEmpty) return '';
final resolved = target == '#'
? (option == 'error' ? '#failure' : '#success')
: '$target';
return switch (resolved) {
'#success' => 'SUCCESS',
'#failure' => 'FAILURE',
_ => resolved,
};
}
bool _positive(dynamic value) => value is num && value > 0;
String _string(dynamic value) => value == null ? '' : '$value';
@@ -0,0 +1,226 @@
import '../../../core/api_gateway.dart';
import 'run_step_evidence.dart';
const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
bool isTerminalRunStatus(dynamic status) =>
terminalRunStatuses.contains(_word(status));
bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
int runLifecycleRank(dynamic status) => switch (_word(status)) {
'queued' => 0,
'running' || 'waiting' => 1,
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
_ => -1,
};
int stepLifecycleRank(dynamic status) => switch (_word(status)) {
'running' || 'waiting' => 1,
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
_ => -1,
};
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
if (_word(incoming).isEmpty) return false;
final oldRank = rank(current);
final newRank = rank(incoming);
return oldRank >= 0 &&
newRank >= 0 &&
(newRank < oldRank ||
(oldRank == 2 && newRank == 2 && incoming != current));
}
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
final oldRank = rank(current);
final newRank = rank(incoming);
if (oldRank < 0) return '$incoming';
if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) {
return '${current ?? ''}';
}
return '$incoming';
}
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
'queued' || 'running' => true,
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
_ => current,
};
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) {
final oldId = _positiveInt(current['schedule_id']);
final newId = _positiveInt(frame['schedule_id']);
final known =
current.containsKey('scheduled') ||
frame.containsKey('scheduled') ||
oldId > 0 ||
newId > 0;
if (!known) return {};
final id = oldId > 0 ? oldId : newId;
final nameConflict = oldId > 0 && newId > 0 && oldId != newId;
final name =
'${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}';
return {
'scheduled':
current['scheduled'] == true || frame['scheduled'] == true || id > 0,
if (id > 0) 'schedule_id': id,
if (name.isNotEmpty) 'schedule_name': name,
};
}
int _positiveInt(dynamic value) =>
value is num && value > 0 ? value.toInt() : 0;
JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
if (_stale(current['status'], frame['status'], runLifecycleRank) &&
frame['resource_wait_set'] != true) {
return current;
}
final beforeStatus = '${current['status'] ?? ''}';
final status =
frame['resource_wait_set'] == true &&
frame['status'] == 'queued' &&
!isTerminalRunStatus(beforeStatus)
? 'queued'
: _advance(beforeStatus, frame['status'], runLifecycleRank);
final merged = <String, dynamic>{
...current,
..._scheduleOrigin(current, frame),
'status': status,
'executing': executingFor(status, current['executing'] == true),
'completed_steps': _maxInt(
current['completed_steps'],
frame['completed_steps'],
),
'resource_wait': isTerminalRunStatus(status)
? null
: frame['resource_wait_set'] == true
? frame['resource_wait']
: current['resource_wait'],
'notify_mode': _blank(frame['notify_mode'])
? current['notify_mode'] ?? 'auto'
: frame['notify_mode'],
'cancel_requested':
current['cancel_requested'] == true ||
frame['cancel_requested'] == true,
'cleanup_unconfirmed':
current['cleanup_unconfirmed'] == true ||
frame['cleanup_unconfirmed'] == true,
};
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
if (!_blank(frame[key])) merged[key] = frame[key];
}
final oldExport = _positiveInt(current['export_pending_sequence']);
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
merged['export_pending_sequence'] = _blank(frame['status'])
? oldExport
: status == 'waiting'
? _positiveInt(frame['export_pending_sequence'])
: 0;
}
if (current['steps'] is! List) {
final evidence = mergeGraphEvidence(
current['graph_evidence'] as JsonMap?,
frame,
);
if (evidence != null) merged['graph_evidence'] = evidence;
}
return merged;
}
int _maxInt(dynamic a, dynamic b) =>
(a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff);
/// A summary row can be built from a sufficiently identified push; otherwise
/// the caller must resync from the server's authoritative list.
JsonMap? newRunSummaryFromFrame(JsonMap frame) {
final id = frame['run_id'];
final pipelineId = frame['pipeline_id'];
if (id is! num ||
id <= 0 ||
pipelineId is! num ||
pipelineId <= 0 ||
_blank(frame['name'])) {
return null;
}
final row = <String, dynamic>{
'id': id,
'pipeline_id': pipelineId,
'name': frame['name'],
'title': _blank(frame['title']) ? null : frame['title'],
'version': frame['version'] ?? 0,
'notify_mode': frame['notify_mode'] ?? 'auto',
'status': frame['status'] ?? '',
'executing': executingFor(frame['status'], true),
'completed_steps': _maxInt(0, frame['completed_steps']),
'created_at': frame['created_at'] ?? '',
'finished_at': frame['finished_at'] ?? '',
'outcome': frame['outcome'] ?? '',
'current_stage': frame['current_stage'] ?? '',
'resource_wait': frame['resource_wait'],
'cancel_requested': frame['cancel_requested'] == true,
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
};
row.addAll(_scheduleOrigin({}, frame));
final sequence = _positiveInt(frame['export_pending_sequence']);
if (sequence > 0) row['export_pending_sequence'] = sequence;
final evidence = mergeGraphEvidence(null, frame);
if (evidence != null) row['graph_evidence'] = evidence;
return row;
}
({List<JsonMap> runs, bool needsResync}) foldRunEvent(
List<JsonMap> runs,
JsonMap frame,
) {
final id = frame['run_id'];
if (id is! num || id <= 0) return (runs: runs, needsResync: false);
final index = runs.indexWhere((run) => run['id'] == id);
if (index < 0) {
final row = newRunSummaryFromFrame(frame);
return row == null
? (runs: runs, needsResync: true)
: (runs: [row, ...runs], needsResync: false);
}
final updated = _mergeRunFields(runs[index], frame);
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
final next = [...runs];
next[index] = updated;
return (runs: next, needsResync: false);
}
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
if (detail == null || detail['id'] != frame['run_id']) return detail;
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
frame['resource_wait_set'] != true) {
return detail;
}
final merged = _mergeRunFields(detail, frame);
final steps = frame['step'] is Map
? upsertRunStep(
detail['steps'] is List
? (detail['steps'] as List)
.whereType<Map>()
.map((s) => Map<String, dynamic>.from(s))
.toList()
: [],
Map<String, dynamic>.from(frame['step'] as Map),
)
: detail['steps'] ?? [];
return {...merged, 'steps': steps};
}
bool runDetailNeedsFullSync(JsonMap frame) {
final step = frame['step'];
final stepStatus = step is Map ? step['status'] : null;
return isTerminalRunStatus(frame['status']) ||
isWaitingRunStatus(frame['status']) ||
frame['cancel_requested'] == true ||
frame['cleanup_unconfirmed'] == true ||
isWaitingRunStatus(stepStatus) ||
stepLifecycleRank(stepStatus) == 2;
}
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
@@ -0,0 +1,219 @@
import '../../../core/api_gateway.dart';
const runStates = [
'queued',
'running',
'waiting',
'succeeded',
'failed',
'canceled',
'interrupted',
];
/// The largest millisecond value [DateTime] supports, and also exactly
/// representable by the web's JavaScript numbers. The previous
/// `0x7fffffffffffffff` literals failed dart2js compilation.
const int _maxMillis = 8640000000000000;
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
final stored = '${title ?? ''}'.trim();
return (
label: stored.isNotEmpty ? stored : '${name ?? ''}',
pipeline: stored.isNotEmpty ? '${name ?? ''}' : null,
);
}
String runStateOf(dynamic status) =>
switch ('${status ?? ''}'.trim().toLowerCase()) {
'queued' ||
'running' ||
'waiting' ||
'active' ||
'blocked' ||
'skipped' => '${status ?? ''}'.trim().toLowerCase(),
'succeeded' || 'success' || 'completed' || 'done' => 'succeeded',
'failed' || 'error' => 'failed',
'canceled' || 'cancelled' => 'canceled',
'interrupted' => 'interrupted',
_ => 'unknown',
};
List<JsonMap> filterRuns(
List<JsonMap> runs, {
Set<String> statuses = const {},
int? pipelineId,
String timeRange = 'any_time',
String scheduled = 'any',
DateTime? today,
}) => runs.where((run) {
if (statuses.isNotEmpty && !statuses.contains(runStateOf(run['status']))) {
return false;
}
if (pipelineId != null && run['pipeline_id'] != pipelineId) {
return false;
}
if (scheduled == 'scheduled' && !_isScheduled(run)) {
return false;
}
if (scheduled == 'unscheduled' &&
(run['scheduled'] != false || _isScheduled(run))) {
return false;
}
if (timeRange == 'any_time' || timeRange.isEmpty) {
return true;
}
final created = DateTime.tryParse('${run['created_at'] ?? ''}')?.toLocal();
if (created == null) {
return false;
}
final now = today ?? DateTime.now();
final start = DateTime(now.year, now.month, now.day);
final date = DateTime(created.year, created.month, created.day);
if (date.isAfter(start)) {
return false;
}
final days = switch (timeRange) {
'today' => 0,
'last_7_days' => 6,
'last_30_days' => 29,
_ => null,
};
return days == null || !date.isBefore(start.subtract(Duration(days: days)));
}).toList();
bool _isScheduled(JsonMap run) =>
run['scheduled'] == true ||
(run['schedule_id'] is num && (run['schedule_id'] as num) > 0);
String runStatusLabel(JsonMap run) {
final status = '${run['status'] ?? ''}';
if (!{'queued', 'running', 'waiting'}.contains(status)) {
return status.isEmpty ? 'unknown' : status;
}
if (run['cleanup_unconfirmed'] == true) {
return 'Cleanup unconfirmed — workspace reserved';
}
if (run['cancel_requested'] == true) {
return 'Stopping — waiting for execution to stop';
}
if (status == 'waiting' &&
(run['export_pending_sequence'] as num? ?? 0) > 0) {
return 'Waiting for session export';
}
return status;
}
List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
final result = [...runs];
int? instant(dynamic value) =>
DateTime.tryParse('${value ?? ''}')?.millisecondsSinceEpoch;
int? duration(JsonMap run) {
final from = instant(run['created_at']);
final to = instant(run['finished_at']);
if (from == null || to == null || to < from) return null;
return (to - from) ~/ 1000;
}
int cmp<T extends Comparable<Object>>(T a, T b) => a.compareTo(b);
result.sort((a, b) {
final at = instant(a['created_at']);
final bt = instant(b['created_at']);
int primary;
switch (sort) {
case 'oldest_first':
primary = cmp(at ?? _maxMillis, bt ?? _maxMillis);
break;
case 'longest_duration':
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1);
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'shortest_duration':
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
if (primary == 0) {
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
}
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'pipeline_name':
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
'${b['name'] ?? ''}'.toLowerCase(),
);
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
case 'status':
primary = '${a['status'] ?? ''}'.toLowerCase().compareTo(
'${b['status'] ?? ''}'.toLowerCase(),
);
if (primary == 0) {
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
break;
default:
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
}
return primary == 0
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
: primary;
});
return result;
}
/// Null usage means unsupported/unavailable, not zero.
class RunListResult {
const RunListResult(this.runs, this.usage);
final List<JsonMap> runs;
final JsonMap? usage;
}
class DecisionOption {
const DecisionOption(this.key, {this.target = ''});
final String key;
final String target;
}
class DecisionDraft {
const DecisionDraft({this.selected, this.feedback = ''});
final String? selected;
final String feedback;
bool get canSubmit => selected != null && selected!.trim().isNotEmpty;
DecisionDraft select(String option) =>
DecisionDraft(selected: option, feedback: feedback);
DecisionDraft withFeedback(String value) =>
DecisionDraft(selected: selected, feedback: value);
}
String attentionKey(num runId, String kind) => '$runId:$kind';
List<JsonMap> orderAttention(
List<JsonMap> runs, {
Set<String> dismissed = const {},
}) {
final result = runs.where((run) {
final waiting = run['status'] == 'waiting';
if (waiting && (run['export_pending_sequence'] as num? ?? 0) > 0) {
return false;
}
final kind = waiting ? 'Decision' : 'Failed';
return (waiting || run['status'] == 'failed') &&
!dismissed.contains(attentionKey(run['id'] as num, kind));
}).toList();
String recency(JsonMap run) => '${run['finished_at'] ?? ''}'.trim().isNotEmpty
? '${run['finished_at']}'
: '${run['created_at'] ?? ''}';
result.sort((a, b) {
final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(
b['status'] == 'waiting' ? 0 : 1,
);
if (rank != 0) return rank;
final date = recency(b).compareTo(recency(a));
return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num);
});
return result;
}
@@ -0,0 +1,142 @@
import '../../../core/api_gateway.dart';
/// Merge a visit by sequence without allowing stale status or blank sparse
/// deltas to erase evidence already held by the detail cache.
List<JsonMap> upsertRunStep(List<JsonMap> steps, JsonMap delta) {
final sequence = delta['sequence'] is num
? (delta['sequence'] as num).toInt()
: 0;
final index = steps.indexWhere((step) => step['sequence'] == sequence);
if (index < 0) {
final result = [...steps, _stepFields({}, delta, sequence)];
result.sort(
(a, b) => ((a['sequence'] as num?) ?? 0).compareTo(
(b['sequence'] as num?) ?? 0,
),
);
return result;
}
final old = steps[index];
final incomingStatus = '${delta['status'] ?? ''}';
final oldStatus = '${old['status'] ?? ''}';
if (_stale(oldStatus, incomingStatus)) return steps;
final merged = _stepFields(old, delta, sequence);
if (_same(old, merged)) return steps;
final result = [...steps];
result[index] = merged;
return result;
}
JsonMap _stepFields(JsonMap old, JsonMap delta, int sequence) {
final oldStatus = '${old['status'] ?? ''}';
final incoming = '${delta['status'] ?? ''}';
return {
...old,
'sequence': sequence,
for (final key in ['stage', 'outcome', 'target', 'diagnostic'])
key: _blank(delta[key]) ? old[key] ?? '' : delta[key],
'status': _advance(oldStatus, incoming),
};
}
bool _stale(String old, String incoming) {
if (_blank(incoming)) return false;
final before = _rank(old);
final after = _rank(incoming);
return before >= 0 &&
after >= 0 &&
(after < before || (before == 2 && after == 2 && old != incoming));
}
String _advance(String old, String incoming) {
if (_blank(incoming)) return old;
final before = _rank(old);
final after = _rank(incoming);
if (before < 0 || (after >= 0 && after > before && before < 2)) {
return incoming;
}
if (before < 2 && after == before) return incoming;
return old;
}
int _rank(String status) => switch (status.trim().toLowerCase()) {
'running' || 'waiting' => 1,
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
_ => -1,
};
bool _same(JsonMap a, JsonMap b) =>
a.length == b.length && a.entries.every((e) => b[e.key] == e.value);
/// Compact graph evidence is intentionally allowlisted. It retains latest
/// visit-by-stage and distinct outcome routes, not arbitrary frame diagnostics.
JsonMap? mergeGraphEvidence(JsonMap? current, JsonMap frame) {
final incomingEvidence = frame['graph_evidence'];
final graphVisits = frame['graph_visits'];
final step = frame['step'];
if (incomingEvidence is! Map && graphVisits is! List && step is! Map) {
return current;
}
var visits = <JsonMap>[];
final oldVisits = current?['visits'];
if (oldVisits is List) {
visits = oldVisits
.whereType<Map>()
.map((v) => Map<String, dynamic>.from(v))
.toList();
}
final additions = <dynamic>[];
if (incomingEvidence is Map && incomingEvidence['visits'] is List) {
additions.addAll(incomingEvidence['visits'] as List);
}
if (graphVisits is List) additions.addAll(graphVisits);
if (step is Map) additions.add(step);
for (final item in additions.whereType<Map>()) {
final delta = Map<String, dynamic>.from(item);
visits = upsertRunStep(visits, {
'sequence': delta['sequence'],
'stage': delta['stage'],
'status': delta['status'],
'outcome': delta['outcome'],
'target': delta['target'],
});
}
final latestByStage = <String, int>{};
final routeSequence = <String, int>{};
for (final visit in visits) {
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
final stage = '${visit['stage'] ?? ''}';
latestByStage[stage] = sequence;
if (!_blank(visit['outcome']) && !_blank(visit['target'])) {
routeSequence['$stage\u0000${visit['outcome']}\u0000${visit['target']}'] =
sequence;
}
}
visits = visits
.where((visit) {
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
final stage = '${visit['stage'] ?? ''}';
final route = '$stage\u0000${visit['outcome']}\u0000${visit['target']}';
return latestByStage[stage] == sequence ||
routeSequence[route] == sequence;
})
.map(
(visit) => <String, dynamic>{
for (final key in [
'sequence',
'stage',
'status',
'outcome',
'target',
])
key: visit[key],
},
)
.toList();
final complete =
current?['complete'] == true ||
(incomingEvidence is Map && incomingEvidence['complete'] == true);
return {'complete': complete, 'visits': visits};
}
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
+113
View File
@@ -0,0 +1,113 @@
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import 'data/runs_repository.dart';
import 'ui/run_detail_view.dart';
import 'ui/runs_controller.dart';
import 'ui/runs_list.dart';
/// The runs destination's list/detail switch.
///
/// The controller's `selectedRunId` is the only selection source, so an
/// initial run, a pending detail, a failed detail, Back and a route change all
/// navigate the same way. The shell owns the app bar; this screen adds no
/// second one.
class RunsScreen extends StatefulWidget {
const RunsScreen({
super.key,
required this.gateway,
this.initialRunId,
this.syncToken = 0,
this.onRunSelected,
this.onBack,
});
final ApiGateway gateway;
/// The run the current route names, or null for the list.
final int? initialRunId;
/// Advances when the shared socket is replaced. The loaded screen refreshes
/// in place instead of being remounted, so its selection survives.
final int syncToken;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
class _RunsScreenState extends State<RunsScreen> {
late final RunsController controller;
num? _shownRunId;
@override
void initState() {
super.initState();
controller = RunsController(RunsRepository(widget.gateway));
controller.listen(widget.gateway.frames);
controller.addListener(_selectionChanged);
controller.load(widget.initialRunId);
}
@override
void didUpdateWidget(covariant RunsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.syncToken != oldWidget.syncToken) {
controller.resync();
}
if (widget.initialRunId != oldWidget.initialRunId) {
final id = widget.initialRunId;
if (id == null) {
if (controller.selectedRunId != null) controller.back();
} else if (controller.selectedRunId != id) {
controller.select(id);
}
}
}
/// Rebuild the switch only when the selection changes. Detail progress and
/// live updates are already watched by [RunDetailView] and [RunsList], so
/// this avoids a second whole-detail rebuild per notification.
void _selectionChanged() {
final selected = controller.selectedRunId;
if (selected == _shownRunId) return;
_shownRunId = selected;
if (mounted) setState(() {});
}
void _select(num id) {
controller.select(id);
widget.onRunSelected?.call(id.toInt());
}
void _back() {
controller.back();
widget.onBack?.call();
}
@override
void dispose() {
controller.removeListener(_selectionChanged);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final selected = controller.selectedRunId != null;
return Stack(
children: [
AnimatedBuilder(
animation: controller,
builder: (context, _) => Offstage(
offstage: selected,
child: RunsList(controller: controller, onSelected: _select),
),
),
if (selected) RunDetailView(controller: controller, onBack: _back),
],
);
}
}
@@ -0,0 +1,116 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
/// One labelled value in the run detail's metrics block.
typedef DetailMetric = ({String label, String value});
/// One recorded visit in the run detail's timeline.
typedef DetailVisit = ({String title, String subtitle});
/// The run's primary label: the stored title, else the pipeline name, and only
/// then the numeric identity.
String detailTitle(JsonMap run) {
final identity = runIdentity(run['title'], run['name']);
return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label;
}
String detailPipeline(JsonMap run) {
final name = '${run['name'] ?? ''}'.trim();
return name.isEmpty ? 'unavailable' : name;
}
/// The original prompt exactly as the server stored it; never trimmed or
/// replaced by another field.
String? detailPrompt(JsonMap run) {
final input = run['input'];
return input is Map && input['prompt'] is String
? input['prompt'] as String
: null;
}
/// Nested input/output shown as formatted, selectable JSON.
String detailJson(dynamic value) =>
const JsonEncoder.withIndent(' ').convert(value);
bool detailEmpty(dynamic value) => value is! Map || value.isEmpty;
/// Reported run metrics. A present zero with a reporting stage count is a real
/// zero; a zero without that evidence is unavailable, never a measured zero.
List<DetailMetric> detailUsageMetrics(dynamic raw) {
if (raw is! Map || raw.isEmpty) return const [];
final usage = Map<String, dynamic>.from(raw);
final stages = _int(usage['stages']);
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
final costStages = _int(usage['cost_known_stages']) ?? 0;
final totalTokens = _int(usage['tokens_total']);
final splitKnown = usage['split_known'] == true && tokenStages > 0;
final rows = <DetailMetric>[
if (stages != null) (label: 'Stages', value: '$stages'),
(
label: 'Total tokens',
value: tokenStages == 0 || totalTokens == null
? 'Unavailable'
: '$totalTokens',
),
(
label: 'Input tokens',
value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable',
),
(
label: 'Output tokens',
value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable',
),
(
label: 'Reported cost',
// cost_usd is omitted by the server when zero, so a known stage count
// makes an absent value a real $0.000000 rather than an unknown cost.
value: costStages == 0
? 'Unavailable'
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
),
];
if (stages != null && tokenStages < stages) {
rows.add((
label: 'Token reporting',
value: '$tokenStages of $stages stages',
));
}
if (stages != null && costStages < stages) {
rows.add((label: 'Cost reporting', value: '$costStages of $stages stages'));
}
return rows;
}
/// Every recorded visit with its server sequence, in recorded order.
List<DetailVisit> detailTimeline(dynamic steps) {
if (steps is! List) return const [];
return [
for (final step in steps.whereType<Map>())
(
title:
'${_text(step['stage'], 'Stage unavailable')} · visit '
'${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}',
subtitle: _visitSubtitle(step),
),
];
}
String _visitSubtitle(Map step) {
final status = _text(step['status'], 'Status unavailable');
final outcome = '${step['outcome'] ?? ''}'.trim();
final target = '${step['target'] ?? ''}'.trim();
return [
status,
if (outcome.isNotEmpty) outcome,
if (target.isNotEmpty) '→ $target',
].join(' · ');
}
String _text(dynamic value, String fallback) {
final text = '${value ?? ''}'.trim();
return text.isEmpty ? fallback : text;
}
int? _int(dynamic value) => value is num ? value.toInt() : null;
@@ -0,0 +1,203 @@
import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Cupertino controls. It has no Material
/// ancestor: sections use native Cupertino expansion tiles and grouped list
/// sections, and copy feedback is an inline live-region status.
Widget buildCupertinoRunDetail({
required BuildContext context,
required JsonMap run,
required bool detailLoading,
required String? error,
required bool copying,
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
}) {
final theme = CupertinoTheme.of(context);
final prompt = detailPrompt(run);
final visits = detailTimeline(run['steps']);
final metrics = detailUsageMetrics(run['usage']);
return ListView(
key: ValueKey<String>('run-detail-${run['id']}'),
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Row(
children: [
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onBack,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(CupertinoIcons.back),
const SizedBox(width: 4),
const Text('Back'),
],
),
),
const Spacer(),
if (copying) const CupertinoActivityIndicator(),
],
),
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
detailTitle(run),
style: theme.textTheme.navLargeTitleTextStyle,
),
const SizedBox(height: 4),
Text(runStatusLabel(run)),
Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'),
],
),
),
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
if (error != null) _CupertinoNotice(error),
if (prompt != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
Text(
'Original prompt',
style: theme.textTheme.navTitleTextStyle,
),
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: copying ? null : onCopy,
child: const Text('Copy prompt'),
),
],
),
_CupertinoSelectableText(prompt),
if (copyStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Semantics(liveRegion: true, child: Text(copyStatus)),
),
],
),
),
_fieldSection('Input', run['input'], 'No input recorded.'),
_fieldSection('Output', run['output'], 'No output recorded.'),
CupertinoListSection.insetGrouped(
header: const Text('Timeline'),
children: [
if (visits.isEmpty)
const CupertinoListTile(title: Text('No visits recorded.'))
else
for (final visit in visits)
CupertinoListTile(
leading: const Icon(CupertinoIcons.circle),
title: Text(visit.title),
subtitle: Text(visit.subtitle),
),
],
),
CupertinoListSection.insetGrouped(
children: [
CupertinoExpansionTile(
title: const Text('Metrics'),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (metrics.isEmpty)
const Text('No reported usage.')
else
for (final metric in metrics)
CupertinoListTile(
title: Text(metric.label),
subtitle: Text(metric.value),
),
],
),
),
),
],
),
],
);
}
Widget _fieldSection(String title, dynamic value, String empty) {
final text = detailEmpty(value) ? empty : detailJson(value);
return CupertinoListSection.insetGrouped(
children: [
CupertinoExpansionTile(
title: Text(title),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
child: _CupertinoSelectableText(text),
),
),
],
);
}
class _CupertinoNotice extends StatelessWidget {
const _CupertinoNotice(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Semantics(liveRegion: true, child: Text(text)),
);
}
/// A read-only Cupertino text control: plain, selectable text without a
/// Material dependency, while keeping native selection and copy affordances.
class _CupertinoSelectableText extends StatefulWidget {
const _CupertinoSelectableText(this.text);
final String text;
@override
State<_CupertinoSelectableText> createState() =>
_CupertinoSelectableTextState();
}
class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> {
late final TextEditingController _controller = TextEditingController(
text: widget.text,
);
@override
void didUpdateWidget(_CupertinoSelectableText oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text) _controller.text = widget.text;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => CupertinoTextField(
controller: _controller,
readOnly: true,
maxLines: null,
padding: EdgeInsets.zero,
decoration: const BoxDecoration(),
style: CupertinoTheme.of(context).textTheme.textStyle,
);
}
@@ -0,0 +1,126 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Material controls.
Widget buildMaterialRunDetail({
required BuildContext context,
required JsonMap run,
required bool detailLoading,
required String? error,
required bool copying,
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
}) {
final theme = Theme.of(context);
final prompt = detailPrompt(run);
final visits = detailTimeline(run['steps']);
final metrics = detailUsageMetrics(run['usage']);
return ListView(
key: ValueKey<String>('run-detail-${run['id']}'),
padding: const EdgeInsets.all(16),
children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to list'),
),
),
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Chip(label: Text(runStatusLabel(run))),
Text('Run ${run['id']}'),
Text('Pipeline ${detailPipeline(run)}'),
],
),
if (detailLoading) const _Notice('Refreshing run details…'),
if (error != null) _Notice(error),
if (prompt != null) ...[
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
'Original prompt',
style: theme.textTheme.titleMedium,
),
),
IconButton(
tooltip: 'Copy prompt',
onPressed: copying ? null : onCopy,
icon: const Icon(Icons.copy),
),
],
),
SelectableText(prompt),
if (copyStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Semantics(liveRegion: true, child: Text(copyStatus)),
),
],
_fieldSection('Input', run['input'], 'No input recorded.'),
_fieldSection('Output', run['output'], 'No output recorded.'),
Text('Timeline', style: theme.textTheme.titleLarge),
if (visits.isEmpty)
const Text('No visits recorded.')
else
...visits.map(
(visit) => ListTile(
leading: const Icon(Icons.circle_outlined),
title: Text(visit.title),
subtitle: Text(visit.subtitle),
),
),
ExpansionTile(
title: const Text('Metrics'),
children: [
if (metrics.isEmpty)
const Padding(
padding: EdgeInsets.all(16),
child: Text('No reported usage.'),
)
else
...metrics.map(
(metric) => ListTile(
title: Text(metric.label),
subtitle: Text(metric.value),
),
),
],
),
],
);
}
Widget _fieldSection(String title, dynamic value, String empty) {
final text = detailEmpty(value) ? empty : detailJson(value);
return ExpansionTile(
title: Text(title),
children: [
Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)),
],
);
}
class _Notice extends StatelessWidget {
const _Notice(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Semantics(liveRegion: true, child: Text(text)),
);
}
@@ -0,0 +1,124 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import 'run_detail_content.dart';
import 'run_detail_cupertino.dart';
import 'run_detail_material.dart';
import 'runs_controller.dart';
class RunDetailView extends StatefulWidget {
const RunDetailView({
super.key,
required this.controller,
required this.onBack,
});
final RunsController controller;
final VoidCallback onBack;
@override
State<RunDetailView> createState() => _RunDetailViewState();
}
class _RunDetailViewState extends State<RunDetailView> {
bool _copying = false;
String? _copyStatus;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: widget.controller,
builder: (context, _) {
final cupertino = usesCupertinoHost(context);
final run = widget.controller.detail;
if (run == null) return _placeholder(context, cupertino: cupertino);
final prompt = detailPrompt(run);
return cupertino
? buildCupertinoRunDetail(
context: context,
run: run,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
)
: buildMaterialRunDetail(
context: context,
run: run,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
);
},
);
Widget _placeholder(BuildContext context, {required bool cupertino}) {
final loading = widget.controller.detailLoading;
final message = loading
? 'Loading run details…'
: widget.controller.error ?? 'Run details unavailable.';
// Back stays available while the detail is pending as well as after a
// failure, so a slow or refused request can never trap the destination.
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (loading) ...[
if (cupertino)
const CupertinoActivityIndicator()
else
const CircularProgressIndicator(),
const SizedBox(height: 12),
],
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(message, textAlign: TextAlign.center),
),
const SizedBox(height: 12),
if (cupertino)
CupertinoButton(
onPressed: widget.onBack,
child: const Text('Back to list'),
)
else
FilledButton(
onPressed: widget.onBack,
child: const Text('Back to list'),
),
],
),
);
}
/// Copies the stored prompt byte-for-byte. A refusal is surfaced, never
/// replaced by copying a title or the formatted detail.
Future<void> _copyPrompt(String prompt, {required bool cupertino}) async {
if (_copying) return;
setState(() => _copying = true);
String message;
try {
await Clipboard.setData(ClipboardData(text: prompt));
message = 'Prompt copied to clipboard.';
} catch (_) {
message = 'Could not copy prompt to clipboard.';
}
if (!mounted) return;
final scaffold = cupertino ? null : Scaffold.maybeOf(context);
final inline = cupertino || scaffold == null;
setState(() {
_copying = false;
_copyStatus = inline ? message : null;
});
if (!cupertino && scaffold != null) {
ScaffoldMessenger.maybeOf(
context,
)?.showSnackBar(SnackBar(content: Text(message)));
}
}
}
@@ -0,0 +1,270 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../domain/run_events.dart';
import '../domain/run_models.dart';
class RunsController extends ChangeNotifier {
RunsController(this.repository);
final RunsRepository repository;
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> runs = [];
JsonMap? detail, usage;
String? error;
bool loading = false, detailLoading = false;
String query = '',
sort = 'newest_first',
scheduled = 'any',
timeRange = 'any_time';
final Set<String> statuses = {};
int? pipelineId;
// List and detail requests advance independent generations so neither can
// make the other's in-flight reply stale.
int _listGeneration = 0, _detailGeneration = 0;
num? _selectedId;
Timer? _detailRefresh;
bool _listResyncing = false, _listAgain = false;
bool _detailRefreshing = false, _detailAgain = false;
bool _disposed = false;
num? get selectedRunId => _selectedId;
void listen(Stream<JsonMap> frames) {
_subscription?.cancel();
_subscription = frames
.where((f) => f['type'] == 'run_event')
.listen(_event);
}
Future<void> load([int? initialId]) async {
final token = ++_listGeneration;
_listAgain = false;
loading = true;
error = null;
notifyListeners();
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
usage = result.usage;
} catch (e) {
if (!_listOwned(token)) return;
error = '$e';
}
if (!_listOwned(token)) return;
loading = false;
notifyListeners();
// A run event may have arrived while the list request was in flight; one
// resync after it keeps the pushed state without dropping the event.
_resyncAgainIfNeeded();
if (initialId != null) await select(initialId);
}
/// Re-reads the list and the open detail after the socket was replaced.
///
/// The selection is kept, so a reconnect refreshes in place instead of
/// discarding the detail the operator had open.
Future<void> resync() async {
final selected = _selectedId;
await load();
if (selected != null && _selectedId == selected) await select(selected);
}
Future<void> select(num id) async {
final token = ++_detailGeneration;
_cancelDetailRefresh();
// Keep a same-run detail while it refreshes, but never present the previous
// run as if it were the newly selected one.
if (_selectedId != id) detail = null;
_selectedId = id;
detailLoading = true;
error = null;
notifyListeners();
try {
final value = await repository.getRun(id);
if (!_detailOwned(id, token)) return;
detail = value;
} catch (e) {
if (!_detailOwned(id, token)) return;
error = '$e';
}
if (!_detailOwned(id, token)) return;
detailLoading = false;
notifyListeners();
}
void back() {
++_detailGeneration;
_cancelDetailRefresh();
_selectedId = null;
detail = null;
detailLoading = false;
error = null;
notifyListeners();
}
void setQuery(String value) {
query = value;
notifyListeners();
}
void setStatus(String? value) {
if (value == null) {
statuses.clear();
} else if (!statuses.add(value)) {
statuses.remove(value);
}
notifyListeners();
}
void setPipeline(int? value) {
pipelineId = value;
notifyListeners();
}
void setScheduled(String value) {
scheduled = value;
notifyListeners();
}
void setSort(String value) {
sort = value;
notifyListeners();
}
void _event(JsonMap frame) {
final folded = foldRunEvent(runs, frame);
runs = folded.runs;
if (detail?['id'] == frame['run_id']) {
detail = foldRunEventDetail(detail, frame);
}
if (frame['run_id'] == null || folded.needsResync) {
_scheduleListRefresh();
}
final selected = _selectedId;
if (selected != null &&
frame['run_id'] == selected &&
(folded.needsResync || runDetailNeedsFullSync(frame))) {
_scheduleDetailRefresh(selected);
}
notifyListeners();
}
void _scheduleListRefresh() {
if (_disposed) return;
if (_listResyncing || loading) {
_listAgain = true;
return;
}
_listResyncing = true;
loading = true;
notifyListeners();
unawaited(_reloadList());
}
Future<void> _reloadList() async {
final token = ++_listGeneration;
_listAgain = false;
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
usage = result.usage;
error = null;
} catch (e) {
if (_listOwned(token)) error = '$e';
} finally {
_listResyncing = false;
if (_listOwned(token)) {
loading = false;
notifyListeners();
}
// A followup may have been requested while this (possibly superseded)
// request was still the one marked in flight.
_resyncAgainIfNeeded();
}
}
void _resyncAgainIfNeeded() {
if (_disposed || !_listAgain) return;
_listAgain = false;
_scheduleListRefresh();
}
void _scheduleDetailRefresh(num id) {
if (_disposed || _selectedId != id) return;
if (_detailRefreshing) {
_detailAgain = true;
return;
}
_detailRefresh?.cancel();
_detailRefresh = Timer(
const Duration(milliseconds: 150),
() => _refreshDetail(id, _detailGeneration),
);
}
Future<void> _refreshDetail(num id, int token) async {
_detailRefresh = null;
if (!_detailOwned(id, token)) return;
_detailRefreshing = true;
try {
final value = await repository.getRun(id);
if (_detailOwned(id, token)) {
detail = value;
notifyListeners();
}
} catch (e) {
if (_detailOwned(id, token)) {
error = '$e';
notifyListeners();
}
} finally {
if (_detailOwned(id, token)) {
_detailRefreshing = false;
if (_detailAgain) {
_detailAgain = false;
unawaited(_refreshDetail(id, token));
}
}
}
}
void _cancelDetailRefresh() {
_detailRefresh?.cancel();
_detailRefresh = null;
_detailAgain = false;
_detailRefreshing = false;
}
bool _listOwned(int token) => !_disposed && token == _listGeneration;
bool _detailOwned(num id, int token) =>
!_disposed && token == _detailGeneration && _selectedId == id;
List<JsonMap> get visibleRuns => sortRuns(
filterRuns(
runs,
statuses: statuses,
pipelineId: pipelineId,
scheduled: scheduled,
timeRange: timeRange,
)
.where(
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
query.toLowerCase(),
),
)
.toList(),
sort: sort,
);
@override
void dispose() {
_disposed = true;
_subscription?.cancel();
_detailRefresh?.cancel();
super.dispose();
}
}
+243
View File
@@ -0,0 +1,243 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/run_models.dart';
import 'runs_controller.dart';
class RunsList extends StatelessWidget {
const RunsList({
super.key,
required this.controller,
required this.onSelected,
});
final RunsController controller;
final ValueChanged<num> onSelected;
@override
Widget build(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
return Center(
child: usesCupertinoHost(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
if (controller.error != null && controller.runs.isEmpty) {
return _emptyError(context);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (controller.usage != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text('Usage: ${controller.usage}'),
),
if (controller.error != null) _inlineError(context),
Padding(
padding: const EdgeInsets.all(16),
child: usesCupertinoHost(context)
? CupertinoSearchTextField(
placeholder: 'Filter runs',
onChanged: controller.setQuery,
)
: TextField(
decoration: const InputDecoration(
labelText: 'Filter runs',
prefixIcon: Icon(Icons.search),
),
onChanged: controller.setQuery,
),
),
_selectors(context),
Expanded(
child: controller.visibleRuns.isEmpty
? const Center(child: Text('No runs found.'))
: ListView.builder(
itemCount: controller.visibleRuns.length,
itemBuilder: (context, index) =>
_runTile(context, controller.visibleRuns[index]),
),
),
],
);
}
Widget _emptyError(BuildContext context) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(controller.error!),
const SizedBox(height: 8),
usesCupertinoHost(context)
? CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
)
: FilledButton(
onPressed: controller.load,
child: const Text('Retry'),
),
],
),
);
Widget _inlineError(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(child: Text(controller.error!)),
if (usesCupertinoHost(context))
CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
)
else
TextButton(onPressed: controller.load, child: const Text('Retry')),
],
),
);
Widget _selectors(BuildContext context) {
if (usesCupertinoHost(context)) {
return Wrap(
spacing: 8,
children: [
CupertinoButton(
onPressed: () => _choose(
context,
'Sort runs',
_sorts,
controller.sort,
controller.setSort,
),
child: Text('Sort: ${_sortLabel(controller.sort)}'),
),
CupertinoButton(
onPressed: () => _choose(
context,
'Schedule',
_schedules,
controller.scheduled,
controller.setScheduled,
),
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
),
for (final status in _statuses)
CupertinoButton(
onPressed: () => controller.setStatus(status),
child: Text(
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
),
),
],
);
}
return Wrap(
spacing: 8,
children: [
DropdownButton<String>(
value: controller.sort,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setSort(v);
},
items: _sorts
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
DropdownButton<String>(
value: controller.scheduled,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setScheduled(v);
},
items: _schedules
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
for (final status in _statuses)
FilterChip(
label: Text(_title(status)),
selected: controller.statuses.contains(status),
onSelected: (_) => controller.setStatus(status),
),
],
);
}
Future<void> _choose(
BuildContext context,
String title,
List<(String, String)> values,
String selected,
ValueChanged<String> onSelected,
) async {
final value = await showCupertinoModalPopup<String>(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text(title),
actions: [
for (final option in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, option.$1),
child: Text(option.$2),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (value != null && value != selected) onSelected(value);
}
Widget _runTile(BuildContext context, JsonMap run) {
final identity = runIdentity(run['title'], run['name']);
final id = run['id'];
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
final subtitle =
'${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}';
if (usesCupertinoHost(context)) {
return CupertinoListTile(
title: Text(title),
subtitle: Text(subtitle),
additionalInfo: Text(runStatusLabel(run)),
trailing: const CupertinoListTileChevron(),
onTap: id is num ? () => onSelected(id) : null,
);
}
return ListTile(
title: Text(title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(subtitle), Text(runStatusLabel(run))],
),
trailing: const Icon(Icons.chevron_right),
onTap: id is num ? () => onSelected(id) : null,
);
}
}
const _sorts = [
('newest_first', 'Newest'),
('oldest_first', 'Oldest'),
('pipeline_name', 'Pipeline'),
('status', 'Status'),
];
const _schedules = [
('any', 'Any schedule'),
('scheduled', 'Scheduled'),
('unscheduled', 'Unscheduled'),
];
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
String _sortLabel(String value) =>
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
String _scheduleLabel(String value) => _schedules
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
.$2;
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';
@@ -0,0 +1,116 @@
import '../../../core/api_gateway.dart';
import '../domain/saved_schedule.dart';
import '../domain/schedule_json.dart';
/// Client-side protocol failure. Server refusals and transport errors are not
/// wrapped: [ApiGateway] already surfaces their exact text.
class SchedulesRepositoryException implements Exception {
const SchedulesRepositoryException(this.message);
final String message;
@override
String toString() => message;
}
/// The saved-schedule commands of the current web client.
///
/// These are run configurations, not pipeline definitions: this repository
/// never submits, validates or publishes a workflow, and it never starts or
/// polls a run. Timer execution belongs to the server.
class SchedulesRepository {
SchedulesRepository(this._gateway);
final ApiGateway _gateway;
/// Lists saved schedules, optionally for one pipeline.
///
/// An explicit empty reply is a valid empty list. A reply without the
/// `schedules` type is not: that is an older/unsupported server and must be
/// reported rather than shown as "no schedules".
Future<List<SavedSchedule>> listSchedules({int? pipelineId}) async {
final fields = <String, dynamic>{};
if (pipelineId != null) {
if (!_isPositiveId(pipelineId)) {
throw const SchedulesRepositoryException(
'A positive pipeline ID is required.',
);
}
fields['pipeline_id'] = pipelineId;
}
final reply = await _gateway.call('list_schedules', fields);
final schedules = reply['schedules'];
if (reply['type'] != 'schedules' ||
(schedules != null && schedules is! List)) {
throw const SchedulesRepositoryException(
'The server returned no schedules response.',
);
}
if (schedules == null) return const [];
return [
for (final item in schedules as List)
if (item is Map)
SavedSchedule(Map<String, dynamic>.from(item))
else
throw const SchedulesRepositoryException(
'The server returned an invalid schedule record.',
),
];
}
/// Creates or updates one saved schedule.
///
/// Creation sends the web client's sentinel record (`id` 0, no revision) and
/// may carry a stable request key so a lost reply is retried instead of
/// creating a duplicate. Updating sends the record read from the server,
/// whose `revision` is the compare-and-swap token; the key is omitted, as in
/// the web client. A stale revision is refused by the server and propagated
/// unchanged, never overwritten locally.
Future<SavedSchedule> saveSchedule(
JsonMap schedule, {
String? requestKey,
}) async {
if (requestKey != null && requestKey.length > 128) {
throw const SchedulesRepositoryException(
'Schedule request keys must be strings of at most 128 characters.',
);
}
final fields = <String, dynamic>{'schedule': cloneJsonMap(schedule)};
if (requestKey != null && requestKey.isNotEmpty) {
fields['request_key'] = requestKey;
}
final reply = await _gateway.call('save_schedule', fields);
final saved = reply['schedule'];
if (saved is! Map) {
throw const SchedulesRepositoryException(
'The server returned no saved schedule.',
);
}
return SavedSchedule(Map<String, dynamic>.from(saved));
}
/// Deletes exactly the revision the caller read.
///
/// Both identity and revision are required before any request is sent; a
/// confirmation for a different schedule is treated as a failed delete.
Future<void> deleteSchedule(int id, int revision) async {
if (!_isPositiveId(id) || !_isPositiveId(revision)) {
throw const SchedulesRepositoryException(
'An exact schedule ID and revision are required.',
);
}
final reply = await _gateway.call('delete_schedule', {
'schedule_id': id,
'expected_revision': revision,
});
if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) {
throw const SchedulesRepositoryException(
'The server did not confirm deletion of this schedule.',
);
}
}
}
/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks
/// `Number.isSafeInteger` before sending an identity.
const _maxSafeInteger = 9007199254740991;
bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger;
@@ -0,0 +1,87 @@
import '../../../core/api_gateway.dart';
import 'schedule_json.dart';
import 'schedule_rule.dart';
/// One saved run configuration from `list_schedules` or `save_schedule`.
///
/// A saved schedule is a complete run request pinned to one pipeline version.
/// It is deliberately not a pipeline definition: nothing here is published,
/// validated as a graph or treated as the pipeline's current version.
///
/// [raw] keeps the exact server record, including fields this client does not
/// know yet. Typed getters are views; they never rewrite [raw].
class SavedSchedule {
SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw);
final JsonMap raw;
/// Server identity; null when an older reply omits it. Never defaulted to 0,
/// because 0 is the create sentinel rather than a saved identity.
int? get id => _integer(raw['id']);
/// Compare-and-swap token. Updates reuse it and deletes send it as
/// `expected_revision`; this client never invents or increments it.
int? get revision => _integer(raw['revision']);
int? get pipelineId => _integer(raw['pipeline_id']);
int? get version => _integer(raw['version']);
String get name => _text(raw['name']);
bool get enabled => raw['enabled'] == true;
JsonMap get input => _map(raw['input']);
String get prompt => _text(input['prompt']);
String get workspace => _text(raw['workspace']);
ScheduleRule get rule => ScheduleRule(_map(raw['rule']));
List<String> get writePaths => _texts(raw['write_paths']);
bool get allowTools => raw['allow_tools'] == true;
String get model => _text(raw['model']);
Map<String, String> get stageModels => {
for (final entry in _map(raw['stage_models']).entries)
if (entry.value is String) entry.key: entry.value as String,
};
String get notifyMode => _text(raw['notify_mode']);
String get title => _text(raw['title']);
String get outputFormat => _text(raw['output_format']);
String get nextDue => _text(raw['next_due']);
String get createdAt => _text(raw['created_at']);
String get updatedAt => _text(raw['updated_at']);
/// The record to pass to `save_schedule`, deep-copied so callers cannot
/// mutate this snapshot by aliasing.
JsonMap toJson() => cloneJsonMap(raw);
/// Pause/enable copy. Identity, revision and every unknown field are kept so
/// the update still targets the revision this record was read at.
SavedSchedule withEnabled(bool value) {
final copy = toJson();
copy['enabled'] = value;
return SavedSchedule(copy);
}
}
int? _integer(dynamic value) {
if (value is int) return value;
if (value is num && value.isFinite && value == value.truncateToDouble()) {
return value.toInt();
}
return null;
}
String _text(dynamic value) => value is String ? value : '';
JsonMap _map(dynamic value) {
if (value is! Map) return <String, dynamic>{};
return <String, dynamic>{
for (final entry in value.entries)
'${entry.key}': cloneJsonValue(entry.value),
};
}
List<String> _texts(dynamic value) => value is List
? [
for (final item in value)
if (item is String) item,
]
: const [];
@@ -0,0 +1,22 @@
import '../../../core/api_gateway.dart';
/// Deep copy of a decoded JSON value.
///
/// Saved schedules travel back to the server unchanged, so unknown fields (and
/// unknown nested values) must survive every round trip without sharing state
/// with the reply map that produced them.
dynamic cloneJsonValue(dynamic value) {
if (value is Map) {
return <String, dynamic>{
for (final entry in value.entries)
'${entry.key}': cloneJsonValue(entry.value),
};
}
if (value is List) {
return [for (final item in value) cloneJsonValue(item)];
}
return value;
}
JsonMap cloneJsonMap(JsonMap value) =>
Map<String, dynamic>.from(cloneJsonValue(value) as Map);
@@ -0,0 +1,41 @@
import '../../../core/api_gateway.dart';
import 'schedule_json.dart';
/// Weekday keys the server accepts for an interval rule.
const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
/// The timer part of a saved schedule (`rule` on the wire).
///
/// This is a view over the decoded server record, not a timer implementation:
/// it never calculates due times, converts timezones or starts runs. Unknown
/// rule fields stay in [raw] and are returned by [toJson].
class ScheduleRule {
ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {});
final JsonMap raw;
/// Go-style duration such as `24h` or `1h30m`; empty for a clock rule.
String get every => _text(raw['every']);
/// Distinct 24-hour times such as `09:00`; empty for an interval rule.
List<String> get times => _texts(raw['times']);
/// Empty means every day (written as absent on the wire).
List<String> get days => _texts(raw['days']);
/// Empty or `Local` means the server's timezone.
String get timezone => _text(raw['timezone']);
bool get isClock => times.isNotEmpty;
JsonMap toJson() => cloneJsonMap(raw);
}
String _text(dynamic value) => value is String ? value : '';
List<String> _texts(dynamic value) => value is List
? [
for (final item in value)
if (item is String) item,
]
: const [];
+94
View File
@@ -0,0 +1,94 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'data/schedules_repository.dart';
import 'domain/saved_schedule.dart';
import 'ui/list/schedule_list_controller.dart';
import 'ui/list/schedule_list_view.dart';
/// The saved-schedules list body.
///
/// The shell supplies navigation chrome. Selecting a row reports the exact
/// [SavedSchedule] the server returned; this screen does not create, edit,
/// delete, pause or enable anything.
class SchedulesScreen extends StatefulWidget {
const SchedulesScreen({
super.key,
required this.gateway,
required this.onOpen,
this.pipelineId,
});
final ApiGateway gateway;
final ValueChanged<SavedSchedule> onOpen;
final int? pipelineId;
@override
State<SchedulesScreen> createState() => _SchedulesScreenState();
}
class _SchedulesScreenState extends State<SchedulesScreen> {
late SchedulesController _controller;
late final TextEditingController _searchController;
final ScrollController _scrollController = ScrollController();
@override
void initState() {
super.initState();
_controller = _createController();
_searchController = TextEditingController(text: _controller.query);
unawaited(_controller.refresh());
}
SchedulesController _createController() => SchedulesController(
repository: SchedulesRepository(widget.gateway),
pipelineId: widget.pipelineId,
);
@override
void didUpdateWidget(covariant SchedulesScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (identical(oldWidget.gateway, widget.gateway) &&
oldWidget.pipelineId == widget.pipelineId) {
return;
}
final query = _controller.query;
final filter = _controller.filter;
_controller.dispose();
_controller = _createController();
_controller.setQuery(query);
_controller.setFilter(filter);
unawaited(_controller.refresh());
}
@override
void dispose() {
_controller.dispose();
_searchController.dispose();
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
) ==
null;
return AnimatedBuilder(
animation: _controller,
builder: (context, _) => SchedulesListView(
controller: _controller,
searchController: _searchController,
scrollController: _scrollController,
cupertino: cupertino,
onOpen: widget.onOpen,
onRefresh: () => unawaited(_controller.refresh()),
),
);
}
}
@@ -0,0 +1,168 @@
import 'package:flutter/foundation.dart';
import '../../data/schedules_repository.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_format.dart';
enum ScheduleListFilter { all, enabled }
extension ScheduleListFilterLabel on ScheduleListFilter {
String get label => switch (this) {
ScheduleListFilter.all => 'All',
ScheduleListFilter.enabled => 'Enabled',
};
}
/// A list refresh failure, kept apart from a valid empty result.
class ScheduleListFailure {
const ScheduleListFailure(this.message, {this.unsupported = false});
factory ScheduleListFailure.from(Object error) {
final text = error is SchedulesRepositoryException
? error.message
: '$error';
if (text == _unsupportedReply || _unsupportedPattern.hasMatch(text)) {
return ScheduleListFailure(
'This server does not support saved schedules. '
'Upgrade the server to use schedules. ($text)',
unsupported: true,
);
}
return ScheduleListFailure(text);
}
final String message;
final bool unsupported;
/// The repository's exact report for a reply without `type: schedules`.
static const _unsupportedReply = 'The server returned no schedules response.';
/// Matches the web client's older-server detection, so a server that refuses
/// the command with its own `unknown request`/`unsupported` wording gets the
/// same upgrade guidance instead of only the raw error.
static final _unsupportedPattern = RegExp(
r'unknown (message|request|command)|unsupported.*schedule',
caseSensitive: false,
);
}
/// Loads saved run configurations with search and enabled filtering.
///
/// This controller is read-only: it only calls `list_schedules`. It never saves,
/// deletes, pauses or enables a schedule, and it never treats schedules as
/// pipeline definitions.
class SchedulesController extends ChangeNotifier {
SchedulesController({required this.repository, this.pipelineId});
final SchedulesRepository repository;
final int? pipelineId;
List<SavedSchedule> _schedules = const [];
List<SavedSchedule>? _visibleSchedules;
bool _loading = false;
bool _loaded = false;
ScheduleListFailure? _failure;
String _query = '';
ScheduleListFilter _filter = ScheduleListFilter.all;
int _generation = 0;
bool _disposed = false;
List<SavedSchedule> get schedules => _schedules;
bool get isLoading => _loading;
bool get hasLoaded => _loaded;
ScheduleListFailure? get failure => _failure;
String get query => _query;
ScheduleListFilter get filter => _filter;
/// Cached until the list, query or filter changes; the view, count label and
/// toolbar all read it during one build.
List<SavedSchedule> get visibleSchedules =>
_visibleSchedules ??= _filterSchedules();
List<SavedSchedule> _filterSchedules() {
final needle = _query.trim().toLowerCase();
return List.unmodifiable([
for (final schedule in _schedules)
if ((_filter == ScheduleListFilter.all || schedule.enabled) &&
(needle.isEmpty || _matches(schedule, needle)))
schedule,
]);
}
void _invalidateVisibility() => _visibleSchedules = null;
bool get isInitialLoading => _loading && !_loaded;
/// Empty-state wording that names the actual reason when the search box is
/// empty and only the enabled filter hides every row.
String get emptyMessage => _query.trim().isNotEmpty
? 'No schedules match this search.'
: 'No enabled schedules.';
String get countLabel =>
scheduleCountLabel(visibleSchedules.length, _schedules.length);
bool _matches(SavedSchedule schedule, String needle) {
final haystack = [
scheduleDisplayName(schedule),
schedule.prompt,
if (schedule.pipelineId != null) 'Pipeline ${schedule.pipelineId}',
].join('\n').toLowerCase();
return haystack.contains(needle);
}
void setQuery(String value) {
if (value == _query) return;
_query = value;
_invalidateVisibility();
_notify();
}
void setFilter(ScheduleListFilter value) {
if (value == _filter) return;
_filter = value;
_invalidateVisibility();
_notify();
}
void clearQuery() => setQuery('');
/// Reloads the list without recreating the screen, so the search field and
/// the list's scroll position survive a refresh.
///
/// Only the newest request may publish. A slower, older reply is ignored,
/// including one that completes after this controller was disposed.
Future<void> refresh() async {
final generation = ++_generation;
_loading = true;
_failure = null;
_notify();
try {
final schedules = await repository.listSchedules(pipelineId: pipelineId);
if (!_owns(generation)) return;
_schedules = List.unmodifiable(schedules);
_invalidateVisibility();
_loaded = true;
} catch (error) {
if (!_owns(generation)) return;
_failure = ScheduleListFailure.from(error);
} finally {
if (_owns(generation)) {
_loading = false;
_notify();
}
}
}
bool _owns(int generation) => !_disposed && generation == _generation;
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
@@ -0,0 +1,70 @@
import '../../domain/saved_schedule.dart';
/// User-facing values for one saved schedule row.
///
/// Every accessor reports what the server sent. A missing field keeps a
/// distinct "unavailable"/"not scheduled" value instead of being invented.
String scheduleDisplayName(SavedSchedule schedule) {
final name = schedule.name.trim();
return name.isEmpty ? 'Unnamed schedule' : name;
}
String scheduleStatusLabel(SavedSchedule schedule) =>
schedule.enabled ? 'Enabled' : 'Paused';
String schedulePipelineVersionValue(SavedSchedule schedule) {
final pipeline = schedule.pipelineId == null
? 'Pipeline unavailable'
: 'Pipeline ${schedule.pipelineId}';
final version = schedule.version == null
? 'Version unavailable'
: 'v${schedule.version}';
return '$pipeline · $version';
}
String scheduleWorkspaceValue(SavedSchedule schedule) {
final workspace = schedule.workspace.trim();
return workspace.isEmpty ? 'Workspace unavailable' : workspace;
}
String scheduleTimerValue(SavedSchedule schedule) {
final rule = schedule.rule;
final repeat = rule.every.isNotEmpty
? 'Every ${rule.every}'
: rule.times.isNotEmpty
? rule.times.join(', ')
: '';
if (repeat.isEmpty) return 'Timer unavailable';
return rule.days.isEmpty ? repeat : '$repeat · ${rule.days.join(', ')}';
}
/// Matches the web client: an empty or `Local` rule timezone means the server
/// applies its own timezone, which is not an absent value.
String scheduleTimezoneValue(SavedSchedule schedule) {
final timezone = schedule.rule.timezone.trim();
return timezone.isEmpty || timezone == 'Local' ? 'Server timezone' : timezone;
}
/// Paused schedules show the pause state, as in the current web client; enabled
/// schedules show the server's `next_due` or an honest unavailable value.
String scheduleNextDueValue(SavedSchedule schedule) {
if (!schedule.enabled) return 'Paused';
return scheduleDueValue(schedule.nextDue);
}
String scheduleDueValue(String value) {
if (value.isEmpty) return 'Not scheduled';
final date = DateTime.tryParse(value);
if (date == null) return 'Next time unavailable';
final local = date.toLocal();
String two(int part) => part.toString().padLeft(2, '0');
return '${local.year.toString().padLeft(4, '0')}-${two(local.month)}-'
'${two(local.day)} ${two(local.hour)}:${two(local.minute)} '
'(your local time)';
}
String scheduleCountLabel(int visible, int total) {
if (visible != total) return '$visible of $total schedules';
return total == 1 ? '1 schedule' : '$total schedules';
}
@@ -0,0 +1,115 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_format.dart';
/// One tappable saved-schedule row with the server's actual values.
class ScheduleListRow extends StatelessWidget {
const ScheduleListRow({
super.key,
required this.schedule,
required this.cupertino,
required this.onOpen,
});
final SavedSchedule schedule;
final bool cupertino;
final VoidCallback onOpen;
@override
Widget build(BuildContext context) {
final content = Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _details(context)),
const SizedBox(width: 8),
Icon(
cupertino ? CupertinoIcons.chevron_right : Icons.chevron_right,
color: _secondaryColor(context),
),
],
),
);
if (cupertino) {
return CupertinoButton(
padding: EdgeInsets.zero,
alignment: Alignment.centerLeft,
onPressed: onOpen,
child: content,
);
}
return InkWell(onTap: onOpen, child: content);
}
Widget _details(BuildContext context) {
final prompt = schedule.prompt;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
scheduleDisplayName(schedule),
style: _titleStyle(context),
),
),
const SizedBox(width: 8),
Text(scheduleStatusLabel(schedule), style: _statusStyle(context)),
],
),
if (prompt.isNotEmpty) ...[
const SizedBox(height: 4),
Text(prompt, style: _bodyStyle(context)),
],
const SizedBox(height: 6),
_meta(context, schedulePipelineVersionValue(schedule)),
_meta(context, 'Workspace: ${scheduleWorkspaceValue(schedule)}'),
_meta(context, 'Timer: ${scheduleTimerValue(schedule)}'),
_meta(context, 'Timezone: ${scheduleTimezoneValue(schedule)}'),
_meta(context, 'Next due: ${scheduleNextDueValue(schedule)}'),
],
);
}
Widget _meta(BuildContext context, String value) =>
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);
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),
)
: Theme.of(
context,
).textTheme.bodySmall?.copyWith(color: _secondaryColor(context));
TextStyle? _statusStyle(BuildContext context) => _metaStyle(
context,
)?.copyWith(color: _statusColor(context), fontWeight: FontWeight.w600);
Color _secondaryColor(BuildContext context) => cupertino
? CupertinoColors.secondaryLabel.resolveFrom(context)
: Theme.of(context).colorScheme.onSurfaceVariant;
Color _statusColor(BuildContext context) => schedule.enabled
? (cupertino
? CupertinoTheme.of(context).primaryColor
: Theme.of(context).colorScheme.primary)
: _secondaryColor(context);
}
@@ -0,0 +1,179 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'schedule_list_controller.dart';
const scheduleSearchFieldKey = ValueKey<String>('schedule-search-field');
const scheduleFilterKey = ValueKey<String>('schedule-filter');
const scheduleRefreshKey = ValueKey<String>('schedule-refresh');
/// Search, enabled filter and the read-only refresh control.
class ScheduleListToolbar extends StatelessWidget {
const ScheduleListToolbar({
super.key,
required this.controller,
required this.searchController,
required this.cupertino,
required this.onRefresh,
});
final SchedulesController controller;
final TextEditingController searchController;
final bool cupertino;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: _search(context),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 480),
child: _filter(context),
),
),
),
const SizedBox(width: 8),
_refresh(context),
],
),
),
if (controller.hasLoaded)
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(controller.countLabel, style: _metaStyle(context)),
Text(
'Saved run configurations, not pipeline definitions.',
style: _metaStyle(context),
),
],
),
),
],
);
}
Widget _search(BuildContext context) {
if (cupertino) {
return CupertinoSearchTextField(
key: scheduleSearchFieldKey,
controller: searchController,
placeholder: 'Search schedules',
onChanged: controller.setQuery,
onSuffixTap: () {
searchController.clear();
controller.clearQuery();
},
);
}
return TextField(
key: scheduleSearchFieldKey,
controller: searchController,
onChanged: controller.setQuery,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: 'Search schedules',
prefixIcon: const Icon(Icons.search),
suffixIcon: controller.query.isEmpty
? null
: IconButton(
tooltip: 'Clear search',
icon: const Icon(Icons.clear),
onPressed: () {
searchController.clear();
controller.clearQuery();
},
),
),
);
}
Widget _filter(BuildContext context) {
if (cupertino) {
return CupertinoSlidingSegmentedControl<ScheduleListFilter>(
key: scheduleFilterKey,
groupValue: controller.filter,
onValueChanged: (value) {
if (value != null) controller.setFilter(value);
},
children: {
for (final filter in ScheduleListFilter.values)
filter: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
child: Text(filter.label),
),
},
);
}
return SegmentedButton<ScheduleListFilter>(
key: scheduleFilterKey,
segments: [
for (final filter in ScheduleListFilter.values)
ButtonSegment<ScheduleListFilter>(
value: filter,
label: Text(filter.label),
),
],
selected: {controller.filter},
showSelectedIcon: false,
onSelectionChanged: (selection) {
if (selection.isNotEmpty) controller.setFilter(selection.first);
},
);
}
Widget _refresh(BuildContext context) {
if (controller.isLoading) {
return Semantics(
label: 'Refreshing schedules',
liveRegion: true,
child: Padding(
padding: const EdgeInsets.all(12),
child: cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (cupertino) {
return Semantics(
label: 'Refresh schedules',
child: CupertinoButton(
key: scheduleRefreshKey,
padding: EdgeInsets.zero,
onPressed: onRefresh,
child: const Icon(CupertinoIcons.refresh),
),
);
}
return IconButton(
key: scheduleRefreshKey,
tooltip: 'Refresh schedules',
onPressed: onRefresh,
icon: const Icon(Icons.refresh),
);
}
TextStyle? _metaStyle(BuildContext context) => cupertino
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(
fontSize: 14,
color: CupertinoColors.secondaryLabel.resolveFrom(context),
)
: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
);
}
@@ -0,0 +1,188 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../domain/saved_schedule.dart';
import 'schedule_list_controller.dart';
import 'schedule_list_row.dart';
import 'schedule_list_toolbar.dart';
const scheduleListKey = ValueKey<String>('schedule-list');
const scheduleRetryKey = ValueKey<String>('schedule-retry');
/// Platform-adaptive list body. It owns no navigation chrome; the shell frames
/// it as the Schedules destination.
class SchedulesListView extends StatelessWidget {
const SchedulesListView({
super.key,
required this.controller,
required this.searchController,
required this.scrollController,
required this.cupertino,
required this.onOpen,
required this.onRefresh,
});
final SchedulesController controller;
final TextEditingController searchController;
final ScrollController scrollController;
final bool cupertino;
final ValueChanged<SavedSchedule> onOpen;
final VoidCallback onRefresh;
@override
Widget build(BuildContext context) {
return Column(
children: [
ScheduleListToolbar(
controller: controller,
searchController: searchController,
cupertino: cupertino,
onRefresh: onRefresh,
),
Expanded(child: _body(context)),
],
);
}
Widget _body(BuildContext context) {
final failure = controller.failure;
if (failure != null && controller.schedules.isEmpty) {
return _failureState(context, failure);
}
if (controller.isInitialLoading) return _loadingState(context);
if (controller.schedules.isEmpty) {
return _emptyState('No schedules yet.');
}
final content = controller.visibleSchedules.isEmpty
? _emptyState(controller.emptyMessage)
: _list(context);
// The banner slot is always present so a failed or recovered refresh does
// not change the list's ancestors. Replacing the ListView would rebuild the
// Scrollable and drop the user's scroll offset.
return Column(
children: [
if (failure != null)
_failureBanner(context, failure)
else
const SizedBox.shrink(),
Expanded(child: content),
],
);
}
Widget _list(BuildContext context) {
final schedules = controller.visibleSchedules;
return ListView.separated(
key: scheduleListKey,
controller: scrollController,
padding: const EdgeInsets.only(top: 4, bottom: 24),
itemCount: schedules.length,
separatorBuilder: (context, index) =>
cupertino ? _cupertinoSeparator(context) : const Divider(height: 1),
itemBuilder: (context, index) {
final schedule = schedules[index];
return ScheduleListRow(
key: ValueKey<String>(
'schedule-row-$index-${schedule.id ?? 'unknown'}',
),
schedule: schedule,
cupertino: cupertino,
onOpen: () => onOpen(schedule),
);
},
);
}
Widget _cupertinoSeparator(BuildContext context) => Container(
height: 1 / MediaQuery.devicePixelRatioOf(context),
color: CupertinoColors.separator.resolveFrom(context),
);
Widget _loadingState(BuildContext context) {
return Center(
child: Semantics(
liveRegion: true,
label: 'Loading schedules',
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
cupertino
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
const SizedBox(height: 12),
const Text('Loading schedules…'),
],
),
),
);
}
Widget _emptyState(String message) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
Widget _failureState(BuildContext context, ScheduleListFailure failure) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_failureText(context, failure),
const SizedBox(height: 16),
_retryButton(),
],
),
),
);
}
Widget _failureBanner(BuildContext context, ScheduleListFailure failure) {
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: _failureText(context, failure)),
const SizedBox(width: 8),
_retryButton(),
],
),
);
}
Widget _failureText(BuildContext context, ScheduleListFailure failure) {
final color = cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error;
return Semantics(
liveRegion: true,
child: Text(
failure.message,
textAlign: TextAlign.center,
style: TextStyle(color: color),
),
);
}
Widget _retryButton() {
if (cupertino) {
return CupertinoButton(
key: scheduleRetryKey,
padding: EdgeInsets.zero,
onPressed: onRefresh,
child: const Text('Retry'),
);
}
return TextButton(
key: scheduleRetryKey,
onPressed: onRefresh,
child: const Text('Retry'),
);
}
}
@@ -0,0 +1,28 @@
import '../../../core/api_gateway.dart';
import '../domain/search_models.dart';
/// Search protocol requests over the application's shared gateway.
///
/// The request body is exactly `SearchRequest{query, kind, limit}` with
/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`,
/// 50) instead of the client choosing a larger one.
class SearchRepository {
SearchRepository(this._gateway);
final ApiGateway _gateway;
/// Returns the bounded `search_results` body, or null when an older server
/// answered without it (its default `pong`) so the caller can report the
/// "cannot search" sentence rather than showing a false empty success.
Future<SearchResponse?> search({
required String query,
required SearchKind kind,
}) async {
final reply = await _gateway.call('search', {
'search': {'query': query, 'kind': kind.wire, 'limit': 0},
});
final results = reply['search_results'];
if (results is! Map) return null;
return SearchResponse.fromJson(Map<String, dynamic>.from(results));
}
}
@@ -0,0 +1,236 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/search_repository.dart';
import 'search_models.dart';
import 'search_query.dart';
import 'search_row.dart';
/// The body the results area shows, in the browser's precedence order: an error
/// takes precedence over retained results, a refresh keeps results on screen,
/// and a first load shows the searching row.
enum SearchBodyKind { idle, searching, results, empty, error }
/// Debounced, stale-safe omni-search state. It owns no widgets and no socket:
/// the screen listens to it and the repository talks to the shared gateway.
class OmniSearchController extends ChangeNotifier {
OmniSearchController({
required this.repository,
this.debounce = const Duration(milliseconds: 250),
});
final SearchRepository repository;
final Duration debounce;
final SearchSequencer _sequencer = SearchSequencer();
Timer? _timer;
bool _disposed = false;
String _query = '';
SearchKind _selectedKind = SearchKind.all;
List<JsonMap> _results = const [];
bool _loading = false;
bool _loaded = false;
bool _truncated = false;
int _scannedSteps = 0;
int _scannedBytes = 0;
int _cap = 0;
int _scanBoundBytes = 0;
String? _error;
String get query => _query;
SearchKind get selectedKind => _selectedKind;
ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind);
List<JsonMap> get results => _results;
bool get loading => _loading;
bool get loaded => _loaded;
bool get truncated => _truncated;
int get scannedSteps => _scannedSteps;
int get scannedBytes => _scannedBytes;
int get cap => _cap;
int get scanBoundBytes => _scanBoundBytes;
String? get error => _error;
/// The results already in hand, re-narrowed to the effective kind so the list
/// always matches the control while a narrowed request loads.
List<JsonMap> get shownResults {
final kind = parsed.kind;
if (kind == SearchKind.all) return _results;
return _results
.where((hit) => hit['kind'] == kind.wire)
.toList(growable: false);
}
SearchBodyKind get bodyKind {
if (_error != null) return SearchBodyKind.error;
if (shownResults.isNotEmpty) return SearchBodyKind.results;
if (_loading && _results.isEmpty) return SearchBodyKind.searching;
if (emptyMessage != null) return SearchBodyKind.empty;
return SearchBodyKind.idle;
}
/// A thin progress report above retained results while a newer query loads.
bool get showProgress => _loading && _results.isNotEmpty;
String? get emptyMessage {
if (_error != null || _loading || shownResults.isNotEmpty) return null;
final effective = parsed;
if (effective.query.trim().isEmpty) {
if (!_loaded || effective.kind == SearchKind.all) return null;
final label = effective.kind.label.toLowerCase();
return _truncated
? "No $label found within the server's scan limit."
: 'No $label yet.';
}
final bounded = _truncated ? " within the server's scan limit" : '';
if (effective.kind == SearchKind.all) {
return 'No matches for "${effective.query}"$bounded.';
}
return 'No ${effective.kind.label.toLowerCase()} match '
'"${effective.query}"$bounded.';
}
/// The server's own result/scan bounds, so a capped answer is not presented as
/// a complete one. A truncated reply keeps its warning even with no rows;
/// before any loaded reply there is nothing to report.
String? get boundsText {
if (!_loaded) return null;
// A new first load has no current result set yet, so do not carry the
// previous reply's warning while the searching state is on screen.
if (_loading && _results.isEmpty) return null;
if (_results.isEmpty && !_truncated) return null;
final count = _results.length;
final parts = <String>[];
if (_truncated) {
parts.add("Results truncated by the server's result or scan limit.");
}
parts.add('$count ${count == 1 ? 'result' : 'results'}');
if (_cap > 0) parts.add('cap $_cap');
parts.add('scanned $_scannedSteps steps');
parts.add('${humanBytes(_scannedBytes)} scanned');
if (_scanBoundBytes > 0) {
parts.add('scan limit ${humanBytes(_scanBoundBytes)}');
}
return parts.join(' · ');
}
/// Record a keystroke. Blank text with no kind clears locally and sends
/// nothing; valid kind-only browsing is sendable like the browser's search.
void updateQuery(String value) {
_query = value;
_error = null;
_cancelTimer();
final effective = parsed;
if (!searchQuerySendable(effective.query, effective.kind)) {
_sequencer.edit('');
_clearResults();
_notify();
return;
}
_loading = true;
final edit = _sequencer.edit(value);
_notify();
_timer = Timer(debounce, () {
_timer = null;
final sent = _sequencer.begin(edit);
if (sent != null) unawaited(_send(sent));
});
}
/// A kind change removes recognised type tokens from the visible text and
/// sends at once, matching the browser's selector behaviour.
void selectKind(SearchKind kind) {
_query = parseSearchQuery(_query, _selectedKind).query;
_selectedKind = kind;
_error = null;
_notify();
unawaited(sendNow());
}
/// Enter: send the current query immediately, skipping the debounce.
Future<void> submit() => sendNow();
/// Retry the current query after a failure.
Future<void> retry() => sendNow();
Future<void> sendNow() async {
_cancelTimer();
final effective = parseSearchQuery(_query, _selectedKind);
if (!searchQuerySendable(effective.query, effective.kind)) {
_sequencer.edit('');
_clearResults();
_notify();
return;
}
final sent = _sequencer.begin(_sequencer.edit(_query));
if (sent == null) return;
await _send(sent);
}
Future<void> _send(SearchEdit sent) async {
final effective = parseSearchQuery(sent.query, _selectedKind);
_loading = true;
_error = null;
_notify();
try {
final response = await repository.search(
query: effective.query.trim(),
kind: effective.kind,
);
if (!_sequencer.accepts(sent.token) || _disposed) return;
if (response == null) {
_loading = false;
_loaded = true;
_error = unsupportedSearchCopy;
_notify();
return;
}
_results = response.results;
_truncated = response.truncated;
_scannedSteps = response.scannedSteps;
_scannedBytes = response.scannedBytes;
_cap = response.cap;
_scanBoundBytes = response.scanBoundBytes;
_loading = false;
_loaded = true;
_error = null;
_notify();
} catch (error) {
if (!_sequencer.accepts(sent.token) || _disposed) return;
_loading = false;
_loaded = true;
_error = searchFailureText(error);
_notify();
}
}
void _clearResults() {
_results = const [];
_truncated = false;
_scannedSteps = 0;
_scannedBytes = 0;
_cap = 0;
_scanBoundBytes = 0;
_loading = false;
_loaded = false;
_error = null;
}
void _cancelTimer() {
_timer?.cancel();
_timer = null;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_cancelTimer();
super.dispose();
}
}
@@ -0,0 +1,43 @@
/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser.
String humanBytes(int size) {
const unit = 1024;
if (size < unit) return '$size B';
var divisor = unit;
var exponent = 0;
var scaled = size ~/ unit;
while (scaled >= unit && exponent < 5) {
divisor *= unit;
exponent++;
scaled ~/= unit;
}
return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB';
}
const _months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`),
/// or null when blank/unparseable so the caller omits the value rather than
/// printing a blank.
String? formatSearchTimestamp(String value) {
final text = value.trim();
if (text.isEmpty) return null;
final instant = DateTime.tryParse(text);
if (instant == null) return null;
final local = instant.toLocal();
final hour = local.hour.toString().padLeft(2, '0');
final minute = local.minute.toString().padLeft(2, '0');
return '${local.day} ${_months[local.month - 1]} $hour:$minute';
}
@@ -0,0 +1,87 @@
import '../../../core/api_gateway.dart';
/// The server's search narrowing vocabulary (`internal/protocol/search.go`),
/// in the control's display order. The empty [wire] value means every kind.
enum SearchKind {
all('', 'All kinds'),
pipeline('pipeline', 'Pipelines'),
run('run', 'Runs'),
step('step', 'Steps'),
field('field', 'Fields'),
artifact('artifact', 'Artifacts'),
version('version', 'Versions');
const SearchKind(this.wire, this.label);
final String wire;
final String label;
/// A stale or unknown value falls back to [SearchKind.all] rather than
/// inventing an option the server does not accept.
static SearchKind fromWire(String? wire) {
for (final kind in values) {
if (kind.wire == wire) return kind;
}
return SearchKind.all;
}
}
/// A query after `t:`/`type:` tokens have been recognised. [query] is the text
/// the server should match; [kind] is the effective narrowing.
class ParsedSearchQuery {
const ParsedSearchQuery(this.query, this.kind, this.hasType);
final String query;
final SearchKind kind;
final bool hasType;
}
/// The bounded `search_results` body from the server. Every bound the server
/// reports is kept, so the screen can show a truncation/scan indicator instead
/// of pretending a capped reply was complete.
class SearchResponse {
const SearchResponse({
this.query = '',
this.kind = SearchKind.all,
this.results = const [],
this.truncated = false,
this.scannedSteps = 0,
this.scannedBytes = 0,
this.cap = 0,
this.scanBoundBytes = 0,
});
factory SearchResponse.fromJson(JsonMap json) {
final rows = json['results'];
return SearchResponse(
query: '${json['query'] ?? ''}',
kind: SearchKind.fromWire('${json['kind'] ?? ''}'),
results: rows is List
? rows
.whereType<Map>()
.map((row) => Map<String, dynamic>.from(row))
.toList(growable: false)
: const [],
truncated: json['truncated'] == true,
scannedSteps: _integer(json['scanned_steps']),
scannedBytes: _integer(json['scanned_bytes']),
cap: _integer(json['cap']),
scanBoundBytes: _integer(json['scan_bound_bytes']),
);
}
final String query;
final SearchKind kind;
final List<JsonMap> results;
final bool truncated;
final int scannedSteps;
final int scannedBytes;
final int cap;
final int scanBoundBytes;
}
int _integer(Object? value) {
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('$value') ?? 0;
}
@@ -0,0 +1,82 @@
import 'search_models.dart';
/// Wording for a server that cannot answer `search`: an explicit rejection
/// naming an unknown/unsupported command, or a reply without
/// `search_results`. Kept verbatim from the web client's AppViewModel copy.
const unsupportedSearchCopy =
'This server does not support search. Update the Pipelines server, then try again.';
/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token
/// wins. Unknown tokens and quoted text stay literal, including their whitespace.
/// The selector is a fallback; explicitly changing it removes tokens in the view.
///
/// This is the same token grammar as `web/src/search.js`, so `"t:run"`,
/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text.
ParsedSearchQuery parseSearchQuery(
String value, [
SearchKind selectedKind = SearchKind.all,
]) {
var kind = selectedKind;
var hasType = false;
final query = value.replaceAllMapped(_tokenPattern, (match) {
final token = match[0] ?? '';
final type = _typePattern.firstMatch(token);
if (type == null) return token;
final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase());
if (candidate == SearchKind.all) return token;
kind = candidate;
hasType = true;
return '';
});
return ParsedSearchQuery(query, kind, hasType);
}
final _tokenPattern = RegExp(
r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''',
);
final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false);
/// Text searches and valid kind-only browsing are sendable. Empty text with no
/// supported kind clears locally, without an all-kind scan.
bool searchQuerySendable(String query, SearchKind kind) =>
query.trim().isNotEmpty || kind != SearchKind.all;
/// The message for a failed search: the unsupported sentence for a missing
/// payload or an unknown-command rejection, otherwise the server's own text.
String searchFailureText(Object? error) {
if (error == null) return unsupportedSearchCopy;
final message = error.toString().trim();
if (message.isEmpty) return unsupportedSearchCopy;
if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy;
return message;
}
final _unsupportedCommand = RegExp(
r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b',
caseSensitive: false,
);
/// One recorded edit being debounced.
class SearchEdit {
const SearchEdit(this.token, this.query);
final int token;
final String query;
}
/// Query sequencing: a burst of keystrokes collapses into one request, and a
/// reply is accepted only for the newest recorded edit, so a stale reply can
/// never overwrite a newer one. Recording an edit (a keystroke, or an empty
/// edit when the field clears) is enough to invalidate an in-flight reply.
class SearchSequencer {
int _newest = 0;
SearchEdit edit(String query) => SearchEdit(++_newest, query);
SearchEdit? begin(SearchEdit? edit) {
if (edit == null || edit.token != _newest) return null;
return edit;
}
bool accepts(int token) => token == _newest;
}
@@ -0,0 +1,226 @@
import '../../../core/api_gateway.dart';
import 'search_format.dart';
export 'search_format.dart' show humanBytes, formatSearchTimestamp;
/// One run of a field snippet, split so the first case-insensitive occurrence of
/// the query can be emphasised without colour or markup.
class SearchSnippetSpan {
const SearchSnippetSpan(this.text, {required this.matched});
final String text;
final bool matched;
}
/// A render-ready search row. [target] is the server's own stable target token;
/// it is null for an unknown/absent payload or a reply without a target, and
/// such a row is read-only — the client never guesses a route.
class SearchRowView {
const SearchRowView({
required this.title,
required this.secondary,
required this.kindLabel,
required this.snippetSpans,
required this.target,
this.snippet,
this.recency,
});
final String title;
final String secondary;
final String kindLabel;
final String? snippet;
final List<SearchSnippetSpan> snippetSpans;
final String? recency;
final String? target;
bool get openable => target != null;
}
/// One rendered search row, mirroring the browser's per-kind row text. Every
/// server-provided string is only ever compared or rendered as text.
SearchRowView searchRowView(JsonMap hit, String query) {
final pipeline = _map(hit['pipeline']);
final version = _map(hit['version']);
final run = _map(hit['run']);
final step = _map(hit['step']);
final field = _map(hit['field']);
final artifact = _map(hit['artifact']);
final recency = formatSearchTimestamp('${hit['recency'] ?? ''}');
final target = _serverTarget(hit);
if (pipeline != null) {
return SearchRowView(
title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}',
secondary:
'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}'
' · ${_stageCount(pipeline['stages'])}',
kindLabel: 'Pipeline',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (version != null) {
final hash = _nonBlank(version['content_hash']);
return SearchRowView(
title:
'pipeline ${_num(version['pipeline_id'])}'
' · v${_num(version['version'])}',
secondary: _join([
hash == null ? null : 'content $hash',
formatSearchTimestamp('${version['created_at'] ?? ''}'),
]),
kindLabel: 'Pipeline version',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (run != null) {
final name = _nonBlank(run['pipeline_name']);
return SearchRowView(
title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}',
secondary: _join([
_nonBlank(run['status']),
_nonBlank(run['workspace']),
formatSearchTimestamp('${run['created_at'] ?? ''}'),
]),
kindLabel: 'Run',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (step != null) {
final stage = _nonBlank(step['stage']) ?? 'step';
return SearchRowView(
title:
'run #${_num(step['run_id'])} · $stage'
' visit ${_num(step['visit'])}',
secondary: _stepSecondary(step),
kindLabel: 'Step',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (field != null) {
final snippet = '${field['snippet'] ?? ''}';
return SearchRowView(
title:
'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}'
' · ${_nonBlank(field['field']) ?? 'field'}',
secondary: snippet,
kindLabel: 'Field',
snippet: snippet,
snippetSpans: snippetSpans(snippet, query),
recency: recency,
target: target,
);
}
if (artifact != null) {
return SearchRowView(
title: _nonBlank(artifact['name']) ?? 'artifact',
secondary: _join([
'run #${_num(artifact['run_id'])}',
'step ${_num(artifact['sequence'])}',
_nonBlank(artifact['content_type']),
humanBytes(_num(artifact['size_bytes'])),
]),
kindLabel: 'Artifact',
snippetSpans: const [],
recency: recency,
target: target,
);
}
final kind = _nonBlank(hit['kind']);
return SearchRowView(
title: _nonBlank(hit['target']) ?? 'Unrecognised result',
secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only',
kindLabel: 'Unrecognised result',
snippetSpans: const [],
recency: recency,
target: target,
);
}
/// Splits [snippet] so the first case-insensitive occurrence of [query] is a
/// distinct matched span. A blank query or absent match leaves the whole
/// snippet unmatched, so no text is ever dropped.
List<SearchSnippetSpan> snippetSpans(String snippet, String query) {
if (snippet.isEmpty) return const [];
final needle = query.trim();
if (needle.isEmpty) {
return [SearchSnippetSpan(snippet, matched: false)];
}
final index = snippet.toLowerCase().indexOf(needle.toLowerCase());
if (index < 0) return [SearchSnippetSpan(snippet, matched: false)];
final end = index + needle.length;
return [
if (index > 0)
SearchSnippetSpan(snippet.substring(0, index), matched: false),
SearchSnippetSpan(snippet.substring(index, end), matched: true),
if (end < snippet.length)
SearchSnippetSpan(snippet.substring(end), matched: false),
];
}
String _stepSecondary(JsonMap step) {
final diagnostic = '${step['diagnostic'] ?? ''}';
String? line;
for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) {
if (candidate.trim().isNotEmpty) {
line = candidate;
break;
}
}
final target = _nonBlank(step['target']);
final joined = _join([
_nonBlank(step['outcome']),
target == null ? null : '→ $target',
line?.trim(),
]);
return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined;
}
/// The server's own target token, never a target the client invents. A known
/// payload is not enough: an absent token makes the row read-only.
String? _serverTarget(JsonMap hit) {
final target = _nonBlank(hit['target']);
if (target == null) return null;
final known = [
'pipeline',
'version',
'run',
'step',
'field',
'artifact',
].any((key) => _map(hit[key]) != null);
return known ? target : null;
}
String _stageCount(Object? count) {
final n = _num(count);
return '$n ${n == 1 ? 'stage' : 'stages'}';
}
Map<String, dynamic>? _map(Object? value) {
if (value is! Map) return null;
return Map<String, dynamic>.from(value);
}
String? _nonBlank(Object? value) {
final text = '${value ?? ''}';
return text.trim().isEmpty ? null : text;
}
int _num(Object? value) {
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('${value ?? ''}') ?? 0;
}
String _join(List<String?> parts) =>
parts.whereType<String>().where((part) => part.isNotEmpty).join(' · ');
+228
View File
@@ -0,0 +1,228 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'data/search_repository.dart';
import 'domain/search_controller.dart';
import 'domain/search_models.dart';
import 'ui/cupertino_search_body.dart';
import 'ui/material_search_body.dart';
/// Native omni-search over the Pipelines server: a standard search field, an
/// explicit kind selector, and a flat result list whose rows open the server's
/// own target through [onOpen]. The screen never mutates server state and never
/// guesses a route for an unknown or targetless hit.
class SearchScreen extends StatefulWidget {
const SearchScreen({
super.key,
required this.gateway,
required this.onOpen,
this.cupertino,
});
final ApiGateway gateway;
final ValueChanged<JsonMap> onOpen;
/// Lets the shell state the surface it composed. When omitted, iOS/macOS use
/// Cupertino controls and every other platform uses Material.
final bool? cupertino;
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
late final OmniSearchController _controller;
late final TextEditingController _text;
@override
void initState() {
super.initState();
_controller = OmniSearchController(
repository: SearchRepository(widget.gateway),
);
_text = TextEditingController();
_controller.addListener(_onState);
}
void _onState() {
final query = _controller.query;
if (_text.text != query) {
_text.value = TextEditingValue(
text: query,
selection: TextSelection.collapsed(offset: query.length),
);
}
if (mounted) setState(() {});
}
void _clear() {
_text.clear();
_controller.updateQuery('');
}
void _selectKind(SearchKind kind) => _controller.selectKind(kind);
bool get _showHint {
final body = _controller.bodyKind;
return body == SearchBodyKind.idle || body == SearchBodyKind.empty;
}
Future<void> _pickKind(BuildContext context) async {
final selected = await showCupertinoModalPopup<SearchKind>(
context: context,
builder: (context) => CupertinoActionSheet(
title: const Text('Kind'),
actions: [
for (final kind in SearchKind.values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, kind),
isDefaultAction: kind == _controller.parsed.kind,
child: Text(kind.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (selected != null) _selectKind(selected);
}
@override
void dispose() {
_controller.removeListener(_onState);
_controller.dispose();
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
widget.cupertino ??
switch (Theme.of(context).platform) {
TargetPlatform.iOS || TargetPlatform.macOS => true,
_ => false,
};
return cupertino ? _cupertinoScreen() : _materialScreen();
}
Widget _materialScreen() => Scaffold(
appBar: AppBar(title: const Text('Search')),
body: SafeArea(
child: MaterialSearchBody(
controller: _controller,
query: _controller.parsed.query,
onOpen: widget.onOpen,
header: _materialHeader(),
),
),
);
Widget _materialHeader() => Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
SearchBar(
key: const ValueKey('search.field'),
controller: _text,
autoFocus: true,
hintText: 'Search pipelines, runs and artifacts',
leading: const Icon(Icons.search),
trailing: [
if (_text.text.isNotEmpty)
IconButton(
key: const ValueKey('search.clear'),
onPressed: _clear,
tooltip: 'Clear search',
icon: const Icon(Icons.close),
),
],
textInputAction: TextInputAction.search,
onChanged: _controller.updateQuery,
onSubmitted: (_) => _controller.submit(),
),
InputDecorator(
decoration: const InputDecoration(
labelText: 'Kind',
border: OutlineInputBorder(),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<SearchKind>(
key: const ValueKey('search.kind'),
value: _controller.parsed.kind,
isExpanded: true,
onChanged: (kind) {
if (kind != null) _selectKind(kind);
},
items: [
for (final kind in SearchKind.values)
DropdownMenuItem(value: kind, child: Text(kind.label)),
],
),
),
),
if (_showHint) const Text(_tokenHint),
if (_controller.boundsText case final bounds?) Text(bounds),
],
),
);
Widget _cupertinoScreen() => CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Search')),
child: SafeArea(
child: CupertinoSearchBody(
controller: _controller,
query: _controller.parsed.query,
onOpen: widget.onOpen,
header: _cupertinoHeader(context),
),
),
);
Widget _cupertinoHeader(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
CupertinoSearchTextField(
key: const ValueKey('search.field'),
controller: _text,
autofocus: true,
placeholder: 'Search pipelines, runs and artifacts',
onChanged: _controller.updateQuery,
onSubmitted: (_) => _controller.submit(),
onSuffixTap: _clear,
),
Align(
alignment: AlignmentDirectional.centerStart,
child: CupertinoButton(
key: const ValueKey('search.kind'),
padding: EdgeInsets.zero,
onPressed: () => _pickKind(context),
child: Row(
mainAxisSize: MainAxisSize.max,
spacing: 6,
children: [
Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')),
const Icon(CupertinoIcons.chevron_down),
],
),
),
),
if (_showHint) const Text(_tokenHint),
if (_controller.boundsText case final bounds?) Text(bounds),
],
),
);
}
const _tokenHint =
'Filter with t:pipeline or type:artifact (pipeline, run, step, field, '
'artifact, version). Last type wins; choosing Kind replaces it. Quote '
'tokens to search literally.';
@@ -0,0 +1,174 @@
import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import '../domain/search_row.dart';
import 'search_result_view.dart';
/// The Cupertino search view: native search/kind controls and grouped list rows
/// in one scroll view, with standard activity and retry controls.
class CupertinoSearchBody extends StatelessWidget {
const CupertinoSearchBody({
super.key,
required this.controller,
required this.query,
required this.onOpen,
required this.header,
});
final OmniSearchController controller;
final String query;
final ValueChanged<JsonMap> onOpen;
final Widget header;
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
SliverToBoxAdapter(child: header),
if (controller.showProgress)
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CupertinoActivityIndicator(),
),
),
..._content(context),
],
);
}
List<Widget> _content(BuildContext context) {
switch (controller.bodyKind) {
case SearchBodyKind.error:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoError(
message: controller.error!,
onRetry: controller.retry,
),
),
];
case SearchBodyKind.searching:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoSearching(),
),
];
case SearchBodyKind.results:
return [
SliverToBoxAdapter(
child: CupertinoListSection.insetGrouped(
children: [
for (final hit in controller.shownResults)
_CupertinoResult(hit: hit, query: query, onOpen: onOpen),
],
),
),
];
case SearchBodyKind.empty:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoMessage(message: controller.emptyMessage!),
),
];
case SearchBodyKind.idle:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoMessage(
message: 'Search pipelines, runs and artifacts.',
),
),
];
}
}
}
class _CupertinoResult extends StatelessWidget {
const _CupertinoResult({
required this.hit,
required this.query,
required this.onOpen,
});
final JsonMap hit;
final String query;
final ValueChanged<JsonMap> onOpen;
@override
Widget build(BuildContext context) {
final row = searchRowView(hit, query);
return CupertinoListTile(
key: ValueKey('search.result.${hit['target']}'),
leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')),
title: Text(row.title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 2,
children: [searchRowMeta(row), searchRowSnippet(context, row)],
),
onTap: row.openable ? () => onOpen(hit) : null,
);
}
}
class _CupertinoSearching extends StatelessWidget {
const _CupertinoSearching();
@override
Widget build(BuildContext context) => const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [CupertinoActivityIndicator(), Text('Searching…')],
),
),
);
}
class _CupertinoMessage extends StatelessWidget {
const _CupertinoMessage({required this.message});
final String message;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
class _CupertinoError extends StatelessWidget {
const _CupertinoError({required this.message, required this.onRetry});
final String message;
final Future<void> Function() onRetry;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [
Text(message, textAlign: TextAlign.center),
CupertinoButton.filled(
key: const ValueKey('search.retry'),
onPressed: onRetry,
child: const Text('Retry'),
),
],
),
),
);
}
@@ -0,0 +1,166 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import '../domain/search_row.dart';
import 'search_result_view.dart';
/// The Material search view: the controls header and a flat native result list
/// in one scroll view, so text scaling can never clip the controls or a row.
class MaterialSearchBody extends StatelessWidget {
const MaterialSearchBody({
super.key,
required this.controller,
required this.query,
required this.onOpen,
required this.header,
});
final OmniSearchController controller;
final String query;
final ValueChanged<JsonMap> onOpen;
final Widget header;
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
SliverToBoxAdapter(child: header),
if (controller.showProgress)
const SliverToBoxAdapter(child: LinearProgressIndicator()),
..._content(context),
],
);
}
List<Widget> _content(BuildContext context) {
switch (controller.bodyKind) {
case SearchBodyKind.error:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchError(
message: controller.error!,
onRetry: controller.retry,
),
),
];
case SearchBodyKind.searching:
return const [
SliverFillRemaining(hasScrollBody: false, child: _Searching()),
];
case SearchBodyKind.results:
return [
SliverList.builder(
itemCount: controller.shownResults.length,
itemBuilder: (context, index) {
final hit = controller.shownResults[index];
return _MaterialResult(hit: hit, query: query, onOpen: onOpen);
},
),
];
case SearchBodyKind.empty:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchMessage(message: controller.emptyMessage!),
),
];
case SearchBodyKind.idle:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchMessage(
message: 'Search pipelines, runs and artifacts.',
),
),
];
}
}
}
class _MaterialResult extends StatelessWidget {
const _MaterialResult({
required this.hit,
required this.query,
required this.onOpen,
});
final JsonMap hit;
final String query;
final ValueChanged<JsonMap> onOpen;
@override
Widget build(BuildContext context) {
final row = searchRowView(hit, query);
return ListTile(
key: ValueKey('search.result.${hit['target']}'),
leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')),
title: Text(row.title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 2,
children: [searchRowMeta(row), searchRowSnippet(context, row)],
),
onTap: row.openable ? () => onOpen(hit) : null,
);
}
}
class _Searching extends StatelessWidget {
const _Searching();
@override
Widget build(BuildContext context) => const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [CircularProgressIndicator(), Text('Searching…')],
),
),
);
}
class _SearchMessage extends StatelessWidget {
const _SearchMessage({required this.message});
final String message;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
class _SearchError extends StatelessWidget {
const _SearchError({required this.message, required this.onRetry});
final String message;
final Future<void> Function() onRetry;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [
Text(message, textAlign: TextAlign.center),
FilledButton.tonalIcon(
key: const ValueKey('search.retry'),
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
),
],
),
),
);
}

Some files were not shown because too many files have changed in this diff Show More