#!/usr/bin/env node "use strict"; const assert = require("node:assert/strict"); const fs = require("node:fs"); const http = require("node:http"); const net = require("node:net"); const os = require("node:os"); const path = require("node:path"); const { spawn } = require("node:child_process"); const { chromium } = require("playwright"); const { buildControlPlaneTestEnv } = require("./lib/control-plane-test-env"); const TASK = "task492-sidebar-starred-shortcuts-smoke"; const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000); const TEST_PASSWORD = process.env.MNOTE_E2E_PASSWORD || ["Mnote", "E2E", "123!"].join(""); function resolveChromiumExecutablePath() { const explicit = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH || ""; if (explicit && fs.existsSync(explicit)) return explicit; return [ "/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/bin/chromium", "/usr/bin/chromium", "/usr/bin/chromium-browser", ].find((candidate) => fs.existsSync(candidate)) || ""; } function pickPort() { return new Promise((resolve, reject) => { const server = net.createServer(); server.listen(0, "127.0.0.1", () => { const address = server.address(); const port = address && typeof address === "object" ? address.port : 0; server.close(() => resolve(port)); }); server.on("error", reject); }); } function waitForHttpOk(url, timeoutMs) { const deadline = Date.now() + timeoutMs; return new Promise((resolve, reject) => { const tick = () => { const request = http.get(url, (response) => { response.resume(); if (response.statusCode >= 200 && response.statusCode < 500) { resolve(); return; } retry(); }); request.on("error", retry); request.setTimeout(1000, () => { request.destroy(); retry(); }); }; const retry = () => { if (Date.now() > deadline) { reject(new Error(`server_not_ready: ${url}`)); return; } setTimeout(tick, 250); }; tick(); }); } function fileUrlToPath(value) { const url = new URL(value); return decodeURIComponent(url.pathname); } async function main() { const port = await pickPort(); const baseUrl = `http://127.0.0.1:${port}`; const dataRoot = fs.mkdtempSync(path.join(os.tmpdir(), `${TASK}-`)); const controlPlaneEnv = buildControlPlaneTestEnv(dataRoot, process.env); const actorId = `${TASK}-${process.pid}-${Date.now()}`; const server = spawn("cargo", ["run", "-p", "mnote-web", "--bin", "mnote-web"], { cwd: path.join(__dirname, "..", "rust"), env: { ...process.env, MNOTE_WEB_BIND: `127.0.0.1:${port}`, MNOTE_WEB_PUBLIC_BIND: `127.0.0.1:${port}`, ...controlPlaneEnv, MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot, }, stdio: ["ignore", "pipe", "pipe"], }); let stderr = ""; server.stderr.on("data", (chunk) => { stderr += chunk.toString(); }); const executablePath = resolveChromiumExecutablePath(); const browser = await chromium.launch({ headless: true, ...(executablePath ? { executablePath } : {}), }); const context = await browser.newContext(); const page = await context.newPage(); const browserDiagnostics = []; let holdStarredSidebarProjection = false; let releaseStarredSidebarProjection = null; let starredSidebarProjectionCompleted = false; let scopedFileProjectionStartedAt = 0; let scopedFileProjectionCompletedAt = 0; await page.route("**/api/tree/projections/sidebar**", async (route) => { const url = new URL(route.request().url()); if (holdStarredSidebarProjection && url.searchParams.get("sourceKind") === "local_folder") { await new Promise((resolve) => { releaseStarredSidebarProjection = resolve; }); starredSidebarProjectionCompleted = true; } await route.continue(); }); await page.route("**/api/tree/projections/file**", async (route) => { const url = new URL(route.request().url()); if ( holdStarredSidebarProjection && url.pathname.endsWith("/api/tree/projections/file") && url.searchParams.get("parentRelativePath") === "design" ) { scopedFileProjectionStartedAt = scopedFileProjectionStartedAt || Date.now(); await route.continue(); scopedFileProjectionCompletedAt = Date.now(); return; } await route.continue(); }); page.on("console", (message) => { browserDiagnostics.push(`console:${message.type()}:${message.text()}`); }); page.on("pageerror", (error) => { browserDiagnostics.push(`pageerror:${error.message}`); }); page.on("request", (request) => { const url = request.url(); if (url.includes("/api/tree/projections/file")) { browserDiagnostics.push(`request:${url}`); } }); try { await waitForHttpOk(`${baseUrl}/health`, 60_000); const authResponse = await context.request.fetch(`${baseUrl}/api/auth`, { method: "POST", data: { action: "auth:signIn", args: { provider: "password", params: { email: `${actorId}@example.com`, username: actorId, name: actorId, password: TEST_PASSWORD, flow: "signUp", }, }, }, }); assert(authResponse.ok(), `测试账号注册失败: ${authResponse.status()} ${await authResponse.text()}`); await page.goto(baseUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); const createButton = page.locator('[data-testid="mnote-create-default-local-workspace"]').first(); if (await createButton.isVisible({ timeout: 3000 }).catch(() => false)) { await createButton.click({ timeout: UI_TIMEOUT_MS }); await page.waitForURL((url) => url.searchParams.get("sourceKind") === "local_folder", { timeout: UI_TIMEOUT_MS, }); } const rootUri = new URL(page.url()).searchParams.get("rootUri") || await page.evaluate(() => document.body.getAttribute("data-mnote-root-uri") || ""); assert(rootUri, "应进入 local_folder workspace"); const rootPath = fileUrlToPath(rootUri); fs.mkdirSync(path.join(rootPath, "design"), { recursive: true }); fs.mkdirSync(path.join(rootPath, "other"), { recursive: true }); fs.writeFileSync(path.join(rootPath, "Home.md"), "# Home\n", "utf8"); fs.writeFileSync(path.join(rootPath, "design", "Brief.md"), "# Brief\n", "utf8"); fs.writeFileSync(path.join(rootPath, "other", "Other.md"), "# Other\n", "utf8"); const activeDocumentId = "local-md:Home.md"; const url = new URL(page.url()); url.pathname = `/documents/${encodeURIComponent(activeDocumentId)}`; url.searchParams.set("sourceKind", "local_folder"); url.searchParams.set("rootUri", rootUri); url.searchParams.set("treeView", "filetree"); await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator("#sidebar-file-tree-root").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); assert.equal(await page.locator('[data-testid="wolai-public-state"]').isVisible(), false, "未公开页面不应显示全网公开"); await page.locator('[data-mnote-action="toggle-sidebar-shortcut"][data-mnote-shortcut-kind="page"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="page"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }).catch(async (error) => { const debug = await page.evaluate(() => ({ href: location.href, action: document.documentElement.getAttribute("data-mnote-sidebar-shortcut-last-action"), workspaceId: document.getElementById("sidebar-file-tree-root")?.getAttribute("data-workspace-id") || "", rootUri: document.body.getAttribute("data-mnote-root-uri") || "", topbar: document.querySelector(".wolai-topbar-actions")?.innerHTML || "", })); throw new Error(`${error.message}; debug=${JSON.stringify(debug)}; browser=${browserDiagnostics.slice(-8).join(" | ")}`); }); const designRow = page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design"]').first(); await designRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); await designRow.click({ button: "right", timeout: UI_TIMEOUT_MS }); await page.getByText("加入/取消星标置顶").click({ timeout: UI_TIMEOUT_MS }); const designShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first(); await designShortcut.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS }); const cloudSpaceUrl = new URL(baseUrl); cloudSpaceUrl.searchParams.set("workspaceId", "default"); await page.goto(cloudSpaceUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS }); const cloudDesignShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first(); await cloudDesignShortcut.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }); assert.equal( await cloudDesignShortcut.getAttribute("data-mnote-shortcut-root-uri"), rootUri, "回到我的空间后,本地文件夹星标应携带自己的 rootUri", ); await page.evaluate(() => { const panel = document.querySelector("#wolai-sidebar-page-tree-panel, [data-mnote-sidebar-tree-panel='page']"); let root = document.querySelector("#sidebar-tree-root"); if (!(root instanceof HTMLElement) && panel instanceof HTMLElement) { root = document.createElement("div"); root.id = "sidebar-tree-root"; root.className = "sidebar-tree"; root.setAttribute("data-tree-shell-mode", "page"); panel.appendChild(root); } if (!(root instanceof HTMLElement)) throw new Error("无法注入旧页面树 root"); root.innerHTML = [ '