dsh-profile-config-sync 0.4.1 → 0.5.0

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/client.js CHANGED
@@ -172,7 +172,16 @@ window.__ModuleLoader__.load({
172
172
  kvRow: { display: 'flex', gap: '10px', fontSize: '12px', lineHeight: '18px', alignItems: 'flex-start', padding: '2px 0' },
173
173
  kvKey: { minWidth: '100px', width: '100px', flexShrink: 0, color: 'var(--dsw-alias-label-tertiary)' },
174
174
  kvVal: { flex: 1, minWidth: 0, color: 'var(--dsw-alias-label-secondary)', overflowWrap: 'break-word' },
175
- advice: { fontSize: '12px', lineHeight: '19px', color: 'var(--dsw-alias-label-secondary)', margin: 0, paddingLeft: '18px', display: 'flex', flexDirection: 'column', gap: '2px' },
175
+ advice: { fontSize: '12px', lineHeight: '20px', color: 'var(--dsw-alias-label-secondary)', margin: 0, paddingLeft: '18px', display: 'flex', flexDirection: 'column', gap: '4px' },
176
+ anchorBtn: {
177
+ display: 'inline-flex', alignItems: 'center', gap: '3px',
178
+ marginLeft: '8px', padding: '1px 9px', borderRadius: '999px',
179
+ fontSize: '11.5px', lineHeight: '18px', fontWeight: 600,
180
+ border: '1px solid var(--dsw-alias-toast-action)',
181
+ background: 'color-mix(in srgb, var(--dsw-alias-toast-action) 10%, transparent)',
182
+ color: 'var(--dsw-alias-toast-action)', cursor: 'pointer',
183
+ verticalAlign: 'baseline', textDecoration: 'none',
184
+ },
176
185
  actions: { display: 'flex', gap: '8px', flexWrap: 'wrap', alignItems: 'center' },
177
186
  hint: { fontSize: '12px', lineHeight: '19px', color: 'var(--dsw-alias-label-tertiary)', wordBreak: 'break-all' },
178
187
  code: {
@@ -800,8 +809,59 @@ window.__ModuleLoader__.load({
800
809
  )
801
810
  }
802
811
 
812
+ /** 根据待办文案与当前体检状态映射直达目标区(用于「待办」里的锚文本快捷按钮)。 */
813
+ function adviceTarget(text, data) {
814
+ const s = String(text || '')
815
+ const webdavOn = Boolean(data && data.webdav && data.webdav.active)
816
+ if (/初始化推送|Initialize push/i.test(s)) {
817
+ return { section: 'automation', label: M('前往初始化推送 →', 'Go to initialize push →') }
818
+ }
819
+ if (/连不上 WebDAV|Cannot reach WebDAV/i.test(s)) {
820
+ return { section: 'platform', label: M('检查 WebDAV →', 'Check WebDAV →') }
821
+ }
822
+ if (/连不上云端|云端仓库地址|Cloud repo is not set|Cannot reach the cloud/i.test(s)) {
823
+ return { section: webdavOn ? 'platform' : 'targets', label: webdavOn ? M('检查 WebDAV →', 'Check WebDAV →') : M('去配置云端 →', 'Go to cloud settings →') }
824
+ }
825
+ if (/拉取|run Pull|\bPull\b/i.test(s) && !/只允许拉取|only Pull is allowed/i.test(s)) {
826
+ return { section: 'automation', label: M('前往立即拉取 →', 'Go to pull →') }
827
+ }
828
+ if (/只允许拉取|only Pull is allowed/i.test(s)) {
829
+ return { section: webdavOn ? 'platform' : 'targets', label: webdavOn ? M('检查 WebDAV →', 'Check WebDAV →') : M('检查云端配置 →', 'Check cloud config →') }
830
+ }
831
+ if (/推送|run Push|\bPush\b/i.test(s)) {
832
+ return { section: 'automation', label: M('前往立即推送 →', 'Go to push →') }
833
+ }
834
+ if (/仓库路径|本机仓库|Repo path|repo directory is not set|Local repo/i.test(s)) {
835
+ return { section: 'targets', label: M('去设置仓库 →', 'Go to repo settings →') }
836
+ }
837
+ if (/客户端根目录|client root/i.test(s)) {
838
+ return { section: 'roots', openRoots: true, label: M('检查本机路径 →', 'Check local paths →') }
839
+ }
840
+ if (/客户端版本|two clients differ/i.test(s)) {
841
+ return { section: 'platform', label: M('查看跨端契约 →', 'View contract →') }
842
+ }
843
+ if (/bundle|依赖|dependency/i.test(s)) {
844
+ return { section: 'actions', label: M('查看生成脚本 →', 'View scripts →') }
845
+ }
846
+ return null
847
+ }
848
+
803
849
  function Advice(props) {
804
- return h('ul', { style: S.advice }, (props.items || []).map((a, i) => h('li', { key: i }, a)))
850
+ const onNav = typeof props.onNavigate === 'function' ? props.onNavigate : null
851
+ return h('ul', { style: S.advice }, (props.items || []).map((a, i) => {
852
+ const target = onNav ? adviceTarget(a, props.data) : null
853
+ return h('li', { key: i },
854
+ h('span', null, a),
855
+ target
856
+ ? h('button', {
857
+ type: 'button',
858
+ style: S.anchorBtn,
859
+ title: M('点击直达对应操作区', 'Jump directly to this section'),
860
+ onClick: () => onNav(target),
861
+ }, target.label)
862
+ : null,
863
+ )
864
+ }))
805
865
  }
806
866
 
807
867
  function MadeNote(props) {
@@ -2258,6 +2318,10 @@ window.__ModuleLoader__.load({
2258
2318
  setMsg(d
2259
2319
  ? M(`云端:落后 ${d.behind} 个提交,领先 ${d.ahead} 个提交`, `Cloud: ${d.behind} commit(s) behind, ${d.ahead} ahead`)
2260
2320
  : (body.error || M('读不到远端', 'Cannot read the remote')))
2321
+ } else if (action === 'push-live') {
2322
+ setMsg(body.alreadyRunning
2323
+ ? M('后台推送已在运行中,请稍候…', 'Live push is already running…')
2324
+ : M('已开始后台推送(不关闭 DSH),进度与结果会在下方实时更新', 'Live push started in background (DSH stays open) — status updates below'))
2261
2325
  } else {
2262
2326
  setMsg(body.closeRequested
2263
2327
  ? M('已排队:客户端马上关闭,退出后执行;拉取完成后按设置自动重开', 'Queued: the client closes now and the sync runs after exit; it relaunches per your settings when pulling finishes')
@@ -2299,6 +2363,8 @@ window.__ModuleLoader__.load({
2299
2363
  }
2300
2364
 
2301
2365
  const pending = auto.pending
2366
+ const livePush = auto.livePush || null
2367
+ const liveRunning = Boolean(livePush && livePush.running)
2302
2368
  // 后台调度拿不到请求语言,宿主把原因中英各存一份,这里按当前界面语言挑
2303
2369
  const pendingReason = pending ? (langIsZh() ? (pending.reasonZh || pending.reason) : (pending.reasonEn || pending.reason)) : ''
2304
2370
  return h('div', { style: S.card },
@@ -2332,26 +2398,66 @@ window.__ModuleLoader__.load({
2332
2398
  h('button', {
2333
2399
  type: 'button',
2334
2400
  style: canPullNow ? S.btnPrimary : { ...S.btnPrimary, opacity: 0.5, cursor: 'not-allowed' },
2335
- disabled: Boolean(busy) || !canPullNow,
2401
+ disabled: Boolean(busy) || !canPullNow || liveRunning,
2336
2402
  title: canPullNow ? '' : M('云端还是空的:没有内容可拉,先「初始化推送」', 'The cloud is still empty — nothing to pull, initialize push first'),
2337
2403
  onClick: () => act('pull-now'),
2338
2404
  }, M('立即拉取(会关闭 DSH)', 'Pull now (closes DSH)')),
2339
2405
  h('button', {
2340
2406
  type: 'button',
2341
- style: pushAllowed ? S.btnPrimary : { ...S.btnPrimary, opacity: 0.5, cursor: 'not-allowed' },
2342
- disabled: Boolean(busy) || !pushAllowed,
2343
- title: pushAllowed ? '' : M('云端已有内容:本机还是空的,先拉取', 'The cloud already has content — pull first'),
2407
+ style: (pushAllowed && !liveRunning) ? S.btnPrimary : { ...S.btnPrimary, opacity: 0.5, cursor: 'not-allowed' },
2408
+ disabled: Boolean(busy) || !pushAllowed || liveRunning,
2409
+ title: pushAllowed
2410
+ ? M('不关闭 DSH 直接在后台抓配置并上传(只读本地配置,安全不打断当前对话)', 'Capture and push in background without closing DSH')
2411
+ : M('云端已有内容:本机还是空的,先拉取', 'The cloud already has content — pull first'),
2412
+ onClick: () => act('push-live'),
2413
+ }, liveRunning
2414
+ ? M('后台推送中…', 'Pushing in background…')
2415
+ : (initMode
2416
+ ? M('初始化推送(不关 DSH)', 'Initialize push (keep DSH open)')
2417
+ : M('立即推送(不关 DSH)', 'Push now (keep DSH open)'))),
2418
+ h('button', {
2419
+ type: 'button',
2420
+ style: (pushAllowed && !liveRunning) ? S.btn : { ...S.btn, opacity: 0.5, cursor: 'not-allowed' },
2421
+ disabled: Boolean(busy) || !pushAllowed || liveRunning,
2422
+ title: pushAllowed
2423
+ ? M('先退出 DSH 再推,可确保内存中尚未落盘的改动一并写入', 'Exit DSH before pushing so in-memory changes flush first')
2424
+ : M('云端已有内容:本机还是空的,先拉取', 'The cloud already has content — pull first'),
2344
2425
  onClick: () => act('push-now'),
2345
2426
  }, initMode
2346
2427
  ? M('初始化推送(会关闭 DSH)', 'Initialize push (closes DSH)')
2347
- : M('立即推送(会关闭 DSH)', 'Push now (closes DSH)')),
2428
+ : M('退出后推送(会关闭 DSH)', 'Push after exit (closes DSH)')),
2348
2429
  pending ? h('button', { type: 'button', style: S.btn, disabled: Boolean(busy), onClick: () => act('cancel') }, M('取消排队', 'Cancel queue')) : null,
2349
2430
  ),
2431
+ livePush && (livePush.running || livePush.finishedAt)
2432
+ ? h('div', {
2433
+ style: {
2434
+ padding: '8px 10px', borderRadius: '8px', fontSize: '12px', lineHeight: '18px',
2435
+ border: '1px solid ' + (livePush.running
2436
+ ? 'var(--dsw-alias-toast-action)'
2437
+ : (livePush.ok ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)')),
2438
+ background: 'var(--dsw-alias-fill-l1, var(--dsw-alias-bg-layer-2))',
2439
+ color: livePush.running
2440
+ ? 'var(--dsw-alias-label-primary)'
2441
+ : (livePush.ok ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)'),
2442
+ },
2443
+ },
2444
+ h('div', { style: { fontWeight: 600 } },
2445
+ (livePush.running ? '⏳ ' : (livePush.ok ? '✓ ' : '✕ ')) + (livePush.message || '')),
2446
+ livePush.finishedAt
2447
+ ? h('div', { style: { ...S.footnote, marginTop: '2px' } },
2448
+ M(`完成时间:${new Date(livePush.finishedAt).toLocaleTimeString(localeNow(), { hour12: false })}`,
2449
+ `Finished at: ${new Date(livePush.finishedAt).toLocaleTimeString(localeNow(), { hour12: false })}`)
2450
+ + (livePush.log ? ` · ${livePush.log}` : ''))
2451
+ : (livePush.log
2452
+ ? h('div', { style: { ...S.footnote, marginTop: '2px' } }, M(`日志:${livePush.log}`, `Log: ${livePush.log}`))
2453
+ : null),
2454
+ )
2455
+ : null,
2350
2456
  initMode
2351
2457
  ? h('div', { style: { ...S.hint, color: 'var(--dsw-alias-state-warn-primary)' } },
2352
2458
  M(
2353
- '本机仓库和云端仓库都还是空的:点「初始化推送」会把本机配置当作仓库的初始内容推上去(自动 git init + 写仓库骨架 + capture + 提交 + 推送)。这时没有东西可拉,拉取按钮是灰的。',
2354
- 'Both the local repo and the cloud are empty: Initialize push uploads this machine\'s config as the repo\'s initial content (git init + repo skeleton + capture + commit + push). There is nothing to pull yet, so Pull stays disabled.',
2459
+ '本机仓库和云端仓库都还是空的:点「初始化推送(不关 DSH)」会直接在后台抓配置并上传;若需先让内存状态完全落盘,也可选「初始化推送(会关闭 DSH)」。这时没有东西可拉,拉取按钮是灰的。',
2460
+ 'Both the local repo and the cloud are empty: "Initialize push (keep DSH open)" captures and uploads in background; use "(closes DSH)" if you want in-memory state flushed first. Pull stays disabled until content exists.',
2355
2461
  ))
2356
2462
  : null,
2357
2463
  (!pushAllowed || !canPullNow)
@@ -2669,6 +2775,57 @@ window.__ModuleLoader__.load({
2669
2775
  return () => { alive = false; clearInterval(timer) }
2670
2776
  }, [])
2671
2777
 
2778
+ const lastLiveFinishedRef = react.useRef(0)
2779
+
2780
+ const jumpToSection = (sid, opts) => {
2781
+ if (!sid) return
2782
+ if (opts && opts.openRoots && !showRoots) setShowRoots(true)
2783
+ setActiveSection(sid)
2784
+ const scrollNow = () => {
2785
+ const el = document.getElementById('sync-section-' + sid)
2786
+ if (!el || !el.scrollIntoView) return
2787
+ el.scrollIntoView({ behavior: 'smooth', block: 'start' })
2788
+ try {
2789
+ if (typeof el.animate === 'function') {
2790
+ el.animate([
2791
+ { boxShadow: '0 0 0 2px var(--dsw-alias-toast-action)' },
2792
+ { boxShadow: '0 0 0 0px transparent' },
2793
+ ], { duration: 1500, easing: 'ease-out' })
2794
+ }
2795
+ } catch { }
2796
+ }
2797
+ if (opts && opts.openRoots && !showRoots) {
2798
+ setTimeout(scrollNow, 60)
2799
+ } else {
2800
+ scrollNow()
2801
+ }
2802
+ }
2803
+
2804
+ // 后台在线推送进行中时,每 1.5s 轮询状态直到结束,并弹出完成/失败提示
2805
+ const liveRunning = Boolean(data && data.auto && data.auto.livePush && data.auto.livePush.running)
2806
+ react.useEffect(() => {
2807
+ if (!liveRunning) return undefined
2808
+ const timer = setInterval(() => {
2809
+ if (typeof refresh === 'function') refresh()
2810
+ }, 1500)
2811
+ return () => clearInterval(timer)
2812
+ }, [liveRunning])
2813
+
2814
+ react.useEffect(() => {
2815
+ const lp = data && data.auto && data.auto.livePush
2816
+ if (!lp || lp.running || !lp.finishedAt) return
2817
+ if (lastLiveFinishedRef.current === 0) {
2818
+ // 首次挂载时如果已经是很久以前完成的旧记录不重弹;10 秒内刚完成则弹提示
2819
+ if (Date.now() - lp.finishedAt > 10000) {
2820
+ lastLiveFinishedRef.current = lp.finishedAt
2821
+ return
2822
+ }
2823
+ }
2824
+ if (lastLiveFinishedRef.current === lp.finishedAt) return
2825
+ lastLiveFinishedRef.current = lp.finishedAt
2826
+ showToast(lp.message || (lp.ok ? M('推送完成', 'Push completed') : M('推送失败', 'Push failed')))
2827
+ }, [data])
2828
+
2672
2829
  // 上次「退出后自动同步」的结果:15 分钟内、且没弹过,就弹 5 秒提示。
2673
2830
  // 判据与「启动即弹」共用 takeFreshResult(同一个 localStorage 键,不会弹两次)。
2674
2831
  react.useEffect(() => {
@@ -2964,11 +3121,20 @@ window.__ModuleLoader__.load({
2964
3121
  }, pendingDetailOpen ? M('收起', 'Collapse') : M('展开', 'Expand'))
2965
3122
  : null,
2966
3123
  ),
2967
- pendingDetailOpen ? localBlock : (localBlock ? h('div', { style: S.footnote }, M(
2968
- `${data.local.pending > 0 ? `有 ${data.local.pending} 个文件待推送` : '没有新写入'} · 点「展开」看具体会话记录与本机 profile`,
2969
- `${data.local.pending > 0 ? `${data.local.pending} file(s) to push` : 'nothing new'} · click Expand for session names and local profile`,
2970
- )) : null),
2971
- data && Array.isArray(data.advice) && data.advice.length ? h(Advice, { items: data.advice }) : null)
3124
+ pendingDetailOpen ? localBlock : (localBlock ? h('div', { style: S.footnote },
3125
+ h('span', null, M(
3126
+ `${data.local.pending > 0 ? `有 ${data.local.pending} 个文件待推送` : '没有新写入'} · 点「展开」看具体会话记录与本机 profile`,
3127
+ `${data.local.pending > 0 ? `${data.local.pending} file(s) to push` : 'nothing new'} · click Expand for session names and local profile`,
3128
+ )),
3129
+ data.local.pending > 0
3130
+ ? h('button', {
3131
+ type: 'button',
3132
+ style: S.anchorBtn,
3133
+ onClick: () => jumpToSection('automation'),
3134
+ }, M('前往立即推送 →', 'Go to push →'))
3135
+ : null,
3136
+ ) : null),
3137
+ data && Array.isArray(data.advice) && data.advice.length ? h(Advice, { items: data.advice, data, onNavigate: jumpToSection }) : null)
2972
3138
  : null,
2973
3139
  )
2974
3140
 
@@ -3141,12 +3307,7 @@ window.__ModuleLoader__.load({
3141
3307
  fontWeight: active ? 600 : 400,
3142
3308
  },
3143
3309
  title: active ? M('当前所在区', 'Current section') : M('跳转到此区', 'Jump to section'),
3144
- onClick: () => {
3145
- setActiveSection(sid)
3146
- const el = document.getElementById('sync-section-' + sid)
3147
- if (!el || !el.scrollIntoView) return
3148
- el.scrollIntoView({ behavior: 'smooth', block: 'start' })
3149
- },
3310
+ onClick: () => jumpToSection(sid),
3150
3311
  }, label)
3151
3312
  }),
3152
3313
  ),
package/index.js CHANGED
@@ -1261,6 +1261,8 @@ async function inspect(config) {
1261
1261
  script: autoScript(dshHome, repo),
1262
1262
  // post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
1263
1263
  lastResult: readAutoResult(dshHome),
1264
+ // 不关闭 DSH 的在线推送状态(running / finishedAt / ok / phase / message / log)
1265
+ livePush: { ...autoState.livePush },
1264
1266
  },
1265
1267
  // 拉取被本机文件挡住时 sync.ps1 留下的冲突清单,面板「同步冲突」卡据此渲染
1266
1268
  conflicts: (() => {
@@ -1766,6 +1768,16 @@ const autoState = {
1766
1768
  watcherStartedAt: 0,
1767
1769
  timer: null,
1768
1770
  interval: null, // 每 2 分钟的复查(会话/资料是运行中产生的,只判一次会全漏)
1771
+ livePush: {
1772
+ running: false,
1773
+ startedAt: 0,
1774
+ finishedAt: 0,
1775
+ ok: null,
1776
+ phase: '',
1777
+ message: '',
1778
+ log: '',
1779
+ initPush: false,
1780
+ },
1769
1781
  }
1770
1782
 
1771
1783
  function autoScript(dshHome, repo) {
@@ -1956,21 +1968,39 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1956
1968
  }
1957
1969
  } catch { }
1958
1970
 
1971
+ const logsDir = join(dshHome, 'logs')
1972
+ try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
1973
+ const pidFile = join(logsDir, `.watch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.pid`)
1974
+
1959
1975
  const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
1960
1976
  // 这一段是「等待态」:隐藏进程只盯着 DSH 退出,退出后才由它拉起一个可见窗口干活,
1961
1977
  // 否则排队期间(可能几小时)会一直挂着一个挡视线的空窗口。
1962
- '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome]
1978
+ '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome,
1979
+ '-PidFile', pidFile]
1963
1980
  if (repo) args.push('-RepoRoot', repo)
1964
1981
  if (appRoot) args.push('-AppRoot', appRoot)
1965
1982
  if (restart) args.push('-Restart')
1966
1983
  // 更新模式要带上下载地址与校验值,交给 post-exit 的 run 段执行
1967
1984
  if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
1968
1985
  const exe = powershellExe()
1986
+ const argLine = args.map((a) => psWinArg(a)).join(' ')
1969
1987
  const inner = [
1970
- // 等待态进程保持**隐藏**;可见窗口由 post-exit.ps1 在 DSH 真正退出后自己弹(-Phase run)。
1971
- // 每个元素先经 psWinArg 加内层双引号,防止 AppRoot/RepoRoot 含空格时被 Start-Process 拆开。
1988
+ // DSH 在 Windows 下位于带 KILL_ON_JOB_CLOSE 且禁止 BREAKAWAY 的 Job Object 内;
1989
+ // 直接 Start-Process 会继承同一 Job Object,DSH 一退等待进程就被连杀。
1990
+ // 优先通过 Shell.Application.ShellExecute 委托 explorer.exe 启动(inJob=False),
1991
+ // 等待脚本写出真实 PID;若无桌面 Shell 再兜底退回 Start-Process。
1992
+ 'try {',
1993
+ ` (New-Object -ComObject Shell.Application).ShellExecute(${psQuote(exe)}, ${psQuote(argLine)}, ${psQuote(dshHome)}, 'open', 0)`,
1994
+ ` for ($i = 0; $i -lt 35; $i++) {`,
1995
+ ` if (Test-Path -LiteralPath ${psQuote(pidFile)}) {`,
1996
+ ` $v = (Get-Content -LiteralPath ${psQuote(pidFile)} -Raw -ErrorAction SilentlyContinue).Trim()`,
1997
+ ` if ($v -match '^\\d+$') { Write-Output "explorer:$v"; exit 0 }`,
1998
+ ' }',
1999
+ ' Start-Sleep -Milliseconds 150',
2000
+ ' }',
2001
+ '} catch { }',
1972
2002
  `$p = Start-Process -FilePath ${psQuote(exe)} -ArgumentList @(${args.map((a) => psQuote(psWinArg(a))).join(', ')}) -WindowStyle Hidden -PassThru`,
1973
- 'Write-Output $p.Id',
2003
+ 'Write-Output "direct:$($p.Id)"',
1974
2004
  ].join('; ')
1975
2005
  const encoded = Buffer.from(inner, 'utf16le').toString('base64')
1976
2006
  let child
@@ -1978,6 +2008,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1978
2008
  child = spawn(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
1979
2009
  { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
1980
2010
  } catch (error) {
2011
+ try { unlinkSync(pidFile) } catch { }
1981
2012
  const msg = String((error && error.message) || error)
1982
2013
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${msg}`)
1983
2014
  return { ok: false, error: t(`拉不起 powershell(${exe}):${msg}`, `Cannot launch PowerShell (${exe}): ${msg}`) }
@@ -1987,22 +2018,25 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1987
2018
  child.stdout.on('data', (c) => { stdout += c })
1988
2019
  child.stderr.on('data', (c) => { stderr += c })
1989
2020
  const code = await new Promise((resolve) => {
1990
- const timer = setTimeout(() => resolve('timeout'), 8000)
2021
+ const timer = setTimeout(() => resolve('timeout'), 10000)
1991
2022
  child.once('exit', (c) => { clearTimeout(timer); resolve(c) })
1992
2023
  child.once('error', (e) => { clearTimeout(timer); resolve('error:' + ((e && e.message) || e)) })
1993
2024
  })
2025
+ try { unlinkSync(pidFile) } catch { }
1994
2026
  if (code !== 0) {
1995
2027
  const detail = String(stderr || stdout || code).trim().slice(0, 300)
1996
2028
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${detail}`)
1997
2029
  return { ok: false, error: t(`拉不起 post-exit(launcher 退出码 ${code}):${detail}`, `Cannot launch post-exit (launcher exit code ${code}): ${detail}`) }
1998
2030
  }
1999
- const pid = Number(String(stdout).trim().split(/\s+/).pop()) || 0
2031
+ const token = String(stdout).trim().split(/\s+/).pop() || ''
2032
+ const via = token.startsWith('explorer:') ? 'explorer' : 'direct'
2033
+ const pid = Number(token.replace(/^(explorer|direct):/, '')) || 0
2000
2034
  autoState.watcherStartedAt = Date.now()
2001
2035
  try {
2002
2036
  writeFileSync(lockFile, JSON.stringify({ pid, mode, at: Date.now() }), 'utf8')
2003
2037
  } catch { }
2004
- logLaunch(dshHome, `已启动 ${mode} pid=${pid} exe=${exe} script=${script}`)
2005
- return { ok: true, pid }
2038
+ logLaunch(dshHome, `已启动 ${mode} pid=${pid} via=${via} exe=${exe} script=${script}`)
2039
+ return { ok: true, pid, via }
2006
2040
  }
2007
2041
 
2008
2042
  /**
@@ -3607,6 +3641,187 @@ async function handleStatus(req, res, config) {
3607
3641
  * {action:'cancel'} 取消已排队的动作
3608
3642
  * 只做只读 fetch 比对(check),真正动手一律交给退出后的 post-exit.ps1。
3609
3643
  */
3644
+ async function ensurePushAllowed(repo, settings) {
3645
+ // 推送的门禁:真仓库直接推;本机还是空的,只有「云端确实没有文件」才能推 —— 那次推送就是初始化推送。
3646
+ // 云端已有文件时拒绝,让用户先拉取(否则本机状态会被写进一份已经在用的历史里)。
3647
+ // 注意判据是「树里有文件」而不是「有分支」:远端可能只剩一个空分支,那也是空仓库,可以初始化推送。
3648
+ if (repoPhase(repo) === 'ok') return
3649
+ const useWebdav = webdavActive(settings)
3650
+ const url = useWebdav
3651
+ ? normalizeWebdav(settings).url
3652
+ : ((await git(repo, ['remote', 'get-url', 'origin'])) || settings.remoteUrl || '')
3653
+ const probe = useWebdav ? await probeWebdavRemote(settings) : await probeRemote(url, settings)
3654
+ if (!probe || probe.files === null) {
3655
+ throw new Error(t(
3656
+ useWebdav
3657
+ ? `连不上 WebDAV(${url || '未配置'}):${(probe && probe.error) || '初始化推送要先确认云端是空目录'}`
3658
+ : `连不上云端、或还没有云端仓库地址(${url || '未配置'}):初始化推送要先确认云端是空仓库`,
3659
+ useWebdav
3660
+ ? `Cannot reach WebDAV (${url || 'not set'}): ${(probe && probe.error) || 'initialize push needs to confirm the cloud folder is empty.'}`
3661
+ : `Cannot reach the cloud or no remote URL is set (${url || 'not set'}): initialize push needs to confirm the cloud repo is still empty.`,
3662
+ ))
3663
+ }
3664
+ if (probe.files > 0) {
3665
+ throw new Error(t(
3666
+ `云端仓库已经有内容(${probe.files} 个文件):本机还是空的,先「拉取」把内容拉下来,再生成推送`,
3667
+ `The cloud repo already has content (${probe.files} file(s)): run Pull to fetch it first, then push.`,
3668
+ ))
3669
+ }
3670
+ }
3671
+
3672
+ function startLivePush({ repo, dshHome, appRoot, settings }) {
3673
+ if (autoState.livePush.running) {
3674
+ return { alreadyRunning: true, livePush: { ...autoState.livePush } }
3675
+ }
3676
+ const initPush = repoPhase(repo) !== 'ok'
3677
+ const logsDir = join(dshHome, 'logs')
3678
+ try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
3679
+ const d = new Date()
3680
+ const pad = (n) => String(n).padStart(2, '0')
3681
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
3682
+ const logFile = join(logsDir, `live-push-${stamp}.log`)
3683
+
3684
+ let cmd = ''
3685
+ let cmdArgs = []
3686
+ if (IS_WIN) {
3687
+ const syncScript = [join(pluginRoot(), 'runtime', 'sync.ps1'), join(repo, 'sync.ps1')].find((p) => isFile(p))
3688
+ if (!syncScript) throw new Error(t('找不到 sync.ps1,无法在线推送', 'sync.ps1 not found — cannot run live push'))
3689
+ const psArgs = [
3690
+ `Action = 'push'`,
3691
+ `RepoRoot = ${psQuote(repo)}`,
3692
+ `DshHome = ${psQuote(dshHome)}`,
3693
+ ...(appRoot ? [`AppRoot = ${psQuote(appRoot)}`] : []),
3694
+ `Force = $true`,
3695
+ ].join('; ')
3696
+ const psCmd = `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); $OutputEncoding = [Console]::OutputEncoding; $a = @{ ${psArgs} }; & ${psQuote(syncScript)} @a; exit $LASTEXITCODE`
3697
+ cmd = powershellExe()
3698
+ cmdArgs = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(psCmd, 'utf16le').toString('base64')]
3699
+ } else {
3700
+ const engine = [join(pluginRoot(), 'runtime', 'sync-engine.mjs'), join(repo, 'sync-engine.mjs')].find((p) => isFile(p))
3701
+ if (!engine) throw new Error(t('找不到 sync-engine.mjs,无法在线推送', 'sync-engine.mjs not found — cannot run live push'))
3702
+ cmd = hostNodeExe(appRoot) || process.execPath
3703
+ cmdArgs = [engine, 'push', '-RepoRoot', repo, '-DshHome', dshHome, ...(appRoot ? ['-AppRoot', appRoot] : [])]
3704
+ }
3705
+
3706
+ autoState.livePush = {
3707
+ running: true,
3708
+ startedAt: Date.now(),
3709
+ finishedAt: 0,
3710
+ ok: null,
3711
+ phase: 'starting',
3712
+ message: initPush
3713
+ ? t('正在后台初始化推送(不关闭 DSH)…', 'Initializing push in background (DSH stays open)…')
3714
+ : t('正在后台抓取并推送(不关闭 DSH)…', 'Capturing and pushing in background (DSH stays open)…'),
3715
+ log: logFile,
3716
+ initPush,
3717
+ }
3718
+
3719
+ const tail = []
3720
+ const appendLog = (chunk) => {
3721
+ const text = String(chunk || '')
3722
+ try { writeFileSync(logFile, text, { flag: 'a' }) } catch { }
3723
+ for (const rawLine of text.split(/\r?\n/)) {
3724
+ const line = rawLine.trim()
3725
+ if (!line) continue
3726
+ tail.push(line)
3727
+ if (tail.length > 50) tail.shift()
3728
+ if (/==\s*初始化仓库/.test(line)) {
3729
+ autoState.livePush.phase = 'init'
3730
+ autoState.livePush.message = t('正在初始化仓库骨架…', 'Initializing repo skeleton…')
3731
+ } else if (/==\s*抓取|capture/.test(line)) {
3732
+ autoState.livePush.phase = 'capture'
3733
+ autoState.livePush.message = t('正在抓取本机配置与会话…', 'Capturing local config and sessions…')
3734
+ } else if (/==\s*提交/.test(line)) {
3735
+ autoState.livePush.phase = 'commit'
3736
+ autoState.livePush.message = t('正在提交本机变更…', 'Committing local changes…')
3737
+ } else if (/==\s*上传到 WebDAV|WebDAV 上传|==\s*推送/.test(line)) {
3738
+ autoState.livePush.phase = 'upload'
3739
+ autoState.livePush.message = t('正在上传到云端…', 'Uploading to cloud…')
3740
+ }
3741
+ }
3742
+ }
3743
+
3744
+ const finish = async (ok, errText) => {
3745
+ clearWebdavProbeCache()
3746
+ if (ok) {
3747
+ try {
3748
+ if (webdavActive(settings)) {
3749
+ const wp = await probeWebdavRemote(settings)
3750
+ if (wp && wp.files !== null) {
3751
+ autoState.drift = { ahead: 0, behind: 0, transport: 'webdav', files: wp.files, at: Date.now() }
3752
+ autoState.lastCheckAt = Date.now()
3753
+ autoState.lastCheckError = ''
3754
+ }
3755
+ } else {
3756
+ const d2 = await checkDrift(repo)
3757
+ if (d2) {
3758
+ autoState.drift = d2
3759
+ autoState.lastCheckAt = Date.now()
3760
+ autoState.lastCheckError = ''
3761
+ }
3762
+ }
3763
+ } catch { }
3764
+ }
3765
+ autoState.livePush = {
3766
+ ...autoState.livePush,
3767
+ running: false,
3768
+ finishedAt: Date.now(),
3769
+ ok,
3770
+ phase: ok ? 'done' : 'error',
3771
+ message: ok
3772
+ ? (initPush
3773
+ ? t('初始化推送完成(未关闭 DSH)', 'Initialize push completed (DSH stayed open)')
3774
+ : t('推送完成(未关闭 DSH)', 'Push completed (DSH stayed open)'))
3775
+ : (errText || t('推送失败,详见日志', 'Push failed — see log')),
3776
+ }
3777
+ }
3778
+
3779
+ const child = spawn(cmd, cmdArgs, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
3780
+ child.stdout.on('data', appendLog)
3781
+ child.stderr.on('data', appendLog)
3782
+ child.once('error', (e) => {
3783
+ const msg = String((e && e.message) || e)
3784
+ appendLog(`\n[error] ${msg}\n`)
3785
+ finish(false, msg)
3786
+ })
3787
+ child.once('exit', async (code) => {
3788
+ if (code !== 0) {
3789
+ const errLine = [...tail].reverse().find((l) => /\[X\]|失败|error|fatal:/i.test(l)) || tail[tail.length - 1] || `exit ${code}`
3790
+ finish(false, errLine)
3791
+ return
3792
+ }
3793
+ if (!IS_WIN && !webdavActive(settings)) {
3794
+ try {
3795
+ await git(repo, ['add', '-A'])
3796
+ const st = await git(repo, ['status', '--porcelain'])
3797
+ if (st && st.trim()) {
3798
+ await git(repo, ['commit', '-m', `sync(live): ${stamp}`])
3799
+ }
3800
+ await git(repo, ['push'])
3801
+ } catch (e) {
3802
+ const msg = String((e && e.message) || e)
3803
+ appendLog(`\n[git push error] ${msg}\n`)
3804
+ finish(false, msg)
3805
+ return
3806
+ }
3807
+ }
3808
+ if (!IS_WIN) {
3809
+ try {
3810
+ const head = (await git(repo, ['log', '-1', '--format=%h'])) || ''
3811
+ writeFileSync(join(dshHome, STATE_NAME), JSON.stringify({
3812
+ lastSyncAt: new Date().toISOString(),
3813
+ mode: 'push',
3814
+ repo,
3815
+ head: head.trim(),
3816
+ }, null, 2) + '\n', 'utf8')
3817
+ } catch { }
3818
+ }
3819
+ finish(true, '')
3820
+ })
3821
+
3822
+ return { alreadyRunning: false, livePush: { ...autoState.livePush } }
3823
+ }
3824
+
3610
3825
  async function handleAuto(req, res, config) {
3611
3826
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3612
3827
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
@@ -3704,34 +3919,16 @@ async function handleAuto(req, res, config) {
3704
3919
  return
3705
3920
  }
3706
3921
 
3922
+ if (action === 'push-live') {
3923
+ await ensurePushAllowed(repo, settings)
3924
+ const started = startLivePush({ repo, dshHome, appRoot, settings })
3925
+ sendJson(res, 200, { ok: true, action, ...started })
3926
+ return
3927
+ }
3928
+
3707
3929
  if (action === 'pull-now' || action === 'push-now') {
3708
3930
  const mode = action === 'pull-now' ? 'pull' : 'push'
3709
- // 推送的门禁:真仓库直接推;本机还是空的,只有「云端确实没有文件」才能推 —— 那次推送就是初始化推送。
3710
- // 云端已有文件时拒绝,让用户先拉取(否则本机状态会被写进一份已经在用的历史里)。
3711
- // 注意判据是「树里有文件」而不是「有分支」:远端可能只剩一个空分支,那也是空仓库,可以初始化推送。
3712
- if (mode === 'push' && repoPhase(repo) !== 'ok') {
3713
- const useWebdav = webdavActive(settings)
3714
- const url = useWebdav
3715
- ? normalizeWebdav(settings).url
3716
- : ((await git(repo, ['remote', 'get-url', 'origin'])) || settings.remoteUrl || '')
3717
- const probe = useWebdav ? await probeWebdavRemote(settings) : await probeRemote(url, settings)
3718
- if (!probe || probe.files === null) {
3719
- throw new Error(t(
3720
- useWebdav
3721
- ? `连不上 WebDAV(${url || '未配置'}):${(probe && probe.error) || '初始化推送要先确认云端是空目录'}`
3722
- : `连不上云端、或还没有云端仓库地址(${url || '未配置'}):初始化推送要先确认云端是空仓库`,
3723
- useWebdav
3724
- ? `Cannot reach WebDAV (${url || 'not set'}): ${(probe && probe.error) || 'initialize push needs to confirm the cloud folder is empty.'}`
3725
- : `Cannot reach the cloud or no remote URL is set (${url || 'not set'}): initialize push needs to confirm the cloud repo is still empty.`,
3726
- ))
3727
- }
3728
- if (probe.files > 0) {
3729
- throw new Error(t(
3730
- `云端仓库已经有内容(${probe.files} 个文件):本机还是空的,先「拉取」把内容拉下来,再生成推送`,
3731
- `The cloud repo already has content (${probe.files} file(s)): run Pull to fetch it first, then push.`,
3732
- ))
3733
- }
3734
- }
3931
+ if (mode === 'push' && repoPhase(repo) !== 'ok') await ensurePushAllowed(repo, settings)
3735
3932
  // 拉取/推送做完都把客户端拉回来(用户要求"完成后自动启动 dsh"),仍受 autoRestart 开关约束
3736
3933
  const restart = body.restart !== false && settings.autoRestart !== false
3737
3934
  const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart })
@@ -3747,7 +3944,7 @@ async function handleAuto(req, res, config) {
3747
3944
  return
3748
3945
  }
3749
3946
 
3750
- throw new Error(t('action 只能是 check / pull-now / push-now / restore-preview / restore-now / cancel', 'action must be check / pull-now / push-now / restore-preview / restore-now / cancel'))
3947
+ throw new Error(t('action 只能是 check / pull-now / push-now / push-live / restore-preview / restore-now / cancel', 'action must be check / pull-now / push-now / push-live / restore-preview / restore-now / cancel'))
3751
3948
  } catch (error) {
3752
3949
  sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
3753
3950
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-profile-config-sync",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。支持 Windows(PowerShell)/ macOS / Linux(Node 引擎),并可选 WebDAV 作为传输层。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
@@ -28,6 +28,8 @@ param(
28
28
  [switch]$Restart,
29
29
  [int]$MaxWaitMinutes = 30,
30
30
  [string]$LogFile,
31
+ # 仅 Phase=wait 用:由外部启动器(如 ShellExecute 脱离 Job Object)回读本进程真实 PID
32
+ [string]$PidFile = '',
31
33
  # ---- 仅 -Mode restore 用:还原到哪份快照 ----
32
34
  [string]$BackupDir = '',
33
35
  # 备份类型:profile(配置快照,默认)/ plugin(插件本体备份)/ session(会话目录备份)
@@ -46,6 +48,13 @@ param(
46
48
  # 为什么要分两段:窗口必须**在 DSH 退出之后**才出现。排队阶段就弹窗的话,
47
49
  # 用户从开机到关窗口这段时间会一直挂着一个"等 DSH 退出"的黑窗,什么也干不了还挡着视线。
48
50
  if ($Phase -eq 'wait') {
51
+ if ($PidFile) {
52
+ try {
53
+ $pdir = Split-Path -Parent $PidFile
54
+ if ($pdir -and -not (Test-Path -LiteralPath $pdir)) { New-Item -ItemType Directory -Path $pdir -Force | Out-Null }
55
+ [IO.File]::WriteAllText($PidFile, [string]$PID, (New-Object Text.UTF8Encoding $false))
56
+ } catch { }
57
+ }
49
58
  $deadline = (Get-Date).AddMinutes($MaxWaitMinutes)
50
59
  $noWindowTicks = 0
51
60
  $waitLog = Join-Path $DshHome 'logs\auto-sync-wait.log'