Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

Phase 3b: task questions and needs-you

Marla7b5b5672e650
diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjs
index d9cc5dd..a2c322d 100644
--- a/dsh-runtime/plugins/amb-tasks.mjs
+++ b/dsh-runtime/plugins/amb-tasks.mjs
@@ -6,7 +6,8 @@
// - denies the chat-only tools (present, ask_user_question and the task tools; only registered names, since
// tools.restrict throws on unknown ones),
// - adds the task rules (AMB_TASK_RULES, written by the host) as the last system-prompt section,
-// - registers task_report, which reports the task's state to the host,
+// - registers task_report, which reports the task's state to the host (needs_you carries one question for the
+// user; the host asks it and hands the answer back as the session's next input),
// - refuses every tool call once the host has stopped the task.
// Chat sessions get task_start / task_message / task_list; subagents get none of the task tools.
//
@@ -91,7 +92,7 @@ export function apply(ctx) {
}))
ctx.tools.register(defineTool({
name: 'task_message',
- description: 'Pass the user\'s message to one of their background tasks when they refer to it: a working task sees it at its next step, a finished one resumes with it.',
+ description: 'Pass the user\'s message to one of their background tasks when they refer to it or answer its question: a working task sees it at its next step, a finished or waiting one resumes with it.',
parameters: {
task: { type: 'string', required: true, description: 'Task id or part of its title.' },
text: { type: 'string', required: true, description: 'The message, in the user\'s words.' },
@@ -121,12 +122,14 @@ export function apply(ctx) {
const reportTool = () => defineTool({
name: 'task_report',
- description: 'Report this background task\'s state to the app. done: the task is finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. progress records progress and is never sent. After done or failed, end your turn.',
+ description: 'Report this background task\'s state to the app. done: finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. needs_you: only the user can decide; the app asks them question, and their answer is your next message. progress is recorded, never sent. After done, failed or needs_you, end your turn.',
parameters: {
- state: { type: 'string', required: true, enum: ['progress', 'done', 'failed'], description: 'done, failed, or progress.' },
+ state: { type: 'string', required: true, enum: ['progress', 'needs_you', 'done', 'failed'] },
summary: { type: 'string', required: true, description: 'What you did and found, for the record (not sent to the user).' },
message: { type: 'string', description: 'For done and failed: the one line for the user.' },
files: { type: 'array', items: { type: 'string' }, description: 'Paths of files to send to the user, relative to your folder.' },
+ question: { type: 'string', description: 'For needs_you: one short question.' },
+ options: { type: 'array', items: { type: 'string' }, description: 'For needs_you: choices, if any.' },
},
output: TEXT_OUT,
execute: (args, exec) => host('/dsh/task-report', { sessionId: sessionOf(exec), ...args }, exec.signal),
diff --git a/electron/main.ts b/electron/main.ts
index cccad42..8710d8a 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -4,10 +4,11 @@
* - 在进程内启动 App(机器人运行时 + 渠道 + 管理界面 + 受管 magpie 子进程)
* - 窗口加载本机管理界面(每次启动生成随机令牌,其他本机程序/浏览器无法直接访问)
* - 托盘:显示 / 开机自启 / 退出;关闭窗口=隐藏到托盘(可在设置 → 常规里改为退出);退出时干净关闭 magpie
+ * - 「需要你」:托盘提示和角标是件数(没事时什么都不加),新的一件在窗口不在前台时发一条系统通知(每件最多一次)
* - 设置页里的开机自启、缩放、打开数据目录经 core.desktop 回调到这里(同进程,无需 preload/IPC)
* CLI(npm start)与 Docker 走同一套 src/ 代码,本文件只做桌面外壳。
*/
-import { app, BrowserWindow, Menu, Tray, nativeImage, net, shell, dialog, safeStorage } from "electron";
+import { app, BrowserWindow, Menu, Notification, Tray, nativeImage, net, shell, dialog, safeStorage } from "electron";
import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
@@ -16,6 +17,7 @@ import { loadConfig } from "../src/config.js";
import { App } from "../src/app.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
import { initFileLog, logFilePath, logger, registerSecret, setConsoleLog } from "../src/log.js";
+import { notificationOf, trayTitle, type AttentionItem } from "../src/tasks/attention.js";
const log = logger("desktop");
const SMOKE = process.env.AMB_ELECTRON_SMOKE; // 冒烟测试:截图到该路径后退出
@@ -88,13 +90,69 @@ function createWindow(): void {
void win.loadURL(entryUrl);
}
+/** 打开窗口并切到「需要你」 */
+function openNeeds(): void {
+ showWindow();
+ const go = () => void win?.webContents.executeJavaScript(`location.hash = "#/needs"`).catch(() => {});
+ if (win?.webContents.isLoading()) win.webContents.once("did-finish-load", go);
+ else go();
+}
+
+/** 「需要你」的件数(托盘菜单、提示、角标用) */
+let needsCount = 0;
+
+/**
+ * 「需要你」变了:托盘提示与角标是件数(macOS 托盘标题和程序坞、Linux 的启动器角标、Windows 任务栏上的小黄点),
+ * 没事时全部清掉;新的一件、窗口又不在前台时发一条系统通知,点开就是「需要你」。每件最多通知一次(core 记着)。
+ */
+function onAttention(items: AttentionItem[]): void {
+ needsCount = items.length;
+ tray?.setToolTip(trayTitle(PRODUCT, needsCount));
+ if (process.platform === "darwin") tray?.setTitle(needsCount ? String(needsCount) : "");
+ app.setBadgeCount(needsCount);
+ if (isWin) win?.setOverlayIcon(needsCount ? overlayDot() : null, needsCount ? `${needsCount} 件事需要你` : "");
+ renderTray?.();
+ const fresh = core?.attention.takeNew(items) ?? [];
+ const looking = !!win && win.isVisible() && win.isFocused();
+ if (looking || !fresh.length || !Notification.isSupported()) return;
+ // 一下来好几件时只发最早的两条,其余在「需要你」里
+ for (const it of fresh.slice(0, 2)) {
+ const n = new Notification({ ...notificationOf(it), icon: windowIconPath() });
+ n.on("click", openNeeds);
+ n.show();
+ }
+}
+
+/** Windows 任务栏图标上的小黄点(16×16,BGRA):有事时才挂上 */
+let dot: Electron.NativeImage | undefined;
+function overlayDot(): Electron.NativeImage {
+ if (dot) return dot;
+ const size = 16;
+ const buf = Buffer.alloc(size * size * 4);
+ for (let y = 0; y < size; y++)
+ for (let x = 0; x < size; x++) {
+ const d = Math.hypot(x + 0.5 - size / 2, y + 0.5 - size / 2);
+ const a = Math.max(0, Math.min(1, size / 2 - 1 - d));
+ const i = (y * size + x) * 4;
+ // 琥珀色(设计库的 --amber-300 #f2b544,深色界面里的 --amber)
+ buf[i] = 0x44;
+ buf[i + 1] = 0xb5;
+ buf[i + 2] = 0xf2;
+ buf[i + 3] = Math.round(a * 255);
+ }
+ dot = nativeImage.createFromBitmap(buf, { width: size, height: size });
+ return dot;
+}
+
function buildTray(): void {
// 不要 resize:会丢掉 ico 的多尺寸帧和 @2x 图,托盘在高分屏上发糊
tray = new Tray(nativeImage.createFromPath(trayIconPath()));
- tray.setToolTip(PRODUCT);
+ tray.setToolTip(trayTitle(PRODUCT, needsCount));
const render = () =>
tray!.setContextMenu(
Menu.buildFromTemplate([
+ // 有事在等你时才有这一项
+ ...(needsCount ? [{ label: `需要你(${needsCount})`, click: openNeeds }, { type: "separator" as const }] : []),
{ label: `打开 ${PRODUCT}`, click: showWindow },
{ label: "在浏览器中打开", click: () => void shell.openExternal(entryUrl) },
{ type: "separator" },
@@ -154,6 +212,8 @@ async function boot(): Promise<void> {
log.info(`数据目录:${dataDir}`);
log.info(`管理界面:${core.web.url}`);
if (!SMOKE) buildTray();
+ // 「需要你」:托盘、角标、系统通知
+ if (!SMOKE) core.attention.onChange(onAttention);
const atLogin = process.argv.includes("--hidden") || (process.platform === "darwin" && app.getLoginItemSettings().wasOpenedAtLogin);
if (!atLogin || SMOKE) createWindow();
if (SMOKE) await smoke(SMOKE);
diff --git a/src/agent/approvals.ts b/src/agent/approvals.ts
index 981a583..5d2d2b3 100644
--- a/src/agent/approvals.ts
+++ b/src/agent/approvals.ts
@@ -5,6 +5,8 @@ import { logger } from "../log.js";
const log = logger("approvals");
export const APPROVAL_TTL_MS = 10 * 60_000;
+/** 后台任务里的审批:任务会话的那次调用一直等着,12 小时没人批就拒绝(设计第 7 节) */
+export const TASK_APPROVAL_TTL_MS = 12 * 3600_000;
export interface QuestionItem {
id: string;
@@ -27,13 +29,39 @@ export interface ReplyResult {
ack?: string;
}
+/**
+ * 渠道里的一条回复能不能算对后台任务的提问 / 审批的回答(设计第 6 节"回答任务的提问"):
+ * 引用了推给用户的那条提示、以 4 位编号开头,或者那条提示是机器人最后一条消息时只回了选项编号 / 选项原文 / y、n。
+ * 其余都是普通聊天:任务的提问可以等几个小时,不能像聊天回合里的提问那样"随便回一句就算"。
+ */
+export interface ReplyContext {
+ /** 用户引用的那条消息的文字(微信的引用) */
+ quote?: string;
+ /** 去掉引用之后用户自己写的 */
+ plain?: string;
+ /** 引用的是不是推给用户的这一条提示 */
+ quotes?: (row: ApprovalRow, quote: string) => boolean;
+ /** 这一条的提示是不是机器人在这个会话里最后发的一条消息 */
+ latest?: (row: ApprovalRow) => boolean;
+ /** 回答了任务的提问之后给用户的一句话 */
+ answered?: (row: ApprovalRow) => string | undefined;
+}
+
+export type ApprovalEvent = { type: "created" | "decided"; row: ApprovalRow };
+
+const YES = /^(y|yes|ok|是|同意|批准|允许)$/i;
+const YES_NO = /^(y|yes|ok|是|同意|批准|允许|n|no|否|拒绝|不)\s*[#::]?\s*(\d{4})?$/i;
+
/**
* 审批中心:DSH 插件经 bridge 发来的审批/提问请求落入 sqlite(4 位码、10 分钟过期、重启后仍可查),
* 由微信文本 “y 1234 / n 1234”、飞书卡片按钮或网页/API 决定。允许 = allow once;拒绝/超时/退出 = reject。
+ * 后台任务的也在这里(taskId):任务会话里的审批(阻塞,12 小时),任务报 needs_you 的提问(不阻塞、不过期,
+ * 回答成为任务的新输入)。任务的提示不进聊天回合的出口,由任务服务推给用户(listen 的 created)。
*/
export class ApprovalCenter {
private waiters = new Map<string, Set<() => void>>();
private sinks = new Map<string, PromptSink>();
+ private listeners = new Set<(e: ApprovalEvent) => void>();
private timer: NodeJS.Timeout | undefined;
/** 决定后的回调(例如通知 UI/日志) */
onDecided: ((row: ApprovalRow) => void) | undefined;
@@ -47,10 +75,31 @@ export class ApprovalCenter {
return (this.opts.now ?? Date.now)();
}
- /** 启动:上次运行遗留的 pending(DSH 子进程已不在)一律视为拒绝;之后定时清理过期。 */
+ /** 还在等:没过期(0 = 不过期) */
+ private alive(r: ApprovalRow): boolean {
+ return r.expiresAt === 0 || r.expiresAt > this.now();
+ }
+
+ /** 订阅新建与决定(任务服务推提示、更新阶段,"需要你"刷新);返回取消函数 */
+ listen(fn: (e: ApprovalEvent) => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+
+ private emit(e: ApprovalEvent): void {
+ for (const fn of this.listeners) {
+ try {
+ fn(e);
+ } catch (err) {
+ log.warn("approval listener failed", { message: (err as Error).message });
+ }
+ }
+ }
+
+ /** 启动:上次运行遗留的阻塞请求(DSH 那次调用已经不在了)一律视为拒绝;任务的提问留着。之后定时清理过期。 */
start(): void {
for (const r of this.store.listApprovals({ status: "pending", limit: 500 })) {
- this.store.decideApproval(r.id, "expired", "restart");
+ if (r.blocking) this.store.decideApproval(r.id, "expired", "restart");
}
this.timer ??= setInterval(() => this.sweep(), 5000);
this.timer.unref?.();
@@ -59,14 +108,14 @@ export class ApprovalCenter {
stop(): void {
if (this.timer) clearInterval(this.timer);
this.timer = undefined;
- // 进程退出:未决请求按拒绝处理
- for (const r of this.store.listApprovals({ status: "pending", limit: 500 })) this.finish(r.id, "expired", "shutdown");
+ // 进程退出:阻塞着的按拒绝处理;任务的提问留到下次启动
+ for (const r of this.store.listApprovals({ status: "pending", limit: 500 })) if (r.blocking) this.finish(r.id, "expired", "shutdown");
}
sweep(): void {
const now = this.now();
for (const r of this.store.listApprovals({ status: "pending", limit: 500 })) {
- if (r.expiresAt <= now) this.finish(r.id, "expired", "timeout");
+ if (r.expiresAt && r.expiresAt <= now) this.finish(r.id, "expired", "timeout");
}
}
@@ -80,8 +129,23 @@ export class ApprovalCenter {
return String(crypto.randomInt(1000, 10000));
}
- create(input: { kind: ApprovalRow["kind"]; botId: string; conversationId: string; sessionId: string; tool: string; detail: string; reason: string; payload?: string }): ApprovalRow {
+ /** ttlMs = 0:不过期(任务的提问) */
+ create(input: {
+ kind: ApprovalRow["kind"];
+ botId: string;
+ conversationId: string;
+ sessionId: string;
+ tool: string;
+ detail: string;
+ reason: string;
+ payload?: string;
+ taskId?: string;
+ runId?: string;
+ blocking?: boolean;
+ ttlMs?: number;
+ }): ApprovalRow {
const now = this.now();
+ const ttl = input.ttlMs ?? this.opts.ttlMs ?? APPROVAL_TTL_MS;
const row = this.store.insertApproval({
id: crypto.randomUUID(),
code: this.newCode(),
@@ -94,11 +158,16 @@ export class ApprovalCenter {
reason: input.reason.slice(0, 1000),
payload: input.payload ?? "",
createdAt: now,
- expiresAt: now + (this.opts.ttlMs ?? APPROVAL_TTL_MS),
+ expiresAt: ttl === 0 ? 0 : now + ttl,
+ taskId: input.taskId ?? "",
+ runId: input.runId ?? "",
+ blocking: input.blocking !== false,
});
- log.info(`${row.kind} ${row.code} created`, { bot: row.botId, tool: row.tool });
- const sink = this.sinks.get(row.conversationId);
+ log.info(`${row.kind} ${row.code} created`, { bot: row.botId, tool: row.tool, ...(row.taskId ? { task: row.taskId } : {}) });
+ // 聊天回合的提示进这一轮的回复;任务的由任务服务推(不混进同一会话里正在进行的聊天回复)
+ const sink = row.taskId ? undefined : this.sinks.get(row.conversationId);
if (sink) void sink(row).catch((e) => log.warn("prompt sink failed", { message: (e as Error).message }));
+ this.emit({ type: "created", row });
return row;
}
@@ -118,6 +187,7 @@ export class ApprovalCenter {
this.onDecided?.(row);
for (const w of this.waiters.get(id) ?? []) w();
this.waiters.delete(id);
+ this.emit({ type: "decided", row });
}
return ok;
}
@@ -125,7 +195,7 @@ export class ApprovalCenter {
decide(id: string, allow: boolean, by: string): boolean {
const r = this.store.getApproval(id);
if (!r || r.kind !== "approval") return false;
- if (r.expiresAt <= this.now()) {
+ if (!this.alive(r)) {
this.finish(id, "expired", "timeout");
return false;
}
@@ -138,6 +208,13 @@ export class ApprovalCenter {
return this.finish(id, "answered", by, JSON.stringify(answer));
}
+ /** 用一段文字回答这一个提问:编号对应选项,其余算用户自己写的回答 */
+ answerText(id: string, text: string, by: string): boolean {
+ const r = this.store.getApproval(id);
+ if (!r || r.kind !== "question" || r.status !== "pending") return false;
+ return this.answer(id, parseAnswer(questionsOf(r), text), by);
+ }
+
cancel(id: string, by = "agent"): boolean {
return this.finish(id, "cancelled", by);
}
@@ -161,44 +238,87 @@ export class ApprovalCenter {
}
pending(conversationId: string, kind?: ApprovalRow["kind"]): ApprovalRow[] {
- return this.store.listApprovals({ status: "pending", conversationId }).filter((r) => (!kind || r.kind === kind) && r.expiresAt > this.now());
+ return this.store.listApprovals({ status: "pending", conversationId }).filter((r) => (!kind || r.kind === kind) && this.alive(r));
+ }
+
+ /** 这个会话里聊天回合在等的(不含后台任务的):中止、/reset 只作废这些 */
+ pendingChat(conversationId: string): ApprovalRow[] {
+ return this.pending(conversationId).filter((r) => !r.taskId);
+ }
+
+ /** 这个任务还在等的提问和审批 */
+ pendingForTask(taskId: string): ApprovalRow[] {
+ return this.store.listApprovals({ status: "pending", taskId, limit: 50 }).filter((r) => this.alive(r));
+ }
+
+ /** 所有还在等的("需要你") */
+ pendingAll(): ApprovalRow[] {
+ return this.store.listApprovals({ status: "pending", limit: 500 }).filter((r) => this.alive(r));
}
/**
* 解析渠道里的用户回复(在每用户串行队列之前调用,避免与等待审批的回合互相阻塞):
- * - “y 1234” / “n 1234”(也接受 是/否/同意/拒绝/yes/no;会话中只有一个待批准时可省略编号)
- * - 有待回答的提问时,回复编号(多选用逗号/空格分隔)或直接回复文字
+ * - 引用了任务推来的提示(ctx.quote):这条就是对它的回答
+ * - “y 1234” / “n 1234”(也接受 是/否/同意/拒绝/yes/no);聊天里只有一个待批准、或任务的审批是机器人最后一条消息时可省略编号
+ * - “1234 中文”:以任务提问的编号开头
+ * - 聊天回合在等的提问:回复编号(多选用逗号/空格分隔)或直接回复文字
+ * - 任务的提问是机器人最后一条消息:只认选项编号或选项原文
*/
- handleReply(conversationId: string, text: string, by: string): ReplyResult {
+ handleReply(conversationId: string, text: string, by: string, ctx: ReplyContext = {}): ReplyResult {
const t = text.trim();
if (!t || t.startsWith("/")) return { handled: false };
- const m = /^(y|yes|ok|是|同意|批准|允许|n|no|否|拒绝|不)\s*[#::]?\s*(\d{4})?$/i.exec(t);
- if (m && (m[2] || this.pending(conversationId, "approval").length)) {
- const allow = /^(y|yes|ok|是|同意|批准|允许)$/i.test(m[1]);
- let row: ApprovalRow | undefined;
- if (m[2]) {
- row = this.store.pendingApprovalByCode(m[2]);
- if (!row || row.conversationId !== conversationId || row.kind !== "approval") {
- return { handled: true, ack: `⚠️ 没有编号为 ${m[2]} 的待批准请求(可能已过期或已处理)` };
- }
- } else {
- const list = this.pending(conversationId, "approval");
- if (list.length === 1) row = list[0];
- else return { handled: true, ack: `有 ${list.length} 个待批准请求,请带上编号回复,例如 y ${list[0].code}` };
+ const all = this.pending(conversationId);
+ const chat = all.filter((r) => !r.taskId);
+ const task = all.filter((r) => r.taskId);
+ // 引用了任务的提示
+ const quote = ctx.quote;
+ const quoted = quote ? task.find((r) => ctx.quotes?.(r, quote)) : undefined;
+ if (quoted) return this.replyTo(quoted, (ctx.plain ?? t).trim(), by, ctx);
+ const m = YES_NO.exec(t);
+ if (m && m[2]) {
+ const row = this.store.pendingApprovalByCode(m[2]);
+ if (!row || row.conversationId !== conversationId || row.kind !== "approval") {
+ return { handled: true, ack: `⚠️ 没有编号为 ${m[2]} 的待批准请求(可能已过期或已处理)` };
}
- const ok = this.decide(row.id, allow, by);
- if (!ok) return { handled: true, ack: `⚠️ 请求 ${row.code} 已过期或已处理` };
- return { handled: true, ack: allow ? `✅ 已批准 ${row.code}(仅本次)` : `❌ 已拒绝 ${row.code}` };
+ return this.decideReply(row, YES.test(m[1]), by);
}
- const q = this.pending(conversationId, "question")[0];
+ if (m) {
+ const list = [...chat.filter((r) => r.kind === "approval"), ...task.filter((r) => r.kind === "approval" && ctx.latest?.(r))];
+ if (list.length === 1) return this.decideReply(list[0], YES.test(m[1]), by);
+ if (list.length > 1) return { handled: true, ack: `有 ${list.length} 个待批准请求,请带上编号回复,例如 y ${list[0].code}` };
+ }
+ // 「1234 中文」:以任务提问的编号开头
+ const c = /^(\d{4})(?:\s*[::,,.。、]\s*|\s+)(\S[\s\S]*)$/.exec(t);
+ const byCode = c ? task.find((r) => r.kind === "question" && r.code === c[1]) : undefined;
+ if (c && byCode) return this.replyTo(byCode, c[2], by, ctx);
+ // 聊天回合在等的提问:直接回复就是回答
+ const q = chat.find((r) => r.kind === "question");
if (q) {
- const questions = safeJson<QuestionItem[]>(q.payload, []);
- const answer = parseAnswer(questions, t);
- this.answer(q.id, answer, by);
+ this.answer(q.id, parseAnswer(questionsOf(q), t), by);
return { handled: true };
}
+ // 任务的提问是机器人最后一条消息:只认选项编号或选项原文
+ const last = task.find((r) => r.kind === "question" && ctx.latest?.(r));
+ if (last && isOptionReply(questionsOf(last), t)) return this.replyTo(last, t, by, ctx);
return { handled: false };
}
+
+ private decideReply(row: ApprovalRow, allow: boolean, by: string): ReplyResult {
+ if (!this.decide(row.id, allow, by)) return { handled: true, ack: `⚠️ 请求 ${row.code} 已过期或已处理` };
+ return { handled: true, ack: allow ? `✅ 已批准 ${row.code}(仅本次)` : `❌ 已拒绝 ${row.code}` };
+ }
+
+ /** 认定是对这一条的回答:提问记下回答;审批要 y / n */
+ private replyTo(row: ApprovalRow, text: string, by: string, ctx: ReplyContext): ReplyResult {
+ if (row.kind === "approval") {
+ const m = YES_NO.exec(text);
+ if (!m || (m[2] && m[2] !== row.code)) return { handled: true, ack: `回复 y ${row.code} 批准,n ${row.code} 拒绝` };
+ return this.decideReply(row, YES.test(m[1]), by);
+ }
+ if (!text) return { handled: true, ack: "引用时写上你的回答" };
+ if (!this.answerText(row.id, text, by)) return { handled: true, ack: "这个问题已经回答过了" };
+ return { handled: true, ack: ctx.answered?.(row) };
+ }
}
function safeJson<T>(s: string, d: T): T {
@@ -209,6 +329,31 @@ function safeJson<T>(s: string, d: T): T {
}
}
+/** 提问行里的问题 */
+export function questionsOf(row: ApprovalRow): QuestionItem[] {
+ return row.kind === "question" ? safeJson<QuestionItem[]>(row.payload, []) : [];
+}
+
+/** 只是选项编号(多选可以几个)或某个选项的原文:光回这个才算回答"最后一条消息"的那个提问 */
+export function isOptionReply(questions: QuestionItem[], text: string): boolean {
+ const q = questions.length === 1 ? questions[0] : undefined;
+ const opts = q?.options ?? [];
+ if (!q || !opts.length) return false;
+ const t = text.trim();
+ if (opts.some((o) => o.label === t)) return true;
+ const nums = t.split(/[\s,,、]+/).filter(Boolean);
+ return nums.length > 0 && (!!q.multiSelect || nums.length === 1) && nums.every((n) => /^\d+$/.test(n) && Number(n) >= 1 && Number(n) <= opts.length);
+}
+
+/** 记下的回答 → 一句话("中文"、"中文、英文"、用户自己写的) */
+export function answerLine(row: ApprovalRow): string {
+ const a = safeJson<QuestionAnswer>(row.result, { answers: [] }).answers ?? [];
+ return a
+ .map((x) => [...(x.selected ?? []), ...(x.custom ? [x.custom] : [])].join("、"))
+ .filter(Boolean)
+ .join("\n");
+}
+
/** 把用户的文本回复映射成 ask_user_question 的答案:多个问题按行对应;编号选项;其余作为自定义回答。 */
export function parseAnswer(questions: QuestionItem[], text: string): QuestionAnswer {
const lines = questions.length > 1 ? text.split(/\n+/).map((s) => s.trim()).filter(Boolean) : [text.trim()];
@@ -236,7 +381,7 @@ export function promptText(row: ApprovalRow): string {
const why = row.reason && !row.detail ? `(${row.reason.slice(0, 200)})` : "";
return `需批准: ${row.tool}${cmd}${why} — 回复 y ${row.code} / n ${row.code}`;
}
- const qs = safeJson<QuestionItem[]>(row.payload, []);
+ const qs = questionsOf(row);
const blocks = qs.map((q, i) => {
const head = `${qs.length > 1 ? `${i + 1}) ` : ""}${q.question}${q.detail ? `\n${q.detail}` : ""}`;
const opts = (q.options ?? []).map((o, j) => ` ${j + 1}. ${o.label}${o.description ? ` — ${o.description}` : ""}`);
@@ -245,3 +390,32 @@ export function promptText(row: ApprovalRow): string {
const hint = qs.length > 1 ? "(每行回答一个问题:回复编号或直接写答案)" : qs[0]?.options?.length ? `(回复编号${qs[0].multiSelect ? ",可多选用逗号分隔" : ""},或直接写答案)` : "(直接回复答案)";
return `❓ ${blocks.join("\n\n")}\n${hint}`;
}
+
+/**
+ * 后台任务推给用户的提示(设计第 6 节的消息样式):
+ * 提问「❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)」;
+ * 审批「需批准(任务「清理旧构建」):`rm -rf build/` — 回复 y 4821 / n 4821」。
+ */
+export function taskPromptText(row: ApprovalRow, title: string): string {
+ if (row.kind === "approval") {
+ const what = row.detail ? `\`${row.detail.replace(/`/g, "'").slice(0, 300)}\`` : `${row.tool}${row.reason ? `(${row.reason.slice(0, 200)})` : ""}`;
+ return `需批准(任务「${title}」):${what} — 回复 y ${row.code} / n ${row.code}`;
+ }
+ const q = questionsOf(row)[0];
+ const opts = (q?.options ?? []).map((o, i) => `${i + 1}. ${o.label}`);
+ const hint = opts.length ? `(回复编号${q?.multiSelect ? ",可多选" : ""},或引用这条消息回答)` : "(引用这条消息回答)";
+ return [`❓「${title}」想问你:${q?.question ?? row.detail}`, ...opts, hint].join("\n");
+}
+
+/** 卡片渠道(飞书)的按钮:审批是允许 / 拒绝;单选的提问是每个选项一个按钮 */
+export function promptButtons(row: ApprovalRow): Array<{ label: string; value: Record<string, string>; style: "primary" | "danger" | "default" }> | undefined {
+ if (row.kind === "approval") {
+ return [
+ { label: "允许(仅本次)", value: { amb: "approval", id: row.id, decision: "allow" }, style: "primary" },
+ { label: "拒绝", value: { amb: "approval", id: row.id, decision: "deny" }, style: "danger" },
+ ];
+ }
+ const qs = questionsOf(row);
+ const single = qs.length === 1 ? qs[0] : undefined;
+ return single?.options?.length && !single.multiSelect ? single.options.map((o, i) => ({ label: o.label, value: { amb: "question", id: row.id, option: String(i + 1) }, style: "default" as const })) : undefined;
+}
diff --git a/src/agent/host.ts b/src/agent/host.ts
index ba8a776..1d62c9d 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -1525,6 +1525,12 @@ exec "$REAL" "$@"
if (n.params.status === "running") this.taskBusy.add(root);
else if (n.params.status === "idle") this.taskBusy.delete(root);
}
+ // 任务会话(和它的子代理)的工具调用也记下:它们要批准时,审批里显示这条命令
+ const ev = n.method === "session.event" ? n.params?.event : undefined;
+ if (ev?.type === "tool/call" && ev.data?.callId) {
+ this.calls.set(String(ev.data.callId), { name: String(ev.data.name), args: String(ev.data.arguments ?? ""), at: Date.now() });
+ if (this.calls.size > 500) this.calls.delete(this.calls.keys().next().value!);
+ }
this.o.onTaskEvent?.(root, n);
return;
}
@@ -1561,6 +1567,11 @@ exec "$REAL" "$@"
}
}
+ /** 这个会话是不是任务会话或它的子代理:是就给出任务会话 id(子代理里的审批也算这个任务的) */
+ taskRootOf(sessionId: string): string | undefined {
+ return this.taskRoot({ method: "session.event", params: { sessionId } } as SdkNotification);
+ }
+
/** 通知属于哪个任务会话(task-* 本身,或它的子代理);不属于任务就是 undefined */
private taskRoot(n: SdkNotification): string | undefined {
const sub = n.method === "subagent.started" || n.method === "subagent.finished";
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index fa53a33..4773636 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -9,7 +9,7 @@ import { ServerCompaction, type CompactEndpoint, type CompactionEvent } from "./
import { ActivityLog, promotedJob, type ActivityStep } from "./activity.js";
import { ApiFallbacks, type ApiFallback } from "./api-fallback.js";
import type { MediaModel, MediaPlan, MediaService } from "./media.js";
-import { APPROVAL_TTL_MS, ApprovalCenter, type QuestionItem } from "./approvals.js";
+import { APPROVAL_TTL_MS, ApprovalCenter, TASK_APPROVAL_TTL_MS, type QuestionItem } from "./approvals.js";
import { MemoryError, MemoryStore, type Scope } from "./memory.js";
import type { TaskHost, TaskService } from "../tasks/service.js";
import { DEFAULT_SETTINGS, type BotSettings, type MediaConfirm } from "./settings.js";
@@ -316,7 +316,7 @@ export class AgentManager {
const idleMs = this.o.idleTimeoutMs ?? 10 * 60_000;
const watchdog = setInterval(() => {
if (!t.lastProgress || t.abort.signal.aborted) return;
- if (this.approvals.pending(conv).length || t.tools.size || t.jobs.size || t.media) t.lastProgress = Date.now();
+ if (this.approvals.pendingChat(conv).length || t.tools.size || t.jobs.size || t.media) t.lastProgress = Date.now();
else if (Date.now() - t.lastProgress > idleMs) {
log.warn("agent turn idle, stopping", { bot: botId, conversationId: conv, idleMs, lastStep: t.activity.last });
this.halt(conv, t, new TurnStopped("idle", idleMs));
@@ -350,7 +350,7 @@ export class AgentManager {
} catch (e) {
if (e instanceof TurnStopped && e.reason === "timeout") {
t.activity.end("超过单回合上限");
- for (const r of this.approvals.pending(conv)) this.approvals.cancel(r.id, "stopped");
+ for (const r of this.approvals.pendingChat(conv)) this.approvals.cancel(r.id, "stopped");
}
throw e;
} finally {
@@ -392,7 +392,7 @@ export class AgentManager {
t.activity.end(why.reason === "user" ? "用户中止" : why.reason === "idle" ? "长时间没有进展,自动中止" : "超过单回合上限");
t.abort.abort(why);
// 这一轮还在等的批准 / 回答随之作废(回合被中止,没人再等它们)
- for (const r of this.approvals.pending(conv)) this.approvals.cancel(r.id, "stopped");
+ for (const r of this.approvals.pendingChat(conv)) this.approvals.cancel(r.id, "stopped");
}
/** 跟踪代理自己醒来的一轮:不用等管家闸门(代理已经在跑),结束后同样交给管家判定 */
@@ -800,7 +800,7 @@ export class AgentManager {
this.o.store.clearAgentSession(conversationId);
this.o.store.setKV(`seed:${conversationId}`, "");
this.mediaGrants.delete(conversationId);
- for (const r of this.approvals.pending(conversationId)) this.approvals.cancel(r.id, "reset");
+ for (const r of this.approvals.pendingChat(conversationId)) this.approvals.cancel(r.id, "reset");
}
async stopBot(botId: string): Promise<void> {
@@ -901,12 +901,17 @@ export class AgentManager {
};
}
+ /** 任务会话或它的子代理属于哪个任务(审批落到请求这个任务的会话,"需要你"里也认得它) */
+ private taskOf(botId: string, sessionId: string) {
+ return this.tasks?.taskOfSession(sessionId, this.hosts.get(botId)?.taskRootOf(sessionId));
+ }
+
private resolveConversation(botId: string, sessionId: string): string {
const c = this.o.store.conversationForSession(sessionId);
if (c) return c;
- // 后台任务会话:落到请求它的会话(3b 再把审批推给用户)
- const task = this.tasks?.conversationOf(sessionId);
- if (task) return task;
+ // 后台任务会话(和它的子代理):落到请求它的会话
+ const task = this.taskOf(botId, sessionId);
+ if (task) return task.conversationId;
const active = [...(this.activeConvs.get(botId) ?? [])];
return active.length === 1 ? active[0] : "";
}
@@ -916,9 +921,12 @@ export class AgentManager {
if (!this.hosts.has(botId)) throw new Error("unknown bot");
const sessionId = String(b?.sessionId ?? "");
const conversationId = this.resolveConversation(botId, sessionId);
+ // 后台任务里来的:记下是哪个任务、哪个 run,由任务服务推给用户;没人在旁边看,等 12 小时
+ const t = this.o.store.conversationForSession(sessionId) ? undefined : this.taskOf(botId, sessionId);
+ const task = t ? { taskId: t.taskId, runId: t.runId, ttlMs: TASK_APPROVAL_TTL_MS } : {};
if (b?.kind === "question") {
const qs = (Array.isArray(b.questions) ? b.questions : []) as QuestionItem[];
- const row = this.approvals.create({ kind: "question", botId, conversationId, sessionId, tool: "ask_user_question", detail: qs.map((q) => q.question).join(" / "), reason: "", payload: JSON.stringify(qs) });
+ const row = this.approvals.create({ kind: "question", botId, conversationId, sessionId, tool: "ask_user_question", detail: qs.map((q) => q.question).join(" / "), reason: "", payload: JSON.stringify(qs), ...task });
return { id: row.id };
}
const host = this.hosts.get(botId)!;
@@ -937,6 +945,7 @@ export class AgentManager {
tool,
detail: call ? callDetail(call.name, call.args) : "",
reason: String(b?.reason ?? ""),
+ ...task,
});
return { id: row.id };
}
diff --git a/src/agent/prompts/tasks.ts b/src/agent/prompts/tasks.ts
index f89f1a2..2bca727 100644
--- a/src/agent/prompts/tasks.ts
+++ b/src/agent/prompts/tasks.ts
@@ -3,6 +3,7 @@
* 重启后的恢复说明、没有报告时的提醒。改这里的文字要过 test/prompts.unit.test.ts(必须有、不能有的句子和长度上限)。
*
* 沟通规则改编自 dsh-superagent(MIT,DeepSeek)的 worker 提示词:只在做完、需要决定或做不下去时说话,一句话,不汇报进展。
+ * 需要决定时(3b):先自己选合理的默认;非用户定不可才报 needs_you,一次一个问题,回答作为下一条消息回来。
*/
/** 任务会话的系统提示词段:名字与位置(排在机器人段 amb:bot 之后,同时冲突时以它为准) */
@@ -12,8 +13,8 @@ export const TASK_SECTION_ORDER = 20_100;
/** 任务会话的规则 */
export const TASK_RULES = [
"# 后台任务(优先于上面的聊天规则)",
- "你在后台独立完成一个任务,用户不在旁边看,也不会回答问题。任务和用户的原话在第一条消息里;当前目录是这个任务的文件夹,产出的文件放在这里。",
- "- 不要问用户:需要决定时自己选一个合理的做法,在结果里说明。",
+ "你在后台独立完成一个任务,用户不在旁边。任务和用户的原话在第一条消息里;当前目录是这个任务的文件夹,产出的文件放在这里。",
+ "- 能自己定的就选一个合理的做法,在结果里说明;非用户定不可才问:task_report 报 needs_you 和一个问题(有选项就给),结束这一轮。",
"- 做会改变外部的事(发送、发帖、付款、删除、调用会改动东西的接口)之前和之后,各在 .task/journal.md 里追加一行。",
"- 做完或做不下去时调用 task_report:state 为 done 或 failed,message 是给用户的一句话(不超过 300 字:结果是什么、在哪里),files 列出要发给用户的文件。然后结束这一轮。",
"- 中途不用汇报;想记下进展可以报 progress,不会发给用户。",
diff --git a/src/app.ts b/src/app.ts
index c767487..5587d81 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -43,6 +43,7 @@ import { MediaService, pickDefault } from "./agent/media.js";
import { COMPACT_ENDPOINT, serverCompactionEnabled, type CompactEndpoint } from "./agent/server-compaction.js";
import type { BotSettings } from "./agent/settings.js";
import { TaskService } from "./tasks/service.js";
+import { Attention, approvalItems, type AttentionItem } from "./tasks/attention.js";
const log = logger("app");
@@ -120,6 +121,8 @@ export class App {
readonly access: AccessControl;
/** 后台任务:自己的会话和文件夹,结果经出站队列回到请求它的会话 */
readonly tasks: TaskService;
+ /** "需要你":所有机器人里在等人的事(侧栏、托盘角标、系统通知) */
+ readonly attention: Attention;
web: WebServer | undefined;
desktop: DesktopHooks | undefined;
/** Modelflare 账户(登录、余额、预算);start() 时创建,桌面外壳的钥匙串那时已就绪 */
@@ -210,15 +213,23 @@ export class App {
: undefined,
onNotice: (text) => this.notice("warn", text),
});
+ this.attention = new Attention({ store: this.store });
this.tasks = new TaskService({
store: this.store,
host: this.agent.taskHost(),
outbox: this.outbox,
+ approvals: this.agent.approvals,
+ onChange: () => this.attention.kick(),
defaultModel: () => this.config.llm.defaultModel,
route: (botId, model) => this.routeModel(botId, model),
maxBackground: config.agent.maxBackground,
});
this.agent.tasks = this.tasks;
+ // "需要你"的三份:在等的提问和审批、任务(失败、没送到)、渠道(微信登录过期)
+ this.attention.addSource(() => approvalItems(this.store, this.agent.approvals.pendingAll()));
+ this.attention.addSource(() => this.tasks.attention());
+ this.attention.addSource(() => this.loginAttention());
+ this.agent.approvals.listen(() => this.attention.kick());
this.runtime = new BotRuntime({
agent: this.agent,
store: this.store,
@@ -231,6 +242,17 @@ export class App {
});
}
+ /** 渠道登录过期了(微信 -14):"需要你"里一行,去重新扫码 */
+ private loginAttention(): AttentionItem[] {
+ const out: AttentionItem[] = [];
+ for (const [botId, ch] of this.channels) {
+ const st = ch.weixin?.status;
+ if (st?.state !== "expired") continue;
+ out.push({ id: `login:${botId}:weixin`, kind: "login", botId, botName: this.store.getBot(botId)?.name ?? botId, subject: "微信登录已过期", status: "", line: "", since: st.since, severity: "err", actions: ["relogin"], channel: "weixin" });
+ }
+ return out;
+ }
+
/** 主动给某个渠道的某个人发通知(使用请求、批准结果):能发就进出站队列,返回是否已排队 */
private reach(to: { botId: string; channel: string; peerId: string }, text: string, id: string): boolean {
const ch = this.channels.get(to.botId);
@@ -515,6 +537,7 @@ export class App {
this.runtime.shutdown();
// 后台任务不再开始新的 run;跑着的留在库里,下次启动时恢复
this.tasks.stop();
+ this.attention.stop();
this.offPwsh?.();
if (this.accountTimer) clearInterval(this.accountTimer);
if (this.picksTimer) clearInterval(this.picksTimer);
@@ -649,7 +672,10 @@ export class App {
pollTimeoutMs: this.opts.weixinPollTimeoutMs,
outbox: this.outbox,
});
- ch.weixin.onExpired = () => this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);
+ ch.weixin.onExpired = () => {
+ this.notice("warn", `机器人「${bot.name}」微信登录已过期,请在信息面板的「渠道」里重新扫码`);
+ this.attention.kick();
+ };
const wx = ch.weixin;
// 代理自己醒来的一轮:经出站队列发给这个微信用户(发送时才查 24 小时窗口和配额)
this.runtime.registerReplier(bot.id, "weixin", (conv, _handle, key) => ({ out: wx.followUp(conv.peerId, key) }));
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 34ee6c9..f29ddd7 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -10,7 +10,7 @@ import { describeStep, fmtSecs, type ActivityStep } from "../agent/activity.js";
import type { Store } from "../store/db.js";
import { logger } from "../log.js";
import type { AgentManager } from "../agent/manager.js";
-import { promptText, type QuestionItem } from "../agent/approvals.js";
+import { promptButtons, promptText } from "../agent/approvals.js";
import { segmentInput, type ChatPlace } from "../agent/prompts/index.js";
import { clearInflight, markInflight, takeNotice } from "./recovery.js";
import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";
@@ -418,7 +418,9 @@ export class BotRuntime {
return { handled: true, ack: `正在中止上一条消息(已处理 ${fmtSecs(Date.now() - since)})…` };
}
if (!agent) return { handled: false };
- const r = agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`);
+ // 审批、提问的回复;后台任务的只认引用、编号开头,或它是机器人最后一条消息时的选项编号(见 ApprovalCenter.handleReply)
+ const { quote, plain } = quoteOf(ev);
+ const r = agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`, { ...tasks?.replyContext(convId), ...(quote ? { quote, plain } : {}) });
if (r.handled) return r;
// 前一条还在处理:能并入进行中的代理回合时由 handle 并入并回一句;不能时说一声这条排在后面、怎么中止(每个回合只说一次),消息照常入队
const t = agent.turnsInProgress.get(convId);
@@ -464,8 +466,8 @@ export class BotRuntime {
return agent.approvals.decide(row.id, allow, by) ? { toast: allow ? `已批准 ${row.code}(仅本次)` : `已拒绝 ${row.code}`, ok: true } : { toast: "已过期", ok: false };
}
if (value.amb === "question") {
- const r = agent.approvals.handleReply(row.conversationId, String(value.option ?? ""), by);
- return r.handled ? { toast: "已提交", ok: true } : { toast: "提交失败", ok: false };
+ // 回答按钮所在的这一个提问(会话里可能同时有几个)
+ return agent.approvals.answerText(row.id, String(value.option ?? ""), by) ? { toast: "已提交", ok: true } : { toast: "提交失败", ok: false };
}
return { toast: "未知操作", ok: false };
}
@@ -782,36 +784,23 @@ export function firstInput(agent: AgentManager, botId: string, convId: string, t
/** 审批/提问 → 出站交互操作(文本渠道用 prompt;卡片渠道用 buttons)。 */
export function interactiveOp(row: ApprovalRow) {
- if (row.kind === "approval") {
- return {
- type: "interactive" as const,
- kind: "approval" as const,
- prompt: promptText(row),
- requestId: row.id,
- code: row.code,
- buttons: [
- { label: "允许(仅本次)", value: { amb: "approval", id: row.id, decision: "allow" }, style: "primary" as const },
- { label: "拒绝", value: { amb: "approval", id: row.id, decision: "deny" }, style: "danger" as const },
- ],
- };
- }
- let qs: QuestionItem[] = [];
- try {
- qs = JSON.parse(row.payload);
- } catch {
- /* ignore */
- }
- const single = qs.length === 1 ? qs[0] : undefined;
return {
type: "interactive" as const,
- kind: "ask_user" as const,
+ kind: row.kind === "approval" ? ("approval" as const) : ("ask_user" as const),
prompt: promptText(row),
requestId: row.id,
code: row.code,
- buttons: single?.options?.length && !single.multiSelect ? single.options.map((o, i) => ({ label: o.label, value: { amb: "question", id: row.id, option: String(i + 1) }, style: "default" as const })) : undefined,
+ buttons: promptButtons(row),
};
}
+/** 消息里引用的那段(微信的引用)和用户自己写的(去掉引用) */
+export function quoteOf(ev: InboundEvent): { quote: string; plain: string } {
+ const quote = ev.parts.map((p) => (p.type === "quote" ? p.text : "")).filter(Boolean).join("\n");
+ const plain = eventText({ ...ev, parts: ev.parts.filter((p) => p.type !== "quote") });
+ return { quote, plain };
+}
+
const clipLine = (s: string, n = 80) => (s.length > n ? s.slice(0, n - 1) + "…" : s);
/** /status 里"上一条还在处理"那一行:处理了多久、现在在做什么、多久没动了;steer = 新消息会并入这一轮 */
diff --git a/src/store/db.ts b/src/store/db.ts
index 40d7657..e5c3bc6 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -84,8 +84,14 @@ export interface ApprovalRow {
result: string;
decidedBy: string;
createdAt: number;
+ /** 0 = 不过期(后台任务的提问,等多久都行) */
expiresAt: number;
decidedAt: number;
+ /** 后台任务的(任务会话或它的子代理里来的,或任务报的 needs_you 提问);聊天里的是空 */
+ taskId: string;
+ runId: string;
+ /** true:有一次 DSH 调用在等它(审批、聊天里的提问);false:任务的提问,回答作为任务的新输入 */
+ blocking: boolean;
}
/**
@@ -392,6 +398,10 @@ const COLUMNS: Array<[string, string, string]> = [
["conversations", "kind", "TEXT NOT NULL DEFAULT 'dm'"],
// 代理回合的活动记录(JSON 数组,见 agent/activity.ts);只在助手消息上
["messages", "activity", "TEXT NOT NULL DEFAULT ''"],
+ // 后台任务的提问与审批(3b):属于哪个任务、哪个 run;blocking = 有 DSH 调用在等它
+ ["approvals", "task_id", "TEXT NOT NULL DEFAULT ''"],
+ ["approvals", "run_id", "TEXT NOT NULL DEFAULT ''"],
+ ["approvals", "blocking", "INTEGER NOT NULL DEFAULT 1"],
];
export class Store {
@@ -762,15 +772,18 @@ export class Store {
createdAt: Number(r.created_at),
expiresAt: Number(r.expires_at),
decidedAt: Number(r.decided_at),
+ taskId: String(r.task_id ?? ""),
+ runId: String(r.run_id ?? ""),
+ blocking: Number(r.blocking ?? 1) !== 0,
};
}
- insertApproval(a: Omit<ApprovalRow, "status" | "result" | "decidedBy" | "decidedAt">): ApprovalRow {
+ insertApproval(a: Omit<ApprovalRow, "status" | "result" | "decidedBy" | "decidedAt" | "taskId" | "runId" | "blocking"> & Partial<Pick<ApprovalRow, "taskId" | "runId" | "blocking">>): ApprovalRow {
this.db
.prepare(
- `INSERT INTO approvals(id, code, kind, bot_id, conversation_id, session_id, tool, detail, reason, payload, status, created_at, expires_at)
- VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`,
+ `INSERT INTO approvals(id, code, kind, bot_id, conversation_id, session_id, tool, detail, reason, payload, status, created_at, expires_at, task_id, run_id, blocking)
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?)`,
)
- .run(a.id, a.code, a.kind, a.botId, a.conversationId, a.sessionId, a.tool, a.detail, a.reason, a.payload, a.createdAt, a.expiresAt);
+ .run(a.id, a.code, a.kind, a.botId, a.conversationId, a.sessionId, a.tool, a.detail, a.reason, a.payload, a.createdAt, a.expiresAt, a.taskId ?? "", a.runId ?? "", a.blocking === false ? 0 : 1);
return this.getApproval(a.id)!;
}
getApproval(id: string): ApprovalRow | undefined {
@@ -781,12 +794,14 @@ export class Store {
const r = this.db.prepare("SELECT * FROM approvals WHERE code = ? AND status = 'pending' ORDER BY created_at DESC LIMIT 1").get(code) as Row | undefined;
return r ? this.toApproval(r) : undefined;
}
- listApprovals(opts: { status?: ApprovalStatus; botId?: string; conversationId?: string; limit?: number } = {}): ApprovalRow[] {
+ listApprovals(opts: { status?: ApprovalStatus; botId?: string; conversationId?: string; taskId?: string; runId?: string; limit?: number } = {}): ApprovalRow[] {
const where: string[] = [];
const args: Array<string | number> = [];
if (opts.status) (where.push("status = ?"), args.push(opts.status));
if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));
if (opts.conversationId) (where.push("conversation_id = ?"), args.push(opts.conversationId));
+ if (opts.taskId) (where.push("task_id = ?"), args.push(opts.taskId));
+ if (opts.runId) (where.push("run_id = ?"), args.push(opts.runId));
const sql = `SELECT * FROM approvals ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY created_at DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;
return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toApproval(r));
}
@@ -935,6 +950,11 @@ export class Store {
const sql = `SELECT * FROM outbox ${where.length ? "WHERE " + where.join(" AND ") : ""} ORDER BY seq DESC LIMIT ${Math.max(1, Math.min(500, opts.limit ?? 100))}`;
return (this.db.prepare(sql).all(...args) as Row[]).map((r) => this.toOutbox(r));
}
+ /** 机器人在这个会话里最近发(或要发)的一条消息(合并掉的、放弃了的不算):微信里光回编号算不算回答提问,看它 */
+ lastOutbox(conversationId: string): OutboxRow | undefined {
+ const r = this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status IN ('pending', 'held', 'sent') ORDER BY seq DESC LIMIT 1").get(conversationId) as Row | undefined;
+ return r ? this.toOutbox(r) : undefined;
+ }
/** 留着等这个会话的对方发消息的,按写入顺序 */
heldOutbox(conversationId: string): OutboxRow[] {
return (this.db.prepare("SELECT * FROM outbox WHERE conversation_id = ? AND status = 'held' ORDER BY seq").all(conversationId) as Row[]).map((r) => this.toOutbox(r));
diff --git a/src/tasks/attention.ts b/src/tasks/attention.ts
new file mode 100644
index 0000000..a6e6ad8
--- /dev/null
+++ b/src/tasks/attention.ts
@@ -0,0 +1,218 @@
+/**
+ * "需要你"(设计第 1、6 节的 Attention):所有机器人里在等人的事。有的存着(提问、审批:approvals 表),
+ * 有的从状态推出来(失败的任务、没送到的结果、过期的微信登录)。原因没了它自己就消失。
+ *
+ * - 来源可以登记(addSource):审批中心、任务服务、渠道各给一份;3c 的"留着没发出去的消息"也从这里接进来。
+ * - 有变化(kick,或每 10 秒看一眼)时通知订阅者:侧栏的数字、托盘角标、系统通知。
+ * - 系统通知每一项最多一次(takeNew:记在 KV 里,重启也算)。
+ * 健康时什么都没有:没有行、没有角标、没有通知。
+ */
+import type { ApprovalRow, Store } from "../store/db.js";
+import { questionsOf, type QuestionItem } from "../agent/approvals.js";
+import { logger } from "../log.js";
+
+const log = logger("attention");
+
+/** question / approval:在等你回答、批准;failed:任务失败了;delivery:结果没送到;login:渠道登录过期了 */
+export type AttentionKind = "question" | "approval" | "failed" | "delivery" | "login";
+/** answer、approve、deny、retry、stop、seen(知道了)、relogin(去重新扫码)、open(打开对话) */
+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "seen" | "relogin" | "open";
+
+export interface AttentionItem {
+ /** 稳定 id:approval:<id>、task:<id>、login:<bot>:<渠道> */
+ id: string;
+ kind: AttentionKind;
+ botId: string;
+ botName: string;
+ /** 说的是什么:任务名、渠道名("微信"),或一句话("微信登录已过期") */
+ subject: string;
+ /** 状态:等你回答 / 等你批准 / 失败 / 未送达;没有就不显示 */
+ status: string;
+ /** 第二行:问题、命令、失败原因、没送到的那句话 */
+ line: string;
+ since: number;
+ severity: "warn" | "err";
+ actions: AttentionAction[];
+ conversationId?: string;
+ channel?: string;
+ taskId?: string;
+ approvalId?: string;
+ code?: string;
+ questions?: QuestionItem[];
+}
+
+export type AttentionSource = () => AttentionItem[];
+
+/** 排序:提问和审批在前(等着的事),再是失败、没送到,最后是系统的(登录);同一类旧的在前 */
+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, delivery: 2, login: 3 };
+
+const NOTIFIED = "attention:notified";
+
+export class Attention {
+ private sources = new Set<AttentionSource>();
+ private listeners = new Set<(items: AttentionItem[]) => void>();
+ private sig = "";
+ private scheduled: NodeJS.Timeout | undefined;
+ private timer: NodeJS.Timeout | undefined;
+
+ constructor(private o: { store: Store; intervalMs?: number; debounceMs?: number }) {}
+
+ /** 登记一个来源,返回注销函数 */
+ addSource(fn: AttentionSource): () => void {
+ this.sources.add(fn);
+ this.kick();
+ return () => {
+ this.sources.delete(fn);
+ this.kick();
+ };
+ }
+
+ list(): AttentionItem[] {
+ const out: AttentionItem[] = [];
+ const seen = new Set<string>();
+ for (const fn of this.sources) {
+ let items: AttentionItem[] = [];
+ try {
+ items = fn();
+ } catch (e) {
+ log.warn("attention source failed", { message: (e as Error).message.slice(0, 200) });
+ }
+ for (const it of items) if (!seen.has(it.id)) (seen.add(it.id), out.push(it));
+ }
+ return out.sort((a, b) => ORDER[a.kind] - ORDER[b.kind] || a.since - b.since);
+ }
+
+ count(): number {
+ return this.list().length;
+ }
+
+ /** 每个机器人几件、最早那件是什么(侧栏机器人行的"GPU 价格调研等你回答") */
+ byBot(items = this.list()): Record<string, { n: number; line: string }> {
+ const out: Record<string, { n: number; line: string }> = {};
+ for (const it of items) {
+ const cur = out[it.botId];
+ if (cur) cur.n++;
+ else out[it.botId] = { n: 1, line: botLine(it) };
+ }
+ return out;
+ }
+
+ /** 订阅变化(立即收到当前的一份);返回取消函数。有订阅者时每 intervalMs 看一眼(推出来的状态没有事件) */
+ onChange(fn: (items: AttentionItem[]) => void): () => void {
+ this.listeners.add(fn);
+ const items = this.list();
+ this.sig = signature(items);
+ fn(items);
+ if (!this.timer) {
+ this.timer = setInterval(() => this.check(), this.o.intervalMs ?? 10_000);
+ this.timer.unref?.();
+ }
+ return () => {
+ this.listeners.delete(fn);
+ if (!this.listeners.size && this.timer) {
+ clearInterval(this.timer);
+ this.timer = undefined;
+ }
+ };
+ }
+
+ /** 有东西变了(审批、任务、渠道):稍等一下再看(同一时刻的几次变化合成一次) */
+ kick(): void {
+ if (!this.listeners.size || this.scheduled) return;
+ this.scheduled = setTimeout(() => {
+ this.scheduled = undefined;
+ this.check();
+ }, this.o.debounceMs ?? 200);
+ this.scheduled.unref?.();
+ }
+
+ stop(): void {
+ clearTimeout(this.scheduled);
+ clearInterval(this.timer);
+ this.scheduled = this.timer = undefined;
+ this.listeners.clear();
+ }
+
+ private check(): void {
+ const items = this.list();
+ const sig = signature(items);
+ if (sig === this.sig) return;
+ this.sig = sig;
+ for (const fn of this.listeners) {
+ try {
+ fn(items);
+ } catch (e) {
+ log.warn("attention listener failed", { message: (e as Error).message });
+ }
+ }
+ }
+
+ /** 还没发过系统通知的项(记下来,之后不再给;重启后也一样)。已经不在列表里的记录随之清掉 */
+ takeNew(items = this.list()): AttentionItem[] {
+ let done: string[] = [];
+ try {
+ done = JSON.parse(this.o.store.getKV(NOTIFIED) || "[]");
+ } catch {
+ done = [];
+ }
+ const had = new Set(done);
+ const fresh = items.filter((it) => !had.has(it.id));
+ const keep = items.map((it) => it.id);
+ if (fresh.length || keep.length !== done.length) this.o.store.setKV(NOTIFIED, JSON.stringify(keep.slice(-500)));
+ return fresh;
+ }
+}
+
+const CHANNEL: Record<string, string> = { weixin: "微信", feishu: "飞书", web: "对话" };
+
+/**
+ * 审批中心那一份:还在等的提问和审批(聊天回合里的、后台任务的)。任务的以任务名为题,聊天里的以渠道为题:
+ * 「小蓝 · GPU 价格调研 · 等你回答」「小蓝 · 微信 · 等你批准」。
+ */
+export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[] {
+ return rows.map((r) => {
+ const task = r.taskId ? store.getTask(r.taskId) : undefined;
+ const channel = store.getConversation(r.conversationId)?.channel ?? r.conversationId.split(":")[1] ?? "";
+ const qs = questionsOf(r);
+ const line = r.kind === "approval" ? r.detail || r.reason || r.tool : qs.map((q) => q.question).join(" / ") || r.detail;
+ return {
+ id: `approval:${r.id}`,
+ kind: r.kind,
+ botId: r.botId,
+ botName: store.getBot(r.botId)?.name ?? r.botId,
+ subject: task?.title ?? CHANNEL[channel] ?? "对话",
+ status: r.kind === "approval" ? "等你批准" : "等你回答",
+ line: line.length > 300 ? line.slice(0, 299) + "…" : line,
+ since: r.createdAt,
+ severity: "warn",
+ actions: r.kind === "approval" ? ["approve", "deny"] : ["answer"],
+ conversationId: r.conversationId,
+ channel,
+ ...(r.taskId ? { taskId: r.taskId } : {}),
+ approvalId: r.id,
+ code: r.code,
+ ...(r.kind === "question" ? { questions: qs } : {}),
+ };
+ });
+}
+
+/** 列表变没变:id + 状态 + 第二行 */
+function signature(items: AttentionItem[]): string {
+ return items.map((it) => `${it.id}|${it.status}|${it.line}`).join("\n");
+}
+
+/** 侧栏机器人行的第二行:"GPU 价格调研等你回答"、"微信登录已过期" */
+export function botLine(it: AttentionItem): string {
+ return it.status ? `${it.subject}${it.status}` : it.subject;
+}
+
+/** 系统通知:标题「小蓝 需要你」,正文「GPU 价格调研:报告用中文还是英文?」(设计第 6 节) */
+export function notificationOf(it: AttentionItem): { title: string; body: string } {
+ const body = it.line ? `${it.subject}:${it.line}` : botLine(it);
+ return { title: `${it.botName} 需要你`, body: body.length > 120 ? body.slice(0, 119) + "…" : body };
+}
+
+/** 托盘:有事时提示文字带上件数,没事时只有应用名(健康时什么都不加) */
+export function trayTitle(product: string, n: number): string {
+ return n > 0 ? `${product} · ${n} 件事需要你` : product;
+}
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index 67149e6..42aef15 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -11,7 +11,10 @@
* 跑着的 run 记为 interrupted,给任务排一个恢复 run:先交一条恢复说明,没被会话收下的输入再交一次,收下过的不再交。
* - 停止只停这个任务(指令通道:取消这一轮、停它的后台命令、之后的工具调用一律拒绝),聊天和别的任务照常。
*
- * 3b–3f 的缝:Report 的 needs_you / question、阶段表的"等你"几行、规则(rule_id)、花费(cost_usd、budget)。
+ * - 提问(3b):代理报 needs_you 带一个问题,这一轮结束时变成审批中心里一条不阻塞、不过期的提问,推给请求它的会话
+ * (一个会话同时只推一个);回答成为任务的新输入,任务在人的名额里接着做。任务会话里的审批也推过去(阻塞、12 小时)。
+ *
+ * 3c–3f 的缝:规则(rule_id)、花费(cost_usd、budget)。
*/
import crypto from "node:crypto";
import fs from "node:fs";
@@ -19,9 +22,12 @@ import path from "node:path";
import type { Outbox } from "../core/outbox.js";
import { ActivityLog, type ActivityStep } from "../agent/activity.js";
import { ResumeFailed, deliverables } from "../agent/host.js";
+import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";
+import { actionCardSpec } from "../channels/feishu/transport.js";
import { NUDGE, attachmentsOf, rebrief, recoveryNote, retryNote, taskBrief } from "../agent/prompts/index.js";
import type { BotSettings } from "../agent/settings.js";
-import type { Conversation, InputKind, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";
+import type { ApprovalRow, Conversation, InputKind, RunCause, RunInputRow, RunOutcome, RunRow, Store, TaskReport, TaskRow } from "../store/db.js";
+import type { AttentionItem } from "./attention.js";
import { logger } from "../log.js";
import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";
import { taskStage, type Stage } from "./stage.js";
@@ -35,6 +41,16 @@ export const MESSAGE_MAX = 300;
/** 一轮出错后重试前等多久(设计:15、30、60 秒) */
export const RETRY_DELAYS_MS = [15_000, 30_000, 60_000];
+/** 提问的问题、选项的上限 */
+export const QUESTION_MAX = 300;
+export const OPTIONS_MAX = 6;
+
+/** 审批中心里任务要用的这几样(审批中心是提问和审批的唯一写入者) */
+export type TaskApprovals = Pick<ApprovalCenter, "create" | "cancel" | "answerText" | "pending" | "pendingForTask" | "pendingAll" | "listen">;
+
+/** 推给用户的提问 / 审批在出站队列里的 id(同一条只推一次;引用、"最后一条消息"按它认) */
+export const askId = (row: Pick<ApprovalRow, "taskId" | "id">) => `task:${row.taskId}:ask:${row.id}`;
+
/** 宿主这边能为任务做的事(AgentManager 实现;单元测试换成假的) */
export interface TaskHost {
/** 代理模式可用 */
@@ -66,6 +82,8 @@ export interface TaskServiceOptions {
host: TaskHost;
/** 微信、飞书的结果经出站队列发(没有就只写进会话历史) */
outbox?: Outbox;
+ /** 任务的提问、任务会话里的审批(没有就不能问用户) */
+ approvals?: TaskApprovals;
/** 机器人没设模型时用的默认模型 */
defaultModel?: () => string;
/** 发给网关前限定到机器人用的 Key(同聊天) */
@@ -167,6 +185,7 @@ export class TaskService {
private closing = false;
/** 正在删除的机器人 */
private dropped = new Set<string>();
+ private unlisten: (() => void) | undefined;
constructor(private o: TaskServiceOptions) {}
@@ -179,23 +198,34 @@ export class TaskService {
// ---------- 生命周期 ----------
- /** 启动:上次没跑完的 run 记为 interrupted 并排恢复;结束了却没送出的结果补送;开始排队的 run */
+ /**
+ * 启动:上次没跑完的 run 记为 interrupted 并排恢复;结束了却没送出的结果补送、没问出去的问题补问;
+ * 每个会话把该推的提问推出去;开始排队的 run
+ */
start(): void {
this.started = true;
this.closing = false;
+ this.unlisten ??= this.o.approvals?.listen((e) => this.onApproval(e));
this.recover(undefined, "应用重启");
for (const r of this.store.listRuns({ states: ["ended"] })) {
- if (!r.delivery && (r.outcome === "done" || r.outcome === "failed") && r.taskId) {
+ if (!r.taskId) continue;
+ if (!r.delivery && (r.outcome === "done" || r.outcome === "failed")) {
const task = this.store.getTask(r.taskId);
if (task) this.deliver(task, r.id, r.outcome, r.report, r.error);
+ } else if (r.outcome === "needs_you" && r.report?.question) {
+ const task = this.store.getTask(r.taskId);
+ if (task && task.endReason !== "stopped" && this.store.latestRun(task.id)?.id === r.id) this.ask(task, r.id, r.report.question);
}
}
+ for (const conv of new Set((this.o.approvals?.pendingAll() ?? []).filter((r) => r.taskId).map((r) => r.conversationId))) this.pushNext(conv);
this.pump();
}
/** 应用退出:不再开始新的 run;跑着的留在库里(下次启动时恢复),步骤先存下 */
stop(): void {
this.closing = true;
+ this.unlisten?.();
+ this.unlisten = undefined;
for (const l of this.live.values()) {
clearTimeout(l.timer);
try {
@@ -232,6 +262,8 @@ export class TaskService {
if (l) this.forget(l);
this.store.updateRun(run.id, { state: "ended", outcome: "interrupted", endedAt: this.now(), error: why, ...(l ? { activity: JSON.stringify(steps), tokensIn: l.tokensIn, tokensOut: l.tokensOut } : {}) });
const task = run.taskId ? this.store.getTask(run.taskId) : undefined;
+ // 这一轮在等的批准随它没了(DSH 那次调用不在了):恢复后代理需要的话再问
+ for (const a of run.taskId ? (this.o.approvals?.pendingForTask(run.taskId) ?? []) : []) if (a.blocking) this.o.approvals!.cancel(a.id, "interrupted");
if (!task || task.endedAt) continue;
const jobs = steps.filter((s) => s.kind === "job" && s.status === "running").map((s) => clip(oneLine(s.summary || s.title), 120));
this.addInput(task.id, "recovery", recoveryNote(jobs), false);
@@ -300,33 +332,55 @@ export class TaskService {
* 人的追加(task_message):任务在跑一轮就并进去(下一步看到);空着(收尾、等重试)就马上交给会话;
* 在排队就跟着这个 run 一起交;已完成或失败了就在同一个任务里开一个新 run(人的唤醒,排在前面)。停了的不接。
*/
- async message(taskId: string, text: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed"; error?: string }> {
+ async message(taskId: string, text: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed" | "answered"; error?: string }> {
const task = this.store.getTask(taskId);
if (!task) return { error: "task not found" };
if (task.endReason === "stopped") return { error: `「${task.title}」已停止,不能再追加;需要的话开个新任务。` };
+ // 任务在等用户回答:这句话就是回答(回答成为它的新输入,见 onApproval)
+ const open = this.o.approvals?.pendingForTask(task.id).find((r) => r.kind === "question" && !r.blocking);
+ if (open && this.o.approvals!.answerText(open.id, text.trim(), "followup")) return { how: "answered" };
const input = this.addInput(task.id, "followup", `[用户追加]\n${text.trim()}`, true);
+ return { how: await this.wake(task, input, "followup") };
+ }
+
+ /** 失败的任务再试一次("需要你"里的重试):人的输入,开一个 retry run */
+ async retry(taskId: string): Promise<{ how?: "steered" | "sent" | "queued" | "resumed"; error?: string }> {
+ const task = this.store.getTask(taskId);
+ if (!task) return { error: "task not found" };
+ if (task.endReason === "stopped") return { error: `「${task.title}」已停止` };
+ const last = this.store.latestRun(task.id);
+ const why = last?.report?.message || last?.error || "";
+ const input = this.addInput(task.id, "followup", `[用户让你再试一次]${why ? `\n上次没做完:${clip(oneLine(why), 300)}` : ""}`, true);
+ return { how: await this.wake(task, input, "retry") };
+ }
+
+ /**
+ * 把人的输入交给任务:在跑一轮就并进去(下一步看到);空着(收尾、等重试)就马上交给会话;在排队就跟着这个 run 一起交;
+ * 已完成、失败了或在等回答,就在同一个任务里开一个新 run(人的唤醒,排在前面)。
+ */
+ private async wake(task: TaskRow, input: RunInputRow, cause: RunCause): Promise<"steered" | "sent" | "queued" | "resumed"> {
const l = this.liveOf(task.id);
if (l) {
if (l.busy && !l.starting && (await this.o.host.steer(l.botId, l.sessionId, input.id, input.text).catch(() => false))) {
this.store.updateInput(input.id, { runId: l.runId, messageId: input.id, deliveredAt: this.now(), ...(l.seen.has(input.id) ? { takenAt: this.now() } : {}) });
this.reopen(l);
- return { how: "steered" };
+ return "steered";
}
if (!l.busy && !l.starting && !l.checking) {
clearTimeout(l.timer);
l.timer = undefined;
void this.deliver_(l, [input]);
- return { how: "sent" };
+ return "sent";
}
// 正在交上一条:这一轮空下来时交(checkSettle 先交没交出去的输入)
- return { how: "queued" };
+ return "queued";
}
- if (this.queuedRun(task.id)) return { how: "queued" };
+ if (this.queuedRun(task.id)) return "queued";
if (task.endedAt) this.store.updateTask(task.id, { endedAt: 0, endReason: "", updatedAt: this.now() });
- this.enqueue(task, "followup");
+ this.enqueue(task, cause);
this.changed(task.id);
this.pump();
- return { how: "resumed" };
+ return "resumed";
}
/** 停止(/stop 编号、界面、聊天代理):只停这个任务,聊天和别的任务照常 */
@@ -336,6 +390,8 @@ export class TaskService {
const now = this.now();
this.store.updateTask(taskId, { endedAt: now, endReason: "stopped", stoppedBy: by, updatedAt: now });
for (const r of this.store.listRuns({ taskId, states: ["queued"] })) this.store.updateRun(r.id, { state: "ended", outcome: "stopped", endedAt: now });
+ // 它在等的提问、审批作废("需要你"里随之消失,同一会话的下一个提问可以推了)
+ for (const a of this.o.approvals?.pendingForTask(taskId) ?? []) this.o.approvals!.cancel(a.id, "stopped");
const l = this.liveOf(taskId);
if (l) {
l.activity.end("已停止");
@@ -372,7 +428,9 @@ export class TaskService {
if (!this.started || this.closing) return;
const queued = this.store.listRuns({ states: ["queued"] }).filter((r) => r.taskId && !this.dropped.has(r.botId));
if (!queued.length) return;
- const running = this.store.listRuns({ states: ["running", "settling"] });
+ // 等批准的 run 让出名额(DSH 那次调用照样等着,批了就接着做)
+ const blocked = new Set((this.o.approvals?.pendingAll() ?? []).filter((a) => a.taskId && a.blocking && a.kind === "approval").map((a) => a.taskId));
+ const running = this.store.listRuns({ states: ["running", "settling"] }).filter((r) => !blocked.has(r.taskId));
const picks = pickRuns(
queued.map((r) => ({ id: r.id, botId: r.botId, priority: priorityOf(r.cause), queuedAt: r.queuedAt })),
running,
@@ -590,7 +648,7 @@ export class TaskService {
*/
private finish(l: Live): void {
if (this.live.get(l.runId) !== l) return;
- if (l.final) return this.end(l, l.final.state === "done" ? "done" : "failed", l.final);
+ if (l.final) return this.end(l, l.final.state === "done" ? "done" : l.final.state === "needs_you" ? "needs_you" : "failed", l.final);
if (l.turnError && l.retries < this.delays.length) {
const error = l.turnError;
l.turnError = undefined;
@@ -622,6 +680,7 @@ export class TaskService {
if (task && outcome === "done") this.store.updateTask(task.id, { endedAt: now, endReason: "done", updatedAt: now });
else if (task) this.store.updateTask(task.id, { updatedAt: now });
if (task && (outcome === "done" || outcome === "failed")) this.deliver(task, l.runId, outcome, report, error);
+ if (task && outcome === "needs_you" && report?.question) this.ask(task, l.runId, report.question);
log.info("background task run ended", { task: l.taskId, run: l.runId, outcome, ...(error ? { error } : {}) });
this.changed(l.taskId);
this.pump();
@@ -697,19 +756,22 @@ export class TaskService {
// ---------- 插件经 bridge 来的 ----------
- /** task_report:记下 Report;done / failed 在这一轮结束、会话安静后发给用户 */
+ /** task_report:记下 Report;done / failed 在这一轮结束、会话安静后发给用户,needs_you 的问题那时问用户 */
report(b: any): { text?: string; error?: string } {
const l = this.bySession.get(String(b?.sessionId ?? ""));
if (!l) return { error: "This background task is not running any more (it was stopped or has ended). Stop working on it." };
const state = String(b?.state ?? "");
- if (state === "needs_you") return { error: "You cannot ask the user from a background task. Decide yourself and say so in the result, or report failed with what you need from the user." };
- if (state !== "progress" && state !== "done" && state !== "failed") return { error: "state must be progress, done or failed" };
+ if (state !== "progress" && state !== "done" && state !== "failed" && state !== "needs_you") return { error: "state must be progress, needs_you, done or failed" };
+ const question = state === "needs_you" ? questionOf(b) : undefined;
+ if (state === "needs_you" && !question) return { error: "needs_you needs a question: one question for the user, with options when there are clear choices." };
+ if (state === "needs_you" && !this.o.approvals) return { error: "The app cannot ask the user right now. Decide yourself and say so in the result." };
const message = typeof b?.message === "string" ? oneLine(b.message) : "";
const report: TaskReport = {
state,
summary: clip(String(b?.summary ?? "").trim(), 2000),
...(message ? { message: clip(message, MESSAGE_MAX) } : {}),
...(Array.isArray(b?.files) && b.files.length ? { files: b.files.map(String).slice(0, 8) } : {}),
+ ...(question ? { question } : {}),
at: this.now(),
};
this.store.updateRun(l.runId, { report });
@@ -717,6 +779,7 @@ export class TaskService {
if (state !== "progress") l.final = report;
this.changed(l.taskId);
if (state === "progress") return { text: "Progress recorded (it is not sent to the user). Continue the task." };
+ if (state === "needs_you") return { text: "Recorded. End your turn now: the app asks the user, and their answer arrives as your next message." };
return { text: `Recorded. End your turn now: the app sends your message to the user${state === "done" && !message ? " (you gave no message, so the user only hears that the task is done)" : ""}.` };
}
@@ -740,7 +803,7 @@ export class TaskService {
if (!task) return { error: `No background task matches "${String(a.task ?? "")}". Call task_list to see them.` };
const r = await this.message(task.id, String(a.text ?? ""));
if (r.error) return { error: r.error };
- const how = { steered: "It reaches the task at its next step.", sent: "The task picks it up now.", queued: "The task gets it when it starts.", resumed: "The finished task resumes with it." }[r.how!];
+ const how = { steered: "It reaches the task at its next step.", sent: "The task picks it up now.", queued: "The task gets it when it starts.", resumed: "The finished task resumes with it.", answered: "It answers the task's open question; the task continues." }[r.how!];
return { text: `Passed to 「${task.title}」. ${how} Tell the user in one short sentence.` };
}
case "list": {
@@ -763,15 +826,146 @@ export class TaskService {
/** 任务会话所在的聊天(任务会话里的审批落到请求它的会话) */
conversationOf(sessionId: string): string | undefined {
- return this.bySession.get(sessionId) ? this.store.getTask(this.bySession.get(sessionId)!.taskId)?.conversationId : this.store.taskBySession(sessionId)?.conversationId;
+ return this.taskOfSession(sessionId)?.conversationId;
+ }
+
+ /** 任务会话(或它的子代理:root 是所在的任务会话)属于哪个任务、哪个 run、哪个会话 */
+ taskOfSession(sessionId: string, root?: string): { taskId: string; runId: string; conversationId: string } | undefined {
+ const l = this.bySession.get(sessionId) ?? (root ? this.bySession.get(root) : undefined);
+ const task = l ? this.store.getTask(l.taskId) : (this.store.taskBySession(sessionId) ?? (root ? this.store.taskBySession(root) : undefined));
+ if (!task) return undefined;
+ return { taskId: task.id, runId: l?.runId ?? this.store.latestRun(task.id)?.id ?? "", conversationId: task.conversationId };
+ }
+
+ // ---------- 提问与审批(3b) ----------
+
+ /** 代理报了 needs_you、这一轮结束了:问题记成一条不阻塞、不过期的提问(每个 run 只问一次),给聊天代理留张便条 */
+ private ask(task: TaskRow, runId: string, q: NonNullable<TaskReport["question"]>): void {
+ const a = this.o.approvals;
+ if (!a || this.store.listApprovals({ runId, limit: 5 }).some((r) => r.kind === "question" && r.taskId === task.id)) return;
+ const item: QuestionItem = { id: "answer", question: q.question, ...(q.options?.length ? { options: q.options.map((label) => ({ label })) } : {}), ...(q.multiSelect ? { multiSelect: true } : {}) };
+ a.create({ kind: "question", botId: task.botId, conversationId: task.conversationId, sessionId: task.sessionId, tool: "task_report", detail: q.question, reason: "", payload: JSON.stringify([item]), taskId: task.id, runId, blocking: false, ttlMs: 0 });
+ log.info("background task asks the user", { task: task.id, run: runId });
+ this.note(task.conversationId, `[后台任务「${task.title}」在等用户回答:${q.question}${q.options?.length ? `(${q.options.join(" / ")})` : ""}。用户在聊天里回答它时,用 task_message 转给这个任务]`);
+ }
+
+ /** 审批中心有新的、或有了决定:任务的提问有了回答就交给任务;更新阶段;同一会话的下一个提问可以推了 */
+ private onApproval(e: ApprovalEvent): void {
+ const row = e.row;
+ if (!row.taskId) return;
+ const task = this.store.getTask(row.taskId);
+ if (!task) return;
+ if (e.type === "decided" && row.kind === "question" && !row.blocking && row.status === "answered" && task.endReason !== "stopped") this.answered(task, row);
+ this.changed(task.id);
+ // 等批准时让出的名额:有了决定,排队的可能要等它了
+ if (e.type === "decided" && row.blocking) this.pump();
+ this.pushNext(row.conversationId);
+ }
+
+ /** 用户回答了任务的提问:回答成为任务的新输入(人的唤醒:预留名额、排在前面) */
+ private answered(task: TaskRow, row: ApprovalRow): void {
+ const q = questionsOf(row)[0]?.question ?? row.detail;
+ const input = this.addInput(task.id, "answer", `[用户回答了你的问题]\n问题:${q}\n回答:${answerLine(row) || "(没有写)"}`, true);
+ log.info("the user answered a background task's question", { task: task.id, by: row.decidedBy });
+ void this.wake(task, input, "answer");
+ }
+
+ /**
+ * 推给请求它的会话(微信、飞书;网页的提问卡片就在对话里):一个会话同时只推一个,前一个没回答,后面的只在"需要你"里等,
+ * 微信里光回编号才不会认错。出站 id 固定(askId),同一条只推一次;发不出去(微信窗口关了)由出站队列留着。
+ */
+ private pushNext(conversationId: string): void {
+ const a = this.o.approvals;
+ const outbox = this.o.outbox;
+ if (!a || !outbox || !this.started) return;
+ const conv = this.store.getConversation(conversationId);
+ if (!conv || (conv.channel !== "weixin" && conv.channel !== "feishu")) return;
+ const rows = a.pending(conversationId).filter((r) => r.taskId).sort((x, y) => x.createdAt - y.createdAt);
+ const pushed = (r: ApprovalRow) => this.store.getOutbox(askId(r));
+ if (rows.some((r) => (pushed(r)?.status ?? "gone") !== "gone")) return;
+ const row = rows.find((r) => !pushed(r));
+ const task = row ? this.store.getTask(row.taskId) : undefined;
+ if (!row || !task || task.endReason === "stopped") return;
+ const text = taskPromptText(row, task.title);
+ const base = { id: askId(row), botId: task.botId, channel: conv.channel as "weixin" | "feishu", peerId: conv.peerId };
+ if (conv.channel === "weixin") void outbox.send({ ...base, kind: "text", body: { text, raw: true } });
+ else {
+ const replyTo = task.originRef || replyHandle(this.store, conv.id).messageId || "";
+ const buttons = promptButtons(row);
+ const title = row.kind === "approval" ? `需批准(任务「${task.title}」)` : `「${task.title}」想问你`;
+ const body = row.kind === "approval" ? (row.detail ? "`" + row.detail.slice(0, 300) + "`" : row.tool) : (questionsOf(row)[0]?.question ?? row.detail);
+ if (replyTo && buttons) void outbox.send({ ...base, kind: "card", replyTo, body: { text, card: actionCardSpec(title, body, buttons) } });
+ else void outbox.send({ ...base, kind: replyTo ? "text" : "notice", replyTo, body: { text } });
+ }
+ if (row.kind === "question") this.store.addMessage(conv.id, "assistant", text);
+ log.info("pushed a background task's prompt", { task: task.id, kind: row.kind, channel: conv.channel });
+ }
+
+ /**
+ * 渠道里的回复怎么认任务的提问(ApprovalCenter.handleReply 用):推给用户的那条是不是机器人最后一条消息(出站队列里这个会话最新的一条)、
+ * 引用的是不是那一条(按推出去的原文比,引用可能被截短、前面带名字)、回答之后回一句"收到"。
+ */
+ replyContext(conversationId: string): ReplyContext {
+ return {
+ latest: (row) => !!row.taskId && this.store.lastOutbox(conversationId)?.id === askId(row),
+ quotes: (row, quote) => !!row.taskId && quotes(this.store.getOutbox(askId(row))?.body.text ?? "", quote, questionsOf(row)[0]?.question ?? row.detail),
+ answered: (row) => {
+ const t = this.store.getTask(row.taskId);
+ return t ? `收到,「${t.title}」继续。` : undefined;
+ },
+ };
+ }
+
+ /** 没送到的结果:用户在"需要你"里看过了(知道了),不再算需要他 */
+ seenDelivery(taskId: string): boolean {
+ const run = this.store.latestRun(taskId);
+ if (!run?.delivery || /:(dropped|seen)$/.test(run.delivery)) return false;
+ this.store.updateRun(run.id, { delivery: `${run.delivery}:seen` });
+ this.changed(taskId);
+ return true;
+ }
+
+ /** "需要你"里任务那一份:失败、没送到、预算用完(提问和审批由审批中心那一份给) */
+ attention(): AttentionItem[] {
+ const out: AttentionItem[] = [];
+ const since = this.now() - 7 * 86400_000;
+ const tasks = [...this.store.listTasks({ open: true, limit: 200 }), ...this.store.listTasks({ open: false, since, limit: 100 })];
+ for (const t of tasks) {
+ const run = this.store.latestRun(t.id);
+ const st = this.stage(t, run);
+ if (st.key !== "failed" && st.key !== "needs-you/delivery" && st.key !== "needs-you/budget") continue;
+ const bot = this.store.getBot(t.botId);
+ const conv = this.store.getConversation(t.conversationId);
+ const r = run?.report ?? t.report;
+ const line = st.key === "failed" ? r?.message || run?.error || "没有给出结果" : r?.message || r?.summary.split("\n")[0] || "";
+ out.push({
+ id: `task:${t.id}`,
+ kind: st.key === "needs-you/delivery" ? "delivery" : "failed",
+ botId: t.botId,
+ botName: bot?.name ?? t.botId,
+ subject: t.title,
+ status: st.label,
+ line: clip(oneLine(line), 200),
+ since: run?.endedAt || t.updatedAt,
+ severity: st.key === "failed" ? "err" : "warn",
+ actions: st.key === "needs-you/delivery" ? ["seen"] : ["retry", "stop"],
+ conversationId: t.conversationId,
+ channel: conv?.channel ?? "",
+ taskId: t.id,
+ });
+ }
+ return out;
}
// ---------- 查看 ----------
private stage(task: TaskRow, run = this.store.latestRun(task.id)): Stage {
- const delivery = run?.delivery && !run.delivery.endsWith(":dropped") ? this.o.store.getOutbox(run.delivery) : undefined;
- const approval = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 100 }).some((a) => a.sessionId === task.sessionId && a.kind === "approval");
- return taskStage({ stopped: task.endReason === "stopped", undelivered: delivery?.status === "gone", waiting: approval ? "approval" : undefined, run });
+ const delivery = run?.delivery && !/:(dropped|seen)$/.test(run.delivery) ? this.o.store.getOutbox(run.delivery) : undefined;
+ // 它在等的:任务会话(或子代理)里的审批、它报的提问
+ const now = this.now();
+ const rows = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 200 }).filter((a) => (a.taskId === task.id || a.sessionId === task.sessionId) && (a.expiresAt === 0 || a.expiresAt > now));
+ const waiting = rows.some((a) => a.kind === "approval") ? "approval" : rows.length ? "answer" : undefined;
+ return taskStage({ stopped: task.endReason === "stopped", undelivered: delivery?.status === "gone", waiting, run });
}
view(task: TaskRow): TaskView {
@@ -860,6 +1054,31 @@ export class TaskService {
}
}
+/** task_report 的 question:一句问题(字符串或 {question, options, multiSelect}),选项最多 6 个 */
+function questionOf(b: any): TaskReport["question"] | undefined {
+ const raw = b?.question;
+ const obj = typeof raw === "object" && raw ? raw : undefined;
+ const text = oneLine(String(obj ? (obj.question ?? "") : (raw ?? "")));
+ if (!text) return undefined;
+ const list = (Array.isArray(obj?.options) ? obj.options : Array.isArray(b?.options) ? b.options : []) as unknown[];
+ const label = (o: unknown) => clip(oneLine(String(typeof o === "object" && o ? ((o as { label?: unknown }).label ?? "") : (o ?? ""))), 60);
+ const options = [...new Set(list.map(label).filter(Boolean))].slice(0, OPTIONS_MAX);
+ const multi = obj?.multiSelect === true || b?.multi_select === true;
+ return { question: clip(text, QUESTION_MAX), ...(options.length ? { options } : {}), ...(multi && options.length > 1 ? { multiSelect: true } : {}) };
+}
+
+/** 引用的是不是推出去的那一条:去掉空白和记号再比;引用可能被截短(末尾省略号)、前面带名字 */
+export function quotes(sent: string, quote: string, question: string): boolean {
+ const norm = (s: string) => s.replace(/\s+/g, "").replace(/[❓⚠\uFE0F]/g, "").replace(/(…|\.\.\.)+$/, "");
+ const q = norm(quote);
+ if (!q) return false;
+ const s = norm(sent);
+ const ask = norm(question);
+ // 前面可能带着发送者的名字("小蓝:")
+ const bare = q.replace(/^[^::「]{1,24}[::]/, "");
+ return (!!s && (s === q || [q, bare].some((x) => x.length >= 6 && s.includes(x)))) || (ask.length >= 2 && q.includes(ask));
+}
+
function parseSteps(json: string | undefined): ActivityStep[] {
if (!json) return [];
try {
diff --git a/src/web/server.ts b/src/web/server.ts
index 616080c..44c5d59 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -16,7 +16,7 @@ import { normalizeLine } from "../modelflare.js";
import { SseReply } from "./sse-reply.js";
import { LiveTurns, type LiveTurn } from "./live.js";
import { connectionFromPids } from "../agent/peer-guard.js";
-import type { ApprovalRow } from "../store/db.js";
+import type { ApprovalRow, Store } from "../store/db.js";
import { normalizeSettings } from "../agent/settings.js";
import { scopeLabel } from "../agent/memory.js";
import { pwshProbe, type PwshMode } from "../agent/pwsh.js";
@@ -129,7 +129,8 @@ function webEvent(botId: string, text: string): InboundEvent {
}
const consoleConvId = (botId: string) => `${botId}:web:console`;
-function publicApproval(r: ApprovalRow) {
+/** 审批 / 提问给界面的字段;后台任务的带上任务名(卡片上「GPU 价格调研」想问你) */
+function publicApproval(r: ApprovalRow, store?: Store) {
const { payload, result, ...rest } = r;
let questions: unknown = undefined;
if (r.kind === "question") {
@@ -139,7 +140,8 @@ function publicApproval(r: ApprovalRow) {
questions = [];
}
}
- return { ...rest, questions };
+ const taskTitle = r.taskId ? store?.getTask(r.taskId)?.title : undefined;
+ return { ...rest, questions, ...(taskTitle ? { taskTitle } : {}) };
}
/** 允许名单 / 使用请求:界面要的字段(平台 id 只给末尾几位,界面不需要完整的) */
@@ -428,7 +430,34 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
}
// busy:有消息在处理的机器人(纯对话、排队、代理还在启动都算),侧栏的"正在工作"
// background:每个机器人正在进行的后台任务数
- if (p === "/agent" && m === "GET") return send(res, 200, { ...app.agent.status(), busy: [...new Set([...live.bots(), ...app.runtime.busyBots()])], background: app.tasks.background() });
+ // attention:"需要你"的件数(侧栏那一行,没有就是 0);needs:每个机器人几件、最早那件(机器人行的第二行)
+ if (p === "/agent" && m === "GET") {
+ const items = app.attention.list();
+ return send(res, 200, { ...app.agent.status(), busy: [...new Set([...live.bots(), ...app.runtime.busyBots()])], background: app.tasks.background(), attention: items.length, needs: app.attention.byBot(items) });
+ }
+ // —— 需要你(3b):所有机器人里在等人的事,和对它们的操作 ——
+ if (seg[0] === "attention") {
+ if (seg.length === 1 && m === "GET") return send(res, 200, { items: app.attention.list() });
+ const id = decodeURIComponent(seg[1] ?? "");
+ const action = seg[2] ?? "";
+ if (seg.length !== 3 || m !== "POST") throw new HttpError(404, "not found");
+ const item = app.attention.list().find((x) => x.id === id);
+ if (!item) throw new HttpError(409, "已经处理过了");
+ if (!(item.actions as string[]).includes(action)) throw new HttpError(400, "不支持这个操作");
+ const b = await readJson(req);
+ let ok = false;
+ if (action === "approve" || action === "deny") ok = app.agent.approvals.decide(item.approvalId!, action === "approve", "web");
+ else if (action === "answer") {
+ ok = Array.isArray(b.answers)
+ ? app.agent.approvals.answer(item.approvalId!, { answers: b.answers.map((a: any) => ({ id: String(a.id), selected: (a.selected ?? []).map(String), ...(a.custom ? { custom: String(a.custom) } : {}) })) }, "web")
+ : app.agent.approvals.answerText(item.approvalId!, String(b.text ?? ""), "web");
+ } else if (action === "retry") ok = !(await app.tasks.retry(item.taskId!)).error;
+ else if (action === "stop") ok = await app.tasks.stopTask(item.taskId!, "web");
+ else if (action === "seen") ok = app.tasks.seenDelivery(item.taskId!);
+ if (!ok) throw new HttpError(409, "没能完成,可能已经处理过了");
+ app.attention.kick();
+ return send(res, 200, { ok: true, items: app.attention.list() });
+ }
// —— 后台任务(3a:列表、详情、一个 run 的步骤、停止)——
if (seg[0] === "tasks") {
if (seg.length === 1 && m === "GET") {
@@ -537,25 +566,25 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
if (seg[0] === "approvals") {
if (seg.length === 1 && m === "GET") {
const status = url.searchParams.get("status") || undefined;
- return send(res, 200, { approvals: app.store.listApprovals({ status: status as any, botId: url.searchParams.get("bot") || undefined, limit: 100 }).map(publicApproval) });
+ return send(res, 200, { approvals: app.store.listApprovals({ status: status as any, botId: url.searchParams.get("bot") || undefined, limit: 100 }).map((r) => publicApproval(r, app.store)) });
}
const row = seg[1] ? app.store.getApproval(decodeURIComponent(seg[1])) : undefined;
if (!row) throw new HttpError(404, "请求不存在");
- if (seg.length === 2 && m === "GET") return send(res, 200, { approval: publicApproval(row) });
+ if (seg.length === 2 && m === "GET") return send(res, 200, { approval: publicApproval(row, app.store) });
if (seg.length === 3 && m === "POST" && (seg[2] === "approve" || seg[2] === "deny")) {
if (row.kind !== "approval") throw new HttpError(400, "不是审批请求");
const ok = app.agent.approvals.decide(row.id, seg[2] === "approve", "web");
if (!ok) throw new HttpError(409, "请求已处理或已过期");
- return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!) });
+ return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!, app.store) });
}
if (seg.length === 3 && m === "POST" && seg[2] === "answer") {
if (row.kind !== "question" || row.status !== "pending") throw new HttpError(409, "请求已处理或已过期");
const b = await readJson(req);
const ok = Array.isArray(b.answers)
? app.agent.approvals.answer(row.id, { answers: b.answers.map((a: any) => ({ id: String(a.id), selected: (a.selected ?? []).map(String), ...(a.custom ? { custom: String(a.custom) } : {}) })) }, "web")
- : app.agent.approvals.handleReply(row.conversationId, String(b.text ?? ""), "web").handled;
+ : app.agent.approvals.answerText(row.id, String(b.text ?? ""), "web");
if (!ok) throw new HttpError(409, "提交失败");
- return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!) });
+ return send(res, 200, { approval: publicApproval(app.store.getApproval(row.id)!, app.store) });
}
}
if (seg[0] === "conversations") {
@@ -768,7 +797,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
conversationId: consoleConvId(id),
model: conv?.model ?? "",
messages: conv ? app.store.listMessages(conv.id, 200).filter((x) => x.id <= cut) : [],
- pending: app.store.listApprovals({ status: "pending", conversationId: consoleConvId(id), limit: 50 }).map(publicApproval),
+ pending: app.store.listApprovals({ status: "pending", conversationId: consoleConvId(id), limit: 50 }).map((r) => publicApproval(r, app.store)),
live: turns.map((t) => t.snapshot()),
});
}
diff --git a/test/agent.unit.test.ts b/test/agent.unit.test.ts
index 1a6e2ed..f5affbc 100644
--- a/test/agent.unit.test.ts
+++ b/test/agent.unit.test.ts
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { Store } from "../src/store/db.js";
-import { ApprovalCenter, parseAnswer, promptText } from "../src/agent/approvals.js";
+import { ApprovalCenter, isOptionReply, parseAnswer, promptText, taskPromptText } from "../src/agent/approvals.js";
import { WeixinReply } from "../src/channels/weixin/channel.js";
import { WeixinQuota } from "../src/channels/weixin/quota.js";
import { AgentHost, SHELL_LIMITS, agentApi, modelLimits, providerFor, providerProfiles, type AgentApi, type ModelRoute } from "../src/agent/host.js";
@@ -87,6 +87,102 @@ describe("ApprovalCenter", () => {
});
});
+describe("ApprovalCenter:后台任务的提问和审批(3b)", () => {
+ const qPayload = JSON.stringify([{ id: "answer", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }] }]);
+ const taskQuestion = (c: ApprovalCenter) => c.create({ kind: "question", ...base, tool: "task_report", detail: "报告用中文还是英文?", payload: qPayload, taskId: "t_1", runId: "r_1", blocking: false, ttlMs: 0 });
+
+ it("任务的提问不过期、重启后还在;阻塞的照旧作废", () => {
+ let now = 1_000;
+ const c = new ApprovalCenter(store, { ttlMs: 1000, now: () => now });
+ const q = taskQuestion(c);
+ expect(q).toMatchObject({ expiresAt: 0, blocking: false, taskId: "t_1", runId: "r_1" });
+ const a = c.create({ kind: "approval", ...base, taskId: "t_1", runId: "r_1" });
+ expect(a.blocking).toBe(true);
+ now += 10 * 3600_000;
+ c.sweep();
+ expect(store.getApproval(q.id)!.status).toBe("pending");
+ expect(store.getApproval(a.id)!.status).toBe("expired");
+ const c2 = new ApprovalCenter(store);
+ c2.start();
+ c2.stop();
+ expect(store.getApproval(q.id)!.status).toBe("pending");
+ expect(c2.pendingForTask("t_1").map((r) => r.id)).toEqual([q.id]);
+ });
+
+ it("任务的提示不进聊天回合的出口(由任务服务推),新建和决定都通知订阅者", async () => {
+ const c = new ApprovalCenter(store);
+ const sunk: string[] = [];
+ const events: string[] = [];
+ c.bindSink(base.conversationId, async (r) => void sunk.push(r.id));
+ c.listen((e) => events.push(`${e.type}:${e.row.status}`));
+ const chat = c.create({ kind: "approval", ...base });
+ const q = taskQuestion(c);
+ expect(sunk).toEqual([chat.id]);
+ c.answerText(q.id, "2", "web");
+ expect(events).toEqual(["created:pending", "created:pending", "decided:answered"]);
+ expect(JSON.parse(store.getApproval(q.id)!.result)).toEqual({ answers: [{ id: "answer", selected: ["英文"] }] });
+ // 中止、/reset 只作废聊天回合的
+ expect(c.pendingChat(base.conversationId).map((r) => r.id)).toEqual([chat.id]);
+ });
+
+ it("任务的提问:随便回一句不算;引用、编号开头、或它是最后一条消息时的选项编号 / 原文才算", () => {
+ const c = new ApprovalCenter(store);
+ const q = taskQuestion(c);
+ let latest = false;
+ const ctx = { latest: () => latest, quotes: (_r: any, quote: string) => quote.includes("中文还是英文"), answered: () => "收到" };
+ const conv = base.conversationId;
+ expect(c.handleReply(conv, "你好", "u1", ctx)).toEqual({ handled: false });
+ expect(c.handleReply(conv, "1", "u1", ctx)).toEqual({ handled: false });
+ expect(c.handleReply(conv, "y", "u1", ctx)).toEqual({ handled: false });
+ latest = true;
+ expect(c.handleReply(conv, "你好", "u1", ctx)).toEqual({ handled: false });
+ expect(c.handleReply(conv, "3", "u1", ctx)).toEqual({ handled: false });
+ expect(c.handleReply(conv, "英文", "u1", ctx)).toEqual({ handled: true, ack: "收到" });
+ expect(JSON.parse(store.getApproval(q.id)!.result).answers[0].selected).toEqual(["英文"]);
+ const q2 = taskQuestion(c);
+ latest = false;
+ expect(c.handleReply(conv, `${q2.code}:都要`, "u1", ctx)).toEqual({ handled: true, ack: "收到" });
+ expect(JSON.parse(store.getApproval(q2.id)!.result).answers[0]).toEqual({ id: "answer", selected: [], custom: "都要" });
+ const q3 = taskQuestion(c);
+ expect(c.handleReply(conv, "> 中文还是英文?\n先用中文", "u1", { ...ctx, quote: "报告用中文还是英文?", plain: "先用中文" })).toEqual({ handled: true, ack: "收到" });
+ expect(JSON.parse(store.getApproval(q3.id)!.result).answers[0]).toEqual({ id: "answer", selected: [], custom: "先用中文" });
+ });
+
+ it("聊天回合在等的提问优先:随便一句都算它的(任务的提问只在引用、编号时才抢)", () => {
+ const c = new ApprovalCenter(store);
+ const tq = taskQuestion(c);
+ const chat = c.create({ kind: "question", ...base, tool: "", detail: "", payload: JSON.stringify([{ id: "q1", question: "继续吗?" }]) });
+ const ctx = { latest: () => true };
+ expect(c.handleReply(base.conversationId, "继续", "u1", ctx).handled).toBe(true);
+ expect(store.getApproval(chat.id)!.status).toBe("answered");
+ expect(store.getApproval(tq.id)!.status).toBe("pending");
+ });
+
+ it("任务的审批:y 编号总能批;光回 y 只在它是最后一条消息时;引用时要 y / n", () => {
+ const c = new ApprovalCenter(store);
+ const a = c.create({ kind: "approval", ...base, taskId: "t_1", runId: "r_1", ttlMs: 12 * 3600_000 });
+ let latest = false;
+ const ctx = { latest: () => latest, quotes: () => true };
+ expect(c.handleReply(base.conversationId, "ok", "u1", { latest: () => latest })).toEqual({ handled: false });
+ latest = true;
+ expect(c.handleReply(base.conversationId, "n", "u1", ctx)).toEqual({ handled: true, ack: `❌ 已拒绝 ${a.code}` });
+ const b = c.create({ kind: "approval", ...base, taskId: "t_1", runId: "r_1" });
+ expect(c.handleReply(base.conversationId, "看看再说", "u1", { ...ctx, quote: "需批准", plain: "看看再说" })).toEqual({ handled: true, ack: `回复 y ${b.code} 批准,n ${b.code} 拒绝` });
+ latest = false;
+ expect(c.handleReply(base.conversationId, `y ${b.code}`, "u1", ctx)).toEqual({ handled: true, ack: `✅ 已批准 ${b.code}(仅本次)` });
+ });
+
+ it("任务推给用户的提示样式", () => {
+ const c = new ApprovalCenter(store);
+ expect(taskPromptText(taskQuestion(c), "GPU 价格调研")).toBe("❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)");
+ const a = c.create({ kind: "approval", ...base, detail: "rm -rf build/", taskId: "t_1" });
+ expect(taskPromptText(a, "清理旧构建")).toBe(`需批准(任务「清理旧构建」):\`rm -rf build/\` — 回复 y ${a.code} / n ${a.code}`);
+ expect(isOptionReply([{ id: "a", question: "颜色", options: [{ label: "红" }, { label: "蓝" }], multiSelect: true }], "1, 2")).toBe(true);
+ expect(isOptionReply([{ id: "a", question: "颜色", options: [{ label: "红" }, { label: "蓝" }] }], "1, 2")).toBe(false);
+ expect(isOptionReply([{ id: "a", question: "名字" }], "1")).toBe(false);
+ });
+});
+
describe("parseAnswer", () => {
const qs = [
{ id: "a", question: "颜色", options: [{ label: "红" }, { label: "蓝" }, { label: "绿" }], multiSelect: true },
diff --git a/test/attention.unit.test.ts b/test/attention.unit.test.ts
new file mode 100644
index 0000000..ec09151
--- /dev/null
+++ b/test/attention.unit.test.ts
@@ -0,0 +1,126 @@
+/**
+ * 「需要你」(3b):来源合在一起、排好序;有变化才通知;系统通知每项最多一次(重启也算);健康时什么都没有。
+ * 界面那一半:侧栏的「需要你」行和托盘角标在没事时不画。
+ */
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { Store } from "../src/store/db.js";
+import { ApprovalCenter } from "../src/agent/approvals.js";
+import { Attention, approvalItems, botLine, notificationOf, trayTitle, type AttentionItem } from "../src/tasks/attention.js";
+
+const item = (o: Partial<AttentionItem> & Pick<AttentionItem, "id" | "kind">): AttentionItem => ({
+ botId: "b",
+ botName: "小蓝",
+ subject: "GPU 价格调研",
+ status: "等你回答",
+ line: "报告用中文还是英文?",
+ since: 1,
+ severity: "warn",
+ actions: [],
+ ...o,
+});
+
+/** vnode 里所有的字(只看结构,不渲染) */
+const textOf = (v: any): string => (v == null || typeof v === "boolean" ? "" : typeof v !== "object" ? String(v) : Array.isArray(v) ? v.map(textOf).join("") : textOf(v.props?.children));
+
+describe("界面:侧栏的「需要你」行", () => {
+ it("没事时不画这一行;有事时是黄点、「需要你」和件数", async () => {
+ // 界面模块在浏览器里跑:只补上它们加载时要的那一点
+ (globalThis as any).window ??= { matchMedia: () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) };
+ // @ts-expect-error 界面代码是不经构建的 JS
+ const { NeedsRow } = await import("../ui/screens/needs-you.js");
+ expect(NeedsRow({ count: 0 })).toBeNull();
+ expect(NeedsRow({ count: undefined })).toBeNull();
+ const row = NeedsRow({ count: 3, on: true, onClick: () => {} }) as any;
+ expect(row.props.class).toBe("needs-row sel");
+ expect(textOf(row)).toBe("需要你3");
+ });
+});
+
+describe("Attention", () => {
+ let store: Store;
+ let att: Attention;
+ beforeEach(() => {
+ store = new Store(":memory:");
+ att = new Attention({ store, debounceMs: 1, intervalMs: 60_000 });
+ });
+ afterEach(() => {
+ att.stop();
+ store.close();
+ });
+
+ it("健康时什么都没有:没有项、没有件数、托盘只有应用名", () => {
+ att.addSource(() => []);
+ expect(att.list()).toEqual([]);
+ expect(att.count()).toBe(0);
+ expect(att.byBot()).toEqual({});
+ expect(trayTitle("AnyModelBot", 0)).toBe("AnyModelBot");
+ expect(att.takeNew()).toEqual([]);
+ });
+
+ it("排序:提问和审批在前,再是失败、没送到、登录;同一类旧的在前;同一 id 只算一次", () => {
+ att.addSource(() => [item({ id: "login:b:weixin", kind: "login", since: 1 }), item({ id: "task:t2", kind: "failed", since: 2 }), item({ id: "approval:a2", kind: "approval", since: 9 })]);
+ att.addSource(() => [item({ id: "task:t3", kind: "delivery", since: 0 }), item({ id: "approval:a1", kind: "question", since: 5 }), item({ id: "task:t2", kind: "failed", since: 2 })]);
+ expect(att.list().map((x) => x.id)).toEqual(["approval:a1", "approval:a2", "task:t2", "task:t3", "login:b:weixin"]);
+ expect(att.count()).toBe(5);
+ });
+
+ it("每个机器人几件、最早那件(侧栏机器人行的第二行)", () => {
+ att.addSource(() => [item({ id: "a", kind: "question", since: 1 }), item({ id: "b", kind: "failed", since: 2, status: "失败" }), item({ id: "c", kind: "login", botId: "g", botName: "绿草", subject: "微信登录已过期", status: "" })]);
+ expect(att.byBot()).toEqual({ b: { n: 2, line: "GPU 价格调研等你回答" }, g: { n: 1, line: "微信登录已过期" } });
+ });
+
+ it("系统通知每项最多一次,重启后也不再给;处理掉的项从记录里清掉", () => {
+ let items = [item({ id: "approval:a1", kind: "question" })];
+ att.addSource(() => items);
+ expect(att.takeNew().map((x) => x.id)).toEqual(["approval:a1"]);
+ expect(att.takeNew()).toEqual([]);
+ const again = new Attention({ store });
+ again.addSource(() => items);
+ expect(again.takeNew()).toEqual([]);
+ items = [item({ id: "approval:a2", kind: "approval" })];
+ expect(again.takeNew().map((x) => x.id)).toEqual(["approval:a2"]);
+ expect(JSON.parse(store.getKV("attention:notified")!)).toEqual(["approval:a2"]);
+ });
+
+ it("订阅:立即拿到一份;有变化才再通知(kick 合并同一时刻的几次)", async () => {
+ let items: AttentionItem[] = [];
+ att.addSource(() => items);
+ const seen: number[] = [];
+ const off = att.onChange((x) => seen.push(x.length));
+ expect(seen).toEqual([0]);
+ att.kick();
+ await new Promise((r) => setTimeout(r, 20));
+ expect(seen).toEqual([0]);
+ items = [item({ id: "a", kind: "question" })];
+ att.kick();
+ att.kick();
+ await new Promise((r) => setTimeout(r, 20));
+ expect(seen).toEqual([0, 1]);
+ off();
+ items = [];
+ att.kick();
+ await new Promise((r) => setTimeout(r, 20));
+ expect(seen).toEqual([0, 1]);
+ });
+
+ it("系统通知的样子:标题「小蓝 需要你」,正文「GPU 价格调研:报告用中文还是英文?」", () => {
+ expect(notificationOf(item({ id: "a", kind: "question" }))).toEqual({ title: "小蓝 需要你", body: "GPU 价格调研:报告用中文还是英文?" });
+ expect(notificationOf(item({ id: "l", kind: "login", subject: "微信登录已过期", status: "", line: "" }))).toEqual({ title: "小蓝 需要你", body: "微信登录已过期" });
+ expect(botLine(item({ id: "f", kind: "failed", status: "失败" }))).toBe("GPU 价格调研失败");
+ expect(trayTitle("AnyModelBot", 3)).toBe("AnyModelBot · 3 件事需要你");
+ });
+
+ it("审批中心那一份:任务的以任务名为题,聊天里的以渠道为题", () => {
+ store.createBot({ id: "b", name: "小蓝" });
+ store.ensureConversation("b", "weixin", "owner", "owner");
+ const c = new ApprovalCenter(store);
+ const now = Date.now();
+ store.insertTask({ id: "t_1", botId: "b", conversationId: "b:weixin:owner", originMessageId: 0, originRef: "", title: "清理旧构建", brief: "", sessionId: "task-t_1", folder: "tasks/x", model: "m", permission: "workspace", budgetUsd: 1, createdAt: now, updatedAt: now });
+ const a = c.create({ kind: "approval", botId: "b", conversationId: "b:weixin:owner", sessionId: "task-t_1", tool: "bash", detail: "rm -rf build/", reason: "", taskId: "t_1" });
+ const q = c.create({ kind: "question", botId: "b", conversationId: "b:weixin:owner", sessionId: "chat", tool: "ask_user_question", detail: "继续吗?", reason: "", payload: JSON.stringify([{ id: "q", question: "继续吗?" }]) });
+ const items = approvalItems(store, c.pendingAll());
+ expect(items.find((x) => x.id === `approval:${a.id}`)).toMatchObject({ kind: "approval", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", actions: ["approve", "deny"], taskId: "t_1", code: a.code, channel: "weixin" });
+ expect(items.find((x) => x.id === `approval:${q.id}`)).toMatchObject({ kind: "question", subject: "微信", status: "等你回答", line: "继续吗?", actions: ["answer"], questions: [{ id: "q", question: "继续吗?" }] });
+ expect(items.find((x) => x.id === `approval:${q.id}`)!.taskId).toBeUndefined();
+ });
+});
diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.ts
index af13155..a3c4ac9 100644
--- a/test/prompts.unit.test.ts
+++ b/test/prompts.unit.test.ts
@@ -126,8 +126,10 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [
["生视频工具:默认模型、花费不高直接生成", "tool generate_video", ["generates right away", "\"confirm\""], ["Before anything is generated the user is asked"]],
// —— 后台任务(3a)——
["聊天代理:长活或用户说后台做才开任务,能马上答的不开;开了只说一句,不自己做", "tool task_start", ["more than a few minutes or many steps", "后台做", "not for what you can answer now", "前台做", "in one sentence", "do not do the work yourself"]],
- ["用户提到某个任务时把话转给它", "tool task_message", ["when they refer to it", "next step", "resumes"]],
- ["任务规则优先于聊天规则;不问用户,自己决定并说明", "task", ["优先于上面的聊天规则", "不要问用户", "在结果里说明"], ["ask_user_question"]],
+ ["用户提到某个任务、回答它的问题时把话转给它", "tool task_message", ["when they refer to it", "answer its question", "next step", "resumes"]],
+ // —— 任务的提问(3b):先自己定,非用户定不可才问,一次一个,问完结束这一轮 ——
+ ["任务规则优先于聊天规则;能自己定的自己定并说明,非用户定不可才问", "task", ["优先于上面的聊天规则", "选一个合理的做法", "在结果里说明", "非用户定不可", "needs_you", "一个问题", "结束这一轮"], ["ask_user_question"]],
+ ["task_report:needs_you 带一个问题,回答是下一条消息;问完结束这一轮", "tool task_report", ["needs_you", "only the user can decide", "their answer is your next message", "After done, failed or needs_you, end your turn"]],
["任务:外部动作前后记日志(重启后靠它不重复做)", "task", [".task/journal.md"]],
["任务:做完或做不下去才说话,一句话,结果和在哪里;中途不汇报", "task", ["task_report", "done 或 failed", "不超过 300 字", "在哪里", "中途不用汇报", "不会发给用户"]],
["task_report:done / failed 的那句话是用户收到的,progress 不发;报完结束这一轮", "tool task_report", ["one line the user receives", "at most 300 characters", "never sent", "end your turn"]],
@@ -173,8 +175,11 @@ describe.skipIf(!runtime)("提示词约定", () => {
expect(prompt + tools, `${prompt} characters of prompt and ${tools} of tools`).toBeLessThanOrEqual(BUDGET);
});
- /** 任务会话在聊天会话之外多出来的:任务规则段 + task_report(去掉的工具不算)。基线 1,255(规则 363 + task_report 892),上限高约 5%。 */
- const TASK_BUDGET = 1_320;
+ /**
+ * 任务会话在聊天会话之外多出来的:任务规则段 + task_report(去掉的工具不算)。上限高约 5%。
+ * 3a 基线 1,255(规则 363 + task_report 892);3b 加上提问(needs_you、question、options 和怎么问的那条规则)后 1,533(规则 399 + task_report 1,134)。
+ */
+ const TASK_BUDGET = 1_610;
it("任务会话多出来的提示词和工具不超过字符数上限", async () => {
const { task } = await loadPlugins();
const extra = TASK_RULES.length + JSON.stringify(task.tools).length;
diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.ts
index 229a5bc..4453954 100644
--- a/test/tasks.integration.test.ts
+++ b/test/tasks.integration.test.ts
@@ -3,6 +3,8 @@
* 退出演示:微信里说「调研 Y」,聊天代理开一个后台任务,聊天照常回答;任务跑完,结果经出站队列回到同一个微信会话、只发一次;
* 任务跑到一半应用重启,带着恢复说明接着做,结果仍只发一次。另外:/stop 编号和界面的停止只停这个任务;
* 两个任务在跑时,聊天消息不排在它们后面(人的通道);收尾(后台命令)、没报告时的提醒、每种会话的工具。
+ * 3b 退出演示:任务在微信里问「中文还是英文?」,用户回编号,任务接着做完;桌面的「需要你」列出它,回答后变空。
+ * 另外:引用回答、中间的普通聊天不被当成回答;任务会话里的审批推到同一个微信会话(带任务名),y 编号批准后接着做。
*/
import fs from "node:fs";
import os from "node:os";
@@ -63,6 +65,18 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
if (/The app restarted while you were working/.test(user)) return report(`RECOVERED-${tag}:调研好了,结论在 notes.md。`);
if (/^Report this task's state with task_report now/.test(user)) return report(`NUDGED-${tag}`);
if (/^background job /.test(user)) return report(`BGRESULT-${tag}`);
+ // ASK:先问用户(needs_you),回答作为下一条输入回来,再按回答做完
+ if (tag.startsWith("ASK")) {
+ const ans = /^\[用户回答了你的问题\][\s\S]*回答:(.+)$/.exec(user);
+ if (ans) return report(`ANSWERED-${tag}:用${ans[1]}写好了。`);
+ return done ? { text: "已提问" } : { tool: { name: "task_report", args: { state: "needs_you", summary: "差语言", question: "中文还是英文?", options: ["中文", "英文"] } } };
+ }
+ // APPR:一条要提权的命令(要批准),批了才跑
+ if (tag.startsWith("APPR")) {
+ if (done === 0) return { tool: { name: "bash", args: { description: "run", command: "echo appr-$((40+2))", sandbox_permissions: "danger-full-access", justification: "测试提权" } } };
+ const out = messages.filter((m) => m.role === "tool").map((m) => textOf(m.content)).join("|");
+ return report(`APPROVED-${tag}<<${out.includes("appr-42") ? "ran" : "not run"}>>`, 1);
+ }
if (tag.startsWith("HANG")) return { hang: true };
if (tag.startsWith("TOOLS")) return done ? { text: `TASKTOOLS` } : report(`TASKTOOLS-${tag}<<${tools.join(",")}>>`);
if (tag.startsWith("QUIET")) return { text: "我做完了" }; // 不调用 task_report:宿主提醒一次
@@ -178,6 +192,80 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
expect(host.restarts).toBe(0);
}, 180_000);
+ it("exit demo (3b): a task asks 「中文还是英文?」 on WeChat; a bare number answers it and the task continues; needs-you lists it on desktop and is empty after", async () => {
+ expect((await api("/attention")).items).toEqual([]);
+ const t = await research("ASKQ");
+ // 问题推到同一个微信会话:设计里的样式,只推一次
+ await waitFor(() => sentTo("❓「调研 ASKQ」").length === 1);
+ expect(sentTo("❓「调研 ASKQ」")[0].text).toBe("❓「调研 ASKQ」想问你:中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)");
+ await waitFor(() => stage("ASKQ") === "needs-you/answer");
+ // 桌面:「需要你」列出它,侧栏的件数是 1
+ const { items } = await api("/attention");
+ expect(items).toHaveLength(1);
+ expect(items[0]).toMatchObject({ kind: "question", botName: "小蓝", subject: "调研 ASKQ", status: "等你回答", line: "中文还是英文?", channel: "weixin", taskId: t.id, actions: ["answer"] });
+ expect(items[0].questions[0].options.map((o: any) => o.label)).toEqual(["中文", "英文"]);
+ expect((await api("/agent")).attention).toBe(1);
+ // 用户在微信里只回了一个编号:是回答,不进聊天
+ const chats = calls.filter((c) => !c.task).length;
+ ilink.push(OWNER, "1");
+ await waitFor(() => sentTo("收到,「调研 ASKQ」继续。").length === 1);
+ await waitFor(() => sentTo("ANSWERED-ASKQ").length === 1);
+ expect(sentTo("ANSWERED-ASKQ")[0].text).toBe("ANSWERED-ASKQ:用中文写好了。");
+ await waitFor(() => stage("ASKQ") === "ready");
+ expect(calls.slice(0).filter((c) => !c.task).length).toBe(chats);
+ // 回答作为任务的下一条输入,在同一个会话里接着做(人的唤醒:answer run)
+ const last = calls.filter((c) => c.task && c.users.some((u) => u.includes("RESEARCH ASKQ"))).at(-1)!;
+ expect(last.users).toContain("[用户回答了你的问题]\n问题:中文还是英文?\n回答:中文");
+ const d = await api(`/tasks/${t.id}`);
+ expect(d.runs.map((r: any) => [r.cause, r.outcome])).toEqual([
+ ["launch", "needs_you"],
+ ["answer", "done"],
+ ]);
+ // 回答之后「需要你」是空的;问题只推过一次
+ expect((await api("/attention")).items).toEqual([]);
+ expect((await api("/agent")).attention).toBe(0);
+ await app.outbox.idle();
+ expect(sentTo("❓「调研 ASKQ」")).toHaveLength(1);
+ expect(app.store.listApprovals({ taskId: t.id })[0]).toMatchObject({ status: "answered", blocking: false, conversationId: CONV });
+ }, 180_000);
+
+ it("answering by quote: a bare number after other chat is ordinary chat; quoting the question answers it", async () => {
+ const t = await research("ASKW");
+ await waitFor(() => sentTo("❓「调研 ASKW」").length === 1);
+ const asked = sentTo("❓「调研 ASKW」")[0].text;
+ // 中间聊了一句:机器人最后一条消息不再是提问
+ ilink.push(OWNER, "PING mid");
+ await waitFor(() => sentTo("PONG-mid").length === 1);
+ ilink.push(OWNER, "2");
+ await waitFor(() => calls.some((c) => !c.task && c.users.at(-1) === "2"));
+ expect(stage("ASKW")).toBe("needs-you/answer");
+ // 引用那条提问回答(自己写的回答)
+ ilink.pushItems(OWNER, [{ type: 1, text_item: { text: "英文" }, ref_msg: { title: "", message_item: { type: 1, text_item: { text: asked } } } }]);
+ await waitFor(() => sentTo("ANSWERED-ASKW").length === 1);
+ expect(sentTo("ANSWERED-ASKW")[0].text).toBe("ANSWERED-ASKW:用英文写好了。");
+ expect(sentTo("收到,「调研 ASKW」继续。")).toHaveLength(1);
+ await waitFor(() => stage("ASKW") === "ready");
+ expect(calls.some((c) => !c.task && c.users.some((u) => u.includes("英文") && u.includes(">")))).toBe(false);
+ expect((await api(`/tasks/${t.id}`)).runs.map((r: any) => r.cause)).toEqual(["launch", "answer"]);
+ }, 180_000);
+
+ it("an approval from a task session lands on the task's WeChat chat, named after the task; 'y CODE' lets the task continue", async () => {
+ const t = await research("APPR1");
+ await waitFor(() => sentTo("需批准(任务「调研 APPR1」)").length === 1);
+ const row = app.store.listApprovals({ status: "pending", taskId: t.id })[0];
+ expect(row).toMatchObject({ kind: "approval", blocking: true, conversationId: CONV, tool: "bash", detail: "echo appr-$((40+2))" });
+ expect(row.expiresAt - row.createdAt).toBe(12 * 3600_000);
+ expect(sentTo("需批准(任务「调研 APPR1」)")[0].text).toBe(`需批准(任务「调研 APPR1」):\`echo appr-$((40+2))\` — 回复 y ${row.code} / n ${row.code}`);
+ expect(stage("APPR1")).toBe("needs-you/approval");
+ expect((await api("/attention")).items.map((x: any) => [x.kind, x.subject, x.status, x.line])).toEqual([["approval", "调研 APPR1", "等你批准", "echo appr-$((40+2))"]]);
+ ilink.push(OWNER, `y ${row.code}`);
+ await waitFor(() => sentTo(`✅ 已批准 ${row.code}`).length === 1);
+ await waitFor(() => sentTo("APPROVED-APPR1").length === 1);
+ expect(sentTo("APPROVED-APPR1")[0].text).toBe("APPROVED-APPR1<<ran>>");
+ await waitFor(() => stage("APPR1") === "ready");
+ expect((await api("/attention")).items).toEqual([]);
+ }, 180_000);
+
it("each session kind gets its own tools: tasks report and never present, ask or start tasks; chats start tasks but cannot report", async () => {
ilink.push(OWNER, "LISTTOOLS");
await waitFor(() => sentTo("CHATTOOLS<<").length === 1);
diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.ts
index b686bd2..fe066ad 100644
--- a/test/tasks.unit.test.ts
+++ b/test/tasks.unit.test.ts
@@ -2,6 +2,7 @@
* 后台任务(3a)的零件:阶段表(一行一行)、名额(每个机器人、总数、人的预留名额与先后)、
* TaskService 对着一个假的宿主:建任务与第一条输入、一轮结束与收尾、Report、提醒、出错重试、追加、停止、
* 重启恢复(恢复说明在前、没收下的输入再交一次)、送达(出站队列 id 固定,只交一次)、/tasks 与 /stop 编号。
+ * 3b:任务的提问(needs_you → 不阻塞的提问 → 推给会话、一次一个 → 回答成为新输入)、任务会话里的审批、「需要你」。
*/
import fs from "node:fs";
import os from "node:os";
@@ -9,7 +10,8 @@ import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { taskStage, type StageInput } from "../src/tasks/stage.js";
import { byPriority, pickRuns, priorityOf, type Waiting } from "../src/tasks/slots.js";
-import { TaskService, slugOf, takeTaskNotes, type TaskHost, type TaskNotification } from "../src/tasks/service.js";
+import { TaskService, askId, quotes, slugOf, takeTaskNotes, type TaskHost, type TaskNotification } from "../src/tasks/service.js";
+import { ApprovalCenter } from "../src/agent/approvals.js";
import { AgentHost, ResumeFailed } from "../src/agent/host.js";
import { DEFAULT_SETTINGS, normalizeSettings } from "../src/agent/settings.js";
import { NUDGE, TASK_RULES, recoveryNote, taskBrief } from "../src/agent/prompts/index.js";
@@ -154,11 +156,12 @@ describe("TaskService(假宿主)", () => {
let store: Store;
let host: FakeHost;
let outbox: Outbox;
+ let approvals: ApprovalCenter;
let svc: TaskService;
let ws: string;
const CONV = "b:weixin:owner";
- const make = () => new TaskService({ store, host, outbox, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
+ const make = () => new TaskService({ store, host, outbox, approvals, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });
beforeEach(() => {
ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-unit-"));
store = new Store(":memory:");
@@ -169,6 +172,7 @@ describe("TaskService(假宿主)", () => {
store.addMessage(CONV, "user", "帮我后台调研一下三家云的 GPU 价格 [文件 价目.pdf → inbox/20261031-x-价目.pdf]");
host = new FakeHost(ws);
outbox = new Outbox(store);
+ approvals = new ApprovalCenter(store);
svc = make();
svc.start();
});
@@ -257,11 +261,230 @@ describe("TaskService(假宿主)", () => {
expect(store.listOutbox({ limit: 50 }).map((r) => r.id)).toEqual([`task:${t.id}:failure:${store.listRuns({ taskId: t.id })[0].id}`]);
});
- it("问用户在 3a 不可用:needs_you 被拒,代理自己决定", async () => {
+ /** 代理报 needs_you 带一个问题,结束这一轮 */
+ const ask = (sessionId: string, question = "报告用中文还是英文?", options: string[] | undefined = ["中文", "英文"]) =>
+ turn(sessionId, () => void expect(svc.report({ sessionId, state: "needs_you", summary: "查完了,差语言", question, ...(options ? { options } : {}) }).text).toMatch(/^Recorded\. End your turn now: the app asks the user/));
+ const reply = (text: string, ctx = {}) => approvals.handleReply(CONV, text, "weixin:owner", { ...svc.replyContext(CONV), ...ctx });
+ const asks = () => store.listOutbox({ limit: 100 }).filter((r) => r.id.includes(":ask:")).reverse();
+
+ it("needs_you:要有一个问题;没有审批中心就不能问", async () => {
const t = start();
await flush();
- expect(report(t.sessionId, "needs_you").error).toMatch(/cannot ask the user/);
- expect(report(t.sessionId, "maybe").error).toMatch(/state must be/);
+ expect(report(t.sessionId, "needs_you").error).toMatch(/needs a question/);
+ expect(report(t.sessionId, "maybe").error).toMatch(/state must be progress, needs_you, done or failed/);
+ svc.stop();
+ const bare = new TaskService({ store, host, outbox, defaultModel: () => "m" });
+ bare.start();
+ const u = bare.create({ botId: "b", conversationId: CONV, title: "U", brief: "" }).task!;
+ await flush();
+ expect(bare.report({ sessionId: u.sessionId, state: "needs_you", summary: "", question: "要吗?" }).error).toMatch(/cannot ask the user right now/);
+ bare.stop();
+ });
+
+ it("退出演示的单元版:提问推到微信(一次),阶段等你回答;回编号算回答,回答成为新输入、开一个 answer run,任务接着做完", async () => {
+ const t = start();
+ await flush();
+ await ask(t.sessionId);
+ expect(runs(t.id)).toEqual([["launch", "ended", "needs_you"]]);
+ const [q] = approvals.pendingForTask(t.id);
+ expect(q).toMatchObject({ kind: "question", blocking: false, expiresAt: 0, taskId: t.id, runId: store.listRuns({ taskId: t.id })[0].id, conversationId: CONV, sessionId: t.sessionId });
+ expect(svc.get(t.id)!.stage).toMatchObject({ key: "needs-you/answer", label: "等你回答", group: "needs" });
+ // 推给微信:设计里的样式,原样发(不过 Markdown 过滤),id 固定
+ expect(asks().map((r) => [r.id, r.kind, r.body.text, r.body.raw])).toEqual([[askId(q), "text", "❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)", true]]);
+ expect(store.listMessages(CONV).at(-1)!.content).toBe(asks()[0].body.text);
+ // 聊天代理知道这件事(用户在聊天里回答时,它能转给任务)
+ expect(takeTaskNotes(store, CONV)).toBe("[后台任务「GPU 价格调研」在等用户回答:报告用中文还是英文?(中文 / 英文)。用户在聊天里回答它时,用 task_message 转给这个任务]");
+ // 提问是机器人最后一条消息:光回编号就是回答
+ expect(reply("1")).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });
+ await flush();
+ expect(store.getApproval(q.id)).toMatchObject({ status: "answered", decidedBy: "weixin:owner" });
+ expect(runs(t.id)).toEqual([["launch", "ended", "needs_you"], ["answer", "running", ""]]);
+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, resume: true });
+ expect(host.prompts.at(-1)!.text).toBe("[用户回答了你的问题]\n问题:报告用中文还是英文?\n回答:中文");
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "报告写好了(中文),在 report.md。"));
+ expect(runs(t.id).at(-1)).toEqual(["answer", "ended", "done"]);
+ expect(store.listOutbox({ limit: 50 }).find((r) => r.id.includes(":result:"))!.body.text).toBe("报告写好了(中文),在 report.md。");
+ expect(asks()).toHaveLength(1);
+ });
+
+ it("提问不是机器人最后一条消息时,光回编号是普通聊天;引用和编号开头什么时候都算", async () => {
+ const t = start();
+ await flush();
+ await ask(t.sessionId);
+ const [q] = approvals.pendingForTask(t.id);
+ // 之后机器人又在这个会话里回了一句(聊天)
+ store.insertOutbox({ id: "wx:b:m9:final", botId: "b", channel: "weixin", conversationId: CONV, peerId: "owner", kind: "text", body: { text: "下午 3 点的会是线上的" }, replyTo: "", due: Date.now(), createdAt: Date.now(), expiresAt: Date.now() + 60_000 });
+ expect(reply("1")).toEqual({ handled: false });
+ expect(reply("中文")).toEqual({ handled: false });
+ expect(reply("好的")).toEqual({ handled: false });
+ // 以编号开头
+ expect(reply(`${q.code} 英文`)).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });
+ await flush();
+ expect(host.prompts.at(-1)!.text).toContain("回答:英文");
+ // 引用(被截短、前面带名字也认得)
+ const u = start("季度报告");
+ await flush();
+ await ask(u.sessionId, "PPT 要几页?", []);
+ const [q2] = approvals.pendingForTask(u.id);
+ expect(asks().find((r) => r.id === askId(q2))!.body.text).toBe("❓「季度报告」想问你:PPT 要几页?\n(引用这条消息回答)");
+ expect(reply("10 页左右", { quote: "引用了别的消息", plain: "10 页左右" })).toEqual({ handled: false });
+ expect(reply("> 小蓝: ❓「季度报告」想问你:PPT 要…\n10 页左右", { quote: "小蓝: ❓「季度报告」想问你:PPT 要…", plain: "10 页左右" })).toEqual({ handled: true, ack: "收到,「季度报告」继续。" });
+ await flush();
+ expect(host.prompts.at(-1)!.text).toBe("[用户回答了你的问题]\n问题:PPT 要几页?\n回答:10 页左右");
+ });
+
+ it("引用匹配:推出去的原文、截短的、带名字的;太短的片段和别的消息不算", () => {
+ const sent = "❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)";
+ expect(quotes(sent, sent, "报告用中文还是英文?")).toBe(true);
+ expect(quotes(sent, "❓「GPU 价格调研」想问你:报告用中文还是…", "报告用中文还是英文?")).toBe(true);
+ expect(quotes(sent, "小蓝:报告用中文还是英文?", "报告用中文还是英文?")).toBe(true);
+ expect(quotes(sent, "中文", "报告用中文还是英文?")).toBe(false);
+ expect(quotes(sent, "下午 3 点的会是线上的", "报告用中文还是英文?")).toBe(false);
+ expect(quotes(sent, "", "报告用中文还是英文?")).toBe(false);
+ });
+
+ it("一个会话同时只推一个:第二个任务的提问在「需要你」里等,第一个回答了才推", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 4 });
+ const a = start("A 任务");
+ const b = start("B 任务");
+ await flush();
+ await ask(a.sessionId, "A 用哪个?");
+ await ask(b.sessionId, "B 用哪个?");
+ const qa = approvals.pendingForTask(a.id)[0];
+ const qb = approvals.pendingForTask(b.id)[0];
+ expect(asks().map((r) => r.id)).toEqual([askId(qa)]);
+ expect(svc.get(b.id)!.stage.key).toBe("needs-you/answer");
+ // 光回编号只认推出去的那个(它是最后一条消息)
+ expect(reply("2")).toMatchObject({ handled: true, ack: "收到,「A 任务」继续。" });
+ await flush();
+ expect(store.getApproval(qb.id)!.status).toBe("pending");
+ expect(asks().map((r) => r.id)).toEqual([askId(qa), askId(qb)]);
+ expect(asks().at(-1)!.body.text).toBe("❓「B 任务」想问你:B 用哪个?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)");
+ });
+
+ it("聊天代理的 task_message:任务在等回答时,这句话就是回答", async () => {
+ store.setAgentSession(CONV, "b", "session-chat");
+ const t = start();
+ await flush();
+ await ask(t.sessionId);
+ const r = await svc.chatTool({ botId: "b", sessionId: "session-chat", op: "message", args: { task: "GPU", text: "用英文吧" } });
+ expect(r.text).toMatch(/^Passed to 「GPU 价格调研」\. It answers the task's open question; the task continues\./);
+ await flush();
+ expect(approvals.pendingForTask(t.id)).toEqual([]);
+ expect(host.prompts.at(-1)!.text).toBe("[用户回答了你的问题]\n问题:报告用中文还是英文?\n回答:用英文吧");
+ expect(runs(t.id).at(-1)).toEqual(["answer", "running", ""]);
+ });
+
+ it("重启:提问留着(不阻塞的不作废),不再推一遍;重启后回答照样开 run;阻塞的审批作废", async () => {
+ const t = start();
+ await flush();
+ await ask(t.sessionId);
+ const blocking = approvals.create({ kind: "approval", botId: "b", conversationId: "b:web:console", sessionId: "session-chat", tool: "bash", detail: "rm -rf x", reason: "" });
+ svc.stop();
+ approvals = new ApprovalCenter(store);
+ approvals.start();
+ approvals.stop();
+ expect(store.getApproval(blocking.id)!.status).toBe("expired");
+ svc = make();
+ svc.start();
+ const [q] = approvals.pendingForTask(t.id);
+ expect(q.status).toBe("pending");
+ expect(asks()).toHaveLength(1);
+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/answer");
+ expect(reply("2").handled).toBe(true);
+ await flush();
+ expect(runs(t.id).at(-1)).toEqual(["answer", "running", ""]);
+ });
+
+ it("这一轮以 needs_you 结束、提问还没建就重启了:启动时补问一次", async () => {
+ const t = start();
+ await flush();
+ const run = store.listRuns({ taskId: t.id })[0];
+ svc.stop();
+ store.updateRun(run.id, { state: "ended", outcome: "needs_you", endedAt: Date.now(), report: { state: "needs_you", summary: "", question: { question: "要几页?" }, at: Date.now() } });
+ svc = make();
+ svc.start();
+ expect(approvals.pendingForTask(t.id).map((r) => [r.detail, r.runId])).toEqual([["要几页?", run.id]]);
+ svc.stop();
+ svc = make();
+ svc.start();
+ expect(approvals.pendingForTask(t.id)).toHaveLength(1);
+ });
+
+ it("停止任务:它的提问作废,同一会话的下一个提问推出去", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 4 });
+ const a = start("A 任务");
+ const b = start("B 任务");
+ await flush();
+ await ask(a.sessionId);
+ await ask(b.sessionId);
+ const qa = approvals.pendingForTask(a.id)[0];
+ expect(asks()).toHaveLength(1);
+ await svc.stopTask(a.id, "test");
+ expect(store.getApproval(qa.id)).toMatchObject({ status: "cancelled", decidedBy: "stopped" });
+ expect(asks()).toHaveLength(2);
+ expect(svc.get(a.id)!.stage.key).toBe("stopped");
+ });
+
+ it("任务会话里的审批:推到会话(带任务名);最后一条消息是它时光回 y 也行;等批准时让出名额", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 1 });
+ const t = start();
+ await flush();
+ const runId = store.listRuns({ taskId: t.id })[0].id;
+ const a = approvals.create({ kind: "approval", botId: "b", conversationId: CONV, sessionId: t.sessionId, tool: "bash", detail: "rm -rf build/", reason: "", taskId: t.id, runId, ttlMs: 12 * 3600_000 });
+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/approval");
+ expect(asks().map((r) => r.body.text)).toEqual([`需批准(任务「GPU 价格调研」):\`rm -rf build/\` — 回复 y ${a.code} / n ${a.code}`]);
+ // 名额:1 个,被等批准的 run 让出来了,第二个任务能开始
+ const u = start("U");
+ await flush();
+ expect(runs(u.id)).toEqual([["launch", "running", ""]]);
+ expect(reply("y")).toEqual({ handled: true, ack: `✅ 已批准 ${a.code}(仅本次)` });
+ expect(store.getApproval(a.id)!.status).toBe("allowed");
+ expect(svc.get(t.id)!.stage.key).toBe("working");
+ });
+
+ it("飞书:提问是带选项按钮的卡片,回复在请求那条消息下", async () => {
+ const fs1 = store.ensureConversation("b", "feishu", "oc_1", "主人");
+ store.addMessage(fs1.id, "user", "后台调研一下 GPU 价格");
+ store.setKV(`reply-to:${fs1.id}`, JSON.stringify({ messageId: "om_req", chatId: "oc_1" }));
+ const f = svc.create({ botId: "b", conversationId: fs1.id, title: "GPU", brief: "" }).task!;
+ await flush();
+ await ask(f.sessionId);
+ const row = asks()[0];
+ expect(row).toMatchObject({ channel: "feishu", kind: "card", replyTo: "om_req", peerId: "oc_1" });
+ expect(JSON.stringify(row.body.card)).toContain("「GPU」想问你");
+ const q = approvals.pendingForTask(f.id)[0];
+ expect(JSON.stringify(row.body.card)).toContain(JSON.stringify({ amb: "question", id: q.id, option: "2" }));
+ });
+
+ it("网页:提问不进出站队列(卡片就在对话里)", async () => {
+ const web = store.ensureConversation("b", "web", "console", "控制台");
+ store.addMessage(web.id, "user", "后台整理发票");
+ const w = svc.create({ botId: "b", conversationId: web.id, title: "发票", brief: "" }).task!;
+ await flush();
+ await ask(w.sessionId);
+ expect(asks()).toEqual([]);
+ expect(approvals.pending(web.id).map((r) => r.taskId)).toEqual([w.id]);
+ });
+
+ it("「需要你」里任务的那一份:失败的(重试、停止),没送到的(知道了);重试开一个 retry run", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => void report(t.sessionId, "failed", "X 云的价格页要登录"));
+ const [item] = svc.attention();
+ expect(item).toMatchObject({ id: `task:${t.id}`, kind: "failed", botName: "小蓝", subject: "GPU 价格调研", status: "失败", line: "X 云的价格页要登录", severity: "err", actions: ["retry", "stop"], channel: "weixin" });
+ expect((await svc.retry(t.id)).how).toBe("resumed");
+ await flush();
+ expect(runs(t.id).at(-1)).toEqual(["retry", "running", ""]);
+ expect(host.prompts.at(-1)!.text).toBe("[用户让你再试一次]\n上次没做完:X 云的价格页要登录");
+ expect(svc.attention()).toEqual([]);
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));
+ store.updateOutbox(store.latestRun(t.id)!.delivery, { status: "gone", error: "窗口关了" });
+ expect(svc.attention().map((x) => [x.kind, x.status, x.line, x.actions])).toEqual([["delivery", "未送达", "好了", ["seen"]]]);
+ expect(svc.seenDelivery(t.id)).toBe(true);
+ expect(svc.attention()).toEqual([]);
+ expect(svc.get(t.id)!.stage.key).toBe("ready");
});
it("这一轮没报告:提醒一次;还没有就失败(没有给出结果)", async () => {
@@ -519,6 +742,10 @@ describe("TaskService(假宿主)", () => {
await flush();
store.insertApproval({ id: "a1", code: "1234", kind: "approval", botId: "b", conversationId: CONV, sessionId: t.sessionId, tool: "bash", detail: "rm -rf build", reason: "", payload: "", createdAt: Date.now(), expiresAt: Date.now() + 60_000 });
expect(svc.get(t.id)!.stage.key).toBe("needs-you/approval");
+ // 子代理里的(会话 id 不同,记着任务)也算
+ store.decideApproval("a1", "allowed", "t");
+ store.insertApproval({ id: "a2", code: "1235", kind: "approval", botId: "b", conversationId: CONV, sessionId: "sub-1", tool: "bash", detail: "rm -rf build", reason: "", payload: "", createdAt: Date.now(), expiresAt: Date.now() + 60_000, taskId: t.id });
+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/approval");
});
it("每个机器人最多 10 个进行中的任务", async () => {
diff --git a/ui/components/tasks.js b/ui/components/tasks.js
index 2c87ee2..b160068 100644
--- a/ui/components/tasks.js
+++ b/ui/components/tasks.js
@@ -55,14 +55,16 @@ export function TaskDetail({ task, onChanged }) {
}, [task.id, working, task.updatedAt]);
const now = Date.now();
const runs = d?.runs || [];
+ // 取到的最新状态(「需要你」里只给了 id)
+ const view = d?.task || task;
const stop = async () => {
setStopping(true);
if (await stopTask(task)) onChanged?.();
setStopping(false);
};
return html`<div class="task-detail">
- ${task.latest && html`<div class="task-line"><span class="t-label">最新进展</span><span class="v selectable">${task.latest}</span></div>`}
- <div class="task-line"><span class="t-label">文件夹</span><span class="v mono selectable">${task.folder}</span></div>
+ ${view.latest && html`<div class="task-line"><span class="t-label">最新进展</span><span class="v selectable">${view.latest}</span></div>`}
+ ${view.folder && html`<div class="task-line"><span class="t-label">文件夹</span><span class="v mono selectable">${view.folder}</span></div>`}
${runs.map(
(r, i) => html`<${ActivityLine} key=${r.id + (r.state === "ended" ? ":e" : "")} label=${runLabel(r, i, now)} live=${r.state === "running" || r.state === "settling"} count=${r.steps}
load=${() => api(`/tasks/${encodeURIComponent(task.id)}/runs/${encodeURIComponent(r.id)}/activity`).then((x) => x.steps)} />`,
diff --git a/ui/css/settings.css b/ui/css/settings.css
index fa1786e..b4a36df 100644
--- a/ui/css/settings.css
+++ b/ui/css/settings.css
@@ -55,6 +55,31 @@
.notif p { font-size: var(--fs-sm); color: var(--fg-2); white-space: pre-wrap; }
.notif time { font-size: var(--fs-2xs); color: var(--faint); }
+/* 需要你(screens/needs-you.js):和设置页同一种页面;一组 .list,一件事一块,块间一条细线。
+ 左边一列是状态点,右边一列从上到下:谁 · 什么 · 状态(可点:展开任务详情)、问题或命令、行内操作 */
+.needs-list .need {
+ display: grid; grid-template-columns: auto minmax(0, 1fr); column-gap: var(--space-2-5); row-gap: var(--space-2);
+ padding: var(--space-3-5) var(--space-4);
+}
+.needs-list .need + .need { border-top: 1px solid var(--line-2); }
+.need > .dot { grid-row: 1; align-self: center; }
+.need > :not(.dot) { grid-column: 2; }
+.need-head { display: flex; align-items: center; gap: var(--space-2); min-width: 0; text-align: left; font-size: var(--fs-sm); color: var(--fg-2); }
+button.need-head { --focus-offset: 2px; border-radius: var(--r-sm); transition: color var(--t-fast); }
+button.need-head:hover, button.need-head:hover .need-who b { color: var(--fg); }
+.need-who { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.need-who b { font-weight: var(--fw-semibold); color: var(--fg); }
+.need-when { flex: none; font-size: var(--fs-xs); color: var(--muted); }
+.need-head .chev { flex: none; color: var(--muted); transition: transform var(--t-fast); }
+.need.open .need-head .chev { transform: rotate(90deg); }
+.need-line { font-size: var(--fs-lg); font-weight: var(--fw-medium); color: var(--fg); line-height: var(--lh-snug); overflow-wrap: anywhere; }
+.need-line.mono { font-family: var(--code); font-size: var(--fs-sm); font-weight: var(--fw-regular); }
+.need-actions { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }
+.need-actions:empty { display: none; }
+.need-reply { display: flex; align-items: center; gap: var(--ctl-gap); }
+.need-reply .field { flex: 1; --field-h: var(--ctl-md); }
+.need-detail .task-detail { margin-top: var(--space-1); }
+
/* 故障排查(screens/troubleshoot.js):状态和检测结果是普通的行;stderr 尾部是组里展开的一块(不再套底);
日志是自己的一块 --well(和代码块同一种面),不描边 */
.ts-state { display: inline-flex; align-items: center; gap: var(--space-1-5); font-size: var(--fs-sm); color: var(--fg-2); white-space: nowrap; }
diff --git a/ui/css/shell.css b/ui/css/shell.css
index e21b062..88b4feb 100644
--- a/ui/css/shell.css
+++ b/ui/css/shell.css
@@ -112,6 +112,20 @@ button.thread:active { background: var(--side-press); }
animation: breathe var(--dur-pulse) var(--ease-in-out) infinite;
}
.thread-skel { flex: 1; display: grid; gap: var(--space-1-5); }
+/* 「需要你」(screens/needs-you.js):机器人列表上方一行,只在有事时出现。黄点在头像那一列的中线上,
+ 文字和机器人名对齐,件数和机器人行的计数在同一条竖线上;选中时和机器人行一样是浮起的玻璃片 */
+.needs-row {
+ --focus-offset: -2px;
+ display: flex; align-items: center; gap: var(--space-3); width: 100%; height: var(--ctl-xl); padding: 0 var(--side-row-px);
+ border-radius: var(--r-xl); text-align: left; font-size: var(--fs-lg); font-weight: var(--fw-medium); color: var(--fg);
+ transition: background var(--t-fast), box-shadow var(--t-fast);
+}
+.needs-row:hover { background: var(--side-hover); }
+.needs-row:active { background: var(--side-press); }
+.needs-row.sel, .needs-row.sel:active { background: var(--side-active); box-shadow: var(--shadow-tile); }
+.needs-row .mark { width: 38px; flex: none; display: grid; place-items: center; } /* 和侧栏头像一样宽 */
+.needs-row .label { flex: 1; min-width: 0; }
+.needs-row .badge.count { --badge-bg: var(--amber-soft); --badge-fg: var(--amber); }
.thread .field { --field-h: 30px; }
/* 侧栏空状态:一句话 + 一个按钮,靠留白成组,不套卡片 */
.side-empty {
diff --git a/ui/design/gallery.js b/ui/design/gallery.js
index caf4a91..56b4b5f 100644
--- a/ui/design/gallery.js
+++ b/ui/design/gallery.js
@@ -4,6 +4,7 @@ import { useContext, useEffect, useLayoutEffect, useRef, useState } from "preact
import { html, Icon, Button, IconButton, Seg, Switch, MenuButton, Menu, Badge, Notice, Skeleton, Spinner, CopyButton, Toasts, DialogHost } from "../components/ui.js";
import { BotAvatar, AvatarPicker, AppMark, BOT_CHARS, CHAR_KEYS, MAIN_CHAR } from "../components/avatar.js";
import { TEMPLATES } from "../screens/new-bot.js";
+import { NeedItem, NeedsRow } from "../screens/needs-you.js";
import { Markdown } from "../components/markdown.js";
import { useStore, toast, saved, failed, confirmSheet } from "../lib/store.js";
import { themeMode, setThemeMode } from "../lib/theme.js";
@@ -371,7 +372,7 @@ function Gallery() {
["原则", [["principles", "分层与约定"]]],
["Token", [["color", "颜色"], ["material", "材质"], ["type", "文字"], ["space", "间距与尺寸"], ["elevation", "投影与层级"], ["motion", "动效"]]],
["组件", [["states", "状态矩阵"], ["buttons", "按钮"], ["inputs", "输入"], ["menus", "菜单与分段"], ["status", "状态与反馈"], ["lists", "列表行"], ["overlays", "对话框与提示"], ["avatars", "头像"]]],
- ["页面模式", [["patterns", "对话"], ["custom", "定制"]]],
+ ["页面模式", [["patterns", "对话"], ["needs", "需要你"], ["custom", "定制"]]],
];
return html`<${Compare.Provider} value=${compare}><div class="gal">
<nav class="gal-nav" aria-label="目录">
@@ -565,6 +566,17 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
<//>
<//>
+ <${Section} id="needs" title="需要你" lead="所有机器人里在等你的事:提问和审批在前,再是失败、没送到、登录。侧栏那一行和托盘角标只在有事时出现;一件一块,操作在行里,点标题行展开任务详情。">
+ <${Demo} title="侧栏" note="NeedsRow:件数为 0 时不画">
+ ${() => html`<div class="gal-strip-in" style="width: 264px; padding: var(--space-2); border-radius: var(--r-pane); background: var(--grain), var(--glass-side)">
+ <${NeedsRow} count=${3} onClick=${() => {}} /><${NeedsRow} count=${2} on onClick=${() => {}} /><${NeedsRow} count=${0} />
+ </div>`}
+ <//>
+ <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 失败 / 登录过期">
+ ${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}
+ <//>
+ <//>
+
<${Section} id="custom" title="定制" lead="不改组件源码:在上下文里覆盖组件变量;需要一块不同主题的区域时,加 data-theme。">
<${Demo} title="覆盖组件变量" code=${`.notice .btn { --btn-h: var(--ctl-sm); --btn-px: var(--space-2-5); } /* 上下文覆盖 */
<button class="btn" style="--btn-bg: var(--green-soft); --btn-fg: var(--green)">…</button>
@@ -586,6 +598,14 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场
</div><//>`;
}
+/** 「需要你」的样例(单人:一个人用自己的机器人) */
+const NEEDS = [
+ { id: "q", kind: "question", botName: "小蓝", subject: "GPU 价格调研", status: "等你回答", line: "报告用中文还是英文?", since: Date.now() - 2 * 60_000, severity: "warn", questions: [{ id: "a", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }] }] },
+ { id: "a", kind: "approval", botName: "小蓝", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", since: Date.now() - 5 * 60_000, severity: "warn" },
+ { id: "f", kind: "failed", botName: "红魔", subject: "季度报告", status: "失败", line: "X 云的价格页要登录,我进不去", since: Date.now() - 40 * 60_000, severity: "err" },
+ { id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },
+];
+
// 等 @import 进来的样式表都加载完再复制伪类规则
if (document.readyState === "complete") mirrorPseudoStates();
else addEventListener("load", mirrorPseudoStates, { once: true });
diff --git a/ui/main.js b/ui/main.js
index f6dfa39..44b6eb3 100644
--- a/ui/main.js
+++ b/ui/main.js
@@ -9,18 +9,20 @@ import { InfoPanel } from "./screens/info-panel.js";
import { SettingsScreen, SettingsSide, TABS } from "./screens/settings.js";
import { BotSettingsScreen } from "./screens/bot-settings.js";
import { NewBotScreen } from "./screens/new-bot.js";
+import { NeedsYouScreen } from "./screens/needs-you.js";
import { BotAvatar, MAIN_CHAR, charOf } from "./components/avatar.js";
import { Onboarding } from "./screens/onboarding.js";
import { api } from "./lib/api.js";
import { setThemeMode } from "./lib/theme.js";
import { failed, toast } from "./lib/store.js";
-// —— 路由:#/chat/<bot> · #/new · #/settings/<tab>[/<row>] · #/bot/<bot>/settings[/<section>] ——
+// —— 路由:#/chat/<bot> · #/new · #/needs · #/settings/<tab>[/<row>] · #/bot/<bot>/settings[/<section>] ——
function parseHash() {
const [kind, a, b, c] = location.hash.replace(/^#\/?/, "").split("/").map((x) => decodeURIComponent(x || ""));
if (kind === "settings") return { view: "settings", tab: TABS.some(([t]) => t === a) ? a : "general", row: b || "" };
if (kind === "bot" && a && b === "settings") return { view: "bot-settings", botId: a, section: c || "" };
if (kind === "new") return { view: "new" };
+ if (kind === "needs") return { view: "needs" };
if (kind === "models") return { view: "settings", tab: "modelflare", row: "" }; // 旧链接
return { view: "chat", botId: kind === "chat" ? a : "" };
}
@@ -134,6 +136,8 @@ function App() {
const [agentWorking, setAgentWorking] = useState({});
// 有后台任务在进行的机器人:侧栏头像也是"工作中"(不算对话在忙,对话页不因此去接进行中的消息)
const [bgWorking, setBgWorking] = useState({});
+ // 「需要你」:件数(侧栏那一行,0 时没有)和每个机器人的件数、最早那件
+ const [needs, setNeeds] = useState({ n: 0, bots: {} });
const [localWorking, setLocalWorking] = useState({});
const [infoOpen, setInfoOpen] = useState(false);
const [palette, setPalette] = useState(false);
@@ -217,11 +221,13 @@ function App() {
const bg = {};
for (const [id, n] of Object.entries(a.background || {})) if (Number(n) > 0) bg[id] = true;
setBgWorking(bg);
+ setNeeds({ n: Number(a.attention) || 0, bots: a.needs || {} });
})
.catch(() => {}),
[],
);
useInterval(pollWorking, 3000, connected);
+ useEffect(() => void (connected && pollWorking()), [connected]);
const working = useMemo(() => {
const m = { ...agentWorking };
for (const src of [bgWorking, localWorking]) for (const [k, v] of Object.entries(src)) if (v) m[k] = true;
@@ -245,6 +251,12 @@ function App() {
go(`/chat/${encodeURIComponent(id || (bot && bot.id) || "")}`);
};
const newBot = () => go("/new");
+ const openNeeds = () => go("/needs");
+ // 「需要你」里的重新扫码:去这个机器人的对话,打开信息面板(渠道在最上面)
+ const relogin = (id) => {
+ openChat(id);
+ setInfoOpen(true);
+ };
useEffect(() => {
if (route.view !== "settings") setSettingsQ("");
}, [route.view]);
@@ -280,6 +292,7 @@ function App() {
if (route.view === "bot-settings" && !typing) openChat(route.botId);
else if (route.view === "new" && !typing && bots && bots.length) openChat();
else if (route.view === "settings" && !typing) openChat();
+ else if (route.view === "needs" && !typing) openChat();
else if (route.view === "chat" && infoOpen && !typing) setInfoOpen(false);
}
};
@@ -290,6 +303,7 @@ function App() {
const commands = [
{ label: "打开设置", kbd: isMac ? "⌘," : "Ctrl+,", keys: "settings preferences", run: () => openSettings() },
{ label: "新建机器人", kbd: isMac ? "⌘N" : "Ctrl+N", keys: "new bot", run: newBot },
+ ...(needs.n > 0 ? [{ label: `需要你(${needs.n})`, keys: "needs attention 需要你 待办", run: openNeeds }] : []),
...(route.view === "chat" ? [{ label: infoOpen ? "关闭信息面板" : "打开信息面板", kbd: isMac ? "⌘⇧I" : "Ctrl+Shift+I", keys: "info panel", run: () => setInfoOpen((v) => !v) }] : []),
...(bot ? [{ label: `「${bot.name}」的设置`, keys: "bot settings", run: () => openBotSettings(bot.id) }] : []),
{ label: "Modelflare 设置", keys: "modelflare key 密钥 模型", run: () => openSettings("modelflare") },
@@ -325,8 +339,8 @@ function App() {
? html`<${SettingsSide} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} onBack=${() => openChat()}
username=${status && status.username} account=${managed ? account : null} />`
: html`<${Sidebar} bots=${bots} botsError=${botsErr} reloadBots=${reloadBots} selectedId=${bot && bot.id} view=${view === "chat" && bots && !bots.length ? "new" : view}
- previews=${previews} pending=${pending} working=${working} username=${status && status.username} account=${managed ? account : null}
- onNew=${newBot} onSelect=${openChat} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} />`}
+ previews=${previews} pending=${pending} working=${working} needs=${needs} username=${status && status.username} account=${managed ? account : null}
+ onNew=${newBot} onSelect=${openChat} onNeeds=${openNeeds} onDeleted=${onDeleted} onOpenSettings=${() => openSettings()} />`}
<main class="main">
${view === "chat" && bot && html`<${ChatScreen} key=${bot.id} bot=${bot} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}
defaultModel=${settings && settings.defaultModel} infoOpen=${infoOpen} onToggleInfo=${() => setInfoOpen((v) => !v)}
@@ -336,6 +350,7 @@ function App() {
${view === "settings" && html`<${SettingsScreen} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} focusRow=${route.row}
mf=${mf} onMfChanged=${reloadMf} onSettings=${setSettings} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}
status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} account=${managed ? account : null} onAccount=${setAccount} />`}
+ ${view === "needs" && html`<${NeedsYouScreen} multiBot=${!!bots && bots.length > 1} onChanged=${pollWorking} onOpenChat=${openChat} onRelogin=${relogin} />`}
${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}
models=${models} modelsError=${modelsError} reloadModels=${reloadModels} defaultModel=${settings && settings.defaultModel}
account=${managed ? account : null} onOpenSettings=${openSettings}
diff --git a/ui/screens/chat.js b/ui/screens/chat.js
index 12016ed..a22a785 100644
--- a/ui/screens/chat.js
+++ b/ui/screens/chat.js
@@ -86,7 +86,7 @@ export function PromptCard({ requestId, fallback }) {
};
if (row.kind === "approval") {
return html`<div class=${`card${pending ? "" : " done"}`}>
- <div class="meta"><span>需要你的批准 · <span class="num">${row.code}</span></span>${!pending && html`<${Badge} s=${row.status} />`}</div>
+ <div class="meta"><span>${row.taskTitle ? `「${row.taskTitle}」` : ""}需要你的批准 · <span class="num">${row.code}</span></span>${!pending && html`<${Badge} s=${row.status} />`}</div>
<div class="q">${row.reason || "机器人想执行一个超出工作区的操作"}</div>
${(row.tool || row.detail) && html`<div class="cmd">${row.tool}${row.detail ? " " + row.detail : ""}</div>`}
${pending && html`<div class="actions">
@@ -123,6 +123,7 @@ export function PromptCard({ requestId, fallback }) {
const sendAll = () =>
submit(qs.map((q, i) => ({ id: q.id, selected: picked[q.id] || [], ...(i === qs.length - 1 && custom.trim() ? { custom: custom.trim() } : {}) })));
return html`<div class=${`card${pending ? "" : " done"}`}>
+ ${row.taskTitle && html`<div class="meta"><span>「${row.taskTitle}」想问你</span></div>`}
${qs.map((q) => html`<div class="q-block">
<div class="q">${q.question}</div>
${q.detail && html`<div class="q-detail">${q.detail}</div>`}
diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.js
new file mode 100644
index 0000000..9940f0c
--- /dev/null
+++ b/ui/screens/needs-you.js
@@ -0,0 +1,108 @@
+// 需要你(3b):所有机器人里在等你的事,一行一件,操作就在行里(回答、批准、重试…);点标题那一行展开详情。
+// 没事时侧栏没有这一行,直接打开这一页只有一句「没有需要你处理的事」。状态是"点 + 文字":黄 = 等你,红 = 失败 / 登录过期。
+import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { html, Icon, Button, Skeleton } from "../components/ui.js";
+import { TaskDetail } from "../components/tasks.js";
+import { api } from "../lib/api.js";
+import { failed } from "../lib/store.js";
+import { fmtAgo } from "../lib/format.js";
+
+/** 侧栏机器人列表上方的「需要你」:只有件数大于 0 时才有 */
+export function NeedsRow({ count, on, onClick }) {
+ if (!count) return null;
+ return html`<button type="button" class=${`needs-row${on ? " sel" : ""}`} aria-current=${on ? "page" : undefined} onClick=${onClick}>
+ <span class="mark" aria-hidden="true"><span class="dot warn"></span></span><span class="label">需要你</span><span class="badge count warn">${count}</span>
+ </button>`;
+}
+
+/** 单选、有选项的一个问题:选项直接是按钮;其余(多选、没有选项、几个问题)写一句话回答 */
+function choices(item) {
+ const qs = item.questions || [];
+ const q = qs.length === 1 ? qs[0] : null;
+ return q && !q.multiSelect && (q.options || []).length ? q.options : null;
+}
+
+/**
+ * 一件事:标题行(机器人 · 任务 · 状态 · 时间;只有一个机器人时不写机器人名)、第二行(问题 / 命令 / 原因)、行内操作。
+ * onAct(action, body) 返回 Promise
+ */
+export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin }) {
+ const [busy, setBusy] = useState("");
+ const [open, setOpen] = useState(false);
+ const [writing, setWriting] = useState(false);
+ const [text, setText] = useState("");
+ const input = useRef(null);
+ const opts = item.kind === "question" ? choices(item) : null;
+ useEffect(() => {
+ if (writing) requestAnimationFrame(() => input.current?.focus());
+ }, [writing]);
+ const act = async (action, body = {}, key = action) => {
+ setBusy(key);
+ try {
+ await onAct(action, body);
+ } catch (e) {
+ failed(e);
+ }
+ setBusy("");
+ };
+ const send = () => text.trim() && act("answer", { text: text.trim() }, "text");
+ // 详情一下就能看到:任务的展开处理过程;网页对话里的去对话
+ const canOpen = !!item.taskId || item.channel === "web";
+ const head = () => (item.taskId ? setOpen((v) => !v) : onOpenChat?.(item.botId));
+ const [lead, ...rest] = [multiBot && item.botName, item.subject, item.status].filter(Boolean);
+ const headIn = html`<span class="need-who"><b>${lead}</b>${rest.map((x) => ` · ${x}`).join("")}</span>
+ <span class="need-when num">${fmtAgo(item.since)}</span>
+ ${item.taskId && html`<${Icon} name="chevRight" size=${12} class="chev" />`}`;
+ return html`<div class=${`need${open ? " open" : ""}`}>
+ <span class=${`dot ${item.severity === "err" ? "err" : "warn"}`} aria-hidden="true"></span>
+ ${canOpen
+ ? html`<button type="button" class="need-head" aria-expanded=${item.taskId ? open : undefined} title=${item.taskId ? (open ? "收起" : "查看任务") : "打开对话"} onClick=${head}>${headIn}</button>`
+ : html`<div class="need-head">${headIn}</div>`}
+ ${item.line && html`<div class=${`need-line selectable${item.kind === "approval" ? " mono" : ""}`}>${item.line}</div>`}
+ <div class="need-actions">
+ ${opts && opts.map((o, i) => html`<${Button} loading=${busy === `o${i}`} disabled=${!!busy} onClick=${() => act("answer", { text: String(i + 1) }, `o${i}`)}>${o.label}<//>`)}
+ ${item.kind === "question" && !writing && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => setWriting(true)}>回复…</button>`}
+ ${item.kind === "approval" && html`<${Button} variant="primary" loading=${busy === "approve"} disabled=${!!busy} onClick=${() => act("approve")}>批准一次<//>
+ <${Button} loading=${busy === "deny"} disabled=${!!busy} onClick=${() => act("deny")}>拒绝<//>`}
+ ${item.kind === "failed" && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>重试<//>
+ <button type="button" class="text danger" disabled=${!!busy} onClick=${() => act("stop")}>停止</button>`}
+ ${item.kind === "delivery" && html`<${Button} loading=${busy === "seen"} disabled=${!!busy} onClick=${() => act("seen")}>知道了<//>`}
+ ${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>重新扫码<//>`}
+ </div>
+ ${writing && html`<div class="need-reply">
+ <input ref=${input} class="field" placeholder="你的回答" value=${text} disabled=${busy === "text"}
+ onInput=${(e) => setText(e.target.value)} onKeyDown=${(e) => {
+ if (e.key === "Enter" && !e.isComposing) send();
+ if (e.key === "Escape") (e.stopPropagation(), setWriting(false));
+ }} />
+ <${Button} variant="primary" loading=${busy === "text"} disabled=${!text.trim()} onClick=${send}>发送<//>
+ </div>`}
+ ${open && item.taskId && html`<div class="need-detail"><${TaskDetail} task=${{ id: item.taskId, title: item.subject, stage: { group: "needs" } }} /></div>`}
+ </div>`;
+}
+
+/** 主区的「需要你」:每 3 秒看一次;处理掉的那件立刻消失(onChanged 让侧栏的件数也跟上) */
+export function NeedsYouScreen({ multiBot, onChanged, onOpenChat, onRelogin }) {
+ const [items, setItems] = useState(null);
+ const load = useCallback(() => api("/attention").then((d) => setItems(d.items || [])).catch(() => setItems((v) => v || [])), []);
+ useEffect(() => {
+ load();
+ const t = setInterval(() => document.visibilityState === "visible" && load(), 3000);
+ return () => clearInterval(t);
+ }, [load]);
+ const onAct = (it) => async (action, body) => {
+ const d = await api(`/attention/${encodeURIComponent(it.id)}/${action}`, { method: "POST", body });
+ setItems(d.items || []);
+ onChanged?.();
+ };
+ return html`<div class="settings needs view" data-screen="needs">
+ <div class="set-head"><h1 class="set-title">需要你</h1></div>
+ <div class="set-body">
+ ${!items && html`<div class="list needs-list"><div class="need"><${Skeleton} w="50%" /><${Skeleton} w="70%" /></div></div>`}
+ ${items && !items.length && html`<p class="set-none">没有需要你处理的事</p>`}
+ ${items && items.length > 0 && html`<div class="list needs-list">
+ ${items.map((it) => html`<${NeedItem} key=${it.id} item=${it} multiBot=${multiBot} onAct=${onAct(it)} onOpenChat=${onOpenChat} onRelogin=${onRelogin} />`)}
+ </div>`}
+ </div>
+ </div>`;
+}
diff --git a/ui/screens/sidebar.js b/ui/screens/sidebar.js
index dfbd975..a300b2e 100644
--- a/ui/screens/sidebar.js
+++ b/ui/screens/sidebar.js
@@ -1,5 +1,6 @@
// 侧栏 280(参考 Grok Bot):顶部只有新建按钮,常驻搜索框,机器人行(头像 + 名称 + 时间 + 一行预览),左下角账户(打开设置)。
// 新建在主区的新建页(screens/new-bot.js);新建页打开时列表顶部有一行占位的"新机器人"。
+// 有事在等你时,机器人列表上方多一行「需要你 N」(没事时没有这一行);机器人行的第二行换成最早那件事。
import { useEffect, useRef, useState } from "preact/hooks";
import { html, Icon, IconButton, Menu, Skeleton } from "../components/ui.js";
import { BotAvatar } from "../components/avatar.js";
@@ -7,6 +8,7 @@ import { api } from "../lib/api.js";
import { confirmSheet, failed, toast } from "../lib/store.js";
import { fmtAgo } from "../lib/format.js";
import { MF_TOPUP, usd } from "../lib/links.js";
+import { NeedsRow } from "./needs-you.js";
/** 左下角账户:头像字母 + 名称(登录后是 Modelflare 账户名)与余额 + 齿轮,点开设置 */
export function AccountButton({ username, account, on, onClick }) {
@@ -27,7 +29,7 @@ function LowBalance({ account }) {
</a>`;
}
-export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, username, account, onNew, onSelect, onDeleted, onOpenSettings }) {
+export function Sidebar({ bots, botsError, reloadBots, selectedId, view, previews, pending, working, needs = { n: 0, bots: {} }, username, account, onNew, onSelect, onNeeds, onDeleted, onOpenSettings }) {
const [q, setQ] = useState("");
const [ctx, setCtx] = useState(null); // { bot, x, y }
const [renaming, setRenaming] = useState("");
@@ -74,6 +76,7 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, preview
onKeyDown=${(e) => e.key === "Escape" && q && (e.stopPropagation(), setQ(""))} />
</label>
<nav class="side-list" aria-label="机器人列表">
+ <${NeedsRow} count=${needs.n} on=${view === "needs"} onClick=${onNeeds} />
${view === "new" && html`<div class="thread sel" aria-current="page"><${BotAvatar} neutral size=${38} />
<span class="body"><span class="line"><span class="title">新机器人</span></span><span class="line"><span class="snip">正在创建…</span></span></span></div>`}
${botsError && html`<div class="side-empty"><span>无法读取机器人列表</span><button type="button" class="btn" onClick=${reloadBots}>重试</button></div>`}
@@ -82,7 +85,9 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, preview
${bots && needle && !list.length && html`<p class="hint">没有匹配的机器人</p>`}
${list.map((b) => {
const sel = (view === "chat" || view === "bot-settings") && b.id === selectedId;
- const n = pending[b.id] || 0;
+ // 等你的:「需要你」里这个机器人的件数和最早那件(没有时退回待审批数)
+ const nd = needs.bots[b.id];
+ const n = nd?.n || pending[b.id] || 0;
if (renaming === b.id)
return html`<div class="thread sel" key=${b.id}><${BotAvatar} bot=${b} size=${38} />
<input class="field" value=${renameText} aria-label="新名称" ref=${renameRef}
@@ -94,7 +99,7 @@ export function Sidebar({ bots, botsError, reloadBots, selectedId, view, preview
<span class="avatar-wrap"><${BotAvatar} bot=${b} size=${38} state=${n > 0 ? "waiting" : working[b.id] ? "working" : "idle"} />${working[b.id] && html`<span class="working-dot" title="工作中"></span>`}</span>
<span class="body">
<span class="line"><span class="title">${b.name}</span>${pv?.at && html`<span class="when num">${fmtAgo(pv.at)}</span>`}</span>
- <span class="line"><span class="snip">${working[b.id] ? "正在工作…" : pv?.text || "还没有对话"}</span>${n > 0 && html`<span class="badge count" title=${`${n} 个待审批`}>${n}</span>`}</span>
+ <span class="line"><span class="snip">${nd?.line || (working[b.id] ? "正在工作…" : pv?.text || "还没有对话")}</span>${n > 0 && html`<span class="badge count" title=${`${n} 件事需要你`}>${n}</span>`}</span>
</span>
</button>`;
})}