@andy.ian/dsh-homing 2.1.8 → 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
@@ -14374,8 +14374,10 @@ async function fetchWindows() {
14374
14374
  }
14375
14375
  return data.windows || [];
14376
14376
  }
14377
+ var pollPausedUntil = 0;
14377
14378
  async function pollWindows() {
14378
14379
  if (!connected) return;
14380
+ if (Date.now() < pollPausedUntil) return;
14379
14381
  try {
14380
14382
  const windows = await fetchWindows();
14381
14383
  const ids = new Set(windows.map((w) => w.hwnd));
@@ -14402,6 +14404,7 @@ async function pollWindows() {
14402
14404
  if (Date.now() - lastClickAt > 5e3) pendingForeground = null;
14403
14405
  knownWindows = ids;
14404
14406
  } catch {
14407
+ pollPausedUntil = Date.now() + 5e3;
14405
14408
  }
14406
14409
  }
14407
14410
  async function waitForeground(hwnd, timeout = 3e3) {
package/lib/vnc-app.js CHANGED
@@ -255,8 +255,11 @@ function refreshWindowView(windows) {
255
255
  if (changed) focusWindowRect(match)
256
256
  }
257
257
 
258
+ let pollPausedUntil = 0
259
+
258
260
  async function pollWindows() {
259
261
  if (!connected) return
262
+ if (Date.now() < pollPausedUntil) return
260
263
  try {
261
264
  const windows = await fetchWindows()
262
265
  const ids = new Set(windows.map((w) => w.hwnd))
@@ -285,7 +288,10 @@ async function pollWindows() {
285
288
  if (Date.now() - lastClickAt > 5000) pendingForeground = null
286
289
 
287
290
  knownWindows = ids
288
- } catch { /* 忽略轮询错误 */ }
291
+ } catch {
292
+ // 窗口代理卡住/超时:暂停轮询 5 秒,别把请求链继续堆满
293
+ pollPausedUntil = Date.now() + 5000
294
+ }
289
295
  }
290
296
 
291
297
  /** 等窗口真正成为前台,最多 timeout 毫秒 */
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=42'
35
+ script.src = '/vnc/bundle.js?v=43'
36
36
  script.onload = () => {
37
37
  boot('就绪,点连接')
38
38
  report('bundle-loaded', 'ok')
@@ -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.8",
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",