diff --git a/.changeset/33723-chat-cjk-bold.md b/.changeset/33723-chat-cjk-bold.md new file mode 100644 index 00000000000..2410aefff4c --- /dev/null +++ b/.changeset/33723-chat-cjk-bold.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-chatbot': patch +--- + +fix(plugin-chatbot): bold next to CJK full-width punctuation renders bold in chat answers + +Clause-②: no +Metadata-protocol: none + +A `**` run with a CJK letter on one side and full-width punctuation on the other (book-title marks, corner brackets, the full-width comma, full stop, exclamation and question marks, the enumeration comma) showed as literal asterisks in chat answers and the reasoning panel: CommonMark's flanking rule reads full-width punctuation as punctuation, and a CJK sentence puts no space beside the run. Both chat markdown surfaces now render with `remark-cjk-friendly` in streamdown's `cjk` plugin slot, so such a run opens and closes. ASCII emphasis, inline code spans and backslash-escaped asterisks keep their CommonMark meaning. A caller that passes its own `plugins` to `MessageResponse` keeps the CJK rule. + +`@object-ui/plugin-chatbot` gains the dependency `remark-cjk-friendly` (MIT). diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eee49b58b90..8d8351d101a 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5019,6 +5019,9 @@ importers: react-dom: specifier: 19.3.0 version: 19.3.0(react@19.3.0) + remark-cjk-friendly: + specifier: ^2.3.4 + version: 2.3.4(@types/mdast@4.0.4)(micromark-util-types@2.0.2)(micromark@4.0.2)(unified@11.0.5) shiki: specifier: ^4.4.2 version: 4.4.3 @@ -11879,9 +11882,21 @@ packages: mdast-util-to-hast@13.2.1: resolution: {integrity: sha512-cctsq2wp5vTsLIcaymblUriiTcZd0CwWtCbLvrOzYCDZoWyMNV8sZ7krj09FSnsiJi3WVsHLM4k6Dq/yaPyCXA==} + mdast-util-to-markdown-cjk-friendly@1.0.2: + resolution: {integrity: sha512-1HCuZwTxQX3WfaNFk8PDb/VW8Ulvzn+nHD+W79Q9k5NXUSkGXH9Zv3eMJ4VI7GjZIz4Ff7WbruEFgMUaPmRJ8g==} + engines: {node: '>=18'} + peerDependencies: + '@types/mdast': '*' + peerDependenciesMeta: + '@types/mdast': + optional: true + mdast-util-to-markdown@2.1.2: resolution: {integrity: sha512-xj68wMTvGXVOKonmog6LwyJKrYXZPvlwabaryTjLh9LuvovB/KAH+kvi8Gjj+7rJjsFi23nkUxRQv1KqSroMqA==} + mdast-util-to-markdown@2.2.3: + resolution: {integrity: sha512-dImdB6VZRMRac1SwAW6o1c0ESk/7pFFAMCMuKM+9v7LpTSthMM5nzXpqKw4Mjo66aXVKhNkyrP4bMB9MurPyWg==} + mdast-util-to-string@4.0.0: resolution: {integrity: sha512-0H44vDimn51F0YwvxSJSm0eCDOJTRlmN0R1yBh4HLj9wiV1Dn0QoXGbvFAWj2hSItVTlCmBF1hqKlIyUBVFLPg==} @@ -11916,6 +11931,25 @@ packages: micromark-core-commonmark@2.0.3: resolution: {integrity: sha512-RDBrHEMSxVFLg6xvnXmb1Ayr2WzLAWjeSATAoxwKYJV94TeNavgoIdA0a9ytzDSVzBy2YKFK+emCPOEibLeCrg==} + micromark-extension-cjk-friendly-util@3.0.1: + resolution: {integrity: sha512-GcbXqTTHOsiZHyF753oIddP/J2eH8j9zpyQPhkof6B2JNxfEJabnQqxbCgzJNuNes0Y2jTNJ3LiYPSXr6eJA8w==} + engines: {node: '>=18'} + peerDependencies: + micromark-util-types: '*' + peerDependenciesMeta: + micromark-util-types: + optional: true + + micromark-extension-cjk-friendly@2.0.2: + resolution: {integrity: sha512-/BqZNCkDWg3Hj9zEEcRitZ5uMF3X78qmBFuP17oAjnVDZ0+H1GHiDKMJZDpJsXasCHEn/kzl6QHozUiWgCHtPQ==} + engines: {node: '>=18'} + peerDependencies: + micromark: ^4.0.0 + micromark-util-types: ^2.0.0 + peerDependenciesMeta: + micromark-util-types: + optional: true + micromark-extension-gfm-autolink-literal@2.1.0: resolution: {integrity: sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==} @@ -12892,6 +12926,16 @@ packages: rehype-slug@6.0.0: resolution: {integrity: sha512-lWyvf/jwu+oS5+hL5eClVd3hNdmwM1kAC0BUvEGD19pajQMIzcNUd/k9GsfQ+FfECvX+JE+e9/btsKH0EjJT6A==} + remark-cjk-friendly@2.3.4: + resolution: {integrity: sha512-xhBzjXkumeN5tKXXg6k/THSCZCP6AYV6+wSxnCsPTkxHt60bb9Yk0IWhdD87CFaDCiTqd86LKHtVObcJTmgcow==} + engines: {node: '>=18'} + peerDependencies: + '@types/mdast': ^4.0.0 + unified: ^11.0.0 + peerDependenciesMeta: + '@types/mdast': + optional: true + remark-gfm@4.0.1: resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==} @@ -20034,6 +20078,18 @@ snapshots: unist-util-visit: 5.1.0 vfile: 6.0.3 + mdast-util-to-markdown-cjk-friendly@1.0.2(@types/mdast@4.0.4)(micromark-util-types@2.0.2): + dependencies: + mdast-util-to-markdown: 2.2.3 + micromark-extension-cjk-friendly-util: 3.0.1(micromark-util-types@2.0.2) + micromark-util-character: 2.1.1 + micromark-util-classify-character: 2.0.1 + micromark-util-html-tag-name: 2.0.1 + optionalDependencies: + '@types/mdast': 4.0.4 + transitivePeerDependencies: + - micromark-util-types + mdast-util-to-markdown@2.1.2: dependencies: '@types/mdast': 4.0.4 @@ -20046,6 +20102,20 @@ snapshots: unist-util-visit: 5.1.0 zwitch: 2.0.4 + mdast-util-to-markdown@2.2.3: + dependencies: + '@types/mdast': 4.0.4 + '@types/unist': 3.0.3 + longest-streak: 3.1.0 + mdast-util-phrasing: 4.1.0 + mdast-util-to-string: 4.0.0 + micromark-util-character: 2.1.1 + micromark-util-classify-character: 2.0.1 + micromark-util-decode-string: 2.0.1 + micromark-util-html-tag-name: 2.0.1 + unist-util-visit: 5.1.0 + zwitch: 2.0.4 + mdast-util-to-string@4.0.0: dependencies: '@types/mdast': 4.0.4 @@ -20108,6 +20178,25 @@ snapshots: micromark-util-symbol: 2.0.1 micromark-util-types: 2.0.2 + micromark-extension-cjk-friendly-util@3.0.1(micromark-util-types@2.0.2): + dependencies: + get-east-asian-width: 1.6.0 + micromark-util-character: 2.1.1 + micromark-util-symbol: 2.0.1 + optionalDependencies: + micromark-util-types: 2.0.2 + + micromark-extension-cjk-friendly@2.0.2(micromark-util-types@2.0.2)(micromark@4.0.2): + dependencies: + devlop: 1.1.0 + micromark: 4.0.2 + micromark-extension-cjk-friendly-util: 3.0.1(micromark-util-types@2.0.2) + micromark-util-chunked: 2.0.1 + micromark-util-resolve-all: 2.0.1 + micromark-util-symbol: 2.0.1 + optionalDependencies: + micromark-util-types: 2.0.2 + micromark-extension-gfm-autolink-literal@2.1.0: dependencies: micromark-util-character: 2.1.1 @@ -21238,6 +21327,17 @@ snapshots: hast-util-to-string: 3.0.1 unist-util-visit: 5.1.0 + remark-cjk-friendly@2.3.4(@types/mdast@4.0.4)(micromark-util-types@2.0.2)(micromark@4.0.2)(unified@11.0.5): + dependencies: + mdast-util-to-markdown-cjk-friendly: 1.0.2(@types/mdast@4.0.4)(micromark-util-types@2.0.2) + micromark-extension-cjk-friendly: 2.0.2(micromark-util-types@2.0.2)(micromark@4.0.2) + unified: 11.0.5 + optionalDependencies: + '@types/mdast': 4.0.4 + transitivePeerDependencies: + - micromark + - micromark-util-types + remark-gfm@4.0.1: dependencies: '@types/mdast': 4.0.4 diff --git a/ui/packages/plugin-chatbot/package.json b/ui/packages/plugin-chatbot/package.json index 218417f86fe..8c50742c647 100644 --- a/ui/packages/plugin-chatbot/package.json +++ b/ui/packages/plugin-chatbot/package.json @@ -50,6 +50,7 @@ "lucide-react": "^1.43.0", "motion": "^13.2.0", "nanoid": "^6.0.1", + "remark-cjk-friendly": "^2.3.4", "shiki": "^4.4.2", "streamdown": "^2.5.0", "use-stick-to-bottom": "^1.1.6" diff --git a/ui/packages/plugin-chatbot/src/__tests__/chatAnswerLayout-13032.test.tsx b/ui/packages/plugin-chatbot/src/__tests__/chatAnswerLayout-13032.test.tsx index 8f210d154c7..6bb479c652b 100644 --- a/ui/packages/plugin-chatbot/src/__tests__/chatAnswerLayout-13032.test.tsx +++ b/ui/packages/plugin-chatbot/src/__tests__/chatAnswerLayout-13032.test.tsx @@ -28,6 +28,7 @@ import { ConversationScrollButton, } from '../elements/conversation'; import { ChatbotEnhanced } from '../ChatbotEnhanced'; +import { Reasoning, ReasoningContent } from '../elements/reasoning'; import type { ChatbotEnhancedMessage } from '../ChatbotEnhanced'; /** Geometry the component reads, set per test. */ @@ -256,3 +257,80 @@ describe('an assistant answer in the side panel (objectui#13032)', () => { expect(list).toHaveClass('min-h-0', 'flex-1'); }); }); + +/** + * objectstack#33723 — `**` beside CJK full-width punctuation. CommonMark's + * flanking rule reads full-width punctuation as punctuation, so a run with a + * CJK letter on one side and full-width punctuation on the other never opens + * or closes, and the asterisks show. Every chat markdown surface renders with + * `CHAT_MARKDOWN_PLUGINS` (remark-cjk-friendly in streamdown's `cjk` slot). + */ +describe('bold next to CJK full-width punctuation (objectstack#33723)', () => { + /** The text of every strong run in the rendered answer. */ + async function strongRuns(markdown: string): Promise { + const { container } = render({markdown}); + await waitFor(() => expect(container.querySelector('p, pre')).not.toBeNull()); + return Array.from(container.querySelectorAll('[data-streamdown="strong"]')).map((el) => el.textContent ?? ''); + } + + it.each([ + ['an opener after a CJK letter, before a book-title mark', '借书人是**《书名》**的作者', '《书名》'], + ['an opener after a CJK letter, before a corner bracket', '他说**「引文」**之后', '「引文」'], + ['a closer after a full-width comma, before a CJK letter', '他说**你好,**我们走', '你好,'], + ['a closer after a full-width full stop, before a CJK letter', '看**这个。**然后', '这个。'], + ['a closer after a full-width exclamation mark, before a CJK letter', '真**好!**再来', '好!'], + ['a closer after a full-width question mark, before a CJK letter', '是**谁?**不知道', '谁?'], + ['a closer after an enumeration comma, before a CJK letter', '有**甲、**乙两种', '甲、'], + ['a closer after a closing corner bracket, before a CJK letter', '他说**「好」**然后走', '「好」'], + ])('renders %s bold', async (_name, markdown, bold) => { + expect(await strongRuns(markdown)).toEqual([bold]); + }); + + it.each([ + ['the card example, opener after a corner bracket', '「**《书名》,借书人**」', '《书名》,借书人'], + ['bold ending before a full-width comma', '**借书人**,下一位', '借书人'], + ['bold ending before a full-width full stop', '是**借书人**。', '借书人'], + ['bold ending before a full-width exclamation mark', '是**借书人**!', '借书人'], + ['bold ending before a full-width question mark', '是**借书人**?', '借书人'], + ['bold ending before an enumeration comma', '**甲**、乙', '甲'], + ['bold ending before a closing corner bracket', '「**开头**」再', '开头'], + ['bold starting after an opening corner bracket', '说「**开头**」', '开头'], + ])('control: %s stays bold', async (_name, markdown, bold) => { + expect(await strongRuns(markdown)).toEqual([bold]); + }); + + it.each([ + ['ASCII emphasis', 'This is **bold** text and foo**bar**baz', ['bold', 'bar'], 'This is bold text and foobarbaz'], + ['ASCII punctuation inside the run beside letters (CommonMark: literal)', 'a**"b"**c', [], 'a**"b"**c'], + ['escaped asterisks', '\\*\\*《书名》\\*\\*', [], '**《书名》**'], + ])('control: %s keeps its CommonMark meaning', async (_name, markdown, bold, text) => { + const { container } = render({markdown}); + await waitFor(() => expect(container.querySelector('p')).not.toBeNull()); + const runs = Array.from(container.querySelectorAll('[data-streamdown="strong"]')).map((el) => el.textContent); + expect(runs).toEqual(bold); + expect(container.querySelector('p')!.textContent).toBe(text); + }); + + it('control: `**` inside an inline code span stays literal', async () => { + const { container } = render({'书名是`**《书名》**`的写法'}); + await waitFor(() => expect(container.querySelector('code')).not.toBeNull()); + expect(container.querySelector('code')!.textContent).toBe('**《书名》**'); + expect(container.querySelector('[data-streamdown="strong"]')).toBeNull(); + }); + + it('a caller\'s own plugins keep the CJK rule', async () => { + const { container } = render({'借书人是**《书名》**的作者'}); + await waitFor(() => expect(container.querySelector('p')).not.toBeNull()); + expect(container.querySelector('[data-streamdown="strong"]')?.textContent).toBe('《书名》'); + }); + + it('the reasoning panel renders with the same rule', async () => { + const { container } = render( + + {'借书人是**《书名》**的作者'} + , + ); + await waitFor(() => expect(container.querySelector('p')).not.toBeNull()); + expect(container.querySelector('[data-streamdown="strong"]')?.textContent).toBe('《书名》'); + }); +}); diff --git a/ui/packages/plugin-chatbot/src/chatMarkdownPlugins.ts b/ui/packages/plugin-chatbot/src/chatMarkdownPlugins.ts new file mode 100644 index 00000000000..a3da6f4f8cd --- /dev/null +++ b/ui/packages/plugin-chatbot/src/chatMarkdownPlugins.ts @@ -0,0 +1,39 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import remarkCjkFriendly from "remark-cjk-friendly/parseOnly"; +import type { CjkPlugin, PluginConfig } from "streamdown"; + +/** + * Emphasis next to CJK full-width punctuation. + * + * CommonMark decides whether a `**` run can open or close emphasis from the + * characters on either side, and counts full-width punctuation (book-title + * marks, corner brackets, the full-width comma and full stop) as punctuation. + * A CJK sentence puts no space beside the run, so a run with a CJK letter on + * one side and full-width punctuation on the other is neither left- nor + * right-flanking the way the writer meant it, and stays literal asterisks. + * + * `remark-cjk-friendly` replaces the attention tokenizer with the + * markdown-cjk-friendly rule, which reads a CJK character beside the run the + * way it reads the whitespace an English sentence would have there. It runs + * before remark-gfm (streamdown's `cjk.remarkPluginsBefore` slot) so it owns + * the emphasis tokenizer; ASCII emphasis, code spans and backslash escapes + * keep their CommonMark meaning. The `parseOnly` entry leaves out the + * markdown serializer half, which the chat never runs. + */ +const CJK_EMPHASIS: CjkPlugin = { + name: "cjk", + type: "cjk", + remarkPlugins: [remarkCjkFriendly], + remarkPluginsBefore: [remarkCjkFriendly], + remarkPluginsAfter: [], +}; + +/** The streamdown plugins every chat markdown surface renders with. */ +export const CHAT_MARKDOWN_PLUGINS: PluginConfig = { cjk: CJK_EMPHASIS }; diff --git a/ui/packages/plugin-chatbot/src/elements/message.tsx b/ui/packages/plugin-chatbot/src/elements/message.tsx index 9d2aa9a2fb0..5202147dbdb 100644 --- a/ui/packages/plugin-chatbot/src/elements/message.tsx +++ b/ui/packages/plugin-chatbot/src/elements/message.tsx @@ -38,6 +38,7 @@ import { import { useSafeTranslate } from "@object-ui/i18n"; import { Streamdown } from "streamdown"; import { ListLinkContext, RecordLinkContext, withRecordLinks } from "../recordLink"; +import { CHAT_MARKDOWN_PLUGINS } from "../chatMarkdownPlugins"; export type MessageProps = HTMLAttributes & { from: UIMessage["role"]; @@ -407,6 +408,7 @@ const MessageResponseImpl = ({ translations, isAnimating, linkSafety, + plugins, ...props }: MessageResponseProps) => { const tt = useSafeTranslate(); @@ -514,6 +516,7 @@ const MessageResponseImpl = ({ components={{ ...ANSWER_COMPONENTS, ...components }} isAnimating={isAnimating} linkSafety={answerLinkSafety} + plugins={{ ...CHAT_MARKDOWN_PLUGINS, ...plugins }} translations={{ ...translations, viewFullscreen: expandTableLabel, diff --git a/ui/packages/plugin-chatbot/src/elements/reasoning.tsx b/ui/packages/plugin-chatbot/src/elements/reasoning.tsx index 519bb864b80..ba5c0ef09a7 100644 --- a/ui/packages/plugin-chatbot/src/elements/reasoning.tsx +++ b/ui/packages/plugin-chatbot/src/elements/reasoning.tsx @@ -17,6 +17,7 @@ import { BrainIcon, ChevronDownIcon } from "lucide-react"; import type { ComponentProps, ReactNode } from "react"; import { createContext, memo, useContext, useEffect, useState } from "react"; import { Streamdown } from "streamdown"; +import { CHAT_MARKDOWN_PLUGINS } from "../chatMarkdownPlugins"; import { Shimmer } from "./shimmer"; type ReasoningContextValue = { @@ -176,7 +177,7 @@ export const ReasoningContent = memo( )} {...props} > - {children} + {children} ) );