dsh-config-sync-plugin 0.3.92 → 0.3.94

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,23 @@ 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
+ ### Clean up cross-restart stale watchers — the lock can no longer be held by an old instance (0.3.94)
261
+
262
+ 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:
263
+
264
+ 1. **Lock records watchPid and checks for staleness before reuse**: `auto-sync.lock` now stores `{pid, mode, watchPid: current DSH pid, at}`. Before reusing a lock, spawnWatcher checks whether `watchPid` is still alive: a missing watchPid (old lock) or an exited DSH means stale — kill the old watcher, clear the lock, and re-queue. Only when both DSH and watcher are alive and the mode matches is the watcher reused.
265
+ 2. **post-exit wait phase self-clears stale watchers**: when WatchPid has exited but processes with the DSH name remain, compare their start times — if they are all newer than this waiter, the DSH we waited for already exited and restarted, so this watcher is a leftover from the previous generation: log it, remove its own lock, and `exit 3` to yield, instead of waiting 30 minutes and hogging the lock.
266
+
267
+ `post-exit.ps1` is also mirrored into the config repo's runtime copies so the repo fallback script carries the same fix.
268
+
269
+ ### Clicking × to close DSH now checks once for auto pull/push immediately (0.3.93)
270
+
271
+ With "Pull on startup" or "Push on exit" enabled, the only queues used to be the 8-second startup check and the 2-minute re-check. If you made changes between two re-checks and then clicked the top-right × to close DSH, no watcher was waiting for the exit at that moment, so nothing ran after closing. A quit hook now covers it: when the last visible window closes (the × click), the plugin checks once and queues the watcher **before** the client exits; once the DSH processes are gone the watcher runs the pull/push immediately.
272
+
273
+ 1. **Check once on exit**: when no visible windows remain, call `triggerAutoSyncOnClose(config)`, which reads the `autoPull`/`autoPush` switches; an in-flight watcher is reused rather than relaunched; with an empty local repo only autoPull can queue (first clone).
274
+ 2. **Same criteria as the re-check**: pull takes priority (behind > 0 → queue pull, no confirmation dialog on the close path); push queues when any of "commits ahead / uncommitted changes / local data newer than last sync" hits; `autoRestart` semantics unified to `!== false` (relaunch by default).
275
+ 3. **Queue before quit**: the queue must be awaited **before** `app.quit()` — the plugin dies with the main process, so checking after quit is too late. With both switches off / nothing to sync the function returns quickly and does not slow down closing; a successful queue logs "queued pull/push before exit …: runs right after DSH exits".
276
+
260
277
  ### Remote "uncommitted" now includes local pending changes + Refresh really fetches (0.3.92)
261
278
 
262
279
  Root cause found by measurement for "remote info still not updating": the git-level behind/ahead really is 0 (local HEAD matches the gitee cloud), while what the user means by "not updated" is the runtime-generated changes on this machine not yet captured into the repo. Two substantive fixes:
@@ -584,8 +601,8 @@ Default exclusions (50 entries, edit freely): `*.db` / `*.db-*` / `*.sqlite*` /
584
601
 
585
602
  | Switch | Behaviour |
586
603
  |---|---|
587
- | Pull on startup | 8 s after start, a read-only `git fetch` comparison; behind > 0 → system confirmation dialog (Yes/No) → "Yes" **exits the whole client family right away** (measured: processes gone within 5 s) → a visible window runs the pull → relaunches automatically |
588
- | Push on exit | **queued when any of three sources hit**: local commits ahead, uncommitted changes, local data newer than the last sync (new sessions etc). Re-checked every 2 minutes after start, no duplicate watcher while queued; pushes only after DSH fully exits, then relaunches |
604
+ | Pull on startup | 8 s after start, a read-only `git fetch` comparison; behind > 0 → system confirmation dialog (Yes/No) → "Yes" **exits the whole client family right away** (measured: processes gone within 5 s) → a visible window runs the pull → relaunches automatically. Clicking × to close also checks once and queues (0.3.93; no confirmation dialog on the close path — behind > 0 queues the pull) |
605
+ | Push on exit | **queued when any of three sources hit**: local commits ahead, uncommitted changes, local data newer than the last sync (new sessions etc). Re-checked every 2 minutes after start, and checked once more when × closes the window (0.3.93), no duplicate watcher while queued; pushes only after DSH fully exits, then relaunches |
589
606
 
590
607
  - 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.
591
608
  - 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.
@@ -704,6 +721,8 @@ The log shows which path ran: `文件比较(快筛):比对 N 个,深哈
704
721
 
705
722
  | Date | Version | Summary |
706
723
  |---|---|---|
724
+ | 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
+ | 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 |
707
726
  | 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" |
708
727
  | 2026-11-24 | 0.3.91 | Settings summary row fetches before refreshing remote info (no longer stale, auto-refresh every 30s); four generate-script buttons replaced with Pull/Push now (closes DSH) sharing the automation queue |
709
728
  | 2026-11-24 | 0.3.90 | Jump tabs highlight the current section; "Local data" label removed from To-do; To-do expands to concrete session names and local profile files |
package/README.md CHANGED
@@ -277,6 +277,23 @@ 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
+ ### 清理跨重启僵死 watcher,锁不再被旧实例占死(0.3.94)
281
+
282
+ 实测「勾了开关、点 × 关闭还是不触发」还有一个更深的原因:插件更新流程重启 DSH 后,更新前排的那个 watcher 还在等**已经退出的旧 DSH 进程**(WatchPid 已死),却被 post-exit 的「进程名还有新实例」判断挡着不敢开工,于是僵死在 wait 段、一直占着 `~/.dsh/auto-sync.lock`。此时点 × 新排的 watcher 看到锁里 pid 存活且同为 push,就误判「同一个同步正在等」直接复用——复用的是一个永远不会执行的僵死 watcher,所以看着像彻底没触发。这次两处修复:
283
+
284
+ 1. **锁记录 watchPid、复用前查僵死**:`auto-sync.lock` 现在写入 `{pid, mode, watchPid: 当前 DSH pid, at}`。spawnWatcher 复用锁前先看 `watchPid` 是否还活着:watchPid 缺失(旧版锁)或对应 DSH 已退出 → 判定僵死,杀掉旧 watcher、清锁、重新排;只有 DSH 与 watcher 都还活着,且 mode 相同才复用。
285
+ 2. **post-exit wait 段自清过期 watcher**:当 WatchPid 已退出、而进程名还有实例时,比较这批 DSH 进程的启动时间——若它们全部晚于本等待进程,说明我们等的那次 DSH 早已退出重启,本 watcher 属于上一代残留:写日志、清掉自己那把锁、`exit 3` 让位,不再死等 30 分钟霸占锁。
286
+
287
+ 配套把 `post-exit.ps1` 同步进配置仓库的执行体镜像,保证走仓库兜底脚本时也是同一份修复。
288
+
289
+ ### 点 × 关闭 DSH 时立即判一次自动拉取/推送(0.3.93)
290
+
291
+ 勾了「启动时自动拉取」或「退出时自动推送」后,原来只有启动后的 8 秒首检 + 每 2 分钟复查会排队。如果你在两次复查之间做了改动就点右上角 × 关闭,那一刻没有 watcher 在等退出,关闭后什么都不会执行。现在补上退出钩子:点 ×(最后一个可见窗口关闭)时插件先判一次并排好 watcher,再退出客户端;DSH 进程归零后 watcher 立刻执行拉取/推送。
292
+
293
+ 1. **退出前判一次**:无可见窗口时调用 `triggerAutoSyncOnClose(config)`,读 `autoPull`/`autoPush` 开关;已有在途 watcher 就复用、不重复拉起;本机仓库为空时只有 autoPull 能排队(首次 clone)。
294
+ 2. **判据与复查完全一致**:拉取优先(云端领先 > 0 就排 pull,关闭时不弹确认框);推送按「领先提交 / 未提交改动 / 本机资料比上次同步新」三来源任一命中就排 push;`autoRestart` 语义统一为 `!== false`(默认重启)。
295
+ 3. **排队先于 quit**:必须在 `app.quit()` 之前 `await` 排队——插件随主进程退出而消失,quit 后再判就来不及。开关都关 / 无待同步内容时该函数很快返回,不影响关闭速度;排队成功写日志「退出前已排队 …:DSH 退出后立即执行」。
296
+
280
297
  ### 远端「未提交」纳入本机待同步 + 刷新按钮真正 fetch(0.3.92)
281
298
 
282
299
  针对「远端信息还是没更新」的实测根因:git 层的「落后/领先」确实是 0(本机 HEAD 与云端 gitee 一致),用户说的「没更新」其实是本机运行期新产生、还没 capture 进仓库的待同步数据。这次做两处实质性改动:
@@ -562,8 +579,8 @@ DSH 的会话标题会演进:先产生 fallback 临时标题(首条消息截
562
579
 
563
580
  | 开关 | 行为 |
564
581
  |---|---|
565
- | 启动时自动拉取 | 启动 8 秒后只读 `git fetch` 比对;落后 > 0 → 系统确认框 → 选"是"**当场把客户端整族退出**(实测 5 秒内进程归零)→ 可见窗口跑拉取 → 拉完自动重启 |
566
- | 退出时自动推送 | **三个来源任意命中就排队**:本地领先提交、未提交改动、本机资料比上次同步新(新会话等)。启动后每 2 分钟复查,已排队不重复拉起;等 DSH 完全退出后才 push,推完自动重启 |
582
+ | 启动时自动拉取 | 启动 8 秒后只读 `git fetch` 比对;落后 > 0 → 系统确认框 → 选"是"**当场把客户端整族退出**(实测 5 秒内进程归零)→ 可见窗口跑拉取 → 拉完自动重启。手动点 × 关闭时也会判一次并排队(0.3.93,关闭场景不弹确认框,云端领先就排) |
583
+ | 退出时自动推送 | **三个来源任意命中就排队**:本地领先提交、未提交改动、本机资料比上次同步新(新会话等)。启动后每 2 分钟复查,点 × 关闭时也会立即判一次(0.3.93),已排队不重复拉起;等 DSH 完全退出后才 push,推完自动重启 |
567
584
 
568
585
  - 动手由插件拉起 `runtime\post-exit.ps1 -Phase wait`(**隐藏**)盯退出;真退了才用 `-WindowStyle Normal` 起 `-Phase run` 的**可见**窗口,标题「DSH 配置同步 · 拉取/推送」。**排队期间不弹窗**。
569
586
  - 仓库还没就位(含空目录)时首检直接跳过,且不记成"检查失败"。
@@ -686,6 +703,8 @@ pwsh -File sync.ps1 push -ScanHistory
686
703
 
687
704
  | 日期 | 版本 | 要点 |
688
705
  |---|---|---|
706
+ | 2026-11-24 | 0.3.94 | 修复跨重启僵死 watcher 占锁:锁记 watchPid、复用前查僵死、旧锁杀掉重排;post-exit wait 段过期 watcher 自清让位;解决「勾了开关点 × 仍不触发」 |
707
+ | 2026-11-24 | 0.3.93 | 点 × 关闭 DSH 时立即判一次自动拉取/推送并排队 watcher,不再等 2 分钟复查窗口;autoRestart 语义统一为 !== false |
689
708
  | 2026-11-24 | 0.3.92 | 远端「未提交」纳入本机待同步数据(pending),刷新按钮真正触发 git fetch;解决「远端数字一直是 0」 |
690
709
  | 2026-11-24 | 0.3.91 | 设置-通用-配置同步摘要行展开时先 fetch 再刷新远端信息(不再陈旧、每 30 秒自动刷新);四个生成脚本按钮换成「立即拉取/推送(会关闭 DSH)」两个,走自动同步同一队列 |
691
710
  | 2026-11-24 | 0.3.90 | 顶部跳转按钮跟随当前位置高亮;待办去掉「本机数据」字眼、可展开看具体会话记录名与本机 profile |
package/index.js CHANGED
@@ -1630,17 +1630,27 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1630
1630
  if (isFile(lockFile)) {
1631
1631
  const lockText = readFileSync(lockFile, 'utf8')
1632
1632
  const lockPid = Number((lockText.match(/"pid"\s*:\s*(\d+)/) || [])[1])
1633
+ const lockWatchPid = Number((lockText.match(/"watchPid"\s*:\s*(\d+)/) || [])[1])
1633
1634
  if (lockPid > 0) {
1634
1635
  let alive = false
1635
1636
  try { process.kill(lockPid, 0); alive = true } catch { alive = false }
1636
- if (alive) {
1637
- const lockMode = (lockText.match(/"mode"\s*:\s*"([a-z]+)"/) || [])[1]
1638
- // 同一种同步已经在等,直接复用,别再加一个并行的
1637
+ const lockMode = (lockText.match(/"mode"\s*:\s*"([a-z]+)"/) || [])[1]
1638
+ // 僵死判定:锁文件没记 watchPid(旧版本锁),或记的 DSH pid 已经不在了。
1639
+ // 场景:插件更新重启后,旧 watcher 还在等已经死掉的旧 DSH 进程,却被「进程名还有新实例」
1640
+ // 挡着不敢开工,一直占着锁。此时它永远不会执行,必须杀掉重排,绝不能复用。
1641
+ let watcherOwnerAlive = false
1642
+ if (lockWatchPid > 0) { try { process.kill(lockWatchPid, 0); watcherOwnerAlive = true } catch { watcherOwnerAlive = false } }
1643
+ const stale = !lockWatchPid || !watcherOwnerAlive
1644
+ if (alive && !stale) {
1645
+ // 锁里的 DSH 还活着、watcher 也在 → 才是真正「同一个同步正在等」,可以直接复用
1639
1646
  if (lockMode === mode) return { ok: true, pid: lockPid, reused: true }
1640
1647
  // 不同的同步正在等(例如首检排了推送、用户在确认框点了拉取):用户的手动动作优先,
1641
1648
  // 干掉那个还没开工的等待进程,改排这一次。它此时只可能在等 DSH 退出,没有副作用。
1642
1649
  try { process.kill(lockPid) } catch { }
1643
1650
  logLaunch(dshHome, `取消上一个等待中的 ${lockMode || '同步'}(pid ${lockPid}),改排 ${mode}`)
1651
+ } else if (alive && stale) {
1652
+ try { process.kill(lockPid) } catch { }
1653
+ logLaunch(dshHome, `清理僵死 watcher(pid ${lockPid},其 DSH pid ${lockWatchPid || '未记录'} 已退出),改排 ${mode}`)
1644
1654
  }
1645
1655
  }
1646
1656
  try { unlinkSync(lockFile) } catch { }
@@ -1689,7 +1699,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1689
1699
  const pid = Number(String(stdout).trim().split(/\s+/).pop()) || 0
1690
1700
  autoState.watcherStartedAt = Date.now()
1691
1701
  try {
1692
- writeFileSync(lockFile, JSON.stringify({ pid, mode, at: Date.now() }), 'utf8')
1702
+ writeFileSync(lockFile, JSON.stringify({ pid, mode, watchPid: process.pid, at: Date.now() }), 'utf8')
1693
1703
  } catch { }
1694
1704
  logLaunch(dshHome, `已启动 ${mode} pid=${pid} exe=${exe} script=${script}`)
1695
1705
  return { ok: true, pid }
@@ -3525,6 +3535,86 @@ function scheduleAutoStart(config) {
3525
3535
  } catch { }
3526
3536
  }
3527
3537
 
3538
+ /**
3539
+ * 用户点右上角 × 关闭 DSH 时,立即判一次自动拉取/推送并排好 watcher(0.3.93)。
3540
+ *
3541
+ * 为什么要单独做:原来开关只在 scheduleAutoStart 的 8 秒首检 + 每 2 分钟复查里判,
3542
+ * 用户勾了开关、做了改动,没等到下一次复查就点 × 关掉 —— 那一刻没有任何 watcher 在排队,
3543
+ * 退出后自然什么都不执行,看着就像"勾了没用"。现在把「判一次并排队」接到关闭钩子上:
3544
+ * 点 × → 这里同步判一次 → 拉起独立 watcher → app.quit(),watcher 在 DSH 退出后照常执行,
3545
+ * 语义和手动「立即拉取/推送」完全一致。
3546
+ *
3547
+ * 关闭场景窗口都在关了,不弹确认框;autoPull 仍只在云端确实领先(或本机仓库还没内容)时才排队,
3548
+ * 免得没更新也白拉一次还把客户端重启回来。和 scheduleAutoStart 一样「拉取优先,二者只排一个」。
3549
+ */
3550
+ async function triggerAutoSyncOnClose(config) {
3551
+ const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
3552
+ try {
3553
+ const settings = readSettings(dshHome)
3554
+ if (!settings.autoPull && !settings.autoPush) return { queued: false }
3555
+ // 已经排过队(2 分钟复查 / 手动按钮)就别重复拉起 watcher:spawnWatcher 的锁也会挡,这里先省一次开销。
3556
+ // 注意:这里只信 autoState.pending(本进程内、一定带当前 DSH pid 的新 watcher)。跨重启的旧锁
3557
+ // 不带 autoState.pending,仍会往下走;由 spawnWatcher 里的僵死判定负责清理,绝不在这一步复用。
3558
+ if (autoState.pending && isProcessAlive(autoState.pending.watcherPid)) {
3559
+ return { queued: false, reused: true, mode: autoState.pending.mode }
3560
+ }
3561
+ const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
3562
+ if (!repo) return { queued: false }
3563
+ const appRoot = resolveAppRoot(config?.appRoot) || ''
3564
+ const phase = repoPhase(repo)
3565
+
3566
+ // 本机仓库还没内容:autoPull 可以直接排队(sync.ps1 首次 clone),autoPush 不行(要先确认云端为空)
3567
+ if (phase !== 'ok') {
3568
+ if (settings.autoPull && phase === 'empty') {
3569
+ const restart = settings.autoRestart !== false
3570
+ const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart })
3571
+ if (!started.ok) return { queued: false, error: started.error }
3572
+ autoState.pending = { mode: 'pull', at: Date.now(), reasonZh: '本机仓库为空,拉取初始化', reasonEn: 'Empty local repo — pull to initialize', restart, watcherPid: started.pid }
3573
+ return { queued: true, mode: 'pull' }
3574
+ }
3575
+ return { queued: false }
3576
+ }
3577
+
3578
+ const drift = await checkDrift(repo)
3579
+ if (!drift) return { queued: false }
3580
+
3581
+ // 拉取优先,和 scheduleAutoStart 一致;关闭时不再弹确认框,云端领先就排
3582
+ if (settings.autoPull && drift.behind > 0) {
3583
+ const restart = settings.autoRestart !== false
3584
+ const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart })
3585
+ if (!started.ok) return { queued: false, error: started.error }
3586
+ autoState.pending = {
3587
+ mode: 'pull', at: Date.now(), restart, watcherPid: started.pid,
3588
+ reasonZh: `退出前检查:云端领先 ${drift.behind} 个提交`, reasonEn: `Checked on exit: ${drift.behind} commit(s) behind`,
3589
+ }
3590
+ return { queued: true, mode: 'pull' }
3591
+ }
3592
+
3593
+ if (settings.autoPush) {
3594
+ // 判据和 scheduleAutoStart 完全相同:领先提交 / 未提交改动 / 本机资料比上次同步新
3595
+ let dirty = 0
3596
+ const raw = await git(repo, ['status', '--porcelain'])
3597
+ if (raw) dirty = raw.split('\n').filter((l) => l.trim()).length
3598
+ const syncState = readSyncState(dshHome)
3599
+ const lp = localPending(dshHome, syncState.lastSyncAt, config?.profileName, { repo, appRoot })
3600
+ const shouldPush = drift.ahead > 0 || dirty > 0 || (lp.known && lp.pending > 0)
3601
+ if (shouldPush) {
3602
+ const restart = settings.autoRestart !== false
3603
+ const reasonZh = drift.ahead > 0 ? `领先 ${drift.ahead} 个提交` : dirty > 0 ? `未提交 ${dirty} 项` : `本机 ${lp.pending} 个文件比上次同步新`
3604
+ const reasonEn = drift.ahead > 0 ? `${drift.ahead} commit(s) ahead` : dirty > 0 ? `${dirty} uncommitted change(s)` : `${lp.pending} file(s) newer than the last sync`
3605
+ const started = await spawnWatcher({ mode: 'push', repo, appRoot, dshHome, restart })
3606
+ if (!started.ok) return { queued: false, error: started.error }
3607
+ autoState.pending = { mode: 'push', at: Date.now(), reason: reasonZh, reasonZh, reasonEn, restart, watcherPid: started.pid }
3608
+ return { queued: true, mode: 'push' }
3609
+ }
3610
+ }
3611
+ return { queued: false }
3612
+ } catch (error) {
3613
+ logLaunch(dshHome, `退出前自动同步排队失败:${(error && error.message) || error}`)
3614
+ return { queued: false }
3615
+ }
3616
+ }
3617
+
3528
3618
  async function handlePrepare(req, res, config) {
3529
3619
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3530
3620
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
@@ -4624,7 +4714,7 @@ export function apply(ctx, config) {
4624
4714
  // 云端探测预热:插件一装上就去探一次(不阻塞、不 await)。这样面板打开时缓存多半已经热了,
4625
4715
  // status 不用再为首屏那 2.5 秒的 ls-remote 埋单。
4626
4716
  typeof setTimeout === 'function' ? setTimeout(() => { try { warmRemoteProbe(config) } catch { } }, 300) : null
4627
- installQuitWhenAllWindowsClosed(ctx)
4717
+ installQuitWhenAllWindowsClosed(ctx, config)
4628
4718
  // 0.3.76:会话投影缓存守卫的定时扫描(默认开,设置里可关)
4629
4719
  scheduleCacheGuard(config)
4630
4720
  } catch (error) {
@@ -4641,7 +4731,7 @@ export function apply(ctx, config) {
4641
4731
  * 而「退出后自动推送」的守护进程只认"主进程 pid 消失"——于是永远等不到,推送不执行。
4642
4732
  * 这里在窗口 closed 后查一遍:一个可见窗口都没有了就 app.quit()。
4643
4733
  */
4644
- function installQuitWhenAllWindowsClosed(ctx) {
4734
+ function installQuitWhenAllWindowsClosed(ctx, config) {
4645
4735
  try {
4646
4736
  const el = electronApp()
4647
4737
  if (!el) return
@@ -4651,11 +4741,20 @@ function installQuitWhenAllWindowsClosed(ctx) {
4651
4741
  el.app.on('browser-window-created', (_event, win) => {
4652
4742
  try {
4653
4743
  win.on('closed', () => {
4654
- setTimeout(() => {
4744
+ setTimeout(async () => {
4655
4745
  try {
4656
4746
  const alive = el.BrowserWindow.getAllWindows().filter((w) => w && !w.isDestroyed())
4657
4747
  const visible = alive.filter((w) => { try { return w.isVisible() } catch { return false } })
4658
4748
  if (visible.length === 0) {
4749
+ // 0.3.93:退出前判一次自动拉取/推送并排好 watcher,再 quit。
4750
+ // 必须在 app.quit() 之前 await:插件随主进程退出而消失,quit 后再判就来不及排队了。
4751
+ // 开关都关 / 没有待同步内容时这个函数很快返回,不影响关闭速度。
4752
+ try {
4753
+ const r = await triggerAutoSyncOnClose(config)
4754
+ if (r && r.queued) {
4755
+ try { ctx.logger?.info?.(`[${PACKAGE_ID}] 退出前已排队 ${r.mode}(自动同步):DSH 退出后立即执行`) } catch { }
4756
+ }
4757
+ } catch { }
4659
4758
  try { ctx.logger?.info?.(`[${PACKAGE_ID}] 已无可见窗口,退出客户端(好让退出后同步开始)`) } catch { }
4660
4759
  el.app.quit()
4661
4760
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-sync-plugin",
3
- "version": "0.3.92",
3
+ "version": "0.3.94",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
@@ -1,4 +1,4 @@
1
- <#
1
+ <#
2
2
  退出后执行同步:等 DSH 完全退出,再跑 pull 或 push(插件在 DSH 进程里,自己等不了自己退出)
3
3
 
4
4
  由插件在 DSH 运行期用 detached 方式拉起:
@@ -65,6 +65,29 @@ if ($Phase -eq 'wait') {
65
65
  $byPid = if ($WatchPid -gt 0) { Get-Process -Id $WatchPid -ErrorAction SilentlyContinue } else { $null }
66
66
  if ($byName.Count -eq 0 -and -not $byPid) { WaitLog 'DSH 已完全退出'; break }
67
67
 
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
+ $newerAll = @($byName | Where-Object { $_.StartTime -and $_.StartTime -ge $myStart })
77
+ if ($newerAll.Count -eq $byName.Count) {
78
+ WaitLog ('WatchPid {0} 已退出,现存 DSH 均为本等待启动后的新实例,判定为过期 watcher,退出让位' -f $WatchPid)
79
+ try {
80
+ $lockFile = Join-Path $DshHome 'auto-sync.lock'
81
+ if (Test-Path -LiteralPath $lockFile) {
82
+ $lock = Get-Content -LiteralPath $lockFile -Raw -Encoding utf8 | ConvertFrom-Json
83
+ if ($lock -and $lock.pid -eq $PID) { Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue }
84
+ }
85
+ } catch { }
86
+ exit 3
87
+ }
88
+ }
89
+ }
90
+
68
91
  # 用户点了窗口右上角的关闭、前台窗口全没了,但进程赖着不走(实测 7 个进程全部 hwnd=0 还活着)。
69
92
  # 不能只看「曾经出现过窗口」——等待进程可能是在窗口关掉之后才起来的(实测就这么漏判了),
70
93
  # 改用批次年龄:这批客户端进程已经活了 60 秒以上、却一个可见窗口都没有 → 认定用户已关闭。
@@ -1776,5 +1776,59 @@ console.log('== 0.3.86:本机数据挪进待办 + 会话显示会话名 + 按
1776
1776
  && idxSrc.includes("'plugin-data': ['插件数据', 'Plugin data']")
1777
1777
  && idxSrc.includes("mnemon: ['记忆数据', 'Memory data']"), '分组口径')
1778
1778
  }
1779
+ console.log('')
1780
+ console.log('== 0.3.93:点 × 关闭时判一次并排队自动拉取/推送 ==')
1781
+ {
1782
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1783
+ // 1) 新增退出前排队函数:读开关 / 复用在途 watcher / 空仓只拉 / 拉取优先 / 判据同 scheduleAutoStart
1784
+ check('退出前排队函数存在且读 autoPull/autoPush 开关',
1785
+ /async function triggerAutoSyncOnClose\(config\)/.test(idxSrc)
1786
+ && /if \(!settings\.autoPull && !settings\.autoPush\) return/.test(idxSrc), 'index.js triggerAutoSyncOnClose')
1787
+ check('已有在途 watcher 时复用、不重复拉起',
1788
+ /autoState\.pending[\s\S]{0,200}isProcessAlive\(autoState\.pending\.watcherPid\)[\s\S]{0,120}reused: true/.test(idxSrc), 'index.js 复用守卫')
1789
+ check('本机仓库为空时仅 autoPull 可排队初始化',
1790
+ /phase !== 'ok'[\s\S]{0,320}settings\.autoPull && phase === 'empty'/.test(idxSrc), 'index.js 空仓分支')
1791
+ check('退出前拉取优先:云端领先就排 pull(且不弹确认框)',
1792
+ /settings\.autoPull && drift\.behind > 0[\s\S]{0,420}mode: 'pull'/.test(idxSrc)
1793
+ && /退出前检查:云端领先/.test(idxSrc), 'index.js 拉取优先')
1794
+ check('退出前 push 判据与 scheduleAutoStart 一致(领先/未提交/本机待同步)',
1795
+ /const shouldPush = drift\.ahead > 0 \|\| dirty > 0 \|\| \(lp\.known && lp\.pending > 0\)/.test(idxSrc)
1796
+ && /if \(shouldPush\)/.test(idxSrc), 'index.js push 判据')
1797
+ check('退出前排队的 restart 语义统一为 autoRestart !== false',
1798
+ /function triggerAutoSyncOnClose[\s\S]{0,2600}settings\.autoRestart !== false/.test(idxSrc)
1799
+ && !/function triggerAutoSyncOnClose[\s\S]{0,2600}settings\.autoRestart === true/.test(idxSrc), 'index.js autoRestart')
1800
+ // 2) 关闭钩子:接 config、quit 之前 await 排队、再 quit;apply 内传 config
1801
+ check('关闭钩子接住 config(installQuitWhenAllWindowsClosed(ctx, config))',
1802
+ /function installQuitWhenAllWindowsClosed\(ctx, config\)/.test(idxSrc)
1803
+ && /installQuitWhenAllWindowsClosed\(ctx, config\)/.test(idxSrc), 'index.js 钩子签名与调用点')
1804
+ check('点 × 无可见窗口时先 await 退出前排队、再 app.quit()',
1805
+ /await triggerAutoSyncOnClose\(config\)[\s\S]{0,600}el\.app\.quit\(\)/.test(idxSrc), 'index.js 排队先于 quit')
1806
+ check('排队成功写日志:退出后立即执行',
1807
+ /退出前已排队 \$\{r\.mode\}(自动同步)/.test(idxSrc), 'index.js 排队日志')
1808
+ }
1809
+ console.log('')
1810
+ console.log('== 0.3.94:清理跨重启僵死 watcher,锁不再被旧实例占死 ==')
1811
+ {
1812
+ const idxSrc = existsSync(join(pluginRootSelf, 'index.js')) ? readFileSync(join(pluginRootSelf, 'index.js'), 'utf8') : ''
1813
+ const postSrc = existsSync(join(pluginRuntime, 'post-exit.ps1')) ? readFileSync(join(pluginRuntime, 'post-exit.ps1'), 'utf8') : ''
1814
+ check('锁文件写入 watchPid=当前 DSH pid',
1815
+ /JSON\.stringify\(\{ pid, mode, watchPid: process\.pid, at: Date\.now\(\) \}\)/.test(idxSrc), 'index.js 写锁')
1816
+ check('复用前先判定锁是否僵死:读取 lockWatchPid',
1817
+ /"watchPid"\\s\*:\\s\*\(\\d\+\)/.test(idxSrc)
1818
+ || idxSrc.includes('const lockWatchPid = Number('), 'index.js 读 watchPid')
1819
+ check('僵死判定:watchPid 缺失或其进程已退出',
1820
+ idxSrc.includes('const stale = !lockWatchPid || !watcherOwnerAlive')
1821
+ && /process\.kill\(lockWatchPid, 0\)/.test(idxSrc), 'index.js stale 判定')
1822
+ check('只在锁未僵死时才复用同 mode 的 watcher',
1823
+ /if \(alive && !stale\)[\s\S]{0,300}?if \(lockMode === mode\) return/.test(idxSrc), 'index.js 复用守卫')
1824
+ check('僵死锁会被杀掉并记日志,不再复用',
1825
+ /else if \(alive && stale\)/.test(idxSrc)
1826
+ && idxSrc.includes('清理僵死 watcher'), 'index.js 清僵死')
1827
+ check('post-exit wait:WatchPid 已死但进程名有新实例时判定过期 watcher',
1828
+ postSrc.includes('-not $byPid -and $byName.Count -gt 0')
1829
+ && postSrc.includes('判定为过期 watcher'), 'post-exit.ps1 过期判定')
1830
+ check('post-exit wait:过期 watcher 清自己的锁并 exit 3 让位',
1831
+ /\$lock\.pid -eq \$PID/.test(postSrc) && /\bexit 3\b/.test(postSrc), 'post-exit.ps1 让位')
1832
+ }
1779
1833
  process.exit(failures === 0 ? 0 : 1)
1780
1834