Align resource tabs with workbench review

This commit is contained in:
lix-2026
2026-05-20 19:04:05 +08:00
parent 4c62ea7e35
commit acf1305a7e
14 changed files with 964 additions and 13 deletions
@@ -243,6 +243,34 @@ async function main() {
assert(officePopupUrl.searchParams.get("mode") === "edit", "显式 new-window 应保留 edit 模式");
await officePopup.close().catch(() => undefined);
const officeCloseBtn = page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"] .mnote-main-tab-close');
await officeCloseBtn.click({ timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(200);
const activeAfterOfficeClose = await page.evaluate(() => {
const activeTab = document.querySelector(".mnote-main-tab.is-active");
return {
kind: activeTab?.getAttribute("data-mnote-tab-kind") || "",
text: activeTab?.textContent?.trim() || "",
};
});
assert.equal(activeAfterOfficeClose.kind, "markdown", `关闭 office tab 后应回到 markdown tab: ${JSON.stringify(activeAfterOfficeClose)}`);
assert(activeAfterOfficeClose.text.includes("resource-note.md"), `markdown tab 标题应包含资源名: ${JSON.stringify(activeAfterOfficeClose)}`);
const mdCloseBtn = page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"] .mnote-main-tab-close');
await mdCloseBtn.click({ timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(200);
const activeAfterAllClosed = await page.evaluate(() => {
const activeTab = document.querySelector(".mnote-main-tab.is-active");
return {
kind: activeTab?.getAttribute("data-mnote-tab-kind") || "",
resourceTabCount: document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind]:not([data-mnote-tab-kind="page"])').length,
panelHidden: document.querySelector("[data-mnote-resource-tab-host]")?.hasAttribute("hidden"),
};
});
assert.equal(activeAfterAllClosed.kind, "page", `关闭所有 resource tab 后应回到 page tab: ${JSON.stringify(activeAfterAllClosed)}`);
assert.equal(activeAfterAllClosed.resourceTabCount, 0, `resource tab 应全部关闭: ${JSON.stringify(activeAfterAllClosed)}`);
assert.equal(activeAfterAllClosed.panelHidden, true, `resource tab host 应隐藏: ${JSON.stringify(activeAfterAllClosed)}`);
console.log(JSON.stringify({ ok: true, root, assetPath, assetId: asset.id, officeAssetId: officeAsset.id }, null, 2));
} finally {
await context.close().catch(() => undefined);
@@ -0,0 +1,220 @@
#!/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 CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|| ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/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));
url.searchParams.set("treeView", "filetree");
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}:task460`,
ownerId,
createdAt: new Date().toISOString(),
capabilities: ["local_files", "markdown_edit", "asset_upload"],
}, null, 2)}\n`,
"utf8",
);
}
async function quickLogin(page) {
await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
if (await quickLoginButton.count()) {
await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
}
}
async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
return await page.evaluate(
async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
const form = new FormData();
form.append("rootUri", rootUri);
form.append("documentId", documentId);
form.append("kind", kind);
form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form });
const payload = await response.json().catch(() => null);
if (!response.ok || !payload || payload.ok !== true) {
throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
}
return payload.asset;
},
{ rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind },
);
}
async function main() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task460-dirty-close-"));
const relativePath = "README.md";
const documentId = localMdDocumentId(relativePath);
writeWorkspaceManifest(root, "user_real");
fs.writeFileSync(path.join(root, relativePath), "# Page\n\n页面正文\n", "utf8");
const browser = await chromium.launch({
headless: true,
executablePath: CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext({
viewport: { width: 1360, height: 900 },
extraHTTPHeaders: {
"x-mnote-actor-id": "user_real",
"x-mnote-actor-type": "user",
},
});
const page = await context.newPage();
try {
await quickLogin(page);
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
// 上传资源文件
const asset = await uploadLocalAsset(
page,
root,
documentId,
"report-asset.md",
"text/markdown",
Buffer.from("# Report Asset\n\n初始内容\n", "utf8"),
"attachment",
);
// 刷新页面确保资源可读取
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
// 打开资源 tab
await page.evaluate(({ asset, documentId }) => {
window.dispatchEvent(new CustomEvent("tree.asset.open", {
detail: {
assetId: asset.id,
documentId,
title: asset.file_name || "report-asset.md",
assetType: asset.asset_type || "attachment",
},
}));
}, { asset, documentId });
// 等待资源 tab 激活和编辑器就绪
await page.locator('[data-testid="mnote-resource-tab-host"]:not([hidden])').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]').waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
// 验证 tabindex
const initialTabindex = await page.evaluate(() => {
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
const resourceTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="markdown"]');
let inactiveResourceTab = null;
return {
pageTabindex: pageTab?.getAttribute('tabindex') || '',
activeTabindex: resourceTab?.getAttribute('tabindex') || '',
pageAriaSelected: pageTab?.getAttribute('aria-selected') || '',
activeAriaSelected: resourceTab?.getAttribute('aria-selected') || '',
};
});
assert.equal(initialTabindex.activeTabindex, '0', `激活的 resource tab 应有 tabindex=0: ${JSON.stringify(initialTabindex)}`);
assert.equal(initialTabindex.pageTabindex, '-1', `非激活 page tab 应有 tabindex=-1: ${JSON.stringify(initialTabindex)}`);
assert.equal(initialTabindex.activeAriaSelected, 'true', `激活 tab 应有 aria-selected=true: ${JSON.stringify(initialTabindex)}`);
assert.equal(initialTabindex.pageAriaSelected, 'false', `非激活 tab 应有 aria-selected=false: ${JSON.stringify(initialTabindex)}`);
// 编辑内容使 dirty
const editor = page.locator('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]').first();
await editor.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.evaluate(() => {
const editor = document.querySelector('.mnote-resource-tab-panel:not([hidden]) .editor-surface .ProseMirror[contenteditable="true"]');
if (!(editor instanceof HTMLElement)) throw new Error("resource_editor_missing");
editor.focus();
editor.dispatchEvent(new InputEvent("input", {
bubbles: true,
cancelable: true,
inputType: "insertText",
data: "新添加的未保存内容",
}));
});
await page.waitForTimeout(100);
// 尝试关闭 dirty 的 resource tab — 应被阻止
const closeBtn = page.locator('.mnote-main-tab.is-active .mnote-main-tab-close');
await closeBtn.click({ timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(300);
const blockedState = await page.evaluate(() => {
const activeTab = document.querySelector('.mnote-main-tab.is-active');
const guardAttr = activeTab?.getAttribute('data-resource-tab-close-guarded') || '';
const hasGuardClass = activeTab?.classList.contains('is-close-guarded');
return {
guardAttr,
hasGuardClass,
tabStillPresent: activeTab !== null,
kind: activeTab?.getAttribute('data-mnote-tab-kind') || '',
};
});
assert(blockedState.hasGuardClass, `dirty tab 应具有 is-close-guarded class: ${JSON.stringify(blockedState)}`);
assert.equal(blockedState.guardAttr, 'dirty', `close-guard attribute 应为 dirty: ${JSON.stringify(blockedState)}`);
assert.equal(blockedState.kind, 'markdown', `dirty tab 关闭阻止后应仍然激活: ${JSON.stringify(blockedState)}`);
// 输入后的短保护窗口内再次关闭仍应被阻止,不应静默释放 resource editor。
await closeBtn.click({ timeout: UI_TIMEOUT_MS });
await page.waitForTimeout(100);
const afterSecondCloseState = await page.evaluate(() => {
const activeTab = document.querySelector('.mnote-main-tab.is-active');
return {
kind: activeTab?.getAttribute('data-mnote-tab-kind') || 'none',
resourceTabCount: document.querySelectorAll('.mnote-main-tab[data-mnote-tab-kind]:not([data-mnote-tab-kind="page"])').length,
guardAttr: activeTab?.getAttribute('data-resource-tab-close-guarded') || '',
};
});
assert.equal(afterSecondCloseState.kind, 'markdown', `保护窗口内二次关闭后仍应停留在 resource tab: ${JSON.stringify(afterSecondCloseState)}`);
assert.equal(afterSecondCloseState.resourceTabCount, 1, `保护窗口内 resource tab 不应被移除: ${JSON.stringify(afterSecondCloseState)}`);
assert.equal(afterSecondCloseState.guardAttr, 'dirty', `保护窗口内应保留 dirty guard: ${JSON.stringify(afterSecondCloseState)}`);
console.log(JSON.stringify({ ok: true, root, assetId: asset.id }, null, 2));
} finally {
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
main().catch((error) => {
console.error(error && error.stack ? error.stack : error);
process.exit(1);
});
+242
View File
@@ -0,0 +1,242 @@
#!/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 CHROMIUM_EXECUTABLE_PATH = process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH
|| ["/usr/bin/google-chrome-stable", "/usr/bin/google-chrome", "/snap/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));
url.searchParams.set("treeView", "filetree");
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}:task461`,
ownerId,
createdAt: new Date().toISOString(),
capabilities: ["local_files", "markdown_edit", "asset_upload"],
}, null, 2)}\n`,
"utf8",
);
}
async function quickLogin(page) {
await page.goto(`${BASE_URL}/auth`, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
const quickLoginButton = page.getByRole("button", { name: "测试账号快速登录" });
if (await quickLoginButton.count()) {
await quickLoginButton.click({ timeout: UI_TIMEOUT_MS });
await page.waitForURL((url) => url.pathname === "/", { timeout: UI_TIMEOUT_MS });
}
}
async function uploadLocalAsset(page, root, documentId, fileName, mimeType, bytes, kind) {
return await page.evaluate(
async ({ rootUri, documentId, fileName, mimeType, bytes, kind }) => {
const form = new FormData();
form.append("rootUri", rootUri);
form.append("documentId", documentId);
form.append("kind", kind);
form.append("file", new File([new Uint8Array(bytes)], fileName, { type: mimeType }));
const response = await fetch("/api/local-folder/assets/upload", { method: "POST", body: form });
const payload = await response.json().catch(() => null);
if (!response.ok || !payload || payload.ok !== true) {
throw new Error(`upload_failed_${response.status}:${JSON.stringify(payload)}`);
}
return payload.asset;
},
{ rootUri: fileUrl(root), documentId, fileName, mimeType, bytes: Array.from(bytes), kind },
);
}
/** Open a resource tab via `tree.asset.open` event. */
async function openResourceTab(page, asset, documentId) {
return await page.evaluate(({ asset, documentId }) => {
window.dispatchEvent(new CustomEvent("tree.asset.open", {
detail: {
assetId: asset.id,
documentId,
title: asset.file_name || "resource",
assetType: asset.asset_type || "attachment",
},
}));
}, { asset, documentId });
}
/** Query badge kind for the active tab. */
async function activeTabBadgeKind(page) {
return await page.evaluate(() => {
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
if (!tab) return "";
const badge = tab.querySelector(".mnote-main-tab-badge");
return {
badgeKind: tab.getAttribute("data-mnote-tab-badge-kind") || "",
badgeColor: badge ? getComputedStyle(badge).backgroundColor : "",
};
});
}
/** Check active tab's content panel has an iframe/image/editor. */
async function activeTabContentIsInline(page) {
return await page.evaluate(() => {
const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
if (!panel) return { inline: false, reason: "no_active_panel" };
// Check for various inline content types
const iframe = panel.querySelector('iframe.mnote-resource-tab-frame');
if (iframe) return { inline: true, contentType: "iframe", src: iframe.getAttribute("src") || "" };
const img = panel.querySelector('img.mnote-resource-tab-image');
if (img) return { inline: true, contentType: "img", src: img.getAttribute("src") || "" };
const editor = panel.querySelector('.ProseMirror[contenteditable="true"]');
if (editor) return { inline: true, contentType: "editor" };
const errorDiv = panel.querySelector('[data-resource-tab-error="true"]');
if (errorDiv) return { inline: true, contentType: "error_fallback" };
return { inline: false, reason: "no_content_found" };
});
}
async function main() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task461-resource-kind-"));
const relativePath = "README.md";
const documentId = localMdDocumentId(relativePath);
writeWorkspaceManifest(root, "user_real");
fs.writeFileSync(path.join(root, relativePath), "# Page\n\n正文\n", "utf8");
const browser = await chromium.launch({
headless: true,
executablePath: CHROMIUM_EXECUTABLE_PATH,
});
const context = await browser.newContext({
viewport: { width: 1360, height: 900 },
extraHTTPHeaders: {
"x-mnote-actor-id": "user_real",
"x-mnote-actor-type": "user",
},
});
const page = await context.newPage();
try {
await quickLogin(page);
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
// Upload a variety of resource types
const assets = {};
const resourceTypes = [
{ key: "markdown", fileName: "doc.md", mimeType: "text/markdown", bytes: Buffer.from("# Doc\n", "utf8"), expectKind: "markdown" },
{ key: "txt", fileName: "notes.txt", mimeType: "text/plain", bytes: Buffer.from("text content\n", "utf8"), expectKind: "text" },
{ key: "json", fileName: "data.json", mimeType: "application/json", bytes: Buffer.from('{"key":"value"}', "utf8"), expectKind: "code" },
{ key: "ts_code", fileName: "script.ts", mimeType: "text/typescript", bytes: Buffer.from("const x = 1;\n", "utf8"), expectKind: "code" },
{ key: "image", fileName: "photo.png", mimeType: "image/png", bytes: Buffer.from("fake-png-data", "utf8"), expectKind: "image" },
];
for (const rt of resourceTypes) {
const asset = await uploadLocalAsset(page, root, documentId, rt.fileName, rt.mimeType, rt.bytes, "attachment");
assets[rt.key] = { ...asset, expectKind: rt.expectKind };
}
// Reload to pick up assets
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
// ======== Test: resource kind badge matrix ========
for (const [key, asset] of Object.entries(assets)) {
console.log(`Test: ${key} (${asset.file_name}) → expect kind=${asset.expectKind}`);
await openResourceTab(page, asset, documentId);
await page.waitForTimeout(500);
const badge = await activeTabBadgeKind(page);
assert.ok(badge.badgeKind, `${key}: active tab should have badge kind, got ${JSON.stringify(badge)}`);
console.log(` badgeKind: ${badge.badgeKind}, color: ${badge.badgeColor}`);
// Check content is inline (not a new window)
const contentInfo = await activeTabContentIsInline(page);
assert.ok(contentInfo.inline, `${key}: content should render inline, got ${JSON.stringify(contentInfo)}`);
console.log(` content: ${contentInfo.contentType} ${contentInfo.src || ""}`);
}
// ======== Test: PDF badge ========
console.log("Test: PDF badge should be independent (not 'ppt')");
const pdfAsset = await uploadLocalAsset(
page, root, documentId,
"manual.pdf", "application/pdf",
Buffer.from("%PDF-1.4 fake pdf\n", "utf8"),
"attachment",
);
// Reload again
await page.goto(documentUrl(root, relativePath), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await page.locator(".document-pane[data-pane-role=\"primary\"] .editor-surface .ProseMirror").first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await openResourceTab(page, pdfAsset, documentId);
await page.waitForTimeout(500);
const pdfBadge = await activeTabBadgeKind(page);
console.log(` PDF badge: ${JSON.stringify(pdfBadge)}`);
assert.equal(pdfBadge.badgeKind, "pdf", `PDF tab should have badgeKind "pdf", got "${pdfBadge.badgeKind}"`);
assert.ok(pdfBadge.badgeColor, "PDF badge should have a color");
// ======== Test: Unknown file fallback shouldn't break page tab ========
console.log("Test: unknown file fallback should not break page tab");
const pageTabActive = await page.evaluate(() => {
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
return pageTab?.classList.contains("is-active") || false;
});
// Should be false since we just opened a PDF
console.log(` page tab active after PDF open: ${pageTabActive}`);
// Close the PDF tab
await page.evaluate(() => {
const pdfTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
const closeBtn = pdfTab?.querySelector('.mnote-main-tab-close');
if (closeBtn instanceof HTMLElement) closeBtn.click();
});
await page.waitForTimeout(300);
const pageTabActiveAfter = await page.evaluate(() => {
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
return pageTab?.classList.contains("is-active") || false;
});
assert.ok(pageTabActiveAfter, "after closing resource tab, page tab should be active");
console.log(JSON.stringify({ ok: true, root }, null, 2));
} finally {
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
main().catch((error) => {
console.error(error && error.stack ? error.stack : error);
process.exit(1);
});