dsh-profile-config-sync 0.4.0 → 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/index.js CHANGED
@@ -522,6 +522,35 @@ async function probeRemote(url, settings) {
522
522
  return value
523
523
  }
524
524
 
525
+ async function probeWebdavRemote(settings) {
526
+ const w = normalizeWebdav(settings)
527
+ if (!w.enabled) return null
528
+ const key = `webdav:${w.url}/${w.dir}`
529
+ const hit = remoteProbeCache.get(key)
530
+ if (hit && Date.now() - hit.at < REMOTE_PROBE_TTL) return hit.value
531
+ let value = { heads: null, files: null }
532
+ try {
533
+ const res = await testConnection(w)
534
+ if (res && res.ok) {
535
+ value = (!res.exists || res.files === 0)
536
+ ? { heads: 0, files: 0, transport: 'webdav' }
537
+ : { heads: 1, files: res.files, transport: 'webdav' }
538
+ } else {
539
+ value = { heads: null, files: null, transport: 'webdav', error: (res && res.error) || '' }
540
+ }
541
+ } catch {
542
+ value = { heads: null, files: null, transport: 'webdav' }
543
+ }
544
+ remoteProbeCache.set(key, { at: Date.now(), value })
545
+ return value
546
+ }
547
+
548
+ function clearWebdavProbeCache() {
549
+ for (const k of remoteProbeCache.keys()) {
550
+ if (String(k).startsWith('webdav:')) remoteProbeCache.delete(k)
551
+ }
552
+ }
553
+
525
554
  /** 只读缓存,不触发任何网络动作。 */
526
555
  function probeRemoteCached(url) {
527
556
  const hit = remoteProbeCache.get(url)
@@ -537,6 +566,10 @@ function warmRemoteProbe(config) {
537
566
  const settings = readSettings(dshHome)
538
567
  const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
539
568
  if (repo && repoPhase(repo) === 'ok') return
569
+ if (webdavActive(settings)) {
570
+ probeWebdavRemote(settings).catch(() => { })
571
+ return
572
+ }
540
573
  const url = settings.remoteUrl || ''
541
574
  if (!url) return
542
575
  probeRemote(url, settings).catch(() => { })
@@ -552,17 +585,20 @@ function warmRemoteProbe(config) {
552
585
  * 下次刷新(或后台预热)就能读到真值。
553
586
  */
554
587
  function probeRemoteQuick(url, settings, budgetMs) {
555
- if (!url) return Promise.resolve(null)
556
- const cached = probeRemoteCached(url)
588
+ const useWebdav = webdavActive(settings)
589
+ if (!url && !useWebdav) return Promise.resolve(null)
590
+ const w = useWebdav ? normalizeWebdav(settings) : null
591
+ const cacheKey = useWebdav ? `webdav:${w.url}/${w.dir}` : url
592
+ const cached = probeRemoteCached(cacheKey)
557
593
  if (cached) return Promise.resolve(cached)
558
594
  const unknown = { heads: null, files: null }
559
- const running = probeRemote(url, settings)
595
+ const running = useWebdav ? probeWebdavRemote(settings) : probeRemote(url, settings)
560
596
  return new Promise((resolve) => {
561
597
  let done = false
562
598
  const timer = setTimeout(() => {
563
599
  if (done) return
564
600
  done = true
565
- resolve(probeRemoteCached(url) || unknown)
601
+ resolve(probeRemoteCached(cacheKey) || unknown)
566
602
  }, budgetMs)
567
603
  if (typeof timer.unref === 'function') timer.unref()
568
604
  running.then((value) => {
@@ -1012,8 +1048,11 @@ async function inspect(config) {
1012
1048
  // 本机仓库处在哪个阶段:空白目录 = 等首次拉取,是正常状态,不该报异常
1013
1049
  const phase = repoPhase(repo)
1014
1050
  // 云端有没有「可拉的内容」:只在本地仓库还没就位时才探(真仓库不需要每次刷面板都打一次网络)
1015
- const remoteProbeUrl = gitRemoteUrl || settings.remoteUrl || ''
1016
- const remoteProbe = (remoteProbeUrl && phase !== 'ok') ? await probeRemoteQuick(remoteProbeUrl, settings, 2500) : null
1051
+ const useWebdav = webdavActive(settings)
1052
+ const remoteProbeUrl = useWebdav ? normalizeWebdav(settings).url : (gitRemoteUrl || settings.remoteUrl || '')
1053
+ const remoteProbe = (remoteProbeUrl && phase !== 'ok')
1054
+ ? await probeRemoteQuick(remoteProbeUrl, settings, 2500)
1055
+ : null
1017
1056
  const remoteHeads = remoteProbe ? remoteProbe.heads : null
1018
1057
  // 分支指向的树里有几个文件 —— 这才是「有没有内容」的真判据:分支还在但树被删空,等同空中空
1019
1058
  const remoteFiles = remoteProbe ? remoteProbe.files : null
@@ -1027,8 +1066,8 @@ async function inspect(config) {
1027
1066
  }
1028
1067
  if (!repo) {
1029
1068
  advice.push(t(
1030
- '还没有配置仓库目录:请在下面的「本机仓库」卡里点「设置路径」,指向那台机器上的 dsh-config 仓库(含 apply.ps1 和 profile\\package.json)',
1031
- 'The repo directory is not set: use the Local repo card below to point at the dsh-config repo on this machine (it must contain apply.ps1 and profile\\package.json).',
1069
+ '还没有配置仓库目录:请在下面「本机仓库」卡的「仓库路径」框里填好目录并点「保存」(已有仓库或新空目录均可)',
1070
+ 'The repo directory is not set: enter the path in the Repo path box in the Local repo card below and click Save (an existing repo or new empty folder both work).',
1032
1071
  ))
1033
1072
  } else if (phase === 'empty' || phase === 'missing') {
1034
1073
  const where = phase === 'missing'
@@ -1036,10 +1075,14 @@ async function inspect(config) {
1036
1075
  : t(`还是空目录(${repo})`, `is still an empty folder (${repo})`)
1037
1076
  if (remoteFiles === 0) {
1038
1077
  advice.push(t(
1039
- `本机仓库${where},云端仓库也还没有任何内容:点「初始化推送」把本机配置当作初始内容推上去(自动 git init + capture + 提交 + 推送)`,
1040
- `The local repo ${where} and the cloud has nothing yet: use "Initialize push" to upload this machine's config as the initial content (git init + capture + commit + push).`,
1078
+ useWebdav
1079
+ ? `本机仓库${where},云端 WebDAV 也还没有任何内容:点「初始化推送」把本机配置作为初始内容传上去(自动抓配置并上传 WebDAV)`
1080
+ : `本机仓库${where},云端仓库也还没有任何内容:点「初始化推送」把本机配置当作初始内容推上去(自动 git init + capture + 提交 + 推送)`,
1081
+ useWebdav
1082
+ ? `The local repo ${where} and WebDAV has nothing yet: use "Initialize push" to capture and upload this machine's config as the initial content.`
1083
+ : `The local repo ${where} and the cloud has nothing yet: use "Initialize push" to upload this machine's config as the initial content (git init + capture + commit + push).`,
1041
1084
  ))
1042
- } else if (remoteFiles === null && remoteHeads === 0) {
1085
+ } else if (remoteFiles === null && (remoteHeads === 0 || remoteHeads === null)) {
1043
1086
  advice.push(t(
1044
1087
  `本机仓库${where},云端连不上/判不了(离线或认证失败):按老规矩先只允许拉取`,
1045
1088
  `The local repo ${where} and the cloud cannot be determined (offline or auth failure): only Pull is allowed, as before.`,
@@ -1051,8 +1094,12 @@ async function inspect(config) {
1051
1094
  ))
1052
1095
  } else {
1053
1096
  advice.push(t(
1054
- `本机仓库${where} —— 执行「拉取」会从云端把仓库内容拉到这里(首次拉取自动初始化,不需要推送)`,
1055
- `The local repo ${where} — running Pull brings the repo down from the cloud (the first pull initializes it; no push needed).`,
1097
+ useWebdav
1098
+ ? `本机仓库${where} —— 执行「拉取」会从 WebDAV 把配置拉到这里(首次拉取自动下载并还原,不需要推送)`
1099
+ : `本机仓库${where} —— 执行「拉取」会从云端把仓库内容拉到这里(首次拉取自动初始化,不需要推送)`,
1100
+ useWebdav
1101
+ ? `The local repo ${where} — running Pull downloads the repo from WebDAV into this folder (no push needed).`
1102
+ : `The local repo ${where} — running Pull brings the repo down from the cloud (the first pull initializes it; no push needed).`,
1056
1103
  ))
1057
1104
  }
1058
1105
  } else if (!isRepoDir(repo)) {
@@ -1214,6 +1261,8 @@ async function inspect(config) {
1214
1261
  script: autoScript(dshHome, repo),
1215
1262
  // post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
1216
1263
  lastResult: readAutoResult(dshHome),
1264
+ // 不关闭 DSH 的在线推送状态(running / finishedAt / ok / phase / message / log)
1265
+ livePush: { ...autoState.livePush },
1217
1266
  },
1218
1267
  // 拉取被本机文件挡住时 sync.ps1 留下的冲突清单,面板「同步冲突」卡据此渲染
1219
1268
  conflicts: (() => {
@@ -1378,12 +1427,18 @@ function buildCmd(config, action, repo, appRoot, dshHome, state = {}) {
1378
1427
  // 铁律:GIT_SSH_COMMAND 必须以可执行程序开头。找不到 ssh.exe 时宁可不设(交给 .ssh\config),
1379
1428
  // 也不能输出「-i "key" -o …」——git 会把它当命令交给 sh,直接 invalid option,报错还伪装成"仓库读不到"。
1380
1429
  const settings = readSettings(dshHome)
1430
+ const w = normalizeWebdav(settings)
1431
+ const useWebdav = webdavActive(settings)
1381
1432
  const key = settings.sshKey || defaultSshKey()
1382
1433
  const hasKey = Boolean(key) && isFile(key)
1383
1434
  const coreSsh = readSshCommandFromGitConfig(repo)
1384
1435
  const sshExe = coreSsh ? '' : resolveSshExe()
1385
1436
  let envLines = []
1386
- if (hasKey && coreSsh) {
1437
+ if (useWebdav) {
1438
+ envLines = [
1439
+ `echo ${echoSafe(`传输:WebDAV(${w.url} / ${w.dir})`)}`,
1440
+ ]
1441
+ } else if (hasKey && coreSsh) {
1387
1442
  envLines = [
1388
1443
  `set GIT_SSH_COMMAND=${coreSsh}`,
1389
1444
  `echo ${echoSafe(`认证:git config core.sshCommand(私钥 ${key} 由该命令使用)`)}`,
@@ -1601,14 +1656,20 @@ function buildSh(config, action, repo, appRoot, dshHome, state = {}) {
1601
1656
  `-DshHome ${shQuote(dshHome)}`,
1602
1657
  ]
1603
1658
  const settings = readSettings(dshHome)
1659
+ const w = normalizeWebdav(settings)
1660
+ const useWebdav = webdavActive(settings)
1604
1661
  const key = settings.sshKey || defaultSshKey()
1605
1662
  const hasKey = Boolean(key) && isFile(key)
1606
1663
  const sshExe = hasKey ? resolveSshExe() : ''
1607
1664
  const envLines = []
1608
- if (hasKey && sshExe) {
1609
- envLines.push(`export GIT_SSH_COMMAND=${shQuote(`${sshExe} -i ${key} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`)}`)
1665
+ if (useWebdav) {
1666
+ envLines.push(`echo ${shQuote(`传输:WebDAV(${w.url} / ${w.dir})`)}`)
1667
+ } else {
1668
+ if (hasKey && sshExe) {
1669
+ envLines.push(`export GIT_SSH_COMMAND=${shQuote(`${sshExe} -i ${key} -o BatchMode=yes -o StrictHostKeyChecking=accept-new`)}`)
1670
+ }
1671
+ envLines.push('echo "认证:未配置私钥时交给 .ssh/config 决定"')
1610
1672
  }
1611
- envLines.push('echo "认证:未配置私钥时交给 .ssh/config 决定"')
1612
1673
 
1613
1674
  const target = action === 'push' ? 'push' : 'pull'
1614
1675
  const label = target === 'push'
@@ -1707,6 +1768,16 @@ const autoState = {
1707
1768
  watcherStartedAt: 0,
1708
1769
  timer: null,
1709
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
+ },
1710
1781
  }
1711
1782
 
1712
1783
  function autoScript(dshHome, repo) {
@@ -1844,6 +1915,19 @@ function psQuote(value) {
1844
1915
  return "'" + String(value).replace(/'/g, "''") + "'"
1845
1916
  }
1846
1917
 
1918
+ /**
1919
+ * 为 PowerShell 的 `Start-Process -ArgumentList @(...)` 拼单个参数。
1920
+ * PowerShell 5.1 会把数组元素直接用空格拼成命令行、不会自动给含空格的值加引号,
1921
+ * 结果像 `C:\Users\...\DeepSeek Harness` 会被拆成两个参数,把后续参数全顶偏并崩溃。
1922
+ * 这里按 Windows CommandLineToArgvW 规则把空串或含空白/引号的参数包上双引号。
1923
+ */
1924
+ function psWinArg(value) {
1925
+ const s = String(value == null ? '' : value)
1926
+ if (!s) return '""'
1927
+ if (!/[\s"]/.test(s)) return s
1928
+ return '"' + s.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1') + '"'
1929
+ }
1930
+
1847
1931
  /**
1848
1932
  * 拉起外部守护:等本进程退出后执行一次同步。
1849
1933
  *
@@ -1884,20 +1968,39 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1884
1968
  }
1885
1969
  } catch { }
1886
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
+
1887
1975
  const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
1888
1976
  // 这一段是「等待态」:隐藏进程只盯着 DSH 退出,退出后才由它拉起一个可见窗口干活,
1889
1977
  // 否则排队期间(可能几小时)会一直挂着一个挡视线的空窗口。
1890
- '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome]
1978
+ '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome,
1979
+ '-PidFile', pidFile]
1891
1980
  if (repo) args.push('-RepoRoot', repo)
1892
1981
  if (appRoot) args.push('-AppRoot', appRoot)
1893
1982
  if (restart) args.push('-Restart')
1894
1983
  // 更新模式要带上下载地址与校验值,交给 post-exit 的 run 段执行
1895
1984
  if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
1896
1985
  const exe = powershellExe()
1986
+ const argLine = args.map((a) => psWinArg(a)).join(' ')
1897
1987
  const inner = [
1898
- // 等待态进程保持**隐藏**;可见窗口由 post-exit.ps1 在 DSH 真正退出后自己弹(-Phase run)。
1899
- `$p = Start-Process -FilePath ${psQuote(exe)} -ArgumentList @(${args.map(psQuote).join(', ')}) -WindowStyle Hidden -PassThru`,
1900
- 'Write-Output $p.Id',
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 { }',
2002
+ `$p = Start-Process -FilePath ${psQuote(exe)} -ArgumentList @(${args.map((a) => psQuote(psWinArg(a))).join(', ')}) -WindowStyle Hidden -PassThru`,
2003
+ 'Write-Output "direct:$($p.Id)"',
1901
2004
  ].join('; ')
1902
2005
  const encoded = Buffer.from(inner, 'utf16le').toString('base64')
1903
2006
  let child
@@ -1905,6 +2008,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1905
2008
  child = spawn(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
1906
2009
  { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
1907
2010
  } catch (error) {
2011
+ try { unlinkSync(pidFile) } catch { }
1908
2012
  const msg = String((error && error.message) || error)
1909
2013
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${msg}`)
1910
2014
  return { ok: false, error: t(`拉不起 powershell(${exe}):${msg}`, `Cannot launch PowerShell (${exe}): ${msg}`) }
@@ -1914,22 +2018,25 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1914
2018
  child.stdout.on('data', (c) => { stdout += c })
1915
2019
  child.stderr.on('data', (c) => { stderr += c })
1916
2020
  const code = await new Promise((resolve) => {
1917
- const timer = setTimeout(() => resolve('timeout'), 8000)
2021
+ const timer = setTimeout(() => resolve('timeout'), 10000)
1918
2022
  child.once('exit', (c) => { clearTimeout(timer); resolve(c) })
1919
2023
  child.once('error', (e) => { clearTimeout(timer); resolve('error:' + ((e && e.message) || e)) })
1920
2024
  })
2025
+ try { unlinkSync(pidFile) } catch { }
1921
2026
  if (code !== 0) {
1922
2027
  const detail = String(stderr || stdout || code).trim().slice(0, 300)
1923
2028
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${detail}`)
1924
2029
  return { ok: false, error: t(`拉不起 post-exit(launcher 退出码 ${code}):${detail}`, `Cannot launch post-exit (launcher exit code ${code}): ${detail}`) }
1925
2030
  }
1926
- 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
1927
2034
  autoState.watcherStartedAt = Date.now()
1928
2035
  try {
1929
2036
  writeFileSync(lockFile, JSON.stringify({ pid, mode, at: Date.now() }), 'utf8')
1930
2037
  } catch { }
1931
- logLaunch(dshHome, `已启动 ${mode} pid=${pid} exe=${exe} script=${script}`)
1932
- return { ok: true, pid }
2038
+ logLaunch(dshHome, `已启动 ${mode} pid=${pid} via=${via} exe=${exe} script=${script}`)
2039
+ return { ok: true, pid, via }
1933
2040
  }
1934
2041
 
1935
2042
  /**
@@ -2228,8 +2335,8 @@ async function handleSettings(req, res, config) {
2228
2335
  // (可能正克隆到一半)也放行,否则刚 init 完的目录会被拒。
2229
2336
  if (repoPath && repoPhase(repoPath) === 'unusable' && !isFile(join(repoPath, '.git', 'HEAD'))) {
2230
2337
  throw new Error(t(
2231
- `这个目录里已经有别的东西,又不像 dsh-config 仓库(缺 apply.ps1 或 profile\\package.json):${repoPath}`,
2232
- `That directory already holds something else and does not look like a dsh-config repo (no apply.ps1 or profile\\package.json): ${repoPath}`,
2338
+ `这个目录里已经有别的东西,又不像 dsh-config 仓库(缺 apply.ps1 / sync-engine.mjs 或 profile\\package.json):${repoPath}`,
2339
+ `That directory already holds something else and does not look like a dsh-config repo (no apply.ps1 / sync-engine.mjs or profile\\package.json): ${repoPath}`,
2233
2340
  ))
2234
2341
  }
2235
2342
  }
@@ -3534,6 +3641,187 @@ async function handleStatus(req, res, config) {
3534
3641
  * {action:'cancel'} 取消已排队的动作
3535
3642
  * 只做只读 fetch 比对(check),真正动手一律交给退出后的 post-exit.ps1。
3536
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
+
3537
3825
  async function handleAuto(req, res, config) {
3538
3826
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3539
3827
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
@@ -3568,15 +3856,25 @@ async function handleAuto(req, res, config) {
3568
3856
  }
3569
3857
  autoState.checking = true
3570
3858
  autoState.lastCheckError = ''
3571
- const drift = await checkDrift(repo)
3859
+ let drift = null
3860
+ if (webdavActive(settings)) {
3861
+ const wp = await probeWebdavRemote(settings)
3862
+ if (wp && wp.files !== null) {
3863
+ drift = { ahead: 0, behind: 0, transport: 'webdav', files: wp.files, at: Date.now() }
3864
+ } else {
3865
+ autoState.lastCheckError = (wp && wp.error) || t('连不上 WebDAV 服务端', 'Cannot reach WebDAV server')
3866
+ }
3867
+ } else {
3868
+ drift = await checkDrift(repo)
3869
+ if (!drift) {
3870
+ autoState.lastCheckError = t(
3871
+ '读不到远端(fetch 失败或没有 origin),先确认云端仓库地址与 SSH',
3872
+ 'Cannot read the remote (fetch failed or there is no origin) — check the cloud repo URL and SSH setup',
3873
+ )
3874
+ }
3875
+ }
3572
3876
  autoState.checking = false
3573
3877
  autoState.lastCheckAt = Date.now()
3574
- if (!drift) {
3575
- autoState.lastCheckError = t(
3576
- '读不到远端(fetch 失败或没有 origin),先确认云端仓库地址与 SSH',
3577
- 'Cannot read the remote (fetch failed or there is no origin) — check the cloud repo URL and SSH setup',
3578
- )
3579
- }
3580
3878
  autoState.drift = drift
3581
3879
  sendJson(res, 200, { ok: true, action, drift, error: autoState.lastCheckError || null })
3582
3880
  return
@@ -3621,27 +3919,16 @@ async function handleAuto(req, res, config) {
3621
3919
  return
3622
3920
  }
3623
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
+
3624
3929
  if (action === 'pull-now' || action === 'push-now') {
3625
3930
  const mode = action === 'pull-now' ? 'pull' : 'push'
3626
- // 推送的门禁:真仓库直接推;本机还是空的,只有「云端确实没有文件」才能推 —— 那次推送就是初始化推送。
3627
- // 云端已有文件时拒绝,让用户先拉取(否则本机状态会被写进一份已经在用的历史里)。
3628
- // 注意判据是「树里有文件」而不是「有分支」:远端可能只剩一个空分支,那也是空仓库,可以初始化推送。
3629
- if (mode === 'push' && repoPhase(repo) !== 'ok') {
3630
- const url = (await git(repo, ['remote', 'get-url', 'origin'])) || settings.remoteUrl || ''
3631
- const probe = await probeRemote(url, settings)
3632
- if (!probe || probe.files === null) {
3633
- throw new Error(t(
3634
- `连不上云端、或还没有云端仓库地址(${url || '未配置'}):初始化推送要先确认云端是空仓库`,
3635
- `Cannot reach the cloud or no remote URL is set (${url || 'not set'}): initialize push needs to confirm the cloud repo is still empty.`,
3636
- ))
3637
- }
3638
- if (probe.files > 0) {
3639
- throw new Error(t(
3640
- `云端仓库已经有内容(${probe.files} 个文件):本机还是空的,先「拉取」把内容拉下来,再生成推送`,
3641
- `The cloud repo already has content (${probe.files} file(s)): run Pull to fetch it first, then push.`,
3642
- ))
3643
- }
3644
- }
3931
+ if (mode === 'push' && repoPhase(repo) !== 'ok') await ensurePushAllowed(repo, settings)
3645
3932
  // 拉取/推送做完都把客户端拉回来(用户要求"完成后自动启动 dsh"),仍受 autoRestart 开关约束
3646
3933
  const restart = body.restart !== false && settings.autoRestart !== false
3647
3934
  const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart })
@@ -3657,7 +3944,7 @@ async function handleAuto(req, res, config) {
3657
3944
  return
3658
3945
  }
3659
3946
 
3660
- 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'))
3661
3948
  } catch (error) {
3662
3949
  sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
3663
3950
  }
@@ -3674,7 +3961,8 @@ function scheduleAutoStart(config) {
3674
3961
  // 已经排队等退出了就别重复拉起 watcher:第二遍 fetch/stat 纯属浪费
3675
3962
  if (autoState.pending) return
3676
3963
  const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
3677
- if (!repo || !isDir(join(repo, '.git'))) {
3964
+ const useWebdav = webdavActive(settings)
3965
+ if (!repo || (!useWebdav && !isDir(join(repo, '.git'))) || (useWebdav && repoPhase(repo) !== 'ok')) {
3678
3966
  // 空目录是「等首次拉取」的正常状态:不记错误,免得面板的云端徽标把它当成 fetch 失败
3679
3967
  autoState.lastCheckError = (repo && repoPhase(repo) === 'empty')
3680
3968
  ? ''
@@ -3683,12 +3971,24 @@ function scheduleAutoStart(config) {
3683
3971
  return
3684
3972
  }
3685
3973
  autoState.checking = true
3686
- const drift = await checkDrift(repo)
3687
- autoState.checking = false
3688
- autoState.lastCheckAt = Date.now()
3689
- if (!drift) {
3690
- autoState.lastCheckError = t('读不到远端(fetch 失败或没有 origin)', 'Cannot read the remote (fetch failed or there is no origin)')
3691
- return
3974
+ let drift = null
3975
+ if (useWebdav) {
3976
+ const wp = await probeWebdavRemote(settings)
3977
+ autoState.checking = false
3978
+ autoState.lastCheckAt = Date.now()
3979
+ if (!wp || wp.files === null) {
3980
+ autoState.lastCheckError = (wp && wp.error) || t('连不上 WebDAV 服务端', 'Cannot reach WebDAV server')
3981
+ return
3982
+ }
3983
+ drift = { ahead: 0, behind: 0, transport: 'webdav', files: wp.files, at: Date.now() }
3984
+ } else {
3985
+ drift = await checkDrift(repo)
3986
+ autoState.checking = false
3987
+ autoState.lastCheckAt = Date.now()
3988
+ if (!drift) {
3989
+ autoState.lastCheckError = t('读不到远端(fetch 失败或没有 origin)', 'Cannot read the remote (fetch failed or there is no origin)')
3990
+ return
3991
+ }
3692
3992
  }
3693
3993
  autoState.drift = drift
3694
3994
  const appRoot = resolveAppRoot(config?.appRoot) || ''
@@ -3800,7 +4100,10 @@ async function triggerAutoSyncOnClose(config) {
3800
4100
  return { queued: false }
3801
4101
  }
3802
4102
 
3803
- const drift = await checkDrift(repo)
4103
+ const useWebdav = webdavActive(settings)
4104
+ const drift = useWebdav
4105
+ ? (() => ({ ahead: 0, behind: 0, transport: 'webdav', at: Date.now() }))()
4106
+ : await checkDrift(repo)
3804
4107
  if (!drift) return { queued: false }
3805
4108
 
3806
4109
  // 拉取优先,和 scheduleAutoStart 一致;关闭时不再弹确认框,云端领先就排
@@ -3818,8 +4121,10 @@ async function triggerAutoSyncOnClose(config) {
3818
4121
  if (settings.autoPush) {
3819
4122
  // 判据和 scheduleAutoStart 完全相同:领先提交 / 未提交改动 / 本机资料比上次同步新
3820
4123
  let dirty = 0
3821
- const raw = await git(repo, ['status', '--porcelain'])
3822
- if (raw) dirty = raw.split('\n').filter((l) => l.trim()).length
4124
+ if (!useWebdav || isDir(join(repo, '.git'))) {
4125
+ const raw = await git(repo, ['status', '--porcelain'])
4126
+ if (raw) dirty = raw.split('\n').filter((l) => l.trim()).length
4127
+ }
3823
4128
  const syncState = readSyncState(dshHome)
3824
4129
  const lp = localPending(dshHome, syncState.lastSyncAt, config?.profileName, { repo, appRoot })
3825
4130
  const shouldPush = drift.ahead > 0 || dirty > 0 || (lp.known && lp.pending > 0)
@@ -3856,8 +4161,8 @@ async function handlePrepare(req, res, config) {
3856
4161
  // 只有「压根没配过路径」才拦。
3857
4162
  if (!repo) {
3858
4163
  throw new Error(t(
3859
- '还没有配置仓库目录:请先在面板「本机仓库」卡里点「设置路径」,指到一个目录(本地还没有仓库时,首次拉取会自动从云端克隆)',
3860
- 'The repo directory is not configured: set the path in the Local repo card first (if the repo is not local yet, the first pull clones it from the cloud automatically)',
4164
+ '还没有配置仓库目录:请先在面板「本机仓库」卡的「仓库路径」框里填好目录并点「保存」(本地还没有仓库时,首次拉取会自动从云端拉取/初始化)',
4165
+ 'The repo directory is not configured: enter the path in the Repo path box in the Local repo card and click Save first (if the repo is not local yet, the first pull initializes it from the cloud automatically)',
3861
4166
  ))
3862
4167
  }
3863
4168
  const repoReady = isRepoDir(repo)
@@ -3866,22 +4171,30 @@ async function handlePrepare(req, res, config) {
3866
4171
  // 一次请求算清楚,下面 push 门禁、all 的脚本组合、bootstrap 说明都用这同一个答案。
3867
4172
  // 判据是「云端分支树里有没有文件」——远端只剩空分支时也算空仓库(历史被删空就是这个样子)。
3868
4173
  const probeSettings = readSettings(dshHome)
4174
+ const useWebdavForPrepare = webdavActive(probeSettings)
3869
4175
  let remoteFilesForPrepare = null
3870
4176
  let remoteHeadsForPrepare = null
3871
4177
  if (phase !== 'ok') {
3872
- const probeUrl = (await git(repo, ['remote', 'get-url', 'origin'])) || probeSettings.remoteUrl || ''
3873
- const probe = await probeRemote(probeUrl, probeSettings)
3874
- remoteFilesForPrepare = probe ? probe.files : null
3875
- remoteHeadsForPrepare = probe ? probe.heads : null
4178
+ if (useWebdavForPrepare) {
4179
+ const probe = await probeWebdavRemote(probeSettings)
4180
+ remoteFilesForPrepare = probe ? probe.files : null
4181
+ remoteHeadsForPrepare = probe ? probe.heads : null
4182
+ } else {
4183
+ const probeUrl = (await git(repo, ['remote', 'get-url', 'origin'])) || probeSettings.remoteUrl || ''
4184
+ const probe = await probeRemote(probeUrl, probeSettings)
4185
+ remoteFilesForPrepare = probe ? probe.files : null
4186
+ remoteHeadsForPrepare = probe ? probe.heads : null
4187
+ }
3876
4188
  }
3877
4189
  // 空白文件夹(或还没建)代表「本机还没有仓库内容」:能不能推,取决于云端有没有内容 ——
3878
4190
  // 云端也空 → 允许,这次推送就是「初始化推送」(sync.ps1 会 git init + 写骨架 + capture + 提交 + 推)
3879
4191
  // 云端有内容 → 拒绝,先拉取(硬推会把本机状态写进一份正在使用的历史)
3880
4192
  if (action === 'push' && phase !== 'ok') {
3881
4193
  if (remoteFilesForPrepare === null) {
4194
+ const targetHint = useWebdavForPrepare ? normalizeWebdav(probeSettings).url : (probeSettings.remoteUrl || '还没配地址')
3882
4195
  throw new Error(t(
3883
- `连不上云端仓库(${probeSettings.remoteUrl || '还没配地址'}):初始化推送要先确认云端是空仓库,请先确认地址与网络`,
3884
- `Cannot reach the cloud repo (${probeSettings.remoteUrl || 'no URL configured'}): initialize push needs to confirm the cloud repo is empty — check the URL and network.`,
4196
+ `连不上云端仓库(${targetHint}):初始化推送要先确认云端是空仓库,请先确认地址与网络`,
4197
+ `Cannot reach the cloud repo (${useWebdavForPrepare ? normalizeWebdav(probeSettings).url : (probeSettings.remoteUrl || 'no URL configured')}): initialize push needs to confirm the cloud repo is empty — check the URL and network.`,
3885
4198
  ))
3886
4199
  }
3887
4200
  if (remoteFilesForPrepare > 0) {
@@ -3895,9 +4208,10 @@ async function handlePrepare(req, res, config) {
3895
4208
  // 面板状态原地不动,人以为「同步过了」,实际什么都没下来。两边都空只走「推送(初始化)」。
3896
4209
  if (action === 'pull' && phase !== 'ok') {
3897
4210
  if (remoteFilesForPrepare === null) {
4211
+ const targetHint = useWebdavForPrepare ? normalizeWebdav(probeSettings).url : (probeSettings.remoteUrl || '还没配地址')
3898
4212
  throw new Error(t(
3899
- '连不上云端仓库(' + (probeSettings.remoteUrl || '还没配地址') + '):先确认地址与网络,再生成拉取脚本',
3900
- 'Cannot reach the cloud repo (' + (probeSettings.remoteUrl || 'no URL configured') + '): check the URL and network before generating the pull script.',
4213
+ '连不上云端仓库(' + targetHint + '):先确认地址与网络,再生成拉取脚本',
4214
+ 'Cannot reach the cloud repo (' + (useWebdavForPrepare ? normalizeWebdav(probeSettings).url : (probeSettings.remoteUrl || 'no URL configured')) + '): check the URL and network before generating the pull script.',
3901
4215
  ))
3902
4216
  }
3903
4217
  if (remoteFilesForPrepare === 0) {
@@ -3908,9 +4222,10 @@ async function handlePrepare(req, res, config) {
3908
4222
  }
3909
4223
  }
3910
4224
  // 推送 / 拉取都以「云端仓库地址」为前置;还原(最新快照或指定快照)只动本机快照,不需要远端。
3911
- if (action !== 'restore' && action !== 'restore-backup') {
4225
+ // 0.4.0:WebDAV 模式下不需要 git remoteUrl。
4226
+ if (action !== 'restore' && action !== 'restore-backup' && !useWebdavForPrepare) {
3912
4227
  const origin = isDir(join(repo, '.git')) ? await git(repo, ['remote', 'get-url', 'origin']) : null
3913
- const remoteUrl = origin || readSettings(dshHome).remoteUrl
4228
+ const remoteUrl = origin || probeSettings.remoteUrl
3914
4229
  if (!remoteUrl) {
3915
4230
  throw new Error(t(
3916
4231
  '还没有配置云端仓库地址:请先在面板「云端仓库」卡里填好远端地址并保存,再生成推送/拉取脚本',
@@ -4158,6 +4473,7 @@ async function handleWebdav(req, res, config) {
4158
4473
  if (typeof body.pass === 'string' && body.pass.length > 0) next.webdavPass = body.pass
4159
4474
  try {
4160
4475
  writeSettings(dshHome, next)
4476
+ clearWebdavProbeCache()
4161
4477
  const w = normalizeWebdav(next)
4162
4478
  sendJson(res, 200, { ok: true, configured: Boolean(w.url), hasPassword: Boolean(w.pass), mode: w.mode })
4163
4479
  } catch (e) {