fix: stabilize local folder AI document workflow

- scope local-folder PageTree revision and document sidebar rendering to fileTreeScope

- preserve projected table/image attrs for local Markdown aggregate fallback

- avoid FileTree restore forced layouts on cold design open

- add API ChatOnly provider runtime and local OCR task handling regressions
This commit is contained in:
lix-2026
2026-06-02 17:17:49 +08:00
parent 610b23d3a5
commit 9f4b5c4d48
27 changed files with 3825 additions and 229 deletions
@@ -28,6 +28,10 @@ function paragraphText(doc) {
return doc?.content?.[0]?.content?.[0]?.text || "";
}
function firstTableCellText(doc) {
return doc?.content?.[0]?.content?.[0]?.content?.[0]?.content?.[0]?.content?.[0]?.text || "";
}
const {
pageBodyTiptapDocumentSource,
pageBodyTiptapDocument,
@@ -62,6 +66,39 @@ assert.equal(
"Block truth",
);
const localWithProjectedTable = {
projectionSource: "local_markdown.content",
blockDocument: {
documentId: "local-md:design~2F07-ai~2Fdone~2F7-45-chatonly-api-provider-runtime-v1.md",
rootBlockIds: ["table-1"],
blocks: [{
blockId: "table-1",
type: "table",
attrs: {
tiptapTable: {
type: "table",
content: [{
type: "tableRow",
content: [{
type: "tableCell",
attrs: { colspan: 1, rowspan: 1, colwidth: null },
content: [{
type: "paragraph",
content: [{ type: "text", text: "Provider 类别" }],
}],
}],
}],
},
},
contentNodes: [],
}],
},
};
assert.equal(
firstTableCellText(pageBodyTiptapDocument(localWithProjectedTable)),
"Provider 类别",
);
const localLegacyOnly = {
projectionSource: "local_markdown.content",
content: legacyContent,
+191 -106
View File
@@ -80,11 +80,17 @@ async function main() {
const relativePath = "docs/Page.md";
const documentId = localMdDocumentId(relativePath);
const sourceRootRelativePath = "docs/Page.assets/photo.png";
const failedSourceRootRelativePath = "docs/Page.assets/photo-failed.png";
const ocrToken = "TASK526_OCR_TOKEN";
writeWorkspaceManifest(root, actorId);
fs.mkdirSync(path.join(root, "docs", "Page.assets"), { recursive: true });
fs.writeFileSync(path.join(root, relativePath), "# OCR Page\n\n![photo](./Page.assets/photo.png)\n", "utf8");
fs.writeFileSync(path.join(root, sourceRootRelativePath), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a]));
fs.writeFileSync(path.join(root, relativePath), "# OCR Page\n\n![photo](<./Page.assets/photo.png>)\n", "utf8");
const tinyPng = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAFgwJ/l8FQOQAAAABJRU5ErkJggg==",
"base64",
);
fs.writeFileSync(path.join(root, sourceRootRelativePath), tinyPng);
fs.writeFileSync(path.join(root, failedSourceRootRelativePath), tinyPng);
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext();
@@ -93,6 +99,15 @@ async function main() {
try {
await ensureAuthenticated(page, context.request);
await ensureDocumentVisible(page, root, relativePath);
await page.waitForFunction(() => {
const image = document.querySelector('.document-pane[data-pane-role="primary"] .editor-surface .ProseMirror img');
return image instanceof HTMLImageElement
&& image.complete
&& image.naturalWidth > 0
&& image.src.includes("Page.assets%2Fphoto.png")
&& !image.src.includes("%3C")
&& !image.src.includes("%3E");
}, null, { timeout: UI_TIMEOUT_MS });
screenshots.page = path.join(OUTPUT_DIR, "01-page.png");
await page.screenshot({ path: screenshots.page, fullPage: true });
@@ -126,17 +141,23 @@ async function main() {
sourceRootRelativePath,
workspaceId,
});
await page.locator('[data-testid="mnote-local-ocr-toolbar"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.getByTestId("mnote-local-ocr-run").click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(() => document.querySelector('[data-mnote-local-ocr-status="done"]'), null, {
await page.locator('[data-mnote-resource-tab-panel]:not([hidden]) [data-testid="mnote-local-ocr-toolbar"]').first().waitFor({
state: "detached",
timeout: UI_TIMEOUT_MS,
});
const watchBatchBeforeOcr = await page.evaluate(() => document.documentElement.getAttribute("data-mnote-local-folder-watch-batch-applied") || "");
await page.getByTestId("mnote-local-ocr-task-toggle").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.getByTestId("mnote-local-ocr-task-toggle").click({ timeout: UI_TIMEOUT_MS });
await page.getByTestId("mnote-local-ocr-task-drawer").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.getByTestId("mnote-local-ocr-task-drawer").waitFor({ state: "hidden", timeout: UI_TIMEOUT_MS });
const topbarOcrButtonInfo = await page.getByTestId("mnote-local-ocr-task-toggle").evaluate((node) => {
const topbar = node.closest(".wolai-topbar-actions");
return {
inTopbar: Boolean(topbar),
text: node.textContent || "",
badge: node.querySelector("[data-mnote-local-ocr-task-count]")?.textContent || "",
};
});
assert.equal(topbarOcrButtonInfo.inTopbar, true, `OCR 任务入口应位于右上角 topbar: ${JSON.stringify(topbarOcrButtonInfo)}`);
await page.waitForFunction(
(sourcePath) => {
const row = document.querySelector(`[data-mnote-local-ocr-task-row="${CSS.escape(sourcePath)}"]`);
@@ -145,111 +166,100 @@ async function main() {
sourceRootRelativePath,
{ timeout: UI_TIMEOUT_MS },
);
const uiOcrPath = await page.locator('[data-mnote-local-ocr-path]').first().getAttribute("data-mnote-local-ocr-path");
await page.getByTestId("mnote-local-ocr-task-toggle").click({ timeout: UI_TIMEOUT_MS });
await page.getByTestId("mnote-local-ocr-task-drawer").waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
const uiOcrPath = await page.evaluate(async ({ rootUri, sourceRootRelativePath }) => {
const url = new URL("/api/local-folder/ocr/status", window.location.origin);
url.searchParams.set("rootUri", rootUri);
url.searchParams.set("sourceRootRelativePath", sourceRootRelativePath);
const response = await fetch(url.toString(), { cache: "no-store", headers: { accept: "application/json" } });
const payload = await response.json().catch(() => null);
return payload?.job?.ocrRootRelativePath || "";
}, {
rootUri: fileUrl(root),
sourceRootRelativePath,
});
assert(uiOcrPath && uiOcrPath.endsWith(".ocr.md"), `UI OCR path invalid: ${uiOcrPath}`);
await page.waitForFunction(
({ before, ocrPath }) => {
const root = document.documentElement;
const marker = root.getAttribute("data-mnote-local-ocr-filetree-refresh") || "";
const applied = root.getAttribute("data-mnote-local-folder-watch-batch-applied") || "";
return marker === ocrPath && applied && applied !== before;
},
{ before: watchBatchBeforeOcr, ocrPath: uiOcrPath },
{ timeout: UI_TIMEOUT_MS },
);
screenshots.ocrToolbar = path.join(OUTPUT_DIR, "02-ocr-toolbar.png");
await page.screenshot({ path: screenshots.ocrToolbar, fullPage: true });
await page.getByTestId("mnote-local-ocr-insert").click({ timeout: UI_TIMEOUT_MS });
await page.getByTestId("mnote-local-ocr-status").filter({ hasText: "OCR 链接已插入正文" }).waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.getByTestId("mnote-local-ocr-open").click({ timeout: UI_TIMEOUT_MS });
await page.locator('[data-mnote-resource-tab-panel][data-resource-kind="markdown"]:not([hidden]) [data-testid="mnote-leptos-tiptap-island-editor-root"]').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
const result = await page.evaluate(async ({ rootUri, documentId, sourceRootRelativePath, workspaceId, ocrToken }) => {
async function jsonFetch(pathname, init = {}) {
const response = await fetch(pathname, {
...init,
headers: {
"content-type": "application/json",
...(init.headers || {}),
},
});
const payload = await response.json().catch(() => null);
return { status: response.status, payload };
}
const create = await jsonFetch("/api/local-folder/ocr/jobs", {
method: "POST",
body: JSON.stringify({
rootUri,
documentId,
sourceRootRelativePath,
provider: "mock",
mockMarkdown: `# OCR Result\n\n${ocrToken} browser smoke text`,
}),
const failedOcrRoute = async (route) => {
if (route.request().method() !== "POST") return route.fallback();
const body = route.request().postDataJSON();
if (body?.sourceRootRelativePath !== failedSourceRootRelativePath) return route.fallback();
return route.fulfill({
status: 401,
contentType: "application/json",
body: JSON.stringify({ ok: false, error: { message: "local_ocr_job_failed_401" } }),
});
const ocrRootRelativePath = create.payload?.job?.ocrRootRelativePath || "";
const read = await jsonFetch(`/api/local-folder/ocr/read?rootUri=${encodeURIComponent(rootUri)}&ocrRootRelativePath=${encodeURIComponent(ocrRootRelativePath)}`, {
method: "GET",
headers: {},
};
await page.route("**/api/local-folder/ocr/jobs", failedOcrRoute);
await page.evaluate(async ({ rootUri, documentId, sourceRootRelativePath, workspaceId }) => {
window.__MNOTE_LOCAL_OCR_PROVIDER = "mineru";
const title = sourceRootRelativePath.split("/").filter(Boolean).pop() || "photo-failed.png";
const fileUrl = new URL("/api/local-folder/files/open", window.location.origin);
fileUrl.searchParams.set("rootUri", rootUri);
fileUrl.searchParams.set("path", sourceRootRelativePath);
const opened = await window.__mnoteDocumentPaneRuntime.openResourceInActiveTab({
objectIdentity: `local-file:${sourceRootRelativePath}`,
assetId: `local-file:${sourceRootRelativePath}`,
title,
fileName: title,
kind: "image",
rootUri,
path: sourceRootRelativePath,
href: fileUrl.toString(),
documentId,
ownerDocumentId: documentId,
workspaceId,
sourceKind: "local_folder",
});
const status = await jsonFetch(`/api/local-folder/ocr/status?rootUri=${encodeURIComponent(rootUri)}&sourceRootRelativePath=${encodeURIComponent(sourceRootRelativePath)}`, {
method: "GET",
headers: {},
});
const jobs = await jsonFetch(`/api/local-folder/ocr/jobs?rootUri=${encodeURIComponent(rootUri)}`, {
method: "GET",
headers: {},
});
const withoutOcr = await jsonFetch("/api/search/documents", {
method: "POST",
body: JSON.stringify({
workspaceId,
sourceKind: "local_folder",
rootUri,
query: ocrToken,
limit: 5,
filters: { includeOcr: false },
}),
});
const withOcr = await jsonFetch("/api/search/documents", {
method: "POST",
body: JSON.stringify({
workspaceId,
sourceKind: "local_folder",
rootUri,
query: ocrToken,
limit: 5,
filters: { includeOcr: true },
}),
});
const insert = await jsonFetch("/api/local-folder/ocr/insert", {
method: "POST",
body: JSON.stringify({
rootUri,
documentId,
ocrRootRelativePath,
mode: "link",
}),
});
return { create, read, status, jobs, withoutOcr, withOcr, insert, ocrRootRelativePath };
if (!opened) throw new Error("OCR failed source image resource tab did not open");
}, {
rootUri: fileUrl(root),
documentId,
sourceRootRelativePath,
sourceRootRelativePath: failedSourceRootRelativePath,
workspaceId,
ocrToken,
});
assert.equal(result.create.status, 200, `OCR create failed: ${JSON.stringify(result.create)}`);
assert.equal(result.create.payload.job.status, "done", `OCR job should be done: ${JSON.stringify(result.create.payload)}`);
assert(result.ocrRootRelativePath.endsWith(".ocr.md"), `OCR path invalid: ${result.ocrRootRelativePath}`);
assert.equal(result.read.status, 200, `OCR read failed: ${JSON.stringify(result.read)}`);
assert(result.read.payload.markdown.includes(ocrToken), "OCR read should include mock OCR text");
assert.equal(result.status.payload.job.ocrRootRelativePath, result.ocrRootRelativePath, "status should return OCR sidecar path");
assert(result.jobs.payload.jobs.some((job) => job.ocrRootRelativePath === result.ocrRootRelativePath), "jobs list should include OCR job");
assert.equal(result.withoutOcr.payload.results.length, 0, `includeOcr=false should not match OCR text: ${JSON.stringify(result.withoutOcr.payload)}`);
const ocrResult = result.withOcr.payload.results.find((item) => item.hasOcr === true);
assert(ocrResult, `includeOcr=true should return owner page OCR result: ${JSON.stringify(result.withOcr.payload)}`);
assert.equal(ocrResult.documentId, documentId, "OCR search result should point to owner document");
assert.equal(ocrResult.ocrEvidence.ocrRootRelativePath, result.ocrRootRelativePath, "OCR evidence should include sidecar path");
assert.equal(result.insert.status, 200, `OCR insert failed: ${JSON.stringify(result.insert)}`);
const ownerMarkdown = fs.readFileSync(path.join(root, relativePath), "utf8");
assert(ownerMarkdown.includes(`[OCRphoto.png](`), `owner markdown should include explicit OCR link:\n${ownerMarkdown}`);
const failedImageTab = page.locator('.mnote-main-tab[data-mnote-tab-kind="image"]', { hasText: "photo-failed.png" }).first();
await failedImageTab.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await failedImageTab.click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(
() => {
const active = document.querySelector('.mnote-main-tab.is-active[data-mnote-tab-kind="image"] .mnote-main-tab-title');
return active && (active.textContent || "").includes("photo-failed.png");
},
null,
{ timeout: UI_TIMEOUT_MS },
);
await page.locator('[data-mnote-resource-tab-panel]:not([hidden]) [data-testid="mnote-local-ocr-toolbar"]').first().waitFor({
state: "detached",
timeout: UI_TIMEOUT_MS,
});
await page.getByTestId("mnote-local-ocr-task-toggle").click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(
(sourcePath) => {
const row = document.querySelector(`[data-mnote-local-ocr-task-row="${CSS.escape(sourcePath)}"]`);
return row
&& row.getAttribute("data-mnote-local-ocr-task-status") === "failed"
&& (row.textContent || "").includes("local_ocr_job_failed_401");
},
failedSourceRootRelativePath,
{ timeout: UI_TIMEOUT_MS },
);
screenshots.ocrFailedTask = path.join(OUTPUT_DIR, "04-ocr-failed-task.png");
await page.screenshot({ path: screenshots.ocrFailedTask, fullPage: true });
await page.unroute("**/api/local-folder/ocr/jobs", failedOcrRoute);
const openResourceResult = await page.evaluate(async ({ rootUri, documentId, ocrRootRelativePath, workspaceId }) => {
const runtime = window.__mnoteDocumentPaneRuntime;
@@ -273,7 +283,7 @@ async function main() {
}, {
rootUri: fileUrl(root),
documentId,
ocrRootRelativePath: result.ocrRootRelativePath,
ocrRootRelativePath: uiOcrPath,
workspaceId,
});
assert.equal(openResourceResult, true, "OCR sidecar resource tab should open");
@@ -281,15 +291,90 @@ async function main() {
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await page.waitForFunction(
() => {
const active = document.querySelector('[data-mnote-resource-tab-panel][data-resource-kind="markdown"]:not([hidden]) .ProseMirror');
return active && (active.textContent || "").includes("OCR UI smoke text");
},
null,
{ timeout: UI_TIMEOUT_MS },
).catch(async (error) => {
const debug = await page.evaluate(() => ({
activeTab: document.querySelector('.mnote-main-tab.is-active')?.outerHTML || '',
activePanels: Array.from(document.querySelectorAll('[data-mnote-resource-tab-panel]:not([hidden])')).map((panel) => ({
kind: panel.getAttribute('data-resource-kind') || '',
objectIdentity: panel.getAttribute('data-mnote-object-identity') || '',
text: (panel.textContent || '').slice(0, 200),
html: panel.innerHTML.slice(0, 500),
})),
marker: document.documentElement.getAttribute('data-mnote-local-ocr-filetree-open') || '',
}));
throw new Error(`${error.message}; debug=${JSON.stringify(debug)}`);
});
const fileTreeOpenResult = await page.evaluate((ocrRootRelativePath) => {
const parentPath = ocrRootRelativePath.split("/").slice(0, -1).join("/");
const parentRow = document.querySelector(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${CSS.escape(parentPath)}"]`);
if (!(parentRow instanceof HTMLElement)) return { ok: false, reason: "ocr_parent_row_missing", parentPath };
if (parentRow.getAttribute("aria-expanded") !== "true") {
const toggle = parentRow.querySelector('[data-rust-action="toggle"]');
if (toggle instanceof HTMLElement) toggle.click();
}
return { ok: true, parentPath };
}, uiOcrPath);
assert.equal(fileTreeOpenResult.ok, true, `OCR sidecar parent should exist in filetree: ${JSON.stringify(fileTreeOpenResult)}`);
const ocrFileTreeRow = page.locator(`#sidebar-file-tree-root .tree-row[data-shell-mode="filetree"][data-local-relative-path="${uiOcrPath.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"]`).first();
await ocrFileTreeRow.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await ocrFileTreeRow.click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(
() => document.documentElement.getAttribute("data-mnote-local-ocr-filetree-open") === "resource-tab",
null,
{ timeout: UI_TIMEOUT_MS },
);
await page.waitForFunction(
() => {
const active = document.querySelector('[data-mnote-resource-tab-panel][data-resource-kind="markdown"]:not([hidden]) .ProseMirror');
return active && (active.textContent || "").includes("OCR UI smoke text");
},
null,
{ timeout: UI_TIMEOUT_MS },
).catch(async (error) => {
const debug = await page.evaluate(() => ({
activeTab: document.querySelector('.mnote-main-tab.is-active')?.outerHTML || '',
activePanels: Array.from(document.querySelectorAll('[data-mnote-resource-tab-panel]:not([hidden])')).map((panel) => ({
kind: panel.getAttribute('data-resource-kind') || '',
objectIdentity: panel.getAttribute('data-mnote-object-identity') || '',
text: (panel.textContent || '').slice(0, 200),
html: panel.innerHTML.slice(0, 500),
})),
marker: document.documentElement.getAttribute('data-mnote-local-ocr-filetree-open') || '',
}));
throw new Error(`${error.message}; debug=${JSON.stringify(debug)}`);
});
screenshots.ocrResource = path.join(OUTPUT_DIR, "03-ocr-resource-tab.png");
await page.screenshot({ path: screenshots.ocrResource, fullPage: true });
await page.evaluate((sourcePath) => {
const row = document.querySelector(`[data-mnote-local-ocr-task-row="${CSS.escape(sourcePath)}"]`);
const clear = row && row.querySelector("[data-mnote-local-ocr-task-clear]");
if (!(clear instanceof HTMLButtonElement)) throw new Error("missing OCR clear button");
clear.click();
}, failedSourceRootRelativePath);
await page.waitForFunction(
(sourcePath) => !document.querySelector(`[data-mnote-local-ocr-task-row="${CSS.escape(sourcePath)}"]`),
failedSourceRootRelativePath,
{ timeout: UI_TIMEOUT_MS },
);
const deleteButtonVisible = await page.evaluate((sourcePath) => {
const row = document.querySelector(`[data-mnote-local-ocr-task-row="${CSS.escape(sourcePath)}"]`);
return Boolean(row && row.querySelector("[data-mnote-local-ocr-task-delete]"));
}, sourceRootRelativePath);
assert.equal(deleteButtonVisible, true, "已完成 OCR 任务应展示删除 OCR 按钮");
await writeResult({
ok: true,
task: TASK,
root,
documentId,
ocrRootRelativePath: result.ocrRootRelativePath,
ocrRootRelativePath: uiOcrPath,
screenshots,
});
console.log(JSON.stringify({
@@ -297,7 +382,7 @@ async function main() {
task: TASK,
root,
documentId,
ocrRootRelativePath: result.ocrRootRelativePath,
ocrRootRelativePath: uiOcrPath,
screenshots,
}, null, 2));
} catch (error) {
@@ -0,0 +1,366 @@
#!/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 { execFileSync } = require("node:child_process");
const { chromium } = require("playwright");
const {
BASE_URL,
UI_TIMEOUT_MS,
ensureAuthenticated,
} = require("./tree-shell-smoke-helpers");
const CONTROL_PLANE_DB = "/mnt/Data1T/Mnote_data/control-plane/control-plane.db";
const CHROMIUM_EXECUTABLE_PATH =
process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH ||
[
"/usr/bin/google-chrome-stable",
"/usr/bin/google-chrome",
"/snap/bin/chromium",
"/usr/bin/chromium",
].find((candidate) => fs.existsSync(candidate));
const PROVIDERS = [
{
key: "gpt",
profileId: "shared_api_gpt_chat",
chipText: "ChatOnly / GPT",
markerPrefix: "MNOTE_API_CHAT_GPT",
expectedProfile: "api-gpt-chat",
expectedModel: "aisz-chat/gpt-5.5-extra-high-fast",
},
{
key: "deepseek-flash",
profileId: "shared_api_deepseek_flash_chat",
chipText: "ChatOnly / DeepSeek Flash",
markerPrefix: "MNOTE_API_CHAT_DEEPSEEK_FLASH",
expectedProfile: "api-deepseek-flash-chat",
expectedModel: "deepseek-v4-flash",
},
];
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "task527-chatonly-api-provider-smoke");
const RESULT_PATH = path.join(OUTPUT_DIR, "result.json");
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, workspaceId) {
fs.mkdirSync(path.join(root, ".mnote"), { recursive: true });
fs.writeFileSync(
path.join(root, ".mnote", "workspace.json"),
`${JSON.stringify(
{
workspaceId,
ownerId,
createdAt: new Date().toISOString(),
capabilities: ["local_files", "ai_sessions", "markdown_edit"],
},
null,
2,
)}\n`,
"utf8",
);
}
function sqlQuote(value) {
return `'${String(value).replaceAll("'", "''")}'`;
}
function sqliteExec(sql) {
execFileSync("sqlite3", [CONTROL_PLANE_DB, sql], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
});
}
function sqliteJson(sql, fallback = null) {
try {
const raw = execFileSync("sqlite3", ["-json", CONTROL_PLANE_DB, sql], {
encoding: "utf8",
stdio: ["ignore", "pipe", "pipe"],
}).trim();
return raw ? JSON.parse(raw) : fallback;
} catch {
return fallback;
}
}
function grantWorkspaceAccess({ actorId, workspaceId, root, rootUri, grantId }) {
const now = new Date().toISOString();
sqliteExec(`
INSERT OR IGNORE INTO users (id, email, username, display_name, role, status, created_at, updated_at, revision)
VALUES (${sqlQuote(actorId)}, ${sqlQuote(`${actorId}@example.com`)}, ${sqlQuote(actorId)}, ${sqlQuote(actorId)}, 'user', 'active', ${sqlQuote(now)}, ${sqlQuote(now)}, 1);
INSERT OR REPLACE INTO workspaces (id, owner_user_id, name, kind, root_uri, root_path, source_kind, status, created_at, updated_at, revision)
VALUES (${sqlQuote(workspaceId)}, ${sqlQuote(actorId)}, ${sqlQuote(actorId)}, 'personal', ${sqlQuote(rootUri)}, ${sqlQuote(root)}, 'local_folder', 'active', ${sqlQuote(now)}, ${sqlQuote(now)}, 1);
INSERT OR REPLACE INTO directory_grants (id, user_id, workspace_id, root_uri, root_path, permission, recursive, capabilities_json, source, status, created_by, created_at, updated_at, revision)
VALUES (${sqlQuote(grantId)}, ${sqlQuote(actorId)}, ${sqlQuote(workspaceId)}, ${sqlQuote(rootUri)}, ${sqlQuote(root)}, 'write', 1, '["ai","markdown_edit"]', 'smoke', 'active', ${sqlQuote(actorId)}, ${sqlQuote(now)}, ${sqlQuote(now)}, 1);
`);
}
async function saveScreenshot(page, name) {
const target = path.join(OUTPUT_DIR, `${name}.png`);
await page.screenshot({ path: target, fullPage: false });
return target;
}
async function waitForAssistantMarker(page, marker) {
await page.waitForFunction(
(expectedMarker) => {
const assistantText = Array.from(document.querySelectorAll(".wolai-page-ai-message--assistant"))
.map((node) => node.textContent || "")
.join("\n");
return assistantText.includes(expectedMarker);
},
marker,
{ timeout: 180_000 },
);
}
async function ensurePageAiDrawerOpen(page) {
const drawer = page.locator('[data-testid="wolai-page-ai-drawer"]');
if (await drawer.isVisible().catch(() => false)) return;
await page.getByTestId("wolai-floating-ai").click({ timeout: UI_TIMEOUT_MS });
await drawer.waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
}
async function selectProvider(page, provider) {
await page.locator("[data-page-ai-agent-button]").click({ timeout: UI_TIMEOUT_MS });
await page.locator(`[data-page-ai-agent-id="chat_only"][data-page-ai-profile-id="${provider.profileId}"]`).click({
timeout: UI_TIMEOUT_MS,
});
await page.waitForFunction(
(expected) => document.querySelector("[data-page-ai-agent-chip]")?.textContent?.includes(expected),
provider.chipText,
{ timeout: UI_TIMEOUT_MS },
);
}
async function runProviderSmoke(page, provider, suffix) {
const marker = `${provider.markerPrefix}_${suffix}`;
const runRequests = [];
const runResponses = [];
const deleteResponses = [];
const runRoute = async (route) => {
runRequests.push(JSON.parse(route.request().postData() || "{}"));
await route.continue();
};
await page.route("**/api/hermes/client/runs", runRoute);
const responseListener = async (response) => {
const url = response.url();
const request = response.request();
if (request.method() === "POST" && url.includes("/api/hermes/client/runs")) {
runResponses.push({
url,
status: response.status(),
body: await response.text().catch(() => ""),
});
}
if (request.method() === "DELETE" && url.includes("/api/hermes/client/sessions/")) {
deleteResponses.push({
url,
status: response.status(),
body: await response.text().catch(() => ""),
});
}
};
page.on("response", responseListener);
try {
await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="new-session"]').click({
timeout: UI_TIMEOUT_MS,
});
await selectProvider(page, provider);
await page.locator("[data-page-ai-input]").fill(`请只回复:${marker}`, { timeout: UI_TIMEOUT_MS });
await page.locator('[data-page-ai-action="send"]').click({ timeout: UI_TIMEOUT_MS });
await waitForAssistantMarker(page, marker);
await page.waitForFunction(
() => (document.querySelector("[data-page-ai-run-status]")?.textContent || "").includes("完成"),
null,
{ timeout: 180_000 },
).catch(() => {});
const afterMessageScreenshot = await saveScreenshot(page, `${provider.key}-after-message`);
assert.strictEqual(runRequests.length, 1, `${provider.key} 本轮应只创建一个 run`);
const run = runRequests[0];
assert.strictEqual(run.agentId, "chat_only", `${provider.key} 应使用 ChatOnly agent`);
assert.strictEqual(run.profileId, provider.profileId, `${provider.key} 应使用 API ChatOnly profile`);
assert(run.sessionId, `${provider.key} run payload 应包含 MNote sessionId`);
assert.strictEqual(runResponses.length, 1, `${provider.key} 应返回一个 run response`);
assert.strictEqual(runResponses[0].status, 200, `${provider.key} run response 应成功`);
const runResponse = JSON.parse(runResponses[0].body || "{}");
assert.strictEqual(runResponse.providerKind, "api-chat", `${provider.key} 后端应分流到 api-chat`);
assert.strictEqual(runResponse.runtime?.transport, "api-chat", `${provider.key} 不应启动 ACP/OpenClaw runtime`);
assert.strictEqual(runResponse.runtime?.model, provider.expectedModel, `${provider.key} model 应匹配 registry`);
assert.strictEqual(runResponse.profile, provider.expectedProfile, `${provider.key} 应使用 isolated API profile`);
const assistantTexts = await page.locator(".wolai-page-ai-message--assistant").allTextContents();
const markerAssistantCount = assistantTexts.filter((text) => text.includes(marker)).length;
assert.strictEqual(markerAssistantCount, 1, `${provider.key} 可见 API 回复应只有一条`);
const sessionId = String(run.sessionId);
const bindingRows = sqliteJson(
`SELECT mnote_session_id, provider, status FROM ai_external_conversation_bindings WHERE user_id=${sqlQuote("mnote-e2e")} AND mnote_session_id=${sqlQuote(sessionId)} ORDER BY updated_at DESC LIMIT 5;`,
[],
);
assert.strictEqual(bindingRows.length, 0, `${provider.key} API ChatOnly 不应写网页 provider conversation binding`);
await page.reload({ waitUntil: "domcontentloaded", timeout: UI_TIMEOUT_MS });
await ensurePageAiDrawerOpen(page);
await waitForAssistantMarker(page, marker);
const afterReloadScreenshot = await saveScreenshot(page, `${provider.key}-after-reload`);
const reloadedAssistantTexts = await page.locator(".wolai-page-ai-message--assistant").allTextContents();
assert.strictEqual(
reloadedAssistantTexts.filter((text) => text.includes(marker)).length,
1,
`${provider.key} 刷新恢复后仍应只有一条助手回复`,
);
await page.locator('.wolai-page-ai-header-actions [data-page-ai-action="history"]').click({ timeout: UI_TIMEOUT_MS });
await page.locator('[data-page-ai-panel="history"]').waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
await page.locator(`[data-page-ai-session-row="${sessionId}"]`).waitFor({ state: "visible", timeout: UI_TIMEOUT_MS });
page.once("dialog", async (dialog) => {
await dialog.accept();
});
await page.locator(`[data-page-ai-session-delete="${sessionId}"]`).click({ timeout: UI_TIMEOUT_MS });
await page.waitForFunction(
(id) => !document.querySelector(`[data-page-ai-session-row="${CSS.escape(id)}"]`),
sessionId,
{ timeout: UI_TIMEOUT_MS },
);
const afterDeleteScreenshot = await saveScreenshot(page, `${provider.key}-after-delete`);
assert(deleteResponses.length >= 1, `${provider.key} 应发出本地 session DELETE 请求`);
assert.strictEqual(deleteResponses.at(-1).status, 200, `${provider.key} DELETE 应成功`);
const deleteBody = JSON.parse(deleteResponses.at(-1).body || "{}");
assert.strictEqual(deleteBody?.result?.remoteDelete?.attempted, false, `${provider.key} 不应调用网页远端删除`);
assert.strictEqual(
deleteBody?.result?.remoteDelete?.reason,
"api_chat_has_no_remote_conversation",
`${provider.key} remoteDelete reason 应说明 API Chat 无远端会话`,
);
const remainingRows = sqliteJson(
`SELECT session_id, status FROM ai_runtime_runs WHERE user_id=${sqlQuote("mnote-e2e")} AND session_id=${sqlQuote(sessionId)} AND deleted_at IS NULL LIMIT 5;`,
[],
);
assert.strictEqual(remainingRows.length, 0, `${provider.key} 删除后 SQLite active run 不应残留`);
return {
provider: provider.key,
profileId: provider.profileId,
model: provider.expectedModel,
sessionId,
runId: runResponse.runId,
screenshots: {
afterMessage: afterMessageScreenshot,
afterReload: afterReloadScreenshot,
afterDelete: afterDeleteScreenshot,
},
};
} finally {
await page.unroute("**/api/hermes/client/runs", runRoute).catch(() => {});
page.off("response", responseListener);
}
}
async function main() {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
const suffix = Date.now().toString(36);
const actorId = "mnote-e2e";
const root = fs.mkdtempSync(path.join(os.tmpdir(), "mnote-task527-api-chat-"));
const rootUri = fileUrl(root);
const workspaceId = `local-ws:${actorId}:task527-api-chat-${suffix}`;
const relativePath = "ApiChatOnly.md";
writeWorkspaceManifest(root, actorId, workspaceId);
fs.writeFileSync(path.join(root, relativePath), ["# API ChatOnly", "", `MNOTE_API_CHAT_WORKSPACE_${suffix}`, ""].join("\n"), "utf8");
grantWorkspaceAccess({
actorId,
workspaceId,
root,
rootUri,
grantId: `grant_task527_api_chat_${suffix}`,
});
const browser = await chromium.launch({
headless: true,
...(CHROMIUM_EXECUTABLE_PATH ? { executablePath: CHROMIUM_EXECUTABLE_PATH } : {}),
});
const context = await browser.newContext({
viewport: { width: 1440, height: 960 },
locale: "zh-CN",
extraHTTPHeaders: {
"x-mnote-actor-id": actorId,
"x-mnote-actor-type": "user",
},
});
const page = await context.newPage();
let caughtError = null;
const results = [];
try {
await ensureAuthenticated(page, context.request);
const response = await page.goto(documentUrl(root, relativePath), {
waitUntil: "domcontentloaded",
timeout: UI_TIMEOUT_MS,
});
assert(response && response.status() === 200, `文档页状态码异常: ${response && response.status()}`);
await page.locator('[data-testid="mnote-leptos-tiptap-island-editor-root"] .ProseMirror').first().waitFor({
state: "visible",
timeout: UI_TIMEOUT_MS,
});
await ensurePageAiDrawerOpen(page);
await saveScreenshot(page, "initial-drawer");
for (const provider of PROVIDERS) {
results.push(await runProviderSmoke(page, provider, suffix));
}
} catch (error) {
caughtError = error;
await saveScreenshot(page, "failure").catch(() => undefined);
} finally {
await browser.close().catch(() => {});
}
const resultPayload = {
ok: !caughtError,
error: caughtError ? String(caughtError && caughtError.stack || caughtError) : "",
root,
workspaceId,
relativePath,
providers: results,
outputDir: OUTPUT_DIR,
resultPath: RESULT_PATH,
};
fs.writeFileSync(RESULT_PATH, `${JSON.stringify(resultPayload, null, 2)}\n`, "utf8");
if (caughtError) {
console.error(JSON.stringify(resultPayload, null, 2));
process.exit(1);
}
console.log(JSON.stringify(resultPayload, null, 2));
}
main().catch((error) => {
console.error(error);
process.exit(1);
});