Complete workbench P0 resource tab cutover
This commit is contained in:
@@ -0,0 +1,235 @@
|
||||
#!/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}:task462`,
|
||||
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 main() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task462-error-placeholder-"));
|
||||
const relativePath = "README.md";
|
||||
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,
|
||||
});
|
||||
|
||||
// ======== Test 1: Open non-existent resource → error placeholder tab ========
|
||||
console.log("Test 1: Open non-existent asset → error placeholder tab");
|
||||
const fakeAssetId = `local-file:nonexistent/error-test-${Date.now()}.md`;
|
||||
|
||||
// Dispatch tree.asset.open with a non-existent local asset
|
||||
await page.evaluate(({ fakeAssetId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: fakeAssetId,
|
||||
documentId: document.body?.dataset?.documentId || "",
|
||||
title: "error-test.md",
|
||||
assetType: "attachment",
|
||||
},
|
||||
}));
|
||||
}, { fakeAssetId });
|
||||
|
||||
// Wait for the error tab to appear (since the file doesn't exist, it should create an error tab)
|
||||
await page.waitForTimeout(1000);
|
||||
|
||||
// Check error placeholder created: the resource tab panel should have an error indicator
|
||||
const errorPanelState = await page.evaluate(() => {
|
||||
const errorPanel = document.querySelector('[data-resource-tab-error="true"]');
|
||||
const activeTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
|
||||
const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
|
||||
// Count how many tabs have error content
|
||||
const errorTabs = Array.from(allResourceTabs).filter(tab => {
|
||||
const identity = tab.getAttribute('data-mnote-main-tab') || '';
|
||||
const panel = document.querySelector(`[data-mnote-resource-tab-panel="${CSS.escape(identity)}"]`);
|
||||
return panel && panel.querySelector('[data-resource-tab-error="true"]');
|
||||
});
|
||||
return {
|
||||
hasErrorPanel: !!errorPanel,
|
||||
errorPanelText: errorPanel?.textContent || "",
|
||||
activeTabExists: !!activeTab,
|
||||
totalResourceTabs: allResourceTabs.length,
|
||||
errorTabCount: errorTabs.length,
|
||||
};
|
||||
});
|
||||
|
||||
console.log(` Error panel state: ${JSON.stringify(errorPanelState)}`);
|
||||
assert.equal(errorPanelState.hasErrorPanel, true, `missing error placeholder: ${JSON.stringify(errorPanelState)}`);
|
||||
assert.match(errorPanelState.errorPanelText, /资源打开失败/, `error panel should explain failure: ${JSON.stringify(errorPanelState)}`);
|
||||
assert.equal(errorPanelState.activeTabExists, true, `error tab should stay active: ${JSON.stringify(errorPanelState)}`);
|
||||
assert.equal(errorPanelState.errorTabCount, 1, `one error tab should be registered: ${JSON.stringify(errorPanelState)}`);
|
||||
|
||||
const pageTabReachable = await page.evaluate(() => {
|
||||
const pageTab = document.querySelector('[data-mnote-main-tab="page"]');
|
||||
return pageTab instanceof HTMLElement;
|
||||
});
|
||||
assert.ok(pageTabReachable, "Page tab should always be present");
|
||||
|
||||
// ======== Test 2: Error tab close button → removes tab ========
|
||||
console.log("Test 2: Close error tab → cleans up");
|
||||
|
||||
// Try to close any open resource tab
|
||||
await page.evaluate(() => {
|
||||
const resourceTab = document.querySelector('.mnote-main-tab.is-active:not([data-mnote-main-tab="page"])');
|
||||
if (resourceTab instanceof HTMLElement) {
|
||||
const closeBtn = resourceTab.querySelector('.mnote-main-tab-close');
|
||||
if (closeBtn instanceof HTMLElement) {
|
||||
closeBtn.click();
|
||||
}
|
||||
}
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
const afterCloseState = await page.evaluate(() => {
|
||||
return {
|
||||
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||
};
|
||||
});
|
||||
console.log(` After close: ${JSON.stringify(afterCloseState)}`);
|
||||
|
||||
// Page tab should be active after closing all resource tabs
|
||||
assert.ok(afterCloseState.pageTabActive, "Page tab should be active after closing error tab");
|
||||
|
||||
// ======== Test 3: Multiple sequential opens with failure ========
|
||||
console.log("Test 3: Sequential failed opens should not cause runaway tabs");
|
||||
|
||||
const fakeIds = [];
|
||||
for (let i = 0; i < 3; i++) {
|
||||
fakeIds.push(`local-file:nonexistent/test-${i}-${Date.now()}.md`);
|
||||
}
|
||||
|
||||
for (const fakeId of fakeIds) {
|
||||
await page.evaluate(({ fakeId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: fakeId,
|
||||
documentId: document.body?.dataset?.documentId || "",
|
||||
title: `test-${fakeId.split("-")[1]}.md`,
|
||||
assetType: "attachment",
|
||||
},
|
||||
}));
|
||||
}, { fakeId });
|
||||
}
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const afterMultipleState = await page.evaluate(() => {
|
||||
return {
|
||||
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||
};
|
||||
});
|
||||
console.log(` After multiple failed opens: ${JSON.stringify(afterMultipleState)}`);
|
||||
|
||||
// Should not have runaway tabs (at most the 3 we opened, some may not create tabs if they fail fast)
|
||||
assert.ok(afterMultipleState.resourceTabs <= fakeIds.length,
|
||||
`Should not exceed ${fakeIds.length} resource tabs: ${afterMultipleState.resourceTabs}`);
|
||||
|
||||
// ======== Test 4: Recover after error state ========
|
||||
console.log("Test 4: Close all error tabs and verify page tab is cleanly active");
|
||||
|
||||
// Close all resource tabs
|
||||
await page.evaluate(() => {
|
||||
const allResourceTabs = document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])');
|
||||
allResourceTabs.forEach(tab => {
|
||||
const closeBtn = tab.querySelector('.mnote-main-tab-close');
|
||||
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||
});
|
||||
});
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const finalState = await page.evaluate(() => {
|
||||
return {
|
||||
resourceTabs: document.querySelectorAll('.mnote-main-tab[data-mnote-main-tab]:not([data-mnote-main-tab="page"])').length,
|
||||
pageTabActive: document.querySelector('[data-mnote-main-tab="page"]')?.classList.contains("is-active") || false,
|
||||
pagePanelHidden: document.querySelector('[data-mnote-page-tab-panel]')?.hidden || false,
|
||||
resourceHostHidden: document.querySelector('[data-mnote-resource-tab-host]')?.hidden ?? true,
|
||||
errorPanels: document.querySelectorAll('[data-resource-tab-error="true"]').length,
|
||||
};
|
||||
});
|
||||
console.log(` Final state: ${JSON.stringify(finalState)}`);
|
||||
|
||||
assert.ok(finalState.pageTabActive, "Page tab should be active after cleanup");
|
||||
assert.equal(finalState.resourceTabs, 0, "All resource tabs should be removed");
|
||||
assert.equal(finalState.errorPanels, 0, "All error panels should be removed");
|
||||
assert.equal(finalState.pagePanelHidden, false, "Page panel should not be hidden");
|
||||
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,368 @@
|
||||
#!/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}:task463`,
|
||||
ownerId,
|
||||
createdAt: new Date().toISOString(),
|
||||
capabilities: ["local_files", "markdown_edit", "asset_upload"],
|
||||
}, null, 2)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
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 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 main() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task463-onlyoffice-resolver-"));
|
||||
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 Office files
|
||||
const officeAssets = {};
|
||||
|
||||
// docx
|
||||
officeAssets.docx = await uploadLocalAsset(
|
||||
page, root, documentId,
|
||||
"report.docx",
|
||||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
Buffer.from("task463 docx probe", "utf8"),
|
||||
"attachment",
|
||||
);
|
||||
|
||||
// pptx
|
||||
officeAssets.pptx = await uploadLocalAsset(
|
||||
page, root, documentId,
|
||||
"slides.pptx",
|
||||
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
||||
Buffer.from("task463 pptx probe", "utf8"),
|
||||
"attachment",
|
||||
);
|
||||
|
||||
// xlsx
|
||||
officeAssets.xlsx = await uploadLocalAsset(
|
||||
page, root, documentId,
|
||||
"data.xlsx",
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
Buffer.from("task463 xlsx probe", "utf8"),
|
||||
"attachment",
|
||||
);
|
||||
|
||||
// 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 1: docx opens in main editor tab with /onlyoffice iframe ========
|
||||
console.log("Test 1: docx opens in main editor tab with /onlyoffice iframe");
|
||||
await page.evaluate(({ asset, documentId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: asset.id,
|
||||
documentId,
|
||||
title: asset.file_name || "report.docx",
|
||||
assetType: asset.asset_type || "attachment",
|
||||
},
|
||||
}));
|
||||
}, { asset: officeAssets.docx, documentId });
|
||||
|
||||
// Wait for office tab to become active
|
||||
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
const officeTabInfo = await page.evaluate(() => {
|
||||
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
const panel = document.querySelector('.mnote-resource-tab-panel:not([hidden])');
|
||||
const iframe = panel?.querySelector('iframe.mnote-resource-tab-frame');
|
||||
return {
|
||||
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||
iframeSrc: iframe?.getAttribute("src") || "",
|
||||
iframeExists: !!iframe,
|
||||
};
|
||||
});
|
||||
console.log(` Office tab: badgeKind=${officeTabInfo.badgeKind}, iframe=${officeTabInfo.iframeSrc}`);
|
||||
|
||||
// docx should have badge kind "word"
|
||||
assert.equal(officeTabInfo.badgeKind, "word", `docx should have badgeKind 'word', got '${officeTabInfo.badgeKind}'`);
|
||||
assert.ok(officeTabInfo.iframeExists, "Office tab should have an iframe");
|
||||
assert.ok(officeTabInfo.iframeSrc.includes("/onlyoffice"), `iframe src should include /onlyoffice: ${officeTabInfo.iframeSrc}`);
|
||||
|
||||
// Parse iframe URL and verify required params
|
||||
const iframeUrl = new URL(officeTabInfo.iframeSrc, BASE_URL);
|
||||
assert.equal(iframeUrl.pathname, "/onlyoffice", `iframe pathname should be /onlyoffice: ${iframeUrl.pathname}`);
|
||||
|
||||
// Check that assetId is in the URL (either in query params or encoded)
|
||||
const iframeAssetId = iframeUrl.searchParams.get("assetId") || "";
|
||||
assert.ok(iframeAssetId, "iframe URL should carry assetId param");
|
||||
assert.ok(iframeUrl.searchParams.has("mode"), "iframe URL should carry mode param");
|
||||
assert.ok(iframeUrl.searchParams.has("fileUrl"), "iframe URL should carry fileUrl param");
|
||||
|
||||
// The fileUrl for local-folder should point to /api/local-folder/files/open
|
||||
const fileUrlParam = iframeUrl.searchParams.get("fileUrl") || "";
|
||||
assert.ok(
|
||||
fileUrlParam.includes("/api/local-folder/files/open") || fileUrlParam.startsWith("/api/"),
|
||||
`fileUrl should use Rust proxy URL: ${fileUrlParam}`
|
||||
);
|
||||
console.log(` fileUrl uses Rust-accessible URL: ${fileUrlParam}`);
|
||||
|
||||
// Close the docx tab
|
||||
await page.evaluate(() => {
|
||||
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// ======== Test 2: pptx opens with ppt badge ========
|
||||
console.log("Test 2: pptx opens with ppt badge");
|
||||
await page.evaluate(({ asset, documentId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: asset.id,
|
||||
documentId,
|
||||
title: asset.file_name || "slides.pptx",
|
||||
assetType: asset.asset_type || "attachment",
|
||||
},
|
||||
}));
|
||||
}, { asset: officeAssets.pptx, documentId });
|
||||
|
||||
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
const pptTabInfo = await page.evaluate(() => {
|
||||
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
return {
|
||||
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||
};
|
||||
});
|
||||
console.log(` PPT tab badge: ${pptTabInfo.badgeKind}`);
|
||||
assert.equal(pptTabInfo.badgeKind, "ppt", `pptx should have badgeKind 'ppt', got '${pptTabInfo.badgeKind}'`);
|
||||
|
||||
// Close pptx tab
|
||||
await page.evaluate(() => {
|
||||
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// ======== Test 3: xlsx opens with sheet badge ========
|
||||
console.log("Test 3: xlsx opens with sheet badge");
|
||||
await page.evaluate(({ asset, documentId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: asset.id,
|
||||
documentId,
|
||||
title: asset.file_name || "data.xlsx",
|
||||
assetType: asset.asset_type || "attachment",
|
||||
},
|
||||
}));
|
||||
}, { asset: officeAssets.xlsx, documentId });
|
||||
|
||||
await page.locator('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]').waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
const xlsxTabInfo = await page.evaluate(() => {
|
||||
const tab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
return {
|
||||
badgeKind: tab?.getAttribute('data-mnote-tab-badge-kind') || "",
|
||||
};
|
||||
});
|
||||
console.log(` XLSX tab badge: ${xlsxTabInfo.badgeKind}`);
|
||||
assert.equal(xlsxTabInfo.badgeKind, "sheet", `xlsx should have badgeKind 'sheet', got '${xlsxTabInfo.badgeKind}'`);
|
||||
|
||||
// Close xlsx tab
|
||||
await page.evaluate(() => {
|
||||
const officeTab = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="office"]');
|
||||
const closeBtn = officeTab?.querySelector('.mnote-main-tab-close');
|
||||
if (closeBtn instanceof HTMLElement) closeBtn.click();
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
// ======== Test 4: new-window opens /onlyoffice with edit mode ========
|
||||
console.log("Test 4: new-window opens /onlyoffice with edit mode");
|
||||
const [officePopup] = await Promise.all([
|
||||
page.waitForEvent("popup", { timeout: UI_TIMEOUT_MS }).catch(() => null),
|
||||
page.evaluate(({ asset, documentId }) => {
|
||||
window.dispatchEvent(new CustomEvent("tree.asset.open", {
|
||||
detail: {
|
||||
assetId: asset.id,
|
||||
documentId,
|
||||
title: asset.file_name || "report.docx",
|
||||
assetType: asset.asset_type || "attachment",
|
||||
openTarget: "new-window",
|
||||
},
|
||||
}));
|
||||
}, { asset: officeAssets.docx, documentId }),
|
||||
]);
|
||||
|
||||
if (officePopup) {
|
||||
await officePopup.waitForLoadState("domcontentloaded", { timeout: UI_TIMEOUT_MS }).catch(() => undefined);
|
||||
const popupUrl = new URL(officePopup.url());
|
||||
console.log(` New-window URL: ${popupUrl.toString()}`);
|
||||
assert.equal(popupUrl.pathname, "/onlyoffice", `new-window pathname should be /onlyoffice: ${popupUrl.pathname}`);
|
||||
|
||||
// new-window should use edit mode
|
||||
const popupMode = popupUrl.searchParams.get("mode") || "";
|
||||
assert.equal(popupMode, "edit", `new-window mode should be 'edit', got '${popupMode}'`);
|
||||
|
||||
// Check assetId is present
|
||||
const popupAssetId = popupUrl.searchParams.get("assetId") || "";
|
||||
assert.ok(popupAssetId, "new-window URL should carry assetId");
|
||||
|
||||
await officePopup.close().catch(() => undefined);
|
||||
} else {
|
||||
console.warn(" No popup triggered — this may mean the run is headless and popup was blocked. Acceptable in CI.");
|
||||
}
|
||||
|
||||
// ======== Test 5: OnlyOffice /onlyoffice page self-test (config URL/document URL/callback URL) ========
|
||||
console.log("Test 5: /onlyoffice page structure validation");
|
||||
const onlyofficeUrl = new URL("/onlyoffice", BASE_URL);
|
||||
onlyofficeUrl.searchParams.set("fileUrl", "/api/local-folder/files/open?rootUri=file:///test&path=doc.docx");
|
||||
onlyofficeUrl.searchParams.set("fileName", "test.docx");
|
||||
onlyofficeUrl.searchParams.set("fileType", "docx");
|
||||
onlyofficeUrl.searchParams.set("assetId", "test-asset-id");
|
||||
onlyofficeUrl.searchParams.set("mode", "edit");
|
||||
|
||||
const response = await page.goto(onlyofficeUrl.toString(), {
|
||||
waitUntil: "domcontentloaded",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
|
||||
// Verify the page rendered
|
||||
const pageContent = await page.evaluate(() => {
|
||||
return {
|
||||
title: document.title,
|
||||
hasFrameContainer: !!document.getElementById("onlyoffice-frame"),
|
||||
hasErrorContainer: !!document.getElementById("onlyoffice-error"),
|
||||
hasScript: typeof window.__MNOTE_ONLYOFFICE_READY__ !== "undefined",
|
||||
initialConfig: typeof window.initial !== "undefined",
|
||||
};
|
||||
});
|
||||
console.log(` /onlyoffice page: ${JSON.stringify(pageContent)}`);
|
||||
|
||||
assert.ok(pageContent.hasFrameContainer, "/onlyoffice should have #onlyoffice-frame container");
|
||||
assert.ok(pageContent.hasErrorContainer, "/onlyoffice should have #onlyoffice-error container");
|
||||
assert.ok(pageContent.hasScript, "/onlyoffice should have runtime script");
|
||||
|
||||
// Verify the config has correct document URL and callback URL source
|
||||
const scriptContent = await page.evaluate(() => {
|
||||
const scripts = document.querySelectorAll("script");
|
||||
const relevant = Array.from(scripts).filter(s => s.textContent && s.textContent.includes("buildCallbackUrl"));
|
||||
const text = relevant.length > 0 ? relevant[0].textContent : "";
|
||||
return {
|
||||
hasCallbackUrlBuilder: text.includes("buildCallbackUrl"),
|
||||
hasResolveDocumentUrl: text.includes("resolveDocumentUrl"),
|
||||
hasProxyLogic: text.includes("/api/onlyoffice/proxy"),
|
||||
snippet: text.substring(0, 200),
|
||||
};
|
||||
});
|
||||
console.log(` Script: hasCallbackUrl=${scriptContent.hasCallbackUrlBuilder}, hasResolveDocumentUrl=${scriptContent.hasResolveDocumentUrl}`);
|
||||
|
||||
assert.ok(scriptContent.hasCallbackUrlBuilder, "OnlyOffice page should define buildCallbackUrl");
|
||||
assert.ok(scriptContent.hasResolveDocumentUrl, "OnlyOffice page should define resolveDocumentUrl");
|
||||
// The proxy logic may not appear if the script template isn't fully rendered - check for proxy handling
|
||||
const hasProxy = scriptContent.hasProxyLogic || pageContent.initialConfig;
|
||||
assert.ok(hasProxy, "OnlyOffice page should have proxy-based URL resolution strategy");
|
||||
|
||||
console.log(JSON.stringify({ ok: true, root, assets: Object.keys(officeAssets) }, 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);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
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 writeWorkspaceManifest(root) {
|
||||
const metadataDir = path.join(root, ".mnote");
|
||||
fs.mkdirSync(metadataDir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(metadataDir, "workspace.json"),
|
||||
`${JSON.stringify({
|
||||
workspaceId: "local-ws:user_real:task464",
|
||||
ownerId: "user_real",
|
||||
createdAt: new Date().toISOString(),
|
||||
capabilities: ["local_files", "tree_commands", "markdown_edit", "asset_upload"],
|
||||
}, null, 2)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
async function postTreeCommand(rootUri, action, documentId) {
|
||||
const response = await fetch(`${BASE_URL}/api/tree/commands`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-mnote-actor-id": "user_real",
|
||||
"x-mnote-actor-type": "user",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action,
|
||||
sourceKind: "local_folder",
|
||||
rootUri,
|
||||
documentId,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json().catch(async () => ({ text: await response.text() }));
|
||||
assert.equal(response.status, 200, `${action} failed: ${JSON.stringify(payload)}`);
|
||||
return payload;
|
||||
}
|
||||
|
||||
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 openTrash(page, rootUri) {
|
||||
const url = new URL(`${BASE_URL}/trash`);
|
||||
url.searchParams.set("sourceKind", "local_folder");
|
||||
url.searchParams.set("rootUri", rootUri);
|
||||
await page.goto(url.toString(), { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
||||
await page.locator('[data-testid="mnote-trash-workbench"][data-trash-source-kind="local_folder"]').waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task464-trash-ui-"));
|
||||
const rootUri = fileUrl(root);
|
||||
const assetId = "local-file:docs/资源.txt";
|
||||
const sourcePath = path.join(root, "docs", "资源.txt");
|
||||
const trashIndexPath = path.join(root, ".mnote", "trash-index.json");
|
||||
fs.mkdirSync(path.join(root, "docs"), { recursive: true });
|
||||
writeWorkspaceManifest(root);
|
||||
fs.writeFileSync(path.join(root, "README.md"), "# Local Root\n", "utf8");
|
||||
fs.writeFileSync(sourcePath, "asset body", "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);
|
||||
|
||||
const archived = await postTreeCommand(rootUri, "delete", assetId);
|
||||
assert.equal(archived.result?.execution?.canonicalCommand, "tree.resource.archive");
|
||||
assert.equal(fs.existsSync(sourcePath), false, "archive 后源文件应移入垃圾箱");
|
||||
|
||||
await openTrash(page, rootUri);
|
||||
const row = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
|
||||
await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||
await row.getByRole("button", { name: "恢复" }).click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
assert.equal(fs.existsSync(sourcePath), true, "UI restore 后源文件应恢复");
|
||||
|
||||
await postTreeCommand(rootUri, "delete", assetId);
|
||||
await openTrash(page, rootUri);
|
||||
const rowAgain = page.locator(`article[data-trash-row="local"][data-trash-entry-id="${assetId}"]`);
|
||||
await rowAgain.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||
page.once("dialog", (dialog) => dialog.accept());
|
||||
await rowAgain.getByRole("button", { name: "彻底删除" }).click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.waitForFunction(() => !document.querySelector('[data-trash-entry-id="local-file:docs/资源.txt"]'), null, {
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
assert.equal(fs.existsSync(sourcePath), false, "UI purge 后源文件不应恢复");
|
||||
const index = fs.existsSync(trashIndexPath) ? fs.readFileSync(trashIndexPath, "utf8") : "";
|
||||
assert.doesNotMatch(index, /local-file:docs\/资源\.txt/, "UI purge 后 trash index 应清理 entry");
|
||||
|
||||
console.log(JSON.stringify({ ok: true, root, assetId }, null, 2));
|
||||
} finally {
|
||||
await context.close().catch(() => undefined);
|
||||
await browser.close().catch(() => undefined);
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error && error.stack ? error.stack : error);
|
||||
process.exit(1);
|
||||
});
|
||||
Reference in New Issue
Block a user