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. 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'; /// 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, String version = '', String workspace = '', String timezone = '', }) => ScheduleDraft._(null, pipelineId) ..version = version ..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}) { 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' ..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. /// The draft and the source snapshot are never mutated. ScheduleSaveResult build() { final errors = {}; void fail(String field, String message) => errors.putIfAbsent(field, () => message); final selectedPipeline = source?.pipelineId ?? pipelineId; if (!_validIdentity(selectedPipeline)) { fail('pipelineId', 'Choose a valid pipeline.'); } if (source != null && (!_validIdentity(source!.id) || !_validIdentity(source!.revision))) { fail( 'record', 'Schedule identity or revision is missing. Refresh before editing.', ); } 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(); record['pipeline_id'] = selectedPipeline; record['version'] = pinned; record['enabled'] = enabled; // 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. 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; // 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 {}); } } 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]'); 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); }