feat(app): add deliberate run cancellation action

Port the browser's canCancel rule and cancel_run request into a native
Material/Cupertino confirmation. Opening the prompt or choosing Keep sends
nothing; a refusal stays visible with the server's words and the run is
re-read so the owner always receives server truth. Includes eligibility,
double-submit, disposal and narrow 2x-text tests plus R2b evidence.
This commit is contained in:
2026-10-21 14:41:33 +01:00
parent 3e6f950991
commit faa5866410
8 changed files with 865 additions and 0 deletions
@@ -0,0 +1,145 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'cancel_wording.dart';
/// Sends the confirmed cancellation. Returns null once the server has accepted
/// it, or the server's refusal verbatim; the prompt then stays open.
typedef CancelSubmit = Future<String?> Function();
/// Opens the native cancel confirmation for [runId].
///
/// Nothing is sent until the operator presses the confirm action, and the
/// dismiss action (`Keep`) only closes the prompt.
Future<void> showCancelRunPrompt({
required BuildContext context,
required num runId,
required bool cupertino,
required CancelSubmit onSubmit,
}) {
final prompt = _CancelPrompt(
runId: runId,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _CancelPrompt extends StatefulWidget {
const _CancelPrompt({
required this.runId,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final bool cupertino;
final CancelSubmit onSubmit;
@override
State<_CancelPrompt> createState() => _CancelPromptState();
}
class _CancelPromptState extends State<_CancelPrompt> {
bool _sending = false;
String? _error;
void _keep() {
if (!_sending) Navigator.of(context).pop();
}
Future<void> _confirm() async {
if (_sending) return;
setState(() {
_sending = true;
_error = null;
});
final refusal = await widget.onSubmit();
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
setState(() {
_sending = false;
_error = refusal;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: Text(cancelDialogTitle(widget.runId)),
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
actions: [
TextButton(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
FilledButton(
key: cancelConfirmKey,
onPressed: _sending ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(cancelDialogTitle(widget.runId)),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
CupertinoDialogAction(
key: cancelKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(cancelKeepLabel),
),
CupertinoDialogAction(
key: cancelConfirmKey,
isDestructiveAction: true,
onPressed: _sending ? null : _confirm,
child: const Text(cancelConfirmLabel),
),
],
);
}
Widget _body({required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(cancelDialogMessage),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: cancelErrorKey, style: errorStyle),
),
],
);
}
}
@@ -0,0 +1,31 @@
import '../../../core/api_gateway.dart';
/// Whether the operator may cancel [run], matching `canCancel` in
/// `web/src/actions.js` exactly:
///
/// `(executing || (status == "waiting" && export_pending_sequence > 0)) &&
/// !cancel_requested && !cleanup_unconfirmed`
///
/// The status word alone is not enough: a stale `running` status without
/// `executing` is not cancellable, while a run waiting on a pending session
/// export is.
bool canCancelRun(JsonMap? run) {
if (run == null) return false;
final exportPending = _number(run['export_pending_sequence']);
return (run['executing'] == true ||
(run['status'] == 'waiting' && exportPending > 0)) &&
run['cancel_requested'] != true &&
run['cleanup_unconfirmed'] != true;
}
/// The run id used by the cancel request, or null for a malformed run.
num? cancelRunId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
/// `Number(value) > 0`, tolerating numeric strings as the browser does.
double _number(dynamic value) {
if (value is num) return value.toDouble();
return double.tryParse('${value ?? ''}'.trim()) ?? 0;
}
@@ -0,0 +1,101 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'cancel_dialog.dart';
import 'cancel_eligibility.dart';
import 'cancel_wording.dart';
/// The run detail's deliberate cancel entry point.
///
/// Renders one native button only while [run] is cancellable under the browser
/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends
/// nothing; only the confirm action asks the server to stop the run. A refusal
/// is shown verbatim in the kept-open prompt and the run is re-read, so
/// [onRunChanged] always receives server truth instead of a local guess.
class CancelRunAction extends StatefulWidget {
const CancelRunAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<CancelRunAction> createState() => _CancelRunActionState();
}
class _CancelRunActionState extends State<CancelRunAction> {
bool _dialogOpen = false;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = cancelRunId(widget.run);
if (id == null || !canCancelRun(widget.run) || _dialogOpen) return;
_dialogOpen = true;
try {
await showCancelRunPrompt(
context: context,
runId: id,
cupertino: _usesCupertino(context),
onSubmit: () => _submit(id),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<String?> _submit(num id) async {
final repository = RunsRepository(widget.gateway);
try {
final run = await repository.cancelRun(id);
if (!mounted) return null;
widget.onRunChanged(run);
return null;
} catch (error) {
final refusal = describeCancelError(error);
if (!mounted) return refusal;
JsonMap? refreshed;
try {
refreshed = await repository.getRun(id);
} catch (_) {
// A failed re-read must not hide or replace the server's refusal.
}
if (!mounted) return refusal;
if (refreshed != null) widget.onRunChanged(refreshed);
return refusal;
}
}
@override
Widget build(BuildContext context) {
if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) {
return const SizedBox.shrink();
}
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
return FilledButton(
key: cancelActionKey,
onPressed: _open,
child: const Text(cancelActionLabel),
);
}
}
@@ -0,0 +1,23 @@
import 'package:flutter/widgets.dart';
/// The browser client's cancel wording, kept verbatim.
const cancelActionLabel = 'Cancel run';
const cancelDialogMessage = 'This asks the server to stop the active run.';
const cancelConfirmLabel = 'Cancel run';
const cancelKeepLabel = 'Keep';
/// Stable test/semantics keys shared by the action and its prompt.
const cancelActionKey = ValueKey<String>('cancel-run-action');
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
const cancelErrorKey = ValueKey<String>('cancel-run-error');
/// The cancel dialog's title: `Cancel run {id}?`.
String cancelDialogTitle(num runId) => 'Cancel run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a cancellation that did not happen.
String describeCancelError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not cancel the run.' : message;
}