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.
@@ -0,0 +1,809 @@
1
+ <#
2
+ 退出后执行同步:等 DSH 完全退出,再跑 pull 或 push(插件在 DSH 进程里,自己等不了自己退出)
3
+
4
+ 由插件在 DSH 运行期用 detached 方式拉起:
5
+ powershell -NoProfile -ExecutionPolicy Bypass -File post-exit.ps1 -Mode pull|push -WatchPid <dsh pid> `
6
+ -RepoRoot G:\dsh-config -DshHome C:\Users\xx\.dsh -AppRoot G:\DeepSeekHarness [-Restart]
7
+
8
+ 要点
9
+ - 只认 WatchPid:那个进程消失(DSH 真退出,含托盘)后才动手,避免在运行中的客户端上 apply。
10
+ - pull 用 apply 落地配置,必须 DSH 不在;push 要抓配置同样必须退出。
11
+ - pull 失败要**自动回滚**:仓库 reset 回拉取前的 HEAD,配置用这次 apply 之前刚建的快照
12
+ (backups\config-<时间戳>)还原,然后照常重启,让客户端回到动手前的样子。
13
+ - -Restart:pull / push 都支持 —— 动作做完(无论成败)把客户端重新拉起来。
14
+ pull:成功=用新配置,失败=用回滚后的原配置;push:成功=回到刚推完的状态,失败=回到原状。
15
+ - 不论成败都写 <DshHome>\auto-sync-result.json,客户端下次启动读它弹 5 秒提示。
16
+ - 本脚本由插件以**可见窗口**启动:进度用 Write-Host 实时打到窗口,同时照旧写日志文件
17
+ <DshHome>\logs\auto-sync-<时间戳>.log(窗口被关/没显示时也能查)。
18
+ #>
19
+ param(
20
+ [Parameter(Mandatory = $true)][ValidateSet('pull', 'push', 'restore', 'update', 'relaunch')][string]$Mode,
21
+ [int]$WatchPid = 0,
22
+ # wait:隐藏进程,只等 DSH 退出,退出后换一个**可见窗口**跑 run
23
+ # run :真正执行同步(默认,直接调用时不用传)
24
+ [ValidateSet('wait', 'run')][string]$Phase = 'run',
25
+ [string]$RepoRoot,
26
+ [string]$DshHome = $(Join-Path $env:USERPROFILE '.dsh'),
27
+ [string]$AppRoot = '',
28
+ [switch]$Restart,
29
+ [int]$MaxWaitMinutes = 30,
30
+ [string]$LogFile,
31
+ # ---- 仅 -Mode restore 用:还原到哪份快照 ----
32
+ [string]$BackupDir = '',
33
+ # 备份类型:profile(配置快照,默认)/ plugin(插件本体备份)/ session(会话目录备份)
34
+ [ValidateSet('profile', 'plugin', 'session')]
35
+ [string]$SnapshotKind = 'profile',
36
+ # ---- 仅 -Mode update 用:插件自身更新 ----
37
+ [string]$PluginDir = '',
38
+ [string]$UpdateVersion = '',
39
+ [string]$UpdateTgz = '',
40
+ [string]$UpdateSha256 = '',
41
+ # 仓库是私有库时必须带的只读令牌(Gitee 私人令牌);留空就按匿名方式下载
42
+ [string]$UpdateToken = ''
43
+ )
44
+
45
+ # ---------- Phase=wait:只等退出,然后换成可见窗口执行 ----------
46
+ # 为什么要分两段:窗口必须**在 DSH 退出之后**才出现。排队阶段就弹窗的话,
47
+ # 用户从开机到关窗口这段时间会一直挂着一个"等 DSH 退出"的黑窗,什么也干不了还挡着视线。
48
+ if ($Phase -eq 'wait') {
49
+ $deadline = (Get-Date).AddMinutes($MaxWaitMinutes)
50
+ $noWindowTicks = 0
51
+ $waitLog = Join-Path $DshHome 'logs\auto-sync-wait.log'
52
+ function WaitLog([string]$text) {
53
+ try {
54
+ $dir = Split-Path -Parent $waitLog
55
+ if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
56
+ Add-Content -LiteralPath $waitLog -Value ("[{0}] [{1}] {2}" -f (Get-Date -Format 'HH:mm:ss'), $Mode, $text) -Encoding utf8
57
+ } catch { }
58
+ }
59
+ WaitLog ("等待开始(pid {0})" -f $WatchPid)
60
+ while ($true) {
61
+ # 按**进程名**判断,而不是只看传进来的 pid:插件传的 pid 未必是「那个活着的客户端」——
62
+ # 实测出现过 watchPid 对应的进程早就不在了、而客户端明明还在跑,等待态于是当场开工,
63
+ # 在 DSH 运行期间拉取/推送(正是绝对不能发生的事)。
64
+ $byName = @(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue)
65
+ $byPid = if ($WatchPid -gt 0) { Get-Process -Id $WatchPid -ErrorAction SilentlyContinue } else { $null }
66
+ if ($byName.Count -eq 0 -and -not $byPid) { WaitLog 'DSH 已完全退出'; break }
67
+
68
+ # 用户点了窗口右上角的关闭、前台窗口全没了,但进程赖着不走(实测 7 个进程全部 hwnd=0 还活着)。
69
+ # 不能只看「曾经出现过窗口」——等待进程可能是在窗口关掉之后才起来的(实测就这么漏判了),
70
+ # 改用批次年龄:这批客户端进程已经活了 60 秒以上、却一个可见窗口都没有 → 认定用户已关闭。
71
+ $visible = @($byName | Where-Object { $_.MainWindowHandle -ne 0 })
72
+ $newest = $byName | Sort-Object StartTime -Descending | Select-Object -First 1
73
+ $ageSec = if ($newest -and $newest.StartTime) { ((Get-Date) - $newest.StartTime).TotalSeconds } else { 0 }
74
+ if ($visible.Count -eq 0 -and $ageSec -gt 60) { $noWindowTicks++ } else { $noWindowTicks = 0 }
75
+ if ($noWindowTicks -ge 8) {
76
+ WaitLog '前台窗口已关闭且进程不退,强制结束残留进程'
77
+ try { Stop-Process -Name 'DeepSeek Harness' -Force -ErrorAction SilentlyContinue } catch { }
78
+ Start-Sleep -Seconds 3
79
+ if (@(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue).Count -eq 0) { WaitLog '已全部结束'; break }
80
+ $noWindowTicks = 0
81
+ }
82
+ if ((Get-Date) -gt $deadline) { WaitLog '等待超时,放弃本次同步'; exit 2 }
83
+ Start-Sleep -Seconds 2
84
+ }
85
+ # 进程刚退时文件句柄还没释放,留一点余量再交给可见实例
86
+ Start-Sleep -Seconds 2
87
+ $pwshExe = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
88
+ if (-not (Test-Path -LiteralPath $pwshExe)) { $pwshExe = 'powershell.exe' }
89
+ $relay = @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $PSCommandPath,
90
+ '-Mode', $Mode, '-WatchPid', '0', '-Phase', 'run', '-DshHome', $DshHome)
91
+ if ($RepoRoot) { $relay += @('-RepoRoot', $RepoRoot) }
92
+ if ($AppRoot) { $relay += @('-AppRoot', $AppRoot) }
93
+ if ($Restart) { $relay += '-Restart' }
94
+ if ($BackupDir) { $relay += @('-BackupDir', $BackupDir) }
95
+ if ($PluginDir) { $relay += @('-PluginDir', $PluginDir) }
96
+ if ($UpdateVersion) { $relay += @('-UpdateVersion', $UpdateVersion) }
97
+ if ($UpdateTgz) { $relay += @('-UpdateTgz', $UpdateTgz) }
98
+ if ($UpdateSha256) { $relay += @('-UpdateSha256', $UpdateSha256) }
99
+ if ($UpdateToken) { $relay += @('-UpdateToken', $UpdateToken) }
100
+ try { Start-Process -FilePath $pwshExe -ArgumentList $relay -WindowStyle Normal | Out-Null } catch { }
101
+ exit 0
102
+ }
103
+
104
+ $ErrorActionPreference = 'Continue'
105
+ $stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
106
+
107
+ # 窗口是可见的:给它一个能看懂的标题,并把控制台编码设成 UTF-8(否则中文进度全是乱码)
108
+ try { $Host.UI.RawUI.WindowTitle = ('DSH 配置同步 · ' + $(if ($Mode -eq 'update') { '插件更新' } elseif ($Mode -eq 'relaunch') { '重启' } elseif ($Mode -eq 'restore') { '还原' } elseif ($Mode -eq 'pull') { '拉取' } else { '推送' })) } catch { }
109
+ try { [Console]::OutputEncoding = New-Object Text.UTF8Encoding $false; $OutputEncoding = [Console]::OutputEncoding } catch { }
110
+
111
+ if (-not $LogFile) {
112
+ $logDir = Join-Path $DshHome 'logs'
113
+ if (-not (Test-Path -LiteralPath $logDir)) { New-Item -ItemType Directory -Path $logDir -Force | Out-Null }
114
+ $LogFile = Join-Path $logDir ("auto-sync-{0}-{1}.log" -f $Mode, $stamp)
115
+ }
116
+ function Log([string]$text) {
117
+ $line = "[{0}] {1}" -f (Get-Date -Format 'HH:mm:ss'), $text
118
+ Add-Content -LiteralPath $LogFile -Value $line -Encoding utf8
119
+ # 同步打到可见窗口;窗口不显示或已被关掉就静默跳过,绝不因为写屏失败中断同步
120
+ try { Write-Host $line } catch { }
121
+ }
122
+
123
+ $ResultFile = Join-Path $DshHome 'auto-sync-result.json'
124
+ # 接管互斥锁:等待阶段记的是那个等候进程的 pid,这里换成真正干活的进程;
125
+ # 别的同步动作看到这把锁(且 pid 活着)就会排队等待/放弃,不会两个一起改配置。
126
+ try {
127
+ [IO.File]::WriteAllText((Join-Path $DshHome 'auto-sync.lock'),
128
+ ([ordered]@{ pid = $PID; mode = $Mode; at = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() } | ConvertTo-Json),
129
+ (New-Object Text.UTF8Encoding $false))
130
+ } catch { }
131
+ # 结果文件给客户端下次启动读:ok/mode/at/code/message/restored/log (+ notices)
132
+ function Write-Result([bool]$ok, [int]$code, [string]$message, [bool]$restored) {
133
+ # 未同步文件清单(sync.ps1 / capture.ps1 / apply.ps1 攒下的):面板要常驻显示,
134
+ # 所以它必须跟着结果一起落盘,而不是只留在本次的日志里。
135
+ $notices = $null
136
+ try {
137
+ $np = Join-Path $DshHome 'sync-notices.json'
138
+ if (Test-Path -LiteralPath $np) {
139
+ $notices = Get-Content -LiteralPath $np -Raw -Encoding utf8 | ConvertFrom-Json
140
+ if ($notices -and [int]$notices.total -le 0) { $notices = $null }
141
+ }
142
+ } catch { $notices = $null }
143
+ $obj = [ordered]@{
144
+ mode = $Mode
145
+ ok = $ok
146
+ at = [long]([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds())
147
+ code = $code
148
+ message = $message
149
+ restored = $restored
150
+ log = $LogFile
151
+ appRoot = $AppRoot
152
+ restart = [bool]$Restart
153
+ notices = $notices
154
+ }
155
+ try {
156
+ $dir = Split-Path -Parent $ResultFile
157
+ if ($dir -and -not (Test-Path -LiteralPath $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
158
+ $json = $obj | ConvertTo-Json -Depth 6
159
+ [IO.File]::WriteAllText($ResultFile, $json, (New-Object Text.UTF8Encoding $false))
160
+ Log ("结果已写入:{0}" -f $ResultFile)
161
+ } catch { Log ("写结果文件失败:{0}" -f $_.Exception.Message) }
162
+ }
163
+
164
+ # 进度窗口末尾的小结:哪些文件这次没同步、为什么。顺序按「必须该修」在前。
165
+ function Show-NoticesSummary {
166
+ $np = Join-Path $DshHome 'sync-notices.json'
167
+ if (-not (Test-Path -LiteralPath $np)) { return }
168
+ $n = $null
169
+ try { $n = Get-Content -LiteralPath $np -Raw -Encoding utf8 | ConvertFrom-Json } catch { return }
170
+ if (-not $n -or [int]$n.total -le 0) { return }
171
+ $groups = @(
172
+ @{ Kind = 'history'; Title = '历史提交里的超限文件(远端会拒收,需换仓库或清史)' }
173
+ @{ Kind = 'too-large'; Title = '超过单文件上限,未进仓库' }
174
+ @{ Kind = 'failed'; Title = '写入/推送失败' }
175
+ @{ Kind = 'skipped'; Title = '按规则跳过' }
176
+ )
177
+ Write-Host ''
178
+ Write-Host ("---------------- 未同步的文件 {0} 个 ----------------" -f $n.total) -ForegroundColor Yellow
179
+ foreach ($g in $groups) {
180
+ $items = @($n.items | Where-Object { $_.kind -eq $g.Kind })
181
+ if ($items.Count -eq 0) { continue }
182
+ Write-Host (" [{0}] {1}" -f $items.Count, $g.Title) -ForegroundColor Yellow
183
+ $i = 0
184
+ foreach ($it in $items) {
185
+ if ($i -ge 5) { break }
186
+ $size = if ($it.bytes) { '({0:N1} MB)' -f ([double]$it.bytes / 1MB) } else { '' }
187
+ Write-Host (" - {0}{1}:{2}" -f $it.path, $size, $it.reason)
188
+ $i++
189
+ }
190
+ if ($items.Count -gt 5) { Write-Host (" …还有 {0} 个,完整清单:{1}" -f ($items.Count - 5), $np) }
191
+ }
192
+ Write-Host (" 清单文件:{0}" -f $np)
193
+ Write-Host '--------------------------------------------------------' -ForegroundColor Yellow
194
+ }
195
+
196
+ function Finish([int]$code, [string]$note) {
197
+ Log ("结束:{0}(退出码 {1})" -f $note, $code)
198
+ Log ("日志:{0}" -f $LogFile)
199
+ # 放开互斥锁:只删自己写的那把(锁里 pid 不是本进程就别动,可能是后来者)
200
+ try {
201
+ $lockPath = Join-Path $DshHome 'auto-sync.lock'
202
+ if (Test-Path -LiteralPath $lockPath) {
203
+ $lock = Get-Content -LiteralPath $lockPath -Raw | ConvertFrom-Json
204
+ if ([int]$lock.pid -eq $PID) { Remove-Item -LiteralPath $lockPath -Force }
205
+ }
206
+ } catch { }
207
+
208
+ # 推送 / 拉取 / 插件更新:**不自动关窗**,把结果留在屏幕上让用户自己关。
209
+ # 为什么敢一直挂着:客户端是在这之前的 RestartClient 里用 explorer 代启的,跟本窗口没有父子/作业关系,
210
+ # 所以窗口留多久、还是被点 × 直接结束,都不会把客户端带走。
211
+ # 只有 relaunch(纯重启,窗口里没有可看的结果)仍旧停 3 秒自动关。
212
+ if ($Mode -eq 'pull' -or $Mode -eq 'push' -or $Mode -eq 'update' -or $Mode -eq 'restore') {
213
+ $title = if ($Mode -eq 'update') { '插件更新已完成' } elseif ($Mode -eq 'restore') { '还原已完成' } else { '同步已完成' }
214
+ try {
215
+ Show-NoticesSummary
216
+ Write-Host ''
217
+ Write-Host ("================ {0} ================" -f $title)
218
+ Write-Host ' 这个窗口不会自动关闭:看完按任意键,或点右上角 × 关闭。'
219
+ Write-Host ' 客户端已在后台由 explorer 拉起,关掉这个窗口不会影响它。'
220
+ Write-Host '==========================================='
221
+ $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
222
+ } catch {
223
+ # 不是真控制台(被重定向/无窗口)时 ReadKey 会抛,退化成长时间挂起而不是立刻消失
224
+ try { Start-Sleep -Seconds 3600 } catch { }
225
+ }
226
+ } else {
227
+ # 窗口跟着进程一起关,停 3 秒让用户看清成功/失败与日志路径
228
+ try { Start-Sleep -Seconds 3 } catch { }
229
+ }
230
+ exit $code
231
+ }
232
+
233
+ # git 位置探测的正主在 dsh-sync-common.ps1(Get-GitExe)。本脚本故意保留一份最小实现:
234
+ # 它的职责是「仓库/插件目录残了也要能等退出并重启」,不能反过来依赖仓库里的公共文件。
235
+ # 改位置表时两边一起改(这里只有兜底逻辑,不参与路径归一)。
236
+ if (-not (Get-Command Get-GitExe -ErrorAction SilentlyContinue)) {
237
+ function Get-GitExe {
238
+ foreach ($p in @("$env:ProgramFiles\Git\cmd\git.exe", "$env:LOCALAPPDATA\Programs\Git\cmd\git.exe", "${env:ProgramFiles(x86)}\Git\cmd\git.exe")) {
239
+ if ($p -and (Test-Path -LiteralPath $p)) { return $p }
240
+ }
241
+ $c = Get-Command git.exe -ErrorAction SilentlyContinue
242
+ if ($c) { return $c.Source }
243
+ return $null
244
+ }
245
+ }
246
+
247
+ Log ("开始:mode={0} watchPid={1}" -f $Mode, $WatchPid)
248
+ Log ("仓库:{0}" -f $RepoRoot)
249
+
250
+ # ---------- 等 DSH 退出(只在被直接调用、还带着 pid 时;正常链路由 Phase=wait 干这件事) ----------
251
+ if ($WatchPid -gt 0) {
252
+ Log ("等 DSH 完全退出(pid {0},最多 {1} 分钟)…关掉客户端窗口就行,同步会自动开始" -f $WatchPid, $MaxWaitMinutes)
253
+ $deadline = (Get-Date).AddMinutes($MaxWaitMinutes)
254
+ while ($true) {
255
+ $p = Get-Process -Id $WatchPid -ErrorAction SilentlyContinue
256
+ if (-not $p) { break }
257
+ if ((Get-Date) -gt $deadline) {
258
+ Log ("等待超时({0} 分钟),DSH 仍在运行,放弃本次同步" -f $MaxWaitMinutes)
259
+ Finish 2 '等待超时'
260
+ }
261
+ Start-Sleep -Seconds 2
262
+ }
263
+ Log 'DSH 已退出'
264
+ # 进程刚退时文件句柄可能还没释放,留一点余量
265
+ Start-Sleep -Seconds 3
266
+ }
267
+
268
+
269
+ # ---------- 自动重启:动作做完就把客户端拉起来(pull / push / update 共用) ----------
270
+
271
+ # 为什么不能直接用 Start-Process 拉客户端:
272
+ # 进度窗口是个控制台程序,从它里面 Start-Process 出来的客户端会跟着进那个控制台的作业;
273
+ # 用户点窗口的 × 关掉进度显示时,conhost 清理作业会把刚重启的客户端一起结束(实测复现:
274
+ # 结束探测窗口进程后,它用 Start-Process 起的子进程同时消失)。
275
+ # 而窗口自己跑完、进程正常退出时不做这次清理,所以"等它自己关"看起来是好的。
276
+ # 实测三种启动方式(visible 控制台 + notepad 做探针):
277
+ # Start-Process → 关窗口后子进程被连坐
278
+ # explorer 代启 → 子进程存活(Explorer 长期驻留,不在本窗口的作业里)
279
+ # 自建 DETACHED/BREAKAWAY 进程 → 进程起不活,不可用(所以没保留这条分支)
280
+ function Start-Detached([string]$exe) {
281
+ $workDir = Split-Path -Parent $exe
282
+ $explorer = Join-Path $env:SystemRoot 'explorer.exe'
283
+ if (Test-Path -LiteralPath $explorer) {
284
+ try {
285
+ Start-Process -FilePath $explorer -ArgumentList ('"' + $exe + '"') | Out-Null
286
+ return 'explorer'
287
+ } catch { Log ("explorer 代启失败:{0}" -f $_.Exception.Message) }
288
+ }
289
+ # 兜底:原方式。会把客户端挂进本窗口的作业,手动关进度窗口时仍有被连坐的风险。
290
+ try {
291
+ Start-Process -FilePath $exe -WorkingDirectory $workDir | Out-Null
292
+ return 'plain'
293
+ } catch {
294
+ Log ("启动命令失败:{0}" -f $_.Exception.Message)
295
+ return $null
296
+ }
297
+ }
298
+
299
+ # ---------- 默认工作区校正(0.3.28) ----------
300
+ # 客户端重启后会自己开一个新会话,落点由 <DshHome>\storages\workspace.json 的
301
+ # global.defaultWorkspaceId 决定。这个值只在本机首次初始化时被 DSH 写过一次,之后
302
+ # 谁都不会自动改 —— 于是同步过几次之后它可能停在某个「上次用的工作区」上。
303
+ #
304
+ # 时机:必须在客户端**完全退出之后、重新拉起之前**写。客户端持有这份登记表并在退出时
305
+ # 回写,早写会被盖回去(apply.ps1 也是同一个道理)。
306
+ # 目标:默认取「标题或路径是 default-workspace 的那个工作区」;
307
+ # 设置文件里的 defaultWorkspace 可以指定工作区路径或 ID,填 off/none 则不干预。
308
+ # 安全:只在值真的不同时才动,动之前原样备份一份 workspace.json.bak-<时间>,写完回读校验。
309
+ function Get-NormPath([string]$p) {
310
+ if (-not $p) { return '' }
311
+ return ($p.Replace('/', '\').TrimEnd('\')).ToLowerInvariant()
312
+ }
313
+
314
+ function Set-DefaultWorkspace {
315
+ if (-not $DshHome) { return }
316
+ $reg = Join-Path $DshHome 'storages/workspace.json'
317
+ if (-not (Test-Path -LiteralPath $reg)) { Log '没有 workspace.json,跳过默认工作区校正'; return }
318
+
319
+ $spec = ''
320
+ try {
321
+ $sf = Join-Path $DshHome 'dsh-config-sync.json'
322
+ if (Test-Path -LiteralPath $sf) {
323
+ $s = Get-Content -LiteralPath $sf -Raw -Encoding UTF8 | ConvertFrom-Json
324
+ if ($s -and $s.PSObject.Properties['defaultWorkspace']) { $spec = [string]$s.defaultWorkspace }
325
+ }
326
+ } catch { $spec = '' }
327
+ $spec = $spec.Trim()
328
+
329
+ if ($spec -match '^(off|none|false|0)$') { Log '默认工作区校正已关闭(defaultWorkspace=off)'; return }
330
+
331
+ try {
332
+ $obj = Get-Content -LiteralPath $reg -Raw -Encoding UTF8 | ConvertFrom-Json
333
+ $tables = $obj.tables.workspaces
334
+ if (-not $tables) { Log 'workspace.json 里没有 workspaces 表,跳过默认工作区校正'; return }
335
+
336
+ $cur = [string]$obj.global.defaultWorkspaceId
337
+ $target = ''
338
+ if ($spec) {
339
+ if (@($tables.PSObject.Properties.Name) -contains $spec) { $target = $spec }
340
+ else {
341
+ $want = Get-NormPath $spec
342
+ foreach ($p in $tables.PSObject.Properties) {
343
+ if ((Get-NormPath ([string]$p.Value.path)) -eq $want) { $target = $p.Name; break }
344
+ }
345
+ }
346
+ if (-not $target) { Log ("设置里的 defaultWorkspace 找不到对应工作区:{0}(跳过,不改)" -f $spec); return }
347
+ } else {
348
+ foreach ($p in $tables.PSObject.Properties) {
349
+ $path = Get-NormPath ([string]$p.Value.path)
350
+ $title = ([string]$p.Value.title).Trim().ToLowerInvariant()
351
+ if ($title -eq 'default-workspace' -or $path.EndsWith('\deepseek-harness\default-workspace')) { $target = $p.Name; break }
352
+ }
353
+ if (-not $target) { Log '本机没有名为 default-workspace 的工作区,跳过默认工作区校正'; return }
354
+ }
355
+
356
+ $targetEntry = $tables.PSObject.Properties[$target].Value
357
+ if ($cur -eq $target) { Log ("默认工作区已经是 {0}({1}),不动" -f (Get-NormPath ([string]$targetEntry.path)), $target); return }
358
+
359
+ $stamp = (Get-Date).ToString('yyyyMMddHHmmss')
360
+ Copy-Item -LiteralPath $reg -Destination ($reg + '.bak-' + $stamp) -Force
361
+ $obj.global.defaultWorkspaceId = $target
362
+ $text = (($obj | ConvertTo-Json -Depth 12) -replace "`r`n", "`n") + "`n"
363
+ [IO.File]::WriteAllText($reg, $text, (New-Object Text.UTF8Encoding($false)))
364
+
365
+ # 回读校验:值改对了、工作区条数没变,才算成功;否则静默保持原样会让「新会话落在哪」继续不对。
366
+ $back = Get-Content -LiteralPath $reg -Raw -Encoding UTF8 | ConvertFrom-Json
367
+ $countBefore = @($tables.PSObject.Properties).Count
368
+ $countAfter = @($back.tables.workspaces.PSObject.Properties).Count
369
+ if ([string]$back.global.defaultWorkspaceId -ne $target -or $countAfter -ne $countBefore) {
370
+ Log ("默认工作区写入后校验不通过({0} 个工作区,期望 {1} 个),已留备份 {2}" -f $countAfter, $countBefore, ($reg + '.bak-' + $stamp))
371
+ return
372
+ }
373
+ Log ("默认工作区:{0} → {1}({2}),重启后新会话落在 {3}" -f $cur, $target, [string]$targetEntry.title, [string]$targetEntry.path)
374
+ } catch {
375
+ Log ("默认工作区校正失败(不影响重启):{0}" -f $_.Exception.Message)
376
+ }
377
+ }
378
+
379
+ function RestartClient([switch]$SkipWatermark) {
380
+ $exe = $null
381
+ if ($AppRoot) { $candidate = Join-Path $AppRoot 'DeepSeek Harness.exe'; if (Test-Path -LiteralPath $candidate) { $exe = $candidate } }
382
+ if (-not $exe) {
383
+ try {
384
+ $reg = Get-ItemProperty -LiteralPath 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' -ErrorAction SilentlyContinue |
385
+ Where-Object { $_.DisplayName -match 'DeepSeek Harness' } | Select-Object -First 1
386
+ if ($reg -and $reg.InstallLocation) {
387
+ $candidate = Join-Path $reg.InstallLocation 'DeepSeek Harness.exe'
388
+ if (Test-Path -LiteralPath $candidate) { $exe = $candidate }
389
+ }
390
+ } catch { }
391
+ }
392
+ if ($exe) {
393
+ # 先定好重启后要落在哪个工作区:客户端已经完全退出,此刻写 workspace.json 才不会被回写盖掉。
394
+ Set-DefaultWorkspace
395
+ # 继承来的环境变量会让客户端「启动了但立刻退出、没有窗口」:
396
+ # ELECTRON_RUN_AS_NODE=1 → exe 以纯 node 模式跑,不建窗口,几秒后退出
397
+ # NODE_OPTIONS / NODE_PATH → 预加载或解析路径错乱
398
+ # 这些变量是宿主主进程给「自己派生的子进程」用的,客户端本身不需要,启动前清干净。
399
+ foreach ($name in @('ELECTRON_RUN_AS_NODE', 'ELECTRON_NO_ATTACH_CONSOLE', 'NODE_OPTIONS', 'NODE_PATH')) {
400
+ $value = [Environment]::GetEnvironmentVariable($name)
401
+ if ($value) {
402
+ Log ("清掉继承的环境变量 {0}={1}" -f $name, $value)
403
+ [Environment]::SetEnvironmentVariable($name, $null)
404
+ }
405
+ }
406
+ Log ("启动环境:RUN_AS_NODE={0} NODE_OPTIONS={1} DSH_HOME={2}" -f $env:ELECTRON_RUN_AS_NODE, $env:NODE_OPTIONS, $env:DSH_HOME)
407
+
408
+ # 为什么重试:Electron 刚退出时用户数据目录的锁还没释放干净,此时拉起的实例
409
+ # 会启动后立刻静默退出(实测:push 完 19:24:29「已启动」,19:24:57 一查 0 进程;
410
+ # 手动隔 11 秒再启就正常 6 进程)。所以启动后数一下进程,没活就等一会儿重试。
411
+ $ok = $false
412
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
413
+ Log ("重启客户端(第 {0} 次):{1}" -f $attempt, $exe)
414
+ $how = Start-Detached $exe
415
+ if (-not $how) { continue }
416
+ Log ("启动方式:{0}(不继承进度窗口的控制台与作业)" -f $how)
417
+ Start-Sleep -Seconds 5
418
+ $alive = @(Get-Process -Name 'DeepSeek Harness' -ErrorAction SilentlyContinue).Count
419
+ if ($alive -gt 0) { Log ("已启动(当前 {0} 个进程)" -f $alive); $ok = $true; break }
420
+ Log '启动后进程又退了(旧实例的锁可能还没释放),等 8 秒重试'
421
+ Start-Sleep -Seconds 8
422
+ }
423
+ if (-not $ok) { Finish 4 '重启失败(试了 3 次都没起来)' }
424
+
425
+ # 重启成功后再刷一次"上次同步时间"。apply/capture 刚写过的文件 mtime 落在这之前,
426
+ # 客户端起来 8 秒的首检会把它们当成"本机有未推送的新内容",立刻排一个空推送
427
+ #(实测:拉取重启后 19:46:04 又排了一次 push)。把分水岭推到重启之后,首检就安静了。
428
+ #
429
+ # 但**同步失败时绝不能刷**:分水岭一推,面板就认为"已同步",本机改动再也等不到提示,
430
+ # 等于把一次失败变成静默丢数据(2026-11-12 21:37 就是这么演的)。宁可按一次多余推送。
431
+ if (-not $SkipWatermark) {
432
+ try {
433
+ $stateFile = Join-Path $DshHome 'config-sync-state.json'
434
+ $state = @{ lastSyncAt = (Get-Date).ToString('o'); mode = $Mode; repo = $RepoRoot }
435
+ if (Test-Path -LiteralPath $stateFile) {
436
+ $old = Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json
437
+ $state = [ordered]@{
438
+ lastSyncAt = (Get-Date).ToString('o')
439
+ mode = $Mode
440
+ repo = $(if ($old.repo) { $old.repo } else { $RepoRoot })
441
+ head = $old.head
442
+ }
443
+ }
444
+ [IO.File]::WriteAllText($stateFile, ($state | ConvertTo-Json -Depth 4), (New-Object Text.UTF8Encoding $false))
445
+ Log '已刷新同步分水岭(重启后的首检不会误报待推送)'
446
+ } catch { Log ("刷新同步分水岭失败:{0}" -f $_.Exception.Message) }
447
+ } else {
448
+ Log '同步未成功:保留原分水岭,下次启动首检仍会提示本机有内容待推送'
449
+ }
450
+ } else {
451
+ Log '找不到 DeepSeek Harness.exe,跳过自动重启'
452
+ }
453
+ }
454
+
455
+ # ---------- 仅重启:不碰仓库、不装插件,纯粹为了让已经装好的新版本生效 ----------
456
+ # 0.3.7 起面板不再走这条(改为 update 模式:退出后安装)。保留它是为了兼容两种情况:
457
+ # 老的 install-live 已经把新版本覆盖进插件目录、但用户还没重启;以及只换界面语言/清缓存这类
458
+ # 不需要装东西的纯重启。做的事只有一件:等退出 → 用 explorer 代启拉回来。
459
+ if ($Mode -eq 'relaunch') {
460
+ Log '只重启客户端(新版本插件在重启后生效)'
461
+ Write-Result $true 0 '已重启客户端' $false
462
+ if ($Restart) { RestartClient }
463
+ Finish 0 '完成(已重启)'
464
+ }
465
+
466
+ # ---------- 仅更新模式:下载插件包 → 校验 sha256 → 备份旧版 → 覆盖安装 → 重启 ----------
467
+ # 更新的是**插件自己**(<AppRoot>\dsh-config-sync-<ver>\),不是配置仓库:
468
+ # 所以不能走 sync.ps1,也不能先 apply(那会把旧插件部署回去)。
469
+ # 覆盖发生在 DSH 已经退出之后 —— 这样运行中的面板不会被卸载,用户也就不会被弹回默认页。
470
+ if ($Mode -eq 'update') {
471
+ if (-not $PluginDir -or -not (Test-Path -LiteralPath $PluginDir)) { Finish 6 ('找不到插件目录:' + $PluginDir) }
472
+ if (-not $UpdateTgz) { Finish 6 '更新清单里没有 tgz 下载地址' }
473
+
474
+ $currentVersion = ''
475
+ try { $currentVersion = (Get-Content -LiteralPath (Join-Path $PluginDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).version } catch { }
476
+ Log ("插件目录:{0}(当前版本 {1})" -f $PluginDir, $currentVersion)
477
+ Log ("目标版本:{0}" -f $UpdateVersion)
478
+
479
+ $tar = Join-Path $env:SystemRoot 'System32\tar.exe'
480
+ if (-not (Test-Path -LiteralPath $tar)) { $tar = 'tar.exe' }
481
+
482
+ $tmp = Join-Path $env:TEMP ("dsh-plugin-{0}-{1}.tgz" -f $UpdateVersion, $stamp)
483
+ if (Test-Path -LiteralPath $UpdateTgz -PathType Leaf) {
484
+ # 宿主在 DSH 运行期只做了「下载 + 校验」,包已经在暂存目录里(面板的
485
+ # 「下载更新 → 重启并安装」就是这个流程)。这里直接用,不再重复下载。
486
+ Log ("使用已下载的安装包:{0}({1:N0} 字节)" -f $UpdateTgz, (Get-Item -LiteralPath $UpdateTgz).Length)
487
+ try { Copy-Item -LiteralPath $UpdateTgz -Destination $tmp -Force } catch { $tmp = $UpdateTgz }
488
+ } else {
489
+ # 私有仓库:把 raw 链接换成 Gitee API 的 raw 端点并带 access_token(匿名 raw 会 403)
490
+ $fetchUrl = $UpdateTgz
491
+ if ($UpdateToken) {
492
+ # raw 链接 → API raw 端点;分支不能留在路径里,要改成 ref 参数
493
+ $m = [regex]::Match($UpdateTgz, '^https://gitee\.com/([^/]+)/([^/]+)/raw/([^/]+)/(.+)$')
494
+ if ($m.Success) {
495
+ $fetchUrl = ("https://gitee.com/api/v5/repos/{0}/{1}/raw/{2}?ref={3}" -f $m.Groups[1].Value, $m.Groups[2].Value, $m.Groups[4].Value, $m.Groups[3].Value)
496
+ }
497
+ $sep = if ($fetchUrl.Contains('?')) { '&' } else { '?' }
498
+ $fetchUrl = "$fetchUrl${sep}access_token=$([uri]::EscapeDataString($UpdateToken))"
499
+ }
500
+ Log ("下载安装包:{0}{1}" -f $UpdateTgz, $(if ($UpdateToken) { '(私有仓库,带令牌)' } else { '' }))
501
+ $downloadError = $null
502
+ try {
503
+ Invoke-WebRequest -Uri $fetchUrl -OutFile $tmp -UseBasicParsing -TimeoutSec 180
504
+ } catch {
505
+ $downloadError = $_.Exception.Message
506
+ }
507
+ if ($downloadError -or -not (Test-Path -LiteralPath $tmp)) {
508
+ $msg = "插件更新失败:下载安装包失败({0})" -f $(if ($downloadError) { $downloadError } else { '文件没有落盘' })
509
+ Log $msg
510
+ Write-Result $false 7 $msg $false
511
+ Finish 7 '更新失败:下载失败'
512
+ }
513
+ Log ("已下载 {0:N0} 字节:{1}" -f (Get-Item -LiteralPath $tmp).Length, $tmp)
514
+ }
515
+
516
+ if ($UpdateSha256) {
517
+ $hash = (Get-FileHash -LiteralPath $tmp -Algorithm SHA256).Hash.ToLower()
518
+ Log ("sha256:{0}" -f $hash)
519
+ if ($hash -ne $UpdateSha256.ToLower()) {
520
+ Write-Result $false 7 '插件更新失败:安装包 sha256 校验不通过(可能没下载全或被改动)' $false
521
+ Finish 7 '更新失败:sha256 不符'
522
+ }
523
+ Log 'sha256 校验通过'
524
+ }
525
+
526
+ $stage = Join-Path $env:TEMP ("dsh-plugin-stage-" + $stamp)
527
+ $stageError = $null
528
+ try {
529
+ if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force }
530
+ New-Item -ItemType Directory -Path $stage -Force | Out-Null
531
+ & $tar -xzf $tmp -C $stage *>&1 | ForEach-Object { Log ([string]$_) }
532
+ if ($LASTEXITCODE -ne 0) { throw ("解包失败,退出码 {0}" -f $LASTEXITCODE) }
533
+ $payload = Join-Path $stage 'package'
534
+ if (-not (Test-Path -LiteralPath $payload)) { throw '安装包结构不对(里面没有 package 目录)' }
535
+ $newVersion = (Get-Content -LiteralPath (Join-Path $payload 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).version
536
+ if ($UpdateVersion -and $newVersion -ne $UpdateVersion) { throw ("安装包里的版本是 {0},与清单 {1} 不一致" -f $newVersion, $UpdateVersion) }
537
+ } catch { $stageError = $_.Exception.Message }
538
+ if ($stageError) {
539
+ Log ("解包/校验失败:{0}" -f $stageError)
540
+ Write-Result $false 7 ("插件更新失败:" + $stageError) $false
541
+ Finish 7 '更新失败:安装包有问题'
542
+ }
543
+
544
+ # 装之前先整目录备份:写坏了能手动拷回去(不给自动回滚,是因为回滚本身也要覆盖安装)
545
+ $backup = Join-Path (Join-Path $DshHome 'backups') ("plugin-{0}-{1}" -f $currentVersion, $stamp)
546
+ try {
547
+ New-Item -ItemType Directory -Path (Split-Path -Parent $backup) -Force | Out-Null
548
+ Copy-Item -LiteralPath $PluginDir -Destination $backup -Recurse -Force
549
+ Log ("旧版已备份:{0}" -f $backup)
550
+ } catch { Log ("备份旧版失败(继续安装):{0}" -f $_.Exception.Message) }
551
+
552
+ Log '覆盖安装…'
553
+ $installError = $null
554
+ try {
555
+ foreach ($it in @(Get-ChildItem -LiteralPath $payload -Force)) {
556
+ Copy-Item -LiteralPath $it.FullName -Destination $PluginDir -Recurse -Force
557
+ }
558
+ $installed = (Get-Content -LiteralPath (Join-Path $PluginDir 'package.json') -Raw -Encoding utf8 | ConvertFrom-Json).version
559
+ Log ("安装完成,插件目录现在指向版本 {0}" -f $installed)
560
+ } catch { $installError = $_.Exception.Message }
561
+ if ($installError) {
562
+ Write-Result $false 7 ("插件更新失败:写入失败(" + $installError + "),旧版备份在 " + $backup) $false
563
+ Finish 7 '更新失败:写入失败'
564
+ }
565
+
566
+ Remove-Item -LiteralPath $tmp -Force -ErrorAction SilentlyContinue
567
+ Remove-Item -LiteralPath $stage -Recurse -Force -ErrorAction SilentlyContinue
568
+ Write-Result $true 0 ("插件已更新到 " + $UpdateVersion + "(重启后生效)") $false
569
+ if ($Restart) { RestartClient }
570
+ Finish 0 ('完成(插件已更新到 ' + $UpdateVersion + ')')
571
+ }
572
+
573
+ # ---------- 找 sync.ps1(插件自带优先,仓库副本兜底) ----------
574
+ <#
575
+ 仓库里的 sync.ps1 是随配置仓库一起同步的一份副本,插件升级后它可能还停在旧版;
576
+ 旧版里没有冲突清单、没有 exit 6,pull 会被退回「直接 git pull → 失败就 reset 回滚」,
577
+ 面板上选好的「用本机 / 用云端」就永远不会被消费(真实踩过:18 项全选云端却拉不下来)。
578
+ 所以顺序反过来:先插件 runtime,再 AppRoot 下最新安装的插件,最后才是仓库那份。
579
+ #>
580
+ function Find-PluginScript([string]$name = 'sync.ps1') {
581
+ if ($PluginDir) {
582
+ $p = Join-Path $PluginDir ('runtime\' + $name)
583
+ if (Test-Path -LiteralPath $p) { return $p }
584
+ }
585
+ if ($PSScriptRoot) {
586
+ $p = Join-Path $PSScriptRoot $name
587
+ $isRepoCopy = $false
588
+ if ($RepoRoot) {
589
+ try {
590
+ $a = (Resolve-Path -LiteralPath $PSScriptRoot).Path
591
+ $b = (Resolve-Path -LiteralPath $RepoRoot).Path
592
+ if ($a -eq $b) { $isRepoCopy = $true }
593
+ } catch { }
594
+ }
595
+ if ((Test-Path -LiteralPath $p) -and -not $isRepoCopy) { return $p }
596
+ }
597
+ if ($AppRoot) {
598
+ $cands = @(Get-ChildItem -LiteralPath $AppRoot -Directory -Filter 'dsh-config-sync*' -ErrorAction SilentlyContinue |
599
+ Where-Object { -not $_.Name.EndsWith('.old') } | Sort-Object LastWriteTime -Descending)
600
+ foreach ($cand in $cands) {
601
+ $p = Join-Path $cand.FullName ('runtime\' + $name)
602
+ if (Test-Path -LiteralPath $p) { return $p }
603
+ }
604
+ }
605
+ return $null
606
+ }
607
+
608
+ # ---------- restore 模式:执行体是 restore.ps1,不走 sync.ps1 ----------
609
+ <#
610
+ 为什么要单独一条分支:还原不动仓库、也不跑 apply,靠的是 restore.ps1。
611
+ 和 pull 的区别只在「执行体 + 参数」,其余全部沿用同一套(互斥锁、结果文件、日志、自动重启),
612
+ 这样面板上的「立即还原」和「立即拉取」在体验上就是同一件事。
613
+ #>
614
+ if ($Mode -eq 'restore') {
615
+ $restore = Find-PluginScript 'restore.ps1'
616
+ if (-not $restore -and $RepoRoot) { $c = Join-Path $RepoRoot 'restore.ps1'; if (Test-Path -LiteralPath $c) { $restore = $c } }
617
+ if (-not $restore) { Log '找不到 restore.ps1(插件 runtime 和仓库都没有),放弃'; Finish 3 '缺 restore.ps1' }
618
+ if (-not $RepoRoot) { $RepoRoot = Split-Path -Parent $restore }
619
+ Log ("执行体:{0}" -f $restore)
620
+ if ($BackupDir) { Log ("目标快照:{0}" -f $BackupDir) } else { Log '未指定快照,由 restore.ps1 自己取最新一份' }
621
+
622
+ $rargs = @{
623
+ RepoRoot = $RepoRoot
624
+ DshHome = $DshHome
625
+ Force = $true
626
+ }
627
+ # 只有 profile 快照是「时点还原」:插件/会话备份只做「备份当前 → 写回」,不撤走任何东西
628
+ if ($SnapshotKind -eq 'profile') { $rargs['RollbackToPoint'] = $true }
629
+ else {
630
+ $rargs['SnapshotKind'] = $SnapshotKind
631
+ Log ("备份类型:{0}" -f $SnapshotKind)
632
+ }
633
+ if ($AppRoot) { $rargs['AppRoot'] = $AppRoot }
634
+ if ($BackupDir) { $rargs['BackupDir'] = $BackupDir }
635
+ # 插件回滚要知道写回哪个目录:优先面板传的 $PluginDir,否则交给 restore.ps1 自己按 AppRoot 探测
636
+ if ($SnapshotKind -eq 'plugin' -and $PluginDir) { $rargs['PluginDir'] = $PluginDir }
637
+
638
+ # 返回码可信性与 sync 分支同一套规矩:压哨兵 → try/catch 记日志 → 没跑完即失败
639
+ $LASTEXITCODE = -1
640
+ $invokeOk = $false
641
+ try {
642
+ & $restore @rargs *>&1 | ForEach-Object { Log ([string]$_) }
643
+ $invokeOk = $true
644
+ } catch {
645
+ Log ('执行体调用异常:{0}' -f $_.Exception.Message)
646
+ if ($_.InvocationInfo) { Log (' 位置:{0}' -f (($_.InvocationInfo.PositionMessage) -replace "`r?`n", ' ')) }
647
+ if ($_.ScriptStackTrace) { Log (' 堆栈:{0}' -f (($_.ScriptStackTrace) -replace "`r?`n", ' ')) }
648
+ }
649
+ $code = $LASTEXITCODE
650
+ if (-not $invokeOk) {
651
+ if ($null -eq $code -or $code -le 0) { $code = 1 }
652
+ Log '执行体没有正常跑完,本次按失败处理'
653
+ } elseif ($null -eq $code) {
654
+ $code = 0
655
+ }
656
+ Log ("restore.ps1 还原退出码:{0}" -f $code)
657
+
658
+ $okText = switch ($SnapshotKind) {
659
+ 'plugin' { '插件已回滚到所选备份;回滚前的插件整份留在 backups\plugin-<版本>-<时间戳>,可再回滚一次' }
660
+ 'session' { '会话目录已还原到所选备份;同名目录先前的状态留在 backups\session-<时间戳>' }
661
+ default { '配置已还原到所选快照;快照之后新增的文件与插件已移入 manual 备份,随时可再还原' }
662
+ }
663
+ $failText = switch ($SnapshotKind) {
664
+ 'plugin' { '插件回滚失败:详见日志;回滚前的插件状态已整份留在 backups\plugin-<版本>-<时间戳>' }
665
+ 'session' { '会话还原失败:详见日志;同名目录先前的状态已留在 backups\session-<时间戳>' }
666
+ default { '还原失败:详见日志;还原前的状态已整份留在 backups\manual-<时间戳>,可再还原一次' }
667
+ }
668
+ if ($code -ne 0) {
669
+ Write-Result $false $code $failText $false
670
+ } else {
671
+ Write-Result $true 0 $okText $false
672
+ }
673
+ if ($Restart) { RestartClient -SkipWatermark:($code -ne 0) }
674
+ if ($code -ne 0) { Finish 5 '还原失败,请打开日志核对' }
675
+ Finish 0 '完成(已还原)'
676
+ }
677
+
678
+ $sync = Find-PluginScript 'sync.ps1'
679
+ if (-not $sync -and $RepoRoot) { $candidate = Join-Path $RepoRoot 'sync.ps1'; if (Test-Path -LiteralPath $candidate) { $sync = $candidate } }
680
+ if (-not $sync) { Log '找不到 sync.ps1(插件 runtime 和仓库都没有),放弃'; Finish 3 '缺 sync.ps1' }
681
+ # 找到了也可能已经不可用(安装覆盖到一半、目录被移走):真正调用前再确认一次文件在
682
+ if (-not (Test-Path -LiteralPath $sync)) { Log ('执行体文件不存在:{0}' -f $sync); Finish 3 '缺 sync.ps1' }
683
+ if (-not $RepoRoot) { $RepoRoot = Split-Path -Parent $sync }
684
+ Log ("执行体:{0}" -f $sync)
685
+
686
+ $syncArgs = @{
687
+ Action = $Mode
688
+ RepoRoot = $RepoRoot
689
+ DshHome = $DshHome
690
+ Force = $true
691
+ }
692
+ if ($AppRoot) { $syncArgs['AppRoot'] = $AppRoot }
693
+
694
+ # ---------- pull 前留一张底:HEAD + 备份快照清单 ----------
695
+ $git = Get-GitExe
696
+ $headBefore = ''
697
+ $backupRoot = Join-Path $DshHome 'backups'
698
+ $backupsBefore = @()
699
+ if ($Mode -eq 'pull') {
700
+ if ($git) {
701
+ $headBefore = (& $git -C $RepoRoot rev-parse HEAD 2>$null | Out-String).Trim()
702
+ Log ("拉取前 HEAD:{0}" -f $headBefore)
703
+ } else {
704
+ Log '找不到 git.exe,失败时将无法回滚仓库(只能回滚配置)'
705
+ }
706
+ if (Test-Path -LiteralPath $backupRoot) {
707
+ $backupsBefore = @(Get-ChildItem -LiteralPath $backupRoot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like 'config-*' } | Select-Object -ExpandProperty FullName)
708
+ }
709
+ }
710
+
711
+ # ---------- 执行 ----------
712
+ # 这一步的返回码必须自己保证可信。踩过的坑:& $sync 没真正跑起来时(执行体被覆盖/占用、
713
+ # 脚本自身抛终止错误),PowerShell 只把红字喷到控制台,而 $LASTEXITCODE 仍是上一条命令
714
+ # 残留的 0 —— 于是整次同步被当成成功:结果写 ok:true、分水岭被刷新,面板从此不再提示
715
+ # 「待推送」,本机改动静默滞留(2026-11-12 21:37 实测,控制台报
716
+ # 「管道元素中的 & 后面的表达式生成无效的对象」,日志里却一条证据都没有)。
717
+ # 所以:先压哨兵值 → 用 try/catch 兜住终止错误并写进日志 → 没跑完一律判失败。
718
+ $LASTEXITCODE = -1
719
+ $invokeOk = $false
720
+ try {
721
+ & $sync @syncArgs *>&1 | ForEach-Object { Log ([string]$_) }
722
+ $invokeOk = $true
723
+ } catch {
724
+ Log ('执行体调用异常:{0}' -f $_.Exception.Message)
725
+ if ($_.InvocationInfo) { Log (' 位置:{0}' -f (($_.InvocationInfo.PositionMessage) -replace "`r?`n", ' ')) }
726
+ if ($_.ScriptStackTrace) { Log (' 堆栈:{0}' -f (($_.ScriptStackTrace) -replace "`r?`n", ' ')) }
727
+ }
728
+ $code = $LASTEXITCODE
729
+ if (-not $invokeOk) {
730
+ if ($null -eq $code -or $code -le 0) { $code = 1 }
731
+ Log '执行体没有正常跑完,本次按失败处理(不写成功结果、不刷新分水岭)'
732
+ } elseif ($null -eq $code) {
733
+ $code = 0
734
+ }
735
+ Log ("sync.ps1 {0} 退出码:{1}" -f $Mode, $code)
736
+
737
+ $failed = ($code -ne 0)
738
+
739
+ # ---------- 失败自动回滚(仅 pull) ----------
740
+ $conflictPending = ($code -eq 6)
741
+ $restored = $false
742
+ if ($failed -and $Mode -eq 'pull' -and (-not $conflictPending)) {
743
+ Log '拉取失败:开始自动回滚'
744
+ # 1) 仓库回到拉取前的提交(pull 可能已经把仓库更新了,失败的是后面的 apply)
745
+ if ($git -and $headBefore) {
746
+ & $git -C $RepoRoot reset --hard $headBefore *>&1 | ForEach-Object { Log ([string]$_) }
747
+ if ($LASTEXITCODE -eq 0) { Log ("仓库已回滚到 {0}" -f $headBefore) } else { Log ("仓库回滚失败(退出码 {0}),继续回滚配置" -f $LASTEXITCODE) }
748
+ }
749
+ # 2) 配置用「这次动作中新出现的快照」还原(apply 在写盘前必先建一份)
750
+ $snapshot = $null
751
+ if (Test-Path -LiteralPath $backupRoot) {
752
+ $all = @(Get-ChildItem -LiteralPath $backupRoot -Directory -ErrorAction SilentlyContinue | Where-Object { $_.Name -like 'config-*' } | Sort-Object Name -Descending)
753
+ if ($all.Count -gt 0) {
754
+ $newest = $all[0].FullName
755
+ # 优先用「这次动作中新出现的」快照;没有新的(说明 apply 没走到建快照)就用最新那份,
756
+ # 反正都是本次动作内唯一的候选,多一层数组长度判断是死代码,已删。
757
+ $snapshot = $newest
758
+ if ($backupsBefore -contains $newest) { Log '这次动作没新建快照,退回用最新一份已有快照' }
759
+ }
760
+ }
761
+ if ($snapshot) {
762
+ Log ("用快照还原配置:{0}" -f $snapshot)
763
+ $restore = Join-Path $RepoRoot 'restore.ps1'
764
+ if (-not (Test-Path -LiteralPath $restore)) { $restore = Join-Path $PSScriptRoot 'restore.ps1' }
765
+ if (Test-Path -LiteralPath $restore) {
766
+ $rargs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; BackupDir = $snapshot; Force = $true }
767
+ if ($AppRoot) { $rargs['AppRoot'] = $AppRoot }
768
+ & $restore @rargs *>&1 | ForEach-Object { Log ([string]$_) }
769
+ if ($LASTEXITCODE -eq 0) { $restored = $true } else { Log ("还原失败(退出码 {0}),请手动处理" -f $LASTEXITCODE) }
770
+ Log ("配置还原退出码:{0}" -f $LASTEXITCODE)
771
+ } else {
772
+ Log '找不到 restore.ps1,无法自动还原配置'
773
+ }
774
+ } else {
775
+ Log '没有可用快照(apply 可能还没开始写盘),跳过配置还原'
776
+ }
777
+ if ($restored) { Log '已回滚到拉取前的状态' } else { Log '回滚不完整,请打开日志核对' }
778
+ }
779
+
780
+ # ---------- 写结果文件(客户端下次启动弹提示用) ----------
781
+ if ($Mode -eq 'pull') {
782
+ if ($conflictPending) {
783
+ # 冲突不是"失败":本机文件挡住了快进,仓库没动、配置没动,等用户在面板里逐项选完再拉
784
+ Write-Result $false 6 '拉取被本机文件挡住:面板「同步冲突」里逐项选「用本机 / 用云端」后再拉取' $false
785
+ } elseif ($failed) {
786
+ Write-Result $false $code ("拉取失败" + $(if ($restored) { ',已自动还原上一次的配置' } else { ',且未能完整还原' }) + ';详见日志') $restored
787
+ } else {
788
+ Write-Result $true 0 '云端配置已拉取到本机' $false
789
+ }
790
+ } else {
791
+ if ($failed) { Write-Result $false $code '推送失败(改动还在本地,下次再推)' $false }
792
+ else { Write-Result $true 0 '本机改动已推送到云端' $false }
793
+ }
794
+
795
+ # 动作做完、结果已落盘,再把客户端拉起来(更新模式在上面自己调过 RestartClient 了)
796
+ # 失败时刻意不刷分水岭:否则面板会以为已经同步过,本机改动再也等不到「待推送」提示。
797
+ if ($Restart) { RestartClient -SkipWatermark:$failed }
798
+
799
+ if ($failed) {
800
+ # 文案按动作分开写(旧版一律写「pull 已尝试回滚」,push 失败时也这么报,误导排查)
801
+ if ($Mode -eq 'pull') {
802
+ if ($conflictPending) { Finish 6 '拉取待处理:本机有文件与云端冲突,打开面板「同步冲突」选择' }
803
+ elseif ($restored) { Finish 5 '同步失败:拉取失败,已回滚到同步前的配置' }
804
+ else { Finish 5 '同步失败:拉取失败,回滚不完整,请打开日志核对' }
805
+ } else {
806
+ Finish 5 '同步失败:推送失败,改动仍在本地,下次启动可再推'
807
+ }
808
+ }
809
+ Finish 0 ('完成' + $(if ($Mode -eq 'pull') { '(已拉取)' } else { '(已推送)' }))