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
@@ -5,6 +5,21 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 0.5.1 计划任务与「全部功能」入口(分支 `flutter`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
| --- | --- |
|
||||||
|
| 入口 | 侧栏底部、设置按钮左侧新增「全部功能」按钮,打开一个功能页;目前里面只有【计划任务】一张卡片(图标 + 一句说明) |
|
||||||
|
| 计划任务 | 对照网页端:顶部选择运行位置(已注册项目 + 「聊天」scope,默认取当前会话所在项目),下面列出该项目的任务。每张卡片显示名称、计划、上次运行/状态、下次运行、模型行与错误;开关直接暂停/启用,菜单里可立即运行、编辑、删除;下拉刷新 |
|
||||||
|
| 编辑器 | 底部弹层:任务名称(≤80)、提示词(≤20000)、计划类型(每天 / 每周 / 一次性 / Cron)、时间点(可加多个)、星期、日期与时间(中文的日期/时间选择器)、Cron 示例、是否启用;默认「使用默认模型与智能体」,关闭后可选模型(复用模型选择器)与智能体 |
|
||||||
|
| 接口 | `GET/PUT /api/projects/:id/scheduled-tasks`、`DELETE …/:taskId`、`POST …/:taskId/run`,与网页端同一份数据;`openchamber:chats` 作为聊天 scope;服务器没有该接口(404)时页面写明「服务器不支持计划任务」。时间按服务器时区 |
|
||||||
|
| 中文化 | 应用整体指定中文(`flutter_localizations`),系统自带的日期/时间选择器、文本选择菜单随之是中文 |
|
||||||
|
| 测试 | 新增 `test/scheduled_tasks_test.dart`:四种计划的解析与展示文案、保存时只带该类型用到的字段、默认模型判断、状态与相对时间、功能页入口、编辑器的必填校验与草稿;`sidebar_footer_test` 覆盖新按钮;95 项全过 |
|
||||||
|
| 验证 | 模拟器(真实服务端):侧栏「全部功能」→ 计划任务;默认运行位置取当前会话所在项目(聊天目录与 chats 根不出现在项目列表里,统一归到末尾的「聊天」scope)。新建「Daily time report」(每天 09:00)后列表显示「下次:8 小时 45 分钟后」;「立即运行」→ 服务端 `lastStatus: sent` 并新建一个 scheduled 会话,卡片显示「上次运行 00:16 · 成功」;编辑弹层带出原值;关掉开关变「已暂停」;删除 → 确认 → 列表为空、服务端任务为空(运行产生的会话也已删除);切到「聊天」scope 正常加载 |
|
||||||
|
| 版本 | **0.5.1(code 501)** |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 0.5.0 设置「常规」分组与「通用」页(分支 `flutter`)
|
## 0.5.0 设置「常规」分组与「通用」页(分支 `flutter`)
|
||||||
|
|
||||||
| 项 | 结果 |
|
| 项 | 结果 |
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
|
|||||||
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
|
||||||
Flutter to compare mobile UI maturity.
|
Flutter to compare mobile UI maturity.
|
||||||
|
|
||||||
Status: 0.5.0 — servers (passwordless / password login, HTTP/HTTPS and
|
Status: 0.5.1 — servers (passwordless / password login, HTTP/HTTPS and
|
||||||
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
|
SOCKS5/socks5h proxy, self-signed certificates and pinning, or a pairing link
|
||||||
over the OpenChamber private relay with end-to-end encryption; the pairing
|
over the OpenChamber private relay with end-to-end encryption; the pairing
|
||||||
link is pasted or scanned with the camera), session list with search and live
|
link is pasted or scanned with the camera), session list with search and live
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import 'dart:typed_data';
|
|||||||
|
|
||||||
import '../version.dart';
|
import '../version.dart';
|
||||||
import 'models.dart';
|
import 'models.dart';
|
||||||
|
import 'scheduled_tasks.dart';
|
||||||
import 'shells.dart';
|
import 'shells.dart';
|
||||||
import 'terminal.dart';
|
import 'terminal.dart';
|
||||||
import 'transport.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`.
|
/// Moves a waiting prompt between `steer` and `queue`.
|
||||||
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
|
Future<void> updateInbox(String sessionId, String inboxId, String delivery,
|
||||||
{String? directory}) async {
|
{String? directory}) async {
|
||||||
|
|||||||
@@ -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)}';
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_localizations/flutter_localizations.dart';
|
||||||
|
|
||||||
import 'appearance_prefs.dart';
|
import 'appearance_prefs.dart';
|
||||||
import 'pets/pet_library.dart';
|
import 'pets/pet_library.dart';
|
||||||
@@ -58,6 +59,15 @@ class _OpenChamberAppState extends State<OpenChamberApp>
|
|||||||
: HomeScreen(app: app);
|
: HomeScreen(app: app);
|
||||||
return MaterialApp(
|
return MaterialApp(
|
||||||
title: 'OpenChamber',
|
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,
|
themeMode: look.themeMode,
|
||||||
theme: ThemeData(
|
theme: ThemeData(
|
||||||
colorScheme: ColorScheme.fromSeed(
|
colorScheme: ColorScheme.fromSeed(
|
||||||
|
|||||||
@@ -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),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import 'package:flutter_slidable/flutter_slidable.dart';
|
|||||||
import '../api/models.dart';
|
import '../api/models.dart';
|
||||||
import '../state.dart';
|
import '../state.dart';
|
||||||
import '../widgets/project_icon.dart';
|
import '../widgets/project_icon.dart';
|
||||||
|
import 'features_screen.dart';
|
||||||
import 'servers_screen.dart';
|
import 'servers_screen.dart';
|
||||||
import 'settings_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(
|
IconButton(
|
||||||
icon: const Icon(Icons.settings_outlined),
|
icon: const Icon(Icons.settings_outlined),
|
||||||
tooltip: '设置',
|
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() {
|
void _openSettings() {
|
||||||
// A phone's list is a drawer: close it before the settings page covers
|
// A phone's list is a drawer: close it before the settings page covers
|
||||||
// the shell.
|
// the shell.
|
||||||
|
|||||||
@@ -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)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -279,7 +279,7 @@ packages:
|
|||||||
source: hosted
|
source: hosted
|
||||||
version: "6.0.0"
|
version: "6.0.0"
|
||||||
flutter_localizations:
|
flutter_localizations:
|
||||||
dependency: transitive
|
dependency: "direct main"
|
||||||
description: flutter
|
description: flutter
|
||||||
source: sdk
|
source: sdk
|
||||||
version: "0.0.0"
|
version: "0.0.0"
|
||||||
|
|||||||
+3
-1
@@ -2,7 +2,7 @@ name: openchamber
|
|||||||
description: "A lightweight OpenChamber client for phones."
|
description: "A lightweight OpenChamber client for phones."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 0.5.0+500
|
version: 0.5.1+501
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.14.0
|
sdk: ^3.14.0
|
||||||
@@ -24,6 +24,8 @@ dependencies:
|
|||||||
zxing2: ^0.2.4
|
zxing2: ^0.2.4
|
||||||
flutter_svg: ^2.5.0
|
flutter_svg: ^2.5.0
|
||||||
package_info_plus: ^10.2.2
|
package_info_plus: ^10.2.2
|
||||||
|
flutter_localizations:
|
||||||
|
sdk: flutter
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
sdk: flutter
|
sdk: flutter
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:flutter_test/flutter_test.dart';
|
||||||
|
import 'package:openchamber/api/scheduled_tasks.dart';
|
||||||
|
import 'package:openchamber/screens/features_screen.dart';
|
||||||
|
import 'package:openchamber/screens/scheduled_tasks_screen.dart';
|
||||||
|
import 'package:openchamber/state.dart';
|
||||||
|
import 'package:openchamber/widgets/scheduled_task_editor.dart';
|
||||||
|
|
||||||
|
Map<String, dynamic> dailyJson() => {
|
||||||
|
'id': 'task_1',
|
||||||
|
'name': '每日同步',
|
||||||
|
'enabled': true,
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'daily',
|
||||||
|
'times': ['09:00', '18:30'],
|
||||||
|
'timezone': 'Asia/Shanghai',
|
||||||
|
},
|
||||||
|
'execution': {
|
||||||
|
'prompt': '总结未完成任务',
|
||||||
|
'providerID': 'axonhub',
|
||||||
|
'modelID': 'deepseek-flash',
|
||||||
|
'agent': 'build',
|
||||||
|
},
|
||||||
|
'state': {
|
||||||
|
'lastStatus': 'success',
|
||||||
|
'lastRunAt': 1000,
|
||||||
|
'nextRunAt': 2000,
|
||||||
|
'lastDurationMs': 4000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
void main() {
|
||||||
|
group('scheduled task wire shape', () {
|
||||||
|
test('a daily task reads its schedule, execution and state', () {
|
||||||
|
final task = ScheduledTask.fromJson(dailyJson());
|
||||||
|
expect(task.id, 'task_1');
|
||||||
|
expect(task.name, '每日同步');
|
||||||
|
expect(task.enabled, isTrue);
|
||||||
|
expect(task.kind, 'daily');
|
||||||
|
expect(task.times, ['09:00', '18:30']);
|
||||||
|
expect(task.timezone, 'Asia/Shanghai');
|
||||||
|
expect(task.prompt, '总结未完成任务');
|
||||||
|
expect(task.useDefaults, isFalse);
|
||||||
|
expect(task.providerId, 'axonhub');
|
||||||
|
expect(task.modelId, 'deepseek-flash');
|
||||||
|
expect(task.agent, 'build');
|
||||||
|
expect(task.lastStatus, 'success');
|
||||||
|
expect(task.nextRunAt, 2000);
|
||||||
|
expect(scheduledScheduleText(task), '每天 09:00、18:30');
|
||||||
|
expect(task.modelLabel, 'axonhub/deepseek-flash · build');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing useDefaults means the session defaults', () {
|
||||||
|
final json = dailyJson();
|
||||||
|
(json['execution'] as Map<String, dynamic>)
|
||||||
|
..remove('providerID')
|
||||||
|
..remove('modelID')
|
||||||
|
..remove('agent');
|
||||||
|
final task = ScheduledTask.fromJson(json);
|
||||||
|
expect(task.useDefaults, isTrue);
|
||||||
|
expect(task.modelLabel, '使用默认模型与智能体');
|
||||||
|
expect(scheduledScheduleText(task), '每天 09:00、18:30');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('weekly, once and cron schedules read as the web client says', () {
|
||||||
|
final weekly = ScheduledTask.fromJson({
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'weekly',
|
||||||
|
'times': ['09:00'],
|
||||||
|
'weekdays': [1, 3],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(weekly), '每周 周一、周三 09:00');
|
||||||
|
|
||||||
|
final once = ScheduledTask.fromJson({
|
||||||
|
'schedule': {
|
||||||
|
'kind': 'once',
|
||||||
|
'date': '2026-12-01',
|
||||||
|
'time': '08:05',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(once), '一次性 2026-12-01 08:05');
|
||||||
|
|
||||||
|
final cron = ScheduledTask.fromJson({
|
||||||
|
'schedule': {'kind': 'cron', 'cron': '*/5 * * * *'},
|
||||||
|
});
|
||||||
|
expect(scheduledScheduleText(cron), 'Cron:*/5 * * * *');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saving sends only the schedule fields the kind uses', () {
|
||||||
|
const daily = ScheduledTask(
|
||||||
|
id: 'task_9',
|
||||||
|
name: '每日同步',
|
||||||
|
kind: 'daily',
|
||||||
|
times: ['09:00'],
|
||||||
|
prompt: '总结',
|
||||||
|
useDefaults: true,
|
||||||
|
);
|
||||||
|
final json = daily.toJson();
|
||||||
|
expect(json['id'], 'task_9');
|
||||||
|
expect(json['schedule'], {'kind': 'daily', 'times': ['09:00']});
|
||||||
|
expect(json['execution'], {'prompt': '总结', 'useDefaults': true});
|
||||||
|
expect(json.containsKey('targetSessionId'), isFalse);
|
||||||
|
|
||||||
|
const once = ScheduledTask(
|
||||||
|
name: '一次性',
|
||||||
|
kind: 'once',
|
||||||
|
date: '2026-12-01',
|
||||||
|
time: '08:05',
|
||||||
|
prompt: '提醒',
|
||||||
|
useDefaults: false,
|
||||||
|
providerId: 'axonhub',
|
||||||
|
modelId: 'deepseek-flash',
|
||||||
|
agent: 'plan',
|
||||||
|
);
|
||||||
|
final onceJson = once.toJson();
|
||||||
|
expect(onceJson.containsKey('id'), isFalse);
|
||||||
|
expect(onceJson['schedule'],
|
||||||
|
{'kind': 'once', 'date': '2026-12-01', 'time': '08:05'});
|
||||||
|
expect(onceJson['execution'], {
|
||||||
|
'prompt': '提醒',
|
||||||
|
'useDefaults': false,
|
||||||
|
'providerID': 'axonhub',
|
||||||
|
'modelID': 'deepseek-flash',
|
||||||
|
'agent': 'plan',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('status labels and relative times', () {
|
||||||
|
expect(scheduledStatusLabel('success'), '成功');
|
||||||
|
expect(scheduledStatusLabel('running'), '运行中');
|
||||||
|
expect(scheduledStatusLabel('failed'), '错误');
|
||||||
|
expect(scheduledStatusLabel(''), '空闲');
|
||||||
|
|
||||||
|
final soon = scheduledRelativeTime(
|
||||||
|
DateTime.now().add(const Duration(minutes: 5)).millisecondsSinceEpoch);
|
||||||
|
expect(soon, contains('分钟后'));
|
||||||
|
final past = scheduledRelativeTime(
|
||||||
|
DateTime.now().subtract(const Duration(hours: 2)).millisecondsSinceEpoch);
|
||||||
|
expect(past, contains('小时前'));
|
||||||
|
expect(scheduledRelativeTime(0), '');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
group('screens', () {
|
||||||
|
testWidgets('全部功能 lists the scheduled tasks entry', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
await tester.pumpWidget(MaterialApp(home: FeaturesScreen(app: app)));
|
||||||
|
|
||||||
|
expect(find.text('全部功能'), findsOneWidget);
|
||||||
|
expect(find.text('计划任务'), findsOneWidget);
|
||||||
|
expect(find.text('按时间向会话发送提示词'), findsOneWidget);
|
||||||
|
|
||||||
|
await tester.tap(find.text('计划任务'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
// No client in the test: the page says so instead of listing tasks.
|
||||||
|
expect(find.byType(ScheduledTasksScreen), findsOneWidget);
|
||||||
|
expect(find.text('未连接服务器'), findsOneWidget);
|
||||||
|
});
|
||||||
|
|
||||||
|
testWidgets('the editor validates and hands back the draft', (tester) async {
|
||||||
|
final app = AppState();
|
||||||
|
addTearDown(app.dispose);
|
||||||
|
ScheduledTask? saved;
|
||||||
|
await tester.pumpWidget(MaterialApp(
|
||||||
|
home: Scaffold(
|
||||||
|
body: SizedBox(
|
||||||
|
height: 900,
|
||||||
|
child: ScheduledTaskEditor(
|
||||||
|
app: app,
|
||||||
|
scopeLabel: 'openchamber-android-native',
|
||||||
|
onSave: (draft) async {
|
||||||
|
saved = draft;
|
||||||
|
return false;
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
));
|
||||||
|
|
||||||
|
expect(find.text('新建计划任务'), findsOneWidget);
|
||||||
|
expect(find.text('运行位置:openchamber-android-native'), findsOneWidget);
|
||||||
|
|
||||||
|
// An empty name is refused with a message, not saved.
|
||||||
|
await tester.tap(find.widgetWithText(TextButton, '保存'));
|
||||||
|
await tester.pump();
|
||||||
|
expect(find.text('任务名称为必填项'), findsOneWidget);
|
||||||
|
expect(saved, isNull);
|
||||||
|
|
||||||
|
await tester.enterText(find.byType(TextField).at(0), '每日同步');
|
||||||
|
await tester.enterText(find.byType(TextField).at(1), '总结未完成任务');
|
||||||
|
await tester.tap(find.widgetWithText(TextButton, '保存'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
|
expect(saved, isNotNull);
|
||||||
|
expect(saved!.name, '每日同步');
|
||||||
|
expect(saved!.prompt, '总结未完成任务');
|
||||||
|
expect(saved!.kind, 'daily');
|
||||||
|
expect(saved!.times, ['09:00']);
|
||||||
|
expect(saved!.enabled, isTrue);
|
||||||
|
expect(saved!.useDefaults, isTrue);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -21,8 +21,16 @@ void main() {
|
|||||||
|
|
||||||
expect(find.text('家里的服务器'), findsOneWidget);
|
expect(find.text('家里的服务器'), findsOneWidget);
|
||||||
expect(find.byIcon(Icons.dns_outlined), findsOneWidget);
|
expect(find.byIcon(Icons.dns_outlined), findsOneWidget);
|
||||||
|
expect(find.byTooltip('全部功能'), findsOneWidget);
|
||||||
expect(find.byTooltip('设置'), findsOneWidget);
|
expect(find.byTooltip('设置'), findsOneWidget);
|
||||||
|
|
||||||
|
// 全部功能 sits left of the settings key and holds the scheduled tasks.
|
||||||
|
await tester.tap(find.byTooltip('全部功能'));
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
expect(find.text('计划任务'), findsOneWidget);
|
||||||
|
await tester.pageBack();
|
||||||
|
await tester.pumpAndSettle();
|
||||||
|
|
||||||
await tester.tap(find.byTooltip('设置'));
|
await tester.tap(find.byTooltip('设置'));
|
||||||
await tester.pumpAndSettle();
|
await tester.pumpAndSettle();
|
||||||
// The settings page replaced the shell.
|
// The settings page replaced the shell.
|
||||||
|
|||||||
Reference in new issue
Block a user