AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(mcp): support creating infographic notes via MCP and companion
tianma-if50d4d5a75bd5
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.tsindex 60767323..142b46ad 100644--- a/apps/api/src/companion-agent-tools.ts+++ b/apps/api/src/companion-agent-tools.ts@@ -1,4 +1,4 @@-import { COMPANION_NOTE_EDIT_MAX_CHARS, parseDiagramDocument, parseTableDocument, type CompanionSource, type CompanionTodo, type CompanionToolCall, type CompanionToolDefinition, type CompanionTurnInput, type MemoDetail, type MemoSummary } from "@edgeever/shared";+import { COMPANION_NOTE_EDIT_MAX_CHARS, parseDiagramDocument, parseInfographicDocument, parseTableDocument, type CompanionSource, type CompanionTodo, type CompanionToolCall, type CompanionToolDefinition, type CompanionTurnInput, type MemoDetail, type MemoSummary } from "@edgeever/shared";import type { DatabaseAdapter } from "./storage-contract";import type { AppContext } from "./api-context";import type { CompanionScope } from "./companion-service";@@ -15,7 +15,7 @@ import { AppError } from "./app-error";const AUTO_APPLY_WRITES = new Set(COMPANION_MCP_TOOLS.filter(tool => !tool.annotations.readOnlyHint).map(tool => tool.name),);-const INBOX_DEFAULT_NOTEBOOK_TOOLS = new Set(["create_memo", "create_diagram_memo", "use_note_template"]);+const INBOX_DEFAULT_NOTEBOOK_TOOLS = new Set(["create_memo", "create_diagram_memo", "create_infographic_memo", "use_note_template"]);export async function resolveWorkspaceInboxId(db: DatabaseAdapter, workspaceId: string) {const preferred = workspaceInboxId(workspaceId);@@ -69,7 +69,11 @@ export const explicitDiagramKind = (message: string): ExplicitDiagramKind | undereturn matches.length === 1 ? matches[0][0] : undefined;};+export const requestsInfographic = (message: string) =>+ /(?:信息图|資訊圖|インフォグラフィック|\binfographic\b)/iu.test(message);+const creatingUnplacedNote = (message: string) => Boolean(explicitDiagramKind(message))+ || requestsInfographic(message)|| /(?:新建|创建|生成|写一).{0,16}(?:笔记|备忘|流程图|思维导图|架构图|mind map|flowchart)/iu.test(message);const asksForDestinationNotebook = (prompt: string) =>@@ -114,8 +118,9 @@ const TOOL_HINTS: Record<string, string> = {list_memos: " To list a named notebook, call find_notebooks first and pass that id. Without notebookId this lists the whole workspace, newest updated first. For newly created notes in a time range, use search_memos with createdAfter. If hasMore is true, say the list is incomplete.",search_memos: " Searches note titles and bodies, not notebook names. query is optional. For recently created or added notes, pass createdAfter (YYYY-MM-DD or ISO date-time) and omit query; never put this week/最近/新增 in query. For recently edited notes, use updatedAfter. Do not pass notebookId unless find_notebooks or list_notebooks returned it. For notes in a named notebook, find_notebooks then list_memos. If hasMore is true, say the list is incomplete.",list_tags: " Use this when the user names a tag.",- create_memo: " For prose Markdown notes only. Never use this for 思维导图/mind maps, 流程图/flowcharts, or 架构图; use create_diagram_memo. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",- create_diagram_memo: " Create an editable visual diagram note. kind=mind-map for 思维导图/mind map, flowchart for 流程图, architecture for 架构图. Omit edge ids; EdgeEver generates them. For mind maps, give a root and children with parentId; omit node type. If the user did not name a notebook, omit notebookId. The diagram is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Build nodes from the open note body in Focus DATA when the user refers to this note.",+ create_memo: " For prose Markdown notes only. Never use this for 思维导图/mind maps, 流程图/flowcharts, 架构图, or 信息图/infographics. Use create_diagram_memo for diagrams and create_infographic_memo for infographics. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",+ create_diagram_memo: " Create an editable visual diagram note. kind=mind-map for 思维导图/mind map, flowchart for 流程图, architecture for 架构图. Never use this for 信息图/infographic; call create_infographic_memo. Omit edge ids; EdgeEver generates them. For mind maps, give a root and children with parentId; omit node type. If the user did not name a notebook, omit notebookId. The diagram is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Build nodes from the open note body in Focus DATA when the user refers to this note.",+ create_infographic_memo: " Create an AntV infographic note (信息图). A share, proportion, or 占比 uses template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. The infographic is saved in the inbox (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it.",get_diagram: " Read an existing editable diagram as a semantic graph. Call this before update_diagram. Do not use get_memo when you only need the diagram structure.",update_diagram: " Edit an existing diagram after get_diagram. Pass expectedRevision from get_diagram. Use add_node, update_node, remove_node, add_edge, update_edge, or remove_edge. Do not create a new diagram unless the user asked for a new note.",use_note_template: " Create a new memo from a template. If the user did not name a notebook, omit notebookId. The note is saved in the inbox (等待分类). Do not ask which notebook.",@@ -197,22 +202,37 @@ const companionMcpDescription = (definition: (typeof COMPANION_MCP_TOOLS)[numberexport function companionToolDefinitions(input: CompanionTurnInput): CompanionToolDefinition[] {if (!input.allowNotes) return [];const requestedDiagramKind = explicitDiagramKind(input.message);+ const infographicRequest = requestsInfographic(input.message) && !requestedDiagramKind;+ const shareRequest = infographicRequest && /(?:占比|份额|构成比例|饼图|环形图|\bpie\b|\bdonut\b)/iu.test(input.message);return [...companionMcpCatalog(input).map(definition => {const inputSchema = definition.inputSchema as Record<string, unknown>;- if (definition.name !== "create_diagram_memo" || !requestedDiagramKind) {- return withOptionalInboxNotebook({ name: definition.name, description: companionMcpDescription(definition), inputSchema });+ let described = withOptionalInboxNotebook({ name: definition.name, description: companionMcpDescription(definition), inputSchema });+ if (definition.name === "create_diagram_memo" && requestedDiagramKind) {+ const properties = inputSchema.properties as Record<string, unknown>;+ const kind = properties.kind as Record<string, unknown>;+ described = withOptionalInboxNotebook({+ name: definition.name,+ description: `${companionMcpDescription(definition)} The user explicitly requested kind=${requestedDiagramKind}; use exactly that kind.`,+ inputSchema: {+ ...inputSchema,+ properties: { ...properties, kind: { ...kind, enum: [requestedDiagramKind] } },+ },+ });}- const properties = inputSchema.properties as Record<string, unknown>;- const kind = properties.kind as Record<string, unknown>;- return withOptionalInboxNotebook({- name: definition.name,- description: `${companionMcpDescription(definition)} The user explicitly requested kind=${requestedDiagramKind}; use exactly that kind.`,- inputSchema: {- ...inputSchema,- properties: { ...properties, kind: { ...kind, enum: [requestedDiagramKind] } },- },- });+ if (definition.name === "create_diagram_memo" && infographicRequest) {+ described = {+ ...described,+ description: `${described.description} The user asked for an infographic (信息图). Do not call this tool. Call create_infographic_memo.`,+ };+ }+ if (definition.name === "create_infographic_memo" && shareRequest) {+ described = {+ ...described,+ description: `${described.description} This request is a share or 占比. Use template chart-pie-donut-plain-text with numeric data.values. Do not imitate it with a mind map.`,+ };+ }+ return described;}),{name: "todo_write",@@ -221,7 +241,7 @@ export function companionToolDefinitions(input: CompanionTurnInput): CompanionTo},{name: "ask_user_question",- description: "Ask the user 1-3 structured questions when you cannot proceed without a choice among existing notes or strategies. Do not use this to choose a notebook for a new note, diagram, or template. Do not use this to narrate writes you can already perform. Stop after calling it.",+ description: "Ask the user 1-3 structured questions when you cannot proceed without a choice among existing notes or strategies. Do not use this to choose a notebook for a new note, diagram, infographic, or template. Do not use this to narrate writes you can already perform. Stop after calling it.",inputSchema: ASK_USER_QUESTION_SCHEMA,},];@@ -284,6 +304,10 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Compani}const { args: parameters_ } = validateCompanionTool(definition.name, parameters);const requestedDiagramKind = explicitDiagramKind(args.input.message);+ if (definition.name === "create_diagram_memo" && requestsInfographic(args.input.message) && !requestedDiagramKind) {+ throw new AppError("invalid_params",+ "The user asked for an infographic (信息图). Call create_infographic_memo. Do not create a mind map, flowchart, or architecture diagram.", 400);+ }if (definition.name === "create_diagram_memo" && requestedDiagramKind && parameters_.kind !== requestedDiagramKind) {throw new AppError("invalid_params",`The user explicitly requested ${requestedDiagramKind}; create_diagram_memo.kind must be ${requestedDiagramKind}.`, 400);@@ -321,6 +345,9 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companiif (parseTableDocument(memo.contentMarkdown)) {throw new AppError("invalid_params", "This is a structured table. Do not replace it with update_memo.", 400);}+ if (parseInfographicDocument(memo.contentMarkdown)) {+ throw new AppError("invalid_params", "This is an infographic. Do not replace it with update_memo.", 400);+ }if (memo.contentMarkdown.length > COMPANION_NOTE_EDIT_MAX_CHARS || parameters_.contentMarkdown.length > COMPANION_NOTE_EDIT_MAX_CHARS) {throw new AppError("invalid_params", "This note edit is too large to review. Split it into a smaller change.", 400);}@@ -380,6 +407,20 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: CompaninodeCount: Array.isArray(created.diagram?.nodes) ? created.diagram.nodes.length : undefined,});}+ if (definition.name === "create_infographic_memo") {+ const created = result as { memo: MemoDetail; template?: string };+ remember(created.memo);+ return done({+ applied: true,+ id: created.memo.id,+ title: created.memo.title,+ notebookId: created.memo.notebookId,+ notebookName: await notebookName(created.memo.notebookId),+ revision: created.memo.revision,+ template: created.template,+ infographic: true,+ });+ }if (definition.name === "update_diagram") {const updated = result as { memo: { id: string; title: string | null; revision: number }; diagram?: { nodes?: unknown[] }; changes?: unknown };inspected.set(updated.memo.id, updated.memo.revision);@@ -412,7 +453,7 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companireturn done(payload);}if (definition.name === "get_memo") {- const payload = result as { memo: MemoDetail; diagram?: { kind?: string }; structuredTable?: unknown };+ const payload = result as { memo: MemoDetail; diagram?: { kind?: string }; structuredTable?: unknown; infographic?: { template?: string } };const memo = payload.memo;remember(memo);if (payload.diagram) {@@ -428,7 +469,10 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companireturn done({ id: memo.id, title: memo.title, notebookId: memo.notebookId, tags: memo.tags, revision: memo.revision,createdAt: memo.createdAt, updatedAt: memo.updatedAt,content, truncated: content.length !== memo.contentMarkdown.length,- ...(payload.structuredTable ? {+ ...(payload.infographic ? {+ infographic: payload.infographic,+ message: "This is an infographic note. Do not replace it with update_memo or turn it into a diagram.",+ } : payload.structuredTable ? {structuredTable: payload.structuredTable,message: "This is a structured table. Answer from this content. Do not replace it with update_memo.",} : {}),diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.tsindex 4eb08660..eae1117a 100644--- a/apps/api/src/companion-prepare.ts+++ b/apps/api/src/companion-prepare.ts@@ -11,7 +11,7 @@ import { listCompanionMemories, listCompanionTurns, mapCompanionTurn, type Compaimport { companionToolDefinitions } from "./companion-agent-tools";import { parseJsonArray } from "./companion-tool-receipts";-export const COMPANION_IDENTITY_VERSION = 14;+export const COMPANION_IDENTITY_VERSION = 15;export const COMPANION_MAX_STEPS = 8;export const COMPANION_MAX_OUTPUT_TOKENS = 2048;export const COMPANION_INSTRUCTIONS = `You are EdgeEver, a thoughtful personal knowledge companion.@@ -21,13 +21,13 @@ Only claim to remember information present in supplied context. Distinguish explThe user controls long-term memory through the UI. You cannot save, edit, or forget memories yourself.Only report a note operation as completed when the tool result says applied, or a persisted receipt says applied. A proposal is not completion.Never claim a reminder was scheduled or an external action completed.-You can use EdgeEver's shared tools to read, create, update, import, merge, move, tag, trash and restore notes, restore revisions, organize notebooks, create editable diagrams, and manage note templates and AI instructions.+You can use EdgeEver's shared tools to read, create, update, import, merge, move, tag, trash and restore notes, restore revisions, organize notebooks, create editable diagrams and infographics, and manage note templates and AI instructions.Title, tag, move, trash, restore, create, merge, and diagram tools execute immediately. An update_memo that includes contentMarkdown returns awaiting_user_confirmation and does not change the note until the user confirms. Never describe that proposal as applied. Trashed notes go to the recycle bin; content edits keep revision history. Read tools and explicit dry runs execute immediately.Read every source note completely before merging or replacing its body. Do not merge merely because notes share a broad topic: look for one coherent idea or the user's explicit selection.Merging preserves source bodies/attachments and existing tags, moves sources to trash and revokes their public shares. A destination notebook may be specified.Content changes use update_memo with the exact replacement Markdown. Prefer existing tags; remove tags only when requested.Never operate on hypothetical IDs: confirm the prerequisite first, then use its real result.-For multi-step organization (≥3 steps), call todo_write first and keep it current. If you cannot choose among existing notes or strategies, call ask_user_question once and stop. Never ask which notebook should receive a new note, diagram, or template. Omit notebookId and it is saved in the inbox notebook (等待分类).+For multi-step organization (≥3 steps), call todo_write first and keep it current. If you cannot choose among existing notes or strategies, call ask_user_question once and stop. Never ask which notebook should receive a new note, diagram, infographic, or template. Omit notebookId and it is saved in the inbox notebook (等待分类).Do not repeat writes already listed as applied in Historical operation receipts.The user already sees each tool in a timeline. Do not narrate that you will search, read, or create, and do not write status updates such as "I will now" or "I have obtained". After tools finish, write only the user-facing answer: what you did, with note links.Emptying the trash, public sharing, binary uploads, and system administration are not exposed. Do not claim otherwise.@@ -44,6 +44,7 @@ search_memos matches note titles and bodies, not notebook names. Query is optionIf list_memos or search_memos sets hasMore, say the list is incomplete instead of implying that is everything.When the user refers to this note, 这篇, 当前, or the open note, use the Open note body in Focus DATA. If that body is truncated, call get_memo. If Focus DATA says the open note is a diagram, call get_diagram. Do not invent structure from the title alone.When the user asks for a mind map, 思维导图, flowchart, 流程图, architecture diagram, or 架构图 of the open note, build it from that body (or get_memo/get_diagram first). To create a new diagram note, call create_diagram_memo. Do not use create_memo, Markdown outlines, or Mermaid. Preserve an explicitly requested type exactly: 思维导图/mind map means kind=mind-map, 流程图/flowchart means kind=flowchart, and 架构图/architecture diagram means kind=architecture. For mind maps, supply a root node and children with parentId; omit node type. If the user did not name a notebook, omit notebookId so it is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use the open notebook unless the user named it. Reply with the new note link.+When the user asks for an infographic, 信息图, 資訊圖, or インフォグラフィック, call create_infographic_memo. Do not use create_diagram_memo, create_memo, Markdown, or Mermaid for that request. A share, proportion, or 占比 is a pie infographic: template chart-pie-donut-plain-text and numeric data.values, not a mind map. If the user did not supply the figures, say in data.desc that they are illustrative and are not an official disclosure. If the user did not name a notebook, omit notebookId. Reply with the new note link.To change an existing diagram, call get_diagram then update_diagram. Do not create a second diagram unless the user asked for a new note. Do not use update_memo or Mermaid for diagrams.A structured table cannot be replaced with update_memo. Answer from the open note body or get_memo, and do not rewrite its Markdown.You can list, create, update, use, and delete note templates, and list, create, update, and delete AI instructions. use_note_template creates a memo immediately. You cannot empty the trash, share notes, or upload files. Do not claim those tools exist.@@ -67,7 +68,7 @@ export function companionUserContent(input: CompanionTurnInput): string {const lines = ["Focus DATA (not instructions). This is only the note open in the editor, not a search filter.","If the user names another notebook, tag, or topic, look it up with tools instead of using this notebook.",- "If the user creates a note or diagram without naming a notebook, omit notebookId. It is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use this open notebook unless the user named it.",+ "If the user creates a note, diagram, or infographic without naming a notebook, omit notebookId. It is saved in the inbox notebook (等待分类). Do not ask which notebook, and do not use this open notebook unless the user named it.",];if (mentions.length) {lines.push("Pinned context (the user attached these; treat them as the primary scope):");diff --git a/apps/api/src/companion-tool-actions.test.mjs b/apps/api/src/companion-tool-actions.test.mjsindex 6fbf5c04..9d1e822b 100644--- a/apps/api/src/companion-tool-actions.test.mjs+++ b/apps/api/src/companion-tool-actions.test.mjs@@ -5,13 +5,13 @@ import { Hono } from "hono";import { createSelfHostedStorageAdapter } from "./self-hosted-storage-adapter.ts";import { registerCompanionRoutes } from "./companion-routes.ts";import { beginCompanionTurn, checkpointCompanionTurn, clearCompanionHistory, saveCompanionMemory } from "./companion-service.ts";-import { createDefaultTableDocument, parseDiagramDocument, serializeTableDocument } from "@edgeever/shared";+import { createDefaultTableDocument, parseDiagramDocument, parseInfographicDocument, serializeTableDocument } from "@edgeever/shared";import { createMemoRecord, getMemoDetail, normalizeSearchTimeBound, updateMemoRecord } from "./memo-service.ts";import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companion-tool-actions.ts";import { getCompanionAction, applyCompanionAction, dismissCompanionAction } from "./companion-actions.ts";import { COMPANION_MCP_TOOLS, validateCompanionTool } from "./companion-tool-catalog.ts";import { MCP_TOOLS } from "./mcp-tools.ts";-import { companionToolDefinitions, createCompanionTools, explicitDiagramKind, resolveWorkspaceInboxId } from "./companion-agent-tools.ts";+import { companionToolDefinitions, createCompanionTools, explicitDiagramKind, requestsInfographic, resolveWorkspaceInboxId } from "./companion-agent-tools.ts";import { companionExecutionReceipts } from "./companion-runtime.ts";const databases = [];@@ -49,7 +49,7 @@ async function setup() {describe("shared companion MCP adapter", () => {test("reuses the exact reviewed MCP definitions, with no administration or upload tools", () => {- expect(COMPANION_MCP_TOOLS).toHaveLength(43);+ expect(COMPANION_MCP_TOOLS).toHaveLength(44);for (const definition of COMPANION_MCP_TOOLS) expect(MCP_TOOLS.includes(definition)).toBe(true);for (const name of ["upload_memo_image", "upload_memo_attachment", "empty_trash", "share_memo"]) {expect(() => validateCompanionTool(name, {})).toThrow();@@ -115,7 +115,7 @@ describe("shared companion MCP adapter", () => {test("read and dry-run tools reuse MCP without writing or requiring a proposal", async () => {const f = await setup();const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });- expect(Object.keys(tools)).toHaveLength(45);+ expect(Object.keys(tools)).toHaveLength(46);expect(await tools.get_memo.execute({ memoId: f.notes[0].id })).toMatchObject({ content: "One original content" });expect(await tools.trash_memos.execute({ memoIds: [f.notes[0].id], dryRun: true })).toMatchObject({ dryRun: true });expect(await getMemoDetail(f.db, scope.workspaceId, f.notes[0].id)).not.toBeNull();@@ -294,7 +294,7 @@ describe("shared companion MCP adapter", () => {expect(definition.description).toContain("use exactly that kind");expect(definition.description).toContain("等待分类");const plain = companionToolDefinitions(f.input);- for (const name of ["create_memo", "create_diagram_memo", "use_note_template"]) {+ for (const name of ["create_memo", "create_diagram_memo", "create_infographic_memo", "use_note_template"]) {const tool = plain.find(item => item.name === name);expect(tool.inputSchema.required ?? []).not.toContain("notebookId");expect(tool.description).toContain("等待分类");@@ -335,6 +335,58 @@ describe("shared companion MCP adapter", () => {expect(named.memo.notebookId).toBe("ideas");expect(await resolveWorkspaceInboxId(f.db, scope.workspaceId)).toBe(inboxId);});+ test("an infographic request creates a pie infographic instead of a mind map", async () => {+ const message = "给我生成一个腾讯营收占比的信息图。";+ expect(requestsInfographic(message)).toBe(true);+ expect(explicitDiagramKind(message)).toBeUndefined();+ const f = await setup();+ const inboxId = `${scope.workspaceId}_inbox`;+ f.sqlite.query("INSERT INTO notebooks(id, workspace_id, name, slug) VALUES (?, ?, '等待分类', 'inbox')").run(inboxId, scope.workspaceId);+ const agentInput = { ...f.input, message };+ const definitions = companionToolDefinitions(agentInput);+ expect(definitions.find(tool => tool.name === "create_diagram_memo").description).toContain("create_infographic_memo");+ expect(definitions.find(tool => tool.name === "create_infographic_memo").description).toContain("chart-pie-donut-plain-text");+ const tools = createCompanionTools({ ...f, input: agentInput, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });+ await expect(tools.create_diagram_memo.execute({+ title: "腾讯 2025 年营收占比信息图",+ kind: "mind-map",+ nodes: [{ id: "root", label: "营收" }, { id: "ads", label: "网络广告 16%", parentId: "root" }],+ })).rejects.toMatchObject({ code: "invalid_params", message: expect.stringContaining("create_infographic_memo") });+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM memos WHERE title LIKE '%营收%'").get().n).toBe(0);+ const created = await tools.create_infographic_memo.execute({+ data: {+ title: "腾讯 2025 年营收占比",+ desc: "图中比例为演示用估算,不代表腾讯官方披露数据。",+ values: [+ { label: "增值服务", value: 52 },+ { label: "金融科技与企业服务", value: 30 },+ { label: "网络广告", value: 16 },+ { label: "其他业务", value: 2 },+ ],+ },+ template: "chart-pie-donut-plain-text",+ });+ expect(created).toMatchObject({+ applied: true,+ notebookId: inboxId,+ template: "chart-pie-donut-plain-text",+ title: "腾讯 2025 年营收占比",+ infographic: true,+ });+ expect(JSON.stringify(created)).not.toContain("edgeever-infographic-v1");+ const stored = await getMemoDetail(f.db, scope.workspaceId, created.id);+ const infographic = parseInfographicDocument(stored.contentMarkdown);+ expect(infographic.syntax).toContain("infographic chart-pie-donut-plain-text");+ expect(infographic.syntax).toContain("label 增值服务");+ expect(infographic.syntax).not.toContain("parentId");+ const read = await tools.get_memo.execute({ memoId: created.id });+ expect(read.infographic).toMatchObject({ template: "chart-pie-donut-plain-text" });+ expect(read.message).toContain("infographic");+ expect(JSON.stringify(read)).not.toContain("edgeever-infographic-v1");+ await expect(tools.update_memo.execute({ memoId: created.id, contentMarkdown: "# no" })).rejects.toThrow(+ "This is an infographic. Do not replace it with update_memo.",+ );+ });test("a diagram request cannot pause to ask which notebook", async () => {const f = await setup();const run = { tools: [], todos: [], questions: [], pause: { ask: false } };diff --git a/apps/api/src/companion-tool-catalog.ts b/apps/api/src/companion-tool-catalog.tsindex 4c5559e7..91f151e0 100644--- a/apps/api/src/companion-tool-catalog.ts+++ b/apps/api/src/companion-tool-catalog.ts@@ -5,7 +5,7 @@ import { AppError } from "./app-error";// Exposure policy, not a second tool implementation/schema registry. New MCP// capabilities must be reviewed rather than silently acquiring user authority.const allowed = new Set([- "get_current_user", "search_memos", "list_memos", "get_memo", "create_memo", "create_diagram_memo", "get_diagram",+ "get_current_user", "search_memos", "list_memos", "get_memo", "create_memo", "create_diagram_memo", "create_infographic_memo", "get_diagram","update_diagram","import_memos", "update_memo","trash_memos", "restore_memos", "move_memos", "add_tags_to_memos", "remove_tags_from_memos",diff --git a/apps/api/src/companion-tool-receipts.ts b/apps/api/src/companion-tool-receipts.tsindex 165fda32..e16f5437 100644--- a/apps/api/src/companion-tool-receipts.ts+++ b/apps/api/src/companion-tool-receipts.ts@@ -34,7 +34,7 @@ export function describeCompanionTool(return memos.slice(0, 5).map(item => effect("listed", asMemo(item)));}if (name === "get_memo" || name === "get_diagram") return [effect("read", memo ?? { id: String(args.memoId ?? record?.id ?? "") })];- if (name === "create_memo" || name === "create_diagram_memo" || name === "use_note_template") {+ if (name === "create_memo" || name === "create_diagram_memo" || name === "create_infographic_memo" || name === "use_note_template") {return [effect("created", memo)];}if (name === "update_memo" || name === "update_diagram" || name === "restore_memo_revision") {diff --git a/apps/api/src/companion.test.mjs b/apps/api/src/companion.test.mjsindex 9faa0f5a..dfc9b40a 100644--- a/apps/api/src/companion.test.mjs+++ b/apps/api/src/companion.test.mjs@@ -545,6 +545,9 @@ describe("actual AI SDK companion runtime", () => {expect(COMPANION_INSTRUCTIONS).toContain("Do not ask which notebook or tag first");expect(COMPANION_INSTRUCTIONS).toContain("after you have already searched");expect(COMPANION_INSTRUCTIONS).toContain("create_diagram_memo");+ expect(COMPANION_INSTRUCTIONS).toContain("create_infographic_memo");+ expect(COMPANION_INSTRUCTIONS).toContain("信息图");+ expect(COMPANION_INSTRUCTIONS).toContain("chart-pie-donut-plain-text");expect(COMPANION_INSTRUCTIONS).toContain("思维导图");expect(COMPANION_INSTRUCTIONS).toContain("架构图/architecture diagram means kind=architecture");expect(COMPANION_INSTRUCTIONS).toContain("update_diagram");diff --git a/apps/api/src/mcp-management-tools.test.mjs b/apps/api/src/mcp-management-tools.test.mjsindex 4681845a..453596fd 100644--- a/apps/api/src/mcp-management-tools.test.mjs+++ b/apps/api/src/mcp-management-tools.test.mjs@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test";import { globSync, readFileSync } from "node:fs";import { Database } from "bun:sqlite";import { callMcpTool } from "./index.ts";-import { addTableField, parseDiagramDocument, parseTableDocument, serializeTableDocument, createDefaultTableDocument } from "@edgeever/shared";+import { addTableField, parseDiagramDocument, parseInfographicDocument, parseTableDocument, serializeTableDocument, createDefaultTableDocument } from "@edgeever/shared";class SqliteD1PreparedStatement {constructor(db, sql, bindings = []) {@@ -124,6 +124,47 @@ describe("MCP template and AI instruction management", () => {}});+ test("creates a revenue-share infographic and refuses to overwrite it as markdown", async () => {+ const { sqlite, auth, context } = createFixture();+ sqlite.query("INSERT INTO notebooks (id, workspace_id, name) VALUES (?, ?, ?)")+ .run("nb_graphics", "ws_mcp", "Graphics");+ const created = await callMcpTool(context, auth, "create_infographic_memo", {+ notebookId: "nb_graphics",+ template: "chart-pie-donut-plain-text",+ data: {+ title: "腾讯 2025 年营收占比",+ desc: "图中比例为演示用估算,不代表腾讯官方披露数据。",+ values: [+ { label: "增值服务", value: 52 },+ { label: "金融科技与企业服务", value: 30 },+ { label: "网络广告", value: 16 },+ { label: "其他业务", value: 2 },+ ],+ },+ });+ expect(created).toMatchObject({ infographic: true, template: "chart-pie-donut-plain-text", memo: { title: "腾讯 2025 年营收占比" } });+ expect(JSON.stringify(created.memo)).not.toContain("edgeever-infographic-v1");+ const stored = sqlite.query("SELECT content_markdown FROM memo_contents WHERE memo_id = ?").get(created.memo.id);+ const infographic = parseInfographicDocument(stored.content_markdown);+ expect(infographic.syntax).toContain("value 52");+ const read = await callMcpTool(context, auth, "get_memo", { memoId: created.memo.id });+ expect(read.infographic).toEqual({ template: "chart-pie-donut-plain-text" });+ expect(read.memo.contentMarkdown).not.toContain("edgeever-infographic-v1");+ await expect(callMcpTool(context, auth, "update_memo", {+ memoId: created.memo.id, contentMarkdown: "# replaced",+ })).rejects.toMatchObject({ code: "infographic_update_required" });+ await expect(callMcpTool(context, auth, "create_infographic_memo", {+ notebookId: "nb_graphics",+ template: "chart-pie-donut-plain-text",+ data: { title: "坏占比", values: [{ label: "甲", value: -5 }] },+ })).rejects.toMatchObject({ code: "invalid_params" });+ await expect(callMcpTool(context, { ...auth, scopes: ["read:memos"] }, "create_infographic_memo", {+ notebookId: "nb_graphics",+ template: "chart-pie-donut-plain-text",+ data: { title: "占比", values: [{ label: "甲", value: 1 }] },+ })).rejects.toMatchObject({ code: "forbidden" });+ });+test("rejects invalid diagram graphs before creating a memo", async () => {const { auth, context } = createFixture();await expect(callMcpTool(context, auth, "create_diagram_memo", {diff --git a/apps/api/src/mcp-tool-service.ts b/apps/api/src/mcp-tool-service.tsindex 26f2e979..124e70aa 100644--- a/apps/api/src/mcp-tool-service.ts+++ b/apps/api/src/mcp-tool-service.ts@@ -4,7 +4,12 @@ import {ARCHITECTURE_RESOURCE_ICONS,TemplateCreateSchema,TemplateUpdateSchema,+ compileInfographicNote,docToText,+ hasInfographicDocumentMarker,+ INFOGRAPHIC_SCHEMA_VERSION,+ infographicFallbackMarkdown,+ infographicSyntaxTemplate,markdownToDoc,addTableField,addTableRecord,@@ -17,13 +22,16 @@ import {TABLE_SCHEMA_VERSION,hasTableDocumentMarker,parseDiagramDocument,+ parseInfographicDocument,parseTableDocument,listTableAttachmentResourceIds,removeTableField,removeTableRecord,serializeDiagramDocument,+ serializeInfographicDocument,serializeTableDocument,stripDiagramDocumentMarker,+ stripInfographicDocumentMarker,stripTableDocumentMarker,tableFallbackMarkdown,updateTableField,@@ -411,6 +419,12 @@ const memoWithoutTablePayload = (memo: MemoDetail) => {return { ...memo, contentMarkdown, contentJson, contentText: docToText(contentJson) };};+const memoWithoutInfographicPayload = (memo: MemoDetail) => {+ const contentMarkdown = stripInfographicDocumentMarker(memo.contentMarkdown);+ const contentJson = markdownToDoc(contentMarkdown);+ return { ...memo, contentMarkdown, contentJson, contentText: docToText(contentJson) };+};+const requiredTableRevision = (value: unknown) => {if (!Number.isSafeInteger(value) || (value as number) < 0) {throw new AppError("invalid_params", "expectedRevision must be a non-negative integer", 400);@@ -938,6 +952,13 @@ export const callMcpTool = async (if (diagram) return { memo: memoWithoutDiagramPayload(memo), diagram: diagramSemanticGraph(diagram) };const table = parseTableDocument(memo.contentMarkdown);if (table) return { memo: memoWithoutTablePayload(memo), structuredTable: getTableSummary(memo.contentMarkdown).tablePreview };+ const infographic = parseInfographicDocument(memo.contentMarkdown);+ if (infographic) {+ return {+ memo: memoWithoutInfographicPayload(memo),+ infographic: { template: infographicSyntaxTemplate(infographic.syntax) },+ };+ }return { memo };}case "get_table_records": {@@ -1082,6 +1103,27 @@ export const callMcpTool = async (return { memo };}+ case "create_infographic_memo": {+ assertScope(auth, "write:memos");+ const notebookId = getRequiredString(args.notebookId, "notebookId");+ const template = getRequiredString(args.template, "template");+ const compiled = compileInfographicNote(template, args.data);+ if (!compiled.ok) throw new AppError("invalid_params", compiled.message, 400);+ const document = { schemaVersion: INFOGRAPHIC_SCHEMA_VERSION, syntax: compiled.syntax };+ const memo = await createMemoRecord(c.env.storage.db, auth.workspaceId, {+ notebookId,+ title: getOptionalString(args.title) ?? compiled.title,+ contentMarkdown: serializeInfographicDocument(document),+ contentJson: markdownToDoc(infographicFallbackMarkdown(document)),+ tags: getOptionalStringArray(args.tags),+ }, getAuditActor(c), getActorLabel(c));+ return {+ memo: memoWithoutInfographicPayload(memo),+ infographic: true,+ template,+ revision: memo.revision,+ };+ }case "create_diagram_memo": {assertScope(auth, "write:memos");const notebookId = getRequiredString(args.notebookId, "notebookId");@@ -1182,6 +1224,13 @@ export const callMcpTool = async (400,);}+ if (existing && hasInfographicDocumentMarker(existing.contentMarkdown)) {+ throw new AppError(+ "infographic_update_required",+ "Infographic content cannot be replaced through update_memo.",+ 400,+ );+ }}const actor = getAuditActor(c);const actorLabel = getActorLabel(c);diff --git a/apps/api/src/mcp-tools.test.mjs b/apps/api/src/mcp-tools.test.mjsindex 467dc456..c04c8f37 100644--- a/apps/api/src/mcp-tools.test.mjs+++ b/apps/api/src/mcp-tools.test.mjs@@ -46,6 +46,12 @@ describe("MCP tool catalog", () => {destructiveHint: false,idempotentHint: true,});+ expect(byName.get("create_infographic_memo")?.annotations).toMatchObject({+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ });+ expect(byName.get("create_infographic_memo")?.inputSchema.properties.template.enum).toContain("chart-pie-donut-plain-text");expect(byName.get("create_diagram_memo")?.annotations).toMatchObject({readOnlyHint: false,destructiveHint: false,diff --git a/apps/api/src/mcp-tools.ts b/apps/api/src/mcp-tools.tsindex 160e2668..2c5932a9 100644--- a/apps/api/src/mcp-tools.ts+++ b/apps/api/src/mcp-tools.ts@@ -1,4 +1,4 @@-import { ARCHITECTURE_RESOURCE_ICONS, TABLE_FIELD_TYPES } from "@edgeever/shared";+import { ARCHITECTURE_RESOURCE_ICONS, INFOGRAPHIC_NOTE_TEMPLATES, TABLE_FIELD_TYPES } from "@edgeever/shared";const DIAGRAM_IR_NODE_TYPES = ["topic",@@ -67,6 +67,82 @@ const tableFieldSchema = {},};+const infographicLabel = {+ type: "object",+ additionalProperties: false,+ required: ["label"],+ properties: {+ label: { type: "string", minLength: 1, maxLength: 160 },+ desc: { type: "string", maxLength: 240 },+ },+};++const infographicChild = {+ type: "object",+ additionalProperties: false,+ required: ["label"],+ properties: {+ label: { type: "string", minLength: 1, maxLength: 160 },+ desc: { type: "string", maxLength: 240 },+ children: { type: "array", maxItems: 8, items: infographicLabel },+ },+};++const infographicDataSchema = {+ type: "object",+ additionalProperties: false,+ required: ["title"],+ properties: {+ title: { type: "string", minLength: 1, maxLength: 160 },+ desc: { type: "string", maxLength: 240 },+ values: {+ type: "array",+ maxItems: 12,+ items: {+ type: "object",+ additionalProperties: false,+ required: ["label", "value"],+ properties: {+ label: { type: "string", minLength: 1, maxLength: 80 },+ value: { type: "number" },+ },+ },+ },+ compares: { type: "array", maxItems: 4, items: infographicChild },+ sequences: { type: "array", maxItems: 12, items: infographicLabel },+ lists: { type: "array", maxItems: 12, items: infographicLabel },+ root: infographicChild,+ nodes: {+ type: "array",+ maxItems: 12,+ items: {+ type: "object",+ additionalProperties: false,+ required: ["id", "label"],+ properties: {+ id: { type: "string", minLength: 1, maxLength: 40 },+ label: { type: "string", minLength: 1, maxLength: 80 },+ desc: { type: "string", maxLength: 240 },+ },+ },+ },+ relations: {+ type: "array",+ maxItems: 24,+ items: {+ type: "object",+ additionalProperties: false,+ required: ["from", "to"],+ properties: {+ from: { type: "string", minLength: 1, maxLength: 40 },+ to: { type: "string", minLength: 1, maxLength: 40 },+ direction: { type: "string", maxLength: 20 },+ },+ },+ },+ },+};+const MCP_TOOL_DEFINITIONS = [{name: "get_current_user",@@ -234,6 +310,23 @@ const MCP_TOOL_DEFINITIONS = [},},},+ {+ name: "create_infographic_memo",+ description:+ "Create an AntV infographic note (信息图). Use this for 信息图, infographic, 占比, 构成, 饼图, 柱状图, 折线图, 对比, 四象限, 时间线, and a process infographic. Do not use create_diagram_memo, create_memo, or a mind map. Use chart-pie-donut-plain-text with data.values for a share or 占比; chart-column-simple for columns; chart-line-plain-text for a trend; compare-binary-horizontal-badge-card-vs for two subjects with matched children; compare-quadrant-quarter-simple-card for four quadrants; sequence-timeline-rounded-rect-node for a timeline; sequence-steps-simple for steps; list-grid-simple for a parallel list; hierarchy-tree-tech-style-capsule-item for a tree; relation-network-simple-circle-node for a network. Fill only the data array that matches the template. data.title is the note title. If the user did not supply the figures, say in data.desc that the values are illustrative and are not an official disclosure. 思维导图, 流程图, and 架构图 still use create_diagram_memo.",+ inputSchema: {+ type: "object",+ required: ["notebookId", "template", "data"],+ additionalProperties: false,+ properties: {+ notebookId: { type: "string", minLength: 1 },+ title: { type: "string", maxLength: 160 },+ template: { type: "string", enum: [...INFOGRAPHIC_NOTE_TEMPLATES] },+ data: infographicDataSchema,+ tags: { type: "array", maxItems: 100, items: { type: "string" } },+ },+ },+ },{name: "create_diagram_memo",description:@@ -891,6 +984,7 @@ const NON_DESTRUCTIVE_MCP_TOOLS = new Set(["create_memo","create_table_memo","create_diagram_memo",+ "create_infographic_memo","import_memos","restore_memos","move_memos",diff --git a/apps/web/src/lib/infographic-generation.test.mjs b/apps/web/src/lib/infographic-generation.test.mjsindex 4275c95b..b67f1874 100644--- a/apps/web/src/lib/infographic-generation.test.mjs+++ b/apps/web/src/lib/infographic-generation.test.mjs@@ -1,5 +1,6 @@import { describe, expect, test } from "bun:test";import { parseSyntax, getTemplate, getTemplates } from "@antv/infographic";+import { compileInfographicNote, INFOGRAPHIC_NOTE_TEMPLATES } from "@edgeever/shared";import {buildInfographicSyntax,buildOfficialInfographicSyntax,@@ -223,6 +224,18 @@ describe("infographic generation", () => {expect(new Set(candidates.map(officialTemplateFamily))).toEqual(new Set(["chart", "comparison", "hierarchy", "list", "quadrant", "relation", "sequence"]));});+ test("companion infographic templates render with AntV", () => {+ for (const template of INFOGRAPHIC_NOTE_TEMPLATES) {+ const compiled = compileInfographicNote(template, sampleOfficialData(template));+ expect(compiled.ok).toBe(true);+ if (!compiled.ok) continue;+ const parsed = parseSyntax(compiled.syntax);+ expect(parsed.errors).toEqual([]);+ expect(parsed.options.template).toBe(template);+ expect(getTemplate(template)).toBeTruthy();+ }+ });+test("development history prioritizes timeline templates over the current comparison", () => {const current = "compare-binary-horizontal-badge-card-vs";expect(inferInfographicFamily("给我换成字节的发展历程")).toBe("sequence");diff --git a/apps/web/src/lib/infographic-generation.ts b/apps/web/src/lib/infographic-generation.tsindex 179091af..ac0e02d8 100644--- a/apps/web/src/lib/infographic-generation.ts+++ b/apps/web/src/lib/infographic-generation.ts@@ -1,4 +1,13 @@-import { infographicRequestsTimeline } from "@edgeever/shared";+import {+ buildOfficialInfographicSyntax,+ infographicRequestsTimeline,+ officialTemplateFamily,+ parseGeneratedOfficialData,+ type OfficialTemplateFamily,+} from "@edgeever/shared";++export { buildOfficialInfographicSyntax, officialTemplateFamily, parseGeneratedOfficialData };+export type { OfficialTemplateFamily };export const INFOGRAPHIC_TEMPLATES = [{ id: "list-row-simple-horizontal-arrow", label: "simpleList", kind: "steps", hint: "short horizontal process" },@@ -33,7 +42,6 @@ export const selectableInfographicTemplates = INFOGRAPHIC_TEMPLATES.filter((itemexport const infographicTemplatePrompt = () => selectableInfographicTemplates.map((item) => `${item.id} (${item.kind}: ${item.hint})`).join("; ");-export type OfficialTemplateFamily = "chart" | "comparison" | "hierarchy" | "list" | "quadrant" | "relation" | "sequence";export const INFOGRAPHIC_FAMILIES: OfficialTemplateFamily[] = ["chart", "comparison", "hierarchy", "list", "quadrant", "relation", "sequence"];export type InfographicFamilyDecision = {@@ -79,16 +87,6 @@ export const infographicFamilyChoices = (decision: InfographicFamilyDecision) =>decision.ambiguous || decision.confidence < 0.65? [decision.family, ...decision.alternatives].slice(0, 3) : [];-export const officialTemplateFamily = (id: string): OfficialTemplateFamily => {- if (/^(compare-)?quadrant-/.test(id) || id.startsWith("compare-quadrant-")) return "quadrant";- if (id.startsWith("compare-")) return "comparison";- if (id.startsWith("hierarchy-")) return "hierarchy";- if (id.startsWith("relation-")) return "relation";- if (id.startsWith("chart-")) return "chart";- if (id.startsWith("sequence-")) return "sequence";- return "list";-};-export const templateForRequest = (request: string): string | null => {if (/(饼图|环形图|pie|donut)/i.test(request)) return "chart-pie-donut-plain-text";if (/(柱状图|条形图|bar chart|column chart)/i.test(request)) return "chart-column-simple";@@ -115,89 +113,6 @@ export const sampleOfficialData = (template: string): Record<string, unknown> =>return { title: "示例列表", lists: [entry("项目 A", "简短说明"), entry("项目 B", "简短说明"), entry("项目 C", "简短说明")] };};-const syntaxScalar = (value: string | number | boolean) => String(value).replace(/\s+/g, " ").trim();--const syntaxEntries = (value: Record<string, unknown>, indent: string): string[] => {- const lines: string[] = [];- for (const [key, entry] of Object.entries(value)) {- if (!/^[a-zA-Z][\w-]*$/.test(key) || entry == null) continue;- if (Array.isArray(entry)) {- if (!entry.length) continue;- lines.push(`${indent}${key}`);- for (const item of entry) {- if (!isRecord(item)) continue;- const firstKey = ["label", "id", "from"].find((candidate) => typeof item[candidate] === "string" && item[candidate]);- if (!firstKey) continue;- lines.push(`${indent} - ${firstKey} ${syntaxScalar(item[firstKey] as string)}`);- const rest = Object.fromEntries(Object.entries(item).filter(([field]) => field !== firstKey));- lines.push(...syntaxEntries(rest, `${indent} `));- }- } else if (isRecord(entry)) {- lines.push(`${indent}${key}`);- lines.push(...syntaxEntries(entry, `${indent} `));- } else if (["string", "number", "boolean"].includes(typeof entry)) {- lines.push(`${indent}${key} ${syntaxScalar(entry as string | number | boolean)}`);- }- }- return lines;-};--export const buildOfficialInfographicSyntax = (template: string, data: Record<string, unknown>, dark = false) => [- `infographic ${template}`,- ...(dark ? ["theme dark"] : []),- "data",- ...syntaxEntries(data, " "),-].join("\n");--const normalizedDatum = (value: unknown, depth = 0): Record<string, unknown> | null => {- if (!isRecord(value) || depth > 5) return null;- const result: Record<string, unknown> = {};- for (const field of ["id", "from", "to", "group", "label", "desc", "direction", "category"]) {- if (typeof value[field] === "string" && String(value[field]).trim()) result[field] = stringValue(value[field]);- }- if (!result.desc && typeof value.description === "string") result.desc = stringValue(value.description);- if (typeof value.value === "number" && Number.isFinite(value.value)) result.value = value.value;- if (Array.isArray(value.children)) result.children = value.children.slice(0, 12).map((child) => normalizedDatum(child, depth + 1)).filter(Boolean);- return Object.keys(result).length ? result : null;-};--export const parseGeneratedOfficialData = (output: string, template: string): Record<string, unknown> | null => {- const first = output.indexOf("{");- const last = output.lastIndexOf("}");- if (first < 0 || last <= first) return null;- let parsed: unknown;- try { parsed = JSON.parse(output.slice(first, last + 1)); } catch { return null; }- if (!isRecord(parsed)) return null;- const source = isRecord(parsed.data) ? parsed.data : parsed;- const family = officialTemplateFamily(template);- const field = { chart: "values", comparison: "compares", hierarchy: "root", list: "lists", quadrant: "compares", relation: "nodes", sequence: "sequences" }[family];- const data: Record<string, unknown> = { title: stringValue(source.title) || "信息图" };- if (typeof source.desc === "string" || typeof source.description === "string") data.desc = stringValue(source.desc ?? source.description);- if (family === "hierarchy") {- const root = normalizedDatum(source.root);- if (!root?.label) return null;- data.root = root;- } else {- const raw = source[field] ?? source.items;- if (!Array.isArray(raw)) return null;- const items = raw.slice(0, family === "quadrant" ? 4 : family === "comparison" ? 4 : 16).map((item) => normalizedDatum(item)).filter((item): item is Record<string, unknown> => Boolean(item));- if (!items.length || (family === "quadrant" && items.length !== 4) || (template.startsWith("compare-binary-") && items.length !== 2) || (template === "compare-swot" && items.length !== 4)) return null;- if (family !== "relation" && items.some((item) => !item.label)) return null;- if (template.startsWith("compare-binary-") && (items.some((item) => !Array.isArray(item.children) || !item.children.length)- || (items[0].children as unknown[]).length !== (items[1].children as unknown[]).length)) return null;- if (family === "chart" && items.some((item) => typeof item.value !== "number" || !item.label)) return null;- if (family === "relation" && (items.some((item) => !item.id || !item.label) || new Set(items.map((item) => item.id)).size !== items.length)) return null;- data[field] = items;- if (family === "relation") {- const ids = new Set(items.map((item) => item.id));- const relations = Array.isArray(source.relations) ? source.relations.slice(0, 24).map((item) => normalizedDatum(item)).filter((item): item is Record<string, unknown> => Boolean(item?.from && item?.to && ids.has(item.from) && ids.has(item.to))) : [];- if (items.length > 1 && !relations.length) return null;- data.relations = relations;- }- }- return data;-};-export const parseGeneratedOfficialSelection = (output: string, templates: string[]) => {const first = output.indexOf("{");const last = output.lastIndexOf("}");diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex dc231043..2d4abbf6 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -38,6 +38,7 @@ export * from "./deployment-metadata";export * from "./diagram";export * from "./diagram-canvas";export * from "./infographic";+export * from "./infographic-syntax";export * from "./table";export * from "./diagram-palette";export * from "./diagram-flowchart-style";diff --git a/packages/shared/src/infographic-syntax.test.mjs b/packages/shared/src/infographic-syntax.test.mjsnew file mode 100644index 00000000..b7d5b00c--- /dev/null+++ b/packages/shared/src/infographic-syntax.test.mjs@@ -0,0 +1,47 @@+import { describe, expect, test } from "bun:test";+import { compileInfographicNote, infographicSyntaxTemplate, parseInfographicDocument, serializeInfographicDocument } from "./index.ts";++describe("infographic note syntax", () => {+ test("compiles a revenue share into a pie infographic", () => {+ const compiled = compileInfographicNote("chart-pie-donut-plain-text", {+ title: "腾讯 2025 年营收占比",+ desc: "图中比例为演示用估算,不代表腾讯官方披露数据。",+ values: [+ { label: "增值服务", value: 52 },+ { label: "金融科技与企业服务", value: 30 },+ { label: "网络广告", value: 16 },+ { label: "其他业务", value: 2 },+ ],+ });+ expect(compiled.ok).toBe(true);+ if (!compiled.ok) return;+ expect(compiled.title).toBe("腾讯 2025 年营收占比");+ expect(compiled.syntax).toBe(`infographic chart-pie-donut-plain-text+data+ title 腾讯 2025 年营收占比+ desc 图中比例为演示用估算,不代表腾讯官方披露数据。+ values+ - label 增值服务+ value 52+ - label 金融科技与企业服务+ value 30+ - label 网络广告+ value 16+ - label 其他业务+ value 2`);+ expect(infographicSyntaxTemplate(compiled.syntax)).toBe("chart-pie-donut-plain-text");+ expect(parseInfographicDocument(serializeInfographicDocument({ schemaVersion: 1, syntax: compiled.syntax }))?.syntax).toBe(compiled.syntax);+ });++ test("rejects a share chart whose parts are not positive numbers", () => {+ expect(compileInfographicNote("chart-pie-donut-plain-text", {+ title: "占比",+ values: [{ label: "甲", value: -1 }, { label: "乙", value: 2 }],+ })).toMatchObject({ ok: false });+ expect(compileInfographicNote("chart-column-simple", {+ title: "趋势",+ values: [{ label: "甲" }],+ })).toMatchObject({ ok: false });+ expect(compileInfographicNote("not-a-template", { title: "占比", values: [{ label: "甲", value: 1 }] })).toMatchObject({ ok: false });+ });+});diff --git a/packages/shared/src/infographic-syntax.ts b/packages/shared/src/infographic-syntax.tsnew file mode 100644index 00000000..4c9fcd1c--- /dev/null+++ b/packages/shared/src/infographic-syntax.ts@@ -0,0 +1,155 @@+// AntV infographic syntax shared by the editor and the companion.+// The editor's generation tests accept this exact text shape.++export type OfficialTemplateFamily = "chart" | "comparison" | "hierarchy" | "list" | "quadrant" | "relation" | "sequence";++export const INFOGRAPHIC_NOTE_TEMPLATES = [+ "chart-pie-donut-plain-text",+ "chart-column-simple",+ "chart-line-plain-text",+ "compare-binary-horizontal-badge-card-vs",+ "compare-quadrant-quarter-simple-card",+ "sequence-timeline-rounded-rect-node",+ "sequence-steps-simple",+ "list-grid-simple",+ "hierarchy-tree-tech-style-capsule-item",+ "relation-network-simple-circle-node",+] as const;++export type InfographicNoteTemplate = (typeof INFOGRAPHIC_NOTE_TEMPLATES)[number];++export const isInfographicNoteTemplate = (value: string): value is InfographicNoteTemplate =>+ (INFOGRAPHIC_NOTE_TEMPLATES as readonly string[]).includes(value);++export const officialTemplateFamily = (id: string): OfficialTemplateFamily => {+ if (/^(compare-)?quadrant-/.test(id) || id.startsWith("compare-quadrant-")) return "quadrant";+ if (id.startsWith("compare-")) return "comparison";+ if (id.startsWith("hierarchy-")) return "hierarchy";+ if (id.startsWith("relation-")) return "relation";+ if (id.startsWith("chart-")) return "chart";+ if (id.startsWith("sequence-")) return "sequence";+ return "list";+};++export const infographicSyntaxTemplate = (syntax: string) =>+ /^infographic\s+([a-z0-9-]+)/.exec(syntax)?.[1] ?? "";++const plainLine = (value: string) => value.replace(/\s+/g, " ").trim();++const isRecord = (value: unknown): value is Record<string, unknown> =>+ Boolean(value) && typeof value === "object" && !Array.isArray(value);++const stringValue = (value: unknown) => typeof value === "string" ? plainLine(value).slice(0, 160) : "";++const syntaxScalar = (value: string | number | boolean) => String(value).replace(/\s+/g, " ").trim();++const syntaxEntries = (value: Record<string, unknown>, indent: string): string[] => {+ const lines: string[] = [];+ for (const [key, entry] of Object.entries(value)) {+ if (!/^[a-zA-Z][\w-]*$/.test(key) || entry == null) continue;+ if (Array.isArray(entry)) {+ if (!entry.length) continue;+ lines.push(`${indent}${key}`);+ for (const item of entry) {+ if (!isRecord(item)) continue;+ const firstKey = ["label", "id", "from"].find((candidate) => typeof item[candidate] === "string" && item[candidate]);+ if (!firstKey) continue;+ lines.push(`${indent} - ${firstKey} ${syntaxScalar(item[firstKey] as string)}`);+ const rest = Object.fromEntries(Object.entries(item).filter(([field]) => field !== firstKey));+ lines.push(...syntaxEntries(rest, `${indent} `));+ }+ } else if (isRecord(entry)) {+ lines.push(`${indent}${key}`);+ lines.push(...syntaxEntries(entry, `${indent} `));+ } else if (["string", "number", "boolean"].includes(typeof entry)) {+ lines.push(`${indent}${key} ${syntaxScalar(entry as string | number | boolean)}`);+ }+ }+ return lines;+};++export const buildOfficialInfographicSyntax = (template: string, data: Record<string, unknown>, dark = false) => [+ `infographic ${template}`,+ ...(dark ? ["theme dark"] : []),+ "data",+ ...syntaxEntries(data, " "),+].join("\n");++const normalizedDatum = (value: unknown, depth = 0): Record<string, unknown> | null => {+ if (!isRecord(value) || depth > 5) return null;+ const result: Record<string, unknown> = {};+ for (const field of ["id", "from", "to", "group", "label", "desc", "direction", "category"]) {+ if (typeof value[field] === "string" && String(value[field]).trim()) result[field] = stringValue(value[field]);+ }+ if (!result.desc && typeof value.description === "string") result.desc = stringValue(value.description);+ if (typeof value.value === "number" && Number.isFinite(value.value)) result.value = value.value;+ if (Array.isArray(value.children)) {+ result.children = value.children.slice(0, 12).map((child) => normalizedDatum(child, depth + 1)).filter((child): child is Record<string, unknown> => Boolean(child));+ }+ return Object.keys(result).length ? result : null;+};++export const parseGeneratedOfficialData = (output: string, template: string): Record<string, unknown> | null => {+ const first = output.indexOf("{");+ const last = output.lastIndexOf("}");+ if (first < 0 || last <= first) return null;+ let parsed: unknown;+ try { parsed = JSON.parse(output.slice(first, last + 1)); } catch { return null; }+ if (!isRecord(parsed)) return null;+ const source = isRecord(parsed.data) ? parsed.data : parsed;+ const family = officialTemplateFamily(template);+ const field = { chart: "values", comparison: "compares", hierarchy: "root", list: "lists", quadrant: "compares", relation: "nodes", sequence: "sequences" }[family];+ const data: Record<string, unknown> = { title: stringValue(source.title) || "信息图" };+ if (typeof source.desc === "string" || typeof source.description === "string") data.desc = stringValue(source.desc ?? source.description);+ if (family === "hierarchy") {+ const root = normalizedDatum(source.root);+ if (!root?.label) return null;+ data.root = root;+ } else {+ const raw = source[field] ?? source.items;+ if (!Array.isArray(raw)) return null;+ const items = raw.slice(0, family === "quadrant" ? 4 : family === "comparison" ? 4 : 16).map((item) => normalizedDatum(item)).filter((item): item is Record<string, unknown> => Boolean(item));+ if (!items.length || (family === "quadrant" && items.length !== 4) || (template.startsWith("compare-binary-") && items.length !== 2) || (template === "compare-swot" && items.length !== 4)) return null;+ if (family !== "relation" && items.some((item) => !item.label)) return null;+ if (template.startsWith("compare-binary-") && (items.some((item) => !Array.isArray(item.children) || !item.children.length)+ || (items[0].children as unknown[]).length !== (items[1].children as unknown[]).length)) return null;+ if (family === "chart" && items.some((item) => typeof item.value !== "number" || !item.label)) return null;+ if (family === "relation" && (items.some((item) => !item.id || !item.label) || new Set(items.map((item) => item.id)).size !== items.length)) return null;+ data[field] = items;+ if (family === "relation") {+ const ids = new Set(items.map((item) => item.id));+ const relations = Array.isArray(source.relations) ? source.relations.slice(0, 24).map((item) => normalizedDatum(item)).filter((item): item is Record<string, unknown> => Boolean(item?.from && item?.to && ids.has(item.from) && ids.has(item.to))) : [];+ if (items.length > 1 && !relations.length) return null;+ data.relations = relations;+ }+ }+ return data;+};++const FAMILY_REQUIREMENTS: Record<OfficialTemplateFamily, string> = {+ chart: "Chart infographics need data.values: 1–12 items with a label and a finite number value.",+ comparison: "Comparison infographics need data.compares: exactly 2 items, each with a label and the same number of labeled children.",+ quadrant: "Quadrant infographics need data.compares: exactly 4 items with labels.",+ sequence: "Sequence infographics need data.sequences: 1–12 items with labels.",+ list: "List infographics need data.lists: 1–12 items with labels.",+ hierarchy: "Hierarchy infographics need data.root with a label.",+ relation: "Relation infographics need data.nodes with unique ids and labels, plus data.relations connecting them when there is more than one node.",+};++export type CompiledInfographicNote = { ok: true; syntax: string; title: string } | { ok: false; message: string };++export const compileInfographicNote = (template: string, data: unknown): CompiledInfographicNote => {+ if (!isInfographicNoteTemplate(template)) {+ return { ok: false, message: "Choose a template from the create_infographic_memo list." };+ }+ if (!isRecord(data)) return { ok: false, message: FAMILY_REQUIREMENTS[officialTemplateFamily(template)] };+ const parsed = parseGeneratedOfficialData(JSON.stringify({ data }), template);+ if (!parsed) return { ok: false, message: FAMILY_REQUIREMENTS[officialTemplateFamily(template)] };+ if (template.startsWith("chart-pie-")) {+ const values = parsed.values as Array<{ value: number }>;+ if (values.some((item) => item.value < 0) || values.reduce((sum, item) => sum + item.value, 0) <= 0) {+ return { ok: false, message: "A share infographic needs data.values with positive numbers." };+ }+ }+ return { ok: true, syntax: buildOfficialInfographicSyntax(template, parsed), title: String(parsed.title) };+};