@sonicloud/dsh-sonicloud-device 0.1.0 → 0.1.2

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.
@@ -2,58 +2,98 @@ using System;
2
2
  using System.Collections.Generic;
3
3
  using System.Drawing;
4
4
  using System.Drawing.Drawing2D;
5
+ using System.Runtime.InteropServices;
6
+ using System.Text;
5
7
  using System.Text.RegularExpressions;
6
8
  using System.Linq;
7
9
  using System.Threading;
8
10
  using System.Windows.Automation;
9
- using System.Windows.Automation.Text;
10
11
  using System.Windows.Forms;
11
12
  using System.Web.Script.Serialization;
12
13
 
13
14
  namespace Sonicloud {
14
- sealed class Insertion {
15
- AutomationElement element;
16
- string original;
17
- int[] runtime;
18
- int start, length;
19
- static bool Read(AutomationElement target, out string value, out int offset, out int count) {
20
- value = ""; offset = count = 0;
21
- object vp, tp;
22
- if (target.Current.IsPassword || !target.TryGetCurrentPattern(ValuePattern.Pattern, out vp)
23
- || ((ValuePattern)vp).Current.IsReadOnly || !target.TryGetCurrentPattern(TextPattern.Pattern, out tp)) return false;
24
- value = ((ValuePattern)vp).Current.Value;
25
- var pattern = (TextPattern)tp;
26
- var selected = pattern.GetSelection();
27
- if (selected.Length != 1) return false;
28
- var before = pattern.DocumentRange.Clone();
29
- before.MoveEndpointByRange(TextPatternRangeEndpoint.End, selected[0], TextPatternRangeEndpoint.Start);
30
- offset = before.GetText(-1).Length; count = selected[0].GetText(-1).Length;
31
- // UIA text/value views must agree before making any replacement.
32
- return pattern.DocumentRange.GetText(-1) == value && offset + count <= value.Length;
33
- }
34
- public static Insertion Capture() {
35
- try {
36
- var target = AutomationElement.FocusedElement;
37
- string value; int offset, count;
38
- if (target == null || !Read(target, out value, out offset, out count)) return null;
39
- return new Insertion { element = target, runtime = target.GetRuntimeId(), original = value, start = offset, length = count };
40
- } catch { return null; }
15
+ // typer.dll 标准注入库(纯 C ABI):会话式逐字打字,实时退格更正,逐字模式不占用剪贴板。
16
+ static class Typer {
17
+ public const int ModePerChar = 0;
18
+ public const int ErrInvalidArg = -1, ErrNotSupported = -2, ErrAccessDenied = -4, ErrWrongState = -6, ErrQueueFull = -8;
19
+ public delegate void ErrorCallback(IntPtr user, int code);
20
+ // typer_config v1.1 布局(x64 自然对齐与 C 一致);drained_cb 不用,置空。
21
+ [StructLayout(LayoutKind.Sequential)]
22
+ public struct Config {
23
+ public IntPtr size, drained_cb, drained_user;
24
+ public int xkb_bind_delay_ms, xkb_char_interval_ms, xdotool_char_delay_ms, xclip_settle_ms,
25
+ paste_settle_ms, ime_settle_ms, proc_timeout_ms, queue_limit;
26
+ public IntPtr error_cb, error_user;
27
+ }
28
+ // typer_caps 完整布局(含尾部 char ime_tool_path[260],探测要求 size 覆盖全结构)。
29
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
30
+ public struct Caps {
31
+ public IntPtr size;
32
+ public int session_type, text_typing, increment_typing, whole_phrase_paste, ime_guard,
33
+ input_permitted, has_xdotool, has_xclip, has_fcitx_remote;
34
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string ime_tool_path;
41
35
  }
42
- public bool Insert(string text) {
36
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] static extern IntPtr LoadLibrary(string path);
37
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr typer_create(ref Config config);
38
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern void typer_destroy(IntPtr ctx);
39
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_session_begin(IntPtr ctx, int mode);
40
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_feed_partial(IntPtr ctx, byte[] utf8);
41
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_feed_final(IntPtr ctx, byte[] utf8);
42
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_session_end(IntPtr ctx);
43
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_session_abort(IntPtr ctx);
44
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern int typer_probe(ref Caps caps);
45
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr typer_version();
46
+ [DllImport("typer.dll", CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr typer_strerror(int code);
47
+ public static bool loaded;
48
+ public static void Load(string directory) {
43
49
  try {
44
- var current = AutomationElement.FocusedElement;
45
- string value; int offset, count;
46
- if (current == null || !current.GetRuntimeId().SequenceEqual(runtime)
47
- || !Read(current, out value, out offset, out count) || value != original || offset != start || count != length) return false;
48
- ((ValuePattern)element.GetCurrentPattern(ValuePattern.Pattern)).SetValue(original.Substring(0, start) + text + original.Substring(start + length));
49
- // Setting value succeeded; caret placement is best effort, never repeat insertion.
50
- try {
51
- var range = ((TextPattern)element.GetCurrentPattern(TextPattern.Pattern)).DocumentRange;
52
- range.MoveEndpointByRange(TextPatternRangeEndpoint.End, range, TextPatternRangeEndpoint.Start);
53
- range.Move(TextUnit.Character, start + text.Length); range.Select();
54
- } catch { }
55
- return true;
56
- } catch { return false; }
50
+ if (LoadLibrary(System.IO.Path.Combine(directory, "typer.dll")) == IntPtr.Zero) return;
51
+ StringAt(typer_version()); // 触发一次导出调用,确认模块与 ABI 可用
52
+ loaded = true;
53
+ } catch { loaded = false; }
54
+ }
55
+ public static string StringAt(IntPtr pointer) { return pointer == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(pointer); }
56
+ }
57
+ // 面板持有的 typer 会话封装;error 回调来自库内打字线程,只做投递,不在回调内再调 typer_*。
58
+ sealed class TyperEngine {
59
+ static Action<int> notify;
60
+ static readonly Typer.ErrorCallback errorCallback = OnNativeError;
61
+ static void OnNativeError(IntPtr user, int code) { Action<int> handler = notify; if (handler != null) handler(code); }
62
+ public IntPtr context;
63
+ public bool Open(Action<int> onError) {
64
+ if (!Typer.loaded) return false;
65
+ var config = new Typer.Config();
66
+ config.size = (IntPtr)Marshal.SizeOf(typeof(Typer.Config));
67
+ config.queue_limit = 1024; // 默认 256,长语音的中间结果可能更多
68
+ config.error_cb = Marshal.GetFunctionPointerForDelegate(errorCallback);
69
+ try { context = Typer.typer_create(ref config); } catch { context = IntPtr.Zero; }
70
+ if (context == IntPtr.Zero) return false;
71
+ notify = onError;
72
+ return true;
73
+ }
74
+ public void Close() {
75
+ if (context != IntPtr.Zero) { Typer.typer_destroy(context); context = IntPtr.Zero; }
76
+ notify = null;
77
+ }
78
+ public int Begin(int mode) { return context == IntPtr.Zero ? Typer.ErrNotSupported : Typer.typer_session_begin(context, mode); }
79
+ public int Partial(string text) { return context == IntPtr.Zero ? Typer.ErrNotSupported : Typer.typer_feed_partial(context, Bytes(text)); }
80
+ public int Final(string text) { return context == IntPtr.Zero ? Typer.ErrNotSupported : Typer.typer_feed_final(context, Bytes(text)); }
81
+ public int End() { return context == IntPtr.Zero ? Typer.ErrNotSupported : Typer.typer_session_end(context); }
82
+ public int Abort() { return context == IntPtr.Zero ? Typer.ErrNotSupported : Typer.typer_session_abort(context); }
83
+ public static string ErrorText(int code) {
84
+ switch (code) {
85
+ case Typer.ErrInvalidArg: return "文本包含不支持的字符";
86
+ case Typer.ErrAccessDenied: return "目标窗口拒绝模拟输入";
87
+ case Typer.ErrWrongState: return "打字会话已中断";
88
+ case Typer.ErrQueueFull: return "打字任务过多,请稍候";
89
+ default: return "打字失败(代码 " + code + ")";
90
+ }
91
+ }
92
+ static byte[] Bytes(string text) {
93
+ if (string.IsNullOrEmpty(text)) return new byte[] { 0 };
94
+ byte[] data = Encoding.UTF8.GetBytes(text);
95
+ Array.Resize(ref data, data.Length + 1); // 追加 NUL 终止
96
+ return data;
57
97
  }
58
98
  }
59
99
  static class CapsuleShape {
@@ -90,12 +130,19 @@ namespace Sonicloud {
90
130
  public sealed class VoicePanel : Form {
91
131
  readonly SingleLineText text = new SingleLineText();
92
132
  readonly Waveform waveform = new Waveform();
93
- readonly Button close = new Button(), copy = new Button();
133
+ readonly Button close = new Button(), copy = new Button(), submit = new Button();
94
134
  readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = 300000 };
95
135
  readonly System.Windows.Forms.Timer pulse = new System.Windows.Forms.Timer { Interval = 40 };
96
136
  string session = "", preview = "", phase = "", message = "";
97
137
  bool active;
98
- Insertion insertion;
138
+ TyperEngine typer;
139
+ bool sessionTyping; // typer 会话已 begin 且未 end/abort
140
+ bool typingLive; // voice_input:中间结果实时逐字打进目标窗口
141
+ bool typingBlocked; // 密码框 / 组件不可用,本次会话拒绝打字
142
+ string blockedReason = "";
143
+ bool typingError; // 注入失败已闩(error_cb),后续 feed/end 只会返回 WRONG_STATE
144
+ int typingErrorCode;
145
+ bool pendingSubmit; // 宿主 submitOffer:文本留在浮窗,等用户放好焦点后一键提交
99
146
  Screen screen;
100
147
  protected override bool ShowWithoutActivation { get { return true; } }
101
148
  protected override CreateParams CreateParams {
@@ -120,16 +167,19 @@ namespace Sonicloud {
120
167
  }
121
168
  close.Image = icon; close.AccessibleName = "取消";
122
169
  copy.Text = "复制结果";
123
- Controls.AddRange(new Control[] { text, waveform, close, copy });
170
+ submit.Text = "一键提交"; submit.AccessibleName = "一键提交";
171
+ Controls.AddRange(new Control[] { text, waveform, close, copy, submit });
124
172
  close.Click += delegate {
125
173
  if (active) Emit(new Dictionary<string, object> { { "event", "cancel" }, { "sessionId", session } });
126
- active = false; insertion = null; preview = message = ""; Hide();
174
+ EndSession(); preview = message = ""; pendingSubmit = false; Hide();
127
175
  };
176
+ submit.Click += delegate { SubmitPending(); };
128
177
  copy.Click += delegate { try { Clipboard.SetText(preview); copy.Text = "已复制"; } catch { copy.Text = "复制失败"; } };
129
178
  pulse.Tick += delegate { waveform.Phase += 0.25; waveform.Invalidate(); };
130
179
  VisibleChanged += delegate { pulse.Enabled = Visible && active; };
131
180
  Microsoft.Win32.SystemEvents.DisplaySettingsChanged += DisplayChanged;
132
181
  FormClosed += delegate { pulse.Dispose(); close.Image.Dispose(); Microsoft.Win32.SystemEvents.DisplaySettingsChanged -= DisplayChanged; };
182
+ Disposed += delegate { EndSession(); if (typer != null) { typer.Close(); typer = null; } };
133
183
  }
134
184
  void DisplayChanged(object sender, EventArgs e) { if (!IsDisposed && Visible) BeginInvoke((Action)Render); }
135
185
  void Render() {
@@ -140,44 +190,126 @@ namespace Sonicloud {
140
190
  var previous = Region; Region = new Region(outline); if (previous != null) previous.Dispose();
141
191
  }
142
192
  waveform.SetBounds(20, (height - 26) / 2, 23, 26);
143
- close.SetBounds(width - 44, (height - 28) / 2, 28, 28); copy.SetBounds(width - 146, (height - 32) / 2, 96, 32);
144
- waveform.Visible = active; copy.Visible = !active && preview.Length > 0; close.AccessibleName = active ? "取消" : "关闭";
193
+ close.SetBounds(width - 44, (height - 28) / 2, 28, 28);
194
+ if (pendingSubmit) {
195
+ submit.SetBounds(width - 148, (height - 32) / 2, 96, 32);
196
+ copy.SetBounds(width - 252, (height - 32) / 2, 96, 32);
197
+ } else copy.SetBounds(width - 146, (height - 32) / 2, 96, 32);
198
+ waveform.Visible = active; submit.Visible = pendingSubmit;
199
+ copy.Visible = !active && preview.Length > 0; close.AccessibleName = active ? "取消" : "关闭";
145
200
  int left = active ? 54 : 22, right = copy.Visible ? copy.Left : close.Left;
146
201
  text.SetBounds(left, 0, Math.Max(0, right - left - 12), height);
147
202
  string status = message.Length > 0 ? message : phase == "finishing" ? "正在整理…" : phase == "translating" ? "正在翻译…" : "";
148
203
  string displayText = (status + " " + preview).Trim();
149
204
  text.Text = Regex.Replace(displayText, @"[\r\n\t\u0085\u2028\u2029]+", " ");
150
- pulse.Enabled = active;
205
+ pulse.Enabled = Visible && active;
151
206
  Show();
152
207
  }
153
208
  static string Get(Dictionary<string, object> item, string key) { object value; return item.TryGetValue(key, out value) ? Convert.ToString(value) : ""; }
154
209
  void Emit(Dictionary<string, object> value) { Console.WriteLine(json.Serialize(value)); Console.Out.Flush(); }
210
+ // UIA 不可达时放行(fail-open):最坏情况等于无密码检查的直接注入。
211
+ static bool FocusedElementIsPassword() {
212
+ try { var element = AutomationElement.FocusedElement; return element != null && element.Current.IsPassword; }
213
+ catch { return false; }
214
+ }
215
+ void EndSession() {
216
+ active = false; typingLive = false;
217
+ if (sessionTyping) { sessionTyping = false; if (typer != null) typer.Abort(); }
218
+ }
219
+ void HandleTypingError(int code) {
220
+ typingError = true; typingErrorCode = code;
221
+ message = "未回填:" + TyperEngine.ErrorText(code) + ",可复制结果";
222
+ Render();
223
+ }
224
+ // 一键提交:把保留的文本一次性逐字注入点击时聚焦的窗口(浮窗不抢焦点,焦点仍在用户摆好的目标上)。
225
+ void SubmitPending() {
226
+ if (!pendingSubmit) return;
227
+ pendingSubmit = false;
228
+ string reason = null;
229
+ if (typer == null || typer.context == IntPtr.Zero) reason = "打字组件不可用";
230
+ else if (FocusedElementIsPassword()) reason = "目标为密码输入框";
231
+ else {
232
+ int rc = typer.Begin(Typer.ModePerChar);
233
+ if (rc != 0) reason = TyperEngine.ErrorText(rc);
234
+ else {
235
+ sessionTyping = true;
236
+ rc = typer.Final(preview);
237
+ if (rc == 0) { typer.End(); sessionTyping = false; }
238
+ else { typer.Abort(); sessionTyping = false; reason = TyperEngine.ErrorText(rc); }
239
+ }
240
+ }
241
+ if (reason == null) { preview = message = ""; Hide(); }
242
+ else { message = "未回填:" + reason + ",可复制结果"; Render(); }
243
+ }
155
244
  void HandleCommand(Dictionary<string, object> item) {
156
245
  string command = Get(item, "command"), incoming = Get(item, "sessionId"); bool ok = true, inserted = false;
157
246
  if (command == "begin") {
158
247
  session = incoming; preview = message = ""; phase = "connecting"; active = true;
159
- insertion = Get(item, "action") == "speechSearch" || Get(item, "action") == "ai_input" ? null : Insertion.Capture();
248
+ string action = Get(item, "action");
249
+ typingBlocked = false; typingError = false; sessionTyping = false; typingLive = false; pendingSubmit = false;
250
+ if (action == "voice_input" || action == "translate") {
251
+ typingLive = action == "voice_input"; // 翻译只在最终译文出来后打字,避免先打原文再整段退格
252
+ if (typer == null || typer.context == IntPtr.Zero) { typingBlocked = true; blockedReason = "打字组件不可用"; }
253
+ else if (FocusedElementIsPassword()) { typingBlocked = true; blockedReason = "目标为密码输入框"; }
254
+ else {
255
+ int rc = typer.Begin(Typer.ModePerChar);
256
+ if (rc == 0) sessionTyping = true;
257
+ else { typingBlocked = true; blockedReason = TyperEngine.ErrorText(rc); }
258
+ }
259
+ }
160
260
  screen = Screen.FromPoint(Cursor.Position); copy.Text = "复制结果"; Render();
161
- } else if (incoming.Length > 0 && incoming != session) ok = false;
261
+ } else if (incoming.Length > 0 && incoming != session) { ok = false; }
162
262
  else if (command == "result" && active) {
163
- preview = Get(item, "text"); inserted = insertion != null && insertion.Insert(preview);
164
- insertion = null; active = false;
165
- if (inserted) Hide(); else { message = "未回填,可复制结果"; Render(); }
263
+ preview = Get(item, "text");
264
+ string reason = null;
265
+ if (typingBlocked) reason = blockedReason;
266
+ else if (typingError) reason = TyperEngine.ErrorText(typingErrorCode);
267
+ else if (sessionTyping) {
268
+ int rc = typer.Final(preview);
269
+ if (rc != 0) reason = TyperEngine.ErrorText(rc);
270
+ else { typer.End(); sessionTyping = false; }
271
+ }
272
+ EndSession();
273
+ if (reason == null) { inserted = true; Hide(); }
274
+ else { message = "未回填:" + reason + ",可复制结果"; Render(); }
166
275
  } else if (command == "event") {
167
276
  switch (Get(item, "type")) {
168
- case "preview": if (active) { preview = Get(item, "text"); Render(); } break;
277
+ case "preview":
278
+ if (active) {
279
+ preview = Get(item, "text");
280
+ if (typingLive && sessionTyping && !typingError) typer.Partial(preview);
281
+ Render();
282
+ }
283
+ break;
169
284
  case "phase": if (active) { phase = Get(item, "phase"); Render(); } break;
170
285
  case "notice": message = Get(item, "message"); Render(); break;
171
- case "failed": active = false; insertion = null; message = Get(item, "message"); Render(); break;
172
- case "cancelled": case "finished": active = false; insertion = null; preview = message = ""; Hide(); break;
286
+ case "failed": EndSession(); message = Get(item, "message"); Render(); break;
287
+ case "submitOffer":
288
+ // 宿主无法填入 Harness 对话(窗口/渲染不可达):文本留在浮窗,交给一键提交注入当前焦点窗口。
289
+ preview = Get(item, "text");
290
+ EndSession();
291
+ typingError = false; // 清闩,本次提交允许重新注入
292
+ pendingSubmit = preview.Length > 0;
293
+ message = pendingSubmit ? Get(item, "message") : "没有可输入的内容";
294
+ if (message.Length == 0) message = "请打开需要输入界面";
295
+ copy.Text = "复制结果"; Render();
296
+ break;
297
+ case "cancelled": case "finished":
298
+ // 空结果收尾(无 result):实时打出的中间结果用空 partial 修正掉,再结束会话。
299
+ if (sessionTyping && typingLive && !typingError) { typer.Partial(""); typer.End(); sessionTyping = false; }
300
+ EndSession(); preview = message = ""; Hide();
301
+ break;
173
302
  }
174
303
  } else ok = false;
175
304
  object id; if (item.TryGetValue("id", out id)) Emit(new Dictionary<string, object> { { "id", id }, { "ok", ok }, { "value", inserted } });
176
305
  }
177
- [STAThread] public static void Run() {
306
+ [STAThread] public static void Run(string dllDirectory) {
307
+ Typer.Load(dllDirectory);
178
308
  Application.EnableVisualStyles();
179
309
  using (var form = new VoicePanel()) {
180
- var handle = form.Handle;
310
+ var handle = form.Handle; // 先建句柄,后台线程的 BeginInvoke 才有目标
311
+ form.typer = new TyperEngine();
312
+ form.typer.Open(code => { if (!form.IsDisposed) form.BeginInvoke((Action)(() => form.HandleTypingError(code))); });
181
313
  var input = new Thread(() => {
182
314
  string line;
183
315
  while ((line = Console.ReadLine()) != null) {
Binary file
@@ -6,4 +6,4 @@ $references = @('System.Windows.Forms', 'System.Drawing', 'System.Web.Extensions
6
6
  [System.Windows.Automation.AutomationElement].Assembly.Location,
7
7
  [System.Windows.Automation.Text.TextPatternRangeEndpoint].Assembly.Location)
8
8
  Add-Type -Path (Join-Path $PSScriptRoot 'VoicePanel.cs') -ReferencedAssemblies $references
9
- [Sonicloud.VoicePanel]::Run()
9
+ [Sonicloud.VoicePanel]::Run($PSScriptRoot)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sonicloud/dsh-sonicloud-device",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "DeepSeek Harness 智能鼠标、多设备设置与共享语音服务",
5
5
  "icon": "./src/client/assets/sonicloud.png",
6
6
  "type": "module",
@@ -18,6 +18,7 @@
18
18
  "dist",
19
19
  "cordis.patch.yml",
20
20
  "README.md",
21
+ "README.zh.md",
21
22
  "src/devices",
22
23
  "src/desktop",
23
24
  "native",
@@ -36,7 +36,13 @@ export async function systemAction(action, value, { platform = process.platform,
36
36
  const scripts = {
37
37
  enter: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{ENTER}")',
38
38
  backspace: '$s=New-Object -ComObject WScript.Shell; $s.SendKeys("{BACKSPACE}")',
39
- openAi: '$s=New-Object -ComObject WScript.Shell; if(-not $s.AppActivate("DeepSeek Harness")){exit 1}',
39
+ // The window title varies with the active page, so title matching fails intermittently; activate by handle.
40
+ // Minimized windows need ShowWindow(SW_RESTORE) because AppActivate never restores them. When no visible handle
41
+ // exists (hidden to the tray), a second launch of the running exe reaches the single-instance handler, which
42
+ // restores or recreates the window from inside the app. The plugin backend itself runs the app exe as node via
43
+ // ELECTRON_RUN_AS_NODE, and a second launch inheriting that variable would also start as plain node and exit
44
+ // without any window, so the Electron overrides must be stripped before handing off.
45
+ openAi: "$p=Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 } | Select-Object -First 1; if($p){ Add-Type -Namespace Win -Name Native -MemberDefinition '[DllImport(\"user32.dll\")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);[DllImport(\"user32.dll\")] public static extern bool SetForegroundWindow(IntPtr hWnd);'; [Win.Native]::ShowWindow($p.MainWindowHandle, 9) | Out-Null; if([Win.Native]::SetForegroundWindow($p.MainWindowHandle)){ exit 0 } }; Remove-Item Env:\\ELECTRON_RUN_AS_NODE, Env:\\ELECTRON_NO_ATTACH_CONSOLE, Env:\\ELECTRON_NO_ASAR -ErrorAction SilentlyContinue; $exe=(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue | Select-Object -First 1).Path; if($exe){ Start-Process -FilePath $exe -ArgumentList 'dsh://open'; exit 0 }; Start-Process -FilePath rundll32.exe -ArgumentList 'url.dll,FileProtocolHandler','dsh://open' -WindowStyle Hidden; exit 0",
40
46
  };
41
47
  if (!scripts[action]) throw new Error('不支持此按键动作');
42
48
  args = ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(scripts[action], 'utf16le').toString('base64')];
@@ -74,60 +74,74 @@ export class DeviceManager {
74
74
  }
75
75
  async event(event) {
76
76
  if (this.disposed) return;
77
- const id = event.id;
78
- if (event.type === 'diagnostic') {
79
- if (!this.devices.size) { this.status = event.message; this.snapshot(); }
80
- } else if (event.type === 'connected') {
81
- const previous = this.devices.get(id);
82
- if (previous) this.cancelFor(id);
83
- const stable = isStableSn(id);
84
- const category = event.deviceType ?? 'smart-mouse';
85
- const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
86
- this.devices.set(id, { id, sn: stable ? id : '', type: category, name: event.name || (category === 'smart-mouse' ? '智能鼠标' : '设备'),
87
- connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
88
- identityConfirmed: stable, dpiState: 'unknown', ...saved });
89
- this.clearPressed(id);
90
- this.status = '设备已连接';
91
- if (saved?.revision > 0) await this.applyDpi(this.devices.get(id));
92
- this.snapshot();
93
- } else if (event.type === 'disconnected') {
94
- const device = this.devices.get(id);
95
- if (!device || device.connection !== (event.mode === 1 ? 'ble' : 'usb')) return;
96
- this.cancelFor(id, '设备已断开,语音已取消'); this.devices.delete(id); this.clearPressed(id);
97
- if (!this.devices.size) this.status = '设备已断开,正在重新查找智能鼠标…';
98
- this.snapshot();
99
- } else if (event.type === 'overflow') this.cancelFor(id, '鼠标音频处理过慢,本次识别已停止');
100
- else if (event.type === 'warning') this.publish({ type: 'notice', message: event.message });
101
- else if (event.type === 'message') {
102
- const device = this.devices.get(id), message = event.message;
103
- if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '鼠标连接异常' }); return; }
104
- if (message.type === 'queueOverflow') { this.cancel(undefined, '鼠标音频丢失,请重新录音'); return; }
105
- if (!device) return;
106
- if (message.type === 'deviceInfo') {
107
- if (isStableSn(message.sn) && message.sn !== device.sn) {
108
- // Re-key only a temporary identity, never merge two real devices.
109
- if (device.identityConfirmed || this.devices.has(message.sn)) {
110
- device.identityConfirmed = false; this.cancelFor(id, '设备 SN 冲突,请重连');
111
- } else {
112
- this.devices.delete(id); device.sn = message.sn; device.identityConfirmed = true;
113
- if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn)); this.devices.set(id, device);
114
- }
115
- }
116
- if (Number.isFinite(message.battery) && message.battery >= 0 && message.battery <= 100) device.battery = message.battery;
117
- this.snapshot();
118
- } else if (message.type === 'dpiChanged') {
119
- if (!Number.isInteger(message.level) || message.level < 0 || message.level > 255) return;
120
- device.dpiRaw = message.level;
121
- // Hardware broadcasts use a separate mapping from software command bytes.
122
- const matches = Object.entries(this.dpiReportLevels).filter(([, level]) => level === message.level);
123
- if (matches.length === 1 && device.type === 'smart-mouse' && device.identityConfirmed) {
124
- Object.assign(device, await this.store.reportDpi(device.sn, matches[0][0]));
125
- device.dpiState = 'reported';
126
- } else if (device.dpiState === 'reported') device.dpiState = 'unknown';
127
- this.snapshot();
128
- } else if (message.type === 'keyEvent') await this.key(device, message);
77
+ switch (event.type) {
78
+ case 'connected': return this.connectDevice(event);
79
+ case 'disconnected': return this.disconnectDevice(event);
80
+ case 'message': return this.deviceMessage(event);
81
+ case 'overflow': return this.cancelFor(event.id, '鼠标音频处理过慢,本次识别已停止');
82
+ case 'warning': return this.publish({ type: 'notice', message: event.message });
83
+ case 'diagnostic':
84
+ if (!this.devices.size) { this.status = event.message; this.snapshot(); }
85
+ }
86
+ }
87
+ async connectDevice(event) {
88
+ const { id } = event;
89
+ if (this.devices.has(id)) this.cancelFor(id);
90
+ const stable = isStableSn(id);
91
+ const category = event.deviceType ?? 'smart-mouse';
92
+ const saved = stable && category === 'smart-mouse' ? await this.store.get(id) : null;
93
+ const device = { id, sn: stable ? id : '', type: category, name: event.name || (category === 'smart-mouse' ? '智能鼠标' : '设备'),
94
+ connection: event.mode === 1 ? 'ble' : 'usb', connectionId: randomUUID(), battery: null,
95
+ identityConfirmed: stable, dpiState: 'unknown', ...saved };
96
+ this.devices.set(id, device);
97
+ this.clearPressed(id);
98
+ this.status = '设备已连接';
99
+ if (saved?.revision > 0) await this.applyDpi(device);
100
+ this.snapshot();
101
+ }
102
+ disconnectDevice({ id, mode }) {
103
+ const device = this.devices.get(id);
104
+ if (!device || device.connection !== (mode === 1 ? 'ble' : 'usb')) return;
105
+ this.cancelFor(id, '设备已断开,语音已取消'); this.devices.delete(id); this.clearPressed(id);
106
+ if (!this.devices.size) this.status = '设备已断开,正在重新查找智能鼠标…';
107
+ this.snapshot();
108
+ }
109
+ async deviceMessage({ id, message }) {
110
+ const device = this.devices.get(id);
111
+ if (message.type === 'warning') { this.publish({ type: 'notice', message: message.text || '鼠标连接异常' }); return; }
112
+ if (message.type === 'queueOverflow') { this.cancel(undefined, '鼠标音频丢失,请重新录音'); return; }
113
+ if (!device) return;
114
+ switch (message.type) {
115
+ case 'deviceInfo': return this.updateDeviceInfo(device, message);
116
+ case 'dpiChanged': return this.reportDpi(device, message.level);
117
+ case 'keyEvent': return this.key(device, message);
129
118
  }
130
119
  }
120
+ async updateDeviceInfo(device, message) {
121
+ if (isStableSn(message.sn) && message.sn !== device.sn) {
122
+ // 只补全临时身份,不合并已确认的设备。
123
+ if (device.identityConfirmed || this.devices.has(message.sn)) {
124
+ device.identityConfirmed = false; this.cancelFor(device.id, '设备 SN 冲突,请重连');
125
+ } else {
126
+ this.devices.delete(device.id); device.sn = message.sn; device.identityConfirmed = true;
127
+ if (device.type === 'smart-mouse') Object.assign(device, await this.store.get(message.sn));
128
+ this.devices.set(device.id, device);
129
+ }
130
+ }
131
+ if (Number.isFinite(message.battery) && message.battery >= 0 && message.battery <= 100) device.battery = message.battery;
132
+ this.snapshot();
133
+ }
134
+ async reportDpi(device, level) {
135
+ if (!Number.isInteger(level) || level < 0 || level > 255) return;
136
+ device.dpiRaw = level;
137
+ // 硬件上报映射与软件下发字节独立。
138
+ const matches = Object.entries(this.dpiReportLevels).filter(([, value]) => value === level);
139
+ if (matches.length === 1 && device.type === 'smart-mouse' && device.identityConfirmed) {
140
+ Object.assign(device, await this.store.reportDpi(device.sn, matches[0][0]));
141
+ device.dpiState = 'reported';
142
+ } else if (device.dpiState === 'reported') device.dpiState = 'unknown';
143
+ this.snapshot();
144
+ }
131
145
  clearPressed(id) { for (const key of this.pressed.keys()) if (key.startsWith(id + ':')) this.pressed.delete(key); }
132
146
  save(sn, revision, preferences) {
133
147
  // Keep UI saves and hardware reports in order so neither overwrites newer state.
@@ -198,7 +212,8 @@ export class DeviceManager {
198
212
  async prepareAi(run) {
199
213
  try {
200
214
  if (!this.aiConversation || !this.desktop) throw new Error('AI 对话功能不可用,请重新加载插件');
201
- await this.action('openAi');
215
+ // Activation failure alone must not abort: with the window tray-hidden the renderer lives on and insertion still works.
216
+ try { await this.action('openAi'); } catch { run.aiActivateFailed = true; }
202
217
  run.lifetime.signal.throwIfAborted();
203
218
  await this.aiConversation.prepare(run);
204
219
  return {};
@@ -271,35 +286,50 @@ export class DeviceManager {
271
286
  }
272
287
  if (this.run !== run || run.closing) return;
273
288
  if (!complete || !run.released) throw new Error('ASR 连接中断,识别结果未完成');
274
- let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
275
- if (!text.trim()) {
276
- this.publish({ type: 'finished', sessionId: run.id });
277
- await this.finish(run);
278
- return;
279
- }
280
- if (run.action === 'translate') {
281
- this.publish({ type: 'phase', sessionId: run.id, phase: 'translating' });
282
- text = await this.translate({ sn: run.sn, service: run.service, text, from: run.preferences.from, to: run.preferences.to, signal: run.lifetime.signal, config: this.config.translation });
283
- }
289
+ await this.complete(run);
290
+ } catch (error) { this.fail(run, error.message || '语音处理失败,请重试'); }
291
+ }
292
+ async complete(run) {
293
+ let text = formatTranscript(run.transcript.finalText(), run.preferences, run.action);
294
+ if (!text.trim()) {
295
+ this.publish({ type: 'finished', sessionId: run.id });
296
+ await this.finish(run);
297
+ return;
298
+ }
299
+ if (run.action === 'translate') {
300
+ this.publish({ type: 'phase', sessionId: run.id, phase: 'translating' });
301
+ text = await this.translate({ sn: run.sn, service: run.service, text, from: run.preferences.from, to: run.preferences.to, signal: run.lifetime.signal, config: this.config.translation });
302
+ }
303
+ if (this.run !== run || run.closing) return;
304
+ if (run.action === 'ai_input') {
305
+ const prepared = await run.aiReady;
284
306
  if (this.run !== run || run.closing) return;
285
- if (run.action === 'ai_input') {
286
- const prepared = await run.aiReady;
287
- if (this.run !== run || run.closing) return;
288
- // Keep the complete text available in the native panel if target preparation/insertion fails.
289
- this.publish({ type: 'preview', sessionId: run.id, text });
307
+ // Keep the complete text available in the native panel if target preparation/insertion fails.
308
+ this.publish({ type: 'preview', sessionId: run.id, text });
309
+ try {
290
310
  if (prepared.error) throw prepared.error;
291
311
  await this.aiConversation.insert(run, text);
292
312
  if (this.run !== run || run.closing) return;
293
- this.publish({ type: 'finished', sessionId: run.id });
294
- } else if (run.action === 'speechSearch') {
295
- await this.action('openUrl', searchAddress(run.preferences.searchUrl, text));
296
- if (this.run !== run || run.closing) return;
297
- this.publish({ type: 'finished', sessionId: run.id });
298
- } else if (this.desktop) {
299
- await this.desktop.complete(run, text);
300
- } else this.publish({ type: 'result', sessionId: run.id, text });
301
- await this.finish(run);
302
- } catch (error) { this.fail(run, error.message || '语音处理失败,请重试'); }
313
+ this.publish(run.aiActivateFailed
314
+ ? { type: 'failed', sessionId: run.id, message: '窗口未唤起,文字已填入对话草稿,可复制结果' }
315
+ : { type: 'finished', sessionId: run.id });
316
+ } catch (error) {
317
+ // On Windows the panel keeps the text so the user can focus any input and submit it there.
318
+ if (this.desktop?.platform === 'win32') {
319
+ this.publish({ type: 'submitOffer', sessionId: run.id, text, message: '请打开需要输入界面' });
320
+ await this.finish(run);
321
+ return;
322
+ }
323
+ throw error;
324
+ }
325
+ } else if (run.action === 'speechSearch') {
326
+ await this.action('openUrl', searchAddress(run.preferences.searchUrl, text));
327
+ if (this.run !== run || run.closing) return;
328
+ this.publish({ type: 'finished', sessionId: run.id });
329
+ } else if (this.desktop) {
330
+ await this.desktop.complete(run, text);
331
+ } else this.publish({ type: 'result', sessionId: run.id, text });
332
+ await this.finish(run);
303
333
  }
304
334
  fail(run, message) {
305
335
  if (this.run !== run || run.closing) return;