dsh-profile-config-sync 0.5.0 → 0.6.41

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),
@@ -1775,8 +1880,11 @@ const autoState = {
1775
1880
  ok: null,
1776
1881
  phase: '',
1777
1882
  message: '',
1883
+ detail: '',
1884
+ recent: [],
1778
1885
  log: '',
1779
1886
  initPush: false,
1887
+ transport: '',
1780
1888
  },
1781
1889
  }
1782
1890
 
@@ -1939,7 +2047,7 @@ function psWinArg(value) {
1939
2047
  * detached=false 立刻就在写日志。所以这里不 detached,而是让一个短命 powershell 用
1940
2048
  * Start-Process 把真正的 post-exit 起成独立进程 —— 父进程(DSH)退出后它照样活着。
1941
2049
  */
1942
- async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [] }) {
2050
+ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [], closeRequested = false }) {
1943
2051
  const script = autoScript(dshHome, repo)
1944
2052
  if (!script) return { ok: false, error: t('插件与仓库里都没有 post-exit.ps1,无法排队', 'post-exit.ps1 is in neither the plugin nor the repo — cannot queue') }
1945
2053
 
@@ -1977,6 +2085,9 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
1977
2085
  // 否则排队期间(可能几小时)会一直挂着一个挡视线的空窗口。
1978
2086
  '-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome,
1979
2087
  '-PidFile', pidFile]
2088
+ // 只有「插件自己请求过关闭客户端」的流程才允许守护进程在窗口消失后强杀残留进程;
2089
+ // 被动等待(自动推送/拉取)绝不强杀 —— 否则用户把窗口收进托盘就会被静默杀掉。
2090
+ if (closeRequested) args.push('-CloseWhenIdle')
1980
2091
  if (repo) args.push('-RepoRoot', repo)
1981
2092
  if (appRoot) args.push('-AppRoot', appRoot)
1982
2093
  if (restart) args.push('-Restart')
@@ -2102,11 +2213,19 @@ function readSyncState(dshHome) {
2102
2213
 
2103
2214
  /** 本机登记的工作区目录(capture 会把它们镜像进仓库,所以它们变了也算待推送)。 */
2104
2215
  function workspaceRoots(dshHome) {
2105
- const reg = readJson(join(dshHome, 'storages', 'workspace.json')) || {}
2106
- const list = (reg.tables && reg.tables.workspaces) || reg.workspaces || []
2107
- return Array.isArray(list)
2108
- ? list.map((w) => (w && typeof w.path === 'string' ? w.path : '')).filter(Boolean)
2109
- : []
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 + '--'
2110
2229
  }
2111
2230
 
2112
2231
  // 本机待推送文件按「同步内容」的分组归类;标签与 collectScopeGroups 的 titleZh/titleEn 对齐
@@ -2126,16 +2245,26 @@ const PENDING_GROUP_LABEL = {
2126
2245
  other: ['其它', 'Other'],
2127
2246
  }
2128
2247
 
2129
- function pendingGroupOf(file, dshHome, profileDir, workspacePaths) {
2248
+ function pendingGroupOf(file, dshHome, profileDir, workspacePaths, roots, settingsPaths) {
2130
2249
  const norm = String(file).replace(/\\/g, '/')
2131
2250
  const base = String(dshHome).replace(/\\/g, '/').replace(/\/+$/, '')
2132
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'
2133
2255
  if (prof && norm.startsWith(prof + '/')) return 'profile'
2134
2256
  if (/\/AGENTS\.md$|\/prompt-inject\.md$/i.test(norm)) return 'prompt'
2135
2257
  if (norm.startsWith(base + '/skills/')) return 'skills'
2136
2258
  if (norm.startsWith(base + '/.agent-presets/')) return 'presets'
2259
+ if (norm.startsWith(base + '/storages/@montersy123/dsh-skill-market/data/')) return 'storages-record'
2137
2260
  if (norm.startsWith(base + '/mnemon/')) return 'mnemon'
2138
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
+ }
2139
2268
  for (const w of workspacePaths || []) {
2140
2269
  const wn = String(w).replace(/\\/g, '/').replace(/\/+$/, '')
2141
2270
  if (wn && norm.startsWith(wn + '/')) return 'workspace'
@@ -2167,29 +2296,171 @@ function sessionTitleOf(dshHome, sessionId) {
2167
2296
  function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2168
2297
  const since = lastSyncAt ? Date.parse(lastSyncAt) : NaN
2169
2298
  if (!Number.isFinite(since)) return { known: false, pending: 0, newestAt: '', sample: [], groups: [] }
2170
- 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'])
2171
2302
  const profile = join(dshHome, 'profiles', profileName || 'desktop')
2172
- 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 / 预设 / 台账 / 设置 / 记忆 / 会话
2173
2331
  const stack = [
2174
- join(dshHome, 'sessions'),
2175
- join(dshHome, 'skills'),
2176
- join(dshHome, '.agent-presets'),
2177
- join(dshHome, 'mnemon'),
2178
- join(dshHome, 'AGENTS.md'),
2179
- join(dshHome, 'prompt-inject.md'),
2180
2332
  join(profile, 'package.json'),
2181
2333
  join(profile, 'pnpm-lock.yaml'),
2334
+ join(profile, 'pnpm-workspace.yaml'),
2335
+ join(profile, 'cordis.yml'),
2182
2336
  join(profile, 'cordis.patch.yml'),
2183
2337
  join(profile, 'host-contract.json'),
2184
- ...workspaceRoots(dshHome),
2185
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)
2186
2457
  // 有仓库对应物的单文件:路径 → 仓库里的那份。只有这些才值得读内容比对。
2187
2458
  const repoRoot = String(ctx.repo || '')
2188
2459
  const mirrored = new Map()
2189
2460
  if (repoRoot) {
2190
2461
  mirrored.set(join(dshHome, 'AGENTS.md'), join(repoRoot, 'prompt', 'AGENTS.md'))
2191
2462
  mirrored.set(join(dshHome, 'prompt-inject.md'), join(repoRoot, 'prompt', 'prompt-inject.md'))
2192
- 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']) {
2193
2464
  mirrored.set(join(profile, f), join(repoRoot, 'profile', f))
2194
2465
  }
2195
2466
  }
@@ -2202,12 +2473,46 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2202
2473
  // 每组保留具体明细名称(会话记录名 / 本机 profile 文件名 …),供面板展开查看
2203
2474
  const groupItems = new Map()
2204
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
+ }
2205
2495
  while (stack.length && scanned < 20000 && Date.now() < deadline) {
2206
2496
  const cur = stack.pop()
2207
2497
  let st
2208
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
+ }
2209
2509
  if (st.isDirectory()) {
2210
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
+ }
2211
2516
  let entries = []
2212
2517
  try { entries = readdirSync(cur) } catch { continue }
2213
2518
  for (const e of entries) stack.push(join(cur, e))
@@ -2215,6 +2520,11 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2215
2520
  }
2216
2521
  scanned++
2217
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
+ }
2218
2528
  // 镜像文件的 mtime 更新可能只是宿主重写占位符:内容归一后一致就不算待推送
2219
2529
  const twin = mirrored.get(cur)
2220
2530
  if (twin && isFile(twin)) {
@@ -2224,7 +2534,10 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2224
2534
  }
2225
2535
  pending++
2226
2536
  if (st.mtimeMs > newest) newest = st.mtimeMs
2227
- 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 }
2228
2541
  groupCount.set(gid, (groupCount.get(gid) || 0) + 1)
2229
2542
  // 会话文件显示会话标题而不是目录 ID;其余显示父目录/文件名
2230
2543
  let label = `${basename(dirname(cur))}/${basename(cur)}`
@@ -2260,6 +2573,8 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2260
2573
  groups,
2261
2574
  profileName: profileName || 'desktop',
2262
2575
  truncated: scanned >= 20000 || Date.now() >= deadline,
2576
+ // 非 Windows 时只统计引擎真会同步的四组,把这件事说出来(面板会显示,不让用户以为别的组也在同步)
2577
+ engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
2263
2578
  }
2264
2579
  }
2265
2580
 
@@ -2408,7 +2723,13 @@ async function handleSettings(req, res, config) {
2408
2723
 
2409
2724
  // 新仓库路径一落盘,后面的 git remote 要对它做,别用改之前解析出来的旧仓库。
2410
2725
  const repo = repoPath || (resolveRepo(config?.repoPath, dshHome).repo || '')
2411
- 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
+ })
2412
2733
 
2413
2734
  const changed = {
2414
2735
  repoPath: before.repoPath !== repoPath,
@@ -2572,16 +2893,16 @@ function resolveTgzUrl(manifest, manifestUrl = UPDATE_MANIFEST_URL) {
2572
2893
  return ''
2573
2894
  }
2574
2895
 
2575
- async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT) {
2896
+ async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT, headers = {}) {
2576
2897
  if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch,无法检查更新', 'fetch is unavailable in this runtime — cannot check for updates'))
2577
2898
  const seconds = Math.round(timeoutMs / 1000)
2578
2899
  const ctrl = typeof AbortController === 'function' ? new AbortController() : null
2579
2900
  let timedOut = false
2580
2901
  const timer = ctrl ? setTimeout(() => { timedOut = true; try { ctrl.abort() } catch { } }, timeoutMs) : null
2581
2902
  try {
2582
- 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 })
2583
2904
  if (!res.ok) {
2584
- 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)') : ''}`)
2585
2906
  }
2586
2907
  const json = await res.json()
2587
2908
  if (!json || !json.version) throw new Error(t('version.json 里没有 version 字段', 'version.json has no "version" field'))
@@ -2595,17 +2916,66 @@ async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT) {
2595
2916
  }
2596
2917
  }
2597
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
+
2598
2960
  /**
2599
- * 读清单:自定义地址只用它自己;没配则按 UPDATE_MANIFEST_MIRRORS 依次试,第一个成功的就用。
2961
+ * 读清单:自定义地址只用它自己;没配则按候选源依次试,第一个成功的就用。
2962
+ * 有令牌时把 GitHub API 放在最前面(私有库第三方反代必 404、直连 raw 常超时,API 几百毫秒直达)。
2600
2963
  * 全失败时把每个源各自的失败原因汇总抛出 —— 面板上一眼能看出是超时、HTTP 状态还是解析失败。
2601
2964
  */
2602
2965
  async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH_TIMEOUT) {
2603
2966
  const custom = String(targetUrl || '').trim()
2604
- 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())
2605
2972
  const tried = []
2606
2973
  for (const cand of candidates) {
2607
2974
  try {
2608
- 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)
2609
2979
  tried.push({ url: cand, ok: true })
2610
2980
  return { manifest, url: cand, tried }
2611
2981
  } catch (error) {
@@ -2627,11 +2997,15 @@ async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH
2627
2997
  * 注意 API 的 raw 端点不吃"分支写进路径",分支要单独给 ref:
2628
2998
  * https://gitee.com/<owner>/<repo>/raw/<branch>/<path>
2629
2999
  * → https://gitee.com/api/v5/repos/<owner>/<repo>/raw/<path>?ref=<branch>&access_token=…
2630
- * 公开库不填令牌时保持原样,行为跟以前一致。
3000
+ * 公开库与第三方反代(gh-proxy / ghfast)不拼入令牌,避免泄露给中间代理。
2631
3001
  */
2632
3002
  function withAccessToken(url, token) {
2633
3003
  const raw = String(url || '')
2634
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 }
2635
3009
  let target = raw
2636
3010
  const m = /^https:\/\/gitee\.com\/([^/]+)\/([^/]+)\/raw\/([^/]+)\/(.+)$/.exec(raw.split('?')[0])
2637
3011
  if (m) target = `https://gitee.com/api/v5/repos/${m[1]}/${m[2]}/raw/${m[4]}?ref=${encodeURIComponent(m[3])}`
@@ -2665,9 +3039,10 @@ async function checkUpdate({ force = false, url = '', token = '' } = {}) {
2665
3039
  return updateState
2666
3040
  }
2667
3041
 
2668
- function updatePayload(state, settings = {}) {
3042
+ function updatePayload(state, settings = {}, resolvedToken = null) {
2669
3043
  const remote = state.manifest
2670
3044
  const custom = String(settings.updateManifestUrl || '')
3045
+ const resolvedUpd = resolvedToken || resolveTokenSpec(settings.updateToken, custom ? [] : GH_TOKEN_ENV_CANDIDATES)
2671
3046
  const installed = state.liveInstall || null
2672
3047
  // 装好了但进程还在跑旧代码 = 需要重启;重启后 PLUGIN_VERSION 追上来,这条自然消失
2673
3048
  const restartRequired = Boolean(installed && compareVersion(installed.version, PLUGIN_VERSION) > 0)
@@ -2679,7 +3054,10 @@ function updatePayload(state, settings = {}) {
2679
3054
  manifestUrl: custom || UPDATE_MANIFEST_MIRRORS[0],
2680
3055
  manifestUrlIsDefault: !custom,
2681
3056
  manifestSources: custom ? [] : UPDATE_MANIFEST_MIRRORS.slice(),
2682
- 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,
2683
3061
  },
2684
3062
  remote: remote ? {
2685
3063
  version: String(remote.version || ''),
@@ -2727,7 +3105,36 @@ function updatePayload(state, settings = {}) {
2727
3105
  * 候选地址逐个试(raw 常常不通,反代在前面兜着),全失败时把每个源的原因汇总抛出。
2728
3106
  * 返回 { ok, file, size, sha256, url } 或 { ok:false, error }
2729
3107
  */
2730
- 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 = '' }) {
2731
3138
  if (typeof fetch !== 'function') return { ok: false, error: t('当前运行环境没有 fetch,无法下载更新包', 'fetch is unavailable in this runtime — cannot download the update package') }
2732
3139
  const dir = join(dshHome, 'update-staging')
2733
3140
  try { mkdirSync(dir, { recursive: true }) } catch { }
@@ -2738,16 +3145,24 @@ async function downloadPackage({ urls, sha256, version, dshHome }) {
2738
3145
  const url = String(rawUrl || '').trim()
2739
3146
  if (!url) continue
2740
3147
  try {
2741
- const ctrl = typeof AbortController === 'function' ? new AbortController() : null
2742
- const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120 * 1000) : null
2743
- let res
2744
- try {
2745
- res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
2746
- } finally {
2747
- 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())
2748
3165
  }
2749
- if (!res.ok) throw new Error(`HTTP ${res.status}`)
2750
- const buf = Buffer.from(await res.arrayBuffer())
2751
3166
  if (!buf.length) throw new Error(t('下载到的文件是空的', 'the downloaded file is empty'))
2752
3167
  const hash = createHash('sha256').update(buf).digest('hex')
2753
3168
  if (want && hash !== want) throw new Error(t(`sha256 不一致(拿到 ${hash})`, `sha256 mismatch (got ${hash})`))
@@ -2814,23 +3229,29 @@ async function handleUpdate(req, res, config) {
2814
3229
  const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
2815
3230
  const settings = readSettings(dshHome)
2816
3231
  // 清单地址允许被设置覆盖:换镜像/自建仓库、或本地搭测试服务时不改动插件源码。
2817
- // 留空 = 用内置候选列表(jsDelivr 优先、raw 兜底)
3232
+ // 留空 = 用内置候选列表(GitHub API / gh-proxy / ghfast / raw)
2818
3233
  const manifestUrl = String(settings.updateManifestUrl || '')
2819
- const updateToken = String(settings.updateToken || '')
2820
3234
  try {
2821
3235
  if (req.method === 'GET') {
2822
- 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))
2823
3238
  return
2824
3239
  }
2825
3240
  if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET or POST only' }); return }
2826
3241
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3242
+ // 先读 body 再解析令牌:读 body 之前不能有 await,否则请求流可能已经被读空/结束,
3243
+ // 事件监听挂晚了就永远等不到 'end'(实测:把令牌解析提到前面会让所有 POST 一直挂住)。
2827
3244
  const raw = await readBody(req)
2828
3245
  const body = raw.trim() ? JSON.parse(raw) : {}
2829
3246
  const action = String(body.action || 'check')
3247
+ const resolvedUpd = await resolveUpdateToken(settings, manifestUrl)
3248
+ const updateToken = resolvedUpd.token
2830
3249
 
2831
3250
  if (action === 'check') {
2832
- const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
2833
- 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) })
2834
3255
  return
2835
3256
  }
2836
3257
 
@@ -2846,12 +3267,12 @@ async function handleUpdate(req, res, config) {
2846
3267
  // 同一个版本已经下好就不重复下(DSH 一直开着时用户可能点第二次)
2847
3268
  const prev = updateState.prepared
2848
3269
  if (prev && prev.version === String(remote.version) && isFile(prev.file)) {
2849
- sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings) })
3270
+ sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings, resolvedUpd) })
2850
3271
  return
2851
3272
  }
2852
3273
  const urls = resolveTgzCandidates(remote, state.url)
2853
3274
  if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
2854
- 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 })
2855
3276
  if (!got.ok) throw new Error(String(got.error || t('下载失败', 'download failed')))
2856
3277
  updateState.prepared = {
2857
3278
  version: String(remote.version),
@@ -2861,7 +3282,7 @@ async function handleUpdate(req, res, config) {
2861
3282
  at: Date.now(),
2862
3283
  url: got.url,
2863
3284
  }
2864
- 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) })
2865
3286
  return
2866
3287
  }
2867
3288
 
@@ -2884,6 +3305,7 @@ async function handleUpdate(req, res, config) {
2884
3305
  appRoot,
2885
3306
  dshHome,
2886
3307
  restart: true,
3308
+ closeRequested: true,
2887
3309
  extraArgs: [
2888
3310
  '-PluginDir', PLUGIN_DIR,
2889
3311
  '-UpdateTgz', prepared.file,
@@ -2895,7 +3317,7 @@ async function handleUpdate(req, res, config) {
2895
3317
  autoState.pending = { mode: 'update', at: Date.now(), version: String(prepared.version), restart: true, watcherPid: started.pid, installFrom: prepared.file }
2896
3318
  const closed = closeDsh()
2897
3319
  autoState.pending.closeRequested = closed
2898
- 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) })
2899
3321
  return
2900
3322
  }
2901
3323
 
@@ -2920,7 +3342,7 @@ async function handleUpdate(req, res, config) {
2920
3342
  }
2921
3343
  // 注意 hasUpdate 仍是 true:进程里跑的还是旧代码,重启后 PLUGIN_VERSION 才追上来。
2922
3344
  // 面板靠 restartRequired 换成「已装好,重启生效」
2923
- 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) })
2924
3346
  return
2925
3347
  }
2926
3348
 
@@ -2948,7 +3370,7 @@ async function handleUpdate(req, res, config) {
2948
3370
  if (!tgz) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
2949
3371
  const notes = String((langStore.getStore() === 'en' ? (remote.notesEn || remote.notes) : remote.notes) || '').trim()
2950
3372
  const yes = await askConfirm(
2951
- t('更新「配置同步」插件', 'Update the Config Sync plugin'),
3373
+ t('更新「配置备份与同步」插件', 'Update the Config Backup & Sync plugin'),
2952
3374
  t(
2953
3375
  `把插件从 ${PLUGIN_VERSION} 更新到 ${remote.version}?`
2954
3376
  + (notes ? `\n\n${notes}` : '')
@@ -2958,7 +3380,7 @@ async function handleUpdate(req, res, config) {
2958
3380
  + '\n\nSteps: exit DSH → download and verify the package → back up the old version → install over it → relaunch automatically.',
2959
3381
  ),
2960
3382
  )
2961
- 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 }
2962
3384
 
2963
3385
  const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
2964
3386
  const appRoot = resolveAppRoot(config?.appRoot) || ''
@@ -2968,6 +3390,7 @@ async function handleUpdate(req, res, config) {
2968
3390
  appRoot,
2969
3391
  dshHome,
2970
3392
  restart: true,
3393
+ closeRequested: true,
2971
3394
  extraArgs: [
2972
3395
  '-PluginDir', PLUGIN_DIR,
2973
3396
  '-UpdateVersion', String(remote.version),
@@ -3074,6 +3497,14 @@ function countEntries(dir) {
3074
3497
  }
3075
3498
  }
3076
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
+
3077
3508
  /** profile 目录:优先 desktop,其次 profiles 下唯一的那一个 */
3078
3509
  function resolveProfileDir(dshHome) {
3079
3510
  const desktop = join(dshHome, 'profiles', 'desktop')
@@ -3132,18 +3563,92 @@ const EXTRA_HARD_MAX_BYTES = 104857600
3132
3563
  const EXTRA_DEFAULT_SKIP_DIRS = [
3133
3564
  'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
3134
3565
  'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
3135
- 'im', 'node_modules',
3566
+ 'browser-profiles', 'im', 'node_modules',
3136
3567
  ]
3137
3568
  const EXTRA_DEFAULT_EXCLUDE = [
3138
3569
  '*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
3139
3570
  '*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
3140
3571
  '*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
3141
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',
3142
3574
  'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
3143
3575
  '*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
3576
+ 'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
3144
3577
  'node_modules', '.git', '.cache', '__pycache__', '.venv',
3145
3578
  ]
3146
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
+
3147
3652
  function extraConfigPath(dshHome) { return join(dshHome, EXTRA_CONFIG_NAME) }
3148
3653
 
3149
3654
  function readExtraConfig(dshHome) {
@@ -3180,6 +3685,12 @@ function readExtraConfig(dshHome) {
3180
3685
  }
3181
3686
  }
3182
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
+ }
3183
3694
  return cfg
3184
3695
  }
3185
3696
 
@@ -3198,7 +3709,7 @@ function saveExtraConfig(dshHome, cfg) {
3198
3709
  paths: (cfg.extra.paths || []).map((x) => ({ id: x.id, src: x.src, label: x.label || x.id })),
3199
3710
  },
3200
3711
  }
3201
- writeFileSync(p, JSON.stringify(out, null, 2) + '\n', 'utf8')
3712
+ writeFileAtomicSync(p, JSON.stringify(out, null, 2) + '\n')
3202
3713
  return p
3203
3714
  }
3204
3715
 
@@ -3308,14 +3819,11 @@ function collectScopeGroups(dshHome, appRoot) {
3308
3819
  descZh: '技能市场的安装台账与面板状态', descEn: 'Skill-market install ledger and panel state',
3309
3820
  items: ledger.map((f) => ({ id: f.id, label: f.id })) })
3310
3821
 
3311
- const settingsFiles = [
3312
- { id: 'our-free-model.json', src: join(dshHome, 'our-free-model', 'settings.json') },
3313
- { id: 'comfyui-workflows.json', src: join(dshHome, 'data', 'dsh-comfyui', 'workflows.json') },
3314
- { id: 'dsh-pet-main-config.jsonc', src: join(dshHome, 'dsh-pet', 'main-config.jsonc') },
3315
- { id: 'dsh-market-state.json', src: join(profileDir, '.dsh-market', 'state.json') },
3316
- ].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))
3317
3825
  groups.push({ id: 'settings', titleZh: '插件设置与工作流', titleEn: 'Plugin settings & workflows',
3318
- 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',
3319
3827
  items: settingsFiles.map((x) => ({ id: x.id, label: x.id })) })
3320
3828
 
3321
3829
  const mnemonDir = appRoot ? join(appRoot, 'mnemon') : ''
@@ -3393,7 +3901,14 @@ async function handleScope(req, res, config) {
3393
3901
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3394
3902
  const raw = await readBody(req)
3395
3903
  const body = raw.trim() ? JSON.parse(raw) : {}
3396
- 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
3397
3912
  // 排除项只认「本机当前真实存在、且允许单独排除」的条目:
3398
3913
  // 拖着一堆早就不存在的 id 会让用户以后勾不回来(看不见却一直挡着同步)。
3399
3914
  const allowed = {}
@@ -3439,20 +3954,30 @@ async function handleScope(req, res, config) {
3439
3954
  */
3440
3955
  function conflictPath(dshHome) { return join(dshHome, 'sync-conflicts.json') }
3441
3956
 
3957
+ const CONFLICT_MISSING = null
3958
+
3959
+ /** 读冲突清单:没有 → null;有但坏了 → { broken:true, error }(不能再统一当「没有」)。 */
3442
3960
  function readConflicts(dshHome) {
3443
3961
  const p = conflictPath(dshHome)
3444
- 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
+ }
3445
3967
  try {
3446
- const obj = JSON.parse(readFileSync(p, 'utf8'))
3447
- 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 数组' }
3448
3971
  return obj
3449
- } catch { return null }
3972
+ } catch (error) {
3973
+ return { broken: true, error: `清单解析失败:${String((error && error.message) || error)}` }
3974
+ }
3450
3975
  }
3451
3976
 
3452
3977
  function writeConflicts(dshHome, obj) {
3453
3978
  const p = conflictPath(dshHome)
3454
3979
  mkdirSync(dirname(p), { recursive: true })
3455
- writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', 'utf8')
3980
+ writeFileAtomicSync(p, JSON.stringify(obj, null, 2) + '\n')
3456
3981
  return p
3457
3982
  }
3458
3983
 
@@ -3497,28 +4022,23 @@ async function handleExtraConfig(req, res, config) {
3497
4022
  if (src.extra && typeof src.extra === 'object') {
3498
4023
  if (typeof src.extra.enabled === 'boolean') cur.extra.enabled = src.extra.enabled
3499
4024
  if (Array.isArray(src.extra.paths)) {
3500
- const used = new Set()
3501
- const paths = []
3502
- for (const p of src.extra.paths) {
3503
- if (!p || typeof p.src !== 'string' || !p.src.trim()) continue
3504
- const abs = p.src.trim().replace(/\//g, '\\')
3505
- if (!/^[A-Za-z]:\\/.test(abs) && !abs.startsWith('\\\\')) continue
3506
- const base = (typeof p.label === 'string' && p.label.trim())
3507
- ? p.label.trim()
3508
- : (typeof p.id === 'string' && p.id.trim() ? p.id.trim() : basename(abs))
3509
- let id = String(base).replace(/[\\/:*?"<>|\s]+/g, '-').replace(/^-+|-+$/g, '') || 'extra'
3510
- if (!isAbsolute(abs)) continue
3511
- let n = 2
3512
- const root = id
3513
- while (used.has(id.toLowerCase())) { id = `${root}-${n++}` }
3514
- used.add(id.toLowerCase())
3515
- 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
+ ))
3516
4033
  }
3517
- cur.extra.paths = paths
4034
+ cur.extra.paths = norm.paths
3518
4035
  }
3519
4036
  }
4037
+ // 保存前再补一次安全必需项:上面刚用用户提交的名单整份覆盖过,
4038
+ // 不补就等于「用户点一次保存,browser-profiles 规则被删掉」(实测丢过一次)。
4039
+ const added = topUpExtraMandatory(cur)
3520
4040
  const p = saveExtraConfig(dshHome, cur)
3521
- sendJson(res, 200, { ok: true, path: p, config: readExtraConfig(dshHome) })
4041
+ sendJson(res, 200, { ok: true, path: p, mandatoryRestored: added, config: readExtraConfig(dshHome) })
3522
4042
  } catch (error) {
3523
4043
  sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
3524
4044
  }
@@ -3530,6 +4050,18 @@ async function handleConflict(req, res, config) {
3530
4050
  if (req.method === 'GET') {
3531
4051
  const obj = readConflicts(dshHome)
3532
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
+ }
3533
4065
  const items = obj.items.map((it) => ({
3534
4066
  path: String(it.path || ''),
3535
4067
  kind: String(it.kind || ''),
@@ -3559,6 +4091,13 @@ async function handleConflict(req, res, config) {
3559
4091
  if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
3560
4092
  const raw = await readBody(req)
3561
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
+
3562
4101
  const obj = readConflicts(dshHome)
3563
4102
  if (!obj) {
3564
4103
  throw new Error(t(
@@ -3566,16 +4105,20 @@ async function handleConflict(req, res, config) {
3566
4105
  'No pending conflict list (one is created automatically when a pull is blocked)',
3567
4106
  ))
3568
4107
  }
3569
-
3570
- if (body.action === 'reset') {
3571
- try { unlinkSync(conflictPath(dshHome)) } catch { }
3572
- sendJson(res, 200, { ok: true, cleared: true })
3573
- 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
+ ))
3574
4113
  }
3575
4114
 
3576
4115
  if (body.action === 'restore') {
3577
4116
  const rel = String(body.path || '').trim()
3578
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
+ }
3579
4122
  const side = body.side === 'cloud' ? 'cloud' : 'local'
3580
4123
  // 还原落到「当时发生冲突的那个仓库」(清单里记着),而不是此刻设置里的路径:
3581
4124
  // 用户之后改过 repoPath 也不会把副本写进另一个仓库。
@@ -3673,7 +4216,9 @@ function startLivePush({ repo, dshHome, appRoot, settings }) {
3673
4216
  if (autoState.livePush.running) {
3674
4217
  return { alreadyRunning: true, livePush: { ...autoState.livePush } }
3675
4218
  }
4219
+ const reqLang = langStore.getStore() || 'zh'
3676
4220
  const initPush = repoPhase(repo) !== 'ok'
4221
+ const transport = webdavActive(settings) ? 'webdav' : 'git'
3677
4222
  const logsDir = join(dshHome, 'logs')
3678
4223
  try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
3679
4224
  const d = new Date()
@@ -3693,9 +4238,25 @@ function startLivePush({ repo, dshHome, appRoot, settings }) {
3693
4238
  ...(appRoot ? [`AppRoot = ${psQuote(appRoot)}`] : []),
3694
4239
  `Force = $true`,
3695
4240
  ].join('; ')
3696
- const psCmd = `[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false); $OutputEncoding = [Console]::OutputEncoding; $a = @{ ${psArgs} }; & ${psQuote(syncScript)} @a; exit $LASTEXITCODE`
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('; ')
3697
4258
  cmd = powershellExe()
3698
- cmdArgs = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(psCmd, 'utf16le').toString('base64')]
4259
+ cmdArgs = ['-NoProfile', '-NonInteractive', '-OutputFormat', 'Text', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', Buffer.from(psCmd, 'utf16le').toString('base64')]
3699
4260
  } else {
3700
4261
  const engine = [join(pluginRoot(), 'runtime', 'sync-engine.mjs'), join(repo, 'sync-engine.mjs')].find((p) => isFile(p))
3701
4262
  if (!engine) throw new Error(t('找不到 sync-engine.mjs,无法在线推送', 'sync-engine.mjs not found — cannot run live push'))
@@ -3712,36 +4273,85 @@ function startLivePush({ repo, dshHome, appRoot, settings }) {
3712
4273
  message: initPush
3713
4274
  ? t('正在后台初始化推送(不关闭 DSH)…', 'Initializing push in background (DSH stays open)…')
3714
4275
  : t('正在后台抓取并推送(不关闭 DSH)…', 'Capturing and pushing in background (DSH stays open)…'),
4276
+ detail: '',
4277
+ recent: [],
3715
4278
  log: logFile,
3716
4279
  initPush,
4280
+ transport,
3717
4281
  }
3718
4282
 
3719
4283
  const tail = []
3720
- const appendLog = (chunk) => {
3721
- const text = String(chunk || '')
3722
- try { writeFileSync(logFile, text, { flag: 'a' }) } catch { }
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 = []
3723
4303
  for (const rawLine of text.split(/\r?\n/)) {
3724
- const line = rawLine.trim()
3725
- if (!line) continue
3726
- tail.push(line)
3727
- if (tail.length > 50) tail.shift()
3728
- if (/==\s*初始化仓库/.test(line)) {
3729
- autoState.livePush.phase = 'init'
3730
- autoState.livePush.message = t('正在初始化仓库骨架…', 'Initializing repo skeleton…')
3731
- } else if (/==\s*抓取|capture/.test(line)) {
3732
- autoState.livePush.phase = 'capture'
3733
- autoState.livePush.message = t('正在抓取本机配置与会话…', 'Capturing local config and sessions…')
3734
- } else if (/==\s*提交/.test(line)) {
3735
- autoState.livePush.phase = 'commit'
3736
- autoState.livePush.message = t('正在提交本机变更…', 'Committing local changes…')
3737
- } else if (/==\s*上传到 WebDAV|WebDAV 上传|==\s*推送/.test(line)) {
3738
- autoState.livePush.phase = 'upload'
3739
- autoState.livePush.message = t('正在上传到云端…', 'Uploading to cloud…')
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 { }
3740
4319
  }
3741
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
+ })
3742
4352
  }
3743
4353
 
3744
- const finish = async (ok, errText) => {
4354
+ const finish = (ok, errText, opts = {}) => langStore.run(reqLang, async () => {
3745
4355
  clearWebdavProbeCache()
3746
4356
  if (ok) {
3747
4357
  try {
@@ -3768,25 +4378,33 @@ function startLivePush({ repo, dshHome, appRoot, settings }) {
3768
4378
  finishedAt: Date.now(),
3769
4379
  ok,
3770
4380
  phase: ok ? 'done' : 'error',
3771
- message: ok
3772
- ? (initPush
3773
- ? t('初始化推送完成(未关闭 DSH)', 'Initialize push completed (DSH stayed open)')
3774
- : t('推送完成(未关闭 DSH)', 'Push completed (DSH stayed open)'))
3775
- : (errText || t('推送失败,详见日志', 'Push failed — see log')),
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),
3776
4389
  }
3777
- }
4390
+ })
3778
4391
 
3779
4392
  const child = spawn(cmd, cmdArgs, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
3780
- child.stdout.on('data', appendLog)
3781
- child.stderr.on('data', appendLog)
4393
+ child.stdout.on('data', (c) => appendLog(c, false))
4394
+ child.stderr.on('data', (c) => appendLog(c, true))
3782
4395
  child.once('error', (e) => {
3783
4396
  const msg = String((e && e.message) || e)
3784
4397
  appendLog(`\n[error] ${msg}\n`)
3785
4398
  finish(false, msg)
3786
4399
  })
3787
4400
  child.once('exit', async (code) => {
3788
- if (code !== 0) {
3789
- const errLine = [...tail].reverse().find((l) => /\[X\]|失败|error|fatal:/i.test(l)) || tail[tail.length - 1] || `exit ${code}`
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}`
3790
4408
  finish(false, errLine)
3791
4409
  return
3792
4410
  }
@@ -3808,12 +4426,12 @@ function startLivePush({ repo, dshHome, appRoot, settings }) {
3808
4426
  if (!IS_WIN) {
3809
4427
  try {
3810
4428
  const head = (await git(repo, ['log', '-1', '--format=%h'])) || ''
3811
- writeFileSync(join(dshHome, STATE_NAME), JSON.stringify({
4429
+ writeFileAtomicSync(join(dshHome, STATE_NAME), JSON.stringify({
3812
4430
  lastSyncAt: new Date().toISOString(),
3813
4431
  mode: 'push',
3814
4432
  repo,
3815
4433
  head: head.trim(),
3816
- }, null, 2) + '\n', 'utf8')
4434
+ }, null, 2) + '\n')
3817
4435
  } catch { }
3818
4436
  }
3819
4437
  finish(true, '')
@@ -3904,9 +4522,10 @@ async function handleAuto(req, res, config) {
3904
4522
  const extraArgs = ['-BackupDir', snap.dir]
3905
4523
  if (snap.kind !== 'profile') extraArgs.push('-SnapshotKind', snap.kind)
3906
4524
  if (snap.kind === 'plugin') extraArgs.push('-PluginDir', PLUGIN_ROOT)
4525
+ const closeNow = body.closeNow !== false
3907
4526
  const started = await spawnWatcher({
3908
4527
  mode: 'restore', repo, appRoot, dshHome, restart,
3909
- extraArgs,
4528
+ extraArgs, closeRequested: closeNow,
3910
4529
  })
3911
4530
  if (!started.ok) throw new Error(started.error)
3912
4531
  autoState.pending = { mode: 'restore', at: Date.now(), restart, watcherPid: started.pid, closeRequested: false, backupDir: snap.dir, snapshotKind: snap.kind }
@@ -3931,7 +4550,8 @@ async function handleAuto(req, res, config) {
3931
4550
  if (mode === 'push' && repoPhase(repo) !== 'ok') await ensurePushAllowed(repo, settings)
3932
4551
  // 拉取/推送做完都把客户端拉回来(用户要求"完成后自动启动 dsh"),仍受 autoRestart 开关约束
3933
4552
  const restart = body.restart !== false && settings.autoRestart !== false
3934
- 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 })
3935
4555
  if (!started.ok) throw new Error(started.error)
3936
4556
  autoState.pending = { mode, at: Date.now(), restart, watcherPid: started.pid, closeRequested: false }
3937
4557
  // 用户明确要求"现在就同步":排队后请求客户端退出(不带 /F,走正常关闭,配置能存下来)
@@ -4006,7 +4626,8 @@ function scheduleAutoStart(config) {
4006
4626
  ),
4007
4627
  )
4008
4628
  if (yes) {
4009
- 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 })
4010
4631
  if (started.ok) {
4011
4632
  autoState.pending = { mode: 'pull', at: Date.now(), restart: settings.autoRestart, watcherPid: started.pid, closeRequested: true }
4012
4633
  closeDsh()
@@ -4490,15 +5111,39 @@ async function handleWebdav(req, res, config) {
4490
5111
  return
4491
5112
  }
4492
5113
 
4493
- // 上传/下载都要动本机文件:没有仓库目录就没意义,先明确报错
5114
+ // 上传/下载都要动本机文件,但两者的前提不同:
5115
+ // upload 必须有内容(空目录没东西可传)
5116
+ // download 恰恰要把空目录填满 —— 新机器首次拉取就是这个场景,不能拒
4494
5117
  const repo = resolveRepo(config?.repoPath, dshHome).repo
4495
- if (!repo || !isDir(repo)) {
4496
- sendJson(res, 400, { ok: false, error: '本机仓库目录不存在(先在「本机仓库」卡里设置路径)' })
5118
+ if (!repo) {
5119
+ sendJson(res, 400, { ok: false, error: '还没有设置本机仓库目录(先在「本机仓库」卡里设置路径)' })
4497
5120
  return
4498
5121
  }
4499
- if (!isRepoDir(repo) && !isDir(join(repo, 'machines'))) {
4500
- sendJson(res, 400, { ok: false, error: `这个目录不像同步仓库:${repo}` })
4501
- 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
+ }
4502
5147
  }
4503
5148
 
4504
5149
  if (action === 'upload') {
@@ -4636,12 +5281,8 @@ async function handleRoots(req, res, config) {
4636
5281
  confirmed: [],
4637
5282
  updatedAt: new Date().toISOString(),
4638
5283
  }
4639
- const rawCustom = input.custom && typeof input.custom === 'object' ? input.custom : (prev.custom || {})
4640
- for (const [k, v] of Object.entries(rawCustom)) {
4641
- const key = String(k || '').trim()
4642
- const val = String(v == null ? '' : v).trim()
4643
- if (key && val) next.custom[key] = val
4644
- }
5284
+ const rawCustom = Object.prototype.hasOwnProperty.call(input, 'custom') ? input.custom : (prev.custom || {})
5285
+ next.custom = normalizeCustomRoots(rawCustom)
4645
5286
  // 校验:三个根都不能空、必须是绝对路径。目录不存在只提示不拒 —— 新机器上目标目录常常还没建。
4646
5287
  const warns = []
4647
5288
  for (const key of ['appRoot', 'dshHome', 'workspaceHome']) {
@@ -4669,7 +5310,7 @@ async function handleRoots(req, res, config) {
4669
5310
  next.confirmed = [...confirmed]
4670
5311
 
4671
5312
  mkdirSync(dirname(rootsPathOf(dshHome)), { recursive: true })
4672
- writeFileSync(rootsPathOf(dshHome), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
5313
+ writeFileAtomicSync(rootsPathOf(dshHome), `${JSON.stringify(next, null, 2)}\n`)
4673
5314
  // 根都确认了,待确认清单就没意义了:清掉,下次拉取不再拦
4674
5315
  try { if (existsSync(pendingPathOf(dshHome))) unlinkSync(pendingPathOf(dshHome)) } catch { }
4675
5316
 
@@ -4687,6 +5328,67 @@ async function handleRoots(req, res, config) {
4687
5328
  }
4688
5329
  }
4689
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
+ }
4690
5392
  /**
4691
5393
  * 问题反馈:落成仓库里的 feedback\<时间戳>-<id>.json,再 git add/commit/push 到云端。
4692
5394
  * 为什么用文件而不是 Issue:不依赖 API 令牌,另一台机器拉取后同样能在面板里看到;
@@ -4696,7 +5398,16 @@ async function handleRoots(req, res, config) {
4696
5398
  // 面板里提交 → 直接建 issue(label=feedback,正文附环境块);列表读 issue(含 open/closed);
4697
5399
  // 点「已解决」就 PATCH 成 closed。网络不通时先进本机待发队列,下次点「补发」再建 issue。
4698
5400
 
4699
- 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'])
4700
5411
  const GH_FEEDBACK_LABEL = 'feedback'
4701
5412
 
4702
5413
  /** 当前插件版本(读自己的 package.json;读不到就空串,不抛)。 */
@@ -4710,11 +5421,18 @@ function pluginVersion() {
4710
5421
  function ghPathOf(dshHome) { return join(dshHome, 'config-sync-gh.json') }
4711
5422
  function outboxPathOf(dshHome) { return join(dshHome, 'config-sync-feedback-outbox.json') }
4712
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
+
4713
5430
  function readGh(dshHome) {
4714
5431
  const j = readJson(ghPathOf(dshHome)) || {}
4715
5432
  return {
4716
5433
  token: String(j.token || ''),
4717
- repo: String(j.repo || GH_DEFAULT_REPO),
5434
+ tokenEnv: String(j.tokenEnv || '').trim(),
5435
+ repo: normalizeGhRepo(j.repo),
4718
5436
  login: String(j.login || ''),
4719
5437
  updatedAt: String(j.updatedAt || ''),
4720
5438
  }
@@ -4724,11 +5442,15 @@ function writeGh(dshHome, o) {
4724
5442
  const f = ghPathOf(dshHome)
4725
5443
  try { mkdirSync(dirname(f), { recursive: true }) } catch { }
4726
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')
4727
5448
  const body = {
4728
- token: String(o.token || ''),
4729
- 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),
4730
5452
  // 令牌没换就沿用之前认出来的账号,免得每轮都调 /user
4731
- login: String(o.login || prev.login || ''),
5453
+ login: hasLogin ? String(o.login || '') : prev.login,
4732
5454
  updatedAt: new Date().toISOString(),
4733
5455
  }
4734
5456
  writeFileSync(f, `${JSON.stringify(body, null, 2)}\n`, 'utf8')
@@ -4747,38 +5469,86 @@ function writeOutbox(dshHome, items) {
4747
5469
  return f
4748
5470
  }
4749
5471
 
4750
- /** 从本机 git 凭据里取一次 GitHub 令牌:用户平时 push 过,这里就不用再填。 */
4751
- function tokenFromGitCredential() {
5472
+ /** 从本机 git 凭据里取 GitHub 令牌与用户名:用户平时 push 过,这里就不用再填。 */
5473
+ function credFromGitCredential() {
4752
5474
  return new Promise((resolve) => {
4753
5475
  let p = null
4754
5476
  try {
4755
5477
  p = spawn(resolveGitExe(), ['credential', 'fill'], { windowsHide: true })
4756
- } catch { resolve(''); return }
5478
+ } catch { resolve({ token: '', username: '' }); return }
4757
5479
  let out = ''
4758
- const timer = setTimeout(() => { try { p.kill() } catch { } resolve('') }, 8000)
5480
+ const timer = setTimeout(() => { try { p.kill() } catch { } resolve({ token: '', username: '' }) }, 8000)
4759
5481
  p.stdout.on('data', (d) => { out += String(d) })
4760
- p.on('error', () => { clearTimeout(timer); resolve('') })
5482
+ p.on('error', () => { clearTimeout(timer); resolve({ token: '', username: '' }) })
4761
5483
  p.on('close', () => {
4762
5484
  clearTimeout(timer)
4763
- const m = out.match(/password=([^\r\n]+)/)
4764
- 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() : '' })
4765
5488
  })
4766
5489
  try { p.stdin.write('protocol=https\nhost=github.com\n\n'); p.stdin.end() } catch { }
4767
5490
  })
4768
5491
  }
4769
5492
 
4770
- /** 有存下来的令牌就用它,没有就向 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
+ */
4771
5523
  async function ghToken(config, dshHome) {
4772
5524
  const g = readGh(dshHome)
4773
- if (g.token) return g
4774
- const auto = await tokenFromGitCredential()
4775
- if (!auto) return g
4776
- writeGh(dshHome, { ...g, token: auto })
4777
- 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 || '' }
4778
5548
  }
4779
5549
 
4780
5550
  async function ghApi(pathname, options = {}) {
4781
- const { method = 'GET', token, body } = options
5551
+ const { method = 'GET', token, body, timeoutMs = 15000 } = options
4782
5552
  const url = pathname.startsWith('http') ? pathname : `https://api.github.com${pathname}`
4783
5553
  const headers = {
4784
5554
  Accept: 'application/vnd.github+json',
@@ -4792,11 +5562,28 @@ async function ghApi(pathname, options = {}) {
4792
5562
  headers['Content-Type'] = 'application/json; charset=utf-8'
4793
5563
  init.body = JSON.stringify(body)
4794
5564
  }
4795
- const res = await fetch(url, init)
4796
- const raw = await res.text()
4797
- let json = null
4798
- try { json = raw ? JSON.parse(raw) : null } catch { json = null }
4799
- 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
+ }
4800
5587
  }
4801
5588
 
4802
5589
  function issueToItem(it) {
@@ -4848,16 +5635,22 @@ function ownerOf(repo) {
4848
5635
  return String(repo || '').split('/')[0] || ''
4849
5636
  }
4850
5637
 
4851
- /** 令牌属于谁(GET /user)。结果缓存在 gh.json 里,不每轮都问。 */
5638
+ const ghIdentityCache = new Map()
5639
+ /** 令牌属于谁(GET /user)。按令牌哈希放内存缓存,不依赖落盘的旧账号。 */
4852
5640
  async function ghIdentity(token, dshHome, known) {
4853
- 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) || ''
4854
5644
  const r = await ghApi('/user', { token })
4855
5645
  const login = r.ok && r.json ? String(r.json.login || '') : ''
4856
5646
  if (login) {
4857
- const g = readGh(dshHome)
4858
- 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
4859
5652
  }
4860
- return login
5653
+ return String(known || '')
4861
5654
  }
4862
5655
 
4863
5656
  /**
@@ -5124,13 +5917,16 @@ async function handleFeedback(req, res, config) {
5124
5917
 
5125
5918
  if (req.method === 'GET') {
5126
5919
  try {
5920
+ if (url.searchParams.get('refresh') === '1') clearWinEnvCache()
5127
5921
  const g = await ghToken(config, dshHome)
5128
5922
  const outbox = readOutbox(dshHome)
5129
5923
  const owner = ownerOf(g.repo)
5130
- 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)))
5131
5926
  const base = {
5132
5927
  ok: true,
5133
5928
  repo: g.repo,
5929
+ defaultRepo: GH_DEFAULT_REPO,
5134
5930
  label: GH_FEEDBACK_LABEL,
5135
5931
  owner,
5136
5932
  login,
@@ -5138,13 +5934,18 @@ async function handleFeedback(req, res, config) {
5138
5934
  canClose: !!(login && owner && login.toLowerCase() === owner.toLowerCase()),
5139
5935
  connected: false,
5140
5936
  readAnon: false,
5141
- 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,
5142
5942
  items: [],
5943
+ counts: { open: 0, closed: 0, total: 0 },
5143
5944
  outbox: outbox.map((x) => ({ title: String(x.title || ''), createdAt: String(x.createdAt || '') })),
5144
5945
  version: pluginVersion(),
5145
5946
  ghFile: ghPathOf(dshHome),
5146
5947
  }
5147
- // 读:有令牌先带令牌(自己的账号、限额 5000/小时),失败或没令牌就退回匿名(公开仓库 60 次/小时)
5948
+ // 读:有令牌先带令牌(自己的账号、限额 5000/小时);网络本身不通时不重复打匿名请求,仅 HTTP 401/403 才退回匿名
5148
5949
  const attempts = g.token ? [g.token, ''] : ['']
5149
5950
  let lastError = ''
5150
5951
  for (const tok of attempts) {
@@ -5162,12 +5963,15 @@ async function handleFeedback(req, res, config) {
5162
5963
  items,
5163
5964
  counts,
5164
5965
  note: !tok
5165
- ? 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.'))
5166
5969
  : '',
5167
5970
  })
5168
5971
  return
5169
5972
  } catch (error) {
5170
5973
  lastError = String((error && error.message) || error)
5974
+ if (tok && /^0\s/.test(lastError)) break
5171
5975
  }
5172
5976
  }
5173
5977
  sendJson(res, 200, { ...base, error: lastError || t('读不到 issue 列表', 'Cannot read the issue list') })
@@ -5185,21 +5989,77 @@ async function handleFeedback(req, res, config) {
5185
5989
  const payload = raw.trim() ? JSON.parse(raw) : {}
5186
5990
  const g = await ghToken(config, dshHome)
5187
5991
 
5188
- // 1) 存令牌(填一次就够了;顺手用一次只读接口验证)
5992
+ // 1) 存令牌 / 绑定环境变量 / 换反馈仓库(用一次只读接口验证;绑定环境变量时绝不落盘令牌值)
5189
5993
  if (action === 'token') {
5190
- const token = String(payload.token || '').trim()
5994
+ clearWinEnvCache()
5191
5995
  const repo = String(payload.repo || g.repo || GH_DEFAULT_REPO).trim() || GH_DEFAULT_REPO
5192
- if (!token) throw new Error(t('令牌是空的', 'The token is empty'))
5193
- 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 })
5194
6050
  if (!probe.ok) throw new Error(`${probe.status} ${String((probe.json && probe.json.message) || '').slice(0, 160) || '令牌或仓库不对'}`)
5195
- const me = await ghIdentity(token, dshHome)
5196
- writeGh(dshHome, { token, repo, login: me })
6051
+ const me = await ghIdentity(verifyToken, dshHome)
6052
+ writeGh(dshHome, { ...saveFields, login: me })
5197
6053
  const owner = ownerOf(repo)
5198
6054
  sendJson(res, 200, {
5199
6055
  ok: true,
5200
6056
  connected: true,
6057
+ tokenPresent: true,
5201
6058
  repo,
5202
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)),
5203
6063
  login: me,
5204
6064
  owner,
5205
6065
  canClose: !!(me && owner && me.toLowerCase() === owner.toLowerCase()),