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
fix(companion): save new notes in the inbox without asking
tianma-ifcc1dac72b1aa
diff --git a/apps/api/src/companion-agent-tools.ts b/apps/api/src/companion-agent-tools.tsindex 55be779a..dbae12bf 100644--- a/apps/api/src/companion-agent-tools.ts+++ b/apps/api/src/companion-agent-tools.ts@@ -8,11 +8,53 @@ import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companioimport { describeCompanionTool } from "./companion-tool-receipts";import { executeWorkspaceTool } from "./mcp-tool-executor";import { getMemoDetail } from "./memo-service";+import { inboxNotebookIdentitySql } from "./notebook-service";+import { workspaceInboxId } from "./workspace-provisioning";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"]);++export async function resolveWorkspaceInboxId(db: DatabaseAdapter, workspaceId: string) {+ const preferred = workspaceInboxId(workspaceId);+ const row = await db.prepare(+ `SELECT id FROM notebooks+ WHERE workspace_id = ? AND is_deleted = 0+ AND ${inboxNotebookIdentitySql("notebooks")}+ ORDER BY CASE WHEN id = ? THEN 0 WHEN id = 'nb_inbox' THEN 1 ELSE 2 END+ LIMIT 1`,+ ).bind(workspaceId, preferred).first<{ id: string }>();+ if (!row) throw new AppError("inbox_notebook_missing", "The inbox notebook (等待分类) is unavailable.", 409);+ return row.id;+}++const withOptionalInboxNotebook = (definition: CompanionToolDefinition): CompanionToolDefinition => {+ if (!INBOX_DEFAULT_NOTEBOOK_TOOLS.has(definition.name)) return definition;+ const inputSchema = definition.inputSchema as {+ required?: string[];+ properties?: Record<string, Record<string, unknown>>;+ };+ const properties = inputSchema.properties ?? {};+ const notebookId = properties.notebookId;+ return {+ ...definition,+ inputSchema: {+ ...inputSchema,+ required: (inputSchema.required ?? []).filter(name => name !== "notebookId"),+ properties: {+ ...properties,+ ...(notebookId ? {+ notebookId: {+ ...notebookId,+ description: "Exact notebook id from find_notebooks or list_notebooks. Omit when the user did not name a notebook; the note is saved in the inbox (等待分类).",+ },+ } : {}),+ },+ },+ };+};type ExplicitDiagramKind = "mind-map" | "flowchart" | "architecture";@@ -27,6 +69,12 @@ export const explicitDiagramKind = (message: string): ExplicitDiagramKind | undereturn matches.length === 1 ? matches[0][0] : undefined;};+const creatingUnplacedNote = (message: string) => Boolean(explicitDiagramKind(message))+ || /(?:新建|创建|生成|写一).{0,16}(?:笔记|备忘|流程图|思维导图|架构图|mind map|flowchart)/iu.test(message);++const asksForDestinationNotebook = (prompt: string) =>+ /笔记本|notebook/i.test(prompt) && /保存|存到|放到|放进|哪个|名称|which|name/i.test(prompt);+export type CompanionAgentSession = {calls: number;consecutiveErrors: number;@@ -66,11 +114,11 @@ 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.",- 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, use the open notebook id from Focus DATA. 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 架构图; 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.",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, use the open notebook id from Focus DATA.",+ 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.",create_note_template: " Save a reusable note template from Markdown or from an existing memoId.",list_ai_instructions: " List the user's reusable AI instructions, including built-in ones.",};@@ -138,7 +186,9 @@ const companionMcpDescription = (definition: (typeof COMPANION_MCP_TOOLS)[number? " Title, tags, and notebook changes execute immediately. Including contentMarkdown returns awaiting_user_confirmation and does not change the note until the user confirms. Never describe that proposal as applied.": readOnly || autoApply? autoApply- ? " This executes immediately. New notes are created in the named notebook. Trashed notes go to the recycle bin; edits keep revision history."+ ? INBOX_DEFAULT_NOTEBOOK_TOOLS.has(definition.name)+ ? " This executes immediately. If notebookId is omitted, the note is saved in the inbox notebook (等待分类). Do not ask the user to choose a notebook."+ : " This executes immediately. New notes are created in the named notebook. Trashed notes go to the recycle bin; edits keep revision history.": "": " This only proposes changes; the user must confirm the card. Supply a short _reason.";return `${definition.description}${TOOL_HINTS[definition.name] ?? ""}${execution}`;@@ -151,18 +201,18 @@ export function companionToolDefinitions(input: CompanionTurnInput): CompanionTo...companionMcpCatalog(input).map(definition => {const inputSchema = definition.inputSchema as Record<string, unknown>;if (definition.name !== "create_diagram_memo" || !requestedDiagramKind) {- return { name: definition.name, description: companionMcpDescription(definition), inputSchema };+ return withOptionalInboxNotebook({ name: definition.name, description: companionMcpDescription(definition), inputSchema });}const properties = inputSchema.properties as Record<string, unknown>;const kind = properties.kind as Record<string, unknown>;- return {+ 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] } },},- };+ });}),{name: "todo_write",@@ -171,7 +221,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 (notebook, notes, or strategy). 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, or template. Do not use this to narrate writes you can already perform. Stop after calling it.",inputSchema: ASK_USER_QUESTION_SCHEMA,},];@@ -226,6 +276,12 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companiawait args.run?.onProgress?.();try {const { _reason, ...parameters } = input;+ if (INBOX_DEFAULT_NOTEBOOK_TOOLS.has(definition.name)) {+ const notebookId = parameters.notebookId;+ if (typeof notebookId !== "string" || !notebookId.trim()) {+ parameters.notebookId = await resolveWorkspaceInboxId(args.db, args.scope.workspaceId);+ }+ }const { args: parameters_ } = validateCompanionTool(definition.name, parameters);const requestedDiagramKind = explicitDiagramKind(args.input.message);if (definition.name === "create_diagram_memo" && requestedDiagramKind && parameters_.kind !== requestedDiagramKind) {@@ -432,6 +488,12 @@ export function createCompanionTools(args: { db: DatabaseAdapter; scope: Companiargs.signal.throwIfAborted();await args.assertActive();if (!args.run) return { waiting: false };+ if (creatingUnplacedNote(args.input.message) && questions.some(question => asksForDestinationNotebook(question.prompt))) {+ return {+ waiting: false,+ error: "Do not ask which notebook. Omit notebookId. The note is saved in the inbox notebook (等待分类).",+ };+ }args.run.questions.splice(0, args.run.questions.length, ...questions.slice(0, 3).map(question => ({id: question.id.slice(0, 80),prompt: question.prompt.slice(0, 200),diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.tsindex c2310c60..1be0dff9 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 = 13;+export const COMPANION_IDENTITY_VERSION = 14;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.@@ -27,7 +27,7 @@ Read every source note completely before merging or replacing its body. Do not mMerging 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 notebooks, notes, or strategies, call ask_user_question once and stop.+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 (等待分类).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.@@ -43,7 +43,7 @@ When asked what is new, recent, added, created, or updated (最近/新增/本周search_memos matches note titles and bodies, not notebook names. Query is optional. Named tags go through list_tags or search_memos tags.If 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 no notebook is named, use the open notebook from Focus DATA. Reply with the new note link.+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.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.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.Call get_memo only when you must quote, summarize, or edit one specific note; even then quote at most a short phrase and always include the link.@@ -66,7 +66,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, use this open 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 (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 f41026b8..73e9988f 100644--- a/apps/api/src/companion-tool-actions.test.mjs+++ b/apps/api/src/companion-tool-actions.test.mjs@@ -11,7 +11,7 @@ import { companionWorkspaceCursor, proposeCompanionToolAction } from "./companioimport { 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 } from "./companion-agent-tools.ts";+import { companionToolDefinitions, createCompanionTools, explicitDiagramKind, resolveWorkspaceInboxId } from "./companion-agent-tools.ts";import { companionExecutionReceipts } from "./companion-runtime.ts";const databases = [];@@ -272,7 +272,16 @@ describe("shared companion MCP adapter", () => {const agentInput = { ...f.input, message: "帮我生成一个架构图笔记作为说明。" };const definition = companionToolDefinitions(agentInput).find(tool => tool.name === "create_diagram_memo");expect(definition.inputSchema.properties.kind.enum).toEqual(["architecture"]);+ expect(definition.inputSchema.required ?? []).not.toContain("notebookId");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"]) {+ const tool = plain.find(item => item.name === name);+ expect(tool.inputSchema.required ?? []).not.toContain("notebookId");+ expect(tool.description).toContain("等待分类");+ }+ expect(plain.find(item => item.name === "ask_user_question").description).toContain("Do not use this to choose a notebook");const tools = createCompanionTools({ ...f, input: agentInput, scope, signal: new AbortController().signal,assertActive: async () => {}, sources: [] });@@ -287,6 +296,62 @@ describe("shared companion MCP adapter", () => {expect(await tools.create_diagram_memo.execute({ ...graph, kind: "architecture" })).toMatchObject({ applied: true, diagramKind: "architecture" });});+ test("a new note or diagram without a named notebook is saved in the inbox", async () => {+ 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 tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });+ const note = await tools.create_memo.execute({ title: "Inbox note", contentMarkdown: "Saved without asking" });+ expect(note.memo.notebookId).toBe(inboxId);+ const diagram = await tools.create_diagram_memo.execute({+ title: "模型蒸馏",+ kind: "flowchart",+ nodes: [+ { id: "teacher", label: "教师模型", type: "process" },+ { id: "student", label: "学生模型", type: "process" },+ ],+ edges: [{ source: "teacher", target: "student" }],+ });+ expect(diagram).toMatchObject({ applied: true, notebookId: inboxId, diagramKind: "flowchart" });+ const named = await tools.create_memo.execute({ notebookId: "ideas", title: "Named", contentMarkdown: "Stay put" });+ expect(named.memo.notebookId).toBe("ideas");+ expect(await resolveWorkspaceInboxId(f.db, scope.workspaceId)).toBe(inboxId);+ });+ test("a diagram request cannot pause to ask which notebook", async () => {+ const f = await setup();+ const run = { tools: [], todos: [], questions: [], pause: { ask: false } };+ const tools = createCompanionTools({+ ...f,+ input: { ...f.input, message: "给我生成一个模型蒸馏的流程图" },+ scope,+ signal: new AbortController().signal,+ assertActive: async () => {},+ sources: [],+ run,+ });+ const blocked = await tools.ask_user_question.execute({+ questions: [{ id: "notebook", prompt: "流程图要保存到哪个笔记本?请提供笔记本名称。", inputType: "free_text" }],+ });+ expect(blocked).toMatchObject({ waiting: false, error: expect.stringContaining("等待分类") });+ expect(run.pause.ask).toBe(false);+ expect(run.questions).toEqual([]);+ const allowed = await tools.ask_user_question.execute({+ questions: [{+ id: "strategy",+ prompt: "按主题合并,还是按时间合并?",+ inputType: "single_select",+ options: [{ id: "topic", label: "主题" }, { id: "time", label: "时间" }],+ }],+ });+ expect(allowed).toMatchObject({ waiting: true });+ expect(run.questions).toHaveLength(1);+ });+ test("creating a note without a notebook fails when the inbox is missing", async () => {+ const f = await setup();+ const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });+ await expect(tools.create_memo.execute({ title: "Nowhere", contentMarkdown: "body" })).rejects.toMatchObject({ code: "inbox_notebook_missing" });+ expect(f.sqlite.query("SELECT COUNT(*) AS n FROM memos WHERE title = 'Nowhere'").get().n).toBe(0);+ });test("note templates and AI instructions execute immediately including deletes", async () => {const f = await setup();const tools = createCompanionTools({ ...f, scope, signal: new AbortController().signal, assertActive: async () => {}, sources: [] });diff --git a/apps/api/src/companion.test.mjs b/apps/api/src/companion.test.mjsindex 84a72b4c..9faa0f5a 100644--- a/apps/api/src/companion.test.mjs+++ b/apps/api/src/companion.test.mjs@@ -79,7 +79,11 @@ describe("companion turn context", () => {expect(companionUserContent(input({message: "帮我新建一个RAG原理的思维导图。",focus: { memoId: "memo_1", notebookId: "nb_demo_features", notebookTitle: "功能演示" },- }))).toContain("use this open notebook");+ }))).toContain("saved in the inbox notebook (等待分类)");+ expect(companionUserContent(input({+ message: "帮我新建一个RAG原理的思维导图。",+ focus: { memoId: "memo_1", notebookId: "nb_demo_features", notebookTitle: "功能演示" },+ }))).toContain("Do not ask which notebook");expect(companionUserContent(input({message: "根据这篇做思维导图",focus: {@@ -550,6 +554,9 @@ describe("actual AI SDK companion runtime", () => {expect(COMPANION_INSTRUCTIONS).toContain("use_note_template");expect(COMPANION_INSTRUCTIONS).toContain("todo_write");expect(COMPANION_INSTRUCTIONS).toContain("ask_user_question");+ expect(COMPANION_INSTRUCTIONS).toContain("Omit notebookId and it is saved in the inbox notebook (等待分类)");+ expect(COMPANION_INSTRUCTIONS).toContain("Do not ask which notebook, and do not use the open notebook unless the user named it");+ expect(COMPANION_INSTRUCTIONS).not.toContain("use the open notebook from Focus DATA");expect(COMPANION_INSTRUCTIONS).toContain("Do not narrate");expect(COMPANION_INSTRUCTIONS).toContain("AI instructions");expect(COMPANION_INSTRUCTIONS).toContain("cannot empty the trash");