Skip to content

🤖 Open-source, local-first alternative to Grok Bot, OpenAI dots and Claude Duet. Your own AI bots on any model: GPT, Claude, Gemini, Grok, DeepSeek, Kimi, GLM and 70+ more through one Modelflare key. Reach them in the app, WeChat or Feishu; they remember you, work in the background, run commands and use your computer. Pay per use.

fix(windows): no console storm, no endless "thinking"; app.log and a troubleshooting page

Marla3f7e33057f73
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e3cfc7f..e797a6b 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2,6 +2,8 @@
# Typecheck, unit tests and the TypeScript build. Installers are not built here because the six
# native runners (two of them macOS) cost far more; use the Release workflow's "Run workflow"
# button for a full packaging test.
+# Changes to the agent host, the gateway supervisor, the desktop shell or dsh-runtime also run a
+# Windows end-to-end job (~6 min) with the real DSH host against a mock model.
name: CI
@@ -44,3 +46,92 @@ jobs:
- run: npm run typecheck
- run: npm test
- run: npm run build
+
+ # Does this change touch the agent host, the gateway or the desktop shell? Only then run the
+ # Windows end-to-end job below (it needs a Windows runner and ~6 minutes).
+ changes:
+ name: Agent paths changed?
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ outputs:
+ agent: ${{ steps.diff.outputs.agent }}
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+ fetch-depth: 0
+
+ - id: diff
+ env:
+ BASE: ${{ github.event_name == 'pull_request' && github.event.pull_request.base.sha || github.event.before }}
+ run: |
+ if [ -z "$BASE" ] || ! git cat-file -e "$BASE^{commit}" 2>/dev/null; then
+ echo "agent=true" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ files=$(git diff --name-only "$BASE" HEAD)
+ echo "$files"
+ if echo "$files" | grep -qE '^(src/agent/|src/magpie/|electron/|dsh-runtime/|scripts/prepare-dsh\.mjs$|scripts/e2e-agent\.mjs$|scripts/ci/|\.github/workflows/ci\.yml$)'; then
+ echo "agent=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "agent=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ # Windows end-to-end: the real app (electron .) with the bundled magpie gateway and the real DSH
+ # agent host, "Modelflare" pointed at a scripted mock model. One chat through the UI's SSE path
+ # with a shell tool call, the troubleshooting page's "test model" / "test agent", and no console
+ # window may appear (v0.1.5 flashed a stream of them; see scripts/e2e-agent.mjs).
+ windows-agent-e2e:
+ name: Windows agent e2e (mock model + real DSH host)
+ needs: changes
+ if: needs.changes.outputs.agent == 'true'
+ runs-on: windows-2025
+ timeout-minutes: 20
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Fetch magpie
+ run: git submodule update --init --depth 1 vendor/magpie
+
+ - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
+ with:
+ node-version: "22"
+ cache: npm
+ cache-dependency-path: |
+ package-lock.json
+ dsh-runtime/package-lock.json
+
+ - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
+ with:
+ go-version-file: vendor/magpie/go.mod
+ cache-dependency-path: vendor/magpie/go.sum
+
+ - run: npm ci --no-audit --no-fund
+ - run: npm run build
+ - run: node scripts/prepare-dsh.mjs
+ - run: node scripts/build-magpie.mjs --target windows/amd64
+ - run: node scripts/fetch-cua-driver.mjs --target win32/x64
+
+ # Electron 44 downloads its binary on the first require("electron"), not at npm install time.
+ - name: Fetch the Electron binary
+ run: |
+ exe=$(node -p 'require("electron")' | tail -n 1)
+ test -f "$exe"
+ echo "ELECTRON_EXE=$exe" >> "$GITHUB_ENV"
+
+ # --launch shell: Start-Process without redirection (ShellExecute), so the app has no std
+ # handles, like a Start-menu launch. /status is probed before and during the first turn.
+ - name: Chat through the app; no console windows
+ run: node scripts/e2e-agent.mjs --out "$RUNNER_TEMP/e2e" --launch shell --cwd "$GITHUB_WORKSPACE" --timeout-ms 150000 --procmon --managed --stream --tool --status-probes --observe-ms 20000 --max-console-windows 0 --expect-diagnostics -- "$ELECTRON_EXE" .
+
+ - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
+ if: failure()
+ with:
+ name: windows-agent-e2e
+ path: ${{ runner.temp }}/e2e
+ retention-days: 7
diff --git a/dsh-runtime/plugins/amb-cua-mcp.mjs b/dsh-runtime/plugins/amb-cua-mcp.mjs
index 0e19a65..969685b 100644
--- a/dsh-runtime/plugins/amb-cua-mcp.mjs
+++ b/dsh-runtime/plugins/amb-cua-mcp.mjs
@@ -2,6 +2,8 @@
// anymodel bot: stdio MCP front for the bundled Cua Driver (MIT, part of anymodel bot).
//
// DSH's mcp-client launches this script instead of `cua-driver mcp` directly. It:
+// 0. answers the MCP handshake itself right away and brings the driver up in the background, so
+// the agent's startup never waits for (or crash-loops on) the driver (see createFront),
// 1. asks the bundled binary which tools exist on this platform (`cua-driver list-tools`),
// 2. writes a bounded-mode capability manifest (v3) allowing only our reviewed tool set
// (intersected with what exists; unknown names would make the driver refuse to start),
@@ -12,7 +14,7 @@
// Never passes --dangerously-bypass-approvals; telemetry and update checks are off.
// Config comes from the JSON file named by AMB_CUA_CONFIG (written by the host):
// { bin, manifest, tools: string[], apps: [{executable}|{bundle_id}], display: boolean, direct?: boolean }
-import { spawn, execFileSync } from 'node:child_process'
+import { spawn, execFile } from 'node:child_process'
import fs from 'node:fs'
import readline from 'node:readline'
import { fileURLToPath } from 'node:url'
@@ -21,8 +23,24 @@ const LIFETIME_MS = 23 * 3600_000
const yq = (s) => JSON.stringify(String(s))
+/**
+ * One entry per application identity. cua-driver refuses to start ("application resources repeat
+ * an identity") when the same app appears twice, and Windows paths differ only in case surprisingly
+ * often (C:\Windows\System32\notepad.exe vs a Start-menu shortcut's C:\WINDOWS\system32\notepad.exe).
+ */
+export function uniqueApps(apps = [], platform = process.platform) {
+ const seen = new Set()
+ return apps.filter((a) => {
+ const key = a.bundle_id ? `b:${String(a.bundle_id).toLowerCase()}` : `x:${platform === 'win32' || platform === 'darwin' ? String(a.executable).toLowerCase() : String(a.executable)}`
+ if (seen.has(key)) return false
+ seen.add(key)
+ return true
+ })
+}
+
/** Bounded-mode capability manifest (YAML, version 3). */
export function manifestYaml({ tools, apps = [], display = false }) {
+ apps = uniqueApps(apps)
const lines = ['# generated by anymodel bot; do not edit', 'version: 3', 'expires_after: 24h', 'idle_timeout: 24h', 'allow:', ' tools:']
for (const t of tools) lines.push(` - ${yq(t)}`)
lines.push('resources:')
@@ -62,6 +80,8 @@ export function childEnv(base, cfg) {
DO_NOT_TRACK: '1',
CUA_TELEMETRY_ENABLED: '0',
CUA_DRIVER_RS_TELEMETRY_ENABLED: '0',
+ // no update check either: it is a network request at every start and prints a notice to stderr
+ CUA_DRIVER_RS_UPDATE_CHECK: '0',
})
return env
}
@@ -92,78 +112,215 @@ export function createFilter(allowed) {
}
}
-function main() {
- const cfg = JSON.parse(fs.readFileSync(process.env.AMB_CUA_CONFIG, 'utf8'))
- const env = childEnv(process.env, cfg)
- let available
- try {
- available = parseToolList(execFileSync(cfg.bin, ['list-tools'], { env, encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'ignore'] }))
- } catch (e) {
- process.stderr.write(`amb-cua-mcp: cua-driver list-tools failed: ${e?.message ?? e}\n`)
- process.exit(1)
- }
- const tools = cfg.tools.filter((t) => available.has(t))
- const allowed = new Set(tools)
- fs.writeFileSync(cfg.manifest, manifestYaml({ tools, apps: cfg.apps ?? [], display: !!cfg.display }), { mode: 0o600 })
- const filter = createFilter(allowed)
- const args = ['mcp', ...(cfg.direct ? ['--direct'] : [])]
+/** `cua-driver list-tools`, asynchronously (never blocks the MCP channel). */
+function listTools(cfg, env, timeoutMs = 30_000) {
+ return new Promise((resolve, reject) => {
+ execFile(cfg.bin, ['list-tools'], { env, encoding: 'utf8', timeout: timeoutMs, windowsHide: true, maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => {
+ if (err) reject(new Error(`cua-driver list-tools failed: ${err.message}`))
+ else resolve(parseToolList(stdout))
+ })
+ })
+}
+
+const START_TIMEOUT_MS = 60_000
+const RETRY_AFTER_MS = 60_000
+const LIST_WAIT_MS = 3_000
+/**
+ * The MCP front. It answers `initialize` itself and starts the driver in the background, so DSH's
+ * startup (which waits for every MCP server's first connection) never waits for cua-driver. Until
+ * the driver is up, tools/list is empty; when it comes up the client gets
+ * notifications/tools/list_changed and re-lists. A driver that fails to start is NOT a reason to
+ * exit: exiting makes the MCP client relaunch this process (and the driver, and on Windows a
+ * console for each) again and again. Instead calls report the failure, and the driver is retried
+ * at most once a minute, on demand.
+ */
+export function createFront({ cfg, env, send, log, spawnDriver, listTools: list = () => listTools(cfg, env), now = Date.now }) {
+ let allowed = new Set()
+ let filter = createFilter(allowed)
let child
+ let ready = false
+ let starting
let startedAt = 0
- let initMsg
- let initializedMsg
+ let lastAttempt = 0
+ let lastFailure = ''
+ let clientInit
+ let owedListChanged = false
+ let initSeq = 0
const pending = new Set()
- const send = (msg) => process.stdout.write(JSON.stringify(msg) + '\n')
-
- const start = (replay) => {
- startedAt = Date.now()
- const c = spawn(cfg.bin, args, { env, stdio: ['pipe', 'pipe', 'inherit'] })
- child = c
- const rl = readline.createInterface({ input: c.stdout })
- rl.on('line', (line) => {
- if (!line.trim()) return
- let msg
- try { msg = JSON.parse(line) } catch { return }
- if (typeof msg.id === 'string' && msg.id.startsWith('amb-reinit-')) return
- if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) pending.delete(msg.id)
- send(filter.fromDriver(msg))
- })
- c.on('exit', (code) => {
- if (child !== c) return
- child = undefined
- for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: `cua-driver exited (${code})` } })
- pending.clear()
+ const waiters = new Set()
+ const settleWaiters = () => {
+ for (const w of waiters) w()
+ waiters.clear()
+ }
+ const whenReady = (ms) =>
+ ready
+ ? Promise.resolve(true)
+ : new Promise((resolve) => {
+ const done = () => {
+ clearTimeout(t)
+ waiters.delete(done)
+ resolve(ready)
+ }
+ const t = setTimeout(done, ms)
+ waiters.add(done)
+ })
+
+ const fail = (why) => {
+ lastFailure = why
+ log(why)
+ settleWaiters()
+ }
+
+ const onDriverLine = (c, initId, line) => {
+ if (!line.trim()) return
+ let msg
+ try { msg = JSON.parse(line) } catch { return }
+ if (msg.id === initId) {
+ if (msg.error) return fail(`cua-driver refused initialize: ${msg.error.message ?? JSON.stringify(msg.error)}`)
+ c.stdin.write(JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }) + '\n')
+ ready = true
+ startedAt = now()
+ lastFailure = ''
+ log('cua-driver ready')
+ settleWaiters()
+ if (owedListChanged) {
+ owedListChanged = false
+ send({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' })
+ }
+ return
+ }
+ if (typeof msg.id === 'string' && msg.id.startsWith('amb-')) return
+ if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) pending.delete(msg.id)
+ send(filter.fromDriver(msg))
+ }
+
+ const start = () => {
+ if (starting) return starting
+ starting = (async () => {
+ lastAttempt = now()
+ let available
+ try {
+ available = await list()
+ } catch (e) {
+ return fail(String(e?.message ?? e))
+ }
+ const tools = cfg.tools.filter((t) => available.has(t))
+ allowed = new Set(tools)
+ filter = createFilter(allowed)
+ fs.writeFileSync(cfg.manifest, manifestYaml({ tools, apps: cfg.apps ?? [], display: !!cfg.display }), { mode: 0o600 })
+ const c = spawnDriver()
+ child = c
+ const initId = `amb-init-${++initSeq}`
+ readline.createInterface({ input: c.stdout }).on('line', (line) => onDriverLine(c, initId, line))
+ c.stderr?.on('data', (d) => process.stderr.write(d))
+ // A driver that already exited must not take this process down with EPIPE on the next write.
+ c.stdin.on('error', () => {})
+ c.on('error', (e) => fail(`cua-driver could not start: ${e.message}`))
+ c.on('exit', (code) => {
+ if (child !== c) return
+ child = undefined
+ ready = false
+ for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: `cua-driver exited (${code})` } })
+ pending.clear()
+ fail(`cua-driver mcp exited (${code})`)
+ })
+ const params = clientInit?.params ?? { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'amb-cua-mcp', version: '1' } }
+ c.stdin.write(JSON.stringify({ jsonrpc: '2.0', id: initId, method: 'initialize', params }) + '\n')
+ if (!(await whenReady(START_TIMEOUT_MS)) && child === c) {
+ fail(`cua-driver did not answer initialize within ${START_TIMEOUT_MS / 1000} s`)
+ c.kill()
+ }
+ })().finally(() => {
+ starting = undefined
})
- if (replay && initMsg) {
- c.stdin.write(JSON.stringify({ ...initMsg, id: `amb-reinit-${startedAt}` }) + '\n')
- if (initializedMsg) c.stdin.write(JSON.stringify(initializedMsg) + '\n')
+ return starting
+ }
+
+ /** Driver is up, or try once more if the last attempt is old enough; resolves to readiness. */
+ const ensure = async (waitMs) => {
+ if (ready) return true
+ if (!starting) {
+ // failed less than a minute ago: answer right away instead of waiting for nothing
+ if (now() - lastAttempt < RETRY_AFTER_MS) return false
+ void start()
+ }
+ return whenReady(waitMs)
+ }
+
+ const forward = (msg) => {
+ if (msg.id !== undefined && msg.method) pending.add(msg.id)
+ child.stdin.write(JSON.stringify(msg) + '\n')
+ }
+
+ const onClient = async (msg) => {
+ if (msg.method === 'initialize' && msg.id !== undefined) {
+ clientInit = msg
+ send({ jsonrpc: '2.0', id: msg.id, result: { protocolVersion: msg.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: { listChanged: true } }, serverInfo: { name: 'amb-cua-mcp', version: '1.0.0' } } })
+ void start()
+ return
+ }
+ if (msg.method === 'notifications/initialized') return // the driver gets its own
+ if (msg.method === 'ping' && msg.id !== undefined) return send({ jsonrpc: '2.0', id: msg.id, result: {} })
+ if (msg.method === 'tools/list' && msg.id !== undefined) {
+ if (await ensure(LIST_WAIT_MS)) return forward(filter.fromClient(msg).forward)
+ owedListChanged = true
+ return send({ jsonrpc: '2.0', id: msg.id, result: { tools: [] } })
+ }
+ if (msg.method === 'tools/call' && msg.id !== undefined) {
+ // The manifest lives at most 24 h: start a fresh driver (same manifest) before it expires.
+ if (ready && now() - startedAt > LIFETIME_MS) {
+ const old = child
+ child = undefined
+ ready = false
+ for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: 'cua-driver restarted' } })
+ pending.clear()
+ old?.kill()
+ lastAttempt = 0
+ }
+ if (!(await ensure(START_TIMEOUT_MS))) {
+ return send({ jsonrpc: '2.0', id: msg.id, result: { isError: true, content: [{ type: 'text', text: `Computer Use is unavailable on this computer right now (${lastFailure || 'the Cua Driver is still starting'}). Tell the user instead of retrying.` }] } })
+ }
+ const r = filter.fromClient(msg)
+ return r.reply ? send(r.reply) : forward(r.forward)
}
+ if (ready) return forward(msg)
+ if (msg.id !== undefined && msg.method) send({ jsonrpc: '2.0', id: msg.id, error: { code: -32603, message: lastFailure || 'cua-driver is starting' } })
}
- start(false)
+ return {
+ onClient,
+ stop: () => child?.kill(),
+ get ready() {
+ return ready
+ },
+ }
+}
+
+function main() {
+ const cfg = JSON.parse(fs.readFileSync(process.env.AMB_CUA_CONFIG, 'utf8'))
+ const env = childEnv(process.env, cfg)
+ const args = ['mcp', ...(cfg.direct ? ['--direct'] : [])]
+ for (const s of [process.stdout, process.stderr]) s.on('error', () => {})
+ const front = createFront({
+ cfg,
+ env,
+ send: (msg) => process.stdout.write(JSON.stringify(msg) + '\n'),
+ log: (s) => process.stderr.write(`amb-cua-mcp: ${s}\n`),
+ // stdio all piped (stderr forwarded): with windowsHide that also means CREATE_NO_WINDOW, so
+ // no console window exists at all (SW_HIDE alone is not enough when Windows Terminal is the
+ // default console host).
+ spawnDriver: () => spawn(cfg.bin, args, { env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }),
+ })
const rl = readline.createInterface({ input: process.stdin })
rl.on('line', (line) => {
if (!line.trim()) return
let msg
try { msg = JSON.parse(line) } catch { return }
- if (msg.method === 'initialize') initMsg = msg
- if (msg.method === 'notifications/initialized') initializedMsg = msg
- const r = filter.fromClient(msg)
- if (r.reply) return send(r.reply)
- // The manifest lives at most 24 h: start a fresh driver (same manifest) before it expires.
- if (child && msg.method === 'tools/call' && Date.now() - startedAt > LIFETIME_MS) {
- const old = child
- child = undefined
- for (const id of pending) send({ jsonrpc: '2.0', id, error: { code: -32603, message: 'cua-driver restarted' } })
- pending.clear()
- old.kill()
- }
- if (!child) start(msg.method !== 'initialize')
- if (msg.id !== undefined && msg.method) pending.add(msg.id)
- child.stdin.write(JSON.stringify(r.forward) + '\n')
+ front.onClient(msg).catch((e) => process.stderr.write(`amb-cua-mcp: ${e?.message ?? e}\n`))
})
- rl.on('close', () => { child?.kill(); process.exit(0) })
- for (const s of ['SIGTERM', 'SIGINT']) process.on(s, () => { child?.kill(); process.exit(0) })
+ rl.on('close', () => { front.stop(); process.exit(0) })
+ for (const s of ['SIGTERM', 'SIGINT']) process.on(s, () => { front.stop(); process.exit(0) })
}
if (process.argv[1] && fileURLToPath(import.meta.url) === fs.realpathSync(process.argv[1])) main()
diff --git a/electron/main.ts b/electron/main.ts
index c75e923..47be9bd 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -15,7 +15,7 @@ import { fileURLToPath } from "node:url";
import { loadConfig } from "../src/config.js";
import { App } from "../src/app.js";
import { findAppRoot } from "../src/magpie/supervisor.js";
-import { logger } from "../src/log.js";
+import { initFileLog, logFilePath, logger, registerSecret, setConsoleLog } from "../src/log.js";
const log = logger("desktop");
const SMOKE = process.env.AMB_ELECTRON_SMOKE; // 冒烟测试:截图到该路径后退出
@@ -119,10 +119,13 @@ function setAutostart(on: boolean): void {
async function boot(): Promise<void> {
const dataDir = process.env.AMB_DATA_DIR ? path.resolve(process.env.AMB_DATA_DIR) : path.join(app.getPath("userData"), "data");
fs.mkdirSync(dataDir, { recursive: true });
+ // 尽早打开日志文件:配置读取失败、启动失败也能留下记录
+ initFileLog(path.join(dataDir, "logs"));
const config = loadConfig({ dataDir });
// 桌面版:仅回环 + 每次启动随机令牌;端口沿用配置(默认 3600,被占用时自动换随机端口)
config.ui.host = "127.0.0.1";
if (!config.ui.token) config.ui.token = crypto.randomBytes(24).toString("base64url");
+ registerSecret(config.ui.token);
core = new App(config);
core.desktop = {
autostart: () => ({ supported: canAutostart, on: canAutostart && app.getLoginItemSettings().openAtLogin }),
@@ -170,6 +173,25 @@ async function smoke(out: string): Promise<void> {
}
}
+// Windows 安装版是 GUI 程序:stdout/stderr 要么不存在,要么是别人的管道(读端关掉 = EPIPE,读端不读 = 同步写入卡住
+// 主进程)。日志只写文件(设置 → 故障排查里能看),需要控制台输出时设 AMB_LOG_STDOUT=1。
+if (process.platform === "win32" && app.isPackaged && process.env.AMB_LOG_STDOUT !== "1") setConsoleLog(false);
+
+// 未捕获异常:Electron 默认弹一个同步的错误框,在用户关掉它之前整个主进程(本机服务、模型桥、所有对话)都卡住,
+// 界面上就是一直"思考中"。这里改成记日志 + 非阻塞提示;stdio 写失败(EPIPE 等)只记日志不提示。
+let lastErrorBox = 0;
+process.on("uncaughtException", (e) => {
+ const err = e as NodeJS.ErrnoException;
+ log.error(`uncaught exception: ${err?.stack || String(e)}`);
+ if (["EPIPE", "EBADF", "EOF", "ERR_STREAM_DESTROYED"].includes(String(err?.code))) return;
+ if (Date.now() - lastErrorBox < 60_000 || !app.isReady()) return;
+ lastErrorBox = Date.now();
+ void dialog
+ .showMessageBox({ type: "error", title: PRODUCT, message: `${PRODUCT} 出错了`, detail: `${err?.message ?? String(e)}\n\n详细信息见日志:${logFilePath() ?? "(未启用)"}` })
+ .catch(() => {});
+});
+process.on("unhandledRejection", (e) => log.warn(`unhandled rejection: ${(e as Error)?.stack || String(e)}`));
+
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
diff --git a/scripts/ci/procmon.ps1 b/scripts/ci/procmon.ps1
new file mode 100644
index 0000000..56bf504
--- /dev/null
+++ b/scripts/ci/procmon.ps1
@@ -0,0 +1,78 @@
+# CI helper (Windows): log process starts and visible console windows as JSON lines until -StopFile exists.
+# Used by scripts/e2e-agent.mjs --procmon to check that the app opens no console windows.
+param([Parameter(Mandatory = $true)][string]$Out, [Parameter(Mandatory = $true)][string]$StopFile)
+$ErrorActionPreference = 'Continue'
+
+Add-Type @"
+using System;
+using System.Text;
+using System.Runtime.InteropServices;
+using System.Collections.Generic;
+public static class AmbWin {
+ public delegate bool EnumProc(IntPtr h, IntPtr p);
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr p);
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetClassName(IntPtr h, StringBuilder s, int n);
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int n);
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
+ public static List<string> Consoles() {
+ var r = new List<string>();
+ EnumWindows((h, p) => {
+ if (!IsWindowVisible(h)) return true;
+ var c = new StringBuilder(256);
+ GetClassName(h, c, 256);
+ var cls = c.ToString();
+ if (cls == "ConsoleWindowClass" || cls == "CASCADIA_HOSTING_WINDOW_CLASS" || cls == "PseudoConsoleWindow") {
+ var t = new StringBuilder(512);
+ GetWindowText(h, t, 512);
+ uint pid;
+ GetWindowThreadProcessId(h, out pid);
+ r.Add(h.ToInt64() + "|" + pid + "|" + cls + "|" + t.ToString());
+ }
+ return true;
+ }, IntPtr.Zero);
+ return r;
+ }
+}
+"@
+
+function Log($obj) {
+ $obj['t'] = (Get-Date).ToString('HH:mm:ss.fff')
+ Add-Content -Path $Out -Value ($obj | ConvertTo-Json -Compress -Depth 3)
+}
+
+$wmi = $true
+try {
+ Register-CimIndicationEvent -ClassName Win32_ProcessStartTrace -SourceIdentifier ambStart -ErrorAction Stop | Out-Null
+ Register-CimIndicationEvent -ClassName Win32_ProcessStopTrace -SourceIdentifier ambStop -ErrorAction Stop | Out-Null
+} catch {
+ $wmi = $false
+ Log @{ kind = 'error'; message = "WMI trace unavailable: $($_.Exception.Message)" }
+}
+Log @{ kind = 'ready'; wmi = $wmi }
+
+# Visible consoles that already exist (the runner's own) are reported once with kind=console-preexisting.
+$seen = @{}
+foreach ($w in [AmbWin]::Consoles()) { $seen[$w] = 1; Log @{ kind = 'console-preexisting'; window = $w } }
+
+while (-not (Test-Path $StopFile)) {
+ if ($wmi) {
+ foreach ($e in @(Get-Event -SourceIdentifier ambStart -ErrorAction SilentlyContinue)) {
+ $n = $e.SourceEventArgs.NewEvent
+ $cmd = $null
+ try { $cmd = (Get-CimInstance Win32_Process -Filter "ProcessId=$($n.ProcessID)" -ErrorAction Stop).CommandLine } catch {}
+ Log @{ kind = 'start'; pid = [int]$n.ProcessID; ppid = [int]$n.ParentProcessID; name = [string]$n.ProcessName; cmd = $cmd }
+ Remove-Event -EventIdentifier $e.EventIdentifier
+ }
+ foreach ($e in @(Get-Event -SourceIdentifier ambStop -ErrorAction SilentlyContinue)) {
+ $n = $e.SourceEventArgs.NewEvent
+ Log @{ kind = 'stop'; pid = [int]$n.ProcessID; name = [string]$n.ProcessName; exit = [int64]$n.ExitStatus }
+ Remove-Event -EventIdentifier $e.EventIdentifier
+ }
+ }
+ foreach ($w in [AmbWin]::Consoles()) {
+ if (-not $seen.ContainsKey($w)) { $seen[$w] = 1; Log @{ kind = 'console-window'; window = $w } }
+ }
+ Start-Sleep -Milliseconds 150
+}
+Log @{ kind = 'done' }
diff --git a/scripts/e2e-agent.mjs b/scripts/e2e-agent.mjs
new file mode 100644
index 0000000..42e2695
--- /dev/null
+++ b/scripts/e2e-agent.mjs
@@ -0,0 +1,392 @@
+#!/usr/bin/env node
+// End-to-end check of the agent path in a real app process (installed build or `electron .`):
+// a scripted OpenAI-compatible mock model, the app in external-endpoint mode pointing at it,
+// one chat message through the local HTTP API, and a hard timeout. Everything is written to --out
+// (app stdout/stderr, model requests, agent status polls, the data dir) so CI can upload it.
+//
+// node scripts/e2e-agent.mjs --out <dir> [--timeout-ms 180000] [--procmon] [--tool] [--managed] [--stream]
+// [--reasoning] [--observe-ms N] [--max-console-windows N] -- <app exe> [args...]
+//
+// --procmon (Windows): also log every process start and every visible console window while the app
+// runs (scripts/ci/procmon.ps1), which is how the "flashing console windows" report is checked.
+// --max-console-windows N: fail when more than N new visible console windows appeared (needs --procmon).
+// --expect-diagnostics: also require the troubleshooting page's "test model" and "test agent" to pass.
+// --tool: the mock model asks for one shell tool call before answering (exercises tool spawning).
+// --managed: use the bundled magpie gateway (as users do) with "Modelflare" pointed at the mock
+// (AMB_MODELFLARE_BASE_URL) and connected through the API; otherwise the app calls the mock directly.
+// --stream: send the message through the UI's SSE endpoint (/chat/stream) instead of /chat.
+// --reasoning: the mock streams reasoning_content deltas before the answer (like reasoning models).
+// --observe-ms N: keep the app running N ms after the reply (process monitor keeps logging), then
+// send a second message.
+// --launch node|shell|redirect (Windows): how the app is started. node (default) = child_process
+// with stdout/stderr to files; shell = PowerShell Start-Process without redirection, i.e.
+// ShellExecute like a Start-menu shortcut: the GUI app gets NO std handles; redirect =
+// Start-Process with -RedirectStandardOutput/-Error (what users do to capture output);
+// broken-pipe = stdout/stderr are pipes whose read end is closed right away (what PowerShell's
+// `*>` does to a GUI program): every console write fails with EPIPE.
+// --cwd <dir>: working directory for shell/redirect launches (default: the exe's folder, like the
+// installed shortcut).
+// --status-probes: send /status before anything else and again while the first message is
+// in flight; both must answer within 20 s (they must never wait behind the agent).
+// Exit code 0 = the reply came back and contained the mock's answer; 1 otherwise.
+import { spawn, spawnSync } from "node:child_process";
+import crypto from "node:crypto";
+import fs from "node:fs";
+import http from "node:http";
+import net from "node:net";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const argv = process.argv.slice(2);
+const dash = argv.indexOf("--");
+const opts = dash >= 0 ? argv.slice(0, dash) : argv;
+const cmd = dash >= 0 ? argv.slice(dash + 1) : [];
+const opt = (k, d) => {
+ const i = opts.indexOf(`--${k}`);
+ return i >= 0 ? opts[i + 1] : d;
+};
+const flag = (k) => opts.includes(`--${k}`);
+if (!cmd.length) {
+ console.error("usage: e2e-agent.mjs --out <dir> [--timeout-ms N] [--procmon] [--tool] -- <app> [args...]");
+ process.exit(2);
+}
+// A relative app path (node_modules/electron/dist/electron.exe) is resolved here: spawn() on Windows
+// does not resolve paths with separators against the cwd.
+if (/[\\/]/.test(cmd[0]) && !path.isAbsolute(cmd[0])) cmd[0] = path.resolve(cmd[0]);
+const out = path.resolve(opt("out", "e2e-out"));
+const timeoutMs = Number(opt("timeout-ms", 180_000));
+const here = path.dirname(fileURLToPath(import.meta.url));
+fs.mkdirSync(out, { recursive: true });
+// --data-dir: e.g. a path with CJK characters and spaces, like a Chinese Windows user name gives
+const dataDir = path.resolve(opt("data-dir", path.join(out, "data")));
+fs.mkdirSync(dataDir, { recursive: true });
+const t0 = Date.now();
+const stamp = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;
+const say = (...a) => console.log(stamp(), ...a);
+const jl = (file, obj) => fs.appendFileSync(path.join(out, file), JSON.stringify({ t: stamp(), ...obj }) + "\n");
+
+const MODEL = "mock-agent";
+const ANSWER = "pong-from-mock";
+const wantTool = flag("tool");
+const managed = flag("managed");
+const reasoning = flag("reasoning");
+const observeMs = Number(opt("observe-ms", 0));
+const maxConsoles = opt("max-console-windows");
+
+function textOf(c) {
+ if (typeof c === "string") return c;
+ if (Array.isArray(c)) return c.map((p) => (typeof p === "string" ? p : p?.text ?? "")).join("");
+ return "";
+}
+
+function freePort() {
+ return new Promise((resolve, reject) => {
+ const s = net.createServer();
+ s.on("error", reject);
+ s.listen(0, "127.0.0.1", () => {
+ const p = s.address().port;
+ s.close(() => resolve(p));
+ });
+ });
+}
+
+// ---------- mock model ----------
+const llm = http.createServer(async (req, res) => {
+ const chunks = [];
+ for await (const c of req) chunks.push(c);
+ let b = {};
+ try {
+ b = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
+ } catch {
+ /* ignore */
+ }
+ const tools = (b.tools ?? []).map((t) => t.function?.name ?? t.name);
+ const msgs = b.messages ?? [];
+ jl("llm-requests.jsonl", { method: req.method, url: req.url, model: b.model, stream: b.stream, tools, roles: msgs.map((m) => m.role), last: textOf(msgs.at(-1)?.content).slice(-200) });
+ if (req.url?.endsWith("/models")) {
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ object: "list", data: [{ id: MODEL, object: "model" }] }));
+ return;
+ }
+ if (!req.url?.endsWith("/chat/completions")) return void res.writeHead(404).end();
+ // One shell call first when asked (and the runtime offers a shell tool), then the answer.
+ const shell = tools.find((n) => n === "bash" || n === "pwsh" || n === "powershell");
+ const toolResults = msgs.filter((m) => m.role === "tool");
+ const call = wantTool && b.tools && shell && !toolResults.length ? { name: shell, args: { description: "say hi", command: "echo tool-ran-ok" } } : undefined;
+ const text = toolResults.length ? `${ANSWER} [${toolResults.map((m) => textOf(m.content)).join("|").slice(0, 300)}]` : ANSWER;
+ if (!b.stream) {
+ res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ id: "c1", object: "chat.completion", model: b.model, choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } }));
+ return;
+ }
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const send = (o) => res.write(`data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: b.model, ...o })}\n\n`);
+ if (call) {
+ send({ choices: [{ index: 0, delta: { role: "assistant", tool_calls: [{ index: 0, id: "call_" + crypto.randomBytes(4).toString("hex"), type: "function", function: { name: call.name, arguments: JSON.stringify(call.args) } }] } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] });
+ } else {
+ if (reasoning) for (const r of ["Thinking", " about", " it."]) send({ choices: [{ index: 0, delta: { role: "assistant", content: null, reasoning_content: r } }] });
+ send({ choices: [{ index: 0, delta: { role: "assistant", content: text } }] });
+ send({ choices: [{ index: 0, delta: {}, finish_reason: "stop" }] });
+ }
+ send({ choices: [], usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } });
+ res.end("data: [DONE]\n\n");
+});
+await new Promise((r) => llm.listen(0, "127.0.0.1", r));
+const llmUrl = `http://127.0.0.1:${llm.address().port}`;
+say("mock model at", llmUrl);
+
+// ---------- optional process monitor (Windows) ----------
+let procmon;
+const stopFile = path.join(out, "procmon.stop");
+if (flag("procmon") && process.platform === "win32") {
+ procmon = spawn("powershell.exe", ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", path.join(here, "ci", "procmon.ps1"), "-Out", path.join(out, "procmon.jsonl"), "-StopFile", stopFile], { stdio: ["ignore", fs.openSync(path.join(out, "procmon.stdout.log"), "w"), fs.openSync(path.join(out, "procmon.stderr.log"), "w")], windowsHide: true });
+ await new Promise((r) => setTimeout(r, 4000)); // let the WMI subscription settle
+}
+
+// ---------- the app ----------
+const port = await freePort();
+const token = crypto.randomBytes(16).toString("hex");
+const base = `http://127.0.0.1:${port}`;
+const env = {
+ ...process.env,
+ AMB_DATA_DIR: dataDir,
+ ...(managed ? { AMB_MODELFLARE_BASE_URL: llmUrl + "/v1" } : { AMB_MAGPIE_BASE_URL: llmUrl + "/v1", AMB_MAGPIE_API_KEY: "mock-key", AMB_DEFAULT_MODEL: MODEL }),
+ AMB_UI_PORT: String(port),
+ AMB_UI_TOKEN: token,
+ AMB_LOG_LEVEL: "debug",
+ AMB_DSH_TRACE: path.join(out, "dsh-trace.jsonl"),
+ AMB_WEIXIN_API_BASE: "http://127.0.0.1:9",
+ AMB_MEMORY_REVIEW_DELAY_MS: "600000",
+};
+const launch = opt("launch", "node");
+say("launching", launch, JSON.stringify(cmd));
+let app;
+let appExit;
+if (launch === "node" || launch === "broken-pipe") {
+ const appOut = fs.openSync(path.join(out, "app.stdout.log"), "w");
+ const appErr = fs.openSync(path.join(out, "app.stderr.log"), "w");
+ app = spawn(cmd[0], cmd.slice(1), { env, stdio: launch === "node" ? ["ignore", appOut, appErr] : ["ignore", "pipe", "pipe"] });
+ if (launch === "broken-pipe") {
+ app.stdout.destroy();
+ app.stderr.destroy();
+ }
+ app.on("exit", (code, signal) => {
+ appExit = { code, signal };
+ say("app exited", code, signal);
+ });
+ app.on("error", (e) => say("app spawn error", e.message));
+} else {
+ // Start-Process: ShellExecute (shell) or CreateProcess with file handles (redirect); env is inherited.
+ const q = (v) => `'${String(v).replaceAll("'", "''")}'`;
+ const wd = opt("cwd", path.dirname(cmd[0]));
+ const argList = cmd.length > 1 ? ` -ArgumentList ${cmd.slice(1).map(q).join(",")}` : "";
+ const redirect = launch === "redirect" ? ` -RedirectStandardOutput ${q(path.join(out, "app.stdout.log"))} -RedirectStandardError ${q(path.join(out, "app.stderr.log"))}` : "";
+ // The PID comes back through a file, and PowerShell gets no pipes from us: Start-Process with
+ // redirection creates the app with inherited handles, and an inherited pipe would keep this
+ // call waiting until the app exits.
+ const pidFile = path.join(out, "app.pid");
+ const ps = `(Start-Process -FilePath ${q(cmd[0])}${argList} -WorkingDirectory ${q(wd)}${redirect} -PassThru).Id | Out-File -Encoding ascii ${q(pidFile)}`;
+ const r = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { env, stdio: "ignore", windowsHide: true, timeout: 60_000 });
+ const pid = Number(fs.existsSync(pidFile) ? fs.readFileSync(pidFile, "utf8").trim() : NaN);
+ say("started pid", pid, "cwd", wd, r.error ? r.error.message : "");
+ app = { pid, kill: () => {} };
+ const alive = setInterval(() => {
+ try {
+ process.kill(pid, 0);
+ } catch {
+ appExit = { code: "gone", signal: null };
+ say("app exited");
+ clearInterval(alive);
+ }
+ }, 1000);
+ alive.unref();
+}
+
+const H = { "x-amb-token": token };
+async function api(p, init = {}, ms = 15_000) {
+ const r = await fetch(base + p, { ...init, headers: { ...H, ...(init.body ? { "content-type": "application/json" } : {}), ...(init.headers ?? {}) }, signal: AbortSignal.timeout(ms) });
+ const text = await r.text();
+ let body;
+ try {
+ body = JSON.parse(text);
+ } catch {
+ body = text;
+ }
+ return { status: r.status, body };
+}
+
+const summary = { appPid: app.pid, ok: false };
+
+/** The UI's path: POST /chat/stream (SSE). Every event is logged with a timestamp. */
+async function streamChat(text, ms) {
+ const r = await fetch(`${base}/amb/api/bots/default/chat/stream`, { method: "POST", headers: { ...H, "content-type": "application/json" }, body: JSON.stringify({ text }), signal: AbortSignal.timeout(ms) });
+ if (!r.ok || !r.body) return { status: r.status, reply: await r.text() };
+ const dec = new TextDecoder();
+ let buf = "";
+ let reply = "";
+ let last = "";
+ for await (const chunk of r.body) {
+ buf += dec.decode(chunk, { stream: true });
+ let i;
+ while ((i = buf.indexOf("\n\n")) >= 0) {
+ const block = buf.slice(0, i);
+ buf = buf.slice(i + 2);
+ const ev = /^event: (.*)$/m.exec(block)?.[1] ?? (block.startsWith(":") ? "comment" : "message");
+ const data = /^data: (.*)$/m.exec(block)?.[1];
+ jl("sse-events.jsonl", { ev, data: data?.slice(0, 300) });
+ last = ev;
+ if (ev === "text" && data) reply = JSON.parse(data).text ?? reply;
+ if (ev === "error" && data) reply = `ERROR ${JSON.parse(data).message}`;
+ }
+ }
+ return { status: r.status, reply, lastEvent: last };
+}
+let poll;
+try {
+ // 1) UI up
+ let up = false;
+ for (let i = 0; i < 180 && !up && !appExit; i++) {
+ try {
+ up = (await api("/amb/healthz", {}, 2000)).status === 200;
+ } catch {
+ /* not yet */
+ }
+ if (!up) await new Promise((r) => setTimeout(r, 500));
+ }
+ if (!up) throw new Error("app UI never came up");
+ say("UI up");
+ summary.status = (await api("/amb/api/status")).body;
+
+ // 2) poll agent status while the turn runs
+ poll = setInterval(() => {
+ api("/amb/api/agent", {}, 5000).then((r) => jl("agent-status.jsonl", r.body), (e) => jl("agent-status.jsonl", { error: String(e?.message ?? e) }));
+ }, 2000);
+
+ // 2b) managed: connect "Modelflare" (= the mock) through the API, like onboarding does
+ if (managed) {
+ for (let i = 0; i < 60 && summary.status?.gateway?.state !== "running"; i++) {
+ await new Promise((r) => setTimeout(r, 500));
+ summary.status = (await api("/amb/api/status")).body;
+ }
+ const c = await api("/amb/api/modelflare", { method: "PUT", body: JSON.stringify({ apiKey: "mf-e2e-key-0123456789", line: "auto" }) }, 60_000);
+ summary.connect = { status: c.status, connected: c.body?.connected, error: c.body?.error, models: c.body?.models };
+ say("modelflare connect:", JSON.stringify(summary.connect));
+ summary.models = (await api("/amb/api/models", {}, 30_000)).body?.models;
+ say("models:", JSON.stringify(summary.models));
+ }
+
+ // 3) chat
+ const chat = async (text, ms = timeoutMs) => {
+ const started = Date.now();
+ try {
+ if (flag("stream")) return { ...(await streamChat(text, ms)), ms: Date.now() - started };
+ const r = await api("/amb/api/bots/default/chat", { method: "POST", body: JSON.stringify({ text }) }, ms);
+ return { status: r.status, ms: Date.now() - started, reply: r.body?.reply ?? r.body };
+ } catch (e) {
+ return { error: String(e?.message ?? e), ms: Date.now() - started };
+ }
+ };
+ const good = (c) => typeof c?.reply === "string" && c.reply.includes(ANSWER) && (!wantTool || c.reply.includes("tool-ran-ok"));
+ const statusOk = (c) => typeof c?.reply === "string" && c.reply.includes("当前模型") && c.ms < 20_000;
+ if (flag("status-probes")) {
+ summary.statusFirst = await chat("/status", 20_000);
+ say("/status (first):", JSON.stringify(summary.statusFirst).slice(0, 500));
+ }
+ summary.chatStartedAt = stamp();
+ const first = chat(wantTool ? "Run the tool, then answer. TOOLTEST" : "Say hi. PINGTEST");
+ if (flag("status-probes")) {
+ await new Promise((r) => setTimeout(r, 3000));
+ summary.statusDuring = await chat("/status", 20_000);
+ say("/status (while the first message runs):", JSON.stringify(summary.statusDuring).slice(0, 500));
+ }
+ summary.chat = await first;
+ say("chat:", JSON.stringify(summary.chat).slice(0, 600));
+ summary.ok = good(summary.chat);
+ if (flag("status-probes")) summary.ok &&= statusOk(summary.statusFirst) && statusOk(summary.statusDuring);
+ if (observeMs > 0) {
+ say(`observing for ${observeMs} ms`);
+ await new Promise((r) => setTimeout(r, observeMs));
+ summary.chat2 = await chat("Again. PINGTEST 2");
+ say("chat2:", JSON.stringify(summary.chat2).slice(0, 600));
+ summary.ok &&= good(summary.chat2);
+ }
+ summary.agent = (await api("/amb/api/agent").catch((e) => ({ body: String(e) }))).body;
+
+ // 4) troubleshooting endpoints (present from 0.1.6)
+ for (const [name, p, init] of [
+ ["diag", "/amb/api/diagnostics"],
+ ["testModel", "/amb/api/diagnostics/test-model", { method: "POST", body: "{}" }],
+ ["testAgent", "/amb/api/diagnostics/test-agent", { method: "POST", body: "{}" }],
+ ["logs", "/amb/api/diagnostics/logs?lines=400"],
+ ]) {
+ try {
+ const r = await api(p, init, 150_000);
+ fs.writeFileSync(path.join(out, `diag-${name}.json`), JSON.stringify(r, null, 2));
+ if (name === "testAgent") summary.testAgent = r.body;
+ if (name === "testModel") summary.testModel = r.body;
+ } catch (e) {
+ fs.writeFileSync(path.join(out, `diag-${name}.json`), JSON.stringify({ error: String(e?.message ?? e) }));
+ }
+ }
+ if (flag("expect-diagnostics")) {
+ // The troubleshooting page's own checks must pass against the same mock.
+ const m = summary.testModel;
+ const modelOk = !!m?.direct?.ok && (!!m?.gateway?.ok || !!m?.gateway?.skipped);
+ say(`test model: ${modelOk ? "ok" : "FAILED"} (${m?.verdict ?? "no result"}); test agent: ${summary.testAgent?.ok ? "ok" : `FAILED at ${summary.testAgent?.stuckAt ?? "?"}`}`);
+ summary.ok &&= modelOk && !!summary.testAgent?.ok;
+ }
+} catch (e) {
+ summary.error = String(e?.message ?? e);
+ say("error:", summary.error);
+} finally {
+ clearInterval(poll);
+ summary.appExit = appExit;
+ // Process tree snapshot before teardown (Windows), then stop everything.
+ if (process.platform === "win32") {
+ const ps = spawnSync("powershell.exe", ["-NoProfile", "-Command", "Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId,Name,CommandLine | ConvertTo-Json -Depth 2"], { encoding: "utf8", windowsHide: true, maxBuffer: 64 * 1024 * 1024 });
+ fs.writeFileSync(path.join(out, "processes-before-exit.json"), ps.stdout || ps.stderr || "");
+ if (!appExit && app?.pid) spawnSync("taskkill", ["/PID", String(app.pid), "/T", "/F"], { windowsHide: true });
+ } else if (!appExit) {
+ app.kill("SIGTERM");
+ await new Promise((r) => setTimeout(r, 3000));
+ if (!appExit) app.kill("SIGKILL");
+ }
+ if (procmon) {
+ fs.writeFileSync(stopFile, "");
+ await new Promise((r) => setTimeout(r, 3000));
+ try {
+ procmon.kill();
+ } catch {
+ /* ignore */
+ }
+ }
+ llm.close();
+ // Startup timings: from the app's own log when it has one (0.1.7+), else time to the first model request.
+ try {
+ const log = fs.readFileSync(path.join(dataDir, "logs", "app.log"), "utf8").split(/\r?\n/);
+ summary.dshStages = log.filter((l) => /dsh start: |dsh started|dsh still initializing|prewarming/.test(l)).map((l) => l.slice(0, 260));
+ } catch {
+ /* no app.log (0.1.6 and older) */
+ }
+ try {
+ const reqs = fs.readFileSync(path.join(out, "llm-requests.jsonl"), "utf8").split(/\r?\n/).filter(Boolean).map((l) => JSON.parse(l));
+ const firstChat = reqs.find((r) => String(r.url).endsWith("/chat/completions") && (r.tools?.length ?? 0) > 0);
+ summary.firstAgentModelRequestAt = firstChat?.t;
+ } catch {
+ /* ignore */
+ }
+ if (procmon) {
+ // Visible console windows that appeared while the app ran (Windows Terminal or conhost windows;
+ // ConPTY's PseudoConsoleWindow is never shown and is not counted).
+ const lines = fs.existsSync(path.join(out, "procmon.jsonl")) ? fs.readFileSync(path.join(out, "procmon.jsonl"), "utf8").split(/\r?\n/).filter(Boolean) : [];
+ const wins = lines.map((l) => JSON.parse(l)).filter((e) => e.kind === "console-window" && !String(e.window).includes("|PseudoConsoleWindow|"));
+ summary.consoleWindows = wins.map((w) => `${w.t} ${w.window}`);
+ say(`visible console windows: ${wins.length}`);
+ if (maxConsoles !== undefined && wins.length > Number(maxConsoles)) {
+ summary.ok = false;
+ summary.error = `${wins.length} console windows appeared (allowed ${maxConsoles})`;
+ }
+ }
+ fs.writeFileSync(path.join(out, "summary.json"), JSON.stringify(summary, null, 2));
+ say("summary:", JSON.stringify({ ok: summary.ok, chat: summary.chat, error: summary.error }).slice(0, 800));
+ process.exit(summary.ok ? 0 : 1);
+}
diff --git a/src/agent/bridge.ts b/src/agent/bridge.ts
index c8aae1e..cbef5c9 100644
--- a/src/agent/bridge.ts
+++ b/src/agent/bridge.ts
@@ -2,7 +2,7 @@ import http from "node:http";
import crypto from "node:crypto";
import { Readable } from "node:stream";
import type { AddressInfo } from "node:net";
-import { logger } from "../log.js";
+import { logger, redactText, registerSecret } from "../log.js";
const log = logger("agent.bridge");
@@ -20,6 +20,12 @@ export interface BridgeHandlers {
media?(body: any): Promise<unknown>;
}
+/** 模型代理的一次请求(故障排查的"测试代理"用它判断模型调用这一步) */
+export type ProxyEvent =
+ | { phase: "request"; id: number; path: string; model?: string; tools?: string[]; lastUser?: string }
+ | { phase: "response"; id: number; path: string; status: number; ms: number; error?: string }
+ | { phase: "error"; id: number; path: string; ms: number; error: string };
+
/**
* 仅回环的内部桥:DSH 子进程用每次启动随机生成的令牌访问。
* - /v1/*:模型代理,替换 Authorization 为真实网关密钥(子进程环境里没有任何真实密钥)
@@ -29,8 +35,27 @@ export class AgentBridge {
readonly token = crypto.randomBytes(24).toString("base64url");
private server: http.Server | undefined;
port = 0;
+ private seq = 0;
+ private proxyListeners = new Set<(e: ProxyEvent) => void>();
+
+ constructor(private h: BridgeHandlers) {
+ registerSecret(this.token);
+ }
- constructor(private h: BridgeHandlers) {}
+ /** 订阅模型代理事件;返回取消函数 */
+ onProxy(fn: (e: ProxyEvent) => void): () => void {
+ this.proxyListeners.add(fn);
+ return () => this.proxyListeners.delete(fn);
+ }
+ private emitProxy(e: ProxyEvent): void {
+ for (const fn of this.proxyListeners) {
+ try {
+ fn(e);
+ } catch {
+ /* ignore */
+ }
+ }
+ }
get url(): string {
return `http://127.0.0.1:${this.port}`;
@@ -93,16 +118,52 @@ export class AgentBridge {
}
if (up.apiKey) headers.authorization = `Bearer ${up.apiKey}`;
const body = req.method === "GET" || req.method === "HEAD" ? undefined : await this.readBody(req);
+ const id = ++this.seq;
+ const p = url.split("?")[0];
+ const t0 = Date.now();
+ if (this.proxyListeners.size) this.emitProxy({ phase: "request", id, path: p, ...requestInfo(body) });
const ac = new AbortController();
res.on("close", () => ac.abort());
- const r = await fetch(target, { method: req.method, headers, body: body ? new Uint8Array(body) : undefined, signal: ac.signal });
+ // 上游迟迟不回响应头时每分钟记一条:代理"一直转圈"多半是这里卡住(代理自己要等 5 分钟才判超时并重试)
+ const slow = setInterval(() => log.warn("model request still waiting for upstream response", { path: p, waitedMs: Date.now() - t0 }), 60_000);
+ let r: Response;
+ try {
+ r = await fetch(target, { method: req.method, headers, body: body ? new Uint8Array(body) : undefined, signal: ac.signal });
+ } catch (e) {
+ const error = (e as Error).message;
+ this.emitProxy({ phase: "error", id, path: p, ms: Date.now() - t0, error });
+ throw e;
+ } finally {
+ clearInterval(slow);
+ }
const out: Record<string, string> = {};
r.headers.forEach((v, k) => {
if (!["content-encoding", "content-length", "transfer-encoding", "connection", "set-cookie"].includes(k)) out[k] = v;
});
+ if (r.status >= 400) {
+ // 上游报错:读完错误体(不大)记日志,再原样转给子进程
+ const text = await r.text().catch(() => "");
+ const error = redactText(text.slice(0, 1000));
+ log.warn("model request rejected by upstream", { path: p, status: r.status, ms: Date.now() - t0, body: error });
+ this.emitProxy({ phase: "response", id, path: p, status: r.status, ms: Date.now() - t0, error });
+ res.writeHead(r.status, out);
+ return void res.end(text);
+ }
+ const headersMs = Date.now() - t0;
+ this.emitProxy({ phase: "response", id, path: p, status: r.status, ms: headersMs });
res.writeHead(r.status, out);
if (!r.body) return void res.end();
- Readable.fromWeb(r.body as any).on("error", () => res.destroy()).pipe(res);
+ const stream = Readable.fromWeb(r.body as any);
+ let bytes = 0;
+ stream.on("data", (c: Buffer) => (bytes += c.length));
+ stream.on("end", () => log.info("model request done", { path: p, status: r.status, headersMs, totalMs: Date.now() - t0, bytes }));
+ stream.on("error", (e) => {
+ // 子进程读完 [DONE] 就断开时上游流会被中止(res close → abort),这不是错误
+ if (ac.signal.aborted) log.debug("model response closed by the agent", { path: p, ms: Date.now() - t0, bytes });
+ else log.warn("model response stream failed", { path: p, ms: Date.now() - t0, bytes, error: e.message });
+ res.destroy();
+ });
+ stream.pipe(res);
}
private async dsh(req: http.IncomingMessage, res: http.ServerResponse, url: string): Promise<void> {
@@ -120,3 +181,18 @@ export class AgentBridge {
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(out));
}
}
+
+/** 请求体里的模型名、工具名与第一条用户消息开头(只在有人订阅时解析;解析失败就不给) */
+function requestInfo(body: Buffer | undefined): { model?: string; tools?: string[]; lastUser?: string } {
+ if (!body || body.length > 8 * 1024 * 1024) return {};
+ try {
+ const j = JSON.parse(body.toString("utf8"));
+ const tools = Array.isArray(j?.tools) ? j.tools.map((t: any) => String(t?.function?.name ?? t?.name ?? "")).filter(Boolean) : undefined;
+ const users = Array.isArray(j?.messages) ? j.messages.filter((m: any) => m?.role === "user") : [];
+ const text = (c: unknown): string => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p: any) => (typeof p === "string" ? p : String(p?.text ?? ""))).join("") : "");
+ const lastUser = users.length ? users.map((m: any) => text(m.content).slice(0, 2000)).join("\n") : undefined;
+ return { model: typeof j?.model === "string" ? j.model : undefined, tools, lastUser };
+ } catch {
+ return {};
+ }
+}
diff --git a/src/agent/cua-driver.ts b/src/agent/cua-driver.ts
index 8cc6e4f..47279eb 100644
--- a/src/agent/cua-driver.ts
+++ b/src/agent/cua-driver.ts
@@ -1,4 +1,4 @@
-import { execFileSync } from "node:child_process";
+import { execFile, execFileSync } from "node:child_process";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -166,13 +166,22 @@ export function detectCua(roots: string[], probe: CuaProbe = defaultCuaProbe()):
return off("需要在已登录用户的交互式会话中运行(检测到服务或非交互会话)");
}
+/** 进程的 SessionId 不会变:只查一次(每次查都要同步起一个 PowerShell,冷启动时会卡住主进程好几秒)。 */
+let sessionIdCache: { v: number | undefined } | undefined;
+
/** Windows:当前进程的 SessionId(交互式用户会话 > 0;服务/Session 0 = 0)。失败返回 undefined。 */
export function queryWindowsSessionId(): number | undefined {
+ sessionIdCache ??= { v: querySessionIdOnce() };
+ return sessionIdCache.v;
+}
+
+function querySessionIdOnce(): number | undefined {
try {
const out = execFileSync(
"powershell.exe",
["-NoProfile", "-NonInteractive", "-Command", "(Get-Process -Id $PID).SessionId"],
- { encoding: "utf8", timeout: 5000, windowsHide: true },
+ // stdio 显式:execFileSync 默认把子进程 stderr 转写到本进程 stderr(GUI 程序里可能是坏管道)
+ { encoding: "utf8", timeout: 5000, windowsHide: true, stdio: ["ignore", "pipe", "ignore"] },
).trim();
const n = Number(out);
return Number.isInteger(n) && n >= 0 ? n : undefined;
@@ -259,7 +268,7 @@ export function macApps(homedir: string): CuaApp[] {
try {
const raw = fs.readFileSync(plist);
if (raw.subarray(0, 6).toString() === "bplist") {
- id = execFileSync("/usr/bin/plutil", ["-extract", "CFBundleIdentifier", "raw", "-o", "-", plist], { encoding: "utf8", timeout: 5000 }).trim();
+ id = execFileSync("/usr/bin/plutil", ["-extract", "CFBundleIdentifier", "raw", "-o", "-", plist], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"] }).trim();
} else {
id = /<key>CFBundleIdentifier<\/key>\s*<string>([^<]+)<\/string>/.exec(raw.toString("utf8"))?.[1]?.trim() ?? "";
}
@@ -272,33 +281,84 @@ export function macApps(homedir: string): CuaApp[] {
return [...out].sort().map((bundle_id) => ({ bundle_id }));
}
-/** Windows:开始菜单快捷方式指向的 .exe + 几个系统自带程序(未在真机验证)。 */
-export function windowsApps(env: Record<string, string | undefined>): CuaApp[] {
- const out = new Set<string>();
+const WIN_SHORTCUTS_PS =
+ "$s=New-Object -ComObject WScript.Shell;" +
+ "$d=@([Environment]::GetFolderPath('CommonStartMenu'),[Environment]::GetFolderPath('StartMenu'));" +
+ "Get-ChildItem -Path $d -Recurse -Filter *.lnk -ErrorAction SilentlyContinue|ForEach-Object{try{$s.CreateShortcut($_.FullName).TargetPath}catch{}}";
+
+/** 真实路径(Windows 上 realpath.native 给出盘上的大小写与长文件名);失败时原样返回。 */
+function canonicalPath(p: string): string {
+ try {
+ return fs.realpathSync.native(p);
+ } catch {
+ return p;
+ }
+}
+
+/**
+ * 按"身份"去重:Windows 路径不分大小写。cua-driver 的能力清单里同一个程序出现两次(例如系统自带的
+ * C:\Windows\System32\notepad.exe 和开始菜单快捷方式指向的 C:\WINDOWS\system32\notepad.exe)时,
+ * `cua-driver mcp` 会以 "application resources repeat an identity" 拒绝启动——v0.1.5 在 Windows 上
+ * 就是这样陷入 MCP 重连循环、不停弹出控制台窗口的。
+ */
+export function uniqueApps(apps: CuaApp[], platform: NodeJS.Platform = process.platform): CuaApp[] {
+ const seen = new Set<string>();
+ const out: CuaApp[] = [];
+ for (const a of apps) {
+ const key = "executable" in a ? `x:${platform === "win32" || platform === "darwin" ? a.executable.toLowerCase() : a.executable}` : `b:${a.bundle_id.toLowerCase()}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push(a);
+ }
+ return out;
+}
+
+/** Windows:几个系统自带程序 + PowerShell 列出的开始菜单快捷方式目标(只留存在的 .exe,按路径不分大小写去重)。 */
+export function windowsAppsFrom(
+ env: Record<string, string | undefined>,
+ shortcutTargets: string,
+ exists: (p: string) => boolean = fs.existsSync,
+ canon: (p: string) => string = canonicalPath,
+): CuaApp[] {
+ const found: string[] = [];
const win = env.SystemRoot || env.WINDIR || "C:\\Windows";
for (const p of ["notepad.exe", "mspaint.exe", "write.exe", "explorer.exe"].map((x) => (x === "explorer.exe" ? path.win32.join(win, x) : path.win32.join(win, "System32", x)))) {
- if (fs.existsSync(p)) out.add(p);
+ if (exists(p)) found.push(canon(p));
}
- try {
- const ps =
- "$s=New-Object -ComObject WScript.Shell;" +
- "$d=@([Environment]::GetFolderPath('CommonStartMenu'),[Environment]::GetFolderPath('StartMenu'));" +
- "Get-ChildItem -Path $d -Recurse -Filter *.lnk -ErrorAction SilentlyContinue|ForEach-Object{try{$s.CreateShortcut($_.FullName).TargetPath}catch{}}";
- const text = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ps], { encoding: "utf8", timeout: 20000, windowsHide: true });
- for (const line of text.split(/\r?\n/)) {
- const p = line.trim();
- if (/\.exe$/i.test(p) && fs.existsSync(p)) out.add(p);
- }
- } catch {
- /* PowerShell 不可用时只用系统程序 */
+ for (const line of shortcutTargets.split(/\r?\n/)) {
+ const p = line.trim();
+ if (/\.exe$/i.test(p) && exists(p)) found.push(canon(p));
}
- return [...out].sort().map((executable) => ({ executable }));
+ const apps = found.sort((a, b) => a.localeCompare(b)).map((executable) => ({ executable }));
+ return uniqueApps(apps, "win32");
+}
+
+/** Windows:开始菜单快捷方式指向的 .exe + 几个系统自带程序(未在真机验证)。异步,不阻塞主进程。 */
+export async function windowsApps(env: Record<string, string | undefined>): Promise<CuaApp[]> {
+ const text = await new Promise<string>((resolve) =>
+ execFile("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WIN_SHORTCUTS_PS], { encoding: "utf8", timeout: 20000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (err, stdout) =>
+ resolve(err ? "" : String(stdout)), // PowerShell 不可用时只用系统程序
+ ),
+ );
+ return windowsAppsFrom(env, text);
}
-export function discoverApps(platform: NodeJS.Platform = process.platform, env = process.env, homedir = os.homedir()): CuaApp[] {
- const self = process.execPath;
- const apps = platform === "linux" ? linuxDesktopApps(env, homedir) : platform === "darwin" ? macApps(homedir) : platform === "win32" ? windowsApps(env) : [];
- return apps.filter((a) => !("executable" in a) || a.executable !== self).slice(0, 800);
+export async function discoverApps(platform: NodeJS.Platform = process.platform, env = process.env, homedir = os.homedir()): Promise<CuaApp[]> {
+ const self = platform === "win32" ? process.execPath.toLowerCase() : process.execPath;
+ const apps = platform === "linux" ? linuxDesktopApps(env, homedir) : platform === "darwin" ? macApps(homedir) : platform === "win32" ? await windowsApps(env) : [];
+ return uniqueApps(apps, platform)
+ .filter((a) => !("executable" in a) || (platform === "win32" ? a.executable.toLowerCase() : a.executable) !== self)
+ .slice(0, 800);
+}
+
+let appsCache: { at: number; apps: Promise<CuaApp[]> } | undefined;
+/** 已安装应用清单(10 分钟内复用):每次重启代理进程都重扫一遍开始菜单太慢。 */
+export function discoverAppsCached(ttlMs = 10 * 60_000): Promise<CuaApp[]> {
+ if (!appsCache || Date.now() - appsCache.at > ttlMs) {
+ const apps = discoverApps().catch(() => [] as CuaApp[]);
+ appsCache = { at: Date.now(), apps };
+ }
+ return appsCache.apps;
}
export interface CuaConfig {
diff --git a/src/agent/host.ts b/src/agent/host.ts
index ca51b27..2a7f062 100644
--- a/src/agent/host.ts
+++ b/src/agent/host.ts
@@ -2,13 +2,13 @@ import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { pathToFileURL } from "node:url";
-import { logger } from "../log.js";
+import { lineLogger, logger } from "../log.js";
import type { Store } from "../store/db.js";
import type { AgentBridge } from "./bridge.js";
import os from "node:os";
import { findAppRoot } from "../magpie/supervisor.js";
import { adaptSkill, mcpPatchLines, resolveComputerUse, type CuResolved } from "./computer-use.js";
-import { cuaConfig, cuaMcpEnv, discoverApps } from "./cua-driver.js";
+import { cuaConfig, cuaMcpEnv, discoverAppsCached, type CuaApp } from "./cua-driver.js";
import { DEFAULT_SETTINGS, permissionMode, type BotSettings } from "./settings.js";
const log = logger("agent.host");
@@ -131,10 +131,48 @@ export interface AgentHostOptions {
settings?: () => BotSettings;
/** 单回合上限,超时则重启子进程(SDK 无中断接口) */
turnTimeoutMs?: number;
+ /** 需要让用户看到的提示(界面通知) */
+ onNotice?: (text: string) => void;
}
export type HostState = "stopped" | "starting" | "running" | "backoff" | "error";
+/** 传给 Windows 上代理子进程的系统变量(都不是密钥;值来自本进程环境) */
+export const WIN_SYSTEM_ENV = [
+ "SystemRoot",
+ "SystemDrive",
+ "windir",
+ "ComSpec",
+ "PATHEXT",
+ "TEMP",
+ "TMP",
+ "APPDATA",
+ "LOCALAPPDATA",
+ "ProgramData",
+ "ProgramFiles",
+ "ProgramFiles(x86)",
+ "ProgramW6432",
+ "CommonProgramFiles",
+ "CommonProgramFiles(x86)",
+ "CommonProgramW6432",
+ "ALLUSERSPROFILE",
+ "PUBLIC",
+ "OS",
+ "PROCESSOR_ARCHITECTURE",
+ "PROCESSOR_IDENTIFIER",
+ "NUMBER_OF_PROCESSORS",
+ "USERNAME",
+ "USERDOMAIN",
+ "COMPUTERNAME",
+];
+
+/** 子进程生命周期事件(故障排查的"测试代理"按它判断卡在哪一步) */
+export type HostEvent =
+ | { type: "spawned"; pid: number | undefined }
+ | { type: "initialized"; pid: number | undefined; ms: number }
+ | { type: "failed"; message: string }
+ | { type: "exit"; pid: number | undefined; code: number | null; signal: string | null };
+
const MODEL_LIMITS: Array<[RegExp, number, number]> = [
[/grok-4/i, 256_000, 32_000],
[/claude/i, 200_000, 32_000],
@@ -209,6 +247,20 @@ export class AgentHost {
private stopped = false;
/** callId → 工具调用(供审批提示展示命令) */
readonly calls = new Map<string, { name: string; args: string; at: number }>();
+ /** DSH 子进程 stderr 的最后几十行(已脱敏),故障排查页展示 */
+ readonly stderrTail: string[] = [];
+ /** 最近一次子进程退出 */
+ lastExit: { pid: number | undefined; code: number | null; signal: string | null; at: number } | undefined;
+ /** 当前子进程启动完成的时间 */
+ startedAt = 0;
+ /** 正在启动:开始时间与当前阶段(故障排查页显示进度) */
+ startingSince = 0;
+ initStage = "";
+ /** 最近一次成功初始化(子进程拉起到 initialize 返回)的耗时 */
+ lastInitMs = 0;
+ private initFailures = 0;
+ private retryAfter = 0;
+ private listeners = new Set<(e: HostEvent) => void>();
constructor(private o: AgentHostOptions) {}
@@ -225,7 +277,39 @@ export class AgentHost {
return this.harness?.client?.child?.pid;
}
- private writePatch(model: string): string {
+ /** 订阅生命周期事件;返回取消函数 */
+ on(fn: (e: HostEvent) => void): () => void {
+ this.listeners.add(fn);
+ return () => this.listeners.delete(fn);
+ }
+ private emit(e: HostEvent): void {
+ for (const fn of this.listeners) {
+ try {
+ fn(e);
+ } catch {
+ /* ignore */
+ }
+ }
+ }
+
+ /** 接上子进程的 stderr(逐行写日志 + 保留尾部)与退出事件。sdk-client 自己也在读 stderr,两边互不影响。 */
+ private watchChild(child: any): void {
+ if (!child) return;
+ const pid: number | undefined = child.pid;
+ const lines = lineLogger(`dsh:${this.o.botId}`, "info", (line) => {
+ this.stderrTail.push(line);
+ if (this.stderrTail.length > 80) this.stderrTail.splice(0, this.stderrTail.length - 80);
+ });
+ child.stderr?.on?.("data", (d: Buffer | string) => lines.push(d));
+ child.once?.("exit", (code: number | null, signal: string | null) => {
+ lines.flush();
+ this.lastExit = { pid, code, signal, at: Date.now() };
+ log.info("dsh process exited", { bot: this.o.botId, pid, code, signal });
+ this.emit({ type: "exit", pid, code, signal });
+ });
+ }
+
+ private writePatch(model: string, apps: CuaApp[] = []): string {
const lim = MODEL_LIMITS.find(([re]) => re.test(model)) ?? [/./, 128_000, 16_000];
const plugin = path.join(this.o.runtimeDir, "plugins", "amb-bridge.mjs");
const memory = path.join(this.o.runtimeDir, "plugins", "amb-memory.mjs");
@@ -262,7 +346,7 @@ export class AgentHost {
" name: '@deepseek-ai/dsh-tool-ask-user'",
" - id: amb-present",
" name: '@deepseek-ai/dsh-tool-present'",
- ...this.computerUseLines(),
+ ...this.computerUseLines(apps),
"",
].join("\n");
const f = path.join(this.home, "amb.patch.yml");
@@ -285,7 +369,7 @@ export class AgentHost {
* Computer Use:插入 mcp-client(Cua Driver 经 amb-cua-mcp.mjs,或 macOS 上的 Codex 桥;都用宿主自己的
* node/Electron 运行),并写入对应的 SKILL.md。默认所有操作自动执行;只有设置为 ask-input 时才加载审批闸门。
*/
- private computerUseLines(): string[] {
+ private computerUseLines(apps: CuaApp[]): string[] {
const skillDir = path.join(this.home, "skills", "computer-use");
const st = this.computerUseActive();
this.cuReadTools = st ? st.readTools.join(",") : "";
@@ -301,7 +385,7 @@ export class AgentHost {
lines = mcpPatchLines(st.codex, process.execPath, yamlStr);
} else {
fs.writeFileSync(path.join(skillDir, "SKILL.md"), CUA_SKILL);
- lines = this.cuaLines(st);
+ lines = this.cuaLines(st, apps);
}
} catch (e) {
log.warn("computer-use setup failed", { err: String(e) });
@@ -314,10 +398,10 @@ export class AgentHost {
}
/** Cua Driver:写配置(清单在 amb-cua-mcp.mjs 启动时按本平台实有工具生成),返回 mcp-client 配置行。 */
- private cuaLines(st: CuResolved): string[] {
+ private cuaLines(st: CuResolved, apps: CuaApp[]): string[] {
const dir = path.join(this.home, "cua");
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
- const cfg = cuaConfig(st.cua, dir, { readonly: this.settings().permission === "readonly", apps: discoverApps() });
+ const cfg = cuaConfig(st.cua, dir, { readonly: this.settings().permission === "readonly", apps });
const cfgFile = path.join(dir, "config.json");
fs.writeFileSync(cfgFile, JSON.stringify(cfg, null, 2), { mode: 0o600 });
const env = cuaMcpEnv(process.env, os.homedir(), cfgFile);
@@ -333,6 +417,10 @@ export class AgentHost {
...Object.entries(env).map(([k, v]) => ` ${k}: ${yamlStr(v)}`),
" toolCallTimeoutMs: 120000",
" failOnStartupError: false",
+ // 默认最多重连 10 次(约 2.5 分钟):驱动起不来时每次都要重新拉起 cua-driver,3 次足够分辨偶发与必然
+ " reconnect:",
+ " maxAttempts: 3",
+ " initialDelayMs: 2000",
];
}
@@ -399,6 +487,15 @@ exec "$REAL" "$@"
AMB_BRIDGE_TOKEN: this.o.bridge.token,
AMB_BOT_ID: this.o.botId,
};
+ if (process.platform === "win32") {
+ // Windows:系统目录类变量不是密钥,但工具进程离不开(npm/pip 找 APPDATA,脚本找 ProgramFiles、ComSpec…)。
+ // libuv 只自动补 SystemRoot/TEMP/USERPROFILE 等少数几个。TZ 只认 POSIX 写法,不设,用系统时区。
+ for (const k of WIN_SYSTEM_ENV) {
+ const v = process.env[k];
+ if (v) env[k] = v;
+ }
+ if (!process.env.TZ) delete env.TZ;
+ }
if (process.versions.electron) env.ELECTRON_RUN_AS_NODE = "1";
if (process.env.AMB_DSH_LOG_LEVEL) env.DSH_LOG_LEVEL = process.env.AMB_DSH_LOG_LEVEL;
return env;
@@ -430,7 +527,7 @@ exec "$REAL" "$@"
let cmd = "";
try {
if (process.platform === "linux") cmd = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ");
- else if (process.platform === "darwin") cmd = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
+ else if (process.platform === "darwin") cmd = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
} catch {
/* ignore */
}
@@ -446,6 +543,10 @@ exec "$REAL" "$@"
async ensure(model: string): Promise<SdkHarness> {
if (this.stopped) throw new Error("agent host stopped");
+ // 连续启动失败后不再每条消息都重试一遍(每次都要等满初始化超时):直到手动重启或冷却结束
+ if (!this.harness && !this.starting && this.state === "error" && Date.now() < this.retryAfter) {
+ throw new Error(`代理进程启动失败,${Math.ceil((this.retryAfter - Date.now()) / 60_000)} 分钟后再试(或在 设置 → 故障排查 里重启代理进程):${this.lastError}`);
+ }
if (this.harness && this.model !== model && this.active === 0) {
log.info("model changed, restarting dsh", { bot: this.o.botId, model });
await this.closeHarness();
@@ -459,6 +560,30 @@ exec "$REAL" "$@"
return this.starting;
}
+ /** 本机上一次成功启动的耗时;没有记录 = 第一次启动(冷启动:杀毒软件逐个扫描运行时文件,可能要几分钟) */
+ private get initRecordFile(): string {
+ return path.join(this.o.dataDir, "dsh", ".init.json");
+ }
+ private readInitRecord(): { ms: number; at: number } | undefined {
+ try {
+ const j = JSON.parse(fs.readFileSync(this.initRecordFile, "utf8"));
+ return Number(j?.ms) > 0 ? { ms: Number(j.ms), at: Number(j.at) || 0 } : undefined;
+ } catch {
+ return undefined;
+ }
+ }
+ /** 初始化超时:第一次 10 分钟,之后 3 分钟(AMB_DSH_INIT_TIMEOUT_MS 可覆盖) */
+ initTimeoutMs(): number {
+ const env = Number(process.env.AMB_DSH_INIT_TIMEOUT_MS);
+ if (env > 0) return env;
+ return this.readInitRecord() ? 180_000 : 600_000;
+ }
+
+ private stage(name: string, t0: number, extra: Record<string, unknown> = {}): void {
+ this.initStage = name;
+ log.info(`dsh start: ${name}`, { bot: this.o.botId, ms: Date.now() - t0, ...extra });
+ }
+
private async spawn(model: string): Promise<SdkHarness> {
const wait = this.nextStartAt - Date.now();
if (wait > 0) {
@@ -466,57 +591,110 @@ exec "$REAL" "$@"
await new Promise((r) => setTimeout(r, wait));
}
this.state = "starting";
- fs.mkdirSync(this.home, { recursive: true, mode: 0o700 });
- fs.mkdirSync(this.workspace, { recursive: true });
- this.reapStale();
- await this.o.bridge.start();
- const sdk = await loadSdk(this.o.runtimeDir);
- const patch = this.writePatch(model);
- this.sig = this.settingsSig();
- const h = new sdk.DeepSeekHarness({
- profile: "sdk",
- patches: [patch],
- dshHome: this.home,
- env: this.env(),
- cwd: this.workspace,
- processCwd: this.workspace,
- provider: "magpie",
- model,
- initializeTimeoutMs: 90_000,
- shutdownTimeoutMs: 3000,
- });
+ this.startingSince = Date.now();
+ this.initStage = "prepare";
+ const t0 = Date.now();
+ let h: SdkHarness | undefined;
+ let watchdog: NodeJS.Timeout | undefined;
try {
- await h.start();
- } catch (e) {
- this.onFailure(e as Error);
+ fs.mkdirSync(this.home, { recursive: true, mode: 0o700 });
+ fs.mkdirSync(this.workspace, { recursive: true });
+ this.reapStale();
+ await this.o.bridge.start();
+ this.stage("bridge ready", t0, { port: this.o.bridge.port });
+ const sdk = await loadSdk(this.o.runtimeDir);
+ this.stage("sdk loaded", t0);
+ // 应用清单(Computer Use 的能力清单用)异步扫描并缓存,不阻塞主进程
+ const cu = this.computerUseActive();
+ const apps = cu && cu.backend === "cua" ? await discoverAppsCached() : [];
+ const patch = this.writePatch(model, apps);
+ this.sig = this.settingsSig();
+ const timeoutMs = this.initTimeoutMs();
+ this.stage("patch written", t0, { computerUse: cu ? cu.backend : "off", apps: apps.length, initTimeoutMs: timeoutMs });
+ h = new sdk.DeepSeekHarness({
+ profile: "sdk",
+ patches: [patch],
+ dshHome: this.home,
+ env: this.env(),
+ cwd: this.workspace,
+ processCwd: this.workspace,
+ provider: "magpie",
+ model,
+ initializeTimeoutMs: timeoutMs,
+ shutdownTimeoutMs: 3000,
+ });
+ // start() 同步拉起子进程,然后才等 initialize:此时就能接上 stderr,启动阶段的报错也不会漏
+ const tSpawn = Date.now();
+ const started = h.start();
+ const spawned = h.client?.child;
+ this.watchChild(spawned);
+ this.stage("child spawned", t0, { pid: spawned?.pid, model, runtime: this.o.runtimeDir });
+ this.initStage = "initializing";
+ this.emit({ type: "spawned", pid: spawned?.pid });
+ // 初始化迟迟不回来时每 15 秒记一条,带上最近的 stderr:冷启动慢还是卡住,日志里一眼能看出来
+ watchdog = setInterval(
+ () => log.warn("dsh still initializing", { bot: this.o.botId, pid: spawned?.pid, waitedMs: Date.now() - tSpawn, timeoutMs, lastStderr: this.stderrTail.at(-1) }),
+ 15_000,
+ );
+ await started;
+ clearInterval(watchdog);
+ const initMs = Date.now() - tSpawn;
+ this.lastInitMs = initMs;
+ this.emit({ type: "initialized", pid: spawned?.pid, ms: initMs });
try {
- await h.close();
+ fs.writeFileSync(this.initRecordFile, JSON.stringify({ ms: initMs, at: Date.now() }));
} catch {
/* ignore */
}
+ const child = h.client?.child;
+ if (child?.pid) fs.writeFileSync(this.pidFile, String(child.pid));
+ const harness = h;
+ child?.once?.("exit", (code: number | null, sig: string | null) => {
+ if (this.harness !== harness) return;
+ this.harness = undefined;
+ this.opened.clear();
+ if (this.stopped) return;
+ this.onFailure(new Error(`dsh exited (code=${code} signal=${sig})`));
+ });
+ this.harness = h;
+ this.model = model;
+ this.state = "running";
+ this.initStage = "";
+ this.lastError = "";
+ this.initFailures = 0;
+ this.startedAt = Date.now();
+ log.info("dsh started", { bot: this.o.botId, pid: child?.pid, model, ms: Date.now() - t0, initMs });
+ return h;
+ } catch (e) {
+ clearInterval(watchdog);
+ this.emit({ type: "failed", message: (e as Error).message });
+ this.initFailures++;
+ this.onFailure(e as Error);
+ if (h) {
+ try {
+ await h.close();
+ } catch {
+ /* ignore */
+ }
+ }
throw e;
+ } finally {
+ this.startingSince = 0;
}
- const child = h.client?.child;
- if (child?.pid) fs.writeFileSync(this.pidFile, String(child.pid));
- child?.once?.("exit", (code: number | null, sig: string | null) => {
- if (this.harness !== h) return;
- this.harness = undefined;
- this.opened.clear();
- if (this.stopped) return;
- this.onFailure(new Error(`dsh exited (code=${code} signal=${sig})`));
- });
- this.harness = h;
- this.model = model;
- this.state = "running";
- this.lastError = "";
- log.info("dsh started", { bot: this.o.botId, pid: child?.pid, model });
- return h;
}
private onFailure(e: Error): void {
this.failures++;
this.restarts++;
this.lastError = e.message.slice(0, 500);
+ if (this.initFailures >= 2) {
+ // 连续两次起不来:先停 10 分钟(期间纯对话照常),不再每条消息都等一遍初始化
+ this.state = "error";
+ this.retryAfter = Date.now() + 10 * 60_000;
+ log.error("dsh failed to start twice; agent paused for 10 minutes (plain chat still works)", { bot: this.o.botId, message: this.lastError });
+ this.o.onNotice?.(`代理进程连续两次启动失败,已暂停 10 分钟(期间用纯对话回复)。可在 设置 → 故障排查 查看原因并重启代理进程。原因:${this.lastError.slice(0, 200)}`);
+ return;
+ }
const delay = Math.min(30_000, 1000 * 2 ** Math.min(this.failures - 1, 5));
this.nextStartAt = Date.now() + delay;
this.state = "backoff";
@@ -616,6 +794,43 @@ exec "$REAL" "$@"
return { state: this.state, pid: this.pid, model: this.model, restarts: this.restarts, lastError: this.lastError, workspace: this.workspace, activeTurns: this.active };
}
+ /** 故障排查用的完整状态(含 stderr 尾部与最近一次退出) */
+ diagnostics(): Record<string, unknown> {
+ const rec = this.readInitRecord();
+ return {
+ ...this.status(),
+ startingForMs: this.startingSince ? Date.now() - this.startingSince : undefined,
+ initStage: this.initStage || undefined,
+ initTimeoutMs: this.initTimeoutMs(),
+ lastInitMs: this.lastInitMs || rec?.ms,
+ firstStart: !rec,
+ retryInMs: this.state === "error" ? Math.max(0, this.retryAfter - Date.now()) : undefined,
+ startedAt: this.startedAt || undefined,
+ lastExit: this.lastExit,
+ nextStartInMs: this.state === "backoff" ? Math.max(0, this.nextStartAt - Date.now()) : undefined,
+ stderrTail: this.stderrTail.slice(-50),
+ };
+ }
+
+ /** 清掉失败退避与暂停(故障排查时立即重试,不等退避时间) */
+ resetBackoff(): void {
+ this.nextStartAt = 0;
+ this.retryAfter = 0;
+ if (this.state === "error") this.state = "stopped";
+ }
+
+ /** 手动重启:关掉子进程、清掉退避与暂停,下一条消息(或 ensure)重新拉起。 */
+ async restart(): Promise<void> {
+ await this.starting?.catch(() => undefined);
+ await this.closeHarness();
+ this.failures = 0;
+ this.initFailures = 0;
+ this.retryAfter = 0;
+ this.nextStartAt = 0;
+ this.state = "stopped";
+ log.info("dsh restarted by user", { bot: this.o.botId });
+ }
+
async stop(): Promise<void> {
this.stopped = true;
await this.starting?.catch(() => undefined);
diff --git a/src/agent/manager.ts b/src/agent/manager.ts
index dca264e..a6d373a 100644
--- a/src/agent/manager.ts
+++ b/src/agent/manager.ts
@@ -37,6 +37,8 @@ export interface AgentManagerOptions {
reviewDelayMs?: number;
/** 生图 / 生视频(amb-media 插件经 bridge 调用);缺省时工具返回不可用 */
media?: MediaService;
+ /** 需要让用户看到的提示(代理进程起不来等) */
+ onNotice?: (text: string) => void;
}
function deferred<T>() {
@@ -103,6 +105,7 @@ export class AgentManager {
store: this.o.store,
turnTimeoutMs: this.o.turnTimeoutMs,
settings: () => this.settings(botId),
+ onNotice: this.o.onNotice,
});
this.hosts.set(botId, h);
}
@@ -137,7 +140,32 @@ export class AgentManager {
return this.o.store.getBot(botId)?.settings ?? DEFAULT_SETTINGS;
}
+ /**
+ * 预热:应用启动后就在后台拉起代理进程,第一次启动(冷启动)可能要几分钟,不该等到用户发第一条消息。
+ * 失败只记日志(ensure 自己会记录并退避),不抛错。
+ */
+ prewarm(botId: string, model: string): void {
+ if (!this.available || !model) return;
+ const h = this.host(botId);
+ if (h.state === "running" || h.state === "starting") return;
+ log.info("prewarming agent host", { bot: botId, model });
+ void h.ensure(model).catch(() => undefined);
+ }
+
+ /** 会话 → 正在进行的回合开始时间(/status 与故障排查用:后来的消息排在它后面) */
+ readonly turnsInProgress = new Map<string, { botId: string; since: number }>();
+
async runTurn(botId: string, input: { conversationId: string; text: string; model: string; observer?: TurnObserver }) {
+ const conv = input.conversationId;
+ this.turnsInProgress.set(conv, { botId, since: Date.now() });
+ try {
+ return await this.runTurnInner(botId, input);
+ } finally {
+ this.turnsInProgress.delete(conv);
+ }
+ }
+
+ private async runTurnInner(botId: string, input: { conversationId: string; text: string; model: string; observer?: TurnObserver }) {
const conv = input.conversationId;
const gate = this.gates.get(conv);
if (gate) await withTimeout(gate, 240_000, undefined);
@@ -426,6 +454,39 @@ 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 }> } {
+ 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 })),
+ };
+ }
+
+ /** 一句话的代理状态(/status 用;不等待、不拉起进程) */
+ hostSummary(botId: string): string {
+ if (!this.available) return "";
+ const h = this.hosts.get(botId);
+ if (!h || h.state === "stopped") return "代理进程:未启动(收到消息时启动)";
+ const d = h.diagnostics() as any;
+ if (h.state === "running") return `代理进程:运行中(pid ${h.pid ?? "?"}${d.lastInitMs ? `,启动用时 ${Math.round(d.lastInitMs / 1000)} 秒` : ""})`;
+ if (h.state === "starting") {
+ const s = Math.round((d.startingForMs ?? 0) / 1000);
+ return `代理进程:正在启动(已 ${s} 秒${d.firstStart ? ";第一次启动可能要几分钟" : ""})`;
+ }
+ if (h.state === "backoff") return `代理进程:上次启动失败,稍后重试(${h.lastError.slice(0, 120)})`;
+ return `代理进程:启动失败,已暂停(${h.lastError.slice(0, 120)})`;
+ }
+
+ /** 故障排查的"重启代理进程":关掉(全部或指定机器人的)子进程并清掉退避;返回重启了哪些。 */
+ async restartHosts(botId?: string): Promise<string[]> {
+ const ids = [...this.hosts.keys()].filter((id) => !botId || id === botId);
+ await Promise.all(ids.map((id) => this.hosts.get(id)!.restart()));
+ return ids;
+ }
+
private resolveConversation(botId: string, sessionId: string): string {
const c = this.o.store.conversationForSession(sessionId);
if (c) return c;
diff --git a/src/app.ts b/src/app.ts
index f3e38ca..d2b052f 100644
--- a/src/app.ts
+++ b/src/app.ts
@@ -13,7 +13,7 @@ import { LarkTransport, type FeishuTransport } from "./channels/feishu/transport
import { WeixinChannel } from "./channels/weixin/channel.js";
import { WeixinLogin } from "./channels/weixin/login.js";
import { startWebServer, type WebServer } from "./web/server.js";
-import { logger, mask } from "./log.js";
+import { initFileLog, logFilePath, logger, mask, registerSecret } from "./log.js";
import { AgentManager } from "./agent/manager.js";
import { normalizeSettings } from "./agent/settings.js";
import { locateDshRuntime } from "./agent/host.js";
@@ -86,6 +86,8 @@ export interface AppOptions {
noWeb?: boolean;
/** 登录二维码是否打印到终端 */
printQrToTerminal?: boolean;
+ /** 写 <dataDir>/logs/app.log(默认 true) */
+ fileLog?: boolean;
}
interface BotChannels {
@@ -107,12 +109,30 @@ export class App {
desktop: DesktopHooks | undefined;
/** Modelflare 账户(登录、余额、预算);start() 时创建,桌面外壳的钥匙串那时已就绪 */
account!: AccountManager;
+ /** 故障排查页最近一次"测试模型 / 测试代理"的结果(复制诊断信息时带上) */
+ lastDiagnostics: { model?: import("./diagnostics.js").ModelTestResult; agent?: import("./diagnostics.js").AgentTestResult } = {};
private notices: Array<{ at: number; level: "info" | "warn"; text: string }> = [];
private accountTimer: NodeJS.Timeout | undefined;
private picksTimer: NodeJS.Timeout | undefined;
private modelInfoCache: { at: number; data: Record<string, ModelInfo> } | undefined;
constructor(readonly config: AppConfig, readonly opts: AppOptions = {}) {
+ // 日志文件:<dataDir>/logs/app.log(打包后的桌面版看不到 stdout,故障排查全靠它)
+ if (opts.fileLog !== false) initFileLog(path.join(config.dataDir, "logs"));
+ registerSecret(config.ui.token);
+ registerSecret(config.magpie.externalApiKey);
+ log.info(`anymodel bot ${appVersion()} starting`, {
+ platform: process.platform,
+ arch: process.arch,
+ os: os.release(),
+ electron: process.versions.electron,
+ node: process.versions.node,
+ pid: process.pid,
+ dataDir: config.dataDir,
+ gateway: config.magpie.mode,
+ agent: config.agent.mode,
+ log: logFilePath(),
+ });
this.store = new Store(path.join(config.dataDir, "anymodel.db"));
if (config.magpie.mode === "managed") {
this.magpie = new MagpieSupervisor({ dataDir: config.dataDir, binPath: config.magpie.binPath || undefined });
@@ -150,6 +170,7 @@ export class App {
workspace: (botId) => path.join(config.dataDir, "workspaces", botId),
})
: undefined,
+ onNotice: (text) => this.notice("warn", text),
});
this.runtime = new BotRuntime({
agent: this.agent,
@@ -162,6 +183,22 @@ export class App {
});
}
+ /**
+ * 启动后在后台拉起默认机器人的代理进程(AMB_AGENT_PREWARM=0 关闭)。第一次启动要加载上万个运行时文件,
+ * 杀毒软件逐个扫描时可能要几分钟;提前做,用户发第一条消息时多半已经就绪。
+ */
+ async prewarmAgent(): Promise<void> {
+ if (process.env.AMB_AGENT_PREWARM === "0" || this.opts.noWeb || !this.agent.available) return;
+ const bot = this.store.listBots()[0];
+ if (!bot) return;
+ try {
+ const model = bot.defaultModel || this.config.llm.defaultModel || (await this.runtime.listModels(true).catch(() => [] as string[]))[0] || "";
+ if (model) this.agent.prewarm(bot.id, this.routeModel(bot.id, model));
+ } catch (e) {
+ log.warn("agent prewarm skipped", { message: (e as Error).message });
+ }
+ }
+
/** 每个经 Modelflare 的请求都带的请求头(调用归因) */
requestHeaders(): Record<string, string> {
return skillHeader(appVersion());
@@ -326,6 +363,7 @@ export class App {
this.picksTimer = setInterval(() => void this.syncModelPicks(), 3600_000);
this.picksTimer.unref();
}
+ void this.prewarmAgent();
if (this.magpie && !this.opts.noWeb) {
// 余额与低余额提醒:启动后读一次,之后每 5 分钟一次
const tick = () => {
@@ -378,6 +416,8 @@ export class App {
this.modelInfoCache = undefined;
this.setModelflareLineConfig(line);
await this.runtime.listModels(true).catch(() => []);
+ // 刚连上:现在才有模型可用,把代理进程也提前拉起来(首次启动可能要几分钟)
+ void this.prewarmAgent();
return r;
}
@@ -419,6 +459,8 @@ export class App {
async startBot(botId: string): Promise<void> {
const bot = this.store.getBot(botId);
if (!bot) return;
+ registerSecret(bot.feishuAppSecret);
+ registerSecret(this.store.getWeixinAccount(botId)?.botToken);
const ch: BotChannels = this.channels.get(botId) ?? {};
this.channels.set(botId, ch);
if (bot.feishuAppId && bot.feishuAppSecret && !ch.feishu) {
diff --git a/src/core/runtime.ts b/src/core/runtime.ts
index df00504..a1a91d3 100644
--- a/src/core/runtime.ts
+++ b/src/core/runtime.ts
@@ -83,9 +83,12 @@ export class BotRuntime {
const routed = this.opts.route ? this.opts.route(bot.id, model) : model;
const agent = this.opts.agent;
+ let note = "";
if (agent?.available) {
const handled = await this.handleAgent(agent, bot.id, conv.id, text, routed, bot.systemPrompt, out);
- if (handled) return;
+ if (handled === true) return;
+ // 代理进程还在启动(第一次可能要几分钟):这条消息先由模型直接回答,不让用户干等
+ if (handled === "starting") note = "(代理还在启动,这条消息先由模型直接回答;启动完成后会自动用回代理。)";
}
store.addMessage(conv.id, "user", text);
@@ -104,7 +107,7 @@ export class BotRuntime {
});
const finalText = full || acc || "(模型没有返回内容)";
store.addMessage(conv.id, "assistant", finalText);
- await out.apply({ type: "stream.finish", text: finalText });
+ await out.apply({ type: "stream.finish", text: note ? `${note}\n\n${finalText}` : finalText });
} catch (e) {
const err = e as Error & { status?: number };
if (opts.signal?.aborted) {
@@ -122,13 +125,33 @@ export class BotRuntime {
/** 渠道在进入每会话串行队列之前调用:处理审批回复(y 1234 / n 1234)与提问回答。 */
interceptReply(ev: InboundEvent): { handled: boolean; ack?: string } {
- const agent = this.opts.agent;
- if (!agent) return { handled: false };
const text = eventText(ev);
const convId = `${ev.botId}:${ev.channel}:${ev.conversation.id}`;
+ // /status、/help 只读、不碰模型和代理进程:不进会话队列,不会排在一个卡住或正在启动代理的回合后面
+ const cmd = text.trim().toLowerCase();
+ if (cmd === "/status" || cmd === "/help") {
+ const bot = this.opts.store.getBot(ev.botId);
+ 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;
+ if (!agent) return { handled: false };
return agent.approvals.handleReply(convId, text, `${ev.channel}:${ev.sender.id}`);
}
+ /** /status 的内容:只读本地状态,立即返回 */
+ statusText(botId: string, convId: string, convModel: string, botModel: string): string {
+ const m = convModel || botModel || this.opts.defaultModel() || "(自动:第一个可用模型)";
+ const a = this.opts.agent;
+ const mode = a?.available ? "代理模式(DeepSeek Harness,工作区沙箱)" : "纯对话模式";
+ const pend = a ? a.approvals.pending(convId).map((r) => `${r.kind === "approval" ? "待批准" : "待回答"} ${r.code}`) : [];
+ const cui = a?.available ? a.computerUse(botId) : undefined;
+ const cu = cui ? [`电脑操作:${cui.backend === "codex" ? "Codex 桥" : "Cua Driver"},${cui.active ? "已启用" : "未启用"}——${cui.reason}`, ...(cui.notice && cui.enabled ? [cui.notice] : [])] : [];
+ const host = a?.available ? [a.hostSummary(botId)] : [];
+ const turn = a?.turnsInProgress.get(convId);
+ const busy = turn ? [`本会话上一条消息还在处理(已 ${Math.round((Date.now() - turn.since) / 1000)} 秒),新消息会排在它后面`] : [];
+ return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...host, ...busy, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
+ }
+
/** 卡片按钮回调:批准/拒绝/选择选项。 */
cardAction(botId: string, value: Record<string, string>, by: string): { toast: string; ok: boolean } {
const agent = this.opts.agent;
@@ -146,8 +169,11 @@ export class BotRuntime {
return { toast: "未知操作", ok: false };
}
- /** 代理回合;返回 false 表示宿主不可用且尚无任何输出,调用方回退到纯对话。 */
- private async handleAgent(agent: AgentManager, botId: string, convId: string, text: string, model: string, systemPrompt: string, out: ReplySession): Promise<boolean> {
+ /**
+ * 代理回合;返回 false 表示宿主不可用且尚无任何输出(调用方回退到纯对话),
+ * "starting" 表示代理进程在等待时限内没有启动好(同样回退,启动在后台继续)。
+ */
+ private async handleAgent(agent: AgentManager, botId: string, convId: string, text: string, model: string, systemPrompt: string, out: ReplySession): Promise<boolean | "starting"> {
const { store } = this.opts;
let visible = false;
const unbind = agent.approvals.bindSink(convId, async (row) => {
@@ -156,7 +182,39 @@ export class BotRuntime {
});
await out.apply({ type: "typing", on: true });
await out.apply({ type: "stream.start" });
+ // 代理进程还没就绪(第一次启动可能要几分钟):先说清楚在等什么,而不是一直"思考中"。最终回复会替换这段文字
+ const host = agent.host(botId);
+ let startup: NodeJS.Timeout | undefined;
+ if (host.state !== "running") {
+ const since = Date.now();
+ const show = () => {
+ if (host.state === "running") {
+ clearInterval(startup);
+ return void out.apply({ type: "stream.update", text: "代理已就绪,正在处理…" });
+ }
+ const s = Math.round((Date.now() - since) / 1000);
+ const first = (host.diagnostics() as any).firstStart;
+ void out.apply({ type: "stream.update", text: `代理正在启动…${s >= 5 ? `(已 ${s} 秒)` : ""}${first ? "首次启动可能需要几分钟。" : ""}` });
+ };
+ show();
+ startup = setInterval(show, 5000);
+ }
try {
+ if (host.state !== "running") {
+ const waitMs = Number(process.env.AMB_AGENT_START_WAIT_MS) || 90_000;
+ let timer: NodeJS.Timeout | undefined;
+ const ready = await Promise.race([
+ host.ensure(model).then(
+ () => true,
+ () => false,
+ ),
+ new Promise<boolean>((r) => (timer = setTimeout(() => r(false), waitMs))),
+ ]).finally(() => clearTimeout(timer));
+ if (!ready && (host.state as string) !== "running") {
+ log.warn("agent host not ready, answering with plain chat", { bot: botId, state: host.state, waitedMs: waitMs });
+ return host.state === "starting" ? "starting" : false;
+ }
+ }
const input = store.getAgentSession(convId) ? text : firstInput(agent, botId, convId, systemPrompt, text);
const r = await agent.runTurn(botId, {
conversationId: convId,
@@ -168,7 +226,7 @@ export class BotRuntime {
visible = true;
},
},
- });
+ }).finally(() => clearInterval(startup));
store.addMessage(convId, "user", text);
const finalText = r.text.trim() || "(已完成,没有文字回复)";
store.addMessage(convId, "assistant", finalText);
@@ -192,6 +250,7 @@ export class BotRuntime {
await out.apply({ type: "stream.finish", text: `⚠️ 代理执行失败:${err.message.slice(0, 300)}` });
return true;
} finally {
+ clearInterval(startup);
unbind();
await out.apply({ type: "typing", on: false });
}
@@ -219,15 +278,8 @@ export class BotRuntime {
}
return "✅ 已开始新的一段对话(旧对话已归档并留下交接便条,长期记忆保留)";
}
- case "/status": {
- const m = convModel || botModel || this.opts.defaultModel() || "(自动:第一个可用模型)";
- const a = this.opts.agent;
- const mode = a?.available ? "代理模式(DeepSeek Harness,工作区沙箱)" : "纯对话模式";
- const pend = a ? a.approvals.pending(convId).map((r) => `${r.kind === "approval" ? "待批准" : "待回答"} ${r.code}`) : [];
- const cui = a?.available ? a.computerUse(botId) : undefined;
- const cu = cui ? [`电脑操作:${cui.backend === "codex" ? "Codex 桥" : "Cua Driver"},${cui.active ? "已启用" : "未启用"}——${cui.reason}`, ...(cui.notice && cui.enabled ? [cui.notice] : [])] : [];
- return [`当前模型:${m}${convModel ? "(会话设置)" : ""}`, `运行方式:${mode}`, ...cu, ...(pend.length ? [`未决:${pend.join(",")}`] : [])].join("\n");
- }
+ case "/status":
+ return this.statusText(botId, convId, convModel, botModel);
case "/model": {
let list: string[];
try {
diff --git a/src/diagnostics.ts b/src/diagnostics.ts
new file mode 100644
index 0000000..bf6af87
--- /dev/null
+++ b/src/diagnostics.ts
@@ -0,0 +1,398 @@
+/**
+ * 故障排查(设置 → 故障排查):状态汇总、"测试模型"(经内置网关 vs 直连端点)、"测试代理"(逐段定位卡在哪一步)、
+ * 日志尾部与可复制的诊断报告。所有输出都经过脱敏;任何密钥都不出现在结果里。
+ */
+import crypto from "node:crypto";
+import os from "node:os";
+import { appVersion, type App } from "./app.js";
+import type { HostEvent } from "./agent/host.js";
+import type { ProxyEvent } from "./agent/bridge.js";
+import { logFilePath, logger, readLogTail, redactText, redactValue } from "./log.js";
+import { bareModel } from "./modelflare.js";
+
+const log = logger("diagnostics");
+
+// ---------- 测试模型 ----------
+export interface ProbeResult {
+ route: "gateway" | "direct";
+ /** 请求的端点(不含密钥) */
+ url: string;
+ ok: boolean;
+ /** 没有测(例如外部端点模式下没有内置网关) */
+ skipped?: string;
+ status?: number;
+ ms?: number;
+ /** 发出去的模型名 */
+ model?: string;
+ /** 响应里回显的模型名 */
+ echoedModel?: string;
+ reply?: string;
+ error?: string;
+}
+
+export interface ModelTestResult {
+ at: number;
+ model: string;
+ gateway: ProbeResult;
+ direct: ProbeResult;
+ /** 一句话结论 */
+ verdict: string;
+}
+
+export const PROBE_PROMPT = "Reply with the single word: pong";
+
+function describeFetchError(e: unknown, timeoutMs: number): string {
+ const err = e as Error & { cause?: { code?: string; message?: string } };
+ if (err?.name === "TimeoutError" || err?.name === "AbortError") return `超时(${Math.round(timeoutMs / 1000)} 秒内没有响应)`;
+ const cause = err?.cause?.code || err?.cause?.message;
+ return redactText(cause ? `${err.message}(${cause})` : String(err?.message ?? err));
+}
+
+function errorText(j: any, text: string): string {
+ const m = j?.error?.message ?? j?.error ?? j?.message;
+ const body = typeof m === "string" && m ? `${m}${j?.error?.code ? `(${j.error.code})` : ""}` : text;
+ return redactText(String(body).slice(0, 2000));
+}
+
+/** 发一个最小的非流式对话请求,记录状态码、耗时、回显的模型名;失败时带回错误体。 */
+export async function probeChat(
+ route: ProbeResult["route"],
+ baseUrl: string,
+ apiKey: string,
+ model: string,
+ opts: { timeoutMs?: number; fetchImpl?: typeof fetch; headers?: Record<string, string> } = {},
+): Promise<ProbeResult> {
+ const timeoutMs = opts.timeoutMs ?? 60_000;
+ const base = baseUrl.replace(/\/+$/, "");
+ const res: ProbeResult = { route, url: redactText(base), ok: false, model };
+ if (!base) return { ...res, error: "没有配置端点地址" };
+ if (!model) return { ...res, error: "没有可用的模型:请先在 Modelflare 里选择默认模型" };
+ const t0 = Date.now();
+ try {
+ const r = await (opts.fetchImpl ?? fetch)(`${base}/chat/completions`, {
+ method: "POST",
+ headers: { ...opts.headers, "content-type": "application/json", accept: "application/json", ...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}) },
+ body: JSON.stringify({ model, messages: [{ role: "user", content: PROBE_PROMPT }], stream: false }),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ const text = await r.text();
+ res.ms = Date.now() - t0;
+ res.status = r.status;
+ let j: any;
+ try {
+ j = JSON.parse(text);
+ } catch {
+ /* 不是 JSON */
+ }
+ if (typeof j?.model === "string") res.echoedModel = j.model;
+ if (!r.ok) return { ...res, error: errorText(j, text) || `HTTP ${r.status}` };
+ const content = j?.choices?.[0]?.message?.content;
+ if (typeof content !== "string") return { ...res, error: `响应里没有 choices[0].message.content:${redactText(text.slice(0, 500))}` };
+ return { ...res, ok: true, reply: redactText(content.slice(0, 200)) };
+ } catch (e) {
+ return { ...res, ms: Date.now() - t0, error: describeFetchError(e, timeoutMs) };
+ }
+}
+
+/** 机器人实际会用的模型:指定 → 机器人默认 → 全局默认 → 列表第一个。 */
+export async function pickModel(app: App, botId?: string, explicit?: string): Promise<string> {
+ if (explicit?.trim()) return explicit.trim();
+ const bot = botId ? app.store.getBot(botId) : undefined;
+ if (bot?.defaultModel) return bot.defaultModel;
+ if (app.config.llm.defaultModel) return app.config.llm.defaultModel;
+ const list = await app.runtime.listModels(true).catch(() => [] as string[]);
+ return list[0] ?? "";
+}
+
+
+function modelVerdict(g: ProbeResult, d: ProbeResult): string {
+ if (g.skipped) return d.ok ? "端点正常" : `端点出错:${d.status ? `HTTP ${d.status}` : d.error}`;
+ if (g.ok && d.ok) return "内置网关与直连端点都正常";
+ if (g.ok && !d.ok) return d.skipped ? "内置网关正常" : "经内置网关正常,直连端点失败(网关可能用了别的线路或重试)";
+ if (!g.ok && d.ok) return "端点本身正常,问题在内置网关";
+ if (d.skipped) return "内置网关出错,未能直连对比";
+ return `端点本身出错(${d.status ? `HTTP ${d.status}` : d.error}),内置网关也失败`;
+}
+
+export async function testModel(app: App, opts: { botId?: string; model?: string; timeoutMs?: number; fetchImpl?: typeof fetch } = {}): Promise<ModelTestResult> {
+ const botId = opts.botId || app.store.listBots()[0]?.id || "default";
+ // 和机器人发出的请求一样:限定到它用的 provider(开了预算的机器人用自己的 Key)
+ const model = app.routeModel(botId, await pickModel(app, botId, opts.model));
+ const mp = app.magpie;
+ const probeOpts = { timeoutMs: opts.timeoutMs, fetchImpl: opts.fetchImpl };
+ let gateway: Promise<ProbeResult>;
+ let direct: Promise<ProbeResult>;
+ if (mp) {
+ gateway = probeChat("gateway", mp.baseUrl, mp.gatewayKey, model, probeOpts).then((r) =>
+ mp.state === "running" || r.ok ? r : { ...r, error: `${r.error ?? ""}(内置网关状态:${mp.state}${mp.lastError ? `,${redactText(mp.lastError)}` : ""})` },
+ );
+ const up = mp.upstreamEndpoint(model.includes("/") ? model.split("/")[0] : undefined);
+ direct = up
+ ? probeChat("direct", up.baseUrl, up.apiKey, bareModel(model), { ...probeOpts, headers: app.requestHeaders() })
+ : Promise.resolve({ route: "direct", url: "", ok: false, skipped: "还没有连接 Modelflare" });
+ } else {
+ const base = app.config.magpie.externalBaseUrl;
+ gateway = Promise.resolve({ route: "gateway", url: "", ok: false, skipped: "外部端点模式:机器人直接调用该端点,不经内置网关" });
+ direct = probeChat("direct", base, app.config.magpie.externalApiKey, model, probeOpts);
+ }
+ const [g, d] = await Promise.all([gateway, direct]);
+ const result: ModelTestResult = { at: Date.now(), model, gateway: g, direct: d, verdict: modelVerdict(g, d) };
+ app.lastDiagnostics.model = result;
+ log.info("test model", { model, gateway: summarizeProbe(g), direct: summarizeProbe(d) });
+ return result;
+}
+
+function summarizeProbe(p: ProbeResult): string {
+ if (p.skipped) return `skipped: ${p.skipped}`;
+ return `${p.ok ? "ok" : "fail"} status=${p.status ?? "-"} ms=${p.ms ?? "-"}${p.echoedModel ? ` model=${p.echoedModel}` : ""}${p.error ? ` error=${p.error.slice(0, 200)}` : ""}`;
+}
+
+// ---------- 测试代理 ----------
+export type StageId = "queue" | "spawn" | "plugins" | "model" | "reply";
+export interface AgentStage {
+ id: StageId;
+ label: string;
+ /** warn:不算失败,但值得注意(例如有回合正在处理,同一会话的新消息会排在后面) */
+ status: "pending" | "ok" | "warn" | "fail" | "timeout" | "skipped";
+ ms?: number;
+ detail?: string;
+}
+export interface AgentTestResult {
+ at: number;
+ ok: boolean;
+ botId: string;
+ model: string;
+ ms: number;
+ /** 卡住或失败的那一步 */
+ stuckAt?: StageId;
+ stages: AgentStage[];
+ reply?: string;
+ error?: string;
+}
+
+const STAGES: Array<[StageId, string]> = [
+ ["queue", "消息队列"],
+ ["spawn", "启动代理进程"],
+ ["plugins", "加载插件"],
+ ["model", "调用模型"],
+ ["reply", "得到回复"],
+];
+
+const TIMEOUT_DETAIL: Record<StageId, (s: number) => string> = {
+ queue: () => "",
+ spawn: (s) => `代理进程 ${s} 秒内没有完成启动(initialize 没有返回)`,
+ plugins: (s) => `代理进程已启动,但 ${s} 秒内没有发出模型请求`,
+ model: (s) => `模型请求已发出,${s} 秒内上游没有响应`,
+ reply: (s) => `模型已响应,但代理 ${s} 秒内没有结束这一轮`,
+};
+
+/**
+ * 让代理进程完整跑一轮最小对话(独立的诊断会话,不进聊天记录),按事件判断每一步:
+ * 启动(spawn + initialize)→ 插件(模型请求里有插件注册的工具)→ 模型调用(bridge 看到上游响应)→ 回复(回合结束)。
+ */
+export async function testAgent(app: App, opts: { botId?: string; model?: string; timeoutMs?: number } = {}): Promise<AgentTestResult> {
+ const t0 = Date.now();
+ const timeoutMs = Math.min(Math.max(opts.timeoutMs ?? 120_000, 5_000), 600_000);
+ const botId = opts.botId || app.store.listBots()[0]?.id || "default";
+ const stages: AgentStage[] = STAGES.map(([id, label]) => ({ id, label, status: "pending" }));
+ const result: AgentTestResult = { at: Date.now(), ok: false, botId, model: "", ms: 0, stages };
+ const st = (id: StageId) => stages.find((s) => s.id === id)!;
+ const begun: Partial<Record<StageId, number>> = {};
+ const mark = (id: StageId, status: AgentStage["status"], detail?: string, ms?: number) => {
+ const s = st(id);
+ if (s.status !== "pending") return;
+ s.status = status;
+ if (detail) s.detail = redactText(detail).slice(0, 1500);
+ s.ms = ms ?? (begun[id] !== undefined ? Date.now() - begun[id]! : undefined);
+ // 下一步从这里开始计时
+ const next = STAGES[STAGES.findIndex(([x]) => x === id) + 1]?.[0];
+ if (next && begun[next] === undefined) begun[next] = Date.now();
+ };
+ const failedAlready = () => stages.some((s) => s.status === "fail" || s.status === "timeout");
+ const finish = (): AgentTestResult => {
+ for (const s of stages) if (s.status === "pending") s.status = "skipped";
+ result.ok = stages.every((s) => s.status === "ok" || s.status === "warn");
+ result.stuckAt = stages.find((s) => s.status === "fail" || s.status === "timeout")?.id;
+ result.ms = Date.now() - t0;
+ app.lastDiagnostics.agent = result;
+ log.info("test agent", { botId, model: result.model, ok: result.ok, stuckAt: result.stuckAt, ms: result.ms, stages: stages.map((s) => `${s.id}:${s.status}${s.ms !== undefined ? `/${s.ms}ms` : ""}`).join(" ") });
+ return result;
+ };
+
+ if (!app.agent.available) {
+ mark("spawn", "fail", app.config.agent.mode === "off" ? "代理模式已关闭(AMB_AGENT=off),机器人只做纯对话" : "找不到代理运行时(DSH),机器人只能纯对话");
+ return finish();
+ }
+ const picked = await pickModel(app, botId, opts.model);
+ result.model = picked ? app.routeModel(botId, picked) : "";
+ if (!result.model) {
+ mark("spawn", "fail", "没有可用的模型:请先连接 Modelflare 并选择默认模型");
+ return finish();
+ }
+
+ const host = app.agent.host(botId);
+ const nonce = crypto.randomBytes(4).toString("hex");
+ const marker = `[诊断 ${nonce}]`;
+ const ours = new Set<number>();
+ const memory = app.agent.settings(botId).memory.enabled;
+ const expectedTools = ["present", "ask_user_question", ...(memory ? ["remember"] : [])];
+
+ // 同一机器人正在处理的回合:同一会话里后来的消息(包括用户看到"一直思考中"的那条)都排在它后面
+ const turns = app.agent.diagnostics().turns.filter((t) => t.botId === botId);
+ if (!turns.length) mark("queue", "ok", "没有正在处理的回合", 0);
+ else mark("queue", "warn", `${turns.length} 轮对话正在处理(最长已 ${Math.round(Math.max(...turns.map((t) => t.forMs)) / 1000)} 秒);同一会话的新消息会排在它后面。卡住时用下面的"重启代理进程"`, 0);
+
+ begun.spawn = Date.now();
+ if (host.state === "starting") {
+ const d = host.diagnostics() as { startingForMs?: number; initStage?: string };
+ st("spawn").detail = `等待正在进行的启动(已 ${Math.round((d.startingForMs ?? 0) / 1000)} 秒,阶段:${d.initStage ?? "-"})`;
+ }
+ const offHost = host.on((e: HostEvent) => {
+ if (e.type === "spawned") st("spawn").detail = `pid ${e.pid ?? "?"},等待初始化…`;
+ else if (e.type === "initialized") mark("spawn", "ok", `pid ${e.pid ?? "?"}`, e.ms);
+ else if (e.type === "failed") mark("spawn", "fail", e.message);
+ else if (e.type === "exit") {
+ const pending = failedAlready() ? undefined : stages.find((s) => s.status === "pending");
+ if (pending) mark(pending.id, "fail", `代理进程退出(code=${e.code ?? "-"}, signal=${e.signal ?? "-"})${host.stderrTail.length ? `;stderr:${host.stderrTail.slice(-5).join(" | ")}` : ""}`);
+ }
+ });
+ const offProxy = app.agent.bridge.onProxy((e: ProxyEvent) => {
+ if (!e.path.endsWith("/chat/completions")) return;
+ if (e.phase === "request") {
+ if (!e.lastUser?.includes(marker)) return;
+ ours.add(e.id);
+ if (st("plugins").status === "pending") {
+ const missing = expectedTools.filter((t) => !e.tools?.includes(t));
+ mark("plugins", missing.length ? "fail" : "ok", missing.length ? `模型请求里缺少插件提供的工具:${missing.join(", ")}` : `${e.tools?.length ?? 0} 个工具`);
+ }
+ return;
+ }
+ if (!ours.has(e.id) || st("model").status !== "pending") return;
+ if (e.phase === "response") mark("model", e.status < 400 ? "ok" : "fail", e.status < 400 ? `HTTP ${e.status}` : `HTTP ${e.status}${e.error ? `:${e.error}` : ""}`, e.ms);
+ else mark("model", "fail", e.error, e.ms);
+ });
+
+ const conv = `${botId}:diag:test-agent`;
+ app.store.clearAgentSession(conv);
+ let timer: NodeJS.Timeout | undefined;
+ try {
+ if (host.state === "running" && host.pid) mark("spawn", "ok", `已在运行(pid ${host.pid})`, 0);
+ host.resetBackoff();
+ const turn = host.runTurn({ conversationId: conv, text: `${marker} ${PROBE_PROMPT}`, model: result.model });
+ const outcome = await Promise.race([
+ turn.then(
+ (r) => ({ kind: "done" as const, r }),
+ (e) => ({ kind: "error" as const, e: e as Error }),
+ ),
+ new Promise<{ kind: "timeout" }>((r) => (timer = setTimeout(() => r({ kind: "timeout" }), timeoutMs))),
+ ]);
+ if (outcome.kind === "done") {
+ result.reply = redactText(outcome.r.text.slice(0, 300));
+ // 回合结束了但某一步没看到(例如 bridge 事件丢失):按结果补齐
+ if (st("spawn").status === "pending") mark("spawn", "ok");
+ if (st("plugins").status === "pending") mark("plugins", "ok", "(没有观察到模型请求)");
+ if (st("model").status === "pending") mark("model", "ok", "(没有观察到上游响应)");
+ mark("reply", outcome.r.text.trim() ? "ok" : "fail", outcome.r.text.trim() ? result.reply : "回合结束了,但没有文字回复");
+ } else if (outcome.kind === "error") {
+ result.error = redactText(outcome.e.message.slice(0, 1500));
+ // 已经有一步明确失败(启动失败、上游报错)时不再往后记
+ const pending = failedAlready() ? undefined : stages.find((s) => s.status === "pending");
+ if (pending) mark(pending.id, "fail", result.error);
+ } else {
+ const pending = stages.find((s) => s.status === "pending");
+ const stageNow = pending?.id === "spawn" && host.initStage ? `;当前阶段:${host.initStage}${host.stderrTail.length ? `;最近输出:${host.stderrTail.at(-1)}` : ""}` : "";
+ if (pending) mark(pending.id, "timeout", TIMEOUT_DETAIL[pending.id](Math.round(timeoutMs / 1000)) + stageNow);
+ result.error = "超时";
+ turn.catch(() => undefined);
+ }
+ } finally {
+ clearTimeout(timer);
+ offHost();
+ offProxy();
+ app.store.clearAgentSession(conv);
+ }
+ return finish();
+}
+
+// ---------- 状态与报告 ----------
+export function diagnosticsStatus(app: App): Record<string, unknown> {
+ const mp = app.magpie;
+ return {
+ at: Date.now(),
+ version: appVersion(),
+ platform: process.platform,
+ arch: process.arch,
+ os: `${os.type()} ${os.release()}`,
+ electron: process.versions.electron,
+ node: process.versions.node,
+ pid: process.pid,
+ uptimeSec: Math.round(process.uptime()),
+ dataDir: app.config.dataDir,
+ logFile: logFilePath(),
+ defaultModel: app.config.llm.defaultModel,
+ gateway: mp
+ ? {
+ mode: "managed",
+ state: mp.state,
+ pid: mp.pid,
+ restarts: mp.restarts,
+ lastError: mp.lastError,
+ lastExit: mp.lastExit,
+ url: mp.state === "running" ? mp.baseUrl : undefined,
+ logTail: mp.recentLog.slice(-20),
+ }
+ : { mode: "external", state: "external", url: redactText(app.config.magpie.externalBaseUrl) },
+ agent: app.agent.diagnostics(),
+ last: app.lastDiagnostics,
+ };
+}
+
+const ts = (t?: number) => (t ? new Date(t).toISOString() : "-");
+
+function probeLine(name: string, p: ProbeResult): string {
+ if (p.skipped) return ` ${name}: 未测(${p.skipped})`;
+ return ` ${name}: ${p.ok ? "正常" : "失败"} · HTTP ${p.status ?? "-"} · ${p.ms ?? "-"} ms · ${p.url}${p.echoedModel ? ` · 回显模型 ${p.echoedModel}` : ""}${p.reply ? ` · 回复 ${JSON.stringify(p.reply)}` : ""}${p.error ? `\n 错误:${p.error}` : ""}`;
+}
+
+/** 可复制的纯文本诊断报告:状态 + 最近的测试结果 + 日志尾部,整体再脱敏一遍。 */
+export function diagnosticsReport(app: App, lines = 200): string {
+ const s = diagnosticsStatus(app) as any;
+ const out: string[] = [];
+ out.push(`anymodel bot 诊断信息 · ${ts(s.at)}`);
+ out.push(`版本 ${s.version} · ${s.platform} ${s.arch} · ${s.os}${s.electron ? ` · Electron ${s.electron}` : ""} · Node ${s.node} · 运行 ${s.uptimeSec} 秒`);
+ out.push(`数据目录 ${s.dataDir}`);
+ out.push(`日志文件 ${s.logFile ?? "(未启用)"}`);
+ out.push(`默认模型 ${s.defaultModel || "(自动)"}`);
+ out.push("");
+ const g = s.gateway;
+ out.push(`[模型网关] ${g.mode === "managed" ? `内置 magpie · ${g.state} · pid ${g.pid ?? "-"} · 重启 ${g.restarts} 次${g.lastExit ? ` · 上次退出 code=${g.lastExit.code} signal=${g.lastExit.signal}` : ""}${g.lastError ? ` · ${g.lastError}` : ""}` : `外部端点 ${g.url}`}`);
+ for (const l of g.logTail ?? []) out.push(` | ${l}`);
+ const a = s.agent;
+ out.push(`[代理] ${a.enabled ? "已启用" : "未启用"} · 运行时 ${a.runtimeDir ?? "缺失"}`);
+ for (const [id, h] of Object.entries<any>(a.hosts ?? {})) {
+ out.push(` 机器人 ${id}: ${h.state} · pid ${h.pid ?? "-"} · 重启 ${h.restarts} 次 · 进行中 ${h.activeTurns}${h.lastExit ? ` · 上次退出 code=${h.lastExit.code} signal=${h.lastExit.signal} @ ${ts(h.lastExit.at)}` : ""}${h.lastError ? `\n 最近错误:${h.lastError}` : ""}`);
+ for (const l of h.stderrTail ?? []) out.push(` | ${l}`);
+ }
+ const m = app.lastDiagnostics.model;
+ if (m) {
+ out.push("");
+ out.push(`[测试模型] ${ts(m.at)} · 模型 ${m.model || "-"} · ${m.verdict}`);
+ out.push(probeLine("经内置网关", m.gateway));
+ out.push(probeLine("直连端点", m.direct));
+ }
+ const t = app.lastDiagnostics.agent;
+ if (t) {
+ out.push("");
+ out.push(`[测试代理] ${ts(t.at)} · 机器人 ${t.botId} · 模型 ${t.model || "-"} · ${t.ok ? "通过" : `未通过(${t.stuckAt ?? "?"})`} · ${t.ms} ms`);
+ for (const st of t.stages) out.push(` ${st.label}: ${st.status}${st.ms !== undefined ? ` · ${st.ms} ms` : ""}${st.detail ? ` · ${st.detail}` : ""}`);
+ }
+ out.push("");
+ out.push(`[最近 ${lines} 行日志]`);
+ out.push(...readLogTail(lines));
+ return redactText(out.join("\n"));
+}
+
+/** 状态对象再过一遍脱敏(字段名像密钥的整项替换,字符串里的密钥原文替换) */
+export function safeStatus(app: App): unknown {
+ return redactValue(diagnosticsStatus(app));
+}
diff --git a/src/log.ts b/src/log.ts
index 98a5816..8a3e78a 100644
--- a/src/log.ts
+++ b/src/log.ts
@@ -1,18 +1,50 @@
-/** 极简日志:统一脱敏,任何密钥/令牌都不会原样写进日志。 */
+/**
+ * 极简日志:统一脱敏,任何密钥/令牌都不会原样写进日志。
+ * 输出到 stdout/stderr,并在 initFileLog() 之后同时写入 <dataDir>/logs/app.log(按大小轮转,保留几个旧文件)。
+ * 打包后的 Windows/macOS 桌面版看不到 stdout,日志文件是唯一的现场记录(设置 → 故障排查 里可看最近几百行)。
+ */
+import fs from "node:fs";
+import path from "node:path";
+
type Level = "debug" | "info" | "warn" | "error";
const ORDER: Record<Level, number> = { debug: 10, info: 20, warn: 30, error: 40 };
let threshold: Level = (process.env.AMB_LOG_LEVEL as Level) || "info";
const SECRET_KEYS = /(secret|token|password|api[_-]?key|authorization|cookie|aeskey|bot_token|context_token|key)$/i;
const SECRET_VALUE = /\b(sk-[A-Za-z0-9_-]{6,}|Bearer\s+[A-Za-z0-9._~+/=-]{6,})/g;
+/** URL 参数里的令牌(magpie 的启动链接带 ?k=<web key>,界面入口带 ?token=) */
+const SECRET_PARAM = /([?&](?:token|k|key|api[_-]?key|access_token)=)[^&\s"'<>]+/gi;
+/** JSON 文本里的密钥字段(例如上游错误体回显了请求) */
+const SECRET_JSON = /("(?:api[_-]?key|apiKey|token|secret|password|authorization|key)"\s*:\s*")[^"]*(")/gi;
+
+/** 运行时已知的密钥原文(界面令牌、bridge 令牌、网关密钥、上游 API Key…):出现在任何日志里都替换成 *** */
+const known = new Set<string>();
+let knownSorted: string[] = [];
+
+export function registerSecret(value: string | undefined | null): void {
+ const v = String(value ?? "").trim();
+ if (v.length < 6 || known.has(v)) return;
+ known.add(v);
+ knownSorted = [...known].sort((a, b) => b.length - a.length);
+}
export function setLogLevel(level: Level): void {
threshold = level;
}
+/** 文本脱敏:已登记的密钥原文、sk-…/Bearer …、URL 里的 token 参数、JSON 里的密钥字段。 */
+export function redactText(s: string): string {
+ let out = s;
+ for (const v of knownSorted) if (out.includes(v)) out = out.split(v).join("***");
+ return out
+ .replace(SECRET_VALUE, (m) => m.slice(0, 4) + "***")
+ .replace(SECRET_PARAM, "$1***")
+ .replace(SECRET_JSON, "$1***$2");
+}
+
export function redactValue(value: unknown, depth = 0): unknown {
if (depth > 6) return "[depth]";
- if (typeof value === "string") return value.replace(SECRET_VALUE, (m) => m.slice(0, 4) + "***");
+ if (typeof value === "string") return redactText(value);
if (Array.isArray(value)) return value.map((v) => redactValue(v, depth + 1));
if (value && typeof value === "object") {
const out: Record<string, unknown> = {};
@@ -30,12 +62,164 @@ export function mask(secret: string | undefined | null): string {
return secret.length <= 4 ? "****" : "****" + secret.slice(-4);
}
+// ---------- 文件输出(按大小轮转) ----------
+interface FileSink {
+ dir: string;
+ file: string;
+ fd: number;
+ size: number;
+ maxBytes: number;
+ /** 总文件数(app.log + app.1.log … app.<files-1>.log) */
+ files: number;
+}
+let sink: FileSink | undefined;
+
+export const LOG_FILE = "app.log";
+const rotated = (dir: string, i: number) => path.join(dir, i === 0 ? LOG_FILE : `app.${i}.log`);
+
+/**
+ * 打开 <dir>/app.log(追加)。同一目录重复调用不做事;换目录时关掉旧文件。
+ * 默认单文件 3 MB、共 4 个文件。失败时只写控制台,不影响程序。
+ */
+export function initFileLog(dir: string, opts: { maxBytes?: number; files?: number } = {}): string | undefined {
+ const abs = path.resolve(dir);
+ if (sink?.dir === abs) return sink.file;
+ closeFileLog();
+ try {
+ fs.mkdirSync(abs, { recursive: true });
+ const file = path.join(abs, LOG_FILE);
+ const fd = fs.openSync(file, "a", 0o600);
+ sink = { dir: abs, file, fd, size: fs.fstatSync(fd).size, maxBytes: opts.maxBytes ?? 3 * 1024 * 1024, files: Math.max(2, opts.files ?? 4) };
+ return file;
+ } catch (e) {
+ writeConsole(process.stderr, `log: cannot open log file in ${abs}: ${(e as Error).message}\n`);
+ sink = undefined;
+ return undefined;
+ }
+}
+
+export function closeFileLog(): void {
+ if (!sink) return;
+ try {
+ fs.closeSync(sink.fd);
+ } catch {
+ /* ignore */
+ }
+ sink = undefined;
+}
+
+export function logFilePath(): string | undefined {
+ return sink?.file;
+}
+
+function rotate(s: FileSink): void {
+ fs.closeSync(s.fd);
+ try {
+ fs.rmSync(rotated(s.dir, s.files - 1), { force: true });
+ for (let i = s.files - 2; i >= 0; i--) {
+ const from = rotated(s.dir, i);
+ if (fs.existsSync(from)) fs.renameSync(from, rotated(s.dir, i + 1));
+ }
+ } catch {
+ // Windows 上杀毒软件或别的进程正开着旧文件时改名会失败:这次不轮转,继续写当前文件
+ }
+ s.fd = fs.openSync(s.file, "a", 0o600);
+ s.size = fs.fstatSync(s.fd).size > s.maxBytes ? 0 : fs.fstatSync(s.fd).size;
+}
+
+function writeFile(line: string): void {
+ const s = sink;
+ if (!s) return;
+ try {
+ const buf = Buffer.from(line, "utf8");
+ if (s.size > 0 && s.size + buf.length > s.maxBytes) rotate(s);
+ fs.writeSync(s.fd, buf);
+ s.size += buf.length;
+ } catch (e) {
+ sink = undefined;
+ writeConsole(process.stderr, `log: writing ${s.file} failed, file logging disabled: ${(e as Error).message}\n`);
+ }
+}
+
+/** 最近 n 行(从当前文件往旧文件读,已脱敏)。 */
+export function readLogTail(n = 200, dir = sink?.dir): string[] {
+ if (!dir) return [];
+ const out: string[] = [];
+ for (let i = 0; i < 10 && out.length < n; i++) {
+ const f = rotated(dir, i);
+ let text: string;
+ try {
+ const st = fs.statSync(f);
+ const want = Math.min(st.size, 512 * 1024);
+ const fd = fs.openSync(f, "r");
+ try {
+ const buf = Buffer.alloc(want);
+ fs.readSync(fd, buf, 0, want, st.size - want);
+ text = buf.toString("utf8");
+ } finally {
+ fs.closeSync(fd);
+ }
+ if (want < st.size) text = text.slice(text.indexOf("\n") + 1); // 去掉被截断的第一行
+ } catch {
+ break;
+ }
+ const lines = text.split(/\r?\n/).filter((l) => l.length);
+ out.unshift(...lines.slice(-(n - out.length)));
+ }
+ return out.map(redactText);
+}
+
+// ---------- 控制台输出:永远不能把异常抛回调用方 ----------
+// Windows 上 GUI 程序的 stdout/stderr 要么不存在,要么是别人建的管道(例如 PowerShell 的 *> 重定向):
+// 管道读端关了,写入就是 EPIPE(未处理的 'error' 事件 = 未捕获异常,Electron 会弹出阻塞主进程的错误框);
+// 读端不读,Windows 上的同步管道写入会卡住整个主进程。所以:stdio 出错一次就不再写控制台,
+// 桌面版在 Windows 上默认只写日志文件(electron/main.ts 调 setConsoleLog(false))。
+let consoleOn = process.env.AMB_LOG_STDOUT !== "0";
+const brokenStdio = new Set<NodeJS.WriteStream>();
+function guardStdio(stream: NodeJS.WriteStream | undefined): void {
+ if (!stream || typeof stream.on !== "function") return;
+ stream.on("error", () => {
+ // EPIPE / EBADF / EOF:读端没了。之后不再写这个流(日志文件不受影响)
+ brokenStdio.add(stream);
+ });
+}
+guardStdio(process.stdout);
+guardStdio(process.stderr);
+
+/** 控制台输出开关(日志文件不受影响) */
+export function setConsoleLog(on: boolean): void {
+ consoleOn = on;
+}
+
+function writeConsole(stream: NodeJS.WriteStream, line: string): void {
+ if (!consoleOn || brokenStdio.has(stream) || stream.destroyed || stream.writable === false) return;
+ try {
+ stream.write(line, () => {});
+ } catch {
+ brokenStdio.add(stream);
+ }
+}
+
function emit(level: Level, scope: string, msg: string, extra?: unknown): void {
if (ORDER[level] < ORDER[threshold]) return;
- const ts = new Date().toISOString();
- const line = `${ts} ${level.toUpperCase().padEnd(5)} [${scope}] ${redactValue(msg)}` +
- (extra === undefined ? "" : " " + JSON.stringify(redactValue(extra)));
- (level === "error" || level === "warn" ? process.stderr : process.stdout).write(line + "\n");
+ let line: string;
+ try {
+ const ts = new Date().toISOString();
+ line = redactText(`${ts} ${level.toUpperCase().padEnd(5)} [${scope}] ${redactValue(msg)}` + (extra === undefined ? "" : " " + safeJson(redactValue(extra)))) + "\n";
+ } catch {
+ return;
+ }
+ // 先写文件:控制台不可用时日志照样留下
+ writeFile(line);
+ writeConsole(level === "error" || level === "warn" ? process.stderr : process.stdout, line);
+}
+
+function safeJson(v: unknown): string {
+ try {
+ return JSON.stringify(v);
+ } catch {
+ return String(v);
+ }
}
export interface Logger {
@@ -53,3 +237,37 @@ export function logger(scope: string): Logger {
error: (m, e) => emit("error", scope, m, e),
};
}
+
+/**
+ * 子进程输出 → 日志:按行切分(保留跨块的半行),每行带作用域前缀并脱敏;onLine 拿到的是脱敏后的行。
+ * 返回的函数直接接到 stream.on("data") 上;flush() 把最后半行也写出去。
+ */
+export function lineLogger(scope: string, level: Level = "info", onLine?: (line: string) => void): { push(chunk: Buffer | string): void; flush(): void } {
+ const log = logger(scope);
+ let buf = "";
+ const one = (raw: string) => {
+ const line = raw.replace(/\s+$/, "");
+ if (!line) return;
+ const safe = redactText(line).slice(0, 4000);
+ onLine?.(safe);
+ log[level](safe);
+ };
+ return {
+ push(chunk) {
+ buf += chunk.toString();
+ let i;
+ while ((i = buf.indexOf("\n")) >= 0) {
+ one(buf.slice(0, i));
+ buf = buf.slice(i + 1);
+ }
+ if (buf.length > 16_000) {
+ one(buf);
+ buf = "";
+ }
+ },
+ flush() {
+ if (buf) one(buf);
+ buf = "";
+ },
+ };
+}
diff --git a/src/magpie/supervisor.ts b/src/magpie/supervisor.ts
index 15f9b0c..da97f02 100644
--- a/src/magpie/supervisor.ts
+++ b/src/magpie/supervisor.ts
@@ -4,7 +4,7 @@ import fs from "node:fs";
import net from "node:net";
import path from "node:path";
import { fileURLToPath } from "node:url";
-import { logger } from "../log.js";
+import { lineLogger, logger, registerSecret } from "../log.js";
import { BOT_PROVIDER_PREFIX, MODELFLARE_PROVIDER, botProviderId, keyTail, modelflareApiBases } from "../modelflare.js";
const log = logger("magpie");
@@ -95,6 +95,9 @@ export class MagpieSupervisor {
private readonly root: string;
private restartTimer: NodeJS.Timeout | undefined;
private logTail: string[] = [];
+ /** 当前(或最近一次)magpie 子进程 */
+ pid: number | undefined;
+ lastExit: { code: number | null; signal: string | null; at: number } | undefined;
constructor(private opts: MagpieOptions) {
this.root = path.join(opts.dataDir, "magpie");
@@ -170,6 +173,20 @@ export class MagpieSupervisor {
this.keys = { webKey: genKey(), gatewayKey: "amb-" + genKey() };
}
this.saveKeys();
+ registerSecret(this.keys.webKey);
+ registerSecret(this.keys.gatewayKey);
+ this.registerProviderKeys();
+ }
+
+ /** 上游 API Key(providers.json 里的 key 字段)登记为密钥,日志里出现时替换成 *** */
+ private registerProviderKeys(): void {
+ const f = path.join(this.root, "config", "magpie", "providers.json");
+ try {
+ const j = JSON.parse(fs.readFileSync(f, "utf8"));
+ for (const p of Array.isArray(j) ? j : j.providers ?? []) registerSecret(String(p?.key ?? ""));
+ } catch {
+ /* 还没有 */
+ }
}
private saveKeys(): void {
@@ -181,7 +198,7 @@ export class MagpieSupervisor {
if (!this.binPath) return Promise.reject(new Error("找不到 magpie 可执行文件,请先运行 npm run setup"));
if (!this.keys) this.prepare();
return new Promise((resolve, reject) => {
- const p = spawn(this.binPath!, args, { env: this.env(), stdio: ["pipe", "pipe", "pipe"] });
+ const p = spawn(this.binPath!, args, { env: this.env(), stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
let stdout = "";
let stderr = "";
const t = setTimeout(() => p.kill("SIGKILL"), timeoutMs);
@@ -195,6 +212,8 @@ export class MagpieSupervisor {
clearTimeout(t);
resolve({ code: code ?? -1, stdout, stderr });
});
+ // magpie 可能不读 stdin 就退出:写入失败(EPIPE)不能变成未捕获异常
+ p.stdin.on("error", () => {});
p.stdin.end(stdin ?? "");
});
}
@@ -224,22 +243,24 @@ export class MagpieSupervisor {
private async spawnOnce(): Promise<void> {
this.state = this.restarts ? "restarting" : "starting";
const args = ["web", "--addr", `127.0.0.1:${this.webPort}`, "--no-open", "--gateway"];
- const child = spawn(this.binPath!, args, { env: this.env(), stdio: ["ignore", "pipe", "pipe"] });
+ // windowsHide:magpie 是控制台程序,Electron 是 GUI 程序;不加的话 Windows 上每次启动都会弹出一个黑色控制台窗口
+ const child = spawn(this.binPath!, args, { env: this.env(), stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
this.child = child;
+ this.pid = child.pid;
if (child.pid) fs.writeFileSync(this.pidFile, String(child.pid));
- const onLine = (d: Buffer) => {
- for (const line of d.toString().split(/\r?\n/)) {
- if (!line.trim()) continue;
- // magpie 打印的启动链接含 ?k=<web key>,记录前脱敏
- const safe = line.replaceAll(this.keys.webKey, "***").replaceAll(this.keys.gatewayKey, "***");
- this.logTail.push(safe);
- if (this.logTail.length > 200) this.logTail.shift();
- log.debug(safe);
- }
+ // magpie 打印的启动链接含 ?k=<web key>:lineLogger 按已登记的密钥与 URL 参数脱敏后再记录
+ const keep = (safe: string) => {
+ this.logTail.push(safe);
+ if (this.logTail.length > 200) this.logTail.shift();
};
- child.stdout?.on("data", onLine);
- child.stderr?.on("data", onLine);
+ const out = lineLogger("magpie", "info", keep);
+ const err = lineLogger("magpie", "info", keep);
+ child.stdout?.on("data", (d) => out.push(d));
+ child.stderr?.on("data", (d) => err.push(d));
child.on("exit", (code, signal) => {
+ out.flush();
+ err.flush();
+ this.lastExit = { code, signal, at: Date.now() };
if (this.child !== child) return;
this.child = undefined;
if (this.stopping) {
@@ -321,7 +342,7 @@ export class MagpieSupervisor {
let cmd = "";
try {
if (process.platform === "linux") cmd = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").replaceAll("\0", " ");
- else if (process.platform === "darwin") cmd = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
+ else if (process.platform === "darwin") cmd = execFileSync("ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
} catch {
return;
}
@@ -395,6 +416,7 @@ export class MagpieSupervisor {
private async upsertProvider(existing: string | undefined, wantId: string, name: string, apiKey: string, baseUrl: string, allowed: string[], headers: Record<string, string>, picks: string[]): Promise<void> {
if (!allowed.includes(baseUrl)) throw new Error("不支持的 Modelflare 地址");
if (!apiKey.trim()) throw new Error("缺少 API Key");
+ registerSecret(apiKey.trim());
let id = existing;
if (!id) {
const add = await this.runCli(["provider", "add", name, `id=${wantId}`, `url=${baseUrl}`, "key=placeholder-key"]);
@@ -472,6 +494,20 @@ export class MagpieSupervisor {
return { connected, keyTail: connected ? keyTail(key) : "", baseUrl: String(p?.chat ?? "") };
}
+ /**
+ * 网关背后的上游端点(故障排查"直连端点"对比用):地址、真实 key、provider id(缺省为共用连接;
+ * 开了预算的机器人用自己的 mfb-<botId>)。只在本进程内使用,不外传。
+ * 网关里的模型名带 provider 前缀(modelflare/<上游模型名>),直连时要去掉。
+ */
+ upstreamEndpoint(providerId?: string): { id: string; baseUrl: string; apiKey: string } | undefined {
+ const id = providerId && this.hasProvider(providerId) ? providerId : this.modelflareId();
+ const p = id ? this.readProviderRaw(id) : undefined;
+ const key = String(p?.key ?? "");
+ if (!id || !p || !key || key === "placeholder-key") return undefined;
+ registerSecret(key);
+ return { id, baseUrl: String(p.chat ?? "").replace(/\/+$/, ""), apiKey: key };
+ }
+
private modelflareId(): string | undefined {
const hit = this.listProviders().find((p) => p.id.toLowerCase() === MODELFLARE_PROVIDER || p.name.toLowerCase() === MODELFLARE_PROVIDER);
return hit?.id;
diff --git a/src/web/server.ts b/src/web/server.ts
index c1994f5..f07fa79 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -6,7 +6,8 @@ import { createRequire } from "node:module";
import { appVersion, type App } from "../app.js";
import type { InboundEvent, OutboundOp, ReplySession } from "../core/types.js";
import { findAppRoot } from "../magpie/supervisor.js";
-import { logger, mask } from "../log.js";
+import { logFilePath, logger, mask, readLogTail, registerSecret } from "../log.js";
+import { diagnosticsReport, safeStatus, testAgent, testModel } from "../diagnostics.js";
import { ZOOMS, normalizeLowBalance, saveConfigFile } from "../config.js";
import { ApiError } from "../account/client.js";
import { OAuthError } from "../account/oauth.js";
@@ -164,6 +165,7 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
fs.writeFileSync(f, token, { mode: 0o600 });
log.warn(`UI 监听在非回环地址 ${host},访问需带令牌:见 ${f}(打开 /?token=<令牌> 一次即可)`);
}
+ registerSecret(token);
let boundPort = 0;
const allowedHosts = () => new Set([`127.0.0.1:${boundPort}`, `localhost:${boundPort}`, `[::1]:${boundPort}`]);
@@ -352,6 +354,35 @@ export async function startWebServer(app: App, opts: { port?: number; host?: str
return send(res, 200, { ok: true });
}
if (p === "/agent" && m === "GET") return send(res, 200, app.agent.status());
+ // —— 故障排查(设置 → 故障排查):所有输出都已脱敏 ——
+ if (seg[0] === "diagnostics") {
+ const sub = seg.slice(1).join("/");
+ if (sub === "" && m === "GET") return send(res, 200, safeStatus(app));
+ if (sub === "logs" && m === "GET") {
+ const n = Math.min(Math.max(Number(url.searchParams.get("lines")) || 200, 1), 2000);
+ return send(res, 200, { file: logFilePath() ?? "", lines: readLogTail(n) });
+ }
+ if (sub === "report" && m === "GET") return send(res, 200, { text: diagnosticsReport(app, Math.min(Math.max(Number(url.searchParams.get("lines")) || 200, 1), 2000)) });
+ if (sub === "test-model" && m === "POST") {
+ const b = await readJson(req);
+ const botId = b.botId ? String(b.botId) : undefined;
+ if (botId && !app.store.getBot(botId)) throw new HttpError(404, "机器人不存在");
+ return send(res, 200, await testModel(app, { botId, model: b.model ? String(b.model) : undefined, timeoutMs: b.timeoutMs ? Number(b.timeoutMs) : undefined }));
+ }
+ if (sub === "test-agent" && m === "POST") {
+ const b = await readJson(req);
+ const botId = b.botId ? String(b.botId) : undefined;
+ if (botId && !app.store.getBot(botId)) throw new HttpError(404, "机器人不存在");
+ return send(res, 200, await testAgent(app, { botId, model: b.model ? String(b.model) : undefined, timeoutMs: b.timeoutMs ? Number(b.timeoutMs) : undefined }));
+ }
+ if (sub === "restart-agent" && m === "POST") {
+ const b = await readJson(req);
+ const restarted = await app.agent.restartHosts(b.botId ? String(b.botId) : undefined);
+ log.info("agent hosts restarted from troubleshooting", { restarted });
+ return send(res, 200, { restarted, agent: (safeStatus(app) as any).agent });
+ }
+ throw new HttpError(404, "not found");
+ }
if (seg[0] === "approvals") {
if (seg.length === 1 && m === "GET") {
const status = url.searchParams.get("status") || undefined;
diff --git a/test/agent.integration.test.ts b/test/agent.integration.test.ts
index c54dbf7..65d1ade 100644
--- a/test/agent.integration.test.ts
+++ b/test/agent.integration.test.ts
@@ -194,4 +194,27 @@ describe.skipIf(!runtime || !hasBwrap || process.platform !== "linux")("agent ho
const r = await chat("LOOPBACK check");
expect(r.reply).toContain("API 403");
}, 120_000);
+
+ it("troubleshooting: test agent passes every stage, restart respawns the host", async () => {
+ const post = async (p: string, body: unknown = {}) =>
+ (await (await fetch(`${base}/amb/api/diagnostics/${p}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })).json()) as any;
+ const t = await post("test-agent", { timeoutMs: 60_000 });
+ expect(t.stages.map((s: any) => `${s.id}:${s.status}`)).toEqual(["queue:ok", "spawn:ok", "plugins:ok", "model:ok", "reply:ok"]);
+ expect(t.reply).toBe("好的");
+ // 诊断会话不进聊天记录
+ const convs = ((await (await fetch(`${base}/amb/api/conversations?bot=default`)).json()) as any).conversations;
+ expect(convs.some((c: any) => String(c.id).includes("diag"))).toBe(false);
+ const status = ((await (await fetch(`${base}/amb/api/diagnostics`)).json()) as any).agent.hosts.default;
+ expect(status).toMatchObject({ state: "running" });
+ expect(Array.isArray(status.stderrTail)).toBe(true);
+
+ const r = await post("restart-agent");
+ expect(r.restarted).toEqual(["default"]);
+ expect(r.agent.hosts.default.state).toBe("stopped");
+ // 重启后下一条消息重新拉起代理进程(脚本化模型按会话历史回答,这里只看不是错误)
+ const again = await chat("hello after restart");
+ expect(again.reply).toBeTruthy();
+ expect(again.reply).not.toContain("⚠️");
+ expect(app.agent.host("default").state).toBe("running");
+ }, 180_000);
});
diff --git a/test/cua-driver.unit.test.ts b/test/cua-driver.unit.test.ts
index 680a640..bb1e6f8 100644
--- a/test/cua-driver.unit.test.ts
+++ b/test/cua-driver.unit.test.ts
@@ -1,8 +1,10 @@
+import { EventEmitter } from "node:events";
+import { PassThrough, Writable } from "node:stream";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vitest";
-import { cuaConfig, cuaMcpEnv, cuaRoots, CUA_INPUT_TOOLS, CUA_READ_TOOLS, CUA_TOOLS, detectCua, linuxDesktopApps, type CuaProbe } from "../src/agent/cua-driver.js";
+import { cuaConfig, cuaMcpEnv, cuaRoots, CUA_INPUT_TOOLS, CUA_READ_TOOLS, CUA_TOOLS, detectCua, linuxDesktopApps, uniqueApps, windowsAppsFrom, type CuaProbe } from "../src/agent/cua-driver.js";
import { Store } from "../src/store/db.js";
const proxy = path.join(__dirname, "..", "dsh-runtime", "plugins", "amb-cua-mcp.mjs");
@@ -91,6 +93,115 @@ describe("cua-driver config", () => {
});
});
+describe("Windows app manifest", () => {
+ it("dedupes Start-menu targets case-insensitively (v0.1.5 MCP crash loop)", () => {
+ // 真实 windows-2025 runner 上的情况:系统自带的 notepad/mspaint 与开始菜单快捷方式只差大小写
+ const onDisk = new Set(["C:\\Windows\\System32\\notepad.exe", "C:\\Windows\\System32\\mspaint.exe", "C:\\Windows\\explorer.exe", "C:\\Program Files\\App\\app.exe"].map((p) => p.toLowerCase()));
+ const exists = (p: string) => onDisk.has(p.toLowerCase());
+ const shortcuts = ["C:\\WINDOWS\\system32\\notepad.exe", "C:\\WINDOWS\\system32\\mspaint.exe", "C:\\Program Files\\App\\app.exe", "C:\\PROGRAM FILES\\APP\\APP.EXE", "C:\\gone\\x.exe", "C:\\x\\readme.txt", ""].join("\r\n");
+ const apps = windowsAppsFrom({ SystemRoot: "C:\\Windows" }, shortcuts, exists, (p) => p);
+ const ids = apps.map((a) => ("executable" in a ? a.executable.toLowerCase() : ""));
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(ids.sort()).toEqual(["c:\\program files\\app\\app.exe", "c:\\windows\\explorer.exe", "c:\\windows\\system32\\mspaint.exe", "c:\\windows\\system32\\notepad.exe"]);
+ expect(uniqueApps([{ bundle_id: "com.apple.Safari" }, { bundle_id: "com.apple.safari" }], "darwin")).toHaveLength(1);
+ });
+});
+
+/** 假的 cua-driver 子进程:记录写进 stdin 的消息,测试从 stdout 回消息 */
+function fakeDriver() {
+ const c: any = new EventEmitter();
+ c.stdout = new PassThrough();
+ c.stderr = new PassThrough();
+ c.sent = [] as any[];
+ c.stdin = new Writable({
+ write(chunk, _enc, cb) {
+ for (const l of String(chunk).split("\n")) if (l.trim()) c.sent.push(JSON.parse(l));
+ cb();
+ },
+ });
+ c.reply = (msg: unknown) => c.stdout.write(JSON.stringify(msg) + "\n");
+ c.kill = () => c.emit("exit", null);
+ return c;
+}
+
+describe("cua MCP front: startup never waits for (or crash-loops on) the driver", () => {
+ const setup = async (o: { list?: () => Promise<Set<string>> } = {}) => {
+ const m = await import(proxy);
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "amb-front-"));
+ const out: any[] = [];
+ const logs: string[] = [];
+ const drivers: any[] = [];
+ const front = m.createFront({
+ cfg: { bin: "cua-driver", manifest: path.join(dir, "m.yaml"), tools: ["click", "list_windows"], apps: [], display: true },
+ env: {},
+ send: (msg: any) => out.push(msg),
+ log: (s: string) => logs.push(s),
+ spawnDriver: () => {
+ const d = fakeDriver();
+ drivers.push(d);
+ return d;
+ },
+ listTools: o.list ?? (async () => new Set(["click", "list_windows", "run_script"])),
+ });
+ return { front, out, logs, drivers, dir };
+ };
+ const tick = () => new Promise((r) => setTimeout(r, 20));
+
+ it("answers initialize itself, then lists the driver's (filtered) tools once it is up", async () => {
+ const { front, out, drivers } = await setup();
+ await front.onClient({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {} } });
+ expect(out[0]).toMatchObject({ id: 1, result: { capabilities: { tools: { listChanged: true } } } });
+ await tick();
+ const d = drivers[0];
+ expect(d.sent[0]).toMatchObject({ method: "initialize" });
+ d.reply({ jsonrpc: "2.0", id: d.sent[0].id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} } } });
+ await tick();
+ expect(front.ready).toBe(true);
+ const listing = front.onClient({ jsonrpc: "2.0", id: 2, method: "tools/list" });
+ await listing;
+ const fwd = d.sent.find((x: any) => x.id === 2);
+ expect(fwd.method).toBe("tools/list");
+ d.reply({ jsonrpc: "2.0", id: 2, result: { tools: [{ name: "click" }, { name: "run_script" }] } });
+ await tick();
+ expect(out.find((x) => x.id === 2).result.tools.map((t: any) => t.name)).toEqual(["click"]);
+ });
+
+ it("a slow driver: tools/list is empty at first, then tools/list_changed", async () => {
+ const { front, out, drivers } = await setup();
+ await front.onClient({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} });
+ await front.onClient({ jsonrpc: "2.0", id: 2, method: "tools/list" }); // waits ~3 s, driver silent
+ expect(out.find((x) => x.id === 2).result.tools).toEqual([]);
+ const d = drivers[0];
+ d.reply({ jsonrpc: "2.0", id: d.sent[0].id, result: {} });
+ await tick();
+ expect(out.at(-1)).toMatchObject({ method: "notifications/tools/list_changed" });
+ }, 10_000);
+
+ it("a driver that dies at startup: no exit, no restart storm, calls report why", async () => {
+ const { front, out, drivers, logs } = await setup();
+ await front.onClient({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} });
+ await tick();
+ drivers[0].stderr.write("Error: application resources repeat an identity\n");
+ drivers[0].emit("exit", 1);
+ await tick();
+ expect(logs.join("\n")).toContain("cua-driver mcp exited (1)");
+ await front.onClient({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "click", arguments: {} } });
+ const r = out.find((x) => x.id === 3);
+ expect(r.result.isError).toBe(true);
+ expect(r.result.content[0].text).toContain("exited (1)");
+ expect(drivers).toHaveLength(1); // retried at most once a minute, not per message
+ });
+
+ it("list-tools failing is reported the same way", async () => {
+ const { front, out, drivers } = await setup({ list: async () => Promise.reject(new Error("cua-driver list-tools failed: timeout")) });
+ await front.onClient({ jsonrpc: "2.0", id: 1, method: "initialize", params: {} });
+ await tick();
+ await front.onClient({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "click" } });
+ expect(out.find((x) => x.id === 2).result.content[0].text).toContain("list-tools failed");
+ expect(drivers).toHaveLength(0);
+ });
+});
+
describe("cua MCP front (amb-cua-mcp.mjs)", () => {
it("writes a bounded v3 manifest", async () => {
const m = await import(proxy);
@@ -102,6 +213,14 @@ describe("cua MCP front (amb-cua-mcp.mjs)", () => {
expect(y).toContain("terminate: driver_launched");
expect(y).toContain(" desktop:\n display: true");
});
+ it("never repeats an app identity (cua-driver refuses to start on duplicates)", async () => {
+ const m = await import(proxy);
+ const apps = [{ executable: "C:\\Windows\\System32\\notepad.exe" }, { executable: "C:\\WINDOWS\\system32\\notepad.exe" }, { bundle_id: "com.A.b" }, { bundle_id: "com.a.B" }];
+ expect(m.uniqueApps(apps, "win32")).toEqual([apps[0], apps[2]]);
+ expect(m.uniqueApps([{ executable: "/usr/bin/x" }, { executable: "/usr/bin/X" }], "linux")).toHaveLength(2);
+ const y = m.manifestYaml({ tools: ["click"], apps: process.platform === "win32" ? apps : [{ executable: "/a" }, { executable: "/a" }] });
+ expect(y.match(/- (executable|bundle_id):/g)!.length).toBe(process.platform === "win32" ? 2 : 1);
+ });
it("parses list-tools and builds a bounded, telemetry-free env", async () => {
const m = await import(proxy);
expect([...m.parseToolList("click: Click a thing\nbrowser_x: y\n indented: no\nnot a tool\n")]).toEqual(["click", "browser_x"]);
diff --git a/test/diagnostics.unit.test.ts b/test/diagnostics.unit.test.ts
new file mode 100644
index 0000000..3e00fae
--- /dev/null
+++ b/test/diagnostics.unit.test.ts
@@ -0,0 +1,373 @@
+/**
+ * 日志文件(轮转、脱敏、尾部)+ 故障排查(测试模型 / 测试代理的分段判定 / 接口与报告不泄露密钥)。
+ */
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { App } from "../src/app.js";
+import { loadConfig } from "../src/config.js";
+import { closeFileLog, initFileLog, lineLogger, logger, readLogTail, redactText, registerSecret } from "../src/log.js";
+import { probeChat, testAgent } from "../src/diagnostics.js";
+import type { HostEvent } from "../src/agent/host.js";
+import type { ProxyEvent } from "../src/agent/bridge.js";
+import { mockOpenAI } from "./helpers.js";
+
+const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "amb-diag-"));
+
+describe("日志文件", () => {
+ it("按大小轮转,只保留固定个数", () => {
+ const dir = tmp();
+ initFileLog(dir, { maxBytes: 2000, files: 3 });
+ const log = logger("t");
+ for (let i = 0; i < 200; i++) log.info(`line ${i} ${"x".repeat(40)}`);
+ closeFileLog();
+ const files = fs.readdirSync(dir).sort();
+ expect(files).toEqual(["app.1.log", "app.2.log", "app.log"]);
+ for (const f of files) expect(fs.statSync(path.join(dir, f)).size).toBeLessThanOrEqual(2000);
+ const tail = readLogTail(5, dir);
+ expect(tail).toHaveLength(5);
+ expect(tail.at(-1)).toContain("line 199");
+ expect(tail[0]).toContain("line 195");
+ // 尾部跨文件:当前文件不够时从旧文件补
+ const many = readLogTail(60, dir);
+ expect(many.at(-1)).toContain("line 199");
+ expect(many.length).toBeGreaterThan(fs.readFileSync(path.join(dir, "app.log"), "utf8").trim().split("\n").length);
+ });
+
+ it("写进文件的每一行都脱敏:登记过的密钥、sk-/Bearer、URL 令牌参数、JSON 密钥字段", () => {
+ const dir = tmp();
+ initFileLog(dir);
+ registerSecret("ui-token-1234567890");
+ const log = logger("t");
+ log.info("open http://127.0.0.1:3600/?token=ui-token-1234567890 now");
+ log.warn("upstream said", { body: '{"error":{"message":"bad"},"api_key":"mf-live-abcdef123456"}', auth: "Bearer abcdefghijkl", note: "sk-proj-abcdefghijklmnop" });
+ log.info("magpie web http://127.0.0.1:5000/?k=AbCdEfGhIjKlMnOp&x=1");
+ closeFileLog();
+ const text = fs.readFileSync(path.join(dir, "app.log"), "utf8");
+ expect(text).not.toMatch(/ui-token-1234567890|mf-live-abcdef123456|abcdefghijkl|sk-proj-abcdefghijklmnop|AbCdEfGhIjKlMnOp/);
+ expect(text).toContain("?token=***");
+ expect(text).toContain("k=***&x=1");
+ expect(redactText("x ui-token-1234567890 y")).toBe("x *** y");
+ });
+
+ it("控制台坏了(EPIPE):日志调用不抛错,'error' 事件不成为未捕获异常,日志文件照写", () => {
+ const dir = tmp();
+ initFileLog(dir);
+ const orig = process.stdout.write;
+ (process.stdout as any).write = () => {
+ throw Object.assign(new Error("write EPIPE"), { code: "EPIPE" });
+ };
+ try {
+ expect(() => logger("t").info("still logged")).not.toThrow();
+ } finally {
+ (process.stdout as any).write = orig;
+ }
+ // 异步的写失败以 'error' 事件出现:log.ts 已经挂了监听,不会变成未捕获异常
+ expect(process.stdout.listenerCount("error")).toBeGreaterThan(0);
+ process.stdout.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
+ expect(() => logger("t").warn("after broken stdout")).not.toThrow();
+ closeFileLog();
+ const text = fs.readFileSync(path.join(dir, "app.log"), "utf8");
+ expect(text).toContain("still logged");
+ expect(text).toContain("after broken stdout");
+ });
+
+ it("子进程输出按行记录(跨块的半行拼起来),带作用域前缀", () => {
+ const dir = tmp();
+ initFileLog(dir);
+ const seen: string[] = [];
+ const l = lineLogger("dsh:default", "info", (s) => seen.push(s));
+ l.push("first li");
+ l.push(Buffer.from("ne\r\nsecond line\nthi"));
+ l.push("rd");
+ l.flush();
+ closeFileLog();
+ expect(seen).toEqual(["first line", "second line", "third"]);
+ const text = fs.readFileSync(path.join(dir, "app.log"), "utf8");
+ expect(text).toMatch(/INFO \[dsh:default\] first line/);
+ });
+});
+
+describe("测试模型 probeChat", () => {
+ let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+ beforeAll(async () => {
+ llm = await mockOpenAI({ key: "probe-key-123456", reply: () => "pong" });
+ });
+ afterAll(() => llm.close());
+
+ it("正常:状态码、耗时、回复", async () => {
+ const r = await probeChat("direct", llm.url + "/v1", "probe-key-123456", "mock-a");
+ expect(r).toMatchObject({ ok: true, status: 200, reply: "pong", model: "mock-a", url: llm.url + "/v1" });
+ expect(r.ms).toBeGreaterThanOrEqual(0);
+ expect(llm.calls.at(-1)!.messages[0].content).toMatch(/pong/);
+ });
+ it("失败:带回错误体,不带密钥", async () => {
+ const r = await probeChat("direct", llm.url + "/v1", "wrong-key-abcdef", "mock-a");
+ expect(r).toMatchObject({ ok: false, status: 401, error: "bad key" });
+ expect(JSON.stringify(r)).not.toContain("wrong-key-abcdef");
+ });
+ it("连不上:给出原因", async () => {
+ const r = await probeChat("gateway", "http://127.0.0.1:9/v1", "", "m", { timeoutMs: 3000 });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/ECONNREFUSED|fetch failed|超时/);
+ });
+});
+
+/** 只实现 testAgent 用到的部分:用事件模拟代理进程走到哪一步 */
+function fakeApp(script: (h: { emit: (e: HostEvent) => void; proxy: (e: ProxyEvent) => void; text: string }) => Promise<{ text: string }>) {
+ const hostListeners = new Set<(e: HostEvent) => void>();
+ const proxyListeners = new Set<(e: ProxyEvent) => void>();
+ const host = {
+ state: "stopped",
+ initStage: "",
+ diagnostics: () => ({}),
+ pid: undefined as number | undefined,
+ stderrTail: ["boom from stderr"],
+ on: (fn: (e: HostEvent) => void) => (hostListeners.add(fn), () => hostListeners.delete(fn)),
+ resetBackoff: () => {},
+ runTurn: (input: { text: string }) =>
+ script({ emit: (e) => hostListeners.forEach((f) => f(e)), proxy: (e) => proxyListeners.forEach((f) => f(e)), text: input.text }).then((r) => ({ ...r, sessionId: "s", files: [], usage: { tokens: 0, window: 0, maxTokens: 0 } })),
+ };
+ const app: any = {
+ agent: {
+ available: true,
+ host: () => host,
+ diagnostics: () => ({ turns: [] }),
+ settings: () => ({ memory: { enabled: true } }),
+ bridge: { onProxy: (fn: (e: ProxyEvent) => void) => (proxyListeners.add(fn), () => proxyListeners.delete(fn)) },
+ },
+ store: { listBots: () => [{ id: "b1" }], getBot: () => ({ id: "b1", defaultModel: "m1" }), clearAgentSession: () => {} },
+ config: { llm: { defaultModel: "" }, agent: { mode: "dsh" } },
+ runtime: { listModels: async () => ["m1"] },
+ routeModel: (_bot: string, m: string) => m,
+ lastDiagnostics: {},
+ };
+ return app as App;
+}
+const TOOLS = ["present", "ask_user_question", "remember", "bash"];
+
+describe("测试代理:分段定位", () => {
+ it("全部通过", async () => {
+ const app = fakeApp(async ({ emit, proxy, text }) => {
+ emit({ type: "spawned", pid: 42 });
+ emit({ type: "initialized", pid: 42, ms: 1200 });
+ proxy({ phase: "request", id: 1, path: "/v1/chat/completions", tools: TOOLS, lastUser: text });
+ proxy({ phase: "response", id: 1, path: "/v1/chat/completions", status: 200, ms: 300 });
+ return { text: "pong" };
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.ok).toBe(true);
+ expect(r.stages.map((s) => s.status)).toEqual(["ok", "ok", "ok", "ok", "ok"]);
+ expect(r.stages[1]).toMatchObject({ ms: 1200, detail: "pid 42" });
+ expect(r.stages[3]).toMatchObject({ ms: 300, detail: "HTTP 200" });
+ expect(r.reply).toBe("pong");
+ expect((app as any).lastDiagnostics.agent).toBe(r);
+ });
+
+ it("模型请求发出后上游一直不响应:卡在“调用模型”(超时)", async () => {
+ const app = fakeApp(({ emit, proxy, text }) => {
+ emit({ type: "spawned", pid: 7 });
+ emit({ type: "initialized", pid: 7, ms: 10 });
+ proxy({ phase: "request", id: 9, path: "/v1/chat/completions", tools: TOOLS, lastUser: text });
+ return new Promise(() => {});
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.ok).toBe(false);
+ expect(r.stuckAt).toBe("model");
+ expect(r.stages.map((s) => s.status)).toEqual(["ok", "ok", "ok", "timeout", "skipped"]);
+ expect(r.stages[3].detail).toContain("上游没有响应");
+ }, 10_000);
+
+ it("初始化失败:卡在“启动代理进程”,带上错误", async () => {
+ const app = fakeApp(async ({ emit }) => {
+ emit({ type: "spawned", pid: 7 });
+ emit({ type: "failed", message: "initialize timed out after 90000ms; stderr tail: plugin amb-memory failed" });
+ throw new Error("initialize timed out after 90000ms");
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.stuckAt).toBe("spawn");
+ expect(r.stages[1]).toMatchObject({ status: "fail" });
+ expect(r.stages[1].detail).toContain("plugin amb-memory failed");
+ expect(r.stages.slice(2).map((s) => s.status)).toEqual(["skipped", "skipped", "skipped"]);
+ });
+
+ it("插件工具缺失、上游 401:分别标在“加载插件”和“调用模型”", async () => {
+ const app = fakeApp(async ({ emit, proxy, text }) => {
+ emit({ type: "initialized", pid: 1, ms: 5 });
+ proxy({ phase: "request", id: 1, path: "/v1/chat/completions", tools: ["bash"], lastUser: text });
+ proxy({ phase: "response", id: 1, path: "/v1/chat/completions", status: 401, ms: 20, error: "invalid api key" });
+ throw new Error("401 invalid api key");
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.stages[2]).toMatchObject({ status: "fail" });
+ expect(r.stages[2].detail).toContain("present");
+ expect(r.stages[3]).toMatchObject({ status: "fail", detail: "HTTP 401:invalid api key" });
+ });
+
+ it("别的会话的模型请求不算(按诊断标记区分)", async () => {
+ const app = fakeApp(({ emit, proxy }) => {
+ emit({ type: "initialized", pid: 1, ms: 5 });
+ proxy({ phase: "request", id: 3, path: "/v1/chat/completions", tools: TOOLS, lastUser: "someone else's chat" });
+ proxy({ phase: "response", id: 3, path: "/v1/chat/completions", status: 200, ms: 20 });
+ return new Promise(() => {});
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.stuckAt).toBe("plugins");
+ expect(r.stages[2].detail).toContain("没有发出模型请求");
+ }, 10_000);
+
+ it("代理进程中途退出:标在当时那一步,并附 stderr", async () => {
+ const app = fakeApp(async ({ emit }) => {
+ emit({ type: "initialized", pid: 1, ms: 5 });
+ emit({ type: "exit", pid: 1, code: 3, signal: null });
+ throw new Error("DeepSeek Harness runtime exited");
+ });
+ const r = await testAgent(app, { timeoutMs: 5000 });
+ expect(r.stuckAt).toBe("plugins");
+ expect(r.stages[2].detail).toMatch(/code=3.*boom from stderr/);
+ });
+});
+
+describe("故障排查接口", () => {
+ let llm: Awaited<ReturnType<typeof mockOpenAI>>;
+ let app: App;
+ let base: string;
+ const TOKEN = "ui-token-for-diag-tests";
+ const KEY = "gw-key-for-diag-tests";
+ const api = async (p: string, init: { method?: string; body?: unknown; token?: string | null } = {}) => {
+ const res = await fetch(base + "/amb/api" + p, {
+ method: init.method ?? "GET",
+ headers: { ...(init.body !== undefined ? { "content-type": "application/json" } : {}), ...(init.token === null ? {} : { "x-amb-token": init.token ?? TOKEN }) },
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ });
+ const text = await res.text();
+ let json: any = {};
+ try {
+ json = JSON.parse(text);
+ } catch {
+ /* ignore */
+ }
+ return { status: res.status, json, text };
+ };
+
+ beforeAll(async () => {
+ llm = await mockOpenAI({ key: KEY, models: ["mock-a"], reply: () => "pong" });
+ const dataDir = tmp();
+ const config = loadConfig({
+ dataDir,
+ env: { AMB_MAGPIE_BASE_URL: llm.url + "/v1", AMB_MAGPIE_API_KEY: KEY, AMB_UI_PORT: "0", AMB_UI_TOKEN: TOKEN, AMB_AGENT: "off", AMB_WEIXIN_API_BASE: "http://127.0.0.1:9" },
+ });
+ app = new App(config, { printQrToTerminal: false });
+ await app.start();
+ base = app.web!.url.replace(/\/$/, "");
+ });
+ afterAll(async () => {
+ await app?.stop();
+ await llm?.close();
+ });
+
+ it("/status 不进会话队列:前面有卡住的回合也立刻回答", async () => {
+ let release!: () => void;
+ void app.queue.run("web:default:console", () => new Promise<void>((r) => (release = r)));
+ const t0 = Date.now();
+ const r = await api("/bots/default/chat", { method: "POST", body: { text: "/status" } });
+ expect(Date.now() - t0).toBeLessThan(3000);
+ expect(r.json.reply).toContain("当前模型");
+ expect(r.json.reply).toContain("纯对话模式");
+ release();
+ });
+
+ it("需要访问令牌", async () => {
+ expect((await api("/diagnostics", { token: null })).status).toBe(401);
+ expect((await api("/diagnostics/logs", { token: "wrong" })).status).toBe(401);
+ });
+
+ it("状态:版本、平台、目录、网关与代理", async () => {
+ const r = await api("/diagnostics");
+ expect(r.status).toBe(200);
+ expect(r.json).toMatchObject({ platform: process.platform, arch: process.arch, gateway: { mode: "external" }, agent: { enabled: false, available: false } });
+ expect(r.json.dataDir).toBe(app.config.dataDir);
+ expect(r.json.logFile).toBe(path.join(app.config.dataDir, "logs", "app.log"));
+ expect(r.text).not.toContain(KEY);
+ expect(r.text).not.toContain(TOKEN);
+ });
+
+ it("测试模型:外部端点模式只直连,网关一项标为未测", async () => {
+ const r = await api("/diagnostics/test-model", { method: "POST", body: {} });
+ expect(r.status).toBe(200);
+ expect(r.json.model).toBe("mock-a");
+ expect(r.json.direct).toMatchObject({ ok: true, status: 200, reply: "pong" });
+ expect(r.json.gateway.skipped).toBeTruthy();
+ expect(llm.calls.at(-1)!.auth).toBe(`Bearer ${KEY}`);
+ expect(r.text).not.toContain(KEY);
+ });
+
+ it("测试代理:代理关闭时停在第一步并说明原因", async () => {
+ const r = await api("/diagnostics/test-agent", { method: "POST", body: {} });
+ expect(r.status).toBe(200);
+ expect(r.json).toMatchObject({ ok: false, stuckAt: "spawn" });
+ expect(r.json.stages[1].detail).toContain("代理模式已关闭");
+ expect((await api("/diagnostics/test-agent", { method: "POST", body: { botId: "nope" } })).status).toBe(404);
+ });
+
+ it("重启代理进程、写操作要求 JSON", async () => {
+ const r = await api("/diagnostics/restart-agent", { method: "POST", body: {} });
+ expect(r.status).toBe(200);
+ expect(r.json.restarted).toEqual([]);
+ const bad = await fetch(base + "/amb/api/diagnostics/restart-agent", { method: "POST", headers: { "x-amb-token": TOKEN, "content-type": "text/plain" }, body: "{}" });
+ expect(bad.status).toBe(415);
+ });
+
+ it("日志尾部与诊断报告:带测试结果,不含任何密钥", async () => {
+ const logs = await api("/diagnostics/logs?lines=50");
+ expect(logs.status).toBe(200);
+ expect(logs.json.lines.length).toBeGreaterThan(0);
+ expect(logs.json.lines.join("\n")).toMatch(/\[app\] anymodel bot .* starting/);
+ const rep = await api("/diagnostics/report");
+ expect(rep.status).toBe(200);
+ expect(rep.json.text).toContain("[测试模型]");
+ expect(rep.json.text).toContain("[测试代理]");
+ expect(rep.json.text).toContain("[最近 200 行日志]");
+ expect(rep.text).not.toContain(KEY);
+ expect(rep.text).not.toContain(TOKEN);
+ });
+});
+
+describe("代理还在启动时的消息", () => {
+ it("先说明在启动,等待超过时限就由模型直接回答(启动在后台继续)", async () => {
+ const { BotRuntime } = await import("../src/core/runtime.js");
+ const { Store } = await import("../src/store/db.js");
+ const store = new Store(path.join(tmp(), "t.db"));
+ const bot = store.createBot({ id: "b1", name: "b", defaultModel: "m1" });
+ let ensureCalls = 0;
+ const host = { state: "starting", ensure: () => (ensureCalls++, new Promise(() => {})), diagnostics: () => ({ firstStart: true }) };
+ const agent: any = {
+ available: true,
+ host: () => host,
+ approvals: { bindSink: () => () => {}, handleReply: () => ({ handled: false }), pending: () => [] },
+ runTurn: () => Promise.reject(new Error("should not run")),
+ settings: () => ({ memory: { enabled: false } }),
+ };
+ const models: any = { listModels: async () => ["m1"], streamChat: async (_r: unknown, onDelta: (d: string) => void) => (onDelta("plain answer"), "plain answer") };
+ const rt = new BotRuntime({ store, models, defaultModel: () => "", contextMessages: 10, contextChars: 5000, agent });
+ const ops: any[] = [];
+ const prev = process.env.AMB_AGENT_START_WAIT_MS;
+ process.env.AMB_AGENT_START_WAIT_MS = "300";
+ try {
+ const ev: any = { id: "e1", channel: "web", botId: bot.id, conversation: { kind: "dm", id: "console" }, sender: { id: "u", name: "u" }, parts: [{ type: "text", text: "hi" }], replyHandle: {}, receivedAt: Date.now() };
+ await rt.handle(ev, { apply: async (op: any) => void ops.push(op) });
+ } finally {
+ if (prev === undefined) delete process.env.AMB_AGENT_START_WAIT_MS;
+ else process.env.AMB_AGENT_START_WAIT_MS = prev;
+ }
+ expect(ensureCalls).toBe(1);
+ expect(ops.find((o) => o.type === "stream.update")?.text).toContain("代理正在启动");
+ const fin = ops.filter((o) => o.type === "stream.finish").at(-1);
+ expect(fin.text).toContain("代理还在启动");
+ expect(fin.text).toContain("plain answer");
+ // 历史里只存模型的回答,不存提示
+ expect(store.listMessages("b1:web:console").map((m: any) => m.content)).toEqual(["hi", "plain answer"]);
+ store.close();
+ });
+});
diff --git a/ui/components/ui.js b/ui/components/ui.js
index 1838851..3f7c7c8 100644
--- a/ui/components/ui.js
+++ b/ui/components/ui.js
@@ -45,6 +45,7 @@ const P = {
chat: "M3.25 2.75h9.5c.41 0 .75.34.75.75v6.75c0 .41-.34.75-.75.75H7.25L4.5 13.25V11H3.25a.75.75 0 0 1-.75-.75V3.5c0-.41.34-.75.75-.75Z",
code: "M5.25 4.5 1.75 8l3.5 3.5M10.75 4.5 14.25 8l-3.5 3.5M9.1 2.75 6.9 13.25",
shield: "M8 1.75 2.75 3.6v4.15c0 3.05 2.2 5.4 5.25 6.5 3.05-1.1 5.25-3.45 5.25-6.5V3.6L8 1.75Z",
+ pulse: "M1.75 8.25h2.5l1.5-3.75 2.75 7.5 1.75-5 1 1.25h3",
};
export function Icon({ name, size = 16, stroke = 1.6, class: cls = "" }) {
const fill = name === "stop";
diff --git a/ui/css/settings.css b/ui/css/settings.css
index 2220bb1..9102bb7 100644
--- a/ui/css/settings.css
+++ b/ui/css/settings.css
@@ -52,6 +52,24 @@
.notif p { font-size: var(--fs-sm); color: var(--fg-2); white-space: pre-wrap; }
.notif time { font-size: var(--fs-2xs); color: var(--faint); }
+/* 故障排查(screens/troubleshoot.js):状态和检测结果是普通的行;stderr 尾部是组里展开的一块(不再套底);
+ 日志是自己的一块 --well(和代码块同一种面),不描边 */
+.ts-state { display: inline-flex; align-items: center; gap: var(--space-1-5); font-size: var(--fs-sm); color: var(--fg-2); white-space: nowrap; }
+.ts-mono { font-family: var(--code); font-size: var(--fs-xs); user-select: text; -webkit-user-select: text; }
+.settings .row .sub.ts-mono { max-width: none; word-break: break-all; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
+.ts-tail pre { margin: 0; white-space: pre-wrap; word-break: break-all; line-height: var(--lh-normal); color: var(--fg-2); max-height: 200px; overflow: auto; }
+.ts-log-head { display: flex; align-items: center; gap: var(--space-2); }
+.ts-log-head .t-meta { font-weight: var(--fw-regular); }
+.ts-log-head .grow { flex: 1; }
+.ts-log-head .text { display: inline-flex; align-items: center; gap: var(--space-1); font-weight: var(--fw-regular); }
+.ts-log {
+ margin: 0; padding: var(--card-pad); border-radius: var(--r-well); background: var(--well);
+ font: var(--fs-xs)/var(--lh-normal) var(--code); color: var(--fg-2);
+ white-space: pre-wrap; word-break: break-all; max-height: 420px; overflow: auto;
+ user-select: text; -webkit-user-select: text;
+}
+.ts-note { margin-top: var(--space-2); font-size: var(--fs-xs); color: var(--muted); line-height: var(--lh-normal); }
+
/* 机器人设置:身份是带标签的输入框(参考 Codex 的编辑页) */
.set-field { display: grid; gap: var(--space-2); margin-bottom: var(--space-5); }
.set-field .k { display: flex; align-items: baseline; gap: var(--space-2); font-size: var(--fs-md); font-weight: var(--fw-medium); color: var(--fg-2); }
diff --git a/ui/main.js b/ui/main.js
index ddd89e2..d93eb1a 100644
--- a/ui/main.js
+++ b/ui/main.js
@@ -322,7 +322,7 @@ function App() {
onWorking=${onWorking} pending=${pending[bot.id] || 0} onOpenSettings=${openSettings} onOpenBotSettings=${openBotSettings} onBotUpdated=${onBotUpdated} />`}
${(view === "new" || (view === "chat" && bots && !bots.length)) && html`<${NewBotScreen} first=${!!bots && !bots.length}
onCreated=${(b) => { reloadBots(); openChat(b.id); }} onCancel=${bots && bots.length ? () => openChat() : null} />`}
- ${view === "settings" && html`<${SettingsScreen} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} focusRow=${route.row}
+ ${view === "settings" && html`<${SettingsScreen} tab=${route.tab} query=${settingsQ} onQuery=${setSettingsQ} onTab=${(t) => openSettings(t)} focusRow=${route.row}
mf=${mf} onMfChanged=${reloadMf} onSettings=${setSettings} models=${models} modelsError=${modelsError} reloadModels=${reloadModels}
status=${status} bots=${bots} onOpenBotSettings=${openBotSettings} account=${managed ? account : null} onAccount=${setAccount} />`}
${view === "bot-settings" && routedBot && html`<${BotSettingsScreen} key=${routedBot.id} bot=${routedBot} section=${route.section}
diff --git a/ui/screens/settings.js b/ui/screens/settings.js
index dfee5bd..8728741 100644
--- a/ui/screens/settings.js
+++ b/ui/screens/settings.js
@@ -10,6 +10,7 @@ import { api } from "../lib/api.js";
import { MF_CONSOLE, MF_DOCS, MF_TOPUP, usd } from "../lib/links.js";
import { useStore, confirmSheet, failed, saved } from "../lib/store.js";
import { themeMode, setThemeMode } from "../lib/theme.js";
+import { TroubleshootPane } from "./troubleshoot.js";
export const TABS = [
["general", "常规", "sliders"],
@@ -18,6 +19,7 @@ export const TABS = [
["privacy", "隐私与安全", "lock"],
["network", "网络与访问", "globe"],
["data", "数据", "database"],
+ ["troubleshoot", "故障排查", "pulse"],
["about", "关于", "info"],
];
const ZOOMS = [
@@ -85,7 +87,7 @@ export function SettingsSide({ tab, query, onQuery, onTab, onBack, username, acc
</aside>`;
}
-export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings, account: acct, onAccount }) {
+export function SettingsScreen({ tab, query: q, onQuery: setQ, onTab, focusRow, mf, onMfChanged, onSettings, models, modelsError, reloadModels, status, bots, onOpenBotSettings, account: acct, onAccount }) {
const [s, setS] = useState(null);
const [rekey, setRekey] = useState(false);
const [notices, setNotices] = useState(false);
@@ -255,7 +257,10 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onM
{ tab: "about", id: "licenses", name: "许可与第三方声明", sub: "MIT;界面部分样式改编自 magpie(MIT)", keys: "license",
ctl: html`<button type="button" class="text" onClick=${() => setNotices(true)}>查看</button>` },
{ tab: "about", id: "diagnostics", name: "诊断信息", sub: status ? `内置模型网关 · ${GATEWAY[status.gateway.state] || status.gateway.state}${status.gateway.restarts ? ` · 重启 ${status.gateway.restarts} 次` : ""}${status.gateway.lastError ? ` · ${status.gateway.lastError}` : ""}` : "", keys: "网关 gateway magpie",
- ctl: null },
+ ctl: html`<button type="button" class="text" onClick=${() => onTab?.("troubleshoot")}>故障排查</button>` },
+ // 故障排查页是单独的面板(troubleshoot.js),这一行只给搜索用:搜"日志""测试模型"时能找到入口
+ { tab: "troubleshoot", id: "troubleshoot", name: "故障排查", sub: "模型网关与代理进程的状态、测试模型、测试代理、最近日志、复制诊断信息", keys: "日志 log 测试 test 代理 agent 卡住 转圈 诊断 diagnostics 重启",
+ ctl: html`<button type="button" class="text" onClick=${() => { setQ(""); onTab?.("troubleshoot"); }}>打开</button>` },
{ tab: "about", id: "links", name: "Modelflare", sub: "官网与文档",
ctl: html`<a class="text" href=${MF_CONSOLE} target="_blank" rel="noopener noreferrer">modelflare.dev ↗</a><a class="text" href=${MF_DOCS} target="_blank" rel="noopener noreferrer">文档 ↗</a>` },
].filter(Boolean);
@@ -271,7 +276,7 @@ export function SettingsScreen({ tab, query: q, onQuery: setQ, focusRow, mf, onM
<div class="set-body">
${!s && html`<div class="list"><div class="row"><${Skeleton} w="40%" /></div><div class="row"><${Skeleton} w="55%" /></div></div>`}
${s && !shown.length && html`<p class="set-none">没有匹配的设置</p>`}
- ${parts.map(([label, list]) => html`${label && html`<div class="set-part">${label}</div>`}
+ ${s && !needle && tab === "troubleshoot" ? html`<${TroubleshootPane} bots=${bots} desktop=${desktop} />` : parts.map(([label, list]) => html`${label && html`<div class="set-part">${label}</div>`}
<div class="list">${list.map((r) => html`<${Row} key=${r.id} id=${r.id} name=${r.name} sub=${r.sub} title=${r.title || r.sub} flash=${flash === r.id}>${r.ctl}<//>`)}</div>`)}
</div>
${rekey && html`<${Sheet} title="更换 Modelflare 密钥" onClose=${() => setRekey(false)}>
diff --git a/ui/screens/troubleshoot.js b/ui/screens/troubleshoot.js
new file mode 100644
index 0000000..55dfe82
--- /dev/null
+++ b/ui/screens/troubleshoot.js
@@ -0,0 +1,183 @@
+// 设置 → 故障排查:状态(网关、代理进程、版本、目录)、测试模型(经内置网关 vs 直连端点)、测试代理(逐段定位卡在哪)、
+// 重启代理进程、最近日志、复制诊断信息。所有内容由后端脱敏,界面不再拼接任何密钥。
+import { useEffect, useRef, useState } from "preact/hooks";
+import { html, Button, CopyButton, Icon, Skeleton } from "../components/ui.js";
+import { api } from "../lib/api.js";
+import { failed, toast } from "../lib/store.js";
+
+const GATEWAY = { running: ["运行中", "ok"], starting: ["启动中", "warn"], restarting: ["重启中", "warn"], failed: ["失败", "err"], stopped: ["已停止", "off"], external: ["外部端点", "ok"] };
+const HOST = { running: ["运行中", "ok"], starting: ["启动中", "warn"], backoff: ["等待重试", "warn"], error: ["已暂停", "err"], stopped: ["未启动", "off"] };
+const STAGE = { ok: ["通过", "ok"], warn: ["注意", "warn"], fail: ["失败", "err"], timeout: ["超时", "err"], skipped: ["未执行", "off"], pending: ["进行中", "warn"] };
+const INIT_STAGE = { prepare: "准备", "bridge ready": "模型桥已就绪", "sdk loaded": "加载运行时", "patch written": "写入配置", "child spawned": "进程已拉起", initializing: "初始化(加载插件)" };
+
+/** 代理进程一行的说明:启动中显示进度和阶段,运行中显示上次启动用时 */
+function hostSub(h) {
+ const secs = (ms) => (ms >= 10_000 ? `${Math.round(ms / 1000)} 秒` : `${(ms / 1000).toFixed(1)} 秒`);
+ if (h.state === "starting")
+ return join(`已 ${secs(h.startingForMs || 0)}`, h.initStage && `阶段:${INIT_STAGE[h.initStage] || h.initStage}`, h.firstStart && "首次启动可能需要几分钟(杀毒软件会逐个扫描运行时文件)", h.initTimeoutMs && `最多等 ${Math.round(h.initTimeoutMs / 60000)} 分钟`);
+ return join(
+ h.pid && `pid ${h.pid}`,
+ h.model,
+ h.lastInitMs && `启动用时 ${secs(h.lastInitMs)}`,
+ h.restarts ? `重启 ${h.restarts} 次` : "",
+ h.activeTurns ? `${h.activeTurns} 轮进行中` : "",
+ h.retryInMs ? `${Math.ceil(h.retryInMs / 60000)} 分钟后自动重试,或点下面的"重启代理进程"` : "",
+ exitText(h.lastExit),
+ h.lastError,
+ );
+}
+
+function Row({ id, name, sub, mono, children, compact }) {
+ return html`<div class=${`row${compact ? " compact" : ""}`} id=${id ? `ts-${id}` : undefined}>
+ <div class="who"><div class="name">${name}</div>${sub && html`<div class=${`sub wrap${mono ? " ts-mono" : ""}`}>${sub}</div>`}</div>
+ <div class="ctl">${children}</div>
+ </div>`;
+}
+
+const State = ({ map, s }) => {
+ const [text, kind] = map[s] || [s || "未知", "off"];
+ return html`<span class="ts-state"><span class=${`dot ${kind === "off" ? "" : kind}`}></span>${text}</span>`;
+};
+
+const Verdict = ({ ok }) => html`<span class="ts-state"><span class=${`dot ${ok ? "ok" : "err"}`}></span>${ok ? "正常" : "有问题"}</span>`;
+
+const ms = (v) => (v === undefined || v === null ? "" : v >= 10_000 ? `${(v / 1000).toFixed(1)} 秒` : `${v} ms`);
+const exitText = (e) => (e ? `上次退出 code=${e.code ?? "-"}${e.signal ? ` signal=${e.signal}` : ""}` : "");
+const join = (...a) => a.filter(Boolean).join(" · ");
+
+function ProbeRow({ name, p }) {
+ if (!p) return null;
+ if (p.skipped) return html`<${Row} compact name=${name} sub=${p.skipped}><span class="ts-state"><span class="dot"></span>未测</span><//>`;
+ const sub = p.ok ? join(p.url, p.echoedModel && `回显模型 ${p.echoedModel}`, p.reply && `回复 “${p.reply}”`) : join(p.url, p.error);
+ return html`<${Row} compact name=${name} sub=${sub} mono=${!p.ok}>
+ <span class="ts-state"><span class=${`dot ${p.ok ? "ok" : "err"}`}></span>${p.status ? `HTTP ${p.status}` : p.ok ? "正常" : "失败"}</span>
+ ${p.ms !== undefined && html`<span class="val num">${ms(p.ms)}</span>`}
+ <//>`;
+}
+
+export function TroubleshootPane({ bots, desktop }) {
+ const [st, setSt] = useState(null);
+ const [logs, setLogs] = useState(null);
+ const [busy, setBusy] = useState("");
+ const [modelRes, setModelRes] = useState(null);
+ const [agentRes, setAgentRes] = useState(null);
+ const logRef = useRef(null);
+ const botName = (id) => (bots || []).find((b) => b.id === id)?.name || id;
+
+ const loadStatus = () =>
+ api("/diagnostics")
+ .then((d) => {
+ setSt(d);
+ // 最近一次结果在服务端保留:切走再回来也能看到
+ if (d.last?.model) setModelRes((v) => v || d.last.model);
+ if (d.last?.agent) setAgentRes((v) => v || d.last.agent);
+ })
+ .catch(() => {});
+ const loadLogs = () =>
+ api("/diagnostics/logs?lines=200")
+ .then((d) => {
+ setLogs(d);
+ requestAnimationFrame(() => logRef.current && (logRef.current.scrollTop = logRef.current.scrollHeight));
+ })
+ .catch((e) => setLogs({ lines: [`读取日志失败:${e.message}`] }));
+
+ useEffect(() => {
+ loadStatus();
+ loadLogs();
+ const t = setInterval(loadStatus, 3000);
+ return () => clearInterval(t);
+ }, []);
+
+ const run = async (what, fn) => {
+ setBusy(what);
+ try {
+ await fn();
+ } catch (e) {
+ failed(e);
+ } finally {
+ setBusy("");
+ loadStatus();
+ loadLogs();
+ }
+ };
+ const testModel = () => run("model", async () => setModelRes(await api("/diagnostics/test-model", { method: "POST", body: {} })));
+ const testAgent = () => run("agent", async () => setAgentRes(await api("/diagnostics/test-agent", { method: "POST", body: { timeoutMs: 120000 } })));
+ const restart = () =>
+ run("restart", async () => {
+ const r = await api("/diagnostics/restart-agent", { method: "POST", body: {} });
+ toast(r.restarted.length ? "代理进程已重启" : "代理进程还没有启动,下一条消息时启动");
+ });
+ const copy = () =>
+ run("copy", async () => {
+ const { text } = await api("/diagnostics/report?lines=200");
+ await navigator.clipboard.writeText(text);
+ toast("诊断信息已复制(已去掉密钥)");
+ });
+
+ if (!st) return html`<div class="list"><div class="row"><${Skeleton} w="40%" /></div><div class="row"><${Skeleton} w="55%" /></div></div>`;
+
+ const g = st.gateway || {};
+ const hosts = Object.entries(st.agent?.hosts || {});
+ const tail = hosts.flatMap(([, h]) => h.stderrTail || []).slice(-12);
+ return html`
+ <div class="set-part">状态</div>
+ <div class="list">
+ <${Row} id="gateway" name="模型网关"
+ sub=${g.mode === "managed" ? join(g.pid && `pid ${g.pid}`, g.restarts ? `重启 ${g.restarts} 次` : "", exitText(g.lastExit), g.lastError) : join("由 AMB_MAGPIE_BASE_URL 指定", g.url)}>
+ <${State} map=${GATEWAY} s=${g.state} />
+ <//>
+ ${!st.agent?.available && html`<${Row} id="agent" name="代理进程" sub=${st.agent?.enabled ? "找不到代理运行时(DSH),机器人只能纯对话" : "代理模式已关闭,机器人只做纯对话"}><${State} map=${HOST} s="error" /><//>`}
+ ${st.agent?.available && !hosts.length && html`<${Row} id="agent" name="代理进程" sub="收到第一条消息时启动"><${State} map=${HOST} s="stopped" /><//>`}
+ ${hosts.map(([id, h]) => html`<${Row} key=${id} id=${`agent-${id}`} name=${hosts.length > 1 ? `代理进程 · ${botName(id)}` : "代理进程"}
+ sub=${hostSub(h)}>
+ <${State} map=${HOST} s=${h.state} />
+ <//>`)}
+ ${tail.length > 0 && html`<div class="row-edit ts-tail"><span class="t-label">代理进程输出(stderr 最后 ${tail.length} 行)</span><pre class="ts-mono">${tail.join("\n")}</pre></div>`}
+ <${Row} id="version" name="版本" sub=${join(st.os, st.electron && `Electron ${st.electron}`, `Node ${st.node}`)}>
+ <span class="val">${st.version} · ${st.platform} ${st.arch}</span>
+ <//>
+ <${Row} id="data-dir" name="数据目录">
+ <span class="val" title=${st.dataDir}>${st.dataDir}</span><${CopyButton} text=${st.dataDir} label="复制路径" />
+ ${desktop && html`<button type="button" class="text" onClick=${() => api("/desktop/open-data-dir", { method: "POST", body: {} }).catch(failed)}>打开</button>`}
+ <//>
+ <${Row} id="log-file" name="日志文件" sub="按大小轮转,保留最近 4 个文件">
+ <span class="val" title=${st.logFile || ""}>${st.logFile || "未启用"}</span>${st.logFile && html`<${CopyButton} text=${st.logFile} label="复制路径" />`}
+ <//>
+ </div>
+
+ <div class="set-part">检测</div>
+ <div class="list">
+ <${Row} id="test-model" name="测试模型" sub="发一个最小请求:经内置网关、直连端点各一次,对比两边的状态码、耗时与回显的模型名">
+ <${Button} size="sm" loading=${busy === "model"} disabled=${!!busy} onClick=${testModel}>测试<//>
+ <//>
+ ${modelRes && html`
+ <${Row} compact name=${modelRes.verdict} sub=${`模型 ${modelRes.model || "(无)"}`}>
+ <${Verdict} ok=${modelRes.direct.ok && (modelRes.gateway.ok || !!modelRes.gateway.skipped)} />
+ <//>
+ <${ProbeRow} name="经内置网关" p=${modelRes.gateway} />
+ <${ProbeRow} name="直连端点" p=${modelRes.direct} />`}
+ <${Row} id="test-agent" name="测试代理" sub="让代理进程完整跑一轮最小对话(不进聊天记录),看卡在哪一步:启动 → 插件 → 模型 → 回复">
+ <${Button} size="sm" loading=${busy === "agent"} disabled=${!!busy} onClick=${testAgent}>测试<//>
+ <//>
+ ${agentRes && html`
+ <${Row} compact name=${agentRes.ok ? "代理正常" : `卡在:${(agentRes.stages.find((s) => s.id === agentRes.stuckAt) || {}).label || "未知"}`}
+ sub=${join(`机器人 ${botName(agentRes.botId)}`, agentRes.model && `模型 ${agentRes.model}`, `共 ${ms(agentRes.ms)}`)}>
+ <${Verdict} ok=${agentRes.ok} />
+ <//>
+ ${agentRes.stages.map((s) => html`<${Row} compact key=${s.id} name=${s.label} sub=${s.detail} mono=${s.status === "fail" || s.status === "timeout"}>
+ <${State} map=${STAGE} s=${s.status} />${s.ms !== undefined && html`<span class="val num">${ms(s.ms)}</span>`}
+ <//>`)}`}
+ <${Row} id="restart-agent" name="重启代理进程" sub="回复一直转圈时用:结束代理进程并清掉重试等待,下一条消息重新启动">
+ <${Button} size="sm" loading=${busy === "restart"} disabled=${!!busy} onClick=${restart}>重启<//>
+ <//>
+ </div>
+
+ <div class="set-part ts-log-head">
+ <span>最近日志</span><span class="t-meta">${logs ? `${logs.lines.length} 行` : ""}</span><span class="grow"></span>
+ <button type="button" class="text" onClick=${loadLogs}><${Icon} name="refresh" size=${13} /> 刷新</button>
+ <${Button} size="sm" icon="copy" loading=${busy === "copy"} disabled=${!!busy && busy !== "copy"} onClick=${copy}>复制诊断信息<//>
+ </div>
+ <pre class="ts-log" ref=${logRef} tabindex="0" aria-label="最近日志">${logs ? logs.lines.join("\n") || "(还没有日志)" : "加载中…"}</pre>
+ <p class="ts-note">复制的诊断信息包含上面的状态、最近一次测试结果和日志,API Key、令牌等已替换成 ***,可以直接发给支持人员。</p>
+ `;
+}