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): 语音润色中切任务仍把消息发到原任务 (#2803)

Dash847c28d83f3b
diff --git a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
index a2431ae9ae..37060fada1 100644
--- a/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
+++ b/apps/desktop/src/renderer/__tests__/chatInputSessionFocus.test.ts
@@ -202,6 +202,9 @@ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
expect(chatInputSource).toContain('browserComments: browserCommentsRef.current');
expect(chatInputSource).toContain("editor.commands.focus('end');");
expect(chatInputSource).toContain('restoreFiles(restored.attachments);');
+ expect(chatInputSource).toContain(
+ 'latestStorageKeyRef.current === sourceStorageKey && editorOwnsSource',
+ );
expect(chatInputSource).toContain(
'latestStorageKeyRef.current === sourceStorageKey &&\n storageKeyForDraftRef.current === sourceStorageKey',
);
@@ -232,7 +235,9 @@ expect(capabilitySelectionBlock).toContain('!ghost?.enabled');
expect(chatInputSource).toContain('getOrCreateRemoteOptimisticTransitionCheckpoint(');
expect(chatInputSource).toContain('saveComposerTextAfterAsyncTransition(');
expect(chatInputSource).toContain('recoveryCheckpoint!');
- expect(chatInputSource).toContain('if (pendingStopAndSend || voiceInputBusyRef.current)');
+ expect(chatInputSource).toContain(
+ 'if ((pendingStopAndSend || voiceInputBusyRef.current) && prevEditorKey && voiceOwnerKey)',
+ );
expect(chatInputSource).toContain('}, [editor, storageKey]);');
expect(chatInputSource).not.toContain('}, [editor, storageKey, voiceInput.isBusy]);');
expect(chatInputSource.match(/storageKeyTransitionRecoveryRef\.current = null;/g)).toHaveLength(
diff --git a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
index 7ce2e8ccbd..d34e742bb6 100644
--- a/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
+++ b/apps/desktop/src/renderer/__tests__/effortRuntimeDirtySendGuard.test.ts
@@ -13,7 +13,9 @@ describe('effort runtime send guard', () => {
expect(chatInputSource).toContain(
'const composerEditorLocked = disabled || sendDispatchInFlight;',
);
- expect(chatInputSource).toContain('const composerMutationLocked = composerEditorLocked || voiceInput.isBusy;');
+ expect(chatInputSource).toContain(
+ 'const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;',
+ );
expect(chatInputSource).toContain('editable: !composerEditorLocked');
expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
expect(chatInputSource).toContain("trigger.kind !== 'slash' || composerMutationLockedRef.current");
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts
index 5a0c832b0e..9cb6e58832 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputButtonAnchor.test.ts
@@ -43,10 +43,10 @@ describe('ChatInput voice button anchor contract', () => {
// 只在录音态挪 Stop 是不够的:录音结束且草稿非空时 Stop 会跳回右边,语音按钮同样
// 左移一格,只是把误点风险推迟到「刚点完停止录音」那一刻。
expect(chatInputSource).toContain(
- 'const showSecondaryStop =\n showStopButton && (canSend || voiceInput.isBusy) && !sendDispatchInFlight;',
+ 'const showSecondaryStop =\n showStopButton && (canSend || voiceBusyOnCurrentComposer) && !sendDispatchInFlight;',
);
expect(chatInputSource).toContain(
- 'const mainSlotIsStop =\n showStopButton && (sendDispatchInFlight || (!canSend && !voiceInput.isBusy));',
+ 'const mainSlotIsStop =\n showStopButton && (sendDispatchInFlight || (!canSend && !voiceBusyOnCurrentComposer));',
);
});
@@ -61,7 +61,7 @@ describe('ChatInput voice button anchor contract', () => {
);
expect(slotDecisionBlock).not.toContain('voiceInput.isListening');
- expect(slotDecisionBlock).toContain('voiceInput.isBusy');
+ expect(slotDecisionBlock).toContain('voiceBusyOnCurrentComposer');
});
it('keeps the stop controls enabled while voice input owns the editor lock', () => {
@@ -69,7 +69,9 @@ describe('ChatInput voice button anchor contract', () => {
// shortcut that is needed to end the active recording.
expect(chatInputSource).toContain('const disabledRef = useRef(composerEditorLocked);');
expect(chatInputSource).toContain('disabledRef.current = composerEditorLocked;');
- expect(chatInputSource).toContain('disabled={composerEditorLocked || !editor}');
+ expect(chatInputSource).toContain(
+ 'disabled={\n composerEditorLocked ||\n !editor ||\n (voiceInput.isBusy && !voiceBusyOnCurrentComposer)\n }',
+ );
expect(chatInputSource).not.toContain('disabled={composerMutationLocked || !editor}');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
index 4d6fd2d481..f828219a7e 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEditorEditability.test.ts
@@ -11,11 +11,11 @@ const chatInputSource = readFileSync(
describe('ChatInput voice lifecycle locks', () => {
it('keeps the editor read-only for the entire voice lifecycle', () => {
expect(chatInputSource).toContain(
- 'const composerMutationLocked = composerEditorLocked || voiceInput.isBusy;',
+ 'const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;',
);
expect(chatInputSource).toContain('editor?.setEditable(!composerMutationLocked);');
expect(chatInputSource).toContain('if (composerMutationLockedRef.current) return true;');
- expect(chatInputSource).toContain('active={voiceInput.isBusy}');
+ expect(chatInputSource).toContain('active={voiceBusyOnCurrentComposer}');
});
it('keeps attachments locked while leaving permission mode available', () => {
@@ -52,5 +52,6 @@ describe('ChatInput voice lifecycle locks', () => {
expect(shortcutHandlerBlock.indexOf('[data-morph-side]')).toBeLessThan(
voiceCancelStart,
);
+ expect(shortcutHandlerBlock).toContain('voiceOwnsCurrentComposer');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
index 40c53b2283..264278c259 100644
--- a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
+++ b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts
@@ -63,7 +63,9 @@ describe('ChatInput voice input Enter-to-send contract', () => {
});
it('keeps finish-and-send enabled while listening before ASR draft arrives', () => {
- expect(chatInputSource).toContain('!voiceInput.isListening && !canSend && !hasVoiceDraftText');
+ expect(chatInputSource).toContain(
+ '!voiceBusyOnCurrentComposer && !canSend && !hasVoiceDraftText',
+ );
});
it('routes Enter from the Tiptap editor through stop-and-send or stop-and-steer while listening', () => {
@@ -129,7 +131,7 @@ describe('ChatInput voice input Enter-to-send contract', () => {
'const handleClickSend = useCallback(',
'voiceInputStopAndSendRef.current = handleClickSend;',
);
- expect(handleClickSendBlock).toContain('voiceInput.isBusy');
+ expect(handleClickSendBlock).toContain('voiceBusyOnCurrentComposer');
expect(handleClickSendBlock).toContain(
'voiceInputStopAndSendPromiseRef.current = stopAndSend;',
);
@@ -144,19 +146,102 @@ describe('ChatInput voice input Enter-to-send contract', () => {
const restoreEffectBlock = extractBetween(
chatInputSource,
'const pendingStopAndSend = voiceInputStopAndSendPromiseRef.current;',
- "// storageKey actually changed — swap the editor's content.",
+ '// ── External draft writes for the CURRENT session',
);
- expect(restoreEffectBlock).toContain('await pendingStopAndSend;');
+ expect(restoreEffectBlock).toContain('wasBusyWithoutSend');
+ expect(restoreEffectBlock).toContain('mergeDetachedVoiceTextIntoDocument(');
expect(restoreEffectBlock).toContain(
'await voiceInputStopRef.current({ waitForRefinement: true });',
);
- expect(restoreEffectBlock).toContain('if (isCurrentTransition()) {');
- expect(restoreEffectBlock).toContain('restoreNextDraft();');
+ expect(restoreEffectBlock).toContain('frozenVoiceSendRef.current = {');
+ expect(restoreEffectBlock).toContain('serialized: serializeEditorContent(editor)');
expect(restoreEffectBlock).toContain('pendingStopAndSend || voiceInputBusyRef.current');
+ expect(restoreEffectBlock).not.toContain('deferRestoreForLiveListening');
+ expect(restoreEffectBlock).not.toContain('await pendingStopAndSend;');
+ expect(restoreEffectBlock.indexOf('restoreNextDraft()')).toBeLessThan(
+ restoreEffectBlock.indexOf('wasBusyWithoutSend && prevEditorKey'),
+ );
expect(chatInputSource).toContain('}, [editor, storageKey]);');
expect(chatInputSource).not.toContain('}, [editor, storageKey, voiceInput.isBusy]);');
});
+ it('still dispatches the pinned source send after a deferred restoreNextDraft switch', () => {
+ expect(chatInputSource).toContain("from './composerSendOwnership'");
+
+ const serializeGuard = extractBetween(
+ chatInputSource,
+ 'await resolveSessionMessageReferencesForSend(editor);',
+ 'serializedContent = serializeEditorContent(editor);',
+ );
+ expect(serializeGuard).toContain('editorOwnsSourceDraft({');
+ expect(serializeGuard).toContain('editorStorageKey: storageKeyForDraftRef.current');
+ expect(serializeGuard).not.toContain('latestStorageKeyRef.current !== sourceStorageKey');
+ expect(chatInputSource).toContain('frozenVoiceSendRef.current');
+ expect(chatInputSource).toContain('voiceInput.getLastRefinement()');
+ expect(chatInputSource).toContain('applyVoiceResultToSerializedText(');
+ expect(chatInputSource).toContain('armDetachedVoiceDraftPersist(');
+ expect(
+ chatInputSource.lastIndexOf('armDetachedVoiceDraftPersist('),
+ ).toBeLessThan(
+ chatInputSource.indexOf('const voiceInput = useVoiceInput('),
+ );
+ expect(chatInputSource).toContain(
+ 'const persistKey = voiceOwnerStorageKeyRef.current ?? editorStorageKey;',
+ );
+ expect(chatInputSource).toContain('persistKey === editorStorageKey');
+ expect(chatInputSource).toContain("frozenVoiceSend.kind !== 'send'");
+ expect(chatInputSource).toContain(
+ 'frozenVoiceSend = frozenVoiceSendRef.current;',
+ );
+ expect(chatInputSource).toContain('dispatchSendInFlightKeysRef');
+ expect(chatInputSource).toContain('lockCurrentComposer');
+ expect(chatInputSource).toContain('lockComposerForEffort');
+ const planCommandSendBlock = extractBetween(
+ chatInputSource,
+ 'isPlanModeComposerCommandText(',
+ 'const text = formatBrowserCommentsForSend(',
+ );
+ expect(planCommandSendBlock).toContain('const editorOwnsSource = editorOwnsSourceDraft({');
+ expect(planCommandSendBlock).toContain('if (editorOwnsSource) {');
+ expect(planCommandSendBlock).toContain('editor.commands.clearContent(true)');
+ expect(planCommandSendBlock.indexOf('if (editorOwnsSource) {')).toBeLessThan(
+ planCommandSendBlock.indexOf('editor.commands.clearContent(true)'),
+ );
+ expect(chatInputSource).toContain('resolveSourceOwnedComposerExtras({');
+ expect(chatInputSource).toContain('sourceAttachments:');
+ expect(chatInputSource).toContain('sourceComments:');
+
+ const effortSettleBlock = extractBetween(
+ chatInputSource,
+ 'if (!runtimeSettled) {',
+ 'result = await onSend(',
+ );
+ expect(effortSettleBlock).not.toContain(
+ 'if (!isSessionScopeCurrent(sessionId, currentSessionIdRef.current))',
+ );
+ expect(effortSettleBlock).toContain('must not cancel that pinned send');
+
+ const clearBlock = extractBetween(
+ chatInputSource,
+ 'const clearSentComposer = (options?: { preserveNewerContent?: boolean }) => {',
+ 'const restoreOptimisticallyClearedComposer = (',
+ );
+ expect(clearBlock).toContain('const editorOwnsSource = editorOwnsSourceDraft({');
+ expect(clearBlock).toContain('if (!optimisticallyClearRemoteComposer) {');
+ expect(clearBlock).toContain('if (editorOwnsSource) {');
+ expect(clearBlock).toContain('editor.commands.clearContent(true)');
+ expect(clearBlock).toContain('if (sourceStorageKey) clearComposerDraft(sourceStorageKey);');
+ const deferredClearStart = clearBlock.indexOf('if (!optimisticallyClearRemoteComposer) {');
+ const deferredClearEnd = clearBlock.indexOf(
+ 'if (!options?.preserveNewerContent || !sourceStorageKey)',
+ deferredClearStart,
+ );
+ const deferredClear = clearBlock.slice(deferredClearStart, deferredClearEnd);
+ expect(deferredClear).toContain('if (editorOwnsSource) {');
+ expect(deferredClear).toContain('editor.commands.clearContent(true)');
+ expect(deferredClear).not.toContain('clearFiles()');
+ });
+
it('keeps storageKey hydration and stop completion safe across switch races', () => {
const initialHydrationBlock = extractBetween(
chatInputSource,
@@ -169,7 +254,7 @@ describe('ChatInput voice input Enter-to-send contract', () => {
const restoreEffectBlock = extractBetween(
chatInputSource,
'const transitionSeq = storageKeyTransitionSeqRef.current + 1;',
- "// storageKey actually changed — swap the editor's content.",
+ '// ── External draft writes for the CURRENT session',
);
expect(chatInputSource).toContain(
'const latestStorageKeyRef = useRef<string | undefined>(storageKey);',
@@ -180,7 +265,12 @@ describe('ChatInput voice input Enter-to-send contract', () => {
expect(restoreEffectBlock).toContain('!editor.isDestroyed');
expect(restoreEffectBlock).toContain('latestStorageKeyRef.current === storageKey');
expect(restoreEffectBlock).toContain('if (!isCurrentTransition()) return;');
- expect(restoreEffectBlock).toContain('return () => {\n cancelled = true;\n };');
+ expect(restoreEffectBlock).toContain('restoreNextDraft();');
+ expect(restoreEffectBlock).toContain('setSendDispatchInFlight(false);');
+ expect(restoreEffectBlock).toContain('wasBusyWithoutSend');
+ expect(restoreEffectBlock.indexOf('restoreNextDraft();')).toBeLessThan(
+ restoreEffectBlock.indexOf('setSendDispatchInFlight(false);'),
+ );
const waitForBusyCompletionBlock = extractBetween(
voiceInputSource,
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index 85bd4e80a8..7306a23979 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -115,6 +115,14 @@ import {
getEffortChangeCoordinator,
isSessionScopeCurrent,
} from './effortChangeQueue';
+import {
+ applyVoiceResultToSerializedText,
+ armDetachedVoiceDraftPersist,
+ editorOwnsSourceDraft,
+ mergeDetachedVoiceTextIntoDocument,
+ resolveSourceOwnedComposerExtras,
+ voiceLocksCurrentComposer,
+} from './composerSendOwnership';
import { captureComposerSendSnapshot, isComposerSendSnapshotCurrent } from './composerSendSnapshot';
import { useRemoteSessionConnection } from '@/features/cc-agent/hooks/useRemoteSessionConnection';
@@ -266,7 +274,11 @@ import {
type ComposerRenderSnapshot,
} from './composerRenderGate';
import { createComposerFrameScheduler } from './composerFrameScheduler';
-import { serializeEditorContent, serializeEditorSlice } from './composerContentSerialization';
+import {
+ serializeEditorContent,
+ serializeEditorSlice,
+ type SerializedComposerContent,
+} from './composerContentSerialization';
import {
composerDocumentContainsHostCapabilityChip,
composerDocumentContainsList,
@@ -2850,14 +2862,98 @@ export function ChatInput({
}
}, [confirmDialog, t]);
+ const voiceOwnerStorageKeyRef = useRef<string | undefined>(undefined);
+ const frozenVoiceSendRef = useRef<{
+ kind: 'send' | 'persist';
+ sourceStorageKey: string;
+ serialized: SerializedComposerContent;
+ attachments: AttachedFile[];
+ comments: BrowserCommentDraftItem[];
+ } | null>(null);
const voiceInputOptions = useMemo(
- () => ({ onMicrophonePermissionRequired: handleVoiceInputPermissionRequired }),
+ () => ({
+ onMicrophonePermissionRequired: handleVoiceInputPermissionRequired,
+ shouldApplyToEditor: () =>
+ voiceOwnerStorageKeyRef.current === undefined ||
+ voiceOwnerStorageKeyRef.current === storageKeyForDraftRef.current,
+ getDraftStorageKey: () => storageKeyForDraftRef.current,
+ }),
[handleVoiceInputPermissionRequired],
);
+ const voiceInputBusyRef = useRef(false);
+ const voiceInputStopAndSendPromiseRef = useRef<Promise<void> | null>(null);
+
+ // Declared before useVoiceInput so React 19 runs this cleanup first
+ // (declaration order). Arm must be visible before the voice hook decides
+ // whether to cancel or settle; otherwise the run is cancelled and a later
+ // unmount can skip microphone teardown.
+ useEffect(() => {
+ if (!editor) return;
+ const dataOwnerAtEffect = editorDataOwnerRef.current;
+ return () => {
+ if (!isDataOwnerGenerationCurrent(dataOwnerAtEffect)) {
+ draftSaveSchedulerRef.current?.cancel();
+ return;
+ }
+ draftSaveSchedulerRef.current?.flush();
+ const editorStorageKey = storageKeyForDraftRef.current;
+ if (!editorStorageKey) return;
+ const existing = getComposerDraft(editorStorageKey);
+ const hasText = !isEditorEmpty(editor);
+ if (hasText || existing) {
+ saveComposerDraft(
+ editorStorageKey,
+ {
+ text: editor.getJSON(),
+ attachments: existing?.attachments ?? [],
+ quotes: existing?.quotes ?? [],
+ browserComments: existing?.browserComments ?? [],
+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),
+ ...(existing?.pendingHostCapabilityGhostId
+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }
+ : {}),
+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),
+ },
+ { silent: true },
+ );
+ }
+ const persistKey = voiceOwnerStorageKeyRef.current ?? editorStorageKey;
+ // Only arm the composer that still owns this voice run. After a session
+ // switch the switch effect already persists to the source; do not write
+ // the source preview into the destination draft.
+ if (
+ voiceInputBusyRef.current &&
+ !voiceInputStopAndSendPromiseRef.current &&
+ persistKey &&
+ persistKey === editorStorageKey
+ ) {
+ armDetachedVoiceDraftPersist(
+ persistKey,
+ voiceDraftTextRef.current.trim(),
+ );
+ }
+ };
+ }, [editor]);
+
const voiceInput = useVoiceInput(editor, disabled, messages, voiceInputOptions);
+ if (voiceInput.isBusy) {
+ if (voiceOwnerStorageKeyRef.current === undefined) {
+ voiceOwnerStorageKeyRef.current = storageKeyForDraftRef.current ?? storageKey;
+ }
+ } else {
+ voiceOwnerStorageKeyRef.current = undefined;
+ if (frozenVoiceSendRef.current?.kind === 'persist') {
+ frozenVoiceSendRef.current = null;
+ }
+ }
voiceDraftTextRef.current = voiceInput.draftText;
- const composerMutationLocked = composerEditorLocked || voiceInput.isBusy;
+ const voiceBusyOnCurrentComposer = voiceLocksCurrentComposer({
+ isBusy: voiceInput.isBusy,
+ ownerStorageKey: voiceOwnerStorageKeyRef.current,
+ currentStorageKey: storageKeyForDraftRef.current,
+ });
+ const composerMutationLocked = composerEditorLocked || voiceBusyOnCurrentComposer;
composerMutationLockedRef.current = composerMutationLocked;
useEffect(() => {
editor?.setEditable(!composerMutationLocked);
@@ -2933,13 +3029,12 @@ export function ChatInput({
const voiceShortcutRef = useRef(voiceInputSettings.shortcut);
const voiceInputStateRef = useRef(voiceInput.state);
const voiceInputStopRef = useRef(handleVoiceInputStopWithRefinement);
- const voiceInputBusyRef = useRef(voiceInput.isBusy);
voiceInputBusyRef.current = voiceInput.isBusy;
+ voiceDraftTextRef.current = voiceInput.draftText;
const voiceInputCancelRef = useRef(voiceInput.cancel);
const voiceInputStopAndSendRef = useRef<
(deliveryMode?: MessageDeliveryMode) => void | Promise<void>
>(() => {});
- const voiceInputStopAndSendPromiseRef = useRef<Promise<void> | null>(null);
const voiceInputCanStopAndSendRef = useRef(false);
const composerCanSubmitRef = useRef(false);
const handleVoiceInputStartRef = useRef(handleVoiceInputStart);
@@ -3025,10 +3120,14 @@ export function ChatInput({
}
const platform = window.electronAPI?.platform;
if (event.key === 'Escape' && !event.repeat && !event.isComposing) {
+ const voiceOwnsCurrentComposer =
+ voiceOwnerStorageKeyRef.current === undefined ||
+ voiceOwnerStorageKeyRef.current === storageKeyForDraftRef.current;
if (
- currentState === 'listening' ||
- currentState === 'submitting' ||
- currentState === 'refining'
+ voiceOwnsCurrentComposer &&
+ (currentState === 'listening' ||
+ currentState === 'submitting' ||
+ currentState === 'refining')
) {
event.preventDefault();
clearPressTimer();
@@ -3298,29 +3397,32 @@ export function ChatInput({
// While dictation holds the editor read-only the native caret disappears;
// the decoration renders a mic-shaped caret at the insertion point instead
// (listening = animated level bars, submitting/refining = spinner).
- const voiceCaretState: VoiceInputCaretState | null = voiceInput.isListening
- ? 'listening'
- : voiceInput.isBusy
- ? 'processing'
- : null;
+ const voiceCaretState: VoiceInputCaretState | null = !voiceBusyOnCurrentComposer
+ ? null
+ : voiceInput.isListening
+ ? 'listening'
+ : voiceInput.isBusy
+ ? 'processing'
+ : null;
useEffect(() => {
setVoiceInputDraftDecoration(
editor,
- voiceInput.draftText,
- voiceInput.draftSource,
- voiceInput.draftRange,
+ voiceBusyOnCurrentComposer ? voiceInput.draftText : '',
+ voiceBusyOnCurrentComposer ? voiceInput.draftSource : null,
+ voiceBusyOnCurrentComposer ? voiceInput.draftRange : null,
voiceCaretState,
);
// Caret-only (no draft text yet) must also stay visible: the insertion
// point can sit outside the viewport when the composer is scrolled.
- if (voiceInput.draftText || voiceCaretState) {
+ if (voiceBusyOnCurrentComposer && (voiceInput.draftText || voiceCaretState)) {
requestAnimationFrame(() => {
if (editor) scrollVoiceInputDraftEndIntoView(editor);
});
}
}, [
editor,
+ voiceBusyOnCurrentComposer,
voiceCaretState,
voiceInput.draftRange,
voiceInput.draftSource,
@@ -3328,39 +3430,8 @@ export function ChatInput({
]);
// Route changes such as Chat -> Settings unmount the composer immediately.
- // `onUpdate` is still the primary "instant save" path, but this cleanup
- // snapshots the final editor state before React tears the instance down.
- useEffect(() => {
- if (!editor) return;
- const dataOwnerAtEffect = editorDataOwnerRef.current;
- return () => {
- if (!isDataOwnerGenerationCurrent(dataOwnerAtEffect)) {
- draftSaveSchedulerRef.current?.cancel();
- return;
- }
- draftSaveSchedulerRef.current?.flush();
- const editorStorageKey = storageKeyForDraftRef.current;
- if (!editorStorageKey) return;
- const existing = getComposerDraft(editorStorageKey);
- const hasText = !isEditorEmpty(editor);
- if (!hasText && !existing) return;
- saveComposerDraft(
- editorStorageKey,
- {
- text: editor.getJSON(),
- attachments: existing?.attachments ?? [],
- quotes: existing?.quotes ?? [],
- browserComments: existing?.browserComments ?? [],
- ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),
- ...(existing?.pendingHostCapabilityGhostId
- ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }
- : {}),
- ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),
- },
- { silent: true },
- );
- };
- }, [editor]);
+ // Draft snapshot + detached-voice arm run in the earlier effect declared
+ // before useVoiceInput, so React 19 cleanup arms persist first.
// ── composer-draft-per-session: restore on storageKey change ────────
// Whenever the parent switches `storageKey` (= `draftKey ?? sessionId`),
@@ -3494,29 +3565,78 @@ export function ChatInput({
};
const pendingStopAndSend = voiceInputStopAndSendPromiseRef.current;
- if (pendingStopAndSend || voiceInputBusyRef.current) {
+ const wasBusyWithoutSend = !pendingStopAndSend && voiceInputBusyRef.current;
+ const submittedAtSwitch = wasBusyWithoutSend ? voiceInput.getLastSubmittedText().trim() : '';
+ const unlandedPreview =
+ wasBusyWithoutSend && !submittedAtSwitch ? voiceDraftTextRef.current.trim() : '';
+ const voiceOwnerKey = voiceOwnerStorageKeyRef.current ?? prevEditorKey;
+ if ((pendingStopAndSend || voiceInputBusyRef.current) && prevEditorKey && voiceOwnerKey) {
+ const existingFreeze = frozenVoiceSendRef.current;
+ if (
+ prevEditorKey === voiceOwnerKey &&
+ (!existingFreeze || existingFreeze.sourceStorageKey === voiceOwnerKey)
+ ) {
+ const sourceDraft = getComposerDraft(prevEditorKey);
+ frozenVoiceSendRef.current = {
+ kind: pendingStopAndSend ? 'send' : 'persist',
+ sourceStorageKey: voiceOwnerKey,
+ serialized: serializeEditorContent(editor),
+ attachments: [...(sourceDraft?.attachments ?? [])],
+ comments: [...(sourceDraft?.browserComments ?? browserCommentsRef.current)],
+ };
+ }
+ }
+
+ // storageKey actually changed — swap the editor's content immediately so
+ // 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);
+ if (wasBusyWithoutSend && prevEditorKey && prevEditorKey === voiceOwnerKey) {
+ const sourceKey = prevEditorKey;
+ const persistDetachedVoice = (previousVoiceText: string, nextVoiceText: string) => {
+ if (!nextVoiceText) return;
+ const existing = getComposerDraft(sourceKey);
+ saveComposerDraft(
+ sourceKey,
+ {
+ text: mergeDetachedVoiceTextIntoDocument(
+ existing?.text,
+ previousVoiceText,
+ nextVoiceText,
+ ),
+ attachments: existing?.attachments ?? [],
+ quotes: existing?.quotes ?? [],
+ browserComments: existing?.browserComments ?? [],
+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),
+ ...(existing?.pendingHostCapabilityGhostId
+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }
+ : {}),
+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),
+ },
+ { silent: latestStorageKeyRef.current !== sourceKey },
+ );
+ };
+ // Submitted text is already in the editor snapshot. Only persist a
+ // still-ghost listening preview, then upgrade it after stop/refine.
+ if (unlandedPreview) persistDetachedVoice('', unlandedPreview);
void (async () => {
try {
- if (pendingStopAndSend) {
- await pendingStopAndSend;
- } else {
- await voiceInputStopRef.current({ waitForRefinement: true });
- }
- } finally {
- if (isCurrentTransition()) {
- saveCurrentEditorDraft();
- }
- restoreNextDraft();
+ await voiceInputStopRef.current({ waitForRefinement: true });
+ } catch {
+ const submitted = voiceInput.getLastSubmittedText().trim();
+ if (submitted && unlandedPreview) persistDetachedVoice(unlandedPreview, submitted);
+ return;
}
+ const submitted = voiceInput.getLastSubmittedText().trim();
+ const refined = voiceInput.getLastRefinement()?.refinedText.trim() ?? '';
+ const nextVoice = refined || submitted;
+ if (!nextVoice) return;
+ persistDetachedVoice(unlandedPreview || submittedAtSwitch, nextVoice);
})();
- return () => {
- cancelled = true;
- };
}
-
- // storageKey actually changed — swap the editor's content.
- saveCurrentEditorDraft();
- restoreNextDraft();
}, [editor, storageKey]);
// ── External draft writes for the CURRENT session (e.g. rewind / fork
@@ -4635,7 +4755,7 @@ export function ChatInput({
);
// ── Send / Stop wiring ─────────────────────────────────────────────
- const dispatchSendInFlightRef = useRef(false);
+ const dispatchSendInFlightKeysRef = useRef(new Set<string>());
const dispatchSendRef = useRef<(deliveryMode?: MessageDeliveryMode) => void | Promise<void>>(
() => {},
);
@@ -4646,9 +4766,10 @@ export function ChatInput({
// React 的 disabled 状态可能尚未完成下一帧渲染;同步读协调器兜住点击、快捷键、
// 语音发送等所有入口,确保 host 已登记切换意图后才允许 maker:send。
if (sessionId && hasPendingAgentSendDispatch(sessionId)) return;
- if (dispatchSendInFlightRef.current) return;
const sourceSessionId = sessionId;
const sourceStorageKey = storageKey;
+ const sendInFlightKey = sourceStorageKey ?? sourceSessionId ?? '__draft__';
+ if (dispatchSendInFlightKeysRef.current.has(sendInFlightKey)) return;
const optimisticallyClearRemoteComposer = Boolean(deviceLinkDeviceId && sourceSessionId);
// Device-link sends freeze the entire composer at click time. Any remote
// reference hydration happens against this immutable payload after the
@@ -4674,34 +4795,70 @@ export function ChatInput({
: () => {};
if (!finishAgentSendDispatch) return;
draftSaveSchedulerRef.current?.flush();
- dispatchSendInFlightRef.current = true;
+ dispatchSendInFlightKeysRef.current.add(sendInFlightKey);
// 发送新消息时立即递增 turnGen,让任何还未落地的旧 turn 预测结果失效。
// 必须在所有异步操作(resolveSessionMessageReferencesForSend / effort settle)
// 之前递增,防止旧预测在 reference 解析等异步等待期间落地到输入框。
turnGenRef.current += 1;
// 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) {
+ // click-time snapshot is cleared. A background source send after a
+ // session switch must not lock the newly restored composer.
+ const lockCurrentComposer =
+ !optimisticallyClearRemoteComposer &&
+ storageKeyForDraftRef.current === sourceStorageKey;
+ if (lockCurrentComposer) {
captureSendFocusForRestore();
setSendDispatchInFlight(true);
}
try {
let serializedContent = serializedAtClick;
+ let frozenVoiceSend = frozenVoiceSendRef.current;
if (!serializedContent) {
- await resolveSessionMessageReferencesForSend(editor);
- // Local/SSH keeps the live editor until acceptance. A routed ChatInput
- // may have switched sessions during hydration; never serialize or
- // clear the newly hydrated composer with the old send continuation.
if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;
- if (
- editor.isDestroyed ||
- latestStorageKeyRef.current !== sourceStorageKey ||
- storageKeyForDraftRef.current !== sourceStorageKey
- ) {
- return;
+ const editorOwnsSource = editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ });
+ if (editorOwnsSource) {
+ await resolveSessionMessageReferencesForSend(editor);
+ if (sourceSessionId && hasPendingAgentSwitchOperation(sourceSessionId)) return;
+ if (
+ editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ })
+ ) {
+ serializedContent = serializeEditorContent(editor);
+ if (frozenVoiceSendRef.current?.sourceStorageKey === sourceStorageKey) {
+ frozenVoiceSendRef.current = null;
+ }
+ }
+ }
+ // Switch during hydration may have just frozen the source send.
+ frozenVoiceSend = frozenVoiceSendRef.current;
+ if (!serializedContent) {
+ if (
+ !frozenVoiceSend ||
+ frozenVoiceSend.kind !== 'send' ||
+ frozenVoiceSend.sourceStorageKey !== sourceStorageKey
+ ) {
+ return;
+ }
+ const submitted = voiceInput.getLastSubmittedText();
+ const refined = voiceInput.getLastRefinement()?.refinedText ?? '';
+ serializedContent = {
+ ...frozenVoiceSend.serialized,
+ text: applyVoiceResultToSerializedText(
+ frozenVoiceSend.serialized.text,
+ submitted,
+ refined,
+ ),
+ };
+ frozenVoiceSendRef.current = null;
}
- serializedContent = serializeEditorContent(editor);
}
const {
text: editorText,
@@ -4713,12 +4870,27 @@ export function ChatInput({
hostCapability,
} = serializedContent;
let agentReferences = serializedAgentReferences;
+ const sourceDraftExtras =
+ sourceStorageKey !== undefined ? getComposerDraft(sourceStorageKey) : undefined;
+ const frozenExtras =
+ frozenVoiceSend?.sourceStorageKey === sourceStorageKey ? frozenVoiceSend : null;
+ const sourceOwnedExtras = resolveSourceOwnedComposerExtras({
+ editorOwnsSource: editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ }),
+ liveAttachments: latestAttachmentsRef.current,
+ liveComments: browserCommentsRef.current,
+ sourceAttachments: frozenExtras?.attachments ?? sourceDraftExtras?.attachments,
+ sourceComments: frozenExtras?.comments ?? sourceDraftExtras?.browserComments,
+ });
const attachmentsForSend = optimisticallyClearRemoteComposer
? attachmentsBeforeOptimisticClear
- : [...latestAttachmentsRef.current];
+ : sourceOwnedExtras.attachments;
const commentsForSend = optimisticallyClearRemoteComposer
? commentsBeforeOptimisticClear
- : [...browserCommentsRef.current];
+ : sourceOwnedExtras.comments;
if (
!hostCapability &&
isPlanModeComposerCommandText(
@@ -4727,16 +4899,23 @@ export function ChatInput({
slashCommandsReady ? mergedCommands : null,
)
) {
- planModeEntry?.onToggle(!planModeEntry.enabled);
- isRestoringRef.current = true;
- try {
- editor.commands.clearContent(true);
- } finally {
- isRestoringRef.current = false;
+ const editorOwnsSource = editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ });
+ if (editorOwnsSource) {
+ planModeEntry?.onToggle(!planModeEntry.enabled);
+ isRestoringRef.current = true;
+ try {
+ editor.commands.clearContent(true);
+ } finally {
+ isRestoringRef.current = false;
+ }
+ historyIndexRef.current = -1;
+ hydratedHistoryDocumentRef.current = null;
+ draftRef.current = null;
}
- historyIndexRef.current = -1;
- hydratedHistoryDocumentRef.current = null;
- draftRef.current = null;
if (sourceStorageKey) {
if (
shouldPreservePlanModeComposerDraft(
@@ -4748,7 +4927,7 @@ export function ChatInput({
saveComposerDraft(
sourceStorageKey,
{
- text: editor.getJSON(),
+ text: editorOwnsSource ? editor.getJSON() : (existingDraft?.text ?? null),
attachments: attachmentsForSend,
quotes: existingDraft?.quotes ?? [],
browserComments: commentsForSend,
@@ -4906,27 +5085,46 @@ export function ChatInput({
});
};
const clearSentComposer = (options?: { preserveNewerContent?: boolean }) => {
+ const editorOwnsSource = editorOwnsSourceDraft({
+ editorDestroyed: editor.isDestroyed,
+ editorStorageKey: storageKeyForDraftRef.current,
+ sourceStorageKey,
+ });
const isCurrentComposer =
- latestStorageKeyRef.current === sourceStorageKey &&
- storageKeyForDraftRef.current === sourceStorageKey &&
- !editor.isDestroyed;
+ latestStorageKeyRef.current === sourceStorageKey && editorOwnsSource;
// Local/SSH sends keep the live composer until onSend is accepted.
- // If the async send crossed a session/editor switch or the user
- // changed the snapshot while it was in flight, leave the current
- // draft untouched rather than clearing newer input.
+ // 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.
if (
!optimisticallyClearRemoteComposer &&
- (!isCurrentComposer ||
- !isComposerSendSnapshotCurrent(
- sendSnapshot,
- editor.getJSON(),
- latestAttachmentsRef.current,
- browserCommentsRef.current,
- ))
+ isCurrentComposer &&
+ !isComposerSendSnapshotCurrent(
+ sendSnapshot,
+ editor.getJSON(),
+ latestAttachmentsRef.current,
+ browserCommentsRef.current,
+ )
) {
return;
}
if (!isCurrentComposer) {
+ if (!optimisticallyClearRemoteComposer) {
+ if (editorOwnsSource) {
+ isRestoringRef.current = true;
+ try {
+ editor.commands.clearContent(true);
+ } finally {
+ isRestoringRef.current = false;
+ }
+ historyIndexRef.current = -1;
+ hydratedHistoryDocumentRef.current = null;
+ draftRef.current = null;
+ }
+ if (sourceStorageKey) clearComposerDraft(sourceStorageKey);
+ return;
+ }
if (!options?.preserveNewerContent || !sourceStorageKey) {
if (sourceStorageKey) clearComposerDraft(sourceStorageKey);
return;
@@ -5194,8 +5392,10 @@ export function ChatInput({
const coordinator = effortChangeCoordinatorRef.current;
let runtimeSettled = false;
let timeoutId: ReturnType<typeof setTimeout> | undefined;
- captureSendFocusForRestore();
- setSendDispatchInFlight(true);
+ const lockComposerForEffort =
+ !optimisticallyClearRemoteComposer &&
+ storageKeyForDraftRef.current === sourceStorageKey;
+ if (lockComposerForEffort) setSendDispatchInFlight(true);
try {
await Promise.race([
coordinator.awaitRuntimeSettled(sessionId).then(() => {
@@ -5207,7 +5407,12 @@ export function ChatInput({
]);
} finally {
if (timeoutId !== undefined) clearTimeout(timeoutId);
- setSendDispatchInFlight(false);
+ if (
+ lockComposerForEffort &&
+ storageKeyForDraftRef.current === sourceStorageKey
+ ) {
+ setSendDispatchInFlight(false);
+ }
}
// 不把 timeout 写成全局 dirty:若迟到的是「持久化失败、runtime 尚未触碰」,旧实现
@@ -5217,11 +5422,11 @@ export function ChatInput({
if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
return;
}
- // 路由切换后复用的编辑器不能把 A 会话的内容送进 B,也不能清掉 B 的草稿。
- if (!isSessionScopeCurrent(sessionId, currentSessionIdRef.current)) {
- if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
- return;
- }
+ // onSend is the click-time closure and still targets the source
+ // session. A route change while effort settles (or while voice
+ // refine was deferred) must not cancel that pinned send; clearing
+ // the live composer is gated separately so session B's draft is
+ // never wiped.
if (coordinator.isRuntimeDirty(sessionId)) {
toast.error(t('newChat.chatInput.effortRuntimeDirty'));
if (optimisticallyClearRemoteComposer) restoreRemoteComposerAndRelease();
@@ -5263,8 +5468,13 @@ export function ChatInput({
markRecentPluginUsage();
if (!optimisticallyClearRemoteComposer) clearSentComposer();
} finally {
- dispatchSendInFlightRef.current = false;
- setSendDispatchInFlight(false);
+ dispatchSendInFlightKeysRef.current.delete(sendInFlightKey);
+ if (
+ lockCurrentComposer &&
+ storageKeyForDraftRef.current === sourceStorageKey
+ ) {
+ setSendDispatchInFlight(false);
+ }
finishAgentSendDispatch();
}
},
@@ -5314,7 +5524,7 @@ export function ChatInput({
const handleClickSend = useCallback(
async (deliveryMode: MessageDeliveryMode = 'queue') => {
- if (voiceInput.isBusy) {
+ if (voiceBusyOnCurrentComposer) {
const currentCanSend = !isEditorEmpty(editor) || hasAttachments;
if (!voiceInput.isListening && !currentCanSend && voiceInput.draftText.trim().length === 0)
return;
@@ -5348,6 +5558,7 @@ export function ChatInput({
editor,
handleVoiceInputStop,
hasAttachments,
+ voiceBusyOnCurrentComposer,
voiceInput.draftText,
voiceInput.isBusy,
voiceInput.isListening,
@@ -6742,9 +6953,10 @@ export function ChatInput({
const hasMessage = !isEditorEmpty(editor);
renderSnapshotRef.current = composerRenderSnapshot(trigger, hasMessage);
const canSend = hasMessage || hasAttachments || browserComments.length > 0;
- const hasVoiceDraftText = voiceInput.draftText.trim().length > 0;
+ const hasVoiceDraftText =
+ voiceBusyOnCurrentComposer && voiceInput.draftText.trim().length > 0;
// 推荐 overlay 的可见判据:开关开启 + 有推荐词 + 输入框空 + 无附件/浏览器评论/语音草稿 + 输入框未锁定。
- // composerMutationLocked 涵盖 disabled、sendDispatchInFlight、voiceInput.isBusy 及远程只读/锁定状态。
+ // composerMutationLocked 涵盖 disabled、sendDispatchInFlight、当前输入框所属语音及远程只读/锁定状态。
const showRecommendationOverlay =
recommendationEnabled &&
!!recommendedPrompt &&
@@ -6766,9 +6978,9 @@ export function ChatInput({
// host 尚未完成切换意图登记时不能发送,否则 maker:send 可能先被旧引擎消费。
agentSwitchInFlight ||
sendDispatchInFlight ||
- (!voiceInput.isListening && !canSend && !hasVoiceDraftText) ||
- voiceInput.state === 'submitting' ||
- voiceInput.state === 'refining',
+ (!voiceBusyOnCurrentComposer && !canSend && !hasVoiceDraftText) ||
+ (voiceBusyOnCurrentComposer &&
+ (voiceInput.state === 'submitting' || voiceInput.state === 'refining')),
);
// Send / Stop 双槽语义 (voice busy = voiceInput.isBusy = listening|submitting|refining,
// 判定为何用 isBusy 而不是 isListening 见下方第三段):
@@ -6795,9 +7007,9 @@ export function ChatInput({
// (listening + submitting + refining), 让槽位从开录到润色结束保持不变; 润色期间主槽是
// 禁用态 Send (见 sendButtonDisabled), 停止任务的能力由次槽 Stop 承担.
const mainSlotIsStop =
- showStopButton && (sendDispatchInFlight || (!canSend && !voiceInput.isBusy));
+ showStopButton && (sendDispatchInFlight || (!canSend && !voiceBusyOnCurrentComposer));
const showSecondaryStop =
- showStopButton && (canSend || voiceInput.isBusy) && !sendDispatchInFlight;
+ showStopButton && (canSend || voiceBusyOnCurrentComposer) && !sendDispatchInFlight;
useEffect(() => {
voiceInputCanStopAndSendRef.current = !sendButtonDisabled;
composerCanSubmitRef.current = !sendButtonDisabled;
@@ -7188,7 +7400,7 @@ export function ChatInput({
{/* Editor — 用负 margin 向右破出容器的 px-[11px],让 scrollbar 贴到圆角边;
内层 ProseMirror 加 pr-[11px] 作为文字 gutter,视觉上文字宽度与原先一致。 */}
<VoiceInputPointerHintLayer
- active={voiceInput.isBusy}
+ active={voiceBusyOnCurrentComposer}
state={voiceInput.state}
className="w-full"
>
@@ -7203,9 +7415,11 @@ export function ChatInput({
'w-[calc(100%+11px)] -mr-[11px]',
// Disabled gets the same visual cue as the old textarea
composerMutationLocked && 'cursor-not-allowed opacity-60',
- voiceInput.isBusy && 'cursor-default',
+ voiceBusyOnCurrentComposer && 'cursor-default',
)}
- data-voice-draft-active={voiceInput.draftText ? 'true' : undefined}
+ data-voice-draft-active={
+ voiceBusyOnCurrentComposer && voiceInput.draftText ? 'true' : undefined
+ }
/>
{/* 字号 / 行高 / 颜色与原生 placeholder 对齐,单行截断防止长句撑高输入框。
py-[3px] 是镜像 .ProseMirror 的 py-[3px]:它的 -my-[3px] 会穿过这里
@@ -7445,10 +7659,14 @@ export function ChatInput({
/>
)}
<VoiceInputButton
- state={voiceInput.state}
+ state={voiceBusyOnCurrentComposer ? voiceInput.state : 'idle'}
// The surrounding controls stay locked during voice input, but
// this control must remain enabled so the recording can stop.
- disabled={composerEditorLocked || !editor}
+ disabled={
+ composerEditorLocked ||
+ !editor ||
+ (voiceInput.isBusy && !voiceBusyOnCurrentComposer)
+ }
shortcutLabel={voiceInputShortcutLabel}
onStart={handleVoiceInputStart}
onStop={handleVoiceInputPlainStop}
diff --git a/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendOwnership.test.ts b/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendOwnership.test.ts
new file mode 100644
index 0000000000..3c0f530c09
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/__tests__/composerSendOwnership.test.ts
@@ -0,0 +1,201 @@
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { discardDraft, getDraft } from '@/lib/composerDraftStore';
+
+import {
+ applyRefinementToSerializedText,
+ applyVoiceResultToSerializedText,
+ armDetachedVoiceDraftPersist,
+ clearArmedDetachedVoiceDraft,
+ editorOwnsSourceDraft,
+ hasArmedDetachedVoiceDraft,
+ mergeDetachedVoiceTextIntoDocument,
+ resolveSourceOwnedComposerExtras,
+ settleArmedDetachedVoiceDraft,
+ voiceLocksCurrentComposer,
+} from '../composerSendOwnership';
+
+describe('editorOwnsSourceDraft', () => {
+ it('is true while the reused editor still holds the source session document', () => {
+ expect(
+ editorOwnsSourceDraft({
+ editorDestroyed: false,
+ editorStorageKey: 'session-a',
+ sourceStorageKey: 'session-a',
+ }),
+ ).toBe(true);
+ });
+
+ it('is false after restoreNextDraft has swapped the editor to another session', () => {
+ expect(
+ editorOwnsSourceDraft({
+ editorDestroyed: false,
+ editorStorageKey: 'session-b',
+ sourceStorageKey: 'session-a',
+ }),
+ ).toBe(false);
+ });
+
+ it('is false when the editor has been destroyed', () => {
+ expect(
+ editorOwnsSourceDraft({
+ editorDestroyed: true,
+ editorStorageKey: 'session-a',
+ sourceStorageKey: 'session-a',
+ }),
+ ).toBe(false);
+ });
+
+ it('treats a matching undefined key as still owned (draft composer before a session id exists)', () => {
+ expect(
+ editorOwnsSourceDraft({
+ editorDestroyed: false,
+ editorStorageKey: undefined,
+ sourceStorageKey: undefined,
+ }),
+ ).toBe(true);
+ });
+});
+
+describe('voiceLocksCurrentComposer', () => {
+ it('locks only the session that started the in-flight voice run', () => {
+ expect(
+ voiceLocksCurrentComposer({
+ isBusy: true,
+ ownerStorageKey: 'session-a',
+ currentStorageKey: 'session-a',
+ }),
+ ).toBe(true);
+ expect(
+ voiceLocksCurrentComposer({
+ isBusy: true,
+ ownerStorageKey: 'session-a',
+ currentStorageKey: 'session-b',
+ }),
+ ).toBe(false);
+ });
+
+ it('does not lock after voice has settled', () => {
+ expect(
+ voiceLocksCurrentComposer({
+ isBusy: false,
+ ownerStorageKey: 'session-a',
+ currentStorageKey: 'session-a',
+ }),
+ ).toBe(false);
+ });
+});
+
+describe('applyRefinementToSerializedText', () => {
+ it('replaces the last matching ASR span with the refined text', () => {
+ expect(
+ applyRefinementToSerializedText('prefix ASR draft ASR draft', 'ASR draft', 'Asr draft.'),
+ ).toBe('prefix ASR draft Asr draft.');
+ });
+
+ it('leaves the payload unchanged when the ASR span is missing or identical', () => {
+ expect(applyRefinementToSerializedText('hello', 'ASR', 'Hello.')).toBe('hello');
+ expect(applyRefinementToSerializedText('hello', 'hello', 'hello')).toBe('hello');
+ expect(applyRefinementToSerializedText('hello', '', 'Hello.')).toBe('hello');
+ });
+});
+
+describe('applyVoiceResultToSerializedText', () => {
+ it('appends submitted or refined text when the freeze happened before ASR landed', () => {
+ expect(applyVoiceResultToSerializedText('typed prefix', 'asr draft', '')).toBe(
+ 'typed prefix\nasr draft',
+ );
+ expect(applyVoiceResultToSerializedText('typed prefix', 'asr draft', 'Asr draft.')).toBe(
+ 'typed prefix\nAsr draft.',
+ );
+ });
+
+ it('replaces a submitted span that already made it into the freeze', () => {
+ expect(applyVoiceResultToSerializedText('typed asr draft', 'asr draft', 'Asr draft.')).toBe(
+ 'typed Asr draft.',
+ );
+ });
+});
+
+describe('resolveSourceOwnedComposerExtras', () => {
+ it('keeps live extras while the editor still belongs to the source session', () => {
+ expect(
+ resolveSourceOwnedComposerExtras({
+ editorOwnsSource: true,
+ liveAttachments: ['live-file'],
+ liveComments: ['live-comment'],
+ sourceAttachments: ['source-file'],
+ sourceComments: ['source-comment'],
+ }),
+ ).toEqual({
+ attachments: ['live-file'],
+ comments: ['live-comment'],
+ });
+ });
+
+ it('does not send the next session extras after restoreNextDraft', () => {
+ expect(
+ resolveSourceOwnedComposerExtras({
+ editorOwnsSource: false,
+ liveAttachments: ['session-b-file'],
+ liveComments: ['session-b-comment'],
+ sourceAttachments: ['session-a-file'],
+ sourceComments: ['session-a-comment'],
+ }),
+ ).toEqual({
+ attachments: ['session-a-file'],
+ comments: ['session-a-comment'],
+ });
+ });
+});
+
+describe('mergeDetachedVoiceTextIntoDocument', () => {
+ it('becomes the document when the source draft is empty', () => {
+ expect(mergeDetachedVoiceTextIntoDocument(null, '', 'Hello world.')).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Hello world.' }] }],
+ });
+ });
+
+ it('replaces a previously appended listening draft with the refined text', () => {
+ const typed = {
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'typed' }] }],
+ };
+ const withListening = mergeDetachedVoiceTextIntoDocument(typed, '', 'asr draft');
+ expect(mergeDetachedVoiceTextIntoDocument(withListening, 'asr draft', 'Asr draft.')).toEqual({
+ type: 'doc',
+ content: [
+ { type: 'paragraph', content: [{ type: 'text', text: 'typed' }] },
+ { type: 'paragraph', content: [{ type: 'text', text: 'Asr draft.' }] },
+ ],
+ });
+ });
+});
+
+describe('detached voice draft persist across unmount', () => {
+ afterEach(() => {
+ clearArmedDetachedVoiceDraft();
+ discardDraft('__new_maker_draft__');
+ });
+
+ it('writes the listening draft immediately and upgrades it on settle', () => {
+ armDetachedVoiceDraftPersist('__new_maker_draft__', 'asr draft');
+ expect(getDraft('__new_maker_draft__')?.text).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'asr draft' }] }],
+ });
+ settleArmedDetachedVoiceDraft('Asr draft.');
+ expect(getDraft('__new_maker_draft__')?.text).toEqual({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Asr draft.' }] }],
+ });
+ expect(hasArmedDetachedVoiceDraft()).toBe(false);
+ });
+
+ it('does not let another composer key settle the armed persist', () => {
+ armDetachedVoiceDraftPersist('__new_maker_draft__', 'asr draft');
+ expect(hasArmedDetachedVoiceDraft('session-b')).toBe(false);
+ expect(hasArmedDetachedVoiceDraft('__new_maker_draft__')).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts b/apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts
new file mode 100644
index 0000000000..26becbe214
--- /dev/null
+++ b/apps/desktop/src/renderer/components/new-chat/composerSendOwnership.ts
@@ -0,0 +1,214 @@
+/**
+ * ChatInput reuses one Tiptap editor across session switches. A send the user
+ * already requested must still go to that source session, even after the live
+ * editor has been swapped to the next task's draft.
+ *
+ * Restore is immediate: the next task must not keep showing the source
+ * session's listening or refining text. Detached voice text is merged back
+ * into the source draft after stop/refine settles.
+ */
+
+import type { JSONContent } from '@tiptap/core';
+
+import {
+ captureDraftDiscardToken,
+ getDraft as getComposerDraft,
+ isDraftDiscardTokenCurrent,
+ saveDraft as saveComposerDraft,
+ type ComposerDraftDiscardToken,
+} from '@/lib/composerDraftStore';
+import { plainTextToComposerDocument } from '@/lib/composerListDocument';
+
+export function editorOwnsSourceDraft(input: {
+ editorDestroyed: boolean;
+ editorStorageKey: string | undefined;
+ sourceStorageKey: string | undefined;
+}): boolean {
+ return !input.editorDestroyed && input.editorStorageKey === input.sourceStorageKey;
+}
+
+export function voiceLocksCurrentComposer(input: {
+ isBusy: boolean;
+ ownerStorageKey: string | undefined;
+ currentStorageKey: string | undefined;
+}): boolean {
+ return input.isBusy && input.ownerStorageKey === input.currentStorageKey;
+}
+
+export function applyRefinementToSerializedText(
+ text: string,
+ basedOnText: string,
+ refinedText: string,
+): string {
+ if (!basedOnText || basedOnText === refinedText) return text;
+ const index = text.lastIndexOf(basedOnText);
+ if (index === -1) return text;
+ return text.slice(0, index) + refinedText + text.slice(index + basedOnText.length);
+}
+
+/** Patch a frozen composer payload after ASR/refine lands off the live editor. */
+export function applyVoiceResultToSerializedText(
+ text: string,
+ submittedText: string,
+ refinedText: string,
+): string {
+ if (refinedText) {
+ const replaced = applyRefinementToSerializedText(
+ text,
+ submittedText || refinedText,
+ refinedText,
+ );
+ if (replaced !== text) return replaced;
+ if (text.includes(refinedText)) return text;
+ return text ? `${text}\n${refinedText}` : refinedText;
+ }
+ if (submittedText && !text.includes(submittedText)) {
+ return text ? `${text}\n${submittedText}` : submittedText;
+ }
+ return text;
+}
+
+/**
+ * After a session switch the live attachment/comment refs belong to the next
+ * task. A send that started on the source session must keep using the source
+ * draft extras, never the newly restored composer.
+ */
+export function resolveSourceOwnedComposerExtras<TAttachment, TComment>(input: {
+ editorOwnsSource: boolean;
+ liveAttachments: readonly TAttachment[];
+ liveComments: readonly TComment[];
+ sourceAttachments?: readonly TAttachment[];
+ sourceComments?: readonly TComment[];
+}): { attachments: TAttachment[]; comments: TComment[] } {
+ if (input.editorOwnsSource) {
+ return {
+ attachments: [...input.liveAttachments],
+ comments: [...input.liveComments],
+ };
+ }
+ return {
+ attachments: [...(input.sourceAttachments ?? [])],
+ comments: [...(input.sourceComments ?? [])],
+ };
+}
+
+function composerBlockPlainText(block: JSONContent): string {
+ if (block.type === 'text') return block.text ?? '';
+ return (block.content ?? []).map(composerBlockPlainText).join('');
+}
+
+function composerBlocksPlainText(blocks: JSONContent[]): string {
+ return blocks.map(composerBlockPlainText).join('\n');
+}
+
+/**
+ * Land detached ASR / refined text on the source session draft after the live
+ * editor has already been swapped to another task.
+ */
+export function mergeDetachedVoiceTextIntoDocument(
+ document: JSONContent | null | undefined,
+ previousVoiceText: string,
+ nextVoiceText: string,
+): JSONContent {
+ if (!nextVoiceText) {
+ return document?.type === 'doc'
+ ? document
+ : { type: 'doc', content: [{ type: 'paragraph' }] };
+ }
+ const voiceBlocks = plainTextToComposerDocument(nextVoiceText).content ?? [];
+ const existing = document?.type === 'doc' ? [...(document.content ?? [])] : [];
+ const existingText = composerBlocksPlainText(existing).trim();
+ if (existing.length === 0 || existingText.length === 0) {
+ return { type: 'doc', content: voiceBlocks };
+ }
+ if (previousVoiceText) {
+ const previousBlocks = plainTextToComposerDocument(previousVoiceText).content ?? [];
+ if (
+ previousBlocks.length > 0 &&
+ previousBlocks.length <= existing.length &&
+ composerBlocksPlainText(existing.slice(-previousBlocks.length)) ===
+ composerBlocksPlainText(previousBlocks)
+ ) {
+ return {
+ type: 'doc',
+ content: [...existing.slice(0, -previousBlocks.length), ...voiceBlocks],
+ };
+ }
+ }
+ return { type: 'doc', content: [...existing, ...voiceBlocks] };
+}
+
+type ArmedDetachedVoiceDraft = {
+ storageKey: string;
+ previousVoiceText: string;
+ token: ComposerDraftDiscardToken;
+};
+
+let armedDetachedVoiceDraft: ArmedDetachedVoiceDraft | null = null;
+
+export function persistDetachedVoiceToDraft(
+ storageKey: string,
+ previousVoiceText: string,
+ nextVoiceText: string,
+ token?: ComposerDraftDiscardToken,
+): void {
+ if (!nextVoiceText) return;
+ if (token && !isDraftDiscardTokenCurrent(token)) return;
+ const existing = getComposerDraft(storageKey);
+ saveComposerDraft(
+ storageKey,
+ {
+ text: mergeDetachedVoiceTextIntoDocument(existing?.text, previousVoiceText, nextVoiceText),
+ attachments: existing?.attachments ?? [],
+ quotes: existing?.quotes ?? [],
+ browserComments: existing?.browserComments ?? [],
+ ...(existing?.pendingGhostId ? { pendingGhostId: existing.pendingGhostId } : {}),
+ ...(existing?.pendingHostCapabilityGhostId
+ ? { pendingHostCapabilityGhostId: existing.pendingHostCapabilityGhostId }
+ : {}),
+ ...(existing?.focusAtEnd ? { focusAtEnd: true } : {}),
+ },
+ { silent: false },
+ );
+}
+
+export function armDetachedVoiceDraftPersist(
+ storageKey: string,
+ previousVoiceText: string,
+): void {
+ armedDetachedVoiceDraft = {
+ storageKey,
+ previousVoiceText,
+ token: captureDraftDiscardToken(storageKey),
+ };
+ if (previousVoiceText) {
+ persistDetachedVoiceToDraft(
+ storageKey,
+ '',
+ previousVoiceText,
+ armedDetachedVoiceDraft.token,
+ );
+ }
+}
+
+export function hasArmedDetachedVoiceDraft(storageKey?: string): boolean {
+ if (!armedDetachedVoiceDraft) return false;
+ if (storageKey === undefined) return true;
+ return armedDetachedVoiceDraft.storageKey === storageKey;
+}
+
+export function settleArmedDetachedVoiceDraft(nextVoiceText: string): void {
+ if (!armedDetachedVoiceDraft) return;
+ const { storageKey, previousVoiceText, token } = armedDetachedVoiceDraft;
+ armedDetachedVoiceDraft = null;
+ persistDetachedVoiceToDraft(
+ storageKey,
+ previousVoiceText || nextVoiceText,
+ nextVoiceText,
+ token,
+ );
+}
+
+export function clearArmedDetachedVoiceDraft(): void {
+ armedDetachedVoiceDraft = null;
+}
diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
index b28b8771ad..0a92d41f12 100644
--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
@@ -67,6 +67,10 @@ import {
type EditorTextRange,
} from './editorRangeMapping';
import { isVoiceInputServiceConnectionError, VOICE_INPUT_ERROR_CODE_KEYS } from './overlayErrors';
+import {
+ hasArmedDetachedVoiceDraft,
+ settleArmedDetachedVoiceDraft,
+} from '@/components/new-chat/composerSendOwnership';
import {
VOICE_INPUT_DICTIONARY_LEARNING_TRACK_TIMEOUT_MS,
} from '../../shared/voiceInputDictionaryLearning';
@@ -123,6 +127,11 @@ const STOP_WAIT_REFINEMENT_FAILSAFE_MS = 90_000;
const START_READY_STOP_TIMEOUT_MS = 10_000;
const INLINE_ERROR_AUTO_DISMISS_MS = 8_000;
+export type VoiceInputRefinementSnapshot = {
+ basedOnText: string;
+ refinedText: string;
+};
+
export type UseVoiceInputResult = {
state: VoiceInputState;
draftText: string;
@@ -131,6 +140,8 @@ export type UseVoiceInputResult = {
lastError: string | null;
isListening: boolean;
isBusy: boolean;
+ getLastSubmittedText: () => string;
+ getLastRefinement: () => VoiceInputRefinementSnapshot | null;
start: () => Promise<void>;
stop: (options?: VoiceInputStopOptions) => Promise<void>;
cancel: () => Promise<void>;
@@ -154,6 +165,9 @@ type StopCompletionWaiter = {
export type UseVoiceInputOptions = {
onMicrophonePermissionRequired?: (error: string) => void | Promise<void>;
+ /** When false, keep refining in the background but do not write the live editor. */
+ shouldApplyToEditor?: () => boolean;
+ getDraftStorageKey?: () => string | undefined;
};
/**
@@ -211,8 +225,15 @@ export function useVoiceInput(
const applyingVoiceTextRef = useRef(false);
const editorRef = useRef<Editor | null>(editor);
const disabledRef = useRef(Boolean(disabled));
+ const optionsRef = useRef(options);
+ const lastRefinementRef = useRef<VoiceInputRefinementSnapshot | null>(null);
+ const lastSubmittedTextRef = useRef('');
+ const stopWithGateRef = useRef<((options?: VoiceInputStopOptions) => Promise<void>) | null>(
+ null,
+ );
editorRef.current = editor;
disabledRef.current = Boolean(disabled);
+ optionsRef.current = options;
const setVoiceState = useCallback((next: VoiceInputState) => {
stateRef.current = next;
@@ -810,6 +831,7 @@ export function useVoiceInput(
}, [readEditorSnapshot]);
const insertSubmittedText = useCallback((text: string): { start: number; end: number } | null => {
+ if (optionsRef.current?.shouldApplyToEditor?.() === false) return null;
const current = editorRef.current;
if (!current || current.isDestroyed) return null;
current.commands.focus();
@@ -834,6 +856,7 @@ export function useVoiceInput(
}, [clampEditorTextRange]);
const applyRefinedText = useCallback((event: Extract<VoiceInputRendererEvent, { type: 'refined' }>): boolean => {
+ if (optionsRef.current?.shouldApplyToEditor?.() === false) return false;
const segmentId = event.range.segmentIds[0];
const range = segmentId ? submittedRangesRef.current.get(segmentId) : undefined;
const current = editorRef.current;
@@ -915,7 +938,7 @@ export function useVoiceInput(
}, [upsertDictionaryLearningWatch]);
useEffect(() => {
- return window.electronAPI.voiceInput.onEvent((event) => {
+ const unsubscribe = window.electronAPI.voiceInput.onEvent((event) => {
if (!shouldHandleVoiceInputEvent(
ownedRunIdRef.current,
event.runId,
@@ -959,6 +982,7 @@ export function useVoiceInput(
break;
case 'submitted':
{
+ lastSubmittedTextRef.current = event.text;
const range = insertSubmittedText(event.text);
transcriptLandedRef.current = Boolean(range);
if (range) {
@@ -1000,6 +1024,7 @@ export function useVoiceInput(
// lookup keyed by segmentId binds the preview to its target text,
// exactly like the 'refined' / 'submitted' paths.
{
+ if (optionsRef.current?.shouldApplyToEditor?.() === false) break;
const segmentId = event.range.segmentIds[0];
const range = segmentId ? submittedRangesRef.current.get(segmentId) : undefined;
const current = editorRef.current;
@@ -1018,6 +1043,14 @@ export function useVoiceInput(
}
break;
case 'refined':
+ {
+ const segmentId = event.range.segmentIds[0];
+ const range = segmentId ? submittedRangesRef.current.get(segmentId) : undefined;
+ lastRefinementRef.current = {
+ basedOnText: event.segment.basedOnText ?? range?.submittedText ?? '',
+ refinedText: event.text,
+ };
+ }
if (applyRefinedText(event)) {
recordVisibleTextChanged({
runId: event.runId,
@@ -1070,10 +1103,44 @@ export function useVoiceInput(
break;
}
});
+ return () => {
+ if (hasArmedDetachedVoiceDraft(optionsRef.current?.getDraftStorageKey?.())) {
+ const timeoutId = window.setTimeout(unsubscribe, STOP_WAIT_REFINEMENT_FAILSAFE_MS);
+ const intervalId = window.setInterval(() => {
+ if (hasArmedDetachedVoiceDraft(optionsRef.current?.getDraftStorageKey?.())) return;
+ window.clearInterval(intervalId);
+ window.clearTimeout(timeoutId);
+ unsubscribe();
+ }, 100);
+ return;
+ }
+ unsubscribe();
+ };
}, [applyRefinedText, clampEditorTextRange, commitUsageStats, formatVoiceInputError, insertSubmittedText, promptCodexSessionExpired, recordVisibleTextChanged, reportVoiceInputError, resolveStopCompletion, restoreEditorFocusAfterVoiceInput, restoreSystemAudioForRecording, setVoiceState, stopEngine, upsertDictionaryLearningWatch]);
useEffect(() => {
return () => {
+ const draftKey = optionsRef.current?.getDraftStorageKey?.();
+ if (hasArmedDetachedVoiceDraft(draftKey)) {
+ const stop = stopWithGateRef.current;
+ void (stop ? stop({ waitForRefinement: true }) : Promise.resolve())
+ .catch(() => undefined)
+ .finally(() => {
+ settleArmedDetachedVoiceDraft(
+ lastRefinementRef.current?.refinedText.trim() || lastSubmittedTextRef.current.trim(),
+ );
+ commitUsageStats();
+ clearDictionaryLearningWatches();
+ void stopEngine();
+ void restoreSystemAudioForRecording();
+ clearInlineErrorDismissTimer();
+ });
+ return;
+ }
+ if (hasArmedDetachedVoiceDraft()) {
+ // Another ChatInput owns the in-flight persist; do not cancel or settle it.
+ return;
+ }
resolveStopCompletion();
commitUsageStats();
clearDictionaryLearningWatches();
@@ -1184,6 +1251,8 @@ export function useVoiceInput(
runIdRef.current = null;
ownedRunIdRef.current = null;
submittedRangesRef.current.clear();
+ lastRefinementRef.current = null;
+ lastSubmittedTextRef.current = '';
sentAudioMsRef.current = 0;
terminalOutcomeRef.current = 'success';
systemAudioMuteGateOpenRef.current = true;
@@ -1582,6 +1651,7 @@ export function useVoiceInput(
stopInFlightPromiseRef.current = stopPromise;
return stopPromise;
}, [stop]);
+ stopWithGateRef.current = stopWithGate;
const cancel = useCallback(async () => {
const runId = runIdRef.current;
@@ -1633,6 +1703,8 @@ export function useVoiceInput(
lastError,
isListening: state === 'listening',
isBusy: state === 'listening' || state === 'submitting' || state === 'refining',
+ getLastSubmittedText: () => lastSubmittedTextRef.current,
+ getLastRefinement: () => lastRefinementRef.current,
start,
stop: stopWithGate,
cancel,