#!/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 = "task537-page-ai-local-agent-readonly-write-guard-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 waitForEditorText(page, expected) { await page.waitForFunction( (text) => { const editor = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror'); return (editor?.textContent || "").includes(text); }, expected, { timeout: UI_TIMEOUT_MS }, ); } async function main() { fs.mkdirSync(OUTPUT_DIR, { recursive: true }); const suffix = Date.now().toString(36); const actorId = "mnote-e2e"; const workspaceId = `local-ws:${actorId}:task537`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task537-readonly-")); const rootUri = fileUrl(root); const relativePath = "ReadonlyGuard.md"; const documentId = localMdDocumentId(relativePath); const filePath = path.join(root, relativePath); const initialToken = `task537-initial-${suffix}`; const forbiddenToken = `task537-forbidden-${suffix}`; const captured = []; const blockedRequests = []; let caughtError = null; writeWorkspaceManifest(root, actorId, workspaceId); fs.writeFileSync( filePath, ["# Readonly Guard", "", initialToken, ""].join("\n"), "utf8", ); const originalDiskContent = fs.readFileSync(filePath, "utf8"); const browser = await chromium.launch({ headless: process.env.HEADFUL !== "1", ...(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(); page.on("request", (request) => { const url = request.url(); if (url.includes("/api/documents/save") || url.includes("/api/page-body/write")) { blockedRequests.push({ url, method: request.method(), body: request.postData() || "" }); } }); 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_task537_${suffix}`, userId: actorId, workspaceId, rootUri, rootPath: root, permission: "read", recursive: true, capabilities: ["ai"], source: "user", status: "active", }], }), }); }); await page.route("**/api/ui/preferences**", async (route) => { 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 }, profile: { name: "reasonix", modelConfigured: true, apiKeyConfigured: true } }), }); }); 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/ai/agent-profiles**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, agentId: "reasonix", profiles: [] }) }); }); 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: "mnoteai", profiles: [{ name: "mnoteai", label: "MNote AI", 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/capabilities**", async (route) => { await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, runtime: "mnote", 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_task537_${suffix}`, title: "task537", traceId: `trace_task537_session_${suffix}` }), }); }); 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: 500, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: false, code: "task537_runs_should_not_be_called" }), }); }); 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 waitForEditorText(page, initialToken); 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 }); await page.locator("[data-page-ai-input]").fill(`请新增 ${forbiddenToken}`, { timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS }); await page.waitForFunction( () => document.documentElement.getAttribute("data-mnote-page-ai-run-status") === "failed" && (document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || "").includes("只读授权"), null, { timeout: UI_TIMEOUT_MS }, ); const runs = captured.filter((item) => item.kind === "run"); const blockedBeforeRun = runs.length === 0; assert(blockedBeforeRun, `只读写入应在 /runs 前被拦截,实际捕获 ${runs.length} 次 run`); assert.strictEqual(blockedRequests.length, 0, `只读写入不应调用页面写入接口: ${JSON.stringify(blockedRequests)}`); const finalDiskContent = fs.readFileSync(filePath, "utf8"); const diskChanged = finalDiskContent !== originalDiskContent; assert(!diskChanged, "只读 guard 后磁盘内容必须保持不变"); assert(!finalDiskContent.includes(forbiddenToken), "只读 guard 后磁盘不应包含 forbidden token"); const screenshot = await saveScreenshot(page, "01-readonly-guard"); const result = { ok: true, task: TASK, baseUrl: BASE_URL, root, rootUri, documentId, relativePath, forbiddenToken, screenshot, captured, blockedRequests, blockedBeforeRun, diskChanged, finalDiskContent, }; 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 { 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); }); }