Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(desktop): add composer send shortcut preference (#1346)
Raymond Lauc576cfbd65dd
diff --git a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.tsindex a62ceb5b0b..cb475ea95a 100644--- a/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/anthropicModelDiscovery.test.ts@@ -42,6 +42,12 @@ const oauthRefreshMock = vi.hoisted(() => ({}));vi.mock('../claude-oauth-refresh.js', () => oauthRefreshMock);+// HTTP discovery tests inject global fetch responses; keep the production+// proxy-aware transport out of this unit's network boundary.+vi.mock('../outbound-fetch.js', () => ({+ outboundFetch: (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init),+}));+import {evaluateHttpShrink,isDegenerateModelListShrink,diff --git a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.tsindex 4a83fc9984..32ab813f3d 100644--- a/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/grokAuthRejectionRecovery.test.ts@@ -44,6 +44,12 @@ vi.mock('../nativeProviderAuthBinding.js', () => ({}),}));+// The recovery tests inject global fetch responses; keep the production+// proxy-aware transport out of this unit's network boundary.+vi.mock('../outbound-fetch.js', () => ({+ outboundFetch: (input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init),+}));+import {logoutGrok,recoverGrokAuthAfterRejection,diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/android.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/android.test.tsindex 72fb876aeb..46adfa974a 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/android.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/android.test.ts@@ -1,8 +1,9 @@import { EventEmitter } from 'node:events';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-const { existsSyncMock, spawnMock } = vi.hoisted(() => ({+const { existsSyncMock, outboundFetchMock, spawnMock } = vi.hoisted(() => ({existsSyncMock: vi.fn(),+ outboundFetchMock: vi.fn(),spawnMock: vi.fn(),}));@@ -41,6 +42,10 @@ vi.mock('electron', () => ({},}));+vi.mock('../../maker-host/outbound-fetch.js', () => ({+ outboundFetch: (...args: unknown[]) => outboundFetchMock(...args),+}));+import {callAndroidDriverTool,clearAndroidStateSnapshotsForTest,@@ -163,6 +168,7 @@ describe('android mcp integration', () => {beforeEach(() => {spawnMock.mockReset();existsSyncMock.mockReset();+ outboundFetchMock.mockReset();existsSyncMock.mockReturnValue(false);clearAndroidStateSnapshotsForTest();setAndroidAutomationSettingsReaderForTest(null);@@ -706,14 +712,13 @@ emulator-5554 device product:sdk_gphone64_arm64 model:Pixel_8 device:emu transpoconst archSpy = vi.spyOn(process, 'arch', 'get').mockReturnValue('x64');setAndroidPlatformToolsDownloadTimeoutForTest(1);mockAdbSpawn({ error: Object.assign(new Error('spawn adb ENOENT'), { code: 'ENOENT' }) });- const fetchMock = vi.fn((_url: string, init?: { signal?: AbortSignal }) => (+ outboundFetchMock.mockImplementation((_url: string, init?: { signal?: AbortSignal }) => (new Promise<Response>((_resolve, reject) => {init?.signal?.addEventListener('abort', () => {reject(Object.assign(new Error('download aborted'), { name: 'AbortError' }));}, { once: true });})));- vi.stubGlobal('fetch', fetchMock);try {const result = await prepareAndroidAdb();@@ -725,7 +730,7 @@ emulator-5554 device product:sdk_gphone64_arm64 model:Pixel_8 device:emu transpo});expect(slashPath(result.path)).toBe('/Users/tester/android-platform-tools/linux-x64/platform-tools/adb');expect(result.error).toContain('Android platform-tools download timed out after 1ms');- expect(fetchMock).toHaveBeenCalledWith(+ expect(outboundFetchMock).toHaveBeenCalledWith('https://dl.google.com/android/repository/platform-tools-latest-linux.zip',{ signal: expect.any(AbortSignal) },);diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex d7cae37124..0588462bf6 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -51,10 +51,15 @@ vi.mock('../../secrets/providerSecretStore.js', () => ({readCustomProviderKey: vi.fn(),}));-vi.mock('undici', () => ({- fetch: vi.fn(),+vi.mock('../../maker-host/outbound-proxy-resolver.js', () => ({+ resolveDesktopOutboundProxy: vi.fn(async () => null),}));+vi.mock('undici', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return { ...actual, fetch: vi.fn() };+});+// SUT 链(maker-host/runtime-configs → effectiveXdGatewayBaseUrl)运行期读// model-access 下发的 endpoint;mock 成 fixture 值。vi.mock('../../model-access/effectiveEndpoint.js', async () => {diff --git a/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.tsindex dba0f9acb5..afbd04db54 100644--- a/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/CodexResponsesTextModelClient.test.ts@@ -1,13 +1,16 @@import { afterEach, describe, expect, it, vi } from 'vitest';// CodexResponsesTextModelClient uses undici.fetch + Agent for the shared-// keepalive pool. Stub them so the tests stay hermetic; Agent is a no-op since-// we don't exercise pool behavior here.+// keepalive pool. Keep the real Undici exports and replace only fetch so the+// tests stay hermetic without changing the transport module's shape.const undiciFetchMock = vi.fn();-vi.mock('undici', () => ({- fetch: (...args: unknown[]) => undiciFetchMock(...args),- Agent: class { /* no-op stub */ },-}));+vi.mock('undici', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return {+ ...actual,+ fetch: (...args: unknown[]) => undiciFetchMock(...args),+ };+});import { CodexResponsesTextModelClient } from '../CodexResponsesTextModelClient.js';diff --git a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.tsindex 21e231f2ee..3ccd45710b 100644--- a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTextModelClient.test.ts@@ -1,10 +1,13 @@import { afterEach, describe, expect, it, vi } from 'vitest';const undiciFetchMock = vi.fn();-vi.mock('undici', () => ({- fetch: (...args: unknown[]) => undiciFetchMock(...args),- Agent: class { /* no-op stub */ },-}));+vi.mock('undici', async (importOriginal) => {+ const actual = await importOriginal<Record<string, unknown>>();+ return {+ ...actual,+ fetch: (...args: unknown[]) => undiciFetchMock(...args),+ };+});import { LiteLlmTextModelClient } from '../LiteLlmTextModelClient.js';import { isRefinerModelOutputError } from '../refinerErrorKind.js';diff --git a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.tsindex b833cfc396..2f16e5eb62 100644--- a/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts+++ b/apps/desktop/src/main/voice-input/__tests__/LiteLlmTranscriptionProvider.test.ts@@ -1,5 +1,10 @@import { afterEach, describe, expect, it, vi } from 'vitest';+const outboundFetchMock = vi.hoisted(() => vi.fn());+vi.mock('../../maker-host/outbound-fetch.js', () => ({+ outboundFetch: (...args: unknown[]) => outboundFetchMock(...args),+}));+import {LiteLlmTranscriptionProvider,transcribeLiteLlmAudioFile,@@ -8,13 +13,13 @@ import type { AsrEvent } from '@cindy/voice-input-core';describe('LiteLlmTranscriptionProvider', () => {afterEach(() => {- vi.unstubAllGlobals();+ outboundFetchMock.mockReset();});it('posts captured audio to LiteLLM using ElevenLabs Scribe v2', async () => {let requestUrl = '';let requestInit: RequestInit | undefined;- const fetchMock = vi.fn(async (url: string | URL | Request, init?: RequestInit) => {+ outboundFetchMock.mockImplementation(async (url: string | URL | Request, init?: RequestInit) => {requestUrl = String(url);requestInit = init;return new Response(JSON.stringify({ text: 'hello world' }), {@@ -22,7 +27,6 @@ describe('LiteLlmTranscriptionProvider', () => {headers: { 'Content-Type': 'application/json' },});});- vi.stubGlobal('fetch', fetchMock);const events: AsrEvent[] = [];const provider = new LiteLlmTranscriptionProvider({@@ -47,14 +51,13 @@ describe('LiteLlmTranscriptionProvider', () => {it('posts an existing audio file to LiteLLM and returns trimmed text', async () => {let requestInit: RequestInit | undefined;- const fetchMock = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {+ outboundFetchMock.mockImplementation(async (_url: string | URL | Request, init?: RequestInit) => {requestInit = init;return new Response(JSON.stringify({ text: ' mobile voice ' }), {status: 200,headers: { 'Content-Type': 'application/json' },});});- vi.stubGlobal('fetch', fetchMock);const text = await transcribeLiteLlmAudioFile({proxyApiKey: 'sk-test',diff --git a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts b/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.tsindex ec72666eab..9dc568a1bc 100644--- a/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputListContinuation.test.ts@@ -10,8 +10,7 @@ const chatInputSource = readFileSync(/*** ChatInput 列表接续接线契约:* - Shift/Alt+Enter 优先处理结构化列表,再兼容旧纯文本列表;- * - 普通 Enter 一律保持"发送"语义,绝不被列表接续拦截(2026-07 产品定案:- * Enter=发送的肌肉记忆优先);+ * - 普通 Enter 不由列表接续拦截,发送或原生换行由共享快捷键 resolver 决定;* - 守住 IME composition 边界。* 结构化与旧纯文本接续行为由各自的编辑器测试覆盖。*/@@ -27,7 +26,7 @@ describe('ChatInput list continuation wiring contract', () => {const block = extractBetween(chatInputSource,'// Shift/Alt+Enter — split or exit a structured item.',- '// Plain Enter keeps the existing queue semantics.',+ '// Resolve the configurable send shortcut after structured list handling.',);expect(block).toContain('(event.shiftKey || event.altKey) &&');expect(block).toContain('!event.metaKey');@@ -36,6 +35,7 @@ describe('ChatInput list continuation wiring contract', () => {expect(block).toContain('if (handleStructuredListBreak(view) || applyListContinuation(view)) {',);+ expect(block).not.toContain('resolveComposerEnterIntent');// 非列表行必须放行给 ComposerHardBreak 默认换行expect(block).toContain('return false;');});@@ -65,14 +65,15 @@ describe('ChatInput list continuation wiring contract', () => {);});- it('never intercepts plain Enter — send semantics stay untouched', () => {+ it('keeps plain Enter outside list continuation — the resolver owns its semantics', () => {const plainEnterBlock = extractBetween(chatInputSource,- '// Plain Enter keeps the existing queue semantics.',- "void dispatchSendRef.current(wantsSteer ? 'steer' : 'queue');",+ '// Resolve the configurable send shortcut after structured list handling.',+ "if (enterIntent === 'queue' || enterIntent === 'steer') {",);expect(plainEnterBlock).not.toContain('handleStructuredListBreak');expect(plainEnterBlock).not.toContain('applyListContinuation');+ expect(plainEnterBlock).toContain('resolveComposerEnterIntent(');});it('keeps tabular-nums on the editor so multi-line list prefixes align', () => {diff --git a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.tsindex edd1e91741..3aab718155 100644--- a/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts+++ b/apps/desktop/src/renderer/__tests__/chatInputSteerShortcut.test.ts@@ -2,6 +2,12 @@ import { readFileSync } from 'node:fs';import { resolve } from 'node:path';import { describe, expect, it } from 'vitest';+import {+ resolveComposerEnterIntent,+ type ComposerEnterEvent,+ type ComposerEnterIntent,+} from '@/hooks/useComposerSendShortcutPreference';+const chatInputSource = readFileSync(resolve(__dirname, '..', 'components', 'new-chat', 'ChatInput.tsx'),'utf8',@@ -10,6 +16,10 @@ const pendingQueuePanelSource = readFileSync(resolve(__dirname, '..', 'components', 'new-chat', 'PendingQueuePanel.tsx'),'utf8',).replace(/\r\n?/g, '\n');+const composerSettingsSource = readFileSync(+ resolve(__dirname, '..', 'components', 'settings', 'ComposerSendShortcutSection.tsx'),+ 'utf8',+).replace(/\r\n?/g, '\n');describe('ChatInput steer shortcut contract', () => {it('routes Cmd/Ctrl+Enter in the composer through steer while a turn is running', () => {@@ -20,43 +30,42 @@ describe('ChatInput steer shortcut contract', () => {);const editorEnterBlock = extractBetween(chatInputSource,- '// Plain Enter keeps the existing queue semantics.',- 'return true;\n }\n return false;',+ '// Resolve the configurable send shortcut after structured list handling.',+ 'return false;\n },\n },',);- const windowComposerSteerBlock = extractBetween(+ const windowComposerCaptureBlock = extractBetween(windowKeydownBlock,- 'if (\n showStopButtonRef.current &&',+ 'const enterIntent = resolveComposerEnterIntent(',"if (\n currentState === 'listening'",);- const editorSteerChoice = extractBetween(- editorEnterBlock,- 'const wantsSteer =',- "void dispatchSendRef.current(wantsSteer ? 'steer' : 'queue');",- );-expect(chatInputSource).toContain('const composerCanSubmitRef = useRef(false);');expect(chatInputSource).toContain('composerCanSubmitRef.current = !sendButtonDisabled;');expect(windowKeydownBlock).toContain('showStopButtonRef.current');+ expect(windowKeydownBlock).toContain('const platform = window.electronAPI?.platform;');expect(windowKeydownBlock).toContain('isComposerEnterTarget(event.target)');- expect(windowKeydownBlock).toContain("event.key === 'Enter'");- expect(windowKeydownBlock).toContain('event.metaKey || event.ctrlKey');- expect(windowKeydownBlock).toContain('!event.altKey');+ expect(windowKeydownBlock).toContain('resolveComposerEnterIntent(');+ expect(windowKeydownBlock).toContain('getComposerSendShortcutPreference()');+ expect(windowKeydownBlock).toContain(+ 'const isModifiedEnter = hasComposerModifier(event, platform);',+ );+ expect(windowKeydownBlock).toContain("(enterIntent === 'queue' || enterIntent === 'steer')");expect(windowKeydownBlock).toContain("currentState !== 'listening'");- expect(windowKeydownBlock).toContain("void dispatchSendRef.current('steer');");+ expect(windowKeydownBlock).toContain('void dispatchSendRef.current(enterIntent);');expect(chatInputSource).toContain("'Alt-Enter': () => this.editor.commands.setHardBreak()");expect(chatInputSource).toContain('ComposerHardBreak');expect(chatInputSource).toContain('turnRunning={showStopButton}');expect(chatInputSource).toContain('onSteer={onQueueSteer ? handleQueueSteer : undefined}');- expect(editorEnterBlock).toContain("event.key === 'Enter' && !event.shiftKey && !event.altKey");- expect(editorEnterBlock).toContain("voiceInputStateRef.current !== 'listening'");- expect(editorEnterBlock).toContain(- "void dispatchSendRef.current(wantsSteer ? 'steer' : 'queue');",- );+ expect(editorEnterBlock).toContain('resolveComposerEnterIntent(');+ expect(editorEnterBlock).toContain('getComposerSendShortcutPreference()');+ expect(editorEnterBlock).toContain('turnRunning: showStopButtonRef.current');+ expect(editorEnterBlock).toContain('platform: window.electronAPI?.platform');+ expect(editorEnterBlock).toContain("if (enterIntent === 'native') return false;");+ expect(editorEnterBlock).toContain("if (enterIntent === 'ignore')");+ expect(editorEnterBlock).toContain('void dispatchSendRef.current(enterIntent);');// Tiptap's document is current before React's send-button effect updates- // composerCanSubmitRef. The shortcut must not use that lagging UI mirror- // to choose between steer and normal queue delivery.- expect(windowComposerSteerBlock).not.toContain('composerCanSubmitRef.current');- expect(editorSteerChoice).not.toContain('composerCanSubmitRef.current');+ // composerCanSubmitRef. The resolver must not use that lagging UI mirror.+ expect(windowComposerCaptureBlock).not.toContain('composerCanSubmitRef.current');+ expect(editorEnterBlock).not.toContain('composerCanSubmitRef.current');});it('steers without an interrupt confirmation gate (same-turn injection)', () => {@@ -78,8 +87,71 @@ describe('ChatInput steer shortcut contract', () => {"const base = t(turnRunning ? 'newChat.pendingQueue.steerRunningTip' : 'newChat.pendingQueue.steerPausedTip');",);});++ it('keeps mode A queue and running-turn steer semantics on the Tiptap path', () => {+ expect(+ resolveComposerEnterIntent(makeEnterEvent(), 'enter', {+ turnRunning: false,+ platform: 'darwin',+ }),+ ).toBe('queue');+ expect(+ resolveComposerEnterIntent(makeEnterEvent({ metaKey: true }), 'enter', {+ turnRunning: true,+ platform: 'darwin',+ }),+ ).toBe('steer');+ expect(+ resolveComposerEnterIntent(makeEnterEvent({ ctrlKey: true }), 'enter', {+ turnRunning: false,+ platform: 'darwin',+ }),+ ).toBe('queue');+ });++ it('maps mode B modifier send and native/boundary cases without list interception', () => {+ const modeB = (event: ComposerEnterEvent): ComposerEnterIntent =>+ resolveComposerEnterIntent(event, 'modifier-enter', {+ turnRunning: true,+ platform: 'darwin',+ });++ expect(modeB(makeEnterEvent())).toBe('native');+ expect(modeB(makeEnterEvent({ metaKey: true }))).toBe('queue');+ expect(modeB(makeEnterEvent({ ctrlKey: true }))).toBe('queue');+ expect(modeB(makeEnterEvent({ shiftKey: true }))).toBeNull();+ expect(modeB(makeEnterEvent({ altKey: true }))).toBeNull();+ expect(modeB(makeEnterEvent({ isComposing: true }))).toBe('native');+ expect(modeB(makeEnterEvent({ repeat: true }))).toBe('native');+ expect(modeB(makeEnterEvent({ metaKey: true, repeat: true }))).toBe('ignore');+ });++ it('wires Settings preference updates to ChatInput copy while preserving row-level steer', () => {+ expect(composerSettingsSource).toContain('useComposerSendShortcutPreference()');+ expect(composerSettingsSource).toContain("setPreference(enabled ? 'modifier-enter' : 'enter')");+ expect(composerSettingsSource).toContain("setPreference('enter');");+ expect(chatInputSource).toContain('useComposerSendShortcutPreference()');+ expect(chatInputSource).toContain('getComposerSendShortcutLabel(');+ expect(chatInputSource).toContain("composerSendShortcutPreference === 'modifier-enter'");+ expect(chatInputSource).toContain('newChat.sendButton.queueTooltipSendMode');+ expect(pendingQueuePanelSource).toContain('isPendingQueueSteerShortcut');+ expect(pendingQueuePanelSource).toContain('void onSteer(entry.clientId);');+ });});+function makeEnterEvent(overrides: Partial<ComposerEnterEvent> = {}): ComposerEnterEvent {+ return {+ key: 'Enter',+ shiftKey: false,+ altKey: false,+ metaKey: false,+ ctrlKey: false,+ repeat: false,+ isComposing: false,+ ...overrides,+ };+}+function extractBetween(sourceBlock: string, startNeedle: string, endNeedle: string): string {const start = sourceBlock.indexOf(startNeedle);const end = sourceBlock.indexOf(endNeedle, start);diff --git a/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts b/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.tsindex a253d8eb92..4ade2ccd2e 100644--- a/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts+++ b/apps/desktop/src/renderer/__tests__/emptyDocSelectionGuard.test.ts@@ -54,8 +54,8 @@ describe('isBlankParagraphDoc', () => {expect(isBlankParagraphDoc(editor.state.doc)).toBe(false);});- // 多段落来自引用回填 / 历史草稿等程序化构造与多段粘贴;Shift/Alt/Mod+Enter 是- // hardBreak(留在同一 paragraph 内),plain Enter 是发送,都不产生新段落。+ // 多段落来自引用回填 / 历史草稿等程序化构造与多段粘贴;Shift/Alt+Enter 是+ // hardBreak(留在同一 paragraph 内),普通/修饰键 Enter 是否发送由快捷键 resolver 决定。it('多个空段落不是真空(多段结构本身是真实内容)', () => {const editor = makeEditor();editor.commands.setContent({diff --git a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.tsindex d659b99f3c..2535e74609 100644--- a/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts+++ b/apps/desktop/src/renderer/__tests__/voiceInputEnterToSend.test.ts@@ -28,14 +28,16 @@ describe('ChatInput voice input Enter-to-send contract', () => {expect(keydownBlock).toContain("currentState === 'listening'");expect(keydownBlock).toContain('voiceInputCanStopAndSendRef.current');expect(keydownBlock).toContain('isVoiceInputEnterTarget(event.target)');- expect(keydownBlock).toContain("event.key === 'Enter'");+ expect(keydownBlock).toContain('resolveComposerEnterIntent(');+ expect(keydownBlock).toContain('getComposerSendShortcutPreference()');+ expect(keydownBlock).toContain('const platform = window.electronAPI?.platform;');+ expect(keydownBlock).toContain('turnRunning: showStopButtonRef.current');+ expect(keydownBlock).toContain("(enterIntent === 'queue' || enterIntent === 'steer')");expect(keydownBlock).toContain('!isVoiceInputShortcutMatch(event, voiceShortcutRef.current)');- expect(keydownBlock).toContain(- "(event.metaKey || event.ctrlKey) &&\n showStopButtonRef.current &&\n composerCanSubmitRef.current\n ? 'steer'\n : 'queue'",- );expect(keydownBlock).toContain('event.preventDefault();');expect(keydownBlock).toContain('event.stopPropagation();');- expect(keydownBlock).toContain('void voiceInputStopAndSendRef.current(deliveryMode);');+ expect(keydownBlock).toContain('void voiceInputStopAndSendRef.current(enterIntent);');+ expect(keydownBlock).not.toContain('composerCanSubmitRef.current');});it('allows voice Enter-to-send only when the event target itself falls back to the document body', () => {@@ -66,29 +68,45 @@ describe('ChatInput voice input Enter-to-send contract', () => {);const enterBlock = extractBetween(tiptapKeydownBlock,- "if (event.key === 'Enter' && !event.shiftKey && !event.altKey) {",- 'const wantsSteer =',+ '// Resolve the configurable send shortcut after structured list handling.',+ 'void voiceInputStopAndSendRef.current(enterIntent);',);+ expect(enterBlock).toContain("if (enterIntent === 'queue' || enterIntent === 'steer') {");expect(enterBlock).toContain("voiceInputStateRef.current === 'listening'");expect(enterBlock).toContain('voiceInputCanStopAndSendRef.current');expect(enterBlock).toContain('const isEditorEnterTarget = event.target instanceof Node && view.dom.contains(event.target);');expect(enterBlock).toContain('isEditorEnterTarget');expect(enterBlock).not.toContain('isComposerEnterTarget(event.target)');expect(enterBlock).toContain('!isVoiceInputShortcutMatch(event, voiceShortcutRef.current)');- expect(enterBlock).toContain(- "(event.metaKey || event.ctrlKey) &&\n showStopButtonRef.current &&\n composerCanSubmitRef.current\n ? 'steer'\n : 'queue'",- );- expect(enterBlock).toContain('!event.altKey');- expect(enterBlock).toContain('!event.repeat');- expect(enterBlock).toContain('!event.isComposing');+ expect(enterBlock).toContain('resolveComposerEnterIntent(');+ expect(enterBlock).toContain('getComposerSendShortcutPreference()');+ expect(enterBlock).toContain('platform: window.electronAPI?.platform');+ expect(enterBlock).toContain('turnRunning: showStopButtonRef.current');expect(enterBlock).toContain('event.stopPropagation();');- expect(enterBlock).toContain('void voiceInputStopAndSendRef.current(deliveryMode);');+ expect(chatInputSource).toContain('void voiceInputStopAndSendRef.current(enterIntent);');});- it('shows Enter shortcuts in the same label-dot-shortcut tooltip style as the voice input button', () => {- expect(chatInputSource).toContain("`${t('newChat.chatInput.voiceInput.finishAndSend')} · Enter`");- expect(chatInputSource).toContain("`${t('newChat.sendButton.send')} · Enter`");+ it('uses the configured composer shortcut in send and voice tooltips', () => {+ expect(chatInputSource).toContain(+ 'const { preference: composerSendShortcutPreference } = useComposerSendShortcutPreference();',+ );+ expect(chatInputSource).toContain(+ 'const composerSendShortcutLabel = getComposerSendShortcutLabel(',+ );+ expect(chatInputSource).toContain('window.electronAPI?.platform');+ expect(chatInputSource).toContain(+ "`${t('newChat.chatInput.voiceInput.finishAndSend')} · ${composerSendShortcutLabel}`",+ );+ expect(chatInputSource).toContain(+ "`${t('newChat.sendButton.send')} · ${composerSendShortcutLabel}`",+ );+ expect(chatInputSource).toContain("t('newChat.sendButton.queueTooltipSendMode', {");+ expect(chatInputSource).toContain('shortcut: composerSendShortcutLabel');+ expect(chatInputSource).not.toContain(+ "`${t('newChat.chatInput.voiceInput.finishAndSend')} · Enter`",+ );+ expect(chatInputSource).not.toContain("`${t('newChat.sendButton.send')} · Enter`");});it('allows release-to-send while listening before ASR draft arrives', () => {diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsxindex 2f2832c74a..fd723737c8 100644--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx@@ -194,6 +194,13 @@ import type { Effort, PermissionMode } from '@/lib/userPreferences.types';import { getAppShortcutCombos } from '@/lib/appShortcutStore';import { getNextPermissionMode } from '@/lib/permissionModeCycle';import { matchesKeyboardEvent } from '../../../shared/appShortcuts';+import {+ getComposerSendShortcutPreference,+ getComposerSendShortcutLabel,+ hasComposerModifier,+ resolveComposerEnterIntent,+ useComposerSendShortcutPreference,+} from '@/hooks/useComposerSendShortcutPreference';import { createLogger } from '@/lib/logger';import { createComposerDraftSaveScheduler } from '@/lib/composerDraftSaveScheduler';import {@@ -901,7 +908,12 @@ export function ChatInput({}: ChatInputProps) {const { t } = useTranslation();const navigate = useNavigate();+ const { preference: composerSendShortcutPreference } = useComposerSendShortcutPreference();const resolvedPlaceholder = placeholder ?? t('newChat.chatInput.defaultPlaceholder');+ const composerSendShortcutLabel = getComposerSendShortcutLabel(+ composerSendShortcutPreference,+ window.electronAPI?.platform,+ );const steerShortcutLabel = useMemo(() => (window.electronAPI?.platform === 'darwin' ? '⌘↵' : 'Ctrl+Enter'),[],@@ -2024,42 +2036,36 @@ export function ChatInput({return false;}- // Plain Enter keeps the existing queue semantics. Cmd/Ctrl+Enter is- // only treated as 插话 while a turn is actually running; otherwise it- // falls back to the normal send path so the shortcut never becomes a- // "no active turn" footgun on an idle composer.- if (event.key === 'Enter' && !event.shiftKey && !event.altKey) {+ // Resolve the configurable send shortcut after structured list handling.+ // Native mode keeps Enter available to Tiptap for paragraph breaks and+ // IME composition; queue/steer modes continue through the existing+ // send and voice state machines.+ const enterIntent = resolveComposerEnterIntent(+ event,+ getComposerSendShortcutPreference(),+ { turnRunning: showStopButtonRef.current, platform: window.electronAPI?.platform },+ );+ if (enterIntent === 'native') return false;+ if (enterIntent === 'ignore') {event.preventDefault();+ return true;+ }+ if (enterIntent === null) return false;++ event.preventDefault();+ if (enterIntent === 'queue' || enterIntent === 'steer') {const isEditorEnterTarget = event.target instanceof Node && view.dom.contains(event.target);if (voiceInputStateRef.current === 'listening' &&voiceInputCanStopAndSendRef.current &&isEditorEnterTarget &&- !event.altKey &&- !event.repeat &&- !event.isComposing &&!isVoiceInputShortcutMatch(event, voiceShortcutRef.current)) {event.stopPropagation();- const deliveryMode =- (event.metaKey || event.ctrlKey) &&- showStopButtonRef.current &&- composerCanSubmitRef.current- ? 'steer'- : 'queue';- void voiceInputStopAndSendRef.current(deliveryMode);+ void voiceInputStopAndSendRef.current(enterIntent);return true;}- // Do not gate the delivery choice on composerCanSubmitRef here.- // Tiptap updates its document synchronously, while that ref mirrors- // sendButtonDisabled from a later React effect. A quick Cmd/Ctrl+Enter- // after typing could otherwise observe the previous empty state and- // incorrectly enqueue instead of steering the running turn.- const wantsSteer =- (event.metaKey || event.ctrlKey) &&- showStopButtonRef.current &&- voiceInputStateRef.current !== 'listening';- void dispatchSendRef.current(wantsSteer ? 'steer' : 'queue');+ void dispatchSendRef.current(enterIntent);return true;}return false;@@ -2489,6 +2495,7 @@ export function ChatInput({const handleKeyDown = (event: KeyboardEvent) => {const currentState = voiceInputStateRef.current;+ const platform = window.electronAPI?.platform;if (event.key === 'Escape' && !event.repeat && !event.isComposing) {if (currentState === 'listening' ||@@ -2503,22 +2510,23 @@ export function ChatInput({}}+ const enterIntent = resolveComposerEnterIntent(+ event,+ getComposerSendShortcutPreference(),+ { turnRunning: showStopButtonRef.current, platform },+ );+ const isModifiedEnter = hasComposerModifier(event, platform);if (- showStopButtonRef.current &&isComposerEnterTarget(event.target) &&- event.key === 'Enter' &&- (event.metaKey || event.ctrlKey) &&- !event.shiftKey &&- !event.altKey &&- !event.repeat &&- !event.isComposing &&+ isModifiedEnter &&+ (enterIntent === 'queue' || enterIntent === 'steer') &¤tState !== 'listening') {event.preventDefault();event.stopPropagation();clearPressTimer();voiceShortcutPressRef.current = null;- void dispatchSendRef.current('steer');+ void dispatchSendRef.current(enterIntent);return;}@@ -2526,24 +2534,14 @@ export function ChatInput({currentState === 'listening' &&voiceInputCanStopAndSendRef.current &&isVoiceInputEnterTarget(event.target) &&- event.key === 'Enter' &&- !event.shiftKey &&- !event.altKey &&- !event.repeat &&- !event.isComposing &&+ (enterIntent === 'queue' || enterIntent === 'steer') &&!isVoiceInputShortcutMatch(event, voiceShortcutRef.current)) {event.preventDefault();event.stopPropagation();clearPressTimer();voiceShortcutPressRef.current = null;- const deliveryMode =- (event.metaKey || event.ctrlKey) &&- showStopButtonRef.current &&- composerCanSubmitRef.current- ? 'steer'- : 'queue';- void voiceInputStopAndSendRef.current(deliveryMode);+ void voiceInputStopAndSendRef.current(enterIntent);return;}@@ -5805,13 +5803,17 @@ export function ChatInput({voiceReleaseToSendActive? t('newChat.chatInput.voiceInput.releaseToSend'): voiceInput.isListening && !sendButtonDisabled- ? `${t('newChat.chatInput.voiceInput.finishAndSend')} · Enter`+ ? `${t('newChat.chatInput.voiceInput.finishAndSend')} · ${composerSendShortcutLabel}`: showStopButton- ? t('newChat.sendButton.queueTooltip', {- shortcut: steerShortcutLabel,- })+ ? composerSendShortcutPreference === 'modifier-enter'+ ? t('newChat.sendButton.queueTooltipSendMode', {+ shortcut: composerSendShortcutLabel,+ })+ : t('newChat.sendButton.queueTooltip', {+ shortcut: steerShortcutLabel,+ }): !sendButtonDisabled- ? `${t('newChat.sendButton.send')} · Enter`+ ? `${t('newChat.sendButton.send')} · ${composerSendShortcutLabel}`: selectedSourceDisconnected? t('newChat.sourceDisconnected.sendBlocked'): nulldiff --git a/apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx b/apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsxnew file mode 100644index 0000000000..7976bdb32c--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/ComposerSendShortcutSection.tsx@@ -0,0 +1,58 @@+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++import { Switch } from '@/components/ui/switch';+import {+ getComposerModifierShortcutLabel,+ useComposerSendShortcutPreference,+} from '@/hooks/useComposerSendShortcutPreference';+import { toast } from '@/lib/toast';+import { DefaultOverrideControls } from './DefaultOverrideControls';++export function ComposerSendShortcutSection() {+ const { t } = useTranslation();+ const { preference, isCustomized, setPreference } = useComposerSendShortcutPreference();+ const shortcut = getComposerModifierShortcutLabel(window.electronAPI?.platform);++ const onReset = useCallback(() => {+ setPreference('enter');+ toast.success(t('settings.defaults.restored'));+ }, [setPreference, t]);++ return (+ <div className="flex flex-col gap-[14px]">+ <div className="flex flex-col gap-1">+ <h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">+ {t('settings.composer.title')}+ </h2>+ </div>++ <div className="flex flex-col gap-[14px] rounded-xl border border-[var(--settings-theme-card-border)] bg-[var(--settings-theme-card-bg)] p-4">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0 flex-1">+ <p className="text-14 font-medium leading-[1.3] text-[var(--text-primary)]">+ {t('settings.composer.sendShortcut.label', { shortcut })}+ </p>+ <p className="mt-1 text-12 leading-[1.5] text-[var(--text-secondary)]">+ {t('settings.composer.sendShortcut.hint', { shortcut })}+ </p>+ </div>++ <div className="flex shrink-0 items-center gap-2">+ <DefaultOverrideControls isCustomized={isCustomized} onReset={onReset} />+ <Switch+ checked={preference === 'modifier-enter'}+ onCheckedChange={(enabled) => {+ const result = setPreference(enabled ? 'modifier-enter' : 'enter');+ if (!result.ok && result.conflict === 'composer-voice-input') {+ toast.error(t('settings.shortcuts.errors.composerVoiceConflict'));+ }+ }}+ aria-label={t('settings.composer.sendShortcut.ariaLabel', { shortcut })}+ />+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/settings/SettingsView.tsx b/apps/desktop/src/renderer/components/settings/SettingsView.tsxindex 4c713b6dc0..f7f7f3053d 100644--- a/apps/desktop/src/renderer/components/settings/SettingsView.tsx+++ b/apps/desktop/src/renderer/components/settings/SettingsView.tsx@@ -16,6 +16,7 @@ import { McpServersSection } from './McpServersSection';import { RemoteControlSection } from './RemoteControlSection';import { NotificationSection } from './NotificationSection';import { WindowBehaviorSection } from './WindowBehaviorSection';+import { ComposerSendShortcutSection } from './ComposerSendShortcutSection';import { KeyboardShortcutsSection } from './KeyboardShortcutsSection';import { AgentIslandSection } from './AgentIslandSection';import { LanguageSection } from './LanguageSection';@@ -292,6 +293,15 @@ export function SettingsView() {<WindowBehaviorSection /></section>+ {/* Section — Composer send shortcut (应用级、本地输入偏好)。 */}+ <section+ id="settings-composer"+ className="py-[18px]"+ aria-label={t('settings.sections.composer')}+ >+ <ComposerSendShortcutSection />+ </section>+{/* Section — Experimental (py 18)内部按 EXPERIMENTAL_FEATURES 注册表渲染; admin-only 项对非 admin 用户自动跳过。如果当前没有任何可见 feature, ExperimentalSection 自身返回 null,diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsxindex 5ddccc2a77..6f5aa78c16 100644--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx@@ -27,6 +27,7 @@ import {type VoiceInputDictionaryEntrySource,type VoiceInputLanguage,} from '@/hooks/useVoiceInputSettings';+import { getComposerSendShortcutPreference } from '@/hooks/useComposerSendShortcutPreference';import { useVoiceInputModelSelection } from '@/hooks/useVoiceInputModelSelection';import { useVoiceInputUsageStats } from '@/hooks/useVoiceInputUsageStats';import { useVoiceInputHistory } from '@/hooks/useVoiceInputHistory';@@ -41,6 +42,7 @@ import {findVoiceInputAppShortcutConflict,type AppShortcutComboEntry,} from '@/voice-input/appShortcutConflict';+import { findComposerVoiceInputConflict } from '@/voice-input/composerVoiceInputConflict';import { shouldShowInputMonitoringBadge } from '@/voice-input/inputMonitoringBadge';import {createVoiceInputModifierShortcut,@@ -1342,6 +1344,20 @@ export function VoiceInputSection() {[t],);+ const showComposerVoiceConflict = useCallback(() => {+ toast.error(t('settings.shortcuts.errors.composerVoiceConflict'));+ }, [t]);++ const hasComposerVoiceConflict = useCallback(+ (shortcut: VoiceInputShortcut | null): boolean =>+ findComposerVoiceInputConflict(+ getComposerSendShortcutPreference(),+ shortcut,+ window.electronAPI?.platform,+ ) !== null,+ [],+ );+const commitRecordedShortcut = useCallback((shortcut: VoiceInputShortcut | null) => {// 提交代次。录制框在这次提交 await 期间仍然开着,用户可以再录一个键提交第二次;@@ -1357,6 +1373,11 @@ export function VoiceInputSection() {if (isStaleSubmission()) return;// 被更晚的一轮顶掉:那一轮才决定最终结果,这里静默丢弃,不报错也不收口录制态。if (!result.ok && result.errorCode === 'superseded') return;+ if (!result.ok && result.conflict === 'composer-voice-input') {+ showComposerVoiceConflict();+ if (shortcut) setRecordingShortcutPreview(shortcut);+ return;+ }if (!result.ok) {// 'failed' = 原生 listener 起不来。main 已把细节消毒成固定英文(原文含内部// 路径),所以这里改用自带下一步的中文文案,不再把那句英文插进模板。@@ -1389,7 +1410,7 @@ export function VoiceInputSection() {if (shortcutCommitPromiseRef.current === commit) shortcutCommitPromiseRef.current = null;});},- [schedulePermissionRefresh, setShortcut, t],+ [schedulePermissionRefresh, setShortcut, showComposerVoiceConflict, t],);const getAppShortcutEntries = useCallback((): AppShortcutComboEntry[] => {@@ -1463,6 +1484,10 @@ export function VoiceInputSection() {toast.error(t('settings.voiceInput.shortcut.toast.systemReserved'));return;}+ if (hasComposerVoiceConflict(shortcut)) {+ showComposerVoiceConflict();+ return;+ }const conflictId = findVoiceInputAppShortcutConflict(shortcut, getAppShortcutEntries());if (conflictId) {showAppShortcutConflict(conflictId);@@ -1472,7 +1497,15 @@ export function VoiceInputSection() {pendingKeyboardShortcutRef.current = shortcut;setRecordingShortcutPreview(shortcut);},- [commitRecordedShortcut, getAppShortcutEntries, recordingShortcut, showAppShortcutConflict, t],+ [+ commitRecordedShortcut,+ getAppShortcutEntries,+ hasComposerVoiceConflict,+ recordingShortcut,+ showAppShortcutConflict,+ showComposerVoiceConflict,+ t,+ ],);const handleShortcutKeyUp = useCallback(@@ -1527,6 +1560,10 @@ export function VoiceInputSection() {pendingKeyboardShortcutRef.current = null;setRecordingShortcutPreview(null);if (shortcut) {+ if (hasComposerVoiceConflict(shortcut)) {+ showComposerVoiceConflict();+ return;+ }const conflictId = findVoiceInputAppShortcutConflict(shortcut, getAppShortcutEntries());if (conflictId) {showAppShortcutConflict(conflictId);@@ -1564,7 +1601,14 @@ export function VoiceInputSection() {pendingKeyboardShortcutRef.current = null;setRecordingShortcutPreview(null);},- [commitRecordedShortcut, getAppShortcutEntries, recordingShortcut, showAppShortcutConflict],+ [+ commitRecordedShortcut,+ getAppShortcutEntries,+ hasComposerVoiceConflict,+ recordingShortcut,+ showAppShortcutConflict,+ showComposerVoiceConflict,+ ],);useEffect(() => {diff --git a/apps/desktop/src/renderer/components/settings/__tests__/ComposerSendShortcutSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/ComposerSendShortcutSection.test.tsxnew file mode 100644index 0000000000..2ef8a597b8--- /dev/null+++ b/apps/desktop/src/renderer/components/settings/__tests__/ComposerSendShortcutSection.test.tsx@@ -0,0 +1,132 @@+// @vitest-environment jsdom++import { fireEvent, render, screen } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const toastMocks = vi.hoisted(() => ({+ error: vi.fn(),+ success: vi.fn(),+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string, options?: { shortcut?: string }) => {+ const translations: Record<string, string> = {+ 'settings.composer.title': 'Message input',+ 'settings.composer.sendShortcut.label': 'Use {{shortcut}} to send',+ 'settings.composer.sendShortcut.hint':+ 'When enabled, {{shortcut}} sends messages. When disabled, Enter sends messages and Shift+Enter inserts a new line.',+ 'settings.composer.sendShortcut.ariaLabel': 'Use {{shortcut}} to send messages',+ 'settings.defaults.customizedBadge': 'Customized',+ 'settings.defaults.restore': 'Restore default',+ 'settings.defaults.restored': 'Restored default',+ 'settings.shortcuts.errors.composerVoiceConflict':+ 'Conflicts with the voice input shortcut. Change either shortcut.',+ };+ return (translations[key] ?? key).replace('{{shortcut}}', options?.shortcut ?? '');+ },+ }),+}));++vi.mock('@/components/ui/tooltip', () => ({+ Tip: ({ children }: { children: React.ReactNode }) => children,+}));++vi.mock('@/lib/toast', () => ({+ toast: toastMocks,+}));++import {+ COMPOSER_SEND_SHORTCUT_STORAGE_KEY,+ _resetComposerSendShortcutPreferenceForTests,+} from '@/hooks/useComposerSendShortcutPreference';+import { ComposerSendShortcutSection } from '../ComposerSendShortcutSection';++function setPlatform(platform: string): void {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: { platform },+ });+}++function setVoiceInputShortcut(shortcut: object | null): void {+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ voiceInput: {+ getDataSnapshot: () => ({ settings: { shortcut } }),+ },+ },+ });+}++describe('ComposerSendShortcutSection', () => {+ beforeEach(() => {+ localStorage.clear();+ _resetComposerSendShortcutPreferenceForTests();+ toastMocks.error.mockReset();+ toastMocks.success.mockReset();+ setPlatform('win32');+ });++ it('shows the default Enter mode and platform-specific shortcut copy', () => {+ setPlatform('darwin');++ render(<ComposerSendShortcutSection />);++ expect(+ screen.getByRole('switch', { name: 'Use ⌘+Enter to send messages' }).getAttribute('data-state'),+ ).toBe('unchecked');+ expect(screen.queryByText('Use ⌘+Enter to send')).not.toBeNull();+ expect(+ screen.queryByText(+ 'When enabled, ⌘+Enter sends messages. When disabled, Enter sends messages and Shift+Enter inserts a new line.',+ ),+ ).not.toBeNull();+ });++ it('synchronizes mode B across subscribers and restores the default override', () => {+ render(+ <>+ <ComposerSendShortcutSection />+ <ComposerSendShortcutSection />+ </>,+ );++ const switches = screen.getAllByRole('switch', { name: 'Use Ctrl+Enter to send messages' });+ fireEvent.click(switches[0]);++ expect(localStorage.getItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY)).toBe('modifier-enter');+ expect(switches[0].getAttribute('data-state')).toBe('checked');+ expect(switches[1].getAttribute('data-state')).toBe('checked');+ expect(screen.getAllByText('Customized')).toHaveLength(2);++ fireEvent.click(screen.getAllByRole('button', { name: 'Restore default' })[0]);++ expect(localStorage.getItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY)).toBeNull();+ expect(switches[0].getAttribute('data-state')).toBe('unchecked');+ expect(switches[1].getAttribute('data-state')).toBe('unchecked');+ expect(toastMocks.success).toHaveBeenCalledWith('Restored default');+ });++ it('rejects a Composer shortcut that is already used by Voice Input', () => {+ setVoiceInputShortcut({+ trigger: 'keyboard',+ code: 'Enter',+ key: 'Enter',+ modifiers: { meta: true, ctrl: false, alt: false, shift: false, fn: false },+ });++ render(<ComposerSendShortcutSection />);++ const switchControl = screen.getByRole('switch', { name: 'Use ⌘+Enter to send messages' });+ fireEvent.click(switchControl);++ expect(localStorage.getItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY)).toBeNull();+ expect(switchControl.getAttribute('data-state')).toBe('unchecked');+ expect(toastMocks.error).toHaveBeenCalledWith(+ 'Conflicts with the voice input shortcut. Change either shortcut.',+ );+ });+});diff --git a/apps/desktop/src/renderer/hooks/__tests__/useComposerSendShortcutPreference.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useComposerSendShortcutPreference.test.tsnew file mode 100644index 0000000000..c03a8fe7a4--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useComposerSendShortcutPreference.test.ts@@ -0,0 +1,267 @@+// @vitest-environment jsdom++import { beforeEach, describe, expect, it } from 'vitest';+import { act, renderHook } from '@testing-library/react';++import {+ _resetComposerSendShortcutPreferenceForTests,+ getComposerSendShortcutPreference,+ getComposerSendShortcutLabel,+ resolveComposerEnterIntent,+ useComposerSendShortcutPreference,+ type ComposerSendShortcutPreference,+} from '../useComposerSendShortcutPreference';+import { getDefaultVoiceInputSettings } from '../../../shared/voiceInputData';++const KEY = 'chat.sendShortcutPreference';++function enterEvent(+ overrides: Partial<Pick<KeyboardEvent, 'shiftKey' | 'altKey' | 'metaKey' | 'ctrlKey' | 'repeat' | 'isComposing'>> = {},+): KeyboardEvent {+ return new KeyboardEvent('keydown', { key: 'Enter', ...overrides });+}++describe('useComposerSendShortcutPreference', () => {+ beforeEach(() => {+ localStorage.clear();+ _resetComposerSendShortcutPreferenceForTests();+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ voiceInput: {+ getDataSnapshot: () => ({ settings: getDefaultVoiceInputSettings('darwin') }),+ },+ },+ });+ });++ it.each([+ ['enter', 'darwin', 'Enter'],+ ['enter', 'win32', 'Enter'],+ ['modifier-enter', 'darwin', '⌘+Enter'],+ ['modifier-enter', 'linux', 'Ctrl+Enter'],+ ] as const)('formats the send shortcut label for %s on %s', (preference, platform, expected) => {+ expect(getComposerSendShortcutLabel(preference, platform)).toBe(expected);+ });++ it('defaults to Enter and treats the default as not customized', () => {+ expect(getComposerSendShortcutPreference()).toBe('enter');++ const { result } = renderHook(() => useComposerSendShortcutPreference());++ expect(result.current.preference).toBe('enter');+ expect(result.current.isCustomized).toBe(false);+ });++ it('only accepts the modifier-enter override from storage', () => {+ localStorage.setItem(KEY, 'modifier-enter');+ expect(getComposerSendShortcutPreference()).toBe('modifier-enter');++ _resetComposerSendShortcutPreferenceForTests();+ localStorage.setItem(KEY, 'enter');+ expect(getComposerSendShortcutPreference()).toBe('enter');++ _resetComposerSendShortcutPreferenceForTests();+ localStorage.setItem(KEY, 'garbage');+ expect(getComposerSendShortcutPreference()).toBe('enter');+ });++ it('persists the non-default override and removes it when reset', () => {+ const { result } = renderHook(() => useComposerSendShortcutPreference());++ act(() => result.current.setPreference('modifier-enter'));+ expect(localStorage.getItem(KEY)).toBe('modifier-enter');+ expect(getComposerSendShortcutPreference()).toBe('modifier-enter');+ expect(result.current.isCustomized).toBe(true);++ act(() => result.current.setPreference('enter'));+ expect(localStorage.getItem(KEY)).toBeNull();+ expect(getComposerSendShortcutPreference()).toBe('enter');+ expect(result.current.isCustomized).toBe(false);+ });++ it('keeps the Composer preference unchanged when Voice Input owns Cmd+Enter', () => {+ const settings = {+ ...getDefaultVoiceInputSettings('darwin'),+ shortcut: {+ trigger: 'keyboard' as const,+ code: 'Enter',+ key: 'Enter',+ modifiers: { meta: true, ctrl: false, alt: false, shift: false, fn: false },+ },+ };+ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ voiceInput: { getDataSnapshot: () => ({ settings }) },+ },+ });++ const { result } = renderHook(() => useComposerSendShortcutPreference());+ let updateResult: ReturnType<typeof result.current.setPreference> | undefined;++ act(() => {+ updateResult = result.current.setPreference('modifier-enter');+ });++ expect(updateResult).toEqual({ ok: false, conflict: 'composer-voice-input' });+ expect(result.current.preference).toBe('enter');+ expect(localStorage.getItem(KEY)).toBeNull();+ });++ it('updates mounted hooks when another renderer changes the preference', () => {+ const { result } = renderHook(() => useComposerSendShortcutPreference());++ act(() => {+ window.dispatchEvent(+ new StorageEvent('storage', {+ key: KEY,+ newValue: 'modifier-enter',+ }),+ );+ });++ expect(result.current.preference).toBe('modifier-enter');+ expect(result.current.isCustomized).toBe(true);+ });++ describe('resolveComposerEnterIntent', () => {+ const cases: Array<{+ name: string;+ preference: ComposerSendShortcutPreference;+ platform: string;+ turnRunning: boolean;+ event: KeyboardEvent;+ expected: 'queue' | 'steer' | 'native' | 'ignore' | null;+ }> = [+ {+ name: 'sends with plain Enter in Enter mode',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent(),+ expected: 'queue',+ },+ {+ name: 'steers with Cmd/Ctrl+Enter while a turn is running in Enter mode',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: true,+ event: enterEvent({ metaKey: true }),+ expected: 'steer',+ },+ {+ name: 'queues with Cmd/Ctrl+Enter while idle in Enter mode',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ ctrlKey: true }),+ expected: 'queue',+ },+ {+ name: 'uses native Enter for a newline in modifier-enter mode',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: true,+ event: enterEvent(),+ expected: 'native',+ },+ {+ name: 'queues with Cmd+Enter in modifier-enter mode on macOS',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: true,+ event: enterEvent({ metaKey: true }),+ expected: 'queue',+ },+ {+ name: 'queues with Ctrl+Enter in modifier-enter mode on macOS',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: true,+ event: enterEvent({ ctrlKey: true }),+ expected: 'queue',+ },+ {+ name: 'does not treat Win+Enter as the modifier shortcut on Windows',+ preference: 'modifier-enter',+ platform: 'win32',+ turnRunning: true,+ event: enterEvent({ metaKey: true }),+ expected: 'native',+ },+ {+ name: 'does not treat Meta+Enter as the modifier shortcut on Linux',+ preference: 'modifier-enter',+ platform: 'linux',+ turnRunning: true,+ event: enterEvent({ metaKey: true }),+ expected: 'native',+ },+ {+ name: 'ignores a repeated Enter send',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: true,+ event: enterEvent({ repeat: true }),+ expected: 'ignore',+ },+ {+ name: 'keeps a repeated plain Enter native in modifier-enter mode',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ repeat: true }),+ expected: 'native',+ },+ {+ name: 'ignores a repeated modifier Enter send in modifier-enter mode',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ metaKey: true, repeat: true }),+ expected: 'ignore',+ },+ {+ name: 'leaves IME composition to the native editor path',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ isComposing: true }),+ expected: 'native',+ },+ {+ name: 'ignores Shift+Enter so list and hard-break handling can run',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ shiftKey: true }),+ expected: null,+ },+ {+ name: 'ignores Alt+Enter so hard-break handling can run',+ preference: 'modifier-enter',+ platform: 'darwin',+ turnRunning: false,+ event: enterEvent({ altKey: true }),+ expected: null,+ },+ {+ name: 'ignores other keys',+ preference: 'enter',+ platform: 'darwin',+ turnRunning: false,+ event: new KeyboardEvent('keydown', { key: 'Escape' }),+ expected: null,+ },+ ];++ it.each(cases)('$name', ({ preference, platform, turnRunning, event, expected }) => {+ expect(resolveComposerEnterIntent(event, preference, { turnRunning, platform })).toBe(+ expected,+ );+ });+ });+});diff --git a/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.shortcutConflict.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.shortcutConflict.test.tsnew file mode 100644index 0000000000..44d5a43767--- /dev/null+++ b/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.shortcutConflict.test.ts@@ -0,0 +1,120 @@+// @vitest-environment jsdom++import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import {+ getDefaultVoiceInputSettings,+ type VoiceInputSettings,+} from '../../../shared/voiceInputData';+import {+ COMPOSER_SEND_SHORTCUT_STORAGE_KEY,+ _resetComposerSendShortcutPreferenceForTests,+} from '../useComposerSendShortcutPreference';+import { useVoiceInputSettings } from '../useVoiceInputSettings';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/lib/logger', () => ({+ createLogger: () => ({ warn: vi.fn(), debug: vi.fn() }),+}));++vi.mock('@/lib/toast', () => ({+ toast: { error: vi.fn(), info: vi.fn(), success: vi.fn() },+}));++const composerVoiceShortcut = {+ trigger: 'keyboard' as const,+ code: 'Enter',+ key: 'Enter',+ modifiers: { meta: true, ctrl: false, alt: false, shift: false, fn: false },+};++let settings: VoiceInputSettings;+let updateShortcutSetting: ReturnType<typeof vi.fn>;++function installElectronApi(): void {+ updateShortcutSetting = vi.fn(async (shortcut) => {+ settings = { ...settings, shortcut };+ return { ok: true, settings };+ });++ Object.defineProperty(window, 'electronAPI', {+ configurable: true,+ value: {+ platform: 'darwin',+ voiceInput: {+ getDataSnapshot: () => ({ settings }),+ updateShortcutSetting,+ updateSettings: vi.fn(),+ setGlobalShortcut: vi.fn().mockResolvedValue({ ok: true }),+ onDataChanged: vi.fn(() => () => {}),+ },+ },+ });+}++describe('useVoiceInputSettings Composer conflict guard', () => {+ beforeEach(() => {+ localStorage.clear();+ _resetComposerSendShortcutPreferenceForTests();+ settings = { ...getDefaultVoiceInputSettings('darwin'), shortcut: null };+ installElectronApi();+ });++ afterEach(() => {+ Reflect.deleteProperty(window, 'electronAPI');+ });++ it('rejects a conflicting shortcut before calling the persistence IPC', async () => {+ localStorage.setItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY, 'modifier-enter');++ const { result } = renderHook(() => useVoiceInputSettings());+ let updateResult!: Awaited<ReturnType<typeof result.current.setShortcut>>;++ await act(async () => {+ updateResult = await result.current.setShortcut(composerVoiceShortcut);+ });++ expect(updateResult).toEqual({+ ok: false,+ conflict: 'composer-voice-input',+ error: 'Voice Input shortcut conflicts with the Composer send shortcut',+ });+ expect(updateShortcutSetting).not.toHaveBeenCalled();+ expect(settings.shortcut).toBeNull();+ });++ it('allows a non-conflicting shortcut through the existing persistence path', async () => {+ localStorage.setItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY, 'modifier-enter');+ const nonConflictingShortcut = {+ ...composerVoiceShortcut,+ modifiers: { meta: false, ctrl: true, alt: false, shift: true, fn: false },+ };++ const { result } = renderHook(() => useVoiceInputSettings());+ await act(async () => {+ await result.current.setShortcut(nonConflictingShortcut);+ });++ expect(updateShortcutSetting).toHaveBeenCalledWith(nonConflictingShortcut);+ expect(settings.shortcut).toEqual(nonConflictingShortcut);+ });++ it('rechecks the current Composer preference when a recording commit is in flight', async () => {+ const { result } = renderHook(() => useVoiceInputSettings());++ localStorage.setItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY, 'modifier-enter');+ _resetComposerSendShortcutPreferenceForTests();++ let updateResult!: Awaited<ReturnType<typeof result.current.setShortcut>>;+ await act(async () => {+ updateResult = await result.current.setShortcut(composerVoiceShortcut);+ });++ expect(updateResult).toMatchObject({ ok: false, conflict: 'composer-voice-input' });+ expect(updateShortcutSetting).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/renderer/hooks/useComposerSendShortcutPreference.ts b/apps/desktop/src/renderer/hooks/useComposerSendShortcutPreference.tsnew file mode 100644index 0000000000..ac7da2a309--- /dev/null+++ b/apps/desktop/src/renderer/hooks/useComposerSendShortcutPreference.ts@@ -0,0 +1,146 @@+import { useCallback, useEffect, useState } from 'react';++import { getVoiceInputSettings } from './useVoiceInputSettings';+import { findComposerVoiceInputConflict } from '@/voice-input/composerVoiceInputConflict';+import { hasComposerModifier } from '@/voice-input/composerShortcut';++export { hasComposerModifier } from '@/voice-input/composerShortcut';++export type ComposerSendShortcutPreference = 'enter' | 'modifier-enter';++export type ComposerEnterIntent = 'queue' | 'steer' | 'native' | 'ignore' | null;++export type ComposerEnterEvent = Pick<+ KeyboardEvent,+ 'key' | 'shiftKey' | 'altKey' | 'metaKey' | 'ctrlKey' | 'repeat' | 'isComposing'+>;++export type ComposerSendShortcutUpdateResult =+ | { ok: true }+ | { ok: false; conflict: 'composer-voice-input' };++export const COMPOSER_SEND_SHORTCUT_STORAGE_KEY = 'chat.sendShortcutPreference';+export const DEFAULT_COMPOSER_SEND_SHORTCUT: ComposerSendShortcutPreference = 'enter';++export function getComposerModifierShortcutLabel(platform: string | undefined): string {+ return platform === 'darwin' ? '⌘+Enter' : 'Ctrl+Enter';+}++export function getComposerSendShortcutLabel(+ preference: ComposerSendShortcutPreference,+ platform: string | undefined,+): string {+ return preference === 'modifier-enter' ? getComposerModifierShortcutLabel(platform) : 'Enter';+}++function parsePreference(raw: string | null): ComposerSendShortcutPreference | null {+ return raw === 'modifier-enter' ? raw : null;+}++/**+ * Decide what the composer should do with an Enter keydown.+ *+ * The resolver deliberately does not perform any side effect. Callers can+ * therefore share the same preference semantics while keeping their own+ * event-target and delivery plumbing.+ */+export function resolveComposerEnterIntent(+ event: ComposerEnterEvent,+ preference: ComposerSendShortcutPreference,+ options: { turnRunning: boolean; platform: string | undefined },+): ComposerEnterIntent {+ if (event.key !== 'Enter' || event.shiftKey || event.altKey) return null;+ if (event.isComposing) return 'native';++ const hasModifier = hasComposerModifier(event, options.platform);+ if (event.repeat) {+ const isSendShortcut = preference === 'enter' || hasModifier;+ return isSendShortcut ? 'ignore' : 'native';+ }++ if (preference === 'modifier-enter') {+ return hasModifier ? 'queue' : 'native';+ }++ if (!hasModifier) return 'queue';+ return options.turnRunning ? 'steer' : 'queue';+}++/** Module-level memory is the synchronous source of truth for event handlers. */+let memoryValue: ComposerSendShortcutPreference | null = null;++const listeners = new Set<() => void>();++export function getComposerSendShortcutPreference(): ComposerSendShortcutPreference {+ if (memoryValue !== null) return memoryValue;+ try {+ const parsed = parsePreference(localStorage.getItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY));+ if (parsed) return (memoryValue = parsed);+ } catch {+ // localStorage may be unavailable in a restricted renderer.+ }+ return DEFAULT_COMPOSER_SEND_SHORTCUT;+}++export function useComposerSendShortcutPreference(): {+ preference: ComposerSendShortcutPreference;+ isCustomized: boolean;+ setPreference: (next: ComposerSendShortcutPreference) => ComposerSendShortcutUpdateResult;+} {+ const [preference, setState] = useState<ComposerSendShortcutPreference>(+ getComposerSendShortcutPreference,+ );++ const setPreference = useCallback((next: ComposerSendShortcutPreference): ComposerSendShortcutUpdateResult => {+ if (+ findComposerVoiceInputConflict(+ next,+ getVoiceInputSettings().shortcut,+ window.electronAPI?.platform,+ )+ ) {+ return { ok: false, conflict: 'composer-voice-input' };+ }++ memoryValue = next;+ setState(next);+ try {+ if (next === DEFAULT_COMPOSER_SEND_SHORTCUT) {+ localStorage.removeItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY);+ } else {+ localStorage.setItem(COMPOSER_SEND_SHORTCUT_STORAGE_KEY, next);+ }+ } catch {+ // The in-memory value still applies for this renderer.+ }+ listeners.forEach((fn) => fn());+ return { ok: true };+ }, []);++ useEffect(() => {+ const sync = () => setState(getComposerSendShortcutPreference());+ listeners.add(sync);+ const onStorage = (event: StorageEvent) => {+ if (event.key !== COMPOSER_SEND_SHORTCUT_STORAGE_KEY) return;+ memoryValue = parsePreference(event.newValue) ?? DEFAULT_COMPOSER_SEND_SHORTCUT;+ sync();+ };+ window.addEventListener('storage', onStorage);+ return () => {+ listeners.delete(sync);+ window.removeEventListener('storage', onStorage);+ };+ }, []);++ return {+ preference,+ isCustomized: preference !== DEFAULT_COMPOSER_SEND_SHORTCUT,+ setPreference,+ };+}++/** Test-only reset for the module-level source of truth. */+export function _resetComposerSendShortcutPreferenceForTests(): void {+ memoryValue = null;+ listeners.clear();+}diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.tsindex 243b12ea7d..6baf9f64e7 100644--- a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts+++ b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts@@ -30,6 +30,8 @@ import {type VoiceInputSettings,} from '../../shared/voiceInputData';import type { VoiceInputShortcut } from '@/voice-input/shortcut';+import { findComposerVoiceInputConflict } from '@/voice-input/composerVoiceInputConflict';+import { getComposerSendShortcutPreference } from './useComposerSendShortcutPreference';export {DEFAULT_VOICE_INPUT_REFINEMENT_INSTRUCTIONS,@@ -145,7 +147,12 @@ export type VoiceInputShortcutUpdateResult =pendingInputMonitoring?: boolean;}// 用 IPC 契约的固定联合而不是裸 string,避免误传/误判不存在的 code。- | { ok: false; error: string; errorCode?: VoiceInputGlobalErrorCode };+ | {+ ok: false;+ error: string;+ errorCode?: VoiceInputGlobalErrorCode;+ conflict?: 'composer-voice-input';+ };/*** 录制期挂起全局快捷键。@@ -314,6 +321,20 @@ export function useVoiceInputSettings(): {const setShortcut = useCallback(async (shortcut: VoiceInputShortcut | null): Promise<VoiceInputShortcutUpdateResult> => {+ if (+ findComposerVoiceInputConflict(+ getComposerSendShortcutPreference(),+ shortcut,+ window.electronAPI?.platform,+ )+ ) {+ return {+ ok: false,+ conflict: 'composer-voice-input',+ error: 'Voice Input shortcut conflicts with the Composer send shortcut',+ };+ }+try {const result = await window.electronAPI.voiceInput.updateShortcutSetting(shortcut);if (!result.ok) log.warn('voice input shortcut setting update failed:', result.error);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 80e13eb0a0..a7b0f7fac4 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -127,6 +127,7 @@"subagentModels": "Subagents","compaction": "Context compaction","terminalShell": "Default terminal shell",+ "composer": "Message input","linkOpen": "Link open behavior","compatMode": "Tips","voiceInput": "Voice input",@@ -2258,6 +2259,14 @@"selectAria": "Select default terminal shell"}},+ "composer": {+ "title": "Message input",+ "sendShortcut": {+ "label": "Use {{shortcut}} to send",+ "hint": "When enabled, {{shortcut}} sends messages. When disabled, Enter sends messages and Shift+Enter inserts a new line.",+ "ariaLabel": "Use {{shortcut}} to send messages"+ }+ },"linkOpen": {"title": "Link open behavior","description": "Where web links and HTML files in messages open on left click.",@@ -2972,6 +2981,7 @@"systemReserved": "Reserved by the operating system","conflict": "Conflicts with \"{{name}}\"","voiceConflict": "Conflicts with the voice input shortcut",+ "composerVoiceConflict": "Conflicts with the voice input shortcut. Change either the composer send shortcut or the voice input shortcut.","menuAccelerator": "This combination cannot be registered as a menu shortcut"},"items": {@@ -4786,6 +4796,7 @@"send": "Send message","queue": "Queue message","queueTooltip": "Click to queue; press {{shortcut}} to steer without interrupting the task",+ "queueTooltipSendMode": "Click to queue; press {{shortcut}} to send this message","stop": "Stop generating"},"pluginSetup": {diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 2e10d58cef..6d5d837d10 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -127,6 +127,7 @@"subagentModels": "サブエージェント","compaction": "コンテキスト圧縮","terminalShell": "デフォルトターミナルシェル",+ "composer": "メッセージ入力","linkOpen": "リンクの開き方","compatMode": "ヒント","voiceInput": "音声入力",@@ -2257,6 +2258,14 @@"selectAria": "デフォルトターミナルシェルを選択"}},+ "composer": {+ "title": "メッセージ入力",+ "sendShortcut": {+ "label": "{{shortcut}}で送信",+ "hint": "オンにすると{{shortcut}}でメッセージを送信します。オフにするとEnterで送信し、Shift+Enterで改行します。",+ "ariaLabel": "{{shortcut}}でメッセージを送信"+ }+ },"linkOpen": {"title": "リンクの開き方","description": "メッセージ内のリンクや HTML ファイルを左クリックしたときの既定の開き先です。",@@ -2971,6 +2980,7 @@"systemReserved": "OS によって予約されています","conflict": "「{{name}}」と競合しています","voiceConflict": "音声入力のショートカットと競合しています",+ "composerVoiceConflict": "音声入力のショートカットと競合しています。メッセージ入力の送信ショートカットまたは音声入力のショートカットを変更してください。","menuAccelerator": "この組み合わせはメニューショートカットとして登録できません"},"items": {@@ -4784,6 +4794,7 @@"send": "メッセージを送信","queue": "キューに追加","queueTooltip": "クリックでキューに追加。{{shortcut}} でタスクを中断せずに割り込み送信",+ "queueTooltipSendMode": "クリックでキューに追加、{{shortcut}}でこのメッセージを送信","stop": "生成を停止"},"pluginSetup": {diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 38d10f0eec..98a461d58a 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -127,6 +127,7 @@"subagentModels": "하위 에이전트","compaction": "컨텍스트 압축","terminalShell": "기본 터미널 셸",+ "composer": "메시지 입력","linkOpen": "링크 열기 방식","compatMode": "팁","voiceInput": "음성 입력",@@ -2257,6 +2258,14 @@"selectAria": "기본 터미널 셸 선택"}},+ "composer": {+ "title": "메시지 입력",+ "sendShortcut": {+ "label": "{{shortcut}}로 보내기",+ "hint": "켜면 {{shortcut}}로 메시지를 보냅니다. 끄면 Enter로 보내고 Shift+Enter로 줄을 바꿉니다.",+ "ariaLabel": "{{shortcut}}로 메시지 보내기"+ }+ },"linkOpen": {"title": "링크 열기 방식","description": "메시지의 링크나 HTML 파일을 왼쪽 클릭했을 때 기본으로 여는 위치입니다.",@@ -2971,6 +2980,7 @@"systemReserved": "운영 체제에서 예약된 조합입니다","conflict": "\"{{name}}\"과(와) 충돌합니다","voiceConflict": "음성 입력 단축키와 충돌합니다",+ "composerVoiceConflict": "음성 입력 단축키와 충돌합니다. 메시지 입력의 보내기 단축키 또는 음성 입력 단축키를 변경하세요.","menuAccelerator": "이 조합은 메뉴 단축키로 등록할 수 없습니다"},"items": {@@ -4784,6 +4794,7 @@"send": "메시지 전송","queue": "대기열에 추가","queueTooltip": "클릭하면 대기열에 추가됩니다. {{shortcut}} 를 누르면 작업을 중단하지 않고 끼어듭니다",+ "queueTooltipSendMode": "클릭하면 대기열에 추가하고, {{shortcut}}를 누르면 이 메시지를 보냅니다.","stop": "생성 중지"},"pluginSetup": {diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 58b3c7089d..4144d265dc 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -127,6 +127,7 @@"subagentModels": "Subagent","compaction": "上下文压缩","terminalShell": "默认终端 shell",+ "composer": "消息输入","linkOpen": "链接打开方式","compatMode": "小技巧","voiceInput": "语音输入",@@ -2222,6 +2223,14 @@"selectAria": "选择默认终端 shell"}},+ "composer": {+ "title": "消息输入",+ "sendShortcut": {+ "label": "使用 {{shortcut}} 发送",+ "hint": "开启后按 {{shortcut}} 发送消息;关闭后按 Enter 发送消息,按 Shift+Enter 换行。",+ "ariaLabel": "使用 {{shortcut}} 发送消息"+ }+ },"linkOpen": {"title": "链接打开方式","description": "消息里左键点击网页链接或 HTML 文件时的默认打开位置。",@@ -2971,6 +2980,7 @@"systemReserved": "该组合键被系统保留","conflict": "与「{{name}}」冲突","voiceConflict": "与语音输入快捷键冲突",+ "composerVoiceConflict": "与语音输入快捷键冲突,请修改发送或语音输入快捷键。","menuAccelerator": "该组合键无法注册为菜单快捷键"},"items": {@@ -4784,6 +4794,7 @@"send": "发送消息","queue": "排队发送","queueTooltip": "点击排队发送;按 {{shortcut}} 插话,不打断当前任务",+ "queueTooltipSendMode": "点击可排队;按 {{shortcut}} 发送此消息","stop": "停止生成"},"pluginSetup": {diff --git a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.tsindex 33a7262861..2e197080fe 100644--- a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts+++ b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.recordingGate.test.ts@@ -15,6 +15,20 @@ describe('VoiceInputSection shortcut recording gate', () => {expect(source).toContain('window.electronAPI.appShortcuts.setRecording(false)');});+ it('checks the active Composer binding before preview and persistence', () => {+ const source = readFileSync(+ new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),+ 'utf8',+ );++ expect(source).toContain('const hasComposerVoiceConflict = useCallback(');+ expect(source).toContain('getComposerSendShortcutPreference()');+ expect(source).toContain('findComposerVoiceInputConflict(');+ expect(source).toContain("result.conflict === 'composer-voice-input'");+ expect(source).toContain("settings.shortcuts.errors.composerVoiceConflict");+ expect(source).toContain('findVoiceInputAppShortcutConflict(shortcut, getAppShortcutEntries())');+ });+it('waits for shortcut suspension before committing and restores the latest persisted shortcut', () => {const source = readFileSync(new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),@@ -67,8 +81,12 @@ describe('VoiceInputSection shortcut recording gate', () => {'utf8',);- expect(source).toMatch(/const startFnKeyCapture = useCallback\([\s\S]*?\n {2}\}, \[\]\);/);- expect(source).not.toMatch(/const startFnKeyCapture = useCallback\([\s\S]*?\n {2}\}, \[t\]\);/);+ expect(source).toMatch(+ /const startFnKeyCapture = useCallback\([\s\S]*?\n {2}\}, \[\]\);\n\n \/\//,+ );+ expect(source).not.toMatch(+ /const startFnKeyCapture = useCallback\([\s\S]*?\n {2}\}, \[t\]\);\n\n \/\//,+ );expect(source).toContain('const translateRef = useRef(t);');expect(source).toContain('translateRef.current = t;');});diff --git a/apps/desktop/src/renderer/voice-input/__tests__/composerVoiceInputConflict.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/composerVoiceInputConflict.test.tsnew file mode 100644index 0000000000..69e9718a3c--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/__tests__/composerVoiceInputConflict.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from 'vitest';++import { findComposerVoiceInputConflict } from '../composerVoiceInputConflict';+import type { VoiceInputShortcut } from '../shortcut';++type ShortcutOverrides = Omit<Partial<VoiceInputShortcut>, 'modifiers'> & {+ modifiers?: Partial<VoiceInputShortcut['modifiers']>;+};++function shortcut(overrides: ShortcutOverrides = {}): VoiceInputShortcut {+ const { modifiers: overrideModifiers, ...shortcutOverrides } = overrides;+ return {+ trigger: 'keyboard',+ code: 'Enter',+ key: 'Enter',+ ...shortcutOverrides,+ modifiers: {+ meta: false,+ ctrl: true,+ alt: false,+ shift: false,+ fn: false,+ ...overrideModifiers,+ },+ };+}++describe('findComposerVoiceInputConflict', () => {+ it.each([+ ['darwin', shortcut({ modifiers: { meta: true, ctrl: false } })],+ ['darwin', shortcut()],+ ['win32', shortcut()],+ ['linux', shortcut()],+ ] as const)('detects the platform modifier+Enter conflict on %s', (platform, voiceShortcut) => {+ expect(findComposerVoiceInputConflict('modifier-enter', voiceShortcut, platform)).toBe(+ 'composer-voice-input',+ );+ });++ it.each([+ ['default Composer mode', 'enter', shortcut(), 'win32'],+ [+ 'plain Enter',+ 'modifier-enter',+ shortcut({ modifiers: { meta: false, ctrl: false } }),+ 'win32',+ ],+ [+ 'wrong platform modifier',+ 'modifier-enter',+ shortcut({ modifiers: { meta: true, ctrl: false } }),+ 'win32',+ ],+ ['Alt+Enter', 'modifier-enter', shortcut({ modifiers: { alt: true } }), 'win32'],+ ['Shift+Enter', 'modifier-enter', shortcut({ modifiers: { shift: true } }), 'win32'],+ ['Fn+Enter', 'modifier-enter', shortcut({ modifiers: { fn: true } }), 'win32'],+ [+ 'modifier-only shortcut',+ 'modifier-enter',+ shortcut({ trigger: 'modifier', code: 'ControlLeft', key: 'ControlLeft' }),+ 'win32',+ ],+ ['empty Voice Input shortcut', 'modifier-enter', null, 'win32'],+ ] as const)('does not flag %s', (_name, preference, voiceShortcut, platform) => {+ expect(findComposerVoiceInputConflict(preference, voiceShortcut, platform)).toBeNull();+ });++ it('matches the Composer modifier logic when both platform modifiers are held', () => {+ expect(+ findComposerVoiceInputConflict(+ 'modifier-enter',+ shortcut({ modifiers: { meta: true, ctrl: true } }),+ 'darwin',+ ),+ ).toBe('composer-voice-input');+ });+});diff --git a/apps/desktop/src/renderer/voice-input/composerShortcut.ts b/apps/desktop/src/renderer/voice-input/composerShortcut.tsnew file mode 100644index 0000000000..9e694d1694--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/composerShortcut.ts@@ -0,0 +1,6 @@+export function hasComposerModifier(+ event: Pick<KeyboardEvent, 'metaKey' | 'ctrlKey'>,+ platform: string | undefined,+): boolean {+ return event.ctrlKey || (platform === 'darwin' && event.metaKey);+}diff --git a/apps/desktop/src/renderer/voice-input/composerVoiceInputConflict.ts b/apps/desktop/src/renderer/voice-input/composerVoiceInputConflict.tsnew file mode 100644index 0000000000..aef5a8d061--- /dev/null+++ b/apps/desktop/src/renderer/voice-input/composerVoiceInputConflict.ts@@ -0,0 +1,34 @@+import type { ComposerSendShortcutPreference } from '@/hooks/useComposerSendShortcutPreference';+import { hasComposerModifier } from './composerShortcut';+import type { VoiceInputShortcut } from './shortcut';++export type ShortcutConflict = 'composer-voice-input' | null;++/**+ * Return a conflict only when Voice Input owns the platform's complete+ * modifier+Enter combination used by Composer's modifier-send mode.+ */+export function findComposerVoiceInputConflict(+ preference: ComposerSendShortcutPreference,+ voiceShortcut: VoiceInputShortcut | null,+ platform: string | undefined,+): ShortcutConflict {+ if (preference !== 'modifier-enter' || !voiceShortcut) return null;+ if (voiceShortcut.trigger === 'modifier' || voiceShortcut.modifiers.fn) return null;+ if (voiceShortcut.code !== 'Enter' || voiceShortcut.key !== 'Enter') return null;+ if (voiceShortcut.modifiers.alt || voiceShortcut.modifiers.shift) return null;++ if (+ !hasComposerModifier(+ {+ metaKey: voiceShortcut.modifiers.meta,+ ctrlKey: voiceShortcut.modifiers.ctrl,+ },+ platform,+ )+ ) {+ return null;+ }++ return 'composer-voice-input';+}