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。

feat(voice-input): 长按输入框呼出语音输入 (#5025)

Lizida9b8fde3dd1
diff --git a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
index ace23cfe07..e842c49625 100644
--- a/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
+++ b/apps/desktop/src/main/voice-input/VoiceInputDataStore.ts
@@ -103,25 +103,26 @@ export class VoiceInputDataStore {
updateSettings(patch: unknown): VoiceInputSettings {
const current = this.load();
- const syncJustEnabled = isRecord(patch)
- && patch.dictionarySyncEnabled === true
- && current.settings.dictionarySyncEnabled === false;
- const syncJustDisabled = isRecord(patch)
- && patch.dictionarySyncEnabled === false
- && current.settings.dictionarySyncEnabled === true;
+ // 同步开关的立即广播不能只看布尔 patch:「恢复默认」(传 null)同样会翻转有效值
+ // (比如显式关闭后恢复默认,有效值 false → 当前默认 true),对端可能早已在线,
+ // 必须按更新前后的有效值判断是否跨越开关边界。
+ const syncEnabledBefore = current.settings.dictionarySyncEnabled;
// 词典三件套的真相在同步状态里,不接受整份覆盖 —— 那会绕过 CRDT,让本地写入
// 在下一次物化时被静默丢掉。词典变更一律走下面的语义化入口。
const nextSettings = normalizeVoiceInputSettings({
...current.settings,
- ...stripDictionaryFields(patch),
+ ...translateComposerLongPressPatch(stripDictionaryFields(patch)),
}, process.platform);
this.replaceState({
...current,
settings: nextSettings,
});
- // 开关刚切到开或关:对端可能早已在线,既没有 presence 事件也没有词典变更。
- // 打开时立刻推当前投影;关闭时立刻推空表,清掉已经在线的手机缓存。
- if (syncJustEnabled || syncJustDisabled) notifyDictionaryChanged({ immediate: true });
+ // 开关刚切到开或关(含恢复默认导致的翻转):对端可能早已在线,既没有 presence
+ // 事件也没有词典变更。打开时立刻推当前投影;关闭时立刻推空表,清掉已经在线的
+ // 手机缓存。
+ if (syncEnabledBefore !== nextSettings.dictionarySyncEnabled) {
+ notifyDictionaryChanged({ immediate: true });
+ }
return cloneSettings(nextSettings);
}
@@ -644,7 +645,7 @@ export class VoiceInputDataStore {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const tmp = `${filePath}.tmp`;
- fs.writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf-8');
+ fs.writeFileSync(tmp, JSON.stringify(projectVoiceInputDataForPersist(state), null, 2), 'utf-8');
fs.renameSync(tmp, filePath);
} catch (error) {
log.warn('voice input data write failed', {
@@ -949,6 +950,20 @@ function cloneSettings(settings: VoiceInputSettings): VoiceInputSettings {
return JSON.parse(JSON.stringify(settings)) as VoiceInputSettings;
}
+/**
+ * 落盘只记录 override。运行时快照里的 `composerLongPressEnabled` / `dictionarySyncEnabled`
+ * 是默认值 + override 合成的有效值;写进文件会把当时的默认钉死,未自定义的用户就跟不上
+ * 后续改默认 —— 尤其是「恢复默认」后残留的旧有效值,将来默认一变就会被
+ * `legacyDictionarySyncOverride()` 重新解释成显式 override。两个字段都只持久化
+ * 各自的 `*Override`。
+ */
+function projectVoiceInputDataForPersist(state: StoredVoiceInputData): unknown {
+ const settings: Record<string, unknown> = { ...state.settings };
+ delete settings.composerLongPressEnabled;
+ delete settings.dictionarySyncEnabled;
+ return { ...state, settings };
+}
+
function cloneHistory(history: VoiceInputHistoryEntry[]): VoiceInputHistoryEntry[] {
return JSON.parse(JSON.stringify(history)) as VoiceInputHistoryEntry[];
}
@@ -1026,3 +1041,20 @@ function stripDictionaryFields(patch: unknown): Record<string, unknown> {
}
return next;
}
+
+/**
+ * 长按输入框开关:UI 传有效值,持久化只认 override(规则同上面的同步开关)。
+ * 每次显式拨动都记成 override;`null` = 恢复默认,删掉 override 跟随版本默认值。
+ */
+function translateComposerLongPressPatch(patch: Record<string, unknown>): Record<string, unknown> {
+ if (!('composerLongPressEnabled' in patch)) return patch;
+ const next = { ...patch };
+ const value = next.composerLongPressEnabled;
+ delete next.composerLongPressEnabled;
+ if (typeof value === 'boolean') {
+ next.composerLongPressEnabledOverride = value;
+ } else if (value === null) {
+ next.composerLongPressEnabledOverride = null;
+ }
+ return next;
+}
diff --git a/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts b/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
index 9e87429fae..8ede4225f6 100644
--- a/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
+++ b/apps/desktop/src/main/voice-input/__tests__/VoiceInputDataStore.test.ts
@@ -38,7 +38,7 @@ import {
voiceInputDataStore,
VoiceInputDataStore,
} from '../VoiceInputDataStore.js';
-import { createVoiceInputHistoryEntry } from '../../../shared/voiceInputData.js';
+import { createVoiceInputHistoryEntry, getDefaultVoiceInputSettings } from '../../../shared/voiceInputData.js';
describe('VoiceInputDataStore persistence', () => {
let dataDir: string;
@@ -69,6 +69,30 @@ describe('VoiceInputDataStore persistence', () => {
}
});
+ it('恢复默认跨过开关边界也立刻广播:显式关闭后恢复默认不让在线设备留旧词典', () => {
+ const store = new VoiceInputDataStore();
+ const listener = vi.fn();
+ const unsubscribe = onVoiceInputDictionaryChanged(listener);
+ try {
+ store.updateSettings({ dictionarySyncEnabled: false });
+ expect(listener).toHaveBeenCalledWith({ immediate: true });
+ listener.mockClear();
+ // 「恢复默认」传 null:有效值从 false 翻回当前默认值,必须与普通开关翻转
+ // 同样立刻广播,否则早已在线的设备会一直保留旧词典状态。
+ const next = store.updateSettings({ dictionarySyncEnabled: null });
+ expect(next.dictionarySyncEnabled).toBe(
+ getDefaultVoiceInputSettings(process.platform).dictionarySyncEnabled,
+ );
+ expect(listener).toHaveBeenCalledWith({ immediate: true });
+ listener.mockClear();
+ // 有效值没有跨越边界就不广播(例如重复恢复默认)。
+ store.updateSettings({ dictionarySyncEnabled: null });
+ expect(listener).not.toHaveBeenCalled();
+ } finally {
+ unsubscribe();
+ }
+ });
+
it('writes the candidate before committing state and broadcasting it', () => {
const store = new VoiceInputDataStore();
diff --git a/apps/desktop/src/main/voice-input/__tests__/composerLongPressSetting.test.ts b/apps/desktop/src/main/voice-input/__tests__/composerLongPressSetting.test.ts
new file mode 100644
index 0000000000..a018665d6b
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/__tests__/composerLongPressSetting.test.ts
@@ -0,0 +1,110 @@
+/**
+ * 长按输入框语音输入开关的落盘契约:持久化只记录用户 override,不把默认值固化进
+ * 用户配置(docs/dev-rules/configuration-and-overrides.md §2)。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+let tempDir = '';
+
+vi.mock('electron', () => ({
+ app: { getPath: () => tempDir },
+ ipcMain: { handle: vi.fn(), on: vi.fn() },
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: 'owner-1' }),
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(tempDir, 'owners', 'owner-1', ...parts),
+}));
+vi.mock('../../utils/ipcValidate.js', () => ({
+ throwIpcError: (code: string, message: string) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+}));
+
+const { voiceDictionarySyncStore } = await import('../VoiceDictionarySyncStore.js');
+const { voiceInputDataStore } = await import('../VoiceInputDataStore.js');
+
+const DATA_FILE = 'voice-input-data.v1.json';
+
+function dataFilePath(): string {
+ return path.join(tempDir, 'owners', 'owner-1', DATA_FILE);
+}
+
+function writeSettingsFile(settings: Record<string, unknown>): void {
+ fs.mkdirSync(path.dirname(dataFilePath()), { recursive: true });
+ fs.writeFileSync(dataFilePath(), JSON.stringify({ version: 1, settings, history: [] }), 'utf-8');
+}
+
+function readPersistedSettings(): Record<string, unknown> {
+ return JSON.parse(fs.readFileSync(dataFilePath(), 'utf-8')).settings;
+}
+
+/** 两个 store 都按 ownerId 缓存内存状态,每个用例都要从磁盘重新读。 */
+function resetStoreCaches(): void {
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).data = null;
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).dataOwnerId = null;
+ (voiceDictionarySyncStore as unknown as { pendingRecovery: unknown }).pendingRecovery = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).state = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).stateOwnerId = null;
+}
+
+beforeEach(() => {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-composer-long-press-'));
+ resetStoreCaches();
+});
+
+afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+});
+
+describe('长按输入框语音输入开关 —— 只持久化用户 override', () => {
+ it('默认关闭;无关设置保存不会把默认值记成用户选择', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ expect(voiceInputDataStore.getSettings().composerLongPressEnabled).toBe(false);
+
+ voiceInputDataStore.updateSettings({ language: 'zh-CN' });
+ expect(readPersistedSettings().composerLongPressEnabledOverride).toBeUndefined();
+ expect(readPersistedSettings().composerLongPressEnabled).toBeUndefined();
+ });
+
+ it('用户打开后记录 override,重载后保持', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ const next = voiceInputDataStore.updateSettings({ composerLongPressEnabled: true });
+ expect(next.composerLongPressEnabled).toBe(true);
+ expect(readPersistedSettings().composerLongPressEnabledOverride).toBe(true);
+ expect(readPersistedSettings().composerLongPressEnabled).toBeUndefined();
+
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().composerLongPressEnabled).toBe(true);
+ });
+
+ it('再次关闭也记为显式选择,而不是删掉 override', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ composerLongPressEnabled: true });
+ voiceInputDataStore.updateSettings({ composerLongPressEnabled: false });
+ expect(readPersistedSettings().composerLongPressEnabledOverride).toBe(false);
+ expect(readPersistedSettings().composerLongPressEnabled).toBeUndefined();
+ });
+
+ it('传 null 恢复默认:删除 override,重新跟随版本默认值', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ composerLongPressEnabled: true });
+ const next = voiceInputDataStore.updateSettings({ composerLongPressEnabled: null });
+ expect(next.composerLongPressEnabled).toBe(false);
+ expect(readPersistedSettings().composerLongPressEnabledOverride).toBeUndefined();
+ expect(readPersistedSettings().composerLongPressEnabled).toBeUndefined();
+ });
+
+ it('配置里残留的有效值不会被当成用户选择', () => {
+ // 有效值只是写盘时的投影;没有 override 就一律跟随默认值。
+ writeSettingsFile({ dictionaryEntries: [], composerLongPressEnabled: true });
+ expect(voiceInputDataStore.getSettings().composerLongPressEnabled).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/main/voice-input/__tests__/dictionarySyncOverrideSetting.test.ts b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncOverrideSetting.test.ts
new file mode 100644
index 0000000000..7e8c833e15
--- /dev/null
+++ b/apps/desktop/src/main/voice-input/__tests__/dictionarySyncOverrideSetting.test.ts
@@ -0,0 +1,120 @@
+/**
+ * 词典同步开关的落盘契约:持久化只记录用户 override,不把派生的有效值固化进用户
+ * 配置(docs/dev-rules/configuration-and-overrides.md §2)。派生值一旦落盘,「恢复
+ * 默认」清除 override 后它仍残留在文件里 —— 将来版本修改默认值时,
+ * `legacyDictionarySyncOverride()` 会把这个旧值重新解释成显式 override,已恢复
+ * 默认的用户就再也跟不上新默认。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+let tempDir = '';
+
+vi.mock('electron', () => ({
+ app: { getPath: () => tempDir },
+ ipcMain: { handle: vi.fn(), on: vi.fn() },
+ BrowserWindow: { getAllWindows: () => [] },
+}));
+vi.mock('../../logger.js', () => ({
+ createLogger: () => ({ info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }),
+}));
+vi.mock('../../appSessionState.js', () => ({
+ getActiveAppSession: () => ({ dataOwnerId: 'owner-1' }),
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(tempDir, 'owners', 'owner-1', ...parts),
+}));
+vi.mock('../../utils/ipcValidate.js', () => ({
+ throwIpcError: (code: string, message: string) => {
+ throw new Error(`[${code}] ${message}`);
+ },
+}));
+
+const { voiceDictionarySyncStore } = await import('../VoiceDictionarySyncStore.js');
+const { voiceInputDataStore } = await import('../VoiceInputDataStore.js');
+const { getDefaultVoiceInputSettings } = await import('../../../shared/voiceInputData.js');
+
+const DATA_FILE = 'voice-input-data.v1.json';
+
+function dataFilePath(): string {
+ return path.join(tempDir, 'owners', 'owner-1', DATA_FILE);
+}
+
+function writeSettingsFile(settings: Record<string, unknown>): void {
+ fs.mkdirSync(path.dirname(dataFilePath()), { recursive: true });
+ fs.writeFileSync(dataFilePath(), JSON.stringify({ version: 1, settings, history: [] }), 'utf-8');
+}
+
+function readPersistedSettings(): Record<string, unknown> {
+ return JSON.parse(fs.readFileSync(dataFilePath(), 'utf-8')).settings;
+}
+
+/** 两个 store 都按 ownerId 缓存内存状态,每个用例都要从磁盘重新读。 */
+function resetStoreCaches(): void {
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).data = null;
+ (voiceDictionarySyncStore as unknown as { data: unknown; dataOwnerId: unknown }).dataOwnerId = null;
+ (voiceDictionarySyncStore as unknown as { pendingRecovery: unknown }).pendingRecovery = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).state = null;
+ (voiceInputDataStore as unknown as { state: unknown; stateOwnerId: unknown }).stateOwnerId = null;
+}
+
+beforeEach(() => {
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-dictionary-sync-override-'));
+ resetStoreCaches();
+});
+
+afterEach(() => {
+ fs.rmSync(tempDir, { recursive: true, force: true });
+});
+
+describe('词典同步开关 —— 落盘只持久化用户 override', () => {
+ it('拨动记成 override,落盘不写派生的有效值', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ const next = voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+ expect(next.dictionarySyncEnabled).toBe(false);
+ expect(readPersistedSettings().dictionarySyncEnabledOverride).toBe(false);
+ expect(readPersistedSettings().dictionarySyncEnabled).toBeUndefined();
+
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(false);
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabledOverride).toBe(false);
+ });
+
+ it('恢复默认后磁盘不残留有效值,重新跟随版本默认值', () => {
+ const defaults = getDefaultVoiceInputSettings(process.platform);
+ writeSettingsFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+ const next = voiceInputDataStore.updateSettings({ dictionarySyncEnabled: null });
+ expect(next.dictionarySyncEnabled).toBe(defaults.dictionarySyncEnabled);
+ expect(readPersistedSettings().dictionarySyncEnabledOverride).toBeUndefined();
+ expect(readPersistedSettings().dictionarySyncEnabled).toBeUndefined();
+
+ resetStoreCaches();
+ const reloaded = voiceInputDataStore.getSettings();
+ expect(reloaded.dictionarySyncEnabled).toBe(defaults.dictionarySyncEnabled);
+ expect(reloaded.dictionarySyncEnabledOverride).toBeUndefined();
+ });
+
+ it('恢复默认后无关保存不把有效值写回,后续默认变更可跟随', () => {
+ writeSettingsFile({ dictionaryEntries: [] });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: false });
+ voiceInputDataStore.updateSettings({ dictionarySyncEnabled: null });
+ voiceInputDataStore.updateSettings({ language: 'zh-CN' });
+
+ // 文件里没有这个键,将来改默认值的版本加载同一文件只会看到「无 override」,
+ // legacyDictionarySyncOverride() 没有旧值可误读,必然跟随新默认。
+ const persisted = readPersistedSettings();
+ expect(persisted.dictionarySyncEnabled).toBeUndefined();
+ expect(persisted.dictionarySyncEnabledOverride).toBeUndefined();
+ resetStoreCaches();
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabledOverride).toBeUndefined();
+ });
+
+ it('历史版本落盘的有效值仍按一次性迁移认作显式选择', () => {
+ // 兼容路径不能被本契约改动破坏:老文件没有 override 字段,只有当时的有效值。
+ writeSettingsFile({ dictionaryEntries: [], dictionarySyncEnabled: false });
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabled).toBe(false);
+ expect(voiceInputDataStore.getSettings().dictionarySyncEnabledOverride).toBe(false);
+ });
+});
diff --git a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
index a1face06d3..4b378a7cb6 100644
--- a/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
+++ b/apps/desktop/src/renderer/components/new-chat/ChatInput.tsx
@@ -7,6 +7,7 @@ import {
useSyncExternalStore,
useLayoutEffect,
type DragEvent as ReactDragEvent,
+ type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type RefObject,
type ReactNode,
@@ -395,6 +396,10 @@ import {
type VoiceInputShortcut,
} from '@/voice-input/shortcut';
import { VoiceInputPointerHintLayer } from '@/voice-input/VoiceInputPointerHintLayer';
+import {
+ createComposerLongPressVoiceGesture,
+ type ComposerLongPressVoiceGesture,
+} from '@/voice-input/composerLongPressGesture';
import { requestRendererMicrophonePermission } from '@/voice-input/startGuards';
import { COMPOSER_MENTION_MIME, decodeComposerMentionPayload } from '@/lib/composerMentionDrag';
import { createWorkLouderCodexVoiceGesture } from '@/lib/workLouderCodexVoiceGesture';
@@ -3230,8 +3235,10 @@ export function ChatInput({
prepareVoiceInputCues();
}
}, [voiceInputSettings.playInteractionSound]);
- const handleVoiceInputStart = useCallback(async () => {
- await voiceInput.start({
+ const handleVoiceInputStart = useCallback((): boolean => {
+ // 同步 claim 录音后立刻返回是否占用;授权确认(beforeStart)与启动提示音
+ // 由 useVoiceInput 的后台启动流程继续处理。
+ return voiceInput.start({
startedAt: performance.now(),
beforeStart: onBeforeVoiceInputStart,
onStartFeedback: () => {
@@ -3268,6 +3275,7 @@ export function ChatInput({
const voiceShortcutRef = useRef(voiceInputSettings.shortcut);
const voiceInputStateRef = useRef(voiceInput.state);
+ const voiceInputGetStateRef = useRef(voiceInput.getState);
const voiceInputStopRef = useRef(handleVoiceInputStopWithRefinement);
voiceInputBusyRef.current = voiceInput.isBusy;
voiceDraftTextRef.current = voiceInput.draftText;
@@ -3313,6 +3321,7 @@ export function ChatInput({
useEffect(() => {
voiceInputStateRef.current = voiceInput.state;
+ voiceInputGetStateRef.current = voiceInput.getState;
voiceInputStopRef.current = handleVoiceInputStopWithRefinement;
voiceInputCancelRef.current = voiceInput.cancel;
handleVoiceInputStartRef.current = handleVoiceInputStart;
@@ -3326,6 +3335,7 @@ export function ChatInput({
handleVoiceInputStart,
handleVoiceInputStopWithRefinement,
voiceInput.cancel,
+ voiceInput.getState,
voiceInput.state,
]);
@@ -3522,6 +3532,125 @@ export function ChatInput({
};
}, []);
+ // 长按输入框语音输入(语音设置里打开,默认关闭):输入框不加任何提示,按住鼠标
+ // 左键不动片刻即开始录音,松开结束。按下由输入框的 onMouseDown 接入(要读
+ // detail 才能排除双击);移动/松开挂在 window 上。真正开始录音后再指针捕获,
+ // 拖出窗口松开也能停;等待期间不捕获,免得打断选字。
+ const composerLongPressVoiceInputEnabled = voiceInputSettings.composerLongPressEnabled;
+ const composerLongPressGestureRef = useRef<ComposerLongPressVoiceGesture | null>(null);
+ const armComposerLongPressCaptureRef = useRef<((pointerId: number, target: Element) => void) | null>(
+ null,
+ );
+ useEffect(() => {
+ if (!composerLongPressVoiceInputEnabled) return;
+ let capture: { pointerId: number; target: Element } | null = null;
+ let gesture: ComposerLongPressVoiceGesture;
+
+ const handleLostPointerCapture = (event: Event) => {
+ if (!(event instanceof PointerEvent)) return;
+ if (!capture || event.pointerId !== capture.pointerId) return;
+ gesture.release();
+ };
+
+ const releaseCapture = () => {
+ if (!capture) return;
+ const current = capture;
+ capture = null;
+ current.target.removeEventListener('lostpointercapture', handleLostPointerCapture);
+ if (current.target.hasPointerCapture(current.pointerId)) {
+ try {
+ current.target.releasePointerCapture(current.pointerId);
+ } catch {
+ // 指针已经抬起或捕获已被系统清掉。
+ }
+ }
+ };
+
+ gesture = createComposerLongPressVoiceGesture({
+ getState: () => voiceInputGetStateRef.current(),
+ start: () => handleVoiceInputStartRef.current(),
+ stop: () => voiceInputStopRef.current(),
+ onHoldStart: () => {
+ if (!capture) return;
+ try {
+ capture.target.setPointerCapture(capture.pointerId);
+ capture.target.addEventListener('lostpointercapture', handleLostPointerCapture);
+ } catch {
+ capture = null;
+ }
+ },
+ onHoldEnd: releaseCapture,
+ });
+ composerLongPressGestureRef.current = gesture;
+ armComposerLongPressCaptureRef.current = (pointerId, target) => {
+ capture = { pointerId, target };
+ };
+
+ const handlePointerMove = (event: PointerEvent) => {
+ // 按住录音时鼠标还是按下的,Chromium 会拿 move 继续拖选文字;取消默认
+ // 行为,说话时挪动鼠标不会拉出一片选区。
+ if (gesture.isHolding()) {
+ event.preventDefault();
+ return;
+ }
+ gesture.move({ x: event.clientX, y: event.clientY });
+ };
+ const handleLeftButtonRelease = (event: PointerEvent | MouseEvent) => {
+ if (event.button !== 0) return;
+ gesture.release();
+ // 没到时长就松开时不会走 onHoldEnd,但仍要清掉按下时记下的 pointerId。
+ releaseCapture();
+ };
+ const handleAbort = () => {
+ gesture.release();
+ releaseCapture();
+ };
+ window.addEventListener('pointermove', handlePointerMove, true);
+ window.addEventListener('pointerup', handleLeftButtonRelease, true);
+ window.addEventListener('mouseup', handleLeftButtonRelease, true);
+ window.addEventListener('pointercancel', handleAbort, true);
+ // 按在已选中的文字上会进入原生拖拽,之后不再有 move / up。
+ window.addEventListener('dragstart', handleAbort, true);
+ window.addEventListener('blur', handleAbort);
+ return () => {
+ armComposerLongPressCaptureRef.current = null;
+ if (composerLongPressGestureRef.current === gesture) {
+ composerLongPressGestureRef.current = null;
+ }
+ gesture.dispose();
+ releaseCapture();
+ window.removeEventListener('pointermove', handlePointerMove, true);
+ window.removeEventListener('pointerup', handleLeftButtonRelease, true);
+ window.removeEventListener('mouseup', handleLeftButtonRelease, true);
+ window.removeEventListener('pointercancel', handleAbort, true);
+ window.removeEventListener('dragstart', handleAbort, true);
+ window.removeEventListener('blur', handleAbort);
+ };
+ }, [composerLongPressVoiceInputEnabled]);
+
+ const handleComposerLongPressPointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
+ if (event.button !== 0) return;
+ armComposerLongPressCaptureRef.current?.(event.pointerId, event.currentTarget);
+ }, []);
+
+ const handleComposerLongPressMouseDown = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {
+ const gesture = composerLongPressGestureRef.current;
+ if (!gesture) return;
+ // 只认单击左键:修饰键点击是扩选/多光标,双击后按住是按词拖选。
+ if (event.button !== 0 || event.detail > 1) return;
+ if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey) return;
+ if (disabledRef.current || composerMutationLockedRef.current) return;
+ const editorInstance = editorRef.current;
+ if (!editorInstance || editorInstance.isDestroyed) return;
+ const editorElement = editorInstance.view.dom;
+ const target = event.target;
+ if (!(target instanceof Element) || !editorElement.contains(target)) return;
+ // 提及 / 粘贴文本 / 引用这类 chip 自带点击与拖拽行为,不在上面起手。
+ const atom = target.closest('[contenteditable="false"]');
+ if (atom && atom !== editorElement && editorElement.contains(atom)) return;
+ gesture.press({ x: event.clientX, y: event.clientY });
+ }, []);
+
useEffect(() => {
return window.electronAPI.voiceInput.onGlobalShortcutTrigger((payload) => {
if (disabledRef.current || !editorRef.current || editorRef.current.isDestroyed) return;
@@ -3615,6 +3744,12 @@ export function ChatInput({
const releaseInFlight = () => {
window.setTimeout(() => {
voiceShortcutActionInFlightRef.current = false;
+ // 启动已改为同步 claim,排队的「松开即停」可能在 claim 完成后才被
+ // 登记;锁释放时兜底消费一次,避免短按快松后麦克风一直开着。
+ if (voiceShortcutStopAfterStartRef.current) {
+ voiceShortcutStopAfterStartRef.current = false;
+ void voiceInputStopRef.current().catch(() => undefined);
+ }
}, 120);
};
@@ -3623,9 +3758,10 @@ export function ChatInput({
return;
}
- void handleVoiceInputStartRef
- .current()
- .then(() => {
+ void Promise.resolve(handleVoiceInputStartRef.current())
+ .then((claimed) => {
+ // start 同步 claim 后立刻返回;这次没占到录音就不代它停别人的。
+ if (claimed === false) return;
if (!voiceShortcutStopAfterStartRef.current) return;
voiceShortcutStopAfterStartRef.current = false;
return voiceInputStopRef.current();
@@ -7593,7 +7729,9 @@ export function ChatInput({
const gesture = createWorkLouderCodexVoiceGesture({
longPressMs: VOICE_INPUT_LONG_PRESS_MS,
getState: () => voiceInputStateRef.current,
- start: () => handleVoiceInputStartRef.current(),
+ start: () => {
+ void handleVoiceInputStartRef.current();
+ },
stop: () => voiceInputStopRef.current(),
});
workLouderVoiceGestureRef.current = gesture;
@@ -8763,6 +8901,8 @@ export function ChatInput({
data-recommendation-active={showRecommendationOverlay ? 'true' : undefined}
// 建议预览生效时由 CSS 隐去编辑器正文。
data-prompt-preview-active={showPromptPreview ? 'true' : undefined}
+ onPointerDown={handleComposerLongPressPointerDown}
+ onMouseDown={handleComposerLongPressMouseDown}
>
<EditorContent
editor={editor}
@@ -9448,7 +9588,7 @@ function VoiceInputButton({
state: import('@cindy/voice-input-core').VoiceInputState;
disabled: boolean;
shortcutLabel: string;
- onStart: () => Promise<void>;
+ onStart: () => boolean | Promise<boolean | void>;
onStop: () => Promise<void>;
onStopAndSend: () => Promise<void>;
sendTargetRef: RefObject<HTMLElement | null>;
diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts b/apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts
index 200861aaa7..80f6be26da 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts
+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.settings-search.ts
@@ -16,6 +16,7 @@ export default {
{ id: 'settings.voiceInput.history.label', fallbackTargetId: 'settings-panel-voice-input', tab: 'voice-input', targetId: 'settings-search-settings-voiceInput-history-label', titleKey: 'settings.voiceInput.history.label', sectionKey: 'settings.tabs.voiceInput' },
{ id: 'settings.voiceInput.sections.usageData', fallbackTargetId: 'settings-panel-voice-input', tab: 'voice-input', targetId: 'settings-search-voice-usage-data', titleKey: 'settings.voiceInput.sections.usageData', sectionKey: 'settings.tabs.voiceInput' },
{ id: 'settings.voiceInput.fastActivation.label', fallbackTargetId: 'settings-panel-voice-input', tab: 'voice-input', targetId: 'settings-search-settings-voiceInput-fastActivation-label', titleKey: 'settings.voiceInput.fastActivation.label', sectionKey: 'settings.tabs.voiceInput', descriptionKey: 'settings.voiceInput.fastActivation.hint' },
+ { id: 'settings.voiceInput.composerLongPress.label', fallbackTargetId: 'settings-panel-voice-input', tab: 'voice-input', targetId: 'settings-search-settings-voiceInput-composerLongPress-label', titleKey: 'settings.voiceInput.composerLongPress.label', sectionKey: 'settings.tabs.voiceInput', descriptionKey: 'settings.voiceInput.composerLongPress.hint' },
{ id: 'settings.voiceInput.shortcut.label', fallbackTargetId: 'settings-panel-voice-input', tab: 'voice-input', targetId: 'settings-search-settings-voiceInput-shortcut-label', titleKey: 'settings.voiceInput.shortcut.label', sectionKey: 'settings.tabs.voiceInput', descriptionKey: 'settings.voiceInput.shortcut.hint' },
],
diff --git a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
index e310035ed0..c1fd616761 100644
--- a/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/VoiceInputSection.tsx
@@ -1,6 +1,7 @@
import { Button } from '@/components/ui/button';
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react';
import { useSettingsSearchNavigation } from './SettingsSearchNavigation';
+import { DefaultOverrideControls } from './DefaultOverrideControls';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';
import * as Dialog from '@radix-ui/react-dialog';
@@ -1041,10 +1042,13 @@ export function VoiceInputSection() {
setMuteSystemAudio,
setPlayInteractionSound,
setFastActivationEnabled,
+ setComposerLongPressEnabled,
+ resetComposerLongPressEnabled,
setRefinementEnabled,
setRefinementInstructions,
setAutoDictionaryEnabled,
setDictionarySyncEnabled,
+ resetDictionarySyncEnabled,
addDictionaryEntry: addDictionarySettingEntry,
importDictionaryEntries: importDictionarySettingEntries,
editDictionaryEntry: editDictionarySettingEntry,
@@ -2211,11 +2215,21 @@ export function VoiceInputSection() {
</p>
</div>
- <Switch
- checked={settings.dictionarySyncEnabled}
- onCheckedChange={setDictionarySyncEnabled}
- aria-label={t('settings.voiceInput.refinement.dictionary.deviceSync.ariaLabel')}
- />
+ <div className="flex shrink-0 items-center gap-2">
+ <DefaultOverrideControls
+ isCustomized={settings.dictionarySyncEnabledOverride != null}
+ onReset={() => {
+ void resetDictionarySyncEnabled().then((ok) => {
+ if (ok) toast.success(t('settings.defaults.restored'));
+ });
+ }}
+ />
+ <Switch
+ checked={settings.dictionarySyncEnabled}
+ onCheckedChange={setDictionarySyncEnabled}
+ aria-label={t('settings.voiceInput.refinement.dictionary.deviceSync.ariaLabel')}
+ />
+ </div>
</div>
<div className="flex flex-wrap items-center justify-between gap-3">
@@ -2687,6 +2701,36 @@ export function VoiceInputSection() {
/>
</div>
+ <div className="flex items-center justify-between gap-5 border-t border-[var(--settings-theme-card-border)] pt-4">
+ <div className="flex min-w-0 flex-col gap-1">
+ <p id="settings-search-settings-voiceInput-composerLongPress-label"
+ className="text-13 font-medium text-[var(--settings-section-title)]"
+ style={{ letterSpacing: '0.12px' }}
+ >
+ {t('settings.voiceInput.composerLongPress.label')}
+ </p>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.voiceInput.composerLongPress.hint')}
+ </p>
+ </div>
+
+ <div className="flex shrink-0 items-center gap-2">
+ <DefaultOverrideControls
+ isCustomized={settings.composerLongPressEnabledOverride != null}
+ onReset={() => {
+ void resetComposerLongPressEnabled().then((ok) => {
+ if (ok) toast.success(t('settings.defaults.restored'));
+ });
+ }}
+ />
+ <Switch
+ checked={settings.composerLongPressEnabled}
+ onCheckedChange={setComposerLongPressEnabled}
+ aria-label={t('settings.voiceInput.composerLongPress.ariaLabel')}
+ />
+ </div>
+ </div>
+
<div className="flex items-center justify-between gap-5 border-t border-[var(--settings-theme-card-border)] pt-4">
<div className="flex min-w-0 flex-col gap-1">
<p id="settings-search-settings-voiceInput-interactionSound-label"
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.overrideReset.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.overrideReset.test.ts
new file mode 100644
index 0000000000..b02f29d468
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/__tests__/useVoiceInputSettings.overrideReset.test.ts
@@ -0,0 +1,126 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ getDefaultVoiceInputSettings,
+ type VoiceInputSettings,
+ type VoiceInputSettingsPatch,
+} from '../../../shared/voiceInputData';
+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(), success: vi.fn() },
+}));
+
+import { toast } from '@/lib/toast';
+
+let settings: VoiceInputSettings;
+let updateSettings: ReturnType<typeof vi.fn>;
+
+function installElectronApi(): void {
+ updateSettings = vi.fn(async () => settings);
+ Object.defineProperty(window, 'electronAPI', {
+ configurable: true,
+ value: {
+ platform: 'darwin',
+ voiceInput: {
+ getDataSnapshot: () => ({ settings }),
+ updateSettings,
+ setGlobalShortcut: vi.fn().mockResolvedValue({ ok: true }),
+ onDataChanged: vi.fn(() => () => {}),
+ },
+ },
+ });
+}
+
+describe('voice input override restore defaults', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ settings = {
+ ...getDefaultVoiceInputSettings('darwin'),
+ composerLongPressEnabled: true,
+ composerLongPressEnabledOverride: true,
+ dictionarySyncEnabled: true,
+ dictionarySyncEnabledOverride: true,
+ };
+ installElectronApi();
+ });
+
+ it('长按开关恢复默认提交 null 删除 override,成功后采纳返回的设置', async () => {
+ const { result } = renderHook(() => useVoiceInputSettings());
+ updateSettings.mockImplementation(async (patch: VoiceInputSettingsPatch) => {
+ expect(patch).toEqual({ composerLongPressEnabled: null });
+ const next = { ...settings };
+ delete next.composerLongPressEnabledOverride;
+ next.composerLongPressEnabled = false;
+ return next;
+ });
+
+ let ok!: boolean;
+ await act(async () => {
+ ok = await result.current.resetComposerLongPressEnabled();
+ });
+
+ expect(ok).toBe(true);
+ expect(updateSettings).toHaveBeenCalledTimes(1);
+ expect(updateSettings).toHaveBeenCalledWith({ composerLongPressEnabled: null });
+ expect(result.current.settings.composerLongPressEnabled).toBe(false);
+ expect(result.current.settings.composerLongPressEnabledOverride).toBeUndefined();
+ });
+
+ it('词典同步开关同一套约定:恢复默认提交 null', async () => {
+ const { result } = renderHook(() => useVoiceInputSettings());
+ updateSettings.mockImplementation(async (patch: VoiceInputSettingsPatch) => {
+ expect(patch).toEqual({ dictionarySyncEnabled: null });
+ const next = { ...settings };
+ delete next.dictionarySyncEnabledOverride;
+ next.dictionarySyncEnabled = false;
+ return next;
+ });
+
+ let ok!: boolean;
+ await act(async () => {
+ ok = await result.current.resetDictionarySyncEnabled();
+ });
+
+ expect(ok).toBe(true);
+ expect(updateSettings).toHaveBeenCalledWith({ dictionarySyncEnabled: null });
+ expect(result.current.settings.dictionarySyncEnabledOverride).toBeUndefined();
+ });
+
+ it('普通拨动仍写布尔有效值,不会顺手清掉 override 语义', async () => {
+ const { result } = renderHook(() => useVoiceInputSettings());
+
+ await act(async () => {
+ result.current.setComposerLongPressEnabled(false);
+ });
+
+ expect(updateSettings).toHaveBeenCalledWith({ composerLongPressEnabled: false });
+ expect(updateSettings).not.toHaveBeenCalledWith({ composerLongPressEnabled: null });
+ });
+
+ it('持久化失败时恢复默认返回 false 并提示,不谎报成功', async () => {
+ const { result } = renderHook(() => useVoiceInputSettings());
+ updateSettings.mockRejectedValue(new Error('ipc unavailable'));
+
+ let ok!: boolean;
+ await act(async () => {
+ ok = await result.current.resetComposerLongPressEnabled();
+ });
+
+ expect(ok).toBe(false);
+ expect(toast.error).toHaveBeenCalledTimes(1);
+ expect(toast.success).not.toHaveBeenCalled();
+ expect(result.current.settings.composerLongPressEnabledOverride).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
index 9d5623af9a..fd98cd16b7 100644
--- a/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
+++ b/apps/desktop/src/renderer/hooks/useVoiceInputSettings.ts
@@ -28,6 +28,7 @@ import {
type VoiceInputDictionaryLearningEvidence,
type VoiceInputLanguage,
type VoiceInputSettings,
+ type VoiceInputSettingsPatch,
} from '../../shared/voiceInputData';
import type { VoiceInputShortcut } from '@/voice-input/shortcut';
import { findComposerVoiceInputConflict } from '@/voice-input/composerVoiceInputConflict';
@@ -194,10 +195,18 @@ export function useVoiceInputSettings(): {
setMuteSystemAudio: (enabled: boolean) => void;
setPlayInteractionSound: (enabled: boolean) => void;
setFastActivationEnabled: (enabled: boolean) => void;
+ setComposerLongPressEnabled: (enabled: boolean) => void;
+ /**
+ * 「恢复默认」= 传 `null` 删除 override、重新跟随当前版本默认值
+ * (`configuration-and-overrides.md` §4)。返回持久化结果,成功才收口 UI。
+ */
+ resetComposerLongPressEnabled: () => Promise<boolean>;
setRefinementEnabled: (enabled: boolean) => void;
setRefinementInstructions: (instructions: string) => void;
setAutoDictionaryEnabled: (enabled: boolean) => void;
setDictionarySyncEnabled: (enabled: boolean) => void;
+ /** 同 {@link resetComposerLongPressEnabled}:null 删 override 恢复默认。 */
+ resetDictionarySyncEnabled: () => Promise<boolean>;
/** 这几个返回持久化结果:成功才收口 UI(关对话框、清草稿、提示成功)。 */
addDictionaryEntry: (text: string) => Promise<boolean>;
importDictionaryEntries: (texts: string[]) => Promise<boolean>;
@@ -210,7 +219,7 @@ export function useVoiceInputSettings(): {
const { t } = useTranslation();
const [settings, setSettings] = useState<VoiceInputSettings>(getVoiceInputSettings);
- const updateSettings = useCallback((patch: Partial<VoiceInputSettings>) => {
+ const updateSettings = useCallback((patch: VoiceInputSettingsPatch) => {
const previousShortcut = getVoiceInputSettings().shortcut;
void window.electronAPI.voiceInput
.updateSettings(patch)
@@ -251,6 +260,11 @@ export function useVoiceInputSettings(): {
[updateSettings],
);
+ const setComposerLongPressEnabled = useCallback(
+ (composerLongPressEnabled: boolean) => updateSettings({ composerLongPressEnabled }),
+ [updateSettings],
+ );
+
const setRefinementEnabled = useCallback(
(refinementEnabled: boolean) => updateSettings({ refinementEnabled }),
[updateSettings],
@@ -271,6 +285,37 @@ export function useVoiceInputSettings(): {
[updateSettings],
);
+ // 恢复默认与普通拨动分开:拨动写布尔 override,恢复默认要传 null 删 override
+ // (规则 §4 不允许写静态快照)。失败时 toast 由这里统一收口,成功提示交给调用方。
+ const runOverrideReset = useCallback(
+ (patch: VoiceInputSettingsPatch): Promise<boolean> =>
+ window.electronAPI.voiceInput
+ .updateSettings(patch)
+ .then((next) => {
+ setSettings(next);
+ return true;
+ })
+ .catch((error) => {
+ log.warn(
+ 'voice input settings restore default failed:',
+ error instanceof Error ? error.message : String(error),
+ );
+ toast.error(formatVoiceInputPersistenceError(t, error));
+ return false;
+ }),
+ [t],
+ );
+
+ const resetComposerLongPressEnabled = useCallback(
+ () => runOverrideReset({ composerLongPressEnabled: null }),
+ [runOverrideReset],
+ );
+
+ const resetDictionarySyncEnabled = useCallback(
+ () => runOverrideReset({ dictionarySyncEnabled: null }),
+ [runOverrideReset],
+ );
+
// 词典的增改删都是语义化操作:主进程按「用户做了什么」更新同步状态,再把物化
// 结果回投影成 settings。整份覆盖词条数组表达不了用户意图,也会被下一次物化冲掉。
/**
@@ -378,10 +423,13 @@ export function useVoiceInputSettings(): {
setMuteSystemAudio,
setPlayInteractionSound,
setFastActivationEnabled,
+ setComposerLongPressEnabled,
+ resetComposerLongPressEnabled,
setRefinementEnabled,
setRefinementInstructions,
setAutoDictionaryEnabled,
setDictionarySyncEnabled,
+ resetDictionarySyncEnabled,
addDictionaryEntry,
importDictionaryEntries,
renameDictionaryEntry,
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index d24c3f3058..02df457c50 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -1542,6 +1542,11 @@
"hint": "Keeps the microphone ready briefly after use so recording starts sooner after pressing the shortcut or button; usually about 100 ms faster. The microphone is released automatically after 30 minutes of no use.",
"ariaLabel": "Toggle fast voice activation"
},
+ "composerLongPress": {
+ "label": "Hold composer for voice input",
+ "hint": "Press and hold the left mouse button in the composer for a moment to start voice input. Release to stop and insert the text.",
+ "ariaLabel": "Toggle hold composer for voice input"
+ },
"refinement": {
"enabled": {
"label": "Voice refinement",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index c76eacd766..fd40954378 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -1542,6 +1542,11 @@
"hint": "使用後しばらくマイクを待機状態に保ち、ショートカットやボタンを押してから録音開始までを短縮します。通常は約 100 ms 速くなります。30 分間使用しないと自動的にマイクを解放します。",
"ariaLabel": "音声入力の高速開始を切り替え"
},
+ "composerLongPress": {
+ "label": "入力欄の長押しで音声入力",
+ "hint": "入力欄でマウスの左ボタンを少し長押しすると音声入力を開始し、離すと終了して文字を入力します。",
+ "ariaLabel": "入力欄の長押しで音声入力を切り替え"
+ },
"refinement": {
"enabled": {
"label": "音声テキストを整える",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index acf113d14e..a3df51bd23 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -1542,6 +1542,11 @@
"hint": "사용 후 잠시 마이크를 대기 상태로 유지해 단축키나 버튼을 누른 뒤 녹음이 시작되기까지의 시간을 줄입니다. 보통 약 100 ms 빨라집니다. 30분 동안 다시 사용하지 않으면 마이크를 자동으로 해제합니다.",
"ariaLabel": "음성 입력 빠른 시작 전환"
},
+ "composerLongPress": {
+ "label": "입력창 길게 눌러 음성 입력",
+ "hint": "입력창에서 마우스 왼쪽 버튼을 잠시 길게 누르면 음성 입력이 시작되고, 버튼을 놓으면 종료되어 텍스트가 입력됩니다.",
+ "ariaLabel": "입력창 길게 눌러 음성 입력 전환"
+ },
"refinement": {
"enabled": {
"label": "음성 텍스트 정리",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 36a7de60d5..1e73309c09 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -1542,6 +1542,11 @@
"hint": "用完后让麦克风短暂待命,缩短按下快捷键或按钮到开始录音的等待;通常可快约 100 毫秒。若 30 分钟内没有再次使用,会自动释放麦克风。",
"ariaLabel": "切换快速启动语音输入"
},
+ "composerLongPress": {
+ "label": "长按输入框语音输入",
+ "hint": "在输入框里按住鼠标左键片刻即开始语音输入,松开后结束并填入文字。",
+ "ariaLabel": "切换长按输入框语音输入"
+ },
"refinement": {
"enabled": {
"label": "语音润色",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index c7c3b084db..769b72f728 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -1542,6 +1542,11 @@
"hint": "用完後讓麥克風短暫待命,縮短按下快捷鍵或按鈕到開始錄音的等待;通常可快約 100 毫秒。若 30 分鐘內沒有再次使用,會自動釋放麥克風。",
"ariaLabel": "切換快速啟動語音輸入"
},
+ "composerLongPress": {
+ "label": "長按輸入框語音輸入",
+ "hint": "在輸入框裡按住滑鼠左鍵片刻即開始語音輸入,放開後結束並填入文字。",
+ "ariaLabel": "切換長按輸入框語音輸入"
+ },
"refinement": {
"enabled": {
"label": "語音潤色",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 4967502218..75075af306 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -269,6 +269,7 @@ type VoiceInputDictionaryAdviceInput =
type VoiceInputDictionaryLearningAction =
import('@cindy/voice-input-core').DictationDictionaryLearningAction;
type VoiceInputSettingsData = import('../shared/voiceInputData').VoiceInputSettings;
+type VoiceInputSettingsPatchData = import('../shared/voiceInputData').VoiceInputSettingsPatch;
type VoiceInputHistoryEntryData = import('../shared/voiceInputData').VoiceInputHistoryEntry;
type VoiceInputDataSnapshot = import('../shared/voiceInputData').VoiceInputDataSnapshot;
type VoiceInputProviderKindData = import('../shared/voiceInputAsrProfiles').VoiceInputProviderKind;
@@ -1831,7 +1832,7 @@ interface ElectronAPI {
settingsRaw?: string | null;
historyRaw?: string | null;
}) => VoiceInputDataSnapshot;
- updateSettings: (patch: Partial<VoiceInputSettingsData>) => Promise<VoiceInputSettingsData>;
+ updateSettings: (patch: VoiceInputSettingsPatchData) => Promise<VoiceInputSettingsData>;
updateShortcutSetting: (shortcut: VoiceInputShortcut | null) => Promise<
| {
ok: true;
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts
new file mode 100644
index 0000000000..23790682c6
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/__tests__/VoiceInputSection.overrideReset.test.ts
@@ -0,0 +1,35 @@
+import { readFileSync } from 'node:fs';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * 「恢复默认」入口的接线约束。行为链路(提交 null 删 override)由
+ * `useVoiceInputSettings.overrideReset.test.ts` 与 main 侧
+ * `composerLongPressSetting.test.ts`(「传 null 恢复默认」)覆盖;这里锁住
+ * VoiceInputSection 的行级接线,防止入口被静默摘掉又只剩布尔开关。
+ */
+describe('VoiceInputSection restore default entries', () => {
+ it('shows restore controls only for override-backed switches and restores via null submitters', () => {
+ const source = readFileSync(
+ new URL('../../components/settings/VoiceInputSection.tsx', import.meta.url),
+ 'utf8',
+ );
+
+ // 长按输入框开关:override 存在时才出现「已自定义/恢复默认」,恢复走提交 null 的动作。
+ expect(source).toContain('isCustomized={settings.composerLongPressEnabledOverride != null}');
+ expect(source).toContain('void resetComposerLongPressEnabled()');
+ // 词典同步开关与长按开关同一套 override 约定,入口必须成对存在。
+ expect(source).toContain('isCustomized={settings.dictionarySyncEnabledOverride != null}');
+ expect(source).toContain('void resetDictionarySyncEnabled()');
+ });
+
+ it('restore helpers submit null instead of writing a static default snapshot', () => {
+ const source = readFileSync(
+ new URL('../../hooks/useVoiceInputSettings.ts', import.meta.url),
+ 'utf8',
+ );
+
+ expect(source).toContain('runOverrideReset({ composerLongPressEnabled: null })');
+ expect(source).toContain('runOverrideReset({ dictionarySyncEnabled: null })');
+ });
+});
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/composerLongPressGesture.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/composerLongPressGesture.test.ts
new file mode 100644
index 0000000000..298fc7b73d
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/__tests__/composerLongPressGesture.test.ts
@@ -0,0 +1,294 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { VoiceInputState } from '@cindy/voice-input-core';
+import {
+ COMPOSER_LONG_PRESS_MOVE_TOLERANCE_PX,
+ COMPOSER_LONG_PRESS_VOICE_INPUT_MS,
+ createComposerLongPressVoiceGesture,
+} from '../composerLongPressGesture';
+
+const origin = { x: 100, y: 40 };
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>((nextResolve) => {
+ resolve = nextResolve;
+ });
+ return { promise, resolve };
+}
+
+async function settle(): Promise<void> {
+ for (let index = 0; index < 8; index += 1) await Promise.resolve();
+}
+
+function setup(initialState: VoiceInputState = 'idle') {
+ let state: VoiceInputState = initialState;
+ const start = vi.fn(async () => {
+ state = 'listening';
+ });
+ const stop = vi.fn(async () => {
+ state = 'done';
+ });
+ const gesture = createComposerLongPressVoiceGesture({
+ getState: () => state,
+ start,
+ stop,
+ });
+ return {
+ gesture,
+ start,
+ stop,
+ getState: () => state,
+ setState: (next: VoiceInputState) => {
+ state = next;
+ },
+ };
+}
+
+describe('createComposerLongPressVoiceGesture', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('按住不动到时长才开始录音,松开结束', async () => {
+ const { gesture, start, stop, getState } = setup();
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS - 1);
+ await settle();
+ expect(start).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+ await settle();
+ expect(start).toHaveBeenCalledOnce();
+ expect(getState()).toBe('listening');
+ expect(gesture.isHolding()).toBe(true);
+
+ gesture.release();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+ expect(gesture.isHolding()).toBe(false);
+ });
+
+ it('没到时长就松开是普通点击,不录音', async () => {
+ const { gesture, start, stop } = setup();
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS / 2);
+ gesture.release();
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+
+ expect(start).not.toHaveBeenCalled();
+ expect(stop).not.toHaveBeenCalled();
+ });
+
+ it('等待期间拖动超出容差视为选字,放弃长按', async () => {
+ const { gesture, start } = setup();
+
+ gesture.press(origin);
+ gesture.move({ x: origin.x + COMPOSER_LONG_PRESS_MOVE_TOLERANCE_PX, y: origin.y });
+ gesture.move({ x: origin.x + COMPOSER_LONG_PRESS_MOVE_TOLERANCE_PX + 1, y: origin.y });
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it('容差内的手抖不影响长按', async () => {
+ const { gesture, start } = setup();
+
+ gesture.press(origin);
+ gesture.move({ x: origin.x + 2, y: origin.y - 2 });
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+
+ expect(start).toHaveBeenCalledOnce();
+ });
+
+ it('语音输入已在进行时不接管按下', async () => {
+ const { gesture, start } = setup('submitting');
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+
+ expect(start).not.toHaveBeenCalled();
+ });
+
+ it('授权确认还没占用录音就松开,等这次 start 占用成功后再停', async () => {
+ let state: VoiceInputState = 'idle';
+ const startGate = deferred();
+ const start = vi.fn(async () => {
+ await startGate.promise;
+ state = 'listening';
+ return true;
+ });
+ const stop = vi.fn(async () => {
+ state = 'done';
+ });
+ const gesture = createComposerLongPressVoiceGesture({
+ getState: () => state,
+ start,
+ stop,
+ });
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ expect(start).toHaveBeenCalledOnce();
+
+ gesture.release();
+ await settle();
+ expect(stop).not.toHaveBeenCalled();
+
+ startGate.resolve();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('这次长按没有占用录音时,延后停止不会停掉别人的录音', async () => {
+ let state: VoiceInputState = 'idle';
+ const startGate = deferred();
+ const start = vi.fn(async () => {
+ await startGate.promise;
+ return false;
+ });
+ const stop = vi.fn(async () => {
+ state = 'done';
+ });
+ const gesture = createComposerLongPressVoiceGesture({
+ getState: () => state,
+ start,
+ stop,
+ });
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ gesture.release();
+ state = 'listening';
+ startGate.resolve();
+ await settle();
+
+ expect(stop).not.toHaveBeenCalled();
+ expect(state).toBe('listening');
+ });
+
+ it('start 在返回前把状态写成 listening,松开时不依赖下一次渲染', async () => {
+ let state: VoiceInputState = 'idle';
+ const start = vi.fn(() => {
+ state = 'listening';
+ return true;
+ });
+ const stop = vi.fn(() => {
+ state = 'done';
+ });
+ const gesture = createComposerLongPressVoiceGesture({
+ getState: () => state,
+ start,
+ stop,
+ });
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ expect(start).toHaveBeenCalledOnce();
+ expect(state).toBe('listening');
+
+ gesture.release();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('占用录音后松开立刻进入 stop,不必等 start promise 里剩余的启动流程', async () => {
+ let state: VoiceInputState = 'idle';
+ const bootstrapGate = deferred();
+ let bootstrapFinished = false;
+ const start = vi.fn(async () => {
+ state = 'listening';
+ void bootstrapGate.promise.then(() => {
+ bootstrapFinished = true;
+ });
+ return true;
+ });
+ const stop = vi.fn(async () => {
+ state = 'done';
+ });
+ const gesture = createComposerLongPressVoiceGesture({
+ getState: () => state,
+ start,
+ stop,
+ });
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ expect(start).toHaveBeenCalledOnce();
+ expect(state).toBe('listening');
+
+ gesture.release();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+ expect(bootstrapFinished).toBe(false);
+
+ bootstrapGate.resolve();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+ });
+
+ it('到达时长时通知 onHoldStart,松开时通知 onHoldEnd', async () => {
+ const onHoldStart = vi.fn();
+ const onHoldEnd = vi.fn();
+ const { start } = setup();
+ const gestureWithHold = createComposerLongPressVoiceGesture({
+ getState: () => 'idle',
+ start,
+ stop: vi.fn(),
+ onHoldStart,
+ onHoldEnd,
+ });
+
+ gestureWithHold.press(origin);
+ expect(onHoldStart).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ expect(onHoldStart).toHaveBeenCalledOnce();
+
+ gestureWithHold.release();
+ expect(onHoldEnd).toHaveBeenCalledOnce();
+ });
+
+ it('录音被 Esc 取消后再松开不会重复停止', async () => {
+ const { gesture, stop, setState } = setup();
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ setState('idle');
+
+ gesture.release();
+ await settle();
+ expect(stop).not.toHaveBeenCalled();
+ });
+
+ it('按住录音时销毁(关掉开关或卸载)会结束录音,之后不再响应', async () => {
+ const { gesture, start, stop } = setup();
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ gesture.dispose();
+ await settle();
+ expect(stop).toHaveBeenCalledOnce();
+
+ gesture.press(origin);
+ vi.advanceTimersByTime(COMPOSER_LONG_PRESS_VOICE_INPUT_MS);
+ await settle();
+ expect(start).toHaveBeenCalledOnce();
+ });
+});
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
index 5575f6b5fa..720fb17237 100644
--- a/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
+++ b/apps/desktop/src/renderer/voice-input/__tests__/useVoiceInput.startup.test.ts
@@ -101,6 +101,9 @@ function chunk(index: number, amplitude = 512): PcmChunk {
};
}
+// useVoiceInput.start() 同步 claim 录音后立刻返回是否占用;启动流程(采集、授权
+// 确认、连接)在后台继续,测试里捕获的 starting 是 claim 结果,启动收尾由 act
+// 的刷新覆盖。
function mount() {
const connection = deferred<{ ok: true; runId: string }>();
const mute = deferred<{ ok: true }>();
@@ -160,7 +163,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
const device = deferred<void>();
mocks.startEngine.mockReturnValue(device.promise);
const endCue = vi.fn();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start();
});
@@ -218,7 +221,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('finishes silent capture without waiting for a pending cloud connection, and cancels a late run', async () => {
const h = mount();
const endCue = vi.fn();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start();
});
@@ -284,7 +287,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('retains all 8 seconds while both cloud and system mute are pending; signals ready only after PCM', async () => {
const h = mount();
const cue = vi.fn();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start({ onStartFeedback: cue });
});
@@ -311,7 +314,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('starts local capture before a slow preflight, and stops it if preflight declines', async () => {
const h = mount();
const preflight = deferred<boolean>();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start({ beforeStart: () => preflight.promise });
});
@@ -334,7 +337,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
const cue = vi.fn(() => {
expect(mocks.startEngine).toHaveBeenCalledTimes(1);
});
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start({ onStartFeedback: cue });
});
@@ -355,7 +358,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('retains PCM during the start cue and mutes only after playback finishes', async () => {
const h = mount();
const cue = deferred<void>();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start({ onStartFeedback: () => cue.promise });
});
@@ -381,7 +384,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
const device = deferred<void>();
mocks.startEngine.mockReturnValue(device.promise);
const cue = vi.fn();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start({ onStartFeedback: cue });
});
@@ -418,7 +421,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('preserves buffered opening audio when Stop is pressed before cloud connects', async () => {
const h = mount();
- let starting!: Promise<void>;
+ let starting!: boolean;
await act(async () => {
starting = h.result.current.start();
});
@@ -449,7 +452,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
it('ignores the old connection after cancel and immediate restart', async () => {
const h = mount();
- let oldStart!: Promise<void>;
+ let oldStart!: boolean;
await act(async () => {
oldStart = h.result.current.start();
});
@@ -459,7 +462,7 @@ describe('local voice capture independent of startup checks and cloud', () => {
});
const nextConnection = deferred<{ ok: true; runId: string }>();
h.api.start.mockReturnValue(nextConnection.promise);
- let nextStart!: Promise<void>;
+ let nextStart!: boolean;
await act(async () => {
nextStart = h.result.current.start();
});
diff --git a/apps/desktop/src/renderer/voice-input/composerLongPressGesture.ts b/apps/desktop/src/renderer/voice-input/composerLongPressGesture.ts
new file mode 100644
index 0000000000..e077680e54
--- /dev/null
+++ b/apps/desktop/src/renderer/voice-input/composerLongPressGesture.ts
@@ -0,0 +1,162 @@
+import type { VoiceInputState } from '@cindy/voice-input-core';
+
+/** 在输入框里按住鼠标左键多久才开始语音输入。 */
+export const COMPOSER_LONG_PRESS_VOICE_INPUT_MS = 600;
+/** 等待期间指针移动超过这个距离即视为在拖选文字,放弃本次长按。 */
+export const COMPOSER_LONG_PRESS_MOVE_TOLERANCE_PX = 4;
+
+export type ComposerLongPressPoint = { x: number; y: number };
+
+export type ComposerLongPressVoiceGestureOptions = {
+ holdMs?: number;
+ moveTolerancePx?: number;
+ getState: () => VoiceInputState;
+ /**
+ * 开始录音。返回 `false` 表示这次没有占用录音(已在录音、被取消等),
+ * 调用方不得再对当前会话执行 `stop()`。
+ */
+ start: () => boolean | void | Promise<boolean | void>;
+ stop: () => void | Promise<void>;
+ /** 已过时长、真正开始按住录音时。用来补指针捕获,好在窗口外松开。 */
+ onHoldStart?: () => void;
+ /** 松开、放弃或销毁时。用来释放指针捕获。 */
+ onHoldEnd?: () => void;
+};
+
+export type ComposerLongPressVoiceGesture = {
+ /** 左键按下:开始计时。按键、修饰键与命中目标由调用方过滤。 */
+ press(point: ComposerLongPressPoint): void;
+ move(point: ComposerLongPressPoint): void;
+ /**
+ * 松开、失焦、开始拖拽都走这里:没到时长就当普通点击放弃;已经开始录音则结束
+ * 录音,文字照常填回输入框。
+ */
+ release(): void;
+ /** 是否正按住录音(已过时长、还没松开)。 */
+ isHolding(): boolean;
+ dispose(): void;
+};
+
+type PendingPress = {
+ origin: ComposerLongPressPoint;
+ timer: ReturnType<typeof setTimeout>;
+};
+
+const isIdleLike = (state: VoiceInputState): boolean =>
+ state === 'idle' || state === 'done' || state === 'error';
+
+/**
+ * 输入框长按语音输入手势(微信式「按住说话」):
+ *
+ * - 按住不动达到 `holdMs` 才开始录音,之前松开或移动都不影响普通点击与选字;
+ * - 开始后松开即结束录音。
+ *
+ * `start` 可能先走授权确认再占用麦克风:松开时若已经在 listening 就立刻停;
+ * 若还在确认中,等这次 start 确认占用成功后再停,避免误停别人后来开的录音。
+ * 独立于 React,按住期间的重渲染不会打断它。
+ */
+export function createComposerLongPressVoiceGesture(
+ options: ComposerLongPressVoiceGestureOptions,
+): ComposerLongPressVoiceGesture {
+ const holdMs = options.holdMs ?? COMPOSER_LONG_PRESS_VOICE_INPUT_MS;
+ const moveTolerancePx = options.moveTolerancePx ?? COMPOSER_LONG_PRESS_MOVE_TOLERANCE_PX;
+ let pending: PendingPress | null = null;
+ let holding = false;
+ let startPromise: Promise<boolean> | null = null;
+ let stopAfterStart = false;
+ let ownedSession = false;
+ let stopInFlight = false;
+ let disposed = false;
+ let startGeneration = 0;
+
+ const clearPending = (): void => {
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ pending = null;
+ };
+
+ const endHold = (): void => {
+ if (!holding) return;
+ holding = false;
+ options.onHoldEnd?.();
+ };
+
+ const runStop = (): void => {
+ if (stopInFlight) return;
+ stopInFlight = true;
+ ownedSession = false;
+ void Promise.resolve()
+ .then(() => options.stop())
+ .catch(() => undefined)
+ .finally(() => {
+ stopInFlight = false;
+ });
+ };
+
+ const requestStop = (): void => {
+ if (startPromise) {
+ // 授权确认还没结束:记下,等这次 start 占用成功后再停。
+ // 占用成功后(stateRef 已是 listening、bootstrap 可能还在跑)由
+ // useVoiceInput.stop() 立刻进入停止流程,不必等麦克风 / WebSocket 就绪。
+ stopAfterStart = true;
+ return;
+ }
+ // start 已结束:只停这次长按占用、且现在仍在听的录音。Esc 取消后
+ // getState 已不是 listening,不能再 stop。
+ if (!ownedSession || options.getState() !== 'listening') return;
+ runStop();
+ };
+
+ const beginVoiceInput = (): void => {
+ pending = null;
+ if (disposed || !isIdleLike(options.getState())) return;
+ holding = true;
+ options.onHoldStart?.();
+ const generation = ++startGeneration;
+ const currentStart = Promise.resolve()
+ .then(() => options.start())
+ .then((claimed) => claimed !== false)
+ .catch(() => false);
+ startPromise = currentStart;
+ void currentStart.then((claimed) => {
+ if (startPromise !== currentStart) return;
+ startPromise = null;
+ if (generation !== startGeneration) return;
+ ownedSession = claimed;
+ if (!stopAfterStart) return;
+ stopAfterStart = false;
+ if (claimed) runStop();
+ });
+ };
+
+ const release = (): void => {
+ clearPending();
+ if (!holding) return;
+ endHold();
+ requestStop();
+ };
+
+ return {
+ press(point) {
+ if (disposed || pending || holding || startPromise) return;
+ if (!isIdleLike(options.getState())) return;
+ pending = {
+ origin: point,
+ timer: setTimeout(beginVoiceInput, holdMs),
+ };
+ },
+ move(point) {
+ if (!pending) return;
+ const dx = point.x - pending.origin.x;
+ const dy = point.y - pending.origin.y;
+ if (dx * dx + dy * dy > moveTolerancePx * moveTolerancePx) clearPending();
+ },
+ release,
+ isHolding: () => holding,
+ dispose() {
+ // 关掉开关或卸载时如果正按住录音,按松开处理,麦克风不能一直开着。
+ release();
+ disposed = true;
+ },
+ };
+}
diff --git a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
index 68318453bc..68dfc6164e 100644
--- a/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
+++ b/apps/desktop/src/renderer/voice-input/useVoiceInput.ts
@@ -143,7 +143,10 @@ export type UseVoiceInputResult = {
isBusy: boolean;
getLastSubmittedText: () => string;
getLastRefinement: () => VoiceInputRefinementSnapshot | null;
- start: (options?: VoiceInputStartOptions) => Promise<void>;
+ /** 同步读取当前状态,不经过 React 渲染。长按手势靠它判断是否占用了录音。 */
+ getState: () => VoiceInputState;
+ /** 同步 claim 录音后立刻返回是否占用;启动流程(授权确认、采集、连接)在后台继续。 */
+ start: (options?: VoiceInputStartOptions) => boolean;
stop: (options?: VoiceInputStopOptions) => Promise<void>;
cancel: () => Promise<void>;
};
@@ -250,6 +253,8 @@ export function useVoiceInput(
setState(next);
}, []);
+ const getState = useCallback(() => stateRef.current, []);
+
const isActiveStartAttempt = useCallback((attemptId: number) => (
startAttemptIdRef.current === attemptId
&& (stateRef.current === 'listening' || stateRef.current === 'submitting')
@@ -1231,7 +1236,7 @@ export function useVoiceInput(
voiceInputSettings.microphoneDeviceId,
]);
- const start = useCallback(async (startOptions?: VoiceInputStartOptions) => {
+ const start = useCallback((startOptions?: VoiceInputStartOptions): boolean => {
const currentState = stateRef.current;
if (
disabled ||
@@ -1241,7 +1246,7 @@ export function useVoiceInput(
currentState === 'submitting' ||
currentState === 'refining'
) {
- return;
+ return false;
}
const timeline = createVoiceInputStartupTimeline('inline', startOptions?.startedAt);
startupTimelineRef.current = timeline;
@@ -1265,6 +1270,10 @@ export function useVoiceInput(
sentAudioMsRef.current = 0;
terminalOutcomeRef.current = 'success';
+ // 同步 claim 已经返回,启动流程在后台继续:本地采集与提示音先走,授权确认
+ // (beforeStart)、服务可用性检查与云端连接随后;stop() 通过 start-ready 等待
+ // 这段启动期,松手后立刻进入停止流程,不必等这里的异步步骤全部完成。
+ void (async () => {
const { elapsedMs } = timeline;
const capturePromise = startVoiceInputCaptureSession({
@@ -1525,6 +1534,12 @@ export function useVoiceInput(
}
captureStart.drainPendingChunks();
resolveStartReadyState(attemptId, result);
+ })().catch((error) => {
+ log.warn('voice input start failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ return true;
}, [
appendAudioChunk,
buildRefinementContext,
@@ -1773,6 +1788,7 @@ export function useVoiceInput(
isBusy: state === 'listening' || state === 'submitting' || state === 'refining',
getLastSubmittedText: () => lastSubmittedTextRef.current,
getLastRefinement: () => lastRefinementRef.current,
+ getState,
start,
stop: stopWithGate,
cancel,
diff --git a/apps/desktop/src/shared/voiceInputData.ts b/apps/desktop/src/shared/voiceInputData.ts
index dfcde7c796..386352bd30 100644
--- a/apps/desktop/src/shared/voiceInputData.ts
+++ b/apps/desktop/src/shared/voiceInputData.ts
@@ -103,6 +103,15 @@ export interface VoiceInputSettings {
* 在当时的默认值上,以后改默认值也带不动他们,「恢复默认」也失去意义。
*/
dictionarySyncEnabledOverride?: boolean | null;
+ /**
+ * 是否允许在输入框里按住鼠标左键呼出语音输入(**有效值** = 默认 + 用户 override)。
+ * 输入框不显示任何提示,只在设置里打开后生效。
+ *
+ * 读这个字段即可;写请走 {@link composerLongPressEnabledOverride}。
+ */
+ composerLongPressEnabled: boolean;
+ /** 用户对上面那个开关的显式选择;`undefined` = 从未自定义,跟随当前版本默认值。 */
+ composerLongPressEnabledOverride?: boolean | null;
dictionaryEntries: VoiceInputDictionaryEntry[];
dictionaryCandidates: VoiceInputDictionaryCandidate[];
suppressedAutomaticDictionaryTexts: string[];
@@ -120,6 +129,20 @@ export interface VoiceInputDataSnapshot {
history: VoiceInputHistoryEntry[];
}
+/**
+ * settings 写入 patch。两个带 override 语义的开关额外接受 `null`:
+ * **不是**写入「关闭」,而是「恢复默认」—— 删除 override、重新跟随当前版本默认值
+ * (`docs/dev-rules/configuration-and-overrides.md` §4)。传 `undefined` 做不到这件事:
+ * patch 是展开合并的,`undefined` 会被现有值盖掉。main 侧 VoiceInputDataStore
+ * 按同一规则转写成 `*Override = null`。
+ */
+export type VoiceInputSettingsPatch = Partial<
+ Omit<VoiceInputSettings, 'dictionarySyncEnabled' | 'composerLongPressEnabled'>
+> & {
+ dictionarySyncEnabled?: boolean | null;
+ composerLongPressEnabled?: boolean | null;
+};
+
export type VoiceInputDictionaryLearningEvidence = Pick<
DictationDictionaryAdviceInput,
'source' | 'rawTranscriptText' | 'beforeText' | 'afterText' | 'context'
@@ -128,6 +151,12 @@ export type VoiceInputDictionaryLearningEvidence = Pick<
/** 词典跨设备同步的系统默认值。改这里即可让未自定义的用户随版本跟随。 */
export const DEFAULT_DICTIONARY_SYNC_ENABLED = true;
+/**
+ * 长按输入框语音输入的系统默认值。默认关闭:按住鼠标通常是在选字,只有用户主动
+ * 打开才改变这个手势的含义。
+ */
+export const DEFAULT_COMPOSER_LONG_PRESS_ENABLED = false;
+
export const MAX_VOICE_INPUT_REFINEMENT_INSTRUCTIONS_CHARS = 1_000;
export const MAX_VOICE_INPUT_DICTIONARY_ENTRIES = 1_000;
export const MAX_VOICE_INPUT_DICTIONARY_CANDIDATES = 200;
@@ -473,6 +502,7 @@ export function getDefaultVoiceInputSettings(
autoDictionaryEnabled: true,
// 有效值 = 默认;override 缺省不写(见 dictionarySyncEnabledOverride 注释)。
dictionarySyncEnabled: DEFAULT_DICTIONARY_SYNC_ENABLED,
+ composerLongPressEnabled: DEFAULT_COMPOSER_LONG_PRESS_ENABLED,
dictionaryEntries: [],
dictionaryCandidates: [],
suppressedAutomaticDictionaryTexts: [],
@@ -529,6 +559,7 @@ export function normalizeVoiceInputSettings(
// 区分「用户选的」和「当时的默认」——按规则 §3 只做一次性兼容:仅当它与当前
// 默认不同时才当作用户的显式选择,相同则视为未自定义。
...normalizeDictionarySyncOverride(candidate),
+ ...normalizeComposerLongPressOverride(candidate),
dictionaryEntries: normalizeVoiceInputDictionaryEntries(
candidate.dictionaryEntries ?? (candidate as { customDictionary?: unknown }).customDictionary,
),
@@ -928,6 +959,21 @@ function legacyDictionarySyncOverride(value: unknown): boolean | undefined {
return value === DEFAULT_DICTIONARY_SYNC_ENABLED ? undefined : value;
}
+/**
+ * 长按输入框开关的 override 归一。只认 override 字段:持久化里的有效值只是投影,
+ * 读它等于把写盘那一刻的默认值当成用户选择。该开关从一开始就带 override,没有
+ * 需要兼容的历史格式。
+ */
+function normalizeComposerLongPressOverride(
+ candidate: Partial<VoiceInputSettings>,
+): Pick<VoiceInputSettings, 'composerLongPressEnabled'> & { composerLongPressEnabledOverride?: boolean } {
+ const override = candidate.composerLongPressEnabledOverride;
+ if (typeof override !== 'boolean') {
+ return { composerLongPressEnabled: DEFAULT_COMPOSER_LONG_PRESS_ENABLED };
+ }
+ return { composerLongPressEnabled: override, composerLongPressEnabledOverride: override };
+}
+
function isVoiceInputLanguage(value: unknown): value is VoiceInputLanguage {
if (value === 'auto') return true;
return typeof value === 'string' && (SUPPORTED_LOCALES as readonly string[]).includes(value);