Improve local filetree view state and sidebar performance

This commit is contained in:
lix-2026
2026-05-27 11:31:12 +08:00
parent 58e2fdb5d8
commit 3ae33cc21d
56 changed files with 8614 additions and 461 deletions
@@ -92,7 +92,7 @@ async function readRuntimePageOptions(page) {
async function waitForOptionsResponse(page, documentId, mutate) {
const responsePromise = page.waitForResponse(
async (response) => {
if (!response.url().includes("/api/documents/options") || response.request().method() !== "POST") {
if (!response.url().includes("/api/ui/preferences") || response.request().method() !== "PUT") {
return false;
}
const payload = response.request().postDataJSON();
@@ -103,8 +103,8 @@ async function waitForOptionsResponse(page, documentId, mutate) {
await mutate();
const response = await responsePromise;
const payload = await response.json();
assert.equal(payload?.meta?.commandName, "page.layout.updateOptions", "页面设置写入必须走 page.layout.updateOptions");
assert.equal(payload?.meta?.canonicalCommand, "page.layout.updateOptions", "页面设置 canonical command 必须稳定");
assert.equal(payload?.owner, "mnote-web", "页面设置写入必须由 mnote-web 持有");
assert(payload?.result?.pageOptions, "页面设置写入必须返回 SQLite 合并后的 pageOptions");
return payload;
}
@@ -174,7 +174,7 @@ async function openPageSettingsDialog(page) {
async function waitForOptionsResponse(page, documentId, mutate) {
const responsePromise = page.waitForResponse(
async (response) => {
if (!response.url().includes("/api/documents/options") || response.request().method() !== "POST") {
if (!response.url().includes("/api/ui/preferences") || response.request().method() !== "PUT") {
return false;
}
const payload = response.request().postDataJSON();
@@ -185,8 +185,8 @@ async function waitForOptionsResponse(page, documentId, mutate) {
await mutate();
const response = await responsePromise;
const payload = await response.json();
assert.equal(payload?.meta?.commandName, "page.layout.updateOptions", "页面设置写入必须走 page.layout.updateOptions");
assert.equal(payload?.meta?.canonicalCommand, "page.layout.updateOptions", "页面设置 canonical command 必须稳定");
assert.equal(payload?.owner, "mnote-web", "页面设置写入必须由 mnote-web 持有");
assert(payload?.result?.pageOptions, "页面设置写入必须返回 SQLite 合并后的 pageOptions");
return response.status();
}
@@ -286,7 +286,8 @@ async function run() {
request.url().includes("/api/tree/commands") ||
request.url().includes("/api/documents/title") ||
request.url().includes("/api/documents/save") ||
request.url().includes("/api/documents/options")
request.url().includes("/api/documents/options") ||
request.url().includes("/api/ui/preferences")
) {
requests.push({
url: request.url(),
@@ -298,7 +299,6 @@ async function run() {
try {
await page.goto(documentUrl(root, "local-md:README.md"), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.evaluate(() => window.localStorage.removeItem("mnote.global.showHeadingNumbers"));
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForText(page, "Frontmatter Title");
const dialogs = [];
@@ -393,21 +393,14 @@ async function run() {
if (!optionsResponse.ok) throw new Error(`options_failed_${optionsResponse.status}`);
}, { rootUri: fileUrl(root) });
assert(fs.readFileSync(path.join(root, "README.md"), "utf8").includes("Browser saved body"), "浏览器保存应写回 Markdown 正文");
assert(fs.existsSync(path.join(root, ".mnote", "page-options.json")), "浏览器页面设置保存写入 .mnote/page-options.json");
assert(!fs.existsSync(path.join(root, ".mnote", "page-options.json")), "浏览器页面设置保存不应继续写入 .mnote/page-options.json");
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForText(page, "Browser Saved Title");
await waitForText(page, "Browser saved body");
const globallyDisabledHeadingBefore = await page.locator("#mnote-leptos-tiptap-island-editor-root .ProseMirror h1").first().evaluate((node) =>
window.getComputedStyle(node, "::before").content
);
assert(globallyDisabledHeadingBefore === "none", "全局关闭时,即使页面设置显式开启 showHeadingNumbers,也不应显示标题自动编号");
await page.evaluate(() => window.localStorage.setItem("mnote.global.showHeadingNumbers", "true"));
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForText(page, "Browser Saved Title");
const enabledHeadingBefore = await page.locator("#mnote-leptos-tiptap-island-editor-root .ProseMirror h1").first().evaluate((node) =>
window.getComputedStyle(node, "::before").content
);
assert(enabledHeadingBefore !== "none", "全局开启后应显示标题自动编号");
assert(enabledHeadingBefore !== "none", "SQLite 偏好开启后应显示标题自动编号");
await page.goto(documentUrl(root, "local-md:docs~2Fblocks.md"), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await waitForText(page, "Complex Title");
await waitForText(page, "Bullet item");
@@ -193,8 +193,10 @@ async function main() {
);
assert(markdown.includes("# 正文标题"), "正文 H1 应写回 markdown");
assert(markdown.includes("正文已保存"), "正文段落应写回 markdown");
const options = fs.readFileSync(path.join(managedRoot, ".mnote", "page-options.json"), "utf8");
assert(options.includes("showToc"), "页面设置应写入 .mnote/page-options.json");
assert(
!fs.existsSync(path.join(managedRoot, ".mnote", "page-options.json")),
"页面设置不应继续写入 .mnote/page-options.json",
);
console.log("task167 local markdown title/body/options no-convex smoke passed");
} finally {
@@ -81,11 +81,21 @@ async function main() {
});
const page = await context.newPage();
const treeCommands = [];
const treeCommandResponses = [];
const unexpectedDialogs = [];
page.on("request", (request) => {
if (!request.url().includes("/api/tree/commands")) return;
const body = request.postDataJSON?.() || null;
treeCommands.push({ method: request.method(), body });
});
page.on("response", async (response) => {
if (!response.url().includes("/api/tree/commands")) return;
let body = "";
try {
body = await response.text();
} catch (_) {}
treeCommandResponses.push({ status: response.status(), body });
});
try {
await quickLogin(page);
@@ -95,6 +105,14 @@ async function main() {
url.searchParams.set("treeView", "filetree");
await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
const docsRow = page.locator('#sidebar-file-tree-root .tree-row[data-local-relative-path="docs"]').first();
if (await docsRow.isVisible({ timeout: UI_TIMEOUT_MS }).catch(() => false)) {
const expanded = await docsRow.getAttribute("aria-expanded").catch(() => null);
if (expanded !== "true") {
await docsRow.locator('[data-rust-action="toggle"]').click({ timeout: UI_TIMEOUT_MS });
}
}
const selectors = assets.map((asset) => `#sidebar-file-tree-root .tree-row[data-asset-id="${asset.assetId}"]`);
await page.locator(selectors[0]).waitFor({
state: "visible",
@@ -137,8 +155,16 @@ async function main() {
await page.locator('.mnote-tree-context-menu__item[data-action="delete-trash"]').click({ timeout: UI_TIMEOUT_MS });
const confirmText = await dialogPromise;
assert.match(confirmText, /2 个附件/, `右键 bulk delete 确认文案应包含附件数量: ${confirmText}`);
page.on("dialog", async (dialog) => {
unexpectedDialogs.push(dialog.message());
await dialog.accept().catch(() => undefined);
});
await page.waitForFunction(() => document.documentElement.getAttribute("data-mnote-filetree-bulk-delete-applied") === "true", null, {
await page.waitForFunction(() => {
const status = document.documentElement.getAttribute("data-mnote-filetree-last-action-status");
return document.documentElement.getAttribute("data-mnote-filetree-bulk-delete-applied") === "true"
|| status === "failed";
}, null, {
timeout: UI_TIMEOUT_MS,
});
const actionState = await page.evaluate(() => ({
@@ -146,8 +172,11 @@ async function main() {
status: document.documentElement.getAttribute("data-mnote-filetree-last-action-status"),
rowId: document.documentElement.getAttribute("data-mnote-filetree-last-action-row-id"),
applied: document.documentElement.getAttribute("data-mnote-filetree-bulk-delete-applied"),
batchId: document.documentElement.getAttribute("data-mnote-filetree-bulk-delete-batch-id"),
batchRefresh: document.documentElement.getAttribute("data-mnote-filetree-batch-refresh-applied"),
}));
assert.equal(actionState.action, "bulk-delete", `bulk delete 应记录 action 名: ${JSON.stringify(actionState)}`);
assert.deepEqual(unexpectedDialogs, [], `bulk delete 不应出现失败 alert: ${JSON.stringify({ unexpectedDialogs, treeCommands, treeCommandResponses })}`);
assert.equal(actionState.status, "archived", `bulk delete 应记录 undo/archive 状态: ${JSON.stringify(actionState)}`);
assert.equal(actionState.rowId, rowIds[1], `bulk delete 应记录触发目标 row: ${JSON.stringify(actionState)}`);
for (const asset of assets) {
@@ -159,6 +188,13 @@ async function main() {
}
const archiveCommands = treeCommands.filter((entry) => entry.body && entry.body.action === "archive");
assert.equal(archiveCommands.length, 2, `bulk delete 应发出两个 archive tree command: ${JSON.stringify(treeCommands)}`);
assert(actionState.batchId, `bulk delete 应生成 batch id: ${JSON.stringify(actionState)}`);
assert.equal(actionState.batchRefresh, actionState.batchId, `bulk delete 应按 batch 完成后统一刷新: ${JSON.stringify(actionState)}`);
assert.deepEqual(
Array.from(new Set(archiveCommands.map((entry) => entry.body.batchId))).sort(),
[actionState.batchId],
`archive command 应共享同一个 batchId: ${JSON.stringify(archiveCommands)}`,
);
assert.deepEqual(
archiveCommands.map((entry) => entry.body.documentId).sort(),
assets.map((asset) => asset.assetId).sort(),
@@ -850,22 +850,17 @@ async function main() {
await hideTitleCheckbox.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const hideTitleCheckedBefore = await hideTitleCheckbox.isChecked();
assert.equal(hideTitleCheckedBefore, false, "托管工作区(我的空间)默认不隐藏文件标题");
await hideTitleCheckbox.setChecked(true, { timeout: UI_TIMEOUT_MS });
const optionsPath = path.join(root, ".mnote", "page-options.json");
const optionsHidden = await waitForFileContent(
optionsPath,
(content) => {
try {
const payload = JSON.parse(content);
return payload?.pages?.["local-md:MyNotes.md"]?.hideTitleHeader === true;
} catch {
return false;
}
await hideTitleCheckbox.setChecked(true, { timeout: UI_TIMEOUT_MS });
await page.waitForFunction(
() => {
const header = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell-header');
return header instanceof HTMLElement ? header.hidden || header.getAttribute("data-page-title-hidden") === "true" : false;
},
UI_TIMEOUT_MS,
null,
{ timeout: UI_TIMEOUT_MS },
);
assert(optionsHidden.ok, `隐藏标题应持久化 hideTitleHeader=true,实际: ${optionsHidden.content}`);
await page.waitForTimeout(500);
assert(!fs.existsSync(optionsPath), "隐藏标题不应继续写入 .mnote/page-options.json");
const titleHeaderHiddenAfterCheck = await page.evaluate(() => {
const header = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell-header');
return header instanceof HTMLElement ? header.hidden || header.getAttribute("data-page-title-hidden") === "true" : false;
@@ -873,20 +868,15 @@ async function main() {
assert(titleHeaderHiddenAfterCheck, "勾选隐藏标题后标题应隐藏");
await hideTitleCheckbox.setChecked(false, { timeout: UI_TIMEOUT_MS });
const optionsShown = await waitForFileContent(
optionsPath,
(content) => {
try {
const payload = JSON.parse(content);
return payload?.pages?.["local-md:MyNotes.md"]?.hideTitleHeader === false;
} catch {
return false;
}
await page.waitForFunction(
() => {
const header = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell-header');
return header instanceof HTMLElement ? !header.hidden && header.getAttribute("data-page-title-hidden") === "false" : false;
},
UI_TIMEOUT_MS,
null,
{ timeout: UI_TIMEOUT_MS },
);
assert(optionsShown.ok, `显示标题应持久化 hideTitleHeader=false,实际: ${optionsShown.content}`);
await page.waitForTimeout(500);
assert(!fs.existsSync(optionsPath), "显示标题不应继续写入 .mnote/page-options.json");
const titleHeaderVisibleAfterToggle = await page.evaluate(() => {
const header = document.querySelector('.document-pane[data-pane-role="primary"] .document-shell-header');
return header instanceof HTMLElement ? !header.hidden && header.getAttribute("data-page-title-hidden") === "false" : false;
@@ -0,0 +1,323 @@
#!/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 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 dbPath = path.join(dataRoot, "control-plane.sqlite3");
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}`,
MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
MNOTE_CONTROL_PLANE_DB_PATH: dbPath,
MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot,
CONVEX_SELF_HOSTED_URL: "http://127.0.0.1:9",
NEXT_PUBLIC_CONVEX_URL: "http://127.0.0.1:9",
},
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 = [];
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 = [
'<ul class="tree-root" role="tree">',
'<li class="tree-node" data-node-id="stale-my-space-page">',
'<div class="tree-row" role="treeitem" data-shell-mode="page" data-node-id="stale-my-space-page" data-active="true">',
'<button type="button" class="tree-link" data-rust-action="open" data-node-id="stale-my-space-page">',
'<span class="tree-link-title">我的空间旧页面</span>',
"</button>",
"</div>",
"</li>",
"</ul>",
].join("");
});
await cloudDesignShortcut.click({ timeout: UI_TIMEOUT_MS });
await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const scopedExplorerUrl = new URL(page.url());
assert.equal(scopedExplorerUrl.searchParams.get("sourceKind"), "local_folder", "点击星标文件夹后应切到本地文件夹 source");
assert.equal(scopedExplorerUrl.searchParams.get("rootUri"), rootUri, "点击星标文件夹后 URL 应保留显式 rootUri");
assert.equal(scopedExplorerUrl.searchParams.get("fileTreeScope"), "design", "点击星标文件夹后 URL 应进入 design scope");
assert.equal(
await page.evaluate(() => document.documentElement.getAttribute("data-mnote-sidebar-shortcut-open-error") || ""),
"",
"星标文件夹打开不应依赖 workspaceId 反推 rootUri",
);
const scopedText = await page.locator("#sidebar-file-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
assert.match(scopedText, /Brief/);
assert.doesNotMatch(scopedText, /Other/);
const scopedPageTreeState = await page.evaluate(() => {
const root = document.querySelector("#sidebar-tree-root");
return {
text: root?.innerText || "",
rowCount: root?.querySelectorAll('.tree-row[data-shell-mode="page"]').length || 0,
staleRowCount: root?.querySelectorAll('.tree-row[data-shell-mode="page"][data-node-id="stale-my-space-page"]').length || 0,
activeRows: Array.from(root?.querySelectorAll('.tree-row[data-shell-mode="page"][data-active="true"]') || []).map((row) => ({
nodeId: row.getAttribute("data-node-id") || "",
title: row.querySelector(".tree-link-title")?.textContent?.trim() || "",
})),
};
});
assert.equal(
scopedPageTreeState.staleRowCount,
0,
`打开星标本地文件夹后不应保留原我的空间页面树: ${JSON.stringify(scopedPageTreeState)}`,
);
assert(
scopedPageTreeState.rowCount > 0 && /Brief/.test(scopedPageTreeState.text),
`打开星标本地文件夹后应显示本地 Markdown 页面树投影: ${JSON.stringify(scopedPageTreeState)}`,
);
await page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/Brief.md"] .tree-link').first().click({
timeout: UI_TIMEOUT_MS,
});
await page.waitForURL((nextUrl) => nextUrl.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
const scopedDocumentUrl = page.url();
const scopedDocumentResponse = await context.request.fetch(scopedDocumentUrl);
const scopedDocumentHtml = await scopedDocumentResponse.text();
assert(scopedDocumentHtml.includes('data-mnote-filetree-scope="design"'), "SSR document shell 应输出 filetree scope");
assert(scopedDocumentHtml.includes("Brief.md"), "SSR document shell 应输出 scoped 文件树内容");
await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="design"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const documentScopedText = await page.locator("#sidebar-file-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
assert.match(documentScopedText, /Brief/, `打开 scoped md 后应保留 design scope: url=${page.url()} text=${documentScopedText} browser=${browserDiagnostics.slice(-12).join(" | ")}`);
assert.doesNotMatch(documentScopedText, /Other/, `打开 scoped md 后不应回到根目录: url=${page.url()} text=${documentScopedText} browser=${browserDiagnostics.slice(-12).join(" | ")}`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
const reloadedDesignShortcut = page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').first();
await reloadedDesignShortcut.waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await reloadedDesignShortcut.hover({ timeout: UI_TIMEOUT_MS });
await reloadedDesignShortcut.locator('[data-mnote-shortcut-action="menu"]').click({ timeout: UI_TIMEOUT_MS });
await page.locator('[data-testid="mnote-sidebar-shortcut-menu"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.getByRole("menuitem", { name: "取消星标" }).click({ timeout: UI_TIMEOUT_MS });
await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').waitFor({
state: "detached",
timeout: UI_TIMEOUT_MS,
});
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
assert.equal(
await page.locator('.wolai-starred-section [data-mnote-shortcut-kind="folder"][data-mnote-shortcut-relative-path="design"]').count(),
0,
"三点菜单取消星标后刷新不应恢复该文件夹星标",
);
console.log(JSON.stringify({ ok: true, task: TASK, baseUrl }, null, 2));
} finally {
await browser.close();
server.kill("SIGINT");
fs.rmSync(dataRoot, { recursive: true, force: true });
if (server.exitCode == null) {
await new Promise((resolve) => server.once("exit", resolve));
}
if (server.exitCode && server.exitCode !== 130 && server.exitCode !== null) {
process.stderr.write(stderr);
}
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,216 @@
#!/usr/bin/env node
"use strict";
const assert = require("node:assert");
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 TIMEOUT_MS = Number(process.env.UI_TIMEOUT_MS || 30_000);
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(1_000, () => {
request.destroy();
retry();
});
};
const retry = () => {
if (Date.now() > deadline) {
reject(new Error(`server_not_ready: ${url}`));
return;
}
setTimeout(tick, 250);
};
tick();
});
}
async function requestJson(requestContext, baseUrl, pathname, init = {}) {
const response = await requestContext.fetch(`${baseUrl}${pathname}`, {
method: init.method || "GET",
headers: {
"content-type": "application/json",
...(init.headers || {}),
},
data: init.data,
timeout: TIMEOUT_MS,
});
const payload = await response.json().catch(() => null);
assert(
response.ok(),
`${init.method || "GET"} ${pathname} failed ${response.status()}: ${JSON.stringify(payload)}`,
);
return payload;
}
async function loadAggregate(requestContext, baseUrl, documentId, rootUri) {
const url = new URL(`/api/page-aggregate/${encodeURIComponent(documentId)}`, baseUrl);
url.searchParams.set("sourceKind", "local_folder");
url.searchParams.set("rootUri", rootUri);
const payload = await requestJson(requestContext, baseUrl, `${url.pathname}${url.search}`);
return payload.result || payload;
}
async function effectivePreferences(requestContext, baseUrl, documentId, rootUri) {
const url = new URL("/api/ui/preferences/effective", baseUrl);
url.searchParams.set("sourceKind", "local_folder");
url.searchParams.set("rootUri", rootUri);
url.searchParams.set("documentId", documentId);
const payload = await requestJson(requestContext, baseUrl, `${url.pathname}${url.search}`);
return payload.result;
}
async function main() {
const port = await pickPort();
const baseUrl = `http://127.0.0.1:${port}`;
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-ui-pref-smoke-"));
const policyRoot = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-ui-pref-policy-"));
const policyFile = path.join(policyRoot, "access-policy.json");
const actorId = `ui-pref-smoke-${process.pid}-${Date.now()}`;
const otherActorId = `${actorId}-other`;
const documentId = "local-md:README.md";
const rootUri = `file://${root}`;
fs.writeFileSync(path.join(root, "README.md"), "# README\n\n正文\n", "utf8");
fs.writeFileSync(
policyFile,
JSON.stringify({
grants: [
{
userId: actorId,
rootUri,
permission: "write",
recursive: true,
},
],
}),
"utf8",
);
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}`,
MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
MNOTE_LOCAL_ACCESS_POLICY_FILE: policyFile,
CONVEX_SELF_HOSTED_URL: "http://127.0.0.1:9",
NEXT_PUBLIC_CONVEX_URL: "http://127.0.0.1:9",
},
stdio: ["ignore", "pipe", "pipe"],
});
let stderr = "";
server.stderr.on("data", (chunk) => {
stderr += chunk.toString();
});
const browser = await chromium.launch({ headless: true });
const firstContext = await browser.newContext({
extraHTTPHeaders: {
"x-mnote-actor-id": actorId,
"x-mnote-actor-type": "user",
},
});
const secondContext = await browser.newContext({
extraHTTPHeaders: {
"x-mnote-actor-id": actorId,
"x-mnote-actor-type": "user",
},
});
const otherContext = await browser.newContext({
extraHTTPHeaders: {
"x-mnote-actor-id": otherActorId,
"x-mnote-actor-type": "user",
},
});
try {
await waitForHttpOk(`${baseUrl}/health`, 60_000);
const initialAggregate = await loadAggregate(firstContext.request, baseUrl, documentId, rootUri);
assert.equal(
initialAggregate.layout.pageOptions.hideTitleHeader,
true,
"普通外部 local folder 默认隐藏本地 Markdown 标题",
);
await requestJson(firstContext.request, baseUrl, "/api/ui/preferences", {
method: "PUT",
data: {
sourceKind: "local_folder",
rootUri,
documentId,
updates: {
hideTitleHeader: false,
showHeadingNumbers: true,
wideLayout: true,
pageFont: "song",
},
},
});
assert(
!fs.existsSync(path.join(root, ".mnote", "page-options.json")),
"SQLite 偏好写入不应生成 .mnote/page-options.json",
);
const sameUserEffective = await effectivePreferences(secondContext.request, baseUrl, documentId, rootUri);
assert.equal(sameUserEffective.pageOptions.hideTitleHeader, false, "同用户第二浏览器应读到隐藏标题偏好");
assert.equal(sameUserEffective.pageOptions.showHeadingNumbers, true, "同用户第二浏览器应读到标题编号偏好");
assert.equal(sameUserEffective.pageOptions.wideLayout, true, "同用户第二浏览器应读到页面宽度偏好");
assert.equal(sameUserEffective.pageOptions.pageFont, "song", "同用户第二浏览器应读到页面字体偏好");
const otherUserEffective = await effectivePreferences(otherContext.request, baseUrl, documentId, rootUri);
assert.equal(otherUserEffective.pageOptions.hideTitleHeader, true, "不同用户不应串读 source family 偏好");
assert.equal(otherUserEffective.pageOptions.showHeadingNumbers, false, "不同用户不应串读 global 偏好");
console.log("task493 page settings sqlite preferences smoke passed");
} finally {
await firstContext.close().catch(() => {});
await secondContext.close().catch(() => {});
await otherContext.close().catch(() => {});
await browser.close().catch(() => {});
server.kill("SIGINT");
fs.rmSync(root, { recursive: true, force: true });
fs.rmSync(policyRoot, { recursive: true, force: true });
if (server.exitCode == null) {
await new Promise((resolve) => server.once("exit", resolve));
}
if (server.exitCode && server.exitCode !== 130 && server.exitCode !== null) {
process.stderr.write(stderr);
}
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,544 @@
#!/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 TASK = "task494-filetree-lazy-loading-dedup-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);
}
function localMarkdownDocumentPath(documentId) {
const encoded = String(documentId || "").replace(/^local-md:/, "");
return decodeURIComponent(encoded.replace(/~/g, "%"));
}
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 dbPath = path.join(dataRoot, "control-plane.sqlite3");
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}`,
MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
MNOTE_CONTROL_PLANE_DB_PATH: dbPath,
MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot,
CONVEX_SELF_HOSTED_URL: "http://127.0.0.1:9",
NEXT_PUBLIC_CONVEX_URL: "http://127.0.0.1:9",
},
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 targetChildrenRequests = 0;
let staleScopeChildrenRequests = 0;
let scopedRootProjectionRequests = 0;
let workspaceRootProjectionRequests = 0;
let forceChangingWatchRevision = false;
let localWatchRevision = 0;
page.on("console", (message) => {
browserDiagnostics.push(`console:${message.type()}:${message.text()}`);
});
page.on("pageerror", (error) => {
browserDiagnostics.push(`pageerror:${error.message}`);
});
await page.route("**/api/tree/projections/file**", async (route) => {
const url = new URL(route.request().url());
const parentRelativePath = url.searchParams.get("parentRelativePath") || "";
if (url.pathname.endsWith("/api/tree/projections/file") && parentRelativePath === "design") {
scopedRootProjectionRequests += 1;
}
if (url.pathname.endsWith("/api/tree/projections/file") && !parentRelativePath) {
workspaceRootProjectionRequests += 1;
}
if (url.pathname.endsWith("/api/tree/projections/file/children") && parentRelativePath === "design/03-rust-web") {
targetChildrenRequests += 1;
await new Promise((resolve) => setTimeout(resolve, 250));
}
if (url.pathname.endsWith("/api/tree/projections/file/children") && parentRelativePath === "design/slow-scope") {
staleScopeChildrenRequests += 1;
await new Promise((resolve) => setTimeout(resolve, 600));
}
await route.continue();
});
await page.route("**/api/tree/local-folder-watch**", async (route) => {
if (!forceChangingWatchRevision) {
await route.continue();
return;
}
localWatchRevision += 1;
await route.fulfill({
status: 200,
contentType: "application/json",
body: JSON.stringify({
ok: true,
result: {
revision: `forced-watch-${localWatchRevision}`,
},
}),
});
});
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 initialUrl = new URL(page.url());
const workspaceId = initialUrl.searchParams.get("workspaceId") || "";
const rootUri = initialUrl.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", "03-rust-web", "done"), { recursive: true });
fs.mkdirSync(path.join(rootPath, "design", "03-rust-web", "process"), { recursive: true });
fs.mkdirSync(path.join(rootPath, "design", "03-rust-web", "reference"), { recursive: true });
fs.mkdirSync(path.join(rootPath, "design", "reveal-parent", "child"), { recursive: true });
fs.mkdirSync(path.join(rootPath, "design", "slow-scope", "child"), { recursive: true });
fs.mkdirSync(path.join(rootPath, "docs", "target"), { recursive: true });
fs.writeFileSync(path.join(rootPath, "Home.md"), "# Home\n", "utf8");
fs.writeFileSync(path.join(rootPath, "design", "Overview.md"), "Plain paragraph without office attachment.\n", "utf8");
fs.writeFileSync(path.join(rootPath, "design", "03-rust-web", "plan.md"), "# Plan\n", "utf8");
fs.writeFileSync(path.join(rootPath, "design", "reveal-parent", "child", "note.md"), "# Reveal\n", "utf8");
fs.writeFileSync(path.join(rootPath, "design", "slow-scope", "child", "note.md"), "# Slow child\n", "utf8");
fs.writeFileSync(path.join(rootPath, "docs", "target", "note.md"), "# Docs child\n", "utf8");
fs.writeFileSync(path.join(rootPath, "docs", "opened-rename.md"), "# Opened rename\n", "utf8");
const fileTreeUrl = new URL(baseUrl);
if (workspaceId) fileTreeUrl.searchParams.set("workspaceId", workspaceId);
fileTreeUrl.searchParams.set("sourceKind", "local_folder");
fileTreeUrl.searchParams.set("rootUri", rootUri);
fileTreeUrl.searchParams.set("treeView", "filetree");
await page.goto(fileTreeUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator('[data-mnote-sidebar-tree-tab="filetree"]').click({ timeout: UI_TIMEOUT_MS });
await page.getByRole("button", { name: "新建页面" }).first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => url.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(300);
const firstCreatedDocumentId = decodeURIComponent(new URL(page.url()).pathname.split("/").filter(Boolean).pop() || "");
const firstCreatedRelativePath = localMarkdownDocumentPath(firstCreatedDocumentId);
const firstCreatedParentPath = firstCreatedRelativePath.split("/").slice(0, -1).join("/");
await page.getByRole("button", { name: "新建页面" }).first().click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => {
const documentId = decodeURIComponent(url.pathname.split("/").filter(Boolean).pop() || "");
return url.pathname.startsWith("/documents/") && documentId !== firstCreatedDocumentId;
}, { timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(500);
const secondCreatedDocumentId = decodeURIComponent(new URL(page.url()).pathname.split("/").filter(Boolean).pop() || "");
const secondCreatedRelativePath = localMarkdownDocumentPath(secondCreatedDocumentId);
const secondCreatedParentPath = secondCreatedRelativePath.split("/").slice(0, -1).join("/");
const createExpansionState = await page.evaluate(({ firstParent, secondParent }) => {
const readRow = (relativePath) => {
const row = document.querySelector(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${CSS.escape(relativePath)}"]`);
return row
? {
relativePath,
expanded: row.getAttribute("aria-expanded"),
selected: row.getAttribute("data-selected"),
active: row.getAttribute("data-active"),
}
: null;
};
return {
first: readRow(firstParent),
second: readRow(secondParent),
firstMarkdownVisible: Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${CSS.escape(firstParent + "/" + firstParent.split("/").pop() + ".md")}"]`)),
secondMarkdownVisible: Boolean(document.querySelector(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${CSS.escape(secondParent + "/" + secondParent.split("/").pop() + ".md")}"]`)),
};
}, { firstParent: firstCreatedParentPath, secondParent: secondCreatedParentPath });
assert.equal(
createExpansionState.first?.expanded,
"false",
`连续新建页面不应把上一个页面包目录自动展开: ${JSON.stringify(createExpansionState)}`,
);
assert.equal(
createExpansionState.second?.expanded,
"false",
`连续新建页面不应为了选中内部 md 而展开当前页面包目录: ${JSON.stringify(createExpansionState)}`,
);
assert.equal(createExpansionState.firstMarkdownVisible, false, `上一个页面包内部 md 不应闪现/常驻: ${JSON.stringify(createExpansionState)}`);
assert.equal(createExpansionState.secondMarkdownVisible, false, `当前页面包内部 md 不应闪现/常驻: ${JSON.stringify(createExpansionState)}`);
assert.equal(createExpansionState.second?.active, "true", `当前页面包目录应承接 active 状态: ${JSON.stringify(createExpansionState)}`);
const scopedUrl = new URL(baseUrl);
if (workspaceId) scopedUrl.searchParams.set("workspaceId", workspaceId);
scopedUrl.searchParams.set("sourceKind", "local_folder");
scopedUrl.searchParams.set("rootUri", rootUri);
scopedUrl.searchParams.set("treeView", "filetree");
scopedUrl.searchParams.set("fileTreeScope", "design");
await page.goto(scopedUrl.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[data-mnote-filetree-scope="design"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const scopedRootRequestsAfterInitialLoad = scopedRootProjectionRequests;
const workspaceRootRequestsAfterInitialLoad = workspaceRootProjectionRequests;
await page.evaluate(() => {
window.__mnoteScopedFileOpenNoReloadMarker = "kept";
document.documentElement.setAttribute("data-mnote-scoped-file-open-no-reload-marker", "kept");
});
await page.locator('#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/Overview.md"] .tree-link').first().click({
timeout: UI_TIMEOUT_MS,
});
await page.waitForURL((nextUrl) => nextUrl.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
await page.locator('.document-pane[data-pane-role="primary"] .editor-surface').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.evaluate(() => {
if (typeof window.__mnoteEnhanceEditorAttachmentLinks === "function") {
window.__mnoteEnhanceEditorAttachmentLinks();
}
});
await page.waitForTimeout(800);
const scopedOpenMarker = await page.evaluate(() => window.__mnoteScopedFileOpenNoReloadMarker || "");
assert.equal(scopedOpenMarker, "kept", "scoped 文件树打开 md 应走 pane 内导航,不应整页 reload 重建侧栏");
assert.equal(
scopedRootProjectionRequests,
scopedRootRequestsAfterInitialLoad,
"scoped 文件树打开已可见 md 不应重新请求 scope 根 projection",
);
assert.equal(
workspaceRootProjectionRequests,
workspaceRootRequestsAfterInitialLoad,
"普通 Markdown 打开不应为了 legacy office 附件兼容重拉 workspace root projection",
);
const scopedRootRequestsBeforeRootSnapshot = scopedRootProjectionRequests;
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent("tree:snapshot", {
detail: {
payload: {
dataset: {
kernel_file_tree_projection: {
parentRelativePath: "",
items: [
{
rowId: "local:folder:root-probe",
nodeId: "local:folder:root-probe",
title: "root-probe",
rowKind: "folder",
resourceMeta: {
workspacePath: { relativePath: "root-probe" },
},
},
],
},
},
},
},
}));
});
await page.waitForTimeout(350);
assert.equal(
scopedRootProjectionRequests,
scopedRootRequestsBeforeRootSnapshot,
"scoped 文件树收到非 scope root snapshot 不应兜底重拉 scope 根 projection",
);
const scopedRootRequestsBeforeCoarseWatch = scopedRootProjectionRequests;
forceChangingWatchRevision = true;
await page.waitForTimeout(1600);
forceChangingWatchRevision = false;
assert.equal(
scopedRootProjectionRequests,
scopedRootRequestsBeforeCoarseWatch,
"scoped 文件树收到 coarse local-folder-watch revision 不应重拉 scope 根 projection",
);
const rowSelector = '#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/03-rust-web"]';
const childSelector = '#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path^="design/03-rust-web/"]';
await page.locator(rowSelector).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
assert.equal(targetChildrenRequests, 0, "scoped 首屏不应预加载 design/03-rust-web children");
await page.locator(rowSelector).evaluate((row) => {
const toggle = row.querySelector('[data-rust-action="toggle"]');
for (let index = 0; index < 5; index += 1) toggle.click();
});
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
return row && row.getAttribute("aria-expanded") === "true" && row.getAttribute("data-filetree-children-loaded") === "true";
}, rowSelector, { timeout: UI_TIMEOUT_MS });
await page.locator(`${childSelector}[data-local-relative-path="design/03-rust-web/done"]`).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
assert.equal(targetChildrenRequests, 1, "同一路径快速重复展开最多只能产生一个 children 请求");
const firstExpandRequests = targetChildrenRequests;
await page.locator(`${rowSelector} [data-rust-action="toggle"]`).click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
return row && row.getAttribute("aria-expanded") === "false";
}, rowSelector, { timeout: UI_TIMEOUT_MS });
const expandStartedAt = Date.now();
await page.locator(`${rowSelector} [data-rust-action="toggle"]`).click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
const child = document.querySelector('[data-local-relative-path="design/03-rust-web/process"]');
return row && child && row.getAttribute("aria-expanded") === "true";
}, rowSelector, { timeout: UI_TIMEOUT_MS });
const cachedExpandMs = Date.now() - expandStartedAt;
assert.equal(targetChildrenRequests, firstExpandRequests, "收起后再次展开应命中 cache,不应再次请求 children");
await page.locator(`${childSelector}[data-local-relative-path="design/03-rust-web/done"]`).evaluate((row) => {
row.setAttribute("data-selected", "true");
row.setAttribute("data-focused", "true");
row.setAttribute("data-active", "true");
});
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent("tree:local-command", {
detail: {
body: {
action: "rename",
documentId: "local-md:design~2F03-rust-web~2Fplan.md",
title: "plan",
parentRelativePath: "design/03-rust-web",
},
result: {
parentRelativePath: "design/03-rust-web",
},
},
}));
});
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
const done = document.querySelector('[data-local-relative-path="design/03-rust-web/done"]');
const process = document.querySelector('[data-local-relative-path="design/03-rust-web/process"]');
return row && done && process && row.getAttribute("aria-expanded") === "true";
}, rowSelector, { timeout: UI_TIMEOUT_MS });
assert.equal(targetChildrenRequests, firstExpandRequests, "局部 parent refresh 不应绕过 cache 触发 children 重复请求");
const selectedAfterRefresh = await page.locator(`${childSelector}[data-local-relative-path="design/03-rust-web/done"]`).evaluate((row) => ({
selected: row.getAttribute("data-selected"),
focused: row.getAttribute("data-focused"),
active: row.getAttribute("data-active"),
}));
assert.deepEqual(selectedAfterRefresh, {
selected: "true",
focused: "true",
active: "true",
}, "局部 parent refresh 后应按 logical state 复投影 selection/focus/active");
fs.writeFileSync(path.join(rootPath, "design", "03-rust-web", "watch-created.md"), "# Watch\n", "utf8");
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent("tree:local-folder-watch-batch", {
detail: {
payload: {
schema: "mnote.local_folder_watch_batch.v1",
revision: "smoke-watch-1",
affectedParents: [{ relativePath: "design/03-rust-web", reason: "child-watch" }],
changedPaths: [{ relativePath: "design/03-rust-web/watch-created.md", kind: "Create(File)" }],
eventKinds: ["Create(File)"],
fallbackResync: false,
},
},
}));
});
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
const created = document.querySelector('[data-local-relative-path="design/03-rust-web/watch-created.md"]');
return row && created && row.getAttribute("aria-expanded") === "true";
}, rowSelector, { timeout: UI_TIMEOUT_MS });
assert.equal(
await page.locator(rowSelector).getAttribute("aria-expanded"),
"true",
"watch batch 局部刷新后已展开 parent 不应折叠",
);
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent("mnote:primary-document-activated", {
detail: { documentId: "local-md:design~2Freveal-parent~2Fchild~2Fnote.md" },
}));
});
const revealTargetSelector = '#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/reveal-parent/child/note.md"]';
await page.waitForFunction((selector) => {
const row = document.querySelector(selector);
return row
&& row.getAttribute("data-selected") === "true"
&& row.getAttribute("data-focused") === "true"
&& row.getAttribute("data-active") === "true";
}, revealTargetSelector, { timeout: UI_TIMEOUT_MS });
const slowScopeSelector = '#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="design/slow-scope"]';
await page.locator(slowScopeSelector).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator(`${slowScopeSelector} [data-rust-action="toggle"]`).click({ timeout: UI_TIMEOUT_MS });
const docsUrl = new URL(scopedUrl.toString());
docsUrl.searchParams.set("fileTreeScope", "docs");
await page.goto(docsUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator('#sidebar-file-tree-root[data-mnote-filetree-scope="docs"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.waitForTimeout(800);
assert.equal(staleScopeChildrenRequests, 1, "慢目录切 scope 前应触发一次 children 请求");
const staleRowsInDocsScope = await page.locator('#sidebar-file-tree-root .tree-row[data-local-relative-path^="design/slow-scope/"]').count();
assert.equal(staleRowsInDocsScope, 0, "慢请求返回后不得把旧 design scope children patch 到 docs scope");
const rootText = await page.locator("#sidebar-file-tree-root").innerText({ timeout: UI_TIMEOUT_MS });
assert.match(rootText, /target/);
const openedDocumentId = "local-md:docs~2Fopened-rename.md";
const renamedDocumentId = "local-md:docs~2Fopened-renamed.md";
const documentUrl = new URL(`${baseUrl}/documents/${encodeURIComponent(openedDocumentId)}`);
if (workspaceId) documentUrl.searchParams.set("workspaceId", workspaceId);
documentUrl.searchParams.set("sourceKind", "local_folder");
documentUrl.searchParams.set("rootUri", rootUri);
await page.goto(documentUrl.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator('.document-pane[data-pane-role="primary"] .editor-surface').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const renameResponse = await context.request.fetch(`${baseUrl}/api/tree/commands`, {
method: "POST",
data: {
action: "rename",
workspaceId,
sourceKind: "local_folder",
rootUri,
documentId: openedDocumentId,
title: "opened-renamed",
},
});
assert(renameResponse.ok(), `opened markdown rename command failed: ${renameResponse.status()} ${await renameResponse.text()}`);
const bufferStateUrl = new URL(`${baseUrl}/api/documents/buffer-state`);
bufferStateUrl.searchParams.set("documentId", renamedDocumentId);
if (workspaceId) bufferStateUrl.searchParams.set("workspaceId", workspaceId);
bufferStateUrl.searchParams.set("sourceKind", "local_folder");
bufferStateUrl.searchParams.set("rootUri", rootUri);
bufferStateUrl.searchParams.set("relativePath", "docs/opened-renamed.md");
const bufferStateResponse = await context.request.fetch(bufferStateUrl.toString());
assert(bufferStateResponse.ok(), `opened markdown rename should rekey buffer: ${bufferStateResponse.status()} ${await bufferStateResponse.text()}`);
const bufferStatePayload = await bufferStateResponse.json();
assert.equal(bufferStatePayload.result.documentId, renamedDocumentId, "opened markdown rename 后 buffer key 应更新到新 documentId");
console.log(JSON.stringify({
ok: true,
task: TASK,
baseUrl,
targetChildrenRequests,
staleScopeChildrenRequests,
cachedExpandMs,
}, null, 2));
} finally {
await browser.close();
server.kill("SIGINT");
fs.rmSync(dataRoot, { recursive: true, force: true });
if (server.exitCode == null) {
await new Promise((resolve) => server.once("exit", resolve));
}
if (server.exitCode && server.exitCode !== 130 && server.exitCode !== null) {
process.stderr.write(stderr);
}
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,151 @@
#!/usr/bin/env node
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const REPO_ROOT = path.resolve(__dirname, "..");
const RUNTIME_PATH = path.join(
REPO_ROOT,
"rust/crates/mnote-web/browser/sidebar-filetree-command-runtime.js",
);
function loadRuntimeFactory() {
const source = fs
.readFileSync(RUNTIME_PATH, "utf8")
.replace(
"export const createSidebarFileTreeCommandRuntime = (dependencies = {}) => {",
"const createSidebarFileTreeCommandRuntime = (dependencies = {}) => {",
);
const context = {
console,
CustomEvent: class CustomEvent {
constructor(type, init) {
this.type = type;
this.detail = init && init.detail;
}
},
HTMLElement: class HTMLElement {},
navigator: {
clipboard: {
writeText: async (text) => {
context.__clipboardText = text;
},
},
},
document: {
body: {},
documentElement: {
attrs: {},
setAttribute(name, value) {
this.attrs[name] = String(value);
},
},
createElement() {
return {};
},
querySelector() {
return null;
},
querySelectorAll() {
return [];
},
},
window: {
alert() {},
confirm() {
return true;
},
dispatchEvent() {},
},
URL,
setTimeout,
clearTimeout,
};
context.globalThis = context;
vm.createContext(context);
vm.runInContext(
`${source}\nglobalThis.__factory = createSidebarFileTreeCommandRuntime;`,
context,
{ filename: RUNTIME_PATH },
);
return context;
}
async function runCopyId(runtime, context, detail) {
context.__clipboardText = "";
runtime.handleTreeContextMenuAction("copy-id", detail, null);
await new Promise((resolve) => setImmediate(resolve));
return context.__clipboardText;
}
async function main() {
const context = loadRuntimeFactory();
const runtime = context.__factory({
currentRootUri: () => "file:///mnt/Data1T/mnote",
currentSourceKind: () => "local_folder",
cssEscape: (value) => String(value).replace(/"/g, '\\"'),
fileTreeRuntimeFunction: () => null,
localFilePathFromAssetId: (assetId) =>
String(assetId || "").replace(/^local-file:/, ""),
resolveWorkspaceId: () => "local-folder",
runtimeState: { activeTreeContextMenu: null },
selectedSidebarFileTreeSelection: { selectedRowIds: new Set(), focusedRowId: null },
});
assert.equal(
await runCopyId(runtime, context, {
contextKind: "filetree",
rowKind: "folder",
documentId: "local-dir:docs",
rowId: "local:folder:docs",
title: "docs",
}),
"/mnt/Data1T/mnote/docs",
"复制本地文件夹页面 ID 应得到绝对路径",
);
assert.equal(
await runCopyId(runtime, context, {
contextKind: "filetree",
rowKind: "markdown",
documentId: "local-md:docs~2FPage.md",
rowId: "local:markdown:docs~2FPage.md",
title: "Page",
}),
"/mnt/Data1T/mnote/docs/Page.md",
"复制本地 Markdown 页面 ID 应得到绝对路径",
);
assert.equal(
await runCopyId(runtime, context, {
contextKind: "filetree",
rowKind: "asset",
assetId: "local-file:assets~2Freport.pdf",
rowId: "local:asset:assets~2Freport.pdf",
title: "report.pdf",
}),
"/mnt/Data1T/mnote/assets/report.pdf",
"复制本地资源 ID 应得到绝对路径",
);
console.log(
JSON.stringify(
{
ok: true,
copied: [
"/mnt/Data1T/mnote/docs",
"/mnt/Data1T/mnote/docs/Page.md",
"/mnt/Data1T/mnote/assets/report.pdf",
],
},
null,
2,
),
);
}
main().catch((error) => {
console.error(error);
process.exit(1);
});
@@ -0,0 +1,204 @@
#!/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 TASK = "task496-editor-open-parallel-runtime-aggregate-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 dbPath = path.join(dataRoot, "control-plane.sqlite3");
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}`,
MNOTE_WEB_ENABLE_LEGACY_NEXT_COMPAT: "0",
MNOTE_CONTROL_PLANE_DB_PATH: dbPath,
MNOTE_LOCAL_WORKSPACE_BASE_DIR: dataRoot,
CONVEX_SELF_HOSTED_URL: "http://127.0.0.1:9",
NEXT_PUBLIC_CONVEX_URL: "http://127.0.0.1:9",
},
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 requestTimes = {
manifest: 0,
pageAggregate: 0,
};
await page.addInitScript(() => {
window.requestIdleCallback = () => 0;
});
await page.route("**/api/leptos-tiptap-runtime/manifest.json", async (route) => {
if (!requestTimes.manifest) requestTimes.manifest = Date.now();
await new Promise((resolve) => setTimeout(resolve, 1000));
await route.continue();
});
await page.route("**/api/page-aggregate/**", async (route) => {
if (!requestTimes.pageAggregate) requestTimes.pageAggregate = Date.now();
await route.continue();
});
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.writeFileSync(path.join(rootPath, "Target.md"), "# Target\n\nEditor cold open target.\n", "utf8");
const fileTreeUrl = new URL(baseUrl);
const workspaceId = new URL(page.url()).searchParams.get("workspaceId") || "";
if (workspaceId) fileTreeUrl.searchParams.set("workspaceId", workspaceId);
fileTreeUrl.searchParams.set("sourceKind", "local_folder");
fileTreeUrl.searchParams.set("rootUri", rootUri);
fileTreeUrl.searchParams.set("treeView", "filetree");
await page.goto(fileTreeUrl.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 .tree-row[data-local-relative-path="Target.md"] .tree-link').click({
timeout: UI_TIMEOUT_MS,
});
await page.waitForURL((url) => url.pathname.startsWith("/documents/"), { timeout: UI_TIMEOUT_MS });
await page.locator('.document-pane[data-pane-role="primary"] .editor-surface').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
assert(requestTimes.manifest > 0, "应在打开文档时加载 editor runtime manifest");
assert(requestTimes.pageAggregate > 0, "应在打开文档时请求 Page Aggregate");
const aggregateDelayMs = requestTimes.pageAggregate - requestTimes.manifest;
assert(
aggregateDelayMs < 500,
`Page Aggregate fetch 应与 editor runtime load 并行启动,实际晚于 manifest ${aggregateDelayMs}ms`,
);
console.log(JSON.stringify({
ok: true,
task: TASK,
aggregateDelayMs,
requestTimes,
}, null, 2));
} finally {
await browser.close();
server.kill("SIGINT");
fs.rmSync(dataRoot, { recursive: true, force: true });
if (server.exitCode == null) {
setTimeout(() => server.kill("SIGKILL"), 2000).unref();
}
}
}
main().catch((error) => {
console.error(error);
process.exit(1);
});