The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): three renderer/markdown fixes — CJK math escape, reasoning bold split, subagent fade
Brooklyn Nicholson0bd1991db176
diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts b/apps/desktop/src/components/assistant-ui/markdown-text.test.tsindex cda508bfdd6..9f08d5fbef0 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.test.ts+++ b/apps/desktop/src/components/assistant-ui/markdown-text.test.ts@@ -485,4 +485,50 @@ describe('preprocessMarkdown', () => {expect(output).toBe('Per the paper, $\\sqrt[3]{8}$ is 2.')})++ // #103546: a bare `$identifier` twice in CJK prose is not math. The escape+ // fires on the OPENING `$` of a span whose body carries East Asian script or+ // punctuation, so remark-math reads it as a literal dollar and the sentence+ // renders as prose with recoverable copy-out.+ it('does not pair two bare dollars around CJK prose as inline math (#103546)', () => {+ const input = '...的经典嫌疑是 **$connection 被别的写者整包覆盖**(丢了 `isFullscreen` 字段)...搜 `$connection` 的所有写者:'++ const output = preprocessMarkdown(input)++ expect(output).toContain('\\$connection 被别的写者整包覆盖')+ // The backticked `$connection` is untouched — inline code stays code.+ expect(output).toContain('`$connection`')+ })++ it('escapes the opening dollar when both identifiers are bare in CJK prose (#103546)', () => {+ const output = preprocessMarkdown('搜 $connection 的所有写者,再搜 $session 的读者')++ expect(output).toContain('\\$connection')+ })++ it('escapes a span whose body is fullwidth punctuation plus Latin (#103546)', () => {+ const output = preprocessMarkdown('值 $foo(bar)$ 已确认')++ expect(output).toContain('\\$foo(bar)$')+ })++ it('leaves real inline math in CJK prose untouched (#103546)', () => {+ const output = preprocessMarkdown('代入 $x^2 + y^2$ 得到结果')++ expect(output).toContain('$x^2 + y^2$')+ expect(output).not.toContain('\\$x^2')+ })++ it('leaves real inline math adjacent to CJK untouched (#103546)', () => {+ const output = preprocessMarkdown('其中 $\\alpha = 1$,所以')++ expect(output).toContain('$\\alpha = 1$')+ expect(output).not.toContain('\\$\\alpha')+ })++ it('leaves display math in CJK prose untouched (#103546)', () => {+ const output = preprocessMarkdown('公式 $$E = mc^2$$ 成立')++ expect(output).toContain('$$E = mc^2$$')+ })})diff --git a/apps/desktop/src/components/assistant-ui/tool/delegate.test.tsx b/apps/desktop/src/components/assistant-ui/tool/delegate.test.tsxnew file mode 100644index 00000000000..a70f9f76f8a--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/tool/delegate.test.tsx@@ -0,0 +1,96 @@+import { cleanup, render } from '@testing-library/react'+import { atom } from 'nanostores'+import { afterEach, describe, expect, it } from 'vitest'++import { type SessionView, SessionViewProvider } from '@/app/chat/session-view'+import { I18nProvider } from '@/i18n/context'+import type { ChatMessage } from '@/lib/chat-messages'+import { $activeSessionId } from '@/store/session'+import { $subagentsBySession, clearSessionSubagents, upsertSubagent } from '@/store/subagents'++import { DelegateTool } from './delegate'++const SESSION = 'sess-delegate-test'++function view(): SessionView {+ return {+ kind: 'primary',+ $runtimeId: atom<string | null>(SESSION),+ $storedId: atom<string | null>(null),+ $messages: atom<ChatMessage[]>([]),+ $busy: atom(false),+ $awaitingResponse: atom(false),+ $messagesEmpty: atom(true),+ $lastVisibleIsUser: atom(false),+ $turnStartedAt: atom<null | number>(null),+ $cwd: atom(''),+ $model: atom(''),+ $provider: atom(''),+ $fast: atom(false),+ $reasoningEffort: atom(''),+ $reasoningEffortPending: atom(false),+ $reasoningEffortWire: atom('')+ } satisfies SessionView+}++function renderCard() {+ return render(+ <I18nProvider configClient={null} initialLocale="en">+ <SessionViewProvider value={view()}>+ <DelegateTool args={{ tasks: [{ goal: 'Inspect the delegate card' }] }} result={undefined} toolCallId="call-1" />+ </SessionViewProvider>+ </I18nProvider>+ )+}++afterEach(() => {+ cleanup()+ clearSessionSubagents(SESSION)+ $subagentsBySession.set({})+ $activeSessionId.set(null)+})++describe('delegate card fade', () => {+ // Scaffold opacity opens a stacking context. The activity ticker is a+ // transformed reel clipped to one line; when the mark sat on the wrapper+ // around both, the reel's clip degraded and every old activity line painted+ // through the current one (#105579). The mark belongs on the goal row; the+ // ticker stays outside it.+ it('does not put the activity ticker inside a scaffold fade', () => {+ $activeSessionId.set(SESSION)+ upsertSubagent(+ SESSION,+ {+ goal: 'Inspect the delegate card',+ status: 'running',+ subagent_id: 'delegate-tool:call-1:0',+ task_index: 0,+ text: 'Thinking about the card'+ },+ true,+ 'subagent.thinking'+ )+ upsertSubagent(+ SESSION,+ {+ subagent_id: 'delegate-tool:call-1:0',+ task_index: 0,+ tool_name: 'terminal',+ tool_preview: 'git status'+ },+ false,+ 'subagent.tool'+ )++ const { container } = renderCard()+ const ticker = container.querySelector('[data-tool-ticker]')+ const marked = container.querySelector('[data-conversation-scaffold]')++ expect(ticker).not.toBeNull()+ expect(marked).not.toBeNull()+ expect(ticker?.closest('[data-conversation-scaffold]')).toBeNull()+ // The card wrapper itself carries no mark — the fade is per surface, never+ // on a container (styles.css invariant).+ expect(container.querySelector('[data-delegate-card]')?.hasAttribute('data-conversation-scaffold')).toBe(false)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/tool/delegate.tsx b/apps/desktop/src/components/assistant-ui/tool/delegate.tsxindex 381332944cf..363127d126f 100644--- a/apps/desktop/src/components/assistant-ui/tool/delegate.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/delegate.tsx@@ -86,12 +86,14 @@ function DelegateRowView({ row }: { row: DelegateRow }) {// Only a child that reported its own session id has somewhere to go.const open = sessionId ? () => void openSessionInNewWindow(sessionId, { watch: true }) : undefined+ // The scaffold mark goes on the goal row, NEVER on this wrapper: it fades to+ // 0.67, and opacity opens a stacking context around the ticker's transformed+ // reel, which is how old activity lines painted through the one-line window+ // and the whole card read as stacked ghosts (#105579). styles.css's own+ // invariant: the mark is per surface and never on a container.return (- <div- className="grid min-w-0 max-w-full gap-0.5 rounded-xl border border-(--ui-stroke-tertiary) px-3 py-2"- data-conversation-scaffold=""- >- <div className="flex min-w-0 max-w-full items-center gap-1.5">+ <div className="grid min-w-0 max-w-full gap-0.5 rounded-xl border border-(--ui-stroke-tertiary) px-3 py-2">+ <div className="flex min-w-0 max-w-full items-center gap-1.5" data-conversation-scaffold=""><span className={SCAFFOLD_GLYPH_CLASS}>{statusGlyph(row.status, statusLabel)}</span><buttonclassName={cn(diff --git a/apps/desktop/src/lib/file-preview-math.render.test.tsx b/apps/desktop/src/lib/file-preview-math.render.test.tsxindex 9223d04ce4f..6a4f6801559 100644--- a/apps/desktop/src/lib/file-preview-math.render.test.tsx+++ b/apps/desktop/src/lib/file-preview-math.render.test.tsx@@ -3,7 +3,7 @@ import { Streamdown } from 'streamdown'import { describe, expect, it } from 'vitest'import { createMemoizedMathPlugin } from '@/lib/katex-memo'-import { normalizeFilePreviewMath } from '@/lib/markdown-preprocess'+import { normalizeFilePreviewMath, preprocessMarkdown } from '@/lib/markdown-preprocess'// This is the exact pipeline the file preview runs: normalizeFilePreviewMath// → Streamdown with the memoized math plugin. Rendering here (jsdom) proves the@@ -61,4 +61,25 @@ describe('file-preview math rendering', () => {})expect(container.querySelector('code')?.textContent).toContain('$HOME')})++ // #103546: the exact chat-pipeline shape (preprocessMarkdown → Streamdown+ // with the memoized single-dollar math plugin, as markdown-text.tsx wires+ // it). Before the CJK escape, micromark paired the two bare `$` signs and+ // the whole sentence rendered through KaTeX — per-character math-italic+ // copy-out, CJK in a serif fallback at 1.21em. After, it renders as prose+ // and the source text is recoverable from the DOM.+ it('does not typeset a bare dollar pair spanning CJK prose as KaTeX (#103546)', async () => {+ const source = '...的经典嫌疑是 **$connection 被别的写者整包覆盖**(丢了 `isFullscreen` 字段)...搜 `$connection` 的所有写者:'++ const { container } = render(+ <Streamdown mode="static" plugins={{ math: mathPlugin }}>+ {preprocessMarkdown(source)}+ </Streamdown>+ )++ await waitFor(() => {+ expect(container.querySelector('.katex')).toBeNull()+ })+ expect(container.textContent).toContain('$connection 被别的写者整包覆盖')+ })})diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.tsindex 7b0c606b017..4c48947335f 100644--- a/apps/desktop/src/lib/markdown-preprocess.ts+++ b/apps/desktop/src/lib/markdown-preprocess.ts@@ -500,6 +500,61 @@ function escapeCurrencyDollarsPreservingMath(text: string): string {return out + text.slice(copiedThrough)}+// East Asian script and punctuation ranges: CJK Symbols/Punctuation, Hiragana,+// Katakana, Han (incl. Extension A and compatibility ideographs), Hangul, and+// the fullwidth/halfwidth forms. Fullwidth punctuation (() , :) is+// near-universal in CJK prose and is included so a `$foo(bar)$`-shaped span+// with no Han glyph in its body still classifies as prose.+const CJK_RE = /[\u3000-\u303f\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uac00-\ud7af\uff00-\uffef]/u++/**+ * Escape the opening `$` of any same-line single-dollar span whose body+ * contains East Asian script or punctuation, so remark-math reads it as a+ * literal dollar instead of pairing it with the later `$` and typesetting the+ * intervening prose as one KaTeX inline formula (#103546).+ *+ * A bare `$identifier` in CJK prose (written twice in one sentence) is the+ * classic false positive of `singleDollarTextMath: true`: the whole sentence+ * renders through KaTeX — CJK glyphs in a serif fallback face at 1.21em, and+ * copy-out yields per-character math-italic codepoints, not the source text.+ * CJK prose sets no inter-word spaces and rarely writes `$…$` math around+ * non-Latin text, so a CJK body is prose with near certainty.+ *+ * Escaping only the OPENING `$` is enough: the closing `$` loses its partner+ * and renders literally. Real math is untouched — its body carries no CJK —+ * and `$$` display runs are skipped by the same `$$`-run guard the currency+ * escape uses. The one accepted tradeoff: genuine inline math whose body+ * names a CJK variable (`$x = 变量$`) renders as literal prose. Losing one+ * equation is far cheaper than corrupting a sentence's copy-out.+ */+function escapeCjkProseDollars(text: string): string {+ let out = ''+ let copiedThrough = 0++ for (let cursor = 0; cursor < text.length; cursor += 1) {+ if (text[cursor] !== '$' || text[cursor - 1] === '$' || isEscapedAt(text, cursor)) {+ continue+ }++ const closingIndex = findClosingSingleDollar(text, cursor)++ if (closingIndex === -1) {+ continue+ }++ const body = text.slice(cursor + 1, closingIndex)++ if (!CJK_RE.test(body)) {+ continue+ }++ out += `${text.slice(copiedThrough, cursor)}\\$`+ copiedThrough = cursor + 1+ }++ return out + text.slice(copiedThrough)+}+/*** Moves the `$$` delimiters of a MULTI-LINE display-math block onto their own* lines: `$$\begin{aligned}` … `\end{aligned}$$` becomes a `$$`-only line, the@@ -618,8 +673,9 @@ function normalizeProseMath(text: string): string {// `$$\begin{aligned}…\end{aligned}$$`. Running afterwards catches both the// hugging math the model emitted and the hugging math the rewrite produced.const normalized = splitHuggingDisplayMath(normalizeMathDelimiters(normalizeDisplayMathForMarkdown(text)))+ const cjkEscaped = escapeCjkProseDollars(normalized)- return escapeCurrencyDollarsPreservingMath(normalized)+ return escapeCurrencyDollarsPreservingMath(cjkEscaped)}function extend(out: string[], lines: string[]) {diff --git a/apps/desktop/src/lib/reasoning-blocks.test.ts b/apps/desktop/src/lib/reasoning-blocks.test.tsindex cab4ab90e25..910d25d7538 100644--- a/apps/desktop/src/lib/reasoning-blocks.test.ts+++ b/apps/desktop/src/lib/reasoning-blocks.test.ts@@ -45,4 +45,42 @@ describe('separateGluedReasoningBlocks', () => {it('does not split a heading that already opens the text', () => {expect(separateGluedReasoningBlocks('**Only one part**')).toBe('**Only one part**')})++ // CJK prose sets no inter-word spaces, so the old lazy body matched from the+ // close of one bold pair to the open of the next and injected a paragraph+ // break mid-sentence (#107813). A match must be one complete pair that+ // closes its own line — inline emphasis is left exactly as written.+ it('leaves CJK inline bold mid-sentence alone (#107813)', () => {+ const prose = '1. **日经原因**(共同社):指数重挫——**半导体领跌**——与美股同步。'++ expect(separateGluedReasoningBlocks(prose)).toBe(prose)+ })++ it('leaves punctuation-glued CJK emphasis alone (#107813)', () => {+ const prose = '——**唯一解释**:只有一条路——**破案**!'++ expect(separateGluedReasoningBlocks(prose)).toBe(prose)+ })++ it('leaves English inline bold mid-sentence alone', () => {+ const prose = 'The **core issue** is that the regex was over-broad.'++ expect(separateGluedReasoningBlocks(prose)).toBe(prose)+ })++ it('still splits a heading that closes its own line after prose', () => {+ const glued = 'interaction!**Checking logs**'++ expect(separateGluedReasoningBlocks(glued)).toBe('interaction!\n\n**Checking logs**')+ })++ it('still repairs the **First****Second** heading run', () => {+ expect(separateGluedReasoningBlocks('**First****Second**')).toBe('**First**\n\n**Second**')+ })++ it('is idempotent on separated CJK headings', () => {+ const separated = '**第一个部分**\n\n**第二个部分**'++ expect(separateGluedReasoningBlocks(separated)).toBe(separated)+ })})diff --git a/apps/desktop/src/lib/reasoning-blocks.ts b/apps/desktop/src/lib/reasoning-blocks.tsindex a1122bd7478..c91459f2b48 100644--- a/apps/desktop/src/lib/reasoning-blocks.ts+++ b/apps/desktop/src/lib/reasoning-blocks.ts@@ -24,7 +24,13 @@// Emphasis that legitimately follows whitespace is left alone, and a heading// must close on its own line to count as a summary part.const GLUED_HEADING_RUN = /(?<!\*)\*{4}(?!\*)/g-const GLUED_AFTER_PROSE = /(?<=[^\s*])(\*\*(?=[^\s*])[^\n]*?\*\*)/g+// A `[^*` + newline + `]*` body never crosses a bold delimiter, so a match is+// one complete pair; `(?=\s*$)` (with `m`) honors the line-final contract+// above — an inline bold followed by more sentence (`**A**(text)…`) is left+// alone. The previous lazy any-character body spanned pair boundaries and,+// because CJK sets no inter-word spaces, fired on practically every CJK+// inline bold, splitting prose mid-sentence (#107813).+const GLUED_AFTER_PROSE = /(?<=[^\s*])(\*\*(?=[^\s*])[^*\n]*\*\*)(?=\s*$)/gmexport function separateGluedReasoningBlocks(text: string): string {return text.replace(GLUED_HEADING_RUN, '**\n\n**').replace(GLUED_AFTER_PROSE, '\n\n$1')diff --git a/apps/desktop/src/lib/use-enter-animation.test.tsx b/apps/desktop/src/lib/use-enter-animation.test.tsxindex 936aeab2668..17d50cd972d 100644--- a/apps/desktop/src/lib/use-enter-animation.test.tsx+++ b/apps/desktop/src/lib/use-enter-animation.test.tsx@@ -47,7 +47,7 @@ describe('useEnterAnimation', () => {const played = mountAnimated(true, 'plays-once')expect(played).toBeDefined()- expect(played?.keyframes[0]).toMatchObject({ opacity: 0 })+ expect(played?.keyframes[0]).toMatchObject({ transform: 'translateY(0.375rem)' })})it('stays out of the way when disabled', () => {@@ -64,19 +64,21 @@ describe('useEnterAnimation', () => {})/**- * The animation fills forwards, so any value in its last keyframe is held in- * the animation origin of the cascade for the life of the element — above- * the stylesheet. Naming an end opacity therefore doesn't just finish the- * fade, it permanently overrules whatever opacity CSS wants the element to- * rest at, and transcript scaffolding rests dimmed. Rows that animated in- * during the turn stayed bright while their rehydrated neighbours faded, and- * no hover could lift the bright ones because the sheet had lost the- * argument. Opacity has to be left to CSS at the end.+ * Opacity on any keyframe, under a fill that holds while the document+ * timeline is paused (alt-tab, HUD hide, an unfocused window), pins the+ * node at that value — opening at 0 left subagent rows and thinking blocks+ * invisible (#105579). CSS already rests those surfaces at 0.67; the slide+ * is transform-only and fill is 'backwards', so the offset applies on the+ * first frame and then the effect releases instead of holding a filled+ * transform (and its compositor layer) for the life of the node.*/- it('leaves the resting opacity to the stylesheet', () => {+ it('never animates opacity, and does not hold a filled transform', () => {const played = mountAnimated(true, 'resting-opacity')- expect(played?.options.fill).toBe('both')- expect(played?.keyframes.at(-1)).not.toHaveProperty('opacity')+ expect(played?.options.fill).toBe('backwards')++ for (const frame of played?.keyframes ?? []) {+ expect(frame).not.toHaveProperty('opacity')+ }})})diff --git a/apps/desktop/src/lib/use-enter-animation.ts b/apps/desktop/src/lib/use-enter-animation.tsindex 267eaa4cac5..172e436ab9e 100644--- a/apps/desktop/src/lib/use-enter-animation.ts+++ b/apps/desktop/src/lib/use-enter-animation.ts@@ -79,23 +79,21 @@ export function useEnterAnimation(enabled: boolean, animationKey?: string): (el:return}- el.animate(- [- { opacity: 0, transform: 'translateY(0.375rem)' },- // No `opacity` on the way out, deliberately. A filled animation holds- // its final value in the animation origin of the cascade, which- // outranks the stylesheet for as long as the element lives — naming 1- // here permanently pinned full opacity onto everything the sheet dims.- // Transcript scaffolding is dimmed that way, so a tool row or thinking- // header kept whichever opacity it happened to mount with: full if it- // animated in during the turn, faded if it was rehydrated or remounted- // past its one-shot key. Adjacent identical rows disagreed, and hover- // couldn't lift the pinned ones. Left neutral, opacity rises to- // whatever CSS says it should be and answers hover afterwards.- { transform: 'translateY(0)' }- ],- { duration: 180, easing: 'cubic-bezier(0.16, 1, 0.3, 1)', fill: 'both' }- )+ // Transform only. Opacity on ANY keyframe outranks the stylesheet while the+ // effect applies: `fill: 'both'` plus `opacity: 0` on the opening frame+ // pinned rows invisible whenever Chromium paused the document timeline+ // (alt-tab, a hidden window, an unfocused one) — the animation never runs,+ // and the backwards fill holds the opening frame (#105579). Naming 1 on+ // the way out has the inverse problem the comment below used to defend+ // against. CSS already rests these surfaces at 0.67, so the slide is+ // transform-only and fill is 'backwards': the offset applies on the first+ // frame and then the effect releases instead of holding a filled+ // transform (and its compositor layer) for the life of the node.+ el.animate([{ transform: 'translateY(0.375rem)' }, { transform: 'translateY(0)' }], {+ duration: 180,+ easing: 'cubic-bezier(0.16, 1, 0.3, 1)',+ fill: 'backwards'+ })if (key) {// In React StrictMode the first mount can be immediately torn down.diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.cssindex 26fec9ffee1..029b290e75d 100644--- a/apps/desktop/src/styles.css+++ b/apps/desktop/src/styles.css@@ -2411,6 +2411,10 @@ button[data-slot='aui_msg-reactions'] svg {.tool-ticker {height: var(--conversation-line-height);overflow: hidden;+ /* clip beats hidden when an ancestor opacity stacking context would+ otherwise let the transformed reel paint old rows through the window. */+ overflow: clip;+ isolation: isolate;}.tool-ticker__reel {