dsh-profile-config-sync 0.4.1 → 0.6.40

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
@@ -21,6 +21,7 @@ import { spawn } from 'node:child_process'
21
21
  import { createHash } from 'node:crypto'
22
22
  import { createRequire } from 'node:module'
23
23
  import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync, chmodSync } from 'node:fs'
24
+ import { writeFileAtomicSync } from './runtime/atomic-write.mjs'
24
25
  import { homedir, hostname, tmpdir } from 'node:os'
25
26
  import { basename, dirname, isAbsolute, join, relative } from 'node:path'
26
27
  import { fileURLToPath } from 'node:url'
@@ -28,6 +29,8 @@ import { fileURLToPath } from 'node:url'
28
29
  import { runGuard, clearSessionCaches, appendGuardLog } from './runtime/tools/session-cache-guard.mjs'
29
30
  // 0.3.76:工作区显示状态(三态 + 会话独立隐藏),自包含读写 DSH 两个权威文件
30
31
  import { readView, setWorkspaceState, setSessionState } from './runtime/tools/workspace-view.mjs'
32
+ // 0.5.2:在线推送的 CLIXML 日志清洗(单独成文件,自检可直接跑真实片段)
33
+ import { extractLiveLogText } from './runtime/live-log.mjs'
31
34
  // 0.3.82:实时通道。拿不到 workspaceRegistry 时,这两个函数内部自动退回上面的文件写法。
32
35
  import { setWorkspaceStateLive, setSessionStateLive } from './runtime/tools/workspace-view.mjs'
33
36
  // 0.4.0:跨端(Windows / macOS / Linux)。平台差异全部收敛在 runtime/platform.mjs,
@@ -37,6 +40,7 @@ import {
37
40
  findGit, findSsh, hostNodeExe,
38
41
  hostDshNodeModules as platformHostDshNodeModules,
39
42
  isAppRoot as pfIsAppRoot, isFile as pfIsFile, platformFamily, platformLabel,
43
+ normalizeSyncExtraPaths,
40
44
  } from './runtime/platform.mjs'
41
45
  // 0.4.0:客户端身份(仓库里 machines/<id>.json)—— 跨端不分叉仓库,只登记「谁推的」
42
46
  import { listMachines } from './runtime/machines.mjs'
@@ -107,16 +111,82 @@ const PLUGIN_VERSION = (() => {
107
111
  // **不要**用 jsDelivr 兜清单:它对 `@main` 这类分支别名有明显缓存(实测发版后仍返回上一版清单,purge 接口也没
108
112
  // 立刻刷新),拿它当清单源会让"有新版本"晚几小时才出现,比读不到更误导人。
109
113
  // 用户自己在设置里填了清单地址时只用他那一个 —— 不掺镜像,免得"读到的其实不是他指定的源"。
110
- const RAW_MANIFEST_URL = 'https://raw.githubusercontent.com/huanyu-a/dsh-profile-config-sync/main/version.json'
114
+ const UPDATE_REPO_OWNER = 'huanyu-a'
115
+ const UPDATE_REPO_NAME = 'dsh-profile-config-sync'
116
+ const RAW_MANIFEST_URL = `https://raw.githubusercontent.com/${UPDATE_REPO_OWNER}/${UPDATE_REPO_NAME}/main/version.json`
117
+ const API_MANIFEST_URL = `https://api.github.com/repos/${UPDATE_REPO_OWNER}/${UPDATE_REPO_NAME}/contents/version.json?ref=main`
111
118
  const UPDATE_MANIFEST_MIRRORS = [
112
- 'https://gh-proxy.com/https://raw.githubusercontent.com/huanyu-a/dsh-profile-config-sync/main/version.json',
113
- 'https://ghfast.top/https://raw.githubusercontent.com/huanyu-a/dsh-profile-config-sync/main/version.json',
119
+ `https://gh-proxy.com/${RAW_MANIFEST_URL}`,
120
+ `https://ghfast.top/${RAW_MANIFEST_URL}`,
121
+ API_MANIFEST_URL,
114
122
  RAW_MANIFEST_URL,
115
123
  ]
116
124
  const UPDATE_MANIFEST_URL = RAW_MANIFEST_URL
117
125
  // 30 秒:慢链路 10 秒根本不够(raw 通的时候也要几百毫秒到十几秒不等)
118
126
  const UPDATE_FETCH_TIMEOUT = 30 * 1000
119
127
  const UPDATE_CHECK_TTL = 30 * 60 * 1000
128
+ const GH_TOKEN_ENV_CANDIDATES = ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']
129
+
130
+ const winEnvCache = new Map()
131
+ function clearWinEnvCache() { winEnvCache.clear() }
132
+
133
+ function parseEnvTokenRef(raw) {
134
+ const s = String(raw || '').trim()
135
+ if (!s) return ''
136
+ let m = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(s)
137
+ if (m) return m[1]
138
+ m = /^\$([A-Za-z_][A-Za-z0-9_]*)$/.exec(s)
139
+ if (m) return m[1]
140
+ m = /^env:([A-Za-z_][A-Za-z0-9_]*)$/i.exec(s)
141
+ if (m) return m[1]
142
+ return ''
143
+ }
144
+
145
+ function readWinEnvVar(name) {
146
+ if (!IS_WIN || !name) return ''
147
+ const now = Date.now()
148
+ const hit = winEnvCache.get(name)
149
+ if (hit && now - hit.at < 15000) return hit.value
150
+ let val = ''
151
+ const regPaths = ['HKCU\\Environment', 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment']
152
+ for (const regPath of regPaths) {
153
+ try {
154
+ const out = execFileSync('reg.exe', ['query', regPath, '/v', name], { windowsHide: true, encoding: 'utf8', timeout: 2000, stdio: ['ignore', 'pipe', 'pipe'] })
155
+ const lines = String(out || '').split(/\r?\n/)
156
+ for (const line of lines) {
157
+ const m = line.match(/^\s*\S+\s+REG_(?:EXPAND_)?SZ\s+(.*)$/i)
158
+ if (m && m[1].trim()) { val = m[1].trim(); break }
159
+ }
160
+ if (val) break
161
+ } catch { }
162
+ }
163
+ winEnvCache.set(name, { value: val, at: now })
164
+ return val
165
+ }
166
+
167
+ function getEnvValue(name) {
168
+ const key = String(name || '').trim()
169
+ if (!key) return ''
170
+ const fromProc = String(process.env[key] || '').trim()
171
+ if (fromProc) return fromProc
172
+ return readWinEnvVar(key)
173
+ }
174
+
175
+ function resolveTokenSpec(spec, fallbackNames = GH_TOKEN_ENV_CANDIDATES) {
176
+ const raw = String(spec || '').trim()
177
+ const envRef = parseEnvTokenRef(raw)
178
+ if (envRef) {
179
+ return { token: getEnvValue(envRef), source: 'env', envName: envRef, rawRef: true }
180
+ }
181
+ if (raw) {
182
+ return { token: raw, source: 'file', envName: '', rawRef: false }
183
+ }
184
+ for (const name of (fallbackNames || [])) {
185
+ const v = getEnvValue(name)
186
+ if (v) return { token: v, source: 'env', envName: name, rawRef: false }
187
+ }
188
+ return { token: '', source: 'none', envName: '', rawRef: false }
189
+ }
120
190
 
121
191
  /**
122
192
  * 定位客户端根目录(AppRoot)。
@@ -281,7 +351,9 @@ function backupRootOf(dshHome, settings) {
281
351
  }
282
352
 
283
353
  function writeSettings(dshHome, s) {
284
- const payload = JSON.stringify({
354
+ // 归一化已知字段,但**以传入对象为底**:面板只提交一个开关时,不能把没说到的
355
+ // WebDAV 地址/账号/密码/模式(以及以后新增的键)连带清空 —— 那是数据丢失。
356
+ const merged = { ...(s && typeof s === 'object' ? s : {}),
285
357
  repoPath: s.repoPath || '',
286
358
  remoteUrl: s.remoteUrl || '',
287
359
  sshKey: s.sshKey || '',
@@ -299,8 +371,10 @@ function writeSettings(dshHome, s) {
299
371
  webdavUser: s.webdavUser || '',
300
372
  webdavPass: s.webdavPass || '',
301
373
  webdavDir: s.webdavDir || '',
302
- }, null, 2) + '\n'
303
- writeFileSync(settingsPath(dshHome), payload, 'utf8')
374
+ }
375
+ const payload = JSON.stringify(merged, null, 2) + '\n'
376
+ // 这份文件里有 WebDAV 密码与更新令牌:POSIX 上收紧到仅本人可读写(Windows 靠用户目录 ACL,0o600 是空操作)
377
+ writeFileAtomicSync(settingsPath(dshHome), payload, { mode: 0o600 })
304
378
  }
305
379
 
306
380
  /** 没配过时给一个能用的默认私钥:优先 gitee 那把,其次通用 id_ed25519。 */
@@ -1155,12 +1229,43 @@ async function inspect(config) {
1155
1229
  advice.push(t(`工作区有 ${dirty} 项未提交:退出 DSH 后跑「推送」会一并提交`, `${dirty} uncommitted change(s): running Push after DSH exits commits them too.`))
1156
1230
  }
1157
1231
  if (local.known && local.pending > 0) {
1158
- advice.push(t(
1159
- `本机有 ${local.pending} 个文件在上次同步之后有更新(新会话/资料之类),仓库里还没有:退出 DSH 后跑「推送」`,
1160
- `${local.pending} file(s) changed since the last sync (new sessions/materials) and are not in the repo yet: run Push after DSH exits.`,
1161
- ))
1232
+ // 文案按「实际参与同步的类别」说:取消勾选「会话记录」后还写「新会话/资料」,
1233
+ // 用户会以为取消勾选没生效(实测反馈)。这里只提真正会被推送的那些组,
1234
+ // 并且按条数从多到少点名最多三类——待推送现在覆盖 12 组,只写「配置类文件」
1235
+ // 会把「插件数据改了 3 个文件」说成配置变更,同样是错话。
1236
+ const ranked = (Array.isArray(local.groups) ? local.groups : [])
1237
+ .filter((g) => g && g.count > 0 && PENDING_GROUP_LABEL[g.id])
1238
+ .sort((a, b) => b.count - a.count)
1239
+ .slice(0, 3)
1240
+ const kindsZh = ranked.map((g) => PENDING_GROUP_LABEL[g.id][0]).join(' / ')
1241
+ const kindsEn = ranked.map((g) => PENDING_GROUP_LABEL[g.id][1]).join(' / ')
1242
+ advice.push(kindsZh
1243
+ ? t(
1244
+ `本机有 ${local.pending} 个文件在上次同步之后有更新(${kindsZh}${ranked.length < local.groups.length ? ' 等' : ''}),仓库里还没有:退出 DSH 后跑「推送」`,
1245
+ `${local.pending} file(s) changed since the last sync (${kindsEn}${ranked.length < (local.groups || []).length ? ' etc.' : ''}) and are not in the repo yet: run Push after DSH exits.`,
1246
+ )
1247
+ : t(
1248
+ `本机有 ${local.pending} 个文件在上次同步之后有更新,仓库里还没有:退出 DSH 后跑「推送」`,
1249
+ `${local.pending} file(s) changed since the last sync and are not in the repo yet: run Push after DSH exits.`,
1250
+ ))
1251
+ }
1252
+ if (!advice.length) {
1253
+ // 「一致」这句话只有在真的扫完、且真的没变化时才成立:
1254
+ // 从没同步过(known=false)与扫描被预算截断(truncated)都不等于「一致」。
1255
+ if (local && local.known === false) {
1256
+ advice.push(t('本机还没有同步记录:先推送一次,之后才知道哪些是新的', 'No sync record on this machine yet — push once, then the panel can tell what is new.'))
1257
+ } else if (local && local.truncated) {
1258
+ advice.push(t('待推送扫描没跑完(文件太多或超时),这次的数字可能偏小:可再刷新一次', 'The pending scan did not finish (too many files or a timeout); the count may be low — refresh again.'))
1259
+ } else if (local && Array.isArray(local.engineGroups)) {
1260
+ // 非 Windows:这句话只覆盖引擎真会同步的四组,不能写成「仓库与本机一致」
1261
+ advice.push(t(
1262
+ `这台机器走跨平台引擎,只同步 ${local.engineGroups.join(' / ')},这几组与仓库一致(会话记录、插件数据、额外路径要 Windows 版才会同步)`,
1263
+ `This machine uses the cross-platform engine, which syncs only ${local.engineGroups.join(' / ')}; those groups match the repo (conversations, plugin data and extra paths sync on Windows).`,
1264
+ ))
1265
+ } else {
1266
+ advice.push(t('仓库与本机一致,没有待办', 'The repo matches this machine — nothing to do.'))
1267
+ }
1162
1268
  }
1163
- if (!advice.length) advice.push(t('仓库与本机一致,没有待办', 'The repo matches this machine — nothing to do.'))
1164
1269
 
1165
1270
  return {
1166
1271
  ok: true,
@@ -1219,7 +1324,7 @@ async function inspect(config) {
1219
1324
  sshKeyExists: Boolean(sshKey) && isFile(sshKey),
1220
1325
  sshKeyFrom: settings.sshKey ? 'settings' : (sshKey ? 'default' : 'none'),
1221
1326
  sshConfig: isFile(join(homedir(), '.ssh', 'config')),
1222
- updateTokenSet: Boolean(settings.updateToken),
1327
+ updateTokenSet: Boolean(resolveTokenSpec(settings.updateToken, settings.updateManifestUrl ? [] : GH_TOKEN_ENV_CANDIDATES).token),
1223
1328
  // 备份根:留空=默认。面板「还原备份」卡据此显示当前值并判断是否被改过
1224
1329
  backupRoot: backupRootOf(dshHome, settings),
1225
1330
  backupRootCustom: Boolean(settings.backupRoot),
@@ -1261,6 +1366,8 @@ async function inspect(config) {
1261
1366
  script: autoScript(dshHome, repo),
1262
1367
  // post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
1263
1368
  lastResult: readAutoResult(dshHome),
1369
+ // 不关闭 DSH 的在线推送状态(running / finishedAt / ok / phase / message / log)
1370
+ livePush: { ...autoState.livePush },
1264
1371
  },
1265
1372
  // 拉取被本机文件挡住时 sync.ps1 留下的冲突清单,面板「同步冲突」卡据此渲染
1266
1373
  conflicts: (() => {
@@ -1766,6 +1873,19 @@ const autoState = {
1766
1873
  watcherStartedAt: 0,
1767
1874
  timer: null,
1768
1875
  interval: null, // 每 2 分钟的复查(会话/资料是运行中产生的,只判一次会全漏)
1876
+ livePush: {
1877
+ running: false,
1878
+ startedAt: 0,
1879
+ finishedAt: 0,
1880
+ ok: null,
1881
+ phase: '',
1882
+ message: '',
1883
+ detail: '',
1884
+ recent: [],
1885
+ log: '',
1886
+ initPush: false,
1887
+ transport: '',
1888
+ },
1769
1889
  }
1770
1890
 
1771
1891
  function autoScript(dshHome, repo) {
@@ -1927,7 +2047,7 @@ function psWinArg(value) {
1927
2047
  * detached=false 立刻就在写日志。所以这里不 detached,而是让一个短命 powershell 用
1928
2048
  * Start-Process 把真正的 post-exit 起成独立进程 —— 父进程(DSH)退出后它照样活着。
1929
2049
  */
1930
- async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [] }) {
2050
+ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [], closeRequested = false }) {
1931
2051
  const script = autoScript(dshHome, repo)
1932
2052
  if (!script) return { ok: false, error: t('插件与仓库里都没有 post-exit.ps1,无法排队', 'post-exit.ps1 is in neither the plugin nor the repo — cannot queue') }
1933
2053
 
@@ -1956,21 +2076,42 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1956
2076
  }
1957
2077
  } catch { }
1958
2078
 
2079
+ const logsDir = join(dshHome, 'logs')
2080
+ try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
2081
+ const pidFile = join(logsDir, `.watch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.pid`)
2082
+
1959
2083
  const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
1960
2084
  // 这一段是「等待态」:隐藏进程只盯着 DSH 退出,退出后才由它拉起一个可见窗口干活,
1961
2085
  // 否则排队期间(可能几小时)会一直挂着一个挡视线的空窗口。
1962
- '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome]
2086
+ '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome,
2087
+ '-PidFile', pidFile]
2088
+ // 只有「插件自己请求过关闭客户端」的流程才允许守护进程在窗口消失后强杀残留进程;
2089
+ // 被动等待(自动推送/拉取)绝不强杀 —— 否则用户把窗口收进托盘就会被静默杀掉。
2090
+ if (closeRequested) args.push('-CloseWhenIdle')
1963
2091
  if (repo) args.push('-RepoRoot', repo)
1964
2092
  if (appRoot) args.push('-AppRoot', appRoot)
1965
2093
  if (restart) args.push('-Restart')
1966
2094
  // 更新模式要带上下载地址与校验值,交给 post-exit 的 run 段执行
1967
2095
  if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
1968
2096
  const exe = powershellExe()
2097
+ const argLine = args.map((a) => psWinArg(a)).join(' ')
1969
2098
  const inner = [
1970
- // 等待态进程保持**隐藏**;可见窗口由 post-exit.ps1 在 DSH 真正退出后自己弹(-Phase run)。
1971
- // 每个元素先经 psWinArg 加内层双引号,防止 AppRoot/RepoRoot 含空格时被 Start-Process 拆开。
2099
+ // DSH 在 Windows 下位于带 KILL_ON_JOB_CLOSE 且禁止 BREAKAWAY 的 Job Object 内;
2100
+ // 直接 Start-Process 会继承同一 Job Object,DSH 一退等待进程就被连杀。
2101
+ // 优先通过 Shell.Application.ShellExecute 委托 explorer.exe 启动(inJob=False),
2102
+ // 等待脚本写出真实 PID;若无桌面 Shell 再兜底退回 Start-Process。
2103
+ 'try {',
2104
+ ` (New-Object -ComObject Shell.Application).ShellExecute(${psQuote(exe)}, ${psQuote(argLine)}, ${psQuote(dshHome)}, 'open', 0)`,
2105
+ ` for ($i = 0; $i -lt 35; $i++) {`,
2106
+ ` if (Test-Path -LiteralPath ${psQuote(pidFile)}) {`,
2107
+ ` $v = (Get-Content -LiteralPath ${psQuote(pidFile)} -Raw -ErrorAction SilentlyContinue).Trim()`,
2108
+ ` if ($v -match '^\\d+$') { Write-Output "explorer:$v"; exit 0 }`,
2109
+ ' }',
2110
+ ' Start-Sleep -Milliseconds 150',
2111
+ ' }',
2112
+ '} catch { }',
1972
2113
  `$p = Start-Process -FilePath ${psQuote(exe)} -ArgumentList @(${args.map((a) => psQuote(psWinArg(a))).join(', ')}) -WindowStyle Hidden -PassThru`,
1973
- 'Write-Output $p.Id',
2114
+ 'Write-Output "direct:$($p.Id)"',
1974
2115
  ].join('; ')
1975
2116
  const encoded = Buffer.from(inner, 'utf16le').toString('base64')
1976
2117
  let child
@@ -1978,6 +2119,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1978
2119
  child = spawn(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
1979
2120
  { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
1980
2121
  } catch (error) {
2122
+ try { unlinkSync(pidFile) } catch { }
1981
2123
  const msg = String((error && error.message) || error)
1982
2124
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${msg}`)
1983
2125
  return { ok: false, error: t(`拉不起 powershell(${exe}):${msg}`, `Cannot launch PowerShell (${exe}): ${msg}`) }
@@ -1987,22 +2129,25 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1987
2129
  child.stdout.on('data', (c) => { stdout += c })
1988
2130
  child.stderr.on('data', (c) => { stderr += c })
1989
2131
  const code = await new Promise((resolve) => {
1990
- const timer = setTimeout(() => resolve('timeout'), 8000)
2132
+ const timer = setTimeout(() => resolve('timeout'), 10000)
1991
2133
  child.once('exit', (c) => { clearTimeout(timer); resolve(c) })
1992
2134
  child.once('error', (e) => { clearTimeout(timer); resolve('error:' + ((e && e.message) || e)) })
1993
2135
  })
2136
+ try { unlinkSync(pidFile) } catch { }
1994
2137
  if (code !== 0) {
1995
2138
  const detail = String(stderr || stdout || code).trim().slice(0, 300)
1996
2139
  logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${detail}`)
1997
2140
  return { ok: false, error: t(`拉不起 post-exit(launcher 退出码 ${code}):${detail}`, `Cannot launch post-exit (launcher exit code ${code}): ${detail}`) }
1998
2141
  }
1999
- const pid = Number(String(stdout).trim().split(/\s+/).pop()) || 0
2142
+ const token = String(stdout).trim().split(/\s+/).pop() || ''
2143
+ const via = token.startsWith('explorer:') ? 'explorer' : 'direct'
2144
+ const pid = Number(token.replace(/^(explorer|direct):/, '')) || 0
2000
2145
  autoState.watcherStartedAt = Date.now()
2001
2146
  try {
2002
2147
  writeFileSync(lockFile, JSON.stringify({ pid, mode, at: Date.now() }), 'utf8')
2003
2148
  } catch { }
2004
- logLaunch(dshHome, `已启动 ${mode} pid=${pid} exe=${exe} script=${script}`)
2005
- return { ok: true, pid }
2149
+ logLaunch(dshHome, `已启动 ${mode} pid=${pid} via=${via} exe=${exe} script=${script}`)
2150
+ return { ok: true, pid, via }
2006
2151
  }
2007
2152
 
2008
2153
  /**
@@ -2068,11 +2213,19 @@ function readSyncState(dshHome) {
2068
2213
 
2069
2214
  /** 本机登记的工作区目录(capture 会把它们镜像进仓库,所以它们变了也算待推送)。 */
2070
2215
  function workspaceRoots(dshHome) {
2071
- const reg = readJson(join(dshHome, 'storages', 'workspace.json')) || {}
2072
- const list = (reg.tables && reg.tables.workspaces) || reg.workspaces || []
2073
- return Array.isArray(list)
2074
- ? list.map((w) => (w && typeof w.path === 'string' ? w.path : '')).filter(Boolean)
2075
- : []
2216
+ return listWorkspaceEntries(dshHome).map((w) => w.path).filter(Boolean)
2217
+ }
2218
+
2219
+ function encodeSessionDirName(pathStr) {
2220
+ let out = '--'
2221
+ for (const ch of String(pathStr || '')) {
2222
+ const c = ch.charCodeAt(0)
2223
+ if (c === 58) continue
2224
+ if (c === 92 || c === 47) { out += '-'; continue }
2225
+ if (c < 128) out += ch
2226
+ else out += '~' + c.toString(16).toUpperCase().padStart(4, '0')
2227
+ }
2228
+ return out + '--'
2076
2229
  }
2077
2230
 
2078
2231
  // 本机待推送文件按「同步内容」的分组归类;标签与 collectScopeGroups 的 titleZh/titleEn 对齐
@@ -2092,16 +2245,26 @@ const PENDING_GROUP_LABEL = {
2092
2245
  other: ['其它', 'Other'],
2093
2246
  }
2094
2247
 
2095
- function pendingGroupOf(file, dshHome, profileDir, workspacePaths) {
2248
+ function pendingGroupOf(file, dshHome, profileDir, workspacePaths, roots, settingsPaths) {
2096
2249
  const norm = String(file).replace(/\\/g, '/')
2097
2250
  const base = String(dshHome).replace(/\\/g, '/').replace(/\/+$/, '')
2098
2251
  const prof = String(profileDir).replace(/\\/g, '/').replace(/\/+$/, '')
2252
+ // 设置类单文件排在最前:它们多数住在 <DshHome> 一级目录里(our-free-model / dsh-pet / task-board …),
2253
+ // 同时也落在「插件数据」的槽里,先认成设置才不会被算到插件数据头上、也不会被 profile 前缀吞掉。
2254
+ if (settingsPaths && settingsPaths.has(norm.toLowerCase())) return 'settings'
2099
2255
  if (prof && norm.startsWith(prof + '/')) return 'profile'
2100
2256
  if (/\/AGENTS\.md$|\/prompt-inject\.md$/i.test(norm)) return 'prompt'
2101
2257
  if (norm.startsWith(base + '/skills/')) return 'skills'
2102
2258
  if (norm.startsWith(base + '/.agent-presets/')) return 'presets'
2259
+ if (norm.startsWith(base + '/storages/@montersy123/dsh-skill-market/data/')) return 'storages-record'
2103
2260
  if (norm.startsWith(base + '/mnemon/')) return 'mnemon'
2104
2261
  if (norm.startsWith(base + '/sessions/')) return 'conversations'
2262
+ // 用户自己指定的根(插件数据槽 / 额外路径 / 本地插件包)先认:
2263
+ // 额外路径很可能就指在某个工作区里,那种情况该算「额外路径」而不是「工作区资料」。
2264
+ for (const r of roots || []) {
2265
+ const rn = String(r.path).replace(/\\/g, '/').replace(/\/+$/, '')
2266
+ if (rn && (norm === rn || norm.startsWith(rn + '/'))) return r.group
2267
+ }
2105
2268
  for (const w of workspacePaths || []) {
2106
2269
  const wn = String(w).replace(/\\/g, '/').replace(/\/+$/, '')
2107
2270
  if (wn && norm.startsWith(wn + '/')) return 'workspace'
@@ -2133,29 +2296,171 @@ function sessionTitleOf(dshHome, sessionId) {
2133
2296
  function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2134
2297
  const since = lastSyncAt ? Date.parse(lastSyncAt) : NaN
2135
2298
  if (!Number.isFinite(since)) return { known: false, pending: 0, newestAt: '', sample: [], groups: [] }
2136
- const skip = new Set(['node_modules', '.git', 'models', '_tmp', 'staging', 'logs', 'attachments'])
2299
+ // 注意 attachments 不在跳过名单里:conversations 组现在把 <DshHome>\attachments 也算一块
2300
+ // (capture 就是这么抓的),留着它会让附件永远不计入待推送。
2301
+ const skip = new Set(['node_modules', '.git', 'models', '_tmp', 'staging', 'logs'])
2137
2302
  const profile = join(dshHome, 'profiles', profileName || 'desktop')
2138
- const workspacePaths = workspaceRoots(dshHome)
2303
+ const appRoot = String(ctx.appRoot || '')
2304
+ const scope = readScope(dshHome)
2305
+ const wsEntries = listWorkspaceEntries(dshHome)
2306
+ const wsEncToId = new Map()
2307
+ const activeWorkspacePaths = []
2308
+ for (const w of wsEntries) {
2309
+ if (w.path) wsEncToId.set(encodeSessionDirName(w.path), w.id)
2310
+ if (w.path && scopeItemEnabled(scope, 'workspace', w.id)) activeWorkspacePaths.push(w.path)
2311
+ }
2312
+ const workspacePaths = scopeGroupEnabled(scope, 'workspace') ? activeWorkspacePaths : []
2313
+ // 分组归类靠这张表:便宜的配置类根(下面 stack2)按路径前缀一眼能认出来,
2314
+ // 而插件数据 / 额外路径 / 本地插件包这类「用户自己指定的根」只能登记下来再比对。
2315
+ const roots = []
2316
+ // 只有「设置组真的会同步的那个文件」才算设置:关掉设置组之后,这些文件如果还落在
2317
+ // 某个插件数据槽里,capture 会以插件数据的名义照抓,这时就该算插件数据(否则会漏报)。
2318
+ const settingsPaths = new Set(
2319
+ scopeGroupEnabled(scope, 'settings')
2320
+ ? SYNC_SETTINGS_SOURCES
2321
+ .filter((e) => scopeItemEnabled(scope, 'settings', e.id))
2322
+ .map((e) => settingsSourcePath(dshHome, profile, e).replace(/\\/g, '/').toLowerCase())
2323
+ : [],
2324
+ )
2325
+ const addRoot = (path, group, item, extra) => {
2326
+ if (!path) return null
2327
+ roots.push({ path, group, item: item || '', ...(extra || {}) })
2328
+ return path
2329
+ }
2330
+ // ① 便宜且要紧的根(先扫完,再扫贵的):profile / 提示 / Skills / 预设 / 台账 / 设置 / 记忆 / 会话
2139
2331
  const stack = [
2140
- join(dshHome, 'sessions'),
2141
- join(dshHome, 'skills'),
2142
- join(dshHome, '.agent-presets'),
2143
- join(dshHome, 'mnemon'),
2144
- join(dshHome, 'AGENTS.md'),
2145
- join(dshHome, 'prompt-inject.md'),
2146
2332
  join(profile, 'package.json'),
2147
2333
  join(profile, 'pnpm-lock.yaml'),
2334
+ join(profile, 'pnpm-workspace.yaml'),
2335
+ join(profile, 'cordis.yml'),
2148
2336
  join(profile, 'cordis.patch.yml'),
2149
2337
  join(profile, 'host-contract.json'),
2150
- ...workspaceRoots(dshHome),
2151
2338
  ]
2339
+ if (scopeGroupEnabled(scope, 'prompt')) {
2340
+ if (scopeItemEnabled(scope, 'prompt', 'AGENTS.md')) stack.push(join(dshHome, 'AGENTS.md'))
2341
+ if (scopeItemEnabled(scope, 'prompt', 'prompt-inject.md')) stack.push(join(dshHome, 'prompt-inject.md'))
2342
+ }
2343
+ if (scopeGroupEnabled(scope, 'skills')) {
2344
+ const skillsRoot = join(dshHome, 'skills')
2345
+ for (const name of listSubDirs(skillsRoot)) {
2346
+ if (scopeItemEnabled(scope, 'skills', name)) stack.push(join(skillsRoot, name))
2347
+ }
2348
+ }
2349
+ if (scopeGroupEnabled(scope, 'presets')) {
2350
+ const presetsRoot = join(dshHome, '.agent-presets')
2351
+ for (const name of listSubDirs(presetsRoot)) {
2352
+ if (scopeItemEnabled(scope, 'presets', name)) stack.push(join(presetsRoot, name))
2353
+ }
2354
+ }
2355
+ // 技能市场台账:capture 抓的是这两个 fixed 文件,面板的待推送也只看这两个
2356
+ if (scopeGroupEnabled(scope, 'storages-record')) {
2357
+ const ledgerDir = join(dshHome, 'storages', '@montersy123', 'dsh-skill-market', 'data')
2358
+ for (const [file, id] of [['installed.json', 'skill-market-installed.json'], ['panel.json', 'skill-market-panel.json']]) {
2359
+ if (scopeItemEnabled(scope, 'storages-record', id)) stack.push(join(ledgerDir, file))
2360
+ }
2361
+ }
2362
+ // 插件设置与工作流:与 collectScopeGroups / capture 的 Get-SyncSettingsMap 同一份清单(14 条)
2363
+ if (scopeGroupEnabled(scope, 'settings')) {
2364
+ for (const entry of SYNC_SETTINGS_SOURCES) {
2365
+ if (!scopeItemEnabled(scope, 'settings', entry.id)) continue
2366
+ stack.push(settingsSourcePath(dshHome, profile, entry))
2367
+ }
2368
+ }
2369
+ // 记忆数据:capture 读的是 <AppRoot>\mnemon(不是 <DshHome>\mnemon,这里以前写错过)
2370
+ if (scopeGroupEnabled(scope, 'mnemon') && appRoot) {
2371
+ const mnemonRoot = join(appRoot, 'mnemon')
2372
+ addRoot(mnemonRoot, 'mnemon', 'mnemon')
2373
+ stack.push(mnemonRoot)
2374
+ }
2375
+ // ② 贵的根(会话、工作区、插件数据、额外路径、本地插件包):扫描预算有限,
2376
+ // 它们必须排在便宜的配置类之后,否则工作区里两万个文件会把 skills/profile 挤出去,
2377
+ // 面板就报「配置没变」而其实配置变了。
2378
+ const deferred = []
2379
+ let extraCfg = null
2380
+ try { extraCfg = readExtraConfig(dshHome) } catch { extraCfg = null }
2381
+ if (scopeGroupEnabled(scope, 'conversations')) {
2382
+ // conversations 组在 capture 里是四块(sessions / attachments / projcache / policies),
2383
+ // 以前待推送只数 sessions:往附件里丢一张图、或某个会话的 projcache 更新,
2384
+ // 面板照样说「仓库与本机一致」,一推却动了文件。
2385
+ const sessRoot = join(dshHome, 'sessions')
2386
+ const skipSessIds = new Set()
2387
+ for (const dirName of listSubDirs(sessRoot)) {
2388
+ if (/default-workspace/i.test(dirName)) continue
2389
+ const wsId = wsEncToId.get(dirName)
2390
+ if (wsId && !scopeItemEnabled(scope, 'conversations', wsId)) {
2391
+ for (const sid of listSubDirs(join(sessRoot, dirName))) skipSessIds.add(sid)
2392
+ continue
2393
+ }
2394
+ deferred.push(join(sessRoot, dirName))
2395
+ }
2396
+ const attachRoot = join(dshHome, 'attachments')
2397
+ if (existsSync(attachRoot)) {
2398
+ addRoot(attachRoot, 'conversations', 'attachments')
2399
+ deferred.push(attachRoot)
2400
+ }
2401
+ // projcache / policies:第一段是会话 id(形如 <sid>.json),按被取消勾选的会话逐个筛掉
2402
+ for (const [root, item] of [
2403
+ [join(dshHome, 'storages', 'session_projcache', 'sessions'), 'projcache'],
2404
+ [join(dshHome, 'storages', 'vision_router_session_policy', 'policies'), 'policies'],
2405
+ ]) {
2406
+ if (!existsSync(root)) continue
2407
+ addRoot(root, 'conversations', item, { skipSessionIds: skipSessIds })
2408
+ deferred.push(root)
2409
+ }
2410
+ }
2411
+ deferred.push(...workspacePaths)
2412
+ // 本地插件包:capture 把 link: 挂进来的插件目录打成 zip,所以源目录就是待推送的判据
2413
+ if (scopeGroupEnabled(scope, 'local-plugins')) {
2414
+ try {
2415
+ const pkg = readJson(join(profile, 'package.json')) || {}
2416
+ const deps = pkg.dependencies || {}
2417
+ for (const [name, spec] of Object.entries(deps)) {
2418
+ if (typeof spec !== 'string' || !spec.startsWith('link:')) continue
2419
+ const target = spec.slice(5)
2420
+ const leaf = String(target).split(/[\\/]+/).filter(Boolean).pop() || name
2421
+ if (!scopeItemEnabled(scope, 'local-plugins', leaf)) continue
2422
+ if (!isDir(target)) continue
2423
+ addRoot(target, 'local-plugins', leaf)
2424
+ deferred.push(target)
2425
+ }
2426
+ } catch { /* link 目标读不出来就不算,反正 push 时还会再判一次 */ }
2427
+ }
2428
+ // 插件数据:槽清单与面板「插件数据」组一致(都是 <DshHome> 一级目录去掉 skipDirs 与隐藏目录),
2429
+ // 但这里**不调 listPluginDataSlots**:那个函数会把每个槽整个数一遍文件,
2430
+ // 而待推送扫描本来就要走一遍,数两遍纯粹浪费(browser-profiles 这种槽就几千个文件)。
2431
+ if (extraCfg && scopeGroupEnabled(scope, 'plugin-data') && extraCfg.pluginData.enabled !== false) {
2432
+ const skipDirs = new Set(extraCfg.pluginData.skipDirs || [])
2433
+ let entries = []
2434
+ try { entries = readdirSync(dshHome, { withFileTypes: true }) } catch { entries = [] }
2435
+ for (const e of entries) {
2436
+ if (!e.isDirectory()) continue
2437
+ if (skipDirs.has(e.name)) continue
2438
+ if (e.name.startsWith('.')) continue
2439
+ // 浏览器剖面/凭据库一律不扫(哪怕用户规则里删掉了这条跳过项)
2440
+ if (isBlockedProfilePath(e.name)) continue
2441
+ if (!scopeItemEnabled(scope, 'plugin-data', e.name)) continue
2442
+ addRoot(join(dshHome, e.name), 'plugin-data', e.name)
2443
+ deferred.push(join(dshHome, e.name))
2444
+ }
2445
+ }
2446
+ // 额外路径:用户自己登记的 src(文件或目录),逐个按条目勾选
2447
+ if (extraCfg && scopeGroupEnabled(scope, 'extra') && extraCfg.extra.enabled !== false) {
2448
+ for (const p of extraCfg.extra.paths || []) {
2449
+ if (!p || !p.src) continue
2450
+ if (!scopeItemEnabled(scope, 'extra', p.id)) continue
2451
+ addRoot(p.src, 'extra', p.id)
2452
+ deferred.push(p.src)
2453
+ }
2454
+ }
2455
+ // unshift 而不是 push:pop() 从尾部取,贵的根要排在数组前部才会最后被扫到
2456
+ stack.unshift(...deferred)
2152
2457
  // 有仓库对应物的单文件:路径 → 仓库里的那份。只有这些才值得读内容比对。
2153
2458
  const repoRoot = String(ctx.repo || '')
2154
2459
  const mirrored = new Map()
2155
2460
  if (repoRoot) {
2156
2461
  mirrored.set(join(dshHome, 'AGENTS.md'), join(repoRoot, 'prompt', 'AGENTS.md'))
2157
2462
  mirrored.set(join(dshHome, 'prompt-inject.md'), join(repoRoot, 'prompt', 'prompt-inject.md'))
2158
- for (const f of ['package.json', 'pnpm-lock.yaml', 'cordis.patch.yml', 'host-contract.json']) {
2463
+ for (const f of ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml', 'host-contract.json']) {
2159
2464
  mirrored.set(join(profile, f), join(repoRoot, 'profile', f))
2160
2465
  }
2161
2466
  }
@@ -2168,12 +2473,46 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2168
2473
  // 每组保留具体明细名称(会话记录名 / 本机 profile 文件名 …),供面板展开查看
2169
2474
  const groupItems = new Map()
2170
2475
  const DETAIL_CAP = 50
2476
+ // 用户自定的根(插件数据槽 / 额外路径 / 本地插件包)里 capture 还会按规则过滤:
2477
+ // 插件数据与额外路径走 config-sync-extra.json 的 exclude 名单与单文件上限,本地插件包固定跳过
2478
+ // .git / node_modules / releases / .cache。待推送计数必须同样过滤,否则「被排除的 .db 一直在变」
2479
+ // 会让面板永远建议推送(插件自己的 sqlite 每次写入都会更新 mtime)。
2480
+ const normRoots = roots.map((r) => ({
2481
+ group: r.group,
2482
+ base: String(r.path).replace(/\\/g, '/').replace(/\/+$/, ''),
2483
+ skipSessionIds: r.skipSessionIds || null,
2484
+ rules: (r.group === 'plugin-data' || r.group === 'extra') && extraCfg
2485
+ ? { cfg: extraCfg, dirs: dirHasRules(extraCfg) }
2486
+ : r.group === 'local-plugins' ? { cfg: null, segs: new Set(['.git', 'node_modules', 'releases', '.cache']) } : null,
2487
+ }))
2488
+ const ownerOf = (p) => {
2489
+ const n = String(p).replace(/\\/g, '/')
2490
+ for (const r of normRoots) {
2491
+ if (n === r.base || n.startsWith(r.base + '/')) return r
2492
+ }
2493
+ return null
2494
+ }
2171
2495
  while (stack.length && scanned < 20000 && Date.now() < deadline) {
2172
2496
  const cur = stack.pop()
2173
2497
  let st
2174
2498
  try { st = statSync(cur) } catch { continue }
2499
+ const owner = ownerOf(cur)
2500
+ // 浏览器剖面 / 凭据库的路径段:capture 永远不会抓(Test-BlockedProfilePath 硬拦),
2501
+ // 待推送也不该数——否则浏览器一跑,几千个缓存/登录态文件就永远显示「待推送」。
2502
+ if (owner && (owner.group === 'plugin-data' || owner.group === 'extra') && isBlockedProfilePath(relative(owner.base, String(cur).replace(/\\/g, '/')))) continue
2503
+ // projcache / policies:第一段是会话 id(<sid>.json),被取消勾选的工作区里的会话整块不抓
2504
+ if (owner && owner.skipSessionIds && owner.skipSessionIds.size) {
2505
+ const head = relative(owner.base, String(cur).replace(/\\/g, '/')).split('/')[0] || ''
2506
+ const sid = head.replace(/\.[^.]+$/, '')
2507
+ if (owner.skipSessionIds.has(head) || owner.skipSessionIds.has(sid)) continue
2508
+ }
2175
2509
  if (st.isDirectory()) {
2176
2510
  if (skip.has(basename(cur))) continue
2511
+ const leaf = basename(cur).toLowerCase()
2512
+ if (owner && owner.rules) {
2513
+ if (owner.rules.dirs && owner.rules.dirs.some((re) => re.test(basename(cur)))) continue
2514
+ if (owner.rules.segs && owner.rules.segs.has(leaf)) continue
2515
+ }
2177
2516
  let entries = []
2178
2517
  try { entries = readdirSync(cur) } catch { continue }
2179
2518
  for (const e of entries) stack.push(join(cur, e))
@@ -2181,6 +2520,11 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2181
2520
  }
2182
2521
  scanned++
2183
2522
  if (st.mtimeMs > since) {
2523
+ // 被 capture 的规则排除掉的文件永远进不了仓库,不该算成「待推送」
2524
+ if (owner && owner.rules && owner.rules.cfg) {
2525
+ const rel = relative(owner.base, String(cur).replace(/\\/g, '/'))
2526
+ if (extraSkipReason(rel, st.size, owner.rules.cfg)) continue
2527
+ }
2184
2528
  // 镜像文件的 mtime 更新可能只是宿主重写占位符:内容归一后一致就不算待推送
2185
2529
  const twin = mirrored.get(cur)
2186
2530
  if (twin && isFile(twin)) {
@@ -2190,7 +2534,10 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2190
2534
  }
2191
2535
  pending++
2192
2536
  if (st.mtimeMs > newest) newest = st.mtimeMs
2193
- const gid = pendingGroupOf(cur, dshHome, profile, workspacePaths)
2537
+ const gid = pendingGroupOf(cur, dshHome, profile, workspacePaths, roots, settingsPaths)
2538
+ // 非 Windows 走的是 runtime\sync-engine.mjs:它只抓 profile / 提示 / Skills / 预设。
2539
+ // 在这台机器上把会话记录、插件数据、额外路径也算成「待推送」,等于承诺一件永远不会发生的事。
2540
+ if (ENGINE_SYNCED_GROUPS && !ENGINE_SYNCED_GROUPS.has(gid)) { pending--; continue }
2194
2541
  groupCount.set(gid, (groupCount.get(gid) || 0) + 1)
2195
2542
  // 会话文件显示会话标题而不是目录 ID;其余显示父目录/文件名
2196
2543
  let label = `${basename(dirname(cur))}/${basename(cur)}`
@@ -2226,6 +2573,8 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2226
2573
  groups,
2227
2574
  profileName: profileName || 'desktop',
2228
2575
  truncated: scanned >= 20000 || Date.now() >= deadline,
2576
+ // 非 Windows 时只统计引擎真会同步的四组,把这件事说出来(面板会显示,不让用户以为别的组也在同步)
2577
+ engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
2229
2578
  }
2230
2579
  }
2231
2580
 
@@ -2374,7 +2723,13 @@ async function handleSettings(req, res, config) {
2374
2723
 
2375
2724
  // 新仓库路径一落盘,后面的 git remote 要对它做,别用改之前解析出来的旧仓库。
2376
2725
  const repo = repoPath || (resolveRepo(config?.repoPath, dshHome).repo || '')
2377
- writeSettings(dshHome, { repoPath, remoteUrl, sshKey, autoPull, autoPush, autoRestart, updateToken, updateManifestUrl, backupRoot, defaultWorkspace, cacheGuard })
2726
+ // 以「磁盘上的原始 JSON」为底:用户这次没提交的字段(尤其 webdav* / syncMode)必须原样留下。
2727
+ const rawBefore = readJson(file) || {}
2728
+ writeSettings(dshHome, {
2729
+ ...rawBefore,
2730
+ repoPath, remoteUrl, sshKey, autoPull, autoPush, autoRestart,
2731
+ updateToken, updateManifestUrl, backupRoot, defaultWorkspace, cacheGuard,
2732
+ })
2378
2733
 
2379
2734
  const changed = {
2380
2735
  repoPath: before.repoPath !== repoPath,
@@ -2538,16 +2893,16 @@ function resolveTgzUrl(manifest, manifestUrl = UPDATE_MANIFEST_URL) {
2538
2893
  return ''
2539
2894
  }
2540
2895
 
2541
- async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT) {
2896
+ async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT, headers = {}) {
2542
2897
  if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch,无法检查更新', 'fetch is unavailable in this runtime — cannot check for updates'))
2543
2898
  const seconds = Math.round(timeoutMs / 1000)
2544
2899
  const ctrl = typeof AbortController === 'function' ? new AbortController() : null
2545
2900
  let timedOut = false
2546
2901
  const timer = ctrl ? setTimeout(() => { timedOut = true; try { ctrl.abort() } catch { } }, timeoutMs) : null
2547
2902
  try {
2548
- const res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
2903
+ const res = await fetch(url, { cache: 'no-store', headers, signal: ctrl ? ctrl.signal : undefined })
2549
2904
  if (!res.ok) {
2550
- throw new Error(`HTTP ${res.status}${res.status === 403 ? t('(私有仓库要填只读令牌)', ' (a read-only token is required for private repos)') : ''}`)
2905
+ throw new Error(`HTTP ${res.status}${(res.status === 401 || res.status === 403 || res.status === 404) ? t('(若为私有仓库,需配置只读令牌或环境变量)', ' (if private, configure a read-only token or env var)') : ''}`)
2551
2906
  }
2552
2907
  const json = await res.json()
2553
2908
  if (!json || !json.version) throw new Error(t('version.json 里没有 version 字段', 'version.json has no "version" field'))
@@ -2561,17 +2916,66 @@ async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT) {
2561
2916
  }
2562
2917
  }
2563
2918
 
2919
+ /** 仅向直连官方域传令牌(绝不把令牌发给第三方反代 gh-proxy / ghfast)。 */
2920
+ function authHeadersForUrl(url, token) {
2921
+ try {
2922
+ const u = new URL(url)
2923
+ const host = u.hostname.toLowerCase()
2924
+ if (host === 'api.github.com') {
2925
+ const headers = {
2926
+ Accept: u.pathname.includes('/contents/') ? 'application/vnd.github.raw+json' : 'application/vnd.github+json',
2927
+ 'X-GitHub-Api-Version': '2022-11-28',
2928
+ 'User-Agent': PACKAGE_ID,
2929
+ }
2930
+ if (token) headers.Authorization = `Bearer ${token}`
2931
+ return headers
2932
+ }
2933
+ if (token && (host === 'raw.githubusercontent.com' || host === 'github.com' || host.endsWith('.github.com'))) {
2934
+ return { Authorization: `Bearer ${token}`, 'User-Agent': PACKAGE_ID }
2935
+ }
2936
+ } catch { }
2937
+ return {}
2938
+ }
2939
+
2940
+ function isGithubUrl(url) {
2941
+ try {
2942
+ const host = new URL(String(url || '')).hostname.toLowerCase()
2943
+ return host === 'github.com' || host.endsWith('.github.com') || host === 'raw.githubusercontent.com' || host === 'api.github.com'
2944
+ } catch { return false }
2945
+ }
2946
+
2947
+ /** 解析更新检查/下载用的令牌:自定义非 GitHub 地址不自动借用本机 GitHub 登录态。 */
2948
+ async function resolveUpdateToken(settings, customUrl = '') {
2949
+ const custom = String(customUrl || '').trim()
2950
+ const spec = resolveTokenSpec(settings.updateToken, custom && !isGithubUrl(custom) ? [] : GH_TOKEN_ENV_CANDIDATES)
2951
+ if (spec.token) return spec
2952
+ if (custom && !isGithubUrl(custom)) return spec
2953
+ const cred = await credFromGitCredential()
2954
+ if (cred.token) return { token: cred.token, source: 'git-credential', envName: '', rawRef: false }
2955
+ const cliTok = await tokenFromGhCli()
2956
+ if (cliTok) return { token: cliTok, source: 'gh-cli', envName: '', rawRef: false }
2957
+ return spec
2958
+ }
2959
+
2564
2960
  /**
2565
- * 读清单:自定义地址只用它自己;没配则按 UPDATE_MANIFEST_MIRRORS 依次试,第一个成功的就用。
2961
+ * 读清单:自定义地址只用它自己;没配则按候选源依次试,第一个成功的就用。
2962
+ * 有令牌时把 GitHub API 放在最前面(私有库第三方反代必 404、直连 raw 常超时,API 几百毫秒直达)。
2566
2963
  * 全失败时把每个源各自的失败原因汇总抛出 —— 面板上一眼能看出是超时、HTTP 状态还是解析失败。
2567
2964
  */
2568
2965
  async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH_TIMEOUT) {
2569
2966
  const custom = String(targetUrl || '').trim()
2570
- const candidates = custom ? [custom] : UPDATE_MANIFEST_MIRRORS.slice()
2967
+ const candidates = custom
2968
+ ? [custom]
2969
+ : (token
2970
+ ? [API_MANIFEST_URL, ...UPDATE_MANIFEST_MIRRORS.filter((u) => u !== API_MANIFEST_URL)]
2971
+ : UPDATE_MANIFEST_MIRRORS.slice())
2571
2972
  const tried = []
2572
2973
  for (const cand of candidates) {
2573
2974
  try {
2574
- const manifest = await fetchManifest(withAccessToken(cand, token), timeoutMs)
2975
+ const headers = authHeadersForUrl(cand, token)
2976
+ // 有令牌且走直连 GitHub 域时改用 Authorization Header,绝不把令牌拼进第三方反代 URL
2977
+ const reqUrl = Object.keys(headers).length ? cand : withAccessToken(cand, token)
2978
+ const manifest = await fetchManifest(reqUrl, timeoutMs, headers)
2575
2979
  tried.push({ url: cand, ok: true })
2576
2980
  return { manifest, url: cand, tried }
2577
2981
  } catch (error) {
@@ -2593,11 +2997,15 @@ async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH
2593
2997
  * 注意 API 的 raw 端点不吃"分支写进路径",分支要单独给 ref:
2594
2998
  * https://gitee.com/<owner>/<repo>/raw/<branch>/<path>
2595
2999
  * → https://gitee.com/api/v5/repos/<owner>/<repo>/raw/<path>?ref=<branch>&access_token=…
2596
- * 公开库不填令牌时保持原样,行为跟以前一致。
3000
+ * 公开库与第三方反代(gh-proxy / ghfast)不拼入令牌,避免泄露给中间代理。
2597
3001
  */
2598
3002
  function withAccessToken(url, token) {
2599
3003
  const raw = String(url || '')
2600
3004
  if (!token) return raw
3005
+ try {
3006
+ const host = new URL(raw).hostname.toLowerCase()
3007
+ if (host !== 'gitee.com' && !host.endsWith('.gitee.com')) return raw
3008
+ } catch { return raw }
2601
3009
  let target = raw
2602
3010
  const m = /^https:\/\/gitee\.com\/([^/]+)\/([^/]+)\/raw\/([^/]+)\/(.+)$/.exec(raw.split('?')[0])
2603
3011
  if (m) target = `https://gitee.com/api/v5/repos/${m[1]}/${m[2]}/raw/${m[4]}?ref=${encodeURIComponent(m[3])}`
@@ -2631,9 +3039,10 @@ async function checkUpdate({ force = false, url = '', token = '' } = {}) {
2631
3039
  return updateState
2632
3040
  }
2633
3041
 
2634
- function updatePayload(state, settings = {}) {
3042
+ function updatePayload(state, settings = {}, resolvedToken = null) {
2635
3043
  const remote = state.manifest
2636
3044
  const custom = String(settings.updateManifestUrl || '')
3045
+ const resolvedUpd = resolvedToken || resolveTokenSpec(settings.updateToken, custom ? [] : GH_TOKEN_ENV_CANDIDATES)
2637
3046
  const installed = state.liveInstall || null
2638
3047
  // 装好了但进程还在跑旧代码 = 需要重启;重启后 PLUGIN_VERSION 追上来,这条自然消失
2639
3048
  const restartRequired = Boolean(installed && compareVersion(installed.version, PLUGIN_VERSION) > 0)
@@ -2645,7 +3054,10 @@ function updatePayload(state, settings = {}) {
2645
3054
  manifestUrl: custom || UPDATE_MANIFEST_MIRRORS[0],
2646
3055
  manifestUrlIsDefault: !custom,
2647
3056
  manifestSources: custom ? [] : UPDATE_MANIFEST_MIRRORS.slice(),
2648
- tokenSet: Boolean(settings.updateToken),
3057
+ tokenSet: Boolean(resolvedUpd.token),
3058
+ tokenSaved: Boolean(settings.updateToken && !parseEnvTokenRef(settings.updateToken)),
3059
+ tokenSource: resolvedUpd.source,
3060
+ tokenEnv: resolvedUpd.envName,
2649
3061
  },
2650
3062
  remote: remote ? {
2651
3063
  version: String(remote.version || ''),
@@ -2693,7 +3105,36 @@ function updatePayload(state, settings = {}) {
2693
3105
  * 候选地址逐个试(raw 常常不通,反代在前面兜着),全失败时把每个源的原因汇总抛出。
2694
3106
  * 返回 { ok, file, size, sha256, url } 或 { ok:false, error }
2695
3107
  */
2696
- async function downloadPackage({ urls, sha256, version, dshHome }) {
3108
+ /** 私有 GitHub Release 资产必须通过 API + Accept: application/octet-stream 取,重定向后剥掉 Authorization。 */
3109
+ async function fetchGithubReleaseAsset(url, token, timeoutMs = 120 * 1000) {
3110
+ const m = /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/releases\/download\/([^/]+)\/([^/?#]+)/i.exec(String(url || ''))
3111
+ if (!m || !token) return null
3112
+ const [, owner, repo, tag, assetName] = m
3113
+ const apiUrl = `https://api.github.com/repos/${owner}/${repo}/releases/tags/${encodeURIComponent(tag)}`
3114
+ const apiHeaders = { Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': PACKAGE_ID, Authorization: `Bearer ${token}` }
3115
+ const relRes = await fetch(apiUrl, { cache: 'no-store', headers: apiHeaders, signal: AbortSignal.timeout(timeoutMs) })
3116
+ if (!relRes.ok) throw new Error(`GitHub Release API HTTP ${relRes.status}`)
3117
+ const rel = await relRes.json()
3118
+ const asset = (Array.isArray(rel && rel.assets) ? rel.assets : []).find((a) => a && a.name === decodeURIComponent(assetName))
3119
+ if (!asset || !asset.url) throw new Error(t(`Release ${tag} 里找不到资产 ${assetName}`, `Asset ${assetName} not found in release ${tag}`))
3120
+ const assetRes = await fetch(asset.url, {
3121
+ cache: 'no-store',
3122
+ redirect: 'manual',
3123
+ headers: { Accept: 'application/octet-stream', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': PACKAGE_ID, Authorization: `Bearer ${token}` },
3124
+ signal: AbortSignal.timeout(timeoutMs),
3125
+ })
3126
+ if (assetRes.status >= 300 && assetRes.status < 400) {
3127
+ const loc = assetRes.headers.get('location')
3128
+ if (!loc) throw new Error(`HTTP ${assetRes.status}`)
3129
+ const s3Res = await fetch(loc, { cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) })
3130
+ if (!s3Res.ok) throw new Error(`HTTP ${s3Res.status}`)
3131
+ return Buffer.from(await s3Res.arrayBuffer())
3132
+ }
3133
+ if (!assetRes.ok) throw new Error(`HTTP ${assetRes.status}`)
3134
+ return Buffer.from(await assetRes.arrayBuffer())
3135
+ }
3136
+
3137
+ async function downloadPackage({ urls, sha256, version, dshHome, token = '' }) {
2697
3138
  if (typeof fetch !== 'function') return { ok: false, error: t('当前运行环境没有 fetch,无法下载更新包', 'fetch is unavailable in this runtime — cannot download the update package') }
2698
3139
  const dir = join(dshHome, 'update-staging')
2699
3140
  try { mkdirSync(dir, { recursive: true }) } catch { }
@@ -2704,16 +3145,24 @@ async function downloadPackage({ urls, sha256, version, dshHome }) {
2704
3145
  const url = String(rawUrl || '').trim()
2705
3146
  if (!url) continue
2706
3147
  try {
2707
- const ctrl = typeof AbortController === 'function' ? new AbortController() : null
2708
- const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120 * 1000) : null
2709
- let res
2710
- try {
2711
- res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
2712
- } finally {
2713
- if (timer) clearTimeout(timer)
3148
+ let buf = null
3149
+ if (token && /^https:\/\/github\.com\/[^/]+\/[^/]+\/releases\/download\//i.test(url)) {
3150
+ try { buf = await fetchGithubReleaseAsset(url, token) } catch { buf = null }
3151
+ }
3152
+ if (!buf) {
3153
+ const ctrl = typeof AbortController === 'function' ? new AbortController() : null
3154
+ const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120 * 1000) : null
3155
+ const headers = authHeadersForUrl(url, token)
3156
+ const reqUrl = Object.keys(headers).length ? url : withAccessToken(url, token)
3157
+ let res
3158
+ try {
3159
+ res = await fetch(reqUrl, { cache: 'no-store', headers, signal: ctrl ? ctrl.signal : undefined })
3160
+ } finally {
3161
+ if (timer) clearTimeout(timer)
3162
+ }
3163
+ if (!res.ok) throw new Error(`HTTP ${res.status}`)
3164
+ buf = Buffer.from(await res.arrayBuffer())
2714
3165
  }
2715
- if (!res.ok) throw new Error(`HTTP ${res.status}`)
2716
- const buf = Buffer.from(await res.arrayBuffer())
2717
3166
  if (!buf.length) throw new Error(t('下载到的文件是空的', 'the downloaded file is empty'))
2718
3167
  const hash = createHash('sha256').update(buf).digest('hex')
2719
3168
  if (want && hash !== want) throw new Error(t(`sha256 不一致(拿到 ${hash})`, `sha256 mismatch (got ${hash})`))
@@ -2780,23 +3229,29 @@ async function handleUpdate(req, res, config) {
2780
3229
  const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
2781
3230
  const settings = readSettings(dshHome)
2782
3231
  // 清单地址允许被设置覆盖:换镜像/自建仓库、或本地搭测试服务时不改动插件源码。
2783
- // 留空 = 用内置候选列表(jsDelivr 优先、raw 兜底)
3232
+ // 留空 = 用内置候选列表(GitHub API / gh-proxy / ghfast / raw)
2784
3233
  const manifestUrl = String(settings.updateManifestUrl || '')
2785
- const updateToken = String(settings.updateToken || '')
2786
3234
  try {
2787
3235
  if (req.method === 'GET') {
2788
- sendJson(res, 200, updatePayload(await checkUpdate({ url: manifestUrl, token: updateToken }), settings))
3236
+ const resolvedUpd = await resolveUpdateToken(settings, manifestUrl)
3237
+ sendJson(res, 200, updatePayload(await checkUpdate({ url: manifestUrl, token: resolvedUpd.token }), settings, resolvedUpd))
2789
3238
  return
2790
3239
  }
2791
3240
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET or POST only' }); return }
2792
3241
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3242
+ // 先读 body 再解析令牌:读 body 之前不能有 await,否则请求流可能已经被读空/结束,
3243
+ // 事件监听挂晚了就永远等不到 'end'(实测:把令牌解析提到前面会让所有 POST 一直挂住)。
2793
3244
  const raw = await readBody(req)
2794
3245
  const body = raw.trim() ? JSON.parse(raw) : {}
2795
3246
  const action = String(body.action || 'check')
3247
+ const resolvedUpd = await resolveUpdateToken(settings, manifestUrl)
3248
+ const updateToken = resolvedUpd.token
2796
3249
 
2797
3250
  if (action === 'check') {
2798
- const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
2799
- sendJson(res, 200, { ok: !state.error, action, ...updatePayload(state, settings) })
3251
+ clearWinEnvCache()
3252
+ const refreshedUpd = await resolveUpdateToken(settings, manifestUrl)
3253
+ const state = await checkUpdate({ force: true, url: manifestUrl, token: refreshedUpd.token })
3254
+ sendJson(res, 200, { ok: !state.error, action, ...updatePayload(state, settings, refreshedUpd) })
2800
3255
  return
2801
3256
  }
2802
3257
 
@@ -2812,12 +3267,12 @@ async function handleUpdate(req, res, config) {
2812
3267
  // 同一个版本已经下好就不重复下(DSH 一直开着时用户可能点第二次)
2813
3268
  const prev = updateState.prepared
2814
3269
  if (prev && prev.version === String(remote.version) && isFile(prev.file)) {
2815
- sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings) })
3270
+ sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings, resolvedUpd) })
2816
3271
  return
2817
3272
  }
2818
3273
  const urls = resolveTgzCandidates(remote, state.url)
2819
3274
  if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
2820
- const got = await downloadPackage({ urls, sha256: String(remote.sha256 || ''), version: String(remote.version), dshHome })
3275
+ const got = await downloadPackage({ urls, sha256: String(remote.sha256 || ''), version: String(remote.version), dshHome, token: updateToken })
2821
3276
  if (!got.ok) throw new Error(String(got.error || t('下载失败', 'download failed')))
2822
3277
  updateState.prepared = {
2823
3278
  version: String(remote.version),
@@ -2827,7 +3282,7 @@ async function handleUpdate(req, res, config) {
2827
3282
  at: Date.now(),
2828
3283
  url: got.url,
2829
3284
  }
2830
- sendJson(res, 200, { ok: true, action, prepared: updateState.prepared, ...updatePayload(state, settings) })
3285
+ sendJson(res, 200, { ok: true, action, prepared: updateState.prepared, ...updatePayload(state, settings, resolvedUpd) })
2831
3286
  return
2832
3287
  }
2833
3288
 
@@ -2850,6 +3305,7 @@ async function handleUpdate(req, res, config) {
2850
3305
  appRoot,
2851
3306
  dshHome,
2852
3307
  restart: true,
3308
+ closeRequested: true,
2853
3309
  extraArgs: [
2854
3310
  '-PluginDir', PLUGIN_DIR,
2855
3311
  '-UpdateTgz', prepared.file,
@@ -2861,7 +3317,7 @@ async function handleUpdate(req, res, config) {
2861
3317
  autoState.pending = { mode: 'update', at: Date.now(), version: String(prepared.version), restart: true, watcherPid: started.pid, installFrom: prepared.file }
2862
3318
  const closed = closeDsh()
2863
3319
  autoState.pending.closeRequested = closed
2864
- sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed, ...updatePayload(await checkUpdate({ force: false, url: manifestUrl, token: updateToken }), settings) })
3320
+ sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed, ...updatePayload(await checkUpdate({ force: false, url: manifestUrl, token: updateToken }), settings, resolvedUpd) })
2865
3321
  return
2866
3322
  }
2867
3323
 
@@ -2886,7 +3342,7 @@ async function handleUpdate(req, res, config) {
2886
3342
  }
2887
3343
  // 注意 hasUpdate 仍是 true:进程里跑的还是旧代码,重启后 PLUGIN_VERSION 才追上来。
2888
3344
  // 面板靠 restartRequired 换成「已装好,重启生效」
2889
- sendJson(res, 200, { ok: true, action, installed: updateState.liveInstall, ...updatePayload(state, settings) })
3345
+ sendJson(res, 200, { ok: true, action, installed: updateState.liveInstall, ...updatePayload(state, settings, resolvedUpd) })
2890
3346
  return
2891
3347
  }
2892
3348
 
@@ -2914,7 +3370,7 @@ async function handleUpdate(req, res, config) {
2914
3370
  if (!tgz) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
2915
3371
  const notes = String((langStore.getStore() === 'en' ? (remote.notesEn || remote.notes) : remote.notes) || '').trim()
2916
3372
  const yes = await askConfirm(
2917
- t('更新「配置同步」插件', 'Update the Config Sync plugin'),
3373
+ t('更新「配置备份与同步」插件', 'Update the Config Backup & Sync plugin'),
2918
3374
  t(
2919
3375
  `把插件从 ${PLUGIN_VERSION} 更新到 ${remote.version}?`
2920
3376
  + (notes ? `\n\n${notes}` : '')
@@ -2924,7 +3380,7 @@ async function handleUpdate(req, res, config) {
2924
3380
  + '\n\nSteps: exit DSH → download and verify the package → back up the old version → install over it → relaunch automatically.',
2925
3381
  ),
2926
3382
  )
2927
- if (!yes) { sendJson(res, 200, { ok: true, action, cancelled: true, ...updatePayload(state, settings) }); return }
3383
+ if (!yes) { sendJson(res, 200, { ok: true, action, cancelled: true, ...updatePayload(state, settings, resolvedUpd) }); return }
2928
3384
 
2929
3385
  const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
2930
3386
  const appRoot = resolveAppRoot(config?.appRoot) || ''
@@ -2934,6 +3390,7 @@ async function handleUpdate(req, res, config) {
2934
3390
  appRoot,
2935
3391
  dshHome,
2936
3392
  restart: true,
3393
+ closeRequested: true,
2937
3394
  extraArgs: [
2938
3395
  '-PluginDir', PLUGIN_DIR,
2939
3396
  '-UpdateVersion', String(remote.version),
@@ -3040,6 +3497,14 @@ function countEntries(dir) {
3040
3497
  }
3041
3498
  }
3042
3499
 
3500
+ /**
3501
+ * 这台机器上的同步执行体实际会抓的组。
3502
+ * Windows 走 sync.ps1(12 组);macOS/Linux 走 runtime\sync-engine.mjs,它只抓
3503
+ * profile(4 个文件)/ prompt / skills / presets —— 别的组在那台机器上根本不会被同步。
3504
+ * null 表示「全部组」,非 Windows 时是白名单。
3505
+ */
3506
+ const ENGINE_SYNCED_GROUPS = IS_WIN ? null : new Set(['profile', 'prompt', 'skills', 'presets'])
3507
+
3043
3508
  /** profile 目录:优先 desktop,其次 profiles 下唯一的那一个 */
3044
3509
  function resolveProfileDir(dshHome) {
3045
3510
  const desktop = join(dshHome, 'profiles', 'desktop')
@@ -3098,18 +3563,92 @@ const EXTRA_HARD_MAX_BYTES = 104857600
3098
3563
  const EXTRA_DEFAULT_SKIP_DIRS = [
3099
3564
  'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
3100
3565
  'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
3101
- 'im', 'node_modules',
3566
+ 'browser-profiles', 'im', 'node_modules',
3102
3567
  ]
3103
3568
  const EXTRA_DEFAULT_EXCLUDE = [
3104
3569
  '*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
3105
3570
  '*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
3106
3571
  '*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
3107
3572
  '*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
3573
+ '*.env', '.env*', 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json', 'dsh-ssh-master.key',
3108
3574
  'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
3109
3575
  '*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
3576
+ 'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
3110
3577
  'node_modules', '.git', '.cache', '__pycache__', '.venv',
3111
3578
  ]
3112
3579
 
3580
+ /**
3581
+ * 安全必需项:用户自己的 config-sync-extra.json 不允许把它们去掉。
3582
+ * 与 runtime\dsh-sync-common.ps1 的 $SyncExtraMandatorySkipDirs / $SyncExtraMandatoryExcludes 同一份名单。
3583
+ *
3584
+ * 起因(本机实测):exclude / skipDirs 是「整份替换」语义,用户早先存下的 50 条旧快照会让
3585
+ * 0.6.12 新增的 browser-profiles 规则整条失效 —— 那目录里有 3,696 个文件 / 268MB,含密码库与登录态。
3586
+ * 0.6.15 在 PowerShell 侧补了这条,JS 侧(面板规则 / 待推送扫描)一直没补:
3587
+ * 于是待推送会把 browser-profiles 里几千个文件的 mtime 变动算成「待推送」,而 capture 根本不会抓它们
3588
+ * —— 面板永远消不掉,退出自动推送也每次白跑。
3589
+ */
3590
+ const EXTRA_MANDATORY_SKIP_DIRS = ['browser-profiles']
3591
+ const EXTRA_MANDATORY_EXCLUDES = ['browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State']
3592
+
3593
+ /**
3594
+ * 浏览器剖面 / 凭据库的路径段黑名单:与 PS 的 $SyncBlockedProfileSegments、webdav.mjs 的
3595
+ * BLOCKED_PROFILE_SEGMENTS 一致。按**路径段**判定,深层嵌套(User Data\Default\Login Data)也拦得住。
3596
+ */
3597
+ const BLOCKED_PROFILE_SEGMENTS = new Set([
3598
+ 'browser-profiles', 'user data', 'login data', 'login data for account',
3599
+ 'cookies', 'cookies-journal', 'web data', 'web data-journal', 'secure preferences',
3600
+ 'local state', 'history', 'history-journal', 'top sites', 'current session', 'current tabs',
3601
+ ])
3602
+
3603
+ /**
3604
+ * 把安全必需项补进 cfg(就地修改),返回补了哪些,便于面板/日志说出来。
3605
+ * 读配置要用、保存前也要用:POST 拿用户提交的名单覆盖掉之后,
3606
+ * 如果只在读的时候补,用户一保存就又把它删掉了(实测就是这样丢的)。
3607
+ */
3608
+ function topUpExtraMandatory(cfg) {
3609
+ if (!cfg || !cfg.pluginData) return { skipDirs: [], exclude: [] }
3610
+ const addedSkip = EXTRA_MANDATORY_SKIP_DIRS.filter((x) => !(cfg.pluginData.skipDirs || []).includes(x))
3611
+ const addedExcl = EXTRA_MANDATORY_EXCLUDES.filter((x) => !(cfg.pluginData.exclude || []).includes(x))
3612
+ if (addedSkip.length) cfg.pluginData.skipDirs = [...(cfg.pluginData.skipDirs || []), ...addedSkip]
3613
+ if (addedExcl.length) cfg.pluginData.exclude = [...(cfg.pluginData.exclude || []), ...addedExcl]
3614
+ return { skipDirs: addedSkip, exclude: addedExcl }
3615
+ }
3616
+
3617
+ function isBlockedProfilePath(rel) {
3618
+ const s = String(rel || '')
3619
+ if (!s) return false
3620
+ for (const seg of s.split(/[\\/]+/)) {
3621
+ if (seg && BLOCKED_PROFILE_SEGMENTS.has(seg.toLowerCase())) return true
3622
+ }
3623
+ return false
3624
+ }
3625
+
3626
+ /**
3627
+ * 「插件设置与工作流」组的源清单 —— 必须与 runtime\dsh-sync-common.ps1 的 Get-SyncSettingsMap 一致。
3628
+ * 以前 JS 只写了 4 条,capture 却抓 14 条:面板少列了 10 个文件,用户既看不到也勾不掉它们。
3629
+ * 每条 { id, rel }:rel 是相对 <DshHome> 的路径;profileRel 表示相对 profile 目录。
3630
+ */
3631
+ const SYNC_SETTINGS_SOURCES = [
3632
+ { id: 'our-free-model.json', rel: ['our-free-model', 'settings.json'] },
3633
+ { id: 'comfyui-workflows.json', rel: ['data', 'dsh-comfyui', 'workflows.json'] },
3634
+ { id: 'dsh-pet-main-config.jsonc', rel: ['dsh-pet', 'main-config.jsonc'] },
3635
+ { id: 'dsh-market-state.json', profileRel: ['.dsh-market', 'state.json'] },
3636
+ { id: 'dsh-pet-memory.json', rel: ['dsh-pet', 'memory.json'] },
3637
+ { id: 'our-free-model-picks.json', rel: ['our-free-model', 'picks.json'] },
3638
+ { id: 'dsh-im-interface-language.json', rel: ['integrations', 'dsh-im', 'interface-language.json'] },
3639
+ { id: 'dsh-qq-config.json', rel: ['integrations', 'dsh-qq', 'config.json'] },
3640
+ { id: 'dsh-qq-workspaces.json', rel: ['integrations', 'dsh-qq', 'workspaces.json'] },
3641
+ { id: 'redteam-preset-declare.json', rel: ['redteam', 'preset-declare.json'] },
3642
+ { id: 'task-board-ledger.json', rel: ['task-board', 'ledger-v2.json'] },
3643
+ { id: 'task-board-scheduler.json', rel: ['task-board', 'scheduler-v2.json'] },
3644
+ { id: 'dsh-workspaces.json', rel: ['storages', 'workspace.json'] },
3645
+ { id: 'workspace-archives.json', rel: ['dsh-session-manager', 'workspace-archives.v1.json'] },
3646
+ ]
3647
+
3648
+ function settingsSourcePath(dshHome, profileDir, entry) {
3649
+ return entry.profileRel ? join(profileDir, ...entry.profileRel) : join(dshHome, ...entry.rel)
3650
+ }
3651
+
3113
3652
  function extraConfigPath(dshHome) { return join(dshHome, EXTRA_CONFIG_NAME) }
3114
3653
 
3115
3654
  function readExtraConfig(dshHome) {
@@ -3146,6 +3685,12 @@ function readExtraConfig(dshHome) {
3146
3685
  }
3147
3686
  }
3148
3687
  } catch { /* 坏了就按默认规则走,不让面板整页读不出来 */ }
3688
+ // 安全必需项补齐(与 PowerShell 的 Get-SyncExtraConfig 同一步):用户文件可以改别的,
3689
+ // 但这些名字必须留着。补齐了要能让面板说出来(missingMandatory),不静默改用户的口径。
3690
+ const added = topUpExtraMandatory(cfg)
3691
+ if (added.skipDirs.length || added.exclude.length) {
3692
+ cfg.pluginData.missingMandatory = { skipDirs: added.skipDirs, exclude: added.exclude }
3693
+ }
3149
3694
  return cfg
3150
3695
  }
3151
3696
 
@@ -3164,7 +3709,7 @@ function saveExtraConfig(dshHome, cfg) {
3164
3709
  paths: (cfg.extra.paths || []).map((x) => ({ id: x.id, src: x.src, label: x.label || x.id })),
3165
3710
  },
3166
3711
  }
3167
- writeFileSync(p, JSON.stringify(out, null, 2) + '\n', 'utf8')
3712
+ writeFileAtomicSync(p, JSON.stringify(out, null, 2) + '\n')
3168
3713
  return p
3169
3714
  }
3170
3715
 
@@ -3274,14 +3819,11 @@ function collectScopeGroups(dshHome, appRoot) {
3274
3819
  descZh: '技能市场的安装台账与面板状态', descEn: 'Skill-market install ledger and panel state',
3275
3820
  items: ledger.map((f) => ({ id: f.id, label: f.id })) })
3276
3821
 
3277
- const settingsFiles = [
3278
- { id: 'our-free-model.json', src: join(dshHome, 'our-free-model', 'settings.json') },
3279
- { id: 'comfyui-workflows.json', src: join(dshHome, 'data', 'dsh-comfyui', 'workflows.json') },
3280
- { id: 'dsh-pet-main-config.jsonc', src: join(dshHome, 'dsh-pet', 'main-config.jsonc') },
3281
- { id: 'dsh-market-state.json', src: join(profileDir, '.dsh-market', 'state.json') },
3282
- ].filter((x) => existsSync(x.src))
3822
+ const settingsFiles = SYNC_SETTINGS_SOURCES
3823
+ .map((x) => ({ id: x.id, src: settingsSourcePath(dshHome, profileDir, x) }))
3824
+ .filter((x) => existsSync(x.src))
3283
3825
  groups.push({ id: 'settings', titleZh: '插件设置与工作流', titleEn: 'Plugin settings & workflows',
3284
- descZh: '免付费模型设置、ComfyUI 工作流库、桌宠配置、插件市场状态', descEn: 'Free-model settings, ComfyUI workflows, desktop-pet config, market state',
3826
+ descZh: '免付费模型设置、ComfyUI 工作流库、桌宠配置、插件市场状态等插件自己的小配置', descEn: 'Small per-plugin configs such as free-model settings, ComfyUI workflows, desktop-pet config and market state',
3285
3827
  items: settingsFiles.map((x) => ({ id: x.id, label: x.id })) })
3286
3828
 
3287
3829
  const mnemonDir = appRoot ? join(appRoot, 'mnemon') : ''
@@ -3359,7 +3901,14 @@ async function handleScope(req, res, config) {
3359
3901
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3360
3902
  const raw = await readBody(req)
3361
3903
  const body = raw.trim() ? JSON.parse(raw) : {}
3362
- const groupsIn = body && typeof body.groups === 'object' && body.groups ? body.groups : {}
3904
+ // 空 POST(或只发了 deleteCloud 的残缺请求)一律拒绝:groups 缺省会得到 {},
3905
+ // 下面 writeScope 就会把文件改写成「全部默认」,等于用户点一下就把所有排除项清空。
3906
+ // 合法清空必须显式传 groups:{}(面板保存时永远带全量 groups)。
3907
+ if (!body || typeof body !== 'object' || !body.groups || typeof body.groups !== 'object') {
3908
+ sendJson(res, 400, { ok: false, error: '请求体缺少 groups(清空同步范围请显式传 groups:{})' })
3909
+ return
3910
+ }
3911
+ const groupsIn = body.groups
3363
3912
  // 排除项只认「本机当前真实存在、且允许单独排除」的条目:
3364
3913
  // 拖着一堆早就不存在的 id 会让用户以后勾不回来(看不见却一直挡着同步)。
3365
3914
  const allowed = {}
@@ -3405,20 +3954,30 @@ async function handleScope(req, res, config) {
3405
3954
  */
3406
3955
  function conflictPath(dshHome) { return join(dshHome, 'sync-conflicts.json') }
3407
3956
 
3957
+ const CONFLICT_MISSING = null
3958
+
3959
+ /** 读冲突清单:没有 → null;有但坏了 → { broken:true, error }(不能再统一当「没有」)。 */
3408
3960
  function readConflicts(dshHome) {
3409
3961
  const p = conflictPath(dshHome)
3410
- if (!isFile(p)) return null
3962
+ if (!isFile(p)) return CONFLICT_MISSING
3963
+ let text = ''
3964
+ try { text = readFileSync(p, 'utf8') } catch (error) {
3965
+ return { broken: true, error: `读不到清单文件:${String((error && error.message) || error)}` }
3966
+ }
3411
3967
  try {
3412
- const obj = JSON.parse(readFileSync(p, 'utf8'))
3413
- if (!obj || !Array.isArray(obj.items)) return null
3968
+ const obj = JSON.parse(text)
3969
+ if (!obj || typeof obj !== 'object') return { broken: true, error: '清单不是 JSON 对象' }
3970
+ if (!Array.isArray(obj.items)) return { broken: true, error: '清单缺少 items 数组' }
3414
3971
  return obj
3415
- } catch { return null }
3972
+ } catch (error) {
3973
+ return { broken: true, error: `清单解析失败:${String((error && error.message) || error)}` }
3974
+ }
3416
3975
  }
3417
3976
 
3418
3977
  function writeConflicts(dshHome, obj) {
3419
3978
  const p = conflictPath(dshHome)
3420
3979
  mkdirSync(dirname(p), { recursive: true })
3421
- writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', 'utf8')
3980
+ writeFileAtomicSync(p, JSON.stringify(obj, null, 2) + '\n')
3422
3981
  return p
3423
3982
  }
3424
3983
 
@@ -3463,28 +4022,23 @@ async function handleExtraConfig(req, res, config) {
3463
4022
  if (src.extra && typeof src.extra === 'object') {
3464
4023
  if (typeof src.extra.enabled === 'boolean') cur.extra.enabled = src.extra.enabled
3465
4024
  if (Array.isArray(src.extra.paths)) {
3466
- const used = new Set()
3467
- const paths = []
3468
- for (const p of src.extra.paths) {
3469
- if (!p || typeof p.src !== 'string' || !p.src.trim()) continue
3470
- const abs = p.src.trim().replace(/\//g, '\\')
3471
- if (!/^[A-Za-z]:\\/.test(abs) && !abs.startsWith('\\\\')) continue
3472
- const base = (typeof p.label === 'string' && p.label.trim())
3473
- ? p.label.trim()
3474
- : (typeof p.id === 'string' && p.id.trim() ? p.id.trim() : basename(abs))
3475
- let id = String(base).replace(/[\\/:*?"<>|\s]+/g, '-').replace(/^-+|-+$/g, '') || 'extra'
3476
- if (!isAbsolute(abs)) continue
3477
- let n = 2
3478
- const root = id
3479
- while (used.has(id.toLowerCase())) { id = `${root}-${n++}` }
3480
- used.add(id.toLowerCase())
3481
- paths.push({ id, src: abs, label: base })
4025
+ // 校验搬进 runtime/platform.mjs(按 win32 / posix 分档),被拒的路径要整批报错:
4026
+ // 静默丢弃 = 用户的自选目录一条都没存进去,面板却显示保存成功。
4027
+ const norm = normalizeSyncExtraPaths(src.extra.paths)
4028
+ if (norm.dropped.length) {
4029
+ throw new Error(t(
4030
+ `这些路径不是绝对路径(或有盘符/分隔符问题),整批未保存:${norm.dropped.join('、')}`,
4031
+ `These paths are not absolute (or have a bad drive/separator), so nothing was saved: ${norm.dropped.join(', ')}`,
4032
+ ))
3482
4033
  }
3483
- cur.extra.paths = paths
4034
+ cur.extra.paths = norm.paths
3484
4035
  }
3485
4036
  }
4037
+ // 保存前再补一次安全必需项:上面刚用用户提交的名单整份覆盖过,
4038
+ // 不补就等于「用户点一次保存,browser-profiles 规则被删掉」(实测丢过一次)。
4039
+ const added = topUpExtraMandatory(cur)
3486
4040
  const p = saveExtraConfig(dshHome, cur)
3487
- sendJson(res, 200, { ok: true, path: p, config: readExtraConfig(dshHome) })
4041
+ sendJson(res, 200, { ok: true, path: p, mandatoryRestored: added, config: readExtraConfig(dshHome) })
3488
4042
  } catch (error) {
3489
4043
  sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
3490
4044
  }
@@ -3496,6 +4050,18 @@ async function handleConflict(req, res, config) {
3496
4050
  if (req.method === 'GET') {
3497
4051
  const obj = readConflicts(dshHome)
3498
4052
  if (!obj) { sendJson(res, 200, { ok: true, exists: false, path: conflictPath(dshHome) }); return }
4053
+ // 清单坏了也要让面板看见:否则界面显示「没有冲突」,用户以为一切正常
4054
+ if (obj.broken) {
4055
+ sendJson(res, 200, {
4056
+ ok: true,
4057
+ exists: true,
4058
+ broken: true,
4059
+ error: obj.error,
4060
+ path: conflictPath(dshHome),
4061
+ at: '', head: '', remoteHead: '', backupDir: '', items: [],
4062
+ })
4063
+ return
4064
+ }
3499
4065
  const items = obj.items.map((it) => ({
3500
4066
  path: String(it.path || ''),
3501
4067
  kind: String(it.kind || ''),
@@ -3525,6 +4091,13 @@ async function handleConflict(req, res, config) {
3525
4091
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3526
4092
  const raw = await readBody(req)
3527
4093
  const body = raw.trim() ? JSON.parse(raw) : {}
4094
+ // 重置不需要清单可读:删文件本身幂等,坏清单也得能从面板清掉(以前这里先 throw,界面无法自救)
4095
+ if (body.action === 'reset') {
4096
+ try { unlinkSync(conflictPath(dshHome)) } catch { }
4097
+ sendJson(res, 200, { ok: true, cleared: true })
4098
+ return
4099
+ }
4100
+
3528
4101
  const obj = readConflicts(dshHome)
3529
4102
  if (!obj) {
3530
4103
  throw new Error(t(
@@ -3532,16 +4105,20 @@ async function handleConflict(req, res, config) {
3532
4105
  'No pending conflict list (one is created automatically when a pull is blocked)',
3533
4106
  ))
3534
4107
  }
3535
-
3536
- if (body.action === 'reset') {
3537
- try { unlinkSync(conflictPath(dshHome)) } catch { }
3538
- sendJson(res, 200, { ok: true, cleared: true })
3539
- return
4108
+ if (obj.broken) {
4109
+ throw new Error(t(
4110
+ `冲突清单损坏(${obj.error}),已保留原文件;可以先点「重置」丢弃它,下次拉取会重新生成`,
4111
+ `The conflict list is corrupted (${obj.error}); the file was kept. Use Reset to discard it; a new one is created on the next blocked pull`,
4112
+ ))
3540
4113
  }
3541
4114
 
3542
4115
  if (body.action === 'restore') {
3543
4116
  const rel = String(body.path || '').trim()
3544
4117
  if (!rel) throw new Error(t('没有指定要还原的文件', 'No file was given to restore'))
4118
+ // 清单是引擎/脚本写的,但来源终究是仓库路径:还原时再挡一道越界,别把文件写出仓库。
4119
+ if (/^[\\/]/.test(rel) || /^[A-Za-z]:/.test(rel) || rel.split(/[\\/]/).some((seg) => seg === '..')) {
4120
+ throw new Error(t(`这个路径会写出仓库,拒绝还原:${rel}`, `This path escapes the repo and was refused: ${rel}`))
4121
+ }
3545
4122
  const side = body.side === 'cloud' ? 'cloud' : 'local'
3546
4123
  // 还原落到「当时发生冲突的那个仓库」(清单里记着),而不是此刻设置里的路径:
3547
4124
  // 用户之后改过 repoPath 也不会把副本写进另一个仓库。
@@ -3607,6 +4184,262 @@ async function handleStatus(req, res, config) {
3607
4184
  * {action:'cancel'} 取消已排队的动作
3608
4185
  * 只做只读 fetch 比对(check),真正动手一律交给退出后的 post-exit.ps1。
3609
4186
  */
4187
+ async function ensurePushAllowed(repo, settings) {
4188
+ // 推送的门禁:真仓库直接推;本机还是空的,只有「云端确实没有文件」才能推 —— 那次推送就是初始化推送。
4189
+ // 云端已有文件时拒绝,让用户先拉取(否则本机状态会被写进一份已经在用的历史里)。
4190
+ // 注意判据是「树里有文件」而不是「有分支」:远端可能只剩一个空分支,那也是空仓库,可以初始化推送。
4191
+ if (repoPhase(repo) === 'ok') return
4192
+ const useWebdav = webdavActive(settings)
4193
+ const url = useWebdav
4194
+ ? normalizeWebdav(settings).url
4195
+ : ((await git(repo, ['remote', 'get-url', 'origin'])) || settings.remoteUrl || '')
4196
+ const probe = useWebdav ? await probeWebdavRemote(settings) : await probeRemote(url, settings)
4197
+ if (!probe || probe.files === null) {
4198
+ throw new Error(t(
4199
+ useWebdav
4200
+ ? `连不上 WebDAV(${url || '未配置'}):${(probe && probe.error) || '初始化推送要先确认云端是空目录'}`
4201
+ : `连不上云端、或还没有云端仓库地址(${url || '未配置'}):初始化推送要先确认云端是空仓库`,
4202
+ useWebdav
4203
+ ? `Cannot reach WebDAV (${url || 'not set'}): ${(probe && probe.error) || 'initialize push needs to confirm the cloud folder is empty.'}`
4204
+ : `Cannot reach the cloud or no remote URL is set (${url || 'not set'}): initialize push needs to confirm the cloud repo is still empty.`,
4205
+ ))
4206
+ }
4207
+ if (probe.files > 0) {
4208
+ throw new Error(t(
4209
+ `云端仓库已经有内容(${probe.files} 个文件):本机还是空的,先「拉取」把内容拉下来,再生成推送`,
4210
+ `The cloud repo already has content (${probe.files} file(s)): run Pull to fetch it first, then push.`,
4211
+ ))
4212
+ }
4213
+ }
4214
+
4215
+ function startLivePush({ repo, dshHome, appRoot, settings }) {
4216
+ if (autoState.livePush.running) {
4217
+ return { alreadyRunning: true, livePush: { ...autoState.livePush } }
4218
+ }
4219
+ const reqLang = langStore.getStore() || 'zh'
4220
+ const initPush = repoPhase(repo) !== 'ok'
4221
+ const transport = webdavActive(settings) ? 'webdav' : 'git'
4222
+ const logsDir = join(dshHome, 'logs')
4223
+ try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
4224
+ const d = new Date()
4225
+ const pad = (n) => String(n).padStart(2, '0')
4226
+ const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
4227
+ const logFile = join(logsDir, `live-push-${stamp}.log`)
4228
+
4229
+ let cmd = ''
4230
+ let cmdArgs = []
4231
+ if (IS_WIN) {
4232
+ const syncScript = [join(pluginRoot(), 'runtime', 'sync.ps1'), join(repo, 'sync.ps1')].find((p) => isFile(p))
4233
+ if (!syncScript) throw new Error(t('找不到 sync.ps1,无法在线推送', 'sync.ps1 not found — cannot run live push'))
4234
+ const psArgs = [
4235
+ `Action = 'push'`,
4236
+ `RepoRoot = ${psQuote(repo)}`,
4237
+ `DshHome = ${psQuote(dshHome)}`,
4238
+ ...(appRoot ? [`AppRoot = ${psQuote(appRoot)}`] : []),
4239
+ `Force = $true`,
4240
+ ].join('; ')
4241
+ // PowerShell 5.1 脚本发生 ParseException 或终止错误时 $LASTEXITCODE 可能仍为 0,
4242
+ // 所以必须同时检查 $? 与 try/catch,否则崩溃会被当成 exit 0 假绿。
4243
+ const psCmd = [
4244
+ '[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)',
4245
+ '$OutputEncoding = [Console]::OutputEncoding',
4246
+ "$ErrorActionPreference = 'Stop'",
4247
+ 'try {',
4248
+ ` $a = @{ ${psArgs} }`,
4249
+ ` & ${psQuote(syncScript)} @a`,
4250
+ ' if (-not $?) { if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE } else { exit 1 } }',
4251
+ ' if ($LASTEXITCODE -and $LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
4252
+ ' exit 0',
4253
+ '} catch {',
4254
+ ' [Console]::Error.WriteLine(($_ | Out-String))',
4255
+ ' exit 1',
4256
+ '}',
4257
+ ].join('; ')
4258
+ cmd = powershellExe()
4259
+ cmdArgs = ['-NoProfile', '-NonInteractive', '-OutputFormat', 'Text', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(psCmd, 'utf16le').toString('base64')]
4260
+ } else {
4261
+ const engine = [join(pluginRoot(), 'runtime', 'sync-engine.mjs'), join(repo, 'sync-engine.mjs')].find((p) => isFile(p))
4262
+ if (!engine) throw new Error(t('找不到 sync-engine.mjs,无法在线推送', 'sync-engine.mjs not found — cannot run live push'))
4263
+ cmd = hostNodeExe(appRoot) || process.execPath
4264
+ cmdArgs = [engine, 'push', '-RepoRoot', repo, '-DshHome', dshHome, ...(appRoot ? ['-AppRoot', appRoot] : [])]
4265
+ }
4266
+
4267
+ autoState.livePush = {
4268
+ running: true,
4269
+ startedAt: Date.now(),
4270
+ finishedAt: 0,
4271
+ ok: null,
4272
+ phase: 'starting',
4273
+ message: initPush
4274
+ ? t('正在后台初始化推送(不关闭 DSH)…', 'Initializing push in background (DSH stays open)…')
4275
+ : t('正在后台抓取并推送(不关闭 DSH)…', 'Capturing and pushing in background (DSH stays open)…'),
4276
+ detail: '',
4277
+ recent: [],
4278
+ log: logFile,
4279
+ initPush,
4280
+ transport,
4281
+ }
4282
+
4283
+ const tail = []
4284
+ let sawFatalOutput = false
4285
+ // CLIXML 清洗细节(为什么这样判、踩过什么坑)见 runtime/live-log.mjs 的文件头。
4286
+ const extractUsefulText = (raw, fromStderr) => extractLiveLogText(raw, fromStderr)
4287
+
4288
+ // 日志上限:同步流程会按文件刷进度,病态情况下能刷到几十 MB。
4289
+ // 超过上限后只更新面板进度、不再写盘(面板照旧能看最近几行)。
4290
+ const LOG_MAX_BYTES = 8 * 1024 * 1024
4291
+ let logBytes = 0
4292
+ try { if (existsSync(logFile)) logBytes = statSync(logFile).size } catch { }
4293
+ let logTruncated = false
4294
+ const recentWritten = []
4295
+
4296
+ const appendLog = (chunk, fromStderr = false) => {
4297
+ const text = extractUsefulText(chunk, fromStderr)
4298
+ if (!text.trim()) return
4299
+ // Write-Host 出来的同一行会同时出现在 stdout 与 stderr(CLIXML),
4300
+ // 清洗后两条通道都能读出正文 → 日志里同一句话连写两遍(实测「另一台机器执行…」重复)。
4301
+ // 用最近 24 行做去重窗口,跨块也生效。
4302
+ const keep = []
4303
+ for (const rawLine of text.split(/\r?\n/)) {
4304
+ if (!rawLine.trim()) continue
4305
+ const key = rawLine.trim()
4306
+ if (recentWritten.includes(key)) continue
4307
+ recentWritten.push(key)
4308
+ if (recentWritten.length > 24) recentWritten.shift()
4309
+ keep.push(rawLine)
4310
+ }
4311
+ if (!keep.length) return
4312
+ const outText = keep.join('\n')
4313
+ const bytes = Buffer.byteLength(outText)
4314
+ if (logBytes < LOG_MAX_BYTES) {
4315
+ try { writeFileSync(logFile, `${outText}\n`, { flag: 'a' }); logBytes += bytes } catch { }
4316
+ if (logBytes >= LOG_MAX_BYTES && !logTruncated) {
4317
+ logTruncated = true
4318
+ try { writeFileSync(logFile, `\n[日志已截断:本次输出超过 ${Math.round(LOG_MAX_BYTES / 1048576)} MB,后续只更新面板进度]\n`, { flag: 'a' }) } catch { }
4319
+ }
4320
+ }
4321
+ if (/ParserError|FullyQualifiedErrorId|CommandNotFoundException|\+\s+CategoryInfo\s*:/i.test(outText)) sawFatalOutput = true
4322
+ langStore.run(reqLang, () => {
4323
+ for (const rawLine of outText.split(/\r?\n/)) {
4324
+ const line = rawLine.trim()
4325
+ if (!line) continue
4326
+ tail.push(line)
4327
+ if (tail.length > 50) tail.shift()
4328
+ autoState.livePush.detail = line
4329
+ autoState.livePush.recent = tail.slice(-5)
4330
+ if (/==\s*初始化仓库/.test(line)) {
4331
+ autoState.livePush.phase = 'init'
4332
+ autoState.livePush.message = t('正在初始化仓库骨架…', 'Initializing repo skeleton…')
4333
+ } else if (/==\s*DSH 配置同步\s*\/\s*capture|==\s*抓取|==\s*归档|==\s*工作区|\bcapture\b/i.test(line)) {
4334
+ autoState.livePush.phase = 'capture'
4335
+ const convOn = scopeGroupEnabled(readScope(dshHome), 'conversations')
4336
+ autoState.livePush.message = convOn
4337
+ ? t('正在抓取本机配置与会话…', 'Capturing local config and sessions…')
4338
+ : t('正在抓取本机配置…', 'Capturing local config…')
4339
+ } else if (/==\s*提交/.test(line)) {
4340
+ autoState.livePush.phase = 'commit'
4341
+ autoState.livePush.message = t('正在提交本机变更…', 'Committing local changes…')
4342
+ } else if (/==\s*上传到 WebDAV|上传扫描:|上传进度:|WebDAV 上传|==\s*推送/.test(line)) {
4343
+ autoState.livePush.phase = 'upload'
4344
+ if (/上传进度:/.test(line)) {
4345
+ autoState.livePush.message = line
4346
+ } else {
4347
+ autoState.livePush.message = t('正在上传到云端…', 'Uploading to cloud…')
4348
+ }
4349
+ }
4350
+ }
4351
+ })
4352
+ }
4353
+
4354
+ const finish = (ok, errText, opts = {}) => langStore.run(reqLang, async () => {
4355
+ clearWebdavProbeCache()
4356
+ if (ok) {
4357
+ try {
4358
+ if (webdavActive(settings)) {
4359
+ const wp = await probeWebdavRemote(settings)
4360
+ if (wp && wp.files !== null) {
4361
+ autoState.drift = { ahead: 0, behind: 0, transport: 'webdav', files: wp.files, at: Date.now() }
4362
+ autoState.lastCheckAt = Date.now()
4363
+ autoState.lastCheckError = ''
4364
+ }
4365
+ } else {
4366
+ const d2 = await checkDrift(repo)
4367
+ if (d2) {
4368
+ autoState.drift = d2
4369
+ autoState.lastCheckAt = Date.now()
4370
+ autoState.lastCheckError = ''
4371
+ }
4372
+ }
4373
+ } catch { }
4374
+ }
4375
+ autoState.livePush = {
4376
+ ...autoState.livePush,
4377
+ running: false,
4378
+ finishedAt: Date.now(),
4379
+ ok,
4380
+ phase: ok ? 'done' : 'error',
4381
+ message: opts.skipped
4382
+ ? t('跳过:另一个同步动作正在进行(不是故障)', 'Skipped: another sync is already running (not a failure)')
4383
+ : ok
4384
+ ? (initPush
4385
+ ? t('初始化推送完成(未关闭 DSH)', 'Initialize push completed (DSH stayed open)')
4386
+ : t('推送完成(未关闭 DSH)', 'Push completed (DSH stayed open)'))
4387
+ : (errText || t('推送失败,详见日志', 'Push failed — see log')),
4388
+ skipped: Boolean(opts.skipped),
4389
+ }
4390
+ })
4391
+
4392
+ const child = spawn(cmd, cmdArgs, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
4393
+ child.stdout.on('data', (c) => appendLog(c, false))
4394
+ child.stderr.on('data', (c) => appendLog(c, true))
4395
+ child.once('error', (e) => {
4396
+ const msg = String((e && e.message) || e)
4397
+ appendLog(`\n[error] ${msg}\n`)
4398
+ finish(false, msg)
4399
+ })
4400
+ child.once('exit', async (code) => {
4401
+ // 3 是 capture/apply 的「另一个同步动作正在进行」:什么都没做,但也不是故障。
4402
+ // 按失败处理会让面板变红,还会从 tail 里随便挑一行当原因(实测会挑到「接着执行(二选一)」)。
4403
+ if (code === 3) { finish(true, null, { skipped: true }); return }
4404
+ if (code !== 0 || sawFatalOutput) {
4405
+ const errLine = [...tail].reverse().find((l) => /\[X\]|失败|error|fatal:|ParserError|UnexpectedToken/i.test(l))
4406
+ || tail[tail.length - 1]
4407
+ || `exit ${code}`
4408
+ finish(false, errLine)
4409
+ return
4410
+ }
4411
+ if (!IS_WIN && !webdavActive(settings)) {
4412
+ try {
4413
+ await git(repo, ['add', '-A'])
4414
+ const st = await git(repo, ['status', '--porcelain'])
4415
+ if (st && st.trim()) {
4416
+ await git(repo, ['commit', '-m', `sync(live): ${stamp}`])
4417
+ }
4418
+ await git(repo, ['push'])
4419
+ } catch (e) {
4420
+ const msg = String((e && e.message) || e)
4421
+ appendLog(`\n[git push error] ${msg}\n`)
4422
+ finish(false, msg)
4423
+ return
4424
+ }
4425
+ }
4426
+ if (!IS_WIN) {
4427
+ try {
4428
+ const head = (await git(repo, ['log', '-1', '--format=%h'])) || ''
4429
+ writeFileAtomicSync(join(dshHome, STATE_NAME), JSON.stringify({
4430
+ lastSyncAt: new Date().toISOString(),
4431
+ mode: 'push',
4432
+ repo,
4433
+ head: head.trim(),
4434
+ }, null, 2) + '\n')
4435
+ } catch { }
4436
+ }
4437
+ finish(true, '')
4438
+ })
4439
+
4440
+ return { alreadyRunning: false, livePush: { ...autoState.livePush } }
4441
+ }
4442
+
3610
4443
  async function handleAuto(req, res, config) {
3611
4444
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
3612
4445
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
@@ -3689,9 +4522,10 @@ async function handleAuto(req, res, config) {
3689
4522
  const extraArgs = ['-BackupDir', snap.dir]
3690
4523
  if (snap.kind !== 'profile') extraArgs.push('-SnapshotKind', snap.kind)
3691
4524
  if (snap.kind === 'plugin') extraArgs.push('-PluginDir', PLUGIN_ROOT)
4525
+ const closeNow = body.closeNow !== false
3692
4526
  const started = await spawnWatcher({
3693
4527
  mode: 'restore', repo, appRoot, dshHome, restart,
3694
- extraArgs,
4528
+ extraArgs, closeRequested: closeNow,
3695
4529
  })
3696
4530
  if (!started.ok) throw new Error(started.error)
3697
4531
  autoState.pending = { mode: 'restore', at: Date.now(), restart, watcherPid: started.pid, closeRequested: false, backupDir: snap.dir, snapshotKind: snap.kind }
@@ -3704,37 +4538,20 @@ async function handleAuto(req, res, config) {
3704
4538
  return
3705
4539
  }
3706
4540
 
4541
+ if (action === 'push-live') {
4542
+ await ensurePushAllowed(repo, settings)
4543
+ const started = startLivePush({ repo, dshHome, appRoot, settings })
4544
+ sendJson(res, 200, { ok: true, action, ...started })
4545
+ return
4546
+ }
4547
+
3707
4548
  if (action === 'pull-now' || action === 'push-now') {
3708
4549
  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
- }
4550
+ if (mode === 'push' && repoPhase(repo) !== 'ok') await ensurePushAllowed(repo, settings)
3735
4551
  // 拉取/推送做完都把客户端拉回来(用户要求"完成后自动启动 dsh"),仍受 autoRestart 开关约束
3736
4552
  const restart = body.restart !== false && settings.autoRestart !== false
3737
- const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart })
4553
+ const closeNow = body.closeNow !== false
4554
+ const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart, closeRequested: closeNow })
3738
4555
  if (!started.ok) throw new Error(started.error)
3739
4556
  autoState.pending = { mode, at: Date.now(), restart, watcherPid: started.pid, closeRequested: false }
3740
4557
  // 用户明确要求"现在就同步":排队后请求客户端退出(不带 /F,走正常关闭,配置能存下来)
@@ -3747,7 +4564,7 @@ async function handleAuto(req, res, config) {
3747
4564
  return
3748
4565
  }
3749
4566
 
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'))
4567
+ 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
4568
  } catch (error) {
3752
4569
  sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
3753
4570
  }
@@ -3809,7 +4626,8 @@ function scheduleAutoStart(config) {
3809
4626
  ),
3810
4627
  )
3811
4628
  if (yes) {
3812
- const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart: settings.autoRestart })
4629
+ // 用户点了确认,插件随后自己关客户端 → 允许守护进程在窗口消失后清残留
4630
+ const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart: settings.autoRestart, closeRequested: true })
3813
4631
  if (started.ok) {
3814
4632
  autoState.pending = { mode: 'pull', at: Date.now(), restart: settings.autoRestart, watcherPid: started.pid, closeRequested: true }
3815
4633
  closeDsh()
@@ -4293,15 +5111,39 @@ async function handleWebdav(req, res, config) {
4293
5111
  return
4294
5112
  }
4295
5113
 
4296
- // 上传/下载都要动本机文件:没有仓库目录就没意义,先明确报错
5114
+ // 上传/下载都要动本机文件,但两者的前提不同:
5115
+ // upload 必须有内容(空目录没东西可传)
5116
+ // download 恰恰要把空目录填满 —— 新机器首次拉取就是这个场景,不能拒
4297
5117
  const repo = resolveRepo(config?.repoPath, dshHome).repo
4298
- if (!repo || !isDir(repo)) {
4299
- sendJson(res, 400, { ok: false, error: '本机仓库目录不存在(先在「本机仓库」卡里设置路径)' })
5118
+ if (!repo) {
5119
+ sendJson(res, 400, { ok: false, error: '还没有设置本机仓库目录(先在「本机仓库」卡里设置路径)' })
4300
5120
  return
4301
5121
  }
4302
- if (!isRepoDir(repo) && !isDir(join(repo, 'machines'))) {
4303
- sendJson(res, 400, { ok: false, error: `这个目录不像同步仓库:${repo}` })
4304
- return
5122
+ const repoLooksReal = isRepoDir(repo) || isDir(join(repo, 'machines'))
5123
+ if (action === 'upload') {
5124
+ if (!isDir(repo)) {
5125
+ sendJson(res, 400, { ok: false, error: '本机仓库目录不存在(先在「本机仓库」卡里设置路径)' })
5126
+ return
5127
+ }
5128
+ if (!repoLooksReal) {
5129
+ sendJson(res, 400, { ok: false, error: `这个目录不像同步仓库:${repo}` })
5130
+ return
5131
+ }
5132
+ }
5133
+ if (action === 'download') {
5134
+ // 不存在就建;空目录放行;非空又不像仓库才拒(防止把配置铺到别人的目录里)
5135
+ if (!isDir(repo)) {
5136
+ try { mkdirSync(repo, { recursive: true }) } catch (e) {
5137
+ sendJson(res, 400, { ok: false, error: `建不了本机仓库目录:${String((e && e.message) || e)}` })
5138
+ return
5139
+ }
5140
+ }
5141
+ let entries = []
5142
+ try { entries = readdirSync(repo).filter((n) => !n.startsWith('.')) } catch { entries = [] }
5143
+ if (entries.length > 0 && !repoLooksReal) {
5144
+ sendJson(res, 400, { ok: false, error: `这个目录不像同步仓库:${repo}` })
5145
+ return
5146
+ }
4305
5147
  }
4306
5148
 
4307
5149
  if (action === 'upload') {
@@ -4439,12 +5281,8 @@ async function handleRoots(req, res, config) {
4439
5281
  confirmed: [],
4440
5282
  updatedAt: new Date().toISOString(),
4441
5283
  }
4442
- const rawCustom = input.custom && typeof input.custom === 'object' ? input.custom : (prev.custom || {})
4443
- for (const [k, v] of Object.entries(rawCustom)) {
4444
- const key = String(k || '').trim()
4445
- const val = String(v == null ? '' : v).trim()
4446
- if (key && val) next.custom[key] = val
4447
- }
5284
+ const rawCustom = Object.prototype.hasOwnProperty.call(input, 'custom') ? input.custom : (prev.custom || {})
5285
+ next.custom = normalizeCustomRoots(rawCustom)
4448
5286
  // 校验:三个根都不能空、必须是绝对路径。目录不存在只提示不拒 —— 新机器上目标目录常常还没建。
4449
5287
  const warns = []
4450
5288
  for (const key of ['appRoot', 'dshHome', 'workspaceHome']) {
@@ -4472,7 +5310,7 @@ async function handleRoots(req, res, config) {
4472
5310
  next.confirmed = [...confirmed]
4473
5311
 
4474
5312
  mkdirSync(dirname(rootsPathOf(dshHome)), { recursive: true })
4475
- writeFileSync(rootsPathOf(dshHome), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
5313
+ writeFileAtomicSync(rootsPathOf(dshHome), `${JSON.stringify(next, null, 2)}\n`)
4476
5314
  // 根都确认了,待确认清单就没意义了:清掉,下次拉取不再拦
4477
5315
  try { if (existsSync(pendingPathOf(dshHome))) unlinkSync(pendingPathOf(dshHome)) } catch { }
4478
5316
 
@@ -4490,6 +5328,67 @@ async function handleRoots(req, res, config) {
4490
5328
  }
4491
5329
  }
4492
5330
 
5331
+ /**
5332
+ * 归一化「自选目录」。三种形状都认:
5333
+ * { 名字: '绝对路径' } —— 真实文件 / 面板发送的形状
5334
+ * [ { name|key: '名字', path: '绝对路径' } ] —— 数组形状(手工编辑或旧文件)
5335
+ * [ '绝对路径', ... ] —— 纯路径数组,名字取目录名
5336
+ * 返回对象映射;形状完全无法识别时抛一条人能看懂的错。
5337
+ */
5338
+ function normalizeCustomRoots(raw) {
5339
+ const out = {}
5340
+ const leafKey = (v) => String(v).replace(/[\\/]+$/, '').split(/[\\/]/).filter(Boolean).pop() || ''
5341
+ const put = (name, value) => {
5342
+ const key = String(name || '').trim() || leafKey(value)
5343
+ const val = String(value == null ? '' : value).trim()
5344
+ if (key && val) out[key] = val
5345
+ }
5346
+ if (Array.isArray(raw)) {
5347
+ raw.forEach((item, i) => {
5348
+ if (item == null) return
5349
+ if (typeof item === 'string') { put('', item); return }
5350
+ if (typeof item === 'object') {
5351
+ const path = item.path ?? item.value ?? item.dir ?? ''
5352
+ const name = item.name ?? item.key ?? item.id ?? ''
5353
+ if (!String(path || '').trim()) {
5354
+ throw new Error(t(
5355
+ `自选目录第 ${i + 1} 项没有 path 字段(应为 { name, path } 或纯路径字符串)`,
5356
+ `Custom folder entry #${i + 1} has no path field (expected { name, path } or a plain path string)`,
5357
+ ))
5358
+ }
5359
+ put(name, path)
5360
+ return
5361
+ }
5362
+ throw new Error(t(
5363
+ `自选目录第 ${i + 1} 项看不懂:${typeof item}(应为 { name, path } 或纯路径字符串)`,
5364
+ `Custom folder entry #${i + 1} is not understood: ${typeof item} (expected { name, path } or a plain path string)`,
5365
+ ))
5366
+ })
5367
+ return out
5368
+ }
5369
+ if (raw && typeof raw === 'object') {
5370
+ for (const [k, v] of Object.entries(raw)) {
5371
+ if (v && typeof v === 'object') {
5372
+ const nested = v.path ?? v.value ?? v.dir ?? ''
5373
+ if (!String(nested || '').trim()) {
5374
+ throw new Error(t(
5375
+ `自选目录「${k}」没有 path 字段(应为 { name, path } 或纯路径字符串)`,
5376
+ `Custom folder "${k}" has no path field (expected { name, path } or a plain path string)`,
5377
+ ))
5378
+ }
5379
+ put(k, nested)
5380
+ continue
5381
+ }
5382
+ put(k, v)
5383
+ }
5384
+ return out
5385
+ }
5386
+ if (raw == null || raw === '') return out
5387
+ throw new Error(t(
5388
+ `自选目录格式不对:应为 { 名字: 路径 } 或数组`,
5389
+ `Custom folders must be an object map or an array`,
5390
+ ))
5391
+ }
4493
5392
  /**
4494
5393
  * 问题反馈:落成仓库里的 feedback\<时间戳>-<id>.json,再 git add/commit/push 到云端。
4495
5394
  * 为什么用文件而不是 Issue:不依赖 API 令牌,另一台机器拉取后同样能在面板里看到;
@@ -4499,7 +5398,16 @@ async function handleRoots(req, res, config) {
4499
5398
  // 面板里提交 → 直接建 issue(label=feedback,正文附环境块);列表读 issue(含 open/closed);
4500
5399
  // 点「已解决」就 PATCH 成 closed。网络不通时先进本机待发队列,下次点「补发」再建 issue。
4501
5400
 
4502
- const GH_DEFAULT_REPO = 'huanyu-a/dsh-profile-config-sync'
5401
+ const GH_DEFAULT_REPO = (() => {
5402
+ try {
5403
+ const pkg = JSON.parse(readFileSync(join(PLUGIN_DIR, 'package.json'), 'utf8'))
5404
+ const raw = String((pkg && pkg.repository && (pkg.repository.url || pkg.repository)) || '')
5405
+ const m = raw.match(/github\.com[/:]([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?(?:[#?/]|$)/i)
5406
+ if (m && m[1]) return m[1]
5407
+ } catch { }
5408
+ return 'huanyu-a/dsh-profile-config-sync'
5409
+ })()
5410
+ const LEGACY_UPSTREAM_REPOS = new Set(['QcWyGm/dsh-config-sync-plugin', 'QcWyGm/dsh-config-sync'])
4503
5411
  const GH_FEEDBACK_LABEL = 'feedback'
4504
5412
 
4505
5413
  /** 当前插件版本(读自己的 package.json;读不到就空串,不抛)。 */
@@ -4513,11 +5421,18 @@ function pluginVersion() {
4513
5421
  function ghPathOf(dshHome) { return join(dshHome, 'config-sync-gh.json') }
4514
5422
  function outboxPathOf(dshHome) { return join(dshHome, 'config-sync-feedback-outbox.json') }
4515
5423
 
5424
+ function normalizeGhRepo(raw) {
5425
+ const s = String(raw || '').trim()
5426
+ if (!s || LEGACY_UPSTREAM_REPOS.has(s)) return GH_DEFAULT_REPO
5427
+ return s
5428
+ }
5429
+
4516
5430
  function readGh(dshHome) {
4517
5431
  const j = readJson(ghPathOf(dshHome)) || {}
4518
5432
  return {
4519
5433
  token: String(j.token || ''),
4520
- repo: String(j.repo || GH_DEFAULT_REPO),
5434
+ tokenEnv: String(j.tokenEnv || '').trim(),
5435
+ repo: normalizeGhRepo(j.repo),
4521
5436
  login: String(j.login || ''),
4522
5437
  updatedAt: String(j.updatedAt || ''),
4523
5438
  }
@@ -4527,11 +5442,15 @@ function writeGh(dshHome, o) {
4527
5442
  const f = ghPathOf(dshHome)
4528
5443
  try { mkdirSync(dirname(f), { recursive: true }) } catch { }
4529
5444
  const prev = readGh(dshHome)
5445
+ const hasToken = Object.prototype.hasOwnProperty.call(o || {}, 'token')
5446
+ const hasTokenEnv = Object.prototype.hasOwnProperty.call(o || {}, 'tokenEnv')
5447
+ const hasLogin = Object.prototype.hasOwnProperty.call(o || {}, 'login')
4530
5448
  const body = {
4531
- token: String(o.token || ''),
4532
- repo: String(o.repo || GH_DEFAULT_REPO),
5449
+ token: hasToken ? String(o.token || '') : prev.token,
5450
+ tokenEnv: hasTokenEnv ? String(o.tokenEnv || '').trim() : prev.tokenEnv,
5451
+ repo: normalizeGhRepo((o && o.repo) || prev.repo),
4533
5452
  // 令牌没换就沿用之前认出来的账号,免得每轮都调 /user
4534
- login: String(o.login || prev.login || ''),
5453
+ login: hasLogin ? String(o.login || '') : prev.login,
4535
5454
  updatedAt: new Date().toISOString(),
4536
5455
  }
4537
5456
  writeFileSync(f, `${JSON.stringify(body, null, 2)}\n`, 'utf8')
@@ -4550,38 +5469,86 @@ function writeOutbox(dshHome, items) {
4550
5469
  return f
4551
5470
  }
4552
5471
 
4553
- /** 从本机 git 凭据里取一次 GitHub 令牌:用户平时 push 过,这里就不用再填。 */
4554
- function tokenFromGitCredential() {
5472
+ /** 从本机 git 凭据里取 GitHub 令牌与用户名:用户平时 push 过,这里就不用再填。 */
5473
+ function credFromGitCredential() {
4555
5474
  return new Promise((resolve) => {
4556
5475
  let p = null
4557
5476
  try {
4558
5477
  p = spawn(resolveGitExe(), ['credential', 'fill'], { windowsHide: true })
4559
- } catch { resolve(''); return }
5478
+ } catch { resolve({ token: '', username: '' }); return }
4560
5479
  let out = ''
4561
- const timer = setTimeout(() => { try { p.kill() } catch { } resolve('') }, 8000)
5480
+ const timer = setTimeout(() => { try { p.kill() } catch { } resolve({ token: '', username: '' }) }, 8000)
4562
5481
  p.stdout.on('data', (d) => { out += String(d) })
4563
- p.on('error', () => { clearTimeout(timer); resolve('') })
5482
+ p.on('error', () => { clearTimeout(timer); resolve({ token: '', username: '' }) })
4564
5483
  p.on('close', () => {
4565
5484
  clearTimeout(timer)
4566
- const m = out.match(/password=([^\r\n]+)/)
4567
- resolve(m ? m[1].trim() : '')
5485
+ const pm = out.match(/password=([^\r\n]+)/)
5486
+ const um = out.match(/username=([^\r\n]+)/)
5487
+ resolve({ token: pm ? pm[1].trim() : '', username: um ? um[1].trim() : '' })
4568
5488
  })
4569
5489
  try { p.stdin.write('protocol=https\nhost=github.com\n\n'); p.stdin.end() } catch { }
4570
5490
  })
4571
5491
  }
4572
5492
 
4573
- /** 有存下来的令牌就用它,没有就向 git 凭据要一次并落盘(本机私有、不进仓库)。 */
5493
+ function tokenFromGitCredential() {
5494
+ return credFromGitCredential().then((c) => c.token)
5495
+ }
5496
+
5497
+ /** 从本机 GitHub CLI(gh auth token)读取登录令牌,作为 git credential 的补充。 */
5498
+ function tokenFromGhCli() {
5499
+ return new Promise((resolve) => {
5500
+ let p = null
5501
+ try {
5502
+ p = spawn(IS_WIN ? 'gh.exe' : 'gh', ['auth', 'token'], { windowsHide: true })
5503
+ } catch { resolve(''); return }
5504
+ let out = ''
5505
+ const timer = setTimeout(() => { try { p.kill() } catch { } resolve('') }, 4000)
5506
+ p.stdout.on('data', (d) => { out += String(d) })
5507
+ p.on('error', () => { clearTimeout(timer); resolve('') })
5508
+ p.on('close', (code) => {
5509
+ clearTimeout(timer)
5510
+ resolve(code === 0 ? String(out || '').trim() : '')
5511
+ })
5512
+ })
5513
+ }
5514
+
5515
+ /**
5516
+ * 令牌读取顺序(绝不把环境变量或凭据助手的令牌写进同步仓库):
5517
+ * 1. config-sync-gh.json 里显式绑定的环境变量名 tokenEnv(实时读取,不落盘明文);
5518
+ * 2. config-sync-gh.json 里保存的令牌(若写成 $VAR / ${VAR} / env:VAR 也按环境变量实时解析);
5519
+ * 3. 本机常见环境变量(DSH_CONFIG_SYNC_GH_TOKEN / GITHUB_TOKEN / GH_TOKEN,不落盘);
5520
+ * 4. 本机 git 凭据(git credential fill,仅放内存使用,不落盘);
5521
+ * 5. 本机 GitHub CLI(gh auth token,仅放内存使用,不落盘)。
5522
+ */
4574
5523
  async function ghToken(config, dshHome) {
4575
5524
  const g = readGh(dshHome)
4576
- if (g.token) return g
4577
- const auto = await tokenFromGitCredential()
4578
- if (!auto) return g
4579
- writeGh(dshHome, { ...g, token: auto })
4580
- return { ...g, token: auto }
5525
+ if (g.tokenEnv) {
5526
+ return { ...g, token: getEnvValue(g.tokenEnv), source: 'env', envName: g.tokenEnv, tokenSaved: false, credLogin: '' }
5527
+ }
5528
+ if (g.token) {
5529
+ const refEnv = parseEnvTokenRef(g.token)
5530
+ if (refEnv) {
5531
+ return { ...g, token: getEnvValue(refEnv), source: 'env', envName: refEnv, tokenSaved: false, credLogin: '' }
5532
+ }
5533
+ return { ...g, source: 'file', envName: '', tokenSaved: true, credLogin: '' }
5534
+ }
5535
+ for (const name of GH_TOKEN_ENV_CANDIDATES) {
5536
+ const v = getEnvValue(name)
5537
+ if (v) return { ...g, token: v, source: 'env', envName: name, tokenSaved: false, credLogin: '' }
5538
+ }
5539
+ const cred = await credFromGitCredential()
5540
+ if (cred.token) {
5541
+ return { ...g, token: cred.token, source: 'git-credential', envName: '', tokenSaved: false, credLogin: cred.username || '' }
5542
+ }
5543
+ const ghCliTok = await tokenFromGhCli()
5544
+ if (ghCliTok) {
5545
+ return { ...g, token: ghCliTok, source: 'gh-cli', envName: '', tokenSaved: false, credLogin: cred.username || '' }
5546
+ }
5547
+ return { ...g, source: 'none', envName: '', tokenSaved: false, credLogin: cred.username || '' }
4581
5548
  }
4582
5549
 
4583
5550
  async function ghApi(pathname, options = {}) {
4584
- const { method = 'GET', token, body } = options
5551
+ const { method = 'GET', token, body, timeoutMs = 15000 } = options
4585
5552
  const url = pathname.startsWith('http') ? pathname : `https://api.github.com${pathname}`
4586
5553
  const headers = {
4587
5554
  Accept: 'application/vnd.github+json',
@@ -4595,11 +5562,28 @@ async function ghApi(pathname, options = {}) {
4595
5562
  headers['Content-Type'] = 'application/json; charset=utf-8'
4596
5563
  init.body = JSON.stringify(body)
4597
5564
  }
4598
- const res = await fetch(url, init)
4599
- const raw = await res.text()
4600
- let json = null
4601
- try { json = raw ? JSON.parse(raw) : null } catch { json = null }
4602
- return { ok: res.ok, status: res.status, json, text: raw }
5565
+ let timer = null
5566
+ try {
5567
+ if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
5568
+ init.signal = AbortSignal.timeout(timeoutMs)
5569
+ } else if (typeof AbortController !== 'undefined') {
5570
+ const ac = new AbortController()
5571
+ init.signal = ac.signal
5572
+ timer = setTimeout(() => ac.abort(), timeoutMs)
5573
+ }
5574
+ const res = await fetch(url, init)
5575
+ const raw = await res.text()
5576
+ let json = null
5577
+ try { json = raw ? JSON.parse(raw) : null } catch { json = null }
5578
+ return { ok: res.ok, status: res.status, networkError: false, json, text: raw }
5579
+ } catch (err) {
5580
+ const causeMsg = err && err.cause && err.cause.message ? String(err.cause.message) : ''
5581
+ const baseMsg = String((err && err.message) || err || 'fetch failed')
5582
+ const msg = causeMsg && !baseMsg.includes(causeMsg) ? `${baseMsg}: ${causeMsg}` : baseMsg
5583
+ return { ok: false, status: 0, networkError: true, json: { message: msg }, text: msg }
5584
+ } finally {
5585
+ if (timer) clearTimeout(timer)
5586
+ }
4603
5587
  }
4604
5588
 
4605
5589
  function issueToItem(it) {
@@ -4651,16 +5635,22 @@ function ownerOf(repo) {
4651
5635
  return String(repo || '').split('/')[0] || ''
4652
5636
  }
4653
5637
 
4654
- /** 令牌属于谁(GET /user)。结果缓存在 gh.json 里,不每轮都问。 */
5638
+ const ghIdentityCache = new Map()
5639
+ /** 令牌属于谁(GET /user)。按令牌哈希放内存缓存,不依赖落盘的旧账号。 */
4655
5640
  async function ghIdentity(token, dshHome, known) {
4656
- if (known) return known
5641
+ if (!token) return ''
5642
+ const key = createHash('sha256').update(String(token)).digest('hex')
5643
+ if (ghIdentityCache.has(key)) return ghIdentityCache.get(key) || ''
4657
5644
  const r = await ghApi('/user', { token })
4658
5645
  const login = r.ok && r.json ? String(r.json.login || '') : ''
4659
5646
  if (login) {
4660
- const g = readGh(dshHome)
4661
- writeGh(dshHome, { ...g, login })
5647
+ ghIdentityCache.set(key, login)
5648
+ if (isFile(ghPathOf(dshHome)) && known !== login) {
5649
+ try { writeGh(dshHome, { login }) } catch { }
5650
+ }
5651
+ return login
4662
5652
  }
4663
- return login
5653
+ return String(known || '')
4664
5654
  }
4665
5655
 
4666
5656
  /**
@@ -4927,13 +5917,16 @@ async function handleFeedback(req, res, config) {
4927
5917
 
4928
5918
  if (req.method === 'GET') {
4929
5919
  try {
5920
+ if (url.searchParams.get('refresh') === '1') clearWinEnvCache()
4930
5921
  const g = await ghToken(config, dshHome)
4931
5922
  const outbox = readOutbox(dshHome)
4932
5923
  const owner = ownerOf(g.repo)
4933
- const login = g.token ? await ghIdentity(g.token, dshHome, g.login) : ''
5924
+ const login = g.token ? await ghIdentity(g.token, dshHome, g.login || g.credLogin || '') : ''
5925
+ const envCandidates = GH_TOKEN_ENV_CANDIDATES.filter((n) => Boolean(getEnvValue(n)))
4934
5926
  const base = {
4935
5927
  ok: true,
4936
5928
  repo: g.repo,
5929
+ defaultRepo: GH_DEFAULT_REPO,
4937
5930
  label: GH_FEEDBACK_LABEL,
4938
5931
  owner,
4939
5932
  login,
@@ -4941,13 +5934,18 @@ async function handleFeedback(req, res, config) {
4941
5934
  canClose: !!(login && owner && login.toLowerCase() === owner.toLowerCase()),
4942
5935
  connected: false,
4943
5936
  readAnon: false,
4944
- tokenSaved: !!g.token,
5937
+ tokenPresent: Boolean(g.token),
5938
+ tokenSaved: Boolean(g.tokenSaved),
5939
+ tokenSource: g.source || (g.token ? 'file' : 'none'),
5940
+ tokenEnv: g.envName || g.tokenEnv || '',
5941
+ envCandidates,
4945
5942
  items: [],
5943
+ counts: { open: 0, closed: 0, total: 0 },
4946
5944
  outbox: outbox.map((x) => ({ title: String(x.title || ''), createdAt: String(x.createdAt || '') })),
4947
5945
  version: pluginVersion(),
4948
5946
  ghFile: ghPathOf(dshHome),
4949
5947
  }
4950
- // 读:有令牌先带令牌(自己的账号、限额 5000/小时),失败或没令牌就退回匿名(公开仓库 60 次/小时)
5948
+ // 读:有令牌先带令牌(自己的账号、限额 5000/小时);网络本身不通时不重复打匿名请求,仅 HTTP 401/403 才退回匿名
4951
5949
  const attempts = g.token ? [g.token, ''] : ['']
4952
5950
  let lastError = ''
4953
5951
  for (const tok of attempts) {
@@ -4965,12 +5963,15 @@ async function handleFeedback(req, res, config) {
4965
5963
  items,
4966
5964
  counts,
4967
5965
  note: !tok
4968
- ? t('匿名读取(公开仓库,不限令牌;上限 60 次/小时),提交和关单需要令牌', 'Anonymous read (public repo, no token needed; 60 requests/hour). Submitting and closing need a token.')
5966
+ ? (g.token
5967
+ ? t(`当前令牌认证未通过(${lastError || '401'}),已退回匿名读取;请点「换令牌」或重新登录 GitHub`, `Token auth failed (${lastError || '401'}); fell back to anonymous read. Re-auth or update token.`)
5968
+ : t('匿名读取(公开仓库,不限令牌;上限 60 次/小时),提交和关单需要令牌', 'Anonymous read (public repo, no token needed; 60 requests/hour). Submitting and closing need a token.'))
4969
5969
  : '',
4970
5970
  })
4971
5971
  return
4972
5972
  } catch (error) {
4973
5973
  lastError = String((error && error.message) || error)
5974
+ if (tok && /^0\s/.test(lastError)) break
4974
5975
  }
4975
5976
  }
4976
5977
  sendJson(res, 200, { ...base, error: lastError || t('读不到 issue 列表', 'Cannot read the issue list') })
@@ -4988,21 +5989,77 @@ async function handleFeedback(req, res, config) {
4988
5989
  const payload = raw.trim() ? JSON.parse(raw) : {}
4989
5990
  const g = await ghToken(config, dshHome)
4990
5991
 
4991
- // 1) 存令牌(填一次就够了;顺手用一次只读接口验证)
5992
+ // 1) 存令牌 / 绑定环境变量 / 换反馈仓库(用一次只读接口验证;绑定环境变量时绝不落盘令牌值)
4992
5993
  if (action === 'token') {
4993
- const token = String(payload.token || '').trim()
5994
+ clearWinEnvCache()
4994
5995
  const repo = String(payload.repo || g.repo || GH_DEFAULT_REPO).trim() || GH_DEFAULT_REPO
4995
- if (!token) throw new Error(t('令牌是空的', 'The token is empty'))
4996
- const probe = await ghApi(`/repos/${repo}`, { token })
5996
+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) {
5997
+ throw new Error(t('仓库格式不对,应为 owner/repo', 'Invalid repo format — expected owner/repo'))
5998
+ }
5999
+ if (payload.clearToken === true) {
6000
+ writeGh(dshHome, {
6001
+ token: '',
6002
+ tokenEnv: payload.clearEnv === true ? '' : undefined,
6003
+ repo,
6004
+ login: '',
6005
+ })
6006
+ const next = await ghToken(config, dshHome)
6007
+ const me = next.token ? await ghIdentity(next.token, dshHome, next.credLogin || '') : ''
6008
+ const owner = ownerOf(repo)
6009
+ sendJson(res, 200, {
6010
+ ok: true,
6011
+ cleared: true,
6012
+ connected: Boolean(next.token),
6013
+ tokenPresent: Boolean(next.token),
6014
+ repo,
6015
+ tokenSource: next.source || 'none',
6016
+ tokenEnv: next.envName || next.tokenEnv || '',
6017
+ tokenSaved: Boolean(next.tokenSaved),
6018
+ login: me,
6019
+ owner,
6020
+ canClose: !!(me && owner && me.toLowerCase() === owner.toLowerCase()),
6021
+ })
6022
+ return
6023
+ }
6024
+ const rawToken = String(payload.token || '').trim()
6025
+ const explicitEnv = String(payload.tokenEnv || '').trim()
6026
+ const envName = explicitEnv || parseEnvTokenRef(rawToken)
6027
+ let verifyToken = ''
6028
+ let saveFields = { repo }
6029
+ if (envName) {
6030
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(envName)) {
6031
+ throw new Error(t('环境变量名格式不对(仅支持字母、数字和下划线)', 'Invalid env var name (letters, digits and underscores only)'))
6032
+ }
6033
+ verifyToken = getEnvValue(envName)
6034
+ if (!verifyToken) {
6035
+ throw new Error(t(`本机环境变量 ${envName} 为空,请先设置它后再保存`, `Local environment variable ${envName} is empty — set it first`))
6036
+ }
6037
+ // 只存变量名,绝不把令牌值写进 config-sync-gh.json
6038
+ saveFields = { token: '', tokenEnv: envName, repo }
6039
+ } else if (rawToken) {
6040
+ verifyToken = rawToken
6041
+ saveFields = { token: rawToken, tokenEnv: '', repo }
6042
+ } else if (g.token) {
6043
+ // 只改 repo(保留当前已有的环境变量 / 凭据 / 已存令牌)
6044
+ verifyToken = g.token
6045
+ saveFields = { repo }
6046
+ } else {
6047
+ throw new Error(t('请输入令牌或环境变量名(如 $GITHUB_TOKEN)', 'Enter a token or an environment variable reference (e.g. $GITHUB_TOKEN)'))
6048
+ }
6049
+ const probe = await ghApi(`/repos/${repo}`, { token: verifyToken })
4997
6050
  if (!probe.ok) throw new Error(`${probe.status} ${String((probe.json && probe.json.message) || '').slice(0, 160) || '令牌或仓库不对'}`)
4998
- const me = await ghIdentity(token, dshHome)
4999
- writeGh(dshHome, { token, repo, login: me })
6051
+ const me = await ghIdentity(verifyToken, dshHome)
6052
+ writeGh(dshHome, { ...saveFields, login: me })
5000
6053
  const owner = ownerOf(repo)
5001
6054
  sendJson(res, 200, {
5002
6055
  ok: true,
5003
6056
  connected: true,
6057
+ tokenPresent: true,
5004
6058
  repo,
5005
6059
  saved: ghPathOf(dshHome),
6060
+ tokenSource: envName ? 'env' : (rawToken ? 'file' : (g.source || 'file')),
6061
+ tokenEnv: envName || g.envName || '',
6062
+ tokenSaved: Boolean(rawToken || (!envName && g.tokenSaved)),
5006
6063
  login: me,
5007
6064
  owner,
5008
6065
  canClose: !!(me && owner && me.toLowerCase() === owner.toLowerCase()),