agent-console 1.0.0: a page plugin that drives the local Agent CLIs (#535)

Adds Agent Console (@magpie-community/page-agent-console 1.0.0), a community page plugin that drives the Agent CLIs on this computer (Claude Code, Codex, ACP agents) through a local daemon on 127.0.0.1, with its source in packages/agent-console and a registry entry. Claude Code is the user's own `claude` CLI driven over stream-json (daemon/src/providers/claude/cli.ts); no Anthropic SDK is installed, bundled or in the branch's history. Cold install ~45 MB (node-pty ~26 MB), stated in the README and registry summary in en and zh.

By qingnian108 (#535).

What was run at 8e8f910 (mote, macOS, throwaway HOME, no real accounts):
- packages/agent-console: `npm ci --ignore-scripts --workspaces=false`; `node scripts/verify-build.mjs`: all five bundles byte-identical (daemon/dist/main.js 08c95aa3…, app/app.js 9a6911f3…); `vitest run`: 45 files, 254 passed, 17 skipped; `npm run check` clean.
- Real Claude Code 2.1.316 (npm @anthropic-ai/claude-code, sandbox HOME/CLAUDE_CONFIG_DIR, local fake Messages API): `AC_REAL_CLAUDE=… vitest run --config vitest.real.config.ts test/real/claude-cli.real.test.ts`: 4 of 4 (initialize lists 51 slash commands, streaming turn, Bash permission approved and denied, interrupt, --resume with set_model).
- Probe: the driver's exact argv with `--permission-mode bypassPermissions --allow-dangerously-skip-permissions`: the tool runs with no can_use_tool request.
- Repo root: `HOME=$(mktemp -d) bun test`: 4006 tests, 0 fail; `bun scripts/check.mjs` exit 0.
- Install as magpie does: `npm pack --ignore-scripts` (552 KB) then `bun add --ignore-scripts`: 45 MB node_modules, no @anthropic-ai/*, index.mjs imports.
- Read every changed line since 41c7a94: argv values limited to SAFE_ARG tokens (no cmd.exe metacharacters reach the shim path), no new network hosts, no install scripts, no eval; no commit in main..8e8f910 contains claude-agent-sdk.

Not tried: magpie's desktop window loading the page; a Windows .cmd/.ps1 claude shim end to end.
This commit is contained in:
qingnian108
2026-10-31 20:11:22 +08:00
committed by GitHub
parent 62ba6d7267
commit a431798fe1
527 changed files with 180426 additions and 0 deletions
@@ -0,0 +1,33 @@
// Chromium-family browser for the e2e / screenshot scripts: MSEDGE_PATH / CHROME_PATH first,
// then the usual Edge, Chrome and Chromium install locations per platform.
import { existsSync } from "node:fs";
export function findBrowser(env = process.env, platform = process.platform, exists = existsSync) {
const explicit = env.MSEDGE_PATH || env.CHROME_PATH;
if (explicit) return explicit;
const local = env.LOCALAPPDATA || "";
const candidates =
platform === "win32"
? [
"C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe",
"C:/Program Files/Microsoft/Edge/Application/msedge.exe",
"C:/Program Files/Google/Chrome/Application/chrome.exe",
"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
local && `${local.replace(/\\/g, "/")}/Google/Chrome/Application/chrome.exe`,
]
: platform === "darwin"
? [
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"/Applications/Chromium.app/Contents/MacOS/Chromium",
]
: [
"/usr/bin/microsoft-edge",
"/usr/bin/google-chrome",
"/usr/bin/google-chrome-stable",
"/usr/bin/chromium",
"/usr/bin/chromium-browser",
"/snap/bin/chromium",
];
return candidates.filter(Boolean).find((p) => exists(p));
}
+100
View File
@@ -0,0 +1,100 @@
// Deterministic v1 build: daemon ESM bundle plus browser bundle and HTML.
import * as esbuild from "esbuild";
import { copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
export const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
export function options(outRoot = root) {
return {
daemon: {
entryPoints: ["daemon/src/main.ts"],
absWorkingDir: root,
platform: "node",
format: "esm",
target: "node20",
bundle: true,
packages: "external",
outfile: path.join(outRoot, "daemon/dist/main.js"),
sourcemap: "linked",
sourceRoot: "",
banner: {
js: "import { createRequire } from 'module'; const require = createRequire(import.meta.url);",
},
logLevel: "silent",
},
web: {
entryPoints: ["web/src/main.tsx"],
absWorkingDir: root,
platform: "browser",
format: "iife",
target: "es2020",
bundle: true,
minify: true,
jsx: "automatic",
jsxImportSource: "react",
outfile: path.join(outRoot, "app/app.js"),
loader: { ".svg": "text" },
define: { "process.env.NODE_ENV": '"production"' },
logLevel: "silent",
},
};
}
async function normalizeSourcemap(outRoot) {
const file = path.join(outRoot, "daemon/dist/main.js.map");
const map = JSON.parse(await readFile(file, "utf8"));
// Esbuild makes sources relative to the outfile; normalize temporary-output paths
// so a clean build and the committed build have identical bytes.
// Sources live under the repo root (daemon/src, lib/); express each one relative to
// <repo>/daemon/dist regardless of where this build was written.
const outDir = path.join(outRoot, "daemon/dist");
map.sources = map.sources.map((source) => {
// esbuild URL-encodes non-ASCII characters in paths (e.g. "magpie插件") in sources; decode them before computing the relative path,
// otherwise building from a temp directory under a non-ASCII directory doesn't yield ../src/… and verify:build reports a false main.js.map mismatch
let decoded = source;
try {
decoded = decodeURIComponent(source);
} catch {}
const abs = path.resolve(outDir, decoded);
let rel = path.relative(outRoot, abs);
if (rel.startsWith("..") || path.isAbsolute(rel)) rel = path.relative(root, abs);
return path.posix.relative("daemon/dist", rel.split(path.sep).join("/"));
});
await writeFile(file, JSON.stringify(map));
}
export async function buildAll(outRoot = root) {
const buildOptions = options(outRoot);
await mkdir(path.join(outRoot, "daemon/dist"), { recursive: true });
await mkdir(path.join(outRoot, "app"), { recursive: true });
await copyFile(path.join(root, "web/index.html"), path.join(outRoot, "app/index.html"));
await Promise.all([esbuild.build(buildOptions.daemon), esbuild.build(buildOptions.web)]);
if (!existsSync(path.join(outRoot, "app/app.css")))
await writeFile(path.join(outRoot, "app/app.css"), "/* built by build-v1 */\n");
await normalizeSourcemap(outRoot);
}
async function main() {
await buildAll();
const size = await stat(path.join(root, "app/app.js"));
if (size.size > 3 * 1024 * 1024)
console.warn(`[build-v1] warning: app.js ${(size.size / 1024 / 1024).toFixed(2)}MB exceeds 3MB budget`);
else console.log(`[build-v1] app.js ${(size.size / 1024).toFixed(0)}KB`);
console.log("[build-v1] complete");
}
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
if (process.argv.includes("--watch")) {
const buildOptions = options();
await copyFile(path.join(root, "web/index.html"), path.join(root, "app/index.html"));
const daemonContext = await esbuild.context(buildOptions.daemon);
const webContext = await esbuild.context(buildOptions.web);
await Promise.all([daemonContext.watch(), webContext.watch()]);
console.log("[build-v1] watch mode started");
} else {
await main();
}
}
+541
View File
@@ -0,0 +1,541 @@
// e2e (§11.2): playwright-core + Edge, isolated data directory _tmp/e2e-xdg, port 3497, AGENT_CONSOLE_MOCK=1.
// Scenarios 1–12, 16–19; each prints ✓/✗, and any ✗ exits with code 1.
import { spawn, execFileSync } from "node:child_process";
import { findBrowser } from "./browser-path.mjs";
import { mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright-core";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const TMP = join(root, "_tmp");
const XDG = join(TMP, "e2e-xdg");
const PROJ = join(TMP, "e2e-proj");
const PORT = 3497;
// Edge / Chrome / Chromium (Windows, macOS, Linux); MSEDGE_PATH or CHROME_PATH may be set
const EDGE = findBrowser();
const results = [];
const pageErrors = [];
let daemon, page, browser;
let daemonErr = [];
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const log = (...a) => console.log(...a);
function record(name, ok, extra = "") {
results.push({ name, ok });
log(`${ok ? "✓" : "✗"} ${name}${extra ? " " + extra : ""}`);
}
async function wsCall(method, params) {
return page.evaluate(async ([m, p]) => {
const ws = window.__ws;
return await ws.call(m, p);
}, [method, params]);
}
async function waitFor(fn, ms = 15000, label = "") {
const t0 = Date.now();
while (Date.now() - t0 < ms) {
try {
const v = await fn();
if (v) return v;
} catch {}
await sleep(200);
}
throw new Error("等待超时 " + label);
}
const sel = {
newProject: 'text=新建项目',
dlgInput: '.dlg .tinput',
dlgAdd: '.dlg .btn.primary',
threadItem: '.t-item',
ta: '.cp-ta',
send: '.cp-send',
stop: '.cp-stop',
permCard: '.card.perm',
allow: 'button:has-text("允许")',
queueItem: '.q-item',
pill: '.tb-pill',
};
async function setup() {
rmSync(XDG, { recursive: true, force: true });
rmSync(PROJ, { recursive: true, force: true });
mkdirSync(PROJ, { recursive: true });
writeFileSync(join(PROJ, "a.txt"), "alpha\nbeta\n");
writeFileSync(join(PROJ, "b.txt"), "gamma\n");
mkdirSync(join(PROJ, "src"), { recursive: true });
writeFileSync(join(PROJ, "src", "index.ts"), "const x = 1;\n");
writeFileSync(join(PROJ, ".gitattributes"), "* -text\n");
// Initialize e2e-proj as a git repository (scenario 13 needs it)
try {
const g = (a) => execFileSync("git", a, { cwd: PROJ, stdio: "pipe", windowsHide: true });
g(["init"]); g(["config", "user.email", "e@e"]); g(["config", "user.name", "e"]);
g(["config", "core.autocrlf", "false"]); // Keep CRLF from making a.txt show as modified again after restore
g(["add", "-A"]); g(["commit", "-m", "init", "-q"]);
} catch (e) { log("[e2e] git init 失败(场景13 会失败):", String(e).slice(0, 120)); }
daemon = spawn("node", [join(root, "daemon/dist/main.js"), "--port", String(PORT), "--data", XDG], {
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
});
daemonErr = [];
daemon.stderr.on("data", (d) => { daemonErr.push(String(d).trim()); process.stderr.write(`[daemon] ${d}`); });
daemon.stdout.on("data", (d) => { const s = String(d); if (s.includes("已启动") || s.includes("error")) log("[daemon]", s.trim()); });
// Wait for ping
const t0 = Date.now();
let token = null;
while (Date.now() - t0 < 15000) {
try {
const dj = JSON.parse(readFileSync(join(XDG, "magpie/agent-console/daemon.json"), "utf8"));
token = dj.token;
break;
} catch { await sleep(300); }
}
if (!token) throw new Error("daemon 未启动");
globalThis.__token = token;
browser = await chromium.launch({ executablePath: EDGE, headless: true, args: process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [] });
page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
page.on("pageerror", (e) => pageErrors.push(`pageerror: ${e.message}`));
page.on("dialog", (d) => { pageErrors.push(`dialog: ${d.message()}`); void d.dismiss(); });
page.on("console", (m) => { if (m.type() === "error") pageErrors.push(`console: ${m.text()}`); if (m.text().startsWith("[tl]") || m.text().startsWith("[ws]")) pageErrors.push(`dbg: ${m.text()}`); });
await page.goto(`http://127.0.0.1:${PORT}/?lang=zh#t=${encodeURIComponent(token)}`, { waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", { timeout: 10000 });
// e2e uses the Mock provider (real Claude would show permission prompts and bill usage)
await wsCall("settings.set", { patch: { defaultProvider: "mock" } });
// Codex detection in providers.list takes seconds: wait for the data layer before acting, so the empty-conversation composer and "+" don't each create a conversation
await page.waitForFunction(() => window.__stores?.useData?.getState?.().loaded === true, { timeout: 20000 });
}
async function newProjectFlow() {
// Scenario 1: no-project onboarding → create → land in a new conversation
await page.click(sel.newProject);
await page.fill(sel.dlgInput, PROJ);
await page.waitForSelector('text=目录可用', { timeout: 5000 });
await page.click(sel.dlgAdd);
await waitFor(async () => (await page.$$('.pj-group')).length >= 1, 8000, "项目组出现");
// New conversation (project row +); wait until it's really selected — the empty state also has .cp-ta, and acting early would create another conversation
await page.hover('.pj');
await page.click('.pj-act[title="新建对话"]');
await page.waitForSelector('.t-item.on', { timeout: 8000 });
await page.waitForSelector(sel.ta, { timeout: 5000 });
record("场景1 新建项目→新对话", true);
}
async function send(text) {
await page.fill(sel.ta, text);
await page.keyboard.press("Enter");
}
// End-of-turn markers: count turnend/err entries in the store, not the DOM (the virtual list renders only the visible area, so DOM counts miss some).
async function endCount() {
return await page.evaluate(() => {
const items = window.__tl?.getState?.().items ?? [];
return items.filter((i) => i.kind === "turnend" || (i.kind === "permission" && i.status !== "pending")).length;
});
}
async function waitEnd(seq = 0) {
const t0 = Date.now();
while (Date.now() - t0 < 45000) {
const n = await endCount();
if (n > seq) return n;
// The daemon is idle but the DOM has no closing marker, which is also wrong → fall back to checking the DOM
const st = await wsCall("threads.get", { id: await curThread() }).then((g) => g.runtimeStatus).catch(() => "?");
if (st !== "running" && st !== "initializing") {
await sleep(400); // Wait for the last frame to render
if ((await endCount()) > seq) return seq + 1;
}
await sleep(300);
}
const dbg = await wsCall("threads.get", { id: await curThread() }).then((g) => `${g.runtimeStatus} evts:${g.events.length} last:${g.events.map(e=>e.type).slice(-3).join(",")} provider:${g.meta.provider}`).catch((e) => String(e));
const dom = await page.evaluate(() => document.querySelector(".tl-wrap")?.innerText?.slice(-200)).catch(() => "?");
throw new Error(`等待超时 turn_ended ${seq}(${dbg})dom尾=${dom}`);
}
async function scenario2() {
await send("看下这个项目");
await waitEnd();
const checks = await page.evaluate(() => ({
md: !!document.querySelector(".md"),
tg: !!document.querySelector(".tg"),
diff: !!document.querySelector(".diff"),
todo: !!document.querySelector(".rs-item"),
te: !!document.querySelector(".te"),
}));
record("场景2 默认剧本(正文/工具组/diff/待办/结束行)", checks.md && checks.tg && checks.diff && checks.todo && checks.te, JSON.stringify(checks));
}
async function scenario3() {
const sid0 = await wsCall("threads.get", { id: await curThread() }).then((g) => g.meta.providerSessionId);
await send("再问一句");
await waitEnd(1);
const sid1 = await wsCall("threads.get", { id: await curThread() }).then((g) => g.meta.providerSessionId);
record("场景3 多轮同一会话(providerSessionId 不变)", sid0 === sid1 && !!sid0, `${sid0} → ${sid1}`);
}
let _tid = null;
async function curThread() {
// Use the conversation currently selected on the page (threads.list()[0] is sorted by updatedAt and picks the wrong one with several conversations)
if (!_tid) _tid = await page.evaluate(() => window.__stores?.useUi?.getState?.().currentThreadId ?? null);
return _tid;
}
async function scenario4() {
await send("/slow");
await waitFor(async () => (await page.$(sel.pill)) !== null, 8000, "running 胶囊");
await send("排队消息一");
await send("排队消息二");
const n = await waitFor(async () => {
const c = await page.$$eval(sel.queueItem, (e) => e.length);
return c >= 2 ? c : null;
}, 5000, "排队列表");
await waitEnd(1 + await page.$$eval('.te', (e) => e.length).catch(() => 1)); // Wait for slow to finish, then queue two more turns
// Wait for three turnends: slow + queue 1 + queue 2 — relaxed to waiting until the queue is empty
await waitFor(async () => (await page.$$eval(sel.queueItem, (e) => e.length)) === 0, 45000, "队列清空");
record("场景4 /slow 排队列表 + 自动发送", n >= 2);
}
async function scenario5() {
await send("/slow");
await waitFor(() => page.$(sel.stop), 8000, "运行中");
await page.keyboard.down("Control");
await page.fill(sel.ta, "插话内容XYZ");
await page.keyboard.press("Enter");
await page.keyboard.up("Control");
await waitFor(async () => {
const html = await page.content();
return html.includes("插话:插话内容XYZ");
}, 40000, "回复含插话");
record("场景5 Ctrl+Enter 插话", true);
}
async function scenario6() {
await send("/slow");
await waitFor(() => page.$(sel.stop), 8000, "stop 按钮");
const t0 = Date.now();
await page.click(sel.stop);
await waitFor(async () => {
const g = await wsCall("threads.get", { id: await curThread() });
return g.runtimeStatus === "idle" || g.runtimeStatus === "closed" ? true : null;
}, 8000, "idle");
const ms = Date.now() - t0;
await send("停完再来一句");
await waitEnd(await page.$$eval('.te, .err-card', (e) => e.length));
record("场景6 停止≤1s→idle→再发成功", ms < 5000, `interrupted ${ms}ms`);
}
async function scenario7() {
const tid = await curThread();
await send("/perm");
await page.waitForSelector(sel.permCard, { timeout: 15000 });
const waiting = await page.$eval(sel.ta, (el) => el.placeholder.includes("授权"));
await page.click(`${sel.permCard} button:has-text("允许")`);
await waitEnd(await page.$$eval('.te', (e) => e.length - 0));
// Deny path
await send("/perm");
await page.waitForSelector(`${sel.permCard} button:has-text("拒绝")`, { timeout: 15000 });
await page.click(`${sel.permCard} button:has-text("拒绝")`);
await waitFor(async () => {
const html = await page.content();
return html.includes("已被用户拒绝") || html.includes("已按你的要求跳过");
}, 15000, "拒绝后回复");
record("场景7 授权卡片 允许/拒绝", waiting);
}
async function scenario8() {
await send("/plan");
await page.waitForSelector('.card.plan', { timeout: 15000 });
await page.click('.card.perm button:has-text("开始实施")');
await waitEnd(await page.$$eval('.te', (e) => e.length - 0));
const mode = await wsCall("threads.get", { id: await curThread() }).then((g) => g.meta.mode);
record("场景8 计划卡片 → 实施(模式变化检查)", mode !== null);
}
async function scenario9() {
await send("/ask");
await page.waitForSelector('.card.ask', { timeout: 15000 });
await page.click('.card.ask button:has-text("生产环境")');
await page.fill('.ask-free', "记得备份");
await page.click('.card.ask button:has-text("提交")');
await waitFor(async () => (await page.content()).includes("生产环境"), 15000, "回复含答案");
record("场景9 提问卡片 → 回复包含答案", true);
}
async function scenario10() {
await send("/exit");
let last = "?";
try {
await waitFor(async () => {
const g = await wsCall("threads.get", { id: await curThread() });
last = `${g.runtimeStatus}/${g.meta.status} evts:${g.events.length}`;
return g.runtimeStatus === "closed" || g.meta.status === "closed" ? true : null;
}, 15000, "closed");
} catch (e) {
const dom = await page.evaluate(() => document.querySelector(".cp-ta")?.placeholder + "|disabled:" + document.querySelector(".cp-ta")?.disabled + "|" + document.querySelector(".tl-wrap")?.innerText?.slice(-150));
throw new Error(`等待超时 closed last=${last} dom=${dom}`);
}
await send("你还在吗");
try {
await waitFor(async () => (await page.content()).includes("(已续接)"), 20000, "续接前缀");
} catch (e) {
const g = await wsCall("threads.get", { id: await curThread() }).catch((x) => String(x));
const dbg = await page.evaluate(() => {
const tl = window.__tl?.getState?.();
return {
status: tl?.status, tid: tl?.threadId, n: tl?.items?.length, deduped: tl?.deduped, gaps: tl?.gaps?.slice(0, 8), seqMax: tl?.seqMax, evCount: tl?.evCount,
tail: tl?.items?.slice(-6).map((i) => `${i.kind}:${(i.text ?? i.title ?? "").slice(0, 40)}`),
dom: document.querySelector(".tl-wrap")?.innerText?.slice(-150),
};
}).catch((x) => String(x));
throw new Error(`续接前缀超时 rt=${g.runtimeStatus} meta=${g.meta?.status} evts=${g.events?.length} last=${g.events?.slice(-5).map((x) => x.type + ":" + (x.status ?? "")).join(",")} dbg=${JSON.stringify(dbg).slice(0, 200)} logs=${pageErrors.filter((e) => e.startsWith("dbg:")).slice(-6).join("|")}`);
}
record("场景10 /exit 崩溃 → 再发续接", true);
}
async function scenario11() {
await send("/perm");
await page.waitForSelector(sel.permCard, { timeout: 15000 });
await page.reload({ waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", { timeout: 10000 });
// After a reload the current conversation is still there (lastThreadId) and so is the card (pending or cancelled)
await waitFor(async () => (await page.$('.card.perm')) !== null || (await page.$('.cp-ta')) !== null, 10000, "刷新后恢复");
const hasPerm = await page.$('.card.perm');
const cur = await curThread().catch(() => null);
const selTid = await page.evaluate(() => window.__stores?.useUi?.getState?.().currentThreadId).catch(() => "?");
record("场景11 刷新恢复(对话/卡片)", !!cur && !!hasPerm, `cur=${cur} sel=${selTid} perm=${!!hasPerm}`);
// Cleanup: cancel this permission card (deny) so it doesn't block later scenarios
try {
const g = await wsCall("threads.get", { id: cur });
const pend = g.pending?.[0];
if (pend) await wsCall("thread.respond", { id: cur, requestId: pend.requestId, optionId: "decline" });
} catch {}
}
async function scenario12() {
// Upload a small png with the attachment button (setInputFiles goes through input[type=file])
const png = join(TMP, "e2e.png");
writeFileSync(png, Buffer.from("89504e470d0a1a0a0000000d49484452000000010000000108060000001f15c4890000000d49444154789c626001000000ffff03000006000557bfabd40000000049454e44ae426082", "hex"));
const input = await page.waitForSelector('input[type=file]', { state: "attached", timeout: 8000 });
await input.setInputFiles(png);
await page.waitForSelector('.att', { timeout: 8000 });
// Wait for the upload to finish (send is disabled while uploading)
try {
await waitFor(async () => !(await page.$eval(sel.send, (b) => b.disabled).catch(() => true)), 15000, "上传完成");
} catch (e) {
const probe = await page.evaluate(async () => {
const tl = window.__tl?.getState?.();
return {
pending: tl?.pending, status: tl?.status,
atts: [...document.querySelectorAll(".att")].map((a) => a.outerHTML.slice(0, 120)),
sendDisabled: document.querySelector(".cp-send")?.disabled,
};
});
throw new Error(`上传完成超时 ${JSON.stringify(probe)} errs=${pageErrors.slice(-6).join("|").slice(0, 300)}`);
}
await page.click(sel.send);
// Verify at the data layer (the user message has an attachment of image type); thumbnail rendering is the UI layer's job
await waitFor(async () => {
const g = await wsCall("threads.get", { id: await curThread() });
const um = g.events.filter((e) => e.type === "user_message").pop();
return um?.attachments?.some((a) => a.mime?.startsWith("image/")) ? true : null;
}, 15000, "用户消息带图片附件");
await waitFor(async () => (await page.$('.um-img')) !== null || (await page.evaluate(() => {
const items = window.__tl?.getState?.().items ?? [];
return items.some((i) => i.kind === "user" && i.attachments?.length);
})), 15000, "缩略图条目");
record("场景12 附件上传 → 用户消息含缩略图", true);
}
async function scenario16() {
await page.keyboard.press("Control+k");
await page.waitForSelector(".cpal", { timeout: 5000 });
const title = await page.$eval('.t-item.on .t-title, .t-item .t-title', (e) => e.textContent).catch(() => "新对话");
await page.fill(".cpal-in", "新对话");
await page.keyboard.press("Enter");
await sleep(400);
const on = await page.$eval(".tb-title", (e) => e.textContent).catch(() => "");
record("场景16 命令面板 → 打开对话", !!on);
}
async function scenario17() {
const t0 = Date.now();
await send("/long");
const opened = Date.now() - t0;
await waitFor(async () => (await page.$('.te')) !== null, 60000, "/long 完成");
// Scroll to the top and back to the bottom without errors (virtual list already tested; check for no new pageerror)
const errBefore = pageErrors.length;
await page.evaluate(() => { const s = document.querySelector(".scroll"); s.scrollTop = 0; });
await sleep(300);
await page.evaluate(() => { const s = document.querySelector(".scroll"); s.scrollTop = s.scrollHeight; });
await sleep(300);
record("场景17 /long 打开 ≤1s(记录值)+ 滚动无错", opened < 3000 && pageErrors.length === errBefore, `${opened}ms`);
}
async function scenario18() {
await page.setViewportSize({ width: 560, height: 900 });
await sleep(400);
const res = await page.evaluate(() => {
const sb = document.querySelector(".sidebar");
const st = getComputedStyle(sb);
return {
sbFixed: st.position === "fixed",
noHScroll: document.documentElement.scrollWidth <= 560 + 1,
};
});
record("场景18 窄屏 560px:抽屉 + 无横向滚动", res.sbFixed && res.noHScroll, JSON.stringify(res));
await page.setViewportSize({ width: 1440, height: 900 });
}
async function scenario19() {
// Filter benign console errors (e.g. favicon 404)
const bad = pageErrors.filter((e) => !/favicon|404|net::/i.test(e) && !e.startsWith("dbg:"));
record("场景19 无 pageerror / console error", bad.length === 0, bad.slice(0, 3).join(" | "));
}
async function scenario13() {
// e2e-proj is already a git repository; make a change → changes panel appears → click diff → discard → it disappears
const pid = await page.evaluate(() => {
const ui = window.__stores.useUi.getState();
const data = window.__stores.useData.getState();
const th = data.threads.find((t) => t.id === ui.currentThreadId);
return th?.projectId ?? ui.currentProjectId ?? data.projects[0]?.id;
});
writeFileSync(join(PROJ, "a.txt"), "alpha\nbeta\nCHANGEME\n");
await page.click('.ibtn[title="改动(Ctrl+J)"]');
await page.waitForSelector(".chg-row", { timeout: 8000 });
const name = await page.$eval(".chg-row .chg-path", (e) => e.textContent);
await page.click(".chg-row");
await page.waitForSelector(".chg-diff .diff", { timeout: 8000 });
const hasAdd = await page.$eval(".chg-diff", (e) => e.textContent.includes("CHANGEME"));
// Discard the change
await page.hover(".chg-row");
await page.click(".chg-discard");
await page.waitForSelector(".dlg", { timeout: 5000 });
await page.click('.dlg .btn.danger');
try {
await waitFor(async () => {
const st = await wsCall("git.status", { projectId: pid });
return !(st.files ?? []).some((f) => f.path === "a.txt") ? true : null;
}, 10000, "a.txt 改动消失");
} catch (e) {
const st = await wsCall("git.status", { projectId: pid }).catch((x) => String(x));
const onDisk = readFileSync(join(PROJ, "a.txt"), "utf8");
throw new Error(`${e.message} | status=${JSON.stringify(st).slice(0, 300)} | disk=${JSON.stringify(onDisk).slice(0, 120)} | pid=${pid}`);
}
await waitFor(async () => {
const p = await page.$$eval(".chg-path", (e) => e.map((x) => x.textContent));
return !p.includes("a.txt") ? true : null;
}, 6000, "a.txt 行从 DOM 消失");
const rowPaths = await page.$$eval(".chg-path", (e) => e.map((x) => x.textContent));
const aTxtGone = !rowPaths.includes("a.txt");
record("场景13 改动面板:列表→diff→放弃→a.txt 消失", name === "a.txt" && hasAdd && aTxtGone, `file=${name} add=${hasAdd} rows=${JSON.stringify(rowPaths)}`);
}
async function scenario14() {
await page.click('.ibtn[title="文件"]');
await page.waitForSelector(".ft-row", { timeout: 8000 });
// Expand src/ and click a.txt to preview it
const rows = await page.$$eval(".ft-row .ft-name", (els) => els.map((e) => e.textContent));
await page.click('.ft-row:has-text("src")');
await page.waitForSelector('.ft-row:has-text("index.ts")', { timeout: 5000 });
await page.click('.ft-row:has-text("a.txt")');
await page.waitForSelector(".ft-pre", { timeout: 8000 });
const text = await page.$eval(".ft-pre", (e) => e.textContent);
record("场景14 文件面板:树展开 + 预览", rows.includes("src") && text.includes("alpha"), `rows=${rows.length} text=${text.slice(0, 30)}`);
}
async function scenario15() {
await page.click('.ibtn[title="终端"]');
// New terminal
await waitFor(async () => {
const empty = await page.$('.tm-body .pn-empty .btn');
if (empty) { await empty.click(); return true; }
return (await page.$$(".tm-view")).length > 0 ? true : null;
}, 5000, "新建终端");
await waitFor(async () => (await page.$$(".tm-tab")).length >= 1, 8000, "终端 tab");
// Wait for xterm to mount + attach to finish, then type echo hello-e2e
try {
await page.waitForSelector(".tm-view .xterm", { timeout: 10000 });
} catch (e) {
const dbg = await page.evaluate(() => ({
tabs: [...document.querySelectorAll(".tm-tab")].map((x) => x.textContent),
views: [...document.querySelectorAll(".tm-view")].map((x) => ({ d: x.style.display, cs: getComputedStyle(x).display, w: x.offsetWidth, h: x.offsetHeight })),
pnBody: document.querySelector(".pn-body")?.className,
panelOpen: window.__stores?.useUi?.getState?.().panelOpen,
})).catch((x) => String(x));
throw new Error(`xterm 未可见 ${JSON.stringify(dbg)}`);
}
await sleep(1200); // Type only after the attach snapshot has been replayed
await page.click(".tm-view .xterm");
await page.keyboard.type("echo hello-e2e", { delay: 10 });
await page.keyboard.press("Enter");
await waitFor(async () => {
const t = await page.$eval(".tm-view .xterm", (e) => e.textContent).catch(() => "");
return t.includes("hello-e2e") ? true : null;
}, 15000, "终端输出 echo");
// Reload the page → the terminal is still there with its history
await page.reload({ waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", { timeout: 10000 });
await page.waitForFunction(() => window.__stores?.useData?.getState?.().loaded === true, { timeout: 20000 });
// Panel state persists in settings: after a reload, don't click if it's already open (clicking again would close it)
const needOpen = await page.evaluate(() => {
const u = window.__stores.useUi.getState();
return !(u.panelOpen && u.panelTab === "terminal");
});
if (needOpen) await page.click('.ibtn[title="终端"]');
await waitFor(async () => (await page.$$(".tm-tab")).length >= 1, 10000, "刷新后终端仍在");
try {
await page.waitForSelector(".tm-view .xterm", { timeout: 10000 });
} catch (e) {
const dbg = await page.evaluate(() => ({
tabs: [...document.querySelectorAll(".tm-tab")].map((x) => x.textContent),
views: [...document.querySelectorAll(".tm-view")].map((x) => ({ d: x.style.display, cs: getComputedStyle(x).display, w: x.offsetWidth, h: x.offsetHeight })),
terms: [...document.querySelectorAll(".tm-body")].map((x) => x.childElementCount),
})).catch((x) => String(x));
throw new Error(`刷新后 xterm 未可见 ${JSON.stringify(dbg)}`);
}
await waitFor(async () => {
const t = await page.$eval(".tm-view .xterm", (e) => e.textContent).catch(() => "");
return t.includes("hello-e2e") ? true : null;
}, 15000, "刷新后历史仍在");
record("场景15 终端:echo→输出→刷新→历史仍在", true);
}
async function main() {
await setup();
try {
await newProjectFlow();
await scenario2();
await scenario3();
await scenario4();
await scenario5();
await scenario6();
await scenario7();
await scenario8();
await scenario9();
await scenario10();
await scenario11();
await scenario12();
await scenario13();
await scenario14();
await scenario15();
await scenario16();
await scenario17();
await scenario18();
await scenario19();
} catch (e) {
record("中途异常", false, String(e?.message ?? e).slice(0, 600) + " ||daemon:" + daemonErr.slice(-4).join("|").slice(0, 400));
}
const pass = results.filter((r) => r.ok).length;
log(`\n===== ${pass}/${results.length} 通过 =====`);
await browser?.close().catch(() => {});
daemon?.kill();
process.exit(results.every((r) => r.ok) ? 0 : 1);
}
main().catch((e) => { console.error(e); daemon?.kill(); process.exit(1); });
+199
View File
@@ -0,0 +1,199 @@
// Screenshot self-check (§11.3): playwright-core + Edge, scenarios × light/dark × 1440/960/560 → _tmp/shots/v1/.
// Scenarios: empty-project onboarding, empty conversation, default script finished, permission card, plan card, command palette (panel scenarios belong to P3-5).
// Each scenario also captures ?audit=1 metrics → _tmp/shots/v1/audit.json.
import { spawn } from "node:child_process";
import { findBrowser } from "./browser-path.mjs";
import { mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { chromium } from "playwright-core";
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const TMP = join(root, "_tmp");
const XDG = join(TMP, "shot-xdg");
const PROJ = join(TMP, "shot-proj");
const OUT = join(TMP, "shots", "v1");
const PORT = 3497;
// Edge / Chrome / Chromium (Windows, macOS, Linux); MSEDGE_PATH or CHROME_PATH may be set
const EDGE = findBrowser();
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const audits = {};
let daemon, browser;
async function wsCall(page, m, p) {
return page.evaluate(async ([m, p]) => await window.__ws.call(m, p), [m, p]);
}
async function setup() {
rmSync(XDG, { recursive: true, force: true });
rmSync(PROJ, { recursive: true, force: true });
rmSync(OUT, { recursive: true, force: true });
mkdirSync(PROJ, { recursive: true });
mkdirSync(OUT, { recursive: true });
writeFileSync(join(PROJ, "a.txt"), "alpha\nbeta\n");
// The changes panel scenario needs a git repository
try {
const { execFileSync } = await import("node:child_process");
const g = (a) => execFileSync("git", a, { cwd: PROJ, stdio: "pipe", windowsHide: true });
g(["init"]); g(["config", "user.email", "s@s"]); g(["config", "user.name", "s"]);
g(["config", "core.autocrlf", "false"]);
g(["add", "-A"]); g(["commit", "-m", "init", "-q"]);
} catch {}
daemon = spawn("node", [join(root, "daemon/dist/main.js"), "--port", String(PORT), "--data", XDG], {
env: { ...process.env, AGENT_CONSOLE_MOCK: "1" },
stdio: ["ignore", "pipe", "pipe"], windowsHide: true,
});
daemon.stderr.on("data", (d) => process.stderr.write(`[daemon] ${d}`));
const t0 = Date.now();
while (Date.now() - t0 < 15000) {
try { JSON.parse(readFileSync(join(XDG, "magpie/agent-console/daemon.json"), "utf8")); break; }
catch { await sleep(300); }
}
browser = await chromium.launch({ executablePath: EDGE, headless: true, args: process.platform === "linux" && process.getuid?.() === 0 ? ["--no-sandbox"] : [] });
}
// A separate page per scenario: set up the state first, then switch theme/width and shoot
async function newPage(width, theme, audit = false) {
const page = await browser.newPage({ viewport: { width, height: 900 } });
const dj = JSON.parse(readFileSync(join(XDG, "magpie/agent-console/daemon.json"), "utf8"));
const query = `?theme=${encodeURIComponent(theme)}&lang=zh${audit ? "&audit=1" : ""}`;
await page.goto(`http://127.0.0.1:${PORT}/${query}#t=${encodeURIComponent(dj.token)}`, { waitUntil: "domcontentloaded" });
await page.waitForFunction(() => window.__ws && window.__ws.getState() === "open", { timeout: 10000 });
await page.waitForFunction(() => window.__stores?.useData?.getState?.().loaded === true, { timeout: 20000 });
await wsCall(page, "settings.set", { patch: { defaultProvider: "mock" } });
return page;
}
async function shot(page, name, theme, width) {
await page.screenshot({ path: join(OUT, `${name}-${theme}-${width}.png`) });
}
async function grabAudit(page, name, theme, width) {
const el = await page.waitForSelector("#audit", { state: "attached", timeout: 8000 }).catch(() => null);
if (!el) { audits[`${name}-${theme}-${width}`] = { error: "no audit" }; return; }
audits[`${name}-${theme}-${width}`] = JSON.parse(await el.textContent());
}
// —— scenario setup (each state once, then one shot for each of 3 widths × 2 themes) ——
// For simplicity: evaluate inside the page to change data-theme + viewport and reshoot, instead of rebuilding the state for every combination.
async function scenario_emptyProject() {
const page = await newPage(1440, "light");
// No project: empty onboarding
return page;
}
async function scenario_emptyThread(page) {
// Create a project + conversation but send no message
await page.click("text=新建项目");
await page.fill(".dlg .tinput", PROJ);
await page.waitForSelector("text=目录可用");
await page.click(".dlg .btn.primary");
await sleep(600);
await page.hover(".pj");
await page.click('.pj-act[title="新建对话"]');
await page.waitForSelector(".t-item.on", { timeout: 8000 });
}
async function scenario_default(page) {
await page.fill(".cp-ta", "看下这个项目");
await page.keyboard.press("Enter");
// Wait for turn_ended
const t0 = Date.now();
while (Date.now() - t0 < 45000) {
const g = await wsCall(page, "threads.get", { id: await page.evaluate(() => window.__stores.useUi.getState().currentThreadId) });
if (g.runtimeStatus === "idle") break;
await sleep(300);
}
await sleep(1500); // reveal catches up
}
async function scenario_perm(page) {
await page.fill(".cp-ta", "/perm");
await page.keyboard.press("Enter");
await page.waitForSelector(".card.perm", { timeout: 15000 });
}
async function scenario_plan(page) {
await page.fill(".cp-ta", "/plan");
await page.keyboard.press("Enter");
await page.waitForSelector(".card.plan", { timeout: 15000 });
}
async function scenario_cpal(page) {
await page.keyboard.press("Control+k");
await page.waitForSelector(".cpal", { timeout: 5000 });
await page.fill(".cpal-in", "对话");
await sleep(300);
}
async function scenario_changes(page) {
// Changes panel open: make a change, open the panel and click a file to see its diff
writeFileSync(join(PROJ, "a.txt"), "alpha\nbeta\nchanged-line\n");
await page.click('.ibtn[title="改动(Ctrl+J)"]');
await page.waitForSelector(".chg-row", { timeout: 8000 });
await page.click(".chg-row");
await page.waitForSelector(".chg-diff .diff", { timeout: 8000 });
}
async function scenario_terminal(page) {
await page.click('.ibtn[title="终端"]');
const empty = await page.$(".tm-body .pn-empty .btn");
if (empty) await empty.click();
await page.waitForSelector(".tm-view .xterm", { timeout: 10000 });
await page.click(".tm-view .xterm");
await page.keyboard.type("echo hello", { delay: 15 });
await page.keyboard.press("Enter");
await sleep(1500);
}
const SCENARIOS = [
{ name: "empty", prep: scenario_emptyProject },
{ name: "thread", prep: scenario_emptyThread },
{ name: "default", prep: scenario_default },
{ name: "perm", prep: scenario_perm },
{ name: "plan", prep: scenario_plan },
{ name: "cpal", prep: scenario_cpal },
{ name: "changes", prep: scenario_changes },
{ name: "terminal", prep: scenario_terminal },
];
async function main() {
await setup();
// One long page accumulating state: empty → thread → default → perm (resolved) → plan (resolved) → cpal
// A separate page per scenario is cleaner: a new page per scenario + set up the preceding state as needed
for (const sc of SCENARIOS) {
const page = await newPage(1440, "light", true);
try {
// Preconditions: thread needs a project + conversation; every other scenario starts from a conversation and then does its own setup
if (sc.name === "empty") {
// Empty-project onboarding
} else if (sc.name === "thread") {
await scenario_emptyThread(page);
} else {
await scenario_emptyThread(page);
await sc.prep(page);
}
await grabAudit(page, sc.name, "light", 1440);
for (const theme of ["light", "dark"]) {
await page.evaluate((t) => { document.documentElement.dataset.theme = t; }, theme);
for (const w of [1440, 960, 560]) {
await page.setViewportSize({ width: w, height: 900 });
await sleep(500);
await shot(page, sc.name, theme, w);
}
}
} catch (e) {
console.log(`✗ ${sc.name}: ${String(e?.message ?? e).slice(0, 120)}`);
}
await page.close();
}
writeFileSync(join(OUT, "audit.json"), JSON.stringify(audits, null, 2));
console.log(`截图完成 → ${OUT}(audit.json ${Object.keys(audits).length} 条)`);
await browser?.close().catch(() => {});
daemon?.kill();
process.exit(0);
}
main().catch((e) => { console.error(e); daemon?.kill(); process.exit(1); });
@@ -0,0 +1,31 @@
import { createHash } from "node:crypto";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { buildAll, root } from "./build-v1.mjs";
const files = [
"app/app.js",
"app/app.css",
"app/index.html",
"daemon/dist/main.js",
"daemon/dist/main.js.map",
];
const output = await mkdtemp(join(tmpdir(), "agent-console-build-"));
let failed = false;
try {
await buildAll(output);
for (const file of files) {
const expected = await readFile(join(root, file));
const actual = await readFile(join(output, file));
const hash = createHash("sha256").update(expected).digest("hex");
if (expected.equals(actual)) console.log(`OK ${hash} ${file}`);
else {
console.error(`MISMATCH ${hash} ${file}`);
failed = true;
}
}
} finally {
await rm(output, { recursive: true, force: true });
}
if (failed) process.exitCode = 1;
@@ -0,0 +1,420 @@
#!/usr/bin/env node
// One-shot Windows self-check (also runs on macOS / Linux, where Windows-only items are marked SKIP).
//
// cd /d <path to agent-console>
// node scripts\verify-windows.mjs full: npm ci → build → verify:build → npm test → all checks
// node scripts\verify-windows.mjs --quick skip npm ci and npm test (when dependencies are already installed)
//
// Changes no real configuration: the daemon uses a temporary data directory + the Mock Provider; Agent CLIs only run --version.
// The report is also written to _tmp/verify-windows.log. Exit code: 1 if anything FAILs, otherwise 0.
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, appendFileSync } from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const IS_WIN = process.platform === "win32";
const args = new Set(process.argv.slice(2));
const QUICK = args.has("--quick");
const logFile = path.join(root, "_tmp", "verify-windows.log");
mkdirSync(path.dirname(logFile), { recursive: true });
writeFileSync(logFile, `verify-windows ${new Date().toISOString()}\n`);
const results = [];
function out(line) {
console.log(line);
try {
appendFileSync(logFile, line + "\n");
} catch {}
}
function record(status, name, detail = "") {
results.push({ status, name, detail });
const mark = { PASS: "✓ PASS", WARN: "! WARN", FAIL: "✗ FAIL", SKIP: "- SKIP" }[status];
out(`${mark} ${name}${detail ? " — " + detail : ""}`);
}
async function step(name, fn) {
try {
const r = await fn();
if (r && typeof r === "object" && r.status) record(r.status, name, r.detail ?? "");
else record("PASS", name, typeof r === "string" ? r : "");
} catch (e) {
record("FAIL", name, String(e?.message ?? e).slice(0, 800));
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// npm is npm.cmd on Windows: run it through cmd.exe (the command is hard-coded, no user input)
function npm(cmdArgs, { inherit = true } = {}) {
const r = IS_WIN
? spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", `npm ${cmdArgs.join(" ")}`], {
cwd: root,
stdio: inherit ? "inherit" : "pipe",
windowsHide: true,
})
: spawnSync("npm", cmdArgs, { cwd: root, stdio: inherit ? "inherit" : "pipe" });
if (r.error) throw r.error;
if (r.status !== 0) throw new Error(`npm ${cmdArgs.join(" ")} 退出码 ${r.status}`);
return r.stdout ? String(r.stdout).trim() : "";
}
function decode(buf) {
try {
return new TextDecoder("utf-8", { fatal: true }).decode(buf);
} catch {
try {
return new TextDecoder("gbk").decode(buf);
} catch {
return Buffer.from(buf).toString("utf8");
}
}
}
// Bundle the tools from the daemon sources (PATH scan, shim resolution, process-tree termination, Provider catalog, default shell) into a temporary ESM and load it,
// so the checks run against exactly the code that goes into the daemon.
async function loadDaemonHelpers(tmp) {
const esbuild = await import("esbuild");
const entry = path.join(tmp, "helpers-entry.ts");
const rel = (p) => path.relative(tmp, path.join(root, p)).split(path.sep).join("/");
writeFileSync(
entry,
[
`export * from ${JSON.stringify(rel("daemon/src/util/bin.ts"))};`,
`export { PROVIDER_CATALOG } from ${JSON.stringify(rel("daemon/src/providers/catalog.ts"))};`,
`export { pickShell } from ${JSON.stringify(rel("daemon/src/terminal/service.ts"))};`,
`export { decodePickFolderStdout } from ${JSON.stringify(rel("daemon/src/util/pickFolderWin.ts"))};`,
`export { normPath } from ${JSON.stringify(rel("daemon/src/util/paths.ts"))};`,
].join("\n"),
);
const outfile = path.join(root, "_tmp", `verify-helpers-${process.pid}.mjs`);
await esbuild.build({
entryPoints: [entry],
bundle: true,
platform: "node",
format: "esm",
target: "node20",
packages: "external",
outfile,
logLevel: "silent",
banner: { js: 'import { createRequire as __vcr } from "node:module"; const require = __vcr(import.meta.url);' },
});
try {
return await import(pathToFileURL(outfile).href);
} finally {
// Already loaded into memory; the file can be deleted
setTimeout(() => rmSync(outfile, { force: true }), 100).unref();
}
}
function runWithTimeout(child, ms) {
return new Promise((resolve) => {
let stdout = Buffer.alloc(0);
let stderr = Buffer.alloc(0);
child.stdout?.on("data", (d) => (stdout = Buffer.concat([stdout, d])));
child.stderr?.on("data", (d) => (stderr = Buffer.concat([stderr, d])));
const t = setTimeout(() => resolve({ code: null, timedOut: true, stdout, stderr }), ms);
child.on("error", (e) => {
clearTimeout(t);
resolve({ code: null, error: e, stdout, stderr });
});
child.on("close", (code) => {
clearTimeout(t);
resolve({ code, stdout, stderr });
});
});
}
function pidAlive(pid) {
try {
process.kill(pid, 0);
return true;
} catch (e) {
return e?.code === "EPERM";
}
}
function getJson(port, pathname, token) {
return new Promise((resolve, reject) => {
const req = http.get({ host: "127.0.0.1", port, path: pathname, headers: { "x-agent-console": token }, timeout: 3000 }, (res) => {
let body = "";
res.on("data", (c) => (body += c));
res.on("end", () => {
try {
resolve({ status: res.statusCode, body: JSON.parse(body) });
} catch {
resolve({ status: res.statusCode, body });
}
});
});
req.on("error", reject);
req.on("timeout", () => req.destroy(new Error("timeout")));
});
}
async function main() {
out(`系统: ${os.type()} ${os.release()} ${process.arch} Node ${process.version} (${process.execPath})`);
out(`仓库: ${root}`);
out(`用户目录: ${os.homedir()} 数据目录: ${path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "magpie", "agent-console")}`);
if (IS_WIN) {
try {
const cp = execFileSync(process.env.ComSpec || "cmd.exe", ["/d", "/c", "chcp"], { windowsHide: true });
out(`控制台代码页: ${decode(cp).trim()}`);
} catch {}
}
out("");
// 1. Node / npm
await step("Node.js ≥ 20", () => {
const major = Number(process.versions.node.split(".")[0]);
if (major < 20) throw new Error(`当前 ${process.version},需要 20+`);
return process.version;
});
await step("npm 可用", () => "npm " + npm(["-v"], { inherit: false }));
const nonAscii = /[^\x00-\x7f]/.test(root) || /\s/.test(root);
record(nonAscii ? "PASS" : "SKIP", "仓库路径含中文/空格(用于覆盖编码问题)", nonAscii ? root : "路径全是 ASCII,未覆盖");
// 2. Install / build
if (QUICK) record("SKIP", "npm ci", "--quick");
else await step("npm ci", () => npm(["ci"]));
await step("npm run build", () => npm(["run", "build"]));
await step("npm run verify:build(提交的 bundle 与重新构建一致)", () => npm(["run", "verify:build"]));
await step("npm run check(类型检查)", () => npm(["run", "check"]));
if (QUICK) record("SKIP", "npm test", "--quick");
else await step("npm test(含 Windows 专属的 CP936 用例)", () => npm(["test"]));
const tmp = mkdtempSync(path.join(os.tmpdir(), "ac-verify-"));
let helpers = null;
try {
await step("加载 daemon 工具代码(esbuild 临时打包)", async () => {
helpers = await loadDaemonHelpers(tmp);
return "ok";
});
// 3. node-pty
await step("node-pty 加载 + 用默认 shell 起一个 PTY", async () => {
const pty = await import("node-pty");
const shell = helpers ? helpers.pickShell() : IS_WIN ? "powershell.exe" : "/bin/sh";
const marker = "AC-PTY-中文-" + randomBytes(3).toString("hex");
const p = pty.spawn(shell, [], { name: "xterm-256color", cols: 100, rows: 30, cwd: root, env: process.env });
let text = "";
p.onData((d) => (text += d));
await sleep(1500);
p.write(`echo ${marker}\r`);
const t0 = Date.now();
while (Date.now() - t0 < 10000 && !text.includes(marker + "\r") && !text.includes(marker + "\n")) await sleep(100);
const ok = text.split(marker).length >= 3 || /AC-PTY-中文-[0-9a-f]{6}\r?\n/.test(text);
try {
p.kill();
} catch {}
if (!text.includes(marker)) throw new Error(`没有收到回显(shell=${shell}):${JSON.stringify(text.slice(-300))}`);
return ok ? `shell=${shell}` : { status: "WARN", detail: `收到回显但格式不同(shell=${shell})` };
});
// 4. Agent CLI resolution
if (helpers) {
const { PROVIDER_CATALOG, resolveFirstBin, resolveBin, spawnBin, killTree } = helpers;
for (const p of PROVIDER_CATALOG) {
await step(`CLI 解析: ${p.name} (${p.bins.join(" / ")})`, async () => {
const r = await resolveFirstBin(p.bins);
if (!r.ok) return { status: "SKIP", detail: "未安装(PATH 和常见目录里都没有)" };
const child = spawnBin(r, ["--version"], { stdio: ["ignore", "pipe", "pipe"] });
const res = await runWithTimeout(child, 20000);
if (res.timedOut) await killTree(child, { graceMs: 500 });
const text = decode(Buffer.concat([res.stdout, res.stderr])).trim().split(/\r?\n/)[0] ?? "";
const detail = `via=${r.via} ${r.display}${text ? " → " + text.slice(0, 120) : ""}`;
if (res.error) throw new Error(`${detail} 启动失败: ${res.error.message}`);
if (res.timedOut) return { status: "WARN", detail: `${detail} (--version 20 秒没返回)` };
return { status: res.code === 0 ? "PASS" : "WARN", detail: res.code === 0 ? detail : `${detail} 退出码 ${res.code}` };
});
}
await step("CLI 解析: npx", async () => {
const r = await resolveBin("npx");
if (!r.ok) throw new Error(r.reason);
return `via=${r.via} ${r.display}`;
});
// 4b. shim resolution + argument escaping: create .cmd / .ps1 in a temp directory whose name has spaces and Chinese characters
const shimDir = path.join(tmp, "shim 测试 dir");
mkdirSync(shimDir, { recursive: true });
const probeArgs = ["a b", "x&y", "中文", 'q"t', "100%"];
if (IS_WIN) {
writeFileSync(path.join(shimDir, "ac-args.js"), "process.stdout.write(JSON.stringify(process.argv.slice(2)))");
writeFileSync(path.join(shimDir, "acjs.cmd"), '@ECHO off\r\n"node" "%~dp0\\ac-args.js" %*\r\n');
writeFileSync(path.join(shimDir, "acbat.cmd"), "@ECHO off\r\nnode -e \"process.stdout.write(JSON.stringify(process.argv.slice(1)))\" -- %*\r\n");
writeFileSync(
path.join(shimDir, "acps.ps1"),
"[Console]::OutputEncoding=[Text.Encoding]::UTF8\r\n[Console]::Out.Write((ConvertTo-Json -Compress @($args)))\r\n",
);
} else {
writeFileSync(path.join(shimDir, "acjs"), `#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify(process.argv.slice(2)))\n`, { mode: 0o755 });
}
const oldPath = process.env.PATH;
const pathKey = Object.keys(process.env).find((k) => k.toUpperCase() === "PATH") ?? "PATH";
process.env[pathKey] = shimDir + path.delimiter + (process.env[pathKey] ?? "");
helpers.clearBinCache?.();
try {
const cases = IS_WIN
? [
["acjs", "shim-js"],
["acbat", "cmd-shim"],
["acps", "ps1"],
]
: [["acjs", "path"]];
for (const [name, via] of cases) {
await step(`shim + 参数转义: ${name} (${via}),目录含空格和中文`, async () => {
const r = await resolveBin(name);
if (!r.ok) throw new Error(r.reason);
if (r.via !== via) throw new Error(`via=${r.via},期望 ${via}`);
const child = spawnBin(r, probeArgs, { stdio: ["ignore", "pipe", "pipe"] });
const res = await runWithTimeout(child, 20000);
const text = decode(res.stdout).trim();
let got = null;
try {
got = JSON.parse(text);
} catch {}
const want = probeArgs;
if (JSON.stringify(got) !== JSON.stringify(want)) {
// Batch %* and PowerShell -File each have quirks with embedded quotes: when the argument count is right and only a few characters differ, record a WARN for comparison
const detail = `得到 ${text || decode(res.stderr).slice(0, 200)},期望 ${JSON.stringify(want)}`;
if (name !== "acjs" && Array.isArray(got) && got.length === want.length) return { status: "WARN", detail };
throw new Error(detail);
}
return JSON.stringify(got);
});
}
} finally {
process.env[pathKey] = oldPath;
helpers.clearBinCache?.();
}
// 5. Process tree termination
await step("进程树结束(killTree:子进程 + 孙进程)", async () => {
const script = path.join(tmp, "tree-parent.js");
writeFileSync(
script,
[
'const { spawn } = require("node:child_process");',
'const g = spawn(process.execPath, ["-e", "setInterval(()=>{},1000)"], { stdio: "ignore" });',
"process.stdout.write(String(g.pid) + '\\n');",
"setInterval(()=>{},1000);",
].join("\n"),
);
writeFileSync(path.join(tmp, "package.json"), '{"type":"commonjs"}');
const r = { ok: true, cmd: process.execPath, prefixArgs: [script], display: "node", via: "path" };
const child = spawnBin(r, [], { stdio: ["ignore", "pipe", "ignore"], group: true });
const gpid = await new Promise((resolve, reject) => {
const t = setTimeout(() => reject(new Error("没拿到孙进程 pid")), 10000);
child.stdout.once("data", (d) => {
clearTimeout(t);
resolve(Number(String(d).trim()));
});
});
if (!pidAlive(gpid)) throw new Error("孙进程没起来");
await killTree(child, { graceMs: 1500 });
for (let i = 0; i < 40 && pidAlive(gpid); i++) await sleep(100);
if (pidAlive(gpid)) {
try {
process.kill(gpid, "SIGKILL");
} catch {}
throw new Error(`孙进程 ${gpid} 还活着`);
}
return `子 ${child.pid} / 孙 ${gpid} 都已结束`;
});
// 6. Encoding
await step("编码:GBK 控制台输出解码(pickFolder 回退)", () => {
const buf = Buffer.concat([Buffer.from("D:\\workwork\\magpie", "ascii"), Buffer.from("b2e5bcfe", "hex")]);
const s = helpers.decodePickFolderStdout(buf);
if (s !== "D:\\workwork\\magpie插件") throw new Error(String(s));
if (!IS_WIN) return "静态样本 ok(真实 powershell 只在 Windows 上测)";
const real = execFileSync(
"powershell.exe",
["-NoProfile", "-Command", "[Console]::OutputEncoding = [Text.Encoding]::GetEncoding(936); [Console]::Out.WriteLine('D:\\workwork\\magpie插件')"],
{ windowsHide: true },
);
const t = helpers.decodePickFolderStdout(real);
if (t !== "D:\\workwork\\magpie插件") throw new Error(`真实 powershell 得到 ${JSON.stringify(t)}`);
return "静态样本 + 真实 powershell CP936 都 ok";
});
await step("路径规范化(大小写 / 分隔符 / 中文)", () => {
const a = helpers.normPath(root);
const b = helpers.normPath(IS_WIN ? root.toUpperCase().replace(/\\/g, "/") : root);
if (IS_WIN && a !== b) throw new Error(`${a} != ${b}`);
return a;
});
}
// 7. Daemon start / stop
await step("daemon 启动 → /api/ping → 关 stdin 退出(Mock,临时数据目录)", async () => {
const dataRoot = path.join(tmp, "数据 data");
const token = randomBytes(32).toString("hex");
const child = spawn(
process.execPath,
[path.join(root, "daemon", "dist", "main.js"), "--port", "0", "--data", dataRoot, "--parent-pid", String(process.pid)],
{ env: { ...process.env, AGENT_CONSOLE_TOKEN: token, AGENT_CONSOLE_MOCK: "1" }, stdio: ["pipe", "pipe", "pipe"], windowsHide: true },
);
let stderr = "";
child.stderr.on("data", (d) => (stderr += d));
const port = await new Promise((resolve, reject) => {
let buf = "";
const t = setTimeout(() => reject(new Error("15 秒内没有就绪行 " + stderr.slice(-300))), 15000);
child.stdout.on("data", (d) => {
buf += d;
for (const line of buf.split(/\r?\n/)) {
try {
const j = JSON.parse(line);
if (j.agentConsoleReady) {
clearTimeout(t);
resolve(j.port);
}
} catch {}
}
});
child.once("exit", (code) => reject(new Error(`daemon 提前退出 ${code} ${stderr.slice(-300)}`)));
});
const ping = await getJson(port, "/api/ping", token);
if (ping.status !== 200 || !ping.body?.ok) throw new Error("ping 失败 " + JSON.stringify(ping));
const bad = await getJson(port, "/api/ping", "wrong");
if (bad.status !== 403) throw new Error("错误令牌没有被拒绝");
const daemonJson = path.join(dataRoot, "magpie", "agent-console", "daemon.json");
if (!existsSync(daemonJson)) throw new Error("没有写 daemon.json");
const t0 = Date.now();
child.stdin.end();
const code = await new Promise((resolve) => {
const t = setTimeout(() => resolve("timeout"), 8000);
child.once("exit", (c) => {
clearTimeout(t);
resolve(c);
});
});
if (code === "timeout") {
child.kill();
throw new Error("关 stdin 后 8 秒没退出");
}
if (existsSync(daemonJson)) throw new Error("退出后 daemon.json 还在");
return `端口 ${port},${Date.now() - t0}ms 内退出(code ${code}),数据目录含中文和空格`;
});
// 8. Plugin entry: the message when node can't be found inside Bun (function check only)
await step("插件宿主找 node(宿主是 Bun 时)", async () => {
const m = await import(pathToFileURL(path.join(root, "lib", "pathscan.mjs")).href);
const node = m.requireNode({ execPath: IS_WIN ? "C:\\Magpie\\bun.exe" : "/opt/magpie/bun" });
return node;
});
} finally {
rmSync(tmp, { recursive: true, force: true });
}
const count = (s) => results.filter((r) => r.status === s).length;
out("");
out(`===== PASS ${count("PASS")} WARN ${count("WARN")} FAIL ${count("FAIL")} SKIP ${count("SKIP")} =====`);
out(`报告: ${logFile}`);
process.exit(count("FAIL") ? 1 : 0);
}
main().catch((e) => {
out("自检脚本异常: " + (e?.stack ?? e));
process.exit(1);
});