diff --git a/app/lib/features/schedules/domain/editor/schedule_draft.dart b/app/lib/features/schedules/domain/editor/schedule_draft.dart new file mode 100644 index 00000000..1beb75cc --- /dev/null +++ b/app/lib/features/schedules/domain/editor/schedule_draft.dart @@ -0,0 +1,210 @@ +import '../../../../core/api_gateway.dart'; +import '../saved_schedule.dart'; +import '../schedule_rule.dart'; + +/// Which half of the timer rule the editor is writing. +enum ScheduleTimerMode { interval, clock } + +/// Either a ready-to-send `save_schedule` record or field errors keyed by the +/// draft field the control binds to. [record] is null when any field fails, so +/// an invalid draft can never be mistaken for a save payload. +class ScheduleSaveResult { + ScheduleSaveResult(this.record, this.errors); + + final JsonMap? record; + final Map errors; + + bool get isValid => record != null; +} + +/// Core editor state for one saved schedule, mirroring the web editor draft. +/// +/// Pure draft only: no network, timer calculation or timezone conversion. +/// [build] mirrors `serializeSchedule` in `web/src/schedules.js` for name, +/// prompt, pinned version, server workspace, timer rule, weekdays and +/// timezone. It starts from a deep copy of the server record, so unknown +/// record/input/rule/run-option fields and the exact revision survive an edit. +class ScheduleDraft { + ScheduleDraft._(this.source, this.pipelineId); + + /// The record this draft edits; null for a create. + final SavedSchedule? source; + final int? pipelineId; + + String name = ''; + String prompt = ''; + String version = ''; + String workspace = ''; + bool enabled = true; + ScheduleTimerMode mode = ScheduleTimerMode.interval; + String every = '24h'; + String times = ''; + List days = []; + String timezone = ''; + String notifyMode = 'auto'; + + /// New schedule: the server's create sentinel is `id: 0` with no revision. + factory ScheduleDraft.create({ + required int pipelineId, + String version = '', + String workspace = '', + String timezone = '', + }) => ScheduleDraft._(null, pipelineId) + ..version = version + ..workspace = workspace + ..timezone = timezone; + + /// Existing record: every field starts from the server value, never from a + /// default that could overwrite it. + factory ScheduleDraft.fromSchedule(SavedSchedule s, {int? pipelineId}) { + final rule = s.rule; + return ScheduleDraft._(s, s.pipelineId ?? pipelineId) + ..name = s.name + ..prompt = s.prompt + ..version = s.version?.toString() ?? '' + ..workspace = s.workspace + ..enabled = s.raw['enabled'] is bool ? s.enabled : true + ..mode = rule.isClock + ? ScheduleTimerMode.clock + : ScheduleTimerMode.interval + ..every = rule.raw['every'] is String ? rule.every : '24h' + ..times = rule.times.join(', ') + ..days = [...rule.days] + ..timezone = rule.timezone + ..notifyMode = s.raw['notify_mode'] is String ? s.notifyMode : 'auto'; + } + + /// Validates every field and assembles the exact `save_schedule` record. + /// The draft and the source snapshot are never mutated. + ScheduleSaveResult build() { + final errors = {}; + void fail(String field, String message) => + errors.putIfAbsent(field, () => message); + + if (name.trim().isEmpty) fail('name', 'Enter a schedule name.'); + if (prompt.trim().isEmpty) fail('prompt', 'Enter a prompt.'); + final pinned = int.tryParse(version); + if (!_digits.hasMatch(version) || + pinned == null || + pinned < 1 || + pinned > _maxSafeInteger) { + fail('version', 'Choose a positive pinned version, not latest (0).'); + } + if (!workspace.startsWith('/') || _workspaceBreaks.hasMatch(workspace)) { + fail('workspace', 'Enter an absolute workspace path on the server.'); + } + if (!const {'auto', 'on', 'off'}.contains(notifyMode)) { + fail('notifyMode', 'Choose a notification mode.'); + } + if (days.any((day) => !scheduleDays.contains(day)) || + days.toSet().length != days.length) { + fail('days', 'Choose valid, distinct weekdays.'); + } + List? clock; + if (mode == ScheduleTimerMode.interval) { + if (!_validDuration(every)) { + fail( + 'every', + 'Interval must be at least 1m (for example 24h or 1h30m).', + ); + } + } else { + clock = [for (final time in times.split(',')) time.trim()]; + if (clock.any((time) => !_timeOfDay.hasMatch(time)) || + clock.toSet().length != clock.length) { + fail('times', 'Enter distinct 24-hour times, such as 09:00, 17:30.'); + } + } + if (!_validTimezone(timezone.trim())) { + fail('timezone', 'Enter a valid IANA timezone.'); + } + if (errors.isNotEmpty) return ScheduleSaveResult(null, errors); + + final record = source?.toJson() ?? {}; + if (source == null) record['id'] = 0; + record['name'] = name.trim(); + final pipeline = source?.pipelineId ?? pipelineId; + if (pipeline != null) record['pipeline_id'] = pipeline; + record['version'] = pinned; + record['enabled'] = enabled; + record['input'] = (source?.input ?? {}) + ..['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. + record['workspace'] = workspace; + + final rule = source?.rule.toJson() ?? {}; + for (final key in const ['every', 'times', 'days', 'timezone']) { + rule.remove(key); + } + if (mode == ScheduleTimerMode.interval) { + rule['every'] = every.trim(); + } else { + rule['times'] = clock; + } + if (days.isNotEmpty) { + final prior = source?.rule.days ?? const []; + final unchanged = + prior.length == days.length && prior.every(days.contains); + rule['days'] = unchanged ? [...prior] : [...days]; + } + if (timezone.trim().isNotEmpty) rule['timezone'] = timezone.trim(); + record['rule'] = rule; + record['notify_mode'] = notifyMode; + return ScheduleSaveResult(record, const {}); + } +} + +const _maxSafeInteger = 9007199254740991; +final _digits = RegExp(r'^\d+$'); +final _timeOfDay = RegExp(r'^([01]\d|2[0-3]):[0-5]\d$'); +final _workspaceBreaks = RegExp(r'[\x00\r\n]'); +final _zonePart = RegExp(r'^[A-Za-z0-9_+\-]+$'); +const _durationPart = r'((?:\d+(?:\.\d*)?|\.\d+))(ms|us|µs|ns|h|m|s)'; +final _areas = + 'Africa America Antarctica Arctic Asia Atlantic Australia ' + 'Brazil Canada Chile Etc Europe Indian Mexico Pacific US' + .split(' '); +final _singleZones = + 'UTC GMT UCT Zulu Universal Greenwich CET EET EST HST ' + 'MST WET GB NZ PRC ROC ROK W-SU Egypt Eire Iceland Iran Israel Jamaica ' + 'Japan Kwajalein Libya Navajo Poland Portugal Singapore Turkey Cuba ' + 'Hongkong' + .split(' '); + +double? _unit(String unit) => switch (unit) { + 'h' => 3600000, + 'm' => 60000, + 's' => 1000, + 'ms' => 1, + 'us' || 'µs' => .001, + 'ns' => .000001, + _ => null, +}; + +/// Go-style compound duration, at least one minute, as the web client accepts. +bool _validDuration(String text) { + final every = text.trim(); + final parts = RegExp(_durationPart).allMatches(every).toList(); + final duration = parts.fold( + 0, + (sum, part) => sum + double.parse(part[1]!) * _unit(part[2]!)!, + ); + return parts.map((part) => part[0]!).join() == every && + duration.isFinite && + duration >= 60000; +} + +/// Structural IANA check. Dart carries no timezone database, so a known area +/// plus a well-formed location is the strongest pure check; the server stays +/// the final validator. +bool _validTimezone(String value) { + if (value.isEmpty || value == 'Local' || _singleZones.contains(value)) { + return true; + } + final parts = value.split('/'); + return parts.length > 1 && + _areas.contains(parts.first) && + parts.every(_zonePart.hasMatch); +} diff --git a/app/notes/S1-draft.md b/app/notes/S1-draft.md new file mode 100644 index 00000000..27ca42db --- /dev/null +++ b/app/notes/S1-draft.md @@ -0,0 +1,134 @@ +# S1-draft — pure saved-schedule editor draft and validation + +## What changed + +New files only; no existing feature, shell, transport, `main` or pubspec source +edited: + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/schedules/domain/editor/schedule_draft.dart` | 210 | mutable editor draft over `SavedSchedule`/`ScheduleRule`, web-mirrored validation, `save_schedule` record assembly | +| `test/features/schedules/domain/editor/draft_fixtures.dart` | 42 | shared server-record fixture and deep-copy helper | +| `test/features/schedules/domain/editor/schedule_draft_test.dart` | 134 | create/edit record assembly, CAS, unknown fields, workspace, source immutability | +| `test/features/schedules/domain/editor/schedule_draft_validation_test.dart` | 130 | timer/day/timezone/core field validation and invalid-field behavior | + +The production file is one cohesive file (below the 220-line slice budget) and +keeps the existing domain pattern: `SavedSchedule` and `ScheduleRule` are +read-only views, `ScheduleDraft` is the separate editable state. Tests are split +by responsibility (record assembly vs. validation) so neither file exceeds the +working agreement's ~250-line aim. + +## Review fix — workspace is now written into the record + +Review visit 1 found that `build()` validated `workspace` but never wrote it, so +creates were refused by `save_schedule` and workspace edits were dropped. The +fix writes `record['workspace'] = workspace;` beside `name`/`version`/`enabled`, +untrimmed to match `workspace: draft.workspace` in `web/src/schedules.js` +(validation also runs on the untrimmed value). Direct probe against the real +classes: + +``` +create keys: enabled, id, input, name, notify_mode, pipeline_id, rule, version, workspace +create: {"id":0,...,"workspace":"/srv","rule":{"every":"24h","timezone":"UTC"},"notify_mode":"auto"} +edit workspace: /new (source /old) +edit revision: 13 +``` + +New assertions cover the create record, an unchanged edit, a changed edit and +the untrimmed value. + +## Behavior copied from `web/src/schedules.js` + +`ScheduleDraft.build()` returns `ScheduleSaveResult(null, errors)` while any +field is invalid, so an invalid draft cannot yield a save payload. Errors are a +field-name → message map using the web editor's exact words: + +- name `Enter a schedule name.` (stored trimmed, as the web record is) +- prompt `Enter a prompt.` (stored untrimmed) +- pinned version: digits only, safe integer, at least 1 — `Choose a positive + pinned version, not latest (0).` +- workspace must start with `/` and contain no NUL/CR/LF — `Enter an absolute + workspace path on the server.` +- interval is Go-style compound duration (`24h`, `1h30m`, `.5h`, `1.5m`) whose + matched text covers the whole value and totals at least one minute — + `Interval must be at least 1m (for example 24h or 1h30m).` +- clock times are comma-separated, trimmed, distinct `HH:mm` in 00:00–23:59 — + `Enter distinct 24-hour times, such as 09:00, 17:30.` +- weekday keys must be distinct values from `scheduleDays` — + `Choose valid, distinct weekdays.` +- notification mode is `auto`, `on` or `off` — `Choose a notification mode.` +- timezone is blank, `Local`, a known single-zone alias or a well-formed + `Area/Location` — `Enter a valid IANA timezone.` + +Rule assembly mirrors the web editor: the prior rule is copied, `every`, +`times`, `days` and `timezone` are removed, then only the selected timer shape +is written. Empty weekdays mean every day (the key stays absent). A weekday set +that is unchanged keeps the server's original order (the web editor does this +so editing only a prompt does not reorder days). A blank timezone is omitted. + +## Losslessness and CAS + +- Edits start from `SavedSchedule.toJson()` (a deep copy): unknown top-level, + `input`, `rule` and run-option fields (`model`, `stage_models`, `write_paths`, + `allow_tools`, `title`, `output_format`, `next_due`, timestamps, future + fields) survive untouched. +- `input` keeps every unknown key and replaces only `prompt`. +- **Every build starts from a fresh copy**, so the source snapshot and the + draft are not mutated or aliased by a returned payload. +- The edit record keeps the exact server `revision`; it is never incremented, + invented or defaulted. An edit never rewrites `id`. +- A create has no source: it emits the web sentinel `id: 0`, no `revision`, no + unknown/run-option leftovers, `pipeline_id` from the caller, `enabled`, + `input: {prompt}`, `rule`, and `notify_mode`. +- `notify_mode` and `enabled` default the same way as the web draft when absent + from a malformed older record, but an existing non-default string/boolean is + preserved and validated rather than silently replaced. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/schedules/domain/editor test/features/schedules/domain/editor +flutter analyze # No issues found! (1.1s) +flutter test test/features/schedules/domain/editor # 9 passed +flutter test test/features/schedules # 56 passed +``` + +Focused coverage maps to the requested acceptance: + +- create: sentinel `id: 0`, no revision, pipeline/version/prompt/workspace/rule; +- lossless edit: id 9/revision 13, unknown record/input/rule/run options, + workspace from the source, original map and `SavedSchedule` snapshot + unchanged, returned payload not aliased; +- changed workspace is written untrimmed, matching the web serializer; +- prompt-only edit keeps the server weekday order and clock rule; +- clock ↔ interval switching removes the other timer key and keeps unknown + rule fields; +- invalid timers (`59s`, `NaN`, `-1h`, `1.1x`, `Infinityh`, mixed text) and + valid parity cases (`.5h`, `1h30m`, `24h`); +- invalid clock times, duplicate weekdays, bad notification mode, invalid + timezones, bad name/prompt/version/workspace; +- invalid draft mutates nothing and has no record. + +## Honest limits + +- **Scope is the core editor slice.** Name, prompt, pinned version, workspace, + timer mode/every/times, weekdays, timezone, enabled and notification mode are + editable. Advanced JSON run options (`otherInput`, `stage models`, write + paths, model, title, output format) and tools are **preserved exactly but not + editable in this slice**; no control or parser for them was invented here. +- **Timezone is structural.** Dart ships no IANA database, so the check accepts + blank/`Local`, known single-zone aliases and a known area plus a well-formed + location (e.g. `Europe/London`, `Etc/GMT+5`). It rejects clearly malformed + values such as `Nowhere/Invalid` and `Europe/`, but cannot prove that every + location in an accepted area exists. The server remains the final validator. + This is documented at the function. +- **No UI, network, CRUD, run dispatch, polling or scheduling engine.** The + draft only assembles a record; the existing repository owns `save_schedule`, + and no server was contacted. +- **No browser capture applies.** This is a nonvisual pure domain item; there + is no rendered change, so no fixture or screenshot was produced. +- **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.** This stage forbids commit, push and deploy, so the + candidate remains in the `flutter/schedule-draft` worktree for the manager. diff --git a/app/test/features/schedules/domain/editor/draft_fixtures.dart b/app/test/features/schedules/domain/editor/draft_fixtures.dart new file mode 100644 index 00000000..a5cb6406 --- /dev/null +++ b/app/test/features/schedules/domain/editor/draft_fixtures.dart @@ -0,0 +1,42 @@ +import 'dart:convert'; + +import 'package:pipelines_app/core/api_gateway.dart'; + +JsonMap deepCopy(JsonMap value) => jsonDecode(jsonEncode(value)) as JsonMap; + +/// A server record with every editable field plus unknown record, input, rule +/// and run-option keys this slice must preserve. +JsonMap completeRecord() => { + 'id': 9, + 'revision': 13, + 'name': 'Saved topic', + 'pipeline_id': 4, + 'version': 2, + 'enabled': true, + 'input': { + 'prompt': 'Topic', + 'count': 4, + 'flag': false, + 'nested': { + 'list': [null, 2], + }, + }, + 'workspace': '/srv/research', + 'rule': { + 'times': ['09:00', '17:30'], + 'days': ['fri', 'mon'], + 'timezone': '', + 'future': 'keep', + }, + 'model': 'provider/model', + 'stage_models': {'research': 'provider/other'}, + 'write_paths': ['src/file.go'], + 'allow_tools': true, + 'title': 'Saved title', + 'output_format': 'json', + 'notify_mode': 'off', + 'next_due': '2026-10-22T09:00:00Z', + 'server_extra': { + 'keep': [1, true], + }, +}; diff --git a/app/test/features/schedules/domain/editor/schedule_draft_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_test.dart new file mode 100644 index 00000000..228e76f7 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_test.dart @@ -0,0 +1,134 @@ +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 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'draft_fixtures.dart'; + +void main() { + test('a new schedule snapshots prompt, pipeline, workspace and version', () { + final draft = + ScheduleDraft.create( + pipelineId: 42, + version: '7', + workspace: '/srv/research', + timezone: 'UTC', + ) + ..name = 'AI news' + ..prompt = 'Research AI news'; + final result = draft.build(); + + expect(result.isValid, isTrue); + expect(result.errors, isEmpty); + final record = result.record!; + expect(record['id'], 0); + expect(record.containsKey('revision'), isFalse); + expect(record['pipeline_id'], 42); + expect(record['version'], 7); + expect(record['enabled'], isTrue); + expect(record['name'], 'AI news'); + expect(record['workspace'], '/srv/research'); + expect(record['input'], {'prompt': 'Research AI news'}); + expect(record['rule'], {'every': '24h', 'timezone': 'UTC'}); + expect(record['notify_mode'], 'auto'); + }); + + test('an edit preserves CAS, unknown fields and untouched run options', () { + final original = completeRecord(); + final snapshot = deepCopy(original); + final schedule = SavedSchedule(original); + final draft = ScheduleDraft.fromSchedule(schedule)..prompt = 'Changed'; + final result = draft.build(); + + expect(result.isValid, isTrue); + final record = result.record!; + expect(record['id'], 9); + expect(record['revision'], 13); + expect(record['workspace'], '/srv/research'); + expect(record['server_extra'], snapshot['server_extra']); + expect(record['next_due'], snapshot['next_due']); + expect(record['model'], 'provider/model'); + expect(record['stage_models'], {'research': 'provider/other'}); + expect(record['write_paths'], ['src/file.go']); + expect(record['allow_tools'], isTrue); + expect(record['title'], 'Saved title'); + expect(record['output_format'], 'json'); + expect(record['notify_mode'], 'off'); + expect((record['input'] as JsonMap)['count'], 4); + expect((record['input'] as JsonMap)['nested'], { + 'list': [null, 2], + }); + expect((record['input'] as JsonMap)['prompt'], 'Changed'); + expect((record['rule'] as JsonMap)['future'], 'keep'); + expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']); + + // Neither the server map nor the SavedSchedule snapshot was mutated. + expect(original, snapshot); + expect(schedule.toJson(), snapshot); + ((record['input'] as JsonMap)['nested'] as JsonMap)['extra'] = true; + expect(schedule.input['nested'], { + 'list': [null, 2], + }); + }); + + test( + 'an edit writes the changed workspace, untrimmed like the web client', + () { + final record = (ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = '/srv/other').build().record!; + expect(record['workspace'], '/srv/other'); + + final untrimmed = (ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = '/srv/dir ').build().record!; + expect(untrimmed['workspace'], '/srv/dir '); + }, + ); + + test('a prompt-only edit keeps the existing weekday order', () { + final original = completeRecord(); + final draft = ScheduleDraft.fromSchedule(SavedSchedule(original)) + ..prompt = 'New topic' + ..days = ['mon', 'fri']; + final record = draft.build().record!; + + expect((record['rule'] as JsonMap)['days'], ['fri', 'mon']); + expect((record['rule'] as JsonMap)['times'], ['09:00', '17:30']); + expect((record['rule'] as JsonMap)['timezone'], isNull); + }); + + test('switching modes removes the other timer shape and keeps unknowns', () { + final original = completeRecord(); + final clock = ScheduleDraft.fromSchedule(SavedSchedule(original)) + ..mode = ScheduleTimerMode.clock + ..times = '09:00, 23:59'; + final clockRule = clock.build().record!['rule'] as JsonMap; + expect(clockRule['times'], ['09:00', '23:59']); + expect(clockRule.containsKey('every'), isFalse); + expect(clockRule['future'], 'keep'); + + final interval = + ScheduleDraft.fromSchedule(SavedSchedule(clock.build().record!)) + ..mode = ScheduleTimerMode.interval + ..every = '1.5m'; + final intervalRule = interval.build().record!['rule'] as JsonMap; + expect(intervalRule['every'], '1.5m'); + expect(intervalRule.containsKey('times'), isFalse); + expect(intervalRule['future'], 'keep'); + }); + + test('the source record is never aliased by a built payload', () { + final original = completeRecord(); + final schedule = SavedSchedule(original); + final first = (ScheduleDraft.fromSchedule(schedule)).build(); + expect(first.record, isNotNull); + expect(schedule.toJson(), original); + + final second = (ScheduleDraft.fromSchedule( + schedule, + )..prompt = 'Other').build(); + expect((second.record!['input'] as JsonMap)['prompt'], 'Other'); + expect(schedule.input['prompt'], 'Topic'); + }); +} diff --git a/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart b/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart new file mode 100644 index 00000000..dd69b4a3 --- /dev/null +++ b/app/test/features/schedules/domain/editor/schedule_draft_validation_test.dart @@ -0,0 +1,130 @@ +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 'package:pipelines_app/features/schedules/domain/saved_schedule.dart'; + +import 'draft_fixtures.dart'; + +void main() { + test('invalid intervals are field errors and never a record', () { + for (final every in [ + '', + '59s', + 'NaN', + '-1h', + '1.1x', + 'Infinityh', + '1m2h x', + ]) { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..every = every; + final result = draft.build(); + expect(result.record, isNull, reason: every); + expect( + result.errors['every'], + 'Interval must be at least 1m (for example 24h or 1h30m).', + reason: every, + ); + } + for (final every in ['1m', '.5h', '1h30m', '24h']) { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..every = every; + final result = draft.build(); + expect(result.record, isNotNull, reason: every); + expect((result.record!['rule'] as JsonMap)['every'], every); + } + }); + + test('invalid clock times, weekdays and timezones are field errors', () { + final draft = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..mode = ScheduleTimerMode.clock + ..times = '24:00' + ..days = ['mon', 'mon'] + ..timezone = 'Nowhere/Invalid' + ..notifyMode = 'sometimes'; + final result = draft.build(); + + expect(result.record, isNull); + expect( + result.errors['times'], + 'Enter distinct 24-hour times, such as 09:00, 17:30.', + ); + expect(result.errors['days'], 'Choose valid, distinct weekdays.'); + expect(result.errors['timezone'], 'Enter a valid IANA timezone.'); + expect(result.errors['notifyMode'], 'Choose a notification mode.'); + + for (final times in ['', '9:00', '09:60', '09:00,09:00']) { + final invalid = + ScheduleDraft.fromSchedule(SavedSchedule(completeRecord())) + ..mode = ScheduleTimerMode.clock + ..times = times; + expect(invalid.build().errors['times'], isNotNull, reason: times); + } + for (final timezone in ['Europe', 'Europe/', '/London']) { + final invalid = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..timezone = timezone; + expect(invalid.build().errors['timezone'], isNotNull, reason: timezone); + } + for (final timezone in ['Local', 'UTC', 'Asia/Tokyo', 'Etc/GMT+5']) { + final valid = + ScheduleDraft.create(pipelineId: 4, version: '2', workspace: '/srv') + ..name = 'Timer' + ..prompt = 'Prompt' + ..timezone = timezone; + expect(valid.build().isValid, isTrue, reason: timezone); + } + }); + + test('invalid core fields report every error without mutating the draft', () { + final draft = ScheduleDraft.create(pipelineId: 4) + ..prompt = ' ' + ..version = '7junk' + ..workspace = '/srv\npath'; + final before = { + 'name': draft.name, + 'prompt': draft.prompt, + 'version': draft.version, + 'workspace': draft.workspace, + }; + final result = draft.build(); + + expect(result.record, isNull); + expect(result.errors, { + 'name': 'Enter a schedule name.', + 'prompt': 'Enter a prompt.', + 'version': 'Choose a positive pinned version, not latest (0).', + 'workspace': 'Enter an absolute workspace path on the server.', + }); + expect({ + 'name': draft.name, + 'prompt': draft.prompt, + 'version': draft.version, + 'workspace': draft.workspace, + }, before); + + for (final version in ['0', '-1', '1.2', 'Infinity']) { + final invalid = ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..version = version; + expect(invalid.build().errors['version'], isNotNull, reason: version); + } + for (final workspace in ['', 'relative', '~/repo']) { + final invalid = ScheduleDraft.fromSchedule( + SavedSchedule(completeRecord()), + )..workspace = workspace; + expect(invalid.build().errors['workspace'], isNotNull, reason: workspace); + } + }); +}