dsh-profile-config-sync 0.6.47 → 0.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +43 -2
- package/README.md +52 -5
- package/client.js +226 -38
- package/docs/CHANGELOG.md +1 -0
- package/docs/REFERENCE.md +39 -3
- package/index.js +696 -201
- package/package.json +4 -3
- package/release-notes.json +5 -4
- package/runtime/contract.mjs +10 -3
- package/runtime/conversations.mjs +433 -0
- package/runtime/extra-rules.mjs +238 -0
- package/runtime/install-plugin.mjs +279 -0
- package/runtime/install-plugin.ps1 +5 -6
- package/runtime/platform.mjs +198 -5
- package/runtime/porting.mjs +319 -0
- package/runtime/post-exit.mjs +347 -0
- package/runtime/post-exit.ps1 +7 -7
- package/runtime/settings-sources.mjs +46 -0
- package/runtime/sync-engine.mjs +1190 -52
- package/runtime/webdav.mjs +247 -24
- package/runtime/zip.mjs +156 -0
package/index.js
CHANGED
|
@@ -23,6 +23,12 @@ import { createRequire } from 'node:module'
|
|
|
23
23
|
import { gunzipSync } from 'node:zlib'
|
|
24
24
|
import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync, chmodSync } from 'node:fs'
|
|
25
25
|
import { writeFileAtomicSync } from './runtime/atomic-write.mjs'
|
|
26
|
+
import { SETTINGS_SOURCES, settingsSourcePath as settingsSourcePathOf, zeroVolatileFields } from './runtime/settings-sources.mjs'
|
|
27
|
+
import {
|
|
28
|
+
EXTRA_CONFIG_NAME, EXTRA_DEFAULT_EXCLUDE, EXTRA_DEFAULT_SKIP_DIRS, EXTRA_HARD_MAX_BYTES,
|
|
29
|
+
EXTRA_MANDATORY_EXCLUDES, EXTRA_MANDATORY_SKIP_DIRS, extraConfigPath, extraSkipReason,
|
|
30
|
+
readExtraConfig, topUpExtraMandatory, wildcardToRegex,
|
|
31
|
+
} from './runtime/extra-rules.mjs'
|
|
26
32
|
import { homedir, hostname, tmpdir } from 'node:os'
|
|
27
33
|
import { basename, dirname, isAbsolute, join, relative } from 'node:path'
|
|
28
34
|
import { fileURLToPath } from 'node:url'
|
|
@@ -37,10 +43,12 @@ import { setWorkspaceStateLive, setSessionStateLive } from './runtime/tools/work
|
|
|
37
43
|
// 0.4.0:跨端(Windows / macOS / Linux)。平台差异全部收敛在 runtime/platform.mjs,
|
|
38
44
|
// 这里只消费它的结论 —— 业务代码里不允许再出现 process.platform 分支。
|
|
39
45
|
import {
|
|
40
|
-
IS_WIN, OS, appRootCandidates, appRootLayout,
|
|
41
|
-
findGit, findSsh, hostNodeExe,
|
|
46
|
+
IS_WIN, OS, appRootCandidates, appRootLayout, asarPath, clientExecutable,
|
|
47
|
+
clientProcessPattern, defaultRepoPath, findGit, findSsh, hostNodeExe,
|
|
42
48
|
hostDshNodeModules as platformHostDshNodeModules,
|
|
43
|
-
isAppRoot as pfIsAppRoot, isFile as pfIsFile, platformFamily, platformLabel,
|
|
49
|
+
isAppRoot as pfIsAppRoot, isFile as pfIsFile, normalizeAppRoot, platformFamily, platformLabel,
|
|
50
|
+
postExitScriptName, readAppVersion as platformReadAppVersion,
|
|
51
|
+
readElectronVersion as platformReadElectronVersion, repoPathProblem,
|
|
44
52
|
normalizeSyncExtraPaths,
|
|
45
53
|
} from './runtime/platform.mjs'
|
|
46
54
|
// 0.4.0:客户端身份(仓库里 machines/<id>.json)—— 跨端不分叉仓库,只登记「谁推的」
|
|
@@ -49,7 +57,9 @@ import { listMachines } from './runtime/machines.mjs'
|
|
|
49
57
|
import { checkContract, readContract } from './runtime/contract.mjs'
|
|
50
58
|
// 0.4.0:WebDAV 通道(第二种同步方式,与 git 共用同一份仓库格式)
|
|
51
59
|
import {
|
|
52
|
-
downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive,
|
|
60
|
+
downloadRepo, isSecureUrl, normalizeWebdav, sanitizeUserAgent, testConnection, uploadRepo, webdavActive,
|
|
61
|
+
purgeForbiddenFromCloud,
|
|
62
|
+
purgeStaleLocksFromCloud,
|
|
53
63
|
} from './runtime/webdav.mjs'
|
|
54
64
|
|
|
55
65
|
const pluginRequire = createRequire(import.meta.url)
|
|
@@ -64,6 +74,8 @@ const ROUTE_CONFLICT = '/config-sync/conflict'
|
|
|
64
74
|
// 0.3.30:跨机路径确认(每台机器把自己的根目录报给插件一次)与问题反馈(落仓库 feedback\ 再推 GitHub)
|
|
65
75
|
const ROUTE_ROOTS = '/config-sync/roots'
|
|
66
76
|
const ROUTE_FEEDBACK = '/config-sync/feedback'
|
|
77
|
+
/** 反馈请求体上限:4 个附件 × 20 MB 的 base64(约 27 MB/个)+ 余量。 */
|
|
78
|
+
const ROUTE_FEEDBACK_MAX_BODY = 160 * 1024 * 1024
|
|
67
79
|
// 0.3.76:会话投影缓存守卫(GET 只读扫描 / POST scan|sweep|clear|busy)
|
|
68
80
|
const ROUTE_CACHE_GUARD = '/config-sync/cache-guard'
|
|
69
81
|
// 0.3.76:工作区显示状态(GET 读 / POST workspace 三态 | session 独立隐藏)
|
|
@@ -275,6 +287,12 @@ function resolveAppRoot(explicit) {
|
|
|
275
287
|
for (const c of candidates) {
|
|
276
288
|
if (pfIsAppRoot(c)) return c
|
|
277
289
|
}
|
|
290
|
+
// 用户可能把 appRoot 填成 .app 内部路径(/Applications/X.app/Contents/Resources)。
|
|
291
|
+
// 第二轮把候选归一成「客户端根」再判一次,别让一个多余的后缀把整块功能锁死。
|
|
292
|
+
for (const c of candidates) {
|
|
293
|
+
const n = normalizeAppRoot(c)
|
|
294
|
+
if (n && n !== c && pfIsAppRoot(n)) return n
|
|
295
|
+
}
|
|
278
296
|
// 一个都认不出就返回空,让上层明确报错;绝不把插件自己所在的那一级当成客户端根。
|
|
279
297
|
return ''
|
|
280
298
|
}
|
|
@@ -292,11 +310,14 @@ function readAppMeta(appRoot) {
|
|
|
292
310
|
const res = layout.resources || join(appRoot, 'resources')
|
|
293
311
|
const plain = readJson(join(res, 'app', 'package.json'))
|
|
294
312
|
if (plain) return plain
|
|
295
|
-
|
|
296
|
-
//
|
|
313
|
+
// 打包版:优先交给平台层按 asar 头解析(macOS 的 asar 在 Contents/Resources 下,
|
|
314
|
+
// 路径由 asarPath 统一算,不再各处硬拼 <root>/resources)
|
|
315
|
+
const viaPlatform = platformReadAppVersion(appRoot)
|
|
316
|
+
if (viaPlatform) return { version: viaPlatform }
|
|
317
|
+
const asar = asarPath(appRoot)
|
|
297
318
|
const viaMount = readJson(join(asar, 'dsh', 'package.json'))
|
|
298
319
|
if (viaMount) return viaMount
|
|
299
|
-
if (!pfIsFile(asar)) return null
|
|
320
|
+
if (!asar || !pfIsFile(asar)) return null
|
|
300
321
|
try {
|
|
301
322
|
const fd = openSync(asar, 'r')
|
|
302
323
|
try {
|
|
@@ -364,6 +385,9 @@ function readSettings(dshHome) {
|
|
|
364
385
|
webdavPass: typeof raw.webdavPass === 'string' ? raw.webdavPass : '',
|
|
365
386
|
// WebDAV 上存放同步包的目录(相对根,默认 dsh-config-sync)
|
|
366
387
|
webdavDir: typeof raw.webdavDir === 'string' ? raw.webdavDir : '',
|
|
388
|
+
// 0.6.48:自定义 User-Agent。部分第三方 WebDAV 按 UA 放行/拦截,默认 undici UA 会被拒。
|
|
389
|
+
// 留空 = 不发 User-Agent 头(与 0.6.47 之前的行为一致)。
|
|
390
|
+
webdavUserAgent: typeof raw.webdavUserAgent === 'string' ? raw.webdavUserAgent : '',
|
|
367
391
|
}
|
|
368
392
|
}
|
|
369
393
|
|
|
@@ -394,6 +418,7 @@ function writeSettings(dshHome, s) {
|
|
|
394
418
|
webdavUser: s.webdavUser || '',
|
|
395
419
|
webdavPass: s.webdavPass || '',
|
|
396
420
|
webdavDir: s.webdavDir || '',
|
|
421
|
+
webdavUserAgent: s.webdavUserAgent || '',
|
|
397
422
|
}
|
|
398
423
|
const payload = JSON.stringify(merged, null, 2) + '\n'
|
|
399
424
|
// 这份文件里有 WebDAV 密码与更新令牌:POSIX 上收紧到仅本人可读写(Windows 靠用户目录 ACL,0o600 是空操作)
|
|
@@ -498,7 +523,12 @@ function resolveRepo(explicit, dshHome) {
|
|
|
498
523
|
}
|
|
499
524
|
|
|
500
525
|
const home = homedir()
|
|
501
|
-
|
|
526
|
+
// 0.6.49:自动探测的候选随平台走 —— 原来前三个是 Windows 盘符(D:/G:/C:),
|
|
527
|
+
// macOS 上等于扫了三个永远不存在的位置;现在 Windows 保原样,POSIX 只探自己语义下的路径。
|
|
528
|
+
const guesses = IS_WIN
|
|
529
|
+
? ['D:\\dsh-config', 'G:\\dsh-config', 'C:\\dsh-config', join(home, 'dsh-config')]
|
|
530
|
+
: [defaultRepoPath(), join(home, 'Documents', 'dsh-config'), join(home, 'dsh-config')]
|
|
531
|
+
for (const c of guesses) {
|
|
502
532
|
if (isRepoDir(c)) {
|
|
503
533
|
tried.push(`自动探测:${c}`)
|
|
504
534
|
return { repo: c, source: 'auto' }
|
|
@@ -728,7 +758,8 @@ function readBundles(profileDir) {
|
|
|
728
758
|
let asarNamesCache = new Map()
|
|
729
759
|
function asarBundleNames(appRoot) {
|
|
730
760
|
if (!appRoot) return null
|
|
731
|
-
const asar =
|
|
761
|
+
const asar = asarPath(appRoot)
|
|
762
|
+
if (!asar) return null
|
|
732
763
|
if (asarNamesCache.has(asar)) return asarNamesCache.get(asar)
|
|
733
764
|
let names = null
|
|
734
765
|
try {
|
|
@@ -866,7 +897,9 @@ function inspectBackup(dshHome, rootOverride) {
|
|
|
866
897
|
entryNames = list.slice(0, 6).map((e) => e.name)
|
|
867
898
|
} catch { }
|
|
868
899
|
}
|
|
869
|
-
|
|
900
|
+
// at 用整型毫秒:mtimeMs 是浮点,直接进 JSON 会变成 1795845400410.4312 这种小数,
|
|
901
|
+
// 面板与读结果文件的地方都得再处理一次
|
|
902
|
+
all.push({ name, dir, at: Math.round(st.mtimeMs), files: null, bytes: null, hasProfile, plugins, bundles, kind, entries, entryNames })
|
|
870
903
|
} catch { }
|
|
871
904
|
}
|
|
872
905
|
all.sort((a, b) => b.at - a.at)
|
|
@@ -1107,7 +1140,9 @@ async function inspect(config) {
|
|
|
1107
1140
|
|
|
1108
1141
|
const localApp = readAppMeta(appRoot)
|
|
1109
1142
|
const localVersion = typeof localApp?.version === 'string' ? localApp.version : ''
|
|
1110
|
-
|
|
1143
|
+
// 0.6.49:Electron 版本统一交给 platform.mjs(macOS 没有 <root>/version 文件,
|
|
1144
|
+
// 原来读出来永远是空串,面板那一格只剩 "app 0.2.2-rc.5 /")
|
|
1145
|
+
const electronVersion = platformReadElectronVersion(appRoot) || readText(join(appRoot, 'version')).trim()
|
|
1111
1146
|
const contract = readJson(join(repo, 'profile', 'host-contract.json'))
|
|
1112
1147
|
const contractVersion = typeof contract?.appVersion === 'string' ? contract.appVersion : ''
|
|
1113
1148
|
|
|
@@ -1281,10 +1316,15 @@ async function inspect(config) {
|
|
|
1281
1316
|
advice.push(t('待推送扫描没跑完(文件太多或超时),这次的数字可能偏小:可再刷新一次', 'The pending scan did not finish (too many files or a timeout); the count may be low — refresh again.'))
|
|
1282
1317
|
} else if (local && Array.isArray(local.engineGroups)) {
|
|
1283
1318
|
// 非 Windows:这句话只覆盖引擎真会同步的四组,不能写成「仓库与本机一致」
|
|
1284
|
-
advice.push(
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1319
|
+
advice.push(local.engineAllGroups
|
|
1320
|
+
? t(
|
|
1321
|
+
`这台机器走跨平台引擎,${local.engineGroups.length} 组内容(${local.engineGroups.join(' / ')})都与仓库一致`,
|
|
1322
|
+
`This machine uses the cross-platform engine; all ${local.engineGroups.length} groups (${local.engineGroups.join(' / ')}) match the repo.`,
|
|
1323
|
+
)
|
|
1324
|
+
: t(
|
|
1325
|
+
`这台机器走跨平台引擎,只同步 ${local.engineGroups.join(' / ')},这几组与仓库一致(其余组要 Windows 版才会同步)`,
|
|
1326
|
+
`This machine uses the cross-platform engine, which syncs only ${local.engineGroups.join(' / ')}; those groups match the repo (the rest sync on Windows).`,
|
|
1327
|
+
))
|
|
1288
1328
|
} else {
|
|
1289
1329
|
advice.push(t('仓库与本机一致,没有待办', 'The repo matches this machine — nothing to do.'))
|
|
1290
1330
|
}
|
|
@@ -1385,6 +1425,9 @@ async function inspect(config) {
|
|
|
1385
1425
|
lastCheckError: autoState.lastCheckError,
|
|
1386
1426
|
drift: autoState.drift,
|
|
1387
1427
|
pending: autoState.pending,
|
|
1428
|
+
// 0.6.49:后台自动拉取(启动时那条,没有请求也没有面板)在 macOS 上不再弹原生框,
|
|
1429
|
+
// 而是把这个提示挂出来,由面板的「立即拉取」接手 —— 否则对话框被窗口挡住就等于永不发生。
|
|
1430
|
+
pullPrompt: autoState.pullPrompt || null,
|
|
1388
1431
|
watcherStartedAt: autoState.watcherStartedAt,
|
|
1389
1432
|
script: autoScript(dshHome, repo),
|
|
1390
1433
|
// post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
|
|
@@ -1404,7 +1447,7 @@ async function inspect(config) {
|
|
|
1404
1447
|
// 0.4.0:跨端信息。面板据此显示「本机平台 / 仓库契约来自哪个平台 / 已登记哪些机器」。
|
|
1405
1448
|
// 这里刻意不显示本机绝对路径的明文(那是本机私有),只给平台族与版本。
|
|
1406
1449
|
platform: (() => {
|
|
1407
|
-
const contract = repo ? readContract(repo) : null
|
|
1450
|
+
const contract = repo ? readContract(repo, process.platform) : null
|
|
1408
1451
|
const local = {
|
|
1409
1452
|
os: OS,
|
|
1410
1453
|
osLabel: platformLabel(),
|
|
@@ -1445,6 +1488,8 @@ async function inspect(config) {
|
|
|
1445
1488
|
url: w.url,
|
|
1446
1489
|
user: w.user,
|
|
1447
1490
|
dir: w.dir,
|
|
1491
|
+
// 0.6.48:UA(留空 = 不发 User-Agent 头)
|
|
1492
|
+
userAgent: w.ua,
|
|
1448
1493
|
secure: isSecureUrl(w.url),
|
|
1449
1494
|
}
|
|
1450
1495
|
})(),
|
|
@@ -1509,14 +1554,21 @@ function sendJson(res, code, body) {
|
|
|
1509
1554
|
} catch { /* 客户端已断开就忽略 */ }
|
|
1510
1555
|
}
|
|
1511
1556
|
|
|
1512
|
-
function readBody(req) {
|
|
1557
|
+
function readBody(req, maxBytes = 64 * 1024) {
|
|
1513
1558
|
return new Promise((resolve, reject) => {
|
|
1514
|
-
|
|
1559
|
+
// 用数组收块、最后再 join:反馈路由的请求体上限放宽到 160 MB,
|
|
1560
|
+
// 逐块 `data += c` 会在这种体量下反复复制整条字符串(O(n²)),内存也翻倍。
|
|
1561
|
+
const chunks = []
|
|
1562
|
+
let total = 0
|
|
1515
1563
|
req.on('data', (c) => {
|
|
1516
|
-
|
|
1517
|
-
|
|
1564
|
+
const buf = Buffer.isBuffer(c) ? c : Buffer.from(c)
|
|
1565
|
+
total += buf.length
|
|
1566
|
+
// 0.6.48:上限可放宽(反馈带附件时 base64 会超 64 KB),默认值不变,
|
|
1567
|
+
// 其它路由的行为一个字节都不动。
|
|
1568
|
+
if (total > maxBytes) { reject(new Error('body too large')); req.destroy() }
|
|
1569
|
+
else chunks.push(buf)
|
|
1518
1570
|
})
|
|
1519
|
-
req.on('end', () => resolve(
|
|
1571
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
1520
1572
|
req.on('error', reject)
|
|
1521
1573
|
})
|
|
1522
1574
|
}
|
|
@@ -1784,13 +1836,15 @@ function shHead(title) {
|
|
|
1784
1836
|
* 进程守护:DSH 还在跑就拒绝执行。
|
|
1785
1837
|
* 用 pgrep -f 匹配客户端可执行文件;找不到 pgrep 时跳过(不假装守护成功)。
|
|
1786
1838
|
*/
|
|
1787
|
-
function shProcGuard() {
|
|
1788
|
-
|
|
1789
|
-
|
|
1839
|
+
function shProcGuard(appRoot) {
|
|
1840
|
+
// 0.6.49:用**客户端可执行文件路径**匹配,不用进程名。
|
|
1841
|
+
// 按名字匹配会命中我们自己的 Node 执行体(它的命令行里带着 ".../DeepSeek Harness.app/..."),
|
|
1842
|
+
// 于是一个已经退出的场景也会被判成「还在运行」,脚本永远拒绝执行。
|
|
1843
|
+
const pattern = clientProcessPattern(appRoot)
|
|
1790
1844
|
return [
|
|
1791
1845
|
'# 先确认 DSH 已退出:运行中 capture 会读到写了一半的 cordis.patch.yml',
|
|
1792
1846
|
'if command -v pgrep >/dev/null 2>&1; then',
|
|
1793
|
-
` if pgrep -f
|
|
1847
|
+
` if pgrep -f ${shQuote(pattern)} >/dev/null 2>&1; then`,
|
|
1794
1848
|
' echo "[X] DSH 还在运行,请先完全退出(窗口 + 托盘)再重试。"',
|
|
1795
1849
|
' exit 1',
|
|
1796
1850
|
' fi',
|
|
@@ -1843,6 +1897,29 @@ function buildSh(config, action, repo, appRoot, dshHome, state = {}) {
|
|
|
1843
1897
|
const note = target === 'push'
|
|
1844
1898
|
? String(state.message || '').replace(/["\r\n]/g, ' ').trim().slice(0, 120)
|
|
1845
1899
|
: ''
|
|
1900
|
+
// 提示与 .cmd 版同语义(面板拿 payload.warnings 提示「本机领先,别点错」)。
|
|
1901
|
+
// 0.6.49 之前 buildSh 直接不返回这两个字段,于是 macOS 面板上永远看不到这些提醒。
|
|
1902
|
+
const warnings = []
|
|
1903
|
+
if (target === 'pull') {
|
|
1904
|
+
const ahead = Number(state.ahead) || 0
|
|
1905
|
+
const dirty = Number(state.dirty) || 0
|
|
1906
|
+
if (ahead > 0) {
|
|
1907
|
+
warnings.push(t(
|
|
1908
|
+
`本机领先远端 ${ahead} 个提交(还没推送),拉取后这些改动在仓库里仍然缺失`,
|
|
1909
|
+
`This machine is ${ahead} commit(s) ahead (not pushed yet); after pulling, those changes are still missing from the repo.`,
|
|
1910
|
+
))
|
|
1911
|
+
}
|
|
1912
|
+
if (dirty > 0) {
|
|
1913
|
+
warnings.push(t(
|
|
1914
|
+
`工作区有 ${dirty} 项未提交,拉取会用仓库版本覆盖对应的本机文件`,
|
|
1915
|
+
`${dirty} uncommitted change(s): pulling overwrites the matching local files with the repo version.`,
|
|
1916
|
+
))
|
|
1917
|
+
}
|
|
1918
|
+
warnings.push(t(
|
|
1919
|
+
'拉取 = 拉远端 + apply 到本机:会用仓库里的版本覆盖本机配置',
|
|
1920
|
+
'Pull = fetch the remote and apply it locally: the repo version overwrites the local config.',
|
|
1921
|
+
))
|
|
1922
|
+
}
|
|
1846
1923
|
|
|
1847
1924
|
const confirmBlock = target === 'pull'
|
|
1848
1925
|
? [
|
|
@@ -1858,60 +1935,137 @@ function buildSh(config, action, repo, appRoot, dshHome, state = {}) {
|
|
|
1858
1935
|
]
|
|
1859
1936
|
: []
|
|
1860
1937
|
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1938
|
+
// 还原:生成时就挑好快照并写进脚本(与 .cmd 版同语义)。
|
|
1939
|
+
// 0.6.49 之前 POSIX 的还原脚本只是裸调一次 restore —— 既不显示用的是哪份快照、
|
|
1940
|
+
// 也不先 dry-run、更没有确认(.cmd 版三样都有);响应里也没有 backup 字段,面板拿不到快照信息。
|
|
1941
|
+
let backupInfo = null
|
|
1942
|
+
const body = []
|
|
1943
|
+
if (isRestore) {
|
|
1944
|
+
const settings = readSettings(dshHome)
|
|
1945
|
+
const backup = inspectBackup(dshHome, backupRootOf(dshHome, settings))
|
|
1946
|
+
const picked = String(state.backupDir || '')
|
|
1947
|
+
const pickedSnap = picked ? (backup.snapshots || []).find((sn) => sn.dir === picked) : null
|
|
1948
|
+
const chosen = picked || backup.latest || ''
|
|
1949
|
+
const kind = String(state.snapshotKind || (pickedSnap ? pickedSnap.kind : '') || '')
|
|
1950
|
+
const restoreState = { ...state, backupDir: chosen, snapshotKind: kind }
|
|
1951
|
+
backupInfo = {
|
|
1952
|
+
dir: chosen, root: backup.root,
|
|
1953
|
+
at: pickedSnap ? pickedSnap.at : backup.latestAt,
|
|
1954
|
+
count: backup.count, files: pickedSnap ? pickedSnap.files : backup.latestFiles,
|
|
1955
|
+
}
|
|
1956
|
+
const drySupported = engineSupportsDryRun(engine)
|
|
1957
|
+
const dry = drySupported
|
|
1958
|
+
? buildShRestoreInvocation({ engine, nodeExe, common, state: restoreState, extra: ['-DryRun'] })
|
|
1959
|
+
: []
|
|
1960
|
+
const real = buildShRestoreInvocation({ engine, nodeExe, common, state: restoreState })
|
|
1961
|
+
body.push(
|
|
1962
|
+
chosen
|
|
1963
|
+
? `echo ${shQuote(`备份快照:${chosen}`)}`
|
|
1964
|
+
: `echo ${shQuote(`备份快照:${backup.root}(生成脚本时这里还没有快照)`)}`,
|
|
1965
|
+
chosen
|
|
1966
|
+
? `echo ${shQuote(`快照时间:${new Date(backupInfo.at || Date.now()).toLocaleString('zh-CN', { hour12: false })} 备份根下共 ${backup.count} 份`
|
|
1967
|
+
// files 可能是 null(体积/文件数不递归统计,见 inspectBackup)——别把 null 印成「含 null 个文件」
|
|
1968
|
+
+ (typeof backupInfo.files === 'number' && Number.isFinite(backupInfo.files)
|
|
1969
|
+
? `,这份含 ${backupInfo.files} 个文件` : '(文件数未统计)'))}`
|
|
1970
|
+
: `echo ${shQuote('执行时由 sync-engine.mjs 自动取该目录下最新一份;若那时仍为空,会提示你先跑一次拉取。')}`,
|
|
1971
|
+
'',
|
|
1972
|
+
...(drySupported
|
|
1973
|
+
? [`echo ${shQuote('[第一步] 只看不动,先打印还原计划:')}`, ...dry]
|
|
1974
|
+
: [`echo ${shQuote('[!] 这个执行体还不认 -DryRun(仓库里那份偏旧):跳过计划预览;先推送一次即可刷新它。')}`]),
|
|
1975
|
+
'echo',
|
|
1976
|
+
...restoreConfirmBlock(),
|
|
1977
|
+
`echo ${shQuote('[第二步] 开始还原(会先把当前 profile 另存一份再覆盖):')}`,
|
|
1978
|
+
...real,
|
|
1979
|
+
)
|
|
1980
|
+
} else {
|
|
1981
|
+
body.push(
|
|
1982
|
+
...confirmBlock,
|
|
1864
1983
|
`${shQuote(nodeExe)} ${shQuote(engine)} ${target} ${common.join(' ')}` +
|
|
1865
|
-
|
|
1866
|
-
|
|
1984
|
+
(note ? ` -Message ${shQuote(note)}` : ''),
|
|
1985
|
+
)
|
|
1986
|
+
}
|
|
1867
1987
|
|
|
1988
|
+
const headWhat = isRestore
|
|
1989
|
+
? t('把本机 profile 退回到下面这个快照(先留底、再覆盖、再核对依赖)。',
|
|
1990
|
+
'Roll the local profile back to the snapshot below (copy aside, restore, then verify dependencies).')
|
|
1991
|
+
: `会先确认 DSH 是否已退出,再执行「${label}」。`
|
|
1868
1992
|
const text = [
|
|
1869
|
-
...shHead(
|
|
1870
|
-
...shProcGuard(),
|
|
1993
|
+
...shHead(headWhat),
|
|
1994
|
+
...shProcGuard(appRoot),
|
|
1871
1995
|
...envLines,
|
|
1872
1996
|
'',
|
|
1873
|
-
...
|
|
1874
|
-
...invocation,
|
|
1997
|
+
...body,
|
|
1875
1998
|
'',
|
|
1876
|
-
|
|
1999
|
+
`echo ${shQuote(isRestore ? '执行结束。确认无误后再启动 DSH。' : '执行结束。若为拉取,确认无误后启动 DSH。')}`,
|
|
1877
2000
|
].join('\n')
|
|
1878
2001
|
|
|
1879
2002
|
const fileName = isRestore
|
|
1880
|
-
? (state
|
|
2003
|
+
? (pickedName(state))
|
|
1881
2004
|
: `同步-${target === 'push' ? '推送' : '拉取'}.sh`
|
|
1882
2005
|
const path = join(repo, fileName)
|
|
1883
2006
|
writeFileSync(path, text, 'utf8')
|
|
1884
2007
|
try { chmodSync(path, 0o755) } catch { /* Windows 上没意义,忽略 */ }
|
|
1885
|
-
|
|
2008
|
+
const result = {
|
|
1886
2009
|
action: isRestore ? 'restore' : target,
|
|
1887
2010
|
label: isRestore ? t('还原(本机 → 快照)', 'Restore (machine → snapshot)') : label,
|
|
1888
2011
|
path,
|
|
1889
|
-
command:
|
|
2012
|
+
command: body.filter((l) => /sync-engine\.mjs/.test(l)).pop() || '',
|
|
2013
|
+
warnings,
|
|
2014
|
+
message: note,
|
|
1890
2015
|
platform: 'posix',
|
|
1891
2016
|
}
|
|
2017
|
+
if (backupInfo) result.backup = backupInfo
|
|
2018
|
+
return result
|
|
2019
|
+
}
|
|
2020
|
+
|
|
2021
|
+
/** 还原脚本文件名:面板点某一行的还原时带快照名,多份脚本互不覆盖。 */
|
|
2022
|
+
function pickedName(state) {
|
|
2023
|
+
return state.snapshotName ? `同步-还原-${state.snapshotName}.sh` : '同步-还原.sh'
|
|
1892
2024
|
}
|
|
1893
2025
|
|
|
1894
2026
|
/** 还原脚本的命令拼装(POSIX)。 */
|
|
1895
|
-
function buildShRestoreInvocation({ engine, nodeExe, common, state }) {
|
|
2027
|
+
function buildShRestoreInvocation({ engine, nodeExe, common, state, extra = [] }) {
|
|
1896
2028
|
const args = [...common]
|
|
1897
2029
|
if (state.backupDir) args.push(`-BackupDir ${shQuote(state.backupDir)}`)
|
|
1898
2030
|
if (state.snapshotKind && state.snapshotKind !== 'profile') {
|
|
1899
2031
|
args.push(`-SnapshotKind ${shQuote(state.snapshotKind)}`)
|
|
1900
2032
|
}
|
|
2033
|
+
args.push(...extra)
|
|
1901
2034
|
return [`${shQuote(nodeExe)} ${shQuote(engine)} restore ${args.join(' ')}`]
|
|
1902
2035
|
}
|
|
1903
2036
|
|
|
2037
|
+
/** 还原的确认守卫(POSIX):--yes 免确认,否则读一行 y。 */
|
|
2038
|
+
function restoreConfirmBlock() {
|
|
2039
|
+
return [
|
|
2040
|
+
'if [ "${1:-}" = "--yes" ]; then',
|
|
2041
|
+
' :',
|
|
2042
|
+
'else',
|
|
2043
|
+
' printf "按上面的计划执行还原?(y/N) "',
|
|
2044
|
+
' read -r GO',
|
|
2045
|
+
' case "$GO" in y|Y) ;; *) echo "没有收到确认(y),已退出:本机什么都没改。"; exit 0 ;; esac',
|
|
2046
|
+
'fi',
|
|
2047
|
+
'',
|
|
2048
|
+
]
|
|
2049
|
+
}
|
|
2050
|
+
|
|
1904
2051
|
/**
|
|
1905
2052
|
* 挑执行引擎:优先仓库里的 sync-engine.mjs(随仓库更新),
|
|
1906
2053
|
* 其次插件自带的 runtime\(新机器刚装、仓库还没拉下来时)。
|
|
1907
2054
|
* 找不到返回空串,调用方据此明确报错,不生成一个必然失败的脚本。
|
|
1908
2055
|
*/
|
|
1909
2056
|
function pickEngine(repo) {
|
|
1910
|
-
|
|
1911
|
-
|
|
2057
|
+
// 0.6.49:插件自带的执行体优先。旧顺序是仓库优先(理由:随仓库更新),但实测代价太大 ——
|
|
2058
|
+
// 仓库里那份可能是老版本,它不认识新参数(-DryRun 被当成未知参数忽略,还原脚本的
|
|
2059
|
+
// 「第一步只看不动」直接变成真还原)。插件自带的永远是「正在跑的这份代码」,其余从属。
|
|
1912
2060
|
const fromPlugin = join(pluginRoot(), 'runtime', 'sync-engine.mjs')
|
|
1913
2061
|
if (isFile(fromPlugin)) return fromPlugin
|
|
1914
|
-
|
|
2062
|
+
const fromRepo = join(repo, 'sync-engine.mjs')
|
|
2063
|
+
return isFile(fromRepo) ? fromRepo : ''
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
/** 执行体是否认 -DryRun(老版本的仓库执行体不认,别让「计划」变成真跑)。 */
|
|
2067
|
+
function engineSupportsDryRun(engine) {
|
|
2068
|
+
try { return readFileSync(engine, 'utf8').includes('DryRun') } catch { return false }
|
|
1915
2069
|
}
|
|
1916
2070
|
|
|
1917
2071
|
/* ============================ 自动同步 / 自动推送 ============================
|
|
@@ -1948,10 +2102,20 @@ const autoState = {
|
|
|
1948
2102
|
}
|
|
1949
2103
|
|
|
1950
2104
|
function autoScript(dshHome, repo) {
|
|
1951
|
-
|
|
2105
|
+
// 0.6.49:执行体随平台走 —— Windows 用 post-exit.ps1,macOS / Linux 用 post-exit.mjs。
|
|
2106
|
+
// 原来这里只找 .ps1,于是非 Windows 上 autoScript() 恒为空,spawnWatcher 直接返回
|
|
2107
|
+
// 「插件与仓库里都没有 post-exit.ps1,无法排队」—— 退出后推送/拉取/还原/更新整条链路都是死的。
|
|
2108
|
+
const name = postExitScriptName()
|
|
2109
|
+
const fromPlugin = join(pluginRoot(), 'runtime', name)
|
|
1952
2110
|
if (isFile(fromPlugin)) return fromPlugin
|
|
1953
|
-
const fromRepo = join(repo || '',
|
|
1954
|
-
|
|
2111
|
+
const fromRepo = join(repo || '', name)
|
|
2112
|
+
if (isFile(fromRepo)) return fromRepo
|
|
2113
|
+
// 兼容老仓库(里面只有 .ps1):Windows 上仍能退回它,POSIX 上不能(跑不起来)
|
|
2114
|
+
if (IS_WIN) {
|
|
2115
|
+
const legacy = join(repo || '', 'post-exit.ps1')
|
|
2116
|
+
if (isFile(legacy)) return legacy
|
|
2117
|
+
}
|
|
2118
|
+
return ''
|
|
1955
2119
|
}
|
|
1956
2120
|
|
|
1957
2121
|
/**
|
|
@@ -2032,6 +2196,10 @@ async function checkDrift(repo) {
|
|
|
2032
2196
|
|
|
2033
2197
|
/** 系统确认框(立在 DSH 窗口前面,不开面板也看得见)。Yes → true。 */
|
|
2034
2198
|
function askConfirm(title, text) {
|
|
2199
|
+
// 0.6.49:POSIX 上用 osascript 的 display dialog。原来只会 spawn powershell.exe,
|
|
2200
|
+
// macOS 上 'error' 事件直接 resolve(false) —— 自动拉取的确认框永远等于「用户点了取消」,
|
|
2201
|
+
// 更新(apply)流程也永远走不到安装那一步。
|
|
2202
|
+
if (!IS_WIN) return askConfirmPosix(title, text)
|
|
2035
2203
|
return new Promise((resolve) => {
|
|
2036
2204
|
// 参数走 spawn 的数组形式,不经过 shell 解析,所以文本里的引号/换行不会被二次解释。
|
|
2037
2205
|
const safe = (s) => String(s).replace(/'/g, "''")
|
|
@@ -2052,6 +2220,35 @@ function askConfirm(title, text) {
|
|
|
2052
2220
|
})
|
|
2053
2221
|
}
|
|
2054
2222
|
|
|
2223
|
+
/**
|
|
2224
|
+
* POSIX 版确认框:AppleScript 的 display dialog。
|
|
2225
|
+
* 两个按钮「取消 / 继续」,默认「继续」;回车=继续,Esc/取消=取消。
|
|
2226
|
+
* 脚本从 stdin 读,免得把中文与引号拼进 -e 参数时被 shell/AppleScript 二次解释。
|
|
2227
|
+
*/
|
|
2228
|
+
function askConfirmPosix(title, text) {
|
|
2229
|
+
return new Promise((resolve) => {
|
|
2230
|
+
if (!isFile('/usr/bin/osascript')) { resolve(false); return }
|
|
2231
|
+
// AppleScript 字符串就是 "...":用 JSON.stringify 得到同样语义的转义(\" \\ \n)
|
|
2232
|
+
const asStr = (s) => JSON.stringify(String(s == null ? '' : s))
|
|
2233
|
+
const script = [
|
|
2234
|
+
'try',
|
|
2235
|
+
` display dialog ${asStr(text)} with title ${asStr(title)} buttons {"取消", "继续"} default button "继续" with icon caution`,
|
|
2236
|
+
' return "continue"',
|
|
2237
|
+
'on error number -128',
|
|
2238
|
+
' return "cancel"',
|
|
2239
|
+
'end try',
|
|
2240
|
+
].join('\n')
|
|
2241
|
+
let out = ''
|
|
2242
|
+
const child = spawn('/usr/bin/osascript', ['-'], { stdio: ['pipe', 'pipe', 'ignore'] })
|
|
2243
|
+
child.on('error', () => resolve(false))
|
|
2244
|
+
child.stdout.on('data', (c) => { out += c })
|
|
2245
|
+
child.on('close', () => resolve(/continue/.test(out)))
|
|
2246
|
+
try { child.stdin.end(script, 'utf8') } catch { resolve(false) }
|
|
2247
|
+
const timer = setTimeout(() => { try { child.kill() } catch { } resolve(false) }, 12 * 60 * 1000)
|
|
2248
|
+
try { timer.unref?.() } catch { }
|
|
2249
|
+
})
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2055
2252
|
/**
|
|
2056
2253
|
* 找 powershell 的绝对路径。
|
|
2057
2254
|
* 不能只写 'powershell.exe' 靠 PATH:Electron 主进程继承的 PATH 可能被裁剪(本机实测就是
|
|
@@ -2108,11 +2305,19 @@ function psWinArg(value) {
|
|
|
2108
2305
|
*/
|
|
2109
2306
|
async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [], closeRequested = false }) {
|
|
2110
2307
|
const script = autoScript(dshHome, repo)
|
|
2111
|
-
if (!script)
|
|
2112
|
-
|
|
2308
|
+
if (!script) {
|
|
2309
|
+
return { ok: false, error: t(
|
|
2310
|
+
`插件与仓库里都没有 ${postExitScriptName()},无法排队`,
|
|
2311
|
+
`${postExitScriptName()} is in neither the plugin nor the repo — cannot queue`,
|
|
2312
|
+
) }
|
|
2313
|
+
}
|
|
2113
2314
|
// 同一时刻只允许一次同步。实测过的坑:启动首检排了 push、用户在确认框点确认又排了 pull,
|
|
2114
2315
|
// 两个守护都在等同一个 pid —— DSH 一退出它们**同时开工**,一次推送一次拉取并行跑、各重启一次,
|
|
2115
2316
|
// 配置可能互相覆盖。锁文件记 pid,进程还活着就拒掉后来者。
|
|
2317
|
+
//
|
|
2318
|
+
// 0.6.49:这段原来只在 Windows 分支里(在 spawnWatcher 后半段),POSIX 走新分支后
|
|
2319
|
+
// 锁就没人写了 —— 面板显示「排队中」而磁盘上没有痕迹,两个动作同时排队也没人挡。
|
|
2320
|
+
// 现在两个平台共用同一套判定,放在分支之前。
|
|
2116
2321
|
const lockFile = join(dshHome, 'auto-sync.lock')
|
|
2117
2322
|
try {
|
|
2118
2323
|
if (isFile(lockFile)) {
|
|
@@ -2126,7 +2331,7 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
|
|
|
2126
2331
|
// 同一种同步已经在等,直接复用,别再加一个并行的
|
|
2127
2332
|
if (lockMode === mode) return { ok: true, pid: lockPid, reused: true }
|
|
2128
2333
|
// 不同的同步正在等(例如首检排了推送、用户在确认框点了拉取):用户的手动动作优先,
|
|
2129
|
-
//
|
|
2334
|
+
// 干掉那个还没开工的等待进程,改排这一次。
|
|
2130
2335
|
try { process.kill(lockPid) } catch { }
|
|
2131
2336
|
logLaunch(dshHome, `取消上一个等待中的 ${lockMode || '同步'}(pid ${lockPid}),改排 ${mode}`)
|
|
2132
2337
|
}
|
|
@@ -2135,6 +2340,35 @@ async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs =
|
|
|
2135
2340
|
}
|
|
2136
2341
|
} catch { }
|
|
2137
2342
|
|
|
2343
|
+
// 0.6.49:POSIX 走 Node 执行体(post-exit.mjs)。它不是「等退出→换可见窗口」两段式,
|
|
2344
|
+
// 自己就盯着 pid,所以这里直接 detached 起它,不必先起一个短命 launcher。
|
|
2345
|
+
if (!IS_WIN) {
|
|
2346
|
+
const nodeExe = hostNodeExe(appRoot) || process.execPath
|
|
2347
|
+
const args = ['-Mode', mode, '-WatchPid', String(process.pid), '-DshHome', dshHome]
|
|
2348
|
+
if (closeRequested) args.push('-CloseWhenIdle')
|
|
2349
|
+
if (repo) args.push('-RepoRoot', repo)
|
|
2350
|
+
if (appRoot) args.push('-AppRoot', appRoot)
|
|
2351
|
+
if (restart) args.push('-Restart')
|
|
2352
|
+
if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
|
|
2353
|
+
try {
|
|
2354
|
+
const child = spawn(nodeExe, [script, ...args], {
|
|
2355
|
+
detached: true, stdio: 'ignore', windowsHide: true,
|
|
2356
|
+
})
|
|
2357
|
+
child.unref()
|
|
2358
|
+
} catch (error) {
|
|
2359
|
+
const msg = String((error && error.message) || error)
|
|
2360
|
+
try { unlinkSync(lockFile) } catch { }
|
|
2361
|
+
logLaunch(dshHome, `启动失败 ${mode} exe=${nodeExe}:${msg}`)
|
|
2362
|
+
return { ok: false, error: t(`拉不起 Node 执行体(${nodeExe}):${msg}`, `Cannot launch the Node runner (${nodeExe}): ${msg}`) }
|
|
2363
|
+
}
|
|
2364
|
+
autoState.watcherStartedAt = Date.now()
|
|
2365
|
+
try {
|
|
2366
|
+
writeFileSync(lockFile, JSON.stringify({ pid: process.pid, mode, at: Date.now() }), 'utf8')
|
|
2367
|
+
} catch { }
|
|
2368
|
+
logLaunch(dshHome, `已启动 ${mode}(Node 执行体 ${postExitScriptName()},等 pid ${process.pid} 退出)`)
|
|
2369
|
+
return { ok: true, pid: process.pid, via: 'node' }
|
|
2370
|
+
}
|
|
2371
|
+
|
|
2138
2372
|
const logsDir = join(dshHome, 'logs')
|
|
2139
2373
|
try { if (!existsSync(logsDir)) mkdirSync(logsDir, { recursive: true }) } catch { }
|
|
2140
2374
|
const pidFile = join(logsDir, `.watch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.pid`)
|
|
@@ -2229,11 +2463,42 @@ function electronApp() {
|
|
|
2229
2463
|
*
|
|
2230
2464
|
* 现在优先 app.quit()(走 before-quit,配置照常落盘);拿不到 electron 才退回 taskkill。
|
|
2231
2465
|
*/
|
|
2232
|
-
function closeDsh() {
|
|
2466
|
+
function closeDsh(appRoot = '') {
|
|
2467
|
+
const el = electronApp()
|
|
2468
|
+
const quitSoft = () => {
|
|
2469
|
+
// Electron 主进程形态下 app.quit 最温和(有 before-quit 落盘)
|
|
2470
|
+
if (el) { try { el.app.quit(); return true } catch { } }
|
|
2471
|
+
return false
|
|
2472
|
+
}
|
|
2473
|
+
|
|
2474
|
+
// 0.6.49:POSIX 上没有 taskkill(原来这里 join(C:\\Windows, System32, taskkill.exe),
|
|
2475
|
+
// 在 macOS 上 spawn 一个不存在的可执行文件,'error' 事件没人接 —— 关不掉客户端还会掉异常)。
|
|
2476
|
+
if (!IS_WIN) {
|
|
2477
|
+
if (quitSoft()) return true
|
|
2478
|
+
// 交给 AppleScript 走客户端的正常退出流程(等价于用户按 ⌘Q,配置照常落盘)
|
|
2479
|
+
try {
|
|
2480
|
+
spawn('/usr/bin/osascript', ['-e', 'tell application "DeepSeek Harness" to quit'],
|
|
2481
|
+
{ stdio: 'ignore', detached: false })
|
|
2482
|
+
} catch { /* 没有 osascript 时退回下面的强杀 */ }
|
|
2483
|
+
// 6 秒后还在就按可执行文件整族结束(用户已经点过「立即同步」,明确授权关闭)
|
|
2484
|
+
const timer = setTimeout(() => {
|
|
2485
|
+
// 按可执行文件路径精确结束:按名字会把「等客户端退出的 post-exit.mjs」一起杀掉,
|
|
2486
|
+
// 于是用户点完「立即拉取」反而什么都没发生。
|
|
2487
|
+
try {
|
|
2488
|
+
spawn('/usr/bin/pkill', ['-f', clientProcessPattern(appRoot || resolveAppRoot(''))], { stdio: 'ignore' })
|
|
2489
|
+
} catch { }
|
|
2490
|
+
}, 6000)
|
|
2491
|
+
try { timer.unref?.() } catch { }
|
|
2492
|
+
return true
|
|
2493
|
+
}
|
|
2494
|
+
|
|
2233
2495
|
const exe = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe')
|
|
2234
2496
|
const imageName = 'DeepSeek Harness.exe'
|
|
2235
2497
|
const run = (args) => {
|
|
2236
|
-
try {
|
|
2498
|
+
try {
|
|
2499
|
+
const child = spawn(isFile(exe) ? exe : 'taskkill', args, { stdio: 'ignore', windowsHide: true, detached: false })
|
|
2500
|
+
child.on?.('error', () => { })
|
|
2501
|
+
} catch { }
|
|
2237
2502
|
}
|
|
2238
2503
|
|
|
2239
2504
|
// 先走一次「礼貌关闭」(不带 /F 只对带窗口的进程有效,会让 Electron 走正常关闭流程)。
|
|
@@ -2244,9 +2509,7 @@ function closeDsh() {
|
|
|
2244
2509
|
const timer = setTimeout(() => { run(['/IM', imageName, '/F']) }, 3500)
|
|
2245
2510
|
try { timer.unref?.() } catch { }
|
|
2246
2511
|
|
|
2247
|
-
|
|
2248
|
-
const el = electronApp()
|
|
2249
|
-
if (el) { try { setTimeout(() => { try { el.app.quit() } catch { } }, 150) } catch { } }
|
|
2512
|
+
quitSoft()
|
|
2250
2513
|
return true
|
|
2251
2514
|
}
|
|
2252
2515
|
|
|
@@ -2634,6 +2897,7 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
|
|
|
2634
2897
|
truncated: scanned >= 20000 || Date.now() >= deadline,
|
|
2635
2898
|
// 非 Windows 时只统计引擎真会同步的四组,把这件事说出来(面板会显示,不让用户以为别的组也在同步)
|
|
2636
2899
|
engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
|
|
2900
|
+
engineAllGroups: ENGINE_COVERS_ALL,
|
|
2637
2901
|
}
|
|
2638
2902
|
}
|
|
2639
2903
|
|
|
@@ -2702,7 +2966,28 @@ async function handleSettings(req, res, config) {
|
|
|
2702
2966
|
let repoPath = before.repoPath
|
|
2703
2967
|
if (has('repoPath')) {
|
|
2704
2968
|
repoPath = String(body.repoPath || '').trim().replace(/[\\/]+$/, '')
|
|
2969
|
+
// POSIX 用户习惯写 ~/dsh-config:这里先展开再校验,否则会被「要绝对路径」挡回去,
|
|
2970
|
+
// 而用户会以为插件连自己家目录都不认。
|
|
2971
|
+
if (repoPath === '~' || repoPath.startsWith('~/')) repoPath = join(homedir(), repoPath.slice(1)).replace(/[\\/]+$/, '')
|
|
2705
2972
|
if (!repoPath) throw new Error(t('仓库路径不能为空', 'Repo path cannot be empty'))
|
|
2973
|
+
// 0.6.49:先按平台校验写法。踩过的坑:macOS 上把 `D:\dsh-config` 当相对路径,
|
|
2974
|
+
// 后续 mkdirSync 会在当前工作目录里真的建出一个叫 `D:\dsh-config` 的目录(本仓库根就留了一个);
|
|
2975
|
+
// 反过来 Windows 也不该接受 /Users/x/dsh-config。被拒的路径整批报错,绝不静默存成别的意思。
|
|
2976
|
+
const problem = repoPathProblem(repoPath)
|
|
2977
|
+
if (!problem.ok) {
|
|
2978
|
+
throw new Error(t(
|
|
2979
|
+
problem.reason === 'windows-shape'
|
|
2980
|
+
? `仓库路径要填本机(${platformLabel()})的绝对路径,不能是 Windows 盘符写法:${repoPath}`
|
|
2981
|
+
: (problem.reason === 'posix-absolute'
|
|
2982
|
+
? `仓库路径要填绝对路径(以 / 开头,例如 ${defaultRepoPath()}):${repoPath}`
|
|
2983
|
+
: `仓库路径要填本机(${platformLabel()})的绝对路径(例如 ${defaultRepoPath()}):${repoPath}`),
|
|
2984
|
+
problem.reason === 'windows-shape'
|
|
2985
|
+
? `Repo path must be an absolute ${platformLabel()} path, not a Windows drive path: ${repoPath}`
|
|
2986
|
+
: (problem.reason === 'posix-absolute'
|
|
2987
|
+
? `Repo path must be absolute (starting with /, e.g. ${defaultRepoPath()}): ${repoPath}`
|
|
2988
|
+
: `Repo path must be an absolute ${platformLabel()} path (e.g. ${defaultRepoPath()}): ${repoPath}`),
|
|
2989
|
+
))
|
|
2990
|
+
}
|
|
2706
2991
|
// 新机器上这个目录常常还不存在、或者是个空目录(等着首次拉取去初始化):都允许存。
|
|
2707
2992
|
// 只有「已经有别的东西、又明显不是 dsh-config 仓库」才拒,免得住错地方把人家目录写乱。
|
|
2708
2993
|
// 判据统一交给 repoPhase,跟面板、体检那边保持同一套口径;带 .git\HEAD 的目录
|
|
@@ -3443,8 +3728,41 @@ async function downloadPackage({ urls, sha256, integrity = '', sha1 = '', versio
|
|
|
3443
3728
|
* 返回 { ok, version, backup, log, error }
|
|
3444
3729
|
*/
|
|
3445
3730
|
function runInstallPlugin({ version, sha256, integrity = '', sha1 = '', urls, dshHome }) {
|
|
3446
|
-
|
|
3447
|
-
|
|
3731
|
+
// 0.6.49:执行体随平台走。非 Windows 用 install-plugin.mjs(原来只找 .ps1,
|
|
3732
|
+
// 于是 macOS 上 install-live 永远返回「插件目录里没有 runtime\install-plugin.ps1」)。
|
|
3733
|
+
const script = IS_WIN
|
|
3734
|
+
? join(PLUGIN_DIR, 'runtime', 'install-plugin.ps1')
|
|
3735
|
+
: join(PLUGIN_DIR, 'runtime', 'install-plugin.mjs')
|
|
3736
|
+
if (!isFile(script)) {
|
|
3737
|
+
const name = IS_WIN ? 'install-plugin.ps1' : 'install-plugin.mjs'
|
|
3738
|
+
return Promise.resolve({ ok: false, error: t(`插件目录里没有 runtime\\${name}`, `runtime/${name} is missing from the plugin directory`) })
|
|
3739
|
+
}
|
|
3740
|
+
const parse = (err, stdout, stderr) => {
|
|
3741
|
+
const text = String(stdout || '') + String(stderr || '')
|
|
3742
|
+
// 执行体最后一行固定是 RESULT:{json};前面是给人看的进度
|
|
3743
|
+
const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
|
|
3744
|
+
if (!line) {
|
|
3745
|
+
return { ok: false, error: t('安装脚本没有返回结果:', 'The installer returned no result: ') + (text.trim().slice(-400) || String((err && err.message) || '无输出')) }
|
|
3746
|
+
}
|
|
3747
|
+
try { return JSON.parse(line.slice('RESULT:'.length)) } catch { return { ok: false, error: t('安装脚本返回的结果不是合法 JSON', 'The installer result is not valid JSON') } }
|
|
3748
|
+
}
|
|
3749
|
+
if (!IS_WIN) {
|
|
3750
|
+
const nodeExe = hostNodeExe(resolveAppRoot('')) || process.execPath
|
|
3751
|
+
const args = [script,
|
|
3752
|
+
'-PluginDir', PLUGIN_DIR,
|
|
3753
|
+
'-Version', String(version || ''),
|
|
3754
|
+
'-Sha256', String(sha256 || ''),
|
|
3755
|
+
...(integrity ? ['-Integrity', String(integrity)] : []),
|
|
3756
|
+
...(sha1 ? ['-Sha1', String(sha1)] : []),
|
|
3757
|
+
'-TgzUrls', urls.join('|'),
|
|
3758
|
+
'-DshHome', dshHome,
|
|
3759
|
+
]
|
|
3760
|
+
return new Promise((resolve) => {
|
|
3761
|
+
execFile(nodeExe, args, { timeout: 6 * 60 * 1000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
3762
|
+
resolve(parse(err, stdout, stderr))
|
|
3763
|
+
})
|
|
3764
|
+
})
|
|
3765
|
+
}
|
|
3448
3766
|
const sysRoot = process.env.SystemRoot || 'C:\\Windows'
|
|
3449
3767
|
const ps = join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
3450
3768
|
const args = [
|
|
@@ -3459,14 +3777,7 @@ function runInstallPlugin({ version, sha256, integrity = '', sha1 = '', urls, ds
|
|
|
3459
3777
|
]
|
|
3460
3778
|
return new Promise((resolve) => {
|
|
3461
3779
|
execFile(ps, args, { windowsHide: true, timeout: 6 * 60 * 1000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
3462
|
-
|
|
3463
|
-
// 脚本最后一行固定是 RESULT:{json};前面是给人看的进度
|
|
3464
|
-
const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
|
|
3465
|
-
if (!line) {
|
|
3466
|
-
resolve({ ok: false, error: t('安装脚本没有返回结果:', 'The installer returned no result: ') + (text.trim().slice(-400) || String((err && err.message) || '无输出')) })
|
|
3467
|
-
return
|
|
3468
|
-
}
|
|
3469
|
-
try { resolve(JSON.parse(line.slice('RESULT:'.length))) } catch { resolve({ ok: false, error: t('安装脚本返回的结果不是合法 JSON', 'The installer result is not valid JSON') }) }
|
|
3780
|
+
resolve(parse(err, stdout, stderr))
|
|
3470
3781
|
})
|
|
3471
3782
|
})
|
|
3472
3783
|
}
|
|
@@ -3773,7 +4084,9 @@ function countEntries(dir) {
|
|
|
3773
4084
|
* profile(4 个文件)/ prompt / skills / presets —— 别的组在那台机器上根本不会被同步。
|
|
3774
4085
|
* null 表示「全部组」,非 Windows 时是白名单。
|
|
3775
4086
|
*/
|
|
3776
|
-
const ENGINE_SYNCED_GROUPS = IS_WIN ? null : new Set(['profile', 'prompt', 'skills', 'presets'])
|
|
4087
|
+
const ENGINE_SYNCED_GROUPS = IS_WIN ? null : new Set(['profile', 'prompt', 'skills', 'presets', 'storages-record', 'settings', 'mnemon', 'local-plugins', 'plugin-data', 'extra', 'workspace', 'conversations'])
|
|
4088
|
+
/** 引擎是否已覆盖全部内容分组('other' 是兜底桶,不算)。0.6.49 起非 Windows 是全 12 组。 */
|
|
4089
|
+
const ENGINE_COVERS_ALL = !ENGINE_SYNCED_GROUPS || Object.keys(PENDING_GROUP_LABEL).filter((id) => id !== 'other').every((id) => ENGINE_SYNCED_GROUPS.has(id))
|
|
3777
4090
|
|
|
3778
4091
|
/** profile 目录:优先 desktop,其次 profiles 下唯一的那一个 */
|
|
3779
4092
|
function resolveProfileDir(dshHome) {
|
|
@@ -3827,25 +4140,6 @@ function listLocalPlugins(dshHome) {
|
|
|
3827
4140
|
* 与 runtime\dsh-sync-common.ps1 的默认值必须一致,否则面板说"会同步"、capture 却跳过。
|
|
3828
4141
|
*/
|
|
3829
4142
|
const ROUTE_EXTRA_CONFIG = '/config-sync/extra-config'
|
|
3830
|
-
const EXTRA_CONFIG_NAME = 'config-sync-extra.json'
|
|
3831
|
-
/** GitHub 单文件硬上限 100MB,超过必被拒收,所以配置里调多大都按这个封顶。 */
|
|
3832
|
-
const EXTRA_HARD_MAX_BYTES = 104857600
|
|
3833
|
-
const EXTRA_DEFAULT_SKIP_DIRS = [
|
|
3834
|
-
'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
|
|
3835
|
-
'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
|
|
3836
|
-
'browser-profiles', 'im', 'node_modules',
|
|
3837
|
-
]
|
|
3838
|
-
const EXTRA_DEFAULT_EXCLUDE = [
|
|
3839
|
-
'*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
|
|
3840
|
-
'*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
|
|
3841
|
-
'*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
|
|
3842
|
-
'*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
|
|
3843
|
-
'*.env', '.env*', 'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json', 'dsh-ssh-master.key',
|
|
3844
|
-
'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
|
|
3845
|
-
'*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
|
|
3846
|
-
'browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State',
|
|
3847
|
-
'node_modules', '.git', '.cache', '__pycache__', '.venv',
|
|
3848
|
-
]
|
|
3849
4143
|
|
|
3850
4144
|
/**
|
|
3851
4145
|
* 安全必需项:用户自己的 config-sync-extra.json 不允许把它们去掉。
|
|
@@ -3857,8 +4151,6 @@ const EXTRA_DEFAULT_EXCLUDE = [
|
|
|
3857
4151
|
* 于是待推送会把 browser-profiles 里几千个文件的 mtime 变动算成「待推送」,而 capture 根本不会抓它们
|
|
3858
4152
|
* —— 面板永远消不掉,退出自动推送也每次白跑。
|
|
3859
4153
|
*/
|
|
3860
|
-
const EXTRA_MANDATORY_SKIP_DIRS = ['browser-profiles']
|
|
3861
|
-
const EXTRA_MANDATORY_EXCLUDES = ['browser-profiles', 'User Data', 'Login Data', 'Cookies', 'Web Data', 'Local State']
|
|
3862
4154
|
|
|
3863
4155
|
/**
|
|
3864
4156
|
* 浏览器剖面 / 凭据库的路径段黑名单:与 PS 的 $SyncBlockedProfileSegments、webdav.mjs 的
|
|
@@ -3875,14 +4167,6 @@ const BLOCKED_PROFILE_SEGMENTS = new Set([
|
|
|
3875
4167
|
* 读配置要用、保存前也要用:POST 拿用户提交的名单覆盖掉之后,
|
|
3876
4168
|
* 如果只在读的时候补,用户一保存就又把它删掉了(实测就是这样丢的)。
|
|
3877
4169
|
*/
|
|
3878
|
-
function topUpExtraMandatory(cfg) {
|
|
3879
|
-
if (!cfg || !cfg.pluginData) return { skipDirs: [], exclude: [] }
|
|
3880
|
-
const addedSkip = EXTRA_MANDATORY_SKIP_DIRS.filter((x) => !(cfg.pluginData.skipDirs || []).includes(x))
|
|
3881
|
-
const addedExcl = EXTRA_MANDATORY_EXCLUDES.filter((x) => !(cfg.pluginData.exclude || []).includes(x))
|
|
3882
|
-
if (addedSkip.length) cfg.pluginData.skipDirs = [...(cfg.pluginData.skipDirs || []), ...addedSkip]
|
|
3883
|
-
if (addedExcl.length) cfg.pluginData.exclude = [...(cfg.pluginData.exclude || []), ...addedExcl]
|
|
3884
|
-
return { skipDirs: addedSkip, exclude: addedExcl }
|
|
3885
|
-
}
|
|
3886
4170
|
|
|
3887
4171
|
function isBlockedProfilePath(rel) {
|
|
3888
4172
|
const s = String(rel || '')
|
|
@@ -3898,71 +4182,10 @@ function isBlockedProfilePath(rel) {
|
|
|
3898
4182
|
* 以前 JS 只写了 4 条,capture 却抓 14 条:面板少列了 10 个文件,用户既看不到也勾不掉它们。
|
|
3899
4183
|
* 每条 { id, rel }:rel 是相对 <DshHome> 的路径;profileRel 表示相对 profile 目录。
|
|
3900
4184
|
*/
|
|
3901
|
-
const SYNC_SETTINGS_SOURCES =
|
|
3902
|
-
{ id: 'our-free-model.json', rel: ['our-free-model', 'settings.json'] },
|
|
3903
|
-
{ id: 'comfyui-workflows.json', rel: ['data', 'dsh-comfyui', 'workflows.json'] },
|
|
3904
|
-
{ id: 'dsh-pet-main-config.jsonc', rel: ['dsh-pet', 'main-config.jsonc'] },
|
|
3905
|
-
{ id: 'dsh-market-state.json', profileRel: ['.dsh-market', 'state.json'] },
|
|
3906
|
-
{ id: 'dsh-pet-memory.json', rel: ['dsh-pet', 'memory.json'] },
|
|
3907
|
-
{ id: 'our-free-model-picks.json', rel: ['our-free-model', 'picks.json'] },
|
|
3908
|
-
{ id: 'dsh-im-interface-language.json', rel: ['integrations', 'dsh-im', 'interface-language.json'] },
|
|
3909
|
-
{ id: 'dsh-qq-config.json', rel: ['integrations', 'dsh-qq', 'config.json'] },
|
|
3910
|
-
{ id: 'dsh-qq-workspaces.json', rel: ['integrations', 'dsh-qq', 'workspaces.json'] },
|
|
3911
|
-
{ id: 'redteam-preset-declare.json', rel: ['redteam', 'preset-declare.json'] },
|
|
3912
|
-
{ id: 'task-board-ledger.json', rel: ['task-board', 'ledger-v2.json'] },
|
|
3913
|
-
{ id: 'task-board-scheduler.json', rel: ['task-board', 'scheduler-v2.json'] },
|
|
3914
|
-
{ id: 'dsh-workspaces.json', rel: ['storages', 'workspace.json'] },
|
|
3915
|
-
{ id: 'workspace-archives.json', rel: ['dsh-session-manager', 'workspace-archives.v1.json'] },
|
|
3916
|
-
]
|
|
3917
|
-
|
|
3918
|
-
function settingsSourcePath(dshHome, profileDir, entry) {
|
|
3919
|
-
return entry.profileRel ? join(profileDir, ...entry.profileRel) : join(dshHome, ...entry.rel)
|
|
3920
|
-
}
|
|
4185
|
+
const SYNC_SETTINGS_SOURCES = SETTINGS_SOURCES
|
|
3921
4186
|
|
|
3922
|
-
|
|
4187
|
+
const settingsSourcePath = settingsSourcePathOf
|
|
3923
4188
|
|
|
3924
|
-
function readExtraConfig(dshHome) {
|
|
3925
|
-
const cfg = {
|
|
3926
|
-
version: 1,
|
|
3927
|
-
pluginData: {
|
|
3928
|
-
enabled: true,
|
|
3929
|
-
maxFileBytes: EXTRA_HARD_MAX_BYTES,
|
|
3930
|
-
exclude: [...EXTRA_DEFAULT_EXCLUDE],
|
|
3931
|
-
skipDirs: [...EXTRA_DEFAULT_SKIP_DIRS],
|
|
3932
|
-
},
|
|
3933
|
-
extra: { enabled: true, paths: [] },
|
|
3934
|
-
}
|
|
3935
|
-
const p = extraConfigPath(dshHome)
|
|
3936
|
-
if (!isFile(p)) return cfg
|
|
3937
|
-
try {
|
|
3938
|
-
const j = JSON.parse(readFileSync(p, 'utf8'))
|
|
3939
|
-
const pd = j?.pluginData
|
|
3940
|
-
if (pd) {
|
|
3941
|
-
if (pd.enabled === false) cfg.pluginData.enabled = false
|
|
3942
|
-
const n = Number(pd.maxFileBytes)
|
|
3943
|
-
if (Number.isFinite(n) && n > 0) cfg.pluginData.maxFileBytes = Math.min(Math.floor(n), EXTRA_HARD_MAX_BYTES)
|
|
3944
|
-
// 排除名单整份替换:用户在面板里删掉一条就真的不再排除
|
|
3945
|
-
if (Array.isArray(pd.exclude)) cfg.pluginData.exclude = pd.exclude.filter((x) => typeof x === 'string' && x)
|
|
3946
|
-
if (Array.isArray(pd.skipDirs)) cfg.pluginData.skipDirs = pd.skipDirs.filter((x) => typeof x === 'string' && x)
|
|
3947
|
-
}
|
|
3948
|
-
const ex = j?.extra
|
|
3949
|
-
if (ex) {
|
|
3950
|
-
if (ex.enabled === false) cfg.extra.enabled = false
|
|
3951
|
-
if (Array.isArray(ex.paths)) {
|
|
3952
|
-
cfg.extra.paths = ex.paths
|
|
3953
|
-
.filter((x) => x && typeof x.id === 'string' && typeof x.src === 'string' && x.id && x.src)
|
|
3954
|
-
.map((x) => ({ id: x.id, src: x.src, label: typeof x.label === 'string' && x.label ? x.label : x.id }))
|
|
3955
|
-
}
|
|
3956
|
-
}
|
|
3957
|
-
} catch { /* 坏了就按默认规则走,不让面板整页读不出来 */ }
|
|
3958
|
-
// 安全必需项补齐(与 PowerShell 的 Get-SyncExtraConfig 同一步):用户文件可以改别的,
|
|
3959
|
-
// 但这些名字必须留着。补齐了要能让面板说出来(missingMandatory),不静默改用户的口径。
|
|
3960
|
-
const added = topUpExtraMandatory(cfg)
|
|
3961
|
-
if (added.skipDirs.length || added.exclude.length) {
|
|
3962
|
-
cfg.pluginData.missingMandatory = { skipDirs: added.skipDirs, exclude: added.exclude }
|
|
3963
|
-
}
|
|
3964
|
-
return cfg
|
|
3965
|
-
}
|
|
3966
4189
|
|
|
3967
4190
|
function saveExtraConfig(dshHome, cfg) {
|
|
3968
4191
|
const p = extraConfigPath(dshHome)
|
|
@@ -3983,25 +4206,6 @@ function saveExtraConfig(dshHome, cfg) {
|
|
|
3983
4206
|
return p
|
|
3984
4207
|
}
|
|
3985
4208
|
|
|
3986
|
-
function wildcardToRegex(pat) {
|
|
3987
|
-
const esc = String(pat).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
|
|
3988
|
-
return new RegExp(`^${esc}$`, 'i')
|
|
3989
|
-
}
|
|
3990
|
-
|
|
3991
|
-
/** 返回跳过原因('' = 允许同步),与 runtime 的 Test-SyncExtraSkip 判定一致。 */
|
|
3992
|
-
function extraSkipReason(relName, size, cfg) {
|
|
3993
|
-
const max = Math.min(cfg.pluginData.maxFileBytes || EXTRA_HARD_MAX_BYTES, EXTRA_HARD_MAX_BYTES)
|
|
3994
|
-
if (size > max) return 'too-big'
|
|
3995
|
-
if (!relName) return ''
|
|
3996
|
-
const parts = String(relName).split(/[\\/]+/).filter((x) => x)
|
|
3997
|
-
const name = parts.length ? parts[parts.length - 1] : relName
|
|
3998
|
-
for (const pat of cfg.pluginData.exclude || []) {
|
|
3999
|
-
const re = wildcardToRegex(pat)
|
|
4000
|
-
if (re.test(name)) return 'excluded'
|
|
4001
|
-
for (const seg of parts) if (re.test(seg)) return 'excluded'
|
|
4002
|
-
}
|
|
4003
|
-
return ''
|
|
4004
|
-
}
|
|
4005
4209
|
|
|
4006
4210
|
function dirHasRules(cfg) { return (cfg.pluginData.exclude || []).map(wildcardToRegex) }
|
|
4007
4211
|
|
|
@@ -4162,8 +4366,12 @@ async function handleScope(req, res, config) {
|
|
|
4162
4366
|
desc: t(g.descZh, g.descEn),
|
|
4163
4367
|
enabled: g.enabled,
|
|
4164
4368
|
required: g.required === true,
|
|
4369
|
+
// 0.6.49:这台机器上的引擎会不会真的同步这一组。非 Windows 只有四组(ENGINE_SYNCED_GROUPS),
|
|
4370
|
+
// 面板据此把其余组标成「此平台暂不支持」并禁用勾选 —— 让人勾上却永远不生效,比不给勾更糟。
|
|
4371
|
+
supported: ENGINE_SYNCED_GROUPS ? ENGINE_SYNCED_GROUPS.has(g.id) : true,
|
|
4165
4372
|
items: g.items.map((it) => ({ id: it.id, label: it.label, enabled: it.enabled, excludable: it.excludable !== false })),
|
|
4166
4373
|
})),
|
|
4374
|
+
engineGroups: ENGINE_SYNCED_GROUPS ? [...ENGINE_SYNCED_GROUPS] : null,
|
|
4167
4375
|
})
|
|
4168
4376
|
return
|
|
4169
4377
|
}
|
|
@@ -4764,6 +4972,7 @@ async function handleAuto(req, res, config) {
|
|
|
4764
4972
|
autoState.checking = false
|
|
4765
4973
|
autoState.lastCheckAt = Date.now()
|
|
4766
4974
|
autoState.drift = drift
|
|
4975
|
+
if (!drift || !(drift.behind > 0)) autoState.pullPrompt = null
|
|
4767
4976
|
sendJson(res, 200, { ok: true, action, drift, error: autoState.lastCheckError || null })
|
|
4768
4977
|
return
|
|
4769
4978
|
}
|
|
@@ -4824,6 +5033,7 @@ async function handleAuto(req, res, config) {
|
|
|
4824
5033
|
const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart, closeRequested: closeNow })
|
|
4825
5034
|
if (!started.ok) throw new Error(started.error)
|
|
4826
5035
|
autoState.pending = { mode, at: Date.now(), restart, watcherPid: started.pid, closeRequested: false }
|
|
5036
|
+
autoState.pullPrompt = null
|
|
4827
5037
|
// 用户明确要求"现在就同步":排队后请求客户端退出(不带 /F,走正常关闭,配置能存下来)
|
|
4828
5038
|
let closed = false
|
|
4829
5039
|
if (body.closeNow !== false) {
|
|
@@ -4881,20 +5091,35 @@ function scheduleAutoStart(config) {
|
|
|
4881
5091
|
}
|
|
4882
5092
|
}
|
|
4883
5093
|
autoState.drift = drift
|
|
5094
|
+
if (!drift || !(drift.behind > 0)) autoState.pullPrompt = null
|
|
4884
5095
|
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
4885
5096
|
|
|
4886
5097
|
if (settings.autoPull && drift.behind > 0) {
|
|
4887
|
-
const
|
|
4888
|
-
|
|
4889
|
-
|
|
4890
|
-
|
|
4891
|
-
|
|
4892
|
-
|
|
4893
|
-
|
|
4894
|
-
|
|
4895
|
-
+ `(This machine is ${drift.ahead} commit(s) ahead — pulling leaves those alone.)`,
|
|
4896
|
-
),
|
|
5098
|
+
const title = t('云端有更新,要同步到本机吗?', 'The cloud has new commits — sync them to this machine?')
|
|
5099
|
+
const text = t(
|
|
5100
|
+
`云端比本机多 ${drift.behind} 个提交。\n`
|
|
5101
|
+
+ '同步需要先完全退出 DSH:确认后客户端会自动关闭,拉取完成后按设置自动重新打开。\n'
|
|
5102
|
+
+ `(本机领先 ${drift.ahead} 个提交,拉取不会动它们)`,
|
|
5103
|
+
`The cloud is ${drift.behind} commit(s) ahead of this machine.\n`
|
|
5104
|
+
+ 'Syncing requires DSH to fully exit first: after you confirm, the client closes itself and reopens according to your settings once the pull finishes.\n'
|
|
5105
|
+
+ `(This machine is ${drift.ahead} commit(s) ahead — pulling leaves those alone.)`,
|
|
4897
5106
|
)
|
|
5107
|
+
// 0.6.49:启动时的自动拉取不再在 macOS 上弹原生框。这条路径是**没有请求、没有面板**的
|
|
5108
|
+
// 后台流程,osascript 的 display dialog 往往落在应用窗口后面甚至不出现在前台 —— 用户看
|
|
5109
|
+
// 不见就等于「自动拉取从来不会发生」,而 DSH 还以为在等确认(12 分钟超时)。
|
|
5110
|
+
// 现在改成把提示挂进状态,面板的「不一致 · 立即拉取」一键接手;Windows 保持原样。
|
|
5111
|
+
let yes = false
|
|
5112
|
+
if (IS_WIN) {
|
|
5113
|
+
yes = await askConfirm(title, text)
|
|
5114
|
+
} else {
|
|
5115
|
+
autoState.pullPrompt = { behind: drift.behind, ahead: drift.ahead, at: Date.now(), title, message: text }
|
|
5116
|
+
try {
|
|
5117
|
+
const logDir = join(dshHome, 'logs')
|
|
5118
|
+
mkdirSync(logDir, { recursive: true })
|
|
5119
|
+
writeFileSync(join(logDir, 'auto-sync-pull-prompt.log'),
|
|
5120
|
+
`[${new Date().toISOString()}] 云端领先 ${drift.behind} 个提交:等用户在面板里点「立即拉取」\n`, { flag: 'a' })
|
|
5121
|
+
} catch { }
|
|
5122
|
+
}
|
|
4898
5123
|
if (yes) {
|
|
4899
5124
|
// 用户点了确认,插件随后自己关客户端 → 允许守护进程在窗口消失后清残留
|
|
4900
5125
|
const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart: settings.autoRestart, closeRequested: true })
|
|
@@ -5340,6 +5565,9 @@ async function handleWebdav(req, res, config) {
|
|
|
5340
5565
|
user: w.user,
|
|
5341
5566
|
dir: w.dir,
|
|
5342
5567
|
mode: w.mode,
|
|
5568
|
+
// 0.6.48:UA 回显(面板要能确认「发出去的到底是什么」),留空表示不发 User-Agent
|
|
5569
|
+
userAgent: w.ua,
|
|
5570
|
+
userAgentSanitized: Boolean(String(settings.webdavUserAgent || '').trim()) && !w.ua,
|
|
5343
5571
|
secure: isSecureUrl(w.url),
|
|
5344
5572
|
probe,
|
|
5345
5573
|
platform: OS,
|
|
@@ -5356,13 +5584,26 @@ async function handleWebdav(req, res, config) {
|
|
|
5356
5584
|
|
|
5357
5585
|
// save:只更新给出的字段;密码留空表示「不改」(避免面板回显后把密码清空)
|
|
5358
5586
|
if (action === 'save') {
|
|
5359
|
-
const next = { ...settings }
|
|
5360
|
-
if (typeof body.url === 'string') next.webdavUrl = body.url.trim()
|
|
5361
|
-
if (typeof body.user === 'string') next.webdavUser = body.user.trim()
|
|
5362
|
-
if (typeof body.dir === 'string') next.webdavDir = body.dir.trim()
|
|
5363
|
-
if (typeof body.mode === 'string' && ['git', 'webdav', 'auto'].includes(body.mode)) next.syncMode = body.mode
|
|
5364
|
-
if (typeof body.pass === 'string' && body.pass.length > 0) next.webdavPass = body.pass
|
|
5365
5587
|
try {
|
|
5588
|
+
const next = { ...settings }
|
|
5589
|
+
if (typeof body.url === 'string') next.webdavUrl = body.url.trim()
|
|
5590
|
+
if (typeof body.user === 'string') next.webdavUser = body.user.trim()
|
|
5591
|
+
if (typeof body.dir === 'string') next.webdavDir = body.dir.trim()
|
|
5592
|
+
if (typeof body.mode === 'string' && ['git', 'webdav', 'auto'].includes(body.mode)) next.syncMode = body.mode
|
|
5593
|
+
if (typeof body.pass === 'string' && body.pass.length > 0) next.webdavPass = body.pass
|
|
5594
|
+
// 0.6.48:UA。非法值(含 CRLF / 非 ASCII / 超长)不静默存:明确报错,
|
|
5595
|
+
// 否则用户以为填上了,实际发出去的还是默认 UA,症状又变成「连不上」。
|
|
5596
|
+
if (typeof body.userAgent === 'string') {
|
|
5597
|
+
const raw = body.userAgent.trim()
|
|
5598
|
+
const safe = sanitizeUserAgent(raw)
|
|
5599
|
+
if (raw && !safe) {
|
|
5600
|
+
throw new Error(t(
|
|
5601
|
+
'User-Agent 只能是一行可见 ASCII(不含换行、中文、制表符),且不超过 200 字符',
|
|
5602
|
+
'User-Agent must be a single line of visible ASCII (no newlines, CJK or tabs), at most 200 characters',
|
|
5603
|
+
))
|
|
5604
|
+
}
|
|
5605
|
+
next.webdavUserAgent = safe
|
|
5606
|
+
}
|
|
5366
5607
|
writeSettings(dshHome, next)
|
|
5367
5608
|
clearWebdavProbeCache()
|
|
5368
5609
|
const w = normalizeWebdav(next)
|
|
@@ -5418,7 +5659,17 @@ async function handleWebdav(req, res, config) {
|
|
|
5418
5659
|
|
|
5419
5660
|
if (action === 'upload') {
|
|
5420
5661
|
const r = await uploadRepo(w, repo)
|
|
5421
|
-
|
|
5662
|
+
// 顺手清掉老版本推上去的浏览器剖面(Login Data / Cookies 不该待在云端)
|
|
5663
|
+
const purge = await purgeForbiddenFromCloud(w)
|
|
5664
|
+
const lockPurge = await purgeStaleLocksFromCloud(w)
|
|
5665
|
+
sendJson(res, 200, {
|
|
5666
|
+
ok: r.ok,
|
|
5667
|
+
uploaded: r.uploaded.length,
|
|
5668
|
+
skipped: r.skipped.length,
|
|
5669
|
+
purged: purge.deleted.length,
|
|
5670
|
+
purgedLocks: lockPurge.deleted.length,
|
|
5671
|
+
errors: r.errors.slice(0, 20),
|
|
5672
|
+
})
|
|
5422
5673
|
return
|
|
5423
5674
|
}
|
|
5424
5675
|
if (action === 'download') {
|
|
@@ -5892,11 +6143,174 @@ function issueBodyOf(text, config) {
|
|
|
5892
6143
|
return `${String(text || '').trim()}\n\n---\n### 环境 / Environment\n${env}\n`
|
|
5893
6144
|
}
|
|
5894
6145
|
|
|
5895
|
-
|
|
6146
|
+
/* ---------- 0.6.48:反馈附件(图片 / 视频) ----------
|
|
6147
|
+
* 起因(issue #9):面板只能打字,截图与录屏没法带上来 —— 而这两样恰恰是
|
|
6148
|
+
* 「界面显示不对」「同步报错」类反馈里最关键的证据。
|
|
6149
|
+
*
|
|
6150
|
+
* 做法:走 GitHub 自己的 release asset 上传接口,不借道第三方图床。
|
|
6151
|
+
* 1) 找一个用来挂附件的 release(见 feedbackAssetRelease):没有就建一个
|
|
6152
|
+
* 名为 `feedback-assets` 的草稿 release(draft,标签页看不见,只有
|
|
6153
|
+
* 知道链接的人才打得到 —— 反馈附件本来就不该公开发布);
|
|
6154
|
+
* 2) POST 到该 release 的 `upload_url`(形如
|
|
6155
|
+
* https://uploads.github.com/repos/<o>/<r>/releases/<id>/assets{?name,label}),
|
|
6156
|
+
* body 是原始字节,Content-Type 是真实类型,`?name=` 给出文件名;
|
|
6157
|
+
* 3) 把返回的 `browser_download_url` 按 Markdown 图片 / 普通链接插进正文。
|
|
6158
|
+
*
|
|
6159
|
+
* 为什么要自己找 release:Issue 本身没有附件接口,只有 release 才有。
|
|
6160
|
+
* 而附件存成 release asset 的好处是:链接永久有效、换机器与别人看都能打开,
|
|
6161
|
+
* 且不依赖你本机的文件还在不在。
|
|
6162
|
+
*
|
|
6163
|
+
* 边界:
|
|
6164
|
+
* - 单文件 20 MB、最多 4 个(GitHub 单 asset 上限 2 GB,这里收紧是为了面板不卡);
|
|
6165
|
+
* - 白名单类型:PNG / JPEG / GIF / WebP / MP4 / MOV / WebM / 文本日志;
|
|
6166
|
+
* 其它一律拒(可执行文件、压缩包不进资产);
|
|
6167
|
+
* - 没有令牌时退回「浏览器预填页面」,并明确告知附件没上传,
|
|
6168
|
+
* 提示用户手动拖进网页 —— 不静默丢弃。
|
|
6169
|
+
*/
|
|
6170
|
+
const FEEDBACK_MAX_ATTACH_BYTES = 20 * 1024 * 1024
|
|
6171
|
+
const FEEDBACK_MAX_ATTACH_COUNT = 4
|
|
6172
|
+
const FEEDBACK_ATTACH_MIME = {
|
|
6173
|
+
png: 'image/png',
|
|
6174
|
+
jpg: 'image/jpeg',
|
|
6175
|
+
jpeg: 'image/jpeg',
|
|
6176
|
+
gif: 'image/gif',
|
|
6177
|
+
webp: 'image/webp',
|
|
6178
|
+
bmp: 'image/bmp',
|
|
6179
|
+
svg: 'image/svg+xml',
|
|
6180
|
+
mp4: 'video/mp4',
|
|
6181
|
+
mov: 'video/quicktime',
|
|
6182
|
+
webm: 'video/webm',
|
|
6183
|
+
log: 'text/plain; charset=utf-8',
|
|
6184
|
+
txt: 'text/plain; charset=utf-8',
|
|
6185
|
+
md: 'text/plain; charset=utf-8',
|
|
6186
|
+
json: 'text/plain; charset=utf-8',
|
|
6187
|
+
}
|
|
6188
|
+
|
|
6189
|
+
/** 附件的扩展名 → MIME。不在白名单里返回 ''(调用方据此拒收)。 */
|
|
6190
|
+
function feedbackAttachMime(name) {
|
|
6191
|
+
const leaf = String(name || '').split(/[\\/]/).pop() || ''
|
|
6192
|
+
const dot = leaf.lastIndexOf('.')
|
|
6193
|
+
if (dot <= 0) return ''
|
|
6194
|
+
return FEEDBACK_ATTACH_MIME[leaf.slice(dot + 1).toLowerCase()] || ''
|
|
6195
|
+
}
|
|
6196
|
+
|
|
6197
|
+
/** Markdown 引用:图片用 ![](),其它(视频/日志)用普通链接,点开是下载/播放。 */
|
|
6198
|
+
function feedbackAttachMarkdown(item) {
|
|
6199
|
+
const url = String((item && item.url) || '')
|
|
6200
|
+
const name = String((item && item.name) || 'attachment').replace(/([\[\]])/g, '\\$1')
|
|
6201
|
+
if (!url) return ''
|
|
6202
|
+
return /^image\//.test(String((item && item.type) || '')) ? `` : `- [${name}](${url})`
|
|
6203
|
+
}
|
|
6204
|
+
|
|
6205
|
+
/**
|
|
6206
|
+
* 上传一个附件到 GitHub(两步:拿上传地址 → PUT 字节)。
|
|
6207
|
+
* 成功返回 { ok: true, name, url, type },失败返回 { ok: false, name, error } —— 不抛,
|
|
6208
|
+
* 因为「有一个附件传不上去」不该让整条反馈都发不出去。
|
|
6209
|
+
*/
|
|
6210
|
+
/**
|
|
6211
|
+
* 找(或建)一个用来挂反馈附件的 release。
|
|
6212
|
+
*
|
|
6213
|
+
* GitHub 只有 release 有 asset 接口,Issue 没有。先按 tag `feedback-assets` 找;
|
|
6214
|
+
* 找不到就建一个**草稿** release(draft=true):它不会出现在 Releases 页面、
|
|
6215
|
+
* 不会被搜索引擎收录,但知道链接的人打得开 —— 反馈附件本来就不该公开发布。
|
|
6216
|
+
*
|
|
6217
|
+
* 缓存到进程内存里:一次反馈最多 4 个附件,不该为每个文件都去查一遍。
|
|
6218
|
+
*/
|
|
6219
|
+
const feedbackReleaseCache = new Map()
|
|
6220
|
+
|
|
6221
|
+
async function feedbackAssetRelease(repo, token) {
|
|
6222
|
+
const cached = feedbackReleaseCache.get(repo)
|
|
6223
|
+
if (cached) return cached
|
|
6224
|
+
const tag = 'feedback-assets'
|
|
6225
|
+
const found = await ghApi(`/repos/${repo}/releases/tags/${encodeURIComponent(tag)}`, { token })
|
|
6226
|
+
if (found.ok && found.json && found.json.id) {
|
|
6227
|
+
const r = { id: found.json.id, uploadUrl: String(found.json.upload_url || '') }
|
|
6228
|
+
feedbackReleaseCache.set(repo, r)
|
|
6229
|
+
return r
|
|
6230
|
+
}
|
|
6231
|
+
// 没有就建:草稿 release,tag 固定,名字写明用途
|
|
6232
|
+
const created = await ghApi(`/repos/${repo}/releases`, {
|
|
6233
|
+
method: 'POST',
|
|
6234
|
+
token,
|
|
6235
|
+
body: {
|
|
6236
|
+
tag_name: tag,
|
|
6237
|
+
name: 'feedback-assets',
|
|
6238
|
+
body: 'Draft release holding the attachments of GitHub Issues in this repository. Created automatically by dsh-profile-config-sync; not published on purpose.',
|
|
6239
|
+
draft: true,
|
|
6240
|
+
prerelease: false,
|
|
6241
|
+
},
|
|
6242
|
+
timeoutMs: 20000,
|
|
6243
|
+
})
|
|
6244
|
+
if (!created.ok || !created.json || !created.json.id) {
|
|
6245
|
+
return { error: `${created.status} ${String((created.json && created.json.message) || '').slice(0, 160) || '建不了存放附件的 release'}` }
|
|
6246
|
+
}
|
|
6247
|
+
const r = { id: created.json.id, uploadUrl: String(created.json.upload_url || '') }
|
|
6248
|
+
feedbackReleaseCache.set(repo, r)
|
|
6249
|
+
return r
|
|
6250
|
+
}
|
|
6251
|
+
|
|
6252
|
+
/**
|
|
6253
|
+
* 上传一个附件到 GitHub 的 release assets。
|
|
6254
|
+
* 成功返回 { ok: true, name, url, type },失败返回 { ok: false, name, error } —— 不抛,
|
|
6255
|
+
* 因为「有一个附件传不上去」不该让整条反馈都发不出去。
|
|
6256
|
+
*/
|
|
6257
|
+
async function uploadFeedbackAsset(repo, token, name, buf, mime) {
|
|
6258
|
+
const safe = String(name || 'attachment').split(/[\\/]/).pop().slice(0, 120) || 'attachment'
|
|
6259
|
+
const rel = await feedbackAssetRelease(repo, token)
|
|
6260
|
+
if (!rel || !rel.id) {
|
|
6261
|
+
return { ok: false, name: safe, error: String((rel && rel.error) || '拿不到存放附件的 release') }
|
|
6262
|
+
}
|
|
6263
|
+
if (!rel.uploadUrl) {
|
|
6264
|
+
return { ok: false, name: safe, error: 'release 没有 upload_url' }
|
|
6265
|
+
}
|
|
6266
|
+
// upload_url 形如 https://uploads.github.com/repos/<o>/<r>/releases/<id>/assets{?name,label}
|
|
6267
|
+
// —— 官方格式是「{?name,label}」这一整段,不能只把 {name} 当占位符替换。
|
|
6268
|
+
// 去掉那段之后地址末尾没有查询串,所以要用「?」而不是「&」。
|
|
6269
|
+
const base = rel.uploadUrl.replace(/\{\?[^}]*\}/g, '')
|
|
6270
|
+
const target = base + (base.includes('?') ? '&' : '?') + 'name=' + encodeURIComponent(safe)
|
|
6271
|
+
const headers = {
|
|
6272
|
+
Accept: 'application/vnd.github+json',
|
|
6273
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
6274
|
+
'User-Agent': PACKAGE_ID,
|
|
6275
|
+
Authorization: `Bearer ${token}`,
|
|
6276
|
+
'Content-Type': mime || 'application/octet-stream',
|
|
6277
|
+
'Content-Length': String(buf.length),
|
|
6278
|
+
}
|
|
6279
|
+
let res
|
|
6280
|
+
try {
|
|
6281
|
+
const ctrl = typeof AbortController === 'function' ? new AbortController() : null
|
|
6282
|
+
const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120000) : null
|
|
6283
|
+
try {
|
|
6284
|
+
res = await fetch(target, { method: 'POST', headers, body: buf, signal: ctrl ? ctrl.signal : undefined })
|
|
6285
|
+
} finally { if (timer) clearTimeout(timer) }
|
|
6286
|
+
} catch (e) {
|
|
6287
|
+
return { ok: false, name: safe, error: String((e && e.message) || e) }
|
|
6288
|
+
}
|
|
6289
|
+
const raw = await res.text().catch(() => '')
|
|
6290
|
+
let json = null
|
|
6291
|
+
try { json = raw ? JSON.parse(raw) : null } catch { json = null }
|
|
6292
|
+
if (!res.ok || !json || !json.browser_download_url) {
|
|
6293
|
+
return { ok: false, name: safe, error: `${res.status} ${String((json && json.message) || raw).slice(0, 160) || '上传失败'}` }
|
|
6294
|
+
}
|
|
6295
|
+
return { ok: true, name: safe, url: String(json.browser_download_url), type: mime || '' }
|
|
6296
|
+
}
|
|
6297
|
+
|
|
6298
|
+
/**
|
|
6299
|
+
* 正文 = 用户写的 + 附件引用 + 环境块(环境块永远在最后一段)。
|
|
6300
|
+
* 有附件时附件在前、环境块在后;没附件时就是原来的形状,老行为一个字节都不变。
|
|
6301
|
+
*/
|
|
6302
|
+
function issueBodyWithAttachments(text, config, attachments) {
|
|
6303
|
+
const base = String(text || '').trim()
|
|
6304
|
+
const refs = (attachments || []).map(feedbackAttachMarkdown).filter(Boolean)
|
|
6305
|
+
const withRefs = refs.length ? `${base}${base ? '\n\n' : ''}### 附件 / Attachments\n${refs.join('\n')}\n` : base
|
|
6306
|
+
return issueBodyOf(withRefs, config)
|
|
6307
|
+
}
|
|
6308
|
+
|
|
6309
|
+
async function createIssue(repo, token, title, text, config, attachments = []) {
|
|
5896
6310
|
return ghApi(`/repos/${repo}/issues`, {
|
|
5897
6311
|
method: 'POST',
|
|
5898
6312
|
token,
|
|
5899
|
-
body: { title, body:
|
|
6313
|
+
body: { title, body: issueBodyWithAttachments(text, config, attachments), labels: [GH_FEEDBACK_LABEL] },
|
|
5900
6314
|
})
|
|
5901
6315
|
}
|
|
5902
6316
|
|
|
@@ -6255,7 +6669,9 @@ async function handleFeedback(req, res, config) {
|
|
|
6255
6669
|
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
6256
6670
|
|
|
6257
6671
|
try {
|
|
6258
|
-
|
|
6672
|
+
// 0.6.48:反馈可能带最多 4 个附件的 base64(每个 20 MB 上限,但 base64 后按 32 MB 算)。
|
|
6673
|
+
// 这里给 160 MB 的上限:够 4×20 MB 的极端情况,又不至于让一个请求把内存吃穿。
|
|
6674
|
+
const raw = await readBody(req, ROUTE_FEEDBACK_MAX_BODY)
|
|
6259
6675
|
const payload = raw.trim() ? JSON.parse(raw) : {}
|
|
6260
6676
|
const g = await ghToken(config, dshHome)
|
|
6261
6677
|
|
|
@@ -6344,7 +6760,9 @@ async function handleFeedback(req, res, config) {
|
|
|
6344
6760
|
const sent = []
|
|
6345
6761
|
const failed = []
|
|
6346
6762
|
for (const item of pending) {
|
|
6347
|
-
|
|
6763
|
+
// 0.6.48:队列里可能带着已经上传好的附件 URL(建 issue 那步失败时留下的),
|
|
6764
|
+
// 补发直接引用,不再重传 —— 附件已经在仓库资产里,重传只会留下垃圾。
|
|
6765
|
+
const r = await createIssue(g.repo, g.token, String(item.title || ''), String(item.body || ''), config, Array.isArray(item.attachments) ? item.attachments : [])
|
|
6348
6766
|
if (r.ok && r.json) sent.push({ number: r.json.number, url: r.json.html_url })
|
|
6349
6767
|
else failed.push(item)
|
|
6350
6768
|
}
|
|
@@ -6378,31 +6796,108 @@ async function handleFeedback(req, res, config) {
|
|
|
6378
6796
|
const text = String(payload.body || payload.detail || '').trim().slice(0, 6000)
|
|
6379
6797
|
if (!title) throw new Error(t('先写个标题,方便以后对上号', 'Give it a title so it can be found later'))
|
|
6380
6798
|
|
|
6381
|
-
//
|
|
6799
|
+
// 4a) 附件(issue #9:图片 / 视频)。面板把文件读成 base64 放进 payload.attachments:
|
|
6800
|
+
// [{ name, type, data }]。这里先校验再上传 —— 上传是不可撤销的(资产留在仓库里),
|
|
6801
|
+
// 所以宁可在本地就拒掉不合规的,也不要传上去再删。
|
|
6802
|
+
const attachments = []
|
|
6803
|
+
const attachErrors = []
|
|
6804
|
+
const rawAttachments = Array.isArray(payload.attachments) ? payload.attachments : []
|
|
6805
|
+
if (rawAttachments.length > FEEDBACK_MAX_ATTACH_COUNT) {
|
|
6806
|
+
throw new Error(t(
|
|
6807
|
+
`附件最多 ${FEEDBACK_MAX_ATTACH_COUNT} 个(收到 ${rawAttachments.length} 个)`,
|
|
6808
|
+
`At most ${FEEDBACK_MAX_ATTACH_COUNT} attachments (got ${rawAttachments.length})`,
|
|
6809
|
+
))
|
|
6810
|
+
}
|
|
6811
|
+
for (const item of rawAttachments) {
|
|
6812
|
+
const name = String((item && item.name) || '')
|
|
6813
|
+
const mime = feedbackAttachMime(name)
|
|
6814
|
+
if (!mime) {
|
|
6815
|
+
attachErrors.push(`${name || '?'}: ${t('不支持的文件类型(只收图片 / 视频 / 日志)', 'unsupported type (images, videos and logs only)')}`)
|
|
6816
|
+
continue
|
|
6817
|
+
}
|
|
6818
|
+
let buf = null
|
|
6819
|
+
try {
|
|
6820
|
+
const b64 = String((item && item.data) || '')
|
|
6821
|
+
// 先按 base64 长度粗筛:base64 约为原字节的 4/3,
|
|
6822
|
+
// 超上限十几倍的数据根本不该解码(否则先占一份内存再丢掉)。
|
|
6823
|
+
if (b64 && b64.length <= Math.ceil(FEEDBACK_MAX_ATTACH_BYTES * 4 / 3) + 8) buf = Buffer.from(b64, 'base64')
|
|
6824
|
+
} catch { buf = null }
|
|
6825
|
+
if (!buf || buf.length === 0) {
|
|
6826
|
+
attachErrors.push(`${name || '?'}: ${t('读不到文件内容', 'cannot read the file content')}`)
|
|
6827
|
+
continue
|
|
6828
|
+
}
|
|
6829
|
+
if (buf.length > FEEDBACK_MAX_ATTACH_BYTES) {
|
|
6830
|
+
attachErrors.push(`${name}: ${t(`超过 ${Math.round(FEEDBACK_MAX_ATTACH_BYTES / 1048576)} MB`, `larger than ${Math.round(FEEDBACK_MAX_ATTACH_BYTES / 1048576)} MB`)}`)
|
|
6831
|
+
continue
|
|
6832
|
+
}
|
|
6833
|
+
attachments.push({ name, type: mime, buf })
|
|
6834
|
+
}
|
|
6835
|
+
|
|
6836
|
+
// 没令牌:不硬失败,给一条浏览器预填链接(浏览器登录了 GitHub 就能点提交)。
|
|
6837
|
+
// 有附件时必须在消息里说清楚「附件没带上,要手动拖进网页」—— 静默丢弃是这类功能最常见的坑。
|
|
6382
6838
|
if (!g.token) {
|
|
6839
|
+
const localNames = attachments.map((a) => a.name)
|
|
6840
|
+
const notes = []
|
|
6841
|
+
if (localNames.length) {
|
|
6842
|
+
notes.push(t(
|
|
6843
|
+
`没有令牌:附件(${localNames.join('、')})没能上传,请在打开的页面里手动把它们拖进正文;标题和正文都已填好。`,
|
|
6844
|
+
`No token: attachments (${localNames.join(', ')}) were not uploaded — drag them into the body on the opened page; title and body are prefilled.`,
|
|
6845
|
+
))
|
|
6846
|
+
}
|
|
6847
|
+
// 被拒的附件也要说:悄悄丢掉一个 .exe,用户会以为「它上去了」
|
|
6848
|
+
if (attachErrors.length) {
|
|
6849
|
+
notes.push(t(`有附件没带上:${attachErrors.join('、')}`, `Some attachments were left out: ${attachErrors.join(', ')}`))
|
|
6850
|
+
}
|
|
6383
6851
|
sendJson(res, 200, {
|
|
6384
6852
|
ok: true,
|
|
6385
6853
|
needToken: true,
|
|
6386
6854
|
submitted: false,
|
|
6387
6855
|
fallbackUrl: newIssueUrl(g.repo, title, text, config),
|
|
6388
|
-
|
|
6856
|
+
pendingAttachments: localNames,
|
|
6857
|
+
attachmentErrors: attachErrors,
|
|
6858
|
+
error: notes.join(' ') || t('没有令牌:可以打开预填好的新建 issue 页面,在浏览器里点一下提交', 'No token: open the prefilled new-issue page and press submit in the browser'),
|
|
6389
6859
|
})
|
|
6390
6860
|
return
|
|
6391
6861
|
}
|
|
6392
6862
|
|
|
6393
|
-
|
|
6863
|
+
// 先传附件:资产一旦上传就留在仓库里,所以放在建 issue 之前——
|
|
6864
|
+
// 建 issue 失败时至少能把这些 URL 存进待发队列,补发时不用再传一遍。
|
|
6865
|
+
const uploaded = []
|
|
6866
|
+
for (const a of attachments) {
|
|
6867
|
+
const r = await uploadFeedbackAsset(g.repo, g.token, a.name, a.buf, a.type)
|
|
6868
|
+
if (r.ok) uploaded.push({ name: r.name, url: r.url, type: r.type })
|
|
6869
|
+
else attachErrors.push(`${a.name}: ${r.error}`)
|
|
6870
|
+
}
|
|
6871
|
+
|
|
6872
|
+
const r = await createIssue(g.repo, g.token, title, text, config, uploaded)
|
|
6394
6873
|
if (r.ok && r.json) {
|
|
6395
|
-
sendJson(res, 200, {
|
|
6874
|
+
sendJson(res, 200, {
|
|
6875
|
+
ok: true,
|
|
6876
|
+
number: r.json.number,
|
|
6877
|
+
url: r.json.html_url,
|
|
6878
|
+
item: issueToItem(r.json),
|
|
6879
|
+
attachments: uploaded.map((u) => ({ name: u.name, url: u.url })),
|
|
6880
|
+
attachmentErrors: attachErrors,
|
|
6881
|
+
})
|
|
6396
6882
|
return
|
|
6397
6883
|
}
|
|
6398
6884
|
// 建 issue 失败:进本机队列,网络好了点「补发」
|
|
6399
6885
|
const items = readOutbox(dshHome)
|
|
6400
|
-
items.push({
|
|
6886
|
+
items.push({
|
|
6887
|
+
title,
|
|
6888
|
+
body: text,
|
|
6889
|
+
createdAt: new Date().toISOString(),
|
|
6890
|
+
error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`,
|
|
6891
|
+
// 附件 URL 一起入队:补发时直接引用,不重复上传
|
|
6892
|
+
attachments: uploaded.map((u) => ({ name: u.name, url: u.url, type: u.type })),
|
|
6893
|
+
})
|
|
6401
6894
|
writeOutbox(dshHome, items)
|
|
6402
6895
|
sendJson(res, 200, {
|
|
6403
6896
|
ok: true,
|
|
6404
6897
|
queued: true,
|
|
6405
6898
|
remaining: items.length,
|
|
6899
|
+
attachments: uploaded.map((u) => ({ name: u.name, url: u.url })),
|
|
6900
|
+
attachmentErrors: attachErrors,
|
|
6406
6901
|
error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`,
|
|
6407
6902
|
})
|
|
6408
6903
|
} catch (error) {
|