dsh-config-sync-plugin 0.3.94 → 0.3.96
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 +18 -0
- package/README.md +18 -0
- package/client.js +47 -0
- package/index.js +56 -2
- package/package.json +1 -1
- package/runtime/post-exit.ps1 +1 -1
- package/tools/clientcheck.mjs +9 -0
- package/tools/selftest.mjs +59 -2
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
|
+
### Page-unload beacon replaces the Electron close hook, finally fixing "× does not trigger" (0.3.96)
|
|
261
|
+
|
|
262
|
+
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:
|
|
263
|
+
|
|
264
|
+
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.
|
|
265
|
+
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.
|
|
266
|
+
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.
|
|
267
|
+
|
|
268
|
+
### Fix post-exit.ps1 missing UTF-8 BOM, which crashed every queued sync (0.3.95)
|
|
269
|
+
|
|
270
|
+
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".
|
|
271
|
+
|
|
272
|
+
1. **Restore the BOM on the executor**: `post-exit.ps1` (plugin runtime, config-repo mirror, deployed directory) was rewritten with `UTF8Encoding($true)` to restore the BOM; `ParseFile` syntax errors dropped from 55 to 0, and an isolated probe confirmed the wait phase starts, writes its log, and stays alive.
|
|
273
|
+
2. **Regression assertion**: `selftest.mjs` now checks that every `runtime/*.ps1` carries a UTF-8 BOM (first 3 bytes `EF BB BF`), with an extra check on `post-exit.ps1`. Editing a script and losing its BOM now turns the self-test red.
|
|
274
|
+
3. **Packaging preserves BOM**: `fs.copyFileSync` copies bytes verbatim and never strips a BOM; this incident was the source file being edited incorrectly. The packed tarball is verified to contain a `post-exit.ps1` with BOM.
|
|
275
|
+
|
|
260
276
|
### Clean up cross-restart stale watchers — the lock can no longer be held by an old instance (0.3.94)
|
|
261
277
|
|
|
262
278
|
A deeper cause was measured behind "switches enabled, clicking × still triggers nothing": after a plugin update restarts DSH, the watcher queued before the update is still waiting on the **old, already-dead DSH process** (WatchPid is gone), but the post-exit "a process with this name still exists" guard keeps it from starting. It hangs in the wait phase and holds `~/.dsh/auto-sync.lock` forever. When × queues a new watcher, it sees a live pid with the same mode in the lock, assumes "the same sync is already waiting" and reuses it — reusing a watcher that will never run, so nothing appears to happen. Two fixes:
|
|
@@ -721,6 +737,8 @@ The log shows which path ran: `文件比较(快筛):比对 N 个,深哈
|
|
|
721
737
|
|
|
722
738
|
| Date | Version | Summary |
|
|
723
739
|
|---|---|---|
|
|
740
|
+
| 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" |
|
|
741
|
+
| 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 |
|
|
724
742
|
| 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" |
|
|
725
743
|
| 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 |
|
|
726
744
|
| 2026-11-24 | 0.3.92 | Remote "uncommitted" now includes local pending data (pending); Refresh button really triggers git fetch; fixes "remote figures always 0" |
|
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
|
+
### 页面卸载信标取代 Electron 关窗钩子,真正修好「点 × 不触发」(0.3.96)
|
|
281
|
+
|
|
282
|
+
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 命中)。这次彻底换路:
|
|
283
|
+
|
|
284
|
+
1. **前端卸载信标**:`client.js` 在 `apply()` 里装 `pagehide` + `beforeunload` 监听,页面卸载(点 × / 关标签 / 进程退出)时用 `navigator.sendBeacon('/config-sync/auto-exit')` 发一个 fire-and-forget 请求——完全不依赖 Electron 事件。全程 `typeof` 守卫,没有 `navigator.sendBeacon` 的环境静默跳过。
|
|
285
|
+
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 进程全消失后执行。
|
|
286
|
+
3. **防回归**:selftest 断言新路由/handler/fast 分支/无 fetch/clientcheck 断言 `sendBeacon` 与 typeof 守卫。0.3.93/0.3.94/0.3.95 的修复全部保留。
|
|
287
|
+
|
|
288
|
+
### 修复 post-exit.ps1 丢 UTF-8 BOM 致排队同步全崩(0.3.95)
|
|
289
|
+
|
|
290
|
+
前面几版「勾了自动拉取/推送、点 × 还是不触发」的最终根因,既不在排队逻辑也不在关闭钩子,而在**执行体脚本的编码**: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 分钟复查、点 × 触发)全部启动即崩,表现成「完全没触发」。
|
|
291
|
+
|
|
292
|
+
1. **执行体补回 BOM**:`post-exit.ps1`(插件 runtime、配置仓库镜像、实际部署目录三处)用 `UTF8Encoding($true)` 重写补回 BOM,`ParseFile` 语法错误从 55 降到 0,隔离探针实测 wait 段能正常启动、写日志、持续存活。
|
|
293
|
+
2. **防回归断言**:`selftest.mjs` 新增检查——所有 `runtime/*.ps1` 必须带 UTF-8 BOM(前 3 字节 `EF BB BF`),`post-exit.ps1` 执行体单独再验一次。以后再有人编辑脚本丢了 BOM,自测直接红。
|
|
294
|
+
3. **打包保持 BOM**:`fs.copyFileSync` 原样复制不会丢 BOM;本次是源文件被编辑工具写坏的,打包产物核验包内 `post-exit.ps1` 带 BOM。
|
|
295
|
+
|
|
280
296
|
### 清理跨重启僵死 watcher,锁不再被旧实例占死(0.3.94)
|
|
281
297
|
|
|
282
298
|
实测「勾了开关、点 × 关闭还是不触发」还有一个更深的原因:插件更新流程重启 DSH 后,更新前排的那个 watcher 还在等**已经退出的旧 DSH 进程**(WatchPid 已死),却被 post-exit 的「进程名还有新实例」判断挡着不敢开工,于是僵死在 wait 段、一直占着 `~/.dsh/auto-sync.lock`。此时点 × 新排的 watcher 看到锁里 pid 存活且同为 push,就误判「同一个同步正在等」直接复用——复用的是一个永远不会执行的僵死 watcher,所以看着像彻底没触发。这次两处修复:
|
|
@@ -703,6 +719,8 @@ pwsh -File sync.ps1 push -ScanHistory
|
|
|
703
719
|
|
|
704
720
|
| 日期 | 版本 | 要点 |
|
|
705
721
|
|---|---|---|
|
|
722
|
+
| 2026-11-24 | 0.3.96 | 页面卸载信标(pagehide→sendBeacon /auto-exit)取代失效的 Electron 关窗钩子,fast 判据(本地 tracking ref、不 fetch)毫秒级排队 watcher,真正修好「点 × 不触发」 |
|
|
723
|
+
| 2026-11-24 | 0.3.95 | 修复 post-exit.ps1 丢 UTF-8 BOM 致 PS5.1 按 GBK 解码、55 处语法错启动即崩:三处执行体补回 BOM,selftest 加全量 ps1 BOM 断言防回归 |
|
|
706
724
|
| 2026-11-24 | 0.3.94 | 修复跨重启僵死 watcher 占锁:锁记 watchPid、复用前查僵死、旧锁杀掉重排;post-exit wait 段过期 watcher 自清让位;解决「勾了开关点 × 仍不触发」 |
|
|
707
725
|
| 2026-11-24 | 0.3.93 | 点 × 关闭 DSH 时立即判一次自动拉取/推送并排队 watcher,不再等 2 分钟复查窗口;autoRestart 语义统一为 !== false |
|
|
708
726
|
| 2026-11-24 | 0.3.92 | 远端「未提交」纳入本机待同步数据(pending),刷新按钮真正触发 git fetch;解决「远端数字一直是 0」 |
|
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) => {
|
|
@@ -3547,7 +3570,7 @@ function scheduleAutoStart(config) {
|
|
|
3547
3570
|
* 关闭场景窗口都在关了,不弹确认框;autoPull 仍只在云端确实领先(或本机仓库还没内容)时才排队,
|
|
3548
3571
|
* 免得没更新也白拉一次还把客户端重启回来。和 scheduleAutoStart 一样「拉取优先,二者只排一个」。
|
|
3549
3572
|
*/
|
|
3550
|
-
async function triggerAutoSyncOnClose(config) {
|
|
3573
|
+
async function triggerAutoSyncOnClose(config, options = {}) {
|
|
3551
3574
|
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3552
3575
|
try {
|
|
3553
3576
|
const settings = readSettings(dshHome)
|
|
@@ -3575,7 +3598,9 @@ async function triggerAutoSyncOnClose(config) {
|
|
|
3575
3598
|
return { queued: false }
|
|
3576
3599
|
}
|
|
3577
3600
|
|
|
3578
|
-
|
|
3601
|
+
// 0.3.96:页面卸载信标走 fast 模式——只读本地 tracking ref,毫秒级返回,绝不 git fetch。
|
|
3602
|
+
// 原来的 Electron 关窗钩子(慢模式)仍可走 checkDrift,两条路共用后续判据。
|
|
3603
|
+
const drift = options.fast ? await checkDriftFast(repo) : await checkDrift(repo)
|
|
3579
3604
|
if (!drift) return { queued: false }
|
|
3580
3605
|
|
|
3581
3606
|
// 拉取优先,和 scheduleAutoStart 一致;关闭时不再弹确认框,云端领先就排
|
|
@@ -3615,6 +3640,29 @@ async function triggerAutoSyncOnClose(config) {
|
|
|
3615
3640
|
}
|
|
3616
3641
|
}
|
|
3617
3642
|
|
|
3643
|
+
/**
|
|
3644
|
+
* 0.3.96:页面卸载信标专用接口。
|
|
3645
|
+
* 前端 pagehide → navigator.sendBeacon('/config-sync/auto-exit'),绕开失效的 Electron closed 钩子
|
|
3646
|
+
* (插件跑在 host 子进程拿不到 app,且 browser-window-created 事件在插件 apply 时早错过了)。
|
|
3647
|
+
* sendBeacon 是 fire-and-forget,页面卸载后浏览器会取消在途请求,所以这里必须毫秒级返回:
|
|
3648
|
+
* 走 triggerAutoSyncOnClose 的 fast 模式(只读本地 tracking ref,不 git fetch)。
|
|
3649
|
+
* 只排队 watcher,真正的 pull/push 由独立的 post-exit.ps1 在 DSH 进程全消失后执行。
|
|
3650
|
+
*/
|
|
3651
|
+
async function handleAutoExit(req, res, config) {
|
|
3652
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
3653
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3654
|
+
try {
|
|
3655
|
+
// sendBeacon 的 body 可能是空 / text/plain / application/json,读不读都不影响排队;容错读一下即可。
|
|
3656
|
+
try { await readBody(req) } catch { }
|
|
3657
|
+
const result = await triggerAutoSyncOnClose(config, { fast: true })
|
|
3658
|
+
sendJson(res, 200, { ok: true, ...result })
|
|
3659
|
+
} catch (error) {
|
|
3660
|
+
logLaunch(config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh'),
|
|
3661
|
+
`auto-exit 信标处理失败:${(error && error.message) || error}`)
|
|
3662
|
+
sendJson(res, 200, { ok: true, queued: false })
|
|
3663
|
+
}
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3618
3666
|
async function handlePrepare(req, res, config) {
|
|
3619
3667
|
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
3620
3668
|
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
@@ -4666,6 +4714,12 @@ export function apply(ctx, config) {
|
|
|
4666
4714
|
path: ROUTE_AUTO,
|
|
4667
4715
|
handler: withLang(handleAuto),
|
|
4668
4716
|
}))
|
|
4717
|
+
// 0.3.96:页面卸载信标(pagehide → sendBeacon),绕开 Electron closed 钩子死结
|
|
4718
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4719
|
+
kind: 'exact',
|
|
4720
|
+
path: ROUTE_AUTO_EXIT,
|
|
4721
|
+
handler: withLang(handleAutoExit),
|
|
4722
|
+
}))
|
|
4669
4723
|
scoped.effect(() => scoped.webServer.register({
|
|
4670
4724
|
kind: 'exact',
|
|
4671
4725
|
path: ROUTE_UPDATE,
|
package/package.json
CHANGED
package/runtime/post-exit.ps1
CHANGED
package/tools/clientcheck.mjs
CHANGED
|
@@ -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')
|
package/tools/selftest.mjs
CHANGED
|
@@ -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 ===
|
|
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 复用守卫')
|
|
@@ -1830,5 +1830,62 @@ console.log('== 0.3.94:清理跨重启僵死 watcher,锁不再被旧实例
|
|
|
1830
1830
|
check('post-exit wait:过期 watcher 清自己的锁并 exit 3 让位',
|
|
1831
1831
|
/\$lock\.pid -eq \$PID/.test(postSrc) && /\bexit 3\b/.test(postSrc), 'post-exit.ps1 让位')
|
|
1832
1832
|
}
|
|
1833
|
+
console.log('')
|
|
1834
|
+
console.log('== 0.3.95:所有 runtime/*.ps1 必须带 UTF-8 BOM(PS5.1 中文脚本防乱码崩溃)==')
|
|
1835
|
+
{
|
|
1836
|
+
// 决定性教训:0.3.94 编辑 post-exit.ps1 时写入工具丢了 BOM,PS5.1 按 GBK 解码,
|
|
1837
|
+
// 中文全角括号被解成引号 → 55 处语法错 → 脚本启动即崩 → 所有排队同步(含点 ×)全部失效。
|
|
1838
|
+
// 所有含中文的 .ps1 必须带 UTF-8 BOM,否则在 Windows PowerShell 5.1 下必崩。
|
|
1839
|
+
const ps1Names = ['apply.ps1', 'capture.ps1', 'dsh-sync-common.ps1', 'install-plugin.ps1',
|
|
1840
|
+
'post-exit.ps1', 'restore.ps1', 'sync.ps1']
|
|
1841
|
+
for (const name of ps1Names) {
|
|
1842
|
+
const p = join(pluginRuntime, name)
|
|
1843
|
+
if (!existsSync(p)) continue
|
|
1844
|
+
const bytes = readFileSync(p)
|
|
1845
|
+
const hasBom = bytes.length >= 3 && bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF
|
|
1846
|
+
const hex = [...bytes.slice(0, 3)].map((b) => b.toString(16).padStart(2, '0')).join(' ')
|
|
1847
|
+
check(`${name} 带 UTF-8 BOM(PS5.1 不会按 GBK 解成乱码)`, hasBom, `前3字节 ${hex}`)
|
|
1848
|
+
}
|
|
1849
|
+
// post-exit.ps1 是排队同步(含点 × 触发)的唯一执行体,崩了就全盘不动,单独强调
|
|
1850
|
+
const postPath = join(pluginRuntime, 'post-exit.ps1')
|
|
1851
|
+
if (existsSync(postPath)) {
|
|
1852
|
+
const b = readFileSync(postPath)
|
|
1853
|
+
check('post-exit.ps1 执行体非零字节且带 BOM',
|
|
1854
|
+
b.length > 1000 && b[0] === 0xEF && b[1] === 0xBB && b[2] === 0xBF, `bytes=${b.length}`)
|
|
1855
|
+
}
|
|
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
|
+
}
|
|
1833
1890
|
process.exit(failures === 0 ? 0 : 1)
|
|
1834
1891
|
|