dsh-chat-history-sync 0.12.81 → 0.12.83

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.12.83
4
+
5
+ - 附件:会话无新增/更新时也扫描数据集缺失附件,重新拉详情拿新 signed_path 重试下载
6
+ - 附件:同步摘要显示部分附件下载失败,不再只写 sync.log
7
+ - 账号:设置镜像改为增量合并,config 中未列出的账号不再被 5 秒 tick 抹掉
8
+ - 登录:登录进行中禁止触发「更新聊天记录」,避免杀进程中断登录
9
+ - 更新:20 秒预检期间检测到新回复会写 cancel 标记,杀进程前再次退出
10
+ - 更新:安装脚本轮询重启结果并写 restartOk,宿主提示自动重启失败
11
+ - 状态:重启后从 install-result 提前显示更新完成,整理旧报告不覆盖成功态
12
+ - 冷却:15 分钟锁期间点击显示剩余分钟,不再静默忽略
13
+ - 账号:用 token 的 users/current 补齐昵称/头像,API 字段和 localStorage 双路读取
14
+
15
+ ## 0.12.82
16
+
17
+ - 修复主按钮 hover 时文字消失:显式设置 hover 背景与前景色
18
+ - 安装成功后不再被启动 12 秒清理定时器提前清掉,左下角能显示成功状态
19
+ - 安装/导入完成后强制刷新「DSH 更新报告」,不再沿用旧报告内容
20
+
3
21
  ## 0.12.81
4
22
 
5
23
  - 修复更新用 PowerShell 脚本硬编码作者本机 `D:\Software\nodejs\node.exe` 的问题;改为写入当前运行 Node 的绝对路径并显式校验,PATH 中没有 node 的机器也能完成导入
@@ -888,3 +906,5 @@
888
906
 
889
907
 
890
908
 
909
+
910
+
package/client/client.js CHANGED
@@ -66,7 +66,7 @@ let autoAction = '';
66
66
  .msx-btn:hover:not(:disabled){background:var(--dsw-alias-bg-layer-2)}
67
67
  .msx-btn:disabled{opacity:.45;cursor:default}
68
68
  .msx-btn-primary{background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-base);border:1px solid transparent;font-weight:600}
69
- .msx-btn-primary:hover:not(:disabled){opacity:.88}
69
+ .msx-btn-primary:hover:not(:disabled){opacity:1;background:color-mix(in srgb,var(--dsw-alias-label-primary) 86%,var(--dsw-alias-bg-base));color:var(--dsw-alias-bg-base)!important}
70
70
  .msx-btn-ghost{background:transparent;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-primary)}
71
71
  .msx-btn-ghost:hover:not(:disabled){border-color:var(--dsw-alias-border-l2)}
72
72
  .msx-btn-danger{background:transparent;border:none;color:var(--dsw-alias-state-error-primary);padding:7px 6px}
@@ -1,4 +1,4 @@
1
- # 发布候选状态(0.12.81)
1
+ # 发布候选状态(0.12.83)
2
2
 
3
3
  ## 结论
4
4
 
@@ -9,7 +9,7 @@
9
9
 
10
10
  ```text
11
11
  TESTS PASSED
12
- version audit passed: 329 points / 185 versions
12
+ version audit passed: 341 points / 187 versions
13
13
  package file checks passed (41 files)
14
14
  runtime version match: 0.12.81
15
15
  test:e2e: cancel/install controls present, cancel process-tree passed
@@ -77,3 +77,5 @@ test:sandbox: ok=true code=0
77
77
 
78
78
 
79
79
 
80
+
81
+
@@ -1,10 +1,10 @@
1
- # 0.9.0 → 0.12.81 全版本复盘与 300 轮迭代基线
1
+ # 0.9.0 → 0.12.83 全版本复盘与 300 轮迭代基线
2
2
 
3
3
  ## 1. 复盘范围
4
4
 
5
5
  本复盘不只覆盖 0.12.30 之后。
6
6
 
7
- 从 0.9.0 公开改名开始,到 0.12.81,共 **185 个版本、329 条改动点**,全部抽取到:
7
+ 从 0.9.0 公开改名开始,到 0.12.83,共 **187 个版本、341 条改动点**,全部抽取到:
8
8
 
9
9
  [VERSION_AUDIT.md](VERSION_AUDIT.md)
10
10
 
@@ -135,3 +135,5 @@
135
135
 
136
136
 
137
137
 
138
+
139
+
@@ -7,7 +7,7 @@
7
7
  - `TODO`:未执行
8
8
  - `HOLD`:发布动作暂停,全部验证前不执行
9
9
 
10
- 当前基线:0.12.79 已加载;npm latest 已是 0.12.79(在“暂停发布”指令前已批准,需回退标签时必须由用户提供 OTP)。
10
+ 当前基线:本地/远程已有 0.12.83 候选(未发布);清单按用户复核后的 91 项统计:76 PASS / 7 PARTIAL / 7 TODO / 1 HOLD。A7 发布暂停仍有效。
11
11
 
12
12
  ## A. 发布与版本
13
13
 
@@ -50,7 +50,7 @@
50
50
  | C10 | 断网/超时 | 故障注入 | 失败可重试,不破坏数据 | PASS(mock timeout 注入:失败、dataset 保持空) |
51
51
  | C11 | 部分账号失败 | 故障注入 | 成功账号保留、失败明确 | PASS(mock 三账号:good 无变化,bad/timeout 失败,三个 dataset 均未变) |
52
52
  | C12 | 401/403/风控 | 故障注入 | 提示重新登录 | PASS(假 token 实跑:API 40003 INVALID_TOKEN,engine 输出失败,dataset 未变) |
53
- | C13 | token 过期后恢复 | 真实/故障 | 重新登录后可同步 | PASS(真实退出蓝糕 Edge → API 40003 INVALID_TOKEN/部分失败 → 重新登录 → 12:39:56 两账号同步成功,无数据丢失) |
53
+ | C13 | token 过期后恢复 | 真实/故障 | 重新登录后可同步 | TODO(需在 0.12.83 上重跑 token 过期恢复) |
54
54
  | C14 | 侧栏同步按钮 revision 冲突自动重试 | 行为/真实 UI | 不直接显示「重试」 | PARTIAL(已加 describe+重试;重启后待真实点击) |
55
55
 
56
56
  ## D. 更新、取消、活动回复
@@ -79,7 +79,7 @@
79
79
  | E4 | 报告内容为变更日志,分类索引可选 | 真实报告/测试 | 默认不再附全量分类目录;分类文件保留 | PASS(报告已精简;分类文件 `history/_raw/分类目录.md` 可选) |
80
80
  | E5 | 每条 50–100 字摘要 | catalog 测试 | 长度在范围 | PASS |
81
81
  | E6 | 同名分组提示 | UI/报告 | 3 组同名可见 | PASS |
82
- | E7 | 报告写入失败 | 故障注入 | `report_failed` 可重试 | PASS(受控报告故障时真实出现 report_failed / 更新完成,但报告未生成;见 E8) |
82
+ | E7 | 报告写入失败 | 故障注入 | `report_failed` 可重试 | PARTIAL(0.12.83 报告/更新链路改动后需重跑报告失败重试) |
83
83
  | E8 | 重试后成功 | UI | 状态回 succeeded | PASS(受控注入 _verifyTestReportFailure:report_failed → 关闭故障 → 重试成功,success 日志出现;钩子已移除) |
84
84
  | E9 | 报告会话被删除后重建 | 故障注入 | 不产生多份 | PARTIAL(needsNewReportSession 行为测试 + 宿主重建;真实删除会话待验) |
85
85
 
@@ -144,7 +144,7 @@
144
144
  | J1 | 干净 npm 安装 | temp install | 成功 | PASS |
145
145
  | J2 | dsh plugin add | 真实 CLI | 成功 | PASS(0.12.79 CLI 安装成功;0.12.80 npm pack + 临时目录 npm install,apply 为 function) |
146
146
  | J3 | DSH 版本兼容 | 多版本 | 启动正常 | PARTIAL(DSH CLI 0.2.2-rc.5 满足 engine;未多版本启动) |
147
- | J4 | Windows 10/11 | 多机 | 启动正常 | PASS(真实第二台 Windows 11 机器:DSH 已安装并登录蓝糕,界面正常) |
147
+ | J4 | Windows 10/11 | 多机 | 启动正常 | PARTIAL(Windows 11 远程已安装并登录;0.12.83 尚需远程回归) |
148
148
  | J5 | 杀毒/权限 | 故障注入 | 可诊断 | TODO |
149
149
  | J6 | 磁盘满 | 故障注入 | 不破坏数据 | TODO |
150
150
  | J7 | 低内存 | 故障注入 | 不崩溃 | TODO |
@@ -1,12 +1,24 @@
1
- # 全版本逐点审计(0.9.0 → 0.12.81)
1
+ # 全版本逐点审计(0.9.0 → 0.12.83)
2
2
 
3
- 本文件由 CHANGELOG.md 自动抽取,覆盖 185 个版本、329 条改动点。
3
+ 本文件由 CHANGELOG.md 自动抽取,覆盖 187 个版本、341 条改动点。
4
4
  每条都需要在后续轮次中逐项核对:当前代码是否仍有该行为、是否有测试、是否有回归风险。
5
5
 
6
6
  状态说明:待审计 尚未逐条核对;保留 已确认仍需要;修复 已发现残留并修复;退役 已不再适用。
7
7
 
8
8
  | # | 版本 | 领域 | 改动点 | 状态 |
9
9
  |---:|---|---|---|---|
10
+ | 341 | 0.12.83 | 附件 | 无新增/更新时也重试数据集缺失附件,拉新 signed_path | 修复(0.12.83,attachment retry) |
11
+ | 340 | 0.12.83 | 账号 | token users/current 补齐昵称/头像,双路读取 | 修复(0.12.83,profile fallback) |
12
+ | 339 | 0.12.83 | UI/状态 | 重启后提前显示更新完成,整理旧报告不覆盖成功态 | 修复(0.12.83,success boot) |
13
+ | 338 | 0.12.83 | 更新 | 杀进程前再次检查活动回复并写 cancel 标记 | 修复(0.12.83,turn guard) |
14
+ | 337 | 0.12.83 | 登录 | 登录进行中禁止更新,避免中断登录 | 修复(0.12.83,login guard) |
15
+ | 336 | 0.12.83 | 更新 | 安装脚本轮询重启结果并写 restartOk | 修复(0.12.83,restart verify) |
16
+ | 335 | 0.12.83 | 更新 | 15 分钟锁期间显示剩余冷却分钟 | 修复(0.12.83,cooldown feedback) |
17
+ | 334 | 0.12.83 | 附件 | 同步摘要显示部分附件下载失败 | 修复(0.12.83,attachment warning) |
18
+ | 333 | 0.12.83 | 账号 | 设置镜像增量合并,不再整组替换 config 账号 | 修复(0.12.83,account merge) |
19
+ | 332 | 0.12.82 | UI/交互 | 主按钮 hover 不再白字消失 | 修复(0.12.82,hover contrast) |
20
+ | 331 | 0.12.82 | UI/状态 | 安装成功后 12 秒清理定时器不再提前清掉成功状态 | 修复(0.12.82,success persistence) |
21
+ | 330 | 0.12.82 | 报告 | 安装/导入后强制刷新 DSH 更新报告 | 修复(0.12.82,report refresh after import) |
10
22
  | 329 | 0.12.81 | 安装 | 更新 PowerShell 不再硬编码作者 Node 路径,PATH 无 node 也能导入 | 修复(0.12.81,node-exe fallback) |
11
23
  | 317 | 0.12.80 | 报告/状态 | 报告写入成功后 flush/收尾异常不再误判「报告未生成」 | 修复(0.12.80,report flush) |
12
24
  | 318 | 0.12.80 | 报告/状态 | 无变化更新不追加报告,避免同步报告与更新报告重复 | 修复(0.12.80,no-change skip) |
@@ -341,3 +353,4 @@
341
353
 
342
354
 
343
355
 
356
+
@@ -117,7 +117,7 @@ try {
117
117
  const b = (me.data && (me.data.biz_data || me.data)) || {};
118
118
  let ui = {};
119
119
  try { ui = JSON.parse(localStorage.getItem('userInfo') || '{}') || {}; } catch (e) { ui = {}; }
120
- return { userId: b.id || b.user_id || '', nickname: ui.name || ui.nickname || ui.user_name || ui.userName || ui.nickName || '', avatarUrl: ui.avatar || ui.avatar_url || ui.avatarUrl || ui.head_url || ui.headUrl || '' };
120
+ return { userId: b.id || b.user_id || '', nickname: ui.name || ui.nickname || ui.user_name || ui.userName || ui.nickName || b.name || b.nickname || b.user_name || '', avatarUrl: ui.avatar || ui.avatar_url || ui.avatarUrl || ui.head_url || ui.headUrl || b.avatar_url || b.avatarUrl || b.avatar || b.head_url || '' };
121
121
  } catch (e) { return { userId: '', nickname: '', avatarUrl: '' }; }
122
122
  })(${JSON.stringify(tok)})`,
123
123
  awaitPromise: true,
@@ -88,8 +88,8 @@ try {
88
88
  try { ui = JSON.parse(localStorage.getItem('userInfo') || '{}') || {}; } catch (e) { ui = {}; }
89
89
  return {
90
90
  userId: b.id || b.user_id || '',
91
- nickname: ui.name || ui.nickname || ui.user_name || ui.userName || ui.nickName || '',
92
- avatarUrl: ui.avatar || ui.avatar_url || ui.avatarUrl || ui.head_url || ui.headUrl || '',
91
+ nickname: ui.name || ui.nickname || ui.user_name || ui.userName || ui.nickName || b.name || b.nickname || b.user_name || '',
92
+ avatarUrl: ui.avatar || ui.avatar_url || ui.avatarUrl || ui.head_url || ui.headUrl || b.avatar_url || b.avatarUrl || b.avatar || b.head_url || '',
93
93
  };
94
94
  } catch (e) { return { userId: '', nickname: '', avatarUrl: '' }; }
95
95
  }, tok).catch(() => ({ userId: '', nickname: '', avatarUrl: '' }));
@@ -179,9 +179,39 @@ function buildMessages(b) {
179
179
  const fresh = sessions.filter((s) => !known.has(s.id));
180
180
  const byId = new Map(ds.conversations.map((c) => [c.id, c]));
181
181
  const updated = sessions.filter((s) => byId.has(s.id) && (Number(s.updated_at) || 0) > (Number(byId.get(s.id).updated_at) || 0) + 5);
182
- console.log(`${label}: 总数 ${sessions.length},新增 ${fresh.length},更新 ${updated.length}`);
183
- if (!fresh.length && !updated.length) { summary.push(`${label}: 无变化`); continue; }
184
- const targets = [...fresh, ...updated];
182
+ // 已同步会话里可能有上次签名过期/下载失败而缺失的附件:即使会话本身没变,也要重新拉详情拿新 signed_path 再试
183
+ const retryIds = new Set();
184
+ if (!DRY && cfg.attachmentMode !== 'none') {
185
+ for (const c of ds.conversations) {
186
+ const convDir = path.join(acc.root, safe(c.title) || '未命名');
187
+ const convTag = crypto.createHash('sha256').update(String(acc.key) + '|' + String(c.id || '')).digest('hex').slice(0, 8);
188
+ let missing = false;
189
+ for (const m of c.messages || []) {
190
+ for (const f of m.files || []) {
191
+ if (cfg.attachmentMode === 'images' && !f.is_image) continue;
192
+ const id8 = String(f.id || '').replace(/^file-/, '').slice(0, 8);
193
+ const dest = path.join(convDir, convTag + '_' + id8 + '_' + safe(f.name));
194
+ const oldDest = path.join(convDir, id8 + '_' + safe(f.name));
195
+ let ok = false;
196
+ for (const p of [dest, oldDest]) {
197
+ try { if (fs.existsSync(p) && (!f.size || fs.statSync(p).size === f.size)) { ok = true; break; } } catch (e) {}
198
+ }
199
+ if (!ok) { missing = true; break; }
200
+ }
201
+ if (missing) break;
202
+ }
203
+ if (missing) retryIds.add(c.id);
204
+ }
205
+ }
206
+ const freshIds = new Set(fresh.map((s) => s.id));
207
+ const updatedIds = new Set(updated.map((s) => s.id));
208
+ const targetMap = new Map();
209
+ for (const s of [...fresh, ...updated]) targetMap.set(s.id, s);
210
+ for (const s of sessions) if (retryIds.has(s.id) && !targetMap.has(s.id)) targetMap.set(s.id, s);
211
+ const targets = [...targetMap.values()];
212
+ const retryOnlyCount = targets.filter((s) => !freshIds.has(s.id) && !updatedIds.has(s.id)).length;
213
+ console.log(`${label}: 总数 ${sessions.length},新增 ${fresh.length},更新 ${updated.length},附件重试 ${retryOnlyCount}`);
214
+ if (!targets.length) { summary.push(`${label}: 无变化`); continue; }
185
215
  let doneCount = 0;
186
216
  const totalCount = targets.length;
187
217
  const rebuilt = [];
@@ -202,7 +232,9 @@ function buildMessages(b) {
202
232
  if (!msgs.length && previous && (previous.messages || []).length) { fetchBad += 1; continue; }
203
233
  if (previous && msgs.length < (previous.messages || []).length) { fetchBad += 1; continue; }
204
234
  // updated_at 变了但消息内容没变(常见于服务端元数据刷新):不能当成真实更新
205
- if (previous) {
235
+ // 附件重试会话例外:正文没变也要继续下载缺失附件,并刷新 signed_path
236
+ const isRetryOnly = !freshIds.has(s.id) && !updatedIds.has(s.id);
237
+ if (previous && !isRetryOnly) {
206
238
  let same = false;
207
239
  try { same = JSON.stringify(msgs) === JSON.stringify(previous.messages || []); } catch (e) { same = false; }
208
240
  if (same) { noContent += 1; continue; }
@@ -266,7 +298,7 @@ function buildMessages(b) {
266
298
  continue;
267
299
  }
268
300
  }
269
- const changedNames = rebuilt.map((s) => {
301
+ const changedNames = rebuilt.filter((s) => freshIds.has(s.id) || updatedIds.has(s.id)).map((s) => {
270
302
  const old = byId.get(s.id);
271
303
  const n = Array.isArray(s.messages) ? s.messages.length : 0;
272
304
  const oldN = old && Array.isArray(old.messages) ? old.messages.length : 0;
@@ -274,7 +306,7 @@ function buildMessages(b) {
274
306
  return title ? title + '(' + (old ? '+' + Math.max(0, n - oldN) + ' 条' : '新增 ' + n + ' 条') + ')' : '';
275
307
  }).filter(Boolean);
276
308
  const namesText = changedNames.length ? ';会话:' + changedNames.slice(0, 5).join('、') + (changedNames.length > 5 ? ' 等 ' + changedNames.length + ' 个' : '') : '';
277
- summary.push(`${label}: 新增 ${fresh.length},更新 ${updated.length - noContent},附件 ${fOk} 成功${fBad ? '/' + fBad + ' 失败' : ''}${fNoSign ? ',' + fNoSign + ' 个旧附件无签名链接' : ''}${fetchBad ? ',' + fetchBad + ' 条抓取失败' : ''}${namesText}${DRY ? '(干跑未写入)' : ''}`);
309
+ summary.push(`${label}: 新增 ${fresh.length},更新 ${updated.length - noContent},附件 ${fOk} 成功${fBad ? '/' + fBad + ' 失败' : ''}${fNoSign ? ',' + fNoSign + ' 个旧附件无签名链接' : ''}${fetchBad ? ',' + fetchBad + ' 条抓取失败' : ''}${retryOnlyCount ? ',附件重试 ' + retryOnlyCount + ' 个会话' : ''}${namesText}${DRY ? '(干跑未写入)' : ''}`);
278
310
  await new Promise((r) => setTimeout(r, 600));
279
311
  }
280
312
  console.log('=== SUMMARY ===');
package/lib/index.js CHANGED
@@ -261,7 +261,8 @@ let cancelRequested = false;
261
261
  const scheduleLock = path.join(dataDir, 'install-schedule.lock');
262
262
  try {
263
263
  const st = nodeFs.statSync(scheduleLock);
264
- if (Date.now() - st.mtimeMs < 15 * 60 * 1000) return 'cancelled';
264
+ const age = Date.now() - st.mtimeMs;
265
+ if (age < 15 * 60 * 1000) return 'cooldown:' + Math.max(1, Math.ceil((15 * 60 * 1000 - age) / 60000));
265
266
  } catch (e) {}
266
267
  try { nodeFs.writeFileSync(scheduleLock, JSON.stringify({ at: Date.now() })); } catch (e) {}
267
268
  if (existsSync(cancelMarker)) {
@@ -284,6 +285,7 @@ let cancelRequested = false;
284
285
  '$log = ' + q(path.join(dataDir, 'install-public.log')),
285
286
  '"=== install start " + (Get-Date).ToString("o") + " ===" | Out-File -FilePath $log -Encoding utf8 -Append',
286
287
  'Start-Sleep -Seconds 20',
288
+ 'if (Test-Path $cancelFile) { Remove-Item $cancelFile -Force; "cancelled after precheck" | Out-File -FilePath $log -Encoding utf8 -Append; schtasks.exe /delete /TN DshSyncInstall2 /f | Out-Null; exit 0 }',
287
289
  '$cancelFile = ' + q(path.join(dataDir, 'install-cancel.json')),
288
290
  'if (Test-Path $cancelFile) { Remove-Item $cancelFile -Force; "cancelled" | Out-File -FilePath $log -Encoding utf8 -Append; schtasks.exe /delete /TN DshSyncInstall2 /f | Out-Null; exit 0 }',
289
291
  'taskkill.exe /IM "DeepSeek Harness.exe" /F | Out-Null',
@@ -304,7 +306,9 @@ let cancelRequested = false;
304
306
  '"exit=" + $installCode | Out-File -FilePath $log -Encoding utf8 -Append',
305
307
  '$installResult = @{ ok = ($installCode -eq 0); code = $installCode; at = (Get-Date).ToString("o"); log = $log } | ConvertTo-Json -Compress',
306
308
  '[IO.File]::WriteAllText($env:DSH_SYNC_INSTALL_RESULT, $installResult)',
307
- 'Start-Process -FilePath ' + q(process.execPath),
309
+ '$restartOk = $false',
310
+ 'try { $p = Start-Process -FilePath ' + q(process.execPath) + ' -PassThru; for ($i = 0; $i -lt 25; $i++) { Start-Sleep -Seconds 1; if (Get-Process -Id $p.Id -ErrorAction SilentlyContinue) { $restartOk = $true; break }; if (Get-Process -Name "DeepSeek Harness" -ErrorAction SilentlyContinue) { $restartOk = $true; break } } } catch {}',
311
+ 'if (-not $restartOk) { $failedResult = @{ ok = ($installCode -eq 0); code = $installCode; at = (Get-Date).ToString("o"); log = $log; restartOk = $false } | ConvertTo-Json -Compress; [IO.File]::WriteAllText($env:DSH_SYNC_INSTALL_RESULT, $failedResult) }',
308
312
  'schtasks.exe /delete /TN DshSyncInstall2 /f | Out-Null',
309
313
  ].join('\r\n') + '\r\n';
310
314
  const vbs = 'Set sh = CreateObject("WScript.Shell")\r\nsh.Run "powershell.exe -NoProfile -ExecutionPolicy Bypass -File """ & WScript.Arguments(0) & """", 0, False\r\n';
@@ -398,7 +402,7 @@ let cancelRequested = false;
398
402
  try { detail = await fsp.readFile(path.join(dataDir, '同步报告-full.md'), 'utf8'); } catch (e) {}
399
403
  if (!detail) { try { detail = await fsp.readFile(path.join(dataDir, '同步报告.md'), 'utf8'); } catch (e) {} }
400
404
  body = '# 🧠 DSH 更新报告\n\n时间:' + localTime() + '\n\n' + (detail ? detail.replace(/^# .*\n\n?/, '') : cfgGet('reportText', '')) + '\n\n---\n本报告由本地规则生成,不调用模型。\n';
401
- if (ws && !recentSyncReport && hasReportableChange(cfgGet('deltaText', ''))) reportOk = !!(await writeReport(ws, '🧠 DSH 更新报告', body));
405
+ if (ws && !recentSyncReport) reportOk = !!(await writeReport(ws, '🧠 DSH 更新报告', body));
402
406
  else reportOk = true;
403
407
  if (!hasReportableChange(cfgGet('deltaText', ''))) {
404
408
  try { nodeFs.appendFileSync(path.join(dataDir, 'settings.log'), new Date().toISOString() + ' update no-change; report skipped\n'); } catch (e) {}
@@ -406,9 +410,10 @@ let cancelRequested = false;
406
410
  } catch (e) {}
407
411
  if (reportOk) {
408
412
  const reportDelta = detail.split('\n').filter((line) => /^.+[::]\s*新增\s*\d+\s*\/\s*更新\s*\d+/.test(line)).join('\n');
409
- await publishPersistent({ installSucceeded: true, reportingAt: 0, statusText: '更新完成', reportText: body.slice(0, 12000), ...(reportDelta ? { deltaText: reportDelta.slice(0, 4000) } : {}) });
413
+ const restartFailed = !!(r && r.restartOk === false);
414
+ await publishPersistent({ installSucceeded: true, reportingAt: 0, statusText: restartFailed ? '更新完成,但自动重启失败,请手动打开 DSH' : '更新完成', reportText: body.slice(0, 12000), ...(reportDelta ? { deltaText: reportDelta.slice(0, 4000) } : {}) });
410
415
  try { nodeFs.appendFileSync(path.join(dataDir, 'settings.log'), new Date().toISOString() + ' update success state set reportOk=true\n'); } catch (e) {}
411
- setTimeout(() => { if (cfgGet('installSucceeded', false)) void publishPersistent(successLabelPatch()); }, SUCCESS_LABEL_TTL_MS);
416
+ if (!restartFailed) setTimeout(() => { if (cfgGet('installSucceeded', false)) void publishPersistent(successLabelPatch()); }, SUCCESS_LABEL_TTL_MS);
412
417
  setTimeout(() => { if (String(cfgGet('statusText', '')) === '更新完成') void publishPersistent({ statusText: '已同步' }); }, 8000);
413
418
  setTimeout(() => { if (cfgGet('installSucceeded', false) || cfgGet('importPhase') === 'succeeded') void publishPersistent(successExpiryPatch()); }, SUCCESS_TTL_MS);
414
419
  notify('聊天历史同步', '新对话已加入 DSH');
@@ -423,6 +428,17 @@ let cancelRequested = false;
423
428
  return true;
424
429
  } catch (e) {}
425
430
  }, 8000);
431
+ setTimeout(async () => {
432
+ try {
433
+ const resultPath = path.join(dataDir, 'install-result.json');
434
+ if (!existsSync(resultPath)) return;
435
+ if (Date.now() - nodeFs.statSync(resultPath).mtimeMs > 180000) return;
436
+ const r = JSON.parse(nodeFs.readFileSync(resultPath, 'utf8').replace(/^\uFEFF/, ''));
437
+ if (!r || !r.ok) return;
438
+ if (cfgGet('installSucceeded', false)) return;
439
+ await publishPersistent({ installSucceeded: true, statusText: r.restartOk === false ? '更新完成,但自动重启失败,请手动打开 DSH' : '更新完成' });
440
+ } catch (e) {}
441
+ }, 2000);
426
442
  setTimeout(async () => {
427
443
  try {
428
444
  if (!cfgGet('installScheduled', false)) return;
@@ -433,9 +449,6 @@ let cancelRequested = false;
433
449
  if (patch) await publishPersistent(patch);
434
450
  } catch (e) {}
435
451
  }, 15000);
436
- setTimeout(async () => {
437
- try { if (cfgGet('installSucceeded', false)) await publishPersistent({ installSucceeded: false }); } catch (e) {}
438
- }, 12000);
439
452
  setTimeout(async () => {
440
453
  try {
441
454
  if (!/^已安排更新/.test(String(cfgGet('statusText', '')))) return;
@@ -694,9 +707,14 @@ let cancelRequested = false;
694
707
  const accs = await loadAccounts();
695
708
  let changed = false;
696
709
  for (const a of accs.accounts || []) {
697
- if (!a.token || a.userId) continue;
710
+ if (!a.token || (a.userId && a.nickname && a.avatarUrl)) continue;
698
711
  const id = await fetchIdentity(a.token);
699
- if (id && id.userId) { a.userId = id.userId; changed = true; }
712
+ if (!id) continue;
713
+ if (id.userId && id.userId !== a.userId) { a.userId = id.userId; changed = true; }
714
+ if (id.nickname && !a.nickname) { a.nickname = id.nickname; changed = true; }
715
+ if (id.avatarUrl && !a.avatarUrl) { a.avatarUrl = id.avatarUrl; changed = true; }
716
+ if (id.nickname && (!a.name || /^账号[0-9a-zA-Z-]*$/.test(String(a.name)))) { a.name = id.nickname; changed = true; }
717
+ if (id.nickname && (!a.prefix || /^账号[0-9a-zA-Z-]*$/.test(String(a.prefix)))) { a.prefix = safeName(id.nickname) || a.prefix || id.nickname; changed = true; }
700
718
  }
701
719
  if (changed) { await saveAccounts(accs); await refreshAccountsMirror(); }
702
720
  } catch (e) {}
@@ -1099,7 +1117,8 @@ let cancelRequested = false;
1099
1117
  if (!parts.length) return (partialFailures.length || skippedAccounts) ? '同步失败:没有账号成功同步' : '同步完成(无变化)';
1100
1118
  const changed = parts.some((p) => !/:新增 0 \/ 更新 0$/.test(p));
1101
1119
  const head = (partialFailures.length || skippedAccounts) ? '同步完成(部分账号失败)' : '同步完成';
1102
- return head + (changed ? ' · ' + parts.join(' · ') : '(无变化)');
1120
+ const attachmentWarning = parts.some((p) => /附件\s*\d+\s*成功\s*[//]\s*\d+\s*失败/.test(p));
1121
+ return head + (changed ? ' · ' + parts.join(' · ') : '(无变化)') + (attachmentWarning ? ' · 部分附件下载失败(链接可能过期)' : '');
1103
1122
  };
1104
1123
 
1105
1124
  // 账号合并:「设置」里的行(name/token/enabled)叠加到 config.json 的账号上,
@@ -1125,10 +1144,18 @@ let cancelRequested = false;
1125
1144
  if (a.prefix) byName.set(String(a.prefix), a);
1126
1145
  }
1127
1146
  let dirty = false;
1128
- const nextAccounts = rows.map((r, i) => {
1147
+ const usedBase = new Set();
1148
+ const nextAccounts = [];
1149
+ for (const [i, r] of rows.entries()) {
1129
1150
  // 名称/前缀匹配;用户改名时按同一位置兜底(行数与 config 一致时)
1130
1151
  const b = byName.get(String(r.name || '')) || byName.get(String(r.prefix || ''))
1131
1152
  || (rows.length === base.length ? base[i] : null) || {};
1153
+ if (b && b !== {}) usedBase.add(b);
1154
+ if (!b.dataset || !b.root) {
1155
+ // 镜像先于 config 落盘时,不能用一个没有 dataset/root 的空壳覆盖真实账号
1156
+ try { await fsp.appendFile(path.join(dataDir, 'sync.log'), '[accounts] mirror row without dataset/root skipped: ' + String(r.name || r.prefix || '') + '\n'); } catch (e) {}
1157
+ continue;
1158
+ }
1132
1159
  const nextPrefix = safeName(r.prefix || r.name) || safeName(b.prefix || b.name) || ('账号' + String(b.id || b.userId || '').slice(-4));
1133
1160
  const next = {
1134
1161
  ...b,
@@ -1139,8 +1166,15 @@ let cancelRequested = false;
1139
1166
  dataset: b.dataset, root: b.root, id: b.id,
1140
1167
  };
1141
1168
  if (next.name !== b.name || next.prefix !== b.prefix || next.nickname !== b.nickname || next.avatarUrl !== b.avatarUrl) dirty = true;
1142
- return next;
1143
- }).filter((a) => a.dataset && a.root);
1169
+ nextAccounts.push(next);
1170
+ }
1171
+ // 镜像可能落后于 config(新登录账号尚未 publish):保留 config 中镜像未列出的账号,避免 5 秒 tick 抹掉
1172
+ for (const b of base) {
1173
+ if (usedBase.has(b)) continue;
1174
+ nextAccounts.push(b);
1175
+ dirty = true;
1176
+ try { await fsp.appendFile(path.join(dataDir, 'sync.log'), '[accounts] preserved config account not in mirror: ' + String(b.name || b.prefix || '') + '\n'); } catch (e) {}
1177
+ }
1144
1178
  const seenPrefixes = new Set();
1145
1179
  for (const a of nextAccounts) {
1146
1180
  if (!a.prefix || seenPrefixes.has(a.prefix)) {
@@ -1444,6 +1478,7 @@ let cancelRequested = false;
1444
1478
  }
1445
1479
 
1446
1480
  // 「立即更新」确认:installNow 上升沿 → 调度独立进程更新(20 秒后预检→重启)
1481
+ let loginInProgress = false;
1447
1482
  const installNowField = config && config.installNow;
1448
1483
  const hasOpenTurn = () => {
1449
1484
  try {
@@ -1493,9 +1528,18 @@ let cancelRequested = false;
1493
1528
  await publishPersistent({ installNow: false, installPending: true, installScheduled: false, statusText: '检测到正在回复,已暂缓更新;回复结束后会自动继续,也可点「取消更新」' });
1494
1529
  return;
1495
1530
  }
1531
+ if (loginInProgress) {
1532
+ await publishPersistent({ installNow: false, installPending: true, installScheduled: false, statusText: '登录进行中,请完成登录后再更新' });
1533
+ return;
1534
+ }
1496
1535
  const wsDir = resolveWorkspaceDir(await withSettingsAccounts());
1497
1536
  const ok = wsDir ? await scheduleWorkspaceInstall(wsDir) : false;
1498
1537
  if (ok === 'cancelled') { await publishPersistent({ installNow: false }); return; }
1538
+ if (typeof ok === 'string' && ok.startsWith('cooldown:')) {
1539
+ const mins = ok.split(':')[1] || '15';
1540
+ await publishPersistent({ installNow: false, statusText: '更新冷却中,请约 ' + mins + ' 分钟后再试' });
1541
+ return;
1542
+ }
1499
1543
  const patch2 = { installNow: false, statusText: ok ? '已安排更新:约 20 秒后重启 DSH' : '更新调度失败,请重试或重新安装插件' };
1500
1544
  if (ok) { patch2.installPending = false; patch2.installDeferred = false; patch2.installDeferredByUser = false; patch2.installScheduled = true; patch2.installSucceeded = false; }
1501
1545
  else { patch2.installDeferred = false; patch2.installDeferredByUser = false; patch2.installScheduled = false; patch2.installSucceeded = false; }
@@ -1512,6 +1556,20 @@ let cancelRequested = false;
1512
1556
  ctx.effect(() => () => clearInterval(timer2));
1513
1557
  }
1514
1558
 
1559
+ // 更新已安排后的活动回合守卫:20 秒预检期间开始回复时,写入 cancel 标记让安装脚本在杀进程前再次退出
1560
+ const installTurnGuard = setInterval(() => {
1561
+ try {
1562
+ if (!cfgGet('installScheduled', false)) return;
1563
+ const cancelPath = path.join(dataDir, 'install-cancel.json');
1564
+ if (existsSync(cancelPath)) return;
1565
+ if (!hasOpenTurn()) return;
1566
+ nodeFs.writeFileSync(cancelPath, JSON.stringify({ at: Date.now(), reason: 'open-turn' }));
1567
+ void publishPersistent({ installScheduled: false, installPending: true, statusText: '检测到正在回复,已暂缓更新;回复结束后会自动继续' });
1568
+ try { nodeFs.appendFileSync(path.join(dataDir, 'sync.log'), 'install guard: open turn, cancel requested\n'); } catch (e) {}
1569
+ } catch (e) {}
1570
+ }, 700);
1571
+ ctx.effect(() => () => clearInterval(installTurnGuard));
1572
+
1515
1573
  // 「取消本次更新」:保留待更新文件,标记为稍后处理;状态卡会保留「更新」入口
1516
1574
  const installCancelField = config && config.installCancel;
1517
1575
  if (installCancelField && typeof installCancelField.get === 'function') {
@@ -1543,6 +1601,7 @@ let cancelRequested = false;
1543
1601
  const archiveTimer = setInterval(async () => {
1544
1602
  try {
1545
1603
  if (!archiveOldReportsField.get()) return;
1604
+ if (cfgGet('installSucceeded', false)) return;
1546
1605
  await persistSettings({ archiveOldReports: false });
1547
1606
  const reg = ctx.get('workspaceRegistry');
1548
1607
  const entries = reg && typeof reg.list === 'function' ? reg.list() : [];
@@ -1639,7 +1698,12 @@ let cancelRequested = false;
1639
1698
  try {
1640
1699
  const j = JSON.parse(Buffer.concat(c).toString('utf8'));
1641
1700
  const b = (j.data && (j.data.biz_data || j.data)) || {};
1642
- resolve({ userId: String(b.id || '') });
1701
+ const pick = (...keys) => { for (const k of keys) { const v = b[k]; if (typeof v === 'string' && v.trim()) return v.trim(); } return ''; };
1702
+ resolve({
1703
+ userId: String(b.id || b.user_id || ''),
1704
+ nickname: pick('name', 'nickname', 'user_name', 'userName', 'nick_name'),
1705
+ avatarUrl: pick('avatar_url', 'avatarUrl', 'avatar', 'head_url', 'headUrl'),
1706
+ });
1643
1707
  } catch (e) { resolve(null); }
1644
1708
  });
1645
1709
  });
@@ -1673,6 +1737,7 @@ let cancelRequested = false;
1673
1737
  }
1674
1738
  if (loginBusy) return;
1675
1739
  loginBusy = true;
1740
+ loginInProgress = true;
1676
1741
  const wsDir = resolveWorkspaceDir(await loadAccounts());
1677
1742
  if (!wsDir) { await publishPersistent({ loginStatus: '找不到可用工作区,请先在 DSH 创建或打开一个工作区' }); return; }
1678
1743
  const resultFile = path.join(dataDir, 'login-result.json');
@@ -1834,7 +1899,7 @@ let cancelRequested = false;
1834
1899
  try { if (cleanupProfile) nodeFs.rmSync(cleanupProfile, { recursive: true, force: true }); } catch (e2) {}
1835
1900
  try { await fsp.appendFile(path.join(dataDir, 'sync.log'), 'login: ' + String(e) + '\n'); } catch (e2) {}
1836
1901
  await publishPersistent({ loginStatus: '登录流程出错:' + String((e && e.message) || e).slice(0, 120) });
1837
- } finally { loginBusy = false; }
1902
+ } finally { loginBusy = false; loginInProgress = false; }
1838
1903
  }, 1500);
1839
1904
  ctx.effect(() => () => clearInterval(loginTimer));
1840
1905
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-chat-history-sync",
3
3
  "description": "免费。把 DeepSeek 账号的网页端和手机 App 聊天记录同步进 DSH:按月份归档、可选分类索引、可继续对话。只增不减,不碰自建会话。Windows only,token 本机 DPAPI 加密,无遥测,不调用模型。",
4
- "version": "0.12.81",
4
+ "version": "0.12.83",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "exports": {
@@ -25,7 +25,7 @@
25
25
  "LICENSE"
26
26
  ],
27
27
  "scripts": {
28
- "test": "node test/run.cjs && node test/catalog.test.cjs && node test/a11y.test.cjs && node test/version-audit.test.cjs && node test/legacy.test.cjs && node test/import-reliability.test.cjs && node test/audit-0119.test.cjs && node test/audit-0121.test.cjs && node test/audit-0141.test.cjs && node test/audit-0161.test.cjs && node test/audit-0181.test.cjs && node test/audit-0120.test.cjs && node test/report-format.test.cjs && node test/import-state.test.cjs && node test/state-consistency.test.cjs && node test/import-phase-migration.test.cjs && node test/first-use.test.cjs && node test/state-ui.test.cjs && node test/import-retry.test.cjs && node test/sync-report-failure.test.cjs && node test/report-title.test.cjs && node test/report-frequency.test.cjs && node test/report-detail.test.cjs && node test/report-size.test.cjs && node test/privacy-log.test.cjs && node test/privacy-login.test.cjs && node test/privacy-login-cleanup.test.cjs && node test/privacy-dpapi.test.cjs && node test/privacy-diagnostics.test.cjs && node test/reporting-watchdog.test.cjs && node test/child-node-exe.test.cjs && node test/docs-version.test.cjs && node test/engine-bom.test.cjs && node test/engine-bom-json.test.cjs && node test/auth-401-html.test.cjs && node test/success-toast.test.cjs && node test/auto-sync-digest.test.cjs && node test/digest.test.cjs && node test/safety-claims.test.cjs && node test/report-layout.test.cjs && node test/lifecycle.test.cjs && node test/revision-retry.test.cjs && node test/report-updated-sessions.test.cjs && node test/pending-unified.test.cjs && node test/floating-sync.test.cjs && node test/quick-manage-split.test.cjs && node test/button-audit.test.cjs && node test/report-links.test.cjs && node test/phase2.test.cjs && node test/advanced-order.test.cjs && node test/phase3.test.cjs && node test/phase4.test.cjs && node test/report-session.test.cjs && node test/fault-injection.test.cjs && node test/install-lock.test.cjs",
28
+ "test": "node test/run.cjs && node test/catalog.test.cjs && node test/a11y.test.cjs && node test/version-audit.test.cjs && node test/legacy.test.cjs && node test/import-reliability.test.cjs && node test/audit-0119.test.cjs && node test/audit-0121.test.cjs && node test/audit-0141.test.cjs && node test/audit-0161.test.cjs && node test/audit-0181.test.cjs && node test/audit-0120.test.cjs && node test/report-format.test.cjs && node test/import-state.test.cjs && node test/state-consistency.test.cjs && node test/import-phase-migration.test.cjs && node test/first-use.test.cjs && node test/state-ui.test.cjs && node test/import-retry.test.cjs && node test/sync-report-failure.test.cjs && node test/report-title.test.cjs && node test/report-frequency.test.cjs && node test/report-detail.test.cjs && node test/report-size.test.cjs && node test/privacy-log.test.cjs && node test/privacy-login.test.cjs && node test/privacy-login-cleanup.test.cjs && node test/privacy-dpapi.test.cjs && node test/privacy-diagnostics.test.cjs && node test/reporting-watchdog.test.cjs && node test/child-node-exe.test.cjs && node test/docs-version.test.cjs && node test/engine-bom.test.cjs && node test/engine-bom-json.test.cjs && node test/auth-401-html.test.cjs && node test/success-toast.test.cjs && node test/auto-sync-digest.test.cjs && node test/digest.test.cjs && node test/safety-claims.test.cjs && node test/report-layout.test.cjs && node test/lifecycle.test.cjs && node test/revision-retry.test.cjs && node test/report-updated-sessions.test.cjs && node test/pending-unified.test.cjs && node test/floating-sync.test.cjs && node test/quick-manage-split.test.cjs && node test/button-audit.test.cjs && node test/report-links.test.cjs && node test/phase2.test.cjs && node test/advanced-order.test.cjs && node test/phase3.test.cjs && node test/phase4.test.cjs && node test/report-session.test.cjs && node test/fault-injection.test.cjs && node test/install-lock.test.cjs && node test/attachment-retry.test.cjs && node test/remediation-083.test.cjs",
29
29
  "test:e2e": "node test/e2e-smoke.cjs",
30
30
  "test:sandbox": "node test/install-sandbox.test.cjs",
31
31
  "test:package": "node test/package.test.cjs",