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

+42
View File
@@ -8,6 +8,7 @@ import 'dart:typed_data';
import '../version.dart';
import 'models.dart';
import 'scheduled_tasks.dart';
import 'shells.dart';
import 'terminal.dart';
import 'transport.dart';
@@ -400,6 +401,47 @@ class Client {
});
}
// ------------------------------------------------------ scheduled tasks
/// The project id the scheduled-tasks API uses for sessions outside any
/// project: the web client's chats scope.
static const scheduledChatsScope = 'openchamber:chats';
static String _scheduledTasksPath(String projectId) =>
'/api/projects/${Uri.encodeComponent(projectId)}/scheduled-tasks';
static List<ScheduledTask> _scheduledTasks(Map<String, dynamic> r) => [
for (final task in r['tasks'] as List? ?? const [])
if (task is Map<String, dynamic>) ScheduledTask.fromJson(task),
];
Future<List<ScheduledTask>> scheduledTasks(String projectId) async =>
_scheduledTasks(await _json('GET', _scheduledTasksPath(projectId)));
/// Creates or replaces [task]; the server answers with the project's tasks.
Future<List<ScheduledTask>> saveScheduledTask(
String projectId, ScheduledTask task) async {
final r = await _json('PUT', _scheduledTasksPath(projectId),
body: {'task': task.toJson()});
return _scheduledTasks(r);
}
Future<List<ScheduledTask>> deleteScheduledTask(
String projectId, String taskId) async {
final r = await _json('DELETE',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}');
return _scheduledTasks(r);
}
/// Starts a run now; the run's task (with its new state) comes back.
Future<ScheduledTask?> runScheduledTask(
String projectId, String taskId) async {
final r = await _json('POST',
'${_scheduledTasksPath(projectId)}/${Uri.encodeComponent(taskId)}/run');
final task = r['task'];
return task is Map<String, dynamic> ? ScheduledTask.fromJson(task) : null;
}
/// Moves a waiting prompt between `steer` and `queue`.
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
{String? directory}) async {
+244
View File
@@ -0,0 +1,244 @@
// Scheduled tasks: prompts the server sends on a schedule, into a new session
// or an existing one. The wire shape follows the web client
// (`/api/projects/:projectId/scheduled-tasks`), which reads the same tasks.
class ScheduledTask {
final String id;
final String name;
final bool enabled;
/// 'daily' | 'weekly' | 'once' | 'cron'.
final String kind;
/// Daily and weekly: the `HH:mm` times it runs at.
final List<String> times;
/// Weekly: 0 is Sunday, as the server counts.
final List<int> weekdays;
/// Once: `YYYY-MM-DD` and `HH:mm`.
final String date;
final String time;
/// Cron: the expression.
final String cron;
/// IANA name; empty means the server's own zone.
final String timezone;
/// What a run does: the prompt, and whether the session's defaults are used
/// instead of a fixed model and agent.
final String prompt;
final bool useDefaults;
final String providerId;
final String modelId;
final String variant;
final String agent;
/// Sends into this session instead of a new one; empty means a new session.
final String targetSessionId;
final String lastStatus;
final String lastError;
final int lastRunAt;
final int nextRunAt;
final int lastDurationMs;
final String lastSessionId;
const ScheduledTask({
this.id = '',
this.name = '',
this.enabled = true,
this.kind = 'daily',
this.times = const [],
this.weekdays = const [],
this.date = '',
this.time = '',
this.cron = '',
this.timezone = '',
this.prompt = '',
this.useDefaults = true,
this.providerId = '',
this.modelId = '',
this.variant = '',
this.agent = '',
this.targetSessionId = '',
this.lastStatus = '',
this.lastError = '',
this.lastRunAt = 0,
this.nextRunAt = 0,
this.lastDurationMs = 0,
this.lastSessionId = '',
});
factory ScheduledTask.fromJson(Map<String, dynamic> j) {
final schedule = j['schedule'] as Map<String, dynamic>? ?? const {};
final execution = j['execution'] as Map<String, dynamic>? ?? const {};
final state = j['state'] as Map<String, dynamic>? ?? const {};
String text(Object? value) => value is String ? value : '';
int number(Object? value) => (value is num) ? value.toInt() : 0;
return ScheduledTask(
id: text(j['id']),
name: text(j['name']),
enabled: j['enabled'] != false,
kind: text(schedule['kind']),
times: [
for (final value in schedule['times'] as List? ?? const [])
if (value is String) value,
],
weekdays: [
for (final value in schedule['weekdays'] as List? ?? const [])
if (value is num) value.toInt(),
],
date: text(schedule['date']),
time: text(schedule['time']),
cron: text(schedule['cron']),
timezone: text(schedule['timezone']),
prompt: text(execution['prompt']),
// The web client treats a task without a fixed model as using the
// session's defaults, whatever the flag says.
useDefaults: execution['useDefaults'] == true || text(execution['modelID']).isEmpty,
providerId: text(execution['providerID']),
modelId: text(execution['modelID']),
variant: text(execution['variant']),
agent: text(execution['agent']),
targetSessionId: text(j['targetSessionId']),
lastStatus: text(state['lastStatus']),
lastError: text(state['lastError']),
lastRunAt: number(state['lastRunAt']),
nextRunAt: number(state['nextRunAt']),
lastDurationMs: number(state['lastDurationMs']),
lastSessionId: text(state['lastSessionId']),
);
}
/// What the server is sent on save. State is the server's own; a task keeps
/// it unless it is deliberately replaced.
Map<String, dynamic> toJson() => {
if (id.isNotEmpty) 'id': id,
'name': name,
'enabled': enabled,
'schedule': {
'kind': kind,
if (kind == 'daily' || kind == 'weekly') 'times': times,
if (kind == 'weekly') 'weekdays': weekdays,
if (kind == 'once') ...{'date': date, 'time': time},
if (kind == 'cron') 'cron': cron,
if (timezone.isNotEmpty) 'timezone': timezone,
},
'execution': {
'prompt': prompt,
'useDefaults': useDefaults,
if (!useDefaults && providerId.isNotEmpty) 'providerID': providerId,
if (!useDefaults && modelId.isNotEmpty) 'modelID': modelId,
if (!useDefaults && variant.isNotEmpty) 'variant': variant,
if (!useDefaults && agent.isNotEmpty) 'agent': agent,
},
if (targetSessionId.isNotEmpty) 'targetSessionId': targetSessionId,
};
ScheduledTask copyWith({bool? enabled}) => ScheduledTask(
id: id,
name: name,
enabled: enabled ?? this.enabled,
kind: kind,
times: times,
weekdays: weekdays,
date: date,
time: time,
cron: cron,
timezone: timezone,
prompt: prompt,
useDefaults: useDefaults,
providerId: providerId,
modelId: modelId,
variant: variant,
agent: agent,
targetSessionId: targetSessionId,
lastStatus: lastStatus,
lastError: lastError,
lastRunAt: lastRunAt,
nextRunAt: nextRunAt,
lastDurationMs: lastDurationMs,
lastSessionId: lastSessionId,
);
/// The model line: a fixed choice, or that the run uses the session's.
String get modelLabel {
if (useDefaults || modelId.isEmpty) return '使用默认模型与智能体';
final model = [providerId, modelId].where((s) => s.isNotEmpty).join('/');
return agent.isEmpty ? model : '$model · $agent';
}
}
const scheduledWeekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
const scheduledTaskKindLabels = {
'daily': '每天',
'weekly': '每周',
'once': '一次性',
'cron': 'Cron',
};
/// '每天 09:00', '每周 周一、周三 09:00', '一次性 2026-12-01 09:00', …
String scheduledScheduleText(ScheduledTask task) {
final times = task.times.isEmpty ? task.time : task.times.join('、');
switch (task.kind) {
case 'daily':
return '每天 ${times.isEmpty ? '--:--' : times}';
case 'weekly':
final days = [
for (final day in task.weekdays)
if (day >= 0 && day < scheduledWeekdays.length) scheduledWeekdays[day],
].join('、');
return '每周 ${days.isEmpty ? '未选' : days} ${times.isEmpty ? '--:--' : times}';
case 'once':
return '一次性 ${task.date.isEmpty ? '未选日期' : task.date} '
'${task.time.isEmpty ? '--:--' : task.time}';
case 'cron':
return 'Cron:${task.cron}';
}
return '';
}
String scheduledStatusLabel(String status) => switch (status) {
'success' || 'sent' => '成功',
'error' || 'failed' => '错误',
'running' => '运行中',
'queued' => '已排队',
'skipped' => '已跳过',
'cancelled' => '已取消',
_ => '空闲',
};
/// How far away a moment is, in the words the web client uses.
String scheduledRelativeTime(int milliseconds) {
if (milliseconds <= 0) return '';
final diff = milliseconds - DateTime.now().millisecondsSinceEpoch;
final abs = diff.abs();
const minute = 60 * 1000;
const hour = 60 * minute;
const day = 24 * hour;
final future = diff >= 0;
if (abs < minute) return future ? '不到 1 分钟后' : '刚刚';
if (abs < hour) {
final m = (abs / minute).round();
return future ? '$m 分钟后' : '$m 分钟前';
}
if (abs < day) {
final h = abs ~/ hour;
final m = ((abs % hour) / minute).round();
final body = m > 0 ? '$h 小时 $m 分钟' : '$h 小时';
return future ? '$body后' : '$body前';
}
final d = abs ~/ day;
final h = ((abs % day) / hour).round();
final body = h > 0 ? '$d 天 $h 小时' : '$d 天';
return future ? '$body后' : '$body前';
}
String scheduledClock(int milliseconds) {
if (milliseconds <= 0) return '';
final at = DateTime.fromMillisecondsSinceEpoch(milliseconds);
String two(int n) => n.toString().padLeft(2, '0');
return '${two(at.hour)}:${two(at.minute)}';
}
+10
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'appearance_prefs.dart';
import 'pets/pet_library.dart';
@@ -58,6 +59,15 @@ class _OpenChamberAppState extends State<OpenChamberApp>
: HomeScreen(app: app);
return MaterialApp(
title: 'OpenChamber',
// The app speaks Chinese only; this also puts the built-in pieces
// (date and time pickers, text selection menu) in Chinese.
locale: const Locale('zh', 'CN'),
supportedLocales: const [Locale('zh', 'CN'), Locale('en')],
localizationsDelegates: const [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
themeMode: look.themeMode,
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(
+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.
+494
View File
@@ -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)),
);
}
}