Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 修复回车发送后输入框失焦 (#2266)

Dash2d42f44fa688
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index 4f0c115087..c19cad311f 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -55,7 +55,7 @@ describe('ChatInput session switch focus contract', () => {
);
expect(restoreNextDraftBlock).toContain('if (!isCurrentTransition()) return;');
expect(restoreNextDraftBlock).toContain(
- 'if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor)) return;',
+ 'if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)) return;',
);
expect(restoreNextDraftBlock).toContain("editor.commands.focus('end');");
expect(firstMountHydrationBlock).toContain('focusOnStorageKeyChangeRef.current');
@@ -87,10 +87,25 @@ describe('ChatInput session switch focus contract', () => {
});
it('guards delayed storageKey focus against stealing from another focused control', () => {
- expect(chatInputSource).toContain('function hasFocusMovedToInteractiveElement(');
- expect(chatInputSource).toContain('if (activeElement === focusAnchor) return false;');
- expect(chatInputSource).toContain('if (editor.view.dom.contains(activeElement)) return false;');
- expect(chatInputSource).toContain('return isInteractiveFocusedElement(activeElement);');
+ expect(chatInputSource).toContain(
+ 'hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)',
+ );
+ });
+
+ it('wires local send locking through the behavior-tested focus restore hook', () => {
+ const localSendLockBlock = extractBetween(
+ chatInputSource,
+ '// Local/SSH sends keep the live composer while references and runtime',
+ 'try {\n let serializedContent',
+ );
+
+ expect(chatInputSource).toContain(
+ 'const captureSendFocusForRestore = useComposerSendFocusRestore(',
+ );
+ expect(localSendLockBlock).toContain('captureSendFocusForRestore();');
+ expect(localSendLockBlock.indexOf('captureSendFocusForRestore();')).toBeLessThan(
+ localSendLockBlock.indexOf('setSendDispatchInFlight(true);'),
+ );
});
it('reuses in-composer Plugin placement for routed Use and end-focuses Create with Cindy', () => {
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 1d2318264b..e9668a1bfd 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -46,6 +46,10 @@ import {
} from './ComposerListNodes';
import { WindowsSelectionReplacement } from './WindowsSelectionReplacement';
import { EmptyDocSelectionGuard } from './EmptyDocSelectionGuard';
+import {
+ hasFocusMovedToInteractiveElement,
+ useComposerSendFocusRestore,
+} from './useComposerSendFocusRestore';
import {
setVoiceInputDraftDecoration,
VoiceInputDraftDecoration,
@@ -191,7 +195,6 @@ import { composerDocIsEmpty } from './composerDocState';
import { canUseLocalAttachmentPicker } from './localAttachmentPicker';
import {
isComposerBlankPointerTarget,
- isInteractiveFocusedElement,
resolveComposerBlankFocusIntent,
} from './composerBlankPointerFocus';
import {
@@ -744,20 +747,6 @@ function scrollVoiceInputDraftEndIntoView(editor: Editor): void {
}
}
-function hasFocusMovedToInteractiveElement(focusAnchor: Element | null, editor: Editor): boolean {
- const activeElement = document.activeElement;
- if (
- !activeElement ||
- activeElement === document.body ||
- activeElement === document.documentElement
- ) {
- return false;
- }
- if (activeElement === focusAnchor) return false;
- if (editor.view.dom.contains(activeElement)) return false;
- return isInteractiveFocusedElement(activeElement);
-}
-
/**
* Is the editor document "empty" (no text and no chips)? Used to mimic the
* textarea's `message.trim().length > 0` gate for the Send button.
@@ -2580,6 +2569,11 @@ export function ChatInput({
useEffect(() => {
editor?.setEditable(!composerMutationLocked);
}, [composerMutationLocked, editor]);
+ const captureSendFocusForRestore = useComposerSendFocusRestore(
+ editor,
+ composerMutationLocked,
+ sendDispatchInFlight,
+ );
const { settings: voiceInputSettings } = useVoiceInputSettings();
const voiceInputShortcutLabel = useMemo(
() => formatVoiceInputShortcut(voiceInputSettings.shortcut),
@@ -3095,7 +3089,7 @@ export function ChatInput({
window.requestAnimationFrame(() => {
if (editor.isDestroyed || !editor.isEditable) return;
if (latestStorageKeyRef.current !== storageKey) return;
- if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor)) return;
+ if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)) return;
editor.commands.focus('end');
});
}
@@ -3162,7 +3156,7 @@ export function ChatInput({
if (!focusOnStorageKeyChangeRef.current) return;
if (disableAutofocusRef.current || disabledRef.current) return;
if (editor.isDestroyed || !editor.isEditable) return;
- if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor)) return;
+ if (hasFocusMovedToInteractiveElement(storageKeyFocusAnchor, editor.view.dom)) return;
editor.commands.focus('end');
});
};
@@ -4234,7 +4228,10 @@ export function ChatInput({
// Local/SSH sends keep the live composer while references and runtime
// settings settle; remote sends must stay editable after their
// click-time snapshot is cleared.
- if (!optimisticallyClearRemoteComposer) setSendDispatchInFlight(true);
+ if (!optimisticallyClearRemoteComposer) {
+ captureSendFocusForRestore();
+ setSendDispatchInFlight(true);
+ }
try {
let serializedContent = serializedAtClick;
if (!serializedContent) {
@@ -4809,6 +4806,7 @@ export function ChatInput({
confirmDialog,
navigate,
planModeEntry,
+ captureSendFocusForRestore,
],
);
useEffect(() => {
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx b/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx
new file mode 100644
index 0000000000..777357a767
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx
@@ -0,0 +1,207 @@
+// @vitest-environment jsdom
+import { useEffect } from 'react';
+import { act, fireEvent, renderHook } from '@testing-library/react';
+import { Editor } from '@tiptap/core';
+import Document from '@tiptap/extension-document';
+import Paragraph from '@tiptap/extension-paragraph';
+import Text from '@tiptap/extension-text';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useComposerSendFocusRestore } from '../useComposerSendFocusRestore';
+
+interface HarnessProps {
+ composerMutationLocked: boolean;
+ sendDispatchInFlight: boolean;
+}
+
+let createdEditors: Editor[] = [];
+
+function createEditor(): Editor {
+ const mount = document.createElement('div');
+ document.body.append(mount);
+ const editor = new Editor({
+ element: mount,
+ extensions: [Document, Paragraph, Text],
+ content: '<p>next message</p>',
+ editorProps: { handleScrollToSelection: () => true },
+ });
+ createdEditors.push(editor);
+ return editor;
+}
+
+describe('useComposerSendFocusRestore', () => {
+ let nextFrameId = 1;
+ let frames = new Map<number, FrameRequestCallback>();
+
+ beforeEach(() => {
+ createdEditors = [];
+ frames = new Map();
+ vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ const id = nextFrameId++;
+ frames.set(id, callback);
+ return id;
+ });
+ vi.spyOn(window, 'cancelAnimationFrame').mockImplementation((id) => {
+ frames.delete(id);
+ });
+ });
+
+ afterEach(() => {
+ for (const editor of createdEditors) editor.destroy();
+ document.getSelection()?.removeAllRanges();
+ document.body.replaceChildren();
+ vi.restoreAllMocks();
+ });
+
+ const flushAnimationFrames = () => {
+ act(() => {
+ for (let round = 0; frames.size > 0 && round < 10; round += 1) {
+ const pendingFrames = [...frames.values()];
+ frames.clear();
+ for (const callback of pendingFrames) callback(0);
+ }
+ });
+ };
+
+ const renderRestoreHook = (editor: Editor) =>
+ renderHook(
+ ({ composerMutationLocked, sendDispatchInFlight }: HarnessProps) => {
+ useEffect(() => {
+ editor.setEditable(!composerMutationLocked);
+ }, [composerMutationLocked, editor]);
+ return useComposerSendFocusRestore(editor, composerMutationLocked, sendDispatchInFlight);
+ },
+ {
+ initialProps: { composerMutationLocked: false, sendDispatchInFlight: false },
+ },
+ );
+
+ const focusComposerSelection = (editor: Editor) => {
+ act(() => {
+ editor.commands.setTextSelection({ from: 2, to: 6 });
+ editor.view.focus();
+ });
+ expect(document.activeElement).toBe(editor.view.dom);
+ };
+
+ it('restores the focused composer after the temporary send lock', () => {
+ const editor = createEditor();
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ act(() => editor.view.dom.blur());
+ expect(document.activeElement).toBe(document.body);
+
+ hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ flushAnimationFrames();
+
+ expect(document.activeElement).toBe(editor.view.dom);
+ expect(editor.state.selection.from).toBe(2);
+ expect(editor.state.selection.to).toBe(6);
+ });
+
+ it('keeps the restore intent until every composer lock is released', () => {
+ const editor = createEditor();
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ act(() => editor.view.dom.blur());
+
+ // The send lock has settled, but voice input still owns the mutation lock.
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: false });
+ flushAnimationFrames();
+ expect(document.activeElement).toBe(document.body);
+
+ hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ flushAnimationFrames();
+ expect(document.activeElement).toBe(editor.view.dom);
+ });
+
+ it('does not steal focus from another interactive control', () => {
+ const editor = createEditor();
+ const button = document.createElement('button');
+ document.body.append(button);
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ act(() => button.focus());
+ hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ flushAnimationFrames();
+
+ expect(document.activeElement).toBe(button);
+ });
+
+ it('preserves a non-collapsed message selection created during the send lock', () => {
+ const editor = createEditor();
+ const message = document.createElement('p');
+ const messageText = document.createTextNode('select this message');
+ message.append(messageText);
+ document.body.prepend(message);
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ act(() => {
+ editor.view.dom.blur();
+ const range = document.createRange();
+ range.setStart(messageText, 0);
+ range.setEnd(messageText, 6);
+ const selection = document.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ });
+
+ hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ flushAnimationFrames();
+
+ expect(document.activeElement).toBe(document.body);
+ expect(document.getSelection()?.toString()).toBe('select');
+ });
+
+ it('does not interrupt a message selection drag before the range expands', () => {
+ const editor = createEditor();
+ const message = document.createElement('p');
+ const messageText = document.createTextNode('start selecting here');
+ message.append(messageText);
+ document.body.prepend(message);
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ act(() => {
+ editor.view.dom.blur();
+ const range = document.createRange();
+ range.setStart(messageText, 0);
+ range.collapse(true);
+ const selection = document.getSelection();
+ selection?.removeAllRanges();
+ selection?.addRange(range);
+ });
+ fireEvent.pointerDown(message);
+
+ hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ flushAnimationFrames();
+
+ expect(document.activeElement).toBe(document.body);
+ expect(document.getSelection()?.isCollapsed).toBe(true);
+ expect(document.getSelection()?.anchorNode).toBe(messageText);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts
new file mode 100644
index 0000000000..283ab5f4d9
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts
@@ -0,0 +1,112 @@
+import { useCallback, useEffect, useRef } from 'react';
+
+import { isInteractiveFocusedElement } from './composerBlankPointerFocus';
+
+export interface ComposerFocusEditor {
+ readonly isDestroyed: boolean;
+ readonly isEditable: boolean;
+ readonly isFocused: boolean;
+ readonly view: { readonly dom: HTMLElement };
+ readonly commands: { focus: () => unknown };
+}
+
+interface PendingComposerFocusRestore {
+ readonly editor: ComposerFocusEditor;
+ readonly focusAnchor: Element | null;
+}
+
+export function hasFocusMovedToInteractiveElement(
+ focusAnchor: Element | null,
+ editorDom: HTMLElement,
+): boolean {
+ const activeElement = editorDom.ownerDocument.activeElement;
+ if (
+ !activeElement ||
+ activeElement === editorDom.ownerDocument.body ||
+ activeElement === editorDom.ownerDocument.documentElement
+ ) {
+ return false;
+ }
+ if (activeElement === focusAnchor) return false;
+ if (editorDom.contains(activeElement)) return false;
+ return isInteractiveFocusedElement(activeElement);
+}
+
+export function hasNonCollapsedSelectionOutsideComposer(editorDom: HTMLElement): boolean {
+ const selection = editorDom.ownerDocument.getSelection?.() ?? null;
+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) return false;
+ const { anchorNode, focusNode } = selection;
+ if (!anchorNode || !focusNode) return false;
+ return !editorDom.contains(anchorNode) || !editorDom.contains(focusNode);
+}
+
+export function useComposerSendFocusRestore(
+ editor: ComposerFocusEditor | null,
+ composerMutationLocked: boolean,
+ sendDispatchInFlight: boolean,
+): () => void {
+ const pendingRestoreRef = useRef<PendingComposerFocusRestore | null>(null);
+
+ useEffect(() => {
+ if (!editor) return;
+ const editorDom = editor.view.dom;
+ const ownerDocument = editorDom.ownerDocument;
+ const cancelRestoreForOutsidePointer = (event: PointerEvent) => {
+ const pendingRestore = pendingRestoreRef.current;
+ if (!pendingRestore || pendingRestore.editor !== editor) return;
+ const target = event.target;
+ if (target instanceof Node && editorDom.contains(target)) return;
+ pendingRestoreRef.current = null;
+ };
+
+ ownerDocument.addEventListener('pointerdown', cancelRestoreForOutsidePointer, true);
+ return () => {
+ ownerDocument.removeEventListener('pointerdown', cancelRestoreForOutsidePointer, true);
+ };
+ }, [editor]);
+
+ useEffect(() => {
+ if (!editor || sendDispatchInFlight || composerMutationLocked) return;
+
+ const pendingRestore = pendingRestoreRef.current;
+ if (!pendingRestore) return;
+ if (pendingRestore.editor !== editor) {
+ pendingRestoreRef.current = null;
+ return;
+ }
+
+ const frame = window.requestAnimationFrame(() => {
+ if (pendingRestoreRef.current !== pendingRestore) return;
+ if (editor.isDestroyed) {
+ pendingRestoreRef.current = null;
+ return;
+ }
+ // A second lock can begin before this frame runs. Keep the pending intent
+ // so the next unlocked effect can try again instead of dropping it.
+ if (!editor.isEditable) return;
+ if (editor.isFocused) {
+ pendingRestoreRef.current = null;
+ return;
+ }
+ if (
+ hasFocusMovedToInteractiveElement(pendingRestore.focusAnchor, editor.view.dom) ||
+ hasNonCollapsedSelectionOutsideComposer(editor.view.dom)
+ ) {
+ pendingRestoreRef.current = null;
+ return;
+ }
+
+ pendingRestoreRef.current = null;
+ editor.commands.focus();
+ });
+
+ return () => window.cancelAnimationFrame(frame);
+ }, [composerMutationLocked, editor, sendDispatchInFlight]);
+
+ return useCallback(() => {
+ pendingRestoreRef.current =
+ editor && !editor.isDestroyed && editor.isFocused
+ ? { editor, focusAnchor: editor.view.dom.ownerDocument.activeElement }
+ : null;
+ }, [editor]);
+}