dsh-desktop-statusbar 3.0.5 → 3.0.7

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.
@@ -7,7 +7,7 @@
7
7
  * 删除后行消失、「恢复默认」找回(数据来自 docs/official-models.json);
8
8
  * ③ 模型价格气泡里**不再有**第三方平台字段(勾选 / 请求头 / 令牌 / 用户 ID / 地址 / 余额字段 / 倍率),
9
9
  * 改为价格卡下方独立的「第三方平台」区块:平台增删改、适用模型**自由输入行** → 按模型倍率写进价格条目、
10
- * secret 一次性(不回显 / 不落 localStorage)、地址留空 = 只按倍率计费、档案里没填的字段存空
10
+ * secret 一次性(不回显 / 不落 localStorage)、地址留空仍保存(endpoint 保持空,首次查询再自动探测)、档案里没填的字段存空
11
11
  * (默认值只在向宿主 POST 余额配置时补)、旧 relay 配置迁移成平台;
12
12
  * ③-2 平台名 123 / 英文 / 符号都能添加并立刻出现编辑行;「点别处」不会取消刚打开的平台编辑(task-41);
13
13
  * ④ 开发模式 0 次真实 fetch(中转站 GET 也要遵守);
@@ -19,9 +19,10 @@
19
19
  */
20
20
  const fs = require('fs');
21
21
  const path = require('path');
22
- const vm = require('vm');
23
22
  const assert = require('assert');
24
23
  const os = require('os');
24
+ const hostLib = require('./_host-lib');
25
+ const { findAll, hasClass, textOf, makeFakeDocument, runPlugin } = require('./helpers/client-harness');
25
26
 
26
27
  const TEMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), 'dsb-test-home-relay-settings-'));
27
28
  process.env.DSH_HOME = TEMP_HOME;
@@ -91,8 +92,11 @@ function useStateSlot(init) {
91
92
  ];
92
93
  }
93
94
 
94
- function loadClient(fetchImpl, initialStore) {
95
+ function loadClient(fetchImpl, initialStore, options) {
95
96
  /* initialStore:模拟"用户机器上已有的 localStorage"([key, value] 数组),用来测迁移播种 */
97
+ /* options.dom:传入 { platformNode } 时启用滚动模拟(给 getComputedStyle,并把平台编辑区
98
+ 节点挂到 platformEditRef 上),供 task-14 的「打开编辑区不滚动」回归测试使用。 */
99
+ const domOpt = options === undefined || options === null || options.dom === undefined ? null : options.dom;
96
100
  const store = new Map(initialStore === undefined ? [] : initialStore);
97
101
  const fetchLog = [];
98
102
  const fakeWindow = {
@@ -106,6 +110,7 @@ function loadClient(fetchImpl, initialStore) {
106
110
  addEventListener: () => {}, removeEventListener: () => {},
107
111
  requestAnimationFrame: (fn) => { fn(); return 0; },
108
112
  cancelAnimationFrame: () => {},
113
+ getComputedStyle: domOpt === null ? undefined : (node) => ({ overflowY: node !== null && node !== undefined && typeof node.__overflowY === 'string' ? node.__overflowY : '' }),
109
114
  fetch: (url, init) => {
110
115
  fetchLog.push({ url: String(url), init: init });
111
116
  return fetchImpl === undefined
@@ -113,15 +118,22 @@ function loadClient(fetchImpl, initialStore) {
113
118
  : fetchImpl(String(url), init);
114
119
  }
115
120
  };
116
- let captured = null;
117
- fakeWindow.__ModuleLoader__ = { load: (entry) => { captured = entry; } };
121
+
118
122
 
119
123
  const reactStub = {
120
- createElement: (type, props, ...children) => ({
121
- type: type,
122
- props: props === null || props === undefined ? {} : props,
123
- children: children.flat(Infinity).filter((one) => one !== null && one !== undefined && one !== false)
124
- }),
124
+ createElement: (type, props, ...children) => {
125
+ const node = {
126
+ type: type,
127
+ props: props === null || props === undefined ? {} : props,
128
+ children: children.flat(Infinity).filter((one) => one !== null && one !== undefined && one !== false)
129
+ };
130
+ /* domOpt:模拟 React 把平台编辑区 DOM 节点挂到 ref 上(滚动回归测试用) */
131
+ if (domOpt !== null && node.props.ref !== null && node.props.ref !== undefined && typeof node.props.ref === 'object'
132
+ && typeof node.props.className === 'string' && node.props.className.split(' ').indexOf('dsb-platform-pop') !== -1) {
133
+ node.props.ref.current = domOpt.platformNode;
134
+ }
135
+ return node;
136
+ },
125
137
  useState: (init) => useStateSlot(init),
126
138
  useEffect: (fn, deps) => {
127
139
  if (activeHooks === null || typeof fn !== 'function') return;
@@ -156,40 +168,9 @@ function loadClient(fetchImpl, initialStore) {
156
168
 
157
169
  /* 文档级 click 监听:页面上的「点别处收起编辑区」靠它。测试里可以主动派发一次
158
170
  「点在编辑区外面」的点击,验证它不会把刚打开的平台编辑行顺手取消掉。 */
159
- const docClicks = [];
160
- const fakeDocument = {
161
- documentElement: { classList: { add() {}, remove() {} } },
162
- querySelector: () => null,
163
- querySelectorAll: () => [],
164
- createElement: () => ({ dataset: {}, style: {}, appendChild() {}, setAttribute() {}, className: '' }),
165
- body: {}, head: { appendChild() {} },
166
- addEventListener: (name, fn) => { if (name === 'click' && docClicks.indexOf(fn) === -1) docClicks.push(fn); },
167
- removeEventListener: (name, fn) => {
168
- const at = docClicks.indexOf(fn);
169
- if (at !== -1) docClicks.splice(at, 1);
170
- }
171
- };
172
- const sandbox = {
173
- window: fakeWindow,
174
- document: fakeDocument,
175
- MutationObserver: class { observe() {} disconnect() {} },
176
- react: reactStub,
177
- console: console, Promise: Promise, Date: Date, Math: Math, JSON: JSON, Object: Object, Array: Array,
178
- Number: Number, String: String, Boolean: Boolean, Symbol: Symbol, Set: Set, Map: Map, Error: Error,
179
- setTimeout: setTimeout, clearTimeout: clearTimeout,
180
- requestAnimationFrame: (fn) => { fn(); return 0; },
181
- cancelAnimationFrame: () => {}
182
- };
183
- sandbox.globalThis = sandbox;
184
- vm.createContext(sandbox);
185
- vm.runInContext(injected, sandbox, { filename: 'client.js' });
186
- assert.ok(captured !== null && captured.factory !== undefined, '插件工厂没被捕获');
187
- const api = captured.factory((name) => {
188
- if (name === 'react') return reactStub;
189
- if (name === 'react-dom') throw new Error('no react-dom');
190
- throw new Error('unexpected require: ' + name);
191
- }).__test;
192
- assert.ok(api !== undefined, '__test 插桩导出没拿到');
171
+
172
+ const { document: fakeDocument, docClicks } = makeFakeDocument();
173
+ const api = runPlugin(injected, reactStub, fakeWindow, fakeDocument);
193
174
  return {
194
175
  api: api, store: store, fetchLog: fetchLog, hooks: makeHooks,
195
176
  /* 派发一次「点在编辑区外面」的文档点击(target 不是 DOM 节点 = 不在任何浮层里) */
@@ -209,30 +190,7 @@ function translator(api) {
209
190
  };
210
191
  }
211
192
  const plain = (value) => JSON.parse(JSON.stringify(value));
212
- function textOf(node) {
213
- const out = [];
214
- (function step(one) {
215
- if (typeof one === 'string' || typeof one === 'number') { out.push(String(one)); return; }
216
- if (one === null || one === undefined || one === false || one === true) return;
217
- if (Array.isArray(one)) { one.forEach(step); return; }
218
- if (typeof one !== 'object') return;
219
- (one.children || []).forEach(step);
220
- })(node);
221
- return out.join('');
222
- }
223
- function findAll(node, pred) {
224
- const out = [];
225
- (function step(one) {
226
- if (one === null || one === undefined || one === false || one === true) return;
227
- if (Array.isArray(one)) { one.forEach(step); return; }
228
- if (typeof one !== 'object') return;
229
- if (pred(one)) out.push(one);
230
- (one.children || []).forEach(step);
231
- })(node);
232
- return out;
233
- }
234
- const classOf = (node) => (typeof node.props.className === 'string' ? node.props.className : '');
235
- const hasClass = (node, name) => classOf(node).split(' ').indexOf(name) !== -1;
193
+
236
194
  const buttonsByLabel = (tree, label) => findAll(tree, (node) => node.type === 'button'
237
195
  && hasClass(node, 'dsb-action') && textOf(node) === label);
238
196
  const findLabelInput = (tree, label) => {
@@ -581,17 +539,44 @@ console.log('\n===== ③ 第三方平台区块(独立于模型价格气泡)
581
539
  const SECRET = 'sk-test-placeholder-0001';
582
540
  const USER_SECRET = 'user-42';
583
541
  {
584
- const channels = [{ channelKey: 'my-relay', tokenConfigured: true, userIdConfigured: false }];
542
+ /* 模拟 Host relayConfigView:非密字段会带运行时默认值(New-Api-User / data.quota / 500000),
543
+ 这些默认值不是用户填过的值,编辑区不得据此回填。 */
544
+ const channels = [{
545
+ channelKey: 'my-relay',
546
+ endpoint: '',
547
+ tokenHeader: 'authorization',
548
+ userIdHeader: 'New-Api-User',
549
+ tokenPrefix: 'Bearer ',
550
+ balancePath: 'data.quota',
551
+ currency: 'CNY',
552
+ feeMultiplier: 1,
553
+ balanceDivisor: 500000,
554
+ tokenConfigured: true,
555
+ userIdConfigured: false
556
+ }];
585
557
  const postBodies = [];
558
+ let relayPostOutcome = 'ok';
586
559
  const inst = loadClient((url, init) => {
587
560
  if (String(url).indexOf('/api/relay-balance-config') !== -1) {
588
561
  if (init !== undefined && init.method === 'POST') {
589
562
  postBodies.push(JSON.parse(init.body));
563
+ if (relayPostOutcome === 'fail') {
564
+ return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'relay-config-failed' }) });
565
+ }
566
+ if (relayPostOutcome === 'throw') return Promise.reject(new Error('relay network down'));
590
567
  const body = postBodies[postBodies.length - 1];
591
568
  return Promise.resolve({ json: () => Promise.resolve({
592
569
  ok: true,
593
570
  channels: body.remove === true ? [] : [{
594
571
  channelKey: body.channelKey,
572
+ endpoint: body.endpoint,
573
+ tokenHeader: body.tokenHeader,
574
+ userIdHeader: body.userIdHeader,
575
+ tokenPrefix: body.tokenPrefix,
576
+ balancePath: body.balancePath,
577
+ currency: body.currency,
578
+ feeMultiplier: body.feeMultiplier,
579
+ balanceDivisor: body.balanceDivisor,
595
580
  tokenConfigured: body.token !== undefined && body.token !== '',
596
581
  userIdConfigured: body.userId !== undefined && body.userId !== ''
597
582
  }]
@@ -626,7 +611,8 @@ const USER_SECRET = 'user-42';
626
611
  const feeLabelLines = (row) => findAll(row, (node) => (node.type === 'label' || node.type === 'div') && hasClass(node, 'dsb-relay-line')
627
612
  && textOf(node).indexOf(t('priceFeeMultiplier')) !== -1
628
613
  && findAll(node, (one) => one.type === 'input' && one.props.type === 'number').length > 0);
629
- const rowModelTrigger = (row, index) => findAll(modelLabelLines(row)[index], (node) => node.type === 'button' && hasClass(node, 'dsb-select-btn'))[0];
614
+ /* task-15:模型控件由 button 改为原生 input(可输入筛选),查找器按 input 找 */
615
+ const rowModelTrigger = (row, index) => findAll(modelLabelLines(row)[index], (node) => node.type === 'input' && hasClass(node, 'dsb-select-btn'))[0];
630
616
  const rowModelMenu = (row, index) => findAll(modelLabelLines(row)[index], (node) => hasClass(node, 'dsb-select-menu'))[0];
631
617
  const rowModelItems = (row, index) => findAll(rowModelMenu(row, index), (node) => node.type === 'button' && hasClass(node, 'dsb-select-item'));
632
618
  /* row 允许传节点或「返回当前树节点的函数」:菜单打开后树会重渲染,函数能取到带菜单的新节点 */
@@ -638,7 +624,7 @@ const USER_SECRET = 'user-42';
638
624
  const anchor = { getBoundingClientRect: () => rect, closest: (sel) => (sel === '.dsb-model' ? target : null) };
639
625
  return { stopPropagation: () => {}, currentTarget: { closest: (sel) => (sel === '.dsb-select' ? anchor : null) } };
640
626
  };
641
- const clickModelTrigger = (row, index) => rowModelTrigger(rowNodeOf(row), index).props.onClick(menuEvent(rowNodeOf(row)));
627
+ const clickModelTrigger = (row, index) => rowModelTrigger(rowNodeOf(row), index).props.onFocus(menuEvent(rowNodeOf(row)));
642
628
  const openModelMenu = (state, row, index) => {
643
629
  clickModelTrigger(row, index);
644
630
  rerender(state);
@@ -732,8 +718,10 @@ const USER_SECRET = 'user-42';
732
718
  assert.ok(textOf(modelLabelLines(row())[0]).indexOf(t('platformModels')) === 0, '模型行自带「适用模型」标签(标签在左、下拉紧随其后)');
733
719
  assert.ok(textOf(feeLabelLines(row())[0]).indexOf(t('priceFeeMultiplier')) === 0, '右半行以「费用倍率」标签开头(标签在左、输入框紧随其后)');
734
720
  const modelTrigger = rowModelTrigger(row(), 0);
735
- assert.ok(modelTrigger !== undefined, '每行有自定义下拉按钮');
736
- assert.strictEqual(textOf(modelTrigger), t('platformModelSelectPh'), '新行显示「请选择模型」占位');
721
+ assert.ok(modelTrigger !== undefined, '每行有可输入筛选的模型框(原生 input)');
722
+ assert.strictEqual(modelTrigger.props.type, 'text', '模型框是原生文本输入');
723
+ assert.strictEqual(modelTrigger.props.role, 'combobox', '模型框保留 combobox 语义');
724
+ assert.strictEqual(modelTrigger.props.placeholder, t('platformModelSelectPh'), '新行显示「请选择模型」占位');
737
725
  openModelMenu(state, row, 0);
738
726
  const modelItems = rowModelItems(row(), 0);
739
727
  const modelItemKeys = modelItems.map((node) => node.props.key);
@@ -741,7 +729,7 @@ const USER_SECRET = 'user-42';
741
729
  assert.ok(modelItemKeys.indexOf('deepseek-flash') !== -1, '菜单选项来自价格库(按 catalogOrder 的厂商顺序)');
742
730
  assert.strictEqual(textOf(modelItems[0]), 'DeepSeek-Flash', '菜单只含价格库模型名(displayModelName 显示)');
743
731
  pickModel(state, row, 0, 'deepseek-flash');
744
- assert.strictEqual(textOf(rowModelTrigger(row(), 0)), 'DeepSeek-Flash', '选中后按钮显示模型名');
732
+ assert.strictEqual(rowModelTrigger(row(), 0).props.value, 'DeepSeek-Flash', '选中后输入框显示模型名');
745
733
  assert.ok(rowFeeIn(row(), 0) !== undefined, '模型行仍有费用倍率输入框');
746
734
  assert.strictEqual(rowFeeIn(row(), 0).props.value, '', '倍率留空 = 1(不预填)');
747
735
  assert.strictEqual(rowFeeIn(row(), 0).props.placeholder, t('platformFeePh'), '倍率输入框提示文案「如 0.02」');
@@ -781,9 +769,17 @@ const USER_SECRET = 'user-42';
781
769
  openModelMenu(state, row, 2);
782
770
  const dupItem = rowModelItems(row(), 2).filter((node) => node.props.key === 'deepseek-flash')[0];
783
771
  assert.strictEqual(dupItem, undefined, '其他行已选中的模型从第三行下拉列表移除');
784
- assert.strictEqual(rowModelItems(row(), 2).length, 0, '夹具唯一模型已被其他行占用 ⇒ 该行菜单为空(占位项已删,无项可选)');
785
- clickModelTrigger(row, 2);
772
+ assert.strictEqual(rowModelItems(row(), 2).length, 0, '夹具唯一模型已被其他行占用 ⇒ 无候选可选');
773
+ assert.strictEqual(rowModelMenu(row(), 2), undefined, '无候选时完全不渲染 listbox');
774
+ assert.strictEqual(rowModelTrigger(row(), 2).props['aria-expanded'], 'false', '无候选时 aria-expanded=false');
775
+ rowModelTrigger(row(), 2).props.onChange({ target: { value: 'Custom-Model' } });
776
+ rerender(state);
777
+ assert.strictEqual(rowModelTrigger(row(), 2).props.value, 'Custom-Model', '自定义模型输入保留在筛选框');
778
+ assert.strictEqual(rowModelMenu(row(), 2), undefined, '自定义筛选文本不自动加入候选');
779
+ rowModelTrigger(row(), 2).props.onBlur({ currentTarget: { value: 'Custom-Model' } });
786
780
  rerender(state);
781
+ assert.strictEqual(rowModelTrigger(row(), 2).props.value, 'Custom-Model', '失焦并重渲染后仍显示自定义模型');
782
+ assert.strictEqual(rowModelMenu(row(), 2), undefined, '失焦后关闭无匹配筛选菜单');
787
783
  rowFeeIn(row(), 2).props.onChange({ target: { value: '0.5' } });
788
784
  rerender(state);
789
785
  buttonsByLabel(row(), t('priceSave'))[0].props.onClick();
@@ -799,8 +795,21 @@ const USER_SECRET = 'user-42';
799
795
  balancePath: 'data.quota',
800
796
  currency: 'CNY',
801
797
  balanceDivisor: 500000,
802
- models: [{ model: 'deepseek-flash', feeMultiplier: 2 }]
798
+ models: [{ model: 'deepseek-flash', feeMultiplier: 2 }, { model: 'Custom-Model', feeMultiplier: 0.5 }]
803
799
  }, '平台档案存非密字段(没填就是空)+ 适用模型 + 倍率;空行忽略、同名宽容去重');
800
+ platformHead(row()).props.onClick();
801
+ rerender(state);
802
+ assert.strictEqual(rowModelTrigger(row(), 1).props.value, 'Custom-Model', '保存后重新打开平台编辑区仍回显自定义模型');
803
+ openModelMenu(state, row, 1);
804
+ assert.strictEqual(rowModelMenu(row(), 1), undefined, '重开后未知自定义模型不应进入下拉候选');
805
+ assert.strictEqual(rowModelTrigger(row(), 1).props['aria-expanded'], 'false', '重开后未知自定义模型菜单保持关闭');
806
+ rowModelTrigger(row(), 1).props.onChange({ target: { value: '' } });
807
+ rerender(state);
808
+ const reopenedItems = rowModelItems(row(), 1);
809
+ assert.strictEqual(reopenedItems.length, 0, '清空筛选后当前夹具无可用候选');
810
+ assert.strictEqual(reopenedItems.filter((node) => node.props.key === 'Custom-Model').length, 0, '清空筛选后候选仍不含未知自定义模型');
811
+ rowModelTrigger(row(), 1).props.onKeyDown({ key: 'Escape', preventDefault: () => {} });
812
+ rerender(state);
804
813
  assert.strictEqual(savedModels(inst)['deepseek-flash'].feeMultiplier, 2, '适用模型写进价格条目倍率(宽容同名匹配到条目键)');
805
814
  assert.strictEqual(JSON.stringify(Array.from(inst.store.values())).indexOf(SECRET), -1, '令牌不写 localStorage');
806
815
  assert.strictEqual(JSON.stringify(Array.from(inst.store.values())).indexOf(USER_SECRET), -1, '用户 ID 不写 localStorage');
@@ -836,11 +845,13 @@ const USER_SECRET = 'user-42';
836
845
  rerender(state);
837
846
  assert.strictEqual(findLabelInput(row(), t('priceEndpoint')).props.value, 'https://relay.example.com/balance', '地址回填');
838
847
  assert.strictEqual(findLabelInput(row(), t('priceBalanceField')).props.value, '¥data.quota / 500000', '余额字段反拼回填');
839
- assert.strictEqual(findLabelInput(row(), t('priceTokenHeader')).props.value, '',
840
- '请求头没填过 → 打开时仍为空(不再回填 New-Api-User)');
841
- assert.strictEqual(modelLabelLines(row()).length, 1, '适用模型行按档案回填 1 行');
842
- assert.strictEqual(textOf(rowModelTrigger(row(), 0)), 'DeepSeek-Flash', '已保存的模型在下拉按钮中回填');
848
+ assert.strictEqual(findLabelInput(row(), t('priceTokenHeader')).props.value, 'New-Api-User',
849
+ '地址可用(saved.endpoint 非空)→ Host 默认请求头能查到余额,回填 New-Api-User');
850
+ assert.strictEqual(modelLabelLines(row()).length, 2, '适用模型行按档案回填 2 行');
851
+ assert.strictEqual(rowModelTrigger(row(), 0).props.value, 'DeepSeek-Flash', '已保存的模型在输入框中回填');
843
852
  assert.strictEqual(rowFeeIn(row(), 0).props.value, '2', '已存倍率回填');
853
+ assert.strictEqual(rowModelTrigger(row(), 1).props.value, 'Custom-Model', '保存的自定义模型在重开后回显');
854
+ assert.strictEqual(rowFeeIn(row(), 1).props.value, '0.5', '自定义模型倍率重开后回显');
844
855
  assert.strictEqual(findLabelInput(row(), t('priceToken')).props.value, '', '令牌打开时仍为空');
845
856
  assert.strictEqual(findLabelInput(row(), t('priceUserId')).props.value, '', '用户 ID 打开时仍为空');
846
857
  assert.strictEqual(findLabelInput(row(), t('priceToken')).props.placeholder, t('platformSecretSaved'),
@@ -871,7 +882,11 @@ const USER_SECRET = 'user-42';
871
882
  /* 删掉适用模型行 → 保存:价格条目上的倍率被清掉(平台档案里也不再列该模型) */
872
883
  buttonsByLabel(feeLabelLines(row())[0], t('priceRemove'))[0].props.onClick();
873
884
  rerender(state);
874
- assert.strictEqual(modelLabelLines(row()).length, 0, '行尾删除 → 该行消失');
885
+ assert.strictEqual(modelLabelLines(row()).length, 1, '删除 DeepSeek 后自定义模型行仍在');
886
+ assert.strictEqual(rowModelTrigger(row(), 0).props.value, 'Custom-Model', '删除顺序留下自定义模型');
887
+ buttonsByLabel(feeLabelLines(row())[0], t('priceRemove'))[0].props.onClick();
888
+ rerender(state);
889
+ assert.strictEqual(modelLabelLines(row()).length, 0, '删除两行后模型行全部消失');
875
890
  buttonsByLabel(row(), t('priceSave'))[0].props.onClick();
876
891
  await settle();
877
892
  rerender(state);
@@ -901,7 +916,7 @@ const USER_SECRET = 'user-42';
901
916
  buttonsByLabel(row(), t('priceSave'))[0].props.onClick();
902
917
  await settle();
903
918
  rerender(state);
904
- assert.ok(noticeShown(state, 'priceEndpointInvalid'), '地址非法 → 顶部提示');
919
+ assert.strictEqual(noticeShown(state, 'priceEndpointInvalid'), false, '地址非法 → 不显示顶部提示');
905
920
  assert.strictEqual(plain(savedPlatforms()['my-relay']).endpoint, '', '非法地址按空地址落库(不拦截保存)');
906
921
  platformHead(row()).props.onClick();
907
922
  rerender(state);
@@ -938,8 +953,8 @@ const USER_SECRET = 'user-42';
938
953
  '删除平台 → POST remove');
939
954
  assert.strictEqual(postBodies.length, beforeRemove + 1, '只发一条 remove');
940
955
 
941
- /* 只按倍率计费(地址留空):不查余额、不发余额配置请求,但倍率仍写进条目;
942
- 档案里没填的请求头 / 余额字段保持空(默认值只在向宿主 POST 时补) */
956
+ /* 只按倍率计费(地址留空):仍要 POST(endpoint 空,Host 保存空地址;
957
+ 首次查询再用平台配置探测余额端点),倍率仍写进条目;档案里没填的请求头 / 余额字段保持空 */
943
958
  const beforeLite = postBodies.length;
944
959
  addPlatform(state, 'magpie-like');
945
960
  const maggieRow = () => platformRow(state.tree, 'magpie-like');
@@ -963,13 +978,90 @@ const USER_SECRET = 'user-42';
963
978
  models: [{ model: 'deepseek-flash', feeMultiplier: 0.02 }]
964
979
  }, '地址为空 = 只按倍率计费;没填的余额字段与请求头**存空**,不塞默认值');
965
980
  assert.strictEqual(savedModels(inst)['deepseek-flash'].feeMultiplier, 0.02, '折扣倍率 0.02 落库');
966
- assert.strictEqual(postBodies.length, beforeLite, '地址留空不发余额配置请求');
981
+ assert.strictEqual(postBodies.length, beforeLite + 1, '地址留空仍提交(endpoint 空,交给 Host 保存并在首次查询时探测)');
982
+ assert.strictEqual(postBodies[postBodies.length - 1].endpoint, '', '地址留空 → POST 空 endpoint');
967
983
  const maggieHead = findAll(maggieRow(), (node) => hasClass(node, 'dsb-model-head'))[0];
968
984
  assert.ok(textOf(maggieHead).indexOf('magpie-like') !== -1, '平台头部只显示平台名');
969
985
  assert.strictEqual(textOf(maggieHead).indexOf('DeepSeek-Flash'), -1, '平台头部不显示适用模型名摘要');
970
986
  assert.strictEqual(textOf(maggieHead).indexOf('只按倍率计费'), -1, '平台头部不再显示「只按倍率计费」');
971
987
  assert.strictEqual(textOf(maggieHead).indexOf('未填适用模型'), -1, '平台头部不再显示「未填适用模型」');
972
988
 
989
+ /* 空白地址 + 令牌 + 用户 ID:令牌只随 POST 走,地址没填也必须提交;重新打开显示已保存占位。 */
990
+ const openPlatform = (name) => {
991
+ platformHead(platformRow(state.tree, name)).props.onClick();
992
+ rerender(state);
993
+ };
994
+ const beforeBlankSecret = postBodies.length;
995
+ addPlatform(state, 'blank-secret');
996
+ openPlatform('blank-secret');
997
+ findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceToken')).props.onChange({ target: { value: SECRET } });
998
+ rerender(state);
999
+ findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceUserId')).props.onChange({ target: { value: USER_SECRET } });
1000
+ rerender(state);
1001
+ buttonsByLabel(platformRow(state.tree, 'blank-secret'), t('priceSave'))[0].props.onClick();
1002
+ await settle();
1003
+ rerender(state);
1004
+ const blankSecretPost = postBodies[postBodies.length - 1];
1005
+ assert.strictEqual(postBodies.length, beforeBlankSecret + 1, '空白地址 + 令牌 + 用户 ID → 仍发一条 POST');
1006
+ assert.strictEqual(blankSecretPost.endpoint, '', '空白地址 → payload.endpoint 空串(Host 保存为空)');
1007
+ assert.strictEqual(blankSecretPost.token, SECRET, '空白地址也要带上令牌');
1008
+ assert.strictEqual(blankSecretPost.userId, USER_SECRET, '空白地址也要带上用户 ID');
1009
+ assert.strictEqual(blankSecretPost.balancePath, 'data.quota', '空白地址 → 其余字段仍补默认 data.quota');
1010
+ assert.strictEqual(blankSecretPost.balanceDivisor, 500000, '空白地址 → 其余字段仍补默认 500000');
1011
+ openPlatform('blank-secret');
1012
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceToken')).props.value, '', '重新打开:令牌框不回显明文');
1013
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceToken')).props.placeholder, t('platformSecretSaved'), '重新打开:令牌显示「已保存」占位');
1014
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceUserId')).props.value, '', '重新打开:用户 ID 不回显明文');
1015
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceUserId')).props.placeholder, t('platformSecretSaved'), '重新打开:用户 ID 显示「已保存」占位');
1016
+ /* 只填了令牌 / 用户 ID,请求头 / 地址 / 余额字段保持空:Host relayConfigView 回传的运行时默认值
1017
+ (New-Api-User / data.quota / 500000)不能当成用户填过的值回填。 */
1018
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceTokenHeader')).props.value, '', '重新打开:请求头仍为空(Host 默认值不回填)');
1019
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceEndpoint')).props.value, '', '重新打开:地址仍为空');
1020
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-secret'), t('priceBalanceField')).props.value, '', '重新打开:余额字段仍为空(Host 默认值不回填)');
1021
+
1022
+ /* task-26:空地址但已配 token/userId 的平台,删除也必须发幂等 remove。
1023
+ 旧逻辑只在 endpoint 非空时 remove,空地址平台会跳过 → Host 不清 credential →
1024
+ 同名重建仍残留 token/userId。这里补回归:删除空地址+已配 secret 的平台要发 remove。 */
1025
+ const beforeBlankSecretRemove = postBodies.length;
1026
+ buttonsByLabel(platformRow(state.tree, 'blank-secret'), t('priceRemove'))[0].props.onClick();
1027
+ await settle();
1028
+ rerender(state);
1029
+ assert.deepStrictEqual(plain(postBodies[postBodies.length - 1]), { remove: true, channelKey: 'blank-secret' },
1030
+ '空地址+已配 token/userId 的平台删除 → 仍发 remove');
1031
+ assert.strictEqual(postBodies.length, beforeBlankSecretRemove + 1, '空地址删除只发一条 remove');
1032
+ assert.strictEqual(plain(savedPlatforms())['blank-secret'], undefined, '空地址平台删除后本地档案消失');
1033
+
1034
+ /* 只填部分字段:只填令牌 / 只填用户 ID 也必须保存,另一个保持未配置。 */
1035
+ addPlatform(state, 'blank-token-only');
1036
+ openPlatform('blank-token-only');
1037
+ findLabelInput(platformRow(state.tree, 'blank-token-only'), t('priceToken')).props.onChange({ target: { value: 'sk-only-token' } });
1038
+ rerender(state);
1039
+ buttonsByLabel(platformRow(state.tree, 'blank-token-only'), t('priceSave'))[0].props.onClick();
1040
+ await settle();
1041
+ rerender(state);
1042
+ const tokenOnlyPost = postBodies[postBodies.length - 1];
1043
+ assert.strictEqual(tokenOnlyPost.endpoint, '', '只填令牌:地址仍为空也要 POST');
1044
+ assert.strictEqual(tokenOnlyPost.token, 'sk-only-token', '只填令牌:令牌要保存');
1045
+ assert.strictEqual(tokenOnlyPost.userId, undefined, '只填令牌:不伪造用户 ID');
1046
+ openPlatform('blank-token-only');
1047
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-token-only'), t('priceToken')).props.placeholder, t('platformSecretSaved'), '只填令牌:重新打开显示已保存');
1048
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-token-only'), t('priceUserId')).props.placeholder, t('priceUserIdHint'), '只填令牌:用户 ID 仍是未配置提示');
1049
+
1050
+ addPlatform(state, 'blank-user-only');
1051
+ openPlatform('blank-user-only');
1052
+ findLabelInput(platformRow(state.tree, 'blank-user-only'), t('priceUserId')).props.onChange({ target: { value: 'user-only-7' } });
1053
+ rerender(state);
1054
+ buttonsByLabel(platformRow(state.tree, 'blank-user-only'), t('priceSave'))[0].props.onClick();
1055
+ await settle();
1056
+ rerender(state);
1057
+ const userOnlyPost = postBodies[postBodies.length - 1];
1058
+ assert.strictEqual(userOnlyPost.endpoint, '', '只填用户 ID:地址仍为空也要 POST');
1059
+ assert.strictEqual(userOnlyPost.userId, 'user-only-7', '只填用户 ID:用户 ID 要保存');
1060
+ assert.strictEqual(userOnlyPost.token, undefined, '只填用户 ID:不伪造令牌');
1061
+ openPlatform('blank-user-only');
1062
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-user-only'), t('priceUserId')).props.placeholder, t('platformSecretSaved'), '只填用户 ID:重新打开显示已保存');
1063
+ assert.strictEqual(findLabelInput(platformRow(state.tree, 'blank-user-only'), t('priceToken')).props.placeholder, t('priceTokenHint'), '只填用户 ID:令牌仍是未配置提示');
1064
+
973
1065
  /* 删模型:平台档案保留,但该模型从「适用模型」里摘掉(不会连带丢掉无关平台) */
974
1066
  const priceFlashCard = findAll(state.tree, (node) => hasClass(node, 'dsb-model') && node.props.key === 'deepseek-flash')[0];
975
1067
  assert.ok(priceFlashCard !== undefined, '前置:deepseek-flash 价格卡在');
@@ -1002,8 +1094,10 @@ const USER_SECRET = 'user-42';
1002
1094
  '档案里这四项仍是空(默认值只在 POST 时补,不写回档案)');
1003
1095
  platformHead(clearRow()).props.onClick();
1004
1096
  rerender(state);
1005
- assert.strictEqual(findLabelInput(clearRow(), t('priceBalanceField')).props.value, '', '再次打开:余额字段仍为空');
1006
- assert.strictEqual(findLabelInput(clearRow(), t('priceTokenHeader')).props.value, '', '再次打开:请求头仍为空');
1097
+ assert.strictEqual(findLabelInput(clearRow(), t('priceBalanceField')).props.value, '¥data.quota / 500000',
1098
+ '再次打开:地址可用 → 默认余额字段能查到余额,回填默认值');
1099
+ assert.strictEqual(findLabelInput(clearRow(), t('priceTokenHeader')).props.value, 'New-Api-User',
1100
+ '再次打开:地址可用 → 默认请求头能查到余额,回填默认值');
1007
1101
  findLabelInput(clearRow(), t('priceEndpoint')).props.onChange({ target: { value: '' } });
1008
1102
  rerender(state);
1009
1103
  const beforeClear = postBodies.length;
@@ -1053,11 +1147,15 @@ const USER_SECRET = 'user-42';
1053
1147
  models: [{ model: 'deepseek-flash', feeMultiplier: 2 }]
1054
1148
  }
1055
1149
  }, '旧 relay 迁移成平台档案(平台名 = 模型名)');
1150
+ assert.deepStrictEqual(plain(migratedSnap.relayPlatformOrder), ['deepseek-flash'],
1151
+ '独立数组初始化:旧 relay 迁移出的平台进入显示顺序');
1056
1152
  const reloaded = loadClient(undefined, [[CONFIG_KEY, migrated.store.get(CONFIG_KEY)]]);
1057
1153
  assert.deepStrictEqual(plain(reloaded.api.snapshot().relayPlatforms), plain(migratedSnap.relayPlatforms),
1058
1154
  '二次加载平台档案保持不变(迁移幂等)');
1155
+ assert.deepStrictEqual(plain(reloaded.api.snapshot().relayPlatformOrder), ['deepseek-flash'],
1156
+ '二次加载显示顺序保持不变');
1059
1157
 
1060
- /* 旧档案兼容:平台里已有但价格库没有的旧模型名,也必须出现在该行下拉选项里 */
1158
+ /* 旧档案兼容:平台里已有但价格库没有的旧模型名只回显,不进入该行下拉选项 */
1061
1159
  const LEGACY_PLATFORM_CONFIG = JSON.stringify({
1062
1160
  version: 6, priceVersion: 7, currency: 'CNY',
1063
1161
  models: CNY_BASE,
@@ -1085,37 +1183,76 @@ const USER_SECRET = 'user-42';
1085
1183
  const legacyRow = () => findAll(legacyState.tree, (node) => hasClass(node, 'dsb-model') && node.props.key === 'legacy-p')[0];
1086
1184
  findAll(legacyRow(), (node) => hasClass(node, 'dsb-platform-head'))[0].props.onClick();
1087
1185
  legacyRender();
1088
- const legacyTrigger = findAll(legacyRow(), (node) => node.type === 'button' && hasClass(node, 'dsb-select-btn'))[0];
1089
- legacyTrigger.props.onClick(menuEvent(legacyRow()));
1186
+ const legacyTrigger = findAll(legacyRow(), (node) => node.type === 'input' && hasClass(node, 'dsb-select-btn'))[0];
1187
+ legacyTrigger.props.onFocus(menuEvent(legacyRow()));
1090
1188
  legacyRender();
1091
1189
  const legacyMenu = findAll(legacyRow(), (node) => hasClass(node, 'dsb-select-menu'))[0];
1092
1190
  const legacyOptions = findAll(legacyMenu, (node) => node.type === 'button' && hasClass(node, 'dsb-select-item')).map((node) => node.props.key);
1093
- assert.ok(legacyOptions.indexOf('old-model') !== -1, '旧档案模型不在价格库时,下拉仍并入该选项');
1094
- const legacyTriggers = findAll(legacyRow(), (node) => node.type === 'button' && hasClass(node, 'dsb-select-btn'));
1191
+ assert.strictEqual(legacyOptions.indexOf('old-model'), -1, '旧档案未知模型不进入下拉候选');
1192
+ const legacyTriggers = findAll(legacyRow(), (node) => node.type === 'input' && hasClass(node, 'dsb-select-btn'));
1095
1193
  assert.strictEqual(legacyTriggers.length, 3, '旧档案三行模型都渲染');
1096
- assert.strictEqual(textOf(legacyTriggers[1]), 'Mimo-V2.6-Pro-Ultraspeed', '24 字符长模型名完整显示');
1097
- assert.strictEqual(textOf(legacyTriggers[2]), 'Mimo-V2.6-Pro-Ultraspeed-Plus', '超长模型名完整显示');
1098
- /* 按容器宽度实测:scrollWidth 随当前字号等比缩放,模拟真实文本排版 */
1099
- const measureBtn = (baseWidth, clientWidth) => {
1100
- const el = { style: {}, clientWidth: clientWidth };
1101
- Object.defineProperty(el, 'scrollWidth', { get() { const size = parseFloat(el.style.fontSize || '13'); return Math.round(baseWidth * size / 13); } });
1102
- return el;
1194
+ assert.strictEqual(legacyTriggers[1].props.value, 'Mimo-V2.6-Pro-Ultraspeed', '24 字符长模型名完整保留(原生 input value)');
1195
+ assert.strictEqual(legacyTriggers[2].props.value, 'Mimo-V2.6-Pro-Ultraspeed-Plus', '超长模型名完整保留(原生 input value)');
1196
+ /* 原生 input 不再按容器宽度缩字号:长名靠 CSS 省略号截断显示,数据层保留全名 */
1197
+ legacyTriggers.forEach((trigger) => {
1198
+ assert.strictEqual(trigger.type, 'input', '模型控件是原生 input');
1199
+ assert.strictEqual(trigger.props.type, 'text', '模型控件是原生文本输入');
1200
+ assert.strictEqual(trigger.props.role, 'combobox', '模型控件保留 combobox 语义');
1201
+ assert.strictEqual(typeof trigger.props.onChange, 'function', '模型控件支持输入筛选');
1202
+ });
1203
+ /* Host 同步失败 / 抛错:只在 console.warn 留日志,平台区块不出现任何用户可见提示。
1204
+ 成功与字段校验提示不受影响。 */
1205
+ const relayFailureNotice = (reason) => t('priceRelaySyncFailed', { reason: reason });
1206
+ const relayNoticeShown = () => {
1207
+ const text = textOf(section(state.tree));
1208
+ return text.indexOf(relayFailureNotice('relay-config-failed')) !== -1
1209
+ || text.indexOf(relayFailureNotice('failed')) !== -1
1210
+ || text.indexOf('第三方平台配置同步失败') !== -1;
1211
+ };
1212
+ const withWarnCapture = async (fn) => {
1213
+ const lines = [];
1214
+ const original = console.warn;
1215
+ console.warn = (...args) => { lines.push(args.map((one) => String(one)).join(' ')); };
1216
+ try { await fn(); } finally { console.warn = original; }
1217
+ return lines;
1218
+ };
1219
+ const saveNewPlatform = async (name, endpoint) => {
1220
+ addPlatform(state, name);
1221
+ const target = () => platformRow(state.tree, name);
1222
+ platformHead(target()).props.onClick();
1223
+ rerender(state);
1224
+ if (endpoint !== undefined) {
1225
+ findLabelInput(target(), t('priceEndpoint')).props.onChange({ target: { value: endpoint } });
1226
+ rerender(state);
1227
+ }
1228
+ buttonsByLabel(target(), t('priceSave'))[0].props.onClick();
1229
+ await settle();
1230
+ rerender(state);
1103
1231
  };
1104
- const shortBtn = measureBtn(120, 240);
1105
- legacyTriggers[0].props.ref(shortBtn);
1106
- assert.strictEqual(shortBtn.style.fontSize, '13px', '短名不缩小,默认 13px');
1107
- const midBtn = measureBtn(210, 200);
1108
- legacyTriggers[1].props.ref(midBtn);
1109
- assert.strictEqual(midBtn.style.fontSize, '12px', '长名按容器宽度自适应缩小(12px 能放下)');
1110
- const longBtn = measureBtn(400, 180);
1111
- legacyTriggers[2].props.ref(longBtn);
1112
- assert.strictEqual(longBtn.style.fontSize, '10px', '超长名最多缩到 10px 下限');
1113
- const resetBtn = measureBtn(120, 240);
1114
- resetBtn.style.fontSize = '10px';
1115
- legacyTriggers[0].props.ref(resetBtn);
1116
- assert.strictEqual(resetBtn.style.fontSize, '13px', '每次重渲染重置 13px 再量');
1117
- assert.strictEqual(typeof legacyTriggers[0].props.ref, 'function', '模型按钮挂载 ref 自适应回调');
1118
- console.log(' 气泡无第三方字段;平台增删改;模型下拉→倍率落库;secret 一次性;地址留空=只按倍率;旧 relay 迁移成平台;旧档案模型可选');
1232
+ /* 成功:不显示同步失败提示 */
1233
+ relayPostOutcome = 'ok';
1234
+ await saveNewPlatform('sync-ok', 'https://relay.example.com/balance');
1235
+ assert.strictEqual(relayNoticeShown(), false, '同步成功不显示 priceRelaySyncFailed');
1236
+ /* postRelayState 返回 ok:false:不显示提示,只写 console.warn */
1237
+ relayPostOutcome = 'fail';
1238
+ const failWarns = await withWarnCapture(async () => { await saveNewPlatform('sync-fail', 'https://relay.example.com/balance'); });
1239
+ assert.strictEqual(relayNoticeShown(), false, 'postRelayState 返回失败时平台编辑区不出现 priceRelaySyncFailed');
1240
+ assert.ok(failWarns.some((line) => line.indexOf(relayFailureNotice('relay-config-failed')) !== -1),
1241
+ '同步失败只写 console.warn(带 Host 返回的 reason)');
1242
+ /* postRelayState 抛错:同样不显示提示,只写 console.warn */
1243
+ relayPostOutcome = 'throw';
1244
+ const throwWarns = await withWarnCapture(async () => { await saveNewPlatform('sync-throw', 'https://relay.example.com/balance'); });
1245
+ assert.strictEqual(relayNoticeShown(), false, 'postRelayState 抛错时平台编辑区不出现 priceRelaySyncFailed');
1246
+ assert.ok(throwWarns.some((line) => line.indexOf(relayFailureNotice('failed')) !== -1),
1247
+ '同步抛错只写 console.warn(reason=failed)');
1248
+ /* 字段校验提示不受影响:同步失败的同一轮仍显示地址非法提示 */
1249
+ relayPostOutcome = 'fail';
1250
+ await saveNewPlatform('sync-validation', 'not-a-url');
1251
+ assert.strictEqual(relayNoticeShown(), false, '同步失败不出现 priceRelaySyncFailed');
1252
+ assert.strictEqual(noticeShown(state, 'priceEndpointInvalid'), false, '同步失败时不显示 priceEndpointInvalid');
1253
+ relayPostOutcome = 'ok';
1254
+ console.log(' 同步失败/抛错只 console.warn,不显示 priceRelaySyncFailed;校验提示照常');
1255
+ console.log(' 气泡无第三方字段;平台增删改;模型下拉→倍率落库;secret 一次性;地址留空=只按倍率;旧 relay 迁移成平台;旧档案模型只回显');
1119
1256
  }
1120
1257
 
1121
1258
  /* ====================================================================
@@ -1222,6 +1359,828 @@ console.log('\n===== ③-2 平台名 123/英文/符号都能添加;点别处
1222
1359
  console.log(' 123 / abcXYZ / My Relay 2.0 / a_b-c 都能添加并出现编辑行;空平台存空;点别处不取消');
1223
1360
  }
1224
1361
 
1362
+ /* ====================================================================
1363
+ ③-2b 平台显示顺序:纯数字名排最后 / 旧配置迁移 / 删除重加
1364
+ ==================================================================== */
1365
+ console.log('\n===== ③-2b 平台显示顺序(纯数字名 35326 排最后) =====');
1366
+ {
1367
+ const inst = loadClient();
1368
+ const api = inst.api;
1369
+ const t = translator(api);
1370
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: {} });
1371
+ const props = { t: t, useProjection: () => undefined };
1372
+ const bucket = inst.hooks();
1373
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1374
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1375
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1376
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1377
+ const rowNames = () => findAll(section(), (node) => hasClass(node, 'dsb-model') && typeof node.props.key === 'string').map((node) => node.props.key);
1378
+ const typeName = (value) => {
1379
+ const input = findAll(section(), (node) => node.type === 'input' && node.props.placeholder === t('platformNewPh'))[0];
1380
+ input.props.onChange({ target: { value: value } });
1381
+ rerender();
1382
+ };
1383
+ const clickAdd = () => { buttonsByLabel(section(), t('platformAdd'))[0].props.onClick(); rerender(); };
1384
+ const addPlatform = (name) => { typeName(name); clickAdd(); };
1385
+
1386
+ addPlatform('alpha');
1387
+ addPlatform('beta');
1388
+ addPlatform('35326');
1389
+ assert.deepStrictEqual(plain(api.snapshot().relayPlatformOrder), ['alpha', 'beta', '35326'],
1390
+ '添加顺序写进 relayPlatformOrder');
1391
+ assert.deepStrictEqual(rowNames(), ['alpha', 'beta', '35326'],
1392
+ '渲染顺序:纯数字平台 35326 排最后(不因 JS 键序跑到前面)');
1393
+
1394
+ /* 保存平台不改顺序 */
1395
+ findAll(platformRow('alpha'), (node) => hasClass(node, 'dsb-platform-head'))[0].props.onClick();
1396
+ rerender();
1397
+ buttonsByLabel(platformRow('alpha'), t('priceSave'))[0].props.onClick();
1398
+ rerender();
1399
+ assert.deepStrictEqual(plain(api.snapshot().relayPlatformOrder), ['alpha', 'beta', '35326'],
1400
+ '保存平台不改顺序');
1401
+
1402
+ /* 删除中间平台 → 数组同步移除;重加同名平台 → 回到末尾 */
1403
+ buttonsByLabel(platformRow('beta'), t('priceRemove'))[0].props.onClick();
1404
+ rerender();
1405
+ assert.ok(platformRow('beta') === undefined, '删除平台后行消失');
1406
+ assert.deepStrictEqual(plain(api.snapshot().relayPlatformOrder), ['alpha', '35326'],
1407
+ '删除平台从 relayPlatformOrder 移除');
1408
+ addPlatform('beta');
1409
+ assert.deepStrictEqual(plain(api.snapshot().relayPlatformOrder), ['alpha', '35326', 'beta'],
1410
+ '重新添加同名平台回到末尾');
1411
+ assert.deepStrictEqual(rowNames(), ['alpha', '35326', 'beta'],
1412
+ '渲染顺序同步(重加不插回原位置)');
1413
+
1414
+ /* setConfig 更新其它字段时保留顺序 */
1415
+ api.setConfig({ models: CNY_BASE });
1416
+ assert.deepStrictEqual(plain(api.snapshot().relayPlatformOrder), ['alpha', '35326', 'beta'],
1417
+ 'setConfig 更新价格库时保留 relayPlatformOrder');
1418
+
1419
+ /* 持久化重载:顺序与平台表一起存进 localStorage,重载后不丢 */
1420
+ const reloaded = loadClient(undefined, [[api.STORAGE_KEY, inst.store.get(api.STORAGE_KEY)]]);
1421
+ assert.deepStrictEqual(plain(reloaded.api.snapshot().relayPlatformOrder), ['alpha', '35326', 'beta'],
1422
+ '持久化重载后平台顺序保持不变');
1423
+ assert.deepStrictEqual(Object.keys(plain(reloaded.api.snapshot().relayPlatforms)).sort(), ['35326', 'alpha', 'beta'],
1424
+ '持久化重载后平台不丢');
1425
+ console.log(' 35326 添加后排最后;保存不改顺序;删除移除、重加回末尾;重载顺序保持');
1426
+ }
1427
+
1428
+ /* 旧配置没有 relayPlatformOrder:按当前 Object.keys(relayPlatforms) 初始化,保留既有显示顺序 */
1429
+ {
1430
+ const probe = loadClient();
1431
+ const CONFIG_KEY = probe.api.STORAGE_KEY;
1432
+ const LEGACY_ORDER_CONFIG = JSON.stringify({
1433
+ version: 6,
1434
+ priceVersion: 8,
1435
+ currency: 'CNY',
1436
+ models: CNY_BASE,
1437
+ modelOrder: ['deepseek-flash'],
1438
+ relayPlatforms: {
1439
+ zeta: { endpoint: '', models: [] },
1440
+ alpha: { endpoint: '', models: [] },
1441
+ beta: { endpoint: '', models: [] }
1442
+ }
1443
+ });
1444
+ const legacyInst = loadClient(undefined, [[CONFIG_KEY, LEGACY_ORDER_CONFIG]]);
1445
+ const legacyApi = legacyInst.api;
1446
+ const legacySnap = legacyApi.snapshot();
1447
+ assert.deepStrictEqual(plain(legacySnap.relayPlatformOrder), ['zeta', 'alpha', 'beta'],
1448
+ '旧配置迁移:按 Object.keys(relayPlatforms) 初始化,保留既有显示顺序');
1449
+ assert.deepStrictEqual(Object.keys(plain(legacySnap.relayPlatforms)).sort(), ['alpha', 'beta', 'zeta'],
1450
+ '迁移不丢任何平台');
1451
+ const legacyT = translator(legacyApi);
1452
+ const legacyTree = withHooks(legacyInst.hooks(), () => legacyApi.SettingsSection({ t: legacyT, useProjection: () => undefined }));
1453
+ const legacySection = findAll(legacyTree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1454
+ const legacyNames = findAll(legacySection, (node) => hasClass(node, 'dsb-model') && typeof node.props.key === 'string').map((node) => node.props.key);
1455
+ assert.deepStrictEqual(legacyNames, ['zeta', 'alpha', 'beta'], '迁移后渲染顺序与旧显示顺序一致');
1456
+
1457
+ /* 手改配置:数组只列了部分平台(还带已删除的脏名字)→ 仍存在的按数组顺序,缺的按 Object.keys 补末尾 */
1458
+ const PARTIAL_CONFIG = JSON.stringify({
1459
+ version: 6,
1460
+ priceVersion: 8,
1461
+ currency: 'CNY',
1462
+ models: CNY_BASE,
1463
+ modelOrder: ['deepseek-flash'],
1464
+ relayPlatforms: {
1465
+ alpha: { endpoint: '', models: [] },
1466
+ beta: { endpoint: '', models: [] },
1467
+ gamma: { endpoint: '', models: [] }
1468
+ },
1469
+ relayPlatformOrder: ['ghost', 'beta']
1470
+ });
1471
+ const partial = loadClient(undefined, [[CONFIG_KEY, PARTIAL_CONFIG]]);
1472
+ assert.deepStrictEqual(plain(partial.api.snapshot().relayPlatformOrder), ['beta', 'alpha', 'gamma'],
1473
+ '手改配置:数组里缺的平台按 Object.keys 补末尾,脏名字丢弃');
1474
+ console.log(' 旧配置迁移保留 zeta→alpha→beta;缺项按 Object.keys 补末尾且不丢平台');
1475
+ }
1476
+
1477
+ /* ====================================================================
1478
+ ③-3 Host 默认值只在 saved.endpoint 非空(地址可用)时回显
1479
+ ==================================================================== */
1480
+ console.log('\n===== ③-3 Host 默认值仅在地址可用时回显 =====');
1481
+ {
1482
+ const inst = loadClient((url) => {
1483
+ if (String(url).indexOf('/api/relay-balance-config') !== -1) {
1484
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: [
1485
+ {
1486
+ channelKey: 'probed',
1487
+ endpoint: 'https://relay.example.com/balance',
1488
+ tokenHeader: 'authorization',
1489
+ userIdHeader: 'New-Api-User',
1490
+ tokenPrefix: 'Bearer ',
1491
+ balancePath: 'data.quota',
1492
+ currency: 'CNY',
1493
+ feeMultiplier: 1,
1494
+ balanceDivisor: 500000,
1495
+ tokenConfigured: true,
1496
+ userIdConfigured: true
1497
+ },
1498
+ {
1499
+ channelKey: 'unprobed',
1500
+ endpoint: '',
1501
+ tokenHeader: 'authorization',
1502
+ userIdHeader: 'New-Api-User',
1503
+ tokenPrefix: 'Bearer ',
1504
+ balancePath: 'data.quota',
1505
+ currency: 'CNY',
1506
+ feeMultiplier: 1,
1507
+ balanceDivisor: 500000,
1508
+ tokenConfigured: true,
1509
+ userIdConfigured: true
1510
+ }
1511
+ ] }) });
1512
+ }
1513
+ return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
1514
+ });
1515
+ const api = inst.api;
1516
+ const t = translator(api);
1517
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
1518
+ api.setConfig({
1519
+ models: CNY_BASE,
1520
+ modelOrder: ['deepseek-flash'],
1521
+ priceConfigured: true,
1522
+ relayPlatforms: { probed: plain(emptyPlatform), unprobed: plain(emptyPlatform) }
1523
+ });
1524
+ await api.ensureRelayState();
1525
+ const props = { t: t, useProjection: () => undefined };
1526
+ const bucket = inst.hooks();
1527
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1528
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1529
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1530
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1531
+ const open = (name) => {
1532
+ findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0].props.onClick();
1533
+ rerender();
1534
+ };
1535
+ open('probed');
1536
+ assert.strictEqual(findLabelInput(platformRow('probed'), t('priceTokenHeader')).props.value, 'New-Api-User',
1537
+ '地址可用 → 回显宿主默认请求头 New-Api-User');
1538
+ assert.strictEqual(findLabelInput(platformRow('probed'), t('priceBalanceField')).props.value, '¥data.quota / 500000',
1539
+ '地址可用 → 回显宿主默认余额字段 ¥data.quota / 500000');
1540
+ assert.strictEqual(findLabelInput(platformRow('probed'), t('priceEndpoint')).props.value, 'https://relay.example.com/balance',
1541
+ '地址可用 → 回显宿主可用地址');
1542
+ assert.strictEqual(findLabelInput(platformRow('probed'), t('priceToken')).props.placeholder, t('platformSecretSaved'),
1543
+ '地址可用 → 令牌仍是已保存状态');
1544
+ assert.strictEqual(findLabelInput(platformRow('probed'), t('priceUserId')).props.placeholder, t('platformSecretSaved'),
1545
+ '地址可用 → 用户 ID 仍是已保存状态');
1546
+ open('unprobed');
1547
+ assert.strictEqual(findLabelInput(platformRow('unprobed'), t('priceTokenHeader')).props.value, '',
1548
+ '地址为空 → 不回显默认请求头');
1549
+ assert.strictEqual(findLabelInput(platformRow('unprobed'), t('priceBalanceField')).props.value, '',
1550
+ '地址为空 → 不回显默认余额字段');
1551
+ assert.strictEqual(findLabelInput(platformRow('unprobed'), t('priceEndpoint')).props.value, '',
1552
+ '地址为空 → 地址保持空');
1553
+ assert.strictEqual(findLabelInput(platformRow('unprobed'), t('priceToken')).props.placeholder, t('platformSecretSaved'),
1554
+ '地址为空 → 令牌仍是已保存状态');
1555
+ assert.strictEqual(findLabelInput(platformRow('unprobed'), t('priceUserId')).props.placeholder, t('platformSecretSaved'),
1556
+ '地址为空 → 用户 ID 仍是已保存状态');
1557
+ console.log(' saved.endpoint 非空 → 显示 Host 默认值;endpoint 为空 → 只显示本地显式值(空)');
1558
+ }
1559
+ /* ====================================================================
1560
+ ③-4 清空 Host 自动探测地址:不残留运行时默认值 / 显式值保留 / 真 remove
1561
+ ==================================================================== */
1562
+ console.log('\n===== ③-4 清空 Host 探测地址:不残留默认值 / 显式值保留 / 真 remove =====');
1563
+ {
1564
+ /* fake 宿主:只维护一个 channel 内存表;GET 返回它,POST 按 payload 更新 / remove。
1565
+ 用于模拟「Host 自动探测写入 endpoint,而本地旧档案 endpoint 为空」。 */
1566
+ const hostChannels = new Map();
1567
+ const posts = [];
1568
+ const inst = loadClient((url, init) => {
1569
+ if (String(url).indexOf('/api/relay-balance-config') === -1) {
1570
+ return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
1571
+ }
1572
+ if (init !== undefined && init !== null && init.method === 'POST') {
1573
+ const body = JSON.parse(init.body);
1574
+ posts.push(body);
1575
+ if (body.remove === true) {
1576
+ hostChannels.delete(body.channelKey);
1577
+ } else {
1578
+ hostChannels.set(body.channelKey, {
1579
+ channelKey: body.channelKey,
1580
+ endpoint: body.endpoint,
1581
+ tokenHeader: body.tokenHeader,
1582
+ userIdHeader: body.userIdHeader,
1583
+ tokenPrefix: body.tokenPrefix,
1584
+ balancePath: body.balancePath,
1585
+ currency: body.currency,
1586
+ feeMultiplier: body.feeMultiplier,
1587
+ balanceDivisor: body.balanceDivisor,
1588
+ tokenConfigured: body.token !== undefined && body.token !== '',
1589
+ userIdConfigured: body.userId !== undefined && body.userId !== ''
1590
+ });
1591
+ }
1592
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: Array.from(hostChannels.values()) }) });
1593
+ }
1594
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: Array.from(hostChannels.values()) }) });
1595
+ });
1596
+ const api = inst.api;
1597
+ const t = translator(api);
1598
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
1599
+ /* Host 已自动探测出可用地址(endpoint 非空),但本地旧档案 endpoint 为空、默认字段也为空 */
1600
+ const probedChannel = (key) => ({
1601
+ channelKey: key,
1602
+ endpoint: 'https://host.example.com/balance',
1603
+ tokenHeader: 'authorization',
1604
+ userIdHeader: 'New-Api-User',
1605
+ tokenPrefix: 'Bearer ',
1606
+ balancePath: 'data.quota',
1607
+ currency: 'CNY',
1608
+ feeMultiplier: 1,
1609
+ balanceDivisor: 500000,
1610
+ tokenConfigured: true,
1611
+ userIdConfigured: true
1612
+ });
1613
+ hostChannels.set('probed-clear', probedChannel('probed-clear'));
1614
+ hostChannels.set('probed-explicit', probedChannel('probed-explicit'));
1615
+ hostChannels.set('probed-retype-user', probedChannel('probed-retype-user'));
1616
+ hostChannels.set('probed-retype-balance', probedChannel('probed-retype-balance'));
1617
+ /* task-29:Host 自动探测出 credits 余额(balanceKind=credits,balancePath 保留原始 '$.balance',精确 divisor/currency) */
1618
+ hostChannels.set('probed-credits', {
1619
+ channelKey: 'probed-credits',
1620
+ endpoint: 'https://credits.example.com/api/balance',
1621
+ tokenHeader: 'authorization',
1622
+ userIdHeader: 'New-Api-User',
1623
+ tokenPrefix: 'Bearer ',
1624
+ balancePath: '$.balance',
1625
+ currency: 'USD',
1626
+ feeMultiplier: 1,
1627
+ balanceDivisor: 1,
1628
+ balanceKind: 'credits',
1629
+ tokenConfigured: true,
1630
+ userIdConfigured: true
1631
+ });
1632
+ api.setConfig({
1633
+ models: CNY_BASE,
1634
+ modelOrder: ['deepseek-flash'],
1635
+ priceConfigured: true,
1636
+ relayPlatforms: { 'probed-clear': plain(emptyPlatform), 'probed-explicit': plain(emptyPlatform), 'probed-retype-user': plain(emptyPlatform), 'probed-retype-balance': plain(emptyPlatform), 'probed-credits': plain(emptyPlatform) }
1637
+ });
1638
+ await api.ensureRelayState();
1639
+ const props = { t: t, useProjection: () => undefined };
1640
+ const bucket = inst.hooks();
1641
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1642
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1643
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1644
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1645
+ const open = (name) => {
1646
+ findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0].props.onClick();
1647
+ rerender();
1648
+ };
1649
+ const savedPlatforms = () => JSON.parse(inst.store.get(api.STORAGE_KEY)).relayPlatforms;
1650
+
1651
+ /* —— 场景一:清空 Host 探测地址 → 真 remove,且本地不残留运行时默认值 —— */
1652
+ open('probed-clear');
1653
+ assert.strictEqual(findLabelInput(platformRow('probed-clear'), t('priceTokenHeader')).props.value, 'New-Api-User',
1654
+ '前置:地址可用 → 回显 Host 默认请求头');
1655
+ findLabelInput(platformRow('probed-clear'), t('priceEndpoint')).props.onChange({ target: { value: '' } });
1656
+ rerender();
1657
+ buttonsByLabel(platformRow('probed-clear'), t('priceSave'))[0].props.onClick();
1658
+ await settle();
1659
+ rerender();
1660
+ assert.deepStrictEqual(plain(posts[posts.length - 1]), { remove: true, channelKey: 'probed-clear' },
1661
+ 'Host 当前有地址、本地为空 → 清空时必须是 remove,不能 POST 空 endpoint');
1662
+ const cleared = plain(savedPlatforms()['probed-clear']);
1663
+ assert.strictEqual(cleared.endpoint, '', '本地 endpoint 保持空');
1664
+ assert.deepStrictEqual([cleared.userIdHeader, cleared.balancePath, cleared.currency, cleared.balanceDivisor], ['', '', '', null],
1665
+ 'Host 预填的请求头 / 余额字段不能变成永久本地值');
1666
+ open('probed-clear');
1667
+ assert.strictEqual(findLabelInput(platformRow('probed-clear'), t('priceTokenHeader')).props.value, '', '清空后重开:不再残留默认请求头');
1668
+ assert.strictEqual(findLabelInput(platformRow('probed-clear'), t('priceBalanceField')).props.value, '', '清空后重开:不再残留默认余额字段');
1669
+ assert.strictEqual(findLabelInput(platformRow('probed-clear'), t('priceEndpoint')).props.value, '', '清空后重开:地址仍为空');
1670
+
1671
+ /* —— 场景二:用户明确改过的值仍保留(自动值不残留) —— */
1672
+ open('probed-explicit');
1673
+ findLabelInput(platformRow('probed-explicit'), t('priceTokenHeader')).props.onChange({ target: { value: 'X-Custom-Id' } });
1674
+ rerender();
1675
+ findLabelInput(platformRow('probed-explicit'), t('priceEndpoint')).props.onChange({ target: { value: '' } });
1676
+ rerender();
1677
+ const beforeExplicit = posts.length;
1678
+ buttonsByLabel(platformRow('probed-explicit'), t('priceSave'))[0].props.onClick();
1679
+ await settle();
1680
+ rerender();
1681
+ assert.deepStrictEqual(plain(posts[posts.length - 1]), { remove: true, channelKey: 'probed-explicit' },
1682
+ '显式改过请求头后清空地址 → 仍是 remove');
1683
+ assert.strictEqual(posts.length, beforeExplicit + 1, '清空地址只发一条 remove');
1684
+ const explicitSaved = plain(savedPlatforms()['probed-explicit']);
1685
+ assert.strictEqual(explicitSaved.userIdHeader, 'X-Custom-Id', '用户明确改过的请求头保留');
1686
+ assert.deepStrictEqual([explicitSaved.balancePath, explicitSaved.currency, explicitSaved.balanceDivisor], ['', '', null],
1687
+ '未改动的默认余额字段不残留');
1688
+ open('probed-explicit');
1689
+ assert.strictEqual(findLabelInput(platformRow('probed-explicit'), t('priceTokenHeader')).props.value, 'X-Custom-Id',
1690
+ '重开:显式请求头保留');
1691
+ assert.strictEqual(findLabelInput(platformRow('probed-explicit'), t('priceBalanceField')).props.value, '',
1692
+ '重开:自动余额字段仍为空');
1693
+ /* —— 场景三:重新输入的请求头恰好等于 Host 默认值 → 仍作为显式值保留 —— */
1694
+ open('probed-retype-user');
1695
+ findLabelInput(platformRow('probed-retype-user'), t('priceTokenHeader')).props.onChange({ target: { value: 'New-Api-User' } });
1696
+ rerender();
1697
+ findLabelInput(platformRow('probed-retype-user'), t('priceEndpoint')).props.onChange({ target: { value: '' } });
1698
+ rerender();
1699
+ buttonsByLabel(platformRow('probed-retype-user'), t('priceSave'))[0].props.onClick();
1700
+ await settle();
1701
+ rerender();
1702
+ assert.deepStrictEqual(plain(posts[posts.length - 1]), { remove: true, channelKey: 'probed-retype-user' }, '重新输入默认请求头后清空地址 → remove');
1703
+ const retypeUser = plain(savedPlatforms()['probed-retype-user']);
1704
+ assert.strictEqual(retypeUser.userIdHeader, 'New-Api-User', '明确重新输入的默认请求头必须保留(不因等于 Host 默认而被清)');
1705
+ assert.deepStrictEqual([retypeUser.balancePath, retypeUser.currency, retypeUser.balanceDivisor], ['', '', null], '未改动的余额字段仍不残留');
1706
+ open('probed-retype-user');
1707
+ assert.strictEqual(findLabelInput(platformRow('probed-retype-user'), t('priceTokenHeader')).props.value, 'New-Api-User', '重开:保留重新输入的默认请求头');
1708
+
1709
+ /* —— 场景四:重新输入的余额字段恰好等于 Host 默认值 → 仍作为显式值保留 —— */
1710
+ open('probed-retype-balance');
1711
+ findLabelInput(platformRow('probed-retype-balance'), t('priceBalanceField')).props.onChange({ target: { value: '¥data.quota / 500000' } });
1712
+ rerender();
1713
+ findLabelInput(platformRow('probed-retype-balance'), t('priceEndpoint')).props.onChange({ target: { value: '' } });
1714
+ rerender();
1715
+ buttonsByLabel(platformRow('probed-retype-balance'), t('priceSave'))[0].props.onClick();
1716
+ await settle();
1717
+ rerender();
1718
+ assert.deepStrictEqual(plain(posts[posts.length - 1]), { remove: true, channelKey: 'probed-retype-balance' }, '重新输入默认余额字段后清空地址 → remove');
1719
+ const retypeBal = plain(savedPlatforms()['probed-retype-balance']);
1720
+ assert.deepStrictEqual([retypeBal.balancePath, retypeBal.currency, retypeBal.balanceDivisor], ['data.quota', 'CNY', 500000], '明确重新输入的默认余额字段必须保留');
1721
+ assert.strictEqual(retypeBal.userIdHeader, '', '未改动的请求头不残留');
1722
+ open('probed-retype-balance');
1723
+ assert.strictEqual(findLabelInput(platformRow('probed-retype-balance'), t('priceBalanceField')).props.value, '¥data.quota / 500000', '重开:保留重新输入的默认余额字段');
1724
+ assert.strictEqual(findLabelInput(platformRow('probed-retype-balance'), t('priceTokenHeader')).props.value, '', '重开:未改动请求头仍为空');
1725
+
1726
+ /* —— 场景五(task-29):Host 自动探测 credits 余额,打开后未触碰字段直接保存 ——
1727
+ POST 必须沿用 Host 的精确解析字段($.balance / 1 / USD),不得回填 data.quota/500000;
1728
+ 否则 Server 视为解析字段变化会清 balanceKind → 后续同 endpoint 查询永久 invalid-balance。 */
1729
+ open('probed-credits');
1730
+ const beforeCreditsSave = posts.length;
1731
+ buttonsByLabel(platformRow('probed-credits'), t('priceSave'))[0].props.onClick();
1732
+ await settle();
1733
+ rerender(state);
1734
+ const creditsPost = posts[posts.length - 1];
1735
+ assert.strictEqual(posts.length, beforeCreditsSave + 1, 'credits 平台自动保存发出一条 POST');
1736
+ assert.strictEqual(creditsPost.channelKey, 'probed-credits', 'POST 目标是 credits 平台');
1737
+ assert.strictEqual(creditsPost.endpoint, 'https://credits.example.com/api/balance', '地址保持 Host 已探测地址');
1738
+ assert.strictEqual(creditsPost.balancePath, '$.balance', '保留 Host 原始 balancePath($.balance),不回退 data.quota');
1739
+ assert.strictEqual(creditsPost.balanceDivisor, 1, '保留 Host 精确 balanceDivisor(1),不回退 500000');
1740
+ assert.strictEqual(creditsPost.currency, 'USD', '保留 Host 精确 currency(USD)');
1741
+ assert.strictEqual(creditsPost.balanceKind, undefined, '客户端不把 balanceKind 写给 Host(服务端按相同字段自然保留)');
1742
+ const creditsLocal = plain(savedPlatforms()['probed-credits']);
1743
+ assert.deepStrictEqual([creditsLocal.balancePath, creditsLocal.currency, creditsLocal.balanceDivisor], ['', '', null],
1744
+ '本地档案仍不写入 Host 解析字段(运行时默认不落本地)');
1745
+ assert.strictEqual(creditsLocal.endpoint, 'https://credits.example.com/api/balance', '本地档案记录已探测地址');
1746
+ open('probed-credits');
1747
+ assert.strictEqual(findLabelInput(platformRow('probed-credits'), t('priceBalanceField')).props.value, '$balance',
1748
+ '重开:仍显示 Host 原始余额字段,未变成 ¥data.quota / 500000');
1749
+ console.log(' credits 自动探测:自动保存 POST 保留 $.balance/1/USD,不回退 data.quota/500000');
1750
+ console.log(' 清空 Host 探测地址 → remove;自动默认值不残留;显式值保留');
1751
+ }
1752
+
1753
+ /* ====================================================================
1754
+ ③-6 打开平台前强制刷新 Host 快照(task-31:陈旧空快照不得覆盖自动探测结果)
1755
+ ==================================================================== */
1756
+ console.log('\n===== ③-6 已加载空快照后 Host 自动探测 credits:打开平台强制刷新 =====');
1757
+ {
1758
+ /* 初始 Host 快照为空:客户端先加载到空快照(模拟设置页挂载后只 GET 一次)。 */
1759
+ let hostList = [];
1760
+ const posts = [];
1761
+ const creditChannel = {
1762
+ channelKey: 'stale-credits',
1763
+ endpoint: 'https://credits.example.com/api/balance',
1764
+ tokenHeader: 'authorization',
1765
+ userIdHeader: 'New-Api-User',
1766
+ tokenPrefix: 'Bearer ',
1767
+ balancePath: '$.balance',
1768
+ currency: 'USD',
1769
+ feeMultiplier: 1,
1770
+ balanceDivisor: 1,
1771
+ balanceKind: 'credits',
1772
+ tokenConfigured: true,
1773
+ userIdConfigured: true
1774
+ };
1775
+ const inst = loadClient((url, init) => {
1776
+ if (String(url).indexOf('/api/relay-balance-config') === -1) {
1777
+ return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
1778
+ }
1779
+ if (init !== undefined && init !== null && init.method === 'POST') {
1780
+ posts.push(JSON.parse(init.body));
1781
+ }
1782
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: hostList }) });
1783
+ });
1784
+ const api = inst.api;
1785
+ const t = translator(api);
1786
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
1787
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: { 'stale-credits': plain(emptyPlatform) } });
1788
+ await api.ensureRelayState(); /* 客户端加载“空快照” */
1789
+ const props = { t: t, useProjection: () => undefined };
1790
+ const bucket = inst.hooks();
1791
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1792
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1793
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1794
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1795
+ const open = (name) => { findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0].props.onClick(); rerender(); };
1796
+ /* 服务端后台自动探测完成:Host 快照出现 credits channel,而客户端仍是旧的空快照 */
1797
+ hostList = [ JSON.parse(JSON.stringify(creditChannel)) ];
1798
+ /* 打开平台:应强制刷新 Host 快照并用最新数据初始化 draft(不是旧空快照) */
1799
+ open('stale-credits');
1800
+ await settle();
1801
+ rerender();
1802
+ assert.strictEqual(findLabelInput(platformRow('stale-credits'), t('priceEndpoint')).props.value,
1803
+ 'https://credits.example.com/api/balance', '打开平台强制刷新:draft 用最新 Host endpoint(不是空/旧地址)');
1804
+ assert.strictEqual(findLabelInput(platformRow('stale-credits'), t('priceBalanceField')).props.value,
1805
+ '$balance', '打开平台强制刷新:draft 用最新 Host 解析字段($balance)');
1806
+ /* 点击头部触发自动保存(与“点外部 → savePlatform”同一保存路径) */
1807
+ const beforeSave = posts.length;
1808
+ open('stale-credits');
1809
+ await settle();
1810
+ rerender();
1811
+ const saved = posts[posts.length - 1];
1812
+ assert.strictEqual(posts.length, beforeSave + 1, '自动保存发出一条 POST');
1813
+ assert.strictEqual(saved.endpoint, 'https://credits.example.com/api/balance', '保存保留 Host endpoint,不被空地址覆盖');
1814
+ assert.strictEqual(saved.balancePath, '$.balance', '保存保留 $.balance,不回退 data.quota');
1815
+ assert.strictEqual(saved.balanceDivisor, 1, '保存保留 divisor 1,不回退 500000');
1816
+ assert.strictEqual(saved.currency, 'USD', '保存保留 currency USD');
1817
+ assert.strictEqual(saved.balanceKind, undefined, '客户端不写 balanceKind(由服务端按相同字段保留)');
1818
+ const localPlatform = plain(JSON.parse(inst.store.get(api.STORAGE_KEY)).relayPlatforms['stale-credits']);
1819
+ assert.deepStrictEqual([localPlatform.balancePath, localPlatform.currency, localPlatform.balanceDivisor], ['', '', null],
1820
+ '本地档案仍不落 Host 运行时默认值');
1821
+ assert.strictEqual(localPlatform.endpoint, 'https://credits.example.com/api/balance', '本地档案记录已探测地址');
1822
+ console.log(' 空快照→后台探测 credits→打开强制刷新→自动保存:保留 endpoint/$.balance/1/USD');
1823
+ }
1824
+
1825
+ /* ====================================================================
1826
+ ③-7 刷新尚未返回时立即点外部保存的竞态(task-33)
1827
+ ==================================================================== */
1828
+ console.log('\n===== ③-7 刷新未返回即点外部保存:不用旧空快照覆盖自动探测结果 =====');
1829
+ {
1830
+ let hostList = [];
1831
+ const posts = [];
1832
+ const creditChannel = {
1833
+ channelKey: 'race-credits',
1834
+ endpoint: 'https://credits.example.com/api/balance',
1835
+ tokenHeader: 'authorization',
1836
+ userIdHeader: 'New-Api-User',
1837
+ tokenPrefix: 'Bearer ',
1838
+ balancePath: '$.balance',
1839
+ currency: 'USD',
1840
+ feeMultiplier: 1,
1841
+ balanceDivisor: 1,
1842
+ balanceKind: 'credits',
1843
+ tokenConfigured: true,
1844
+ userIdConfigured: true
1845
+ };
1846
+ const inst = loadClient((url, init) => {
1847
+ if (String(url).indexOf('/api/relay-balance-config') === -1) {
1848
+ return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
1849
+ }
1850
+ if (init !== undefined && init !== null && init.method === 'POST') {
1851
+ posts.push(JSON.parse(init.body));
1852
+ }
1853
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: hostList }) });
1854
+ });
1855
+ const api = inst.api;
1856
+ const t = translator(api);
1857
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
1858
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: { 'race-credits': plain(emptyPlatform) } });
1859
+ await api.ensureRelayState(); /* 客户端加载“空快照” */
1860
+ const props = { t: t, useProjection: () => undefined };
1861
+ const bucket = inst.hooks();
1862
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1863
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1864
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1865
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1866
+ const headOf = (name) => findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0];
1867
+ /* 服务端后台自动探测完成:Host 快照出现 credits channel,而客户端仍是旧空快照 */
1868
+ hostList = [ JSON.parse(JSON.stringify(creditChannel)) ];
1869
+ /* 打开平台:触发强制刷新,但**不等待 GET 返回** */
1870
+ headOf('race-credits').props.onClick();
1871
+ rerender();
1872
+ /* 刷新尚未返回就立即点头部保存(= 点外部 pointerdown 自动保存的同一 savePlatform 路径) */
1873
+ const before = posts.length;
1874
+ headOf('race-credits').props.onClick();
1875
+ await settle();
1876
+ rerender();
1877
+ const saved = posts[posts.length - 1];
1878
+ assert.strictEqual(posts.length, before + 1, '竞态下仍只发一条保存 POST');
1879
+ assert.strictEqual(saved.endpoint, 'https://credits.example.com/api/balance', '竞态保存不发送空 endpoint(不覆盖 Host 已探测地址)');
1880
+ assert.strictEqual(saved.balancePath, '$.balance', '竞态保存保留 $.balance,不回退 data.quota');
1881
+ assert.strictEqual(saved.balanceDivisor, 1, '竞态保存保留 divisor 1,不回退 500000');
1882
+ assert.strictEqual(saved.currency, 'USD', '竞态保存保留 currency USD');
1883
+ assert.strictEqual(saved.balanceKind, undefined, '竞态保存不写 balanceKind(服务端按相同字段保留 credits)');
1884
+ const local = plain(JSON.parse(inst.store.get(api.STORAGE_KEY)).relayPlatforms['race-credits']);
1885
+ assert.deepStrictEqual([local.balancePath, local.currency, local.balanceDivisor], ['', '', null], '本地仍不落 Host 默认');
1886
+ assert.strictEqual(local.endpoint, 'https://credits.example.com/api/balance', '本地记录已探测地址');
1887
+ console.log(' 刷新未回→立即保存:仍保留 endpoint/$.balance/1/USD(未用空快照覆盖)');
1888
+ }
1889
+
1890
+ /* ====================================================================
1891
+ ③-8 强制刷新 GET 失败:不发送 fallback,交给 Host existing 合并(task-35)
1892
+ ==================================================================== */
1893
+ console.log('\n===== ③-8 强制刷新 GET 失败:不发 fallback,Host existing 保留自动探测 =====');
1894
+ {
1895
+ let hostChannel = null; /* Host 服务端已有(自动探测)credits channel,客户端起初不知道 */
1896
+ const failGet = { on: false };
1897
+ const posts = [];
1898
+ const creditsChannel = {
1899
+ channelKey: 'failing-credits',
1900
+ endpoint: 'https://credits.example.com/api/balance',
1901
+ tokenHeader: 'authorization',
1902
+ userIdHeader: 'New-Api-User',
1903
+ tokenPrefix: 'Bearer ',
1904
+ balancePath: '$.balance',
1905
+ currency: 'USD',
1906
+ feeMultiplier: 1,
1907
+ balanceDivisor: 1,
1908
+ balanceKind: 'credits',
1909
+ tokenConfigured: true,
1910
+ userIdConfigured: true
1911
+ };
1912
+ /* 模拟 Host updateRelayConfig 的 existing 合并:payload 未提供的字段沿用现有配置。 */
1913
+ const hostMerge = (body) => {
1914
+ const existing = hostChannel === null ? {} : hostChannel;
1915
+ const pick = (key, fallback) => body[key] === undefined ? (existing[key] === undefined ? fallback : existing[key]) : body[key];
1916
+ const next = {
1917
+ channelKey: body.channelKey,
1918
+ endpoint: pick('endpoint', ''),
1919
+ tokenHeader: pick('tokenHeader', 'authorization'),
1920
+ userIdHeader: pick('userIdHeader', 'x-user-id'),
1921
+ tokenPrefix: pick('tokenPrefix', 'Bearer '),
1922
+ balancePath: pick('balancePath', '$.balance'),
1923
+ currency: pick('currency', 'CNY'),
1924
+ balanceDivisor: pick('balanceDivisor', 1),
1925
+ balanceKind: pick('balanceKind', undefined),
1926
+ feeMultiplier: 1,
1927
+ tokenConfigured: body.token === undefined ? (existing.tokenConfigured === true) : body.token !== '',
1928
+ userIdConfigured: body.userId === undefined ? (existing.userIdConfigured === true) : body.userId !== ''
1929
+ };
1930
+ hostChannel = next;
1931
+ return next;
1932
+ };
1933
+ const inst = loadClient((url, init) => {
1934
+ if (String(url).indexOf('/api/relay-balance-config') === -1) return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
1935
+ if (init !== undefined && init !== null && init.method === 'POST') {
1936
+ const body = JSON.parse(init.body);
1937
+ posts.push(body);
1938
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: [hostMerge(body)] }) });
1939
+ }
1940
+ if (failGet.on === true) return Promise.reject(new Error('relay-config GET failed'));
1941
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: hostChannel === null ? [] : [hostChannel] }) });
1942
+ });
1943
+ const api = inst.api;
1944
+ const t = translator(api);
1945
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
1946
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: { 'failing-credits': plain(emptyPlatform) } });
1947
+ await api.ensureRelayState(); /* 客户端读到“空快照”(Host 此刻返回空) */
1948
+ /* Host 后台自动探测出 credits;随后编辑时的强制 GET 失败 */
1949
+ hostChannel = JSON.parse(JSON.stringify(creditsChannel));
1950
+ failGet.on = true;
1951
+ const props = { t: t, useProjection: () => undefined };
1952
+ const bucket = inst.hooks();
1953
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
1954
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
1955
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
1956
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
1957
+ const headOf = (name) => findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0];
1958
+ headOf('failing-credits').props.onClick(); /* 打开:触发强制刷新(将失败) */
1959
+ await settle();
1960
+ rerender();
1961
+ /* 未编辑,直接保存(点头部 = savePlatform) */
1962
+ const before = posts.length;
1963
+ headOf('failing-credits').props.onClick();
1964
+ await settle();
1965
+ rerender();
1966
+ const post = posts[posts.length - 1];
1967
+ assert.strictEqual(posts.length, before + 1, '刷新失败时未编辑保存仍发一条 POST');
1968
+ assert.strictEqual('endpoint' in post, false, '刷新失败:POST 不发送 endpoint(不覆盖 Host 已探测地址)');
1969
+ assert.strictEqual('balancePath' in post, false, '刷新失败:POST 不发送 balancePath');
1970
+ assert.strictEqual('currency' in post, false, '刷新失败:POST 不发送 currency');
1971
+ assert.strictEqual('balanceDivisor' in post, false, '刷新失败:POST 不发送 balanceDivisor');
1972
+ assert.strictEqual('balanceKind' in post, false, '刷新失败:客户端也不写 balanceKind');
1973
+ assert.strictEqual(hostChannel.endpoint, 'https://credits.example.com/api/balance', 'Host existing merge 保留 endpoint');
1974
+ assert.strictEqual(hostChannel.balancePath, '$.balance', 'Host existing merge 保留 balancePath');
1975
+ assert.strictEqual(hostChannel.currency, 'USD', 'Host existing merge 保留 currency');
1976
+ assert.strictEqual(hostChannel.balanceDivisor, 1, 'Host existing merge 保留 divisor');
1977
+ assert.strictEqual(hostChannel.balanceKind, 'credits', 'Host existing merge 保留 balanceKind=credits(解析逻辑不变)');
1978
+ const local = plain(JSON.parse(inst.store.get(api.STORAGE_KEY)).relayPlatforms['failing-credits']);
1979
+ assert.deepStrictEqual([local.balancePath, local.currency, local.balanceDivisor], ['', '', null], '本地仍不落 runtime 默认值');
1980
+ console.log(' GET 失败→未编辑保存:不发 fallback,Host existing 保留 endpoint/$.balance/USD/1/credits');
1981
+ }
1982
+
1983
+ /* ====================================================================
1984
+ ③-9 stale-empty-channel / 本地显式 parser 对照(task-37)
1985
+ ==================================================================== */
1986
+ console.log('\n===== ③-9 快照已有空 endpoint channel:GET 失败保存不覆盖;本地显式保留 =====');
1987
+ {
1988
+ /* 模拟“客户端已加载一个 endpoint='' 的 channel” + “服务端后台已探测 credits” + “打开时 GET 失败”。 */
1989
+ const buildScenario = (opts) => {
1990
+ const st = { snapshot: opts.snapshot, server: opts.server, fail: false, posts: [] };
1991
+ const hostMerge = (body) => {
1992
+ const existing = st.server === null ? {} : st.server;
1993
+ const pick = (key, fallback) => body[key] === undefined ? (existing[key] === undefined ? fallback : existing[key]) : body[key];
1994
+ const parseProvided = body.balancePath !== undefined || body.balanceDivisor !== undefined;
1995
+ const next = {
1996
+ channelKey: body.channelKey,
1997
+ endpoint: pick('endpoint', ''),
1998
+ tokenHeader: pick('tokenHeader', 'authorization'),
1999
+ userIdHeader: pick('userIdHeader', 'x-user-id'),
2000
+ tokenPrefix: pick('tokenPrefix', 'Bearer '),
2001
+ balancePath: pick('balancePath', '$.balance'),
2002
+ currency: pick('currency', 'CNY'),
2003
+ balanceDivisor: pick('balanceDivisor', 1),
2004
+ balanceKind: parseProvided ? undefined : pick('balanceKind', undefined),
2005
+ feeMultiplier: 1,
2006
+ tokenConfigured: body.token === undefined ? existing.tokenConfigured === true : body.token !== '',
2007
+ userIdConfigured: body.userId === undefined ? existing.userIdConfigured === true : body.userId !== ''
2008
+ };
2009
+ st.server = next;
2010
+ return next;
2011
+ };
2012
+ const inst = loadClient((url, init) => {
2013
+ if (String(url).indexOf('/api/relay-balance-config') === -1) return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
2014
+ if (init !== undefined && init !== null && init.method === 'POST') {
2015
+ const body = JSON.parse(init.body);
2016
+ st.posts.push(body);
2017
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: [hostMerge(body)] }) });
2018
+ }
2019
+ if (st.fail === true) return Promise.reject(new Error('relay-config GET failed'));
2020
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: st.snapshot }) });
2021
+ });
2022
+ return { inst: inst, st: st };
2023
+ };
2024
+ const mountScenario = async (sc, platformName, localPlatform) => {
2025
+ const api = sc.inst.api;
2026
+ const t = translator(api);
2027
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: { [platformName]: plain(localPlatform) } });
2028
+ await api.ensureRelayState(); /* 客户端先加载快照(此时 snapshot 里已有一个 endpoint='' 的 channel) */
2029
+ sc.st.fail = true; /* 之后编辑时强制 GET 失败 */
2030
+ const props = { t: t, useProjection: () => undefined };
2031
+ const bucket = sc.inst.hooks();
2032
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
2033
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
2034
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
2035
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
2036
+ const headOf = (name) => findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0];
2037
+ headOf(platformName).props.onClick(); /* 打开:触发强制刷新(GET 失败) */
2038
+ await settle();
2039
+ rerender();
2040
+ const before = sc.st.posts.length;
2041
+ headOf(platformName).props.onClick(); /* 未编辑直接保存 */
2042
+ await settle();
2043
+ rerender();
2044
+ return { api: api, t: t, posts: sc.st.posts, before: before };
2045
+ };
2046
+ /* 场景 A:本地空,Host existing 应保留 credits endpoint / 解析字段 / balanceKind。 */
2047
+ {
2048
+ const emptyChannelSnap = {
2049
+ channelKey: 'stale-empty', endpoint: '', tokenHeader: 'authorization', userIdHeader: '',
2050
+ tokenPrefix: 'Bearer ', balancePath: '$.balance', currency: 'CNY', balanceDivisor: 1,
2051
+ tokenConfigured: true, userIdConfigured: false
2052
+ };
2053
+ const sc = buildScenario({
2054
+ snapshot: [ JSON.parse(JSON.stringify(emptyChannelSnap)) ],
2055
+ server: { channelKey: 'stale-empty', endpoint: 'https://credits.example.com/api/balance', tokenHeader: 'authorization', userIdHeader: 'New-Api-User', tokenPrefix: 'Bearer ', balancePath: '$.balance', currency: 'USD', balanceDivisor: 1, balanceKind: 'credits', feeMultiplier: 1, tokenConfigured: true, userIdConfigured: true }
2056
+ });
2057
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
2058
+ const run = await mountScenario(sc, 'stale-empty', emptyPlatform);
2059
+ const post = run.posts[run.posts.length - 1];
2060
+ assert.strictEqual(run.posts.length, run.before + 1, 'A:未编辑保存仍发一条 POST');
2061
+ assert.strictEqual('endpoint' in post, false, 'A:snapshot 已有空 channel(GET 失败)→ POST 不发 endpoint,交给 existing 合并');
2062
+ assert.strictEqual('balancePath' in post, false, 'A:POST 不发 balancePath');
2063
+ assert.strictEqual('currency' in post, false, 'A:POST 不发 currency');
2064
+ assert.strictEqual('balanceDivisor' in post, false, 'A:POST 不发 balanceDivisor');
2065
+ const serverA = sc.st.server;
2066
+ assert.strictEqual(serverA.endpoint, 'https://credits.example.com/api/balance', 'A:existing merge 保留 endpoint');
2067
+ assert.strictEqual(serverA.balancePath, '$.balance', 'A:保留 balancePath');
2068
+ assert.strictEqual(serverA.currency, 'USD', 'A:保留 currency');
2069
+ assert.strictEqual(serverA.balanceDivisor, 1, 'A:保留 divisor');
2070
+ assert.strictEqual(serverA.balanceKind, 'credits', 'A:保留 balanceKind=credits');
2071
+ const localA = plain(JSON.parse(sc.inst.store.get(run.api.STORAGE_KEY)).relayPlatforms['stale-empty']);
2072
+ assert.deepStrictEqual([localA.balancePath, localA.currency, localA.balanceDivisor], ['', '', null], 'A:本地仍不落 runtime 默认值');
2073
+ console.log(' A 快照已有空 channel→GET失败保存:不发 fallback,existing 保留 credits endpoint/kind');
2074
+ }
2075
+ /* 场景 B:本地已有显式 header / parser,必须照常发给 Host(不被 omit 丢掉)。 */
2076
+ {
2077
+ const emptyChannelSnap = {
2078
+ channelKey: 'explicit-local', endpoint: '', tokenHeader: 'authorization', userIdHeader: '',
2079
+ tokenPrefix: 'Bearer ', balancePath: '', currency: '', balanceDivisor: null,
2080
+ tokenConfigured: true, userIdConfigured: false
2081
+ };
2082
+ const sc = buildScenario({
2083
+ snapshot: [ JSON.parse(JSON.stringify(emptyChannelSnap)) ],
2084
+ server: { channelKey: 'explicit-local', endpoint: 'https://credits.example.com/api/balance', tokenHeader: 'authorization', userIdHeader: 'New-Api-User', tokenPrefix: 'Bearer ', balancePath: '$.balance', currency: 'USD', balanceDivisor: 1, balanceKind: 'credits', feeMultiplier: 1, tokenConfigured: true, userIdConfigured: true }
2085
+ });
2086
+ const explicitLocal = { endpoint: '', tokenHeader: 'authorization', userIdHeader: 'X-Custom-User', balancePath: 'data.custom', currency: 'CNY', balanceDivisor: 2, models: [] };
2087
+ const run = await mountScenario(sc, 'explicit-local', explicitLocal);
2088
+ const post = run.posts[run.posts.length - 1];
2089
+ assert.strictEqual('endpoint' in post, false, 'B:仍不发送 endpoint(本地地址空、未更改)');
2090
+ assert.strictEqual(post.userIdHeader, 'X-Custom-User', 'B:本地显式请求头必须照常发出(不丢配置)');
2091
+ assert.strictEqual(post.balancePath, 'data.custom', 'B:本地显式 balancePath 必须照常发出');
2092
+ assert.strictEqual(post.currency, 'CNY', 'B:本地显式 currency 必须照常发出');
2093
+ assert.strictEqual(post.balanceDivisor, 2, 'B:本地显式 divisor 必须照常发出');
2094
+ const serverB = sc.st.server;
2095
+ assert.strictEqual(serverB.endpoint, 'https://credits.example.com/api/balance', 'B:endpoint 仍由 existing 保留');
2096
+ assert.strictEqual(serverB.balancePath, 'data.custom', 'B:显式 parser 已写入 Host');
2097
+ assert.strictEqual(serverB.currency, 'CNY', 'B:显式 currency 已写入 Host');
2098
+ assert.strictEqual(serverB.balanceDivisor, 2, 'B:显式 divisor 已写入 Host');
2099
+ const localB = plain(JSON.parse(sc.inst.store.get(run.api.STORAGE_KEY)).relayPlatforms['explicit-local']);
2100
+ assert.deepStrictEqual([localB.userIdHeader, localB.balancePath, localB.currency, localB.balanceDivisor], ['X-Custom-User', 'data.custom', 'CNY', 2], 'B:本地显式配置保留');
2101
+ console.log(' B 本地显式 header/parser→GET失败保存:照常发送,不丢配置');
2102
+ }
2103
+ }
2104
+
2105
+ /* ====================================================================
2106
+ ③-10 首次 GET 也未成功(无快照):GET 一直失败时保存仍交给 Host existing(task-39)
2107
+ ==================================================================== */
2108
+ console.log('\n===== ③-10 首次 GET 从未成功、无快照:GET 一直失败保存仍保留 Host 自动探测 =====');
2109
+ {
2110
+ /* Host 服务端已有 credits channel;客户端连首次 ensure GET 都失败,从未拿到任何快照。 */
2111
+ let serverChannel = {
2112
+ channelKey: 'never-loaded',
2113
+ endpoint: 'https://credits.example.com/api/balance',
2114
+ tokenHeader: 'authorization', userIdHeader: 'New-Api-User', tokenPrefix: 'Bearer ',
2115
+ balancePath: '$.balance', currency: 'USD', balanceDivisor: 1, balanceKind: 'credits',
2116
+ feeMultiplier: 1, tokenConfigured: true, userIdConfigured: true
2117
+ };
2118
+ const posts = [];
2119
+ const hostMerge = (body) => {
2120
+ const existing = serverChannel;
2121
+ const pick = (key, fallback) => body[key] === undefined ? (existing[key] === undefined ? fallback : existing[key]) : body[key];
2122
+ const parseProvided = body.balancePath !== undefined || body.balanceDivisor !== undefined;
2123
+ const next = {
2124
+ channelKey: body.channelKey,
2125
+ endpoint: pick('endpoint', ''),
2126
+ tokenHeader: pick('tokenHeader', 'authorization'),
2127
+ userIdHeader: pick('userIdHeader', 'x-user-id'),
2128
+ tokenPrefix: pick('tokenPrefix', 'Bearer '),
2129
+ balancePath: pick('balancePath', '$.balance'),
2130
+ currency: pick('currency', 'CNY'),
2131
+ balanceDivisor: pick('balanceDivisor', 1),
2132
+ balanceKind: parseProvided ? undefined : pick('balanceKind', undefined),
2133
+ feeMultiplier: 1,
2134
+ tokenConfigured: body.token === undefined ? true : body.token !== '',
2135
+ userIdConfigured: body.userId === undefined ? true : body.userId !== ''
2136
+ };
2137
+ serverChannel = next;
2138
+ return next;
2139
+ };
2140
+ const inst = loadClient((url, init) => {
2141
+ if (String(url).indexOf('/api/relay-balance-config') === -1) return Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) });
2142
+ if (init !== undefined && init !== null && init.method === 'POST') {
2143
+ const body = JSON.parse(init.body);
2144
+ posts.push(body);
2145
+ return Promise.resolve({ json: () => Promise.resolve({ ok: true, channels: [hostMerge(body)] }) });
2146
+ }
2147
+ return Promise.reject(new Error('relay-config GET always fails'));
2148
+ });
2149
+ const api = inst.api;
2150
+ const t = translator(api);
2151
+ const emptyPlatform = { endpoint: '', tokenHeader: 'authorization', userIdHeader: '', balancePath: '', currency: '', balanceDivisor: null, models: [] };
2152
+ api.setConfig({ models: CNY_BASE, modelOrder: ['deepseek-flash'], priceConfigured: true, relayPlatforms: { 'never-loaded': plain(emptyPlatform) } });
2153
+ await api.ensureRelayState(); /* 首次 GET reject:从未拿到快照 */
2154
+ const props = { t: t, useProjection: () => undefined };
2155
+ const bucket = inst.hooks();
2156
+ const state = { bucket: bucket, tree: withHooks(bucket, () => api.SettingsSection(props)) };
2157
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
2158
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
2159
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
2160
+ const headOf = (name) => findAll(platformRow(name), (node) => hasClass(node, 'dsb-platform-head'))[0];
2161
+ headOf('never-loaded').props.onClick(); /* 打开:强制 refresh 也 reject */
2162
+ await settle();
2163
+ rerender();
2164
+ const before = posts.length;
2165
+ headOf('never-loaded').props.onClick(); /* 未编辑直接保存 */
2166
+ await settle();
2167
+ rerender();
2168
+ const post = posts[posts.length - 1];
2169
+ assert.strictEqual(posts.length, before + 1, '首次 GET 也失败时未编辑保存仍发一条 POST');
2170
+ assert.strictEqual('endpoint' in post, false, '无快照+GET失败:不发 endpoint,交给 existing 合并');
2171
+ assert.strictEqual('balancePath' in post, false, '不发 balancePath');
2172
+ assert.strictEqual('currency' in post, false, '不发 currency');
2173
+ assert.strictEqual('balanceDivisor' in post, false, '不发 balanceDivisor');
2174
+ assert.strictEqual(serverChannel.endpoint, 'https://credits.example.com/api/balance', 'Host existing merge 保留 endpoint');
2175
+ assert.strictEqual(serverChannel.balancePath, '$.balance', '保留 balancePath');
2176
+ assert.strictEqual(serverChannel.currency, 'USD', '保留 currency');
2177
+ assert.strictEqual(serverChannel.balanceDivisor, 1, '保留 divisor');
2178
+ assert.strictEqual(serverChannel.balanceKind, 'credits', '保留 balanceKind=credits');
2179
+ const local = plain(JSON.parse(inst.store.get(api.STORAGE_KEY)).relayPlatforms['never-loaded']);
2180
+ assert.deepStrictEqual([local.balancePath, local.currency, local.balanceDivisor], ['', '', null], '本地仍不落 runtime 默认值');
2181
+ console.log(' 首次 GET 也失败+无快照:未编辑保存不发 fallback,Host existing 保留 credits');
2182
+ }
2183
+
1225
2184
  /* ====================================================================
1226
2185
  ④ 开发模式 0 次真实 fetch(中转站 GET 也要遵守)
1227
2186
  ==================================================================== */
@@ -1385,6 +2344,98 @@ console.log('\n===== ⑦ 余额请求追加 &relay=平台名 =====');
1385
2344
  console.log(' 归属平台 → &relay=' + PLATFORM + ';无归属 → 不带 relay');
1386
2345
  }
1387
2346
 
2347
+ /* ====================================================================
2348
+ ⑧ Host:空白 endpoint 保存为空(不预填默认地址),token/userId 仍保存
2349
+ ==================================================================== */
2350
+ console.log('\n===== ⑧ Host 空白 endpoint 保持为空 =====');
2351
+ {
2352
+ const HOST_TMP = path.join(__dirname, '.tmp-host-relay-settings');
2353
+ const source = hostLib.prepare(HOST_TMP, ['updateRelayConfig', 'readRelayConfig']);
2354
+ try {
2355
+ const host = await hostLib.loadHost(source, 'relay-default-endpoint');
2356
+ const secrets = new Map();
2357
+ const credentials = {
2358
+ resolve: async (ref) => (secrets.has(ref) ? { value: secrets.get(ref), source: 'test' } : null),
2359
+ set: async (ref, value) => { secrets.set(ref, value); },
2360
+ unset: async (ref) => { secrets.delete(ref); }
2361
+ };
2362
+ const settings = {
2363
+ describe: () => [{
2364
+ ns: 'include:llm-pi-ai',
2365
+ value: { providers: { orbi: { baseURL: 'https://orbi.example/v1' } } }
2366
+ }]
2367
+ };
2368
+ const ctx = {
2369
+ credentials: credentials,
2370
+ get: (name) => name === 'settings' ? settings : (name === 'credentials' ? credentials : undefined)
2371
+ };
2372
+ const saved = await host.updateRelayConfig(ctx, {
2373
+ channelKey: 'orbi', endpoint: '', token: 'orbi-token-sentinel', userId: 'orbi-user-sentinel',
2374
+ userIdHeader: 'New-Api-User', balancePath: 'data.quota', currency: 'CNY', balanceDivisor: 500000, feeMultiplier: 1
2375
+ });
2376
+ assert.strictEqual(saved.status, 200, '空白 endpoint + token/userId 保存成功');
2377
+ const channel = host.readRelayConfig().channels.find((one) => one.channelKey === 'orbi');
2378
+ assert.ok(channel !== undefined, 'orbi 平台档案已写入');
2379
+ assert.strictEqual(channel.endpoint, '', '地址为空就保持空(不预填 /api/user/self)');
2380
+ assert.strictEqual(secrets.size, 1, 'token/userId 已写入凭据服务');
2381
+ const envelope = JSON.parse(Array.from(secrets.values())[0]);
2382
+ assert.strictEqual(envelope.token, 'orbi-token-sentinel', 'token 已保存');
2383
+ assert.strictEqual(envelope.userId, 'orbi-user-sentinel', 'userId 已保存');
2384
+ /* 没有 provider baseURL 时不能因为地址空就拒绝保存/清空 */
2385
+ const noBase = await host.updateRelayConfig(ctx, { channelKey: 'no-base', endpoint: '', token: 'no-base-token', userId: 'no-base-user' });
2386
+ assert.strictEqual(noBase.status, 200, '没有 provider baseURL 也能保存');
2387
+ const noBaseChannel = host.readRelayConfig().channels.find((one) => one.channelKey === 'no-base');
2388
+ assert.ok(noBaseChannel !== undefined, '无 baseURL 的平台档案保留');
2389
+ assert.strictEqual(noBaseChannel.endpoint, '', '没有 provider baseURL 时 endpoint 也保持空');
2390
+ console.log(' 空白 endpoint:保存为空;token/userId 仍保存');
2391
+ } finally {
2392
+ hostLib.cleanup(HOST_TMP);
2393
+ }
2394
+ }
2395
+
2396
+ /* ====================================================================
2397
+ ③-5 打开已有平台编辑区不自动滚动(task-14);加模型行仍自动露出
2398
+ ==================================================================== */
2399
+ console.log('\n===== ③-5 打开已有平台:scrollTop 不变;加模型行仍露出 =====');
2400
+ {
2401
+ const scroller = {
2402
+ __overflowY: 'auto', scrollHeight: 2000, clientHeight: 500, scrollTop: 300, parentElement: null,
2403
+ getBoundingClientRect: () => ({ left: 0, top: 0, right: 900, bottom: 100, width: 900, height: 500 })
2404
+ };
2405
+ const platformNode = {
2406
+ parentElement: scroller,
2407
+ getBoundingClientRect: () => ({ left: 0, top: 200, right: 900, bottom: 600, width: 900, height: 400 })
2408
+ };
2409
+ const inst = loadClient(undefined, undefined, { dom: { platformNode: platformNode } });
2410
+ const api = inst.api;
2411
+ const t = translator(api);
2412
+ const props = { t: t, useProjection: () => undefined };
2413
+ const state = { bucket: inst.hooks(), tree: null };
2414
+ const rerender = () => { state.tree = withHooks(state.bucket, () => api.SettingsSection(props)); };
2415
+ const section = () => findAll(state.tree, (node) => hasClass(node, 'dsb-section') && node.props.key === '__platforms')[0];
2416
+ const platformRow = (name) => findAll(section(), (node) => hasClass(node, 'dsb-model') && node.props.key === name)[0];
2417
+ const platformHead = (name) => findAll(platformRow(name), (one) => hasClass(one, 'dsb-platform-head'))[0];
2418
+ rerender();
2419
+ /* 新建平台并落库(addPlatform 即写 config);随后点头部 = 打开已有平台编辑区 */
2420
+ const nameInput = findAll(section(), (node) => node.type === 'input' && node.props.placeholder === t('platformNewPh'))[0];
2421
+ nameInput.props.onChange({ target: { value: 'existing-relay' } });
2422
+ rerender();
2423
+ buttonsByLabel(section(), t('platformAdd'))[0].props.onClick();
2424
+ rerender();
2425
+ assert.ok(platformRow('existing-relay') !== undefined, '前置:平台行已存在(已落库)');
2426
+ /* 用户原本滚到某个位置:打开编辑区不得把它挪走 */
2427
+ scroller.scrollTop = 300;
2428
+ platformHead('existing-relay').props.onClick();
2429
+ rerender();
2430
+ assert.strictEqual(findAll(platformRow('existing-relay'), (node) => hasClass(node, 'dsb-platform-pop')).length, 1, '前置:编辑区已打开');
2431
+ assert.strictEqual(scroller.scrollTop, 300, '打开已有平台编辑区不得滚动(scrollTop 必须保持原值)');
2432
+ /* 保留原行为:点「添加模型」新增行后仍把编辑区底边带进视野 */
2433
+ buttonsByLabel(platformRow('existing-relay'), t('platformAddModel'))[0].props.onClick();
2434
+ rerender();
2435
+ assert.ok(scroller.scrollTop > 300, '新增模型行仍应把编辑区底边带进视野(保留原露出行为)');
2436
+ console.log(' 打开已有平台 scrollTop 保持不变(300);加模型行后自动露出(' + scroller.scrollTop + ')');
2437
+ }
2438
+
1388
2439
  console.log('\n全部通过');
1389
2440
  }
1390
2441