From 266916f92a8f0446e58a7b60920ef266e450c8a5 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sat, 31 Oct 2026 22:19:36 +0000 Subject: [PATCH] Runs: multi-select delete, run sizes and Largest-first sort - Select mode (bar Select or long-press): per-row checkboxes, per-day Select all/Deselect all over finished runs only, "N selected" with the selection size, Delete and Done. Active runs get a disabled checkbox whose semantics give the reason. - Native destructive confirmation, then delete_runs {run_ids} (batched by 1000); the nested runs_deleted reply removes deleted rows and reports "Deleted N runs, freed X" plus refusals verbatim. runs_removed pushes remove rows and close an open detail; a deleted open run closes too. Delete run in the row and detail menus. - size_bytes shown compactly in rows (0/absent = unknown, nothing shown), updated from run_event frames that carry it; Largest first sort (flat, unknowns last); the sort choice persists. - Shared AppListRow gains selectionControl and onLongPress. - Browser probe tool/runs_delete_probe.mjs; fixture server implements delete_runs/runs_removed. --- .../runs/actions/delete_runs_action.dart | 41 +++ .../runs/actions/delete_runs_dialog.dart | 154 ++++++++++ .../features/runs/data/runs_repository.dart | 47 +++ .../features/runs/data/runs_sort_store.dart | 56 ++++ .../features/runs/domain/run_deletion.dart | 180 +++++++++++ app/lib/features/runs/domain/run_events.dart | 2 + app/lib/features/runs/domain/run_models.dart | 14 + app/lib/features/runs/screen.dart | 13 +- app/lib/features/runs/ui/run_detail_view.dart | 1 + app/lib/features/runs/ui/run_list_row.dart | 147 +++++++++ app/lib/features/runs/ui/run_more_menu.dart | 38 ++- app/lib/features/runs/ui/runs_controller.dart | 88 +++++- .../features/runs/ui/runs_filter_options.dart | 5 + app/lib/features/runs/ui/runs_list.dart | 195 +++++------- app/lib/features/runs/ui/runs_selection.dart | 85 ++++++ .../features/runs/ui/runs_selection_bar.dart | 226 ++++++++++++++ app/lib/ui/layout/app_list_row.dart | 35 ++- app/notes/runs-delete-size.md | 25 ++ .../runs/domain/run_deletion_test.dart | 168 ++++++++++ .../features/runs/ui/runs_delete_test.dart | 288 ++++++++++++++++++ app/tool/runs_delete_probe.mjs | 229 ++++++++++++++ app/tool/runs_probe_server.mjs | 33 +- 22 files changed, 1928 insertions(+), 142 deletions(-) create mode 100644 app/lib/features/runs/actions/delete_runs_action.dart create mode 100644 app/lib/features/runs/actions/delete_runs_dialog.dart create mode 100644 app/lib/features/runs/data/runs_sort_store.dart create mode 100644 app/lib/features/runs/domain/run_deletion.dart create mode 100644 app/lib/features/runs/ui/run_list_row.dart create mode 100644 app/lib/features/runs/ui/runs_selection.dart create mode 100644 app/lib/features/runs/ui/runs_selection_bar.dart create mode 100644 app/notes/runs-delete-size.md create mode 100644 app/test/features/runs/domain/run_deletion_test.dart create mode 100644 app/test/features/runs/ui/runs_delete_test.dart create mode 100644 app/tool/runs_delete_probe.mjs diff --git a/app/lib/features/runs/actions/delete_runs_action.dart b/app/lib/features/runs/actions/delete_runs_action.dart new file mode 100644 index 00000000..aa3685d5 --- /dev/null +++ b/app/lib/features/runs/actions/delete_runs_action.dart @@ -0,0 +1,41 @@ +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../data/runs_repository.dart'; +import '../domain/run_deletion.dart'; +import 'delete_runs_dialog.dart'; + +/// Confirms and deletes the finished runs among [runs]. +/// +/// Active runs are left out; nothing is sent unless the operator confirms. A +/// transport or server error stays in the open prompt. The server's reply, +/// including any refusals, goes to [onDeleted] exactly as received. +Future confirmDeleteRuns( + BuildContext context, { + required Iterable runs, + required ApiGateway gateway, + required ValueChanged onDeleted, + bool? cupertino, +}) { + final deletable = runs.where(runIsDeletable).toList(); + final ids = deletableRunIds(deletable); + if (ids.isEmpty) return Future.value(false); + return showDeleteRunsPrompt( + context: context, + count: ids.length, + size: runsSizeLabel(deletable), + cupertino: cupertino ?? usesCupertinoHost(context), + onSubmit: () async { + try { + onDeleted(await RunsRepository(gateway).deleteRuns(ids)); + return null; + } catch (error) { + final message = '$error'.trim(); + return message.isEmpty + ? 'The server did not delete the runs.' + : message; + } + }, + ); +} diff --git a/app/lib/features/runs/actions/delete_runs_dialog.dart b/app/lib/features/runs/actions/delete_runs_dialog.dart new file mode 100644 index 00000000..ef28ee3d --- /dev/null +++ b/app/lib/features/runs/actions/delete_runs_dialog.dart @@ -0,0 +1,154 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../domain/run_deletion.dart'; + +const deleteRunsConfirmKey = ValueKey('runs.delete.confirm'); +const deleteRunsKeepKey = ValueKey('runs.delete.keep'); +const deleteRunsErrorKey = ValueKey('runs.delete.error'); + +/// Sends the confirmed deletion. Returns null once the server replied, or the +/// failure to show in the still-open prompt. +typedef DeleteRunsSubmit = Future Function(); + +/// Opens the native destructive confirmation for deleting [count] runs. +/// +/// Nothing is sent until Delete is pressed; Cancel only closes the prompt. +/// Resolves true when the server answered the deletion. +Future showDeleteRunsPrompt({ + required BuildContext context, + required int count, + required String? size, + required bool cupertino, + required DeleteRunsSubmit onSubmit, +}) async { + final prompt = _DeleteRunsPrompt( + count: count, + size: size, + cupertino: cupertino, + onSubmit: onSubmit, + ); + final result = cupertino + ? await showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ) + : await showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + return result ?? false; +} + +class _DeleteRunsPrompt extends StatefulWidget { + const _DeleteRunsPrompt({ + required this.count, + required this.size, + required this.cupertino, + required this.onSubmit, + }); + + final int count; + final String? size; + final bool cupertino; + final DeleteRunsSubmit onSubmit; + + @override + State<_DeleteRunsPrompt> createState() => _DeleteRunsPromptState(); +} + +class _DeleteRunsPromptState extends State<_DeleteRunsPrompt> { + bool _sending = false; + String? _error; + + Future _confirm() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final error = await widget.onSubmit(); + if (!mounted) return; + if (error == null) { + Navigator.of(context).pop(true); + return; + } + setState(() { + _sending = false; + _error = error; + }); + } + + void _keep() { + if (!_sending) Navigator.of(context).pop(false); + } + + @override + Widget build(BuildContext context) => PopScope( + canPop: !_sending, + child: widget.cupertino ? _cupertinoDialog(context) : _material(context), + ); + + Widget _material(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return AlertDialog( + scrollable: true, + title: Text(deleteRunsTitle(widget.count)), + content: _body(TextStyle(color: scheme.error)), + actions: [ + TextButton( + key: deleteRunsKeepKey, + onPressed: _sending ? null : _keep, + child: const Text('Cancel'), + ), + FilledButton( + key: deleteRunsConfirmKey, + style: FilledButton.styleFrom( + backgroundColor: scheme.error, + foregroundColor: scheme.onError, + ), + onPressed: _sending ? null : _confirm, + child: Text(_sending ? 'Deleting…' : 'Delete'), + ), + ], + ); + } + + Widget _cupertinoDialog(BuildContext context) => CupertinoAlertDialog( + title: Text(deleteRunsTitle(widget.count)), + content: _body( + TextStyle(color: CupertinoColors.systemRed.resolveFrom(context)), + ), + actions: [ + CupertinoDialogAction( + key: deleteRunsKeepKey, + onPressed: _sending ? null : _keep, + child: const Text('Cancel'), + ), + CupertinoDialogAction( + key: deleteRunsConfirmKey, + isDestructiveAction: true, + onPressed: _sending ? null : _confirm, + child: Text(_sending ? 'Deleting…' : 'Delete'), + ), + ], + ); + + Widget _body(TextStyle errorStyle) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(deleteRunsMessage(widget.count, size: widget.size)), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Semantics( + liveRegion: true, + child: Text(error, key: deleteRunsErrorKey, style: errorStyle), + ), + ), + ], + ); +} diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart index a9430e03..8dfe59f9 100644 --- a/app/lib/features/runs/data/runs_repository.dart +++ b/app/lib/features/runs/data/runs_repository.dart @@ -1,4 +1,5 @@ import '../../../core/api_gateway.dart'; +import '../domain/run_deletion.dart'; import '../domain/run_models.dart'; /// Protocol failure kept separate from transport errors; server error envelopes @@ -10,6 +11,9 @@ class RunsRepositoryException implements Exception { String toString() => message; } +/// The most run ids one `delete_runs` request may carry. +const deleteRunsBatch = 1000; + /// Run protocol requests over the application's shared gateway. class RunsRepository { RunsRepository(this._gateway); @@ -41,6 +45,49 @@ class RunsRepository { 'run_detail', ); + /// Deletes finished runs and their recorded data. The server answers + /// `runs_deleted` with the ids it removed, the ones it refused (with its + /// reason) and the bytes it freed. + /// + /// The server accepts at most [deleteRunsBatch] ids per request, so a larger + /// selection is sent in consecutive batches and the replies combined. A + /// failing batch stops the rest; batches already answered are kept. + Future deleteRuns(List ids) async { + if (ids.isEmpty) { + throw const RunsRepositoryException('Choose runs to delete.'); + } + RunsDeletion? result; + for (var start = 0; start < ids.length; start += deleteRunsBatch) { + final batch = ids.sublist( + start, + (start + deleteRunsBatch).clamp(0, ids.length), + ); + final RunsDeletion deletion; + try { + final reply = await _gateway.call('delete_runs', {'run_ids': batch}); + deletion = + RunsDeletion.fromReply(reply) ?? + (throw const RunsRepositoryException( + 'The server returned no runs_deleted reply.', + )); + } catch (error) { + if (result == null) rethrow; + // Report what earlier batches deleted, and the rest as not deleted. + return result.merge( + RunsDeletion( + deleted: const [], + refused: [ + for (final id in ids.sublist(start)) + (runId: id, reason: '$error'), + ], + ), + ); + } + result = result == null ? deletion : result.merge(deletion); + } + return result!; + } + /// Reads the exact recorded visit again; it never reruns its stage or tools. /// /// The body is the web client's `repair_session_export` request: the run and diff --git a/app/lib/features/runs/data/runs_sort_store.dart b/app/lib/features/runs/data/runs_sort_store.dart new file mode 100644 index 00000000..a2354f57 --- /dev/null +++ b/app/lib/features/runs/data/runs_sort_store.dart @@ -0,0 +1,56 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +/// The Runs list's persisted sort choice. +const runsSortStorageKey = 'pipelines.next.runsSort.v1'; + +/// The persistence seam for the Runs list's sort. Both directions may fail: a +/// null read means "nothing saved", a false write means "this session only". +abstract interface class RunsSortStore { + Future read(); + + Future write(String value); +} + +/// `shared_preferences` storage under [runsSortStorageKey]. +class SharedPreferencesRunsSortStore implements RunsSortStore { + const SharedPreferencesRunsSortStore(); + + @override + Future read() async { + try { + return (await SharedPreferences.getInstance()).getString( + runsSortStorageKey, + ); + } catch (_) { + return null; + } + } + + @override + Future write(String value) async { + try { + return await (await SharedPreferences.getInstance()).setString( + runsSortStorageKey, + value, + ); + } catch (_) { + return false; + } + } +} + +/// An in-memory store for tests and isolated fixtures. +class MemoryRunsSortStore implements RunsSortStore { + MemoryRunsSortStore([this.value]); + + String? value; + + @override + Future read() async => value; + + @override + Future write(String value) async { + this.value = value; + return true; + } +} diff --git a/app/lib/features/runs/domain/run_deletion.dart b/app/lib/features/runs/domain/run_deletion.dart new file mode 100644 index 00000000..f8c8388b --- /dev/null +++ b/app/lib/features/runs/domain/run_deletion.dart @@ -0,0 +1,180 @@ +import '../../../core/api_gateway.dart'; +import 'run_models.dart' show runStateOf; + +/// Run deletion and disk-size rules. No widgets here. + +/// The states a run can be deleted in: it has finished one way or another. +const _terminalStates = {'succeeded', 'failed', 'canceled', 'interrupted'}; + +/// Why an active run cannot be selected or deleted, for its disabled control. +const runDeleteBlockedReason = + 'Active runs can’t be deleted until they finish.'; + +/// Whether [run] has finished, so its recorded data may be deleted. A run +/// still executing (running, waiting, queued, pending) never qualifies, nor +/// does one whose status the client does not recognise. +bool runIsDeletable(JsonMap run) => + run['id'] is int && + run['executing'] != true && + _terminalStates.contains(runStateOf(run['status'])); + +/// The run's recorded size on disk, or null when it is unknown: older servers +/// omit `size_bytes`, and the server sends 0 for "not measured yet". +int? runSizeBytes(JsonMap run) { + final value = run['size_bytes']; + if (value is int && value > 0) return value; + if (value is num && value > 0 && value.isFinite) return value.round(); + return null; +} + +/// A compact human size: `512 B`, `4.2 KB`, `340 MB`, `1.2 GB`. +/// +/// Binary multiples, one decimal below ten units, whole units above. +String formatByteSize(int bytes) { + if (bytes < 1024) return '$bytes B'; + const units = ['KB', 'MB', 'GB', 'TB', 'PB']; + var value = bytes / 1024; + var unit = 0; + while (value >= 1024 && unit < units.length - 1) { + value /= 1024; + unit++; + } + // Rounding 1023.6 MB up would print "1024 MB"; promote it instead. + if (value >= 1023.5 && unit < units.length - 1) { + value /= 1024; + unit++; + } + final text = value < 9.95 + ? value.toStringAsFixed(1).replaceFirst(RegExp(r'\.0$'), '') + : value.round().toString(); + return '$text ${units[unit]}'; +} + +/// The known total of [runs]' sizes, and whether any size was unknown. +({int bytes, int unknown}) runsSizeTotal(Iterable runs) { + var bytes = 0; + var unknown = 0; + for (final run in runs) { + final size = runSizeBytes(run); + if (size == null) { + unknown++; + } else { + bytes += size; + } + } + return (bytes: bytes, unknown: unknown); +} + +/// The selection's size for its summary, or null when no size is known. +String? runsSizeLabel(Iterable runs) { + final total = runsSizeTotal(runs); + if (total.bytes == 0 && total.unknown > 0) return null; + final size = formatByteSize(total.bytes); + return total.unknown > 0 ? '$size + unknown' : size; +} + +String _runs(int count) => count == 1 ? '1 run' : '$count runs'; + +String deleteRunsTitle(int count) => 'Delete ${_runs(count)}?'; + +/// The confirmation's body. The freed amount is omitted when no size is known. +String deleteRunsMessage(int count, {String? size}) { + final whose = count == 1 ? 'its' : 'their'; + final frees = size == null ? '' : ' and frees about $size'; + return 'This removes $whose artifacts, documents and history$frees. ' + 'This can’t be undone.'; +} + +/// The deleted run ids are drawn from selected runs that can be deleted, in +/// list order. +List deletableRunIds(Iterable runs) => [ + for (final run in runs) + if (runIsDeletable(run)) run['id'] as int, +]; + +/// One run the server kept, in its own words. +typedef RunDeleteRefusal = ({int runId, String reason}); + +/// The server's `runs_deleted` reply. +class RunsDeletion { + const RunsDeletion({ + required this.deleted, + this.refused = const [], + this.freedBytes, + }); + + /// Parses the reply envelope, whose result is nested under `runs_deleted`, + /// or returns null when it is not a deletion reply. + static RunsDeletion? fromReply(JsonMap reply) { + final body = reply['runs_deleted']; + return body is Map ? fromBody(Map.from(body)) : null; + } + + /// Parses the nested `{deleted, refused, freed_bytes}` result. + static RunsDeletion? fromBody(JsonMap reply) { + final deleted = reply['deleted']; + if (deleted is! List) return null; + final refused = reply['refused']; + final freed = reply['freed_bytes']; + return RunsDeletion( + deleted: [for (final id in deleted) ?_intId(id)], + refused: [ + if (refused is List) + for (final entry in refused.whereType()) + if (_intId(entry['run_id']) case final id?) + (runId: id, reason: '${entry['reason'] ?? ''}'.trim()), + ], + freedBytes: freed is num && freed >= 0 ? freed.round() : null, + ); + } + + final List deleted; + final List refused; + final int? freedBytes; + + /// Combines the replies of consecutive batches into one outcome. + RunsDeletion merge(RunsDeletion other) => RunsDeletion( + deleted: [...deleted, ...other.deleted], + refused: [...refused, ...other.refused], + freedBytes: freedBytes == null && other.freedBytes == null + ? null + : (freedBytes ?? 0) + (other.freedBytes ?? 0), + ); + + /// `Deleted 3 runs, freed 1.2 GB.` and one line per refused run. + String get report { + final lines = []; + if (deleted.isNotEmpty || refused.isEmpty) { + final freed = freedBytes == null + ? '' + : ', freed ${formatByteSize(freedBytes!)}'; + lines.add('Deleted ${_runs(deleted.length)}$freed.'); + } + if (refused.isNotEmpty) { + lines.add( + refused.length == 1 + ? '1 run was not deleted:' + : '${refused.length} runs were not deleted:', + ); + for (final refusal in refused) { + final reason = refusal.reason.isEmpty + ? 'refused by the server' + : refusal.reason; + lines.add('Run ${refusal.runId}: $reason'); + } + } + return lines.join('\n'); + } +} + +/// The ids a `runs_removed` broadcast names. +List removedRunIds(JsonMap frame) { + final ids = frame['run_ids']; + return ids is List ? [for (final id in ids) ?_intId(id)] : const []; +} + +int? _intId(dynamic value) { + if (value is int) return value; + if (value is num && value == value.roundToDouble()) return value.toInt(); + return null; +} diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 3ce3bc87..4c1d7a2f 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -112,6 +112,8 @@ JsonMap _mergeRunFields(JsonMap current, JsonMap frame) { for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) { if (!_blank(frame[key])) merged[key] = frame[key]; } + // Snapshot and terminal frames carry the measured size; others omit it. + if (frame['size_bytes'] is num) merged['size_bytes'] = frame['size_bytes']; final oldExport = _positiveInt(current['export_pending_sequence']); if (oldExport > 0 || frame.containsKey('export_pending_sequence')) { merged['export_pending_sequence'] = _blank(frame['status']) diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index b869a6b8..118966b2 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -254,6 +254,20 @@ List sortRuns(List runs, {String sort = 'newest_first'}) { primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); } break; + case 'largest_first': + // Unknown sizes (older servers) sort after every known size. + final sa = a['size_bytes'], sb = b['size_bytes']; + // 0 means "not measured yet" and is unknown, like an absent size. + final an = sa is num && sa > 0 ? sa : null; + final bn = sb is num && sb > 0 ? sb : null; + primary = cmp(an == null ? 1 : 0, bn == null ? 1 : 0); + if (primary == 0 && an != null && bn != null) { + primary = bn.compareTo(an); + } + if (primary == 0) { + primary = cmp(bt ?? -_maxMillis, at ?? -_maxMillis); + } + break; case 'pipeline_name': primary = '${a['name'] ?? ''}'.toLowerCase().compareTo( '${b['name'] ?? ''}'.toLowerCase(), diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index d0784ea7..12e563ec 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -14,6 +14,7 @@ import '../attention/runtime/attention_controller.dart'; import '../attention/runtime/attention_store.dart'; import 'actions/decision_action.dart'; import 'data/runs_repository.dart'; +import 'data/runs_sort_store.dart'; import 'domain/run_decisions.dart'; import 'ui/run_pipeline_link.dart'; import 'ui/run_detail_view.dart'; @@ -45,6 +46,7 @@ class RunsScreen extends StatefulWidget { this.attentionNow, this.notifications, this.attention, + this.sortStore = const SharedPreferencesRunsSortStore(), }); final ApiGateway gateway; @@ -89,6 +91,9 @@ class RunsScreen extends StatefulWidget { /// The app's shared attention controller, mirrored on the shell's Runs tab. final AttentionController? attention; + /// Where the list's sort choice persists; tests inject a memory store. + final RunsSortStore sortStore; + @override State createState() => _RunsScreenState(); } @@ -109,7 +114,13 @@ class _RunsScreenState extends State { @override void initState() { super.initState(); - controller = RunsController(RunsRepository(widget.gateway)); + controller = RunsController( + RunsRepository(widget.gateway), + sortStore: widget.sortStore, + ); + // A deleted open run closes its detail; the route returns to the list. + controller.onOpenRunRemoved = () => + widget.onBack?.call(controller.pipelineId); _reportedPipelineId = widget.initialPipelineId; if (widget.initialPipelineId != null) { controller.clearFilters(); diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index a9920fd3..57bf6b44 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -117,6 +117,7 @@ class _RunDetailViewState extends State { onRunChanged: widget.controller.acceptRunDetail, cupertino: cupertino, onRunOpened: widget.onRunOpened, + onDeleted: widget.controller.applyDeletion, ); if (inShellBar) { return ShellBar( diff --git a/app/lib/features/runs/ui/run_list_row.dart b/app/lib/features/runs/ui/run_list_row.dart new file mode 100644 index 00000000..ec7815b1 --- /dev/null +++ b/app/lib/features/runs/ui/run_list_row.dart @@ -0,0 +1,147 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../../ui/layout/app_list_avatar.dart'; +import '../../../ui/layout/app_list_row.dart'; +import '../../../ui/status/run_status_icon.dart'; +import '../../../ui/text/relative_time.dart'; +import '../domain/run_deletion.dart'; +import '../domain/run_models.dart'; +import 'run_more_menu.dart'; + +/// One run in the list: a status avatar, title/time, and one muted fact +/// line in the app's shared row. Its detail retains the full timestamp, +/// path, and other diagnostics. +/// +/// In the list's select mode ([selecting]) the row leads with a checkbox, a +/// tap toggles it instead of opening the run, and the menu is hidden. Active +/// runs keep a disabled checkbox that says why. +class RunListRow extends StatelessWidget { + const RunListRow({ + super.key, + required this.run, + required this.now, + this.selected = false, + this.divider = true, + this.onTap, + this.gateway, + this.onRunChanged, + this.onRunOpened, + this.onDeleted, + this.selecting = false, + this.checked = false, + this.onToggle, + this.onLongPress, + }); + + final JsonMap run; + final DateTime now; + final bool selected; + + /// False for the last row before a day heading or the end of the list. + final bool divider; + final VoidCallback? onTap; + final ApiGateway? gateway; + final ValueChanged? onRunChanged; + final ValueChanged? onRunOpened; + final ValueChanged? onDeleted; + + /// The list is in select mode; [checked] is this run's selection. + final bool selecting; + final bool checked; + final VoidCallback? onToggle; + + /// Enters select mode from a touch long-press. + final VoidCallback? onLongPress; + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final identity = runIdentity(run['title'], run['name']); + final id = run['id']; + final title = identity.label.isEmpty ? 'Run $id' : identity.label; + final facts = runRowFacts(run, now); + // A run without its own title is named by its pipeline, so the pipeline + // line does not repeat it. + final pipeline = identity.pipeline?.trim(); + // With no stored title, `name` is already the row title; repeating it as + // a subtitle adds no identity. A titled run with an empty name genuinely + // lacks its pipeline, so make that absence explicit. + final pipelineLabel = pipeline == null + ? null + : pipeline.isEmpty + ? 'Pipeline unavailable' + : pipeline; + final scheduled = run['scheduled'] == true; + final bytes = runSizeBytes(run); + final size = bytes == null ? null : formatByteSize(bytes); + final subtitle = [ + ?pipelineLabel, + if (scheduled) 'Scheduled', + ?facts.duration, + ?facts.progress, + ?size, + ].join(' · '); + // A narrow pane keeps the decision facts: the pipeline, and progress + // while executing (duration only when there is no pipeline to show). + final compactSubtitle = [ + ?pipelineLabel, + if (scheduled) 'Scheduled', + if (run['executing'] == true && facts.progress != null) facts.progress!, + if (pipelineLabel == null && facts.duration != null) facts.duration!, + ?size, + ].join(' · '); + final state = runStateOf(run['status']); + return AppListRow( + key: ValueKey('run-row-$id'), + cupertino: cupertino, + selected: selected, + divider: divider, + onTap: selecting ? (runIsDeletable(run) ? onToggle : null) : onTap, + onLongPress: selecting ? null : onLongPress, + selectionControl: selecting ? _checkbox(context, cupertino) : null, + leading: AppListAvatar( + foreground: runStatusColor(state).resolveFrom(context), + child: RunStatusIcon(state: state, label: runStatusLabel(run)), + ), + title: Text(title), + time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now), + subtitle: Text(subtitle), + compactSubtitle: Text(compactSubtitle), + // A narrow list pane beside the open run leaves the row no room for a + // second control; the open run's detail beside it carries the same menu. + menu: + !selecting && + gateway != null && + onRunChanged != null && + showRunMoreMenu(run, deletable: onDeleted != null) + ? RunMoreMenu( + run: run, + gateway: gateway!, + onRunChanged: onRunChanged!, + onRunOpened: onRunOpened, + onDeleted: onDeleted, + cupertino: cupertino, + menuKey: ValueKey('run-list-more-menu-$id'), + ) + : null, + ); + } + + Widget _checkbox(BuildContext context, bool cupertino) { + final id = run['id']; + final enabled = runIsDeletable(run); + final title = runIdentity(run['title'], run['name']).label; + final name = title.isEmpty ? 'run $id' : title; + final changed = enabled ? (_) => onToggle?.call() : null; + final box = cupertino + ? CupertinoCheckbox(value: checked, onChanged: changed) + : Checkbox(value: checked, onChanged: changed); + return Semantics( + label: enabled ? 'Select $name' : 'Select $name. $runDeleteBlockedReason', + child: KeyedSubtree(key: ValueKey('run-select-$id'), child: box), + ); + } +} diff --git a/app/lib/features/runs/ui/run_more_menu.dart b/app/lib/features/runs/ui/run_more_menu.dart index 6cabbca2..77f4e427 100644 --- a/app/lib/features/runs/ui/run_more_menu.dart +++ b/app/lib/features/runs/ui/run_more_menu.dart @@ -4,18 +4,26 @@ import '../../../ui/layout/app_overflow_menu.dart'; import '../../../core/api_gateway.dart'; import '../../schedules/ui/run/schedule_run_action.dart'; +import '../actions/delete_runs_action.dart'; import '../actions/retry_action.dart'; import '../actions/retry_eligibility.dart'; import '../actions/retry_wording.dart'; import '../actions/title_action.dart'; import '../actions/title_wording.dart'; +import '../domain/run_deletion.dart'; import '../domain/run_models.dart' show runIdentity; const runMoreMenuKey = ValueKey('run-more-menu'); +const deleteRunActionKey = ValueKey('run-delete-action'); +const deleteRunActionLabel = 'Delete run'; -/// Whether the run has anything for its more menu. -bool showRunMoreMenu(JsonMap run) => - runTitleId(run) != null || canScheduleRun(run) || _canRetry(run); +/// Whether the run has anything for its more menu. [deletable] says the host +/// can apply a deletion, so a finished run offers Delete run. +bool showRunMoreMenu(JsonMap run, {bool deletable = false}) => + runTitleId(run) != null || + canScheduleRun(run) || + _canRetry(run) || + (deletable && runIsDeletable(run)); /// The run's own name for its action sheet: its title or pipeline, else /// `Run `, as its list row shows it. @@ -26,13 +34,14 @@ String runMoreMenuTitle(JsonMap run) { bool _canRetry(JsonMap run) => retryRunId(run) != null && canRetryRun(run); -enum _RunMoreItem { retry, rename, schedule } +enum _RunMoreItem { retry, rename, schedule, delete } /// Each item keeps the key its standalone button had. Key _keyOf(_RunMoreItem item) => switch (item) { _RunMoreItem.retry => retryActionKey, _RunMoreItem.rename => runTitleActionKey, _RunMoreItem.schedule => scheduleRunActionKey, + _RunMoreItem.delete => deleteRunActionKey, }; /// The run detail's more menu: Retry (failed runs only), Rename and Schedule @@ -47,6 +56,7 @@ class RunMoreMenu extends StatefulWidget { required this.onRunChanged, required this.cupertino, this.onRunOpened, + this.onDeleted, this.menuKey = runMoreMenuKey, }); @@ -58,6 +68,9 @@ class RunMoreMenu extends StatefulWidget { /// Opens the new run an accepted retry names. final ValueChanged? onRunOpened; + /// Applies an answered deletion; without it the menu offers no Delete run. + final ValueChanged? onDeleted; + /// Detail menus retain the shared key; list rows supply a per-run key. final Key menuKey; @@ -73,6 +86,8 @@ class _RunMoreMenuState extends State { if (_canRetry(run)) (_RunMoreItem.retry, retryActionLabel), if (runTitleId(run) != null) (_RunMoreItem.rename, runTitleActionLabel), if (canScheduleRun(run)) (_RunMoreItem.schedule, scheduleRunActionLabel), + if (widget.onDeleted != null && runIsDeletable(run)) + (_RunMoreItem.delete, deleteRunActionLabel), ]; void _pick(BuildContext context, _RunMoreItem item) { @@ -97,6 +112,14 @@ class _RunMoreMenuState extends State { ); case _RunMoreItem.schedule: openScheduleRunEditor(context, run: run, gateway: widget.gateway); + case _RunMoreItem.delete: + confirmDeleteRuns( + context, + runs: [run], + gateway: widget.gateway, + onDeleted: widget.onDeleted!, + cupertino: widget.cupertino, + ); } } @@ -109,7 +132,12 @@ class _RunMoreMenuState extends State { sheetTitle: runMoreMenuTitle(run), actions: [ for (final (item, label) in _items) - AppMenuAction(key: _keyOf(item), value: item, label: label), + AppMenuAction( + key: _keyOf(item), + value: item, + label: label, + destructive: item == _RunMoreItem.delete, + ), ], onSelected: _pick, ); diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 745dd8cb..7c3e5a35 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -2,12 +2,34 @@ import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; +import '../data/runs_sort_store.dart'; +import '../domain/run_deletion.dart'; import '../domain/run_events.dart'; import '../domain/run_models.dart'; +import 'runs_filter_options.dart'; +import 'runs_selection.dart'; class RunsController extends ChangeNotifier { - RunsController(this.repository); + RunsController(this.repository, {this.sortStore}) { + selection.addListener(notifyListeners); + unawaited(_restoreSort()); + } final RunsRepository repository; + + /// Where the sort choice persists; null keeps it for this controller only. + final RunsSortStore? sortStore; + + /// Multi-select for deletion and the last deletion report. + final RunsSelection selection = RunsSelection(); + + /// Called when the open run was deleted (here or by another client) and its + /// detail closed, so the host can return its route to the list. + VoidCallback? onOpenRunRemoved; + + /// Deleted run ids never return: a list read already in flight when the + /// deletion landed must not bring a row back. + final Set _removed = {}; + bool _sortChosen = false; StreamSubscription? _subscription; List runs = []; JsonMap? detail, usage; @@ -40,9 +62,15 @@ class RunsController extends ChangeNotifier { void listen(Stream frames) { _subscription?.cancel(); - _subscription = frames - .where((f) => f['type'] == 'run_event') - .listen(_event); + _subscription = frames.listen((frame) { + switch (frame['type']) { + case 'run_event': + _event(frame); + case 'runs_removed': + // Another client deleted these runs. + removeRuns(removedRunIds(frame)); + } + }); } Future load([int? initialId]) async { @@ -54,7 +82,7 @@ class RunsController extends ChangeNotifier { try { final result = await repository.listRuns(); if (!_listOwned(token)) return; - runs = result.runs; + _setRuns(result.runs); usage = result.usage; } catch (e) { if (!_listOwned(token)) return; @@ -183,8 +211,52 @@ class RunsController extends ChangeNotifier { } void setSort(String value) { + _sortChosen = true; sort = value; notifyListeners(); + unawaited(sortStore?.write(value)); + } + + /// Applies the saved sort unless the operator already chose one. + Future _restoreSort() async { + final saved = await sortStore?.read(); + if (_disposed || _sortChosen || saved == null || saved == sort) return; + if (!runSorts.any((option) => option.$1 == saved)) return; + sort = saved; + notifyListeners(); + } + + void _setRuns(List value) { + runs = _removed.isEmpty + ? value + : value.where((run) => !_removed.contains(run['id'])).toList(); + selection.retain(runs); + } + + /// Drops deleted runs from the list and the selection, and closes the open + /// detail when it showed one of them. + void removeRuns(Iterable ids) { + final gone = ids.toSet(); + if (gone.isEmpty) return; + _removed.addAll(gone); + final before = runs.length; + runs = runs.where((run) => !gone.contains(run['id'])).toList(); + var changed = runs.length != before; + selection.retain(runs); + final open = _selectedId; + if (open != null && gone.contains(open)) { + back(); + onOpenRunRemoved?.call(); + changed = false; // back() already notified. + } + if (changed) notifyListeners(); + } + + /// Applies the server's `runs_deleted` reply: removes what it deleted and + /// records the report (including refusals) for the list. + void applyDeletion(RunsDeletion deletion) { + removeRuns(deletion.deleted); + selection.applied(deletion); } /// Returns every filter to its default, like the browser's `Clear filters`. @@ -197,8 +269,10 @@ class RunsController extends ChangeNotifier { } void _event(JsonMap frame) { + if (_removed.contains(frame['run_id'])) return; final folded = foldRunEvent(runs, frame); runs = folded.runs; + selection.retain(runs); if (detail?['id'] == frame['run_id']) { detail = foldRunEventDetail(detail, frame); } @@ -232,7 +306,7 @@ class RunsController extends ChangeNotifier { try { final result = await repository.listRuns(); if (!_listOwned(token)) return; - runs = result.runs; + _setRuns(result.runs); usage = result.usage; error = null; } catch (e) { @@ -326,6 +400,8 @@ class RunsController extends ChangeNotifier { @override void dispose() { _disposed = true; + selection.removeListener(notifyListeners); + selection.dispose(); _subscription?.cancel(); _detailRefresh?.cancel(); super.dispose(); diff --git a/app/lib/features/runs/ui/runs_filter_options.dart b/app/lib/features/runs/ui/runs_filter_options.dart index 35bea7e0..87a57a8f 100644 --- a/app/lib/features/runs/ui/runs_filter_options.dart +++ b/app/lib/features/runs/ui/runs_filter_options.dart @@ -6,6 +6,7 @@ import 'runs_controller.dart'; const runSorts = [ ('newest_first', 'Newest first'), ('oldest_first', 'Oldest first'), + ('largest_first', 'Largest first'), ('longest_duration', 'Longest duration'), ('shortest_duration', 'Shortest duration'), ('pipeline_name', 'Pipeline name'), @@ -23,6 +24,10 @@ const runTimeRanges = [ ('last_30_days', 'Last 30 days'), ]; +/// Sorts that list runs flat instead of under day headings: an order by +/// size has no meaningful day grouping. +const flatRunSorts = {'largest_first'}; + /// The pipelines the loaded runs belong to, by name then id. List<({int id, String name})> runFilterPipelines(RunsController controller) { final names = {}; diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index d73d5789..67a99479 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -1,6 +1,3 @@ -import '../../../ui/layout/app_list_avatar.dart'; -import '../../../ui/layout/app_list_row.dart'; -import '../../../ui/layout/section_heading.dart'; import '../../../ui/motion/motion.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; @@ -8,19 +5,21 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/host.dart'; -import '../../../ui/status/run_status_icon.dart'; import '../../attention/notify/notification_controller.dart'; import '../../attention/runtime/attention_controller.dart'; import '../../attention/runtime/attention_store.dart'; import '../../attention/ui/needs_you_runs_heading.dart'; -import '../../../ui/text/relative_time.dart'; import '../domain/run_models.dart'; import '../../../shell/shell_bar.dart'; -import 'run_more_menu.dart'; +import 'run_list_row.dart'; import 'runs_controller.dart'; +import 'runs_filter_options.dart'; +import 'runs_selection_bar.dart'; import 'runs_stats_page.dart'; import 'runs_filters.dart'; +export 'run_list_row.dart'; + class RunsList extends StatelessWidget { const RunsList({ super.key, @@ -58,6 +57,30 @@ class RunsList extends StatelessWidget { @override Widget build(BuildContext context) { + // Select mode replaces the bar: `N selected` and its size, Delete, Done. + if (controller.selection.active) { + final bar = runsSelectionBar(context, controller); + if (!ShellBar.available(context)) { + return _ownBar(context, [ + Expanded( + child: Text( + [bar.title, ?bar.subtitle].join(' · '), + key: runsSelectionCountKey, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ...bar.actions, + ]); + } + return ShellBar( + active: active, + title: bar.title, + subtitle: bar.subtitle, + actions: bar.actions, + child: _list(context), + ); + } final actions = [ // The Needs-you bell sits with the other actions, freeing the row. NeedsYouRunsHeading( @@ -73,22 +96,11 @@ class RunsList extends StatelessWidget { ...RunsBarActions( controller, ).build(context, onStats: () => openRunsStats(context, controller)), + if (controller.runs.isNotEmpty) runsSelectAction(context, controller), ]; // Outside the app shell (the list on its own) the actions head the list. if (!ShellBar.available(context)) { - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Padding( - padding: const EdgeInsetsDirectional.fromSTEB(8, 4, 8, 0), - child: Row( - mainAxisAlignment: MainAxisAlignment.end, - children: actions, - ), - ), - Expanded(child: _list(context)), - ], - ); + return _ownBar(context, [const Spacer(), ...actions]); } return ShellBar( active: active, @@ -102,6 +114,17 @@ class RunsList extends StatelessWidget { ); } + Widget _ownBar(BuildContext context, List bar) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 0), + child: Row(children: bar), + ), + Expanded(child: _list(context)), + ], + ); + Widget _list(BuildContext context) { if (controller.loading && controller.runs.isEmpty) { return _state( @@ -119,6 +142,8 @@ class RunsList extends StatelessWidget { // behind the top bar with the runs and start below it at rest. final header = [ if (controller.error != null) _inlineError(context), + if (controller.selection.report != null) + RunsDeleteReport(controller: controller), RunsFilters(controller: controller), ]; if (controller.visibleRuns.isNotEmpty) return _groupedRuns(context, header); @@ -145,11 +170,18 @@ class RunsList extends StatelessWidget { } Widget _groupedRuns(BuildContext context, List header) { - final groups = groupRunsByDay(controller.visibleRuns, DateTime.now()); - final entries = <({String? label, JsonMap? run})>[]; - for (final group in groups) { - entries.add((label: group.label, run: null)); - entries.addAll(group.runs.map((run) => (label: null, run: run))); + final entries = <_Entry>[]; + if (flatRunSorts.contains(controller.sort)) { + // An order by size is one flat list: day headings would split it. + entries.addAll( + controller.visibleRuns.map((run) => (day: null, run: run)), + ); + } else { + final groups = groupRunsByDay(controller.visibleRuns, DateTime.now()); + for (final group in groups) { + entries.add((day: group, run: null)); + entries.addAll(group.runs.map((run) => (day: null, run: run))); + } } // Runs that start while the list is open enter with a short fade. return ArrivalScope( @@ -158,10 +190,7 @@ class RunsList extends StatelessWidget { ); } - Widget _entriesList( - List<({String? label, JsonMap? run})> entries, - List header, - ) { + Widget _entriesList(List<_Entry> entries, List header) { // The default padding is the media padding: the first row starts below // the top bar and the last clears the floating tab bar. return ListView.builder( @@ -169,14 +198,12 @@ class RunsList extends StatelessWidget { itemBuilder: (context, index) { if (index < header.length) return header[index]; final entry = entries[index - header.length]; - if (entry.label case final label?) { + if (entry.day case final day?) { // A day heading reads as a divider between groups of runs. - return Padding( - padding: const EdgeInsets.only(top: 8), - child: Semantics( - header: true, - child: SectionHeading(title: label, minHeight: 32), - ), + return RunsDayHeading( + label: day.label, + runs: day.runs, + controller: controller, ); } // The last run of a day (before the next heading) has no divider. @@ -269,7 +296,14 @@ class RunsList extends StatelessWidget { Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) { final id = run['id']; + final selection = controller.selection; return RunListRow( + selecting: selection.active, + checked: selection.contains(id), + onToggle: () => selection.toggle(run), + // A long-press enters select mode with this run selected. + onLongPress: () => selection.enter(run), + onDeleted: controller.applyDeletion, run: run, divider: divider, selected: id == controller.selectedRunId, @@ -282,93 +316,4 @@ class RunsList extends StatelessWidget { } } -/// One run in the list: a status avatar, title/time, and one muted fact -/// line in the app's shared row. Its detail retains the full timestamp, -/// path, and other diagnostics. -class RunListRow extends StatelessWidget { - const RunListRow({ - super.key, - required this.run, - required this.now, - this.selected = false, - this.divider = true, - this.onTap, - this.gateway, - this.onRunChanged, - this.onRunOpened, - }); - - final JsonMap run; - final DateTime now; - final bool selected; - - /// False for the last row before a day heading or the end of the list. - final bool divider; - final VoidCallback? onTap; - final ApiGateway? gateway; - final ValueChanged? onRunChanged; - final ValueChanged? onRunOpened; - - @override - Widget build(BuildContext context) { - final cupertino = usesCupertinoHost(context); - final identity = runIdentity(run['title'], run['name']); - final id = run['id']; - final title = identity.label.isEmpty ? 'Run $id' : identity.label; - final facts = runRowFacts(run, now); - // A run without its own title is named by its pipeline, so the pipeline - // line does not repeat it. - final pipeline = identity.pipeline?.trim(); - // With no stored title, `name` is already the row title; repeating it as - // a subtitle adds no identity. A titled run with an empty name genuinely - // lacks its pipeline, so make that absence explicit. - final pipelineLabel = pipeline == null - ? null - : pipeline.isEmpty - ? 'Pipeline unavailable' - : pipeline; - final scheduled = run['scheduled'] == true; - final subtitle = [ - ?pipelineLabel, - if (scheduled) 'Scheduled', - ?facts.duration, - ?facts.progress, - ].join(' · '); - // A narrow pane keeps the decision facts: the pipeline, and progress - // while executing (duration only when there is no pipeline to show). - final compactSubtitle = [ - ?pipelineLabel, - if (scheduled) 'Scheduled', - if (run['executing'] == true && facts.progress != null) facts.progress!, - if (pipelineLabel == null && facts.duration != null) facts.duration!, - ].join(' · '); - final state = runStateOf(run['status']); - return AppListRow( - key: ValueKey('run-row-$id'), - cupertino: cupertino, - selected: selected, - divider: divider, - onTap: onTap, - leading: AppListAvatar( - foreground: runStatusColor(state).resolveFrom(context), - child: RunStatusIcon(state: state, label: runStatusLabel(run)), - ), - title: Text(title), - time: formatRelativeTimestamp('${run['created_at'] ?? ''}', now: now), - subtitle: Text(subtitle), - compactSubtitle: Text(compactSubtitle), - // A narrow list pane beside the open run leaves the row no room for a - // second control; the open run's detail beside it carries the same menu. - menu: gateway != null && onRunChanged != null && showRunMoreMenu(run) - ? RunMoreMenu( - run: run, - gateway: gateway!, - onRunChanged: onRunChanged!, - onRunOpened: onRunOpened, - cupertino: cupertino, - menuKey: ValueKey('run-list-more-menu-$id'), - ) - : null, - ); - } -} +typedef _Entry = ({({String label, List runs})? day, JsonMap? run}); diff --git a/app/lib/features/runs/ui/runs_selection.dart b/app/lib/features/runs/ui/runs_selection.dart new file mode 100644 index 00000000..8b1e03a4 --- /dev/null +++ b/app/lib/features/runs/ui/runs_selection.dart @@ -0,0 +1,85 @@ +import 'package:flutter/foundation.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/run_deletion.dart'; + +/// The Runs list's multi-select mode and the last deletion report. +/// +/// Only finished runs can be selected ([runIsDeletable]); the ids are the +/// server's run ids, so a list reload keeps the selection of runs still shown. +class RunsSelection extends ChangeNotifier { + bool _active = false; + final Set _ids = {}; + String? _report; + + bool get active => _active; + Set get ids => Set.unmodifiable(_ids); + int get count => _ids.length; + bool contains(Object? id) => _ids.contains(id); + + /// The last deletion's outcome, until dismissed or replaced. + String? get report => _report; + + void enter([JsonMap? run]) { + _active = true; + if (run != null && runIsDeletable(run)) _ids.add(run['id'] as int); + notifyListeners(); + } + + void exit() { + if (!_active && _ids.isEmpty) return; + _active = false; + _ids.clear(); + notifyListeners(); + } + + void toggle(JsonMap run) { + if (!_active || !runIsDeletable(run)) return; + final id = run['id'] as int; + if (!_ids.remove(id)) _ids.add(id); + notifyListeners(); + } + + /// Whether every deletable run of [runs] (one day) is selected. + bool allSelected(Iterable runs) { + final ids = deletableRunIds(runs); + return ids.isNotEmpty && ids.every(_ids.contains); + } + + /// Selects every finished run of [runs], or deselects them all when they + /// already are. Active runs are never selected. + void toggleAll(Iterable runs) { + if (!_active) return; + final ids = deletableRunIds(runs); + if (ids.isEmpty) return; + if (ids.every(_ids.contains)) { + _ids.removeAll(ids); + } else { + _ids.addAll(ids); + } + notifyListeners(); + } + + /// Drops ids no longer listed (deleted, removed elsewhere, or now active). + void retain(Iterable runs) { + final keep = deletableRunIds(runs).toSet(); + final before = _ids.length; + _ids.retainWhere(keep.contains); + if (_ids.length != before) notifyListeners(); + } + + /// Records a deletion: its ids leave the selection, and the mode ends once + /// nothing (no refused run) remains selected. + void applied(RunsDeletion deletion) { + _ids.removeAll(deletion.deleted); + if (_ids.isEmpty) _active = false; + _report = deletion.report; + notifyListeners(); + } + + void dismissReport() { + if (_report == null) return; + _report = null; + notifyListeners(); + } +} diff --git a/app/lib/features/runs/ui/runs_selection_bar.dart b/app/lib/features/runs/ui/runs_selection_bar.dart new file mode 100644 index 00000000..ecce474b --- /dev/null +++ b/app/lib/features/runs/ui/runs_selection_bar.dart @@ -0,0 +1,226 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../../../ui/layout/section_heading.dart'; +import '../actions/delete_runs_action.dart'; +import '../domain/run_deletion.dart'; +import 'runs_controller.dart'; + +const runsSelectKey = ValueKey('runs.select'); +const runsSelectDoneKey = ValueKey('runs.select.done'); +const runsDeleteSelectedKey = ValueKey('runs.select.delete'); +const runsSelectionCountKey = ValueKey('runs.select.count'); +const runsDeleteReportKey = ValueKey('runs.delete.report'); +const runsDeleteReportDismissKey = ValueKey( + 'runs.delete.report.dismiss', +); + +/// The day heading's Select all / Deselect all toggle key. +ValueKey runsDaySelectKey(String day) => + ValueKey('runs.select.day.$day'); + +/// The Runs bar's `Select` action, entering multi-select. +Widget runsSelectAction(BuildContext context, RunsController controller) { + void enter() => controller.selection.enter(); + if (usesCupertinoHost(context)) { + return Semantics( + button: true, + label: 'Select', + excludeSemantics: true, + onTap: enter, + child: CupertinoButton( + key: runsSelectKey, + padding: EdgeInsets.zero, + minimumSize: const Size.square(kMinInteractiveDimensionCupertino), + onPressed: enter, + child: const Icon(CupertinoIcons.checkmark_circle), + ), + ); + } + return IconButton( + key: runsSelectKey, + tooltip: 'Select', + onPressed: enter, + icon: const Icon(Icons.checklist), + ); +} + +/// What the bar shows in select mode: `N selected` over the selection's size, +/// then Delete and Done. +({String title, String? subtitle, List actions}) runsSelectionBar( + BuildContext context, + RunsController controller, +) { + final selection = controller.selection; + final selected = [ + for (final run in controller.runs) + if (selection.contains(run['id'])) run, + ]; + final count = selected.length; + final size = count == 0 ? null : runsSizeLabel(selected); + final cupertino = usesCupertinoHost(context); + final delete = count == 0 + ? null + : () => confirmDeleteRuns( + context, + runs: selected, + gateway: controller.repository.gateway, + onDeleted: controller.applyDeletion, + cupertino: cupertino, + ); + final deleteLabel = count == 0 + ? 'Delete selected runs' + : 'Delete $count selected ${count == 1 ? 'run' : 'runs'}'; + final List actions; + if (cupertino) { + actions = [ + Semantics( + button: true, + enabled: delete != null, + label: deleteLabel, + excludeSemantics: true, + onTap: delete, + child: CupertinoButton( + key: runsDeleteSelectedKey, + onPressed: delete, + child: Text( + 'Delete', + style: TextStyle( + color: delete == null + ? null + : CupertinoColors.systemRed.resolveFrom(context), + ), + ), + ), + ), + CupertinoButton( + key: runsSelectDoneKey, + onPressed: selection.exit, + child: const Text('Done'), + ), + ]; + } else { + final scheme = Theme.of(context).colorScheme; + actions = [ + Semantics( + label: deleteLabel, + excludeSemantics: true, + onTap: delete, + button: true, + enabled: delete != null, + child: TextButton( + key: runsDeleteSelectedKey, + style: TextButton.styleFrom(foregroundColor: scheme.error), + onPressed: delete, + child: const Text('Delete'), + ), + ), + TextButton( + key: runsSelectDoneKey, + onPressed: selection.exit, + child: const Text('Done'), + ), + ]; + } + return (title: '$count selected', subtitle: size, actions: actions); +} + +/// A day's heading; in select mode it carries that day's Select all / +/// Deselect all toggle, covering only the day's finished runs. +class RunsDayHeading extends StatelessWidget { + const RunsDayHeading({ + super.key, + required this.label, + required this.runs, + required this.controller, + }); + + final String label; + final List runs; + final RunsController controller; + + @override + Widget build(BuildContext context) { + final selection = controller.selection; + final trailing = []; + if (selection.active) { + final any = deletableRunIds(runs).isNotEmpty; + final all = selection.allSelected(runs); + final text = all ? 'Deselect all' : 'Select all'; + final toggle = any ? () => selection.toggleAll(runs) : null; + final key = runsDaySelectKey(label); + trailing.add( + Semantics( + button: true, + enabled: any, + label: any + ? '$text $label' + : '$text $label. No finished runs to select.', + excludeSemantics: true, + onTap: toggle, + child: usesCupertinoHost(context) + ? CupertinoButton( + key: key, + padding: const EdgeInsets.symmetric(horizontal: 8), + minimumSize: const Size(0, kMinInteractiveDimensionCupertino), + onPressed: toggle, + child: Text(text), + ) + : TextButton(key: key, onPressed: toggle, child: Text(text)), + ), + ); + } + return Padding( + padding: const EdgeInsets.only(top: 8), + child: SectionHeading( + title: label, + minHeight: 32, + header: true, + trailing: trailing, + ), + ); + } +} + +/// The last deletion's outcome above the list, until dismissed. +class RunsDeleteReport extends StatelessWidget { + const RunsDeleteReport({super.key, required this.controller}); + + final RunsController controller; + + @override + Widget build(BuildContext context) { + final report = controller.selection.report; + if (report == null) return const SizedBox.shrink(); + final cupertino = usesCupertinoHost(context); + final dismiss = controller.selection.dismissReport; + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(16, 4, 8, 4), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Semantics( + liveRegion: true, + child: Text(report, key: runsDeleteReportKey), + ), + ), + cupertino + ? CupertinoButton( + key: runsDeleteReportDismissKey, + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: dismiss, + child: const Text('Dismiss'), + ) + : TextButton( + key: runsDeleteReportDismissKey, + onPressed: dismiss, + child: const Text('Dismiss'), + ), + ], + ), + ); + } +} diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index 2859e592..86f06f58 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -23,7 +23,9 @@ const appListRowDividerKey = ValueKey('app-list-row-divider'); /// Layout: [leading] (an [AppListAvatar]), then a bold one-line [title] with /// the [time] at its trailing edge, then one muted [subtitle] line (with an /// optional [subtitleLeading] dot/prefix and [subtitleTrailing] mark), then -/// the optional [menu] (an `AppOverflowMenu`). An inset hairline [divider] +/// the optional [menu] (an `AppOverflowMenu`). A row in a multi-select list +/// puts its checkbox in [selectionControl], which leads the row even when it +/// is compact. An inset hairline [divider] /// under the text column separates rows. Nothing has a fixed height: the row /// grows with text scaling and every line ellipsises. /// @@ -43,6 +45,8 @@ class AppListRow extends StatelessWidget { this.subtitleTrailing, this.menu, this.onTap, + this.onLongPress, + this.selectionControl, this.tapKey, this.selected = false, this.emphasized = false, @@ -64,6 +68,12 @@ class AppListRow extends StatelessWidget { final Widget? menu; final VoidCallback? onTap; + /// A touch long-press on the row (for example, entering a select mode). + final VoidCallback? onLongPress; + + /// A checkbox leading the row in a multi-select list; kept when compact. + final Widget? selectionControl; + /// Placed on the tap target ([InkWell] / [GestureDetector]). final Key? tapKey; final bool selected; @@ -112,6 +122,11 @@ class AppListRow extends StatelessWidget { ), child: Row( children: [ + if (selectionControl case final control?) + Padding( + padding: const EdgeInsetsDirectional.only(end: 8), + child: control, + ), if (showLeading) Padding( padding: const EdgeInsetsDirectional.only(end: _avatarGap), @@ -130,6 +145,7 @@ class AppListRow extends StatelessWidget { ? _CupertinoRowSurface( tapKey: tapKey, onTap: onTap, + onLongPress: onLongPress, selected: selected, child: content, ) @@ -138,11 +154,19 @@ class AppListRow extends StatelessWidget { color: selected ? selectedColor(context, cupertino: false) : Colors.transparent, - child: InkWell(key: tapKey, onTap: onTap, child: content), + child: InkWell( + key: tapKey, + onTap: onTap, + onLongPress: onLongPress, + child: content, + ), ); if (!divider) return surface; - final textStart = - start + (showLeading ? kAppListAvatarSize + _avatarGap : 0); + // The divider stays under the text column; a checkbox's width is + // not known here, so a selectable row's divider starts at the inset. + final textStart = selectionControl != null + ? start + : start + (showLeading ? kAppListAvatarSize + _avatarGap : 0); return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, @@ -289,11 +313,13 @@ class _CupertinoRowSurface extends StatefulWidget { required this.tapKey, required this.onTap, required this.selected, + this.onLongPress, required this.child, }); final Key? tapKey; final VoidCallback? onTap; + final VoidCallback? onLongPress; final bool selected; final Widget child; @@ -320,6 +346,7 @@ class _CupertinoRowSurfaceState extends State<_CupertinoRowSurface> { key: widget.tapKey, behavior: HitTestBehavior.opaque, onTap: widget.onTap, + onLongPress: widget.onLongPress, onTapDown: enabled ? (_) => _press(true) : null, onTapUp: enabled ? (_) => _press(false) : null, onTapCancel: enabled ? () => _press(false) : null, diff --git a/app/notes/runs-delete-size.md b/app/notes/runs-delete-size.md new file mode 100644 index 00000000..eb8a228c --- /dev/null +++ b/app/notes/runs-delete-size.md @@ -0,0 +1,25 @@ +# Runs: multi-select delete and size sort + +Client side of the `delete_runs` contract (server built in parallel): + +- Request `delete_runs` `{run_ids: [int]}`; reply `runs_deleted` + `{deleted: [int], refused: [{run_id, reason}], freed_bytes: int}`. +- Broadcast `runs_removed` `{run_ids: [int]}` removes rows and closes an open + detail (route returns to the list). +- Run summaries may carry `size_bytes`; absent means unknown (nothing shown, + sorted last under Largest first). + +UI: bar action Select (or long-press a row) enters select mode; day headings +get Select all / Deselect all for that day's finished runs; active runs have a +disabled checkbox whose semantics give the reason. The bar shows `N selected`, +the selection size, Delete and Done. The run row and detail menus offer +Delete run for finished runs. The sort choice persists +(`pipelines.next.runsSort.v1`). + +Code: `lib/features/runs/domain/run_deletion.dart`, +`ui/runs_selection.dart`, `ui/runs_selection_bar.dart`, +`actions/delete_runs_{action,dialog}.dart`, `data/runs_sort_store.dart`. +Tests: `test/features/runs/domain/run_deletion_test.dart`, +`test/features/runs/ui/runs_delete_test.dart`. +Browser evidence: `node tool/runs_delete_probe.mjs build/web ` (real app +against `tool/runs_probe_server.mjs`, which now implements `delete_runs`). diff --git a/app/test/features/runs/domain/run_deletion_test.dart b/app/test/features/runs/domain/run_deletion_test.dart new file mode 100644 index 00000000..5c11fa94 --- /dev/null +++ b/app/test/features/runs/domain/run_deletion_test.dart @@ -0,0 +1,168 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_deletion.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +void main() { + test('formats sizes compactly', () { + expect(formatByteSize(0), '0 B'); + expect(formatByteSize(512), '512 B'); + expect(formatByteSize(4300), '4.2 KB'); + expect(formatByteSize(1024 * 1024), '1 MB'); + expect(formatByteSize(340 * 1024 * 1024), '340 MB'); + expect(formatByteSize((1.2 * 1024 * 1024 * 1024).round()), '1.2 GB'); + expect(formatByteSize(1024 * 1024 * 1024 - 1), '1 GB'); + expect(formatByteSize(12 * 1024 * 1024 * 1024), '12 GB'); + }); + + test('a missing or invalid size is unknown, not zero', () { + expect(runSizeBytes({'id': 1}), isNull); + expect(runSizeBytes({'size_bytes': -1}), isNull); + expect(runSizeBytes({'size_bytes': 'big'}), isNull); + expect(runSizeBytes({'size_bytes': 0}), isNull, reason: 'not measured'); + expect(runSizeBytes({'size_bytes': 1}), 1); + expect( + runsSizeLabel([ + {'id': 1}, + ]), + isNull, + ); + expect( + runsSizeLabel([ + {'size_bytes': 2048}, + {'id': 2}, + ]), + '2 KB + unknown', + ); + }); + + test('only finished runs are deletable', () { + for (final status in ['succeeded', 'failed', 'canceled', 'interrupted']) { + expect( + runIsDeletable({'id': 1, 'status': status}), + isTrue, + reason: status, + ); + } + for (final status in ['running', 'waiting', 'queued', 'pending', '']) { + expect( + runIsDeletable({'id': 1, 'status': status}), + isFalse, + reason: status, + ); + } + expect( + runIsDeletable({'id': 1, 'status': 'failed', 'executing': true}), + isFalse, + ); + }); + + test('largest first sorts by size with unknown sizes last', () { + final sorted = sortRuns([ + {'id': 1, 'created_at': '2026-10-30T10:00:00Z'}, + {'id': 2, 'size_bytes': 10, 'created_at': '2026-10-30T10:00:00Z'}, + {'id': 3, 'size_bytes': 5000, 'created_at': '2026-10-29T10:00:00Z'}, + {'id': 4, 'size_bytes': 0, 'created_at': '2026-10-31T10:00:00Z'}, + {'id': 5, 'size_bytes': 700, 'created_at': '2026-10-31T10:00:00Z'}, + ], sort: 'largest_first'); + expect([for (final r in sorted) r['id']], [3, 5, 2, 4, 1]); + }); + + test('parses runs_deleted and words the report', () { + final deletion = RunsDeletion.fromReply({ + 'type': 'runs_deleted', + 'id': '1', + 'runs_deleted': { + 'deleted': [3, 4], + 'refused': [ + {'run_id': 5, 'reason': 'run is active'}, + ], + 'freed_bytes': 1288490189, + }, + })!; + expect(deletion.deleted, [3, 4]); + expect(deletion.refused.single.runId, 5); + expect( + deletion.report, + 'Deleted 2 runs, freed 1.2 GB.\n1 run was not deleted:\n' + 'Run 5: run is active', + ); + expect(RunsDeletion.fromReply({'type': 'error'}), isNull); + expect( + RunsDeletion.fromReply({ + 'deleted': [1], + }), + isNull, + reason: 'the result is nested under runs_deleted', + ); + expect( + removedRunIds({ + 'run_ids': [1, 2.0, 'x'], + }), + [1, 2], + ); + }); + + test('confirmation wording', () { + expect(deleteRunsTitle(1), 'Delete 1 run?'); + expect( + deleteRunsMessage(3, size: '1.2 GB'), + 'This removes their artifacts, documents and history and frees about ' + '1.2 GB. This can’t be undone.', + ); + expect( + deleteRunsMessage(1), + 'This removes its artifacts, documents and history. ' + 'This can’t be undone.', + ); + }); + + test('run events update the size only when they carry one', () { + final rows = [ + {'id': 1, 'status': 'running', 'size_bytes': 0}, + ]; + final progress = foldRunEvent(rows, {'run_id': 1, 'status': 'running'}); + expect(progress.runs.single['size_bytes'], 0); + final done = foldRunEvent(progress.runs, { + 'run_id': 1, + 'status': 'succeeded', + 'size_bytes': 4096, + }); + expect(runSizeBytes(done.runs.single), 4096); + }); + + test('more than 1000 ids are sent in batches and combined', () async { + final gateway = _BatchGateway(); + final ids = [for (var id = 1; id <= 2500; id++) id]; + final result = await RunsRepository(gateway).deleteRuns(ids); + expect( + [for (final batch in gateway.batches) batch.length], + [1000, 1000, 500], + ); + expect(result.deleted, ids); + expect(result.freedBytes, 2500); + }); +} + +class _BatchGateway implements ApiGateway { + final batches = >[]; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + final ids = (fields['run_ids'] as List).cast(); + batches.add(ids); + return { + 'type': 'runs_deleted', + 'runs_deleted': { + 'deleted': ids, + 'refused': [], + 'freed_bytes': ids.length, + }, + }; + } +} diff --git a/app/test/features/runs/ui/runs_delete_test.dart b/app/test/features/runs/ui/runs_delete_test.dart new file mode 100644 index 00000000..6082ac34 --- /dev/null +++ b/app/test/features/runs/ui/runs_delete_test.dart @@ -0,0 +1,288 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/delete_runs_dialog.dart'; +import 'package:pipelines_app/features/runs/data/runs_sort_store.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; +import 'package:pipelines_app/features/runs/ui/run_more_menu.dart'; +import 'package:pipelines_app/features/runs/ui/runs_selection_bar.dart'; + +class _Gateway implements ApiGateway { + _Gateway(this.runs); + + final List runs; + final frames$ = StreamController.broadcast(); + final deletes = []; + JsonMap deleteReply = const {}; + + @override + Stream get frames => frames$.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + switch (type) { + case 'list_runs': + return {'runs': runs}; + case 'get_run': + final id = fields['run_id']; + return {'run_detail': runs.firstWhere((run) => run['id'] == id)}; + case 'delete_runs': + deletes.add(fields); + return {'type': 'runs_deleted', 'runs_deleted': deleteReply}; + } + throw UnsupportedError(type); + } +} + +String _stamp(DateTime day, int hour) => + DateTime(day.year, day.month, day.day, hour).toUtc().toIso8601String(); + +List _fixture() { + final today = DateTime.now(); + final yesterday = today.subtract(const Duration(days: 1)); + return [ + { + 'id': 11, + 'title': 'Today done', + 'status': 'succeeded', + 'created_at': _stamp(today, 1), + 'size_bytes': 340 * 1024 * 1024, + }, + { + 'id': 12, + 'title': 'Today failed', + 'status': 'failed', + 'created_at': _stamp(today, 0), + 'size_bytes': 1024 * 1024 * 1024, + }, + { + 'id': 13, + 'title': 'Today running', + 'status': 'running', + 'executing': true, + 'created_at': _stamp(today, 0), + }, + { + 'id': 21, + 'title': 'Yesterday done', + 'status': 'succeeded', + 'created_at': _stamp(yesterday, 10), + 'size_bytes': 0, + }, + ]; +} + +Future _mount( + WidgetTester tester, + _Gateway gateway, { + bool cupertino = false, + int? initialRunId, + RunsSortStore? store, + ValueChanged? onBack, +}) async { + tester.view.physicalSize = const Size(1100, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final screen = RunsScreen( + gateway: gateway, + initialRunId: initialRunId, + onBack: onBack, + sortStore: store ?? MemoryRunsSortStore(), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp(home: CupertinoPageScaffold(child: screen)) + : MaterialApp(home: Scaffold(body: screen)), + ); + await tester.pumpAndSettle(); +} + +Checkbox _box(WidgetTester tester, int id) => tester.widget( + find.descendant( + of: find.byKey(ValueKey('run-select-$id')), + matching: find.byType(Checkbox), + ), +); + +void main() { + testWidgets('day select-all selects only that day\'s finished runs', ( + tester, + ) async { + final gateway = _Gateway(_fixture()); + await _mount(tester, gateway); + expect(find.textContaining('340 MB'), findsOneWidget); + expect(find.textContaining('1 GB'), findsOneWidget); + + await tester.tap(find.byKey(runsSelectKey)); + await tester.pumpAndSettle(); + expect(find.text('0 selected'), findsOneWidget); + // The active run's checkbox is disabled and says why. + expect(_box(tester, 13).onChanged, isNull); + expect( + find.bySemanticsLabel(RegExp('Today running.*can’t be deleted')), + findsOneWidget, + ); + + await tester.tap(find.byKey(runsDaySelectKey('Today'))); + await tester.pumpAndSettle(); + expect(_box(tester, 11).value, isTrue); + expect(_box(tester, 12).value, isTrue); + expect(_box(tester, 13).value, isFalse); + expect(_box(tester, 21).value, isFalse); + expect(find.text('2 selected · 1.3 GB'), findsOneWidget); + expect(find.text('Deselect all'), findsOneWidget); + + // Tapping a row toggles it instead of opening the run. + await tester.tap(find.text('Yesterday done')); + await tester.pumpAndSettle(); + expect(_box(tester, 21).value, isTrue); + expect(find.textContaining('3 selected'), findsOneWidget); + + await tester.tap(find.byKey(runsDaySelectKey('Today'))); + await tester.pumpAndSettle(); + expect(_box(tester, 11).value, isFalse); + expect(_box(tester, 21).value, isTrue); + + await tester.tap(find.byKey(runsSelectDoneKey)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('run-select-11')), findsNothing); + }); + + testWidgets('delete confirms, sends delete_runs and reports refusals', ( + tester, + ) async { + final gateway = _Gateway(_fixture()) + ..deleteReply = { + 'deleted': [11], + 'refused': [ + {'run_id': 12, 'reason': 'run is being exported'}, + ], + 'freed_bytes': 340 * 1024 * 1024, + }; + await _mount(tester, gateway); + await tester.tap(find.byKey(runsSelectKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(runsDaySelectKey('Today'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(runsDeleteSelectedKey)); + await tester.pumpAndSettle(); + + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text('Delete 2 runs?'), findsOneWidget); + expect( + find.text( + 'This removes their artifacts, documents and history and frees about ' + '1.3 GB. This can’t be undone.', + ), + findsOneWidget, + ); + expect(gateway.deletes, isEmpty, reason: 'nothing before confirming'); + + await tester.tap(find.byKey(deleteRunsConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.deletes.single['run_ids'], [11, 12]); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text('Today done'), findsNothing); + expect(find.text('Today failed'), findsOneWidget); + expect( + find.text( + 'Deleted 1 run, freed 340 MB.\n1 run was not deleted:\n' + 'Run 12: run is being exported', + ), + findsOneWidget, + ); + // The refused run stays selected. + expect(find.text('1 selected · 1 GB'), findsOneWidget); + }); + + testWidgets('Cancel in the prompt sends nothing', (tester) async { + final gateway = _Gateway(_fixture()); + await _mount(tester, gateway, cupertino: true); + await tester.tap(find.byKey(runsSelectKey)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Yesterday done')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(runsDeleteSelectedKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text('Delete 1 run?'), findsOneWidget); + await tester.tap(find.byKey(deleteRunsKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.deletes, isEmpty); + expect(find.text('Yesterday done'), findsOneWidget); + }); + + testWidgets('runs_removed removes rows and closes the open detail', ( + tester, + ) async { + final gateway = _Gateway(_fixture()); + final backs = []; + await _mount(tester, gateway, initialRunId: 12, onBack: backs.add); + expect(find.byKey(const ValueKey('run-detail-pane')), findsOneWidget); + + gateway.frames$.add({ + 'type': 'runs_removed', + 'run_ids': [12, 21], + }); + await tester.pumpAndSettle(); + expect(find.text('Today failed'), findsNothing); + expect(find.text('Yesterday done'), findsNothing); + expect(find.text('Today done'), findsOneWidget); + expect(find.byKey(const ValueKey('run-detail-pane')), findsNothing); + expect(backs, hasLength(1)); + }); + + testWidgets('Delete run in the detail menu deletes the open run', ( + tester, + ) async { + final gateway = _Gateway(_fixture()) + ..deleteReply = { + 'deleted': [21], + 'refused': [], + 'freed_bytes': 0, + }; + final backs = []; + await _mount(tester, gateway, initialRunId: 21, onBack: backs.add); + await tester.tap(find.byKey(runMoreMenuKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(deleteRunActionKey)); + await tester.pumpAndSettle(); + expect(find.text('Delete 1 run?'), findsOneWidget); + await tester.tap(find.byKey(deleteRunsConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.deletes.single['run_ids'], [21]); + expect(find.byKey(const ValueKey('run-detail-pane')), findsNothing); + expect(find.text('Yesterday done'), findsNothing); + expect(backs, hasLength(1)); + }); + + testWidgets('Largest first is flat, unknown sizes last, and persists', ( + tester, + ) async { + final store = MemoryRunsSortStore('largest_first'); + await _mount(tester, _Gateway(_fixture()), store: store); + expect(find.text('Today'), findsNothing, reason: 'no day headings'); + final order = [ + for (final title in [ + 'Today failed', + 'Today done', + 'Today running', + 'Yesterday done', + ]) + tester.getTopLeft(find.text(title)).dy, + ]; + expect(order, orderedEquals([...order]..sort())); + // Unknown sizes come after every known size. + expect(order[2], greaterThan(order[1])); + + await tester.tap(find.byKey(const ValueKey('runs.sort'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Newest first')); + await tester.pumpAndSettle(); + expect(store.value, 'newest_first'); + expect(find.text('Today'), findsOneWidget); + }); +} diff --git a/app/tool/runs_delete_probe.mjs b/app/tool/runs_delete_probe.mjs new file mode 100644 index 00000000..5eb0897b --- /dev/null +++ b/app/tool/runs_delete_probe.mjs @@ -0,0 +1,229 @@ +import { execFile, spawn } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; +import { once } from 'node:events'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +import { startFixture } from './runs_probe_server.mjs'; + +// Browser evidence for the Runs list's multi-select, delete and size sort. +// +// The normal app composition (`flutter build web`) talks to the isolated +// loopback fixture in runs_probe_server.mjs, which implements `delete_runs` +// and broadcasts `runs_removed`. Run from app/: +// flutter build web +// node tool/runs_delete_probe.mjs build/web /tmp/runs-delete-evidence +const root = resolve(process.argv[2] ?? 'build/web'); +const output = resolve(process.argv[3] ?? process.env.OPENCODE_ARTIFACT_DIR ?? 'build/runs-delete-evidence'); +await mkdir(output, { recursive: true }); + +const MB = 1024 * 1024; +const stamp = (daysAgo, hour) => { + const now = new Date(); + return new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysAgo, hour).toISOString(); +}; +const run = (id, title, status, daysAgo, hour, size, extra = {}) => ({ + id, title, name: 'nightly-report', pipeline_id: 10, status, + executing: ['running', 'queued'].includes(status), + created_at: stamp(daysAgo, hour), + finished_at: ['running', 'queued', 'waiting'].includes(status) ? undefined : stamp(daysAgo, hour + 1), + ...(size == null ? {} : { size_bytes: size }), + ...extra, +}); +const runs = [ + run(31, 'Index rebuild', 'running', 0, 0, null), + run(32, 'Model sweep', 'succeeded', 0, 0, Math.round(1.2 * 1024 * MB)), + run(33, 'Docs refresh', 'failed', 0, 0, 340 * MB), + run(34, 'Waiting review', 'waiting', 0, 0, 12 * MB), + run(21, 'Screenshot capture', 'succeeded', 1, 9, 2600 * MB), + run(22, 'Old import', 'canceled', 1, 8, null), + run(11, 'Weekly digest', 'succeeded', 3, 10, 48 * MB), +]; + +const fixture = await startFixture({ root, runs }); +const profile = await mkdtemp(join(tmpdir(), 'runs-delete-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +const waitFor = async (fn, label, attempts = 150) => { + for (let i = 0; i < attempts; i++) { + const value = await fn(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${label}`); +}; + +let ws; +const captures = []; +const pageErrors = []; +try { + const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], 'Chrome DevTools'); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.method === 'Runtime.exceptionThrown') { + pageErrors.push(JSON.stringify(message.params?.exceptionDetails?.text)); + } + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.result?.exceptionDetails) throw new Error(JSON.stringify(response.result.exceptionDetails)); + return response.result?.result?.value; + }; + const labels = () => evaluate(`[...document.querySelectorAll('flt-semantics')] + .map((el) => (el.getAttribute('aria-label') || (!el.children.length && el.innerText) || '').trim()) + .filter(Boolean)`); + const expectText = async (text) => { + try { + await waitFor(async () => (await labels()).some((label) => label.includes(text)), JSON.stringify(text)); + } catch (error) { + throw new Error(`${error.message}\nLabels: ${JSON.stringify(await labels())}`); + } + }; + const expectAbsent = async (text) => { + await delay(400); + if ((await labels()).some((label) => label.includes(text))) { + throw new Error(`Unexpected ${JSON.stringify(text)}: ${JSON.stringify(await labels())}`); + } + }; + const click = async (text, { exact = true } = {}) => { + let clicked = false; + for (let attempt = 0; attempt < 30 && !clicked; attempt++) { + if (attempt) await delay(200); + clicked = await tryClick(text, exact); + } + if (!clicked) await capture(`failed-click`); + if (!clicked) throw new Error(`Could not click ${JSON.stringify(text)}: ${JSON.stringify(await labels())}`); + await delay(500); + }; + const tryClick = async (text, exact) => { + return evaluate(`(() => { + const wanted = ${JSON.stringify(text)}; + const nodes = [...document.querySelectorAll('flt-semantics')].filter((el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return ${exact} ? label === wanted : label.includes(wanted); + }); + const target = nodes.find((el) => ['button', 'checkbox', 'menuitem', 'tab'].includes(el.getAttribute('role'))) ?? nodes[0]; + if (!target) return false; + target.click(); + return true; + })()`); + }; + const capture = async (name) => { + await delay(500); + const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data; + const path = join(output, `${name}.png`); + await writeFile(path, Buffer.from(data, 'base64')); + captures.push(path); + }; + // Dialog and bar text is canvas-rendered; OCR reads it from the capture. + const expectOcr = async (texts) => { + const path = captures[captures.length - 1]; + // Piped through stdin: some sandboxes deny tesseract direct file reads. + const ocr = promisify(execFile)('tesseract', ['stdin', 'stdout']); + ocr.child.stdin.end(await readFile(path)); + const { stdout } = await ocr; + const read = stdout.replace(/\s+/g, ' '); + for (const text of texts) { + if (!read.includes(text)) throw new Error(`OCR of ${path} lacks ${JSON.stringify(text)}:\n${read}`); + } + }; + const setSize = async (width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(600); + }; + + await setSize(560, 900); + await send('Page.navigate', { url: `${fixture.url}/runs` }, session); + await waitFor(() => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), 'semantics placeholder'); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await expectText('Model sweep'); + await expectText('1.2 GB'); + await expectText('340 MB'); + + // 560 wide: select mode with Today selected, then the confirmation (kept). + await click('Select'); + // The bar title (`N selected`) is canvas text; the Delete label carries N. + await expectText('Delete selected runs'); + await click('Select all Today'); + await expectText('Delete 2 selected runs'); + await capture('runs-select-day-560'); + await expectOcr(['2 selected', 'Deselect all']); + await click('Delete 2 selected runs'); + await expectText('Cancel'); + await capture('runs-confirm-560'); + await expectOcr(['Delete 2 runs?', 'frees about 1.5 GB', 'undone']); + await click('Cancel'); + await expectAbsent('Cancel'); + if (fixture.deleteRequests.length) throw new Error('Cancel sent a delete'); + await click('Done'); + + await click('Sort runs: Newest first', { exact: false }); + await click('Largest first'); + await expectText('Screenshot capture'); + await capture('runs-largest-560'); + await expectAbsent('Select all Today'); + await click('Sort runs: Largest first', { exact: false }); + await click('Newest first'); + + // 1100 wide: the same with an open detail, then a confirmed delete. + await setSize(1100, 800); + await click('Docs refresh', { exact: false }); + await expectText('Summary'); + await click('Select'); + await click('Select all Today'); + await expectText('Delete 2 selected runs'); + await capture('runs-select-day-1100'); + await expectOcr(['2 selected']); + await click('Delete 2 selected runs'); + await expectText('Cancel'); + // Checked by eye: OCR misses the dialog over the dimmed two-pane page. + await capture('runs-confirm-1100'); + await click('Delete'); + await expectText('Dismiss'); + await expectAbsent('Docs refresh'); + await capture('runs-deleted-1100'); + await expectOcr(['Deleted 2 runs, freed 1.5 GB.']); + const sent = fixture.deleteRequests; + if (sent.length !== 1 || JSON.stringify(sent[0].run_ids) !== '[32,33]') { + throw new Error(`Unexpected delete_runs: ${JSON.stringify(sent)}`); + } + await click('Sort runs: Newest first', { exact: false }); + await click('Largest first'); + await capture('runs-largest-1100'); + + if (pageErrors.length) throw new Error(`Page exceptions: ${pageErrors.join('\n')}`); + const manifest = { fixture: 'tool/runs_probe_server.mjs', deleteRequests: sent, captures }; + await writeFile(join(output, 'manifest.json'), JSON.stringify(manifest, null, 2)); + console.log(JSON.stringify(manifest, null, 2)); +} finally { + ws?.close(); + chrome.kill('SIGTERM'); + await Promise.race([once(chrome, 'exit'), delay(3000)]); + await fixture.close(); + // Chrome may still be flushing its profile; a leftover temp dir is harmless. + await rm(profile, { recursive: true, force: true, maxRetries: 5 }).catch(() => {}); +} diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index 39b97745..f43df9a0 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -322,6 +322,10 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c let getRun = 0; const canceled = new Set(); const cancelRequests = []; + // `delete_runs` removes finished runs from later `list_runs` replies and + // broadcasts `runs_removed`, as the server's contract describes. + const deleted = new Set(); + const deleteRequests = []; let decisionAccepted = false; const decisionRequests = []; let chatSubscribed = 0; @@ -478,7 +482,7 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c } if (request.type === 'list_runs') { listRuns++; - client.send({ id: request.id, type: 'runs', runs: runs.map((run) => + client.send({ id: request.id, type: 'runs', runs: runs.filter((run) => !deleted.has(run.id)).map((run) => canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null }); return; @@ -510,6 +514,30 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c ? humanDetail(decisionAccepted, runs) : detail(id, live, canceled.has(id), runs) }); return; } + if (request.type === 'delete_runs') { + const ids = Array.isArray(request.run_ids) ? request.run_ids : []; + deleteRequests.push({ run_ids: ids }); + const done = []; + const refused = []; + let freed = 0; + for (const id of ids) { + const run = runs.find((item) => item.id === id); + if (!run || deleted.has(id)) { + refused.push({ run_id: id, reason: 'run not found' }); + } else if (run.executing || ['running', 'waiting', 'queued', 'pending'].includes(run.status)) { + refused.push({ run_id: id, reason: 'run is still active' }); + } else { + deleted.add(id); + done.push(id); + freed += run.size_bytes ?? 0; + } + } + client.send({ id: request.id, type: 'runs_deleted', runs_deleted: { deleted: done, refused, freed_bytes: freed } }); + if (done.length) { + for (const other of connections) other.send({ type: 'runs_removed', run_ids: done }); + } + return; + } if (request.type === 'cancel_run' && request.run_id === 4) { cancelRequests.push({ run_id: request.run_id }); canceled.add(4); @@ -670,6 +698,9 @@ export async function startFixture({ root, runs = RUNS, runDetail, files = {}, c get subscribed() { return subscribed; }, + get deleteRequests() { + return deleteRequests; + }, close: () => new Promise((resolveClose) => { for (const connection of connections) connection.close();