From f2c33d2a1e7ea7a95ef5d9ecee119c613e99b6d4 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 17:28:28 +0100 Subject: [PATCH] feat(app): schedule a recorded run with its options The run detail now offers the web's "Schedule this run" action when the run names a positive pipeline and pinned version. It opens the existing create editor seeded from the run and sends nothing until Save. The seed preserves every field the browser's scheduleDraft({ run }) copies: title (following the title_source rule), all input keys with prompt kept editable, pinned version, workspace, notify mode, write paths, tool access, model, stage models and output format. build() emits the same conditional payload as serializeSchedule. One request key is minted per editor opening so a refused save retries without duplicating the schedule. Advanced options are seed-only for now: the editor has no controls for them yet. --- .../features/runs/ui/run_detail_actions.dart | 3 + .../domain/editor/schedule_draft.dart | 132 ++++++++- .../schedules/domain/schedule_json.dart | 21 ++ .../schedules/ui/run/schedule_run_action.dart | 86 ++++++ .../editor/schedule_draft_from_run_test.dart | 214 ++++++++++++++ .../ui/run/schedule_run_action_test.dart | 262 ++++++++++++++++++ 6 files changed, 715 insertions(+), 3 deletions(-) create mode 100644 app/lib/features/schedules/ui/run/schedule_run_action.dart create mode 100644 app/test/features/schedules/domain/editor/schedule_draft_from_run_test.dart create mode 100644 app/test/features/schedules/ui/run/schedule_run_action_test.dart diff --git a/app/lib/features/runs/ui/run_detail_actions.dart b/app/lib/features/runs/ui/run_detail_actions.dart index 9a961e0b..6b0943de 100644 --- a/app/lib/features/runs/ui/run_detail_actions.dart +++ b/app/lib/features/runs/ui/run_detail_actions.dart @@ -2,6 +2,7 @@ import 'package:flutter/widgets.dart'; import '../../../core/api_gateway.dart'; import '../../artifacts/ui/artifact_gallery_action.dart'; +import '../../schedules/ui/run/schedule_run_action.dart'; import '../actions/cancel_eligibility.dart'; import '../actions/cancel_run_action.dart'; import '../actions/retry_action.dart'; @@ -46,6 +47,8 @@ class RunDetailActions extends StatelessWidget { gateway: gateway, onRunChanged: onRunChanged, ), + if (canScheduleRun(run)) + ScheduleRunAction(run: run, gateway: gateway), if (retryRunId(run) != null && canRetryRun(run)) RetryRunAction( run: run, diff --git a/app/lib/features/schedules/domain/editor/schedule_draft.dart b/app/lib/features/schedules/domain/editor/schedule_draft.dart index a07edc97..5d45a27c 100644 --- a/app/lib/features/schedules/domain/editor/schedule_draft.dart +++ b/app/lib/features/schedules/domain/editor/schedule_draft.dart @@ -1,5 +1,6 @@ import '../../../../core/api_gateway.dart'; import '../saved_schedule.dart'; +import '../schedule_json.dart'; import '../schedule_rule.dart'; /// Which half of the timer rule the editor is writing. @@ -43,6 +44,18 @@ class ScheduleDraft { String timezone = ''; String notifyMode = 'auto'; + /// Advanced run options the editor does not render yet. A create from a run + /// seeds them from that run and an edit seeds them from the saved record, so + /// [build] always saves the run's original configuration instead of silently + /// dropping it. + String model = ''; + JsonMap stageModels = {}; + List writePaths = []; + bool allowTools = false; + JsonMap otherInput = {}; + String title = ''; + String outputFormat = ''; + /// New schedule: the server's create sentinel is `id: 0` with no revision. factory ScheduleDraft.create({ required int pipelineId, @@ -54,6 +67,31 @@ class ScheduleDraft { ..workspace = workspace ..timezone = timezone; + /// New schedule seeded from one recorded run, mirroring `scheduleDraft({ + /// run })` in `web/src/schedules.js`: the run's title, prompt, pinned version, + /// absolute workspace, notification mode and advanced run options are copied. + /// Every input key survives with `prompt` kept as the editable field; the + /// schedule `title` follows the browser's `title_source` rule. Timer, + /// weekday and timezone fields keep the create defaults (an empty timezone + /// means the server's zone), and nothing is sent until the editor is saved. + factory ScheduleDraft.fromRun(JsonMap run) { + final input = run['input']; + final notifyMode = run['notify_mode']; + return ScheduleDraft._(null, jsonInteger(run['pipeline_id'])) + ..name = jsonText(run['title']) + ..prompt = jsonText(input is Map ? input['prompt'] : null) + ..version = _runVersion(run['version']) + ..workspace = jsonText(run['workspace']) + ..notifyMode = notifyMode is String ? notifyMode : 'auto' + ..model = jsonText(run['model']) + ..stageModels = _jsonObject(run['stage_models']) + ..writePaths = _jsonTexts(run['write_paths']) + ..allowTools = run['allow_tools'] == true + ..otherInput = _inputExceptPrompt(input) + ..title = _runScheduleTitle(run) + ..outputFormat = jsonText(run['output_format']); + } + /// Existing record: every field starts from the server value, never from a /// default that could overwrite it. factory ScheduleDraft.fromSchedule(SavedSchedule s, {int? pipelineId}) { @@ -71,7 +109,14 @@ class ScheduleDraft { ..times = rule.times.join(', ') ..days = [...rule.days] ..timezone = rule.timezone - ..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto'; + ..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto' + ..model = s.model + ..stageModels = _jsonObject(s.raw['stage_models']) + ..writePaths = s.writePaths + ..allowTools = s.allowTools + ..otherInput = _inputExceptPrompt(s.input) + ..title = s.title + ..outputFormat = s.outputFormat; } /// Validates every field and assembles the exact `save_schedule` record. @@ -138,8 +183,11 @@ class ScheduleDraft { record['pipeline_id'] = selectedPipeline; record['version'] = pinned; record['enabled'] = enabled; - record['input'] = (source?.input ?? {}) - ..['prompt'] = prompt; + // Every run/record input key survives; only the editable prompt is replaced. + record['input'] = { + ...cloneJsonMap(otherInput), + 'prompt': prompt, + }; // Untrimmed like `workspace: draft.workspace`; validation also runs on the // untrimmed value, so a valid workspace is sent exactly as the operator // entered it. @@ -163,6 +211,38 @@ class ScheduleDraft { if (timezone.trim().isNotEmpty) rule['timezone'] = timezone.trim(); record['rule'] = rule; record['notify_mode'] = notifyMode; + // Advanced options follow `serializeSchedule`: an empty value removes the + // key so a create stays minimal and an edit drops what the operator cleared. + if (writePaths.isNotEmpty) { + record['write_paths'] = [...writePaths]; + } else { + record.remove('write_paths'); + } + if (allowTools) { + record['allow_tools'] = true; + } else { + record.remove('allow_tools'); + } + if (model.isNotEmpty) { + record['model'] = model; + } else { + record.remove('model'); + } + if (stageModels.isNotEmpty) { + record['stage_models'] = cloneJsonMap(stageModels); + } else { + record.remove('stage_models'); + } + if (title.isNotEmpty) { + record['title'] = title; + } else { + record.remove('title'); + } + if (outputFormat.isNotEmpty) { + record['output_format'] = outputFormat; + } else { + record.remove('output_format'); + } return ScheduleSaveResult(record, const {}); } } @@ -170,6 +250,52 @@ class ScheduleDraft { const _maxSafeInteger = 9007199254740991; bool _validIdentity(int? value) => value != null && value > 0 && value <= _maxSafeInteger; + +/// A run input with `prompt` removed, deep-copied so the draft never aliases the +/// reply map. Build re-adds the editable prompt. +JsonMap _inputExceptPrompt(dynamic input) { + if (input is! Map) return {}; + return { + for (final entry in input.entries) + if ('${entry.key}' != 'prompt') + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +/// Deep-copied JSON object for `stage_models`; a non-object field is empty. +JsonMap _jsonObject(dynamic value) { + if (value is! Map) return {}; + return { + for (final entry in value.entries) + '${entry.key}': cloneJsonValue(entry.value), + }; +} + +List _jsonTexts(dynamic value) => value is List + ? [ + for (final item in value) + if (item is String) item, + ] + : const []; + +/// Renders like the browser's `String(run.version)`: a number keeps its exact +/// text (an integral one without a `.0`), while a malformed value stays visible +/// so the editor's own check explains it. +String _runVersion(dynamic value) => switch (value) { + String() => value, + num() when value.isFinite => (jsonInteger(value) ?? value).toString(), + _ => '', +}; + +/// The schedule `title` seeded from a run, mirroring `scheduleDraft({ run })`: +/// a generated or fallback run title is not copied, while an explicit/operator +/// title (or a run that does not report its source) is. +String _runScheduleTitle(JsonMap run) { + final source = jsonText(run['title_source']); + if (source.isNotEmpty && source != 'explicit' && source != 'user') return ''; + return jsonText(run['title']); +} + final _digits = RegExp(r'^\d+$'); final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$'); final _workspaceBreaks = RegExp(r'[\x00\r\n]'); diff --git a/app/lib/features/schedules/domain/schedule_json.dart b/app/lib/features/schedules/domain/schedule_json.dart index a0e541bf..8f1788cf 100644 --- a/app/lib/features/schedules/domain/schedule_json.dart +++ b/app/lib/features/schedules/domain/schedule_json.dart @@ -20,3 +20,24 @@ dynamic cloneJsonValue(dynamic value) { JsonMap cloneJsonMap(JsonMap value) => Map.from(cloneJsonValue(value) as Map); + +/// Whole number from a decoded JSON field, as the browser's `Number(value)` +/// followed by an integer check: integral numbers and integral numeric strings +/// are accepted; null, fractions, non-finite values and non-numeric text are +/// not. +int? jsonInteger(dynamic value) { + if (value is int) return value; + if (value is num) { + if (!value.isFinite || value != value.truncateToDouble()) return null; + return value.toInt(); + } + if (value is String) { + final number = num.tryParse(value.trim()); + if (number == null || !number.isFinite) return null; + return number == number.truncateToDouble() ? number.toInt() : null; + } + return null; +} + +/// String field from a decoded JSON value; anything else is the empty string. +String jsonText(dynamic value) => value is String ? value : ''; diff --git a/app/lib/features/schedules/ui/run/schedule_run_action.dart b/app/lib/features/schedules/ui/run/schedule_run_action.dart new file mode 100644 index 00000000..5ed5227c --- /dev/null +++ b/app/lib/features/schedules/ui/run/schedule_run_action.dart @@ -0,0 +1,86 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../../core/api_gateway.dart'; +import '../../../../ui/adaptive/host.dart'; +import '../../data/schedules_repository.dart'; +import '../../domain/editor/schedule_draft.dart'; +import '../../domain/schedule_json.dart'; +import '../pipeline/schedule_pipeline_editor.dart'; + +/// Browser wording for the run detail's independent schedule entry point. +const scheduleRunActionLabel = 'Schedule this run'; +const scheduleRunActionHint = + 'Save this run\'s prompt and options with an independent timer; ' + 'does not rerun it now'; +const scheduleRunActionKey = ValueKey('schedule-run-action'); + +/// Whether [run] names the positive pipeline and pinned version the web client +/// requires before offering "Schedule this run" (`Number(...) > 0`). +bool canScheduleRun(JsonMap run) => + _positive(jsonInteger(run['pipeline_id'])) && + _positive(jsonInteger(run['version'])); + +bool _positive(int? value) => value != null && value > 0; + +/// The run detail's "Schedule this run" action. +/// +/// Pressing it only opens the landed create editor over [ScheduleDraft.fromRun]: +/// the run's prompt, title, pinned version, absolute workspace, notification +/// mode and advanced options are prefilled and nothing is sent until Save. One +/// request key is minted per opening and captured by the submit callback, so +/// retrying a refused save cannot create a duplicate. An accepted save closes +/// the editor; this action never runs, retries or changes the source run. +class ScheduleRunAction extends StatefulWidget { + const ScheduleRunAction({ + super.key, + required this.run, + required this.gateway, + }); + + final JsonMap run; + final ApiGateway gateway; + + @override + State createState() => _ScheduleRunActionState(); +} + +class _ScheduleRunActionState extends State { + bool _opening = false; + + Future _open() async { + if (_opening || !canScheduleRun(widget.run)) return; + _opening = true; + // Minted once for this editor; every retry inside it reuses the key. + final requestKey = newScheduleCreateRequestKey(); + final repository = SchedulesRepository(widget.gateway); + try { + await openSchedulePipelineEditor( + context, + draft: ScheduleDraft.fromRun(widget.run), + onSubmit: (record) => + repository.saveSchedule(record, requestKey: requestKey), + ); + } finally { + _opening = false; + } + } + + @override + Widget build(BuildContext context) { + if (!canScheduleRun(widget.run)) return const SizedBox.shrink(); + final cupertino = usesCupertinoHost(context); + final action = cupertino + ? CupertinoButton( + key: scheduleRunActionKey, + onPressed: _open, + child: const Text(scheduleRunActionLabel), + ) + : OutlinedButton( + key: scheduleRunActionKey, + onPressed: _open, + child: const Text(scheduleRunActionLabel), + ); + return Tooltip(message: scheduleRunActionHint, child: action); + } +} diff --git a/app/test/features/schedules/domain/editor/schedule_draft_from_run_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_from_run_test.dart new file mode 100644 index 00000000..f88b2415 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_from_run_test.dart @@ -0,0 +1,214 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/schedules/domain/editor/schedule_draft.dart'; + +import 'draft_fixtures.dart'; + +/// A run that exercised every run-level option: extra input keys, a non-auto +/// notification mode, write restrictions, tool access, model overrides, an +/// explicit title and an output format. +JsonMap restrictedRun() => { + 'id': 7, + 'title': 'Nightly build', + 'title_source': 'explicit', + 'pipeline_id': 4, + 'version': 5, + 'input': { + 'prompt': ' keep\n\nspacing ', + 'topic': 'release notes', + 'pwd': '/srv/work', + 'nested': {'alpha': 1}, + }, + 'workspace': '/srv/run-workspace', + 'rule': { + 'every': '2h', + 'days': ['mon'], + 'timezone': 'Europe/London', + }, + 'notify_mode': 'off', + 'write_paths': ['src/file.go', 'notes'], + 'allow_tools': true, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'output_format': 'json', +}; + +void main() { + test('a run seeds every option the browser copies into a create', () { + final run = restrictedRun(); + final snapshot = deepCopy(run); + final draft = ScheduleDraft.fromRun(run); + + expect(draft.source, isNull); + expect(draft.pipelineId, 4); + expect(draft.name, 'Nightly build'); + expect(draft.prompt, ' keep\n\nspacing '); + expect(draft.version, '5'); + expect(draft.workspace, '/srv/run-workspace'); + // The run is a prompt snapshot, not a saved timer: create defaults stand. + expect(draft.enabled, isTrue); + expect(draft.mode, ScheduleTimerMode.interval); + expect(draft.every, '24h'); + expect(draft.times, ''); + expect(draft.days, isEmpty); + expect(draft.timezone, ''); + // Run-level options are seeded verbatim. + expect(draft.notifyMode, 'off'); + expect(draft.model, 'provider/model'); + expect(draft.stageModels, {'research': 'provider/other'}); + expect(draft.writePaths, ['src/file.go', 'notes']); + expect(draft.allowTools, isTrue); + expect(draft.title, 'Nightly build'); + expect(draft.outputFormat, 'json'); + expect(draft.otherInput, { + 'topic': 'release notes', + 'pwd': '/srv/work', + 'nested': {'alpha': 1}, + }); + + final result = draft.build(); + expect(result.errors, isEmpty); + expect(result.record, { + 'id': 0, + 'name': 'Nightly build', + 'pipeline_id': 4, + 'version': 5, + 'enabled': true, + 'input': { + 'prompt': ' keep\n\nspacing ', + 'topic': 'release notes', + 'pwd': '/srv/work', + 'nested': {'alpha': 1}, + }, + 'workspace': '/srv/run-workspace', + 'rule': {'every': '24h'}, + 'notify_mode': 'off', + 'write_paths': ['src/file.go', 'notes'], + 'allow_tools': true, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'title': 'Nightly build', + 'output_format': 'json', + }); + expect(run, snapshot); + }); + + test('a run without the advanced options still saves a minimal create', () { + final draft = ScheduleDraft.fromRun({ + 'title': 'Plain run', + 'pipeline_id': 4, + 'version': 5, + 'input': {'prompt': 'P'}, + 'workspace': '/srv', + }); + + expect(draft.notifyMode, 'auto'); + expect(draft.model, ''); + expect(draft.stageModels, isEmpty); + expect(draft.writePaths, isEmpty); + expect(draft.allowTools, isFalse); + expect(draft.otherInput, isEmpty); + expect(draft.title, 'Plain run'); + expect(draft.outputFormat, ''); + + final record = draft.build().record!; + expect(record, { + 'id': 0, + 'name': 'Plain run', + 'pipeline_id': 4, + 'version': 5, + 'enabled': true, + 'input': {'prompt': 'P'}, + 'workspace': '/srv', + 'rule': {'every': '24h'}, + 'notify_mode': 'auto', + // A run that does not report a title source keeps its title. + 'title': 'Plain run', + }); + }); + + test('a generated run title is not copied into the schedule title', () { + for (final source in ['model', 'fallback']) { + final draft = ScheduleDraft.fromRun({ + ...restrictedRun(), + 'title_source': source, + }); + + // The schedule name still uses the run title, as `scheduleDraft` does. + expect(draft.name, 'Nightly build'); + expect(draft.title, ''); + expect(draft.build().record!.containsKey('title'), isFalse); + } + + for (final source in ['explicit', 'user', null]) { + final run = restrictedRun(); + if (source == null) { + run.remove('title_source'); + } else { + run['title_source'] = source; + } + expect(ScheduleDraft.fromRun(run).title, 'Nightly build'); + } + }); + + test('a run without pipeline, version, prompt or name stays invalid', () { + final draft = ScheduleDraft.fromRun({ + 'version': 0, + 'input': {'prompt': ''}, + }); + + expect(draft.pipelineId, isNull); + expect(draft.name, ''); + expect(draft.prompt, ''); + expect(draft.version, '0'); + expect(draft.workspace, ''); + + final result = draft.build(); + expect(result.isValid, isFalse); + expect(result.record, isNull); + expect( + result.errors.keys, + containsAll(['pipelineId', 'name', 'prompt', 'version', 'workspace']), + ); + }); + + test('numeric variants render like the browser string and the run is read ' + 'only', () { + final run = { + 'title': 'T', + 'pipeline_id': 4.0, + 'version': 5.0, + 'input': {'prompt': 'P'}, + 'workspace': '/srv', + }; + final snapshot = Map.from(run); + final draft = ScheduleDraft.fromRun(run); + + expect(draft.pipelineId, 4); + expect(draft.version, '5'); + expect(draft.build().isValid, isTrue); + expect(run, snapshot); + expect( + ScheduleDraft.fromRun({'pipeline_id': 4, 'version': '6'}).version, + '6', + ); + // `String(value)` for a non-integral number, rather than hiding it. + expect( + ScheduleDraft.fromRun({'pipeline_id': '4', 'version': 5.5}).version, + '5.5', + ); + }); + + test('built input never aliases the run map', () { + final run = restrictedRun(); + final draft = ScheduleDraft.fromRun(run); + final record = draft.build().record!; + + ((record['input'] as JsonMap)['nested'] as JsonMap)['extra'] = true; + (record['stage_models'] as JsonMap)['research'] = 'changed'; + + expect((run['input'] as JsonMap)['nested'], {'alpha': 1}); + expect(draft.otherInput['nested'], {'alpha': 1}); + expect(draft.stageModels['research'], 'provider/other'); + }); +} diff --git a/app/test/features/schedules/ui/run/schedule_run_action_test.dart b/app/test/features/schedules/ui/run/schedule_run_action_test.dart new file mode 100644 index 00000000..50420061 --- /dev/null +++ b/app/test/features/schedules/ui/run/schedule_run_action_test.dart @@ -0,0 +1,262 @@ +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/ui/run_detail_actions.dart'; +import 'package:pipelines_app/features/schedules/ui/editor/schedule_editor_wording.dart'; +import 'package:pipelines_app/features/schedules/ui/run/schedule_run_action.dart'; + +/// Records every `save_schedule` and refuses the first one on demand. No socket +/// or Pipelines server is involved. +class SaveGateway implements ApiGateway { + final calls = >[]; + bool refuseNext = false; + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type != 'save_schedule') throw UnsupportedError('unexpected $type'); + calls.add(Map.from(fields)); + if (refuseNext) { + refuseNext = false; + throw const ProtocolError('conflict: revision 4 is stale'); + } + final schedule = Map.from(fields['schedule'] as Map); + return { + 'type': 'schedule_saved', + 'schedule': {...schedule, 'id': 12, 'revision': 1}, + }; + } +} + +JsonMap runFixture({ + Object? version = 5, + Object? pipelineId = 4, + String title = 'Nightly build', + String prompt = 'Summarise the release notes.', + String workspace = '/srv/run-workspace', +}) => { + 'id': 7, + 'title': title, + 'pipeline_id': ?pipelineId, + 'version': ?version, + 'status': 'succeeded', + 'input': { + 'prompt': prompt, + 'nested': {'kept': true}, + }, + 'workspace': workspace, +}; + +/// A run carrying every option the browser's run seed preserves. +JsonMap restrictedRunFixture() => { + ...runFixture(), + 'title_source': 'explicit', + 'input': { + 'prompt': 'Summarise the release notes.', + 'topic': 'release notes', + 'nested': {'kept': true}, + }, + 'notify_mode': 'off', + 'write_paths': ['src/file.go', 'notes'], + 'allow_tools': true, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'output_format': 'json', +}; + +Future pumpAction( + WidgetTester tester, + Widget child, { + bool cupertino = false, +}) async { + tester.view.physicalSize = const Size(390, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: child)), + ) + : MaterialApp( + home: Scaffold(body: SafeArea(child: child)), + ), + ); + await tester.pumpAndSettle(); +} + +Future tapSave(WidgetTester tester) async { + // A focused field keeps itself visible, so drop focus before scrolling. + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pumpAndSettle(); + final finder = find.byKey(scheduleEditorSubmitKey); + await tester.ensureVisible(finder); + await tester.pump(); + await tester.tap(finder); + await tester.pumpAndSettle(); +} + +String materialField(WidgetTester tester, Key key) => + tester.widget(find.byKey(key)).controller!.text; + +void main() { + testWidgets('opens a create editor seeded from the run without sending', ( + tester, + ) async { + final gateway = SaveGateway(); + await pumpAction( + tester, + ScheduleRunAction(run: runFixture(), gateway: gateway), + ); + + await tester.tap(find.byKey(scheduleRunActionKey)); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(find.text('Add schedule'), findsOneWidget); + expect(materialField(tester, scheduleEditorNameKey), 'Nightly build'); + expect( + materialField(tester, scheduleEditorPromptKey), + 'Summarise the release notes.', + ); + expect(materialField(tester, scheduleEditorVersionKey), '5'); + expect( + materialField(tester, scheduleEditorWorkspaceKey), + '/srv/run-workspace', + ); + expect(materialField(tester, scheduleEditorEveryKey), '24h'); + expect(materialField(tester, scheduleEditorTimezoneKey), ''); + expect(gateway.calls, isEmpty); + }); + + testWidgets('saves the run\'s input, restrictions and overrides once, and ' + 'reuses the one key after a refusal', (tester) async { + final gateway = SaveGateway()..refuseNext = true; + await pumpAction( + tester, + ScheduleRunAction(run: restrictedRunFixture(), gateway: gateway), + ); + await tester.tap(find.byKey(scheduleRunActionKey)); + await tester.pumpAndSettle(); + + await tapSave(tester); + + expect(gateway.calls, hasLength(1)); + final key = gateway.calls.single['request_key']; + expect(key, isA()); + expect(key, isNotEmpty); + expect('$key'.length, lessThanOrEqualTo(128)); + expect( + find.textContaining('conflict: revision 4 is stale'), + findsOneWidget, + ); + expect(find.textContaining('Your draft is preserved.'), findsOneWidget); + expect(find.byKey(scheduleEditorSubmitKey), findsOneWidget); + expect( + materialField(tester, scheduleEditorPromptKey), + 'Summarise the release notes.', + ); + + await tapSave(tester); + + expect(gateway.calls, hasLength(2)); + expect(gateway.calls[0]['request_key'], key); + expect(gateway.calls[1]['request_key'], key); + expect(gateway.calls[1]['schedule'], { + 'id': 0, + 'name': 'Nightly build', + 'pipeline_id': 4, + 'version': 5, + 'enabled': true, + 'input': { + 'prompt': 'Summarise the release notes.', + 'topic': 'release notes', + 'nested': {'kept': true}, + }, + 'workspace': '/srv/run-workspace', + 'rule': {'every': '24h'}, + 'notify_mode': 'off', + 'write_paths': ['src/file.go', 'notes'], + 'allow_tools': true, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'title': 'Nightly build', + 'output_format': 'json', + }); + expect(find.byKey(scheduleEditorSubmitKey), findsNothing); + }); + + testWidgets('the action is wired into run detail and hidden without a pin', ( + tester, + ) async { + final gateway = SaveGateway(); + await pumpAction( + tester, + RunDetailActions( + run: runFixture(), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + expect(find.byKey(scheduleRunActionKey), findsOneWidget); + expect(find.text(scheduleRunActionLabel), findsOneWidget); + + await pumpAction( + tester, + RunDetailActions( + run: runFixture(version: 0), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + expect(find.byKey(scheduleRunActionKey), findsNothing); + + await pumpAction( + tester, + RunDetailActions( + run: runFixture(pipelineId: null), + gateway: gateway, + onRunChanged: (_) {}, + ), + ); + expect(find.byKey(scheduleRunActionKey), findsNothing); + }); + + testWidgets('Cupertino uses the native action and fields', (tester) async { + final gateway = SaveGateway(); + await pumpAction( + tester, + ScheduleRunAction(run: runFixture(), gateway: gateway), + cupertino: true, + ); + + final action = find.byKey(scheduleRunActionKey); + expect( + find.widgetWithText(CupertinoButton, scheduleRunActionLabel), + findsOne, + ); + await tester.tap(action); + await tester.pumpAndSettle(); + + expect(gateway.calls, isEmpty); + expect(find.byKey(scheduleEditorSubmitKey), findsOneWidget); + expect( + tester + .widget(find.byKey(scheduleEditorVersionKey)) + .controller + ?.text, + '5', + ); + expect( + tester + .widget(find.byKey(scheduleEditorWorkspaceKey)) + .controller + ?.text, + '/srv/run-workspace', + ); + }); +}