Files
mnote/scripts/task-page-block-ai-context-format-smoke.js
T
lix-2026 f292c6710a feat: EditorRuntimeActor - 三层缓存/delta/事件架构
Phase A — EditorRuntimeActor 内存缓存层
- 新增 editor_actor.rs: EditorBlockDocument 内存态 + apply_command + load_or_init
- block.rs 四个写工具(replace/insert/delete/move)接入 actor 路径
- editor_actor feature flag(MNOTE_WEB_ENABLE_EDITOR_ACTOR=true 默认开启)
- bridge-runtime 三个核心函数公开化
- rust-toolchain: 1.89 → stable(修复 spike WASM 编译阻塞)

Phase B — 编辑器增量 delta channel
- BlockDelta/DeltaOperation 类型 + actor.build_block_delta()
- leptos-tiptap spike: mnote:editor:block-delta CustomEvent 监听 + JSON patch
- DocumentAiAgentPanel: 拦截 blockDelta → window dispatchEvent
- 工具响应含 blockDelta 字段供前端消费

Phase C — 事件 stream delta
- broadcast channel 在 AppState/actor/SSE 三层贯通
- tree_events SSE 端点发 block.delta 事件
- 旧客户端降级兼容

环境修复
- rustc recursion_limit = 1024(修复 Leptos SSR 类型深度溢出)
- run-convex-deploy.js(封装 Convex function 部署到本地后端 3210)

ref: design/07-ai/process/7-13-page-block-editor-runtime-actor-v1.md
2026-05-16 22:03:30 +08:00

316 lines
12 KiB
JavaScript

#!/usr/bin/env node
"use strict";
const assert = require("node:assert");
const fs = require("node:fs/promises");
const path = require("node:path");
const { chromium } = require("playwright");
const {
BASE_URL,
cleanupDocuments,
createTempDocument,
ensureAuthenticated,
openDocument,
renameDocument,
requestJson,
} = require("./tree-shell-smoke-helpers");
const OUT_DIR = path.join(process.cwd(), "tmp", "page-block-ai-context-format-smoke");
async function callMnoteTool(request, payload) {
return requestJson(request, "/api/hermes/tools/mnote/call", {
method: "POST",
headers: { "x-mnote-actor-id": payload.actorId || "smoke-user" },
data: payload,
});
}
function toolByName(manifest, name) {
const tools = manifest?.manifest?.tools || manifest?.tools || [];
const tool = tools.find((candidate) => candidate.name === name);
assert(tool, `manifest 缺少工具:${name}`);
return tool;
}
function assertAnnotationShape(tool, expected) {
assert(tool.annotations, `${tool.name} 缺少 annotations`);
for (const key of [
"readonly",
"destructive",
"idempotent",
"requiresApproval",
"approvalMode",
"runtimeOwner",
"writeOwner",
"selectionEffect",
]) {
assert(Object.hasOwn(tool.annotations, key), `${tool.name} annotations 缺少 ${key}`);
}
for (const [key, value] of Object.entries(expected)) {
assert.deepEqual(tool.annotations[key], value, `${tool.name} annotations.${key} 不符合预期`);
}
}
function assertIncludes(value, fragment, message) {
assert(String(value || "").includes(fragment), message);
}
function assertExcludes(value, fragment, message) {
assert(!String(value || "").includes(fragment), message);
}
async function main() {
const suffix = Date.now().toString(36);
const title = `TEST-AI-CONTEXT-FORMAT-${suffix}`;
const createdIds = [];
const evidence = {
ok: false,
baseUrl: BASE_URL,
title,
steps: [],
};
await fs.mkdir(OUT_DIR, { recursive: true });
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
try {
const viewer = await ensureAuthenticated(page, context.request);
const actorId = viewer.userId || "smoke-user";
const target = await createTempDocument(context.request);
createdIds.push(target.documentId);
evidence.documentId = target.documentId;
evidence.workspaceId = target.workspaceId;
await renameDocument(context.request, target.workspaceId, target.documentId, title);
const manifest = await requestJson(context.request, "/api/hermes/tools/mnote/manifest", {
method: "GET",
headers: { "x-mnote-actor-id": actorId },
});
const docFetchTool = toolByName(manifest, "mnote.doc.fetch");
const blockFetchTool = toolByName(manifest, "mnote.block.fetch");
const blockReplaceTool = toolByName(manifest, "mnote.block.replace");
const pageSaveTool = toolByName(manifest, "mnote.page.save");
assertAnnotationShape(docFetchTool, {
readonly: true,
destructive: false,
runtimeOwner: "mnote-web",
writeOwner: "rust-runtime-kernel",
selectionEffect: "preserve",
});
assertAnnotationShape(blockFetchTool, {
readonly: true,
destructive: false,
selectionEffect: "preserve",
});
assertAnnotationShape(blockReplaceTool, {
readonly: false,
destructive: false,
selectionEffect: "may_change",
});
assertAnnotationShape(pageSaveTool, {
readonly: false,
destructive: true,
approvalMode: "yolo",
selectionEffect: "may_change",
});
evidence.steps.push({
name: "manifest.annotations",
checkedTools: [docFetchTool.name, blockFetchTool.name, blockReplaceTool.name, pageSaveTool.name],
pageSaveDestructive: pageSaveTool.annotations.destructive,
});
const seed = await callMnoteTool(context.request, {
toolName: "mnote.page.save",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_seed_${suffix}`,
runId: `run_context_seed_${suffix}`,
toolCallId: `call_context_seed_${suffix}`,
traceId: `trace_context_seed_${suffix}`,
idempotencyKey: `idem_context_seed_${suffix}`,
dryRun: false,
capabilityScope: ["page.write"],
args: {
mode: "replace",
content: [
{ id: "p_1", type: "paragraph", content: [{ type: "text", text: `第一段 ${suffix}` }] },
{ id: "p_2", type: "paragraph", content: [{ type: "text", text: `第二段 ${suffix}` }] },
{ id: "p_3", type: "paragraph", content: [{ type: "text", text: `第三段 ${suffix}` }] },
],
},
});
assert.equal(seed.ok, true, "初始化 page.save 应成功");
evidence.steps.push({ name: "seed", commandName: seed.result.commandName });
const selectionXml = await callMnoteTool(context.request, {
toolName: "mnote.doc.fetch",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_fetch_${suffix}`,
runId: `run_context_fetch_xml_${suffix}`,
toolCallId: `call_context_fetch_xml_${suffix}`,
traceId: `trace_context_fetch_xml_${suffix}`,
capabilityScope: ["page.read"],
args: {
scope: "selection",
selectedBlockIds: ["p_2"],
format: "page_xml",
detail: "with_ids",
maxBlocks: 10,
},
});
assert.equal(selectionXml.result.schema, "mnote.page_ai_context.v1", "doc.fetch 应返回 page AI context schema");
assert.equal(selectionXml.result.scope, "selection", "doc.fetch 应保留 selection scope");
assert.equal(selectionXml.result.format, "page_xml", "doc.fetch 应返回 page_xml format");
assert.deepEqual(selectionXml.result.allowedTargetBlockIds, ["p_2"], "selection 应冻结 allowedTargetBlockIds");
assert.equal(selectionXml.result.blocks.length, 1, "selection 只应返回选中块");
assert.equal(selectionXml.result.blocks[0].blockId, "p_2", "selection 应返回 p_2");
assert(selectionXml.result.blocks[0].revisionRef, "selection block 必须带 revisionRef");
assertIncludes(selectionXml.result.content, '<block id="p_2"', "page_xml 应包含 p_2 block id");
assertIncludes(selectionXml.result.content, 'revisionRef="', "page_xml 应包含 revisionRef");
assertIncludes(selectionXml.result.content, `第二段 ${suffix}`, "page_xml 应包含选中文本");
assertExcludes(selectionXml.result.content, `第一段 ${suffix}`, "page_xml 不应包含未选中 p_1");
assertExcludes(selectionXml.result.content, `第三段 ${suffix}`, "page_xml 不应包含未选中 p_3");
evidence.steps.push({
name: "doc.fetch.selection.page_xml",
schema: selectionXml.result.schema,
allowedTargetBlockIds: selectionXml.result.allowedTargetBlockIds,
revision: selectionXml.result.revision,
conflictDetectionKey: selectionXml.result.conflictDetectionKey,
blockRevisionRef: selectionXml.result.blocks[0].revisionRef,
});
const selectionText = await callMnoteTool(context.request, {
toolName: "mnote.doc.fetch",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_fetch_${suffix}`,
runId: `run_context_fetch_text_${suffix}`,
toolCallId: `call_context_fetch_text_${suffix}`,
traceId: `trace_context_fetch_text_${suffix}`,
capabilityScope: ["page.read"],
args: {
scope: "selection",
selectedBlockIds: ["p_2"],
format: "text",
detail: "with_ids",
},
});
assertIncludes(selectionText.result.content, `[p_2] 第二段 ${suffix}`, "text format 应包含选中块 id 与文本");
assertExcludes(selectionText.result.content, `第一段 ${suffix}`, "text format 不应包含未选中 p_1");
assertExcludes(selectionText.result.content, `第三段 ${suffix}`, "text format 不应包含未选中 p_3");
evidence.steps.push({ name: "doc.fetch.selection.text", content: selectionText.result.content });
const blockXml = await callMnoteTool(context.request, {
toolName: "mnote.block.fetch",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_block_${suffix}`,
runId: `run_context_block_xml_${suffix}`,
toolCallId: `call_context_block_xml_${suffix}`,
traceId: `trace_context_block_xml_${suffix}`,
capabilityScope: ["block.read"],
args: {
blockId: "p_2",
contextBefore: 1,
contextAfter: 1,
format: "page_xml",
},
});
assert.equal(blockXml.result.block.blockId, "p_2", "block.fetch page_xml 应读取 p_2");
assert.equal(blockXml.result.context.before[0].blockId, "p_1", "block.fetch before 应来自同父级");
assert.equal(blockXml.result.context.after[0].blockId, "p_3", "block.fetch after 应来自同父级");
assertIncludes(blockXml.result.content, '<block id="p_2"', "block.fetch page_xml 应包含目标 block id");
assertIncludes(blockXml.result.content, 'revisionRef="', "block.fetch page_xml 应包含 revisionRef");
const blockText = await callMnoteTool(context.request, {
toolName: "mnote.block.fetch",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_block_${suffix}`,
runId: `run_context_block_text_${suffix}`,
toolCallId: `call_context_block_text_${suffix}`,
traceId: `trace_context_block_text_${suffix}`,
capabilityScope: ["block.read"],
args: {
blockId: "p_2",
format: "text",
},
});
assertIncludes(blockText.result.content, `[p_2] 第二段 ${suffix}`, "block.fetch text 应包含块 id 与文本");
evidence.steps.push({
name: "block.fetch.page_xml.text",
blockId: blockXml.result.block.blockId,
revisionRef: blockXml.result.block.revisionRef,
contextBefore: blockXml.result.context.before.map((block) => block.blockId),
contextAfter: blockXml.result.context.after.map((block) => block.blockId),
});
const outOfScopeResponse = await context.request.fetch(`${BASE_URL}/api/hermes/tools/mnote/call`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-mnote-actor-id": actorId,
},
data: JSON.stringify({
toolName: "mnote.doc.apply_block_ops",
workspaceId: target.workspaceId,
documentId: target.documentId,
actorId,
sessionId: `sess_context_scope_${suffix}`,
runId: `run_context_scope_${suffix}`,
toolCallId: `call_context_scope_${suffix}`,
traceId: `trace_context_scope_${suffix}`,
idempotencyKey: `idem_context_scope_${suffix}`,
dryRun: true,
capabilityScope: ["block.write"],
args: {
allowedTargetBlockIds: ["p_2"],
operations: [
{
op: "replace",
blockId: "p_1",
content: `越界修改 ${suffix}`,
},
],
},
}),
});
const outOfScopeText = await outOfScopeResponse.text();
assert.equal(outOfScopeResponse.status(), 400, "选区外写入应被 Rust tool 拒绝");
assertIncludes(outOfScopeText, "mnote_block_target_out_of_scope", "选区外写入应返回明确错误码");
evidence.steps.push({
name: "write.out_of_scope.blocked",
status: outOfScopeResponse.status(),
errorCode: "mnote_block_target_out_of_scope",
});
await openDocument(page, target.workspaceId, target.documentId);
await page.getByText(`第二段 ${suffix}`).waitFor({ state: "visible", timeout: 30_000 });
const screenshotPath = path.join(OUT_DIR, `${suffix}-page.png`);
await page.screenshot({ path: screenshotPath, fullPage: true });
evidence.screenshot = screenshotPath;
evidence.ok = true;
const evidencePath = path.join(OUT_DIR, `${suffix}.json`);
await fs.writeFile(evidencePath, JSON.stringify(evidence, null, 2), "utf8");
console.log(JSON.stringify({ ...evidence, evidencePath }, null, 2));
} finally {
await cleanupDocuments(context.request, createdIds).catch(() => undefined);
await context.close().catch(() => undefined);
await browser.close().catch(() => undefined);
}
}
main().catch((error) => {
console.error(error instanceof Error ? error.stack || error.message : String(error));
process.exit(1);
});