diff --git a/packages/agent-console/README.md b/packages/agent-console/README.md index 06993be..cd9d5d4 100644 --- a/packages/agent-console/README.md +++ b/packages/agent-console/README.md @@ -41,7 +41,8 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar - **Persistent sessions**: each thread binds to a long-lived Agent process; after a daemon restart, running threads are marked closed and can be resumed (`--resume` / `thread/resume`) - **Multiple Agents**: Claude Code, Codex, Cursor, Copilot, OpenCode, Pi, Devin, dsh; missing CLIs show an install hint - **Model / permission / thinking**: per-thread; four permission modes and five thinking levels (what each Agent actually supports) -- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card +- **Structured timeline**: user message → thinking (expandable) → tool calls (read / edit / command, with line-level diffs) → todos → usage and duration; answer permission requests (tools / plan / questions) on the card. Since 1.3 every tool call is one compact row: a type icon, the command or path (monospace, relative to the project, never wrapping), `+N -M` for an edit and the status on the right; click a row for its output or diff, and a failed step opens by itself. A run of more than 6 tool calls (with the short thinking between them) folds into one summary row (改动 2 · 运行 3 · 读取 4 · 搜索 1 · 1 失败) that expands to the same rows; while it runs, one line shows the current step (正在运行:npm test…). The Agent's step list (Claude Code TodoWrite, Codex plan updates, an ACP agent's plan) is a checklist with N/M, and while it has open items an "N/M 个任务" pill above the composer jumps to it. Each reply ends with 复制 · model · time · duration (plus tokens / cost when the Agent reports them). Code blocks have a language label, line numbers, a wrap toggle and a copy button (the copy is the raw code). The look is grayscale and was inspired by [Better Paseo](https://github.com/RoundRedDot/better-paseo) (MIT); no code was copied +- **Instant send (1.3)**: your message shows in the timeline the moment you click 发送 and the composer switches to working at once. The daemon saves and pushes the message before it starts the Agent (spawn + ACP `initialize` / `session/new`, seconds on Windows) instead of after; the page draws it right away and swaps in the daemon's copy by a client message id, so it neither doubles nor jumps. A send that fails stays in place marked 发送失败 with 重试 / 移除. A message sent while a turn runs still goes to the queue list - **Steer and queue**: steer while running, queue the next message, interrupt - **Changes panel**: git status refresh every 3s, unified per-file diffs; discarded untracked files go to trash instead of a hard delete - **Files panel**: lazy directory tree (respects `.gitignore`), syntax-highlighted preview @@ -52,9 +53,9 @@ UI principle: **obvious at a glance, nothing extra**. Three columns — sidebar - **Preview tab** (1.2): a small browser in the right panel for local dev servers (`localhost`, `127.0.0.1`, `[::1]`, `*.localhost`, `0.0.0.0`): address bar, back / forward, reload, open in the system browser, widen the panel. The address is remembered per conversation. Pages load through the daemon's local preview proxy (see the security model), so module scripts, `fetch` and HMR WebSockets work inside Magpie's sandboxed frame. Limits: popups, `alert` and native form posts don't run in the sandbox; `localStorage` / `sessionStorage` / `document.cookie` are in-memory and reset on reload, and cookies are not passed (use 用浏览器打开 / Open in browser for logins) - **Links in chat** (1.2): local addresses in agent text, rendered Markdown and tool output (`localhost:5173`, `http://127.0.0.1:8080/x`, …) become links that open in the Preview tab; Ctrl/⌘+click, and any other `http(s)` link, opens the system browser through the daemon (`app.openExternal`: http/https only, re-serialized, run with `execFile` and no shell: `rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `xdg-open` on Linux; if that fails the link is copied). The terminal is not linkified - **File chips** (1.2): drag a row from the Files tab into the composer, or right-click → 插入到聊天 / Add to chat, to attach a path chip. Chips are sent as project-relative paths, checked by the daemon (inside the project, no `..`, no symlink escape, must exist, at most 50), and reach the Agent as a "Referenced files" section with absolute paths after your text (plus `resource_link` blocks for ACP Agents). Dropping files from the OS file manager still uploads them as attachments -- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted +- **Layout settings** (1.2): content width (narrow 640 / default 720 / wide 880 / full) and chat font size (12–18 px, default 13; timeline, composer, tool cards, diffs and the file viewer scale together, code 1 px smaller; the sidebar, top bar, panel tabs, menus and dialogs stay on the fixed 13 px UI scale); the sidebar collapses with the panel button at its top-left or Ctrl/⌘+B (collapses automatically in narrow windows); all persisted - **Follows Magpie live** (1.2): light/dark, Magpie's neutral colours and its language follow Magpie while the page is open (and after a reconnect); the accent stays neutral grey -- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 9 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve`) so UI work does not burn tokens +- **Mock Agent**: `AGENT_CONSOLE_MOCK=1` registers a demo Agent with 11 scripts (`default` / `perm` / `plan` / `ask` / `slow` / `error` / `long` / `exit` / `serve` / `tools` / `bashhint`) so UI work does not burn tokens ## Architecture @@ -66,7 +67,8 @@ Magpie window ▼ Magpie plugin host (Bun) ── index.mjs + lib/gate.mjs "gate" on 127.0.0.1: (default 3488) │ first /open: spawns the daemon as a child process (node, --port 0, stdin lifeline, --parent-pid) - │ 302 → http://127.0.0.1:/?theme=…#t= + │ 302 → http://127.0.0.1:/app?theme=…#t=&p= (1.3: the gate's wrapper page, lib/wrapper.mjs) + │ └─ " + + "" + + `` + + "" + ); +} + +/** + * Who may frame /app: the gate itself, a loopback page (Magpie's plugin page and `magpie web` on this computer) and + * Magpie's desktop window, which is wails://localhost on macOS / Linux and http://wails.localhost on Windows (WebView2). + * Any other site gets a blank frame. Keep in sync with the README's security section. + */ +export const WRAPPER_FRAME_ANCESTORS = + "frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:"; + +export function wrapperCsp(nonce) { + return [ + "default-src 'none'", + `script-src 'nonce-${nonce}'`, + `style-src 'nonce-${nonce}'`, + "frame-src http://127.0.0.1:*", + WRAPPER_FRAME_ANCESTORS, + "base-uri 'none'", + "form-action 'none'", + ].join("; "); +} diff --git a/packages/agent-console/package-lock.json b/packages/agent-console/package-lock.json index 7b7f436..6b85abb 100644 --- a/packages/agent-console/package-lock.json +++ b/packages/agent-console/package-lock.json @@ -1,12 +1,12 @@ { "name": "@magpie-community/page-agent-console", - "version": "1.2.0", + "version": "1.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@magpie-community/page-agent-console", - "version": "1.2.0", + "version": "1.3.0", "license": "MIT", "dependencies": { "@agentclientprotocol/sdk": "2.1.0", diff --git a/packages/agent-console/package.json b/packages/agent-console/package.json index 39869cc..a4240ba 100644 --- a/packages/agent-console/package.json +++ b/packages/agent-console/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/page-agent-console", - "version": "1.2.0", + "version": "1.3.0", "description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.", "author": "qingnian108 (https://github.com/qingnian108)", "homepage": "https://github.com/qingnian108/magpie-agent-console", diff --git a/packages/agent-console/page/boot.js b/packages/agent-console/page/boot.js index 26186b3..e5c0c81 100644 --- a/packages/agent-console/page/boot.js +++ b/packages/agent-console/page/boot.js @@ -37,6 +37,9 @@ const here = new URL(location.href); const lostAt = Number(here.searchParams.get("ac_lost")) || 0; here.searchParams.delete("ac_lost"); + // ac_try: the gate wrapper's count of automatic reconnects (1.3), handed on to it through the gate + const tries = here.searchParams.get("ac_try") || ""; + here.searchParams.delete("ac_try"); here.hash = ""; function validSession(s) { return ( @@ -103,6 +106,7 @@ const q = new URLSearchParams(); q.set("k", session.key); if (theme) q.set("theme", theme); + if (/^\d{10,15}\.[0-9]$/.test(tries)) q.set("ac_try", tries); if (lang) q.set("lang", lang); const slim = {}; for (const [k, v] of Object.entries(tokens || {})) { diff --git a/packages/agent-console/scripts/e2e-v1.mjs b/packages/agent-console/scripts/e2e-v1.mjs index 23b5340..6573fef 100644 --- a/packages/agent-console/scripts/e2e-v1.mjs +++ b/packages/agent-console/scripts/e2e-v1.mjs @@ -1,5 +1,8 @@ // 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. +// Scenarios 1–12, 16–26 (20, 22–26: 1.3 overlap at 600 px, message actions, quotes, instant send, tool rows / summary, +// checklist + pill + reply footer + code block); each prints ✓/✗, and any ✗ exits with code 1. +// The mock Agent starts slowly (E2E_MOCK_START_MS, default 1200 ms) like a real one on Windows, so every scenario runs +// with the user's message arriving before the Agent is up. import { spawn, execFileSync } from "node:child_process"; import { findBrowser } from "./browser-path.mjs"; import { mkdirSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs"; @@ -78,7 +81,7 @@ async function setup() { } 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" }, + env: { ...process.env, AGENT_CONSOLE_MOCK: "1", AGENT_CONSOLE_MOCK_START_MS: process.env.E2E_MOCK_START_MS ?? "1200" }, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, }); @@ -160,14 +163,34 @@ async function waitEnd(seq = 0) { async function scenario2() { await send("看下这个项目"); await waitEnd(); - const checks = await page.evaluate(() => ({ + // 1.3 timeline polish: a short run (≤6 tool calls) stays flat, one compact row per step; the edit row shows +N -M + // and opens its diff on click; the step list is a checklist with N/M + const rows = await page.evaluate(() => { + const g = [...document.querySelectorAll(".tg")].pop(); + const ts = g ? [...g.querySelectorAll(".ts:not(.ts-think)")] : []; + const edit = ts.find((x) => x.dataset.kind === "edit"); + const r = { + flat: !!g?.classList.contains("flat") && !g.querySelector(".tg-head"), + steps: ts.length, + oneLine: ts.every((x) => x.querySelector(".ts-head").getBoundingClientRect().height <= 30), + diffStat: edit?.querySelector(".ts-diff")?.textContent?.replace(/\s+/g, " ").trim() ?? "", + closed: !g?.querySelector(".diff"), + ok: ts.filter((x) => x.querySelector(".ts-st.ok")).length, + }; + edit?.querySelector(".ts-head")?.click(); + return r; + }); + await sleep(200); + const checks = await page.evaluate((rows) => ({ + ...rows, md: !!document.querySelector(".md"), - tg: !!document.querySelector(".tg"), - diff: !!document.querySelector(".diff"), - todo: !!document.querySelector(".rs-item"), + diff: !!document.querySelector(".tg .ts .diff"), + checklist: document.querySelector(".ck .ck-n")?.textContent ?? "", te: !!document.querySelector(".te"), - })); - record("场景2 默认剧本(正文/工具组/diff/待办/结束行)", checks.md && checks.tg && checks.diff && checks.todo && checks.te, JSON.stringify(checks)); + }), rows); + const ok = checks.flat && checks.steps === 5 && checks.oneLine && /\+2\s*[-−]1/.test(checks.diffStat) && checks.closed && checks.ok === 5 + && checks.md && checks.diff && checks.checklist === "3/4" && checks.te; + record("场景2 默认剧本(正文/工具行/+N -M/diff/清单/结束行)", ok, JSON.stringify(checks)); } async function scenario3() { @@ -391,6 +414,242 @@ async function scenario18() { await page.setViewportSize({ width: 1440, height: 900 }); } +// ---- 1.3 (Nolan's Windows report) ---- +async function newThread() { + // Over the API (scenario 18 may leave the sidebar as a drawer); close the right panel earlier scenarios opened + // (below ~900 px it is a sheet over the chat) + await page.setViewportSize({ width: 1440, height: 900 }); + await page.evaluate(() => window.__stores.useUi.getState().closePanel?.()); + // A dialog left open (e.g. scenario 16's palette when nothing matched): close it by pressing on its scrim + for (let i = 0; i < 3 && await page.$(".dlg-scrim"); i++) { await page.mouse.click(4, 4); await sleep(200); } + const projects = await wsCall("projects.list", {}); + const proj = projects.find((p) => p.path === PROJ) ?? projects[0]; + const th = await wsCall("threads.create", { projectId: proj.id, provider: "mock", mode: "default" }); + await page.waitForFunction((id) => window.__stores.useData.getState().threads.some((t) => t.id === id), th.id, { timeout: 8000 }); + await page.evaluate(([p, t]) => window.__stores.useUi.getState().select(p, t), [proj.id, th.id]); + await page.waitForFunction((id) => window.__stores.useUi.getState().currentThreadId === id, th.id, { timeout: 5000 }); + _tid = th.id; + await page.waitForSelector(sel.ta, { timeout: 5000 }); + await sleep(300); +} +async function waitIdle(ms = 45000) { + const t0 = Date.now(); + while (Date.now() - t0 < ms) { + const st = await wsCall("threads.get", { id: await curThread() }).then((g) => g.runtimeStatus).catch(() => "?"); + if (st !== "running" && st !== "initializing") return; + await sleep(250); + } + throw new Error("等待空闲超时"); +} +/** Timeline rows never overlap: each row paints inside its virtual slot, one-line rows stay one line */ +async function overlapProblems() { + return page.evaluate(() => { + const bad = []; + const inked = (el) => { const rg = document.createRange(); rg.selectNodeContents(el); const rs = [...rg.getClientRects()].filter((x) => x.height > 0); + return rs.length ? { top: Math.min(...rs.map((x) => x.top)), bottom: Math.max(...rs.map((x) => x.bottom)) } : null; }; + const rows = [...document.querySelectorAll(".tl-wrap [data-index]")].map((el) => ({ el, i: +el.dataset.index, r: el.getBoundingClientRect() })).sort((a, b) => a.i - b.i); + for (const row of rows) { const k = inked(row.el); if (k && (k.bottom > row.r.bottom + 1 || k.top < row.r.top - 1)) bad.push(`row ${row.i} paints outside its slot`); } + for (let k = 0; k + 1 < rows.length; k++) if (rows[k + 1].i === rows[k].i + 1 && rows[k].r.bottom > rows[k + 1].r.top + 0.5) bad.push(`row ${rows[k].i} overlaps ${rows[k + 1].i}`); + for (const el of document.querySelectorAll(".tl-wrap .tg-head, .tl-wrap .tg-run, .tl-wrap .rs-head, .tl-wrap .ts-head")) { + const r = el.getBoundingClientRect(); const k = inked(el); + if (r.height > 30 || (k && (k.bottom > r.bottom + 1 || k.top < r.top - 1))) bad.push(`${el.className} wraps/spills`); + } + return bad; + }); +} + +async function scenario20() { + // Folded tool groups + running row + long PowerShell commands + a pending approval, at Nolan's ~600 px window + await newThread(); + await page.setViewportSize({ width: 600, height: 860 }); + // E2E_NEG_OVERLAP=1: put back 1.2's squeeze to prove this check catches it (must fail) + const neg = process.env.E2E_NEG_OVERLAP ? await page.addStyleTag({ content: ".tg-head{height:24px!important;min-height:0!important;overflow:visible!important;white-space:normal!important}.tg-sum{white-space:normal!important;overflow:visible!important;max-width:42px}.ts-head{height:24px!important;min-height:0!important;overflow:visible!important;white-space:normal!important}.ts-title{white-space:normal!important;overflow:visible!important;max-width:42px}" }) : null; + await send("/winrun 帮我启动一下"); + const seen = new Set(); + let approved = false; + const t0 = Date.now(); + while (Date.now() - t0 < 30000) { + for (const b of await overlapProblems()) seen.add(b); + if (!approved && await page.$(".card.perm:not(.done)")) { + await sleep(400); + for (const b of await overlapProblems()) seen.add(b); + await page.click(".card.perm:not(.done) .btn.primary"); + approved = true; + } + const st = await wsCall("threads.get", { id: await curThread() }).then((g) => g.runtimeStatus).catch(() => "?"); + if (approved && st !== "running" && st !== "initializing") break; + await sleep(40); + } + for (const b of await overlapProblems()) seen.add(b); + await neg?.evaluate((el) => el.remove()); + await page.setViewportSize({ width: 1440, height: 900 }); + record("场景20 600px 运行中折叠行/运行行不重叠", approved && seen.size === 0, [...seen].slice(0, 3).join(" | ")); +} + +async function scenario22() { + // User-message actions: under the bubble, reachable without a hover gap, copy feedback, edit fills the input + await newThread(); + await send("帮我启动一下"); + await page.waitForSelector(".um", { timeout: 8000 }); + await waitIdle(); + const bb = await (await page.$(".um")).boundingBox(); + await page.mouse.move(bb.x + bb.width / 2, bb.y + bb.height / 2); + await sleep(200); + const ab = await (await page.$(".um-act")).boundingBox(); + let hidden = 0; + for (let i = 0; i <= 10; i++) { + await page.mouse.move(bb.x + bb.width / 2 + (ab.x + 8 - bb.x - bb.width / 2) * i / 10, bb.y + bb.height / 2 + (ab.y + 12 - bb.y - bb.height / 2) * i / 10); + const vis = await page.$eval(".um-act", (a) => Number(getComputedStyle(a).opacity) > 0.5); + if (!vis) hidden++; + } + const below = ab.y >= bb.y + bb.height - 1 && ab.x + ab.width <= bb.x + bb.width + 1; + await page.click('.um-act button[aria-label="编辑(填回输入框,不会马上发送)"]'); + await sleep(200); + const filled = await page.$eval(sel.ta, (t) => t.value); + await page.fill(sel.ta, ""); + record("场景22 用户消息操作:气泡下方、无悬停缺口、编辑回填", below && hidden === 0 && filled === "帮我启动一下", `below=${below} hidden=${hidden} filled=${filled}`); +} + +async function scenario23() { + // Select text in a reply → 添加到对话 → quote chip → sent in front of the message as "> " + await newThread(); + await send("看下这个项目"); + await page.waitForSelector(".tl-wrap .md p", { timeout: 15000 }); + await waitIdle(); + // A real mouse drag across the first reply paragraph + await page.evaluate(() => document.querySelector(".tl-wrap .md p")?.scrollIntoView({ block: "center" })); + await sleep(300); + const pb = await (await page.$(".tl-wrap .md p")).boundingBox(); + await page.mouse.move(pb.x + 2, pb.y + 8); + await page.mouse.down(); + await page.mouse.move(pb.x + Math.min(pb.width - 4, 200), pb.y + 8, { steps: 8 }); + await page.mouse.up(); + const r = await page.evaluate(() => window.getSelection()?.toString()); + await page.waitForSelector(".qs-pop", { timeout: 3000 }); + await page.click(".qs-pop"); + await page.waitForSelector(".qchip", { timeout: 3000 }); + await send("这句什么意思?"); + await waitIdle(); + const g = await wsCall("threads.get", { id: await curThread() }); + const last = g.events.filter((e) => e.type === "user_message").pop(); + const ok = !!r && typeof last?.text === "string" && last.text.startsWith("> ") && last.text.endsWith("这句什么意思?") && !!(await page.$(".um-quote")); + record("场景23 选中添加到对话 → 引用随消息发送", ok, JSON.stringify(last?.text ?? "").slice(0, 120)); +} + +async function scenario24() { + // 1.3 (Nolan): the bubble shows the moment 发送 is clicked, while the (slow) mock Agent is still starting; the + // daemon's echo takes over the same DOM node (no duplicate, no jump); a failed send stays with 重试 + await newThread(); + await page.setViewportSize({ width: 600, height: 860 }); + await sleep(200); + const text = "马上显示这条消息"; + await page.fill(sel.ta, text); + const t = await page.evaluate((text) => new Promise((resolve) => { + const t0 = performance.now(); + const r = { bubble: null, working: null }; + const tick = () => { + const now = Math.round(performance.now() - t0); + const row = [...document.querySelectorAll(".tl-wrap .um-row")].find((e) => e.textContent?.includes(text)); + if (r.bubble == null && row) { r.bubble = now; row.__mark = 1; r.cid = row.dataset.clientId; } + if (r.working == null && document.querySelector(".cp-stop")) r.working = now; + if ((r.bubble == null || r.working == null) && now < 5000) requestAnimationFrame(tick); else resolve(r); + }; + requestAnimationFrame(tick); + document.querySelector(".cp-send").click(); + }), text); + // the echo (the daemon's user_message) replaces it in place + await waitFor(() => page.evaluate((text) => (window.__tl.getState().items ?? []).some((i) => i.kind === "user" && i.text === text && !i.sendState), text), 8000, "回显"); + const same = await page.evaluate((cid) => !!document.querySelector(`.um-row[data-client-id="${cid}"]`)?.__mark, t.cid); + await waitIdle(); + const count = await page.evaluate((text) => (window.__tl.getState().items ?? []).filter((i) => i.kind === "user" && i.text === text).length, text); + const scrolled = await page.evaluate(() => { const el = document.querySelector(".scroll"); return el ? el.scrollHeight - el.scrollTop - el.clientHeight < 80 : false; }); + // Failure: thread.send rejects → the bubble stays, marked failed; 重试 sends it once + await page.evaluate(() => { const ws = window.__ws; window.__origCall = ws.call.bind(ws); + ws.call = (m, p, tm) => m === "thread.send" ? new Promise((_, rej) => setTimeout(() => rej(new Error("连接已断开")), 200)) : window.__origCall(m, p, tm); }); + await page.fill(sel.ta, "这条会发送失败"); + await page.click(sel.send); + const failed = await page.waitForSelector(".um-row.failed .um-fail", { timeout: 5000 }).then(() => true).catch(() => false); + await page.evaluate(() => { window.__ws.call = window.__origCall; }); + await page.click('.um-row.failed .um-fail-b[title="重新发送"]').catch(() => {}); + await waitFor(() => page.evaluate(() => !document.querySelector(".um-row.failed") && (window.__tl.getState().items ?? []).some((i) => i.kind === "user" && i.text === "这条会发送失败" && !i.sendState)), 8000, "重试后回显"); + await waitIdle(); + const retried = await page.evaluate(() => (window.__tl.getState().items ?? []).filter((i) => i.kind === "user" && i.text === "这条会发送失败").length); + await page.setViewportSize({ width: 1440, height: 900 }); + const ok = t.bubble != null && t.bubble < 300 && t.working != null && t.working < 300 && same && count === 1 && scrolled && failed && retried === 1; + record("场景24 点发送气泡立即出现(Agent 慢启动)、回显不重复不跳、失败可重试", ok, + `bubble=${t.bubble}ms working=${t.working}ms sameNode=${same} count=${count} bottom=${scrolled} failed=${failed} retried=${retried}`); +} + +async function scenario25() { + // 1.3 timeline polish: a long run (/tools, 8 tool calls) folds into one summary row with counts and a failure count; + // it expands to the same one-line rows, and the failed step shows its output + await newThread(); + await send("/tools 跑一下 lint 和测试"); + await page.waitForSelector(".tg:not(.flat) .tg-head", { timeout: 15000 }); + const running = await page.waitForSelector(".tg-run", { timeout: 15000 }).then(() => true).catch(() => false); + await waitIdle(); + const head = await page.evaluate(() => { + const g = [...document.querySelectorAll(".tg:not(.flat)")].pop(); + const r = { sum: g?.querySelector(".tg-sum")?.textContent ?? "", fail: g?.querySelector(".tg-fail")?.textContent ?? "", + closed: !g?.querySelector(".tg-list"), h: g?.querySelector(".tg-head")?.getBoundingClientRect().height ?? 99 }; + g?.querySelector(".tg-head")?.click(); + return r; + }); + await sleep(200); + const open = await page.evaluate(() => { + const g = [...document.querySelectorAll(".tg.open")].pop(); + const ts = g ? [...g.querySelectorAll(".ts:not(.ts-think)")] : []; + const failed = ts.find((x) => x.querySelector(".ts-st.fail")); + return { steps: ts.length, failedOpen: !!failed?.querySelector(".ts-out"), failedOut: /no-unused-vars/.test(failed?.textContent ?? ""), + edit: ts.find((x) => x.dataset.kind === "edit")?.querySelector(".ts-diff")?.textContent?.replace(/\s+/g, " ").trim() ?? "" }; + }); + const ok = running && /读取 3/.test(head.sum) && /搜索 2/.test(head.sum) && /运行 2/.test(head.sum) && /改动 1/.test(head.sum) && /1/.test(head.fail) + && head.closed && head.h <= 30 && open.steps === 8 && open.failedOpen && open.failedOut && /[-−]1/.test(open.edit); + record("场景25 长运行折叠成摘要(计数/失败数),展开为单行步骤", ok, JSON.stringify({ running, ...head, ...open })); +} + +async function scenario26() { + // 1.3 timeline polish: /tasks — an ACP plan (entries) as an N/M checklist, the "N/M 个任务" pill above the composer + // (click scrolls the list into view), the reply footer (copy · model · time · duration) and the code block + // (language, line numbers, wrap toggle, copy of the raw code) + await newThread(); + await send("/tasks 修一下 checkout 偶发失败的测试"); + const pill = await waitFor(() => page.evaluate(() => { + const t = document.querySelector(".tasks-pill")?.textContent ?? ""; + return /\d\/3/.test(t) ? t : null; + }), 15000, "任务胶囊").catch(() => null); + await waitIdle(); + await sleep(300); + const done = await page.evaluate(() => { + const ck = [...document.querySelectorAll(".ck")].pop(); + return { n: ck?.querySelector(".ck-n")?.textContent ?? "", rows: ck?.querySelectorAll(".ck-i.done").length ?? 0, lists: document.querySelectorAll(".ck").length, + pillGone: !document.querySelector(".tasks-pill") }; + }); + const te = await page.evaluate(() => { + const t = [...document.querySelectorAll(".te")].pop(); + const metas = t ? [...t.querySelectorAll(".te-m")].map((m) => m.textContent.trim()) : []; + return { copy: !!t?.querySelector(".te-copy"), model: metas.some((m) => /演示/.test(m)), time: metas.some((m) => /^\d{1,2}\/\d{1,2} \d{2}:\d{2}$|^\d{2}:\d{2}$/.test(m)), + dur: metas.some((m) => /^\d+(\.\d+)?\s*(ms|s|分|m)/.test(m)) }; + }); + await page.evaluate(() => { window.__copied = null; navigator.clipboard.writeText = (s) => { window.__copied = s; return Promise.resolve(); }; }); + const cb = await page.evaluate(() => { + const b = [...document.querySelectorAll(".md .cb")].pop(); + if (!b) return null; + const r = { lang: b.querySelector(".cb-lang")?.textContent ?? "", lines: b.querySelectorAll(".cb-l").length, numbered: b.querySelector("pre, code")?.closest(".numbered") != null || b.querySelector(".numbered") != null }; + b.querySelector(".cb-wrap").click(); + r.wrap = b.classList.contains("wrap") || b.querySelector(".cb-wrap").getAttribute("aria-pressed") === "true"; + b.querySelector(".cb-copy").click(); + return r; + }); + await sleep(200); + const copied = await page.evaluate(() => window.__copied); + const okCopy = typeof copied === "string" && copied.startsWith("async function submit() {") && copied.trim().endsWith("}") && !/^\s*\d/.test(copied.split("\n")[1] ?? ""); + const ok = !!pill && done.n === "3/3" && done.rows === 3 && done.lists === 1 && done.pillGone && te.copy && te.model && te.time && te.dur + && cb && cb.lang === "ts" && cb.lines === 5 && cb.numbered && cb.wrap && okCopy; + record("场景26 任务清单 N/M + 胶囊、回复页脚(复制·模型·时间·用时)、代码块(语言/行号/换行/复制)", ok, + JSON.stringify({ pill, ...done, ...te, cb, copied: copied?.slice(0, 30) })); +} + 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:")); @@ -510,24 +769,11 @@ 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(); + // E2E_ONLY_13=1 runs just the 1.3 scenarios (20–23) and the console-error check + const all = [scenario2, scenario3, scenario4, scenario5, scenario6, scenario7, scenario8, scenario9, scenario10, scenario11, + scenario12, scenario13, scenario14, scenario15, scenario16, scenario17, scenario18, scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19]; + const only13 = new Set([scenario20, scenario22, scenario23, scenario24, scenario25, scenario26, scenario19]); + for (const f of all) if (!process.env.E2E_ONLY_13 || only13.has(f)) await f(); } catch (e) { record("中途异常", false, String(e?.message ?? e).slice(0, 600) + " ||daemon:" + daemonErr.slice(-4).join("|").slice(0, 400)); } diff --git a/packages/agent-console/test/v1/ac11.test.ts b/packages/agent-console/test/v1/ac11.test.ts index 402fb1a..a5c2741 100644 --- a/packages/agent-console/test/v1/ac11.test.ts +++ b/packages/agent-console/test/v1/ac11.test.ts @@ -186,9 +186,9 @@ describe("self-heal back URL (host restart)", () => { try { const ok = await request(port, `/open?k=${key}&theme=dark&back=${encodeURIComponent(good)}`); expect(ok.status).toBe(302); - expect(ok.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?theme=dark#t=${token}&b=${encodeURIComponent(good)}`); + expect(ok.headers.location).toBe(`http://127.0.0.1:${port}/app?theme=dark#t=${token}&p=${daemonPort}&b=${encodeURIComponent(good)}`); const bad = await request(port, `/open?k=${key}&back=${encodeURIComponent("https://evil.example/")}`); - expect(bad.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?#t=${token}`); + expect(bad.headers.location).toBe(`http://127.0.0.1:${port}/app?#t=${token}&p=${daemonPort}`); // without the key there's still nothing expect((await request(port, `/open?back=${encodeURIComponent(good)}`)).status).toBe(403); } finally { diff --git a/packages/agent-console/test/v1/ac12.test.ts b/packages/agent-console/test/v1/ac12.test.ts index dcd9748..f0b3191 100644 --- a/packages/agent-console/test/v1/ac12.test.ts +++ b/packages/agent-console/test/v1/ac12.test.ts @@ -471,14 +471,14 @@ describe("1.2 QA fixes", () => { expect(i18n.t("sidebar.newProject")).toBe("New project"); expect(i18n.setLocale("en-US")).toBe(false); expect(i18n.setLocale("zh-TW")).toBe(true); - expect(i18n.tf("timeline.toolSummaryOne", { n: 1, parts: "读取 1" })).toBe("已执行 1 步 · 读取 1"); + expect(i18n.tf("timeline.cat.read", { n: 1 })).toBe("读取 1"); }); it("every new 1.2 key exists in both languages", async () => { const { messages } = await import("../../web/src/i18n/messages.js"); const keys = (o: Record, p = ""): string[] => Object.entries(o).flatMap(([k, v]) => (typeof v === "object" && v ? keys(v as Record, p + k + ".") : [p + k])); const zh = new Set(keys(messages.zh as unknown as Record)); const en = new Set(keys(messages.en as unknown as Record)); - for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.toolSummaryOne"]) { + for (const k of ["preview.tab", "preview.empty", "preview.limits", "preview.noLocalhost", "links.openPreviewTitle", "links.externalFailed", "mention.add", "mention.drop", "sidebar.collapse", "sidebar.expand", "settings.contentWidth", "settings.chatFont", "timeline.cat.read"]) { expect(zh.has(k), "zh " + k).toBe(true); expect(en.has(k), "en " + k).toBe(true); } diff --git a/packages/agent-console/test/v1/decode.test.ts b/packages/agent-console/test/v1/decode.test.ts new file mode 100644 index 0000000..8862128 --- /dev/null +++ b/packages/agent-console/test/v1/decode.test.ts @@ -0,0 +1,113 @@ +// 1.3 item 3: UTF-8 vs GBK (system code page) decoding of raw process output +import { describe, it, expect, afterEach } from "vitest"; +import { OutputDecoder, decodeOutput, parseCodePage, codePageLabel, labelForLocale, systemLegacyEncoding, _setSystemLegacyEncoding } from "../../daemon/src/util/decode.js"; + +const hex = (h: string) => Buffer.from(h.replace(/\s+/g, ""), "hex"); +// GBK fixtures (encoded with Python's gbk codec) +const GBK_HELLO = hex("c4e3bac3a3accac0bde7"); // 你好,世界 +const GBK_NOPATH = hex("cfb5cdb3d5d2b2bbb5bdd6b8b6a8b5c4c2b7beb6a1a3"); // 系统找不到指定的路径。 +const GBK_ERR = hex("b4edcef33a20d5d2b2bbb5bdcec4bcfe20612e7478740d0a"); // 错误: 找不到文件 a.txt\r\n +const GBK_YI = hex("d2bb"); // 一 — also valid UTF-8 (U+04BB "һ") + +/** Feed buf in pieces of the given sizes (the rest as one piece) */ +function feed(d: OutputDecoder, buf: Buffer, sizes: number[]): string { + let out = "", i = 0; + for (const n of sizes) { out += d.write(buf.subarray(i, i + n)); i += n; } + return out + d.write(buf.subarray(i)) + d.end(); +} + +afterEach(() => _setSystemLegacyEncoding(undefined)); + +describe("OutputDecoder (Windows, code page 936)", () => { + it("TextDecoder has gbk/gb18030/big5/shift_jis (full ICU, also Node 20)", () => { + expect(new TextDecoder("gbk").decode(GBK_HELLO)).toBe("你好,世界"); + for (const l of ["gbk", "gb18030", "big5", "shift_jis", "euc-kr"]) expect(codePageLabel({ gbk: 936, gb18030: 54936, big5: 950, shift_jis: 932, "euc-kr": 949 }[l]!)).toBe(l); + }); + + it("valid UTF-8 stays UTF-8, GBK chunks are decoded as GBK", () => { + const d = new OutputDecoder("gbk"); + expect(d.write(Buffer.from("构建成功 ✓\n"))).toBe("构建成功 ✓\n"); + expect(d.write(GBK_NOPATH)).toBe("系统找不到指定的路径。"); + expect(d.write(Buffer.from("ok\n"))).toBe("ok\n"); + expect(d.write(Buffer.from("又是 UTF-8"))).toBe("又是 UTF-8"); + expect(d.end()).toBe(""); + }); + + it("streaming-safe: GBK and UTF-8 characters split at every byte boundary", () => { + for (let cut = 1; cut < GBK_ERR.length; cut++) { + expect(feed(new OutputDecoder("gbk"), GBK_ERR, [cut]), `gbk cut ${cut}`).toBe("错误: 找不到文件 a.txt\r\n"); + } + const u = Buffer.from("中文输出 → 完成😀"); + for (let cut = 1; cut < u.length; cut++) expect(feed(new OutputDecoder("gbk"), u, [cut]), `utf8 cut ${cut}`).toBe("中文输出 → 完成😀"); + // one byte at a time + expect(feed(new OutputDecoder("gbk"), GBK_HELLO, Array(GBK_HELLO.length).fill(1))).toBe("你好,世界"); + }); + + it("bounded: never holds more than 3 bytes", () => { + const d = new OutputDecoder("gb18030"); + expect(d.write(hex("9439fc"))).toBe(""); // 3 of the 4 bytes of 😀 in GB18030 + expect(d.write(hex("36"))).toBe("😀"); + const big = Buffer.concat(Array(2000).fill(GBK_HELLO)); + expect(d.write(big).length).toBe(5 * 2000); + expect((d as unknown as { pending: Uint8Array }).pending.length).toBeLessThanOrEqual(3); + }); + + it("after GBK output, an ambiguous 2-byte chunk (一 = D2 BB) sticks with GBK; a fresh decoder reads it as UTF-8", () => { + const d = new OutputDecoder("gbk"); + d.write(GBK_HELLO); + expect(d.write(GBK_YI)).toBe("一"); + expect(new OutputDecoder("gbk").write(GBK_YI)).toBe("һ"); + // 3-byte UTF-8 (CJK) is strong evidence and switches back + expect(d.write(Buffer.from("好"))).toBe("好"); + expect(d.write(GBK_YI)).toBe("һ"); + }); + + it("end() flushes a truncated character instead of dropping it", () => { + const d = new OutputDecoder("gbk"); + expect(d.write(hex("c4e3ba"))).toBe("你"); + expect(d.end()).toBe("\ufffd"); + }); + + it("strings pass through (streams already set to utf8)", () => { + expect(new OutputDecoder("gbk").write("abc")).toBe("abc"); + }); +}); + +describe("OutputDecoder off Windows / no legacy decoder", () => { + it("lenient UTF-8 with split characters kept", () => { + const d = new OutputDecoder(null); + const u = Buffer.from("你好"); + expect(d.write(u.subarray(0, 4)) + d.write(u.subarray(4)) + d.end()).toBe("你好"); + expect(decodeOutput(GBK_HELLO, null)).toContain("\ufffd"); + }); + it("systemLegacyEncoding is null on macOS and Linux", () => { + expect(systemLegacyEncoding("darwin")).toBeNull(); + expect(systemLegacyEncoding("linux")).toBeNull(); + }); + it("an unknown label falls back to UTF-8", () => { + expect(new OutputDecoder("no-such-enc").write(Buffer.from("ok"))).toBe("ok"); + }); +}); + +describe("code page detection", () => { + it("parses reg query and chcp output", () => { + expect(parseCodePage("\r\nHKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Nls\\CodePage\r\n ACP REG_SZ 936\r\n\r\n")).toBe(936); + expect(parseCodePage("Active code page: 65001\r\n")).toBe(65001); + expect(parseCodePage("活动代码页: 936")).toBe(936); + expect(parseCodePage("garbage")).toBeNull(); + }); + it("maps code pages and locales", () => { + expect(codePageLabel(936)).toBe("gbk"); + expect(codePageLabel(437)).toBeNull(); + expect(codePageLabel(1252)).toBe("windows-1252"); + expect(labelForLocale("zh-CN")).toBe("gbk"); + expect(labelForLocale("zh-TW")).toBe("big5"); + expect(labelForLocale("zh-Hant-HK")).toBe("big5"); + expect(labelForLocale("ja-JP")).toBe("shift_jis"); + expect(labelForLocale("en-US")).toBeNull(); + }); + it("decodeOutput uses the cached system encoding by default", () => { + _setSystemLegacyEncoding("gbk"); + expect(decodeOutput(GBK_NOPATH)).toBe("系统找不到指定的路径。"); + }); +}); diff --git a/packages/agent-console/test/v1/fold.test.ts b/packages/agent-console/test/v1/fold.test.ts new file mode 100644 index 0000000..d0f9963 --- /dev/null +++ b/packages/agent-console/test/v1/fold.test.ts @@ -0,0 +1,128 @@ +// 1.3 item 2: Claude-desktop-style folding of tool calls and short thinking +import { describe, it, expect } from "vitest"; +import { foldTimeline, summarize, stepTarget, activeStep, SHORT_THINK_CHARS } from "../../web/src/timeline/fold.js"; +import { reduceTimeline, type DisplayItem, type ToolStep } from "../../web/src/timeline/reducer.js"; +import { mapSdkMessage, newMapState } from "../../daemon/src/providers/claude/map.js"; + +type Ev = Record; +let seq = 0; +const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: 0, threadId: "t", turnId: "u1", ...e })) as never[]; +const tool = (itemId: string, kind: string, status: string, extra: Ev = {}): Ev => ({ type: "tool_call", itemId, kind, title: `${kind} ${itemId}`, status, ...extra }); +const kinds = (items: DisplayItem[]) => items.map((i) => i.kind); +const group = (items: DisplayItem[], n = 0) => items.filter((i) => i.kind === "toolgroup")[n] as Extract; + +describe("foldTimeline", () => { + it("merges tool runs split by short thinking into one group; long thinking and text still break it", () => { + const { items } = reduceTimeline(tl([ + { type: "user_message", text: "hi" }, + { type: "reasoning", itemId: "r0", text: "先看看" }, + tool("a", "read", "ok"), + { type: "reasoning", itemId: "r1", text: "" }, + tool("b", "bash", "ok"), + { type: "reasoning", itemId: "r2", text: "嗯".repeat(20) }, + tool("c", "edit", "ok"), + { type: "reasoning", itemId: "r3", text: "长".repeat(SHORT_THINK_CHARS + 1) }, + tool("d", "search", "ok"), + { type: "assistant_message", itemId: "m", text: "完成" }, + tool("e", "read", "ok"), + ]), { runtimeStatus: "idle" }); + // the reducer alone makes 5 groups; folded: [user, group(r0,a,r1,b,r2,c), long reasoning, group(d), assistant, group(e)] + expect(items.filter((i) => i.kind === "toolgroup")).toHaveLength(5); + const f = foldTimeline(items); + expect(kinds(f)).toEqual(["user", "toolgroup", "reasoning", "toolgroup", "assistant", "toolgroup"]); + // the empty finished thinking (r1) is dropped, the short ones become steps + expect(group(f).steps.map((s) => s.kind)).toEqual(["think", "read", "bash", "think", "edit"]); + expect(summarize(group(f).steps).counts).toEqual([["edit", 1], ["run", 1], ["read", 1]]); + }); + + it("does not mutate the reducer's items", () => { + const { items } = reduceTimeline(tl([tool("a", "read", "ok"), { type: "reasoning", itemId: "r", text: "x" }, tool("b", "read", "ok")]), {}); + const before = JSON.stringify(items); + foldTimeline(items); + foldTimeline(items); + expect(JSON.stringify(items)).toBe(before); + }); + + it("drops a lone finished empty thinking row, keeps short thinking that has no tools next to it", () => { + const { items } = reduceTimeline(tl([ + { type: "reasoning", itemId: "r0", text: "" }, + { type: "assistant_message", itemId: "m", text: "a" }, + { type: "reasoning", itemId: "r1", text: "短" }, + { type: "assistant_message", itemId: "m2", text: "b" }, + ]), { runtimeStatus: "idle" }); + expect(kinds(foldTimeline(items))).toEqual(["assistant", "reasoning", "assistant"]); + }); + + it("showThinking off hides thinking everywhere, also inside groups", () => { + const { items } = reduceTimeline(tl([{ type: "reasoning", itemId: "r0", text: "x" }, tool("a", "read", "ok"), { type: "reasoning", itemId: "r1", text: "y".repeat(500) }]), {}); + const f = foldTimeline(items, { showThinking: false }); + expect(kinds(f)).toEqual(["toolgroup"]); + expect(group(f).steps.map((s) => s.kind)).toEqual(["read"]); + }); + + it("gone items are transparent (a hidden row doesn't split a run)", () => { + const items = [ + { kind: "toolgroup", key: "g1", steps: [{ itemId: "a", kind: "read", title: "", status: "ok" }] }, + { kind: "gone", key: "x" }, + { kind: "toolgroup", key: "g2", steps: [{ itemId: "b", kind: "glob", title: "", status: "ok" }] }, + ] as DisplayItem[]; + const f = foldTimeline(items); + expect(f).toHaveLength(1); + expect(f[0]!.key).toBe("g1"); + }); +}); + +describe("summary, failures and the running row", () => { + it("counts by category in a fixed order and counts failures", () => { + const steps = [ + { itemId: "1", kind: "glob", title: "", status: "ok" }, { itemId: "2", kind: "web", title: "", status: "ok" }, + { itemId: "3", kind: "bash", title: "", status: "failed" }, { itemId: "4", kind: "write", title: "", status: "ok" }, + { itemId: "5", kind: "edit", title: "", status: "failed" }, { itemId: "6", kind: "mcp", title: "", status: "ok" }, + { itemId: "7", kind: "think", title: "", status: "ok", think: { text: "x".repeat(80), streaming: false } }, + ] as ToolStep[]; + expect(summarize(steps)).toEqual({ counts: [["edit", 2], ["run", 1], ["search", 2], ["other", 1]], failed: 2, thinkSecs: 2 }); + }); + + it("running row: the last running tool's command / file, else streaming thinking at the end", () => { + const run = { itemId: "1", kind: "bash", title: "运行 npm test", status: "running", input: { command: "npm\n test --run" } } as ToolStep; + expect(stepTarget(run)).toBe("npm test --run"); + expect(stepTarget({ itemId: "2", kind: "read", title: "读取 a", status: "running", input: { file_path: "src/a.ts" } })).toBe("src/a.ts"); + expect(stepTarget({ itemId: "3", kind: "other", title: "Some tool", status: "running" })).toBe("Some tool"); + expect(activeStep([run, { itemId: "x", kind: "read", title: "", status: "ok" }])).toBe(run); + const think = { itemId: "t", kind: "think", title: "", status: "running", think: { text: "", streaming: true } } as ToolStep; + expect(activeStep([{ itemId: "x", kind: "read", title: "", status: "ok" }, think])).toBe(think); + expect(activeStep([{ itemId: "x", kind: "read", title: "", status: "ok" }])).toBeNull(); + }); + + it("an interrupted turn: leftover running steps become failures once idle", () => { + const { items } = reduceTimeline(tl([tool("a", "bash", "running", { input: { command: "sleep 99" } })]), { runtimeStatus: "idle" }); + const f = foldTimeline(items); + expect(summarize(group(f).steps).failed).toBe(1); + expect(activeStep(group(f).steps)).toBeNull(); + }); +}); + +describe("real adapter shapes: claude stream-json", () => { + it("thinking + Read + Bash(error) in one assistant message fold into one summary with 1 failure", () => { + const st = newMapState(); + const raw: Ev[] = [ + ...mapSdkMessage({ type: "assistant", message: { id: "m1", content: [ + { type: "thinking", thinking: "先读文件再跑测试" }, + { type: "tool_use", id: "tu1", name: "Read", input: { file_path: "src/a.ts" } }, + { type: "tool_use", id: "tu2", name: "Bash", input: { command: "npm test" } }, + ] } }, st, "/p") as Ev[], + ...mapSdkMessage({ type: "user", message: { role: "user", content: [ + { type: "tool_result", tool_use_id: "tu1", content: [{ type: "text", text: "export {}" }] }, + { type: "tool_result", tool_use_id: "tu2", content: "Error: 1 test failed", is_error: true }, + ] } }, st, "/p") as Ev[], + ]; + const { items } = reduceTimeline(tl(raw), { runtimeStatus: "idle" }); + const f = foldTimeline(items); + expect(kinds(f)).toEqual(["toolgroup"]); + const sum = summarize(group(f).steps); + expect(sum.counts).toEqual([["run", 1], ["read", 1]]); + expect(sum.failed).toBe(1); + const failed = group(f).steps.find((s) => s.status === "failed")!; + expect(failed.output).toContain("1 test failed"); + }); +}); diff --git a/packages/agent-console/test/v1/gate.test.ts b/packages/agent-console/test/v1/gate.test.ts index 5692fd9..b235d11 100644 --- a/packages/agent-console/test/v1/gate.test.ts +++ b/packages/agent-console/test/v1/gate.test.ts @@ -46,7 +46,8 @@ describe("gate (lib/gate.mjs)", () => { expect(calls).toBe(1); for (const result of results) { expect(result.status).toBe(302); - expect(result.headers.location).toBe(`http://127.0.0.1:${daemonPort}/?theme=dark#t=${token}`); + // 1.3: to the gate's own wrapper page, the daemon port next to the token in the fragment + expect(result.headers.location).toBe(`http://127.0.0.1:${port}/app?theme=dark#t=${token}&p=${daemonPort}`); expect(result.headers["cache-control"]).toBe("no-store"); expect(result.headers["x-content-type-options"]).toBe("nosniff"); expect(result.headers["referrer-policy"]).toBe("no-referrer"); diff --git a/packages/agent-console/test/v1/gitbash.test.ts b/packages/agent-console/test/v1/gitbash.test.ts new file mode 100644 index 0000000..1156a58 --- /dev/null +++ b/packages/agent-console/test/v1/gitbash.test.ts @@ -0,0 +1,206 @@ +// 1.3: Git Bash detection for the agents on Windows, with a mocked file system (no Windows here). +import { describe, it, expect, afterEach } from "vitest"; +import { + bashEnv, bashForGitDir, checkBashPath, driveBashCandidates, findGitBash, isWslBash, knownBashCandidates, bashPathDir, +} from "../../daemon/src/util/gitBash.js"; +import { agentShellStatus, bashMissingFor, refreshAgentShell, withAgentShell } from "../../daemon/src/util/agentShell.js"; + +const lc = (s: string) => s.toLowerCase(); +/** A fake Windows disk: the given files exist (case-insensitive), nothing else does */ +function disk(files: string[]) { + const set = new Set(files.map(lc)); + const isFile = (p: string) => set.has(lc(p)); + return { isFile, isFileAsync: async (p: string) => isFile(p) }; +} +const WIN_ENV = { + SystemRoot: "C:\\WINDOWS", + ProgramFiles: "C:\\Program Files", + "ProgramFiles(x86)": "C:\\Program Files (x86)", + LOCALAPPDATA: "C:\\Users\\nolan\\AppData\\Local", + PATHEXT: ".COM;.EXE;.BAT;.CMD", +}; +const WSL = "C:\\WINDOWS\\system32\\bash.exe"; +const APPS = "C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps\\bash.exe"; + +describe("isWslBash", () => { + it("System32 / SysWOW64 / Sysnative / WindowsApps bash are the WSL launcher", () => { + expect(isWslBash(WSL, WIN_ENV)).toBe(true); + expect(isWslBash("c:/windows/System32/bash.exe")).toBe(true); + expect(isWslBash("C:\\Windows\\SysWOW64\\bash.exe")).toBe(true); + expect(isWslBash("C:\\Windows\\Sysnative\\bash.exe")).toBe(true); + expect(isWslBash(APPS)).toBe(true); + expect(isWslBash("D:\\Win\\System32\\bash.exe", { SystemRoot: "D:\\Win" })).toBe(true); + expect(isWslBash("E:\\Git\\bin\\bash.exe", WIN_ENV)).toBe(false); + expect(isWslBash("C:\\Program Files\\Git\\usr\\bin\\bash.exe", WIN_ENV)).toBe(false); + }); +}); + +describe("checkBashPath (Settings → Bash path)", () => { + const d = disk(["E:\\Git\\bin\\bash.exe", WSL, "E:\\Git\\bin\\git.exe"]); + it("accepts an existing bash.exe, with quotes and spaces trimmed", () => { + expect(checkBashPath(' "E:\\Git\\bin\\bash.exe" ', { ...d, env: WIN_ENV })).toEqual({ ok: true, path: "E:\\Git\\bin\\bash.exe" }); + expect(checkBashPath("e:/Git/bin/bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: true, path: "e:\\Git\\bin\\bash.exe" }); + }); + it("refuses empty, relative, non-bash, WSL and missing paths", () => { + expect(checkBashPath("", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "empty" }); + expect(checkBashPath("bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "relative" }); + // UNC paths are refused: the check is synchronous and a dead share could stall the daemon + expect(checkBashPath("\\\\srv\\share\\Git\\bin\\bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "relative" }); + expect(checkBashPath("E:\\Git\\bin\\git.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "notBash" }); + expect(checkBashPath(WSL, { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "wsl" }); + expect(checkBashPath("F:\\Git\\bin\\bash.exe", { ...d, env: WIN_ENV })).toEqual({ ok: false, reason: "missing" }); + }); +}); + +describe("candidates", () => { + it("bash next to git.exe: cmd, bin, mingw64\\bin, usr\\bin", () => { + expect(bashForGitDir("E:\\Git\\cmd")[0]).toBe("E:\\Git\\bin\\bash.exe"); + expect(bashForGitDir("E:\\Git\\bin")).toContain("E:\\Git\\bin\\bash.exe"); + expect(bashForGitDir("E:\\Git\\mingw64\\bin")[0]).toBe("E:\\Git\\bin\\bash.exe"); + expect(bashForGitDir("D:\\Tools\\Git\\usr\\bin")[0]).toBe("D:\\Tools\\Git\\bin\\bash.exe"); + }); + it("known install dirs in order, deduped", () => { + const k = knownBashCandidates(WIN_ENV, "C:\\Users\\nolan"); + expect(k[0]).toBe("C:\\Program Files\\Git\\bin\\bash.exe"); + expect(k).toContain("C:\\Program Files (x86)\\Git\\bin\\bash.exe"); + expect(k).toContain("C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe"); + expect(k).toContain("C:\\Users\\nolan\\scoop\\apps\\git\\current\\bin\\bash.exe"); + expect(new Set(k.map(lc)).size).toBe(k.length); + }); + it("other drives", () => { + expect(driveBashCandidates(["e", "F:", "1"])).toEqual([ + "E:\\Git\\bin\\bash.exe", "E:\\Program Files\\Git\\bin\\bash.exe", + "F:\\Git\\bin\\bash.exe", "F:\\Program Files\\Git\\bin\\bash.exe", + ]); + }); +}); + +describe("findGitBash", () => { + it("Nolan's machine: Git on E:\\Git with git on PATH, WSL bash in System32 first → E:\\Git\\bin\\bash.exe", async () => { + const d = disk([WSL, APPS, "E:\\Git\\cmd\\git.exe", "E:\\Git\\bin\\bash.exe"]); + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\WINDOWS;E:\\Git\\cmd;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" }; + const r = await findGitBash("", { ...d, env, drives: [] }); + expect(r.found).toEqual({ path: "E:\\Git\\bin\\bash.exe", source: "git" }); + }); + it("git not on PATH: finds X:\\Git on another drive, and never System32 or WindowsApps", async () => { + const d = disk([WSL, APPS, "E:\\Git\\bin\\bash.exe"]); + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" }; + const r = await findGitBash("", { ...d, env }); + expect(r.found).toEqual({ path: "E:\\Git\\bin\\bash.exe", source: "drive" }); + }); + it("Program Files before other drives; LocalAppData\\Programs for per-user installs", async () => { + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" }; + expect((await findGitBash("", { ...disk(["C:\\Program Files\\Git\\bin\\bash.exe", "E:\\Git\\bin\\bash.exe"]), env })).found) + .toEqual({ path: "C:\\Program Files\\Git\\bin\\bash.exe", source: "known" }); + expect((await findGitBash("", { ...disk(["C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe"]), env, drives: [] })).found) + .toEqual({ path: "C:\\Users\\nolan\\AppData\\Local\\Programs\\Git\\bin\\bash.exe", source: "known" }); + }); + it("only the WSL launcher → nothing found", async () => { + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\Users\\nolan\\AppData\\Local\\Microsoft\\WindowsApps" }; + expect((await findGitBash("", { ...disk([WSL, APPS]), env })).found).toBeNull(); + }); + it("a non-WSL bash.exe on PATH (MSYS2) is the last resort", async () => { + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32;C:\\msys64\\usr\\bin" }; + expect((await findGitBash("", { ...disk([WSL, "C:\\msys64\\usr\\bin\\bash.exe"]), env, drives: [] })).found) + .toEqual({ path: "C:\\msys64\\usr\\bin\\bash.exe", source: "path" }); + }); + it("the manual setting wins; an unusable one is reported and detection still runs", async () => { + const d = disk(["D:\\PortableGit\\bin\\bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", WSL]); + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" }; + expect((await findGitBash("D:\\PortableGit\\bin\\bash.exe", { ...d, env })).found).toEqual({ path: "D:\\PortableGit\\bin\\bash.exe", source: "manual" }); + const bad = await findGitBash(WSL, { ...d, env }); + expect(bad.manualError).toEqual({ ok: false, reason: "wsl" }); + expect(bad.found?.source).toBe("known"); + }); + it("a valid CLAUDE_CODE_GIT_BASH_PATH is kept; one pointing at WSL is ignored", async () => { + const d = disk(["F:\\g\\bin\\bash.exe", "C:\\Program Files\\Git\\bin\\bash.exe", WSL]); + const env = { ...WIN_ENV, Path: "", CLAUDE_CODE_GIT_BASH_PATH: "F:\\g\\bin\\bash.exe" }; + expect((await findGitBash("", { ...d, env })).found).toEqual({ path: "F:\\g\\bin\\bash.exe", source: "env" }); + expect((await findGitBash("", { ...d, env: { ...env, CLAUDE_CODE_GIT_BASH_PATH: WSL } })).found?.source).toBe("known"); + }); + it("a drive probe that hangs (dead network drive) times out instead of blocking", async () => { + const env = { ...WIN_ENV, Path: "" }; + const t0 = Date.now(); + const r = await findGitBash("", { + isFile: () => false, + isFileAsync: (p) => (p.startsWith("Z:") ? new Promise(() => {}) : Promise.resolve(p === "E:\\Git\\bin\\bash.exe")), + env, probeTimeoutMs: 200, + }); + expect(r.found?.path).toBe("E:\\Git\\bin\\bash.exe"); + expect(Date.now() - t0).toBeLessThan(2000); + }); +}); + +describe("bashEnv (per-spawn environment)", () => { + const d = disk([WSL, "E:\\Git\\bin\\bash.exe", "E:\\Git\\cmd\\git.exe"]); + it("sets both agent variables and puts Git\\bin before System32 so `where bash.exe` (Pi) and PATH lookups (dsh) find it", () => { + const env = { Path: "C:\\WINDOWS\\system32;E:\\Git\\cmd", PATHEXT: ".EXE" }; + const out = bashEnv({ path: "E:\\Git\\bin\\bash.exe", source: "git" }, env, d.isFile); + expect(out.CLAUDE_CODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe"); + expect(out.OPENCODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe"); + expect(out.Path).toBe("E:\\Git\\bin;C:\\WINDOWS\\system32;E:\\Git\\cmd"); + expect(out.PATH).toBeUndefined(); + }); + it("PATH is left alone when the first bash.exe on it is already the chosen one", () => { + const env = { PATH: "E:\\Git\\bin;C:\\WINDOWS\\system32", PATHEXT: ".EXE" }; + const out = bashEnv({ path: "E:\\Git\\bin\\bash.exe", source: "git" }, env, d.isFile); + expect(out.PATH).toBeUndefined(); + }); + it("usr\\bin picks the Git\\bin directory for PATH (only bash/sh/git there, no coreutils shadowing)", () => { + const dd = disk(["E:\\Git\\bin\\bash.exe", "E:\\Git\\usr\\bin\\bash.exe"]); + expect(bashPathDir("E:\\Git\\usr\\bin\\bash.exe", dd.isFile)).toBe("E:\\Git\\bin"); + expect(bashPathDir("C:\\msys64\\usr\\bin\\bash.exe", dd.isFile)).toBe("C:\\msys64\\usr\\bin"); + }); + it("nothing found → no changes", () => { + expect(bashEnv(null, { PATH: "x" })).toEqual({}); + }); +}); + +describe("agentShell state", () => { + afterEach(async () => { await refreshAgentShell("", { platform: "linux" }); }); + it("is a no-op on macOS / Linux", async () => { + await refreshAgentShell("C:\\x\\bash.exe", { platform: "darwin" }); + expect(agentShellStatus().needed).toBe(false); + const env = { PATH: "/usr/bin" }; + expect(withAgentShell(env)).toBe(env); + expect(bashMissingFor("claude")).toBe(false); + }); + it("Windows: merges the variables into a spawn env; hint only for agents that need bash", async () => { + const d = disk([WSL, "E:\\Git\\bin\\bash.exe"]); + const env = { ...WIN_ENV, Path: "C:\\WINDOWS\\system32" }; + await refreshAgentShell("", { platform: "win32", deps: { ...d, env } }); + expect(agentShellStatus().found?.path).toBe("E:\\Git\\bin\\bash.exe"); + const out: Record = withAgentShell({ Path: "C:\\WINDOWS\\system32", FOO: "1" }); + expect(out.CLAUDE_CODE_GIT_BASH_PATH).toBe("E:\\Git\\bin\\bash.exe"); + expect(out.Path).toBe("E:\\Git\\bin;C:\\WINDOWS\\system32"); + expect(out.FOO).toBe("1"); + expect(bashMissingFor("claude")).toBe(false); + + await refreshAgentShell("", { platform: "win32", deps: { ...disk([WSL]), env, drives: [] } }); + expect(agentShellStatus().found).toBeNull(); + expect(bashMissingFor("claude")).toBe(true); + expect(bashMissingFor("pi")).toBe(true); + expect(bashMissingFor("codex")).toBe(false); + expect(withAgentShell({ Path: "x" })).toEqual({ Path: "x" }); + }); + it("an unusable manual path is reported in the status", async () => { + const env = { ...WIN_ENV, Path: "" }; + await refreshAgentShell(WSL, { platform: "win32", deps: { ...disk([WSL]), env, drives: [] } }); + expect(agentShellStatus().manualError).toBe("wsl"); + }); +}); + +describe("probeInChild (other drives, out of process)", () => { + it("returns the first existing candidate in list order, null when none", async () => { + const { mkdtempSync, writeFileSync } = await import("node:fs"); + const { tmpdir } = await import("node:os"); + const { join } = await import("node:path"); + const { probeInChild } = await import("../../daemon/src/util/gitBash.js"); + const dir = mkdtempSync(join(tmpdir(), "ac-probe-")); + const a = join(dir, "a"), b = join(dir, "b"); + writeFileSync(a, ""); writeFileSync(b, ""); + expect(await probeInChild([join(dir, "nope"), b, a], 5000)).toBe(b); + expect(await probeInChild([join(dir, "nope"), dir], 5000)).toBeNull(); // a directory is not a file + expect(await probeInChild([], 5000)).toBeNull(); + }); +}); diff --git a/packages/agent-console/test/v1/manager.test.ts b/packages/agent-console/test/v1/manager.test.ts index 23c0f11..38f7df2 100644 --- a/packages/agent-console/test/v1/manager.test.ts +++ b/packages/agent-console/test/v1/manager.test.ts @@ -201,11 +201,13 @@ describe("AgentManager", () => { it("idle recycling: idle timeout → closed", async () => { await settings.set({ idleCloseMinutes: 0.0001 }); // ~6ms await manager.send(threadId, { text: "你好" }); - await waitFor(async () => (await threads.get(threadId))?.status === "idle"); + // The turn's end already runs recycleIdle() itself; with a ~6ms timeout that one may close the thread before a + // poll sees "idle" (and while it is still closing, the manual call below returns at once), so accept both here + await waitFor(async () => ["idle", "closed"].includes((await threads.get(threadId))?.status ?? "")); // lastActivity is in milliseconds; wait more than 6ms, then trigger recycling by hand await sleep(50); await (manager as unknown as { recycleIdle(): Promise }).recycleIdle(); - expect((await threads.get(threadId))?.status).toBe("closed"); + await waitFor(async () => (await threads.get(threadId))?.status === "closed", 5000); }, 15000); it("B17: at most MAX_WARM_IDLE idle agent processes stay warm", async () => { diff --git a/packages/agent-console/test/v1/plugin-entry.test.ts b/packages/agent-console/test/v1/plugin-entry.test.ts index ef8a15d..49c4ec1 100644 --- a/packages/agent-console/test/v1/plugin-entry.test.ts +++ b/packages/agent-console/test/v1/plugin-entry.test.ts @@ -123,7 +123,10 @@ describe("plugin entry (index.mjs)", () => { expect(open.status).toBe(302); const location = new URL(String(open.headers.location)); expect(location.hostname).toBe("127.0.0.1"); - const daemonPort = Number(location.port); + // 1.3: the gate's own wrapper page; the daemon's port is in the fragment next to the token + expect(Number(location.port)).toBe(port); + expect(location.pathname).toBe("/app"); + const daemonPort = Number(new URLSearchParams(location.hash.slice(1)).get("p")); expect(daemonPort).toBeGreaterThan(0); expect(daemonPort).not.toBe(port); // From the first open on the host refreshes session.js (beat), so a page that lost its connection can tell it from a dead host's @@ -137,7 +140,7 @@ describe("plugin entry (index.mjs)", () => { expect(token).not.toBe(key); expect(location.search).not.toContain(token); expect(location.search).not.toContain(key); - expect(location.hash).toBe(`#t=${token}`); + expect(location.hash).toBe(`#t=${token}&p=${daemonPort}`); expect(readFileSync(sessionPath, "utf8")).not.toContain(token); // The daemon token can't be used as the gate key (nor the key as the daemon token, see the ping below) @@ -161,7 +164,7 @@ describe("plugin entry (index.mjs)", () => { // Opening a second time reuses the same daemon const again = await request(port, `/open?k=${key}&theme=dark`); expect(again.status).toBe(302); - expect(Number(new URL(String(again.headers.location)).port)).toBe(daemonPort); + expect(new URLSearchParams(new URL(String(again.headers.location)).hash.slice(1)).get("p")).toBe(String(daemonPort)); // Origin: null reading a static page → 403 const opaque = await request(daemonPort, "/", { origin: "null" }); diff --git a/packages/agent-console/test/v1/send-latency.test.ts b/packages/agent-console/test/v1/send-latency.test.ts new file mode 100644 index 0000000..c96c197 --- /dev/null +++ b/packages/agent-console/test/v1/send-latency.test.ts @@ -0,0 +1,130 @@ +// 1.3 (Nolan, Windows): the user's message must not wait for the Agent to start. The daemon persists and pushes the +// user_message (with the page's clientId) before detection / spawn / ACP initialize, and a start that fails afterwards +// leaves the message with an error card instead of dropping it. +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AgentManager } from "../../daemon/src/agents/manager.js"; +import { ThreadsStore } from "../../daemon/src/store/threads.js"; +import { ProjectsStore } from "../../daemon/src/store/projects.js"; +import { SettingsStore } from "../../daemon/src/store/settings.js"; +import { AttachmentStore } from "../../daemon/src/store/attachments.js"; +import { Gateway } from "../../daemon/src/ws/gateway.js"; +import { initProviders, getProvider } from "../../daemon/src/providers/registry.js"; +import { clearProviderCache } from "../../daemon/src/providers/infoCache.js"; +import type { Config } from "../../daemon/src/config.js"; + +process.env.AGENT_CONSOLE_MOCK = "1"; +const cfg: Config = { port: 0, dataDir: "", token: "t", version: "0.0.0", idleExitMinutes: 60, buildStamp: "0" }; + +let dir: string; +let threads: ThreadsStore; +let projects: ProjectsStore; +let gw: Gateway; +let manager: AgentManager; +let threadId: string; +let projectId: string; +let pushed: { at: number; ch: string; data: { type?: string; status?: string; event?: { type: string; clientId?: string; text?: string } } }[]; + +beforeEach(async () => { + dir = mkdtempSync(join(tmpdir(), "ac-lat-")); + threads = new ThreadsStore(dir); + projects = new ProjectsStore(dir); + gw = new Gateway(cfg); + pushed = []; + const orig = gw.publish.bind(gw); + vi.spyOn(gw, "publish").mockImplementation((ch, data) => { pushed.push({ at: Date.now(), ch, data: data as never }); orig(ch, data); }); + initProviders(); + manager = new AgentManager(gw, threads, projects, new SettingsStore(dir), new AttachmentStore(join(dir, "attachments"))); + const proj = await projects.create(dir); + projectId = proj.id; + threadId = (await threads.create({ projectId, provider: "mock" })).id; +}); + +afterEach(async () => { + delete process.env.AGENT_CONSOLE_MOCK_START_MS; + delete process.env.AGENT_CONSOLE_MOCK_DETECT_MS; + vi.restoreAllMocks(); + await manager.shutdown(); + // a status / title patch may still be renaming meta.json.tmp-*: wait for it before the directory goes (Windows ENOENT) + await threads.idle(); + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 }); +}); + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const waitFor = async (fn: () => boolean | Promise, ms = 15000) => { + const t0 = Date.now(); + while (Date.now() - t0 < ms) { if (await fn()) return; await sleep(20); } + throw new Error("waitFor 超时"); +}; +const userPush = (clientId?: string) => pushed.find((p) => p.ch === `thread:${threadId}` && p.data.type === "event" && p.data.event?.type === "user_message" && (!clientId || p.data.event.clientId === clientId)); +const statusPush = (s: string) => pushed.find((p) => p.ch === `thread:${threadId}` && p.data.type === "status" && p.data.status === s); + +describe("send latency (1.3)", () => { + it("user_message (with clientId) is pushed before a slow Agent start finishes", async () => { + process.env.AGENT_CONSOLE_MOCK_START_MS = "1500"; + const t0 = Date.now(); + const sending = manager.send(threadId, { text: "你好", clientId: "c-test-1" }); + await waitFor(() => !!userPush("c-test-1"), 3000); + const echo = userPush("c-test-1")!; + expect(echo.at - t0).toBeLessThan(300); + // the working state follows right after (pushed once the title patch is on disk), the Agent is still starting + await waitFor(() => !!statusPush("initializing"), 1000); + expect(statusPush("running")).toBeFalsy(); + await sending; + expect(statusPush("running")!.at - t0).toBeGreaterThanOrEqual(1400); + // persisted with the clientId, ahead of turn_started (snapshot reconcile works after a reload) + const evs = await threads.readEvents(threadId, 0, 1000); + const iu = evs.findIndex((e) => e.type === "user_message"); + expect((evs[iu] as { clientId?: string }).clientId).toBe("c-test-1"); + await waitFor(async () => (await threads.get(threadId))?.status === "idle", 20000); + const ev2 = await threads.readEvents(threadId, 0, 1000); + expect(ev2.findIndex((e) => e.type === "turn_started")).toBeGreaterThan(iu); + expect(ev2.filter((e) => e.type === "user_message").length).toBe(1); + }, 30000); + + it("a slow detection (cold CLI probe) does not hold the message back either", async () => { + process.env.AGENT_CONSOLE_MOCK_DETECT_MS = "1200"; + clearProviderCache("mock"); // a cold (or >60 s old) detection cache + const t0 = Date.now(); + const sending = manager.send(threadId, { text: "检测慢", clientId: "c-test-2" }); + await waitFor(() => !!userPush("c-test-2"), 3000); + expect(userPush("c-test-2")!.at - t0).toBeLessThan(300); + await sending; + expect(statusPush("running")!.at - t0).toBeGreaterThanOrEqual(1100); // detection did run, after the message + await waitFor(async () => (await threads.get(threadId))?.status === "idle", 20000); + }, 30000); + + it("a failed Agent start keeps the message, adds the error card, and doesn't lock the Agent", async () => { + const mock = getProvider("mock")!; + const spy = vi.spyOn(mock, "createSession").mockRejectedValue(new Error("spawn EPERM")); + await expect(manager.send(threadId, { text: "启动失败", clientId: "c-test-3" })).rejects.toThrow(/EPERM/); + const evs = await threads.readEvents(threadId, 0, 1000); + expect(evs.map((e) => e.type)).toEqual(["user_message", "notice", "turn_ended"]); + expect((evs[2] as { status?: string }).status).toBe("failed"); + spy.mockRestore(); + // the Agent never ran: switching it is still allowed (mock is the only one here, so switch to itself) + await expect(manager.setProvider(threadId, "mock")).resolves.toBeUndefined(); + }, 20000); + + it("an unknown Agent is refused before anything is saved", async () => { + const t = await threads.create({ projectId, provider: "nope-agent" }); + await expect(manager.send(t.id, { text: "x", clientId: "c-test-4" })).rejects.toThrow(); + expect((await threads.readEvents(t.id, 0, 100)).length).toBe(0); + }); + + it("a queued message keeps its clientId until its turn starts; steer carries it too", async () => { + await manager.send(threadId, { text: "/slow", clientId: "c-a" }); + await waitFor(async () => (await threads.get(threadId))?.status === "running"); + expect(await manager.send(threadId, { text: "排队的", clientId: "c-q" })).toBe("queued"); + expect(userPush("c-q")).toBeFalsy(); + await waitFor(() => !!userPush("c-q"), 25000); + // "running" is stored before session.send returns, and until then (rt.starting) a steer is queued by design: + // wait for the turn to have really started, not just for the status (under load the poll lands in that window) + await waitFor(async () => (await threads.get(threadId))?.status === "running" && manager.runtimeInfo(threadId)?.starting === false); + expect(await manager.send(threadId, { text: "插话", clientId: "c-s" }, "steer")).toBe("steered"); + expect(userPush("c-s")).toBeTruthy(); + await waitFor(async () => (await threads.get(threadId))?.status === "idle", 25000); + }, 60000); +}); diff --git a/packages/agent-console/test/v1/timeline-polish.test.ts b/packages/agent-console/test/v1/timeline-polish.test.ts new file mode 100644 index 0000000..c7f0236 --- /dev/null +++ b/packages/agent-console/test/v1/timeline-polish.test.ts @@ -0,0 +1,77 @@ +// 1.3 timeline polish: compact tool rows (+N -M), checklists from every provider's step list, the tasks pill, +// and the reply footer's model / time +import { describe, it, expect } from "vitest"; +import { foldTimeline, toolStepCount, stepDiffStat, todoProgress, currentChecklist, TOOL_COLLAPSE_AT } from "../../web/src/timeline/fold.js"; +import { reduceTimeline, type DisplayItem, type ToolStep } from "../../web/src/timeline/reducer.js"; +import { editDetail } from "../../daemon/src/agents/diff.js"; + +type Ev = Record; +let seq = 0; +const tl = (evs: Ev[]) => evs.map((e) => ({ seq: ++seq, ts: 1000 + seq, threadId: "t", turnId: "u1", ...e })) as never[]; +const tool = (itemId: string, kind: string, status: string, extra: Ev = {}): Ev => ({ type: "tool_call", itemId, kind, title: `${kind} ${itemId}`, status, ...extra }); +const step = (kind: string, detail?: unknown): ToolStep => ({ itemId: kind, kind, title: kind, status: "ok", detail } as ToolStep); +const todos = (items: DisplayItem[]) => items.filter((i): i is Extract => i.kind === "todo"); + +describe("checklists", () => { + it("an ACP plan with entries is a checklist (completed → done); a plan without entries stays a plan card", () => { + const { items } = reduceTimeline(tl([ + { type: "plan", itemId: "p", markdown: "- a\n- b", entries: [{ step: "a", status: "completed" }, { step: "b", status: "in_progress" }, { step: "c", status: "pending" }] }, + { type: "plan", itemId: "q", markdown: "## 计划\n1. x" }, + ]), {}); + expect(todos(items)[0]!.items).toEqual([{ text: "a", status: "done" }, { text: "b", status: "in_progress" }, { text: "c", status: "pending" }]); + expect(items.some((i) => i.kind === "plan")).toBe(true); + }); + + it("only the latest list of a user turn is shown; Claude's TodoWrite tool row is not repeated as a step", () => { + const { items } = reduceTimeline(tl([ + { type: "user_message", text: "1" }, + { type: "todo", items: [{ text: "a", status: "pending" }] }, + tool("w", "todo", "ok"), + tool("r", "read", "ok"), + { type: "todo", items: [{ text: "a", status: "done" }] }, + { type: "user_message", text: "2" }, + { type: "todo", items: [{ text: "b", status: "pending" }] }, + ]), {}); + const f = foldTimeline(items); + expect(todos(f).map((t) => t.items[0]!.text + t.items[0]!.status)).toEqual(["adone", "bpending"]); + const g = f.find((i) => i.kind === "toolgroup") as Extract; + expect(g.steps.map((s) => s.kind)).toEqual(["read"]); + }); + + it("the pill shows the latest turn's list while something is open, not a finished one or an older turn's", () => { + const run = (evs: Ev[]) => currentChecklist(foldTimeline(reduceTimeline(tl(evs), {}).items)); + expect(run([{ type: "user_message", text: "1" }, { type: "todo", items: [{ text: "a", status: "done" }, { text: "b", status: "pending" }] }])?.items).toHaveLength(2); + expect(run([{ type: "user_message", text: "1" }, { type: "todo", items: [{ text: "a", status: "done" }] }])).toBeNull(); + expect(run([{ type: "todo", items: [{ text: "a", status: "pending" }] }, { type: "user_message", text: "2" }])).toBeNull(); + expect(todoProgress([{ status: "done" }, { status: "completed" }, { status: "in_progress" }])).toEqual({ done: 2, total: 3 }); + }); +}); + +describe("tool rows", () => { + it("counts tool calls (not thinking) against the collapse threshold", () => { + expect(TOOL_COLLAPSE_AT).toBe(6); + expect(toolStepCount([step("think"), step("read"), step("bash"), step("think")])).toBe(2); + }); + + it("+N -M from the daemon's counts, else from the hunks; null without a diff", () => { + const d = editDetail({ path: "a.ts", old: "x\ny\n", new: "x\nz\nw\n" }); + expect(stepDiffStat(step("edit", d))).toEqual({ added: 2, removed: 1 }); + expect(stepDiffStat(step("edit", { hunks: d.hunks }))).toEqual({ added: 2, removed: 1 }); + expect(stepDiffStat(step("edit"))).toBeNull(); + expect(stepDiffStat(step("bash", "text"))).toBeNull(); + }); +}); + +describe("reply footer", () => { + it("the turn end carries the turn's model and end time", () => { + const { items } = reduceTimeline(tl([ + { type: "turn_started", model: "gpt-5.5" }, + { type: "assistant_message", itemId: "m", text: "ok" }, + { type: "turn_ended", status: "completed" }, + ]), {}); + const te = items.find((i) => i.kind === "turnend") as Extract; + expect(te.model).toBe("gpt-5.5"); + expect(typeof te.ts).toBe("number"); + expect(te.durationMs).toBeGreaterThanOrEqual(0); + }); +}); diff --git a/packages/agent-console/test/v1/title-text.test.ts b/packages/agent-console/test/v1/title-text.test.ts new file mode 100644 index 0000000..75d03fa --- /dev/null +++ b/packages/agent-console/test/v1/title-text.test.ts @@ -0,0 +1,11 @@ +// 1.3: auto titles of a message sent with "添加到对话" quotes use the user's own words. +import { describe, it, expect } from "vitest"; +import { titleText } from "../../daemon/src/agents/manager.js"; + +describe("titleText (1.3 quotes)", () => { + it("auto titles skip the leading quote blocks", () => { + expect(titleText("> [src/a.ts]\n> const x = 1;\n\n> second\n\n这句什么意思?")).toBe("这句什么意思?"); + expect(titleText("帮我 启动\n一下")).toBe("帮我 启动 一下"); + expect(titleText("> only a quote")).toBe("only a quote"); + }); +}); diff --git a/packages/agent-console/test/v1/wrapper.test.ts b/packages/agent-console/test/v1/wrapper.test.ts new file mode 100644 index 0000000..6a6020f --- /dev/null +++ b/packages/agent-console/test/v1/wrapper.test.ts @@ -0,0 +1,215 @@ +// 1.3 item 5: the gate's wrapper page (lib/wrapper.mjs) that keeps the plugin frame on the stable gate port +import { describe, expect, it } from "vitest"; +import { join, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { freePort, request } from "./helpers-net.js"; + +const root = resolve(__dirname, "..", ".."); +const gateUrl = pathToFileURL(join(root, "lib", "gate.mjs")).href; +const wrapperUrl = pathToFileURL(join(root, "lib", "wrapper.mjs")).href; + +type Msg = { source: unknown; data: unknown }; + +/** Runs the wrapper's script against a tiny fake DOM with a controllable clock */ +async function runWrapper(hash: string, search = "", opts: { visible?: boolean } = {}) { + const { wrapperHtml, WRAP_TIMING } = await import(/* @vite-ignore */ wrapperUrl); + const html: string = wrapperHtml("n0nce", WRAP_TIMING); + const script = html.split('")[0]!; + let now = 1_800_000_000_000; + const intervals: (() => void)[] = []; + const childWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } }; + const parentWin = { posted: [] as unknown[], postMessage(d: unknown) { this.posted.push(d); } }; + const el = (id: string) => ({ id, hidden: id !== "f", textContent: "", src: "", disabled: false, onclick: null as null | (() => void), + classList: { set: new Set(), add(c: string) { this.set.add(c); }, remove(c: string) { this.set.delete(c); } }, + on: {} as Record void>, addEventListener(t: string, fn: () => void) { this.on[t] = fn; } }); + const els: Record> = { f: el("f"), m: el("m"), s: el("s"), r: el("r") }; + (els.f as unknown as { contentWindow: unknown }).contentWindow = childWin; + let onMessage: (e: Msg) => void = () => {}; + const loc = { hash, search, replaced: null as string | null, replace(u: string) { this.replaced = u; } }; + const win: Record = { + parent: parentWin, + addEventListener: (t: string, fn: (e: Msg) => void) => { if (t === "message") onMessage = fn; }, + }; + const doc = { getElementById: (id: string) => els[id], documentElement: { className: "" }, visibilityState: opts.visible === false ? "hidden" : "visible" }; + const DateFake = { now: () => now }; + const fn = new Function("window", "document", "location", "setInterval", "Date", "URL", "URLSearchParams", script); + fn(win, doc, loc, (f: () => void) => { intervals.push(f); return 1; }, DateFake, URL, URLSearchParams); + const tick = (ms: number, step = 1000) => { for (let t = 0; t < ms; t += step) { now += step; intervals.forEach((f) => f()); } }; + return { + els, loc, childWin, parentWin, tick, doc, + fromChild: (data: unknown) => onMessage({ source: childWin, data }), + fromParent: (data: unknown) => onMessage({ source: parentWin, data }), + fromOther: (data: unknown) => onMessage({ source: {}, data }), + jump: (ms: number) => { now += ms; }, + now: () => now, + }; +} + +const TOKEN = "a".repeat(64); +const BACK = "http://127.0.0.1:5000/_magpie/plugin/abc123/page/index.html?x=1"; +const hash = (o: Record) => "#" + new URLSearchParams(o).toString(); + +describe("gate /app", () => { + it("serves the wrapper with a fresh nonce CSP; Host and Origin checks still apply; no secrets in it", async () => { + const { createGate } = await import(/* @vite-ignore */ gateUrl); + const port = await freePort(); + const key = "c".repeat(64); + const gate = createGate({ port, key, token: TOKEN, ensureDaemon: async () => ({ port: 4999 }) }); + await gate.listen(); + try { + const a = await request(port, "/app"); + const b = await request(port, "/app?theme=dark"); + expect(a.status).toBe(200); + expect(a.headers["content-type"]).toContain("text/html"); + const csp = String(a.headers["content-security-policy"]); + expect(csp).toMatch(/script-src 'nonce-[A-Za-z0-9+/=]+'/); + expect(csp).toContain("default-src 'none'"); + expect(csp).toContain("frame-src http://127.0.0.1:*"); + // only loopback pages and Magpie's own window (wails://localhost, http://wails.localhost) may frame /app + expect(csp).toContain("frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:"); + expect(csp).not.toMatch(/frame-ancestors[^;]*\s(\*|https:|http:)(\s|;|$)/); // never "any site" + expect(csp).not.toBe(String(b.headers["content-security-policy"])); + expect(a.headers["cache-control"]).toBe("no-store"); + expect(a.body).not.toContain(TOKEN); + expect(a.body).not.toContain(key); + expect((await request(port, "/app", { host: `evil.example:${port}` })).status).toBe(421); + expect((await request(port, "/app", { origin: "null" })).status).toBe(403); + // ac_try is forwarded to the wrapper only in its exact shape + const ok = await request(port, `/open?k=${key}&ac_try=1800000000000.2`); + expect(new URL(String(ok.headers.location)).searchParams.get("ac_try")).toBe("1800000000000.2"); + const bad = await request(port, `/open?k=${key}&ac_try=${encodeURIComponent("1.2