@sonicloud/dsh-sonicloud-device 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/CHANGELOG.zh.md +37 -1
  3. package/README.md +18 -14
  4. package/README.zh.md +9 -5
  5. package/dist/build.json +1 -1
  6. package/dist/client.js +2112 -120
  7. package/docs/contributing/development.md +7 -5
  8. package/docs/specs/ci-cd.md +5 -4
  9. package/docs/specs/mouse-settings.md +1 -1
  10. package/docs/specs/multilingual.md +98 -0
  11. package/docs/specs/smart-mouse-plugin.md +6 -3
  12. package/locale/de.json +7 -0
  13. package/locale/en.json +7 -0
  14. package/locale/es.json +7 -0
  15. package/locale/fr.json +7 -0
  16. package/locale/ja.json +7 -0
  17. package/locale/pt.json +7 -0
  18. package/locale/ru.json +7 -0
  19. package/locale/zh.json +7 -0
  20. package/native/desktop/VOICE_SOURCE.json +2 -2
  21. package/native/desktop/VoicePanel.cs +70 -33
  22. package/native/desktop/VoicePanel.swift +58 -21
  23. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
  24. package/native/screenshot/README.md +9 -4
  25. package/native/screenshot/SOURCE.json +48 -17
  26. package/native/screenshot/darwin-arm64/screentool-macos-1.2.2.zip +0 -0
  27. package/native/screenshot/helper-i18n/de.json +85 -0
  28. package/native/screenshot/helper-i18n/es.json +85 -0
  29. package/native/screenshot/helper-i18n/fr.json +85 -0
  30. package/native/screenshot/patches/{hide-cloud-actions.patch → macos/hide-cloud-actions.patch} +84 -76
  31. package/native/screenshot/patches/macos/mac-clang-compat.patch +14 -0
  32. package/native/screenshot/patches/macos/mac-color-panel.patch +40 -0
  33. package/native/screenshot/patches/macos/mac-permissions.patch +549 -0
  34. package/native/screenshot/patches/macos/mac-ui-focus.patch +658 -0
  35. package/native/screenshot/patches/macos/upstream-files.json +77 -0
  36. package/native/screenshot/patches/upstream-files.json +12 -8
  37. package/native/screenshot/win32-x64/i18n/de.json +85 -0
  38. package/native/screenshot/win32-x64/i18n/es.json +85 -0
  39. package/native/screenshot/win32-x64/i18n/fr.json +85 -0
  40. package/native/screenshot/win32-x64/screenhelper.exe +0 -0
  41. package/package.json +5 -3
  42. package/src/asr/auth.mjs +9 -8
  43. package/src/asr/config.mjs +1 -1
  44. package/src/asr/stream.mjs +25 -24
  45. package/src/desktop/presentation.mjs +18 -12
  46. package/src/desktop/screenshot-shortcut-worker.mjs +188 -0
  47. package/src/desktop/screenshot-shortcut.mjs +266 -0
  48. package/src/desktop/screenshot-worker.mjs +49 -32
  49. package/src/desktop/screenshot.mjs +46 -26
  50. package/src/devices/actions.mjs +7 -6
  51. package/src/devices/config.mjs +2 -1
  52. package/src/devices/diagnostics.mjs +4 -3
  53. package/src/devices/manager.mjs +77 -43
  54. package/src/devices/native-worker.mjs +4 -3
  55. package/src/devices/native.mjs +9 -8
  56. package/src/devices/queue.mjs +4 -3
  57. package/src/devices/recognition.mjs +5 -4
  58. package/src/devices/store.mjs +3 -2
  59. package/src/devices/translate.mjs +11 -10
  60. package/src/host/ai-conversation.mjs +8 -7
  61. package/src/host/index.mjs +13 -3
  62. package/src/host/locale.mjs +44 -0
  63. package/src/shared/devices.mjs +13 -12
  64. package/src/shared/i18n.mjs +47 -0
  65. package/src/shared/locales/de.json +181 -0
  66. package/src/shared/locales/en.json +181 -0
  67. package/src/shared/locales/es.json +181 -0
  68. package/src/shared/locales/fr.json +181 -0
  69. package/src/shared/locales/ja.json +181 -0
  70. package/src/shared/locales/pt.json +181 -0
  71. package/src/shared/locales/ru.json +181 -0
  72. package/src/shared/locales/zh.json +181 -0
  73. package/src/shared/remote.mjs +7 -1
  74. package/src/shared/screenshot-shortcut.mjs +50 -0
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { AsyncQueue, PcmPackets } from './queue.mjs';
3
4
  import { DeviceStore } from './store.mjs';
@@ -10,18 +11,18 @@ import { translateText } from './translate.mjs';
10
11
 
11
12
  const VOICE = new Set(['voice_input', 'translate', 'speechSearch', 'ai_input']);
12
13
  export class DeviceManager {
13
- constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, screenshot, aiConversation, config = {} }) {
14
- Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, screenshot, aiConversation, config });
14
+ constructor({ credentials, recognize, prepare = async () => undefined, sdk = new MouseSdk(), action = systemAction, translate = translateText, desktop, screenshot, shortcut, aiConversation, config = {} }) {
15
+ Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, screenshot, shortcut, aiConversation, config });
15
16
  this.store = new DeviceStore(credentials);
16
17
  this.devices = new Map(); this.clients = new Set(); this.pressed = new Map(); this.pending = Promise.resolve();
17
- this.status = '尚未连接 SDK'; this.disposed = false;
18
+ this.status = msg('status.connecting'); this.disposed = false;
18
19
  this.languages = config.recognitionLanguages ?? DEFAULT_LANGUAGES;
19
20
  this.dpiLevels = config.dpiLevels ?? { '800': 21, '1200': 32, '1600': 42, '2400': 63 };
20
21
  this.dpiReportLevels = config.dpiReportLevels ?? { '800': 0, '1200': 1, '1600': 2, '2400': 3 };
21
22
  this.onEvent = event => {
22
23
  // Audio is copied in the worker. Process it synchronously in IPC order; commands are serialized separately.
23
24
  if (event.type === 'audio') { this.audio(event); return; }
24
- this.pending = this.pending.then(() => this.event(event)).catch(() => this.publish({ type: 'notice', message: '设备事件处理失败,请重连设备' }));
25
+ this.pending = this.pending.then(() => this.event(event)).catch(() => this.publish({ type: 'notice', message: msg('error.device') }));
25
26
  };
26
27
  this.onFault = message => {
27
28
  this.status = message; this.cancel();
@@ -29,17 +30,30 @@ export class DeviceManager {
29
30
  };
30
31
  if (desktop) {
31
32
  desktop.onCancel = id => this.cancel(id);
32
- desktop.onFault = () => this.cancel(undefined, '桌面语音浮层已断开,请重新触发');
33
+ desktop.onFault = () => this.cancel(undefined, msg('error.panel'));
33
34
  }
34
35
  this.onScreenshotNotice = message => { if (!this.disposed) this.publish({ type: 'notice', message }); };
35
36
  screenshot?.on('notice', this.onScreenshotNotice);
37
+ this.onShortcutTrigger = () => {
38
+ if (!this.disposed) void this.captureScreenshot('hotkey').catch(error => this.onScreenshotNotice(error.message));
39
+ };
40
+ this.onShortcutChange = value => { if (!this.disposed) this.publish({ type: 'screenshotShortcut', value }); };
41
+ shortcut?.on('trigger', this.onShortcutTrigger);
42
+ shortcut?.on('notice', this.onScreenshotNotice);
43
+ shortcut?.on('change', this.onShortcutChange);
36
44
  sdk.on('event', this.onEvent); sdk.on('fault', this.onFault);
37
45
  }
46
+ // 宿主 UI 语言变化:语音浮层与截图组件分别尽力跟随,互不阻断。
47
+ setLocale(locale) {
48
+ try { this.desktop?.setLocale?.(locale); } catch { /* 呈现层失败不影响其余跟随 */ }
49
+ try { this.screenshot?.setLocale?.(locale); } catch { /* 截图组件失败不影响其余跟随 */ }
50
+ }
38
51
  async start() {
39
52
  if (this.started) return this.started;
40
53
  this.started = (async () => {
41
54
  try { this.desktop?.start?.(); } catch { /* Key press reports unsupported native presentation. */ }
42
- try { await this.sdk.start(); this.status = this.devices.size ? '设备已连接' : '设备服务已启动,正在查找智能鼠标…'; }
55
+ try { await this.shortcut?.start(); } catch { this.onScreenshotNotice(msg('shortcut.unavailable')); }
56
+ try { await this.sdk.start(); this.status = this.devices.size ? msg('status.connected') : msg('status.searching'); }
43
57
  catch (error) { this.status = error.message; }
44
58
  this.snapshot();
45
59
  })();
@@ -47,7 +61,7 @@ export class DeviceManager {
47
61
  }
48
62
  publish(event) {
49
63
  this.desktop?.event(event);
50
- if (this.desktop && !['devices', 'notice'].includes(event.type)) return;
64
+ if (this.desktop && !['devices', 'notice', 'screenshotShortcut'].includes(event.type)) return;
51
65
  for (const queue of this.clients) {
52
66
  try { queue.push(event); } catch { queue.end(true); this.clients.delete(queue); if (!this.desktop) this.cancel(); }
53
67
  }
@@ -61,13 +75,14 @@ export class DeviceManager {
61
75
  }
62
76
  snapshot() { this.publish({ type: 'devices', ...this.view() }); }
63
77
  async *watch(clientId, signal) {
64
- if (!this.desktop && this.owner) { yield { type: 'notice', message: '智能鼠标已由另一个窗口接管' }; return; }
78
+ if (!this.desktop && this.owner) { yield { type: 'notice', message: msg('error.busy') }; return; }
65
79
  const queue = new AsyncQueue(256); if (!this.desktop) this.owner = clientId; this.clients.add(queue);
66
80
  const abort = () => queue.end(true);
67
81
  signal.addEventListener('abort', abort, { once: true });
68
82
  try {
69
83
  signal.throwIfAborted(); await this.start();
70
84
  queue.push({ type: 'devices', ...this.view() });
85
+ if (this.shortcut) queue.push({ type: 'screenshotShortcut', value: await this.shortcut.state() });
71
86
  yield* queue;
72
87
  } finally {
73
88
  signal.removeEventListener('abort', abort); queue.end(true); this.clients.delete(queue);
@@ -80,7 +95,7 @@ export class DeviceManager {
80
95
  case 'connected': return this.connectDevice(event);
81
96
  case 'disconnected': return this.disconnectDevice(event);
82
97
  case 'message': return this.deviceMessage(event);
83
- case 'overflow': return this.cancelFor(event.id, '鼠标音频处理过慢,本次识别已停止');
98
+ case 'overflow': return this.cancelFor(event.id, msg('error.audio'));
84
99
  case 'warning': return this.publish({ type: 'notice', message: event.message });
85
100
  case 'diagnostic':
86
101
  if (!this.devices.size) { this.status = event.message; this.snapshot(); }
@@ -92,26 +107,26 @@ export class DeviceManager {
92
107
  const stable = isStableSn(id);
93
108
  const category = event.deviceType ?? 'smart-mouse';
94
109
  const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
95
- const device = { id, sn: stable ? id : '', type: category, name: event.name || (category === 'smart-mouse' ? '智能鼠标' : '设备'),
110
+ const device = { id, sn: stable ? id : '', type: category, name: event.name || '', defaultName: !event.name,
96
111
  connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
97
112
  identityConfirmed: stable, dpiState: 'unknown', ...saved };
98
113
  this.devices.set(id, device);
99
114
  this.clearPressed(id);
100
- this.status = '设备已连接';
115
+ this.status = msg('status.connected');
101
116
  if (saved?.revision > 0) await this.applyDpi(device);
102
117
  this.snapshot();
103
118
  }
104
119
  disconnectDevice({ id, mode }) {
105
120
  const device = this.devices.get(id);
106
121
  if (!device || device.connection !== (mode === 1 ? 'ble' : 'usb')) return;
107
- this.cancelFor(id, '设备已断开,语音已取消'); this.devices.delete(id); this.clearPressed(id);
108
- if (!this.devices.size) this.status = '设备已断开,正在重新查找智能鼠标…';
122
+ this.cancelFor(id, msg('error.device')); this.devices.delete(id); this.clearPressed(id);
123
+ if (!this.devices.size) this.status = msg('status.searching');
109
124
  this.snapshot();
110
125
  }
111
126
  async deviceMessage({ id, message }) {
112
127
  const device = this.devices.get(id);
113
- if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '鼠标连接异常' }); return; }
114
- if (message.type === 'queueOverflow') { this.cancel(undefined, '鼠标音频丢失,请重新录音'); return; }
128
+ if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || msg('error.device') }); return; }
129
+ if (message.type === 'queueOverflow') { this.cancel(undefined, msg('error.audio')); return; }
115
130
  if (!device) return;
116
131
  switch (message.type) {
117
132
  case 'deviceInfo': return this.updateDeviceInfo(device, message);
@@ -123,7 +138,7 @@ export class DeviceManager {
123
138
  if (isStableSn(message.sn) && message.sn !== device.sn) {
124
139
  // 只补全临时身份,不合并已确认的设备。
125
140
  if (device.identityConfirmed || this.devices.has(message.sn)) {
126
- device.identityConfirmed = false; this.cancelFor(device.id, '设备 SN 冲突,请重连');
141
+ device.identityConfirmed = false; this.cancelFor(device.id, msg('error.device'));
127
142
  } else {
128
143
  this.devices.delete(device.id); device.sn = message.sn; device.identityConfirmed = true;
129
144
  if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn));
@@ -153,31 +168,31 @@ export class DeviceManager {
153
168
  }
154
169
  async savePreferences(sn, revision, preferences) {
155
170
  const device = [...this.devices.values()].find(item => item.sn === sn && item.identityConfirmed);
156
- if (!device || device.type !== 'smart-mouse') throw new Error('设备已离线、SN 未确认或不支持此配置');
171
+ if (!device || device.type !== 'smart-mouse') throw new Error(msg('error.settings'));
157
172
  const connectionId = device.connectionId;
158
173
  const dpiChanged = preferences.dpi !== device.preferences.dpi || device.dpiState === 'failed';
159
174
  const saved = await this.store.save(sn, revision, preferences);
160
- if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: '配置已保存,设备离线后需重连应用' }; }
175
+ if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: msg('settings.savedOffline') }; }
161
176
  Object.assign(device, saved);
162
- let message = '已保存';
177
+ let message = msg('settings.saved');
163
178
  if (dpiChanged) {
164
- message = '配置已保存,' + await this.applyDpi(device);
179
+ message = msg('settings.savedDpi', { reason: await this.applyDpi(device) });
165
180
  }
166
181
  this.snapshot(); return { ...saved, message };
167
182
  }
168
183
  async applyDpi(device) {
169
184
  const level = this.dpiLevels[device.preferences.dpi];
170
185
  try {
171
- if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error('此固件未配置 DPI 档位映射');
172
- if (await this.sdk.dpi(device.id, level) !== 1) throw new Error('DPI 下发失败');
173
- device.dpiState = 'sent'; return 'DPI 指令已下发(设备不返回生效确认)';
186
+ if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error(msg('keys.dpiFailed'));
187
+ if (await this.sdk.dpi(device.id, level) !== 1) throw new Error(msg('keys.dpiFailed'));
188
+ device.dpiState = 'sent'; return msg('settings.dpiSent');
174
189
  } catch (error) { device.dpiState = 'failed'; return error.message; }
175
190
  }
176
191
  async key(device, event) {
177
192
  if (this.disposed || device.type !== 'smart-mouse') return;
178
193
  if (event.key !== 'capture' && !this.owner && !this.desktop) return;
179
194
  if (!device.identityConfirmed) {
180
- if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: '设备身份未确认,请重新连接鼠标' });
195
+ if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: msg('error.device') });
181
196
  return;
182
197
  }
183
198
  const key = `${device.id}:${event.key}:${event.index ?? 0}`;
@@ -208,7 +223,7 @@ export class DeviceManager {
208
223
  this.pressed.set(key, structuredClone(device.preferences));
209
224
  const action = event.key === 'ai' ? 'ai_input' : event.key === 'm' ? device.preferences.mAction : event.key === 'translation' ? 'translate' : device.preferences.speechAction;
210
225
  if (!VOICE.has(action)) return;
211
- if (this.run) { this.publish({ type: 'notice', message: '其他语音会话正在进行,请稍后重试' }); return; }
226
+ if (this.run) { this.publish({ type: 'notice', message: msg('error.busy') }); return; }
212
227
  let query;
213
228
  try {
214
229
  query = recognitionQuery(device.preferences, action, this.languages);
@@ -220,30 +235,45 @@ export class DeviceManager {
220
235
  };
221
236
  run.packets = new PcmPackets(chunk => run.queue.push(chunk));
222
237
  this.run = run;
223
- if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, '界面未响应,请重新打开宿主窗口'), 5000);
238
+ if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, msg('error.connection')), 5000);
224
239
  run.durationTimer = setTimeout(() => this.release(run), 600000);
225
240
  // Opening the app/client must not block key-up or device-disconnect events.
226
241
  if (action === 'ai_input') void this.begin(run, device);
227
242
  else await this.begin(run, device);
228
243
  }
229
244
  async captureScreenshot(trigger = 'ui') {
230
- if (this.disposed) throw new Error('插件已关闭,请重新启用后截图');
231
- if (!this.screenshot) throw new Error('截图服务不可用,请重新加载插件');
245
+ if (this.disposed) throw new Error(msg('error.closed'));
246
+ if (!this.screenshot) throw new Error(msg('error.screenshot'));
232
247
  return this.screenshot.capture(trigger);
233
248
  }
234
249
  async screenshotPermissions(action = 'check') {
235
- if (this.disposed) throw new Error('插件已关闭,请重新启用后检查截图权限');
236
- if (!this.screenshot?.permissions) throw new Error('截图权限检查不可用,请重新加载插件');
250
+ if (this.disposed) throw new Error(msg('error.closed'));
251
+ if (!this.screenshot?.permissions) throw new Error(msg('error.permission'));
237
252
  return this.screenshot.permissions(action);
238
253
  }
254
+ async screenshotShortcutState() {
255
+ if (this.disposed) throw new Error(msg('error.closed'));
256
+ if (!this.shortcut) return { supported: false, platform: 'other', binding: null, registered: false, error: '' };
257
+ return this.shortcut.state();
258
+ }
259
+ async setScreenshotShortcut(binding) {
260
+ if (this.disposed) throw new Error(msg('error.closed'));
261
+ if (!this.shortcut) throw new Error(msg('shortcut.unavailable'));
262
+ return this.shortcut.set(binding);
263
+ }
264
+ async pauseScreenshotShortcut(clientId, paused) {
265
+ if (this.disposed) throw new Error(msg('error.closed'));
266
+ if (!this.shortcut) throw new Error(msg('shortcut.unavailable'));
267
+ return this.shortcut.suspend(clientId, paused);
268
+ }
239
269
  async typingPermissions(action = 'check') {
240
- if (this.disposed) throw new Error('插件已关闭,请重新启用后检查打字权限');
241
- if (!this.desktop?.permissions) throw new Error('打字权限检查不可用,请重新加载插件');
270
+ if (this.disposed) throw new Error(msg('error.closed'));
271
+ if (!this.desktop?.permissions) throw new Error(msg('error.permission'));
242
272
  return this.desktop.permissions(action);
243
273
  }
244
274
  async prepareAi(run) {
245
275
  try {
246
- if (!this.aiConversation || !this.desktop) throw new Error('AI 对话功能不可用,请重新加载插件');
276
+ if (!this.aiConversation || !this.desktop) throw new Error(msg('error.ai'));
247
277
  // Activation failure alone must not abort: with the window tray-hidden the renderer lives on and insertion still works.
248
278
  try { await this.action('openAi'); } catch { run.aiActivateFailed = true; }
249
279
  run.lifetime.signal.throwIfAborted();
@@ -254,12 +284,12 @@ export class DeviceManager {
254
284
  async begin(run, device) {
255
285
  try {
256
286
  if (run.action === 'ai_input') run.aiReady = this.prepareAi(run);
257
- if (run.action === 'ai_input' && !this.desktop) throw new Error('AI 对话需要桌面语音浮层');
287
+ if (run.action === 'ai_input' && !this.desktop) throw new Error(msg('error.ai'));
258
288
  if (this.desktop) await this.desktop.begin(run);
259
289
  if (this.run !== run || run.closing) return;
260
290
  run.service = await this.prepare();
261
291
  if (this.run !== run || run.closing) return;
262
- if (await this.sdk.source(device.id) !== 1) throw new Error('无法选定鼠标音频源');
292
+ if (await this.sdk.source(device.id) !== 1) throw new Error(msg('error.audio'));
263
293
  if (this.run !== run || run.closing) return;
264
294
  if (this.desktop) { run.started = true; void this.process(run); }
265
295
  else this.publish({ type: 'request', sessionId: run.id, sn: run.sn, action: run.action });
@@ -274,9 +304,9 @@ export class DeviceManager {
274
304
  if (!run || run.deviceId !== event.id || run.audioEnded || this.devices.get(event.id)?.connectionId !== run.connectionId) return;
275
305
  try {
276
306
  const buffer = Buffer.from(event.data, 'base64');
277
- if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error('鼠标音频数据无效');
307
+ if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error(msg('error.audio'));
278
308
  run.bytes += buffer.length;
279
- if (!run.ready && run.bytes > 320000) throw new Error('连接等待的鼠标音频超过 10 秒,请重试');
309
+ if (!run.ready && run.bytes > 320000) throw new Error(msg('error.audio'));
280
310
  run.packets.write(buffer);
281
311
  } catch (error) { this.fail(run, error.message); }
282
312
  }
@@ -287,7 +317,7 @@ export class DeviceManager {
287
317
  run.started = true; clearTimeout(run.captureTimer);
288
318
  void this.process(run); return true;
289
319
  }
290
- assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error('此窗口未接管智能鼠标'); }
320
+ assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error(msg('error.busy')); }
291
321
  release(run) {
292
322
  if (this.run !== run || run.released) return;
293
323
  run.released = true;
@@ -298,7 +328,7 @@ export class DeviceManager {
298
328
  try { run.audioEnded = true; run.packets.flush(); run.queue.end(); }
299
329
  catch (error) { this.fail(run, error.message); }
300
330
  }, this.config.tailMs ?? 150);
301
- run.uploadTimer = setTimeout(() => this.fail(run, '音频上传结束超时'), 15000);
331
+ run.uploadTimer = setTimeout(() => this.fail(run, msg('error.timeout')), 15000);
302
332
  }
303
333
  async process(run) {
304
334
  try {
@@ -317,9 +347,9 @@ export class DeviceManager {
317
347
  if (event.type === 'complete') { complete = true; break; }
318
348
  }
319
349
  if (this.run !== run || run.closing) return;
320
- if (!complete || !run.released) throw new Error('ASR 连接中断,识别结果未完成');
350
+ if (!complete || !run.released) throw new Error(msg('error.connection'));
321
351
  await this.complete(run);
322
- } catch (error) { this.fail(run, error.message || '语音处理失败,请重试'); }
352
+ } catch (error) { this.fail(run, error.message || msg('error.generic')); }
323
353
  }
324
354
  async complete(run) {
325
355
  let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
@@ -343,12 +373,12 @@ export class DeviceManager {
343
373
  await this.aiConversation.insert(run, text);
344
374
  if (this.run !== run || run.closing) return;
345
375
  this.publish(run.aiActivateFailed
346
- ? { type: 'failed', sessionId: run.id, message: '窗口未唤起,文字已填入对话草稿,可复制结果' }
376
+ ? { type: 'failed', sessionId: run.id, message: msg('error.aiWindow') }
347
377
  : { type: 'finished', sessionId: run.id });
348
378
  } catch (error) {
349
379
  // On Windows the panel keeps the text so the user can focus any input and submit it there.
350
380
  if (this.desktop?.platform === 'win32') {
351
- this.publish({ type: 'submitOffer', sessionId: run.id, text, message: '请打开需要输入界面' });
381
+ this.publish({ type: 'submitOffer', sessionId: run.id, text, message: msg('panel.openInput') });
352
382
  await this.finish(run);
353
383
  return;
354
384
  }
@@ -391,6 +421,10 @@ export class DeviceManager {
391
421
  this.clients.clear(); this.owner = undefined;
392
422
  this.sdk.off('event', this.onEvent); this.sdk.off('fault', this.onFault);
393
423
  this.screenshot?.off('notice', this.onScreenshotNotice);
424
+ this.shortcut?.off('trigger', this.onShortcutTrigger);
425
+ this.shortcut?.off('notice', this.onScreenshotNotice);
426
+ this.shortcut?.off('change', this.onShortcutChange);
427
+ try { await this.shortcut?.close(); } catch { /* Release the native registration before the capture process. */ }
394
428
  this.aiConversation?.close();
395
429
  try { await this.screenshot?.close(); } catch { /* 截图进程退出失败不阻断设备和语音清理。 */ }
396
430
  await this.desktop?.close();
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import koffi from 'koffi';
2
3
  import { dirname } from 'node:path';
3
4
  const path = process.argv[2];
@@ -29,10 +30,10 @@ try {
29
30
  bind('um_register_connected', 'void MouseConnected(const char *id, int mode)', (id, mode) => notify({ type: 'connected', id, mode }));
30
31
  bind('um_register_disconnected', 'void MouseDisconnected(const char *id, int mode)', (id, mode) => notify({ type: 'disconnected', id, mode }));
31
32
  bind('um_register_message', 'void MouseMessage(const char *id, const char *json)', (id, json) => {
32
- try { notify({ type: 'message', id, message: JSON.parse(json) }); } catch { notify({ type: 'warning', message: '鼠标返回无效设备信息' }); }
33
+ try { notify({ type: 'message', id, message: JSON.parse(json) }); } catch { notify({ type: 'warning', message: msg('error.device') }); }
33
34
  });
34
35
  bind('um_register_audio', 'void MouseAudio(const char *id, const void *pcm, int len)', (id, pcm, len) => {
35
- if (len <= 0 || len > 320000 || len % 2) { notify({ type: 'warning', message: '鼠标音频格式无效' }); return; }
36
+ if (len <= 0 || len > 320000 || len % 2) { notify({ type: 'warning', message: msg('error.audio') }); return; }
36
37
  // The SDK buffer expires as soon as this callback returns.
37
38
  const audio = Buffer.from(koffi.decode(pcm, 'uint8_t', len));
38
39
  if (queued > 100) { notify({ type: 'overflow', id }); return; }
@@ -51,7 +52,7 @@ try {
51
52
  await asyncCall(api.init, 0);
52
53
  notify({ type: 'ready', version: library.func('const char *um_sdk_version(void)')() });
53
54
  } catch {
54
- notify({ type: 'fatal', message: '鼠标 SDK 加载失败,请检查系统架构、动态库和运行依赖' });
55
+ notify({ type: 'fatal', message: msg('error.sdk') });
55
56
  process.exitCode = 1; setTimeout(() => process.exit(1), 50);
56
57
  }
57
58
  async function close() {
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { EventEmitter } from 'node:events';
2
3
  import { fork } from 'node:child_process';
3
4
  import { fileURLToPath } from 'node:url';
@@ -10,7 +11,7 @@ export class MouseSdk extends EventEmitter {
10
11
  const target = `${process.platform}-${process.arch}`;
11
12
  const filename = process.platform === 'win32' ? 'uMouseSdk.dll' : 'libuMouseSdk.dylib';
12
13
  const path = this.config.libraryPath ?? fileURLToPath(new URL(`../../native/${target}/${filename}`, import.meta.url));
13
- if (!existsSync(path)) throw new Error(`当前平台 ${target} 缺少鼠标 SDK,请配置匹配的动态库`);
14
+ if (!existsSync(path)) throw new Error(msg('error.sdk'));
14
15
  const child = fork(fileURLToPath(new URL('./native-worker.mjs', import.meta.url)), [path], {
15
16
  stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [],
16
17
  });
@@ -27,7 +28,7 @@ export class MouseSdk extends EventEmitter {
27
28
  finally { diagnosing = false; }
28
29
  };
29
30
  this.starting = new Promise((resolve, reject) => {
30
- const timer = setTimeout(() => { child.kill(); reject(new Error('鼠标 SDK 启动超时')); }, 15000);
31
+ const timer = setTimeout(() => { child.kill(); reject(new Error(msg('error.timeout'))); }, 15000);
31
32
  child.on('message', message => {
32
33
  if (message.type === 'ready') {
33
34
  clearTimeout(timer); resolve(message.version);
@@ -49,23 +50,23 @@ export class MouseSdk extends EventEmitter {
49
50
  clearInterval(this.diagnosticTimer);
50
51
  clearTimeout(timer);
51
52
  if (this.child === child) this.child = undefined;
52
- for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('鼠标 SDK 已停止')); }
53
+ for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error(msg('error.sdk'))); }
53
54
  this.pending.clear();
54
- reject(new Error('鼠标 SDK 未能启动'));
55
- if (!this.stopping) this.emit('fault', '鼠标 SDK 已停止,请重新启用插件');
55
+ reject(new Error(msg('error.sdk')));
56
+ if (!this.stopping) this.emit('fault', msg('error.sdk'));
56
57
  };
57
58
  child.once('exit', failed); child.once('error', failed);
58
59
  });
59
60
  return this.starting;
60
61
  }
61
62
  command(command, fields = {}) {
62
- if (!this.child?.connected) return Promise.reject(new Error('鼠标 SDK 未连接'));
63
+ if (!this.child?.connected) return Promise.reject(new Error(msg('error.sdk')));
63
64
  const requestId = ++this.serial;
64
65
  return new Promise((resolve, reject) => {
65
- const timer = setTimeout(() => { this.pending.delete(requestId); reject(new Error('鼠标指令超时')); }, 3000);
66
+ const timer = setTimeout(() => { this.pending.delete(requestId); reject(new Error(msg('error.timeout'))); }, 3000);
66
67
  this.pending.set(requestId, { resolve, reject, timer });
67
68
  this.child.send({ command, requestId, ...fields }, error => {
68
- if (error) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error('鼠标指令发送失败')); }
69
+ if (error) { clearTimeout(timer); this.pending.delete(requestId); reject(new Error(msg('error.device'))); }
69
70
  });
70
71
  });
71
72
  }
@@ -1,8 +1,9 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  export class AsyncQueue {
2
3
  constructor(limit = 256) { this.limit = limit; this.items = []; this.ended = false; }
3
4
  push(value) {
4
5
  if (this.ended) return false;
5
- if (this.items.length >= this.limit) throw new Error('数据处理过慢,请重新录音');
6
+ if (this.items.length >= this.limit) throw new Error(msg('error.audio'));
6
7
  this.items.push(value); this.wake?.(); return true;
7
8
  }
8
9
  end(clear = false) { if (clear) this.items = []; this.ended = true; this.wake?.(); }
@@ -17,9 +18,9 @@ export class AsyncQueue {
17
18
  export class PcmPackets {
18
19
  constructor(output) { this.output = output; this.tail = Buffer.alloc(0); this.bytes = 0; }
19
20
  write(buffer) {
20
- if (buffer.length % 2) throw new Error('鼠标音频格式无效');
21
+ if (buffer.length % 2) throw new Error(msg('error.audio'));
21
22
  this.bytes += buffer.length;
22
- if (this.bytes > 19_200_000) throw new Error('单次录音最长 10 分钟');
23
+ if (this.bytes > 19_200_000) throw new Error(msg('error.duration'));
23
24
  const bytes = Buffer.concat([this.tail, buffer]);
24
25
  let offset = 0;
25
26
  while (offset + 3200 <= bytes.length) { this.output(bytes.subarray(offset, offset + 3200).toString('base64')); offset += 3200; }
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { sourceRecognitionLanguage, languageKey, REC_LANG_LIST, TRANS_FROM_LANG_LIST, TRANS_TO_LANG_LIST } from '../shared/devices.mjs';
2
3
  import { DEFAULT_LANGUAGES } from '../asr/languages.mjs';
3
4
  export { DEFAULT_LANGUAGES };
@@ -5,16 +6,16 @@ export function recognitionQuery(preferences, action, mappings = DEFAULT_LANGUAG
5
6
  let selected = preferences.recognition;
6
7
  if (action === 'translate') {
7
8
  if (!TRANS_FROM_LANG_LIST.some(item => item.value === preferences.from) || !TRANS_TO_LANG_LIST.some(item => item.value === preferences.to)) {
8
- throw new Error('原翻译语言已不再支持,请在设备设置中重新选择');
9
+ throw new Error(msg('error.language'));
9
10
  }
10
11
  selected = sourceRecognitionLanguage(preferences.from);
11
12
  }
12
- if (!selected || !REC_LANG_LIST.some(item => languageKey(item) === languageKey(selected))) throw new Error('原识别语言已不再支持,请在设备设置中重新选择');
13
+ if (!selected || !REC_LANG_LIST.some(item => languageKey(item) === languageKey(selected))) throw new Error(msg('error.language'));
13
14
  const mapping = selected && mappings.find(item => languageKey(item) === languageKey(selected));
14
- if (!mapping?.query) throw new Error('当前 ASR 尚未配置此语言的接口映射,请选择已支持的语言');
15
+ if (!mapping?.query) throw new Error(msg('error.language'));
15
16
  const query = {};
16
17
  for (const [key, value] of Object.entries(mapping.query)) {
17
- if (!['lid', 'lanid', 'role', 'language', 'accent', 'rlang'].includes(key) || !['string', 'number'].includes(typeof value)) throw new Error('ASR 语言映射配置无效');
18
+ if (!['lid', 'lanid', 'role', 'language', 'accent', 'rlang'].includes(key) || !['string', 'number'].includes(typeof value)) throw new Error(msg('error.language'));
18
19
  query[key] = String(value);
19
20
  }
20
21
  return query;
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { defaultPreferences, preferencesSchema, storedPreferencesSchema, snSchema } from '../shared/devices.mjs';
2
3
  // 保留旧存储键,继续读取重命名前保存的配置。
3
4
  const KEY = 'dsh-asr/devices';
@@ -6,7 +7,7 @@ export class DeviceStore {
6
7
  async state() {
7
8
  let record = await this.credentials.readRecord(KEY);
8
9
  if (!record) record = await this.credentials.modifyRecord(KEY, current => current ?? { kind: 'grant', payload: { version: 1, devices: {} } });
9
- if (record?.kind !== 'grant' || record.payload?.version !== 1 || !record.payload.devices) throw new Error('设备配置无法读取');
10
+ if (record?.kind !== 'grant' || record.payload?.version !== 1 || !record.payload.devices) throw new Error(msg('error.settings'));
10
11
  return structuredClone(record.payload);
11
12
  }
12
13
  async get(sn) {
@@ -35,7 +36,7 @@ export class DeviceStore {
35
36
  await this.credentials.modifyRecord(KEY, record => {
36
37
  const state = structuredClone(record.payload);
37
38
  const saved = state.devices[sn];
38
- if ((saved?.revision ?? 0) !== revision) throw new Error('设备配置已变更,请刷新后重试');
39
+ if ((saved?.revision ?? 0) !== revision) throw new Error(msg('error.settings'));
39
40
  state.devices[sn] = { revision: revision + 1, preferences };
40
41
  return { kind: 'grant', payload: state };
41
42
  });
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { BUILTIN_ASR } from '../asr/config.mjs';
2
3
  import { TRANS_FROM_LANG_LIST, TRANS_TO_LANG_LIST } from '../shared/languages.mjs';
3
4
 
@@ -5,11 +6,11 @@ export const TRANSLATE_URL = BUILTIN_ASR.translateUrl;
5
6
 
6
7
  export async function translateText({ text, from, to, signal, getToken, userId, config = {}, fetchImpl = globalThis.fetch, url = TRANSLATE_URL }) {
7
8
  signal.throwIfAborted();
8
- if (typeof text !== 'string' || !text.trim()) throw new Error('没有可翻译的文本');
9
- if ([...text].length > 5000) throw new Error('翻译文本超过 5000 字符,可复制原文');
10
- if (!TRANS_FROM_LANG_LIST.some(item => item.value === from) || !TRANS_TO_LANG_LIST.some(item => item.value === to)) throw new Error('翻译语言无效,请重新选择');
9
+ if (typeof text !== 'string' || !text.trim()) throw new Error(msg('error.noSpeech'));
10
+ if ([...text].length > 5000) throw new Error(msg('error.translationLength'));
11
+ if (!TRANS_FROM_LANG_LIST.some(item => item.value === from) || !TRANS_TO_LANG_LIST.some(item => item.value === to)) throw new Error(msg('error.language'));
11
12
  const payload = { text, from: from === 'cn' ? 'zh' : from, to: to === 'cn' ? 'zh' : to };
12
- if (payload.from === payload.to) throw new Error('翻译源语言与目标语言不能相同');
13
+ if (payload.from === payload.to) throw new Error(msg('error.sameLanguage'));
13
14
  for (let attempt = 0; attempt < 2; attempt++) {
14
15
  const token = await getToken(signal);
15
16
  signal.throwIfAborted();
@@ -25,20 +26,20 @@ export async function translateText({ text, from, to, signal, getToken, userId,
25
26
  requestSignal.throwIfAborted();
26
27
  } catch {
27
28
  signal.throwIfAborted();
28
- throw new Error('翻译请求失败或响应无效,可复制原文后重试');
29
+ throw new Error(msg('error.translation'));
29
30
  }
30
31
  if (String(body?.code) === '1004') {
31
32
  getToken.invalidate(token);
32
33
  if (attempt === 0) continue;
33
- throw new Error('翻译认证失败,请稍后重试');
34
+ throw new Error(msg('error.auth'));
34
35
  }
35
36
  if (!response.ok || body?.code !== 0) {
36
- const messages = { 1001: '翻译参数错误', 1003: '翻译额度不足', 1005: '翻译请求过于频繁',
37
- 1006: '翻译应用不可用', 1007: '翻译应用已下线', 3005: '翻译请求超时' };
38
- throw new Error((messages[body?.code] ?? '翻译服务调用失败') + ',可复制原文后重试');
37
+ const messages = { 1001: msg('error.translation'), 1003: msg('error.quota'), 1005: msg('error.busy'),
38
+ 1006: msg('error.translation'), 1007: msg('error.translation'), 3005: msg('error.timeout') };
39
+ throw new Error(messages[body?.code] ?? msg('error.translation'));
39
40
  }
40
41
  const result = body.data?.resultText;
41
- if (typeof result !== 'string' || !result.trim() || result.length > 65536) throw new Error('翻译未返回有效译文,可复制原文后重试');
42
+ if (typeof result !== 'string' || !result.trim() || result.length > 65536) throw new Error(msg('error.translation'));
42
43
  signal.throwIfAborted(); return result;
43
44
  }
44
45
  }
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { AsyncQueue } from '../devices/queue.mjs';
3
4
 
@@ -19,7 +20,7 @@ export class AiConversationBridge {
19
20
  } finally {
20
21
  signal.removeEventListener('abort', abort); this.clients.delete(client); client.queue.end(true);
21
22
  for (const [id, session] of this.sessions) {
22
- if (session.client === client) this.release(id, 'AI 对话连接已断开,结果可复制');
23
+ if (session.client === client) this.release(id, msg('error.ai'));
23
24
  }
24
25
  }
25
26
  }
@@ -31,18 +32,18 @@ export class AiConversationBridge {
31
32
  if (!session.client) return;
32
33
  pending.sent = true;
33
34
  try { session.client.queue.push(pending.message); }
34
- catch { pending.reject(new Error('AI 对话连接繁忙,请重试')); }
35
+ catch { pending.reject(new Error(msg('error.ai'))); }
35
36
  }
36
37
  request(sessionId, operation, signal, text, autoSend) {
37
38
  signal.throwIfAborted();
38
- if (this.closed || !this.sessions.has(sessionId)) return Promise.reject(new Error('AI 对话连接不可用'));
39
+ if (this.closed || !this.sessions.has(sessionId)) return Promise.reject(new Error(msg('error.ai')));
39
40
  const requestId = randomUUID();
40
41
  return new Promise((resolve, reject) => {
41
42
  const cleanup = () => { clearTimeout(timer); signal.removeEventListener('abort', abort); this.requests.delete(requestId); };
42
43
  const fail = error => { cleanup(); reject(error); };
43
- const abort = () => fail(new Error('AI 语音会话已取消'));
44
+ const abort = () => fail(new Error(msg('error.ai')));
44
45
  const timer = setTimeout(() => {
45
- fail(new Error('AI 对话未响应,结果可复制'));
46
+ fail(new Error(msg('error.ai')));
46
47
  this.release(sessionId);
47
48
  }, this.timeoutMs);
48
49
  const pending = { message: { requestId, sessionId, operation, expiresAt: Date.now() + this.timeoutMs, ...(text === undefined ? {} : { text, autoSend }) },
@@ -62,10 +63,10 @@ export class AiConversationBridge {
62
63
  const session = pending && this.sessions.get(pending.message.sessionId);
63
64
  if (!pending?.sent || session?.client?.clientId !== clientId) return false;
64
65
  if (ok) pending.resolve();
65
- else pending.reject(new Error('AI 对话无法创建、填充或自动发送,结果可复制'));
66
+ else pending.reject(new Error(msg('error.ai')));
66
67
  return true;
67
68
  }
68
- release(sessionId, message = 'AI 语音会话已结束') {
69
+ release(sessionId, message = msg('error.ai')) {
69
70
  const session = this.sessions.get(sessionId);
70
71
  this.sessions.delete(sessionId);
71
72
  for (const pending of this.requests.values()) {
@@ -1,3 +1,5 @@
1
+ import { HostLocale, attachHostLocale } from './locale.mjs';
2
+ import { message as msg, safeMessage } from '../shared/i18n.mjs';
1
3
  import { TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol';
2
4
  import { ServiceStore } from './store.mjs';
3
5
  import { createTokenProvider } from '../asr/auth.mjs';
@@ -8,6 +10,7 @@ import { DeviceManager } from '../devices/manager.mjs';
8
10
  import { MouseSdk } from '../devices/native.mjs';
9
11
  import { DesktopPresentation } from '../desktop/presentation.mjs';
10
12
  import { ScreenshotService } from '../desktop/screenshot.mjs';
13
+ import { ScreenshotShortcutService } from '../desktop/screenshot-shortcut.mjs';
11
14
  import { pluginConfigSchema } from '../devices/config.mjs';
12
15
  import { AiConversationBridge } from './ai-conversation.mjs';
13
16
 
@@ -28,14 +31,19 @@ export class MouseController extends TypertRemoteService {
28
31
  sdk: dependencies.sdk ?? new MouseSdk(config.native), ...dependencies, aiConversation: this.aiConversation,
29
32
  prepare: () => this.service(), recognize: request => this.recognize(request),
30
33
  translate: request => this.translate(request) });
34
+ this.locale = new HostLocale(locale => this.manager.setLocale(locale));
31
35
  ctx.effect(() => () => {
32
36
  this.lifetime.abort(); this.providers.clear(); return this.manager.close();
33
37
  });
34
38
  }
35
39
  async service() { await this.initialized; return { ...await this.store.resolve(), ...this.dependencies.endpoints }; }
40
+ syncLocale(request) { return this.locale.accept(request); }
36
41
  catalog() { return this.store.catalog(); }
37
42
  devices() { return this.manager.view(); }
38
43
  captureScreenshot() { return this.manager.captureScreenshot(); }
44
+ screenshotShortcut() { return this.manager.screenshotShortcutState(); }
45
+ setScreenshotShortcut(binding) { return this.manager.setScreenshotShortcut(binding); }
46
+ pauseScreenshotShortcut(clientId, paused) { return this.manager.pauseScreenshotShortcut(clientId, paused); }
39
47
  screenshotPermissions(action) { return this.manager.screenshotPermissions(action); }
40
48
  typingPermissions(action) { return this.manager.typingPermissions(action); }
41
49
  saveDevice(sn, revision, preferences) { return this.manager.save(sn, revision, preferences); }
@@ -80,8 +88,8 @@ export class MouseController extends TypertRemoteService {
80
88
  }
81
89
  } catch (error) {
82
90
  if (!signal.aborted && !this.lifetime.signal.aborted) yield { type: 'error',
83
- message: connection.signal.aborted ? 'ASR 连接超时,请稍后重试'
84
- : /^(Token |设备|License |ASR )/.test(error.message) ? error.message : 'ASR 服务暂不可用,请稍后重试' };
91
+ message: connection.signal.aborted ? msg('error.timeout')
92
+ : safeMessage(error.message, 'error.connection') };
85
93
  } finally { clearTimeout(timer); }
86
94
  }
87
95
  async translate({ sn, service: capturedService, ...request }) {
@@ -94,7 +102,9 @@ export class MouseController extends TypertRemoteService {
94
102
  }
95
103
  export async function apply(ctx, config = {}) {
96
104
  ctx.effect(() => ctx.typert.register(TYPERT));
97
- const controller = new MouseController(ctx, config, { desktop: new DesktopPresentation(), screenshot: new ScreenshotService() });
105
+ const controller = new MouseController(ctx, config, { desktop: new DesktopPresentation(), screenshot: new ScreenshotService(),
106
+ shortcut: new ScreenshotShortcutService({ credentials: ctx.credentials }) });
107
+ attachHostLocale(ctx, controller);
98
108
  await controller.initialized;
99
109
  void controller.manager.start();
100
110
  }