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:
blumia committed 2026-11-26 00:36:27 +08:00
1 parent 2f5ce61692
commit da4bfb6826
13 files changed
+1612 -3

No files matched your search

+101
View File
@@ -0,0 +1,101 @@
// 全部功能: the tools the sidebar keeps behind one button, each opening its
// own page. Scheduled tasks so far; more entries go into the grid.
import 'package:flutter/material.dart';
import '../state.dart';
import 'scheduled_tasks_screen.dart';
class FeaturesScreen extends StatelessWidget {
final AppState app;
const FeaturesScreen({super.key, required this.app});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(title: const Text('全部功能')),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 32),
children: [
Text('服务器与智能体的工具都收在这里。',
style: TextStyle(fontSize: 12.5, color: theme.hintColor)),
const SizedBox(height: 14),
GridView.count(
crossAxisCount: 2,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
mainAxisSpacing: 12,
crossAxisSpacing: 12,
childAspectRatio: 1.25,
children: [
_FeatureTile(
icon: Icons.schedule,
title: '计划任务',
caption: '按时间向会话发送提示词',
onTap: () => Navigator.of(context).push(MaterialPageRoute(
builder: (_) => ScheduledTasksScreen(app: app),
)),
),
],
),
],
),
);
}
}
class _FeatureTile extends StatelessWidget {
final IconData icon;
final String title;
final String caption;
final VoidCallback onTap;
const _FeatureTile({
required this.icon,
required this.title,
required this.caption,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Material(
color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(16),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 38,
height: 38,
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer,
borderRadius: BorderRadius.circular(11),
),
child: Icon(icon,
size: 21, color: theme.colorScheme.onPrimaryContainer),
),
const Spacer(),
Text(title,
style: const TextStyle(
fontSize: 14.5, fontWeight: FontWeight.w600)),
const SizedBox(height: 2),
Text(
caption,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11.5, color: theme.hintColor),
),
],
),
),
),
);
}
}
+475
View File
@@ -0,0 +1,475 @@
// 计划任务: 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<ScheduledTasksScreen> createState() => _ScheduledTasksScreenState();
}
class _ScheduledTasksScreenState extends State<ScheduledTasksScreen> {
late final List<_TaskScope> _scopes;
late _TaskScope? _scope;
List<ScheduledTask> _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<void> _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<void> _openEditor([ScheduledTask? task]) async {
final scope = _scope;
if (scope == null) return;
await showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
builder: (_) => ScheduledTaskEditor(
app: app,
scopeLabel: scope.label,
initial: task,
onSave: (draft) => _save(scope, draft),
),
);
}
Future<bool> _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<void> _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<void> _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<void> _delete(ScheduledTask task) async {
final scope = _scope;
final client = app.client;
if (scope == null || client == null) return;
final ok = await showDialog<bool>(
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<String>(
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<String>(
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),
),
],
),
),
),
);
}
}
+13
View File
@@ -7,6 +7,7 @@ import 'package:flutter_slidable/flutter_slidable.dart';
import '../api/models.dart';
import '../state.dart';
import '../widgets/project_icon.dart';
import 'features_screen.dart';
import 'servers_screen.dart';
import 'settings_screen.dart';
@@ -185,6 +186,11 @@ class _SessionListPaneState extends State<SessionListPane> {
),
),
),
IconButton(
icon: const Icon(Icons.widgets_outlined),
tooltip: '全部功能',
onPressed: _openFeatures,
),
IconButton(
icon: const Icon(Icons.settings_outlined),
tooltip: '设置',
@@ -196,6 +202,13 @@ class _SessionListPaneState extends State<SessionListPane> {
);
}
void _openFeatures() {
widget.onOpened?.call();
Navigator.of(context).push(MaterialPageRoute(
builder: (_) => FeaturesScreen(app: _app),
));
}
void _openSettings() {
// A phone's list is a drawer: close it before the settings page covers
// the shell.