// 计划任务: the server's scheduled prompts, one project (or the chats scope) // at a time. The list follows the web client: name, schedule, last result, // next run, and the actions it offers — run now, pause, edit, delete. import 'package:flutter/material.dart'; import '../api/client.dart'; import '../api/models.dart'; import '../api/scheduled_tasks.dart'; import '../state.dart'; import '../widgets/scheduled_task_editor.dart'; /// Where a task runs: a registered project, or the chats scope. class _TaskScope { final String id; final String label; /// The checkout the tasks run in; empty for the chats scope. final String directory; const _TaskScope(this.id, this.label, [this.directory = '']); } class ScheduledTasksScreen extends StatefulWidget { final AppState app; const ScheduledTasksScreen({super.key, required this.app}); @override State createState() => _ScheduledTasksScreenState(); } class _ScheduledTasksScreenState extends State { late final List<_TaskScope> _scopes; late _TaskScope? _scope; List _tasks = const []; bool _loading = true; String? _error; String _busyId = ''; AppState get app => widget.app; @override void initState() { super.initState(); _scopes = _buildScopes(); _scope = _defaultScope(); _load(); } List<_TaskScope> _buildScopes() { return [ for (final project in app.projects) // A chat's own directory is not a project of its own: every chat // schedules into the chats scope below. if (project.canonical.isNotEmpty && !app.isChatDirectory(project.canonical)) _TaskScope( project.metaId.isNotEmpty ? project.metaId : Client.projectIdFor(project.canonical), project.label, project.canonical, ), const _TaskScope(Client.scheduledChatsScope, '聊天'), ]; } _TaskScope? _defaultScope() { if (_scopes.isEmpty) return null; final directory = app.directory; if (directory.isNotEmpty) { // A session below the chats root schedules into the chats scope. if (app.isChatDirectory(directory)) return _scopes.last; for (final scope in _scopes) { if (slashPath(scope.directory) == slashPath(directory)) return scope; } } return _scopes.first; } Future _load() async { final scope = _scope; final client = app.client; if (scope == null || client == null) { setState(() { _loading = false; _tasks = const []; _error = client == null ? '未连接服务器' : null; }); return; } setState(() { _loading = true; _error = null; }); try { final tasks = await client.scheduledTasks(scope.id); if (!mounted || _scope?.id != scope.id) return; setState(() { _tasks = tasks; _loading = false; }); } on ApiError catch (e) { if (!mounted || _scope?.id != scope.id) return; setState(() { _loading = false; _tasks = const []; _error = e.status == 404 ? '服务器不支持计划任务' : '加载计划任务失败:${e.message}'; }); } catch (e) { if (!mounted || _scope?.id != scope.id) return; setState(() { _loading = false; _tasks = const []; _error = '加载计划任务失败:$e'; }); } } void _say(String message) { if (!mounted) return; ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: Text(message))); } Future _openEditor([ScheduledTask? task]) async { final scope = _scope; if (scope == null) return; await showModalBottomSheet( context: context, isScrollControlled: true, useSafeArea: true, showDragHandle: true, builder: (_) => ScheduledTaskEditor( app: app, scopeLabel: scope.label, initial: task, onSave: (draft) => _save(scope, draft), ), ); } Future _save(_TaskScope scope, ScheduledTask draft) async { final client = app.client; if (client == null) { _say('未连接服务器'); return false; } try { final tasks = await client.saveScheduledTask(scope.id, draft); if (!mounted) return true; if (_scope?.id == scope.id) setState(() => _tasks = tasks); _say('计划任务已保存'); return true; } on ApiError catch (e) { _say(e.message.isEmpty ? '保存任务失败' : e.message); return false; } catch (e) { _say('保存任务失败:$e'); return false; } } Future _toggle(ScheduledTask task, bool enabled) async { final scope = _scope; final client = app.client; if (scope == null || client == null || _busyId.isNotEmpty) return; setState(() => _busyId = task.id); try { final tasks = await client.saveScheduledTask(scope.id, task.copyWith(enabled: enabled)); if (!mounted) return; if (_scope?.id == scope.id) setState(() => _tasks = tasks); } catch (e) { _say(e is ApiError && e.message.isNotEmpty ? e.message : '更新任务失败'); await _load(); } finally { if (mounted) setState(() => _busyId = ''); } } Future _runNow(ScheduledTask task) async { final scope = _scope; final client = app.client; if (scope == null || client == null || _busyId.isNotEmpty) return; setState(() => _busyId = task.id); try { await client.runScheduledTask(scope.id, task.id); _say('任务已启动'); await _load(); } on ApiError catch (e) { _say(e.status == 409 ? '任务已在队列中等待' : (e.message.isEmpty ? '运行任务失败' : e.message)); } catch (e) { _say('运行任务失败:$e'); } finally { if (mounted) setState(() => _busyId = ''); } } Future _delete(ScheduledTask task) async { final scope = _scope; final client = app.client; if (scope == null || client == null) return; final ok = await showDialog( context: context, builder: (dialog) => AlertDialog( title: const Text('删除计划任务?'), content: Text('“${task.name}”及其计划会被删除。'), actions: [ TextButton( onPressed: () => Navigator.pop(dialog, false), child: const Text('取消')), FilledButton( onPressed: () => Navigator.pop(dialog, true), child: const Text('删除')), ], ), ); if (ok != true || !mounted) return; setState(() => _busyId = task.id); try { final tasks = await client.deleteScheduledTask(scope.id, task.id); if (!mounted) return; if (_scope?.id == scope.id) setState(() => _tasks = tasks); _say('计划任务已删除'); } catch (e) { _say(e is ApiError && e.message.isNotEmpty ? e.message : '删除任务失败'); } finally { if (mounted) setState(() => _busyId = ''); } } @override Widget build(BuildContext context) { final theme = Theme.of(context); return Scaffold( appBar: AppBar( title: const Text('计划任务'), actions: [ IconButton( icon: const Icon(Icons.refresh), tooltip: '刷新', onPressed: _loading ? null : _load, ), IconButton( icon: const Icon(Icons.add), tooltip: '新建任务', onPressed: _scope == null ? null : () => _openEditor(), ), ], ), body: Column( children: [ _scopeBar(theme), const Divider(height: 1), Expanded(child: _body(theme)), ], ), ); } Widget _scopeBar(ThemeData theme) { return Padding( padding: const EdgeInsets.fromLTRB(16, 6, 8, 6), child: Row( children: [ Icon(Icons.folder_outlined, size: 18, color: theme.hintColor), const SizedBox(width: 8), Text('运行位置', style: TextStyle(fontSize: 13, color: theme.hintColor)), const SizedBox(width: 10), Expanded( child: DropdownButtonHideUnderline( child: DropdownButton( value: _scope?.id, isExpanded: true, items: [ for (final scope in _scopes) DropdownMenuItem( value: scope.id, child: Text(scope.label, maxLines: 1, overflow: TextOverflow.ellipsis), ), ], onChanged: (id) { final scope = _scopes.where((s) => s.id == id).cast<_TaskScope?>().firstOrNull; if (scope == null || scope.id == _scope?.id) return; setState(() { _scope = scope; _tasks = const []; _loading = true; _error = null; }); _load(); }, ), ), ), ], ), ); } Widget _body(ThemeData theme) { if (_loading) return const Center(child: CircularProgressIndicator()); if (_error != null) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Text(_error!, style: TextStyle(color: theme.hintColor)), const SizedBox(height: 8), TextButton(onPressed: _load, child: const Text('重试')), ], ), ); } if (_tasks.isEmpty) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ Icon(Icons.event_note_outlined, size: 36, color: theme.hintColor), const SizedBox(height: 10), Text('暂无计划任务。', style: TextStyle(color: theme.hintColor)), const SizedBox(height: 8), FilledButton.tonalIcon( onPressed: () => _openEditor(), icon: const Icon(Icons.add, size: 18), label: const Text('新建任务'), ), ], ), ); } return RefreshIndicator( onRefresh: _load, child: ListView.builder( padding: const EdgeInsets.fromLTRB(12, 8, 12, 24), itemCount: _tasks.length, itemBuilder: (context, i) => _card(theme, _tasks[i]), ), ); } Widget _card(ThemeData theme, ScheduledTask task) { final running = task.lastStatus == 'running' || task.lastStatus == 'queued'; final statusColor = switch (task.lastStatus) { 'success' || 'sent' => theme.colorScheme.primary, 'error' || 'failed' => theme.colorScheme.error, 'running' || 'queued' => theme.colorScheme.tertiary, _ => theme.hintColor, }; final next = task.nextRunAt > 0 && task.enabled ? '下次:${scheduledRelativeTime(task.nextRunAt)}' : (task.enabled ? '' : '已暂停'); final last = task.lastRunAt > 0 ? '上次运行 ${scheduledClock(task.lastRunAt)} · ${scheduledStatusLabel(task.lastStatus)}' : '从未运行'; return Card( margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 2), clipBehavior: Clip.antiAlias, child: InkWell( onTap: () => _openEditor(task), child: Padding( padding: const EdgeInsets.fromLTRB(14, 10, 6, 10), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ Expanded( child: Text( task.name, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle( fontSize: 15.5, fontWeight: FontWeight.w600), ), ), if (_busyId == task.id) const Padding( padding: EdgeInsets.symmetric(horizontal: 12), child: SizedBox( width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 1.8)), ) else Switch( value: task.enabled, onChanged: (v) => _toggle(task, v), ), PopupMenuButton( tooltip: '更多', onSelected: (value) { switch (value) { case 'run': _runNow(task); case 'edit': _openEditor(task); case 'delete': _delete(task); } }, itemBuilder: (_) => [ const PopupMenuItem(value: 'run', child: Text('立即运行')), const PopupMenuItem(value: 'edit', child: Text('编辑')), PopupMenuItem( value: 'delete', child: Text('删除', style: TextStyle(color: theme.colorScheme.error)), ), ], ), ], ), Text(scheduledScheduleText(task), style: TextStyle(fontSize: 13, color: theme.colorScheme.onSurfaceVariant)), if (task.targetSessionId.isEmpty) const SizedBox.shrink() else Text('发送到现有会话', style: TextStyle(fontSize: 11.5, color: theme.hintColor)), const SizedBox(height: 4), Row( children: [ if (running) ...[ SizedBox( width: 12, height: 12, child: CircularProgressIndicator( strokeWidth: 1.6, color: statusColor), ), const SizedBox(width: 6), ] else ...[ Icon(Icons.circle, size: 8, color: statusColor), const SizedBox(width: 6), ], Expanded( child: Text( last, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11.5, color: theme.hintColor), ), ), if (next.isNotEmpty) Text(next, style: TextStyle(fontSize: 11.5, color: theme.hintColor)), ], ), if (task.lastError.isNotEmpty) Padding( padding: const EdgeInsets.only(top: 4), child: Text( task.lastError, maxLines: 2, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11.5, color: theme.colorScheme.error), ), ), const SizedBox(height: 2), Text( task.modelLabel, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 11.5, color: theme.hintColor), ), ], ), ), ), ); } }