Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 语音录音时输入框首行不再多一个空行 (#736)
Dash320c074f39c3
diff --git a/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts b/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.tsnew file mode 100644index 0000000000..f4a734db4e--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/composerExternalDraftEmptyDoc.test.ts@@ -0,0 +1,41 @@+/**+ * composerExternalDraftEmptyDoc.test.ts — 外部草稿通知的「空文档」判空口径+ * ---------------------------------------------------------------------------+ * ChatInput 订阅 composerDraftStore 的外部写入后,只有在草稿正文与编辑器当前+ * 文档真的不同时才做全量 setContent。草稿正文在存储里是 Tiptap JSON:空草稿+ * 常常是 `{doc:[空 paragraph]}` 而不是 `null`,而比较的另一侧对「编辑器为空」+ * 一律折叠成 `null`。两侧口径不一致时,每条外部通知都会拿一份空文档原地重建+ * doc(`replace(0, size)`),把所有按位置存活的编辑器状态强行跨整篇映射——语音+ * 录音时 caret 锚点被推出段落、首行多一个空行就是这么来的。+ *+ * 契约锁在源码层:该分支必须用 composerDraftStore 的判空把空文档折叠成 null,+ * 不能只判断 `draft.text` 是否存在。+ */+import { readFileSync } from 'node:fs';+import path from 'node:path';++import { describe, expect, it } from 'vitest';++// CRLF 归一化:Windows checkout 下源码带 \r\n,否则跨 checkout 断言会假失败+// (同 chatInputSessionFocus 等既有源码契约测试)。+const chatInput = readFileSync(+ path.join(path.resolve(__dirname, '..'), 'components/new-chat/ChatInput.tsx'),+ 'utf8',+).replace(/\r\n?/g, '\n');++describe('external draft notification empty-document handling', () => {+ it('collapses an empty draft document to null before comparing with the editor', () => {+ const start = chatInput.indexOf('return subscribeComposerDraft(storageKey, () => {');+ expect(start).toBeGreaterThan(-1);+ // 两个锚点都必须真实命中:end 缺失时 indexOf 返回 -1,slice(start, -1) 会切出+ // 一大段无关源码,让下面的 toContain 假通过、契约形同失效。+ const end = chatInput.indexOf('const textUnchanged', start);+ expect(end).toBeGreaterThan(start);+ const block = chatInput.slice(start, end);++ expect(block).toContain('normalizeComposerDocumentJSON(draft.text)');+ // 判空必须走共享实现,与 draftHasContent / isEditorEmpty 同源。+ expect(block).toContain('tiptapDocHasContent(');+ expect(block).not.toMatch(/const normalizedDraftText = draft\.text\s*\n?\s*\?/);+ });+});diff --git a/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.tsindex a79ae309fd..ed82588490 100644--- a/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts+++ b/apps/desktop/src/renderer/__tests__/voiceInputDraftDecoration.test.ts@@ -225,6 +225,57 @@ describe('voice input draft decoration anti-flicker contract', () => {expect(node.dataset.voiceDraftSource).toBeUndefined();});+ // 录音期间输入框文档被整段重建(外部草稿通知走 setContent → replace(0, size))时,+ // 折叠锚点跨整篇映射会被推到 block 边界:widget 的 pos 落在 doc 层,ProseMirror 就+ // 把这个 inline span 渲染到 <p> 外面,浏览器给它单独一行 —— 表现为"第一句话出现前+ // 先多一个换行"。锚点必须留在段落内的 inline 位置。+ it('keeps the caret anchor inside the paragraph when the document is rebuilt wholesale', () => {+ const { plugin, state } = makeState('');+ const listening = applyDraftMeta(state, {+ text: '',+ source: null,+ from: 1,+ to: 1,+ caretState: 'listening',+ });+ expect(plugin.getState(listening)).toMatchObject({ from: 1, to: 1 });++ const rebuilt = listening.apply(+ listening.tr.replaceWith(+ 0,+ listening.doc.content.size,+ schema.nodes.paragraph.create(),+ ),+ );+ const anchor = plugin.getState(rebuilt);+ expect(anchor).toMatchObject({ from: 1, to: 1 });+ const widget = plugin.getState(rebuilt)?.decorations.find()[0];+ expect(widget?.from).toBe(1);+ expect(rebuilt.doc.resolve(widget!.from).parent.isTextblock).toBe(true);+ });++ it('keeps a collapsed anchor collapsed across a full-document replacement', () => {+ const { plugin, state } = makeState('已经上屏的文字');+ const listening = applyDraftMeta(state, {+ text: '流式草稿',+ source: 'partial',+ from: 1 + '已经上屏的文字'.length,+ to: 1 + '已经上屏的文字'.length,+ caretState: 'listening',+ });+ const rebuilt = listening.apply(+ listening.tr.replaceWith(+ 0,+ listening.doc.content.size,+ schema.nodes.paragraph.create(null, schema.text('已经上屏的文字')),+ ),+ );+ const anchor = plugin.getState(rebuilt);+ // 膨胀成区间会让 voice-input-draft-replaced 把正文整段 display:none 隐藏掉。+ expect(anchor?.from).toBe(anchor?.to);+ expect(rebuilt.doc.resolve(anchor!.from).parent.isTextblock).toBe(true);+ });+it('deduplicates identical setVoiceInputDraftDecoration calls without dispatching', () => {const { state } = makeState('前文');let current = state;diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 977f8ca3c8..75d9c67ae6 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -73,6 +73,7 @@ import {saveDraft as saveComposerDraft,clearDraft as clearComposerDraft,subscribeDraft as subscribeComposerDraft,+ tiptapDocHasContent,} from '@/lib/composerDraftStore';import { subscribeSessionLinkInsert } from '@/lib/composerActionsBus';import { ModelSelector, type ModelMemoryAccessors } from './ModelSelector';@@ -2708,9 +2709,13 @@ export function ChatInput({setBrowserComments(draft.browserComments ?? []);// 同值外部写入不做全量 setContent,避免把用户停在中段的光标弹到末尾、// 打断 IME 组合。appendQuoteToDraft 会改变正文文档,自然走下方 setContent。- const normalizedDraftText = draft.text- ? normalizeComposerDocumentJSON(draft.text)- : null;+ // 空草稿在存储里可能是 `{doc:[空 paragraph]}` 而不是 undefined,而右侧对+ // "编辑器为空"一律折叠成 null。两侧判空口径必须一致,否则每次外部草稿通知都+ // 会拿一份空文档整段 setContent:doc 被原地重建,所有按位置存活的状态(语音+ // 草稿锚点等)被迫跨整篇映射(#720 后语音录音时首行多一个空行的成因)。+ const draftDocument = draft.text ? normalizeComposerDocumentJSON(draft.text) : null;+ const normalizedDraftText =+ draftDocument && tiptapDocHasContent(draftDocument) ? draftDocument : null;const textUnchanged =JSON.stringify(normalizedDraftText) ===JSON.stringify(composerDocIsEmpty(editor.state.doc) ? null : editor.getJSON());diff --git a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.tsindex ef79721532..36e04e3832 100644--- a/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts+++ b/apps/desktop/src/renderer/components/new-chat/VoiceInputDraftDecoration.ts@@ -1,5 +1,11 @@import { Extension, type Editor } from '@tiptap/core';-import { Plugin, PluginKey, type EditorState, type Transaction } from '@tiptap/pm/state';+import {+ Plugin,+ PluginKey,+ TextSelection,+ type EditorState,+ type Transaction,+} from '@tiptap/pm/state';import { Decoration, DecorationSet } from '@tiptap/pm/view';import type { Node as PMNode } from '@tiptap/pm/model';import type { VoiceInputDraftSource } from '@cindy/voice-input-core';@@ -43,10 +49,29 @@ function clampPosition(doc: PMNode, position: number): number {return Math.max(0, Math.min(position, doc.content.size));}+/**+ * Snap a position onto the nearest place that can hold inline content.+ *+ * The draft/caret widgets are inline: rendered at a position whose parent is+ * NOT a textblock (0 or a boundary between blocks), ProseMirror puts them in+ * the doc-level DOM — an inline span between two `<p>`s, which the browser then+ * gives its own line. That reads as a stray blank line above the dictation+ * caret. Anchors reach such a position whenever the composer document is+ * rebuilt wholesale while dictation is live (external draft restore does a+ * `replace(0, size)`), because mapping a collapsed anchor across a full+ * replacement pushes it out to the block boundary.+ */+function clampToInlinePosition(doc: PMNode, position: number): number {+ const clamped = clampPosition(doc, position);+ const $pos = doc.resolve(clamped);+ if ($pos.parent.isTextblock) return clamped;+ return TextSelection.near($pos, 1).from;+}+function clampRange(doc: PMNode, from: number, to: number): { from: number; to: number } {- const safeFrom = clampPosition(doc, Math.min(from, to));- const safeTo = clampPosition(doc, Math.max(from, to));- return { from: safeFrom, to: safeTo };+ const safeFrom = clampToInlinePosition(doc, Math.min(from, to));+ const safeTo = clampToInlinePosition(doc, Math.max(from, to));+ return safeFrom <= safeTo ? { from: safeFrom, to: safeTo } : { from: safeFrom, to: safeFrom };}/**@@ -263,8 +288,13 @@ export function createVoiceInputDraftPlugin(): Plugin<VoiceInputDraftDecorationS}}if (tr.docChanged) {- const mappedFrom = tr.mapping.map(old.from, -1);- const mappedTo = tr.mapping.map(old.to, 1);+ // A collapsed anchor must stay collapsed: mapping it with opposite+ // biases grows it into a range, and a non-empty range makes the+ // `voice-input-draft-replaced` decoration hide whatever text now sits+ // inside it (a full-document rebuild would blank the existing draft).+ const collapsed = old.from === old.to;+ const mappedFrom = tr.mapping.map(old.from, collapsed ? 1 : -1);+ const mappedTo = collapsed ? mappedFrom : tr.mapping.map(old.to, 1);return createState(tr.doc,old.text,diff --git a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.tsindex 453f8c9c52..1fd9f0977b 100644--- a/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/composerDraftStore.test.ts@@ -13,6 +13,7 @@ import {setComposerDraftOwner,subscribeDraft,subscribeDraftPresence,+ tiptapDocHasContent,type ComposerDraft,} from '@/lib/composerDraftStore';@@ -272,4 +273,16 @@ describe('draft presence subscription', () => {unsubPresence();unsubContent();});++ // ChatInput 的外部草稿订阅用这个判空把「空文档 JSON」折叠成 null,再与+ // 「编辑器为空」比较。两侧口径不一致时,每次外部草稿通知都会拿一份空文档整段+ // setContent,把按位置存活的编辑器状态(语音草稿锚点)连带重建 —— 语音录音时+ // 首行多出一个空行就是这么来的。+ it('treats an empty / whitespace-only document as having no content', () => {+ expect(tiptapDocHasContent(emptyDoc)).toBe(false);+ expect(tiptapDocHasContent(whitespaceDoc)).toBe(false);+ expect(tiptapDocHasContent(null)).toBe(false);+ expect(tiptapDocHasContent(textDoc)).toBe(true);+ expect(tiptapDocHasContent(mentionDoc)).toBe(true);+ });});diff --git a/apps/desktop/src/renderer/lib/composerDraftStore.ts b/apps/desktop/src/renderer/lib/composerDraftStore.tsindex e7738a4633..e64857ab00 100644--- a/apps/desktop/src/renderer/lib/composerDraftStore.ts+++ b/apps/desktop/src/renderer/lib/composerDraftStore.ts@@ -134,7 +134,7 @@ const presenceCache = new Map<string, boolean>();* Empty paragraphs / whitespace-only → no content. 两处判定必须同步演进,* 否则「只含 chip 的草稿」侧边栏不亮未发送标记(review P2)。*/-function tiptapDocHasContent(node: JSONContent | null | undefined): boolean {+export function tiptapDocHasContent(node: JSONContent | null | undefined): boolean {if (!node) return false;if (node.type === 'mentionChip' ||