dsh-config-sync-plugin 0.4.5 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -677,7 +677,8 @@ Default exclusions (50 entries, edit freely): `*.db` / `*.db-*` / `*.sqlite*` /
677
677
  - The work is done by `runtime\post-exit.ps1 -Phase wait`, which the plugin launches as a **hidden** process to watch for the client exiting; only after it really exits does it start a **visible** `-Phase run` window titled "DSH 配置同步 · 拉取/推送". **No window while queued** — otherwise an empty window would sit in the way from boot to shutdown.
678
678
  - When the repo is not in place yet (empty folder included) the startup check simply skips and does **not** record a failure — an empty folder is only waiting for the first pull.
679
679
  - **Launch pitfalls hit here**: `detached: true` PowerShell exits immediately on Windows (not one log line), so a short-lived PowerShell starts a separate process with `Start-Process -PassThru`; `spawn()` failures are asynchronous (only an `error` event), so the launcher's exit code is awaited and a missing pid fails honestly, logged to `~\.dsh\logs\auto-sync-launch.log`.
680
- - **Waiting for exit cannot rely on pid**: the plugin runs in a child process, so `process.pid` is not the client's main process — pid checks produce "client still running, waiter thinks it exited" and pull mid-run. It matches by process name instead; "closed but processes linger" (measured: 7 processes with `hwnd=0` alive for over a minute) also counts: alive past 60 s with no visible window for 16 s → kill the leftovers, then sync (`auto-sync-wait.log` records it).
680
+ - **Waiting for exit cannot rely on pid**: the plugin runs in a child process, so `process.pid` is not the client's main process — pid checks produce "client still running, waiter thinks it exited" and pull mid-run. It matches by process name instead. Since 0.4.06 "closed but processes linger" is decided by **visible windows, not process age**: once a window has been seen, 3 consecutive zero-window samples are enough to kill the leftovers and start syncing (`auto-sync-wait.log` records it). The old "alive past 60 s with no visible window for 16 s" rule survives only as the fallback for a watcher queued after the window was already gone.
681
+ - **The × close is detected by the backend, not the browser (0.4.06)**: a resident PowerShell sampler reports the visible-window count every 250 ms; "a window was seen, then 4 consecutive zero samples (~1 s)" means the user is closing. The plugin then checks drift once, queues the watcher, and only force-kills the leftover process family **when there is actually pending work** — with nothing to sync the client exits normally (no skipped flush). The `pagehide → sendBeacon` frontend beacon and the 2-minute pre-queue from 0.4.05 stay as backups. Both switches must still be on.
681
682
  - **One sync at a time**: `~\.dsh\auto-sync.lock` records the pid. A startup push and a user-confirmed pull once ran together and rewrote config in parallel; now the later one reads the lock — same kind is reused, a different kind (manual wins) first ends the waiting process that has not started yet, then re-queues.
682
683
  - **Exit uses the whole process family**: `taskkill /PID <main>` (without `/F`) does nothing for the Electron main process (`This process can only be terminated forcefully`), so it uses `/IM "DeepSeek Harness.exe"` and adds `/F` 3.5 s later.
683
684
  - **Clear environment variables before relaunching**: clients started through the plugin chain "quit right after start" three times in a row while the same script in a clean shell succeeded — the difference was the inherited `ELECTRON_RUN_AS_NODE` (plus `ELECTRON_NO_ATTACH_CONSOLE`/`NODE_OPTIONS`/`NODE_PATH`); clearing them worked first try. After start it also counts processes and retries up to 3 times, 8 s each.
@@ -791,6 +792,7 @@ The log shows which path ran: `文件比较(快筛):比对 N 个,深哈
791
792
 
792
793
  | Date | Version | Summary |
793
794
  |---|---|---|
795
+ | 2026-11-25 | 0.4.06 | × close now executes immediately: backend resident window watcher (250ms sampling of visible window count; minimized still counts) treats "window seen, then 4 consecutive zero samples" as the close → checks drift on the spot, queues the watcher, and force-kills leftovers only when there is real work. No frontend dependency. post-exit wait starts after 3 zero samples; stale-watcher yield tightened to ">5 min waited and never saw a window" |
794
796
  | 2026-11-25 | 0.4.05 | Pending push but nothing on × close: root cause frontend beacon not delivered; backend periodic check now pre-queues watcher (no auto-close), runs on window close; frontend beacon demoted to backup |
795
797
  | 2026-11-25 | 0.4.04 | Fix watcher stuck in wait after × close due to windowless orphan process: stale check now looks for a leftover foreground window, clears lock and hands over immediately |
796
798
  | 2026-11-25 | 0.4.03 | Repackaged release: code identical to 0.4.02; only version and release metadata updated to 0.4.03 |
package/README.md CHANGED
@@ -277,6 +277,16 @@ pwsh -File runtime\sync.ps1 pull `
277
277
 
278
278
  「插件更新」卡新增一行 **npm 下载路径**,直接显示实际兜底地址(国内镜像 `registry.npmmirror.com` + 官方 `registry.npmjs.org` 两个源)。GitHub release 整段不通时(国内常见),更新包会自动兜底从 npm 下载;仍按 `version.json` 里的权威 sha256 校验,换源不放宽校验。两个源互为备份:镜像首发同步窗口期会短暂 404,官方源随即兜上。实测 npm tarball 与 GitHub release tgz 是同一份产物、sha256 完全一致。
279
279
 
280
+ ### 点 × 立即执行待推送/待拉取:后端窗口监视(0.4.06)
281
+
282
+ 0.4.05 把「点 × 后没执行」的根因定位到前端信标送不到后端,用 2 分钟定时复查预排 watcher 绕开。但预排有窗口期:用户在两次复查之间点 ×,那一刻既没有预排 watcher、信标又送不到,退出后就什么都不执行。
283
+
284
+ 0.4.06 把这个判断彻底搬到后端,不再依赖任何浏览器事件:插件 apply 时起一个常驻 PowerShell 采样进程,每 250ms 报一次「DeepSeek Harness 的可见窗口数 / 进程总数」。判据是「曾经有过可见窗口,现在连续 4 拍(约 1 秒)一个都没有」——最小化仍有窗口句柄,不算关闭;页面重载不销毁 BrowserWindow,也不会误判。命中后当场调 `triggerAutoSyncOnClose(fast)` 判一次 drift:确有待拉取/待推送才排队 watcher 并强杀残留进程族让它立刻开工,没有待同步内容时绝不强杀,让客户端走正常退出流程(不跳过落盘)。前端信标与 2 分钟预排都保留作双保险。
285
+
286
+ 配套收紧了 watcher 的两条判据:`post-exit.ps1` 的 wait 段改成「可见窗口归零 3 拍即收拾残留进程开工」,不再等 60 秒批次年龄(那正是「点 × 后要等一两分钟才动」的原因);过期 watcher 让位从「WatchPid 消失且无遗留前台窗口」收紧为「等待已超 5 分钟且从未见过窗口」,避免把点 × 后刚排好、正要开工的 watcher 自己让掉。
287
+
288
+ 前提不变:必须勾选「启动时自动拉取」/「退出时自动推送」,否则退出时不做任何同步(0.4.01 起的行为)。
289
+
280
290
  ### 点 × 有待推送却没推送:改后端定时预排 watcher(0.4.05)
281
291
 
282
292
  端到端诊断(手动 POST `/config-sync/auto-exit`)证明后端判据与路由完全正常——立即返回 `queued:true`、排上 watcher、强制退出 DSH 并完成推送。根因在前端:`pagehide → navigator.sendBeacon('/config-sync/auto-exit')` 在 DSH 真正退出时请求送不到后端(launch.log 里点 × 时段无任何信标到达记录),而 0.3.96 起一直依赖它,代码级自测过、真实 UI 却从未验证到。
@@ -655,7 +665,8 @@ DSH 的会话标题会演进:先产生 fallback 临时标题(首条消息截
655
665
  - 动手由插件拉起 `runtime\post-exit.ps1 -Phase wait`(**隐藏**)盯退出;真退了才用 `-WindowStyle Normal` 起 `-Phase run` 的**可见**窗口,标题「DSH 配置同步 · 拉取/推送」。**排队期间不弹窗**。
656
666
  - 仓库还没就位(含空目录)时首检直接跳过,且不记成"检查失败"。
657
667
  - **拉起方式**:`detached: true` 起 powershell 在 Windows 上会当场退出(日志一行都没有),改成短命 powershell 用 `Start-Process -PassThru` 起独立进程;`spawn()` 失败是异步的,所以要等 launcher 退出码、拿不到 pid 就如实失败,并写 `~\.dsh\logs\auto-sync-launch.log`。
658
- - **等退出不能只看 pid**(插件跑在子进程里):改成按进程名;「点了关闭但进程赖着不走」(实测 7 个进程 `hwnd=0` 存活 1 分钟以上)也认——活过 60 秒、无可见窗口持续 16 秒 → 结束残留进程再同步。
668
+ - **等退出不能只看 pid**(插件跑在子进程里):改成按进程名。0.4.06 起「点了关闭但进程赖着不走」改由**可见窗口**判定:见过窗口之后连续 3 拍归零就结束残留进程开工;旧的「活过 60 秒、无可见窗口持续 16 秒」只保留给「窗口在 watcher 启动前就关了」这一种兜底。
669
+ - **点 × 由后端窗口监视识别,不靠浏览器**(0.4.06):常驻采样进程每 250ms 报一次 DeepSeek Harness 的可见窗口数;「见过窗口 + 连续 4 拍归零(约 1 秒)」就是用户在关窗。此时判一次 drift、排好 watcher,**只有确有活要干**才强杀残留进程族;没有待同步内容就让客户端正常退出(不跳过落盘)。前端 `pagehide → sendBeacon` 信标与 0.4.05 的 2 分钟预排都保留作双保险。两个开关仍需勾选。
659
670
  - **一个时刻只跑一次同步**:`~\.dsh\auto-sync.lock` 记 pid,后来者读锁(同种复用,不同种先结束那个没开工的等待进程再改排)。
660
671
  - **退出客户端用整族结束**:`taskkill /PID` 不带 `/F` 对 Electron 主进程无效,改 `/IM "DeepSeek Harness.exe"`,3.5 秒后再补 `/F`。
661
672
  - **重启前清环境变量**:继承的 `ELECTRON_RUN_AS_NODE` / `ELECTRON_NO_ATTACH_CONSOLE` / `NODE_OPTIONS` / `NODE_PATH` 会让客户端"起来就退",清掉后一次成功;启动后数进程、没活等 8 秒重试,最多 3 次。
@@ -773,6 +784,7 @@ pwsh -File sync.ps1 push -ScanHistory
773
784
 
774
785
  | 日期 | 版本 | 要点 |
775
786
  |---|---|---|
787
+ | 2026-11-25 | 0.4.06 | 点 × 立即执行:后端新增常驻窗口监视(250ms 采样可见窗口数,最小化不算),曾经有窗口且连续 4 拍归零即认定关窗 → 当场判 drift、排队 watcher、确有活才强杀残留进程;不依赖前端信标。post-exit wait 归零 3 拍即开工,过期 watcher 让位收紧到「超 5 分钟且从未见过窗口」 |
776
788
  | 2026-11-25 | 0.4.05 | 点 × 有待推送却没推送:根因前端信标未送达,改后端定时复查预排 watcher(不关 DSH),关窗后自动执行;前端信标降为双保险 |
777
789
  | 2026-11-25 | 0.4.04 | 修复点 × 关闭后 push watcher 被无窗口孤儿进程卡在 wait 不执行:过期判定改看有无遗留前台窗口,立即清锁让位 |
778
790
  | 2026-11-25 | 0.4.03 | 重新打包发布:代码与 0.4.02 一致,仅版本与发布元数据更新到 0.4.03 |
package/index.js CHANGED
@@ -1473,6 +1473,13 @@ const autoState = {
1473
1473
  watcherStartedAt: 0,
1474
1474
  timer: null,
1475
1475
  interval: null, // 每 2 分钟的复查(会话/资料是运行中产生的,只判一次会全漏)
1476
+ // 0.4.06:窗口监视。前端信标(pagehide→sendBeacon)在 DSH 真退出时送不到后端,
1477
+ // 所以「点 × 」这个动作改由后端自己看:DSH 曾经有可见窗口、之后一个可见窗口都不剩,
1478
+ // 就是用户在关。这条链路不经过浏览器,DSH 怎么退出都拦不住它。
1479
+ windowTimer: null,
1480
+ windowHadVisible: false,
1481
+ windowZeroTicks: 0,
1482
+ windowFired: false,
1476
1483
  }
1477
1484
 
1478
1485
  function autoScript(dshHome, repo) {
@@ -1802,6 +1809,142 @@ function isProcessAlive(pid) {
1802
1809
  if (!pid) return false
1803
1810
  try { process.kill(pid, 0); return true } catch { return false }
1804
1811
  }
1812
+
1813
+ /**
1814
+ * 0.4.06:后端窗口监视 —— 不依赖前端信标判断「用户点了 ×」。
1815
+ *
1816
+ * 为什么必须放在后端:0.3.96~0.4.05 一直靠 `pagehide → navigator.sendBeacon('/config-sync/auto-exit')`
1817
+ * 通知后端,实测 DSH 真正退出时这个请求根本到不了(launch.log 里点 × 时段没有任何信标到达)。
1818
+ * 0.4.05 加了「2 分钟定时预排」绕开它,但预排有窗口期:用户在两次复查之间点 ×,
1819
+ * 那一刻既没有预排 watcher、信标又送不到 → 退出后什么都不执行。
1820
+ *
1821
+ * 这里用一条和浏览器完全无关的链路补上这个窗口期:起一个常驻 PowerShell 子进程,
1822
+ * 每 250ms 报一次「DeepSeek Harness 里可见窗口数 / 进程总数」。判据是
1823
+ * 「曾经有过可见窗口、现在连续 4 拍(约 1 秒)一个都没有」= 用户在关窗口(最小化不算,最小化仍有窗口句柄)。
1824
+ * 命中后当场判一次 drift、排好 watcher,再强杀残留进程族让 watcher 立刻开工。
1825
+ *
1826
+ * 零副作用保证:窗口从没出现过(CLI / 无窗口启动)时 windowHadVisible 一直是 false,永不触发。
1827
+ * 采样进程带三个退出条件(DSH 全消失 / 宿主消失 / 30 分钟上限),宿主退出后不会留下空转进程。
1828
+ */
1829
+ function startWindowWatcher(config) {
1830
+ if (autoState.windowTimer) return
1831
+ const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
1832
+ const exe = powershellExe()
1833
+ // 一个进程内死循环采样:比每次 spawn 一个 powershell 便宜得多(后者每秒一次会明显吃 CPU)
1834
+ // 采样进程要能活过宿主消失的那一拍:detached + 自带退出条件(宿主没了 / DSH 没了 / 硬上限)。
1835
+ // 否则宿主一退就变成永远转圈的空转进程。
1836
+ const script = [
1837
+ "$ErrorActionPreference = 'SilentlyContinue'",
1838
+ `$parent = ${Number(process.pid) || 0}`,
1839
+ '$parentSeen = $false',
1840
+ '$deadline = (Get-Date).AddMinutes(30)',
1841
+ 'while ($true) {',
1842
+ " $all = @(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue)",
1843
+ ' $vis = @($all | Where-Object { $_.MainWindowHandle -ne 0 }).Count',
1844
+ ' try { Write-Output ("{0} {1}" -f $vis, $all.Count) } catch { break }',
1845
+ ' if ($all.Count -eq 0) { break }',
1846
+ // 父进程存活检查必须「先见过再判死」:首拍查不到(权限/竞态)不能当成已退出,
1847
+ // 否则采样进程刚起来就自杀,窗口归零那一拍永远发不出去。
1848
+ ' if ($parent -gt 0) {',
1849
+ ' if (Get-Process -Id $parent -ErrorAction SilentlyContinue) { $parentSeen = $true }',
1850
+ ' elseif ($parentSeen) { break }',
1851
+ ' }',
1852
+ ' if ((Get-Date) -gt $deadline) { break }',
1853
+ ' Start-Sleep -Milliseconds 250',
1854
+ '}',
1855
+ ].join('\n')
1856
+ let child
1857
+ try {
1858
+ // 必须走 -EncodedCommand:把多行脚本塞进 -Command 在非交互窗口下实测零输出(心跳全丢)。
1859
+ const encoded = Buffer.from(script, 'utf16le').toString('base64')
1860
+ // 绝不能 detached:实测 detached=true 时这条 stdout 管道**一行都收不到**(0 行 vs 12 行)。
1861
+ // 也不需要 detached —— 「窗口归零」那一拍必然发生在宿主还活着的时候(点 × 关的是窗口,不是进程),
1862
+ // 整个判定与排队都在宿主动作,采样进程不需要活过宿主。
1863
+ child = spawn(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
1864
+ { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
1865
+ } catch (error) {
1866
+ logLaunch(dshHome, `窗口监视启动失败:${(error && error.message) || error}`)
1867
+ return
1868
+ }
1869
+ const handle = { stop: () => { try { child.kill() } catch { } } }
1870
+ autoState.windowTimer = handle
1871
+ try { child.unref?.() } catch { }
1872
+
1873
+ let buffer = ''
1874
+ const onSample = (line) => {
1875
+ const m = /^(\d+)\s+(\d+)$/.exec(line)
1876
+ if (!m) return
1877
+ const visible = Number(m[1])
1878
+ const total = Number(m[2])
1879
+ if (visible > 0) {
1880
+ autoState.windowHadVisible = true
1881
+ autoState.windowZeroTicks = 0
1882
+ // 窗口又回来了(用户重新打开 / 重载):允许下一次关闭再触发一次
1883
+ autoState.windowFired = false
1884
+ return
1885
+ }
1886
+ // 进程都不在了:DSH 已经自己退干净,watcher 会按进程名判定开工,这里不用管
1887
+ if (total === 0) return
1888
+ if (!autoState.windowHadVisible) return
1889
+ autoState.windowZeroTicks++
1890
+ // 连续 4 拍(250ms × 4 ≈ 1 秒)都没有可见窗口才算数。
1891
+ // 取 1 秒而不是更长:Electron 关窗到进程族全退只有 1-3 秒,判太慢插件自己就没机会排队了。
1892
+ // 安全性由「曾经见过窗口」保证——页面重载不销毁 BrowserWindow、最小化仍有窗口句柄,
1893
+ // 真正让句柄归零的只有关闭窗口。
1894
+ if (autoState.windowZeroTicks < 4) return
1895
+ if (autoState.windowFired) return
1896
+ autoState.windowFired = true
1897
+ logLaunch(dshHome, `窗口监视:可见窗口已全部关闭(残留进程 ${total} 个),开始判一次自动同步`)
1898
+ onWindowClosedSync(config, dshHome)
1899
+ }
1900
+ child.stdout.on('data', (chunk) => {
1901
+ buffer += String(chunk)
1902
+ let idx = buffer.indexOf('\n')
1903
+ while (idx >= 0) {
1904
+ const line = buffer.slice(0, idx).trim()
1905
+ buffer = buffer.slice(idx + 1)
1906
+ onSample(line)
1907
+ idx = buffer.indexOf('\n')
1908
+ }
1909
+ if (buffer.length > 4096) buffer = ''
1910
+ })
1911
+ child.stderr.on('data', () => { })
1912
+ child.on('error', (error) => {
1913
+ logLaunch(dshHome, `窗口监视进程异常:${(error && error.message) || error}`)
1914
+ try { autoState.windowTimer = null } catch { }
1915
+ })
1916
+ child.on('exit', () => {
1917
+ // 被我们自己 kill(插件卸载)时不要把状态清掉,否则重装会重复挂
1918
+ if (autoState.windowTimer === handle) autoState.windowTimer = null
1919
+ })
1920
+ }
1921
+
1922
+ /**
1923
+ * 「窗口已关闭」那一刻的动作:先判一次是否需要拉取/推送,需要就排队,再强杀残留进程族。
1924
+ *
1925
+ * forceClose 只在**确实有活要干**时才做(排上了 / 复用了已排队的 watcher)。没有待同步内容时
1926
+ * 让 DSH 自己走正常退出流程,绝不无端强杀 —— 强杀会跳过客户端自己的落盘。
1927
+ */
1928
+ async function onWindowClosedSync(config, dshHome) {
1929
+ try {
1930
+ const pendingAlive = autoState.pending && isProcessAlive(autoState.pending.watcherPid)
1931
+ if (pendingAlive) {
1932
+ logLaunch(dshHome, `窗口监视:复用已排队的 ${autoState.pending.mode},强杀残留进程让它开工`)
1933
+ forceCloseDshDetached(config)
1934
+ return
1935
+ }
1936
+ const result = await triggerAutoSyncOnClose(config, { fast: true })
1937
+ const mode = result && result.mode ? result.mode : ''
1938
+ if (result && (result.queued || result.reused)) {
1939
+ logLaunch(dshHome, `窗口监视:已排队 ${mode}(${result.queued ? '新排' : '复用'}),强杀残留进程让它开工`)
1940
+ forceCloseDshDetached(config)
1941
+ return
1942
+ }
1943
+ logLaunch(dshHome, `窗口监视:没有待拉取/待推送(${(result && result.reason) || 'no_action_needed'}),不强制退出`)
1944
+ } catch (error) {
1945
+ logLaunch(dshHome, `窗口监视:处理失败 ${(error && error.message) || error}`)
1946
+ }
1947
+ }
1805
1948
  const STATE_NAME = 'config-sync-state.json'
1806
1949
 
1807
1950
  /**
@@ -4832,6 +4975,15 @@ export function apply(ctx, config) {
4832
4975
  })
4833
4976
  // 开关打开才排一次启动检查(默认关 = 什么都不做)
4834
4977
  scheduleAutoStart(config)
4978
+ // 0.4.06:后端窗口监视。点 × 这个动作由后端自己看(可见窗口归零),不依赖前端信标。
4979
+ startWindowWatcher(config)
4980
+ try {
4981
+ ctx.effect(() => () => {
4982
+ const w = autoState.windowTimer
4983
+ try { w && w.stop && w.stop() } catch { }
4984
+ autoState.windowTimer = null
4985
+ })
4986
+ } catch { }
4835
4987
  // 云端探测预热:插件一装上就去探一次(不阻塞、不 await)。这样面板打开时缓存多半已经热了,
4836
4988
  // status 不用再为首屏那 2.5 秒的 ls-remote 埋单。
4837
4989
  typeof setTimeout === 'function' ? setTimeout(() => { try { warmRemoteProbe(config) } catch { } }, 300) : null
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-sync-plugin",
3
- "version": "0.4.05",
3
+ "version": "0.4.06",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
@@ -47,6 +47,7 @@ param(
47
47
  # 用户从开机到关窗口这段时间会一直挂着一个"等 DSH 退出"的黑窗,什么也干不了还挡着视线。
48
48
  if ($Phase -eq 'wait') {
49
49
  $deadline = (Get-Date).AddMinutes($MaxWaitMinutes)
50
+ $waitStart = Get-Date
50
51
  $noWindowTicks = 0
51
52
  $waitLog = Join-Path $DshHome 'logs\auto-sync-wait.log'
52
53
  function WaitLog([string]$text) {
@@ -57,6 +58,12 @@ if ($Phase -eq 'wait') {
57
58
  } catch { }
58
59
  }
59
60
  WaitLog ("等待开始(pid {0})" -f $WatchPid)
61
+ # 0.4.06:不再只靠「进程数归零」判退出。实测点 × 后进程族常残留(无窗口但活着),
62
+ # 旧逻辑要等 60 秒批次年龄 + 连续 16 秒才动手,用户以为没生效。
63
+ # 这里改成和进程年龄无关的判据:曾经出现过可见窗口、之后连续 3 次(约 6 秒)一个都没有
64
+ # → 认定用户在关窗,直接收掉残留进程族开工。最小化不影响(最小化仍有窗口句柄)。
65
+ $hadVisible = $false
66
+ $visZeroTicks = 0
60
67
  while ($true) {
61
68
  # 按**进程名**判断,而不是只看传进来的 pid:插件传的 pid 未必是「那个活着的客户端」——
62
69
  # 实测出现过 watchPid 对应的进程早就不在了、而客户端明明还在跑,等待态于是当场开工,
@@ -65,48 +72,70 @@ if ($Phase -eq 'wait') {
65
72
  $byPid = if ($WatchPid -gt 0) { Get-Process -Id $WatchPid -ErrorAction SilentlyContinue } else { $null }
66
73
  if ($byName.Count -eq 0 -and -not $byPid) { WaitLog 'DSH 已完全退出'; break }
67
74
 
68
- # 僵死 watcher 自清:WatchPid(排队那次的 DSH)已经退出,但进程名还有实例 ——
69
- # 若这些实例全部是本 watcher 启动之后才起来的,说明我们等的那次 DSH 早就退出并重启过了,
70
- # 本 watcher 属于上一代残留。继续等只会被「进程名还有新实例」挡住、死等 30 分钟还霸占锁,
71
- # 让新排的 watcher(带当前 DSH pid)无法复用/接管。这里主动退出并清锁,把位置让出来。
72
- # 正常场景不会误伤:排队时 DSH 已在运行,其进程启动时间一定早于本 watcher。
73
- if ($WatchPid -gt 0 -and -not $byPid -and $byName.Count -gt 0) {
74
- $myStart = (Get-Process -Id $PID -ErrorAction SilentlyContinue).StartTime
75
- if ($myStart) {
76
- # 0.4.04:原判据「所有 DSH 都比 watcher 新」会被**无窗口的孤儿进程**破坏——
77
- # 实测 WatchPid 被强杀后留下一个比 watcher 还早启动的子进程(父已死、hwnd=0),
78
- # 它既不是用户在用的实例、也不会消失,把 newerAll.Count -eq byName.Count 永远卡死,
79
- # watcher 死等 30 分钟还霸占 auto-sync.lock。真正代表「排队那次 DSH 还在用」的,
80
- # 是比 watcher 早启动**且有前台窗口**的实例;无窗口残留/新实例都不该挡住让位。
81
- $visibleOld = @($byName | Where-Object { $_.MainWindowHandle -ne 0 -and $_.StartTime -and $_.StartTime -lt $myStart })
82
- if ($visibleOld.Count -eq 0) {
83
- WaitLog ('WatchPid {0} 已退出,无遗留前台窗口(现存为残留进程或新实例),判定为过期 watcher,退出让位' -f $WatchPid)
84
- try {
85
- $lockFile = Join-Path $DshHome 'auto-sync.lock'
86
- if (Test-Path -LiteralPath $lockFile) {
87
- $lock = Get-Content -LiteralPath $lockFile -Raw -Encoding utf8 | ConvertFrom-Json
88
- if ($lock -and $lock.pid -eq $PID) { Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue }
89
- }
90
- } catch { }
91
- exit 3
75
+ # 0.4.06:可见窗口判据(优先于年龄判据)
76
+ # A. 本 watcher 亲眼见过窗口 → 连续 3 拍(约 6 秒)归零就动手:这是「点 × 」最常见的路径。
77
+ # B. 没见过窗口(排队后窗口先关掉了)→ 退回「无可见窗口 + 进程已活过 25 秒」累计 8 拍(约 16 秒)。
78
+ # 加 25 秒下限是为了不把「客户端刚启动、窗口还没建出来」误判成关闭。
79
+ $visNow = @($byName | Where-Object { $_.MainWindowHandle -ne 0 })
80
+ if ($visNow.Count -gt 0) {
81
+ $hadVisible = $true
82
+ $visZeroTicks = 0
83
+ $noWindowTicks = 0
84
+ } elseif ($byName.Count -gt 0) {
85
+ if ($hadVisible) {
86
+ $visZeroTicks++
87
+ if ($visZeroTicks -ge 3) {
88
+ WaitLog '可见窗口已全部关闭(进程仍残留),强制结束残留进程族后开工'
89
+ try { Stop-Process -Name 'DeepSeek Harness' -Force -ErrorAction SilentlyContinue } catch { }
90
+ Start-Sleep -Seconds 3
91
+ if (@(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue).Count -eq 0) { WaitLog '已全部结束'; break }
92
+ $visZeroTicks = 0
93
+ }
94
+ } else {
95
+ $newest = $byName | Sort-Object StartTime -Descending | Select-Object -First 1
96
+ $ageSec = if ($newest -and $newest.StartTime) { ((Get-Date) - $newest.StartTime).TotalSeconds } else { 0 }
97
+ if ($ageSec -gt 25) { $noWindowTicks++ } else { $noWindowTicks = 0 }
98
+ if ($noWindowTicks -ge 8) {
99
+ WaitLog '前台窗口已关闭且进程不退,强制结束残留进程'
100
+ try { Stop-Process -Name 'DeepSeek Harness' -Force -ErrorAction SilentlyContinue } catch { }
101
+ Start-Sleep -Seconds 3
102
+ if (@(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue).Count -eq 0) { WaitLog '已全部结束'; break }
103
+ $noWindowTicks = 0
92
104
  }
93
105
  }
94
106
  }
95
107
 
96
- # 用户点了窗口右上角的关闭、前台窗口全没了,但进程赖着不走(实测 7 个进程全部 hwnd=0 还活着)。
97
- # 不能只看「曾经出现过窗口」——等待进程可能是在窗口关掉之后才起来的(实测就这么漏判了),
98
- # 改用批次年龄:这批客户端进程已经活了 60 秒以上、却一个可见窗口都没有 → 认定用户已关闭。
99
- $visible = @($byName | Where-Object { $_.MainWindowHandle -ne 0 })
100
- $newest = $byName | Sort-Object StartTime -Descending | Select-Object -First 1
101
- $ageSec = if ($newest -and $newest.StartTime) { ((Get-Date) - $newest.StartTime).TotalSeconds } else { 0 }
102
- if ($visible.Count -eq 0 -and $ageSec -gt 60) { $noWindowTicks++ } else { $noWindowTicks = 0 }
103
- if ($noWindowTicks -ge 8) {
104
- WaitLog '前台窗口已关闭且进程不退,强制结束残留进程'
105
- try { Stop-Process -Name 'DeepSeek Harness' -Force -ErrorAction SilentlyContinue } catch { }
106
- Start-Sleep -Seconds 3
107
- if (@(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue).Count -eq 0) { WaitLog '已全部结束'; break }
108
- $noWindowTicks = 0
108
+ # 僵死 watcher 自清:只处理「排队那次的 DSH 早就退出并重启过」这一种情况。
109
+ # 0.4.06 加了可见窗口判据之后这里要收紧:点 × 后 WatchPid 立即消失、进程族还在,
110
+ # 原来的「没有比 watcher 更早的可见窗口就 exit 3」会把**正准备开工的本次 watcher**
111
+ # 直接让掉(窗口本来就刚关掉)。所以只有在「现存实例全是新实例」且「等待已超过 5 分钟」时
112
+ # 才认定自己是上一代残留,否则一律继续等,由上面的窗口判据接手开工。
113
+ if ($WatchPid -gt 0 -and -not $byPid -and $byName.Count -gt 0 -and -not $hadVisible) {
114
+ $waited = ((Get-Date) - $waitStart).TotalSeconds
115
+ if ($waited -gt 300) {
116
+ $myStart = (Get-Process -Id $PID -ErrorAction SilentlyContinue).StartTime
117
+ if ($myStart) {
118
+ # 0.4.04:原判据「所有 DSH 都比 watcher 新」会被**无窗口的孤儿进程**破坏——
119
+ # 实测 WatchPid 被强杀后留下一个比 watcher 还早启动的子进程(父已死、hwnd=0),
120
+ # 它既不是用户在用的实例、也不会消失,把 newerAll.Count -eq byName.Count 永远卡死,
121
+ # watcher 死等 30 分钟还霸占 auto-sync.lock。真正代表「排队那次 DSH 还在用」的,
122
+ # 是比 watcher 早启动**且有前台窗口**的实例;无窗口残留/新实例都不该挡住让位。
123
+ $visibleOld = @($byName | Where-Object { $_.MainWindowHandle -ne 0 -and $_.StartTime -and $_.StartTime -lt $myStart })
124
+ if ($visibleOld.Count -eq 0) {
125
+ WaitLog ('WatchPid {0} 已退出超过 5 分钟,无遗留前台窗口(现存为残留进程或新实例),判定为过期 watcher,退出让位' -f $WatchPid)
126
+ try {
127
+ $lockFile = Join-Path $DshHome 'auto-sync.lock'
128
+ if (Test-Path -LiteralPath $lockFile) {
129
+ $lock = Get-Content -LiteralPath $lockFile -Raw -Encoding utf8 | ConvertFrom-Json
130
+ if ($lock -and $lock.pid -eq $PID) { Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue }
131
+ }
132
+ } catch { }
133
+ exit 3
134
+ }
135
+ }
136
+ }
109
137
  }
138
+
110
139
  if ((Get-Date) -gt $deadline) { WaitLog '等待超时,放弃本次同步'; exit 2 }
111
140
  Start-Sleep -Seconds 2
112
141
  }
@@ -1981,5 +1981,43 @@ console.log('== 0.4.05:定时复查预排 watcher,不依赖前端信标 ==')
1981
1981
  check('已排队守卫检查 watcher 存活(超时后可重排)',
1982
1982
  /autoState\.pending && isProcessAlive\(autoState\.pending\.watcherPid\)/.test(idxSrc), 'index.js 存活守卫')
1983
1983
  }
1984
+ console.log('')
1985
+ console.log('== 0.4.06:点 × 由后端窗口监视触发(不依赖前端信标),watcher 窗口一消失就开工 ==')
1986
+ {
1987
+ const idxSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1988
+ const postSrc = existsSync(join(pluginRuntime, 'post-exit.ps1'))
1989
+ ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
1990
+ check('新增 startWindowWatcher:常驻采样可见窗口数',
1991
+ /function startWindowWatcher\(config\)/.test(idxSrc)
1992
+ && idxSrc.includes("Get-Process -Name 'DeepSeek Harness'")
1993
+ && idxSrc.includes('MainWindowHandle -ne 0'), 'index.js 窗口监视')
1994
+ check('窗口监视 apply 时启动、卸载时回收',
1995
+ /startWindowWatcher\(config\)/.test(idxSrc)
1996
+ && /autoState\.windowTimer = null/.test(idxSrc), 'index.js 生命周期')
1997
+ check('关闭判据:曾经有窗口 + 连续 4 拍归零(最小化不算)',
1998
+ /autoState\.windowHadVisible = true/.test(idxSrc)
1999
+ && /autoState\.windowZeroTicks < 4/.test(idxSrc), 'index.js 归零判据')
2000
+ check('采样进程自带退出条件(DSH 全消失 / 宿主消失 / 时限)',
2001
+ idxSrc.includes('if ($all.Count -eq 0) { break }')
2002
+ && idxSrc.includes('(Get-Date) -gt $deadline'), 'index.js 采样进程退出条件')
2003
+ check('采样进程不得 detached(实测 detached 时 stdout 全丢,心跳为 0 行)',
2004
+ /detached: true/.test(idxSrc.split('function startWindowWatcher')[1]?.split('async function onWindowClosedSync')[0] || '')
2005
+ ? false : true, 'index.js 采样进程非 detached')
2006
+ check('父进程判死必须先见过父进程(首拍查不到不能自杀)',
2007
+ idxSrc.includes('$parentSeen = $false') && idxSrc.includes('elseif ($parentSeen) { break }'), 'index.js 父进程判死')
2008
+ check('命中后先判一次同步再强杀,且只在有待同步时才强杀',
2009
+ /async function onWindowClosedSync/.test(idxSrc)
2010
+ && /result\.queued \|\| result\.reused/.test(idxSrc)
2011
+ && /没有待拉取\/待推送/.test(idxSrc), 'index.js 按需强杀')
2012
+ check('没有可见窗口出现过(CLI/无窗口启动)永不触发',
2013
+ /if \(!autoState\.windowHadVisible\) return/.test(idxSrc), 'index.js 无窗口不触发')
2014
+ check('post-exit wait:可见窗口归零即收拾进程族,不再等 60 秒批次年龄',
2015
+ postSrc.includes('$hadVisible = $false')
2016
+ && postSrc.includes('$visZeroTicks -ge 3')
2017
+ && postSrc.includes('可见窗口已全部关闭'), 'post-exit.ps1 wait 判据')
2018
+ check('过期 watcher 让位收紧:必须等待超过 5 分钟且没见过窗口',
2019
+ postSrc.includes('$waited -gt 300')
2020
+ && postSrc.includes('-and -not $hadVisible'), 'post-exit.ps1 让位收紧')
2021
+ }
1984
2022
  process.exit(failures === 0 ? 0 : 1)
1985
2023