@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.
- package/CHANGELOG.md +16 -1
- package/CHANGELOG.zh.md +16 -1
- package/README.md +15 -13
- package/README.zh.md +2 -0
- package/dist/build.json +1 -1
- package/dist/client.js +1506 -109
- package/docs/contributing/development.md +4 -2
- package/docs/specs/ci-cd.md +5 -4
- package/docs/specs/multilingual.md +98 -0
- package/locale/de.json +7 -0
- package/locale/en.json +7 -0
- package/locale/es.json +7 -0
- package/locale/fr.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/pt.json +7 -0
- package/locale/ru.json +7 -0
- package/locale/zh.json +7 -0
- package/native/desktop/VOICE_SOURCE.json +2 -2
- package/native/desktop/VoicePanel.cs +70 -33
- package/native/desktop/VoicePanel.swift +58 -21
- package/native/desktop/darwin-arm64/Sonicloud Voice.app/Contents/MacOS/sonicloud-voice +0 -0
- package/package.json +5 -3
- package/src/asr/auth.mjs +9 -8
- package/src/asr/config.mjs +1 -1
- package/src/asr/stream.mjs +25 -24
- package/src/desktop/presentation.mjs +17 -11
- package/src/desktop/screenshot-worker.mjs +33 -32
- package/src/desktop/screenshot.mjs +25 -24
- package/src/devices/actions.mjs +7 -6
- package/src/devices/config.mjs +2 -1
- package/src/devices/diagnostics.mjs +4 -3
- package/src/devices/manager.mjs +41 -40
- package/src/devices/native-worker.mjs +4 -3
- package/src/devices/native.mjs +9 -8
- package/src/devices/queue.mjs +4 -3
- package/src/devices/recognition.mjs +5 -4
- package/src/devices/store.mjs +3 -2
- package/src/devices/translate.mjs +11 -10
- package/src/host/ai-conversation.mjs +8 -7
- package/src/host/index.mjs +7 -2
- package/src/host/locale.mjs +42 -0
- package/src/shared/devices.mjs +13 -12
- package/src/shared/i18n.mjs +47 -0
- package/src/shared/locales/de.json +155 -0
- package/src/shared/locales/en.json +155 -0
- package/src/shared/locales/es.json +155 -0
- package/src/shared/locales/fr.json +155 -0
- package/src/shared/locales/ja.json +155 -0
- package/src/shared/locales/pt.json +155 -0
- package/src/shared/locales/ru.json +155 -0
- package/src/shared/locales/zh.json +155 -0
- package/src/shared/remote.mjs +2 -1
package/src/devices/manager.mjs
CHANGED
|
@@ -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';
|
|
@@ -14,14 +15,14 @@ export class DeviceManager {
|
|
|
14
15
|
Object.assign(this, { sdk, recognize, prepare, action, translate, desktop, screenshot, 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 = '
|
|
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,7 +30,7 @@ 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);
|
|
@@ -39,7 +40,7 @@ export class DeviceManager {
|
|
|
39
40
|
if (this.started) return this.started;
|
|
40
41
|
this.started = (async () => {
|
|
41
42
|
try { this.desktop?.start?.(); } catch { /* Key press reports unsupported native presentation. */ }
|
|
42
|
-
try { await this.sdk.start(); this.status = this.devices.size ? '
|
|
43
|
+
try { await this.sdk.start(); this.status = this.devices.size ? msg('status.connected') : msg('status.searching'); }
|
|
43
44
|
catch (error) { this.status = error.message; }
|
|
44
45
|
this.snapshot();
|
|
45
46
|
})();
|
|
@@ -61,7 +62,7 @@ export class DeviceManager {
|
|
|
61
62
|
}
|
|
62
63
|
snapshot() { this.publish({ type: 'devices', ...this.view() }); }
|
|
63
64
|
async *watch(clientId, signal) {
|
|
64
|
-
if (!this.desktop && this.owner) { yield { type: 'notice', message: '
|
|
65
|
+
if (!this.desktop && this.owner) { yield { type: 'notice', message: msg('error.busy') }; return; }
|
|
65
66
|
const queue = new AsyncQueue(256); if (!this.desktop) this.owner = clientId; this.clients.add(queue);
|
|
66
67
|
const abort = () => queue.end(true);
|
|
67
68
|
signal.addEventListener('abort', abort, { once: true });
|
|
@@ -80,7 +81,7 @@ export class DeviceManager {
|
|
|
80
81
|
case 'connected': return this.connectDevice(event);
|
|
81
82
|
case 'disconnected': return this.disconnectDevice(event);
|
|
82
83
|
case 'message': return this.deviceMessage(event);
|
|
83
|
-
case 'overflow': return this.cancelFor(event.id, '
|
|
84
|
+
case 'overflow': return this.cancelFor(event.id, msg('error.audio'));
|
|
84
85
|
case 'warning': return this.publish({ type: 'notice', message: event.message });
|
|
85
86
|
case 'diagnostic':
|
|
86
87
|
if (!this.devices.size) { this.status = event.message; this.snapshot(); }
|
|
@@ -92,26 +93,26 @@ export class DeviceManager {
|
|
|
92
93
|
const stable = isStableSn(id);
|
|
93
94
|
const category = event.deviceType ?? 'smart-mouse';
|
|
94
95
|
const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
|
|
95
|
-
const device = { id, sn: stable ? id : '', type: category, name: event.name ||
|
|
96
|
+
const device = { id, sn: stable ? id : '', type: category, name: event.name || '', defaultName: !event.name,
|
|
96
97
|
connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
|
|
97
98
|
identityConfirmed: stable, dpiState: 'unknown', ...saved };
|
|
98
99
|
this.devices.set(id, device);
|
|
99
100
|
this.clearPressed(id);
|
|
100
|
-
this.status = '
|
|
101
|
+
this.status = msg('status.connected');
|
|
101
102
|
if (saved?.revision > 0) await this.applyDpi(device);
|
|
102
103
|
this.snapshot();
|
|
103
104
|
}
|
|
104
105
|
disconnectDevice({ id, mode }) {
|
|
105
106
|
const device = this.devices.get(id);
|
|
106
107
|
if (!device || device.connection !== (mode === 1 ? 'ble' : 'usb')) return;
|
|
107
|
-
this.cancelFor(id, '
|
|
108
|
-
if (!this.devices.size) this.status = '
|
|
108
|
+
this.cancelFor(id, msg('error.device')); this.devices.delete(id); this.clearPressed(id);
|
|
109
|
+
if (!this.devices.size) this.status = msg('status.searching');
|
|
109
110
|
this.snapshot();
|
|
110
111
|
}
|
|
111
112
|
async deviceMessage({ id, message }) {
|
|
112
113
|
const device = this.devices.get(id);
|
|
113
|
-
if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '
|
|
114
|
-
if (message.type === 'queueOverflow') { this.cancel(undefined, '
|
|
114
|
+
if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || msg('error.device') }); return; }
|
|
115
|
+
if (message.type === 'queueOverflow') { this.cancel(undefined, msg('error.audio')); return; }
|
|
115
116
|
if (!device) return;
|
|
116
117
|
switch (message.type) {
|
|
117
118
|
case 'deviceInfo': return this.updateDeviceInfo(device, message);
|
|
@@ -123,7 +124,7 @@ export class DeviceManager {
|
|
|
123
124
|
if (isStableSn(message.sn) && message.sn !== device.sn) {
|
|
124
125
|
// 只补全临时身份,不合并已确认的设备。
|
|
125
126
|
if (device.identityConfirmed || this.devices.has(message.sn)) {
|
|
126
|
-
device.identityConfirmed = false; this.cancelFor(device.id, '
|
|
127
|
+
device.identityConfirmed = false; this.cancelFor(device.id, msg('error.device'));
|
|
127
128
|
} else {
|
|
128
129
|
this.devices.delete(device.id); device.sn = message.sn; device.identityConfirmed = true;
|
|
129
130
|
if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn));
|
|
@@ -153,31 +154,31 @@ export class DeviceManager {
|
|
|
153
154
|
}
|
|
154
155
|
async savePreferences(sn, revision, preferences) {
|
|
155
156
|
const device = [...this.devices.values()].find(item => item.sn === sn && item.identityConfirmed);
|
|
156
|
-
if (!device || device.type !== 'smart-mouse') throw new Error('
|
|
157
|
+
if (!device || device.type !== 'smart-mouse') throw new Error(msg('error.settings'));
|
|
157
158
|
const connectionId = device.connectionId;
|
|
158
159
|
const dpiChanged = preferences.dpi !== device.preferences.dpi || device.dpiState === 'failed';
|
|
159
160
|
const saved = await this.store.save(sn, revision, preferences);
|
|
160
|
-
if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: '
|
|
161
|
+
if (this.devices.get(device.id)?.connectionId !== connectionId) { this.snapshot(); return { ...saved, message: msg('settings.savedOffline') }; }
|
|
161
162
|
Object.assign(device, saved);
|
|
162
|
-
let message = '
|
|
163
|
+
let message = msg('settings.saved');
|
|
163
164
|
if (dpiChanged) {
|
|
164
|
-
message = '
|
|
165
|
+
message = msg('settings.savedDpi', { reason: await this.applyDpi(device) });
|
|
165
166
|
}
|
|
166
167
|
this.snapshot(); return { ...saved, message };
|
|
167
168
|
}
|
|
168
169
|
async applyDpi(device) {
|
|
169
170
|
const level = this.dpiLevels[device.preferences.dpi];
|
|
170
171
|
try {
|
|
171
|
-
if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error('
|
|
172
|
-
if (await this.sdk.dpi(device.id, level) !== 1) throw new Error('
|
|
173
|
-
device.dpiState = 'sent'; return '
|
|
172
|
+
if (!Number.isInteger(level) || level < 0 || level > 255) throw new Error(msg('keys.dpiFailed'));
|
|
173
|
+
if (await this.sdk.dpi(device.id, level) !== 1) throw new Error(msg('keys.dpiFailed'));
|
|
174
|
+
device.dpiState = 'sent'; return msg('settings.dpiSent');
|
|
174
175
|
} catch (error) { device.dpiState = 'failed'; return error.message; }
|
|
175
176
|
}
|
|
176
177
|
async key(device, event) {
|
|
177
178
|
if (this.disposed || device.type !== 'smart-mouse') return;
|
|
178
179
|
if (event.key !== 'capture' && !this.owner && !this.desktop) return;
|
|
179
180
|
if (!device.identityConfirmed) {
|
|
180
|
-
if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: '
|
|
181
|
+
if (event.action === 'down' || event.action === 'click') this.publish({ type: 'notice', message: msg('error.device') });
|
|
181
182
|
return;
|
|
182
183
|
}
|
|
183
184
|
const key = `${device.id}:${event.key}:${event.index ?? 0}`;
|
|
@@ -208,7 +209,7 @@ export class DeviceManager {
|
|
|
208
209
|
this.pressed.set(key, structuredClone(device.preferences));
|
|
209
210
|
const action = event.key === 'ai' ? 'ai_input' : event.key === 'm' ? device.preferences.mAction : event.key === 'translation' ? 'translate' : device.preferences.speechAction;
|
|
210
211
|
if (!VOICE.has(action)) return;
|
|
211
|
-
if (this.run) { this.publish({ type: 'notice', message: '
|
|
212
|
+
if (this.run) { this.publish({ type: 'notice', message: msg('error.busy') }); return; }
|
|
212
213
|
let query;
|
|
213
214
|
try {
|
|
214
215
|
query = recognitionQuery(device.preferences, action, this.languages);
|
|
@@ -220,30 +221,30 @@ export class DeviceManager {
|
|
|
220
221
|
};
|
|
221
222
|
run.packets = new PcmPackets(chunk => run.queue.push(chunk));
|
|
222
223
|
this.run = run;
|
|
223
|
-
if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, '
|
|
224
|
+
if (!this.desktop) run.captureTimer = setTimeout(() => this.fail(run, msg('error.connection')), 5000);
|
|
224
225
|
run.durationTimer = setTimeout(() => this.release(run), 600000);
|
|
225
226
|
// Opening the app/client must not block key-up or device-disconnect events.
|
|
226
227
|
if (action === 'ai_input') void this.begin(run, device);
|
|
227
228
|
else await this.begin(run, device);
|
|
228
229
|
}
|
|
229
230
|
async captureScreenshot(trigger = 'ui') {
|
|
230
|
-
if (this.disposed) throw new Error('
|
|
231
|
-
if (!this.screenshot) throw new Error('
|
|
231
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
232
|
+
if (!this.screenshot) throw new Error(msg('error.screenshot'));
|
|
232
233
|
return this.screenshot.capture(trigger);
|
|
233
234
|
}
|
|
234
235
|
async screenshotPermissions(action = 'check') {
|
|
235
|
-
if (this.disposed) throw new Error('
|
|
236
|
-
if (!this.screenshot?.permissions) throw new Error('
|
|
236
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
237
|
+
if (!this.screenshot?.permissions) throw new Error(msg('error.permission'));
|
|
237
238
|
return this.screenshot.permissions(action);
|
|
238
239
|
}
|
|
239
240
|
async typingPermissions(action = 'check') {
|
|
240
|
-
if (this.disposed) throw new Error('
|
|
241
|
-
if (!this.desktop?.permissions) throw new Error('
|
|
241
|
+
if (this.disposed) throw new Error(msg('error.closed'));
|
|
242
|
+
if (!this.desktop?.permissions) throw new Error(msg('error.permission'));
|
|
242
243
|
return this.desktop.permissions(action);
|
|
243
244
|
}
|
|
244
245
|
async prepareAi(run) {
|
|
245
246
|
try {
|
|
246
|
-
if (!this.aiConversation || !this.desktop) throw new Error('
|
|
247
|
+
if (!this.aiConversation || !this.desktop) throw new Error(msg('error.ai'));
|
|
247
248
|
// Activation failure alone must not abort: with the window tray-hidden the renderer lives on and insertion still works.
|
|
248
249
|
try { await this.action('openAi'); } catch { run.aiActivateFailed = true; }
|
|
249
250
|
run.lifetime.signal.throwIfAborted();
|
|
@@ -254,12 +255,12 @@ export class DeviceManager {
|
|
|
254
255
|
async begin(run, device) {
|
|
255
256
|
try {
|
|
256
257
|
if (run.action === 'ai_input') run.aiReady = this.prepareAi(run);
|
|
257
|
-
if (run.action === 'ai_input' && !this.desktop) throw new Error('
|
|
258
|
+
if (run.action === 'ai_input' && !this.desktop) throw new Error(msg('error.ai'));
|
|
258
259
|
if (this.desktop) await this.desktop.begin(run);
|
|
259
260
|
if (this.run !== run || run.closing) return;
|
|
260
261
|
run.service = await this.prepare();
|
|
261
262
|
if (this.run !== run || run.closing) return;
|
|
262
|
-
if (await this.sdk.source(device.id) !== 1) throw new Error('
|
|
263
|
+
if (await this.sdk.source(device.id) !== 1) throw new Error(msg('error.audio'));
|
|
263
264
|
if (this.run !== run || run.closing) return;
|
|
264
265
|
if (this.desktop) { run.started = true; void this.process(run); }
|
|
265
266
|
else this.publish({ type: 'request', sessionId: run.id, sn: run.sn, action: run.action });
|
|
@@ -274,9 +275,9 @@ export class DeviceManager {
|
|
|
274
275
|
if (!run || run.deviceId !== event.id || run.audioEnded || this.devices.get(event.id)?.connectionId !== run.connectionId) return;
|
|
275
276
|
try {
|
|
276
277
|
const buffer = Buffer.from(event.data, 'base64');
|
|
277
|
-
if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error('
|
|
278
|
+
if (buffer.toString('base64') !== event.data || buffer.length > 320000) throw new Error(msg('error.audio'));
|
|
278
279
|
run.bytes += buffer.length;
|
|
279
|
-
if (!run.ready && run.bytes > 320000) throw new Error('
|
|
280
|
+
if (!run.ready && run.bytes > 320000) throw new Error(msg('error.audio'));
|
|
280
281
|
run.packets.write(buffer);
|
|
281
282
|
} catch (error) { this.fail(run, error.message); }
|
|
282
283
|
}
|
|
@@ -287,7 +288,7 @@ export class DeviceManager {
|
|
|
287
288
|
run.started = true; clearTimeout(run.captureTimer);
|
|
288
289
|
void this.process(run); return true;
|
|
289
290
|
}
|
|
290
|
-
assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error('
|
|
291
|
+
assertOwner(clientId) { if (!this.owner || this.owner !== clientId) throw new Error(msg('error.busy')); }
|
|
291
292
|
release(run) {
|
|
292
293
|
if (this.run !== run || run.released) return;
|
|
293
294
|
run.released = true;
|
|
@@ -298,7 +299,7 @@ export class DeviceManager {
|
|
|
298
299
|
try { run.audioEnded = true; run.packets.flush(); run.queue.end(); }
|
|
299
300
|
catch (error) { this.fail(run, error.message); }
|
|
300
301
|
}, this.config.tailMs ?? 150);
|
|
301
|
-
run.uploadTimer = setTimeout(() => this.fail(run, '
|
|
302
|
+
run.uploadTimer = setTimeout(() => this.fail(run, msg('error.timeout')), 15000);
|
|
302
303
|
}
|
|
303
304
|
async process(run) {
|
|
304
305
|
try {
|
|
@@ -317,9 +318,9 @@ export class DeviceManager {
|
|
|
317
318
|
if (event.type === 'complete') { complete = true; break; }
|
|
318
319
|
}
|
|
319
320
|
if (this.run !== run || run.closing) return;
|
|
320
|
-
if (!complete || !run.released) throw new Error('
|
|
321
|
+
if (!complete || !run.released) throw new Error(msg('error.connection'));
|
|
321
322
|
await this.complete(run);
|
|
322
|
-
} catch (error) { this.fail(run, error.message || '
|
|
323
|
+
} catch (error) { this.fail(run, error.message || msg('error.generic')); }
|
|
323
324
|
}
|
|
324
325
|
async complete(run) {
|
|
325
326
|
let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
|
|
@@ -343,12 +344,12 @@ export class DeviceManager {
|
|
|
343
344
|
await this.aiConversation.insert(run, text);
|
|
344
345
|
if (this.run !== run || run.closing) return;
|
|
345
346
|
this.publish(run.aiActivateFailed
|
|
346
|
-
? { type: 'failed', sessionId: run.id, message: '
|
|
347
|
+
? { type: 'failed', sessionId: run.id, message: msg('error.aiWindow') }
|
|
347
348
|
: { type: 'finished', sessionId: run.id });
|
|
348
349
|
} catch (error) {
|
|
349
350
|
// On Windows the panel keeps the text so the user can focus any input and submit it there.
|
|
350
351
|
if (this.desktop?.platform === 'win32') {
|
|
351
|
-
this.publish({ type: 'submitOffer', sessionId: run.id, text, message: '
|
|
352
|
+
this.publish({ type: 'submitOffer', sessionId: run.id, text, message: msg('panel.openInput') });
|
|
352
353
|
await this.finish(run);
|
|
353
354
|
return;
|
|
354
355
|
}
|
|
@@ -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: '
|
|
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: '
|
|
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() {
|
package/src/devices/native.mjs
CHANGED
|
@@ -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(
|
|
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('
|
|
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('
|
|
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('
|
|
55
|
-
if (!this.stopping) this.emit('fault', '
|
|
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('
|
|
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('
|
|
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
|
}
|
package/src/devices/queue.mjs
CHANGED
|
@@ -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('
|
|
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('
|
|
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('
|
|
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;
|
package/src/devices/store.mjs
CHANGED
|
@@ -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('
|
|
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: '
|
|
37
|
-
1006: '
|
|
38
|
-
throw new Error(
|
|
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, '
|
|
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('
|
|
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('
|
|
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('
|
|
44
|
+
const abort = () => fail(new Error(msg('error.ai')));
|
|
44
45
|
const timer = setTimeout(() => {
|
|
45
|
-
fail(new Error('
|
|
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('
|
|
66
|
+
else pending.reject(new Error(msg('error.ai')));
|
|
66
67
|
return true;
|
|
67
68
|
}
|
|
68
|
-
release(sessionId, message = '
|
|
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()) {
|
package/src/host/index.mjs
CHANGED
|
@@ -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';
|
|
@@ -28,11 +30,13 @@ export class MouseController extends TypertRemoteService {
|
|
|
28
30
|
sdk: dependencies.sdk ?? new MouseSdk(config.native), ...dependencies, aiConversation: this.aiConversation,
|
|
29
31
|
prepare: () => this.service(), recognize: request => this.recognize(request),
|
|
30
32
|
translate: request => this.translate(request) });
|
|
33
|
+
this.locale = new HostLocale(locale => this.manager.desktop?.setLocale(locale));
|
|
31
34
|
ctx.effect(() => () => {
|
|
32
35
|
this.lifetime.abort(); this.providers.clear(); return this.manager.close();
|
|
33
36
|
});
|
|
34
37
|
}
|
|
35
38
|
async service() { await this.initialized; return { ...await this.store.resolve(), ...this.dependencies.endpoints }; }
|
|
39
|
+
syncLocale(request) { return this.locale.accept(request); }
|
|
36
40
|
catalog() { return this.store.catalog(); }
|
|
37
41
|
devices() { return this.manager.view(); }
|
|
38
42
|
captureScreenshot() { return this.manager.captureScreenshot(); }
|
|
@@ -80,8 +84,8 @@ export class MouseController extends TypertRemoteService {
|
|
|
80
84
|
}
|
|
81
85
|
} catch (error) {
|
|
82
86
|
if (!signal.aborted && !this.lifetime.signal.aborted) yield { type: 'error',
|
|
83
|
-
message: connection.signal.aborted ? '
|
|
84
|
-
:
|
|
87
|
+
message: connection.signal.aborted ? msg('error.timeout')
|
|
88
|
+
: safeMessage(error.message, 'error.connection') };
|
|
85
89
|
} finally { clearTimeout(timer); }
|
|
86
90
|
}
|
|
87
91
|
async translate({ sn, service: capturedService, ...request }) {
|
|
@@ -95,6 +99,7 @@ export class MouseController extends TypertRemoteService {
|
|
|
95
99
|
export async function apply(ctx, config = {}) {
|
|
96
100
|
ctx.effect(() => ctx.typert.register(TYPERT));
|
|
97
101
|
const controller = new MouseController(ctx, config, { desktop: new DesktopPresentation(), screenshot: new ScreenshotService() });
|
|
102
|
+
attachHostLocale(ctx, controller);
|
|
98
103
|
await controller.initialized;
|
|
99
104
|
void controller.manager.start();
|
|
100
105
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { LOCALES, resolveLocale } from '../shared/i18n.mjs';
|
|
2
|
+
|
|
3
|
+
// Host 配置 revision 是跨窗口的权威顺序;客户端 locale revision 仅在单个窗口有效。
|
|
4
|
+
export class HostLocale {
|
|
5
|
+
constructor(apply) { this.apply = apply; this.locale = 'en'; this.revision = undefined; this.automatic = undefined; }
|
|
6
|
+
attach(read) { this.read = read; this.refresh(); }
|
|
7
|
+
refresh() {
|
|
8
|
+
const state = this.read?.();
|
|
9
|
+
if (!state || !Number.isInteger(state.revision)) return undefined;
|
|
10
|
+
if (state.revision !== this.revision) {
|
|
11
|
+
this.revision = state.revision;
|
|
12
|
+
this.automatic = undefined;
|
|
13
|
+
this.preference = typeof state.value?.preference === 'string' ? state.value.preference : undefined;
|
|
14
|
+
if (this.preference) this.set(resolveLocale(this.preference));
|
|
15
|
+
}
|
|
16
|
+
return state;
|
|
17
|
+
}
|
|
18
|
+
set(locale) {
|
|
19
|
+
if (locale === this.locale) return;
|
|
20
|
+
this.locale = locale; this.apply(locale);
|
|
21
|
+
}
|
|
22
|
+
accept({ active, resolved, revision }) {
|
|
23
|
+
const state = this.refresh();
|
|
24
|
+
if (!state || revision !== state.revision || !LOCALES.includes(resolved)) return false;
|
|
25
|
+
if (LOCALES.includes(active.toLowerCase()) && resolved !== active.toLowerCase()) return false;
|
|
26
|
+
if (this.preference) {
|
|
27
|
+
if (active.toLowerCase() !== this.preference.toLowerCase()) return false;
|
|
28
|
+
} else {
|
|
29
|
+
if (this.automatic && this.automatic !== `${active}:${resolved}`) return false;
|
|
30
|
+
this.automatic = `${active}:${resolved}`;
|
|
31
|
+
}
|
|
32
|
+
this.set(resolved); return true;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function attachHostLocale(ctx, controller) {
|
|
36
|
+
return ctx.inject(['settings'], scope => {
|
|
37
|
+
const sync = () => controller.locale.refresh();
|
|
38
|
+
controller.locale.attach(() => scope.settings.describe().find(item => item.ns === 'locale'));
|
|
39
|
+
scope.on('settings/document-updated', ns => { if (ns === 'locale') queueMicrotask(sync); });
|
|
40
|
+
scope.effect(() => () => { controller.locale.read = undefined; });
|
|
41
|
+
});
|
|
42
|
+
}
|