🤖 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.
Python ai-agentai-assistantchatbotclaudecomputer-usedeepseekdesktop-appdshelectronfeishugeminigptgrokllmlocal-firstmodelflaremulti-modelopenai-compatiblepersonal-ai-agentwechat
Rules: needs-you asks whether to switch an observed rule to act
Marla6f6324f5239b
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.mdindex 5c7ce50..4f8362b 100644--- a/docs/design/background-tasks-and-proactive.md+++ b/docs/design/background-tasks-and-proactive.md@@ -283,7 +283,7 @@ The time zone is the system's IANA zone, stored on the rule when it is created.| Recorded | "本会发送:…" / "本会保持安静" / "本会做:…" plus cost and steps | what it said and did |- **Every new rule starts in observe.** The one exception is a **fixed reminder**, such as 「明天下午 3 点提醒我开会」. The user dictated both the text and the time, so there is nothing to judge. It runs in act and delivers the text without a model turn. (Open question Q6.)-- **Switching modes.** After 3 observed runs, the rule row shows a quiet hint 「已观察 3 次 · 改为执行?」. The hint is never pushed. The user switches in the UI or by telling the bot. Act can go back to observe at any time.+- **Switching modes.** After 3 good observed runs on the current version (outcome done; failed and skipped runs don't count), "needs you" asks: 「规则「看 X 价格」已观察 3 次,需要你来决定是否执行」, with the latest run's line (「本会发送:“…”」) under it and [改为执行] [继续观察]. It is the least urgent kind: last in the list, never pushed, no desktop notification, though it counts toward the badge. 继续观察 stops asking for this version (kept across restarts); editing the instruction makes a new version, which asks again after 3 more good runs. The row goes away when the rule switches to act or off, pauses, or is deleted. The user can also switch in the rule detail or by telling the bot. Act can go back to observe at any time.- **Editing the instruction** puts the rule back in observe; this needs PO confirmation (Q7). Editing only the schedule keeps the mode.- **Tasks a person asked for are never in observe.** An explicit request is its own mandate, as in superagent, where explicit requests work in every accept mode.- **What observe guarantees:** no message to anyone through AnyModelBot, and no file changes, because the sandbox is read-only. It does not block network calls from shell tools. The prompt forbids outside actions, and the Report lists what the rule would do. We say exactly this in the UI help text.@@ -463,10 +463,14 @@ These use `ui/design/README.md`:│─────────────────────────────────────────────────────────────││ ● 绿草 · 微信登录已过期 今天 │ red dot│ [重新扫码] │+│─────────────────────────────────────────────────────────────│+│ ● 小蓝 · 规则「看 X 价格」已观察 3 次,需要你来决定是否执行 08:00 │ never pushed+│ 本会发送:“X 降价了,现在 ¥199(昨天 ¥259)” │+│ [改为执行] [继续观察] │└─────────────────────────────────────────────────────────────┘```-Order: questions and approvals first (time-sensitive), then failures, then deliveries, then the system (logins, stuck turns, budget). When the list is empty, there is no sidebar row and no badge. Opening the view directly shows a quiet 「没有需要你处理的事」.+Order: questions and approvals first (time-sensitive), then failures, then deliveries, then the system (logins, stuck turns, budget), and last a rule that has observed enough and asks whether to act. When the list is empty, there is no sidebar row and no badge. Opening the view directly shows a quiet 「没有需要你处理的事」.**Tasks view** (main pane; all bots, with a bot filter). Sections appear only when non-empty.@@ -481,7 +485,6 @@ Order: questions and approvals first (time-sensitive), then failures, then deliv规则┌─────────────────────────────────────────────────────────────┐│ ○ 每天 08:00 · 看 X 价格 观察中 · 下次 明天 08:00 › │ grey-│ 已观察 3 次 · 改为执行? │ quiet hint, text button│ ● 每周一 09:00 · issue 周报 执行中 · 上次 周一 · 说了 1 句 › │└─────────────────────────────────────────────────────────────┘已完成 · 最近 7 天diff --git a/docs/development.md b/docs/development.mdindex c4f6870..0f42815 100644--- a/docs/development.md+++ b/docs/development.md@@ -167,7 +167,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令要跑一阵子的事在后台做,不占聊天(设计见 `docs/design/background-tasks-and-proactive.md`,代码在 `src/tasks/`):- **后台任务**:聊天代理用 `task_start` 开一个任务(自己的 DSH 会话 `task-<id>` 和工作区里的文件夹 `tasks/<名字>-<id6>/`),一句话说清在后台做什么;做完把结果发回原会话(微信引用、飞书回复那条消息可以接着问)。中途要问你的,一个会话一次只推一个问题。应用重启后接着做,已经做过的外部动作先查再做。`/tasks` 列出任务和规则,`/stop 编号` 停一个。-- **规则**:`rule_create` 或 机器人设置 › 主动消息 › 规则 建好。检查从观察开始(只读,不发消息,只记「本会发送」),观察 3 次后提示改为执行;固定提醒直接执行。每次运行一个新会话,运行记录可以导出成 Markdown。+- **规则**:`rule_create` 或 机器人设置 › 主动消息 › 规则 建好。检查从观察开始(只读,不发消息,只记「本会发送」),好好观察 3 次后在「需要你」里问要不要改为执行;固定提醒直接执行。每次运行一个新会话,运行记录可以导出成 Markdown。- **看得到、不打扰**:信息面板的「任务」组列着这个机器人的任务和规则(结束了的收在「已结束」里),点开看来自哪、最新进展、预算、文件夹和每次运行的处理过程;所有在等你的事在侧栏的「需要你」里。只推结果、要你决定的事和失败;免打扰(默认 22:00–08:00)、每天上限(微信 3 条、飞书 5 条)、合并成摘要都在 机器人设置 › 主动消息。- **预算**:任务默认 $1,规则每次 $0.10、每月 $3(估算,按 Modelflare 的参考价)。用完时停下问你;任务详情里能改任务的预算,规则编辑器里能改规则的。机器人的预算 Key 剩不到 20% 时停后台工作,留给聊天。- **暂停**:机器人设置 › 主动消息 › 暂停后台工作(或跟机器人说),任务和规则先停、主动消息排着,聊天照常。diff --git a/src/i18n/messages/rules.ts b/src/i18n/messages/rules.tsindex 207640f..7d203c0 100644--- a/src/i18n/messages/rules.ts+++ b/src/i18n/messages/rules.ts@@ -62,6 +62,7 @@ export const zh = {subject: "规则「{title}」",failingPaused: { other: "连续失败 {count} 次,已暂停" },failing: { other: "连续失败 {count} 次" },+ suggest: { other: "规则「{title}」已观察 {count} 次,需要你来决定是否执行" },// 推送:连续失败暂停了(执行中的规则)pausedPush: "⚠️ 规则「{title}」连续失败 {count} 次,已暂停:{why}",// 建规则时建议给用户的那句(经聊天代理转述)@@ -151,6 +152,7 @@ export const en: Catalog<typeof zh> = {subject: "Rule “{title}”",failingPaused: { one: "Failed {count} time in a row, paused", other: "Failed {count} times in a row, paused" },failing: { one: "Failed {count} time in a row", other: "Failed {count} times in a row" },+ suggest: { one: "Rule “{title}” has observed {count} time; decide whether it should act", other: "Rule “{title}” has observed {count} times; decide whether it should act" },pausedPush: "⚠️ Rule “{title}” failed {count} times in a row and is paused: {why}",createdReply: "Rule set: {title}, {when}. It watches quietly for a few days; switch it to act under Tasks.",remindReply: "OK, reminder set for {when}.",diff --git a/src/tasks/attention.ts b/src/tasks/attention.tsindex a1918e2..05d06e4 100644--- a/src/tasks/attention.ts+++ b/src/tasks/attention.ts@@ -4,7 +4,7 @@** - 来源可以登记(addSource):审批中心、任务服务、渠道各给一份;3c 的"留着没发出去的消息"也从这里接进来。* - 有变化(kick,或每 10 秒看一眼)时通知订阅者:侧栏的数字、托盘角标、系统通知。- * - 系统通知每一项最多一次(takeNew:记在 KV 里,重启也算)。+ * - 系统通知每一项最多一次(takeNew:记在 KV 里,重启也算);问要不要改为执行的那种(suggest)不发。* 健康时什么都没有:没有行、没有角标、没有通知。*/import type { ApprovalRow, Store } from "../store/db.js";@@ -19,17 +19,18 @@ const log = logger("attention");/*** question / approval:在等你回答、批准(任务预算用完时的「再给 $1 继续?」也是 question);failed:任务失败了;* rule:规则连续失败或本月预算用完(暂停了);delivery:结果没送到;login:渠道登录过期了;budget:机器人的预算留给聊天,后台工作停着;- * cleanup:任务文件夹 30 天没动过,过几天清理(3f)+ * cleanup:任务文件夹 30 天没动过,过几天清理(3f);suggest:观察中的规则这一版好好观察了 3 次,问要不要改为执行(最不急:不推送、不发系统通知)*/-export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget" | "cleanup";+export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget" | "cleanup" | "suggest";/*** answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、- * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)、keep(保留要清理的任务文件夹)+ * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)、keep(保留要清理的任务文件夹)、+ * act(规则改为执行;suggest 的 dismiss 是继续观察)*/-export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue" | "keep";+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue" | "keep" | "act";export interface AttentionItem {- /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天)、cleanup:<bot> */+ /** 稳定 id:approval:<id>、task:<id>、rule:<id>、suggest:<规则>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天)、cleanup:<bot> */id: string;kind: AttentionKind;botId: string;@@ -48,8 +49,10 @@ export interface AttentionItem {conversationId?: string;channel?: string;taskId?: string;- /** 规则(3d):连续失败的、执行时的审批 */+ /** 规则(3d):连续失败的、执行时的审批、问要不要改为执行的 */ruleId?: string;+ /** 规则的名字(改为执行后的提示「「看 X 价格」改为执行」用) */+ ruleTitle?: string;approvalId?: string;code?: string;questions?: QuestionItem[];@@ -57,8 +60,10 @@ export interface AttentionItem {export type AttentionSource = () => AttentionItem[];-/** 排序:提问和审批在前(等着的事),再是失败、没送到,最后是系统的(登录、预算);同一类旧的在前 */-const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3, cleanup: 3 };+/** 排序:提问和审批在前(等着的事),再是失败、没送到,再是系统的(登录、预算),问要不要改为执行的最后;同一类旧的在前 */+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3, cleanup: 3, suggest: 4 };+/** 不发系统通知的:只是建议,等用户自己来看 */+const QUIET = new Set<AttentionKind>(["suggest"]);const NOTIFIED = "attention:notified";@@ -161,8 +166,9 @@ export class Attention {}}- /** 还没发过系统通知的项(记下来,之后不再给;重启后也一样)。已经不在列表里的记录随之清掉 */- takeNew(items = this.list()): AttentionItem[] {+ /** 还没发过系统通知的项(记下来,之后不再给;重启后也一样)。已经不在列表里的记录随之清掉;不发通知的那几种不算 */+ takeNew(all = this.list()): AttentionItem[] {+ const items = all.filter((it) => !QUIET.has(it.kind));let done: string[] = [];try {done = JSON.parse(this.o.store.getKV(NOTIFIED) || "[]");diff --git a/src/tasks/rules.ts b/src/tasks/rules.tsindex dce4044..83b0d7c 100644--- a/src/tasks/rules.ts+++ b/src/tasks/rules.ts@@ -14,8 +14,8 @@ import { describe } from "./schedule.js";export const RULE_FAILS_TO_PAUSE = 3;/** 连续失败几次出现在「需要你」里 */export const RULE_FAILS_TO_SHOW = 2;-/** 观察几次好的之后提示改为执行 */-export const RULE_HINT_AFTER = 3;+/** 这一版好好观察了几次(做完了的;失败、跳过的不算)之后,「需要你」里问要不要改为执行 */+export const RULE_SUGGEST_AFTER = 3;/** 改了原话之后先观察几次(产品负责人:1 次) */export const RULE_OBSERVE_AFTER_EDIT = 1;/** 每个机器人最多几条规则 */@@ -85,10 +85,6 @@ export interface RuleView {nextRunAt: number;/** 最近一次:时间、结果、一行 */last?: { at: number; outcome: string; line: string };- /** 已观察 3 次(这一版)、可以改为执行 */- hint: boolean;- /** 这一版好好观察过几次 */- observed: number;failures: number;/** 暂停的原因:failures / budget;空 = 没暂停 */pausedReason: string;diff --git a/src/tasks/service.ts b/src/tasks/service.tsindex 6fb8b78..0907afc 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -72,9 +72,9 @@ import {RULE_DENY_PREFIX,RULE_FAILS_TO_PAUSE,RULE_FAILS_TO_SHOW,- RULE_HINT_AFTER,RULE_OBSERVE_AFTER_EDIT,RULE_RUN_CAP_MS,+ RULE_SUGGEST_AFTER,RUN_ERROR,WOULD_APPROVAL,errorText,@@ -280,6 +280,8 @@ const NOTES = "task-notes:";const TRASH = "tasks:session-trash";/** 「需要你」里清理文件夹那一行点过「知道了」:到哪个清理时间为止不再显示(每个机器人一个) */const CLEANUP_SEEN = "tasks:cleanup-seen:";+/** 「需要你」里问要不要改为执行的那一行点过「继续观察」:哪一版不再问(每条规则一个;删规则时一起删) */+const SUGGEST_SEEN = "rules:suggest-seen:";/** 预算用完时的回答:不要了 */const STOP_WORDS = /^(停止|停|不用了?|不要了?|算了|取消|stop|no|cancel)[。.!!]*$/i;@@ -2250,6 +2252,8 @@ export class TaskService {if (reopened) (next.failures = 0), (next.pausedReason = "");if (next.trigger || next.mode !== undefined || reopened) next.nextRunAt = this.nextFor({ trigger, mode, pausedReason: reopened ? "" : rule.pausedReason }, now);this.store.updateRule(id, next);+ // 自己选了观察(从执行、关着切回来):这一版算是决定过了,「需要你」里不再问要不要改为执行(改了原话的新一版照样会问)+ if (mode === "observe" && rule.mode !== "observe" && !reworded) this.store.setKV(SUGGEST_SEEN + id, String(rule.version));log.info("rule updated", { rule: id, fields: Object.keys(next).filter((k) => k !== "updatedAt") });this.ruleChanged(id);return { rule: this.store.getRule(id) };@@ -2289,6 +2293,7 @@ export class TaskService {const l = [...this.live.values()].find((x) => x.ruleId === id);if (l) this.forget(l);this.store.deleteRule(id);+ this.store.deleteKV(SUGGEST_SEEN + id);if (l) await this.o.host.stop(l.botId, l.sessionId).catch(() => undefined);log.info("rule deleted", { rule: id });this.ruleChanged(id);@@ -2800,7 +2805,6 @@ export class TaskService {ruleView(rule: RuleRow): RuleView {const live = this.store.listRuns({ ruleId: rule.id, states: ["queued", "running", "settling"], limit: 1 })[0];const last = this.store.ruleRuns(rule.id, { limit: 5 }).find((r) => r.state === "ended");- const observed = rule.kind === "check" ? this.store.ruleRuns(rule.id, { mode: "observe", outcome: "done", version: rule.version, limit: RULE_HINT_AFTER }).length : 0;return {id: rule.id,botId: rule.botId,@@ -2817,8 +2821,6 @@ export class TaskService {state: ruleState(rule, !!live),nextRunAt: rule.nextRunAt,...(last ? { last: { at: last.queuedAt, outcome: last.outcome, line: runLine(last, rule.kind, this.carrier(last)) } } : {}),- hint: rule.kind === "check" && rule.mode === "observe" && !rule.pausedReason && observed >= RULE_HINT_AFTER,- observed,failures: rule.failures,pausedReason: rule.pausedReason,monthUsd: rule.kind === "check" ? this.monthSpent(rule) : 0,@@ -2867,12 +2869,14 @@ export class TaskService {}/**- * 「需要你」里规则那一份:连续失败 3 次暂停了的(红),连续失败 2 次的(黄),本月预算用完暂停了的(黄,可以再给 $3 接着跑)。- * 原因没了(重试成功、关掉、删掉、下个月了)就消失。规则执行时的审批由审批中心那一份给。+ * 「需要你」里规则那一份:连续失败 3 次暂停了的(红),连续失败 2 次的(黄),本月预算用完暂停了的(黄,可以再给 $3 接着跑),+ * 观察够了、问要不要改为执行的(suggestItem)。原因没了(重试成功、关掉、删掉、下个月了)就消失。规则执行时的审批由审批中心那一份给。*/ruleAttention(): AttentionItem[] {const out: AttentionItem[] = [];for (const rule of this.store.listRules()) {+ const suggest = this.suggestItem(rule);+ if (suggest) out.push(suggest);const paused = !!rule.pausedReason;if (!paused && (rule.mode === "off" || rule.failures < RULE_FAILS_TO_SHOW)) continue;const conv = this.store.getConversation(rule.conversationId);@@ -2914,6 +2918,45 @@ export class TaskService {}return out;}++ /**+ * 观察中、没暂停的检查,这一版好好观察了 3 次(做完了的;失败、跳过的不算):「需要你」里问要不要改为执行,第二行是最近那次+ * 运行记录里的那一行。只在应用里:不推送、不发系统通知。改为执行、关掉、暂停、删掉就消失;继续观察了的这一版不再问+ * (改了原话版本加 1,新的一版再好好观察 3 次再问)。+ */+ private suggestItem(rule: RuleRow): AttentionItem | undefined {+ if (rule.kind !== "check" || rule.mode !== "observe" || rule.pausedReason) return undefined;+ if (Number(this.store.getKV(SUGGEST_SEEN + rule.id) || 0) >= rule.version) return undefined;+ const good = this.store.ruleRuns(rule.id, { mode: "observe", outcome: "done", version: rule.version, limit: RULE_SUGGEST_AFTER });+ if (good.length < RULE_SUGGEST_AFTER) return undefined;+ const last = good[0];+ return {+ id: `suggest:${rule.id}`,+ kind: "suggest",+ botId: rule.botId,+ botName: this.store.getBot(rule.botId)?.name ?? rule.botId,+ subject: tr("rules.suggest", { title: rule.title, count: RULE_SUGGEST_AFTER }),+ status: "",+ line: runLine(last, rule.kind, this.carrier(last)),+ since: last.endedAt || last.queuedAt,+ severity: "warn",+ actions: ["act", "dismiss"],+ conversationId: rule.conversationId,+ channel: this.store.getConversation(rule.conversationId)?.channel ?? "",+ ruleId: rule.id,+ ruleTitle: rule.title,+ };+ }++ /** 「需要你」里的继续观察:这一版不再问要不要改为执行 */+ keepObserving(id: string): boolean {+ const rule = this.store.getRule(id);+ if (!rule) return false;+ this.store.setKV(SUGGEST_SEEN + id, String(rule.version));+ log.info("rule keeps observing", { rule: id, version: rule.version });+ this.changed(id);+ return true;+ }}/**diff --git a/src/web/server.ts b/src/web/server.tsindex e5069ab..baf34d1 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -487,6 +487,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str} else if (item.kind === "delivery" && (action === "retry" || action === "dismiss")) ok = app.delivery.act(item.id, action);// 清理任务文件夹(3f):保留(再算 30 天)、知道了(到时照样清理)else if (item.kind === "cleanup") ok = action === "keep" ? app.tasks.keepCleanup(item.botId) : app.tasks.dismissCleanup(item.botId);+ // 观察够了的规则:改为执行(和规则详情里切模式一样)、继续观察(这一版不再问)+ else if (item.kind === "suggest") ok = action === "act" ? !app.tasks.updateRule(item.ruleId!, { mode: "act" }).error : app.tasks.keepObserving(item.ruleId!);else if (item.kind === "rule" && action === "retry") ok = !app.tasks.resumeRule(item.ruleId!).error;// 加预算接着做:规则每月再给 $3,任务再给 $1else if (item.kind === "rule" && action === "continue") ok = !app.tasks.addRuleBudget(item.ruleId!).error;diff --git a/test/rules.integration.test.ts b/test/rules.integration.test.tsindex 1c65ed3..2aa822b 100644--- a/test/rules.integration.test.ts+++ b/test/rules.integration.test.ts@@ -1,7 +1,7 @@/*** 规则(3d)端到端:真实 DSH 子进程 + 脚本化的模型 + mock iLink(主人在微信里和自己的机器人聊)。* 退出演示:微信里说「每天 08:00 看 X 价格」,聊天代理 rule_create 建好规则(观察);「三天」到点各跑一次(把 next_run_at 拨到现在、- * 叫醒定时器),运行记录读得懂,什么都没发;提示改为执行;改了之后命中时推一句,只推一次。+ * 叫醒定时器),运行记录读得懂,什么都没发;「需要你」里问要不要改为执行;改了之后命中时推一句,只推一次。* 另外:每次运行一个新会话;观察只读(写不了文件),执行可写工作区;规则会话的工具(观察去掉能改变什么的);检查用小模型、* 那一句用主模型写;观察时要批准的自动拒绝、记下来,「需要你」里没有;事件触发走同一条路。*/@@ -161,7 +161,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (rconst chat = calls.find((c) => !c.rule && c.users.some((u) => u.includes("RULE PRICE")))!;expect(chat.tools).toEqual(expect.arrayContaining(["rule_create", "rule_update", "task_list"]));const [rule] = (await api("/rules?bot=default")).rules;- expect(rule).toMatchObject({ title: "看 X 价格", when: "每天 08:00", mode: "observe", state: { key: "observe", label: "观察中" }, instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我", conversationId: CONV, hint: false });+ expect(rule).toMatchObject({ title: "看 X 价格", when: "每天 08:00", mode: "observe", state: { key: "observe", label: "观察中" }, instruction: "每天 08:00 看看 X 的价格,低于 200 告诉我", conversationId: CONV });// 三天:观察。每次一个新会话,检查用小模型;写不了文件(只读);什么都不发price(259);const d1 = await tick(rule.id);@@ -198,11 +198,13 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("rules (rexpect(calls.filter((c) => c.tools.length === 0 && c.system.includes(RULE_RESULT_SYSTEM.split("\n")[0])).map((c) => c.model)).toEqual(["mock-agent"]);await app.outbox.idle();expect(ilink.state.sent.filter((s) => /MAIN|199/.test(s.text))).toEqual([]);- // 观察了 3 次:提示改为执行(只在界面上)- expect((await api(`/rules/${rule.id}`)).rule).toMatchObject({ hint: true, observed: 3 });- // 改为执行:命中时推一句(主模型写的),只推一次;执行能写自己的文件夹- const put = await api(`/rules/${rule.id}`, { method: "PUT", body: { mode: "act" } });- expect(put.rule).toMatchObject({ mode: "act", state: { key: "act", label: "执行中" }, hint: false });+ // 观察了 3 次:「需要你」里问要不要改为执行(只在应用里,不推)+ const ask = (await api("/attention")).items.find((i: any) => i.id === `suggest:${rule.id}`);+ expect(ask).toMatchObject({ kind: "suggest", subject: "规则「看 X 价格」已观察 3 次,需要你来决定是否执行", line: "本会保持安静:X 现在 ¥262;写文件失败", actions: ["act", "dismiss"] });+ // 在那里改为执行:命中时推一句(主模型写的),只推一次;执行能写自己的文件夹+ const acted = await api(`/attention/suggest:${rule.id}/act`, { method: "POST", body: {} });+ expect(acted.items.find((i: any) => i.id === `suggest:${rule.id}`)).toBeUndefined();+ expect((await api(`/rules/${rule.id}`)).rule).toMatchObject({ mode: "act", state: { key: "act", label: "执行中" } });price(195);const d4 = await tick(rule.id);expect(d4).toMatchObject({ mode: "act", outcome: "done", permission: "workspace-write" });diff --git a/test/rules.unit.test.ts b/test/rules.unit.test.tsindex 0b133f3..b5391cb 100644--- a/test/rules.unit.test.ts+++ b/test/rules.unit.test.ts@@ -1,6 +1,7 @@/*** 规则(3d)的零件:时间表(解析、给人看的话、下一次 / 上一次、夏令时、宽限期、cron)、宿主的定时器、事件的过滤条件、数据目录锁,- * 以及 TaskService 对着一个假宿主和一个假时钟:从观察开始、观察只记「本会发送」、3 次好的观察后提示改为执行、执行时经出站队列发一句、+ * 以及 TaskService 对着一个假宿主和一个假时钟:从观察开始、观察只记「本会发送」、3 次好的观察后在「需要你」里问要不要改为执行(失败、+ * 跳过的不算;不推送、不发系统通知;继续观察了这一版不再问,重启也一样;改了原话再观察 3 次再问)、执行时经出站队列发一句、* 改了原话先观察 1 次再回到执行、连续失败 3 次自动暂停(执行的推一句,观察的只在「需要你」里)、错过的按宽限期补跑一次或记为跳过、* 等名额超过宽限期跳过、固定提醒不进模型、重启后宽限期内重跑一次、运行记录、事件触发、时间上限、观察时的审批自动拒绝、* 检查用小模型而那一句用主模型写、微信配额预留和续期提醒、/tasks 列出并关掉规则。@@ -21,6 +22,7 @@ import { RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, ruleRules } from "../src/agimport { Outbox } from "../src/core/outbox.js";import { Delivery } from "../src/core/delivery.js";import { Store, type RunRow } from "../src/store/db.js";+import { Attention } from "../src/tasks/attention.js";import { DataDirLocked, LOCK_FILE, lockDataDir } from "../src/store/lock.js";const TZ = "Asia/Shanghai";@@ -365,7 +367,7 @@ describe("规则(假宿主、假时钟)", () => {expect(rule.nextRunAt).toBe(at("2026-11-02T08:00"));expect(text).toContain("「已建好规则:每天 08:00 看 X 价格。先观察几天,只记录不打扰你;在「任务」里可以改成执行。」");expect(text).toContain(tServer("rules.weixinNote"));- expect(svc.getRuleView(rule.id)).toMatchObject({ when: "每天 08:00", state: { key: "observe", label: "观察中", dot: "" }, hint: false });+ expect(svc.getRuleView(rule.id)).toMatchObject({ when: "每天 08:00", state: { key: "observe", label: "观察中", dot: "" } });// 时间表说不清:照着错误改const bad = await svc.chatTool({ botId: "b", sessionId: "chat-1", op: "rule_create", args: { title: "t", instruction: "i", schedule: "每天" } });expect(bad.error).toMatch(/Use one of/);@@ -406,11 +408,12 @@ describe("规则(假宿主、假时钟)", () => {expect(writes[0]).toMatchObject({ model: "main-model", system: RULE_RESULT_SYSTEM });expect(writes[0].user).toContain("[草稿]\nX 降到 199 了");expect(log[0]).toMatchObject({ version: 1, permission: "只读", cause: "schedule", at: at("2026-11-04T08:00") });- // 3 次好的观察:提示改为执行(不推)- expect(svc.getRuleView(rule.id)).toMatchObject({ hint: true, observed: 3, state: { key: "observe" } });+ // 3 次好的观察:「需要你」里问要不要改为执行(不推)+ expect(svc.ruleAttention().map((a) => [a.kind, a.subject])).toEqual([["suggest", "规则「看 X 价格」已观察 3 次,需要你来决定是否执行"]]);// 改为执行:下一次带着「执行」,权限是可写工作区,命中时推一句(id 固定)svc.updateRule(rule.id, { mode: "act" });- expect(svc.getRuleView(rule.id)).toMatchObject({ hint: false, state: { key: "act", label: "执行中", dot: "ok" } });+ expect(svc.getRuleView(rule.id)).toMatchObject({ state: { key: "act", label: "执行中", dot: "ok" } });+ expect(svc.ruleAttention()).toEqual([]);await go(at("2026-11-05T08:00"));expect(host.prompts.at(-1)!.text).toContain("[这次]\n执行:message 会发给用户。");expect(svc.sessionConfig({ sessionId: host.prompts.at(-1)!.sessionId })).toMatchObject({ mode: "act", permission: "workspace-write", deny: RULE_DENY.act });@@ -425,6 +428,110 @@ describe("规则(假宿主、假时钟)", () => {expect(svc.ruleLog(rule.id)[0].line).toBe("保持安静:X 现在 ¥199");});+ it("观察够了:这一版好好观察 3 次后「需要你」里问要不要改为执行(失败、跳过的不算),排在最后,算件数但不推送、不发系统通知", async () => {+ const { rule } = await create();+ const ask = () => svc.ruleAttention().filter((a) => a.kind === "suggest");+ await day("2026-11-02", report("done"));+ await day("2026-11-03", report("failed", "X 的页面打不开"));+ await day("2026-11-04", report("done", "X 降到 199 了"));+ // 跳过的(电脑没开)也不算+ store.insertEndedRun({ id: "r_skipped00001", botId: "b", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "skipped", error: "app_off", queuedAt: at("2026-11-04T20:00"), endedAt: at("2026-11-04T20:00") });+ expect(runsOf(rule.id).map((r) => r.outcome)).toEqual(["done", "failed", "done", "skipped"]);+ expect(ask()).toEqual([]);+ await day("2026-11-05", report("done", "", { would: "在 X 的页面上点「降价提醒」" }));+ // 第二行是最近那次运行记录里的那一行+ expect(ask()).toEqual([+ {+ id: `suggest:${rule.id}`,+ kind: "suggest",+ botId: "b",+ botName: "小蓝",+ subject: "规则「看 X 价格」已观察 3 次,需要你来决定是否执行",+ status: "",+ line: "本会做:在 X 的页面上点「降价提醒」",+ since: runsOf(rule.id).at(-1)!.endedAt,+ severity: "warn",+ actions: ["act", "dismiss"],+ conversationId: CONV,+ channel: "weixin",+ ruleId: rule.id,+ ruleTitle: "看 X 价格",+ },+ ]);+ expect(withLang("en", () => ask()[0].subject)).toBe("Rule “看 X 价格” has observed 3 times; decide whether it should act");+ // 不推送(观察本来就什么都不发);在「需要你」里排在最后,算在件数里,但不发系统通知+ expect(store.listOutbox({ limit: 100 })).toEqual([]);+ const att = new Attention({ store });+ att.addSource(() => svc.ruleAttention());+ att.addSource(() => [{ id: "cleanup:b", kind: "cleanup", botId: "b", botName: "小蓝", subject: "1 个任务文件夹 11月9日 删除", status: "", line: "", since: now + H, severity: "warn", actions: ["keep", "dismiss"] }]);+ expect(att.list().map((a) => a.id)).toEqual(["cleanup:b", `suggest:${rule.id}`]);+ expect(att.count()).toBe(2);+ expect(att.takeNew().map((a) => a.id)).toEqual(["cleanup:b"]);+ att.stop();+ });++ it("观察够了:改为执行、关掉、暂停、删掉就消失;继续观察了这一版不再问(重启也一样),改了原话再好好观察 3 次再问", async () => {+ const { rule } = await create();+ const asks = () => svc.ruleAttention().filter((a) => a.kind === "suggest").length;+ for (const d of ["2026-11-02", "2026-11-03", "2026-11-04"]) await day(d, report("done"));+ expect(asks()).toBe(1);+ // 改为执行(和规则详情里切模式一样)、关掉:消失+ svc.updateRule(rule.id, { mode: "act" });+ expect(store.getRule(rule.id)!.mode).toBe("act");+ expect(asks()).toBe(0);+ svc.updateRule(rule.id, { mode: "off" });+ expect(asks()).toBe(0);+ // 自己又选了观察:这一版算是决定过了,不再问(之后关掉,免得和下面的规则一起跑)+ svc.updateRule(rule.id, { mode: "observe" });+ expect(asks()).toBe(0);+ svc.updateRule(rule.id, { mode: "off" });+ // 另一条:暂停了(本月预算用完)消失,删掉也消失+ const other = (await create("daily 09:00")).rule;+ for (const d of ["2026-11-05", "2026-11-06", "2026-11-07"]) {+ await go(at(`${d}T09:00`));+ await turn(report("done"));+ }+ expect(svc.ruleAttention().map((a) => a.id)).toEqual([`suggest:${other.id}`]);+ store.updateRule(other.id, { pausedReason: "budget" });+ expect(svc.ruleAttention().map((a) => a.id)).toEqual([`rule:${other.id}`]);+ store.updateRule(other.id, { pausedReason: "" });+ expect(svc.ruleAttention().map((a) => a.id)).toEqual([`suggest:${other.id}`]);+ svc.keepObserving(other.id);+ expect(store.getKV(`rules:suggest-seen:${other.id}`)).toBe("1");+ await svc.deleteRule(other.id);+ expect(svc.ruleAttention()).toEqual([]);+ expect(store.getKV(`rules:suggest-seen:${other.id}`)).toBeUndefined();++ // 继续观察:这一版不再问,再好好观察一次也不问;重启后也一样+ const third = (await create("daily 10:00")).rule;+ for (const d of ["2026-11-08", "2026-11-09", "2026-11-10"]) {+ await go(at(`${d}T10:00`));+ await turn(report("done"));+ }+ expect(svc.ruleAttention().map((a) => a.id)).toEqual([`suggest:${third.id}`]);+ expect(svc.keepObserving(third.id)).toBe(true);+ expect(svc.ruleAttention()).toEqual([]);+ expect(store.getRule(third.id)!.mode).toBe("observe");+ await go(at("2026-11-11T10:00"));+ await turn(report("done"));+ svc.stop();+ svc = make();+ svc.start();+ expect(svc.ruleAttention()).toEqual([]);+ // 改了原话:新的一版,再好好观察 3 次才问+ svc.updateRule(third.id, { instruction: "每天看看 X 的价格,低于 180 告诉我" });+ expect(store.getRule(third.id)).toMatchObject({ version: 2, mode: "observe" });+ for (const d of ["2026-11-12", "2026-11-13"]) {+ await go(at(`${d}T10:00`));+ await turn(report("done"));+ }+ expect(svc.ruleAttention()).toEqual([]);+ await go(at("2026-11-14T10:00"));+ await turn(report("done"));+ expect(svc.ruleAttention().map((a) => [a.id, a.line])).toEqual([[`suggest:${third.id}`, "本会保持安静:X 现在 ¥199"]]);+ expect(svc.keepObserving("rl_nope")).toBe(false);+ });+it("完全权限的机器人:执行时最多可写工作区;只读的机器人:执行也只读", async () => {const { rule } = await create();svc.updateRule(rule.id, { mode: "act" });diff --git a/test/tasks-view.e2e.test.ts b/test/tasks-view.e2e.test.tsindex 1213220..654c430 100644--- a/test/tasks-view.e2e.test.ts+++ b/test/tasks-view.e2e.test.ts@@ -5,6 +5,7 @@* 规则运行记录和任务导出成 Markdown(下载的文件名、按 ?lang= 的语言)。* 问了个有默认回答的问题、接着在做的任务:在进行中那组,「进行中,有个问题等你回答」;详情、「需要你」、对话里的卡片都有那一句* 「不回复就按中文做」(按界面的语言)。+ * 观察够了的规则:「需要你」里问要不要改为执行;改为执行(同 PUT /rules/:id 切模式)、继续观察(这一版不再问)。*/import fs from "node:fs";import os from "node:os";@@ -174,3 +175,44 @@ describe("问了还在做:有默认回答的提问", () => {expect((await api(`/approvals/${q.id}`)).data.approval.note).toBeUndefined();});});++describe("观察够了的规则:「需要你」里问要不要改为执行", () => {+ /** 一条观察中的检查和它这一版的 n 次好好观察(直接写库;最近那次「本会发送」) */+ const observed = async (title: string, n: number): Promise<string> => {+ const rule = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title, instruction: `每天看看${title}`, schedule: { kind: "daily", time: "08:00" } } })).data.rule;+ for (let i = 0; i < n; i++) {+ const at = Date.now() - (n - i) * 86400_000;+ const id = `r_${rule.id.slice(3, 9)}${String(i).padStart(6, "0")}`;+ app.store.insertEndedRun({ id, botId: "default", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "done", error: "", queuedAt: at, endedAt: at + 60_000 });+ app.store.updateRun(id, { report: { state: "done", summary: "X 现在 ¥259", message: i === n - 1 ? "X 降到 199 了" : "", at } });+ }+ return rule.id;+ };+ const find = async (id: string, lang?: string) => (await api("/attention", { lang })).data.items.find((i: any) => i.id === `suggest:${id}`);++ it("改为执行和规则详情里切模式一样,那一行随之消失;继续观察了这一版不再问;英文", async () => {+ const few = await observed("Y 价格", 2);+ expect(await find(few)).toBeUndefined();+ const id = await observed("X 价格", 3);+ expect(await find(id)).toMatchObject({ kind: "suggest", subject: "规则「X 价格」已观察 3 次,需要你来决定是否执行", status: "", line: "本会发送:“X 降到 199 了”", actions: ["act", "dismiss"], ruleId: id, ruleTitle: "X 价格" });+ expect((await find(id, "en")).subject).toBe("Rule “X 价格” has observed 3 times; decide whether it should act");+ // 算在侧栏的件数里+ expect((await api("/agent")).data.attention).toBeGreaterThan(0);+ const r = await api(`/attention/suggest:${id}/act`, { method: "POST", body: {} });+ expect(r.status).toBe(200);+ expect(r.data.items.find((i: any) => i.id === `suggest:${id}`)).toBeUndefined();+ expect((await api(`/rules/${id}`)).data.rule).toMatchObject({ mode: "act", state: { key: "act", label: "执行中" } });+ // 已经处理掉了:再点是 409+ expect((await api(`/attention/suggest:${id}/act`, { method: "POST", body: {} })).status).toBe(409);+ // 继续观察:这一版不再问,模式不变+ const keep = await observed("Z 价格", 3);+ expect(await find(keep)).toBeDefined();+ expect((await api(`/attention/suggest:${keep}/dismiss`, { method: "POST", body: {} })).status).toBe(200);+ expect(await find(keep)).toBeUndefined();+ expect((await api(`/rules/${keep}`)).data.rule).toMatchObject({ mode: "observe" });+ // 不支持的操作+ const other = await observed("W 价格", 3);+ expect((await api(`/attention/suggest:${other}/retry`, { method: "POST", body: {} })).status).toBe(400);+ for (const x of [few, id, keep, other]) await api(`/rules/${x}`, { method: "DELETE" });+ });+});diff --git a/ui/components/rules.js b/ui/components/rules.jsindex d8f06d3..6ef7feb 100644--- a/ui/components/rules.js+++ b/ui/components/rules.js@@ -1,5 +1,5 @@-// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一行是状态和下次运行;观察了 3 次的,行里多一句-// 「已观察 3 次 · 改为执行?」(只在这里,从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,+// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一行是状态和下次运行(观察够了要不要改为执行,在「需要你」里问,+// 从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,// 和运行记录(一次一行:时间 · 模式 · 本会发送 / 保持安静 / 失败 / 跳过),每行再点开看报告、步骤、版本和权限;运行记录可以导出成// Markdown(3f)。编辑器里有每次、每月的预算(3f,检查才有)。// 健康时不多说话:状态是"点 + 文字"(绿 = 执行中、提醒,灰 = 观察中、关了,红 = 暂停了)。@@ -60,20 +60,12 @@ async function put(rule, body, done) {/** 信息面板里的一行:点开是详情(和行同一块,像普通的折叠一样展开) */export function RuleRow({ rule, onChanged, open, onToggle }) {- const [busy, setBusy] = useState(false);- const toAct = async (e) => {- e.stopPropagation();- setBusy(true);- if (await put(rule, { mode: "act" })) (toast(t("rules.nowActs", { title: rule.title })), onChanged?.());- setBusy(false);- };return html`<div class=${`row compact clickable rule-row${open ? " open" : ""}`} role="button" tabindex="0" aria-expanded=${open}onClick=${onToggle} onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && (e.preventDefault(), onToggle())}><span class=${`dot ${rule.state.dot}`} aria-hidden="true"></span><div class="who"><div class="name">${rule.when} · ${rule.title}</div><div class="sub">${ruleSub(rule)}</div>- ${rule.hint && html`<button type="button" class="text rule-hint" disabled=${busy} onClick=${toAct} onKeyDown=${(e) => e.stopPropagation()}>${t("rules.hint", { count: rule.observed })}</button>`}</div></div>${open && html`<div class="row-edit rule-edit"><${RuleDetail} rule=${rule} onChanged=${onChanged} /></div>`}`;diff --git a/ui/css/shell.css b/ui/css/shell.cssindex 1076130..d96ef12 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -296,10 +296,9 @@ button.thread:active { background: var(--side-press); }.transcript-turn { display: grid; gap: var(--space-1); }.transcript .work-line { font-size: var(--fs-sm); }-/* 规则(components/rules.js):「任务」组里一条规则一行(时间表 · 标题、状态和下次),观察够了的行里多一句改为执行;+/* 规则(components/rules.js):「任务」组里一条规则一行(时间表 · 标题、状态和下次;观察够了要不要改为执行在「需要你」里问);点开是同一块里的详情(原话、模式、操作、运行记录),运行记录一次一行、不画分隔线,点开一行看报告和步骤,也不另起一块 */.rule-row .dot { flex: none; }-.rule-hint { display: block; margin-top: var(--space-0-5); font-size: var(--fs-xs); text-align: left; }.rule-detail { display: grid; gap: var(--space-2); min-width: 0; }.rule-detail > .actions { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }.rule-detail > .actions .grow { flex: 1; }diff --git a/ui/design/gallery.js b/ui/design/gallery.jsindex a525057..e4ebdfb 100644--- a/ui/design/gallery.js+++ b/ui/design/gallery.js@@ -604,19 +604,19 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<//><//>- <${Section} id="needs" title="需要你" lead="所有机器人里在等你的事:提问和审批在前,再是失败、没送到、登录。侧栏那一行和托盘角标只在有事时出现;一件一块,操作在行里,点标题行展开任务详情。">+ <${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:等你回答 / 等你回答(任务接着在做,不回复就按默认)/ 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天">+ <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你回答(任务接着在做,不回复就按默认)/ 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天 / 清理文件夹 / 观察够了,要不要改为执行(不推送)">${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}<//><//>- <${Section} id="rules" title="规则" lead="信息面板「任务」组里一条规则一行:时间表 · 标题,状态和下次运行。观察了 3 次的,行里多一句改为执行(只在这里,从不推送)。点开是同一块里的详情和运行记录,记录一次一行、不画分隔线,再点开一行看报告。">- <${Demo} title="行" note="RuleRow:观察中(提示改为执行)/ 执行中 / 暂停 / 提醒">+ <${Section} id="rules" title="规则" lead="信息面板「任务」组里一条规则一行:时间表 · 标题,状态和下次运行。观察够了要不要改为执行,在「需要你」里问(从不推送)。点开是同一块里的详情和运行记录,记录一次一行、不画分隔线,再点开一行看报告。">+ <${Demo} title="行" note="RuleRow:观察中 / 执行中 / 暂停 / 提醒">${() => html`<div class="panel-body" style="width: 340px; flex: none; padding: var(--space-2); border-radius: var(--r-pane); background: var(--grain), var(--glass-panel)"><div class="list">${RULES.map((r) => html`<${RuleRow} rule=${r} open=${false} onToggle=${() => {}} />`)}</div></div>`}@@ -689,6 +689,7 @@ const NEEDS = [{ id: "l", kind: "login", botName: "绿草", subject: "微信登录已过期", status: "", line: "", since: Date.now() - 3 * 3600_000, severity: "err" },{ id: "rs", kind: "budget", botName: "小蓝", subject: "后台工作已停", status: "", line: "机器人预算只剩约 $1.80(共 $10),留给聊天", since: Date.now() - 4 * 3600_000, severity: "warn", actions: ["open"] },{ id: "c", kind: "cleanup", botName: "小蓝", subject: "2 个任务文件夹 11月4日 删除", status: "", line: "整理下载目录和旧照片归档 · 30 天没动过", since: Date.now() - 5 * 3600_000, severity: "warn", actions: ["keep", "dismiss"] },+ { id: "s", kind: "suggest", botName: "小蓝", subject: "规则「看 X 价格」已观察 3 次,需要你来决定是否执行", status: "", line: "本会发送:“X 降价了,现在 ¥199(昨天 ¥259)”", since: Date.now() - 6 * 3600_000, severity: "warn", actions: ["act", "dismiss"], ruleTitle: "看 X 价格" },];/** 任务的样例(单人:自己的机器人小蓝):在调研的、问了个有默认回答的问题接着在做的、等你回答的、昨天做完的(文件夹 3 天后清理) */@@ -733,16 +734,16 @@ const ENDED_DETAIL = {runs: [{ id: "r2", cause: "launch", state: "ended", outcome: "done", queuedAt: ago(27 * 1440 + 10), startedAt: ago(27 * 1440 + 10), endedAt: ago(27 * 1440 - 20), steps: 0 }],};-/** 规则的样例(单人:自己的机器人小蓝):每天 8 点看 X 价格(观察了 3 次)、每周的 issue 周报、暂停了的巡检、一次性的提醒 */+/** 规则的样例(单人:自己的机器人小蓝):每天 8 点看 X 价格(观察中)、每周的 issue 周报、暂停了的巡检、一次性的提醒 */const at = (days, h, m = 0) => {const d = new Date();d.setDate(d.getDate() + days);d.setHours(h, m, 0, 0);return d.getTime();};-const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", observeLeft: 0, failures: 0, hint: false, observed: 0, channel: "weixin", message: "", trigger: { kind: "schedule" }, version: 1, ...o });+const rule = (o) => ({ botId: "b", kind: "check", mode: "observe", observeLeft: 0, failures: 0, channel: "weixin", message: "", trigger: { kind: "schedule" }, version: 1, ...o });const RULES = [- rule({ id: "g1", title: "看 X 价格", when: "每天 08:00", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", state: { key: "observe", label: "观察中", dot: "" }, nextRunAt: at(1, 8), hint: true, observed: 3, monthUsd: 0.41, monthBudgetUsd: 3 }),+ rule({ id: "g1", title: "看 X 价格", when: "每天 08:00", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", state: { key: "observe", label: "观察中", dot: "" }, nextRunAt: at(1, 8), monthUsd: 0.41, monthBudgetUsd: 3 }),rule({ id: "g2", title: "issue 周报", when: "每周一 09:00", instruction: "每周一早上把仓库上周的 issue 汇总成三句话发给我", mode: "act", state: { key: "act", label: "执行中", dot: "ok" }, nextRunAt: at(3, 9) }),rule({ id: "g3", title: "每日 issue 巡检", when: "每天 08:30", instruction: "每天看看有没有新的 issue 需要我回复", mode: "act", state: { key: "paused", label: "已暂停", dot: "err" }, failures: 3, nextRunAt: 0 }),rule({ id: "g4", title: "交房租", when: "11月3日 12:00", kind: "remind", mode: "act", message: "该交房租了。", state: { key: "remind", label: "提醒", dot: "ok" }, nextRunAt: at(2, 12) }),diff --git a/ui/locales/en/needs.js b/ui/locales/en/needs.jsindex 2e8805f..429f1bd 100644--- a/ui/locales/en/needs.js+++ b/ui/locales/en/needs.js@@ -18,4 +18,6 @@ export default {continue: "Continue",raiseBudget: "Change budget",keep: "Keep",+ toAct: "Switch to act",+ keepObserving: "Keep observing",};diff --git a/ui/locales/en/rules.js b/ui/locales/en/rules.jsindex b937da2..5de03dd 100644--- a/ui/locales/en/rules.js+++ b/ui/locales/en/rules.js@@ -9,7 +9,6 @@ export default {paused: { one: "Paused · failed {count} time in a row", other: "Paused · failed {count} times in a row" },pausedBudget: "Paused · monthly budget used up",month: "This month about {spent} of {budget}",- hint: { one: "Observed {count} time · switch to act?", other: "Observed {count} times · switch to act?" },nowActs: "“{title}” now acts",version: "Version {n}",manual: "Run manually",diff --git a/ui/locales/zh-CN/needs.js b/ui/locales/zh-CN/needs.jsindex 70b7c8c..2ec72e5 100644--- a/ui/locales/zh-CN/needs.js+++ b/ui/locales/zh-CN/needs.js@@ -18,4 +18,6 @@ export default {continue: "继续",raiseBudget: "调整预算",keep: "保留",+ toAct: "改为执行",+ keepObserving: "继续观察",};diff --git a/ui/locales/zh-CN/rules.js b/ui/locales/zh-CN/rules.jsindex d208e95..9f7cb1c 100644--- a/ui/locales/zh-CN/rules.js+++ b/ui/locales/zh-CN/rules.js@@ -9,7 +9,6 @@ export default {paused: { other: "已暂停 · 连续失败 {count} 次" },pausedBudget: "已暂停 · 本月预算用完",month: "本月 约 {spent} / {budget}",- hint: { other: "已观察 {count} 次 · 改为执行?" },nowActs: "「{title}」改为执行",version: "第 {n} 版",manual: "手动运行",diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.jsindex a0bd6a8..1ec6d46 100644--- a/ui/screens/needs-you.js+++ b/ui/screens/needs-you.js@@ -4,12 +4,13 @@// 预算(3e):任务预算用完是一个提问(「已用约 $1.00,再给 $1 继续?」继续 / 停止);规则本月预算用完可以继续;// 机器人的预算留给聊天、后台工作停着的,去机器人设置调整预算。// 清理(3f):任务文件夹 30 天没动过、过几天删除的,一个机器人一行,可以保留或知道了(不推送,只在这里说一次)。+// 观察够了的规则:问要不要改为执行(第二行是最近那次的「本会发送:…」),可以改为执行或继续观察;排在最后,不推送、不发系统通知。import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { html, Icon, Button, Skeleton } from "../components/ui.js";import { TaskDetail } from "../components/tasks.js";import { RuleDetail } from "../components/rules.js";import { api } from "../lib/api.js";-import { failed } from "../lib/store.js";+import { failed, toast } from "../lib/store.js";import { fmtAgo } from "../lib/format.js";import { t } from "../lib/i18n.js";@@ -45,12 +46,15 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB}, [writing]);const act = async (action, body = {}, key = action) => {setBusy(key);+ let ok = false;try {await onAct(action, body);+ ok = true;} catch (e) {failed(e);}setBusy("");+ return ok;};const send = () => text.trim() && act("answer", { text: text.trim() }, "text");// 详情一下就能看到:任务的展开处理过程,规则的展开运行记录;网页对话里的去对话@@ -86,6 +90,8 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB${item.kind === "login" && html`<${Button} onClick=${() => onRelogin?.(item.botId)}>${t("needs.relogin")}<//>`}${item.kind === "cleanup" && html`<${Button} loading=${busy === "keep"} disabled=${!!busy} onClick=${() => act("keep")}>${t("needs.keep")}<//><button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.seen")}</button>`}+ ${item.kind === "suggest" && html`<${Button} loading=${busy === "act"} disabled=${!!busy} onClick=${async () => (await act("act")) && toast(t("rules.nowActs", { title: item.ruleTitle }))}>${t("needs.toAct")}<//>+ <button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.keepObserving")}</button>`}</div>${writing && html`<div class="need-reply"><input ref=${input} class="field" placeholder=${t("needs.answerPlaceholder")} value=${text} disabled=${busy === "text"}