#!/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, } = require("./tree-shell-smoke-helpers"); 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 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", ); } async function main() { const suffix = Date.now().toString(36); const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-local-ai-changed-files-")); const documentId = "local-md:README.md"; const actorId = "user_real"; const sessionId = `mnote_local_ai_changed_${suffix}`; const runId = `run_local_ai_changed_${suffix}`; const marker = `LOCAL-AI-CHANGED-FILES-${suffix}`; const readmePath = path.join(root, "README.md"); const captured = []; const browser = await chromium.launch({ headless: true, ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}), }); const context = await browser.newContext({ viewport: { width: 1440, height: 960 }, extraHTTPHeaders: { "x-mnote-actor-id": actorId, "x-mnote-actor-type": "user", }, }); const page = await context.newPage(); try { const workspaceId = `local-ws:${actorId}:task453`; writeWorkspaceManifest(root, actorId, workspaceId); fs.writeFileSync(readmePath, `# Local AI Changed Files\n初始内容 ${suffix}\n`, "utf8"); const rootUri = fileUrl(root); await page.route("**/api/ai-agent/run", async (route) => { throw new Error(`页面 AI 不应请求旧 /api/ai-agent/run: ${route.request().url()}`); }); 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/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, title: "本地 changed files", traceId: `trace_local_changed_${suffix}`, persistence: "local_ai_session_jsonl", sessionStorage: "local_private", }), }); }); await page.route(`**/api/hermes/client/sessions/${sessionId}/resume`, async (route) => { captured.push({ kind: "session-resume", method: route.request().method(), body: "" }); await route.fulfill({ status: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, sessionId, session: { sessionId, messages: [] }, runtime: { sessionId, runId, status: "completed", profile: "reasonix", documentId, traceId: `trace_local_changed_resume_${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: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true, sessionId, runId, events: [], traceId: `trace_local_changed_run_${suffix}`, persistence: "local_ai_session_jsonl", sessionStorage: "local_private", }), }); }); await page.route(`**/api/hermes/client/events/${runId}`, async (route) => { captured.push({ kind: "events", method: route.request().method(), body: "" }); fs.appendFileSync(readmePath, `\nAI 写入标记:${marker}\n`, "utf8"); await route.fulfill({ status: 200, headers: { "content-type": "text/event-stream; charset=utf-8" }, body: `data: ${JSON.stringify({ event: "message.delta", run_id: runId, session_id: sessionId, delta: "已修改本地 README。" })}\n\n` + `data: ${JSON.stringify({ event: "run.completed", run_id: runId, session_id: sessionId, output: "已修改本地 README。", agentAudit: { eventId: `audit_local_changed_${suffix}`, rootUri, diffSummary: "1 changed file(s)", changedFiles: [ { path: "README.md", changeType: "modified", summary: `追加 ${marker}`, }, ], }, })}\n\n`, }); }); const documentUrl = new URL(`${BASE_URL}/documents/${encodeURIComponent(documentId)}`); documentUrl.searchParams.set("sourceKind", "local_folder"); documentUrl.searchParams.set("rootUri", rootUri); await page.goto(documentUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); await page.waitForFunction( () => (document.body.textContent || "").includes("Local AI Changed Files"), null, { timeout: UI_TIMEOUT_MS }, ); await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({ state: "attached", timeout: UI_TIMEOUT_MS, }).catch(() => undefined); await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS }); await page.locator("[data-page-ai-input]").fill(`请修改 README 并记录 changed files ${marker}`, { timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS }); await page.waitForFunction( () => { const drawerText = document.querySelector('[data-testid="wolai-page-ai-drawer"]')?.textContent || ""; return drawerText.includes("agent.changed_files") && drawerText.includes("README.md"); }, null, { timeout: UI_TIMEOUT_MS }, ); const cards = await page.$$eval("[data-page-ai-tool-card]", (nodes) => nodes.map((node) => ({ status: node.getAttribute("data-page-ai-tool-status"), text: node.textContent || "", })), ); assert( cards.some((card) => card.status === "completed" && card.text.includes("agent.changed_files") && card.text.includes("README.md") && card.text.includes(marker) ), `本地 AI changed files 工具卡未显示 README.md 与 diff 摘要: ${JSON.stringify(cards)}`, ); assert(fs.readFileSync(readmePath, "utf8").includes(marker), "本地 README.md 未写入 smoke 标记"); assert(captured.some((entry) => entry.kind === "run"), "未捕获 page AI run 请求"); console.log( JSON.stringify({ ok: true, root, documentId, sessionId, runId, marker, capturedKinds: captured.map((entry) => entry.kind), }, null, 2), ); } finally { await context.close().catch(() => undefined); await browser.close().catch(() => undefined); fs.rmSync(root, { recursive: true, force: true }); } } main().catch((error) => { console.error(error instanceof Error ? error.stack || error.message : String(error)); process.exit(1); });