Merge branch 'main' into flutter/d1-diff-viewer
This commit is contained in:
@@ -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,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,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,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;
|
||||
}
|
||||
@@ -10,6 +10,11 @@ const runStates = [
|
||||
'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 (
|
||||
@@ -116,25 +121,22 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
int primary;
|
||||
switch (sort) {
|
||||
case 'oldest_first':
|
||||
primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff);
|
||||
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 ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
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) ?? 0x7fffffffffffffff,
|
||||
duration(b) ?? 0x7fffffffffffffff,
|
||||
);
|
||||
primary = cmp(duration(a) ?? _maxMillis, duration(b) ?? _maxMillis);
|
||||
}
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'pipeline_name':
|
||||
@@ -142,7 +144,7 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
'${b['name'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
@@ -150,11 +152,11 @@ List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
'${b['status'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis);
|
||||
}
|
||||
return primary == 0
|
||||
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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 [];
|
||||
@@ -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(' · ');
|
||||
@@ -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'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/search_row.dart';
|
||||
|
||||
/// Kind, recency and read-only affordance for one row. Deliberately unstyled
|
||||
/// beyond weight so Material and Cupertino inherit their own system typography
|
||||
/// and colours, including dark mode and text scaling.
|
||||
Widget searchRowMeta(SearchRowView row) {
|
||||
final parts = [row.kindLabel, if (row.recency != null) row.recency!];
|
||||
return Text(
|
||||
parts.join(' · '),
|
||||
style: const TextStyle(fontWeight: FontWeight.w600),
|
||||
);
|
||||
}
|
||||
|
||||
/// The snippet with the first query occurrence emphasised by weight, never by
|
||||
/// parsing server text as markup or by a bespoke colour.
|
||||
Widget searchRowSnippet(BuildContext context, SearchRowView row) {
|
||||
final snippet = row.snippet;
|
||||
if (snippet == null) {
|
||||
return row.secondary.isEmpty
|
||||
? const SizedBox.shrink()
|
||||
: Text(row.secondary);
|
||||
}
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
for (final span in row.snippetSpans)
|
||||
TextSpan(
|
||||
text: span.text,
|
||||
style: span.matched
|
||||
? const TextStyle(fontWeight: FontWeight.bold)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
IconData searchMaterialIcon(String kind) => switch (kind) {
|
||||
'pipeline' => Icons.account_tree_outlined,
|
||||
'version' => Icons.layers_outlined,
|
||||
'run' => Icons.play_circle_outline,
|
||||
'step' => Icons.arrow_forward,
|
||||
'field' => Icons.notes,
|
||||
'artifact' => Icons.attach_file,
|
||||
_ => Icons.help_outline,
|
||||
};
|
||||
|
||||
IconData searchCupertinoIcon(String kind) => switch (kind) {
|
||||
'pipeline' => CupertinoIcons.arrow_branch,
|
||||
'version' => CupertinoIcons.square_stack_3d_up,
|
||||
'run' => CupertinoIcons.play_circle,
|
||||
'step' => CupertinoIcons.arrow_right,
|
||||
'field' => CupertinoIcons.doc_text,
|
||||
'artifact' => CupertinoIcons.paperclip,
|
||||
_ => CupertinoIcons.question_circle,
|
||||
};
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// The websocket endpoint the web build offers by default: the page's own
|
||||
/// origin, upgraded to ws/wss, at the server's `/connect` path.
|
||||
///
|
||||
/// The web client is served by a same-origin proxy, so this is a configurable
|
||||
/// starting value, not a baked host: it is derived from the page the operator
|
||||
/// actually loaded. Native builds have no such origin and start blank, so no
|
||||
/// server host or production endpoint is compiled into the app.
|
||||
///
|
||||
/// `web` and `base` are injectable only so the rule can be tested without a
|
||||
/// browser; production callers use the platform defaults.
|
||||
String defaultServerUrl({bool? web, Uri? base}) {
|
||||
if (!(web ?? kIsWeb)) return '';
|
||||
final origin = base ?? Uri.base;
|
||||
if (origin.host.isEmpty) return '';
|
||||
final secure = origin.scheme.toLowerCase() == 'https';
|
||||
return Uri(
|
||||
scheme: secure ? 'wss' : 'ws',
|
||||
host: origin.host,
|
||||
port: origin.hasPort ? origin.port : null,
|
||||
path: '/connect',
|
||||
).toString();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
/// Public API the manager needs to register the Settings destination.
|
||||
///
|
||||
/// The screen receives the shared `PipelinesClient`; it never creates, replaces
|
||||
/// or disposes one. `SettingsController` is exposed for previews and focused
|
||||
/// tests, not for the shell to construct separately.
|
||||
library;
|
||||
|
||||
export 'default_endpoint.dart';
|
||||
export 'settings_controller.dart' show PingCallback, SettingsController;
|
||||
export 'settings_copy.dart';
|
||||
export 'settings_screen.dart';
|
||||
export 'settings_store.dart';
|
||||
@@ -0,0 +1,281 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../core/transport/pipelines_client.dart' as transport;
|
||||
import '../../core/transport/server_url.dart';
|
||||
import 'settings_copy.dart';
|
||||
import 'settings_store.dart';
|
||||
|
||||
/// The ping request the status card makes once per connection. The default is
|
||||
/// the shared client's own `ping` request; tests inject a recorded callback.
|
||||
typedef PingCallback = Future<Map<String, dynamic>> Function();
|
||||
|
||||
/// Owns the Settings screen's draft text, validation and the actions that drive
|
||||
/// the shared [transport.PipelinesClient].
|
||||
///
|
||||
/// The feature never owns the client: it subscribes to the client's state and
|
||||
/// calls connect/disconnect, but never calls `dispose()` on it, and it never
|
||||
/// opens a connection by itself. One controller is created per screen, not per
|
||||
/// rebuild, so rebuilding Settings cannot start a second connection.
|
||||
class SettingsController extends ChangeNotifier {
|
||||
SettingsController({
|
||||
required this.client,
|
||||
required this.store,
|
||||
this.initialEndpoint,
|
||||
String defaultEndpoint = '',
|
||||
PingCallback? ping,
|
||||
}) : _defaultServerUrl = defaultEndpoint,
|
||||
_ping = ping ?? (() => client.call('ping')),
|
||||
_connection = client.state {
|
||||
_lastKind = _connection.kind;
|
||||
_subscription = client.states.listen(_onConnectionState);
|
||||
// Details belong to the current socket, not to the preferences read.
|
||||
// Mark them pending before the first frame when opening Settings live.
|
||||
if (_connection.kind == transport.ConnectionKind.connected) _requestPing();
|
||||
}
|
||||
|
||||
final transport.PipelinesClient client;
|
||||
final SettingsStore store;
|
||||
final Uri? initialEndpoint;
|
||||
final String _defaultServerUrl;
|
||||
final PingCallback _ping;
|
||||
|
||||
late final StreamSubscription<transport.ConnectionState> _subscription;
|
||||
|
||||
transport.ConnectionState _connection;
|
||||
transport.ConnectionKind _lastKind = transport.ConnectionKind.idle;
|
||||
String _serverUrl = '';
|
||||
String _urlError = '';
|
||||
String _workspaceDraft = '';
|
||||
String _savedWorkspace = '';
|
||||
String _workspaceSaveError = '';
|
||||
String _endpointSaveError = '';
|
||||
String _actionError = '';
|
||||
String _buildVersion = '';
|
||||
String _buildCommit = '';
|
||||
String _serverTime = '';
|
||||
String _pingError = '';
|
||||
bool _pingInFlight = false;
|
||||
bool _pingRequestedForConnected = false;
|
||||
int _pingToken = 0;
|
||||
bool _initialized = false;
|
||||
bool _serverUrlEdited = false;
|
||||
bool _workspaceEdited = false;
|
||||
bool _disposed = false;
|
||||
|
||||
transport.ConnectionState get connection => _connection;
|
||||
String get serverUrl => _serverUrl;
|
||||
String get urlError => _urlError;
|
||||
String get workspaceDraft => _workspaceDraft;
|
||||
String get savedWorkspace => _savedWorkspace;
|
||||
String get workspaceError => validateWorkspacePath(_workspaceDraft) ?? '';
|
||||
String get workspaceSaveError => _workspaceSaveError;
|
||||
String get endpointSaveError => _endpointSaveError;
|
||||
String get actionError => _actionError;
|
||||
String get buildVersion => _buildVersion;
|
||||
String get buildCommit => _buildCommit;
|
||||
String get serverTime => _serverTime;
|
||||
String get pingError => _pingError;
|
||||
bool get pingInFlight => _pingInFlight;
|
||||
|
||||
bool get connectionActive =>
|
||||
_connection.kind == transport.ConnectionKind.connected ||
|
||||
_connection.kind == transport.ConnectionKind.connecting;
|
||||
|
||||
String get primaryActionLabel => connectionActive ? 'Disconnect' : 'Connect';
|
||||
String get secondaryActionLabel => connectionActive ? 'Connect' : 'Reconnect';
|
||||
|
||||
List<String> get connectionLines => connectionCardLines(
|
||||
_connection,
|
||||
buildVersion: _buildVersion,
|
||||
buildCommit: _buildCommit,
|
||||
serverTime: _serverTime,
|
||||
pingError: _pingError,
|
||||
pingInFlight: _pingInFlight,
|
||||
);
|
||||
|
||||
/// Reads the feature's own persisted values once. A draft the operator has
|
||||
/// already typed into is never overwritten by the asynchronous read.
|
||||
Future<void> initialize() async {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
final values = await store.load();
|
||||
if (_disposed) return;
|
||||
if (!_serverUrlEdited) {
|
||||
final saved = values.serverUrl.trim();
|
||||
_serverUrl =
|
||||
initialEndpoint?.toString() ??
|
||||
(saved.isNotEmpty ? saved : _defaultServerUrl);
|
||||
}
|
||||
if (!_workspaceEdited) {
|
||||
_workspaceDraft = values.workspace;
|
||||
_savedWorkspace = values.workspace.trim();
|
||||
}
|
||||
// The screen may be opened while the shared client is already connected;
|
||||
// find out what that server is. This never opens a connection.
|
||||
if (_connection.kind == transport.ConnectionKind.connected) _requestPing();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void updateServerUrl(String value) {
|
||||
_serverUrlEdited = true;
|
||||
_serverUrl = value;
|
||||
_urlError = '';
|
||||
_actionError = '';
|
||||
_notify();
|
||||
}
|
||||
|
||||
void updateWorkspace(String value) {
|
||||
_workspaceEdited = true;
|
||||
_workspaceDraft = value;
|
||||
_workspaceSaveError = '';
|
||||
_notify();
|
||||
}
|
||||
|
||||
/// Validates the draft, persists the endpoint and connects the shared client.
|
||||
/// An invalid draft names the problem on the field and touches no socket.
|
||||
Future<void> connect() async {
|
||||
final raw = _serverUrl;
|
||||
String wsUrl;
|
||||
try {
|
||||
wsUrl = ServerUrl.validate(raw).wsUrl;
|
||||
} on FormatException catch (error) {
|
||||
_urlError = error.message.toString();
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
_urlError = '';
|
||||
_actionError = '';
|
||||
if (_serverUrl != wsUrl) _serverUrl = wsUrl;
|
||||
final stored = await store.saveServerUrl(wsUrl);
|
||||
if (_disposed) return;
|
||||
_endpointSaveError = stored
|
||||
? ''
|
||||
: 'The server URL could not be saved; it applies to this session only.';
|
||||
_notify();
|
||||
try {
|
||||
await client.connect(Uri.parse(wsUrl));
|
||||
} catch (error) {
|
||||
if (_disposed) return;
|
||||
_actionError = 'Could not connect: ${_describe(error)}';
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-opening the validated endpoint is the same client operation as
|
||||
/// connecting; only the label differs, matching the web/Android settings.
|
||||
Future<void> reconnect() => connect();
|
||||
|
||||
/// Closes this screen's connection through the shared client. It never
|
||||
/// disposes the client: other features keep using the same instance.
|
||||
Future<void> disconnect() async {
|
||||
_actionError = '';
|
||||
try {
|
||||
await client.disconnect();
|
||||
} catch (error) {
|
||||
if (_disposed) return;
|
||||
_actionError = 'Could not disconnect: ${_describe(error)}';
|
||||
}
|
||||
if (!_disposed) _notify();
|
||||
}
|
||||
|
||||
/// Persists the trimmed absolute workspace. Only a stored value updates the
|
||||
/// `Saved workspace:` line; a failed write says so instead of claiming one.
|
||||
Future<void> saveWorkspace() async {
|
||||
if (!canSaveWorkspace(_workspaceDraft)) {
|
||||
_notify();
|
||||
return;
|
||||
}
|
||||
final value = _workspaceDraft.trim();
|
||||
final stored = await store.saveWorkspace(value);
|
||||
if (_disposed) return;
|
||||
_workspaceDraft = value;
|
||||
if (stored) {
|
||||
_savedWorkspace = value;
|
||||
_workspaceSaveError = '';
|
||||
} else {
|
||||
_workspaceSaveError =
|
||||
'The workspace could not be saved; it is not stored on this device.';
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _onConnectionState(transport.ConnectionState state) {
|
||||
if (_disposed) return;
|
||||
final previous = _lastKind;
|
||||
_connection = state;
|
||||
_lastKind = state.kind;
|
||||
if (state.kind == transport.ConnectionKind.connected) {
|
||||
_requestPing();
|
||||
} else {
|
||||
// Never keep one server's build/time while another connection, or no
|
||||
// connection, is being shown.
|
||||
_clearPingDetails();
|
||||
if (previous == transport.ConnectionKind.connected) _pingToken++;
|
||||
}
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _requestPing() {
|
||||
if (_disposed || _pingRequestedForConnected) return;
|
||||
_pingRequestedForConnected = true;
|
||||
_pingError = '';
|
||||
_pingInFlight = true;
|
||||
final token = ++_pingToken;
|
||||
unawaited(_runPing(token));
|
||||
}
|
||||
|
||||
Future<void> _runPing(int token) async {
|
||||
try {
|
||||
final reply = await _ping();
|
||||
if (!_isCurrentPing(token)) return;
|
||||
final build = reply['build'];
|
||||
_buildVersion = build is Map
|
||||
? '${build['version'] ?? ''}'.trim()
|
||||
: '${build ?? ''}'.trim();
|
||||
_buildCommit = build is Map ? '${build['commit'] ?? ''}'.trim() : '';
|
||||
_serverTime = '${reply['time'] ?? ''}'.trim();
|
||||
_pingError = '';
|
||||
} catch (error) {
|
||||
if (!_isCurrentPing(token)) return;
|
||||
_pingError = 'Server details unavailable: ${_describe(error)}';
|
||||
} finally {
|
||||
if (_isCurrentPing(token)) {
|
||||
_pingInFlight = false;
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool _isCurrentPing(int token) =>
|
||||
!_disposed && token == _pingToken && _pingRequestedForConnected;
|
||||
|
||||
void _clearPingDetails() {
|
||||
_pingRequestedForConnected = false;
|
||||
_pingInFlight = false;
|
||||
_pingError = '';
|
||||
_buildVersion = '';
|
||||
_buildCommit = '';
|
||||
_serverTime = '';
|
||||
}
|
||||
|
||||
String _describe(Object error) {
|
||||
final text = error.toString().trim();
|
||||
return text.isEmpty ? 'unknown error' : text;
|
||||
}
|
||||
|
||||
void _notify() {
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
_disposed = true;
|
||||
_pingToken++;
|
||||
_subscription.cancel();
|
||||
// The shared client outlives this screen; it is deliberately not disposed.
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'settings_layout.dart';
|
||||
|
||||
/// Whether the current platform expects Cupertino controls. The app's theme is
|
||||
/// the single source of the platform answer, so dark mode and platform overrides
|
||||
/// stay consistent with the rest of the shell.
|
||||
bool usesCupertinoControls(BuildContext context) =>
|
||||
Theme.of(context).platform == TargetPlatform.iOS;
|
||||
|
||||
/// A native text field with a label and one supporting line. Both platforms lay
|
||||
/// the label out as wrapping text above the field; Material uses an outlined
|
||||
/// [TextField] and iOS a [CupertinoTextField]. Labels and helper/error copy are
|
||||
/// never line-capped, so large text cannot truncate them. No font sizes, heights
|
||||
/// or colours are fixed here.
|
||||
class SettingsTextField extends StatelessWidget {
|
||||
const SettingsTextField({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.label,
|
||||
required this.placeholder,
|
||||
required this.helper,
|
||||
required this.onChanged,
|
||||
this.error = '',
|
||||
});
|
||||
|
||||
final TextEditingController controller;
|
||||
final String label;
|
||||
final String placeholder;
|
||||
final String helper;
|
||||
final ValueChanged<String> onChanged;
|
||||
final String error;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final hasError = error.trim().isNotEmpty;
|
||||
// The label is laid out as normal wrapping text on both platforms. A
|
||||
// Material floating label is single-line and ellipsizes the workspace label
|
||||
// at narrow widths or large text, dropping required words.
|
||||
final labelWidget = ExcludeSemantics(
|
||||
child: Text(label, style: theme.textTheme.titleSmall),
|
||||
);
|
||||
if (!usesCupertinoControls(context)) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
labelWidget,
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Semantics(
|
||||
label: label,
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
onChanged: onChanged,
|
||||
keyboardType: TextInputType.url,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
textInputAction: TextInputAction.done,
|
||||
decoration: InputDecoration(
|
||||
hintText: placeholder,
|
||||
// `helperText`/`errorText` single-line-ellipsize unless capped
|
||||
// by `helperMaxLines`/`errorMaxLines`. Widgets wrap with no line
|
||||
// cap, so the full instructions stay readable at 2x.
|
||||
helper: hasError
|
||||
? null
|
||||
: Text(
|
||||
helper,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
error: hasError
|
||||
? Text(
|
||||
error,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
)
|
||||
: null,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
final supportingColor = hasError
|
||||
? theme.colorScheme.error
|
||||
: theme.colorScheme.onSurfaceVariant;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
labelWidget,
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Semantics(
|
||||
label: label,
|
||||
child: CupertinoTextField(
|
||||
controller: controller,
|
||||
onChanged: onChanged,
|
||||
placeholder: placeholder,
|
||||
keyboardType: TextInputType.url,
|
||||
autocorrect: false,
|
||||
enableSuggestions: false,
|
||||
clearButtonMode: OverlayVisibilityMode.editing,
|
||||
textInputAction: TextInputAction.done,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
hasError ? error : helper,
|
||||
style: theme.textTheme.bodySmall?.copyWith(color: supportingColor),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The filled primary and outlined secondary settings actions. Buttons wrap on
|
||||
/// a narrow window (or with large text) instead of overflowing.
|
||||
class SettingsActions extends StatelessWidget {
|
||||
const SettingsActions({
|
||||
super.key,
|
||||
required this.primaryLabel,
|
||||
required this.secondaryLabel,
|
||||
required this.onPrimary,
|
||||
required this.onSecondary,
|
||||
this.primaryKey,
|
||||
this.secondaryKey,
|
||||
});
|
||||
|
||||
final String primaryLabel;
|
||||
final String secondaryLabel;
|
||||
final VoidCallback onPrimary;
|
||||
final VoidCallback onSecondary;
|
||||
final Key? primaryKey;
|
||||
final Key? secondaryKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (usesCupertinoControls(context)) {
|
||||
return Wrap(
|
||||
spacing: settingsControlGap,
|
||||
runSpacing: settingsControlGap,
|
||||
children: <Widget>[
|
||||
CupertinoButton.filled(
|
||||
key: primaryKey,
|
||||
onPressed: onPrimary,
|
||||
child: Text(primaryLabel),
|
||||
),
|
||||
CupertinoButton(
|
||||
key: secondaryKey,
|
||||
onPressed: onSecondary,
|
||||
child: Text(secondaryLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Wrap(
|
||||
spacing: settingsControlGap,
|
||||
runSpacing: settingsControlGap,
|
||||
children: <Widget>[
|
||||
FilledButton(
|
||||
key: primaryKey,
|
||||
onPressed: onPrimary,
|
||||
child: Text(primaryLabel),
|
||||
),
|
||||
OutlinedButton(
|
||||
key: secondaryKey,
|
||||
onPressed: onSecondary,
|
||||
child: Text(secondaryLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// One standard settings card: a Material [Card] or an inset-grouped Cupertino
|
||||
/// section, both using theme surfaces and native corner/padding defaults.
|
||||
class SettingsCard extends StatelessWidget {
|
||||
const SettingsCard({super.key, required this.child});
|
||||
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (usesCupertinoControls(context)) {
|
||||
return CupertinoListSection.insetGrouped(
|
||||
margin: EdgeInsets.zero,
|
||||
children: <Widget>[
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(settingsCardPadding),
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Card(
|
||||
margin: EdgeInsets.zero,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(settingsCardPadding),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import '../../core/transport/pipelines_client.dart' as transport;
|
||||
|
||||
/// Field and explanatory copy, matching the current web Settings destination
|
||||
/// (web/src/settings.js) and the Android SettingsScreen it quotes.
|
||||
const String serverUrlPlaceholder = 'ws://192.168.1.20:8081/connect';
|
||||
|
||||
const String serverUrlHelper =
|
||||
'ws:// on a trusted LAN/VPN, or wss:// through a proxy/VPN. '
|
||||
'No authentication is used.';
|
||||
|
||||
const String workspacePlaceholder = '/Users/you/repos/pipelines';
|
||||
|
||||
const String workspaceHelper =
|
||||
'An absolute directory that already exists on the execution server. For '
|
||||
'Docker, mount the host directory at the same absolute path with its '
|
||||
"owner's UID/GID. This is not the phone's storage.";
|
||||
|
||||
const String workspacePathError =
|
||||
'The workspace must be an absolute path that exists on the execution '
|
||||
'server.';
|
||||
|
||||
const String trustTitle = 'Trusted LAN/VPN only';
|
||||
|
||||
const String trustBody =
|
||||
'The Pipelines API has no authentication and is not internet-safe. Do not '
|
||||
'expose it to untrusted networks, and never enter provider credentials '
|
||||
'here \u2014 the app stores none.';
|
||||
|
||||
/// The workspace draft is valid when it is untouched (empty) or absolute. A
|
||||
/// relative path is the one rejected value; the execution server resolves the
|
||||
/// path, so the phone's filesystem is irrelevant.
|
||||
String? validateWorkspacePath(String value) {
|
||||
final trimmed = value.trim();
|
||||
if (trimmed.isEmpty) return null;
|
||||
if (!trimmed.startsWith('/')) return workspacePathError;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Saving requires a real absolute path, not just "no error": the web Settings
|
||||
/// page deliberately refuses a blank field and records that strictness.
|
||||
bool canSaveWorkspace(String value) {
|
||||
final trimmed = value.trim();
|
||||
return trimmed.isNotEmpty && validateWorkspacePath(trimmed) == null;
|
||||
}
|
||||
|
||||
/// The persisted workspace line. An absent value is named, never rendered as a
|
||||
/// zero or an empty gap.
|
||||
String savedWorkspaceLine(String value) {
|
||||
final trimmed = value.trim();
|
||||
return 'Saved workspace: ${trimmed.isEmpty ? '(none)' : trimmed}';
|
||||
}
|
||||
|
||||
/// The exact shared connecting sentence used by the banner and status card.
|
||||
String connectingLabel(int attempt) => 'Connecting (attempt $attempt)\u2026';
|
||||
|
||||
/// `Server build {version} ({commit})`, with whichever parts the ping reported.
|
||||
String serverBuildLabel({String? version, String? commit}) {
|
||||
final v = (version ?? '').trim();
|
||||
final c = (commit ?? '').trim();
|
||||
final parts = <String>[if (v.isNotEmpty) v, if (c.isNotEmpty) '($c)'];
|
||||
if (parts.isEmpty) return '';
|
||||
return 'Server build ${parts.join(' ')}';
|
||||
}
|
||||
|
||||
/// The pending sentence shown between `Connected` and the ping reply. It is a
|
||||
/// request in flight, not a missing value.
|
||||
const String serverDetailsPending = 'Loading server details\u2026';
|
||||
|
||||
/// The status card's lines in the web/Android order. While the ping is in
|
||||
/// flight the card says it is loading. A completed reply names the build and
|
||||
/// time, saying "unavailable" only when that reply omitted them; a failed ping
|
||||
/// is one explicit line instead of two "unavailable" lines plus the error.
|
||||
List<String> connectionCardLines(
|
||||
transport.ConnectionState state, {
|
||||
String? buildVersion,
|
||||
String? buildCommit,
|
||||
String? serverTime,
|
||||
String pingError = '',
|
||||
bool pingInFlight = false,
|
||||
}) {
|
||||
switch (state.kind) {
|
||||
case transport.ConnectionKind.connected:
|
||||
final build = serverBuildLabel(
|
||||
version: buildVersion,
|
||||
commit: buildCommit,
|
||||
);
|
||||
final time = (serverTime ?? '').trim();
|
||||
final failure = pingError.trim();
|
||||
if (pingInFlight && build.isEmpty && time.isEmpty && failure.isEmpty) {
|
||||
return const <String>['Connected', serverDetailsPending];
|
||||
}
|
||||
if (failure.isNotEmpty && build.isEmpty && time.isEmpty) {
|
||||
return <String>['Connected', failure];
|
||||
}
|
||||
return <String>[
|
||||
'Connected',
|
||||
build.isEmpty ? 'Server build unavailable' : build,
|
||||
time.isEmpty ? 'Server time unavailable' : 'Server time $time',
|
||||
if (failure.isNotEmpty) failure,
|
||||
];
|
||||
case transport.ConnectionKind.connecting:
|
||||
return <String>[connectingLabel(state.attempt)];
|
||||
case transport.ConnectionKind.disconnected:
|
||||
final reason = state.reason.trim();
|
||||
return <String>[
|
||||
'Disconnected',
|
||||
if (reason.isNotEmpty) reason,
|
||||
if (state.retrying) 'Retrying with backoff\u2026',
|
||||
];
|
||||
case transport.ConnectionKind.idle:
|
||||
return const <String>['Not connected'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The keys the screen and its widget tests share. They name controls, not
|
||||
/// dimensions or copy.
|
||||
abstract final class SettingsKeys {
|
||||
static const serverUrl = ValueKey<String>('settings.serverUrl');
|
||||
static const connect = ValueKey<String>('settings.connect');
|
||||
static const disconnect = ValueKey<String>('settings.disconnect');
|
||||
static const reconnect = ValueKey<String>('settings.reconnect');
|
||||
static const workspace = ValueKey<String>('settings.workspace');
|
||||
static const saveWorkspace = ValueKey<String>('settings.saveWorkspace');
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/// The one place the Settings screen keeps its necessary layout constraints.
|
||||
///
|
||||
/// Everything else (control heights, font sizes, colours, button padding) comes
|
||||
/// from the active Material or Cupertino theme, so text scaling and platform
|
||||
/// defaults are never overridden here.
|
||||
library;
|
||||
|
||||
/// A comfortable reading width on wide windows; the body is centred inside it.
|
||||
const double settingsContentMaxWidth = 720;
|
||||
|
||||
/// Space between the Settings sections.
|
||||
const double settingsSectionGap = 24;
|
||||
|
||||
/// Space between a section title and its controls.
|
||||
const double settingsTitleGap = 12;
|
||||
|
||||
/// Space between a field and its supporting text.
|
||||
const double settingsFieldGap = 6;
|
||||
|
||||
/// Space between wrapped action buttons.
|
||||
const double settingsControlGap = 8;
|
||||
|
||||
/// Padding around the page body on narrow windows.
|
||||
const double settingsPagePadding = 16;
|
||||
|
||||
/// Padding inside a standard Material card / Cupertino inset row.
|
||||
const double settingsCardPadding = 16;
|
||||
@@ -0,0 +1,148 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/transport/pipelines_client.dart' as transport;
|
||||
import 'default_endpoint.dart';
|
||||
import 'settings_controller.dart';
|
||||
import 'settings_controls.dart';
|
||||
import 'settings_layout.dart';
|
||||
import 'settings_sections.dart';
|
||||
import 'settings_store.dart';
|
||||
|
||||
/// The Settings destination: the server connection and the server-side
|
||||
/// workspace, in native Material (native platforms) or Cupertino (iOS) controls.
|
||||
///
|
||||
/// The shared [transport.PipelinesClient] is supplied by the shell. This screen
|
||||
/// subscribes to it, connects/disconnects it and pings it on connected, but it
|
||||
/// never opens a connection on its own and never disposes the client. One
|
||||
/// controller is created in [initState], so rebuilding the screen cannot start
|
||||
/// a second connection.
|
||||
class SettingsScreen extends StatefulWidget {
|
||||
const SettingsScreen({
|
||||
super.key,
|
||||
required this.client,
|
||||
this.initialEndpoint,
|
||||
this.store,
|
||||
this.ping,
|
||||
});
|
||||
|
||||
final transport.PipelinesClient client;
|
||||
|
||||
/// A fixture/preview seed for the URL field. Persisted settings still load;
|
||||
/// this value takes precedence for the draft and is never written by itself.
|
||||
final Uri? initialEndpoint;
|
||||
|
||||
/// The feature's own persistence. Defaults to the `pipelines.next` keys.
|
||||
final SettingsStore? store;
|
||||
|
||||
/// Test seam for the exact ping request. Production uses `client.call('ping')`.
|
||||
final PingCallback? ping;
|
||||
|
||||
@override
|
||||
State<SettingsScreen> createState() => _SettingsScreenState();
|
||||
}
|
||||
|
||||
class _SettingsScreenState extends State<SettingsScreen> {
|
||||
final TextEditingController _serverUrlField = TextEditingController();
|
||||
final TextEditingController _workspaceField = TextEditingController();
|
||||
late final SettingsController _controller;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_controller = SettingsController(
|
||||
client: widget.client,
|
||||
store: widget.store ?? const SharedPreferencesSettingsStore(),
|
||||
initialEndpoint: widget.initialEndpoint,
|
||||
defaultEndpoint: defaultServerUrl(),
|
||||
ping: widget.ping,
|
||||
);
|
||||
_controller.addListener(_onSettingsChanged);
|
||||
unawaited(_controller.initialize());
|
||||
}
|
||||
|
||||
void _onSettingsChanged() {
|
||||
if (!mounted) return;
|
||||
_syncField(_serverUrlField, _controller.serverUrl);
|
||||
_syncField(_workspaceField, _controller.workspaceDraft);
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
/// Follow the controller's value (a restored value or the normalised URL)
|
||||
/// without disturbing a field the operator is already typing in.
|
||||
void _syncField(TextEditingController field, String value) {
|
||||
if (field.text == value) return;
|
||||
field.value = TextEditingValue(
|
||||
text: value,
|
||||
selection: TextSelection.collapsed(offset: value.length),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.removeListener(_onSettingsChanged);
|
||||
_controller.dispose();
|
||||
_serverUrlField.dispose();
|
||||
_workspaceField.dispose();
|
||||
// The shared client is owned by the shell and deliberately outlives this
|
||||
// screen, so it is not disposed here.
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final content = SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(settingsPagePadding),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: settingsContentMaxWidth,
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
const _SectionTitle('Connection'),
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
SettingsConnectionSection(
|
||||
controller: _controller,
|
||||
serverUrlField: _serverUrlField,
|
||||
),
|
||||
const SizedBox(height: settingsSectionGap),
|
||||
const _SectionTitle('Workspace'),
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
SettingsWorkspaceSection(
|
||||
controller: _controller,
|
||||
workspaceField: _workspaceField,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (usesCupertinoControls(context)) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(middle: Text('Settings')),
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: content,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SectionTitle extends StatelessWidget {
|
||||
const _SectionTitle(this.title);
|
||||
|
||||
final String title;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Text(title, style: Theme.of(context).textTheme.titleMedium);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../core/transport/pipelines_client.dart' as transport;
|
||||
import 'settings_controller.dart';
|
||||
import 'settings_controls.dart';
|
||||
import 'settings_copy.dart';
|
||||
import 'settings_keys.dart';
|
||||
import 'settings_trust_warning.dart';
|
||||
import 'settings_layout.dart';
|
||||
|
||||
/// Connection controls: the editable endpoint, the truthful connection card and
|
||||
/// the trusted-network warning. Every action goes through the shared client the
|
||||
/// controller was given; nothing here opens a second connection.
|
||||
class SettingsConnectionSection extends StatelessWidget {
|
||||
const SettingsConnectionSection({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.serverUrlField,
|
||||
});
|
||||
|
||||
final SettingsController controller;
|
||||
final TextEditingController serverUrlField;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
SettingsTextField(
|
||||
controller: serverUrlField,
|
||||
key: SettingsKeys.serverUrl,
|
||||
label: 'Server URL',
|
||||
placeholder: serverUrlPlaceholder,
|
||||
helper: serverUrlHelper,
|
||||
error: controller.urlError,
|
||||
onChanged: controller.updateServerUrl,
|
||||
),
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
SettingsActions(
|
||||
primaryLabel: controller.primaryActionLabel,
|
||||
secondaryLabel: controller.secondaryActionLabel,
|
||||
primaryKey: controller.connectionActive
|
||||
? SettingsKeys.disconnect
|
||||
: SettingsKeys.connect,
|
||||
secondaryKey: controller.connectionActive
|
||||
? SettingsKeys.connect
|
||||
: SettingsKeys.reconnect,
|
||||
onPrimary: () => unawaited(
|
||||
controller.connectionActive
|
||||
? controller.disconnect()
|
||||
: controller.connect(),
|
||||
),
|
||||
onSecondary: () => unawaited(
|
||||
controller.connectionActive
|
||||
? controller.connect()
|
||||
: controller.reconnect(),
|
||||
),
|
||||
),
|
||||
if (controller.endpointSaveError.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
controller.endpointSaveError,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (controller.actionError.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
controller.actionError,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
SettingsStatusCard(controller: controller),
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
const SettingsTrustWarning(),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The status card's first line is the state; the remaining lines are the
|
||||
/// build/time/reason/backoff facts. Missing ping values stay explicit.
|
||||
class SettingsStatusCard extends StatelessWidget {
|
||||
const SettingsStatusCard({super.key, required this.controller});
|
||||
|
||||
final SettingsController controller;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final state = controller.connection;
|
||||
final lines = controller.connectionLines;
|
||||
final title = lines.isEmpty ? '' : lines.first;
|
||||
final details = lines.length > 1 ? lines.sublist(1) : const <String>[];
|
||||
final titleColor = switch (state.kind) {
|
||||
transport.ConnectionKind.connected => theme.colorScheme.primary,
|
||||
transport.ConnectionKind.disconnected => theme.colorScheme.error,
|
||||
_ => theme.colorScheme.onSurface,
|
||||
};
|
||||
final titleWidget = Text(
|
||||
title,
|
||||
style: theme.textTheme.titleMedium?.copyWith(color: titleColor),
|
||||
);
|
||||
return SettingsCard(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
if (state.kind == transport.ConnectionKind.connecting)
|
||||
Row(
|
||||
children: <Widget>[
|
||||
if (usesCupertinoControls(context))
|
||||
const CupertinoActivityIndicator()
|
||||
else
|
||||
const CircularProgressIndicator(strokeWidth: 2),
|
||||
const SizedBox(width: settingsControlGap),
|
||||
Expanded(child: titleWidget),
|
||||
],
|
||||
)
|
||||
else
|
||||
titleWidget,
|
||||
for (final line in details) ...<Widget>[
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
line,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Workspace controls. The path is resolved by the execution server, and the
|
||||
/// helper says so explicitly; an empty saved value is named "(none)".
|
||||
class SettingsWorkspaceSection extends StatelessWidget {
|
||||
const SettingsWorkspaceSection({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.workspaceField,
|
||||
});
|
||||
|
||||
final SettingsController controller;
|
||||
final TextEditingController workspaceField;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final saveError = controller.workspaceSaveError;
|
||||
final canSave = canSaveWorkspace(controller.workspaceDraft);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: <Widget>[
|
||||
SettingsTextField(
|
||||
controller: workspaceField,
|
||||
key: SettingsKeys.workspace,
|
||||
label: 'Workspace path (on the server)',
|
||||
placeholder: workspacePlaceholder,
|
||||
helper: workspaceHelper,
|
||||
error: controller.workspaceError,
|
||||
onChanged: controller.updateWorkspace,
|
||||
),
|
||||
const SizedBox(height: settingsTitleGap),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: usesCupertinoControls(context)
|
||||
? CupertinoButton.filled(
|
||||
key: SettingsKeys.saveWorkspace,
|
||||
onPressed: canSave
|
||||
? () => unawaited(controller.saveWorkspace())
|
||||
: null,
|
||||
child: const Text('Save workspace'),
|
||||
)
|
||||
: FilledButton(
|
||||
key: SettingsKeys.saveWorkspace,
|
||||
onPressed: canSave
|
||||
? () => unawaited(controller.saveWorkspace())
|
||||
: null,
|
||||
child: const Text('Save workspace'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
savedWorkspaceLine(controller.savedWorkspace),
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
if (saveError.isNotEmpty) ...<Widget>[
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
saveError,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// The app's own settings keys. They are deliberately independent of the legacy
|
||||
/// web/Android storage: no value is imported, migrated or written under an old
|
||||
/// key, and nothing but the endpoint and the server workspace is persisted.
|
||||
const String settingsServerUrlKey = 'pipelines.next.serverUrl.v1';
|
||||
const String settingsWorkspaceKey = 'pipelines.next.workspace.v1';
|
||||
|
||||
/// The persisted settings, read as a pair. Both values are trimmed strings; an
|
||||
/// absent or unreadable value is empty rather than an error.
|
||||
class SettingsValues {
|
||||
const SettingsValues({this.serverUrl = '', this.workspace = ''});
|
||||
|
||||
final String serverUrl;
|
||||
final String workspace;
|
||||
}
|
||||
|
||||
/// The persistence seam used by the screen and its tests. Saves report whether
|
||||
/// the value is actually stored, so the UI never claims a save that failed.
|
||||
abstract interface class SettingsStore {
|
||||
Future<SettingsValues> load();
|
||||
|
||||
Future<bool> saveServerUrl(String value);
|
||||
|
||||
Future<bool> saveWorkspace(String value);
|
||||
}
|
||||
|
||||
/// `shared_preferences`-backed storage under the `pipelines.next` keys.
|
||||
///
|
||||
/// Reads are tolerant (an unavailable store means "nothing saved yet"). Saves
|
||||
/// return false instead of throwing, letting the screen keep the in-memory
|
||||
/// value while saying plainly that it was not stored.
|
||||
class SharedPreferencesSettingsStore implements SettingsStore {
|
||||
const SharedPreferencesSettingsStore();
|
||||
|
||||
Future<SharedPreferences?> _preferences() async {
|
||||
try {
|
||||
return await SharedPreferences.getInstance();
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SettingsValues> load() async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return const SettingsValues();
|
||||
try {
|
||||
return SettingsValues(
|
||||
serverUrl: preferences.getString(settingsServerUrlKey) ?? '',
|
||||
workspace: preferences.getString(settingsWorkspaceKey) ?? '',
|
||||
);
|
||||
} catch (_) {
|
||||
return const SettingsValues();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> saveServerUrl(String value) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(settingsServerUrlKey, value.trim());
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> saveWorkspace(String value) async {
|
||||
final preferences = await _preferences();
|
||||
if (preferences == null) return false;
|
||||
try {
|
||||
return await preferences.setString(settingsWorkspaceKey, value.trim());
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An in-memory store for previews and tests. It never touches the platform
|
||||
/// store, so no production preference can be mutated by a fixture.
|
||||
class MemorySettingsStore implements SettingsStore {
|
||||
MemorySettingsStore({this.serverUrl = '', this.workspace = ''});
|
||||
|
||||
String serverUrl;
|
||||
String workspace;
|
||||
bool failSaves = false;
|
||||
|
||||
@override
|
||||
Future<SettingsValues> load() async =>
|
||||
SettingsValues(serverUrl: serverUrl, workspace: workspace);
|
||||
|
||||
@override
|
||||
Future<bool> saveServerUrl(String value) async {
|
||||
if (failSaves) return false;
|
||||
serverUrl = value.trim();
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> saveWorkspace(String value) async {
|
||||
if (failSaves) return false;
|
||||
workspace = value.trim();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'settings_controls.dart';
|
||||
import 'settings_copy.dart';
|
||||
import 'settings_layout.dart';
|
||||
|
||||
/// The trusted-network warning, using the app's exact web/Android copy. It is a
|
||||
/// card, not a dialog: no confirmation is required to read it.
|
||||
class SettingsTrustWarning extends StatelessWidget {
|
||||
const SettingsTrustWarning({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final icon = usesCupertinoControls(context)
|
||||
? CupertinoIcons.exclamationmark_triangle
|
||||
: Icons.warning_amber_rounded;
|
||||
return SettingsCard(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Icon(icon, color: theme.colorScheme.error),
|
||||
const SizedBox(width: settingsControlGap),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: <Widget>[
|
||||
Text(
|
||||
trustTitle,
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: settingsFieldGap),
|
||||
Text(
|
||||
trustBody,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/template_entry.dart';
|
||||
|
||||
/// A templates protocol refusal kept separate from transport errors; server
|
||||
/// error envelopes are propagated unchanged by [ApiGateway].
|
||||
class TemplateRepositoryException implements Exception {
|
||||
const TemplateRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Template catalogue, definition validation and create-only submission over
|
||||
/// the application's shared gateway.
|
||||
///
|
||||
/// These are reads plus one explicit submit. No method publishes, runs,
|
||||
/// overwrites or schedules a pipeline, so merely loading or validating a
|
||||
/// template can never start work.
|
||||
class TemplateRepository {
|
||||
TemplateRepository(this._gateway);
|
||||
final ApiGateway _gateway;
|
||||
|
||||
/// The server's template catalogue, exactly as `list_templates` returns it.
|
||||
/// A reply without a `templates` field is the older server answering with no
|
||||
/// catalogue, which is an empty list rather than an error.
|
||||
Future<List<TemplateEntry>> listTemplates() async {
|
||||
final reply = await _gateway.call('list_templates');
|
||||
final templates = reply['templates'];
|
||||
if (templates == null) return const [];
|
||||
if (templates is! List) {
|
||||
throw const TemplateRepositoryException(
|
||||
'The server returned no template catalogue.',
|
||||
);
|
||||
}
|
||||
return List.unmodifiable(
|
||||
templates.map((entry) {
|
||||
if (entry is! Map) {
|
||||
throw const TemplateRepositoryException(
|
||||
'The server returned a template that is not an object.',
|
||||
);
|
||||
}
|
||||
return TemplateEntry.fromJson(Map<String, dynamic>.from(entry));
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses one definition source on the server (`validate`) and returns the
|
||||
/// graph it produced. The source is sent byte-for-byte: no trimming, casing or
|
||||
/// whitespace changes. A malformed definition rejects with the server's own
|
||||
/// error; a reply without a graph is refused rather than reported as valid.
|
||||
Future<JsonMap> validate(String source) async {
|
||||
final reply = await _gateway.call('validate', {'source': source});
|
||||
final graph = reply['graph'];
|
||||
if (graph is! Map) {
|
||||
throw const TemplateRepositoryException('The server returned no graph.');
|
||||
}
|
||||
return Map<String, dynamic>.from(graph);
|
||||
}
|
||||
|
||||
/// Creates a new draft pipeline from [source] (`submit`), create-only.
|
||||
///
|
||||
/// A blank name is refused locally before anything is sent, matching the
|
||||
/// browser and Android clients; the name that is sent is trimmed. The source
|
||||
/// is not changed. `create_only` is always true, so an existing pipeline can
|
||||
/// never be overwritten, and no run is started.
|
||||
Future<JsonMap> submit(String name, String source) async {
|
||||
final trimmed = name.trim();
|
||||
if (trimmed.isEmpty) {
|
||||
throw const TemplateRepositoryException('Enter a pipeline name.');
|
||||
}
|
||||
final reply = await _gateway.call('submit', {
|
||||
'name': trimmed,
|
||||
'source': source,
|
||||
'create_only': true,
|
||||
});
|
||||
final detail = reply['detail'];
|
||||
if (detail is! Map) {
|
||||
throw const TemplateRepositoryException(
|
||||
'The server returned no pipeline detail.',
|
||||
);
|
||||
}
|
||||
return Map<String, dynamic>.from(detail);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// One template from the server catalogue.
|
||||
///
|
||||
/// The server owns this record: [key], [name], [description], [source] and
|
||||
/// [scheduled] are read from it verbatim and every other field is kept in
|
||||
/// [raw], so a later view or round-trip never loses fields this client does not
|
||||
/// understand yet. Loading a template is a read; it never publishes or runs it.
|
||||
class TemplateEntry {
|
||||
const TemplateEntry({
|
||||
required this.key,
|
||||
required this.name,
|
||||
required this.description,
|
||||
required this.source,
|
||||
required this.scheduled,
|
||||
required this.raw,
|
||||
});
|
||||
|
||||
factory TemplateEntry.fromJson(JsonMap json) {
|
||||
final raw = _frozenMap(json);
|
||||
return TemplateEntry(
|
||||
key: _text(raw['key']),
|
||||
name: _text(raw['name']),
|
||||
description: _text(raw['description']),
|
||||
source: _text(raw['source']),
|
||||
scheduled: raw['scheduled'] == true,
|
||||
raw: raw,
|
||||
);
|
||||
}
|
||||
|
||||
/// The stable catalogue key the gallery selects on.
|
||||
final String key;
|
||||
final String name;
|
||||
final String description;
|
||||
|
||||
/// The template's complete, untrimmed definition source.
|
||||
final String source;
|
||||
|
||||
/// Whether the source declares a schedule (the summary's "Includes a schedule").
|
||||
final bool scheduled;
|
||||
|
||||
/// Every field the server sent, including fields this client does not model.
|
||||
/// Deeply unmodifiable: nested maps and lists are copied into read-only
|
||||
/// collections too, so a view cannot mutate the server reply through it.
|
||||
final JsonMap raw;
|
||||
|
||||
static String _text(dynamic value) => value == null ? '' : '$value';
|
||||
|
||||
static JsonMap _frozenMap(Map<String, dynamic> 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user