#!/usr/bin/env node "use strict"; const assert = require("node:assert"); const fs = require("node:fs"); const os = require("node:os"); const path = require("node:path"); const { chromium } = require("playwright"); const { BASE_URL, UI_TIMEOUT_MS, ensureAuthenticated, } = require("./tree-shell-smoke-helpers"); const TASK = "task502-page-ai-agent-selector-context-smoke"; const OUTPUT_DIR = path.join(process.cwd(), "tmp", TASK); const RESULT_PATH = path.join(OUTPUT_DIR, "result.json"); const CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH || ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium"] .find((candidate) => fs.existsSync(candidate)); function fileUrl(localPath) { return `file://${localPath}`; } function localMdDocumentId(relativePath) { return `local-md:${relativePath.replaceAll("/", "~2F")}`; } function writeWorkspaceManifest(root, ownerId, workspaceId) { fs.mkdirSync(path.join(root, ".mnote"), { recursive: true }); fs.writeFileSync( path.join(root, ".mnote", "workspace.json"), `${JSON.stringify({ workspaceId, ownerId, createdAt: new Date().toISOString(), capabilities: ["local_files", "ai_sessions", "markdown_edit"], }, null, 2)}\n`, "utf8", ); } function documentUrl(root, relativePath) { const url = new URL(`${BASE_URL}/documents/${encodeURIComponent(localMdDocumentId(relativePath))}`); url.searchParams.set("sourceKind", "local_folder"); url.searchParams.set("rootUri", fileUrl(root)); url.searchParams.set("treeView", "filetree"); return url.toString(); } async function saveScreenshot(page, name) { const target = path.join(OUTPUT_DIR, `${name}.png`); await page.screenshot({ path: target, fullPage: false }); return target; } async function main() { fs.mkdirSync(OUTPUT_DIR, { recursive: true }); const suffix = Date.now().toString(36); const actorId = "mnote-e2e"; const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task502-agent-context-")); const rootUri = fileUrl(root); const workspaceId = `local-ws:${actorId}:task502`; const relativePath = "AgentContext.md"; const documentId = localMdDocumentId(relativePath); const captured = []; let caughtError = null; writeWorkspaceManifest(root, actorId, workspaceId); fs.writeFileSync( path.join(root, relativePath), ["# Agent Context", "", `Task502 ${suffix}`, ""].join("\n"), "utf8", ); const browser = await chromium.launch({ headless: true, ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}), }); const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, locale: "zh-CN", extraHTTPHeaders: { "x-mnote-actor-id": actorId, "x-mnote-actor-type": "user", }, }); const page = await context.newPage(); try { await page.route("**/api/user/access-policy**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, controlPlane: "sqlite", grants: [{ id: `grant_task502_${suffix}`, userId: actorId, workspaceId, rootUri, rootPath: root, permission: "write", recursive: true, capabilities: ["ai", "markdown_edit"], source: "user", status: "active", }], }), }); }); await page.route("**/api/ui/preferences**", async (route) => { captured.push({ kind: "ui-preferences", method: route.request().method(), body: route.request().postData() || "", }); await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, owner: "mnote-web", result: {} }), }); }); await page.route("**/api/hermes/client/gateway/health**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, gateway: { ok: true, status: "mocked" }, profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true }, suggestions: [], }), }); }); await page.route("**/api/hermes/client/tools**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, tools: [] }), }); }); await page.route("**/api/hermes/client/profiles", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, active: "reasonix", profiles: [{ name: "reasonix", label: "Reasonix", modelConfigured: true, apiKeyConfigured: true }], }), }); }); await page.route("**/api/hermes/client/skills**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, categories: [], archived: [] }), }); }); await page.route("**/api/hermes/client/sessions", async (route) => { captured.push({ kind: "session", method: route.request().method(), body: route.request().postData() || "" }); await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, sessionId: `mnote_task502_${suffix}`, title: "task502", traceId: `trace_task502_session_${suffix}`, persistence: "local_ai_session_jsonl", sessionStorage: "local_private", }), }); }); await page.route("**/api/hermes/client/runs", async (route) => { captured.push({ kind: "run", method: route.request().method(), body: route.request().postData() || "" }); await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, sessionId: `mnote_task502_${suffix}`, runId: `run_task502_${suffix}`, events: [], traceId: `trace_task502_run_${suffix}`, }), }); }); await page.route("**/api/hermes/client/events/*", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "text/event-stream; charset=utf-8" }, body: `data: ${JSON.stringify({ event: "message.delta", run_id: `run_task502_${suffix}`, delta: "Task502 response" })}\n\n` + `data: ${JSON.stringify({ event: "run.completed", run_id: `run_task502_${suffix}`, output: "Task502 response" })}\n\n`, }); }); await ensureAuthenticated(page, context.request); const response = await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS, }); assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`); await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }); await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-testid="wolai-page-ai-drawer"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const drawer = page.locator('[data-testid="wolai-page-ai-drawer"]'); const defaultChatText = await drawer.innerText({ timeout: UI_TIMEOUT_MS }); assert(!defaultChatText.includes("问 Hermes"), "默认输入区不应继续固定写“问 Hermes”"); assert(!defaultChatText.includes("model.default"), "默认聊天面不应显示 model.default"); assert(!defaultChatText.includes("gateway:"), "默认聊天面不应显示 gateway 技术详情"); assert(!defaultChatText.includes("Hermes profile"), "默认聊天面不应显示 Hermes profile 技术项"); await page.locator("[data-page-ai-agent-selector]").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const agentIds = await page.$$eval("[data-page-ai-agent-id]", (nodes) => nodes.map((node) => node.getAttribute("data-page-ai-agent-id")).filter(Boolean), ); assert.deepStrictEqual(agentIds.sort(), ["chat_only", "hermes", "reasonix"]); await page.locator('[data-page-ai-agent-id="reasonix"]').click({ timeout: UI_TIMEOUT_MS }); await page.waitForFunction( () => document.documentElement.getAttribute("data-mnote-page-ai-agent-id") === "reasonix", null, { timeout: UI_TIMEOUT_MS }, ); const contextRefs = page.locator("[data-page-ai-context-refs]"); await contextRefs.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); assert( await page.locator('[data-page-ai-context-ref="current_page"][aria-pressed="true"]').isVisible(), "当前页 contextRef 应默认勾选", ); assert( await page.locator("[data-page-ai-allowed-root]").first().isVisible(), "SQLite 授权区域应作为 allowedRoot chip 显示", ); await page.locator('.wolai-page-ai-header-actions [data-page-ai-tab="agent"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-panel="agent"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const commonSettingsText = await page.locator('[data-page-ai-panel="agent"]').innerText({ timeout: UI_TIMEOUT_MS }); assert(commonSettingsText.includes("授权区域"), "Common 设置页应展示授权区域"); assert(commonSettingsText.includes("默认上下文"), "Common 设置页应展示默认 contextRefs"); assert(commonSettingsText.includes("审计"), "Common 设置页应展示审计/changed files 共性设置"); assert(!commonSettingsText.includes("Hermes profile"), "Common 设置页不应包含 Hermes profile"); assert(!commonSettingsText.includes("ACP runtime"), "Common 设置页不应包含 agent runtime 差异项"); await page.locator('[data-page-ai-panel="agent"] [data-page-ai-tab="hermes-settings"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-panel="hermes-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const hermesSettingsText = await page.locator('[data-page-ai-panel="hermes-settings"]').innerText({ timeout: UI_TIMEOUT_MS }); assert(hermesSettingsText.includes("Hermes profile"), "Hermes 设置页应只承接 Hermes profile"); assert(!hermesSettingsText.includes("Reasonix 专属设置"), "Hermes 设置页不应混入 Reasonix 设置"); await page.locator('[data-page-ai-panel="hermes-settings"] [data-page-ai-tab="reasonix-settings"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-panel="reasonix-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const reasonixSettingsText = await page.locator('[data-page-ai-panel="reasonix-settings"]').innerText({ timeout: UI_TIMEOUT_MS }); assert(reasonixSettingsText.includes("ACP runtime"), "Reasonix 设置页应展示 ACP runtime"); assert(reasonixSettingsText.includes("Reasonix 专属设置"), "Reasonix 设置页应展示 Reasonix 专属设置"); assert(!reasonixSettingsText.includes("Hermes profile"), "Reasonix 设置页不应混入 Hermes profile"); await page.locator('[data-page-ai-panel="reasonix-settings"] [data-page-ai-tab="chat-only-settings"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-panel="chat-only-settings"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const chatOnlySettingsText = await page.locator('[data-page-ai-panel="chat-only-settings"]').innerText({ timeout: UI_TIMEOUT_MS }); assert(chatOnlySettingsText.includes("默认不申请文件写权限"), "Chat-only 设置页应说明默认不申请写权限"); assert(!chatOnlySettingsText.includes("ACP runtime"), "Chat-only 设置页不应混入 ACP runtime"); await page.locator('[data-page-ai-panel="chat-only-settings"] [data-page-ai-tab="chat"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-panel="chat"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-context-ref="current_page"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-context-ref="folder"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-context-ref="changed_files"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator("[data-page-ai-input]").fill(`Task502 agent/context ${suffix}`, { timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS }); await page.waitForFunction( () => (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("Task502 response"), null, { timeout: UI_TIMEOUT_MS }, ); const runs = captured.filter((item) => item.kind === "run"); assert(runs.length >= 1, "未捕获 Page AI run payload"); const runBody = JSON.parse(runs[runs.length - 1].body); assert.strictEqual(runBody.agentId, "reasonix"); assert(Array.isArray(runBody.contextRefs), "run payload 必须包含 contextRefs 数组"); assert(!runBody.contextRefs.some((item) => item.kind === "current_page"), "取消当前页后不应发送 current_page contextRef"); assert.strictEqual(runBody.pageContext?.aiContext?.pageText, undefined, "取消当前页后不应发送 pageText"); assert.strictEqual(runBody.pageContext?.aiContext?.pageXml, undefined, "取消当前页后不应发送 pageXml"); assert.strictEqual(runBody.pageContext?.aiContext?.contextBlocks, undefined, "取消当前页后不应发送 contextBlocks"); assert(runBody.contextRefs.some((item) => item.kind === "active_editor" && item.documentId === documentId)); assert(runBody.contextRefs.some((item) => item.kind === "folder" && item.rootUri === rootUri)); assert(runBody.contextRefs.some((item) => item.kind === "changed_files")); assert(Array.isArray(runBody.allowedRoots), "run payload 必须包含 allowedRoots 数组"); assert(runBody.allowedRoots.some((item) => item.rootUri === rootUri && item.permission === "write" && item.source === "sqlite_directory_grant" )); assert.strictEqual(runBody.runTargetSnapshot?.source, "open_editors_snapshot"); const screenshot = await saveScreenshot(page, "01-agent-selector-context"); const result = { ok: true, task: TASK, baseUrl: BASE_URL, root, rootUri, documentId, screenshot, captured, }; fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8"); console.log(JSON.stringify(result, null, 2)); } catch (error) { caughtError = error; await saveScreenshot(page, "failure").catch(() => undefined); } finally { fs.rmSync(root, { recursive: true, force: true }); await page.close().catch(() => undefined); await context.close().catch(() => undefined); await browser.close().catch(() => undefined); } if (caughtError) { throw caughtError; } } if (require.main === module) { main().catch((error) => { console.error(error); process.exit(1); }); }