// 计划任务: 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/project_picker.dart'; import '../widgets/scheduled_task_editor.dart'; import '../l10n.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 selectableProjects(app)) _scopeFor(project), _chatsScope, ]; } static _TaskScope _scopeFor(ProjectInfo project) => _TaskScope( project.metaId.isNotEmpty ? project.metaId : Client.projectIdFor(project.canonical), project.label, project.canonical, ); _TaskScope get _chatsScope => _TaskScope(Client.scheduledChatsScope, tr('Chat')); _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 ? tr('Not connected to a server') : 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 ? 'The server doesn\'t support scheduled tasks' : trArgs('Couldn\'t load scheduled tasks: {0}', [e.message]); }); } catch (e) { if (!mounted || _scope?.id != scope.id) return; setState(() { _loading = false; _tasks = const []; _error = trArgs('Couldn\'t load scheduled tasks: {0}', [e]); }); } } void _say(String message) { if (!mounted) return; ScaffoldMessenger.of(context) .showSnackBar(SnackBar(content: AppText(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(tr('Not connected to a server')); return false; } try { final tasks = await client.saveScheduledTask(scope.id, draft); if (!mounted) return true; if (_scope?.id == scope.id) setState(() => _tasks = tasks); _say('Scheduled task saved'); return true; } on ApiError catch (e) { _say(e.message.isEmpty ? 'Couldn\'t save task' : e.message); return false; } catch (e) { _say(trArgs('Couldn\'t save task: {0}', [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 : 'Couldn\'t update task'); 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('Task started'); await _load(); } on ApiError catch (e) { _say(e.status == 409 ? 'Task is already waiting in the queue' : (e.message.isEmpty ? 'Couldn\'t run task' : e.message)); } catch (e) { _say(trArgs('Couldn\'t run task: {0}', [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 AppText('Delete scheduled task?'), content: AppText(trArgs('“{0}” and its schedule will be deleted.', [task.name])), actions: [ TextButton( onPressed: () => Navigator.pop(dialog, false), child: const AppText('Cancel')), FilledButton( onPressed: () => Navigator.pop(dialog, true), child: const AppText('Delete')), ], ), ); 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('Scheduled task deleted'); } catch (e) { _say(e is ApiError && e.message.isNotEmpty ? e.message : 'Couldn\'t delete task'); } finally { if (mounted) setState(() => _busyId = ''); } } @override Widget build(BuildContext context) { final theme = Theme.of(context); return Scaffold( appBar: AppBar( title: const AppText('Scheduled tasks'), actions: [ IconButton( icon: const Icon(Icons.refresh), tooltip: tr('Refresh'), onPressed: _loading ? null : _load, ), IconButton( icon: const Icon(Icons.add), tooltip: tr('New task'), onPressed: _scope == null ? null : () => _openEditor(), ), ], ), body: Column( children: [ _scopeBar(theme), const Divider(height: 1), Expanded(child: _body(theme)), ], ), ); } /// The same sheet the new-session composer uses: checkouts and the Chat /// scope, with the project list refreshed behind it. Future _pickScope() async { final selected = _scope == null || _scope!.directory.isEmpty ? AppState.chatTarget : _scope!.directory; final choice = await showProjectPicker( context, app: app, selected: selected, ); if (choice == null || !mounted) return; final next = choice.isChat ? _chatsScope : _scopeFor(choice.project!); if (next.id == _scope?.id) return; setState(() { _scope = next; _tasks = const []; _loading = true; _error = null; }); _load(); } 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), AppText('Runs in', style: TextStyle(fontSize: 13, color: theme.hintColor)), const SizedBox(width: 10), Expanded( child: InkWell( borderRadius: BorderRadius.circular(8), onTap: _pickScope, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), child: Row( children: [ Expanded( child: Text( _scope?.label ?? tr('Choose project'), maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle( fontSize: 13.5, color: theme.colorScheme.onSurface), ), ), Icon(Icons.expand_more, size: 18, color: theme.hintColor), ], ), ), ), ), ], ), ); } 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 AppText('Retry')), ], ), ); } 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), AppText('No scheduled tasks yet.', style: TextStyle(color: theme.hintColor)), const SizedBox(height: 8), FilledButton.tonalIcon( onPressed: () => _openEditor(), icon: const Icon(Icons.add, size: 18), label: const AppText('New task'), ), ], ), ); } 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 ? trArgs('Next: {0}', [scheduledRelativeTime(task.nextRunAt)]) : (task.enabled ? '' : 'Paused'); final last = task.lastRunAt > 0 ? trArgs('Last run {0} · {1}', [ scheduledClock(task.lastRunAt), scheduledStatusLabel(task.lastStatus), ]) : 'Never run'; 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: tr('More'), onSelected: (value) { switch (value) { case 'run': _runNow(task); case 'edit': _openEditor(task); case 'delete': _delete(task); } }, itemBuilder: (_) => [ const PopupMenuItem(value: 'run', child: AppText('Run now')), const PopupMenuItem(value: 'edit', child: AppText('Edit')), PopupMenuItem( value: 'delete', child: AppText('Delete', 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 AppText('Sends to an existing session', 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), ), ], ), ), ), ); } }