@andy.ian/dsh-homing 2.1.7 → 2.1.9

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.
@@ -43,6 +43,7 @@ const isWindows = process.platform === 'win32'
43
43
 
44
44
  let worker = null
45
45
  let workerReader = null
46
+ let workerStderr = ''
46
47
  let workerSeq = 0
47
48
  const workerPending = new Map()
48
49
 
@@ -55,7 +56,7 @@ function ensureWorker() {
55
56
  // stdio 工作进程只被守护进程使用,不需要 token(避免二次鉴权)
56
57
  env: { ...process.env, DSH_AGENT_TOKEN: '' },
57
58
  })
58
- child.stderr.on('data', () => { /* 工作进程 stderr 忽略 */ })
59
+ child.stderr.on('data', (chunk) => { workerStderr = (workerStderr + String(chunk)).slice(-2000) })
59
60
  workerReader = readline.createInterface({ input: child.stdout })
60
61
  workerReader.on('line', (line) => {
61
62
  const text = line.trim()
@@ -84,6 +85,11 @@ function workerCall(request, timeoutMs = 20_000) {
84
85
  return new Promise((resolve) => {
85
86
  const timer = setTimeout(() => {
86
87
  workerPending.delete(id)
88
+ // 工作进程卡死:直接杀掉,下一次请求重建,
89
+ // 否则守护进程会一直卡在坏工作进程上直到空闲退出。
90
+ log('worker timeout, killing' + (workerStderr ? ': ' + workerStderr.replace(/\s+/gu, ' ').slice(-300) : ''))
91
+ try { child.kill() } catch { /* 忽略 */ }
92
+ worker = null
87
93
  resolve({ ok: false, error: 'timeout' })
88
94
  }, timeoutMs)
89
95
  workerPending.set(id, (message) => {
@@ -14,8 +14,11 @@ import fs from 'node:fs'
14
14
  import os from 'node:os'
15
15
  import path from 'node:path'
16
16
  import { promisify } from 'node:util'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { powershellExe } from './exec-path.mjs'
17
19
 
18
20
  const run = promisify(execFile)
21
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
19
22
 
20
23
  // 记录"竖屏是不是我们切过去的",用于崩溃/断开后自动恢复横屏
21
24
  const MARKER = path.join(os.tmpdir(), 'dsh-homing-orientation.json')
@@ -79,18 +82,47 @@ async function rotateMac(mode) {
79
82
  return { ok: true, platform: 'darwin', detail: `${idMatch[1]} -> ${rotation}` }
80
83
  }
81
84
 
82
- async function rotateWindows(mode) {
83
- const { rotateScreen, stopAgent } = await import('./window-remote.mjs')
84
- const result = await rotateScreen(mode)
85
- if (typeof stopAgent === 'function') stopAgent()
86
- return {
87
- ok: result.ok === true && result.result === 0,
88
- platform: 'win32',
89
- detail: `result=${result.result ?? '?'} screen=${result.screenWidth}x${result.screenHeight}`,
90
- screen: { width: result.screenWidth, height: result.screenHeight },
85
+ /** 兜底:不经过窗口代理守护进程,直接起一个一次性 PowerShell 转屏 */
86
+ async function rotateWindowsOneShot(mode) {
87
+ const script = path.join(HERE, 'rotate-screen.ps1')
88
+ try {
89
+ const { stdout } = await run(powershellExe(), ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script, '-Mode', mode], {
90
+ timeout: 15_000,
91
+ windowsHide: true,
92
+ })
93
+ const parsed = JSON.parse(String(stdout).trim().split('\n').pop() || '{}')
94
+ return {
95
+ ok: parsed.ok === true,
96
+ platform: 'win32',
97
+ detail: `one-shot result=${parsed.result ?? '?'} screen=${parsed.width ?? 0}x${parsed.height ?? 0}`,
98
+ screen: { width: Number(parsed.width) || 0, height: Number(parsed.height) || 0 },
99
+ }
100
+ } catch (error) {
101
+ return { ok: false, platform: 'win32', detail: String(error?.stderr ?? error?.message ?? error).slice(0, 200) }
91
102
  }
92
103
  }
93
104
 
105
+ async function rotateWindows(mode) {
106
+ // 优先走窗口代理(复用常驻工作进程),失败/超时则走一次性兜底;
107
+ // 常驻工作进程在锁屏、升级、异常退出等场景可能卡住,不能让它拖死转屏。
108
+ if (process.env.DSH_HOMING_FORCE_ONESHOT_ROTATE === '1') return rotateWindowsOneShot(mode)
109
+ try {
110
+ const { rotateScreen, stopAgent } = await import('./window-remote.mjs')
111
+ const result = await rotateScreen(mode, 6_000)
112
+ if (typeof stopAgent === 'function') stopAgent()
113
+ const screen = result.screen ?? { width: Number(result.screenWidth) || 0, height: Number(result.screenHeight) || 0 }
114
+ if (result.ok === true && result.result === 0) {
115
+ return {
116
+ ok: true,
117
+ platform: 'win32',
118
+ detail: `agent result=0 screen=${screen.width}x${screen.height}`,
119
+ screen,
120
+ }
121
+ }
122
+ } catch { /* 走兜底 */ }
123
+ return rotateWindowsOneShot(mode)
124
+ }
125
+
94
126
  /** 设置屏幕方向:portrait(竖屏)/ landscape(横屏) */
95
127
  export async function setOrientation(mode) {
96
128
  assertMode(mode)
@@ -0,0 +1,63 @@
1
+ param(
2
+ [ValidateSet('portrait', 'landscape')]
3
+ [string]$Mode = 'portrait'
4
+ )
5
+
6
+ # 一次性转屏:不依赖窗口代理守护进程/常驻工作进程。
7
+ # 用法:powershell -NoProfile -NonInteractive -File rotate-screen.ps1 -Mode portrait
8
+ # 输出:单行 JSON { ok, result, width, height }
9
+
10
+ $ErrorActionPreference = 'Stop'
11
+ $angle = if ($Mode -eq 'portrait') { 270 } else { 0 }
12
+
13
+ if (-not ('RotHelper' -as [type])) {
14
+ Add-Type @"
15
+ using System; using System.Runtime.InteropServices;
16
+ public static class RotHelper {
17
+ const int EC=-1; const uint O=0x80,W=0x80000,H=0x100000,REG=1,TEST=2,AT=1,PR=4;
18
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DD { public int cb;
19
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dn;
20
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string ds;
21
+ public uint sf;
22
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string di;
23
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string dk; }
24
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DM {
25
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string n;
26
+ public ushort a,b,c,d; public uint f; public int px,py; public uint o,fo;
27
+ public short cc,dd,yy,tt,co;
28
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string fn;
29
+ public ushort lp; public uint bpp,w,h,fl,fr,icm,icmi,mt,dt,r1,r2,pw,ph; }
30
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplayDevices(string d, uint i, ref DD dd, uint f);
31
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplaySettings(string d, int m, ref DM dm);
32
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int ChangeDisplaySettingsEx(string d, ref DM dm, IntPtr h, uint f, IntPtr l);
33
+ public static string Primary() { for (uint i=0;i<64;i++){ DD dd=new DD(); dd.cb=Marshal.SizeOf(typeof(DD));
34
+ if(!EnumDisplayDevices(null,i,ref dd,0)) break; if((dd.sf&AT)==0) continue; if((dd.sf&PR)!=0) return dd.dn; } return null; }
35
+ public static int Rotate(string dev,int angle){ DM m=new DM(); m.c=(ushort)Marshal.SizeOf(typeof(DM));
36
+ if(!EnumDisplaySettings(dev,EC,ref m)) return -100; int oo=(int)m.o, no=angle/90;
37
+ bool op=oo==1||oo==3, np=no==1||no==3; if(op!=np){uint t=m.w;m.w=m.h;m.h=t;}
38
+ m.o=(uint)no; m.f=O|W|H;
39
+ int t1=ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,TEST,IntPtr.Zero); if(t1!=0) return t1*100;
40
+ return ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,REG,IntPtr.Zero); }
41
+ }
42
+ "@
43
+ }
44
+
45
+ $dev = [RotHelper]::Primary()
46
+ if (-not $dev) {
47
+ '{"ok":false,"result":-101,"width":0,"height":0}'
48
+ exit 0
49
+ }
50
+
51
+ $result = [RotHelper]::Rotate($dev, $angle)
52
+ Start-Sleep -Milliseconds 300
53
+
54
+ $width = 0
55
+ $height = 0
56
+ try {
57
+ Add-Type -AssemblyName System.Windows.Forms | Out-Null
58
+ $bounds = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
59
+ $width = $bounds.Width
60
+ $height = $bounds.Height
61
+ } catch { /* 忽略 */ }
62
+
63
+ @{ ok = ($result -eq 0); result = $result; width = $width; height = $height } | ConvertTo-Json -Compress
@@ -14095,6 +14095,94 @@ RFB.cursors = {
14095
14095
  }
14096
14096
  };
14097
14097
 
14098
+ // D:/deepseek/dsh-homing/plugin/lib/vnc-keyboard.mjs
14099
+ var SPECIAL_KEYS = Object.freeze({
14100
+ Backspace: 65288,
14101
+ Tab: 65289,
14102
+ Enter: 65293,
14103
+ Escape: 65307,
14104
+ Delete: 65535
14105
+ });
14106
+ var SYMBOL_CODES = {
14107
+ " ": "Space",
14108
+ "-": "Minus",
14109
+ "=": "Equal",
14110
+ "[": "BracketLeft",
14111
+ "]": "BracketRight",
14112
+ "\\": "Backslash",
14113
+ ";": "Semicolon",
14114
+ "'": "Quote",
14115
+ "`": "Backquote",
14116
+ ",": "Comma",
14117
+ ".": "Period",
14118
+ "/": "Slash"
14119
+ };
14120
+ var SHIFTED_SYMBOLS = {
14121
+ "!": "1",
14122
+ "@": "2",
14123
+ "#": "3",
14124
+ "$": "4",
14125
+ "%": "5",
14126
+ "^": "6",
14127
+ "&": "7",
14128
+ "*": "8",
14129
+ "(": "9",
14130
+ ")": "0",
14131
+ "_": "-",
14132
+ "+": "=",
14133
+ "{": "[",
14134
+ "}": "]",
14135
+ "|": "\\",
14136
+ ":": ";",
14137
+ '"': "'",
14138
+ "<": ",",
14139
+ ">": ".",
14140
+ "?": "/",
14141
+ "~": "`"
14142
+ };
14143
+ function letterCode(letter) {
14144
+ return "Key" + letter.toUpperCase();
14145
+ }
14146
+ function digitCode(digit) {
14147
+ return "Digit" + digit;
14148
+ }
14149
+ function charToKey(char) {
14150
+ if (typeof char !== "string" || char.length === 0) return null;
14151
+ if (char === "\n" || char === "\r") return { keysym: SPECIAL_KEYS.Enter, code: "Enter", shift: false };
14152
+ if (char === "\b") return { keysym: SPECIAL_KEYS.Backspace, code: "Backspace", shift: false };
14153
+ if (char === " ") return { keysym: 32, code: "Space", shift: false };
14154
+ if (char === " ") return { keysym: SPECIAL_KEYS.Tab, code: "Tab", shift: false };
14155
+ if (SHIFTED_SYMBOLS[char]) {
14156
+ const base = SHIFTED_SYMBOLS[char];
14157
+ return { keysym: base.codePointAt(0), code: symbolCode(base), shift: true };
14158
+ }
14159
+ if (/^[a-z]$/u.test(char)) {
14160
+ return { keysym: char.codePointAt(0), code: letterCode(char), shift: false };
14161
+ }
14162
+ if (/^[A-Z]$/u.test(char)) {
14163
+ return { keysym: char.toLowerCase().codePointAt(0), code: letterCode(char), shift: true };
14164
+ }
14165
+ if (/^[0-9]$/u.test(char)) {
14166
+ return { keysym: char.codePointAt(0), code: digitCode(char), shift: false };
14167
+ }
14168
+ if (SYMBOL_CODES[char]) {
14169
+ return { keysym: char.codePointAt(0), code: SYMBOL_CODES[char], shift: false };
14170
+ }
14171
+ return null;
14172
+ }
14173
+ function symbolCode(char) {
14174
+ if (SYMBOL_CODES[char]) return SYMBOL_CODES[char];
14175
+ if (/^[0-9]$/u.test(char)) return digitCode(char);
14176
+ if (/^[a-z]$/u.test(char)) return letterCode(char);
14177
+ return "Unidentified";
14178
+ }
14179
+ function inputTypeToKey(inputType) {
14180
+ if (inputType === "deleteContentBackward") return { keysym: SPECIAL_KEYS.Backspace, code: "Backspace", shift: false };
14181
+ if (inputType === "deleteContentForward") return { keysym: SPECIAL_KEYS.Delete, code: "Delete", shift: false };
14182
+ if (inputType === "insertLineBreak" || inputType === "insertParagraph") return { keysym: SPECIAL_KEYS.Enter, code: "Enter", shift: false };
14183
+ return null;
14184
+ }
14185
+
14098
14186
  // D:/deepseek/dsh-homing/plugin/lib/vnc-app.js
14099
14187
  var statusEl = document.getElementById("status");
14100
14188
  var passwordEl = document.getElementById("password");
@@ -14286,8 +14374,10 @@ async function fetchWindows() {
14286
14374
  }
14287
14375
  return data.windows || [];
14288
14376
  }
14377
+ var pollPausedUntil = 0;
14289
14378
  async function pollWindows() {
14290
14379
  if (!connected) return;
14380
+ if (Date.now() < pollPausedUntil) return;
14291
14381
  try {
14292
14382
  const windows = await fetchWindows();
14293
14383
  const ids = new Set(windows.map((w) => w.hwnd));
@@ -14314,6 +14404,7 @@ async function pollWindows() {
14314
14404
  if (Date.now() - lastClickAt > 5e3) pendingForeground = null;
14315
14405
  knownWindows = ids;
14316
14406
  } catch {
14407
+ pollPausedUntil = Date.now() + 5e3;
14317
14408
  }
14318
14409
  }
14319
14410
  async function waitForeground(hwnd, timeout = 3e3) {
@@ -14443,6 +14534,72 @@ async function rotateDesktop(mode) {
14443
14534
  setStatus("\u5207\u6362\u5931\u8D25\uFF1A" + (error?.message ?? error), "bad");
14444
14535
  }
14445
14536
  }
14537
+ var keyboardInput = null;
14538
+ function focusKeyboard() {
14539
+ if (!keyboardInput) return;
14540
+ try {
14541
+ keyboardInput.focus({ preventScroll: true });
14542
+ setStatus("\u952E\u76D8\u5DF2\u6253\u5F00\uFF0C\u53EF\u76F4\u63A5\u8F93\u5165\uFF08\u8F93\u5165\u5185\u5BB9\u4F1A\u8F6C\u53D1\u5230\u7535\u8111\uFF09", "ok");
14543
+ } catch {
14544
+ }
14545
+ }
14546
+ function sendMappedKey(key) {
14547
+ if (!rfb || !key) return;
14548
+ try {
14549
+ if (key.shift) rfb.sendKey(KEYS.shift, "ShiftLeft", true);
14550
+ rfb.sendKey(key.keysym, key.code || "Unidentified", true);
14551
+ rfb.sendKey(key.keysym, key.code || "Unidentified", false);
14552
+ if (key.shift) rfb.sendKey(KEYS.shift, "ShiftLeft", false);
14553
+ } catch {
14554
+ }
14555
+ }
14556
+ function setupMobileKeyboard() {
14557
+ if (keyboardInput) return;
14558
+ const input = document.createElement("textarea");
14559
+ input.setAttribute("autocapitalize", "off");
14560
+ input.setAttribute("autocomplete", "off");
14561
+ input.setAttribute("autocorrect", "off");
14562
+ input.setAttribute("spellcheck", "false");
14563
+ input.setAttribute("aria-hidden", "true");
14564
+ input.style.cssText = "position:fixed;left:0;bottom:0;width:1px;height:1px;opacity:0.01;border:0;padding:0;margin:0;resize:none;z-index:2147483647;font-size:16px;background:transparent;color:transparent";
14565
+ const clear = () => {
14566
+ try {
14567
+ input.value = "";
14568
+ } catch {
14569
+ }
14570
+ };
14571
+ input.addEventListener("beforeinput", (event) => {
14572
+ event.preventDefault();
14573
+ const mapped = inputTypeToKey(event.inputType);
14574
+ if (mapped) {
14575
+ sendMappedKey(mapped);
14576
+ clear();
14577
+ return;
14578
+ }
14579
+ if (event.data) {
14580
+ for (const char of event.data) sendMappedKey(charToKey(char));
14581
+ clear();
14582
+ }
14583
+ });
14584
+ input.addEventListener("keydown", (event) => {
14585
+ const specials = {
14586
+ Backspace: SPECIAL_KEYS.Backspace,
14587
+ Enter: SPECIAL_KEYS.Enter,
14588
+ Tab: SPECIAL_KEYS.Tab,
14589
+ Escape: SPECIAL_KEYS.Escape,
14590
+ Delete: SPECIAL_KEYS.Delete
14591
+ };
14592
+ const keysym = specials[event.key];
14593
+ if (keysym) {
14594
+ event.preventDefault();
14595
+ sendMappedKey({ keysym, code: event.key, shift: false });
14596
+ clear();
14597
+ }
14598
+ });
14599
+ input.addEventListener("input", clear);
14600
+ document.body.appendChild(input);
14601
+ keyboardInput = input;
14602
+ }
14446
14603
  function setupToolbar() {
14447
14604
  if (document.getElementById("vnc-toolbar")) return;
14448
14605
  const bar = document.createElement("div");
@@ -14472,11 +14629,13 @@ function setupToolbar() {
14472
14629
  autoBtn,
14473
14630
  button("\u5173\u95ED\u7A97\u53E3", () => pickWindowAction("close")),
14474
14631
  button("\u9000\u51FA\u7A0B\u5E8F", () => pickWindowAction("kill")),
14632
+ button("\u952E\u76D8", () => focusKeyboard()),
14475
14633
  button("Ctrl+Alt+Del", () => {
14476
14634
  try {
14477
14635
  if (rfb && typeof rfb.sendCtrlAltDel === "function") {
14478
14636
  rfb.sendCtrlAltDel();
14479
- setStatus("\u5DF2\u53D1\u9001 Ctrl+Alt+Del\uFF0C\u8BF7\u5728\u9501\u5C4F\u8F93\u5165 PIN", "ok");
14637
+ setStatus("\u5DF2\u53D1\u9001 Ctrl+Alt+Del\uFF0C\u952E\u76D8\u5DF2\u5F39\u51FA\uFF0C\u8F93\u5165 PIN \u5373\u53EF", "ok");
14638
+ setTimeout(focusKeyboard, 300);
14480
14639
  } else {
14481
14640
  setStatus("\u5F53\u524D\u8FDE\u63A5\u4E0D\u652F\u6301\u53D1\u9001 Ctrl+Alt+Del", "bad");
14482
14641
  }
@@ -14498,6 +14657,7 @@ function markClick(event) {
14498
14657
  lastClickAt = Date.now();
14499
14658
  clickBaseForeground = lastForeground;
14500
14659
  pendingForeground = null;
14660
+ if (event && event.pointerType && event.pointerType !== "mouse") focusKeyboard();
14501
14661
  }
14502
14662
  canvasOfGuard();
14503
14663
  function canvasOfGuard() {
@@ -14593,6 +14753,7 @@ window.addEventListener("pagehide", () => {
14593
14753
  }
14594
14754
  }
14595
14755
  });
14756
+ setupMobileKeyboard();
14596
14757
  setupToolbar();
14597
14758
  function autoConnect() {
14598
14759
  if (autoTried) return;
package/lib/vnc-app.js CHANGED
@@ -8,6 +8,7 @@
8
8
  * - 自动切换:点击后若弹出新窗口,自动把视图切到那个窗口
9
9
  */
10
10
  import RFB from './vendor/novnc/core/rfb.js'
11
+ import { charToKey, inputTypeToKey, SPECIAL_KEYS } from './vnc-keyboard.mjs'
11
12
 
12
13
  const statusEl = document.getElementById('status')
13
14
  const passwordEl = document.getElementById('password')
@@ -254,8 +255,11 @@ function refreshWindowView(windows) {
254
255
  if (changed) focusWindowRect(match)
255
256
  }
256
257
 
258
+ let pollPausedUntil = 0
259
+
257
260
  async function pollWindows() {
258
261
  if (!connected) return
262
+ if (Date.now() < pollPausedUntil) return
259
263
  try {
260
264
  const windows = await fetchWindows()
261
265
  const ids = new Set(windows.map((w) => w.hwnd))
@@ -284,7 +288,10 @@ async function pollWindows() {
284
288
  if (Date.now() - lastClickAt > 5000) pendingForeground = null
285
289
 
286
290
  knownWindows = ids
287
- } catch { /* 忽略轮询错误 */ }
291
+ } catch {
292
+ // 窗口代理卡住/超时:暂停轮询 5 秒,别把请求链继续堆满
293
+ pollPausedUntil = Date.now() + 5000
294
+ }
288
295
  }
289
296
 
290
297
  /** 等窗口真正成为前台,最多 timeout 毫秒 */
@@ -416,6 +423,77 @@ async function rotateDesktop(mode) {
416
423
  }
417
424
  }
418
425
 
426
+ let keyboardInput = null
427
+
428
+ /** 弹出手机软键盘(必须是用户手势里调用) */
429
+ function focusKeyboard() {
430
+ if (!keyboardInput) return
431
+ try {
432
+ keyboardInput.focus({ preventScroll: true })
433
+ setStatus('键盘已打开,可直接输入(输入内容会转发到电脑)', 'ok')
434
+ } catch { /* 忽略 */ }
435
+ }
436
+
437
+ function sendMappedKey(key) {
438
+ if (!rfb || !key) return
439
+ try {
440
+ if (key.shift) rfb.sendKey(KEYS.shift, 'ShiftLeft', true)
441
+ rfb.sendKey(key.keysym, key.code || 'Unidentified', true)
442
+ rfb.sendKey(key.keysym, key.code || 'Unidentified', false)
443
+ if (key.shift) rfb.sendKey(KEYS.shift, 'ShiftLeft', false)
444
+ } catch { /* 忽略 */ }
445
+ }
446
+
447
+ /**
448
+ * 手机软键盘桥:
449
+ * canvas 不是输入框,点它不会弹键盘;这里放一个 1px 隐藏 textarea,
450
+ * 把手机键盘的字符/退格/回车转换成 VNC 按键事件。
451
+ */
452
+ function setupMobileKeyboard() {
453
+ if (keyboardInput) return
454
+ const input = document.createElement('textarea')
455
+ input.setAttribute('autocapitalize', 'off')
456
+ input.setAttribute('autocomplete', 'off')
457
+ input.setAttribute('autocorrect', 'off')
458
+ input.setAttribute('spellcheck', 'false')
459
+ input.setAttribute('aria-hidden', 'true')
460
+ input.style.cssText = 'position:fixed;left:0;bottom:0;width:1px;height:1px;opacity:0.01;border:0;padding:0;margin:0;resize:none;z-index:2147483647;font-size:16px;background:transparent;color:transparent'
461
+ const clear = () => { try { input.value = '' } catch { /* 忽略 */ } }
462
+
463
+ input.addEventListener('beforeinput', (event) => {
464
+ event.preventDefault()
465
+ const mapped = inputTypeToKey(event.inputType)
466
+ if (mapped) {
467
+ sendMappedKey(mapped)
468
+ clear()
469
+ return
470
+ }
471
+ if (event.data) {
472
+ for (const char of event.data) sendMappedKey(charToKey(char))
473
+ clear()
474
+ }
475
+ })
476
+ input.addEventListener('keydown', (event) => {
477
+ const specials = {
478
+ Backspace: SPECIAL_KEYS.Backspace,
479
+ Enter: SPECIAL_KEYS.Enter,
480
+ Tab: SPECIAL_KEYS.Tab,
481
+ Escape: SPECIAL_KEYS.Escape,
482
+ Delete: SPECIAL_KEYS.Delete,
483
+ }
484
+ const keysym = specials[event.key]
485
+ if (keysym) {
486
+ event.preventDefault()
487
+ sendMappedKey({ keysym, code: event.key, shift: false })
488
+ clear()
489
+ }
490
+ })
491
+ input.addEventListener('input', clear)
492
+
493
+ document.body.appendChild(input)
494
+ keyboardInput = input
495
+ }
496
+
419
497
  function setupToolbar() {
420
498
  if (document.getElementById('vnc-toolbar')) return
421
499
  const bar = document.createElement('div')
@@ -444,11 +522,14 @@ function setupToolbar() {
444
522
  autoBtn,
445
523
  button('关闭窗口', () => pickWindowAction('close')),
446
524
  button('退出程序', () => pickWindowAction('kill')),
525
+ button('键盘', () => focusKeyboard()),
447
526
  button('Ctrl+Alt+Del', () => {
448
527
  try {
449
528
  if (rfb && typeof rfb.sendCtrlAltDel === 'function') {
450
529
  rfb.sendCtrlAltDel()
451
- setStatus('已发送 Ctrl+Alt+Del,请在锁屏输入 PIN', 'ok')
530
+ setStatus('已发送 Ctrl+Alt+Del,键盘已弹出,输入 PIN 即可', 'ok')
531
+ // 在用户手势中立即聚焦隐藏输入框,手机浏览器才允许弹软键盘
532
+ setTimeout(focusKeyboard, 300)
452
533
  } else {
453
534
  setStatus('当前连接不支持发送 Ctrl+Alt+Del', 'bad')
454
535
  }
@@ -470,6 +551,8 @@ function markClick(event) {
470
551
  lastClickAt = Date.now()
471
552
  clickBaseForeground = lastForeground
472
553
  pendingForeground = null
554
+ // 手机上点画面:顺手把隐藏输入框聚焦,软键盘才会出现
555
+ if (event && event.pointerType && event.pointerType !== 'mouse') focusKeyboard()
473
556
  }
474
557
 
475
558
  canvasOfGuard()
@@ -566,6 +649,7 @@ window.addEventListener('pagehide', () => {
566
649
  if (rfb !== null) { try { rfb.disconnect() } catch { /* 忽略 */ } }
567
650
  })
568
651
 
652
+ setupMobileKeyboard()
569
653
  setupToolbar()
570
654
 
571
655
  function autoConnect() {
package/lib/vnc-boot.js CHANGED
@@ -32,7 +32,7 @@
32
32
 
33
33
  const script = document.createElement('script')
34
34
  script.type = 'module'
35
- script.src = '/vnc/bundle.js?v=41'
35
+ script.src = '/vnc/bundle.js?v=43'
36
36
  script.onload = () => {
37
37
  boot('就绪,点连接')
38
38
  report('bundle-loaded', 'ok')
@@ -0,0 +1,92 @@
1
+ /**
2
+ * 手机软键盘 → VNC 按键映射
3
+ *
4
+ * 背景:VNC 画面是 canvas,手机点它不会弹软键盘;noVNC 只抓物理键盘事件。
5
+ * 方案:页面放一个隐藏 textarea,手机键盘输入后把字符转换成 keysym 发出去。
6
+ */
7
+
8
+ /** 特殊键 keysym(X11) */
9
+ export const SPECIAL_KEYS = Object.freeze({
10
+ Backspace: 0xff08,
11
+ Tab: 0xff09,
12
+ Enter: 0xff0d,
13
+ Escape: 0xff1b,
14
+ Delete: 0xffff,
15
+ })
16
+
17
+ /** 普通符号 → 键位 code(US 键盘) */
18
+ const SYMBOL_CODES = {
19
+ ' ': 'Space',
20
+ '-': 'Minus',
21
+ '=': 'Equal',
22
+ '[': 'BracketLeft',
23
+ ']': 'BracketRight',
24
+ '\\': 'Backslash',
25
+ ';': 'Semicolon',
26
+ "'": 'Quote',
27
+ '`': 'Backquote',
28
+ ',': 'Comma',
29
+ '.': 'Period',
30
+ '/': 'Slash',
31
+ }
32
+
33
+ /** 需要按 Shift 的符号 → 对应的无 Shift 字符 */
34
+ const SHIFTED_SYMBOLS = {
35
+ '!': '1', '@': '2', '#': '3', '$': '4', '%': '5',
36
+ '^': '6', '&': '7', '*': '8', '(': '9', ')': '0',
37
+ '_': '-', '+': '=', '{': '[', '}': ']', '|': '\\',
38
+ ':': ';', '"': "'", '<': ',', '>': '.', '?': '/', '~': '`',
39
+ }
40
+
41
+ function letterCode(letter) {
42
+ return 'Key' + letter.toUpperCase()
43
+ }
44
+
45
+ function digitCode(digit) {
46
+ return 'Digit' + digit
47
+ }
48
+
49
+ /**
50
+ * 单个字符 → { keysym, code, shift }
51
+ * 支持:字母(大小写)、数字、常见符号、空格;不支持的返回 null。
52
+ */
53
+ export function charToKey(char) {
54
+ if (typeof char !== 'string' || char.length === 0) return null
55
+ if (char === '\n' || char === '\r') return { keysym: SPECIAL_KEYS.Enter, code: 'Enter', shift: false }
56
+ if (char === '\b') return { keysym: SPECIAL_KEYS.Backspace, code: 'Backspace', shift: false }
57
+ if (char === ' ') return { keysym: 0x20, code: 'Space', shift: false }
58
+ if (char === '\t') return { keysym: SPECIAL_KEYS.Tab, code: 'Tab', shift: false }
59
+
60
+ if (SHIFTED_SYMBOLS[char]) {
61
+ const base = SHIFTED_SYMBOLS[char]
62
+ return { keysym: base.codePointAt(0), code: symbolCode(base), shift: true }
63
+ }
64
+ if (/^[a-z]$/u.test(char)) {
65
+ return { keysym: char.codePointAt(0), code: letterCode(char), shift: false }
66
+ }
67
+ if (/^[A-Z]$/u.test(char)) {
68
+ return { keysym: char.toLowerCase().codePointAt(0), code: letterCode(char), shift: true }
69
+ }
70
+ if (/^[0-9]$/u.test(char)) {
71
+ return { keysym: char.codePointAt(0), code: digitCode(char), shift: false }
72
+ }
73
+ if (SYMBOL_CODES[char]) {
74
+ return { keysym: char.codePointAt(0), code: SYMBOL_CODES[char], shift: false }
75
+ }
76
+ return null
77
+ }
78
+
79
+ function symbolCode(char) {
80
+ if (SYMBOL_CODES[char]) return SYMBOL_CODES[char]
81
+ if (/^[0-9]$/u.test(char)) return digitCode(char)
82
+ if (/^[a-z]$/u.test(char)) return letterCode(char)
83
+ return 'Unidentified'
84
+ }
85
+
86
+ /** inputType → 特殊键 */
87
+ export function inputTypeToKey(inputType) {
88
+ if (inputType === 'deleteContentBackward') return { keysym: SPECIAL_KEYS.Backspace, code: 'Backspace', shift: false }
89
+ if (inputType === 'deleteContentForward') return { keysym: SPECIAL_KEYS.Delete, code: 'Delete', shift: false }
90
+ if (inputType === 'insertLineBreak' || inputType === 'insertParagraph') return { keysym: SPECIAL_KEYS.Enter, code: 'Enter', shift: false }
91
+ return null
92
+ }
@@ -0,0 +1,450 @@
1
+ # Window sharing agent: line-delimited JSON over stdin/stdout.
2
+ #
3
+ # Request: {"id":"1","cmd":"list"}
4
+ # {"id":"2","cmd":"capture","hwnd":"12345","maxWidth":1280}
5
+ # {"id":"3","cmd":"click","hwnd":"12345","x":100,"y":50,"button":"left"}
6
+ # {"id":"4","cmd":"wheel","hwnd":"12345","delta":-120}
7
+ # {"id":"5","cmd":"key","hwnd":"12345","text":"hello"} or {"keys":["enter","tab"]}
8
+ #
9
+ # Response: {"id":"1","ok":true,"windows":[...]}
10
+ # {"id":"2","ok":true,"width":W,"height":H,"data":"<base64 jpeg>"}
11
+ #
12
+ # ASCII only on purpose: Windows PowerShell 5.1 reads scripts as ANSI,
13
+ # so non-ASCII comments would break parsing without a BOM.
14
+ param(
15
+ [string]$PipeName = '',
16
+ [int]$IdleSeconds = 600
17
+ )
18
+
19
+ $ErrorActionPreference = 'Stop'
20
+ # Force UTF-8 on both pipes so JSON (titles, text input) survives GBK default
21
+ [Console]::InputEncoding = [System.Text.UTF8Encoding]::new($false)
22
+ [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)
23
+ $OutputEncoding = [System.Text.UTF8Encoding]::new($false)
24
+ Add-Type -AssemblyName System.Drawing
25
+ Add-Type @"
26
+ using System;
27
+ using System.Text;
28
+ using System.Runtime.InteropServices;
29
+ public class W32 {
30
+ public delegate bool EnumProc(IntPtr h, IntPtr p);
31
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr p);
32
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
33
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
34
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] public static extern int GetClassNameW(IntPtr h, StringBuilder s, int n);
35
+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);
36
+ [DllImport("user32.dll")] public static extern bool GetClientRect(IntPtr h, out RECT r);
37
+ [DllImport("user32.dll")] public static extern bool ClientToScreen(IntPtr h, ref POINT p);
38
+ [DllImport("user32.dll")] public static extern bool PrintWindow(IntPtr h, IntPtr hdc, uint flags);
39
+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);
40
+ [DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
41
+ [DllImport("user32.dll")] public static extern bool IsZoomed(IntPtr h);
42
+ [DllImport("user32.dll")] public static extern bool SwitchToThisWindow(IntPtr h, bool alt);
43
+ [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h);
44
+ [DllImport("user32.dll")] public static extern bool AttachThreadInput(int from, int to, bool attach);
45
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
46
+ [DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr h, int cmd);
47
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
48
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
49
+ [DllImport("user32.dll")] public static extern void mouse_event(uint flags, int dx, int dy, int data, UIntPtr extra);
50
+ [DllImport("user32.dll")] public static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
51
+ [DllImport("user32.dll")] public static extern bool PostMessageW(IntPtr h, uint msg, IntPtr w, IntPtr l);
52
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
53
+ [StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
54
+ [StructLayout(LayoutKind.Explicit, Size = 40)] public struct INPUT { [FieldOffset(0)] public uint type; [FieldOffset(8)] public KEYBDINPUT ki; }
55
+ [DllImport("user32.dll", SetLastError = true)] public static extern uint SendInput(uint n, INPUT[] p, int cb);
56
+ public static bool SendUnicode(string text) {
57
+ if (string.IsNullOrEmpty(text)) { return true; }
58
+ INPUT[] inputs = new INPUT[text.Length * 2];
59
+ for (int i = 0; i < text.Length; i++) {
60
+ inputs[i * 2].type = 1; inputs[i * 2].ki.wScan = (ushort)text[i]; inputs[i * 2].ki.dwFlags = 0x0004;
61
+ inputs[i * 2 + 1].type = 1; inputs[i * 2 + 1].ki.wScan = (ushort)text[i]; inputs[i * 2 + 1].ki.dwFlags = 0x0004 | 0x0002;
62
+ }
63
+ return SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT))) == (uint)inputs.Length;
64
+ }
65
+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
66
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
67
+ }
68
+ "@
69
+
70
+ $MouseLeftDown = 0x0002
71
+ $MouseLeftUp = 0x0004
72
+ $MouseRightDown = 0x0008
73
+ $MouseRightUp = 0x0010
74
+ $MouseWheel = 0x0800
75
+ $KeyUp = 0x0002
76
+
77
+ function Get-Windows {
78
+ $list = New-Object System.Collections.ArrayList
79
+ $cb = [W32+EnumProc]{
80
+ param($h, $p)
81
+ try {
82
+ if ([W32]::IsWindowVisible($h)) {
83
+ $sb = New-Object System.Text.StringBuilder 512
84
+ [void][W32]::GetWindowTextW($h, $sb, 512)
85
+ $title = $sb.ToString().Trim()
86
+ if ($title.Length -gt 0) {
87
+ $r = New-Object W32+RECT
88
+ [void][W32]::GetWindowRect($h, [ref]$r)
89
+ $w = $r.Right - $r.Left
90
+ $hh = $r.Bottom - $r.Top
91
+ if ($w -gt 120 -and $hh -gt 60) {
92
+ $cls = New-Object System.Text.StringBuilder 256
93
+ [void][W32]::GetClassNameW($h, $cls, 256)
94
+ $procId = 0
95
+ [void][W32]::GetWindowThreadProcessId($h, [ref]$procId)
96
+ $procName = ''
97
+ try { $procName = (Get-Process -Id $procId -ErrorAction SilentlyContinue).ProcessName } catch { $procName = '' }
98
+ [void]$list.Add([pscustomobject]@{
99
+ hwnd = $h.ToInt64().ToString()
100
+ title = $title
101
+ className = $cls.ToString()
102
+ x = $r.Left
103
+ y = $r.Top
104
+ width = $w
105
+ height = $hh
106
+ pid = $procId
107
+ process = $procName
108
+ foreground = ([W32]::GetForegroundWindow() -eq $h)
109
+ })
110
+ }
111
+ }
112
+ }
113
+ } catch { }
114
+ return $true
115
+ }
116
+ [void][W32]::EnumWindows($cb, [IntPtr]::Zero)
117
+ return @($list)
118
+ }
119
+
120
+ function Set-Orientation([string]$mode) {
121
+ $angle = if ($mode -eq 'portrait') { 270 } else { 0 }
122
+ if (-not ('RotHelper' -as [type])) {
123
+ Add-Type @"
124
+ using System; using System.Runtime.InteropServices;
125
+ public static class RotHelper {
126
+ const int EC=-1; const uint O=0x80,W=0x80000,H=0x100000,REG=1,TEST=2,AT=1,PR=4;
127
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DD { public int cb;
128
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string dn;
129
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string ds;
130
+ public uint sf;
131
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string di;
132
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=128)] public string dk; }
133
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct DM {
134
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string n;
135
+ public ushort a,b,c,d; public uint f; public int px,py; public uint o,fo;
136
+ public short cc,dd,yy,tt,co;
137
+ [MarshalAs(UnmanagedType.ByValTStr, SizeConst=32)] public string fn;
138
+ public ushort lp; public uint bpp,w,h,fl,fr,icm,icmi,mt,dt,r1,r2,pw,ph; }
139
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplayDevices(string d, uint i, ref DD dd, uint f);
140
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern bool EnumDisplaySettings(string d, int m, ref DM dm);
141
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern int ChangeDisplaySettingsEx(string d, ref DM dm, IntPtr h, uint f, IntPtr l);
142
+ public static string Primary() { for (uint i=0;i<64;i++){ DD dd=new DD(); dd.cb=Marshal.SizeOf(typeof(DD));
143
+ if(!EnumDisplayDevices(null,i,ref dd,0)) break; if((dd.sf&AT)==0) continue; if((dd.sf&PR)!=0) return dd.dn; } return null; }
144
+ public static int Rotate(string dev,int angle){ DM m=new DM(); m.c=(ushort)Marshal.SizeOf(typeof(DM));
145
+ if(!EnumDisplaySettings(dev,EC,ref m)) return -100; int oo=(int)m.o, no=angle/90;
146
+ bool op=oo==1||oo==3, np=no==1||no==3; if(op!=np){uint t=m.w;m.w=m.h;m.h=t;}
147
+ m.o=(uint)no; m.f=O|W|H;
148
+ int t1=ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,TEST,IntPtr.Zero); if(t1!=0) return t1*100;
149
+ return ChangeDisplaySettingsEx(dev,ref m,IntPtr.Zero,REG,IntPtr.Zero); }
150
+ }
151
+ "@
152
+ }
153
+ $dev = [RotHelper]::Primary()
154
+ if (-not $dev) { return -101 }
155
+ return [RotHelper]::Rotate($dev, $angle)
156
+ }
157
+
158
+ function Set-Foreground([IntPtr]$hwnd) {
159
+ [void][W32]::ShowWindow($hwnd, 9)
160
+ [W32]::keybd_event(0x12, 0, 0, [UIntPtr]::Zero)
161
+ [W32]::keybd_event(0x12, 0, 2, [UIntPtr]::Zero)
162
+ $fgPid = 0
163
+ $targetPid = 0
164
+ $fgThread = [W32]::GetWindowThreadProcessId([W32]::GetForegroundWindow(), [ref]$fgPid)
165
+ $targetThread = [W32]::GetWindowThreadProcessId($hwnd, [ref]$targetPid)
166
+ if ($fgThread -ne 0 -and $targetThread -ne 0 -and $fgThread -ne $targetThread) {
167
+ [void][W32]::AttachThreadInput($fgThread, $targetThread, $true)
168
+ [void][W32]::BringWindowToTop($hwnd)
169
+ [void][W32]::SetForegroundWindow($hwnd)
170
+ [void][W32]::AttachThreadInput($fgThread, $targetThread, $false)
171
+ } else {
172
+ [void][W32]::BringWindowToTop($hwnd)
173
+ [void][W32]::SetForegroundWindow($hwnd)
174
+ }
175
+ if ([W32]::GetForegroundWindow() -ne $hwnd -and $targetPid -gt 0) {
176
+ try { Add-Type -AssemblyName Microsoft.VisualBasic; [Microsoft.VisualBasic.Interaction]::AppActivate($targetPid) } catch { }
177
+ }
178
+ if ([W32]::GetForegroundWindow() -ne $hwnd) { [void][W32]::SwitchToThisWindow($hwnd, $true) }
179
+ for ($i = 0; $i -lt 10; $i += 1) {
180
+ if ([W32]::GetForegroundWindow() -eq $hwnd) { return $true }
181
+ Start-Sleep -Milliseconds 100
182
+ }
183
+ return $false
184
+ }
185
+
186
+ function Get-Hwnd([string]$value) {
187
+ return [IntPtr][Int64]::Parse($value)
188
+ }
189
+
190
+ function Capture-Window([IntPtr]$hwnd, [int]$maxWidth) {
191
+ $r = New-Object W32+RECT
192
+ if (-not [W32]::GetWindowRect($hwnd, [ref]$r)) { throw 'window not found' }
193
+ $w = $r.Right - $r.Left
194
+ $h = $r.Bottom - $r.Top
195
+ if ($w -le 0 -or $h -le 0) { throw 'invalid window size' }
196
+ $bmp = New-Object System.Drawing.Bitmap $w, $h
197
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
198
+ $hdc = $g.GetHdc()
199
+ try {
200
+ # 2 = PW_RENDERFULLCONTENT: capture DWM-composed content
201
+ $ok = [W32]::PrintWindow($hwnd, $hdc, 2)
202
+ } finally {
203
+ $g.ReleaseHdc($hdc)
204
+ $g.Dispose()
205
+ }
206
+ if (-not $ok) { $bmp.Dispose(); throw 'capture failed' }
207
+ if ($maxWidth -gt 0 -and $w -gt $maxWidth) {
208
+ $scale = $maxWidth / $w
209
+ $nw = [int]$maxWidth
210
+ $nh = [int]($h * $scale)
211
+ $small = New-Object System.Drawing.Bitmap $nw, $nh
212
+ $g2 = [System.Drawing.Graphics]::FromImage($small)
213
+ $g2.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]::HighQualityBicubic
214
+ $g2.DrawImage($bmp, 0, 0, $nw, $nh)
215
+ $g2.Dispose()
216
+ $bmp.Dispose()
217
+ $bmp = $small
218
+ }
219
+ $outW = $bmp.Width
220
+ $outH = $bmp.Height
221
+ $ms = New-Object System.IO.MemoryStream
222
+ $codec = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | Where-Object { $_.MimeType -eq 'image/jpeg' }
223
+ $encoderParams = New-Object System.Drawing.Imaging.EncoderParameters 1
224
+ $encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter ([System.Drawing.Imaging.Encoder]::Quality), 70L
225
+ $bmp.Save($ms, $codec, $encoderParams)
226
+ $bmp.Dispose()
227
+ $bytes = $ms.ToArray()
228
+ $ms.Dispose()
229
+ return @{ width = $outW; height = $outH; data = [Convert]::ToBase64String($bytes) }
230
+ }
231
+
232
+ function Client-Point([IntPtr]$hwnd, [int]$x, [int]$y) {
233
+ $pt = New-Object W32+POINT
234
+ $pt.X = $x
235
+ $pt.Y = $y
236
+ [void][W32]::ClientToScreen($hwnd, [ref]$pt)
237
+ return $pt
238
+ }
239
+
240
+ $KEYMAP = @{
241
+ enter = 0x0D; tab = 0x09; esc = 0x1B; backspace = 0x08; delete = 0x2E
242
+ up = 0x26; down = 0x28; left = 0x25; right = 0x27
243
+ ctrl = 0x11; alt = 0x12; shift = 0x10; win = 0x5B
244
+ }
245
+
246
+ [void][W32]::SetProcessDPIAware()
247
+
248
+ function Invoke-AgentLine([string]$line) {
249
+ $response = @{ ok = $false }
250
+ try {
251
+ $req = $line | ConvertFrom-Json
252
+ $expected = [string]$env:DSH_AGENT_TOKEN
253
+ if ($expected -ne '' -and [string]$req.token -ne $expected) { throw 'unauthorized' }
254
+ $response.id = $req.id
255
+ switch ($req.cmd) {
256
+ 'list' {
257
+ $response.ok = $true
258
+ $response.windows = @(Get-Windows)
259
+ $response.screenWidth = [W32]::GetSystemMetrics(0)
260
+ $response.screenHeight = [W32]::GetSystemMetrics(1)
261
+ }
262
+ 'capture' {
263
+ $hwnd = Get-Hwnd $req.hwnd
264
+ $shot = Capture-Window $hwnd ([int]($req.maxWidth))
265
+ $response.ok = $true
266
+ $response.width = $shot.width
267
+ $response.height = $shot.height
268
+ $response.data = $shot.data
269
+ }
270
+ 'open' {
271
+ if (-not $req.path) { throw 'missing path' }
272
+ if (-not (Test-Path -LiteralPath $req.path)) { throw 'file not found' }
273
+ $proc = Start-Process -FilePath $req.path -PassThru
274
+ $baseName = [System.IO.Path]::GetFileNameWithoutExtension($req.path)
275
+ # 等窗口出现,然后恢复并置前(否则会藏在其它窗口后面)
276
+ $target = [IntPtr]::Zero
277
+ for ($i = 0; $i -lt 24; $i += 1) {
278
+ Start-Sleep -Milliseconds 250
279
+ if ($null -ne $proc) { $proc.Refresh() }
280
+ if ($null -ne $proc -and $proc.MainWindowHandle -ne [IntPtr]::Zero) { $target = $proc.MainWindowHandle; break }
281
+ $found = Get-Windows | Where-Object { $_.pid -eq $proc.Id } | Select-Object -First 1
282
+ if ($null -ne $found) { $target = Get-Hwnd $found.hwnd; break }
283
+ if ($baseName.Length -gt 0) {
284
+ $found = Get-Windows | Where-Object { $_.title -like "*$baseName*" } | Select-Object -First 1
285
+ if ($null -ne $found) { $target = Get-Hwnd $found.hwnd; break }
286
+ }
287
+ }
288
+ if ($null -ne $target -and $target -ne [IntPtr]::Zero) {
289
+ [void][W32]::ShowWindow($target, 9)
290
+ [void](Set-Foreground $target)
291
+ }
292
+ $response.ok = $true
293
+ $response.path = $req.path
294
+ $response.pid = if ($null -ne $proc) { $proc.Id } else { 0 }
295
+ $response.hwnd = if ($null -ne $target -and $target -ne [IntPtr]::Zero) { $target.ToInt64().ToString() } else { '' }
296
+ }
297
+ 'close' {
298
+ $hwnd = if ($req.hwnd) { Get-Hwnd $req.hwnd } else { [W32]::GetForegroundWindow() }
299
+ [void][W32]::PostMessageW($hwnd, 0x0010, [IntPtr]::Zero, [IntPtr]::Zero)
300
+ $response.ok = $true
301
+ $response.hwnd = $hwnd.ToInt64().ToString()
302
+ }
303
+ 'kill' {
304
+ $hwnd = Get-Hwnd $req.hwnd
305
+ $procId = 0
306
+ [void][W32]::GetWindowThreadProcessId($hwnd, [ref]$procId)
307
+ if ($procId -le 0) { throw 'cannot resolve pid' }
308
+ $procName = ''
309
+ try { $procName = (Get-Process -Id $procId -ErrorAction Stop).ProcessName } catch { throw 'process not found' }
310
+ $blocked = @('system','idle','registry','smss','csrss','wininit','winlogon','services','lsass','svchost','dwm','explorer','fontdrvhost','spoolsv','audiodg','sihost','ctfmon','deepseek harness','searchhost','startmenuexperiencehost')
311
+ if ($blocked -contains $procName.ToLower()) { throw "protected process: $procName" }
312
+ Stop-Process -Id $procId -Force -ErrorAction Stop
313
+ $response.ok = $true
314
+ $response.pid = $procId
315
+ }
316
+ 'focus' {
317
+ $hwnd = Get-Hwnd $req.hwnd
318
+ $response.ok = Set-Foreground $hwnd
319
+ $response.hwnd = $hwnd.ToInt64().ToString()
320
+ }
321
+ 'rotate' {
322
+ $result = Set-Orientation ([string]$req.mode)
323
+ $response.ok = ($result -eq 0)
324
+ $response.result = $result
325
+ $response.screenWidth = [W32]::GetSystemMetrics(0)
326
+ $response.screenHeight = [W32]::GetSystemMetrics(1)
327
+ }
328
+ 'cursor' {
329
+ Add-Type -AssemblyName System.Windows.Forms
330
+ $pt = [System.Windows.Forms.Cursor]::Position
331
+ $response.ok = $true
332
+ $response.x = $pt.X
333
+ $response.y = $pt.Y
334
+ }
335
+ 'click' {
336
+ $hwnd = Get-Hwnd $req.hwnd
337
+ [void][W32]::SetForegroundWindow($hwnd)
338
+ $pt = Client-Point $hwnd ([int]$req.x) ([int]$req.y)
339
+ [void][W32]::SetCursorPos($pt.X, $pt.Y)
340
+ $btn = [string]$req.button
341
+ if ($btn -eq 'right') {
342
+ [W32]::mouse_event($MouseRightDown, 0, 0, 0, [UIntPtr]::Zero)
343
+ [W32]::mouse_event($MouseRightUp, 0, 0, 0, [UIntPtr]::Zero)
344
+ } else {
345
+ [W32]::mouse_event($MouseLeftDown, 0, 0, 0, [UIntPtr]::Zero)
346
+ [W32]::mouse_event($MouseLeftUp, 0, 0, 0, [UIntPtr]::Zero)
347
+ }
348
+ $response.ok = $true
349
+ }
350
+ 'wheel' {
351
+ $hwnd = Get-Hwnd $req.hwnd
352
+ [void][W32]::SetForegroundWindow($hwnd)
353
+ [W32]::mouse_event($MouseWheel, 0, 0, [int]$req.delta, [UIntPtr]::Zero)
354
+ $response.ok = $true
355
+ }
356
+ 'key' {
357
+ $hwnd = Get-Hwnd $req.hwnd
358
+ [void][W32]::SetForegroundWindow($hwnd)
359
+ if ($req.text) { [void][W32]::SendUnicode([string]$req.text) }
360
+ if ($req.keys) {
361
+ foreach ($name in @($req.keys)) {
362
+ $vk = $KEYMAP[[string]$name]
363
+ if ($null -ne $vk) {
364
+ [W32]::keybd_event([byte]$vk, 0, 0, [UIntPtr]::Zero)
365
+ [W32]::keybd_event([byte]$vk, 0, $KeyUp, [UIntPtr]::Zero)
366
+ }
367
+ }
368
+ }
369
+ $response.ok = $true
370
+ }
371
+ default {
372
+ $response.error = "unknown command: $($req.cmd)"
373
+ }
374
+ }
375
+ } catch {
376
+ $response.ok = $false
377
+ $response.error = $_.Exception.Message
378
+ }
379
+ return ($response | ConvertTo-Json -Compress -Depth 5)
380
+ }
381
+
382
+ function Write-AgentLog([string]$message) {
383
+ try {
384
+ $dir = Join-Path $env:LOCALAPPDATA 'dsh-homing'
385
+ if (-not (Test-Path -LiteralPath $dir)) { [void](New-Item -ItemType Directory -Path $dir -Force) }
386
+ $file = Join-Path $dir 'window-agent.log'
387
+ # 简单轮转:超过 2MB 就改名为 .1(只保留一个备份)
388
+ if ((Test-Path -LiteralPath $file) -and ((Get-Item -LiteralPath $file).Length -gt 2MB)) {
389
+ $backup = Join-Path $dir 'window-agent.log.1'
390
+ if (Test-Path -LiteralPath $backup) { Remove-Item -LiteralPath $backup -Force -ErrorAction SilentlyContinue }
391
+ Move-Item -LiteralPath $file -Destination $backup -Force -ErrorAction SilentlyContinue
392
+ }
393
+ $line = (Get-Date).ToString('s') + ' ' + $message
394
+ Add-Content -LiteralPath $file -Value $line -Encoding UTF8
395
+ } catch { }
396
+ }
397
+
398
+ if ($PipeName -ne '') {
399
+ $stop = $false
400
+ Write-AgentLog ('serve start pipe=' + $PipeName)
401
+ while (-not $stop) {
402
+ $pipe = $null
403
+ try {
404
+ $pipe = New-Object System.IO.Pipes.NamedPipeServerStream($PipeName, [System.IO.Pipes.PipeDirection]::InOut, 1, [System.IO.Pipes.PipeTransmissionMode]::Byte, [System.IO.Pipes.PipeOptions]::Asynchronous)
405
+ } catch {
406
+ Write-AgentLog ('pipe busy: ' + $_.Exception.Message)
407
+ exit 3
408
+ }
409
+ try {
410
+ $task = $pipe.WaitForConnectionAsync()
411
+ if (-not $task.Wait([Math]::Max(1, $IdleSeconds) * 1000)) {
412
+ Write-AgentLog 'idle exit'
413
+ break
414
+ }
415
+ $reader = New-Object System.IO.StreamReader($pipe)
416
+ $writer = New-Object System.IO.StreamWriter($pipe)
417
+ $writer.AutoFlush = $true
418
+ while ($true) {
419
+ $line = $reader.ReadLine()
420
+ if ($null -eq $line) { break }
421
+ if ($line.Trim() -eq '') { continue }
422
+ $out = Invoke-AgentLine $line
423
+ $writer.WriteLine($out)
424
+ try {
425
+ $req = $line | ConvertFrom-Json
426
+ if ($req.cmd -eq 'shutdown' -and [string]$req.token -eq [string]$env:DSH_AGENT_TOKEN) {
427
+ $stop = $true
428
+ break
429
+ }
430
+ } catch { }
431
+ }
432
+ $writer.Dispose()
433
+ $reader.Dispose()
434
+ } catch {
435
+ Write-AgentLog ('client error: ' + $_.Exception.Message)
436
+ } finally {
437
+ if ($null -ne $pipe) { $pipe.Dispose() }
438
+ }
439
+ }
440
+ Write-AgentLog 'serve stop'
441
+ exit 0
442
+ }
443
+
444
+ while ($true) {
445
+ $line = [Console]::In.ReadLine()
446
+ if ($null -eq $line) { break }
447
+ if ($line.Trim() -eq '') { continue }
448
+ [Console]::Out.WriteLine((Invoke-AgentLine $line))
449
+ [Console]::Out.Flush()
450
+ }
@@ -149,6 +149,10 @@ async function rawCall(request, timeoutMs) {
149
149
  return new Promise((resolve) => {
150
150
  const timer = setTimeout(() => {
151
151
  pending.delete(id)
152
+ // 超时说明连接/守护进程可能已卡死:销毁套接字,下一次调用重新拉起
153
+ try { socket?.destroy() } catch { /* 忽略 */ }
154
+ socket = null
155
+ rl = null
152
156
  resolve({ id, ok: false, error: 'timeout' })
153
157
  }, timeoutMs)
154
158
  pending.set(id, (message) => {
@@ -174,15 +178,22 @@ function call(request, timeoutMs = 15_000) {
174
178
  return next
175
179
  }
176
180
 
177
- export const listWindows = async () => {
178
- const result = await call({ cmd: 'list' })
179
- return {
180
- ok: result.ok === true,
181
- windows: Array.isArray(result.windows) ? result.windows : [],
182
- screenWidth: Number(result.screenWidth) || 0,
183
- screenHeight: Number(result.screenHeight) || 0,
184
- error: result.error ?? null,
185
- }
181
+ let listInFlight = null
182
+
183
+ /** 窗口列表:并发调用共享同一个请求,避免轮询把请求链塞满 */
184
+ export const listWindows = () => {
185
+ if (listInFlight !== null) return listInFlight
186
+ listInFlight = (async () => {
187
+ const result = await call({ cmd: 'list' }, 10_000)
188
+ return {
189
+ ok: result.ok === true,
190
+ windows: Array.isArray(result.windows) ? result.windows : [],
191
+ screenWidth: Number(result.screenWidth) || 0,
192
+ screenHeight: Number(result.screenHeight) || 0,
193
+ error: result.error ?? null,
194
+ }
195
+ })()
196
+ return listInFlight.finally(() => { listInFlight = null })
186
197
  }
187
198
 
188
199
  export const captureWindow = async (hwnd, maxWidth = 1280) => {
@@ -200,7 +211,7 @@ export const keyWindow = (hwnd, { text = '', keys = [] } = {}) => call({ cmd: 'k
200
211
  export const focusWindow = (hwnd) => call({ cmd: 'focus', hwnd: String(hwnd) })
201
212
  export const closeWindow = (hwnd = '') => call({ cmd: 'close', hwnd: String(hwnd) })
202
213
  export const killWindow = (hwnd) => call({ cmd: 'kill', hwnd: String(hwnd) })
203
- export const rotateScreen = (mode) => call({ cmd: 'rotate', mode: String(mode) }, 20_000)
214
+ export const rotateScreen = (mode, timeoutMs = 20_000) => call({ cmd: 'rotate', mode: String(mode) }, timeoutMs)
204
215
  export const cursorPos = () => call({ cmd: 'cursor' })
205
216
  export const openPath = (filePath) => call({ cmd: 'open', path: String(filePath) }, 20_000)
206
217
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@andy.ian/dsh-homing",
3
- "version": "2.1.7",
3
+ "version": "2.1.9",
4
4
  "type": "module",
5
5
  "description": "把本机 DSH 通过 SSH 反向隧道安全开放到手机浏览器:TLS 端到端(服务器只透传)、账号 + TOTP、局域网与公网双入口,随 DSH 启动。",
6
6
  "keywords": [
@@ -56,7 +56,8 @@
56
56
  "SECURITY.md",
57
57
  "permissions.json",
58
58
  "bin/window-agent-daemon.mjs",
59
- "bin/inbox.mjs"
59
+ "bin/inbox.mjs",
60
+ "lib/*.ps1"
60
61
  ],
61
62
  "publishConfig": {
62
63
  "access": "public",