diff --git a/app/WORK.md b/app/WORK.md index e6fe6224..9d4dff9a 100644 --- a/app/WORK.md +++ b/app/WORK.md @@ -22,9 +22,12 @@ All work under app/. Existing applications remain running and unchanged. | 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 / flutter/r2-retry | Task v6, Flash; small independent action | pending | pending | -| R2d | Native rename-run dialog | run55 / flutter/r2-title | Task v6, Flash; small independent action | pending | pending | -| S1a | Saved schedules repository/revision safety | run56 / flutter/s1-data | Task v6, Flash; nonvisual independent slice | pending | — | +| 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. @@ -57,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, 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/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/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/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); + }); +}