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): 发送后立即清空输入框,避免与气泡重叠 (#3388)

Dash432b465d2217
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index 66c5443d83..22f3df9506 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -145,13 +145,21 @@ describe('ChatInput session switch focus contract', () => {
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',
+ '// Local/SSH lock the live composer only while the click-time document',
'try {\n let serializedContent',
);
expect(chatInputSource).toContain(
'const captureSendFocusForRestore = useComposerSendFocusRestore(',
);
+ const focusRestoreCall = extractBetween(
+ chatInputSource,
+ 'const captureSendFocusForRestore = useComposerSendFocusRestore(',
+ 'const { settings: voiceInputSettings }',
+ );
+ expect(focusRestoreCall).toContain('composerTypingLocked');
+ expect(focusRestoreCall).not.toContain('composerMutationLocked');
+ expect(focusRestoreCall).not.toContain('sendDispatchInFlight');
expect(localSendLockBlock).toContain('captureSendFocusForRestore();');
expect(localSendLockBlock.indexOf('captureSendFocusForRestore();')).toBeLessThan(
localSendLockBlock.indexOf('setSendDispatchInFlight(true);'),
@@ -198,7 +206,7 @@ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
const successfulSendBlock = extractBetween(
chatInputSource,
'if (result === false) {',
- 'if (!optimisticallyClearRemoteComposer) clearSentComposer();',
+ 'finishAgentSendDispatch();',
);
const worktreeSendBlock = extractBetween(
newMakerDraftRouteSource,
@@ -217,11 +225,103 @@ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
);
});
+ it('clears the live composer before awaiting local or remote send', () => {
+ const optimisticClear = chatInputSource.indexOf(
+ '// Click-time composer must disappear before any await that can surface',
+ );
+ const clearCall = chatInputSource.indexOf('clearSentComposer();', optimisticClear);
+ const onSend = chatInputSource.indexOf('result = await onSend(', optimisticClear);
+ const failedRestore = chatInputSource.indexOf('restoreRemoteComposerAndRelease();', onSend);
+
+ expect(optimisticClear).toBeGreaterThanOrEqual(0);
+ expect(clearCall).toBeGreaterThan(optimisticClear);
+ expect(onSend).toBeGreaterThan(clearCall);
+ expect(failedRestore).toBeGreaterThan(onSend);
+ expect(chatInputSource).not.toContain(
+ 'if (!optimisticallyClearRemoteComposer) clearSentComposer();',
+ );
+ });
+
+ it('keeps send and settings locked after optimistic clear while allowing typing', () => {
+ const unlockAfterClear = extractBetween(
+ chatInputSource,
+ '// Click-time composer must disappear before any await that can surface',
+ 'result = await onSend(',
+ );
+ expect(unlockAfterClear).toContain('dispatchSendClearedKeysRef.current.add(sendInFlightKey);');
+ expect(unlockAfterClear).toContain('setAllowTypeDuringSend(true);');
+ expect(unlockAfterClear.indexOf('dispatchSendClearedKeysRef.current.add(sendInFlightKey);')).toBeLessThan(
+ unlockAfterClear.indexOf('setAllowTypeDuringSend(true);'),
+ );
+ expect(unlockAfterClear).not.toContain('setSendDispatchInFlight(false);');
+ expect(chatInputSource).toContain(
+ 'disabled || (sendDispatchInFlight && !allowTypeDuringSend)',
+ );
+ expect(chatInputSource).toContain('sendDispatchInFlight ||');
+ expect(chatInputSource).toContain('setSendDispatchInFlight(nextSendInFlight);');
+ expect(chatInputSource).toContain(
+ 'setAllowTypeDuringSend(nextSendInFlight && nextSendCleared);',
+ );
+ expect(chatInputSource).toContain(
+ 'documentBeforeOptimisticClear = plainTextToComposerDocument(serializedContent.text);',
+ );
+ const settleLockBlock = extractBetween(
+ chatInputSource,
+ 'dispatchSendInFlightKeysRef.current.delete(sendInFlightKey);',
+ 'finishAgentSendDispatch();',
+ );
+ expect(settleLockBlock).toContain(
+ 'dispatchSendClearedKeysRef.current.delete(sendInFlightKey);',
+ );
+ expect(settleLockBlock).toContain(
+ 'storageKeyForDraftRef.current === sourceStorageKey',
+ );
+ expect(settleLockBlock).toContain('setAllowTypeDuringSend(false);');
+ expect(settleLockBlock.indexOf('storageKeyForDraftRef.current === sourceStorageKey')).toBeLessThan(
+ settleLockBlock.indexOf('setAllowTypeDuringSend(false);'),
+ );
+ });
+
+ it('snapshots the source restore payload instead of a reused destination editor', () => {
+ const snapshotBlock = extractBetween(
+ chatInputSource,
+ 'const editorOwnsSourceAtStart = editorOwnsSourceDraft({',
+ 'const dataOwnerAtOptimisticClear = getDataOwnerGeneration();',
+ );
+
+ expect(snapshotBlock).toContain(
+ 'optimisticallyClearRemoteComposer && editorOwnsSourceAtStart',
+ );
+ expect(snapshotBlock).toContain('getComposerDraft(sourceStorageKey)');
+ expect(snapshotBlock).toContain('frozenVoiceSendRef.current?.sourceStorageKey === sourceStorageKey');
+ expect(snapshotBlock).toContain('editorOwnsSourceAtStart\n ? editor.getJSON()');
+ expect(snapshotBlock.indexOf('editorOwnsSourceAtStart')).toBeLessThan(
+ snapshotBlock.indexOf('editor.getJSON()'),
+ );
+ });
+
+ it('refreshes the local restore snapshot only while the editor still owns the source draft', () => {
+ const refreshBlock = extractBetween(
+ chatInputSource,
+ 'const sendSnapshot = captureComposerSendSnapshot(',
+ 'let recentUsageMarked = false;',
+ );
+
+ expect(refreshBlock).toContain('!optimisticallyClearRemoteComposer');
+ expect(refreshBlock).toContain('editorOwnsSourceDraft({');
+ expect(refreshBlock).toContain('documentBeforeOptimisticClear = editor.getJSON();');
+ expect(refreshBlock.indexOf('editorOwnsSourceDraft({')).toBeLessThan(
+ refreshBlock.indexOf('documentBeforeOptimisticClear = editor.getJSON();'),
+ );
+ });
+
it('optimistically clears device-link composer state before awaiting send and restores without dropping newer input', () => {
const transitionBegin = chatInputSource.indexOf(
'makerChatStore.beginRemoteOptimisticComposerTransition(',
);
- const optimisticClear = chatInputSource.indexOf('if (optimisticallyClearRemoteComposer) {');
+ const optimisticClear = chatInputSource.indexOf(
+ '// Click-time composer must disappear before any await that can surface',
+ );
const frozenReferenceHydration = chatInputSource.search(
/agentReferences\s*=\s*await resolveSerializedSessionMessageReferencesForSend\(agentReferences\);/,
);
@@ -230,7 +330,7 @@ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
const restoreAndReleaseBlock = extractBetween(
chatInputSource,
'const restoreRemoteComposerAndRelease = () => {',
- 'if (optimisticallyClearRemoteComposer) {',
+ '// Click-time composer must disappear before any await that can surface',
);
expect(chatInputSource).toContain('deviceLinkDeviceId && sourceSessionId');
diff --git a/apps/desktop/src/renderer/__tests__/dispatchSendClear.test.ts b/apps/desktop/src/renderer/__tests__/dispatchSendClear.test.ts
index 2a3b74fa0c..c3860a18c7 100644
--- a/apps/desktop/src/renderer/__tests__/dispatchSendClear.test.ts
+++ b/apps/desktop/src/renderer/__tests__/dispatchSendClear.test.ts
@@ -1,41 +1,44 @@
/**
* dispatchSendClear.test.ts
* ---------------------------------------------------------------------------
- * Regression test for: new-css-input-lost-on-workdir-select
+ * Regression: sent transcript bubbles must not overlap the live composer.
*
- * Verifies the dispatchSend contract: editor content is only cleared when
- * onSend does NOT return `false`. This mirrors the inline logic in
- * ChatInput.tsx's dispatchSend callback without requiring a full React render.
+ * ChatInput now clears the click-time draft *before* awaiting onSend. Local
+ * enqueue / effort / slash / auth can take long enough for the optimistic
+ * user bubble to appear; waiting until onSend settles left the same text in
+ * both places. A rejected send restores the snapshot.
*/
import { describe, it, expect, vi } from 'vitest';
-// ── Extracted dispatchSend logic ──────────────────────────────────────────
-// This mirrors the core decision flow from ChatInput.tsx:858-870.
-// We intentionally keep it as a standalone function to unit-test the
-// "clear on send" contract independent of React / tiptap.
-
interface DispatchSendDeps {
getText: () => string;
hasAttachments: boolean;
disabled: boolean;
- onSend: (text: string) => boolean | void;
+ onSend: (text: string) => boolean | void | Promise<boolean | void>;
clearContent: () => void;
clearFiles: () => void;
+ restoreContent: () => void;
}
-function dispatchSendLogic(deps: DispatchSendDeps): void {
+async function dispatchSendLogic(deps: DispatchSendDeps): Promise<void> {
if (deps.disabled) return;
const text = deps.getText();
if (!text && !deps.hasAttachments) return;
- const result = deps.onSend(text);
- if (result === false) return;
deps.clearContent();
deps.clearFiles();
+ let result: boolean | void;
+ try {
+ result = await deps.onSend(text);
+ } catch {
+ deps.restoreContent();
+ return;
+ }
+ if (result === false) {
+ deps.restoreContent();
+ }
}
-// ── Tests ─────────────────────────────────────────────────────────────────
-
describe('dispatchSend clear-content contract', () => {
const makeDeps = (overrides: Partial<DispatchSendDeps> = {}): DispatchSendDeps => ({
getText: () => 'hello world',
@@ -44,81 +47,116 @@ describe('dispatchSend clear-content contract', () => {
onSend: vi.fn(),
clearContent: vi.fn(),
clearFiles: vi.fn(),
+ restoreContent: vi.fn(),
...overrides,
});
- it('clears editor when onSend returns void (normal send)', () => {
+ it('clears editor before onSend returns void (normal send)', async () => {
const deps = makeDeps({ onSend: vi.fn(() => undefined) });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).toHaveBeenCalledWith('hello world');
expect(deps.clearContent).toHaveBeenCalledTimes(1);
expect(deps.clearFiles).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).not.toHaveBeenCalled();
});
- it('clears editor when onSend returns true', () => {
+ it('clears editor when onSend returns true', async () => {
const deps = makeDeps({ onSend: vi.fn(() => true) });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.clearContent).toHaveBeenCalledTimes(1);
expect(deps.clearFiles).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).not.toHaveBeenCalled();
});
- it('does NOT clear editor when onSend returns false (send interrupted)', () => {
+ it('clears immediately, then restores when onSend returns false', async () => {
const deps = makeDeps({ onSend: vi.fn(() => false) });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).toHaveBeenCalledWith('hello world');
- expect(deps.clearContent).not.toHaveBeenCalled();
- expect(deps.clearFiles).not.toHaveBeenCalled();
+ expect(deps.clearContent).toHaveBeenCalledTimes(1);
+ expect(deps.clearFiles).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).toHaveBeenCalledTimes(1);
+ });
+
+ it('clears immediately, then restores when onSend throws', async () => {
+ const deps = makeDeps({
+ onSend: vi.fn(() => {
+ throw new Error('rejected');
+ }),
+ });
+ await dispatchSendLogic(deps);
+ expect(deps.clearContent).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).toHaveBeenCalledTimes(1);
+ });
+
+ it('clears before a slow onSend resolves so the bubble cannot overlap', async () => {
+ let resolveSend!: (value: boolean) => void;
+ const order: string[] = [];
+ const deps = makeDeps({
+ clearContent: vi.fn(() => {
+ order.push('clear');
+ }),
+ onSend: vi.fn(
+ () =>
+ new Promise<boolean>((resolve) => {
+ order.push('onSend-started');
+ resolveSend = resolve;
+ }),
+ ),
+ });
+ const done = dispatchSendLogic(deps);
+ expect(order).toEqual(['clear', 'onSend-started']);
+ resolveSend(true);
+ await done;
+ expect(deps.restoreContent).not.toHaveBeenCalled();
});
- it('does not send when disabled', () => {
+ it('does not send when disabled', async () => {
const deps = makeDeps({ disabled: true });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).not.toHaveBeenCalled();
expect(deps.clearContent).not.toHaveBeenCalled();
});
- it('does not send when text is empty and no attachments', () => {
+ it('does not send when text is empty and no attachments', async () => {
const deps = makeDeps({ getText: () => '', hasAttachments: false });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).not.toHaveBeenCalled();
expect(deps.clearContent).not.toHaveBeenCalled();
});
- it('sends when text is empty but has attachments', () => {
+ it('sends when text is empty but has attachments', async () => {
const deps = makeDeps({ getText: () => '', hasAttachments: true, onSend: vi.fn() });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).toHaveBeenCalledWith('');
expect(deps.clearContent).toHaveBeenCalledTimes(1);
expect(deps.clearFiles).toHaveBeenCalledTimes(1);
});
- // Regression: slash commands return void → editor should clear
- it('clears editor for slash commands (onSend returns void)', () => {
+ it('clears editor for slash commands (onSend returns void)', async () => {
const deps = makeDeps({ getText: () => '/clear', onSend: vi.fn() });
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.clearContent).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).not.toHaveBeenCalled();
});
- // Regression: workingDir missing → onSend returns false → editor preserved
- it('preserves editor when workingDir is missing (simulated via return false)', () => {
+ it('restores editor when workingDir is missing (simulated via return false)', async () => {
const deps = makeDeps({
getText: () => 'some user input',
onSend: vi.fn(() => false),
});
- dispatchSendLogic(deps);
+ await dispatchSendLogic(deps);
expect(deps.onSend).toHaveBeenCalledWith('some user input');
- expect(deps.clearContent).not.toHaveBeenCalled();
- expect(deps.clearFiles).not.toHaveBeenCalled();
+ expect(deps.clearContent).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).toHaveBeenCalledTimes(1);
});
- // Regression: API key missing → onSend returns false → editor preserved
- it('preserves editor when API key is missing (simulated via return false)', () => {
+ it('restores editor when API key is missing (simulated via return false)', async () => {
const deps = makeDeps({
getText: () => 'important message',
onSend: vi.fn(() => false),
});
- dispatchSendLogic(deps);
- expect(deps.clearContent).not.toHaveBeenCalled();
- expect(deps.clearFiles).not.toHaveBeenCalled();
+ await dispatchSendLogic(deps);
+ expect(deps.clearContent).toHaveBeenCalledTimes(1);
+ expect(deps.restoreContent).toHaveBeenCalledTimes(1);
});
});
diff --git a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
index e19f977012..c8af08d2dd 100644
--- a/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
+++ b/apps/desktop/src/renderer/__tests__/orcaWorkflowRoute.test.ts
@@ -255,7 +255,7 @@ describe('OrcaWorkflowRoute source invariants', () => {
);
// The composer is also temporarily read-only during the bounded effort-runtime
// preflight, so a pending send cannot clear text entered after its snapshot.
- expect(chatInputSource).toContain('editor?.setEditable(!composerMutationLocked)');
+ expect(chatInputSource).toContain('editor?.setEditable(!composerTypingLocked)');
});
it('does not block collaboration tab opening on worker SDK bootstrap', () => {
diff --git a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
index 9a5fb3fa21..f03eddde7a 100644
--- a/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
+++ b/apps/desktop/src/renderer/__tests__/remoteSessionSyncInvariants.test.ts
@@ -105,7 +105,7 @@ describe('CCAgentSessionView 接线不变式', () => {
);
expect(chatInputSrc).toContain('onDeferredAccepted,');
expect(chatInputSrc).toMatch(
- /if \(optimisticallyClearRemoteComposer\) \{\s*\/\/[^\n]*\n(?:\s*\/\/[^\n]*\n){2}\s*optimisticComposerRestored = false;\s*clearSentComposer\(\{ preserveNewerContent: true \}\);\s*\} else \{[\s\S]*?clearSentComposer\(\);\s*\}/,
+ /if \(optimisticallyClearRemoteComposer\) \{\s*\/\/[^\n]*\n(?:\s*\/\/[^\n]*\n){2}\s*optimisticComposerRestored = false;\s*clearSentComposer\(\{ preserveNewerContent: true \}\);\s*\} else \{[\s\S]*?clearSentComposer\(\{ preserveNewerContent: true \}\);\s*\}/,
);
});
it('已有远程 session 断线时跳过来源门禁,远程草稿与本地任务仍保留门禁', () => {
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
index f828219a7e..0fecd2cdba 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
@@ -13,7 +13,7 @@ describe('ChatInput voice lifecycle locks', () => {
expect(chatInputSource).toContain(
'const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;',
);
- expect(chatInputSource).toContain('editor?.setEditable(!composerMutationLocked);');
+ expect(chatInputSource).toContain('editor?.setEditable(!composerTypingLocked);');
expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
expect(chatInputSource).toContain('active={voiceBusyOnCurrentComposer}');
});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
index 264278c259..74e68b7fc4 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
@@ -195,7 +195,7 @@ describe('ChatInput voice input Enter-to-send contract', () => {
);
expect(chatInputSource).toContain('dispatchSendInFlightKeysRef');
expect(chatInputSource).toContain('lockCurrentComposer');
- expect(chatInputSource).toContain('lockComposerForEffort');
+ expect(chatInputSource).not.toContain('lockComposerForEffort');
const planCommandSendBlock = extractBetween(
chatInputSource,
'isPlanModeComposerCommandText(',
@@ -266,10 +266,19 @@ describe('ChatInput voice input Enter-to-send contract', () => {
expect(restoreEffectBlock).toContain('latestStorageKeyRef.current === storageKey');
expect(restoreEffectBlock).toContain('if (!isCurrentTransition()) return;');
expect(restoreEffectBlock).toContain('restoreNextDraft();');
- expect(restoreEffectBlock).toContain('setSendDispatchInFlight(false);');
+ expect(restoreEffectBlock).toContain(
+ 'dispatchSendInFlightKeysRef.current.has(nextSendKey)',
+ );
+ expect(restoreEffectBlock).toContain('setSendDispatchInFlight(nextSendInFlight);');
+ expect(restoreEffectBlock).toContain(
+ 'setAllowTypeDuringSend(nextSendInFlight && nextSendCleared);',
+ );
+ expect(restoreEffectBlock).toContain(
+ 'dispatchSendClearedKeysRef.current.has(nextSendKey)',
+ );
expect(restoreEffectBlock).toContain('wasBusyWithoutSend');
expect(restoreEffectBlock.indexOf('restoreNextDraft();')).toBeLessThan(
- restoreEffectBlock.indexOf('setSendDispatchInFlight(false);'),
+ restoreEffectBlock.indexOf('setSendDispatchInFlight(nextSendInFlight);'),
);
const waitForBusyCompletionBlock = extractBetween(
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index a6b101edda..5eb5738e85 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -1986,10 +1986,11 @@ export function ChatInput({
const folderOpen = folderPickerOpen ?? internalFolderOpen;
const setFolderOpen = onFolderPickerOpenChange ?? setInternalFolderOpen;
- // `dispatchSend` 在取发送快照后可能等待 effort runtime 同步。此窗口内继续编辑会让
- // 成功发送后的清理误删尚未发送的文字或附件,因此 composer 必须作为一个整体短暂只读。
- // 正常路径没有等待;只有设置同步中的会话最多锁 5 秒(见 dispatchSend 的 preflight)。
+ // `dispatchSend` 在取发送快照后可能等待 effort / enqueue。清空前 composer 必须只读,
+ // 避免快照后的编辑被成功清理误删。乐观清空后只放开打字;发送按钮和设置控件仍由
+ // sendDispatchInFlight 锁到 onSend 结算,避免按钮亮着点了却被 in-flight guard 静默丢掉。
const [sendDispatchInFlight, setSendDispatchInFlight] = useState(false);
+ const [allowTypeDuringSend, setAllowTypeDuringSend] = useState(false);
const composerEditorLocked = disabled || sendDispatchInFlight;
const composerMutationLockedRef = useRef(composerEditorLocked);
composerMutationLockedRef.current = composerEditorLocked;
@@ -3034,10 +3035,12 @@ export function ChatInput({
currentStorageKey: storageKeyForDraftRef.current,
});
const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;
- composerMutationLockedRef.current = composerMutationLocked;
+ const composerTypingLocked =
+ disabled || (sendDispatchInFlight && !allowTypeDuringSend) || voiceBusyOnCurrentComposer;
+ composerMutationLockedRef.current = composerTypingLocked;
useEffect(() => {
- editor?.setEditable(!composerMutationLocked);
- }, [composerMutationLocked, editor]);
+ editor?.setEditable(!composerTypingLocked);
+ }, [composerTypingLocked, editor]);
// 附件/浏览器评论/语音/锁定保持原有「失效」语义(不同于普通文字输入的暂时隐藏)。
// 同步清 ref,避免稳定闭包里的 Tab 在 React 重渲染前填入已隐藏推荐。
@@ -3065,8 +3068,7 @@ export function ChatInput({
const captureSendFocusForRestore = useComposerSendFocusRestore(
editor,
- composerMutationLocked,
- sendDispatchInFlight,
+ composerTypingLocked,
);
const { settings: voiceInputSettings } = useVoiceInputSettings();
const voiceInputShortcutLabel = useMemo(
@@ -3683,9 +3685,15 @@ export function ChatInput({
// the next task never paints the previous session's listening/refining text.
saveCurrentEditorDraft();
restoreNextDraft();
- // The reused composer now shows the destination draft. Drop the source
- // send lock so the next task is immediately editable.
- setSendDispatchInFlight(false);
+ // Destination task must stay editable. If we land back on a task whose send
+ // is still awaiting onSend, restore that task's send lock so the button
+ // stays disabled instead of silently dropping the next click. Typing stays
+ // locked until that send has actually cleared the click-time draft.
+ const nextSendKey = storageKey ?? sessionId ?? '__draft__';
+ const nextSendInFlight = dispatchSendInFlightKeysRef.current.has(nextSendKey);
+ const nextSendCleared = dispatchSendClearedKeysRef.current.has(nextSendKey);
+ setSendDispatchInFlight(nextSendInFlight);
+ setAllowTypeDuringSend(nextSendInFlight && nextSendCleared);
if (wasBusyWithoutSend && prevEditorKey && prevEditorKey === voiceOwnerKey) {
const sourceKey = prevEditorKey;
const persistDetachedVoice = (previousVoiceText: string, nextVoiceText: string) => {
@@ -4855,6 +4863,7 @@ export function ChatInput({
// ── Send / Stop wiring ─────────────────────────────────────────────
const dispatchSendInFlightKeysRef = useRef(new Set<string>());
+ const dispatchSendClearedKeysRef = useRef(new Set<string>());
const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(
() => {},
);
@@ -4874,21 +4883,40 @@ export function ChatInput({
// reference hydration happens against this immutable payload after the
// live composer is cleared, so the user can immediately type the next
// message without it leaking into or being cleared by this send.
- const serializedAtClick = optimisticallyClearRemoteComposer
- ? serializeEditorContent(editor)
- : null;
- const documentBeforeOptimisticClear = optimisticallyClearRemoteComposer
+ // Local/SSH still serialize after live reference hydration, but they
+ // keep the same click-time restore snapshot so a rejected send can put
+ // the original draft back without waiting for enqueue to settle.
+ const editorOwnsSourceAtStart = editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ });
+ // Delayed voice stop-and-send can fire after the reused editor already
+ // shows the next task. Never snapshot that live document as the source
+ // restore payload; use the frozen extras or the source draft slot.
+ const serializedAtClick =
+ optimisticallyClearRemoteComposer && editorOwnsSourceAtStart
+ ? serializeEditorContent(editor)
+ : null;
+ const sourceDraftAtStart =
+ !editorOwnsSourceAtStart && sourceStorageKey
+ ? getComposerDraft(sourceStorageKey)
+ : undefined;
+ const frozenSourceAtStart =
+ !editorOwnsSourceAtStart &&
+ frozenVoiceSendRef.current?.sourceStorageKey === sourceStorageKey
+ ? frozenVoiceSendRef.current
+ : null;
+ let documentBeforeOptimisticClear = editorOwnsSourceAtStart
? editor.getJSON()
- : null;
- const attachmentsBeforeOptimisticClear = optimisticallyClearRemoteComposer
+ : (sourceDraftAtStart?.text ?? { type: 'doc', content: [{ type: 'paragraph' }] });
+ let attachmentsBeforeOptimisticClear = editorOwnsSourceAtStart
? [...latestAttachmentsRef.current]
- : [];
- const commentsBeforeOptimisticClear = optimisticallyClearRemoteComposer
+ : [...(frozenSourceAtStart?.attachments ?? sourceDraftAtStart?.attachments ?? [])];
+ let commentsBeforeOptimisticClear = editorOwnsSourceAtStart
? [...browserCommentsRef.current]
- : [];
- const dataOwnerAtOptimisticClear = optimisticallyClearRemoteComposer
- ? getDataOwnerGeneration()
- : null;
+ : [...(frozenSourceAtStart?.comments ?? sourceDraftAtStart?.browserComments ?? [])];
+ const dataOwnerAtOptimisticClear = getDataOwnerGeneration();
const finishAgentSendDispatch = sourceSessionId
? tryBeginAgentSendDispatch(sourceSessionId)
: () => {};
@@ -4900,10 +4928,11 @@ export function ChatInput({
turnGenRef.current += 1;
showRecommendationRef.current = false;
if (sourceSessionId) dismissPromptRecommendation(sourceSessionId);
- // 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. A background source send after a
- // session switch must not lock the newly restored composer.
+ // Local/SSH lock the live composer only while the click-time document
+ // is still on screen (reference hydration / preflight). After the
+ // optimistic clear, the editor must stay editable for the next message.
+ // A background source send after a session switch must not lock the
+ // newly restored composer.
const lockCurrentComposer =
!optimisticallyClearRemoteComposer && storageKeyForDraftRef.current === sourceStorageKey;
if (lockCurrentComposer) {
@@ -4956,6 +4985,9 @@ export function ChatInput({
refined,
),
};
+ documentBeforeOptimisticClear = plainTextToComposerDocument(serializedContent.text);
+ attachmentsBeforeOptimisticClear = [...frozenVoiceSend.attachments];
+ commentsBeforeOptimisticClear = [...frozenVoiceSend.comments];
frozenVoiceSendRef.current = null;
}
}
@@ -5176,6 +5208,24 @@ export function ChatInput({
latestAttachmentsRef.current,
browserCommentsRef.current,
);
+ if (
+ !optimisticallyClearRemoteComposer &&
+ editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ })
+ ) {
+ // Local/SSH hydrate mentions on the live editor first. Refresh the
+ // restore snapshot to that post-hydration document so a rejected
+ // send puts back exactly what enqueue would have taken. After a
+ // session switch the reused editor already holds the next task;
+ // keep the click-time / frozen source extras so failure restore
+ // cannot write the target draft into the source slot.
+ documentBeforeOptimisticClear = editor.getJSON();
+ attachmentsBeforeOptimisticClear = [...latestAttachmentsRef.current];
+ commentsBeforeOptimisticClear = [...browserCommentsRef.current];
+ }
let recentUsageMarked = false;
const markRecentPluginUsage = () => {
if (!usedGhost || recentUsageMarked) return;
@@ -5195,12 +5245,13 @@ export function ChatInput({
});
const isCurrentComposer =
latestStorageKeyRef.current === sourceStorageKey && editorOwnsSource;
- // Local/SSH sends keep the live composer until onSend is accepted.
- // If the user kept typing on the same session, leave that newer
- // draft untouched. A route switch is not "newer input": the reused
- // editor may still hold the source document because restoreNextDraft
- // was deferred for voice stop/refine/send.
+ // Local/SSH also clear immediately now. If the user kept typing on
+ // the same session after that snapshot, leave the newer draft
+ // untouched. A route switch is not "newer input": the reused editor
+ // may still hold the source document because restoreNextDraft was
+ // deferred for voice stop/refine/send.
if (
+ !options?.preserveNewerContent &&
!optimisticallyClearRemoteComposer &&
isCurrentComposer &&
!isComposerSendSnapshotCurrent(
@@ -5441,9 +5492,10 @@ export function ChatInput({
optimisticComposerRestored = false;
clearSentComposer({ preserveNewerContent: true });
} else {
- // Local/SSH never entered the optimistic-clear path. Reuse the normal
- // snapshot guard so an unchanged accepted draft clears while newer edits survive.
- clearSentComposer();
+ // Folder-picker / deferred local accept: the first attempt already
+ // restored the click-time draft. Clear it now, but keep any newer
+ // edits the user typed while the picker was open.
+ clearSentComposer({ preserveNewerContent: true });
}
markRecentPluginUsage();
};
@@ -5454,13 +5506,19 @@ export function ChatInput({
releaseRemoteComposerTransition();
}
};
- if (optimisticallyClearRemoteComposer) {
- try {
- clearSentComposer();
- } catch (error) {
- restoreRemoteComposerAndRelease();
- throw error;
- }
+ // Click-time composer must disappear before any await that can surface
+ // the user bubble. Device-link already did this; local/SSH used to wait
+ // until onSend resolved, so the same text sat in both the transcript
+ // and the composer while enqueue / effort / slash / auth settled.
+ try {
+ clearSentComposer();
+ } catch (error) {
+ restoreRemoteComposerAndRelease();
+ throw error;
+ }
+ dispatchSendClearedKeysRef.current.add(sendInFlightKey);
+ if (lockCurrentComposer && storageKeyForDraftRef.current === sourceStorageKey) {
+ setAllowTypeDuringSend(true);
}
if (
optimisticallyClearRemoteComposer &&
@@ -5495,10 +5553,6 @@ export function ChatInput({
const coordinator = effortChangeCoordinatorRef.current;
let runtimeSettled = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
- const lockComposerForEffort =
- !optimisticallyClearRemoteComposer &&
- storageKeyForDraftRef.current === sourceStorageKey;
- if (lockComposerForEffort) setSendDispatchInFlight(true);
try {
await Promise.race([
coordinator.awaitRuntimeSettled(sessionId).then(() => {
@@ -5510,16 +5564,13 @@ export function ChatInput({
]);
} finally {
if (timeoutId !== undefined) clearTimeout(timeoutId);
- if (lockComposerForEffort && storageKeyForDraftRef.current === sourceStorageKey) {
- setSendDispatchInFlight(false);
- }
}
// 不把 timeout 写成全局 dirty:若迟到的是「持久化失败、runtime 尚未触碰」,旧实现
// 会永久阻断后续发送。当前这次发送直接失败;下一次会重新等待真实 settle 结果。
if (!runtimeSettled) {
toast.error(t('newChat.chatInput.effortRuntimeDirty'));
- if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
+ restoreRemoteComposerAndRelease();
return;
}
// onSend is the click-time closure and still targets the source
@@ -5529,7 +5580,7 @@ export function ChatInput({
// never wiped.
if (coordinator.isRuntimeDirty(sessionId)) {
toast.error(t('newChat.chatInput.effortRuntimeDirty'));
- if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
+ restoreRemoteComposerAndRelease();
return;
}
// 等待 commit 后,闭包里的 activeEffort 可能仍是旧 props;以该 session 已提交的
@@ -5556,21 +5607,22 @@ export function ChatInput({
},
);
} catch (error) {
- if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
+ restoreRemoteComposerAndRelease();
log.warn('send rejected:', error instanceof Error ? error.message : String(error));
return;
}
if (result === false) {
- if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
+ restoreRemoteComposerAndRelease();
return;
}
releaseRemoteComposerTransition();
markRecentPluginUsage();
- if (!optimisticallyClearRemoteComposer) clearSentComposer();
} finally {
dispatchSendInFlightKeysRef.current.delete(sendInFlightKey);
+ dispatchSendClearedKeysRef.current.delete(sendInFlightKey);
if (lockCurrentComposer && storageKeyForDraftRef.current === sourceStorageKey) {
setSendDispatchInFlight(false);
+ setAllowTypeDuringSend(false);
}
finishAgentSendDispatch();
}
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
index 839d9cffc1..9cc8012199 100644
--- a/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/useComposerSendFocusRestore.test.tsx
@@ -10,8 +10,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { useComposerSendFocusRestore } from '../useComposerSendFocusRestore';
interface HarnessProps {
- composerMutationLocked: boolean;
sendDispatchInFlight: boolean;
+ allowTypeDuringSend: boolean;
+ voiceLocked: boolean;
}
let createdEditors: Editor[] = [];
@@ -63,16 +64,27 @@ describe('useComposerSendFocusRestore', () => {
});
};
+ const typingLocked = ({
+ sendDispatchInFlight,
+ allowTypeDuringSend,
+ voiceLocked,
+ }: HarnessProps) => voiceLocked || (sendDispatchInFlight && !allowTypeDuringSend);
+
const renderRestoreHook = (editor: Editor) =>
renderHook(
- ({ composerMutationLocked, sendDispatchInFlight }: HarnessProps) => {
+ (props: HarnessProps) => {
+ const composerTypingLocked = typingLocked(props);
useEffect(() => {
- editor.setEditable(!composerMutationLocked);
- }, [composerMutationLocked, editor]);
- return useComposerSendFocusRestore(editor, composerMutationLocked, sendDispatchInFlight);
+ editor.setEditable(!composerTypingLocked);
+ }, [composerTypingLocked, editor]);
+ return useComposerSendFocusRestore(editor, composerTypingLocked);
},
{
- initialProps: { composerMutationLocked: false, sendDispatchInFlight: false },
+ initialProps: {
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ },
},
);
@@ -92,11 +104,19 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => editor.view.dom.blur());
expect(document.activeElement).toBe(document.body);
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(editor.view.dom);
@@ -112,14 +132,22 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => editor.view.dom.blur());
// dispatchSend captures a second time after the lock stole focus; this must
// not overwrite the intent captured while the composer was still focused.
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(editor.view.dom);
@@ -133,15 +161,27 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => editor.view.dom.blur());
- // The send lock has settled, but voice input still owns the mutation lock.
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: false });
+ // The send lock has settled, but voice input still owns the typing lock.
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: true,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(document.body);
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(editor.view.dom);
});
@@ -156,9 +196,17 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => button.focus());
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(button);
@@ -176,7 +224,11 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => {
editor.view.dom.blur();
const range = document.createRange();
@@ -187,7 +239,11 @@ describe('useComposerSendFocusRestore', () => {
selection?.addRange(range);
});
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(document.body);
@@ -206,7 +262,11 @@ describe('useComposerSendFocusRestore', () => {
act(() => {
hook.result.current();
});
- hook.rerender({ composerMutationLocked: true, sendDispatchInFlight: true });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
act(() => {
editor.view.dom.blur();
const range = document.createRange();
@@ -218,11 +278,43 @@ describe('useComposerSendFocusRestore', () => {
});
fireEvent.pointerDown(message);
- hook.rerender({ composerMutationLocked: false, sendDispatchInFlight: false });
+ hook.rerender({
+ sendDispatchInFlight: false,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
flushAnimationFrames();
expect(document.activeElement).toBe(document.body);
expect(document.getSelection()?.isCollapsed).toBe(true);
expect(document.getSelection()?.anchorNode).toBe(messageText);
});
+
+ it('restores focus when typing is allowed during an in-flight send', () => {
+ const editor = createEditor();
+ const hook = renderRestoreHook(editor);
+
+ focusComposerSelection(editor);
+ act(() => {
+ hook.result.current();
+ });
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: false,
+ voiceLocked: false,
+ });
+ act(() => editor.view.dom.blur());
+ expect(document.activeElement).toBe(document.body);
+
+ hook.rerender({
+ sendDispatchInFlight: true,
+ allowTypeDuringSend: true,
+ voiceLocked: false,
+ });
+ flushAnimationFrames();
+
+ expect(document.activeElement).toBe(editor.view.dom);
+ expect(editor.state.selection.from).toBe(2);
+ expect(editor.state.selection.to).toBe(6);
+ });
});
diff --git a/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts
index 1f8135afa4..9a6660245a 100644
--- a/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts
+++ b/apps/desktop/src/renderer/components/new-chat/useComposerSendFocusRestore.ts
@@ -42,8 +42,7 @@ export function hasNonCollapsedSelectionOutsideComposer(editorDom: HTMLElement):
export function useComposerSendFocusRestore(
editor: ComposerFocusEditor | null,
- composerMutationLocked: boolean,
- sendDispatchInFlight: boolean,
+ composerTypingLocked: boolean,
): () => void {
const pendingRestoreRef = useRef<PendingComposerFocusRestore | null>(null);
@@ -66,7 +65,7 @@ export function useComposerSendFocusRestore(
}, [editor]);
useEffect(() => {
- if (!editor || sendDispatchInFlight || composerMutationLocked) return;
+ if (!editor || composerTypingLocked) return;
const pendingRestore = pendingRestoreRef.current;
if (!pendingRestore) return;
@@ -101,7 +100,7 @@ export function useComposerSendFocusRestore(
});
return () => window.cancelAnimationFrame(frame);
- }, [composerMutationLocked, editor, sendDispatchInFlight]);
+ }, [composerTypingLocked, editor]);
return useCallback(() => {
// dispatchSend 会在本地路径与远端路径各捕获一次焦点(第二处在 effort settle 后触发)。