@sonicloud/dsh-sonicloud-device 0.1.3 → 0.1.4

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 (52) hide show
  1. package/CHANGELOG.md +16 -1
  2. package/CHANGELOG.zh.md +16 -1
  3. package/README.md +15 -13
  4. package/README.zh.md +2 -0
  5. package/dist/build.json +1 -1
  6. package/dist/client.js +1506 -109
  7. package/docs/contributing/development.md +4 -2
  8. package/docs/specs/ci-cd.md +5 -4
  9. package/docs/specs/multilingual.md +98 -0
  10. package/locale/de.json +7 -0
  11. package/locale/en.json +7 -0
  12. package/locale/es.json +7 -0
  13. package/locale/fr.json +7 -0
  14. package/locale/ja.json +7 -0
  15. package/locale/pt.json +7 -0
  16. package/locale/ru.json +7 -0
  17. package/locale/zh.json +7 -0
  18. package/native/desktop/VOICE_SOURCE.json +2 -2
  19. package/native/desktop/VoicePanel.cs +70 -33
  20. package/native/desktop/VoicePanel.swift +58 -21
  21. package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
  22. package/package.json +5 -3
  23. package/src/asr/auth.mjs +9 -8
  24. package/src/asr/config.mjs +1 -1
  25. package/src/asr/stream.mjs +25 -24
  26. package/src/desktop/presentation.mjs +17 -11
  27. package/src/desktop/screenshot-worker.mjs +33 -32
  28. package/src/desktop/screenshot.mjs +25 -24
  29. package/src/devices/actions.mjs +7 -6
  30. package/src/devices/config.mjs +2 -1
  31. package/src/devices/diagnostics.mjs +4 -3
  32. package/src/devices/manager.mjs +41 -40
  33. package/src/devices/native-worker.mjs +4 -3
  34. package/src/devices/native.mjs +9 -8
  35. package/src/devices/queue.mjs +4 -3
  36. package/src/devices/recognition.mjs +5 -4
  37. package/src/devices/store.mjs +3 -2
  38. package/src/devices/translate.mjs +11 -10
  39. package/src/host/ai-conversation.mjs +8 -7
  40. package/src/host/index.mjs +7 -2
  41. package/src/host/locale.mjs +42 -0
  42. package/src/shared/devices.mjs +13 -12
  43. package/src/shared/i18n.mjs +47 -0
  44. package/src/shared/locales/de.json +155 -0
  45. package/src/shared/locales/en.json +155 -0
  46. package/src/shared/locales/es.json +155 -0
  47. package/src/shared/locales/fr.json +155 -0
  48. package/src/shared/locales/ja.json +155 -0
  49. package/src/shared/locales/pt.json +155 -0
  50. package/src/shared/locales/ru.json +155 -0
  51. package/src/shared/locales/zh.json +155 -0
  52. package/src/shared/remote.mjs +2 -1
@@ -141,7 +141,7 @@ final class WaveformView: NSView {
141
141
  override init(frame frameRect: NSRect) {
142
142
  super.init(frame: frameRect)
143
143
  wantsLayer = true
144
- setAccessibilityElement(true); setAccessibilityLabel("语音处理中")
144
+ setAccessibilityElement(true); setAccessibilityLabel("Processing speech")
145
145
  for bar in bars { bar.backgroundColor = NSColor.systemGreen.cgColor; bar.cornerRadius = 1.5; layer?.addSublayer(bar) }
146
146
  }
147
147
  required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -176,13 +176,37 @@ final class Panel: NSPanel {
176
176
  override var canBecomeKey: Bool { false }
177
177
  override var canBecomeMain: Bool { false }
178
178
  }
179
+ // 文案由插件通过私有 IPC 下发;结果文本始终原样显示。
180
+ final class VoiceLocale {
181
+ static var dictionary: [String: String] = [:]
182
+ static func encode(_ key: String, _ params: [String: Any] = [:]) -> String {
183
+ let data = try! JSONSerialization.data(withJSONObject: ["key": key, "params": params], options: [.sortedKeys])
184
+ return "sonicloud:" + String(data: data, encoding: .utf8)!
185
+ }
186
+ static func text(_ value: String, _ depth: Int = 0) -> String {
187
+ if value.isEmpty { return "" }
188
+ if let text = dictionary[value] { return text }
189
+ if depth < 5 && value.hasPrefix("sonicloud:"), let data = String(value.dropFirst(10)).data(using: .utf8),
190
+ let object = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let key = object["key"] as? String {
191
+ var result = dictionary[key] ?? dictionary["error.generic"] ?? "Operation failed. Please retry."
192
+ for (name, param) in object["params"] as? [String: Any] ?? [:] {
193
+ let raw = String(describing: param)
194
+ let translated = raw.hasPrefix("sonicloud:") || dictionary[raw] != nil ? text(raw, depth + 1) : raw
195
+ result = result.replacingOccurrences(of: "{" + name + "}", with: translated)
196
+ }
197
+ return result
198
+ }
199
+ return dictionary["error.generic"] ?? "Operation failed. Please retry."
200
+ }
201
+ }
179
202
  final class VoiceUI: NSObject {
180
203
  let panel = Panel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
181
204
  let text = NSTextField(labelWithString: "")
182
205
  let waveform = WaveformView(frame: .zero)
183
206
  let closeButton = NSButton(title: "", target: nil, action: nil)
184
- let copyButton = NSButton(title: "复制结果", target: nil, action: nil)
207
+ let copyButton = NSButton(title: "Copy result", target: nil, action: nil)
185
208
  var session = "", preview = "", phase = "connecting", message = ""
209
+ var copyKey = "panel.copy"
186
210
  var active = false
187
211
  var insertion: ClipboardInsertion?
188
212
  var resultPending = false
@@ -200,14 +224,14 @@ final class VoiceUI: NSObject {
200
224
  let content = CapsuleView()
201
225
  panel.contentView = content
202
226
  text.font = .systemFont(ofSize: 15)
203
- text.lineBreakMode = .byTruncatingHead
204
- text.maximumNumberOfLines = 1
205
- text.cell?.usesSingleLineMode = true
206
- text.cell?.wraps = false
227
+ text.lineBreakMode = .byWordWrapping
228
+ text.maximumNumberOfLines = 0
229
+ text.cell?.usesSingleLineMode = false
230
+ text.cell?.wraps = true
207
231
  text.cell?.isScrollable = false
208
- text.setAccessibilityLabel("语音识别结果")
232
+ text.setAccessibilityLabel("Speech recognition result")
209
233
  for view in [waveform, text, closeButton, copyButton] { content.addSubview(view) }
210
- closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "取消")?.withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 14, weight: .medium))
234
+ closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Cancel")?.withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 14, weight: .medium))
211
235
  closeButton.imagePosition = .imageOnly
212
236
  closeButton.isBordered = false
213
237
  closeButton.contentTintColor = .secondaryLabelColor
@@ -219,14 +243,18 @@ final class VoiceUI: NSObject {
219
243
  func position() {
220
244
  let display = NSScreen.screens.first(where: { $0 == screen }) ?? NSScreen.main ?? NSScreen.screens.first
221
245
  guard let frame = display?.visibleFrame else { return }
222
- let width = min(720, max(280, frame.width - 48)), height: CGFloat = 48
246
+ let width = min(720, max(280, frame.width - 48))
247
+ let copyWidth = min(width / 2, max(96, copyButton.intrinsicContentSize.width + 16))
248
+ let available = max(100, width - (copyButton.isHidden ? 110 : copyWidth + 116))
249
+ let bounds = (text.stringValue as NSString).boundingRect(with: NSSize(width: available, height: .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], attributes: [.font: text.font!])
250
+ let height: CGFloat = min(frame.height / 2, max(48, ceil(bounds.height) + 24))
223
251
  panel.setFrame(NSRect(x: frame.midX - width / 2, y: frame.minY + 24, width: width, height: height), display: true)
224
252
  waveform.frame = NSRect(x: 20, y: (height - 26) / 2, width: 23, height: 26)
225
253
  closeButton.frame = NSRect(x: width - 44, y: (height - 28) / 2, width: 28, height: 28)
226
- copyButton.frame = NSRect(x: width - 146, y: (height - 32) / 2, width: 96, height: 32)
254
+ copyButton.frame = NSRect(x: width - 50 - copyWidth, y: (height - 32) / 2, width: copyWidth, height: 32)
227
255
  let left: CGFloat = active ? 54 : 22
228
256
  let right = copyButton.isHidden ? closeButton.frame.minX : copyButton.frame.minX
229
- let textHeight = ceil(text.intrinsicContentSize.height)
257
+ let textHeight = height - 24
230
258
  text.frame = NSRect(x: left, y: (height - textHeight) / 2, width: max(0, right - left - 12), height: textHeight)
231
259
  panel.contentView?.needsDisplay = true
232
260
  panel.invalidateShadow()
@@ -234,10 +262,14 @@ final class VoiceUI: NSObject {
234
262
  func render() {
235
263
  waveform.isHidden = !active
236
264
  waveform.animate(active)
237
- closeButton.setAccessibilityLabel(active ? "取消" : "关闭")
238
- closeButton.toolTip = active ? "取消" : "关闭"
265
+ panel.setAccessibilityLabel(VoiceLocale.text("panel.title"))
266
+ text.setAccessibilityLabel(VoiceLocale.text("panel.result"))
267
+ waveform.setAccessibilityLabel(VoiceLocale.text("panel.processing"))
268
+ copyButton.title = VoiceLocale.text(copyKey)
269
+ closeButton.setAccessibilityLabel(VoiceLocale.text(active ? "panel.cancel" : "panel.close"))
270
+ closeButton.toolTip = VoiceLocale.text(active ? "panel.cancel" : "panel.close")
239
271
  copyButton.isHidden = active || preview.isEmpty
240
- let status = message.isEmpty ? (["finishing": "正在整理…", "translating": "正在翻译…"][phase] ?? "") : message
272
+ let status = message.isEmpty ? VoiceLocale.text(["finishing": "panel.finishing", "translating": "panel.translating"][phase] ?? "") : VoiceLocale.text(message)
241
273
  let fullText = [status, preview].filter { !$0.isEmpty }.joined(separator: " ")
242
274
  text.stringValue = fullText.components(separatedBy: .newlines).joined(separator: " ").replacingOccurrences(of: "\t", with: " ")
243
275
  text.toolTip = fullText
@@ -251,14 +283,14 @@ final class VoiceUI: NSObject {
251
283
  @objc func copyResult() {
252
284
  NSPasteboard.general.clearContents()
253
285
  NSPasteboard.general.setString(preview, forType: .string)
254
- copyButton.title = "已复制"
286
+ copyKey = "panel.copied"; render()
255
287
  }
256
288
  func finishInsertion(_ inserted: Bool, changed: Bool) {
257
289
  insertion = nil; active = false; resultPending = false
258
290
  if inserted { preview = ""; message = ""; hide() }
259
291
  else {
260
- message = !AXIsProcessTrusted() ? "请授权辅助功能以回填;可复制结果"
261
- : changed ? "输入目标已变化或不支持写入,可复制结果" : "此输入框不支持自动回填,可复制结果"
292
+ message = !AXIsProcessTrusted() ? "panel.permission"
293
+ : changed ? "panel.targetChanged" : "panel.targetChanged"
262
294
  render()
263
295
  }
264
296
  }
@@ -268,15 +300,20 @@ final class VoiceUI: NSObject {
268
300
  }
269
301
  func handle(_ command: [String: Any]) {
270
302
  let name = command["command"] as? String ?? ""
303
+ if name == "locale" {
304
+ if let dictionary = command["dictionary"] as? [String: String] { VoiceLocale.dictionary = dictionary }
305
+ if panel.isVisible { render() }
306
+ return
307
+ }
271
308
  if name == "permissions" {
272
309
  let action = command["action"] as? String ?? "check"
273
310
  guard ["check", "refresh", "accessibility"].contains(action) else {
274
- if let id = command["id"] { emit(["id": id, "ok": false, "message": "不支持此打字权限操作"]) }
311
+ if let id = command["id"] { emit(["id": id, "ok": false, "message": VoiceLocale.encode("error.permission")]) }
275
312
  return
276
313
  }
277
314
  if action == "accessibility" {
278
315
  guard !active && !resultPending else {
279
- if let id = command["id"] { emit(["id": id, "ok": false, "message": "请先结束语音输入,再设置打字权限"]) }
316
+ if let id = command["id"] { emit(["id": id, "ok": false, "message": VoiceLocale.encode("error.busy")]) }
280
317
  return
281
318
  }
282
319
  if !AXIsProcessTrusted() {
@@ -303,7 +340,7 @@ final class VoiceUI: NSObject {
303
340
  screen = NSScreen.screens.first(where: { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) })
304
341
  insertion = ["speechSearch", "ai_input"].contains(command["action"] as? String ?? "") ? nil : ClipboardInsertion()
305
342
  resultPending = false
306
- copyButton.title = "复制结果"; render()
343
+ copyKey = "panel.copy"; render()
307
344
  } else if !incoming.isEmpty && incoming != session { success = false }
308
345
  else if name == "result" && active && !resultPending {
309
346
  preview = command["text"] as? String ?? ""
@@ -322,7 +359,7 @@ final class VoiceUI: NSObject {
322
359
  switch command["type"] as? String {
323
360
  case "preview": if active { preview = command["text"] as? String ?? ""; render() }
324
361
  case "phase": if active { phase = command["phase"] as? String ?? phase; render() }
325
- case "failed": active = false; insertion = nil; message = command["message"] as? String ?? "语音处理失败"; render()
362
+ case "failed": active = false; insertion = nil; message = command["message"] as? String ?? "error.generic"; render()
326
363
  case "notice": message = command["message"] as? String ?? ""; render()
327
364
  case "finished", "cancelled": active = false; insertion = nil; preview = ""; message = ""; hide()
328
365
  default: break
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sonicloud/dsh-sonicloud-device",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "DeepSeek Harness 智能鼠标、多设备设置与共享语音服务",
5
5
  "icon": "./src/client/assets/sonicloud.png",
6
6
  "type": "module",
@@ -8,7 +8,8 @@
8
8
  "exports": {
9
9
  ".": "./src/host/index.mjs",
10
10
  "./client": "./dist/client.js",
11
- "./package.json": "./package.json"
11
+ "./package.json": "./package.json",
12
+ "./locale/*.json": "./locale/*.json"
12
13
  },
13
14
  "files": [
14
15
  "src/asr",
@@ -24,7 +25,8 @@
24
25
  "native",
25
26
  "docs",
26
27
  "CHANGELOG.md",
27
- "CHANGELOG.zh.md"
28
+ "CHANGELOG.zh.md",
29
+ "locale"
28
30
  ],
29
31
  "dsh": {
30
32
  "bundle": {
package/src/asr/auth.mjs CHANGED
@@ -1,8 +1,9 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import { BUILTIN_ASR } from './config.mjs';
2
3
  import { isStableSn } from '../shared/devices.mjs';
3
4
 
4
5
  export function createTokenRequest({ sn }) {
5
- if (!isStableSn(sn)) throw new Error('设备身份未确认,请重新连接鼠标');
6
+ if (!isStableSn(sn)) throw new Error(msg('error.device'));
6
7
  return { sn };
7
8
  }
8
9
 
@@ -26,24 +27,24 @@ export function createTokenProvider(config, fetchImpl = globalThis.fetch, lifeti
26
27
  });
27
28
  payload = await response.json();
28
29
  } catch (error) {
29
- if (signal.aborted && !entry.abort.signal.aborted && !lifetime?.aborted) throw new Error('Token 获取超时,请稍后重试');
30
+ if (signal.aborted && !entry.abort.signal.aborted && !lifetime?.aborted) throw new Error(msg('error.timeout'));
30
31
  signal.throwIfAborted();
31
32
  if (!isStableSn(service.sn)) throw error;
32
- throw new Error('Token 获取失败,请检查网络后重试');
33
+ throw new Error(msg('error.auth'));
33
34
  }
34
35
  signal.throwIfAborted();
35
36
  if (!response.ok || payload?.code !== 0) {
36
37
  const messages = {
37
- 4001: '设备身份无效,请重新连接鼠标', 1001: '设备鉴权参数错误,请联系服务方',
38
- 1002: '设备鉴权失败,请联系服务方', 1008: 'License 设备数量已达上限',
38
+ 4001: msg('error.device'), 1001: msg('error.auth'),
39
+ 1002: msg('error.auth'), 1008: msg('error.deviceLimit'),
39
40
  };
40
- throw new Error(messages[payload?.code] ?? 'Token 获取失败,请稍后重试');
41
+ throw new Error(messages[payload?.code] ?? msg('error.auth'));
41
42
  }
42
43
  const { token, expire_time: expiry } = payload.data ?? {};
43
44
  if (typeof token !== 'string' || !token.trim() || !Number.isSafeInteger(expiry) || expiry <= Date.now() / 1000) {
44
- throw new Error('Token 响应无效或已过期,请稍后重试');
45
+ throw new Error(msg('error.auth'));
45
46
  }
46
- if (entry.generation !== generation) throw new Error('Token 请求已失效');
47
+ if (entry.generation !== generation) throw new Error(msg('error.auth'));
47
48
  cachedToken = token; expiresAt = expiry * 1000;
48
49
  return token;
49
50
  }
@@ -1,5 +1,5 @@
1
1
  export const BUILTIN_ASR = Object.freeze({
2
- name: '声云 ASR',
2
+ name: 'Sonicloud ASR',
3
3
  streamUrl: 'wss://openapi.sinicloud.com/talentStreamAsr',
4
4
  tokenUrl: 'https://dsh_device.sonicrhino.cc/api/open.sign/generate',
5
5
  translateUrl: 'https://openapi.sinicloud.com/v1/translate/text',
@@ -1,3 +1,4 @@
1
+ import { message as msg } from '../shared/i18n.mjs';
1
2
  import WebSocket from 'ws';
2
3
 
3
4
  class Queue {
@@ -5,7 +6,7 @@ class Queue {
5
6
  ended = false;
6
7
  push(item) {
7
8
  if (this.ended) return;
8
- if (this.items.length >= 256) { this.items = [{ type: 'error', message: '识别结果接收过慢,请重新录音' }]; this.end(); return; }
9
+ if (this.items.length >= 256) { this.items = [{ type: 'error', message: msg('error.audio') }]; this.end(); return; }
9
10
  this.items.push(item); this.wake?.();
10
11
  }
11
12
  end() { this.ended = true; this.wake?.(); }
@@ -19,12 +20,12 @@ class Queue {
19
20
  }
20
21
 
21
22
  const errors = {
22
- '4010': 'Token 认证失败,请稍后重试',
23
- '4011': 'ASR 额度不足,请充值后重试',
24
- '4012': 'ASR 应用不存在、未认证或已下线',
25
- '4013': 'ASR 并发连接已达上限,请稍后重试',
26
- '4014': 'License 设备未注册', '4015': 'License 设备已被其他会话占用',
27
- '-1': '语音太短,请重新录音', '16': '未识别到语音',
23
+ '4010': msg('error.auth'),
24
+ '4011': msg('error.quota'),
25
+ '4012': msg('error.auth'),
26
+ '4013': msg('error.busy'),
27
+ '4014': msg('error.auth'), '4015': msg('error.busy'),
28
+ '-1': msg('error.noSpeech'), '16': msg('error.noSpeech'),
28
29
  };
29
30
 
30
31
  // The live service also uses numeric strings and code 3 interim / code 10 final frames.
@@ -56,16 +57,16 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
56
57
  socket.terminate();
57
58
  };
58
59
  const arm = (delay, message) => { clearTimeout(timer); timer = setTimeout(() => fail(message), delay); };
59
- connectTimer = setTimeout(() => fail('ASR 连接超时,请检查网络后重试'), connectTimeout);
60
+ connectTimer = setTimeout(() => fail(msg('error.timeout')), connectTimeout);
60
61
  const abort = () => { queue.end(); settleReady(false); socket.terminate(); };
61
62
  signal.addEventListener('abort', abort, { once: true });
62
63
  if (signal.aborted) abort();
63
- socket.on('error', () => fail('ASR 连接失败,请检查服务地址与网络'));
64
+ socket.on('error', () => fail(msg('error.connection')));
64
65
  const transcript = (message, forcedFinal) => {
65
66
  const begin = timestamp(message.Begin), end = timestamp(message.End);
66
67
  if (!ready || complete || typeof message.result !== 'string' || message.result.length > 4096 ||
67
68
  begin === undefined || end === undefined || (end > 0 && end < begin)) {
68
- fail('ASR 返回了无效识别结果'); return false;
69
+ fail(msg('error.connection')); return false;
69
70
  }
70
71
  queue.push({ type: 'transcript', text: message.result, begin, end, final: forcedFinal ?? end > 0 });
71
72
  return true;
@@ -73,20 +74,20 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
73
74
  socket.on('message', data => {
74
75
  if (queue.ended) return;
75
76
  let message;
76
- try { message = JSON.parse(data.toString()); } catch { fail('ASR 返回了无效数据'); return; }
77
+ try { message = JSON.parse(data.toString()); } catch { fail(msg('error.connection')); return; }
77
78
  const code = String(message?.errCode);
78
79
  if (code === '1000') {
79
80
  if (ready) return;
80
81
  ready = true; clearTimeout(connectTimer);
81
- arm(idleTimeout, '录音数据中断,请重新录音'); queue.push({ type: 'ready' });
82
+ arm(idleTimeout, msg('error.audio')); queue.push({ type: 'ready' });
82
83
  settleReady(true);
83
- } else if (code === '1001') queue.push({ type: 'warning', message: 'ASR 余额较低,请及时充值' });
84
+ } else if (code === '1001') queue.push({ type: 'warning', message: msg('warning.lowBalance') });
84
85
  else if (code === '0') transcript(message);
85
86
  else if (code === '3') {
86
87
  // End can be nonzero on live rolling results; code 3 is never a final sentence.
87
88
  if (Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) transcript(message, false);
88
89
  } else if (code === '10') {
89
- if (!ended) { fail('ASR 服务提前结束了录音'); return; }
90
+ if (!ended) { fail(msg('error.connection')); return; }
90
91
  // Older responses send the final sentence separately with code 0. Newer ones
91
92
  // include it in code 10. Do not treat an untimed status message as transcript.
92
93
  if ((Object.hasOwn(message, 'Begin') || Object.hasOwn(message, 'End')) && !transcript(message, true)) return;
@@ -96,12 +97,12 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
96
97
  }
97
98
  else {
98
99
  if (code === '4010') onAuthFailure();
99
- fail(errors[code] ?? (code.startsWith('400') ? 'ASR 连接参数无效,请检查配置' : 'ASR 识别失败,请稍后重试'), code);
100
+ fail(errors[code] ?? msg('error.connection'), code);
100
101
  }
101
102
  });
102
103
  socket.on('close', () => {
103
104
  if (queue.ended) return;
104
- fail('ASR 连接中断,识别结果未完成');
105
+ fail(msg('error.connection'));
105
106
  });
106
107
  const input = uplink[Symbol.asyncIterator]();
107
108
  const upload = async () => {
@@ -114,21 +115,21 @@ export async function* streamRecognition({ service, token, uplink, signal, onAut
114
115
  if (queue.ended || signal.aborted) return;
115
116
  if (done) {
116
117
  ended = true;
117
- arm(finalTimeout, '最终识别结果超时,可复制已有预览后重试');
118
+ arm(finalTimeout, msg('error.timeout'));
118
119
  queue.push({ type: 'finishing' });
119
120
  socket.send('end'); return;
120
121
  }
121
- if (typeof value !== 'string' || value.length > 4400) throw new Error('音频包无效');
122
+ if (typeof value !== 'string' || value.length > 4400) throw new Error(msg('error.audio'));
122
123
  const bytes = Buffer.from(value, 'base64');
123
- if (bytes.toString('base64') !== value || bytes.length <= 80 || bytes.length > 3200 || bytes.length % 2) throw new Error('音频包无效');
124
+ if (bytes.toString('base64') !== value || bytes.length <= 80 || bytes.length > 3200 || bytes.length % 2) throw new Error(msg('error.audio'));
124
125
  totalBytes += bytes.length;
125
- if (totalBytes > 16_000 * 2 * 600) throw new Error('单次录音最长 10 分钟');
126
- if (socket.bufferedAmount > 320_000) throw new Error('网络发送过慢,请重新录音');
127
- socket.send(bytes); arm(idleTimeout, '录音数据中断,请重新录音');
126
+ if (totalBytes > 16_000 * 2 * 600) throw new Error(msg('error.duration'));
127
+ if (socket.bufferedAmount > 320_000) throw new Error(msg('error.generic'));
128
+ socket.send(bytes); arm(idleTimeout, msg('error.audio'));
128
129
  }
129
130
  } catch (error) {
130
- if (!signal.aborted) fail(error.message === '音频包无效' || error.message === '单次录音最长 10 分钟' || error.message === '网络发送过慢,请重新录音'
131
- ? error.message : '音频上传中断,请重新录音');
131
+ if (!signal.aborted) fail(error.message === msg('error.audio') || error.message === msg('error.duration') || error.message === msg('error.generic')
132
+ ? error.message : msg('error.audio'));
132
133
  }
133
134
  };
134
135
  void upload();
@@ -1,3 +1,4 @@
1
+ import { message as msg, nativeDictionary, resolveLocale, safeMessage } from '../shared/i18n.mjs';
1
2
  import { spawn } from 'node:child_process';
2
3
  import { createInterface } from 'node:readline';
3
4
  import { fileURLToPath } from 'node:url';
@@ -7,10 +8,10 @@ import { chmodSync, existsSync } from 'node:fs';
7
8
  export class DesktopPresentation {
8
9
  constructor({ platform = process.platform, arch = process.arch, launch = spawn, timeoutMs = 10000 } = {}) {
9
10
  Object.assign(this, { platform, arch, launch, timeoutMs });
10
- this.requests = new Map(); this.sequence = 0;
11
+ this.requests = new Map(); this.sequence = 0; this.locale = 'en';
11
12
  }
12
13
  start() {
13
- if (this.closed) throw new Error('桌面语音浮层已关闭');
14
+ if (this.closed) throw new Error(msg('error.closed'));
14
15
  if (this.child) return;
15
16
  const root = new URL('../../native/desktop/', import.meta.url);
16
17
  let file, args = [];
@@ -21,7 +22,7 @@ export class DesktopPresentation {
21
22
  }
22
23
  else if (this.platform === 'win32') {
23
24
  file = 'powershell.exe'; args = ['-NoProfile', '-NonInteractive', '-STA', '-ExecutionPolicy', 'Bypass', '-File', fileURLToPath(new URL('windows.ps1', root))];
24
- } else throw new Error('当前平台不支持桌面语音浮层');
25
+ } else throw new Error(msg('error.panel'));
25
26
  const child = this.launch(file, args, { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
26
27
  this.child = child;
27
28
  const lines = createInterface({ input: child.stdout });
@@ -33,19 +34,24 @@ export class DesktopPresentation {
33
34
  if (pending) {
34
35
  clearTimeout(pending.timer); this.requests.delete(message.id);
35
36
  if (message.ok) pending.resolve(message.value);
36
- else pending.reject(new Error(message.message || '桌面语音浮层操作失败'));
37
+ else pending.reject(new Error(message.message || msg('error.panel')));
37
38
  }
38
39
  });
39
40
  const failed = () => {
40
41
  if (this.child !== child) return;
41
42
  this.child = undefined; lines.close();
42
- for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('桌面语音浮层不可用,请检查安装并重试')); }
43
+ for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.panel'))); }
43
44
  this.requests.clear();
44
45
  if (!this.closed) this.onFault?.();
45
46
  };
46
47
  child.once('error', failed); child.once('exit', failed);
47
48
  child.stdin.on('error', failed);
48
49
  child.stderr.resume();
50
+ this.setLocale(this.locale);
51
+ }
52
+ setLocale(locale) {
53
+ this.locale = resolveLocale(locale);
54
+ this.send({ command: 'locale', language: this.locale, dictionary: nativeDictionary(this.locale) });
49
55
  }
50
56
  send(message) {
51
57
  if (!this.child || this.closed) return;
@@ -56,7 +62,7 @@ export class DesktopPresentation {
56
62
  const id = ++this.sequence;
57
63
  return new Promise((resolve, reject) => {
58
64
  const timer = setTimeout(() => {
59
- this.requests.delete(id); reject(new Error('桌面语音浮层响应超时,请重试'));
65
+ this.requests.delete(id); reject(new Error(msg('error.timeout')));
60
66
  if (killOnTimeout) this.child?.kill();
61
67
  }, this.timeoutMs);
62
68
  this.requests.set(id, { resolve, reject, timer }); this.send({ ...message, id });
@@ -67,12 +73,12 @@ export class DesktopPresentation {
67
73
  await this.request({ command: 'begin', sessionId: run.id, action: run.action });
68
74
  }
69
75
  async permissions(action = 'check') {
70
- if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error('不支持此打字权限操作');
71
- if (this.closed) throw new Error('桌面语音浮层已关闭');
76
+ if (!['check', 'accessibility', 'refresh'].includes(action)) throw new Error(msg('error.permission'));
77
+ if (this.closed) throw new Error(msg('error.closed'));
72
78
  if (this.platform !== 'darwin') return { supported: false, accessibility: true, helperApp: '' };
73
79
  const value = await this.request({ command: 'permissions', action }, { killOnTimeout: false });
74
80
  if (!value || value.supported !== true || typeof value.accessibility !== 'boolean' || typeof value.helperApp !== 'string')
75
- throw new Error('打字权限状态不可用,请更新插件后重试');
81
+ throw new Error(msg('error.permission'));
76
82
  return value;
77
83
  }
78
84
  event(event) {
@@ -80,14 +86,14 @@ export class DesktopPresentation {
80
86
  if (event.sessionId && event.sessionId !== this.sessionId) return;
81
87
  // Do not launch a native window for background device discovery messages.
82
88
  if (!this.child) return;
83
- this.send({ command: 'event', ...event });
89
+ this.send({ command: 'event', ...event, ...(event.message ? { message: safeMessage(event.message) } : {}) });
84
90
  }
85
91
  async complete(run, text) {
86
92
  return this.request({ command: 'result', sessionId: run.id, text });
87
93
  }
88
94
  async close() {
89
95
  this.closed = true;
90
- for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error('桌面语音浮层已关闭')); }
96
+ for (const { reject, timer } of this.requests.values()) { clearTimeout(timer); reject(new Error(msg('error.closed'))); }
91
97
  this.requests.clear();
92
98
  const child = this.child; this.child = undefined;
93
99
  if (child) await new Promise(resolve => {