#!/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 = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, ""); const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000); const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task452-local-search-index-browser-smoke"); 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 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)); return url.toString(); } function writeWorkspaceManifest(root, ownerId) { const metadataDir = path.join(root, ".mnote"); fs.mkdirSync(metadataDir, { recursive: true }); fs.writeFileSync( path.join(metadataDir, "workspace.json"), `${JSON.stringify({ workspaceId: `local-ws:${ownerId}:task452`, ownerId, createdAt: new Date().toISOString(), capabilities: ["local_files", "search"], }, null, 2)}\n`, "utf8", ); } async function browserSearch(page, root, query) { return page.evaluate(async ({ rootUri, queryText }) => { const response = await fetch("/api/search/documents", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ workspaceId: "local-ws:user_real:task452", sourceKind: "local_folder", rootUri, query: queryText, limit: 10, }), }); const payload = await response.json(); return { status: response.status, payload, }; }, { rootUri: fileUrl(root), queryText: query }); } async function run() { fs.mkdirSync(OUTPUT_DIR, { recursive: true }); const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-local-search-smoke-")); const debug = { root, baseUrl: BASE_URL }; writeWorkspaceManifest(root, "user_real"); fs.mkdirSync(path.join(root, "docs"), { recursive: true }); const token = `LOCAL-SEARCH-${Date.now()}`; const firstRelativePath = "docs/search-target.md"; const renamedRelativePath = "docs/search-renamed.md"; fs.writeFileSync( path.join(root, "README.md"), `---\ntitle: Search Smoke\ntags: [alpha]\n---\n# Search Smoke\n打开搜索 smoke。\n[Target](docs/search-target.md)\n`, "utf8", ); const browser = await chromium.launch({ headless: true, ...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}), }); const context = await browser.newContext({ viewport: { width: 1280, height: 860 }, extraHTTPHeaders: { "x-mnote-actor-id": "user_real", "x-mnote-actor-type": "user", }, }); const page = await context.newPage(); try { await page.goto(documentUrl(root, "README.md"), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS, }); await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }); fs.writeFileSync( path.join(root, firstRelativePath), `---\ntitle: Search Target\ntags: [alpha, beta]\n---\n# Search Target\n${token}\n`, "utf8", ); const first = await browserSearch(page, root, token); assert.equal(first.status, 200, `初次搜索应成功: ${JSON.stringify(first)}`); debug.first = first.payload; const firstResults = Array.isArray(first.payload.results) ? first.payload.results : []; assert( firstResults.some((item) => item.path === firstRelativePath && item.documentId === localMdDocumentId(firstRelativePath)), `新建页面应立即可搜索: ${JSON.stringify(firstResults)}`, ); await page.goto(documentUrl(root, firstRelativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS, }); await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({ state: "visible", timeout: UI_TIMEOUT_MS, }); await page.locator('[data-testid="wolai-page-settings-trigger"]').click({ timeout: UI_TIMEOUT_MS }); await page.locator('[data-page-settings-tab="index"]').click({ timeout: UI_TIMEOUT_MS }); await page.waitForFunction(() => { const backlinks = document.querySelector('[data-testid="wolai-page-settings-local-index-backlinks"]'); const tags = document.querySelector('[data-testid="wolai-page-settings-local-index-tags"]'); return Boolean( backlinks && backlinks.textContent && backlinks.textContent.includes("Search Smoke") && tags && tags.textContent && tags.textContent.includes("#alpha"), ); }, null, { timeout: UI_TIMEOUT_MS }); debug.localIndexPanel = await page.evaluate(() => ({ backlinks: document.querySelector('[data-testid="wolai-page-settings-local-index-backlinks"]')?.textContent || "", tags: document.querySelector('[data-testid="wolai-page-settings-local-index-tags"]')?.textContent || "", status: document.querySelector('[data-testid="wolai-page-settings-local-index-status"]')?.textContent || "", })); fs.renameSync(path.join(root, firstRelativePath), path.join(root, renamedRelativePath)); const second = await browserSearch(page, root, token); assert.equal(second.status, 200, `重命名后搜索应成功: ${JSON.stringify(second)}`); debug.second = second.payload; const secondResults = Array.isArray(second.payload.results) ? second.payload.results : []; assert( secondResults.some((item) => item.path === renamedRelativePath && item.documentId === localMdDocumentId(renamedRelativePath)), `重命名后搜索结果路径应更新: ${JSON.stringify(secondResults)}`, ); assert( !secondResults.some((item) => item.path === firstRelativePath), `重命名后搜索结果不应继续返回旧路径: ${JSON.stringify(secondResults)}`, ); const result = { ok: true, root, token, firstPath: firstRelativePath, renamedPath: renamedRelativePath, localIndexPanel: debug.localIndexPanel, indexExists: fs.existsSync(path.join(root, ".mnote", "index", "search-index.json")), }; fs.writeFileSync(RESULT_PATH, `${JSON.stringify(result, null, 2)}\n`, "utf8"); console.log(`task452 local search index browser smoke passed: ${RESULT_PATH}`); } catch (error) { fs.writeFileSync(RESULT_PATH, `${JSON.stringify({ ok: false, error: String(error && error.stack || error), debug, }, null, 2)}\n`, "utf8"); throw error; } finally { await browser.close().catch(() => {}); fs.rmSync(root, { recursive: true, force: true }); } } run().catch((error) => { console.error(error); process.exitCode = 1; });