Files
openchamber-android-native/lib/widgets/scheduled_task_editor.dart
T

495 lines
16 KiB
Dart
Raw Normal View History

// The scheduled-task editor: name, prompt, schedule and the run's model. The
// server validates the same limits again; saving hands the draft back so the
// page can keep the list it answers with.
import 'package:flutter/material.dart';
import '../api/models.dart';
import '../api/scheduled_tasks.dart';
import '../state.dart';
import 'model_picker.dart';
import '../l10n.dart';
class ScheduledTaskEditor extends StatefulWidget {
final AppState app;
/// What the task runs in, as the page names it.
final String scopeLabel;
/// Null creates a task.
final ScheduledTask? initial;
/// Saves the draft; false keeps the sheet open (the page has said why).
final Future<bool> Function(ScheduledTask draft) onSave;
const ScheduledTaskEditor({
super.key,
required this.app,
required this.scopeLabel,
required this.onSave,
this.initial,
});
@override
State<ScheduledTaskEditor> createState() => _ScheduledTaskEditorState();
}
class _ScheduledTaskEditorState extends State<ScheduledTaskEditor> {
late final TextEditingController _name;
late final TextEditingController _prompt;
late final TextEditingController _cron;
late String _kind;
late List<String> _times;
late Set<int> _weekdays;
late DateTime _date;
late String _time;
late bool _useDefaults;
late String _providerId;
late String _modelId;
late String _variant;
late String _agent;
late bool _enabled;
bool _saving = false;
@override
void initState() {
super.initState();
final task = widget.initial;
_name = TextEditingController(text: task?.name ?? '');
_prompt = TextEditingController(text: task?.prompt ?? '');
_cron = TextEditingController(
text: task?.kind == 'cron' && task!.cron.isNotEmpty
? task.cron
: '0 9 * * *');
_kind = task != null && task.kind.isNotEmpty ? task.kind : 'daily';
_times = task != null && task.times.isNotEmpty
? [...task.times]
: [task?.time.isNotEmpty == true ? task!.time : '09:00'];
_weekdays = task != null && task.weekdays.isNotEmpty
? {...task.weekdays}
: {1};
_date = _parseDate(task?.date ?? '') ?? _tomorrow();
_time = task != null && task.time.isNotEmpty ? task.time : '09:00';
_useDefaults = task?.useDefaults ?? true;
_providerId = task?.providerId ?? '';
_modelId = task?.modelId ?? '';
_variant = task?.variant ?? '';
_agent = task?.agent ?? '';
_enabled = task?.enabled ?? true;
if (widget.app.modelList.isEmpty) widget.app.refreshModels();
}
@override
void dispose() {
_name.dispose();
_prompt.dispose();
_cron.dispose();
super.dispose();
}
static DateTime _tomorrow() {
final now = DateTime.now();
return DateTime(now.year, now.month, now.day + 1);
}
static DateTime? _parseDate(String value) {
final parts = value.split('-');
if (parts.length != 3) return null;
final year = int.tryParse(parts[0]);
final month = int.tryParse(parts[1]);
final day = int.tryParse(parts[2]);
if (year == null || month == null || day == null) return null;
return DateTime(year, month, day);
}
static String _two(int value) => value.toString().padLeft(2, '0');
static String _dateText(DateTime date) =>
'${date.year}-${_two(date.month)}-${_two(date.day)}';
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return FractionallySizedBox(
heightFactor: 0.92,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 0, 12, 4),
child: Row(
children: [
Expanded(
child: AppText(
widget.initial == null ? 'New scheduled task' : 'Edit scheduled task',
style: const TextStyle(
fontSize: 18, fontWeight: FontWeight.w600),
),
),
TextButton(
onPressed: _saving ? null : _save,
child: AppText(_saving ? 'Saving…' : 'Save'),
),
],
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 32),
children: [
AppText(trArgs('Runs in: {0}', [widget.scopeLabel]),
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
const SizedBox(height: 12),
TextField(
controller: _name,
maxLength: 80,
decoration: InputDecoration(
labelText: tr('Task name'),
hintText: tr('Daily sync'),
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: _prompt,
minLines: 4,
maxLines: 10,
decoration: InputDecoration(
labelText: tr('Prompt'),
hintText: tr('Summarize unfinished tasks and suggest next steps'),
border: const OutlineInputBorder(),
alignLabelWithHint: true,
),
),
const SizedBox(height: 16),
const _FieldLabel('Schedule type'),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final entry in scheduledTaskKindLabels.entries)
ChoiceChip(
label: AppText(entry.value),
selected: _kind == entry.key,
onSelected: (_) => setState(() => _kind = entry.key),
),
],
),
const SizedBox(height: 8),
..._scheduleFields(theme),
const SizedBox(height: 8),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Use default model and agent'),
subtitle: const AppText('Turn off to pin the model and agent this run uses.'),
value: _useDefaults,
onChanged: (v) => setState(() => _useDefaults = v),
),
if (!_useDefaults) ..._executionFields(theme),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Enabled'),
subtitle: const AppText('Paused tasks don\'t run on schedule but can still be run manually.'),
value: _enabled,
onChanged: (v) => setState(() => _enabled = v),
),
const SizedBox(height: 8),
FilledButton(
onPressed: _saving ? null : _save,
child: AppText(_saving ? 'Saving…' : 'Save'),
),
],
),
),
],
),
);
}
List<Widget> _scheduleFields(ThemeData theme) {
switch (_kind) {
case 'daily':
return [_timesField(theme)];
case 'weekly':
return [
const _FieldLabel('Weekdays'),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (var day = 0; day < scheduledWeekdays.length; day++)
FilterChip(
label: AppText(scheduledWeekdays[day]),
selected: _weekdays.contains(day),
onSelected: (selected) => setState(() {
if (selected) {
_weekdays.add(day);
} else if (_weekdays.length > 1) {
_weekdays.remove(day);
}
}),
),
],
),
const SizedBox(height: 8),
_timesField(theme),
];
case 'once':
return [
ListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Date'),
trailing: Text(_dateText(_date)),
onTap: _pickDate,
),
ListTile(
contentPadding: EdgeInsets.zero,
title: const AppText('Time'),
trailing: Text(_time),
onTap: () async {
final picked = await _pickTime(_time);
if (picked != null) setState(() => _time = picked);
},
),
];
case 'cron':
return [
TextField(
controller: _cron,
decoration: InputDecoration(
labelText: tr('Cron expression'),
hintText: '*/5 * * * *',
border: const OutlineInputBorder(),
),
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
for (final example in const [
('Every 5 minutes', '*/5 * * * *'),
('Every hour', '0 * * * *'),
('Daily at 9', '0 9 * * *'),
('Mondays at 9', '0 9 * * 1'),
('1st of each month', '0 9 1 * *'),
])
ActionChip(
label: AppText(example.$1),
onPressed: () =>
setState(() => _cron.text = example.$2),
),
],
),
];
}
return const [];
}
Widget _timesField(ThemeData theme) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const _FieldLabel('Times'),
for (var i = 0; i < _times.length; i++)
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () async {
final picked = await _pickTime(_times[i]);
if (picked != null) setState(() => _times[i] = picked);
},
child: Text(_times[i]),
),
),
IconButton(
icon: const Icon(Icons.remove_circle_outline, size: 20),
tooltip: tr('Remove time'),
onPressed: _times.length <= 1
? null
: () => setState(() => _times.removeAt(i)),
),
],
),
),
TextButton.icon(
onPressed: () async {
final picked = await _pickTime(_times.isEmpty ? '09:00' : _times.last);
if (picked != null) setState(() => _times.add(picked));
},
icon: const Icon(Icons.add, size: 18),
label: const AppText('Add time'),
),
AppText('Times follow the server\'s time zone.', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
],
);
}
List<Widget> _executionFields(ThemeData theme) {
final model = _modelId.isEmpty
? 'Select model'
: (widget.app.modelNames['$_providerId/$_modelId'] ?? '$_providerId/$_modelId');
final agent = _agent.isEmpty ? 'Default agent' : _agent;
return [
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.memory, size: 20),
title: const AppText('Model'),
trailing: Text(model, overflow: TextOverflow.ellipsis),
onTap: _pickModel,
),
ListTile(
contentPadding: EdgeInsets.zero,
leading: const Icon(Icons.smart_toy_outlined, size: 20),
title: const AppText('Agent'),
trailing: AppText(agent, overflow: TextOverflow.ellipsis),
onTap: _pickAgent,
),
];
}
Future<void> _pickDate() async {
final now = DateTime.now();
final picked = await showDatePicker(
context: context,
initialDate: _date,
firstDate: now.subtract(const Duration(days: 1)),
lastDate: now.add(const Duration(days: 365 * 5)),
);
if (picked != null) setState(() => _date = picked);
}
Future<String?> _pickTime(String current) async {
final parts = current.split(':');
final picked = await showTimePicker(
context: context,
initialTime: TimeOfDay(
hour: int.tryParse(parts.first) ?? 9,
minute: parts.length > 1 ? int.tryParse(parts[1]) ?? 0 : 0,
),
);
if (picked == null) return null;
return '${_two(picked.hour)}:${_two(picked.minute)}';
}
Future<void> _pickModel() async {
final current = _modelId.isEmpty
? null
: ModelRef(_modelId, _providerId, _variant.isEmpty ? null : _variant);
await showModelPickerSheet(
context,
app: widget.app,
model: current,
onModel: (model) {
setState(() {
_modelId = model.id;
_providerId = model.providerId;
_variant = model.variant ?? '';
});
},
);
}
Future<void> _pickAgent() async {
if (widget.app.agentList.isEmpty) await widget.app.refreshModels();
if (!mounted) return;
final chosen = await showModalBottomSheet<String>(
context: context,
showDragHandle: true,
builder: (sheet) => ListView(
shrinkWrap: true,
children: [
ListTile(
title: const AppText('Default agent'),
trailing: _agent.isEmpty ? const Icon(Icons.check, size: 20) : null,
onTap: () => Navigator.pop(sheet, ''),
),
for (final agent in widget.app.agentList)
ListTile(
title: Text(agent.name.isEmpty ? agent.id : agent.name),
trailing: _agent == agent.id
? const Icon(Icons.check, size: 20)
: null,
onTap: () => Navigator.pop(sheet, agent.id),
),
],
),
);
if (chosen == null) return;
setState(() => _agent = chosen);
}
Future<void> _save() async {
final name = _name.text.trim();
final prompt = _prompt.text.trim();
final messenger = ScaffoldMessenger.of(context);
String? problem;
if (name.isEmpty) {
problem = 'Task name is required';
} else if (name.length > 80) {
problem = 'Task name can\'t exceed 80 characters';
} else if (prompt.isEmpty) {
problem = 'Prompt is required';
} else if (prompt.length > 20000) {
problem = 'Prompt can\'t exceed 20,000 characters';
} else if ((_kind == 'daily' || _kind == 'weekly') &&
_times.any((t) => !RegExp(r'^([01]\d|2[0-3]):[0-5]\d$').hasMatch(t))) {
problem = 'Time must be in HH:mm format';
} else if (_kind == 'weekly' && _weekdays.isEmpty) {
problem = 'Select at least one weekday';
} else if (_kind == 'cron' && _cron.text.trim().isEmpty) {
problem = 'Cron expression is required';
} else if (!_useDefaults && _modelId.isEmpty) {
problem = 'Select a model, or switch back to the default model';
}
if (problem != null) {
messenger.showSnackBar(SnackBar(content: AppText(problem)));
return;
}
setState(() => _saving = true);
final initial = widget.initial;
final draft = ScheduledTask(
id: initial?.id ?? '',
name: name,
enabled: _enabled,
kind: _kind,
times: _kind == 'daily' || _kind == 'weekly'
? ([..._times]..sort())
: const [],
weekdays: _kind == 'weekly' ? ([..._weekdays]..sort()) : const [],
date: _kind == 'once' ? _dateText(_date) : '',
time: _kind == 'once' ? _time : '',
cron: _kind == 'cron' ? _cron.text.trim() : '',
timezone: initial?.timezone ?? '',
prompt: prompt,
useDefaults: _useDefaults,
providerId: _useDefaults ? '' : _providerId,
modelId: _useDefaults ? '' : _modelId,
variant: _useDefaults ? '' : _variant,
agent: _useDefaults ? '' : _agent,
targetSessionId: initial?.targetSessionId ?? '',
);
final ok = await widget.onSave(draft);
if (!mounted) return;
setState(() => _saving = false);
if (ok) Navigator.of(context).pop();
}
}
class _FieldLabel extends StatelessWidget {
final String text;
const _FieldLabel(this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 6),
child: AppText(text,
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
);
}
}