🤖 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
feat(agent): show what the agent is doing, and stop stuck turns
Marlad6b81bfc3d24
diff --git a/README.md b/README.mdindex 01308f7..52b9ad0 100644--- a/README.md+++ b/README.md@@ -87,7 +87,9 @@ docker exec amb cat /data/ui-token # 打开 http://<主机>:3600/?token=<令- 调用归因:经 Modelflare 的请求都带 `X-Modelflare-Skill: anymodel-bot/<版本>`,链接都带 `utm_source=anymodelbot`。- 线路:默认国际线路 `https://modelflare.dev/v1`;中国大陆可在「高级」或 设置 → Modelflare → 线路 选「中国大陆优化」(`https://origin.modelflare.dev/v1`)。线路由你选定,不自动切换。- 设置 → Modelflare:账户、余额与充值、余额提醒、用量、通知、邀请;连接状态(只显示 Key 尾号);未登录时可更换密钥或断开(机器人与会话保留,断开后回到首次连接页);默认模型、刷新模型列表。-- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/help` 照常可用。+- 对话中输入框右侧的模型按钮可为当前会话切换模型(也可设为机器人默认);`/model`、`/reset`、`/new`、`/status`、`/stop`、`/help` 照常可用。+- 处理过程:代理回合的每一步(模型请求及用时与 tokens、工具调用及参数与输出、重试、子代理)折叠在回复上方的"用时"一行里,点开查看;微信 / 飞书会话在信息面板 → 最近会话里看,正在处理的那一轮实时显示并可中止。+- 卡住的消息:`/stop`(任何渠道)或信息面板里的「中止」立即结束正在处理的回合;代理 10 分钟没有任何进展(模型不回、工具不动、只在重试;等你批准或回答不算)会自动中止,单回合最长 30 分钟(`AMB_AGENT_IDLE_TIMEOUT_MS`、`AMB_AGENT_TURN_TIMEOUT_MS` 可调)。DSH 没有中断单个回合的接口,中止时会重启该机器人的代理进程。前一条还在处理时发来的新消息会先收到一句提示;`/status` 显示它走到了哪一步、多久没有进展。- 内置网关:magpie 以 `--gateway` 模式运行,使用本程序数据目录内独立的 HOME/配置目录;**不读取**你电脑上已有的 Claude/Codex 等订阅凭据,**不改写**任何 agent 配置,关闭自动更新与账户发现。它只供本进程内部调用,界面不再反代它的页面或 `/v1`。- API Key 只保存在内置网关的隔离配置中,不经过命令行参数、不写日志,前端只拿到尾号。- 开发/测试:设置 `AMB_MAGPIE_BASE_URL` 可直接使用一个 OpenAI 兼容端点(不启动内置网关,界面视为已连接,账户功能不可用);`AMB_MODELFLARE_BASE_URL` 可把 Modelflare 基址指向本地 mock,`AMB_MODELFLARE_ISSUER` 把登录与账户接口指向本地 mock。diff --git a/src/agent/activity.ts b/src/agent/activity.tsnew file mode 100644index 0000000..1504ce3--- /dev/null+++ b/src/agent/activity.ts@@ -0,0 +1,229 @@+/**+ * 代理回合的活动记录:把 DSH 的会话事件折叠成看得懂的几类步骤(模型请求、工具调用、重试、子代理、压缩、出错)。+ * 网页对话里折叠在"用时"下面,微信/飞书会话在信息面板里看;/status 和看门狗用它说明卡在哪一步。+ */+import { summarizeCall } from "./host.js";++export interface ActivityStep {+ /** 同一步的更新沿用同一个 id(工具调用 id、m<回合>.<步>…) */+ id: string;+ kind: "model" | "tool" | "retry" | "subagent" | "compact" | "error";+ /** 模型名、工具名… */+ title: string;+ /** 一行摘要:命令、路径、回复开头、失败原因 */+ summary?: string;+ /** 展开后看到的参数 / 输出(已截断) */+ input?: string;+ output?: string;+ status: "running" | "ok" | "error";+ /** 没做完就被打断(回合出错、/stop、看门狗、超时):说明时仍按"正在做"来说 */+ cut?: boolean;+ at: number;+ ms?: number;+ tokens?: { input?: number; output?: number };+}++const MAX_STEPS = 120;+const MAX_INPUT = 1000;+const MAX_OUTPUT = 2000;++const clip = (s: string, n: number) => (s.length > n ? s.slice(0, n - 1) + "…" : s);+const oneLine = (s: string, n = 140) => clip(s.replace(/\s+/g, " ").trim(), n);++function textOf(content: unknown): string {+ if (!Array.isArray(content)) return typeof content === "string" ? content : "";+ return content+ .map((b: any) => (b?.type === "text" ? String(b.text ?? "") : b?.type === "image" ? "[图片]" : ""))+ .filter(Boolean)+ .join("\n");+}++function prettyArgs(args: string): string {+ try {+ return JSON.stringify(JSON.parse(args || "{}"), null, 2);+ } catch {+ return args;+ }+}++export class ActivityLog {+ readonly steps: ActivityStep[] = [];++ /** model:这一轮用的模型(DSH 只在会话第一次请求时报 request/context,之后的回合靠它起名) */+ constructor(+ private onChange?: (step: ActivityStep) => void,+ private model = "",+ ) {}++ get last(): ActivityStep | undefined {+ return this.steps.at(-1);+ }++ /**+ * 喂一条 DSH 会话事件(子代理通知用 subagent/started、subagent/finished)。+ * 返回这条事件算不算"有进展":模型在重试不算,看门狗靠它判断回合是不是卡住了。+ */+ apply(type: string, data: any, time = Date.now()): boolean {+ data ??= {};+ switch (type) {+ case "request/context": {+ // step/start 在它之前:第一步建出来时还不知道模型名+ if (!data.model) return true;+ this.model = String(data.model);+ const cur = this.steps.findLast((s) => s.kind === "model" && s.status === "running");+ if (cur && cur.title !== this.model) this.put({ ...cur, title: this.model });+ return true;+ }+ case "step/start":+ this.put({ id: `m${data.turn}.${data.step}`, kind: "model", title: this.model || "模型", status: "running", at: time });+ return true;+ case "assistant/message": {+ const msg = data.message ?? {};+ const content: any[] = Array.isArray(msg.content) ? msg.content : [];+ const calls = content.filter((b) => b?.type === "tool-call").map((b) => String(b.name));+ const text = content.filter((b) => b?.type === "text").map((b) => String(b.text ?? "")).join("\n").trim();+ const thinking = content.filter((b) => b?.type === "reasoning" || b?.type === "thinking").map((b) => String(b.text ?? b.reasoning ?? "")).join("\n").trim();+ const model = String(msg.source?.model ?? "") || this.model;+ if (model) this.model = model;+ const id = `m${data.turn}.${data.step}`;+ const prev = this.find(id);+ const at = prev?.at ?? time;+ const u = data.usage ?? {};+ this.put({+ id,+ kind: "model",+ title: model || "模型",+ summary: text ? oneLine(text) : calls.length ? `调用 ${calls.join("、")}` : thinking ? "(只有思考,没有文字)" : "(空回复)",+ output: clip([thinking && `[思考]\n${thinking}`, text].filter(Boolean).join("\n\n"), MAX_OUTPUT) || undefined,+ status: "ok",+ at,+ ms: Math.max(0, time - at),+ tokens: u.inputTokens || u.outputTokens ? { input: Number(u.inputTokens) || 0, output: Number(u.outputTokens) || 0 } : undefined,+ });+ return true;+ }+ case "tool/call": {+ const name = String(data.name ?? "tool");+ const args = String(data.arguments ?? "");+ const sum = summarizeCall(name, args);+ this.put({+ id: String(data.callId),+ kind: "tool",+ title: name,+ summary: sum === name ? undefined : sum.slice(name.length + 2),+ input: clip(prettyArgs(args), MAX_INPUT),+ status: "running",+ at: time,+ });+ return true;+ }+ case "tool/result": {+ const msg = data.message ?? {};+ const prev = this.find(String(msg.toolCallId ?? ""));+ if (!prev) return true;+ this.put({ ...prev, status: msg.isError ? "error" : "ok", ms: Math.max(0, time - prev.at), output: clip(textOf(msg.content), MAX_OUTPUT) || undefined });+ return true;+ }+ case "llm/retry": {+ const f = data.failure ?? {};+ const why = String(f.message ?? f.code ?? "请求失败");+ const of = data.maxRetries ? `${data.retry}/${data.maxRetries}` : String(data.retry ?? "");+ this.put({+ id: `r${data.retryId ?? data.turn}.${data.retry}`,+ kind: "retry",+ title: "模型请求失败,重试",+ summary: oneLine(`第 ${of} 次,${Math.round((Number(data.delayMs) || 0) / 1000)} 秒后:${why}`),+ status: "error",+ at: time,+ });+ return false;+ }+ case "llm/retry-started":+ return false;+ case "compaction/start":+ this.put({ id: `c${time}`, kind: "compact", title: "压缩上下文", status: "running", at: time });+ return true;+ case "compaction/end": {+ const prev = this.steps.findLast((s) => s.kind === "compact" && s.status === "running");+ if (prev) this.put({ ...prev, status: "ok", ms: Math.max(0, time - prev.at) });+ return true;+ }+ case "subagent/started":+ this.put({ id: `s${data.childSessionId}`, kind: "subagent", title: "子代理", status: "running", at: time });+ return true;+ case "subagent/finished": {+ const prev = this.find(`s${data.childSessionId}`);+ const last = textOf(data.lastAssistantMessage);+ this.put({+ id: `s${data.childSessionId}`,+ kind: "subagent",+ title: "子代理",+ summary: last ? oneLine(last) : String(data.stopReason ?? "") || undefined,+ output: last ? clip(last, MAX_OUTPUT) : undefined,+ status: data.status === "ok" ? "ok" : "error",+ at: prev?.at ?? time,+ ms: prev ? Math.max(0, time - prev.at) : undefined,+ });+ return true;+ }+ case "turn/end": {+ const r = data.reason ?? {};+ if (r.kind === "error") {+ // 还挂着的步骤(模型请求、工具)跟着这个错误结束+ for (const s of this.steps) if (s.status === "running") this.put({ ...s, status: "error", cut: true, ms: Math.max(0, time - s.at) });+ this.put({ id: `e${data.turn}`, kind: "error", title: "回合出错", summary: oneLine(String(r.error?.message ?? "unknown error"), 300), status: "error", at: time });+ }+ return true;+ }+ default:+ return true;+ }+ }++ /** 外部原因结束(/stop、看门狗、超时):还在进行的步骤标成失败,再记一条说明 */+ end(why: string, time = Date.now()): void {+ for (const s of this.steps) if (s.status === "running") this.put({ ...s, status: "error", cut: true, ms: Math.max(0, time - s.at) });+ this.put({ id: `x${time}`, kind: "error", title: "已中止", summary: why, status: "error", at: time });+ }++ private find(id: string): ActivityStep | undefined {+ return this.steps.find((s) => s.id === id);+ }++ private put(step: ActivityStep): void {+ for (const k of Object.keys(step) as Array<keyof ActivityStep>) if (step[k] === undefined) delete step[k];+ const i = this.steps.findIndex((s) => s.id === step.id);+ if (i >= 0) this.steps[i] = step;+ else {+ this.steps.push(step);+ if (this.steps.length > MAX_STEPS) this.steps.shift();+ }+ this.onChange?.({ ...step });+ }+}++/** 一步的口语说明(/status、排队提示、中止消息里用) */+export function describeStep(s: ActivityStep): string {+ const what = s.summary ? `${s.title}:${s.summary}` : s.title;+ const doing = s.status === "running" || !!s.cut;+ switch (s.kind) {+ case "model":+ return doing ? `等待 ${s.title} 回复` : `${s.title} 回复了${s.summary ? `:${s.summary}` : ""}`;+ case "tool":+ return doing ? `正在运行 ${what}` : `${what}(${s.status === "error" ? "失败" : "完成"})`;+ case "retry":+ return `模型请求失败,正在重试(${s.summary ?? ""})`;+ case "subagent":+ return doing ? "子代理在工作" : `子代理结束${s.summary ? `:${s.summary}` : ""}`;+ case "compact":+ return doing ? "正在压缩上下文" : "压缩了上下文";+ case "error":+ return what;+ }+}++/** "12 秒" / "3 分 5 秒" */+export function fmtSecs(ms: number): string {+ const s = Math.max(0, Math.round(ms / 1000));+ return s < 60 ? `${s} 秒` : `${Math.floor(s / 60)} 分${s % 60 ? ` ${s % 60} 秒` : "钟"}`;+}diff --git a/src/agent/host.ts b/src/agent/host.tsindex 4584b5b..e0fbb71 100644--- a/src/agent/host.ts+++ b/src/agent/host.ts@@ -121,7 +121,23 @@ function loadSdk(runtimeDir: string): Promise<SdkModule> {/** 回合中的可见进度(工具调用等),由渠道批量发送。 */export interface TurnObserver {onProgress?(text: string): void;- onEvent?(type: string, data: any): void;+ /** DSH 会话事件(time 是事件自带的时间);子代理的开始/结束以 subagent/started、subagent/finished 送来 */+ onEvent?(type: string, data: any, time?: number): void;+ /** 消息已经交给代理(之前是等进程、等会话) */+ onStart?(): void;+}++/**+ * 回合被中止:用户 /stop、长时间没有进展(idle)、超过单回合上限(timeout)。+ * SDK 没有中断单个回合的接口,只能关掉子进程;ms 是触发时的时长(idle、timeout 为阈值)。+ */+export class TurnStopped extends Error {+ constructor(+ readonly reason: "user" | "idle" | "timeout",+ readonly ms: number,+ ) {+ super(`agent turn stopped (${reason})`);+ }}export interface AgentHostOptions {@@ -205,6 +221,8 @@ export interface TurnInput {observer?: TurnObserver;/** 只在模型能看图时传(acceptsImages),否则模型只拿到文字里的工作区路径 */images?: TurnImage[];+ /** 中止这个回合(reason 为 TurnStopped):会关掉子进程,同一机器人其它进行中的回合也会失败 */+ signal?: AbortSignal;}/** 回合结束时的上下文用量(来自 DSH 事件)。 */@@ -792,6 +810,8 @@ exec "$REAL" "$@"async runTurn(input: TurnInput): Promise<{ text: string; sessionId: string; files: string[]; usage: TurnUsage }> {const h = await this.ensure(input.model);const s = await this.sessionFor(h, input.conversationId);+ // 在等进程 / 会话时就被中止了:消息还没交出去,不用重启子进程+ if (input.signal?.aborted) throw input.signal.reason instanceof TurnStopped ? input.signal.reason : new TurnStopped("user", 0);this.active++;let timer: NodeJS.Timeout | undefined;let turnError: string | undefined;@@ -799,12 +819,15 @@ exec "$REAL" "$@"const lim = modelLimits(input.model);const usage: TurnUsage = { tokens: 0, window: lim.window, maxTokens: lim.maxTokens };const images = this.imageInput ? (input.images ?? []) : [];+ let unlisten = () => {};try {const timeoutMs = this.o.turnTimeoutMs ?? 30 * 60_000;const prompt = images.length ? [{ type: "text", text: input.text }, ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType }))] : input.text;+ input.observer?.onStart?.();const run = s.run(prompt, {onNotification: (n) => {if (process.env.AMB_DSH_TRACE) fs.appendFileSync(process.env.AMB_DSH_TRACE, JSON.stringify(n).slice(0, 2000) + "\n");+ if (n.method === "subagent.started" || n.method === "subagent.finished") return input.observer?.onEvent?.(n.method.replace(".", "/"), n.params, Date.now());if (n.method !== "session.event" || n.params?.sessionId !== s.id) return;const ev = n.params.event;const data = ev?.data ?? {};@@ -821,25 +844,37 @@ exec "$REAL" "$@"if (t > 0) usage.tokens = t;}if (ev?.type === "turn/end" && data?.reason?.kind === "error") turnError = String(data.reason.error?.message ?? "unknown error");- input.observer?.onEvent?.(String(ev?.type), data);+ input.observer?.onEvent?.(String(ev?.type), data, Number(ev?.time) || Date.now());},});- const timeout = new Promise<never>((_, rej) => {- timer = setTimeout(() => rej(new Error("agent turn timed out")), timeoutMs);+ // 中止后子进程被关掉,run 随后以"runtime closed"失败,已经没人等它+ run.catch(() => undefined);+ const stopped = new Promise<never>((_, rej) => {+ timer = setTimeout(() => rej(new TurnStopped("timeout", timeoutMs)), timeoutMs);+ const sig = input.signal;+ if (!sig) return;+ const onAbort = () => rej(sig.reason instanceof TurnStopped ? sig.reason : new TurnStopped("user", 0));+ if (sig.aborted) return onAbort();+ sig.addEventListener("abort", onAbort, { once: true });+ unlisten = () => sig.removeEventListener("abort", onAbort);});- const r = await Promise.race([run, timeout]);+ const r = await Promise.race([run, stopped]);this.failures = 0;if (!r.finalResponse && turnError) throw new Error(turnError);return { text: r.finalResponse, sessionId: s.id, files: deliverables(this.workspace, presented), usage };} catch (e) {- if (/timed out/.test((e as Error).message)) await this.closeHarness();- else if (images.length && this.state !== "running") {+ if (e instanceof TurnStopped) {+ log.warn("agent turn stopped, restarting dsh", { bot: this.o.botId, reason: e.reason, ms: e.ms, otherTurns: this.active - 1 });+ await this.closeHarness();+ this.state = "stopped";+ } else if (images.length && this.state !== "running") {this.imageInput = false;log.warn("dsh died on a turn with images; sending images by path only until the app restarts", { bot: this.o.botId, message: (e as Error).message.slice(0, 200) });}throw e;} finally {clearTimeout(timer);+ unlisten();this.active--;}}diff --git a/src/agent/manager.ts b/src/agent/manager.tsindex ca13c30..2f08e7a 100644--- a/src/agent/manager.ts+++ b/src/agent/manager.ts@@ -3,7 +3,8 @@ import type { Store } from "../store/db.js";import { logger } from "../log.js";import { AgentBridge } from "./bridge.js";import path from "node:path";-import { AgentHost, callDetail, type TurnInput, type TurnObserver, type TurnUsage } from "./host.js";+import { AgentHost, TurnStopped, callDetail, type TurnInput, type TurnObserver, type TurnUsage } from "./host.js";+import { ActivityLog, type ActivityStep } from "./activity.js";import type { MediaModel, MediaPlan, MediaService } from "./media.js";import { APPROVAL_TTL_MS, ApprovalCenter, type QuestionItem } from "./approvals.js";import { MemoryError, MemoryStore, type Scope } from "./memory.js";@@ -30,6 +31,8 @@ export interface AgentManagerOptions {upstream: () => { baseUrl: string; apiKey: string };enabled: boolean;turnTimeoutMs?: number;+ /** 代理已经在处理、却这么久没有任何进展(模型不回、工具不动、只在重试)就中止;等用户批准/回答不算 */+ idleTimeoutMs?: number;approvalTtlMs?: number;/** 后台小模型调用(管家判定、交接便条、记忆整理);缺省则这些功能静默跳过。botId 用来把请求记到该机器人的 Key 上 */complete?: (botId: string, model: string, system: string, user: string) => Promise<string>;@@ -41,6 +44,18 @@ export interface AgentManagerOptions {onNotice?: (text: string) => void;}+/** 一个进行中的回合(/status、/stop、排队提示、信息面板和故障排查用) */+export interface TurnProgress {+ botId: string;+ since: number;+ /** 最近一次有进展的时间;0 = 消息还没交给代理(在等进程、等会话) */+ lastProgress: number;+ activity: ActivityLog;+ abort: AbortController;+ /** 已经提示过"后来的消息排在它后面" */+ queuedNotice?: boolean;+}+/** 生成确认里"取消"那一项 */const CANCEL = "取消";@@ -163,19 +178,61 @@ export class AgentManager {void h.ensure(model).catch(() => undefined);}- /** 会话 → 正在进行的回合开始时间(/status 与故障排查用:后来的消息排在它后面) */- readonly turnsInProgress = new Map<string, { botId: string; since: number }>();+ /** 会话 → 正在进行的回合(后来的消息排在它后面) */+ readonly turnsInProgress = new Map<string, TurnProgress>();- async runTurn(botId: string, input: TurnInput) {+ /** onStep:活动记录里每新增或更新一步就回调一次(网页对话实时显示、回合结束后存进消息) */+ async runTurn(botId: string, input: TurnInput & { onStep?: (step: ActivityStep) => void }) {const conv = input.conversationId;- this.turnsInProgress.set(conv, { botId, since: Date.now() });+ const t: TurnProgress = { botId, since: Date.now(), lastProgress: 0, activity: new ActivityLog(input.onStep, input.model), abort: new AbortController() };+ this.turnsInProgress.set(conv, t);+ // 看门狗:代理已经在处理,却长时间没有进展(模型不回、工具不动、只在重试),又不是在等用户批准或回答 → 中止+ const idleMs = this.o.idleTimeoutMs ?? 10 * 60_000;+ const watchdog = setInterval(() => {+ if (!t.lastProgress || t.abort.signal.aborted) return;+ if (this.approvals.pending(conv).length) t.lastProgress = Date.now();+ else if (Date.now() - t.lastProgress > idleMs) {+ log.warn("agent turn idle, stopping", { bot: botId, conversationId: conv, idleMs, lastStep: t.activity.last });+ this.halt(conv, t, new TurnStopped("idle", idleMs));+ }+ }, Math.max(250, Math.min(15_000, idleMs / 4)));+ const observer: TurnObserver = {+ ...input.observer,+ onStart: () => {+ t.lastProgress = Date.now();+ input.observer?.onStart?.();+ },+ onEvent: (type, data, time) => {+ if (t.activity.apply(type, data, time)) t.lastProgress = Date.now();+ input.observer?.onEvent?.(type, data, time);+ },+ };try {- return await this.runTurnInner(botId, input);+ return await this.runTurnInner(botId, { ...input, observer, signal: t.abort.signal });+ } catch (e) {+ if (e instanceof TurnStopped && e.reason === "timeout") t.activity.end("超过单回合上限");+ throw e;} finally {+ clearInterval(watchdog);this.turnsInProgress.delete(conv);}}+ /** /stop、信息面板的"中止":返回有没有正在处理的回合 */+ stopTurn(conversationId: string): boolean {+ const t = this.turnsInProgress.get(conversationId);+ if (!t) return false;+ if (!t.abort.signal.aborted) this.halt(conversationId, t, new TurnStopped("user", Date.now() - t.since));+ return true;+ }++ private halt(conv: string, t: TurnProgress, why: TurnStopped): void {+ t.activity.end(why.reason === "user" ? "用户中止" : why.reason === "idle" ? "长时间没有进展,自动中止" : "超过单回合上限");+ t.abort.abort(why);+ // 这一轮还在等的批准 / 回答随之作废(代理进程会被重启,没人再等它们)+ for (const r of this.approvals.pending(conv)) this.approvals.cancel(r.id, "stopped");+ }+private async runTurnInner(botId: string, input: TurnInput) {const conv = input.conversationId;const gate = this.gates.get(conv);@@ -537,13 +594,19 @@ export class AgentManager {}/** 故障排查:运行时位置 + 每个已创建的代理进程的详细状态(stderr 尾部、最近一次退出)+ 进行中的回合 */- diagnostics(): { enabled: boolean; available: boolean; runtimeDir?: string; hosts: Record<string, Record<string, unknown>>; turns: Array<{ conversationId: string; botId: string; forMs: number }> } {+ diagnostics(): { enabled: boolean; available: boolean; runtimeDir?: string; hosts: Record<string, Record<string, unknown>>; turns: Array<{ conversationId: string; botId: string; forMs: number; idleMs?: number; lastStep?: ActivityStep }> } {return {enabled: this.o.enabled,available: this.available,runtimeDir: this.o.runtimeDir,hosts: Object.fromEntries([...this.hosts].map(([id, h]) => [id, h.diagnostics()])),- turns: [...this.turnsInProgress].map(([conversationId, t]) => ({ conversationId, botId: t.botId, forMs: Date.now() - t.since })),+ turns: [...this.turnsInProgress].map(([conversationId, t]) => ({+ conversationId,+ botId: t.botId,+ forMs: Date.now() - t.since,+ idleMs: t.lastProgress ? Date.now() - t.lastProgress : undefined,+ lastStep: t.activity.last,+ })),};}diff --git a/src/app.ts b/src/app.tsindex 51d47fd..8bc8fc9 100644--- a/src/app.ts+++ b/src/app.ts@@ -156,6 +156,7 @@ export class App {upstream,enabled: config.agent.mode === "dsh" && !opts.models,turnTimeoutMs: config.agent.turnTimeoutMs,+ idleTimeoutMs: config.agent.idleTimeoutMs,approvalTtlMs: config.agent.approvalTtlMs,// 后台小任务(管家判定/交接/记忆整理)直接走 magpie,不经代理子进程complete: (botId, model, system, user) =>diff --git a/src/channels/feishu/channel.ts b/src/channels/feishu/channel.tsindex e73b89d..8b1e30e 100644--- a/src/channels/feishu/channel.ts+++ b/src/channels/feishu/channel.ts@@ -95,15 +95,14 @@ export class FeishuChannel {receivedAt: Date.now(),};// 审批/提问回复在入队前处理(正在进行的回合正等着它)+ // 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队const intercepted = this.runtime.interceptReply(inbound);- if (intercepted.handled) {- if (intercepted.ack) {- const p = this.transport.replyText(ev.messageId, intercepted.ack).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));- this.pending.add(p);- void p.finally(() => this.pending.delete(p));- }- return;+ if (intercepted.ack) {+ const p = this.transport.replyText(ev.messageId, intercepted.ack).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));+ this.pending.add(p);+ void p.finally(() => this.pending.delete(p));}+ if (intercepted.handled) return;const p = this.queue.run(`feishu:${this.botId}:${ev.chatId}`, async () => {const reply = new FeishuReply(this.transport, ev.messageId, this.throttleMs);try {diff --git a/src/channels/weixin/channel.ts b/src/channels/weixin/channel.tsindex 34100a7..846edc2 100644--- a/src/channels/weixin/channel.ts+++ b/src/channels/weixin/channel.ts@@ -309,16 +309,15 @@ export class WeixinChannel {receivedAt: Date.now(),};// 审批/提问回复不能排在正在等待审批的回合后面(会死锁),在入队前处理+ // 没处理掉但带 ack 的(前一条还在处理):先说一声,消息照常入队const intercepted = this.runtime.interceptReply(ev);- if (intercepted.handled) {- if (intercepted.ack) {- const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota);- const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));- this.pending.add(p);- void p.finally(() => this.pending.delete(p));- }- return;+ if (intercepted.ack) {+ const ack = new WeixinReply(this.client!, userId, peer.contextToken, this.quota);+ const p = ack.apply({ type: "text", text: intercepted.ack }).catch((e) => this.log.warn("ack failed", { message: (e as Error).message }));+ this.pending.add(p);+ void p.finally(() => this.pending.delete(p));}+ if (intercepted.handled) return;const media = mediaItems(m.item_list);const p = this.queue.run(`weixin:${this.botId}:${userId}`, async () => {const reply = new WeixinReply(this.client!, userId, this.store.getWeixinPeer(this.botId, userId)?.contextToken ?? peer.contextToken, this.quota);diff --git a/src/config.ts b/src/config.tsindex 69ce8ac..1597d7c 100644--- a/src/config.ts+++ b/src/config.ts@@ -38,7 +38,7 @@ export interface AppConfig {/** cdnBaseUrl:收发图片/文件的微信 CDN(测试时指向假服务) */weixin: { apiBaseUrl: string; cdnBaseUrl: string };/** 代理宿主:dsh = DeepSeek Harness(工具/沙箱/审批);off = 纯对话 */- agent: { mode: "dsh" | "off"; turnTimeoutMs: number; approvalTtlMs: number };+ agent: { mode: "dsh" | "off"; turnTimeoutMs: number; idleTimeoutMs: number; approvalTtlMs: number };}export function defaultDataDir(): string {@@ -102,6 +102,7 @@ export function loadConfig(overrides: { dataDir?: string; env?: NodeJS.ProcessEnagent: {mode: (env.AMB_AGENT || file.agent?.mode || "dsh") === "off" ? "off" : "dsh",turnTimeoutMs: num(env.AMB_AGENT_TURN_TIMEOUT_MS, file.agent?.turnTimeoutMs ?? 30 * 60_000),+ idleTimeoutMs: num(env.AMB_AGENT_IDLE_TIMEOUT_MS, file.agent?.idleTimeoutMs ?? 10 * 60_000),approvalTtlMs: num(env.AMB_APPROVAL_TTL_MS, file.agent?.approvalTtlMs ?? 10 * 60_000),},};diff --git a/src/core/runtime.ts b/src/core/runtime.tsindex 6ca9f1a..70f4b47 100644--- a/src/core/runtime.ts+++ b/src/core/runtime.ts@@ -4,7 +4,8 @@ import path from "node:path";import type { InboundEvent, ReplySession } from "./types.js";import { eventText } from "./types.js";import { acceptsImages, type ModelClient, type ChatMessage } from "../llm/client.js";-import type { TurnImage } from "../agent/host.js";+import { TurnStopped, type TurnImage } from "../agent/host.js";+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";@@ -79,7 +80,8 @@ const HELP = ["/model <编号或模型名> — 切换当前会话的模型","/reset — 清空当前会话的上下文(代理模式下同时开启新的代理会话;长期记忆保留)","/new — 开始新的一段对话:旧对话归档并生成交接便条,长期记忆保留",- "/status — 查看当前会话使用的模型",+ "/status — 查看当前模型、代理状态和正在处理的消息走到了哪一步",+ "/stop — 中止正在处理的消息(代理模式下会重启代理进程)","/help — 显示本帮助",].join("\n");@@ -178,7 +180,10 @@ export class BotRuntime {}}- /** 渠道在进入每会话串行队列之前调用:处理审批回复(y 1234 / n 1234)与提问回答。 */+ /**+ * 渠道在进入每会话串行队列之前调用:处理审批回复(y 1234 / n 1234)、提问回答和 /status /help /stop。+ * handled=false 但带 ack:前一条还在处理,渠道先把 ack 发出去,消息照常入队。+ */interceptReply(ev: InboundEvent): { handled: boolean; ack?: string } {const text = eventText(ev);const convId = `${ev.botId}:${ev.channel}:${ev.conversation.id}`;@@ -189,8 +194,23 @@ export class BotRuntime {if (bot) return { handled: true, ack: cmd === "/help" ? HELP : this.statusText(bot.id, convId, this.opts.store.getConversation(convId)?.model ?? "", bot.defaultModel) };}const agent = this.opts.agent;+ // /stop 必须插队:它要停的正是排在前面、卡住的那个回合+ if (cmd === "/stop") {+ const t = agent?.turnsInProgress.get(convId);+ if (!t || !agent?.stopTurn(convId)) return { handled: true, ack: "当前没有正在处理的消息。" };+ return { handled: true, ack: `正在中止上一条消息(已处理 ${fmtSecs(Date.now() - t.since)})…` };+ }if (!agent) return { handled: false };- return agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`);+ const r = agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`);+ if (r.handled) return r;+ // 前一条还在处理:说一声这条排在后面、怎么中止(每个回合只说一次),消息照常入队+ const t = agent.turnsInProgress.get(convId);+ if (t && !t.queuedNotice) {+ t.queuedNotice = true;+ const last = t.activity.last;+ return { handled: false, ack: `上一条消息还在处理(已 ${fmtSecs(Date.now() - t.since)}${last ? `,现在:${clipLine(describeStep(last))}` : ""}),这条会排在它后面。发送 /stop 可以中止。` };+ }+ return r;}/** /status 的内容:只读本地状态,立即返回 */@@ -205,7 +225,7 @@ export class BotRuntime {// Windows:代理执行命令用的 PowerShell;没有 7 时建议安装const ps = a?.available ? pwshStatusLine(pwshProbe.snapshot()) : "";const turn = a?.turnsInProgress.get(convId);- const busy = turn ? [`本会话上一条消息还在处理(已 ${Math.round((Date.now() - turn.since) / 1000)} 秒),新消息会排在它后面`] : [];+ const busy = turn ? [busyLine(turn.since, turn.lastProgress, turn.activity.steps)] : [];return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...host, ...(ps ? [ps] : []), ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");}@@ -233,6 +253,12 @@ export class BotRuntime {private async handleAgent(agent: AgentManager, botId: string, convId: string, text: string, model: string, systemPrompt: string, out: ReplySession, images: TurnImage[] = []): Promise<boolean | "starting"> {const { store } = this.opts;let visible = false;+ // 活动记录:网页对话实时显示(其它渠道忽略这个操作),回合结束后随回复存下来,信息面板里能看+ const steps = new Map<string, ActivityStep>();+ const onStep = (step: ActivityStep) => {+ steps.set(step.id, step);+ void out.apply({ type: "activity", step });+ };const unbind = agent.approvals.bindSink(convId, async (row) => {visible = true;await out.apply(interactiveOp(row));@@ -278,6 +304,7 @@ export class BotRuntime {text: input,model,...(images.length ? { images } : {}),+ onStep,observer: {// 工具调用不进入聊天:只用于判断代理已开始工作(不再回退到纯对话),正在输入状态由渠道维持onProgress: () => {@@ -287,7 +314,7 @@ export class BotRuntime {}).finally(() => clearInterval(startup));store.addMessage(convId, "user", text);const finalText = r.text.trim() || "(已完成,没有文字回复)";- store.addMessage(convId, "assistant", finalText);+ store.addMessage(convId, "assistant", finalText, [...steps.values()]);await out.apply({ type: "stream.finish", text: finalText });for (const f of r.files ?? []) {try {@@ -300,12 +327,14 @@ export class BotRuntime {} catch (e) {const err = e as Error;log.warn("agent turn failed", { message: err.message.slice(0, 300) });- if (!visible && agent.host(botId).state !== "running") {+ if (!(err instanceof TurnStopped) && !visible && agent.host(botId).state !== "running") {log.warn("agent host unavailable, falling back to plain chat");return false;}+ const msg = turnFailedText(err, [...steps.values()]);store.addMessage(convId, "user", text);- await out.apply({ type: "stream.finish", text: `⚠️ 代理执行失败:${err.message.slice(0, 300)}` });+ store.addMessage(convId, "assistant", msg, [...steps.values()]);+ await out.apply({ type: "stream.finish", text: msg });return true;} finally {clearInterval(startup);@@ -414,3 +443,30 @@ export function interactiveOp(row: ApprovalRow) {buttons: single?.options?.length && !single.multiSelect ? single.options.map((o, i) => ({ label: o.label, value: { amb: "question", id: row.id, option: String(i + 1) }, style: "default" as const })) : undefined,};}++const clipLine = (s: string, n = 80) => (s.length > n ? s.slice(0, n - 1) + "…" : s);++/** /status 里"上一条还在处理"那一行:处理了多久、现在在做什么、多久没动了 */+export function busyLine(since: number, lastProgress: number, steps: ActivityStep[]): string {+ const now = Date.now();+ const last = steps.at(-1);+ const parts = [`已 ${fmtSecs(now - since)}`];+ if (steps.length) parts.push(`${steps.length} 步`);+ if (!lastProgress) parts.push("还在等代理进程接手");+ else if (last) parts.push(`现在:${clipLine(describeStep(last))}`);+ if (lastProgress && now - lastProgress >= 60_000) parts.push(`${fmtSecs(now - lastProgress)}没有新进展`);+ return `本会话上一条消息还在处理(${parts.join(",")}),新消息会排在它后面。发送 /stop 可以中止`;+}++/** 代理回合失败时给用户的话:中止(/stop、没进展、超时)各说清原因和下一步,进程被重启的另说 */+export function turnFailedText(err: Error, steps: ActivityStep[]): string {+ const last = steps.filter((s) => s.kind !== "error").at(-1);+ const where = last ? `${last.cut || last.status === "running" ? "卡在" : "最后一步"}:${clipLine(describeStep(last))}。` : "";+ if (err instanceof TurnStopped) {+ if (err.reason === "user") return `已中止(处理了 ${fmtSecs(err.ms)})。代理进程已重启,可以继续发消息。`;+ if (err.reason === "idle") return `⚠️ 代理 ${fmtSecs(err.ms)}没有任何进展,已自动中止并重启代理进程。${where}可以重新发送,或用 /model 换个模型试试。`;+ return `⚠️ 这条消息处理超过了 ${fmtSecs(err.ms)}的上限,已中止并重启代理进程。${where}可以把任务拆小一点再发。`;+ }+ if (/runtime (closed|exited)/i.test(err.message)) return "⚠️ 代理进程重启了(可能是同一机器人的另一个会话中止了卡住的消息),这条消息没有处理完,请重新发送。";+ return `⚠️ 代理执行失败:${err.message.slice(0, 300)}`;+}diff --git a/src/core/types.ts b/src/core/types.tsindex 280324d..c09c425 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2,6 +2,8 @@* 统一消息/事件模型:渠道把平台消息归一化成 InboundEvent,* 运行时只产出 OutboundOp,由渠道按自身能力(ChannelCapabilities)落地或降级。*/+import type { ActivityStep } from "../agent/activity.js";+export type ChannelId = "feishu" | "weixin" | "web";export type Part =@@ -44,6 +46,8 @@ export type OutboundOp =| { type: "stream.update"; text: string }| { type: "stream.finish"; text: string }| { type: "text"; text: string }+ /** 代理回合的一步(新增或更新,按 id):只有网页对话显示,其它渠道忽略 */+ | { type: "activity"; step: ActivityStep }/** 代理交付的本地文件(present):微信走 CDN 媒体消息,飞书上传文件/图片,网页列出文件名 */| { type: "file"; path: string; name: string }/**diff --git a/src/store/db.ts b/src/store/db.tsindex ed50aae..ade3886 100644--- a/src/store/db.ts+++ b/src/store/db.ts@@ -41,6 +41,8 @@ export interface Message {role: "system" | "user" | "assistant";content: string;createdAt: number;+ /** 代理回合的活动记录有几步(内容按需用 getActivity 取) */+ steps?: number;}export interface WeixinAccount {@@ -130,6 +132,8 @@ CREATE TABLE IF NOT EXISTS agent_segments (const COLUMNS: Array<[string, string, string]> = [["bots", "settings", "TEXT NOT NULL DEFAULT '{}'"],["conversations", "kind", "TEXT NOT NULL DEFAULT 'dm'"],+ // 代理回合的活动记录(JSON 数组,见 agent/activity.ts);只在助手消息上+ ["messages", "activity", "TEXT NOT NULL DEFAULT ''"],];export class Store {@@ -294,17 +298,19 @@ export class Store {}// ---------- messages ----------- addMessage(conversationId: string, role: Message["role"], content: string): number {+ addMessage(conversationId: string, role: Message["role"], content: string, activity?: unknown[]): number {const now = Date.now();const res = this.db- .prepare("INSERT INTO messages(conversation_id, role, content, created_at) VALUES(?, ?, ?, ?)")- .run(conversationId, role, content, now);+ .prepare("INSERT INTO messages(conversation_id, role, content, created_at, activity) VALUES(?, ?, ?, ?, ?)")+ .run(conversationId, role, content, now, activity?.length ? JSON.stringify(activity) : "");this.db.prepare("UPDATE conversations SET updated_at = ? WHERE id = ?").run(now, conversationId);return Number(res.lastInsertRowid);}listMessages(conversationId: string, limit = 500): Message[] {const rows = this.db- .prepare("SELECT * FROM (SELECT * FROM messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?) ORDER BY id ASC")+ .prepare(+ "SELECT * FROM (SELECT id, conversation_id, role, content, created_at, CASE WHEN json_valid(activity) THEN json_array_length(activity) ELSE 0 END AS steps FROM messages WHERE conversation_id = ? ORDER BY id DESC LIMIT ?) ORDER BY id ASC",+ ).all(conversationId, limit) as Row[];return rows.map((r) => ({id: Number(r.id),@@ -312,8 +318,18 @@ export class Store {role: String(r.role) as Message["role"],content: String(r.content),createdAt: Number(r.created_at),+ ...(Number(r.steps) ? { steps: Number(r.steps) } : {}),}));}+ /** 一条消息的活动记录(没有则为空数组) */+ getActivity(conversationId: string, messageId: number): unknown[] {+ const r = this.db.prepare("SELECT activity FROM messages WHERE id = ? AND conversation_id = ?").get(messageId, conversationId) as Row | undefined;+ try {+ return r?.activity ? (JSON.parse(String(r.activity)) as unknown[]) : [];+ } catch {+ return [];+ }+ }clearMessages(conversationId: string): void {this.db.prepare("DELETE FROM messages WHERE conversation_id = ?").run(conversationId);}diff --git a/src/web/server.ts b/src/web/server.tsindex 0136465..b7fe14d 100644--- a/src/web/server.ts+++ b/src/web/server.ts@@ -445,6 +445,18 @@ export async function startWebServer(app: App, opts: { port?: number; host?: strif (!conv) throw new HttpError(404, "会话不存在");return send(res, 200, { conversation: conv, messages: app.store.listMessages(conv.id) });}+ // 一条回复的代理活动记录(展开时才取)+ if (seg.length === 5 && seg[2] === "messages" && seg[4] === "activity" && m === "GET") {+ return send(res, 200, { steps: app.store.getActivity(decodeURIComponent(seg[1]), Number(seg[3])) });+ }+ // 正在处理的回合:处理了多久、最近一次进展、到目前为止的步骤(信息面板轮询)+ if (seg.length === 3 && seg[2] === "turn" && m === "GET") {+ const t = app.agent.turnsInProgress.get(decodeURIComponent(seg[1]));+ return send(res, 200, { turn: t ? { since: t.since, lastProgress: t.lastProgress, steps: t.activity.steps } : null });+ }+ if (seg.length === 3 && seg[2] === "stop" && m === "POST") {+ return send(res, 200, { stopped: app.agent.stopTurn(decodeURIComponent(seg[1])) });+ }}if (seg[0] === "bots") {if (seg.length === 1) {diff --git a/src/web/sse-reply.ts b/src/web/sse-reply.tsindex 5caf41f..9116ac8 100644--- a/src/web/sse-reply.ts+++ b/src/web/sse-reply.ts@@ -3,7 +3,7 @@ import type { OutboundOp, ReplySession } from "../core/types.js";/*** 网页对话渠道:把运行时的 OutboundOp 写成 text/event-stream。- * 事件:text(到目前为止的完整回复,覆盖式)、typing、prompt(审批/提问)、file、done、error。+ * 事件:text(到目前为止的完整回复,覆盖式)、typing、prompt(审批/提问)、file、activity(代理的一步,按 id 覆盖)、done、error。* 运行时的 stream.update 本身就是累计文本,所以前端只需整体替换,不用拼接增量。*/export class SseReply implements ReplySession {@@ -53,6 +53,8 @@ export class SseReply implements ReplySession {return this.send("file", { name: op.name });case "interactive":return this.send("prompt", { kind: op.kind, prompt: op.prompt, requestId: op.requestId, code: op.code });+ case "activity":+ return this.send("activity", op.step);}}diff --git a/test/activity.unit.test.ts b/test/activity.unit.test.tsnew file mode 100644index 0000000..3e335e4--- /dev/null+++ b/test/activity.unit.test.ts@@ -0,0 +1,130 @@+/** 代理回合的活动记录:DSH 事件 → 步骤;/status、排队提示、中止消息里的说法。 */+import { describe, it, expect } from "vitest";+import { ActivityLog, describeStep, fmtSecs, type ActivityStep } from "../src/agent/activity.js";+import { TurnStopped } from "../src/agent/host.js";+import { busyLine, turnFailedText } from "../src/core/runtime.js";++const T0 = 1_800_000_000_000;++/** 一轮真实形状的事件(取自 DSH 的 session.event):模型要求跑 bash → 工具结果 → 模型作答 */+function toolTurn(log: ActivityLog) {+ log.apply("turn/start", { turn: 1 }, T0);+ log.apply("step/start", { turn: 1, step: 1 }, T0 + 10);+ expect(log.last!.title).toBe("模型");+ log.apply("request/context", { provider: "magpie", model: "grok-4.7", contextWindow: 128000 }, T0 + 20);+ expect(log.last!.title).toBe("grok-4.7");+ log.apply(+ "assistant/message",+ {+ turn: 1,+ step: 1,+ message: { role: "assistant", content: [{ type: "reasoning", text: "先看看目录" }, { type: "tool-call", id: "call_1", name: "bash", arguments: '{"description":"list","command":"ls -la\\n src"}' }], source: { model: "grok-4.7" } },+ usage: { inputTokens: 1200, outputTokens: 30 },+ },+ T0 + 2010,+ );+ log.apply("tool/call", { turn: 1, step: 1, callId: "call_1", name: "bash", arguments: '{"description":"list","command":"ls -la\\n src"}' }, T0 + 2020);+ log.apply("job/registered", { jobId: "j" }, T0 + 2030);+ log.apply("tool/result", { turn: 1, step: 1, message: { toolCallId: "call_1", content: [{ type: "text", text: "a.ts\nb.ts\n" }], isError: false } }, T0 + 2520);+ log.apply("step/end", { turn: 1, step: 1 }, T0 + 2530);+ log.apply("step/start", { turn: 1, step: 2 }, T0 + 2540);+ log.apply("assistant/message", { turn: 1, step: 2, message: { role: "assistant", content: [{ type: "text", text: "两个文件:\na.ts 和 b.ts" }], source: { model: "grok-4.7" } }, usage: { inputTokens: 1300, outputTokens: 12 } }, T0 + 3540);+ log.apply("turn/end", { turn: 1, reason: { kind: "completed" } }, T0 + 3550);+}++describe("ActivityLog", () => {+ it("folds a tool turn into model / tool / model steps with timings, tokens, args and output", () => {+ const changes: ActivityStep[] = [];+ const log = new ActivityLog((s) => changes.push(s));+ toolTurn(log);+ expect(log.steps.map((s) => [s.kind, s.title, s.status, s.ms])).toEqual([+ ["model", "grok-4.7", "ok", 2000],+ ["tool", "bash", "ok", 500],+ ["model", "grok-4.7", "ok", 1000],+ ]);+ const [m1, tool, m2] = log.steps;+ expect(m1).toMatchObject({ summary: "调用 bash", tokens: { input: 1200, output: 30 } });+ expect(m1.output).toContain("[思考]\n先看看目录");+ expect(tool).toMatchObject({ id: "call_1", summary: "ls -la src", output: "a.ts\nb.ts\n" });+ expect(JSON.parse(tool.input!)).toEqual({ description: "list", command: "ls -la\n src" });+ expect(m2.summary).toBe("两个文件: a.ts 和 b.ts");+ // 每次新增或更新都通知一次,拿到的是副本+ expect(changes.filter((s) => s.id === "call_1").map((s) => s.status)).toEqual(["running", "ok"]);+ changes[0].title = "changed";+ expect(log.steps[0].title).toBe("grok-4.7");+ });++ it("progress: retries are not progress (the watchdog keeps counting); everything else is", () => {+ const log = new ActivityLog();+ expect(log.apply("step/start", { turn: 1, step: 1 }, T0)).toBe(true);+ expect(log.apply("llm/retry", { retryId: "r1", turn: 1, step: 1, retry: 2, maxRetries: 5, delayMs: 4000, failure: { code: "rate_limited", message: "HTTP 429 Too Many Requests" } }, T0 + 5)).toBe(false);+ expect(log.apply("llm/retry-started", { retryId: "r1", retry: 2 }, T0 + 4005)).toBe(false);+ expect(log.last).toMatchObject({ kind: "retry", status: "error", summary: "第 2/5 次,4 秒后:HTTP 429 Too Many Requests" });+ expect(describeStep(log.last!)).toBe("模型请求失败,正在重试(第 2/5 次,4 秒后:HTTP 429 Too Many Requests)");+ expect(log.apply("agent/inbox/spliced", {}, T0 + 4010)).toBe(true);+ });++ it("turn errors and external stops close the running steps", () => {+ const log = new ActivityLog();+ log.apply("step/start", { turn: 3, step: 1 }, T0);+ log.apply("tool/call", { callId: "c", name: "read", arguments: '{"file_path":"x.md"}' }, T0 + 10);+ log.apply("turn/end", { turn: 3, reason: { kind: "error", error: { message: "HTTP 400 image input not supported" } } }, T0 + 50);+ expect(log.steps.map((s) => [s.kind, s.status])).toEqual([["model", "error"], ["tool", "error"], ["error", "error"]]);+ expect(log.last!.summary).toBe("HTTP 400 image input not supported");++ const stopped = new ActivityLog();+ stopped.apply("step/start", { turn: 1, step: 1 }, T0);+ stopped.end("用户中止", T0 + 90_000);+ expect(stopped.steps).toMatchObject([{ kind: "model", status: "error", cut: true, ms: 90_000 }, { kind: "error", title: "已中止", summary: "用户中止" }]);+ expect(describeStep(stopped.steps[0])).toBe("等待 模型 回复");+ });++ it("subagents and compaction become their own steps; unknown tool results are ignored", () => {+ const log = new ActivityLog();+ log.apply("subagent/started", { parentSessionId: "p", childSessionId: "k" }, T0);+ log.apply("compaction/start", {}, T0 + 1);+ log.apply("compaction/end", {}, T0 + 101);+ log.apply("subagent/finished", { childSessionId: "k", status: "ok", stopReason: "completed", lastAssistantMessage: [{ type: "text", text: "查完了" }] }, T0 + 500);+ log.apply("tool/result", { message: { toolCallId: "nope", content: [] } }, T0 + 600);+ expect(log.steps.map((s) => [s.kind, s.status, s.ms, s.summary])).toEqual([+ ["subagent", "ok", 500, "查完了"],+ ["compact", "ok", 100, undefined],+ ]);+ });++ it("keeps the newest steps and clips long arguments and output", () => {+ const log = new ActivityLog();+ for (let i = 0; i < 130; i++) log.apply("tool/call", { callId: `c${i}`, name: "bash", arguments: JSON.stringify({ command: "x".repeat(5000) }) }, T0 + i);+ log.apply("tool/result", { message: { toolCallId: "c129", content: [{ type: "text", text: "y".repeat(10_000) }] } }, T0 + 200);+ expect(log.steps).toHaveLength(120);+ expect(log.steps[0].id).toBe("c10");+ expect(log.last!.input!.length).toBeLessThanOrEqual(1000);+ expect(log.last!.output!.length).toBeLessThanOrEqual(2000);+ expect(log.last!.summary!.length).toBeLessThanOrEqual(120);+ });+});++describe("what the user is told", () => {+ const step = (s: Partial<ActivityStep>): ActivityStep => ({ id: "x", kind: "tool", title: "bash", status: "running", at: Date.now(), ...s });++ it("fmtSecs", () => {+ expect([fmtSecs(400), fmtSecs(12_000), fmtSecs(180_000), fmtSecs(1_315_000)]).toEqual(["0 秒", "12 秒", "3 分钟", "21 分 55 秒"]);+ });++ it("/status busy line: how long, how many steps, what it is doing now, how long without progress", () => {+ const now = Date.now();+ const line = busyLine(now - 1_315_000, now - 400_000, [step({ kind: "model", title: "grok-4.7", status: "ok" }), step({ summary: "npm test", at: now - 400_000 })]);+ expect(line).toBe("本会话上一条消息还在处理(已 21 分 55 秒,2 步,现在:正在运行 bash:npm test,6 分 40 秒没有新进展),新消息会排在它后面。发送 /stop 可以中止");+ expect(busyLine(now - 5_000, 0, [])).toBe("本会话上一条消息还在处理(已 5 秒,还在等代理进程接手),新消息会排在它后面。发送 /stop 可以中止");+ });++ it("stopped / idle / timeout / restarted / other failures", () => {+ const steps = [step({ kind: "model", title: "grok-4.7", status: "error", cut: true }), step({ kind: "error", title: "已中止", status: "error" })];+ expect(turnFailedText(new TurnStopped("user", 95_000), steps)).toBe("已中止(处理了 1 分 35 秒)。代理进程已重启,可以继续发消息。");+ expect(turnFailedText(new TurnStopped("idle", 600_000), steps)).toBe("⚠️ 代理 10 分钟没有任何进展,已自动中止并重启代理进程。卡在:等待 grok-4.7 回复。可以重新发送,或用 /model 换个模型试试。");+ expect(turnFailedText(new TurnStopped("timeout", 1_800_000), [step({ summary: "npm test", status: "ok" })])).toBe("⚠️ 这条消息处理超过了 30 分钟的上限,已中止并重启代理进程。最后一步:bash:npm test(完成)。可以把任务拆小一点再发。");+ expect(turnFailedText(new TurnStopped("timeout", 1_800_000), [])).toBe("⚠️ 这条消息处理超过了 30 分钟的上限,已中止并重启代理进程。可以把任务拆小一点再发。");+ expect(turnFailedText(new Error("DeepSeek Harness runtime closed"), [])).toMatch(/^⚠️ 代理进程重启了/);+ expect(turnFailedText(new Error("boom"), [])).toBe("⚠️ 代理执行失败:boom");+ });+});diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.tsindex 8d25f26..bdef5cf 100644--- a/test/agent.integration.test.ts+++ b/test/agent.integration.test.ts@@ -43,16 +43,19 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent holet dataDir: string;let llm: Awaited<ReturnType<typeof listen>>;const seenAuth = new Set<string>();+ const hung: http.ServerResponse[] = [];let base = "";/** 根据最后一条用户消息与之后的工具结果数量决定下一步 */- function plan(messages: any[]): { tool?: { name: string; args: any }; text?: string } {+ function plan(messages: any[]): { tool?: { name: string; args: any }; text?: string; hang?: boolean } {let lastUser = -1;for (let i = messages.length - 1; i >= 0; i--) {- if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }+ if (messages[i].role === "user" && /QUICKSORT|ESCALATE|SECRET|READFILE|LOOPBACK|PRESENT|ASKQ|NATIVES|LOOKIMG|HANG|\[用户消息\]/.test(textOf(messages[i].content))) { lastUser = i; break; }}const user = textOf(messages[lastUser]?.content);const tools = messages.slice(lastUser + 1).filter((m) => m.role === "tool");+ // 卡住的模型:请求收下了,一直不回+ if (/HANG/.test(user)) return { hang: true };// 看图:回报模型收到的图片(data URL 的头)和文字里有没有工作区路径if (/LOOKIMG/.test(user)) {const content = messages[lastUser]?.content;@@ -92,6 +95,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho}const b = await body(req);const step = b.tools ? plan(b.messages) : { text: "标题" };+ if ("hang" in step && step.hang) return void hung.push(res);if (process.env.AMB_TEST_LLM_LOG) fs.appendFileSync(process.env.AMB_TEST_LLM_LOG, JSON.stringify({ url: req.url, stream: b.stream, tools: (b.tools ?? []).map((t: any) => t.function?.name), msgs: b.messages.map((m: any) => [m.role, textOf(m.content).slice(0, 200), m.tool_calls?.map((t: any) => t.function?.name)]), step }) + "\n");if (!b.stream) {res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ choices: [{ message: { role: "assistant", content: step.text ?? "" }, finish_reason: "stop" }] }));@@ -120,6 +124,7 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho}, 60_000);afterAll(async () => {+ for (const r of hung) r.destroy();await app?.stop();await llm?.close();fs.rmSync(dataDir, { recursive: true, force: true });@@ -270,4 +275,56 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent hoexpect(inbox.filter((f) => /^\d{8}-\d{6}-[0-9a-f]{6}\.png$/.test(f))).toHaveLength(2);expect(fs.readFileSync(path.join(dataDir, "workspaces", "default", "inbox", inbox[0])).equals(png)).toBe(true);}, 180_000);++ // —— 卡住的回合:看门狗、/stop、处理过程 ——+ const console_ = async () => (await (await fetch(`${base}/amb/api/bots/default/chat`)).json()) as { conversationId: string; messages: any[] };+ const api = async (p: string, init?: RequestInit) => (await fetch(`${base}/amb/api${p}`, init)).json();++ it("a turn without progress is stopped by the watchdog: the agent restarts and the reply keeps its steps", async () => {+ const o = (app.agent as any).o;+ const prev = o.idleTimeoutMs;+ o.idleTimeoutMs = 3000;+ try {+ const t0 = Date.now();+ const r = await chat("HANG please");+ expect(r.reply).toBe("⚠️ 代理 3 秒没有任何进展,已自动中止并重启代理进程。卡在:等待 mock-agent 回复。可以重新发送,或用 /model 换个模型试试。");+ expect(Date.now() - t0).toBeLessThan(30_000);+ } finally {+ o.idleTimeoutMs = prev;+ }+ const d = await console_();+ const last = d.messages.at(-1);+ expect(last.steps).toBe(2);+ const a = await api(`/conversations/${encodeURIComponent(d.conversationId)}/messages/${last.id}/activity`);+ expect(a.steps.map((s: any) => [s.kind, s.title, s.status, !!s.cut])).toEqual([["model", "mock-agent", "error", true], ["error", "已中止", "error", false]]);+ expect((await chat("/reset")).reply).toMatch(/已清空/);+ expect((await chat("hello again")).reply).toBe("好的");+ }, 120_000);++ it("/stop ends a stuck turn right away; status and the info panel show where it is", async () => {+ const conv = encodeURIComponent((await console_()).conversationId);+ const pending = chat("HANG again");+ let turn: any = null;+ for (let i = 0; i < 200 && !turn?.steps?.length; i++) {+ await new Promise((r) => setTimeout(r, 100));+ turn = (await api(`/conversations/${conv}/turn`)).turn;+ }+ expect(turn.steps.at(-1)).toMatchObject({ kind: "model", title: "mock-agent", status: "running" });+ expect((await chat("/status")).reply).toMatch(/本会话上一条消息还在处理(已 \d+ 秒,1 步,现在:等待 mock-agent 回复),新消息会排在它后面。发送 \/stop 可以中止/);+ expect((await chat("/stop")).reply).toMatch(/^正在中止上一条消息(已处理 \d+ 秒)…$/);+ expect((await pending).reply).toMatch(/^已中止(处理了 \d+ 秒)。代理进程已重启,可以继续发消息。$/);+ expect((await api(`/conversations/${conv}/turn`)).turn).toBeNull();+ expect((await chat("/stop")).reply).toBe("当前没有正在处理的消息。");+ expect((await chat("/reset")).reply).toMatch(/已清空/);+ expect((await chat("hello once more")).reply).toBe("好的");+ }, 120_000);++ it("a normal agent reply records its model and tool steps", async () => {+ const r = await chat("QUICKSORT again");+ expect(r.reply).toContain("[1, 2, 3, 5, 7, 9]");+ const d = await console_();+ const a = await api(`/conversations/${encodeURIComponent(d.conversationId)}/messages/${d.messages.at(-1).id}/activity`);+ expect(a.steps.map((s: any) => [s.kind, s.status])).toEqual([["model", "ok"], ["tool", "ok"], ["model", "ok"]]);+ expect(a.steps[1]).toMatchObject({ title: "bash", output: expect.stringContaining("[1, 2, 3, 5, 7, 9]") });+ }, 120_000);});diff --git a/ui/components/activity.js b/ui/components/activity.jsnew file mode 100644index 0000000..f9bb0bf--- /dev/null+++ b/ui/components/activity.js@@ -0,0 +1,99 @@+// 代理活动明细:回复上方那一行("思考中 / 用时")可以展开,默认折叠。展开后是这一轮的步骤——+// 模型请求、工具调用、重试、子代理、压缩上下文——每步一行:状态点 + 名称 + 等宽摘要 + 用时;+// 有参数或输出的步骤再点开看全文。对话页实时显示,信息面板里看微信 / 飞书会话的历史与正在处理的回合。+import { useEffect, useState } from "preact/hooks";+import { html, Icon } from "./ui.js";+import { fmtDur } from "../lib/format.js";++const KIND_ICON = { model: "spark", tool: "code", retry: "refresh", subagent: "chat", compact: "database", error: "alert" };+const DOT = { ok: "ok", error: "err", running: "warn" };++/** 步骤用时:不到 1 秒显示一位小数 */+const stepDur = (ms) => (ms < 100 ? "<0.1 秒" : ms < 1000 ? `${(ms / 1000).toFixed(1)} 秒` : fmtDur(ms));+const kTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}k` : String(n));++/** 正在进行的那一步,用在工作状态行上:"运行 bash" / "等待 grok-4.7 回复" */+export function currentStep(steps) {+ const s = (steps || []).findLast((x) => x.status === "running");+ if (!s) return "";+ if (s.kind === "model") return `等待 ${s.title} 回复`;+ if (s.kind === "tool") return `运行 ${s.title}`;+ if (s.kind === "subagent") return "子代理在工作";+ if (s.kind === "compact") return "压缩上下文";+ return s.title;+}++/** 按 id 新增或覆盖一步(SSE 的 activity 事件) */+export function upsertStep(steps, step) {+ const list = steps || [];+ const i = list.findIndex((s) => s.id === step.id);+ return i < 0 ? [...list, step] : [...list.slice(0, i), step, ...list.slice(i + 1)];+}++/** 有步骤在进行时每秒刷新一次(用时跟着走) */+export function useNow(on) {+ const [now, setNow] = useState(Date.now());+ useEffect(() => {+ if (!on) return;+ setNow(Date.now());+ const t = setInterval(() => setNow(Date.now()), 1000);+ return () => clearInterval(t);+ }, [on]);+ return now;+}++function Step({ s, now }) {+ const [open, setOpen] = useState(false);+ const more = !!(s.input || s.output || s.tokens);+ const ms = s.status === "running" ? now - s.at : s.ms;+ const head = html`<span class=${`dot ${DOT[s.status] || ""}`} aria-hidden="true"></span>+ <${Icon} name=${KIND_ICON[s.kind] || "info"} size=${14} class="k" />+ <span class="t">${s.kind === "model" && (s.status === "running" || s.cut) ? `等待 ${s.title} 回复` : s.title}</span>+ ${s.summary && html`<span class="s">${s.summary}</span>`}+ <span class="grow"></span>+ ${ms != null && html`<span class=${`d num${s.status === "running" ? " shimmer" : ""}`}>${stepDur(ms)}</span>`}+ ${more && html`<${Icon} name="chevRight" size=${12} class="chev" />`}`;+ const label = `${s.status === "error" ? "失败" : s.status === "running" ? "进行中" : "完成"}:${s.title}`;+ return html`<li class=${`act-step ${s.status}`}>+ ${more+ ? html`<button type="button" class="act-head" aria-expanded=${open} aria-label=${`${label},${open ? "收起" : "展开"}详情`} onClick=${() => setOpen(!open)}>${head}</button>`+ : html`<div class="act-head" aria-label=${label}>${head}</div>`}+ ${open && html`<div class="act-body">+ ${s.tokens && html`<div class="t-label num">输入 ${kTokens(s.tokens.input || 0)} tokens · 输出 ${kTokens(s.tokens.output || 0)} tokens</div>`}+ ${s.input && html`<div class="t-label">参数</div><pre class="selectable">${s.input}</pre>`}+ ${s.output && html`<div class="t-label">${s.kind === "model" ? "回复" : "输出"}</div><pre class="selectable">${s.output}</pre>`}+ </div>`}+ </li>`;+}++/** 步骤列表(一块 --well;步骤之间一条细线) */+export function ActivityList({ steps }) {+ const now = useNow((steps || []).some((s) => s.status === "running"));+ if (!steps?.length) return html`<div class="act-list empty"><span class="hint">还没有步骤</span></div>`;+ return html`<ol class="act-list">${steps.map((s) => html`<${Step} key=${s.id} s=${s} now=${now} />`)}</ol>`;+}++/**+ * 回复上方的工作状态行,可展开成活动明细。+ * live:进行中(label 由调用方给,比如"思考中 12 秒");steps:已有的步骤;count + load:历史消息只知道有几步,展开时再取。+ */+export function ActivityLine({ label, live, steps, count = 0, load }) {+ const [open, setOpen] = useState(false);+ const [loaded, setLoaded] = useState(null);+ const [err, setErr] = useState("");+ const list = steps || loaded;+ const n = list?.length || count;+ useEffect(() => {+ if (!open || list || !load) return;+ load().then(setLoaded, (e) => setErr(e.message));+ }, [open]);+ const text = html`<span class=${live ? "shimmer" : ""}>${label}</span>`;+ if (!n && !live) return html`<div class="work-line">${text}</div>`;+ if (!n) return html`<div class="work-line live" aria-live="off">${text}</div>`;+ return html`<div class=${`activity${open ? " open" : ""}`}>+ <button type="button" class=${`work-line toggle${live ? " live" : ""}`} aria-expanded=${open} aria-live="off" title=${open ? "收起处理过程" : "查看处理过程"} onClick=${() => setOpen(!open)}>+ ${text}<span class="steps num">${n} 步</span><${Icon} name="chevRight" size=${12} class="chev" />+ </button>+ ${open && (list ? html`<${ActivityList} steps=${list} />` : html`<div class="act-list empty"><span class="hint">${err || "加载中…"}</span></div>`)}+ </div>`;+}diff --git a/ui/css/chat.css b/ui/css/chat.cssindex 224247e..f7964e5 100644--- a/ui/css/chat.css+++ b/ui/css/chat.css@@ -79,6 +79,38 @@ button.head-bot:active { background: var(--pill-press); }}.work-line.live { border-bottom-color: transparent; }.msg-row.assistant .work-line:last-child { margin-bottom: 0; }++/* 处理过程(代理回合):工作状态行可以展开,默认折叠;展开后是一块 --well,步骤之间一条 --line-2。+ 每步一行:状态点 + 类别图标 + 名称 + 等宽摘要 + 用时;有参数或输出的步骤再点开看全文 */+.work-line.toggle { width: 100%; text-align: left; transition: color var(--t-fast); }+.work-line.toggle:hover { color: var(--fg); }+.work-line .steps { color: var(--muted); }+.work-line .steps::before { content: "·"; margin-right: var(--space-1-5); }+.work-line .chev, .act-head .chev { flex: none; transition: transform var(--t-fast); }+[aria-expanded="true"] > .chev { transform: rotate(90deg); }+.activity { display: grid; grid-template-columns: minmax(0, 1fr); }+.activity.open > .work-line { border-bottom-color: transparent; margin-bottom: var(--space-2); }+.msg-row.assistant .activity + .notice { margin-top: var(--space-1); }+.act-list { list-style: none; margin: 0 0 var(--space-3); padding: var(--space-1) 0; background: var(--well); border-radius: var(--r-well); font-size: var(--fs-sm); }+.act-list.empty { padding: var(--space-2-5) var(--space-3); }+.act-step + .act-step { border-top: 1px solid var(--line-2); }+.act-head {+ display: flex; align-items: center; gap: var(--space-2); width: 100%; min-height: var(--ctl-md);+ padding: var(--space-1) var(--space-3); color: var(--fg-2); text-align: left;+}+button.act-head { --focus-offset: -2px; transition: background var(--t-fast); }+button.act-head:hover { background: var(--pill); }+button.act-head:active { background: var(--pill-hover); }+.act-head .k { flex: none; color: var(--muted); }+.act-head .t { flex: none; max-width: 40%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--fg); font-weight: var(--fw-medium); }+.act-head .s { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--code); font-size: var(--fs-xs); color: var(--muted); }+.act-head .d { flex: none; font-size: var(--fs-xs); color: var(--muted); }+.act-body { display: grid; gap: var(--space-1); padding: 0 var(--space-3) var(--space-2-5); }+.act-body .t-label { margin-top: var(--space-1); }+.act-body pre {+ margin: 0; max-height: 240px; overflow: auto; font: var(--fs-xs)/var(--lh-relaxed) var(--code);+ color: var(--fg); white-space: pre-wrap; overflow-wrap: anywhere;+}.shimmer {color: transparent;background: linear-gradient(90deg, var(--muted) 0%, var(--muted) 40%, var(--faint) 50%, var(--muted) 60%, var(--muted) 100%) 0 0 / 300% 100%;diff --git a/ui/css/shell.css b/ui/css/shell.cssindex 2f5db7c..2663aed 100644--- a/ui/css/shell.css+++ b/ui/css/shell.css@@ -195,6 +195,12 @@ button.thread:active { background: var(--side-press); }.transcript-msg.user .bubble { background: var(--bubble-user); }.transcript-msg .hint { margin-top: var(--space-0-5); }.transcript-msg.user .hint { text-align: right; }+/* 回复的处理过程和正在处理的那一轮:占满预览宽度,展开的步骤才放得下命令和输出 */+.transcript-msg:has(> .activity) { justify-self: stretch; max-width: none; }+.transcript-msg:has(> .activity) .bubble { justify-self: start; max-width: 85%; }+.transcript-msg { display: grid; }+.transcript-turn { display: grid; gap: var(--space-1); }+.transcript .work-line { font-size: var(--fs-sm); }.panel-scrim { display: none; }/* narrow window: the panel floats over the chat as a glass drawer over a scrim */diff --git a/ui/screens/chat.js b/ui/screens/chat.jsindex 64a8b39..5e63136 100644--- a/ui/screens/chat.js+++ b/ui/screens/chat.js@@ -6,6 +6,7 @@ import { BotAvatar } from "../components/avatar.js";import { Markdown, Linkified } from "../components/markdown.js";import { ModelPicker, shortModel, sameModel } from "../components/model-picker.js";import { PwshHint } from "../components/pwsh-hint.js";+import { ActivityLine, currentStep, upsertStep } from "../components/activity.js";import { api, streamChat } from "../lib/api.js";import { confirmSheet, failed, saved } from "../lib/store.js";import { fmtSep, fmtClock, fmtDur } from "../lib/format.js";@@ -14,7 +15,8 @@ const COMMANDS = [["/model", "列出或切换模型"],["/new", "开始新的一段对话(旧对话归档并留交接便条)"],["/reset", "清空本会话上下文"],- ["/status", "查看当前模型与运行方式"],+ ["/status", "查看当前模型、运行方式和处理进度"],+ ["/stop", "中止正在处理的消息"],["/help", "显示全部命令"],];// 文件权限(输入框左下角,参考 Codex 的权限胶囊):机器人设置里的同一项@@ -31,11 +33,12 @@ const isError = (t) => typeof t === "string" && t.startsWith("⚠️");const errText = (t) => t.replace(/^⚠️\s*/, "");const isAuthError = (t) => /HTTP 401\b|\b401\b.*(key|密钥|unauthor)/i.test(t);+// steps:代理回合的活动记录有几步(展开时按 mid 取)function toItems(messages) {return messages.map((m) =>m.role === "assistant" && isError(m.content)- ? { kind: "error", id: "m" + m.id, text: errText(m.content), at: m.createdAt }- : { kind: "msg", id: "m" + m.id, role: m.role === "user" ? "user" : "assistant", text: m.content, at: m.createdAt },+ ? { kind: "error", id: "m" + m.id, mid: m.id, text: errText(m.content), at: m.createdAt, steps: m.steps }+ : { kind: "msg", id: "m" + m.id, mid: m.id, role: m.role === "user" ? "user" : "assistant", text: m.content, at: m.createdAt, steps: m.steps },);}@@ -144,8 +147,11 @@ function FileCard({ name }) {</div>`;}-/** 回复上方的工作状态:没出字时"思考中",出字后"正在回复 N 秒",结束后"用时 N 秒"(短于 3 秒不显示) */-function WorkLine({ live, text, startedAt, workedMs }) {+/**+ * 回复上方的工作状态:没出字时"思考中 · 正在做的那一步",出字后"正在回复 N 秒",结束后"用时 N 秒"(短于 3 秒且没有步骤时不显示)。+ * 代理回合有步骤时这一行可以展开成处理过程(默认折叠);历史消息只知道步数,展开时用 load 取。+ */+function WorkLine({ live, text, startedAt, workedMs, steps, count, load }) {const [, tick] = useState(0);useEffect(() => {if (!live) return;@@ -153,9 +159,12 @@ function WorkLine({ live, text, startedAt, workedMs }) {return () => clearInterval(t);}, [live]);const ms = live ? Date.now() - startedAt : workedMs;- if (!live && !(ms >= 3000)) return null;- const label = live ? (text ? `正在回复 ${fmtDur(ms)}` : ms >= 3000 ? `思考中 ${fmtDur(ms)}` : "思考中") : `用时 ${fmtDur(ms)}`;- return html`<div class=${`work-line${live ? " live" : ""}`} aria-live="off"><span class=${live ? "shimmer" : ""}>${label}</span></div>`;+ if (!live && !(ms >= 3000) && !steps?.length && !count) return null;+ const cur = live && !text ? currentStep(steps) : "";+ const label = live+ ? `${text ? `正在回复 ${fmtDur(ms)}` : ms >= 3000 ? `思考中 ${fmtDur(ms)}` : "思考中"}${cur ? ` · ${cur}` : ""}`+ : ms >= 3000 ? `用时 ${fmtDur(ms)}` : "处理过程";+ return html`<${ActivityLine} label=${label} live=${live} steps=${steps} count=${count} load=${load} />`;}/** 消息下方的操作:复制 + 时刻(悬停时出现,最后一条回复常显) */@@ -192,11 +201,13 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeconst ctrl = useRef(null);const mounted = useRef(true);const lastUser = useRef("");+ const convId = useRef("");const load = useCallback(async () => {try {const d = await api(`/bots/${encodeURIComponent(bot.id)}/chat`);if (!mounted.current) return;+ convId.current = d.conversationId || "";setConvModel(d.model || "");const list = toItems(d.messages || []);for (const a of d.pending || []) list.push({ kind: "prompt", id: "p" + a.id, requestId: a.id, prompt: "" });@@ -272,6 +283,7 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModefinalText = d.text;patchLive(liveId, (it) => ({ ...it, text: d.text }));},+ activity: (d) => patchLive(liveId, (it) => ({ ...it, activity: upsertStep(it.activity, d) })),prompt: (d) => mounted.current && setItems((l) => {const i = l.findIndex((x) => x.id === liveId);const card = { kind: "prompt", id: uid(), requestId: d.requestId, prompt: d.prompt };@@ -296,17 +308,21 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeconst out = [];for (const it of l || []) {if (it.id !== liveId) out.push(it);- else if (isError(finalText)) out.push({ kind: "error", id: liveId, text: errText(finalText), retry: t.startsWith("/") ? undefined : t, at: it.at });- else if (finalText) out.push({ ...it, text: finalText, live: false, workedMs: Date.now() - it.startedAt });+ else if (isError(finalText)) out.push({ kind: "error", id: liveId, text: errText(finalText), retry: t.startsWith("/") ? undefined : t, at: it.at, activity: it.activity, workedMs: Date.now() - it.startedAt });+ else if (finalText || it.activity?.length) out.push({ ...it, text: finalText, live: false, workedMs: Date.now() - it.startedAt });}return isReset && !isError(finalText) ? out.filter((x) => x.id === liveId) : out;});if (/^\/model\s+\S/i.test(t)) load();};+ // 停止:代理回合在服务端中止(会重启代理进程),回复流照常收到"已中止"再结束;纯对话直接断开请求const stop = () => {- ctrl.current?.abort();+ const agentTurn = (items || []).some((x) => x.live && x.activity?.length);+ if (convId.current) api(`/conversations/${encodeURIComponent(convId.current)}/stop`, { method: "POST" }).catch(() => {});+ if (!agentTurn) ctrl.current?.abort();};+ const loadActivity = (mid) => () => api(`/conversations/${encodeURIComponent(convId.current)}/messages/${mid}/activity`).then((d) => d.steps);// —— 斜杠命令菜单 ——const slashQuery = /^\/\S*$/.test(text) && !slashOff ? text.toLowerCase() : null;@@ -415,7 +431,8 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultModeout.push(html`<div class=${`${cls}${it.id === lastAi ? " last" : ""}`} key=${it.id}>${it.role === "user"? html`<div class="msg"><${Linkified} text=${it.text} /></div><${MsgActions} text=${it.text} at=${it.at} />`- : html`${(it.live || it.workedMs) && html`<${WorkLine} live=${it.live} text=${it.text} startedAt=${it.startedAt} workedMs=${it.workedMs} />`}+ : html`${(it.live || it.workedMs || it.steps) && html`<${WorkLine} live=${it.live} text=${it.text} startedAt=${it.startedAt} workedMs=${it.workedMs}+ steps=${it.activity} count=${it.steps} load=${it.mid ? loadActivity(it.mid) : undefined} />`}${it.text && html`<div class="msg"><${Markdown} text=${it.text} /></div>`}${!it.live && html`<${MsgActions} text=${it.text} at=${it.at} />`}`}</div>`);@@ -424,7 +441,10 @@ export function ChatScreen({ bot, models, modelsError, reloadModels, defaultMode} else if (it.kind === "file") {out.push(html`<div class=${cls} key=${it.id}><${FileCard} name=${it.name} /></div>`);} else if (it.kind === "error") {- out.push(html`<div class=${cls} key=${it.id}><${ErrorNotice} text=${it.text} onRetry=${it.retry ? () => send(it.retry) : undefined} onFixKey=${() => onOpenSettings("modelflare", "connection")} /></div>`);+ out.push(html`<div class=${cls} key=${it.id}>+ ${(it.activity?.length || it.steps) && html`<${WorkLine} workedMs=${it.workedMs} steps=${it.activity} count=${it.steps} load=${it.mid ? loadActivity(it.mid) : undefined} />`}+ <${ErrorNotice} text=${it.text} onRetry=${it.retry ? () => send(it.retry) : undefined} onFixKey=${() => onOpenSettings("modelflare", "connection")} />+ </div>`);}prev = it;}diff --git a/ui/screens/info-panel.js b/ui/screens/info-panel.jsindex 5d56e7c..791c130 100644--- a/ui/screens/info-panel.js+++ b/ui/screens/info-panel.js@@ -1,10 +1,11 @@// 信息面板:点悬浮胶囊或 ⌘⇧I 打开,面板自己的 ✕ 关闭,⚙ 进机器人设置。-import { useCallback, useEffect, useState } from "preact/hooks";-import { html, Icon, Badge, Sheet, Spinner, Skeleton } from "../components/ui.js";+import { useCallback, useEffect, useRef, useState } from "preact/hooks";+import { html, Icon, Badge, Button, Sheet, Spinner, Skeleton } from "../components/ui.js";+import { ActivityLine, currentStep, useNow } from "../components/activity.js";import { PromptCard } from "./chat.js";import { api } from "../lib/api.js";import { confirmSheet, failed, saved, toast } from "../lib/store.js";-import { fmtAgo, fmtTime } from "../lib/format.js";+import { fmtAgo, fmtDur, fmtTime } from "../lib/format.js";export function usePoll(fn, ms, deps = []) {const [data, setData] = useState(null);@@ -126,16 +127,53 @@ function MemorySection({ botId }) {</div>`;}+/** 会话里正在处理的那一轮:处理了多久、多久没进展、现在在做什么(可展开看步骤),以及"中止" */+function LiveTurn({ turn, convId }) {+ const now = useNow(true);+ const [stopping, setStopping] = useState(false);+ const stop = async () => {+ setStopping(true);+ try {+ await api(`/conversations/${encodeURIComponent(convId)}/stop`, { method: "POST" });+ } catch (e) {+ failed(`中止失败:${e.message}`);+ setStopping(false);+ }+ };+ const idle = turn.lastProgress ? now - turn.lastProgress : 0;+ const cur = currentStep(turn.steps);+ const label = `正在处理 ${fmtDur(now - turn.since)}${cur ? ` · ${cur}` : turn.lastProgress ? "" : " · 等代理进程接手"}`;+ return html`<div class="transcript-turn">+ <${ActivityLine} label=${label} live steps=${turn.steps} />+ <div class="cluster">+ ${idle >= 60_000 && html`<span class="hint">${fmtDur(idle)}没有新进展</span>`}+ <span class="grow"></span>+ <${Button} variant="danger" size="sm" loading=${stopping} onClick=${stop}>中止</${Button}>+ </div>+ </div>`;+}+function ConversationSheet({ conv, onClose }) {- const [d] = usePoll(() => api(`/conversations/${encodeURIComponent(conv.id)}/messages`), 0, [conv.id]);+ const enc = encodeURIComponent(conv.id);+ const [d, , reload] = usePoll(() => api(`/conversations/${enc}/messages`), 0, [conv.id]);+ const [t] = usePoll(() => api(`/conversations/${enc}/turn`), 2000, [conv.id]);+ const turn = t?.turn;+ // 那一轮结束了:重新取消息,新回复和它的处理过程出现在列表里+ const busy = useRef(false);+ useEffect(() => {+ if (busy.current && !turn) reload();+ busy.current = !!turn;+ }, [!!turn]);return html`<${Sheet} title=${`${CHANNEL_NAME[conv.channel] || conv.channel} · ${conv.title || conv.peerId}`} wide onClose=${onClose}><div class="transcript">${!d && html`<span class="hint">加载中…</span>`}- ${d && !d.messages.length && html`<span class="hint">没有消息</span>`}+ ${d && !d.messages.length && !turn && html`<span class="hint">没有消息</span>`}${d && d.messages.map((m) => html`<div class=${`transcript-msg${m.role === "user" ? " user" : ""}`}>+ ${m.steps && html`<${ActivityLine} label="处理过程" count=${m.steps} load=${() => api(`/conversations/${enc}/messages/${m.id}/activity`).then((x) => x.steps)} />`}<div class="bubble selectable">${m.content}</div><div class="hint">${fmtTime(m.createdAt)}</div></div>`)}+ ${turn && html`<${LiveTurn} key=${turn.since} turn=${turn} convId=${conv.id} />`}</div><div class="actions"><button type="button" class="btn" data-autofocus onClick=${onClose}>关闭</button></div><//>`;