#!/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 = "task525-page-ai-mindmap-resource-target-smoke"; const OUT_DIR = path.join(process.cwd(), "tmp", TASK); const RESULT_PATH = path.join(OUT_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 waitFiletreeRow(page, relativePath) { await page.waitForFunction( (expectedRelativePath) => Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]")) .some((row) => row.getAttribute("data-local-relative-path") === expectedRelativePath), relativePath, { timeout: UI_TIMEOUT_MS }, ); } async function clickFiletreeOpen(page, relativePath) { const handle = await page.waitForFunction( (expectedRelativePath) => { const row = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]")) .find((candidate) => candidate.getAttribute("data-local-relative-path") === expectedRelativePath); return row?.querySelector('[data-rust-action="open"], .tree-link') || null; }, relativePath, { timeout: UI_TIMEOUT_MS }, ); await handle.asElement().click(); } async function expandFiletreeFolder(page, relativePath) { await waitFiletreeRow(page, relativePath); const expanded = await page.evaluate((expectedRelativePath) => { const row = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]")) .find((candidate) => candidate.getAttribute("data-local-relative-path") === expectedRelativePath); return row?.getAttribute("aria-expanded") === "true"; }, relativePath); if (!expanded) { await clickFiletreeOpen(page, relativePath); } await page.waitForFunction( (expectedRelativePath) => { const row = Array.from(document.querySelectorAll("#sidebar-file-tree-root .tree-row[data-shell-mode=\"filetree\"]")) .find((candidate) => candidate.getAttribute("data-local-relative-path") === expectedRelativePath); return row?.getAttribute("aria-expanded") === "true"; }, relativePath, { timeout: UI_TIMEOUT_MS }, ); } async function saveScreenshot(page, name) { const target = path.join(OUT_DIR, `${name}.png`); await page.screenshot({ path: target, fullPage: false }); return target; } async function main() { fs.mkdirSync(OUT_DIR, { recursive: true }); const actorId = "mnote-e2e"; const workspaceId = `local-ws:${actorId}:task525`; const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task525-mindmap-target-")); const rootUri = fileUrl(root); const pagePath = "Page/Page.md"; const mindmapPath = "Page/map.mindmap.json"; const documentId = localMdDocumentId(pagePath); const assetId = `local-file:${mindmapPath}`; const expectedTargetId = `resource:mindmap:${documentId}:${assetId}`; const captured = []; let caughtError = null; fs.mkdirSync(path.join(root, "Page"), { recursive: true }); writeWorkspaceManifest(root, actorId, workspaceId); fs.writeFileSync(path.join(root, pagePath), "# Page\n\n[思维导图](map.mindmap.json)\n", "utf8"); fs.writeFileSync( path.join(root, mindmapPath), `${JSON.stringify({ data: { text: "Task525 mindmap" }, children: [] }, null, 2)}\n`, "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(); 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, grants: [{ id: "grant_task525", 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 }, 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_task525", title: "task525", traceId: "trace_task525" }), }); }); 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_task525", runId: "run_task525", events: [], traceId: "trace_run_task525" }), }); }); 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_task525", delta: "Task525 response" })}\n\n` + `data: ${JSON.stringify({ event: "run.completed", run_id: "run_task525", output: "Task525 response" })}\n\n`, }); }); await ensureAuthenticated(page, context.request); const response = await page.goto(documentUrl(root, pagePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`); await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }); await expandFiletreeFolder(page, "Page"); await waitFiletreeRow(page, mindmapPath); await clickFiletreeOpen(page, mindmapPath); await page.waitForFunction( () => { return Boolean(document.querySelector('[data-testid="mnote-mindmap-editor-root"]')) && (document.body?.innerText || "").includes("map.mindmap.json"); }, null, { 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 targetChip = page.locator("[data-page-ai-target-chip]"); await targetChip.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const chipText = (await targetChip.innerText({ timeout: UI_TIMEOUT_MS })).trim(); assert(chipText.includes("map.mindmap.json"), `mindmap resource 打开后 target chip 应指向 map.mindmap.json: ${chipText}`); await page.locator("[data-page-ai-input]").fill("Task525 mindmap target", { 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("Task525 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 || "{}"); const activeEditorRef = runBody.contextRefs?.find((item) => item.kind === "active_editor"); assert(activeEditorRef, `run payload 应包含 active_editor contextRef: ${JSON.stringify(runBody.contextRefs)}`); assert.strictEqual(activeEditorRef.resourceKind, "mindmap", `active_editor 应标记 mindmap resourceKind: ${JSON.stringify(activeEditorRef)}`); assert.strictEqual(activeEditorRef.assetId, assetId, `active_editor 应携带 mindmap assetId: ${JSON.stringify(activeEditorRef)}`); assert.strictEqual(activeEditorRef.objectIdentity, expectedTargetId, `active_editor objectIdentity 不应退化: ${JSON.stringify(activeEditorRef)}`); assert.strictEqual(activeEditorRef.relativePath, mindmapPath, `active_editor 应携带 mindmap relativePath: ${JSON.stringify(activeEditorRef)}`); assert.strictEqual(runBody.targetPackage?.schema, "mnote.agent_target_package.v1", "run payload 应携带 targetPackage"); assert.strictEqual(runBody.targetPackage?.primaryTargetId, expectedTargetId, `targetPackage 应冻结 mindmap target: ${JSON.stringify(runBody.targetPackage)}`); assert.strictEqual(runBody.targetPackage?.objectIdentity, expectedTargetId, `targetPackage objectIdentity 不应退化: ${JSON.stringify(runBody.targetPackage)}`); assert.strictEqual(runBody.targetPackage?.resourceKind, "mindmap", `targetPackage 应保留 mindmap resourceKind: ${JSON.stringify(runBody.targetPackage)}`); assert.strictEqual(runBody.targetPackage?.currentFile?.relativePath, mindmapPath, `targetPackage currentFile 应指向 mindmap resource: ${JSON.stringify(runBody.targetPackage)}`); assert.strictEqual(runBody.targetPackage?.currentFile?.objectIdentity, expectedTargetId, `currentFile objectIdentity 不应退化: ${JSON.stringify(runBody.targetPackage?.currentFile)}`); assert(runBody.targetPackage?.allowedFiles?.includes(mindmapPath), `allowedFiles 应包含 mindmap resource: ${JSON.stringify(runBody.targetPackage?.allowedFiles)}`); const screenshot = await saveScreenshot(page, "01-mindmap-resource-target"); const result = { ok: true, task: TASK, baseUrl: BASE_URL, root, rootUri, documentId, mindmapPath, assetId, expectedTargetId, 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); }); }