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(ai): use unambiguous math delimiters in sidebar replies
tianma-if3164e7fffc5c
diff --git a/apps/api/src/companion-prepare.ts b/apps/api/src/companion-prepare.tsindex 4bf5809e..1c188d31 100644--- a/apps/api/src/companion-prepare.ts+++ b/apps/api/src/companion-prepare.ts@@ -4,7 +4,7 @@ import type {CompanionAnswer, CompanionMemory, CompanionModelContentPart, CompanionPreparedMessage, CompanionPreparedTurn,CompanionQuestion, CompanionTodo, CompanionToolCall, CompanionTurnInput,} from "@edgeever/shared";-import { conversationLanguage, translationTargetInstruction } from "@edgeever/shared";+import { COMPANION_MATH_FORMAT_INSTRUCTION, conversationLanguage, translationTargetInstruction } from "@edgeever/shared";import { AppError } from "./app-error";import type { DatabaseAdapter } from "./storage-contract";import { loadCompanionAttachmentParts } from "./companion-attachments";@@ -17,6 +17,7 @@ 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.Be warm, direct, honest, and concise. Connect ideas without inventing personal history or feelings.+${COMPANION_MATH_FORMAT_INSTRUCTION}Respect the user's autonomy. Do not manipulate intimacy or claim consciousness or exclusivity.Only claim to remember information present in supplied context. Distinguish explicit statements from guesses.The user controls long-term memory through the UI. You cannot save, edit, or forget memories yourself.diff --git a/apps/api/src/companion.test.mjs b/apps/api/src/companion.test.mjsindex e236872c..361a3f5a 100644--- a/apps/api/src/companion.test.mjs+++ b/apps/api/src/companion.test.mjs@@ -122,6 +122,8 @@ describe("companion turn context", () => {]);expect(messages.at(-1).content).toContain("[note:memo_current]");expect(COMPANION_INSTRUCTIONS).toContain("An older translation of different text does not override the latest relevant translation.");+ expect(COMPANION_INSTRUCTIONS).toContain("write inline LaTeX as \\(...\\)");+ expect(COMPANION_INSTRUCTIONS).toContain("Do not use $...$ for inline math");});test("unqualified translations follow conversation language and ask only when source already matches", () => {diff --git a/apps/web/src/components/ai-sidebar/AiSidebarMessage.tsx b/apps/web/src/components/ai-sidebar/AiSidebarMessage.tsxindex 78f3d887..f35807eb 100644--- a/apps/web/src/components/ai-sidebar/AiSidebarMessage.tsx+++ b/apps/web/src/components/ai-sidebar/AiSidebarMessage.tsx@@ -6,7 +6,7 @@ import { memo } from "react";import { Streamdown } from "streamdown";import "katex/dist/katex.min.css";import { cn } from "@/lib/utils";-import { rewriteSidebarNoteLinks, sidebarNoteLinkAllowedTags, sidebarNoteLinkComponents } from "./sidebar-note-links";+import { normalizeSidebarMathDelimiters, rewriteSidebarNoteLinks, sidebarNoteLinkAllowedTags, sidebarNoteLinkComponents } from "./sidebar-note-links";const sidebarStreamdownPlugins = { cjk, code, mermaid, math };@@ -20,7 +20,7 @@ export const AiSidebarMessage = memo(plugins={sidebarStreamdownPlugins}tableMaxHeight={240}>- {rewriteSidebarNoteLinks(children)}+ {rewriteSidebarNoteLinks(normalizeSidebarMathDelimiters(children))}</Streamdown>),(prev, next) => prev.children === next.children && prev.isAnimating === next.isAnimating && prev.className === next.className,diff --git a/apps/web/src/components/ai-sidebar/sidebar-note-links.test.mjs b/apps/web/src/components/ai-sidebar/sidebar-note-links.test.mjsindex 5c76745a..1d3fd0e4 100644--- a/apps/web/src/components/ai-sidebar/sidebar-note-links.test.mjs+++ b/apps/web/src/components/ai-sidebar/sidebar-note-links.test.mjs@@ -2,7 +2,8 @@ import { describe, expect, test } from "bun:test";import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { Streamdown } from "streamdown";-import { rewriteSidebarNoteLinks, sidebarNoteLinkAllowedTags, sidebarNoteLinkComponents } from "./sidebar-note-links.tsx";+import { AiSidebarMessage } from "./AiSidebarMessage.tsx";+import { normalizeSidebarMathDelimiters, rewriteSidebarNoteLinks, sidebarNoteLinkAllowedTags, sidebarNoteLinkComponents } from "./sidebar-note-links.tsx";const render = (markdown) => renderToStaticMarkup(createElement(Streamdown, {allowedTags: sidebarNoteLinkAllowedTags,@@ -12,6 +13,25 @@ const render = (markdown) => renderToStaticMarkup(createElement(Streamdown, {}));describe("sidebar note links", () => {+ test("renders explicit inline math without changing prices or code", () => {+ const markdown = "炼气 $\\rightarrow$ 筑基,价格从 $5 到 $10。公式 \\(x^2\\) 和 \\(\\frac{1}{2}\\)。\n\n`\\(x^2\\)`\n\n```md\n\\(x^2\\)\n```\n\n~~~md\n\\(x^2\\)\n~~~";+ const normalized = normalizeSidebarMathDelimiters(markdown);+ expect(normalized).toContain("炼气 → 筑基,价格从 $5 到 $10。公式 $$x^2$$ 和 $$\\frac{1}{2}$$。");+ expect(normalized).toContain("`\\(x^2\\)`");+ expect(normalized).toContain("```md\n\\(x^2\\)\n```");+ expect(normalized).toContain("~~~md\n\\(x^2\\)\n~~~");+ const markup = renderToStaticMarkup(createElement(AiSidebarMessage, { children: markdown }));+ expect(markup).toContain('class="katex"');+ expect(markup).toContain("$5 到 $10");+ expect(markup).toContain("→");+ const price = renderToStaticMarkup(createElement(AiSidebarMessage, { children: "价格从 $5 到 $10" }));+ expect(price).not.toContain('class="katex"');+ const display = renderToStaticMarkup(createElement(AiSidebarMessage, { children: "$$\nx^2 + y^2 = z^2\n$$" }));+ expect(display).toContain("katex-display");+ const code = renderToStaticMarkup(createElement(AiSidebarMessage, { children: "`\\(x^2\\)`" }));+ expect(code).not.toContain('class="katex"');+ });+test("turns a note link into an in-app anchor and leaves other links alone", () => {const markdown = "已保存至“等待分类”:\n\n[模型蒸馏流程图](#memo=memo_03de025fc0134b7da0d155c2c1686b92)\n\n详见 [文档](https://example.com/docs)。";expect(rewriteSidebarNoteLinks(markdown)).toContain(diff --git a/apps/web/src/components/ai-sidebar/sidebar-note-links.tsx b/apps/web/src/components/ai-sidebar/sidebar-note-links.tsxindex 838895c3..70b4ce4e 100644--- a/apps/web/src/components/ai-sidebar/sidebar-note-links.tsx+++ b/apps/web/src/components/ai-sidebar/sidebar-note-links.tsx@@ -2,9 +2,17 @@ import { createMemoLinkHref } from "@edgeever/shared";import type { ComponentProps, ReactNode } from "react";import { parseAssistantNoteLinkHref } from "@/lib/assistant-note-links";-const CODE_REGION = /(```[\s\S]*?```|```[\s\S]*$|`[^`\n]*`)/g;+const CODE_REGION = /(```[\s\S]*?```|```[\s\S]*$|~~~[\s\S]*?~~~|~~~[\s\S]*$|``[^`\n]*``|`[^`\n]*`)/g;const MARKDOWN_LINK = /\[([^\]\n]+)\]\(([^)\s]+)\)/g;+/** Use explicit inline math delimiters; keep dollar prices untouched. */+export const normalizeSidebarMathDelimiters = (markdown: string): string => markdown+ .split(CODE_REGION)+ .map((part, index) => index % 2 === 1 ? part : part+ .replace(/\$\\rightarrow\$/g, "→") // Existing assistant replies used single-dollar arrows.+ .replace(/(?<!\\)\\\(([^\n]+?)\\\)/g, (_match, latex: string) => `$$${latex}$$`))+ .join("");+const escapeText = (value: string) => value.replace(/&/g, "&").replace(/</g, "<")diff --git a/apps/web/src/lib/ai-sidebar-context.test.mjs b/apps/web/src/lib/ai-sidebar-context.test.mjsindex 1164d803..4d749225 100644--- a/apps/web/src/lib/ai-sidebar-context.test.mjs+++ b/apps/web/src/lib/ai-sidebar-context.test.mjs@@ -20,6 +20,8 @@ describe("AI sidebar note context", () => {expect(localContext).toContain("Title (data): QQ 音乐等级");expect(localContext).toContain("get_memo");expect(localContext).toContain("translate into Simplified Chinese without asking");+ expect(localContext).toContain("write inline LaTeX as \\(...\\)");+ expect(localContext).toContain("Do not use $...$ for inline math");expect(localContext).not.toContain(note.contentMarkdown);});diff --git a/apps/web/src/lib/ai-sidebar-context.ts b/apps/web/src/lib/ai-sidebar-context.tsindex 3c81b1b1..4c5c793a 100644--- a/apps/web/src/lib/ai-sidebar-context.ts+++ b/apps/web/src/lib/ai-sidebar-context.ts@@ -1,4 +1,4 @@-import { conversationLanguage, translationTargetInstruction, type CompanionTurnInput } from "@edgeever/shared";+import { COMPANION_MATH_FORMAT_INSTRUCTION, conversationLanguage, translationTargetInstruction, type CompanionTurnInput } from "@edgeever/shared";export type SidebarNoteContext = {memoId?: string;@@ -38,6 +38,7 @@ export const sidebarLocalContextText = (const selection = context.selectionMarkdown?.trim().slice(0, 2000);const content = includeCurrentNote ? context.contentMarkdown?.trim().slice(0, 2000) : "";return [+ COMPANION_MATH_FORMAT_INSTRUCTION,translationTargetInstruction(conversationLanguage(conversation.message, conversation.recentUserMessages, conversation.fallbackLocale)),context.memoId ? `Open EdgeEver note for this turn. When the user refers to this note, use its ID with the connected EdgeEver MCP get_memo tool to read the full content if available:\nID: ${context.memoId}\nTitle (data): ${context.noteTitle?.trim() || "(untitled)"}` : "",selection ? `Selected text from the current note (data):\n${selection}` : "",diff --git a/packages/shared/src/companion.ts b/packages/shared/src/companion.tsindex 830d578d..c74f75fa 100644--- a/packages/shared/src/companion.ts+++ b/packages/shared/src/companion.ts@@ -1,6 +1,8 @@import { z } from "zod";import { isAiTextAttachment, type AiAttachmentMediaType } from "./ai-assistant";+export const COMPANION_MATH_FORMAT_INSTRUCTION = String.raw`In user-facing replies, write inline LaTeX as \(...\) and display LaTeX as $$...$$ on separate lines. Write monetary amounts with ordinary dollar signs, such as $5 and $10. Do not use $...$ for inline math. Preserve quoted source text and note content exactly when the task requires it.`;+export const CompanionIdSchema = z.string().uuid();export const CompanionMemoryInputSchema = z.object({content: z.string().trim().min(1).max(500),