feat: complete tree shell cutover and regression coverage

This commit is contained in:
lix-2026
2026-04-18 09:38:16 +08:00
parent d3876e56eb
commit 111a87d4fd
53 changed files with 5440 additions and 516 deletions
-1
View File
@@ -175,7 +175,6 @@ async function runTreeShellRegression(page, requestContext, viewer, target) {
await toggleButton.click({ timeout: UI_TIMEOUT_MS });
await childRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
page.once("dialog", (dialog) => dialog.accept(createdTitle));
const createResponsePromise = page.waitForResponse(
(response) =>
response.url().includes(`${MNOTE_WEB_BASE_URL}/api/tree/commands`) &&
+158
View File
@@ -0,0 +1,158 @@
"use strict";
const { chromium } = require("playwright");
const {
BASE_URL,
UI_TIMEOUT_MS,
assert,
cleanupDocuments,
ensureAuthenticated,
openDocument,
openSectionView,
prepareTempTreeFixture,
} = require("./tree-shell-smoke-helpers");
async function runPrimaryPath(page, fixture) {
const streamRequestPromise = page.waitForRequest(
(request) =>
request.url().includes("/api/stream/events") &&
request.method() === "GET",
{ timeout: UI_TIMEOUT_MS },
);
await openDocument(page, fixture.workspaceId, fixture.parentId);
await openSectionView(page);
const streamRequest = await streamRequestPromise;
const shellHost = page.getByTestId("sidebar-page-tree-shell");
const firstVisibleStart = Date.now();
await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const parentRow = shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.parentId}"]`);
const childRow = shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.childId}"]`);
await parentRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await childRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const firstVisibleMs = Date.now() - firstVisibleStart;
assert(
(await shellHost.locator('iframe[title="mnote-web tree shell"]').count()) === 0,
"Sidebar 主树仍残留 iframe tree shell",
);
const navigateStart = Date.now();
await childRow.getByTestId("page-tree-open").click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => url.toString().includes(`/documents/${fixture.childId}`), {
timeout: UI_TIMEOUT_MS,
});
const navigateMs = Date.now() - navigateStart;
return {
streamUrl: streamRequest.url(),
firstVisibleMs,
navigateMs,
};
}
async function runFallbackPath(context, fixture) {
const page = await context.newPage();
let blockedCount = 0;
await page.route("**/api/stream/events**", async (route) => {
blockedCount += 1;
await route.abort("failed");
});
try {
await openDocument(page, fixture.workspaceId, fixture.parentId);
await openSectionView(page);
const shellHost = page.getByTestId("sidebar-page-tree-shell");
const fallbackStart = Date.now();
await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.parentId}"]`).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.childId}"]`).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const fallbackVisibleMs = Date.now() - fallbackStart;
assert(blockedCount > 0, "未命中 stream fallback 拦截");
assert(
(await shellHost.locator('iframe[title="mnote-web tree shell"]').count()) === 0,
"fallback 路径仍残留 iframe tree shell",
);
return {
blockedCount,
fallbackVisibleMs,
};
} finally {
await page.close().catch(() => undefined);
}
}
async function main() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 1440, height: 960 },
});
const page = await context.newPage();
let caughtError = null;
let result = null;
let fixture = null;
try {
const viewer = await ensureAuthenticated(page, context.request);
fixture = await prepareTempTreeFixture(context.request);
const primary = await runPrimaryPath(page, fixture);
const fallback = await runFallbackPath(context, fixture);
result = {
ok: true,
baseUrl: BASE_URL,
viewerUserId: viewer.userId,
workspaceId: fixture.workspaceId,
parentId: fixture.parentId,
childId: fixture.childId,
primary,
fallback,
};
console.log(JSON.stringify(result, null, 2));
} catch (error) {
caughtError = error;
} finally {
if (fixture) {
try {
await cleanupDocuments(context.request, fixture.createdIds);
} catch (cleanupError) {
if (!caughtError) {
caughtError = cleanupError;
} else {
console.error(
`清理临时页面失败:${
cleanupError instanceof Error
? cleanupError.stack || cleanupError.message
: String(cleanupError)
}`,
);
}
}
}
await page.close().catch(() => undefined);
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
if (caughtError) {
throw caughtError;
}
}
main().catch((error) => {
console.error(error instanceof Error ? error.stack || error.message : String(error));
process.exit(1);
});
+188
View File
@@ -0,0 +1,188 @@
"use strict";
const { chromium } = require("playwright");
const {
BASE_URL,
UI_TIMEOUT_MS,
assert,
cleanupDocuments,
ensureAuthenticated,
ensurePageOptionsVisible,
openDocument,
openFilesystemView,
openSectionView,
prepareTempTreeFixture,
} = require("./tree-shell-smoke-helpers");
async function runPageTreeChecks(page, fixture) {
await openDocument(page, fixture.workspaceId, fixture.parentId);
await openSectionView(page);
const shellHost = page.getByTestId("sidebar-page-tree-shell");
await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.parentId}"]`).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await shellHost.locator(`[data-testid="page-tree-row"][data-node-id="${fixture.childId}"]`).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
return {
pageTreeVisible: true,
};
}
async function runFileTreeChecks(page, fixture) {
await openFilesystemView(page);
const shellHost = page.getByTestId("sidebar-file-tree-shell");
const openStart = Date.now();
await shellHost.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const parentDocRow = shellHost.locator(`[data-testid="filetree-doc-row"][data-doc-id="${fixture.parentId}"]`).first();
const childDocRow = shellHost.locator(`[data-testid="filetree-doc-row"][data-doc-id="${fixture.childId}"]`).first();
const parentIndexRow = shellHost.locator(`[data-testid="filetree-index-row"][data-doc-id="${fixture.parentId}"]`).first();
await parentDocRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await childDocRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await parentIndexRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const filetreeVisibleMs = Date.now() - openStart;
assert(
(await shellHost.locator('iframe[title="mnote-web tree shell"]').count()) === 0,
"文件树主路径仍残留 iframe tree shell",
);
const navigateStart = Date.now();
await childDocRow.click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => url.toString().includes(`/documents/${fixture.childId}`), {
timeout: UI_TIMEOUT_MS,
});
const filetreeNavigateMs = Date.now() - navigateStart;
return {
filetreeVisibleMs,
filetreeNavigateMs,
};
}
async function runPickerChecks(page, fixture) {
await ensurePageOptionsVisible(page);
const openButton = page.getByRole("button", { name: "移动/嵌入到..." });
await openButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const openStart = Date.now();
await openButton.click({ timeout: UI_TIMEOUT_MS });
const dialog = page.getByRole("dialog");
await dialog.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const pickerSurface = dialog.getByTestId("tree-picker-surface");
await pickerSurface.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const pickerVisibleMs = Date.now() - openStart;
assert(
(await dialog.locator('iframe[title="mnote-web tree shell"]').count()) === 0,
"picker 默认路径仍残留 iframe tree shell",
);
const rootPick = dialog.getByTestId("tree-picker-root");
await rootPick.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.keyboard.press("Escape");
await dialog.waitFor({ state: "hidden", timeout: UI_TIMEOUT_MS });
await openButton.click({ timeout: UI_TIMEOUT_MS });
await dialog.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const searchInput = dialog.getByPlaceholder("移动到...");
await searchInput.fill(fixture.childTitle, { timeout: UI_TIMEOUT_MS });
const searchStart = Date.now();
await page.waitForTimeout(1000);
const nextErrorOverlay = page.locator('[data-nextjs-dialog-content="true"]');
assert(
(await nextErrorOverlay.count()) === 0,
"picker 搜索触发了前端运行时错误",
);
const searchButtons = dialog.getByRole("button");
const emptyState = dialog.getByText("没有匹配结果");
const hasSearchOutcome =
(await searchButtons.count()) > 0 || (await emptyState.count()) > 0;
assert(hasSearchOutcome, "picker 搜索后既没有结果也没有空态提示");
const pickerSearchMs = Date.now() - searchStart;
await page.keyboard.press("Escape");
await dialog.waitFor({ state: "hidden", timeout: UI_TIMEOUT_MS });
return {
pickerVisibleMs,
pickerSearchMs,
};
}
async function main() {
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({
viewport: { width: 1440, height: 960 },
});
const page = await context.newPage();
let caughtError = null;
let fixture = null;
try {
const viewer = await ensureAuthenticated(page, context.request);
fixture = await prepareTempTreeFixture(context.request);
const pageTree = await runPageTreeChecks(page, fixture);
const filetree = await runFileTreeChecks(page, fixture);
const picker = await runPickerChecks(page, fixture);
console.log(
JSON.stringify(
{
ok: true,
baseUrl: BASE_URL,
viewerUserId: viewer.userId,
workspaceId: fixture.workspaceId,
parentId: fixture.parentId,
childId: fixture.childId,
pageTree,
filetree,
picker,
},
null,
2,
),
);
} catch (error) {
caughtError = error;
} finally {
if (fixture) {
try {
await cleanupDocuments(context.request, fixture.createdIds);
} catch (cleanupError) {
if (!caughtError) {
caughtError = cleanupError;
} else {
console.error(
`清理临时页面失败:${
cleanupError instanceof Error
? cleanupError.stack || cleanupError.message
: String(cleanupError)
}`,
);
}
}
}
await page.close().catch(() => undefined);
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
if (caughtError) {
throw caughtError;
}
}
main().catch((error) => {
console.error(error instanceof Error ? error.stack || error.message : String(error));
process.exit(1);
});
+183
View File
@@ -0,0 +1,183 @@
"use strict";
const BASE_URL = (process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
const MNOTE_WEB_BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || "http://127.0.0.1:3104").replace(/\/+$/, "");
const REQUEST_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_TIMEOUT_MS || 20_000);
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
const TEST_LOGIN_BUTTON_NAME = "测试账号快速登录";
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}
async function requestJson(requestContext, path, init = {}) {
const response = await requestContext.fetch(`${BASE_URL}${path}`, {
...init,
headers:
init.data !== undefined
? {
"content-type": "application/json",
...(init.headers || {}),
}
: {
...(init.headers || {}),
},
timeout: REQUEST_TIMEOUT_MS,
});
const text = await response.text();
let payload = null;
try {
payload = text ? JSON.parse(text) : null;
} catch {
payload = text;
}
if (!response.ok()) {
throw new Error(
`${path} 请求失败: ${response.status()} ${response.statusText()} ${
typeof payload === "string" ? payload : JSON.stringify(payload)
}`,
);
}
const contentType = response.headers()["content-type"] || "";
if (!contentType.includes("application/json")) {
const snippet =
typeof payload === "string"
? payload.slice(0, 200)
: JSON.stringify(payload).slice(0, 200);
throw new Error(`${path} 返回了非 JSON 内容:${snippet}`);
}
return payload;
}
async function createTempDocument(requestContext, parentId = null) {
const payload = await requestJson(requestContext, "/api/documents/create", {
method: "POST",
data: { parentId },
});
assert(payload && typeof payload.id === "string", "创建临时页面失败:缺少 id");
assert(payload && typeof payload.workspace_id === "string", "创建临时页面失败:缺少 workspace_id");
return {
documentId: payload.id,
workspaceId: payload.workspace_id,
};
}
async function renameDocument(requestContext, workspaceId, documentId, title) {
await requestJson(requestContext, "/api/documents/title", {
method: "POST",
data: {
workspaceId,
documentId,
title,
},
});
}
async function purgeDocument(requestContext, documentId) {
await requestJson(requestContext, "/api/documents/purge", {
method: "POST",
data: { documentId },
});
}
async function getViewerIdentity(requestContext) {
const payload = await requestJson(requestContext, "/api/auth/whoami", { method: "GET" });
assert(payload && typeof payload.userId === "string" && payload.userId, "获取当前用户失败:缺少 userId");
return payload;
}
async function ensureAuthenticated(page, requestContext) {
await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
if (page.url().includes("/auth")) {
const quickLoginButton = page.getByRole("button", { name: TEST_LOGIN_BUTTON_NAME });
await quickLoginButton.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => !url.toString().includes("/auth"), {
timeout: UI_TIMEOUT_MS,
});
}
return await getViewerIdentity(requestContext);
}
async function prepareTempTreeFixture(requestContext) {
const uniqueSuffix = Date.now().toString();
const parentTitle = `task-tree-parent-${uniqueSuffix}`;
const childTitle = `task-tree-child-${uniqueSuffix}`;
const parent = await createTempDocument(requestContext, null);
const child = await createTempDocument(requestContext, parent.documentId);
await renameDocument(requestContext, parent.workspaceId, parent.documentId, parentTitle);
await renameDocument(requestContext, parent.workspaceId, child.documentId, childTitle);
return {
uniqueSuffix,
workspaceId: parent.workspaceId,
parentId: parent.documentId,
childId: child.documentId,
parentTitle,
childTitle,
createdIds: [parent.documentId, child.documentId],
};
}
async function cleanupDocuments(requestContext, createdIds) {
for (const documentId of [...createdIds].reverse()) {
await purgeDocument(requestContext, documentId);
}
}
async function openDocument(page, workspaceId, documentId) {
const url = `${BASE_URL}/documents/${documentId}?workspaceId=${encodeURIComponent(workspaceId)}`;
await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
return url;
}
async function openSectionView(page) {
const button = page.getByRole("button", { name: "分组" });
await button.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await button.click({ timeout: UI_TIMEOUT_MS });
}
async function openFilesystemView(page) {
const button = page.getByRole("button", { name: "文件" });
await button.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await button.click({ timeout: UI_TIMEOUT_MS });
}
async function ensurePageOptionsVisible(page) {
const toggle = page.getByRole("button", { name: /显示页面选项|隐藏页面选项/ });
await toggle.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const label = (await toggle.getAttribute("aria-label")) || "";
if (label.includes("显示")) {
await toggle.click({ timeout: UI_TIMEOUT_MS });
}
}
module.exports = {
BASE_URL,
MNOTE_WEB_BASE_URL,
REQUEST_TIMEOUT_MS,
UI_TIMEOUT_MS,
assert,
cleanupDocuments,
createTempDocument,
ensureAuthenticated,
ensurePageOptionsVisible,
getViewerIdentity,
openDocument,
openFilesystemView,
openSectionView,
prepareTempTreeFixture,
purgeDocument,
renameDocument,
requestJson,
};