merge(app): finish retained Runs integration after deadline

This commit is contained in:
2026-10-21 17:26:41 +01:00
40 changed files with 5025 additions and 50 deletions
+12 -10
View File
@@ -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)
+113
View File
@@ -0,0 +1,113 @@
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import 'data/runs_repository.dart';
import 'ui/run_detail_view.dart';
import 'ui/runs_controller.dart';
import 'ui/runs_list.dart';
/// The runs destination's list/detail switch.
///
/// The controller's `selectedRunId` is the only selection source, so an
/// initial run, a pending detail, a failed detail, Back and a route change all
/// navigate the same way. The shell owns the app bar; this screen adds no
/// second one.
class RunsScreen extends StatefulWidget {
const RunsScreen({
super.key,
required this.gateway,
this.initialRunId,
this.syncToken = 0,
this.onRunSelected,
this.onBack,
});
final ApiGateway gateway;
/// The run the current route names, or null for the list.
final int? initialRunId;
/// Advances when the shared socket is replaced. The loaded screen refreshes
/// in place instead of being remounted, so its selection survives.
final int syncToken;
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
class _RunsScreenState extends State<RunsScreen> {
late final RunsController controller;
num? _shownRunId;
@override
void initState() {
super.initState();
controller = RunsController(RunsRepository(widget.gateway));
controller.listen(widget.gateway.frames);
controller.addListener(_selectionChanged);
controller.load(widget.initialRunId);
}
@override
void didUpdateWidget(covariant RunsScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.syncToken != oldWidget.syncToken) {
controller.resync();
}
if (widget.initialRunId != oldWidget.initialRunId) {
final id = widget.initialRunId;
if (id == null) {
if (controller.selectedRunId != null) controller.back();
} else if (controller.selectedRunId != id) {
controller.select(id);
}
}
}
/// Rebuild the switch only when the selection changes. Detail progress and
/// live updates are already watched by [RunDetailView] and [RunsList], so
/// this avoids a second whole-detail rebuild per notification.
void _selectionChanged() {
final selected = controller.selectedRunId;
if (selected == _shownRunId) return;
_shownRunId = selected;
if (mounted) setState(() {});
}
void _select(num id) {
controller.select(id);
widget.onRunSelected?.call(id.toInt());
}
void _back() {
controller.back();
widget.onBack?.call();
}
@override
void dispose() {
controller.removeListener(_selectionChanged);
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final selected = controller.selectedRunId != null;
return Stack(
children: [
AnimatedBuilder(
animation: controller,
builder: (context, _) => Offstage(
offstage: selected,
child: RunsList(controller: controller, onSelected: _select),
),
),
if (selected) RunDetailView(controller: controller, onBack: _back),
],
);
}
}
@@ -0,0 +1,116 @@
import 'dart:convert';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
/// One labelled value in the run detail's metrics block.
typedef DetailMetric = ({String label, String value});
/// One recorded visit in the run detail's timeline.
typedef DetailVisit = ({String title, String subtitle});
/// The run's primary label: the stored title, else the pipeline name, and only
/// then the numeric identity.
String detailTitle(JsonMap run) {
final identity = runIdentity(run['title'], run['name']);
return identity.label.trim().isEmpty ? 'Run ${run['id']}' : identity.label;
}
String detailPipeline(JsonMap run) {
final name = '${run['name'] ?? ''}'.trim();
return name.isEmpty ? 'unavailable' : name;
}
/// The original prompt exactly as the server stored it; never trimmed or
/// replaced by another field.
String? detailPrompt(JsonMap run) {
final input = run['input'];
return input is Map && input['prompt'] is String
? input['prompt'] as String
: null;
}
/// Nested input/output shown as formatted, selectable JSON.
String detailJson(dynamic value) =>
const JsonEncoder.withIndent(' ').convert(value);
bool detailEmpty(dynamic value) => value is! Map || value.isEmpty;
/// Reported run metrics. A present zero with a reporting stage count is a real
/// zero; a zero without that evidence is unavailable, never a measured zero.
List<DetailMetric> detailUsageMetrics(dynamic raw) {
if (raw is! Map || raw.isEmpty) return const [];
final usage = Map<String, dynamic>.from(raw);
final stages = _int(usage['stages']);
final tokenStages = _int(usage['tokens_known_stages']) ?? 0;
final costStages = _int(usage['cost_known_stages']) ?? 0;
final totalTokens = _int(usage['tokens_total']);
final splitKnown = usage['split_known'] == true && tokenStages > 0;
final rows = <DetailMetric>[
if (stages != null) (label: 'Stages', value: '$stages'),
(
label: 'Total tokens',
value: tokenStages == 0 || totalTokens == null
? 'Unavailable'
: '$totalTokens',
),
(
label: 'Input tokens',
value: splitKnown ? '${_int(usage['tokens_in']) ?? 0}' : 'Unavailable',
),
(
label: 'Output tokens',
value: splitKnown ? '${_int(usage['tokens_out']) ?? 0}' : 'Unavailable',
),
(
label: 'Reported cost',
// cost_usd is omitted by the server when zero, so a known stage count
// makes an absent value a real $0.000000 rather than an unknown cost.
value: costStages == 0
? 'Unavailable'
: '\$${((usage['cost_usd'] as num?) ?? 0).toStringAsFixed(6)}',
),
];
if (stages != null && tokenStages < stages) {
rows.add((
label: 'Token reporting',
value: '$tokenStages of $stages stages',
));
}
if (stages != null && costStages < stages) {
rows.add((label: 'Cost reporting', value: '$costStages of $stages stages'));
}
return rows;
}
/// Every recorded visit with its server sequence, in recorded order.
List<DetailVisit> detailTimeline(dynamic steps) {
if (steps is! List) return const [];
return [
for (final step in steps.whereType<Map>())
(
title:
'${_text(step['stage'], 'Stage unavailable')} · visit '
'${step['sequence'] is num ? (step['sequence'] as num).toInt() : 'unavailable'}',
subtitle: _visitSubtitle(step),
),
];
}
String _visitSubtitle(Map step) {
final status = _text(step['status'], 'Status unavailable');
final outcome = '${step['outcome'] ?? ''}'.trim();
final target = '${step['target'] ?? ''}'.trim();
return [
status,
if (outcome.isNotEmpty) outcome,
if (target.isNotEmpty) '→ $target',
].join(' · ');
}
String _text(dynamic value, String fallback) {
final text = '${value ?? ''}'.trim();
return text.isEmpty ? fallback : text;
}
int? _int(dynamic value) => value is num ? value.toInt() : null;
@@ -0,0 +1,203 @@
import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Cupertino controls. It has no Material
/// ancestor: sections use native Cupertino expansion tiles and grouped list
/// sections, and copy feedback is an inline live-region status.
Widget buildCupertinoRunDetail({
required BuildContext context,
required JsonMap run,
required bool detailLoading,
required String? error,
required bool copying,
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
}) {
final theme = CupertinoTheme.of(context);
final prompt = detailPrompt(run);
final visits = detailTimeline(run['steps']);
final metrics = detailUsageMetrics(run['usage']);
return ListView(
key: ValueKey<String>('run-detail-${run['id']}'),
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Row(
children: [
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onBack,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(CupertinoIcons.back),
const SizedBox(width: 4),
const Text('Back'),
],
),
),
const Spacer(),
if (copying) const CupertinoActivityIndicator(),
],
),
),
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
detailTitle(run),
style: theme.textTheme.navLargeTitleTextStyle,
),
const SizedBox(height: 4),
Text(runStatusLabel(run)),
Text('Run ${run['id']} · Pipeline ${detailPipeline(run)}'),
],
),
),
if (detailLoading) const _CupertinoNotice('Refreshing run details…'),
if (error != null) _CupertinoNotice(error),
if (prompt != null)
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 16, 16, 0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
spacing: 8,
runSpacing: 4,
children: [
Text(
'Original prompt',
style: theme.textTheme.navTitleTextStyle,
),
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: copying ? null : onCopy,
child: const Text('Copy prompt'),
),
],
),
_CupertinoSelectableText(prompt),
if (copyStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Semantics(liveRegion: true, child: Text(copyStatus)),
),
],
),
),
_fieldSection('Input', run['input'], 'No input recorded.'),
_fieldSection('Output', run['output'], 'No output recorded.'),
CupertinoListSection.insetGrouped(
header: const Text('Timeline'),
children: [
if (visits.isEmpty)
const CupertinoListTile(title: Text('No visits recorded.'))
else
for (final visit in visits)
CupertinoListTile(
leading: const Icon(CupertinoIcons.circle),
title: Text(visit.title),
subtitle: Text(visit.subtitle),
),
],
),
CupertinoListSection.insetGrouped(
children: [
CupertinoExpansionTile(
title: const Text('Metrics'),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (metrics.isEmpty)
const Text('No reported usage.')
else
for (final metric in metrics)
CupertinoListTile(
title: Text(metric.label),
subtitle: Text(metric.value),
),
],
),
),
),
],
),
],
);
}
Widget _fieldSection(String title, dynamic value, String empty) {
final text = detailEmpty(value) ? empty : detailJson(value);
return CupertinoListSection.insetGrouped(
children: [
CupertinoExpansionTile(
title: Text(title),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 0, 16, 16),
child: _CupertinoSelectableText(text),
),
),
],
);
}
class _CupertinoNotice extends StatelessWidget {
const _CupertinoNotice(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Semantics(liveRegion: true, child: Text(text)),
);
}
/// A read-only Cupertino text control: plain, selectable text without a
/// Material dependency, while keeping native selection and copy affordances.
class _CupertinoSelectableText extends StatefulWidget {
const _CupertinoSelectableText(this.text);
final String text;
@override
State<_CupertinoSelectableText> createState() =>
_CupertinoSelectableTextState();
}
class _CupertinoSelectableTextState extends State<_CupertinoSelectableText> {
late final TextEditingController _controller = TextEditingController(
text: widget.text,
);
@override
void didUpdateWidget(_CupertinoSelectableText oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text) _controller.text = widget.text;
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => CupertinoTextField(
controller: _controller,
readOnly: true,
maxLines: null,
padding: EdgeInsets.zero,
decoration: const BoxDecoration(),
style: CupertinoTheme.of(context).textTheme.textStyle,
);
}
@@ -0,0 +1,126 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/run_models.dart';
import 'run_detail_content.dart';
/// The runs detail with standard Material controls.
Widget buildMaterialRunDetail({
required BuildContext context,
required JsonMap run,
required bool detailLoading,
required String? error,
required bool copying,
required String? copyStatus,
required VoidCallback onBack,
required VoidCallback onCopy,
}) {
final theme = Theme.of(context);
final prompt = detailPrompt(run);
final visits = detailTimeline(run['steps']);
final metrics = detailUsageMetrics(run['usage']);
return ListView(
key: ValueKey<String>('run-detail-${run['id']}'),
padding: const EdgeInsets.all(16),
children: [
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton.icon(
onPressed: onBack,
icon: const Icon(Icons.arrow_back),
label: const Text('Back to list'),
),
),
Text(detailTitle(run), style: theme.textTheme.headlineSmall),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Chip(label: Text(runStatusLabel(run))),
Text('Run ${run['id']}'),
Text('Pipeline ${detailPipeline(run)}'),
],
),
if (detailLoading) const _Notice('Refreshing run details…'),
if (error != null) _Notice(error),
if (prompt != null) ...[
const SizedBox(height: 12),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Text(
'Original prompt',
style: theme.textTheme.titleMedium,
),
),
IconButton(
tooltip: 'Copy prompt',
onPressed: copying ? null : onCopy,
icon: const Icon(Icons.copy),
),
],
),
SelectableText(prompt),
if (copyStatus != null)
Padding(
padding: const EdgeInsets.only(top: 4),
child: Semantics(liveRegion: true, child: Text(copyStatus)),
),
],
_fieldSection('Input', run['input'], 'No input recorded.'),
_fieldSection('Output', run['output'], 'No output recorded.'),
Text('Timeline', style: theme.textTheme.titleLarge),
if (visits.isEmpty)
const Text('No visits recorded.')
else
...visits.map(
(visit) => ListTile(
leading: const Icon(Icons.circle_outlined),
title: Text(visit.title),
subtitle: Text(visit.subtitle),
),
),
ExpansionTile(
title: const Text('Metrics'),
children: [
if (metrics.isEmpty)
const Padding(
padding: EdgeInsets.all(16),
child: Text('No reported usage.'),
)
else
...metrics.map(
(metric) => ListTile(
title: Text(metric.label),
subtitle: Text(metric.value),
),
),
],
),
],
);
}
Widget _fieldSection(String title, dynamic value, String empty) {
final text = detailEmpty(value) ? empty : detailJson(value);
return ExpansionTile(
title: Text(title),
children: [
Padding(padding: const EdgeInsets.all(16), child: SelectableText(text)),
],
);
}
class _Notice extends StatelessWidget {
const _Notice(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Semantics(liveRegion: true, child: Text(text)),
);
}
@@ -0,0 +1,124 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/adaptive/host.dart';
import 'run_detail_content.dart';
import 'run_detail_cupertino.dart';
import 'run_detail_material.dart';
import 'runs_controller.dart';
class RunDetailView extends StatefulWidget {
const RunDetailView({
super.key,
required this.controller,
required this.onBack,
});
final RunsController controller;
final VoidCallback onBack;
@override
State<RunDetailView> createState() => _RunDetailViewState();
}
class _RunDetailViewState extends State<RunDetailView> {
bool _copying = false;
String? _copyStatus;
@override
Widget build(BuildContext context) => AnimatedBuilder(
animation: widget.controller,
builder: (context, _) {
final cupertino = usesCupertinoHost(context);
final run = widget.controller.detail;
if (run == null) return _placeholder(context, cupertino: cupertino);
final prompt = detailPrompt(run);
return cupertino
? buildCupertinoRunDetail(
context: context,
run: run,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: true),
)
: buildMaterialRunDetail(
context: context,
run: run,
detailLoading: widget.controller.detailLoading,
error: widget.controller.error,
copying: _copying,
copyStatus: _copyStatus,
onBack: widget.onBack,
onCopy: () => _copyPrompt(prompt ?? '', cupertino: false),
);
},
);
Widget _placeholder(BuildContext context, {required bool cupertino}) {
final loading = widget.controller.detailLoading;
final message = loading
? 'Loading run details…'
: widget.controller.error ?? 'Run details unavailable.';
// Back stays available while the detail is pending as well as after a
// failure, so a slow or refused request can never trap the destination.
return Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (loading) ...[
if (cupertino)
const CupertinoActivityIndicator()
else
const CircularProgressIndicator(),
const SizedBox(height: 12),
],
Padding(
padding: const EdgeInsets.symmetric(horizontal: 24),
child: Text(message, textAlign: TextAlign.center),
),
const SizedBox(height: 12),
if (cupertino)
CupertinoButton(
onPressed: widget.onBack,
child: const Text('Back to list'),
)
else
FilledButton(
onPressed: widget.onBack,
child: const Text('Back to list'),
),
],
),
);
}
/// Copies the stored prompt byte-for-byte. A refusal is surfaced, never
/// replaced by copying a title or the formatted detail.
Future<void> _copyPrompt(String prompt, {required bool cupertino}) async {
if (_copying) return;
setState(() => _copying = true);
String message;
try {
await Clipboard.setData(ClipboardData(text: prompt));
message = 'Prompt copied to clipboard.';
} catch (_) {
message = 'Could not copy prompt to clipboard.';
}
if (!mounted) return;
final scaffold = cupertino ? null : Scaffold.maybeOf(context);
final inline = cupertino || scaffold == null;
setState(() {
_copying = false;
_copyStatus = inline ? message : null;
});
if (!cupertino && scaffold != null) {
ScaffoldMessenger.maybeOf(
context,
)?.showSnackBar(SnackBar(content: Text(message)));
}
}
}
@@ -0,0 +1,270 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../domain/run_events.dart';
import '../domain/run_models.dart';
class RunsController extends ChangeNotifier {
RunsController(this.repository);
final RunsRepository repository;
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> runs = [];
JsonMap? detail, usage;
String? error;
bool loading = false, detailLoading = false;
String query = '',
sort = 'newest_first',
scheduled = 'any',
timeRange = 'any_time';
final Set<String> statuses = {};
int? pipelineId;
// List and detail requests advance independent generations so neither can
// make the other's in-flight reply stale.
int _listGeneration = 0, _detailGeneration = 0;
num? _selectedId;
Timer? _detailRefresh;
bool _listResyncing = false, _listAgain = false;
bool _detailRefreshing = false, _detailAgain = false;
bool _disposed = false;
num? get selectedRunId => _selectedId;
void listen(Stream<JsonMap> frames) {
_subscription?.cancel();
_subscription = frames
.where((f) => f['type'] == 'run_event')
.listen(_event);
}
Future<void> load([int? initialId]) async {
final token = ++_listGeneration;
_listAgain = false;
loading = true;
error = null;
notifyListeners();
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
usage = result.usage;
} catch (e) {
if (!_listOwned(token)) return;
error = '$e';
}
if (!_listOwned(token)) return;
loading = false;
notifyListeners();
// A run event may have arrived while the list request was in flight; one
// resync after it keeps the pushed state without dropping the event.
_resyncAgainIfNeeded();
if (initialId != null) await select(initialId);
}
/// Re-reads the list and the open detail after the socket was replaced.
///
/// The selection is kept, so a reconnect refreshes in place instead of
/// discarding the detail the operator had open.
Future<void> resync() async {
final selected = _selectedId;
await load();
if (selected != null && _selectedId == selected) await select(selected);
}
Future<void> select(num id) async {
final token = ++_detailGeneration;
_cancelDetailRefresh();
// Keep a same-run detail while it refreshes, but never present the previous
// run as if it were the newly selected one.
if (_selectedId != id) detail = null;
_selectedId = id;
detailLoading = true;
error = null;
notifyListeners();
try {
final value = await repository.getRun(id);
if (!_detailOwned(id, token)) return;
detail = value;
} catch (e) {
if (!_detailOwned(id, token)) return;
error = '$e';
}
if (!_detailOwned(id, token)) return;
detailLoading = false;
notifyListeners();
}
void back() {
++_detailGeneration;
_cancelDetailRefresh();
_selectedId = null;
detail = null;
detailLoading = false;
error = null;
notifyListeners();
}
void setQuery(String value) {
query = value;
notifyListeners();
}
void setStatus(String? value) {
if (value == null) {
statuses.clear();
} else if (!statuses.add(value)) {
statuses.remove(value);
}
notifyListeners();
}
void setPipeline(int? value) {
pipelineId = value;
notifyListeners();
}
void setScheduled(String value) {
scheduled = value;
notifyListeners();
}
void setSort(String value) {
sort = value;
notifyListeners();
}
void _event(JsonMap frame) {
final folded = foldRunEvent(runs, frame);
runs = folded.runs;
if (detail?['id'] == frame['run_id']) {
detail = foldRunEventDetail(detail, frame);
}
if (frame['run_id'] == null || folded.needsResync) {
_scheduleListRefresh();
}
final selected = _selectedId;
if (selected != null &&
frame['run_id'] == selected &&
(folded.needsResync || runDetailNeedsFullSync(frame))) {
_scheduleDetailRefresh(selected);
}
notifyListeners();
}
void _scheduleListRefresh() {
if (_disposed) return;
if (_listResyncing || loading) {
_listAgain = true;
return;
}
_listResyncing = true;
loading = true;
notifyListeners();
unawaited(_reloadList());
}
Future<void> _reloadList() async {
final token = ++_listGeneration;
_listAgain = false;
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
runs = result.runs;
usage = result.usage;
error = null;
} catch (e) {
if (_listOwned(token)) error = '$e';
} finally {
_listResyncing = false;
if (_listOwned(token)) {
loading = false;
notifyListeners();
}
// A followup may have been requested while this (possibly superseded)
// request was still the one marked in flight.
_resyncAgainIfNeeded();
}
}
void _resyncAgainIfNeeded() {
if (_disposed || !_listAgain) return;
_listAgain = false;
_scheduleListRefresh();
}
void _scheduleDetailRefresh(num id) {
if (_disposed || _selectedId != id) return;
if (_detailRefreshing) {
_detailAgain = true;
return;
}
_detailRefresh?.cancel();
_detailRefresh = Timer(
const Duration(milliseconds: 150),
() => _refreshDetail(id, _detailGeneration),
);
}
Future<void> _refreshDetail(num id, int token) async {
_detailRefresh = null;
if (!_detailOwned(id, token)) return;
_detailRefreshing = true;
try {
final value = await repository.getRun(id);
if (_detailOwned(id, token)) {
detail = value;
notifyListeners();
}
} catch (e) {
if (_detailOwned(id, token)) {
error = '$e';
notifyListeners();
}
} finally {
if (_detailOwned(id, token)) {
_detailRefreshing = false;
if (_detailAgain) {
_detailAgain = false;
unawaited(_refreshDetail(id, token));
}
}
}
}
void _cancelDetailRefresh() {
_detailRefresh?.cancel();
_detailRefresh = null;
_detailAgain = false;
_detailRefreshing = false;
}
bool _listOwned(int token) => !_disposed && token == _listGeneration;
bool _detailOwned(num id, int token) =>
!_disposed && token == _detailGeneration && _selectedId == id;
List<JsonMap> get visibleRuns => sortRuns(
filterRuns(
runs,
statuses: statuses,
pipelineId: pipelineId,
scheduled: scheduled,
timeRange: timeRange,
)
.where(
(r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains(
query.toLowerCase(),
),
)
.toList(),
sort: sort,
);
@override
void dispose() {
_disposed = true;
_subscription?.cancel();
_detailRefresh?.cancel();
super.dispose();
}
}
+243
View File
@@ -0,0 +1,243 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../domain/run_models.dart';
import 'runs_controller.dart';
class RunsList extends StatelessWidget {
const RunsList({
super.key,
required this.controller,
required this.onSelected,
});
final RunsController controller;
final ValueChanged<num> onSelected;
@override
Widget build(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
return Center(
child: usesCupertinoHost(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
if (controller.error != null && controller.runs.isEmpty) {
return _emptyError(context);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (controller.usage != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text('Usage: ${controller.usage}'),
),
if (controller.error != null) _inlineError(context),
Padding(
padding: const EdgeInsets.all(16),
child: usesCupertinoHost(context)
? CupertinoSearchTextField(
placeholder: 'Filter runs',
onChanged: controller.setQuery,
)
: TextField(
decoration: const InputDecoration(
labelText: 'Filter runs',
prefixIcon: Icon(Icons.search),
),
onChanged: controller.setQuery,
),
),
_selectors(context),
Expanded(
child: controller.visibleRuns.isEmpty
? const Center(child: Text('No runs found.'))
: ListView.builder(
itemCount: controller.visibleRuns.length,
itemBuilder: (context, index) =>
_runTile(context, controller.visibleRuns[index]),
),
),
],
);
}
Widget _emptyError(BuildContext context) => Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(controller.error!),
const SizedBox(height: 8),
usesCupertinoHost(context)
? CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
)
: FilledButton(
onPressed: controller.load,
child: const Text('Retry'),
),
],
),
);
Widget _inlineError(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Row(
children: [
Expanded(child: Text(controller.error!)),
if (usesCupertinoHost(context))
CupertinoButton(
onPressed: controller.load,
child: const Text('Retry'),
)
else
TextButton(onPressed: controller.load, child: const Text('Retry')),
],
),
);
Widget _selectors(BuildContext context) {
if (usesCupertinoHost(context)) {
return Wrap(
spacing: 8,
children: [
CupertinoButton(
onPressed: () => _choose(
context,
'Sort runs',
_sorts,
controller.sort,
controller.setSort,
),
child: Text('Sort: ${_sortLabel(controller.sort)}'),
),
CupertinoButton(
onPressed: () => _choose(
context,
'Schedule',
_schedules,
controller.scheduled,
controller.setScheduled,
),
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
),
for (final status in _statuses)
CupertinoButton(
onPressed: () => controller.setStatus(status),
child: Text(
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
),
),
],
);
}
return Wrap(
spacing: 8,
children: [
DropdownButton<String>(
value: controller.sort,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setSort(v);
},
items: _sorts
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
DropdownButton<String>(
value: controller.scheduled,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setScheduled(v);
},
items: _schedules
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
for (final status in _statuses)
FilterChip(
label: Text(_title(status)),
selected: controller.statuses.contains(status),
onSelected: (_) => controller.setStatus(status),
),
],
);
}
Future<void> _choose(
BuildContext context,
String title,
List<(String, String)> values,
String selected,
ValueChanged<String> onSelected,
) async {
final value = await showCupertinoModalPopup<String>(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text(title),
actions: [
for (final option in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, option.$1),
child: Text(option.$2),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (value != null && value != selected) onSelected(value);
}
Widget _runTile(BuildContext context, JsonMap run) {
final identity = runIdentity(run['title'], run['name']);
final id = run['id'];
final title = identity.label.isEmpty ? 'Run $id' : identity.label;
final subtitle =
'${run['name'] ?? 'Pipeline unavailable'} · ${run['created_at'] ?? 'Time unavailable'}${run['scheduled'] == true ? ' · Scheduled' : ''}';
if (usesCupertinoHost(context)) {
return CupertinoListTile(
title: Text(title),
subtitle: Text(subtitle),
additionalInfo: Text(runStatusLabel(run)),
trailing: const CupertinoListTileChevron(),
onTap: id is num ? () => onSelected(id) : null,
);
}
return ListTile(
title: Text(title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [Text(subtitle), Text(runStatusLabel(run))],
),
trailing: const Icon(Icons.chevron_right),
onTap: id is num ? () => onSelected(id) : null,
);
}
}
const _sorts = [
('newest_first', 'Newest'),
('oldest_first', 'Oldest'),
('pipeline_name', 'Pipeline'),
('status', 'Status'),
];
const _schedules = [
('any', 'Any schedule'),
('scheduled', 'Scheduled'),
('unscheduled', 'Unscheduled'),
];
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
String _sortLabel(String value) =>
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
String _scheduleLabel(String value) => _schedules
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
.$2;
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';