🤖 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
Phase 3f: tasks view and polish
Marla2bb09fa470bb
diff --git a/README.md b/README.mdindex c226541..dcf4a6b 100644--- a/README.md+++ b/README.md@@ -193,6 +193,17 @@ npm start # 本地管理界面:http://127.0.0.1:3600/<img src="docs/assets/features/agent-files.gif" alt="机器人整理一个杂乱的文件夹:先列出文件、给出方案,移动工作区之外的文件前弹出审批卡片" width="100%"></p>+## ⏳ 在后台干活,需要你时才来找你++- **后台任务。** 要跑一阵子的事(调研、做报告、整理文件),或者你说一句「后台做」,机器人会开一个后台任务,你可以接着聊别的。做完把结果发回原来的对话。+- **接着问。** 在微信里引用结果、在飞书里回复那条消息,就是继续问这个任务。+- **规则。** 「每天早上 8 点看看 X 的价格,低于 200 告诉我」会建成一条规则。新规则先观察:只记下本会说什么,不发消息、不改文件;看过几次觉得靠谱,再改成执行。固定的提醒直接执行。+- **「需要你」。** 所有机器人在等你回答、批准或重试的事都在侧栏这一行里;没事时这一行不出现。信息面板的「任务」组列着这个机器人的任务和规则,每一步都看得到。+- **不吵你。** 只推结果、要你决定的事和失败,进展不推。默认 22:00 到 08:00 免打扰;主动消息每天有上限(微信 3 条、飞书 5 条),多了合成一条。+- **有预算。** 每个任务、每条规则都有预算(任务默认 1 美元,规则每次 0.1 美元、每月 3 美元),快用完时停下问你,可以在任务详情和规则编辑器里改。+- **随时暂停。** 机器人设置 › 主动消息里一个开关暂停后台工作,聊天照常。+- **用完会清理。** 任务和运行记录留 30 天;任务文件夹 30 天没动过会删除,删之前在「需要你」里告诉你,可以保留。运行记录能导出成 Markdown。+## 🖥️ 操作你的电脑,生成图片和视频- **电脑操作**由内置的 [Cua Driver](https://github.com/trycua/cua) 提供。默认自动执行;把某个机器人切到「改变界面前先问我」,每一次点击和输入都要等你点头。读取屏幕内容永远不需要审批。macOS 上的电脑操作是 Beta 功能。@@ -308,7 +319,7 @@ Modelflare 会保留请求日志;保留什么、保留多久,见它的[信我们正在探索的方向。它们不是承诺,顺序也不是排期。-- [ ] **定时任务**:让机器人按时间表自己干活。+- [x] **定时任务**:让机器人按时间表自己干活(已上线,就是上面的规则)。- [ ] **群聊**:目前飞书机器人只处理一对一对话。- [ ] **英文界面**:目前应用界面只有简体中文。- [ ] **macOS 电脑操作**:在更多真机上验证 direct 模式,让它脱离 Beta。diff --git a/README_en.md b/README_en.mdindex c7e5337..bf17017 100644--- a/README_en.md+++ b/README_en.md@@ -193,6 +193,17 @@ A bot is more than a chat window: it has a persona, a default model, its own wor<img src="docs/assets/features/agent-files.gif" alt="A bot tidies a messy folder: it lists the files, proposes a plan, and an approval card asks before moving files outside its workspace" width="100%"></p>+## ⏳ Works in the background, and comes to you only when needed++- **Background tasks.** For work that takes a while (research, a report, sorting files), or when you say "do it in the background", the bot starts a background task and you keep chatting. The result comes back to the conversation that asked for it.+- **Follow-ups.** Quote the result in WeChat, or reply to it in Feishu, to keep talking to that task.+- **Rules.** "Every morning at 8, check X's price and tell me if it drops below 200" becomes a rule. A new rule observes first: it records what it would have said, and sends nothing and changes no files. Once it looks right, switch it to act. Fixed reminders act straight away.+- **Needs you.** Everything any bot is waiting on you for, an answer, an approval or a retry, sits in one sidebar row that is only there when something needs you. The info panel's Tasks group lists the bot's tasks and rules, with every step visible.+- **Quiet by default.** Only results, decisions and failures are pushed, never progress. Quiet hours are 22:00 to 08:00, and unprompted messages are capped per day (3 on WeChat, 5 on Feishu), with the rest merged into one.+- **Budgets.** Every task and rule has a budget (1 US dollar per task; 0.10 per rule run and 3 a month), and work stops and asks when it runs out. Change them in the task details and the rule editor.+- **Pause anytime.** One switch in bot settings › Proactive messages pauses background work; chat carries on.+- **Cleans up after itself.** Tasks and run logs are kept for 30 days. A task folder unused for 30 days is deleted, and you are told first in Needs you, with the option to keep it. Run logs export as Markdown.+## 🖥️ Operates your computer, and makes images and video- **Computer use** is powered by the bundled [Cua Driver](https://github.com/trycua/cua). By default, actions run automatically. Switch a bot to *ask before changing the screen* and every click and keystroke waits for you. Reading the screen never needs approval. On macOS, computer use is a Beta feature.@@ -308,7 +319,7 @@ Modelflare keeps request logs; its [Trust Center](https://modelflare.dev/trust?uDirections we are exploring. They are not promises, and the order is not a schedule.-- [ ] **Scheduled tasks**: let a bot run work on a timer.+- [x] **Scheduled tasks**: let a bot run work on a timer (shipped as rules, above).- [ ] **Group chats**: Feishu bots handle one-to-one chats today.- [ ] **English interface**: the app UI is Simplified Chinese today.- [ ] **macOS computer use**: verify direct mode on more real machines and move it out of Beta.diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.mdindex 2f0c8d9..aaf1c6a 100644--- a/docs/design/background-tasks-and-proactive.md+++ b/docs/design/background-tasks-and-proactive.md@@ -1,6 +1,6 @@# Background tasks and proactive rules (Phase 3 design)-Status: **3a–3e are built**: tasks, questions and needs-you, delivery, rules with observe mode, and cost controls (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`, `test/cost.*`). 3f is still design. Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.+Status: **3a–3f are built**: tasks, questions and needs-you, delivery, rules with observe mode, cost controls, and the tasks view with retention, cleanup and Markdown export (`src/tasks/`, `src/core/delivery.ts`, `dsh-runtime/plugins/amb-tasks.mjs`, `ui/components/tasks.js`; tests in `test/tasks.*`, `test/delivery.*`, `test/rules.*`, `test/cost.*`, `test/retention.*`, `test/tasks-view.*`). Written 2026-10-31 against `master` df22385 and the pinned DSH `0.2.1-rc.4` in `dsh-runtime/`.Feasibility evidence is in [Appendix A](#appendix-a-feasibility-answers-with-evidence). The spike that produced it is `scripts/spikes/p3-tasks/`.## Summary@@ -379,7 +379,7 @@ Each rule has a run log, newest first, with one line per run: time, mode, outcom- 前天 08:00 · 失败:页面打不开(已重试 3 次) · 约 $0.01- 10/27 08:00 · 跳过:电脑没开-Expanding a row shows the Report (summary, message, would-do), the steps, the rule version it ran under and the permission it had. The log is kept for 90 days and is exportable as Markdown.+Expanding a row shows the Report (summary, message, would-do), the steps, the rule version it ran under and the permission it had. The log is kept for 30 days (decision 9) and is exportable as Markdown.### Calm defaults@@ -495,6 +495,13 @@ GPU 价格调研 [停止]**Bot info panel:** a "任务" group (a `.list`) after 渠道 and 待审批, with open tasks and rules in one compact row each. It is absent when the bot has neither.+**As built (3f).** The full tasks view is the info panel's 任务 group, not a new main-pane screen with a sidebar button:++- The panel is already the place for "this bot" (channels, approvals, memory, conversations), bot settings' rules row already points there (「N 条,在信息面板的「任务」里」), and the cross-bot question "does anything need me?" is the needs-you page. A main-pane page would add a permanent sidebar control that shows nothing when healthy.+- Order: working and needs-you tasks (`GET /tasks?bot=&group=working,needs`), then rules, then one quiet row 「已结束 3」 that folds the ended tasks of the last 30 days (`group=ended`). The group is absent when the bot has no task or rule.+- A row opens in place, as rules already do (one `--well`, no lines between the detail's rows): 来自 (channel, time and the user's words; it opens that conversation), 最新进展, 预算 (约 $0.08 / $1.00 with 改), 文件夹 (path, size, 打开 on the desktop), 清理 (only when a date is set, with 保留), then each run as a folded 处理过程, and 停止 / 导出 / 删除. The chat chip and needs-you show the same detail. The command palette has 「任务和规则」.+- Rule detail is as in 3d, plus 导出 next to 编辑 and 删除. The rule editor has 每次 / 每月 budgets for checks.+## 7. Permissions| Work | Sandbox | Approvals | Denied tools (only those registered) |@@ -554,6 +561,7 @@ CREATE TABLE IF NOT EXISTS tasks (report TEXT NOT NULL DEFAULT '', -- latest Report JSONended_at INTEGER NOT NULL DEFAULT 0, end_reason TEXT NOT NULL DEFAULT '', -- done|stopped|archivedstopped_by TEXT NOT NULL DEFAULT '',+ cleanup_at INTEGER NOT NULL DEFAULT 0, -- 3f: when the folder is due for cleanup (the user was told); 0 = nonecreated_at INTEGER NOT NULL, updated_at INTEGER NOT NULL);CREATE INDEX IF NOT EXISTS tasks_open ON tasks(bot_id, ended_at);@@ -629,11 +637,12 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);| Route | Does || --- | --- |-| `GET /tasks?bot=&group=working\|needs\|ended` | List with stage, cost and the latest line |+| `GET /tasks?bot=&group=working\|needs\|ended` | List with stage, cost and the latest line; several groups separated by commas; archived tasks are never listed || `POST /tasks` `{botId, conversationId?, text, budgetUsd?}` | New task from the desktop |-| `GET /tasks/:id` | Detail: origin, Report, runs (without steps), inputs, delivery state |+| `GET /tasks/:id` | Detail: the task view, runs (without steps), origin (channel, time, words), folder and session sizes || `GET /tasks/:id/runs/:run/activity` | Steps of one run |-| `POST /tasks/:id/stop` · `/retry` · `/continue {text}` · `/budget {addUsd}` · `/archive` | Person actions |+| `POST /tasks/:id/stop` · `/retry` · `/continue {text}` · `/budget {addUsd}` or `{budgetUsd}` · `/keep` · `/open` (desktop) · `DELETE /tasks/:id` | Person actions (as built: stop, budget, keep, open and delete; retry and continue go through `/attention`) |+| `GET /tasks/:id/export` · `GET /rules/:id/export` (`?lang=`) | Markdown download of a task's runs or a rule's run log || `GET /rules?bot=` · `POST /rules {botId, conversationId, text}` (returns a draft: words, schedule, mode) · `PUT /rules/:id` · `DELETE /rules/:id` | Rules || `POST /rules/:id/run` | Run now, in the rule's mode || `GET /rules/:id/runs?before=` | Run log |@@ -677,7 +686,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);| Turn ends without a `task_report` | One nudge; then `failed` (「没有给出结果」) || Task loops without progress | The run's time cap and budget stop it; needs you || Job runs forever | Killed 30 minutes after the turn ended; the session is told at its next turn |-| Approval or question never answered | Blocking approval: rejected at its TTL; the task fails with 「批准超时」. Task question: stays in needs-you; no reminders; the task is archived after 14 days (Q9) |+| Approval or question never answered | Blocking approval: rejected at its TTL; the task fails with 「批准超时」. Task question: stays in needs-you; no reminders; the task is archived after 30 idle days and the question withdrawn (decision 9) || Delivery fails (Feishu API, channel logged out) | Retries at 5 s doubling to 300 s; after 3 failures: needs-you `delivery`. Dropped only when the conversation no longer exists || Feishu messages sent while the app is offline | The long connection doesn't re-push them (the SDK reconnects with no position; the platform only re-pushes events it delivered that weren't acked within 3 s). On start and on every reconnect the app reads each Feishu chat active in the last 7 days from history: messages from the last 24 h after the last one it saw, at most 20 per chat, through the normal inbound pipeline and dedupe. Without the history scope it says so once and carries on || WeChat window closed or no quota | Held, piggybacked on the next inbound, shown in needs-you ([WeChat](#wechat-the-hard-constraint)) |@@ -686,7 +695,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);| Two hosts open the same data dir | On desktop, Electron's `requestSingleInstanceLock()` already prevents it. The headless CLI and Docker build need a data-dir lock before the Scheduler starts (a small addition in 3d) || Prompt injection from a web page during a task or rule | Permission caps (observe is read-only; act is capped at workspace), approvals go to needs-you, and denied acting tools. We can't fully prevent network side effects from shell tools, and the UI says so || The DSH child's memory grows with sessions the SDK can't close (one per rule run) | About 0.25–0.45 MB per finished session (measured). After more than 100 task and rule sessions the child is replaced as soon as it is fully idle: no chat turn, run, pending approval, compaction or background job. Nothing is interrupted or recovered |-| Disk growth (task folders, DSH session JSONL) | Retention: archive done tasks after 30 days, and offer to delete their folders and sessions; sizes are shown in the task detail (Q9) |+| Disk growth (task folders, DSH session JSONL) | Retention (decision 9, as built in 3f): a task with no run in flight and nothing new for 30 days is archived (hidden, no follow-ups, open questions withdrawn); run logs are pruned after 30 days, keeping each task's latest run and the current month's rule runs. A folder with files gets a needs-you row (「2 个任务文件夹 11月4日 删除」, 保留 / 知道了, never pushed) at 27 idle days and is deleted at 30 days, no sooner than 3 days after the row appeared, together with the task's DSH session directories (`dsh/<bot>/sessions/*/task-<id>[-N]`; the SDK has no delete, so the host removes them, and retries later if the session is still open in the child). Any use of the task, or 保留, restarts the 30 days. Folder and session sizes are in the task detail; deleting a task removes its folder. State is in `tasks.cleanup_at` and `kv`, so it survives restarts and long times off |## 12. Testing strategydiff --git a/docs/development.md b/docs/development.mdindex 7d4d6fc..c4f6870 100644--- a/docs/development.md+++ b/docs/development.md@@ -116,7 +116,7 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令## 界面- 侧栏:机器人列表(头像 + 名称 + 最近一条消息),+ 新建,右键 重命名 / 删除;左下角账户按钮打开设置(`⌘/Ctrl+,`)。-- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、使用请求、待审批、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。+- 对话页:顶部悬浮的机器人名称胶囊打开信息面板(`⌘/Ctrl+⇧+I`:渠道、使用请求、待审批、任务和规则、记忆、最近会话,⚙ 进机器人设置);回复流式显示(Markdown、代码块一键复制),可随时停止(`Esc`);审批与提问以卡片形式出现在对话里;向上翻阅时不会被拉回底部。- 命令面板 `⌘/Ctrl+K`;外观(跟随系统 / 浅色 / 深色)在 设置 → 常规。- 语言:简体中文 / English,设置 → 常规 → 语言(引导页右上角、命令面板里也能切),默认跟随系统(系统语言不是中文也不是英文时用英文)。偏好存在 config.json 的 `ui.lang`,托盘菜单、服务端报错和状态文字、机器人发到微信 / 飞书的系统消息(`/help`、审批提示等)都跟着它;命令行 / Docker 下"跟随系统"看 `AMB_LANG`,再看 `LC_ALL` / `LANG`,都没有时用简体中文。日志、发给模型的提示词和用户自己起的机器人名不翻译。- 界面文案在 `ui/locales/<语言>/<命名空间>.js`,代码里写 `t("命名空间.键", { 参数 })`(`ui/lib/i18n.js`);服务端在 `src/i18n/messages/<命名空间>.ts`,键有类型检查。每个界面请求带 `x-amb-lang`,服务端在这个请求里用同一种语言回话。@@ -162,6 +162,17 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- 微信只能在对方 24 小时内发过消息时回复,每条消息之后最多回 10 条。这时发不了的消息不丢,先留着(held),等对方下次发消息时先发出去:几条文字合成一条「你不在时:…」(一条微信放得下就合,文件照原样),排在这次的回复前面,顺序不变、只发一次。留着的最多 7 天;“收到”、审批提示这类过一会儿就没意义的照旧按自己的期限。- 再也发不出去的(平台多次拒绝、等待太久)标记出来并写明原因,记在日志和诊断信息里。+## 后台任务和规则++要跑一阵子的事在后台做,不占聊天(设计见 `docs/design/background-tasks-and-proactive.md`,代码在 `src/tasks/`):++- **后台任务**:聊天代理用 `task_start` 开一个任务(自己的 DSH 会话 `task-<id>` 和工作区里的文件夹 `tasks/<名字>-<id6>/`),一句话说清在后台做什么;做完把结果发回原会话(微信引用、飞书回复那条消息可以接着问)。中途要问你的,一个会话一次只推一个问题。应用重启后接着做,已经做过的外部动作先查再做。`/tasks` 列出任务和规则,`/stop 编号` 停一个。+- **规则**:`rule_create` 或 机器人设置 › 主动消息 › 规则 建好。检查从观察开始(只读,不发消息,只记「本会发送」),观察 3 次后提示改为执行;固定提醒直接执行。每次运行一个新会话,运行记录可以导出成 Markdown。+- **看得到、不打扰**:信息面板的「任务」组列着这个机器人的任务和规则(结束了的收在「已结束」里),点开看来自哪、最新进展、预算、文件夹和每次运行的处理过程;所有在等你的事在侧栏的「需要你」里。只推结果、要你决定的事和失败;免打扰(默认 22:00–08:00)、每天上限(微信 3 条、飞书 5 条)、合并成摘要都在 机器人设置 › 主动消息。+- **预算**:任务默认 $1,规则每次 $0.10、每月 $3(估算,按 Modelflare 的参考价)。用完时停下问你;任务详情里能改任务的预算,规则编辑器里能改规则的。机器人的预算 Key 剩不到 20% 时停后台工作,留给聊天。+- **暂停**:机器人设置 › 主动消息 › 暂停后台工作(或跟机器人说),任务和规则先停、主动消息排着,聊天照常。+- **保留与清理**:任务和运行记录留 30 天,30 天没动过的任务归档。任务文件夹 30 天没动过就删除,连同 DSH 里它的会话记录(`dsh/<机器人>/sessions/` 下;SDK 没有删会话的接口,由应用直接删,会话还开在代理进程里的等进程换过再删);删之前在「需要你」里说一次,可以保留。任务详情里能看到文件夹多大,也能直接删掉任务(连同文件夹)。+## 电脑操作(Computer Use)每个机器人可在 机器人设置(信息面板的 ⚙)→ 电脑操作 中开关、选择后端和审批方式;`/status` 与设置页会显示当前后端、是否可用及原因。diff --git a/docs/development_en.md b/docs/development_en.mdindex 9f8ed39..7edfac8 100644--- a/docs/development_en.md+++ b/docs/development_en.md@@ -116,7 +116,7 @@ Inside the container the console listens on 0.0.0.0, so token access is enforced## Interface- Sidebar: bot list (avatar + name + latest message), + New, right-click to rename / delete; the account button at the bottom-left opens Settings (`⌘/Ctrl+,`).-- Chat screen: the floating bot-name pill at the top opens the info panel (`⌘/Ctrl+⇧+I`: channels, requests, pending approvals, memory, recent sessions; ⚙ opens bot settings). Replies stream in (Markdown, one-click copy for code blocks) and can be stopped at any time (`Esc`). Approvals and questions appear as cards in the chat. Scrolling up is never yanked back to the bottom.+- Chat screen: the floating bot-name pill at the top opens the info panel (`⌘/Ctrl+⇧+I`: channels, requests, pending approvals, tasks and rules, memory, recent sessions; ⚙ opens bot settings). Replies stream in (Markdown, one-click copy for code blocks) and can be stopped at any time (`Esc`). Approvals and questions appear as cards in the chat. Scrolling up is never yanked back to the bottom.- Command palette `⌘/Ctrl+K`; appearance (system / light / dark) is in Settings → General.- Language: 简体中文 / English, in Settings → General → Language (also at the top-right of the onboarding screen and in the command palette). It follows the system by default (English when the system language is neither Chinese nor English). The preference is stored in `ui.lang` in config.json; the tray menu, server error and status messages, and system messages bots send to WeChat / Feishu (`/help`, approval prompts, …) all follow it. On the command line / Docker, "System" means `AMB_LANG`, then `LC_ALL` / `LANG`, falling back to Simplified Chinese. Logs, prompts sent to the model and bot names users chose are not translated.- UI strings live in `ui/locales/<lang>/<namespace>.js` and are used as `t("namespace.key", { params })` (`ui/lib/i18n.js`); server strings live in `src/i18n/messages/<namespace>.ts` with type-checked keys. Every UI request carries `x-amb-lang`, and the server answers that request in the same language.@@ -162,6 +162,17 @@ Final replies, delivered files, approval prompts and notices are written to an o- WeChat only lets a bot reply within 24 hours of the person's last message, and at most 10 times per message. A message that cannot go out for that reason is held, not dropped: the next time the person writes, held messages go out first, before the reply, in their original order and only once, with the text ones merged into one "你不在时:…" ("While you were away: …") message when they fit in one WeChat message (files go as they are). Held messages are kept for up to 7 days; short-lived ones such as the "received" note and approval prompts keep their own deadline.- Messages that can no longer be sent (repeated platform rejections, waiting too long) are marked with the reason in the log and the diagnostics.+## Background tasks and rules++Work that takes a while runs in the background and never holds up chat (design: `docs/design/background-tasks-and-proactive.md`; code: `src/tasks/`):++- **Background tasks**: the chat agent starts one with `task_start` (its own DSH session `task-<id>` and a folder `tasks/<name>-<id6>/` in the workspace) and says in one line what it will do; the result comes back to the conversation that asked (quote it in WeChat or reply to it in Feishu to follow up). A task that needs you asks one question at a time per conversation. After an app restart it carries on and checks before repeating outside actions. `/tasks` lists tasks and rules, `/stop <number>` stops one.+- **Rules**: made with `rule_create` or in bot settings › Proactive messages › Rules. A check starts in observe mode (read-only, sends nothing, records "would send"), and after 3 observed runs it suggests switching to act; fixed reminders act straight away. Each run gets a fresh session, and the run log exports as Markdown.+- **Visible, not noisy**: the info panel's Tasks group lists the bot's tasks and rules (ended tasks fold into one "ended" row); open one to see where it came from, the latest progress, the budget, the folder and each run's steps. Everything waiting on you is in the sidebar's Needs you. Only results, decisions and failures are pushed; quiet hours (22:00–08:00 by default), daily caps (3 on WeChat, 5 on Feishu) and digests are in bot settings › Proactive messages.+- **Budgets**: $1 per task, $0.10 per rule run and $3 per rule per month by default (estimated from Modelflare's reference prices). At the limit the work stops and asks; change a task's budget in its details and a rule's in the rule editor. When the bot's budget key is below 20 %, background work stops so chat keeps the rest.+- **Pause**: bot settings › Proactive messages › Pause background work (or ask the bot) holds tasks, rules and pushed messages; chat carries on.+- **Retention**: tasks and run logs are kept for 30 days; a task unused for 30 days is archived. A task folder unused for 30 days is deleted along with the task's DSH session files (under `dsh/<bot>/sessions/`; the SDK has no call to delete a session, so the app removes the files itself, and a session still open in the agent process is removed after the process is replaced). You are told once in Needs you first and can keep it. The task details show the folder's size and can delete the task with its folder.+## Computer useEach bot can turn computer use on or off, choose a backend and an approval mode in Bot settings (⚙ in the info panel) → Computer use; `/status` and the settings page show the current backend, whether it is available, and why not.diff --git a/docs/privacy.md b/docs/privacy.mdindex 1f04f83..94c30b2 100644--- a/docs/privacy.md+++ b/docs/privacy.md@@ -29,6 +29,7 @@| 飞书 App ID / Secret | 数据目录内的配置 | 与飞书开放平台建立长连接时会 | 飞书 || 允许名单与使用请求 | `anymodel.db`:谁能用哪个机器人、陌生人发来的第一条消息(截断,帮你认出是谁) | 不会 | — || 待发送的回复 | `anymodel.db` 的出站队列:还没发出去的消息内容和原因,包括等对方下次发消息再发的微信消息(最多留 7 天;发出去的留 7 天、发不出去的留 30 天后删除) | 发送时会 | 微信 / 飞书 |+| 后台任务和规则 | `anymodel.db`(任务、规则、运行记录,留 30 天);任务文件夹在 `workspaces/<机器人>/tasks/`,30 天没动过会删除(先在「需要你」里告诉你);它们的会话记录在 `dsh/<机器人>/sessions/`,随任务一起删除 | 运行时会 | 同对话:作为模型请求的上下文,经 Modelflare 发给你选定的供应商 || 设置 | `config.json` | 不会 | — || 日志 | `logs/app.log`(按大小轮转) | 不会;「复制诊断信息」由你手动复制,密钥已替换成 `***` | — || 屏幕截图(电脑操作) | 不长期保存 | 会 | 作为模型请求的一部分,经 Modelflare 发给支持视觉的模型;不会转发到微信或飞书聊天,除非你要求作为文件发送 |diff --git a/docs/privacy_en.md b/docs/privacy_en.mdindex 2060c7a..005110f 100644--- a/docs/privacy_en.md+++ b/docs/privacy_en.md@@ -29,6 +29,7 @@ This document explains what AnyModelBot stores where, what leaves your device, a| Feishu App ID / Secret | Configuration inside the data directory | When opening the long connection to the Feishu Open Platform | Feishu || Allowlist and access requests | `anymodel.db`: who may use which bot, and the first message a stranger sent (truncated, so you can tell who it is) | No | — || Replies waiting to be sent | `anymodel.db` outbox: unsent message content and the reason, including WeChat messages held until the person writes again (kept up to 7 days; sent ones are deleted after 7 days, undeliverable ones after 30) | When they are sent | WeChat / Feishu |+| Background tasks and rules | `anymodel.db` (tasks, rules and run logs, kept 30 days); task folders in `workspaces/<bot>/tasks/`, deleted after 30 days unused (you are told first in Needs you); their session files in `dsh/<bot>/sessions/`, deleted with the task | While they run | As for chats: context in model requests, sent through Modelflare to the provider you chose || Settings | `config.json` | No | — || Logs | `logs/app.log` (rotated by size) | No; "Copy diagnostics" is something you copy by hand, with keys replaced by `***` | — || Screenshots (computer use) | Not kept long-term | Yes | Sent as part of the model request through Modelflare to a vision-capable model; never forwarded to WeChat or Feishu chats unless you ask for them as files |diff --git a/electron/main.ts b/electron/main.tsindex 2a0a720..956dc30 100644--- a/electron/main.ts+++ b/electron/main.ts@@ -230,6 +230,7 @@ async function boot(): Promise<void> {updateTitleBar();},openDataDir: () => void shell.openPath(config.dataDir),+ openPath: (p) => void shell.openPath(p),openInBrowser: () => void shell.openExternal(entryUrl),openExternal: (url) => {if (/^https?:/i.test(url)) void shell.openExternal(url);diff --git a/src/agent/host.ts b/src/agent/host.tsindex 7f8182d..61c59a3 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -16,6 +16,7 @@ import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.jimport { acceptsImages } from "../llm/client.js";import { CUA_SKILL, MEDIA_SKILL, TASK_RULES, agentPersona, botPrompt } from "./prompts/index.js";import { t, t as tr } from "../i18n/index.js";+import { dirBytes, taskSessionDirs } from "../tasks/retention.js";const log = logger("agent.host");@@ -1684,6 +1685,29 @@ exec "$REAL" "$@"return !!r.accepted;}+ /** 任务的会话在 DSH 里的记录(DSH_HOME/sessions 下,见 tasks/retention.ts)占多大 */+ taskSessionBytes(taskId: string): number {+ return taskSessionDirs(this.home, taskId).reduce((n, d) => n + dirBytes(d), 0);+ }++ /**+ * 删掉任务会话在 DSH 里的记录(3f:归档、删除任务时)。SDK 没有删会话的接口,直接删目录;会话还开在当前子进程里的不删+ * (DSH 可能还拿着它的文件),返回 false,等子进程换过之后再删。+ */+ removeTaskSessions(taskId: string): boolean {+ const name = `task-${taskId}`;+ if ([...this.opened].some((id) => id === name || id.startsWith(name + "-"))) return false;+ for (const dir of taskSessionDirs(this.home, taskId)) {+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch (e) {+ log.warn("removing a task's session files failed", { task: taskId, message: (e as Error).message.slice(0, 200) });+ return false;+ }+ }+ return true;+ }+/** 停掉任务会话(amb-tasks:取消这一轮、子代理和它的所有后台命令,之后的工具调用一律拒绝) */async stopTask(sessionId: string): Promise<void> {if (!this.harness || !this.control.connected) return;diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex 4e84c6f..5a2e059 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -929,6 +929,8 @@ export class AgentManager {cancel: async (botId, sessionId) => void (await this.hosts.get(botId)?.cancelTask(sessionId)),quiet: (botId, sessionId) => this.hosts.get(botId)?.taskQuiet(sessionId) ?? Promise.resolve({ quiet: true }),runEnded: (botId) => void this.hosts.get(botId)?.restartIfStale().catch(() => undefined),+ sessionBytes: (botId, taskId) => this.host(botId).taskSessionBytes(taskId),+ removeSessions: (botId, taskId) => this.host(botId).removeTaskSessions(taskId),};}diff --git a/src/app.ts b/src/app.tsindex b73e1fd..b5b6263 100644--- a/src/app.ts+++ b/src/app.ts@@ -60,6 +60,8 @@ export interface DesktopHooks {/** Windows 桌面版:窗口右上角的最小化 / 最大化 / 关闭由系统画在界面上,符号颜色跟界面主题(主题只存在界面里) */setTitleBarTheme?(dark: boolean): void;openDataDir(): void;+ /** 在系统的文件管理器里打开一个文件夹(任务详情里的「打开」,3f) */+ openPath?(p: string): void;openInBrowser(): void;/** 在系统浏览器里打开外部链接(Modelflare 登录、充值) */openExternal(url: string): void;diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.tsindex b2dfb98..2b3b8e0 100644--- a/src/i18n/messages/tasks.ts+++ b/src/i18n/messages/tasks.ts@@ -51,6 +51,37 @@ export const zh = {reserveStep: "预算留给聊天",reserveSubject: "后台工作已停",reserveLine: "机器人预算只剩约 {remain}(共 {limit}),留给聊天",+ // 保留与清理(3f):归档了的任务、「需要你」里清理文件夹那一行+ archivedNoFollowup: "「{title}」已归档,不能再追加;需要的话开个新任务。",+ cleanupSubject: { other: "{count} 个任务文件夹 {date} 删除" },+ cleanupLine: "{titles} · 30 天没动过",+ // 导出成 Markdown(3f,tasks/export.ts)+ exportedAt: "导出于 {time}",+ exportLog: "运行记录",+ exportNoRuns: "还没有运行过。",+ exportCost: "约 {spent}",+ exportMonth: "本月 约 {spent} / {budget}",+ exportBudget: "约 {spent} / {budget}",+ exportWould: "本会做",+ exportVersion: "第 {n} 版",+ exportStepFailed: "出错",+ exportMode_observe: "观察",+ exportMode_act: "执行",+ exportFrom: "来自",+ exportFolder: "文件夹",+ exportLatest: "最新进展",+ exportRun: "第 {n} 次",+ exportMinutes: { other: "{count} 分钟" },+ exportFailed: "失败:{why}",+ exportAsked: "问你:{question}",+ exportInterrupted: "中断:应用重启了",+ exportCause_launch: "开始",+ exportCause_followup: "追加后继续",+ exportCause_recover: "重启后继续",+ exportCause_retry: "重试",+ exportCause_continue: "继续",+ exportCause_answer: "回答后继续",+ exportCause_manual: "手动运行",} satisfies Catalog;export const en: Catalog<typeof zh> = {@@ -102,4 +133,33 @@ export const en: Catalog<typeof zh> = {reserveStep: "Budget kept for chat",reserveSubject: "Background work stopped",reserveLine: "The bot's budget is down to about {remain} of {limit}; the rest is kept for chat",+ archivedNoFollowup: "\"{title}\" is archived and can't take follow-ups; start a new task if you need one.",+ cleanupSubject: { one: "{count} task folder will be deleted {date}", other: "{count} task folders will be deleted {date}" },+ cleanupLine: "{titles} · unused for 30 days",+ exportedAt: "Exported {time}",+ exportLog: "Run log",+ exportNoRuns: "No runs yet.",+ exportCost: "about {spent}",+ exportMonth: "This month about {spent} of {budget}",+ exportBudget: "about {spent} of {budget}",+ exportWould: "Would do",+ exportVersion: "Version {n}",+ exportStepFailed: "error",+ exportMode_observe: "Observe",+ exportMode_act: "Act",+ exportFrom: "From",+ exportFolder: "Folder",+ exportLatest: "Latest",+ exportRun: "Run {n}",+ exportMinutes: { one: "{count} min", other: "{count} min" },+ exportFailed: "Failed: {why}",+ exportAsked: "Asked you: {question}",+ exportInterrupted: "Interrupted: the app restarted",+ exportCause_launch: "Started",+ exportCause_followup: "Continued after a follow-up",+ exportCause_recover: "Resumed after a restart",+ exportCause_retry: "Retry",+ exportCause_continue: "Continued",+ exportCause_answer: "Continued after your answer",+ exportCause_manual: "Run manually",};diff --git a/src/i18n/messages/web.ts b/src/i18n/messages/web.tsindex b4c1f27..807eb71 100644--- a/src/i18n/messages/web.ts+++ b/src/i18n/messages/web.ts@@ -31,6 +31,7 @@ export const zh = {taskNotFound: "任务不存在",runNotFound: "没有这次运行",taskAlreadyStopped: "任务已经停止了",+ badGroup: "分组只能是 working、needs 或 ended",windowsOnly: "只在 Windows 上需要",recordNotFound: "记录不存在",requestAlreadyHandled: "这个请求已经处理过了",@@ -68,6 +69,7 @@ export const en: Catalog<typeof zh> = {taskNotFound: "Task not found",runNotFound: "Run not found",taskAlreadyStopped: "The task has already stopped",+ badGroup: "group must be working, needs or ended",windowsOnly: "Only needed on Windows",recordNotFound: "Record not found",requestAlreadyHandled: "This request has already been handled",diff --git a/src/store/db.ts b/src/store/db.tsindex 1542126..e862e3f 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -244,6 +244,8 @@ export interface TaskRow {stoppedBy: string;/** 结果不受免打扰和每天上限限制(用户说了做完马上告诉他) */anytime: boolean;+ /** 3f:文件夹定在什么时候清理(30 天没动、在「需要你」里告诉过用户之后);0 = 没定 */+ cleanupAt: number;createdAt: number;updatedAt: number;}@@ -373,6 +375,7 @@ const TASK_COLS: Record<string, string> = {endedAt: "ended_at",endReason: "end_reason",stoppedBy: "stopped_by",+ cleanupAt: "cleanup_at",updatedAt: "updated_at",};const RUN_COLS: Record<string, string> = {@@ -527,6 +530,8 @@ const COLUMNS: Array<[string, string, string]> = [// 规则的预算(3e):每次运行、每月["rules", "run_budget_usd", "REAL NOT NULL DEFAULT 0.1"],["rules", "month_budget_usd", "REAL NOT NULL DEFAULT 3"],+ // 保留与清理(3f):任务文件夹定在什么时候清理+ ["tasks", "cleanup_at", "INTEGER NOT NULL DEFAULT 0"],];export class Store {@@ -736,6 +741,11 @@ export class Store {const r = this.db.prepare("SELECT MAX(created_at) AS at FROM messages WHERE conversation_id = ? AND role = 'user'").get(conversationId) as Row;return Number(r?.at ?? 0) || 0;}+ /** 一条消息(任务详情里的「来自」:请求那条用户消息) */+ getMessage(id: number): Message | undefined {+ const r = this.db.prepare("SELECT id, conversation_id, role, content, created_at FROM messages WHERE id = ?").get(id) as Row | undefined;+ return r ? { id: Number(r.id), conversationId: String(r.conversation_id), role: String(r.role) as Message["role"], content: String(r.content), createdAt: Number(r.created_at) } : undefined;+ }listMessages(conversationId: string, limit = 500): Message[] {const rows = this.db.prepare(@@ -1203,11 +1213,12 @@ export class Store {endReason: String(r.end_reason),stoppedBy: String(r.stopped_by),anytime: Number(r.anytime ?? 0) === 1,+ cleanupAt: Number(r.cleanup_at ?? 0),createdAt: Number(r.created_at),updatedAt: Number(r.updated_at),};}- insertTask(t: Omit<TaskRow, "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "anytime"> & { anytime?: boolean }): TaskRow {+ insertTask(t: Omit<TaskRow, "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "anytime" | "cleanupAt"> & { anytime?: boolean }): TaskRow {this.db.prepare(`INSERT INTO tasks(id, bot_id, conversation_id, origin_message_id, origin_ref, title, brief, session_id, folder, model, permission, budget_usd, anytime, created_at, updated_at)@@ -1225,16 +1236,16 @@ export class Store {const r = this.db.prepare("SELECT * FROM tasks WHERE session_id = ?").get(sessionId) as Row | undefined;return r ? this.toTask(r) : undefined;}- updateTask(id: string, patch: Partial<Pick<TaskRow, "originRef" | "title" | "sessionId" | "model" | "budgetUsd" | "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "updatedAt">>): void {+ updateTask(id: string, patch: Partial<Pick<TaskRow, "originRef" | "title" | "sessionId" | "model" | "budgetUsd" | "spentUsd" | "report" | "endedAt" | "endReason" | "stoppedBy" | "cleanupAt" | "updatedAt">>): void {updateRow(this.db, "tasks", TASK_COLS, id, patch);}/** 任务又花了一点(每次模型请求的估算加上去) */addTaskSpent(id: string, usd: number): void {if (usd > 0) this.db.prepare("UPDATE tasks SET spent_usd = spent_usd + ? WHERE id = ?").run(usd, id);}- /** open:还没结束(停止、归档)的;since:之后更新过的 */- listTasks(opts: { botId?: string; conversationId?: string; open?: boolean; since?: number; limit?: number } = {}): TaskRow[] {- const where: string[] = [];+ /** open:还没结束(停止、归档)的;since:之后更新过的;归档了的(3f:30 天没动)不列,除非 archived */+ listTasks(opts: { botId?: string; conversationId?: string; open?: boolean; since?: number; limit?: number; archived?: boolean } = {}): TaskRow[] {+ const where: string[] = opts.archived ? [] : ["end_reason != 'archived'"];const args: Array<string | number> = [];if (opts.botId) (where.push("bot_id = ?"), args.push(opts.botId));if (opts.conversationId) (where.push("conversation_id = ?"), args.push(opts.conversationId));@@ -1443,6 +1454,34 @@ export class Store {this.db.prepare("DELETE FROM rules WHERE id = ?").run(id);}+ /** 删掉任务和它的运行记录、输入(3f:界面里的删除;文件夹由任务服务删) */+ deleteTask(id: string): void {+ this.db.prepare("DELETE FROM run_inputs WHERE task_id = ?").run(id);+ this.db.prepare("DELETE FROM runs WHERE task_id = ?").run(id);+ this.db.prepare("DELETE FROM tasks WHERE id = ?").run(id);+ }+ /** 归档的任务不会再跑:它的输入(交过的、没交的)都不要了 */+ deleteTaskInputs(taskId: string): void {+ this.db.prepare("DELETE FROM run_inputs WHERE task_id = ?").run(taskId);+ }+ /**+ * 清理旧的运行记录(3f,决定 9:留 30 天):before 之前结束的 run 删掉,连同它们的输入;每个任务最近的那个 run 留着+ * (任务的阶段看它)。会话收下过的任务输入也只留到 before。返回删了几个 run+ */+ pruneRuns(before: number): number {+ const n = Number(+ this.db+ .prepare(+ `DELETE FROM runs WHERE state = 'ended' AND MAX(queued_at, ended_at) < ? AND (rule_id != '' OR (task_id != '' AND id != (+ SELECT r2.id FROM runs r2 WHERE r2.task_id = runs.task_id ORDER BY r2.queued_at DESC, r2.rowid DESC LIMIT 1)))`,+ )+ .run(before).changes,+ );+ this.db.prepare("DELETE FROM run_inputs WHERE task_id = '' AND run_id != '' AND run_id NOT IN (SELECT id FROM runs)").run();+ this.db.prepare("DELETE FROM run_inputs WHERE task_id != '' AND taken_at > 0 AND created_at < ?").run(before);+ return n;+ }+/** 任务的会话建过(交出去过输入):之后要 resume */taskPrompted(taskId: string): boolean {return !!this.db.prepare("SELECT 1 FROM run_inputs WHERE task_id = ? AND delivered_at > 0 LIMIT 1").get(taskId);diff --git a/src/tasks/attention.ts b/src/tasks/attention.tsindex 293022d..af84098 100644--- a/src/tasks/attention.ts+++ b/src/tasks/attention.ts@@ -18,17 +18,18 @@ const log = logger("attention");/*** question / approval:在等你回答、批准(任务预算用完时的「再给 $1 继续?」也是 question);failed:任务失败了;- * rule:规则连续失败或本月预算用完(暂停了);delivery:结果没送到;login:渠道登录过期了;budget:机器人的预算留给聊天,后台工作停着+ * rule:规则连续失败或本月预算用完(暂停了);delivery:结果没送到;login:渠道登录过期了;budget:机器人的预算留给聊天,后台工作停着;+ * cleanup:任务文件夹 30 天没动过,过几天清理(3f)*/-export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget";+export type AttentionKind = "question" | "approval" | "failed" | "rule" | "delivery" | "login" | "budget" | "cleanup";/*** answer、approve、deny、retry(任务再试 / 消息再发)、stop、dismiss(不再提示)、relogin(去重新扫码)、- * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)+ * open(打开对话;budget 是打开机器人设置的预算)、continue(加预算接着做:任务 $1,规则每月 $3)、keep(保留要清理的任务文件夹)*/-export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue";+export type AttentionAction = "answer" | "approve" | "deny" | "retry" | "stop" | "dismiss" | "relogin" | "open" | "continue" | "keep";export interface AttentionItem {- /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天) */+ /** 稳定 id:approval:<id>、task:<id>、rule:<id>、delivery:<会话>:held|failed、login:<bot>:<渠道>、reserve:<bot>(预算留给聊天)、cleanup:<bot> */id: string;kind: AttentionKind;botId: string;@@ -55,7 +56,7 @@ 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 };+const ORDER: Record<AttentionKind, number> = { question: 0, approval: 0, failed: 1, rule: 1, delivery: 2, login: 3, budget: 3, cleanup: 3 };const NOTIFIED = "attention:notified";diff --git a/src/tasks/export.ts b/src/tasks/export.tsnew file mode 100644index 0000000..b981891--- /dev/null+++ b/src/tasks/export.ts@@ -0,0 +1,121 @@+/**+ * 导出成 Markdown(3f):规则的运行记录、任务的每次运行(结果、花费和折叠起来的处理过程)。+ * 给人看的文字跟着当前语言(接口用请求里的语言),时间按主人的时区写成 2026-11-01 08:00。写库、取数据的是任务服务。+ */+import type { ActivityStep } from "../agent/activity.js";+import { localParts } from "../core/quiet.js";+import { t as tr, tMaybe } from "../i18n/index.js";+import { usdText } from "./cost.js";+import type { RuleRunView, RuleView } from "./rules.js";+import type { Stage } from "./stage.js";++const pad2 = (n: number) => String(n).padStart(2, "0");+const oneLine = (s: string) => s.replace(/\s+/g, " ").trim();+const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);+/** 多行的文字放进引用块 */+const quote = (s: string) =>+ s+ .trim()+ .split("\n")+ .map((l) => `> ${l}`.trimEnd())+ .join("\n");++/** 2026-11-01 08:00(主人的时区) */+export function stampOf(ts: number, tz: string): string {+ const p = localParts(ts, tz);+ const m = Math.floor(p.minute);+ return `${p.y}-${pad2(p.mo)}-${pad2(p.d)} ${pad2(Math.floor(m / 60))}:${pad2(m % 60)}`;+}++/** 有了花费才写(不到一分钱不写) */+const cost = (usd: number) => (usd >= 0.005 ? tr("tasks.exportCost", { spent: usdText(usd) }) : "");++/** 处理过程:一步一行(工具名:命令、路径或回复开头),出错的标出来 */+export function stepLines(steps: ActivityStep[]): string[] {+ return steps.map((s) => {+ const what = clip(oneLine(s.summary || ""), 200);+ const head = what ? `${s.title}: ${what}` : s.title;+ return `- ${head}${s.status === "error" ? ` (${tr("tasks.exportStepFailed")})` : ""}`;+ });+}++export interface ExportedRuleRun extends RuleRunView {+ stepList: ActivityStep[];+}++/** 规则:标题、原话、时间表和状态、本月花费,再是运行记录(新→旧),每次一节 */+export function ruleMarkdown(rule: RuleView, when: string, runs: ExportedRuleRun[], tz: string, now: number): string {+ const words = rule.kind === "remind" ? rule.message : rule.instruction;+ const month = rule.kind === "check" ? tr("tasks.exportMonth", { spent: usdText(rule.monthUsd), budget: usdText(rule.monthBudgetUsd) }) : "";+ const out = [`# ${rule.title}`, "", quote(words), "", [when, rule.state.label, month].filter(Boolean).join(" · "), "", tr("tasks.exportedAt", { time: stampOf(now, tz) }), "", `## ${tr("tasks.exportLog")}`, ""];+ if (!runs.length) out.push(tr("tasks.exportNoRuns"), "");+ for (const r of runs) {+ const mode = rule.kind === "remind" ? "" : (tMaybe(`tasks.exportMode_${r.mode}`) ?? "");+ out.push(`### ${[stampOf(r.at, tz), mode, cost(r.costUsd)].filter(Boolean).join(" · ")}`, "", r.line, "");+ if (r.summary && oneLine(r.summary) !== oneLine(r.line)) out.push(r.summary.trim(), "");+ if (r.would) out.push(`${tr("tasks.exportWould")}: ${r.would}`, "");+ const meta = [tr("tasks.exportVersion", { n: r.version }), r.permission].filter(Boolean).join(" · ");+ if (meta) out.push(meta, "");+ if (r.stepList.length) out.push(...stepLines(r.stepList), "");+ }+ return out.join("\n").trimEnd() + "\n";+}++export interface ExportedTaskRun {+ cause: string;+ outcome: string;+ error: string;+ message: string;+ summary: string;+ question: string;+ costUsd: number;+ queuedAt: number;+ startedAt: number;+ endedAt: number;+ steps: ActivityStep[];+}++/** 一次运行的结果:给用户的那句、失败原因、问用户的问题;停下、中断等用阶段的说法 */+function outcomeLine(r: ExportedTaskRun): string {+ if (r.outcome === "done") return r.message || tr("tasks.stageReady");+ if (r.outcome === "failed") return tr("tasks.exportFailed", { why: r.message || r.error || tr("tasks.noResult") });+ if (r.outcome === "needs_you") return r.question ? tr("tasks.exportAsked", { question: r.question }) : tr("tasks.stageAnswer");+ if (r.outcome === "budget") return tr("tasks.stageBudget");+ if (r.outcome === "stopped") return tr("tasks.stageStopped");+ if (r.outcome === "interrupted") return tr("tasks.exportInterrupted");+ return r.outcome ? r.outcome : tr("tasks.stageWorking");+}++/** 任务:标题、状态和花费、来自哪里(渠道、时间、原话)、文件夹、最新进展,再是每次运行(旧→新) */+export function taskMarkdown(+ task: { title: string; stage: Stage; spentUsd: number; budgetUsd: number; folder: string; latest: string },+ origin: { channel: string; at: number; text: string } | undefined,+ runs: ExportedTaskRun[],+ tz: string,+ now: number,+): string {+ const head = [task.stage.label, tr("tasks.exportBudget", { spent: usdText(task.spentUsd), budget: usdText(task.budgetUsd) })].join(" · ");+ const out = [`# ${task.title}`, "", head, ""];+ if (origin) {+ out.push(`- ${tr("tasks.exportFrom")}: ${[origin.channel, stampOf(origin.at, tz)].filter(Boolean).join(" · ")}`);+ }+ out.push(`- ${tr("tasks.exportFolder")}: \`${task.folder}\``);+ if (task.latest) out.push(`- ${tr("tasks.exportLatest")}: ${task.latest}`);+ out.push(`- ${tr("tasks.exportedAt", { time: stampOf(now, tz) })}`, "");+ if (origin?.text) out.push(quote(origin.text), "");+ runs.forEach((r, i) => {+ const mins = r.startedAt ? Math.max(1, Math.round(((r.endedAt || now) - r.startedAt) / 60_000)) : 0;+ const cause = tMaybe(`tasks.exportCause_${r.cause}`) ?? r.cause;+ const title = [tr("tasks.exportRun", { n: i + 1 }), cause, stampOf(r.queuedAt, tz), mins ? tr("tasks.exportMinutes", { count: mins }) : "", cost(r.costUsd)].filter(Boolean).join(" · ");+ out.push(`## ${title}`, "", outcomeLine(r), "");+ if (r.summary && oneLine(r.summary) !== oneLine(r.message)) out.push(r.summary.trim(), "");+ if (r.steps.length) out.push(...stepLines(r.steps), "");+ });+ return out.join("\n").trimEnd() + "\n";+}++/** 下载时的文件名:标题里不能进文件名的字符换成 -(Content-Disposition 用 RFC 5987 编码,中文照样) */+export function exportFileName(title: string): string {+ const base = title.replace(/[\\/:*?"<>|\u0000-\u001f]+/g, "-").replace(/\s+/g, " ").trim().slice(0, 60) || "export";+ return `${base}.md`;+}diff --git a/src/tasks/retention.ts b/src/tasks/retention.tsnew file mode 100644index 0000000..ca33828--- /dev/null+++ b/src/tasks/retention.ts@@ -0,0 +1,90 @@+/**+ * 保留与清理(设计第 11 节「Disk growth」、决定 9,3f)的纯函数部分;写库、删文件的是任务服务(service.ts 的 retain)。+ *+ * - 任务和运行记录留 30 天:30 天没动过的任务归档(不再列出、不能再追加,等着的提问作废),运行记录只留 30 天+ * (每个任务最近的那个 run 留着:阶段看它)。+ * - 任务文件夹留到任务删掉为止;30 天没动过就清理,清理前先告诉用户一次(「需要你」里一行,可以保留),至少 3 天之后才删,+ * 连同 DSH 里这个任务的会话记录。文件夹是空的就不打扰,直接归档。+ * - 状态都在库里(tasks.cleanup_at、kv),重启不影响;时间都从任务服务的时钟取(测试用假时钟)。+ */+import fs from "node:fs";+import path from "node:path";++export const DAY_MS = 86_400_000;+/** 任务、运行记录、没动过的文件夹留多久 */+export const KEEP_MS = 30 * DAY_MS;+/** 删文件夹之前提前多久告诉用户(之后至少等这么久) */+export const WARN_MS = 3 * DAY_MS;+/** 多久看一次 */+export const SWEEP_MS = 3600_000;++/** 目录占多大(字节):不跟链接,最多看 limit 个条目(很大的文件夹算个大概) */+export function dirBytes(dir: string, limit = 20_000): number {+ let total = 0;+ let seen = 0;+ const walk = (d: string) => {+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(d, { withFileTypes: true });+ } catch {+ return;+ }+ for (const e of entries) {+ if (++seen > limit) return;+ const p = path.join(d, e.name);+ if (e.isDirectory()) walk(p);+ else if (e.isFile()) {+ try {+ total += fs.statSync(p).size;+ } catch {+ /* 刚被删了 */+ }+ }+ }+ };+ walk(dir);+ return total;+}++/** 目录里有没有东西(不存在、空的都算没有) */+export function hasFiles(dir: string): boolean {+ try {+ return fs.readdirSync(dir).length > 0;+ } catch {+ return false;+ }+}++/**+ * 任务会话在 DSH 里的记录:DSH_HOME/sessions/<工作目录>/<会话 id>/(dsh-session-persistence-jsonl 的布局,会话 id 里只有+ * 字母数字和 -_,目录名就是 id)。task-<id>,以及恢复不了时换过的 task-<id>-N。SDK 没有删会话的接口,宿主直接删目录。+ */+export function taskSessionDirs(home: string, taskId: string): string[] {+ const root = path.join(home, "sessions");+ const name = `task-${taskId}`;+ const out: string[] = [];+ let projects: fs.Dirent[];+ try {+ projects = fs.readdirSync(root, { withFileTypes: true });+ } catch {+ return out;+ }+ for (const p of projects) {+ if (!p.isDirectory()) continue;+ let sessions: string[];+ try {+ sessions = fs.readdirSync(path.join(root, p.name));+ } catch {+ continue;+ }+ for (const s of sessions) if (s === name || (s.startsWith(name + "-") && /^\d+$/.test(s.slice(name.length + 1)))) out.push(path.join(root, p.name, s));+ }+ return out;+}++/** 任务文件夹的绝对路径:只认工作区 tasks/ 下面的(库里的值不对就不碰) */+export function taskFolder(workspace: string, folder: string): string | undefined {+ const base = path.resolve(workspace, "tasks");+ const abs = path.resolve(workspace, folder);+ return abs.startsWith(base + path.sep) ? abs : undefined;+}diff --git a/src/tasks/service.ts b/src/tasks/service.tsindex 4b8313d..e615504 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -24,6 +24,10 @@* 推给会话、在「需要你」里,回答「继续」加预算接着做,「停止」停掉);规则每次运行 $0.10(这次以 budget 结束,算一次失败),* 每月 $3(暂停,「需要你」里一行,下个月自动恢复)。机器人有 Modelflare 预算 Key 时,剩下的不到 20% 就停后台工作,留给聊天。* 任务每次运行最多 4 小时(等人批准的时间不算),到了算失败。+ *+ * - 保留与清理(3f,决定 9,见 retention.ts):30 天没动过的任务归档、运行记录只留 30 天;任务文件夹 30 天没动过就清理,+ * 清理前在「需要你」里告诉用户一次(可以保留),连同 DSH 里的会话记录。界面里删任务也删它的文件夹。规则的运行记录、+ * 任务的每次运行可以导出成 Markdown(export.ts)。*/import crypto from "node:crypto";import fs from "node:fs";@@ -54,7 +58,7 @@ import {type Rates,} from "./cost.js";import { DEFAULT_MAX_BACKGROUND, pickRuns, priorityOf } from "./slots.js";-import { taskStage, type Stage } from "./stage.js";+import { taskStage, type Stage, type StageGroup } from "./stage.js";import { MAX_GRACE_MS, graceOf, localTime, nextRun, latestRun, parseSchedule, type Schedule } from "./schedule.js";import { Scheduler } from "./scheduler.js";import { matchesFilter, type RuleEvent } from "./rule-events.js";@@ -81,7 +85,9 @@ import {type RuleRunView,type RuleView,} from "./rules.js";-import { t as tr } from "../i18n/index.js";+import { lang, t as tr } from "../i18n/index.js";+import { KEEP_MS, SWEEP_MS, WARN_MS, dirBytes, hasFiles, taskFolder } from "./retention.js";+import { ruleMarkdown, taskMarkdown, type ExportedTaskRun } from "./export.js";const log = logger("tasks");@@ -124,6 +130,10 @@ export interface TaskHost {quiet(botId: string, sessionId: string): Promise<{ quiet: boolean; jobs?: string[] }>;/** 这个机器人的一个 run 结束了:代理进程完全空闲、开过的会话又多了,就换一个新的(host.ts restartIfStale) */runEnded?(botId: string): void;+ /** 3f:任务的会话在 DSH 里的记录占多大(字节;没有就是 0) */+ sessionBytes?(botId: string, taskId: string): number;+ /** 3f:删掉任务的会话记录(SDK 没有删会话的接口,宿主直接删目录);会话还开在当前代理进程里时不删、返回 false,下次清理再删 */+ removeSessions?(botId: string, taskId: string): boolean;}/** DSH 的一条通知(SDK 的 session.event / session.status / subagent.*) */@@ -184,6 +194,8 @@ export interface TaskView {/** 估算已花的、预算(美元) */spentUsd: number;budgetUsd: number;+ /** 3f:文件夹定在什么时候清理(30 天没动过、告诉过用户);0 = 没定 */+ cleanupAt: number;/** 正在跑的那个 run:开始时间与步数 */live?: { runId: string; since: number; steps: number; current?: ActivityStep };}@@ -259,6 +271,10 @@ export function slugOf(title: string): string {}const NOTES = "task-notes:";+/** 还没删掉的会话记录("<机器人>:<任务>",会话开在代理进程里时删不了,下次清理再删) */+const TRASH = "tasks:session-trash";+/** 「需要你」里清理文件夹那一行点过「知道了」:到哪个清理时间为止不再显示(每个机器人一个) */+const CLEANUP_SEEN = "tasks:cleanup-seen:";/** 预算用完时的回答:不要了 */const STOP_WORDS = /^(停止|停|不用了?|不要了?|算了|取消|stop|no|cancel)[。.!!]*$/i;@@ -301,6 +317,10 @@ export class TaskService {private reserveSince = new Map<string, number>();/** 刚被宿主停下的会话:取消到达之前已经发出去的那次模型请求,花费照样记到这个 run 上(几分钟内) */private halted = new Map<string, { runId: string; taskId: string; botId: string; model: string; until: number }>();+ /** 每小时看一次保留与清理(3f) */+ private retainTimer: NodeJS.Timeout | undefined;+ /** 任务文件夹、会话记录有多大(详情每几秒取一次,不用每次都数一遍) */+ private sizeCache = new Map<string, { at: number; v: { folder: number; sessions: number } }>();/** 宿主的定时器:规则到点开 run(scheduler.ts) */readonly scheduler: Scheduler;@@ -361,6 +381,11 @@ export class TaskService {clearInterval(this.capTimer);this.capTimer = setInterval(() => this.checkCaps(), this.o.capCheckMs ?? 60_000);this.capTimer.unref?.();+ // 保留与清理:启动时看一次(应用关着的这些天也算),之后每小时一次+ this.retain();+ clearInterval(this.retainTimer);+ this.retainTimer = setInterval(() => this.retain(), SWEEP_MS);+ this.retainTimer.unref?.();}/** 应用退出:不再开始新的 run;跑着的留在库里(下次启动时恢复),步骤先存下 */@@ -369,6 +394,8 @@ export class TaskService {this.scheduler.stop();clearInterval(this.capTimer);this.capTimer = undefined;+ clearInterval(this.retainTimer);+ this.retainTimer = undefined;this.unlisten?.();this.unlisten = undefined;for (const l of this.live.values()) {@@ -487,6 +514,7 @@ export class TaskService {const task = this.store.getTask(taskId);if (!task) return { error: "task not found" };if (task.endReason === "stopped") return { error: tr("tasks.stoppedNoFollowup", { title: task.title }) };+ if (task.endReason === "archived") return { error: tr("tasks.archivedNoFollowup", { title: 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" };@@ -499,6 +527,7 @@ export class TaskService {const task = this.store.getTask(taskId);if (!task) return { error: "task not found" };if (task.endReason === "stopped") return { error: tr("tasks.stoppedShort", { title: task.title }) };+ if (task.endReason === "archived") return { error: tr("tasks.archivedNoFollowup", { title: 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);@@ -1380,27 +1409,49 @@ export class TaskService {}/**- * 加预算(「需要你」里的继续、预算提问的回答、POST /tasks/:id/budget):预算加上 addUsd(加完还不够已花的,就从已花的再加);+ * 加预算(「需要你」里的继续、预算提问的回答、POST /tasks/:id/budget {addUsd}):预算加上 addUsd(加完还不够已花的,就从已花的再加);* 停在预算上的任务接着做(人的唤醒:continue run,第一条是说明),还在等的那个预算提问作废。没停的只是把预算调高。*/async addBudget(taskId: string, addUsd: number = TASK_BUDGET_STEP_USD, by = "web", text = ""): Promise<{ task?: TaskView; error?: string }> {+ const add = Number(addUsd);+ return this.changeBudget(taskId, Number.isFinite(add) && add > 0 && add <= 100, (t) => {+ const raised = t.budgetUsd + add;+ return raised > t.spentUsd ? raised : t.spentUsd + add;+ }, by, text);+ }++ /**+ * 改预算(3f:任务详情里改,POST /tasks/:id/budget {budgetUsd}):预算就是这个数,调低也行(在跑的、花到了就停下问);+ * 比已花的多、又停在预算上的,接着做(同加预算)。+ */+ async setBudget(taskId: string, budgetUsd: number, by = "web"): Promise<{ task?: TaskView; error?: string }> {+ const v = Number(budgetUsd);+ return this.changeBudget(taskId, Number.isFinite(v) && v > 0 && v <= TASK_BUDGET_MAX_USD, () => v, by, "");+ }++ private async changeBudget(taskId: string, ok: boolean, next: (t: TaskRow) => number, by: string, text: string): Promise<{ task?: TaskView; error?: string }> {const task = this.store.getTask(taskId);if (!task) return { error: "task not found" };if (task.endReason === "stopped") return { error: tr("tasks.stoppedShort", { title: task.title }) };- const add = Number(addUsd);- if (!Number.isFinite(add) || add <= 0 || add > 100) return { error: tr("tasks.badBudget") };- const raised = task.budgetUsd + add;- const budget = Math.round(Math.min(TASK_BUDGET_MAX_USD, raised > task.spentUsd ? raised : task.spentUsd + add) * 100) / 100;+ if (task.endReason === "archived") return { error: tr("tasks.archivedNoFollowup", { title: task.title }) };+ if (!ok) return { error: tr("tasks.badBudget") };+ const budget = Math.round(Math.min(TASK_BUDGET_MAX_USD, next(task)) * 100) / 100;this.store.updateTask(task.id, { budgetUsd: budget, updatedAt: this.now() });- log.info("background task budget raised", { task: task.id, budgetUsd: budget, by });- for (const r of this.o.approvals?.pendingForTask(task.id) ?? []) if (r.tool === BUDGET_TOOL) this.o.approvals!.cancel(r.id, by);- const last = this.store.latestRun(task.id);- if (last?.state === "ended" && last.outcome === "budget") {- const jobs = parseSteps(this.store.getRun(last.id)?.activity)- .filter((s) => s.kind === "job" && s.cut)- .map((s) => clip(oneLine(s.summary || s.title), 120));- const input = this.addInput(task.id, "followup", `${resumeNote("budget", jobs)}${text ? `\n\n[用户追加]\n${text.trim()}` : ""}`, true);- await this.wake(this.store.getTask(task.id)!, input, "continue");+ log.info("background task budget changed", { task: task.id, budgetUsd: budget, by });+ if (budget > task.spentUsd) {+ for (const r of this.o.approvals?.pendingForTask(task.id) ?? []) if (r.tool === BUDGET_TOOL) this.o.approvals!.cancel(r.id, by);+ const last = this.store.latestRun(task.id);+ if (last?.state === "ended" && last.outcome === "budget") {+ const jobs = parseSteps(this.store.getRun(last.id)?.activity)+ .filter((s) => s.kind === "job" && s.cut)+ .map((s) => clip(oneLine(s.summary || s.title), 120));+ const input = this.addInput(task.id, "followup", `${resumeNote("budget", jobs)}${text ? `\n\n[用户追加]\n${text.trim()}` : ""}`, true);+ await this.wake(this.store.getTask(task.id)!, input, "continue");+ }+ } else {+ // 调到已花的以下:在跑的这就停下,问要不要加+ const l = this.liveOf(task.id);+ if (l) this.checkBudgets(l);}this.changed(task.id);return { task: this.get(task.id) };@@ -1550,6 +1601,7 @@ export class TaskService {actions: ["open"],});}+ out.push(...this.cleanupAttention());return out;}@@ -1593,16 +1645,18 @@ export class TaskService {runs: this.store.listRuns({ taskId: task.id }).length,spentUsd: task.spentUsd,budgetUsd: task.budgetUsd,+ cleanupAt: task.cleanupAt,...(l && run ? { live: { runId: run.id, since: run.startedAt, steps: l.activity.steps.length, current: l.activity.steps.findLast((s) => s.status === "running") } } : {}),};}- /** 任务列表:进行中、等你的在前,再按新旧 */- list(o: { botId?: string; conversationId?: string; limit?: number; since?: number } = {}): TaskView[] {+ /** 任务列表:进行中、等你的在前,再按新旧;group 只要这几组的(GET /tasks?group=,3f)。归档了的不列 */+ list(o: { botId?: string; conversationId?: string; limit?: number; since?: number; group?: StageGroup[] } = {}): TaskView[] {const rank = { working: 0, needs: 1, ended: 2 } as const;return this.store.listTasks({ botId: o.botId, conversationId: o.conversationId, limit: 200 }).map((t) => this.view(t))+ .filter((v) => !o.group?.length || o.group.includes(v.stage.group)).filter((v) => !o.since || v.stage.group !== "ended" || v.updatedAt >= o.since).sort((a, b) => rank[a.stage.group] - rank[b.stage.group] || b.createdAt - a.createdAt).slice(0, o.limit ?? 50);@@ -1680,6 +1734,240 @@ export class TaskService {}}+ // ---------- 保留与清理、删除、导出(3f) ----------++ /**+ * 保留与清理(启动时一次,之后每小时一次;决定 9):每个没在跑的任务看它多久没动了(最近的输入、结果、改预算、保留):+ * - 不到 27 天:什么都不做(之前定了清理的取消:用户又用了它);+ * - 文件夹是空的:到 30 天归档(没什么会丢的,不打扰);+ * - 有文件、还没告诉过:定在 3 天后(且不早于第 30 天)清理,「需要你」里一行(cleanupAttention);+ * - 到了定的时间、也满 30 天了:删文件夹,归档(连同 DSH 里的会话记录)。+ * 运行记录只留 30 天(本月的规则运行留着:本月花费从它们汇总)。之前删不掉的会话记录(还开在代理进程里)再删一次。+ */+ retain(now = this.now()): void {+ if (!this.started || this.closing) return;+ this.emptyTrash();+ for (const task of this.store.listTasks({ limit: 500 })) {+ if (this.dropped.has(task.botId)) continue;+ try {+ this.retainTask(task, now);+ } catch (e) {+ log.warn("retention check failed for a task", { task: task.id, message: (e as Error).message.slice(0, 200) });+ }+ }+ const pruned = this.store.pruneRuns(Math.min(now - KEEP_MS, this.monthStart(now)));+ if (pruned) log.info("old run logs pruned", { runs: pruned });+ }++ private retainTask(task: TaskRow, now: number): void {+ const run = this.store.latestRun(task.id);+ const last = Math.max(task.updatedAt, task.endedAt, run?.endedAt ?? 0, run?.queuedAt ?? 0);+ const idle = now - last;+ if ((run && run.state !== "ended") || this.liveOf(task.id) || idle < KEEP_MS - WARN_MS) {+ if (task.cleanupAt) {+ this.store.updateTask(task.id, { cleanupAt: 0 });+ this.changed(task.id);+ }+ return;+ }+ const dir = taskFolder(this.o.host.workspace(task.botId), task.folder);+ if (!dir || !hasFiles(dir)) {+ if (idle >= KEEP_MS) this.archive(task, now);+ return;+ }+ if (!task.cleanupAt) {+ const at = Math.max(now + WARN_MS, last + KEEP_MS);+ this.store.updateTask(task.id, { cleanupAt: at });+ log.info("task folder unused for a while; telling the user before cleaning it up", { task: task.id, at: new Date(at).toISOString() });+ this.changed(task.id);+ return;+ }+ if (now < task.cleanupAt || idle < KEEP_MS) return;+ this.removeFolder(task);+ log.info("task folder cleaned up after 30 idle days", { task: task.id });+ this.archive(task, now);+ }++ /** 归档:不再列出、不能再追加;等着的提问作废,输入、DSH 里的会话记录不要了(最近的那个 run 留着,运行记录过 30 天另删) */+ private archive(task: TaskRow, now: number): void {+ for (const a of this.o.approvals?.pendingForTask(task.id) ?? []) this.o.approvals!.cancel(a.id, "archived");+ this.store.updateTask(task.id, { endedAt: task.endedAt || now, endReason: "archived", cleanupAt: 0 });+ this.store.deleteTaskInputs(task.id);+ this.trashSessions(task.botId, task.id);+ this.sizeCache.delete(task.id);+ log.info("background task archived", { task: task.id });+ this.changed(task.id);+ }++ private removeFolder(task: TaskRow): void {+ const dir = taskFolder(this.o.host.workspace(task.botId), task.folder);+ if (!dir) return;+ try {+ fs.rmSync(dir, { recursive: true, force: true });+ } catch (e) {+ log.warn("removing a task folder failed", { task: task.id, message: (e as Error).message.slice(0, 200) });+ }+ }++ /** 删掉任务在 DSH 里的会话记录;还开在代理进程里的记下来(库里),下次清理再删 */+ private trashSessions(botId: string, taskId: string): void {+ if (this.o.host.removeSessions?.(botId, taskId) !== false) return;+ const list = this.trash();+ if (!list.includes(`${botId}:${taskId}`)) this.store.setKV(TRASH, JSON.stringify([...list, `${botId}:${taskId}`].slice(-500)));+ }++ private trash(): string[] {+ try {+ const v = JSON.parse(this.store.getKV(TRASH) || "[]");+ return Array.isArray(v) ? v.map(String) : [];+ } catch {+ return [];+ }+ }++ private emptyTrash(): void {+ const list = this.trash();+ if (!list.length) return;+ const left = list.filter((k) => {+ const i = k.indexOf(":");+ return this.o.host.removeSessions?.(k.slice(0, i), k.slice(i + 1)) === false;+ });+ if (left.length !== list.length) this.store.setKV(TRASH, JSON.stringify(left));+ }++ /** 保留这个任务的文件夹(任务详情里的「保留」):从现在起再算 30 天 */+ keepFolder(taskId: string): TaskView | undefined {+ const task = this.store.getTask(taskId);+ if (!task || task.endReason === "archived") return undefined;+ this.store.updateTask(task.id, { cleanupAt: 0, updatedAt: this.now() });+ log.info("task folder kept", { task: task.id });+ this.changed(task.id);+ return this.get(task.id);+ }++ /** 「需要你」里的保留:这个机器人定了清理的文件夹都保留 */+ keepCleanup(botId: string): boolean {+ const tasks = this.store.listTasks({ botId, limit: 500 }).filter((t) => t.cleanupAt > 0);+ for (const t of tasks) this.keepFolder(t.id);+ return tasks.length > 0;+ }++ /** 「需要你」里的知道了:这一行不再显示(到时照样清理);之后又有文件夹要清理时再出现 */+ dismissCleanup(botId: string): boolean {+ const at = Math.max(0, ...this.store.listTasks({ botId, limit: 500 }).map((t) => t.cleanupAt));+ if (!at) return false;+ this.store.setKV(CLEANUP_SEEN + botId, String(at));+ this.changed(botId);+ return true;+ }++ /**+ * 「需要你」里清理文件夹那一份:一个机器人一行,「2 个任务文件夹 11月4日 删除」,第二行是哪几个任务。不推送:+ * 只在应用里(和一次系统通知)。可以保留(再算 30 天)或知道了。+ */+ private cleanupAttention(): AttentionItem[] {+ const out: AttentionItem[] = [];+ const byBot = new Map<string, TaskRow[]>();+ for (const t of this.store.listTasks({ limit: 500 })) if (t.cleanupAt > 0) byBot.set(t.botId, [...(byBot.get(t.botId) ?? []), t]);+ const l = lang();+ for (const [botId, tasks] of byBot) {+ const seen = Number(this.store.getKV(CLEANUP_SEEN + botId) || 0);+ if (tasks.every((t) => t.cleanupAt <= seen)) continue;+ const first = Math.min(...tasks.map((t) => t.cleanupAt));+ const date = new Intl.DateTimeFormat(l === "en" ? "en-US" : "zh-CN", { month: l === "en" ? "short" : "long", day: "numeric", timeZone: this.timeZone }).format(first);+ const names = tasks.slice(0, 3).map((t) => t.title);+ const titles = new Intl.ListFormat(l === "en" ? "en" : "zh-CN", { type: "conjunction" }).format(names) + (tasks.length > 3 ? "…" : "");+ out.push({+ id: `cleanup:${botId}`,+ kind: "cleanup",+ botId,+ botName: this.store.getBot(botId)?.name ?? botId,+ subject: tr("tasks.cleanupSubject", { count: tasks.length, date }),+ status: "",+ line: tr("tasks.cleanupLine", { titles }),+ since: first - WARN_MS,+ severity: "warn",+ actions: ["keep", "dismiss"],+ });+ }+ return out;+ }++ /** 删掉任务(任务详情里的删除):在跑的先停下,等着的提问、审批作废,没发出去的结果不发了,文件夹和 DSH 里的会话记录、运行记录一起删 */+ async deleteTask(taskId: string, by: string): Promise<boolean> {+ const task = this.store.getTask(taskId);+ if (!task) return false;+ if (this.liveOf(taskId) || this.queuedRun(taskId)) await this.stopTask(taskId, by);+ for (const a of this.o.approvals?.pendingForTask(taskId) ?? []) this.o.approvals!.cancel(a.id, "deleted");+ // 还排着、留着没发出去的结果不发了(「需要你」里那一行也跟着消失)+ for (const r of this.store.listRuns({ taskId })) if (r.delivery && !r.delivery.endsWith(":dropped")) this.o.delivery?.withdraw(r.delivery, tr("tasks.withdrawHandled"));+ this.removeFolder(task);+ this.trashSessions(task.botId, task.id);+ this.store.deleteTask(taskId);+ this.sizeCache.delete(taskId);+ log.info("background task deleted", { task: taskId, by });+ this.changed(taskId);+ return true;+ }++ /** 任务详情里的大小:文件夹、DSH 里的会话记录(字节;半分钟内不重数) */+ sizes(taskId: string): { folder: number; sessions: number } | undefined {+ const task = this.store.getTask(taskId);+ if (!task) return undefined;+ const now = this.now();+ const hit = this.sizeCache.get(taskId);+ if (hit && now - hit.at < 30_000) return hit.v;+ const dir = taskFolder(this.o.host.workspace(task.botId), task.folder);+ const v = { folder: dir ? dirBytes(dir) : 0, sessions: this.o.host.sessionBytes?.(task.botId, task.id) ?? 0 };+ this.sizeCache.set(taskId, { at: now, v });+ return v;+ }++ /** 任务的文件夹(绝对路径;不在工作区 tasks/ 下的不给) */+ folderPath(taskId: string): string | undefined {+ const task = this.store.getTask(taskId);+ return task ? taskFolder(this.o.host.workspace(task.botId), task.folder) : undefined;+ }++ /** 任务从哪来:渠道、请求那条消息的时间和原话 */+ origin(taskId: string): { channel: string; at: number; text: string } | undefined {+ const task = this.store.getTask(taskId);+ const m = task?.originMessageId ? this.store.getMessage(task.originMessageId) : undefined;+ if (!task || !m) return undefined;+ return { channel: this.store.getConversation(task.conversationId)?.channel ?? "", at: m.createdAt, text: clip(m.content.trim(), 500) };+ }++ /** 任务导出成 Markdown:状态、来自、文件夹、每次运行(结果、花费、处理过程) */+ exportTask(taskId: string): { title: string; text: string } | undefined {+ const task = this.store.getTask(taskId);+ if (!task) return undefined;+ const origin = this.origin(taskId);+ const ch = origin?.channel;+ const runs: ExportedTaskRun[] = this.store.listRuns({ taskId }).map((r) => ({+ cause: r.cause,+ outcome: r.state === "ended" ? r.outcome : "",+ error: r.error,+ message: r.report?.message ?? "",+ summary: r.report?.summary ?? "",+ question: r.report?.question?.question ?? "",+ costUsd: r.costUsd,+ queuedAt: r.queuedAt,+ startedAt: r.startedAt,+ endedAt: r.endedAt,+ steps: this.activity(r.id),+ }));+ const channel = ch === "weixin" ? tr("tasks.chWeixin") : ch === "feishu" ? tr("tasks.chFeishu") : ch ? tr("tasks.chWeb") : "";+ return { title: task.title, text: taskMarkdown(this.view(task), origin && { ...origin, channel }, runs, this.timeZone, this.now()) };+ }++ /** 规则的运行记录导出成 Markdown(留着的都导出:30 天) */+ exportRule(ruleId: string): { title: string; text: string } | undefined {+ const rule = this.store.getRule(ruleId);+ if (!rule) return undefined;+ const runs = this.ruleLog(ruleId, { limit: 500 }).map((r) => ({ ...r, stepList: r.steps ? this.activity(r.id) : [] }));+ return { title: rule.title, text: ruleMarkdown(this.ruleView(rule), whenOf(rule, true), runs, this.timeZone, this.now()) };+ }+// ---------- 规则(3d) ----------private get timeZone(): string {@@ -1723,7 +2011,19 @@ export class TaskService {* 新规则(聊天代理的 rule_create、界面):检查从观察开始;固定提醒没什么要判断的,直接执行(决定 6),* 不受免打扰限制(时间是用户定的)。时间表或事件触发二选一。*/- createRule(o: { botId: string; conversationId: string; title: string; instruction: string; kind?: RuleKind; message?: string; schedule?: Schedule; trigger?: RuleTrigger }): { rule?: RuleRow; error?: string } {+ createRule(o: {+ botId: string;+ conversationId: string;+ title: string;+ instruction: string;+ kind?: RuleKind;+ message?: string;+ schedule?: Schedule;+ trigger?: RuleTrigger;+ /** 3f:规则编辑器里填的每次、每月预算(不填用默认的 $0.10、$3) */+ runBudgetUsd?: number;+ monthBudgetUsd?: number;+ }): { rule?: RuleRow; error?: string } {const conv = this.store.getConversation(o.conversationId);if (!conv || conv.botId !== o.botId || !this.store.getBot(o.botId)) return { error: "conversation not found" };const kind: RuleKind = o.kind === "remind" ? "remind" : "check";@@ -1738,6 +2038,13 @@ export class TaskService {if (!trigger || (trigger.kind === "event" && !trigger.source.trim())) return { error: "schedule is required" };if (kind === "remind" && trigger.kind !== "schedule") return { error: "a reminder needs a schedule" };if (this.store.listRules({ botId: o.botId }).length >= MAX_RULES) return { error: `This bot already has ${MAX_RULES} rules; delete one first.` };+ const budgets: { runBudgetUsd?: number; monthBudgetUsd?: number } = {};+ for (const k of ["runBudgetUsd", "monthBudgetUsd"] as const) {+ if (o[k] === undefined) continue;+ const v = Number(o[k]);+ if (!Number.isFinite(v) || v <= 0 || v > TASK_BUDGET_MAX_USD) return { error: tr("tasks.badBudget") };+ budgets[k] = Math.round(v * 100) / 100;+ }const now = this.now();const id = `rl_${hex(6)}`;const mode: RuleMode = kind === "remind" ? "act" : "observe";@@ -1754,6 +2061,7 @@ export class TaskService {folder: `rules/${slugOf(title).replace(/^task$/, "rule")}-${id.slice(3, 9)}`,nextRunAt: this.nextFor({ trigger, mode, pausedReason: "" }, now),anytime: kind === "remind",+ ...budgets,createdAt: now,updatedAt: now,});diff --git a/src/web/server.ts b/src/web/server.tsindex f23fd86..8dabc7e 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -23,8 +23,10 @@ import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";import { peerName, shortPeer, whoText } from "../core/access.js";import type { AccessEntry, RuleMode } from "../store/db.js";import { normalizeSchedule, type Schedule } from "../tasks/schedule.js";+import { exportFileName } from "../tasks/export.js";+import type { StageGroup } from "../tasks/stage.js";import { GUIDE_STEPS, deriveGuide, isGuideStep, mergeGuide, normalizeGuide, type GuideState } from "../guide.js";-import { normalizeLang, requestLang, setLangPref, t, type LangPref, t as tr } from "../i18n/index.js";+import { normalizeLang, requestLang, setLangPref, t, withLang, type LangPref, t as tr } from "../i18n/index.js";const log = logger("web");const require = createRequire(import.meta.url);@@ -90,6 +92,18 @@ function send(res: http.ServerResponse, status: number, body: unknown): void {res.end(JSON.stringify(body));}+/** 下载一份 Markdown(3f 的导出):文件名用 RFC 5987 编码,中文标题照样 */+function sendMarkdown(res: http.ServerResponse, title: string, text: string): void {+ const name = exportFileName(title);+ const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/"/g, "_");+ res.writeHead(200, {+ "content-type": "text/markdown; charset=utf-8",+ "cache-control": "no-store",+ "content-disposition": `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`,+ });+ res.end(text);+}+function publicBot(b: NonNullable<ReturnType<App["store"]["getBot"]>>) {return {id: b.id,@@ -469,6 +483,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str? 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 (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 === "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;@@ -479,16 +495,20 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strapp.attention.kick();return send(res, 200, { ok: true, items: app.attention.list() });}- // —— 后台任务(3a:列表、详情、一个 run 的步骤、停止)——+ // —— 后台任务(3a:列表、详情、一个 run 的步骤、停止;3f:分组、大小、改预算、保留、打开文件夹、删除、导出)——if (seg[0] === "tasks") {if (seg.length === 1 && m === "GET") {const recent = url.searchParams.get("recent");+ // group=working|needs|ended(可以用逗号写几组):进行中、等你、结束了(归档了的不列)+ const groups = (url.searchParams.get("group") || "").split(",").map((g) => g.trim()).filter(Boolean);+ if (groups.some((g) => !["working", "needs", "ended"].includes(g))) throw new HttpError(400, tr("web.badGroup"));return send(res, 200, {tasks: app.tasks.list({botId: url.searchParams.get("bot") || undefined,conversationId: url.searchParams.get("conversation") || undefined,since: recent ? Date.now() - Math.min(30, Math.max(0, Number(recent) || 1)) * 86400_000 : undefined,limit: Math.min(100, Number(url.searchParams.get("limit")) || 50),+ group: groups as StageGroup[],}),});}@@ -498,15 +518,45 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst runs = app.store.listRuns({ taskId: task.id }).map((r) => ({ id: r.id, cause: r.cause, state: r.state, outcome: r.outcome, error: r.error, costUsd: r.costUsd, queuedAt: r.queuedAt, startedAt: r.startedAt, endedAt: r.endedAt, steps: app.tasks.activity(r.id).length }));- return send(res, 200, { task, runs });+ // 来自(渠道、时间、原话)、文件夹和会话记录的大小、能不能在系统里打开文件夹(桌面版)+ return send(res, 200, { task, runs, origin: app.tasks.origin(task.id), sizes: app.tasks.sizes(task.id), canOpen: !!app.desktop?.openPath });+ }+ // 删掉任务:在跑的先停下,文件夹、会话记录、运行记录一起删+ if (seg.length === 2 && m === "DELETE") {+ await app.tasks.deleteTask(task.id, "web");+ return send(res, 200, { ok: true });}- // 加预算(3e):{addUsd},默认 $1;停在预算上的任务接着做+ // 预算(3e、3f):{addUsd} 加多少(默认 $1),或 {budgetUsd} 改成多少;停在预算上的任务接着做if (seg.length === 3 && seg[2] === "budget" && m === "POST") {const b = await readJson(req);- const r = await app.tasks.addBudget(task.id, b.addUsd === undefined ? undefined : Number(b.addUsd), "web");+ const r =+ b.budgetUsd !== undefined+ ? await app.tasks.setBudget(task.id, Number(b.budgetUsd), "web")+ : await app.tasks.addBudget(task.id, b.addUsd === undefined ? undefined : Number(b.addUsd), "web");if (r.error) throw new HttpError(400, r.error);return send(res, 200, { task: r.task });}+ // 保留文件夹:定了清理的不清理了,从现在起再算 30 天+ if (seg.length === 3 && seg[2] === "keep" && m === "POST") {+ const v = app.tasks.keepFolder(task.id);+ if (!v) throw new HttpError(409, tr("web.couldntComplete"));+ return send(res, 200, { task: v });+ }+ // 在系统的文件管理器里打开任务文件夹(桌面版)+ if (seg.length === 3 && seg[2] === "open" && m === "POST") {+ const dir = app.tasks.folderPath(task.id);+ if (!app.desktop?.openPath) throw new HttpError(400, tr("web.desktopOnly"));+ if (!dir) throw new HttpError(404, tr("web.taskNotFound"));+ fs.mkdirSync(dir, { recursive: true });+ app.desktop.openPath(dir);+ return send(res, 200, { ok: true });+ }+ // 导出成 Markdown:?lang= 是界面的语言(下载链接带不了请求头)+ if (seg.length === 3 && seg[2] === "export" && m === "GET") {+ const r = withLang(normalizeLang(url.searchParams.get("lang")), () => app.tasks.exportTask(task.id));+ if (!r) throw new HttpError(404, tr("web.taskNotFound"));+ return sendMarkdown(res, r.title, r.text);+ }if (seg.length === 5 && seg[2] === "runs" && seg[4] === "activity" && m === "GET") {const run = app.store.getRun(decodeURIComponent(seg[3]));if (!run || run.taskId !== task.id) throw new HttpError(404, tr("web.runNotFound"));@@ -539,6 +589,8 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strkind: b.kind === "remind" ? "remind" : "check",message: String(b.message ?? ""),schedule: scheduleOf(b.schedule, app.delivery.timeZone),+ ...(b.runBudgetUsd !== undefined ? { runBudgetUsd: Number(b.runBudgetUsd) } : {}),+ ...(b.monthBudgetUsd !== undefined ? { monthBudgetUsd: Number(b.monthBudgetUsd) } : {}),});if (!r.rule) throw new HttpError(400, r.error ?? t("rules.createFailed"));return send(res, 200, { rule: app.tasks.getRuleView(r.rule.id) });@@ -577,6 +629,12 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strconst before = Number(url.searchParams.get("before")) || undefined;return send(res, 200, { runs: app.tasks.ruleLog(rule.id, { before, limit: Math.min(100, Number(url.searchParams.get("limit")) || 20) }) });}+ // 运行记录导出成 Markdown(3f)+ if (seg.length === 3 && seg[2] === "export" && m === "GET") {+ const r = withLang(normalizeLang(url.searchParams.get("lang")), () => app.tasks.exportRule(rule.id));+ if (!r) throw new HttpError(404, t("rules.notFound"));+ return sendMarkdown(res, r.title, r.text);+ }if (seg.length === 5 && seg[2] === "runs" && seg[4] === "activity" && m === "GET") {const run = app.store.getRun(decodeURIComponent(seg[3]));if (!run || run.ruleId !== rule.id) throw new HttpError(404, t("rules.runNotFound"));diff --git a/test/retention.unit.test.ts b/test/retention.unit.test.tsnew file mode 100644index 0000000..d74dbbd--- /dev/null+++ b/test/retention.unit.test.ts@@ -0,0 +1,373 @@+/**+ * 保留与清理、删除、导出、改预算(3f):TaskService 对着假宿主和假时钟。+ * 30 天没动过的任务归档(不再列出、不能追加,等着的提问作废);运行记录只留 30 天(任务最近的那个 run 和本月的规则运行留着);+ * 有文件的文件夹第 27 天在「需要你」里说一次(不推送),至少 3 天后、满 30 天才删,连同 DSH 里的会话记录(开在代理进程里的下次再删);+ * 保留、又用了它都会重新算;知道了只是不再显示。状态都在库里:重启、应用关了很久都照样。删任务删文件夹。导出成 Markdown。+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { TaskService, type TaskHost } from "../src/tasks/service.js";+import { DAY_MS, KEEP_MS, WARN_MS, dirBytes, taskSessionDirs } from "../src/tasks/retention.js";+import { exportFileName, ruleMarkdown, stampOf } from "../src/tasks/export.js";+import { ApprovalCenter } from "../src/agent/approvals.js";+import { DEFAULT_SETTINGS } from "../src/agent/settings.js";+import { Outbox } from "../src/core/outbox.js";+import { Delivery } from "../src/core/delivery.js";+import { Store, type RunOutcome } from "../src/store/db.js";++const TZ = "Asia/Shanghai";+const at = (s: string) => Date.parse(`${s}${s.length === 16 ? ":00" : ""}+08:00`);+const flush = async (n = 6) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setImmediate(r));+};++/** 假的宿主:工作区和 DSH 主目录在临时目录里;open 是开在代理进程里的会话(删不了) */+class FakeHost implements TaskHost {+ available = true;+ prompts: Array<{ sessionId: string; text: string }> = [];+ stops: string[] = [];+ open = new Set<string>();+ constructor(readonly ws: string, readonly home: string) {}+ workspace() {+ return this.ws;+ }+ settings() {+ return { ...DEFAULT_SETTINGS };+ }+ memoryPrefix() {+ return "";+ }+ async prompt(_botId: string, o: { sessionId: string; text: string }) {+ this.prompts.push({ sessionId: o.sessionId, text: o.text });+ return `msg-${this.prompts.length}`;+ }+ async steer() {+ return false;+ }+ async stop(_botId: string, sessionId: string) {+ this.stops.push(sessionId);+ }+ async cancel() {}+ async quiet() {+ return { quiet: true };+ }+ sessionBytes(_botId: string, taskId: string) {+ return taskSessionDirs(this.home, taskId).reduce((n, d) => n + dirBytes(d), 0);+ }+ removeSessions(_botId: string, taskId: string) {+ if ([...this.open].some((s) => s.startsWith(`task-${taskId}`))) return false;+ for (const d of taskSessionDirs(this.home, taskId)) fs.rmSync(d, { recursive: true, force: true });+ return true;+ }+}++describe("保留与清理(假宿主、假时钟)", () => {+ let store: Store;+ let host: FakeHost;+ let outbox: Outbox;+ let approvals: ApprovalCenter;+ let svc: TaskService;+ let tmp: string;+ let now: number;+ const CONV = "b:weixin:owner";++ const make = () =>+ new TaskService({ store, host, delivery: new Delivery({ store, outbox, now: () => now, timeZone: TZ }), approvals, defaultModel: () => "m", maxBackground: 4, now: () => now, timeZone: TZ, retryDelaysMs: [5, 5, 5] });+ beforeEach(() => {+ now = at("2026-11-01T10:00");+ tmp = fs.mkdtempSync(path.join(os.tmpdir(), "amb-retention-unit-"));+ fs.mkdirSync(path.join(tmp, "ws"));+ store = new Store(":memory:");+ store.createBot({ id: "b", name: "小蓝", weixinEnabled: true });+ store.ensureConversation("b", "weixin", "owner", "owner");+ store.addMessage(CONV, "user", "帮我后台调研一下三家云的 GPU 价格");+ host = new FakeHost(path.join(tmp, "ws"), path.join(tmp, "dsh"));+ outbox = new Outbox(store, { now: () => now });+ approvals = new ApprovalCenter(store, { now: () => now });+ svc = make();+ svc.start();+ });+ afterEach(() => {+ svc.stop();+ store.close();+ fs.rmSync(tmp, { recursive: true, force: true });+ });++ /** 一个做完了的任务(结束于 endAt),文件夹里有 files 个文件,DSH 里有它的会话记录 */+ const ended = (title: string, endAt: number, o: { files?: number; outcome?: RunOutcome; sessions?: string[] } = {}) => {+ const id = `t_${Math.random().toString(16).slice(2, 14).padEnd(12, "0")}`;+ const folder = `tasks/task-${id.slice(2, 8)}`;+ const origin = store.listMessages(CONV).at(-1)!;+ store.insertTask({ id, botId: "b", conversationId: CONV, originMessageId: origin.id, originRef: "", title, brief: "b", sessionId: `task-${id}`, folder, model: "m", permission: "workspace", budgetUsd: 1, createdAt: endAt - 3600_000, updatedAt: endAt });+ const outcome = o.outcome ?? "done";+ store.insertRun({ id: `r_${id.slice(2)}`, botId: "b", taskId: id, sessionId: `task-${id}`, cause: "launch", queuedAt: endAt - 3600_000 });+ store.updateRun(`r_${id.slice(2)}`, { state: "ended", outcome, startedAt: endAt - 3600_000, endedAt: endAt, costUsd: 0.08, delivery: `task:${id}:x:dropped`, report: { state: outcome === "done" ? "done" : "failed", summary: "查了三家", message: "A100 最便宜的是 X 云", at: endAt } });+ const report = { state: outcome === "done" ? ("done" as const) : ("failed" as const), summary: "查了三家", message: "A100 最便宜的是 X 云", at: endAt };+ store.updateTask(id, outcome === "done" ? { endedAt: endAt, endReason: "done", spentUsd: 0.08, report } : { spentUsd: 0.08, report });+ const dir = path.join(host.ws, folder);+ fs.mkdirSync(dir, { recursive: true });+ for (let i = 0; i < (o.files ?? 0); i++) fs.writeFileSync(path.join(dir, `f${i}.txt`), "x".repeat(1000));+ for (const s of o.sessions ?? [`task-${id}`]) {+ const sd = path.join(host.home, "sessions", "--ws-tasks--", s);+ fs.mkdirSync(sd, { recursive: true });+ fs.writeFileSync(path.join(sd, "v4.jsonl"), "{}\n".repeat(100));+ }+ return id;+ };+ const cleanupItems = () => svc.attention().filter((i) => i.kind === "cleanup");+ const sessionDirs = (id: string) => taskSessionDirs(host.home, id).length;++ it("没文件的任务:30 天没动过就归档(不再列出、不能追加、会话记录删掉),不打扰用户;运行记录只留 30 天,最近的那个留着", async () => {+ const t = ended("整理下载目录", now);+ store.insertRun({ id: "r_old", botId: "b", taskId: t, sessionId: `task-${t}`, cause: "followup", queuedAt: now - 40 * DAY_MS });+ store.updateRun("r_old", { state: "ended", outcome: "done", endedAt: now - 40 * DAY_MS });+ expect(svc.list().map((x) => x.id)).toEqual([t]);+ now += KEEP_MS - DAY_MS;+ svc.retain();+ expect(store.getTask(t)!.endReason).toBe("done");+ expect(store.getRun("r_old")).toBeUndefined();+ expect(cleanupItems()).toEqual([]);+ now += DAY_MS;+ svc.retain();+ expect(store.getTask(t)).toMatchObject({ endReason: "archived", cleanupAt: 0 });+ expect(svc.list()).toEqual([]);+ expect(svc.get(t)!.stage.key).toBe("ready");+ expect(store.listRuns({ taskId: t })).toHaveLength(1);+ expect(sessionDirs(t)).toBe(0);+ expect((await svc.message(t, "再看看")).error).toBe("「整理下载目录」已归档,不能再追加;需要的话开个新任务。");+ expect((await svc.retry(t)).error).toMatch(/已归档/);+ expect(cleanupItems()).toEqual([]);+ });++ it("有文件的文件夹:第 27 天在「需要你」里说一次(不推送),满 30 天删掉文件夹和会话记录、归档;等着的提问作废", async () => {+ const t = ended("GPU 价格调研", now, { files: 3, outcome: "failed", sessions: [] });+ // 换过一次会话(task-<id>-2):两份记录都要删+ for (const s of [`task-${t}`, `task-${t}-2`]) (fs.mkdirSync(path.join(host.home, "sessions", "--p--", s), { recursive: true }), fs.writeFileSync(path.join(host.home, "sessions", "--p--", s, "v4.jsonl"), "{}\n"));+ // 别的任务的记录不碰+ fs.mkdirSync(path.join(host.home, "sessions", "--p--", `task-${t}x`), { recursive: true });+ approvals.create({ kind: "question", botId: "b", conversationId: CONV, sessionId: `task-${t}`, tool: "task_report", detail: "要不要再查一家?", reason: "", payload: JSON.stringify([{ id: "answer", question: "要不要再查一家?" }]), taskId: t, runId: "", blocking: false, ttlMs: 0 });+ now += KEEP_MS - WARN_MS - 3600_000;+ svc.retain();+ expect(store.getTask(t)!.cleanupAt).toBe(0);+ now += 3600_000;+ svc.retain();+ const due = store.getTask(t)!.cleanupAt;+ expect(due).toBe(now + WARN_MS);+ expect(svc.get(t)!.cleanupAt).toBe(due);+ expect(cleanupItems()).toEqual([+ expect.objectContaining({ id: "cleanup:b", kind: "cleanup", botName: "小蓝", subject: "1 个任务文件夹 12月1日 删除", line: "GPU 价格调研 · 30 天没动过", severity: "warn", actions: ["keep", "dismiss"], since: now }),+ ]);+ // 只在应用里:出站队列里没有它+ expect(store.listOutbox({ limit: 100 }).filter((r) => r.id.includes("cleanup"))).toEqual([]);+ // 再看一次:不会再定一次+ now += DAY_MS;+ svc.retain();+ expect(store.getTask(t)!.cleanupAt).toBe(due);+ expect(fs.existsSync(path.join(host.ws, store.getTask(t)!.folder))).toBe(true);+ now = due;+ svc.retain();+ expect(store.getTask(t)!.endReason).toBe("archived");+ expect(fs.existsSync(path.join(host.ws, store.getTask(t)!.folder))).toBe(false);+ expect(taskSessionDirs(host.home, t)).toEqual([]);+ expect(fs.existsSync(path.join(host.home, "sessions", "--p--", `task-${t}x`))).toBe(true);+ expect(approvals.pendingForTask(t)).toEqual([]);+ expect(cleanupItems()).toEqual([]);+ expect(svc.attention().filter((i) => i.taskId === t)).toEqual([]);+ });++ it("保留:再算 30 天;定了清理之后又用了它(追加、改预算),清理取消", async () => {+ const a = ended("A", now, { files: 1 });+ const b = ended("B", now, { files: 1 });+ now += KEEP_MS - WARN_MS;+ svc.retain();+ expect(cleanupItems()[0].subject).toBe("2 个任务文件夹 12月1日 删除");+ expect(cleanupItems()[0].line).toBe("A和B · 30 天没动过");+ expect(svc.keepCleanup("b")).toBe(true);+ expect(store.getTask(a)!.cleanupAt).toBe(0);+ expect(cleanupItems()).toEqual([]);+ now += WARN_MS + DAY_MS;+ svc.retain();+ expect(store.getTask(a)).toMatchObject({ endReason: "done", cleanupAt: 0 });+ // 又过了 27 天:再说一次+ now += KEEP_MS - WARN_MS;+ svc.retain();+ expect(store.getTask(a)!.cleanupAt).toBeGreaterThan(now);+ // 用了它:改预算(任务详情)→ 下次看时清理取消,那一行跟着消失+ await svc.setBudget(a, 3);+ await svc.setBudget(b, 3);+ svc.retain();+ expect([store.getTask(a)!.cleanupAt, store.getTask(b)!.cleanupAt]).toEqual([0, 0]);+ expect(cleanupItems()).toEqual([]);+ });++ it("知道了:这一行不再显示,到时照样清理;之后又有文件夹要清理时再出现", async () => {+ const a = ended("A", now, { files: 1 });+ now += KEEP_MS - WARN_MS;+ svc.retain();+ expect(svc.dismissCleanup("b")).toBe(true);+ expect(cleanupItems()).toEqual([]);+ const b = ended("B", now - (KEEP_MS - WARN_MS) + DAY_MS, { files: 1 });+ now += DAY_MS;+ svc.retain();+ expect(cleanupItems().map((i) => i.subject)).toEqual(["2 个任务文件夹 12月1日 删除"]);+ now = store.getTask(a)!.cleanupAt;+ svc.retain();+ expect(store.getTask(a)!.endReason).toBe("archived");+ expect(store.getTask(b)!.endReason).toBe("done");+ });++ it("重启和应用关了很久:告诉过的记在库里;关了 60 天也要先说一次、至少 3 天后才删", async () => {+ const t = ended("GPU 价格调研", now, { files: 2 });+ now += 60 * DAY_MS;+ svc.stop();+ svc = make();+ svc.start();+ const due = store.getTask(t)!.cleanupAt;+ expect(due).toBe(now + WARN_MS);+ expect(fs.existsSync(path.join(host.ws, store.getTask(t)!.folder))).toBe(true);+ // 重启:不会再定一次,「需要你」那一行还在+ now += DAY_MS;+ svc.stop();+ svc = make();+ svc.start();+ expect(store.getTask(t)!.cleanupAt).toBe(due);+ expect(cleanupItems()).toHaveLength(1);+ // 关着过了清理时间:下次启动时删+ svc.stop();+ now = due + 10 * DAY_MS;+ svc = make();+ svc.start();+ expect(store.getTask(t)!.endReason).toBe("archived");+ expect(fs.existsSync(path.join(host.ws, store.getTask(t)!.folder))).toBe(false);+ });++ it("会话还开在代理进程里:先不删,记在库里,重启后(代理进程换过)再删", async () => {+ const t = ended("A", now);+ host.open.add(`task-${t}`);+ now += KEEP_MS;+ svc.retain();+ expect(store.getTask(t)!.endReason).toBe("archived");+ expect(sessionDirs(t)).toBe(1);+ svc.stop();+ host.open.clear();+ svc = make();+ svc.start();+ expect(sessionDirs(t)).toBe(0);+ expect(store.getKV("tasks:session-trash")).toBe("[]");+ });++ it("规则的运行记录留 30 天,本月的留着(本月花费从它们汇总)", async () => {+ const r = svc.createRule({ botId: "b", conversationId: CONV, title: "看 X 价格", instruction: "看看 X 的价格", schedule: { kind: "daily", time: "08:00", tz: TZ } }).rule!;+ const run = (id: string, q: number, cost = 0.02) => {+ store.insertEndedRun({ id, botId: "b", ruleId: r.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "done", error: "", queuedAt: q, endedAt: q + 60_000 });+ store.updateRun(id, { costUsd: cost });+ };+ now = at("2026-12-31T10:00");+ run("r_dec1", at("2026-12-01T08:00"));+ run("r_nov30", at("2026-11-30T08:00"));+ run("r_oct", at("2026-10-15T08:00"));+ svc.retain();+ expect(store.ruleRuns(r.id, { limit: 10 }).map((x) => x.id)).toEqual(["r_dec1"]);+ expect(svc.getRuleView(r.id)!.monthUsd).toBeCloseTo(0.02);+ now = at("2027-01-02T10:00");+ svc.retain();+ expect(store.ruleRuns(r.id, { limit: 10 })).toEqual([]);+ });++ it("删任务:在跑的先停下,文件夹、会话记录、运行记录一起删", async () => {+ const r = svc.create({ botId: "b", conversationId: CONV, title: "季度报告", brief: "做个季度报告" });+ const t = r.task!;+ await flush();+ fs.writeFileSync(path.join(host.ws, t.folder, "deck.pptx"), "x".repeat(2048));+ fs.mkdirSync(path.join(host.home, "sessions", "--p--", t.sessionId), { recursive: true });+ fs.writeFileSync(path.join(host.home, "sessions", "--p--", t.sessionId, "v4.jsonl"), "x".repeat(512));+ expect(svc.sizes(t.id)).toEqual({ folder: 2048, sessions: 512 });+ expect(svc.get(t.id)!.stage.group).toBe("working");+ expect(await svc.deleteTask(t.id, "web")).toBe(true);+ expect(host.stops).toEqual([t.sessionId]);+ expect(store.getTask(t.id)).toBeUndefined();+ expect(store.listRuns({ taskId: t.id })).toEqual([]);+ expect(fs.existsSync(path.join(host.ws, t.folder))).toBe(false);+ expect(sessionDirs(t.id)).toBe(0);+ expect(await svc.deleteTask(t.id, "web")).toBe(false);+ });++ it("改预算:调高;停在预算上的,改到已花的以上就接着做;不对的金额不收", async () => {+ const t = ended("季度报告 PPT", now, { outcome: "budget" });+ store.updateTask(t, { spentUsd: 1, budgetUsd: 1 });+ expect(svc.get(t)!.stage.key).toBe("needs-you/budget");+ expect((await svc.setBudget(t, 0)).error).toBe("金额不对");+ expect((await svc.setBudget(t, 5000)).error).toBe("金额不对");+ // 调到已花的以下:只改数,不接着做+ expect((await svc.setBudget(t, 0.5)).task).toMatchObject({ budgetUsd: 0.5, stage: { key: "needs-you/budget" } });+ const r = await svc.setBudget(t, 2.5);+ expect(r.task).toMatchObject({ budgetUsd: 2.5 });+ expect(store.listRuns({ taskId: t }).at(-1)).toMatchObject({ cause: "continue" });+ expect((await svc.addBudget(t, 1)).task!.budgetUsd).toBe(3.5);+ });++ it("导出:规则的运行记录、任务的每次运行(Markdown)", async () => {+ const t = ended("GPU 价格调研", at("2026-11-01T10:00"));+ store.updateRun(`r_${t.slice(2)}`, { activity: JSON.stringify([{ id: "1", kind: "tool", title: "bash", summary: "curl -s x.example/prices", status: "ok", at: 0 }, { id: "2", kind: "tool", title: "read", summary: "b.html", status: "error", at: 0 }]) });+ expect(svc.exportTask(t)!.text).toBe(+ [+ "# GPU 价格调研",+ "",+ "已完成 · 约 $0.08 / $1.00",+ "",+ `- 来自: 微信 · ${stampOf(store.listMessages(CONV).at(-1)!.createdAt, TZ)}`,+ `- 文件夹: \`tasks/task-${t.slice(2, 8)}\``,+ "- 最新进展: A100 最便宜的是 X 云",+ "- 导出于 2026-11-01 10:00",+ "",+ "> 帮我后台调研一下三家云的 GPU 价格",+ "",+ "## 第 1 次 · 开始 · 2026-11-01 09:00 · 60 分钟 · 约 $0.08",+ "",+ "A100 最便宜的是 X 云",+ "",+ "查了三家",+ "",+ "- bash: curl -s x.example/prices",+ "- read: b.html (出错)",+ "",+ ].join("\n"),+ );+ const rule = svc.createRule({ botId: "b", conversationId: CONV, title: "看 X 价格", instruction: "每天早上看看 X 的价格,降到 200 以下告诉我", schedule: { kind: "daily", time: "08:00", tz: TZ } }).rule!;+ store.insertEndedRun({ id: "r_x1", botId: "b", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "done", error: "", queuedAt: at("2026-11-01T08:00"), endedAt: at("2026-11-01T08:01") });+ store.updateRun("r_x1", { costUsd: 0.03, permission: "read-only", report: { state: "done", summary: "X 现在 ¥199", message: "X 降价了,现在 ¥199", at: 0 } });+ store.insertEndedRun({ id: "r_x0", botId: "b", ruleId: rule.id, ruleVersion: 1, mode: "observe", cause: "schedule", outcome: "skipped", error: "app_off", queuedAt: at("2026-10-31T08:00"), endedAt: at("2026-10-31T08:00") });+ expect(svc.exportRule(rule.id)!.text).toBe(+ [+ "# 看 X 价格",+ "",+ "> 每天早上看看 X 的价格,降到 200 以下告诉我",+ "",+ "每天 08:00(Asia/Shanghai) · 观察中 · 本月 约 $0.03 / $3.00",+ "",+ "导出于 2026-11-01 10:00",+ "",+ "## 运行记录",+ "",+ "### 2026-11-01 08:00 · 观察 · 约 $0.03",+ "",+ "本会发送:“X 降价了,现在 ¥199”",+ "",+ "X 现在 ¥199",+ "",+ "第 1 版 · 只读",+ "",+ "### 2026-10-31 08:00 · 观察",+ "",+ "跳过:电脑没开",+ "",+ "第 1 版",+ "",+ ].join("\n"),+ );+ expect(exportFileName("看 X 价格/每天")).toBe("看 X 价格-每天.md");+ expect(ruleMarkdown(svc.getRuleView(rule.id)!, "w", [], TZ, now)).toContain("还没有运行过。");+ });+});diff --git a/test/tasks-view.e2e.test.ts b/test/tasks-view.e2e.test.tsnew file mode 100644index 0000000..f90baef--- /dev/null+++ b/test/tasks-view.e2e.test.ts@@ -0,0 +1,152 @@+/**+ * 任务视图的接口(3f):真实的 App 和本机服务(代理关着,任务和规则直接写库)。+ * GET /tasks?group= 按进行中 / 等你 / 结束了分组(归档了的不列,组名不对 400);详情里有来自、大小;改预算(加多少、改成多少、+ * 不对的金额、停了的任务);删除连同文件夹;保留文件夹(详情里、「需要你」里);打开文件夹只在桌面版;规则编辑器的预算;+ * 规则运行记录和任务导出成 Markdown(下载的文件名、按 ?lang= 的语言)。+ */+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { App } from "../src/app.js";+import { loadConfig } from "../src/config.js";+import type { RunOutcome } from "../src/store/db.js";+import { mockOpenAI } from "./helpers.js";++const CONV = "default:weixin:[email protected]";+let app: App;+let llm: Awaited<ReturnType<typeof mockOpenAI>>;+let dataDir = "";+let base = "";++async function api(p: string, init: { method?: string; body?: unknown; lang?: string } = {}): Promise<{ status: number; data: any }> {+ const res = await fetch(`${base}/amb/api${p}`, {+ method: init.method ?? "GET",+ headers: { ...(init.body !== undefined ? { "content-type": "application/json" } : {}), ...(init.lang ? { "x-amb-lang": init.lang } : {}) },+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,+ });+ return { status: res.status, data: await res.json().catch(() => ({})) };+}++/** 一个任务:最近的 run 是 state / outcome(queued = 在排队) */+function task(title: string, outcome: RunOutcome | "queued", o: { endReason?: string } = {}): string {+ const id = `t_${Math.random().toString(16).slice(2, 14).padEnd(12, "0")}`;+ const now = Date.now();+ const origin = app.store.addMessage(CONV, "user", `帮我做${title}`);+ app.store.insertTask({ id, botId: "default", conversationId: CONV, originMessageId: origin, originRef: "", title, brief: title, sessionId: `task-${id}`, folder: `tasks/task-${id.slice(2, 8)}`, model: "m", permission: "workspace", budgetUsd: 1, createdAt: now, updatedAt: now });+ app.store.insertRun({ id: `r_${id.slice(2)}`, botId: "default", taskId: id, sessionId: `task-${id}`, cause: "launch", queuedAt: now });+ if (outcome !== "queued") app.store.updateRun(`r_${id.slice(2)}`, { state: "ended", outcome, startedAt: now, endedAt: now, delivery: `task:${id}:x:dropped` });+ if (outcome === "done" || o.endReason) app.store.updateTask(id, { endedAt: now, endReason: o.endReason ?? "done" });+ fs.mkdirSync(path.join(dataDir, "workspaces", "default", app.store.getTask(id)!.folder), { recursive: true });+ return id;+}++beforeAll(async () => {+ llm = await mockOpenAI({ key: "gw-key" });+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-tasks-view-e2e-"));+ const config = loadConfig({ dataDir, env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: "gw-key", AMB_UI_PORT: "0", AMB_AGENT: "off" } });+ app = new App(config, { printQrToTerminal: false, timeZone: "Asia/Shanghai" });+ await app.start();+ base = app.web!.url.replace(/\/+$/, "");+ app.store.ensureConversation("default", "weixin", "[email protected]", "owner");+});++afterAll(async () => {+ await app?.stop();+ await llm?.close();+ fs.rmSync(dataDir, { recursive: true, force: true });+});++describe("任务视图的接口", () => {+ let working = "";+ let failed = "";+ let budget = "";+ let done = "";+ let stopped = "";+ beforeAll(() => {+ working = task("GPU 价格调研", "queued");+ failed = task("季度报告", "failed");+ budget = task("季度报告 PPT", "budget");+ done = task("整理下载目录", "done");+ stopped = task("清理旧构建", "stopped", { endReason: "stopped" });+ task("去年的任务", "done", { endReason: "archived" });+ });++ it("GET /tasks?group=:进行中、等你、结束了;几组用逗号;归档了的不列;组名不对 400", async () => {+ const ids = async (q: string) => (await api(`/tasks?bot=default${q}`)).data.tasks.map((t: any) => t.id).sort();+ expect(await ids("&group=working")).toEqual([working]);+ expect(await ids("&group=needs")).toEqual([failed, budget].sort());+ expect(await ids("&group=ended")).toEqual([done, stopped].sort());+ expect(await ids("&group=working,needs")).toEqual([working, failed, budget].sort());+ expect(await ids("")).toEqual([working, failed, budget, done, stopped].sort());+ const groups = (await api("/tasks?bot=default")).data.tasks.map((t: any) => t.stage.group);+ expect(groups).toEqual(["working", "needs", "needs", "ended", "ended"]);+ const bad = await api("/tasks?group=archived");+ expect(bad).toEqual({ status: 400, data: { error: "分组只能是 working、needs 或 ended" } });+ expect((await api("/tasks?group=x", { lang: "en" })).data.error).toBe("group must be working, needs or ended");+ });++ it("GET /tasks/:id:来自(渠道、时间、原话)、文件夹和会话记录的大小;打开文件夹只在桌面版", async () => {+ const dir = path.join(dataDir, "workspaces", "default", app.store.getTask(done)!.folder);+ fs.writeFileSync(path.join(dir, "list.txt"), "x".repeat(1500));+ const { data } = await api(`/tasks/${done}`);+ expect(data.origin).toMatchObject({ channel: "weixin", text: "帮我做整理下载目录" });+ expect(data.sizes).toEqual({ folder: 1500, sessions: 0 });+ expect(data.canOpen).toBe(false);+ expect(data.task).toMatchObject({ id: done, cleanupAt: 0, stage: { key: "ready" } });+ expect((await api(`/tasks/${done}/open`, { method: "POST", body: {} })).status).toBe(400);+ });++ it("POST /tasks/:id/budget:{budgetUsd} 改成多少、{addUsd} 加多少;停在预算上的接着排;金额不对、停了的 400", async () => {+ expect((await api(`/tasks/${working}/budget`, { method: "POST", body: { budgetUsd: 3 } })).data.task).toMatchObject({ budgetUsd: 3 });+ expect((await api(`/tasks/${working}/budget`, { method: "POST", body: { addUsd: 1.5 } })).data.task).toMatchObject({ budgetUsd: 4.5 });+ expect(await api(`/tasks/${working}/budget`, { method: "POST", body: { budgetUsd: -1 } })).toEqual({ status: 400, data: { error: "金额不对" } });+ expect((await api(`/tasks/${working}/budget`, { method: "POST", body: { budgetUsd: "abc" } })).status).toBe(400);+ expect((await api(`/tasks/${stopped}/budget`, { method: "POST", body: { budgetUsd: 2 } })).data.error).toBe("「清理旧构建」已停止");+ app.store.updateTask(budget, { spentUsd: 1 });+ const r = await api(`/tasks/${budget}/budget`, { method: "POST", body: { budgetUsd: 2 } });+ expect(r.data.task).toMatchObject({ budgetUsd: 2, stage: { group: "working" } });+ expect(app.store.listRuns({ taskId: budget }).at(-1)).toMatchObject({ cause: "continue", state: "queued" });+ expect((await api(`/tasks/nope/budget`, { method: "POST", body: { addUsd: 1 } })).status).toBe(404);+ });++ it("保留文件夹:详情里的保留、「需要你」里的保留和知道了", async () => {+ app.store.updateTask(done, { cleanupAt: Date.now() + 3 * 86400_000 });+ const item = (await api("/attention")).data.items.find((i: any) => i.id === "cleanup:default");+ expect(item).toMatchObject({ kind: "cleanup", actions: ["keep", "dismiss"], line: "整理下载目录 · 30 天没动过" });+ expect((await api("/attention/cleanup:default/dismiss", { method: "POST", body: {} })).data.items.find((i: any) => i.kind === "cleanup")).toBeUndefined();+ app.store.updateTask(failed, { cleanupAt: Date.now() + 4 * 86400_000 });+ expect((await api("/attention")).data.items.filter((i: any) => i.kind === "cleanup")).toHaveLength(1);+ await api("/attention/cleanup:default/keep", { method: "POST", body: {} });+ expect([app.store.getTask(done)!.cleanupAt, app.store.getTask(failed)!.cleanupAt]).toEqual([0, 0]);+ app.store.updateTask(done, { cleanupAt: Date.now() + 86400_000 });+ expect((await api(`/tasks/${done}/keep`, { method: "POST", body: {} })).data.task).toMatchObject({ cleanupAt: 0 });+ });++ it("导出:任务和规则的运行记录是 Markdown 下载,按 ?lang= 的语言", async () => {+ const res = await fetch(`${base}/amb/api/tasks/${done}/export?lang=en`);+ expect(res.headers.get("content-type")).toBe("text/markdown; charset=utf-8");+ expect(res.headers.get("content-disposition")).toBe(`attachment; filename="______.md"; filename*=UTF-8''${encodeURIComponent("整理下载目录.md")}`);+ const md = await res.text();+ expect(md).toMatch(/^# 整理下载目录\n\nDone · about \$0\.00 of \$1\.00\n\n- From: WeChat · \d{4}-\d\d-\d\d \d\d:\d\d\n/);+ expect(md).toContain("## Run 1 · Started · ");+ const rule = (await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "看 X 价格", instruction: "每天早上看看 X 的价格", schedule: { kind: "daily", time: "08:00" }, runBudgetUsd: 0.2, monthBudgetUsd: 5 } })).data.rule;+ expect(rule).toMatchObject({ runBudgetUsd: 0.2, monthBudgetUsd: 5, mode: "observe" });+ expect((await api(`/rules/${rule.id}`, { method: "PUT", body: { runBudgetUsd: 0.15, monthBudgetUsd: 4 } })).data.rule).toMatchObject({ runBudgetUsd: 0.15, monthBudgetUsd: 4 });+ expect((await api("/rules", { method: "POST", body: { botId: "default", conversationId: CONV, kind: "check", title: "x", instruction: "x", schedule: { kind: "daily", time: "08:00" }, monthBudgetUsd: 0 } })).status).toBe(400);+ const zh = await (await fetch(`${base}/amb/api/rules/${rule.id}/export`)).text();+ expect(zh).toMatch(/^# 看 X 价格\n\n> 每天早上看看 X 的价格\n\n每天 08:00(Asia\/Shanghai) · 观察中 · 本月 约 \$0\.00 \/ \$4\.00\n\n导出于 .+\n\n## 运行记录\n\n还没有运行过。\n$/);+ const en = await (await fetch(`${base}/amb/api/rules/${rule.id}/export?lang=en`)).text();+ expect(en).toContain("## Run log");+ });++ it("DELETE /tasks/:id:任务、运行记录和文件夹一起删", async () => {+ const dir = path.join(dataDir, "workspaces", "default", app.store.getTask(failed)!.folder);+ fs.writeFileSync(path.join(dir, "a.txt"), "a");+ expect(await api(`/tasks/${failed}`, { method: "DELETE" })).toEqual({ status: 200, data: { ok: true } });+ expect(app.store.getTask(failed)).toBeUndefined();+ expect(app.store.listRuns({ taskId: failed })).toEqual([]);+ expect(fs.existsSync(dir)).toBe(false);+ expect((await api(`/tasks/${failed}`)).status).toBe(404);+ });+});diff --git a/ui/components/rules.js b/ui/components/rules.jsindex ee43b96..d8f06d3 100644--- a/ui/components/rules.js+++ b/ui/components/rules.js@@ -1,6 +1,7 @@// 规则(3d):信息面板「任务」组里一条规则一行——时间表 · 标题,下面一行是状态和下次运行;观察了 3 次的,行里多一句// 「已观察 3 次 · 改为执行?」(只在这里,从不推送)。点开是规则的详情:用户的原话、模式(观察 / 执行 / 关)、立即运行、编辑、删除,-// 和运行记录(一次一行:时间 · 模式 · 本会发送 / 保持安静 / 失败 / 跳过),每行再点开看报告、步骤、版本和权限。+// 和运行记录(一次一行:时间 · 模式 · 本会发送 / 保持安静 / 失败 / 跳过),每行再点开看报告、步骤、版本和权限;运行记录可以导出成+// Markdown(3f)。编辑器里有每次、每月的预算(3f,检查才有)。// 健康时不多说话:状态是"点 + 文字"(绿 = 执行中、提醒,灰 = 观察中、关了,红 = 暂停了)。import { useEffect, useState } from "preact/hooks";import { html, Icon, Button, Seg, Sheet, Spinner } from "./ui.js";@@ -9,7 +10,7 @@ import { api } from "../lib/api.js";import { confirmSheet, failed, toast } from "../lib/store.js";import { channelName } from "../lib/access.js";import { t, locale } from "../lib/i18n.js";-import { hasCost, money } from "./tasks.js";+import { exportUrl, hasCost, money } from "./tasks.js";const pad = (n) => String(n).padStart(2, "0");const hm = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;@@ -152,6 +153,7 @@ export function RuleDetail({ rule, runs: given, onChanged }) {${rule.kind === "check" && rule.mode === "observe" && html`<span class="hint">${t("rules.observeHelp")}</span>`}<div class="actions"><button type="button" class="text" onClick=${() => setEditing(true)}>${t("common.edit")}</button>+ ${!given && html`<a class="text" href=${exportUrl("rules", rule.id)} download>${t("rules.export")}</a>`}<button type="button" class="text danger" disabled=${busy === "del"} onClick=${del}>${t("common.delete")}</button></div><div class="t-label">${t("rules.log")}</div>@@ -222,6 +224,9 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {const [conv, setConv] = useState(rule?.conversationId || "");const [convs, setConvs] = useState(null);const [busy, setBusy] = useState(false);+ // 预算(3f):每次、每月(美元);没改就不发+ const [runB, setRunB] = useState(String(rule?.runBudgetUsd ?? 0.1));+ const [monthB, setMonthB] = useState(String(rule?.monthBudgetUsd ?? 3));const event = rule && rule.trigger.kind !== "schedule";useEffect(() => {api(`/conversations?bot=${encodeURIComponent(botId)}`)@@ -242,6 +247,8 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {...(kind === "remind" ? { message: words, ...(rule ? {} : { instruction: words }) } : { instruction: words }),...(event || (rule && JSON.stringify(scheduleOf(f)) === JSON.stringify(scheduleOf(orig))) ? {} : { schedule: scheduleOf(f) }),...(conv ? { conversationId: conv } : {}),+ ...(kind === "check" && Number(runB) !== (rule?.runBudgetUsd ?? 0.1) ? { runBudgetUsd: Number(runB) } : {}),+ ...(kind === "check" && Number(monthB) !== (rule?.monthBudgetUsd ?? 3) ? { monthBudgetUsd: Number(monthB) } : {}),};const d = rule? await api(`/rules/${encodeURIComponent(rule.id)}`, { method: "PUT", body })@@ -253,8 +260,8 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {}setBusy(false);};- const ok = title.trim() && words.trim() && conv && (event || f.kind !== "weekly" || f.days.length);const remind = kind === "remind";+ const ok = title.trim() && words.trim() && conv && (event || f.kind !== "weekly" || f.days.length) && (remind || (Number(runB) > 0 && Number(monthB) > 0));return html`<${Sheet} title=${rule ? t("rules.editTitle") : t("rules.newTitle")} onClose=${onClose}><div class="rule-form">${!rule && html`<${Seg} label=${t("rules.kind")} options=${[["check", t("rules.kindCheck")], ["remind", t("rules.kindRemind")]]} value=${kind} onChange=${setKind} />`}@@ -278,6 +285,13 @@ export function RuleEditor({ botId, rule, onClose, onSaved }) {<span class="t-label">${t("rules.to")}</span>${!convs ? html`<${Spinner} />` : convs.length ? html`<${Seg} label=${t("rules.to")} options=${convOptions(convs, conv)} value=${conv} onChange=${setConv} />` : html`<span class="hint">${t("rules.noConvs")}</span>`}</div>+ ${!remind && html`<div class="rule-when">+ <span class="t-label">${t("rules.budget")}</span>+ <div class="rule-when-row">+ <label class="rule-budget">${t("rules.perRun")}<span class="num">$</span><input class="field num" type="number" min="0.01" step="0.05" value=${runB} onInput=${(e) => setRunB(e.target.value)} /></label>+ <label class="rule-budget">${t("rules.perMonth")}<span class="num">$</span><input class="field num" type="number" min="0.5" step="0.5" value=${monthB} onInput=${(e) => setMonthB(e.target.value)} /></label>+ </div>+ </div>`}${channel === "weixin" && html`<p class="hint">${t("rules.weixinNote")}</p>`}</div><div class="actions">diff --git a/ui/components/tasks.js b/ui/components/tasks.jsindex ae79b4c..d6bad9c 100644--- a/ui/components/tasks.js+++ b/ui/components/tasks.js@@ -1,13 +1,18 @@-// 后台任务(3a):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是最新进展、花费、每次运行折叠的处理过程和停止;-// 信息面板里一行一个任务。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。健康时不多占地方:-// 花费(3e,「约 $0.08」)在有了花费之后才出现。-import { useEffect, useState } from "preact/hooks";+// 后台任务(3a,3f 补全):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是任务的详情;+// 信息面板的「任务」组(TaskGroup)是一个机器人的全部任务和规则:进行中、等你的、规则,结束了的收在最后一行「已结束 3」里,+// 点开才列出来。一个任务一行,点开是同一块里的详情(和规则一样,像普通的折叠一样展开)。+// 详情:来自(渠道、时间、原话)、最新进展、预算(约 $0.08 / $1.00,可以改)、文件夹(大小、打开)、要清理时的日期和保留、+// 每次运行折叠的处理过程,以及停止 / 导出 / 删除。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。+// 健康时不多占地方:花费有了才写,清理只在定了日期时出现。+import { useEffect, useRef, useState } from "preact/hooks";import { html, Icon, Notice } from "./ui.js";import { ActivityLine } from "./activity.js";+import { RuleRow } from "./rules.js";import { api } from "../lib/api.js";-import { failed, toast } from "../lib/store.js";-import { fmtAgo, fmtDur } from "../lib/format.js";-import { t, has } from "../lib/i18n.js";+import { confirmSheet, failed, toast } from "../lib/store.js";+import { fmtAgo, fmtDay, fmtDur, fmtSep, fmtSize } from "../lib/format.js";+import { channelName } from "../lib/access.js";+import { t, has, getLang } from "../lib/i18n.js";/** 阶段 → 状态点 */export function stageDot(stage) {@@ -43,14 +48,33 @@ export async function stopTask(task) {}}-/** 任务的详情:最新进展、花费、文件夹、每次运行(折叠的处理过程)、停止。working 时每 3 秒刷新 */-export function TaskDetail({ task, onChanged }) {- const [d, setD] = useState(null);- const [stopping, setStopping] = useState(false);- const working = task.stage.group === "working";+/** 导出成 Markdown 的下载地址(下载链接带不了请求头,语言写在查询参数里) */+export const exportUrl = (kind, id) => `/amb/api/${kind}/${encodeURIComponent(id)}/export?lang=${encodeURIComponent(getLang())}`;++/** 原话太长时只留开头 */+const clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);++/**+ * 任务的详情:来自、最新进展、预算、文件夹、清理、每次运行(折叠的处理过程)、停止 / 导出 / 删除。working 时每 3 秒刷新。+ * origin=false 时不写来自(对话里的胶囊就在请求那条消息下面);onOpenConv 给了,来自那一行点开会话;data 给了就不去取(样例页)+ */+export function TaskDetail({ task, onChanged, origin = true, onOpenConv, data }) {+ const [d, setD] = useState(data || null);+ const [busy, setBusy] = useState("");+ const [editing, setEditing] = useState(false);+ const [amount, setAmount] = useState("");+ const [tick, setTick] = useState(0);+ const input = useRef(null);+ useEffect(() => {+ if (editing) requestAnimationFrame(() => (input.current?.focus(), input.current?.select()));+ }, [editing]);+ const view = d?.task || task;+ const working = view.stage.group === "working";+ const id = encodeURIComponent(task.id);useEffect(() => {+ if (data) return;let on = true;- const load = () => api(`/tasks/${encodeURIComponent(task.id)}`).then((x) => on && setD(x)).catch(() => {});+ const load = () => api(`/tasks/${id}`).then((x) => on && setD(x)).catch(() => {});load();if (!working) return () => (on = false);const timer = setInterval(load, 3000);@@ -58,25 +82,70 @@ export function TaskDetail({ task, onChanged }) {on = false;clearInterval(timer);};- }, [task.id, working, task.updatedAt]);+ }, [task.id, working, task.updatedAt, tick]);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);+ // 结束了的(已完成、已停止)不用改预算:追加时还不够会再问+ const ended = view.stage.group === "ended";+ const reload = () => (setTick((n) => n + 1), onChanged?.());+ const act = async (key, fn) => {+ setBusy(key);+ try {+ await fn();+ } catch (e) {+ failed(e);+ }+ setBusy("");};+ const stop = () => act("stop", async () => (await stopTask(view)) && reload());+ const saveBudget = () =>+ Number(amount) > 0 &&+ act("budget", async () => {+ await api(`/tasks/${id}/budget`, { method: "POST", body: { budgetUsd: Number(amount) } });+ setEditing(false);+ reload();+ });+ const keep = () => act("keep", async () => (await api(`/tasks/${id}/keep`, { method: "POST", body: {} }), reload()));+ const open = () => act("open", () => api(`/tasks/${id}/open`, { method: "POST", body: {} }));+ const del = async () => {+ const size = d?.sizes ? d.sizes.folder + d.sizes.sessions : 0;+ const body = size ? t("tasks.deleteBody", { size: fmtSize(size) }) : t("tasks.deleteBodyEmpty");+ if (!(await confirmSheet({ title: t("tasks.deleteTitle", { title: view.title }), body, confirmLabel: t("common.delete"), danger: true }))) return;+ act("del", async () => {+ await api(`/tasks/${id}`, { method: "DELETE" });+ toast(t("tasks.deleted"));+ onChanged?.();+ });+ };+ const o = origin && d?.origin;+ const from = o && t("tasks.originLine", { where: channelName(o.channel), when: fmtSep(o.at), text: clip(o.text.replace(/\s+/g, " "), 60) });+ const budget = hasCost(view.spentUsd) ? t("tasks.costOf", { spent: money(view.spentUsd), budget: money(view.budgetUsd) }) : money(view.budgetUsd);return html`<div class="task-detail">+ ${from && html`<div class="task-line"><span class="t-label">${t("tasks.origin")}</span>+ ${onOpenConv ? html`<button type="button" class="v task-origin" title=${t("tasks.openConv")} onClick=${onOpenConv}>${from}</button>` : html`<span class="v selectable">${from}</span>`}</div>`}${view.latest && html`<div class="task-line"><span class="t-label">${t("tasks.latest")}</span><span class="v selectable">${view.latest}</span></div>`}- ${hasCost(view.spentUsd) && html`<div class="task-line"><span class="t-label">${t("tasks.cost")}</span><span class="v num">${t("tasks.costOf", { spent: money(view.spentUsd), budget: money(view.budgetUsd) })}</span></div>`}- ${view.folder && html`<div class="task-line"><span class="t-label">${t("tasks.folder")}</span><span class="v mono selectable">${view.folder}</span></div>`}+ ${(!ended || hasCost(view.spentUsd)) && html`<div class="task-line"><span class="t-label">${t("tasks.budget")}</span>+ ${editing+ ? html`<span class="v task-budget-edit">$<input ref=${input} class="field num" type="number" min="0.01" step="0.5" value=${amount} aria-label=${t("tasks.budget")}+ onInput=${(e) => setAmount(e.target.value)} onKeyDown=${(e) => (e.key === "Enter" && saveBudget(), e.key === "Escape" && (e.stopPropagation(), setEditing(false)))} />+ <button type="button" class="text accent" disabled=${!(Number(amount) > 0) || busy === "budget"} onClick=${saveBudget}>${t("common.save")}</button>+ <button type="button" class="text" onClick=${() => setEditing(false)}>${t("common.cancel")}</button></span>`+ : html`<span class="v num">${budget}</span>${!ended && html`<button type="button" class="text" onClick=${() => (setAmount(String(view.budgetUsd)), setEditing(true))}>${t("tasks.change")}</button>`}`}+ </div>`}+ ${view.folder && html`<div class="task-line"><span class="t-label">${t("tasks.folder")}</span>+ <span class="v mono selectable">${view.folder}</span>${d?.sizes?.folder > 0 && html`<span class="n num">${fmtSize(d.sizes.folder)}</span>`}+ ${d?.canOpen && html`<button type="button" class="text" disabled=${busy === "open"} onClick=${open}>${t("common.open")}</button>`}</div>`}+ ${view.cleanupAt > 0 && html`<div class="task-line"><span class="t-label">${t("tasks.cleanup")}</span>+ <span class="v">${t("tasks.cleanupOn", { date: fmtDay(view.cleanupAt) })}</span><button type="button" class="text" disabled=${busy === "keep"} onClick=${keep}>${t("tasks.keep")}</button></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)} />`,+ (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} steps=${r.stepList}+ load=${() => api(`/tasks/${id}/runs/${encodeURIComponent(r.id)}/activity`).then((x) => x.steps)} />`,)}- ${working && html`<div class="task-actions"><button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button></div>`}+ <div class="task-actions">+ ${working && html`<button type="button" class="text danger" disabled=${busy === "stop"} onClick=${stop}>${busy === "stop" ? t("tasks.stopping") : t("tasks.stop")}</button>`}+ ${!data && html`<a class="text" href=${exportUrl("tasks", task.id)} download>${t("tasks.export")}</a>`}+ ${!working && html`<button type="button" class="text danger" disabled=${busy === "del"} onClick=${del}>${t("common.delete")}</button>`}+ </div></div>`;}@@ -90,12 +159,15 @@ export function TaskChip({ task, onChanged }) {<span class="k">${t("tasks.chip")}</span><span class="sep">·</span><span class="t">${task.title}</span><span class="sep">·</span><span class="st">${task.stage.label}</span><${Icon} name="chevRight" size=${12} class="chev" /></button>- ${open && html`<${TaskDetail} task=${task} onChanged=${onChanged} />`}+ ${open && html`<${TaskDetail} task=${task} origin=${false} onChanged=${onChanged} />`}</div>`;}-/** 信息面板里的一行:状态点 + 标题,下面一行是状态、什么时候开始的、花了多少(有了花费才写);进行中的可以停止 */-export function TaskRow({ task, onChanged, onOpen }) {+/**+ * 信息面板里的一行:状态点 + 标题,下面一行是状态、多久了(进行中)或什么时候结束的、花了多少(有了花费才写);+ * 进行中的可以直接停止。点开是同一块里的详情(data 给了就是样例页)+ */+export function TaskRow({ task, onChanged, open, onToggle, onOpenConv, data }) {const [stopping, setStopping] = useState(false);const working = task.stage.group === "working";const when = working ? t("tasks.minutes", { count: Math.max(1, Math.round((Date.now() - task.createdAt) / 60_000)) }) : fmtAgo(task.endedAt || task.updatedAt);@@ -105,15 +177,61 @@ export function TaskRow({ task, onChanged, onOpen }) {if (await stopTask(task)) onChanged?.();setStopping(false);};- return html`<div class="row compact task-row${onOpen ? " clickable" : ""}" role=${onOpen ? "button" : undefined} tabindex=${onOpen ? "0" : undefined}- onClick=${onOpen} onKeyDown=${(e) => onOpen && e.key === "Enter" && onOpen()}>- <span class=${`dot ${stageDot(task.stage)}`} aria-hidden="true"></span>- <div class="who">- <div class="name">${task.title}</div>- <div class="sub">${task.stage.label} · ${when}${hasCost(task.spentUsd) ? ` · ${t("tasks.costShort", { spent: money(task.spentUsd) })}` : ""}</div>+ return html`<div class=${`row compact clickable task-row${open ? " open" : ""}`} role="button" tabindex="0" aria-expanded=${!!open}+ onClick=${onToggle} onKeyDown=${(e) => (e.key === "Enter" || e.key === " ") && e.target === e.currentTarget && (e.preventDefault(), onToggle?.())}>+ <span class=${`dot ${stageDot(task.stage)}`} aria-hidden="true"></span>+ <div class="who">+ <div class="name">${task.title}</div>+ <div class="sub">${task.stage.label} · ${when}${hasCost(task.spentUsd) ? ` · ${t("tasks.costShort", { spent: money(task.spentUsd) })}` : ""}</div>+ </div>+ ${working && !open && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop} onKeyDown=${(e) => e.stopPropagation()}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button>`}</div>- ${working && html`<button type="button" class="text danger" disabled=${stopping} onClick=${stop}>${stopping ? t("tasks.stopping") : t("tasks.stop")}</button>`}- </div>`;+ ${open && html`<div class="row-edit task-edit"><${TaskDetail} task=${task} data=${data} onChanged=${onChanged} onOpenConv=${onOpenConv} /></div>`}`;+}++/** 行的第二行:一次性规则跑完了只留一天 */+const freshRule = (r, now = Date.now()) => r.state.key !== "done" || now - (r.last?.at || r.updatedAt) < 86_400_000;++/**+ * 信息面板的「任务」组:这个机器人的任务和规则。进行中、等你的任务(GET /tasks?group=working,needs,每 4 秒)在前,规则其次,+ * 结束了的(group=ended,留 30 天)收在最后一行「已结束 3」里,点开才列出来。什么都没有时整组不画。+ * 一次只展开一个任务或规则;onOpenConv(任务) 打开任务来自的那个会话。tasks / rules / ended 给了就不去取(样例页)+ */+export function TaskGroup({ botId, onOpenConv, tasks: givenTasks, rules: givenRules, ended: givenEnded, details }) {+ const sample = !!givenTasks;+ const [tasks, setTasks] = useState(givenTasks || null);+ const [rules, setRules] = useState(givenRules || null);+ const [ended, setEnded] = useState(givenEnded || null);+ const [openId, setOpenId] = useState("");+ const [showEnded, setShowEnded] = useState(false);+ const bot = encodeURIComponent(botId);+ const loadTasks = () => api(`/tasks?bot=${bot}&group=working,needs&limit=20`).then((d) => setTasks(d.tasks)).catch(() => {});+ const loadRules = () => api(`/rules?bot=${bot}`).then((d) => setRules(d.rules)).catch(() => {});+ const loadEnded = () => api(`/tasks?bot=${bot}&group=ended&limit=50`).then((d) => setEnded(d.tasks)).catch(() => {});+ const reload = () => (loadTasks(), loadRules(), loadEnded());+ useEffect(() => {+ if (sample) return;+ reload();+ const fast = setInterval(() => document.visibilityState === "visible" && (loadTasks(), loadRules()), 4000);+ const slow = setInterval(() => document.visibilityState === "visible" && loadEnded(), 15000);+ return () => (clearInterval(fast), clearInterval(slow));+ }, [botId]);+ const list = (tasks || []).slice(0, 12);+ const rs = (rules || []).filter((r) => freshRule(r));+ const done = ended || [];+ if (!list.length && !rs.length && !done.length) return null;+ const toggle = (id) => setOpenId(openId === id ? "" : id);+ const row = (x) => html`<${TaskRow} key=${x.id} task=${x} open=${openId === x.id} onToggle=${() => toggle(x.id)} onChanged=${reload} data=${details?.[x.id]}+ onOpenConv=${onOpenConv && (() => onOpenConv(x))} />`;+ return html`<div class="list-head">${t("info.tasks")}</div>+ <div class="list task-group">+ ${list.map(row)}+ ${rs.map((r) => html`<${RuleRow} key=${r.id} rule=${r} open=${openId === r.id} onToggle=${() => toggle(r.id)} onChanged=${reload} />`)}+ ${done.length > 0 && html`<button type="button" class=${`row compact clickable task-ended${showEnded ? " open" : ""}`} aria-expanded=${showEnded} onClick=${() => setShowEnded(!showEnded)}>+ <span class="who"><span class="name">${t("tasks.ended", { count: done.length })}</span></span><${Icon} name="chevRight" size=${12} class="chev" />+ </button>`}+ ${showEnded && done.map(row)}+ </div>`;}/** 后台工作暂停时,信息面板顶部的一行(没暂停时不画):任务、规则和主动消息都停着,点「恢复」接着来 */diff --git a/ui/css/chat.css b/ui/css/chat.cssindex 054268b..f6765b1 100644--- a/ui/css/chat.css+++ b/ui/css/chat.css@@ -370,10 +370,18 @@ button.act-head:active { background: var(--pill-hover); }.task-pill .sep { color: var(--muted); }.task-pill .chev { flex: none; color: var(--muted); transition: transform var(--t-fast); }.task-detail { display: grid; grid-template-columns: minmax(0, 1fr); gap: var(--space-2); width: 100%; margin-top: var(--space-3); }+/* 详情里一行一样:小标签 + 值 + 行尾的大小、文字按钮(改预算、打开、保留);每次运行一行折叠的处理过程,行间不画线 */.task-line { display: flex; align-items: baseline; gap: var(--space-2); font-size: var(--fs-sm); color: var(--fg-2); }.task-line .t-label { flex: none; min-width: 4em; }-.task-line .v { min-width: 0; overflow-wrap: anywhere; }+.task-line .v { flex: 1; min-width: 0; overflow-wrap: anywhere; }.task-line .v.mono { font-family: var(--code); font-size: var(--fs-xs); }+.task-line .n { flex: none; font-size: var(--fs-xs); color: var(--muted); }+.task-line .text { flex: none; margin: calc(-1 * var(--space-1)) 0; } /* 文字按钮的悬停底不把行撑高 */+button.task-origin { text-align: left; font-size: inherit; color: inherit; border-radius: var(--r-sm); transition: color var(--t-fast); }+button.task-origin:hover { color: var(--fg); }+.task-budget-edit { display: flex; align-items: center; gap: var(--space-1); flex-wrap: wrap; }+.task-budget-edit .field { width: 88px; --field-h: var(--ctl-sm); }.task-detail .activity, .task-detail .work-line { margin-bottom: 0; }-.task-actions { display: flex; justify-content: flex-start; }+.task-detail .work-line { border-bottom: 0; padding-bottom: 0; }+.task-actions { display: flex; justify-content: flex-start; gap: var(--space-1); }}diff --git a/ui/css/shell.css b/ui/css/shell.cssindex 785be23..1076130 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -330,6 +330,22 @@ button.thread:active { background: var(--side-press); }.rule-days { display: flex; gap: var(--space-1); flex-wrap: wrap; }.rule-days .chip { height: var(--ctl-sm); padding: 0 var(--space-2-5); }.rule-days .chip.on { background: var(--pill-press); color: var(--fg); font-weight: var(--fw-medium); }+.rule-form label.rule-budget { display: flex; align-items: center; gap: var(--space-1-5); font-weight: var(--fw-regular); }+.rule-budget .num { color: var(--muted); }+.rule-budget .field { width: 88px; --field-h: var(--ctl-md); }++/* 任务(components/tasks.js,3f):「任务」组里一个任务一行,点开是同一块里的详情(和规则一样);结束了的收在最后一行+ 「已结束 3」里,点开才列出来。详情里每次运行是一行折叠的处理过程,不画分隔线、不再铺底 */+.task-row .dot { flex: none; }+.task-row > .text { flex: none; }+.task-ended { width: 100%; text-align: left; }+.task-ended .name { color: var(--muted); font-weight: var(--fw-regular); }+.task-ended .chev { flex: none; color: var(--muted); transition: transform var(--t-fast); }+.task-ended.open .chev { transform: rotate(90deg); }+.row-edit .task-detail { margin-top: 0; }+.row-edit .task-detail .act-list, .need-detail .task-detail .act-list { background: none; padding: 0; margin-bottom: 0; }+/* 导出是下载链接,长得和文字按钮一样 */+a.text { display: inline-flex; align-items: center; text-decoration: none; }.panel-scrim { display: none; }/* narrow window: the panel floats over the chat as a glass drawer over a scrim */diff --git a/ui/design/gallery.js b/ui/design/gallery.jsindex 2b4b017..513129f 100644--- a/ui/design/gallery.js+++ b/ui/design/gallery.js@@ -6,7 +6,7 @@ import { BotAvatar, AvatarPicker, AppMark, BOT_CHARS, CHAR_KEYS, MAIN_CHAR } froimport { TEMPLATES } from "../screens/new-bot.js";import { NeedItem, NeedsRow } from "../screens/needs-you.js";import { RuleRow, RuleDetail } from "../components/rules.js";-import { PausedLine } from "../components/tasks.js";+import { PausedLine, TaskGroup, TaskRow } from "../components/tasks.js";import { Markdown } from "../components/markdown.js";import { useStore, toast, saved, failed, confirmSheet } from "../lib/store.js";import { themeMode, setThemeMode } from "../lib/theme.js";@@ -630,6 +630,19 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<//><//>+ <${Section} id="tasks" title="任务" lead="信息面板的「任务」组就是一个机器人的全部任务和规则:进行中、等你的在前,规则其次,结束了的收在最后一行里,点开才列出来(留 30 天)。一个任务一行,点开是同一块里的详情:来自、最新进展、预算(可以改)、文件夹(大小、打开)、要清理时的日期和保留、每次运行折叠的处理过程。什么都没有时整组不画。">+ <${Demo} title="「任务」组" note="TaskGroup:进行中 / 等你回答 / 规则 / 已结束 1(点开列出结束了的,那个文件夹 3 天后清理)">+ ${() => 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)">+ <${TaskGroup} botId="b" tasks=${TASKS} rules=${[RULES[0]]} ended=${ENDED} details=${{ t1: TASK_DETAIL, t2: ASK_DETAIL, t3: ENDED_DETAIL }} />+ </div>`}+ <//>+ <${Demo} title="详情" note="TaskRow 展开:来自 · 最新进展 · 预算 约 $0.08 / $1.00(改) · 文件夹 2.3 MB(打开) · 第 1 次 · 开始 · 停止 / 导出">+ ${() => 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"><${TaskRow} task=${TASKS[0]} open data=${TASK_DETAIL} onToggle=${() => {}} onOpenConv=${() => {}} /></div>+ </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>@@ -662,7 +675,41 @@ const NEEDS = [{ id: "rb", kind: "rule", botName: "小蓝", subject: "规则「看 X 价格」", status: "本月预算用完", line: "已用约 $3.00,下月自动恢复。再给 $3 继续?", since: Date.now() - 2 * 3600_000, severity: "warn", actions: ["continue"] },{ 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"] },+];++/** 任务的样例(单人:自己的机器人小蓝):在调研的、等你回答的、昨天做完的(文件夹 3 天后清理) */+const ago = (min) => Date.now() - min * 60_000;+const task = (o) => ({ botId: "b", conversationId: "b:weixin:me", channel: "weixin", latest: "", runs: 1, spentUsd: 0, budgetUsd: 1, cleanupAt: 0, endedAt: 0, ...o });+const TASKS = [+ task({ id: "t1", title: "GPU 价格调研", stage: { key: "working", label: "进行中", group: "working" }, createdAt: ago(12), updatedAt: ago(1), spentUsd: 0.08, latest: "已比较 3 家,正在核对 B 云的包年价", folder: "tasks/gpu-prices-3f2a1c" }),+ task({ id: "t2", title: "季度报告 PPT", stage: { key: "needs-you/answer", label: "等你回答", group: "needs" }, createdAt: ago(50), updatedAt: ago(5), spentUsd: 0.21, folder: "tasks/task-8c0d42" }),+];+const ENDED = [+ task({ id: "t3", title: "整理下载目录", stage: { key: "ready", label: "已完成", group: "ended" }, createdAt: ago(27 * 1440), endedAt: ago(27 * 1440 - 20), updatedAt: ago(27 * 1440 - 20), spentUsd: 0.02, latest: "按类型分到 6 个文件夹,重复的 14 个放进了 duplicates", folder: "tasks/downloads-9b1e07", cleanupAt: Date.now() + 3 * 86_400_000 }),];+const step = (id, title, summary) => ({ id, kind: "tool", title, summary, status: "ok", at: 0 });+const TASK_DETAIL = {+ task: TASKS[0],+ origin: { channel: "weixin", at: ago(12), text: "帮我调研一下三家云的 GPU 价格,A100 包月的,好了告诉我" },+ sizes: { folder: 2_400_000, sessions: 1_100_000 },+ canOpen: true,+ runs: [{ id: "r1", cause: "launch", state: "running", outcome: "", queuedAt: ago(12), startedAt: ago(12), endedAt: 0, steps: 3, stepList: [step("s1", "web_fetch", "x-cloud.example/pricing"), step("s2", "web_fetch", "b-cloud.example/gpu"), step("s3", "write", "prices.md")] }],+};+const ASK_DETAIL = {+ task: TASKS[1],+ origin: { channel: "weixin", at: ago(50), text: "后台帮我把季度数据做成 PPT" },+ sizes: { folder: 5_600_000, sessions: 900_000 },+ canOpen: true,+ runs: [{ id: "r3", cause: "launch", state: "ended", outcome: "needs_you", queuedAt: ago(50), startedAt: ago(50), endedAt: ago(5), steps: 0 }],+};+const ENDED_DETAIL = {+ task: ENDED[0],+ origin: { channel: "weixin", at: ago(27 * 1440 + 10), text: "把下载目录整理一下" },+ sizes: { folder: 820_000, sessions: 300_000 },+ canOpen: true,+ 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 周报、暂停了的巡检、一次性的提醒 */const at = (days, h, m = 0) => {diff --git a/ui/lib/format.js b/ui/lib/format.jsindex 6c2c48a..1e046cc 100644--- a/ui/lib/format.js+++ b/ui/lib/format.js@@ -46,3 +46,19 @@ export function fmtTime(at) {export function fmtTimeOfDay(at) {return at ? new Date(at).toLocaleTimeString(locale(), { hour12: false }) : "";}++/** 只有日期:"11月4日"(英文:Nov 4) */+export function fmtDay(at) {+ return at ? dateFmt({ month: locale() === "en" ? "short" : "long", day: "numeric" }).format(new Date(at)) : "";+}++/** 文件大小:"900 B" / "12 KB" / "2.4 MB" / "1.1 GB" */+export function fmtSize(n) {+ const v = Number(n) || 0;+ if (v < 1024) return `${v} B`;+ const units = ["KB", "MB", "GB", "TB"];+ let x = v / 1024;+ let i = 0;+ while (x >= 1024 && i < units.length - 1) (x /= 1024), i++;+ return `${x >= 10 ? Math.round(x) : x.toFixed(1)} ${units[i]}`;+}diff --git a/ui/locales/en/app.js b/ui/locales/en/app.jsindex f9291f4..7563e49 100644--- a/ui/locales/en/app.js+++ b/ui/locales/en/app.js@@ -9,6 +9,8 @@ export default {cmd: {needs: "Needs you ({count})",needsKeys: "needs attention to-do",+ tasks: "Tasks and rules",+ tasksKeys: "tasks rules background jobs",settings: "Open Settings",settingsKeys: "settings preferences options",newBot: "New bot",diff --git a/ui/locales/en/needs.js b/ui/locales/en/needs.jsindex 1aad449..2e8805f 100644--- a/ui/locales/en/needs.js+++ b/ui/locales/en/needs.js@@ -17,4 +17,5 @@ export default {dismiss: "Don't show again",continue: "Continue",raiseBudget: "Change budget",+ keep: "Keep",};diff --git a/ui/locales/en/rules.js b/ui/locales/en/rules.jsindex 566de29..b937da2 100644--- a/ui/locales/en/rules.js+++ b/ui/locales/en/rules.js@@ -52,4 +52,8 @@ export default {weixinNote: "WeChat lets the bot message you only within 24 hours of your last message. Otherwise it arrives with your next message and shows on the desktop.",create: "Create",gone: "This rule was deleted",+ export: "Export",+ budget: "Budget",+ perRun: "Per run",+ perMonth: "Per month",};diff --git a/ui/locales/en/tasks.js b/ui/locales/en/tasks.jsindex 8549388..ed21e2c 100644--- a/ui/locales/en/tasks.js+++ b/ui/locales/en/tasks.js@@ -14,7 +14,20 @@ export default {minutes: { one: "{count} min", other: "{count} min" },paused: "Background work is paused",resume: "Resume",- cost: "Cost",costOf: "About {spent} of {budget}",costShort: "About {spent}",+ origin: "From",+ originLine: "{where} · {when} “{text}”",+ openConv: "Open the conversation",+ budget: "Budget",+ change: "Change",+ cleanup: "Cleanup",+ cleanupOn: "Folder deleted {date}",+ keep: "Keep",+ export: "Export",+ deleteTitle: "Delete “{title}”?",+ deleteBody: "Its folder and run log go too, {size} in all.",+ deleteBodyEmpty: "Its run log goes too.",+ deleted: "Deleted",+ ended: { one: "{count} ended", other: "{count} ended" },};diff --git a/ui/locales/zh-CN/app.js b/ui/locales/zh-CN/app.jsindex b3015a5..1f7757d 100644--- a/ui/locales/zh-CN/app.js+++ b/ui/locales/zh-CN/app.js@@ -9,6 +9,8 @@ export default {cmd: {needs: "需要你({count})",needsKeys: "needs attention 需要你 待办",+ tasks: "任务和规则",+ tasksKeys: "tasks rules background 任务 规则 后台",settings: "打开设置",settingsKeys: "settings preferences 设置 偏好",newBot: "新建机器人",diff --git a/ui/locales/zh-CN/needs.js b/ui/locales/zh-CN/needs.jsindex 1c2a519..70b7c8c 100644--- a/ui/locales/zh-CN/needs.js+++ b/ui/locales/zh-CN/needs.js@@ -17,4 +17,5 @@ export default {dismiss: "不再提示",continue: "继续",raiseBudget: "调整预算",+ keep: "保留",};diff --git a/ui/locales/zh-CN/rules.js b/ui/locales/zh-CN/rules.jsindex f670abe..d208e95 100644--- a/ui/locales/zh-CN/rules.js+++ b/ui/locales/zh-CN/rules.js@@ -52,4 +52,8 @@ export default {weixinNote: "微信只在你 24 小时内发过消息时才能主动发给你;否则会在你下次发消息时一起送到,并显示在桌面端。",create: "建好",gone: "规则已经删了",+ export: "导出",+ budget: "预算",+ perRun: "每次",+ perMonth: "每月",};diff --git a/ui/locales/zh-CN/tasks.js b/ui/locales/zh-CN/tasks.jsindex 25f78e5..82aea77 100644--- a/ui/locales/zh-CN/tasks.js+++ b/ui/locales/zh-CN/tasks.js@@ -14,7 +14,21 @@ export default {minutes: { other: "{count} 分钟" },paused: "后台工作已暂停",resume: "恢复",- cost: "花费",costOf: "约 {spent} / {budget}",costShort: "约 {spent}",+ // 3f:任务详情、信息面板的「任务」组+ origin: "来自",+ originLine: "{where} · {when}「{text}」",+ openConv: "打开会话",+ budget: "预算",+ change: "改",+ cleanup: "清理",+ cleanupOn: "{date} 删除文件夹",+ keep: "保留",+ export: "导出",+ deleteTitle: "删除「{title}」?",+ deleteBody: "文件夹和运行记录一起删除,共 {size}。",+ deleteBodyEmpty: "运行记录一起删除。",+ deleted: "已删除",+ ended: { other: "已结束 {count}" },};diff --git a/ui/main.js b/ui/main.jsindex 34cc919..bc13749 100644--- a/ui/main.js+++ b/ui/main.js@@ -338,6 +338,8 @@ function App() {{ label: t("app.cmd.newBot"), kbd: isMac ? "⌘N" : "Ctrl+N", keys: t("app.cmd.newBotKeys"), run: newBot },...(needs.n > 0 ? [{ label: t("app.cmd.needs", { count: needs.n }), keys: t("app.cmd.needsKeys"), run: openNeeds }] : []),...(route.view === "chat" ? [{ label: infoOpen ? t("app.cmd.closeInfo") : t("app.cmd.openInfo"), kbd: isMac ? "⌘⇧I" : "Ctrl+Shift+I", keys: t("app.cmd.infoKeys"), run: () => setInfoOpen((v) => !v) }] : []),+ // 任务和规则在当前机器人的信息面板里(「任务」组)+ ...(bot ? [{ label: t("app.cmd.tasks"), keys: t("app.cmd.tasksKeys"), run: () => (openChat(bot.id), setInfoOpen(true)) }] : []),...(bot ? [{ label: t("app.cmd.botSettings", { name: bot.name }), keys: t("app.cmd.botSettingsKeys"), run: () => openBotSettings(bot.id) }] : []),{ label: t("app.cmd.modelflare"), keys: t("app.cmd.modelflareKeys"), run: () => openSettings("modelflare") },{ label: t("app.cmd.appearance"), keys: t("app.cmd.appearanceKeys"), run: () => openSettings("appearance") },diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.jsindex 9157154..c4ed027 100644--- a/ui/screens/info-panel.js+++ b/ui/screens/info-panel.js@@ -8,9 +8,8 @@ import { confirmSheet, failed, saved, toast } from "../lib/store.js";import { markDone } from "../lib/guide.js";import { fmtAgo, fmtClock, fmtDur, fmtTime } from "../lib/format.js";import { channelName as accessChannel } from "../lib/access.js";-import { PausedLine, TaskRow } from "../components/tasks.js";+import { PausedLine, TaskGroup } from "../components/tasks.js";import { t } from "../lib/i18n.js";-import { RuleRow } from "../components/rules.js";export function usePoll(fn, ms, deps = []) {const [data, setData] = useState(null);@@ -222,14 +221,9 @@ export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChatconst [appr, , reloadAppr] = usePoll(() => api(`/approvals?status=pending&bot=${encodeURIComponent(bot.id)}`), 4000, [bot.id]);const [convs] = usePoll(() => api(`/conversations?bot=${encodeURIComponent(bot.id)}`), 8000, [bot.id]);const [access, , reloadAccess] = usePoll(() => api(`/bots/${encodeURIComponent(bot.id)}/access`), 4000, [bot.id]);- // 后台任务:只列还没结束的(进行中、等你的);一个都没有时不显示这一组- const [taskData, , reloadTasks] = usePoll(() => api(`/tasks?bot=${encodeURIComponent(bot.id)}&limit=20`), 4000, [bot.id]);- const tasks = (taskData?.tasks || []).filter((t) => t.stage.group !== "ended");- // 规则(3d):和任务在同一组;跑完了的一次性规则只留一天- const [ruleData, , reloadRules] = usePoll(() => api(`/rules?bot=${encodeURIComponent(bot.id)}`), 6000, [bot.id]);- const rules = (ruleData?.rules || []).filter((r) => r.state.key !== "done" || Date.now() - (r.last?.at || r.updatedAt) < 86_400_000);- const [openRule, setOpenRule] = useState("");const [viewing, setViewing] = useState(null);+ // 任务来自的会话:网页的就是这里的对话,微信、飞书的在会话记录里看+ const openConv = (task) => (task.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === task.conversationId) || null));const pending = (appr && appr.approvals) || [];// 上手清单:微信扫码绑定了,或飞书连上了,就算接好了渠道useEffect(() => {@@ -263,10 +257,7 @@ export function InfoPanel({ bot, leaving, onClose, onOpenBotSettings, onOpenChat<button type="button" class="text" style="justify-self:start" onClick=${reloadAppr}>${t("common.refresh")}</button></div>`: html`<div class="list"><div class="row"><span class="hint">${t("info.noApprovals")}</span></div></div>`}- ${(tasks.length > 0 || rules.length > 0) && html`<div class="list-head">${t("info.tasks")}</div>- <div class="list">${tasks.slice(0, 8).map((t) => html`<${TaskRow} key=${t.id} task=${t} onChanged=${reloadTasks}- onOpen=${() => (t.channel === "web" ? onOpenChat() : setViewing((convs?.conversations || []).find((c) => c.id === t.conversationId) || null))} />`)}- ${rules.map((r) => html`<${RuleRow} key=${r.id} rule=${r} open=${openRule === r.id} onToggle=${() => setOpenRule(openRule === r.id ? "" : r.id)} onChanged=${reloadRules} />`)}</div>`}+ <${TaskGroup} key=${bot.id} botId=${bot.id} onOpenConv=${openConv} /><${MemorySection} botId=${bot.id} />diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.jsindex a4e66f0..728acd8 100644--- a/ui/screens/needs-you.js+++ b/ui/screens/needs-you.js@@ -2,6 +2,7 @@// 没事时侧栏没有这一行,直接打开这一页只有一句「没有需要你处理的事」。状态是"点 + 文字":黄 = 等你,红 = 失败 / 登录过期。// 预算(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";@@ -81,6 +82,8 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB${item.kind === "delivery" && item.actions.includes("retry") && html`<${Button} loading=${busy === "retry"} disabled=${!!busy} onClick=${() => act("retry")}>${t("common.retry")}<//>`}${item.kind === "delivery" && item.actions.includes("dismiss") && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => act("dismiss")}>${t("needs.dismiss")}</button>`}${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>`}</div>${writing && html`<div class="need-reply"><input ref=${input} class="field" placeholder=${t("needs.answerPlaceholder")} value=${text} disabled=${busy === "text"}