diff --git a/app/.gitignore b/app/.gitignore index 9f91cbac..371e9bd8 100644 --- a/app/.gitignore +++ b/app/.gitignore @@ -45,6 +45,9 @@ app.*.map.json /android/app/release # The repository ignores runtime data/ directories. Feature repository source -# is code, not runtime data, and must be included in fresh checkouts. +# and its tests are code, not runtime data, and must be included in fresh +# checkouts. !/lib/**/data/ !/lib/**/data/** +!/test/**/data/ +!/test/**/data/** diff --git a/app/WORK.md b/app/WORK.md index 987bd9a4..9d4dff9a 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -21,6 +21,13 @@ All work under app/. Existing applications remain running and unchanged. | R2b | Native cancel-run confirmation | run51 →52 / correction5449370 | manager reran23 action tests + analyze, pass; known refusal now immediate and dismissible while resync pending | merged main; ancestry verified | reusable component only; wiring/browser pending | | X1 | Native search and result targets | run49 / flutter/x1-search | Code computed success; WAITING truncated2MiB export | held, review not reached | pending | | I1 | App-owned socket/session + live Runs shell registration | run50 / flutter/r1-native | Code computed success; WAITING truncated2MiB export | held, review not reached | not deployed | +| E1 | Narrow authorized server export-bound fix | run53 / fix/session-export-limit | API v8, Flash; bounded export/repair regressions | pending | no service restart authorized by pipeline | +| R2c | Native retry/restart confirmation | run54 / commit178f22a | manager reran17 focused tests + analyze, pass; exact modes/stable intent keys checked | main804e531, ancestry verified | reusable only; wiring/browser pending | +| R2d | Native rename-run dialog | run55 / commitf2643a0 | manager reran11 focused tests + analyze, pass; clean scoped diff | main3dde288, ancestry verified | reusable only; screen/list update wiring pending | +| S1a | Saved schedules repository/revision safety | run56 / commitb963965 | manager reran18 focused tests + analyze, pass; revision/unknown field preservation checked | maina290858, ancestry verified | — | +| T1a | Templates/validate/create-only requests | run57 / flutter/t1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| S1b | Native read-only schedule list | run58 / flutter/s1-list | Task v6, Flash; separate from editor | pending | pending | +| P2a | Graph identities/recorded-visit model | run59 / flutter/p2-model | Task v6, Flash; separate from layout/rendering | pending | — | ## Next ready work - P1 pipelines list/detail/source/version; P2 graph and stage/visit selection. @@ -53,6 +60,10 @@ override, server edit or shell-write bypass was used by the manager. Allowed pipeline models: Luna or DeepSeek V4.1 Flash; current runs use Luna. ## Latest integration check +At804e531 manager ran the integrated main Flutter suite: 98tests passed and +flutter analyze was clean. These cover landed source/components only, not the +six unreviewed export-blocked feature branches or visible screen delivery. + ### Current delivery blocker — session export cap User asked about failed runs; explicit status inspection found runs34/37/39/42/ 49/50 are waiting, not failed: each Code visit1 computed success and is quiescent, @@ -61,9 +72,16 @@ session identities remain retained. `pipelines repair-session-export 34 1` was attempted once; it returned `session export repair incomplete: partial` at the same cap. No full stage reruns, evidence replacement, cancellation or gate bypass was performed. Remaining waits stay active for eventual export-only recovery. -Server export-cap change is outside the user's explicit app-only authorization; -approval is required before changing server code/configuration/deployment. Do -not burn repeated repair attempts against this deterministic size limit. +User subsequently approved the narrow server export-limit exception and asked +for continued small parallel tasks. Run53 owns ONLY bounded export-limit code, +necessary verification/repair regressions and a focused note. Existing web and +mobile source remain off-limits. Deployment remains a separate operator gate +under internal/server/AGENTS.md; no shared service restart is delegated. After +authorized installation, recover the original exact visits EXPORT-ONLY. Do not +burn repeated repair attempts against the unchanged deterministic size limit. + +Parallel work while E1 runs: R2c/R2d/S1a are separate worktrees, each with its own +focused existing Task v6 run and background wait. No new workflow definitions. At 160ab45: 29 Flutter tests and 6 Node proxy fixtures pass; flutter analyze, flutter build web and git diff --check pass. Real Chrome phone/desktop captures diff --git a/app/lib/features/runs/actions/retry_action.dart b/app/lib/features/runs/actions/retry_action.dart new file mode 100644 index 00000000..28cda388 --- /dev/null +++ b/app/lib/features/runs/actions/retry_action.dart @@ -0,0 +1,123 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'retry_dialog.dart'; +import 'retry_eligibility.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// The run detail's deliberate retry entry point. +/// +/// Renders one native button only while [run] is a stopped `failed` run. Opening +/// the resume or restart confirmation sends nothing; only the confirm action +/// asks the server to retry. A refusal is returned to the kept-open prompt +/// immediately and the run is re-read separately, so [onRunChanged] still +/// receives server truth without locking the prompt while that read is pending. +class RetryRunAction extends StatefulWidget { + const RetryRunAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RetryRunActionState(); +} + +class _RetryRunActionState extends State { + bool _dialogOpen = false; + Future? _resync; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = retryRunId(widget.run); + if (id == null || !canRetryRun(widget.run) || _dialogOpen) return; + _dialogOpen = true; + try { + await showRetryRunPrompt( + context: context, + runId: id, + cupertino: _usesCupertino(context), + onSubmit: (intent) => _submit(id, intent), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, RetryIntent intent) async { + final repository = RunsRepository(widget.gateway); + try { + final run = await repository.retryRun( + id, + requestKey: intent.requestKey, + mode: intent.mode.wireMode, + ); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal( + describeRetryError(error), + stillPossible: _resyncRun(id), + ); + } + } + + bool _owns(num id) => mounted && retryRunId(widget.run) == id; + + /// One bounded re-read per refusal. A refusal that arrives while a read is + /// already in flight observes that same read instead of starting another. + Future _resyncRun(num id) { + return _resync ??= _readRun(id); + } + + Future _readRun(num id) async { + try { + final run = await RunsRepository(widget.gateway).getRun(id); + if (!_owns(id)) return null; + widget.onRunChanged(run); + return canRetryRun(run); + } catch (_) { + // Unknown server truth: keep the refusal and leave a deliberate retry. + return null; + } finally { + _resync = null; + } + } + + @override + Widget build(BuildContext context) { + if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) { + return const SizedBox.shrink(); + } + if (_usesCupertino(context)) { + return CupertinoButton.filled( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } + return FilledButton( + key: retryActionKey, + onPressed: _open, + child: const Text(retryActionLabel), + ); + } +} diff --git a/app/lib/features/runs/actions/retry_dialog.dart b/app/lib/features/runs/actions/retry_dialog.dart new file mode 100644 index 00000000..846133a1 --- /dev/null +++ b/app/lib/features/runs/actions/retry_dialog.dart @@ -0,0 +1,207 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'retry_intent.dart'; +import 'retry_wording.dart'; + +/// Sends the confirmed retry intent. Returns null once the server has accepted +/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt +/// then stays open with dismissal available immediately. +typedef RetrySubmit = Future Function(RetryIntent intent); + +/// Opens the native retry confirmation for [runId]. +/// +/// The first confirmation offers resume (the default) and a secondary +/// `Restart from start` confirmation, exactly like the browser's retry dialog. +/// Nothing is sent until the operator presses a confirm action; `Keep` only +/// closes the prompt. +Future showRetryRunPrompt({ + required BuildContext context, + required num runId, + required bool cupertino, + required RetrySubmit onSubmit, +}) { + final prompt = _RetryPrompt( + runId: runId, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _RetryPrompt extends StatefulWidget { + const _RetryPrompt({ + required this.runId, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final bool cupertino; + final RetrySubmit onSubmit; + + @override + State<_RetryPrompt> createState() => _RetryPromptState(); +} + +class _RetryPromptState extends State<_RetryPrompt> { + RetryMode _mode = RetryMode.resume; + String? _requestKey; + bool _sending = false; + bool _checking = false; + bool _blocked = false; + bool _attempted = false; + String? _error; + + void _keep() { + if (!_sending) Navigator.of(context).pop(); + } + + void _restart() { + if (_sending || _checking || _attempted) return; + setState(() { + _mode = RetryMode.restart; + _error = null; + }); + } + + Future _confirm() async { + if (_sending || _checking || _blocked) return; + setState(() { + _sending = true; + _attempted = true; + _error = null; + }); + final intent = RetryIntent( + mode: _mode, + requestKey: _requestKey ??= newRetryRequestKey(widget.runId), + ); + final refusal = await widget.onSubmit(intent); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + final check = refusal.stillPossible; + setState(() { + _sending = false; + _error = refusal.message; + _checking = check != null; + }); + if (check == null) return; + bool? stillPossible; + try { + stillPossible = await check; + } catch (_) { + // The action reports re-read failures as null; never fabricate one here. + } + if (!mounted) return; + setState(() { + _checking = false; + _blocked = stillPossible == false; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + bool get _confirmDisabled => _sending || _checking || _blocked; + bool get _showRestart => _mode == RetryMode.resume && !_attempted; + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: Text(_dialogTitle), + content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)), + actions: [ + if (_showRestart) + TextButton( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + TextButton( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + FilledButton( + key: retryConfirmKey, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: Text(_dialogTitle), + content: _body( + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + if (_showRestart) + CupertinoDialogAction( + key: retryRestartKey, + onPressed: _sending || _checking ? null : _restart, + child: const Text(restartConfirmLabel), + ), + CupertinoDialogAction( + key: retryKeepKey, + onPressed: _sending ? null : _keep, + child: const Text(retryKeepLabel), + ), + CupertinoDialogAction( + key: retryConfirmKey, + isDestructiveAction: _mode == RetryMode.restart, + onPressed: _confirmDisabled ? null : _confirm, + child: Text(_confirmLabel), + ), + ], + ); + } + + Widget _body({required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(_dialogMessage), + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: retryErrorKey, style: errorStyle), + ), + ], + ); + } + + String get _dialogTitle => _mode == RetryMode.restart + ? restartDialogTitle(widget.runId) + : retryDialogTitle(widget.runId); + + String get _dialogMessage => + _mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage; + + String get _confirmLabel => + _mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel; +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart new file mode 100644 index 00000000..13026230 --- /dev/null +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -0,0 +1,16 @@ +import '../../../core/api_gateway.dart'; + +/// Whether the operator may retry [run], matching `canRetry` in +/// `web/src/actions.js` exactly: a loaded run that is not executing and whose +/// status is `failed`. A stale `failed` status while the run still executes is +/// not retryable. +bool canRetryRun(JsonMap? run) { + if (run == null) return false; + return run['executing'] != true && run['status'] == 'failed'; +} + +/// The run id used by the retry request, or null for a malformed run. +num? retryRunId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} diff --git a/app/lib/features/runs/actions/retry_intent.dart b/app/lib/features/runs/actions/retry_intent.dart new file mode 100644 index 00000000..17140a70 --- /dev/null +++ b/app/lib/features/runs/actions/retry_intent.dart @@ -0,0 +1,29 @@ +import 'dart:math'; + +/// The two deliberate retry choices. `resume` is the server's default, so its +/// wire field is omitted; `restart` replays the whole pipeline. +enum RetryMode { + resume, + restart; + + /// The `retry_mode` value to send, or null to let the server resume. + String? get wireMode => this == RetryMode.restart ? 'restart' : null; +} + +/// One confirmed retry intent: the chosen mode plus the idempotency key that +/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the +/// server can dedupe it; a fresh deliberate intent uses a new key. +class RetryIntent { + const RetryIntent({required this.mode, required this.requestKey}); + + final RetryMode mode; + final String requestKey; +} + +/// A fresh `request_key` for one retry intent. The server requires one and caps +/// it at 128 characters; this stays well inside that bound and unique per call. +String newRetryRequestKey(num runId, {DateTime? now, int? random}) { + final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; + final entropy = random ?? Random().nextInt(1 << 32); + return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; +} diff --git a/app/lib/features/runs/actions/retry_wording.dart b/app/lib/features/runs/actions/retry_wording.dart new file mode 100644 index 00000000..efec7d86 --- /dev/null +++ b/app/lib/features/runs/actions/retry_wording.dart @@ -0,0 +1,33 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's retry wording, kept verbatim. +const retryActionLabel = 'Retry'; +const retryDialogMessage = + 'Only failed runs can be retried. The server starts a new run from the ' + 'same input.'; +const retryConfirmLabel = 'Retry'; +const restartDialogMessage = + 'This replays the whole pipeline from the start instead of resuming the ' + 'failed stage.'; +const restartConfirmLabel = 'Restart from start'; +const retryKeepLabel = 'Keep'; + +/// Stable test/semantics keys shared by the action and its prompt. +const retryActionKey = ValueKey('retry-run-action'); +const retryKeepKey = ValueKey('retry-run-keep'); +const retryConfirmKey = ValueKey('retry-run-confirm'); +const retryRestartKey = ValueKey('retry-run-restart'); +const retryErrorKey = ValueKey('retry-run-error'); + +/// The retry dialog's title: `Retry run {id}?`. +String retryDialogTitle(num runId) => 'Retry run $runId?'; + +/// The restart dialog's title: `Restart run {id}?`. +String restartDialogTitle(num runId) => 'Restart run $runId?'; + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a retry that did not happen. +String describeRetryError(Object error) { + final message = '$error'.trim(); + return message.isEmpty ? 'The server did not retry the run.' : message; +} diff --git a/app/lib/features/runs/actions/title_action.dart b/app/lib/features/runs/actions/title_action.dart new file mode 100644 index 00000000..7a5b9b97 --- /dev/null +++ b/app/lib/features/runs/actions/title_action.dart @@ -0,0 +1,109 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../data/runs_repository.dart'; +import 'action_refusal.dart'; +import 'title_dialog.dart'; +import 'title_wording.dart'; + +/// The run detail's rename entry point, mirroring the browser's rename row. +/// +/// The prompt starts with [run]'s stored title exactly as the server sent it +/// (never a prompt or output fallback). Typing and Cancel send nothing; only +/// Save sends `set_run_title` with the exact run id and title text. A refusal is +/// returned verbatim to the kept-open prompt, and only the server's returned +/// `run_detail` is delivered through [onRunChanged], once. +class RunTitleAction extends StatefulWidget { + const RunTitleAction({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + + @override + State createState() => _RunTitleActionState(); +} + +class _RunTitleActionState extends State { + bool _dialogOpen = false; + bool _saving = false; + + bool _usesCupertino(BuildContext context) { + final material = Localizations.of( + context, + MaterialLocalizations, + ); + return material == null; + } + + Future _open() async { + final id = runTitleId(widget.run); + if (id == null || _dialogOpen) return; + _dialogOpen = true; + try { + await showRunTitlePrompt( + context: context, + runId: id, + initialTitle: storedRunTitle(widget.run), + cupertino: _usesCupertino(context), + onSubmit: (title) => _submit(id, title), + ); + } finally { + _dialogOpen = false; + if (mounted) setState(() {}); + } + } + + Future _submit(num id, String title) async { + if (_saving) return const ActionRefusal(actionAlreadySending); + _saving = true; + try { + final run = await RunsRepository(widget.gateway).setRunTitle(id, title); + if (!mounted) return null; + if (_owns(id)) widget.onRunChanged(run); + return null; + } catch (error) { + return ActionRefusal(describeTitleError(error)); + } finally { + _saving = false; + } + } + + bool _owns(num id) => mounted && runTitleId(widget.run) == id; + + @override + Widget build(BuildContext context) { + if (runTitleId(widget.run) == null) return const SizedBox.shrink(); + if (_usesCupertino(context)) { + return CupertinoButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } + return OutlinedButton( + key: runTitleActionKey, + onPressed: _open, + child: const Text(runTitleActionLabel), + ); + } +} + +/// The run id used by the rename request, or null for a malformed run. +num? runTitleId(JsonMap run) { + final id = run['id']; + return id is num ? id : null; +} + +/// The run's stored title exactly as the browser reads it +/// (`String(d.title ?? "")`); never inferred from the prompt or output. +String storedRunTitle(JsonMap run) { + final title = run['title']; + return title == null ? '' : '$title'; +} diff --git a/app/lib/features/runs/actions/title_dialog.dart b/app/lib/features/runs/actions/title_dialog.dart new file mode 100644 index 00000000..9ae03a11 --- /dev/null +++ b/app/lib/features/runs/actions/title_dialog.dart @@ -0,0 +1,183 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'action_refusal.dart'; +import 'title_wording.dart'; + +/// Sends the typed title. Returns null once the server has accepted it, or an +/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays +/// open with the typed title intact. +typedef TitleSubmit = Future Function(String title); + +/// Opens the native rename prompt for [runId], seeded with the run's stored +/// [initialTitle]. +/// +/// Typing and the dismiss action send nothing; only Save sends the title. The +/// title is passed through exactly as typed, including surrounding whitespace, +/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether +/// a blank title is acceptable. +Future showRunTitlePrompt({ + required BuildContext context, + required num runId, + required String initialTitle, + required bool cupertino, + required TitleSubmit onSubmit, +}) { + final prompt = _TitlePrompt( + runId: runId, + initialTitle: initialTitle, + cupertino: cupertino, + onSubmit: onSubmit, + ); + if (cupertino) { + return showCupertinoDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); + } + return showDialog( + context: context, + barrierDismissible: false, + builder: (_) => prompt, + ); +} + +class _TitlePrompt extends StatefulWidget { + const _TitlePrompt({ + required this.runId, + required this.initialTitle, + required this.cupertino, + required this.onSubmit, + }); + + final num runId; + final String initialTitle; + final bool cupertino; + final TitleSubmit onSubmit; + + @override + State<_TitlePrompt> createState() => _TitlePromptState(); +} + +class _TitlePromptState extends State<_TitlePrompt> { + late final TextEditingController _title = TextEditingController( + text: widget.initialTitle, + ); + bool _sending = false; + String? _error; + + @override + void dispose() { + _title.dispose(); + super.dispose(); + } + + void _cancel() { + if (!_sending) Navigator.of(context).pop(); + } + + Future _save() async { + if (_sending) return; + setState(() { + _sending = true; + _error = null; + }); + final refusal = await widget.onSubmit(_title.text); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).pop(); + return; + } + setState(() { + _sending = false; + _error = refusal.message; + }); + } + + @override + Widget build(BuildContext context) { + final dialog = widget.cupertino ? _cupertino(context) : _material(context); + return PopScope(canPop: !_sending, child: dialog); + } + + Widget _material(BuildContext context) { + final theme = Theme.of(context); + return AlertDialog( + scrollable: true, + title: const Text(runTitleDialogTitle), + content: _body( + field: TextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + decoration: const InputDecoration(labelText: runTitleFieldLabel), + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle(color: theme.colorScheme.error), + ), + actions: [ + TextButton( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + FilledButton( + key: runTitleSaveKey, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _cupertino(BuildContext context) { + return CupertinoAlertDialog( + title: const Text(runTitleDialogTitle), + content: _body( + field: CupertinoTextField( + key: runTitleFieldKey, + controller: _title, + enabled: !_sending, + autofocus: true, + placeholder: runTitleFieldLabel, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _save(), + ), + errorStyle: TextStyle( + color: CupertinoColors.systemRed.resolveFrom(context), + ), + ), + actions: [ + CupertinoDialogAction( + key: runTitleCancelKey, + onPressed: _sending ? null : _cancel, + child: const Text(runTitleCancelLabel), + ), + CupertinoDialogAction( + key: runTitleSaveKey, + isDefaultAction: true, + onPressed: _sending ? null : _save, + child: const Text(runTitleSaveLabel), + ), + ], + ); + } + + Widget _body({required Widget field, required TextStyle errorStyle}) { + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + field, + if (_error case final error?) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error, key: runTitleErrorKey, style: errorStyle), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/actions/title_wording.dart b/app/lib/features/runs/actions/title_wording.dart new file mode 100644 index 00000000..8fa85891 --- /dev/null +++ b/app/lib/features/runs/actions/title_wording.dart @@ -0,0 +1,24 @@ +import 'package:flutter/widgets.dart'; + +/// The browser client's rename wording, kept verbatim. +const runTitleActionLabel = 'Rename'; +const runTitleDialogTitle = 'Rename'; +const runTitleFieldLabel = 'Run title'; +const runTitleSaveLabel = 'Save'; +const runTitleCancelLabel = 'Cancel'; + +/// Stable test/semantics keys shared by the action and its prompt. +const runTitleActionKey = ValueKey('rename-run-action'); +const runTitleFieldKey = ValueKey('rename-run-field'); +const runTitleSaveKey = ValueKey('rename-run-save'); +const runTitleCancelKey = ValueKey('rename-run-cancel'); +const runTitleErrorKey = ValueKey('rename-run-error'); + +/// The server's refusal, verbatim. Only a blank error gets a generic sentence +/// so the prompt never claims a rename that did not happen. +String describeTitleError(Object error) { + final message = '$error'; + return message.trim().isEmpty + ? 'The server did not rename the run.' + : message; +} diff --git a/app/lib/features/schedules/data/schedules_repository.dart b/app/lib/features/schedules/data/schedules_repository.dart new file mode 100644 index 00000000..432bf841 --- /dev/null +++ b/app/lib/features/schedules/data/schedules_repository.dart @@ -0,0 +1,116 @@ +import '../../../core/api_gateway.dart'; +import '../domain/saved_schedule.dart'; +import '../domain/schedule_json.dart'; + +/// Client-side protocol failure. Server refusals and transport errors are not +/// wrapped: [ApiGateway] already surfaces their exact text. +class SchedulesRepositoryException implements Exception { + const SchedulesRepositoryException(this.message); + final String message; + @override + String toString() => message; +} + +/// The saved-schedule commands of the current web client. +/// +/// These are run configurations, not pipeline definitions: this repository +/// never submits, validates or publishes a workflow, and it never starts or +/// polls a run. Timer execution belongs to the server. +class SchedulesRepository { + SchedulesRepository(this._gateway); + + final ApiGateway _gateway; + + /// Lists saved schedules, optionally for one pipeline. + /// + /// An explicit empty reply is a valid empty list. A reply without the + /// `schedules` type is not: that is an older/unsupported server and must be + /// reported rather than shown as "no schedules". + Future> listSchedules({int? pipelineId}) async { + final fields = {}; + if (pipelineId != null) { + if (!_isPositiveId(pipelineId)) { + throw const SchedulesRepositoryException( + 'A positive pipeline ID is required.', + ); + } + fields['pipeline_id'] = pipelineId; + } + final reply = await _gateway.call('list_schedules', fields); + final schedules = reply['schedules']; + if (reply['type'] != 'schedules' || + (schedules != null && schedules is! List)) { + throw const SchedulesRepositoryException( + 'The server returned no schedules response.', + ); + } + if (schedules == null) return const []; + return [ + for (final item in schedules as List) + if (item is Map) + SavedSchedule(Map.from(item)) + else + throw const SchedulesRepositoryException( + 'The server returned an invalid schedule record.', + ), + ]; + } + + /// Creates or updates one saved schedule. + /// + /// Creation sends the web client's sentinel record (`id` 0, no revision) and + /// may carry a stable request key so a lost reply is retried instead of + /// creating a duplicate. Updating sends the record read from the server, + /// whose `revision` is the compare-and-swap token; the key is omitted, as in + /// the web client. A stale revision is refused by the server and propagated + /// unchanged, never overwritten locally. + Future saveSchedule( + JsonMap schedule, { + String? requestKey, + }) async { + if (requestKey != null && requestKey.length > 128) { + throw const SchedulesRepositoryException( + 'Schedule request keys must be strings of at most 128 characters.', + ); + } + final fields = {'schedule': cloneJsonMap(schedule)}; + if (requestKey != null && requestKey.isNotEmpty) { + fields['request_key'] = requestKey; + } + final reply = await _gateway.call('save_schedule', fields); + final saved = reply['schedule']; + if (saved is! Map) { + throw const SchedulesRepositoryException( + 'The server returned no saved schedule.', + ); + } + return SavedSchedule(Map.from(saved)); + } + + /// Deletes exactly the revision the caller read. + /// + /// Both identity and revision are required before any request is sent; a + /// confirmation for a different schedule is treated as a failed delete. + Future deleteSchedule(int id, int revision) async { + if (!_isPositiveId(id) || !_isPositiveId(revision)) { + throw const SchedulesRepositoryException( + 'An exact schedule ID and revision are required.', + ); + } + final reply = await _gateway.call('delete_schedule', { + 'schedule_id': id, + 'expected_revision': revision, + }); + if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) { + throw const SchedulesRepositoryException( + 'The server did not confirm deletion of this schedule.', + ); + } + } +} + +/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks +/// `Number.isSafeInteger` before sending an identity. +const _maxSafeInteger = 9007199254740991; + +bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger; diff --git a/app/lib/features/schedules/domain/saved_schedule.dart b/app/lib/features/schedules/domain/saved_schedule.dart new file mode 100644 index 00000000..32570b72 --- /dev/null +++ b/app/lib/features/schedules/domain/saved_schedule.dart @@ -0,0 +1,87 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; +import 'schedule_rule.dart'; + +/// One saved run configuration from `list_schedules` or `save_schedule`. +/// +/// A saved schedule is a complete run request pinned to one pipeline version. +/// It is deliberately not a pipeline definition: nothing here is published, +/// validated as a graph or treated as the pipeline's current version. +/// +/// [raw] keeps the exact server record, including fields this client does not +/// know yet. Typed getters are views; they never rewrite [raw]. +class SavedSchedule { + SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw); + + final JsonMap raw; + + /// Server identity; null when an older reply omits it. Never defaulted to 0, + /// because 0 is the create sentinel rather than a saved identity. + int? get id => _integer(raw['id']); + + /// Compare-and-swap token. Updates reuse it and deletes send it as + /// `expected_revision`; this client never invents or increments it. + int? get revision => _integer(raw['revision']); + + int? get pipelineId => _integer(raw['pipeline_id']); + int? get version => _integer(raw['version']); + String get name => _text(raw['name']); + bool get enabled => raw['enabled'] == true; + + JsonMap get input => _map(raw['input']); + String get prompt => _text(input['prompt']); + String get workspace => _text(raw['workspace']); + ScheduleRule get rule => ScheduleRule(_map(raw['rule'])); + + List get writePaths => _texts(raw['write_paths']); + bool get allowTools => raw['allow_tools'] == true; + String get model => _text(raw['model']); + Map get stageModels => { + for (final entry in _map(raw['stage_models']).entries) + if (entry.value is String) entry.key: entry.value as String, + }; + String get notifyMode => _text(raw['notify_mode']); + String get title => _text(raw['title']); + String get outputFormat => _text(raw['output_format']); + + String get nextDue => _text(raw['next_due']); + String get createdAt => _text(raw['created_at']); + String get updatedAt => _text(raw['updated_at']); + + /// The record to pass to `save_schedule`, deep-copied so callers cannot + /// mutate this snapshot by aliasing. + JsonMap toJson() => cloneJsonMap(raw); + + /// Pause/enable copy. Identity, revision and every unknown field are kept so + /// the update still targets the revision this record was read at. + SavedSchedule withEnabled(bool value) { + final copy = toJson(); + copy['enabled'] = value; + return SavedSchedule(copy); + } +} + +int? _integer(dynamic value) { + if (value is int) return value; + if (value is num && value.isFinite && value == value.truncateToDouble()) { + return value.toInt(); + } + return null; +} + +String _text(dynamic value) => value is String ? value : ''; + +JsonMap _map(dynamic value) { + if (value is! Map) return {}; + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/lib/features/schedules/domain/schedule_json.dart b/app/lib/features/schedules/domain/schedule_json.dart new file mode 100644 index 00000000..a0e541bf --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_json.dart @@ -0,0 +1,22 @@ +import '../../../core/api_gateway.dart'; + +/// Deep copy of a decoded JSON value. +/// +/// Saved schedules travel back to the server unchanged, so unknown fields (and +/// unknown nested values) must survive every round trip without sharing state +/// with the reply map that produced them. +dynamic cloneJsonValue(dynamic value) { + if (value is Map) { + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; + } + if (value is List) { + return [for (final item in value) cloneJsonValue(item)]; + } + return value; +} + +JsonMap cloneJsonMap(JsonMap value) => + Map.from(cloneJsonValue(value) as Map); diff --git a/app/lib/features/schedules/domain/schedule_rule.dart b/app/lib/features/schedules/domain/schedule_rule.dart new file mode 100644 index 00000000..7eb4bed5 --- /dev/null +++ b/app/lib/features/schedules/domain/schedule_rule.dart @@ -0,0 +1,41 @@ +import '../../../core/api_gateway.dart'; +import 'schedule_json.dart'; + +/// Weekday keys the server accepts for an interval rule. +const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']; + +/// The timer part of a saved schedule (`rule` on the wire). +/// +/// This is a view over the decoded server record, not a timer implementation: +/// it never calculates due times, converts timezones or starts runs. Unknown +/// rule fields stay in [raw] and are returned by [toJson]. +class ScheduleRule { + ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {}); + + final JsonMap raw; + + /// Go-style duration such as `24h` or `1h30m`; empty for a clock rule. + String get every => _text(raw['every']); + + /// Distinct 24-hour times such as `09:00`; empty for an interval rule. + List get times => _texts(raw['times']); + + /// Empty means every day (written as absent on the wire). + List get days => _texts(raw['days']); + + /// Empty or `Local` means the server's timezone. + String get timezone => _text(raw['timezone']); + + bool get isClock => times.isNotEmpty; + + JsonMap toJson() => cloneJsonMap(raw); +} + +String _text(dynamic value) => value is String ? value : ''; + +List _texts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; diff --git a/app/notes/R2c.md b/app/notes/R2c.md new file mode 100644 index 00000000..f2240602 --- /dev/null +++ b/app/notes/R2c.md @@ -0,0 +1,114 @@ +# R2c — native retry / restart action + +Small app-only addition, new files only. `RetryRunAction(run, gateway, +onRunChanged)` is the deliberate retry entry point for a stopped failed run; it +does not add a screen or controller and is not wired into the shell. + +## What changed + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/retry_action.dart` | 123 | `RetryRunAction`, gating, send/refusal/resync orchestration | +| `lib/features/runs/actions/retry_dialog.dart` | 207 | Native resume/restart confirmation, refusal display, key lifetime | +| `lib/features/runs/actions/retry_eligibility.dart` | 16 | `canRetryRun` mirroring the web `canRetry` | +| `lib/features/runs/actions/retry_intent.dart` | 29 | Mode, confirmed intent and idempotency-key generation | +| `lib/features/runs/actions/retry_wording.dart` | 33 | Web-verbatim words, titles, error wording and test keys | +| `test/.../retry_test_support.dart` | 112 | Fake gateway and Material/Cupertino hosts | +| `test/.../retry_action_test.dart` | 245 | Eligibility, both platforms, modes and key fields | +| `test/.../retry_resilience_test.dart` | 223 | Immediate refusals, recheck outcomes, key retention | +| `test/.../retry_safety_test.dart` | 133 | Double submit, late replies, narrow 2x layout | + +No repository, gateway, socket, controller, shell, main, pubspec, web, server or +device file was edited. + +## Behavior + +Eligibility is exactly the browser's rule: a loaded run that is not executing and +whose status is `failed` (`run != null && !run.executing && status == "failed"`). +A stale `failed` status while execution is still in flight, a running/waiting/ +succeeded/canceled run, and a malformed run render nothing. + +The button is a Material `FilledButton` or a Cupertino `CupertinoButton.filled`, +labelled `Retry`. Opening the prompt sends nothing, and `Keep` only closes it. + +The first confirmation is the browser's retry copy: title `Retry run {id}?`, +message `Only failed runs can be retried. The server starts a new run from the +same input.`, confirm `Retry`, dismiss `Keep`, plus the browser-only secondary +`Restart from start` that leads to a distinct confirmation. That second prompt +uses title `Restart run {id}?`, message `This replays the whole pipeline from the +start instead of resuming the failed stage.` and confirm `Restart from start`; +the resume actions are gone, so the more destructive choice cannot be mistaken +for resume. + +Resume calls `RunsRepository.retryRun` with only `run_id` and `request_key`, so +`retry_mode` is omitted and the server's `resume` default applies. Restart sends +`retry_mode: "restart"` with the same two required fields. + +A `request_key` is created on the first confirm of an open prompt, not on opening +or `Keep`. It survives a refusal, so pressing confirm again for the same +uncertain request reuses the key and the server can dedupe it. Closing the prompt +and opening it again is a fresh deliberate intent and gets a new key, so a resume +attempt followed by a restart attempt never shares a key. Switching to the +restart confirmation before any send simply confirms restart with that prompt's +first key. Keys are bounded and run-scoped (`app-retry-{runId}-…`, well under the +server's 128-character cap). + +A server refusal returns to the prompt immediately: the exact server words are +visible and `Keep`/back are available while the detached `get_run` recheck is +still pending. One bounded re-read is issued per refusal, single-flight through a +retained future, with no retry loop or polling. If server truth says the run is no +longer retryable, confirm is disabled and an attempted tap sends nothing; the +refusal stays visible until dismissal. If the recheck itself fails, truth is +unknown, so confirm is re-enabled and a deliberate retry uses the retained key. +Late retry replies and late rechecks after disposal or navigation are ignored. + +Construction, controls and error colour are standard Material/Cupertino defaults; +there is no custom palette, fixed control size or dependency. The narrow layout +relies on the native dialog's own scrolling/wrapping. + +## Acceptance checks + +Fake-gateway widget tests, both platforms, no socket or real server: + +- eligibility table for stopped failed vs executing failed, running, waiting, + succeeded and canceled runs, plus the same visibility table under both apps; +- `Retry` opens the native `AlertDialog`/`CupertinoAlertDialog`, `Keep` closes it + and the recorded gateway calls are still empty; +- resume sends exactly `{run_id, request_key}` and no `retry_mode`; restart sends + exactly `{run_id, request_key, retry_mode: "restart"}`; +- key format is deterministic under an injected clock/entropy, bounded, fresh per + call, retained across an uncertain retry (resume and restart), and different + after a deliberate reopen or mode change; +- refusal message appears while `get_run` is deliberately unresolved, with Keep + enabled, confirm disabled and no callback yet; Keep then closes and the late + recheck still delivers server truth safely; +- ineligible recheck (`succeeded`) blocks a repeat action; failed recheck leaves + the same key and a working deliberate retry; +- two confirm taps while in flight produce one `retry_run`; both the retry reply + and the recheck are safe after disposal; +- 320×480 at 2× text: both resume and restart confirmations render on both apps + with no exception, and Keep sends nothing. + +## Checks actually run + +``` +dart format lib/features/runs/actions test/features/runs/actions # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions # 40 passed +flutter test # 69 passed +flutter build web # Built build/web (14.5s) +``` + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no runs screen or + controller; the manager owns that integration. There is no browser interaction + or rendered capture for this widget, and `flutter build web` proves compilation + only, not rendered behavior. +- Browser parity is by source/word/request-shape comparison with + `web/src/actions.js` and `web/src/repository.js`; the web client itself was not + changed and no live web retry was performed. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. +- No real server or run was retried, canceled or otherwise mutated; all evidence + uses local fakes. +- The candidate is committed, not pushed or deployed. diff --git a/app/notes/R2d.md b/app/notes/R2d.md new file mode 100644 index 00000000..c262351f --- /dev/null +++ b/app/notes/R2d.md @@ -0,0 +1,93 @@ +# R2d — native run title rename + +## What changed + +New `lib/features/runs/actions/title*` slice plus its tests and this note. No +existing source file was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/runs/actions/title_wording.dart` | 24 | Web-verbatim words, test keys, refusal wording | +| `lib/features/runs/actions/title_dialog.dart` | 183 | Native Material/Cupertino text-field prompt and inline refusal | +| `lib/features/runs/actions/title_action.dart` | 109 | `RunTitleAction`, stored-title seeding, send/deliver orchestration | +| `test/features/runs/actions/title_test_support.dart` | 110 | Fake gateway, run fixtures, stateful host, app wrappers | +| `test/features/runs/actions/title_action_test.dart` | 244 | Both-platform open/cancel/exact-save and stored-title seeding | +| `test/features/runs/actions/title_resilience_test.dart` | 243 | Refusal retention, double save, disposal, stale owner, 2x/narrow | + +`RunTitleAction(run: …, gateway: …, onRunChanged: …)` renders one native +`OutlinedButton` (`Rename`) on Material and one plain `CupertinoButton` on +Cupertino, and nothing for a run without a numeric id. Platform style follows the +enclosing app (`MaterialLocalizations` presence). No style overrides, fixed +component sizes or new dependencies. + +## Behaviour and web parity + +The prompt is seeded with the run's actual stored title exactly as the browser +reads it, `String(d.title ?? "")` in `web/src/views/runDetail.js`. It is never +derived from `input.prompt`, stage output or a placeholder. A missing title seeds +an empty field. + +Typing, opening and the dismiss action send nothing. Only `Save` calls the +existing `RunsRepository.setRunTitle(id, title)`, which sends the exact envelope: + +``` +set_run_title {"run_id": , "title": } +``` + +The field text is passed through untrimmed, matching `repo.setRunTitle(id, +String(state.renameValue ?? ""))` in `web/src/repository.js`. Leading/trailing +spaces and Unicode are preserved, and a blank title is sent as `""` so the server, +not the client, decides whether it is acceptable. There is no local +`canSubmit` gate on blank text. + +A refusal (including a blank-title refusal) is shown verbatim below the field and +the prompt stays open with the typed draft intact. Nothing is updated locally. +Only an accepted reply closes the prompt and passes the server's returned +`run_detail` once through `onRunChanged`; the action never fabricates a run or a +title. A second Save tap while sending is ignored, both dialog actions disable +until the reply, and every asynchronous resume checks `mounted`. A reply for a run +the widget no longer owns is dropped. + +## Checks actually run + +``` +dart format lib/features/runs/actions/title*.dart \ + test/features/runs/actions/title*.dart # clean +flutter analyze # No issues found! +flutter test test/features/runs/actions/title_action_test.dart \ + test/features/runs/actions/title_resilience_test.dart # 11 passed +flutter test test/features/runs # 45 passed +flutter test # 63 passed +flutter build web # Built build/web (16.2s) +``` + +Focused acceptance coverage: + +- both platforms: native button and dialog, stored title in the field, typing and + Cancel produce zero gateway calls, Save sends exact `set_run_title` fields; +- exact field values: Unicode plus leading/trailing whitespace preserved; blank + title sent as `""` and the server refusal shown with the blank draft retained; +- failed save: server words verbatim, draft retained, dialog open, no callback and + no local title change; transport failure likewise; +- double Save: one request, action buttons disabled while in flight; +- disposal: a late reply after the tree is replaced throws nothing and delivers + nothing; a reply after the widget's run id changes is not delivered; +- 320x480 at 2x text: both prompts open, show a long title and a refusal, and close + with no rendering exception; +- malformed run: no rename button, and the stored-title helper ignores prompts. + +## Honest limits + +- **Not wired into a run-detail screen.** This branch has no run-detail screen or + controller; the manager owns integration. No real browser interaction or + capture was performed, so rendered feature parity is not claimed. `flutter build + web` proves compilation of the existing entrypoint, not that this widget is + reachable or visible. +- **Mobile unverified.** No Android/iOS build, emulator, ADB or device was used. + Source uses portable Flutter/Cupertino/Material widgets only. +- No real server, operator run or chat was touched. Tests use a local fake gateway + with no socket. +- No repository/domain/controller/shell/main/pubspec, `web/`, Go server, + installer or deployment file was changed. +- Nothing was committed, pushed or deployed; the files above are the candidate in + the working tree, per the stage instruction not to commit. diff --git a/app/notes/S1a.md b/app/notes/S1a.md new file mode 100644 index 00000000..58426e32 --- /dev/null +++ b/app/notes/S1a.md @@ -0,0 +1,94 @@ +# S1a — saved-schedule repository and record + +## What changed + +New, app-only files (no existing feature, shell, transport, `main` or pubspec +source edited): + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/data/schedules_repository.dart` | 116 | `list_schedules`, `save_schedule`, `delete_schedule` envelopes and reply checks | +| `lib/features/schedules/domain/saved_schedule.dart` | 87 | typed view over one saved run configuration; exact raw record retained | +| `lib/features/schedules/domain/schedule_rule.dart` | 41 | interval/clock/timezone/weekday fields of `rule` | +| `lib/features/schedules/domain/schedule_json.dart` | 22 | deep JSON copy used by every round trip | +| `test/features/schedules/data/schedules_repository_test.dart` | 132 | list/create/update envelopes, unchanged input, CAS revision | +| `test/features/schedules/data/schedules_delete_test.dart` | 131 | delete envelope, confirmations, refusals, missing/empty replies | +| `test/features/schedules/data/schedules_protocol_bounds_test.dart` | 81 | web-mirrored ID/revision/request-key bounds | +| `test/features/schedules/data/saved_schedule_record_test.dart` | 101 | provenance, unknown fields, deep-copy and absent-field behavior | +| `test/features/schedules/data/schedule_test_support.dart` | 83 | recording fake gateway and server-shaped fixtures | + +`app/.gitignore` also gained the missing `!/test/**/data/` exception. The root +`.gitignore` ignores every `data/` directory, so without it these assigned tests +would silently disappear from a fresh checkout. The existing `!/lib/**/data/` +exception is for the same reason. + +## Behavior copied from the current web client + +Requests are exactly the ones in `web/src/repository.js`: + +- `list_schedules` with no field, or `pipeline_id` for one pipeline. A positive + safe integer is required before sending; `{type:"schedules"}` or + `schedules:null` is an empty list, while a reply without `type:"schedules"` is + an error, not "no schedules". +- `save_schedule` with `schedule` unchanged. A non-empty `request_key` (at most + 128 characters) is added only for a create retry; updates omit it, as the web + editor does. Creation keeps the web sentinel `id: 0` and no revision. Updates + send the record read from the server, whose `revision` is the server's + compare-and-swap token. The reply is only accepted when it contains + `schedule`. +- `delete_schedule` with exactly `schedule_id` and `expected_revision`; only + `{type:"schedule_deleted", schedule_id:}` counts as success. + +Server refusals are not wrapped or translated. `ApiGateway` already turns an +`error` envelope into `ProtocolError` with the server's text, and the repository +lets that object through unchanged (conflict and unknown-command coverage in +`server refusals and conflicts propagate verbatim`). The repository has no +capability flags, no "not supported" substitution and no local fallback. + +Saved schedules are run configurations, never pipeline definitions. `SavedSchedule` +keeps the complete server map, including unknown future nested fields, and +exposes pipeline, version, prompt/input, workspace, rule (every/times/days/ +timezone), enabled, model/stage models, notify mode, write paths/tools, title, +output format, due time and timestamps. `toJson()` is a deep copy; `withEnabled` +preserves identity, revision and unknowns. Missing identity/revision stays +`null` rather than becoming a fabricated `0`. There is no timer execution, +polling, rule parsing into due dates or timezone conversion in this slice. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules test/features/schedules # 9 files, 5 changed, then clean +flutter test test/features/schedules/data # 18 passed +flutter analyze # No issues found! (1.4s) +flutter test # 70 passed +``` + +Focused coverage maps to the requested acceptance: + +- exact `list_schedules`/`save_schedule`/`delete_schedule` bodies recorded by a + fake gateway, including `expected_revision` only on delete and no invented + create revision/key; +- untouched caller record on save; deep equality of returned records with the + server reply including unknown top-level/rule/input fields; +- update reuses revision 3, accepts server revision 4 and leaves the stale draft + at 3; a mismatch is the server's refusal, propagated verbatim; +- empty list vs missing/unsupported schedules reply, missing/invalid saved + schedule, and delete confirmation for the wrong id/type; +- preflight bounds match the web client: pipeline id, schedule id, revision and + 129-character request keys send nothing; 128 characters is accepted; +- no fabricated identity when a reply contains an empty schedule object. + +## Honest limits + +- **No UI or wiring.** There is no schedules screen, editor, pause/delete control + or shell registration in this slice; the manager owns later UI integration. + No browser interaction or screenshot applies to this nonvisual item. +- **No live server used.** All checks use local recording fakes; no production + schedule, run or workflow was created, changed or deleted. No polling or + scheduler was touched. +- **Mobile unverified.** Only web-targeted Flutter tests and analysis ran. No + Android/iOS build, emulator, ADB or device was used; the code is pure Dart. +- **Not committed.** The stage instruction for this visit forbids commit, push + and deploy, so the candidate remains in the `flutter/s1-data` worktree for the + manager to inspect and commit. No deployment or preview was performed. diff --git a/app/test/features/runs/actions/retry_action_test.dart b/app/test/features/runs/actions/retry_action_test.dart new file mode 100644 index 00000000..ca11fa8b --- /dev/null +++ b/app/test/features/runs/actions/retry_action_test.dart @@ -0,0 +1,245 @@ +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/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_intent.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + test('retry eligibility matches the web canRetry exactly', () { + final cases = <(String, JsonMap, bool)>[ + ('failed and stopped', failedRun(), true), + ('failed but still executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final (label, run, expected) in cases) { + expect(canRetryRun(run), expected, reason: label); + } + expect(canRetryRun(null), isFalse); + expect(retryRunId(failedRun()), 7); + expect(retryRunId({'id': '7'}), isNull); + }); + + test('a generated retry key is bounded, run-scoped and fresh', () { + final first = newRetryRequestKey(7); + final second = newRetryRequestKey(7); + + expect(first, startsWith('app-retry-7-')); + expect(first.length, lessThanOrEqualTo(128)); + expect(second.length, lessThanOrEqualTo(128)); + expect(first, isNot(second)); + expect( + newRetryRequestKey(7, now: DateTime.utc(2026, 1, 1), random: 36), + 'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-10', + ); + }); + + testWidgets( + 'material retry asks first, Keep sends nothing, then omits retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(FilledButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + find.descendant( + of: find.byType(AlertDialog), + matching: find.text(retryConfirmLabel), + ), + findsOneWidget, + ); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields.keys, containsAll(['run_id', 'request_key'])); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['run_id'], 7); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(fields['request_key'].length, lessThanOrEqualTo(128)); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + }, + ); + + testWidgets( + 'material restart has its own confirmation and sends retry_mode', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(find.text(retryDialogTitle(7)), findsNothing); + expect(find.text(retryDialogMessage), findsNothing); + expect(find.text(restartConfirmLabel), findsOneWidget); + expect(find.byKey(retryRestartKey), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields['retry_mode'], 'restart'); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + }, + ); + + testWidgets( + 'cupertino retry uses a native prompt and sends only on confirm', + (tester) async { + final accepted = retriedRun(); + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await pumpRetry( + tester, + gateway: gateway, + changed: changed, + cupertino: true, + ); + + expect(find.byKey(retryActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(FilledButton), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + expect(find.byType(CupertinoAlertDialog), findsNothing); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(1)); + final fields = gateway.retries.single.fields; + expect(fields['run_id'], 7); + expect(fields.containsKey('retry_mode'), isFalse); + expect(fields['request_key'], startsWith('app-retry-7-')); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }, + ); + + testWidgets('cupertino restart switches to the restart confirmation', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: true, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + expect(gateway.retries.single.fields['retry_mode'], 'restart'); + }); + + testWidgets('the action is absent for runs the web does not retry', ( + tester, + ) async { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + final changed = []; + final cases = <(String, JsonMap, bool)>[ + ('failed', failedRun(), true), + ('executing', failedRun(executing: true), false), + ('running', failedRun(status: 'running'), false), + ('waiting', failedRun(status: 'waiting'), false), + ('succeeded', failedRun(status: 'succeeded'), false), + ('canceled', failedRun(status: 'canceled'), false), + ]; + for (final cupertino in [false, true]) { + for (final (label, run, visible) in cases) { + await tester.pumpWidget( + retryApp( + RetryHost( + key: ValueKey('$label-$cupertino'), + gateway: gateway, + initial: run, + changed: changed, + ), + cupertino: cupertino, + ), + ); + expect( + find.byKey(retryActionKey), + visible ? findsOneWidget : findsNothing, + reason: '$label cupertino=$cupertino', + ); + } + } + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); +} diff --git a/app/test/features/runs/actions/retry_resilience_test.dart b/app/test/features/runs/actions/retry_resilience_test.dart new file mode 100644 index 00000000..26053426 --- /dev/null +++ b/app/test/features/runs/actions/retry_resilience_test.dart @@ -0,0 +1,223 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_eligibility.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +Future _openAndConfirm(WidgetTester tester) async { + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); +} + +void main() { + testWidgets('a refusal is shown at once and Keep does not wait for resync', ( + tester, + ) async { + const refusal = 'run 7 is still executing; wait for it to stop completely'; + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError(refusal); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pump(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(retryErrorKey), findsOneWidget); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect(changed, isEmpty); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + + resync.complete({'run_detail': failedRun(status: 'succeeded')}); + await tester.pump(); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed.single['status'], 'succeeded'); + expect(find.byKey(retryActionKey), findsNothing); + }); + + testWidgets('server truth that is ineligible blocks a repeat action', ( + tester, + ) async { + const refusal = 'only failed runs can be retried'; + final finished = failedRun(status: 'succeeded'); + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'retry_run') throw const ProtocolError(refusal); + return {'run_detail': finished}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNotNull, + ); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byKey(retryActionKey), findsNothing); + expect(changed.single, equals(finished)); + expect(canRetryRun(changed.single), isFalse); + }); + + testWidgets('a failed recheck keeps the same key for the uncertain request', ( + tester, + ) async { + const refusal = 'connection dropped while retrying'; + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError(refusal); + return {'run_detail': retriedRun()}; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(find.text(refusal), findsOneWidget); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNotNull, + ); + expect(gateway.retries, hasLength(1)); + + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + expect( + gateway.retries.every((call) => !call.fields.containsKey('retry_mode')), + isTrue, + ); + expect(changed.single, equals(retriedRun())); + expect(find.byType(AlertDialog), findsNothing); + }); + + testWidgets('a restart retry keeps the mode and key across uncertainty', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('network lost'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields['retry_mode'], 'restart'); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.last.fields['request_key'], + gateway.retries.first.fields['request_key'], + ); + }); + + testWidgets('a deliberate reopen sends a fresh request key', (tester) async { + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + throw const ProtocolError('server did not answer'); + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); + + testWidgets('a restart after a dismissed resume uses a fresh key', ( + tester, + ) async { + var attempts = 0; + final gateway = FakeRetryGateway((type, fields) async { + if (type == 'get_run') throw const NotConnectedError(); + attempts += 1; + if (attempts == 1) throw const ProtocolError('resume refused'); + return {'run_detail': retriedRun()}; + }); + await pumpRetry(tester, gateway: gateway, changed: []); + + await _openAndConfirm(tester); + await tester.pumpAndSettle(); + // A refusal leaves the prompt open; keep the mode frozen and dismiss. + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pumpAndSettle(); + + expect(gateway.retries, hasLength(2)); + expect(gateway.retries.first.fields.containsKey('retry_mode'), isFalse); + expect(gateway.retries.last.fields['retry_mode'], 'restart'); + expect( + gateway.retries.first.fields['request_key'], + isNot(gateway.retries.last.fields['request_key']), + ); + }); +} diff --git a/app/test/features/runs/actions/retry_safety_test.dart b/app/test/features/runs/actions/retry_safety_test.dart new file mode 100644 index 00000000..df9e7e88 --- /dev/null +++ b/app/test/features/runs/actions/retry_safety_test.dart @@ -0,0 +1,133 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; + +import 'retry_test_support.dart'; + +void main() { + testWidgets('confirm cannot submit twice while the retry is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + final confirm = find.byKey(retryConfirmKey); + await tester.tap(confirm); + await tester.tap(confirm); + await tester.pump(); + + expect(gateway.retries, hasLength(1)); + expect( + tester.widget(find.byKey(retryConfirmKey)).onPressed, + isNull, + ); + expect( + tester.widget(find.byKey(retryKeepKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': retriedRun()}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + }); + + testWidgets('a late retry reply after disposal is ignored safely', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeRetryGateway((type, fields) => reply.future); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.retries, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a late resync after disposal is ignored safely', (tester) async { + final resync = Completer(); + final gateway = FakeRetryGateway((type, fields) { + if (type == 'retry_run') throw const ProtocolError('refused'); + return resync.future; + }); + final changed = []; + await pumpRetry(tester, gateway: gateway, changed: changed); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(retryConfirmKey)); + await tester.pump(); + expect(gateway.calls.map((call) => call.type), ['retry_run', 'get_run']); + + await tester.pumpWidget(const SizedBox()); + resync.complete({'run_detail': retriedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('both confirmations fit 2x text at a narrow width', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + for (final cupertino in [false, true]) { + final gateway = FakeRetryGateway( + (type, fields) async => {'run_detail': retriedRun()}, + ); + await pumpRetry( + tester, + gateway: gateway, + changed: [], + cupertino: cupertino, + textScale: 2, + ); + + await tester.tap(find.byKey(retryActionKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + expect(find.text(retryDialogMessage), findsOneWidget); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + + await tester.tap(find.byKey(retryRestartKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'restart=$cupertino'); + expect(find.text(restartDialogTitle(7)), findsOneWidget); + expect(find.text(restartDialogMessage), findsOneWidget); + + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.calls, isEmpty); + } + }); +} diff --git a/app/test/features/runs/actions/retry_test_support.dart b/app/test/features/runs/actions/retry_test_support.dart new file mode 100644 index 00000000..67556d05 --- /dev/null +++ b/app/test/features/runs/actions/retry_test_support.dart @@ -0,0 +1,112 @@ +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/retry_action.dart'; + +typedef RetryHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeRetryGateway implements ApiGateway { + FakeRetryGateway(this.handler); + + final RetryHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); + + Iterable<({String type, JsonMap fields})> get retries => + calls.where((call) => call.type == 'retry_run'); +} + +JsonMap failedRun({ + num id = 7, + bool executing = false, + String status = 'failed', + String title = 'Nightly build', +}) => {'id': id, 'title': title, 'status': status, 'executing': executing}; + +JsonMap retriedRun({num id = 8}) => + failedRun(id: id, status: 'running', executing: true, title: 'Retry of 7'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. +class RetryHost extends StatefulWidget { + const RetryHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeRetryGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _RetryHostState(); +} + +class _RetryHostState extends State { + late JsonMap _run = widget.initial; + + @override + Widget build(BuildContext context) { + return RetryRunAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ); + } +} + +Widget retryApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: Center(child: child)), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: Center(child: child)), + ); +} + +Future pumpRetry( + WidgetTester tester, { + required FakeRetryGateway gateway, + required List changed, + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + retryApp( + RetryHost( + gateway: gateway, + initial: run ?? failedRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} diff --git a/app/test/features/runs/actions/title_action_test.dart b/app/test/features/runs/actions/title_action_test.dart new file mode 100644 index 00000000..110fda20 --- /dev/null +++ b/app/test/features/runs/actions/title_action_test.dart @@ -0,0 +1,244 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +String _materialFieldText(WidgetTester tester) => + tester.widget(find.byKey(runTitleFieldKey)).controller!.text; + +String _cupertinoFieldText(WidgetTester tester) => tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + +void main() { + testWidgets( + 'material rename starts from the stored title, typing sends nothing, ' + 'Cancel sends nothing and Save sends the exact text', + (tester) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(OutlinedButton), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsOneWidget); + expect(find.text(runTitleDialogTitle), findsWidgets); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(_materialFieldText(tester), 'Nightly build'); + + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.pump(); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Nightly build'); + await tester.enterText( + find.byKey(runTitleFieldKey), + ' 发布 🚀 — nightly ', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' 发布 🚀 — nightly ', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(AlertDialog), findsNothing); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Release build', + ); + }, + ); + + testWidgets('cupertino rename is native and sends only on Save', ( + tester, + ) async { + final accepted = renamedRun(title: 'Release build'); + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': accepted}, + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: true, + ), + ); + + expect(find.byKey(runTitleActionKey), findsOneWidget); + expect(find.byType(CupertinoButton), findsOneWidget); + expect(find.byType(OutlinedButton), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(find.byType(AlertDialog), findsNothing); + expect(_cupertinoFieldText(tester), 'Nightly build'); + + await tester.enterText(find.byKey(runTitleFieldKey), 'Typed only'); + await tester.pump(); + expect(gateway.calls, isEmpty); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(CupertinoAlertDialog), findsNothing); + expect(gateway.calls, isEmpty); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), 'Release build'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Release build', + }); + expect(changed.single, equals(accepted)); + expect(find.byType(CupertinoAlertDialog), findsNothing); + }); + + testWidgets('a blank title is sent exactly and the server refusal is shown', ( + tester, + ) async { + const refusal = 'title must not be blank'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await tester.pumpWidget( + titleApp( + TitleHost(gateway: gateway, initial: titledRun(), changed: changed), + cupertino: false, + ), + ); + + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(runTitleFieldKey), ''); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.single.fields, {'run_id': 7, 'title': ''}); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_materialFieldText(tester), ''); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + expect( + tester.widget(find.byKey(runTitleSaveKey)).onPressed, + isNotNull, + ); + }); + + testWidgets('the prompt is seeded from the stored title, never the prompt', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + final changed = []; + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun( + title: 'Stored title', + prompt: 'prompt fallback must not appear', + ), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), 'Stored title'); + expect(find.text('prompt fallback must not appear'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(title: null, prompt: 'prompt is not a title'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); + expect(_materialFieldText(tester), ''); + expect(find.text('prompt is not a title'), findsNothing); + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(changed, isEmpty); + }); + + testWidgets('a malformed run has no rename entry point', (tester) async { + final gateway = FakeTitleGateway( + (type, fields) async => {'run_detail': titledRun()}, + ); + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: {'title': 'No id'}, + changed: [], + ), + cupertino: false, + ), + ); + + expect(find.byKey(runTitleActionKey), findsNothing); + expect(gateway.calls, isEmpty); + expect(runTitleId({'title': 'No id'}), isNull); + expect(storedRunTitle({'title': 'Kept'}), 'Kept'); + expect(storedRunTitle({}), ''); + }); +} diff --git a/app/test/features/runs/actions/title_resilience_test.dart b/app/test/features/runs/actions/title_resilience_test.dart new file mode 100644 index 00000000..32a566c3 --- /dev/null +++ b/app/test/features/runs/actions/title_resilience_test.dart @@ -0,0 +1,243 @@ +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/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; + +import 'title_test_support.dart'; + +Future _pump( + WidgetTester tester, + FakeTitleGateway gateway, + List changed, { + bool cupertino = false, + double textScale = 1, + JsonMap? run, +}) async { + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: run ?? titledRun(), + changed: changed, + ), + cupertino: cupertino, + textScale: textScale, + ), + ); +} + +Future _open(WidgetTester tester) async { + await tester.tap(find.byKey(runTitleActionKey)); + await tester.pumpAndSettle(); +} + +String _fieldText(WidgetTester tester, {required bool cupertino}) { + if (cupertino) { + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; + } + return tester + .widget(find.byKey(runTitleFieldKey)) + .controller! + .text; +} + +void main() { + testWidgets('a failed save keeps the prompt open with the draft intact', ( + tester, + ) async { + const refusal = 'rename refused: the run is locked'; + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), ' Renamed draft '); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls.map((call) => call.type), ['set_run_title']); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': ' Renamed draft ', + }); + expect(find.text(refusal), findsOneWidget); + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: false), ' Renamed draft '); + expect(find.byType(AlertDialog), findsOneWidget); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Nightly build', + ); + }); + + testWidgets('a transport failure keeps the server words and the draft', ( + tester, + ) async { + final gateway = FakeTitleGateway( + (type, fields) async => throw const NotConnectedError(), + ); + final changed = []; + await _pump(tester, gateway, changed, cupertino: true); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Unsent title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + + expect(find.byKey(runTitleErrorKey), findsOneWidget); + expect(_fieldText(tester, cupertino: true), 'Unsent title'); + expect(find.byType(CupertinoAlertDialog), findsOneWidget); + expect(changed, isEmpty); + }); + + testWidgets('Save cannot send twice while the rename is in flight', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'One title'); + final save = find.byKey(runTitleSaveKey); + await tester.tap(save); + await tester.tap(save); + await tester.pump(); + + expect( + gateway.calls.where((call) => call.type == 'set_run_title'), + hasLength(1), + ); + expect(tester.widget(save).onPressed, isNull); + expect( + tester.widget(find.byKey(runTitleCancelKey)).onPressed, + isNull, + ); + expect(find.byType(AlertDialog), findsOneWidget); + + reply.complete({'run_detail': renamedRun(title: 'One title')}); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(changed, hasLength(1)); + expect(changed.single['title'], 'One title'); + }); + + testWidgets('a late reply after disposal is ignored safely', (tester) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + expect(gateway.calls, hasLength(1)); + + await tester.pumpWidget(const SizedBox()); + reply.complete({'run_detail': renamedRun()}); + await tester.pump(); + + expect(tester.takeException(), isNull); + expect(changed, isEmpty); + }); + + testWidgets('a reply for a run the widget no longer owns is not delivered', ( + tester, + ) async { + final reply = Completer(); + final gateway = FakeTitleGateway((type, fields) => reply.future); + final changed = []; + await _pump(tester, gateway, changed); + + await _open(tester); + await tester.enterText(find.byKey(runTitleFieldKey), 'Run seven title'); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pump(); + + await tester.pumpWidget( + titleApp( + TitleHost( + gateway: gateway, + initial: titledRun(id: 8, title: 'Another run'), + changed: changed, + ), + cupertino: false, + ), + ); + await tester.pump(); + reply.complete({'run_detail': renamedRun(title: 'Run seven title')}); + await tester.pumpAndSettle(); + + expect(tester.takeException(), isNull); + expect(gateway.calls.single.fields, { + 'run_id': 7, + 'title': 'Run seven title', + }); + expect(changed, isEmpty); + expect( + tester.widget(find.byKey(titleHostTitleKey)).data, + 'Another run', + ); + }); + + testWidgets('both prompts fit 2x text at a narrow width', (tester) async { + tester.view.physicalSize = const Size(320, 480); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + + const refusal = 'the title is too long for this run; shorten it'; + for (final cupertino in [false, true]) { + final gateway = FakeTitleGateway( + (type, fields) async => throw const ProtocolError(refusal), + ); + await _pump( + tester, + gateway, + [], + cupertino: cupertino, + textScale: 2, + ); + await _open(tester); + + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect( + cupertino + ? find.byType(CupertinoAlertDialog) + : find.byType(AlertDialog), + findsOneWidget, + ); + expect(find.text(runTitleFieldLabel), findsOneWidget); + expect(gateway.calls, isEmpty); + + await tester.enterText( + find.byKey(runTitleFieldKey), + 'A deliberately long title that must scroll rather than overflow', + ); + await tester.tap(find.byKey(runTitleSaveKey)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull, reason: 'cupertino=$cupertino'); + expect(find.text(refusal), findsOneWidget); + expect( + _fieldText(tester, cupertino: cupertino), + 'A deliberately long title that must scroll rather than overflow', + ); + + await tester.tap(find.byKey(runTitleCancelKey)); + await tester.pumpAndSettle(); + expect(find.byType(AlertDialog), findsNothing); + expect(find.byType(CupertinoAlertDialog), findsNothing); + } + }); +} diff --git a/app/test/features/runs/actions/title_test_support.dart b/app/test/features/runs/actions/title_test_support.dart new file mode 100644 index 00000000..b566a2d8 --- /dev/null +++ b/app/test/features/runs/actions/title_test_support.dart @@ -0,0 +1,110 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/title_action.dart'; + +typedef TitleHandler = Future Function(String type, JsonMap fields); + +/// A fake gateway that records every request and never owns a socket. +class FakeTitleGateway implements ApiGateway { + FakeTitleGateway(this.handler); + + final TitleHandler handler; + final List<({String type, JsonMap fields})> calls = []; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final copy = Map.from(fields); + calls.add((type: type, fields: copy)); + return handler(type, copy); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap titledRun({ + num id = 7, + String? title = 'Nightly build', + String status = 'succeeded', + String prompt = 'the submitted prompt', +}) => { + 'id': id, + 'title': title, + 'status': status, + 'input': {'prompt': prompt}, +}; + +JsonMap renamedRun({num id = 7, String title = 'Release build'}) => + titledRun(id: id, title: title, status: 'succeeded'); + +/// Owns the run like a run-detail screen would, so the callback's returned +/// server detail is what the action renders next. Re-pumping with a different +/// initial run updates the action in place, as a refreshed detail does. +class TitleHost extends StatefulWidget { + const TitleHost({ + super.key, + required this.gateway, + required this.initial, + required this.changed, + }); + + final FakeTitleGateway gateway; + final JsonMap initial; + final List changed; + + @override + State createState() => _TitleHostState(); +} + +class _TitleHostState extends State { + late JsonMap _run = widget.initial; + + @override + void didUpdateWidget(covariant TitleHost oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.initial, widget.initial)) { + _run = widget.initial; + } + } + + @override + Widget build(BuildContext context) { + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text('${_run['title'] ?? ''}', key: titleHostTitleKey), + RunTitleAction( + run: _run, + gateway: widget.gateway, + onRunChanged: (run) { + widget.changed.add(run); + setState(() => _run = run); + }, + ), + ], + ); + } +} + +const titleHostTitleKey = ValueKey('rename-host-title'); + +Widget titleApp(Widget child, {required bool cupertino, double textScale = 1}) { + Widget media(BuildContext context, Widget? app) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: app!, + ); + final body = Center(child: child); + if (cupertino) { + return CupertinoApp( + builder: media, + home: CupertinoPageScaffold(child: body), + ); + } + return MaterialApp( + builder: media, + home: Scaffold(body: body), + ); +} diff --git a/app/test/features/schedules/data/saved_schedule_record_test.dart b/app/test/features/schedules/data/saved_schedule_record_test.dart new file mode 100644 index 00000000..aef17fe6 --- /dev/null +++ b/app/test/features/schedules/data/saved_schedule_record_test.dart @@ -0,0 +1,101 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('saved schedule exposes run-configuration provenance', () { + final schedule = SavedSchedule(savedRecord()); + + expect(schedule.id, 8); + expect(schedule.revision, 3); + expect(schedule.pipelineId, 4); + expect(schedule.version, 2); + expect(schedule.name, 'Research batteries'); + expect(schedule.enabled, isTrue); + expect(schedule.prompt, 'Research batteries'); + expect(schedule.input['custom'], {'nested': 'kept'}); + expect(schedule.workspace, '/srv/research'); + expect(schedule.writePaths, ['reports/research.md']); + expect(schedule.allowTools, isTrue); + expect(schedule.model, 'openai/gpt-5'); + expect(schedule.stageModels, {'one': 'openai/gpt-5'}); + expect(schedule.notifyMode, 'off'); + expect(schedule.title, 'Battery research'); + expect(schedule.outputFormat, 'markdown'); + expect(schedule.rule.every, '24h'); + expect(schedule.rule.days, ['mon', 'wed']); + expect(schedule.rule.timezone, 'Europe/London'); + expect(schedule.rule.isClock, isFalse); + expect(schedule.nextDue, '2026-10-22T09:00:00Z'); + expect(schedule.createdAt, '2026-10-20T09:00:00Z'); + expect(schedule.updatedAt, '2026-10-21T09:00:00Z'); + }); + + test('unknown fields survive the typed view and pause copy', () { + final schedule = SavedSchedule(savedRecord()); + final paused = schedule.withEnabled(false); + + expect(paused.enabled, isFalse); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + expect(paused.toJson()['input'], { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }); + expect(paused.toJson()['rule'], savedRecord()['rule']); + + // The original snapshot is untouched and still enabled. + expect(schedule.enabled, isTrue); + expect(schedule.revision, 3); + }); + + test('toJson is a deep copy, not an alias of the server reply', () { + final source = savedRecord(); + final schedule = SavedSchedule(source); + + final first = schedule.toJson(); + ((first['future_server_field'] as Map)['nested'] as List).add('changed'); + final second = schedule.toJson(); + expect((second['future_server_field'] as Map)['nested'], [ + 1, + 2, + {'deep': true}, + ]); + + final promptInput = schedule.input; + promptInput['custom'] = 'changed'; + expect(schedule.input['custom'], {'nested': 'kept'}); + }); + + test('missing fields stay absent instead of being fabricated', () { + final schedule = SavedSchedule(const {}); + + expect(schedule.id, isNull); + expect(schedule.revision, isNull); + expect(schedule.pipelineId, isNull); + expect(schedule.version, isNull); + expect(schedule.enabled, isFalse); + expect(schedule.prompt, ''); + expect(schedule.workspace, ''); + expect(schedule.rule.every, ''); + expect(schedule.rule.times, isEmpty); + expect(schedule.writePaths, isEmpty); + expect(schedule.stageModels, isEmpty); + expect(schedule.toJson(), isEmpty); + }); + + test('a fractional revision is not truncated into a false token', () { + final schedule = SavedSchedule(const {'id': 8, 'revision': 3.5}); + + expect(schedule.id, 8); + expect(schedule.revision, isNull); + }); +} diff --git a/app/test/features/schedules/data/schedule_test_support.dart b/app/test/features/schedules/data/schedule_test_support.dart new file mode 100644 index 00000000..f80b852f --- /dev/null +++ b/app/test/features/schedules/data/schedule_test_support.dart @@ -0,0 +1,83 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +class RecordedCall { + const RecordedCall(this.type, this.fields); + final String type; + final JsonMap fields; +} + +/// Records the exact request built by the repository and replays queued +/// replies. Both are deep-copied, so a test can prove the repository neither +/// mutated its input nor depended on alias mutation of a reply. +class RecordingGateway implements ApiGateway { + final calls = []; + final replies = []; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + calls.add(RecordedCall(type, deepCopy(fields))); + if (failure case final error?) throw error; + if (replies.isEmpty) throw StateError('No recorded reply for $type'); + return deepCopy(replies.removeAt(0)); + } + + @override + Stream get frames => const Stream.empty(); +} + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A complete server record including fields this client does not interpret +/// yet, an unknown nested rule field and unknown input. +JsonMap savedRecord() => { + 'id': 8, + 'revision': 3, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Research batteries', + 'custom': {'nested': 'kept'}, + }, + 'workspace': '/srv/research', + 'write_paths': ['reports/research.md'], + 'allow_tools': true, + 'model': 'openai/gpt-5', + 'stage_models': {'one': 'openai/gpt-5'}, + 'notify_mode': 'off', + 'title': 'Battery research', + 'output_format': 'markdown', + 'rule': { + 'every': '24h', + 'days': ['mon', 'wed'], + 'timezone': 'Europe/London', + 'future_rule_field': 'kept', + }, + 'next_due': '2026-10-22T09:00:00Z', + 'created_at': '2026-10-20T09:00:00Z', + 'updated_at': '2026-10-21T09:00:00Z', + 'future_server_field': { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }, +}; + +/// The create form of the record: id 0 is the server's create sentinel and no +/// revision has been issued yet. +JsonMap createRecord() => { + 'id': 0, + 'name': 'Research batteries', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': {'prompt': 'Research batteries'}, + 'workspace': '/srv/research', + 'rule': {'every': '24h', 'timezone': 'Europe/London'}, +}; diff --git a/app/test/features/schedules/data/schedules_delete_test.dart b/app/test/features/schedules/data/schedules_delete_test.dart new file mode 100644 index 00000000..fc4f8d32 --- /dev/null +++ b/app/test/features/schedules/data/schedules_delete_test.dart @@ -0,0 +1,131 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/transport/connection_state.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test('delete sends the exact ID and expected revision', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule_deleted', 'schedule_id': 8}); + final repository = SchedulesRepository(gateway); + + await repository.deleteSchedule(8, 3); + + expect(gateway.calls.single.type, 'delete_schedule'); + expect(gateway.calls.single.fields, { + 'schedule_id': 8, + 'expected_revision': 3, + }); + }); + + test('delete refuses a confirmation for anything else', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedule_deleted'}, + {'type': 'schedule_deleted', 'schedule_id': 9}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.deleteSchedule(8, 3), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server did not confirm deletion of this schedule.', + ), + ), + ); + } + }); + + test('server refusals and conflicts propagate verbatim', () async { + final conflict = const ProtocolError( + 'schedule revision conflict; reload before editing', + ); + final recording = RecordingGateway()..failure = conflict; + final conflicting = SchedulesRepository(recording); + await expectLater( + conflicting.saveSchedule(createRecord()), + throwsA(same(conflict)), + ); + await expectLater( + conflicting.deleteSchedule(8, 3), + throwsA(same(conflict)), + ); + + final unsupported = const ProtocolError( + 'unknown message type: list_schedules', + ); + recording.failure = unsupported; + await expectLater( + conflicting.listSchedules(pipelineId: 4), + throwsA(same(unsupported)), + ); + }); + + test('missing and empty list replies are different facts', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedules'}); + expect(await repository.listSchedules(), isEmpty); + + gateway.replies.add({'type': 'schedules', 'schedules': null}); + expect(await repository.listSchedules(), isEmpty); + + for (final reply in [ + {}, + {'type': 'pong'}, + {'type': 'schedules', 'schedules': {}}, + { + 'type': 'schedules', + 'schedules': ['not a record'], + }, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.listSchedules(), + throwsA(isA()), + ); + } + }); + + test('save requires a saved schedule in the reply', () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + for (final reply in [ + {}, + {'type': 'schedule'}, + {'type': 'schedule', 'schedule': null}, + {'type': 'schedule', 'schedule': 'record'}, + ]) { + gateway.replies.add(reply); + await expectLater( + repository.saveSchedule(createRecord()), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'The server returned no saved schedule.', + ), + ), + ); + } + }); + + test('an empty schedule object is not turned into a fake identity', () async { + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': {}}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(createRecord()); + + expect(saved.id, isNull); + expect(saved.revision, isNull); + expect(saved.toJson(), isEmpty); + }); +} diff --git a/app/test/features/schedules/data/schedules_protocol_bounds_test.dart b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart new file mode 100644 index 00000000..db39b164 --- /dev/null +++ b/app/test/features/schedules/data/schedules_protocol_bounds_test.dart @@ -0,0 +1,81 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'list rejects non-positive and unsafe pipeline IDs before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final id in [0, -1, 9007199254740992]) { + await expectLater( + repository.listSchedules(pipelineId: id), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'A positive pipeline ID is required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'delete rejects an inexact identity or revision before sending', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + for (final pair in [ + (0, 1), + (-1, 1), + (8, 0), + (8, -1), + (8, 9007199254740992), + ]) { + await expectLater( + repository.deleteSchedule(pair.$1, pair.$2), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'An exact schedule ID and revision are required.', + ), + ), + ); + } + expect(gateway.calls, isEmpty); + }, + ); + + test( + 'request keys are bounded at 128 characters like the web client', + () async { + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + await expectLater( + repository.saveSchedule(createRecord(), requestKey: 'x' * 129), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'Schedule request keys must be strings of at most 128 characters.', + ), + ), + ); + expect(gateway.calls, isEmpty); + + final key = 'x' * 128; + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(createRecord(), requestKey: key); + expect(gateway.calls.single.fields['request_key'], key); + }, + ); +} diff --git a/app/test/features/schedules/data/schedules_repository_test.dart b/app/test/features/schedules/data/schedules_repository_test.dart new file mode 100644 index 00000000..8ac1ef4c --- /dev/null +++ b/app/test/features/schedules/data/schedules_repository_test.dart @@ -0,0 +1,132 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/schedules/data/schedules_repository.dart'; +import 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'schedule_test_support.dart'; + +void main() { + test( + 'lists with the exact web envelope and retains every record field', + () async { + final record = savedRecord(); + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedules', + 'schedules': [record], + }); + final repository = SchedulesRepository(gateway); + + final listed = await repository.listSchedules(pipelineId: 4); + + expect(gateway.calls.single.type, 'list_schedules'); + expect(gateway.calls.single.fields, {'pipeline_id': 4}); + expect(listed.single.toJson(), record); + expect(listed.single.pipelineId, 4); + expect(listed.single.version, 2); + expect(listed.single.prompt, 'Research batteries'); + expect(listed.single.workspace, '/srv/research'); + expect(listed.single.enabled, isTrue); + expect(listed.single.rule.every, '24h'); + expect(listed.single.rule.days, ['mon', 'wed']); + expect(listed.single.rule.timezone, 'Europe/London'); + expect(listed.single.model, 'openai/gpt-5'); + expect(listed.single.notifyMode, 'off'); + expect(listed.single.toJson()['future_server_field'], { + 'nested': [ + 1, + 2, + {'deep': true}, + ], + }); + + gateway.replies.add({'type': 'schedules'}); + await repository.listSchedules(); + expect(gateway.calls.last.type, 'list_schedules'); + expect(gateway.calls.last.fields, isEmpty); + }, + ); + + test( + 'create sends the web sentinel record without inventing a revision', + () async { + final create = createRecord(); + final original = deepCopy(create); + final gateway = RecordingGateway() + ..replies.add({'type': 'schedule', 'schedule': savedRecord()}); + final repository = SchedulesRepository(gateway); + + final saved = await repository.saveSchedule(create); + + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields, {'schedule': create}); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(create, original, reason: 'the caller record must be unchanged'); + expect(saved.id, 8); + expect(saved.revision, 3); + expect(saved.toJson(), savedRecord()); + }, + ); + + test( + 'a stable create key is forwarded exactly and blanks are omitted', + () async { + final create = createRecord(); + final gateway = RecordingGateway(); + final repository = SchedulesRepository(gateway); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule( + create, + requestKey: 'schedule:stable-editor-key', + ); + expect(gateway.calls.last.fields, { + 'schedule': create, + 'request_key': 'schedule:stable-editor-key', + }); + + gateway.replies.add({'type': 'schedule', 'schedule': savedRecord()}); + await repository.saveSchedule(create, requestKey: ''); + expect(gateway.calls.last.fields, {'schedule': create}); + }, + ); + + test('update reuses the read revision as the CAS token', () async { + final current = SavedSchedule(savedRecord()); + final paused = current.withEnabled(false); + expect(paused.id, 8); + expect(paused.revision, 3); + expect(paused.toJson()['future_server_field'], isNotNull); + + final gateway = RecordingGateway() + ..replies.add({ + 'type': 'schedule', + 'schedule': {...savedRecord(), 'enabled': false, 'revision': 4}, + }); + final repository = SchedulesRepository(gateway); + + final updated = await repository.saveSchedule(paused.toJson()); + + final body = gateway.calls.single.fields['schedule'] as Map; + expect(gateway.calls.single.type, 'save_schedule'); + expect(gateway.calls.single.fields.containsKey('request_key'), isFalse); + expect( + gateway.calls.single.fields.containsKey('expected_revision'), + isFalse, + ); + expect(body['id'], 8); + expect(body['revision'], 3); + expect(body['enabled'], isFalse); + expect(body['future_server_field'], isNotNull); + expect(updated.revision, 4); + expect(updated.enabled, isFalse); + + // The stale draft keeps its token: a conflict must not be papered over by + // silently adopting the reply revision. + expect(current.revision, 3); + expect(current.enabled, isTrue); + }); +}