Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复输入框列表缩进与卡死 (#622)
zhangyongjie3d9dec380a47
diff --git a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.tsindex 178a5ad5d3..3627240fda 100644--- a/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts+++ b/apps/desktop/src/renderer/__tests__/composerListIndentDecoration.test.ts@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { readFileSync } from 'node:fs';import { resolve } from 'node:path';-import { afterEach, describe, expect, it } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';import { Editor, Node as TiptapNode } from '@tiptap/core';import Document from '@tiptap/extension-document';import Paragraph from '@tiptap/extension-paragraph';@@ -21,6 +21,7 @@ import {setVoiceInputDraftDecoration,VoiceInputDraftDecoration,} from '@/components/new-chat/VoiceInputDraftDecoration';+import { applyListContinuation } from '@/lib/composerListContinuation';/*** composer 列表行缩进 decoration:@@ -85,11 +86,14 @@ describe('buildListIndentDecorations', () => {expect(cjkStyle).not.toContain('10、');});- it('decorates tab-indented lines and leaves their final width to browser measurement', () => {+ it('decorates tab-indented lines with a deterministic fallback width', () => {const ed = makeEditor(['\t1. item']);const tabIndent = ed.view.dom.querySelector('.composer-list-tab-indent');expect(tabIndent).not.toBeNull();expect(tabIndent?.getAttribute('data-composer-list-prefix-length')).toBe('4');+ expect((tabIndent as HTMLElement | null)?.style.getPropertyValue('--composer-list-hang')).toBe(+ '9.8ch',+ );});it('decorates the full content of a single-line item', () => {@@ -169,6 +173,11 @@ describe('buildListIndentDecorations', () => {expect(buildListIndentDecorations(ed.state.doc).find()).toHaveLength(1);});+ it('does not decorate ordered-dot CJK text without a separator space', () => {+ const ed = makeEditor(['5.我']);+ expect(buildListIndentDecorations(ed.state.doc).find()).toHaveLength(0);+ });+it('does not decorate plain text lines', () => {const ed = makeEditor(['hello world', '3.14159']);expect(buildListIndentDecorations(ed.state.doc).find()).toHaveLength(0);@@ -233,6 +242,116 @@ describe('buildListIndentDecorations', () => {});describe('ComposerListIndentDecoration in a real editor', () => {+ it('keeps the automatically inserted ordered prefix indented before body input', () => {+ editor = new Editor({+ element: document.createElement('div'),+ extensions: [Document, Paragraph, Text, HardBreak, ComposerListIndentDecoration],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [{ type: 'text', text: '1. 第一项' }],+ },+ ],+ },+ });+ editor.commands.setTextSelection(editor.state.doc.content.size - 1);++ expect(applyListContinuation(editor.view)).toBe(true);+ expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n', '\n')).toBe(+ '1. 第一项\n2. ',+ );++ const indentedRows = editor.view.dom.querySelectorAll('.composer-list-line-indent');+ expect(indentedRows).toHaveLength(2);+ expect(indentedRows[1]?.textContent).toBe('2. ');++ editor.commands.insertContent('中文');+ expect(editor.state.doc.textBetween(0, editor.state.doc.content.size, '\n', '\n')).toBe(+ '1. 第一项\n2. 中文',+ );+ expect(editor.view.dom.querySelectorAll('.composer-list-line-indent')).toHaveLength(2);+ });++ it('does not rewrite decoration-owned styles while laying out multiline CJK lists', () => {+ const getBoundingClientRect = vi.fn(() => ({+ width: 24,+ height: 22,+ top: 0,+ right: 24,+ bottom: 22,+ left: 0,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ }));+ const originalDescriptor = Object.getOwnPropertyDescriptor(+ Range.prototype,+ 'getBoundingClientRect',+ );+ Object.defineProperty(Range.prototype, 'getBoundingClientRect', {+ configurable: true,+ value: getBoundingClientRect,+ });++ try {+ editor = new Editor({+ element: document.createElement('div'),+ extensions: [+ Document,+ Paragraph,+ Text,+ HardBreak,+ CjkPunctDecoration,+ ComposerListIndentDecoration,+ ],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: '1. 有新增游戏数的用户数、占全部用户比例。' },+ { type: 'hardBreak' },+ { type: 'text', text: '2. 有新增游戏数的近30天、近1年活跃用户数及占比。' },+ { type: 'hardBreak' },+ {+ type: 'text',+ text: '3. 每人新增游戏数的均值、P50、P75、P90、P95、P99、最大值。',+ },+ ],+ },+ ],+ },+ });++ // Force a plugin-view update after the decoration DOM is mounted. Directly+ // writing measured pixels back to these nodes makes ProseMirror's+ // DOMObserver restore the declared decoration styles in Chromium, which+ // can create an update loop and freeze the renderer.+ editor.view.updateState(editor.state);++ expect(getBoundingClientRect).not.toHaveBeenCalled();+ expect(+ editor.view.dom+ .querySelector<HTMLElement>('.composer-list-fallback-prefix')+ ?.style.getPropertyValue('--composer-list-hang'),+ ).toBe('1.8ch');+ expect(+ editor.view.dom+ .querySelector<HTMLElement>('.composer-list-fallback-container')+ ?.style.getPropertyValue('--composer-list-fallback-indent'),+ ).toBe('1.8ch');+ } finally {+ if (originalDescriptor) {+ Object.defineProperty(Range.prototype, 'getBoundingClientRect', originalDescriptor);+ } else {+ Reflect.deleteProperty(Range.prototype, 'getBoundingClientRect');+ }+ }+ });+it('renders the indent span into the DOM for list lines', () => {const ed = makeEditor(['1. hello']);expect(ed.view.dom.querySelector('p.composer-list-block-indent')?.textContent).toBe('1. hello');@@ -552,6 +671,90 @@ describe('ComposerListIndentDecoration in a real editor', () => {);});+ it('keeps a fallback non-list CJK line as one box after deleting its ordered marker', () => {+ editor = new Editor({+ element: document.createElement('div'),+ extensions: [+ Document,+ Paragraph,+ Text,+ HardBreak,+ CjkPunctDecoration,+ ComposerListIndentDecoration,+ ],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: '1. 有新增游戏数的用户数、占全部用户比例。' },+ { type: 'hardBreak' },+ { type: 'text', text: '2. 有新增游戏数的近30天、近1年活跃用户数及占比。' },+ { type: 'hardBreak' },+ {+ type: 'text',+ text: '3. 每人新增游戏数的均值、P50、P75、P90、P95、P99、最大值。',+ },+ ],+ },+ ],+ },+ });++ editor.commands.deleteRange({ from: 1, to: 4 });++ const container = editor.view.dom.querySelector('p.composer-list-fallback-container');+ const unindentedRows = container?.querySelectorAll('.composer-list-fallback-unindented');+ expect(container).not.toBeNull();+ expect(unindentedRows).toHaveLength(1);+ expect(unindentedRows?.[0]?.textContent).toBe('有新增游戏数的用户数、占全部用户比例。');+ expect(unindentedRows?.[0]?.classList.contains('composer-list-cjk-font')).toBe(true);+ expect(unindentedRows?.[0]?.querySelectorAll('span[style*="font-family"]')).toHaveLength(0);+ });++ it('keeps no-space CJK ordered text unindented inside the multiline fallback', () => {+ editor = new Editor({+ element: document.createElement('div'),+ extensions: [+ Document,+ Paragraph,+ Text,+ HardBreak,+ CjkPunctDecoration,+ ComposerListIndentDecoration,+ ],+ content: {+ type: 'doc',+ content: [+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: '1. 有新增游戏数的用户数、占全部用户比例。' },+ { type: 'hardBreak' },+ { type: 'text', text: '5.我' },+ ],+ },+ ],+ },+ });++ const prefixes = editor.view.dom.querySelectorAll('.composer-list-fallback-prefix');+ const unindentedRows = editor.view.dom.querySelectorAll('.composer-list-fallback-unindented');+ expect(prefixes).toHaveLength(1);+ expect(prefixes[0]?.textContent).toBe('1. ');+ expect(unindentedRows).toHaveLength(1);+ expect(unindentedRows[0]?.textContent).toBe('5.我');+ });++ it('keeps fallback long alphanumeric rows in the same visual line as their marker', () => {+ const css = readFileSync(resolve(__dirname, '..', 'styles', 'globals.css'), 'utf8');+ const fallbackContainerRule = css.match(+ /\.ProseMirror \.composer-list-fallback-container \{([\s\S]*?)\n\}/,+ )?.[1];+ expect(fallbackContainerRule).toContain('word-break: break-all;');+ });+it('keeps hanging indent for slash paths and unknown commands without pills', () => {editor = new Editor({element: document.createElement('div'),@@ -634,6 +837,17 @@ describe('wiring contract', () => {expect(css).toContain('.ProseMirror .composer-list-tab-indent');expect(css).toContain('tab-size: 8;');expect(css).toContain('white-space: nowrap;');+ const fallbackPrefixRule = css.match(+ /\.ProseMirror \.composer-list-fallback-prefix \{([\s\S]*?)\n\}/,+ )?.[1];+ expect(fallbackPrefixRule).toContain(+ 'width: var(--composer-list-fallback-indent, 1.25em);',+ );+ expect(fallbackPrefixRule).toContain(+ 'margin-left: calc(0px - var(--composer-list-fallback-indent, 1.25em));',+ );+ expect(fallbackPrefixRule).not.toContain('width: calc(1em +');+ expect(fallbackPrefixRule).not.toContain('margin-left: calc(-1em -');const fallbackBreakRule = css.match(/\.ProseMirror \.composer-list-fallback-break \{([\s\S]*?)\n\}/,)?.[1];diff --git a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.tsindex 0321c6f3a6..a0679c2bcb 100644--- a/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts+++ b/apps/desktop/src/renderer/components/new-chat/CjkPunctDecoration.ts@@ -142,7 +142,12 @@ function listLineRanges();});lineMatches.forEach(({ line, match }) => {- if (!match) return;+ if (!match) {+ if (hasFallbackLine && lines.length > 1 && line.end > line.start) {+ ranges.push({ from: contentBase + line.start, to: contentBase + line.end });+ }+ return;+ }const prefixFrom = contentBase + line.start;const prefixTo = prefixFrom + match.prefixLength;const body = line.text.slice(match.prefixLength);diff --git a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.tsindex c5e6c47eb6..07291c9df0 100644--- a/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts+++ b/apps/desktop/src/renderer/components/new-chat/ComposerListIndentDecoration.ts@@ -8,7 +8,8 @@* decoration;连续数字/字母正文使用 marker/body 两个盒子,避免长串把* 列表标记单独挤到上一行。包含 inline atom/pill 的段落使用段落级 fallback* 容器和每行前缀槽位,避免 inline decoration 在 atom 边界被拆成多个 block。- * 所有路径都把前缀的估算宽度写入 CSS 变量。+ * 所有路径都把前缀的确定性估算宽度写入 CSS 变量,不在 plugin view+ * 阶段读取布局或回写 decoration DOM。* CSS 将列表行作为独立的换行容器:首行用负 text-indent 把标记悬挂在左侧,* 自动换行后的续行则从正文起点开始。用户打完 `1. `(空格落下)那一刻* 缩进立即出现,即"已进入列表状态"的视觉信号;空项退出(前缀被删)时缩进@@ -112,8 +113,9 @@ function addLongRunDecoration(** ChatInput 已启用 tabular-nums,所以数字直接用 1ch;句点、空格、方括号等* 窄字符按 0.4ch 估算;中文顿号按全角 1em。这里只生成数字和 CSS 单位,- * 不会透传用户文本。Tab 先用固定 tab stop 做首帧回退,插件 view 在布局- * 完成后用 Range 实测并覆盖变量,避免比例字体下的 ch 近似误差。+ * 不会透传用户文本。Tab 使用固定 tab stop 估算,不再用 Range 实测后+ * 直接改 decoration DOM:ProseMirror 的 DOMObserver 会尝试恢复这类外部+ * style 变更,在 Chromium 中可能与 plugin view 形成更新循环并卡死 renderer。*/export function listPrefixIndentStyle(prefix: string): string {const { ch, em } = listPrefixIndentValues(prefix);@@ -229,9 +231,15 @@ export function buildListIndentDecorations(const match = matchListPrefix(line.text);if (!match) {if (hasFallbackLine && lines.length > 1 && line.end > line.start) {+ const hasCjkPunctuation = CJK_PUNCTUATION_RE.test(line.text);decorations.push(Decoration.inline(contentBase + line.start, contentBase + line.end, {- class: 'composer-list-fallback-unindented',+ class: [+ 'composer-list-fallback-unindented',+ hasCjkPunctuation ? 'composer-list-cjk-font' : '',+ ]+ .filter(Boolean)+ .join(' '),}),);}@@ -290,7 +298,6 @@ export function buildListIndentDecorations(const prefix = match ? line.text.slice(0, match.prefixLength) : '';const body = line && match ? line.text.slice(match.prefixLength) : '';const from = line ? contentBase + line.start : contentBase;- const to = line ? contentBase + line.end : contentBase;const hasLongAlphanumericBody = LONG_ALPHANUMERIC_BODY_RE.test(body);const prefixHasCjkPunctuation = CJK_PUNCTUATION_RE.test(prefix);const hasTabPrefix = prefix.includes('\t');@@ -403,74 +410,6 @@ export const ComposerListIndentDecoration = Extension.create({return this.getState(state) ?? DecorationSet.empty;},},- view() {- return {- update(view) {- const measurablePrefixes = view.dom.querySelectorAll<HTMLElement>(- '.composer-list-tab-indent, .composer-list-fallback-prefix',- );- const fallbackWidths = new Map<HTMLElement, number>();- measurablePrefixes.forEach((span) => {- const prefixLength = Number(span.dataset.composerListPrefixLength ?? Number.NaN);- if (!Number.isFinite(prefixLength) || prefixLength <= 0) return;- // Once Chromium measurement has replaced the deterministic- // fallback with pixels, the same span no longer needs a- // synchronous Range/layout read on every editor update.- const existingWidth = span.style.getPropertyValue('--composer-list-hang').trim();- let width = existingWidth.endsWith('px')- ? Number.parseFloat(existingWidth.slice(0, -2))- : Number.NaN;- if (!Number.isFinite(width)) {- const walker = document.createTreeWalker(span, NodeFilter.SHOW_TEXT);- let remaining = prefixLength;- let startNode: Text | null = null;- let endNode: Text | null = null;- let endOffset = 0;- while (remaining > 0) {- const node = walker.nextNode() as Text | null;- if (!node) break;- const length = node.data.length;- if (!startNode) startNode = node;- endNode = node;- if (length >= remaining) {- endOffset = remaining;- remaining = 0;- break;- }- remaining -= length;- }- if (!startNode || !endNode || remaining > 0) return;- const range = document.createRange();- range.setStart(startNode, 0);- range.setEnd(endNode, endOffset);- if (typeof range.getBoundingClientRect !== 'function') return;- width = range.getBoundingClientRect().width;- if (!Number.isFinite(width) || width <= 0) return;- span.style.setProperty('--composer-list-hang', `${width}px`);- span.style.setProperty('--composer-list-hang-negative', `-${width}px`);- }- const fallbackContainer = span.closest<HTMLElement>(- '.composer-list-fallback-container',- );- if (fallbackContainer) {- fallbackWidths.set(- fallbackContainer,- Math.max(fallbackWidths.get(fallbackContainer) ?? 0, width),- );- }- });- fallbackWidths.forEach((width, fallbackContainer) => {- const nextWidth = `${width}px`;- if (- fallbackContainer.style.getPropertyValue('--composer-list-fallback-indent') !==- nextWidth- ) {- fallbackContainer.style.setProperty('--composer-list-fallback-indent', nextWidth);- }- });- },- };- },// 注:曾有一个 view().update 里 `if (view.composing) return` 的"IME 保护",// 但重算发生在上面的 state.apply(只看 tr.docChanged),view.update 在视图更新// 之后才跑、DecorationSet 早已算好,该钩子等价 no-op(greptile P2)——已删除。diff --git a/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.tsindex 0d2e2842e6..e4163225b8 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerListContinuation.test.ts@@ -36,8 +36,9 @@ describe('computeListContinuation', () => {expect(computeListContinuation('1. ', ' ')).toEqual({ action: 'exit' });});- it('序号后没有空格不算列表(避免误伤 `1.5倍` 这类输入)', () => {+ it('序号后没有空格不算列表(避免误伤中文正文和 `1.5倍` 这类输入)', () => {expect(computeListContinuation('1.foo')).toBeNull();+ expect(computeListContinuation('1.中文项')).toBeNull();expect(computeListContinuation('1.5倍速')).toBeNull();});});diff --git a/apps/desktop/src/renderer/lib/__tests__/composerListContinuationEditor.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerListContinuationEditor.test.tsindex 02cbb65305..18a2ae8de4 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerListContinuationEditor.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerListContinuationEditor.test.ts@@ -89,6 +89,12 @@ describe('applyListContinuation on a real editor', () => {expect(docText(ed)).toBe('1、第一项\n2、');});+ it('does not continue ordered dot text without a separator space before CJK text', () => {+ const ed = makeEditor(['1.中文项']);+ expect(applyListContinuation(ed.view)).toBe(false);+ expect(docText(ed)).toBe('1.中文项');+ });+it('splits mid-line: caret inside the item carries the remainder to the new item', () => {const ed = makeEditor(['1. abcdef']);// 光标放在 "abc|def" 中间(pos 1 是段首,"1. abc" 共 6 字符 → pos 7)diff --git a/apps/desktop/src/renderer/styles/globals.css b/apps/desktop/src/renderer/styles/globals.cssindex a731c4f824..67fa17cdc4 100644--- a/apps/desktop/src/renderer/styles/globals.css+++ b/apps/desktop/src/renderer/styles/globals.css@@ -367,12 +367,13 @@ html:lang(ko) {width: 100%;padding-left: calc(1em + var(--composer-list-fallback-indent, 1.25em));overflow-wrap: anywhere;+ word-break: break-all;}.ProseMirror .composer-list-fallback-prefix {display: inline-block;box-sizing: border-box;- width: calc(1em + var(--composer-list-fallback-indent, 1.25em));- margin-left: calc(-1em - var(--composer-list-fallback-indent, 1.25em));+ width: var(--composer-list-fallback-indent, 1.25em);+ margin-left: calc(0px - var(--composer-list-fallback-indent, 1.25em));white-space: nowrap;vertical-align: top;}@@ -399,8 +400,9 @@ html:lang(ko) {overflow-wrap: anywhere;}.ProseMirror .composer-list-tab-indent {- /* Keep the fallback and the browser's tab advance deterministic until the- plugin view replaces the CSS variables with a measured Range width. */+ /* Keep the browser's tab advance aligned with the deterministic prefix-width+ estimate. Do not measure and rewrite decoration DOM from a plugin view:+ ProseMirror's DOMObserver may restore that style and enter an update loop. */tab-size: 8;}.ProseMirror .composer-list-cjk-font {