chore: 收口 review 执行清单与 runtime 验证
- 补齐 design/10-review 执行清单、验收标准与相关设计治理记录 - 迁移已完成的 tree、mindmap、runtime fallback、AI kernel 等设计和缺陷条目 - 推进 Rust Web runtime、tree/sidebar、page aggregate、mindmap 与 OnlyOffice 路由侧验证支撑 - 增加 task177-task180 smoke/audit 脚本及前端相关测试覆盖
This commit is contained in:
@@ -126,7 +126,7 @@ function attachNetworkCapture(page, label, records) {
|
||||
url,
|
||||
status,
|
||||
requestBody: request.postData() || null,
|
||||
responseText: responseText ? responseText.slice(0, 4000) : null,
|
||||
responseText: responseText ? responseText.slice(0, 12000) : null,
|
||||
});
|
||||
});
|
||||
page.on("requestfailed", (request) => {
|
||||
@@ -178,6 +178,28 @@ async function readPageState(page) {
|
||||
const assetRows = Array.from(document.querySelectorAll("#sidebar-file-tree-root [data-asset-id]"))
|
||||
.map((node) => (node instanceof HTMLElement ? node.getAttribute("data-asset-id") || "" : ""))
|
||||
.filter(Boolean);
|
||||
const fileTreeAssetRowElements = Array.from(document.querySelectorAll("#sidebar-file-tree-root [data-asset-id]"))
|
||||
.map((node) => (node instanceof HTMLElement ? node.closest(".tree-row") || node : null))
|
||||
.filter((node, index, rows) => node instanceof HTMLElement && rows.indexOf(node) === index);
|
||||
const mindmapRows = fileTreeAssetRowElements
|
||||
.filter((node) => {
|
||||
if (!(node instanceof HTMLElement)) return false;
|
||||
const objectKind = node.getAttribute("data-object-kind") || "";
|
||||
const objectIdentity = node.getAttribute("data-object-identity") || "";
|
||||
const assetId = node.getAttribute("data-asset-id") || "";
|
||||
return objectKind === "mindmap" || objectIdentity.includes('"objectKind":"mindmap"') || assetId.startsWith("mindmap");
|
||||
})
|
||||
.map((node) => {
|
||||
const element = node;
|
||||
return {
|
||||
rowId: element.getAttribute("data-row-id") || "",
|
||||
documentId: element.getAttribute("data-document-id") || element.getAttribute("data-doc-id") || "",
|
||||
assetId: element.getAttribute("data-asset-id") || "",
|
||||
objectKind: element.getAttribute("data-object-kind") || "",
|
||||
objectIdentity: element.getAttribute("data-object-identity") || "",
|
||||
title: element.textContent || "",
|
||||
};
|
||||
});
|
||||
return {
|
||||
url: window.location.href,
|
||||
bodyText: (document.body?.innerText || "").slice(0, 8000),
|
||||
@@ -212,6 +234,7 @@ async function readPageState(page) {
|
||||
mindmapLoadingEvents: window.__MNOTE_MINDMAP_LOADING_EVENTS__ || [],
|
||||
fileTreeText: (document.getElementById("sidebar-file-tree-root")?.textContent || "").slice(0, 4000),
|
||||
fileTreeAssetIds: assetRows,
|
||||
fileTreeMindmapRows: mindmapRows,
|
||||
treeEvents: window.__MNOTE_SMOKE_TREE_EVENTS__ || [],
|
||||
};
|
||||
});
|
||||
@@ -260,6 +283,24 @@ function stableJson(value) {
|
||||
return JSON.stringify(value ?? null);
|
||||
}
|
||||
|
||||
async function waitForMindmapRuntimeViewSettled(page, mindmapId, label) {
|
||||
let previous = await readMindmapRuntimeStabilityState(page, mindmapId);
|
||||
for (let index = 0; index < 12; index += 1) {
|
||||
await page.waitForTimeout(350);
|
||||
const current = await readMindmapRuntimeStabilityState(page, mindmapId);
|
||||
if (
|
||||
stableJson(current.viewTransform) === stableJson(previous.viewTransform) &&
|
||||
stableJson(current.topicRect) === stableJson(previous.topicRect) &&
|
||||
current.runtimeMountCount === previous.runtimeMountCount &&
|
||||
current.runtimeProjectionApplyCount === previous.runtimeProjectionApplyCount
|
||||
) {
|
||||
return current;
|
||||
}
|
||||
previous = current;
|
||||
}
|
||||
throw new Error(`mindmap_runtime_view_not_settled:${label}`);
|
||||
}
|
||||
|
||||
function rectCenter(rect) {
|
||||
if (!rect) return null;
|
||||
return {
|
||||
@@ -271,7 +312,7 @@ function rectCenter(rect) {
|
||||
function centerDistance(a, b) {
|
||||
const ca = rectCenter(a);
|
||||
const cb = rectCenter(b);
|
||||
if (!ca || !cb) return Number.POSITIVE_INFINITY;
|
||||
if (!ca || !cb) return 0;
|
||||
return Math.hypot(ca.x - cb.x, ca.y - cb.y);
|
||||
}
|
||||
|
||||
@@ -324,6 +365,7 @@ async function dispatchSyntheticMindmapTreeSignal(page, documentId, mindmapId, e
|
||||
}
|
||||
|
||||
async function assertMindmapRuntimeDoesNotRefreshForLiveSignals(page, documentId, mindmapId, failures, label) {
|
||||
await waitForMindmapRuntimeViewSettled(page, mindmapId, label);
|
||||
const before = await readPageState(page);
|
||||
const beforeRuntime = await readMindmapRuntimeStabilityState(page, mindmapId);
|
||||
if (before.hasMindmapError || before.hasMindmapLoading || !before.runtimeReady) {
|
||||
@@ -551,6 +593,56 @@ async function assertFileTreeMindmapOpenUsesObjectShell(page, documentId, mindma
|
||||
return { opened, state: readyState };
|
||||
}
|
||||
|
||||
async function assertSingleMindmapAssetRowStable(page, documentId, mindmapId, expectedObjectIdentity, failures, label) {
|
||||
await openFilesystemView(page);
|
||||
const state = await readPageState(page);
|
||||
const rows = state.fileTreeMindmapRows.filter((row) => row.documentId === documentId);
|
||||
if (rows.length !== 1) {
|
||||
failures.push({
|
||||
code: "filetree_mindmap_asset_row_count_changed",
|
||||
label,
|
||||
expectedCount: 1,
|
||||
actualCount: rows.length,
|
||||
rows,
|
||||
state,
|
||||
});
|
||||
return { ok: false, rows, state, objectIdentity: expectedObjectIdentity };
|
||||
}
|
||||
const row = rows[0];
|
||||
if (row.assetId !== mindmapId) {
|
||||
failures.push({
|
||||
code: "filetree_mindmap_asset_id_changed",
|
||||
label,
|
||||
expectedAssetId: mindmapId,
|
||||
row,
|
||||
state,
|
||||
});
|
||||
}
|
||||
if (!row.objectIdentity.includes(`"objectKind":"mindmap"`) || !row.objectIdentity.includes(`"assetId":"${mindmapId}"`)) {
|
||||
failures.push({
|
||||
code: "filetree_mindmap_asset_identity_invalid",
|
||||
label,
|
||||
row,
|
||||
state,
|
||||
});
|
||||
}
|
||||
if (expectedObjectIdentity && row.objectIdentity !== expectedObjectIdentity) {
|
||||
failures.push({
|
||||
code: "filetree_mindmap_asset_identity_changed",
|
||||
label,
|
||||
expectedObjectIdentity,
|
||||
row,
|
||||
state,
|
||||
});
|
||||
}
|
||||
return {
|
||||
ok: failures.length === 0,
|
||||
rows,
|
||||
state,
|
||||
objectIdentity: row.objectIdentity,
|
||||
};
|
||||
}
|
||||
|
||||
async function assertFileTreeIndexOpenUsesPageAggregate(page, documentId, mindmapId, failures) {
|
||||
await openFilesystemView(page);
|
||||
const opened = await page.evaluate(
|
||||
@@ -942,6 +1034,77 @@ function findBadRecord(records) {
|
||||
});
|
||||
}
|
||||
|
||||
function parseJsonMaybe(value) {
|
||||
if (typeof value !== "string" || !value.trim()) return null;
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function assertMindmapCommandApplyArtifactsDoNotTouchTreeResource(records, failures) {
|
||||
const commandApplyResponses = records.filter((record) => {
|
||||
if (record.type !== "response" || record.method !== "POST" || !record.url.includes("/api/mindmap/")) {
|
||||
return false;
|
||||
}
|
||||
const requestBody = parseJsonMaybe(record.requestBody);
|
||||
return requestBody?.commandName === "mindmap.command.apply";
|
||||
});
|
||||
if (commandApplyResponses.length === 0) {
|
||||
failures.push({ code: "mindmap_command_apply_artifact_response_missing" });
|
||||
return { checked: 0, artifacts: [] };
|
||||
}
|
||||
|
||||
const artifacts = [];
|
||||
let parsedCount = 0;
|
||||
let skippedReadFailures = 0;
|
||||
for (const record of commandApplyResponses) {
|
||||
const responseBody = parseJsonMaybe(record.responseText);
|
||||
const eventType = String(responseBody?.artifacts?.domainEvent?.eventType || "");
|
||||
const streamDelta = responseBody?.artifacts?.domainEvent?.payload?.streamDelta || null;
|
||||
const streamOp = String(streamDelta?.op || "");
|
||||
const summary = {
|
||||
url: record.url,
|
||||
commandName: responseBody?.commandName || "",
|
||||
eventType,
|
||||
streamOp,
|
||||
};
|
||||
artifacts.push(summary);
|
||||
if (!responseBody) {
|
||||
if (String(record.responseText || "").startsWith("<<read_response_failed:")) {
|
||||
skippedReadFailures += 1;
|
||||
continue;
|
||||
}
|
||||
failures.push({
|
||||
code: "mindmap_command_apply_artifact_response_unparseable",
|
||||
record,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
parsedCount += 1;
|
||||
if (eventType.startsWith("tree.resource.")) {
|
||||
failures.push({
|
||||
code: "mindmap_command_apply_used_tree_resource_event",
|
||||
summary,
|
||||
});
|
||||
}
|
||||
if (streamOp === "resync_required") {
|
||||
failures.push({
|
||||
code: "mindmap_command_apply_used_tree_resync_delta",
|
||||
summary,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (parsedCount === 0) {
|
||||
failures.push({
|
||||
code: "mindmap_command_apply_artifact_response_all_unparseable",
|
||||
skippedReadFailures,
|
||||
});
|
||||
}
|
||||
return { checked: parsedCount, skippedReadFailures, artifacts };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await fs.mkdir(OUTPUT_DIR, { recursive: true });
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
@@ -1005,6 +1168,15 @@ async function main() {
|
||||
result.mindmapId,
|
||||
failures,
|
||||
);
|
||||
result.fileTreeMindmapRowsAfterInsert = await assertSingleMindmapAssetRowStable(
|
||||
pageA,
|
||||
doc.documentId,
|
||||
result.mindmapId,
|
||||
null,
|
||||
failures,
|
||||
"after-insert",
|
||||
);
|
||||
const stableMindmapObjectIdentity = result.fileTreeMindmapRowsAfterInsert.objectIdentity || "";
|
||||
await waitForMindmapReady(pageA, "after-filetree-mindmap-open");
|
||||
await pageA.waitForTimeout(1000);
|
||||
screenshots.push(await screenshot(pageA, "01-browser-a-after-insert"));
|
||||
@@ -1034,6 +1206,16 @@ async function main() {
|
||||
"after-topic-return",
|
||||
);
|
||||
result.browserAAfterReturnToMindmapDocument = await readPageState(pageA);
|
||||
result.fileTreeMindmapRowsAfterTopicReturn = await assertSingleMindmapAssetRowStable(
|
||||
pageA,
|
||||
doc.documentId,
|
||||
result.mindmapId,
|
||||
stableMindmapObjectIdentity,
|
||||
failures,
|
||||
"after-topic-return",
|
||||
);
|
||||
await openDocument(pageA, doc.workspaceId, doc.documentId);
|
||||
await waitForMindmapReady(pageA, "return-after-topic-row-check");
|
||||
result.runtimeTextAfterReturnToMindmapDocument = await readMindmapRuntimeTextState(
|
||||
pageA,
|
||||
result.mindmapId,
|
||||
@@ -1078,6 +1260,16 @@ async function main() {
|
||||
"after-draft-return",
|
||||
);
|
||||
result.runtimeTextAfterDraftReturn = await readMindmapRuntimeTextState(pageA, result.mindmapId, draftTopicText);
|
||||
result.fileTreeMindmapRowsAfterDraftReturn = await assertSingleMindmapAssetRowStable(
|
||||
pageA,
|
||||
doc.documentId,
|
||||
result.mindmapId,
|
||||
stableMindmapObjectIdentity,
|
||||
failures,
|
||||
"after-draft-return",
|
||||
);
|
||||
await openDocument(pageA, doc.workspaceId, doc.documentId);
|
||||
await waitForMindmapReady(pageA, "return-after-draft-row-check");
|
||||
if (!result.runtimeTextAfterDraftReturn.includesExpectedText) {
|
||||
failures.push({
|
||||
code: "mindmap_uncommitted_text_edit_lost_after_page_switch",
|
||||
@@ -1093,6 +1285,7 @@ async function main() {
|
||||
failures,
|
||||
"browser-a-after-topic-edit",
|
||||
);
|
||||
result.commandApplyArtifactSemantics = assertMindmapCommandApplyArtifactsDoNotTouchTreeResource(records, failures);
|
||||
result.longLanguageEdit = await assertLongLanguageEditSurvivesLiveRefresh(
|
||||
pageA,
|
||||
contextA.request,
|
||||
@@ -1113,6 +1306,16 @@ async function main() {
|
||||
result.mindmapId,
|
||||
failures,
|
||||
);
|
||||
result.fileTreeMindmapRowsAfterLongLanguageEdit = await assertSingleMindmapAssetRowStable(
|
||||
pageA,
|
||||
doc.documentId,
|
||||
result.mindmapId,
|
||||
stableMindmapObjectIdentity,
|
||||
failures,
|
||||
"after-long-language-edit",
|
||||
);
|
||||
await openDocument(pageA, doc.workspaceId, doc.documentId);
|
||||
await waitForMindmapReady(pageA, "return-after-long-language-row-check");
|
||||
if (result.longLanguageEdit && result.longLanguageEdit.longText) {
|
||||
result.runtimeTextAfterMindmapReopen = await readMindmapRuntimeTextState(
|
||||
pageA,
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert");
|
||||
const { chromium } = require("playwright");
|
||||
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");
|
||||
|
||||
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
|
||||
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
|
||||
|
||||
async function readJsonResponse(response, label) {
|
||||
const text = await response.text();
|
||||
let payload = null;
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
|
||||
}
|
||||
assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function postTreeCommand(body, label) {
|
||||
const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const payload = await readJsonResponse(response, label);
|
||||
const result = payload && typeof payload.result === "object" ? payload.result : null;
|
||||
assert(result, `${label} 缺少 result`);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function createTempPage(title, extra = {}) {
|
||||
const result = await postTreeCommand(
|
||||
{
|
||||
action: "create",
|
||||
title,
|
||||
...extra,
|
||||
},
|
||||
`创建临时页面 ${title}`,
|
||||
);
|
||||
assert(result.documentId, `创建临时页面 ${title} 缺少 documentId`);
|
||||
assert(result.workspaceId, `创建临时页面 ${title} 缺少 workspaceId`);
|
||||
return {
|
||||
documentId: result.documentId,
|
||||
workspaceId: result.workspaceId,
|
||||
title,
|
||||
};
|
||||
}
|
||||
|
||||
async function purgeTempPage(target) {
|
||||
if (!target?.documentId || !target?.workspaceId) return;
|
||||
await postTreeCommand(
|
||||
{
|
||||
action: "purge",
|
||||
workspaceId: target.workspaceId,
|
||||
documentId: target.documentId,
|
||||
},
|
||||
`清理临时页面 ${target.documentId}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForSidebarRow(page, documentId) {
|
||||
const row = page.locator(`[data-testid="wolai-sidebar-row"][data-node-id="${documentId}"]`).first();
|
||||
await row.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||
return row;
|
||||
}
|
||||
|
||||
async function armTreeLiveProbe(page) {
|
||||
await page.evaluate(() => {
|
||||
const key = "__task177TreeLiveEvents";
|
||||
window[key] = [];
|
||||
if (window.__task177TreeLiveProbeArmed) return;
|
||||
const push = (kind, detail) => {
|
||||
const payload = detail && typeof detail === "object" && "payload" in detail ? detail.payload : detail;
|
||||
window[key].push({
|
||||
kind,
|
||||
applied: document.documentElement.getAttribute("data-mnote-tree-live-applied") || "",
|
||||
payload,
|
||||
});
|
||||
if (window[key].length > 40) window[key].shift();
|
||||
};
|
||||
window.addEventListener("tree:delta", (event) => push("delta", event.detail));
|
||||
window.addEventListener("tree:resync", (event) => push("resync", event.detail));
|
||||
window.__task177TreeLiveProbeArmed = true;
|
||||
});
|
||||
}
|
||||
|
||||
async function resetTreeLiveProbe(page) {
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.removeAttribute("data-mnote-tree-live-applied");
|
||||
document.documentElement.removeAttribute("data-mnote-tree-live-apply-error");
|
||||
window.__task177TreeLiveEvents = [];
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForTreeLivePayload(page, label, op, documentId) {
|
||||
await page.waitForFunction(
|
||||
({ expectedOp, expectedDocumentId }) => {
|
||||
const events = Array.isArray(window.__task177TreeLiveEvents) ? window.__task177TreeLiveEvents : [];
|
||||
return events.some((event) => {
|
||||
if (!event || (event.kind !== "delta" && event.kind !== "resync")) return false;
|
||||
const applied = event.applied || document.documentElement.getAttribute("data-mnote-tree-live-applied") || "";
|
||||
if (applied !== "delta" && applied !== "resync") return false;
|
||||
try {
|
||||
const raw = JSON.stringify(event.payload || {});
|
||||
return raw.includes(expectedOp) && raw.includes(expectedDocumentId);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
},
|
||||
{ expectedOp: op, expectedDocumentId: documentId },
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
const state = await page.evaluate(() => ({
|
||||
applied: document.documentElement.getAttribute("data-mnote-tree-live-applied") || "",
|
||||
error: document.documentElement.getAttribute("data-mnote-tree-live-apply-error") || "",
|
||||
}));
|
||||
assert(["delta", "resync"].includes(state.applied), `${label} 应应用 delta/resync,实际: ${JSON.stringify(state)}`);
|
||||
assert(!state.error, `${label} 不应留下 live apply error: ${state.error}`);
|
||||
}
|
||||
|
||||
async function assertPageStillStable(page, rootTitle) {
|
||||
await page.waitForFunction(
|
||||
(title) => {
|
||||
const headerText = document.querySelector("header")?.textContent ?? "";
|
||||
const input = document.querySelector('[data-page-title-input="true"][data-pane-role="primary"]');
|
||||
const titleValue =
|
||||
input instanceof HTMLInputElement || input instanceof HTMLTextAreaElement ? input.value : "";
|
||||
return headerText.includes(title) && titleValue.includes(title);
|
||||
},
|
||||
rootTitle,
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const suffix = Date.now().toString(36);
|
||||
const rootTitle = `task177-root-${suffix}`;
|
||||
const childTitle = `task177-child-${suffix}`;
|
||||
const targetTitle = `task177-target-${suffix}`;
|
||||
const archiveTitle = `task177-archive-${suffix}`;
|
||||
let rootPage = null;
|
||||
let childPage = null;
|
||||
let targetPage = null;
|
||||
let archivedPage = null;
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
rootPage = await createTempPage(rootTitle);
|
||||
childPage = await createTempPage(childTitle, {
|
||||
workspaceId: rootPage.workspaceId,
|
||||
parentId: rootPage.documentId,
|
||||
});
|
||||
targetPage = await createTempPage(targetTitle, {
|
||||
workspaceId: rootPage.workspaceId,
|
||||
parentId: rootPage.documentId,
|
||||
});
|
||||
archivedPage = await createTempPage(archiveTitle, {
|
||||
workspaceId: rootPage.workspaceId,
|
||||
parentId: rootPage.documentId,
|
||||
});
|
||||
|
||||
const rootUrl = `${BASE_URL}/documents/${encodeURIComponent(rootPage.documentId)}?workspaceId=${encodeURIComponent(rootPage.workspaceId)}`;
|
||||
const response = await page.goto(rootUrl, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
||||
assert(response, "文档页没有返回响应");
|
||||
assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);
|
||||
assert.equal(response.headers()["x-mnote-web-owner"], "mnote-web", "文档页必须由 mnote-web 拥有");
|
||||
|
||||
await waitForSidebarRow(page, rootPage.documentId);
|
||||
await waitForSidebarRow(page, childPage.documentId);
|
||||
await waitForSidebarRow(page, targetPage.documentId);
|
||||
await waitForSidebarRow(page, archivedPage.documentId);
|
||||
await assertPageStillStable(page, rootTitle);
|
||||
await armTreeLiveProbe(page);
|
||||
|
||||
await resetTreeLiveProbe(page);
|
||||
await postTreeCommand(
|
||||
{
|
||||
action: "move",
|
||||
workspaceId: rootPage.workspaceId,
|
||||
documentId: childPage.documentId,
|
||||
parentId: targetPage.documentId,
|
||||
sortOrder: 0,
|
||||
},
|
||||
"移动临时子页面",
|
||||
);
|
||||
await waitForTreeLivePayload(page, "移动后 tree live", "move_document", childPage.documentId);
|
||||
await page.waitForFunction(
|
||||
({ childId, targetId }) => {
|
||||
const pageRow = document.querySelector(`[data-testid="wolai-sidebar-row"][data-node-id="${childId}"]`);
|
||||
const fileRow = document.querySelector(`.tree-row[data-shell-mode="filetree"][data-doc-id="${childId}"], .tree-row[data-shell-mode="filetree"][data-document-id="${childId}"]`);
|
||||
return pageRow?.getAttribute("data-parent-id") === targetId && fileRow?.getAttribute("data-parent-id") === targetId;
|
||||
},
|
||||
{ childId: childPage.documentId, targetId: targetPage.documentId },
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
await assertPageStillStable(page, rootTitle);
|
||||
|
||||
await resetTreeLiveProbe(page);
|
||||
await postTreeCommand(
|
||||
{
|
||||
action: "archive",
|
||||
workspaceId: rootPage.workspaceId,
|
||||
documentId: archivedPage.documentId,
|
||||
},
|
||||
"归档临时页面",
|
||||
);
|
||||
await waitForTreeLivePayload(page, "归档后 tree live", "remove_document", archivedPage.documentId);
|
||||
await page.waitForFunction(
|
||||
(documentId) =>
|
||||
!document.querySelector(`[data-testid="wolai-sidebar-row"][data-node-id="${documentId}"]`) &&
|
||||
!document.querySelector(`.tree-row[data-shell-mode="filetree"][data-doc-id="${documentId}"], .tree-row[data-shell-mode="filetree"][data-document-id="${documentId}"]`),
|
||||
archivedPage.documentId,
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
await assertPageStillStable(page, rootTitle);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
baseUrl: BASE_URL,
|
||||
workspaceId: rootPage.workspaceId,
|
||||
rootDocumentId: rootPage.documentId,
|
||||
movedDocumentId: childPage.documentId,
|
||||
movedParentId: targetPage.documentId,
|
||||
archivedDocumentId: archivedPage.documentId,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (archivedPage) await purgeTempPage(archivedPage).catch(() => undefined);
|
||||
if (childPage) await purgeTempPage(childPage).catch(() => undefined);
|
||||
if (targetPage) await purgeTempPage(targetPage).catch(() => undefined);
|
||||
if (rootPage) await purgeTempPage(rootPage).catch(() => undefined);
|
||||
await page.close().catch(() => undefined);
|
||||
await context.close().catch(() => undefined);
|
||||
await browser.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.stack || error.message : String(error));
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert");
|
||||
const { chromium } = require("playwright");
|
||||
const { fetchWithTimeout } = require("./task114-rust-web-gateway-entry-smoke.js");
|
||||
|
||||
const BASE_URL = (process.env.MNOTE_WEB_SMOKE_BASE_URL || process.env.MNOTE_UI_BASE_URL || "http://127.0.0.1:3000").replace(/\/+$/, "");
|
||||
const UI_TIMEOUT_MS = Number(process.env.MNOTE_SMOKE_UI_TIMEOUT_MS || 30_000);
|
||||
|
||||
async function readJsonResponse(response, label) {
|
||||
const text = await response.text();
|
||||
let payload = null;
|
||||
try {
|
||||
payload = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(`${label} 返回了非 JSON 内容: ${text.slice(0, 1200)}`);
|
||||
}
|
||||
assert(response.ok, `${label} 请求失败: ${response.status}; body: ${text.slice(0, 1200)}`);
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function postTreeCommand(body, label) {
|
||||
const response = await fetchWithTimeout(`${BASE_URL}/api/tree/commands`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const payload = await readJsonResponse(response, label);
|
||||
const result = payload && typeof payload.result === "object" ? payload.result : null;
|
||||
assert(result, `${label} 缺少 result`);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function createTempPage(title) {
|
||||
const result = await postTreeCommand({ action: "create", title }, `创建临时页面 ${title}`);
|
||||
assert(result.documentId, `创建临时页面 ${title} 缺少 documentId`);
|
||||
assert(result.workspaceId, `创建临时页面 ${title} 缺少 workspaceId`);
|
||||
return { documentId: result.documentId, workspaceId: result.workspaceId, title };
|
||||
}
|
||||
|
||||
async function purgeTempPage(target) {
|
||||
if (!target?.documentId || !target?.workspaceId) return;
|
||||
await postTreeCommand(
|
||||
{ action: "purge", workspaceId: target.workspaceId, documentId: target.documentId },
|
||||
`清理临时页面 ${target.documentId}`,
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForRuntimeIsland(page) {
|
||||
await page.waitForFunction(
|
||||
() => {
|
||||
const host = document.querySelector('[data-testid="mnote-leptos-tiptap-island-editor-root"]');
|
||||
const editor = host?.querySelector(".editor-surface .ProseMirror[contenteditable='true']");
|
||||
return (
|
||||
host?.getAttribute("data-editor-host-kind") === "leptos_tiptap_island" &&
|
||||
host?.getAttribute("data-runtime-editor-status") !== "error" &&
|
||||
editor instanceof HTMLElement &&
|
||||
editor.isContentEditable
|
||||
);
|
||||
},
|
||||
null,
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
}
|
||||
|
||||
async function setLocalHeadingFixture(page, headingText) {
|
||||
await page.evaluate((text) => {
|
||||
const editor = document.querySelector(".editor-surface .ProseMirror")?.editor;
|
||||
if (!editor) throw new Error("找不到 Tiptap editor");
|
||||
editor.commands.setContent({
|
||||
type: "doc",
|
||||
content: [
|
||||
{ type: "heading", attrs: { level: 2 }, content: [{ type: "text", text }] },
|
||||
{ type: "paragraph", content: [{ type: "text", text: "本地正文尚未等待服务端 pageSubtree 刷新。" }] },
|
||||
],
|
||||
});
|
||||
}, headingText);
|
||||
await page.waitForFunction(
|
||||
(text) => Array.from(document.querySelectorAll(".editor-surface .ProseMirror h2")).some((node) => (node.textContent || "").includes(text)),
|
||||
headingText,
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
}
|
||||
|
||||
function stringify(value) {
|
||||
try {
|
||||
return JSON.stringify(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const suffix = Date.now().toString(36);
|
||||
const pageTitle = `task178-page-ai-${suffix}`;
|
||||
const localHeading = `TASK178 本地 Heading ${suffix}`;
|
||||
let target = null;
|
||||
let capturedBody = null;
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 960 } });
|
||||
const page = await context.newPage();
|
||||
|
||||
try {
|
||||
target = await createTempPage(pageTitle);
|
||||
await page.route("**/api/ai-agent/run", async (route) => {
|
||||
const postData = route.request().postData() || "{}";
|
||||
capturedBody = JSON.parse(postData);
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
headers: { "content-type": "text/event-stream; charset=utf-8" },
|
||||
body: 'event: assistant_message\ndata: {"text":"ok"}\n\n',
|
||||
});
|
||||
});
|
||||
|
||||
const url = `${BASE_URL}/documents/${encodeURIComponent(target.documentId)}?workspaceId=${encodeURIComponent(target.workspaceId)}`;
|
||||
const response = await page.goto(url, { waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
|
||||
assert(response, "文档页没有返回响应");
|
||||
assert.equal(response.status(), 200, `文档页状态码异常: ${response.status()}`);
|
||||
assert.equal(response.headers()["x-mnote-web-owner"], "mnote-web", "文档页必须由 mnote-web 拥有");
|
||||
|
||||
await waitForRuntimeIsland(page);
|
||||
await setLocalHeadingFixture(page, localHeading);
|
||||
|
||||
await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.locator("[data-page-ai-input]").fill(`请基于当前本地结构回答:${localHeading}`, { timeout: UI_TIMEOUT_MS });
|
||||
await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.waitForFunction(() => Boolean(window.__task178Noop) || true, null, { timeout: 10 });
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('[data-testid="wolai-page-ai-drawer"] .wolai-page-ai-message--assistant'),
|
||||
null,
|
||||
{ timeout: UI_TIMEOUT_MS },
|
||||
);
|
||||
|
||||
assert(capturedBody, "未捕获 /api/ai-agent/run 请求");
|
||||
const contextPayload = capturedBody.context || {};
|
||||
const rawContext = stringify(contextPayload);
|
||||
assert.equal(contextPayload.pageSubtreeSource, "local", `AI context 应标记本地 pageSubtree,实际: ${rawContext}`);
|
||||
assert(rawContext.includes(localHeading), `AI context 应包含本地 heading: ${rawContext.slice(0, 1600)}`);
|
||||
assert(Array.isArray(contextPayload.documentBlocks), `AI context 应包含本地 documentBlocks: ${rawContext.slice(0, 1600)}`);
|
||||
assert(contextPayload.outline?.some((item) => stringify(item).includes(localHeading)), `AI context outline 应包含本地 heading: ${rawContext.slice(0, 1600)}`);
|
||||
assert(contextPayload.subtree?.stats?.headingCount >= 1, `AI context subtree stats 应包含 headingCount: ${rawContext.slice(0, 1600)}`);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
baseUrl: BASE_URL,
|
||||
documentId: target.documentId,
|
||||
workspaceId: target.workspaceId,
|
||||
localHeading,
|
||||
pageSubtreeSource: contextPayload.pageSubtreeSource,
|
||||
headingCount: contextPayload.subtree?.stats?.headingCount ?? null,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
if (target) await purgeTempPage(target).catch(() => undefined);
|
||||
await page.close().catch(() => undefined);
|
||||
await context.close().catch(() => undefined);
|
||||
await browser.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error(error instanceof Error ? error.stack || error.message : String(error));
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require("playwright");
|
||||
const {
|
||||
BASE_URL,
|
||||
UI_TIMEOUT_MS,
|
||||
cleanupDocuments,
|
||||
createTempDocument,
|
||||
ensureAuthenticated,
|
||||
renameDocument,
|
||||
} = require("./tree-shell-smoke-helpers");
|
||||
|
||||
const TASK = "task179-tree-create-delete-no-reload-smoke";
|
||||
const OUTPUT_DIR = path.join(process.cwd(), "tmp", TASK);
|
||||
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
|
||||
|
||||
async function writeResult(payload) {
|
||||
await fs.mkdir(OUTPUT_DIR, { recursive: true });
|
||||
await fs.writeFile(RESULT_PATH, `${JSON.stringify({ ...payload, resultPath: RESULT_PATH }, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
||||
function fileTreeDocumentRowSelector(documentId) {
|
||||
return `[data-testid="filetree-doc-row"][data-document-id="${documentId}"], [data-testid="filetree-doc-row"][data-doc-id="${documentId}"]`;
|
||||
}
|
||||
|
||||
function pageTreeDocumentRowSelector(documentId) {
|
||||
return `.tree-row[data-shell-mode="page"][data-node-id="${documentId}"]`;
|
||||
}
|
||||
|
||||
function documentRowSelector(mode, documentId) {
|
||||
return mode === "page" ? pageTreeDocumentRowSelector(documentId) : fileTreeDocumentRowSelector(documentId);
|
||||
}
|
||||
|
||||
function renameInputSelector(mode) {
|
||||
return mode === "page"
|
||||
? ".tree-rename-input[data-rename-id]"
|
||||
: ".tree-rename-input[data-rename-id^='doc:']";
|
||||
}
|
||||
|
||||
function documentIdFromRenameId(mode, renameId) {
|
||||
return mode === "page" ? String(renameId || "") : String(renameId || "").replace(/^doc:/, "");
|
||||
}
|
||||
|
||||
async function readShellState(page) {
|
||||
return page.evaluate(() => ({
|
||||
url: window.location.href,
|
||||
rows: Array.from(document.querySelectorAll(".tree-row[data-shell-mode='filetree']")).map((row) => ({
|
||||
rowId: row instanceof HTMLElement ? row.dataset.rowId || "" : "",
|
||||
documentId: row instanceof HTMLElement ? row.dataset.documentId || "" : "",
|
||||
title: row instanceof HTMLElement ? row.textContent || "" : "",
|
||||
})),
|
||||
status: document.getElementById("tree-shell-status")?.textContent || "",
|
||||
lastAction: document.getElementById("tree-shell-last-action")?.textContent || "",
|
||||
}));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const result = {
|
||||
ok: false,
|
||||
task: TASK,
|
||||
baseUrl: BASE_URL,
|
||||
createdIds: [],
|
||||
navigationEvents: [],
|
||||
treeCommandRequests: [],
|
||||
modes: {},
|
||||
};
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
page.on("request", (request) => {
|
||||
const url = request.url();
|
||||
if (url.includes("/api/tree/commands")) {
|
||||
result.treeCommandRequests.push({
|
||||
method: request.method(),
|
||||
url,
|
||||
body: request.postData() || null,
|
||||
at: Date.now(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
await ensureAuthenticated(page, context.request);
|
||||
page.on("framenavigated", (frame) => {
|
||||
if (frame === page.mainFrame()) {
|
||||
result.navigationEvents.push({ url: frame.url(), at: Date.now() });
|
||||
}
|
||||
});
|
||||
|
||||
for (const mode of ["filetree", "page"]) {
|
||||
const root = await createTempDocument(context.request, null);
|
||||
result.createdIds.push(root.documentId);
|
||||
await renameDocument(
|
||||
context.request,
|
||||
root.workspaceId,
|
||||
root.documentId,
|
||||
`task179-tree-${mode}-root-${Date.now().toString().slice(-6)}`,
|
||||
);
|
||||
|
||||
const treeUrl = `${BASE_URL}/tree?workspaceId=${encodeURIComponent(root.workspaceId)}&mode=${encodeURIComponent(mode)}&activeDocumentId=${encodeURIComponent(root.documentId)}`;
|
||||
await page.goto(treeUrl, { waitUntil: "commit", timeout: UI_TIMEOUT_MS });
|
||||
await page.locator(documentRowSelector(mode, root.documentId)).waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
const initialUrl = page.url();
|
||||
const navigationStartIndex = result.navigationEvents.length;
|
||||
|
||||
const createStartedAt = Date.now();
|
||||
await page.getByTestId("tree-create-root").click({ timeout: UI_TIMEOUT_MS });
|
||||
const renameInput = page.locator(renameInputSelector(mode)).first();
|
||||
await renameInput.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
|
||||
const renameId = await renameInput.getAttribute("data-rename-id");
|
||||
const createdDocumentId = documentIdFromRenameId(mode, renameId);
|
||||
if (!createdDocumentId) throw new Error(`${mode}_created_document_id_missing:${renameId || ""}`);
|
||||
result.createdIds.push(createdDocumentId);
|
||||
await page.locator(documentRowSelector(mode, createdDocumentId)).waitFor({
|
||||
state: "visible",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
const createFinishedAt = Date.now();
|
||||
|
||||
const afterCreateUrl = page.url();
|
||||
if (afterCreateUrl !== initialUrl) {
|
||||
throw new Error(`${mode}_create_changed_url:${initialUrl}->${afterCreateUrl}`);
|
||||
}
|
||||
const navigationAfterCreate = result.navigationEvents.slice(navigationStartIndex);
|
||||
if (navigationAfterCreate.length !== 0) {
|
||||
throw new Error(`${mode}_create_triggered_navigation:${JSON.stringify(navigationAfterCreate)}`);
|
||||
}
|
||||
|
||||
let deleteMs = null;
|
||||
let afterDeleteUrl = page.url();
|
||||
let navigationAfterDelete = result.navigationEvents.slice(navigationStartIndex);
|
||||
if (mode === "filetree") {
|
||||
const deleteStartedAt = Date.now();
|
||||
const createdRow = page.locator(documentRowSelector(mode, createdDocumentId)).first();
|
||||
await createdRow.click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.keyboard.press("Delete");
|
||||
const confirmButton = page.locator('.tree-preflight-actions button[data-role="confirm"]').first();
|
||||
await confirmButton.click({ timeout: UI_TIMEOUT_MS });
|
||||
await page.locator(documentRowSelector(mode, createdDocumentId)).waitFor({
|
||||
state: "detached",
|
||||
timeout: UI_TIMEOUT_MS,
|
||||
});
|
||||
const deleteFinishedAt = Date.now();
|
||||
deleteMs = deleteFinishedAt - deleteStartedAt;
|
||||
|
||||
afterDeleteUrl = page.url();
|
||||
if (afterDeleteUrl !== initialUrl) {
|
||||
throw new Error(`${mode}_delete_changed_url:${initialUrl}->${afterDeleteUrl}`);
|
||||
}
|
||||
navigationAfterDelete = result.navigationEvents.slice(navigationStartIndex);
|
||||
if (navigationAfterDelete.length !== 0) {
|
||||
throw new Error(`${mode}_delete_triggered_navigation:${JSON.stringify(navigationAfterDelete)}`);
|
||||
}
|
||||
}
|
||||
|
||||
result.modes[mode] = {
|
||||
timings: {
|
||||
createMs: createFinishedAt - createStartedAt,
|
||||
deleteMs,
|
||||
},
|
||||
initialUrl,
|
||||
finalUrl: afterDeleteUrl,
|
||||
createdDocumentId,
|
||||
navigationEvents: navigationAfterDelete,
|
||||
finalState: await readShellState(page),
|
||||
};
|
||||
}
|
||||
result.ok = true;
|
||||
await writeResult(result);
|
||||
} catch (error) {
|
||||
result.error = error instanceof Error ? error.stack || error.message : String(error);
|
||||
result.failureState = await readShellState(page).catch(() => null);
|
||||
await writeResult(result);
|
||||
throw error;
|
||||
} finally {
|
||||
await cleanupDocuments(context.request, result.createdIds).catch(() => undefined);
|
||||
await context.close().catch(() => undefined);
|
||||
await browser.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
|
||||
const DEFAULT_URL = "http://127.0.0.1:3000/api/sidebar";
|
||||
const DEFAULT_OUTPUT = "tmp/task180-mindmap-ghost-candidate-audit/result.json";
|
||||
|
||||
function stringOrNull(value) {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed || null;
|
||||
}
|
||||
|
||||
function asArray(value) {
|
||||
return Array.isArray(value) ? value : [];
|
||||
}
|
||||
|
||||
function unwrapSidebarPayload(payload) {
|
||||
let unwrapped = payload && typeof payload === "object" ? payload : {};
|
||||
if (unwrapped.data && typeof unwrapped.data === "object") {
|
||||
unwrapped = unwrapped.data;
|
||||
}
|
||||
const result = unwrapped.result && typeof unwrapped.result === "object" ? unwrapped.result : null;
|
||||
if (Array.isArray(result?.items)) {
|
||||
return {
|
||||
...unwrapped,
|
||||
...result,
|
||||
kernelFileTreeProjection: { items: result.items },
|
||||
};
|
||||
}
|
||||
if (Array.isArray(unwrapped.items)) {
|
||||
return {
|
||||
...unwrapped,
|
||||
kernelFileTreeProjection: { items: unwrapped.items },
|
||||
};
|
||||
}
|
||||
return unwrapped;
|
||||
}
|
||||
|
||||
function readAssetId(asset) {
|
||||
return stringOrNull(asset?.id) ?? stringOrNull(asset?.assetId) ?? stringOrNull(asset?.asset_id);
|
||||
}
|
||||
|
||||
function readDocumentId(value) {
|
||||
return stringOrNull(value?.document_id) ?? stringOrNull(value?.documentId) ?? stringOrNull(value?.docId);
|
||||
}
|
||||
|
||||
function isActiveAsset(asset) {
|
||||
return !stringOrNull(asset?.deleted_at) &&
|
||||
!stringOrNull(asset?.deletedAt) &&
|
||||
!stringOrNull(asset?.purged_at) &&
|
||||
!stringOrNull(asset?.purgedAt);
|
||||
}
|
||||
|
||||
function isMindmapAsset(asset) {
|
||||
const type = stringOrNull(asset?.asset_type) ?? stringOrNull(asset?.assetType);
|
||||
return type === "mindmap" || Boolean(readAssetId(asset)?.startsWith("mindmap"));
|
||||
}
|
||||
|
||||
function normalizeMindmapAsset(asset) {
|
||||
return {
|
||||
assetId: readAssetId(asset),
|
||||
documentId: readDocumentId(asset),
|
||||
deletedAt: stringOrNull(asset?.deleted_at) ?? stringOrNull(asset?.deletedAt),
|
||||
title: stringOrNull(asset?.file_name) ?? stringOrNull(asset?.fileName) ?? stringOrNull(asset?.title),
|
||||
};
|
||||
}
|
||||
|
||||
function readProjectionItems(sidebar) {
|
||||
const projection = sidebar.kernelFileTreeProjection ?? sidebar.kernel_file_tree_projection ?? {};
|
||||
return asArray(projection.items);
|
||||
}
|
||||
|
||||
function readFileTreeMindmapRow(item) {
|
||||
const resourceMeta = item?.resourceMeta ?? item?.resource_meta ?? {};
|
||||
const assetId =
|
||||
stringOrNull(resourceMeta.assetId) ??
|
||||
stringOrNull(resourceMeta.asset_id) ??
|
||||
stringOrNull(item?.assetId) ??
|
||||
stringOrNull(item?.asset_id);
|
||||
const documentId =
|
||||
stringOrNull(resourceMeta.documentId) ??
|
||||
stringOrNull(resourceMeta.document_id) ??
|
||||
readDocumentId(item);
|
||||
const resourceKind = stringOrNull(resourceMeta.resourceKind) ?? stringOrNull(resourceMeta.resource_kind);
|
||||
const rowKind = stringOrNull(item?.rowKind) ?? stringOrNull(item?.row_kind);
|
||||
const objectKind = stringOrNull(item?.objectKind) ?? stringOrNull(resourceMeta.objectKind);
|
||||
const isMindmap =
|
||||
resourceKind === "mindmap" ||
|
||||
objectKind === "mindmap" ||
|
||||
Boolean(assetId?.startsWith("mindmap"));
|
||||
if (!isMindmap) return null;
|
||||
return {
|
||||
rowId: stringOrNull(item?.rowId) ?? stringOrNull(item?.row_id),
|
||||
rowKind,
|
||||
documentId,
|
||||
assetId,
|
||||
title: stringOrNull(item?.title),
|
||||
};
|
||||
}
|
||||
|
||||
function groupBy(items, keyFn) {
|
||||
const map = new Map();
|
||||
for (const item of items) {
|
||||
const key = keyFn(item);
|
||||
if (!key) continue;
|
||||
const bucket = map.get(key) ?? [];
|
||||
bucket.push(item);
|
||||
map.set(key, bucket);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
function auditSidebarMindmapGhostCandidates(payload) {
|
||||
const sidebar = unwrapSidebarPayload(payload);
|
||||
const documents = asArray(sidebar.documents);
|
||||
const documentIds = new Set(documents.map((doc) => stringOrNull(doc?.id)).filter(Boolean));
|
||||
const rawMindmapAssets = [
|
||||
...asArray(sidebar.mindmapAssets),
|
||||
...asArray(sidebar.mindmap_assets),
|
||||
];
|
||||
const activeMindmapAssets = rawMindmapAssets
|
||||
.filter((asset) => isMindmapAsset(asset) && isActiveAsset(asset))
|
||||
.map(normalizeMindmapAsset)
|
||||
.filter((asset) => asset.assetId && asset.documentId);
|
||||
|
||||
const byDocument = groupBy(activeMindmapAssets, (asset) => asset.documentId);
|
||||
const multipleActiveMindmapsByDocument = Array.from(byDocument.entries())
|
||||
.filter(([, assets]) => assets.length > 1)
|
||||
.map(([documentId, assets]) => ({
|
||||
documentId,
|
||||
mindmapIds: assets.map((asset) => asset.assetId),
|
||||
count: assets.length,
|
||||
}));
|
||||
|
||||
const byAssetId = groupBy(activeMindmapAssets, (asset) => asset.assetId);
|
||||
const duplicateActiveAssetIds = Array.from(byAssetId.entries())
|
||||
.filter(([, assets]) => assets.length > 1)
|
||||
.map(([assetId, assets]) => ({
|
||||
assetId,
|
||||
documentIds: Array.from(new Set(assets.map((asset) => asset.documentId).filter(Boolean))),
|
||||
count: assets.length,
|
||||
}));
|
||||
|
||||
const activeAssetsWithMissingDocument = activeMindmapAssets
|
||||
.filter((asset) => asset.documentId && !documentIds.has(asset.documentId))
|
||||
.map((asset) => ({
|
||||
assetId: asset.assetId,
|
||||
documentId: asset.documentId,
|
||||
}));
|
||||
|
||||
const fileTreeMindmapRows = readProjectionItems(sidebar)
|
||||
.map(readFileTreeMindmapRow)
|
||||
.filter(Boolean);
|
||||
const byFileTreeObject = groupBy(fileTreeMindmapRows, (row) => `${row.documentId ?? ""}:${row.assetId ?? ""}`);
|
||||
const duplicateFileTreeMindmapRows = Array.from(byFileTreeObject.entries())
|
||||
.filter(([key, rows]) => !key.startsWith(":") && rows.length > 1)
|
||||
.map(([, rows]) => ({
|
||||
documentId: rows[0].documentId,
|
||||
assetId: rows[0].assetId,
|
||||
rowIds: rows.map((row) => row.rowId).filter(Boolean),
|
||||
count: rows.length,
|
||||
}));
|
||||
|
||||
const candidates = {
|
||||
multipleActiveMindmapsByDocument,
|
||||
duplicateActiveAssetIds,
|
||||
activeAssetsWithMissingDocument,
|
||||
duplicateFileTreeMindmapRows,
|
||||
};
|
||||
const candidateCount = Object.values(candidates).reduce((sum, items) => sum + items.length, 0);
|
||||
return {
|
||||
ok: true,
|
||||
readOnly: true,
|
||||
summary: {
|
||||
documents: documents.length,
|
||||
activeMindmapAssets: activeMindmapAssets.length,
|
||||
fileTreeMindmapRows: fileTreeMindmapRows.length,
|
||||
documentGroupsWithMultipleActiveMindmaps: multipleActiveMindmapsByDocument.length,
|
||||
duplicateActiveAssetIds: duplicateActiveAssetIds.length,
|
||||
activeAssetsWithMissingDocument: activeAssetsWithMissingDocument.length,
|
||||
duplicateFileTreeMindmapRows: duplicateFileTreeMindmapRows.length,
|
||||
candidateCount,
|
||||
},
|
||||
candidates,
|
||||
};
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = {
|
||||
input: null,
|
||||
url: DEFAULT_URL,
|
||||
output: DEFAULT_OUTPUT,
|
||||
cookie: process.env.MNOTE_AUTH_COOKIE || "",
|
||||
failOnCandidates: false,
|
||||
help: false,
|
||||
};
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--input") args.input = argv[++index] || null;
|
||||
else if (arg === "--url") args.url = argv[++index] || DEFAULT_URL;
|
||||
else if (arg === "--output") args.output = argv[++index] || DEFAULT_OUTPUT;
|
||||
else if (arg === "--cookie") args.cookie = argv[++index] || "";
|
||||
else if (arg === "--fail-on-candidates") args.failOnCandidates = true;
|
||||
else if (arg === "--help" || arg === "-h") args.help = true;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log([
|
||||
"Usage:",
|
||||
" node scripts/task180-mindmap-ghost-candidate-audit.js --input sidebar.json",
|
||||
" node scripts/task180-mindmap-ghost-candidate-audit.js --url http://127.0.0.1:3000/api/sidebar --cookie '<cookie>'",
|
||||
" node scripts/task180-mindmap-ghost-candidate-audit.js --url 'http://127.0.0.1:3000/api/tree/projections/file?workspaceId=<workspaceId>'",
|
||||
"",
|
||||
"Notes:",
|
||||
" This script is read-only. It only reports cleanup candidates and never deletes data.",
|
||||
" Sidebar payloads can audit duplicate assets, orphan assets, and duplicate File Tree rows.",
|
||||
" File projection payloads only include projection rows, so they can audit duplicate File Tree rows.",
|
||||
].join("\n"));
|
||||
}
|
||||
|
||||
async function loadPayload(args) {
|
||||
if (args.input) {
|
||||
return JSON.parse(await fs.readFile(args.input, "utf8"));
|
||||
}
|
||||
const headers = { accept: "application/json" };
|
||||
if (args.cookie) headers.cookie = args.cookie;
|
||||
const response = await fetch(args.url, { headers });
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(`sidebar_audit_fetch_failed:${response.status}:${text.slice(0, 300)}`);
|
||||
}
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (args.help) {
|
||||
printHelp();
|
||||
return;
|
||||
}
|
||||
const payload = await loadPayload(args);
|
||||
const result = auditSidebarMindmapGhostCandidates(payload);
|
||||
await fs.mkdir(path.dirname(args.output), { recursive: true });
|
||||
await fs.writeFile(args.output, `${JSON.stringify(result, null, 2)}\n`, "utf8");
|
||||
console.log(JSON.stringify(result.summary, null, 2));
|
||||
if (args.failOnCandidates && result.summary.candidateCount > 0) {
|
||||
process.exitCode = 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
auditSidebarMindmapGhostCandidates,
|
||||
};
|
||||
@@ -0,0 +1,93 @@
|
||||
const assert = require("node:assert/strict");
|
||||
|
||||
const {
|
||||
auditSidebarMindmapGhostCandidates,
|
||||
} = require("./task180-mindmap-ghost-candidate-audit");
|
||||
|
||||
const fixture = {
|
||||
documents: [
|
||||
{ id: "doc_1", title: "带重复导图的页面" },
|
||||
{ id: "doc_2", title: "正常页面" },
|
||||
],
|
||||
mindmapAssets: [
|
||||
{ id: "mind_a", document_id: "doc_1", asset_type: "mindmap", deleted_at: null },
|
||||
{ id: "mind_b", document_id: "doc_1", asset_type: "mindmap", deleted_at: null },
|
||||
{ id: "mind_b", document_id: "doc_1", asset_type: "mindmap", deleted_at: null },
|
||||
{ id: "mind_c", document_id: "doc_2", asset_type: "mindmap", deleted_at: "2026-05-01" },
|
||||
{ id: "mind_orphan", document_id: "doc_missing", asset_type: "mindmap", deleted_at: null },
|
||||
],
|
||||
kernelFileTreeProjection: {
|
||||
items: [
|
||||
{
|
||||
rowId: "asset:mind_a",
|
||||
rowKind: "asset",
|
||||
title: "mind_a",
|
||||
resourceMeta: { resourceKind: "mindmap", documentId: "doc_1", assetId: "mind_a" },
|
||||
},
|
||||
{
|
||||
rowId: "asset:mind_a:dup",
|
||||
rowKind: "asset",
|
||||
title: "mind_a duplicate",
|
||||
resourceMeta: { resourceKind: "mindmap", documentId: "doc_1", assetId: "mind_a" },
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const result = auditSidebarMindmapGhostCandidates(fixture);
|
||||
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.summary.activeMindmapAssets, 4);
|
||||
assert.equal(result.summary.documentGroupsWithMultipleActiveMindmaps, 1);
|
||||
assert.equal(result.summary.duplicateActiveAssetIds, 1);
|
||||
assert.equal(result.summary.activeAssetsWithMissingDocument, 1);
|
||||
assert.equal(result.summary.duplicateFileTreeMindmapRows, 1);
|
||||
assert.deepEqual(result.candidates.multipleActiveMindmapsByDocument[0].mindmapIds, [
|
||||
"mind_a",
|
||||
"mind_b",
|
||||
"mind_b",
|
||||
]);
|
||||
assert.deepEqual(result.candidates.duplicateActiveAssetIds[0].assetId, "mind_b");
|
||||
assert.deepEqual(result.candidates.activeAssetsWithMissingDocument[0].assetId, "mind_orphan");
|
||||
assert.deepEqual(result.candidates.duplicateFileTreeMindmapRows[0].assetId, "mind_a");
|
||||
|
||||
const fileProjectionResult = auditSidebarMindmapGhostCandidates({
|
||||
ok: true,
|
||||
result: {
|
||||
items: [
|
||||
{
|
||||
rowId: "resource:mind_projection",
|
||||
title: "导图",
|
||||
resourceMeta: { resourceKind: "mindmap", documentId: "doc_projection", assetId: "mind_projection" },
|
||||
},
|
||||
{
|
||||
rowId: "resource:mind_projection:duplicate",
|
||||
title: "导图副本",
|
||||
resourceMeta: { resourceKind: "mindmap", documentId: "doc_projection", assetId: "mind_projection" },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(fileProjectionResult.summary.documents, 0);
|
||||
assert.equal(fileProjectionResult.summary.activeMindmapAssets, 0);
|
||||
assert.equal(fileProjectionResult.summary.fileTreeMindmapRows, 2);
|
||||
assert.equal(fileProjectionResult.summary.duplicateFileTreeMindmapRows, 1);
|
||||
assert.deepEqual(fileProjectionResult.candidates.duplicateFileTreeMindmapRows[0].rowIds, [
|
||||
"resource:mind_projection",
|
||||
"resource:mind_projection:duplicate",
|
||||
]);
|
||||
|
||||
const directItemsResult = auditSidebarMindmapGhostCandidates({
|
||||
items: [
|
||||
{
|
||||
row_id: "resource:mind_direct",
|
||||
resource_meta: { resource_kind: "mindmap", document_id: "doc_direct", asset_id: "mind_direct" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(directItemsResult.summary.fileTreeMindmapRows, 1);
|
||||
assert.equal(directItemsResult.summary.duplicateFileTreeMindmapRows, 0);
|
||||
|
||||
console.log("task180 mindmap ghost candidate audit self-test passed");
|
||||
Reference in New Issue
Block a user