feat: add scheduled tasks behind a 全部功能 button
- the sidebar footer gains 全部功能 left of 设置; its page lists the features the server offers, planned tasks for now - 计划任务 follows the web client: a project (or the chats scope) picked at the top, then its tasks with schedule, last result, next run, model and error; the switch pauses, the menu runs now, edits or deletes - the editor covers name, prompt, daily/weekly/once/cron schedules (Chinese date and time pickers), several times a day, weekdays, cron examples, enabled, and either the session defaults or a fixed model and agent - the same /api/projects/:id/scheduled-tasks endpoints the web uses; a server without them says so instead of failing silently - the app now pins zh_CN localizations, so the built-in pickers and menus are Chinese too - bump to 0.5.1
This commit is contained in:
1 parent
2f5ce61692
commit
da4bfb6826
13 files changed
+1612
-3
No files matched your search
@@ -0,0 +1,494 @@
|
||||
// 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';
|
||||
|
||||
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: Text(
|
||||
widget.initial == null ? '新建计划任务' : '编辑计划任务',
|
||||
style: const TextStyle(
|
||||
fontSize: 18, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: Text(_saving ? '保存中…' : '保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 32),
|
||||
children: [
|
||||
Text('运行位置:${widget.scopeLabel}',
|
||||
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _name,
|
||||
maxLength: 80,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '任务名称',
|
||||
hintText: '每日同步',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextField(
|
||||
controller: _prompt,
|
||||
minLines: 4,
|
||||
maxLines: 10,
|
||||
decoration: const InputDecoration(
|
||||
labelText: '提示词',
|
||||
hintText: '总结未完成任务并给出下一步建议',
|
||||
border: OutlineInputBorder(),
|
||||
alignLabelWithHint: true,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const _FieldLabel('计划类型'),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final entry in scheduledTaskKindLabels.entries)
|
||||
ChoiceChip(
|
||||
label: Text(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 Text('使用默认模型与智能体'),
|
||||
subtitle: const Text('关闭后可固定这次运行使用的模型和智能体。'),
|
||||
value: _useDefaults,
|
||||
onChanged: (v) => setState(() => _useDefaults = v),
|
||||
),
|
||||
if (!_useDefaults) ..._executionFields(theme),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('已启用'),
|
||||
subtitle: const Text('暂停的任务不会按计划运行,但可以手动运行。'),
|
||||
value: _enabled,
|
||||
onChanged: (v) => setState(() => _enabled = v),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
FilledButton(
|
||||
onPressed: _saving ? null : _save,
|
||||
child: Text(_saving ? '保存中…' : '保存'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _scheduleFields(ThemeData theme) {
|
||||
switch (_kind) {
|
||||
case 'daily':
|
||||
return [_timesField(theme)];
|
||||
case 'weekly':
|
||||
return [
|
||||
const _FieldLabel('星期'),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (var day = 0; day < scheduledWeekdays.length; day++)
|
||||
FilterChip(
|
||||
label: Text(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 Text('日期'),
|
||||
trailing: Text(_dateText(_date)),
|
||||
onTap: _pickDate,
|
||||
),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('时间'),
|
||||
trailing: Text(_time),
|
||||
onTap: () async {
|
||||
final picked = await _pickTime(_time);
|
||||
if (picked != null) setState(() => _time = picked);
|
||||
},
|
||||
),
|
||||
];
|
||||
case 'cron':
|
||||
return [
|
||||
TextField(
|
||||
controller: _cron,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Cron 表达式',
|
||||
hintText: '*/5 * * * *',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
for (final example in const [
|
||||
('每 5 分钟', '*/5 * * * *'),
|
||||
('每小时', '0 * * * *'),
|
||||
('每天 9 点', '0 9 * * *'),
|
||||
('每周一 9 点', '0 9 * * 1'),
|
||||
('每月 1 日', '0 9 1 * *'),
|
||||
])
|
||||
ActionChip(
|
||||
label: Text(example.$1),
|
||||
onPressed: () =>
|
||||
setState(() => _cron.text = example.$2),
|
||||
),
|
||||
],
|
||||
),
|
||||
];
|
||||
}
|
||||
return const [];
|
||||
}
|
||||
|
||||
Widget _timesField(ThemeData theme) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const _FieldLabel('时间点'),
|
||||
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: '移除时间',
|
||||
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 Text('添加时间'),
|
||||
),
|
||||
Text('时间按服务器所在时区。', style: TextStyle(fontSize: 11.5, color: theme.hintColor)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _executionFields(ThemeData theme) {
|
||||
final model = _modelId.isEmpty
|
||||
? '选择模型'
|
||||
: (widget.app.modelNames['$_providerId/$_modelId'] ?? '$_providerId/$_modelId');
|
||||
final agent = _agent.isEmpty ? '默认智能体' : _agent;
|
||||
return [
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: const Icon(Icons.memory, size: 20),
|
||||
title: const Text('模型'),
|
||||
trailing: Text(model, overflow: TextOverflow.ellipsis),
|
||||
onTap: _pickModel,
|
||||
),
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
leading: const Icon(Icons.smart_toy_outlined, size: 20),
|
||||
title: const Text('智能体'),
|
||||
trailing: Text(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 Text('默认智能体'),
|
||||
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 = '任务名称为必填项';
|
||||
} else if (name.length > 80) {
|
||||
problem = '任务名称不能超过 80 个字符';
|
||||
} else if (prompt.isEmpty) {
|
||||
problem = '提示词为必填项';
|
||||
} else if (prompt.length > 20000) {
|
||||
problem = '提示词不能超过 20000 个字符';
|
||||
} else if ((_kind == 'daily' || _kind == 'weekly') &&
|
||||
_times.any((t) => !RegExp(r'^([01]\d|2[0-3]):[0-5]\d$').hasMatch(t))) {
|
||||
problem = '时间格式必须是 HH:mm';
|
||||
} else if (_kind == 'weekly' && _weekdays.isEmpty) {
|
||||
problem = '请至少选择一个星期';
|
||||
} else if (_kind == 'cron' && _cron.text.trim().isEmpty) {
|
||||
problem = 'Cron 表达式为必填项';
|
||||
} else if (!_useDefaults && _modelId.isEmpty) {
|
||||
problem = '请选择模型,或改回使用默认模型';
|
||||
}
|
||||
if (problem != null) {
|
||||
messenger.showSnackBar(SnackBar(content: Text(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: Text(text,
|
||||
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w500)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user