dsh-nvidia-models-panel 1.3.12 → 1.3.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -39,6 +39,8 @@ git clone https://github.com/windxxf/dsh-nvidia-models-panel.git
39
39
  3. 点击「检测」获取可用模型列表 → 「验证」逐个试调用
40
40
  4. 点击「一键配置」,试调用通过的模型即写入 nvidia 供应商目录,可在对话模型选择器中直接选用
41
41
 
42
+ > **未配置 Key 时**:面板顶部会显示黄色提示条,API Key 卡片给出提醒,「检测 / 逐个试调用 / 一键配置」按钮会置灰并给出悬浮说明;此时在对话框里选「NVIDIA 模型组(自动)」也会立即收到「NVIDIA API Key 未配置或已失效,请在 NVIDIA 模型面板顶部保存 Key 后重试」的明确报错,而不是对组内每个模型逐个超时重试。保存 Key 后一切自动恢复。
43
+
42
44
  ## NVIDIA 模型组(自动切换 / 自愈)
43
45
 
44
46
  除了单个模型,插件还注册了一个虚拟供应商 **「NVIDIA 模型组」**(provider id `nvidia-group`)。
@@ -63,6 +65,8 @@ git clone https://github.com/windxxf/dsh-nvidia-models-panel.git
63
65
 
64
66
  **调用日志**:第三个标签页「调用日志」把模型组当天每次尝试都记下来——顶部是今日总调用 / 成功 / 失败 / **自动切换次数** / 输入输出 token 汇总,中间是按模型的用量表(调用数、成功、失败、平均首包、token),底部是最近调用明细(时间、成员、✓/✗、首包、耗时、token、错误,以及该次是否为「← 切换自 X」)。这样即使对话界面不显示切换(故障转移发生在同一次请求内部、模型 id 未变),也能在面板里直观看到切换是否发生、各模型用了多少。日志按天分桶(本地日期,最多保留 7 天、每天最近 200 条),可「清空当日统计」。
65
67
 
68
+ **日志持久化与自动清理**:调用日志不再只存在内存里,会写入 DSH 配置目录下的 `nvidia-usage.json`(`DSH_PROFILE_DIR/nvidia-usage.json`,默认 `~/.dsh/profiles/<profile>/nvidia-usage.json`),采用「全量快照 + 原子写(tmp + rename)」,插件加载时自动读回,因此**重启 DSH、重载插件都不会再丢失当天日志**。每次写入/读回前都会自动清理:只保留最近 7 天的分桶、每天只留最近 200 条明细;损坏或缺失的文件会被安全忽略并从头开始。文件放在配置目录而非插件目录,因此市场重装/升级插件(会替换 `node_modules` 实体目录)也不会影响历史日志。测试环境下(`node --test`)自动禁用文件写入,不会污染真实数据。
69
+
66
70
  **使用说明**:面板标题栏右侧有 `?` 按钮,点开是居中浮层说明:三步上手(配置 Key → 检测/验证/一键配置 → 对话框选「NVIDIA 模型组(自动)」)、机制要点(故障转移 / 熔断冷却 / 能力路由 / 自发现 / token 计数)以及常见问题;未配置 Key 时浮层顶部会提示先配置。浮层限定在面板内(点击遮罩或 ✕ 关闭),不占常驻空间。
67
71
 
68
72
  > 说明:模型组是一个**独立虚拟供应商**(`nvidia-group`),它内部通过 `provider: 'nvidia'` 调用真实模型,因此需要先保存好 NVIDIA API Key。「NVIDIA 模型组」是否出现在模型选择器中,取决于宿主是否暴露了 `llm` 服务(DeepSeek Harness ≥ 0.2.1 默认具备)。
@@ -86,3 +90,15 @@ git clone https://github.com/windxxf/dsh-nvidia-models-panel.git
86
90
  - 随时可点胶囊按钮手动重新检查(检查中显示「检查中…」)。
87
91
  - 检测在面板挂载时执行一次(8 秒超时,失败重试一次);不再静默跳过,成功/失败/最新都有明确反馈。
88
92
  - 本机是 `link:` 安装时市场不会提示更新,所以这个面板内的检测是主要的版本提醒方式。
93
+
94
+ ## 输入框模型组徽标
95
+
96
+ 在对话主输入框上方(与「待办」「队列」同一个 dock 栏)会显示一个轻量徽标,让你不用打开面板就能看到模型组当前的实际状态:
97
+
98
+ - **平时(正常回答中)**:绿色胶囊 `⚡ <当前真正出正文的模型> · 切换 N 次 · 熔断 M`,显示的是**实际产出正文的那个成员**(不是你选的「自动」),加累计切换次数与当前熔断成员数。
99
+ - **刚发生自动切换**:橙色高亮 `⚡ <当前模型> ← 从 <来源模型> 切换 · 切换 N 次`,6 秒后自动回落到常态绿色。
100
+ - **未使用模型组 / 已切换到别的模型**:徽标完全不显示,平时不打扰。徽标会读取当前会话最新的模型路由,一旦你在对话框把模型从「NVIDIA 模型组」切到其它模型(如 DeepSeek),徽标会自动隐藏;切回模型组后再次出现。
101
+
102
+ 点徽标会跳到面板的「调用日志」标签页查看明细(若面板未打开则只记录意图,不会强行弹出侧栏)。徽标数据来自进程级共享状态(重启归零),每 3 秒刷新一次。
103
+
104
+ > 徽标右边缘会在运行时按输入框的实际右边缘自动对齐(测量 `[data-composer-input]` 所在的输入框卡片),适配宿主不同的宽度/缩放设置;窗口尺寸变化后会持续校准。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-nvidia-models-panel",
3
- "version": "1.3.12",
3
+ "version": "1.3.21",
4
4
  "type": "module",
5
5
  "description": "Nvidia 模型面板 — 检测 NVIDIA NIM 可用模型、逐个真实试调用验证、面板内保存 API Key,一键配置进 DeepSeek Harness 设置",
6
6
  "description.en": "Detects available NVIDIA NIM models, verifies each with a real streaming call, saves the API key in-panel, and one-click configures DeepSeek Harness settings.",
package/src/client.js CHANGED
@@ -77,6 +77,146 @@ window.__ModuleLoader__.load({
77
77
  }, s.t);
78
78
  }
79
79
 
80
+ /**
81
+ * 输入框 dock 徽标:显示模型组最近真正出正文的模型 + 切换/熔断计数。
82
+ * 独立 React 树,自己轮询 /api/nvidia-models 的 dockStatus(3 秒一次)。
83
+ * 未使用模型组时(active=false)完全不渲染,平时不打扰。
84
+ */
85
+ function DockBadge(props) {
86
+ const [status, setStatus] = useState(null);
87
+ const btnRef = useRef(null);
88
+
89
+ // 运行时实测对齐:dock 槽位容器的真实宽度/缩进由宿主 CSS 决定,静态猜 CSS 变量不可靠。
90
+ // 直接测量输入框 card 的实际右边缘,动态设置 marginRight 让徽标右边缘与它重合。
91
+ useEffect(function () {
92
+ if (!status || !status.active) return;
93
+ var cancelled = false;
94
+ function findCard(input) {
95
+ var el = input;
96
+ while (el && el !== document.body) {
97
+ var r = el.getBoundingClientRect();
98
+ var cs = window.getComputedStyle(el);
99
+ if (r.width > 400 && r.width <= window.innerWidth - 16 &&
100
+ parseFloat(cs.borderTopLeftRadius) >= 10) return el;
101
+ el = el.parentElement;
102
+ }
103
+ return null;
104
+ }
105
+ function align() {
106
+ if (cancelled) return;
107
+ var btn = btnRef.current;
108
+ var input = document.querySelector('[data-composer-input]');
109
+ if (!btn || !input) return;
110
+ var card = findCard(input);
111
+ if (!card) return;
112
+ // btn.right = 容器右缘 - marginRight。要让 btn.right 追上 card.right(增量 = card.right - btn.right),
113
+ // 需把 marginRight 减去同样的增量(marginRight 越大按钮越靠左)。
114
+ var delta = card.getBoundingClientRect().right - btn.getBoundingClientRect().right;
115
+ if (Math.abs(delta) >= 1) {
116
+ var cur = parseFloat(window.getComputedStyle(btn).marginRight) || 0;
117
+ btn.style.marginRight = (cur - delta) + 'px';
118
+ }
119
+ }
120
+ var n = 0;
121
+ var raf;
122
+ function converge() { align(); if (++n < 10) raf = requestAnimationFrame(converge); }
123
+ converge();
124
+ var timer = setInterval(align, 2000);
125
+ return function () { cancelled = true; cancelAnimationFrame(raf); clearInterval(timer); };
126
+ }, [status && status.active]);
127
+
128
+ const sessionId = props && props.sessionId;
129
+ const refresh = useCallback(async function () {
130
+ try {
131
+ const response = await fetch('/api/nvidia-models', {
132
+ method: 'POST',
133
+ headers: { 'content-type': 'application/json' },
134
+ body: JSON.stringify({ action: 'dockStatus', sessionId: sessionId || undefined }),
135
+ });
136
+ if (!response.ok) return;
137
+ const data = await response.json();
138
+ if (data && data.ok) setStatus(data);
139
+ } catch {
140
+ // best-effort
141
+ }
142
+ }, [sessionId]);
143
+
144
+ useEffect(function () {
145
+ refresh();
146
+ const id = setInterval(refresh, 3000);
147
+ return function () { clearInterval(id); };
148
+ }, [refresh]);
149
+
150
+ if (!status || !status.active) return null;
151
+
152
+ const name = status.memberName || status.memberId || '模型组';
153
+ const justSwitched = Boolean(status.switchFrom);
154
+ const label = justSwitched
155
+ ? ('⚡ ' + name + ' ← 从 ' + status.switchFrom + ' 切换 · 切换 ' + status.switchCount + ' 次')
156
+ : ('⚡ ' + name + ' · 切换 ' + status.switchCount + ' 次 · 熔断 ' + status.cooldownCount);
157
+
158
+ const openUsage = function () {
159
+ try {
160
+ window.dispatchEvent(new CustomEvent('nvidia-models-open-usage'));
161
+ } catch { /* 忽略:面板可能未挂载 */ }
162
+ };
163
+
164
+ // dock 容器(._7yHdaG_dock)相对输入框两边各缩进了 2×--dsh-composer-dock-inset:
165
+ // max-width = card-max - 2×inset,padding = 0 inset,margin 0 auto
166
+ // 所以 dock 内容区右边缘比输入框右边缘靠左 2×inset(默认 16px)。
167
+ // 用 flex-end 靠右后,再给徽标一个负 margin-right = -2×inset 抵消这段缩进,
168
+ // 右边缘就与输入框右边缘像素级对齐。不用 absolute(外层空 div 高度会塌缩成 0)。
169
+ return h('div', {
170
+ style: {
171
+ display: 'flex',
172
+ justifyContent: 'flex-end',
173
+ width: '100%',
174
+ boxSizing: 'border-box',
175
+ },
176
+ }, h('button', {
177
+ ref: btnRef,
178
+ type: 'button',
179
+ onClick: openUsage,
180
+ title: '查看 NVIDIA 模型组调用日志',
181
+ style: {
182
+ display: 'inline-flex',
183
+ alignItems: 'center',
184
+ gap: '4px',
185
+ fontSize: '11px',
186
+ lineHeight: '1.2',
187
+ color: justSwitched ? '#e65100' : '#8fce00',
188
+ border: '1px solid ' + (justSwitched ? 'rgba(230,81,0,0.55)' : 'rgba(143,206,0,0.5)'),
189
+ background: justSwitched ? 'rgba(230,81,0,0.10)' : 'rgba(143,206,0,0.08)',
190
+ borderRadius: '999px',
191
+ padding: '2px 10px',
192
+ cursor: 'pointer',
193
+ whiteSpace: 'nowrap',
194
+ maxWidth: '420px',
195
+ overflow: 'hidden',
196
+ textOverflow: 'ellipsis',
197
+ height: '32px',
198
+ boxSizing: 'border-box',
199
+ flexShrink: 0,
200
+ marginRight: 'calc(-2 * var(--dsh-composer-dock-inset, 8px))',
201
+ },
202
+ }, label));
203
+ }
204
+
205
+ /** 黄色警示条:未配置 Key 时在关键位置提示用户先去保存 Key。 */
206
+ function noKeyWarning(message) {
207
+ return h('div', {
208
+ style: {
209
+ padding: '8px 10px',
210
+ background: 'rgba(230,150,0,0.12)',
211
+ border: '1px solid rgba(230,150,0,0.55)',
212
+ borderRadius: '6px',
213
+ fontSize: '12px',
214
+ lineHeight: 1.5,
215
+ color: '#b8860b',
216
+ },
217
+ }, message);
218
+ }
219
+
80
220
  function NvidiaModelsPanel(props) {
81
221
  const [models, setModels] = useState([]);
82
222
  const [detecting, setDetecting] = useState(false);
@@ -479,6 +619,17 @@ window.__ModuleLoader__.load({
479
619
  // Check once on mount.
480
620
  useEffect(function () { refreshUpdateCheck(); }, [refreshUpdateCheck]);
481
621
 
622
+ // 输入框 dock 徽标点击后,切到「调用日志」标签页。
623
+ useEffect(function () {
624
+ function onOpenUsage() { setTab('usage'); }
625
+ try {
626
+ window.addEventListener('nvidia-models-open-usage', onOpenUsage);
627
+ return function () { window.removeEventListener('nvidia-models-open-usage', onOpenUsage); };
628
+ } catch {
629
+ return undefined;
630
+ }
631
+ }, []);
632
+
482
633
  // Refresh when the user switches to the usage tab.
483
634
  useEffect(function () {
484
635
  if (tab === 'usage') refreshUsage();
@@ -696,6 +847,10 @@ window.__ModuleLoader__.load({
696
847
  )
697
848
  );
698
849
 
850
+ // 未配置 Key:主操作按钮禁用、关键位置给出就地提示(凭据服务不可用时不做拦截)。
851
+ const noKey = Boolean(keyStatus && !keyStatus.configured && !keyStatus.unavailable);
852
+ const keyHint = '尚未配置 NVIDIA API Key —— 请先在上方「NVIDIA API Key」卡片粘贴保存后再继续。';
853
+
699
854
  return h('div', {
700
855
  className: 'nvidia-models-panel',
701
856
  style: {
@@ -884,8 +1039,11 @@ window.__ModuleLoader__.load({
884
1039
  ),
885
1040
  h('p', { style: { margin: 0, fontSize: '11px', opacity: 0.65, lineHeight: 1.5 } },
886
1041
  'Key 保存在 Harness 凭据存储(与正式 nvidia 模型路由共用 NVIDIA_API_KEY 引用),不会写入配置文件或日志;保存后下一次请求立即生效。'),
1042
+ noKey ? h('p', { style: { margin: 0, fontSize: '12px', lineHeight: 1.5, color: '#b8860b' } },
1043
+ '⚠ 未配置 Key:检测、试调用与「模型组」都不可用,请先在上方保存 Key。') : null,
887
1044
  keyMsg ? h('p', { style: { margin: 0, fontSize: '12px', lineHeight: 1.5 } }, keyMsg) : null,
888
1045
  ),
1046
+ noKey ? noKeyWarning(keyHint) : null,
889
1047
  tabBar,
890
1048
  tab === 'models' ? h('div', {
891
1049
  key: 'modelsPane',
@@ -898,7 +1056,8 @@ window.__ModuleLoader__.load({
898
1056
  },
899
1057
  h('button', {
900
1058
  onClick: detectModels,
901
- disabled: detecting || verifying,
1059
+ disabled: detecting || verifying || noKey,
1060
+ title: noKey ? keyHint : undefined,
902
1061
  style: {
903
1062
  padding: '7px 14px',
904
1063
  fontSize: '13px',
@@ -907,13 +1066,14 @@ window.__ModuleLoader__.load({
907
1066
  color: '#ffffff',
908
1067
  border: 'none',
909
1068
  borderRadius: '6px',
910
- cursor: (detecting || verifying) ? 'wait' : 'pointer',
911
- opacity: (detecting || verifying) ? 0.6 : 1,
1069
+ cursor: (detecting || verifying || noKey) ? 'not-allowed' : 'pointer',
1070
+ opacity: (detecting || verifying || noKey) ? 0.6 : 1,
912
1071
  },
913
1072
  }, detecting ? '检测中…' : '检测可用模型'),
914
1073
  h('button', {
915
1074
  onClick: verifyAll,
916
- disabled: detecting || verifying || models.length === 0,
1075
+ disabled: detecting || verifying || models.length === 0 || noKey,
1076
+ title: noKey ? keyHint : undefined,
917
1077
  style: {
918
1078
  padding: '7px 14px',
919
1079
  fontSize: '13px',
@@ -922,7 +1082,8 @@ window.__ModuleLoader__.load({
922
1082
  color: '#ffffff',
923
1083
  border: 'none',
924
1084
  borderRadius: '6px',
925
- cursor: (detecting || verifying || models.length === 0) ? 'wait' : 'pointer',
1085
+ cursor: (detecting || verifying || models.length === 0 || noKey) ? 'not-allowed' : 'pointer',
1086
+ opacity: noKey ? 0.6 : 1,
926
1087
  },
927
1088
  }, verifying ? '试调用中…' : '逐个试调用'),
928
1089
  verifying ? h('button', {
@@ -940,7 +1101,8 @@ window.__ModuleLoader__.load({
940
1101
  }, '停止') : null,
941
1102
  h('button', {
942
1103
  onClick: configureModels,
943
- disabled: configuring || detecting || verifying,
1104
+ disabled: configuring || detecting || verifying || noKey,
1105
+ title: noKey ? keyHint : undefined,
944
1106
  style: {
945
1107
  padding: '7px 14px',
946
1108
  fontSize: '13px',
@@ -948,8 +1110,8 @@ window.__ModuleLoader__.load({
948
1110
  color: 'inherit',
949
1111
  border: '1px solid rgba(128,128,128,0.4)',
950
1112
  borderRadius: '6px',
951
- cursor: (configuring || detecting || verifying) ? 'wait' : 'pointer',
952
- opacity: (configuring || detecting || verifying) ? 0.6 : 1,
1113
+ cursor: (configuring || detecting || verifying || noKey) ? 'not-allowed' : 'pointer',
1114
+ opacity: (configuring || detecting || verifying || noKey) ? 0.6 : 1,
953
1115
  },
954
1116
  }, configuring ? '配置中…' : '一键配置到设置')
955
1117
  ),
@@ -1044,6 +1206,16 @@ window.__ModuleLoader__.load({
1044
1206
  key: panelId,
1045
1207
  }, NvidiaModelsPanel);
1046
1208
  });
1209
+
1210
+ // 对话输入框上方的 dock 徽标:order 10 位于待办(0)与队列(20)之间。
1211
+ ctx.slots.inject('conversation.input.dock', function () {
1212
+ return ctx.slots.register({
1213
+ name: 'conversation.input.dock',
1214
+ id: 'nvidia-group-status',
1215
+ order: 10,
1216
+ inject: function (sessionId) { return { sessionId: sessionId }; },
1217
+ }, DockBadge);
1218
+ });
1047
1219
  },
1048
1220
  };
1049
1221
  },
package/src/group.js CHANGED
@@ -27,6 +27,14 @@ export function isAutoMemberId(id) {
27
27
  * 而非「该模型不可用」。这类失败应当直接换下一个成员,
28
28
  * 且不计入熔断(模型本身是好的,只是不适合这次请求)。
29
29
  */
30
+ /**
31
+ * 致命失败:对所有组员都一样,换模型也不会好转,因此应立即停止故障转移。
32
+ * 目前仅「缺 API Key / 凭据失效」属于此类。
33
+ */
34
+ export function isFatalFailure(failure) {
35
+ return Boolean(failure && typeof failure === 'object' && failure.code === 'NO_API_KEY');
36
+ }
37
+
30
38
  export function isCapabilityMismatch(failure) {
31
39
  if (!failure || typeof failure !== 'object') return false;
32
40
  if (failure.code === 'CONTEXT_WINDOW_EXCEEDED' || failure.code === 'MODEL_SWITCH_COMPACTION_FAILED' || failure.code === 'INVALID_REQUEST') {
@@ -373,6 +381,14 @@ export async function* runFailover(options, deps) {
373
381
  }
374
382
 
375
383
  lastFailure = failure;
384
+ // 致命错误(如缺 API Key):对所有成员都一样,换模型无用——立即停止,如实把友好提示交给用户。
385
+ if (isFatalFailure(failure)) {
386
+ if (typeof deps.onAttempt === 'function') {
387
+ try { deps.onAttempt({ member, error: failure, emitted, sessionId, firstByteMs, elapsedMs: Date.now() - startedAt, usage: null, fatal: true }); } catch { /* 忽略 */ }
388
+ }
389
+ yield { type: 'finish', reason: { kind: 'error', failure: toFailure(failure) } };
390
+ return;
391
+ }
376
392
  // 「能力不符 / 空回答 / 首段正文超时」不是模型“坏了”,而是这次请求不称职:不记熔断,直接换下一个成员。
377
393
  const capability = isCapabilityMismatch(failure) || failure.code === 'EMPTY_ANSWER' || failure.code === 'FIRST_TEXT_TIMEOUT';
378
394
  if (!capability && health && typeof health.recordFailure === 'function') health.recordFailure(member.id, failure);
package/src/index.js CHANGED
@@ -134,6 +134,13 @@ function withCredentials(ctx, operation) {
134
134
  });
135
135
  }
136
136
 
137
+ /** NVIDIA Key 是否已配置(凭据服务不可用时按「已配置」处理,避免误拦截)。 */
138
+ async function hasNvidiaKey(ctx) {
139
+ const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
140
+ if (!info || info.unavailable) return true; // 无法判定时不拦截,交给上游返回真实错误
141
+ return Boolean(info.configured);
142
+ }
143
+
137
144
  /** Run one operation against the configEditor service; resolves null when unavailable. */
138
145
  function withConfigEditor(ctx, operation) {
139
146
  return new Promise((done) => {
@@ -488,8 +495,44 @@ const NVIDIA_KEY_REF = 'NVIDIA_API_KEY';
488
495
  */
489
496
  const groupHealth = createHealthRegistry({ failThreshold: 2, baseCooldownMs: 20000, maxCooldownMs: 300000 });
490
497
 
498
+ /**
499
+ * 调用日志持久化文件(放在 profile 目录而非插件目录):市场重装会替换 node_modules
500
+ * 里的插件实体目录、放到那里会跟着丢;profile 目录稳定。无 DSH_PROFILE_DIR 时返回空,
501
+ * 静默降级为纯内存(便于测试与非 DSH 环境)。
502
+ */
503
+ function defaultUsageFilePath() {
504
+ const dir = process.env.DSH_PROFILE_DIR;
505
+ if (!dir) return '';
506
+ return dir.replace(/\/+$/, '') + '/nvidia-usage.json';
507
+ }
508
+
509
+ /** 文件型 storage(ESM 用动态 import):全量快照覆盖写,读写失败一律静默。 */
510
+ function makeFileStorage() {
511
+ // Never touch the real profile usage file while running under `node --test`
512
+ // (smoke tests exercise apply()/stream and would otherwise pollute it).
513
+ if (process.env.NODE_TEST_CONTEXT) return null;
514
+ const file = defaultUsageFilePath();
515
+ if (!file) return null;
516
+ return {
517
+ async load() {
518
+ try {
519
+ const fs = await import('node:fs/promises');
520
+ return JSON.parse(await fs.readFile(file, 'utf8'));
521
+ } catch { return null; }
522
+ },
523
+ async save(data) {
524
+ try {
525
+ const fs = await import('node:fs/promises');
526
+ const tmp = file + '.tmp';
527
+ await fs.writeFile(tmp, JSON.stringify(data), 'utf8');
528
+ await fs.rename(tmp, file); // atomic replace
529
+ } catch { /* best-effort */ }
530
+ },
531
+ };
532
+ }
533
+
491
534
  /** 当日调用用量登记表(进程级单例):模型组每次尝试都记一条,供面板「调用日志」展示。 */
492
- const groupUsage = createUsageRegistry({ retentionDays: 7, maxLogPerDay: 200 });
535
+ const groupUsage = createUsageRegistry({ retentionDays: 7, maxLogPerDay: 200, storage: makeFileStorage() });
493
536
 
494
537
  /** 组运行参数(内存态,可被 setGroupConfig 覆盖)。 */
495
538
  const groupConfig = {
@@ -499,6 +542,30 @@ const groupConfig = {
499
542
  autoRefreshMs: 300000,
500
543
  };
501
544
 
545
+ /**
546
+ * 输入框 dock 徽标的共享状态(进程级内存,重启归零)。
547
+ * 记录最近一次真正产出正文的成员、最近一次切换来源/时间、累计切换次数,
548
+ * 由 buildGroupAdapter 的 onAttempt / onFailover 更新,route `dockStatus` 暴露给 client。
549
+ */
550
+ const dockGroupState = {
551
+ sessionId: null,
552
+ memberId: '',
553
+ memberName: '',
554
+ switchFrom: '',
555
+ switchAt: 0,
556
+ switchCount: 0,
557
+ updatedAt: 0,
558
+ };
559
+
560
+ /** 成员的短友好名(优先配置里的 name,否则取 id 最后一段)。 */
561
+ function friendlyMemberName(member) {
562
+ if (!member) return '';
563
+ if (member.name) return String(member.name);
564
+ const id = String(member.id || '');
565
+ const tail = id.split('/').pop();
566
+ return tail || id;
567
+ }
568
+
502
569
  /**
503
570
  * 自动发现:最近一次实时检测到的模型(面板点「检测」、configure 成功或后台自动刷新时更新)。
504
571
  * 组成员解析顺序:已配置模型 → 最近检测到的对话模型 → 内置种子。
@@ -616,6 +683,54 @@ function appendGroupEvent(ctx, sessionId, type, data) {
616
683
  }
617
684
  }
618
685
 
686
+ /** 没有 Key / 凭据失效时给出的统一可读提示。 */
687
+ const NO_KEY_MESSAGE = 'NVIDIA API Key 未配置或已失效,请在 NVIDIA 模型面板顶部保存 Key 后重试。';
688
+
689
+ /**
690
+ * 包装 llm.stream:把上游的「缺凭据 / 401 / 403」错误翻译成带 NO_API_KEY 码的
691
+ * 友好失败。这类错误对所有成员都一样,group.js 会识别为致命错误直接停止故障转移。
692
+ */
693
+ function translateKeyError(failure) {
694
+ if (!failure || typeof failure !== 'object') return failure;
695
+ const code = String(failure.code || '');
696
+ const status = failure.status;
697
+ const msg = String(failure.message || '');
698
+ const isKeyIssue = code === 'MISSING_CREDENTIAL' || code === 'NO_API_KEY'
699
+ || status === 401 || status === 403
700
+ || /api.?key|credential|unauthoriz|authentication|invalid.?token/i.test(msg);
701
+ if (!isKeyIssue) return failure;
702
+ return { code: 'NO_API_KEY', message: NO_KEY_MESSAGE, status };
703
+ }
704
+
705
+ function streamChildWithFriendlyKeyErrors(llm, childOptions) {
706
+ const source = llm.stream(childOptions);
707
+ return (async function* () {
708
+ try {
709
+ for await (const chunk of source) {
710
+ // finish error 块:翻译其 failure。
711
+ if (chunk && chunk.type === 'finish' && chunk.reason && (chunk.reason.kind === 'error' || chunk.reason.kind === 'aborted')) {
712
+ const failure = translateKeyError(chunk.reason.failure);
713
+ if (failure !== chunk.reason.failure) {
714
+ yield { ...chunk, reason: { ...chunk.reason, failure } };
715
+ continue;
716
+ }
717
+ }
718
+ yield chunk;
719
+ }
720
+ } catch (error) {
721
+ // 抛出的错误里也可能是缺凭据。
722
+ const failure = translateKeyError(error && typeof error === 'object'
723
+ ? { code: error.code, status: error.status, message: error.message }
724
+ : { message: String(error) });
725
+ if (failure && failure.code === 'NO_API_KEY') {
726
+ yield { type: 'finish', reason: { kind: 'error', failure } };
727
+ } else {
728
+ throw error;
729
+ }
730
+ }
731
+ })();
732
+ }
733
+
619
734
  /** 构造“模型组”适配器:内部按健康度顺序把请求转给真正的 nvidia 路由。 */
620
735
  function buildGroupAdapter(ctx, llm) {
621
736
  return createGroupAdapter({
@@ -626,11 +741,21 @@ function buildGroupAdapter(ctx, llm) {
626
741
  return members;
627
742
  },
628
743
  // 用注入到的 llm 服务实例直接调用(外层 ctx 未声明注入 llm,不能在请求时访问 ctx.llm)。
629
- streamChild: (childOptions) => llm.stream(childOptions),
744
+ // 同时把「没有 Key / 凭据失效」的上游错误翻译成可读提示——这种错误对所有成员都一样,
745
+ // 由 group.js 识别为致命错误直接停止故障转移,避免无谓地逐个重试。
746
+ streamChild: (childOptions) => streamChildWithFriendlyKeyErrors(llm, childOptions),
630
747
  health: groupHealth,
631
748
  firstByteTimeoutMs: () => groupConfig.firstByteTimeoutMs,
632
749
  firstTextTimeoutMs: () => groupConfig.firstTextTimeoutMs,
633
750
  onAttempt: (info) => {
751
+ // dock 徽标:只在「真正产出正文」的成功尝试里更新当前模型名。
752
+ // info.error 为空且 info.emitted 为真代表该成员给出了可见正文(而非纯思考/失败)。
753
+ if (!info.error && info.emitted && info.member) {
754
+ dockGroupState.memberId = String(info.member.id || '');
755
+ dockGroupState.memberName = friendlyMemberName(info.member);
756
+ dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
757
+ dockGroupState.updatedAt = Date.now();
758
+ }
634
759
  appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_PROBE, {
635
760
  member: info.member.id,
636
761
  status: info.error ? 'fail' : 'ok',
@@ -656,6 +781,13 @@ function buildGroupAdapter(ctx, llm) {
656
781
  }
657
782
  },
658
783
  onFailover: (info) => {
784
+ // dock 徽标:记录「刚从哪个模型切换过来」,供几秒内的橙色高亮提示。
785
+ if (info.from) {
786
+ dockGroupState.switchFrom = friendlyMemberName(info.from);
787
+ dockGroupState.switchAt = Date.now();
788
+ dockGroupState.switchCount += 1;
789
+ dockGroupState.sessionId = info.sessionId || dockGroupState.sessionId;
790
+ }
659
791
  appendGroupEvent(ctx, info.sessionId, GROUP_RECORD_FAILOVER, {
660
792
  from: info.from ? info.from.id : '',
661
793
  to: info.to ? info.to.id : '',
@@ -700,6 +832,47 @@ async function groupStatusSnapshot(ctx) {
700
832
  };
701
833
  }
702
834
 
835
+ /** 输入框 dock 徽标状态:当前实际出正文的模型 + 切换/熔断计数。 */
836
+ async function dockStatusSnapshot(ctx, sessionId) {
837
+ const members = (await resolveGroupMembers(ctx)) || [];
838
+ const cooling = members.filter((m) => groupHealth.cooldownRemainingMs(m.id) > 0).length;
839
+ // 「刚切换」提示保留 6 秒,之后回落到常态绿色。
840
+ const SWITCH_NOTICE_MS = 6000;
841
+ const justSwitched = Boolean(dockGroupState.switchFrom) && (Date.now() - dockGroupState.switchAt < SWITCH_NOTICE_MS);
842
+ // 当前会话已切到别的模型时隐藏徽标:读会话最新 request/header 的 provider。
843
+ // best-effort:读不到 header 时保持原逻辑,避免误隐藏。
844
+ let currentProvider = '';
845
+ let currentModel = '';
846
+ try {
847
+ const session = sessionFor(ctx, sessionId);
848
+ const header = session && typeof session.requestHeader === 'function' ? session.requestHeader() : null;
849
+ if (header && header.config) {
850
+ if (typeof header.config.provider === 'string') {
851
+ currentProvider = header.config.provider;
852
+ }
853
+ if (typeof header.config.model === 'string') {
854
+ currentModel = header.config.model;
855
+ }
856
+ }
857
+ } catch {
858
+ currentProvider = '';
859
+ currentModel = '';
860
+ }
861
+ const usingGroup = !currentProvider || currentProvider === 'nvidia-group';
862
+ // best-effort: 读不到 model 信息时不隐藏;只有明确选了非 auto 的具体模型才隐藏。
863
+ const isAutoModel = !currentModel || isAutoMemberId(currentModel);
864
+ return {
865
+ ok: true,
866
+ active: Boolean(dockGroupState.memberName) && usingGroup && isAutoModel,
867
+ memberName: dockGroupState.memberName || '',
868
+ memberId: dockGroupState.memberId || '',
869
+ switchFrom: justSwitched ? dockGroupState.switchFrom : '',
870
+ switchCount: dockGroupState.switchCount || 0,
871
+ cooldownCount: cooling,
872
+ updatedAt: dockGroupState.updatedAt || 0,
873
+ };
874
+ }
875
+
703
876
  /** 探测所有成员(用现有 probeStreaming 快速首包探测),刷新健康表。 */
704
877
  async function probeGroup(ctx) {
705
878
  const members = (await resolveGroupMembers(ctx)) || [];
@@ -725,7 +898,7 @@ async function probeGroup(ctx) {
725
898
  return { ok: true, probed: out.length, results: out };
726
899
  }
727
900
 
728
- /** POST /api/nvidia-models — actions: detect | test | keyStatus | setKey | clearKey | configure | groupStatus | probeGroup | resetGroup | getGroupConfig | setGroupConfig | usageStats | resetUsage. */
901
+ /** POST /api/nvidia-models — actions: detect | test | keyStatus | setKey | clearKey | configure | groupStatus | probeGroup | resetGroup | getGroupConfig | setGroupConfig | usageStats | resetUsage | checkUpdate | dockStatus. */
729
902
  function createNvidiaModelsRoute(ctx) {
730
903
  return {
731
904
  path: '/api/nvidia-models',
@@ -735,7 +908,12 @@ function createNvidiaModelsRoute(ctx) {
735
908
  const body = await readJsonBody(request);
736
909
  const action = body && typeof body.action === 'string' ? body.action : 'detect';
737
910
  let result;
738
- if (action === 'test' && typeof body.model === 'string' && body.model) {
911
+ // 需要 Key 的 action 在没有配置 Key 时统一早退,给出一致的可读提示。
912
+ // keyStatus/setKey/clearKey/resetGroup/resetUsage/checkUpdate 不拦(它们本就用于修复无 Key 状态)。
913
+ const NEED_KEY_ACTIONS = new Set(['detect', 'test', 'configure', 'probeGroup', 'groupStatus', 'dockStatus', 'usageStats']);
914
+ if (NEED_KEY_ACTIONS.has(action) && !(await hasNvidiaKey(ctx))) {
915
+ result = { ok: false, code: 'NO_API_KEY', message: '未配置 NVIDIA API Key,请先在面板上方保存后再继续。' };
916
+ } else if (action === 'test' && typeof body.model === 'string' && body.model) {
739
917
  result = await testNvidiaModel(body.model);
740
918
  } else if (action === 'keyStatus') {
741
919
  const info = await withCredentials(ctx, (credentials) => credentials.describe(NVIDIA_KEY_REF));
@@ -799,6 +977,8 @@ function createNvidiaModelsRoute(ctx) {
799
977
  result = { ok: true, stats: groupUsage.snapshot() };
800
978
  } else if (action === 'checkUpdate') {
801
979
  result = await checkUpdate(ctx);
980
+ } else if (action === 'dockStatus') {
981
+ result = await dockStatusSnapshot(ctx, body.sessionId);
802
982
  } else {
803
983
  result = await detectNvidiaModels();
804
984
  if (result && result.source === 'live') lastDetectedModels = normalizeGroupMembers(result.models);
@@ -915,6 +1095,22 @@ export function apply(ctx) {
915
1095
  // 清零是安全的——真正的上游不可用仍由 FAILOVER 与看板实时探测照常兜底。
916
1096
  try { groupHealth.reset(); } catch { /* 忽略 */ }
917
1097
 
1098
+ // 同步清空 dock 徽标状态:重载后没有"当前模型"可报,徽标回落为不显示,
1099
+ // 直到模型组下一次真正产出正文才重新点亮。
1100
+ try {
1101
+ dockGroupState.sessionId = null;
1102
+ dockGroupState.memberId = '';
1103
+ dockGroupState.memberName = '';
1104
+ dockGroupState.switchFrom = '';
1105
+ dockGroupState.switchAt = 0;
1106
+ dockGroupState.switchCount = 0;
1107
+ dockGroupState.updatedAt = 0;
1108
+ } catch { /* 忽略 */ }
1109
+
1110
+ // 从磁盘读回调用日志快照(重载/重启不丢)。fire-and-forget:hydrate 内部已
1111
+ // 全量 try/catch,失败静默;不阻塞插件激活。
1112
+ try { Promise.resolve(groupUsage.hydrate()).catch(() => {}); } catch { /* 忽略 */ }
1113
+
918
1114
  // Slash-command handlers run against an agent invocation ({ agent, rawInput }),
919
1115
  // NOT the plugin context — so both handlers close over the plugin ctx instead.
920
1116
  disposers.push(ctx.commands.register({
package/src/usage.js CHANGED
@@ -49,12 +49,17 @@ function num(value) {
49
49
  * @param {() => number} [opts.now] clock (defaults to Date.now)
50
50
  * @param {number} [opts.retentionDays] how many day buckets to keep (default 7)
51
51
  * @param {number} [opts.maxLogPerDay] rolling log cap per day (default 200)
52
+ * @param {{load:()=>Promise<any>, save:(data:any)=>Promise<void>}} [opts.storage]
53
+ * optional persistence adapter. Without it the registry stays in-memory only.
52
54
  */
53
55
  export function createUsageRegistry(opts = {}) {
54
56
  const clock = typeof opts.now === 'function' ? opts.now : () => Date.now();
55
57
  const retentionDays = Number.isFinite(opts.retentionDays) && opts.retentionDays > 0 ? opts.retentionDays : 7;
56
58
  const maxLogPerDay =
57
59
  Number.isFinite(opts.maxLogPerDay) && opts.maxLogPerDay > 0 ? Math.floor(opts.maxLogPerDay) : 200;
60
+ const storage = opts.storage && typeof opts.storage.load === 'function' && typeof opts.storage.save === 'function'
61
+ ? opts.storage
62
+ : null;
58
63
 
59
64
  /** @type {Map<string, ReturnType<typeof emptyDay>>} */
60
65
  const days = new Map();
@@ -69,6 +74,84 @@ export function createUsageRegistry(opts = {}) {
69
74
  return day;
70
75
  }
71
76
 
77
+ // ---- persistence -------------------------------------------------------
78
+ // Serialise the whole registry (Map -> plain object) and write a full
79
+ // snapshot on every change. A serial write chain prevents overlapping
80
+ // writes from clobbering each other; failures are swallowed so persistence
81
+ // never breaks the hot failover path.
82
+ let writeChain = Promise.resolve();
83
+
84
+ function serialize() {
85
+ const out = {};
86
+ for (const [key, day] of days) {
87
+ out[key] = {
88
+ total: { ...day.total },
89
+ members: Object.fromEntries(day.members),
90
+ log: day.log.slice(),
91
+ };
92
+ }
93
+ return { version: 1, days: out };
94
+ }
95
+
96
+ function deserialize(data) {
97
+ if (!data || typeof data !== 'object' || !data.days || typeof data.days !== 'object') return;
98
+ for (const [key, raw] of Object.entries(data.days)) {
99
+ if (typeof key !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(key) || !raw || typeof raw !== 'object') continue;
100
+ const day = emptyDay();
101
+ if (raw.total && typeof raw.total === 'object') {
102
+ const t = day.total;
103
+ for (const k of Object.keys(t)) t[k] = num(raw.total[k]);
104
+ }
105
+ if (raw.members && typeof raw.members === 'object') {
106
+ for (const [id, m] of Object.entries(raw.members)) {
107
+ if (!m || typeof m !== 'object') continue;
108
+ const clean = emptyMember();
109
+ for (const k of Object.keys(clean)) clean[k] = k === 'lastError' ? String(m[k] || '') : num(m[k]);
110
+ day.members.set(id, clean);
111
+ }
112
+ }
113
+ if (Array.isArray(raw.log)) {
114
+ day.log = raw.log.slice(-maxLogPerDay).map((e) => ({
115
+ at: num(e && e.at),
116
+ memberId: String((e && e.memberId) || 'unknown'),
117
+ ok: !!(e && e.ok),
118
+ failover: !!(e && e.failover),
119
+ failoverFrom: String((e && e.failoverFrom) || ''),
120
+ firstByteMs: num(e && e.firstByteMs),
121
+ elapsedMs: num(e && e.elapsedMs),
122
+ inputTokens: num(e && e.inputTokens),
123
+ outputTokens: num(e && e.outputTokens),
124
+ error: String((e && e.error) || ''),
125
+ }));
126
+ }
127
+ days.set(key, day);
128
+ }
129
+ }
130
+
131
+ function persist() {
132
+ if (!storage) return;
133
+ writeChain = writeChain.then(async () => {
134
+ try {
135
+ prune();
136
+ await storage.save(serialize());
137
+ } catch {
138
+ // Persistence is best-effort; in-memory stats remain authoritative.
139
+ }
140
+ });
141
+ }
142
+
143
+ /** Load a previously persisted snapshot into memory (best-effort). */
144
+ async function hydrate() {
145
+ if (!storage) return;
146
+ try {
147
+ const data = await storage.load();
148
+ if (data != null) deserialize(data);
149
+ prune();
150
+ } catch {
151
+ // Corrupt / missing storage: start fresh, never throw into apply().
152
+ }
153
+ }
154
+
72
155
  function prune() {
73
156
  const cutoff = clock() - retentionDays * DAY_MS;
74
157
  for (const key of [...days.keys()]) {
@@ -150,6 +233,7 @@ export function createUsageRegistry(opts = {}) {
150
233
  if (day.log.length > maxLogPerDay) {
151
234
  day.log.splice(0, day.log.length - maxLogPerDay);
152
235
  }
236
+ persist();
153
237
  return logEntry;
154
238
  }
155
239
 
@@ -189,6 +273,7 @@ export function createUsageRegistry(opts = {}) {
189
273
  } else {
190
274
  days.clear();
191
275
  }
276
+ persist();
192
277
  }
193
278
 
194
279
  /** List the day keys currently retained (newest last). */
@@ -196,5 +281,5 @@ export function createUsageRegistry(opts = {}) {
196
281
  return [...days.keys()].sort();
197
282
  }
198
283
 
199
- return { record, snapshot, reset, prune, days: days_ };
284
+ return { record, snapshot, reset, prune, days: days_, hydrate, serialize, deserialize };
200
285
  }