diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d9a86d42..b690221f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,56 @@ # Changelog +## [v1.0.15] - 2026-11-20 + +同步上游 v0.7.28 之后到 v0.7.30 的功能提交(跳过上游 0.7.29 / 0.7.30 版本号 bump)。 + +### 流式输出 + +- perf(render): 流式文本按节奏揭示,并减轻 Markdown / 高亮渲染负担 (bef6dd6f) +- feat(stream): 流式文本尾部淡入 (aa3effc3) +- fix(stream): 块结束后立即补齐前面的流式文字 (cd202251) +- feat(settings): 流式逐字节奏与尾部淡入可单独开关 (41d797f6) +- feat(stream): 工具卡按流式节奏生长入场 (1182ec4c) +- fix(stream): 工具卡入场只做淡入,不再插值高度 (af45e12a) +- fix(chat): 流式期间每帧兜底贴底 (af5b1935) + +### Markdown 与高亮 + +- fix(render): 补齐嵌套代码块样式,自定义动画遵从减少动效 (e892dfd9) +- fix(markdown): 补齐标题层级、嵌套表格、HTML 注释与列表 / 链接样式 (8c5ee29c) +- perf(markdown): 缓存非流式消息的分块结果 (a79bd18d) +- perf(markdown): 合并稳定块组,超大 live 块限频完整解析 (14f317a4) +- refactor(markdown): 抽出 Mermaid 渲染块 (aab42f47) +- style(markdown): 去掉 Mermaid 块文件末尾多余空行 (ad1e9011) +- perf(highlight): 流式高亮改为增量协议 (2f958c0b) +- perf(markdown): 大块解析移到 Worker (806773d5) +- feat(markdown): 行内前瞻与长代码块折叠 (fc5a26be) +- perf(highlight): 语法失败按语言冷却 (2b4e25fc) +- fix(markdown): 折叠改为限高可滚动,按钮并入操作区 (50c45413) +- fix(markdown): 围栏语言没写完时不做增量追加 (3e9531e6) +- feat(settings): 长代码块折叠可开关,默认开启 (4c63b193) +- fix(markdown): 增量渲染按块边界判断,不再猜后缀 (e7894e9c) +- perf(markdown): 尾部增量解析与诊断补强 (bd2cc1a8) +- fix(markdown): 图区域不再吞掉触摸滚动 (b50e3407) + +### 长会话、虚拟列表与内存 + +- perf(chat): 长会话下避免逐帧重算与无效重渲染 (cde5248a) +- perf(cache): 消息渲染相关缓存加上体积上限 (ff495683) +- perf(virtual): 会话恢复按 key 取高度,滚动时不再重建 observer (2b17bb58) +- perf(virtual): 冷启动按消息内容估算行高 (5eaf2a94) +- refactor(render): 统一有上限缓存,补开发期耗时打点 (078a7cd1) +- refactor(chat): 抽出时间线高度估算与会话测量缓存 (35104fc1) +- perf(render): 长消息块级窗口化与流式掉帧采样 (c7836eea) +- refactor(message): 拆出工具摘要与内容分组 (3ab37925) +- fix(chat): 翻页锚点让位于用户滚动,跳屏渲染延后到真实布局 (f35f8991) +- feat(memory): 会话持有量统计、按体积分页与闲置回收 (94cb5d61) +- perf(chat): 预渲染窗口改为按像素计算,高亮提前到可见之前 (664af913) + +### 输入 + +- fix(input): 手持设备按触摸优先,不再被媒体查询判成桌面 (5dc51948) + ## [v1.0.14] - 2026-11-18 - fix(chat): 压缩后的续写继续挂过程壳 (1ffc33ac) diff --git a/package-lock.json b/package-lock.json index ac4e9b7fa..3c87c61b1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "opencodeui", - "version": "1.0.14", + "version": "1.0.15", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "opencodeui", - "version": "1.0.14", + "version": "1.0.15", "hasInstallScript": true, "license": "GPL-3.0-only", "dependencies": { diff --git a/package.json b/package.json index d066b0376..fa9ac3b73 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencodeui", - "version": "1.0.14", + "version": "1.0.15", "description": "A third-party web frontend for OpenCode", "license": "GPL-3.0-only", "type": "module", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 7a4982683..435cef517 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -2725,7 +2725,7 @@ dependencies = [ [[package]] name = "opencodeui" -version = "1.0.14" +version = "1.0.15" dependencies = [ "futures-util", "log", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 931673912..d3b0216a0 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodeui" -version = "1.0.14" +version = "1.0.15" description = "OpenCode UI - Tauri Mobile App" authors = ["lehhair"] license = "GPL-3.0-only" diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 32970c50e..78433ee1d 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "../node_modules/@tauri-apps/cli/config.schema.json", "productName": "OpenCode", - "version": "1.0.14", + "version": "1.0.15", "identifier": "com.opencodeui.app", "build": { "frontendDist": "../dist", diff --git a/src/App.tsx b/src/App.tsx index 063756b40..382c6a02e 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -15,6 +15,7 @@ import { useSessionContext } from './contexts/useSessionContext' import { useViewportHeight } from './hooks/useViewportHeight' import { useCloseServiceDialog } from './hooks/useCloseServiceDialog' import { useWakeLock } from './hooks/useWakeLock' +import { useIdleSessionTrim } from './hooks/useIdleSessionTrim' import type { KeybindingHandlers } from './hooks/useKeybindings' import { keybindingStore } from './store/keybindingStore' import { @@ -125,6 +126,7 @@ function App() { useViewportHeight() useWakeLock(wakeLock) + useIdleSessionTrim() const activeDirectories = useMemo( () => diff --git a/src/components/CodeBlock.test.tsx b/src/components/CodeBlock.test.tsx index 2d8cf8118..2db93dcc6 100644 --- a/src/components/CodeBlock.test.tsx +++ b/src/components/CodeBlock.test.tsx @@ -19,7 +19,7 @@ const useStreamingSyntaxHighlightMock = vi.fn( output: null, }), ) -const useInViewMock = vi.fn(() => ({ ref: vi.fn(), inView: false })) +const useNearViewportMock = vi.fn(() => ({ ref: vi.fn(), near: false })) const themeSnapshot = { codeWordWrap: false } vi.mock('../hooks/useInputCapabilities', () => ({ @@ -32,7 +32,7 @@ vi.mock('../hooks/useSyntaxHighlight', () => ({ })) vi.mock('../hooks/useInView', () => ({ - useInView: () => useInViewMock(), + useNearViewport: () => useNearViewportMock(), })) vi.mock('../store/themeStore', () => ({ @@ -63,8 +63,8 @@ describe('CodeBlock', () => { useSyntaxHighlightMock.mockReturnValue({ output: [[{ content: 'highlighted', color: '#fff' }]] }) useStreamingSyntaxHighlightMock.mockClear() useStreamingSyntaxHighlightMock.mockReturnValue({ output: null }) - useInViewMock.mockReset() - useInViewMock.mockReturnValue({ ref: vi.fn(), inView: false }) + useNearViewportMock.mockReset() + useNearViewportMock.mockReturnValue({ ref: vi.fn(), near: false }) }) it('requires tap-to-reveal copy button for unlabeled touch-ui code blocks', () => { @@ -125,7 +125,7 @@ describe('CodeBlock', () => { }) it('renders highlighted tokens as selectable plain pre content', () => { - useInViewMock.mockReturnValue({ ref: vi.fn(), inView: true }) + useNearViewportMock.mockReturnValue({ ref: vi.fn(), near: true }) const { container } = render() @@ -140,7 +140,7 @@ describe('CodeBlock', () => { }) it('keeps highlighted prefix while streaming suffix waits for new tokens', () => { - useInViewMock.mockReturnValue({ ref: vi.fn(), inView: true }) + useNearViewportMock.mockReturnValue({ ref: vi.fn(), near: true }) useSyntaxHighlightMock.mockImplementation((highlightCode: string): HighlightMockOutput => { if (highlightCode === 'const') return { output: [[{ content: 'const', color: '#fff' }]] } return { output: null } @@ -156,7 +156,7 @@ describe('CodeBlock', () => { }) it('enables highlighting when visible', () => { - useInViewMock.mockReturnValue({ ref: vi.fn(), inView: true }) + useNearViewportMock.mockReturnValue({ ref: vi.fn(), near: true }) render() diff --git a/src/components/CodeBlock.tsx b/src/components/CodeBlock.tsx index 5a46bb8e0..36057bbe1 100644 --- a/src/components/CodeBlock.tsx +++ b/src/components/CodeBlock.tsx @@ -3,7 +3,8 @@ import { useInputCapabilities } from '../hooks/useInputCapabilities' import { useSyntaxHighlight, useStreamingSyntaxHighlight, type HighlightTokens } from '../hooks/useSyntaxHighlight' import { themeStore } from '../store/themeStore' import { CopyButton } from './ui' -import { useInView } from '../hooks/useInView' +import { ChevronDownIcon, ChevronUpIcon } from './Icons' +import { useNearViewport } from '../hooks/useInView' /** Languages that carry no useful information — hide the label */ const HIDDEN_LANGS = new Set(['text', 'plain', 'txt', 'plaintext']) @@ -46,12 +47,16 @@ function renderIncrementalTokens(tokens: HighlightTokens, suffix: string) { type FlatHighlightToken = { content: string; color?: string } +/** 共享换行节点,避免每次重排都给换行新造一个对象 */ +const NEWLINE_TOKEN: FlatHighlightToken = { content: '\n' } + function flattenTokens(tokens: HighlightTokens, suffix: string): FlatHighlightToken[] { const result: FlatHighlightToken[] = [] - tokens.forEach((line, lineIndex) => { - line.forEach(token => result.push({ content: token.content, color: token.color })) - if (lineIndex < tokens.length - 1) result.push({ content: '\n' }) - }) + for (let lineIndex = 0; lineIndex < tokens.length; lineIndex += 1) { + const line = tokens[lineIndex] + for (let tokenIndex = 0; tokenIndex < line.length; tokenIndex += 1) result.push(line[tokenIndex]) + if (lineIndex < tokens.length - 1) result.push(NEWLINE_TOKEN) + } if (suffix) result.push({ content: suffix }) return result } @@ -107,6 +112,11 @@ interface CodeBlockProps { streamingHighlight?: boolean /** Persistent controls rendered beside the copy action. */ headerActions?: ReactNode + /** 折叠态:配合 maxHeight 裁剪而不是滚动,用于长代码块 */ + folded?: boolean + /** 展开/收起回调;提供时在 header 或悬浮操作区显示对应按钮 */ + onToggleFold?: () => void + foldLabel?: { expand: string; collapse: string } } export const CodeBlock = memo(function CodeBlock({ @@ -121,6 +131,9 @@ export const CodeBlock = memo(function CodeBlock({ forceHighlight = false, streamingHighlight = false, headerActions, + folded = false, + onToggleFold, + foldLabel, }: CodeBlockProps) { const { codeWordWrap } = useSyncExternalStore(themeStore.subscribe, themeStore.getSnapshot) const { preferTouchUi } = useInputCapabilities() @@ -129,7 +142,10 @@ export const CodeBlock = memo(function CodeBlock({ const highlightCode = code // Lazy load highlighting when close to viewport - const { ref, inView } = useInView({ triggerOnce: true, rootMargin: '200px' }) + // 高亮要赶在可见之前做完:2 屏的提前量,和虚拟列表的预渲染窗口对齐。 + // 用 useNearViewport 而不是 useInView —— 后者 root 取视口,会被聊天滚动容器裁掉, + // 提前量实际不生效,滚到才高亮会看到一段纯文本。 + const { ref, near } = useNearViewport({ rootMargin: '200% 0px', enabled: !deferHighlight, triggerOnce: true }) // Auto-detect tree structure if language is missing or text const effectiveLanguage = useMemo(() => { @@ -147,7 +163,7 @@ export const CodeBlock = memo(function CodeBlock({ return language || 'text' }, [highlightCode, language]) - const shouldHighlight = !deferHighlight && (inView || forceHighlight) + const shouldHighlight = !deferHighlight && (near || forceHighlight) const shouldStreamHighlight = shouldHighlight && streamingHighlight const { output: highlightedTokens } = useSyntaxHighlight(highlightCode, { @@ -207,6 +223,28 @@ export const CodeBlock = memo(function CodeBlock({ const lineHeight = isReasoning ? 'leading-5' : 'leading-6' const textColor = isReasoning ? 'text-text-300' : 'text-text-200' + const foldActionLabel = folded ? foldLabel?.collapse : foldLabel?.expand + const renderFoldAction = (compact: boolean) => + onToggleFold ? ( + + ) : null + const content = displayedHighlight ? (
{language}
           
           
+ {renderFoldAction(false)} {headerActions}
@@ -266,6 +305,8 @@ export const CodeBlock = memo(function CodeBlock({
+ {renderFoldAction(true)} + {headerActions} )} - {/* Scrollable content */} + {/* Scrollable content:折叠态就是限高滚动,不裁切、不渐隐 */}
{content}
diff --git a/src/components/MarkdownRenderer.test.tsx b/src/components/MarkdownRenderer.test.tsx index f8553c406..29ad28fbb 100644 --- a/src/components/MarkdownRenderer.test.tsx +++ b/src/components/MarkdownRenderer.test.tsx @@ -27,6 +27,9 @@ vi.mock('./CodeBlock', () => ({ forceHighlight, streamingHighlight, headerActions, + folded, + onToggleFold, + foldLabel, }: { code: string language?: string @@ -35,6 +38,9 @@ vi.mock('./CodeBlock', () => ({ forceHighlight?: boolean streamingHighlight?: boolean headerActions?: React.ReactNode + folded?: boolean + onToggleFold?: () => void + foldLabel?: { expand: string; collapse: string } }) => (
({ {language} {headerActions} {`${language ?? 'text'}:${code}`} + {onToggleFold ? ( + + ) : null}
), })) @@ -97,6 +108,21 @@ describe('MarkdownRenderer', () => { expect(codeEl.tagName).toBe('CODE') }) + it('keeps h5/h6 semantics instead of collapsing them to h4', () => { + const { container } = render() + + expect(container.querySelector('h5')).toHaveTextContent('Five') + expect(container.querySelector('h6')).toHaveTextContent('Six') + }) + + it('drops raw HTML comments instead of showing them as text when HTML rendering is off', () => { + themeStore.setRenderHtmlContent(false) + const { container } = render(
` + } + + // 嵌在列表 / 引用里的代码块(顶层围栏由 CodeBlock / 流式块接管) + renderer.code = ({ text, lang }) => { + const language = lang?.trim().split(/\s+/, 1)[0] + const languageAttr = language ? ` data-language="${escapeAttribute(language)}"` : '' + return `
${escapeHtml(text)}
` + } + + renderer.codespan = ({ text }) => { + // 内联代码 chip。要点: + // 1) **文字颜色继承正文**,不自己指定:正文是 text-text-200,给主题色或更亮的 + // 色阶都会比正文突出;继承还有个好处——reasoning 里正文变暗时它自动跟着暗 + // 2) **居中不能靠调行高**:行高只是把字形上下的留白等比拉长,字体自身 + // ascent/descent 的不对称(等宽字体 13px 时 12 / 3)一点没变,所以怎么调 + // 都不居中。4x 像素实测:13px + 行高 22px 时拉丁偏下 2.25px、中文偏上 + // 1.5px;把字号降到 0.875em(14px 正文 → 12.25px)配 19px 行高后变成 + // 拉丁 −1.5px / 中文 +1.5px,两边各让一半,是偏差最小的平衡点。 + // 配方对齐 DeepSeek Harness 的内联代码(--dsw-font-markdown-code = 12px/19px, + // 再用 font-size: 0.875em 覆盖成正文字号的 7/8,上下 padding 都为 0) + // 3) **淡底色 + 0.5px 细描边**:靠描边给边界(只给底色在各主题下会和页面糊在一起) + const className = + 'inline-flex items-center font-mono text-[0.875em] leading-[19px] break-words bg-bg-200 border-[0.5px] border-text-100/10 rounded-md px-[5px]' + return `${escapeHtml(text)}` + } + + renderer.strong = function ({ tokens }) { + const className = isReasoning ? 'font-semibold text-text-300' : 'font-semibold text-text-100' + return `${this.parser.parseInline(tokens)}` + } + + renderer.em = function ({ tokens }) { + const className = isReasoning ? 'italic text-text-300' : 'italic text-text-200' + return `${this.parser.parseInline(tokens)}` + } + + // 删除线只来自 ~~...~~(tokenizer 已限制单 ~ 不产生 del) + renderer.del = function ({ tokens }) { + const className = isReasoning + ? 'text-[length:var(--fs-sm)] text-text-500 line-through decoration-text-500/50' + : 'text-text-400 line-through decoration-text-400/50' + return `${this.parser.parseInline(tokens)}` + } + + renderer.link = function ({ href, title, tokens }) { + const content = this.parser.parseInline(tokens) + if (isUnsafeHref(href)) return `${content} [blocked]` + const localPath = decodeLocalFileHref(href) ?? getWindowsAbsolutePath(href) + const normalizedHref = localPath ? encodeLocalFileHref(localPath) : href + const className = isReasoning + ? 'text-[length:var(--fs-sm)] font-medium text-accent-main-200/80 hover:text-accent-main-200 underline underline-offset-2 transition-colors' + : 'font-medium text-accent-main-100 hover:text-accent-main-200 underline underline-offset-2 transition-colors' + const attrs = [ + `href="${escapeAttribute(normalizedHref)}"`, + `class="${className}"`, + localPath ? `title="${escapeAttribute(localPath)}"` : 'target="_blank" rel="noopener noreferrer"', + title && !localPath ? `title="${escapeAttribute(title)}"` : '', + ] + .filter(Boolean) + .join(' ') + return `${content}` + } + + renderer.image = ({ href, title, text }) => { + if (!href || isUnsafeImageSrc(href)) return `[Image blocked: ${escapeHtml(text || '')}]` + const safeTitle = title || text || undefined + const titleAttr = safeTitle ? ` title="${escapeAttribute(safeTitle)}"` : '' + const imgTitleAttr = title ? ` title="${escapeAttribute(title)}"` : '' + const dimensions = inferImageDimensions(href) + const dimensionsAttr = dimensions ? ` width="${dimensions.width}" height="${dimensions.height}"` : '' + return `${escapeAttribute(text || '')}` + } + + renderer.blockquote = function ({ tokens, text }) { + const alertMatch = /^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\][ \t]*(?:\n|$)/i.exec(text) + if (alertMatch) { + const kind = alertMatch[1].toUpperCase() as keyof typeof MARKDOWN_ALERTS + const alert = MARKDOWN_ALERTS[kind] + const body = marked.parse(text.slice(alertMatch[0].length), { renderer, async: false }) as string + const spacingClass = isReasoning ? 'my-2 px-3 py-2' : 'my-4 px-4 py-3' + return `` + } + + const className = isReasoning + ? 'border-l-2 border-text-500/30 pl-3 py-0.5 my-2 first:mt-0 last:mb-0 text-text-400' + : 'border-l-2 border-accent-main-100/60 pl-4 py-1 my-4 first:mt-0 last:mb-0 text-text-300 italic' + return `
${this.parser.parse(tokens)}
` + } + + renderer.list = function ({ ordered, start, items }) { + const tag = ordered ? 'ol' : 'ul' + const className = isReasoning + ? ordered + ? 'text-[length:var(--fs-sm)] list-decimal list-outside mb-2 last:mb-0 space-y-0.5 marker:text-text-500/60' + : 'text-[length:var(--fs-sm)] list-disc list-outside ml-4 mb-2 last:mb-0 space-y-0.5 marker:text-text-500/60' + : ordered + ? 'list-decimal list-outside mb-4 last:mb-0 space-y-1 marker:text-text-400/80' + : 'list-disc list-outside ml-5 mb-4 last:mb-0 space-y-1 marker:text-text-400/80' + const startAttr = ordered && start && start !== 1 ? ` start="${start}"` : '' + const itemsHtml = items.map(item => renderer.listitem(item)).join('') + return `<${tag}${startAttr} class="${className}">${itemsHtml}` + } + + renderer.listitem = function ({ tokens, task }) { + const className = isReasoning + ? 'text-[length:var(--fs-sm)] text-text-400 pl-1 leading-5' + : 'text-text-200 pl-1 leading-7' + const content = tokens ? this.parser.parse(tokens) : '' + // GFM 任务项不显示列表符号,只留勾选框 + return `
  • ${content}
  • ` + } + + // 任务列表勾选框只在这里出一份:marked 会把 `- [x]` 的方括号切成独立的 checkbox token, + // 渲染器再自己加一个就会出现两个勾选框。统一由 checkbox 渲染。 + renderer.checkbox = ({ checked }) => { + return ` ` + } + + renderer.hr = () => { + const className = isReasoning + ? 'border-border-200/40 my-4 first:mt-0 last:mb-0' + : 'border-border-200/60 my-8 first:mt-0 last:mb-0' + return `
    ` + } + + return renderer +} + +const FOOTNOTE_DEFINITION_PATTERN = /^ {0,3}\[\^([^\]\s]+)\]:[ \t]*(.*)$/ +const FENCE_OPENING_PATTERN = /^ {0,3}(`{3,}|~{3,})/ + +export type FootnoteDefinition = { label: string; content: string } + +/** + * 把 GFM 脚注定义(`[^label]: 内容`)从正文里抽出来,交给正文末尾统一渲染。 + * marked 不认脚注语法:不抽出来的话 `[^1]: 注释` 会被当成链接引用定义, + * 正文里的 `[^1]` 就渲染成一个 href 是脚注内容的链接(正文与定义挤在同一个块时)。 + * 定义允许缩进续行(4 空格 / 制表符),代码围栏里的 `[^x]:` 不动。 + */ +export function extractFootnoteDefinitions(src: string): { body: string; definitions: FootnoteDefinition[] } { + const lines = src.split('\n') + const definitions: FootnoteDefinition[] = [] + const body: string[] = [] + let fence: string | null = null + let current: { label: string; lines: string[] } | null = null + + const flush = () => { + if (!current) return + definitions.push({ label: current.label, content: current.lines.join('\n').trim() }) + current = null + } + + for (const line of lines) { + const fenceMatch = FENCE_OPENING_PATTERN.exec(line) + if (fenceMatch) { + const char = fenceMatch[1]![0]! + if (!fence) fence = char + else if (fence === char) fence = null + flush() + body.push(line) + continue + } + + if (!fence) { + const definition = FOOTNOTE_DEFINITION_PATTERN.exec(line) + if (definition) { + flush() + current = { label: definition[1]!, lines: [definition[2] ?? ''] } + continue + } + if (current) { + if (/^(?: {4}|\t)/.test(line)) { + current.lines.push(line.replace(/^(?: {4}|\t)/, '')) + continue + } + if (/^[ \t]*$/.test(line)) { + current.lines.push('') + continue + } + } + } + + flush() + body.push(line) + } + flush() + + if (definitions.length) { + while (body.length && !body[body.length - 1]!.trim()) body.pop() + } + return { body: body.join('\n'), definitions } +} + +function renderFootnoteSectionHtml(definitions: FootnoteDefinition[], isReasoning: boolean, renderHtml: boolean): string { + const renderer = getRenderer(isReasoning, renderHtml) + const items = definitions.map(({ label, content }) => { + const id = getFootnoteId(label) + const markup = marked.parseInline(content, { renderer }) as string + const className = isReasoning ? 'text-[length:var(--fs-sm)] text-text-400 leading-5' : 'text-text-300 leading-6' + return `
  • ${escapeHtml(label)}. ${markup} back
  • ` + }) + + const listClass = isReasoning + ? 'my-2 list-decimal list-inside space-y-1 border-t border-border-200/30 pt-2' + : 'my-4 list-decimal list-inside space-y-1 border-t border-border-200/40 pt-3' + return `
      ${items.join('')}
    ` +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +let rendererCache: Record | null = null +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getRenderer(isReasoning: boolean, renderHtml: boolean): any { + if (!rendererCache) { + rendererCache = { + 'default:html': createMarkdownHtmlRenderer(false, true), + 'default:nohtml': createMarkdownHtmlRenderer(false, false), + 'reasoning:html': createMarkdownHtmlRenderer(true, true), + 'reasoning:nohtml': createMarkdownHtmlRenderer(true, false), + } + } + return rendererCache[`${isReasoning ? 'reasoning' : 'default'}:${renderHtml ? 'html' : 'nohtml'}`] +} + +export function parseMarkdownToHtml(src: string, isReasoning: boolean, renderHtml = true): string { + const displayMath = getDisplayMathSource(src) + if (displayMath != null) { + const className = isReasoning ? 'my-2 overflow-x-auto text-text-400' : 'my-4 overflow-x-auto text-text-200' + return `
    ${renderKatexHtml(displayMath, true)}
    ` + } + + const renderer = getRenderer(isReasoning, renderHtml) + const { body, definitions } = extractFootnoteDefinitions(src) + if (!definitions.length) { + // 关闭 HTML 渲染时,裸 HTML 已在 renderer.html 里转义,输出完全由本地渲染器构造 + return marked.parse(src, { renderer, async: false }) as string + } + const bodyHtml = body.trim() ? (marked.parse(body, { renderer, async: false }) as string) : '' + return `${bodyHtml}${renderFootnoteSectionHtml(definitions, isReasoning, renderHtml)}` +} + +export function parseMarkdownInlineToHtml(src: string, isReasoning: boolean, renderHtml = true): string { + const renderer = getRenderer(isReasoning, renderHtml) + return marked.parseInline(src, { renderer }) as string +} diff --git a/src/components/markdownStream.test.ts b/src/components/markdownStream.test.ts index acdd53473..9f463b85b 100644 --- a/src/components/markdownStream.test.ts +++ b/src/components/markdownStream.test.ts @@ -332,6 +332,111 @@ inside comment expect(next.blocks).toEqual(splitMarkdownStream('before\n\n```ts\nconst x = 1\n```', true)) }) + it('keeps re-splitting while the fence language is still growing', () => { + // 首拍只有半个语言名:不能被当成已打开的代码块做纯追加 + const first = projectMarkdownStream(undefined, '```pytho', true) + const second = projectMarkdownStream(first, '```python', true) + const tail = second.blocks.at(-1)! + + expect(tail.mode).toBe('code') + expect(tail.language).toBe('python') + expect(tail.src).toBe('') + + // 换行之后语言定型,才允许把后续内容当代码追加 + const third = projectMarkdownStream(second, '```python\nprint(1)', true) + const tailAfter = third.blocks.at(-1)! + expect(tailAfter.language).toBe('python') + expect(tailAfter.src).toContain('print(1)') + }) + + it('never merges a new block started after a line break', () => { + // 换行后的列表项必须重新切分,不能被并进上一段 + let text = 'para\n' + let projection = projectMarkdownStream(undefined, text, true) + text += '- item' + projection = projectMarkdownStream(projection, text, true) + + expect(projection.blocks).toEqual(splitMarkdownStream(text, true)) + expect(projection.blocks.at(-1)!.src).toContain('- item') + }) + + it('recognizes setext headings formed across ticks', () => { + let text = 'Title' + let projection = projectMarkdownStream(undefined, text, true) + for (const part of ['\n===', '\n']) { + text += part + projection = projectMarkdownStream(projection, text, true) + } + + expect(projection.blocks).toEqual(splitMarkdownStream(text, true)) + }) + + it('recognizes a fence opener arriving one character at a time', () => { + let text = 'para\n' + let projection = projectMarkdownStream(undefined, text, true) + for (const part of ['`', '`', '`', 'python', '\n', 'print(1)']) { + text += part + projection = projectMarkdownStream(projection, text, true) + } + + const tail = projection.blocks.at(-1)! + expect(tail.mode).toBe('code') + expect(tail.language).toBe('python') + expect(tail.src).toContain('print(1)') + }) + + it('closes a fence arriving one character at a time', () => { + let text = '```ts\nx\n' + let projection = projectMarkdownStream(undefined, text, true) + for (const part of ['`', '`', '`']) { + text += part + projection = projectMarkdownStream(projection, text, true) + } + + expect(projection.blocks).toEqual(splitMarkdownStream(text, true)) + expect(projection.blocks.at(-1)!.complete).toBe(true) + }) + + it('closes an indented fence arriving one character at a time', () => { + let text = '```ts\nx\n' + let projection = projectMarkdownStream(undefined, text, true) + for (const part of [' ', ' ', '`', '`', '`']) { + text += part + projection = projectMarkdownStream(projection, text, true) + } + + expect(projection.blocks.at(-1)!.complete).toBe(true) + }) + + it('tail re-split stays equivalent to a full split across a mixed document', () => { + const source = [ + '# 标题', + '第一段普通文本,包含 **粗体** 和 `行内代码`。', + '- 列表一', + '- 列表二', + '```ts', + 'const a = 1', + 'const b = 2', + '```', + '| 列一 | 列二 |', + '| --- | --- |', + '| 1 | 2 |', + '结尾段落,带一个 [引用][ref]。', + '', + '[ref]: https://example.com', + '', + '最后一行。', + ].join('\n\n') + + let text = '' + let projection: ReturnType | undefined + for (let index = 0; index < source.length; index += 7) { + text = source.slice(0, index + 7) + projection = projectMarkdownStream(projection, text, true) + expect(projection.blocks).toEqual(splitMarkdownStream(text, true)) + } + }) + it('projects pure live-tail append without rebuilding stable blocks', () => { const first = projectMarkdownStream(undefined, 'hello', true) const next = projectMarkdownStream(first, 'hello world', true) @@ -365,3 +470,76 @@ inside comment expect(next.blocks).toEqual(splitMarkdownStream('intro\n- item', true)) }) }) + +describe('Markdown 块组', () => { + it('把达到阈值的一组相邻段落合并成单个块', () => { + const first = 'a'.repeat(400) + const second = 'b'.repeat(400) + const third = 'c'.repeat(300) + const blocks = splitMarkdownStream(`${first}\n\n${second}\n\n${third}`, false) + + expect(blocks).toHaveLength(2) + expect(blocks[0]).toEqual(expect.objectContaining({ mode: 'full' })) + expect(blocks[0].src).toContain(first) + expect(blocks[0].src).toContain(second) + expect(blocks[0].src).not.toContain(third) + expect(blocks[1].src).toContain(third) + }) + + it('流式时最后一块始终独立,并保持稳定 key', () => { + const first = 'a'.repeat(400) + const second = 'b'.repeat(400) + const live = 'c'.repeat(40) + const md = `${first}\n\n${second}\n\n${live}` + const blocks = splitMarkdownStream(md, true) + + expect(blocks).toHaveLength(2) + expect(blocks[0].mode).toBe('full') + expect(blocks[1].mode).toBe('live') + expect(blocks[1].src).toContain(live) + + const next = splitMarkdownStream(`${md}${'d'.repeat(20)}`, true) + expect(next[0].key).toBe(blocks[0].key) + expect(next[1].key).toBe(blocks[1].key) + expect(next[1].src).toContain('c'.repeat(40) + 'd'.repeat(20)) + }) + + it('不把代码块卷进块组', () => { + const md = `${'a'.repeat(400)}\n\n\`\`\`ts\nconst x = 1\n\`\`\`\n\n${'b'.repeat(400)}` + const blocks = splitMarkdownStream(md, false) + + expect(blocks.some(block => block.mode === 'code')).toBe(true) + const code = blocks.find(block => block.mode === 'code') + expect(code?.src).toBe('const x = 1') + }) +}) + +describe('尾部增量解析 · 逐字符', () => { + it('matches a full split for every single-character tick', () => { + const source = [ + '# 标题', + '一段普通文本,**粗体**、`code`、[链接](https://example.com)。', + '- 列表一', + '- 列表二', + '```ts', + 'const a = 1', + '', + 'const b = 2', + '```', + '| a | b |', + '| - | - |', + '| 1 | 2 |', + '结尾 [引用][ref]。', + '', + '[ref]: https://example.com', + ].join('\n\n') + + let text = '' + let projection: ReturnType | undefined + for (let index = 0; index < source.length; index += 1) { + text = source.slice(0, index + 1) + projection = projectMarkdownStream(projection, text, true) + expect(projection.blocks).toEqual(splitMarkdownStream(text, true)) + } + }) +}) diff --git a/src/components/markdownStream.ts b/src/components/markdownStream.ts index 82f455340..1be7dc754 100644 --- a/src/components/markdownStream.ts +++ b/src/components/markdownStream.ts @@ -13,6 +13,10 @@ export type MarkdownStreamBlock = { export type MarkdownStreamProjection = { text: string blocks: MarkdownStreamBlock[] + /** 未分组源块,尾部重解析只从最后一个源块起点开始 */ + sourceBlocks?: MarkdownSourceBlock[] + /** 已收集的引用定义(尾部重解析需要继承) */ + referenceDefinitions?: string } const MARKUP_PREVIEW_LANGUAGES = new Set(['html', 'htm', 'xhtml', 'xml', 'svg']) @@ -58,6 +62,16 @@ function getOpeningFence(raw: string) { return { char: match[1][0], size: match[1].length } } +/** + * 围栏开头那一行是否已经换行。 + * + * 没换行时语言名还在增长(` ```pytho` → ` ```python`),这一阶段必须重新切分; + * 走「未闭合 fence 纯追加」会把剩下的字符拼进代码内容,语言永远停在半截。 + */ +function hasFenceOpeningLineBreak(raw: string): boolean { + return /^[ \t]{0,3}(?:`{3,}|~{3,})[^\n]*\n/.test(raw) +} + function hasOpenFence(raw: string) { return getTrailingOpenFenceStart(raw) === 0 } @@ -65,8 +79,14 @@ function hasOpenFence(raw: string) { function suffixClosesOpenFence(raw: string, suffix: string) { const fence = getOpeningFence(raw) if (!fence) return suffix.includes('```') || suffix.includes('~~~') - const prefix = raw.slice(-(fence.size - 1)) - return new RegExp(`^[\\s\\S]*(?:^|\\n)[ \\t]{0,3}${fence.char}{${fence.size},}[ \\t]*(?:\\n|$)`).test(prefix + suffix) + // 用「当前行 + 后缀」判断:闭合围栏可能被拆成多次到达,也可能带缩进, + // 只取末尾几个字符会丢掉行首和缩进信息。 + const lineStart = raw.lastIndexOf('\n') + 1 + const currentLine = raw.slice(lineStart) + const closePattern = new RegExp( + `(?:^|\\n)[ \\t]{0,3}${fence.char}{${fence.size},}[ \\t]*(?:\\n|$)`, + ) + return closePattern.test(currentLine + suffix) } function getLanguage(value: string | undefined) { @@ -89,7 +109,41 @@ export function stripLeadingHtmlComments(source: string): string { return rest } -type MarkdownSourceBlock = { start: number; raw: string; src: string; token?: Tokens.Generic } +export type MarkdownSourceBlock = { start: number; raw: string; src: string; token?: Tokens.Generic } +/** 相邻小段落合成块组的最小字符数:避免长回答被拆成几百个组件 */ +const MARKDOWN_GROUP_MIN_CHARS = 800 +/** 可以安全合并的 token:都是纯 Markdown 块;代码/表格/HTML artifact 必须保持独立 */ +const GROUPABLE_TOKEN_TYPES = new Set(['paragraph', 'heading', 'list', 'blockquote', 'hr']) + +function groupMarkdownBlocks(blocks: MarkdownSourceBlock[]): MarkdownSourceBlock[] { + const grouped: MarkdownSourceBlock[] = [] + let buffer: MarkdownSourceBlock[] = [] + let bufferRaw = '' + + const flush = (force: boolean) => { + if (buffer.length === 0) return + if (buffer.length === 1 || (!force && bufferRaw.length < MARKDOWN_GROUP_MIN_CHARS)) { + grouped.push(...buffer) + } else { + grouped.push({ start: buffer[0].start, raw: bufferRaw, src: bufferRaw }) + } + buffer = [] + bufferRaw = '' + } + + for (const block of blocks) { + if (!block.token || !GROUPABLE_TOKEN_TYPES.has(block.token.type)) { + flush(false) + grouped.push(block) + continue + } + buffer.push(block) + bufferRaw += block.raw + if (bufferRaw.length >= MARKDOWN_GROUP_MIN_CHARS) flush(true) + } + flush(false) + return grouped +} const BLOCK_HTML_CONTAINERS = new Set([ 'address', @@ -371,14 +425,19 @@ function splitMarkdownBlocks(markdown: string) { } } -export function splitMarkdownStream(markdown: string, isStreaming: boolean): MarkdownStreamBlock[] { +function buildStreamBlocks( + sourceBlocks: MarkdownSourceBlock[], + referenceDefinitions: string, + isStreaming: boolean, + fenceStart: number | null, +): MarkdownStreamBlock[] { if (!isStreaming) { - if (!markdown) return [{ key: 'html:0', src: '', mode: 'full' }] - const { blocks, referenceDefinitions } = splitMarkdownBlocks(markdown) - if (blocks.length === 1 && blocks[0]?.token?.type !== 'code' && blocks[0]?.token?.type !== 'table') { - return [{ key: 'html:0', src: appendReferenceDefinitions(blocks[0]?.raw ?? markdown, referenceDefinitions), mode: 'full' }] + if (sourceBlocks.length === 0) return [{ key: 'html:0', src: '', mode: 'full' }] + const first = sourceBlocks[0]! + if (sourceBlocks.length === 1 && first.token?.type !== 'code' && first.token?.type !== 'table') { + return [{ key: 'html:0', src: appendReferenceDefinitions(first.raw, referenceDefinitions), mode: 'full' }] } - return blocks.map(block => { + return groupMarkdownBlocks(sourceBlocks).map(block => { if (block.token?.type === 'code') { const language = getLanguage((block.token as Tokens.Code).lang) return { @@ -409,16 +468,21 @@ export function splitMarkdownStream(markdown: string, isStreaming: boolean): Mar }) } - if (!markdown) return [{ key: 'html:0', src: '', mode: 'live' }] + if (sourceBlocks.length === 0) return [{ key: 'html:0', src: '', mode: 'live' }] - const fenceStart = getTrailingOpenFenceStart(markdown) - const { blocks, referenceDefinitions } = splitMarkdownBlocks(markdown) - if (blocks.length === 1 && blocks[0]?.token?.type !== 'code' && blocks[0]?.token?.type !== 'table') { - return [{ key: 'html:0', src: appendReferenceDefinitions(blocks[0]?.raw ?? markdown, referenceDefinitions), mode: 'live' }] + const first = sourceBlocks[0]! + if (sourceBlocks.length === 1 && first.token?.type !== 'code' && first.token?.type !== 'table') { + return [{ key: 'html:0', src: appendReferenceDefinitions(first.raw, referenceDefinitions), mode: 'live' }] } - return blocks.map(block => { - const isLiveTail = block === blocks[blocks.length - 1] || (fenceStart != null && block.start >= fenceStart) + // 流式时最后一块永远是 live 尾,不能并进稳定块组 + const groupedBlocks = groupMarkdownBlocks(sourceBlocks.slice(0, -1)) + const liveTail = sourceBlocks[sourceBlocks.length - 1] + if (liveTail) groupedBlocks.push(liveTail) + + return groupedBlocks.map(block => { + const isLiveTail = + block === sourceBlocks[sourceBlocks.length - 1] || (fenceStart != null && block.start >= fenceStart) if (block.token?.type === 'code') { const complete = fenceStart == null || block.start < fenceStart const language = getLanguage((block.token as Tokens.Code).lang) @@ -449,18 +513,102 @@ export function splitMarkdownStream(markdown: string, isStreaming: boolean): Mar }) } -/** suffix 可能切出新块时必须全量 re-lex;宁可多 split,不可错并块 */ -function suffixBreaksLiveBlock(suffix: string): boolean { - if (!suffix) return false - if (suffix.includes('\n\n')) return true - if (suffix.includes('```') || suffix.includes('~~~')) return true - // 引用定义 / 脚注标号 - if (suffix.includes(']:')) return true - // 行首块结构(heading / list / quote / table / hr) - if (/\n(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s?|\||-{3,}|\*{3,}|_{3,})/.test(suffix)) return true - // suffix 本身以块结构开头(上一帧刚好停在段落边界之后) - if (/^(?:#{1,6}\s|[-*+]\s|\d+\.\s|>\s?|\|)/.test(suffix)) return true - return false +function splitMarkdownStreamDetailed( + markdown: string, + isStreaming: boolean, +): Required> { + const { blocks, referenceDefinitions } = splitMarkdownBlocks(markdown) + const fenceStart = isStreaming ? (getTrailingOpenFenceStart(markdown) ?? null) : null + return { + blocks: buildStreamBlocks(blocks, referenceDefinitions, isStreaming, fenceStart), + sourceBlocks: blocks, + referenceDefinitions, + } +} + +export function splitMarkdownStream(markdown: string, isStreaming: boolean): MarkdownStreamBlock[] { + return splitMarkdownStreamDetailed(markdown, isStreaming).blocks +} + +/** + * 只从最后一个源块开始重解析。 + * + * 前面的源块已经收尾,新的文本只可能扩展/改变最后一个块;把尾部切片重新 lex, + * 再和稳定源块拼起来重新分组。引用定义出现在尾部时会影响稳定块的链接, + * 这种情况返回 null,让调用方走全量切分。 + */ +function projectTail( + previous: MarkdownStreamProjection, + markdown: string, + isStreaming: boolean, +): MarkdownStreamProjection | null { + const sources = previous.sourceBlocks + const tailStart = sources?.at(-1)?.start + if (!sources || tailStart === undefined) return null + + const tailText = markdown.slice(tailStart) + const { blocks: tailSources, referenceDefinitions: tailDefinitions } = splitMarkdownBlocks(tailText) + // 新定义会影响已经稳定的块,走全量 + if (tailDefinitions && tailDefinitions !== (previous.referenceDefinitions ?? '')) return null + if (tailSources.length === 0) return null + + const combined = [ + ...sources.slice(0, -1), + ...tailSources.map(block => ({ ...block, start: block.start + tailStart })), + ] + const tailFenceOffset = getTrailingOpenFenceStart(tailText) + const fenceStart = tailFenceOffset === undefined ? null : tailFenceOffset + tailStart + + return { + text: markdown, + blocks: buildStreamBlocks(combined, previous.referenceDefinitions ?? '', isStreaming, fenceStart), + sourceBlocks: combined, + referenceDefinitions: previous.referenceDefinitions ?? '', + } +} + +/** + * 未闭合代码块的代码文本。 + * + * marked 对开放围栏的处理是:取开头围栏行之后的全部内容,只裁掉末尾一个换行。 + * 这里按同一规则从 raw 派生,避免累积拼接和解析器不一致(空行、行尾换行都会偏差)。 + */ +function openFenceCodeText(raw: string): string { + const lineEnd = raw.indexOf('\n') + if (lineEnd === -1) return '' + const content = raw.slice(lineEnd + 1) + return content.endsWith('\n') ? content.slice(0, -1) : content +} +/** + * live 段能否纯追加。 + * + * 块类型只可能在换行处改变,所以只放行「同一行内继续写」这一种情况: + * - 后缀里有换行 → 可能开始新的块,重新切分 + * - 当前段已经停在行首 → 下一个字符可能开启块,重新切分 + * - 当前行正在补围栏开头(``` / ~~~)→ 重新切分,让 launcher 尽早变成 code + * + * 同一行内的追加只影响行内语法,块渲染器会重新解析这一段,类型不会漂移。 + */ +function canAppendToLiveTail(tail: MarkdownStreamBlock, suffix: string): boolean { + if (!suffix || suffix.includes('\n')) return false + if (!tail.src || tail.src.endsWith('\n')) return false + + const lastLine = tail.src.slice(tail.src.lastIndexOf('\n') + 1) + // 已经是 3 个以上的围栏字符:这一段应该是代码块,不能继续当段落追加 + if (/^[ \t]{0,3}(?:`{3,}|~{3,})/.test(lastLine)) return false + // 正在补齐围栏开头(例如两个反引号 + 新的反引号) + if (/^[ \t]{0,3}[`~]+$/.test(lastLine) && /^[ \t]*[`~]/.test(suffix)) return false + // 链接/脚注定义是在同一行内变成 def 的,会让这一块从 blocks 里消失 + if (/^[ \t]{0,3}\[[^\]\n]+\]:/.test(lastLine + suffix)) return false + + // 行首块标记也可能在同一行内完成("-" -> "- "、"--" -> "---"、"#" -> "# "), + // 只有当前行还停在「纯标记」状态时才需要重新切分;一旦标记后面有内容,类型已定。 + const combinedLine = (lastLine + suffix).replace(/^ {0,3}/, '') + if (/^(?:[-*+>]|#{1,6}|\d{1,9}[.)])[ \t]*$/.test(combinedLine)) return false + if (/^(?:`{1,2}|~{1,2})$/.test(combinedLine)) return false + if (/^(?:=+|-+|\*{3,}|_{3,})$/.test(combinedLine)) return false + + return true } export function projectMarkdownStream( @@ -469,7 +617,7 @@ export function projectMarkdownStream( isStreaming: boolean, ): MarkdownStreamProjection { if (!isStreaming || !previous || !markdown.startsWith(previous.text)) { - return { text: markdown, blocks: splitMarkdownStream(markdown, isStreaming) } + return { text: markdown, ...splitMarkdownStreamDetailed(markdown, isStreaming) } } const suffix = markdown.slice(previous.text.length) @@ -486,21 +634,33 @@ export function projectMarkdownStream( hasOpenFence(tail.raw) && !suffixClosesOpenFence(tail.raw, suffix) ) { + // 开头围栏行还没换行 → 语言名可能还在长,重新切分 + if (!hasFenceOpeningLineBreak(tail.raw)) { + return ( + projectTail(previous, markdown, isStreaming) ?? { + text: markdown, + ...splitMarkdownStreamDetailed(markdown, isStreaming), + } + ) + } + const nextRaw = tail.raw + suffix return { text: markdown, blocks: [ ...stablePrefix, { ...tail, - raw: tail.raw + suffix, - src: tail.src + suffix, + raw: nextRaw, + src: openFenceCodeText(nextRaw), }, ], + sourceBlocks: previous.sourceBlocks, + referenceDefinitions: previous.referenceDefinitions, } } - // live 尾段纯追加:稳定块保持同一引用,只改 tail.src - if (tail?.mode === 'live' && !suffixBreaksLiveBlock(suffix)) { + // live 尾段纯追加:只在同一行内继续写时成立 + if (tail?.mode === 'live' && canAppendToLiveTail(tail, suffix)) { return { text: markdown, blocks: [ @@ -510,8 +670,16 @@ export function projectMarkdownStream( src: tail.src + suffix, }, ], + sourceBlocks: previous.sourceBlocks, + referenceDefinitions: previous.referenceDefinitions, } } - return { text: markdown, blocks: splitMarkdownStream(markdown, isStreaming) } + // 只需要重解析最后一个源块;不稳定时退回全量 + return ( + projectTail(previous, markdown, isStreaming) ?? { + text: markdown, + ...splitMarkdownStreamDetailed(markdown, isStreaming), + } + ) } diff --git a/src/components/mermaidRenderCache.ts b/src/components/mermaidRenderCache.ts index a176cdb2f..174fbdfea 100644 --- a/src/components/mermaidRenderCache.ts +++ b/src/components/mermaidRenderCache.ts @@ -1,6 +1,14 @@ +import { BoundedCache } from '../utils/boundedCache' + const MERMAID_CACHE_MAX = 64 +/** SVG 体积差很多,单纯按条数会留下几十张超大图 */ +const MERMAID_CACHE_MAX_CHARS = 4 * 1024 * 1024 -const svgCache = new Map() +const svgCache = new BoundedCache({ + maxEntries: MERMAID_CACHE_MAX, + maxCost: MERMAID_CACHE_MAX_CHARS, + costOf: svg => svg.length, +}) const pendingRenders = new Map>() let renderQueue: Promise = Promise.resolve() @@ -8,19 +16,19 @@ export function getCachedMermaidSvg(key: string) { return svgCache.get(key) } +function rememberSvg(key: string, svg: string) { + svgCache.set(key, svg) +} + export async function getOrRenderMermaidSvg(key: string, render: () => Promise) { - const cached = svgCache.get(key) + const cached = getCachedMermaidSvg(key) if (cached !== undefined) return cached const pending = pendingRenders.get(key) if (pending) return pending const promise = renderQueue.then(render, render).then(svg => { - if (svgCache.size >= MERMAID_CACHE_MAX) { - const firstKey = svgCache.keys().next().value - if (firstKey !== undefined) svgCache.delete(firstKey) - } - svgCache.set(key, svg) + rememberSvg(key, svg) return svg }) renderQueue = promise.then( diff --git a/src/components/streamFade.test.ts b/src/components/streamFade.test.ts new file mode 100644 index 000000000..b25e03af0 --- /dev/null +++ b/src/components/streamFade.test.ts @@ -0,0 +1,79 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + appendStreamingTextWithFade, + createStreamFadeState, + resetStreamFade, + STREAM_FADE_DURATION_MS, +} from './streamFade' + +const originalAnimate = Element.prototype.animate + +describe('streamFade', () => { + beforeEach(() => { + vi.useFakeTimers() + Object.defineProperty(Element.prototype, 'animate', { + configurable: true, + writable: true, + value: vi.fn(() => ({ cancel: vi.fn() })), + }) + }) + + afterEach(() => { + vi.useRealTimers() + if (originalAnimate) { + Object.defineProperty(Element.prototype, 'animate', { + configurable: true, + writable: true, + value: originalAnimate, + }) + } else { + // @ts-expect-error jsdom 默认没有 WAAPI + delete Element.prototype.animate + } + }) + + it('新追加的一段先包成 span,动画结束后并回文本', () => { + const root = document.createElement('div') + root.innerHTML = '

    hello

    ' + const paragraph = root.querySelector('p')! + const state = createStreamFadeState() + + expect(appendStreamingTextWithFade(root, ' world', state)).toBe(true) + const span = paragraph.querySelector('span') + expect(span).toHaveTextContent('world') + expect(Element.prototype.animate).toHaveBeenCalledTimes(1) + + vi.advanceTimersByTime(STREAM_FADE_DURATION_MS + 50) + expect(paragraph.querySelector('span')).toBeNull() + expect(paragraph).toHaveTextContent('hello world') + }) + + it('连续追加的 span 会按顺序合并成一个文本节点', () => { + const root = document.createElement('div') + root.innerHTML = '

    a

    ' + const paragraph = root.querySelector('p')! + const state = createStreamFadeState() + + appendStreamingTextWithFade(root, 'b', state) + appendStreamingTextWithFade(root, 'c', state) + vi.advanceTimersByTime(STREAM_FADE_DURATION_MS + 50) + + expect(paragraph.querySelector('span')).toBeNull() + expect(paragraph.textContent).toBe('abc') + expect(paragraph.childNodes).toHaveLength(1) + }) + + it('reset 会清掉待处理定时器', () => { + const root = document.createElement('div') + root.innerHTML = '

    a

    ' + const state = createStreamFadeState() + + appendStreamingTextWithFade(root, 'b', state) + expect(state.timers.size).toBe(1) + resetStreamFade(state) + expect(state.timers.size).toBe(0) + + vi.advanceTimersByTime(STREAM_FADE_DURATION_MS + 50) + expect(root.querySelector('span')).not.toBeNull() + }) +}) diff --git a/src/components/streamFade.ts b/src/components/streamFade.ts new file mode 100644 index 000000000..4ee9121e1 --- /dev/null +++ b/src/components/streamFade.ts @@ -0,0 +1,106 @@ +/** + * 流式文本的尾部淡入。 + * + * 不逐字符建 span(长文本会爆炸),而是每个揭示节拍给新追加的一段包一个 + * 短命 span,做 200ms 透明度动画,结束后并回普通文本节点。 + * 这样同时最多只有几个 span,长回答也不会把 DOM 撑大。 + */ +import { prefersReducedMotion } from '../utils/motion' + +export const STREAM_FADE_DURATION_MS = 200 +const FADE_FROM_OPACITY = 0.35 +const FADE_CLEANUP_DELAY_MS = 30 +const APPENDABLE_PARENT = /^(P|LI|TD|TH|H[1-6]|BLOCKQUOTE|DIV)$/ + +export interface StreamFadeState { + parent: HTMLElement | null + anchor: Node | null + timers: Set +} + +export function createStreamFadeState(): StreamFadeState { + return { parent: null, anchor: null, timers: new Set() } +} + +export function resetStreamFade(state: StreamFadeState): void { + for (const timer of state.timers) window.clearTimeout(timer) + state.timers.clear() + state.parent = null + state.anchor = null +} + +function canAnimate(): boolean { + return typeof Element !== 'undefined' && typeof (Element.prototype as { animate?: unknown }).animate === 'function' +} + +function resolveAnchor(root: HTMLElement, state: StreamFadeState): { parent: HTMLElement; anchor: Node } | null { + if ( + state.parent && + root.contains(state.parent) && + state.anchor && + state.anchor.parentNode === state.parent && + state.parent.lastChild === state.anchor + ) { + return { parent: state.parent, anchor: state.anchor } + } + + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT) + let last: Text | null = null + let node = walker.nextNode() + while (node) { + last = node as Text + node = walker.nextNode() + } + if (!last) return null + + const parent = last.parentElement + if (!parent || !APPENDABLE_PARENT.test(parent.tagName) || parent.lastChild !== last) return null + + state.parent = parent + state.anchor = last + return { parent, anchor: last } +} + +function finalizeSpan(span: HTMLSpanElement, state: StreamFadeState): void { + const parent = span.parentNode + if (!parent) return + const previous = span.previousSibling + const text = document.createTextNode(span.textContent ?? '') + span.replaceWith(text) + if (state.anchor === span) state.anchor = text + + if (previous && previous.nodeType === Node.TEXT_NODE) { + const previousText = previous as Text + previousText.appendData(text.data) + text.remove() + if (state.anchor === text) state.anchor = previousText + } +} + +/** + * 把一段新文本以淡入方式追加到 live 块的末尾。 + * 返回 false 表示当前环境/结构不适合做动画,调用方应回退到普通文本追加。 + */ +export function appendStreamingTextWithFade(root: HTMLElement, suffix: string, state: StreamFadeState): boolean { + if (!suffix || !canAnimate() || prefersReducedMotion()) return false + const resolved = resolveAnchor(root, state) + if (!resolved) return false + + const span = document.createElement('span') + span.textContent = suffix + resolved.parent.appendChild(span) + state.anchor = span + + span.animate( + [{ opacity: FADE_FROM_OPACITY }, { opacity: 1 }], + { duration: STREAM_FADE_DURATION_MS, easing: 'ease-out', fill: 'none' }, + ) + + const timer = window.setTimeout(() => { + state.timers.delete(timer) + // 全量 parse 可能已经把 span 整个换掉 + if (span.parentNode) finalizeSpan(span, state) + }, STREAM_FADE_DURATION_MS + FADE_CLEANUP_DELAY_MS) + state.timers.add(timer) + return true +} diff --git a/src/components/streamPacing.test.ts b/src/components/streamPacing.test.ts new file mode 100644 index 000000000..814391b90 --- /dev/null +++ b/src/components/streamPacing.test.ts @@ -0,0 +1,164 @@ +import { describe, expect, it, afterEach, vi } from 'vitest' +import { act, renderHook } from '@testing-library/react' +import { + DEFAULT_STREAM_PACING, + safeRevealIndex, + stepStreamPacing, + usePacedStreamContent, + type StreamPacingConfig, +} from './streamPacing' + +/** 模拟持续按固定节拍推进,返回揭示到 target 所需的总时长 */ +function revealDuration(target: number, tickMs = 32, config: Partial = {}) { + let revealed = 0 + let rate = 0 + let elapsed = 0 + for (let guard = 0; guard < 10_000; guard += 1) { + const step = stepStreamPacing(target, revealed, rate, tickMs, config) + revealed = step.revealed + rate = step.rate + elapsed += tickMs + if (step.settled) return elapsed + } + throw new Error('pacing did not settle') +} + +describe('stepStreamPacing', () => { + it('settles immediately when nothing is pending', () => { + expect(stepStreamPacing(10, 10, 120, 32)).toEqual({ + revealed: 10, + rate: 0, + settled: true, + jumped: false, + }) + }) + + it('reveals a small append within roughly one window', () => { + const duration = revealDuration(40) + expect(duration).toBeLessThanOrEqual(700) + expect(duration).toBeGreaterThan(0) + }) + + it('keeps a burst within the reveal window instead of dumping it at once', () => { + const target = 300 + const first = stepStreamPacing(target, 0, 0, 32) + // 第一拍不能直接铺满,否则等于没有节奏 + expect(first.revealed).toBeGreaterThan(0) + expect(first.revealed).toBeLessThan(target) + + const duration = revealDuration(target) + // 目标 450ms 内揭示完,缓动收尾会略长一点 + expect(duration).toBeGreaterThanOrEqual(320) + expect(duration).toBeLessThanOrEqual(900) + }) + + it('caps catch-up speed for a long burst', () => { + const step = stepStreamPacing(2000, 0, 0, 32) + const revealedInOneTick = step.revealed + // 上限 600 字符/秒,单拍 32ms 最多推进约 19.2 字符 + expect(revealedInOneTick).toBeLessThanOrEqual(DEFAULT_STREAM_PACING.maxCharsPerSecond * 0.032 + 0.001) + }) + + it('never advances slower than the minimum rate while catching up', () => { + const step = stepStreamPacing(10, 0, 0, 32) + expect(step.revealed).toBeGreaterThanOrEqual(DEFAULT_STREAM_PACING.minCharsPerSecond * 0.032 - 0.001) + }) + + it('jumps to the target when the backlog is too large', () => { + const step = stepStreamPacing(DEFAULT_STREAM_PACING.jumpLagChars + 1, 0, 100, 32) + expect(step.jumped).toBe(true) + expect(step.settled).toBe(true) + expect(step.revealed).toBe(DEFAULT_STREAM_PACING.jumpLagChars + 1) + }) + + it('clamps an oversized elapsed time so a background tab does not overshoot', () => { + const step = stepStreamPacing(200, 0, 0, 10_000) + expect(step.revealed).toBeLessThanOrEqual( + (DEFAULT_STREAM_PACING.maxCharsPerSecond * DEFAULT_STREAM_PACING.maxStepMs) / 1000, + ) + }) + + it('eases the rate down when the backlog shrinks', () => { + let rate = 600 + let revealed = 0 + const target = 60 + let previousRate = rate + for (let tick = 0; tick < 20; tick += 1) { + const step = stepStreamPacing(target, revealed, rate, 32) + revealed = step.revealed + rate = step.rate + expect(rate).toBeLessThanOrEqual(previousRate + 1e-9) + previousRate = rate + if (step.settled) break + } + }) +}) + +describe('safeRevealIndex', () => { + it('clamps to the text bounds', () => { + expect(safeRevealIndex('abc', -1)).toBe(0) + expect(safeRevealIndex('abc', 99)).toBe(3) + }) + + it('does not split a surrogate pair', () => { + const text = 'a😀b' + // 😀 占用索引 1、2,切在 2 会把它劈成两半 + expect(safeRevealIndex(text, 2)).toBe(1) + expect(safeRevealIndex(text, 3)).toBe(3) + }) + + it('keeps ordinary CJK boundaries untouched', () => { + expect(safeRevealIndex('你好世界', 2)).toBe(2) + }) + + it('does not leave a dangling carriage return before a line feed', () => { + expect(safeRevealIndex('line\r\nnext', 5)).toBe(4) + }) +}) + +describe('usePacedStreamContent', () => { + afterEach(() => { + vi.useRealTimers() + }) + + it('reveals an append over time instead of showing it in one frame', () => { + vi.useFakeTimers() + const { result, rerender } = renderHook( + ({ content, enabled }: { content: string; enabled: boolean }) => usePacedStreamContent(content, enabled), + { initialProps: { content: '你好', enabled: true } }, + ) + + expect(result.current).toBe('你好') + rerender({ content: '你好世界,欢迎回来', enabled: true }) + expect(result.current).toBe('你好') + + act(() => { + vi.advanceTimersByTime(400) + }) + expect(result.current).toBe('你好世界,欢迎回来') + }) + + it('snaps immediately when the stream ends', () => { + vi.useFakeTimers() + const { result, rerender } = renderHook( + ({ content, enabled }: { content: string; enabled: boolean }) => usePacedStreamContent(content, enabled), + { initialProps: { content: 'a', enabled: true } }, + ) + + rerender({ content: 'a much longer tail that would otherwise be paced', enabled: true }) + expect(result.current).toBe('a') + + rerender({ content: 'a much longer tail that would otherwise be paced', enabled: false }) + expect(result.current).toBe('a much longer tail that would otherwise be paced') + }) + + it('snaps when the content is replaced rather than extended', () => { + const { result, rerender } = renderHook( + ({ content }: { content: string }) => usePacedStreamContent(content, true), + { initialProps: { content: 'first version' } }, + ) + + rerender({ content: 'a completely different version' }) + expect(result.current).toBe('a completely different version') + }) +}) diff --git a/src/components/streamPacing.ts b/src/components/streamPacing.ts new file mode 100644 index 000000000..4596d28d2 --- /dev/null +++ b/src/components/streamPacing.ts @@ -0,0 +1,201 @@ +/** + * 流式文本的显示节奏。 + * + * 网络到达是突发的:一个 chunk 可能带来几十上百个字符,直接上屏就是整段 + * 跳出来。这里把「到达速率」和「显示速率」拆开,按固定节奏推进,积压多了 + * 加速追赶,追上了回到目标速率,屏幕上始终是连续出字。 + * + * 纯函数部分与 React 解耦,方便单独验证节奏曲线。 + */ +import { useCallback, useEffect, useRef, useState } from 'react' +import { prefersReducedMotion } from '../utils/motion' + +export interface StreamPacingConfig { + /** 目标:把当前积压揭示完的时间 */ + revealWithinMs: number + /** 最低揭示速率(字符/秒) */ + minCharsPerSecond: number + /** 最高揭示速率(字符/秒) */ + maxCharsPerSecond: number + /** 速率变化缓动,避免起步/追赶时速率突变 */ + easingMs: number + /** 单次推进的最大时间片,避免后台切回时一次冲过头 */ + maxStepMs: number + /** 积压超过这个字符数就直接补齐,不再逐字追 */ + jumpLagChars: number +} + +export const DEFAULT_STREAM_PACING: StreamPacingConfig = { + revealWithinMs: 450, + minCharsPerSecond: 80, + maxCharsPerSecond: 600, + easingMs: 250, + maxStepMs: 100, + jumpLagChars: 2400, +} + +/** 两次提交之间的最小间隔,约等于 30fps */ +const MIN_COMMIT_MS = 32 + +export interface StreamPacingStep { + /** 推进后的已揭示字符数(浮点,提交时再取整) */ + revealed: number + /** 当前速率(字符/秒) */ + rate: number + /** 是否已经追平 */ + settled: boolean + /** 是否因为积压过大直接补齐 */ + jumped: boolean +} + +function clamp(value: number, min: number, max: number) { + return Math.min(Math.max(value, min), max) +} + +/** + * 推进一个显示节拍。 + * + * @param target 目标字符数(已经到达的文本长度) + * @param revealed 当前已揭示字符数 + * @param rate 当前速率(字符/秒),首次推进传 0 + * @param elapsedMs 距上次推进的毫秒数 + */ +export function stepStreamPacing( + target: number, + revealed: number, + rate: number, + elapsedMs: number, + config: Partial = {}, +): StreamPacingStep { + const cfg = { ...DEFAULT_STREAM_PACING, ...config } + + if (target <= revealed) { + return { revealed: target, rate: 0, settled: true, jumped: false } + } + + const lag = target - revealed + if (lag > cfg.jumpLagChars) { + return { revealed: target, rate: 0, settled: true, jumped: true } + } + + const dt = Math.max(0, Math.min(Number.isFinite(elapsedMs) ? elapsedMs : 0, cfg.maxStepMs)) + const revealWindow = Math.max(cfg.revealWithinMs, 1) / 1000 + const desired = clamp(lag / revealWindow, cfg.minCharsPerSecond, cfg.maxCharsPerSecond) + + // 起始没有上一拍速率时直接采用目标速率;之后按时间常数缓动 + const nextRate = rate > 0 && cfg.easingMs > 0 ? rate + (desired - rate) * (1 - Math.exp(-dt / cfg.easingMs)) : desired + + const next = revealed + (nextRate * dt) / 1000 + if (next >= target) { + return { revealed: target, rate: 0, settled: true, jumped: false } + } + return { revealed: next, rate: nextRate, settled: false, jumped: false } +} + +/** + * 截断位置不能落在代理对中间,否则 emoji / 生僻字会短暂显示成半个字符。 + */ +export function safeRevealIndex(text: string, index: number): number { + if (index <= 0) return 0 + if (index >= text.length) return text.length + // CRLF 当成一个整体,避免流式中出现悬空的 \r 被解析成额外换行 + if (text.charCodeAt(index - 1) === 13 && text.charCodeAt(index) === 10) return index - 1 + const code = text.charCodeAt(index) + if (code >= 0xdc00 && code <= 0xdfff) { + const previous = text.charCodeAt(index - 1) + if (previous >= 0xd800 && previous <= 0xdbff) return index - 1 + } + return index +} + +/** + * 把目标文本按节奏揭示。`enabled` 为 false、系统要求减少动效、或内容不是 + * 上一次的前缀扩展时,直接展示全文(流结束、重新生成、编辑都走这条路)。 + */ +export function usePacedStreamContent(content: string, enabled: boolean): string { + const [displayed, setDisplayed] = useState(content) + const displayedRef = useRef(content) + const targetRef = useRef(content) + const revealedRef = useRef(content.length) + const rateRef = useRef(0) + const rafRef = useRef(null) + const lastTickRef = useRef(0) + + const stop = useCallback(() => { + if (rafRef.current !== null) cancelAnimationFrame(rafRef.current) + rafRef.current = null + lastTickRef.current = 0 + }, []) + + const commit = useCallback((text: string) => { + displayedRef.current = text + setDisplayed(text) + }, []) + + useEffect(() => { + const target = content + targetRef.current = target + + if (!enabled || prefersReducedMotion() || !target.startsWith(displayedRef.current)) { + stop() + rateRef.current = 0 + revealedRef.current = target.length + // 内容被替换 / 流结束 / 关闭动效时直接对齐:这是外部数据同步, + // 不是可以由渲染推导出来的状态 + // eslint-disable-next-line react-hooks/set-state-in-effect + if (displayedRef.current !== target) commit(target) + return + } + + if (target.length <= revealedRef.current) { + if (displayedRef.current !== target) { + revealedRef.current = target.length + commit(target) + } + return + } + + // 已经有循环在跑时只更新目标,由循环读取最新的 targetRef + if (rafRef.current !== null) return + + lastTickRef.current = 0 + const tick = (timestamp: number) => { + rafRef.current = null + const elapsed = lastTickRef.current > 0 ? timestamp - lastTickRef.current : MIN_COMMIT_MS + if (lastTickRef.current > 0 && elapsed < MIN_COMMIT_MS) { + rafRef.current = requestAnimationFrame(tick) + return + } + lastTickRef.current = timestamp + + const live = targetRef.current + if (!enabled || !live.startsWith(displayedRef.current)) { + rateRef.current = 0 + revealedRef.current = live.length + commit(live) + return + } + + const step = stepStreamPacing(live.length, revealedRef.current, rateRef.current, elapsed) + rateRef.current = step.rate + revealedRef.current = step.revealed + + const cut = safeRevealIndex(live, Math.floor(step.revealed)) + const next = cut >= live.length ? live : live.slice(0, cut) + if (next !== displayedRef.current) commit(next) + + if (step.settled) { + rateRef.current = 0 + lastTickRef.current = 0 + return + } + rafRef.current = requestAnimationFrame(tick) + } + + rafRef.current = requestAnimationFrame(tick) + }, [commit, content, enabled, stop]) + + useEffect(() => stop, [stop]) + + return displayed +} diff --git a/src/components/ui/CopyButton.tsx b/src/components/ui/CopyButton.tsx index 9a9515ee1..2f908bf74 100644 --- a/src/components/ui/CopyButton.tsx +++ b/src/components/ui/CopyButton.tsx @@ -4,7 +4,8 @@ import { clsx } from 'clsx' import { clipboardErrorHandler, copyTextToClipboard } from '../../utils' interface CopyButtonProps { - text: string + /** 字符串,或点击时才取值的 getter(流式长消息避免每帧拼接全文) */ + text: string | (() => string) className?: string position?: 'absolute' | 'static' /** 用于指定 group 名称,默认响应任意父级 group */ @@ -28,7 +29,7 @@ export function CopyButton({ text, className, position = 'absolute', groupName } async (e: React.MouseEvent) => { e.stopPropagation() // Prevent triggering parent clicks try { - await copyTextToClipboard(text) + await copyTextToClipboard(typeof text === 'function' ? text() : text) setCopied(true) // 清理之前的 timeout if (timeoutRef.current) { diff --git a/src/components/ui/SmoothHeight.tsx b/src/components/ui/SmoothHeight.tsx index a66c001e0..691c2a4dd 100644 --- a/src/components/ui/SmoothHeight.tsx +++ b/src/components/ui/SmoothHeight.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef } from 'react' +import { prefersReducedMotion } from '../../utils/motion' /** * SmoothHeight - 内容高度变化时平滑过渡 @@ -25,7 +26,7 @@ export function SmoothHeight({ useEffect(() => { const outer = outerRef.current const inner = innerRef.current - if (!outer || !inner || !isActive) { + if (!outer || !inner || !isActive || prefersReducedMotion()) { if (outer) { outer.style.height = '' outer.style.clipPath = '' diff --git a/src/features/chat/ChatArea.test.ts b/src/features/chat/ChatArea.test.ts index 7ee893140..c4e485548 100644 --- a/src/features/chat/ChatArea.test.ts +++ b/src/features/chat/ChatArea.test.ts @@ -293,10 +293,28 @@ describe('buildChatPageViewModel', () => { expect(next.visibleMessages[1]).toBe(first.visibleMessages[1]) expect(next.visibleMessages.at(-1)).not.toBe(first.visibleMessages.at(-1)) expect(next.pageRecords[1]).toBe(first.pageRecords[1]) + expect(next.outlineSourceEntries).toBe(first.outlineSourceEntries) + expect(next.outlineOwnerByMessageId).toBe(first.outlineOwnerByMessageId) expect(next.forkTargetIdMap).toBe(first.forkTargetIdMap) expect(next.turnDurationMap).toBe(first.turnDurationMap) }) + it('rebuilds the outline only when user text changes', () => { + const user = { ...createUserMessage('user-1', 1), text: 'first prompt' } + const assistant = createAssistantMessage('assistant-1', [createTextPart('text-1', 'assistant-1', 'answer')], 2, 3) + const first = buildChatPageViewModel([user, assistant]) + + const restreamed = buildChatPageViewModel( + [user, createAssistantMessage('assistant-1', [createTextPart('text-1', 'assistant-1', 'answer more')], 2, 3)], + first, + ) + expect(restreamed.outlineSourceEntries).toBe(first.outlineSourceEntries) + + const edited = buildChatPageViewModel([{ ...user, text: 'edited prompt' }, assistant], restreamed) + expect(edited.outlineSourceEntries).not.toBe(first.outlineSourceEntries) + expect(edited.outlineSourceEntries[0].title).toBe('edited prompt') + }) + it('keeps existing page keys stable when appending a new turn', () => { const messages = Array.from({ length: 8 }, (_unused, index) => [ { diff --git a/src/features/chat/ChatArea.tsx b/src/features/chat/ChatArea.tsx index 369b91467..56e66e7a9 100644 --- a/src/features/chat/ChatArea.tsx +++ b/src/features/chat/ChatArea.tsx @@ -20,7 +20,7 @@ import { useMemo, useState, } from 'react' -import { useVirtualizer, elementScroll, defaultRangeExtractor, type VirtualItem } from '@tanstack/react-virtual' +import { useVirtualizer, elementScroll, type VirtualItem } from '@tanstack/react-virtual' import { useTranslation } from 'react-i18next' import { MessageRenderer, ProcessCollapseBlock, messageHasFinalContent, messageHasProcessContent } from '../message' import { MessageErrorView } from '../message/parts' @@ -48,7 +48,24 @@ import { type TurnDiffInfo, } from './chatPageModel' import { useTheme } from '../../hooks/useTheme' -import { getStreamingHotIndexes, getTimelineRowYClass, mergeVirtualRangeIndexes } from './chatAreaUtils' +import { measurePerf } from '../../utils/perfTrace' +import { createFrameSampler, reportFrameStats } from '../../utils/frameSampler' +import { + getStreamingHotIndexes, + getTimelineRowYClass, + mergeVirtualRangeIndexes, + nextPrependAdjustment, + pickPrependAnchor, +} from './chatAreaUtils' +import { + buildCachedSizeMap, + estimateTimelineItemSize, + estimateTimelineTotalHeight, + readSessionMeasurements, + restoreMeasurements, + sessionCacheKey, + writeSessionMeasurements, +} from './timelineMetrics' import { useAutoScroll } from './virtual/useAutoScroll' import { useEmptyWorkingShellGate } from './virtual/useEmptyWorkingShellGate' @@ -57,34 +74,14 @@ function isAssistantStreaming(message: SessionMessageInfo): boolean { return isAssistantMessage(message) && message.time.completed == null } -const ROW_ESTIMATE = 60 -/** 过程壳 header 行高(Working / Worked 一行) */ -const PROCESS_SHELL_HEADER = 36 /** 用户入场生长结束后,空 Working 壳再等多久(有 assistant 则立刻挂,不等) */ const EMPTY_WORKING_SHELL_EXTRA_DELAY_MS = 500 const DEFAULT_BOTTOM_SPACER = 256 -const SESSION_CACHE_LIMIT = 16 const EMPTY_QUEUE: QueuedUserPrompt[] = [] const EMPTY_COMPACTIONS: QueuedCompaction[] = [] const bottomSpacerHeight = (bottomPadding: number) => (bottomPadding > 0 ? bottomPadding + 48 : DEFAULT_BOTTOM_SPACER) -function estimateTimelineItemSize(item: ProcessTimelineItem | undefined): number { - if (!item) return ROW_ESTIMATE - if (item.kind === 'message') return ROW_ESTIMATE - // 进行中默认展开:header + 壳内消息(空回合至少占 header) - if (item.isActive) { - const body = Math.max(item.children.length, 1) * ROW_ESTIMATE - return PROCESS_SHELL_HEADER + body - } - // 结束后默认折叠:只估 header + 壳外 final,避免刷新时 120→36 的假高度再回弹 - return PROCESS_SHELL_HEADER + (item.finalMessage ? ROW_ESTIMATE : 0) -} - -function sessionCacheKey(sessionId: string, processCollapseEnabled: boolean): string { - return `${sessionId}:${processCollapseEnabled ? 'process' : 'flat'}` -} - // ─── 接口定义(保持不变) ─────────────────────────────────────── interface ChatAreaProps { @@ -172,12 +169,18 @@ const MessageBody = memo(function MessageBody({ onEntryGrowComplete, }: MessageBodyProps) { const messageId = message.id + const registerNode = useCallback( + (node: HTMLDivElement | null) => { + registerMessage?.(messageId, node) + }, + [messageId, registerMessage], + ) const isUser = isUserMessage(message) // undo 边界:用户消息,或 v2 的独立压缩消息(revert.stage 接受任意 messageID) const undoable = isUser || message.type === 'compaction' return (
    registerMessage?.(messageId, node as HTMLDivElement | null)} + ref={registerNode} data-message-id={messageId} data-anchor-source-id={forkMessageId ?? messageId} > @@ -364,10 +367,6 @@ const VirtualRow = memo( prev.onEntryGrowComplete === next.onEntryGrowComplete, ) -// ─── 会话缓存(LRU 16) ─────────────────────────────────────── - -const sessionCache = new Map() - // ─── ChatArea ──────────────────────────────────────────────── export const ChatArea = memo( @@ -450,16 +449,22 @@ export const ChatArea = memo( items?: ProcessTimelineItem[] }>({ processCollapseEnabled }) const timeline = useMemo(() => { - const next = !processCollapseEnabled - ? buildFlatTimeline(visibleMessages, isStreaming, showTurnDiff) - : buildProcessTimeline(visibleMessages, { - turnDurationMap, - sessionIsStreaming: isStreaming, - messageHasProcess: messageHasProcessContent, - messageHasFinal: messageHasFinalContent, - isUserEntryReady: emptyShellGate.isReady, - turnDiff: showTurnDiff, - }) + const next = measurePerf( + 'chat.timeline', + () => + !processCollapseEnabled + ? buildFlatTimeline(visibleMessages, isStreaming, showTurnDiff) + : buildProcessTimeline(visibleMessages, { + turnDurationMap, + sessionIsStreaming: isStreaming, + messageHasProcess: messageHasProcessContent, + messageHasFinal: messageHasFinalContent, + isUserEntryReady: emptyShellGate.isReady, + turnDiff: showTurnDiff, + }), + 4, + `${visibleMessages.length} rows`, + ) const previous = previousTimelineRef.current.processCollapseEnabled === processCollapseEnabled ? previousTimelineRef.current.items @@ -496,6 +501,18 @@ export const ChatArea = memo( // ── Refs(避免闭包过期) ── const scrollRef = useRef(null) const contentRef = useRef(null) + /** 已写入容器的总高度,避免重复写同一个值 */ + const appliedContentHeightRef = useRef(-1) + /** + * 容器总高 = 全部条目之和(含未渲染条目的估算)。 + * 必须跟着尺寸/条数变化同步:只在 scrollToFn 里写会让 scrollHeight 停在旧值, + * 贴底时算出的 max 偏小,滚动条长度也不对。 + */ + const writeContentHeight = useCallback((height: number) => { + if (Math.abs(height - appliedContentHeightRef.current) < 0.5) return + appliedContentHeightRef.current = height + if (contentRef.current) contentRef.current.style.height = `${height}px` + }, []) const sessionIdRef = useRef(sessionId) sessionIdRef.current = sessionId const onLoadMoreRef = useRef(onLoadMore) @@ -568,35 +585,66 @@ export const ChatArea = memo( // parent key={sessionId} remount 后,这里只在 mount 时读一次 cache // cache key 必须带过程折叠模式:flat 与 process 的 item key/高度完全不同 const cacheKey = sessionId ? sessionCacheKey(sessionId, processCollapseEnabled) : null - const initialCacheRef = useRef(cacheKey ? sessionCache.get(cacheKey)?.measurements : undefined) - const coldBottomMount = !initialCacheRef.current?.length - const [renderOverscan, setRenderOverscan] = useState(initialCacheRef.current?.length || coldBottomMount ? 6 : 15) + const initialCacheRef = useRef(cacheKey ? readSessionMeasurements(cacheKey) : undefined) + const cachedSizeByKey = useMemo( + () => buildCachedSizeMap(initialCacheRef.current), + // 只在 mount 读一次 + // eslint-disable-next-line react-hooks/exhaustive-deps + [], + ) + /** + * 视口外预渲染的高度预算,按视口高度的倍数算,而不是按行数。 + * + * 按行数会让短消息只预渲染不到一屏、长消息预渲染好几屏;按像素才能保证 + * 用户感知到的始终是「上下各两屏已经画好了」。首帧用小预算,两帧后放大, + * 避免冷启动一次挂太多。 + */ + const RENDER_BUFFER_RATIO = 2 + const RENDER_BUFFER_RATIO_FIRST_PAINT = 0.5 + const [renderBufferRatio, setRenderBufferRatio] = useState(RENDER_BUFFER_RATIO_FIRST_PAINT) + /** rangeExtractor 可能在 virtualizer 赋值前就被调用,用 holder 拿测量值避免暂时性死区 */ + const measurementsHolder = useRef | null>(null) const resizePinnedRef = useRef([]) const resizePinFrame = useRef(undefined) const resizeAnchorScheduled = useRef(false) + /** dev:上方行从估算修正为实测的累计幅度,用来判断估算模型够不够准 */ + const sizeDriftRef = useRef({ count: 0, px: 0, lastLog: 0 }) /** 流式热行 pin:ref 更新,不碰贴底/SSE 路径 */ const hotPinnedRef = useRef([]) hotPinnedRef.current = getStreamingHotIndexes(timeline.length, isStreaming) - // 冷启动估在底部:有 cache 用 cache 总高,否则 estimate*count + paddingEnd。 + // 流式期间的掉帧采样:只在 dev 里跑,结束时只在指标确实差时打一条警告 + useEffect(() => { + if (!import.meta.env.DEV || import.meta.env.MODE === 'test' || !isStreaming) return + const sampler = createFrameSampler() + sampler.start() + return () => reportFrameStats('chat.stream.jank', sampler.stop()) + }, [isStreaming]) + + // 恢复上一次会话测量值时按当前 timeline 的 key 重新取: + // 消息追加/删除后,旧快照里的绝对 start/end 已经不可信,只有 key→size 还有效。 + const initialMeasurementsCache = useMemo( + () => restoreMeasurements(initialCacheRef.current, timeline), + // 只在 mount 恢复一次 + // eslint-disable-next-line react-hooks/exhaustive-deps + [], + ) + + // 冷启动估在底部:已知 key 用真实高度,新消息用估算值重新累加。 + // 直接用缓存最后一条的 end 会在「缓存之后又来了新消息」时把初始位置算低。 // 不用 MAX_SAFE_INTEGER(单列 range 不会向前扩,只会渲染最后一项)。 - const estimatedBottomOffset = useMemo(() => { - const cached = initialCacheRef.current - if (cached?.length) { - const last = cached[cached.length - 1] - return Math.max(0, (last?.end ?? 0) + spacerHeight - 600) - } - const estimatedTotal = timeline.reduce((sum, item) => sum + estimateTimelineItemSize(item), 0) - return Math.max(0, estimatedTotal + spacerHeight - 600) + const estimatedBottomOffset = useMemo( + () => Math.max(0, estimateTimelineTotalHeight(timeline, cachedSizeByKey) + spacerHeight - 600), // 只在 mount 用初始 count 估一次 // eslint-disable-next-line react-hooks/exhaustive-deps - }, []) + [], + ) const virtualizer = useVirtualizer({ count: timeline.length, getScrollElement: () => scrollRef.current, initialOffset: estimatedBottomOffset, - initialMeasurementsCache: initialCacheRef.current, + initialMeasurementsCache, estimateSize: index => estimateTimelineItemSize(timeline[index]), getItemKey: i => timeline[i]?.key ?? `removed:${i}`, // 关键修复:同步重测(ref / layoutEffect,无 RO entry)必须读真实 DOM 高度。 @@ -615,7 +663,7 @@ export const ChatArea = memo( scrollEndThreshold: 80, // 预写 total height,避免浏览器把新 offset clamp 到旧高度(oc 同款) scrollToFn: (offset, options, instance) => { - if (contentRef.current) contentRef.current.style.height = `${instance.getTotalSize()}px` + writeContentHeight(instance.getTotalSize()) autoMarkAuto(scrollRef.current) elementScroll(offset, options, instance) }, @@ -625,12 +673,33 @@ export const ChatArea = memo( directDomUpdates: true, directDomUpdatesMode: 'transform', rangeExtractor: range => { - const indexes = defaultRangeExtractor({ ...range, overscan: renderOverscan }) + // 从可见范围向两侧按估算/实测高度累加,直到覆盖预算 + const viewport = scrollRef.current?.clientHeight || 800 + const budget = viewport * renderBufferRatio + const measurements = measurementsHolder.current + + let start = range.startIndex + let accumulated = 0 + while (start > 0 && accumulated < budget) { + start -= 1 + accumulated += measurements?.[start]?.size ?? 200 + } + + let end = range.endIndex + accumulated = 0 + while (end < range.count - 1 && accumulated < budget) { + end += 1 + accumulated += measurements?.[end]?.size ?? 200 + } + + const indexes: number[] = [] + for (let index = start; index <= end; index += 1) indexes.push(index) return mergeVirtualRangeIndexes(indexes, resizePinnedRef.current, hotPinnedRef.current) }, }) // 一次性 overrides(resizeItem + shouldAdjust)——对齐 oc + measurementsHolder.current = (virtualizer as any).measurementsCache const overridesApplied = useRef(false) if (!overridesApplied.current) { const origResize = virtualizer.resizeItem @@ -638,14 +707,34 @@ export const ChatArea = memo( const item = (virtualizer as any).measurementsCache[index] const prev = item ? ((virtualizer as any).itemSizeCache.get(item.key) ?? item.size) : undefined const root = scrollRef.current + + // dev 诊断:只看视口上方的行——它们的尺寸修正才会引发位置补偿 + if (import.meta.env.DEV && item && prev !== undefined && root) { + const drift = Math.abs(size - prev) + const offset = (virtualizer as any).getScrollOffset?.() ?? 0 + if (drift > 4 && item.end <= offset) { + const stats = sizeDriftRef.current + stats.count += 1 + stats.px += drift + const now = performance.now() + if (now - stats.lastLog > 2000) { + console.warn(`[perf] chat.rowResize count=${stats.count} px=${Math.round(stats.px)}`) + stats.count = 0 + stats.px = 0 + stats.lastLog = now + } + } + } if (root && prev !== undefined && Math.abs(size - prev) > root.clientHeight) { const view = root.getBoundingClientRect() - resizePinnedRef.current = [...root.querySelectorAll('[data-index]')] - .filter(el => { - const r = el.getBoundingClientRect() - return r.bottom > view.top && r.top < view.bottom + const container = contentRef.current + resizePinnedRef.current = Array.from(container?.children ?? []) + .filter((node): node is HTMLElement => node instanceof HTMLElement && node.hasAttribute('data-index')) + .filter(element => { + const rect = element.getBoundingClientRect() + return rect.bottom > view.top && rect.top < view.bottom }) - .map(el => Number(el.dataset.index)) + .map(element => Number(element.dataset.index)) if (resizePinFrame.current !== undefined) cancelAnimationFrame(resizePinFrame.current) resizePinFrame.current = requestAnimationFrame(() => { resizePinFrame.current = requestAnimationFrame(() => { @@ -673,6 +762,8 @@ export const ChatArea = memo( origResize(index, size) opts.anchorTo = origAnchor } + // 尺寸变了总高就变了:同步容器高度,贴底取 max 和滚动条才跟得上 + writeContentHeight(virtualizer.getTotalSize()) // 跟随中的贴底:绝对写底,不做 isAtEnd 门槛——shouldAnchorBottom() // 已经表达了跟随意图,>80px 的单帧突增(图片/代码块渲染)也必须追回。 if (root && shouldAnchorBottom() && !resizeAnchorScheduled.current) { @@ -690,11 +781,24 @@ export const ChatArea = memo( } virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item: VirtualItem, _delta: number, instance: any) => { if (shouldAnchorBottom()) return false - return item.end <= (instance.getScrollOffset?.() ?? 0) + (instance.scrollAdjustments ?? 0) + const offset = instance.getScrollOffset?.() ?? 0 + // 只补偿完全在视口上方的行:跨过顶边的行自身变高不会推动下面的内容 + if (item.end > offset + (instance.scrollAdjustments ?? 0)) return false + // 首次测量(还没有缓存尺寸)无论往哪滚都要补偿——否则估算和实测的 + // 差额会一直留在那里;只有「重新测量」在向上滚时跳过,避免 + // 一圈接一圈的尺寸修正把滚动顶得一跳一跳。 + const sized = instance.itemSizeCache?.has?.(item.key) ?? false + return !sized || instance.scrollDirection !== 'backward' } overridesApplied.current = true } + // 条数/结构变化(追加、前插、切换视图)都会改变总高,先同步一次; + // 单行尺寸变化走 resizeItem + useLayoutEffect(() => { + writeContentHeight(virtualizer.getTotalSize()) + }, [writeContentHeight, virtualizer, timeline]) + // ── 历史加载(prepend 锚点) ── const prependAnchor = useRef<{ key: string; offset: number } | undefined>(undefined) const prependFrame = useRef(undefined) @@ -713,32 +817,35 @@ export const ChatArea = memo( const root = scrollRef.current if (!root) return const view = root.getBoundingClientRect() - const anchor = [...root.querySelectorAll('[data-timeline-key]')] - .map(el => ({ el, rect: el.getBoundingClientRect() })) - .filter(x => x.rect.bottom > view.top && x.rect.top < view.bottom) - .sort((a, b) => a.rect.top - b.rect.top)[0] - if (anchor?.el.dataset.timelineKey) { - prependAnchor.current = { key: anchor.el.dataset.timelineKey, offset: anchor.rect.top - view.top } - } + // 只遍历已挂载的行(虚拟列表里就十来行),单次取最靠上的可见行 + const rows: Array<{ key?: string; top: number; bottom: number }> = [] + root.querySelectorAll('[data-timeline-key]').forEach(el => { + const rect = el.getBoundingClientRect() + rows.push({ key: el.dataset.timelineKey, top: rect.top, bottom: rect.bottom }) + }) + const next = pickPrependAnchor(rows, view.top, view.bottom) + if (next) prependAnchor.current = next }, []) const applyPrependAnchor = useCallback(() => { const root = scrollRef.current if (!root || !prependAnchor.current) return if (prependFrame.current !== undefined) cancelAnimationFrame(prependFrame.current) - let frames = 0, - stable = 0 + + let state = { frames: 0, stable: 0, expectedScrollTop: undefined as number | undefined } const apply = () => { prependFrame.current = undefined const a = prependAnchor.current if (!a) return + const el = root.querySelector(`[data-timeline-key="${CSS.escape(a.key)}"]`) const delta = el ? el.getBoundingClientRect().top - root.getBoundingClientRect().top - a.offset : undefined - if (delta !== undefined && Math.abs(delta) > 0.5) { - root.scrollTop += delta - stable = 0 - } else stable++ - if (++frames >= 180 || stable >= 30) { + const decision = nextPrependAdjustment(state, { scrollTop: root.scrollTop, delta }) + + if (decision.delta !== 0) root.scrollTop += decision.delta + state = { frames: decision.frames, stable: decision.stable, expectedScrollTop: root.scrollTop } + + if (decision.stop) { if (!prependLoading.current) prependAnchor.current = undefined return } @@ -820,6 +927,26 @@ export const ChatArea = memo( if (max - el.scrollTop >= 2) el.scrollTop = max }, [autoMarkAuto]) + // 流式期间每帧兜底:高度可能来自工具卡、输出文本、图片、展开面板…… + // 只靠某条 resizeItem 路径会漏;用户没离底时按绝对位置贴住, + // 离底后立刻停手,不会把人拽回去。 + useEffect(() => { + if (!isStreaming) return + let frame = 0 + const tick = () => { + const el = scrollRef.current + // 先判断意图再读高度:用户离底后连布局都不碰。 + // 只有真的需要补位才调 pinToBottom(它内部会 markAuto + 写 scrollTop)。 + if (el && !userScrolledRef.current) { + const max = Math.max(0, el.scrollHeight - el.clientHeight) + if (max - el.scrollTop >= 2) pinToBottom() + } + frame = requestAnimationFrame(tick) + } + frame = requestAnimationFrame(tick) + return () => cancelAnimationFrame(frame) + }, [isStreaming, pinToBottom]) + // ── 事件处理 ── const onScroll = useCallback(() => { if (prependLoading.current) updatePrependAnchor() @@ -896,7 +1023,7 @@ export const ChatArea = memo( if (shouldAnchorBottom()) pinToBottom() inner = requestAnimationFrame(() => { if (cancelled) return - if (renderOverscan < 15) setRenderOverscan(15) + if (renderBufferRatio < RENDER_BUFFER_RATIO) setRenderBufferRatio(RENDER_BUFFER_RATIO) if (shouldAnchorBottom()) pinToBottom() }) }) @@ -959,11 +1086,7 @@ export const ChatArea = memo( if (resizePinFrame.current !== undefined) cancelAnimationFrame(resizePinFrame.current) clearPrepend() if (!key) return - sessionCache.delete(key) - sessionCache.set(key, { measurements: virtualizer.takeSnapshot() }) - while (sessionCache.size > SESSION_CACHE_LIMIT) { - sessionCache.delete(sessionCache.keys().next().value!) - } + writeSessionMeasurements(key, virtualizer.takeSnapshot()) } }, [cacheKey, virtualizer, clearPrepend]) @@ -978,11 +1101,19 @@ export const ChatArea = memo( [items, timeline], ) - // Outline 可见消息:跟随虚拟行挂载变化 + // Outline 可见消息:observer 只建一次,虚拟范围变化时只补/撤观察目标。 + // 以前每次虚拟范围变化都新建 observer 并重新 observe 全部行,快速滚动时每帧都在重建。 + const outlineObserverRef = useRef<{ + observer: IntersectionObserver + visible: Set + targets: Set + } | null>(null) + useEffect(() => { const root = scrollRef.current - if (!root) return + if (!root || typeof IntersectionObserver === 'undefined') return const visible = new Set() + const targets = new Set() const observer = new IntersectionObserver( entries => { let changed = false @@ -1003,8 +1134,34 @@ export const ChatArea = memo( }, { root, rootMargin: '100% 0px' }, ) - root.querySelectorAll('[data-message-id]').forEach(el => observer.observe(el)) - return () => observer.disconnect() + const state = { observer, visible, targets } + outlineObserverRef.current = state + return () => { + observer.disconnect() + targets.clear() + if (outlineObserverRef.current === state) outlineObserverRef.current = null + } + }, []) + + useEffect(() => { + const state = outlineObserverRef.current + const root = scrollRef.current + if (!state || !root) return + const current = new Set(root.querySelectorAll('[data-message-id]')) + let changed = false + for (const element of state.targets) { + if (current.has(element)) continue + state.observer.unobserve(element) + state.targets.delete(element) + const id = element.getAttribute('data-message-id') + if (id && state.visible.delete(id)) changed = true + } + for (const element of current) { + if (state.targets.has(element)) continue + state.targets.add(element) + state.observer.observe(element) + } + if (changed) onVisibleIdsRef.current?.(Array.from(state.visible)) }, [mountedMessageIdsKey]) // ── 命令式接口 ── diff --git a/src/features/chat/ChatPane.tsx b/src/features/chat/ChatPane.tsx index cb9d7ba39..8366da663 100644 --- a/src/features/chat/ChatPane.tsx +++ b/src/features/chat/ChatPane.tsx @@ -82,6 +82,9 @@ interface ChatPaneProps { navigatePaneHome: (paneId: string) => void } +const EMPTY_STRING_ARRAY: string[] = [] +const EMPTY_BACKGROUND_TASKS: never[] = [] + // ============================================ // Compact viewport shell for split panes. // Layout/presentation stay fixed; enableCollapsedInputDock is inherited from the @@ -404,7 +407,7 @@ export const ChatPane = memo(function ChatPane({ }, [routeSessionId, currentTurnStartedAt]) const blockingBackgroundTasks = useMemo(() => { - if (!isStreaming || !routeSessionId) return [] + if (!isStreaming || !routeSessionId) return EMPTY_BACKGROUND_TASKS const { sessionId: rawSessionId } = splitSessionKey(routeSessionId) const merged = mergeRunningShells( findBlockingBackgroundTasks(messages), @@ -412,10 +415,12 @@ export const ChatPane = memo(function ChatPane({ rawSessionId ?? routeSessionId, { notBefore: currentTurnStartedAt }, ) + if (merged.length === 0) return EMPTY_BACKGROUND_TASKS if (movedBackgroundKeys.size === 0) return merged - return merged.filter( + const filtered = merged.filter( task => !movedBackgroundKeys.has(`${task.type}:${task.id}`) && !movedBackgroundKeys.has(`label:${task.label}`), ) + return filtered.length === 0 ? EMPTY_BACKGROUND_TASKS : filtered }, [isStreaming, routeSessionId, messages, runningShells, currentTurnStartedAt, movedBackgroundKeys]) const [backgroundMoving, setBackgroundMoving] = useState(false) @@ -1040,12 +1045,16 @@ export const ChatPane = memo(function ChatPane({ ], ) - const revertedMessage = inputRestoreContent - ? { - text: inputRestoreContent.text, - attachments: inputRestoreContent.attachments as Attachment[], - } - : undefined + const revertedMessage = useMemo( + () => + inputRestoreContent + ? { + text: inputRestoreContent.text, + attachments: inputRestoreContent.attachments as Attachment[], + } + : undefined, + [inputRestoreContent], + ) const fileCapabilities = useMemo( () => currentModel @@ -1058,6 +1067,49 @@ export const ChatPane = memo(function ChatPane({ : undefined, [currentModel], ) + const modelVariants = useMemo( + () => currentModel?.variants?.map(variant => variant.id) ?? EMPTY_STRING_ARRAY, + [currentModel], + ) + const handleMoveToBackgroundClick = useCallback(() => { + void handleMoveToBackground() + }, [handleMoveToBackground]) + // 这几块是 InputBox 的 props:对象每帧新建会让整个输入区跟着流失效 memo + const collapsedPermission = useMemo( + () => + visiblePermissionRequests.length > 0 && permissionCollapsed + ? { + label: t('chat:permissionDialog.permission', { + permission: visiblePermissionRequests[0].action, + }), + queueLength: visiblePermissionRequests.length, + onExpand: () => setPermissionCollapsed(false), + } + : undefined, + [permissionCollapsed, t, visiblePermissionRequests], + ) + const collapsedQuestion = useMemo( + () => + visiblePermissionRequests.length === 0 && visibleQuestionRequests.length > 0 && questionCollapsed + ? { + label: t('chat:questionDialog.title'), + queueLength: visibleQuestionRequests.length, + onExpand: () => setQuestionCollapsed(false), + } + : undefined, + [questionCollapsed, t, visiblePermissionRequests.length, visibleQuestionRequests], + ) + const collapsedWebsearch = useMemo( + () => + visibleWebsearchRequest && websearchCollapsed + ? { + label: t('chat:websearch.title'), + queueLength: 1, + onExpand: () => setWebsearchCollapsed(false), + } + : undefined, + [t, visibleWebsearchRequest, websearchCollapsed], + ) const handleScrollToBottom = useCallback(() => { chatAreaRef.current?.scrollToBottom() }, []) @@ -1178,7 +1230,7 @@ export const ChatPane = memo(function ChatPane({ agents={agents} selectedAgent={selectedAgent} onAgentChange={handleAgentChange} - variants={currentModel?.variants?.map(variant => variant.id) ?? []} + variants={modelVariants} selectedVariant={selectedVariant} onVariantChange={handleVariantChange} fileCapabilities={fileCapabilities} @@ -1197,7 +1249,7 @@ export const ChatPane = memo(function ChatPane({ busyDelivery={busyDelivery} onBusyDeliveryChange={setBusyDelivery} backgroundTasks={blockingBackgroundTasks} - onMoveToBackground={() => void handleMoveToBackground()} + onMoveToBackground={handleMoveToBackgroundClick} backgroundMoving={backgroundMoving} canRedo={canRedo} revertSteps={redoSteps} @@ -1208,35 +1260,9 @@ export const ChatPane = memo(function ChatPane({ isAtBottom={isAtBottom} showScrollToBottom={!isAtBottom} onScrollToBottom={handleScrollToBottom} - collapsedPermission={ - visiblePermissionRequests.length > 0 && permissionCollapsed - ? { - label: t('chat:permissionDialog.permission', { - permission: visiblePermissionRequests[0].action, - }), - queueLength: visiblePermissionRequests.length, - onExpand: () => setPermissionCollapsed(false), - } - : undefined - } - collapsedQuestion={ - visiblePermissionRequests.length === 0 && visibleQuestionRequests.length > 0 && questionCollapsed - ? { - label: t('chat:questionDialog.title'), - queueLength: visibleQuestionRequests.length, - onExpand: () => setQuestionCollapsed(false), - } - : undefined - } - collapsedWebsearch={ - visibleWebsearchRequest && websearchCollapsed - ? { - label: t('chat:websearch.title'), - queueLength: 1, - onExpand: () => setWebsearchCollapsed(false), - } - : undefined - } + collapsedPermission={collapsedPermission} + collapsedQuestion={collapsedQuestion} + collapsedWebsearch={collapsedWebsearch} /> {/* 输入框左缘拖拽把手(与对话列把手独立,各调各的宽度) */} {canAdjustChatWidth && paneWidth > 0 && ( diff --git a/src/features/chat/Header.tsx b/src/features/chat/Header.tsx index e60b7e0cd..2570c0f15 100644 --- a/src/features/chat/Header.tsx +++ b/src/features/chat/Header.tsx @@ -1,4 +1,4 @@ -import { useState, useRef, useEffect } from 'react' +import { memo, useState, useRef, useEffect } from 'react' import { useTranslation } from 'react-i18next' import { PanelRightIcon, @@ -198,7 +198,7 @@ function SessionTitleControl({ ) } -export function Header({ +export const Header = memo(function Header({ models, providers, modelsLoading, @@ -392,4 +392,4 @@ export function Header({ />
    ) -} +}) diff --git a/src/features/chat/InlineToolRequestContext.tsx b/src/features/chat/InlineToolRequestContext.tsx index 8a9878f76..8153ceacd 100644 --- a/src/features/chat/InlineToolRequestContext.tsx +++ b/src/features/chat/InlineToolRequestContext.tsx @@ -166,6 +166,11 @@ export function findQuestionRequestForTool( * rootSessionKey 提供时,未认领组只保留当前 session family 的请求—— * 别的会话的 pending 不该弹在这个 pane 上。 */ +const EMPTY_UNCLAIMED = { + permissions: [] as ApiPermissionRequest[], + questions: [] as ApiFormInfo[], +} + export function partitionUnclaimedRequests( messages: SessionMessageInfo[], pendingPermissions: ApiPermissionRequest[], @@ -173,6 +178,9 @@ export function partitionUnclaimedRequests( serverId: string, rootSessionKey?: string, ): { permissions: ApiPermissionRequest[]; questions: ApiFormInfo[] } { + // 没有待处理请求时不必扫全部消息与工具内容(流式每帧都会走到这里) + if (pendingPermissions.length === 0 && pendingQuestions.length === 0) return EMPTY_UNCLAIMED + const claimedPermissions = new Set() const claimedQuestions = new Set() diff --git a/src/features/chat/chatAreaUtils.test.ts b/src/features/chat/chatAreaUtils.test.ts index c6e53f7c0..6bb4338db 100644 --- a/src/features/chat/chatAreaUtils.test.ts +++ b/src/features/chat/chatAreaUtils.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { isChatAreaMountReady } from './chatAreaUtils' +import { isChatAreaMountReady, nextPrependAdjustment, pickPrependAnchor } from './chatAreaUtils' describe('isChatAreaMountReady', () => { it('首页(无会话)直接挂载', () => { @@ -25,3 +25,88 @@ describe('isChatAreaMountReady', () => { expect(isChatAreaMountReady({ hasSession: true, loadState: 'idle', messageCount: 0 })).toBe(false) }) }) + +describe('pickPrependAnchor', () => { + it('取视口内最靠上的可见行', () => { + const anchor = pickPrependAnchor( + [ + { key: 'a', top: -200, bottom: -40 }, // 完全在上方 + { key: 'b', top: -30, bottom: 20 }, // 跨过视口顶,最靠上 + { key: 'c', top: 40, bottom: 120 }, + { key: 'd', top: 500, bottom: 560 }, // 在下方 + ], + 0, + 400, + ) + + expect(anchor).toEqual({ key: 'b', offset: -30 }) + }) + + it('跳过没有 key 的行', () => { + const anchor = pickPrependAnchor( + [ + { top: -10, bottom: 30 }, + { key: 'c', top: 50, bottom: 90 }, + ], + 0, + 400, + ) + + expect(anchor).toEqual({ key: 'c', offset: 50 }) + }) + + it('没有可见行时返回 undefined', () => { + expect(pickPrependAnchor([{ key: 'a', top: 500, bottom: 600 }], 0, 400)).toBeUndefined() + }) +}) + +describe('nextPrependAdjustment', () => { + it('第一帧不看漂移,直接应用实测位移', () => { + const decision = nextPrependAdjustment( + { frames: 0, stable: 0 }, + { scrollTop: 120, delta: -40 }, + ) + + expect(decision).toEqual({ stop: false, delta: -40, frames: 1, stable: 0 }) + }) + + it('视口被外部改动时让位,不再写回', () => { + const decision = nextPrependAdjustment( + { frames: 1, stable: 0, expectedScrollTop: 100 }, + { scrollTop: 260, delta: 12 }, + ) + + expect(decision).toEqual({ stop: true, delta: 0, frames: 2, stable: 0 }) + }) + + it('位置连续稳定到上限就结束', () => { + const decision = nextPrependAdjustment( + { frames: 5, stable: 2, expectedScrollTop: 100 }, + { scrollTop: 100, delta: 0.2 }, + { stableFrames: 3 }, + ) + + expect(decision.stop).toBe(true) + expect(decision.delta).toBe(0) + }) + + it('跑满帧数上限就结束', () => { + const decision = nextPrependAdjustment( + { frames: 179, stable: 0, expectedScrollTop: 100 }, + { scrollTop: 100, delta: 8 }, + { maxFrames: 180 }, + ) + + expect(decision.stop).toBe(true) + expect(decision.delta).toBe(8) + }) + + it('锚点行还没渲染时计为稳定帧,不做位移', () => { + const decision = nextPrependAdjustment( + { frames: 0, stable: 0, expectedScrollTop: 10 }, + { scrollTop: 10, delta: undefined }, + ) + + expect(decision).toEqual({ stop: false, delta: 0, frames: 1, stable: 1 }) + }) +}) diff --git a/src/features/chat/chatAreaUtils.ts b/src/features/chat/chatAreaUtils.ts index 898d6fd31..a89eb3d3e 100644 --- a/src/features/chat/chatAreaUtils.ts +++ b/src/features/chat/chatAreaUtils.ts @@ -76,3 +76,84 @@ export function isChatAreaMountReady(params: { if (loadState === 'loaded' || loadState === 'error') return true return loadState === 'loading' && messageCount > 0 } + +export type PrependAnchor = { key: string; offset: number } + +export type PrependRowRect = { + key?: string + top: number + bottom: number +} + +/** + * 选历史前插的锚点:视口内最靠上的那一行。 + * + * 行 key 必须跨插入保持稳定(这里用 message.id)。锚点只记 key 和它相对视口顶的 + * 偏移,插入完成后按实测位移补偿 scrollTop——不依赖上方占位高度是多少。 + */ +export function pickPrependAnchor( + rows: readonly PrependRowRect[], + viewTop: number, + viewBottom: number, +): PrependAnchor | undefined { + let best: PrependRowRect | undefined + for (const row of rows) { + if (!row.key) continue + if (row.bottom <= viewTop || row.top >= viewBottom) continue + if (!best || row.top < best.top) best = row + } + return best?.key ? { key: best.key, offset: best.top - viewTop } : undefined +} + +export type PrependAdjustState = { + frames: number + stable: number + /** 上一帧写入后读回的 scrollTop;第一帧没有 */ + expectedScrollTop?: number +} + +export type PrependAdjustDecision = { + /** 放弃锚点:视口被用户/其它补偿接管,或者已经稳定 */ + stop: boolean + /** 本帧要写进 scrollTop 的增量 */ + delta: number + frames: number + stable: number +} + +/** + * prepend 锚点校正的每帧决策。 + * + * 两条规则: + * - 视口位置不是我们上一帧写下的那个(用户滚动、virtualizer 自己补偿过)→ 立即让位, + * 绝不把人拽回旧位置; + * - 位移连续稳定若干帧或跑满上限 → 结束(图片/字体/异步 markdown 会让高度继续变)。 + * + * 位移本身是实测值,重复应用是幂等的,所以第一帧不判断漂移。 + */ +export function nextPrependAdjustment( + state: PrependAdjustState, + sample: { scrollTop: number; delta: number | undefined }, + limits: { maxFrames?: number; stableFrames?: number; driftTolerance?: number } = {}, +): PrependAdjustDecision { + const maxFrames = limits.maxFrames ?? 180 + const stableFrames = limits.stableFrames ?? 30 + const driftTolerance = limits.driftTolerance ?? 1 + const frames = state.frames + 1 + + if ( + state.expectedScrollTop !== undefined && + Math.abs(sample.scrollTop - state.expectedScrollTop) > driftTolerance + ) { + return { stop: true, delta: 0, frames, stable: state.stable } + } + + const moving = sample.delta !== undefined && Math.abs(sample.delta) > 0.5 + const stable = moving ? 0 : state.stable + 1 + return { + stop: frames >= maxFrames || stable >= stableFrames, + delta: moving ? (sample.delta as number) : 0, + frames, + stable, + } +} diff --git a/src/features/chat/chatPageModel.ts b/src/features/chat/chatPageModel.ts index 8cc5108e4..38d2feb1a 100644 --- a/src/features/chat/chatPageModel.ts +++ b/src/features/chat/chatPageModel.ts @@ -910,12 +910,20 @@ export function buildFlatTimeline( return items } +const assistantLiveWorkCache = new WeakMap() + function assistantHasLiveWork(message: AssistantMessage): boolean { + const cached = assistantLiveWorkCache.get(message) + if (cached !== undefined) return cached // completed == null 即旧模型的 message.isStreaming - if (message.time.completed == null) return true - return message.content.some( - content => content.type === 'tool' && (content.state.status === 'running' || content.state.status === 'streaming'), - ) + const live = + message.time.completed == null + ? true + : message.content.some( + content => content.type === 'tool' && (content.state.status === 'running' || content.state.status === 'streaming'), + ) + assistantLiveWorkCache.set(message, live) + return live } function resolveTurnDurationMs( @@ -924,8 +932,8 @@ function resolveTurnDurationMs( turnDurationMap: Map, ): number | undefined { if (userStart == null) return undefined - for (const m of [...assistants].reverse()) { - const mapped = turnDurationMap.get(m.id) + for (let index = assistants.length - 1; index >= 0; index -= 1) { + const mapped = turnDurationMap.get(assistants[index].id) if (mapped != null && mapped > 0) return mapped } let latestEnd: number | undefined @@ -1085,20 +1093,19 @@ export function buildProcessTimeline( // 只关心带 user 的回合(过程壳的锚点) const userTurns = turns.filter((t): t is TurnBag & { user: UserMessage } => t.user != null) - const laterHasAssistant = (fromIndex: number) => { - for (let j = fromIndex + 1; j < userTurns.length; j++) { - if (userTurns[j].assistants.length > 0) return true - } - return false + // 后缀聚合:否则每个回合都往后扫一遍,长会话是 O(回合数²) + const laterAssistantSuffix = new Array(userTurns.length + 1).fill(false) + const laterLiveSuffix = new Array(userTurns.length + 1).fill(false) + for (let index = userTurns.length - 1; index >= 0; index -= 1) { + const turn = userTurns[index] + laterAssistantSuffix[index] = laterAssistantSuffix[index + 1] || turn.assistants.length > 0 + laterLiveSuffix[index] = laterLiveSuffix[index + 1] || turn.assistants.some(assistantHasLiveWork) } + const laterHasAssistant = (fromIndex: number) => laterAssistantSuffix[fromIndex + 1] ?? false + /** 更晚回合是否已有 live 助手——SSE 挂 Working 的绝对条件 */ - const laterHasLive = (fromIndex: number) => { - for (let j = fromIndex + 1; j < userTurns.length; j++) { - if (userTurns[j].assistants.some(assistantHasLiveWork)) return true - } - return false - } + const laterHasLive = (fromIndex: number) => laterLiveSuffix[fromIndex + 1] ?? false const isTurnSettled = (turn: TurnBag & { user: UserMessage }, index: number): boolean => { const assistants = turn.assistants diff --git a/src/features/chat/timelineMetrics.test.ts b/src/features/chat/timelineMetrics.test.ts new file mode 100644 index 000000000..7841d9336 --- /dev/null +++ b/src/features/chat/timelineMetrics.test.ts @@ -0,0 +1,116 @@ +import { describe, expect, it } from 'vitest' +import type { VirtualItem } from '@tanstack/react-virtual' +import type { AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' +import type { ProcessTimelineItem } from './chatPageModel' +import { + buildCachedSizeMap, + clearTimelineSessionCache, + estimateMessageHeight, + estimateTimelineItemSize, + estimateTimelineTotalHeight, + readSessionMeasurements, + restoreMeasurements, + sessionCacheKey, + writeSessionMeasurements, +} from './timelineMetrics' + +function user(id: string, text: string): UserMessage { + return { id, type: 'user', text, time: { created: 1 } } +} + +function assistant(id: string, content: AssistantMessage['content']): AssistantMessage { + return { + id, + type: 'assistant', + agent: 'build', + model: { id: 'model', providerID: 'provider' }, + content, + time: { created: 1, completed: 2 }, + } +} + +function messageItem(message: SessionMessageInfo): ProcessTimelineItem { + return { kind: 'message', key: message.id, message } +} + +function measurement(key: string, size: number, index = 0): VirtualItem { + return { key, index, size, start: 0, end: size, lane: 0 } +} + +describe('高度估算', () => { + it('折叠的 reasoning 不按全文高度估算', () => { + const longReasoning = assistant('a', [{ type: 'reasoning', text: 'x'.repeat(20_000) }]) + const longText = assistant('b', [{ type: 'text', text: 'x'.repeat(20_000) }]) + + expect(estimateMessageHeight(longReasoning)).toBeLessThan(200) + expect(estimateMessageHeight(longText)).toBeGreaterThan(estimateMessageHeight(longReasoning)) + }) + + it('用户长消息按折叠预览给上限', () => { + const short = user('u1', 'hi') + const long = user('u2', 'x'.repeat(10_000)) + expect(estimateMessageHeight(long)).toBeGreaterThan(estimateMessageHeight(short)) + expect(estimateMessageHeight(long)).toBeLessThan(400) + }) + + it('过程壳展开时计入子消息,折叠时只计入最终回答', () => { + const child = assistant('child', [{ type: 'text', text: 'x'.repeat(2000) }]) + const final = assistant('final', [{ type: 'text', text: 'x'.repeat(400) }]) + const active: ProcessTimelineItem = { + kind: 'process-shell', + key: 'shell', + userMessageId: 'u1', + isActive: true, + children: [{ message: child, processContentScope: 'process' }], + } + const collapsed: ProcessTimelineItem = { + kind: 'process-shell', + key: 'shell', + userMessageId: 'u1', + isActive: false, + children: [{ message: child, processContentScope: 'process' }], + finalMessage: final, + } + + expect(estimateTimelineItemSize(active)).toBeGreaterThan(estimateTimelineItemSize(collapsed)) + }) +}) + +describe('会话测量缓存', () => { + it('cache key 区分过程折叠模式', () => { + expect(sessionCacheKey('s1', true)).not.toBe(sessionCacheKey('s1', false)) + }) + + it('恢复时只取当前 timeline 仍存在的 key,并重算 index/start/end', () => { + const items = [messageItem(user('a', 'a')), messageItem(user('c', 'c'))] + const restored = restoreMeasurements([measurement('a', 100), measurement('b', 200), measurement('c', 300)], items) + + expect(restored?.map(item => item.key)).toEqual(['a', 'c']) + expect(restored?.map(item => item.index)).toEqual([0, 1]) + expect(restored?.[1]).toMatchObject({ start: 100, size: 300, end: 400 }) + }) + + it('没有匹配 key 时不返回缓存', () => { + expect(restoreMeasurements([measurement('gone', 100)], [messageItem(user('a', 'a'))])).toBeUndefined() + expect(buildCachedSizeMap(undefined)).toBeNull() + }) + + it('总高度对新消息使用估算值', () => { + const items = [messageItem(user('a', 'a')), messageItem(user('b', 'b'))] + const total = estimateTimelineTotalHeight(items, new Map([['a', 100]])) + + expect(total).toBeGreaterThan(100) + expect(total).toBe(100 + estimateTimelineItemSize(items[1])) + }) + + it('写回时只保留靠底部的一段并走 LRU', () => { + clearTimelineSessionCache() + const snapshot = Array.from({ length: 3005 }, (_unused, index) => measurement(`k${index}`, 10, index)) + writeSessionMeasurements('s1', snapshot) + + const restored = readSessionMeasurements('s1') + expect(restored).toHaveLength(3000) + expect(restored?.[0]?.key).toBe('k5') + expect(restored?.at(-1)?.key).toBe('k3004') + }) +}) diff --git a/src/features/chat/timelineMetrics.ts b/src/features/chat/timelineMetrics.ts new file mode 100644 index 000000000..1d297a411 --- /dev/null +++ b/src/features/chat/timelineMetrics.ts @@ -0,0 +1,162 @@ +/** + * 消息时间线的高度估算与会话测量缓存。 + * + * 从 ChatArea 里拆出来:这部分是纯数据计算,应该能单独测试, + * 而不是埋在一个一千多行、同时管虚拟化/滚动/命令式接口的组件里。 + */ +import type { VirtualItem } from '@tanstack/react-virtual' +import { + isAssistantMessage, + isUserMessage, + userMessageText, + type SessionMessageInfo, +} from '../../types/api/message' +import type { ProcessTimelineItem } from './chatPageModel' + +export const ROW_ESTIMATE = 60 +/** 过程壳 header 行高(Working / Worked 一行) */ +export const PROCESS_SHELL_HEADER = 36 +const SESSION_CACHE_LIMIT = 16 +/** 每个会话最多保留这么多条真实高度:长会话只缓存靠底部的一段 */ +const SESSION_MEASUREMENT_LIMIT = 3000 + +/** 文本高度粗估:大致每行 56 字符,行高 24;上限避免单条异常长消息把估算拉爆 */ +export function estimateTextHeight(text: string): number { + if (!text) return 0 + return Math.min(2000, 24 + Math.ceil(text.length / 56) * 24) +} + +const messageHeightCache = new WeakMap() + +/** + * 单条消息的初始高度估算。 + * + * 只在消息还没被真实测量过时使用;历史消息的 reasoning 默认折叠, + * 按 header 高度算,不能按全文长度算(否则初始位置会被大幅高估)。 + */ +export function estimateMessageHeight(message: SessionMessageInfo): number { + const cached = messageHeightCache.get(message) + if (cached != null) return cached + + let height: number + if (isAssistantMessage(message)) { + height = 64 + for (const content of message.content) { + if (content.type === 'reasoning') height += 44 + else if (content.type === 'text') height += estimateTextHeight(content.text) + else if (content.type === 'tool') height += 64 + } + height = Math.min(2400, height) + } else if (isUserMessage(message)) { + // 用户消息默认折叠到 8 行预览 + height = 80 + Math.min(8, Math.ceil(userMessageText(message).length / 48)) * 24 + } else { + height = ROW_ESTIMATE + } + + messageHeightCache.set(message, height) + return height +} + +const timelineItemHeightCache = new WeakMap() + +export function estimateTimelineItemSize(item: ProcessTimelineItem | undefined): number { + if (!item) return ROW_ESTIMATE + const cached = timelineItemHeightCache.get(item) + if (cached != null) return cached + + let size: number + if (item.kind === 'message') { + size = estimateMessageHeight(item.message) + } else if (item.isActive) { + // 进行中默认展开:header + 壳内消息 + const body = item.children.reduce((total, child) => total + estimateMessageHeight(child.message), 0) + size = PROCESS_SHELL_HEADER + Math.max(body, ROW_ESTIMATE) + } else { + // 结束后默认折叠:只估 header + 壳外 final + size = PROCESS_SHELL_HEADER + (item.finalMessage ? estimateMessageHeight(item.finalMessage) : 0) + } + + timelineItemHeightCache.set(item, size) + return size +} + +export function sessionCacheKey(sessionId: string, processCollapseEnabled: boolean): string { + return `${sessionId}:${processCollapseEnabled ? 'process' : 'flat'}` +} + +const sessionCache = new Map() + +export function readSessionMeasurements(key: string): VirtualItem[] | undefined { + const measurements = sessionCache.get(key) + if (!measurements) return undefined + // 读命中刷新 LRU 顺序 + sessionCache.delete(key) + sessionCache.set(key, measurements) + return measurements +} + +export function writeSessionMeasurements(key: string, snapshot: VirtualItem[]): void { + const measurements = + snapshot.length > SESSION_MEASUREMENT_LIMIT ? snapshot.slice(-SESSION_MEASUREMENT_LIMIT) : snapshot + sessionCache.delete(key) + sessionCache.set(key, measurements) + while (sessionCache.size > SESSION_CACHE_LIMIT) { + const oldest = sessionCache.keys().next().value + if (oldest === undefined) break + sessionCache.delete(oldest) + } +} + +/** + * 把缓存的 key→size 重新映射到当前 timeline。 + * + * 旧快照里的绝对 start/end 在消息追加/删除后不可信,只有 key→size 还有效。 + */ +export function restoreMeasurements( + measurements: VirtualItem[] | undefined, + timeline: ProcessTimelineItem[], +): VirtualItem[] | undefined { + if (!measurements?.length || timeline.length === 0) return undefined + const sizeByKey = new Map(measurements.map(item => [item.key, item.size])) + const restored: VirtualItem[] = [] + let start = 0 + for (let index = 0; index < timeline.length; index += 1) { + const item = timeline[index] + const size = sizeByKey.get(item.key) + if (size == null) continue + restored.push({ index, key: item.key, size, start, end: start + size, lane: 0 }) + start += size + } + return restored.length > 0 ? restored : undefined +} + +export function buildCachedSizeMap(measurements: VirtualItem[] | undefined): Map | null { + if (!measurements?.length) return null + return new Map(measurements.map(item => [String(item.key), item.size])) +} + +/** 已知 key 用真实高度,新消息用估算值累加 */ +export function estimateTimelineTotalHeight( + timeline: ProcessTimelineItem[], + sizeByKey: Map | null, +): number { + let total = 0 + for (const item of timeline) { + total += sizeByKey?.get(item.key) ?? estimateTimelineItemSize(item) + } + return total +} + +/** 仅测试/会话清理用 */ +export function clearTimelineSessionCache(): void { + sessionCache.clear() +} + +/** 释放单个会话的高度测量缓存(会话被回收时调用) */ +export function clearSessionMeasurements(sessionId: string): void { + const prefix = `${sessionId}:` + for (const key of sessionCache.keys()) { + if (key.startsWith(prefix)) sessionCache.delete(key) + } +} diff --git a/src/features/chat/useChatPageViewModel.ts b/src/features/chat/useChatPageViewModel.ts index fda84f408..93bdb2a16 100644 --- a/src/features/chat/useChatPageViewModel.ts +++ b/src/features/chat/useChatPageViewModel.ts @@ -1,4 +1,5 @@ import { useMemo, useRef } from 'react' +import { measurePerf } from '../../utils/perfTrace' import { isAssistantMessage, isUserMessage, userMessageText, type SessionMessageInfo } from '../../types/api/message' import { buildOutlineSourceEntries, type OutlineSourceEntry } from '../../components/outlineIndexModel' import { @@ -24,27 +25,35 @@ export interface ChatPageViewModel { forkTargetIdMap: Map turnDurationMap: Map turnLatestAssistantIds: Set + /** 内部结构共享用,不参与渲染(流式时避免每帧重建大纲) */ + outlineModel?: StableOutlineModel } -interface StableOutlineModel { - signature: string +export interface StableOutlineModel { + source: SessionMessageInfo[] entries: OutlineSourceEntry[] ownerByMessageId: Map } -const OUTLINE_MODEL_CACHE_LIMIT = 16 -const outlineModelCache = new Map() - -function buildOutlineSignature(messages: SessionMessageInfo[]): string { - let signature = '' - for (const message of messages) { - signature += `${message.id}:${message.type}|` - if (isUserMessage(message)) { - // v2 的用户消息没有 summary,正文就是 message.text - signature += `${userMessageText(message)}|` +/** + * 大纲只由「用户消息正文」和「消息 id/type 序列」决定。 + * 流式期间变化的是最后一条 assistant 的内容,这里按引用 + 身份比较即可, + * 不再每帧把所有用户文本拼成一个巨型签名。 + */ +function sameOutlineSource(previous: SessionMessageInfo[], next: SessionMessageInfo[]): boolean { + if (previous === next) return true + if (previous.length !== next.length) return false + for (let index = 0; index < next.length; index += 1) { + const left = previous[index] + const right = next[index] + if (left === right) continue + if (left.id !== right.id || left.type !== right.type) return false + // assistant 内容变化不影响大纲;用户消息文本变化才需要重建 + if (isUserMessage(left) && isUserMessage(right) && userMessageText(left) !== userMessageText(right)) { + return false } } - return signature + return true } function buildOutlineOwnerByMessageId(messages: SessionMessageInfo[]): Map { @@ -59,26 +68,16 @@ function buildOutlineOwnerByMessageId(messages: SessionMessageInfo[]): Map OUTLINE_MODEL_CACHE_LIMIT) { - const oldestKey = outlineModelCache.keys().next().value - if (oldestKey) outlineModelCache.delete(oldestKey) - } - return next } function sameStringList(a: readonly string[], b: readonly string[]) { @@ -249,7 +248,7 @@ export function buildChatPageViewModel( ) const visibleMessages = visibleMessagesFromEntries(previous?.visibleMessages, visibleMessageEntries) const forkTargetIdMap = reuseMap(previous?.forkTargetIdMap, buildForkTargetIdMap(visibleMessageEntries)) - const outlineModel = getStableOutlineModel(visibleMessages) + const outlineModel = getStableOutlineModel(visibleMessages, previous?.outlineModel) const turnDurationMap = reuseMap(previous?.turnDurationMap, buildTurnDurationMap(messages, visibleMessages)) const turnLatestAssistantIds = reuseSet( previous?.turnLatestAssistantIds, @@ -272,6 +271,7 @@ export function buildChatPageViewModel( ) return pageRecords }, + outlineModel, outlineSourceEntries: outlineModel.entries, outlineOwnerByMessageId: outlineModel.ownerByMessageId, forkTargetIdMap, @@ -283,7 +283,12 @@ export function buildChatPageViewModel( export function useChatPageViewModel(messages: SessionMessageInfo[], showNotices = false): ChatPageViewModel { const previousRef = useRef(undefined) return useMemo(() => { - const viewModel = buildChatPageViewModel(messages, previousRef.current, showNotices) + const viewModel = measurePerf( + 'chat.pageViewModel', + () => buildChatPageViewModel(messages, previousRef.current, showNotices), + 4, + `${messages.length} msgs`, + ) previousRef.current = viewModel return viewModel }, [messages, showNotices]) diff --git a/src/features/message/CollapsibleUserText.tsx b/src/features/message/CollapsibleUserText.tsx index 3b498de9d..0c5b63dd4 100644 --- a/src/features/message/CollapsibleUserText.tsx +++ b/src/features/message/CollapsibleUserText.tsx @@ -11,6 +11,7 @@ import { useTranslation } from 'react-i18next' import { MarkdownRenderer } from '../../components/MarkdownRenderer' import { useDisclosureScrollLock } from '../../hooks' import { useUiDisclosureState } from '../../utils/uiDisclosureState' +import { BoundedCache } from '../../utils/boundedCache' /** 默认预览 8 行 */ const COLLAPSE_PREVIEW_LINES = 8 @@ -20,7 +21,7 @@ export const USER_HTML_ARTIFACT_PATTERN = /(?:```(?:html|htm)\b|() +const overflowStateCache = new BoundedCache({ maxEntries: 2000 }) export interface CollapsibleUserTextProps { text: string diff --git a/src/features/message/MessageRenderer.test.tsx b/src/features/message/MessageRenderer.test.tsx index 81e897951..151f075bf 100644 --- a/src/features/message/MessageRenderer.test.tsx +++ b/src/features/message/MessageRenderer.test.tsx @@ -24,6 +24,12 @@ vi.mock('motion/mini', () => ({ vi.mock('../../hooks', () => ({ useDelayedRender: (show: boolean) => show, + useCompositorExpand: () => ({ + contentRef: { current: null }, + layoutOpen: true, + keepMounted: true, + panelClassName: '', + }), useDisclosureScrollLock: () => ({ rootRef: () => undefined, headerRef: () => undefined, @@ -67,7 +73,11 @@ vi.mock('../../components/ui', () => ({ })) vi.mock('./parts', () => ({ - TextPartView: ({ part }: { part: { text: string } }) =>
    {part.text}
    , + TextPartView: ({ part, isStreaming }: { part: { text: string }; isStreaming?: boolean }) => ( +
    + {part.text} +
    + ), ReasoningPartView: () => null, ToolPartView: () => null, FilePartView: ({ file }: { file: { name?: string; mime: string } }) => ( @@ -262,6 +272,27 @@ describe('process content split', () => { expect(messageHasFinalContent(streaming)).toBe(false) }) + it('stops text pacing once a later content block exists', () => { + const tool: AssistantContent = { + type: 'tool', + id: 'tool-1', + name: 'bash', + state: { status: 'running', input: { command: 'ls' }, metadata: {} }, + time: { created: 2 }, + } + const message = createAssistantMessage([textContent('before tool'), tool]) + render() + + expect(screen.getByTestId('text-part')).toHaveAttribute('data-streaming', 'false') + }) + + it('keeps the last text block streaming while it is still open', () => { + const message = createAssistantMessage([textContent('still typing')]) + render() + + expect(screen.getByTestId('text-part')).toHaveAttribute('data-streaming', 'true') + }) + it('splits completed tool+text into process and final', () => { const message = createAssistantMessage( [ diff --git a/src/features/message/MessageRenderer.tsx b/src/features/message/MessageRenderer.tsx index fafe404ba..eb4871a90 100644 --- a/src/features/message/MessageRenderer.tsx +++ b/src/features/message/MessageRenderer.tsx @@ -40,11 +40,25 @@ import { MessageExpandPanel, useMessageExpandRender } from './messageExpand' import type { AssistantContent, AssistantMessage, SessionMessageInfo, UserMessage } from '../../types/api/message' import { readPromptAttachments } from '../../api/message' import type { JsonValue } from '@opencode/client/promise' -import { contentEntries, hasVisibleText, idleMessageError, userMessageText, type ContentEntry } from '../../types/api/message' +import { contentEntries, hasVisibleText, idleMessageError, userMessageText } from '../../types/api/message' import { currentToolFailed } from '../../types/api/toolState' +import { buildDescriptiveToolStepsSummary, isToolPartActive, type ToolEntry } from './toolSummary' +import { useCardEnter } from './streamCardEnter' +import { + getProcessSplit, + groupContentForRender, + messageHasFinalContent, + messageHasProcessContent, + messageStillStreamingProcess, + splitProcessRenderItems, + type ProcessSplit, + type RenderItem, +} from './contentGrouping' + +export { messageHasFinalContent, messageHasProcessContent, messageStillStreamingProcess, splitProcessRenderItems } +export type { ProcessSplit } import { resolveTaskChildSessionRef } from '../../utils/taskChildBinding' import { diffLineStats } from '../../utils/diffUtils' -import { expandCodeModeSubCalls } from './parts/executeSubCallSummary' import { ENTRY_GROW_DURATION_MS, isEntryGrowComplete, @@ -59,6 +73,7 @@ import { } from '../../utils/formatUtils' import { lockScrollAroundAnchor } from '../../utils/scrollUtils' import { useUiDisclosureState } from '../../utils/uiDisclosureState' +import { prefersReducedMotion } from '../../utils/motion' /** * 过程折叠 header:进行中自己走表,只有这一行因计时更新;children 不跟时钟走。 @@ -175,98 +190,6 @@ export function ProcessCollapseBlock({ */ export type ProcessContentScope = 'all' | 'process' | 'final' | 'inline' -type ProcessSplit = { - processItems: RenderItem[] - finalItems: RenderItem[] - hasProcess: boolean - hasFinal: boolean -} - -// ============================================ -// 渲染条目 -// -// v2 的助手内容只有 text / reasoning / tool 三类,且元素**没有 id**: -// 稳定 id 一律由 `contentEntries()` 按官方算法派生 -// (text/reasoning 用 `${message.id}:${type}:${perKindOrdinal}`,tool 用 `content.id`)。 -// ============================================ - -/** 派生 id + 原生内容 */ -type ToolEntry = ContentEntry> - -type RenderItem = - | { type: 'single'; id: string; content: Exclude } - | { type: 'tool-group'; tools: ToolEntry[] } - -/** - * 把 render items 拆成「过程」和「最终回答」。 - * 最终回答 = 消息中最后一段连续 text。 - * reasoning / tool 永远进过程。 - */ -export function splitProcessRenderItems(items: RenderItem[]): ProcessSplit { - if (items.length === 0) { - return { processItems: [], finalItems: [], hasProcess: false, hasFinal: false } - } - - let lastTextIdx = -1 - for (let i = items.length - 1; i >= 0; i--) { - const item = items[i] - if (item.type === 'single' && item.content.type === 'text') { - lastTextIdx = i - break - } - break - } - - if (lastTextIdx < 0) { - return { - processItems: items, - finalItems: [], - hasProcess: items.length > 0, - hasFinal: false, - } - } - - let textRunStart = lastTextIdx - while (textRunStart > 0) { - const prev = items[textRunStart - 1] - if (prev.type === 'single' && prev.content.type === 'text') { - textRunStart -= 1 - continue - } - break - } - - const finalItems = items.slice(textRunStart) - const processItems = items.slice(0, textRunStart) - - return { - processItems, - finalItems, - hasProcess: processItems.length > 0, - hasFinal: finalItems.length > 0, - } -} - -/** v2 没有 isStreaming 标志:助手消息 time.completed 缺失即仍在流式 */ -export function messageStillStreamingProcess(message: SessionMessageInfo): boolean { - if (message.type !== 'assistant') return false - return message.time.completed == null -} - -/** 是否有可收进过程块的内容(tool / reasoning 等,不含尾部最终 text) */ -export function messageHasProcessContent(message: SessionMessageInfo): boolean { - if (message.type !== 'assistant') return false - if (messageStillStreamingProcess(message)) return true - return splitProcessRenderItems(groupContentForRender(message)).hasProcess -} - -/** 是否有应留在折叠块外的最终 text(仅消息已结束后才拆) */ -export function messageHasFinalContent(message: SessionMessageInfo): boolean { - if (message.type !== 'assistant') return false - if (messageStillStreamingProcess(message)) return false - return splitProcessRenderItems(groupContentForRender(message)).hasFinal -} - interface MessageRendererProps { message: SessionMessageInfo allowStreamingLayoutAnimation?: boolean @@ -501,7 +424,7 @@ function useEntryGrowAnimation( } // 过程壳内消息禁止入场生长:会连着虚拟行反复 measure,造成整列高度抽搐 - if (!enabled || !el) { + if (!enabled || !el || prefersReducedMotion()) { finish() return } @@ -678,33 +601,38 @@ const AssistantMessageView = memo(function AssistantMessageView({ if (message.time.completed == null) { return processContentScope === 'process' ? items : [] } - const split = splitProcessRenderItems(items) + const split = getProcessSplit(message) if (processContentScope === 'process') return split.processItems if (processContentScope === 'final') return split.finalItems return items }, [message, processContentScope]) - // 判断哪些 reasoning 内容已经结束(后面出现了任何其他 kind 的内容) - const endedReasoningIds = useMemo(() => { + // 哪些文本 / 推理块已经结束:后面出现了别的 content。 + // 平滑只属于仍处于「打开」状态的最后一块;块一旦结束就直接显示完整内容, + // 避免后面的工具卡先出现、前面的文字还在追。 + const endedBlockIds = useMemo(() => { const ended = new Set() const entries = contentEntries(message) - for (let i = 0; i < entries.length; i++) { - if (entries[i].content.type !== 'reasoning') continue - if (i + 1 < entries.length) ended.add(entries[i].id) + for (let i = 0; i < entries.length - 1; i += 1) { + const type = entries[i].content.type + if (type === 'text' || type === 'reasoning') ended.add(entries[i].id) } return ended }, [message]) - // 计算完整文本用于复制(缓存:content 引用未变时复用,避免流式每帧重算字符串拼接) - const fullText = useMemo( - () => + // 复制内容按需拼接:流式每帧把整段正文 join 一遍是纯浪费 + const getCopyText = useMemo( + () => () => message.content .filter(entry => entry.type === 'text') .map(entry => entry.text) .join(''), [message], ) - const hasCopyableText = fullText.trim().length > 0 + const hasCopyableText = useMemo( + () => message.content.some(entry => entry.type === 'text' && hasVisibleText(entry)), + [message], + ) // 检查消息级别错误(v2 是结构化对象) const messageError = message.error @@ -714,6 +642,13 @@ const AssistantMessageView = memo(function AssistantMessageView({ const completed = message.time.completed ?? message.time.streamed const duration = message.time.completed != null ? message.time.completed - created : undefined + // 工具组上下文对象保持稳定,ToolPartView / ToolGroup 的 memo 才能命中, + // 流式时不会把整组已完成工具重渲染一遍 + const toolMessageContext = useMemo( + () => ({ messageID: message.id, created, completed }), + [message.id, created, completed], + ) + // agent / model(仅 assistant 消息) const agent = message.agent || undefined const modelLabel = message.model?.id || undefined @@ -765,7 +700,7 @@ const AssistantMessageView = memo(function AssistantMessageView({ ) @@ -774,9 +709,15 @@ const AssistantMessageView = memo(function AssistantMessageView({ const content = item.content switch (content.type) { case 'text': - return + return ( + + ) case 'reasoning': { - const reasoningDone = endedReasoningIds.has(item.id) + const reasoningDone = endedBlockIds.has(item.id) return ( - + )} @@ -874,6 +815,8 @@ const LARGE_TOOL_GROUP_SIZE = 20 const ToolGroup = memo(function ToolGroup({ tools, messageContext, isStreaming }: ToolGroupProps) { const { t } = useTranslation('message') + // 组初次挂载时的工具数:这批由组级入场带出来,之后新增的卡自己播 + const initialToolCountRef = useRef(tools.length) const { descriptiveToolSteps, inlineToolRequests, immersiveMode, processCollapseEnabled } = useTheme() const { serverId, pendingPermissions, pendingQuestions } = useInlineToolRequests() const hasPendingInteraction = @@ -994,6 +937,22 @@ const ToolGroup = memo(function ToolGroup({ tools, messageContext, isStreaming } // steps header: 多工具始终显示;描述型 steps 模式下,单工具也显示 const showStepsHeader = totalCount > 1 || descriptiveToolSteps + // 组级入场:header 和第一张卡一起长出来,避免 header 先蹦、卡片再长。 + // 之后新加进来的卡自己播入场(idx >= 初始数量)。 + const groupEnter = useCardEnter({ + id: `group:${tools[0]?.id ?? 'empty'}`, + created: tools[0]?.content.time.created ?? 0, + enabled: !!isStreaming && showStepsHeader, + }) + const setGroupRootRef = useCallback( + (node: HTMLDivElement | null) => { + groupEnter.ref(node) + stepsRootRef(node) + }, + [groupEnter.ref, stepsRootRef], + ) + const initialToolCount = initialToolCountRef.current + // 只 map 一次:有 header 时受 expand mount 控制,无 header 时始终挂载 const toolParts = !showStepsHeader || shouldRenderBody @@ -1008,6 +967,7 @@ const ToolGroup = memo(function ToolGroup({ tools, messageContext, isStreaming } descriptive={descriptiveToolSteps} isStreaming={isStreaming} lazyBody={isLargeGroup} + skipEnter={groupEnter.willAnimate && idx < initialToolCount} /> )) : null @@ -1015,7 +975,7 @@ const ToolGroup = memo(function ToolGroup({ tools, messageContext, isStreaming } // 统一容器结构 — ToolPartView 始终在同一 React 树位置, // streaming→idle / 1→N 工具切换时不 remount,expanded 状态不丢失 return ( -
    +
    {showStepsHeader && (descriptiveToolSteps ? (
    )} + + {import.meta.env.DEV && }
    ) } + +/** 仅开发期:把已有的渲染失败、帧统计和持有量放在一个地方,排障不用翻 console */ +function DiagnosticsSection() { + const [refreshedAt, setRefreshedAt] = useState(() => Date.now()) + const failures = getRecentRenderFailures() + const frame = getLastFrameStats() + const held = messageStore.getHeldChatSize() + + return ( + +
    + + + {new Date(refreshedAt).toLocaleTimeString()} + +
    + +
    +
    + 持有:{held.sessions.length} 个会话 / {held.totalMessages} 条消息 /{' '} + {(held.totalChars / 1024).toFixed(1)} KB +
    + {frame ? ( +
    + 最近流式帧:frames={frame.stats.frames} avg={frame.stats.avgFrameMs.toFixed(1)}ms p95= + {frame.stats.p95FrameMs}ms max={frame.stats.longestFrameMs.toFixed(1)}ms dropped= + {frame.stats.droppedFrames} +
    + ) : ( +
    还没有流式帧统计(跑一次流式对话后再看)
    + )} +
    + + {failures.length === 0 ? ( +
    没有渲染失败记录
    + ) : ( +
      + {failures + .slice(-12) + .reverse() + .map((failure, index) => ( +
    • + [{failure.kind}] {failure.scope}: {failure.reason} +
    • + ))} +
    + )} +
    + ) +} diff --git a/src/features/settings/components/ChatSettings.tsx b/src/features/settings/components/ChatSettings.tsx index 5f4ab6c42..4132f73e4 100644 --- a/src/features/settings/components/ChatSettings.tsx +++ b/src/features/settings/components/ChatSettings.tsx @@ -36,6 +36,12 @@ export function ChatSettings() { setRenderHtmlContent, composerSelectorStyle, setComposerSelectorStyle, + streamPacingEnabled, + setStreamPacingEnabled, + streamFadeEnabled, + setStreamFadeEnabled, + markdownCodeFoldEnabled, + setMarkdownCodeFoldEnabled, } = useTheme() const [collapseUserMessages, setCollapseUserMessages] = useState(themeStore.collapseUserMessages) const [stepFinishDisplay, setStepFinishDisplay] = useState(themeStore.stepFinishDisplay) @@ -119,6 +125,17 @@ export function ChatSettings() { setRenderHtmlContent(!renderHtmlContent)} /> + setMarkdownCodeFoldEnabled(!markdownCodeFoldEnabled)} + > + setMarkdownCodeFoldEnabled(!markdownCodeFoldEnabled)} + /> + + + + setStreamPacingEnabled(!streamPacingEnabled)} + > + setStreamPacingEnabled(!streamPacingEnabled)} /> + + + setStreamFadeEnabled(!streamFadeEnabled)} + > + setStreamFadeEnabled(!streamFadeEnabled)} /> + + + {STEP_FINISH_FIELDS.map(({ key, label, desc }) => ( toggleStepField(key)}> diff --git a/src/features/settings/settingsSearchCatalog.ts b/src/features/settings/settingsSearchCatalog.ts index c1e4b387e..eaee1666d 100644 --- a/src/features/settings/settingsSearchCatalog.ts +++ b/src/features/settings/settingsSearchCatalog.ts @@ -56,6 +56,10 @@ export const SETTINGS_SEARCH_DEFINITIONS: SettingsSearchDefinition[] = [ 'chat.collapseLongMessages', 'chat.renderUserMarkdown', 'chat.renderHtmlContent', + 'chat.markdownCodeFold', + 'chat.streamRendering', + 'chat.streamPacing', + 'chat.streamFade', 'chat.outlineCurrentHighlight', 'chat.actionsOnLatestAssistantOnly', 'chat.desktopCollapsedInputDock', diff --git a/src/hooks/useCompositorExpand.ts b/src/hooks/useCompositorExpand.ts index 3a333a64b..911cc9eb5 100644 --- a/src/hooks/useCompositorExpand.ts +++ b/src/hooks/useCompositorExpand.ts @@ -1,5 +1,6 @@ import { useLayoutEffect, useRef, useState, type RefObject } from 'react' import { EXPAND_MOTION } from '../constants/expandMotion' +import { prefersReducedMotion } from '../utils/motion' function isAndroid(): boolean { return typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent) @@ -20,7 +21,7 @@ export const COMPOSITOR_GRID_TRANSITION = EXPAND_MOTION.gridTransition * 子树逐帧量高,组里工具越多越贵,直接瞬时展开。 */ export function useCompositorExpand(open: boolean, animate = true) { - const enabled = isAndroid() && animate + const enabled = isAndroid() && animate && !prefersReducedMotion() const contentRef = useRef(null) const [layoutOpen, setLayoutOpen] = useState(open) const [useGridTransition, setUseGridTransition] = useState(!enabled) diff --git a/src/hooks/useIdleSessionTrim.ts b/src/hooks/useIdleSessionTrim.ts new file mode 100644 index 000000000..d4fc3329b --- /dev/null +++ b/src/hooks/useIdleSessionTrim.ts @@ -0,0 +1,61 @@ +import { useEffect } from 'react' +import { messageStore } from '../store/messageStore' +import { clearSessionMeasurements } from '../features/chat/timelineMetrics' + +/** 窗口隐藏后闲置多久开始回收非活跃会话 */ +const IDLE_TRIM_DELAY_MS = 10 * 60 * 1000 +/** 回收后保留最近使用的会话数;正在流式和分屏保护的会话不受影响 */ +const IDLE_TRIM_KEEP = 2 +/** 持有量不到这个量级就不回收——正常使用不该感觉到切回会话变慢 */ +const IDLE_TRIM_MIN_CHARS = 2 * 1024 * 1024 + +/** + * 后台闲置时回收非活跃会话。 + * + * 应用本身已经按最近使用保留了若干个会话,但一直开着不动时没有回收时机; + * 这里把「窗口隐藏超过十分钟」当作低内存信号,只留当前/最近两个, + * 被回收的会话下次打开会重新拉最近一页。 + */ +export function useIdleSessionTrim() { + useEffect(() => { + let timer: number | null = null + + const cancel = () => { + if (timer !== null) { + window.clearTimeout(timer) + timer = null + } + } + + const trim = () => { + timer = null + const before = messageStore.getHeldChatSize() + if (before.totalChars < IDLE_TRIM_MIN_CHARS) return + const evicted = messageStore.trimIdleSessions(IDLE_TRIM_KEEP) + if (evicted.length === 0) return + for (const sessionId of evicted) clearSessionMeasurements(sessionId) + if (import.meta.env.DEV) { + const held = messageStore.getHeldChatSize() + console.warn( + `[perf] chat.trim sessions=${evicted.length} kept=${held.sessions.length} ` + + `chars=${before.totalChars}->${held.totalChars}`, + ) + } + } + + const onVisibilityChange = () => { + if (document.visibilityState === 'hidden') { + cancel() + timer = window.setTimeout(trim, IDLE_TRIM_DELAY_MS) + } else { + cancel() + } + } + + document.addEventListener('visibilitychange', onVisibilityChange) + return () => { + cancel() + document.removeEventListener('visibilitychange', onVisibilityChange) + } + }, []) +} diff --git a/src/hooks/useInView.test.tsx b/src/hooks/useInView.test.tsx index 8d246a42b..28a7e758e 100644 --- a/src/hooks/useInView.test.tsx +++ b/src/hooks/useInView.test.tsx @@ -8,6 +8,7 @@ class IntersectionObserverMock { callback: IntersectionObserverCallback options: IntersectionObserverInit | undefined observed: Element[] = [] + unobserved: Element[] = [] disconnected = false constructor(callback: IntersectionObserverCallback, options?: IntersectionObserverInit) { @@ -20,7 +21,9 @@ class IntersectionObserverMock { observe = vi.fn((target: Element) => { this.observed.push(target) }) - unobserve = vi.fn() + unobserve = vi.fn((target: Element) => { + this.unobserved.push(target) + }) disconnect = vi.fn(() => { this.disconnected = true }) @@ -196,3 +199,51 @@ describe('useNearViewport', () => { expect(observer.disconnected).toBe(true) }) }) + +function OnceHarness() { + const { ref, near } = useNearViewport({ rootMargin: '200% 0px', triggerOnce: true }) + return ( +
    +
    + {String(near)} +
    + ) +} + +describe('useNearViewport(一次性)', () => { + const originalObserver = globalThis.IntersectionObserver + + beforeEach(() => { + IntersectionObserverMock.instance = null + IntersectionObserverMock.instances = [] + vi.stubGlobal('IntersectionObserver', IntersectionObserverMock as unknown as typeof IntersectionObserver) + }) + + afterEach(() => { + vi.unstubAllGlobals() + globalThis.IntersectionObserver = originalObserver + }) + + it('命中一次后保持 true,并停止观察', () => { + render() + const observer = IntersectionObserverMock.instance! + const target = screen.getByTestId('target') + + act(() => { + observer.callback( + [{ isIntersecting: true, target } as unknown as IntersectionObserverEntry], + {} as IntersectionObserver, + ) + }) + expect(screen.getByTestId('state')).toHaveTextContent('true') + expect(observer.unobserved).toContain(target) + + act(() => { + observer.callback( + [{ isIntersecting: false, target } as unknown as IntersectionObserverEntry], + {} as IntersectionObserver, + ) + }) + expect(screen.getByTestId('state')).toHaveTextContent('true') + }) +}) diff --git a/src/hooks/useInView.ts b/src/hooks/useInView.ts index b0cc8304c..55c70be94 100644 --- a/src/hooks/useInView.ts +++ b/src/hooks/useInView.ts @@ -73,9 +73,28 @@ function observerKey(root: Element | null, rootMargin: string): string { return `root:${id}|${rootMargin}` } -export function useNearViewport(rootMargin = '1000px 0px', enabled = true) { +export type NearViewportOptions = { + rootMargin?: string + enabled?: boolean + /** 进入范围一次后保持 true:代码高亮这类只做一次、不能来回卸载的工作 */ + triggerOnce?: boolean +} + +export function useNearViewport( + rootMarginOrOptions: string | NearViewportOptions = '1000px 0px', + enabledOption = true, +) { + const options: NearViewportOptions = + typeof rootMarginOrOptions === 'string' + ? { rootMargin: rootMarginOrOptions, enabled: enabledOption } + : rootMarginOrOptions + const rootMargin = options.rootMargin ?? '1000px 0px' + const enabled = options.enabled ?? true + const triggerOnce = options.triggerOnce ?? false + const [near, setNear] = useState(false) const [element, setElement] = useState(null) + const triggeredRef = useRef(false) const supported = typeof IntersectionObserver !== 'undefined' const ref = useCallback( @@ -87,6 +106,7 @@ export function useNearViewport(rootMargin = '1000px 0px', enabled = true) { useEffect(() => { if (!enabled || !element || !supported) return + if (triggerOnce && triggeredRef.current) return // 聊天区是内部滚动容器:root 取视口时,rootMargin 只会扩大视口, // 祖先滚动容器的裁切不受影响,1000px 提前量等于没写。 @@ -108,7 +128,18 @@ export function useNearViewport(rootMargin = '1000px 0px', enabled = true) { } const current = shared - current.listeners.set(element, setNear) + const listener: NearListener = value => { + if (value && triggerOnce) { + // 一次性的观察:命中后立刻摘掉,别让它跟着来回触发 + triggeredRef.current = true + current.observer.unobserve(element) + current.listeners.delete(element) + setNear(true) + return + } + setNear(value) + } + current.listeners.set(element, listener) current.observer.observe(element) return () => { @@ -119,7 +150,7 @@ export function useNearViewport(rootMargin = '1000px 0px', enabled = true) { sharedNearObservers.delete(key) } } - }, [element, enabled, rootMargin, supported]) + }, [element, enabled, rootMargin, supported, triggerOnce]) // 关闭门控或没有 IntersectionObserver 的环境(测试 / 老浏览器)都当「在视口内」 return { ref, near: !enabled || !supported || near } diff --git a/src/hooks/useInputCapabilities.test.ts b/src/hooks/useInputCapabilities.test.ts new file mode 100644 index 000000000..ef3d1358d --- /dev/null +++ b/src/hooks/useInputCapabilities.test.ts @@ -0,0 +1,78 @@ +import { describe, expect, it } from 'vitest' +import { getInputCapabilities } from './useInputCapabilities' + +const DESKTOP_UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' +const ANDROID_UA = 'Mozilla/5.0 (Linux; Android 14; SM-S928B) Chrome/124 Mobile Safari/537.36' +const IPAD_UA = 'Mozilla/5.0 (iPad; CPU OS 17_4 like Mac OS X) Version/17.4 Mobile/15E148 Safari/604.1' + +function setEnvironment(env: { + hoverFine?: boolean + coarse?: boolean + touchPoints?: number + userAgent?: string + platform?: string +}) { + const state = { + hoverFine: false, + coarse: false, + touchPoints: 0, + userAgent: DESKTOP_UA, + platform: '', + ...env, + } + + Object.defineProperty(window, 'matchMedia', { + configurable: true, + writable: true, + value: (query: string) => ({ + matches: query.includes('hover: hover') ? state.hoverFine : state.coarse, + media: query, + onchange: null, + addListener: () => {}, + removeListener: () => {}, + addEventListener: () => {}, + removeEventListener: () => {}, + dispatchEvent: () => false, + }), + }) + Object.defineProperty(navigator, 'maxTouchPoints', { configurable: true, get: () => state.touchPoints }) + Object.defineProperty(navigator, 'userAgent', { configurable: true, get: () => state.userAgent }) + Object.defineProperty(navigator, 'platform', { configurable: true, get: () => state.platform }) +} + +describe('getInputCapabilities', () => { + it('keeps desktop controls for a mouse-only desktop', () => { + setEnvironment({ hoverFine: true }) + + expect(getInputCapabilities().preferTouchUi).toBe(false) + }) + + it('prefers touch ui on a phone that reports a hovering fine pointer', () => { + // 带笔的机型会如实报 hover+fine,不能因此退回桌面控件 + setEnvironment({ hoverFine: true, userAgent: ANDROID_UA }) + + const caps = getInputCapabilities() + + expect(caps.hasTouch).toBe(true) + expect(caps.preferTouchUi).toBe(true) + }) + + it('keeps desktop controls on a hybrid laptop with touch screen', () => { + setEnvironment({ hoverFine: true, coarse: true, touchPoints: 10 }) + + expect(getInputCapabilities().preferTouchUi).toBe(false) + }) + + it('prefers touch ui on tablets', () => { + setEnvironment({ coarse: true, touchPoints: 5, userAgent: IPAD_UA }) + + expect(getInputCapabilities().preferTouchUi).toBe(true) + }) + + it('prefers touch ui for an ipad reporting itself as a mac', () => { + // iPadOS 13+ 伪装成 Mac,只能靠触点数区分 + setEnvironment({ hoverFine: true, touchPoints: 5, platform: 'MacIntel' }) + + expect(getInputCapabilities().preferTouchUi).toBe(true) + }) +}) diff --git a/src/hooks/useInputCapabilities.ts b/src/hooks/useInputCapabilities.ts index 7362ffc22..90d3097c0 100644 --- a/src/hooks/useInputCapabilities.ts +++ b/src/hooks/useInputCapabilities.ts @@ -1,7 +1,9 @@ import { useEffect, useState } from 'react' -const CAN_HOVER_QUERY = '((hover: hover) and (pointer: fine)), ((any-hover: hover) and (any-pointer: fine))' -const COARSE_POINTER_QUERY = '(pointer: coarse), (any-pointer: coarse)' +// 只看主输入:any-hover / any-pointer 只要系统里存在精确指针就成立, +// 会把带笔的手机判成桌面机。 +const CAN_HOVER_QUERY = '(hover: hover) and (pointer: fine)' +const COARSE_POINTER_QUERY = '(pointer: coarse)' export interface InputCapabilities { canHover: boolean @@ -18,11 +20,21 @@ function getMatchMediaMatches(query: string) { return window.matchMedia(query).matches } +/** 手机/平板。移动端的媒体查询会被笔和外接指针带偏,UA 才是稳定信号。 */ +function isHandheldDevice() { + if (typeof navigator === 'undefined') return false + if (/Android|iPhone|iPod|iPad|Mobile/i.test(navigator.userAgent)) return true + // iPadOS 13+ 的 UA 伪装成桌面 Mac,只能靠触点数区分 + return navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1 +} + export function getInputCapabilities(): InputCapabilities { + const handheld = isHandheldDevice() const canHover = getMatchMediaMatches(CAN_HOVER_QUERY) const hasCoarsePointer = getMatchMediaMatches(COARSE_POINTER_QUERY) - const hasTouch = typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0 - const preferTouchUi = (hasCoarsePointer || hasTouch) && !canHover + const hasTouch = handheld || (typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0) + // 手持设备一律触摸优先,不让媒体查询否决 + const preferTouchUi = handheld || ((hasCoarsePointer || hasTouch) && !canHover) return { canHover, diff --git a/src/hooks/useSessionManager.ts b/src/hooks/useSessionManager.ts index b1876e831..f0b1ec1e2 100644 --- a/src/hooks/useSessionManager.ts +++ b/src/hooks/useSessionManager.ts @@ -19,6 +19,7 @@ import { takeSessionMessagesPrefetch } from '../api/messagePrefetch' import { sessionErrorHandler } from '../utils' import { isSessionNotFoundError } from '../utils/sessionErrors' import { INITIAL_MESSAGE_LIMIT, HISTORY_LOAD_BATCH_SIZE } from '../constants' +import { derivePageLimit } from '../utils/pageBudget' import { isUserMessage } from '../types/api/message' import type { APIError } from '../types/api/common' import type { SessionMessageInfo } from '../types/api/message' @@ -110,6 +111,8 @@ export function useSessionManager({ const loadSequenceRef = useRef>(new Map()) /** 每个 session 的历史翻页 in-flight 守卫(官方 messageLoads 同款,防止并发翻页) */ const historyLoadsRef = useRef>>(new Map()) + /** 按上一页体积推导出的下一页条数(内容特别肥的会话自动缩小页) */ + const nextPageLimitRef = useRef>(new Map()) const loadSessionRef = useRef<(sid: string, options?: { force?: boolean }) => Promise>(async () => {}) // 桌面端本地 serve 的拉起 / registry 地址回写状态(main.tsx 的 // initializeNativeDesktopService 期间为 true)。此刻本地地址未就绪, @@ -131,7 +134,9 @@ export function useSessionManager({ if (cursor === null) return false const serverId = sessionKeyToServerId(sid) - const page = await getSessionMessagesPage(sid, { limit: HISTORY_LOAD_BATCH_SIZE, cursor }, serverId) + const pageLimit = nextPageLimitRef.current.get(sid) ?? HISTORY_LOAD_BATCH_SIZE + const page = await getSessionMessagesPage(sid, { limit: pageLimit, cursor }, serverId) + nextPageLimitRef.current.set(sid, derivePageLimit(page.messages, HISTORY_LOAD_BATCH_SIZE)) const latestState = messageStore.getSessionState(sid) if (!latestState) return false @@ -269,6 +274,8 @@ export function useSessionManager({ const apiMessages = firstPage.messages const nextCursor = firstPage.nextCursor + // 首屏只拉固定条数;如果这一页特别肥,后续翻页自动缩小 + nextPageLimitRef.current.set(sid, derivePageLimit(apiMessages, HISTORY_LOAD_BATCH_SIZE)) // 再次检查:加载期间 SSE 可能已经推送了更多消息 // force 模式下(重连)始终用服务器数据覆盖,因为本地数据可能不完整 diff --git a/src/hooks/useSyntaxHighlight.ts b/src/hooks/useSyntaxHighlight.ts index a283a259a..4478e5bc4 100644 --- a/src/hooks/useSyntaxHighlight.ts +++ b/src/hooks/useSyntaxHighlight.ts @@ -1,11 +1,20 @@ -import { useState, useEffect, useMemo, useRef, useId, useSyncExternalStore } from 'react' +import { useState, useEffect, useMemo, useRef, useId, useSyncExternalStore, useCallback } from 'react' import type { ShikiThemeInput } from '../lib/shikiTheme' import { getShikiTheme, useIsDarkMode } from '../lib/shikiTheme' -import { disposeShikiWorkerKey, highlightHtmlInWorker, highlightTokensInWorker } from '../lib/shikiWorkerClient' +import { disposeShikiWorkerKey, highlightHtmlInWorker, highlightTokensInWorker, splitTokensIntoLines } from '../lib/shikiWorkerClient' import type { HighlightTokens } from '../lib/highlightTypes' +import { + applyHighlightChunk, + createHighlightAccumulator, + type HighlightAccumulator, +} from '../lib/highlightAccumulator' import { normalizeLanguage } from '../utils/languageUtils' +import { BoundedCache } from '../utils/boundedCache' +import { finishPerf, startPerf } from '../utils/perfTrace' import { THEME_SWITCH_DISABLE_MS } from '../constants' import { themeStore } from '../store/themeStore' +import { reportRenderFailure } from '../utils/renderDiagnostics' +import { isHighlightLanguageCoolingDown, markHighlightLanguageFailed } from '../lib/highlightCooldown' export type { HighlightTokens } from '../lib/highlightTypes' export type { ShikiThemeInput } from '../lib/shikiTheme' @@ -34,83 +43,23 @@ type IdleWindowApi = { type HighlightTask = () => Promise // ============================================ -// LRU 缓存层 - 避免重复高亮相同代码 +// 缓存层 - 避免重复高亮相同代码 // ============================================ -interface CacheEntry { - value: T - /** 估算成本(字符量 / token 数),用于按总量回收 */ - cost: number -} - -/** - * 带成本预算的 LRU。 - * - * 原来的实现只按条数回收:80 条 token 数组,赶上几个大文件就是几百 MB。 - * 现在同时受条数和总量限制,读命中也会移到队尾(真正的 LRU)。 - */ -class LRUCache { - private cache = new Map>() - private totalCost = 0 - private readonly maxSize: number - private readonly maxCost: number - private readonly costOf: (value: T) => number - - constructor(maxSize: number, maxCost = Number.POSITIVE_INFINITY, costOf: (value: T) => number = () => 1) { - this.maxSize = maxSize - this.maxCost = maxCost - this.costOf = costOf - } - - get(key: string): T | undefined { - const entry = this.cache.get(key) - if (!entry) return undefined - this.cache.delete(key) - this.cache.set(key, entry) - return entry.value - } - - set(key: string, value: T): void { - const cost = this.costOf(value) - const existing = this.cache.get(key) - if (existing) { - this.totalCost -= existing.cost - existing.value = value - existing.cost = cost - this.cache.delete(key) - this.cache.set(key, existing) - } else { - this.cache.set(key, { value, cost }) - } - this.totalCost += cost - this.trim() - } - - private trim(): void { - while (this.cache.size > this.maxSize || this.totalCost > this.maxCost) { - const oldest = this.cache.keys().next().value - if (oldest === undefined) break - this.totalCost -= this.cache.get(oldest)?.cost ?? 0 - this.cache.delete(oldest) - } - } - - clear(): void { - this.cache.clear() - this.totalCost = 0 - } - - get size(): number { - return this.cache.size - } -} - -const htmlCache = new LRUCache(120, 4 * 1024 * 1024, html => html.length) -const tokensCache = new LRUCache(80, 8 * 1024 * 1024, tokens => { - // 字符量 + 每个 token 的对象开销,粗略但足够决定回收顺序 - let cost = 0 - for (const line of tokens) for (const token of line) cost += token.content.length + 24 - return cost +const htmlCache = new BoundedCache({ + maxEntries: 120, + maxCost: 4 * 1024 * 1024, + costOf: html => html.length, +}) +const tokensCache = new BoundedCache({ + maxEntries: 80, + maxCost: 8 * 1024 * 1024, + costOf: tokens => { + // 字符量 + 每个 token 的对象开销,粗略但足够决定回收顺序 + let cost = 0 + for (const line of tokens) for (const token of line) cost += token.content.length + 24 + return cost + }, }) /** @@ -121,6 +70,8 @@ const tokensCache = new LRUCache(80, 8 * 1024 * 1024, tokens => const MAX_HIGHLIGHT_CHARS = 160 * 1024 /** 超过这个长度的结果不进缓存:一两条大文件就能把 LRU 撑成几百 MB */ const MAX_CACHED_HIGHLIGHT_CHARS = 64 * 1024 +/** 流式高亮的合并窗口:窗口内只把最新文本送给 worker */ +const STREAMING_HIGHLIGHT_INTERVAL_MS = 48 const highlightQueue: HighlightTask[] = [] let highlightQueueRunning = false @@ -181,6 +132,8 @@ async function highlightWithCache( themeKey: string, mode: 'html' | 'tokens', ): Promise { + if (isHighlightLanguageCoolingDown(lang)) return null + const cacheKey = getCacheKey(code, lang, themeKey) const cacheable = code.length <= MAX_CACHED_HIGHLIGHT_CHARS @@ -197,7 +150,9 @@ async function highlightWithCache( }) if (cacheable) htmlCache.set(cacheKey, html) return html - } catch { + } catch (err) { + reportRenderFailure('highlight', 'degraded', err) + if (!(err instanceof Error) || err.message !== 'superseded') markHighlightLanguageFailed(lang) return null } } else { @@ -205,16 +160,19 @@ async function highlightWithCache( if (cached !== undefined) return cached try { - const { tokens } = await highlightTokensInWorker({ + const { stable } = await highlightTokensInWorker({ key: `tokens:${cacheKey}:${highlightRequestId++}`, text: code, language: lang, theme, complete: true, }) + const tokens = splitTokensIntoLines(stable) if (cacheable) tokensCache.set(cacheKey, tokens) return tokens - } catch { + } catch (err) { + reportRenderFailure('highlight', 'degraded', err) + if (!(err instanceof Error) || err.message !== 'superseded') markHighlightLanguageFailed(lang) return null } } @@ -268,54 +226,133 @@ export function useStreamingSyntaxHighlight( const [outputState, setOutputState] = useState<{ code: string; tokens: HighlightTokens } | null>(null) const [isLoading, setIsLoading] = useState(false) const workerKeyRef = useRef('') - const codeRef = useRef(code) - codeRef.current = code + /** 按 worker key 累积增量 token;换语言/主题时整体丢弃 */ + const accumulatorRef = useRef<{ key: string; acc: HighlightAccumulator } | null>(null) const key = `${instanceId}:${normalizedLang}:${resolvedTheme.key}` + // 流式高亮不必跟满帧:worker 侧是 latest-only,主线程如果每帧都 postMessage, + // 只会反复结构化拷贝整段代码。这里固定一个合并窗口,窗口内只保留最后一次。 + const latestRef = useRef({ + code, + enabled, + key, + language: normalizedLang, + theme: resolvedTheme.theme, + }) + const timerRef = useRef(null) + const lastRequestAtRef = useRef(0) + const runRequestRef = useRef<() => void>(() => {}) + + const scheduleRequest = useCallback(() => { + if (timerRef.current !== null) return + const wait = Math.max(0, STREAMING_HIGHLIGHT_INTERVAL_MS - (performance.now() - lastRequestAtRef.current)) + timerRef.current = window.setTimeout(() => runRequestRef.current(), wait) + }, []) + useEffect(() => { + latestRef.current = { code, enabled, key, language: normalizedLang, theme: resolvedTheme.theme } + + runRequestRef.current = () => { + timerRef.current = null + const request = latestRef.current + if (!request.enabled || isHighlightLanguageCoolingDown(request.language)) { + setIsLoading(false) + return + } + + const isCurrent = () => latestRef.current.key === request.key && latestRef.current.enabled + const currentAccumulator = accumulatorRef.current + if (!currentAccumulator || currentAccumulator.key !== request.key) { + accumulatorRef.current = { key: request.key, acc: createHighlightAccumulator() } + } + + lastRequestAtRef.current = performance.now() + setIsLoading(true) + const startedAt = startPerf() + + void (async () => { + try { + const highlight = (forceReset?: boolean) => + highlightTokensInWorker({ + key: request.key, + text: request.code, + language: request.language, + theme: request.theme, + forceReset, + }) + + let chunk + try { + chunk = await highlight() + } catch (err) { + // 续传的前缀对不上(worker 侧流被丢弃或重开过):带全量文本重开一次 + if (!(err instanceof Error) || err.message !== 'stream-desync') throw err + chunk = await highlight(true) + } + if (!isCurrent()) return + + let state = accumulatorRef.current + if (!state || state.key !== request.key) return + let applied = applyHighlightChunk(state.acc, chunk) + + // 累积状态和 worker 对不上(上一拍被合并、或流被重开):要一次全量重排 + if (!applied.ok) { + chunk = await highlight(true) + if (!isCurrent()) return + state = accumulatorRef.current + if (!state || state.key !== request.key) return + applied = applyHighlightChunk(state.acc, chunk) + if (!applied.ok) return + } + + const tokens = applied.tokens + setOutputState(prev => (prev?.code === chunk.code ? prev : { code: chunk.code, tokens })) + } catch (err) { + if (import.meta.env.DEV && err instanceof Error && err.message !== 'superseded') { + reportRenderFailure('highlight', 'degraded', err) + } + // 语法/词法失败按语言冷却;superseded / 续传错位不是语法问题 + if (!(err instanceof Error) || (err.message !== 'superseded' && err.message !== 'stream-desync')) { + markHighlightLanguageFailed(request.language) + } + } finally { + finishPerf('highlight.stream', startedAt, 80, `${request.code.length} chars`) + if (isCurrent()) setIsLoading(false) + } + })() + } + if (!enabled) { + if (timerRef.current !== null) { + window.clearTimeout(timerRef.current) + timerRef.current = null + } + accumulatorRef.current = null if (workerKeyRef.current) { disposeShikiWorkerKey(workerKeyRef.current) workerKeyRef.current = '' } - setIsLoading(false) return } - let cancelled = false const previousKey = workerKeyRef.current - if (previousKey && previousKey !== key) disposeShikiWorkerKey(previousKey) - workerKeyRef.current = key - - // 同帧多次 code 变更只打一次 worker(读 codeRef 拿最新文本) - const frame = requestAnimationFrame(() => { - if (cancelled) return - const text = codeRef.current - setIsLoading(true) - void highlightTokensInWorker({ key, text, language: normalizedLang, theme: resolvedTheme.theme }) - .then(result => { - if (cancelled) return - setOutputState(prev => (prev?.code === result.code ? prev : { code: result.code, tokens: result.tokens })) - }) - .catch(err => { - if (import.meta.env.DEV && err instanceof Error && err.message !== 'superseded') { - console.warn('[Syntax] streaming Shiki worker error:', err) - } - }) - .finally(() => { - if (!cancelled) setIsLoading(false) - }) - }) - - return () => { - cancelled = true - cancelAnimationFrame(frame) + if (previousKey && previousKey !== key) { + disposeShikiWorkerKey(previousKey) + accumulatorRef.current = null + // 换语言/主题后旧 token 的颜色和语法都不对,先清掉等新结果 + // eslint-disable-next-line react-hooks/set-state-in-effect -- 与 worker 的旧输出解耦,属于外部状态同步 + setOutputState(null) + lastRequestAtRef.current = 0 } - }, [code, enabled, key, normalizedLang, resolvedTheme.theme]) + workerKeyRef.current = key + scheduleRequest() + }, [code, enabled, key, normalizedLang, resolvedTheme.theme, scheduleRequest]) useEffect(() => { return () => { + if (timerRef.current !== null) window.clearTimeout(timerRef.current) + timerRef.current = null if (workerKeyRef.current) disposeShikiWorkerKey(workerKeyRef.current) } }, []) @@ -397,9 +434,7 @@ export function useSyntaxHighlight(code: string, options: HighlightOptions & { m const result = await highlightWithCache(code, normalizedLang, resolvedTheme.theme, resolvedTheme.key, mode) if (!cancelled) setOutputState({ key: outputKey, value: result }) } catch (err) { - if (import.meta.env.DEV) { - console.warn('[Syntax] Shiki error:', err) - } + reportRenderFailure('highlight', 'degraded', err) if (!cancelled) setOutputState({ key: outputKey, value: null }) } finally { if (!cancelled) setIsLoading(false) @@ -507,9 +542,7 @@ export function useSyntaxHighlightRef( setVersion(v => v + 1) } } catch (err) { - if (import.meta.env.DEV) { - console.warn('[Syntax] Shiki error:', err) - } + reportRenderFailure('highlight', 'degraded', err) if (!cancelled) { tokensRef.current = null setVersion(v => v + 1) diff --git a/src/hooks/useTheme.ts b/src/hooks/useTheme.ts index 49e0424ca..93c9e649e 100644 --- a/src/hooks/useTheme.ts +++ b/src/hooks/useTheme.ts @@ -197,6 +197,18 @@ export function useTheme() { themeStore.setCodeWordWrap(enabled) }, []) + const setStreamPacingEnabled = useCallback((enabled: boolean) => { + themeStore.setStreamPacingEnabled(enabled) + }, []) + + const setStreamFadeEnabled = useCallback((enabled: boolean) => { + themeStore.setStreamFadeEnabled(enabled) + }, []) + + const setMarkdownCodeFoldEnabled = useCallback((enabled: boolean) => { + themeStore.setMarkdownCodeFoldEnabled(enabled) + }, []) + // ---- Font Scale ---- const setUIFontScale = useCallback((scale: number) => { @@ -350,6 +362,14 @@ export function useTheme() { codeWordWrap: state.codeWordWrap, setCodeWordWrap, + // 流式输出 + streamPacingEnabled: state.streamPacingEnabled, + setStreamPacingEnabled, + streamFadeEnabled: state.streamFadeEnabled, + setStreamFadeEnabled, + markdownCodeFoldEnabled: state.markdownCodeFoldEnabled, + setMarkdownCodeFoldEnabled, + // 界面字号偏移 uiFontScale: state.uiFontScale, setUIFontScale, diff --git a/src/index.css b/src/index.css index efe424945..070ca3043 100644 --- a/src/index.css +++ b/src/index.css @@ -577,6 +577,58 @@ body { margin-bottom: 0.5rem; } +/* GFM 任务列表:符号让位给勾选框,避免每行同时出现圆点和复选框 */ +.markdown-content li.task-list-item { + list-style: none; +} + +/* 嵌套列表换标记,跟参考的 unorderedMarkers/orderedMarkers 分层一致 */ +.markdown-content ul ul { + list-style-type: circle; +} + +.markdown-content ul ul ul { + list-style-type: square; +} + +.markdown-content ol ol { + list-style-type: lower-alpha; +} + +.markdown-content ol ol ol { + list-style-type: lower-roman; +} + +/* 链接的键盘焦点态:参考里链接有独立的 focus 样式 */ +.markdown-content a:focus-visible { + outline: 2px solid hsl(var(--accent-main-100) / 0.7); + outline-offset: 2px; + border-radius: 2px; +} + +/* 嵌在引用 / 列表里的代码块(顶层围栏走 CodeBlock,不经过这里) */ +.markdown-content .markdown-nested-code { + margin: 1rem 0; + padding: 0.75rem 0.875rem; + overflow-x: auto; + border: 1px solid hsl(var(--border-200) / 0.4); + border-radius: 6px; + background: hsl(var(--bg-200) / 0.4); + color: hsl(var(--text-200)); + font-family: var(--font-mono); + font-size: var(--fs-code); + line-height: var(--fs-code-line-height); + white-space: pre; +} + +.markdown-content .markdown-nested-code:first-child { + margin-top: 0; +} + +.markdown-content .markdown-nested-code:last-child { + margin-bottom: 0; +} + /* Sanitized rich HTML keeps native semantics while matching the Markdown surface. */ .markdown-content .markdown-html-table-scroll { max-width: 100%; @@ -628,6 +680,19 @@ body { text-align: right; } +/* marked 默认表格渲染(嵌在列表/引用里的表格)同样尊重列对齐 */ +.markdown-content :is(th, td)[align='center'] { + text-align: center; +} + +.markdown-content :is(th, td)[align='right'] { + text-align: right; +} + +.markdown-content :is(th, td)[align='left'] { + text-align: left; +} + .markdown-content .markdown-html-table tbody tr:hover > td { background: hsl(var(--bg-200) / 0.32); } diff --git a/src/lib/highlightAccumulator.test.ts b/src/lib/highlightAccumulator.test.ts new file mode 100644 index 000000000..ac64bbb2c --- /dev/null +++ b/src/lib/highlightAccumulator.test.ts @@ -0,0 +1,109 @@ +import { describe, expect, it } from 'vitest' +import { applyHighlightChunk, createHighlightAccumulator } from './highlightAccumulator' +import { splitTokensIntoLines } from './shikiWorkerClient' +import type { WorkerToken } from '../workers/shikiWorker' +import type { HighlightTokens } from './highlightTypes' + +function plainLines(tokens: HighlightTokens): string[][] { + return tokens.map(line => line.map(token => `${token.content}|${token.color ?? ''}`)) +} + +describe('highlightAccumulator', () => { + it('reset 一次性建出完整行,含跨行 token 拆分', () => { + const acc = createHighlightAccumulator() + const stable: WorkerToken[] = [ + ['const a', '#111'], + [' = 1;\nconst b', '#222'], + [' = 2;', '#333'], + ] + + const result = applyHighlightChunk(acc, { reset: true, stable, stableTotal: 3, unstable: [] }) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(plainLines(result.tokens)).toEqual([ + ['const a|#111', ' = 1;|#222'], + ['const b|#222', ' = 2;|#333'], + ]) + }) + + it('增量追加与全量切分结果一致,且不复制旧 token', () => { + const acc = createHighlightAccumulator() + const first: WorkerToken[] = [['const a', '#111']] + const firstResult = applyHighlightChunk(acc, { reset: true, stable: first, stableTotal: 1, unstable: [] }) + expect(firstResult.ok).toBe(true) + if (!firstResult.ok) return + + const second: WorkerToken[] = [[' = 1;\nconst b', '#222']] + const result = applyHighlightChunk(acc, { reset: false, stable: second, stableTotal: 2, unstable: [] }) + expect(result.ok).toBe(true) + if (!result.ok) return + + // 旧 token 对象被复用,没有重新构造 + expect(result.tokens[0][0]).toBe(firstResult.tokens[0][0]) + expect(plainLines(result.tokens)).toEqual(plainLines(splitTokensIntoLines([...first, ...second]))) + }) + + it('unstable 尾巴每拍整体替换,不会重复堆叠', () => { + const acc = createHighlightAccumulator() + const stable: WorkerToken[] = [['let x', '#111']] + applyHighlightChunk(acc, { reset: true, stable, stableTotal: 1, unstable: [[' =', '#222']] }) + + const result = applyHighlightChunk(acc, { + reset: false, + stable: [], + stableTotal: 1, + unstable: [[' = 1', '#222']], + }) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(plainLines(result.tokens)).toEqual([['let x|#111', ' = 1|#222']]) + }) + + it('stableTotal 对不上时报告 desync,且不污染累积状态', () => { + const acc = createHighlightAccumulator() + applyHighlightChunk(acc, { reset: true, stable: [['a', '#111']], stableTotal: 1, unstable: [] }) + + const result = applyHighlightChunk(acc, { + reset: false, + stable: [['b', '#222']], + stableTotal: 3, + unstable: [], + }) + + expect(result).toEqual({ ok: false, reason: 'desync' }) + expect(acc.stableCount).toBe(1) + }) + + it('desync 后用 reset 全量重建即可恢复', () => { + const acc = createHighlightAccumulator() + applyHighlightChunk(acc, { reset: true, stable: [['a', '#111']], stableTotal: 1, unstable: [] }) + applyHighlightChunk(acc, { reset: false, stable: [['b', '#222']], stableTotal: 3, unstable: [] }) + + const rebuilt = applyHighlightChunk(acc, { + reset: true, + stable: [['a', '#111'], ['b', '#222'], ['c', '#333']], + stableTotal: 3, + unstable: [], + }) + + expect(rebuilt.ok).toBe(true) + if (!rebuilt.ok) return + expect(plainLines(rebuilt.tokens)).toEqual([['a|#111', 'b|#222', 'c|#333']]) + }) + + it('unstable 里有换行时按行展开', () => { + const acc = createHighlightAccumulator() + const result = applyHighlightChunk(acc, { + reset: true, + stable: [['x', '#111']], + stableTotal: 1, + unstable: [['\ny', '#222']], + }) + + expect(result.ok).toBe(true) + if (!result.ok) return + expect(plainLines(result.tokens)).toEqual([['x|#111'], ['y|#222']]) + }) +}) diff --git a/src/lib/highlightAccumulator.ts b/src/lib/highlightAccumulator.ts new file mode 100644 index 000000000..00092657f --- /dev/null +++ b/src/lib/highlightAccumulator.ts @@ -0,0 +1,76 @@ +import type { WorkerToken } from '../workers/shikiWorker' +import type { HighlightTokens } from './highlightTypes' + +/** + * 流式高亮的增量累积器。 + * + * worker 每拍只回传「新稳定下来的 token + 当前 unstable 尾巴」,客户端在这里按行累积。 + * 只在 reset 或不同步(stableTotal 对不上)时才需要全量重建。 + */ +export type HighlightAccumulator = { + /** 已稳定的行,最后一行可能为空行 */ + lines: HighlightTokens + /** 已累积的 stable token 数,对应 worker 响应里的 stableTotal */ + stableCount: number +} + +export type HighlightChunk = { + reset: boolean + stable: WorkerToken[] + stableTotal: number + unstable: WorkerToken[] +} + +export type ApplyHighlightResult = + | { ok: true; tokens: HighlightTokens } + | { ok: false; reason: 'desync' } + +export function createHighlightAccumulator(): HighlightAccumulator { + return { lines: [[]], stableCount: 0 } +} + +function appendToken(lines: HighlightTokens, [content, color]: WorkerToken) { + const segments = content.split('\n') + for (let index = 0; index < segments.length; index += 1) { + const segment = segments[index] + if (segment) { + const token = { content: segment, color } + lines[lines.length - 1].push(token) + } + if (index < segments.length - 1) lines.push([]) + } +} + +function appendTokens(lines: HighlightTokens, tokens: WorkerToken[]) { + for (const token of tokens) { + if (!token[0]) continue + appendToken(lines, token) + } +} + +/** 把 unstable 尾巴接在 stable 行后面,返回给渲染用的完整行;不修改稳定区 */ +function withTail(stableLines: HighlightTokens, unstable: WorkerToken[]): HighlightTokens { + const lines = stableLines.slice(0, -1) + const last = stableLines[stableLines.length - 1] ?? [] + lines.push(last.slice()) + appendTokens(lines, unstable) + return lines +} + +export function applyHighlightChunk(accumulator: HighlightAccumulator, chunk: HighlightChunk): ApplyHighlightResult { + if (chunk.reset) { + accumulator.lines = [[]] + appendTokens(accumulator.lines, chunk.stable) + accumulator.stableCount = chunk.stable.length + } else { + if (accumulator.stableCount + chunk.stable.length !== chunk.stableTotal) { + return { ok: false, reason: 'desync' } + } + if (chunk.stable.length > 0) { + appendTokens(accumulator.lines, chunk.stable) + accumulator.stableCount += chunk.stable.length + } + } + + return { ok: true, tokens: withTail(accumulator.lines, chunk.unstable) } +} diff --git a/src/lib/highlightCooldown.test.ts b/src/lib/highlightCooldown.test.ts new file mode 100644 index 000000000..ed3791c81 --- /dev/null +++ b/src/lib/highlightCooldown.test.ts @@ -0,0 +1,32 @@ +import { beforeEach, describe, expect, it } from 'vitest' +import { + isHighlightLanguageCoolingDown, + markHighlightLanguageFailed, + resetHighlightCooldownsForTests, +} from './highlightCooldown' + +describe('highlightCooldown', () => { + beforeEach(() => { + resetHighlightCooldownsForTests() + }) + + it('失败后进入冷却,窗口结束自动恢复', () => { + markHighlightLanguageFailed('Wolfram', 1_000) + expect(isHighlightLanguageCoolingDown('wolfram', 1_500)).toBe(true) + expect(isHighlightLanguageCoolingDown('wolfram', 60_999)).toBe(true) + expect(isHighlightLanguageCoolingDown('wolfram', 61_000)).toBe(false) + expect(isHighlightLanguageCoolingDown('wolfram', 61_001)).toBe(false) + }) + + it('只影响失败的那门语言', () => { + markHighlightLanguageFailed('wolfram', 1_000) + expect(isHighlightLanguageCoolingDown('typescript', 2_000)).toBe(false) + }) + + it('重复失败会刷新窗口', () => { + markHighlightLanguageFailed('php', 1_000) + markHighlightLanguageFailed('php', 30_000) + expect(isHighlightLanguageCoolingDown('php', 80_000)).toBe(true) + expect(isHighlightLanguageCoolingDown('php', 90_001)).toBe(false) + }) +}) diff --git a/src/lib/highlightCooldown.ts b/src/lib/highlightCooldown.ts new file mode 100644 index 000000000..d5e69ecd5 --- /dev/null +++ b/src/lib/highlightCooldown.ts @@ -0,0 +1,38 @@ +/** + * 语法加载失败的短期降级。 + * + * 某一门语言的 grammar 编译/加载失败时,下一个 48ms tick 还会再试一次, + * 流式期间等于持续打 worker。这里按语言记一个冷却窗口,期间直接按纯文本渲染; + * 只影响这一门语言,不影响其它代码块。 + */ +const COOLDOWN_MS = 60_000 +const MAX_LANGUAGES = 32 + +const cooldowns = new Map() + +export function markHighlightLanguageFailed(language: string, now = Date.now()): void { + const lang = language.toLowerCase() + cooldowns.delete(lang) + cooldowns.set(lang, now + COOLDOWN_MS) + while (cooldowns.size > MAX_LANGUAGES) { + const oldest = cooldowns.keys().next().value + if (oldest == null) break + cooldowns.delete(oldest) + } +} + +export function isHighlightLanguageCoolingDown(language: string, now = Date.now()): boolean { + const lang = language.toLowerCase() + const until = cooldowns.get(lang) + if (until === undefined) return false + if (until <= now) { + cooldowns.delete(lang) + return false + } + return true +} + +/** 仅供测试 */ +export function resetHighlightCooldownsForTests(): void { + cooldowns.clear() +} diff --git a/src/lib/markdownWorkerClient.test.ts b/src/lib/markdownWorkerClient.test.ts new file mode 100644 index 000000000..524d107d2 --- /dev/null +++ b/src/lib/markdownWorkerClient.test.ts @@ -0,0 +1,106 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import type { MarkdownWorkerRequest } from '../workers/markdownWorker' +import { + parseMarkdownInWorker, + resetMarkdownWorkerClientForTests, + type MarkdownParseResult, +} from './markdownWorkerClient' + +class FakeWorker { + static instances: FakeWorker[] = [] + static throwOnCreate = false + + posted: MarkdownWorkerRequest[] = [] + onmessage: ((event: { data: unknown }) => void) | null = null + onerror: ((event: { preventDefault?: () => void }) => void) | null = null + terminated = false + + constructor() { + if (FakeWorker.throwOnCreate) throw new Error('Worker unavailable') + FakeWorker.instances.push(this) + } + + postMessage(message: MarkdownWorkerRequest) { + this.posted.push(message) + } + + terminate() { + this.terminated = true + } + + respond(message: unknown) { + this.onmessage?.({ data: message }) + } +} + +const originalWorker = globalThis.Worker + +function flush() { + return new Promise(resolve => { + setTimeout(resolve, 0) + }) +} + +beforeEach(() => { + resetMarkdownWorkerClientForTests() + FakeWorker.instances = [] + FakeWorker.throwOnCreate = false + globalThis.Worker = FakeWorker as unknown as typeof Worker +}) + +afterEach(() => { + resetMarkdownWorkerClientForTests() + globalThis.Worker = originalWorker +}) + +describe('markdownWorkerClient', () => { + it('返回解析结果并带上对应的 src', async () => { + const promise = parseMarkdownInWorker({ key: 'a', src: '# hi', isReasoning: false, renderHtml: true }) + const worker = FakeWorker.instances[0]! + expect(worker.posted[0]?.src).toBe('# hi') + + worker.respond({ type: 'parsed', id: worker.posted[0]!.id, key: 'a', html: '

    hi

    ' }) + + await expect(promise).resolves.toEqual({ status: 'ok', src: '# hi', html: '

    hi

    ' }) + }) + + it('排队中的同一块只解析最新内容', async () => { + const first = parseMarkdownInWorker({ key: 'a', src: 'first', isReasoning: false, renderHtml: true }) + const second = parseMarkdownInWorker({ key: 'b', src: 'old', isReasoning: false, renderHtml: true }) + const third = parseMarkdownInWorker({ key: 'b', src: 'new', isReasoning: false, renderHtml: true }) + + const worker = FakeWorker.instances[0]! + worker.respond({ type: 'parsed', id: worker.posted[0]!.id, key: 'a', html: 'first' }) + await flush() + + expect(worker.posted).toHaveLength(2) + expect(worker.posted[1]?.src).toBe('new') + + worker.respond({ type: 'parsed', id: worker.posted[1]!.id, key: 'b', html: 'new' }) + + expect(await first).toEqual({ status: 'ok', src: 'first', html: 'first' }) + const merged: Array = [await second, await third] + expect(merged).toEqual([ + { status: 'ok', src: 'new', html: 'new' }, + { status: 'ok', src: 'new', html: 'new' }, + ]) + }) + + it('worker 创建失败时返回 unavailable,交给主线程兜底', async () => { + FakeWorker.throwOnCreate = true + await expect( + parseMarkdownInWorker({ key: 'a', src: 'x', isReasoning: false, renderHtml: true }), + ).resolves.toEqual({ status: 'unavailable' }) + }) + + it('worker 崩溃时结算所有等待者并进入冷却', async () => { + const promise = parseMarkdownInWorker({ key: 'a', src: 'x', isReasoning: false, renderHtml: true }) + const worker = FakeWorker.instances[0]! + worker.onerror?.({}) + + await expect(promise).resolves.toEqual({ status: 'unavailable' }) + await expect( + parseMarkdownInWorker({ key: 'b', src: 'y', isReasoning: false, renderHtml: true }), + ).resolves.toEqual({ status: 'unavailable' }) + }) +}) diff --git a/src/lib/markdownWorkerClient.ts b/src/lib/markdownWorkerClient.ts new file mode 100644 index 000000000..92e240242 --- /dev/null +++ b/src/lib/markdownWorkerClient.ts @@ -0,0 +1,184 @@ +import type { MarkdownWorkerRequest, MarkdownWorkerResponse } from '../workers/markdownWorker' +import { reportRenderFailure } from '../utils/renderDiagnostics' + +export type MarkdownParseResult = + /** 解析成功;`src` 是这次解析的输入,调用方据此判断是否已经过期 */ + | { status: 'ok'; src: string; html: string } + /** worker 不可用(环境不支持或连续失败),调用方回退到主线程同步解析 */ + | { status: 'unavailable' } + /** 同一个块已经有更新的请求,这次结果可以丢弃 */ + | { status: 'superseded' } + +export type MarkdownParseParams = { + /** 每个 Markdown 块一个稳定的 key,用于合并同一块的连续请求 */ + key: string + src: string + isReasoning: boolean + renderHtml: boolean +} + +type Waiter = (result: MarkdownParseResult) => void + +type ParseJob = { + id: number + key: string + src: string + isReasoning: boolean + renderHtml: boolean + waiters: Waiter[] +} + +let worker: Worker | null = null +let nextId = 1 +let draining = false +/** worker 创建失败后冷却一段时间,避免每个大块都尝试新建一次 */ +let unavailableUntil = 0 + +const UNAVAILABLE_COOLDOWN_MS = 5000 + +const queue: ParseJob[] = [] +const queuedByKey = new Map() +const pending = new Map() + +function isAvailable(): boolean { + return performance.now() >= unavailableUntil +} + +function markUnavailable() { + unavailableUntil = performance.now() + UNAVAILABLE_COOLDOWN_MS +} + +function resolveJob(job: ParseJob, result: MarkdownParseResult) { + for (const waiter of job.waiters) waiter(result) + job.waiters = [] +} + +function failPending() { + worker?.terminate() + worker = null + markUnavailable() + pending.forEach(({ resolve }) => resolve({ status: 'unavailable' })) + pending.clear() + for (const job of queue) resolveJob(job, { status: 'unavailable' }) + queue.length = 0 + queuedByKey.clear() +} + +function getWorker(): Worker | null { + if (worker) return worker + if (!isAvailable()) return null + + try { + worker = new Worker(new URL('../workers/markdownWorker.ts', import.meta.url), { type: 'module' }) + } catch (error) { + reportRenderFailure('markdown', 'degraded', error) + markUnavailable() + return null + } + + worker.onmessage = (event: MessageEvent) => { + const msg = event.data + const entry = pending.get(msg.id) + if (!entry) return + pending.delete(msg.id) + if (msg.type === 'parsed') { + entry.resolve({ status: 'ok', src: entry.job.src, html: msg.html }) + } else { + // 解析抛错:让调用方走同步路径,行为与以前一致 + reportRenderFailure('markdown', 'degraded', msg.message) + entry.resolve({ status: 'unavailable' }) + } + } + + worker.onerror = event => { + event.preventDefault?.() + reportRenderFailure('markdown', 'retryable', 'markdown worker crashed') + failPending() + } + + return worker +} + +function sendJob(job: ParseJob): Promise { + const w = getWorker() + if (!w) return Promise.resolve({ status: 'unavailable' }) + + return new Promise(resolve => { + pending.set(job.id, { job, resolve }) + w.postMessage({ + type: 'parse', + id: job.id, + key: job.key, + src: job.src, + isReasoning: job.isReasoning, + renderHtml: job.renderHtml, + } satisfies MarkdownWorkerRequest) + }) +} + +async function drain() { + if (draining) return + draining = true + try { + while (queue.length > 0) { + const job = queue.shift() + if (!job) break + queuedByKey.delete(job.key) + const result = await sendJob(job) + resolveJob(job, result) + } + } finally { + draining = false + } +} + +/** + * 把 Markdown 解析交给 worker。 + * + * 同一个 key 的请求在排队阶段会合并:只解析最新的内容,旧请求统一拿最新结果 + * (调用方按 `src` 判断是否过期)。worker 不可用时返回 `unavailable`。 + */ +export function parseMarkdownInWorker(params: MarkdownParseParams): Promise { + const existing = queuedByKey.get(params.key) + if (existing) { + existing.src = params.src + existing.isReasoning = params.isReasoning + existing.renderHtml = params.renderHtml + return new Promise(resolve => existing.waiters.push(resolve)) + } + + const job: ParseJob = { + id: nextId++, + key: params.key, + src: params.src, + isReasoning: params.isReasoning, + renderHtml: params.renderHtml, + waiters: [], + } + const result = new Promise(resolve => job.waiters.push(resolve)) + queue.push(job) + queuedByKey.set(job.key, job) + void drain() + return result +} + +/** 块卸载或内容回退时取消排队中的解析,已在解析的请求结果由调用方忽略 */ +export function cancelMarkdownParse(key: string) { + const job = queuedByKey.get(key) + if (!job) return + queuedByKey.delete(key) + const index = queue.indexOf(job) + if (index >= 0) queue.splice(index, 1) + resolveJob(job, { status: 'superseded' }) +} + +/** 仅测试用:重置内部状态 */ +export function resetMarkdownWorkerClientForTests() { + worker?.terminate() + worker = null + unavailableUntil = 0 + queue.length = 0 + queuedByKey.clear() + pending.clear() + draining = false +} diff --git a/src/lib/shikiStreamRequest.test.ts b/src/lib/shikiStreamRequest.test.ts new file mode 100644 index 000000000..14a3d6a35 --- /dev/null +++ b/src/lib/shikiStreamRequest.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { buildHighlightRequest, type HighlightRequestParams } from './shikiStreamRequest' + +const baseParams: HighlightRequestParams = { + id: 7, + key: 'block:ts:github-dark-default', + text: 'const a = 1\n', + language: 'ts', + theme: 'github-dark-default', + mode: 'tokens', +} + +describe('buildHighlightRequest', () => { + it('无在途请求且只是前缀增长时只发新增片段', () => { + const message = buildHighlightRequest(baseParams, { confirmedText: 'const a', inFlight: 0 }) + + expect(message.append).toBe(' = 1\n') + expect(message.baseLength).toBe(7) + expect(message.text).toBeUndefined() + }) + + it('有在途请求时发全量,避免 worker 位置和客户端认知错位', () => { + const message = buildHighlightRequest(baseParams, { confirmedText: 'const a', inFlight: 1 }) + + expect(message.text).toBe(baseParams.text) + expect(message.append).toBeUndefined() + }) + + it('文本不是前缀增长时发全量', () => { + const message = buildHighlightRequest( + { ...baseParams, text: 'let b = 2' }, + { confirmedText: 'const a', inFlight: 0 }, + ) + + expect(message.text).toBe('let b = 2') + expect(message.append).toBeUndefined() + }) + + it('强制重开、一次性完整排版、html 模式都发全量', () => { + expect(buildHighlightRequest({ ...baseParams, forceReset: true }, { confirmedText: 'const a', inFlight: 0 }).text).toBe( + baseParams.text, + ) + expect(buildHighlightRequest({ ...baseParams, complete: true }, { confirmedText: 'const a', inFlight: 0 }).text).toBe( + baseParams.text, + ) + expect( + buildHighlightRequest({ ...baseParams, mode: 'html' }, { confirmedText: 'const a', inFlight: 0 }).text, + ).toBe(baseParams.text) + }) + + it('还没有确认过前缀时发全量', () => { + const message = buildHighlightRequest(baseParams, { confirmedText: '', inFlight: 0 }) + + expect(message.text).toBe(baseParams.text) + expect(message.append).toBeUndefined() + }) +}) diff --git a/src/lib/shikiStreamRequest.ts b/src/lib/shikiStreamRequest.ts new file mode 100644 index 000000000..3348b450e --- /dev/null +++ b/src/lib/shikiStreamRequest.ts @@ -0,0 +1,68 @@ +import type { BundledTheme } from 'shiki/themes' +import type { WorkerRequest } from '../workers/shikiWorker' + +export type HighlightRequestParams = { + id: number + key: string + text: string + language: string + theme: BundledTheme + mode: 'tokens' | 'html' + complete?: boolean + forceReset?: boolean +} + +export type HighlightStreamState = { + /** worker 里这条流已经处理到的完整文本 */ + confirmedText: string + /** 这个 key 上还没回来的请求数 */ + inFlight: number +} + +export type HighlightRequestMessage = Extract + +/** + * 决定这一拍发「全量文本」还是「只发新增片段」。 + * + * 增量只在同时满足这些条件时成立:tokens 流式、没有在途请求(否则 worker 的位置 + * 可能已经被上一拍推进)、不是强制重开、文本确实是在已确认前缀上继续增长。 + * 其他情况一律发全量,让 worker 自己决定要不要重开流。 + */ +export function buildHighlightRequest( + params: HighlightRequestParams, + state: HighlightStreamState, +): HighlightRequestMessage { + const canAppend = + params.mode === 'tokens' && + !params.complete && + !params.forceReset && + state.inFlight === 0 && + state.confirmedText.length > 0 && + params.text.startsWith(state.confirmedText) + + if (!canAppend) { + return { + type: 'highlight', + id: params.id, + key: params.key, + text: params.text, + language: params.language, + theme: params.theme, + mode: params.mode, + complete: params.complete, + forceReset: params.forceReset, + } + } + + return { + type: 'highlight', + id: params.id, + key: params.key, + append: params.text.slice(state.confirmedText.length), + baseLength: state.confirmedText.length, + language: params.language, + theme: params.theme, + mode: params.mode, + forceReset: params.forceReset, + } +} diff --git a/src/lib/shikiWorkerClient.ts b/src/lib/shikiWorkerClient.ts index da849aead..972446e89 100644 --- a/src/lib/shikiWorkerClient.ts +++ b/src/lib/shikiWorkerClient.ts @@ -1,6 +1,9 @@ import type { BundledTheme } from 'shiki/themes' import type { WorkerRequest, WorkerResponse, WorkerToken } from '../workers/shikiWorker' import type { HighlightTokens } from './highlightTypes' +import { buildHighlightRequest } from './shikiStreamRequest' +import { reportRenderFailure } from '../utils/renderDiagnostics' +import { notePerf } from '../utils/perfTrace' import { DEFAULT_CODE_BLOCK_THEME_DARK, DEFAULT_CODE_BLOCK_THEME_LIGHT, @@ -19,18 +22,43 @@ let workerReadyPromiseReject: ((error: unknown) => void) | null = null let nextId = 1 const pendingRequests = new Map() -/** 每个代码块实例一个 key;长会话里会一直累积,给个上限(只用于丢弃过期请求) */ -const latestRequestByKey = new Map() -const MAX_LATEST_REQUEST_KEYS = 800 - -function rememberLatestRequest(key: string, id: number) { - latestRequestByKey.delete(key) - latestRequestByKey.set(key, id) - while (latestRequestByKey.size > MAX_LATEST_REQUEST_KEYS) { - const oldest = latestRequestByKey.keys().next().value + +/** + * 每个流式代码块一个 key。记录 worker 里这条流的位置(confirmedText), + * 只有「没有在途请求且文本是前缀增长」时才发增量,否则发全量。 + * 长会话里 key 会一直累积,给个上限(被淘汰只会退化成发全量,不影响正确性)。 + */ +type KeyStreamState = { + latestId: number + confirmedText: string + inFlight: number +} + +const keyStates = new Map() +const MAX_TRACKED_KEYS = 800 + +function stateFor(key: string): KeyStreamState { + const existing = keyStates.get(key) + if (existing) { + // 顺带做 LRU:重新插到末尾 + keyStates.delete(key) + keyStates.set(key, existing) + return existing + } + + const state: KeyStreamState = { latestId: 0, confirmedText: '', inFlight: 0 } + keyStates.set(key, state) + while (keyStates.size > MAX_TRACKED_KEYS) { + const oldest = keyStates.keys().next().value if (oldest === undefined) break - latestRequestByKey.delete(oldest) + keyStates.delete(oldest) } + return state +} + +function isSuperseded(key: string, id: number): boolean { + const latest = keyStates.get(key)?.latestId + return latest !== undefined && latest !== 0 && latest !== id } function getWorker(): Worker { @@ -47,6 +75,7 @@ function getWorker(): Worker { } if (msg.type === 'init-error') { + reportRenderFailure('highlight', 'terminal', msg.message) workerReadyPromiseReject?.(new Error(msg.message)) workerReady = null workerReadyPromiseResolve = null @@ -71,6 +100,7 @@ function getWorker(): Worker { } worker.onerror = error => { + reportRenderFailure('highlight', 'terminal', error) workerReadyPromiseReject?.(error) pendingRequests.forEach(pending => pending.reject(error)) pendingRequests.clear() @@ -105,7 +135,7 @@ export function ensureShikiWorkerReady(): Promise { return workerReady } -function splitTokensIntoLines(tokens: WorkerToken[]): HighlightTokens { +export function splitTokensIntoLines(tokens: WorkerToken[]): HighlightTokens { if (tokens.length === 0) return [[]] const lines: HighlightTokens = [] @@ -134,6 +164,11 @@ function splitTokensIntoLines(tokens: WorkerToken[]): HighlightTokens { return lines } +/** 单次高亮超过这个耗时就在 dev 打一条,用来找病态 grammar / 超大块 */ +const SLOW_HIGHLIGHT_MS = 120 +const SLOW_LOG_INTERVAL_MS = 5_000 +const slowLoggedAt = new Map() + async function workerHighlight(params: { key: string text: string @@ -141,35 +176,85 @@ async function workerHighlight(params: { theme: BundledTheme mode: 'tokens' | 'html' complete?: boolean + forceReset?: boolean }): Promise> { await ensureShikiWorkerReady() const id = nextId++ const w = getWorker() - rememberLatestRequest(params.key, id) + const state = stateFor(params.key) + state.latestId = id + const startedAt = performance.now() + + const message = buildHighlightRequest( + { + id, + key: params.key, + text: params.text, + language: params.language, + theme: params.theme, + mode: params.mode, + complete: params.complete, + forceReset: params.forceReset, + }, + state, + ) - return new Promise>((resolve, reject) => { - pendingRequests.set(id, { - resolve: resolve as (response: WorkerResponse) => void, - reject, + state.inFlight += 1 + try { + const response = await new Promise>((resolve, reject) => { + pendingRequests.set(id, { resolve: resolve as (response: WorkerResponse) => void, reject }) + w.postMessage(message) }) - w.postMessage({ type: 'highlight', id, ...params } satisfies WorkerRequest) - }) + // worker 顺序处理同一个 key,这条响应生效后流的位置就是本次请求的文本 + state.confirmedText = params.text + const elapsed = performance.now() - startedAt + if (elapsed >= SLOW_HIGHLIGHT_MS) { + const now = performance.now() + const last = slowLoggedAt.get(params.language) ?? 0 + if (now - last >= SLOW_LOG_INTERVAL_MS) { + slowLoggedAt.set(params.language, now) + notePerf('highlight.slow', `${elapsed.toFixed(0)}ms ${params.language} ${params.text.length}chars`) + } + } + return response + } finally { + state.inFlight = Math.max(0, state.inFlight - 1) + } } +export type HighlightTokensChunk = { + id: number + code: string + reset: boolean + stable: WorkerToken[] + stableTotal: number + unstable: WorkerToken[] +} + +/** + * 流式高亮:返回增量片段,由调用方用 `applyHighlightChunk` 累积。 + * + * 不再在这里抛 `superseded`:worker 对同一个 key 是顺序处理的, + * 迟到的响应也是流上一段合法前缀,丢给调用方按顺序应用即可; + * 真正的过期由调用方检查 key 决定是否采用。 + */ export async function highlightTokensInWorker(params: { key: string text: string language: string theme: BundledTheme complete?: boolean -}): Promise<{ id: number; code: string; tokens: HighlightTokens }> { + forceReset?: boolean +}): Promise { const result = await workerHighlight({ ...params, mode: 'tokens' }) - if (isSuperseded(params.key, result.id)) throw new Error('superseded') return { id: result.id, - code: result.code, - tokens: splitTokensIntoLines([...result.stable, ...result.unstable]), + code: params.text, + reset: result.reset, + stable: result.stable, + stableTotal: result.stableTotal, + unstable: result.unstable, } } @@ -184,18 +269,9 @@ export async function highlightHtmlInWorker(params: { return { id: result.id, html: result.html ?? '' } } -/** - * 键被 LRU 淘汰(`get` 为 undefined)时不能判成过期: - * 那只是「这张表不记得了」,请求本身仍然有效。 - */ -function isSuperseded(key: string, id: number): boolean { - const latest = latestRequestByKey.get(key) - return latest !== undefined && latest !== id -} - export function disposeShikiWorkerKey(key: string) { if (!worker) return worker.postMessage({ type: 'dispose', key } satisfies WorkerRequest) - latestRequestByKey.delete(key) + keyStates.delete(key) } diff --git a/src/locales/en/settings.json b/src/locales/en/settings.json index 67e086873..abc36c138 100644 --- a/src/locales/en/settings.json +++ b/src/locales/en/settings.json @@ -205,6 +205,14 @@ "renderUserMarkdownDesc": "Render sent user messages as Markdown when enabled; keep plain text when disabled", "renderHtmlContent": "Render HTML Content", "renderHtmlContentDesc": "Render HTML in AI output as live preview; show HTML as source code when disabled", + "markdownCodeFold": "Fold Long Code Blocks", + "markdownCodeFoldDesc": "Long code blocks in replies start collapsed with their own scrollbar; expand anytime to read the whole block", + "streamRendering": "Streaming", + "streamRenderingDesc": "How assistant text is revealed while it arrives", + "streamPacing": "Character pacing", + "streamPacingDesc": "Reveal streamed text gradually instead of dumping it in chunks", + "streamFade": "Tail fade", + "streamFadeDesc": "Gently fade in newly revealed text at the end of a streaming message", "outlineCurrentHighlight": "Highlight Current Position", "outlineCurrentHighlightDesc": "Mark the user prompt that owns the current viewport in the right-side history rail", "actionsOnLatestAssistantOnly": "Actions on latest reply only", diff --git a/src/locales/zh-CN/settings.json b/src/locales/zh-CN/settings.json index fc62d3e24..1570e66f4 100644 --- a/src/locales/zh-CN/settings.json +++ b/src/locales/zh-CN/settings.json @@ -205,6 +205,14 @@ "renderUserMarkdownDesc": "开启后,用户发送的消息会按 Markdown 渲染;关闭时保持纯文本显示", "renderHtmlContent": "渲染 HTML 内容", "renderHtmlContentDesc": "开启时将 AI 输出中的 HTML 渲染为实时预览,关闭后一律按源码展示", + "markdownCodeFold": "折叠长代码块", + "markdownCodeFoldDesc": "回复里的长代码块默认收起为可滚动区域,可随时展开查看全文", + "streamRendering": "流式输出", + "streamRenderingDesc": "助手文字到达时如何在屏幕上呈现", + "streamPacing": "逐字节奏", + "streamPacingDesc": "把网络到达的文本按节奏逐渐显示,而不是整段跳出", + "streamFade": "尾部淡入", + "streamFadeDesc": "流式消息末尾新出现的文字做轻微淡入", "outlineCurrentHighlight": "高亮当前对话位置", "outlineCurrentHighlightDesc": "在右侧历史导航条中标出当前视口所属的用户提示词", "actionsOnLatestAssistantOnly": "仅末尾显示操作按钮", diff --git a/src/store/messageStore.test.ts b/src/store/messageStore.test.ts index bfb3dee3c..d2fcb71be 100644 --- a/src/store/messageStore.test.ts +++ b/src/store/messageStore.test.ts @@ -1189,3 +1189,52 @@ describe('inbox 物化与投递(官方 materializeInboxMessage / inbox.deliver expect(messageStore.getSessionState(SESSION)?.messages.map(m => m.id)).toEqual(['msg-a1']) }) }) + +describe('会话持有量与闲置回收', () => { + beforeEach(() => { + messageStore.clearAll() + }) + + it('getHeldChatSize 按正文量统计,并按体积排序', () => { + messageStore.setMessages('s-small', [createUserMessage('u1')]) + messageStore.setMessages('s-big', [ + createUserMessage('u1'), + createAssistantMessage('a1', textContent('xxxxx'), 1), + ]) + + const held = messageStore.getHeldChatSize() + + expect(held.totalMessages).toBe(3) + expect(held.sessions[0]).toEqual({ sessionId: 's-big', messages: 2, chars: 'u1'.length + 5 }) + expect(held.sessions[1]).toEqual({ sessionId: 's-small', messages: 1, chars: 'u1'.length }) + }) + + it('trimIdleSessions 只保留最近使用的会话', () => { + messageStore.setMessages('s-a', [createUserMessage('a')]) + messageStore.setMessages('s-b', [createUserMessage('b')]) + messageStore.setMessages('s-c', [createUserMessage('c')]) + + expect(messageStore.trimIdleSessions(1).sort()).toEqual(['s-a', 's-b']) + expect(messageStore.getSessionState('s-c')).toBeDefined() + expect(messageStore.getSessionState('s-a')).toBeUndefined() + }) + + it('正在流式和受分屏保护的会话不会被回收', () => { + // time.completed 缺省 = 仍在流式 + messageStore.setMessages('s-stream', [createAssistantMessage('a1', textContent('x'))]) + messageStore.setMessages('s-keep', [createUserMessage('k')]) + messageStore.protectSession('s-keep') + messageStore.setMessages('s-old', [createUserMessage('o')]) + + expect(messageStore.trimIdleSessions(0)).toEqual(['s-old']) + expect(messageStore.getSessionState('s-stream')).toBeDefined() + expect(messageStore.getSessionState('s-keep')).toBeDefined() + + messageStore.unprotectSession('s-keep') + }) + + it('没有超出保留数时不做任何事', () => { + messageStore.setMessages('s-a', [createUserMessage('a')]) + expect(messageStore.trimIdleSessions(2)).toEqual([]) + }) +}) diff --git a/src/store/messageStore.ts b/src/store/messageStore.ts index 10384729f..1b3540a92 100644 --- a/src/store/messageStore.ts +++ b/src/store/messageStore.ts @@ -37,6 +37,7 @@ import type { GlobalEvent, SessionMessageInfo } from '../types/api/event' import type { SessionInboxInfo } from '@opencode/client/promise' import type { SessionRevert } from '../types/api/session' import { contentEntries, isUserMessage, userMessageText } from '../types/api/message' +import { estimateMessageChars } from '../utils/messageSize' import type { Attachment } from '../types/ui' import type { APIError } from '../types/api/common' import { logger } from '../utils/logger' @@ -104,6 +105,14 @@ type CompactionFailed = Extract const MAX_CACHED_SESSIONS = 10 +/** 会话持有量诊断用 */ +export type HeldSessionSize = { + sessionId: string + messages: number + chars: number +} +/** 乱序进度暂存上限(正常会在 called 时立即取走) */ +const PENDING_TOOL_PROGRESS_LIMIT = 2048 /** * 由事件 id 派生消息 id。 @@ -240,6 +249,13 @@ class MessageStore { metadata: ToolPayload<'session.tool.progress'>['metadata'], ) { this.pendingToolProgress.set(MessageStore.toolProgressKey(sessionID, assistantMessageID, partId), metadata) + // 只服务于乱序/回放;正常路径 called 会立刻取走。给个上限, + // 防止长期运行里永远等不到 called 的孤儿进度一直堆着 + while (this.pendingToolProgress.size > PENDING_TOOL_PROGRESS_LIMIT) { + const oldest = this.pendingToolProgress.keys().next().value + if (oldest === undefined) break + this.pendingToolProgress.delete(oldest) + } } private takePendingToolProgress( @@ -533,6 +549,9 @@ class MessageStore { this.sessions.delete(oldestId) this.sessionAccessTime.delete(oldestId) this.dirtyContentBySession.delete(oldestId) + for (const key of this.pendingToolProgress.keys()) { + if (key.startsWith(`${oldestId}:`)) this.pendingToolProgress.delete(key) + } } } @@ -810,6 +829,59 @@ class MessageStore { this.notify([sessionId]) } + /** + * 统计当前持有的会话数据量。 + * + * 只给诊断用:长会话到底占多少内存,靠猜没用。字符数是正文量的下界估算, + * 不含工具入参和 DOM,但足以看出「是不是这个会话特别肥」。 + */ + getHeldChatSize(): { sessions: HeldSessionSize[]; totalMessages: number; totalChars: number } { + const sessions: HeldSessionSize[] = [] + let totalMessages = 0 + let totalChars = 0 + for (const [sessionId, state] of this.sessions) { + let chars = 0 + for (const message of state.messages) chars += estimateMessageChars(message) + sessions.push({ sessionId, messages: state.messages.length, chars }) + totalMessages += state.messages.length + totalChars += chars + } + sessions.sort((a, b) => b.chars - a.chars) + return { sessions, totalMessages, totalChars } + } + + /** + * 释放不活跃会话,只保留最近使用的 `keep` 个。 + * + * 正在流式、或被分屏 pane 保护的会话不动。被释放的会话下次打开时会重新从 + * 服务端拉最近一页(滚动位置和已加载历史会重置),这是有意的取舍: + * 后台闲置时把内存让出来,比留着一堆没人看的会话更划算。 + */ + trimIdleSessions(keep: number): string[] { + if (this.sessions.size <= keep) return [] + + // Date.now() 同毫秒内插入的会话时间相同,用 Map 的插入顺序兜底,结果才稳定 + const candidates = Array.from(this.sessionAccessTime.entries()) + .map(([id, time], index) => ({ id, time, index })) + .filter(({ id }) => !this.protectedSessions.has(id) && !this.sessions.get(id)?.isStreaming) + .sort((a, b) => b.time - a.time || b.index - a.index) + + const evicted: string[] = [] + for (const { id } of candidates.slice(Math.max(0, keep))) { + this.sessions.delete(id) + this.sessionAccessTime.delete(id) + this.dirtyContentBySession.delete(id) + this.sessionVersions.delete(id) + for (const key of this.pendingToolProgress.keys()) { + if (key.startsWith(`${id}:`)) this.pendingToolProgress.delete(key) + } + evicted.push(id) + } + + if (evicted.length) this.notify(evicted) + return evicted + } + /** * 用一条权威消息整条落库(重新读取 message.list / 单条 message.get 后的回填)。 * diff --git a/src/store/themeStore.test.ts b/src/store/themeStore.test.ts index 6fa752150..d06f474df 100644 --- a/src/store/themeStore.test.ts +++ b/src/store/themeStore.test.ts @@ -1,6 +1,44 @@ import { beforeEach, describe, expect, it } from 'vitest' import { themeStore } from './themeStore' +describe('themeStore · 流式输出设置', () => { + it('默认开启逐字节奏与尾部淡入', () => { + expect(themeStore.streamPacingEnabled).toBe(true) + expect(themeStore.streamFadeEnabled).toBe(true) + }) + + it('开关会持久化,便于还原为无淡入的原版观感', () => { + themeStore.setStreamFadeEnabled(false) + expect(themeStore.streamFadeEnabled).toBe(false) + expect(localStorage.getItem('stream-fade-enabled')).toBe('false') + + themeStore.setStreamPacingEnabled(false) + expect(themeStore.streamPacingEnabled).toBe(false) + expect(localStorage.getItem('stream-pacing-enabled')).toBe('false') + + themeStore.setStreamPacingEnabled(true) + themeStore.setStreamFadeEnabled(true) + expect(localStorage.getItem('stream-pacing-enabled')).toBe('true') + expect(localStorage.getItem('stream-fade-enabled')).toBe('true') + }) +}) + +describe('themeStore · 长代码块折叠', () => { + it('默认开启', () => { + expect(themeStore.markdownCodeFoldEnabled).toBe(true) + }) + + it('开关会持久化', () => { + themeStore.setMarkdownCodeFoldEnabled(false) + expect(themeStore.markdownCodeFoldEnabled).toBe(false) + expect(localStorage.getItem('markdown-code-fold-enabled')).toBe('false') + + themeStore.setMarkdownCodeFoldEnabled(true) + expect(themeStore.markdownCodeFoldEnabled).toBe(true) + expect(localStorage.getItem('markdown-code-fold-enabled')).toBe('true') + }) +}) + describe('themeStore · 对话列/输入框自定义宽度(chatContentWidth / chatInputWidth)', () => { beforeEach(() => { localStorage.clear() diff --git a/src/store/themeStore.ts b/src/store/themeStore.ts index 09f686382..0d7d2b3be 100644 --- a/src/store/themeStore.ts +++ b/src/store/themeStore.ts @@ -158,6 +158,12 @@ const DEFAULT_RENDER_USER_MARKDOWN = false // 默认不渲染:AI 输出里的 HTML 一律按源码展示(要活预览可在设置里显式打开)。 // HTML 活渲染是个有副作用的开关(iframe / 脚本),默认开的风险大于收益。 const DEFAULT_RENDER_HTML_CONTENT = false +/** 流式文本按节奏揭示(可关闭以回到「数据到达即整段显示」) */ +const DEFAULT_STREAM_PACING_ENABLED = true +/** 新出现的尾部文字做淡入 */ +const DEFAULT_STREAM_FADE_ENABLED = true +/** 长 Markdown 代码块默认折叠(限高可滚动,可展开) */ +const DEFAULT_MARKDOWN_CODE_FOLD_ENABLED = true const DEFAULT_DIFF_STYLE: DiffStyle = 'markers' const DEFAULT_DESCRIPTIVE_TOOL_STEPS = true const DEFAULT_INLINE_TOOL_REQUESTS = true @@ -279,6 +285,12 @@ export interface ThemeState { renderUserMarkdown: boolean /** 是否渲染 AI 输出中的 HTML(关闭后 HTML 一律按源码展示) */ renderHtmlContent: boolean + /** 流式文本按节奏揭示 */ + streamPacingEnabled: boolean + /** 流式文本尾部淡入 */ + streamFadeEnabled: boolean + /** 长 Markdown 代码块默认折叠 */ + markdownCodeFoldEnabled: boolean /** step-finish 信息栏显示开关 */ stepFinishDisplay: StepFinishDisplay /** 完成时刻显示格式 */ @@ -385,6 +397,9 @@ const STORAGE_KEY_ACTIVE_CUSTOM_CSS_SNIPPET_ID = 'theme-active-custom-css-snippe const STORAGE_KEY_COLLAPSE_USER_MESSAGES = 'collapse-user-messages' const STORAGE_KEY_RENDER_USER_MARKDOWN = 'render-user-markdown' const STORAGE_KEY_RENDER_HTML_CONTENT = 'render-html-content' +const STORAGE_KEY_STREAM_PACING_ENABLED = 'stream-pacing-enabled' +const STORAGE_KEY_STREAM_FADE_ENABLED = 'stream-fade-enabled' +const STORAGE_KEY_MARKDOWN_CODE_FOLD_ENABLED = 'markdown-code-fold-enabled' const STORAGE_KEY_STEP_FINISH_DISPLAY = 'step-finish-display' const STORAGE_KEY_COMPLETED_AT_FORMAT = 'completed-at-format' const STORAGE_KEY_REASONING_DISPLAY_MODE = 'reasoning-display-mode' @@ -491,6 +506,14 @@ class ThemeStore { const savedRenderHtmlContent = localStorage.getItem(STORAGE_KEY_RENDER_HTML_CONTENT) const renderHtmlContent = savedRenderHtmlContent === null ? DEFAULT_RENDER_HTML_CONTENT : savedRenderHtmlContent === 'true' + const savedStreamPacing = localStorage.getItem(STORAGE_KEY_STREAM_PACING_ENABLED) + const streamPacingEnabled = + savedStreamPacing === null ? DEFAULT_STREAM_PACING_ENABLED : savedStreamPacing === 'true' + const savedStreamFade = localStorage.getItem(STORAGE_KEY_STREAM_FADE_ENABLED) + const streamFadeEnabled = savedStreamFade === null ? DEFAULT_STREAM_FADE_ENABLED : savedStreamFade === 'true' + const savedMarkdownCodeFold = localStorage.getItem(STORAGE_KEY_MARKDOWN_CODE_FOLD_ENABLED) + const markdownCodeFoldEnabled = + savedMarkdownCodeFold === null ? DEFAULT_MARKDOWN_CODE_FOLD_ENABLED : savedMarkdownCodeFold === 'true' const savedReasoningDisplay = localStorage.getItem(STORAGE_KEY_REASONING_DISPLAY_MODE) const reasoningDisplayMode: ReasoningDisplayMode = savedReasoningDisplay === 'italic' || savedReasoningDisplay === 'markdown' @@ -670,6 +693,9 @@ class ThemeStore { collapseUserMessages, renderUserMarkdown, renderHtmlContent, + streamPacingEnabled, + streamFadeEnabled, + markdownCodeFoldEnabled, stepFinishDisplay, completedAtFormat, reasoningDisplayMode, @@ -748,6 +774,15 @@ class ThemeStore { get renderHtmlContent() { return this.state.renderHtmlContent } + get streamPacingEnabled() { + return this.state.streamPacingEnabled + } + get streamFadeEnabled() { + return this.state.streamFadeEnabled + } + get markdownCodeFoldEnabled() { + return this.state.markdownCodeFoldEnabled + } get stepFinishDisplay() { return this.state.stepFinishDisplay } @@ -1093,6 +1128,27 @@ class ThemeStore { this.emit() } + setStreamPacingEnabled(enabled: boolean) { + if (this.state.streamPacingEnabled === enabled) return + this.state = { ...this.state, streamPacingEnabled: enabled } + localStorage.setItem(STORAGE_KEY_STREAM_PACING_ENABLED, String(enabled)) + this.emit() + } + + setStreamFadeEnabled(enabled: boolean) { + if (this.state.streamFadeEnabled === enabled) return + this.state = { ...this.state, streamFadeEnabled: enabled } + localStorage.setItem(STORAGE_KEY_STREAM_FADE_ENABLED, String(enabled)) + this.emit() + } + + setMarkdownCodeFoldEnabled(enabled: boolean) { + if (this.state.markdownCodeFoldEnabled === enabled) return + this.state = { ...this.state, markdownCodeFoldEnabled: enabled } + localStorage.setItem(STORAGE_KEY_MARKDOWN_CODE_FOLD_ENABLED, String(enabled)) + this.emit() + } + setStepFinishDisplay(display: Partial) { const next = { ...this.state.stepFinishDisplay, ...display } this.state = { ...this.state, stepFinishDisplay: next } @@ -1780,6 +1836,14 @@ function normalizeThemeBackup(raw: unknown): ThemeBackup { typeof parsed?.renderUserMarkdown === 'boolean' ? parsed.renderUserMarkdown : DEFAULT_RENDER_USER_MARKDOWN, renderHtmlContent: typeof parsed?.renderHtmlContent === 'boolean' ? parsed.renderHtmlContent : DEFAULT_RENDER_HTML_CONTENT, + streamPacingEnabled: + typeof parsed?.streamPacingEnabled === 'boolean' ? parsed.streamPacingEnabled : DEFAULT_STREAM_PACING_ENABLED, + streamFadeEnabled: + typeof parsed?.streamFadeEnabled === 'boolean' ? parsed.streamFadeEnabled : DEFAULT_STREAM_FADE_ENABLED, + markdownCodeFoldEnabled: + typeof parsed?.markdownCodeFoldEnabled === 'boolean' + ? parsed.markdownCodeFoldEnabled + : DEFAULT_MARKDOWN_CODE_FOLD_ENABLED, stepFinishDisplay: parsed?.stepFinishDisplay && typeof parsed.stepFinishDisplay === 'object' ? { ...DEFAULT_STEP_FINISH_DISPLAY, ...(parsed.stepFinishDisplay as Partial) } @@ -1913,6 +1977,10 @@ export function importThemeBackup(raw: unknown): void { } localStorage.setItem(STORAGE_KEY_COLLAPSE_USER_MESSAGES, String(backup.collapseUserMessages)) localStorage.setItem(STORAGE_KEY_RENDER_USER_MARKDOWN, String(backup.renderUserMarkdown)) + localStorage.setItem(STORAGE_KEY_RENDER_HTML_CONTENT, String(backup.renderHtmlContent)) + localStorage.setItem(STORAGE_KEY_STREAM_PACING_ENABLED, String(backup.streamPacingEnabled)) + localStorage.setItem(STORAGE_KEY_STREAM_FADE_ENABLED, String(backup.streamFadeEnabled)) + localStorage.setItem(STORAGE_KEY_MARKDOWN_CODE_FOLD_ENABLED, String(backup.markdownCodeFoldEnabled)) localStorage.setItem(STORAGE_KEY_STEP_FINISH_DISPLAY, JSON.stringify(backup.stepFinishDisplay)) localStorage.setItem(STORAGE_KEY_COMPLETED_AT_FORMAT, backup.completedAtFormat) localStorage.setItem(STORAGE_KEY_REASONING_DISPLAY_MODE, backup.reasoningDisplayMode) diff --git a/src/types/api/message.test.ts b/src/types/api/message.test.ts index bcd2bc20d..e22883a05 100644 --- a/src/types/api/message.test.ts +++ b/src/types/api/message.test.ts @@ -76,6 +76,34 @@ describe('contentEntries — 内容 id 派生', () => { expect(entries[0].content).toBe(content) }) + + it('同一消息对象复用派生结果,原地改文本不需要重建', () => { + const content = { type: 'text' as const, text: 'a' } + const message = assistant({ content: [content] }) + + const first = contentEntries(message) + content.text = 'ab' + const second = contentEntries(message) + + expect(second).toBe(first) + expect(second[0].content).toBe(content) + expect((second[0].content as { text: string }).text).toBe('ab') + }) + + it('追加内容(push)或整体替换数组后重建派生结果', () => { + const message = assistant({ content: [{ type: 'text', text: 'a' }] }) + const first = contentEntries(message) + + message.content.push({ type: 'reasoning', text: 'r' }) + const afterPush = contentEntries(message) + expect(afterPush).not.toBe(first) + expect(afterPush.map(entry => entry.id)).toEqual(['msg_1:text:0', 'msg_1:reasoning:0']) + + message.content = [{ type: 'text', text: 'b' }] + const afterReplace = contentEntries(message) + expect(afterReplace).not.toBe(afterPush) + expect(afterReplace.map(entry => entry.id)).toEqual(['msg_1:text:0']) + }) }) describe('resolveContent — 按 id 反查', () => { @@ -106,6 +134,14 @@ describe('判别与文本辅助', () => { expect(isUserMessage(assistant())).toBe(false) }) + it('hasVisibleText 在文本原地增长后重新判断', () => { + const content = { type: 'text' as const, text: ' ' } + expect(hasVisibleText(content)).toBe(false) + + content.text = ' 有内容' + expect(hasVisibleText(content)).toBe(true) + }) + it('assistantText 拼接全部 text 片段(忽略 reasoning / tool)', () => { const message = assistant({ content: [ diff --git a/src/types/api/message.ts b/src/types/api/message.ts index b7bf3d884..2c3a0866a 100644 --- a/src/types/api/message.ts +++ b/src/types/api/message.ts @@ -191,12 +191,25 @@ export type ContentEntry = { } /** 给助手消息的 content 数组补齐稳定 id(与官方算法一致) */ +const contentEntriesCache = new WeakMap< + AssistantMessage, + { source: AssistantContent[]; length: number; entries: Array } +>() + export function contentEntries(message: AssistantMessage): Array { + const cached = contentEntriesCache.get(message) + // 流式期间 text/reasoning 是原地改字段,content 数组与长度都不变,缓存仍然有效; + // 追加内容(push)会改长度,整体替换会换数组引用,两种情况都重建。 + if (cached && cached.source === message.content && cached.length === message.content.length) { + return cached.entries + } const ordinals = { text: 0, reasoning: 0 } - return message.content.map(content => ({ + const entries = message.content.map(content => ({ id: content.type === 'tool' ? content.id : `${message.id}:${content.type}:${ordinals[content.type]++}`, content, })) + contentEntriesCache.set(message, { source: message.content, length: message.content.length, entries }) + return entries } /** 按派生 id 反查内容条目(与官方 resolveContent 同一算法,单次遍历) */ @@ -211,8 +224,17 @@ export function resolveContent(message: SessionMessage | undefined, partID: stri } /** 文本类内容(text / reasoning)是否为「可见正文」(非空白) */ +const visibleTextCache = new WeakMap() + export function hasVisibleText(content: AssistantContent): boolean { - return content.type === 'text' || content.type === 'reasoning' ? content.text.trim().length > 0 : false + if (content.type !== 'text' && content.type !== 'reasoning') return false + const cached = visibleTextCache.get(content) + // 流式增量是给 text 换新字符串:引用/值变了才重新 trim, + // 稳定消息与未改动的片段直接命中,避免每帧扫描整段正文 + if (cached && cached.text === content.text) return cached.visible + const visible = content.text.trim().length > 0 + visibleTextCache.set(content, { text: content.text, visible }) + return visible } /** diff --git a/src/utils/boundedCache.test.ts b/src/utils/boundedCache.test.ts new file mode 100644 index 000000000..d2948a142 --- /dev/null +++ b/src/utils/boundedCache.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it } from 'vitest' +import { BoundedCache } from './boundedCache' + +describe('BoundedCache', () => { + it('evicts the least recently used entry', () => { + const cache = new BoundedCache({ maxEntries: 2 }) + cache.set('a', 1) + cache.set('b', 2) + expect(cache.get('a')).toBe(1) + cache.set('c', 3) + + expect(cache.get('b')).toBeUndefined() + expect(cache.get('a')).toBe(1) + expect(cache.get('c')).toBe(3) + }) + + it('evicts by total cost as well as entry count', () => { + const cache = new BoundedCache({ + maxEntries: 10, + maxCost: 10, + costOf: value => value.length, + }) + cache.set('a', '12345') + cache.set('b', '67890') + cache.set('c', 'x') + + expect(cache.size).toBe(2) + expect(cache.get('a')).toBeUndefined() + expect(cache.get('b')).toBe('67890') + expect(cache.get('c')).toBe('x') + expect(cache.cost).toBe(6) + }) + + it('keeps a single oversized value until the next write', () => { + const cache = new BoundedCache({ + maxEntries: 4, + maxCost: 4, + costOf: value => value.length, + }) + cache.set('huge', '123456789') + + expect(cache.get('huge')).toBe('123456789') + cache.set('small', 'x') + expect(cache.get('huge')).toBeUndefined() + expect(cache.get('small')).toBe('x') + }) + + it('updates an existing key without double counting cost', () => { + const cache = new BoundedCache({ + maxEntries: 10, + maxCost: 100, + costOf: value => value.length, + }) + cache.set('a', '12345') + cache.set('a', '123') + + expect(cache.size).toBe(1) + expect(cache.cost).toBe(3) + expect(cache.get('a')).toBe('123') + }) + + it('supports delete and clear', () => { + const cache = new BoundedCache({ maxEntries: 4, maxCost: 10 }) + cache.set('a', 1) + cache.set('b', 2) + expect(cache.delete('a')).toBe(true) + expect(cache.delete('a')).toBe(false) + expect(cache.cost).toBe(1) + cache.clear() + expect(cache.size).toBe(0) + expect(cache.cost).toBe(0) + }) +}) diff --git a/src/utils/boundedCache.ts b/src/utils/boundedCache.ts new file mode 100644 index 000000000..89a0d1b40 --- /dev/null +++ b/src/utils/boundedCache.ts @@ -0,0 +1,92 @@ +/** + * 有上限的 LRU 缓存。 + * + * 消息渲染链路上有多个“内容相关”的缓存(Markdown HTML、分块结果、Mermaid SVG、 + * 高亮 token、折叠状态)。它们都需要同样的行为: + * - 命中即刷新为最近使用 + * - 同时受条数和估算成本约束 + * - 单个超大值不能把刚写入的条目立刻挤掉 + * + * 以前每个文件各写一份手写淘汰循环,口径容易漂移。统一在这里实现。 + */ +export interface BoundedCacheOptions { + /** 最大条数 */ + maxEntries: number + /** 最大总成本;不传表示只按条数限制 */ + maxCost?: number + /** 单个值的成本估算,默认 1 */ + costOf?: (value: T) => number +} + +interface CacheEntry { + value: T + cost: number +} + +export class BoundedCache { + private readonly entries = new Map>() + private readonly maxEntries: number + private readonly maxCost: number + private readonly costOf: (value: V) => number + private totalCost = 0 + + constructor(options: BoundedCacheOptions) { + this.maxEntries = Math.max(1, Math.floor(options.maxEntries)) + this.maxCost = options.maxCost != null && Number.isFinite(options.maxCost) ? options.maxCost : Number.POSITIVE_INFINITY + this.costOf = options.costOf ?? (() => 1) + } + + get(key: K): V | undefined { + const entry = this.entries.get(key) + if (!entry) return undefined + // Map 的插入顺序即 LRU:命中后移到队尾 + this.entries.delete(key) + this.entries.set(key, entry) + return entry.value + } + + set(key: K, value: V): void { + const cost = this.costOf(value) + const existing = this.entries.get(key) + if (existing) { + this.totalCost -= existing.cost + this.entries.delete(key) + } + this.entries.set(key, { value, cost }) + this.totalCost += cost + this.trim(key) + } + + delete(key: K): boolean { + const entry = this.entries.get(key) + if (!entry) return false + this.totalCost -= entry.cost + return this.entries.delete(key) + } + + clear(): void { + this.entries.clear() + this.totalCost = 0 + } + + get size(): number { + return this.entries.size + } + + /** 当前累计成本,测试与调试用 */ + get cost(): number { + return this.totalCost + } + + private trim(protectedKey: K): void { + while (this.entries.size > this.maxEntries || this.totalCost > this.maxCost) { + const oldest = this.entries.keys().next().value + if (oldest === undefined) break + // 只写了一个超大值时不立刻自我淘汰:下一次写入会把它挤出去 + if (this.entries.size === 1 && oldest === protectedKey) break + const entry = this.entries.get(oldest) + this.entries.delete(oldest) + if (entry) this.totalCost -= entry.cost + } + } +} diff --git a/src/utils/contentBudget.ts b/src/utils/contentBudget.ts index cdd128722..9468df06d 100644 --- a/src/utils/contentBudget.ts +++ b/src/utils/contentBudget.ts @@ -39,11 +39,12 @@ export interface CroppedContent { const EMPTY: CroppedContent = { text: '', cropped: false, omittedChars: 0, omittedLines: 0 } -function countNewlines(text: string): number { +function countNewlines(text: string, limit = Number.POSITIVE_INFINITY): number { let count = 0 let index = text.indexOf('\n') while (index !== -1) { count += 1 + if (count >= limit) return count index = text.indexOf('\n', index + 1) } return count @@ -81,10 +82,13 @@ export function cropContent(text: string, options: CropOptions = {}): CroppedCon const headRatio = Math.min(0.9, Math.max(0.2, options.headRatio ?? 0.6)) const marker = options.marker ?? '…' - const lineCount = countNewlines(text) + 1 - if (text.length <= maxChars && lineCount <= maxLines) { + // 先只数到行数上限:大块输出通常在 900 行内就够判断, + // 没必要为了一个「没超预算」的结论把整段文本扫两遍。 + const probedNewlines = countNewlines(text, maxLines + 1) + if (text.length <= maxChars && probedNewlines <= maxLines) { return { text, cropped: false, omittedChars: 0, omittedLines: 0 } } + const totalLineCount = probedNewlines > maxLines ? countNewlines(text) + 1 : probedNewlines + 1 const headBudget = Math.floor(maxChars * headRatio) const tailBudget = Math.floor(maxChars * 0.3) @@ -93,11 +97,11 @@ export function cropContent(text: string, options: CropOptions = {}): CroppedCon let tailStart = cutAtNextNewline(text, Math.max(headEnd, text.length - tailBudget)) // 行数超限:按行切,再用字符预算收紧(单行超长文本走字符预算) - if (lineCount > maxLines) { + if (totalLineCount > maxLines) { const headLines = Math.max(1, Math.floor(maxLines * headRatio)) const tailLines = Math.max(1, Math.floor(maxLines * 0.3)) headEnd = lineStartOffset(text, headLines) - tailStart = lineStartOffset(text, Math.max(headLines + 1, lineCount - tailLines)) + tailStart = lineStartOffset(text, Math.max(headLines + 1, totalLineCount - tailLines)) if (headEnd > headBudget) headEnd = cutAfterNewline(text, headBudget) if (text.length - tailStart > tailBudget) tailStart = cutAtNextNewline(text, text.length - tailBudget) } @@ -112,7 +116,7 @@ export function cropContent(text: string, options: CropOptions = {}): CroppedCon // 头/尾都从行边界切;末尾没有换行时最后一行也算一行 const headLines = countNewlines(head) + (head.endsWith('\n') ? 0 : 1) const tailLines = countNewlines(tail) + (tail.endsWith('\n') ? 0 : 1) - const omittedLines = Math.max(0, lineCount - headLines - tailLines) + const omittedLines = Math.max(0, totalLineCount - headLines - tailLines) const omittedChars = Math.max(0, text.length - head.length - tail.length) return { diff --git a/src/utils/frameSampler.test.ts b/src/utils/frameSampler.test.ts new file mode 100644 index 000000000..693c717f5 --- /dev/null +++ b/src/utils/frameSampler.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest' +import { createFrameStatsAccumulator } from './frameSampler' + +describe('frameSampler', () => { + it('没有采样时返回 null', () => { + expect(createFrameStatsAccumulator().snapshot()).toBeNull() + }) + + it('统计平均帧、最长帧与掉帧数', () => { + const accumulator = createFrameStatsAccumulator() + // 16.7ms 连续 10 帧 + 一帧 50ms + for (let index = 0; index < 10; index += 1) accumulator.add(16.7) + accumulator.add(50) + + const stats = accumulator.snapshot() + expect(stats).not.toBeNull() + if (!stats) return + + expect(stats.frames).toBe(11) + expect(stats.longestFrameMs).toBe(50) + // 16.7ms ≈ 1 帧预算,不额外掉帧;50ms ≈ 3 帧预算,掉 2 帧 + expect(stats.droppedFrames).toBe(2) + expect(stats.longFrameRatio).toBeCloseTo(1 / 11, 5) + expect(stats.avgFrameMs).toBeCloseTo((16.7 * 10 + 50) / 11, 5) + }) + + it('p95 落在慢帧桶上', () => { + const accumulator = createFrameStatsAccumulator() + for (let index = 0; index < 94; index += 1) accumulator.add(8) + for (let index = 0; index < 6; index += 1) accumulator.add(40) + + const stats = accumulator.snapshot() + expect(stats?.p95FrameMs).toBe(40) + }) + + it('忽略非法间隔,超大间隔落在最后一个桶', () => { + const accumulator = createFrameStatsAccumulator() + accumulator.add(-1) + accumulator.add(Number.NaN) + accumulator.add(5000) + + const stats = accumulator.snapshot() + expect(stats?.frames).toBe(1) + expect(stats?.longestFrameMs).toBe(5000) + expect(stats?.p95FrameMs).toBe(199) + }) +}) diff --git a/src/utils/frameSampler.ts b/src/utils/frameSampler.ts new file mode 100644 index 000000000..7e6ee1d03 --- /dev/null +++ b/src/utils/frameSampler.ts @@ -0,0 +1,135 @@ +/** + * 流式期间的掉帧采样(仅开发期使用)。 + * + * 用 1ms 桶记录每帧间隔,内存固定;结束时给出 p95、最长帧、掉帧比例。 + * 只在 dev 里由 ChatArea 在流式开始/结束时启停,生产构建不会实例化。 + */ +const FRAME_BUDGET_MS = 1000 / 60 +/** 超过这个间隔就算一次明显卡顿(3 帧以上) */ +const LONG_FRAME_MS = 50 +const BUCKET_COUNT = 200 + +export type FrameStats = { + frames: number + spanMs: number + avgFrameMs: number + p95FrameMs: number + longestFrameMs: number + droppedFrames: number + longFrameRatio: number +} + +export type FrameStatsAccumulator = { + add: (deltaMs: number) => void + snapshot: () => FrameStats | null +} + +export function createFrameStatsAccumulator(): FrameStatsAccumulator { + const buckets = new Uint32Array(BUCKET_COUNT) + let frames = 0 + let spanMs = 0 + let longestMs = 0 + let droppedFrames = 0 + + return { + add(deltaMs) { + if (!Number.isFinite(deltaMs) || deltaMs < 0) return + frames += 1 + spanMs += deltaMs + if (deltaMs > longestMs) longestMs = deltaMs + droppedFrames += Math.max(0, Math.round(deltaMs / FRAME_BUDGET_MS) - 1) + const bucket = Math.min(BUCKET_COUNT - 1, Math.floor(deltaMs)) + buckets[bucket] += 1 + }, + snapshot() { + if (frames === 0) return null + + let longFrames = 0 + for (let index = LONG_FRAME_MS; index < BUCKET_COUNT; index += 1) longFrames += buckets[index] + + const p95Rank = Math.ceil(frames * 0.95) + let seen = 0 + let p95FrameMs = 0 + for (let index = 0; index < BUCKET_COUNT; index += 1) { + seen += buckets[index] + if (seen >= p95Rank) { + p95FrameMs = index + break + } + } + + return { + frames, + spanMs, + avgFrameMs: spanMs / frames, + p95FrameMs, + longestFrameMs: longestMs, + droppedFrames, + longFrameRatio: longFrames / frames, + } + }, + } +} + +export type FrameSampler = { + start: () => void + stop: () => FrameStats | null +} + +/** 采样器本身不判断环境,调用方决定是否启用 */ +export function createFrameSampler(): FrameSampler { + let handle: number | null = null + let lastTime = 0 + let accumulator: FrameStatsAccumulator | null = null + + const tick = (time: number) => { + if (!accumulator) return + if (typeof document !== 'undefined' && document.visibilityState === 'hidden') { + // 后台标签页的 rAF 间隔没有意义,跳过这一段 + lastTime = time + } else if (lastTime > 0) { + accumulator.add(time - lastTime) + lastTime = time + } else { + lastTime = time + } + handle = requestAnimationFrame(tick) + } + + return { + start() { + if (typeof requestAnimationFrame === 'undefined') return + if (handle !== null) return + accumulator = createFrameStatsAccumulator() + lastTime = 0 + handle = requestAnimationFrame(tick) + }, + stop() { + if (handle !== null) cancelAnimationFrame(handle) + handle = null + lastTime = 0 + const stats = accumulator?.snapshot() ?? null + accumulator = null + return stats + }, + } +} + +let lastFrameReport: { label: string; stats: FrameStats; at: number } | null = null + +/** 最近一次流式帧统计(dev 诊断面板用) */ +export function getLastFrameStats(): { label: string; stats: FrameStats; at: number } | null { + return lastFrameReport +} + +export function reportFrameStats(label: string, stats: FrameStats | null): void { + if (!stats) return + lastFrameReport = { label, stats, at: Date.now() } + if (stats.frames < 10) return + if (stats.longFrameRatio < 0.02 && stats.p95FrameMs < 32) return + console.warn( + `[perf] ${label} frames=${stats.frames} avg=${stats.avgFrameMs.toFixed(1)}ms ` + + `p95=${stats.p95FrameMs}ms max=${stats.longestFrameMs.toFixed(1)}ms ` + + `dropped=${stats.droppedFrames} long=${(stats.longFrameRatio * 100).toFixed(1)}%`, + ) +} diff --git a/src/utils/messageSize.test.ts b/src/utils/messageSize.test.ts new file mode 100644 index 000000000..dae4e6983 --- /dev/null +++ b/src/utils/messageSize.test.ts @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest' +import type { SessionMessageInfo } from '../types/api/message' +import { estimateMessageChars, estimateMessagesChars } from './messageSize' + +function asMessage(value: object): SessionMessageInfo { + return value as SessionMessageInfo +} + +const base = { id: 'msg', time: { created: 1 } } + +function tool(state: object) { + return { type: 'tool', id: 'tool-1', name: 'bash', state, time: { created: 1 } } +} + +describe('messageSize', () => { + it('用户 / 系统 / 合成消息按正文长度算', () => { + expect(estimateMessageChars(asMessage({ ...base, type: 'user', text: '你好' }))).toBe(2) + expect(estimateMessageChars(asMessage({ ...base, type: 'system', text: 'note' }))).toBe(4) + expect(estimateMessageChars(asMessage({ ...base, type: 'synthetic', text: 'abc' }))).toBe(3) + }) + + it('助手消息累加正文、推理和工具产出文本', () => { + const message = asMessage({ + ...base, + type: 'assistant', + content: [ + { type: 'text', text: '123' }, + { type: 'reasoning', text: '45' }, + { + ...tool({ + status: 'completed', + input: {}, + content: [ + { type: 'text', text: '6789' }, + { type: 'file', uri: 'file://x', mime: 'text/plain' }, + ], + }), + }, + ], + }) + + expect(estimateMessageChars(message)).toBe(3 + 2 + 4) + }) + + it('运行中的工具按 metadata.output 估算,流式工具按半截 input', () => { + const running = asMessage({ + ...base, + type: 'assistant', + content: [{ ...tool({ status: 'running', input: {}, metadata: { output: 'abcdef' } }) }], + }) + expect(estimateMessageChars(running)).toBe(6) + + const streaming = asMessage({ + ...base, + type: 'assistant', + content: [{ ...tool({ status: 'streaming', input: '{"a":1}' }) }], + }) + expect(estimateMessageChars(streaming)).toBe(7) + }) + + it('shell 消息算命令加输出', () => { + const message = asMessage({ + ...base, + type: 'shell', + shellID: 'sh', + command: 'ls -la', + status: 'exited', + output: { output: 'total 0', cursor: 0, size: 7, truncated: false }, + }) + expect(estimateMessageChars(message)).toBe(6 + 7) + }) + + it('列表求和', () => { + const messages = [ + asMessage({ ...base, type: 'user', text: 'aa' }), + asMessage({ ...base, type: 'synthetic', text: 'bbb' }), + ] + expect(estimateMessagesChars(messages)).toBe(5) + }) +}) diff --git a/src/utils/messageSize.ts b/src/utils/messageSize.ts new file mode 100644 index 000000000..d687ba530 --- /dev/null +++ b/src/utils/messageSize.ts @@ -0,0 +1,55 @@ +import type { SessionMessageInfo } from '../types/api/message' + +/** + * 估算一条消息占用的正文字符量。 + * + * 只统计真正会被渲染/持有的文本:正文、推理、工具产出、shell 输出。 + * 不序列化工具入参(那是纯 CPU 开销,而且通常远小于产出), + * 因此这是下界估算,但足够用来判断「这一页是不是特别肥」。 + */ +export function estimateMessageChars(message: SessionMessageInfo): number { + switch (message.type) { + case 'user': + return message.text?.length ?? 0 + case 'system': + case 'synthetic': + return message.text?.length ?? 0 + case 'skill': + return message.text?.length ?? 0 + case 'shell': + return (message.command?.length ?? 0) + (message.output?.output.length ?? 0) + case 'assistant': { + let total = 0 + for (const part of message.content) { + if (part.type === 'text' || part.type === 'reasoning') { + total += part.text.length + continue + } + if (part.type !== 'tool') continue + const state = part.state + if (state.status === 'completed' || state.status === 'error') { + const content = state.content + if (content) { + for (const item of content) { + if (item.type === 'text') total += item.text.length + } + } + } else if (state.status === 'running') { + const output = state.metadata.output + if (typeof output === 'string') total += output.length + } else if (state.status === 'streaming') { + total += state.input.length + } + } + return total + } + default: + return 0 + } +} + +export function estimateMessagesChars(messages: readonly SessionMessageInfo[]): number { + let total = 0 + for (const message of messages) total += estimateMessageChars(message) + return total +} diff --git a/src/utils/motion.ts b/src/utils/motion.ts new file mode 100644 index 000000000..92a2dc2d8 --- /dev/null +++ b/src/utils/motion.ts @@ -0,0 +1,10 @@ +/** + * 系统动态效果偏好的统一读取入口。 + * + * 浏览器/WebView 里 `prefers-reduced-motion` 是用户明确的偏好,自定义的 + * 高度补间、入场生长、流式逐字都不能绕开它。 + */ +export function prefersReducedMotion(): boolean { + if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') return false + return window.matchMedia('(prefers-reduced-motion: reduce)').matches +} diff --git a/src/utils/pageBudget.test.ts b/src/utils/pageBudget.test.ts new file mode 100644 index 000000000..4f798c3fb --- /dev/null +++ b/src/utils/pageBudget.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import type { SessionMessageInfo } from '../types/api/message' +import { MIN_PAGE_LIMIT, PAGE_CHAR_BUDGET, derivePageLimit } from './pageBudget' + +function message(text: string): SessionMessageInfo { + return { id: `m-${text.length}`, type: 'user', time: { created: 1 }, text } as SessionMessageInfo +} + +function messages(count: number, textLength: number): SessionMessageInfo[] { + return Array.from({ length: count }, () => message('x'.repeat(textLength))) +} + +describe('derivePageLimit', () => { + it('普通大小的消息不改变页大小', () => { + expect(derivePageLimit(messages(50, 500), 50)).toBe(50) + }) + + it('肥页按正文字符预算缩到能放下的条数', () => { + // 每条 20KB,256KB 预算大约放得下 12 条 + const limit = derivePageLimit(messages(50, 20 * 1024), 50) + expect(limit).toBe(Math.floor(PAGE_CHAR_BUDGET / (20 * 1024))) + }) + + it('单条就超过整页预算时不低于最小页', () => { + expect(derivePageLimit(messages(10, PAGE_CHAR_BUDGET * 2), 50)).toBe(MIN_PAGE_LIMIT) + }) + + it('不会超过调用方给的上限', () => { + expect(derivePageLimit(messages(10, 1), 5)).toBe(5) + }) + + it('空页或非法上限原样返回', () => { + expect(derivePageLimit([], 50)).toBe(50) + expect(derivePageLimit(messages(10, 100), 0)).toBe(0) + }) +}) diff --git a/src/utils/pageBudget.ts b/src/utils/pageBudget.ts new file mode 100644 index 000000000..ba71fc62c --- /dev/null +++ b/src/utils/pageBudget.ts @@ -0,0 +1,22 @@ +import type { SessionMessageInfo } from '../types/api/message' +import { estimateMessagesChars } from './messageSize' + +/** 一页历史大致允许持有的正文字符量 */ +export const PAGE_CHAR_BUDGET = 256 * 1024 +/** 单条消息就超过预算时,至少还按这个条数翻页,避免翻页细碎到不可用 */ +export const MIN_PAGE_LIMIT = 4 + +/** + * 按上一页的实际体积推导下一页的条数。 + * + * 只按条数分页时,一页 50 条工具输出可能比一页 50 条闲聊大两个数量级; + * 这里用正文量反推,让「肥页」自动变小。条数只会下调,不会超过调用方给的上限。 + */ +export function derivePageLimit(messages: readonly SessionMessageInfo[], baseLimit: number): number { + if (messages.length === 0 || baseLimit <= 0) return baseLimit + const chars = estimateMessagesChars(messages) + if (chars <= 0) return baseLimit + const perMessage = chars / messages.length + const fits = Math.floor(PAGE_CHAR_BUDGET / perMessage) + return Math.max(MIN_PAGE_LIMIT, Math.min(baseLimit, fits)) +} diff --git a/src/utils/perfTrace.test.ts b/src/utils/perfTrace.test.ts new file mode 100644 index 000000000..c27f60506 --- /dev/null +++ b/src/utils/perfTrace.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it, vi } from 'vitest' +import { finishPerf, measurePerf, startPerf } from './perfTrace' + +describe('perfTrace', () => { + it('measurePerf 返回函数结果', () => { + const fn = vi.fn(() => 42) + expect(measurePerf('test', fn)).toBe(42) + expect(fn).toHaveBeenCalledTimes(1) + }) + + it('测试环境下不产出计时值', () => { + // Vitest 的 MODE 是 test,整个打点应当关闭 + expect(startPerf()).toBeNull() + finishPerf('test', null, 0) + }) +}) diff --git a/src/utils/perfTrace.ts b/src/utils/perfTrace.ts new file mode 100644 index 000000000..b7feb0a59 --- /dev/null +++ b/src/utils/perfTrace.ts @@ -0,0 +1,36 @@ +/** + * 开发期的轻量耗时打点。 + * + * 只在 dev 生效:超过阈值的渲染步骤直接打一条带标签和耗时的警告, + * 省得靠肉眼猜“这一帧到底慢在 Markdown 解析、morph 还是视图模型构建”。 + * 生产构建里整个函数体只剩一次同步调用,没有计时和字符串拼接。 + */ +const ENABLED = import.meta.env.DEV && import.meta.env.MODE !== 'test' + +export function startPerf(): number | null { + return ENABLED ? performance.now() : null +} + +export function finishPerf(label: string, startedAt: number | null, warnAfterMs = 8, detail?: string): void { + if (startedAt == null) return + const elapsed = performance.now() - startedAt + if (elapsed < warnAfterMs) return + const suffix = detail ? ` (${detail})` : '' + console.warn(`[perf] ${label} ${elapsed.toFixed(1)}ms${suffix}`) +} + +export function measurePerf(label: string, fn: () => T, warnAfterMs = 8, detail?: string): T { + if (!ENABLED) return fn() + const startedAt = performance.now() + try { + return fn() + } finally { + finishPerf(label, startedAt, warnAfterMs, detail) + } +} + +/** 一次性事件打点:不以耗时为单位,比如「这个块到底有多大」 */ +export function notePerf(label: string, detail: string): void { + if (!ENABLED) return + console.warn(`[perf] ${label} ${detail}`) +} diff --git a/src/utils/renderDiagnostics.ts b/src/utils/renderDiagnostics.ts new file mode 100644 index 000000000..09ad778b3 --- /dev/null +++ b/src/utils/renderDiagnostics.ts @@ -0,0 +1,48 @@ +/** + * 渲染链路的失败分类(开发期诊断用)。 + * + * 以前很多地方 catch 之后只写一句 console.warn 就结束,出问题时无法区分 + * 「降级但还能看」「下次还能重试」「彻底没救了」。这里统一三类: + * + * - degraded:功能降级但内容仍在(比如高亮失败退回纯文本、解析交给主线程) + * - retryable:这次失败,下一次数据/渲染循环还能再试 + * - terminal:这个环境或实例已经不可用,不应再反复尝试 + * + * 只在 dev 记录并打印,生产构建里调用会被裁剪成一次判断。 + */ +const ENABLED = import.meta.env.DEV && import.meta.env.MODE !== 'test' +const MAX_RECORDS = 100 + +export type RenderScope = 'highlight' | 'markdown' | 'mermaid' | 'html-preview' | 'stream' +export type RenderFailureKind = 'degraded' | 'retryable' | 'terminal' + +export type RenderFailure = { + scope: RenderScope + kind: RenderFailureKind + reason: string + at: number +} + +const records: RenderFailure[] = [] + +export function reportRenderFailure(scope: RenderScope, kind: RenderFailureKind, reason: unknown): void { + if (!ENABLED) return + const message = reason instanceof Error ? reason.message : String(reason) + records.push({ scope, kind, reason: message, at: Date.now() }) + if (records.length > MAX_RECORDS) records.splice(0, records.length - MAX_RECORDS) + console.warn(`[render:${kind}] ${scope}: ${message}`) +} + +export function getRecentRenderFailures(): readonly RenderFailure[] { + return records +} + +export function clearRenderFailures(): void { + records.length = 0 +} + +if (ENABLED && typeof window !== 'undefined') { + // 开着 devtools 时可以直接看最近的失败记录 + ;(window as Window & { __opencodeRenderFailures?: typeof getRecentRenderFailures }).__opencodeRenderFailures = + getRecentRenderFailures +} diff --git a/src/workers/markdownWorker.ts b/src/workers/markdownWorker.ts new file mode 100644 index 000000000..58dd7ad98 --- /dev/null +++ b/src/workers/markdownWorker.ts @@ -0,0 +1,36 @@ +/// + +import { parseMarkdownToHtml } from '../components/markdownParseCore' + +export type MarkdownWorkerRequest = { + type: 'parse' + id: number + key: string + src: string + isReasoning: boolean + renderHtml: boolean +} + +export type MarkdownWorkerResponse = + | { type: 'parsed'; id: number; key: string; html: string } + | { type: 'error'; id: number; key: string; message: string } + +/** + * 只做解析(marked + KaTeX),不做 DOM 净化。 + * 净化依赖 DOMPurify 和真实 DOM,留在主线程;解析的大头在这里,不占主线程。 + */ +self.onmessage = (event: MessageEvent) => { + const msg = event.data + if (msg.type !== 'parse') return + try { + const html = parseMarkdownToHtml(msg.src, msg.isReasoning, msg.renderHtml) + self.postMessage({ type: 'parsed', id: msg.id, key: msg.key, html } satisfies MarkdownWorkerResponse) + } catch (error) { + self.postMessage({ + type: 'error', + id: msg.id, + key: msg.key, + message: error instanceof Error ? error.message : String(error), + } satisfies MarkdownWorkerResponse) + } +} diff --git a/src/workers/shikiWorker.ts b/src/workers/shikiWorker.ts index 67236ad47..c5dbca321 100644 --- a/src/workers/shikiWorker.ts +++ b/src/workers/shikiWorker.ts @@ -19,11 +19,18 @@ export type WorkerRequest = type: 'highlight' id: number key: string - text: string + /** 完整文本;续传时可以省略 */ + text?: string + /** 续传:worker 已持有的前缀长度 */ + baseLength?: number + /** 续传:本次新增的文本(避免每拍整段结构化拷贝) */ + append?: string language: string theme: BundledTheme mode: 'tokens' | 'html' complete?: boolean + /** 客户端状态与 worker 不一致时要求重开流(重新全量排版一次) */ + forceReset?: boolean } | { type: 'dispose'; key: string } @@ -32,9 +39,11 @@ export type WorkerResponse = type: 'highlight' id: number key: string - code: string reset: boolean + /** 本次新增的 stable token;reset 时为全量 */ stable: WorkerToken[] + /** 累积已发出的 stable token 数,客户端据此对齐,对不上就请求重开 */ + stableTotal: number unstable: WorkerToken[] html?: string } @@ -48,10 +57,20 @@ type Stream = { theme: BundledTheme source: string tokenizer: ShikiStreamTokenizer + /** tokensStable 中已经发给客户端的原始下标 */ + sentRawStable: number + /** 已经发给客户端的 stable token 数(按过滤后计) */ + sentStableCount: number } const streams = new Map() const activeHighlights = new Set() +/** + * dispose 后仍可能有请求在 await 中,结束时不能再把流塞回 map; + * 记下已销毁的 key,等新请求进来时再清除。 + */ +const disposedKeys = new Set() +const MAX_DISPOSED_KEYS = 2000 const queuedHighlights = new Map>() let highlighter: Promise | undefined let onigWasmPromise: Promise | null = null @@ -146,29 +165,31 @@ async function highlight(request: Extract) if (!loaded) throw new Error(`Unsupported Shiki language: ${request.language}`) if (isPlainText) { + const text = resolveRequestText(request, streams.get(request.key)) post({ type: 'highlight', id: request.id, key: request.key, - code: request.text, reset: true, - stable: request.mode === 'html' ? [] : [[request.text, '']], + stable: request.mode === 'html' ? [] : [[text, '']], + stableTotal: request.mode === 'html' ? 0 : 1, unstable: [], - html: request.mode === 'html' ? plainTextHtml(request.text) : undefined, + html: request.mode === 'html' ? plainTextHtml(text) : undefined, }) return } if (request.mode === 'html') { - const html = instance.codeToHtml(request.text, { lang: language, theme: request.theme }) + const text = resolveRequestText(request, streams.get(request.key)) + const html = instance.codeToHtml(text, { lang: language, theme: request.theme }) streams.delete(request.key) post({ type: 'highlight', id: request.id, key: request.key, - code: request.text, reset: true, stable: [], + stableTotal: 0, unstable: [], html, }) @@ -176,43 +197,83 @@ async function highlight(request: Extract) } if (request.complete) { - const result = instance.codeToTokens(request.text, { lang: language, theme: request.theme }) + const text = resolveRequestText(request, streams.get(request.key)) + const result = instance.codeToTokens(text, { lang: language, theme: request.theme }) streams.delete(request.key) + const stable = result.tokens + .flatMap((line, index) => + index === result.tokens.length - 1 ? line : [...line, { content: '\n', offset: 0 } as ThemedToken], + ) + .map(toWorkerToken) post({ type: 'highlight', id: request.id, key: request.key, - code: request.text, reset: true, - stable: result.tokens - .flatMap((line, index) => - index === result.tokens.length - 1 ? line : [...line, { content: '\n', offset: 0 } as ThemedToken], - ) - .map(toWorkerToken), + stable, + stableTotal: stable.length, unstable: [], }) return } const previous = streams.get(request.key) - const reset = !previous || previous.language !== language || previous.theme !== request.theme || !request.text.startsWith(previous.source) - const stream = reset - ? { language, theme: request.theme, source: '', tokenizer: new ShikiStreamTokenizer({ highlighter: instance, lang: language, theme: request.theme }) } - : previous - const chunk = request.text.slice(stream.source.length) + const resetBase = + request.forceReset || !previous || previous.language !== language || previous.theme !== request.theme + + let stream: Stream + let chunk: string + let reset: boolean + + if (resetBase) { + if (request.text === undefined) throw new Error('stream-desync') + reset = true + stream = createStream(instance, language, request.theme) + chunk = request.text + } else if (request.text !== undefined) { + if (request.text.startsWith(previous!.source)) { + reset = false + stream = previous! + chunk = request.text.slice(stream.source.length) + } else { + reset = true + stream = createStream(instance, language, request.theme) + chunk = request.text + } + } else { + // 续传:只带了新增片段,worker 的流位置必须和客户端认为的一致 + if (request.append === undefined || request.baseLength !== previous!.source.length) { + throw new Error('stream-desync') + } + reset = false + stream = previous! + chunk = request.append + } + if (chunk) await stream.tokenizer.enqueue(chunk) - stream.source = request.text - streams.set(request.key, stream) + stream.source += chunk + if (!disposedKeys.has(request.key)) streams.set(request.key, stream) + + // 只回传这一拍新稳定下来的 token。已稳定前缀不会回退,所以增量是安全的; + // 客户端按 stableTotal 对齐,对不上就带 forceReset 再要一次全量。 + const rawStable = stream.tokenizer.tokensStable + const fresh = rawStable.slice(stream.sentRawStable) + stream.sentRawStable = rawStable.length + const freshTokens = fresh.filter(t => t.content.length > 0).map(toWorkerToken) + stream.sentStableCount += freshTokens.length + post({ type: 'highlight', id: request.id, key: request.key, - code: request.text, reset, - stable: stream.tokenizer.tokensStable.filter(t => t.content.length > 0).map(toWorkerToken), + stable: freshTokens, + stableTotal: stream.sentStableCount, unstable: stream.tokenizer.tokensUnstable.filter(t => t.content.length > 0).map(toWorkerToken), }) } catch (error) { + // 出错时流状态可能已经半推进,直接丢掉;客户端下一次会带全量文本重开 + streams.delete(request.key) post({ type: 'error', id: request.id, key: request.key, message: error instanceof Error ? error.message : String(error) }) } } @@ -221,6 +282,29 @@ function post(response: WorkerResponse) { self.postMessage(response) } +function createStream(instance: HighlighterCore, language: string, theme: BundledTheme): Stream { + return { + language, + theme, + source: '', + tokenizer: new ShikiStreamTokenizer({ highlighter: instance, lang: language, theme }), + sentRawStable: 0, + sentStableCount: 0, + } +} + +/** 只有带 append 的续传请求会省略 text;此时必须能对上前缀 */ +function resolveRequestText( + request: Extract, + previous: Stream | undefined, +): string { + if (request.text !== undefined) return request.text + if (!previous || request.append === undefined || request.baseLength !== previous.source.length) { + throw new Error('stream-desync') + } + return previous.source + request.append +} + function runQueuedHighlight(request: Extract) { activeHighlights.add(request.key) void highlight(request).finally(() => { @@ -279,7 +363,15 @@ self.onmessage = (event: MessageEvent) => { if (queued) post({ type: 'superseded', id: queued.id, key: queued.key }) queuedHighlights.delete(msg.key) streams.delete(msg.key) + disposedKeys.delete(msg.key) + disposedKeys.add(msg.key) + while (disposedKeys.size > MAX_DISPOSED_KEYS) { + const oldest = disposedKeys.values().next().value + if (oldest === undefined) break + disposedKeys.delete(oldest) + } return } + disposedKeys.delete(msg.key) queueHighlight(msg) }