dsh-config-manager 0.8.0 → 0.8.2

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.
Files changed (47) hide show
  1. package/lib/adapters/mcp.d.ts +6 -1
  2. package/lib/adapters/mcp.js +22 -4
  3. package/lib/client.d.ts +18 -1
  4. package/lib/client.js +628 -573
  5. package/lib/core/messages.d.ts +2 -0
  6. package/lib/core/messages.js +4 -0
  7. package/lib/core/patch-document.d.ts +65 -0
  8. package/lib/core/patch-document.js +161 -0
  9. package/lib/foreign/read-trae.d.ts +11 -0
  10. package/lib/foreign/read-trae.js +124 -4
  11. package/lib/foreign/session-source.d.ts +12 -4
  12. package/lib/foreign/session-source.js +5 -3
  13. package/lib/foreign/trae-sqlcipher.d.ts +127 -0
  14. package/lib/foreign/trae-sqlcipher.js +519 -0
  15. package/lib/foreign/trae.js +3 -1
  16. package/lib/foreign/truth-table.js +3 -2
  17. package/lib/foreign/types.d.ts +9 -1
  18. package/lib/index.d.ts +3 -1
  19. package/lib/index.js +35 -53
  20. package/lib/ui/foreign-view.d.ts +19 -0
  21. package/lib/ui/foreign-view.js +24 -0
  22. package/lib/ui/i18n.d.ts +5 -0
  23. package/lib/ui/i18n.js +13 -0
  24. package/package.json +1 -1
  25. package/src/adapters/mcp.test.ts +23 -3
  26. package/src/adapters/mcp.ts +24 -4
  27. package/src/client/import/ForeignImportView.tsx +25 -7
  28. package/src/client/import/foreign-import-view-guard.test.ts +1 -1
  29. package/src/client/locales/foreign.ts +9 -0
  30. package/src/core/messages.ts +4 -0
  31. package/src/core/patch-document.test.ts +107 -0
  32. package/src/core/patch-document.ts +194 -0
  33. package/src/foreign/file-budget.test.ts +7 -1
  34. package/src/foreign/read-trae.ts +117 -5
  35. package/src/foreign/session-source.ts +15 -5
  36. package/src/foreign/trae-sqlcipher.test.ts +360 -0
  37. package/src/foreign/trae-sqlcipher.ts +564 -0
  38. package/src/foreign/trae.test.ts +188 -0
  39. package/src/foreign/trae.ts +3 -1
  40. package/src/foreign/truth-table.ts +4 -2
  41. package/src/foreign/types.ts +10 -1
  42. package/src/index.facade.test.ts +83 -1
  43. package/src/index.ts +37 -47
  44. package/src/ui/foreign-view.test.ts +36 -0
  45. package/src/ui/foreign-view.ts +46 -0
  46. package/src/ui/i18n.ts +13 -0
  47. package/src/utils/patch-yaml.test.ts +1 -1
package/lib/index.js CHANGED
@@ -80,6 +80,7 @@ import { ImportUserSkippedError } from './core/types.js';
80
80
  import { PLUGIN_NPM_PACKAGE } from './core/update-check.js';
81
81
  import { planSelfUpdate, runSelfUpdate } from './core/self-update.js';
82
82
  import { createAdapters } from './adapters/index.js';
83
+ import { describePatchDocument, describePatchLayoutDrift, planPatchDocument, promotedTopLevelIds } from './core/patch-document.js';
83
84
  import { isPatchLayerRel, profilePatchRel, readEffectivePatchLines, USER_PATCH_FILE } from './core/patch-layers.js';
84
85
  import { createLocalPluginPackHook } from './core/local-plugin-host.js';
85
86
  import { ENCRYPTED_CONTAINER_CODE, createEncryptionProvider, readContainerKind, encryptArchive } from './security/index.js';
@@ -148,7 +149,7 @@ export const name = 'config-manager';
148
149
  /** Services required before the engine can mount (present in every profile). */
149
150
  export const inject = ['settings', 'credentials'];
150
151
  /** Plugin version, kept in sync with package.json ("version"). */
151
- export const PLUGIN_VERSION = '0.8.0';
152
+ export const PLUGIN_VERSION = '0.8.2';
152
153
  /** Plugin own package name — excluded from its own exported plugins list. */
153
154
  const PLUGIN_NAME = 'dsh-config-manager';
154
155
  /**
@@ -1487,15 +1488,13 @@ export class DshPatchFileFacade {
1487
1488
  }
1488
1489
  async applyPatchChanges(file, changes) {
1489
1490
  const p = this.patchPath(file);
1490
- // 1. Load the current document into an ordered lineId → raw table.
1491
+ // 1. Load the current document (the ordered table itself is built by planPatchDocument).
1491
1492
  //
1492
1493
  // 读不出来的既有内容**绝不能当作空文档**(issue #75 的数据丢失点):重建后的文件只包含
1493
1494
  // 本次写入的行,等于把用户手写的其余行整段删掉。三种情况分开处理:
1494
1495
  // - 真不存在(ENOENT)→ 空文档(首次创建,既有语义);
1495
1496
  // - 存在但读不到(EACCES/EBUSY/…)→ 抛错,不改写;
1496
1497
  // - 存在但解析不了(含未知方言 / YAML 本身有错)→ 抛错,不改写。
1497
- const rows = new Map();
1498
- const order = [];
1499
1498
  let existing = null;
1500
1499
  try {
1501
1500
  existing = await fs.readFile(p, 'utf8');
@@ -1514,58 +1513,41 @@ export class DshPatchFileFacade {
1514
1513
  throw new Error(this.msg('host.patchRefuseClobber', { file, reason: describePatchYamlError(err) }), { cause: err });
1515
1514
  }
1516
1515
  }
1517
- if (Array.isArray(doc)) {
1518
- for (const item of doc) {
1519
- if (item === null || typeof item !== 'object')
1520
- continue;
1521
- const obj = item;
1522
- const insert = obj['insert'];
1523
- if (Array.isArray(insert)) {
1524
- for (const entry of insert) {
1525
- if (entry === null || typeof entry !== 'object')
1526
- continue;
1527
- const id = entry['id'];
1528
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1529
- rows.set(id, entry);
1530
- order.push(id);
1531
- }
1532
- }
1533
- continue;
1534
- }
1535
- const id = obj['id'];
1536
- if (typeof id === 'string' && id !== '' && !rows.has(id)) {
1537
- rows.set(id, obj);
1538
- order.push(id);
1539
- }
1540
- }
1516
+ // 2. Rebuild through core/patch-document.ts (issue #133): the two shapes are **not**
1517
+ // equivalent on the host side. A top-level `- id: X` row *overrides* entry X and is
1518
+ // dropped with `patch: entry "X" not found` when X does not exist; only an
1519
+ // `- insert:` block member *adds* entries. Emitting every row top-level therefore
1520
+ // turned one update into "every insert-only entry (MCP servers, most notably) is
1521
+ // gone after restart".
1522
+ const plan = planPatchDocument(doc, changes);
1523
+ const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1524
+ + dumpPatchDocument(plan.items);
1525
+ // 3. Post-write structure self-check, before anything touches the disk: re-parse the
1526
+ // text we just serialized and require both id sets to match the plan item by item.
1527
+ // A serializer or dialect change that flattens or swallows insert blocks stops here
1528
+ // (zero write) instead of silently degrading every patch row to an override.
1529
+ const drift = describePatchLayoutDrift(plan, describePatchDocument(loadPatchDocument(text)));
1530
+ if (drift !== null) {
1531
+ throw new Error(this.msg('host.patchSemanticDrift', { file, detail: drift }));
1532
+ }
1533
+ // 4. 跨层提升守卫(issue #133):待写的顶层 id 若是**另一层**的 insert 成员,写下去就从
1534
+ // 「新增」变成「覆盖」(宿主查不到则丢弃)。对侧读不出来/解析不了只跳过守卫 —— 读护栏
1535
+ // 已在各自层报错,损坏的兄弟文件不该永久阻塞本层写入。
1536
+ const other = file === USER_PATCH_FILE ? profilePatchRel(this.profile) : USER_PATCH_FILE;
1537
+ const promoted = promotedTopLevelIds(await this.readPatchDocQuietly(other), plan.topLevelIds);
1538
+ if (promoted.length > 0) {
1539
+ throw new Error(this.msg('host.patchRefusePromote', { file, ids: promoted.join(', ') }));
1541
1540
  }
1542
- // 2. Apply the changes.
1543
- for (const change of changes) {
1544
- if (change.action === 'remove') {
1545
- if (rows.delete(change.lineId)) {
1546
- const at = order.indexOf(change.lineId);
1547
- if (at >= 0)
1548
- order.splice(at, 1);
1549
- }
1550
- }
1551
- else if (change.action === 'insert' || change.action === 'update') {
1552
- if (!rows.has(change.lineId))
1553
- order.push(change.lineId);
1554
- rows.set(change.lineId, change.raw);
1555
- }
1541
+ await atomicWriteFile(p, text);
1542
+ }
1543
+ /** 读另一层并解析;读不到/解析不了 → undefined(跨层守卫 fail-open,见 promotedTopLevelIds)。 */
1544
+ async readPatchDocQuietly(file) {
1545
+ try {
1546
+ return loadPatchDocument(await fs.readFile(resolve(this.homeDir, file), 'utf8'));
1556
1547
  }
1557
- // 3. Rebuild: every id row is emitted as a top-level row. The loader treats
1558
- // a top-level { id, name } row exactly like an `- insert:` block member
1559
- // (dsh-base patch precedent), so the document stays semantically equal.
1560
- const out = [];
1561
- for (const id of order) {
1562
- const raw = rows.get(id);
1563
- if (raw !== undefined)
1564
- out.push(raw);
1548
+ catch {
1549
+ return undefined;
1565
1550
  }
1566
- const text = '# rewritten by dsh-config-manager import (original comments not preserved)\n'
1567
- + dumpPatchDocument(out);
1568
- await atomicWriteFile(p, text);
1569
1551
  }
1570
1552
  }
1571
1553
  /** File facade over $DSH_HOME, confined to the home root. */
@@ -164,3 +164,22 @@ export declare const FOREIGN_LOSSY_KINDS: readonly ForeignLossyKind[];
164
164
  * · **`prompts` 分区** → `systemPrompt` 由字符串写成 `{ persona }` 对象(bundle-format §7.3)。
165
165
  */
166
166
  export declare function foreignLossyRows(sections: readonly string[] | null, t: UiT): readonly ForeignLossyRow[];
167
+ /**
168
+ * 导入失败 → 可见载荷(码 + 后端原话 + 一句人话)。
169
+ *
170
+ * 为什么要有它:宿主把「为什么没东西可导」放在 **400 的 body**(`code` + `skipped`),
171
+ * 而客户端过去只显示 `err.message` —— 于是 `sessions-not-migrated`、
172
+ * `trae-db-key-invalid` 这些**字典里早就有中英文案**的码,用户根本看不到。
173
+ * 现在按同一本字典把码翻成文案(skip 码走冻结映射,`nothing-to-import` 走单独一条键),
174
+ * 翻不出才回落后端 message —— 绝不吞掉原因,也绝不编解释。
175
+ */
176
+ export interface ForeignImportFailure {
177
+ /** 稳定机器码(后端 400 带的 code;没有则为 null) */
178
+ code: string | null;
179
+ /** 后端原始 message(渲染处再过 redact) */
180
+ message: string;
181
+ /** 展示文案(字典优先;没有就用 message) */
182
+ text: string;
183
+ }
184
+ /** 失败载荷的构造(未知码 → 原样返回 message,绝不猜语义) */
185
+ export declare function foreignImportFailure(err: unknown, t: UiT): ForeignImportFailure;
@@ -51,6 +51,11 @@ export const FOREIGN_SKIP_KEY = {
51
51
  'session-id-mismatch': 'foreign.skip.session-id-mismatch',
52
52
  'mcp-server-id-conflict': 'foreign.skip.mcp-server-id-conflict',
53
53
  'project-scan-truncated': 'foreign.skip.project-scan-truncated',
54
+ // 2026-11-12(#134):Trae 2.3.x 加密会话库的四条可判定失败 —— 同样是全量 Record 保底
55
+ 'trae-db-key-invalid': 'foreign.skip.trae-db-key-invalid',
56
+ 'trae-db-too-large': 'foreign.skip.trae-db-too-large',
57
+ 'trae-db-decrypt-failed': 'foreign.skip.trae-db-decrypt-failed',
58
+ 'trae-db-schema-mismatch': 'foreign.skip.trae-db-schema-mismatch',
54
59
  };
55
60
  /**
56
61
  * 机器码 → 字典键。**未知码(未来版本 / 第三方宿主)回退键名本身**,
@@ -256,4 +261,23 @@ export function foreignLossyRows(sections, t) {
256
261
  applicable: applicable[kind],
257
262
  }));
258
263
  }
264
+ /**
265
+ * 非 skip 词表、但同样会作为 400 码出现的导入失败(与 `src/routes/foreign.ts` 同源):
266
+ * `nothing-to-import` 是路由层的码,不在 `ForeignSkipCode` union 里,故单独映射。
267
+ */
268
+ const IMPORT_FAILURE_KEYS = {
269
+ 'nothing-to-import': 'foreign.importNothing',
270
+ };
271
+ /** 失败载荷的构造(未知码 → 原样返回 message,绝不猜语义) */
272
+ export function foreignImportFailure(err, t) {
273
+ const source = typeof err === 'object' && err !== null ? err : null;
274
+ const rawCode = source?.code;
275
+ const code = typeof rawCode === 'string' && rawCode !== '' ? rawCode : null;
276
+ const rawMessage = source?.message;
277
+ const message = typeof rawMessage === 'string' && rawMessage !== '' ? rawMessage : String(err);
278
+ if (code === null)
279
+ return { code, message, text: message };
280
+ const mapped = IMPORT_FAILURE_KEYS[code] ?? (isKnownSkipCode(code) ? FOREIGN_SKIP_KEY[code] : undefined);
281
+ return { code, message, text: mapped === undefined ? message : t(mapped) };
282
+ }
259
283
  //# sourceMappingURL=foreign-view.js.map
package/lib/ui/i18n.d.ts CHANGED
@@ -427,6 +427,11 @@ export declare const uiZh: {
427
427
  readonly 'foreign.skip.legacy-rules-file': '旧式规则文件:DSH 无对等结构,只报告';
428
428
  readonly 'foreign.skip.instructions-merged': '多份指令源被合并为一个全局指令文件';
429
429
  readonly 'foreign.skip.instructions-override-selected': '命中更高优先级的指令文件(override),按它导入';
430
+ readonly 'foreign.importNothing': '没有可导入的内容:该来源在本机没有可转换的配置或会话';
431
+ readonly 'foreign.skip.trae-db-key-invalid': 'Trae 加密会话库的密钥对不上(换版或密钥被覆盖):页面头校验不通过,本次未读出任何会话';
432
+ readonly 'foreign.skip.trae-db-too-large': 'Trae 加密会话库超出本来源的体积上限:未解密,未读出任何会话(全局 1 GiB 上限未改动)';
433
+ readonly 'foreign.skip.trae-db-decrypt-failed': 'Trae 加密会话库无法解密:文件被截断、不是 SQLCipher 形态或读取失败,本次未读出任何会话';
434
+ readonly 'foreign.skip.trae-db-schema-mismatch': 'Trae 加密会话库解密成功但表结构不符(缺 chat_session / history_v2 或必需列):不猜字段,本次未读出任何会话';
430
435
  readonly 'foreign.skip.unsupported-permissions': '权限规则(allow/ask/deny)未迁移:DSH 没有权限规则文件的对等结构,这些规则不在本包内,导入后不会生效';
431
436
  readonly 'foreign.skip.unsupported-settings-keys': 'settings.json 里其余未迁移的顶层键:只记录键名与条数,键值一律不读取,也不会写进本包';
432
437
  readonly 'foreign.skip.unsupported-agents': '.claude/agents/*.md 子代理定义未迁移:DSH 的子代理是运行时 provider 注册制,没有文件级对等结构';
package/lib/ui/i18n.js CHANGED
@@ -452,6 +452,13 @@ export const uiZh = {
452
452
  'foreign.skip.legacy-rules-file': '旧式规则文件:DSH 无对等结构,只报告',
453
453
  'foreign.skip.instructions-merged': '多份指令源被合并为一个全局指令文件',
454
454
  'foreign.skip.instructions-override-selected': '命中更高优先级的指令文件(override),按它导入',
455
+ // ---------- 2026-11-12(#134):Trae 2.3.x 的加密会话库(SQLCipher)四条可判定失败 ----------
456
+ // 纪律同上:每条都要能被代码逐条证明 —— 只说「什么没搬 / 为什么 / 怎么办」,不承诺修好。
457
+ 'foreign.importNothing': '没有可导入的内容:该来源在本机没有可转换的配置或会话',
458
+ 'foreign.skip.trae-db-key-invalid': 'Trae 加密会话库的密钥对不上(换版或密钥被覆盖):页面头校验不通过,本次未读出任何会话',
459
+ 'foreign.skip.trae-db-too-large': 'Trae 加密会话库超出本来源的体积上限:未解密,未读出任何会话(全局 1 GiB 上限未改动)',
460
+ 'foreign.skip.trae-db-decrypt-failed': 'Trae 加密会话库无法解密:文件被截断、不是 SQLCipher 形态或读取失败,本次未读出任何会话',
461
+ 'foreign.skip.trae-db-schema-mismatch': 'Trae 加密会话库解密成功但表结构不符(缺 chat_session / history_v2 或必需列):不猜字段,本次未读出任何会话',
455
462
  // ---------- 2026-10-18:Claude Code 项目级配置 / 插件 / 权限 / 设置键的如实诊断(8 个新码)----------
456
463
  // 纪律:每条都要能被代码逐条证明 —— 只说「什么没搬、为什么、本项是否可补」,
457
464
  // 绝不写「已支持 / 完全兼容」这类无法被代码证明的话。
@@ -930,6 +937,12 @@ export const uiEn = {
930
937
  'foreign.skip.legacy-rules-file': 'Legacy rules file: DSH has no equivalent, reported only',
931
938
  'foreign.skip.instructions-merged': 'Several instruction sources were merged into one global instruction file',
932
939
  'foreign.skip.instructions-override-selected': 'A higher-priority instruction file (override) was found and is the one imported',
940
+ // 2026-11-12 (#134): four decidable failures of the Trae 2.3.x encrypted session database (SQLCipher)
941
+ 'foreign.importNothing': 'Nothing to import: this source has no convertible configuration or sessions on this machine',
942
+ 'foreign.skip.trae-db-key-invalid': 'The Trae encrypted session database key does not match (version change or an overridden key): the page-header checks failed, so no session was read',
943
+ 'foreign.skip.trae-db-too-large': 'The Trae encrypted session database exceeds this source size limit: it was not decrypted, so no session was read (the global 1 GiB limit is unchanged)',
944
+ 'foreign.skip.trae-db-decrypt-failed': 'The Trae encrypted session database cannot be decrypted: the file is truncated, not in SQLCipher form, or unreadable, so no session was read',
945
+ 'foreign.skip.trae-db-schema-mismatch': 'The Trae encrypted session database decrypted but its schema does not match (chat_session / history_v2 or a required column is missing): fields are never guessed, so no session was read',
933
946
  // 2026-10-18: honest diagnostics for Claude Code project-level config / plugins / permissions / settings keys (8 new codes)
934
947
  'foreign.skip.unsupported-permissions': 'Permission rules (allow/ask/deny) were not migrated: DSH has no equivalent permission-rule file, so they are not in this bundle and will not take effect after import',
935
948
  'foreign.skip.unsupported-settings-keys': 'Other unmigrated top-level keys in settings.json: only key names and counts are recorded; values are never read and never enter this bundle',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-manager",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "license": "MIT",
5
5
  "description": "Backup, restore, export, import, migrate and sync your DeepSeek Harness (DSH) configuration: settings, plugins, MCP servers, skills, agent presets and workspaces. One-click migration to another machine. DSH 配置一键备份、恢复、导出、导入、迁移与同步插件。",
6
6
  "icon": "./icon.svg",
@@ -41,11 +41,31 @@ test('mcp: extractMcpServers 兼容单行与 insert 块', () => {
41
41
  assert.equal(http?.sourceLineId, 'mcp-http');
42
42
  });
43
43
 
44
- test('mcp: buildMcpPatchLine 构造写回行', () => {
44
+ test('mcp: buildMcpPatchLine 构造写回行(scoped 包名 + 显式 transport)', () => {
45
45
  const line = buildMcpPatchLine('mcp-fs', { serverName: 'filesystem', type: 'stdio', command: 'npx', args: ['-y', 'x'] });
46
46
  assert.equal(line.id, 'mcp-fs');
47
- assert.equal(line.name, 'dsh-mcp-client');
47
+ assert.equal(line.name, '@deepseek-ai/dsh-mcp-client', '宿主按 bundle id 解析 name,裸名不保证被接受(#133)');
48
+ assert.equal((line.config as Record<string, unknown>)['transport'], 'stdio', 'stdio 必须显式写 transport(此前只能靠 url 缺省猜)');
48
49
  assert.equal((line.config as Record<string, unknown>)['command'], 'npx');
50
+
51
+ const http = buildMcpPatchLine('mcp-remote', { serverName: 'remote', type: 'streamable-http', url: 'https://mcp.example.com/sse' });
52
+ const httpConfig = http.config as Record<string, unknown>;
53
+ assert.equal(httpConfig['transport'], 'streamable-http');
54
+ assert.equal(httpConfig['url'], 'https://mcp.example.com/sse');
55
+ });
56
+
57
+ test('mcp: extractMcpServers 以 transport 为准,缺该字段的旧行才回落 url 猜测', () => {
58
+ const withTransport = extractMcpServers([{
59
+ lineId: 'mcp-stdio-with-url',
60
+ raw: { id: 'mcp-stdio-with-url', name: '@deepseek-ai/dsh-mcp-client', config: { serverName: 's1', transport: 'stdio', command: 'node', url: 'http://127.0.0.1:1/mcp' } },
61
+ }]);
62
+ assert.equal(withTransport[0]?.type, 'stdio', 'transport 在就不该被 url 覆盖');
63
+
64
+ const legacy = extractMcpServers([{
65
+ lineId: 'legacy',
66
+ raw: { id: 'legacy', name: 'dsh-mcp-client', config: { serverName: 's2', url: 'https://mcp.example.com/sse' } },
67
+ }]);
68
+ assert.equal(legacy[0]?.type, 'streamable-http', '没有 transport 的旧行仍按原口径回落');
49
69
  });
50
70
 
51
71
  test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 patch(needsRestart)', async () => {
@@ -69,7 +89,7 @@ test('mcp: export 提取 + analyzeImport Create/Skip/Conflict + applyItem 写 pa
69
89
  assert.equal(r.ok, true);
70
90
  assert.equal(r.needsRestart, true, 'MCP 写 patch 必须重启生效');
71
91
  assert.ok(dst.patchFile.lines.has('mcp-fs'));
72
- assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], 'dsh-mcp-client');
92
+ assert.equal((dst.patchFile.lines.get('mcp-fs')?.raw as Record<string, unknown>)['name'], '@deepseek-ai/dsh-mcp-client');
73
93
 
74
94
  // 幂等:同 serverName 同内容 → Skip
75
95
  items = await adapter.analyzeImport(exported.data, makeImportContext(dst, sections));
@@ -65,7 +65,8 @@ export function extractMcpServers(lines: { lineId: string; raw: unknown; file?:
65
65
  const c = config as Record<string, unknown>;
66
66
  const serverName = c['serverName'];
67
67
  if (typeof serverName !== 'string' || serverName === '') continue;
68
- const type = typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio';
68
+ // transport 优先(写回时一定有);老行没有该字段才回落「有 url = 远程」的猜测
69
+ const type = mcpTransportOf(c) ?? (typeof c['url'] === 'string' && c['url'] !== '' ? 'streamable-http' : 'stdio');
69
70
  servers.push({
70
71
  serverName,
71
72
  type,
@@ -107,6 +108,12 @@ export function stripMcpEntries(raw: unknown): unknown | undefined {
107
108
  return isMcpEntry(single[0]) ? undefined : raw;
108
109
  }
109
110
 
111
+ /** `config.transport` 的合法取值;读不出来(缺字段/写错)返回 undefined,由调用方回落 url 判定。 */
112
+ function mcpTransportOf(c: Record<string, unknown>): McpServerEntry['type'] | undefined {
113
+ const transport = c['transport'];
114
+ return transport === 'stdio' || transport === 'streamable-http' ? transport : undefined;
115
+ }
116
+
110
117
  /** 单个 patch entry 是否是 MCP 服务器行(与 extractMcpServers 的判定同口径) */
111
118
  function isMcpEntry(entry: unknown): boolean {
112
119
  if (entry === null || typeof entry !== 'object') return false;
@@ -131,9 +138,22 @@ function entriesOf(raw: unknown): { id?: unknown; name?: unknown; config?: unkno
131
138
  return [];
132
139
  }
133
140
 
134
- /** 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致) */
141
+ /**
142
+ * MCP server 行的包名(bundle id,**必须带 scope**)。
143
+ *
144
+ * 宿主按 bundle id 解析 patch 行的 `name`;裸名 `dsh-mcp-client` 是否被归一化未经验证,
145
+ * 而用户机上的真实行都是 `@deepseek-ai/dsh-mcp-client`(issue #133 报告的原始行)。
146
+ */
147
+ const MCP_BUNDLE_NAME = '@deepseek-ai/dsh-mcp-client';
148
+
149
+ /**
150
+ * 由导出条目构造写回 patch 行 raw(单行形态,与 dsh-mcp-client 组合 config 语义一致)。
151
+ *
152
+ * `config.transport` 必须显式写:读侧靠它判定 server 类型,只在「没有 transport 的旧行」
153
+ * 上才回落 url 猜测(issue #133:此前写回丢了这个字段,stdio/http 只能靠 url 有没有值猜)。
154
+ */
135
155
  export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Record<string, unknown> {
136
- const config: Record<string, unknown> = { serverName: server.serverName };
156
+ const config: Record<string, unknown> = { serverName: server.serverName, transport: server.type };
137
157
  if (server.type === 'streamable-http') {
138
158
  config['url'] = server.url;
139
159
  if (server.headers !== undefined) config['headers'] = server.headers;
@@ -143,7 +163,7 @@ export function buildMcpPatchLine(lineId: string, server: McpServerEntry): Recor
143
163
  if (server.env !== undefined) config['env'] = server.env;
144
164
  if (server.cwd !== undefined) config['cwd'] = server.cwd;
145
165
  }
146
- return { id: lineId, name: 'dsh-mcp-client', config };
166
+ return { id: lineId, name: MCP_BUNDLE_NAME, config };
147
167
  }
148
168
 
149
169
  /** 连接器计划项的 id 前缀(导入时按前缀分派到 applyConnectorItem) */
@@ -28,7 +28,14 @@ import { useEffect, useState } from 'react'
28
28
  import type { TranslateNS } from '../client-types.ts'
29
29
  import type { ConfigManagerApi, ForeignImportResponse } from '../api.ts'
30
30
  import type { UiT } from '../../ui/i18n.ts'
31
- import { foreignLossyRows, foreignPathsText, foreignSourcesViewModel, type ForeignSourceRow } from '../../ui/foreign-view.ts'
31
+ import {
32
+ foreignImportFailure,
33
+ foreignLossyRows,
34
+ foreignPathsText,
35
+ foreignSourcesViewModel,
36
+ type ForeignImportFailure,
37
+ type ForeignSourceRow,
38
+ } from '../../ui/foreign-view.ts'
32
39
  import { Badge, Banner, Button, Card, SectionTitle } from '../common/ui.tsx'
33
40
  import { SkeletonList } from '../common/Skeleton.tsx'
34
41
  import { InfoHint } from '../common/InfoHint.tsx'
@@ -106,7 +113,13 @@ export function ForeignImportView({ api, t, uiT, onReady }: ForeignImportViewPro
106
113
  const [loadError, setLoadError] = useState<string | null>(null)
107
114
  const [selected, setSelected] = useState<string | null>(null)
108
115
  const [importing, setImporting] = useState(false)
109
- const [importError, setImportError] = useState<string | null>(null)
116
+ /**
117
+ * 上一次导入失败(#134):**带机器码**而不是一句 message。
118
+ *
119
+ * 宿主的 400 会带 `code`,字典里早有对应文案(`sessions-not-migrated` 等)——
120
+ * 只显示 err.message 会让用户永远看不到「为什么这里没有会话」。
121
+ */
122
+ const [importFailure, setImportFailure] = useState<ForeignImportFailure | null>(null)
110
123
  /** 最近一次产包结果的跳过项与凭据引用(产包成功后仍显示,供用户在进向导前先看到) */
111
124
  const [produced, setProduced] = useState<ForeignImportResponse | null>(null)
112
125
  /** F-3:上一次的产包结果因输入变化被作废 —— 重置必须在 UI 上有反馈(绝不静默) */
@@ -148,7 +161,7 @@ export function ForeignImportView({ api, t, uiT, onReady }: ForeignImportViewPro
148
161
  const resetProduced = (): void => {
149
162
  if (produced !== null) setPreviewReset(true)
150
163
  setProduced(null)
151
- setImportError(null)
164
+ setImportFailure(null)
152
165
  }
153
166
 
154
167
  /** 切换来源:同一个来源重复点击不算输入变化(不重置,免得谎报「已作废」)。 */
@@ -168,7 +181,7 @@ export function ForeignImportView({ api, t, uiT, onReady }: ForeignImportViewPro
168
181
  const runImport = async (): Promise<void> => {
169
182
  if (selected === null) return
170
183
  setImporting(true)
171
- setImportError(null)
184
+ setImportFailure(null)
172
185
  setProduced(null)
173
186
  setPreviewReset(false)
174
187
  try {
@@ -177,7 +190,8 @@ export function ForeignImportView({ api, t, uiT, onReady }: ForeignImportViewPro
177
190
  // 交给上层 → 写进 runStore.library.pendingZip → 导入面板消费(复用既有通道)
178
191
  onReady(result)
179
192
  } catch (err) {
180
- setImportError(err instanceof Error ? err.message : String(err))
193
+ // 码 → 字典文案(同一本 UiT 字典);翻不出才回落后端 message(绝不吞掉原因)
194
+ setImportFailure(foreignImportFailure(err, uiT))
181
195
  } finally {
182
196
  setImporting(false)
183
197
  }
@@ -301,8 +315,12 @@ export function ForeignImportView({ api, t, uiT, onReady }: ForeignImportViewPro
301
315
  </Card>
302
316
  )}
303
317
 
304
- {importError !== null && (
305
- <Banner kind="error">{t('foreign.importFailed', { reason: redact(importError) })}</Banner>
318
+ {importFailure !== null && (
319
+ <Banner kind="error">
320
+ {t('foreign.importFailed', { reason: redact(importFailure.text) })}
321
+ {/* 稳定码保留给排查/上报:文案是人话,码是可搜索的锚点(未知码时它就是唯一信息) */}
322
+ {importFailure.code !== null && <span className={css.skipCode}>{importFailure.code}</span>}
323
+ </Banner>
306
324
  )}
307
325
 
308
326
  <div className={css.actionRow}>
@@ -94,7 +94,7 @@ function renderBlocksOf(source: string): { at: number; text: string }[] {
94
94
  test('F-3:切换来源/重新检测都必须走 resetProduced(清产包结果 + 清失败横幅 + 有可见反馈)', () => {
95
95
  const reset = windowOf('const resetProduced = (): void => {', '\n }')
96
96
  assert.match(reset, /setProduced\(null\)/, '必须清掉上一次的产包结果')
97
- assert.match(reset, /setImportError\(null\)/, '上一次的失败横幅也属于上一次输入,必须一并清掉')
97
+ assert.match(reset, /setImportFailure\(null\)/, '上一次的失败横幅也属于上一次输入,必须一并清掉')
98
98
  assert.match(reset, /setPreviewReset\(true\)/, '重置必须留下可见反馈(绝不静默作废)')
99
99
 
100
100
  // 来源行的 onSelect 不得直连 setSelected(那正是 F-3 的原始缺陷形态)
@@ -95,6 +95,11 @@ export const zh = {
95
95
  'foreign.skip.legacy-rules-file': '旧式规则文件:DSH 无对等结构,只报告',
96
96
  'foreign.skip.instructions-merged': '多份指令源被合并为一个全局指令文件',
97
97
  'foreign.skip.instructions-override-selected': '命中更高优先级的指令文件(override),按它导入',
98
+ // 2026-11-12(#134):Trae 2.3.x 加密会话库(SQLCipher)的可判定失败
99
+ 'foreign.skip.trae-db-key-invalid': 'Trae 加密会话库的密钥对不上(换版或密钥被覆盖):页面头校验不通过,本次未读出任何会话',
100
+ 'foreign.skip.trae-db-too-large': 'Trae 加密会话库超出本来源的体积上限:未解密,未读出任何会话(全局 1 GiB 上限未改动)',
101
+ 'foreign.skip.trae-db-decrypt-failed': 'Trae 加密会话库无法解密:文件被截断、不是 SQLCipher 形态或读取失败,本次未读出任何会话',
102
+ 'foreign.skip.trae-db-schema-mismatch': 'Trae 加密会话库解密成功但表结构不符(缺 chat_session / history_v2 或必需列):不猜字段,本次未读出任何会话',
98
103
  // 冲突语义(用户决策:同 id 不覆盖、跳过并报码)
99
104
  'foreign.conflict.policy': '同 id 冲突不覆盖本机内容:跳过并逐条报告',
100
105
  } as const;
@@ -180,5 +185,9 @@ export const en: Record<keyof typeof zh, string> = {
180
185
  'foreign.skip.legacy-rules-file': 'Legacy rules file: DSH has no equivalent, reported only',
181
186
  'foreign.skip.instructions-merged': 'Several instruction sources were merged into one global instruction file',
182
187
  'foreign.skip.instructions-override-selected': 'A higher-priority instruction file (override) was found and is the one imported',
188
+ 'foreign.skip.trae-db-key-invalid': 'The Trae encrypted session database key does not match (version change or an overridden key): the page-header checks failed, so no session was read',
189
+ 'foreign.skip.trae-db-too-large': 'The Trae encrypted session database exceeds this source size limit: it was not decrypted, so no session was read (the global 1 GiB limit is unchanged)',
190
+ 'foreign.skip.trae-db-decrypt-failed': 'The Trae encrypted session database cannot be decrypted: the file is truncated, not in SQLCipher form, or unreadable, so no session was read',
191
+ 'foreign.skip.trae-db-schema-mismatch': 'The Trae encrypted session database decrypted but its schema does not match (chat_session / history_v2 or a required column is missing): fields are never guessed, so no session was read',
183
192
  'foreign.conflict.policy': 'Same-id conflicts never overwrite local content: skipped and listed in the report',
184
193
  };
@@ -209,6 +209,8 @@ export const zh = {
209
209
  'host.patchUnsupported': 'dsh-config-manager 仅支持管理 {user} 与 profile 的 {profile}(收到 {file})',
210
210
  'host.patchUnreadable': 'patch 层 {file} 读不出来({reason}):该层的 patch 行不会被导出/同步,也不会被改写',
211
211
  'host.patchRefuseClobber': 'patch 层 {file} 解析失败({reason}):已拒绝覆盖写入,否则会把这层里读不出来的行整体删掉',
212
+ 'host.patchRefusePromote': 'patch 层 {file} 的写入会把 {ids} 从 insert(新增)改成顶层行(覆盖):已拒绝写入,文件未改动(顶层行按 id 覆盖,查不到就整条丢弃)',
213
+ 'host.patchSemanticDrift': 'patch 层 {file} 写回后结构自检不通过({detail}):已拒绝写入,文件未改动',
212
214
  'host.fsPathEscape': '路径越界: {path}',
213
215
  'host.activationRowFailed': '插件 {pkg} 已安装,但激活行写入 profile 补丁失败:{reason}(重启后该插件可能未激活;修复后重试安装即可幂等补行)',
214
216
  'host.syncTokenWriteFailed': 'token 写入 DSH credentials 失败:{reason}(请在 DSH 凭据管理里配置 {ref} 后重试)',
@@ -735,6 +737,8 @@ export const en: Record<keyof typeof zh, string> = {
735
737
  'host.patchUnsupported': 'dsh-config-manager only manages {user} and the profile {profile} (received {file})',
736
738
  'host.patchUnreadable': 'Cannot read patch layer {file} ({reason}): its patch rows are not exported or synced, and the file is left untouched',
737
739
  'host.patchRefuseClobber': 'Refusing to rewrite patch layer {file}: it cannot be parsed ({reason}), and rewriting would delete every row that could not be read',
740
+ 'host.patchRefusePromote': 'Refusing to write patch layer {file}: it would turn {ids} from insert (add) into top-level rows (override); the file is untouched (top-level rows override by id and are dropped entirely when not found)',
741
+ 'host.patchSemanticDrift': 'Structure self-check failed after serializing patch layer {file} ({detail}): the write was refused and the file is untouched',
738
742
  'host.fsPathEscape': 'Path outside home directory: {path}',
739
743
  'host.activationRowFailed': 'Plugin {pkg} is installed, but writing the activation row into the profile patch failed: {reason} (the plugin may be inactive until restart; retrying the install after fixing is idempotent)',
740
744
  'host.syncTokenWriteFailed': 'Failed to write the token into DSH credentials: {reason} (configure {ref} in DSH credential management, then retry)',
@@ -0,0 +1,107 @@
1
+ /**
2
+ * patch 文档结构重建(issue #133):顶层行 ≠ `- insert:` 块成员。
3
+ *
4
+ * 宿主合并循环里,顶层 `- id: X` 按 id **覆盖**(查不到就 `patch: entry "X" not found` 丢弃),
5
+ * 只有 insert 块成员是**新增**。旧实现把所有行统一输出成顶层行 —— 一条 update 就把只能靠
6
+ * insert 新增的条目(MCP server 最典型)在重启后整段作废。本文件钉住三条不变量:
7
+ * ① 既有 insert 成员更新后**归属不变**;② 新增(action:'insert')落进 insert 块;
8
+ * ③ 任一 id 不得同时具备两种身份。
9
+ */
10
+ import test from 'node:test';
11
+ import assert from 'node:assert/strict';
12
+
13
+ import {
14
+ describePatchDocument, describePatchLayoutDrift, PatchPromoteRefusedError, planPatchDocument,
15
+ } from './patch-document.ts';
16
+
17
+ const DOC = [
18
+ { id: 'top-a', name: '@deepseek-ai/dsh-top', disabled: false },
19
+ { insert: [
20
+ { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'npx' } },
21
+ { id: 'mcp-b', name: 'dsh-mcp-client', config: { transport: 'streamable-http', url: 'http://127.0.0.1:1/mcp' } },
22
+ ] },
23
+ { id: 'top-b', name: '@deepseek-ai/dsh-other' },
24
+ ];
25
+
26
+ test('#133 insert 块保真:更新一条 insert 成员后仍留在块里,成员集合不变', () => {
27
+ const plan = planPatchDocument(DOC, [
28
+ { lineId: 'mcp-a', raw: { id: 'mcp-a', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'uvx' } }, action: 'update' },
29
+ ]);
30
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
31
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
32
+ const block = plan.items.find((item) => Array.isArray((item as Record<string, unknown>)['insert'])) as { insert: { id: string; config: { command: string } }[] };
33
+ assert.ok(block !== undefined, 'insert 块必须仍然存在(旧实现会把它摊平成两条顶层行)');
34
+ assert.deepEqual(block.insert.map((e) => e.id), ['mcp-a', 'mcp-b']);
35
+ assert.equal(block.insert[0]?.config.command, 'uvx', '更新后的值写进块成员');
36
+ });
37
+
38
+ test('#133 顶层行更新不改归属(也不会掉进 insert 块)', () => {
39
+ const plan = planPatchDocument(DOC, [
40
+ { lineId: 'top-a', raw: { id: 'top-a', name: '@deepseek-ai/dsh-top', disabled: true }, action: 'update' },
41
+ ]);
42
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
43
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
44
+ assert.equal((plan.items[0] as { disabled: boolean }).disabled, true, '顶层行保持原位');
45
+ });
46
+
47
+ test('#133 新增条目走 insert 动作时落进 insert 块(新增语义,而不是覆盖)', () => {
48
+ const plan = planPatchDocument(DOC, [
49
+ { lineId: 'mcp-new', raw: { id: 'mcp-new', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'node' } }, action: 'insert' },
50
+ ]);
51
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b', 'mcp-new']);
52
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b'], '新增绝不能出现在顶层行里');
53
+ });
54
+
55
+ test('#133 update 动作写新 id 时保持旧的 upsert 语义(顶层行,不改既有契约)', () => {
56
+ const plan = planPatchDocument(DOC, [
57
+ { lineId: 'plain', raw: { id: 'plain', disabled: true }, action: 'update' },
58
+ ]);
59
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b', 'plain']);
60
+ assert.deepEqual(plan.insertIds, ['mcp-a', 'mcp-b']);
61
+ });
62
+
63
+ test('#133 remove 删掉 insert 成员后块仍保留其余成员', () => {
64
+ const plan = planPatchDocument(DOC, [{ lineId: 'mcp-a', raw: null, action: 'remove' }]);
65
+ assert.deepEqual(plan.insertIds, ['mcp-b']);
66
+ const blocks = plan.items.filter((item) => Array.isArray((item as Record<string, unknown>)['insert']));
67
+ assert.equal(blocks.length, 1);
68
+ });
69
+
70
+ test('#133 remove 删光 insert 成员后不留空块(空块会被宿主当空 insert)', () => {
71
+ const plan = planPatchDocument(DOC, [
72
+ { lineId: 'mcp-a', raw: null, action: 'remove' },
73
+ { lineId: 'mcp-b', raw: null, action: 'remove' },
74
+ ]);
75
+ assert.deepEqual(plan.insertIds, []);
76
+ assert.equal(plan.items.some((item) => Array.isArray((item as Record<string, unknown>)['insert'])), false);
77
+ assert.deepEqual(plan.topLevelIds, ['top-a', 'top-b']);
78
+ });
79
+
80
+ test('#133 空文档 + insert 动作:落成 insert 块(MCP 从零新建的路径)', () => {
81
+ const plan = planPatchDocument(undefined, [
82
+ { lineId: 'first', raw: { id: 'first', name: 'dsh-mcp-client', config: { transport: 'stdio', command: 'npx' } }, action: 'insert' },
83
+ ]);
84
+ assert.deepEqual(plan.insertIds, ['first']);
85
+ assert.deepEqual(plan.topLevelIds, []);
86
+ assert.equal(plan.items.length, 1);
87
+ });
88
+
89
+ test('#133 同一 id 不得同时具备两种身份(防御性不变量)', () => {
90
+ // 文档里同一 id 既在块里又在顶层:以首次出现为准,绝不产生「两种身份并存」的输出
91
+ const plan = planPatchDocument([
92
+ { insert: [{ id: 'dup', name: 'a' }] },
93
+ { id: 'dup', name: 'b' },
94
+ ], []);
95
+ assert.deepEqual(plan.insertIds, ['dup']);
96
+ assert.deepEqual(plan.topLevelIds, []);
97
+ assert.equal(new PatchPromoteRefusedError(['x']).ids[0], 'x');
98
+ });
99
+
100
+ test('#133 写后自检:布局不一致时给出可读差异(一致返回 null)', () => {
101
+ const planned = describePatchDocument(DOC);
102
+ assert.equal(describePatchLayoutDrift(planned, describePatchDocument(DOC)), null);
103
+ const drift = describePatchLayoutDrift(planned, { insertIds: [], topLevelIds: ['top-a', 'mcp-a', 'mcp-b', 'top-b'] });
104
+ assert.ok(drift !== null);
105
+ assert.match(String(drift), /insert=\[mcp-a, mcp-b\]/);
106
+ assert.match(String(drift), /got insert=\[\]/);
107
+ });