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.

Tasks: follow-ups reach the task directly

Marlaecde641ffbcb
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.md
index 227649f..a2757b9 100644
--- a/docs/design/background-tasks-and-proactive.md
+++ b/docs/design/background-tasks-and-proactive.md
@@ -184,7 +184,9 @@ A person's message reaches a task only by explicit reference:
- **WeChat:** a quote (引用) of the task's message. We store the sent text in the outbox and match the quote against it.
- **Any channel:** the chat agent calls `task_message({ task, text })` when the user names the task ("GPU 那个改成英文").
-A follow-up while the task is working is **steered** into it (P1) and lands at its next step. A follow-up to a done task resumes it under the same task. Quoting a task's message also adds the task's latest Report to the chat turn, so "详细说说" is answered by the chat agent from the report without waking the task.
+A follow-up while the task is working is **steered** into it (P1) and lands at its next step. A follow-up to a done or failed task resumes it under the same task. A stopped task can't be continued.
+
+As built: a WeChat quote of a task's pushed result or failure line, or a Feishu message in the reply chain of the task's request message (results are replied under it), goes straight to the task with a one-line acknowledgement (「收到,「GPU 价格调研」继续。」). It doesn't wait for the chat agent to notice. A quote of a digest that names several tasks stays ordinary chat. A pushed result ends with 「引用这条消息可以继续问。」 on WeChat and 「回复这条消息可以继续问。」 on Feishu, and still fits 300 characters. So "详细说说" on a quoted result is answered by the task itself.
### Concurrency and the reserved human lane
diff --git a/src/channels/feishu/card.ts b/src/channels/feishu/card.ts
index f8036e0..7018646 100644
--- a/src/channels/feishu/card.ts
+++ b/src/channels/feishu/card.ts
@@ -1,7 +1,7 @@
import crypto from "node:crypto";
import type { OutboundOp, ReplySession } from "../../core/types.js";
import { splitText } from "../../core/types.js";
-import { Gone, ReplyIds, stableId, type Outbox } from "../../core/outbox.js";
+import { Gone, ReplyIds, sentText, stableId, type Outbox } from "../../core/outbox.js";
import type { OutboxBody, OutboxKind, OutboxRow } from "../../store/db.js";
import { CARD_ELEMENT_ID, actionCardSpec, type FeishuTransport } from "./transport.js";
import { logger } from "../../log.js";
@@ -35,7 +35,7 @@ export async function deliverFeishu(transport: FeishuTransport, row: OutboxRow,
};
switch (row.kind) {
case "text": {
- const text = b.text ?? "";
+ const text = sentText(b);
if (b.cardId && row.attempts === 0 && row.progress === 0) {
let shown = !!b.shown;
const seq = b.cardSeq ?? 1;
diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.ts
index 4e32656..246831f 100644
--- a/src/channels/feishu/channel.ts
+++ b/src/channels/feishu/channel.ts
@@ -114,6 +114,7 @@ export class FeishuChannel {
parts: feishuParts(ev),
mentions: ev.mentions.map((m) => m.openId ?? m.key),
replyHandle: { messageId: ev.messageId, chatId: ev.chatId },
+ ...(ev.rootId || ev.parentId ? { thread: { rootId: ev.rootId, parentId: ev.parentId } } : {}),
receivedAt: Date.now(),
};
// 人在:排着的主动消息(免打扰、每天上限)不用再等,排在这次的回复前面
diff --git a/src/channels/feishu/transport.ts b/src/channels/feishu/transport.ts
index b82853d..d507949 100644
--- a/src/channels/feishu/transport.ts
+++ b/src/channels/feishu/transport.ts
@@ -21,6 +21,27 @@ export interface FeishuMessageEvent {
senderOpenId: string;
mentions: Array<{ key: string; name?: string; openId?: string }>;
createTime: number;
+ /** 回复(或话题里的消息):回复链的根消息、直接回复的那条(message_id);不是回复时没有 */
+ rootId?: string;
+ parentId?: string;
+}
+
+/** im.message.receive_v1 的事件 → FeishuMessageEvent */
+export function messageEventOf(data: any): FeishuMessageEvent {
+ const m = data?.message ?? {};
+ return {
+ eventId: data?.event_id,
+ messageId: m.message_id,
+ chatId: m.chat_id,
+ chatType: m.chat_type,
+ messageType: m.message_type,
+ content: m.content ?? "{}",
+ senderOpenId: data?.sender?.sender_id?.open_id ?? "",
+ mentions: (m.mentions ?? []).map((x: any) => ({ key: x.key, name: x.name, openId: x.id?.open_id })),
+ createTime: Number(m.create_time ?? Date.now()),
+ ...(m.root_id ? { rootId: String(m.root_id) } : {}),
+ ...(m.parent_id ? { parentId: String(m.parent_id) } : {}),
+ };
}
/**
@@ -147,18 +168,7 @@ export class LarkTransport implements FeishuTransport {
"im.message.receive_v1": async (data: any) => {
// 3 秒规则:立即返回,业务异步处理(onMessage 内只入队)
try {
- const m = data.message ?? {};
- onMessage({
- eventId: data.event_id,
- messageId: m.message_id,
- chatId: m.chat_id,
- chatType: m.chat_type,
- messageType: m.message_type,
- content: m.content ?? "{}",
- senderOpenId: data.sender?.sender_id?.open_id ?? "",
- mentions: (m.mentions ?? []).map((x: any) => ({ key: x.key, name: x.name, openId: x.id?.open_id })),
- createTime: Number(m.create_time ?? Date.now()),
- });
+ onMessage(messageEventOf(data));
} catch (e) {
this.log.warn("bad event", { message: (e as Error).message });
}
diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.ts
index 4317d5f..5bf5fa3 100644
--- a/src/channels/weixin/channel.ts
+++ b/src/channels/weixin/channel.ts
@@ -4,7 +4,7 @@ import { splitText } from "../../core/types.js";
import { Dedup, KeyedQueue } from "../../core/queue.js";
import type { BotRuntime } from "../../core/runtime.js";
import type { OutboxBody, OutboxKind, OutboxRow, Store } from "../../store/db.js";
-import { Gone, Held, Later, Outbox, ReplyIds, stableId, type HeldGroup } from "../../core/outbox.js";
+import { Gone, Held, Later, Outbox, ReplyIds, sentText, stableId, type HeldGroup } from "../../core/outbox.js";
import { IlinkClient, MessageItemType, MessageType, WeixinApiError, hasDownloadableMedia, type InboundMedia, type MessageItem, type WeixinMessage } from "./api.js";
import { StreamingMarkdownFilter } from "./markdown-filter.js";
import { WeixinQuota } from "./quota.js";
@@ -170,7 +170,7 @@ export async function deliverWeixin(client: IlinkClient, quota: WeixinQuota, row
quota.tryConsume(user);
return;
}
- const text = row.body.text ?? "";
+ const text = sentText(row.body);
const chunks = splitText(row.body.raw ? text.trim() : filterMarkdown(text), WEIXIN_CAPS.maxTextLength);
let rest = chunks.slice(row.progress);
const budget = budgetOf(quota, user, row);
diff --git a/src/core/delivery.ts b/src/core/delivery.ts
index 1c6788e..6651dae 100644
--- a/src/core/delivery.ts
+++ b/src/core/delivery.ts
@@ -62,6 +62,8 @@ export interface PushInput {
subject: string;
/** 一句话(设计里的消息样式:一行,细节按需) */
text: string;
+ /** 单独发出去时接在后面的提示(任务结果:引用 / 回复这条消息可以继续问);合成摘要时不带 */
+ hint?: string;
/** 跟在后面的文件 */
files?: string[];
/** 飞书:回复在哪条消息下;kind = notice 时直接发到会话 */
@@ -234,7 +236,7 @@ export class Delivery {
const { due, reason } = this.plan(peer, p.purpose, !!p.anytime, now);
const common = { botId: p.botId, channel: p.channel, peerId: p.peerId, replyTo: p.replyTo ?? "", purpose: p.purpose, subject: clip(oneLine(p.subject), 60), ref: p.ref ?? "", due, reason };
const flag = p.anytime ? { anytime: true } : {};
- const extra = { ...(p.card ? { card: p.card } : {}), ...(p.raw ? { raw: true } : {}) };
+ const extra = { ...(p.card ? { card: p.card } : {}), ...(p.raw ? { raw: true } : {}), ...(p.hint ? { hint: p.hint } : {}) };
void this.o.outbox.send({ ...common, id: p.id, kind: p.card ? "card" : (p.kind ?? "text"), body: { text: p.text, ...extra, ...flag } });
(p.files ?? []).forEach((f, i) => void this.o.outbox.send({ ...common, id: `${p.id}:file:${i}`, kind: "file", body: { path: f, name: path.basename(f), ...flag } }));
if (due > now) log.info("proactive message scheduled", { id: p.id, channel: p.channel, reason, inMin: Math.round((due - now) / 60_000) });
diff --git a/src/core/outbox.ts b/src/core/outbox.ts
index 76f615a..4272f2f 100644
--- a/src/core/outbox.ts
+++ b/src/core/outbox.ts
@@ -90,6 +90,17 @@ export function stableId(id: string, part: number, len = 32): string {
return crypto.createHash("sha256").update(`${id}#${part}`).digest("hex").slice(0, len);
}
+/** 发出去的文字:text 后面接上 hint(正文没有句末标点时补一个,中文「。」,英文「. 」) */
+export function sentText(b: Pick<OutboxBody, "text" | "hint">): string {
+ const text = b.text ?? "";
+ if (!b.hint) return text;
+ const head = text.trimEnd();
+ const cjk = /^[\u2e80-\u9fff\uff00-\uffef]/.test(b.hint);
+ if (!head) return b.hint;
+ if (/[。!?!?.…]$/.test(head)) return head + (cjk ? "" : " ") + b.hint;
+ return head + (cjk ? "。" : ". ") + b.hint;
+}
+
/**
* 一次回复里每条出站消息 id 的最后一段:最终回复按"第几个"(同一条入站只有一个最终回复,平台重复投递、模型答得不一样时也不会再发一遍),
* 其余按内容(不同的消息不会因为先后顺序不同撞上同一个 id 而被吞掉)。
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index 24b5375..4e13ba6 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -449,6 +449,9 @@ export class BotRuntime {
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;
+ // 引用了后台任务推来的结果或失败那句(微信),或发在任务请求那条消息的回复链里(飞书):直接交给那个任务,不经聊天代理
+ const follow = tasks?.followUp(convId, { text: quote ? plain : text, ...(quote ? { quote } : {}), ...ev.thread });
+ if (follow?.handled) return follow;
// 前一条还在处理:能并入进行中的代理回合时由 handle 并入并回一句;不能时说一声这条排在后面、怎么中止(每个回合只说一次),消息照常入队
const cur = agent.turnsInProgress.get(convId);
if (cur && !cur.queuedNotice && !agent.canSteer(convId)) {
diff --git a/src/core/types.ts b/src/core/types.ts
index efc52fe..04f47ed 100644
--- a/src/core/types.ts
+++ b/src/core/types.ts
@@ -38,6 +38,8 @@ export interface InboundEvent {
mentions?: string[];
/** 回复所需的平台句柄:飞书 message_id / 微信 context_token 等 */
replyHandle: Record<string, string>;
+ /** 飞书:这条是回复(或话题里的消息)时,回复链的根消息和直接回复的那条(message_id) */
+ thread?: { rootId?: string; parentId?: string };
receivedAt: number;
}
diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.ts
index 832b8b8..c3f5447 100644
--- a/src/i18n/messages/tasks.ts
+++ b/src/i18n/messages/tasks.ts
@@ -27,6 +27,8 @@ export const zh = {
approvalTitle: "需批准(任务「{title}」)",
questionTitle: "「{title}」想问你",
continuing: "收到,「{title}」继续。",
+ hintQuote: "引用这条消息可以继续问。",
+ hintReply: "回复这条消息可以继续问。",
none: "没有后台任务。",
latestSuffix: ":{text}",
listHead: "后台任务:",
@@ -67,6 +69,8 @@ export const en: Catalog<typeof zh> = {
approvalTitle: "Approval needed (task \"{title}\")",
questionTitle: "\"{title}\" has a question",
continuing: "Got it, \"{title}\" carries on.",
+ hintQuote: "Quote this message to follow up.",
+ hintReply: "Reply to this message to follow up.",
none: "No background tasks.",
latestSuffix: ": {text}",
listHead: "Background tasks:",
diff --git a/src/store/db.ts b/src/store/db.ts
index 45b8dc9..081e9dd 100644
--- a/src/store/db.ts
+++ b/src/store/db.ts
@@ -142,6 +142,8 @@ export type OutboxPurpose = "" | "result" | "failure" | "rule" | "reminder" | "q
/** 出站消息的内容:文本(最终回复、提示、通知)、文件、带按钮的卡片(飞书审批) */
export interface OutboxBody {
text?: string;
+ /** 单独发出去时接在 text 后面的一句(任务结果的「引用这条消息可以继续问。」);合成摘要、「你不在时」时不带 */
+ hint?: string;
/** 微信:原样发送,不过 Markdown 过滤(审批提示里的反引号要保留) */
raw?: boolean;
path?: string;
diff --git a/src/tasks/service.ts b/src/tasks/service.ts
index 9867208..b7be55d 100644
--- a/src/tasks/service.ts
+++ b/src/tasks/service.ts
@@ -25,6 +25,7 @@ import crypto from "node:crypto";
import fs from "node:fs";
import path from "node:path";
import { needsPerson, type Delivery } from "../core/delivery.js";
+import { sentText } 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";
@@ -817,16 +818,20 @@ export class TaskService {
return;
}
const msg = oneLine(report?.message ?? "");
- const text = outcome === "done" ? clip(msg, MESSAGE_MAX) || tr("tasks.done", { title: task.title }) : tr("tasks.notDone", { title: task.title, why: clip(msg || error || tr("tasks.noResult"), MESSAGE_MAX) });
+ const pushed = (conv.channel === "weixin" || conv.channel === "feishu") && !!this.o.delivery;
+ // 结果后面那句「引用这条消息可以继续问」(失败那句本来就说了怎么办):微信总有;飞书只在结果回复在请求那条消息下时有
+ // (回复链对得上才认得出是哪个任务,见 followUp)。连它一起不超过 300 字
+ const hint = pushed && outcome === "done" ? (conv.channel === "weixin" ? tr("tasks.hintQuote") : task.originRef ? tr("tasks.hintReply") : "") : "";
+ const text = outcome === "done" ? clip(msg, MESSAGE_MAX - (hint ? hint.length + 2 : 0)) || tr("tasks.done", { title: task.title }) : tr("tasks.notDone", { title: task.title, why: clip(msg || error || tr("tasks.noResult"), MESSAGE_MAX) });
const files = outcome === "done" ? this.files(task, report?.files ?? []) : [];
- if ((conv.channel === "weixin" || conv.channel === "feishu") && this.o.delivery) this.post(conv, task, id, purpose, text, files);
+ if (pushed) this.post(conv, task, id, purpose, text, files, hint);
this.store.addMessage(conv.id, "assistant", files.length && conv.channel === "web" ? `${text}\n\n${files.map((f) => `- ${path.relative(this.o.host.workspace(task.botId), f)}`).join("\n")}` : text);
this.store.updateRun(runId, { delivery: id });
this.note(conv.id, outcome === "done" ? `[后台任务「${task.title}」已完成,已把结果发给用户] ${text}` : `[后台任务「${task.title}」失败了,已告诉用户] ${text}`);
}
/** 微信、飞书:按主动消息的规则写进出站队列(同步落库;渠道没上线时等它上线) */
- private post(conv: Conversation, task: TaskRow, id: string, purpose: "result" | "failure", text: string, files: string[]): void {
+ private post(conv: Conversation, task: TaskRow, id: string, purpose: "result" | "failure", text: string, files: string[], hint: string): void {
const channel = conv.channel as "weixin" | "feishu";
const replyTo = channel === "feishu" ? task.originRef || replyHandle(this.store, conv.id).messageId || "" : "";
const notice = channel === "feishu" && !replyTo;
@@ -838,6 +843,7 @@ export class TaskService {
purpose,
subject: task.title,
text,
+ ...(hint ? { hint } : {}),
files: notice ? [] : files,
replyTo,
kind: notice ? "notice" : "text",
@@ -1047,6 +1053,51 @@ export class TaskService {
};
}
+ /**
+ * 渠道里的一条消息是不是对某个任务的追加(设计 3「Follow-ups and routing」):微信引用了推出去的结果或失败那句,
+ * 飞书发在请求那条消息的回复链里(结果就回复在它下面)。是就直接交给任务(同 task_message:在跑就并进去,
+ * 做完了、失败了在同一个任务里接着做),回一句收到,不经聊天代理;停了的照旧说不能再追加。
+ * 对不上、对上不止一个(引用了合成的摘要)就是普通聊天。runtime.interceptReply 在任务的提问、审批之后调用。
+ */
+ followUp(conversationId: string, m: { text: string; quote?: string; rootId?: string; parentId?: string }): { handled: boolean; ack?: string } {
+ const text = m.text.trim();
+ if (!text || text.startsWith("/")) return { handled: false };
+ const task = this.followTarget(conversationId, m);
+ if (!task) return { handled: false };
+ if (task.endReason === "stopped") return { handled: true, ack: tr("tasks.stoppedNoFollowup", { title: task.title }) };
+ log.info("a follow-up goes straight to its background task", { task: task.id, by: m.quote ? "quote" : "thread" });
+ void this.message(task.id, text).catch((e) => log.warn("follow-up to a background task failed", { task: task.id, message: (e as Error).message.slice(0, 200) }));
+ return { handled: true, ack: tr("tasks.continuing", { title: task.title }) };
+ }
+
+ /**
+ * 引用的是哪个任务推出去的结果或失败那句(按发出去的原文比,取最像的,见 quoteScore);飞书按回复链的根、直接回复的那条比请求那条消息。
+ * 对上不止一个(引用了合成的摘要、一条消息开了两个任务)就不算
+ */
+ private followTarget(conversationId: string, m: { quote?: string; rootId?: string; parentId?: string }): TaskRow | undefined {
+ const tasks = this.store.listTasks({ conversationId, limit: 50 });
+ let hits: TaskRow[] = [];
+ if (m.quote) {
+ const quote = m.quote;
+ const score = (t: TaskRow) =>
+ Math.max(
+ 0,
+ ...this.store.listRuns({ taskId: t.id }).map((r) => {
+ if (!/^task:[^:]+:(result|failure):/.test(r.delivery) || r.delivery.endsWith(":dropped")) return 0;
+ const row = this.store.getOutbox(r.delivery);
+ return row ? quoteScore(sentText(row.body), row.body.text ?? "", quote) : 0;
+ }),
+ );
+ const scored = tasks.map((t) => ({ t, s: score(t) }));
+ const best = Math.max(0, ...scored.map((x) => x.s));
+ hits = best ? scored.filter((x) => x.s === best).map((x) => x.t) : [];
+ } else {
+ const refs = [m.rootId, m.parentId].filter(Boolean);
+ if (refs.length) hits = tasks.filter((t) => !!t.originRef && refs.includes(t.originRef));
+ }
+ return hits.length === 1 ? hits[0] : undefined;
+ }
+
/** "需要你"里任务那一份:失败、预算用完(提问和审批由审批中心那一份给,没送到的由出站队列那一份给:core/delivery.ts) */
attention(): AttentionItem[] {
const out: AttentionItem[] = [];
@@ -1890,18 +1941,36 @@ function questionOf(b: any): TaskReport["question"] | undefined {
return { question: clip(text, QUESTION_MAX), ...(options.length ? { options } : {}), ...(multi && options.length > 1 ? { multiSelect: true } : {}) };
}
+/** 比引用时去掉空白、记号和末尾的省略号(引用可能被截短) */
+const normQuote = (s: string) => s.replace(/\s+/g, "").replace(/[❓⚠\uFE0F]/g, "").replace(/(…|\.\.\.)+$/, "");
+/** 前面可能带着发送者的名字("小蓝:") */
+const unnamed = (q: string) => q.replace(/^[^::「]{1,24}[::]/, "");
+
/** 引用的是不是推出去的那一条:去掉空白和记号再比;引用可能被截短(末尾省略号)、前面带名字 */
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);
+ const q = normQuote(quote);
if (!q) return false;
- const s = norm(sent);
- const ask = norm(question);
- // 前面可能带着发送者的名字("小蓝:")
- const bare = q.replace(/^[^::「]{1,24}[::]/, "");
+ const s = normQuote(sent);
+ const ask = normQuote(question);
+ const bare = unnamed(q);
return (!!s && (s === q || [q, bare].some((x) => x.length >= 6 && s.includes(x)))) || (ask.length >= 2 && q.includes(ask));
}
+/**
+ * 引用和推出去的结果(或失败那句)有多像,几个任务都对得上时取最像的:3 = 就是它(前面可能带名字);
+ * 2 = 引用里有整句结果(「你不在时」合成的一条),或是它被截短;1 = 去掉开头像名字的一段才对得上("RESULT:…" 这种开头也会被当成名字);0 = 不是
+ */
+export function quoteScore(sent: string, text: string, quote: string): number {
+ const q = normQuote(quote);
+ const s = normQuote(sent);
+ if (!q || !s) return 0;
+ const a = normQuote(text);
+ const bare = unnamed(q);
+ if (s === q || s === bare) return 3;
+ if ((a.length >= 2 && q.includes(a)) || (q.length >= 6 && s.includes(q))) return 2;
+ return bare.length >= 6 && s.includes(bare) ? 1 : 0;
+}
+
function parseSteps(json: string | undefined): ActivityStep[] {
if (!json) return [];
try {
diff --git a/test/delivery.e2e.test.ts b/test/delivery.e2e.test.ts
index 2a9a49a..02d1194 100644
--- a/test/delivery.e2e.test.ts
+++ b/test/delivery.e2e.test.ts
@@ -102,7 +102,8 @@ describe("退出演示:免打扰与微信窗口", () => {
expect(to(OWNER, from)).toEqual([]);
await clock("2026-11-07T08:00");
await until(() => to(OWNER, from).length >= 1, 5000);
- expect(to(OWNER, from)).toEqual(["GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。"]);
+ // 单独发出去的结果带着设计里的那句提示;「你不在时」和摘要里不带(见下面两个)
+ expect(to(OWNER, from)).toEqual(["GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。引用这条消息可以继续问。"]);
await clock("2026-11-07T09:00");
expect(to(OWNER, from)).toHaveLength(1);
});
diff --git a/test/helpers.ts b/test/helpers.ts
index 1760389..ec60fe3 100644
--- a/test/helpers.ts
+++ b/test/helpers.ts
@@ -271,6 +271,8 @@ export function feishuEvent(text: string, opts: Partial<FeishuMessageEvent> = {}
senderOpenId: opts.senderOpenId ?? "ou_user1",
mentions: opts.mentions ?? [],
createTime: Date.now(),
+ ...(opts.rootId ? { rootId: opts.rootId } : {}),
+ ...(opts.parentId ? { parentId: opts.parentId } : {}),
};
}
diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.ts
index 2c680fd..7990490 100644
--- a/test/tasks.integration.test.ts
+++ b/test/tasks.integration.test.ts
@@ -65,6 +65,9 @@ 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}`);
+ // 用户引用结果追加的一句(不经聊天代理,直接到任务)
+ const more = /^\[用户追加\]\n(.+)$/.exec(user);
+ if (more) return report(`FOLLOWED-${tag}:${more[1]}`);
// ASK:先问用户(needs_you),回答作为下一条输入回来,再按回答做完
if (tag.startsWith("ASK")) {
const ans = /^\[用户回答了你的问题\][\s\S]*回答:(.+)$/.exec(user);
@@ -194,6 +197,26 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
expect(host.restarts).toBe(0);
}, 180_000);
+ it("follow-ups reach the task directly: quoting its pushed result on WeChat resumes the same task without a chat turn", async () => {
+ const t = await research("FOLLOWQ");
+ await waitFor(() => sentTo("RESULT-FOLLOWQ").length === 1);
+ const result = sentTo("RESULT-FOLLOWQ")[0].text;
+ expect(result).toBe("RESULT-FOLLOWQ:调研好了,结论在 notes.md。引用这条消息可以继续问。");
+ await waitFor(() => stage("FOLLOWQ") === "ready");
+ const chats = calls.filter((c) => !c.task).length;
+ ilink.pushItems(OWNER, [{ type: 1, text_item: { text: "加上 H100" }, ref_msg: { title: "", message_item: { type: 1, text_item: { text: result } } } }]);
+ await waitFor(() => sentTo("收到,「调研 FOLLOWQ」继续。").length === 1);
+ await waitFor(() => sentTo("FOLLOWED-FOLLOWQ").length === 1);
+ expect(sentTo("FOLLOWED-FOLLOWQ")[0].text).toBe("FOLLOWED-FOLLOWQ:加上 H100。引用这条消息可以继续问。");
+ await waitFor(() => stage("FOLLOWQ") === "ready");
+ // 聊天代理没有被叫醒;同一个任务、同一个会话接着做
+ expect(calls.filter((c) => !c.task).length).toBe(chats);
+ expect((await api(`/tasks/${t.id}`)).runs.map((r: any) => [r.cause, r.outcome])).toEqual([
+ ["launch", "done"],
+ ["followup", "done"],
+ ]);
+ }, 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");
@@ -212,7 +235,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
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:用中文写好了。");
+ 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)
@@ -244,7 +267,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
// 引用那条提问回答(自己写的回答)
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("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);
@@ -263,7 +286,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou
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>>");
+ expect(sentTo("APPROVED-APPR1")[0].text).toBe("APPROVED-APPR1<<ran>>。引用这条消息可以继续问。");
await waitFor(() => stage("APPR1") === "ready");
expect((await api("/attention")).items).toEqual([]);
}, 180_000);
diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.ts
index 5739830..116480e 100644
--- a/test/tasks.unit.test.ts
+++ b/test/tasks.unit.test.ts
@@ -15,9 +15,15 @@ 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";
-import { Outbox } from "../src/core/outbox.js";
+import { Outbox, sentText } from "../src/core/outbox.js";
import { Delivery } from "../src/core/delivery.js";
import { Store } from "../src/store/db.js";
+import { BotRuntime } from "../src/core/runtime.js";
+import { KeyedQueue } from "../src/core/queue.js";
+import { FeishuChannel } from "../src/channels/feishu/channel.js";
+import { messageEventOf } from "../src/channels/feishu/transport.js";
+import type { AgentManager } from "../src/agent/manager.js";
+import { FakeFeishu, feishuEvent } from "./helpers.js";
const flush = async (n = 5) => {
for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r));
@@ -580,6 +586,100 @@ describe("TaskService(假宿主)", () => {
expect(store.getTask(t.id)!.endedAt).toBe(0);
});
+ it("追加不经聊天代理(微信):引用推出去的结果(带「引用这条消息可以继续问。」)或失败那句就交给任务,在同一任务里接着做;对不上的是普通聊天;停了的照旧", async () => {
+ const t = start();
+ await flush();
+ await turn(t.sessionId, () => void report(t.sessionId, "done", "GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800"));
+ const row = store.listOutbox({ limit: 50 })[0];
+ expect(row.body).toMatchObject({ text: "GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800", hint: "引用这条消息可以继续问。" });
+ const sent = sentText(row.body);
+ expect(sent).toBe("GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800。引用这条消息可以继续问。");
+ // 会话历史里只有结果本身
+ expect(store.listMessages(CONV).at(-1)!.content).toBe(row.body.text);
+ // 引用了别的、没有引用、只是个命令:普通聊天
+ expect(svc.followUp(CONV, { text: "改成英文", quote: "下午 3 点的会是线上的" })).toEqual({ handled: false });
+ expect(svc.followUp(CONV, { text: "改成英文" })).toEqual({ handled: false });
+ expect(svc.followUp(CONV, { text: "/status", quote: sent })).toEqual({ handled: false });
+ // 引用结果(被截短、前面带名字也认得):交给任务,回一句收到
+ expect(svc.followUp(CONV, { text: "改成英文", quote: `小蓝: ${sent.slice(0, 20)}…` })).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });
+ await flush();
+ expect(runs(t.id)).toEqual([
+ ["launch", "ended", "done"],
+ ["followup", "running", ""],
+ ]);
+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, text: "[用户追加]\n改成英文", resume: true });
+ // 失败那句也认(它不带提示:失败那句本来就说了怎么办)
+ await turn(t.sessionId, () => void report(t.sessionId, "failed", "英文版的价格页打不开"));
+ const fail = store.listOutbox({ limit: 50 }).find((r) => r.id.includes(":failure:"))!;
+ expect(fail.body.hint).toBeUndefined();
+ expect(svc.followUp(CONV, { text: "试试这个链接", quote: fail.body.text })).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });
+ await flush();
+ expect(runs(t.id).at(-1)).toEqual(["followup", "running", ""]);
+ expect(host.prompts.at(-1)!.text).toBe("[用户追加]\n试试这个链接");
+ // 停了的:照旧说不能再追加,不开 run
+ await svc.stopTask(t.id, "web");
+ expect(svc.followUp(CONV, { text: "再试一次", quote: sent })).toEqual({ handled: true, ack: "「GPU 价格调研」已停止,不能再追加;需要的话开个新任务。" });
+ await flush();
+ expect(runs(t.id).at(-1)).toEqual(["followup", "ended", "stopped"]);
+ expect(store.listRuns({ taskId: t.id })).toHaveLength(3);
+ });
+
+ it("追加不经聊天代理:引用合成的摘要(不止一个任务)是普通聊天;结果连提示一起不超过 300 字", async () => {
+ host.settingsValue = normalizeSettings({ taskSlots: 8 });
+ const a = start("A");
+ const b = start("B");
+ await flush();
+ await turn(a.sessionId, () => void report(a.sessionId, "done", "A 做好了,在 a.md"));
+ await turn(b.sessionId, () => void report(b.sessionId, "done", "B 做好了,在 b.md"));
+ expect(svc.followUp(CONV, { text: "详细说说", quote: "2 个后台任务:\n· A 做好了,在 a.md\n· B 做好了,在 b.md" })).toEqual({ handled: false });
+ // 「你不在时」合成的一条里只有一个任务:认得出
+ expect(svc.followUp(CONV, { text: "详细说说", quote: "你不在时:A 做好了,在 a.md" })).toEqual({ handled: true, ack: "收到,「A」继续。" });
+ // 两句结果后半句一样(开头的「D:」也像个名字):取最像的那个
+ const d = start("D");
+ const e = start("E");
+ await flush();
+ await turn(d.sessionId, () => void report(d.sessionId, "done", "D:调研好了,结论在 notes.md。"));
+ await turn(e.sessionId, () => void report(e.sessionId, "done", "E:调研好了,结论在 notes.md。"));
+ const dRow = store.listOutbox({ limit: 50 }).find((r) => r.ref === `task:${d.id}`)!;
+ expect(svc.followUp(CONV, { text: "加上 H100", quote: sentText(dRow.body) })).toEqual({ handled: true, ack: "收到,「D」继续。" });
+ const c = start("C");
+ await flush();
+ await turn(c.sessionId, () => void report(c.sessionId, "done", "长".repeat(400)));
+ const row = store.listOutbox({ limit: 50 }).find((r) => r.ref === `task:${c.id}`)!;
+ expect(sentText(row.body).length).toBeLessThanOrEqual(300);
+ expect(sentText(row.body)).toMatch(/长…引用这条消息可以继续问。$/);
+ });
+
+ 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 turn(f.sessionId, () => void report(f.sessionId, "done", "GPU 好了"));
+ const row = store.listOutbox({ limit: 50 })[0];
+ expect([row.replyTo, row.body.text, row.body.hint]).toEqual(["om_req", "GPU 好了", "回复这条消息可以继续问。"]);
+ expect(svc.followUp(fs1.id, { text: "加上 H100", rootId: "om_other", parentId: "om_other2" })).toEqual({ handled: false });
+ expect(svc.followUp(fs1.id, { text: "加上 H100" })).toEqual({ handled: false });
+ // 回复结果:回复链的根是请求那条
+ expect(svc.followUp(fs1.id, { text: "加上 H100", rootId: "om_req", parentId: "om_result" })).toEqual({ handled: true, ack: "收到,「GPU」继续。" });
+ await flush();
+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: f.sessionId, text: "[用户追加]\n加上 H100", resume: true });
+ // 直接回复请求那条也一样(在跑:并进这一轮)
+ svc.onEvent("b", f.sessionId, status(f.sessionId, "running"));
+ expect(svc.followUp(fs1.id, { text: "再加上 L40S", parentId: "om_req" })).toEqual({ handled: true, ack: "收到,「GPU」继续。" });
+ await flush();
+ expect(host.steers.at(-1)).toMatchObject({ sessionId: f.sessionId, text: "[用户追加]\n再加上 L40S" });
+ // 建任务时会话里还没收到过飞书消息:结果直接发到会话,不带提示(回复链认不出是哪个任务)
+ const fs2 = store.ensureConversation("b", "feishu", "oc_2", "主人");
+ store.addMessage(fs2.id, "user", "后台整理发票");
+ const g = svc.create({ botId: "b", conversationId: fs2.id, title: "发票", brief: "" }).task!;
+ await flush();
+ await turn(g.sessionId, () => void report(g.sessionId, "done", "发票好了"));
+ const notice = store.listOutbox({ limit: 50 }).find((r) => r.ref === `task:${g.id}`)!;
+ expect([notice.kind, notice.body.hint]).toEqual(["notice", undefined]);
+ });
+
it("停止:只停这个任务(宿主停会话),不发任何消息;之后的报告被拒;停了的不能再追加;/stop 编号一样", async () => {
const a = start("A");
const b = start("B");
@@ -862,3 +962,50 @@ describe("宿主:补丁加载 amb-tasks,任务规则经环境变量交给插
store.close();
});
});
+
+describe("追加不经聊天代理:渠道 → runtime.interceptReply → 任务", () => {
+ it("飞书事件带上回复链(root_id、parent_id);发在任务请求那条消息下的不进聊天,交给任务,回一句收到;别的照常进聊天", async () => {
+ const raw = { event_id: "e1", sender: { sender_id: { open_id: "ou_1" } }, message: { message_id: "om_2", root_id: "om_req", parent_id: "om_res", chat_id: "oc_1", chat_type: "p2p", message_type: "text", content: '{"text":"hi"}', create_time: "1" } };
+ expect(messageEventOf(raw)).toMatchObject({ messageId: "om_2", chatId: "oc_1", senderOpenId: "ou_1", rootId: "om_req", parentId: "om_res" });
+ expect(messageEventOf({ message: { message_id: "om_3", chat_id: "oc_1" } })).not.toHaveProperty("rootId");
+ const ws = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-follow-"));
+ const store = new Store(":memory:");
+ store.createBot({ id: "b", name: "小蓝" });
+ const host = new FakeHost(ws);
+ const outbox = new Outbox(store);
+ const approvals = new ApprovalCenter(store);
+ const svc = new TaskService({ store, host, delivery: new Delivery({ store, outbox }), approvals, defaultModel: () => "m", retryDelaysMs: [5, 5, 5] });
+ svc.start();
+ const conv = store.ensureConversation("b", "feishu", "oc_1", "主人");
+ store.addMessage(conv.id, "user", "后台调研一下 GPU 价格");
+ store.setKV(`reply-to:${conv.id}`, JSON.stringify({ messageId: "om_req", chatId: "oc_1" }));
+ const task = svc.create({ botId: "b", conversationId: conv.id, title: "GPU", brief: "" }).task!;
+ await flush();
+ const agent = { available: true, approvals, tasks: svc, turnsInProgress: new Map(), canSteer: () => false } as unknown as AgentManager;
+ const rt = new BotRuntime({ store, models: {} as any, defaultModel: () => "m", contextMessages: 20, contextChars: 20_000, agent });
+ const chats: string[] = [];
+ rt.handle = async (ev) => void chats.push(ev.id);
+ const fake = new FakeFeishu();
+ const ch = new FeishuChannel("b", fake, rt, new KeyedQueue(), 0, outbox);
+ outbox.start();
+ try {
+ await ch.start();
+ fake.onMessage!(feishuEvent("加上 H100", { messageId: "om_f1", chatId: "oc_1", rootId: "om_req", parentId: "om_res" }));
+ await ch.idle();
+ await flush();
+ expect(chats).toEqual([]);
+ expect(fake.calls.filter((c) => c.op === "text").map((c) => c.args.slice(0, 2))).toEqual([["om_f1", "收到,「GPU」继续。"]]);
+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: task.sessionId, text: "[用户追加]\n加上 H100" });
+ // 不在回复链里:照常进聊天
+ fake.onMessage!(feishuEvent("你好", { messageId: "om_f2", chatId: "oc_1" }));
+ await ch.idle();
+ expect(chats).toEqual(["om_f2"]);
+ } finally {
+ await ch.stop();
+ await outbox.stop();
+ svc.stop();
+ store.close();
+ fs.rmSync(ws, { recursive: true, force: true });
+ }
+ });
+});