merge(app): land schedule-seed

This commit is contained in:
2026-10-22 17:47:35 +01:00
6 changed files with 715 additions and 3 deletions
@@ -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,
@@ -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 = <String, dynamic>{};
List<String> writePaths = [];
bool allowTools = false;
JsonMap otherInput = <String, dynamic>{};
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 ?? <String, dynamic>{})
..['prompt'] = prompt;
// Every run/record input key survives; only the editable prompt is replaced.
record['input'] = <String, dynamic>{
...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 <String, dynamic>{};
return <String, dynamic>{
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 <String, dynamic>{};
return <String, dynamic>{
for (final entry in value.entries)
'${entry.key}': cloneJsonValue(entry.value),
};
}
List<String> _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]');
@@ -20,3 +20,24 @@ dynamic cloneJsonValue(dynamic value) {
JsonMap cloneJsonMap(JsonMap value) =>
Map<String, dynamic>.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 : '';
@@ -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<String>('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<ScheduleRunAction> createState() => _ScheduleRunActionState();
}
class _ScheduleRunActionState extends State<ScheduleRunAction> {
bool _opening = false;
Future<void> _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);
}
}