dsh-config-sync-plugin 0.0.0-stage → 0.3.57
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/LICENSE +21 -0
- package/README.en.md +655 -0
- package/README.md +625 -2
- package/client.js +3208 -0
- package/cordis.patch.yml +16 -0
- package/index.js +4281 -0
- package/package.json +57 -3
- package/runtime/apply.ps1 +1437 -0
- package/runtime/capture.ps1 +1188 -0
- package/runtime/dsh-sync-common.ps1 +1002 -0
- package/runtime/install-plugin.ps1 +179 -0
- package/runtime/post-exit.ps1 +809 -0
- package/runtime/restore.ps1 +537 -0
- package/runtime/sync.ps1 +1029 -0
- package/runtime/tools/fix-session-cwd.mjs +200 -0
- package/tools/clientcheck.mjs +259 -0
- package/tools/pack-plugin.ps1 +79 -0
- package/tools/selftest.mjs +1461 -0
package/index.js
ADDED
|
@@ -0,0 +1,4281 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-config-sync — 宿主半身(Host half)
|
|
3
|
+
*
|
|
4
|
+
* 职责边界(重要)
|
|
5
|
+
* ----------------
|
|
6
|
+
* DSH 运行期间不可能安全地做 push/pull:capture 要读正在被应用持有的 cordis.patch.yml,
|
|
7
|
+
* apply 写完之后会被退出时的进程回写覆盖。所以这个插件**不执行**同步动作,只做两件事:
|
|
8
|
+
* 1. 只读体检:两端版本契约、仓库领先/落后、待提交文件、bundle 能否在本机解析;
|
|
9
|
+
* 2. 备命令:按本机实际路径生成一份 同步-推送.cmd / 同步-拉取.cmd,
|
|
10
|
+
* 退出 DSH 后双击即可跑,参数不用手敲。
|
|
11
|
+
*
|
|
12
|
+
* 约束
|
|
13
|
+
* ----
|
|
14
|
+
* - apply() 不抛异常:抛了会让 loader 那条 fiber 失败,启动期报 "Failed to load plugins"。
|
|
15
|
+
* - 只 inject 一定存在的服务(webServer),否则 fiber 会一直 PENDING 拖住整棵插件树。
|
|
16
|
+
* - 零第三方依赖:只用 node:* 内建(第三方插件不能 import @deepseek-ai/*,它们在 app.asar 里)。
|
|
17
|
+
*/
|
|
18
|
+
import { execFile, execFileSync } from 'node:child_process'
|
|
19
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
20
|
+
import { spawn } from 'node:child_process'
|
|
21
|
+
import { createHash } from 'node:crypto'
|
|
22
|
+
import { createRequire } from 'node:module'
|
|
23
|
+
import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
|
|
24
|
+
import { homedir, hostname, tmpdir } from 'node:os'
|
|
25
|
+
import { basename, dirname, isAbsolute, join, relative } from 'node:path'
|
|
26
|
+
import { fileURLToPath } from 'node:url'
|
|
27
|
+
|
|
28
|
+
const pluginRequire = createRequire(import.meta.url)
|
|
29
|
+
|
|
30
|
+
const PACKAGE_ID = 'dsh-config-sync-plugin'
|
|
31
|
+
const ROUTE_STATUS = '/config-sync/status'
|
|
32
|
+
const ROUTE_PREPARE = '/config-sync/prepare'
|
|
33
|
+
const ROUTE_SETTINGS = '/config-sync/settings'
|
|
34
|
+
const ROUTE_UPDATE = '/config-sync/update'
|
|
35
|
+
const ROUTE_SCOPE = '/config-sync/scope'
|
|
36
|
+
const ROUTE_CONFLICT = '/config-sync/conflict'
|
|
37
|
+
// 0.3.30:跨机路径确认(每台机器把自己的根目录报给插件一次)与问题反馈(落仓库 feedback\ 再推 GitHub)
|
|
38
|
+
const ROUTE_ROOTS = '/config-sync/roots'
|
|
39
|
+
const ROUTE_FEEDBACK = '/config-sync/feedback'
|
|
40
|
+
const SETTINGS_NAME = 'dsh-config-sync.json'
|
|
41
|
+
/** 本插件自己的安装目录(插件根,含 runtime\ 与 index.js)—— 插件备份还原时的目标。 */
|
|
42
|
+
const PLUGIN_ROOT = fileURLToPath(new URL('.', import.meta.url)).replace(/[\\/]+$/, '')
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 双语:面板是中文还是英文,跟客户端语言走(客户端每个请求都带 accept-language)。
|
|
46
|
+
* t(zh, en) 只在**面向用户**的文案上用;生成的 .cmd 脚本内容、日志一律保持中文。
|
|
47
|
+
*/
|
|
48
|
+
const langStore = new AsyncLocalStorage()
|
|
49
|
+
|
|
50
|
+
function pickLang(req) {
|
|
51
|
+
try {
|
|
52
|
+
const raw = String((req && req.headers && (req.headers['accept-language'] || req.headers['Accept-Language'])) || '').toLowerCase()
|
|
53
|
+
if (!raw) return 'zh'
|
|
54
|
+
return raw.includes('zh') ? 'zh' : 'en'
|
|
55
|
+
} catch { return 'zh' }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function t(zh, en) {
|
|
59
|
+
return langStore.getStore() === 'en' ? en : zh
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// ---- 插件自身的版本与更新源 ----
|
|
63
|
+
// 插件目录就是 index.js 所在目录(apply 会把它部署成 <AppRoot>\dsh-config-sync-plugin-<ver>\)。
|
|
64
|
+
const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
|
|
65
|
+
const PLUGIN_VERSION = (() => {
|
|
66
|
+
try {
|
|
67
|
+
const pkg = JSON.parse(readFileSync(join(PLUGIN_DIR, 'package.json'), 'utf8'))
|
|
68
|
+
return String(pkg.version || '')
|
|
69
|
+
} catch { return '' }
|
|
70
|
+
})()
|
|
71
|
+
// version.json 放在公开插件仓库根:{ version, notes, releasedAt, tgz, sha256 }
|
|
72
|
+
// 更新检查只读这一个文件,几百字节,不拉整包。公开仓库不需要令牌。
|
|
73
|
+
//
|
|
74
|
+
// 为什么不止一个地址:raw.githubusercontent.com 在这类网络上时通时不通(本机实测一次 20 秒超时 code=000、
|
|
75
|
+
// 另一次 538ms 正常),而宿主的 fetch 是 Node 内置实现、**不读系统代理**,超时一到就被 AbortController 掐断,
|
|
76
|
+
// 面板上只剩一句 "This operation was aborted"。
|
|
77
|
+
//
|
|
78
|
+
// 候选顺序:两个实时反代(gh-proxy / ghfast,实测 1 秒内拿到最新清单,且能把 tgz 一起拉下来)→ 直连 raw。
|
|
79
|
+
// **不要**用 jsDelivr 兜清单:它对 `@main` 这类分支别名有明显缓存(实测发版后仍返回上一版清单,purge 接口也没
|
|
80
|
+
// 立刻刷新),拿它当清单源会让"有新版本"晚几小时才出现,比读不到更误导人。
|
|
81
|
+
// 用户自己在设置里填了清单地址时只用他那一个 —— 不掺镜像,免得"读到的其实不是他指定的源"。
|
|
82
|
+
const RAW_MANIFEST_URL = 'https://raw.githubusercontent.com/QcWyGm/dsh-config-sync-plugin/main/version.json'
|
|
83
|
+
const UPDATE_MANIFEST_MIRRORS = [
|
|
84
|
+
'https://gh-proxy.com/https://raw.githubusercontent.com/QcWyGm/dsh-config-sync-plugin/main/version.json',
|
|
85
|
+
'https://ghfast.top/https://raw.githubusercontent.com/QcWyGm/dsh-config-sync-plugin/main/version.json',
|
|
86
|
+
RAW_MANIFEST_URL,
|
|
87
|
+
]
|
|
88
|
+
const UPDATE_MANIFEST_URL = RAW_MANIFEST_URL
|
|
89
|
+
// 30 秒:慢链路 10 秒根本不够(raw 通的时候也要几百毫秒到十几秒不等)
|
|
90
|
+
const UPDATE_FETCH_TIMEOUT = 30 * 1000
|
|
91
|
+
const UPDATE_CHECK_TTL = 30 * 60 * 1000
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* 定位客户端根目录(AppRoot)。
|
|
95
|
+
* 首选 config.appRoot;其次由插件自身位置反推(插件被 apply 部署在 <AppRoot>\dsh-config-sync-plugin-<ver>\,
|
|
96
|
+
* 上一级就是 AppRoot,换机不用改配置);都对不上时按常见安装位置探测。
|
|
97
|
+
* 判据:解包版有 resources\app\package.json,打包版有 resources\app.asar —— 只看目录名会让装错位置的情况蒙混过去,
|
|
98
|
+
* 只认解包版又会让 asar 构建的机器全部落空(那台会把"插件所在目录"当成客户端根)。
|
|
99
|
+
*/
|
|
100
|
+
function isAppRoot(path) {
|
|
101
|
+
if (!path) return false
|
|
102
|
+
if (isFile(join(path, 'resources', 'app', 'package.json'))) return true
|
|
103
|
+
// 打包版:判据是 resources\app.asar 存在。
|
|
104
|
+
// 注意 Electron 主进程里 statSync('...\\app.asar') 报的是**目录**(asar 被当成一个只读目录挂载),
|
|
105
|
+
// 只写 .isFile() 会让真实客户端里永远认不出客户端根 —— 外面用普通 node 验证却一切正常,极易漏掉。
|
|
106
|
+
const asar = join(path, 'resources', 'app.asar')
|
|
107
|
+
try {
|
|
108
|
+
const st = statSync(asar)
|
|
109
|
+
return st.isFile() || st.isDirectory()
|
|
110
|
+
} catch { return false }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 宿主自带 bundle 的落点:解包版 resources\app\dsh\node_modules,打包版 resources\app.asar.unpacked\dsh\node_modules。 */
|
|
114
|
+
function hostDshNodeModules(appRoot) {
|
|
115
|
+
if (!appRoot) return []
|
|
116
|
+
return [
|
|
117
|
+
join(appRoot, 'resources', 'app', 'dsh', 'node_modules'),
|
|
118
|
+
join(appRoot, 'resources', 'app.asar.unpacked', 'dsh', 'node_modules'),
|
|
119
|
+
]
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** 注册表里的 InstallLocation 最权威:客户端被卸载重装到别的盘时,只有它立刻指向新位置。
|
|
123
|
+
* 用 PowerShell 读三条 Uninstall 根(HKLM / WOW6432Node / HKCU),失败就当没读到。 */
|
|
124
|
+
let registryAppRootCache = null
|
|
125
|
+
let registryAppRootLoaded = false
|
|
126
|
+
function readRegistryAppRoot() {
|
|
127
|
+
if (registryAppRootLoaded) return registryAppRootCache
|
|
128
|
+
registryAppRootLoaded = true
|
|
129
|
+
registryAppRootCache = null
|
|
130
|
+
try {
|
|
131
|
+
const script = "$k=@('HKLM:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'," +
|
|
132
|
+
"'HKLM:\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*'," +
|
|
133
|
+
"'HKCU:\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*');" +
|
|
134
|
+
"Get-ItemProperty -Path $k -ErrorAction SilentlyContinue | " +
|
|
135
|
+
"Where-Object { $_.DisplayName -like '*DeepSeek Harness*' -and $_.InstallLocation } | " +
|
|
136
|
+
"Select-Object -First 1 -ExpandProperty InstallLocation"
|
|
137
|
+
const out = execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script],
|
|
138
|
+
{ windowsHide: true, timeout: 8000, encoding: 'utf8' })
|
|
139
|
+
const value = String(out || '').trim().replace(/[\\/]+$/, '')
|
|
140
|
+
if (value && (isFile(join(value, 'resources', 'app.asar')) || isFile(join(value, 'resources', 'app', 'package.json'))) ) {
|
|
141
|
+
registryAppRootCache = value
|
|
142
|
+
}
|
|
143
|
+
} catch { /* 读不到就退回按位置探测 */ }
|
|
144
|
+
return registryAppRootCache
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function resolveAppRoot(explicit) {
|
|
148
|
+
const candidates = []
|
|
149
|
+
if (explicit) candidates.push(explicit)
|
|
150
|
+
try { candidates.push(dirname(dirname(fileURLToPath(import.meta.url)))) } catch { /* 忽略 */ }
|
|
151
|
+
if (process.env.DSH_APP_ROOT) candidates.push(process.env.DSH_APP_ROOT)
|
|
152
|
+
const fromRegistry = readRegistryAppRoot()
|
|
153
|
+
if (fromRegistry) candidates.push(fromRegistry)
|
|
154
|
+
if (process.env.LOCALAPPDATA) candidates.push(join(process.env.LOCALAPPDATA, 'Programs', 'DeepSeekHarness'))
|
|
155
|
+
// 客户端会被卸载重装到别的盘(每台机器不一定同盘),所以把现有盘符都扫一遍;
|
|
156
|
+
// 判据仍是 resources\app.asar / resources\app\package.json,不看目录名。
|
|
157
|
+
for (const letter of 'CDEFGHIJKLMNOPQRSTUVWXYZ') {
|
|
158
|
+
candidates.push(`${letter}:\\DeepSeekHarness`, `${letter}:\\DSH`)
|
|
159
|
+
}
|
|
160
|
+
for (const c of candidates) {
|
|
161
|
+
if (isAppRoot(c)) return c
|
|
162
|
+
}
|
|
163
|
+
// 一个都认不出就返回空,让上层明确报错;绝不把插件自己所在的那一级当成客户端根。
|
|
164
|
+
return ''
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* 读客户端 app 版本:解包版直接读 resources\app\package.json;打包版从 app.asar 里取 dsh\package.json。
|
|
169
|
+
* 读不到返回 null(调用方只告警,不阻断)。
|
|
170
|
+
*/
|
|
171
|
+
function readAppMeta(appRoot) {
|
|
172
|
+
if (!appRoot) return null
|
|
173
|
+
const plain = readJson(join(appRoot, 'resources', 'app', 'package.json'))
|
|
174
|
+
if (plain) return plain
|
|
175
|
+
const asar = join(appRoot, 'resources', 'app.asar')
|
|
176
|
+
// Electron 主进程把 asar 当目录挂载:直接按「目录 + 内部路径」读最省事(外面普通 node 读不到就是 null,不用管)。
|
|
177
|
+
const viaMount = readJson(join(asar, 'dsh', 'package.json'))
|
|
178
|
+
if (viaMount) return viaMount
|
|
179
|
+
if (!isFile(asar)) return null
|
|
180
|
+
try {
|
|
181
|
+
const fd = openSync(asar, 'r')
|
|
182
|
+
try {
|
|
183
|
+
const head = Buffer.alloc(16)
|
|
184
|
+
readSync(fd, head, 0, 16, 0)
|
|
185
|
+
const headerSize = head.readUInt32LE(4)
|
|
186
|
+
const jsonLen = head.readUInt32LE(12)
|
|
187
|
+
if (jsonLen < 2 || jsonLen > 64 * 1024 * 1024) return null
|
|
188
|
+
const json = Buffer.alloc(jsonLen)
|
|
189
|
+
readSync(fd, json, 0, jsonLen, 16)
|
|
190
|
+
const header = JSON.parse(json.toString('utf8'))
|
|
191
|
+
const entry = header?.files?.dsh?.files?.['package.json'] || header?.files?.['package.json']
|
|
192
|
+
if (!entry || entry.size == null || entry.offset == null) return null
|
|
193
|
+
const body = Buffer.alloc(Number(entry.size))
|
|
194
|
+
readSync(fd, body, 0, Number(entry.size), 8 + headerSize + Number(entry.offset))
|
|
195
|
+
return JSON.parse(body.toString('utf8'))
|
|
196
|
+
} finally { closeSync(fd) }
|
|
197
|
+
} catch { return null }
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 读 JSON;失败返回 null,绝不抛。 */
|
|
201
|
+
function readJson(path) {
|
|
202
|
+
try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return null }
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function readText(path) {
|
|
206
|
+
try { return readFileSync(path, 'utf8') } catch { return '' }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 本机同步设置(仓库路径 + 远端地址 + SSH 私钥路径)。
|
|
211
|
+
* 只存路径不存密钥内容;文件跟着本机走、不进仓库,所以换机重填一次即可。
|
|
212
|
+
*/
|
|
213
|
+
function settingsPath(dshHome) {
|
|
214
|
+
return join(dshHome, SETTINGS_NAME)
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function readSettings(dshHome) {
|
|
218
|
+
const raw = readJson(settingsPath(dshHome)) || {}
|
|
219
|
+
return {
|
|
220
|
+
repoPath: typeof raw.repoPath === 'string' ? raw.repoPath : '',
|
|
221
|
+
remoteUrl: typeof raw.remoteUrl === 'string' ? raw.remoteUrl : '',
|
|
222
|
+
sshKey: typeof raw.sshKey === 'string' ? raw.sshKey : '',
|
|
223
|
+
// 两个自动化开关,默认关:不打开就完全保持原来的手动流程
|
|
224
|
+
autoPull: raw.autoPull === true,
|
|
225
|
+
autoPush: raw.autoPush === true,
|
|
226
|
+
autoRestart: raw.autoRestart !== false,
|
|
227
|
+
// 更新清单地址(留空用内置默认);换镜像/自建仓库或本地测试时才会填
|
|
228
|
+
updateManifestUrl: typeof raw.updateManifestUrl === 'string' ? raw.updateManifestUrl : '',
|
|
229
|
+
// 仓库是私有库时,读清单/下包都要带只读令牌(Gitee 私人令牌);留空就按匿名 raw 读
|
|
230
|
+
updateToken: typeof raw.updateToken === 'string' ? raw.updateToken : '',
|
|
231
|
+
// 备份快照放哪:留空 = 默认 <DshHome>\backups(apply.ps1 每次跑之前都往那儿打一份)
|
|
232
|
+
backupRoot: typeof raw.backupRoot === 'string' ? raw.backupRoot : '',
|
|
233
|
+
// 同步完成重启前把 DSH 的「默认工作区」校正到谁:
|
|
234
|
+
// 留空 = 自动找名字/路径是 default-workspace 的工作区;可填工作区路径或 ID;填 off 关闭。
|
|
235
|
+
defaultWorkspace: typeof raw.defaultWorkspace === 'string' ? raw.defaultWorkspace : '',
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 备份根:设置里填了就用填的,否则用默认 <DshHome>\backups。 */
|
|
240
|
+
function backupRootOf(dshHome, settings) {
|
|
241
|
+
const custom = settings && typeof settings.backupRoot === 'string' ? settings.backupRoot.trim() : ''
|
|
242
|
+
return custom || join(dshHome, 'backups')
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function writeSettings(dshHome, s) {
|
|
246
|
+
const payload = JSON.stringify({
|
|
247
|
+
repoPath: s.repoPath || '',
|
|
248
|
+
remoteUrl: s.remoteUrl || '',
|
|
249
|
+
sshKey: s.sshKey || '',
|
|
250
|
+
autoPull: s.autoPull === true,
|
|
251
|
+
autoPush: s.autoPush === true,
|
|
252
|
+
autoRestart: s.autoRestart !== false,
|
|
253
|
+
updateManifestUrl: s.updateManifestUrl || '',
|
|
254
|
+
updateToken: s.updateToken || '',
|
|
255
|
+
backupRoot: s.backupRoot || '',
|
|
256
|
+
defaultWorkspace: s.defaultWorkspace || '',
|
|
257
|
+
}, null, 2) + '\n'
|
|
258
|
+
writeFileSync(settingsPath(dshHome), payload, 'utf8')
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** 没配过时给一个能用的默认私钥:优先 gitee 那把,其次通用 id_ed25519。 */
|
|
262
|
+
function defaultSshKey() {
|
|
263
|
+
const dir = join(homedir(), '.ssh')
|
|
264
|
+
for (const name of ['id_ed25519_gitee', 'id_ed25519', 'id_rsa']) {
|
|
265
|
+
const p = join(dir, name)
|
|
266
|
+
if (isFile(p)) return p
|
|
267
|
+
}
|
|
268
|
+
return ''
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** ssh.exe 与私钥:生成脚本时用它们拼 GIT_SSH_COMMAND,免依赖 .ssh\config。
|
|
272
|
+
* GIT_SSH_COMMAND 的第一个词必须是可执行程序;Windows 上 Git 有两种安装位(系统级 / 用户级),
|
|
273
|
+
* 只查 %ProgramFiles% 会让用户级安装的机器拼出「-i …」这种非法命令(git 交给 sh 后报 invalid option)。
|
|
274
|
+
*/
|
|
275
|
+
function sshExeCandidates() {
|
|
276
|
+
const list = []
|
|
277
|
+
const add = (p) => { if (p) list.push(p) }
|
|
278
|
+
const lad = process.env.LOCALAPPDATA
|
|
279
|
+
if (lad) {
|
|
280
|
+
add(join(lad, 'Programs', 'Git', 'usr', 'bin', 'ssh.exe'))
|
|
281
|
+
add(join(lad, 'Programs', 'Git', 'mingw64', 'bin', 'ssh.exe'))
|
|
282
|
+
}
|
|
283
|
+
for (const r of [process.env.ProgramFiles, process.env.ProgramW6432, process.env['ProgramFiles(x86)']]) {
|
|
284
|
+
if (r) add(join(r, 'Git', 'usr', 'bin', 'ssh.exe'))
|
|
285
|
+
}
|
|
286
|
+
add(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'OpenSSH', 'ssh.exe'))
|
|
287
|
+
for (const dir of String(process.env.PATH || '').split(';')) {
|
|
288
|
+
const d = dir.trim()
|
|
289
|
+
if (d) add(join(d, 'ssh.exe'))
|
|
290
|
+
}
|
|
291
|
+
return list
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function resolveSshExe() {
|
|
295
|
+
for (const p of sshExeCandidates()) {
|
|
296
|
+
if (isFile(p)) return p
|
|
297
|
+
}
|
|
298
|
+
return ''
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** git 的 core.sshCommand 优先级最高:用户显式写的命令本身带 ssh 程序,直接照用。 */
|
|
302
|
+
function readSshCommandFromGitConfig(repo) {
|
|
303
|
+
const files = [join(homedir(), '.gitconfig')]
|
|
304
|
+
if (repo) files.push(join(repo, '.git', 'config'))
|
|
305
|
+
for (const f of files) {
|
|
306
|
+
try {
|
|
307
|
+
if (!isFile(f)) continue
|
|
308
|
+
const m = readFileSync(f, 'utf8').match(/^\s*sshCommand\s*=\s*(.+)$/mi)
|
|
309
|
+
if (m && m[1].trim()) return m[1].trim()
|
|
310
|
+
} catch { /* 忽略 */ }
|
|
311
|
+
}
|
|
312
|
+
return ''
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function isDir(path) {
|
|
316
|
+
try { return statSync(path).isDirectory() } catch { return false }
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function isFile(path) {
|
|
320
|
+
try { return statSync(path).isFile() } catch { return false }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* 一个目录算不算 dsh-config 仓库:判据是同时有 apply.ps1 与 profile/package.json
|
|
325
|
+
* (避免把同名目录认错)。sync.ps1 用来看「能不能真的推送/拉取」。
|
|
326
|
+
*/
|
|
327
|
+
function isRepoDir(dir) {
|
|
328
|
+
return Boolean(dir) && isFile(join(dir, 'apply.ps1')) && isFile(join(dir, 'profile', 'package.json'))
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 定位 dsh-config 仓库,并说清这个路径是怎么来的(设置文件 → 插件配置 → 自动探测)。
|
|
333
|
+
* 设置文件优先:用户可以在面板里改,不该被 cordis.patch.yml 里的旧值锁死。
|
|
334
|
+
*/
|
|
335
|
+
function resolveRepo(explicit, dshHome) {
|
|
336
|
+
const settingsRepo = dshHome ? readSettings(dshHome).repoPath : ''
|
|
337
|
+
const tried = []
|
|
338
|
+
const pick = (value, source) => {
|
|
339
|
+
if (!value) return null
|
|
340
|
+
tried.push(`${source}:${value}`)
|
|
341
|
+
// 空目录也是有效答案:新机器先把路径填好、等首次拉取,这时不该被自动探测到的另一个仓库顶掉
|
|
342
|
+
const phase = repoPhase(value)
|
|
343
|
+
return (phase === 'ok' || phase === 'empty') ? { repo: value, source } : null
|
|
344
|
+
}
|
|
345
|
+
// 设置里的路径是用户在面板里亲手填的:填了但已失效(目录被移走/改名)就原样报回去,
|
|
346
|
+
// 让面板停在"未配置"强制他重设,而不是静默换成自动探测到的另一个仓库。
|
|
347
|
+
if (settingsRepo && !isRepoDir(settingsRepo)) {
|
|
348
|
+
return { repo: settingsRepo, source: 'settings', tried }
|
|
349
|
+
}
|
|
350
|
+
for (const hit of [
|
|
351
|
+
pick(settingsRepo, 'settings'),
|
|
352
|
+
pick(explicit, 'config'),
|
|
353
|
+
(() => {
|
|
354
|
+
const env = process.env.DSH_CONFIG_REPO || ''
|
|
355
|
+
return env ? pick(env, 'env') : null
|
|
356
|
+
})(),
|
|
357
|
+
]) {
|
|
358
|
+
if (hit) return hit
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const home = homedir()
|
|
362
|
+
for (const c of ['D:\\dsh-config', 'G:\\dsh-config', 'C:\\dsh-config', join(home, 'dsh-config')]) {
|
|
363
|
+
if (isRepoDir(c)) {
|
|
364
|
+
tried.push(`自动探测:${c}`)
|
|
365
|
+
return { repo: c, source: 'auto' }
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
// 都没命中:把「用户填过但不对」的那个原样带回去,面板才能显示他填了什么、错在哪。
|
|
369
|
+
return { repo: settingsRepo || '', source: settingsRepo ? 'settings' : (explicit ? 'config' : 'none'), tried }
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* git 可执行文件的位置。
|
|
374
|
+
* Electron 主进程的 PATH 往往不含 Git(用户双击启动时继承的环境很干净),
|
|
375
|
+
* 裸 'git' 会 ENOENT,体检就只剩一堆 null。所以按常见安装位置先探测一遍。
|
|
376
|
+
*/
|
|
377
|
+
let gitExeCache = null
|
|
378
|
+
function resolveGitExe() {
|
|
379
|
+
if (gitExeCache !== null) return gitExeCache
|
|
380
|
+
const envRoot = process.env.ProgramFiles || 'C:\\Program Files'
|
|
381
|
+
const candidates = [
|
|
382
|
+
process.env.DSH_SYNC_GIT || '',
|
|
383
|
+
join(envRoot, 'Git', 'cmd', 'git.exe'),
|
|
384
|
+
join(process.env.ProgramW6432 || envRoot, 'Git', 'cmd', 'git.exe'),
|
|
385
|
+
join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'Git', 'cmd', 'git.exe'),
|
|
386
|
+
join(process.env.LOCALAPPDATA || '', 'Programs', 'Git', 'cmd', 'git.exe'),
|
|
387
|
+
'C:\\Program Files\\Git\\bin\\git.exe',
|
|
388
|
+
].filter((p) => p && p !== '\\' && !p.startsWith('\\'))
|
|
389
|
+
gitExeCache = candidates.find((p) => { try { return existsSync(p) } catch { return false } }) || 'git'
|
|
390
|
+
return gitExeCache
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/** 跑 git,拿标准输出;找不到 git 或失败返回 null。 */
|
|
394
|
+
function git(repo, args) {
|
|
395
|
+
return new Promise((resolve) => {
|
|
396
|
+
execFile(resolveGitExe(), ['-C', repo, ...args], { windowsHide: true, timeout: 20000 }, (err, stdout) => {
|
|
397
|
+
resolve(err ? null : String(stdout || '').trim())
|
|
398
|
+
})
|
|
399
|
+
})
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* 云端仓库到底有没有「可拉的内容」。
|
|
404
|
+
* 之前只看分支数(ls-remote --heads),结果踩了个大坑:远端 main 还在、树却被删空了,
|
|
405
|
+
* 分支数=1 → 判「有内容,只许拉取」,可拉下来是个空目录,状态永远停在 await-pull,
|
|
406
|
+
* 初始化推送的入口也永远不出现,人就被卡死。所以真正的判据是「分支指向的树里有没有文件」。
|
|
407
|
+
*
|
|
408
|
+
* 分两步,省网络:
|
|
409
|
+
* 1) ls-remote --heads 数分支 —— 0 个分支直接就是空仓库,不用再 fetch 了;
|
|
410
|
+
* 2) 有分支才探树:临时 bare 仓库 fetch --depth 1(优先 --filter=blob:none 只取树对象,
|
|
411
|
+
* 远端不支持就退回普通浅取),再 ls-tree 数文件。探测完删掉临时目录,不碰用户仓库。
|
|
412
|
+
* 返回 { heads, files }:files===null 表示判不了(离线/认证失败/超时),调用方按保守处理。
|
|
413
|
+
*/
|
|
414
|
+
const remoteProbeCache = new Map()
|
|
415
|
+
// 缓存放长到 5 分钟:探测是打一次真实的 ls-remote(+ 可能一次 fetch),不该每分钟都来一遍。
|
|
416
|
+
// 云端真变了也不怕:写操作(推送/拉取)都会自己取最新状态,这个值只用于面板上的「云端有没有内容」。
|
|
417
|
+
const REMOTE_PROBE_TTL = 300000
|
|
418
|
+
|
|
419
|
+
function gitProbeEnv(settings) {
|
|
420
|
+
const key = (settings && settings.sshKey) || defaultSshKey()
|
|
421
|
+
const hasKey = Boolean(key) && isFile(key)
|
|
422
|
+
const coreSsh = readSshCommandFromGitConfig('')
|
|
423
|
+
const sshExe = coreSsh ? '' : resolveSshExe()
|
|
424
|
+
const env = { ...process.env }
|
|
425
|
+
if (hasKey && coreSsh) env.GIT_SSH_COMMAND = coreSsh
|
|
426
|
+
else if (hasKey && sshExe) env.GIT_SSH_COMMAND = `"${sshExe}" -i "${key}" -o BatchMode=yes -o StrictHostKeyChecking=accept-new`
|
|
427
|
+
return env
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/** 跑一次 git,返回 { ok, out };失败不抛。 */
|
|
431
|
+
function runGit(args, env, timeout = 20000) {
|
|
432
|
+
return new Promise((resolve) => {
|
|
433
|
+
execFile(resolveGitExe(), args, { windowsHide: true, timeout, env }, (err, stdout) => {
|
|
434
|
+
resolve({ ok: !err, out: String(stdout || '') })
|
|
435
|
+
})
|
|
436
|
+
})
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function lsRemoteHeads(url, settings) {
|
|
440
|
+
return probeRemote(url, settings).then((p) => (p ? p.heads : null))
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** 临时 bare 仓库里数一次远端某个分支的文件数;失败返回 null。 */
|
|
444
|
+
async function remoteFileCount(url, settings, quiet) {
|
|
445
|
+
const env = gitProbeEnv(settings)
|
|
446
|
+
let dir = ''
|
|
447
|
+
try {
|
|
448
|
+
dir = mkdtempSync(join(tmpdir(), 'dcs-probe-'))
|
|
449
|
+
if (!(await runGit(['init', '--bare', '--quiet', dir], env, 15000)).ok) return null
|
|
450
|
+
// 只取树对象;远端不认 partial clone 时退回普通浅取
|
|
451
|
+
let fetched = await runGit(['-C', dir, 'fetch', '--depth', '1', '--no-tags', '--filter=blob:none', url, 'HEAD'], env, 45000)
|
|
452
|
+
if (!fetched.ok) fetched = await runGit(['-C', dir, 'fetch', '--depth', '1', '--no-tags', url, 'HEAD'], env, 45000)
|
|
453
|
+
if (!fetched.ok) return null
|
|
454
|
+
const tree = await runGit(['-C', dir, 'ls-tree', '-r', '--name-only', 'FETCH_HEAD'], env, 15000)
|
|
455
|
+
if (!tree.ok) return null
|
|
456
|
+
const files = tree.out.split('\n').filter((line) => line.trim()).length
|
|
457
|
+
return files
|
|
458
|
+
} catch {
|
|
459
|
+
return null
|
|
460
|
+
} finally {
|
|
461
|
+
if (dir) { try { rmSync(dir, { recursive: true, force: true }) } catch { } }
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async function probeRemote(url, settings) {
|
|
466
|
+
if (!url) return null
|
|
467
|
+
const hit = remoteProbeCache.get(url)
|
|
468
|
+
if (hit && Date.now() - hit.at < REMOTE_PROBE_TTL) return hit.value
|
|
469
|
+
// 先数分支(便宜),0 个分支就不用 fetch 了
|
|
470
|
+
const headsEnv = gitProbeEnv(settings)
|
|
471
|
+
const heads = await new Promise((resolve) => {
|
|
472
|
+
execFile(resolveGitExe(), ['ls-remote', '--heads', url], { windowsHide: true, timeout: 15000, env: headsEnv }, (err, stdout) => {
|
|
473
|
+
resolve(err ? null : String(stdout || '').split('\n').filter((line) => line.includes('refs/heads/')).length)
|
|
474
|
+
})
|
|
475
|
+
})
|
|
476
|
+
let value = null
|
|
477
|
+
if (heads === null) value = { heads: null, files: null }
|
|
478
|
+
else if (heads === 0) value = { heads: 0, files: 0 }
|
|
479
|
+
else value = { heads, files: await remoteFileCount(url, settings, 'quiet') }
|
|
480
|
+
remoteProbeCache.set(url, { at: Date.now(), value })
|
|
481
|
+
return value
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** 只读缓存,不触发任何网络动作。 */
|
|
485
|
+
function probeRemoteCached(url) {
|
|
486
|
+
const hit = remoteProbeCache.get(url)
|
|
487
|
+
return hit && Date.now() - hit.at < REMOTE_PROBE_TTL ? hit.value : null
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
/**
|
|
491
|
+
* 启动预热:插件装载后先探一次云端(只在本机仓库还没就位时才值得探)。
|
|
492
|
+
* 失败无所谓——probeRemote 自身全兜底,探不到就缓存 null,面板照常工作。
|
|
493
|
+
*/
|
|
494
|
+
function warmRemoteProbe(config) {
|
|
495
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
496
|
+
const settings = readSettings(dshHome)
|
|
497
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
498
|
+
if (repo && repoPhase(repo) === 'ok') return
|
|
499
|
+
const url = settings.remoteUrl || ''
|
|
500
|
+
if (!url) return
|
|
501
|
+
probeRemote(url, settings).catch(() => { })
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* 给 status 用的「带预算的探测」:缓存命中立刻返回;没命中就让探测在后台跑,
|
|
506
|
+
* 自己最多等 budgetMs —— 超时先返回「判不了」(heads/files 都是 null)。
|
|
507
|
+
*
|
|
508
|
+
* 为什么要有预算:Gitee 上 ls-remote 实测 2.5 秒,原样 await 会让整次 status 到
|
|
509
|
+
* 11 秒(还有备份统计的 7.7 秒),前端那一次 fetch 就很容易被宿主/浏览器掐掉,
|
|
510
|
+
* 表现成「几率性读取失败」。这里把等待压到一个可接受的常数,探测本身继续跑,
|
|
511
|
+
* 下次刷新(或后台预热)就能读到真值。
|
|
512
|
+
*/
|
|
513
|
+
function probeRemoteQuick(url, settings, budgetMs) {
|
|
514
|
+
if (!url) return Promise.resolve(null)
|
|
515
|
+
const cached = probeRemoteCached(url)
|
|
516
|
+
if (cached) return Promise.resolve(cached)
|
|
517
|
+
const unknown = { heads: null, files: null }
|
|
518
|
+
const running = probeRemote(url, settings)
|
|
519
|
+
return new Promise((resolve) => {
|
|
520
|
+
let done = false
|
|
521
|
+
const timer = setTimeout(() => {
|
|
522
|
+
if (done) return
|
|
523
|
+
done = true
|
|
524
|
+
resolve(probeRemoteCached(url) || unknown)
|
|
525
|
+
}, budgetMs)
|
|
526
|
+
if (typeof timer.unref === 'function') timer.unref()
|
|
527
|
+
running.then((value) => {
|
|
528
|
+
if (done) return
|
|
529
|
+
done = true
|
|
530
|
+
clearTimeout(timer)
|
|
531
|
+
resolve(value || unknown)
|
|
532
|
+
}, () => {
|
|
533
|
+
if (done) return
|
|
534
|
+
done = true
|
|
535
|
+
clearTimeout(timer)
|
|
536
|
+
resolve(unknown)
|
|
537
|
+
})
|
|
538
|
+
})
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function readBundles(profileDir) {
|
|
542
|
+
const pkg = readJson(join(profileDir, 'package.json'))
|
|
543
|
+
return {
|
|
544
|
+
bundles: Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles : [],
|
|
545
|
+
deps: Object.keys(pkg?.dependencies || {}),
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* 打包版客户端把宿主 bundle 塞在 app.asar 里(dsh/node_modules/<pkg>),磁盘上没有目录。
|
|
551
|
+
* 只查路径会把 asar 版的 20 多个自带 bundle 全判成「缺失」,进而误删实验性 bundle —— 所以读包内包名。
|
|
552
|
+
* 读不到(没 node 运行环境/头损坏)返回 null,调用方当作「判不了」,不要报缺失。
|
|
553
|
+
*/
|
|
554
|
+
let asarNamesCache = new Map()
|
|
555
|
+
function asarBundleNames(appRoot) {
|
|
556
|
+
if (!appRoot) return null
|
|
557
|
+
const asar = join(appRoot, 'resources', 'app.asar')
|
|
558
|
+
if (asarNamesCache.has(asar)) return asarNamesCache.get(asar)
|
|
559
|
+
let names = null
|
|
560
|
+
try {
|
|
561
|
+
if (isFile(asar)) {
|
|
562
|
+
const fd = openSync(asar, 'r')
|
|
563
|
+
try {
|
|
564
|
+
const head = Buffer.alloc(16)
|
|
565
|
+
readSync(fd, head, 0, 16, 0)
|
|
566
|
+
const jsonLen = head.readUInt32LE(12)
|
|
567
|
+
const json = Buffer.alloc(jsonLen)
|
|
568
|
+
readSync(fd, json, 0, jsonLen, 16)
|
|
569
|
+
const header = JSON.parse(json.toString('utf8'))
|
|
570
|
+
const root = header?.files?.dsh?.files?.node_modules || header?.files?.node_modules
|
|
571
|
+
names = []
|
|
572
|
+
const walk = (node, prefix, depth) => {
|
|
573
|
+
if (!node || !node.files || depth > 2) return
|
|
574
|
+
for (const [k, v] of Object.entries(node.files)) {
|
|
575
|
+
const name = prefix ? `${prefix}/${k}` : k
|
|
576
|
+
if (v && v.files) { names.push(name); walk(v, name, depth + 1) }
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
walk(root, '', 1)
|
|
580
|
+
} finally { closeSync(fd) }
|
|
581
|
+
}
|
|
582
|
+
} catch { names = null }
|
|
583
|
+
asarNamesCache.set(asar, names)
|
|
584
|
+
return names
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** bundle 解析顺序与 DSH 一致:profile\node_modules 优先,再宿主的 node_modules(解包版路径 / asar 包内)。 */
|
|
588
|
+
function unresolvedBundles(bundles, profileDir, appRoot) {
|
|
589
|
+
const searchRoots = [join(profileDir, 'node_modules'), ...hostDshNodeModules(appRoot)]
|
|
590
|
+
const inAsar = asarBundleNames(appRoot)
|
|
591
|
+
const missing = []
|
|
592
|
+
for (const b of bundles) {
|
|
593
|
+
const rel = String(b).replace(/\//g, '\\')
|
|
594
|
+
let found = false
|
|
595
|
+
for (const root of searchRoots) {
|
|
596
|
+
if (isFile(join(root, rel, 'package.json'))) { found = true; break }
|
|
597
|
+
}
|
|
598
|
+
if (!found && inAsar) found = inAsar.includes(String(b))
|
|
599
|
+
// 包内清单读不到时(inAsar === null)按「判不了」放过,绝不误报缺失
|
|
600
|
+
if (!found && inAsar !== null) missing.push(b)
|
|
601
|
+
}
|
|
602
|
+
return missing
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function missingDeps(deps, profileDir) {
|
|
606
|
+
return deps.filter((d) => !isDir(join(profileDir, 'node_modules', String(d).replace(/\//g, '\\'))))
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/**
|
|
610
|
+
* 读快照根上的 package.json(没有或读不动就 null)。
|
|
611
|
+
* 不用 isFile 单独判:Windows 上目录同名也会让 isFile 真,读一次最省事也最准。
|
|
612
|
+
*/
|
|
613
|
+
function readSnapshotPkg(dir) {
|
|
614
|
+
try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) } catch { return null }
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* 一份备份快照到底是「哪一类备份」。
|
|
619
|
+
*
|
|
620
|
+
* 备份根 ~\.dsh\backups 是**多用途共用**的,不只是配置快照:
|
|
621
|
+
* profile apply / restore 打的整份配置快照 顶层 package.json,name = dsh-profile-<名字>,带 dependencies
|
|
622
|
+
* plugin 插件自更新前打的插件本体备份 顶层 package.json,name = dsh-config-sync-plugin(带 dsh 字段),
|
|
623
|
+
* 或只有一个 dsh-config-sync-plugin-<ver>\ 子目录(半截残留)
|
|
624
|
+
* session 修会话前的会话目录备份 顶层全是 --<路径编码>-- 目录
|
|
625
|
+
* other 冲突对照 / 手工拷来的 / 认不出来的 只给手动还原指引
|
|
626
|
+
*
|
|
627
|
+
* 为什么不能只看「有没有 package.json」:插件包自己也带 package.json,
|
|
628
|
+
* 按那个判据会把插件备份当成配置快照,还原时把插件的 package.json 写进 profile,依赖清单直接丢。
|
|
629
|
+
*/
|
|
630
|
+
function classifySnapshot(name, dir) {
|
|
631
|
+
const pkg = readSnapshotPkg(dir)
|
|
632
|
+
const pkgName = String((pkg && pkg.name) || '')
|
|
633
|
+
// profile 优先:profile 的 package.json 里**也有** dsh 字段(dsh.profile.bundles),
|
|
634
|
+
// 拿 dsh 判插件会把整份配置快照误判成插件备份 —— 实测 config-* / manual-* 全部中招。
|
|
635
|
+
if (pkg && (/^dsh-profile-/i.test(pkgName) || (pkg.dsh && pkg.dsh.profile))) return 'profile'
|
|
636
|
+
if (pkg && pkgName === PACKAGE_ID) return 'plugin'
|
|
637
|
+
if (pkg && pkg.dependencies) return 'profile'
|
|
638
|
+
if (pkg && pkg.dsh) return 'plugin'
|
|
639
|
+
let entries = []
|
|
640
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return 'other' }
|
|
641
|
+
if (entries.length) {
|
|
642
|
+
// 会话目录在 sessions 下是 --<路径编码>--,原样被拷进快照
|
|
643
|
+
if (entries.every((e) => e.isDirectory() && /^--.*--$/.test(e.name))) return 'session'
|
|
644
|
+
if (entries.some((e) => e.isFile() && e.name === 'client.js') || entries.some((e) => e.isDirectory() && e.name === 'runtime')) return 'plugin'
|
|
645
|
+
if (entries.length === 1 && entries[0].isDirectory() && /^dsh-config-sync/i.test(entries[0].name)) return 'plugin'
|
|
646
|
+
}
|
|
647
|
+
// 名字兜底:目录名本身就是产出来源(空目录 / 半截残留也认得出是哪类)
|
|
648
|
+
if (/^plugin-/i.test(name)) return 'plugin'
|
|
649
|
+
if (/^session/i.test(name)) return 'session'
|
|
650
|
+
if (/^config-|^manual-/i.test(name)) return 'profile'
|
|
651
|
+
return 'other'
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* 还原会用到的快照。规则与 restore.ps1 保持一致:不加 -BackupDir 时取
|
|
656
|
+
* 「备份根」下按修改时间最新的一份;备份根默认 <DshHome>\backups,可在面板里改。
|
|
657
|
+
* 返回的不只是"最新一份":面板要列出所有快照让人挑,所以带上全量列表(最多 60 份)。
|
|
658
|
+
*/
|
|
659
|
+
function inspectBackup(dshHome, rootOverride) {
|
|
660
|
+
const root = rootOverride || join(dshHome, 'backups')
|
|
661
|
+
const defaultRoot = join(dshHome, 'backups')
|
|
662
|
+
const empty = { root, defaultRoot, custom: root !== defaultRoot, exists: false, latest: '', latestAt: null, count: 0, latestFiles: 0, candidates: [], snapshots: [] }
|
|
663
|
+
let names = []
|
|
664
|
+
try { names = readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name) } catch { return empty }
|
|
665
|
+
const all = []
|
|
666
|
+
for (const name of names) {
|
|
667
|
+
const dir = join(root, name)
|
|
668
|
+
try {
|
|
669
|
+
const st = statSync(dir)
|
|
670
|
+
// 体积/文件数**不在这里统计**:每个快照都是一份完整的 profile(几千个文件),
|
|
671
|
+
// 92 份快照 = 4.8 万个文件,逐个 statSync 要 7.7 秒 —— 而 status 每次刷新都会走这里。
|
|
672
|
+
// 列表只给「名字 + 时间 + 插件数 + 能不能还原」,体积交给资源管理器。
|
|
673
|
+
let plugins = 0
|
|
674
|
+
let bundles = 0
|
|
675
|
+
// 先分类,再决定怎么解析:只有 profile 快照的 package.json 才有「插件数」这层含义
|
|
676
|
+
const kind = classifySnapshot(name, dir)
|
|
677
|
+
const hasProfile = kind === 'profile' && isFile(join(dir, 'package.json'))
|
|
678
|
+
if (hasProfile) {
|
|
679
|
+
try {
|
|
680
|
+
const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))
|
|
681
|
+
plugins = Object.keys(pkg?.dependencies || {}).length
|
|
682
|
+
bundles = Array.isArray(pkg?.dsh?.profile?.bundles) ? pkg.dsh.profile.bundles.length : 0
|
|
683
|
+
} catch { }
|
|
684
|
+
}
|
|
685
|
+
// 非 profile 快照:顶层条目数就是「里面有几个东西」,面板上直接给个数(不递归,不拖慢刷新)
|
|
686
|
+
let entries = null
|
|
687
|
+
let entryNames = null
|
|
688
|
+
if (!hasProfile) {
|
|
689
|
+
try {
|
|
690
|
+
const list = readdirSync(dir, { withFileTypes: true })
|
|
691
|
+
entries = list.length
|
|
692
|
+
entryNames = list.slice(0, 6).map((e) => e.name)
|
|
693
|
+
} catch { }
|
|
694
|
+
}
|
|
695
|
+
all.push({ name, dir, at: st.mtimeMs, files: null, bytes: null, hasProfile, plugins, bundles, kind, entries, entryNames })
|
|
696
|
+
} catch { }
|
|
697
|
+
}
|
|
698
|
+
all.sort((a, b) => b.at - a.at)
|
|
699
|
+
if (!all.length) return { ...empty, exists: true }
|
|
700
|
+
const usable = all.filter((x) => x.hasProfile)
|
|
701
|
+
const latestPick = usable[0] || all[0]
|
|
702
|
+
const shape = (x) => ({
|
|
703
|
+
name: x.name,
|
|
704
|
+
dir: x.dir,
|
|
705
|
+
at: x.at,
|
|
706
|
+
files: x.files,
|
|
707
|
+
bytes: x.bytes,
|
|
708
|
+
// usable = 能一键还原。
|
|
709
|
+
// profile:必须有 package.json(otherwise 那是空快照)
|
|
710
|
+
// plugin / session:里面得真有东西(空目录还原只会得到一个空动作)
|
|
711
|
+
// other:认不出类型 → 不给自动还原,面板改给「手动还原」指引
|
|
712
|
+
usable: x.kind === 'profile' ? x.hasProfile : (x.kind === 'plugin' || x.kind === 'session') ? (Number(x.entries || 0) > 0) : false,
|
|
713
|
+
kind: x.kind,
|
|
714
|
+
entries: x.entries,
|
|
715
|
+
entryNames: x.entryNames,
|
|
716
|
+
plugins: x.plugins,
|
|
717
|
+
bundles: x.bundles,
|
|
718
|
+
})
|
|
719
|
+
return {
|
|
720
|
+
root,
|
|
721
|
+
defaultRoot,
|
|
722
|
+
custom: root !== defaultRoot,
|
|
723
|
+
exists: true,
|
|
724
|
+
latest: latestPick.dir,
|
|
725
|
+
latestAt: latestPick.at,
|
|
726
|
+
count: all.length,
|
|
727
|
+
latestFiles: latestPick.files,
|
|
728
|
+
candidates: all.slice(0, 8).map(shape),
|
|
729
|
+
snapshots: all.slice(0, 60).map(shape),
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/**
|
|
734
|
+
* 还原预览:算出「还原到这份快照会发生什么」,给面板的确认框用。
|
|
735
|
+
*
|
|
736
|
+
* 口径必须和 restore.ps1 -RollbackToPoint 完全一致,否则确认框会骗人:
|
|
737
|
+
* willWrite / willOverwrite = 快照里有、会被写回(内容不同才列入 overwrite)
|
|
738
|
+
* willRemove = 当前 profile 有、快照没有 → 会被移进 manual\rollback\files
|
|
739
|
+
* pluginsRemove = 当前依赖有、快照没有 → 会被撤走(链接删掉或实体目录移入 rollback)
|
|
740
|
+
* pluginsInstall = 快照依赖有、当前没有 → 还原后由 pnpm install 装上
|
|
741
|
+
*/
|
|
742
|
+
function restorePreview(dshHome, snapshotDir, config) {
|
|
743
|
+
const profileDir = join(dshHome, 'profiles', config?.profileName || 'desktop')
|
|
744
|
+
const profileFiles = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml']
|
|
745
|
+
const homeFiles = ['AGENTS.md', 'prompt-inject.md']
|
|
746
|
+
|
|
747
|
+
const willWrite = []
|
|
748
|
+
const willOverwrite = []
|
|
749
|
+
const same = (a, b) => {
|
|
750
|
+
try { return readFileSync(a, 'utf8') === readFileSync(b, 'utf8') } catch { return false }
|
|
751
|
+
}
|
|
752
|
+
for (const f of profileFiles) {
|
|
753
|
+
const src = join(snapshotDir, f)
|
|
754
|
+
if (!isFile(src)) continue
|
|
755
|
+
const dst = join(profileDir, f)
|
|
756
|
+
if (!isFile(dst)) { willWrite.push(f); continue }
|
|
757
|
+
if (!same(src, dst)) willOverwrite.push(f)
|
|
758
|
+
}
|
|
759
|
+
for (const f of homeFiles) {
|
|
760
|
+
const src = join(snapshotDir, f)
|
|
761
|
+
if (!isFile(src)) continue
|
|
762
|
+
const dst = join(dshHome, f)
|
|
763
|
+
if (!isFile(dst)) { willWrite.push(f); continue }
|
|
764
|
+
if (!same(src, dst)) willOverwrite.push(f)
|
|
765
|
+
}
|
|
766
|
+
const settingsDir = join(snapshotDir, 'settings')
|
|
767
|
+
if (isDir(settingsDir)) {
|
|
768
|
+
let names = []
|
|
769
|
+
try { names = readdirSync(settingsDir, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name) } catch { }
|
|
770
|
+
for (const n of names) {
|
|
771
|
+
const src = join(settingsDir, n)
|
|
772
|
+
const dst = join(dshHome, n)
|
|
773
|
+
if (!isFile(dst)) { willWrite.push(`settings/${n}`); continue }
|
|
774
|
+
if (!same(src, dst)) willOverwrite.push(`settings/${n}`)
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// 会移走的文件:当前 profile 目录里有、快照里没有(node_modules 单独按插件算)
|
|
779
|
+
const snapSet = new Set()
|
|
780
|
+
const walk = (root, onFile) => {
|
|
781
|
+
const stack = [root]
|
|
782
|
+
while (stack.length) {
|
|
783
|
+
const cur = stack.pop()
|
|
784
|
+
let entries = []
|
|
785
|
+
try { entries = readdirSync(cur, { withFileTypes: true }) } catch { continue }
|
|
786
|
+
for (const e of entries) {
|
|
787
|
+
const p = join(cur, e.name)
|
|
788
|
+
if (e.isDirectory()) stack.push(p)
|
|
789
|
+
else onFile(p, relative(root, p))
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
walk(snapshotDir, (_full, rel) => snapSet.add(rel))
|
|
794
|
+
const willRemove = []
|
|
795
|
+
walk(profileDir, (full, rel) => {
|
|
796
|
+
const normalized = rel.split('/').join('\\')
|
|
797
|
+
if (normalized.toLowerCase().startsWith('node_modules\\')) return
|
|
798
|
+
if (!snapSet.has(rel)) willRemove.push(normalized)
|
|
799
|
+
})
|
|
800
|
+
|
|
801
|
+
const readDeps = (p) => {
|
|
802
|
+
try { return Object.keys(JSON.parse(readFileSync(p, 'utf8'))?.dependencies || {}) } catch { return null }
|
|
803
|
+
}
|
|
804
|
+
const snapDeps = readDeps(join(snapshotDir, 'package.json')) || []
|
|
805
|
+
const curDeps = readDeps(join(profileDir, 'package.json'))
|
|
806
|
+
const pluginsRemove = curDeps === null ? [] : curDeps.filter((d) => !snapDeps.includes(d))
|
|
807
|
+
const pluginsInstall = snapDeps.filter((d) => !(curDeps || []).includes(d))
|
|
808
|
+
|
|
809
|
+
const CAP = 300
|
|
810
|
+
return {
|
|
811
|
+
snapshot: snapshotDir,
|
|
812
|
+
willWrite: willWrite.slice(0, CAP),
|
|
813
|
+
willOverwrite: willOverwrite.slice(0, CAP),
|
|
814
|
+
willRemove: willRemove.slice(0, CAP),
|
|
815
|
+
pluginsRemove,
|
|
816
|
+
pluginsInstall,
|
|
817
|
+
truncated: (willWrite.length + willOverwrite.length + willRemove.length) > CAP,
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* 插件备份 / 会话备份的还原预览。
|
|
823
|
+
*
|
|
824
|
+
* 这两类不是「回到某个时间点的 profile」,所以不复用 restorePreview 的差异口径:
|
|
825
|
+
* plugin 把快照里的插件文件写回当前插件安装目录(先整份备份当前插件)
|
|
826
|
+
* session 把快照里的 --<路径编码>-- 会话目录写回 ~\.dsh\sessions(先备份当前同名目录)
|
|
827
|
+
* 面板只需要「写到哪、写几个东西、先备份到哪」,不要给一堆 willRemove 让人误以为是时点回退。
|
|
828
|
+
*/
|
|
829
|
+
function restorePreviewForKind(snap, dshHome) {
|
|
830
|
+
const kind = snap.kind
|
|
831
|
+
if (kind === 'plugin') {
|
|
832
|
+
// 半截备份会多一层 dsh-config-sync-plugin-<ver>\:真正要写回的是里面的内容
|
|
833
|
+
let srcRoot = snap.dir
|
|
834
|
+
let entries = []
|
|
835
|
+
try { entries = readdirSync(srcRoot, { withFileTypes: true }) } catch { }
|
|
836
|
+
if (entries.length === 1 && entries[0].isDirectory() && /^dsh-config-sync/i.test(entries[0].name)) {
|
|
837
|
+
srcRoot = join(srcRoot, entries[0].name)
|
|
838
|
+
try { entries = readdirSync(srcRoot, { withFileTypes: true }) } catch { entries = [] }
|
|
839
|
+
}
|
|
840
|
+
return {
|
|
841
|
+
snapshot: snap.dir,
|
|
842
|
+
kind: 'plugin',
|
|
843
|
+
target: PLUGIN_ROOT,
|
|
844
|
+
source: srcRoot,
|
|
845
|
+
items: entries.slice(0, 40).map((e) => (e.isDirectory() ? e.name + '\\' : e.name)),
|
|
846
|
+
total: entries.length,
|
|
847
|
+
backupTo: join(dshHome, 'backups', `plugin-<当前版本>-<时间戳>`),
|
|
848
|
+
note: t(
|
|
849
|
+
'会把这份插件备份的文件写回当前插件安装目录,覆盖前先把当前插件整份备份成 plugin-<版本>-<时间戳>;还原后客户端重启才生效',
|
|
850
|
+
'This plugin backup will be written back into the current plugin folder. The current plugin is copied to plugin-<version>-<timestamp> first; the client must restart to pick it up.',
|
|
851
|
+
),
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
let dirs = []
|
|
855
|
+
try { dirs = readdirSync(snap.dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) } catch { }
|
|
856
|
+
return {
|
|
857
|
+
snapshot: snap.dir,
|
|
858
|
+
kind: 'session',
|
|
859
|
+
target: join(dshHome, 'sessions'),
|
|
860
|
+
items: dirs.slice(0, 40),
|
|
861
|
+
total: dirs.length,
|
|
862
|
+
backupTo: join(dshHome, 'backups', 'session-<时间戳>'),
|
|
863
|
+
note: t(
|
|
864
|
+
'会把这份备份里的会话目录写回 ~\\.dsh\\sessions,同名目录先整份备份成 session-<时间戳> 再覆盖;写回的是会话历史文件,不影响配置与插件',
|
|
865
|
+
'These session folders will be written back into ~\\.dsh\\sessions. Any folder with the same name is copied to session-<timestamp> first. Only conversation history is touched — config and plugins are not.',
|
|
866
|
+
),
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
/**
|
|
871
|
+
* 校验「要还原哪一份快照」:存在、在备份根之下、能认出类型、按类型具备还原条件。
|
|
872
|
+
* prepare(生成 cmd)、restore-preview、restore-now 共用,避免三处判断漂移。
|
|
873
|
+
* 返回 { dir, kind }:kind = profile | plugin | session。
|
|
874
|
+
*/
|
|
875
|
+
function resolveSnapshotDir(dshHome, backupDirRaw) {
|
|
876
|
+
const backupDir = String(backupDirRaw || '').trim()
|
|
877
|
+
if (!backupDir) throw new Error(t('没有指定要还原的备份目录', 'No backup directory was given'))
|
|
878
|
+
if (/["\r\n]/.test(backupDir)) throw new Error(t('备份路径里不能含引号或换行', 'The backup path must not contain quotes or newlines'))
|
|
879
|
+
if (!isDir(backupDir)) throw new Error(t(`备份目录不存在:${backupDir}`, `Backup directory does not exist: ${backupDir}`))
|
|
880
|
+
const root = backupRootOf(dshHome, readSettings(dshHome))
|
|
881
|
+
const rel = relative(root, backupDir)
|
|
882
|
+
if (rel.startsWith('..') || rel === '' || isAbsolute(rel)) {
|
|
883
|
+
throw new Error(t(`只能在备份根 ${root} 下选快照,不接受 ${backupDir}`, `Only snapshots under ${root} can be restored; refusing ${backupDir}`))
|
|
884
|
+
}
|
|
885
|
+
const kind = classifySnapshot(basename(backupDir), backupDir)
|
|
886
|
+
if (kind === 'other') {
|
|
887
|
+
throw new Error(t(
|
|
888
|
+
`这份备份认不出是哪一类(不是配置快照、插件备份或会话备份),不能自动还原:${backupDir}`
|
|
889
|
+
+ '。请按面板「还原备份」里的手动还原指引,把里面的文件拷到对应位置',
|
|
890
|
+
`Cannot tell what this backup is (not a config snapshot, plugin backup or session backup), so it cannot be restored automatically: ${backupDir}`
|
|
891
|
+
+ '. Follow the manual restore hint shown on the Restore card and copy the files into place yourself.',
|
|
892
|
+
))
|
|
893
|
+
}
|
|
894
|
+
if (kind === 'profile' && !isFile(join(backupDir, 'package.json'))) {
|
|
895
|
+
throw new Error(t(
|
|
896
|
+
`这份配置快照里没有 profile 文件(package.json),还原会失败:${backupDir}`,
|
|
897
|
+
`This config snapshot has no profile files (package.json) and cannot be restored: ${backupDir}`,
|
|
898
|
+
))
|
|
899
|
+
}
|
|
900
|
+
return { dir: backupDir, kind }
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* 本机仓库当前处在哪个阶段。面板上的「能不能推送 / 能不能拉取」全按它来判:
|
|
905
|
+
* ok 真仓库(有 .git 且是 dsh-config 结构)→ 推送、拉取都可以
|
|
906
|
+
* empty 目录在、但里面是空的(新机器刚建目录,或只有生成过的 同步-*.cmd)
|
|
907
|
+
* → 这是「等着从云端拉」的正常状态,不算异常;拉取会自动 init + fetch + checkout
|
|
908
|
+
* missing 目录不存在(路径写了但没建)
|
|
909
|
+
* unusable 目录在、但既不是空目录也不是仓库(多半填错路径了)
|
|
910
|
+
*/
|
|
911
|
+
function repoPhase(dir) {
|
|
912
|
+
if (!dir) return 'missing'
|
|
913
|
+
if (isRepoDir(dir)) return 'ok'
|
|
914
|
+
if (!isDir(dir)) return 'missing'
|
|
915
|
+
let entries = []
|
|
916
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return 'unusable' }
|
|
917
|
+
// 只有本插件自己生成的脚本、或隐藏项(.git 等)才算「空」:其余文件说明这目录本来就有别的东西
|
|
918
|
+
const others = entries.filter((e) => !e.name.startsWith('.') && !/^同步-[\s\S]*\.cmd$/i.test(e.name))
|
|
919
|
+
return others.length === 0 ? 'empty' : 'unusable'
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
/**
|
|
923
|
+
* 体检。全部只读,不写任何文件(除了 prepare 那次由用户显式触发的 cmd 生成)。
|
|
924
|
+
*/
|
|
925
|
+
async function inspect(config) {
|
|
926
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
927
|
+
const resolved = resolveRepo(config?.repoPath, dshHome)
|
|
928
|
+
const repo = resolved.repo
|
|
929
|
+
const appRoot = resolveAppRoot(config?.appRoot)
|
|
930
|
+
const profileDir = join(dshHome, 'profiles', config?.profileName || 'desktop')
|
|
931
|
+
|
|
932
|
+
const localApp = readAppMeta(appRoot)
|
|
933
|
+
const localVersion = typeof localApp?.version === 'string' ? localApp.version : ''
|
|
934
|
+
const electronVersion = readText(join(appRoot, 'version')).trim()
|
|
935
|
+
const contract = readJson(join(repo, 'profile', 'host-contract.json'))
|
|
936
|
+
const contractVersion = typeof contract?.appVersion === 'string' ? contract.appVersion : ''
|
|
937
|
+
|
|
938
|
+
const { bundles, deps } = readBundles(profileDir)
|
|
939
|
+
const unresolved = unresolvedBundles(bundles, profileDir, appRoot)
|
|
940
|
+
const missing = missingDeps(deps, profileDir)
|
|
941
|
+
|
|
942
|
+
const settings = readSettings(dshHome)
|
|
943
|
+
const gitRemoteUrl = repo && isDir(join(repo, '.git')) ? await git(repo, ['remote', 'get-url', 'origin']) : null
|
|
944
|
+
const sshKey = settings.sshKey || defaultSshKey()
|
|
945
|
+
|
|
946
|
+
const gitStatus = repo && isDir(join(repo, '.git'))
|
|
947
|
+
? (await git(repo, ['status', '--porcelain'])) ?? null
|
|
948
|
+
: null
|
|
949
|
+
const head = repo ? await git(repo, ['log', '-1', '--pretty=%h %s']) : null
|
|
950
|
+
const branch = repo ? await git(repo, ['rev-parse', '--abbrev-ref', 'HEAD']) : null
|
|
951
|
+
const counts = repo ? await git(repo, ['rev-list', '--left-right', '--count', 'HEAD...@{upstream}']) : null
|
|
952
|
+
let ahead = null
|
|
953
|
+
let behind = null
|
|
954
|
+
if (counts) {
|
|
955
|
+
const parts = counts.split(/\s+/)
|
|
956
|
+
ahead = Number(parts[0] ?? '')
|
|
957
|
+
behind = Number(parts[1] ?? '')
|
|
958
|
+
if (!Number.isFinite(ahead)) ahead = null
|
|
959
|
+
if (!Number.isFinite(behind)) behind = null
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
const dirty = gitStatus === null ? null : gitStatus.split('\n').filter(Boolean).length
|
|
963
|
+
const versionMatch = Boolean(localVersion && contractVersion && localVersion === contractVersion)
|
|
964
|
+
// 本机数据(会话/资料)有没有比"上次同步"更新:git 干净也可能有新会话没 capture
|
|
965
|
+
const syncState = readSyncState(dshHome)
|
|
966
|
+
const local = localPending(dshHome, syncState.lastSyncAt, config?.profileName, { repo, appRoot })
|
|
967
|
+
|
|
968
|
+
const advice = []
|
|
969
|
+
// 本机仓库处在哪个阶段:空白目录 = 等首次拉取,是正常状态,不该报异常
|
|
970
|
+
const phase = repoPhase(repo)
|
|
971
|
+
// 云端有没有「可拉的内容」:只在本地仓库还没就位时才探(真仓库不需要每次刷面板都打一次网络)
|
|
972
|
+
const remoteProbeUrl = gitRemoteUrl || settings.remoteUrl || ''
|
|
973
|
+
const remoteProbe = (remoteProbeUrl && phase !== 'ok') ? await probeRemoteQuick(remoteProbeUrl, settings, 2500) : null
|
|
974
|
+
const remoteHeads = remoteProbe ? remoteProbe.heads : null
|
|
975
|
+
// 分支指向的树里有几个文件 —— 这才是「有没有内容」的真判据:分支还在但树被删空,等同空中空
|
|
976
|
+
const remoteFiles = remoteProbe ? remoteProbe.files : null
|
|
977
|
+
if (!appRoot) {
|
|
978
|
+
advice.push(t(
|
|
979
|
+
'定位不到客户端根目录:插件不在 <客户端根> 下(如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.57),'
|
|
980
|
+
+ '或客户端是打包版(resources\\app.asar)而这里没认出来 —— 三份同步脚本会因此生成不了',
|
|
981
|
+
'Cannot locate the client root: the plugin is not under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.57), '
|
|
982
|
+
+ 'or this is a packaged build (resources\\app.asar) that was not recognized — the three sync scripts cannot be generated.',
|
|
983
|
+
))
|
|
984
|
+
}
|
|
985
|
+
if (!repo) {
|
|
986
|
+
advice.push(t(
|
|
987
|
+
'还没有配置仓库目录:请在下面的「本机仓库」卡里点「设置路径」,指向那台机器上的 dsh-config 仓库(含 apply.ps1 和 profile\\package.json)',
|
|
988
|
+
'The repo directory is not set: use the Local repo card below to point at the dsh-config repo on this machine (it must contain apply.ps1 and profile\\package.json).',
|
|
989
|
+
))
|
|
990
|
+
} else if (phase === 'empty' || phase === 'missing') {
|
|
991
|
+
const where = phase === 'missing'
|
|
992
|
+
? t(`目录还不存在(${repo})`, `the folder does not exist yet (${repo})`)
|
|
993
|
+
: t(`还是空目录(${repo})`, `is still an empty folder (${repo})`)
|
|
994
|
+
if (remoteFiles === 0) {
|
|
995
|
+
advice.push(t(
|
|
996
|
+
`本机仓库${where},云端仓库也还没有任何内容:点「初始化推送」把本机配置当作初始内容推上去(自动 git init + capture + 提交 + 推送)`,
|
|
997
|
+
`The local repo ${where} and the cloud has nothing yet: use "Initialize push" to upload this machine's config as the initial content (git init + capture + commit + push).`,
|
|
998
|
+
))
|
|
999
|
+
} else if (remoteFiles === null && remoteHeads === 0) {
|
|
1000
|
+
advice.push(t(
|
|
1001
|
+
`本机仓库${where},云端连不上/判不了(离线或认证失败):按老规矩先只允许拉取`,
|
|
1002
|
+
`The local repo ${where} and the cloud cannot be determined (offline or auth failure): only Pull is allowed, as before.`,
|
|
1003
|
+
))
|
|
1004
|
+
} else if (remoteHeads !== null && remoteHeads > 0 && remoteFiles === 0) {
|
|
1005
|
+
advice.push(t(
|
|
1006
|
+
`云端仓库只有分支、里面一个文件都没有(历史被删空了):点「初始化推送」可以把本机配置重新推成初始内容`,
|
|
1007
|
+
`The cloud repo has a branch but not a single file (its history was emptied): use "Initialize push" to upload this machine's config as the initial content again.`,
|
|
1008
|
+
))
|
|
1009
|
+
} else {
|
|
1010
|
+
advice.push(t(
|
|
1011
|
+
`本机仓库${where} —— 执行「拉取」会从云端把仓库内容拉到这里(首次拉取自动初始化,不需要推送)`,
|
|
1012
|
+
`The local repo ${where} — running Pull brings the repo down from the cloud (the first pull initializes it; no push needed).`,
|
|
1013
|
+
))
|
|
1014
|
+
}
|
|
1015
|
+
} else if (!isRepoDir(repo)) {
|
|
1016
|
+
advice.push(t(
|
|
1017
|
+
`这个目录既不是空目录、也不像 dsh-config 仓库(缺 apply.ps1 或 profile\\package.json):${repo} —— 请在「本机仓库」卡里重新设路径`,
|
|
1018
|
+
`That folder is neither empty nor a dsh-config repo (no apply.ps1 or profile\\package.json): ${repo} — set the path again in the Local repo card.`,
|
|
1019
|
+
))
|
|
1020
|
+
} else if (!isFile(join(repo, 'sync.ps1'))) {
|
|
1021
|
+
advice.push(t(
|
|
1022
|
+
`仓库目录里没有 sync.ps1,推送/拉取跑不起来:${repo}`,
|
|
1023
|
+
`The repo directory has no sync.ps1, so push/pull cannot run: ${repo}`,
|
|
1024
|
+
))
|
|
1025
|
+
}
|
|
1026
|
+
if (repo && !(gitRemoteUrl || settings.remoteUrl)) {
|
|
1027
|
+
advice.push(t(
|
|
1028
|
+
'还没有配置云端仓库地址:推送/拉取生成不了,请在「云端仓库」卡里填远端地址并保存',
|
|
1029
|
+
'The cloud repo is not set: push/pull cannot be generated — fill in the remote URL in the Cloud repo card and save.',
|
|
1030
|
+
))
|
|
1031
|
+
}
|
|
1032
|
+
if (!localVersion) {
|
|
1033
|
+
advice.push(t(
|
|
1034
|
+
`读不到客户端版本(${appRoot ? `${appRoot}\\resources\\app\\package.json 或 resources\\app.asar` : 'AppRoot 没定位到'})`,
|
|
1035
|
+
`Cannot read the client version (${appRoot ? `${appRoot}\\resources\\app\\package.json or resources\\app.asar` : 'AppRoot not found'})`,
|
|
1036
|
+
))
|
|
1037
|
+
}
|
|
1038
|
+
if (localVersion && contractVersion && !versionMatch) {
|
|
1039
|
+
advice.push(t(
|
|
1040
|
+
`两端客户端版本不同:本机 ${localVersion},仓库契约 ${contractVersion}。先升级较旧那台,或 pull 时加 -AllowVersionDrift`,
|
|
1041
|
+
`The two clients differ: this machine ${localVersion}, repo contract ${contractVersion}. Upgrade the older one, or pass -AllowVersionDrift when pulling.`,
|
|
1042
|
+
))
|
|
1043
|
+
}
|
|
1044
|
+
if (unresolved.length) {
|
|
1045
|
+
advice.push(t(
|
|
1046
|
+
`${unresolved.length} 个 bundle 在本机解析不到,启动会在 entry loading 崩溃:${unresolved.join(', ')}`,
|
|
1047
|
+
`${unresolved.length} bundle(s) cannot be resolved on this machine and will crash entry loading: ${unresolved.join(', ')}`,
|
|
1048
|
+
))
|
|
1049
|
+
}
|
|
1050
|
+
if (missing.length) {
|
|
1051
|
+
advice.push(t(
|
|
1052
|
+
`${missing.length} 个依赖没装(pnpm install 没跑成):${missing.join(', ')}`,
|
|
1053
|
+
`${missing.length} dependency(ies) missing (pnpm install did not finish): ${missing.join(', ')}`,
|
|
1054
|
+
))
|
|
1055
|
+
}
|
|
1056
|
+
if (behind !== null && behind > 0) {
|
|
1057
|
+
advice.push(t(`仓库落后 ${behind} 个提交:退出 DSH 后执行「拉取」`, `The repo is ${behind} commit(s) behind: run Pull after DSH exits.`))
|
|
1058
|
+
}
|
|
1059
|
+
if (ahead !== null && ahead > 0) {
|
|
1060
|
+
advice.push(t(`仓库领先 ${ahead} 个提交(本机改过还没推):退出 DSH 后执行「推送」`, `${ahead} local commit(s) not pushed yet: run Push after DSH exits.`))
|
|
1061
|
+
}
|
|
1062
|
+
if (dirty !== null && dirty > 0) {
|
|
1063
|
+
advice.push(t(`工作区有 ${dirty} 项未提交:退出 DSH 后跑「推送」会一并提交`, `${dirty} uncommitted change(s): running Push after DSH exits commits them too.`))
|
|
1064
|
+
}
|
|
1065
|
+
if (local.known && local.pending > 0) {
|
|
1066
|
+
advice.push(t(
|
|
1067
|
+
`本机有 ${local.pending} 个文件在上次同步之后有更新(新会话/资料之类),仓库里还没有:退出 DSH 后跑「推送」`,
|
|
1068
|
+
`${local.pending} file(s) changed since the last sync (new sessions/materials) and are not in the repo yet: run Push after DSH exits.`,
|
|
1069
|
+
))
|
|
1070
|
+
}
|
|
1071
|
+
if (!advice.length) advice.push(t('仓库与本机一致,没有待办', 'The repo matches this machine — nothing to do.'))
|
|
1072
|
+
|
|
1073
|
+
return {
|
|
1074
|
+
ok: true,
|
|
1075
|
+
at: Date.now(),
|
|
1076
|
+
repo: {
|
|
1077
|
+
path: repo,
|
|
1078
|
+
// 有路径 ≠ 目录还在:路径被移走/改名时这里必须是 false,面板才会重新强制设置。
|
|
1079
|
+
exists: Boolean(repo) && isRepoDir(repo),
|
|
1080
|
+
// 空目录 = 等首次拉取(正常状态,不报异常);pushAllowed/pullAllowed 就是按它算出来的门禁
|
|
1081
|
+
phase,
|
|
1082
|
+
empty: phase === 'empty',
|
|
1083
|
+
// 云端仓库的分支数:0=空仓库,null=没探成(离线/认证失败/真仓库时不探)
|
|
1084
|
+
remoteHeads,
|
|
1085
|
+
// 分支树里的文件数:0=有分支但内容为空(历史被删空也算),null=判不了
|
|
1086
|
+
remoteFiles,
|
|
1087
|
+
// 「云端有没有东西可拉」的真判据——不是分支数,是树里的文件数
|
|
1088
|
+
remoteEmpty: remoteFiles === 0,
|
|
1089
|
+
// 仓库三态,面板据此决定强调哪个按钮:
|
|
1090
|
+
// ok 真仓库,推送/拉取都行
|
|
1091
|
+
// await-pull 本机空、云端有内容 → 只允许拉取
|
|
1092
|
+
// await-init 两边都空(含「云端只剩空分支」)→ 只允许推送,而且这次推送就是「初始化推送」
|
|
1093
|
+
mode: phase === 'ok'
|
|
1094
|
+
? 'ok'
|
|
1095
|
+
: (remoteFiles === 0 ? 'await-init' : 'await-pull'),
|
|
1096
|
+
// 推送:真仓库,或「空目录 + 云端确实没文件」的首次推送(判不了时不放行,宁可按老规矩只拉)
|
|
1097
|
+
pushAllowed: phase === 'ok' || (phase === 'empty' && remoteFiles === 0),
|
|
1098
|
+
// 拉取:真仓库,或空目录/没建目录且云端确实有文件(sync.ps1 的 Initialize-RepoIfNeeded 会自动 init + fetch + checkout)
|
|
1099
|
+
pullAllowed: phase === 'ok' || ((phase === 'empty' || phase === 'missing') && remoteFiles !== 0),
|
|
1100
|
+
// 路径是怎么来的:settings=本机设置(面板可改)、config=插件配置、env=环境变量、auto=自动探测、none=没配
|
|
1101
|
+
source: resolved.source,
|
|
1102
|
+
configured: Boolean(settings.repoPath || config?.repoPath),
|
|
1103
|
+
tried: resolved.tried || [],
|
|
1104
|
+
branch: branch || '',
|
|
1105
|
+
head: head || '',
|
|
1106
|
+
dirty,
|
|
1107
|
+
ahead,
|
|
1108
|
+
behind,
|
|
1109
|
+
},
|
|
1110
|
+
version: { local: localVersion, contract: contractVersion, electron: electronVersion, match: versionMatch },
|
|
1111
|
+
// 本机数据侧:上次同步时间 + 「之后又写过多少文件」,与 repo.dirty 是两件事
|
|
1112
|
+
local: { ...syncState, ...local },
|
|
1113
|
+
bundles: { total: bundles.length, unresolved },
|
|
1114
|
+
deps: { total: deps.length, missing },
|
|
1115
|
+
advice,
|
|
1116
|
+
backup: inspectBackup(dshHome, backupRootOf(dshHome, settings)),
|
|
1117
|
+
remote: {
|
|
1118
|
+
url: gitRemoteUrl || settings.remoteUrl || '',
|
|
1119
|
+
urlSource: gitRemoteUrl ? 'git' : (settings.remoteUrl ? 'settings' : 'none'),
|
|
1120
|
+
// 配没配过云端仓库:推送/拉取都以它为前置,缺了面板就强制先设
|
|
1121
|
+
configured: Boolean(gitRemoteUrl || settings.remoteUrl),
|
|
1122
|
+
sshKey,
|
|
1123
|
+
sshKeyExists: Boolean(sshKey) && isFile(sshKey),
|
|
1124
|
+
sshKeyFrom: settings.sshKey ? 'settings' : (sshKey ? 'default' : 'none'),
|
|
1125
|
+
sshConfig: isFile(join(homedir(), '.ssh', 'config')),
|
|
1126
|
+
updateTokenSet: Boolean(settings.updateToken),
|
|
1127
|
+
// 备份根:留空=默认。面板「还原备份」卡据此显示当前值并判断是否被改过
|
|
1128
|
+
backupRoot: backupRootOf(dshHome, settings),
|
|
1129
|
+
backupRootCustom: Boolean(settings.backupRoot),
|
|
1130
|
+
settingsPath: settingsPath(dshHome),
|
|
1131
|
+
},
|
|
1132
|
+
paths: { appRoot, dshHome, profileDir },
|
|
1133
|
+
// 「本机路径」区平时不在页面上出现(0.3.37)。面板靠这三个计数决定标题行按钮是不是该变橙色,
|
|
1134
|
+
// 所以计数必须在 status 里给出——不能等用户把那一区点开才知道有没有事。
|
|
1135
|
+
localPaths: (() => {
|
|
1136
|
+
const countItems = (doc, key) => {
|
|
1137
|
+
const list = doc && Array.isArray(doc[key]) ? doc[key] : []
|
|
1138
|
+
return list.length
|
|
1139
|
+
}
|
|
1140
|
+
const pendingDoc = readJson(pendingPathOf(dshHome)) || {}
|
|
1141
|
+
const absDoc = readJson(absolutePathsPathOf(dshHome)) || {}
|
|
1142
|
+
const ovDoc = readJson(overwritePathOf(dshHome)) || {}
|
|
1143
|
+
const pending = countItems(pendingDoc, 'missing')
|
|
1144
|
+
// 根外路径清单是「推送时」capture 写下来的:本机自己推的,本机这些路径当然都在,
|
|
1145
|
+
// 不该算告警。只有清单来自另一台机器(本机是接收方)时才是真问题,才计入告警数。
|
|
1146
|
+
const absMachine = String(absDoc.machine || '')
|
|
1147
|
+
const absFromOther = Boolean(absMachine) && Boolean(localMachineName()) && !sameMachine(absMachine, localMachineName())
|
|
1148
|
+
const absolute = absFromOther ? countItems(absDoc, 'items') : 0
|
|
1149
|
+
const overwrite = countItems(ovDoc, 'items')
|
|
1150
|
+
// 三类都算告警(0.3.40):待确认路径、仓库里的根外绝对路径(限别的机器写的)、被覆盖的本机配置。
|
|
1151
|
+
// alert 与 total 目前同值,字段分开留着:面板只看 alert,以后要拆开也不用改前端。
|
|
1152
|
+
const total = pending + absolute + overwrite
|
|
1153
|
+
return { pending, absolute, overwrite, alert: total, total, absMachine, absFromOtherMachine: absFromOther }
|
|
1154
|
+
})(),
|
|
1155
|
+
auto: {
|
|
1156
|
+
pull: settings.autoPull === true,
|
|
1157
|
+
push: settings.autoPush === true,
|
|
1158
|
+
restart: settings.autoRestart !== false,
|
|
1159
|
+
checking: autoState.checking,
|
|
1160
|
+
lastCheckAt: autoState.lastCheckAt,
|
|
1161
|
+
lastCheckError: autoState.lastCheckError,
|
|
1162
|
+
drift: autoState.drift,
|
|
1163
|
+
pending: autoState.pending,
|
|
1164
|
+
watcherStartedAt: autoState.watcherStartedAt,
|
|
1165
|
+
script: autoScript(dshHome, repo),
|
|
1166
|
+
// post-exit.ps1 上次执行的结果(成功/失败/是否回滚),客户端启动后据此弹 5 秒提示
|
|
1167
|
+
lastResult: readAutoResult(dshHome),
|
|
1168
|
+
},
|
|
1169
|
+
// 拉取被本机文件挡住时 sync.ps1 留下的冲突清单,面板「同步冲突」卡据此渲染
|
|
1170
|
+
conflicts: (() => {
|
|
1171
|
+
const c = readConflicts(dshHome)
|
|
1172
|
+
if (!c) return { exists: false, total: 0, pending: 0, at: '', backupDir: '' }
|
|
1173
|
+
const pending = c.items.filter((it) => !it.choice).length
|
|
1174
|
+
return { exists: true, total: c.items.length, pending, at: c.at || '', backupDir: c.backupDir || '' }
|
|
1175
|
+
})(),
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
/** 只在 Host 本机、且来源可信时放行(防任意网页 POST 进来)。 */
|
|
1180
|
+
function originAllowed(req) {
|
|
1181
|
+
const host = String(req.headers.host || '')
|
|
1182
|
+
const hostLocal = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host)
|
|
1183
|
+
const site = String(req.headers['sec-fetch-site'] || '').toLowerCase()
|
|
1184
|
+
if (site === 'cross-site' || site === 'same-site') return false
|
|
1185
|
+
const origin = req.headers.origin
|
|
1186
|
+
if (origin === undefined || origin === '') return true
|
|
1187
|
+
if (origin === 'null') return hostLocal
|
|
1188
|
+
if (/^app:/i.test(String(origin))) return hostLocal
|
|
1189
|
+
try { return new URL(String(origin)).host === host } catch { return false }
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
function sendJson(res, code, body) {
|
|
1193
|
+
try {
|
|
1194
|
+
res.statusCode = code
|
|
1195
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
1196
|
+
res.setHeader('cache-control', 'no-store')
|
|
1197
|
+
res.end(JSON.stringify(body))
|
|
1198
|
+
} catch { /* 客户端已断开就忽略 */ }
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function readBody(req) {
|
|
1202
|
+
return new Promise((resolve, reject) => {
|
|
1203
|
+
let data = ''
|
|
1204
|
+
req.on('data', (c) => {
|
|
1205
|
+
data += c
|
|
1206
|
+
if (data.length > 64 * 1024) { reject(new Error('body too large')); req.destroy() }
|
|
1207
|
+
})
|
|
1208
|
+
req.on('end', () => resolve(data))
|
|
1209
|
+
req.on('error', reject)
|
|
1210
|
+
})
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
/**
|
|
1214
|
+
* 生成"退出后执行"的 cmd:参数按本机实际路径写死,双击即可。
|
|
1215
|
+
* action: push | pull | restore
|
|
1216
|
+
*/
|
|
1217
|
+
const PS_EXE = '%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -ExecutionPolicy Bypass -NoProfile'
|
|
1218
|
+
// 绝对路径调任务列表和代码页:PATH 被裁过(或用户改坏)时也能跑,别指望 `tasklist` 能解析到
|
|
1219
|
+
const TASKLIST = '%SystemRoot%\\System32\\tasklist.exe'
|
|
1220
|
+
const CHCP = '%SystemRoot%\\System32\\chcp.com'
|
|
1221
|
+
const FIND = '%SystemRoot%\\System32\\find.exe'
|
|
1222
|
+
const PROC_GUARD = [
|
|
1223
|
+
`${TASKLIST} /fi "imagename eq DeepSeek Harness.exe" | ${FIND} /i "DeepSeek Harness.exe" >nul && (`,
|
|
1224
|
+
' echo [X] DeepSeek Harness 还在运行,请先完全退出(窗口 + 托盘)再重试。',
|
|
1225
|
+
' pause',
|
|
1226
|
+
' exit /b 1',
|
|
1227
|
+
')',
|
|
1228
|
+
]
|
|
1229
|
+
|
|
1230
|
+
function cmdHead(title) {
|
|
1231
|
+
return [
|
|
1232
|
+
'@echo off',
|
|
1233
|
+
`${CHCP} 65001 >nul`,
|
|
1234
|
+
'setlocal',
|
|
1235
|
+
`echo 本脚本由 DSH 插件 dsh-config-sync-plugin 生成:${title}`,
|
|
1236
|
+
...PROC_GUARD,
|
|
1237
|
+
'echo.',
|
|
1238
|
+
]
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/**
|
|
1242
|
+
* cmd 的 echo 会把 < > | & ^ 当语法、把 % 当变量展开:
|
|
1243
|
+
* 直接 echo 一句带 `<时间戳>` 的提示,双击时会变成"从叫 时间戳 的文件读输入"并报
|
|
1244
|
+
* The system cannot find the file specified,那句话还打不出来。所有动态文案先过这里。
|
|
1245
|
+
*/
|
|
1246
|
+
function echoSafe(text) {
|
|
1247
|
+
return String(text).replace(/%/g, '%%').replace(/[<>|&^]/g, (c) => '^' + c)
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* 生成 cmd 时要调用的 PowerShell 入口从哪来:
|
|
1252
|
+
* 1) 仓库里已经有 sync.ps1 / restore.ps1 → 用仓库那份(同步脚本随之更新);
|
|
1253
|
+
* 2) 只有插件、仓库还没克隆(新机器刚装完)→ 用插件自带的 runtime\(随 tgz 一起发布)。
|
|
1254
|
+
* 两条路径都必须存在,否则明确报错,不生成一个双击必然失败的脚本。
|
|
1255
|
+
*/
|
|
1256
|
+
function pickPs1(repo, name) {
|
|
1257
|
+
const fromRepo = join(repo, name)
|
|
1258
|
+
if (isFile(fromRepo)) return fromRepo
|
|
1259
|
+
const fromPlugin = join(pluginRoot(), 'runtime', name)
|
|
1260
|
+
if (isFile(fromPlugin)) return fromPlugin
|
|
1261
|
+
throw new Error(t(
|
|
1262
|
+
`找不到 ${name}:仓库里没有(${fromRepo}),插件自带的 runtime 也没有(${fromPlugin})`,
|
|
1263
|
+
`Cannot find ${name}: not in the repo (${fromRepo}) and not in the plugin's bundled runtime (${fromPlugin})`,
|
|
1264
|
+
))
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
function pluginRoot() {
|
|
1268
|
+
try { return dirname(fileURLToPath(import.meta.url)) } catch { return '' }
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
function buildCmd(config, action, repo, appRoot, dshHome, state = {}) {
|
|
1272
|
+
const isRestore = action === 'restore' || action === 'restore-backup'
|
|
1273
|
+
const restorePs1 = isRestore ? pickPs1(repo, 'restore.ps1') : ''
|
|
1274
|
+
const syncPs1 = isRestore ? '' : pickPs1(repo, 'sync.ps1')
|
|
1275
|
+
// 仓库还没克隆时先建出目录,脚本要落在那里;clone 由 sync.ps1 首次执行时做完。
|
|
1276
|
+
if (!isDir(repo)) { try { mkdirSync(repo) } catch { /* 建不出来就让后面的 writeFileSync 报 */ } }
|
|
1277
|
+
const common = [`-RepoRoot "${repo}"`, `-AppRoot "${appRoot}"`, `-DshHome "${dshHome}"`]
|
|
1278
|
+
|
|
1279
|
+
// push/pull 要跟远端认证:设置里配了私钥就用它,不靠 .ssh\config 的默认选择。
|
|
1280
|
+
// 铁律:GIT_SSH_COMMAND 必须以可执行程序开头。找不到 ssh.exe 时宁可不设(交给 .ssh\config),
|
|
1281
|
+
// 也不能输出「-i "key" -o …」——git 会把它当命令交给 sh,直接 invalid option,报错还伪装成"仓库读不到"。
|
|
1282
|
+
const settings = readSettings(dshHome)
|
|
1283
|
+
const key = settings.sshKey || defaultSshKey()
|
|
1284
|
+
const hasKey = Boolean(key) && isFile(key)
|
|
1285
|
+
const coreSsh = readSshCommandFromGitConfig(repo)
|
|
1286
|
+
const sshExe = coreSsh ? '' : resolveSshExe()
|
|
1287
|
+
let envLines = []
|
|
1288
|
+
if (hasKey && coreSsh) {
|
|
1289
|
+
envLines = [
|
|
1290
|
+
`set GIT_SSH_COMMAND=${coreSsh}`,
|
|
1291
|
+
`echo ${echoSafe(`认证:git config core.sshCommand(私钥 ${key} 由该命令使用)`)}`,
|
|
1292
|
+
]
|
|
1293
|
+
} else if (hasKey && sshExe) {
|
|
1294
|
+
envLines = [
|
|
1295
|
+
`set GIT_SSH_COMMAND="${sshExe}" -i "${key}" -o BatchMode=yes -o StrictHostKeyChecking=accept-new`,
|
|
1296
|
+
`echo ${echoSafe(`认证:SSH 私钥 ${key}`)}`,
|
|
1297
|
+
`echo ${echoSafe(`认证:ssh ${sshExe}`)}`,
|
|
1298
|
+
]
|
|
1299
|
+
} else if (hasKey) {
|
|
1300
|
+
envLines = [
|
|
1301
|
+
`echo ${echoSafe(`认证:私钥 ${key}`)}`,
|
|
1302
|
+
`echo ${echoSafe('认证:本机没找到 ssh.exe,脚本内不设 GIT_SSH_COMMAND(它必须以可执行程序开头)')}`,
|
|
1303
|
+
`echo ${echoSafe('认证:改为交给 .ssh\\config;若仍报 Could not read from remote,就装 Git 官方版或配 git config core.sshCommand')}`,
|
|
1304
|
+
]
|
|
1305
|
+
} else {
|
|
1306
|
+
envLines = [`echo ${echoSafe('认证:未配置私钥,交给 .ssh\\config 决定')}`]
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
if (isRestore) {
|
|
1310
|
+
// 生成时如果已经有快照,就把那一份明写进脚本(双击前就知道退回哪里);
|
|
1311
|
+
// 还没有快照(新机器刚装插件)时不写 -BackupDir,交给 restore.ps1 运行时取最新一份 ——
|
|
1312
|
+
// 否则脚本会一直咬住"生成那一刻没有快照",之后拉取生成了快照也用不上。
|
|
1313
|
+
// 面板「还原备份」里点某一行的还原时,state.backupDir 会带来那一份的绝对路径(已校验在备份根之下)。
|
|
1314
|
+
const settings = readSettings(dshHome)
|
|
1315
|
+
const backup = inspectBackup(dshHome, backupRootOf(dshHome, settings))
|
|
1316
|
+
const picked = String(state.backupDir || '')
|
|
1317
|
+
const pickedSnap = picked ? (backup.snapshots || []).find((s) => s.dir === picked) : null
|
|
1318
|
+
const backupArg = (picked || backup.latest) ? [`-BackupDir "${picked || backup.latest}"`] : []
|
|
1319
|
+
// 指定的是插件备份 / 会话备份时,restore.ps1 要按类型走不同分支(默认 profile)
|
|
1320
|
+
const kind = pickedSnap ? pickedSnap.kind : ''
|
|
1321
|
+
const kindArg = kind && kind !== 'profile' ? [`-SnapshotKind "${kind}"`] : []
|
|
1322
|
+
const pluginArg = kind === 'plugin' ? [`-PluginDir "${pluginRoot()}"`] : []
|
|
1323
|
+
const allArgs = [...common, ...backupArg, ...kindArg, ...pluginArg]
|
|
1324
|
+
const dry = `${PS_EXE} -File "${restorePs1}" ${allArgs.join(' ')} -DryRun`
|
|
1325
|
+
const real = `${PS_EXE} -File "${restorePs1}" ${allArgs.join(' ')}`
|
|
1326
|
+
const backupLines = (picked || backup.latest)
|
|
1327
|
+
? [
|
|
1328
|
+
`echo ${echoSafe(`备份快照:${picked || backup.latest}`)}`,
|
|
1329
|
+
`echo ${echoSafe(`快照时间:${new Date(pickedSnap ? pickedSnap.at : backup.latestAt).toLocaleString('zh-CN', { hour12: false })} 备份根下共 ${backup.count} 份,这份含 ${pickedSnap ? pickedSnap.files : backup.latestFiles} 个文件`)}`,
|
|
1330
|
+
]
|
|
1331
|
+
: [
|
|
1332
|
+
`echo ${echoSafe(`备份快照:${backup.root}(生成脚本时这里还没有快照)`)}`,
|
|
1333
|
+
`echo ${echoSafe('执行时由 restore.ps1 自动取该目录下最新一份;若那时仍为空,会提示你先跑一次拉取。')}`,
|
|
1334
|
+
]
|
|
1335
|
+
const whatItDoes = kind === 'plugin'
|
|
1336
|
+
? t('把当前插件回滚到这份插件备份(先把当前插件整份备份,再覆盖)', 'Roll the plugin back to this plugin backup (the current plugin is copied aside first, then overwritten)')
|
|
1337
|
+
: (kind === 'session'
|
|
1338
|
+
? t('把会话目录还原成这份会话备份(先把当前同名目录备份,再覆盖)', 'Restore the session folders from this backup (folders with the same name are copied aside first, then overwritten)')
|
|
1339
|
+
: t('把本机 profile 退回到下面这个快照(先自保、再回退、再核对/重装依赖)。', 'Roll the local profile back to this snapshot (copy the current state aside, restore, then verify/reinstall dependencies).'))
|
|
1340
|
+
const text = [
|
|
1341
|
+
...cmdHead(whatItDoes),
|
|
1342
|
+
...backupLines,
|
|
1343
|
+
'echo.',
|
|
1344
|
+
'echo 要换成别的快照或仓库某提交,编辑本文件,把 -BackupDir 改掉或换成 -FromCommit。',
|
|
1345
|
+
'echo.',
|
|
1346
|
+
'echo [第一步] 只看不动,先打印还原计划:',
|
|
1347
|
+
dry,
|
|
1348
|
+
'echo.',
|
|
1349
|
+
'if /i "%~1"=="--yes" goto SYNC_RUN',
|
|
1350
|
+
'set /p GO=按上面的计划执行还原?(y/N) ',
|
|
1351
|
+
'if /i "%GO%"=="y" goto SYNC_RUN',
|
|
1352
|
+
`echo ${echoSafe('没有收到确认(y),已退出:本机什么都没改。')}`,
|
|
1353
|
+
'exit /b 0',
|
|
1354
|
+
':SYNC_RUN',
|
|
1355
|
+
'echo.',
|
|
1356
|
+
'echo [第二步] 开始还原(会先把当前 profile 另存一份再覆盖):',
|
|
1357
|
+
real,
|
|
1358
|
+
'echo.',
|
|
1359
|
+
'echo 执行结束。确认无误后再启动 DSH。',
|
|
1360
|
+
'pause',
|
|
1361
|
+
].join('\r\n')
|
|
1362
|
+
// 指定了某一份快照(面板点行还原)时脚本名带上快照名,多份还原脚本可以同时存在、互不覆盖
|
|
1363
|
+
const fileName = pickedSnap ? `同步-还原-${pickedSnap.name}.cmd` : '同步-还原.cmd'
|
|
1364
|
+
const path = join(repo, fileName)
|
|
1365
|
+
writeFileSync(path, text, 'utf8')
|
|
1366
|
+
const label = kind === 'plugin'
|
|
1367
|
+
? t('还原(插件 → 备份版本)', 'Restore (plugin → backup)')
|
|
1368
|
+
: (kind === 'session' ? t('还原(会话 → 备份)', 'Restore (sessions → backup)') : t('还原(本机 → 快照)', 'Restore (machine → snapshot)'))
|
|
1369
|
+
return { action, label, path, command: real,
|
|
1370
|
+
backup: { dir: picked || backup.latest, root: backup.root, at: pickedSnap ? pickedSnap.at : backup.latestAt, count: backup.count, files: pickedSnap ? pickedSnap.files : backup.latestFiles } }
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
const target = action === 'push' ? 'push' : 'pull'
|
|
1374
|
+
const label = target === 'push'
|
|
1375
|
+
? t('推送(本机 → 远端)', 'Push (machine → remote)')
|
|
1376
|
+
: t('拉取(远端 → 本机)', 'Pull (remote → machine)')
|
|
1377
|
+
// 提交说明只对 push 有意义:用户在面板里填一句,时间由 sync.ps1 在实际执行那一刻追加。
|
|
1378
|
+
// 这里只做清洗(去引号/换行、% 转义、限长):引号会破坏参数结构,% 会被 cmd 当变量展开。
|
|
1379
|
+
const note = target === 'push' ? String(state.message || '').replace(/["\r\n]/g, ' ').replace(/%/g, '%%').trim().slice(0, 120) : ''
|
|
1380
|
+
const command = [PS_EXE, '-File', `"${syncPs1}"`, target, ...common.map((c) => c),
|
|
1381
|
+
...(note ? ['-Message', `"${note}"`] : [])].join(' ')
|
|
1382
|
+
const ahead = Number(state.ahead) || 0
|
|
1383
|
+
const dirty = Number(state.dirty) || 0
|
|
1384
|
+
const warnings = []
|
|
1385
|
+
if (target === 'pull') {
|
|
1386
|
+
if (ahead > 0) {
|
|
1387
|
+
warnings.push(t(
|
|
1388
|
+
`本机领先远端 ${ahead} 个提交(还没推送),拉取后这些改动在仓库里仍然缺失`,
|
|
1389
|
+
`This machine is ${ahead} commit(s) ahead (not pushed yet); after pulling, those changes are still missing from the repo.`,
|
|
1390
|
+
))
|
|
1391
|
+
}
|
|
1392
|
+
if (dirty > 0) {
|
|
1393
|
+
warnings.push(t(
|
|
1394
|
+
`工作区有 ${dirty} 项未提交,拉取会用仓库版本覆盖对应的本机文件`,
|
|
1395
|
+
`${dirty} uncommitted change(s): pulling overwrites the matching local files with the repo version.`,
|
|
1396
|
+
))
|
|
1397
|
+
}
|
|
1398
|
+
warnings.push(t(
|
|
1399
|
+
'拉取 = 拉远端 + apply 到本机:会用仓库里的版本覆盖本机配置',
|
|
1400
|
+
'Pull = fetch the remote and apply it locally: the repo version overwrites the local config.',
|
|
1401
|
+
))
|
|
1402
|
+
}
|
|
1403
|
+
const guard = target === 'pull'
|
|
1404
|
+
? [
|
|
1405
|
+
...(ahead > 0 ? [`echo ${echoSafe(`[!] 本机领先远端 ${ahead} 个提交(还没推送),这些改动拉取后不会进仓库。`)}`] : []),
|
|
1406
|
+
...(dirty > 0 ? [`echo ${echoSafe(`[!] 工作区有 ${dirty} 项未提交,拉取会用仓库版本覆盖对应本机文件。`)}`] : []),
|
|
1407
|
+
`echo ${echoSafe('[!] 拉取会用仓库里的版本覆盖本机配置(覆盖前仍会先存一份 backups\\config-<时间戳> 快照)。')}`,
|
|
1408
|
+
'echo.',
|
|
1409
|
+
// chcp 之后 set /p 读不到被重定向的输入(会拿到空值静默退出),所以另给一个 --yes 免确认开关,
|
|
1410
|
+
// 顺便让"没人按 y"这件事有明确回执,而不是什么都不发生。
|
|
1411
|
+
'if /i "%~1"=="--yes" goto SYNC_RUN',
|
|
1412
|
+
'set /p GO=拉取会覆盖本机配置,确认继续?(y/N) ',
|
|
1413
|
+
'if /i "%GO%"=="y" goto SYNC_RUN',
|
|
1414
|
+
`echo ${echoSafe('没有收到确认(y),已退出:本机什么都没改。')}`,
|
|
1415
|
+
'exit /b 0',
|
|
1416
|
+
':SYNC_RUN',
|
|
1417
|
+
'echo.',
|
|
1418
|
+
]
|
|
1419
|
+
: []
|
|
1420
|
+
const text = [
|
|
1421
|
+
...cmdHead(`会先确认 DSH 是否已退出,再执行「${label}」。`),
|
|
1422
|
+
...envLines,
|
|
1423
|
+
'echo.',
|
|
1424
|
+
...guard,
|
|
1425
|
+
...(note ? [`echo ${echoSafe(`提交说明:${note}(时间自动附在后面)`)}`] : []),
|
|
1426
|
+
command,
|
|
1427
|
+
'echo.',
|
|
1428
|
+
`echo 执行结束。若为拉取,确认无误后启动 DSH。`,
|
|
1429
|
+
'pause',
|
|
1430
|
+
].join('\r\n')
|
|
1431
|
+
const path = join(repo, `同步-${target === 'push' ? '推送' : '拉取'}.cmd`)
|
|
1432
|
+
writeFileSync(path, text, 'utf8')
|
|
1433
|
+
return { action: target, label, path, command, warnings, message: note }
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
/* ============================ 自动同步 / 自动推送 ============================
|
|
1437
|
+
* 插件跑在 DSH 主进程里:DSH 一退出插件就没了,所以"等 DSH 完全关闭再同步"不能由插件自己盯。
|
|
1438
|
+
* 做法是:需要动手时,插件用 detached 方式拉起 runtime\post-exit.ps1(它只等本进程 pid 消失),
|
|
1439
|
+
* 由那个外部脚本在退出后执行 pull / push,必要时再重启客户端。
|
|
1440
|
+
* 两个开关默认关;关着一行代码都不会跑。
|
|
1441
|
+
*/
|
|
1442
|
+
|
|
1443
|
+
const ROUTE_AUTO = '/config-sync/auto'
|
|
1444
|
+
|
|
1445
|
+
const autoState = {
|
|
1446
|
+
checking: false,
|
|
1447
|
+
lastCheckAt: 0,
|
|
1448
|
+
lastCheckError: '',
|
|
1449
|
+
drift: null, // { ahead, behind, at }
|
|
1450
|
+
pending: null, // { mode, at, reason?, restarted? } 已排队、等退出后执行
|
|
1451
|
+
watcherStartedAt: 0,
|
|
1452
|
+
timer: null,
|
|
1453
|
+
interval: null, // 每 2 分钟的复查(会话/资料是运行中产生的,只判一次会全漏)
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
function autoScript(dshHome, repo) {
|
|
1457
|
+
const fromPlugin = join(pluginRoot(), 'runtime', 'post-exit.ps1')
|
|
1458
|
+
if (isFile(fromPlugin)) return fromPlugin
|
|
1459
|
+
const fromRepo = join(repo || '', 'post-exit.ps1')
|
|
1460
|
+
return isFile(fromRepo) ? fromRepo : ''
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
/**
|
|
1464
|
+
* 上次「退出后自动同步」的结果(post-exit.ps1 落的盘)。
|
|
1465
|
+
* 只读,读不到/坏掉都返回 null,绝不影响客户端启动。
|
|
1466
|
+
* 字段:{ mode, ok, at(ms), code, message, restored, log, notices }
|
|
1467
|
+
* notices:本次没同步成的文件清单(post-exit 从 sync-notices.json 带过来)
|
|
1468
|
+
*/
|
|
1469
|
+
function readAutoResult(dshHome) {
|
|
1470
|
+
try {
|
|
1471
|
+
const file = join(dshHome, 'auto-sync-result.json')
|
|
1472
|
+
if (!isFile(file)) return null
|
|
1473
|
+
const j = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
1474
|
+
if (!j || typeof j !== 'object') return null
|
|
1475
|
+
return {
|
|
1476
|
+
mode: j.mode === 'push' ? 'push' : 'pull',
|
|
1477
|
+
ok: j.ok === true,
|
|
1478
|
+
at: Number(j.at) || 0,
|
|
1479
|
+
code: Number(j.code) || 0,
|
|
1480
|
+
message: String(j.message || ''),
|
|
1481
|
+
restored: j.restored === true,
|
|
1482
|
+
log: String(j.log || ''),
|
|
1483
|
+
notices: readNoticeList(dshHome, j.notices),
|
|
1484
|
+
}
|
|
1485
|
+
} catch { return null }
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/**
|
|
1489
|
+
* 未同步文件清单:优先用结果文件里带的那份;结果文件里没有(比如面板刷新时这次还没跑完)
|
|
1490
|
+
* 就回落到 ~/.dsh/sync-notices.json。两种情况都做裁剪,避免一个几万文件的仓库把 /status 撑爆。
|
|
1491
|
+
*/
|
|
1492
|
+
function readNoticeList(dshHome, fromResult) {
|
|
1493
|
+
const KINDS = ['history', 'too-large', 'failed', 'skipped']
|
|
1494
|
+
let raw = fromResult
|
|
1495
|
+
if (!raw || !Array.isArray(raw.items)) {
|
|
1496
|
+
try {
|
|
1497
|
+
const file = join(dshHome, 'sync-notices.json')
|
|
1498
|
+
if (isFile(file)) raw = JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
|
|
1499
|
+
} catch { raw = null }
|
|
1500
|
+
}
|
|
1501
|
+
if (!raw || !Array.isArray(raw.items) || !raw.items.length) return null
|
|
1502
|
+
const items = raw.items
|
|
1503
|
+
.filter((it) => it && it.path)
|
|
1504
|
+
.slice(0, 30)
|
|
1505
|
+
.map((it) => ({
|
|
1506
|
+
kind: KINDS.includes(it.kind) ? it.kind : 'skipped',
|
|
1507
|
+
path: String(it.path),
|
|
1508
|
+
bytes: Number(it.bytes) || 0,
|
|
1509
|
+
reason: String(it.reason || ''),
|
|
1510
|
+
}))
|
|
1511
|
+
const byKind = {}
|
|
1512
|
+
for (const k of KINDS) byKind[k] = 0
|
|
1513
|
+
for (const it of raw.items) {
|
|
1514
|
+
const k = KINDS.includes(it && it.kind) ? it.kind : 'skipped'
|
|
1515
|
+
byKind[k] += 1
|
|
1516
|
+
}
|
|
1517
|
+
return {
|
|
1518
|
+
at: Number(raw.at) || 0,
|
|
1519
|
+
mode: String(raw.mode || ''),
|
|
1520
|
+
total: Number(raw.total) || raw.items.length,
|
|
1521
|
+
byKind,
|
|
1522
|
+
items,
|
|
1523
|
+
truncated: (Number(raw.total) || raw.items.length) > items.length,
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
/** 只读探询:fetch 一次再比 HEAD 与 origin/<branch>。任何失败都返回 null,绝不影响客户端启动。 */
|
|
1528
|
+
async function checkDrift(repo) {
|
|
1529
|
+
if (!repo || !isDir(join(repo, '.git'))) return null
|
|
1530
|
+
const branch = await currentBranch(repo)
|
|
1531
|
+
const fetched = await git(repo, ['fetch', 'origin', '--quiet'])
|
|
1532
|
+
if (fetched === null) return null
|
|
1533
|
+
const counts = await git(repo, ['rev-list', '--left-right', '--count', `HEAD...origin/${branch}`])
|
|
1534
|
+
if (!counts) return null
|
|
1535
|
+
const [ahead, behind] = counts.trim().split(/\s+/).map((n) => Number(n) || 0)
|
|
1536
|
+
return { ahead, behind, branch, at: Date.now() }
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
/** 系统确认框(立在 DSH 窗口前面,不开面板也看得见)。Yes → true。 */
|
|
1540
|
+
function askConfirm(title, text) {
|
|
1541
|
+
return new Promise((resolve) => {
|
|
1542
|
+
// 参数走 spawn 的数组形式,不经过 shell 解析,所以文本里的引号/换行不会被二次解释。
|
|
1543
|
+
const safe = (s) => String(s).replace(/'/g, "''")
|
|
1544
|
+
const script = [
|
|
1545
|
+
'Add-Type -AssemblyName System.Windows.Forms | Out-Null',
|
|
1546
|
+
`$r = [System.Windows.Forms.MessageBox]::Show('${safe(text)}', '${safe(title)}', ` +
|
|
1547
|
+
'[System.Windows.Forms.MessageBoxButtons]::YesNo, [System.Windows.Forms.MessageBoxIcon]::Question)',
|
|
1548
|
+
'if ($r -eq [System.Windows.Forms.DialogResult]::Yes) { exit 6 } else { exit 7 }',
|
|
1549
|
+
].join('\n')
|
|
1550
|
+
const ps = spawn('powershell.exe',
|
|
1551
|
+
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', script],
|
|
1552
|
+
{ windowsHide: true, stdio: 'ignore' })
|
|
1553
|
+
ps.on('error', () => resolve(false))
|
|
1554
|
+
ps.on('close', (code) => resolve(code === 6))
|
|
1555
|
+
// 12 分钟没人点就当取消,别把后台挂着
|
|
1556
|
+
const timer = setTimeout(() => { try { ps.kill() } catch { } resolve(false) }, 12 * 60 * 1000)
|
|
1557
|
+
try { timer.unref?.() } catch { }
|
|
1558
|
+
})
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
/**
|
|
1562
|
+
* 找 powershell 的绝对路径。
|
|
1563
|
+
* 不能只写 'powershell.exe' 靠 PATH:Electron 主进程继承的 PATH 可能被裁剪(本机实测就是
|
|
1564
|
+
* spawn 返回对象、pid 看着有,但进程根本没起来、post-exit 的日志一行都没落 —— 假成功)。
|
|
1565
|
+
*/
|
|
1566
|
+
function powershellExe() {
|
|
1567
|
+
const root = process.env.SystemRoot || 'C:\\Windows'
|
|
1568
|
+
for (const c of [
|
|
1569
|
+
join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
1570
|
+
join(root, 'Sysnative', 'WindowsPowerShell', 'v1.0', 'powershell.exe'),
|
|
1571
|
+
]) {
|
|
1572
|
+
if (isFile(c)) return c
|
|
1573
|
+
}
|
|
1574
|
+
return 'powershell.exe'
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/** 记录"起守护进程"这件事本身:成功/失败都留痕,否则失败时只剩一个不存在的 pid。 */
|
|
1578
|
+
function logLaunch(dshHome, text) {
|
|
1579
|
+
try {
|
|
1580
|
+
const dir = join(dshHome, 'logs')
|
|
1581
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
1582
|
+
writeFileSync(join(dir, 'auto-sync-launch.log'), `[${new Date().toISOString()}] ${text}\n`, { flag: 'a' })
|
|
1583
|
+
} catch { }
|
|
1584
|
+
}
|
|
1585
|
+
|
|
1586
|
+
/** 拼 PowerShell 单引号字面量(路径里有单引号就双写)。 */
|
|
1587
|
+
function psQuote(value) {
|
|
1588
|
+
return "'" + String(value).replace(/'/g, "''") + "'"
|
|
1589
|
+
}
|
|
1590
|
+
|
|
1591
|
+
/**
|
|
1592
|
+
* 拉起外部守护:等本进程退出后执行一次同步。
|
|
1593
|
+
*
|
|
1594
|
+
* 两个坑都在这踩过:
|
|
1595
|
+
* 1. spawn() 找不到可执行文件是**异步**报错,不会抛异常 —— 只看 try/catch 会"假装成功";
|
|
1596
|
+
* 所以下面要等 launcher 的 exit 码,失败就如实返回,并写 auto-sync-launch.log。
|
|
1597
|
+
* 2. 直接用 `detached: true` 起 powershell,在 Windows 上它会**当场退出**:
|
|
1598
|
+
* 实测(同一个 exe、同一个脚本)detached=true 时进程 3 秒后已消失、post-exit 日志一行没有;
|
|
1599
|
+
* detached=false 立刻就在写日志。所以这里不 detached,而是让一个短命 powershell 用
|
|
1600
|
+
* Start-Process 把真正的 post-exit 起成独立进程 —— 父进程(DSH)退出后它照样活着。
|
|
1601
|
+
*/
|
|
1602
|
+
async function spawnWatcher({ mode, repo, appRoot, dshHome, restart, extraArgs = [] }) {
|
|
1603
|
+
const script = autoScript(dshHome, repo)
|
|
1604
|
+
if (!script) return { ok: false, error: t('插件与仓库里都没有 post-exit.ps1,无法排队', 'post-exit.ps1 is in neither the plugin nor the repo — cannot queue') }
|
|
1605
|
+
|
|
1606
|
+
// 同一时刻只允许一次同步。实测过的坑:启动首检排了 push、用户在确认框点确认又排了 pull,
|
|
1607
|
+
// 两个守护都在等同一个 pid —— DSH 一退出它们**同时开工**,一次推送一次拉取并行跑、各重启一次,
|
|
1608
|
+
// 配置可能互相覆盖。锁文件记 pid,进程还活着就拒掉后来者。
|
|
1609
|
+
const lockFile = join(dshHome, 'auto-sync.lock')
|
|
1610
|
+
try {
|
|
1611
|
+
if (isFile(lockFile)) {
|
|
1612
|
+
const lockText = readFileSync(lockFile, 'utf8')
|
|
1613
|
+
const lockPid = Number((lockText.match(/"pid"\s*:\s*(\d+)/) || [])[1])
|
|
1614
|
+
if (lockPid > 0) {
|
|
1615
|
+
let alive = false
|
|
1616
|
+
try { process.kill(lockPid, 0); alive = true } catch { alive = false }
|
|
1617
|
+
if (alive) {
|
|
1618
|
+
const lockMode = (lockText.match(/"mode"\s*:\s*"([a-z]+)"/) || [])[1]
|
|
1619
|
+
// 同一种同步已经在等,直接复用,别再加一个并行的
|
|
1620
|
+
if (lockMode === mode) return { ok: true, pid: lockPid, reused: true }
|
|
1621
|
+
// 不同的同步正在等(例如首检排了推送、用户在确认框点了拉取):用户的手动动作优先,
|
|
1622
|
+
// 干掉那个还没开工的等待进程,改排这一次。它此时只可能在等 DSH 退出,没有副作用。
|
|
1623
|
+
try { process.kill(lockPid) } catch { }
|
|
1624
|
+
logLaunch(dshHome, `取消上一个等待中的 ${lockMode || '同步'}(pid ${lockPid}),改排 ${mode}`)
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
try { unlinkSync(lockFile) } catch { }
|
|
1628
|
+
}
|
|
1629
|
+
} catch { }
|
|
1630
|
+
|
|
1631
|
+
const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script,
|
|
1632
|
+
// 这一段是「等待态」:隐藏进程只盯着 DSH 退出,退出后才由它拉起一个可见窗口干活,
|
|
1633
|
+
// 否则排队期间(可能几小时)会一直挂着一个挡视线的空窗口。
|
|
1634
|
+
'-Mode', mode, '-WatchPid', String(process.pid), '-Phase', 'wait', '-DshHome', dshHome]
|
|
1635
|
+
if (repo) args.push('-RepoRoot', repo)
|
|
1636
|
+
if (appRoot) args.push('-AppRoot', appRoot)
|
|
1637
|
+
if (restart) args.push('-Restart')
|
|
1638
|
+
// 更新模式要带上下载地址与校验值,交给 post-exit 的 run 段执行
|
|
1639
|
+
if (Array.isArray(extraArgs) && extraArgs.length) args.push(...extraArgs)
|
|
1640
|
+
const exe = powershellExe()
|
|
1641
|
+
const inner = [
|
|
1642
|
+
// 等待态进程保持**隐藏**;可见窗口由 post-exit.ps1 在 DSH 真正退出后自己弹(-Phase run)。
|
|
1643
|
+
`$p = Start-Process -FilePath ${psQuote(exe)} -ArgumentList @(${args.map(psQuote).join(', ')}) -WindowStyle Hidden -PassThru`,
|
|
1644
|
+
'Write-Output $p.Id',
|
|
1645
|
+
].join('; ')
|
|
1646
|
+
const encoded = Buffer.from(inner, 'utf16le').toString('base64')
|
|
1647
|
+
let child
|
|
1648
|
+
try {
|
|
1649
|
+
child = spawn(exe, ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded],
|
|
1650
|
+
{ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
|
|
1651
|
+
} catch (error) {
|
|
1652
|
+
const msg = String((error && error.message) || error)
|
|
1653
|
+
logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${msg}`)
|
|
1654
|
+
return { ok: false, error: t(`拉不起 powershell(${exe}):${msg}`, `Cannot launch PowerShell (${exe}): ${msg}`) }
|
|
1655
|
+
}
|
|
1656
|
+
let stdout = ''
|
|
1657
|
+
let stderr = ''
|
|
1658
|
+
child.stdout.on('data', (c) => { stdout += c })
|
|
1659
|
+
child.stderr.on('data', (c) => { stderr += c })
|
|
1660
|
+
const code = await new Promise((resolve) => {
|
|
1661
|
+
const timer = setTimeout(() => resolve('timeout'), 8000)
|
|
1662
|
+
child.once('exit', (c) => { clearTimeout(timer); resolve(c) })
|
|
1663
|
+
child.once('error', (e) => { clearTimeout(timer); resolve('error:' + ((e && e.message) || e)) })
|
|
1664
|
+
})
|
|
1665
|
+
if (code !== 0) {
|
|
1666
|
+
const detail = String(stderr || stdout || code).trim().slice(0, 300)
|
|
1667
|
+
logLaunch(dshHome, `启动失败 ${mode} exe=${exe}:${detail}`)
|
|
1668
|
+
return { ok: false, error: t(`拉不起 post-exit(launcher 退出码 ${code}):${detail}`, `Cannot launch post-exit (launcher exit code ${code}): ${detail}`) }
|
|
1669
|
+
}
|
|
1670
|
+
const pid = Number(String(stdout).trim().split(/\s+/).pop()) || 0
|
|
1671
|
+
autoState.watcherStartedAt = Date.now()
|
|
1672
|
+
try {
|
|
1673
|
+
writeFileSync(lockFile, JSON.stringify({ pid, mode, at: Date.now() }), 'utf8')
|
|
1674
|
+
} catch { }
|
|
1675
|
+
logLaunch(dshHome, `已启动 ${mode} pid=${pid} exe=${exe} script=${script}`)
|
|
1676
|
+
return { ok: true, pid }
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
/**
|
|
1680
|
+
* 宿主是 Electron 主进程(插件就装在主进程里),所以能拿到 app —— 但 CLI 形态运行、
|
|
1681
|
+
* 或加载器换了模块解析时取不到,一律返回 null,调用方退回 taskkill。
|
|
1682
|
+
*/
|
|
1683
|
+
function electronApp() {
|
|
1684
|
+
try {
|
|
1685
|
+
const mod = pluginRequire('electron')
|
|
1686
|
+
return mod && mod.app && mod.BrowserWindow ? mod : null
|
|
1687
|
+
} catch { return null }
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
/**
|
|
1691
|
+
* 让客户端**真的退出**。
|
|
1692
|
+
*
|
|
1693
|
+
* 旧实现是 `taskkill /PID <主进程>`(不带 /F):对 Electron 主进程无效 ——
|
|
1694
|
+
* 主进程没有自己的顶层窗口,实测直接报 "This process can only be terminated forcefully",
|
|
1695
|
+
* 于是「确认后自动退出 DSH」根本不生效,守护进程只能干等到 30 分钟超时。
|
|
1696
|
+
*
|
|
1697
|
+
* 现在优先 app.quit()(走 before-quit,配置照常落盘);拿不到 electron 才退回 taskkill。
|
|
1698
|
+
*/
|
|
1699
|
+
function closeDsh() {
|
|
1700
|
+
const exe = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe')
|
|
1701
|
+
const imageName = 'DeepSeek Harness.exe'
|
|
1702
|
+
const run = (args) => {
|
|
1703
|
+
try { spawn(isFile(exe) ? exe : 'taskkill', args, { stdio: 'ignore', windowsHide: true, detached: false }) } catch { }
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
// 先走一次「礼貌关闭」(不带 /F 只对带窗口的进程有效,会让 Electron 走正常关闭流程)。
|
|
1707
|
+
run(['/IM', imageName])
|
|
1708
|
+
// 3.5 秒后强制收尾:实测点关闭后 7 个进程全部残留(单杀 process.pid 只打掉一个子进程,
|
|
1709
|
+
// 因为插件跑在子进程里、进程号不是客户端主进程),必须按映像名整族收掉,
|
|
1710
|
+
// 否则「退出后自动推送」的等待进程会一直等到 30 分钟超时。
|
|
1711
|
+
const timer = setTimeout(() => { run(['/IM', imageName, '/F']) }, 3500)
|
|
1712
|
+
try { timer.unref?.() } catch { }
|
|
1713
|
+
|
|
1714
|
+
// Electron 主进程形态下 app.quit 更温和(有 before-quit 落盘);拿到了就先用它
|
|
1715
|
+
const el = electronApp()
|
|
1716
|
+
if (el) { try { setTimeout(() => { try { el.app.quit() } catch { } }, 150) } catch { } }
|
|
1717
|
+
return true
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
function isProcessAlive(pid) {
|
|
1721
|
+
if (!pid) return false
|
|
1722
|
+
try { process.kill(pid, 0); return true } catch { return false }
|
|
1723
|
+
}
|
|
1724
|
+
const STATE_NAME = 'config-sync-state.json'
|
|
1725
|
+
|
|
1726
|
+
/**
|
|
1727
|
+
* 上次同步成功的时间(由 sync.ps1 在 push/pull 成功后写进 <DshHome>\config-sync-state.json)。
|
|
1728
|
+
* 面板拿它当"本机数据有没有比仓库新"的分界线 —— 以前只比 git status,新会话还没 capture 时
|
|
1729
|
+
* 面板会显示"仓库与本机一致",看着像没同步,其实只是没跑 capture。
|
|
1730
|
+
*/
|
|
1731
|
+
function readSyncState(dshHome) {
|
|
1732
|
+
const s = readJson(join(dshHome, STATE_NAME)) || {}
|
|
1733
|
+
return {
|
|
1734
|
+
lastSyncAt: typeof s.lastSyncAt === 'string' ? s.lastSyncAt : '',
|
|
1735
|
+
mode: typeof s.mode === 'string' ? s.mode : '',
|
|
1736
|
+
head: typeof s.head === 'string' ? s.head : '',
|
|
1737
|
+
}
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
/** 本机登记的工作区目录(capture 会把它们镜像进仓库,所以它们变了也算待推送)。 */
|
|
1741
|
+
function workspaceRoots(dshHome) {
|
|
1742
|
+
const reg = readJson(join(dshHome, 'storages', 'workspace.json')) || {}
|
|
1743
|
+
const list = (reg.tables && reg.tables.workspaces) || reg.workspaces || []
|
|
1744
|
+
return Array.isArray(list)
|
|
1745
|
+
? list.map((w) => (w && typeof w.path === 'string' ? w.path : '')).filter(Boolean)
|
|
1746
|
+
: []
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
/**
|
|
1750
|
+
* 本机 DSH 数据里「上次同步之后又写过」的文件有多少个。
|
|
1751
|
+
* 只看 mtime,不读内容、**不跑 capture**(跑 capture 要复制整个工作区,几 GB)。
|
|
1752
|
+
* 代价控制:跳过 node_modules / models / .git 等,最多 20000 个文件、最多 1.5 秒。
|
|
1753
|
+
*
|
|
1754
|
+
* 为什么要补一层内容比对:`profile\cordis.patch.yml` 这类文件 **DSH 每次启动都会重写**
|
|
1755
|
+
* (把仓库里存的 `{{APP_ROOT}}` 占位符展开成真实安装路径),mtime 永远比上次同步新,
|
|
1756
|
+
* 只看 mtime 就会出现「明明什么都没改,面板却一直建议推送」。所以对这几个有仓库对应物的
|
|
1757
|
+
* 单文件,mtime 更新后再把内容归一(占位符还原、换行统一)比一次,相同就不计入。
|
|
1758
|
+
*/
|
|
1759
|
+
function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
|
|
1760
|
+
const since = lastSyncAt ? Date.parse(lastSyncAt) : NaN
|
|
1761
|
+
if (!Number.isFinite(since)) return { known: false, pending: 0, newestAt: '', sample: [] }
|
|
1762
|
+
const skip = new Set(['node_modules', '.git', 'models', '_tmp', 'staging', 'logs', 'attachments'])
|
|
1763
|
+
const profile = join(dshHome, 'profiles', profileName || 'desktop')
|
|
1764
|
+
const stack = [
|
|
1765
|
+
join(dshHome, 'sessions'),
|
|
1766
|
+
join(dshHome, 'skills'),
|
|
1767
|
+
join(dshHome, '.agent-presets'),
|
|
1768
|
+
join(dshHome, 'mnemon'),
|
|
1769
|
+
join(dshHome, 'AGENTS.md'),
|
|
1770
|
+
join(dshHome, 'prompt-inject.md'),
|
|
1771
|
+
join(profile, 'package.json'),
|
|
1772
|
+
join(profile, 'pnpm-lock.yaml'),
|
|
1773
|
+
join(profile, 'cordis.patch.yml'),
|
|
1774
|
+
join(profile, 'host-contract.json'),
|
|
1775
|
+
...workspaceRoots(dshHome),
|
|
1776
|
+
]
|
|
1777
|
+
// 有仓库对应物的单文件:路径 → 仓库里的那份。只有这些才值得读内容比对。
|
|
1778
|
+
const repoRoot = String(ctx.repo || '')
|
|
1779
|
+
const mirrored = new Map()
|
|
1780
|
+
if (repoRoot) {
|
|
1781
|
+
mirrored.set(join(dshHome, 'AGENTS.md'), join(repoRoot, 'prompt', 'AGENTS.md'))
|
|
1782
|
+
mirrored.set(join(dshHome, 'prompt-inject.md'), join(repoRoot, 'prompt', 'prompt-inject.md'))
|
|
1783
|
+
for (const f of ['package.json', 'pnpm-lock.yaml', 'cordis.patch.yml', 'host-contract.json']) {
|
|
1784
|
+
mirrored.set(join(profile, f), join(repoRoot, 'profile', f))
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
const deadline = Date.now() + 1500
|
|
1788
|
+
let scanned = 0
|
|
1789
|
+
let pending = 0
|
|
1790
|
+
let newest = 0
|
|
1791
|
+
const sample = []
|
|
1792
|
+
while (stack.length && scanned < 20000 && Date.now() < deadline) {
|
|
1793
|
+
const cur = stack.pop()
|
|
1794
|
+
let st
|
|
1795
|
+
try { st = statSync(cur) } catch { continue }
|
|
1796
|
+
if (st.isDirectory()) {
|
|
1797
|
+
if (skip.has(basename(cur))) continue
|
|
1798
|
+
let entries = []
|
|
1799
|
+
try { entries = readdirSync(cur) } catch { continue }
|
|
1800
|
+
for (const e of entries) stack.push(join(cur, e))
|
|
1801
|
+
continue
|
|
1802
|
+
}
|
|
1803
|
+
scanned++
|
|
1804
|
+
if (st.mtimeMs > since) {
|
|
1805
|
+
// 镜像文件的 mtime 更新可能只是宿主重写占位符:内容归一后一致就不算待推送
|
|
1806
|
+
const twin = mirrored.get(cur)
|
|
1807
|
+
if (twin && isFile(twin)) {
|
|
1808
|
+
try {
|
|
1809
|
+
if (mirrorText(cur, ctx.appRoot) === mirrorText(twin, ctx.appRoot)) continue
|
|
1810
|
+
} catch { }
|
|
1811
|
+
}
|
|
1812
|
+
pending++
|
|
1813
|
+
if (st.mtimeMs > newest) newest = st.mtimeMs
|
|
1814
|
+
if (sample.length < 3) sample.push(`${basename(dirname(cur))}/${basename(cur)}`)
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
return {
|
|
1818
|
+
known: true,
|
|
1819
|
+
pending,
|
|
1820
|
+
newestAt: newest ? new Date(newest).toISOString() : '',
|
|
1821
|
+
sample,
|
|
1822
|
+
truncated: scanned >= 20000 || Date.now() >= deadline,
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
/** 读成"可比较的文本":换行统一、去尾部空白、把真实安装路径还原成 {{APP_ROOT}} 占位符。 */
|
|
1827
|
+
function mirrorText(file, appRoot) {
|
|
1828
|
+
let text = readFileSync(file, 'utf8').replace(/\r\n/g, '\n').replace(/\s+$/, '')
|
|
1829
|
+
const root = String(appRoot || '').replace(/[\\/]+$/, '')
|
|
1830
|
+
if (root) {
|
|
1831
|
+
for (const variant of new Set([root, root.replace(/\\/g, '/'), root.replace(/\//g, '\\')])) {
|
|
1832
|
+
if (variant) text = text.split(variant).join('{{APP_ROOT}}')
|
|
1833
|
+
}
|
|
1834
|
+
}
|
|
1835
|
+
return text
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
async function repoState(repo) {
|
|
1839
|
+
if (!repo || !isDir(join(repo, '.git'))) return { ahead: 0, dirty: 0 }
|
|
1840
|
+
const status = await git(repo, ['status', '--porcelain'])
|
|
1841
|
+
const dirty = status ? status.split('\n').filter((l) => l.trim()).length : 0
|
|
1842
|
+
return { ahead: await aheadCount(repo), dirty }
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/** 当前分支名(游离 HEAD 时给出 'main' 兜底,跟以前的行为一致)。 */
|
|
1846
|
+
async function currentBranch(repo) {
|
|
1847
|
+
const raw = await git(repo, ['rev-parse', '--abbrev-ref', 'HEAD'])
|
|
1848
|
+
const name = String(raw || '').trim()
|
|
1849
|
+
return name && name !== 'HEAD' ? name : 'main'
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
/**
|
|
1853
|
+
* 本机领先远端多少提交。
|
|
1854
|
+
* 不能把分支名写死成 origin/main(以前就是这么写的,分支叫 master 或改了名时「领先」永远算 0)。
|
|
1855
|
+
* 优先用上游追踪(HEAD --not @{upstream}),没有上游时用当前分支对应的 origin/<分支>。
|
|
1856
|
+
*/
|
|
1857
|
+
async function aheadCount(repo) {
|
|
1858
|
+
const parse = (s) => Number(String(s || '').trim()) || 0
|
|
1859
|
+
const viaUpstream = await git(repo, ['rev-list', '--count', 'HEAD', '--not', '@{upstream}'])
|
|
1860
|
+
if (viaUpstream) return parse(viaUpstream)
|
|
1861
|
+
const branch = await currentBranch(repo)
|
|
1862
|
+
return parse(await git(repo, ['rev-list', '--count', 'HEAD', '--not', `origin/${branch}`]))
|
|
1863
|
+
}
|
|
1864
|
+
|
|
1865
|
+
/** action 白名单:单个动作,或 all=一次性生成三个脚本。 */
|
|
1866
|
+
const ACTIONS = ['push', 'pull', 'restore', 'restore-backup', 'all']
|
|
1867
|
+
|
|
1868
|
+
|
|
1869
|
+
/** 远端地址只接受三种写法,别的一律拒(避免把乱七八糟的东西塞进 git remote)。 */
|
|
1870
|
+
const REMOTE_RE = /^(git@[\w.\-]+:[^\s]+|ssh:\/\/[^\s]+|https:\/\/[^\s]+)$/i
|
|
1871
|
+
|
|
1872
|
+
/**
|
|
1873
|
+
* 保存仓库路径 / 远端地址 / 私钥路径。三样都可以单独改,也可以一起改。
|
|
1874
|
+
* 顺序:先校验 → 写设置文件 → 改 git remote(失败就回滚设置文件),不会留下半截状态。
|
|
1875
|
+
*/
|
|
1876
|
+
async function handleSettings(req, res, config) {
|
|
1877
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
1878
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
1879
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
1880
|
+
const file = settingsPath(dshHome)
|
|
1881
|
+
const prevRaw = isFile(file) ? readFileSync(file, 'utf8') : null
|
|
1882
|
+
try {
|
|
1883
|
+
const raw = await readBody(req)
|
|
1884
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
1885
|
+
const has = (k) => Object.prototype.hasOwnProperty.call(body, k)
|
|
1886
|
+
const before = readSettings(dshHome)
|
|
1887
|
+
|
|
1888
|
+
let repoPath = before.repoPath
|
|
1889
|
+
if (has('repoPath')) {
|
|
1890
|
+
repoPath = String(body.repoPath || '').trim().replace(/[\\/]+$/, '')
|
|
1891
|
+
if (!repoPath) throw new Error(t('仓库路径不能为空', 'Repo path cannot be empty'))
|
|
1892
|
+
// 新机器上这个目录常常还不存在、或者是个空目录(等着首次拉取去初始化):都允许存。
|
|
1893
|
+
// 只有「已经有别的东西、又明显不是 dsh-config 仓库」才拒,免得住错地方把人家目录写乱。
|
|
1894
|
+
// 判据统一交给 repoPhase,跟面板、体检那边保持同一套口径;带 .git\HEAD 的目录
|
|
1895
|
+
// (可能正克隆到一半)也放行,否则刚 init 完的目录会被拒。
|
|
1896
|
+
if (repoPath && repoPhase(repoPath) === 'unusable' && !isFile(join(repoPath, '.git', 'HEAD'))) {
|
|
1897
|
+
throw new Error(t(
|
|
1898
|
+
`这个目录里已经有别的东西,又不像 dsh-config 仓库(缺 apply.ps1 或 profile\\package.json):${repoPath}`,
|
|
1899
|
+
`That directory already holds something else and does not look like a dsh-config repo (no apply.ps1 or profile\\package.json): ${repoPath}`,
|
|
1900
|
+
))
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
let remoteUrl = before.remoteUrl
|
|
1905
|
+
if (has('remoteUrl')) {
|
|
1906
|
+
remoteUrl = String(body.remoteUrl || '').trim()
|
|
1907
|
+
if (!remoteUrl) throw new Error(t('远端地址不能为空', 'Remote URL cannot be empty'))
|
|
1908
|
+
if (!REMOTE_RE.test(remoteUrl)) throw new Error(t('远端地址只支持 git@host:path、ssh:// 或 https:// 三种写法', 'Remote URL must be git@host:path, ssh:// or https://'))
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
let sshKey = before.sshKey
|
|
1912
|
+
if (has('sshKey')) {
|
|
1913
|
+
sshKey = String(body.sshKey || '').trim()
|
|
1914
|
+
if (sshKey && !isFile(sshKey)) throw new Error(t(`私钥文件不存在:${sshKey}`, `Private key file does not exist: ${sshKey}`))
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
// 更新令牌:私有仓库读清单/下包要用。字段没给就沿用原值,明确 clearUpdateToken 才清空。
|
|
1918
|
+
let updateToken = before.updateToken
|
|
1919
|
+
if (body.clearUpdateToken === true) updateToken = ''
|
|
1920
|
+
else if (has('updateToken')) updateToken = String(body.updateToken || '').trim()
|
|
1921
|
+
|
|
1922
|
+
// 更新清单地址:留空=用内置默认;填了必须 http(s),免得写成半截路径
|
|
1923
|
+
let updateManifestUrl = before.updateManifestUrl
|
|
1924
|
+
if (body.clearUpdateManifestUrl === true) updateManifestUrl = ''
|
|
1925
|
+
else if (has('updateManifestUrl')) {
|
|
1926
|
+
updateManifestUrl = String(body.updateManifestUrl || '').trim()
|
|
1927
|
+
if (updateManifestUrl && !/^https?:\/\//i.test(updateManifestUrl)) {
|
|
1928
|
+
throw new Error(t('清单地址只能是 http(s) 链接;想用内置默认地址就留空', 'The manifest URL must be an http(s) link; leave it empty to use the built-in default'))
|
|
1929
|
+
}
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// 备份根:留空 = 恢复默认 <DshHome>\backups;填了必须是绝对路径(相对路径会随 cwd 漂)
|
|
1933
|
+
let backupRoot = before.backupRoot
|
|
1934
|
+
if (body.clearBackupRoot === true) backupRoot = ''
|
|
1935
|
+
else if (has('backupRoot')) {
|
|
1936
|
+
backupRoot = String(body.backupRoot || '').trim().replace(/[\\/]+$/, '')
|
|
1937
|
+
if (backupRoot && !isAbsolute(backupRoot)) {
|
|
1938
|
+
throw new Error(t('备份目录要填绝对路径(例如 D:\\DSH备份)', 'The backup folder must be an absolute path (e.g. D:\\DSH-backups)'))
|
|
1939
|
+
}
|
|
1940
|
+
if (/["\r\n]/.test(backupRoot)) throw new Error(t('备份路径里不能含引号或换行', 'The backup path must not contain quotes or newlines'))
|
|
1941
|
+
}
|
|
1942
|
+
|
|
1943
|
+
// 默认工作区:留空 = 自动(找名字/路径是 default-workspace 的工作区);off = 不干预;
|
|
1944
|
+
// 其它值按工作区 ID 或绝对路径匹配,匹配不到时脚本会跳过并记日志,不会乱指。
|
|
1945
|
+
let defaultWorkspace = before.defaultWorkspace
|
|
1946
|
+
if (body.clearDefaultWorkspace === true) defaultWorkspace = ''
|
|
1947
|
+
else if (has('defaultWorkspace')) {
|
|
1948
|
+
defaultWorkspace = String(body.defaultWorkspace || '').trim()
|
|
1949
|
+
if (/["\r\n]/.test(defaultWorkspace)) throw new Error(t('默认工作区里不能含引号或换行', 'The default workspace must not contain quotes or newlines'))
|
|
1950
|
+
}
|
|
1951
|
+
|
|
1952
|
+
// 两个自动化开关:只能布尔;字段没给就沿用原值(面板保存单个字段时不会把开关冲掉)
|
|
1953
|
+
const autoPull = has('autoPull') ? body.autoPull === true : before.autoPull
|
|
1954
|
+
const autoPush = has('autoPush') ? body.autoPush === true : before.autoPush
|
|
1955
|
+
const autoRestart = has('autoRestart') ? body.autoRestart !== false : before.autoRestart
|
|
1956
|
+
|
|
1957
|
+
if (!has('repoPath') && !has('remoteUrl') && !has('sshKey') &&
|
|
1958
|
+
!has('autoPull') && !has('autoPush') && !has('autoRestart') &&
|
|
1959
|
+
!has('backupRoot') && !has('defaultWorkspace') &&
|
|
1960
|
+
!has('updateToken') && !has('updateManifestUrl') && body.clearUpdateToken !== true && body.clearUpdateManifestUrl !== true && body.clearBackupRoot !== true && body.clearDefaultWorkspace !== true) {
|
|
1961
|
+
throw new Error(t(
|
|
1962
|
+
'没有要保存的字段(repoPath / remoteUrl / sshKey / autoPull / autoPush / autoRestart / backupRoot / defaultWorkspace / updateToken / updateManifestUrl 至少给一个)',
|
|
1963
|
+
'Nothing to save (provide at least one of repoPath / remoteUrl / sshKey / autoPull / autoPush / autoRestart / backupRoot / defaultWorkspace / updateToken / updateManifestUrl)',
|
|
1964
|
+
))
|
|
1965
|
+
}
|
|
1966
|
+
|
|
1967
|
+
// 新仓库路径一落盘,后面的 git remote 要对它做,别用改之前解析出来的旧仓库。
|
|
1968
|
+
const repo = repoPath || (resolveRepo(config?.repoPath, dshHome).repo || '')
|
|
1969
|
+
writeSettings(dshHome, { repoPath, remoteUrl, sshKey, autoPull, autoPush, autoRestart, updateToken, updateManifestUrl, backupRoot, defaultWorkspace })
|
|
1970
|
+
|
|
1971
|
+
const changed = {
|
|
1972
|
+
repoPath: before.repoPath !== repoPath,
|
|
1973
|
+
remoteUrl: before.remoteUrl !== remoteUrl,
|
|
1974
|
+
sshKey: before.sshKey !== sshKey,
|
|
1975
|
+
autoPull: before.autoPull !== autoPull,
|
|
1976
|
+
autoPush: before.autoPush !== autoPush,
|
|
1977
|
+
backupRoot: before.backupRoot !== backupRoot,
|
|
1978
|
+
defaultWorkspace: before.defaultWorkspace !== defaultWorkspace,
|
|
1979
|
+
}
|
|
1980
|
+
let gitSet = null
|
|
1981
|
+
if (repo && isDir(join(repo, '.git')) && remoteUrl) {
|
|
1982
|
+
const current = await git(repo, ['remote', 'get-url', 'origin'])
|
|
1983
|
+
if (current !== remoteUrl) {
|
|
1984
|
+
// 没有 origin 的新仓库(拷目录/解 tgz 得来的、不是 clone 的)不能 set-url,要先 add。
|
|
1985
|
+
const args = current === null
|
|
1986
|
+
? ['-C', repo, 'remote', 'add', 'origin', remoteUrl]
|
|
1987
|
+
: ['-C', repo, 'remote', 'set-url', 'origin', remoteUrl]
|
|
1988
|
+
const result = await new Promise((resolve) => {
|
|
1989
|
+
execFile(resolveGitExe(), args,
|
|
1990
|
+
{ windowsHide: true, timeout: 20000 }, (err, _out, stderr) => resolve({ err, stderr }))
|
|
1991
|
+
})
|
|
1992
|
+
if (result.err) {
|
|
1993
|
+
// 回滚:设置文件恢复原样,别让面板显示一个 git 并未采用的地址
|
|
1994
|
+
if (prevRaw === null) { try { unlinkSync(file) } catch { } } else { writeFileSync(file, prevRaw, 'utf8') }
|
|
1995
|
+
throw new Error(t(
|
|
1996
|
+
`${current === null ? 'git remote add' : 'git remote set-url'} 失败:${String(result.stderr || result.err.message || result.err).trim()}`,
|
|
1997
|
+
`${current === null ? 'git remote add' : 'git remote set-url'} failed: ${String(result.stderr || result.err.message || result.err).trim()}`,
|
|
1998
|
+
))
|
|
1999
|
+
}
|
|
2000
|
+
gitSet = remoteUrl
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
const sshKey2 = sshKey || defaultSshKey()
|
|
2005
|
+
sendJson(res, 200, {
|
|
2006
|
+
ok: true,
|
|
2007
|
+
changed,
|
|
2008
|
+
gitRemoteSet: Boolean(gitSet),
|
|
2009
|
+
repo: {
|
|
2010
|
+
path: repo || '',
|
|
2011
|
+
exists: Boolean(repo) && isRepoDir(repo),
|
|
2012
|
+
source: repoPath ? 'settings' : (resolveRepo(config?.repoPath, dshHome).source || 'none'),
|
|
2013
|
+
hasGit: Boolean(repo) && isDir(join(repo, '.git')),
|
|
2014
|
+
hasSync: Boolean(repo) && isFile(join(repo, 'sync.ps1')),
|
|
2015
|
+
},
|
|
2016
|
+
remote: {
|
|
2017
|
+
url: remoteUrl,
|
|
2018
|
+
sshKey: sshKey2,
|
|
2019
|
+
sshKeyExists: Boolean(sshKey2) && isFile(sshKey2),
|
|
2020
|
+
sshKeyFrom: sshKey ? 'settings' : (sshKey2 ? 'default' : 'none'),
|
|
2021
|
+
updateTokenSet: Boolean(updateToken),
|
|
2022
|
+
updateManifestUrl: updateManifestUrl || '',
|
|
2023
|
+
backupRoot: backupRoot || backupRootOf(dshHome, { backupRoot: '' }),
|
|
2024
|
+
backupRootCustom: Boolean(backupRoot),
|
|
2025
|
+
defaultWorkspace: defaultWorkspace,
|
|
2026
|
+
defaultWorkspaceAuto: !defaultWorkspace,
|
|
2027
|
+
settingsPath: file,
|
|
2028
|
+
},
|
|
2029
|
+
})
|
|
2030
|
+
} catch (error) {
|
|
2031
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
|
|
2035
|
+
/**
|
|
2036
|
+
* 插件自身的更新检查。
|
|
2037
|
+
*
|
|
2038
|
+
* 老版本机器上怎么知道有新版本:插件每次打开面板(以及每 30 分钟)读一次云端仓库根目录的
|
|
2039
|
+
* version.json,只比版本号,几百字节,不拉整包。有新版 → 面板标题下多一条「有新版本 x.y.z」
|
|
2040
|
+
* 和「更新」按钮;点更新才真正下载 tgz(带 sha256 校验)。
|
|
2041
|
+
*/
|
|
2042
|
+
const updateState = {
|
|
2043
|
+
checkedAt: 0,
|
|
2044
|
+
checking: false,
|
|
2045
|
+
manifest: null, // { version, notes, releasedAt, tgz, sha256 }
|
|
2046
|
+
error: '',
|
|
2047
|
+
requestUrl: '', // 用户配置的清单地址(空 = 用内置候选列表)
|
|
2048
|
+
url: '', // 这次实际读到清单的源(tgz 的相对地址按它解析)
|
|
2049
|
+
sources: [], // 依次试过的源与各自结果,面板要能看见"为什么不通"
|
|
2050
|
+
// DSH 运行中把包装好之后记在这里:{ version, at, backup, log }
|
|
2051
|
+
// 只是本进程内存态:重启后 PLUGIN_VERSION 就是新版本,自然不需要它了
|
|
2052
|
+
liveInstall: null,
|
|
2053
|
+
// 只下载、不安装时记在这里:{ version, sha256, file, size, at, url }
|
|
2054
|
+
// 覆盖插件目录的动作留到 DSH 退出后(post-exit -Mode update),
|
|
2055
|
+
// 因为运行中覆盖会让宿主重建插件树、把用户正在看的面板卸载掉。
|
|
2056
|
+
prepared: null,
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
function versionParts(v) {
|
|
2060
|
+
return String(v || '').replace(/^v/i, '').split(/[.\-+]/).map((x) => Number(String(x).replace(/[^0-9]/g, '')) || 0)
|
|
2061
|
+
}
|
|
2062
|
+
|
|
2063
|
+
/** a>b 返回 1,相等 0,a<b 返回 -1。 */
|
|
2064
|
+
function compareVersion(a, b) {
|
|
2065
|
+
const pa = versionParts(a)
|
|
2066
|
+
const pb = versionParts(b)
|
|
2067
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
2068
|
+
const x = pa[i] || 0
|
|
2069
|
+
const y = pb[i] || 0
|
|
2070
|
+
if (x !== y) return x > y ? 1 : -1
|
|
2071
|
+
}
|
|
2072
|
+
return 0
|
|
2073
|
+
}
|
|
2074
|
+
|
|
2075
|
+
/**
|
|
2076
|
+
* 清单里 tgz 可以写相对路径(releases/xxx.tgz)。下载地址按"读到清单的那个源"优先,
|
|
2077
|
+
* 其余镜像依次兜底 —— 清单通了不代表包一定也能从同一个域名下下来。
|
|
2078
|
+
*/
|
|
2079
|
+
function resolveTgzCandidates(manifest, manifestUrl = '') {
|
|
2080
|
+
const tgz = String((manifest && manifest.tgz) || '')
|
|
2081
|
+
if (!tgz) return []
|
|
2082
|
+
// 清单里写了绝对地址就照它来,不替用户猜镜像
|
|
2083
|
+
if (/^https?:\/\//i.test(tgz)) return [tgz]
|
|
2084
|
+
const rel = tgz.replace(/^\.?\//, '')
|
|
2085
|
+
const bases = []
|
|
2086
|
+
const actual = String(manifestUrl || '').replace(/[^/]*$/, '')
|
|
2087
|
+
if (actual) bases.push(actual)
|
|
2088
|
+
for (const cand of UPDATE_MANIFEST_MIRRORS) {
|
|
2089
|
+
const base = cand.replace(/[^/]*$/, '')
|
|
2090
|
+
if (base && !bases.includes(base)) bases.push(base)
|
|
2091
|
+
}
|
|
2092
|
+
return bases.map((base) => base + rel)
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
/** version.json 里的 tgz 可以写相对路径(releases/xxx.tgz),拼在仓库 raw 根上。 */
|
|
2096
|
+
function resolveTgzUrl(manifest, manifestUrl = UPDATE_MANIFEST_URL) {
|
|
2097
|
+
const list = resolveTgzCandidates(manifest, manifestUrl)
|
|
2098
|
+
if (list.length) return list[0]
|
|
2099
|
+
// 没给 tgz 时保留原来的兜底行为(返回空串,调用方自己报错)
|
|
2100
|
+
return ''
|
|
2101
|
+
}
|
|
2102
|
+
|
|
2103
|
+
async function fetchManifest(url, timeoutMs = UPDATE_FETCH_TIMEOUT) {
|
|
2104
|
+
if (typeof fetch !== 'function') throw new Error(t('当前运行环境没有 fetch,无法检查更新', 'fetch is unavailable in this runtime — cannot check for updates'))
|
|
2105
|
+
const seconds = Math.round(timeoutMs / 1000)
|
|
2106
|
+
const ctrl = typeof AbortController === 'function' ? new AbortController() : null
|
|
2107
|
+
let timedOut = false
|
|
2108
|
+
const timer = ctrl ? setTimeout(() => { timedOut = true; try { ctrl.abort() } catch { } }, timeoutMs) : null
|
|
2109
|
+
try {
|
|
2110
|
+
const res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
|
|
2111
|
+
if (!res.ok) {
|
|
2112
|
+
throw new Error(`HTTP ${res.status}${res.status === 403 ? t('(私有仓库要填只读令牌)', ' (a read-only token is required for private repos)') : ''}`)
|
|
2113
|
+
}
|
|
2114
|
+
const json = await res.json()
|
|
2115
|
+
if (!json || !json.version) throw new Error(t('version.json 里没有 version 字段', 'version.json has no "version" field'))
|
|
2116
|
+
return json
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
// abort 的原话是 "This operation was aborted",看不出是谁的问题,换成能看懂的话
|
|
2119
|
+
if (timedOut) throw new Error(t(`超时(${seconds} 秒内没有响应)`, `timed out (no response in ${seconds}s)`))
|
|
2120
|
+
throw error
|
|
2121
|
+
} finally {
|
|
2122
|
+
if (timer) clearTimeout(timer)
|
|
2123
|
+
}
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
/**
|
|
2127
|
+
* 读清单:自定义地址只用它自己;没配则按 UPDATE_MANIFEST_MIRRORS 依次试,第一个成功的就用。
|
|
2128
|
+
* 全失败时把每个源各自的失败原因汇总抛出 —— 面板上一眼能看出是超时、HTTP 状态还是解析失败。
|
|
2129
|
+
*/
|
|
2130
|
+
async function fetchManifestAuto(targetUrl, token = '', timeoutMs = UPDATE_FETCH_TIMEOUT) {
|
|
2131
|
+
const custom = String(targetUrl || '').trim()
|
|
2132
|
+
const candidates = custom ? [custom] : UPDATE_MANIFEST_MIRRORS.slice()
|
|
2133
|
+
const tried = []
|
|
2134
|
+
for (const cand of candidates) {
|
|
2135
|
+
try {
|
|
2136
|
+
const manifest = await fetchManifest(withAccessToken(cand, token), timeoutMs)
|
|
2137
|
+
tried.push({ url: cand, ok: true })
|
|
2138
|
+
return { manifest, url: cand, tried }
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
const msg = String((error && error.message) || error)
|
|
2141
|
+
let host = cand
|
|
2142
|
+
try { host = new URL(cand).host } catch { }
|
|
2143
|
+
tried.push({ url: cand, host, ok: false, error: msg })
|
|
2144
|
+
if (custom) break
|
|
2145
|
+
}
|
|
2146
|
+
}
|
|
2147
|
+
const detail = tried.map((x) => `${x.host || x.url}:${x.ok ? 'ok' : x.error}`).join(';')
|
|
2148
|
+
const error = new Error(t(`所有更新源都读不到(${detail})`, `No update source could be reached (${detail})`))
|
|
2149
|
+
error.sources = tried
|
|
2150
|
+
throw error
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
/**
|
|
2154
|
+
* 私有仓库的 raw 链接匿名读会 403,必须换成 Gitee API 的 raw 端点再带 access_token。
|
|
2155
|
+
* 注意 API 的 raw 端点不吃"分支写进路径",分支要单独给 ref:
|
|
2156
|
+
* https://gitee.com/<owner>/<repo>/raw/<branch>/<path>
|
|
2157
|
+
* → https://gitee.com/api/v5/repos/<owner>/<repo>/raw/<path>?ref=<branch>&access_token=…
|
|
2158
|
+
* 公开库不填令牌时保持原样,行为跟以前一致。
|
|
2159
|
+
*/
|
|
2160
|
+
function withAccessToken(url, token) {
|
|
2161
|
+
const raw = String(url || '')
|
|
2162
|
+
if (!token) return raw
|
|
2163
|
+
let target = raw
|
|
2164
|
+
const m = /^https:\/\/gitee\.com\/([^/]+)\/([^/]+)\/raw\/([^/]+)\/(.+)$/.exec(raw.split('?')[0])
|
|
2165
|
+
if (m) target = `https://gitee.com/api/v5/repos/${m[1]}/${m[2]}/raw/${m[4]}?ref=${encodeURIComponent(m[3])}`
|
|
2166
|
+
const sep = target.includes('?') ? '&' : '?'
|
|
2167
|
+
return target + sep + 'access_token=' + encodeURIComponent(token)
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
async function checkUpdate({ force = false, url = '', token = '' } = {}) {
|
|
2171
|
+
const custom = String(url || '').trim()
|
|
2172
|
+
const now = Date.now()
|
|
2173
|
+
if (!force && updateState.requestUrl === custom && updateState.token === token && updateState.checkedAt && now - updateState.checkedAt < UPDATE_CHECK_TTL && (updateState.manifest || updateState.error)) {
|
|
2174
|
+
return updateState
|
|
2175
|
+
}
|
|
2176
|
+
updateState.checking = true
|
|
2177
|
+
updateState.requestUrl = custom
|
|
2178
|
+
updateState.token = token
|
|
2179
|
+
try {
|
|
2180
|
+
const got = await fetchManifestAuto(custom, token)
|
|
2181
|
+
updateState.manifest = got.manifest
|
|
2182
|
+
updateState.url = got.url
|
|
2183
|
+
updateState.sources = got.tried
|
|
2184
|
+
updateState.error = ''
|
|
2185
|
+
} catch (error) {
|
|
2186
|
+
updateState.manifest = null
|
|
2187
|
+
if (Array.isArray(error && error.sources)) updateState.sources = error.sources
|
|
2188
|
+
updateState.error = String((error && error.message) || error)
|
|
2189
|
+
} finally {
|
|
2190
|
+
updateState.checking = false
|
|
2191
|
+
updateState.checkedAt = Date.now()
|
|
2192
|
+
}
|
|
2193
|
+
return updateState
|
|
2194
|
+
}
|
|
2195
|
+
|
|
2196
|
+
function updatePayload(state, settings = {}) {
|
|
2197
|
+
const remote = state.manifest
|
|
2198
|
+
const custom = String(settings.updateManifestUrl || '')
|
|
2199
|
+
const installed = state.liveInstall || null
|
|
2200
|
+
// 装好了但进程还在跑旧代码 = 需要重启;重启后 PLUGIN_VERSION 追上来,这条自然消失
|
|
2201
|
+
const restartRequired = Boolean(installed && compareVersion(installed.version, PLUGIN_VERSION) > 0)
|
|
2202
|
+
return {
|
|
2203
|
+
ok: !state.error,
|
|
2204
|
+
local: { version: PLUGIN_VERSION || t('未知', 'unknown'), dir: PLUGIN_DIR },
|
|
2205
|
+
// 更新相关的配置集中在这里(清单地址、令牌是否已存),别散到「云端仓库」卡里
|
|
2206
|
+
config: {
|
|
2207
|
+
manifestUrl: custom || UPDATE_MANIFEST_MIRRORS[0],
|
|
2208
|
+
manifestUrlIsDefault: !custom,
|
|
2209
|
+
manifestSources: custom ? [] : UPDATE_MANIFEST_MIRRORS.slice(),
|
|
2210
|
+
tokenSet: Boolean(settings.updateToken),
|
|
2211
|
+
},
|
|
2212
|
+
remote: remote ? {
|
|
2213
|
+
version: String(remote.version || ''),
|
|
2214
|
+
notes: String(remote.notes || ''),
|
|
2215
|
+
// 清单里的说明是中英两份(notes / notesEn),由客户端按自己的语言挑
|
|
2216
|
+
notesEn: String(remote.notesEn || ''),
|
|
2217
|
+
releasedAt: String(remote.releasedAt || ''),
|
|
2218
|
+
tgz: resolveTgzUrl(remote, state.url),
|
|
2219
|
+
sha256: String(remote.sha256 || ''),
|
|
2220
|
+
} : null,
|
|
2221
|
+
hasUpdate: remote ? compareVersion(remote.version, PLUGIN_VERSION) > 0 : false,
|
|
2222
|
+
checking: state.checking,
|
|
2223
|
+
checkedAt: state.checkedAt || 0,
|
|
2224
|
+
error: state.error || '',
|
|
2225
|
+
// 这次实际用上的源,以及每个源的成败 —— 检查失败时面板直接把原因列出来
|
|
2226
|
+
sourceUsed: state.url || '',
|
|
2227
|
+
sources: Array.isArray(state.sources) ? state.sources : [],
|
|
2228
|
+
installed,
|
|
2229
|
+
// 已经下到暂存目录、等着退出后安装的那个包;ready = 版本比当前进程里的新
|
|
2230
|
+
prepared: state.prepared
|
|
2231
|
+
? {
|
|
2232
|
+
version: String(state.prepared.version || ''),
|
|
2233
|
+
file: String(state.prepared.file || ''),
|
|
2234
|
+
size: Number(state.prepared.size) || 0,
|
|
2235
|
+
sha256: String(state.prepared.sha256 || ''),
|
|
2236
|
+
at: Number(state.prepared.at) || 0,
|
|
2237
|
+
ready: compareVersion(state.prepared.version, PLUGIN_VERSION) > 0,
|
|
2238
|
+
}
|
|
2239
|
+
: null,
|
|
2240
|
+
restartRequired,
|
|
2241
|
+
pending: autoState.pending,
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
/**
|
|
2246
|
+
* 把新版本的包**只下载到暂存目录**,一个字节都不碰插件目录。
|
|
2247
|
+
*
|
|
2248
|
+
* 为什么不能边运行边装:覆盖插件目录会让宿主重新同步插件树,把「配置同步」这个 main 面板
|
|
2249
|
+
* 卸载掉 —— 用户正在看的页面在装到一半时自己跳走,还得点回来才能按「重启」。
|
|
2250
|
+
* 所以把流程拆成两段:这里只负责落盘 + 校验 sha256,真正的覆盖交给退出后的 post-exit。
|
|
2251
|
+
*
|
|
2252
|
+
* 候选地址逐个试(raw 常常不通,反代在前面兜着),全失败时把每个源的原因汇总抛出。
|
|
2253
|
+
* 返回 { ok, file, size, sha256, url } 或 { ok:false, error }
|
|
2254
|
+
*/
|
|
2255
|
+
async function downloadPackage({ urls, sha256, version, dshHome }) {
|
|
2256
|
+
if (typeof fetch !== 'function') return { ok: false, error: t('当前运行环境没有 fetch,无法下载更新包', 'fetch is unavailable in this runtime — cannot download the update package') }
|
|
2257
|
+
const dir = join(dshHome, 'update-staging')
|
|
2258
|
+
try { mkdirSync(dir, { recursive: true }) } catch { }
|
|
2259
|
+
const file = join(dir, `dsh-config-sync-plugin-${version}.tgz`)
|
|
2260
|
+
const want = String(sha256 || '').toLowerCase()
|
|
2261
|
+
const errors = []
|
|
2262
|
+
for (const rawUrl of urls) {
|
|
2263
|
+
const url = String(rawUrl || '').trim()
|
|
2264
|
+
if (!url) continue
|
|
2265
|
+
try {
|
|
2266
|
+
const ctrl = typeof AbortController === 'function' ? new AbortController() : null
|
|
2267
|
+
const timer = ctrl ? setTimeout(() => { try { ctrl.abort() } catch { } }, 120 * 1000) : null
|
|
2268
|
+
let res
|
|
2269
|
+
try {
|
|
2270
|
+
res = await fetch(url, { cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
|
|
2271
|
+
} finally {
|
|
2272
|
+
if (timer) clearTimeout(timer)
|
|
2273
|
+
}
|
|
2274
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`)
|
|
2275
|
+
const buf = Buffer.from(await res.arrayBuffer())
|
|
2276
|
+
if (!buf.length) throw new Error(t('下载到的文件是空的', 'the downloaded file is empty'))
|
|
2277
|
+
const hash = createHash('sha256').update(buf).digest('hex')
|
|
2278
|
+
if (want && hash !== want) throw new Error(t(`sha256 不一致(拿到 ${hash})`, `sha256 mismatch (got ${hash})`))
|
|
2279
|
+
writeFileSync(file, buf)
|
|
2280
|
+
return { ok: true, file, size: buf.length, sha256: hash, url }
|
|
2281
|
+
} catch (error) {
|
|
2282
|
+
let host = url
|
|
2283
|
+
try { host = new URL(url).host } catch { }
|
|
2284
|
+
errors.push(`${host}:${(error && error.message) || String(error)}`)
|
|
2285
|
+
}
|
|
2286
|
+
}
|
|
2287
|
+
return { ok: false, error: t('下载更新包失败(每个地址都试过了):', 'cannot download the update package (every URL was tried): ') + errors.join(t(';', '; ')) }
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
/**
|
|
2291
|
+
* 运行中直接把新版本装进插件目录(不退出 DSH)。
|
|
2292
|
+
*
|
|
2293
|
+
* 注意:界面**不再走这条**。运行中覆盖插件目录会让宿主把当前面板卸载掉,
|
|
2294
|
+
* 用户看到的就是"更新到一半页面自己跳走"。面板改为「prepare 下载 → 退出后安装」,
|
|
2295
|
+
* 见 downloadPackage 的注释。这个函数留给 CLI / 兼容场景。
|
|
2296
|
+
*
|
|
2297
|
+
* 为什么当年能这么干:插件的 ps1 只是磁盘上的脚本,index.js 已经读进内存 —— 覆盖文件不会让当前进程崩,
|
|
2298
|
+
* 只是"文件是新的、进程还是旧的",所以装完必须提示重启才生效。
|
|
2299
|
+
* 真正干活的是 runtime/install-plugin.ps1:它自己依次尝试候选下载地址、校验 sha256、解包、
|
|
2300
|
+
* 备份旧目录(<DshHome>\backups\plugin-<旧版本>-<时间戳>)、覆盖,失败就把备份拷回去。
|
|
2301
|
+
* 返回 { ok, version, backup, log, error }
|
|
2302
|
+
*/
|
|
2303
|
+
function runInstallPlugin({ version, sha256, urls, dshHome }) {
|
|
2304
|
+
const script = join(PLUGIN_DIR, 'runtime', 'install-plugin.ps1')
|
|
2305
|
+
if (!isFile(script)) return Promise.resolve({ ok: false, error: t('插件目录里没有 runtime\\install-plugin.ps1', 'runtime\\install-plugin.ps1 is missing from the plugin directory') })
|
|
2306
|
+
const sysRoot = process.env.SystemRoot || 'C:\\Windows'
|
|
2307
|
+
const ps = join(sysRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe')
|
|
2308
|
+
const args = [
|
|
2309
|
+
'-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', script,
|
|
2310
|
+
'-PluginDir', PLUGIN_DIR,
|
|
2311
|
+
'-Version', String(version || ''),
|
|
2312
|
+
'-Sha256', String(sha256 || ''),
|
|
2313
|
+
'-TgzUrls', urls.join('|'),
|
|
2314
|
+
'-DshHome', dshHome,
|
|
2315
|
+
]
|
|
2316
|
+
return new Promise((resolve) => {
|
|
2317
|
+
execFile(ps, args, { windowsHide: true, timeout: 6 * 60 * 1000, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
|
|
2318
|
+
const text = String(stdout || '') + String(stderr || '')
|
|
2319
|
+
// 脚本最后一行固定是 RESULT:{json};前面是给人看的进度
|
|
2320
|
+
const line = text.split(/\r?\n/).filter((l) => l.startsWith('RESULT:')).pop()
|
|
2321
|
+
if (!line) {
|
|
2322
|
+
resolve({ ok: false, error: t('安装脚本没有返回结果:', 'The installer returned no result: ') + (text.trim().slice(-400) || String((err && err.message) || '无输出')) })
|
|
2323
|
+
return
|
|
2324
|
+
}
|
|
2325
|
+
try { resolve(JSON.parse(line.slice('RESULT:'.length))) } catch { resolve({ ok: false, error: t('安装脚本返回的结果不是合法 JSON', 'The installer result is not valid JSON') }) }
|
|
2326
|
+
})
|
|
2327
|
+
})
|
|
2328
|
+
}
|
|
2329
|
+
|
|
2330
|
+
/**
|
|
2331
|
+
* 更新接口:
|
|
2332
|
+
* GET /config-sync/update 读缓存(30 分钟内不重复拉)
|
|
2333
|
+
* POST {action:'check'} 强制重新检查
|
|
2334
|
+
* POST {action:'install-live'} 运行中下载+校验+覆盖安装(不退出 DSH),装完提示重启生效
|
|
2335
|
+
* POST {action:'restart'} 排队"退出后重启",立刻关闭 DSH,由退出后的脚本用 explorer 代启拉回来
|
|
2336
|
+
* POST {action:'apply'} 兜底:退出 DSH → 可见窗口下载/校验/安装 → 自动重启
|
|
2337
|
+
*/
|
|
2338
|
+
async function handleUpdate(req, res, config) {
|
|
2339
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
2340
|
+
const settings = readSettings(dshHome)
|
|
2341
|
+
// 清单地址允许被设置覆盖:换镜像/自建仓库、或本地搭测试服务时不改动插件源码。
|
|
2342
|
+
// 留空 = 用内置候选列表(jsDelivr 优先、raw 兜底)
|
|
2343
|
+
const manifestUrl = String(settings.updateManifestUrl || '')
|
|
2344
|
+
const updateToken = String(settings.updateToken || '')
|
|
2345
|
+
try {
|
|
2346
|
+
if (req.method === 'GET') {
|
|
2347
|
+
sendJson(res, 200, updatePayload(await checkUpdate({ url: manifestUrl, token: updateToken }), settings))
|
|
2348
|
+
return
|
|
2349
|
+
}
|
|
2350
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET or POST only' }); return }
|
|
2351
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
2352
|
+
const raw = await readBody(req)
|
|
2353
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
2354
|
+
const action = String(body.action || 'check')
|
|
2355
|
+
|
|
2356
|
+
if (action === 'check') {
|
|
2357
|
+
const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
|
|
2358
|
+
sendJson(res, 200, { ok: !state.error, action, ...updatePayload(state, settings) })
|
|
2359
|
+
return
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
// 只下载:把包落到 <DshHome>\update-staging\,校验 sha256,**不动插件目录**。
|
|
2363
|
+
// 面板点「下载更新」走这条 —— 页面不会因为插件被改写而重置。
|
|
2364
|
+
if (action === 'prepare') {
|
|
2365
|
+
const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
|
|
2366
|
+
const remote = state.manifest
|
|
2367
|
+
if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
|
|
2368
|
+
if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
|
|
2369
|
+
throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需更新`, `Already on the latest version (${PLUGIN_VERSION}) — no update needed`))
|
|
2370
|
+
}
|
|
2371
|
+
// 同一个版本已经下好就不重复下(DSH 一直开着时用户可能点第二次)
|
|
2372
|
+
const prev = updateState.prepared
|
|
2373
|
+
if (prev && prev.version === String(remote.version) && isFile(prev.file)) {
|
|
2374
|
+
sendJson(res, 200, { ok: true, action, prepared: prev, ...updatePayload(state, settings) })
|
|
2375
|
+
return
|
|
2376
|
+
}
|
|
2377
|
+
const urls = resolveTgzCandidates(remote, state.url)
|
|
2378
|
+
if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
|
|
2379
|
+
const got = await downloadPackage({ urls, sha256: String(remote.sha256 || ''), version: String(remote.version), dshHome })
|
|
2380
|
+
if (!got.ok) throw new Error(String(got.error || t('下载失败', 'download failed')))
|
|
2381
|
+
updateState.prepared = {
|
|
2382
|
+
version: String(remote.version),
|
|
2383
|
+
sha256: got.sha256,
|
|
2384
|
+
file: got.file,
|
|
2385
|
+
size: got.size,
|
|
2386
|
+
at: Date.now(),
|
|
2387
|
+
url: got.url,
|
|
2388
|
+
}
|
|
2389
|
+
sendJson(res, 200, { ok: true, action, prepared: updateState.prepared, ...updatePayload(state, settings) })
|
|
2390
|
+
return
|
|
2391
|
+
}
|
|
2392
|
+
|
|
2393
|
+
// 装并重启:退出 DSH → 退出后的脚本用**已经下好的本地包**覆盖安装 → 自动拉起
|
|
2394
|
+
// 覆盖发生在 DSH 已退出之后,所以运行中的面板不会被打断,用户也不会被弹走。
|
|
2395
|
+
if (action === 'install-restart') {
|
|
2396
|
+
const prepared = updateState.prepared
|
|
2397
|
+
if (!prepared || !isFile(prepared.file)) {
|
|
2398
|
+
throw new Error(t('还没有下好的更新包,请先点「下载更新」', 'No downloaded package yet — click "Download update" first'))
|
|
2399
|
+
}
|
|
2400
|
+
if (compareVersion(prepared.version, PLUGIN_VERSION) <= 0) {
|
|
2401
|
+
updateState.prepared = null
|
|
2402
|
+
throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需安装`, `Already on the latest version (${PLUGIN_VERSION}) — nothing to install`))
|
|
2403
|
+
}
|
|
2404
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
2405
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
2406
|
+
const started = await spawnWatcher({
|
|
2407
|
+
mode: 'update',
|
|
2408
|
+
repo,
|
|
2409
|
+
appRoot,
|
|
2410
|
+
dshHome,
|
|
2411
|
+
restart: true,
|
|
2412
|
+
extraArgs: [
|
|
2413
|
+
'-PluginDir', PLUGIN_DIR,
|
|
2414
|
+
'-UpdateTgz', prepared.file,
|
|
2415
|
+
'-UpdateVersion', String(prepared.version),
|
|
2416
|
+
'-UpdateSha256', String(prepared.sha256 || ''),
|
|
2417
|
+
],
|
|
2418
|
+
})
|
|
2419
|
+
if (!started.ok) throw new Error(started.error)
|
|
2420
|
+
autoState.pending = { mode: 'update', at: Date.now(), version: String(prepared.version), restart: true, watcherPid: started.pid, installFrom: prepared.file }
|
|
2421
|
+
const closed = closeDsh()
|
|
2422
|
+
autoState.pending.closeRequested = closed
|
|
2423
|
+
sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed, ...updatePayload(await checkUpdate({ force: false, url: manifestUrl, token: updateToken }), settings) })
|
|
2424
|
+
return
|
|
2425
|
+
}
|
|
2426
|
+
|
|
2427
|
+
// 运行中直接装(不退出 DSH,**界面已不再使用**,留给 CLI/兼容):下载 → 校验 sha256 → 备份旧版 → 覆盖插件目录
|
|
2428
|
+
if (action === 'install-live') {
|
|
2429
|
+
const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
|
|
2430
|
+
const remote = state.manifest
|
|
2431
|
+
if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
|
|
2432
|
+
if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
|
|
2433
|
+
throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需更新`, `Already on the latest version (${PLUGIN_VERSION}) — no update needed`))
|
|
2434
|
+
}
|
|
2435
|
+
const urls = resolveTgzCandidates(remote, state.url)
|
|
2436
|
+
if (!urls.length) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
|
|
2437
|
+
// 包只有一百多 KB,同步做完再回包:前端把按钮置灰等这一下就够了
|
|
2438
|
+
const report = await runInstallPlugin({ version: String(remote.version), sha256: String(remote.sha256 || ''), urls, dshHome })
|
|
2439
|
+
if (!report.ok) throw new Error(String(report.error || t('安装失败', 'install failed')))
|
|
2440
|
+
updateState.liveInstall = {
|
|
2441
|
+
version: String(remote.version),
|
|
2442
|
+
at: Date.now(),
|
|
2443
|
+
backup: String(report.backup || ''),
|
|
2444
|
+
log: String(report.log || ''),
|
|
2445
|
+
}
|
|
2446
|
+
// 注意 hasUpdate 仍是 true:进程里跑的还是旧代码,重启后 PLUGIN_VERSION 才追上来。
|
|
2447
|
+
// 面板靠 restartRequired 换成「已装好,重启生效」
|
|
2448
|
+
sendJson(res, 200, { ok: true, action, installed: updateState.liveInstall, ...updatePayload(state, settings) })
|
|
2449
|
+
return
|
|
2450
|
+
}
|
|
2451
|
+
|
|
2452
|
+
// 只重启:排队"退出后拉起",由 post-exit 的 relaunch 模式用 explorer 代启(不继承本窗口作业)
|
|
2453
|
+
if (action === 'restart') {
|
|
2454
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
2455
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
2456
|
+
const started = await spawnWatcher({ mode: 'relaunch', repo, appRoot, dshHome, restart: true })
|
|
2457
|
+
if (!started.ok) throw new Error(started.error)
|
|
2458
|
+
autoState.pending = { mode: 'relaunch', at: Date.now(), restart: true, watcherPid: started.pid }
|
|
2459
|
+
const closed = closeDsh()
|
|
2460
|
+
autoState.pending.closeRequested = closed
|
|
2461
|
+
sendJson(res, 200, { ok: true, action, pending: autoState.pending, closeRequested: closed })
|
|
2462
|
+
return
|
|
2463
|
+
}
|
|
2464
|
+
|
|
2465
|
+
if (action === 'apply') {
|
|
2466
|
+
const state = await checkUpdate({ force: true, url: manifestUrl, token: updateToken })
|
|
2467
|
+
const remote = state.manifest
|
|
2468
|
+
if (!remote) throw new Error(t(`读不到更新清单:${state.error || '未知原因'}`, `Cannot read the update manifest: ${state.error || 'unknown reason'}`))
|
|
2469
|
+
if (compareVersion(remote.version, PLUGIN_VERSION) <= 0) {
|
|
2470
|
+
throw new Error(t(`已经是最新版本(${PLUGIN_VERSION}),无需更新`, `Already on the latest version (${PLUGIN_VERSION}) — no update needed`))
|
|
2471
|
+
}
|
|
2472
|
+
const tgz = resolveTgzUrl(remote, state.url)
|
|
2473
|
+
if (!tgz) throw new Error(t('version.json 里没有给 tgz 下载地址', 'version.json gives no tgz download URL'))
|
|
2474
|
+
const notes = String((langStore.getStore() === 'en' ? (remote.notesEn || remote.notes) : remote.notes) || '').trim()
|
|
2475
|
+
const yes = await askConfirm(
|
|
2476
|
+
t('更新「配置同步」插件', 'Update the Config Sync plugin'),
|
|
2477
|
+
t(
|
|
2478
|
+
`把插件从 ${PLUGIN_VERSION} 更新到 ${remote.version}?`
|
|
2479
|
+
+ (notes ? `\n\n${notes}` : '')
|
|
2480
|
+
+ '\n\n更新过程:退出 DSH → 下载并校验安装包 → 备份旧版 → 覆盖安装 → 自动重启。',
|
|
2481
|
+
`Update the plugin from ${PLUGIN_VERSION} to ${remote.version}?`
|
|
2482
|
+
+ (notes ? `\n\n${notes}` : '')
|
|
2483
|
+
+ '\n\nSteps: exit DSH → download and verify the package → back up the old version → install over it → relaunch automatically.',
|
|
2484
|
+
),
|
|
2485
|
+
)
|
|
2486
|
+
if (!yes) { sendJson(res, 200, { ok: true, action, cancelled: true, ...updatePayload(state, settings) }); return }
|
|
2487
|
+
|
|
2488
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
2489
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
2490
|
+
const started = await spawnWatcher({
|
|
2491
|
+
mode: 'update',
|
|
2492
|
+
repo,
|
|
2493
|
+
appRoot,
|
|
2494
|
+
dshHome,
|
|
2495
|
+
restart: true,
|
|
2496
|
+
extraArgs: [
|
|
2497
|
+
'-PluginDir', PLUGIN_DIR,
|
|
2498
|
+
'-UpdateVersion', String(remote.version),
|
|
2499
|
+
'-UpdateTgz', tgz,
|
|
2500
|
+
'-UpdateSha256', String(remote.sha256 || ''),
|
|
2501
|
+
...(updateToken ? ['-UpdateToken', updateToken] : []),
|
|
2502
|
+
],
|
|
2503
|
+
})
|
|
2504
|
+
if (!started.ok) throw new Error(started.error)
|
|
2505
|
+
autoState.pending = { mode: 'update', at: Date.now(), version: String(remote.version), restart: true, watcherPid: started.pid }
|
|
2506
|
+
const closed = closeDsh()
|
|
2507
|
+
autoState.pending.closeRequested = closed
|
|
2508
|
+
sendJson(res, 200, { ok: true, action, started: true, pending: autoState.pending, closeRequested: closed })
|
|
2509
|
+
return
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
throw new Error(t('action 只能是 check / install-live / restart / apply', 'action must be check / install-live / restart / apply'))
|
|
2513
|
+
} catch (error) {
|
|
2514
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
2515
|
+
}
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
/* ------------------------------------------------------------------------- *
|
|
2519
|
+
* 同步内容勾选(scope)
|
|
2520
|
+
*
|
|
2521
|
+
* 面板「同步内容」卡片的数据落点:<DshHome>\config-sync-scope.json。
|
|
2522
|
+
* capture.ps1 / apply.ps1 读的是**同一个文件**,所以面板上的勾选立刻对
|
|
2523
|
+
* 「推送」和「拉取」两侧生效。文件不存在 = 全勾(保持老行为)。
|
|
2524
|
+
*
|
|
2525
|
+
* 语义:未勾选 = 推送不抓、拉取不还原;deleteCloud(默认关闭)打开时才顺带删掉仓库副本。
|
|
2526
|
+
* ------------------------------------------------------------------------- */
|
|
2527
|
+
|
|
2528
|
+
function scopePath(dshHome) {
|
|
2529
|
+
return join(dshHome, 'config-sync-scope.json')
|
|
2530
|
+
}
|
|
2531
|
+
|
|
2532
|
+
function readScope(dshHome) {
|
|
2533
|
+
const fallback = { version: 1, deleteCloud: false, groups: {} }
|
|
2534
|
+
try {
|
|
2535
|
+
const obj = readJson(scopePath(dshHome))
|
|
2536
|
+
if (!obj || typeof obj !== 'object') return fallback
|
|
2537
|
+
return {
|
|
2538
|
+
version: 1,
|
|
2539
|
+
deleteCloud: obj.deleteCloud === true,
|
|
2540
|
+
groups: (obj.groups && typeof obj.groups === 'object') ? obj.groups : {},
|
|
2541
|
+
}
|
|
2542
|
+
} catch {
|
|
2543
|
+
return fallback
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
function writeScope(dshHome, scope) {
|
|
2548
|
+
const file = scopePath(dshHome)
|
|
2549
|
+
try { mkdirSync(dirname(file), { recursive: true }) } catch { }
|
|
2550
|
+
const payload = JSON.stringify({
|
|
2551
|
+
version: 1,
|
|
2552
|
+
deleteCloud: scope.deleteCloud === true,
|
|
2553
|
+
groups: scope.groups && typeof scope.groups === 'object' ? scope.groups : {},
|
|
2554
|
+
}, null, 2) + '\n'
|
|
2555
|
+
writeFileSync(file, payload, 'utf8')
|
|
2556
|
+
return file
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
// 必需组:不许取消勾选 —— 因为不勾就会报错,而不是"少同步一点"。
|
|
2560
|
+
// profile 里的 package.json / cordis.patch.yml 是 apply 的前置条件(仓库里缺它们 apply.ps1 直接 Die),
|
|
2561
|
+
// host-contract.json 是两端版本一致性校验(丢了它版本不一致也照铺,客户端可能起不来)。
|
|
2562
|
+
const SCOPE_REQUIRED_GROUPS = ['profile']
|
|
2563
|
+
function scopeGroupRequired(id) { return SCOPE_REQUIRED_GROUPS.includes(id) }
|
|
2564
|
+
|
|
2565
|
+
function scopeGroupEnabled(scope, id) {
|
|
2566
|
+
if (scopeGroupRequired(id)) return true
|
|
2567
|
+
const g = scope && scope.groups ? scope.groups[id] : null
|
|
2568
|
+
if (!g || typeof g !== 'object') return true
|
|
2569
|
+
return g.enabled !== false
|
|
2570
|
+
}
|
|
2571
|
+
|
|
2572
|
+
function scopeItemEnabled(scope, id, item) {
|
|
2573
|
+
if (scopeGroupRequired(id)) return true
|
|
2574
|
+
if (!scopeGroupEnabled(scope, id)) return false
|
|
2575
|
+
const g = scope.groups ? scope.groups[id] : null
|
|
2576
|
+
const ex = g && Array.isArray(g.excluded) ? g.excluded : []
|
|
2577
|
+
return !ex.includes(item)
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
/** 目录下的子目录名(排序稳定,避免面板每次顺序都在变) */
|
|
2581
|
+
function listSubDirs(dir) {
|
|
2582
|
+
try {
|
|
2583
|
+
if (!existsSync(dir)) return []
|
|
2584
|
+
return readdirSync(dir, { withFileTypes: true })
|
|
2585
|
+
.filter((e) => e.isDirectory())
|
|
2586
|
+
.map((e) => e.name)
|
|
2587
|
+
.sort((a, b) => a.localeCompare(b))
|
|
2588
|
+
} catch {
|
|
2589
|
+
return []
|
|
2590
|
+
}
|
|
2591
|
+
}
|
|
2592
|
+
|
|
2593
|
+
function countEntries(dir) {
|
|
2594
|
+
try {
|
|
2595
|
+
if (!existsSync(dir)) return 0
|
|
2596
|
+
return readdirSync(dir).length
|
|
2597
|
+
} catch {
|
|
2598
|
+
return 0
|
|
2599
|
+
}
|
|
2600
|
+
}
|
|
2601
|
+
|
|
2602
|
+
/** profile 目录:优先 desktop,其次 profiles 下唯一的那一个 */
|
|
2603
|
+
function resolveProfileDir(dshHome) {
|
|
2604
|
+
const desktop = join(dshHome, 'profiles', 'desktop')
|
|
2605
|
+
if (existsSync(desktop)) return desktop
|
|
2606
|
+
const all = listSubDirs(join(dshHome, 'profiles'))
|
|
2607
|
+
return all.length === 1 ? join(dshHome, 'profiles', all[0]) : desktop
|
|
2608
|
+
}
|
|
2609
|
+
|
|
2610
|
+
/** 本机登记的工作区(title 用用户自己起的名,路径只用来判断在不在) */
|
|
2611
|
+
function listWorkspaceEntries(dshHome) {
|
|
2612
|
+
try {
|
|
2613
|
+
const reg = readJson(join(dshHome, 'storages', 'workspace.json'))
|
|
2614
|
+
const table = reg && reg.tables && reg.tables.workspaces
|
|
2615
|
+
if (!table || typeof table !== 'object') return []
|
|
2616
|
+
return Object.keys(table).sort().map((id) => {
|
|
2617
|
+
const w = table[id] || {}
|
|
2618
|
+
const title = typeof w.title === 'string' && w.title.trim() ? w.title.trim() : id
|
|
2619
|
+
return { id, title, path: typeof w.path === 'string' ? w.path : '' }
|
|
2620
|
+
})
|
|
2621
|
+
} catch {
|
|
2622
|
+
return []
|
|
2623
|
+
}
|
|
2624
|
+
}
|
|
2625
|
+
|
|
2626
|
+
/** link: 进 profile 的本地插件目录名(capture 会把它们打包成 local-plugins\*.zip) */
|
|
2627
|
+
function listLocalPlugins(dshHome) {
|
|
2628
|
+
try {
|
|
2629
|
+
const pkg = readJson(join(resolveProfileDir(dshHome), 'package.json'))
|
|
2630
|
+
const deps = pkg && pkg.dependencies
|
|
2631
|
+
if (!deps || typeof deps !== 'object') return []
|
|
2632
|
+
const names = []
|
|
2633
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
2634
|
+
if (typeof spec !== 'string' || !spec.startsWith('link:')) continue
|
|
2635
|
+
const target = spec.slice(5).replace(/\//g, '\\').replace(/\\+$/, '')
|
|
2636
|
+
const leaf = target.split('\\').filter(Boolean).pop()
|
|
2637
|
+
names.push(leaf || name)
|
|
2638
|
+
}
|
|
2639
|
+
return names.sort((a, b) => a.localeCompare(b))
|
|
2640
|
+
} catch {
|
|
2641
|
+
return []
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
|
|
2645
|
+
/**
|
|
2646
|
+
* 面板要显示的十组内容 + 组内明细项。
|
|
2647
|
+
* 明细项一律用「本机实际存在的名字」,因为用户勾的就是自己看得见的那份。
|
|
2648
|
+
*/
|
|
2649
|
+
/**
|
|
2650
|
+
* 插件数据 / 额外路径(0.3.51 起)的规则文件:<DshHome>\config-sync-extra.json(本机,不进仓库)。
|
|
2651
|
+
* 与 runtime\dsh-sync-common.ps1 的默认值必须一致,否则面板说"会同步"、capture 却跳过。
|
|
2652
|
+
*/
|
|
2653
|
+
const ROUTE_EXTRA_CONFIG = '/config-sync/extra-config'
|
|
2654
|
+
const EXTRA_CONFIG_NAME = 'config-sync-extra.json'
|
|
2655
|
+
/** GitHub 单文件硬上限 100MB,超过必被拒收,所以配置里调多大都按这个封顶。 */
|
|
2656
|
+
const EXTRA_HARD_MAX_BYTES = 104857600
|
|
2657
|
+
const EXTRA_DEFAULT_SKIP_DIRS = [
|
|
2658
|
+
'profiles', 'skills', '.agent-presets', 'storages', 'sessions', 'attachments', 'logs', 'backups',
|
|
2659
|
+
'update-staging', 'electron', 'dsh-runtimes', 'dsh-market', '.dsh-plugin-market', 'dsh-session-manager',
|
|
2660
|
+
'im', 'node_modules',
|
|
2661
|
+
]
|
|
2662
|
+
const EXTRA_DEFAULT_EXCLUDE = [
|
|
2663
|
+
'*.db', '*.db-*', '*.db3', '*.sqlite', '*.sqlite3', '*.sqlite-*', '*.db-shm', '*.db-wal',
|
|
2664
|
+
'*.node', '*.exe', '*.dll', '*.asar', '*.pak', '*.bin', '*.iso', '*.img',
|
|
2665
|
+
'*.zip', '*.7z', '*.rar', '*.tar', '*.gz', '*.tgz', '*.mp4', '*.mkv', '*.avi',
|
|
2666
|
+
'*.log', '*.log.*', '*.tmp', '*.bak', '*.bak-*', '*.old', '*.orig', '*.swp',
|
|
2667
|
+
'api-key', '*.pem', '*.key', '*.p12', '*.pfx', '*.crt',
|
|
2668
|
+
'*cache*', '*token*', '*secret*', '*credential*', '*password*', '*vault*',
|
|
2669
|
+
'node_modules', '.git', '.cache', '__pycache__', '.venv',
|
|
2670
|
+
]
|
|
2671
|
+
|
|
2672
|
+
function extraConfigPath(dshHome) { return join(dshHome, EXTRA_CONFIG_NAME) }
|
|
2673
|
+
|
|
2674
|
+
function readExtraConfig(dshHome) {
|
|
2675
|
+
const cfg = {
|
|
2676
|
+
version: 1,
|
|
2677
|
+
pluginData: {
|
|
2678
|
+
enabled: true,
|
|
2679
|
+
maxFileBytes: EXTRA_HARD_MAX_BYTES,
|
|
2680
|
+
exclude: [...EXTRA_DEFAULT_EXCLUDE],
|
|
2681
|
+
skipDirs: [...EXTRA_DEFAULT_SKIP_DIRS],
|
|
2682
|
+
},
|
|
2683
|
+
extra: { enabled: true, paths: [] },
|
|
2684
|
+
}
|
|
2685
|
+
const p = extraConfigPath(dshHome)
|
|
2686
|
+
if (!isFile(p)) return cfg
|
|
2687
|
+
try {
|
|
2688
|
+
const j = JSON.parse(readFileSync(p, 'utf8'))
|
|
2689
|
+
const pd = j?.pluginData
|
|
2690
|
+
if (pd) {
|
|
2691
|
+
if (pd.enabled === false) cfg.pluginData.enabled = false
|
|
2692
|
+
const n = Number(pd.maxFileBytes)
|
|
2693
|
+
if (Number.isFinite(n) && n > 0) cfg.pluginData.maxFileBytes = Math.min(Math.floor(n), EXTRA_HARD_MAX_BYTES)
|
|
2694
|
+
// 排除名单整份替换:用户在面板里删掉一条就真的不再排除
|
|
2695
|
+
if (Array.isArray(pd.exclude)) cfg.pluginData.exclude = pd.exclude.filter((x) => typeof x === 'string' && x)
|
|
2696
|
+
if (Array.isArray(pd.skipDirs)) cfg.pluginData.skipDirs = pd.skipDirs.filter((x) => typeof x === 'string' && x)
|
|
2697
|
+
}
|
|
2698
|
+
const ex = j?.extra
|
|
2699
|
+
if (ex) {
|
|
2700
|
+
if (ex.enabled === false) cfg.extra.enabled = false
|
|
2701
|
+
if (Array.isArray(ex.paths)) {
|
|
2702
|
+
cfg.extra.paths = ex.paths
|
|
2703
|
+
.filter((x) => x && typeof x.id === 'string' && typeof x.src === 'string' && x.id && x.src)
|
|
2704
|
+
.map((x) => ({ id: x.id, src: x.src, label: typeof x.label === 'string' && x.label ? x.label : x.id }))
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
} catch { /* 坏了就按默认规则走,不让面板整页读不出来 */ }
|
|
2708
|
+
return cfg
|
|
2709
|
+
}
|
|
2710
|
+
|
|
2711
|
+
function saveExtraConfig(dshHome, cfg) {
|
|
2712
|
+
const p = extraConfigPath(dshHome)
|
|
2713
|
+
const out = {
|
|
2714
|
+
version: 1,
|
|
2715
|
+
pluginData: {
|
|
2716
|
+
enabled: cfg.pluginData.enabled !== false,
|
|
2717
|
+
maxFileBytes: Math.min(Math.max(1, Math.floor(Number(cfg.pluginData.maxFileBytes) || EXTRA_HARD_MAX_BYTES)), EXTRA_HARD_MAX_BYTES),
|
|
2718
|
+
exclude: (cfg.pluginData.exclude || []).filter((x) => typeof x === 'string' && x),
|
|
2719
|
+
skipDirs: (cfg.pluginData.skipDirs || []).filter((x) => typeof x === 'string' && x),
|
|
2720
|
+
},
|
|
2721
|
+
extra: {
|
|
2722
|
+
enabled: cfg.extra.enabled !== false,
|
|
2723
|
+
paths: (cfg.extra.paths || []).map((x) => ({ id: x.id, src: x.src, label: x.label || x.id })),
|
|
2724
|
+
},
|
|
2725
|
+
}
|
|
2726
|
+
writeFileSync(p, JSON.stringify(out, null, 2) + '\n', 'utf8')
|
|
2727
|
+
return p
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2730
|
+
function wildcardToRegex(pat) {
|
|
2731
|
+
const esc = String(pat).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
|
|
2732
|
+
return new RegExp(`^${esc}$`, 'i')
|
|
2733
|
+
}
|
|
2734
|
+
|
|
2735
|
+
/** 返回跳过原因('' = 允许同步),与 runtime 的 Test-SyncExtraSkip 判定一致。 */
|
|
2736
|
+
function extraSkipReason(relName, size, cfg) {
|
|
2737
|
+
const max = Math.min(cfg.pluginData.maxFileBytes || EXTRA_HARD_MAX_BYTES, EXTRA_HARD_MAX_BYTES)
|
|
2738
|
+
if (size > max) return 'too-big'
|
|
2739
|
+
if (!relName) return ''
|
|
2740
|
+
const parts = String(relName).split(/[\\/]+/).filter((x) => x)
|
|
2741
|
+
const name = parts.length ? parts[parts.length - 1] : relName
|
|
2742
|
+
for (const pat of cfg.pluginData.exclude || []) {
|
|
2743
|
+
const re = wildcardToRegex(pat)
|
|
2744
|
+
if (re.test(name)) return 'excluded'
|
|
2745
|
+
for (const seg of parts) if (re.test(seg)) return 'excluded'
|
|
2746
|
+
}
|
|
2747
|
+
return ''
|
|
2748
|
+
}
|
|
2749
|
+
|
|
2750
|
+
function dirHasRules(cfg) { return (cfg.pluginData.exclude || []).map(wildcardToRegex) }
|
|
2751
|
+
|
|
2752
|
+
/** 插件数据槽:<DshHome> 的一级目录(跳过系统/已覆盖目录与隐藏目录),带文件数与体积。 */
|
|
2753
|
+
function listPluginDataSlots(dshHome, cfg) {
|
|
2754
|
+
const skip = new Set(cfg.pluginData.skipDirs || [])
|
|
2755
|
+
let entries = []
|
|
2756
|
+
try {
|
|
2757
|
+
entries = readdirSync(dshHome, { withFileTypes: true })
|
|
2758
|
+
} catch { return [] }
|
|
2759
|
+
const out = []
|
|
2760
|
+
for (const e of entries) {
|
|
2761
|
+
if (!e.isDirectory()) continue
|
|
2762
|
+
if (skip.has(e.name)) continue
|
|
2763
|
+
if (e.name.startsWith('.')) continue
|
|
2764
|
+
const stat = countSlotFiles(join(dshHome, e.name), cfg, 0, 4000)
|
|
2765
|
+
out.push({ id: e.name, src: join(dshHome, e.name), files: stat.files, bytes: stat.bytes, capped: stat.capped, skipped: stat.skipped })
|
|
2766
|
+
}
|
|
2767
|
+
return out
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
function countSlotFiles(dir, cfg, depth, limit) {
|
|
2771
|
+
const acc = { files: 0, bytes: 0, skipped: 0, capped: false }
|
|
2772
|
+
if (depth > 8) return acc
|
|
2773
|
+
let entries = []
|
|
2774
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return acc }
|
|
2775
|
+
const rules = dirHasRules(cfg)
|
|
2776
|
+
for (const e of entries) {
|
|
2777
|
+
if (acc.files >= limit) { acc.capped = true; break }
|
|
2778
|
+
if (e.isDirectory()) {
|
|
2779
|
+
if (rules.some((re) => re.test(e.name))) { acc.skipped++; continue }
|
|
2780
|
+
const sub = countSlotFiles(join(dir, e.name), cfg, depth + 1, limit - acc.files)
|
|
2781
|
+
acc.files += sub.files; acc.bytes += sub.bytes; acc.skipped += sub.skipped; acc.capped = acc.capped || sub.capped
|
|
2782
|
+
continue
|
|
2783
|
+
}
|
|
2784
|
+
if (!e.isFile()) continue
|
|
2785
|
+
let size = 0
|
|
2786
|
+
try { size = statSync(join(dir, e.name)).size } catch { continue }
|
|
2787
|
+
if (extraSkipReason(e.name, size, cfg)) { acc.skipped++; continue }
|
|
2788
|
+
acc.files++; acc.bytes += size
|
|
2789
|
+
}
|
|
2790
|
+
return acc
|
|
2791
|
+
}
|
|
2792
|
+
|
|
2793
|
+
function humanBytes(n) {
|
|
2794
|
+
if (n < 1024) return `${n} B`
|
|
2795
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`
|
|
2796
|
+
if (n < 1024 * 1024 * 1024) return `${(n / 1024 / 1024).toFixed(1)} MB`
|
|
2797
|
+
return `${(n / 1024 / 1024 / 1024).toFixed(2)} GB`
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
function collectScopeGroups(dshHome, appRoot) {
|
|
2801
|
+
const profileDir = resolveProfileDir(dshHome)
|
|
2802
|
+
const groups = []
|
|
2803
|
+
|
|
2804
|
+
const profileFiles = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml']
|
|
2805
|
+
.filter((f) => existsSync(join(profileDir, f)))
|
|
2806
|
+
groups.push({ id: 'profile', titleZh: '本机 profile', titleEn: 'Local profile',
|
|
2807
|
+
descZh: 'package.json / lock / cordis 等宿主启动要读的配置', descEn: 'package.json, lockfiles and cordis config the host loads at startup',
|
|
2808
|
+
// 这几个文件互相咬合(lock 与 package.json 的 specifier 必须一致),只做整体开关
|
|
2809
|
+
required: true,
|
|
2810
|
+
items: profileFiles.map((f) => ({ id: f, label: f, excludable: false })) })
|
|
2811
|
+
|
|
2812
|
+
const promptFiles = ['AGENTS.md', 'prompt-inject.md'].filter((f) => existsSync(join(dshHome, f)))
|
|
2813
|
+
groups.push({ id: 'prompt', titleZh: '全局提示', titleEn: 'Global prompts',
|
|
2814
|
+
descZh: 'AGENTS.md 与 prompt-inject.md,所有会话共用的提示词', descEn: 'AGENTS.md and prompt-inject.md — prompts shared by every session',
|
|
2815
|
+
items: promptFiles.map((f) => ({ id: f, label: f })) })
|
|
2816
|
+
|
|
2817
|
+
const skills = listSubDirs(join(dshHome, 'skills'))
|
|
2818
|
+
groups.push({ id: 'skills', titleZh: 'Skills', titleEn: 'Skills',
|
|
2819
|
+
descZh: '整个 skills 目录镜像到云端,另一台机器直接铺回来', descEn: 'The whole skills folder mirrored to the cloud and restored on the other machine',
|
|
2820
|
+
items: skills.map((n) => ({ id: n, label: n })) })
|
|
2821
|
+
|
|
2822
|
+
const presets = listSubDirs(join(dshHome, '.agent-presets'))
|
|
2823
|
+
groups.push({ id: 'presets', titleZh: 'Agent 预设', titleEn: 'Agent presets',
|
|
2824
|
+
descZh: 'Agent 预设目录(新建/编辑过的预设)', descEn: 'Agent preset folders',
|
|
2825
|
+
items: presets.map((n) => ({ id: n, label: n })) })
|
|
2826
|
+
|
|
2827
|
+
const ledgerDir = join(dshHome, 'storages', '@montersy123', 'dsh-skill-market', 'data')
|
|
2828
|
+
const ledger = [
|
|
2829
|
+
{ id: 'skill-market-installed.json', src: join(ledgerDir, 'installed.json') },
|
|
2830
|
+
{ id: 'skill-market-panel.json', src: join(ledgerDir, 'panel.json') },
|
|
2831
|
+
].filter((x) => existsSync(x.src))
|
|
2832
|
+
groups.push({ id: 'storages-record', titleZh: '技能市场台账', titleEn: 'Skill market ledger',
|
|
2833
|
+
descZh: '技能市场的安装台账与面板状态', descEn: 'Skill-market install ledger and panel state',
|
|
2834
|
+
items: ledger.map((f) => ({ id: f.id, label: f.id })) })
|
|
2835
|
+
|
|
2836
|
+
const settingsFiles = [
|
|
2837
|
+
{ id: 'our-free-model.json', src: join(dshHome, 'our-free-model', 'settings.json') },
|
|
2838
|
+
{ id: 'comfyui-workflows.json', src: join(dshHome, 'data', 'dsh-comfyui', 'workflows.json') },
|
|
2839
|
+
{ id: 'dsh-pet-main-config.jsonc', src: join(dshHome, 'dsh-pet', 'main-config.jsonc') },
|
|
2840
|
+
{ id: 'dsh-market-state.json', src: join(profileDir, '.dsh-market', 'state.json') },
|
|
2841
|
+
].filter((x) => existsSync(x.src))
|
|
2842
|
+
groups.push({ id: 'settings', titleZh: '插件设置与工作流', titleEn: 'Plugin settings & workflows',
|
|
2843
|
+
descZh: '免付费模型设置、ComfyUI 工作流库、桌宠配置、插件市场状态', descEn: 'Free-model settings, ComfyUI workflows, desktop-pet config, market state',
|
|
2844
|
+
items: settingsFiles.map((x) => ({ id: x.id, label: x.id })) })
|
|
2845
|
+
|
|
2846
|
+
const mnemonDir = appRoot ? join(appRoot, 'mnemon') : ''
|
|
2847
|
+
const mnemonCount = mnemonDir && existsSync(mnemonDir) ? countEntries(mnemonDir) : 0
|
|
2848
|
+
groups.push({ id: 'mnemon', titleZh: '记忆数据', titleEn: 'Memory data',
|
|
2849
|
+
descZh: '记忆插件的数据目录(mnemon)', descEn: 'Memory-plugin data folder (mnemon)',
|
|
2850
|
+
items: mnemonDir && existsSync(mnemonDir) ? [{ id: 'mnemon', label: `mnemon(${mnemonCount} 项)`, excludable: false }] : [] })
|
|
2851
|
+
|
|
2852
|
+
const localPlugins = listLocalPlugins(dshHome)
|
|
2853
|
+
groups.push({ id: 'local-plugins', titleZh: '本地源码插件包', titleEn: 'Local plugin packages',
|
|
2854
|
+
descZh: 'link 进 profile 的本地插件,打包成 zip 随配置走', descEn: 'link:-mounted local plugins, packaged as zip and carried with the config',
|
|
2855
|
+
items: localPlugins.map((n) => ({ id: n, label: n })) })
|
|
2856
|
+
|
|
2857
|
+
// 0.3.51 起:插件自己写的配置/数据(<DshHome> 一级目录)与用户自选的额外路径
|
|
2858
|
+
// 规则在 config-sync-extra.json 里,默认全勾;已被上面几组覆盖的目录不进这一组(避免仓库出现两份)
|
|
2859
|
+
const extraCfg = readExtraConfig(dshHome)
|
|
2860
|
+
const pdSlots = listPluginDataSlots(dshHome, extraCfg)
|
|
2861
|
+
groups.push({ id: 'plugin-data', titleZh: '插件数据', titleEn: 'Plugin data',
|
|
2862
|
+
descZh: '各插件自己目录里的配置与数据(排除缓存、数据库、密钥与大文件)', descEn: 'Config and data plugins keep in their own folders (caches, databases, keys and big files excluded)',
|
|
2863
|
+
enabledOff: extraCfg.pluginData.enabled === false,
|
|
2864
|
+
items: pdSlots.map((s) => {
|
|
2865
|
+
const size = humanBytes(s.bytes)
|
|
2866
|
+
const label = s.files === 0
|
|
2867
|
+
? `${s.id} · 0 files`
|
|
2868
|
+
: `${s.id} · ${s.capped ? '4000+' : s.files} files · ${size}`
|
|
2869
|
+
return { id: s.id, label, files: s.files, bytes: s.bytes, skipped: s.skipped }
|
|
2870
|
+
}) })
|
|
2871
|
+
|
|
2872
|
+
groups.push({ id: 'extra', titleZh: '额外路径', titleEn: 'Extra paths',
|
|
2873
|
+
descZh: '你自己指定要跟着配置走的文件或目录(存在 config-sync-extra.json)', descEn: 'Files or folders you add yourself (kept in config-sync-extra.json)',
|
|
2874
|
+
enabledOff: extraCfg.extra.enabled === false,
|
|
2875
|
+
items: (extraCfg.extra.paths || []).map((p) => ({ id: p.id, label: `${p.label || p.id} ${p.src}` })) })
|
|
2876
|
+
|
|
2877
|
+
const workspaces = listWorkspaceEntries(dshHome)
|
|
2878
|
+
groups.push({ id: 'workspace', titleZh: '工作区资料', titleEn: 'Workspace files',
|
|
2879
|
+
descZh: '登记过的工作区里的资料(>100MB 与模型权重本来就不同步)', descEn: 'Files inside registered workspaces (big files and model weights are never synced)',
|
|
2880
|
+
items: workspaces.map((w) => ({ id: w.id, label: w.title })) })
|
|
2881
|
+
|
|
2882
|
+
groups.push({ id: 'conversations', titleZh: '会话记录', titleEn: 'Conversations',
|
|
2883
|
+
descZh: '每个工作区的对话、附件与缓存(按工作区勾选)', descEn: 'Chats, attachments and caches per workspace',
|
|
2884
|
+
items: workspaces.map((w) => ({ id: w.id, label: w.title })) })
|
|
2885
|
+
|
|
2886
|
+
const scope = readScope(dshHome)
|
|
2887
|
+
for (const g of groups) {
|
|
2888
|
+
g.enabled = scopeGroupEnabled(scope, g.id)
|
|
2889
|
+
// 组在 config-sync-extra.json 里被关掉时,面板也要显示未勾选(两处判断必须一致)
|
|
2890
|
+
if (g.enabledOff === true) g.enabled = false
|
|
2891
|
+
for (const it of g.items) it.enabled = scopeItemEnabled(scope, g.id, it.id)
|
|
2892
|
+
}
|
|
2893
|
+
return { scope, groups, extraCfg }
|
|
2894
|
+
}
|
|
2895
|
+
|
|
2896
|
+
async function handleScope(req, res, config) {
|
|
2897
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
2898
|
+
try {
|
|
2899
|
+
if (req.method === 'GET') {
|
|
2900
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
2901
|
+
const { scope, groups } = collectScopeGroups(dshHome, appRoot)
|
|
2902
|
+
sendJson(res, 200, {
|
|
2903
|
+
ok: true,
|
|
2904
|
+
deleteCloud: scope.deleteCloud === true,
|
|
2905
|
+
path: scopePath(dshHome),
|
|
2906
|
+
groups: groups.map((g) => ({
|
|
2907
|
+
id: g.id,
|
|
2908
|
+
title: t(g.titleZh, g.titleEn),
|
|
2909
|
+
desc: t(g.descZh, g.descEn),
|
|
2910
|
+
enabled: g.enabled,
|
|
2911
|
+
required: g.required === true,
|
|
2912
|
+
items: g.items.map((it) => ({ id: it.id, label: it.label, enabled: it.enabled, excludable: it.excludable !== false })),
|
|
2913
|
+
})),
|
|
2914
|
+
})
|
|
2915
|
+
return
|
|
2916
|
+
}
|
|
2917
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET/POST only' }); return }
|
|
2918
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
2919
|
+
const raw = await readBody(req)
|
|
2920
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
2921
|
+
const groupsIn = body && typeof body.groups === 'object' && body.groups ? body.groups : {}
|
|
2922
|
+
// 排除项只认「本机当前真实存在、且允许单独排除」的条目:
|
|
2923
|
+
// 拖着一堆早就不存在的 id 会让用户以后勾不回来(看不见却一直挡着同步)。
|
|
2924
|
+
const allowed = {}
|
|
2925
|
+
try {
|
|
2926
|
+
const cur = collectScopeGroups(dshHome, resolveAppRoot(config?.appRoot) || '')
|
|
2927
|
+
for (const g of cur.groups) allowed[g.id] = new Set(g.items.filter((i) => i.excludable !== false).map((i) => i.id))
|
|
2928
|
+
} catch { }
|
|
2929
|
+
const clean = {}
|
|
2930
|
+
// 这两组的整组开关同时写进 config-sync-extra.json:面板显示与 capture 判定都读同一处
|
|
2931
|
+
const extraForScope = readExtraConfig(dshHome)
|
|
2932
|
+
let extraDirty = false
|
|
2933
|
+
for (const [id, key] of [['plugin-data', 'pluginData'], ['extra', 'extra']]) {
|
|
2934
|
+
const g = groupsIn[id]
|
|
2935
|
+
if (g && typeof g === 'object' && typeof g.enabled === 'boolean') { extraForScope[key].enabled = g.enabled; extraDirty = true }
|
|
2936
|
+
}
|
|
2937
|
+
for (const [id, g] of Object.entries(groupsIn)) {
|
|
2938
|
+
if (!g || typeof g !== 'object') continue
|
|
2939
|
+
// 必需组一律按"开启、无排除"处理:关掉它会让另一台 apply 直接报错,不是"少同步一点"
|
|
2940
|
+
if (scopeGroupRequired(id)) continue
|
|
2941
|
+
const entry = {}
|
|
2942
|
+
if (g.enabled === false) entry.enabled = false
|
|
2943
|
+
let ex = Array.isArray(g.excluded) ? g.excluded.filter((x) => typeof x === 'string' && x) : []
|
|
2944
|
+
if (allowed[id]) ex = ex.filter((x) => allowed[id].has(x))
|
|
2945
|
+
if (ex.length) entry.excluded = ex
|
|
2946
|
+
// 全勾的组不落盘:文件里只留"跟默认不一样"的部分,手改起来也清爽
|
|
2947
|
+
if (Object.keys(entry).length) clean[id] = entry
|
|
2948
|
+
}
|
|
2949
|
+
const file = writeScope(dshHome, { deleteCloud: body.deleteCloud === true, groups: clean })
|
|
2950
|
+
if (extraDirty) { try { saveExtraConfig(dshHome, extraForScope) } catch { } }
|
|
2951
|
+
sendJson(res, 200, { ok: true, path: file, deleteCloud: body.deleteCloud === true })
|
|
2952
|
+
} catch (error) {
|
|
2953
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
2954
|
+
}
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
/**
|
|
2958
|
+
* 「同步冲突」接口:pull 被本机文件挡住时,sync.ps1 会写 <DshHome>\sync-conflicts.json。
|
|
2959
|
+
* GET 读清单(两侧预览 + 每项当前选择)
|
|
2960
|
+
* POST {items:[{path,choice}]} 保存选择(choice 只认 '' / 'local' / 'cloud')
|
|
2961
|
+
* POST {action:'restore',path} 把某一项的本机副本从备份写回工作区
|
|
2962
|
+
* POST {action:'reset'} 放弃这份清单(下次拉取会重新算)
|
|
2963
|
+
* 真正按选择落地的是 sync.ps1(下次「立即拉取」读同一份文件),这里只动 JSON 与备份。
|
|
2964
|
+
*/
|
|
2965
|
+
function conflictPath(dshHome) { return join(dshHome, 'sync-conflicts.json') }
|
|
2966
|
+
|
|
2967
|
+
function readConflicts(dshHome) {
|
|
2968
|
+
const p = conflictPath(dshHome)
|
|
2969
|
+
if (!isFile(p)) return null
|
|
2970
|
+
try {
|
|
2971
|
+
const obj = JSON.parse(readFileSync(p, 'utf8'))
|
|
2972
|
+
if (!obj || !Array.isArray(obj.items)) return null
|
|
2973
|
+
return obj
|
|
2974
|
+
} catch { return null }
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
function writeConflicts(dshHome, obj) {
|
|
2978
|
+
const p = conflictPath(dshHome)
|
|
2979
|
+
mkdirSync(dirname(p), { recursive: true })
|
|
2980
|
+
writeFileSync(p, JSON.stringify(obj, null, 2) + '\n', 'utf8')
|
|
2981
|
+
return p
|
|
2982
|
+
}
|
|
2983
|
+
|
|
2984
|
+
/**
|
|
2985
|
+
* 「插件数据 / 额外路径」规则:<DshHome>\config-sync-extra.json。
|
|
2986
|
+
* GET 返回当前规则 + 默认名单(面板用来做「恢复默认」);
|
|
2987
|
+
* POST 覆盖保存:排除名单要可改(用户删一条就真不排除),单文件上限卡在 100MB(GitHub 硬限)。
|
|
2988
|
+
*/
|
|
2989
|
+
async function handleExtraConfig(req, res, config) {
|
|
2990
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
2991
|
+
try {
|
|
2992
|
+
const cfgPath = extraConfigPath(dshHome)
|
|
2993
|
+
if (req.method === 'GET') {
|
|
2994
|
+
const cfg = readExtraConfig(dshHome)
|
|
2995
|
+
sendJson(res, 200, {
|
|
2996
|
+
ok: true,
|
|
2997
|
+
path: cfgPath,
|
|
2998
|
+
exists: isFile(cfgPath),
|
|
2999
|
+
hardMaxBytes: EXTRA_HARD_MAX_BYTES,
|
|
3000
|
+
defaults: {
|
|
3001
|
+
exclude: EXTRA_DEFAULT_EXCLUDE,
|
|
3002
|
+
skipDirs: EXTRA_DEFAULT_SKIP_DIRS,
|
|
3003
|
+
maxFileBytes: EXTRA_HARD_MAX_BYTES,
|
|
3004
|
+
},
|
|
3005
|
+
config: cfg,
|
|
3006
|
+
})
|
|
3007
|
+
return
|
|
3008
|
+
}
|
|
3009
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET/POST only' }); return }
|
|
3010
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3011
|
+
const raw = await readBody(req)
|
|
3012
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
3013
|
+
const src = body && typeof body.config === 'object' && body.config ? body.config : (body || {})
|
|
3014
|
+
const cur = readExtraConfig(dshHome)
|
|
3015
|
+
if (src.pluginData && typeof src.pluginData === 'object') {
|
|
3016
|
+
if (typeof src.pluginData.enabled === 'boolean') cur.pluginData.enabled = src.pluginData.enabled
|
|
3017
|
+
const n = Number(src.pluginData.maxFileBytes)
|
|
3018
|
+
if (Number.isFinite(n) && n > 0) cur.pluginData.maxFileBytes = Math.min(Math.floor(n), EXTRA_HARD_MAX_BYTES)
|
|
3019
|
+
if (Array.isArray(src.pluginData.exclude)) cur.pluginData.exclude = src.pluginData.exclude.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim())
|
|
3020
|
+
if (Array.isArray(src.pluginData.skipDirs)) cur.pluginData.skipDirs = src.pluginData.skipDirs.filter((x) => typeof x === 'string' && x.trim()).map((x) => x.trim())
|
|
3021
|
+
}
|
|
3022
|
+
if (src.extra && typeof src.extra === 'object') {
|
|
3023
|
+
if (typeof src.extra.enabled === 'boolean') cur.extra.enabled = src.extra.enabled
|
|
3024
|
+
if (Array.isArray(src.extra.paths)) {
|
|
3025
|
+
const used = new Set()
|
|
3026
|
+
const paths = []
|
|
3027
|
+
for (const p of src.extra.paths) {
|
|
3028
|
+
if (!p || typeof p.src !== 'string' || !p.src.trim()) continue
|
|
3029
|
+
const abs = p.src.trim().replace(/\//g, '\\')
|
|
3030
|
+
if (!/^[A-Za-z]:\\/.test(abs) && !abs.startsWith('\\\\')) continue
|
|
3031
|
+
const base = (typeof p.label === 'string' && p.label.trim())
|
|
3032
|
+
? p.label.trim()
|
|
3033
|
+
: (typeof p.id === 'string' && p.id.trim() ? p.id.trim() : basename(abs))
|
|
3034
|
+
let id = String(base).replace(/[\\/:*?"<>|\s]+/g, '-').replace(/^-+|-+$/g, '') || 'extra'
|
|
3035
|
+
if (!isAbsolute(abs)) continue
|
|
3036
|
+
let n = 2
|
|
3037
|
+
const root = id
|
|
3038
|
+
while (used.has(id.toLowerCase())) { id = `${root}-${n++}` }
|
|
3039
|
+
used.add(id.toLowerCase())
|
|
3040
|
+
paths.push({ id, src: abs, label: base })
|
|
3041
|
+
}
|
|
3042
|
+
cur.extra.paths = paths
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
const p = saveExtraConfig(dshHome, cur)
|
|
3046
|
+
sendJson(res, 200, { ok: true, path: p, config: readExtraConfig(dshHome) })
|
|
3047
|
+
} catch (error) {
|
|
3048
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
3049
|
+
}
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
async function handleConflict(req, res, config) {
|
|
3053
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3054
|
+
try {
|
|
3055
|
+
if (req.method === 'GET') {
|
|
3056
|
+
const obj = readConflicts(dshHome)
|
|
3057
|
+
if (!obj) { sendJson(res, 200, { ok: true, exists: false, path: conflictPath(dshHome) }); return }
|
|
3058
|
+
const items = obj.items.map((it) => ({
|
|
3059
|
+
path: String(it.path || ''),
|
|
3060
|
+
kind: String(it.kind || ''),
|
|
3061
|
+
localSize: Number(it.localSize) || 0,
|
|
3062
|
+
remoteSize: Number(it.remoteSize) || 0,
|
|
3063
|
+
binary: it.binary === true,
|
|
3064
|
+
localPreview: String(it.localPreview || ''),
|
|
3065
|
+
remotePreview: String(it.remotePreview || ''),
|
|
3066
|
+
// 备份里到底有没有这一份(旧清单 / 备份失败时面板要把对应按钮置灰)
|
|
3067
|
+
localSaved: it.localSaved !== false,
|
|
3068
|
+
cloudSaved: it.cloudSaved === true,
|
|
3069
|
+
choice: String(it.choice || ''),
|
|
3070
|
+
}))
|
|
3071
|
+
sendJson(res, 200, {
|
|
3072
|
+
ok: true,
|
|
3073
|
+
exists: true,
|
|
3074
|
+
path: conflictPath(dshHome),
|
|
3075
|
+
at: obj.at || '',
|
|
3076
|
+
head: obj.head || '',
|
|
3077
|
+
remoteHead: obj.remoteHead || '',
|
|
3078
|
+
backupDir: obj.backupDir || '',
|
|
3079
|
+
items,
|
|
3080
|
+
})
|
|
3081
|
+
return
|
|
3082
|
+
}
|
|
3083
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'GET/POST only' }); return }
|
|
3084
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3085
|
+
const raw = await readBody(req)
|
|
3086
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
3087
|
+
const obj = readConflicts(dshHome)
|
|
3088
|
+
if (!obj) {
|
|
3089
|
+
throw new Error(t(
|
|
3090
|
+
'当前没有待处理的冲突清单(下次拉取被本机文件挡住时会自动生成)',
|
|
3091
|
+
'No pending conflict list (one is created automatically when a pull is blocked)',
|
|
3092
|
+
))
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
if (body.action === 'reset') {
|
|
3096
|
+
try { unlinkSync(conflictPath(dshHome)) } catch { }
|
|
3097
|
+
sendJson(res, 200, { ok: true, cleared: true })
|
|
3098
|
+
return
|
|
3099
|
+
}
|
|
3100
|
+
|
|
3101
|
+
if (body.action === 'restore') {
|
|
3102
|
+
const rel = String(body.path || '').trim()
|
|
3103
|
+
if (!rel) throw new Error(t('没有指定要还原的文件', 'No file was given to restore'))
|
|
3104
|
+
const side = body.side === 'cloud' ? 'cloud' : 'local'
|
|
3105
|
+
// 还原落到「当时发生冲突的那个仓库」(清单里记着),而不是此刻设置里的路径:
|
|
3106
|
+
// 用户之后改过 repoPath 也不会把副本写进另一个仓库。
|
|
3107
|
+
const repo = String(obj.repo || '') || resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
3108
|
+
if (!repo) throw new Error(t('还没有配置仓库目录', 'Repo directory is not configured'))
|
|
3109
|
+
const known = obj.items.find((it) => String(it.path) === rel)
|
|
3110
|
+
if (!known) throw new Error(t(`冲突清单里没有这个文件:${rel}`, `Not in the conflict list: ${rel}`))
|
|
3111
|
+
const base = String(obj.backupDir || '')
|
|
3112
|
+
if (!base) throw new Error(t('这份清单没有记录备份目录', 'The list has no backup directory'))
|
|
3113
|
+
// 目录名带中英说明;旧清单(0.3.17 最早那版)是 files / files-cloud,这里兜底
|
|
3114
|
+
const sub = side === 'cloud'
|
|
3115
|
+
? (isDir(join(base, '云端-Cloud')) ? '云端-Cloud' : 'files-cloud')
|
|
3116
|
+
: (isDir(join(base, '本机-Local')) ? '本机-Local' : 'files')
|
|
3117
|
+
const src = join(base, sub, rel)
|
|
3118
|
+
if (!isFile(src)) {
|
|
3119
|
+
throw new Error(side === 'cloud'
|
|
3120
|
+
? t('备份里没有这一项的云端副本(旧版清单不会存云端),无法还原', 'No cloud copy for this item (older lists did not save one)')
|
|
3121
|
+
: t('备份里没有这一项的本机副本,无法还原', 'No local copy for this item in the backup'))
|
|
3122
|
+
}
|
|
3123
|
+
const dst = join(repo, rel)
|
|
3124
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
3125
|
+
writeFileSync(dst, readFileSync(src))
|
|
3126
|
+
sendJson(res, 200, { ok: true, restored: rel, side })
|
|
3127
|
+
return
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
const incoming = Array.isArray(body.items) ? body.items : []
|
|
3131
|
+
const byPath = new Map(obj.items.map((it) => [String(it.path), it]))
|
|
3132
|
+
for (const one of incoming) {
|
|
3133
|
+
const p = String((one && one.path) || '')
|
|
3134
|
+
const c = String((one && one.choice) || '')
|
|
3135
|
+
const target = byPath.get(p)
|
|
3136
|
+
if (!target) continue
|
|
3137
|
+
target.choice = (c === 'local' || c === 'cloud') ? c : ''
|
|
3138
|
+
}
|
|
3139
|
+
const saved = writeConflicts(dshHome, obj)
|
|
3140
|
+
const pending = obj.items.filter((it) => !it.choice).length
|
|
3141
|
+
sendJson(res, 200, {
|
|
3142
|
+
ok: true,
|
|
3143
|
+
path: saved,
|
|
3144
|
+
pending,
|
|
3145
|
+
total: obj.items.length,
|
|
3146
|
+
chosen: obj.items.length - pending,
|
|
3147
|
+
})
|
|
3148
|
+
} catch (error) {
|
|
3149
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
3150
|
+
}
|
|
3151
|
+
}
|
|
3152
|
+
|
|
3153
|
+
async function handleStatus(req, res, config) {
|
|
3154
|
+
try {
|
|
3155
|
+
sendJson(res, 200, await inspect(config))
|
|
3156
|
+
} catch (error) {
|
|
3157
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
3158
|
+
}
|
|
3159
|
+
}
|
|
3160
|
+
|
|
3161
|
+
/**
|
|
3162
|
+
* 自动同步 / 自动推送的控制口:
|
|
3163
|
+
* {action:'check'} 立刻做一次只读 fetch,返回 ahead/behind
|
|
3164
|
+
* {action:'pull-now'} 排队"退出后拉取",restart=true 时拉完自动拉起客户端;可选择立刻关闭 DSH
|
|
3165
|
+
* {action:'push-now'} 排队"退出后推送"
|
|
3166
|
+
* {action:'cancel'} 取消已排队的动作
|
|
3167
|
+
* 只做只读 fetch 比对(check),真正动手一律交给退出后的 post-exit.ps1。
|
|
3168
|
+
*/
|
|
3169
|
+
async function handleAuto(req, res, config) {
|
|
3170
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
3171
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3172
|
+
try {
|
|
3173
|
+
const raw = await readBody(req)
|
|
3174
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
3175
|
+
const action = String(body.action || '')
|
|
3176
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3177
|
+
const settings = readSettings(dshHome)
|
|
3178
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
3179
|
+
// 还原只动本机快照,仓库没配也能用;推送/拉取才必须以仓库目录为前置
|
|
3180
|
+
const isRestore = action === 'restore-now' || action === 'restore-preview'
|
|
3181
|
+
if (!repo && !isRestore) throw new Error(t('还没有配置仓库目录,自动同步无从谈起', 'The repo directory is not configured, so auto sync cannot work'))
|
|
3182
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
3183
|
+
|
|
3184
|
+
if (action === 'check') {
|
|
3185
|
+
// 空白目录/还没建:这是「等首次拉取」的正常状态,不是错误 —— 别拿 git 命令去撞空目录
|
|
3186
|
+
const phase = repoPhase(repo)
|
|
3187
|
+
if (phase !== 'ok') {
|
|
3188
|
+
autoState.checking = false
|
|
3189
|
+
autoState.lastCheckAt = Date.now()
|
|
3190
|
+
autoState.lastCheckError = ''
|
|
3191
|
+
autoState.drift = null
|
|
3192
|
+
sendJson(res, 200, {
|
|
3193
|
+
ok: true, action, drift: null, error: null, pendingPull: true,
|
|
3194
|
+
note: t(
|
|
3195
|
+
'本机仓库还没内容:云端有内容就点「拉取」;两边都空就点「初始化推送」。比对差异要有仓库内容之后才做',
|
|
3196
|
+
'The local repo has no content yet: Pull if the cloud has content, Initialize push if both are empty. Drift needs repo content first.',
|
|
3197
|
+
),
|
|
3198
|
+
})
|
|
3199
|
+
return
|
|
3200
|
+
}
|
|
3201
|
+
autoState.checking = true
|
|
3202
|
+
autoState.lastCheckError = ''
|
|
3203
|
+
const drift = await checkDrift(repo)
|
|
3204
|
+
autoState.checking = false
|
|
3205
|
+
autoState.lastCheckAt = Date.now()
|
|
3206
|
+
if (!drift) {
|
|
3207
|
+
autoState.lastCheckError = t(
|
|
3208
|
+
'读不到远端(fetch 失败或没有 origin),先确认云端仓库地址与 SSH',
|
|
3209
|
+
'Cannot read the remote (fetch failed or there is no origin) — check the cloud repo URL and SSH setup',
|
|
3210
|
+
)
|
|
3211
|
+
}
|
|
3212
|
+
autoState.drift = drift
|
|
3213
|
+
sendJson(res, 200, { ok: true, action, drift, error: autoState.lastCheckError || null })
|
|
3214
|
+
return
|
|
3215
|
+
}
|
|
3216
|
+
|
|
3217
|
+
if (action === 'cancel') {
|
|
3218
|
+
autoState.pending = null
|
|
3219
|
+
sendJson(res, 200, { ok: true, action, pending: null })
|
|
3220
|
+
return
|
|
3221
|
+
}
|
|
3222
|
+
|
|
3223
|
+
if (action === 'restore-preview') {
|
|
3224
|
+
const snap = resolveSnapshotDir(dshHome, body.backupDir)
|
|
3225
|
+
const preview = snap.kind === 'profile'
|
|
3226
|
+
? { ...restorePreview(dshHome, snap.dir, config), kind: 'profile' }
|
|
3227
|
+
: restorePreviewForKind(snap, dshHome)
|
|
3228
|
+
sendJson(res, 200, { ok: true, action, preview })
|
|
3229
|
+
return
|
|
3230
|
+
}
|
|
3231
|
+
|
|
3232
|
+
if (action === 'restore-now') {
|
|
3233
|
+
// 直接排队「退出后还原」:和 pull-now 一条流水线,只是执行体换成 restore.ps1。
|
|
3234
|
+
// 面板点它之前会先弹确认框(预览差异),确认之后才走到这里。
|
|
3235
|
+
// 类型决定 restore.ps1 走哪条分支:profile(时点回退)/ plugin(插件回滚)/ session(会话还原)。
|
|
3236
|
+
const snap = resolveSnapshotDir(dshHome, body.backupDir)
|
|
3237
|
+
const restart = body.restart !== false && settings.autoRestart !== false
|
|
3238
|
+
const extraArgs = ['-BackupDir', snap.dir]
|
|
3239
|
+
if (snap.kind !== 'profile') extraArgs.push('-SnapshotKind', snap.kind)
|
|
3240
|
+
if (snap.kind === 'plugin') extraArgs.push('-PluginDir', PLUGIN_ROOT)
|
|
3241
|
+
const started = await spawnWatcher({
|
|
3242
|
+
mode: 'restore', repo, appRoot, dshHome, restart,
|
|
3243
|
+
extraArgs,
|
|
3244
|
+
})
|
|
3245
|
+
if (!started.ok) throw new Error(started.error)
|
|
3246
|
+
autoState.pending = { mode: 'restore', at: Date.now(), restart, watcherPid: started.pid, closeRequested: false, backupDir: snap.dir, snapshotKind: snap.kind }
|
|
3247
|
+
let closed = false
|
|
3248
|
+
if (body.closeNow !== false) {
|
|
3249
|
+
closed = closeDsh()
|
|
3250
|
+
autoState.pending.closeRequested = closed
|
|
3251
|
+
}
|
|
3252
|
+
sendJson(res, 200, { ok: true, action, pending: autoState.pending, closeRequested: closed })
|
|
3253
|
+
return
|
|
3254
|
+
}
|
|
3255
|
+
|
|
3256
|
+
if (action === 'pull-now' || action === 'push-now') {
|
|
3257
|
+
const mode = action === 'pull-now' ? 'pull' : 'push'
|
|
3258
|
+
// 推送的门禁:真仓库直接推;本机还是空的,只有「云端确实没有文件」才能推 —— 那次推送就是初始化推送。
|
|
3259
|
+
// 云端已有文件时拒绝,让用户先拉取(否则本机状态会被写进一份已经在用的历史里)。
|
|
3260
|
+
// 注意判据是「树里有文件」而不是「有分支」:远端可能只剩一个空分支,那也是空仓库,可以初始化推送。
|
|
3261
|
+
if (mode === 'push' && repoPhase(repo) !== 'ok') {
|
|
3262
|
+
const url = (await git(repo, ['remote', 'get-url', 'origin'])) || settings.remoteUrl || ''
|
|
3263
|
+
const probe = await probeRemote(url, settings)
|
|
3264
|
+
if (!probe || probe.files === null) {
|
|
3265
|
+
throw new Error(t(
|
|
3266
|
+
`连不上云端、或还没有云端仓库地址(${url || '未配置'}):初始化推送要先确认云端是空仓库`,
|
|
3267
|
+
`Cannot reach the cloud or no remote URL is set (${url || 'not set'}): initialize push needs to confirm the cloud repo is still empty.`,
|
|
3268
|
+
))
|
|
3269
|
+
}
|
|
3270
|
+
if (probe.files > 0) {
|
|
3271
|
+
throw new Error(t(
|
|
3272
|
+
`云端仓库已经有内容(${probe.files} 个文件):本机还是空的,先「拉取」把内容拉下来,再生成推送`,
|
|
3273
|
+
`The cloud repo already has content (${probe.files} file(s)): run Pull to fetch it first, then push.`,
|
|
3274
|
+
))
|
|
3275
|
+
}
|
|
3276
|
+
}
|
|
3277
|
+
// 拉取/推送做完都把客户端拉回来(用户要求"完成后自动启动 dsh"),仍受 autoRestart 开关约束
|
|
3278
|
+
const restart = body.restart !== false && settings.autoRestart !== false
|
|
3279
|
+
const started = await spawnWatcher({ mode, repo, appRoot, dshHome, restart })
|
|
3280
|
+
if (!started.ok) throw new Error(started.error)
|
|
3281
|
+
autoState.pending = { mode, at: Date.now(), restart, watcherPid: started.pid, closeRequested: false }
|
|
3282
|
+
// 用户明确要求"现在就同步":排队后请求客户端退出(不带 /F,走正常关闭,配置能存下来)
|
|
3283
|
+
let closed = false
|
|
3284
|
+
if (body.closeNow !== false) {
|
|
3285
|
+
closed = closeDsh()
|
|
3286
|
+
autoState.pending.closeRequested = closed
|
|
3287
|
+
}
|
|
3288
|
+
sendJson(res, 200, { ok: true, action, pending: autoState.pending, closeRequested: closed })
|
|
3289
|
+
return
|
|
3290
|
+
}
|
|
3291
|
+
|
|
3292
|
+
throw new Error(t('action 只能是 check / pull-now / push-now / restore-preview / restore-now / cancel', 'action must be check / pull-now / push-now / restore-preview / restore-now / cancel'))
|
|
3293
|
+
} catch (error) {
|
|
3294
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
3295
|
+
}
|
|
3296
|
+
}
|
|
3297
|
+
|
|
3298
|
+
/** 启动后的自动检查:延迟跑,避免和客户端自身的启动流程抢 IO;失败只记进状态,不打扰用户。 */
|
|
3299
|
+
function scheduleAutoStart(config) {
|
|
3300
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3301
|
+
const settings = readSettings(dshHome)
|
|
3302
|
+
if (!settings.autoPull && !settings.autoPush) return
|
|
3303
|
+
if (autoState.timer) return
|
|
3304
|
+
const run = async () => {
|
|
3305
|
+
try {
|
|
3306
|
+
// 已经排队等退出了就别重复拉起 watcher:第二遍 fetch/stat 纯属浪费
|
|
3307
|
+
if (autoState.pending) return
|
|
3308
|
+
const repo = resolveRepo(config?.repoPath, dshHome).repo || ''
|
|
3309
|
+
if (!repo || !isDir(join(repo, '.git'))) {
|
|
3310
|
+
// 空目录是「等首次拉取」的正常状态:不记错误,免得面板的云端徽标把它当成 fetch 失败
|
|
3311
|
+
autoState.lastCheckError = (repo && repoPhase(repo) === 'empty')
|
|
3312
|
+
? ''
|
|
3313
|
+
: t('仓库还没就位,跳过本次自动检查', 'The repo is not in place yet — skipping this auto check')
|
|
3314
|
+
autoState.lastCheckAt = Date.now()
|
|
3315
|
+
return
|
|
3316
|
+
}
|
|
3317
|
+
autoState.checking = true
|
|
3318
|
+
const drift = await checkDrift(repo)
|
|
3319
|
+
autoState.checking = false
|
|
3320
|
+
autoState.lastCheckAt = Date.now()
|
|
3321
|
+
if (!drift) {
|
|
3322
|
+
autoState.lastCheckError = t('读不到远端(fetch 失败或没有 origin)', 'Cannot read the remote (fetch failed or there is no origin)')
|
|
3323
|
+
return
|
|
3324
|
+
}
|
|
3325
|
+
autoState.drift = drift
|
|
3326
|
+
const appRoot = resolveAppRoot(config?.appRoot) || ''
|
|
3327
|
+
|
|
3328
|
+
if (settings.autoPull && drift.behind > 0) {
|
|
3329
|
+
const yes = await askConfirm(
|
|
3330
|
+
t('云端有更新,要同步到本机吗?', 'The cloud has new commits — sync them to this machine?'),
|
|
3331
|
+
t(
|
|
3332
|
+
`云端比本机多 ${drift.behind} 个提交。\n`
|
|
3333
|
+
+ '同步需要先完全退出 DSH:确认后客户端会自动关闭,拉取完成后按设置自动重新打开。\n'
|
|
3334
|
+
+ `(本机领先 ${drift.ahead} 个提交,拉取不会动它们)`,
|
|
3335
|
+
`The cloud is ${drift.behind} commit(s) ahead of this machine.\n`
|
|
3336
|
+
+ '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'
|
|
3337
|
+
+ `(This machine is ${drift.ahead} commit(s) ahead — pulling leaves those alone.)`,
|
|
3338
|
+
),
|
|
3339
|
+
)
|
|
3340
|
+
if (yes) {
|
|
3341
|
+
const started = await spawnWatcher({ mode: 'pull', repo, appRoot, dshHome, restart: settings.autoRestart })
|
|
3342
|
+
if (started.ok) {
|
|
3343
|
+
autoState.pending = { mode: 'pull', at: Date.now(), restart: settings.autoRestart, watcherPid: started.pid, closeRequested: true }
|
|
3344
|
+
closeDsh()
|
|
3345
|
+
} else {
|
|
3346
|
+
autoState.lastCheckError = started.error
|
|
3347
|
+
}
|
|
3348
|
+
} else {
|
|
3349
|
+
autoState.pending = null
|
|
3350
|
+
}
|
|
3351
|
+
return
|
|
3352
|
+
}
|
|
3353
|
+
|
|
3354
|
+
if (settings.autoPush) {
|
|
3355
|
+
// 该不该推,三个来源都算:本地领先的提交、未提交的改动、以及"本机资料比上次同步新"
|
|
3356
|
+
// (新会话还没 capture 时仓库是干净的,只看 ahead 会把最该推的那种改动漏掉 —— 真实踩过)
|
|
3357
|
+
let dirty = 0
|
|
3358
|
+
const raw = await git(repo, ['status', '--porcelain'])
|
|
3359
|
+
if (raw) dirty = raw.split('\n').filter((l) => l.trim()).length
|
|
3360
|
+
const syncState = readSyncState(dshHome)
|
|
3361
|
+
const lp = localPending(dshHome, syncState.lastSyncAt, config?.profileName, { repo, appRoot })
|
|
3362
|
+
// 后台调度里拿不到请求语言,所以中英各存一份,由客户端按自己的语言挑
|
|
3363
|
+
const reasonZh = drift.ahead > 0 ? `领先 ${drift.ahead} 个提交`
|
|
3364
|
+
: dirty > 0 ? `未提交 ${dirty} 项`
|
|
3365
|
+
: (lp.known && lp.pending > 0) ? `本机 ${lp.pending} 个文件比上次同步新` : ''
|
|
3366
|
+
const reasonEn = drift.ahead > 0 ? `${drift.ahead} commit(s) ahead`
|
|
3367
|
+
: dirty > 0 ? `${dirty} uncommitted change(s)`
|
|
3368
|
+
: (lp.known && lp.pending > 0) ? `${lp.pending} file(s) newer than the last sync` : ''
|
|
3369
|
+
if (reasonZh) {
|
|
3370
|
+
// 自动推送不需要确认(用户已开开关),排队等退出即可;推完把客户端拉回来
|
|
3371
|
+
const restart = settings.autoRestart !== false
|
|
3372
|
+
const started = await spawnWatcher({ mode: 'push', repo, appRoot, dshHome, restart })
|
|
3373
|
+
if (started.ok) {
|
|
3374
|
+
autoState.pending = { mode: 'push', at: Date.now(), reason: reasonZh, reasonZh, reasonEn, restart, watcherPid: started.pid, closeRequested: false }
|
|
3375
|
+
} else {
|
|
3376
|
+
autoState.lastCheckError = started.error
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
3379
|
+
}
|
|
3380
|
+
} catch (error) {
|
|
3381
|
+
autoState.checking = false
|
|
3382
|
+
autoState.lastCheckAt = Date.now()
|
|
3383
|
+
autoState.lastCheckError = String((error && error.message) || error)
|
|
3384
|
+
}
|
|
3385
|
+
}
|
|
3386
|
+
// 首检别拖太久:用户可能开起来看一眼就关窗口,20 秒会让他这次关闭什么都没推。
|
|
3387
|
+
autoState.timer = setTimeout(run, 8 * 1000)
|
|
3388
|
+
try { autoState.timer.unref?.() } catch { }
|
|
3389
|
+
// 之后每 2 分钟复查一次:会话/资料是运行中才产生的,只在启动判一次会把它们全漏掉。
|
|
3390
|
+
// 命中就排一次队,watcher 已在等进程退出,退出即执行;已排队时 run 会直接返回。
|
|
3391
|
+
try {
|
|
3392
|
+
autoState.interval = setInterval(run, 2 * 60 * 1000)
|
|
3393
|
+
autoState.interval.unref?.()
|
|
3394
|
+
} catch { }
|
|
3395
|
+
}
|
|
3396
|
+
|
|
3397
|
+
async function handlePrepare(req, res, config) {
|
|
3398
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
3399
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3400
|
+
try {
|
|
3401
|
+
const raw = await readBody(req)
|
|
3402
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
3403
|
+
const action = String(body.action || '')
|
|
3404
|
+
if (!ACTIONS.includes(action)) throw new Error(t(`action 只能是 ${ACTIONS.join(' / ')}`, `action must be one of ${ACTIONS.join(' / ')}`))
|
|
3405
|
+
const message = typeof body.message === 'string' ? body.message : ''
|
|
3406
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3407
|
+
const resolved = resolveRepo(config?.repoPath, dshHome)
|
|
3408
|
+
const repo = resolved.repo
|
|
3409
|
+
// 仓库还没克隆(新机器只装了插件)也允许生成:脚本会用插件自带的 runtime\,首次拉取由 sync.ps1 现场 clone。
|
|
3410
|
+
// 只有「压根没配过路径」才拦。
|
|
3411
|
+
if (!repo) {
|
|
3412
|
+
throw new Error(t(
|
|
3413
|
+
'还没有配置仓库目录:请先在面板「本机仓库」卡里点「设置路径」,指到一个目录(本地还没有仓库时,首次拉取会自动从云端克隆)',
|
|
3414
|
+
'The repo directory is not configured: set the path in the Local repo card first (if the repo is not local yet, the first pull clones it from the cloud automatically)',
|
|
3415
|
+
))
|
|
3416
|
+
}
|
|
3417
|
+
const repoReady = isRepoDir(repo)
|
|
3418
|
+
const phase = repoPhase(repo)
|
|
3419
|
+
// 本机还没内容时,先问一次云端:云端也空 = 只能「初始化推送」,云端有内容 = 只能拉取。
|
|
3420
|
+
// 一次请求算清楚,下面 push 门禁、all 的脚本组合、bootstrap 说明都用这同一个答案。
|
|
3421
|
+
// 判据是「云端分支树里有没有文件」——远端只剩空分支时也算空仓库(历史被删空就是这个样子)。
|
|
3422
|
+
const probeSettings = readSettings(dshHome)
|
|
3423
|
+
let remoteFilesForPrepare = null
|
|
3424
|
+
let remoteHeadsForPrepare = null
|
|
3425
|
+
if (phase !== 'ok') {
|
|
3426
|
+
const probeUrl = (await git(repo, ['remote', 'get-url', 'origin'])) || probeSettings.remoteUrl || ''
|
|
3427
|
+
const probe = await probeRemote(probeUrl, probeSettings)
|
|
3428
|
+
remoteFilesForPrepare = probe ? probe.files : null
|
|
3429
|
+
remoteHeadsForPrepare = probe ? probe.heads : null
|
|
3430
|
+
}
|
|
3431
|
+
// 空白文件夹(或还没建)代表「本机还没有仓库内容」:能不能推,取决于云端有没有内容 ——
|
|
3432
|
+
// 云端也空 → 允许,这次推送就是「初始化推送」(sync.ps1 会 git init + 写骨架 + capture + 提交 + 推)
|
|
3433
|
+
// 云端有内容 → 拒绝,先拉取(硬推会把本机状态写进一份正在使用的历史)
|
|
3434
|
+
if (action === 'push' && phase !== 'ok') {
|
|
3435
|
+
if (remoteFilesForPrepare === null) {
|
|
3436
|
+
throw new Error(t(
|
|
3437
|
+
`连不上云端仓库(${probeSettings.remoteUrl || '还没配地址'}):初始化推送要先确认云端是空仓库,请先确认地址与网络`,
|
|
3438
|
+
`Cannot reach the cloud repo (${probeSettings.remoteUrl || 'no URL configured'}): initialize push needs to confirm the cloud repo is empty — check the URL and network.`,
|
|
3439
|
+
))
|
|
3440
|
+
}
|
|
3441
|
+
if (remoteFilesForPrepare > 0) {
|
|
3442
|
+
throw new Error(t(
|
|
3443
|
+
`云端仓库已经有内容(${remoteFilesForPrepare} 个文件):本机还是空的,先执行「拉取」把内容拉下来,之后才能推送`,
|
|
3444
|
+
`The cloud repo already has content (${remoteFilesForPrepare} file(s)): run Pull first to bring it down, then push.`,
|
|
3445
|
+
))
|
|
3446
|
+
}
|
|
3447
|
+
}
|
|
3448
|
+
// 反过来:云端也空的时候不许生成拉取脚本 —— 拉下来只会得到一个空目录 + .git,
|
|
3449
|
+
// 面板状态原地不动,人以为「同步过了」,实际什么都没下来。两边都空只走「推送(初始化)」。
|
|
3450
|
+
if (action === 'pull' && phase !== 'ok') {
|
|
3451
|
+
if (remoteFilesForPrepare === null) {
|
|
3452
|
+
throw new Error(t(
|
|
3453
|
+
'连不上云端仓库(' + (probeSettings.remoteUrl || '还没配地址') + '):先确认地址与网络,再生成拉取脚本',
|
|
3454
|
+
'Cannot reach the cloud repo (' + (probeSettings.remoteUrl || 'no URL configured') + '): check the URL and network before generating the pull script.',
|
|
3455
|
+
))
|
|
3456
|
+
}
|
|
3457
|
+
if (remoteFilesForPrepare === 0) {
|
|
3458
|
+
throw new Error(t(
|
|
3459
|
+
'云端仓库里一个文件都没有,没有内容可拉:本机和云端都空时请用「推送」(那次就是初始化推送)',
|
|
3460
|
+
'The cloud repo has no file at all, so there is nothing to pull: when both sides are empty, use Push (that run initializes the repo).',
|
|
3461
|
+
))
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
// 推送 / 拉取都以「云端仓库地址」为前置;还原(最新快照或指定快照)只动本机快照,不需要远端。
|
|
3465
|
+
if (action !== 'restore' && action !== 'restore-backup') {
|
|
3466
|
+
const origin = isDir(join(repo, '.git')) ? await git(repo, ['remote', 'get-url', 'origin']) : null
|
|
3467
|
+
const remoteUrl = origin || readSettings(dshHome).remoteUrl
|
|
3468
|
+
if (!remoteUrl) {
|
|
3469
|
+
throw new Error(t(
|
|
3470
|
+
'还没有配置云端仓库地址:请先在面板「云端仓库」卡里填好远端地址并保存,再生成推送/拉取脚本',
|
|
3471
|
+
'The cloud repo is not configured: fill in the remote URL in the Cloud repo card and save before generating push/pull scripts',
|
|
3472
|
+
))
|
|
3473
|
+
}
|
|
3474
|
+
}
|
|
3475
|
+
const appRoot = resolveAppRoot(config?.appRoot)
|
|
3476
|
+
// 定位不到客户端根就不许生成脚本:-AppRoot 错了会把插件部署进仓库、{{APP_ROOT}} 也全展开错位。
|
|
3477
|
+
if (!appRoot) {
|
|
3478
|
+
throw new Error(t(
|
|
3479
|
+
'定位不到客户端根目录(要能找到 resources\\app\\package.json 或 resources\\app.asar):'
|
|
3480
|
+
+ '请确认插件装在 <客户端根> 下(例如 D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.57),或在设置里填客户端根 appRoot',
|
|
3481
|
+
'Cannot locate the client root (needs resources\\app\\package.json or resources\\app.asar): '
|
|
3482
|
+
+ 'make sure the plugin is installed under <client root> (e.g. D:\\DeepSeekHarness\\dsh-config-sync-plugin-0.3.57), or set appRoot in the settings',
|
|
3483
|
+
))
|
|
3484
|
+
}
|
|
3485
|
+
const state = {...await repoState(repo), message}
|
|
3486
|
+
// 「还原备份」点某一行:备份目录必须是备份根之下真实存在的一份快照 ——
|
|
3487
|
+
// 面板传来的路径直接拼进 cmd,所以这里既校验存在,也校验不含引号/换行,避免生成出跑不起来的脚本。
|
|
3488
|
+
let backupDir = ''
|
|
3489
|
+
let snapshotKind = ''
|
|
3490
|
+
if (action === 'restore-backup') {
|
|
3491
|
+
// 与 restore-now 共用同一套校验:存在、在备份根之下、能认出类型(profile / plugin / session)
|
|
3492
|
+
const snap = resolveSnapshotDir(dshHome, body.backupDir)
|
|
3493
|
+
backupDir = snap.dir
|
|
3494
|
+
snapshotKind = snap.kind
|
|
3495
|
+
}
|
|
3496
|
+
const stateWithBackup = { ...state, backupDir, snapshotKind }
|
|
3497
|
+
// 「云端确实没有文件」——包括远端只剩空分支(历史被删空的现场)→ 都算可以初始化推送
|
|
3498
|
+
const cloudEmptyForPrepare = remoteFilesForPrepare === 0
|
|
3499
|
+
const bootstrap = repoReady ? null : {
|
|
3500
|
+
repo,
|
|
3501
|
+
initPush: phase !== 'ok' && cloudEmptyForPrepare,
|
|
3502
|
+
note: t(
|
|
3503
|
+
cloudEmptyForPrepare
|
|
3504
|
+
? '本机仓库和云端仓库都还是空的:点「推送」即「初始化推送」——会 git init、写出仓库骨架(apply/capture/sync 等执行体与版本契约)并把本机配置作为初始内容提交推送'
|
|
3505
|
+
: (phase === 'empty'
|
|
3506
|
+
? '本机仓库是空目录:点「拉取」会用插件自带的 runtime 从云端把仓库内容拉到这个路径(拉完就能正常推送/拉取)'
|
|
3507
|
+
: '本机还没有这个仓库(或还没克隆):生成的三份脚本先用插件自带的 runtime,第一次执行拉取会自动从云端克隆到该目录'),
|
|
3508
|
+
cloudEmptyForPrepare
|
|
3509
|
+
? 'Both the local repo and the cloud are empty: Push becomes Initialize push — it runs git init, writes the repo skeleton (apply/capture/sync bodies plus the version contract) and commits this machine\'s config as the initial content.'
|
|
3510
|
+
: (phase === 'empty'
|
|
3511
|
+
? 'The local repo folder is empty: Pull uses the bundled runtime to fetch the repo from the cloud into that path (after that, push/pull work normally).'
|
|
3512
|
+
: 'This repo is not on this machine yet (or not cloned): the scripts use the plugin\'s bundled runtime, and the first pull clones it from the cloud into that directory.'),
|
|
3513
|
+
),
|
|
3514
|
+
}
|
|
3515
|
+
if (action === 'all') {
|
|
3516
|
+
// 脚本怎么组合,跟门禁同一套口径:真仓库全给;两边都空只给「推送(初始化)+ 还原」;
|
|
3517
|
+
// 本机空云端有内容只给「拉取 + 还原」。面板上的「一键生成」按同一份规则显示按钮文案。
|
|
3518
|
+
const wanted = phase === 'ok' ? ['push', 'pull', 'restore']
|
|
3519
|
+
: (cloudEmptyForPrepare ? ['push', 'restore'] : ['pull', 'restore'])
|
|
3520
|
+
const skipped = phase === 'ok' ? [] : (cloudEmptyForPrepare ? ['pull'] : ['push'])
|
|
3521
|
+
const built = wanted.map((a) => buildCmd(config, a, repo, appRoot, dshHome, state))
|
|
3522
|
+
sendJson(res, 200, { ok: true, action, built, bootstrap, skipped })
|
|
3523
|
+
return
|
|
3524
|
+
}
|
|
3525
|
+
const built = buildCmd(config, action, repo, appRoot, dshHome, stateWithBackup)
|
|
3526
|
+
sendJson(res, 200, { ok: true, action, ...built, bootstrap })
|
|
3527
|
+
} catch (error) {
|
|
3528
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
3529
|
+
}
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
/**
|
|
3533
|
+
* 跨机路径根:仓库里的配置存的是 {{APP_ROOT}} / {{DSH_HOME}} / {{WORKSPACE_HOME}} / {{ROOT:<key>}},
|
|
3534
|
+
* 换一台机器落地时,这几个根都不一样。所以每台机器在这里确认一次自己的根,记进
|
|
3535
|
+
* <dshHome>\config-sync-roots.json(本机私有,不进仓库),apply 再按这份值展开。
|
|
3536
|
+
* 确认过的不再问:文件里有值就直接用,面板只在缺值时列出来。
|
|
3537
|
+
*/
|
|
3538
|
+
function rootsPathOf(dshHome) { return join(dshHome, 'config-sync-roots.json') }
|
|
3539
|
+
function pendingPathOf(dshHome) { return join(dshHome, 'config-sync-pending-paths.json') }
|
|
3540
|
+
function absolutePathsPathOf(dshHome) { return join(dshHome, 'config-sync-absolute-paths.json') }
|
|
3541
|
+
function overwritePathOf(dshHome) { return join(dshHome, 'config-sync-overwrite.json') }
|
|
3542
|
+
|
|
3543
|
+
/**
|
|
3544
|
+
* 本机机器名:和 capture.ps1 写报告时用的 $env:COMPUTERNAME 对得上。
|
|
3545
|
+
* 报告里带着 machine,面板据此判断「这份配置是别的机器写的」——只有那种情况才该提示跨机路径。
|
|
3546
|
+
*/
|
|
3547
|
+
function localMachineName() {
|
|
3548
|
+
try { return String(hostname() || '') } catch { return '' }
|
|
3549
|
+
}
|
|
3550
|
+
function sameMachine(a, b) {
|
|
3551
|
+
const x = String(a || '').trim().toLowerCase()
|
|
3552
|
+
const y = String(b || '').trim().toLowerCase()
|
|
3553
|
+
return Boolean(x) && Boolean(y) && x === y
|
|
3554
|
+
}
|
|
3555
|
+
|
|
3556
|
+
/** 路径比较用:统一斜杠、折叠重复斜杠、去尾斜杠、转小写(Windows 不区分大小写) */
|
|
3557
|
+
function pathKeyOf(p) {
|
|
3558
|
+
return String(p == null ? '' : p).replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '').toLowerCase()
|
|
3559
|
+
}
|
|
3560
|
+
|
|
3561
|
+
/**
|
|
3562
|
+
* 给仓库里一条根外绝对路径,算「这台机器上应该在哪个目录」。
|
|
3563
|
+
* 两种依据,从准到糙:
|
|
3564
|
+
* 1) root —— 报告里记着对方那台机器的根值,前缀命中就换成本机的同名根(精确映射)
|
|
3565
|
+
* 2) namesake —— 没有根可换,就按最后一级目录名在本机常见位置找同名目录(启发式)
|
|
3566
|
+
* 都不中就返回 kind='none',面板只说「本机没有等价目录」,不乱指地方。
|
|
3567
|
+
*/
|
|
3568
|
+
function suggestLocalPathFor(remotePath, report, ctx) {
|
|
3569
|
+
const rp = String(remotePath || '')
|
|
3570
|
+
if (!rp) return { path: '', kind: 'none', note: '', remoteRoot: '', rest: '' }
|
|
3571
|
+
// 分段保留原大小写(Windows 路径不敏感,但推荐结果要写成 D:\DSH\SquadLink 这种原样,
|
|
3572
|
+
// 不能因为比较时转小写就把 SquadLink 推荐成 squadlink)
|
|
3573
|
+
const segOrig = rp.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/\/$/, '').split('/').filter(Boolean)
|
|
3574
|
+
const remoteRoots = (report && report.roots && typeof report.roots === 'object') ? report.roots : {}
|
|
3575
|
+
const pairs = []
|
|
3576
|
+
const addPair = (remoteValue, localValue) => {
|
|
3577
|
+
const rk = pathKeyOf(remoteValue)
|
|
3578
|
+
if (rk && localValue) pairs.push({ rk: rk.split('/').filter(Boolean), local: String(localValue) })
|
|
3579
|
+
}
|
|
3580
|
+
addPair(remoteRoots.appRoot, ctx.appRoot)
|
|
3581
|
+
addPair(remoteRoots.dshHome, ctx.dshHome)
|
|
3582
|
+
addPair(remoteRoots.workspaceHome, ctx.workspaceHome)
|
|
3583
|
+
const remoteCustom = (remoteRoots.custom && typeof remoteRoots.custom === 'object') ? remoteRoots.custom : {}
|
|
3584
|
+
for (const [k, v] of Object.entries(remoteCustom)) addPair(v, (ctx.custom || {})[k] || '')
|
|
3585
|
+
// 最长前缀优先:工作区根比客户端安装目录更具体
|
|
3586
|
+
pairs.sort((a, b) => b.rk.length - a.rk.length)
|
|
3587
|
+
for (const pair of pairs) {
|
|
3588
|
+
if (pair.rk.length > segOrig.length) continue
|
|
3589
|
+
if (!pair.rk.every((seg, i) => seg === segOrig[i].toLowerCase())) continue
|
|
3590
|
+
const rest = segOrig.slice(pair.rk.length)
|
|
3591
|
+
const target = rest.length ? join(pair.local, ...rest) : pair.local
|
|
3592
|
+
return {
|
|
3593
|
+
path: target,
|
|
3594
|
+
kind: 'root',
|
|
3595
|
+
remoteRoot: segOrig.slice(0, pair.rk.length).join('/'),
|
|
3596
|
+
rest: rest.join('/'),
|
|
3597
|
+
note: t('按对方机器的根映射到本机同名根', 'mapped onto this machine\'s same root'),
|
|
3598
|
+
}
|
|
3599
|
+
}
|
|
3600
|
+
const leaf = segOrig[segOrig.length - 1] || ''
|
|
3601
|
+
if (leaf && /^[A-Za-z0-9._-]+$/.test(leaf) && leaf.includes('.')) {
|
|
3602
|
+
// 最后一段是文件名,不算目录名,不猜
|
|
3603
|
+
return { path: '', kind: 'none', note: '', remoteRoot: '', rest: '', leaf }
|
|
3604
|
+
}
|
|
3605
|
+
if (leaf) {
|
|
3606
|
+
for (const base of (ctx.candidates || [])) {
|
|
3607
|
+
if (!base) continue
|
|
3608
|
+
const cand = join(base, leaf)
|
|
3609
|
+
try { if (existsSync(cand)) return { path: cand, kind: 'namesake', leaf, note: t('本机有同名目录', 'a same-named folder exists here'), remoteRoot: '', rest: '' } } catch { }
|
|
3610
|
+
}
|
|
3611
|
+
}
|
|
3612
|
+
return { path: '', kind: 'none', note: '', remoteRoot: '', rest: '', leaf }
|
|
3613
|
+
}
|
|
3614
|
+
|
|
3615
|
+
/** 猜同名目录时本机该去哪儿找:本机的几个根、用户主目录、桌面、各固定盘根、已确认的自选目录 */
|
|
3616
|
+
function candidateParentDirs(localRoots) {
|
|
3617
|
+
const out = []
|
|
3618
|
+
const push = (p) => {
|
|
3619
|
+
const s = String(p == null ? '' : p).trim()
|
|
3620
|
+
if (s && !out.some((x) => pathKeyOf(x) === pathKeyOf(s))) out.push(s)
|
|
3621
|
+
}
|
|
3622
|
+
const r = localRoots || {}
|
|
3623
|
+
push(r.appRoot)
|
|
3624
|
+
push(r.workspaceHome)
|
|
3625
|
+
try { push(homedir()) } catch { }
|
|
3626
|
+
try { push(join(homedir(), 'Desktop')) } catch { }
|
|
3627
|
+
for (const letter of ['C', 'D', 'E', 'F', 'G']) {
|
|
3628
|
+
const root = `${letter}:\\`
|
|
3629
|
+
try { if (existsSync(root)) push(root) } catch { }
|
|
3630
|
+
}
|
|
3631
|
+
for (const v of Object.values(r.custom || {})) push(v)
|
|
3632
|
+
return out
|
|
3633
|
+
}
|
|
3634
|
+
|
|
3635
|
+
|
|
3636
|
+
/** 工作区根:本机工作区一般建在同一层,取登记表里出现最多的那个父目录 */
|
|
3637
|
+
function guessWorkspaceHome(dshHome) {
|
|
3638
|
+
const list = workspaceRoots(dshHome)
|
|
3639
|
+
if (!list.length) return ''
|
|
3640
|
+
const parents = list.map((p) => dirname(String(p).replace(/[\\/]+$/, ''))).filter(Boolean)
|
|
3641
|
+
let best = ''
|
|
3642
|
+
let bestCount = 0
|
|
3643
|
+
for (const p of parents) {
|
|
3644
|
+
let c = 0
|
|
3645
|
+
for (const q of parents) { if (q.toLowerCase() === p.toLowerCase()) c += 1 }
|
|
3646
|
+
if (c > bestCount) { bestCount = c; best = p }
|
|
3647
|
+
}
|
|
3648
|
+
return best
|
|
3649
|
+
}
|
|
3650
|
+
|
|
3651
|
+
function tokenHint(token) {
|
|
3652
|
+
const key = String(token || '')
|
|
3653
|
+
if (key === '{{APP_ROOT}}') return t('客户端安装目录(DeepSeekHarness 所在的那个目录)', 'Client install root (the folder that contains DeepSeekHarness)')
|
|
3654
|
+
if (key === '{{DSH_HOME}}') return t('.dsh 配置目录(一般是 %USERPROFILE%\\.dsh)', '.dsh folder (usually %USERPROFILE%\\.dsh)')
|
|
3655
|
+
if (key === '{{WORKSPACE_HOME}}') return t('工作区根目录(本机工作区都建在它下面)', 'Workspace root (all workspaces live under it)')
|
|
3656
|
+
const name = key.replace(/^\{\{ROOT:/, '').replace(/\}\}$/, '')
|
|
3657
|
+
return t(`自选目录:${name} —— 这台机器上对应的路径由你来定`, `Custom folder "${name}" — pick the matching path on this machine`)
|
|
3658
|
+
}
|
|
3659
|
+
|
|
3660
|
+
async function handleRoots(req, res, config) {
|
|
3661
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
3662
|
+
if (req.method === 'GET') {
|
|
3663
|
+
try {
|
|
3664
|
+
const saved = readJson(rootsPathOf(dshHome)) || {}
|
|
3665
|
+
const detected = {
|
|
3666
|
+
appRoot: resolveAppRoot(config?.appRoot) || '',
|
|
3667
|
+
dshHome,
|
|
3668
|
+
workspaceHome: guessWorkspaceHome(dshHome),
|
|
3669
|
+
}
|
|
3670
|
+
const pending = readJson(pendingPathOf(dshHome)) || {}
|
|
3671
|
+
const missing = Array.isArray(pending.missing) ? pending.missing : []
|
|
3672
|
+
// 两份体检报告(0.3.36 起):推送时扫出的「根外绝对路径」、拉取时扫出的「被覆盖的本机配置」
|
|
3673
|
+
const absReport = readJson(absolutePathsPathOf(dshHome)) || {}
|
|
3674
|
+
const absItems = Array.isArray(absReport.items) ? absReport.items : []
|
|
3675
|
+
const ovReport = readJson(overwritePathOf(dshHome)) || {}
|
|
3676
|
+
const ovItems = Array.isArray(ovReport.items) ? ovReport.items : []
|
|
3677
|
+
// 本机这几个根:推荐路径就是拿它们跟报告里「对方机器的根」对出来的
|
|
3678
|
+
const localRoots = {
|
|
3679
|
+
appRoot: saved.appRoot || detected.appRoot,
|
|
3680
|
+
dshHome: saved.dshHome || detected.dshHome,
|
|
3681
|
+
workspaceHome: saved.workspaceHome || detected.workspaceHome,
|
|
3682
|
+
custom: (() => {
|
|
3683
|
+
// 用户主目录能自动探测,不用问人:工作区建在 Documents\deepseek-harness 下时靠它展开
|
|
3684
|
+
const c = saved.custom && typeof saved.custom === 'object' ? { ...saved.custom } : {}
|
|
3685
|
+
let home = ''
|
|
3686
|
+
try { home = homedir() } catch { }
|
|
3687
|
+
if (home && !c.userHome) c.userHome = home
|
|
3688
|
+
return c
|
|
3689
|
+
})(),
|
|
3690
|
+
}
|
|
3691
|
+
sendJson(res, 200, {
|
|
3692
|
+
ok: true,
|
|
3693
|
+
roots: localRoots,
|
|
3694
|
+
confirmed: Array.isArray(saved.confirmed) ? saved.confirmed : [],
|
|
3695
|
+
updatedAt: saved.updatedAt || '',
|
|
3696
|
+
detected,
|
|
3697
|
+
missing: missing.map((m) => ({
|
|
3698
|
+
token: String(m.token || ''),
|
|
3699
|
+
file: String(m.file || ''),
|
|
3700
|
+
label: String(m.label || ''),
|
|
3701
|
+
hint: String(m.hint || tokenHint(m.token)),
|
|
3702
|
+
})),
|
|
3703
|
+
// 根外绝对路径:只有「这份配置是另一台机器写的」才是问题——本机推出去的路径在本机当然存在,
|
|
3704
|
+
// 那条清单在本机显示只会误导(0.3.43 起按 machine 判断,并逐条给本机推荐目录)
|
|
3705
|
+
absolutePaths: (() => {
|
|
3706
|
+
const machine = String(absReport.machine || '')
|
|
3707
|
+
const localMachine = localMachineName()
|
|
3708
|
+
const fromOtherMachine = Boolean(machine) && Boolean(localMachine) && !sameMachine(machine, localMachine)
|
|
3709
|
+
const candidates = candidateParentDirs(localRoots)
|
|
3710
|
+
const adoptedKeys = new Set(Object.values(localRoots.custom || {}).map(pathKeyOf))
|
|
3711
|
+
const items = absItems.slice(0, 30).map((it) => {
|
|
3712
|
+
const remotePath = String(it.path || '')
|
|
3713
|
+
const sug = suggestLocalPathFor(remotePath, absReport, { ...localRoots, candidates })
|
|
3714
|
+
const suggestPath = sug.kind === 'none' ? '' : sug.path
|
|
3715
|
+
return {
|
|
3716
|
+
file: String(it.file || ''),
|
|
3717
|
+
path: remotePath,
|
|
3718
|
+
// config = 配置文件里的路径;data = 工作区/会话记录里的路径(决定工作区开在哪个目录、会话回到哪个目录)
|
|
3719
|
+
scope: String(it.scope || 'config'),
|
|
3720
|
+
suggest: suggestPath,
|
|
3721
|
+
suggestKind: sug.kind,
|
|
3722
|
+
suggestNote: sug.note || '',
|
|
3723
|
+
// 采纳时用的自选目录 key:目录名去扩展名;取不到就 dir
|
|
3724
|
+
suggestKey: String(sug.leaf || (sug.rest || '').split('/').filter(Boolean).pop() || 'dir').replace(/\.[A-Za-z0-9]{1,8}$/, '').replace(/[^A-Za-z0-9_.-]/g, '') || 'dir',
|
|
3725
|
+
adopted: Boolean(suggestPath) && adoptedKeys.has(pathKeyOf(suggestPath)),
|
|
3726
|
+
remoteRoot: sug.remoteRoot || '',
|
|
3727
|
+
rest: sug.rest || '',
|
|
3728
|
+
}
|
|
3729
|
+
})
|
|
3730
|
+
return {
|
|
3731
|
+
at: String(absReport.at || ''),
|
|
3732
|
+
machine,
|
|
3733
|
+
localMachine,
|
|
3734
|
+
fromOtherMachine,
|
|
3735
|
+
total: absItems.length,
|
|
3736
|
+
items,
|
|
3737
|
+
suggested: items.filter((x) => x.suggest).length,
|
|
3738
|
+
adoptedCount: items.filter((x) => x.adopted).length,
|
|
3739
|
+
}
|
|
3740
|
+
})(),
|
|
3741
|
+
// 上次拉取覆盖了哪些本机配置(含备份路径):本机有未推送改动时会出现
|
|
3742
|
+
overwrite: {
|
|
3743
|
+
at: String(ovReport.at || ''),
|
|
3744
|
+
total: ovItems.length,
|
|
3745
|
+
items: ovItems.slice(0, 20).map((it) => ({
|
|
3746
|
+
repo: String(it.repo || ''), label: String(it.label || ''), src: String(it.src || ''), backup: String(it.backup || ''),
|
|
3747
|
+
})),
|
|
3748
|
+
},
|
|
3749
|
+
file: rootsPathOf(dshHome),
|
|
3750
|
+
})
|
|
3751
|
+
} catch (error) {
|
|
3752
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
3753
|
+
}
|
|
3754
|
+
return
|
|
3755
|
+
}
|
|
3756
|
+
if (req.method !== 'POST') { sendJson(res, 405, { ok: false, error: 'POST only' }); return }
|
|
3757
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
3758
|
+
try {
|
|
3759
|
+
const raw = await readBody(req)
|
|
3760
|
+
const body = raw.trim() ? JSON.parse(raw) : {}
|
|
3761
|
+
const input = body.roots && typeof body.roots === 'object' ? body.roots : {}
|
|
3762
|
+
const prev = readJson(rootsPathOf(dshHome)) || {}
|
|
3763
|
+
const pick = (key, fallback) => {
|
|
3764
|
+
const v = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : prev[key]
|
|
3765
|
+
return String(v == null ? '' : v).trim() || String(fallback || '').trim()
|
|
3766
|
+
}
|
|
3767
|
+
const next = {
|
|
3768
|
+
version: 1,
|
|
3769
|
+
appRoot: pick('appRoot', resolveAppRoot(config?.appRoot) || ''),
|
|
3770
|
+
dshHome: pick('dshHome', dshHome),
|
|
3771
|
+
workspaceHome: pick('workspaceHome', guessWorkspaceHome(dshHome)),
|
|
3772
|
+
custom: {},
|
|
3773
|
+
confirmed: [],
|
|
3774
|
+
updatedAt: new Date().toISOString(),
|
|
3775
|
+
}
|
|
3776
|
+
const rawCustom = input.custom && typeof input.custom === 'object' ? input.custom : (prev.custom || {})
|
|
3777
|
+
for (const [k, v] of Object.entries(rawCustom)) {
|
|
3778
|
+
const key = String(k || '').trim()
|
|
3779
|
+
const val = String(v == null ? '' : v).trim()
|
|
3780
|
+
if (key && val) next.custom[key] = val
|
|
3781
|
+
}
|
|
3782
|
+
// 校验:三个根都不能空、必须是绝对路径。目录不存在只提示不拒 —— 新机器上目标目录常常还没建。
|
|
3783
|
+
const warns = []
|
|
3784
|
+
for (const key of ['appRoot', 'dshHome', 'workspaceHome']) {
|
|
3785
|
+
if (!next[key]) {
|
|
3786
|
+
throw new Error(t(
|
|
3787
|
+
`本机路径不能为空:${key}`,
|
|
3788
|
+
`A local path cannot be empty: ${key}`,
|
|
3789
|
+
))
|
|
3790
|
+
}
|
|
3791
|
+
if (!isAbsolute(next[key])) {
|
|
3792
|
+
throw new Error(t(
|
|
3793
|
+
`要填绝对路径(例如 D:\\DeepSeekHarness):${next[key]}`,
|
|
3794
|
+
`An absolute path is required (e.g. D:\\DeepSeekHarness): ${next[key]}`,
|
|
3795
|
+
))
|
|
3796
|
+
}
|
|
3797
|
+
if (!existsSync(next[key])) warns.push(t(`目录还不存在:${next[key]}`, `Folder does not exist yet: ${next[key]}`))
|
|
3798
|
+
}
|
|
3799
|
+
for (const [k, v] of Object.entries(next.custom)) {
|
|
3800
|
+
if (!isAbsolute(v)) throw new Error(t(`自选目录要填绝对路径:${k} = ${v}`, `Custom folder must be an absolute path: ${k} = ${v}`))
|
|
3801
|
+
if (!existsSync(v)) warns.push(t(`目录还不存在:${v}`, `Folder does not exist yet: ${v}`))
|
|
3802
|
+
}
|
|
3803
|
+
const confirmed = new Set(Array.isArray(prev.confirmed) ? prev.confirmed : [])
|
|
3804
|
+
for (const key of ['appRoot', 'dshHome', 'workspaceHome']) confirmed.add(key)
|
|
3805
|
+
for (const k of Object.keys(next.custom)) confirmed.add(`ROOT:${k}`)
|
|
3806
|
+
next.confirmed = [...confirmed]
|
|
3807
|
+
|
|
3808
|
+
mkdirSync(dirname(rootsPathOf(dshHome)), { recursive: true })
|
|
3809
|
+
writeFileSync(rootsPathOf(dshHome), `${JSON.stringify(next, null, 2)}\n`, 'utf8')
|
|
3810
|
+
// 根都确认了,待确认清单就没意义了:清掉,下次拉取不再拦
|
|
3811
|
+
try { if (existsSync(pendingPathOf(dshHome))) unlinkSync(pendingPathOf(dshHome)) } catch { }
|
|
3812
|
+
|
|
3813
|
+
sendJson(res, 200, {
|
|
3814
|
+
ok: true,
|
|
3815
|
+
roots: next,
|
|
3816
|
+
warns,
|
|
3817
|
+
note: t(
|
|
3818
|
+
'已保存本机路径。接着点一次「拉取」(或退出后用拉取脚本),配置就会按这台机器的路径重新落地。',
|
|
3819
|
+
'Saved. Run Pull once (or the pull script after quitting) so the configs are written with these paths.',
|
|
3820
|
+
),
|
|
3821
|
+
})
|
|
3822
|
+
} catch (error) {
|
|
3823
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
3824
|
+
}
|
|
3825
|
+
}
|
|
3826
|
+
|
|
3827
|
+
/**
|
|
3828
|
+
* 问题反馈:落成仓库里的 feedback\<时间戳>-<id>.json,再 git add/commit/push 到云端。
|
|
3829
|
+
* 为什么用文件而不是 Issue:不依赖 API 令牌,另一台机器拉取后同样能在面板里看到;
|
|
3830
|
+
* 推送失败也不回滚本地文件(先把反馈留住,等网络好了下次推送会带上)。
|
|
3831
|
+
*/
|
|
3832
|
+
// ---------- 问题反馈:GitHub Issue 是唯一真源(0.3.31) ----------
|
|
3833
|
+
// 面板里提交 → 直接建 issue(label=feedback,正文附环境块);列表读 issue(含 open/closed);
|
|
3834
|
+
// 点「已解决」就 PATCH 成 closed。网络不通时先进本机待发队列,下次点「补发」再建 issue。
|
|
3835
|
+
|
|
3836
|
+
const GH_DEFAULT_REPO = 'QcWyGm/dsh-config-sync-plugin'
|
|
3837
|
+
const GH_FEEDBACK_LABEL = 'feedback'
|
|
3838
|
+
|
|
3839
|
+
/** 当前插件版本(读自己的 package.json;读不到就空串,不抛)。 */
|
|
3840
|
+
function pluginVersion() {
|
|
3841
|
+
try {
|
|
3842
|
+
const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8'))
|
|
3843
|
+
return String(pkg.version || '')
|
|
3844
|
+
} catch { return '' }
|
|
3845
|
+
}
|
|
3846
|
+
|
|
3847
|
+
function ghPathOf(dshHome) { return join(dshHome, 'config-sync-gh.json') }
|
|
3848
|
+
function outboxPathOf(dshHome) { return join(dshHome, 'config-sync-feedback-outbox.json') }
|
|
3849
|
+
|
|
3850
|
+
function readGh(dshHome) {
|
|
3851
|
+
const j = readJson(ghPathOf(dshHome)) || {}
|
|
3852
|
+
return {
|
|
3853
|
+
token: String(j.token || ''),
|
|
3854
|
+
repo: String(j.repo || GH_DEFAULT_REPO),
|
|
3855
|
+
login: String(j.login || ''),
|
|
3856
|
+
updatedAt: String(j.updatedAt || ''),
|
|
3857
|
+
}
|
|
3858
|
+
}
|
|
3859
|
+
|
|
3860
|
+
function writeGh(dshHome, o) {
|
|
3861
|
+
const f = ghPathOf(dshHome)
|
|
3862
|
+
try { mkdirSync(dirname(f), { recursive: true }) } catch { }
|
|
3863
|
+
const prev = readGh(dshHome)
|
|
3864
|
+
const body = {
|
|
3865
|
+
token: String(o.token || ''),
|
|
3866
|
+
repo: String(o.repo || GH_DEFAULT_REPO),
|
|
3867
|
+
// 令牌没换就沿用之前认出来的账号,免得每轮都调 /user
|
|
3868
|
+
login: String(o.login || prev.login || ''),
|
|
3869
|
+
updatedAt: new Date().toISOString(),
|
|
3870
|
+
}
|
|
3871
|
+
writeFileSync(f, `${JSON.stringify(body, null, 2)}\n`, 'utf8')
|
|
3872
|
+
return f
|
|
3873
|
+
}
|
|
3874
|
+
|
|
3875
|
+
function readOutbox(dshHome) {
|
|
3876
|
+
const j = readJson(outboxPathOf(dshHome))
|
|
3877
|
+
return Array.isArray(j?.items) ? j.items : []
|
|
3878
|
+
}
|
|
3879
|
+
|
|
3880
|
+
function writeOutbox(dshHome, items) {
|
|
3881
|
+
const f = outboxPathOf(dshHome)
|
|
3882
|
+
try { mkdirSync(dirname(f), { recursive: true }) } catch { }
|
|
3883
|
+
writeFileSync(f, `${JSON.stringify({ items }, null, 2)}\n`, 'utf8')
|
|
3884
|
+
return f
|
|
3885
|
+
}
|
|
3886
|
+
|
|
3887
|
+
/** 从本机 git 凭据里取一次 GitHub 令牌:用户平时 push 过,这里就不用再填。 */
|
|
3888
|
+
function tokenFromGitCredential() {
|
|
3889
|
+
return new Promise((resolve) => {
|
|
3890
|
+
let p = null
|
|
3891
|
+
try {
|
|
3892
|
+
p = spawn(resolveGitExe(), ['credential', 'fill'], { windowsHide: true })
|
|
3893
|
+
} catch { resolve(''); return }
|
|
3894
|
+
let out = ''
|
|
3895
|
+
const timer = setTimeout(() => { try { p.kill() } catch { } resolve('') }, 8000)
|
|
3896
|
+
p.stdout.on('data', (d) => { out += String(d) })
|
|
3897
|
+
p.on('error', () => { clearTimeout(timer); resolve('') })
|
|
3898
|
+
p.on('close', () => {
|
|
3899
|
+
clearTimeout(timer)
|
|
3900
|
+
const m = out.match(/password=([^\r\n]+)/)
|
|
3901
|
+
resolve(m ? m[1].trim() : '')
|
|
3902
|
+
})
|
|
3903
|
+
try { p.stdin.write('protocol=https\nhost=github.com\n\n'); p.stdin.end() } catch { }
|
|
3904
|
+
})
|
|
3905
|
+
}
|
|
3906
|
+
|
|
3907
|
+
/** 有存下来的令牌就用它,没有就向 git 凭据要一次并落盘(本机私有、不进仓库)。 */
|
|
3908
|
+
async function ghToken(config, dshHome) {
|
|
3909
|
+
const g = readGh(dshHome)
|
|
3910
|
+
if (g.token) return g
|
|
3911
|
+
const auto = await tokenFromGitCredential()
|
|
3912
|
+
if (!auto) return g
|
|
3913
|
+
writeGh(dshHome, { ...g, token: auto })
|
|
3914
|
+
return { ...g, token: auto }
|
|
3915
|
+
}
|
|
3916
|
+
|
|
3917
|
+
async function ghApi(pathname, options = {}) {
|
|
3918
|
+
const { method = 'GET', token, body } = options
|
|
3919
|
+
const url = pathname.startsWith('http') ? pathname : `https://api.github.com${pathname}`
|
|
3920
|
+
const headers = {
|
|
3921
|
+
Accept: 'application/vnd.github+json',
|
|
3922
|
+
'X-GitHub-Api-Version': '2022-11-28',
|
|
3923
|
+
'User-Agent': PACKAGE_ID,
|
|
3924
|
+
}
|
|
3925
|
+
// 公开仓库的读接口可以匿名调(60 次/小时/IP),所以 token 允许为空
|
|
3926
|
+
if (token) headers.Authorization = `Bearer ${token}`
|
|
3927
|
+
const init = { method, headers }
|
|
3928
|
+
if (body !== undefined) {
|
|
3929
|
+
headers['Content-Type'] = 'application/json; charset=utf-8'
|
|
3930
|
+
init.body = JSON.stringify(body)
|
|
3931
|
+
}
|
|
3932
|
+
const res = await fetch(url, init)
|
|
3933
|
+
const raw = await res.text()
|
|
3934
|
+
let json = null
|
|
3935
|
+
try { json = raw ? JSON.parse(raw) : null } catch { json = null }
|
|
3936
|
+
return { ok: res.ok, status: res.status, json, text: raw }
|
|
3937
|
+
}
|
|
3938
|
+
|
|
3939
|
+
function issueToItem(it) {
|
|
3940
|
+
return {
|
|
3941
|
+
number: Number(it.number || 0),
|
|
3942
|
+
title: String(it.title || ''),
|
|
3943
|
+
body: String(it.body || ''),
|
|
3944
|
+
state: String(it.state || ''),
|
|
3945
|
+
url: String(it.html_url || ''),
|
|
3946
|
+
createdAt: String(it.created_at || ''),
|
|
3947
|
+
updatedAt: String(it.updated_at || ''),
|
|
3948
|
+
user: String((it.user && it.user.login) || ''),
|
|
3949
|
+
comments: Number(it.comments || 0),
|
|
3950
|
+
labels: (Array.isArray(it.labels) ? it.labels : []).map((l) => String((l && l.name) || '')),
|
|
3951
|
+
}
|
|
3952
|
+
}
|
|
3953
|
+
|
|
3954
|
+
async function listIssues(repo, token, state) {
|
|
3955
|
+
const q = `state=${state}&labels=${GH_FEEDBACK_LABEL}&per_page=50&sort=created&direction=desc`
|
|
3956
|
+
const r = await ghApi(`/repos/${repo}/issues?${q}`, { token })
|
|
3957
|
+
if (!r.ok) throw new Error(`${r.status} ${String((r.json && r.json.message) || '').slice(0, 200) || '调用 GitHub 失败'}`)
|
|
3958
|
+
const arr = Array.isArray(r.json) ? r.json : []
|
|
3959
|
+
return arr.filter((x) => !x.pull_request).map(issueToItem)
|
|
3960
|
+
}
|
|
3961
|
+
|
|
3962
|
+
/** 正文末尾附一段环境块:在 GitHub 上看反馈时不用再问"你哪个版本、哪台机器"。 */
|
|
3963
|
+
function issueBodyOf(text, config) {
|
|
3964
|
+
const env = [
|
|
3965
|
+
`- 插件版本 / plugin: ${pluginVersion() || '?'}`,
|
|
3966
|
+
`- 机器 / machine: ${(() => { try { return hostname() } catch { return '?' } })()}`,
|
|
3967
|
+
`- 时间 / at: ${new Date().toISOString()}`,
|
|
3968
|
+
`- 平台 / platform: ${process.platform}`,
|
|
3969
|
+
`- 安装目录 / appRoot: ${(config && config.appRoot) || '?'}`,
|
|
3970
|
+
`- 配置仓库 / repo: ${(config && config.repoPath) || '?'}`,
|
|
3971
|
+
].join('\n')
|
|
3972
|
+
return `${String(text || '').trim()}\n\n---\n### 环境 / Environment\n${env}\n`
|
|
3973
|
+
}
|
|
3974
|
+
|
|
3975
|
+
async function createIssue(repo, token, title, text, config) {
|
|
3976
|
+
return ghApi(`/repos/${repo}/issues`, {
|
|
3977
|
+
method: 'POST',
|
|
3978
|
+
token,
|
|
3979
|
+
body: { title, body: issueBodyOf(text, config), labels: [GH_FEEDBACK_LABEL] },
|
|
3980
|
+
})
|
|
3981
|
+
}
|
|
3982
|
+
|
|
3983
|
+
/** 仓库所有者(第一个 / 前面那段):判断「谁能关单」就看它。 */
|
|
3984
|
+
function ownerOf(repo) {
|
|
3985
|
+
return String(repo || '').split('/')[0] || ''
|
|
3986
|
+
}
|
|
3987
|
+
|
|
3988
|
+
/** 令牌属于谁(GET /user)。结果缓存在 gh.json 里,不每轮都问。 */
|
|
3989
|
+
async function ghIdentity(token, dshHome, known) {
|
|
3990
|
+
if (known) return known
|
|
3991
|
+
const r = await ghApi('/user', { token })
|
|
3992
|
+
const login = r.ok && r.json ? String(r.json.login || '') : ''
|
|
3993
|
+
if (login) {
|
|
3994
|
+
const g = readGh(dshHome)
|
|
3995
|
+
writeGh(dshHome, { ...g, login })
|
|
3996
|
+
}
|
|
3997
|
+
return login
|
|
3998
|
+
}
|
|
3999
|
+
|
|
4000
|
+
/**
|
|
4001
|
+
* 无令牌时的提交入口:把标题/正文/环境块塞进 GitHub 的新建 issue 页面。
|
|
4002
|
+
* 浏览器里已登录 GitHub 就能直接点 Submit——这条路不需要 token,代价是要人工点一次。
|
|
4003
|
+
*/
|
|
4004
|
+
function newIssueUrl(repo, title, text, config) {
|
|
4005
|
+
const q = [
|
|
4006
|
+
`title=${encodeURIComponent(title)}`,
|
|
4007
|
+
`body=${encodeURIComponent(issueBodyOf(text, config))}`,
|
|
4008
|
+
`labels=${encodeURIComponent(GH_FEEDBACK_LABEL)}`,
|
|
4009
|
+
].join('&')
|
|
4010
|
+
return `https://github.com/${repo}/issues/new?${q}`
|
|
4011
|
+
}
|
|
4012
|
+
|
|
4013
|
+
|
|
4014
|
+
async function handleFeedback(req, res, config) {
|
|
4015
|
+
const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
4016
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1')
|
|
4017
|
+
const action = String(url.searchParams.get('action') || '').trim()
|
|
4018
|
+
const number = Number(url.searchParams.get('number') || 0)
|
|
4019
|
+
|
|
4020
|
+
if (req.method === 'GET') {
|
|
4021
|
+
try {
|
|
4022
|
+
const g = await ghToken(config, dshHome)
|
|
4023
|
+
const outbox = readOutbox(dshHome)
|
|
4024
|
+
const owner = ownerOf(g.repo)
|
|
4025
|
+
const login = g.token ? await ghIdentity(g.token, dshHome, g.login) : ''
|
|
4026
|
+
const base = {
|
|
4027
|
+
ok: true,
|
|
4028
|
+
repo: g.repo,
|
|
4029
|
+
label: GH_FEEDBACK_LABEL,
|
|
4030
|
+
owner,
|
|
4031
|
+
login,
|
|
4032
|
+
// 有关闭权限 = 令牌属于仓库所有者;别人的令牌也能改 issue 状态,所以在服务端挡住
|
|
4033
|
+
canClose: !!(login && owner && login.toLowerCase() === owner.toLowerCase()),
|
|
4034
|
+
connected: false,
|
|
4035
|
+
readAnon: false,
|
|
4036
|
+
tokenSaved: !!g.token,
|
|
4037
|
+
items: [],
|
|
4038
|
+
outbox: outbox.map((x) => ({ title: String(x.title || ''), createdAt: String(x.createdAt || '') })),
|
|
4039
|
+
version: pluginVersion(),
|
|
4040
|
+
ghFile: ghPathOf(dshHome),
|
|
4041
|
+
}
|
|
4042
|
+
// 读:有令牌先带令牌(自己的账号、限额 5000/小时),失败或没令牌就退回匿名(公开仓库 60 次/小时)
|
|
4043
|
+
const attempts = g.token ? [g.token, ''] : ['']
|
|
4044
|
+
let lastError = ''
|
|
4045
|
+
for (const tok of attempts) {
|
|
4046
|
+
try {
|
|
4047
|
+
const items = await listIssues(g.repo, tok, 'all')
|
|
4048
|
+
const counts = {
|
|
4049
|
+
open: items.filter((x) => x.state === 'open').length,
|
|
4050
|
+
closed: items.filter((x) => x.state === 'closed').length,
|
|
4051
|
+
total: items.length,
|
|
4052
|
+
}
|
|
4053
|
+
sendJson(res, 200, {
|
|
4054
|
+
...base,
|
|
4055
|
+
connected: !!tok,
|
|
4056
|
+
readAnon: !tok,
|
|
4057
|
+
items,
|
|
4058
|
+
counts,
|
|
4059
|
+
note: !tok
|
|
4060
|
+
? t('匿名读取(公开仓库,不限令牌;上限 60 次/小时),提交和关单需要令牌', 'Anonymous read (public repo, no token needed; 60 requests/hour). Submitting and closing need a token.')
|
|
4061
|
+
: '',
|
|
4062
|
+
})
|
|
4063
|
+
return
|
|
4064
|
+
} catch (error) {
|
|
4065
|
+
lastError = String((error && error.message) || error)
|
|
4066
|
+
}
|
|
4067
|
+
}
|
|
4068
|
+
sendJson(res, 200, { ...base, error: lastError || t('读不到 issue 列表', 'Cannot read the issue list') })
|
|
4069
|
+
} catch (error) {
|
|
4070
|
+
sendJson(res, 500, { ok: false, error: String((error && error.message) || error) })
|
|
4071
|
+
}
|
|
4072
|
+
return
|
|
4073
|
+
}
|
|
4074
|
+
|
|
4075
|
+
if (req.method !== 'POST' && req.method !== 'PATCH') { sendJson(res, 405, { ok: false, error: 'GET / POST / PATCH only' }); return }
|
|
4076
|
+
if (!originAllowed(req)) { sendJson(res, 403, { ok: false, error: 'cross-origin request rejected' }); return }
|
|
4077
|
+
|
|
4078
|
+
try {
|
|
4079
|
+
const raw = await readBody(req)
|
|
4080
|
+
const payload = raw.trim() ? JSON.parse(raw) : {}
|
|
4081
|
+
const g = await ghToken(config, dshHome)
|
|
4082
|
+
|
|
4083
|
+
// 1) 存令牌(填一次就够了;顺手用一次只读接口验证)
|
|
4084
|
+
if (action === 'token') {
|
|
4085
|
+
const token = String(payload.token || '').trim()
|
|
4086
|
+
const repo = String(payload.repo || g.repo || GH_DEFAULT_REPO).trim() || GH_DEFAULT_REPO
|
|
4087
|
+
if (!token) throw new Error(t('令牌是空的', 'The token is empty'))
|
|
4088
|
+
const probe = await ghApi(`/repos/${repo}`, { token })
|
|
4089
|
+
if (!probe.ok) throw new Error(`${probe.status} ${String((probe.json && probe.json.message) || '').slice(0, 160) || '令牌或仓库不对'}`)
|
|
4090
|
+
const me = await ghIdentity(token, dshHome)
|
|
4091
|
+
writeGh(dshHome, { token, repo, login: me })
|
|
4092
|
+
const owner = ownerOf(repo)
|
|
4093
|
+
sendJson(res, 200, {
|
|
4094
|
+
ok: true,
|
|
4095
|
+
connected: true,
|
|
4096
|
+
repo,
|
|
4097
|
+
saved: ghPathOf(dshHome),
|
|
4098
|
+
login: me,
|
|
4099
|
+
owner,
|
|
4100
|
+
canClose: !!(me && owner && me.toLowerCase() === owner.toLowerCase()),
|
|
4101
|
+
})
|
|
4102
|
+
return
|
|
4103
|
+
}
|
|
4104
|
+
|
|
4105
|
+
// 2) 补发本机队列里的反馈
|
|
4106
|
+
if (action === 'flush') {
|
|
4107
|
+
const pending = readOutbox(dshHome)
|
|
4108
|
+
if (!g.token) throw new Error(t('没有 GitHub 令牌,补发不了', 'No GitHub token, cannot flush'))
|
|
4109
|
+
const sent = []
|
|
4110
|
+
const failed = []
|
|
4111
|
+
for (const item of pending) {
|
|
4112
|
+
const r = await createIssue(g.repo, g.token, String(item.title || ''), String(item.body || ''), config)
|
|
4113
|
+
if (r.ok && r.json) sent.push({ number: r.json.number, url: r.json.html_url })
|
|
4114
|
+
else failed.push(item)
|
|
4115
|
+
}
|
|
4116
|
+
writeOutbox(dshHome, failed)
|
|
4117
|
+
sendJson(res, 200, { ok: true, sent, remaining: failed.length })
|
|
4118
|
+
return
|
|
4119
|
+
}
|
|
4120
|
+
|
|
4121
|
+
// 3) 把某条 issue 标记成已解决 / 重新打开 —— 只有仓库所有者本人的令牌可以
|
|
4122
|
+
if (req.method === 'PATCH' || action === 'state') {
|
|
4123
|
+
if (!number) throw new Error(t('缺 issue 编号', 'Missing issue number'))
|
|
4124
|
+
if (!g.token) throw new Error(t('没有令牌:改状态需要令牌', 'No token: changing state needs one'))
|
|
4125
|
+
const login = await ghIdentity(g.token, dshHome, g.login)
|
|
4126
|
+
const owner = ownerOf(g.repo)
|
|
4127
|
+
if (!login || login.toLowerCase() !== owner.toLowerCase()) {
|
|
4128
|
+
sendJson(res, 403, {
|
|
4129
|
+
ok: false,
|
|
4130
|
+
error: t(`只有仓库所有者(${owner})能关单;当前令牌属于 ${login || '未知账号'}`, `Only the repo owner (${owner}) can close issues; this token belongs to ${login || 'unknown'}`),
|
|
4131
|
+
})
|
|
4132
|
+
return
|
|
4133
|
+
}
|
|
4134
|
+
const state = String(payload.state || 'closed') === 'closed' ? 'closed' : 'open'
|
|
4135
|
+
const r = await ghApi(`/repos/${g.repo}/issues/${number}`, { method: 'PATCH', token: g.token, body: { state } })
|
|
4136
|
+
if (!r.ok) throw new Error(`${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`)
|
|
4137
|
+
sendJson(res, 200, { ok: true, number, state })
|
|
4138
|
+
return
|
|
4139
|
+
}
|
|
4140
|
+
|
|
4141
|
+
// 4) 提交一条新反馈
|
|
4142
|
+
const title = String(payload.title || '').trim().slice(0, 200)
|
|
4143
|
+
const text = String(payload.body || payload.detail || '').trim().slice(0, 6000)
|
|
4144
|
+
if (!title) throw new Error(t('先写个标题,方便以后对上号', 'Give it a title so it can be found later'))
|
|
4145
|
+
|
|
4146
|
+
// 没令牌:不硬失败,给一条浏览器预填链接(浏览器登录了 GitHub 就能点提交)
|
|
4147
|
+
if (!g.token) {
|
|
4148
|
+
sendJson(res, 200, {
|
|
4149
|
+
ok: true,
|
|
4150
|
+
needToken: true,
|
|
4151
|
+
submitted: false,
|
|
4152
|
+
fallbackUrl: newIssueUrl(g.repo, title, text, config),
|
|
4153
|
+
error: t('没有令牌:可以打开预填好的新建 issue 页面,在浏览器里点一下提交', 'No token: open the prefilled new-issue page and press submit in the browser'),
|
|
4154
|
+
})
|
|
4155
|
+
return
|
|
4156
|
+
}
|
|
4157
|
+
|
|
4158
|
+
const r = await createIssue(g.repo, g.token, title, text, config)
|
|
4159
|
+
if (r.ok && r.json) {
|
|
4160
|
+
sendJson(res, 200, { ok: true, number: r.json.number, url: r.json.html_url, item: issueToItem(r.json) })
|
|
4161
|
+
return
|
|
4162
|
+
}
|
|
4163
|
+
// 建 issue 失败:进本机队列,网络好了点「补发」
|
|
4164
|
+
const items = readOutbox(dshHome)
|
|
4165
|
+
items.push({ title, body: text, createdAt: new Date().toISOString(), error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}` })
|
|
4166
|
+
writeOutbox(dshHome, items)
|
|
4167
|
+
sendJson(res, 200, {
|
|
4168
|
+
ok: true,
|
|
4169
|
+
queued: true,
|
|
4170
|
+
remaining: items.length,
|
|
4171
|
+
error: `${r.status} ${String((r.json && r.json.message) || '').slice(0, 160)}`,
|
|
4172
|
+
})
|
|
4173
|
+
} catch (error) {
|
|
4174
|
+
sendJson(res, 400, { ok: false, error: String((error && error.message) || error) })
|
|
4175
|
+
}
|
|
4176
|
+
}
|
|
4177
|
+
|
|
4178
|
+
export function apply(ctx, config) {
|
|
4179
|
+
try {
|
|
4180
|
+
ctx.inject(['webServer'], (scoped) => {
|
|
4181
|
+
// 每个请求按 accept-language 决定返回中文还是英文:AsyncLocalStorage 让 t() 在
|
|
4182
|
+
// 任何异步后续里都能读到本次请求的语言,不用把语言参数一层层往下传。
|
|
4183
|
+
const withLang = (handler) => (req, res) => langStore.run(pickLang(req), () => handler(req, res, config))
|
|
4184
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4185
|
+
kind: 'exact',
|
|
4186
|
+
path: ROUTE_STATUS,
|
|
4187
|
+
handler: withLang(handleStatus),
|
|
4188
|
+
}))
|
|
4189
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4190
|
+
kind: 'exact',
|
|
4191
|
+
path: ROUTE_PREPARE,
|
|
4192
|
+
handler: withLang(handlePrepare),
|
|
4193
|
+
}))
|
|
4194
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4195
|
+
kind: 'exact',
|
|
4196
|
+
path: ROUTE_SETTINGS,
|
|
4197
|
+
handler: withLang(handleSettings),
|
|
4198
|
+
}))
|
|
4199
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4200
|
+
kind: 'exact',
|
|
4201
|
+
path: ROUTE_AUTO,
|
|
4202
|
+
handler: withLang(handleAuto),
|
|
4203
|
+
}))
|
|
4204
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4205
|
+
kind: 'exact',
|
|
4206
|
+
path: ROUTE_UPDATE,
|
|
4207
|
+
handler: withLang(handleUpdate),
|
|
4208
|
+
}))
|
|
4209
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4210
|
+
kind: 'exact',
|
|
4211
|
+
path: ROUTE_SCOPE,
|
|
4212
|
+
handler: withLang(handleScope),
|
|
4213
|
+
}))
|
|
4214
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4215
|
+
kind: 'exact',
|
|
4216
|
+
path: ROUTE_EXTRA_CONFIG,
|
|
4217
|
+
handler: withLang(handleExtraConfig),
|
|
4218
|
+
}))
|
|
4219
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4220
|
+
kind: 'exact',
|
|
4221
|
+
path: ROUTE_CONFLICT,
|
|
4222
|
+
handler: withLang(handleConflict),
|
|
4223
|
+
}))
|
|
4224
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4225
|
+
kind: 'exact',
|
|
4226
|
+
path: ROUTE_ROOTS,
|
|
4227
|
+
handler: withLang(handleRoots),
|
|
4228
|
+
}))
|
|
4229
|
+
scoped.effect(() => scoped.webServer.register({
|
|
4230
|
+
kind: 'exact',
|
|
4231
|
+
path: ROUTE_FEEDBACK,
|
|
4232
|
+
handler: withLang(handleFeedback),
|
|
4233
|
+
}))
|
|
4234
|
+
})
|
|
4235
|
+
// 开关打开才排一次启动检查(默认关 = 什么都不做)
|
|
4236
|
+
scheduleAutoStart(config)
|
|
4237
|
+
// 云端探测预热:插件一装上就去探一次(不阻塞、不 await)。这样面板打开时缓存多半已经热了,
|
|
4238
|
+
// status 不用再为首屏那 2.5 秒的 ls-remote 埋单。
|
|
4239
|
+
typeof setTimeout === 'function' ? setTimeout(() => { try { warmRemoteProbe(config) } catch { } }, 300) : null
|
|
4240
|
+
installQuitWhenAllWindowsClosed(ctx)
|
|
4241
|
+
} catch (error) {
|
|
4242
|
+
// 不抛:缺 webServer 的 profile 里这个插件静默不激活即可
|
|
4243
|
+
try { ctx.logger?.warn?.(`[${PACKAGE_ID}] webServer 不可用,设置页面板不会出现:${error}`) } catch { }
|
|
4244
|
+
}
|
|
4245
|
+
}
|
|
4246
|
+
|
|
4247
|
+
/**
|
|
4248
|
+
* 用户点窗口右上角的关闭键时,让客户端**真的退出**。
|
|
4249
|
+
*
|
|
4250
|
+
* 为什么要主动补一刀:宿主自己的 window-all-closed 只在"所有窗口都销毁"时才 quit,
|
|
4251
|
+
* 实测点了关闭后主进程又活了 1.5 分钟以上(还有隐藏/后台窗口在),
|
|
4252
|
+
* 而「退出后自动推送」的守护进程只认"主进程 pid 消失"——于是永远等不到,推送不执行。
|
|
4253
|
+
* 这里在窗口 closed 后查一遍:一个可见窗口都没有了就 app.quit()。
|
|
4254
|
+
*/
|
|
4255
|
+
function installQuitWhenAllWindowsClosed(ctx) {
|
|
4256
|
+
try {
|
|
4257
|
+
const el = electronApp()
|
|
4258
|
+
if (!el) return
|
|
4259
|
+
const flag = '__dshConfigSyncQuitHook'
|
|
4260
|
+
if (globalThis[flag]) return
|
|
4261
|
+
globalThis[flag] = true
|
|
4262
|
+
el.app.on('browser-window-created', (_event, win) => {
|
|
4263
|
+
try {
|
|
4264
|
+
win.on('closed', () => {
|
|
4265
|
+
setTimeout(() => {
|
|
4266
|
+
try {
|
|
4267
|
+
const alive = el.BrowserWindow.getAllWindows().filter((w) => w && !w.isDestroyed())
|
|
4268
|
+
const visible = alive.filter((w) => { try { return w.isVisible() } catch { return false } })
|
|
4269
|
+
if (visible.length === 0) {
|
|
4270
|
+
try { ctx.logger?.info?.(`[${PACKAGE_ID}] 已无可见窗口,退出客户端(好让退出后同步开始)`) } catch { }
|
|
4271
|
+
el.app.quit()
|
|
4272
|
+
}
|
|
4273
|
+
} catch { }
|
|
4274
|
+
}, 600)
|
|
4275
|
+
})
|
|
4276
|
+
} catch { }
|
|
4277
|
+
})
|
|
4278
|
+
} catch { }
|
|
4279
|
+
}
|
|
4280
|
+
|
|
4281
|
+
export default { name: PACKAGE_ID, apply }
|