🤖 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
Tasks: keep working while a question waits
Marla928f6de06015
diff --git a/docs/design/background-tasks-and-proactive.md b/docs/design/background-tasks-and-proactive.mdindex aaf1c6a..5c7ce50 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–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/`.+Status: **3a–3f are built**, plus questions that don't block (a task asks right away and keeps working while a question with a default waits, see [Questions](#questions-ask-early-keep-working)): 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@@ -17,6 +17,7 @@ Key decisions:- **The host is the source of truth.** It owns the tasks, the schedule, delivery and the budget. DSH runs the sessions. One in-child plugin, `amb-tasks.mjs`, decorates the task sessions: it restricts their tools, adds a prompt section and a `task_report` tool, and reports when a session has settled.- **Scheduling stays in the host.** `@deepseek-ai/dsh-schedule` can't be activated under our `sdk` profile. Even if it could, it would fire into chat sessions that nobody is watching.- **The human lane never waits.** Chat turns never take a task slot. Tasks run in separate DSH sessions in the same process; the spike measured a 63 ms chat reply while two 4-second task turns ran. When a person answers a task's question, the task wakes on a reserved slot.+- **A task asks as soon as it needs to know, and keeps working when it can.** A question with a reasonable default doesn't stop the task: it goes on with the work that doesn't depend on the answer and, if nobody answered by the time it finishes, uses the default, says so in its result and withdraws the question. Only a question nobody but the user can decide (paying, deleting, choosing an account) makes the task wait. See [Questions](#questions-ask-early-keep-working).- **We push only three things:** a result the user can use, a decision the user must make, and a failure. WeChat may hold even these: iLink allows sends only within 24 h of the user's last message, and at most 10 sends per inbound message. See [WeChat](#wechat-the-hard-constraint).- **Depends on P1** (the host→child control channel with per-session `steer`, `cancel` and model). Without per-session cancel, stopping one task means killing the bot's DSH process, which also ends the chat and every other task.@@ -60,7 +61,7 @@ flowchart LR| **Task** | A unit of authorized background work. It has its own DSH session (`task-<id>`) and folder (`tasks/<slug>-<id6>/`). | It is created only by a person's request, either through the chat agent's `task_start` or the "new task" button. It holds its origin conversation, a snapshot of the permission preset, the model and the budget. It ends only when it is **done**, when a **person stops** it, or when it fails and is archived. A follow-up from a person can resume a done task. It defines its own stage instead of following the DSH session (see [stage table](#2-states-and-transitions)). | Owns the work, the result and the questions. || **Rule** | A standing instruction in the user's own words, plus a schedule and a mode: `off`, `observe` or `act`. | It is created in `observe` mode, except for a fixed reminder (see [observe](#5-observe-mode)). It never acts beyond its mode or its permission cap. It records its `version`, and each run records which version it ran. Three failed runs in a row, or its monthly budget, pause it. | Proactive work with a mandate the user wrote. || **Run** | One stretch of work in a session: a task's launch, an answer, a retry or a recovery, or one firing of a rule. | It goes `queued`, `running`, `settling`, then `ended` with an outcome. It holds a slot while running or settling. It stores its activity steps and its cost. A rule gets a fresh session for each run. | The unit of audit, cost and recovery (superagent's Assignment). |-| **Report** | The structured state a Run reports through `task_report`. Its state is `progress`, `needs_you`, `done` or `failed`, with a `message` (user-facing, at most 300 characters), a `question` (one question with options), `summary` (internal) and `files`. | The latest Report is "what the task last said". A `progress` Report is internal and never pushed. In observe mode, `message` is recorded as "would have said". | We classify needs-you from structured fields, never from free text. |+| **Report** | The structured state a Run reports through `task_report`. Its state is `progress`, `needs_you`, `done` or `failed`, with a `message` (user-facing, at most 300 characters), a `question` (one question with options and an optional `default`, one of the options), `summary` (internal) and `files`. A `needs_you` with a default is asked but doesn't end the run. | The latest Report is "what the task last said". A `progress` Report is internal and never pushed. In observe mode, `message` is recorded as "would have said". | We classify needs-you from structured fields, never from free text. || **Attention** | One thing that waits for a person. Some are stored: a question, or an approval (the existing `approvals` table, extended). Others are derived from state: a failed task, a rule that keeps failing, an undelivered message, an expired channel login, a stuck turn, a budget that ran out. | It is shown once, in "needs you". It is pushed only when the [push rules](#what-is-pushed-and-only-that) allow. It goes away by itself when its cause is gone. | It answers "does anything need me now?" |**Rejected concepts.** Superagent's model is shaped for a team on GitHub and Feishu. This table lists what we leave out.@@ -82,21 +83,22 @@ flowchart LR| --- | --- | --- | --- | --- || 1 | `stopped` | A person stopped it | 已停止 | ended || 2 | `needs-you/delivery` | Its latest result, question or failure message has not reached the conversation: it failed 3 times, or it is held because the channel needs the person (WeChat window closed or no quota) | 未送达 | needs you |-| 3 | `needs-you/answer` | An open question or approval | 等你回答 · 等你批准 | needs you |+| 3 | `needs-you/answer` | An open approval, or an open question without a default | 等你回答 · 等你批准 | needs you || 4 | `needs-you/budget` | A run stopped at the task budget | 预算用完 | needs you || 5 | `failed` | The latest Report is `failed` or the launch failed, and no person's input since | 失败 | needs you || 6 | `ready` | The latest Report is `done`, and no input since | 已完成 | ended (resumable) || 7 | `working/queued` | Inputs wait, but no run holds a slot | 排队中 | working |-| 8 | `working` | Otherwise | 进行中 | working |+| 8 | `working/asking` | A run is running or settling, and a question with a default waits for an answer | 进行中,有个问题等你回答 | working |+| 9 | `working` | Otherwise | 进行中 | working |-A person's input after rows 3–6 (an answer, a follow-up, "retry" or "continue") starts a new Run. The task then moves to row 7 or 8. Automatic inputs, such as a job wake-up or a recovery after restart, never lift rows 2–5. Recovery applies only to runs that were running.+A person's input after rows 3–6 (an answer, a follow-up, "retry" or "continue") starts a new Run. The task then moves to row 7, 8 or 9. An answer to a question with a default usually reaches a running Run (row 8) and is steered into it, like a follow-up. Automatic inputs, such as a job wake-up or a recovery after restart, never lift rows 2–5. Recovery applies only to runs that were running.**Run.** `queued → running ⇄ settling → ended`.| Outcome | Meaning || --- | --- || `done` | Ended with a `done` Report, with or without a message |-| `needs_you` | Ended with a question; the task waits |+| `needs_you` | Ended with a question that has no default; the task waits || `failed` | Ended with a `failed` Report, an error after 3 transient retries, or no Report after one nudge || `budget` | Cancelled at the run or task budget || `stopped` | A person stopped the task |@@ -108,7 +110,8 @@ A person's input after rows 3–6 (an answer, a follow-up, "retry" or "continue"```mermaidstateDiagram-v2[*] --> working: task_start- working --> needs_you: Report needs_you / approval+ working --> needs_you: Report needs_you (no default) / approval+ working --> working: Report needs_you with default (asked, keeps working)working --> ready: Report done (delivered)working --> failed: Report failed / errorsworking --> needs_you: budget reached@@ -186,7 +189,7 @@ A person's message reaches a task only by explicit reference:A follow-up while the task is working is **steered** into it (P1) and lands at its next step. A follow-up to a done or failed task resumes it under the same task. A stopped task can't be continued.-As built: a WeChat quote of a task's pushed result or failure line, or a Feishu message in the reply chain of the task's request message (results are replied under it), goes straight to the task with a one-line acknowledgement (「收到,「GPU 价格调研」继续。」). It doesn't wait for the chat agent to notice. A quote of a digest that names several tasks stays ordinary chat. A pushed result ends with 「引用这条消息可以继续问。」 on WeChat and 「回复这条消息可以继续问。」 on Feishu, and still fits 300 characters. So "详细说说" on a quoted result is answered by the task itself.+As built: a WeChat quote of a task's pushed result or failure line, or a Feishu message in the reply chain of the task's request message (results are replied under it), goes straight to the task with a one-line acknowledgement (「收到,「GPU 价格调研」继续。」). It doesn't wait for the chat agent to notice. A quote of a digest that names several tasks stays ordinary chat. A quote of a task's question that was withdrawn because the task finished with its default (or failed) goes to the task the same way, as a late answer: 「[用户回答了你之前问的问题(你已经按「中文」做完了)] 问题:… 回答:…」, and the task resumes. A Feishu card button on such a question does the same. A pushed result ends with 「引用这条消息可以继续问。」 on WeChat and 「回复这条消息可以继续问。」 on Feishu, and still fits 300 characters. So "详细说说" on a quoted result is answered by the task itself.### Concurrency and the reserved human lane@@ -204,7 +207,7 @@ Settling lasts at most 30 minutes after a turn ends. After that, its jobs are ki### Stop, steer and model (dependency: P1)- **Stop** uses P1's `cancel(sessionId)`. The task's jobs are killed and its subagents released (superagent's `stopBackground`), and its tools are guarded. Today's only stop is `AgentHost.closeHarness()`, which kills chat and every task of the bot.-- **Steer** uses P1's `steer(sessionId, text)` for follow-ups.+- **Steer** uses P1's `steer(sessionId, text)` for follow-ups and for answers to a question with a default. The steered message carries the host's input id (`messageId` on the control op, because the command envelope's `id` is its own), so the host sees the session take it; until then the Run doesn't end.- **Model:** a task keeps the model it started with (P1's per-session model). Without it, `AgentHost.ensure()` would restart DSH on a chat model switch, and it already waits for `active === 0`. Task runs must count as active.### Restart recovery@@ -222,7 +225,7 @@ The spike shows that a restart keeps some things and loses others (A.5):The host therefore stores everything it owes a session, and recovers like this:1. **At start, and on every DSH child exit:** each Run in `running` or `settling` ends `interrupted`.-2. **For each such task:** a `recover` Run is queued, oldest task first and subject to slots. Tasks that wait for a person (stages 2–5) stay as they were, with one exception. A task blocked on an approval lost that approval with its turn, so it is recovered, and the agent asks again if it still needs to.+2. **For each such task:** a `recover` Run is queued, oldest task first and subject to slots. Tasks that wait for a person (stages 2–5) stay as they were, with one exception. A task blocked on an approval lost that approval with its turn, so it is recovered, and the agent asks again if it still needs to. A Run that had already asked a question without a default (it was settling, or finishing its turn) ends `needs_you` instead of being recovered; its recovery note waits as an input and goes to the session with the answer. Questions are not blocking approvals, so they survive the restart; an open question with a default stays open and its answer reaches the `recover` Run.3. **Inputs:** an input the session never took (no `user/message` event with its message id was seen) is delivered again. An input it took is never delivered again.4. **The recovery note** is the first message of the new Run. It is model-facing and in English, like our skills:@@ -305,7 +308,7 @@ Nothing below is ever pushed. It lives in the tasks view, the bot's info panel a| Push | When | Never || --- | --- | --- || **A result the user can use** | A task's `done` Report; a rule hit in act mode | Progress, "still working", partial drafts, retries, recovery after restart |-| **A decision the user must make** | A task question or an approval, one at a time per conversation | A question the agent could answer with a reasonable default; repeating an unchanged question |+| **A decision the user must make** | A task question (as soon as the task asks, with or without a default) or an approval, one at a time per conversation | A question the agent could decide itself; repeating an unchanged question || **A failure that needs them** | A task failed after automatic retries, or a rule paused after 3 failures | A one-off network error; a failure the agent can work around |The acknowledgement of a new task is the chat reply itself, so it costs no extra message. Observe mode pushes nothing.@@ -319,6 +322,8 @@ Every pushed message is one line, with an optional second line only for a blocke| Ack (part of the chat reply) | 好,后台开始调研三家云的 GPU 价格,好了告诉你,你可以继续聊别的。 | same text | same text, plus a task chip 「后台任务 · GPU 价格调研 · 进行中 ›」 || Result | GPU 价格调研好了:A100 包月最便宜的是 X 云,约 ¥7,800,报告已发给你。引用这条消息可以继续问。 | same line; buttons [详情] [继续改] | message in the conversation; the chip turns 已完成; OS notification only if the window isn't focused || Question | ❓「GPU 价格调研」想问你:报告用中文还是英文?<br>1. 中文<br>2. 英文<br>(回复编号,或引用这条消息回答) | question card with option buttons, as for `ask_user_question` today | the same card in the conversation and in "needs you" |+| Question with a default (the task keeps working) | ❓「GPU 价格调研」想问你:报告用中文还是英文?<br>1. 中文<br>2. 英文<br>不回复就按中文做<br>(回复编号,或引用这条消息回答) | the same card, with 不回复就按中文做 under the question | the card and the needs-you row carry 不回复就按中文做; the task row and chip read 进行中,有个问题等你回答 |+| Result after going with the default | 报告写好了,按中文做的,要英文的话引用这条说一声。引用这条消息可以继续问。 | same line | message in the conversation || Approval | 需批准(任务「清理旧构建」):`rm -rf build/` — 回复 y 4821 / n 4821 | the existing approval card, titled with the task | "needs you" row with [批准一次] [拒绝] || Failure | ⚠️「GPU 价格调研」没做完:X 云的价格页要登录,我进不去。发我一个能打开的链接,或者回复「停止」。 | same, with buttons [重试] [停止] | "needs you" row || Rule hit | X 降价了:现在 ¥199(昨天 ¥259)。 | same | message, with the rule named in small text |@@ -338,6 +343,19 @@ These rules apply to every pushed message. Replies within a user's active chat t- **Feishu:** reply in the thread of the request message when one exists. Results and questions are cards.- **Web/desktop:** an OS notification only for "needs you" items and for results the user asked for, only when the window isn't focused, and at most one per item. The tray badge is the needs-you count.+### Questions: ask early, keep working++As built (decided by the product owner after 3f). A question can wait for hours (quiet hours, the WeChat window), so a task asks as soon as it knows it needs to, and stops only when it must.++- **Two kinds.** `task_report` `needs_you` takes an optional `default` (one of `options` when options are given; a number is read as that option).+ - **With a default** (「报告用中文还是英文?」, default 中文): the host asks right away and the turn goes on. The tool result tells the agent to keep working on what doesn't depend on the answer. An answer reaches the running task at its next step, the same way as a follow-up (steered, or delivered as its next input while it settles). If the agent finishes first, it goes with the default, says so in its result (「按中文做了,要英文的话引用这条说一声」) and reports `done`; the host then withdraws the question everywhere: the ApprovalCenter row is cancelled (`decided_by = default`), so needs-you drops it, and a push that is still pending, scheduled or held is withdrawn. A push that was already sent can't be taken back: quoting it (WeChat) or tapping its card button (Feishu) later reaches the task as a late answer and resumes it; a bare number is ordinary chat.+ - **Must decide** (no safe default: paying, deleting, choosing an account, anything irreversible): unchanged, the agent ends its turn and the Run ends `needs_you` once the session is quiet.+- **Ask immediately.** Both kinds are created and pushed when `task_report` is called, not when the Run ends or settles. An answer that arrives while the Run still settles (background jobs) or while the host is checking whether it is quiet is delivered to the session as its next input; the Run doesn't end until the session took it.+- **What else ends a question.** A Run that ends `done` or `failed` withdraws the task's open questions (a failed task asks again on retry); a stopped or archived task withdraws them as before. Asking the same question again replaces the open one. A `budget` or `interrupted` Run leaves them open.+- **Stage.** A question with a default doesn't block: the task stays in the working group as `working/asking` (进行中,有个问题等你回答). The task detail shows the question, with 不回复就按中文做 under it; the needs-you row shows the question, its options and the same line; so do the pushed WeChat text and the Feishu card.+- **Unchanged.** One open pushed question per conversation (a question with a default that was pushed holds the slot until it is answered or withdrawn); quiet hours, daily caps and the WeChat window apply as before; approvals and the budget question still block; rules have no `needs_you`.+- **Prompt.** The task rules say: decide yourself when you can; with a reasonable default, ask as early as possible with `default` and keep doing only what doesn't depend on the answer; when only the user can decide, do the independent work first, then ask and end the turn.+### WeChat: the hard constraintiLink lets a bot message a user only with a `context_token` from that user's inbound message. AnyModelBot already treats this as hard.@@ -427,6 +445,7 @@ These use `ui/design/README.md`:┌─────────────────────────────────────────────────────────────┐│ ● 小蓝 · GPU 价格调研 · 等你回答 2 分钟前 ││ 报告用中文还是英文? │+│ 不回复就按中文做 │ only for a question with a default│ [中文] [英文] [回复…] ││─────────────────────────────────────────────────────────────││ ● 小蓝 · 清理旧构建 · 等你批准 5 分钟前 │@@ -456,6 +475,7 @@ Order: questions and approvals first (time-sensitive), then failures, then deliv进行中┌─────────────────────────────────────────────────────────────┐│ ● GPU 价格调研 小蓝 · 12 分钟 · 约 $0.08 › │ green+│ ● 竞品周报 进行中,有个问题等你回答 · 20 分钟 › │ green: asked, keeps working│ ● 季度报告 PPT 小蓝 · 等你回答 › │ amber└─────────────────────────────────────────────────────────────┘规则@@ -658,7 +678,7 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);| `task_message` | chat | `{task, text}`: steer a working task or resume a done one || `task_list` | chat | Open tasks and rules with their stage and latest line, read from the host without waking any task || `rule_create` | chat | `{title, instruction, schedule, kind}` → a rule in observe mode, or in act mode for a fixed reminder |-| `task_report` | task and rule | `{state: progress\|needs_you\|done\|failed, summary, message?, question?: {question, options?, multiSelect?}, files?, would?}` |+| `task_report` | task and rule | `{state: progress\|needs_you\|done\|failed, summary, message?, question?, options?, default?, files?, would?}`; `question` may also be `{question, options?, multiSelect?, default?}`. With `default`, `needs_you` is asked and the run goes on |**Bridge** (child → host; the existing loopback with a per-launch token):@@ -686,7 +706,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 30 idle days and the question withdrawn (decision 9) |+| Approval or question never answered | Blocking approval: rejected at its TTL; the task fails with 「批准超时」. Task question without a default: stays in needs-you; no reminders; the task is archived after 30 idle days and the question withdrawn (decision 9). Task question with a default: the task finishes with the default and the question is withdrawn || 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)) |@@ -706,7 +726,8 @@ CREATE INDEX IF NOT EXISTS deliveries_due ON deliveries(status, due_at);- slots, including the reserved person slot and priority order;- Report validation;- the recovery planner: which runs restart and which inputs are delivered again;- - `handleReply` routing for task questions (quote, code, bare number, ordinary chat).+ - `handleReply` routing for task questions (quote, code, bare number, ordinary chat);+ - questions asked right away: a question with a default keeps the run going, its answer is steered in, finishing first withdraws it (needs-you, ApprovalCenter, outbox) and a later quote resumes the task; a question without a default is pushed while the run settles and an answer then is delivered; restart keeps both kinds open.- **Integration against the real DSH and a mock model**, extending `test/agent.integration.test.ts` and `scripts/spikes/p3-tasks`:- a task gets its own folder and ends `done` with its result delivered;- question → answer → resume;diff --git a/dsh-runtime/plugins/amb-control.mjs b/dsh-runtime/plugins/amb-control.mjsindex 54b9e26..5e94bf5 100644--- a/dsh-runtime/plugins/amb-control.mjs+++ b/dsh-runtime/plugins/amb-control.mjs@@ -9,8 +9,10 @@// config read this map (as DSH's installModelSelection does)// providers {providers} replace llm-pi-ai's (volatile) provider profiles, so a model the// launch patch did not list becomes routable without a restart-// steer {sessionId, id, text, images} deliver a user message into the running turn (agent.steer: the-// model sees it at its next step); refused when the agent is idle+// steer {sessionId, messageId, text, images} deliver a user message into the running turn (agent.steer:+// the model sees it at its next step) under the host's message id (the+// session's user/message carries it; the command's own id is the+// envelope's); refused when the agent is idle// cancel {sessionId} cancel just this session's turn (agent.cancel), its subagents// and the shell jobs the turn started// idle {} how many agents are busy (not idle, or input queued) and how many@@ -214,7 +216,9 @@ export function apply(ctx) {await updateProviders(providers)return {}},- async steer({ sessionId, id, text, images }) {+ async steer({ sessionId, messageId, text, images }) {+ const id = String(messageId ?? '')+ if (!id) return { accepted: false, reason: 'no message id' }const agent = agents()?.get(String(sessionId))if (!agent) return { accepted: false, reason: 'no agent' }if (delivered.has(id) || pendingIds(agent).has(id)) return { accepted: true, duplicate: true }diff --git a/dsh-runtime/plugins/amb-tasks.mjs b/dsh-runtime/plugins/amb-tasks.mjsindex e230811..db04b05 100644--- a/dsh-runtime/plugins/amb-tasks.mjs+++ b/dsh-runtime/plugins/amb-tasks.mjs@@ -7,7 +7,8 @@// tools.restrict throws on unknown ones),// - adds the task rules (AMB_TASK_RULES, written by the host) as the last system-prompt section,// - registers task_report, which reports the task's state to the host (needs_you carries one question for the-// user; the host asks it and hands the answer back as the session's next input),+// user; the host asks it right away and hands the answer back as an input: with a default the task keeps working+// and the answer reaches its next step, without one the task ends its turn and waits),// - refuses every tool call once the host has stopped the task.// Chat sessions get task_start / task_message / task_list, rule_create / rule_update and background_pause (pause or// resume all of the bot's background work); subagents get none of them.@@ -176,7 +177,7 @@ export function apply(ctx) {const reportTool = () => defineTool({name: 'task_report',- description: 'Report this background task\'s state to the app. done: finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. needs_you: only the user can decide; the app asks them question, and their answer is your next message. progress is recorded, never sent. After done, failed or needs_you, end your turn.',+ description: 'Report this background task\'s state to the app. done: finished. failed: you cannot finish it. For both, message is the one line the user receives (at most 300 characters, in their language): the result and where it is; files are files to send them. needs_you: the app asks the user question now. With default, keep working on what does not depend on the answer; if you finish first, use default and say so in message. Without default (only the user can decide), their answer is your next message. progress is recorded, never sent. After done, failed or needs_you without default, end your turn.',parameters: {state: { type: 'string', required: true, enum: ['progress', 'needs_you', 'done', 'failed'] },summary: { type: 'string', required: true, description: 'What you did and found, for the record (not sent to the user).' },@@ -184,6 +185,7 @@ export function apply(ctx) {files: { type: 'array', items: { type: 'string' }, description: 'Paths of files to send to the user, relative to your folder.' },question: { type: 'string', description: 'For needs_you: one short question.' },options: { type: 'array', items: { type: 'string' }, description: 'For needs_you: choices, if any.' },+ default: { type: 'string', description: 'For needs_you: the answer you go with if they do not reply (one of options). Omit it when only the user can decide.' },},output: TEXT_OUT,execute: (args, exec) => host('/dsh/task-report', { sessionId: sessionOf(exec), ...args }, exec.signal),diff --git a/src/agent/approvals.ts b/src/agent/approvals.tsindex 8903ab4..40299c5 100644--- a/src/agent/approvals.ts+++ b/src/agent/approvals.ts@@ -16,6 +16,8 @@ export interface QuestionItem {header?: string;options?: Array<{ label: string; description?: string }>;multiSelect?: boolean;+ /** 后台任务的提问:用户没回答时任务按它做(任务接着做,不等);有选项时是其中一个 */+ default?: string;}export interface QuestionAnswer {answers: Array<{ id: string; selected: string[]; custom?: string }>;@@ -339,6 +341,17 @@ export function questionsOf(row: ApprovalRow): QuestionItem[] {return row.kind === "question" ? safeJson<QuestionItem[]>(row.payload, []) : [];}+/** 任务提问的默认回答(有就说明任务不等:没回答就按它做) */+export function defaultOf(row: ApprovalRow): string | undefined {+ return questionsOf(row)[0]?.default || undefined;+}++/** 有默认回答的提问那一句:「不回复就按中文做」(「需要你」、推出去的提问、网页的卡片) */+export function defaultLine(row: ApprovalRow): string | undefined {+ const d = defaultOf(row);+ return d ? t("approvals.taskDefault", { answer: d }) : undefined;+}+/** 只是选项编号(多选可以几个)或某个选项的原文:光回这个才算回答"最后一条消息"的那个提问 */export function isOptionReply(questions: QuestionItem[], text: string): boolean {const q = questions.length === 1 ? questions[0] : undefined;@@ -403,7 +416,8 @@ export function promptText(row: ApprovalRow): string {/*** 后台任务推给用户的提示(设计第 6 节的消息样式):- * 提问「❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)」;+ * 提问「❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n(回复编号,或引用这条消息回答)」,+ * 有默认回答的在选项后面多一行「不回复就按中文做」;* 审批「需批准(任务「清理旧构建」):`rm -rf build/` — 回复 y 4821 / n 4821」。*/export function taskPromptText(row: ApprovalRow, title: string): string {@@ -414,7 +428,8 @@ export function taskPromptText(row: ApprovalRow, title: string): string {const q = questionsOf(row)[0];const opts = (q?.options ?? []).map((o, i) => `${i + 1}. ${o.label}`);const hint = opts.length ? t("approvals.taskHintOptions", { multi: q?.multiSelect ? t("approvals.taskHintMulti") : "" }) : t("approvals.taskHintQuote");- return [t("approvals.taskQuestion", { title, question: q?.question ?? row.detail }), ...opts, hint].join("\n");+ const fallback = defaultLine(row);+ return [t("approvals.taskQuestion", { title, question: q?.question ?? row.detail }), ...opts, ...(fallback ? [fallback] : []), hint].join("\n");}/** 卡片渠道(飞书)的按钮:审批是允许 / 拒绝;单选的提问是每个选项一个按钮 */diff --git a/src/agent/host.ts b/src/agent/host.tsindex 61c59a3..07dbe2a 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -1678,10 +1678,13 @@ exec "$REAL" "$@"return await h.client.prompt(o.sessionId, [{ type: "text", text: o.text }]);}- /** 并进任务正在进行的一轮(agent.steer,id 是我们的输入 id,会话里的用户消息用同一个 id);会话空闲时返回 false */+ /**+ * 并进任务正在进行的一轮(agent.steer,messageId 是我们的输入 id,会话里的用户消息用同一个 id:任务服务按它记下"收下了");+ * 会话空闲时返回 false。不能叫 id:那是指令自己的 id(control.ts 的 send 会盖掉它)+ */async steerTask(sessionId: string, id: string, text: string): Promise<boolean> {if (!this.control.connected) return false;- const r = await this.control.send<{ accepted?: boolean }>("steer", { sessionId, id, text, images: [] }, 15_000);+ const r = await this.control.send<{ accepted?: boolean }>("steer", { sessionId, messageId: id, text, images: [] }, 15_000);return !!r.accepted;}@@ -1826,7 +1829,7 @@ exec "$REAL" "$@"const images = this.imageInput && acceptsImages(t.model) ? (msg.images ?? []) : [];for (let i = 0; i < 2 && this.control.connected; i++) {try {- const r = await this.control.send<{ accepted?: boolean; reason?: string }>("steer", { sessionId: t.sessionId, id: msg.id, text: msg.text, images }, 15_000);+ const r = await this.control.send<{ accepted?: boolean; reason?: string }>("steer", { sessionId: t.sessionId, messageId: msg.id, text: msg.text, images }, 15_000);if (!r.accepted) log.info("steer refused; the message waits for the next turn", { bot: this.o.botId, reason: r.reason });return !!r.accepted;} catch (e) {diff --git a/src/agent/prompts/tasks.ts b/src/agent/prompts/tasks.tsindex 1766920..fd5dd19 100644--- a/src/agent/prompts/tasks.ts+++ b/src/agent/prompts/tasks.ts@@ -3,7 +3,8 @@* 重启后的恢复说明、没有报告时的提醒。改这里的文字要过 test/prompts.unit.test.ts(必须有、不能有的句子和长度上限)。** 沟通规则改编自 dsh-superagent(MIT,DeepSeek)的 worker 提示词:只在做完、需要决定或做不下去时说话,一句话,不汇报进展。- * 需要决定时(3b):先自己选合理的默认;非用户定不可才报 needs_you,一次一个问题,回答作为下一条消息回来。+ * 需要决定时(3b):先自己选合理的默认;要问就一次一个问题。有合理默认的尽早问、带上 default,接着做不依赖回答的部分,+ * 没等到回答就按默认做完、在结果里说明;非用户定不可的(付款、删除、选账号),先做完不依赖它的部分再问,结束这一轮等回答。*//** 任务会话的系统提示词段:名字与位置(排在机器人段 amb:bot 之后,同时冲突时以它为准) */@@ -14,7 +15,9 @@ export const TASK_SECTION_ORDER = 20_100;export const TASK_RULES = ["# 后台任务(优先于上面的聊天规则)","你在后台独立完成一个任务,用户不在旁边。任务和用户的原话在第一条消息里;当前目录是这个任务的文件夹,产出的文件放在这里。",- "- 能自己定的就选一个合理的做法,在结果里说明;非用户定不可才问:task_report 报 needs_you 和一个问题(有选项就给),结束这一轮。",+ "- 能自己定的就选一个合理的做法,在结果里说明。要问用户就用 task_report 报 needs_you 和一个问题(有选项就给):",+ " 有合理默认的尽早问、给 default,接着只做不依赖回答的部分,做完还没回答就按默认;",+ " 非用户定不可的(付款、删除、选账号),先做完不依赖它的部分再问,然后结束这一轮。","- 做会改变外部的事(发送、发帖、付款、删除、调用会改动东西的接口)之前和之后,各在 .task/journal.md 里追加一行。","- 做完或做不下去时调用 task_report:state 为 done 或 failed,message 是给用户的一句话(不超过 300 字:结果是什么、在哪里),files 列出要发给用户的文件。然后结束这一轮。","- 中途不用汇报;想记下进展可以报 progress,不会发给用户。",diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex 4e13ba6..f9a206c 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -10,7 +10,7 @@ import { describeStep, fmtSecs, type ActivityStep } from "../agent/activity.js";import type { Store } from "../store/db.js";import { logger } from "../log.js";import type { AgentManager } from "../agent/manager.js";-import { promptButtons, promptText } from "../agent/approvals.js";+import { promptButtons, promptText, questionsOf } from "../agent/approvals.js";import { segmentInput, type ChatPlace } from "../agent/prompts/index.js";import { clearInflight, markInflight, takeNotice } from "./recovery.js";import { pwshProbe, pwshStatusLine } from "../agent/pwsh.js";@@ -507,6 +507,12 @@ export class BotRuntime {const agent = this.opts.agent;const row = agent && value?.id ? this.opts.store.getApproval(String(value.id)) : undefined;if (!agent || !row || row.botId !== botId) return { toast: t("runtime.requestMissing"), ok: false };+ if (row.status !== "pending" && value.amb === "question" && row.taskId) {+ // 后台任务按默认回答先做完了、提问撤回了,卡片上的按钮还点得到:当作迟到的回答交给任务(同引用那条提问)+ const opt = (questionsOf(row)[0]?.options ?? [])[Number(value.option) - 1]?.label;+ const late = opt ? agent.tasks?.answerWithdrawn(row.id, opt) : undefined;+ if (late?.handled) return { toast: late.ack ?? t("runtime.submitted"), ok: true };+ }if (row.status !== "pending") return { toast: t("runtime.requestDone", { code: row.code }), ok: false };if (value.amb === "approval") {const allow = value.decision === "allow";diff --git a/src/i18n/messages/approvals.ts b/src/i18n/messages/approvals.tsindex bd68e13..afdab65 100644--- a/src/i18n/messages/approvals.ts+++ b/src/i18n/messages/approvals.ts@@ -21,6 +21,7 @@ export const zh = {taskHintOptions: "(回复编号{multi},或引用这条消息回答)",taskHintMulti: ",可多选",taskHintQuote: "(引用这条消息回答)",+ taskDefault: "不回复就按{answer}做",allowOnce: "允许(仅本次)",deny: "拒绝",} satisfies Catalog;@@ -45,6 +46,7 @@ export const en: Catalog<typeof zh> = {taskHintOptions: "(reply with a number{multi}, or quote this message to answer)",taskHintMulti: "; you can pick several",taskHintQuote: "(quote this message to answer)",+ taskDefault: "If you don't reply, it goes with {answer}",allowOnce: "Allow (once)",deny: "Deny",};diff --git a/src/i18n/messages/tasks.ts b/src/i18n/messages/tasks.tsindex 2b3b8e0..1e323a0 100644--- a/src/i18n/messages/tasks.ts+++ b/src/i18n/messages/tasks.ts@@ -11,6 +11,7 @@ export const zh = {stageReady: "已完成",stageQueued: "排队中",stageWorking: "进行中",+ stageAsking: "进行中,有个问题等你回答",recoverAppRestart: "应用重启",recoverAgentExit: "代理进程退出",stoppedNoFollowup: "「{title}」已停止,不能再追加;需要的话开个新任务。",@@ -94,6 +95,7 @@ export const en: Catalog<typeof zh> = {stageReady: "Done",stageQueued: "Queued",stageWorking: "In progress",+ stageAsking: "In progress, with a question for you",recoverAppRestart: "the app restarted",recoverAgentExit: "the agent process exited",stoppedNoFollowup: "\"{title}\" has stopped and can't take follow-ups; start a new task if you need to.",diff --git a/src/store/db.ts b/src/store/db.tsindex e862e3f..5dc9940 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -213,8 +213,10 @@ export interface TaskReport {/** 3d 规则:观察时本会做的事(执行时做了的事) */would?: string;files?: string[];- /** 3b:要问用户的一个问题 */- question?: { question: string; options?: string[]; multiSelect?: boolean };+ /**+ * 3b:要问用户的一个问题。default:有合理默认的问题(用户没回答就按它做,任务不停下来等);没有 = 非用户定不可,这一轮结束、任务等着+ */+ question?: { question: string; options?: string[]; multiSelect?: boolean; default?: string };at: number;}export interface TaskRow {diff --git a/src/tasks/attention.ts b/src/tasks/attention.tsindex af84098..a1918e2 100644--- a/src/tasks/attention.ts+++ b/src/tasks/attention.ts@@ -8,7 +8,7 @@* 健康时什么都没有:没有行、没有角标、没有通知。*/import type { ApprovalRow, Store } from "../store/db.js";-import { questionsOf, type QuestionItem } from "../agent/approvals.js";+import { defaultLine, questionsOf, type QuestionItem } from "../agent/approvals.js";import type { AttentionItem as DeliveryItem } from "../core/delivery.js";import { logger } from "../log.js";import { t as tr } from "../i18n/index.js";@@ -40,6 +40,8 @@ export interface AttentionItem {status: string;/** 第二行:问题、命令、失败原因、没送到的那句话 */line: string;+ /** 有默认回答的提问:不回答会怎样(「不回复就按中文做」);任务这时还在做 */+ note?: string;since: number;severity: "warn" | "err";actions: AttentionAction[];@@ -188,6 +190,7 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[const channel = store.getConversation(r.conversationId)?.channel ?? r.conversationId.split(":")[1] ?? "";const qs = questionsOf(r);const line = r.kind === "approval" ? r.detail || r.reason || r.tool : qs.map((q) => q.question).join(" / ") || r.detail;+ const note = r.kind === "question" ? defaultLine(r) : undefined;return {id: `approval:${r.id}`,kind: r.kind,@@ -197,6 +200,7 @@ export function approvalItems(store: Store, rows: ApprovalRow[]): AttentionItem[// 任务预算用完时问的那个:状态是预算用完(第二行就是「已用约 $1.00,再给 $1 继续?」)status: r.kind === "approval" ? tr("tasks.stageApproval") : r.tool === BUDGET_TOOL ? tr("tasks.stageBudget") : tr("tasks.stageAnswer"),line: line.length > 300 ? line.slice(0, 299) + "…" : line,+ ...(note ? { note } : {}),since: r.createdAt,severity: "warn",actions: r.kind === "approval" ? ["approve", "deny"] : ["answer"],diff --git a/src/tasks/service.ts b/src/tasks/service.tsindex e615504..6fb8b78 100644--- a/src/tasks/service.ts+++ b/src/tasks/service.ts@@ -12,8 +12,11 @@* 跑着的 run 记为 interrupted,给任务排一个恢复 run:先交一条恢复说明,没被会话收下的输入再交一次,收下过的不再交。* - 停止只停这个任务(指令通道:取消这一轮、停它的后台命令、之后的工具调用一律拒绝),聊天和别的任务照常。*- * - 提问(3b):代理报 needs_you 带一个问题,这一轮结束时变成审批中心里一条不阻塞、不过期的提问,推给请求它的会话- * (一个会话同时只推一个);回答成为任务的新输入,任务在人的名额里接着做。任务会话里的审批也推过去(阻塞、12 小时)。+ * - 提问(3b):代理报 needs_you 带一个问题,马上变成审批中心里一条不阻塞、不过期的提问,推给请求它的会话+ * (一个会话同时只推一个);回答成为任务的新输入(同追加:在跑就并进去,结束了就在人的名额里接着做)。+ * 带默认回答的问题不停下来等:代理接着做不依赖回答的部分,先做完就按默认做、在结果里说一声,提问随之撤回(「需要你」、+ * 推送都撤);之后引用那条提问回答,同引用结果一样交给任务接着做。没带默认的(非用户定不可)这一轮结束、任务等着。+ * 任务会话里的审批也推过去(阻塞、12 小时)。** - 规则(3d):一条规则每次运行开一个新会话(rule-<规则>-<run>,工作目录是 rules/<slug>-<id6>/),和任务的 run 走同一套* 排队、名额、收尾、提醒、重试;不同的是结束之后(见「规则」一节):观察只记「本会发送」,执行时那一句经出站队列发出去,@@ -36,7 +39,7 @@ import { needsPerson, type Delivery } from "../core/delivery.js";import { sentText } from "../core/outbox.js";import { ActivityLog, type ActivityStep } from "../agent/activity.js";import { ResumeFailed, deliverables } from "../agent/host.js";-import { answerLine, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";+import { answerLine, defaultLine, defaultOf, parseAnswer, promptButtons, questionsOf, taskPromptText, type ApprovalCenter, type ApprovalEvent, type QuestionItem, type ReplyContext } from "../agent/approvals.js";import { actionCardSpec } from "../channels/feishu/transport.js";import { NUDGE, RULE_NUDGE, RULE_RERUN, RULE_RESULT_SYSTEM, attachmentsOf, rebrief, recoveryNote, resumeNote, retryNote, ruleBrief, ruleResultInput, ruleRules, taskBrief } from "../agent/prompts/index.js";import type { BotSettings } from "../agent/settings.js";@@ -196,6 +199,8 @@ export interface TaskView {budgetUsd: number;/** 3f:文件夹定在什么时候清理(30 天没动过、告诉过用户);0 = 没定 */cleanupAt: number;+ /** 它问用户的、还没回答的问题;note:有默认回答时那一句「不回复就按中文做」 */+ question?: { text: string; note?: string };/** 正在跑的那个 run:开始时间与步数 */live?: { runId: string; since: number; steps: number; current?: ActivityStep };}@@ -444,7 +449,12 @@ export class TaskService {if (!task || task.endedAt) continue;const jobs = steps.filter((s) => s.kind === "job" && s.status === "running").map((s) => clip(oneLine(s.summary || s.title), 120));this.addInput(task.id, "recovery", recoveryNote(jobs), false);- if (!this.queuedRun(task.id)) this.enqueue(task, "recover");+ // 这一轮已经报了 needs_you(没有默认回答)、问题还开着(收尾时重启的):它本来就在等回答,run 记为 needs_you,不排恢复;+ // 恢复说明跟着回答交给下一个 run。带默认回答的照常恢复:问题开着,回答到了交给恢复的 run+ const final = l?.final ?? run.report;+ const waits = final?.state === "needs_you" && !final.question?.default && (this.o.approvals?.pendingForTask(task.id) ?? []).some((a) => a.kind === "question" && a.tool === "task_report" && !defaultOf(a));+ if (waits) this.store.updateRun(run.id, { outcome: "needs_you", error: "" });+ else if (!this.queuedRun(task.id)) this.enqueue(task, "recover");this.changed(task.id);}}@@ -731,7 +741,11 @@ export class TaskService {const task = l.ruleId ? undefined : this.store.getTask(l.taskId);if (!task && !l.ruleId) return;l.starting = true;- l.settling = false;+ if (l.settling) {+ // 收尾中又有输入(回答、追加):又在跑了+ l.settling = false;+ this.store.updateRun(l.runId, { state: "running" });+ }if (inputs.some((i) => i.fromPerson)) this.reopen(l);const text = inputs.map((i) => i.text).join("\n\n");const folder = task ? path.join(this.o.host.workspace(task.botId), task.folder) : l.folder;@@ -1074,6 +1088,9 @@ export class TaskService {l.checking = false;}if (this.live.get(l.runId) !== l || l.busy || l.starting) return;+ // 问插件的时候来了输入(回答、追加):先交给会话,不结束+ const late = this.inputsOf(l).filter((i) => !i.deliveredAt);+ if (late.length) return void this.deliver_(l, late);if (q.quiet) return this.finish(l);l.settling = true;this.store.updateRun(l.runId, { state: "settling" });@@ -1084,7 +1101,14 @@ export class TaskService {settled(b: any): { ok: true } {const l = this.bySession.get(String(b?.sessionId ?? ""));if (!l || l.busy || l.starting || l.checking) return { ok: true };- if (this.inputsOf(l).some((i) => i.deliveredAt && i.runId === l.runId)) return { ok: true };+ const open = this.inputsOf(l);+ if (open.some((i) => i.deliveredAt && i.runId === l.runId)) return { ok: true };+ // 收尾时来了还没交出去的输入(回答、追加):交给会话,接着做,不结束+ const waiting = open.filter((i) => !i.deliveredAt);+ if (waiting.length) {+ void this.deliver_(l, waiting);+ return { ok: true };+ }const killed = Array.isArray(b?.killedJobs) ? b.killedJobs.map(String) : [];if (killed.length) log.info("task settling timed out; background jobs were stopped", { task: l.taskId || l.ruleId, jobs: killed });this.finish(l);@@ -1131,6 +1155,9 @@ export class TaskService {if (task && outcome === "done") this.store.updateTask(task.id, { endedAt: now, endReason: "done", updatedAt: now });else if (task) this.store.updateTask(task.id, { updatedAt: now });if (task && (outcome === "done" || outcome === "failed")) this.deliver(task, l.runId, outcome, report, error);+ // 做完了还没回答的提问:有默认回答的就是按默认做了(结果里说了),作废、撤回;失败了也一样(重试时它会再问)+ if (task && (outcome === "done" || outcome === "failed")) this.withdrawQuestions(task, outcome === "done" ? "default" : "failed");+ // 报 needs_you 时已经问了(report);这里只是兜底(同一个 run 同一个问题不会问两次)if (task && outcome === "needs_you" && report?.question) this.ask(task, l.runId, report.question);if (task && outcome === "budget") this.askBudget(task, l.runId);log.info("background task run ended", { task: l.taskId, run: l.runId, outcome, ...(error ? { error } : {}) });@@ -1226,7 +1253,10 @@ export class TaskService {// ---------- 插件经 bridge 来的 ----------- /** task_report:记下 Report;done / failed 在这一轮结束、会话安静后发给用户,needs_you 的问题那时问用户 */+ /**+ * task_report:记下 Report;done / failed 在这一轮结束、会话安静后发给用户。needs_you 的问题马上问用户(推出去、进「需要你」):+ * 带默认回答的,代理接着做(回答在它的下一步到,同追加);没带的,代理结束这一轮,安静后 run 以 needs_you 结束、任务等着回答。+ */report(b: any): { text?: string; error?: string } {const l = this.bySession.get(String(b?.sessionId ?? ""));if (!l) return { error: "This background task is not running any more (it was stopped or has ended). Stop working on it." };@@ -1235,6 +1265,7 @@ export class TaskService {if (state !== "progress" && state !== "done" && state !== "failed" && state !== "needs_you") return { error: "state must be progress, needs_you, done or failed" };const question = state === "needs_you" ? questionOf(b) : undefined;if (state === "needs_you" && !question) return { error: "needs_you needs a question: one question for the user, with options when there are clear choices." };+ if (question?.default && question.options?.length && !question.options.includes(question.default)) return { error: `default must be one of the options: ${question.options.join(" / ")}.` };if (state === "needs_you" && !this.o.approvals) return { error: "The app cannot ask the user right now. Decide yourself and say so in the result." };const message = typeof b?.message === "string" ? oneLine(b.message) : "";const report: TaskReport = {@@ -1247,9 +1278,16 @@ export class TaskService {};this.store.updateRun(l.runId, { report });this.store.updateTask(l.taskId, { report, updatedAt: this.now() });- if (state !== "progress") l.final = report;+ // 带默认回答的问题不结束这个 run(代理接着做),其余的 done / failed / needs_you 是这一轮的结果+ if (state !== "progress" && !question?.default) l.final = report;+ const task = question ? this.store.getTask(l.taskId) : undefined;+ if (task && question) this.ask(task, l.runId, question);this.changed(l.taskId);if (state === "progress") return { text: "Progress recorded (it is not sent to the user). Continue the task." };+ if (question?.default)+ return {+ text: `Asked the user. Keep working on what does not depend on the answer; if they answer, it arrives as a message at your next step. If you finish first, use "${question.default}", say so in your message, and report done.`,+ };if (state === "needs_you") return { text: "Recorded. End your turn now: the app asks the user, and their answer arrives as your next message." };return { text: `Recorded. End your turn now: the app sends your message to the user${state === "done" && !message ? " (you gave no message, so the user only hears that the task is done)" : ""}.` };}@@ -1337,14 +1375,42 @@ export class TaskService {// ---------- 提问与审批(3b) ----------- /** 代理报了 needs_you、这一轮结束了:问题记成一条不阻塞、不过期的提问(每个 run 只问一次),给聊天代理留张便条 */+ /**+ * 代理报了 needs_you:马上把问题记成一条不阻塞、不过期的提问(审批中心建好就推,见 onApproval),给聊天代理留张便条。+ * 同一个问题只问一次:还开着的(重启后恢复的 run 又问一遍),或这个 run 里问过的(重启后补问)都不再问;+ * 同一个问题换了默认回答(或去掉了默认),开着的那个作废、以新的为准。+ */private ask(task: TaskRow, runId: string, q: NonNullable<TaskReport["question"]>): void {const a = this.o.approvals;- if (!a || this.store.listApprovals({ runId, limit: 5 }).some((r) => r.kind === "question" && r.taskId === task.id)) return;- const item: QuestionItem = { id: "answer", question: q.question, ...(q.options?.length ? { options: q.options.map((label) => ({ label })) } : {}), ...(q.multiSelect ? { multiSelect: true } : {}) };+ if (!a) return;+ const same = this.store.listApprovals({ taskId: task.id, limit: 100 }).filter((r) => r.kind === "question" && r.tool === "task_report" && r.detail === q.question);+ if (same.some((r) => (r.status === "pending" || r.runId === runId) && (defaultOf(r) ?? "") === (q.default ?? ""))) return;+ for (const r of same) if (r.status === "pending") a.cancel(r.id, "superseded");+ const item: QuestionItem = {+ id: "answer",+ question: q.question,+ ...(q.options?.length ? { options: q.options.map((label) => ({ label })) } : {}),+ ...(q.multiSelect ? { multiSelect: true } : {}),+ ...(q.default ? { default: q.default } : {}),+ };a.create({ kind: "question", botId: task.botId, conversationId: task.conversationId, sessionId: task.sessionId, tool: "task_report", detail: q.question, reason: "", payload: JSON.stringify([item]), taskId: task.id, runId, blocking: false, ttlMs: 0 });- log.info("background task asks the user", { task: task.id, run: runId });- this.note(task.conversationId, `[后台任务「${task.title}」在等用户回答:${q.question}${q.options?.length ? `(${q.options.join(" / ")})` : ""}。用户在聊天里回答它时,用 task_message 转给这个任务]`);+ log.info("background task asks the user", { task: task.id, run: runId, ...(q.default ? { keepsWorking: true } : {}) });+ const opts = q.options?.length ? `(${q.options.join(" / ")})` : "";+ this.note(+ task.conversationId,+ q.default+ ? `[后台任务「${task.title}」问了用户:${q.question}${opts},没回答就按「${q.default}」做,任务照常在做。用户在聊天里回答它时,用 task_message 转给这个任务]`+ : `[后台任务「${task.title}」在等用户回答:${q.question}${opts}。用户在聊天里回答它时,用 task_message 转给这个任务]`,+ );+ }++ /** 任务做完了(按默认回答做的,或做不下去了):它还开着的提问作废,「需要你」里的、推给用户还没发出去的随之撤回(onApproval) */+ private withdrawQuestions(task: TaskRow, by: "default" | "failed"): void {+ for (const r of this.o.approvals?.pendingForTask(task.id) ?? []) {+ if (r.kind !== "question" || r.tool !== "task_report") continue;+ this.o.approvals!.cancel(r.id, by);+ log.info("withdrew a background task's open question", { task: task.id, by, ...(defaultOf(r) ? { usedDefault: by === "default" } : {}) });+ }}/** 审批中心有新的、或有了决定:任务的提问有了回答就交给任务;更新阶段;同一会话的下一个提问可以推了 */@@ -1481,7 +1547,8 @@ export class TaskService {const replyTo = task.originRef || replyHandle(this.store, conv.id).messageId || "";const buttons = promptButtons(row);const title = row.kind === "approval" ? tr("tasks.approvalTitle", { title: task.title }) : tr("tasks.questionTitle", { title: task.title });- const body = row.kind === "approval" ? (row.detail ? "`" + row.detail.slice(0, 300) + "`" : row.tool) : (questionsOf(row)[0]?.question ?? row.detail);+ const fallback = defaultLine(row);+ const body = row.kind === "approval" ? (row.detail ? "`" + row.detail.slice(0, 300) + "`" : row.tool) : `${questionsOf(row)[0]?.question ?? row.detail}${fallback ? `\n${fallback}` : ""}`;if (replyTo && buttons) delivery.push({ ...base, replyTo, card: actionCardSpec(title, body, buttons) });else delivery.push({ ...base, replyTo, kind: replyTo ? "text" : "notice" });}@@ -1514,42 +1581,83 @@ export class TaskService {followUp(conversationId: string, m: { text: string; quote?: string; rootId?: string; parentId?: string }): { handled: boolean; ack?: string } {const text = m.text.trim();if (!text || text.startsWith("/")) return { handled: false };- const task = this.followTarget(conversationId, m);- if (!task) return { handled: false };+ const hit = this.followTarget(conversationId, m);+ if (!hit) return { handled: false };+ const { task, asked } = hit;if (task.endReason === "stopped") return { handled: true, ack: tr("tasks.stoppedNoFollowup", { title: task.title }) };+ if (asked) return this.lateAnswer(task, asked, text);log.info("a follow-up goes straight to its background task", { task: task.id, by: m.quote ? "quote" : "thread" });void this.message(task.id, text).catch((e) => log.warn("follow-up to a background task failed", { task: task.id, message: (e as Error).message.slice(0, 200) }));return { handled: true, ack: tr("tasks.continuing", { title: task.title }) };}/**- * 引用的是哪个任务推出去的结果或失败那句(按发出去的原文比,取最像的,见 quoteScore);飞书按回复链的根、直接回复的那条比请求那条消息。+ * 引用的是哪个任务推出去的结果或失败那句(按发出去的原文比,取最像的,见 quoteScore),或它推出去、之后撤回了的提问+ * (任务按默认回答先做完了,asked 是那一条);飞书按回复链的根、直接回复的那条比请求那条消息。* 对上不止一个(引用了合成的摘要、一条消息开了两个任务)就不算*/- private followTarget(conversationId: string, m: { quote?: string; rootId?: string; parentId?: string }): TaskRow | undefined {+ private followTarget(conversationId: string, m: { quote?: string; rootId?: string; parentId?: string }): { task: TaskRow; asked?: ApprovalRow } | undefined {const tasks = this.store.listTasks({ conversationId, limit: 50 });- let hits: TaskRow[] = [];+ let hits: Array<{ task: TaskRow; asked?: ApprovalRow }> = [];if (m.quote) {const quote = m.quote;- const score = (t: TaskRow) =>- Math.max(- 0,- ...this.store.listRuns({ taskId: t.id }).map((r) => {- if (!/^task:[^:]+:(result|failure):/.test(r.delivery) || r.delivery.endsWith(":dropped")) return 0;- const row = this.store.getOutbox(r.delivery);- return row ? quoteScore(sentText(row.body), row.body.text ?? "", quote) : 0;- }),- );- const scored = tasks.map((t) => ({ t, s: score(t) }));+ const score = (t: TaskRow): { s: number; asked?: ApprovalRow } => {+ let best: { s: number; asked?: ApprovalRow } = { s: 0 };+ for (const r of this.store.listRuns({ taskId: t.id })) {+ if (!/^task:[^:]+:(result|failure):/.test(r.delivery) || r.delivery.endsWith(":dropped")) continue;+ const row = this.store.getOutbox(r.delivery);+ const s = row ? quoteScore(sentText(row.body), row.body.text ?? "", quote) : 0;+ if (s > best.s) best = { s };+ }+ for (const a of this.withdrawnAsks(t.id)) {+ const row = this.store.getOutbox(askId(a));+ if (row?.status !== "sent") continue;+ const s = Math.max(quoteScore(sentText(row.body), row.body.text ?? "", quote), quotes(row.body.text ?? "", quote, questionsOf(a)[0]?.question ?? a.detail) ? 2 : 0);+ if (s > best.s) best = { s, asked: a };+ }+ return best;+ };+ const scored = tasks.map((t) => ({ task: t, ...score(t) }));const best = Math.max(0, ...scored.map((x) => x.s));- hits = best ? scored.filter((x) => x.s === best).map((x) => x.t) : [];+ hits = best ? scored.filter((x) => x.s === best).map((x) => ({ task: x.task, asked: x.asked })) : [];} else {const refs = [m.rootId, m.parentId].filter(Boolean);- if (refs.length) hits = tasks.filter((t) => !!t.originRef && refs.includes(t.originRef));+ if (refs.length) hits = tasks.filter((t) => !!t.originRef && refs.includes(t.originRef)).map((task) => ({ task }));}return hits.length === 1 ? hits[0] : undefined;}+ /** 任务问过、因为它先做完了(按默认回答)或失败了而撤回的提问(新的在前) */+ private withdrawnAsks(taskId: string): ApprovalRow[] {+ return this.store.listApprovals({ taskId, status: "cancelled", limit: 20 }).filter((a) => a.kind === "question" && a.tool === "task_report" && (a.decidedBy === "default" || a.decidedBy === "failed"));+ }++ /**+ * 撤回了的提问又被回答了(微信引用那条提问、飞书点了卡片上的按钮):任务已经按默认做完(或失败了),这个回答作为追加交给它,+ * 在同一个任务里接着做(人的唤醒),回一句收到。编号按那个问题的选项认。+ */+ private lateAnswer(task: TaskRow, asked: ApprovalRow, text: string): { handled: boolean; ack?: string } {+ if (task.endReason === "stopped") return { handled: true, ack: tr("tasks.stoppedNoFollowup", { title: task.title }) };+ if (task.endReason === "archived") return { handled: true, ack: tr("tasks.archivedNoFollowup", { title: task.title }) };+ const qs = questionsOf(asked);+ const a = parseAnswer(qs, text).answers[0];+ const said = a ? [...a.selected, ...(a.custom ? [a.custom] : [])].join("、") : text;+ const used = asked.decidedBy === "default" ? defaultOf(asked) : undefined;+ const head = used ? `[用户回答了你之前问的问题(你已经按「${used}」做完了)]` : "[用户回答了你之前问的问题]";+ const input = this.addInput(task.id, "answer", `${head}\n问题:${qs[0]?.question ?? asked.detail}\n回答:${said || text}`, true);+ log.info("a late answer to a withdrawn question goes to its background task", { task: task.id });+ void this.wake(task, input, "answer").catch((e) => log.warn("late answer to a background task failed", { task: task.id, message: (e as Error).message.slice(0, 200) }));+ return { handled: true, ack: tr("tasks.continuing", { title: task.title }) };+ }++ /** 飞书卡片上的按钮:提问已经撤回(任务按默认先做完了),按钮还点得到——当作迟到的回答(同引用那条提问) */+ answerWithdrawn(approvalId: string, text: string): { handled: boolean; ack?: string } {+ const row = this.store.getApproval(approvalId);+ const task = row?.taskId ? this.store.getTask(row.taskId) : undefined;+ if (!row || !task || !this.withdrawnAsks(task.id).some((a) => a.id === row.id)) return { handled: false };+ return this.lateAnswer(task, row, text);+ }+/*** "需要你"里任务那一份:失败的;预算用完的(平常由审批中心那一份给:那个「再给 $1 继续?」的提问;这里只在它不在时补上);* 机器人的预算留给聊天、后台工作停着的(一个机器人一行,没有后台工作时不提)。@@ -1620,8 +1728,11 @@ export class TaskService {const rows = this.store.listApprovals({ status: "pending", botId: task.botId, limit: 200 }).filter((a) => (a.taskId === task.id || a.sessionId === task.sessionId) && a.tool !== BUDGET_TOOL && (a.expiresAt === 0 || a.expiresAt > now));- const waiting = rows.some((a) => a.kind === "approval") ? "approval" : rows.length ? "answer" : undefined;- return taskStage({ stopped: task.endReason === "stopped", undelivered: needsPerson(delivery), waiting, run });+ // 有默认回答的提问不算等你:任务接着做(进行中,有个问题等你回答)+ const blocking = rows.filter((a) => a.kind === "approval" || !defaultOf(a));+ const waiting = blocking.some((a) => a.kind === "approval") ? "approval" : blocking.length ? "answer" : undefined;+ const asking = rows.some((a) => a.kind === "question" && !!defaultOf(a));+ return taskStage({ stopped: task.endReason === "stopped", undelivered: needsPerson(delivery), waiting, asking, run });}view(task: TaskRow): TaskView {@@ -1646,10 +1757,19 @@ export class TaskService {spentUsd: task.spentUsd,budgetUsd: task.budgetUsd,cleanupAt: task.cleanupAt,+ ...this.openQuestion(task),...(l && run ? { live: { runId: run.id, since: run.startedAt, steps: l.activity.steps.length, current: l.activity.steps.findLast((s) => s.status === "running") } } : {}),};}+ /** 任务问用户的、还没回答的那个问题(最新的;预算的那个不算,它有自己的阶段) */+ private openQuestion(task: TaskRow): Pick<TaskView, "question"> {+ const row = this.o.approvals?.pendingForTask(task.id).find((r) => r.kind === "question" && r.tool === "task_report");+ if (!row) return {};+ const note = defaultLine(row);+ return { question: { text: questionsOf(row)[0]?.question ?? row.detail, ...(note ? { note } : {}) } };+ }+/** 任务列表:进行中、等你的在前,再按新旧;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;@@ -2796,7 +2916,10 @@ export class TaskService {}}-/** task_report 的 question:一句问题(字符串或 {question, options, multiSelect}),选项最多 6 个 */+/**+ * task_report 的 question:一句问题(字符串或 {question, options, multiSelect, default}),选项最多 6 个;+ * default:用户没回答时按它做(有选项时要是其中一个,report 里查)+ */function questionOf(b: any): TaskReport["question"] | undefined {const raw = b?.question;const obj = typeof raw === "object" && raw ? raw : undefined;@@ -2806,7 +2929,15 @@ function questionOf(b: any): TaskReport["question"] | undefined {const label = (o: unknown) => clip(oneLine(String(typeof o === "object" && o ? ((o as { label?: unknown }).label ?? "") : (o ?? ""))), 60);const options = [...new Set(list.map(label).filter(Boolean))].slice(0, OPTIONS_MAX);const multi = obj?.multiSelect === true || b?.multi_select === true;- return { question: clip(text, QUESTION_MAX), ...(options.length ? { options } : {}), ...(multi && options.length > 1 ? { multiSelect: true } : {}) };+ const given = clip(oneLine(String(obj?.default ?? b?.default ?? "")), 60);+ // 写成了选项编号("1"):换成那个选项+ const fallback = !options.includes(given) && /^\d+$/.test(given) && Number(given) >= 1 && Number(given) <= options.length ? options[Number(given) - 1] : given;+ return {+ question: clip(text, QUESTION_MAX),+ ...(options.length ? { options } : {}),+ ...(multi && options.length > 1 ? { multiSelect: true } : {}),+ ...(fallback ? { default: fallback } : {}),+ };}/** 比引用时去掉空白、记号和末尾的省略号(引用可能被截短) */diff --git a/src/tasks/stage.ts b/src/tasks/stage.tsindex 35f9dc2..47262fc 100644--- a/src/tasks/stage.ts+++ b/src/tasks/stage.ts@@ -14,6 +14,7 @@ export type StageKey =| "failed"| "ready"| "working/queued"+ | "working/asking"| "working";/** 分组:进行中 / 等你 / 结束了 */@@ -30,8 +31,10 @@ export interface StageInput {stopped: boolean;/** 最近的结果 / 失败消息没送到会话(出站队列放弃了,或渠道要用户先做点什么) */undelivered?: boolean;- /** 等用户回答(3b)或批准(阻塞着的审批) */+ /** 等用户回答(3b,没有默认回答的提问)或批准(阻塞着的审批) */waiting?: "answer" | "approval";+ /** 问了用户一个有默认回答的问题、还没回答:任务接着做,不算等你 */+ asking?: boolean;/** 最近的 run(它的结果就是最近一次 Report 的状态:done / failed / needs_you) */run?: { state: RunState; outcome: RunOutcome };}@@ -45,6 +48,7 @@ const STAGES: Record<StageKey, Stage> = {failed: { key: "failed", get label() { return tr("tasks.stageFailed" as MessageKey); }, group: "needs" },ready: { key: "ready", get label() { return tr("tasks.stageReady" as MessageKey); }, group: "ended" },"working/queued": { key: "working/queued", get label() { return tr("tasks.stageQueued" as MessageKey); }, group: "working" },+ "working/asking": { key: "working/asking", get label() { return tr("tasks.stageAsking" as MessageKey); }, group: "working" },working: { key: "working", get label() { return tr("tasks.stageWorking" as MessageKey); }, group: "working" },};@@ -55,7 +59,8 @@ export function stageOf(key: StageKey): Stage {/*** 阶段表:* 1 停止了 → 已停止;2 最近的消息没送到 → 未送达;3 有问题或审批在等 → 等你回答 / 等你批准;4 run 停在预算上 → 预算用完;- * 5 最近的 run 以失败结束(之后没有人的输入)→ 失败;6 以完成结束 → 已完成;7 有输入在等名额 → 排队中;8 其余 → 进行中。+ * 5 最近的 run 以失败结束(之后没有人的输入)→ 失败;6 以完成结束 → 已完成;7 有输入在等名额 → 排队中;+ * 8 在跑、问了一个有默认回答的问题还没回答 → 进行中,有个问题等你回答(不算等你:没回答就按默认做);9 其余 → 进行中。* 人的输入(回答、追加、重试)会开新的 run,最近的 run 就不再是结束的那个;自动的输入(恢复)不越过 2–5。*/export function taskStage(i: StageInput): Stage {@@ -70,5 +75,5 @@ export function taskStage(i: StageInput): Stage {if (ended && run?.outcome === "failed") return STAGES.failed;if (ended && run?.outcome === "done") return STAGES.ready;if (!run || run.state === "queued" || run.outcome === "interrupted" || run.outcome === "skipped") return STAGES["working/queued"];- return STAGES.working;+ return i.asking ? STAGES["working/asking"] : STAGES.working;}diff --git a/src/web/server.ts b/src/web/server.tsindex 8dabc7e..e5069ab 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -17,6 +17,7 @@ import { SseReply } from "./sse-reply.js";import { LiveTurns, type LiveTurn } from "./live.js";import { connectionFromPids } from "../agent/peer-guard.js";import type { ApprovalRow, Store } from "../store/db.js";+import { defaultLine } from "../agent/approvals.js";import { normalizeSettings } from "../agent/settings.js";import { scopeLabel } from "../agent/memory.js";import { pwshProbe, type PwshMode, type PwshStatus } from "../agent/pwsh.js";@@ -146,7 +147,7 @@ function webEvent(botId: string, text: string): InboundEvent {}const consoleConvId = (botId: string) => `${botId}:web:console`;-/** 审批 / 提问给界面的字段;后台任务的带上任务名(卡片上「GPU 价格调研」想问你) */+/** 审批 / 提问给界面的字段;后台任务的带上任务名(卡片上「GPU 价格调研」想问你),有默认回答的带上「不回复就按中文做」 */function publicApproval(r: ApprovalRow, store?: Store) {const { payload, result, ...rest } = r;let questions: unknown = undefined;@@ -158,7 +159,8 @@ function publicApproval(r: ApprovalRow, store?: Store) {}}const taskTitle = r.taskId ? store?.getTask(r.taskId)?.title : undefined;- return { ...rest, questions, ...(taskTitle ? { taskTitle } : {}) };+ const note = r.taskId && r.status === "pending" ? defaultLine(r) : undefined;+ return { ...rest, questions, ...(taskTitle ? { taskTitle } : {}), ...(note ? { note } : {}) };}/** 允许名单 / 使用请求:界面要的字段(平台 id 只给末尾几位,界面不需要完整的) */diff --git a/test/attention.unit.test.ts b/test/attention.unit.test.tsindex 2058391..7ca0554 100644--- a/test/attention.unit.test.ts+++ b/test/attention.unit.test.ts@@ -129,5 +129,21 @@ describe("Attention", () => {expect(items.find((x) => x.id === `approval:${a.id}`)).toMatchObject({ kind: "approval", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", actions: ["approve", "deny"], taskId: "t_1", code: a.code, channel: "weixin" });expect(items.find((x) => x.id === `approval:${q.id}`)).toMatchObject({ kind: "question", subject: "微信", status: "等你回答", line: "继续吗?", actions: ["answer"], questions: [{ id: "q", question: "继续吗?" }] });expect(items.find((x) => x.id === `approval:${q.id}`)!.taskId).toBeUndefined();+ expect(items.find((x) => x.id === `approval:${q.id}`)!.note).toBeUndefined();+ });++ it("任务问的有默认回答的问题:多一句不回复会怎样(任务接着在做);没有默认的没有这一句", () => {+ store.createBot({ id: "b", name: "小蓝" });+ store.ensureConversation("b", "weixin", "owner", "owner");+ const c = new ApprovalCenter(store);+ const now = Date.now();+ store.insertTask({ id: "t_1", botId: "b", conversationId: "b:weixin:owner", originMessageId: 0, originRef: "", title: "竞品周报", brief: "", sessionId: "task-t_1", folder: "tasks/x", model: "m", permission: "workspace", budgetUsd: 1, createdAt: now, updatedAt: now });+ const ask = (question: string, dflt?: string) =>+ c.create({ kind: "question", botId: "b", conversationId: "b:weixin:owner", sessionId: "task-t_1", tool: "task_report", detail: question, reason: "", taskId: "t_1", blocking: false, ttlMs: 0, payload: JSON.stringify([{ id: "answer", question, options: [{ label: "中文" }, { label: "英文" }], ...(dflt ? { default: dflt } : {}) }]) });+ const d = ask("报告用中文还是英文?", "中文");+ const m = ask("用哪个账号付款?");+ const items = approvalItems(store, c.pendingAll());+ expect(items.find((x) => x.id === `approval:${d.id}`)).toMatchObject({ kind: "question", subject: "竞品周报", status: "等你回答", line: "报告用中文还是英文?", note: "不回复就按中文做", actions: ["answer"] });+ expect(items.find((x) => x.id === `approval:${m.id}`)!.note).toBeUndefined();});});diff --git a/test/live-control.unit.test.ts b/test/live-control.unit.test.tsindex a7e10ca..52aa7fc 100644--- a/test/live-control.unit.test.ts+++ b/test/live-control.unit.test.ts@@ -67,9 +67,10 @@ describe("control channel (host → amb-control plugin over the bridge)", () =>const polling = post("/dsh/control/poll", { botId: "b", controlId: id });await sleep(50);expect(ch.connected).toBe(true);- const sent = ch.send("steer", { sessionId: "s1", text: "hi" }, 5000);+ // 插话带的是我们的消息 id(messageId,会话里的用户消息用它);id 是这条指令自己的,两个不能混+ const sent = ch.send("steer", { sessionId: "s1", messageId: "i_1", text: "hi" }, 5000);const got = (await (await polling).json()) as any;- expect(got.commands).toEqual([{ sessionId: "s1", text: "hi", id: expect.any(String), op: "steer" }]);+ expect(got.commands).toEqual([{ sessionId: "s1", messageId: "i_1", text: "hi", id: expect.stringMatching(/^c\d+$/), op: "steer" }]);expect(JSON.stringify(got)).not.toContain(bridge!.token);expect((await post("/dsh/control/result", { botId: "b", controlId: id, id: got.commands[0].id, ok: true, result: { accepted: true } })).status).toBe(200);expect(await sent).toEqual({ accepted: true });diff --git a/test/prompts.unit.test.ts b/test/prompts.unit.test.tsindex f1107d8..3a9c2f1 100644--- a/test/prompts.unit.test.ts+++ b/test/prompts.unit.test.ts@@ -184,9 +184,13 @@ const RULES: [rule: string, part: string, says: string[], gone?: string[]][] = [// —— 后台任务(3a)——["聊天代理:长活或用户说后台做才开任务,能马上答的不开;开了只说一句,不自己做", "tool task_start", ["more than a few minutes or many steps", "后台做", "not for what you can answer now", "前台做", "in one sentence", "do not do the work yourself"]],["用户提到某个任务、回答它的问题时把话转给它", "tool task_message", ["when they refer to it", "answer its question", "next step", "resumes"]],- // —— 任务的提问(3b):先自己定,非用户定不可才问,一次一个,问完结束这一轮 ——- ["任务规则优先于聊天规则;能自己定的自己定并说明,非用户定不可才问", "task", ["优先于上面的聊天规则", "选一个合理的做法", "在结果里说明", "非用户定不可", "needs_you", "一个问题", "结束这一轮"], ["ask_user_question"]],- ["task_report:needs_you 带一个问题,回答是下一条消息;问完结束这一轮", "tool task_report", ["needs_you", "only the user can decide", "their answer is your next message", "After done, failed or needs_you, end your turn"]],+ // —— 任务的提问(3b):先自己定,要问就一次一个。有合理默认的尽早问、带 default,接着只做不依赖回答的部分,没回答就按默认;+ // 非用户定不可的先做完不依赖它的部分再问,问完结束这一轮 ——+ ["任务规则优先于聊天规则;能自己定的自己定并说明;要问就一次一个", "task", ["优先于上面的聊天规则", "选一个合理的做法", "在结果里说明", "needs_you", "一个问题"], ["ask_user_question"]],+ ["任务规则:有合理默认的尽早问、带 default,接着只做不依赖回答的部分,没回答就按默认", "task", ["有合理默认的尽早问", "default", "只做不依赖回答的部分", "做完还没回答就按默认"]],+ ["任务规则:非用户定不可的先做完不依赖它的部分再问,然后结束这一轮", "task", ["非用户定不可", "付款", "先做完不依赖它的部分再问", "结束这一轮"]],+ ["task_report:needs_you 马上问;带 default 接着做,先做完就按默认并说明;不带的回答是下一条消息,问完结束这一轮", "tool task_report",+ ["needs_you", "the app asks the user question now", "With default, keep working on what does not depend on the answer", "use default and say so in message", "only the user can decide", "their answer is your next message", "After done, failed or needs_you without default, end your turn", '"default"', "Omit it when only the user can decide"]],["任务:外部动作前后记日志(重启后靠它不重复做)", "task", [".task/journal.md"]],["任务:做完或做不下去才说话,一句话,结果和在哪里;中途不汇报", "task", ["task_report", "done 或 failed", "不超过 300 字", "在哪里", "中途不用汇报", "不会发给用户"]],["task_report:done / failed 的那句话是用户收到的,progress 不发;报完结束这一轮", "tool task_report", ["one line the user receives", "at most 300 characters", "never sent", "end your turn"]],@@ -222,7 +226,7 @@ describe.skipIf(!runtime)("提示词约定", () => {it("聊天规则、人设、任务规则和规则段都短", () => {expect(CHAT_RULES.length).toBeLessThan(440);expect(agentPersona({ computerUse: true }).length).toBeLessThan(180);- expect(TASK_RULES.length).toBeLessThan(400);+ expect(TASK_RULES.length).toBeLessThan(500);expect(ruleRules("observe").length).toBeLessThan(300);expect(ruleRules("act").length).toBeLessThan(300);});@@ -292,8 +296,10 @@ describe.skipIf(!runtime)("提示词约定", () => {/*** 任务会话在聊天会话之外多出来的:任务规则段 + task_report(去掉的工具不算)。上限高约 5%。* 3a 基线 1,255(规则 363 + task_report 892);3b 加上提问(needs_you、question、options 和怎么问的那条规则)后 1,533(规则 399 + task_report 1,134)。+ * 问了还接着做(task_report 的 default,规则里有默认的尽早问、接着做,非用户定不可的先做完再问)之后 1,935+ * (规则 481 + task_report 1,454):两种提问各一句是这个功能本身,上限跟着调高。*/- const TASK_BUDGET = 1_610;+ const TASK_BUDGET = 2_030;it("任务会话多出来的提示词和工具不超过字符数上限", async () => {const { task } = await loadPlugins();const extra = TASK_RULES.length + JSON.stringify(task.tools).length;diff --git a/test/tasks-view.e2e.test.ts b/test/tasks-view.e2e.test.tsindex f90baef..1213220 100644--- a/test/tasks-view.e2e.test.ts+++ b/test/tasks-view.e2e.test.ts@@ -3,6 +3,8 @@* GET /tasks?group= 按进行中 / 等你 / 结束了分组(归档了的不列,组名不对 400);详情里有来自、大小;改预算(加多少、改成多少、* 不对的金额、停了的任务);删除连同文件夹;保留文件夹(详情里、「需要你」里);打开文件夹只在桌面版;规则编辑器的预算;* 规则运行记录和任务导出成 Markdown(下载的文件名、按 ?lang= 的语言)。+ * 问了个有默认回答的问题、接着在做的任务:在进行中那组,「进行中,有个问题等你回答」;详情、「需要你」、对话里的卡片都有那一句+ * 「不回复就按中文做」(按界面的语言)。*/import fs from "node:fs";import os from "node:os";@@ -150,3 +152,25 @@ describe("任务视图的接口", () => {expect((await api(`/tasks/${failed}`)).status).toBe(404);});});++describe("问了还在做:有默认回答的提问", () => {+ it("任务在进行中那组(进行中,有个问题等你回答);详情、「需要你」和提问卡片都有不回复会怎样;回答了就回到进行中", async () => {+ const id = task("竞品周报", "queued");+ const runId = `r_${id.slice(2)}`;+ app.store.updateRun(runId, { state: "running", startedAt: Date.now() });+ const payload = JSON.stringify([{ id: "answer", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }], default: "中文" }]);+ const q = app.agent.approvals.create({ kind: "question", botId: "default", conversationId: CONV, sessionId: `task-${id}`, tool: "task_report", detail: "报告用中文还是英文?", reason: "", payload, taskId: id, runId, blocking: false, ttlMs: 0 });+ const list = (await api("/tasks?bot=default&group=working")).data.tasks;+ expect(list.find((t: any) => t.id === id)).toMatchObject({ stage: { key: "working/asking", label: "进行中,有个问题等你回答", group: "working" }, question: { text: "报告用中文还是英文?", note: "不回复就按中文做" } });+ expect((await api(`/tasks/${id}`, { lang: "en" })).data.task).toMatchObject({ stage: { label: "In progress, with a question for you" }, question: { note: "If you don't reply, it goes with 中文" } });+ const item = (await api("/attention")).data.items.find((i: any) => i.id === `approval:${q.id}`);+ expect(item).toMatchObject({ kind: "question", subject: "竞品周报", status: "等你回答", line: "报告用中文还是英文?", note: "不回复就按中文做", actions: ["answer"], taskId: id });+ expect((await api(`/approvals/${q.id}`)).data.approval).toMatchObject({ taskTitle: "竞品周报", note: "不回复就按中文做", questions: [{ default: "中文" }] });+ // 在「需要你」里回答了:回到进行中,卡片上不再有那一句+ expect((await api(`/attention/approval:${q.id}/answer`, { method: "POST", body: { text: "2" } })).status).toBe(200);+ expect((await api(`/tasks/${id}`)).data.task).toMatchObject({ stage: { key: "working", label: "进行中" } });+ expect((await api(`/tasks/${id}`)).data.task.question).toBeUndefined();+ expect((await api(`/approvals/${q.id}`)).data.approval).toMatchObject({ status: "answered" });+ expect((await api(`/approvals/${q.id}`)).data.approval.note).toBeUndefined();+ });+});diff --git a/test/tasks.integration.test.ts b/test/tasks.integration.test.tsindex 9ea2054..6d5eb8b 100644--- a/test/tasks.integration.test.ts+++ b/test/tasks.integration.test.ts@@ -7,6 +7,8 @@* 另外:引用回答、中间的普通聊天不被当成回答;任务会话里的审批推到同一个微信会话(带任务名),y 编号批准后接着做。* 3e 退出演示:模型每次请求报的用量按(mock 的)Modelflare 价格目录估算,任务花到 $1 停下,微信和「需要你」里问* 「已用约 $1.00,再给 $1 继续?」,在桌面上点继续后同一个会话接着做完。+ * 问了还接着做:任务问一个有默认回答的问题(马上推到微信,带「不回复就按中文做」)、接着跑命令;用户回编号,回答并进在跑的这一轮;+ * 没人回答就按默认做完,提问从「需要你」里撤掉,之后引用那条提问回答,任务接着做。*/import fs from "node:fs";import os from "node:os";@@ -78,6 +80,26 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrou// 用户引用结果追加的一句(不经聊天代理,直接到任务)const more = /^\[用户追加\]\n(.+)$/.exec(user);if (more) return report(`FOLLOWED-${tag}:${more[1]}`);+ // ASKD / ASKL:先问一个有默认回答的问题,接着跑一条命令(ASKD 6 秒,等用户回答;ASKL 2 秒,没人回答),+ // 做完时有回答就按回答,没有就按默认;之后又来了回答(引用撤回的提问)就按它改+ if (tag.startsWith("ASKD") || tag.startsWith("ASKL")) {+ const tc = messages.flatMap((m: any) => (m.role === "assistant" ? (m.tool_calls ?? []) : []));+ const names = tc.map((c: any) => String(c.function?.name ?? ""));+ const lastArgs = (() => {+ try {+ return JSON.parse(tc.at(-1)?.function?.arguments ?? "{}");+ } catch {+ return {};+ }+ })();+ if (messages.at(-1)?.role === "tool" && names.at(-1) === "task_report" && lastArgs.state === "done") return { text: "已报告" };+ if (!names.includes("task_report")) return { tool: { name: "task_report", args: { state: "needs_you", summary: "先写正文,差语言", question: "中文还是英文?", options: ["中文", "英文"], default: "中文" } } };+ if (!names.includes("bash")) return { tool: { name: "bash", args: { description: "draft", command: `sleep ${tag.startsWith("ASKD") ? 6 : 2} && echo drafted` } } };+ if (messages.at(-1)?.role === "tool" && names.at(-1) !== "bash") return { text: "继续" };+ // 并进来的回答可能被 DSH 包了一层:不锚定开头结尾+ const ans = all.map((m) => /\[用户回答了你[^\]]*\]\s*问题:[^\n]*\n回答:([^\n<]+)/.exec(m.text)?.[1]?.trim()).filter(Boolean).at(-1);+ return { tool: { name: "task_report", args: { state: "done", summary: "写好了", message: ans ? `ANSWERED-${tag}:用${ans}写好了。` : `DEFAULTED-${tag}:按中文写好了,要英文的话引用这条说一声。` } } };+ }// ASK:先问用户(needs_you),回答作为下一条输入回来,再按回答做完if (tag.startsWith("ASK")) {const ans = /^\[用户回答了你的问题\][\s\S]*回答:(.+)$/.exec(user);@@ -314,6 +336,52 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("backgrouexpect((await api(`/tasks/${t.id}`)).runs.map((r: any) => r.cause)).toEqual(["launch", "answer"]);}, 180_000);+ it("a question with a default is pushed right away and the task keeps working; a bare number answers it and reaches the running turn", async () => {+ const t = await research("ASKD1");+ await waitFor(() => sentTo("❓「调研 ASKD1」").length === 1);+ expect(sentTo("❓「调研 ASKD1」")[0].text).toBe("❓「调研 ASKD1」想问你:中文还是英文?\n1. 中文\n2. 英文\n不回复就按中文做\n(回复编号,或引用这条消息回答)");+ // 推出去的时候任务还在跑(进行中,有个问题等你回答),「需要你」里有它和那一句+ expect(stage("ASKD1")).toBe("working/asking");+ const { items } = await api("/attention");+ expect(items.map((x: any) => [x.kind, x.subject, x.status, x.line, x.note])).toEqual([["question", "调研 ASKD1", "等你回答", "中文还是英文?", "不回复就按中文做"]]);+ const chats = calls.filter((c) => !c.task).length;+ ilink.push(OWNER, "2");+ await waitFor(() => sentTo("收到,「调研 ASKD1」继续。").length === 1);+ await waitFor(() => sentTo("ANSWERED-ASKD1").length === 1);+ expect(sentTo("ANSWERED-ASKD1")[0].text).toBe("ANSWERED-ASKD1:用英文写好了。引用这条消息可以继续问。");+ await waitFor(() => stage("ASKD1") === "ready");+ // 回答并进了在跑的那一轮:一个 run,不经聊天代理+ expect((await api(`/tasks/${t.id}`)).runs.map((r: any) => [r.cause, r.outcome])).toEqual([["launch", "done"]]);+ expect(calls.filter((c) => !c.task).length).toBe(chats);+ expect((await api("/attention")).items).toEqual([]);+ }, 180_000);++ it("a task that finishes before the answer goes with the default and withdraws its question; quoting the question later resumes it", async () => {+ const t = await research("ASKL1");+ await waitFor(() => sentTo("❓「调研 ASKL1」").length === 1);+ const asked = sentTo("❓「调研 ASKL1」")[0].text;+ await waitFor(() => sentTo("DEFAULTED-ASKL1").length === 1);+ await waitFor(() => stage("ASKL1") === "ready");+ expect(sentTo("DEFAULTED-ASKL1")[0].text).toBe("DEFAULTED-ASKL1:按中文写好了,要英文的话引用这条说一声。引用这条消息可以继续问。");+ // 提问撤回了:「需要你」是空的,审批中心里它作废了+ expect((await api("/attention")).items).toEqual([]);+ expect(app.store.listApprovals({ taskId: t.id })[0]).toMatchObject({ status: "cancelled", decidedBy: "default" });+ // 引用那条提问回答:交给任务,同一个任务接着做+ ilink.pushItems(OWNER, [{ type: 1, text_item: { text: "2" }, ref_msg: { title: "", message_item: { type: 1, text_item: { text: asked } } } }]);+ await waitFor(() => sentTo("收到,「调研 ASKL1」继续。").length === 1);+ await waitFor(() => sentTo("ANSWERED-ASKL1").length === 1);+ expect(sentTo("ANSWERED-ASKL1")[0].text).toBe("ANSWERED-ASKL1:用英文写好了。引用这条消息可以继续问。");+ await waitFor(() => stage("ASKL1") === "ready");+ expect((await api(`/tasks/${t.id}`)).runs.map((r: any) => [r.cause, r.outcome])).toEqual([+ ["launch", "done"],+ ["answer", "done"],+ ]);+ // 撤回之后光回编号是普通聊天(聊天的输入前面带着任务的便条)+ ilink.push(OWNER, "1");+ await waitFor(() => calls.some((c) => !c.task && /(^|\n)1$/.test(c.users.at(-1) ?? "")));+ expect(app.store.listApprovals({ taskId: t.id }).map((a) => a.status)).toEqual(["cancelled"]);+ }, 180_000);+it("an approval from a task session lands on the task's WeChat chat, named after the task; 'y CODE' lets the task continue", async () => {const t = await research("APPR1");await waitFor(() => sentTo("需批准(任务「调研 APPR1」)").length === 1);diff --git a/test/tasks.unit.test.ts b/test/tasks.unit.test.tsindex a13b7d4..861bd30 100644--- a/test/tasks.unit.test.ts+++ b/test/tasks.unit.test.ts@@ -3,6 +3,8 @@* TaskService 对着一个假的宿主:建任务与第一条输入、一轮结束与收尾、Report、提醒、出错重试、追加、停止、* 重启恢复(恢复说明在前、没收下的输入再交一次)、送达(出站队列 id 固定,只交一次)、/tasks 与 /stop 编号。* 3b:任务的提问(needs_you → 不阻塞的提问 → 推给会话、一次一个 → 回答成为新输入)、任务会话里的审批、「需要你」。+ * 提问马上问(报 needs_you 时,不等这一轮结束、不等收尾);带默认回答的任务接着做,回答并进去,先做完就按默认、撤回提问,+ * 之后引用那条提问回答照样交给任务;没带默认的这一轮结束等着,收尾时到的回答交给会话。*/import fs from "node:fs";import os from "node:os";@@ -12,6 +14,7 @@ import { taskStage, type StageInput } from "../src/tasks/stage.js";import { byPriority, pickRuns, priorityOf, type Waiting } from "../src/tasks/slots.js";import { TaskService, askId, quotes, slugOf, takeTaskNotes, type TaskHost, type TaskNotification } from "../src/tasks/service.js";import { ApprovalCenter } from "../src/agent/approvals.js";+import { approvalItems } from "../src/tasks/attention.js";import { AgentHost, ResumeFailed } from "../src/agent/host.js";import { DEFAULT_SETTINGS, normalizeSettings } from "../src/agent/settings.js";import { NUDGE, TASK_RULES, recoveryNote, taskBrief } from "../src/agent/prompts/index.js";@@ -158,7 +161,10 @@ class FakeHost implements TaskHost {async cancel(_botId: string, sessionId: string) {this.cancels.push(sessionId);}+ /** 给了就等它(问插件的时候来了输入) */+ quietGate: Promise<void> | undefined;async quiet() {+ await this.quietGate;return this.quiets.shift() ?? { quiet: true };}}@@ -937,6 +943,305 @@ describe("TaskService(假宿主)", () => {expect(delivery.reserved("b", "weixin", "owner")).toBe(1);});+ // —— 问了还接着做:带默认回答的提问马上问、任务不停;没带默认的马上问、这一轮结束等着 ——++ /** 会话收下最近一次交给它的输入、开始跑一轮(不结束) */+ const begin = (sessionId: string) => {+ const p = host.prompts.filter((x) => x.sessionId === sessionId).at(-1)!;+ svc.onEvent("b", sessionId, status(sessionId, "running"));+ svc.onEvent("b", sessionId, ev(sessionId, "turn/start", { turn: 1 }));+ svc.onEvent("b", sessionId, ev(sessionId, "user/message", { id: p.id }));+ };+ /** 这一轮结束、会话空了 */+ const finishTurn = async (sessionId: string) => {+ svc.onEvent("b", sessionId, ev(sessionId, "turn/end", { turn: 1, reason: { kind: "completed" } }));+ svc.onEvent("b", sessionId, status(sessionId, "idle"));+ await flush();+ };+ /** 并进去的输入被会话收下 */+ const takeSteered = (sessionId: string) => svc.onEvent("b", sessionId, ev(sessionId, "user/message", { id: host.steers.at(-1)!.id }));+ /** 代理报 needs_you 带默认回答(接着做,不结束这一轮) */+ const askDefault = (sessionId: string, question = "报告用中文还是英文?", options: string[] | undefined = ["中文", "英文"], dflt = "中文") =>+ svc.report({ sessionId, state: "needs_you", summary: "先写正文,差语言", question, ...(options ? { options } : {}), default: dflt });+ const PUSHED_DEFAULT = "❓「GPU 价格调研」想问你:报告用中文还是英文?\n1. 中文\n2. 英文\n不回复就按中文做\n(回复编号,或引用这条消息回答)";++ it("有默认回答的提问:报了就推出去,这一轮不结束;阶段进行中,有个问题等你回答(进行中那组);「需要你」里有问题、选项和不回复会怎样", async () => {+ const t = start();+ await flush();+ begin(t.sessionId);+ // 默认回答要是选项之一;写成编号的换成那个选项+ expect(askDefault(t.sessionId, "报告用中文还是英文?", ["中文", "英文"], "日文").error).toBe("default must be one of the options: 中文 / 英文.");+ expect(approvals.pendingForTask(t.id)).toEqual([]);+ const r = askDefault(t.sessionId);+ expect(r.text).toBe('Asked the user. Keep working on what does not depend on the answer; if they answer, it arrives as a message at your next step. If you finish first, use "中文", say so in your message, and report done.');+ const [q] = approvals.pendingForTask(t.id);+ expect(q).toMatchObject({ kind: "question", blocking: false, expiresAt: 0, tool: "task_report", runId: store.listRuns({ taskId: t.id })[0].id });+ // 马上推(不等这一轮结束),选项后面多一行「不回复就按中文做」+ expect(asks().map((x) => [x.id, x.body.text, x.body.raw])).toEqual([[askId(q), PUSHED_DEFAULT, true]]);+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ expect(svc.get(t.id)!.stage).toMatchObject({ key: "working/asking", label: "进行中,有个问题等你回答", group: "working" });+ expect(svc.get(t.id)!.question).toEqual({ text: "报告用中文还是英文?", note: "不回复就按中文做" });+ expect(svc.working(CONV).map((x) => x.id)).toEqual([t.id]);+ const [item] = approvalItems(store, approvals.pendingAll());+ expect(item).toMatchObject({ kind: "question", subject: "GPU 价格调研", status: "等你回答", line: "报告用中文还是英文?", note: "不回复就按中文做", actions: ["answer"], taskId: t.id });+ expect(item.questions![0].options!.map((o) => o.label)).toEqual(["中文", "英文"]);+ expect(takeTaskNotes(store, CONV)).toBe("[后台任务「GPU 价格调研」问了用户:报告用中文还是英文?(中文 / 英文),没回答就按「中文」做,任务照常在做。用户在聊天里回答它时,用 task_message 转给这个任务]");+ // 同一个问题又报了一遍:不再问;编号写的默认回答换成选项+ askDefault(t.sessionId);+ expect(approvals.pendingForTask(t.id)).toHaveLength(1);+ const u = start("季度报告");+ await flush();+ begin(u.sessionId);+ askDefault(u.sessionId, "PPT 要几页?", ["10 页", "20 页"], "2");+ expect(svc.get(u.id)!.question).toEqual({ text: "PPT 要几页?", note: "不回复就按20 页做" });+ });++ it("有默认回答的提问被回答了:回答并进在跑的这一轮(同追加),任务接着做完;不开新 run", async () => {+ const t = start();+ await flush();+ begin(t.sessionId);+ askDefault(t.sessionId);+ const [q] = approvals.pendingForTask(t.id);+ // 提问是机器人最后一条消息:光回编号就是回答+ expect(reply("2")).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });+ await flush();+ expect(store.getApproval(q.id)).toMatchObject({ status: "answered" });+ expect(host.steers).toEqual([{ sessionId: t.sessionId, id: expect.stringMatching(/^i_/), text: "[用户回答了你的问题]\n问题:报告用中文还是英文?\n回答:英文" }]);+ expect(svc.get(t.id)!.stage.key).toBe("working");+ expect(svc.get(t.id)!.question).toBeUndefined();+ takeSteered(t.sessionId);+ expect(report(t.sessionId, "done", "报告写好了(英文),在 report.md。").text).toMatch(/^Recorded/);+ await finishTurn(t.sessionId);+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);+ expect(store.listOutbox({ limit: 50 }).find((r) => r.id.includes(":result:"))!.body.text).toBe("报告写好了(英文),在 report.md。");+ expect(store.getApproval(q.id)!.status).toBe("answered");+ });++ it("任务先做完了:按默认做,提问从「需要你」、审批中心和出站队列里撤回(免打扰时排着的那条不会早上再问)", async () => {+ const at = Date.UTC(2026, 10, 6, 23, 0);+ const delivery = new Delivery({ store, outbox, timeZone: "UTC", now: () => at });+ svc.stop();+ svc = new TaskService({ store, host, delivery, approvals, defaultModel: () => "mock-model", retryDelaysMs: [5, 5, 5], maxBackground: 4 });+ svc.start();+ const t = start();+ await flush();+ await turn(t.sessionId, () => {+ askDefault(t.sessionId);+ expect(asks()[0]).toMatchObject({ status: "scheduled", reason: "quiet_hours", purpose: "question" });+ expect(svc.get(t.id)!.stage.key).toBe("working/asking");+ report(t.sessionId, "done", "报告写好了,按中文做的;要英文的话引用这条说一声。");+ });+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);+ const [q] = store.listApprovals({ taskId: t.id });+ expect(q).toMatchObject({ status: "cancelled", decidedBy: "default" });+ expect(approvals.pendingAll()).toEqual([]);+ expect(approvalItems(store, approvals.pendingAll())).toEqual([]);+ expect(svc.attention()).toEqual([]);+ expect(store.getOutbox(askId(q))).toMatchObject({ status: "gone", error: "已处理" });+ expect(store.getOutbox(askId(q))!.seenAt).toBeGreaterThan(0);+ expect(svc.get(t.id)!.stage.key).toBe("ready");+ expect(svc.get(t.id)!.question).toBeUndefined();+ // 结果照常(免打扰时排到早上);不再占微信配额+ expect(store.listOutbox({ limit: 50 }).find((r) => r.id.includes(":result:"))).toMatchObject({ status: "scheduled", body: { text: "报告写好了,按中文做的;要英文的话引用这条说一声。" } });+ expect(delivery.reserved("b", "weixin", "owner")).toBe(1);+ });++ it("迟到的回答:引用撤回了的提问(已经发出去了)交给任务、在同一个任务里接着做;光回编号是普通聊天;停了的照旧", async () => {+ const t = start();+ await flush();+ begin(t.sessionId);+ askDefault(t.sessionId);+ const [q] = approvals.pendingForTask(t.id);+ // 提问已经发到微信了:撤不回来+ store.updateOutbox(askId(q), { status: "sent", sentAt: Date.now() });+ report(t.sessionId, "done", "报告写好了,按中文做的;要英文的话引用这条说一声。");+ await finishTurn(t.sessionId);+ expect(store.getApproval(q.id)).toMatchObject({ status: "cancelled", decidedBy: "default" });+ expect(store.getOutbox(askId(q))!.status).toBe("sent");+ const sent = store.getOutbox(askId(q))!.body.text!;+ // 光回编号(不引用):普通聊天+ expect(reply("2")).toEqual({ handled: false });+ expect(svc.followUp(CONV, { text: "2" })).toEqual({ handled: false });+ // 引用那条提问回答(审批中心认不出了:它已经不在等),交给任务+ expect(reply("> 2", { quote: sent, plain: "2" })).toEqual({ handled: false });+ expect(svc.followUp(CONV, { text: "2", quote: `小蓝: ${sent.slice(0, 24)}…` })).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });+ await flush();+ expect(runs(t.id)).toEqual([+ ["launch", "ended", "done"],+ ["answer", "running", ""],+ ]);+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, resume: true, text: "[用户回答了你之前问的问题(你已经按「中文」做完了)]\n问题:报告用中文还是英文?\n回答:英文" });+ expect(svc.get(t.id)!.stage.key).toBe("working");+ // 引用结果照旧是追加+ await turn(t.sessionId, () => void report(t.sessionId, "done", "改成英文了。"));+ await svc.stopTask(t.id, "web");+ expect(svc.followUp(CONV, { text: "还是中文吧", quote: sent })).toEqual({ handled: true, ack: "「GPU 价格调研」已停止,不能再追加;需要的话开个新任务。" });+ });++ it("没有默认回答的提问:报了就推出去,后台命令让 run 收尾时也一样;收尾时到的回答交给会话、接着做完", async () => {+ const t = start();+ await flush();+ host.quiets.push({ quiet: false, jobs: ["bash-1"] });+ await turn(t.sessionId, () => {+ expect(svc.report({ sessionId: t.sessionId, state: "needs_you", summary: "差付款账号", question: "用哪个账号付款?", options: ["个人", "公司"] }).text).toBe(+ "Recorded. End your turn now: the app asks the user, and their answer arrives as your next message.",+ );+ // 不等这一轮结束+ expect(asks().map((x) => x.body.text)).toEqual(["❓「GPU 价格调研」想问你:用哪个账号付款?\n1. 个人\n2. 公司\n(回复编号,或引用这条消息回答)"]);+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/answer");+ });+ // 后台命令还在跑:收尾,提问早就推出去了+ expect(runs(t.id)).toEqual([["launch", "settling", ""]]);+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/answer");+ expect(asks()).toHaveLength(1);+ expect(reply("2")).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });+ await flush();+ // 回答是会话的下一条输入(同一个 run,又在跑了)+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: t.sessionId, text: "[用户回答了你的问题]\n问题:用哪个账号付款?\n回答:公司" });+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ expect(svc.get(t.id)!.stage.key).toBe("working");+ // 插件这时才报安静:交出去的回答还没被收下,不结束+ svc.settled({ sessionId: t.sessionId });+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ await turn(t.sessionId, () => void report(t.sessionId, "done", "用公司账号付好了。"));+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);+ expect(asks()).toHaveLength(1);+ });++ it("问插件还有没有后台命令时来了回答:先交给会话,不以 needs_you 结束;插件报安静时有没交出去的回答也一样", async () => {+ const t = start();+ await flush();+ let open!: () => void;+ host.quietGate = new Promise<void>((r) => (open = r));+ await turn(t.sessionId, () => void svc.report({ sessionId: t.sessionId, state: "needs_you", summary: "", question: "用哪个账号付款?", options: ["个人", "公司"] }));+ // 正在问插件:回答排着+ expect(reply("1").handled).toBe(true);+ await flush();+ expect(host.prompts.at(-1)!.text).not.toContain("回答:个人");+ host.quietGate = undefined;+ open();+ await flush();+ expect(host.prompts.at(-1)!.text).toBe("[用户回答了你的问题]\n问题:用哪个账号付款?\n回答:个人");+ expect(runs(t.id)).toEqual([["launch", "running", ""]]);+ await turn(t.sessionId, () => void report(t.sessionId, "done", "好了"));+ expect(runs(t.id)).toEqual([["launch", "ended", "done"]]);+ });++ it("一个会话同时只推一个:有默认回答的提问推出去了,别的任务的提问在「需要你」里等;它按默认做完(撤回)才推下一个", async () => {+ host.settingsValue = normalizeSettings({ taskSlots: 4 });+ const a = start("A 任务");+ const b = start("B 任务");+ await flush();+ begin(a.sessionId);+ askDefault(a.sessionId, "A 用哪个?");+ await ask(b.sessionId, "B 用哪个?");+ const qa = approvals.pendingForTask(a.id)[0];+ const qb = approvals.pendingForTask(b.id)[0];+ expect(asks().map((r) => r.id)).toEqual([askId(qa)]);+ expect([svc.get(a.id)!.stage.key, svc.get(b.id)!.stage.key]).toEqual(["working/asking", "needs-you/answer"]);+ report(a.sessionId, "done", "A 按中文做好了。");+ await finishTurn(a.sessionId);+ expect(store.getApproval(qa.id)!.status).toBe("cancelled");+ expect(asks().map((r) => [r.id, r.status])).toEqual([+ [askId(qa), "gone"],+ [askId(qb), "pending"],+ ]);+ // B 的提问现在是机器人最后一条消息:光回编号就是回答它+ expect(reply("1")).toEqual({ handled: true, ack: "收到,「B 任务」继续。" });+ });++ it("重启:有默认回答的提问留着、不再推一遍;恢复的 run 收到回答(并进去)", async () => {+ const t = start();+ await flush();+ begin(t.sessionId);+ askDefault(t.sessionId);+ svc.stop();+ approvals = new ApprovalCenter(store);+ approvals.start();+ approvals.stop();+ svc = make();+ svc.start();+ await flush();+ const [q] = approvals.pendingForTask(t.id);+ expect(q).toMatchObject({ status: "pending", tool: "task_report" });+ expect(asks()).toHaveLength(1);+ expect(runs(t.id)).toEqual([+ ["launch", "ended", "interrupted"],+ ["recover", "running", ""],+ ]);+ expect(host.prompts.at(-1)!.text).toMatch(/^The app restarted while you were working on this task/);+ expect(svc.get(t.id)!.stage.key).toBe("working/asking");+ begin(t.sessionId);+ // 恢复的 run 又问了一遍同一个问题:还开着,不再问、不再推+ askDefault(t.sessionId);+ expect(approvals.pendingForTask(t.id).map((r) => r.id)).toEqual([q.id]);+ expect(asks()).toHaveLength(1);+ // 换了默认回答:以新的为准(旧的作废),新的推出去+ askDefault(t.sessionId, "报告用中文还是英文?", ["中文", "英文"], "英文");+ const [q2] = approvals.pendingForTask(t.id);+ expect([store.getApproval(q.id)!.status, store.getApproval(q.id)!.decidedBy, q2.id !== q.id]).toEqual(["cancelled", "superseded", true]);+ expect(svc.get(t.id)!.question).toEqual({ text: "报告用中文还是英文?", note: "不回复就按英文做" });+ expect(asks().map((r) => r.status)).toEqual(["gone", "pending"]);+ expect(reply("2")).toEqual({ handled: true, ack: "收到,「GPU 价格调研」继续。" });+ await flush();+ expect(store.getApproval(q2.id)!.status).toBe("answered");+ expect(host.steers.at(-1)).toMatchObject({ sessionId: t.sessionId, text: "[用户回答了你的问题]\n问题:报告用中文还是英文?\n回答:英文" });+ takeSteered(t.sessionId);+ report(t.sessionId, "done", "英文报告写好了。");+ await finishTurn(t.sessionId);+ expect(runs(t.id).at(-1)).toEqual(["recover", "ended", "done"]);+ });++ it("重启:没有默认回答的提问问了、run 还在收尾:run 记为 needs_you,不排恢复;回答到了,恢复说明跟着回答交给新的 run", async () => {+ const t = start();+ await flush();+ host.quiets.push({ quiet: false, jobs: ["bash-1"] });+ await turn(t.sessionId, () => void svc.report({ sessionId: t.sessionId, state: "needs_you", summary: "", question: "用哪个账号付款?", options: ["个人", "公司"] }));+ expect(runs(t.id)).toEqual([["launch", "settling", ""]]);+ svc.stop();+ svc = make();+ svc.start();+ await flush();+ expect(runs(t.id)).toEqual([["launch", "ended", "needs_you"]]);+ expect(svc.get(t.id)!.stage.key).toBe("needs-you/answer");+ expect(approvals.pendingForTask(t.id)).toHaveLength(1);+ expect(asks()).toHaveLength(1);+ const before = host.prompts.length;+ expect(reply("2").handled).toBe(true);+ await flush();+ expect(host.prompts).toHaveLength(before + 1);+ expect(host.prompts.at(-1)!.text).toMatch(/^The app restarted while you were working on this task[\s\S]*\n\n\[用户回答了你的问题\]\n问题:用哪个账号付款?\n回答:公司$/);+ expect(runs(t.id).at(-1)).toEqual(["answer", "running", ""]);+ });++ it("飞书:有默认回答的提问卡片里有那一行;撤回之后卡片上的按钮当作迟到的回答交给任务", async () => {+ const fs1 = store.ensureConversation("b", "feishu", "oc_1", "主人");+ store.addMessage(fs1.id, "user", "后台调研一下 GPU 价格");+ store.setKV(`reply-to:${fs1.id}`, JSON.stringify({ messageId: "om_req", chatId: "oc_1" }));+ const f = svc.create({ botId: "b", conversationId: fs1.id, title: "GPU", brief: "" }).task!;+ await flush();+ begin(f.sessionId);+ askDefault(f.sessionId);+ const [q] = approvals.pendingForTask(f.id);+ const row = asks()[0];+ expect(row).toMatchObject({ channel: "feishu", kind: "card", replyTo: "om_req" });+ expect(JSON.stringify(row.body.card)).toContain(JSON.stringify("报告用中文还是英文?\n不回复就按中文做"));+ store.updateOutbox(row.id, { status: "sent", sentAt: Date.now() });+ report(f.sessionId, "done", "按中文做好了。");+ await finishTurn(f.sessionId);+ expect(store.getApproval(q.id)!.status).toBe("cancelled");+ const agent = { available: true, approvals, tasks: svc, turnsInProgress: new Map(), canSteer: () => false } as unknown as AgentManager;+ const rt = new BotRuntime({ store, models: {} as any, defaultModel: () => "m", contextMessages: 20, contextChars: 20_000, agent });+ expect(rt.cardAction("b", { amb: "question", id: q.id, option: "2" }, "feishu:ou_1")).toEqual({ toast: "收到,「GPU」继续。", ok: true });+ await flush();+ expect(host.prompts.at(-1)).toMatchObject({ sessionId: f.sessionId, text: "[用户回答了你之前问的问题(你已经按「中文」做完了)]\n问题:报告用中文还是英文?\n回答:英文" });+ // 回答过的(不是撤回的)照旧说已经处理了+ await turn(f.sessionId, () => void report(f.sessionId, "done", "改成英文了。"));+ const other = approvals.create({ kind: "question", botId: "b", conversationId: fs1.id, sessionId: f.sessionId, tool: "task_report", detail: "要几页?", reason: "", payload: JSON.stringify([{ id: "answer", question: "要几页?", options: [{ label: "10" }] }]), taskId: f.id, blocking: false, ttlMs: 0 });+ approvals.answerText(other.id, "1", "web");+ expect(rt.cardAction("b", { amb: "question", id: other.id, option: "1" }, "feishu:ou_1").ok).toBe(false);+ });+it("任务会话里阻塞着的审批:阶段是等你批准", async () => {const t = start();await flush();diff --git a/ui/components/tasks.js b/ui/components/tasks.jsindex d6bad9c..88bf6e6 100644--- a/ui/components/tasks.js+++ b/ui/components/tasks.js@@ -1,8 +1,10 @@// 后台任务(3a,3f 补全):对话里请求那条消息下面的任务胶囊「后台任务 · 标题 · 进行中 ›」,点开是任务的详情;// 信息面板的「任务」组(TaskGroup)是一个机器人的全部任务和规则:进行中、等你的、规则,结束了的收在最后一行「已结束 3」里,// 点开才列出来。一个任务一行,点开是同一块里的详情(和规则一样,像普通的折叠一样展开)。-// 详情:来自(渠道、时间、原话)、最新进展、预算(约 $0.08 / $1.00,可以改)、文件夹(大小、打开)、要清理时的日期和保留、-// 每次运行折叠的处理过程,以及停止 / 导出 / 删除。状态是"点 + 文字":绿 = 进行中,黄 = 等你,红 = 失败,灰 = 已完成 / 已停止。+// 详情:来自(渠道、时间、原话)、它问你的问题(有默认回答时下面一句「不回复就按中文做」)、最新进展、预算(约 $0.08 / $1.00,+// 可以改)、文件夹(大小、打开)、要清理时的日期和保留、每次运行折叠的处理过程,以及停止 / 导出 / 删除。+// 状态是"点 + 文字":绿 = 进行中(问了个有默认回答的问题、接着在做的也是:「进行中,有个问题等你回答」),黄 = 等你,+// 红 = 失败,灰 = 已完成 / 已停止。// 健康时不多占地方:花费有了才写,清理只在定了日期时出现。import { useEffect, useRef, useState } from "preact/hooks";import { html, Icon, Notice } from "./ui.js";@@ -55,10 +57,11 @@ export const exportUrl = (kind, id) => `/amb/api/${kind}/${encodeURIComponent(idconst clip = (s, n) => (s.length > n ? s.slice(0, n - 1) + "…" : s);/**- * 任务的详情:来自、最新进展、预算、文件夹、清理、每次运行(折叠的处理过程)、停止 / 导出 / 删除。working 时每 3 秒刷新。- * origin=false 时不写来自(对话里的胶囊就在请求那条消息下面);onOpenConv 给了,来自那一行点开会话;data 给了就不去取(样例页)+ * 任务的详情:来自、问题、最新进展、预算、文件夹、清理、每次运行(折叠的处理过程)、停止 / 导出 / 删除。working 时每 3 秒刷新。+ * origin=false 时不写来自(对话里的胶囊就在请求那条消息下面);question=false 时不写问题(「需要你」里那一行就是它);+ * onOpenConv 给了,来自那一行点开会话;data 给了就不去取(样例页)*/-export function TaskDetail({ task, onChanged, origin = true, onOpenConv, data }) {+export function TaskDetail({ task, onChanged, origin = true, question = true, onOpenConv, data }) {const [d, setD] = useState(data || null);const [busy, setBusy] = useState("");const [editing, setEditing] = useState(false);@@ -120,9 +123,12 @@ export function TaskDetail({ task, onChanged, origin = true, onOpenConv, data })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);+ const asked = question && view.question;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>`}+ ${asked && html`<div class="task-line"><span class="t-label">${t("tasks.question")}</span>+ <span class="v selectable">${asked.text}${asked.note && html`<span class="task-note">${asked.note}</span>`}</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>`}${(!ended || hasCost(view.spentUsd)) && html`<div class="task-line"><span class="t-label">${t("tasks.budget")}</span>${editing@@ -149,8 +155,8 @@ export function TaskDetail({ task, onChanged, origin = true, onOpenConv, data })</div>`;}-/** 对话里的任务胶囊:「后台任务 · 标题 · 进行中 ›」,点开看详情 */-export function TaskChip({ task, onChanged }) {+/** 对话里的任务胶囊:「后台任务 · 标题 · 进行中 ›」,点开看详情(data 给了就不去取:样例页) */+export function TaskChip({ task, onChanged, data }) {const [open, setOpen] = useState(false);const dot = stageDot(task.stage);return html`<div class=${`task-chip${open ? " open" : ""}`}>@@ -159,7 +165,7 @@ 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} origin=${false} onChanged=${onChanged} />`}+ ${open && html`<${TaskDetail} task=${task} origin=${false} onChanged=${onChanged} data=${data} />`}</div>`;}diff --git a/ui/css/chat.css b/ui/css/chat.cssindex f6765b1..95a0f7e 100644--- a/ui/css/chat.css+++ b/ui/css/chat.css@@ -376,6 +376,7 @@ button.act-head:active { background: var(--pill-hover); }.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 .task-note { display: block; 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); }diff --git a/ui/css/settings.css b/ui/css/settings.cssindex 6c1ed09..9d67cb5 100644--- a/ui/css/settings.css+++ b/ui/css/settings.css@@ -102,6 +102,8 @@ button.need-head:hover, button.need-head:hover .need-who b { color: var(--fg); }.need.open .need-head .chev { transform: rotate(90deg); }.need-line { font-size: var(--fs-lg); font-weight: var(--fw-medium); color: var(--fg); line-height: var(--lh-snug); overflow-wrap: anywhere; }.need-line.mono { font-family: var(--code); font-size: var(--fs-sm); font-weight: var(--fw-regular); }+/* 有默认回答的提问:不回复会怎样,贴着问题 */+.need-note { margin-top: calc(-1 * var(--space-1)); font-size: var(--fs-sm); color: var(--fg-2); }.need-actions { display: flex; align-items: center; gap: var(--ctl-gap); flex-wrap: wrap; }.need-actions:empty { display: none; }.need-reply { display: flex; align-items: center; gap: var(--ctl-gap); }diff --git a/ui/design/README.md b/ui/design/README.mdindex 9d7ac40..55e568b 100644--- a/ui/design/README.md+++ b/ui/design/README.md@@ -334,6 +334,12 @@ JS 组件(`ui/components/ui.js`)只是给常用组合一个带逻辑的写- **lively**:只给大头像(空态、新建页、启动页):呼吸、眨眼、四处看、脚下有影子。小于 36px 不画粒子。- **图层**:`python3 scripts/build-bot-avatars.py` 把每张原图拆成头(眼睛已抹掉)、两只耳朵、头顶配件和发光部分,输出 `design/bots/<key>.webp`(8 格精灵图)。眼睛是 `avatar.js` 画的 SVG,才能眨眼和换表情(睁眼、开心、闭眼、难过、××、晕、爱心)。换原图后重跑脚本,几何有变化时同步 `BOT_CHARS` 里的百分比。+## 文案++- 最短、能说清就行:不加解释性的括号,不写说明段落。健康、空闲时什么都不显示。+- 一行里接连几个状态时,合成一句自然的话:「进行中,有个问题等你回答」,不是「进行中 · 有个问题」。时间、花费这类简短的元信息照旧用「·」隔开(「进行中 · 12 分钟 · 约 $0.08」)。放不下的细节去掉,不往句子里塞。+- 中文、英文都要有(`ui/locales/`,服务端的在 `src/i18n/messages/`)。+## 新增或修改1. 先在样例页里找现成的 token、组件、文字角色。diff --git a/ui/design/gallery.js b/ui/design/gallery.jsindex 513129f..a525057 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, TaskGroup, TaskRow } from "../components/tasks.js";+import { PausedLine, TaskChip, 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";@@ -591,6 +591,9 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<div class="msg-row assistant"><div class="card"><div class="q-block"><div class="q">要用哪条线路?</div><div class="opts"><button type="button" class="opt picked"><span class="letter">A</span><span>国内线路<span class="desc">延迟低</span></span></button><button type="button" class="opt"><span class="letter">B</span><span>海外线路<span class="desc">模型更全</span></span></button></div></div></div></div>+ <div class="msg-row assistant"><div class="card"><div class="meta"><span>「竞品周报」想问你</span></div><div class="q-block"><div class="q">报告用中文还是英文?</div><div class="q-detail">不回复就按中文做</div>+ <div class="opts"><button type="button" class="opt"><span class="letter">A</span><span>中文</span></button>+ <button type="button" class="opt"><span class="letter">B</span><span>英文</span></button></div></div></div></div><div class="msg-row assistant"><div class="file-card"><${Icon} name="file" size="xl" /><div class="grow"><div class="fname">report.pdf</div><div class="fsub">已交付到机器人工作区</div></div></div></div></div><div class="composer"><textarea rows="1" placeholder="给「我的助手」发消息,/ 查看命令"></textarea>@@ -607,7 +610,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<${NeedsRow} count=${3} onClick=${() => {}} /><${NeedsRow} count=${2} on onClick=${() => {}} /><${NeedsRow} count=${0} /></div>`}<//>- <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天">+ <${Demo} flush col title="列表" note="NeedItem:等你回答 / 等你回答(任务接着在做,不回复就按默认)/ 等你批准 / 预算用完(再给 $1 继续?)/ 未送达 / 失败 / 规则本月预算用完 / 登录过期 / 预算留给聊天">${() => html`<div class="list needs-list">${NEEDS.map((it) => html`<${NeedItem} item=${it} multiBot onAct=${async () => {}} />`)}</div>`}<//><//>@@ -631,11 +634,20 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场<//><${Section} id="tasks" title="任务" lead="信息面板的「任务」组就是一个机器人的全部任务和规则:进行中、等你的在前,规则其次,结束了的收在最后一行里,点开才列出来(留 30 天)。一个任务一行,点开是同一块里的详情:来自、最新进展、预算(可以改)、文件夹(大小、打开)、要清理时的日期和保留、每次运行折叠的处理过程。什么都没有时整组不画。">- <${Demo} title="「任务」组" note="TaskGroup:进行中 / 等你回答 / 规则 / 已结束 1(点开列出结束了的,那个文件夹 3 天后清理)">+ <${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 }} />+ <${TaskGroup} botId="b" tasks=${TASKS} rules=${[RULES[0]]} ended=${ENDED} details=${{ t1: TASK_DETAIL, t4: ASKING_DETAIL, t2: ASK_DETAIL, t3: ENDED_DETAIL }} /></div>`}<//>+ <${Demo} title="问了还在做" note="TaskRow 展开:问题(下面一句不回复就按中文做)· 最新进展 · 预算 · 运行中;对话里的胶囊点开是同一份详情">+ ${() => 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=${ASKING} open data=${ASKING_DETAIL} onToggle=${() => {}} onOpenConv=${() => {}} /></div>+ </div>`}+ <//>+ <${Demo} col title="对话里的胶囊" note="TaskChip:进行中 / 进行中,有个问题等你回答;点开是详情(不写来自)">+ ${() => html`<div class="gal-chat"><div class="msg-row assistant"><${TaskChip} task=${TASKS[0]} data=${TASK_DETAIL} /></div>+ <div class="msg-row assistant"><${TaskChip} task=${ASKING} data=${ASKING_DETAIL} /></div></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>@@ -667,6 +679,7 @@ const { mounted, leaving } = usePresence(open); /* design/motion.js:退场/** 「需要你」的样例(单人:一个人用自己的机器人) */const NEEDS = [{ id: "q", kind: "question", botName: "小蓝", subject: "GPU 价格调研", status: "等你回答", line: "报告用中文还是英文?", since: Date.now() - 2 * 60_000, severity: "warn", questions: [{ id: "a", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }] }] },+ { id: "qd", kind: "question", botName: "小蓝", subject: "竞品周报", status: "等你回答", line: "报告用中文还是英文?", note: "不回复就按中文做", since: Date.now() - 3 * 60_000, severity: "warn", taskId: "t4", questions: [{ id: "answer", question: "报告用中文还是英文?", options: [{ label: "中文" }, { label: "英文" }], default: "中文" }] },{ id: "a", kind: "approval", botName: "小蓝", subject: "清理旧构建", status: "等你批准", line: "rm -rf build/", since: Date.now() - 5 * 60_000, severity: "warn" },{ id: "bq", kind: "question", botName: "小蓝", subject: "季度报告 PPT", status: "预算用完", line: "已用约 $1.00,再给 $1 继续?", since: Date.now() - 8 * 60_000, severity: "warn", questions: [{ id: "budget", question: "已用约 $1.00,再给 $1 继续?", options: [{ label: "继续" }, { label: "停止" }] }] },{ id: "d", kind: "delivery", botName: "小蓝", subject: "1 条结果未送达微信", status: "在微信里发条消息就能收到", line: "季度报告做好了,在 tasks 文件夹里。", since: Date.now() - 20 * 60_000, severity: "warn", actions: [] },@@ -678,13 +691,15 @@ const NEEDS = [{ id: "c", kind: "cleanup", botName: "小蓝", subject: "2 个任务文件夹 11月4日 删除", status: "", line: "整理下载目录和旧照片归档 · 30 天没动过", since: Date.now() - 5 * 3600_000, severity: "warn", actions: ["keep", "dismiss"] },];-/** 任务的样例(单人:自己的机器人小蓝):在调研的、等你回答的、昨天做完的(文件夹 3 天后清理) */+/** 任务的样例(单人:自己的机器人小蓝):在调研的、问了个有默认回答的问题接着在做的、等你回答的、昨天做完的(文件夹 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" }),+ task({ id: "t4", title: "竞品周报", stage: { key: "working/asking", label: "进行中,有个问题等你回答", group: "working" }, createdAt: ago(20), updatedAt: ago(3), spentUsd: 0.05, latest: "三家的更新都整理好了,在写对比", folder: "tasks/weekly-7d1e20", question: { text: "报告用中文还是英文?", note: "不回复就按中文做" } }),+ 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", question: { text: "PPT 要几页?" } }),];+const ASKING = TASKS[1];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 }),];@@ -696,8 +711,15 @@ const TASK_DETAIL = {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 ASKING_DETAIL = {+ task: ASKING,+ origin: { channel: "weixin", at: ago(20), text: "后台帮我把三家竞品这周的更新整理成周报" },+ sizes: { folder: 640_000, sessions: 420_000 },+ canOpen: true,+ runs: [{ id: "r4", cause: "launch", state: "running", outcome: "", queuedAt: ago(20), startedAt: ago(20), endedAt: 0, steps: 2, stepList: [step("s4", "web_fetch", "a.example/changelog"), step("s5", "write", "weekly.md")] }],+};const ASK_DETAIL = {- task: TASKS[1],+ task: TASKS[2],origin: { channel: "weixin", at: ago(50), text: "后台帮我把季度数据做成 PPT" },sizes: { folder: 5_600_000, sessions: 900_000 },canOpen: true,diff --git a/ui/locales/en/tasks.js b/ui/locales/en/tasks.jsindex ed21e2c..9ea98fe 100644--- a/ui/locales/en/tasks.js+++ b/ui/locales/en/tasks.js@@ -17,6 +17,7 @@ export default {costOf: "About {spent} of {budget}",costShort: "About {spent}",origin: "From",+ question: "Question",originLine: "{where} · {when} “{text}”",openConv: "Open the conversation",budget: "Budget",diff --git a/ui/locales/zh-CN/tasks.js b/ui/locales/zh-CN/tasks.jsindex 82aea77..8b212e2 100644--- a/ui/locales/zh-CN/tasks.js+++ b/ui/locales/zh-CN/tasks.js@@ -18,6 +18,7 @@ export default {costShort: "约 {spent}",// 3f:任务详情、信息面板的「任务」组origin: "来自",+ question: "问题",originLine: "{where} · {when}「{text}」",openConv: "打开会话",budget: "预算",diff --git a/ui/screens/chat.js b/ui/screens/chat.jsindex 0c89ee6..76e4ff8 100644--- a/ui/screens/chat.js+++ b/ui/screens/chat.js@@ -136,6 +136,7 @@ export function PromptCard({ requestId, fallback }) {${qs.map((q) => html`<div class="q-block"><div class="q">${q.question}</div>${q.detail && html`<div class="q-detail">${q.detail}</div>`}+ ${row.note && html`<div class="q-detail">${row.note}</div>`}${(q.options || []).length > 0 && html`<div class="opts" role=${q.multiSelect ? "group" : "radiogroup"}>${q.options.map((o, i) => html`<button type="button" class=${`opt${(picked[q.id] || []).includes(o.label) ? " picked" : ""}`} disabled=${!pending || busy}role=${q.multiSelect ? "checkbox" : "radio"} aria-checked=${(picked[q.id] || []).includes(o.label)} onClick=${() => choose(q, o.label)}>diff --git a/ui/screens/needs-you.js b/ui/screens/needs-you.jsindex 728acd8..a0bd6a8 100644--- a/ui/screens/needs-you.js+++ b/ui/screens/needs-you.js@@ -1,4 +1,5 @@// 需要你(3b):所有机器人里在等你的事,一行一件,操作就在行里(回答、批准、重试、加预算继续…);点标题那一行展开详情。+// 任务问的有默认回答的问题(任务接着在做):问题下面一句不回复会怎样(「不回复就按中文做」)。// 没事时侧栏没有这一行,直接打开这一页只有一句「没有需要你处理的事」。状态是"点 + 文字":黄 = 等你,红 = 失败 / 登录过期。// 预算(3e):任务预算用完是一个提问(「已用约 $1.00,再给 $1 继续?」继续 / 停止);规则本月预算用完可以继续;// 机器人的预算留给聊天、后台工作停着的,去机器人设置调整预算。@@ -66,6 +67,7 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB? html`<button type="button" class="need-head" aria-expanded=${expands ? open : undefined} title=${expands ? (open ? t("needs.collapse") : item.ruleId ? t("needs.viewRule") : t("needs.viewTask")) : t("needs.openChat")} onClick=${head}>${headIn}</button>`: html`<div class="need-head">${headIn}</div>`}${item.line && html`<div class=${`need-line selectable${item.kind === "approval" ? " mono" : ""}`}>${item.line}</div>`}+ ${item.note && html`<div class="need-note">${item.note}</div>`}<div class="need-actions">${opts && opts.map((o, i) => html`<${Button} loading=${busy === `o${i}`} disabled=${!!busy} onClick=${() => act("answer", { text: String(i + 1) }, `o${i}`)}>${o.label}<//>`)}${item.kind === "question" && !writing && html`<button type="button" class="text" disabled=${!!busy} onClick=${() => setWriting(true)}>${t("needs.reply")}</button>`}@@ -93,7 +95,7 @@ export function NeedItem({ item, multiBot, onAct, onOpenChat, onRelogin, onOpenB}} /><${Button} variant="primary" loading=${busy === "text"} disabled=${!text.trim()} onClick=${send}>${t("needs.send")}<//></div>`}- ${open && item.taskId && html`<div class="need-detail"><${TaskDetail} task=${{ id: item.taskId, title: item.subject, stage: { group: "needs" } }} /></div>`}+ ${open && item.taskId && html`<div class="need-detail"><${TaskDetail} task=${{ id: item.taskId, title: item.subject, stage: { group: "needs" } }} question=${false} /></div>`}${open && item.ruleId && html`<div class="need-detail"><${RuleOpen} id=${item.ruleId} /></div>`}</div>`;}