dsh-config-sync-plugin 0.3.95 → 0.3.97

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
@@ -257,6 +257,22 @@ Two display fixes on top of 0.3.77:
257
257
 
258
258
  The "Plugin update" card now shows an **npm download URL** line with the actual fallback addresses (domestic mirror `registry.npmmirror.com` + official `registry.npmjs.org`). When the GitHub release download is unreachable (common in mainland China), the update package automatically falls back to npm. It is still verified against the authoritative sha256 in `version.json` — switching source never relaxes verification. The two sources back each other up: the mirror can briefly 404 during its first-sync window, and the official source takes over. The npm tarball is byte-identical to the GitHub release tgz (same sha256).
259
259
 
260
+ ### Clicking × with pending changes now actively exits DSH and syncs immediately (0.3.97)
261
+
262
+ In 0.3.96 the beacon could "check once on × and queue the watcher", but the watcher then sat in `wait`, **passively waiting for all DSH processes to disappear** before working. In practice clicking × leaves 7 orphaned processes (the plugin itself runs in one of them, the host child), so the normal close path often fails to clean up and the watcher just idles until its 30-minute timeout — appearing as "queued but nothing happens". This version closes the last gap:
263
+
264
+ 1. **Active force-exit**: once `triggerAutoSyncOnClose` returns `queued:true` (there really are pending pull/push), `handleAutoExit` immediately calls `forceCloseDshDetached` — from an **independent detached process** it runs `taskkill /IM "DeepSeek Harness.exe" /F` to kill the whole process family (with a `ping -n 3` ~2s grace period for the normal close to flush state first). This must run in a separate process: force-killing takes down the plugin itself (host child), so no `setTimeout` inside the plugin process would survive long enough to fire.
265
+ 2. **Only when something is actually pending**: guarded by `if (result && result.queued)` — clicking × with nothing to sync won't kill DSH; with pending changes, exit + pull/push happen in one shot.
266
+ 3. **Regression guards**: selftest asserts the detached force-kill, `/IM /F`, the call after queuing, and the queued guard.
267
+
268
+ ### Page-unload beacon replaces the Electron close hook, finally fixing "× does not trigger" (0.3.96)
269
+
270
+ After 0.3.95 fixed the BOM (watcher no longer crashes on launch), the real culprit behind "closing × still does not trigger" surfaced: **the Electron close hook never got installed**. Two ironclad facts — the plugin actually runs in the host child process (`dsh-desktop-host`, a `--expose-internals` node process), so `require('electron')` has no `app`, `electronApp()` returns null and `installQuitWhenAllWindowsClosed` bails at `if (!el) return`; and even if it had `el`, `browser-window-created` fired long before plugin `apply`, so that event never fires again and the `closed` callback never runs. So the "check once on ×" chain added in 0.3.93 **never actually ran** (no new watcher in launch.log, zero hook logs). This version changes tack completely:
271
+
272
+ 1. **Front-end unload beacon**: `client.js` installs `pagehide` + `beforeunload` listeners in `apply()`; on page unload (× / tab close / process exit) it fires `navigator.sendBeacon('/config-sync/auto-exit')`, a fire-and-forget request — no Electron events involved. Fully `typeof`-guarded; environments without `navigator.sendBeacon` silently skip.
273
+ 2. **Backend fast check**: new `/config-sync/auto-exit` route; `handleAutoExit` calls `triggerAutoSyncOnClose(config, { fast: true })`. Fast mode reads only the local tracking ref (`rev-list HEAD...origin/branch`, milliseconds) for ahead/behind, **never `git fetch`** — once the beacon arrives the plugin process can be killed at any moment by DSH exiting, so there is no time for a seconds-long network fetch; pull/push criteria match the startup recheck, pull takes priority. It returns right after queuing the watcher; the real pull/push runs from the independently surviving `post-exit.ps1` after all DSH processes exit.
274
+ 3. **Regression guards**: selftest asserts the new route/handler/fast branch/no-fetch, clientcheck asserts `sendBeacon` and the typeof guards. All 0.3.93/0.3.94/0.3.95 fixes retained.
275
+
260
276
  ### Fix post-exit.ps1 missing UTF-8 BOM, which crashed every queued sync (0.3.95)
261
277
 
262
278
  The final root cause behind "auto pull/push enabled, clicking × still triggers nothing" was neither the queue logic nor the close hook — it was the **encoding of the executor script**. When 0.3.94 edited `post-exit.ps1`, the write tool stripped the leading **UTF-8 BOM (`EF BB BF`)**. Windows PowerShell 5.1 decodes a BOM-less Chinese UTF-8 script as GBK, turns full-width Chinese parentheses into quote characters, and fails with 55 syntax errors the moment the script starts. Result: the watcher was queued (`auto-sync-launch.log` logged "started"), but `auto-sync-wait.log` never got a new "waiting started" line — every queued sync (startup check, 2-minute recheck, ×-close trigger) crashed on launch, appearing as "nothing ever triggers".
@@ -729,6 +745,8 @@ The log shows which path ran: `文件比较(快筛):比对 N 个,深哈
729
745
 
730
746
  | Date | Version | Summary |
731
747
  |---|---|---|
748
+ | 2026-11-25 | 0.3.97 | Clicking × with pending pull/push actively force-kills the DSH process family from a detached process (detached taskkill /F); the watcher runs immediately instead of waiting for orphaned processes |
749
+ | 2026-11-24 | 0.3.96 | Page-unload beacon (pagehide→sendBeacon /auto-exit) replaces the dead Electron close hook; fast check (local tracking ref, no fetch) queues the watcher in milliseconds, finally fixing "× does not trigger" |
732
750
  | 2026-11-24 | 0.3.95 | Fix post-exit.ps1 losing UTF-8 BOM (PS5.1 decoded as GBK, 55 syntax errors, crashed on launch): restored BOM on all three executors, selftest adds full ps1 BOM assertion to prevent regression |
733
751
  | 2026-11-24 | 0.3.94 | Fix cross-restart stale watchers holding the lock: lock records watchPid, reuse checks staleness, stale locks are killed and re-queued; post-exit wait self-clears stale watchers; fixes "switches on, clicking × still triggers nothing" |
734
752
  | 2026-11-24 | 0.3.93 | Clicking × to close DSH now checks once for auto pull/push and queues the watcher immediately (no more waiting for the 2-minute window); autoRestart semantics unified to !== false |
package/README.md CHANGED
@@ -277,6 +277,22 @@ 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
+ ### 点 × 检测到待同步就主动退出 DSH 并立即执行(0.3.97)
281
+
282
+ 0.3.96 的信标已经能「点 × 判一次并排好 watcher」,但 watcher 进入 `wait` 后是**被动等 DSH 进程全部消失**才开工。实测点 × 后 DSH 常残留 7 个进程(插件就跑在其中的 host 子进程里),单靠正常关闭流程经常关不干净,watcher 只能干等到 30 分钟超时——表现为「排了队但迟迟不动」。这次补上最后一环:
283
+
284
+ 1. **主动强制退出**:`handleAutoExit` 一旦 `triggerAutoSyncOnClose` 返回 `queued:true`(确实有待拉取/待推送),立即调 `forceCloseDshDetached`——从**独立 detached 进程**用 `taskkill /IM "DeepSeek Harness.exe" /F` 整族强杀(中间用 `ping -n 3` 留 2 秒给正常关闭落盘)。必须在独立进程里做:强杀会把插件自己(host 子进程)也带走,任何挂在插件进程内的 `setTimeout` 都来不及执行。
285
+ 2. **只在真有待同步时才退出**:`if (result && result.queued)` 守卫——没待同步就点 × 不会误杀 DSH;有待同步才「退出 + 拉取/推送」一气呵成。
286
+ 3. **防回归**:selftest 断言 detached 强杀、`/IM /F`、排队后调用与 queued 守卫。
287
+
288
+ ### 页面卸载信标取代 Electron 关窗钩子,真正修好「点 × 不触发」(0.3.96)
289
+
290
+ 0.3.95 修好 BOM(watcher 不再启动即崩)后,「点 × 还是不触发」的真凶才浮出水面:**Electron 关窗钩子根本没装成功**。两条铁证——插件实际跑在 host 子进程(`dsh-desktop-host`,`--expose-internals` 的 node 进程),`require('electron')` 拿不到 `app`,`electronApp()` 返回 null,`installQuitWhenAllWindowsClosed` 一进来 `if (!el) return` 直接退出;并且就算拿得到,`browser-window-created` 在插件 `apply` 时窗口早已建好,那个事件再也不会触发,`closed` 回调永不执行。所以从 0.3.93 加的「点 × 判一次」这条链**从未真正跑过**(launch.log 无新 watcher、钩子日志 0 命中)。这次彻底换路:
291
+
292
+ 1. **前端卸载信标**:`client.js` 在 `apply()` 里装 `pagehide` + `beforeunload` 监听,页面卸载(点 × / 关标签 / 进程退出)时用 `navigator.sendBeacon('/config-sync/auto-exit')` 发一个 fire-and-forget 请求——完全不依赖 Electron 事件。全程 `typeof` 守卫,没有 `navigator.sendBeacon` 的环境静默跳过。
293
+ 2. **后端 fast 判据**:新增 `/config-sync/auto-exit` 路由,`handleAutoExit` 调 `triggerAutoSyncOnClose(config, { fast: true })`。fast 模式只读本地 tracking ref(`rev-list HEAD...origin/branch`,毫秒级)算 ahead/behind,**绝不 `git fetch`**——`sendBeacon` 到达后插件进程随时会被 DSH 退出杀掉,来不及等秒级的网络 fetch;拉取/推送判据与启动复查一致,拉取优先。排好 watcher 后立即返回,真正的 pull/push 由独立存活的 `post-exit.ps1` 在 DSH 进程全消失后执行。
294
+ 3. **防回归**:selftest 断言新路由/handler/fast 分支/无 fetch/clientcheck 断言 `sendBeacon` 与 typeof 守卫。0.3.93/0.3.94/0.3.95 的修复全部保留。
295
+
280
296
  ### 修复 post-exit.ps1 丢 UTF-8 BOM 致排队同步全崩(0.3.95)
281
297
 
282
298
  前面几版「勾了自动拉取/推送、点 × 还是不触发」的最终根因,既不在排队逻辑也不在关闭钩子,而在**执行体脚本的编码**:0.3.94 编辑 `post-exit.ps1` 时,写入工具把文件开头的 **UTF-8 BOM(`EF BB BF`)弄丢了**。Windows PowerShell 5.1 遇到无 BOM 的中文 UTF-8 脚本会按 GBK 解码,中文全角括号被解成引号,脚本一启动就报 55 处语法错直接退出。结果:watcher 明明排上了(`auto-sync-launch.log` 有「已启动」),但 `auto-sync-wait.log` 没有新的「等待开始」——所有排队的同步(启动首检、2 分钟复查、点 × 触发)全部启动即崩,表现成「完全没触发」。
@@ -711,6 +727,8 @@ pwsh -File sync.ps1 push -ScanHistory
711
727
 
712
728
  | 日期 | 版本 | 要点 |
713
729
  |---|---|---|
730
+ | 2026-11-25 | 0.3.97 | 点 × 检测到待拉取/待推送后,从独立进程主动强制退出 DSH 进程族(detached taskkill /F),watcher 立刻执行,不再干等残留进程 |
731
+ | 2026-11-24 | 0.3.96 | 页面卸载信标(pagehide→sendBeacon /auto-exit)取代失效的 Electron 关窗钩子,fast 判据(本地 tracking ref、不 fetch)毫秒级排队 watcher,真正修好「点 × 不触发」 |
714
732
  | 2026-11-24 | 0.3.95 | 修复 post-exit.ps1 丢 UTF-8 BOM 致 PS5.1 按 GBK 解码、55 处语法错启动即崩:三处执行体补回 BOM,selftest 加全量 ps1 BOM 断言防回归 |
715
733
  | 2026-11-24 | 0.3.94 | 修复跨重启僵死 watcher 占锁:锁记 watchPid、复用前查僵死、旧锁杀掉重排;post-exit wait 段过期 watcher 自清让位;解决「勾了开关点 × 仍不触发」 |
716
734
  | 2026-11-24 | 0.3.93 | 点 × 关闭 DSH 时立即判一次自动拉取/推送并排队 watcher,不再等 2 分钟复查窗口;autoRestart 语义统一为 !== false |
package/client.js CHANGED
@@ -3680,6 +3680,44 @@ window.__ModuleLoader__.load({
3680
3680
  }
3681
3681
  }
3682
3682
 
3683
+ /**
3684
+ * 0.3.96:页面卸载信标——绕开 Electron 关窗钩子死结。
3685
+ * 插件跑在 host 子进程里拿不到 electron.app,browser-window-created 事件也在插件 apply 前就错过了,
3686
+ * 所以「点 × 立即判一次」这条链从 0.3.93 起从未真正触发过。改为在前端页面卸载时发一个
3687
+ * navigator.sendBeacon 到 /config-sync/auto-exit,后端 fast 判一次并排 watcher;watcher 独立存活,
3688
+ * DSH 进程全消失后由 post-exit.ps1 真正执行 pull/push。
3689
+ * sendBeacon 是 fire-and-forget,浏览器会在页面卸载时把请求发出去且不等响应。
3690
+ * 全程 typeof 守卫:clientcheck 用 new Function('window','fetch') 加载,没有 document/navigator。
3691
+ */
3692
+ function installExitBeacon() {
3693
+ var noop = function () { }
3694
+ try {
3695
+ if (typeof navigator === 'undefined' || typeof navigator.sendBeacon !== 'function') return noop
3696
+ if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return noop
3697
+ var fired = false
3698
+ var fire = function () {
3699
+ if (fired) return
3700
+ fired = true
3701
+ try {
3702
+ // text/plain 避免任何预检;后端不 care body,只看 settings 与本地 drift。
3703
+ var blob = new Blob(['{"action":"exit"}'], { type: 'text/plain;charset=UTF-8' })
3704
+ navigator.sendBeacon('/config-sync/auto-exit', blob)
3705
+ } catch (e) {
3706
+ try { console.warn('[dsh-config-sync] exit beacon failed:', e) } catch { }
3707
+ }
3708
+ }
3709
+ // pagehide 覆盖「× 关闭 / 页面导航 / 进程退出」;beforeunload 兜底老内核。
3710
+ window.addEventListener('pagehide', fire)
3711
+ window.addEventListener('beforeunload', fire)
3712
+ return function () {
3713
+ try { window.removeEventListener('pagehide', fire) } catch { }
3714
+ try { window.removeEventListener('beforeunload', fire) } catch { }
3715
+ }
3716
+ } catch (e) {
3717
+ return noop
3718
+ }
3719
+ }
3720
+
3683
3721
  function apply(ctx) {
3684
3722
  // 侧栏行 + 配对面板:两个 slot 必须各自 inject(嵌套),再在作用域里成对 register。
3685
3723
  // 只 inject('main') 就向 sidebar.panellist 注册是无效的——区域还没被注入,注册落不下去。
@@ -3716,6 +3754,15 @@ window.__ModuleLoader__.load({
3716
3754
  // 界面还没完全起来时 fetch 可能扑空,所以稍等一会儿再查;只查一次,不轮询。
3717
3755
  try { setTimeout(announceLastResult, 1500) } catch { }
3718
3756
 
3757
+ // 0.3.96:页面卸载信标(点 × / 关标签页 / 进程退出时判一次自动拉取/推送)。
3758
+ // 不依赖 Electron closed 钩子——那条路在 host 子进程里拿不到 app,从未真正装成功过。
3759
+ try {
3760
+ var offBeacon = installExitBeacon()
3761
+ if (typeof ctx.effect === 'function') ctx.effect(function () { return function () { try { offBeacon() } catch { } } })
3762
+ } catch (error) {
3763
+ try { console.warn('[dsh-config-sync] exit beacon install failed:', error) } catch { }
3764
+ }
3765
+
3719
3766
  // 0.3.76:给客户端的 sessions 服务套上 agent-busy 自愈钩子。
3720
3767
  // 拿不到 sessions(老版本宿主 / 服务还没起来)就静默跳过,面板功能不受影响。
3721
3768
  try {
package/index.js CHANGED
@@ -47,6 +47,9 @@ const ROUTE_FEEDBACK = '/config-sync/feedback'
47
47
  const ROUTE_CACHE_GUARD = '/config-sync/cache-guard'
48
48
  // 0.3.76:工作区显示状态(GET 读 / POST workspace 三态 | session 独立隐藏)
49
49
  const ROUTE_WORKSPACE_VIEW = '/config-sync/workspace-view'
50
+ // 0.3.96:页面卸载信标(pagehide/beforeunload 的 navigator.sendBeacon)。
51
+ // 不依赖 Electron 的 closed 事件——插件跑在 host 子进程里拿不到 app,且 browser-window-created 在插件 apply 时早就错过了。
52
+ const ROUTE_AUTO_EXIT = '/config-sync/auto-exit'
50
53
  const SETTINGS_NAME = 'dsh-config-sync.json'
51
54
  /** 本插件自己的安装目录(插件根,含 runtime\ 与 index.js)—— 插件备份还原时的目标。 */
52
55
  const PLUGIN_ROOT = fileURLToPath(new URL('.', import.meta.url)).replace(/[\\/]+$/, '')
@@ -1555,6 +1558,26 @@ async function checkDrift(repo) {
1555
1558
  return { ahead, behind, branch, at: Date.now() }
1556
1559
  }
1557
1560
 
1561
+ /**
1562
+ * 0.3.96:页面卸载信标专用——只用本地 tracking ref 算 ahead/behind,绝不 git fetch。
1563
+ * checkDrift 会阻塞在 `git fetch origin`(网络,秒级),而 sendBeacon 到达后端后,
1564
+ * 插件进程随时可能随 DSH 退出被杀,必须在毫秒级内完成 spawnWatcher。
1565
+ * 本地 rev-list 用的是上次 fetch 留下的 origin/<branch>,对「离开时判一次」足够:
1566
+ * - 本地领先/未提交改动是即时的,push 判据准;
1567
+ * - 云端领先可能滞后到上次 fetch,但 2 分钟复查/面板 check 会持续刷新 tracking ref,
1568
+ * 且真有云端更新时 pull 模式 watcher 自己会再 fetch 一次,不会漏。
1569
+ * 本地算不出来就退回 autoState.drift 缓存;再没有就返回 null,由调用方保守处理。
1570
+ */
1571
+ async function checkDriftFast(repo) {
1572
+ if (!repo || !isDir(join(repo, '.git'))) return autoState.drift
1573
+ const branch = await currentBranch(repo)
1574
+ if (!branch) return autoState.drift
1575
+ const counts = await git(repo, ['rev-list', '--left-right', '--count', `HEAD...origin/${branch}`])
1576
+ if (!counts) return autoState.drift
1577
+ const [ahead, behind] = counts.trim().split(/\s+/).map((n) => Number(n) || 0)
1578
+ return { ahead, behind, branch, at: Date.now(), fast: true }
1579
+ }
1580
+
1558
1581
  /** 系统确认框(立在 DSH 窗口前面,不开面板也看得见)。Yes → true。 */
1559
1582
  function askConfirm(title, text) {
1560
1583
  return new Promise((resolve) => {
@@ -1746,6 +1769,35 @@ function closeDsh() {
1746
1769
  return true
1747
1770
  }
1748
1771
 
1772
+ /**
1773
+ * 0.3.97:页面卸载信标检测到「待拉取/待推送」后,主动、强制退出 DSH 进程族,
1774
+ * 让刚排好的 watcher 立刻从 wait 进入 run,而不是干等用户把 DSH 关干净(实测常残留 7 个进程,
1775
+ * 之前只能等 post-exit 的 30 分钟超时)。
1776
+ *
1777
+ * 决定性约束:必须在 detached 的独立进程里做延迟强杀 —— 插件就跑在 DSH 的 host 子进程里,
1778
+ * 强杀会把插件自己也带走,任何挂在插件进程内的 setTimeout 都来不及执行。
1779
+ * 用 cmd /c + ping 做秒级延时(timeout.exe 在无控制台的非交互进程里会报错),
1780
+ * 先给点 × 触发的正常关闭流程一点时间落盘,再 /F 兜底残留进程。
1781
+ */
1782
+ function forceCloseDshDetached(config) {
1783
+ const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
1784
+ const sys = process.env.SystemRoot || 'C:\\Windows'
1785
+ const cmd = join(sys, 'System32', 'cmd.exe')
1786
+ const taskkill = join(sys, 'System32', 'taskkill.exe')
1787
+ const imageName = 'DeepSeek Harness.exe'
1788
+ // ping -n 3 ≈ 2s:给正常关闭 + watcher 读锁的余量,之后 /F 强杀残留进程族
1789
+ const script = `ping -n 3 127.0.0.1 >nul & "${taskkill}" /IM "${imageName}" /F`
1790
+ try {
1791
+ const child = spawn(cmd, ['/c', script], { stdio: 'ignore', windowsHide: true, detached: true })
1792
+ try { child.unref?.() } catch { }
1793
+ logLaunch(dshHome, `auto-exit:已排队同步,触发强制退出 DSH 进程族(${imageName} /F,独立进程延迟强杀)`)
1794
+ return true
1795
+ } catch (error) {
1796
+ logLaunch(dshHome, `auto-exit:触发退出失败:${(error && error.message) || error}`)
1797
+ return false
1798
+ }
1799
+ }
1800
+
1749
1801
  function isProcessAlive(pid) {
1750
1802
  if (!pid) return false
1751
1803
  try { process.kill(pid, 0); return true } catch { return false }
@@ -3547,7 +3599,7 @@ function scheduleAutoStart(config) {
3547
3599
  * 关闭场景窗口都在关了,不弹确认框;autoPull 仍只在云端确实领先(或本机仓库还没内容)时才排队,
3548
3600
  * 免得没更新也白拉一次还把客户端重启回来。和 scheduleAutoStart 一样「拉取优先,二者只排一个」。
3549
3601
  */
3550
- async function triggerAutoSyncOnClose(config) {
3602
+ async function triggerAutoSyncOnClose(config, options = {}) {
3551
3603
  const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
3552
3604
  try {
3553
3605
  const settings = readSettings(dshHome)
@@ -3575,7 +3627,9 @@ async function triggerAutoSyncOnClose(config) {
3575
3627
  return { queued: false }
3576
3628
  }
3577
3629
 
3578
- const drift = await checkDrift(repo)
3630
+ // 0.3.96:页面卸载信标走 fast 模式——只读本地 tracking ref,毫秒级返回,绝不 git fetch。
3631
+ // 原来的 Electron 关窗钩子(慢模式)仍可走 checkDrift,两条路共用后续判据。
3632
+ const drift = options.fast ? await checkDriftFast(repo) : await checkDrift(repo)
3579
3633
  if (!drift) return { queued: false }
3580
3634
 
3581
3635
  // 拉取优先,和 scheduleAutoStart 一致;关闭时不再弹确认框,云端领先就排
@@ -3615,6 +3669,33 @@ async function triggerAutoSyncOnClose(config) {
3615
3669
  }
3616
3670
  }
3617
3671
 
3672
+ /**
3673
+ * 0.3.96:页面卸载信标专用接口。
3674
+ * 前端 pagehide → navigator.sendBeacon('/config-sync/auto-exit'),绕开失效的 Electron closed 钩子
3675
+ * (插件跑在 host 子进程拿不到 app,且 browser-window-created 事件在插件 apply 时早错过了)。
3676
+ * sendBeacon 是 fire-and-forget,页面卸载后浏览器会取消在途请求,所以这里必须毫秒级返回:
3677
+ * 走 triggerAutoSyncOnClose 的 fast 模式(只读本地 tracking ref,不 git fetch)。
3678
+ * 只排队 watcher,真正的 pull/push 由独立的 post-exit.ps1 在 DSH 进程全消失后执行。
3679
+ */
3680
+ async function handleAutoExit(req, res, config) {
3681
+ if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3682
+ if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3683
+ try {
3684
+ // sendBeacon 的 body 可能是空 / text/plain / application/json,读不读都不影响排队;容错读一下即可。
3685
+ try { await readBody(req) } catch { }
3686
+ const result = await triggerAutoSyncOnClose(config, { fast: true })
3687
+ // 0.3.97:检测到待拉取/待推送并排好 watcher 后,主动强制退出 DSH 进程族,
3688
+ // watcher 立刻从 wait 进入 run;不再干等用户关干净(残留进程会让同步卡到 30 分钟超时)。
3689
+ // 必须在独立进程里做——强杀会带走插件自己(插件跑在 DSH 的 host 子进程)。
3690
+ if (result && result.queued) forceCloseDshDetached(config)
3691
+ sendJson(res, 200, { ok: true, ...result })
3692
+ } catch (error) {
3693
+ logLaunch(config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh'),
3694
+ `auto-exit 信标处理失败:${(error && error.message) || error}`)
3695
+ sendJson(res, 200, { ok: true, queued: false })
3696
+ }
3697
+ }
3698
+
3618
3699
  async function handlePrepare(req, res, config) {
3619
3700
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3620
3701
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
@@ -4666,6 +4747,12 @@ export function apply(ctx, config) {
4666
4747
  path: ROUTE_AUTO,
4667
4748
  handler: withLang(handleAuto),
4668
4749
  }))
4750
+ // 0.3.96:页面卸载信标(pagehide → sendBeacon),绕开 Electron closed 钩子死结
4751
+ scoped.effect(() => scoped.webServer.register({
4752
+ kind: 'exact',
4753
+ path: ROUTE_AUTO_EXIT,
4754
+ handler: withLang(handleAutoExit),
4755
+ }))
4669
4756
  scoped.effect(() => scoped.webServer.register({
4670
4757
  kind: 'exact',
4671
4758
  path: ROUTE_UPDATE,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-sync-plugin",
3
- "version": "0.3.95",
3
+ "version": "0.3.97",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
@@ -132,6 +132,15 @@ check('设置摘要行两个立即按钮走 pull-now / push-now 队列',
132
132
  && source.includes("M('立即拉取(会关闭 DSH)', 'Pull now (closes DSH)')")
133
133
  && source.includes("M('立即推送(会关闭 DSH)', 'Push now (closes DSH)')"))
134
134
  check('每个 inject 回调都返回了回收函数', recycle.length === 3 && recycle.every((r) => typeof r.stop === 'function'), `实际 ${recycle.length} 个`)
135
+ // 0.3.96:页面卸载信标(sendBeacon)绕开 Electron 关窗钩子死结;且必须 typeof 守卫,
136
+ // 否则本自检的 new Function('window','fetch') 环境没有 document/navigator 会 ReferenceError。
137
+ check('页面卸载装 pagehide + beforeunload → sendBeacon(/config-sync/auto-exit)(0.3.96)',
138
+ source.includes("window.addEventListener('pagehide', fire)")
139
+ && source.includes("window.addEventListener('beforeunload', fire)")
140
+ && source.includes("navigator.sendBeacon('/config-sync/auto-exit'"))
141
+ check('卸载信标无 document/navigator 环境不崩(typeof 守卫,本自检直接覆盖)',
142
+ source.includes("if (typeof navigator === 'undefined' || typeof navigator.sendBeacon !== 'function') return noop")
143
+ && source.includes("if (typeof window === 'undefined' || typeof window.addEventListener !== 'function') return noop"))
135
144
 
136
145
  // 关键契约:sidebar.panellist 必须先被 inject,再往里 register(只 inject main 是无效的)
137
146
  const idxInjectSidebar = seq.indexOf('inject:sidebar.panellist')
@@ -94,7 +94,7 @@ function check(label, cond, detail = '') {
94
94
  }
95
95
 
96
96
  console.log('== dsh-config-sync-plugin 宿主半身自检 ==')
97
- check('apply() 注册了路由', routes.size === 12 && routes.has('/config-sync/update') && routes.has('/config-sync/scope') && routes.has('/config-sync/extra-config') && routes.has('/config-sync/conflict') && routes.has('/config-sync/roots') && routes.has('/config-sync/feedback') && routes.has('/config-sync/cache-guard') && routes.has('/config-sync/workspace-view'), `实际 ${routes.size} 条:${[...routes.keys()].join(', ')}`)
97
+ check('apply() 注册了路由', routes.size === 13 && routes.has('/config-sync/auto-exit') && routes.has('/config-sync/update') && routes.has('/config-sync/scope') && routes.has('/config-sync/extra-config') && routes.has('/config-sync/conflict') && routes.has('/config-sync/roots') && routes.has('/config-sync/feedback') && routes.has('/config-sync/cache-guard') && routes.has('/config-sync/workspace-view'), `实际 ${routes.size} 条:${[...routes.keys()].join(', ')}`)
98
98
 
99
99
  const status = await call('/config-sync/status', { headers: { host: 'localhost:3080' } })
100
100
  const body = JSON.parse(status.body || '{}')
@@ -1782,7 +1782,7 @@ console.log('== 0.3.93:点 × 关闭时判一次并排队自动拉取/推送 =
1782
1782
  const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1783
1783
  // 1) 新增退出前排队函数:读开关 / 复用在途 watcher / 空仓只拉 / 拉取优先 / 判据同 scheduleAutoStart
1784
1784
  check('退出前排队函数存在且读 autoPull/autoPush 开关',
1785
- /async function triggerAutoSyncOnClose\(config\)/.test(idxSrc)
1785
+ /async function triggerAutoSyncOnClose\(config, options = \{\}\)/.test(idxSrc)
1786
1786
  && /if \(!settings\.autoPull && !settings\.autoPush\) return/.test(idxSrc), 'index.js triggerAutoSyncOnClose')
1787
1787
  check('已有在途 watcher 时复用、不重复拉起',
1788
1788
  /autoState\.pending[\s\S]{0,200}isProcessAlive\(autoState\.pending\.watcherPid\)[\s\S]{0,120}reused: true/.test(idxSrc), 'index.js 复用守卫')
@@ -1854,5 +1854,55 @@ console.log('== 0.3.95:所有 runtime/*.ps1 必须带 UTF-8 BOM(PS5.1 中文
1854
1854
  b.length > 1000 && b[0] === 0xEF && b[1] === 0xBB && b[2] === 0xBF, `bytes=${b.length}`)
1855
1855
  }
1856
1856
  }
1857
+ console.log('')
1858
+ console.log('== 0.3.96:页面卸载信标(sendBeacon)绕开 Electron 关窗钩子死结 ==')
1859
+ {
1860
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1861
+ const cliSrc = existsSync(join(pluginRootSelf, 'client.js')) ? readFileSync(join(pluginRootSelf, 'client.js'), 'utf8') : ''
1862
+ // 后端:新路由 + handler + fast 判据
1863
+ check('新增 auto-exit 路由常量',
1864
+ /const ROUTE_AUTO_EXIT = '\/config-sync\/auto-exit'/.test(idxSrc), 'index.js ROUTE_AUTO_EXIT')
1865
+ check('auto-exit 路由已注册(withLang(handleAutoExit))',
1866
+ /path: ROUTE_AUTO_EXIT[\s\S]{0,80}handler: withLang\(handleAutoExit\)/.test(idxSrc), 'index.js 路由注册')
1867
+ check('handleAutoExit 存在且走 triggerAutoSyncOnClose fast 模式',
1868
+ /async function handleAutoExit\(req, res, config\)/.test(idxSrc)
1869
+ && /triggerAutoSyncOnClose\(config, \{ fast: true \}\)/.test(idxSrc), 'index.js handleAutoExit')
1870
+ check('triggerAutoSyncOnClose 接 options 并在 fast 时用 checkDriftFast',
1871
+ /async function triggerAutoSyncOnClose\(config, options = \{\}\)/.test(idxSrc)
1872
+ && /options\.fast \? await checkDriftFast\(repo\) : await checkDrift\(repo\)/.test(idxSrc), 'index.js fast 分支')
1873
+ check('checkDriftFast 只读本地 tracking ref,绝不 git fetch',
1874
+ /async function checkDriftFast\(repo\)/.test(idxSrc)
1875
+ && /rev-list', '--left-right', '--count'/.test(idxSrc)
1876
+ && !/async function checkDriftFast[\s\S]{0,700}?git\(repo, \['fetch'/.test(idxSrc), 'index.js checkDriftFast')
1877
+ // 前端:pagehide/beforeunload → sendBeacon,且全程 typeof 守卫(clientcheck 无 document/navigator)
1878
+ check('client.js 安装 pagehide + beforeunload 卸载监听',
1879
+ /window\.addEventListener\('pagehide', fire\)/.test(cliSrc)
1880
+ && /window\.addEventListener\('beforeunload', fire\)/.test(cliSrc), 'client.js 卸载监听')
1881
+ check('卸载时向 /config-sync/auto-exit 发 navigator.sendBeacon',
1882
+ /navigator\.sendBeacon\('\/config-sync\/auto-exit'/.test(cliSrc), 'client.js sendBeacon')
1883
+ check('pagehide 信标全程 typeof 守卫(无 document/navigator 环境不崩)',
1884
+ /if \(typeof navigator === 'undefined' \|\| typeof navigator\.sendBeacon !== 'function'\) return noop/.test(cliSrc)
1885
+ && /if \(typeof window === 'undefined' \|\| typeof window\.addEventListener !== 'function'\) return noop/.test(cliSrc), 'client.js 守卫')
1886
+ check('apply() 内安装信标并用 ctx.effect 回收',
1887
+ /var offBeacon = installExitBeacon\(\)/.test(cliSrc)
1888
+ && /ctx\.effect\(function \(\) \{ return function \(\) \{ try \{ offBeacon\(\) \}/.test(cliSrc), 'client.js apply 安装')
1889
+ }
1890
+ console.log('')
1891
+ console.log('== 0.3.97:检测到待拉取/待推送就主动强制退出 DSH,watcher 立刻执行 ==')
1892
+ {
1893
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1894
+ check('新增 forceCloseDshDetached 独立进程强制退出函数',
1895
+ /function forceCloseDshDetached\(config\)/.test(idxSrc), 'index.js forceCloseDshDetached')
1896
+ check('强制退出用 detached + unref 独立进程(强杀不会带走插件自己)',
1897
+ /spawn\(cmd, \['\/c', script\][\s\S]{0,120}?detached: true/.test(idxSrc)
1898
+ && /child\.unref\?\.\(\)/.test(idxSrc), 'index.js detached 强杀')
1899
+ check('taskkill /IM /F 整族强杀 DeepSeek Harness',
1900
+ /taskkill[\s\S]{0,80}?\/IM[\s\S]{0,80}?\/F/.test(idxSrc)
1901
+ || /"\/IM"[\s\S]{0,120}?"\/F"/.test(idxSrc), 'index.js taskkill /F')
1902
+ check('auto-exit 排队成功后调用 forceCloseDshDetached',
1903
+ /if \(result && result\.queued\) forceCloseDshDetached\(config\)/.test(idxSrc), 'index.js 排队后主动退出')
1904
+ check('只在 queued 时才强制退出(无待同步不误杀 DSH)',
1905
+ /result && result\.queued[\s\S]{0,60}?forceCloseDshDetached/.test(idxSrc), 'index.js queued 守卫')
1906
+ }
1857
1907
  process.exit(failures === 0 ? 0 : 1)
1858
1908