dsh-agent-sdk-bridge 1.0.1 → 1.1.1

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/client.js CHANGED
@@ -1,1802 +1,2411 @@
1
- /**
2
- * dsh-agent-sdk-bridge — browser half.
3
- *
4
- * Contributes one top-level settings section per enabled provider (`qoder-cn`,
5
- * `qoder-intl`, `codebuddy`), each showing its account card and then the model
6
- * list: every model the account exposes, with an on/off switch and a
7
- * context-window choice, plus a collapsed "advanced" area holding the scalars
8
- * worth reaching without editing YAML. The plugin manager's page for this
9
- * bundle carries the switches that decide which of those sections exist.
10
- *
11
- * The model list cannot come from the config form: it is fetched live from the
12
- * provider. So the page reads `GET <prefix>/models`, which joins that live
13
- * catalog with the user's stored choices, while every change goes back through
14
- * the host's own config form. The host owns the catalog, so the page never
15
- * derives state the adapter does not share.
16
- *
17
- * The page can also start the CLI helper shipped with this package
18
- * (`POST <prefix>/setup`, then `GET <prefix>/setup` for its output): installing
19
- * and signing into qoderclicn is a local action a browser cannot perform.
20
- *
21
- * Rendering from the schema-driven form alone would be wrong here: the useful
22
- * controls depend on rows that only exist at runtime.
23
- *
24
- * Hand-written ModuleLoader bundle: no build step, no dependency beyond the
25
- * `react` the shell already provides. Colour comes from theme variables so the
26
- * page survives a scheme switch.
27
- */
28
-
29
- window.__ModuleLoader__.load({
30
- id: 'dsh-agent-sdk-bridge',
31
- factory: require => {
32
- const module = { exports: {} }
33
- const exports = module.exports
34
- const React = require('react')
35
- const { createElement: h, useState, useEffect, useCallback, useMemo, useRef, useSyncExternalStore } = React
36
-
37
- /** The plugin's config namespace — must equal the profile row id. */
38
- const NS = 'llm-qoder-cn'
39
- const inject = ['slots', 'locale', 'configForms']
40
-
41
- // ── copy ────────────────────────────────────────────────────────────────
42
- const zh = {
43
- nav: 'Qoder CN',
44
- title: 'Qoder CN',
45
- intro: '勾选要启用的模型,并为需要的模型指定上下文窗口。改动即时生效,无需重启。',
46
- loading: '正在读取模型列表…',
47
- loadFailed: '读取模型列表失败',
48
- retry: '重试',
49
- refresh: '刷新列表',
50
- refreshing: '刷新中…',
51
- saveFailed: '保存失败',
52
- notApplied: '服务器未报告这次改动,可能被其他窗口覆盖了,请刷新后重试',
53
- timeout: '保存超时,请重试',
54
- saved: '已保存',
55
- saving: '保存中…',
56
- enabledCount: '已启用',
57
- noModels: '账号没有返回任何模型:一般是本机 qoderclicn 还没装好,或者还没登录。',
58
- search: '搜索模型…',
59
- onlyEnabled: '只看已启用',
60
- selectAll: '全部启用',
61
- selectNone: '全部关闭',
62
- colEnabled: '启用',
63
- windowDefault: '默认',
64
- windowDefaultHint: '跟随上游声明的窗口',
65
- vision: '读图',
66
- free: '免费',
67
- advanced: '高级设置',
68
- advancedHint: '以下为细节参数,通常无需改动。',
69
- show: '展开',
70
- hide: '收起',
71
- reset: '恢复默认',
72
- windowWarn: '窗口越大,DSH 的自动压缩触发得越晚。若对话经常超限,请选较小的窗口。',
73
- cliGroup: 'Qoder CN CLI',
74
- cliHint: '插件复用本机 qoderclicn 的登录态。这里可以直接跑随包附带的配置脚本:缺 CLI 就装,未登录就拉起浏览器登录。',
75
- cliRun: '一键配置',
76
- cliLogin: '重新登录',
77
- cliRunning: '正在执行,输出持续刷新…',
78
- cliStartFailed: '无法启动配置脚本',
79
- cliExitOk: '配置脚本执行完成',
80
- cliExitFail: '配置脚本未通过,退出码',
81
- cliShowLog: '查看输出',
82
- cliHideLog: '收起输出',
83
- cliUninstall: '卸载 CLI',
84
- cliUninstallConfirm: '确定要卸载本机的 Qoder CLI 吗?卸载后需要重新安装才能继续使用,登录凭证会保留。',
85
- cliUninstalling: '正在卸载…',
86
- cliUninstallOk: 'CLI 已卸载',
87
- intlNav: 'Qoder 国际版',
88
- intlTitle: 'Qoder 国际版',
89
- intlIntro: '国际版账户(qoder.com)的模型与额度。勾选要启用的模型,并为需要的模型指定上下文窗口。改动即时生效,无需重启。',
90
- intlNoModels: '国际版账号没有返回任何模型:一般是本机 qodercli 还没装好,或者还没登录。',
91
- intlCliGroup: 'Qoder 国际版 CLI',
92
- intlCliHint: '插件复用本机 qodercli 的登录态。这里可以直接跑随包附带的配置脚本:缺 CLI 就装,未登录就拉起浏览器登录。',
93
- usageTitle: '额度',
94
- usageLoading: '正在读取额度…',
95
- usageRefresh: '刷新额度',
96
- usageUnavailable: '无法读取额度',
97
- usageRetry: '重试',
98
- usageAccount: '账号',
99
- usagePlan: '套餐',
100
- usageUsed: '已用',
101
- usageRemaining: '剩余',
102
- usageOf: '/',
103
- usageCredits: 'credits',
104
- usagePlanQuota: '套餐额度',
105
- usageAddOn: '加量包',
106
- usageOrgPackage: '组织资源包',
107
- usageExpires: '到期',
108
- usageNever: '长期有效',
109
- usageDetail: '用量明细',
110
- usageUpgrade: '升级套餐',
111
- usageExceeded: '额度已用完',
112
- usageUpdated: '更新于',
113
- usageUnknownPlan: '未知套餐',
114
- usageStale: '显示上次读数,刷新失败',
115
- pluginOptionsTitle: '启用的版本',
116
- pluginOptionsHint: '关闭后,对应设置页、模型列表与模型分组都会移除;已保存的模型选择保留,重新打开即可恢复。',
117
- pluginOptionsOn: '显示中',
118
- pluginOptionsOff: '已关闭',
119
- pluginOptionsReadOnly: '当前配置不可写',
120
- pluginOptionsRejected: '宿主拒绝了这次改动;若刚更新过插件,请重启 DSH 后再试',
121
- codebuddyNav: 'CodeBuddy',
122
- codebuddyTitle: 'CodeBuddy',
123
- codebuddyIntro: '腾讯 CodeBuddy 账户的模型。请先在下方选择登录区域并登录,再勾选要启用的模型。',
124
- codebuddyNoModels: 'CodeBuddy 账号没有返回任何模型:请确认已选择登录区域并完成登录。',
125
- codebuddyAuthTitle: '登录',
126
- codebuddyAuthHint: 'CodeBuddy 分国际版与国内版,两边账号与模型目录独立。企业域名登录不在本插件支持范围内。',
127
- codebuddyRegionGlobal: '国际版(codebuddy.ai)',
128
- codebuddyRegionCn: '国内版(copilot.tencent.com)',
129
- codebuddyRegionLabel: '登录区域',
130
- codebuddyLogin: '登录',
131
- codebuddyLogout: '退出登录',
132
- codebuddyLoggingIn: '请在浏览器中完成登录…',
133
- codebuddyLoginPrompt: '登录后这里会显示账号与额度信息。',
134
- codebuddyModelsHint: '请先登录 CodeBuddy,登录后才会读取并显示可用模型。',
135
- codebuddyRegionMismatch: '宿主返回的模型列表不属于当前区域,请刷新页面后重试。',
136
- codebuddyLoginStarted: '已打开浏览器,完成登录后这里会自动更新。',
137
- codebuddyLoginFailed: '登录失败',
138
- codebuddyOpenUrl: '手动打开登录页',
139
- codebuddyLoggedOut: '已退出登录',
140
- codebuddyNotLoggedIn: '未登录',
141
- codebuddySignedIn: '已登录',
142
- codebuddyAccountUnknown: '账号信息暂不可用',
143
- codebuddyNoQuota: '暂时无法读取额度。',
144
- codebuddyQuotaFailed: '额度读取失败',
145
- codebuddyQuotaTitle: '积分额度',
146
- codebuddyQuotaPackages: '积分包',
147
- codebuddyQuotaExpires: '最近到期',
148
- codebuddyConfirmLogout: '确定要退出当前区域的 CodeBuddy 登录吗?',
149
- advancedFields: {
150
- displayName: '分组名称',
151
- maxSessions: '并发会话数',
152
- modelCacheTtlSeconds: '模型列表缓存(秒)',
153
- defaultReasoningEffort: '默认思考档位',
154
- defaultMaxTokens: '默认输出上限',
155
- toolResultTimeoutSeconds: '工具结果等待(秒)',
156
- catalogFetchTimeoutSeconds: '模型列表超时(秒)',
157
- abortGraceSeconds: '中断宽限(秒)',
158
- coldMaxTurns: '旁路请求轮次',
159
- modelAliases: '模型别名',
160
- intlDisplayName: '国际版分组名称',
161
- intlModelAliases: '国际版模型别名',
162
- codebuddyDisplayName: 'CodeBuddy 分组名称',
163
- codebuddyModelAliases: 'CodeBuddy 模型别名',
164
- },
165
- }
166
- const en = {
167
- nav: 'Qoder CN',
168
- title: 'Qoder CN',
169
- intro: 'Tick the models you want available and set a context window where needed. Changes apply immediately.',
170
- loading: 'Loading models…',
171
- loadFailed: 'Could not load the model list',
172
- retry: 'Retry',
173
- refresh: 'Refresh',
174
- refreshing: 'Refreshing…',
175
- saveFailed: 'Save failed',
176
- notApplied: 'The host did not report this change; another window may have overwritten it. Refresh and retry.',
177
- timeout: 'Save timed out; please retry',
178
- saved: 'Saved',
179
- saving: 'Saving…',
180
- enabledCount: 'enabled',
181
- noModels: 'The account returned no models - usually qoderclicn is not installed on this machine, or not signed in.',
182
- search: 'Search models…',
183
- onlyEnabled: 'Enabled only',
184
- selectAll: 'Enable all',
185
- selectNone: 'Disable all',
186
- colEnabled: 'On',
187
- windowDefault: 'Default',
188
- windowDefaultHint: "Follow upstream's declared window",
189
- vision: 'Vision',
190
- free: 'Free',
191
- advanced: 'Advanced',
192
- advancedHint: 'Detail parameters; rarely changed.',
193
- show: 'Show',
194
- hide: 'Hide',
195
- reset: 'Reset',
196
- windowWarn: 'A larger window delays DSH\u2019s auto-compaction. Pick a smaller one if conversations overflow.',
197
- cliGroup: 'Qoder CN CLI',
198
- cliHint: 'The plugin reuses this machine\u2019s qoderclicn sign-in. Run the bundled helper from here: it installs the CLI when missing and opens the browser sign-in when signed out.',
199
- cliRun: 'Configure',
200
- cliLogin: 'Re-login',
201
- cliRunning: 'Running, output refreshes…',
202
- cliStartFailed: 'Could not start the helper',
203
- cliExitOk: 'Helper finished',
204
- cliExitFail: 'Helper failed with exit code',
205
- cliShowLog: 'Show output',
206
- cliHideLog: 'Hide output',
207
- cliUninstall: 'Uninstall CLI',
208
- cliUninstallConfirm: 'Uninstall the Qoder CLI from this machine? It must be installed again to keep using this edition. Sign-in files are kept.',
209
- cliUninstalling: 'Uninstalling…',
210
- cliUninstallOk: 'CLI uninstalled',
211
- intlNav: 'Qoder International',
212
- intlTitle: 'Qoder International',
213
- intlIntro: 'Models and quota for the international account (qoder.com). Tick the models you want available and set a context window where needed. Changes apply immediately.',
214
- intlNoModels: 'The international account returned no models - usually qodercli is not installed on this machine, or not signed in.',
215
- intlCliGroup: 'Qoder International CLI',
216
- intlCliHint: 'The plugin reuses this machine\u2019s qodercli sign-in. Run the bundled helper from here: it installs the CLI when missing and opens the browser sign-in when signed out.',
217
- usageTitle: 'Quota',
218
- usageLoading: 'Reading quota…',
219
- usageRefresh: 'Refresh quota',
220
- usageUnavailable: 'Could not read the quota',
221
- usageRetry: 'Retry',
222
- usageAccount: 'Account',
223
- usagePlan: 'Plan',
224
- usageUsed: 'Used',
225
- usageRemaining: 'Remaining',
226
- usageOf: '/',
227
- usageCredits: 'credits',
228
- usagePlanQuota: 'Plan quota',
229
- usageAddOn: 'Add-on package',
230
- usageOrgPackage: 'Organization package',
231
- usageExpires: 'Expires',
232
- usageNever: 'No expiry',
233
- usageDetail: 'Usage details',
234
- usageUpgrade: 'Upgrade',
235
- usageExceeded: 'Quota exhausted',
236
- usageUpdated: 'Updated',
237
- usageUnknownPlan: 'Unknown plan',
238
- usageStale: 'Showing the last reading; refresh failed',
239
- pluginOptionsTitle: 'Enabled editions',
240
- pluginOptionsHint: 'Turning one off removes its settings page, model list, and model group. Saved model choices are kept, so turning it back on restores them.',
241
- pluginOptionsOn: 'Shown',
242
- pluginOptionsOff: 'Off',
243
- pluginOptionsReadOnly: 'This configuration is read-only',
244
- pluginOptionsRejected: 'The host rejected this change; if you just updated the plugin, restart DSH and retry',
245
- codebuddyNav: 'CodeBuddy',
246
- codebuddyTitle: 'CodeBuddy',
247
- codebuddyIntro: 'Models for your Tencent CodeBuddy account. Choose a login region below and sign in before enabling models.',
248
- codebuddyNoModels: 'The CodeBuddy account returned no models: make sure a region is selected and the browser login completed.',
249
- codebuddyAuthTitle: 'Sign in',
250
- codebuddyAuthHint: 'CodeBuddy has independent international and mainland accounts with their own model catalogs. Enterprise-domain login is out of scope for this plugin.',
251
- codebuddyRegionGlobal: 'International (codebuddy.ai)',
252
- codebuddyRegionCn: 'Mainland (copilot.tencent.com)',
253
- codebuddyRegionLabel: 'Login region',
254
- codebuddyLogin: 'Sign in',
255
- codebuddyLogout: 'Sign out',
256
- codebuddyLoggingIn: 'Finish the sign-in in your browser…',
257
- codebuddyLoginPrompt: 'Sign in to see the account and quota here.',
258
- codebuddyModelsHint: 'Sign in to CodeBuddy first; the model catalog is read only after sign-in.',
259
- codebuddyRegionMismatch: 'The host answered with the other region\'s models; reload the page and try again.',
260
- codebuddyLoginStarted: 'Browser opened; this card updates when the login completes.',
261
- codebuddyLoginFailed: 'Sign-in failed',
262
- codebuddyOpenUrl: 'Open the sign-in page',
263
- codebuddyLoggedOut: 'Signed out',
264
- codebuddyNotLoggedIn: 'Not signed in',
265
- codebuddySignedIn: 'Signed in',
266
- codebuddyAccountUnknown: 'Account details are unavailable',
267
- codebuddyNoQuota: 'The quota is temporarily unavailable.',
268
- codebuddyQuotaFailed: 'Could not read the quota',
269
- codebuddyQuotaTitle: 'Credits',
270
- codebuddyQuotaPackages: 'Credit packages',
271
- codebuddyQuotaExpires: 'Earliest expiry',
272
- codebuddyConfirmLogout: 'Sign out of CodeBuddy for the selected region?',
273
- advancedFields: {
274
- displayName: 'Group name',
275
- maxSessions: 'Concurrent sessions',
276
- modelCacheTtlSeconds: 'Catalog cache (s)',
277
- defaultReasoningEffort: 'Default reasoning effort',
278
- defaultMaxTokens: 'Default output cap',
279
- toolResultTimeoutSeconds: 'Tool result wait (s)',
280
- catalogFetchTimeoutSeconds: 'Catalog timeout (s)',
281
- abortGraceSeconds: 'Abort grace (s)',
282
- coldMaxTurns: 'Side-channel turns',
283
- modelAliases: 'Model aliases',
284
- intlDisplayName: 'International group name',
285
- intlModelAliases: 'International model aliases',
286
- codebuddyDisplayName: 'CodeBuddy group name',
287
- codebuddyModelAliases: 'CodeBuddy model aliases',
288
- },
289
- }
290
-
291
- /**
292
- * Scalars shown under Advanced, in order, with how to render each.
293
- *
294
- * The schema is the source of truth for labels, help text and bounds; this
295
- * list only decides order and which control each field gets.
296
- */
297
- const ADVANCED = {
298
- cn: [
299
- ['displayName', 'text'],
300
- ['maxSessions', 'number'],
301
- ['modelCacheTtlSeconds', 'number'],
302
- ['defaultReasoningEffort', 'text'],
303
- ['defaultMaxTokens', 'number'],
304
- ['toolResultTimeoutSeconds', 'number'],
305
- ['catalogFetchTimeoutSeconds', 'number'],
306
- ['abortGraceSeconds', 'number'],
307
- ['coldMaxTurns', 'number'],
308
- ['modelAliases', 'json'],
309
- ],
310
- // The shared scalars above already have a home on the CN page; the intl
311
- // page only adds what is specific to that edition, so the same setting is
312
- // never edited in two places with two different values.
313
- global: [
314
- ['intlDisplayName', 'text'],
315
- ['intlModelAliases', 'json'],
316
- ],
317
- codebuddy: [
318
- ['codebuddyDisplayName', 'text'],
319
- ['codebuddyModelAliases', 'json'],
320
- ],
321
- }
322
-
323
- /**
324
- * One settings section per provider.
325
- *
326
- * They share the page component and the API routes; only the config keys,
327
- * the API brand and the copy differ.
328
- */
329
- const BRANDS = [
330
- {
331
- id: 'cn',
332
- kind: 'qoder',
333
- settingsId: 'qoder-cn',
334
- order: 36,
335
- titleKey: 'title',
336
- navKey: 'nav',
337
- introKey: 'intro',
338
- noModelsKey: 'noModels',
339
- cliGroupKey: 'cliGroup',
340
- cliHintKey: 'cliHint',
341
- fields: {
342
- enabled: 'cnEnabled',
343
- disabled: 'disabledModels',
344
- windows: 'modelContextWindows',
345
- },
346
- },
347
- {
348
- id: 'global',
349
- kind: 'qoder',
350
- settingsId: 'qoder-intl',
351
- order: 37,
352
- titleKey: 'intlTitle',
353
- navKey: 'intlNav',
354
- introKey: 'intlIntro',
355
- noModelsKey: 'intlNoModels',
356
- cliGroupKey: 'intlCliGroup',
357
- cliHintKey: 'intlCliHint',
358
- fields: {
359
- enabled: 'intlEnabled',
360
- disabled: 'intlDisabledModels',
361
- windows: 'intlModelContextWindows',
362
- },
363
- },
364
- {
365
- id: 'codebuddy',
366
- kind: 'codebuddy',
367
- settingsId: 'codebuddy',
368
- order: 38,
369
- titleKey: 'codebuddyTitle',
370
- navKey: 'codebuddyNav',
371
- introKey: 'codebuddyIntro',
372
- noModelsKey: 'codebuddyNoModels',
373
- fields: {
374
- enabled: 'codebuddyEnabled',
375
- // The page swaps these for the selected login region's own fields.
376
- disabled: 'codebuddyGlobalDisabledModels',
377
- windows: 'codebuddyGlobalModelContextWindows',
378
- },
379
- },
380
- ]
381
-
382
- const css = {
383
- page: { maxWidth: '860px', display: 'flex', flexDirection: 'column', gap: '14px', color: 'var(--dsw-alias-label-primary)' },
384
- h2: { margin: '0', fontSize: '1.25em' },
385
- intro: { margin: '0', opacity: 0.72, lineHeight: 1.55, fontSize: '0.92em' },
386
- bar: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' },
387
- btn: { padding: '6px 12px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'transparent', color: 'inherit', cursor: 'pointer', font: 'inherit', fontSize: '0.88em' },
388
- input: { padding: '6px 10px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'var(--dsw-alias-bg-base, transparent)', color: 'inherit', font: 'inherit', fontSize: '0.88em' },
389
- search: { flex: '1 1 180px', minWidth: '140px' },
390
- count: { fontSize: '0.85em', opacity: 0.7, marginLeft: 'auto' },
391
- list: { display: 'flex', flexDirection: 'column', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', borderRadius: '10px', overflow: 'hidden' },
392
- row: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderTop: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.15))' },
393
- rowFirst: { borderTop: 'none' },
394
- rowOff: { opacity: 0.5 },
395
- name: { flex: '1 1 auto', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '2px' },
396
- nameText: { fontSize: '0.92em', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
397
- id: { fontSize: '0.76em', opacity: 0.55, fontFamily: 'ui-monospace, monospace' },
398
- tag: { fontSize: '0.72em', padding: '1px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', opacity: 0.75 },
399
- price: { fontSize: '0.9em', opacity: 0.7, fontWeight: 400 },
400
- select: { padding: '5px 8px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'var(--dsw-alias-bg-base, transparent)', color: 'inherit', font: 'inherit', fontSize: '0.85em', minWidth: '104px' },
401
- switch: { width: '17px', height: '17px', cursor: 'pointer', accentColor: 'var(--dsw-alias-brand-primary, #4c6ef5)' },
402
- note: { fontSize: '0.82em', opacity: 0.62, lineHeight: 1.5 },
403
- err: { fontSize: '0.86em', color: 'var(--dsw-alias-label-danger, #e03131)' },
404
- guide: { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap', padding: '12px 14px', borderRadius: '10px', border: '1px solid var(--dsw-alias-label-danger, #e03131)', background: 'rgba(224,49,49,0.07)' },
405
- guideText: { flex: '1 1 240px', fontSize: '0.88em', lineHeight: 1.5, color: 'var(--dsw-alias-label-danger, #e03131)' },
406
- btnAlert: { border: '1px solid var(--dsw-alias-label-danger, #e03131)', color: 'var(--dsw-alias-label-danger, #e03131)' },
407
- group: { display: 'flex', flexDirection: 'column', gap: '10px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', borderRadius: '10px', padding: '14px 16px' },
408
- advLabel: { fontSize: '0.88em' },
409
- h3: { margin: 0, fontSize: '0.95em' },
410
- log: { margin: '0', maxHeight: '240px', overflowY: 'auto', padding: '8px 10px', borderRadius: '8px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', background: 'var(--dsw-alias-bg-base, rgba(128,128,128,0.05))', fontFamily: 'ui-monospace, monospace', fontSize: '0.76em', lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
411
- usageCard: { display: 'flex', flexDirection: 'column', gap: '10px', padding: '14px 16px', borderRadius: '10px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', background: 'var(--dsw-alias-bg-base, rgba(128,128,128,0.03))' },
412
- usageHead: { display: 'flex', alignItems: 'baseline', gap: '10px', flexWrap: 'wrap' },
413
- usagePct: { marginLeft: 'auto', fontSize: '0.9em', fontWeight: 600 },
414
- progressOuter: { height: '8px', borderRadius: '999px', background: 'var(--dsw-alias-border-l2, rgba(128,128,128,0.22))', overflow: 'hidden' },
415
- progressInner: { height: '100%', borderRadius: '999px', background: 'var(--dsw-alias-brand-primary, #4c6ef5)', transition: 'width .25s ease' },
416
- progressDanger: { background: 'var(--dsw-alias-label-danger, #e03131)' },
417
- usageLine: { display: 'flex', alignItems: 'baseline', gap: '8px', flexWrap: 'wrap', fontSize: '0.86em' },
418
- usageLabel: { opacity: 0.62, minWidth: '72px' },
419
- usageValue: { fontWeight: 500 },
420
- link: { color: 'var(--dsw-alias-brand-primary, #4c6ef5)', textDecoration: 'none', fontSize: '0.86em' },
421
- usageFoot: { display: 'flex', alignItems: 'center', gap: '14px', flexWrap: 'wrap', fontSize: '0.8em', opacity: 0.6 },
422
- optionRow: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 0', borderTop: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.15))' },
423
- optionFirst: { borderTop: 'none', paddingTop: 0 },
424
- optionText: { flex: '1 1 auto', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '2px' },
425
- optionName: { fontSize: '0.92em', fontWeight: 500 },
426
- optionStatus: { fontSize: '0.82em', opacity: 0.62 },
427
- }
428
-
429
- /**
430
- * Same-origin API base, resolved against the document so a deployment under
431
- * a sub-path still reaches its own host.
432
- */
433
- const API = (() => {
434
- try { return new URL('api/llm-qoder-cn', document.baseURI).pathname } catch { return '/api/llm-qoder-cn' }
435
- })()
436
-
437
- /**
438
- * Last successful answer per edition, so reopening a settings page paints
439
- * the previous content immediately and refreshes behind it.
440
- *
441
- * The cache is deliberately stale-while-revalidate: the page never waits on
442
- * the CLI just to show something it showed a minute ago. Both the model list
443
- * and the quota reading are cached separately because they are fetched by
444
- * different cards. `localStorage` keeps the snapshot across a page reload;
445
- * the in-memory map covers a deployment where storage is unavailable.
446
- */
447
- const CACHE_PREFIX = 'dsh-agent-sdk-bridge/cache/v1'
448
- const cacheMemory = new Map()
449
-
450
- function cacheKey(brand, kind) {
451
- return `${CACHE_PREFIX}:${brand}:${kind}`
452
- }
453
-
454
- function readCache(brand, kind) {
455
- const key = cacheKey(brand, kind)
456
- const held = cacheMemory.get(key)
457
- if (held !== undefined) return held
458
- try {
459
- const raw = window.localStorage.getItem(key)
460
- if (raw === null) return undefined
461
- const parsed = JSON.parse(raw)
462
- cacheMemory.set(key, parsed)
463
- return parsed
464
- } catch {
465
- return undefined
466
- }
467
- }
468
-
469
- function writeCache(brand, kind, value) {
470
- const key = cacheKey(brand, kind)
471
- cacheMemory.set(key, value)
472
- try {
473
- window.localStorage.setItem(key, JSON.stringify(value))
474
- } catch {
475
- /* private mode or a full quota: the in-memory copy still works */
476
- }
477
- }
478
-
479
- /** Call the plugin's model API. */
480
- async function api(path, options) {
481
- const { timeout = 30_000, ...rest } = options ?? {}
482
- const ctrl = new AbortController()
483
- const timer = setTimeout(() => ctrl.abort(), timeout)
484
- try {
485
- const response = await fetch(`${API}${path}`, { ...rest, signal: ctrl.signal })
486
- const text = await response.text()
487
- let payload
488
- try { payload = text === '' ? {} : JSON.parse(text) } catch { payload = { error: text.slice(0, 200) } }
489
- if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`)
490
- return payload
491
- } finally {
492
- clearTimeout(timer)
493
- }
494
- }
495
-
496
- /**
497
- * How long a settings write may take before the page gives up on it.
498
- *
499
- * A config write is a round trip to the host, which commits the value into
500
- * the running plugin before it answers, so this is not a normal-path limit —
501
- * it is a floor under the UI. Without it a wire call that never settles
502
- * leaves every control disabled forever, which is exactly how this page was
503
- * previously reported as frozen.
504
- */
505
- const WRITE_TIMEOUT_MS = 20_000
506
-
507
- /** Settle with `promise`, or reject with `message` once `ms` elapse. */
508
- function withDeadline(promise, ms, message) {
509
- return new Promise((resolve, reject) => {
510
- const timer = setTimeout(() => reject(new Error(message)), ms)
511
- promise.then(
512
- value => { clearTimeout(timer); resolve(value) },
513
- error => { clearTimeout(timer); reject(error) },
514
- )
515
- })
516
- }
517
-
518
- /** Compact label for a token count. */
519
- function windowLabel(n) {
520
- if (typeof n !== 'number' || !Number.isFinite(n)) return '—'
521
- if (n >= 1_000_000) return `${Number((n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1))}M`
522
- if (n >= 1000) return `${Math.round(n / 1000)}K`
523
- return String(n)
524
- }
525
-
526
- /**
527
- * The credit multiplier upstream quotes, as a short suffix.
528
- *
529
- * `0` renders as 免费 rather than `x0`, matching how the Qoder client shows
530
- * a free model. A model upstream quoted no multiplier for gets no suffix at
531
- * all — inventing one would misstate its cost.
532
- */
533
- function priceSuffix(t, factor) {
534
- if (typeof factor !== 'number' || !Number.isFinite(factor) || factor < 0) return ''
535
- if (factor === 0) return t('free')
536
- return `x${Number(factor.toFixed(4))}`
537
- }
538
-
539
- /** A 0–100 percentage, clamped, or undefined when the value is not a number. */
540
- function percentOf(value) {
541
- if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
542
- return Math.max(0, Math.min(100, value))
543
- }
544
-
545
- /** A credit count with group separators; dashes for absent values. */
546
- function creditsOf(value) {
547
- if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
548
- return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
549
- }
550
-
551
- /**
552
- * Whether a timestamp means "no expiry".
553
- *
554
- * The quota endpoint reports plan end dates as a sentinel far in the future
555
- * (year 9999). Rendering that as a date is technically true and practically
556
- * noise, so it is shown as "never".
557
- */
558
- function neverExpires(ms) {
559
- return typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0 || ms > Date.now() + 50 * 365 * 24 * 3600 * 1000
560
- }
561
-
562
- /** A short local date for an epoch-millisecond value. */
563
- function dateLabel(ms) {
564
- try { return new Date(ms).toLocaleDateString('zh-CN') } catch { return String(ms) }
565
- }
566
-
567
- /**
568
- * One quota bucket as a line: label, `remaining / total`, percentage.
569
- *
570
- * Both editions quote the same shape (`userQuota`, `addOnQuota`,
571
- * `orgResourcePackage`), so the three render through one function; a bucket
572
- * the account does not have is simply not passed in.
573
- */
574
- function QuotaLine({ t, label, bucket, fallbackUnit }) {
575
- if (bucket === undefined || bucket === null) return null
576
- const total = bucket.total ?? bucket.cap
577
- const remaining = bucket.remaining
578
- const used = bucket.used
579
- // A plan bucket the account does not have is reported as all zeros; an
580
- // empty line describes nothing, so it is omitted rather than rendered.
581
- if ((total === undefined || total === 0) && remaining === undefined) return null
582
- const pct = percentOf(bucket.percentage)
583
- const unit = bucket.unit ?? fallbackUnit ?? t('usageCredits')
584
- const amount = remaining !== undefined && total !== undefined
585
- ? `${t('usageRemaining')} ${creditsOf(remaining)} ${t('usageOf')} ${creditsOf(total)} ${unit}`
586
- : total !== undefined
587
- ? `${t('usageUsed')} ${creditsOf(used)} ${t('usageOf')} ${creditsOf(total)} ${unit}`
588
- : '—'
589
- return h('div', { style: css.usageLine },
590
- h('span', { style: css.usageLabel }, label),
591
- h('span', { style: css.usageValue }, amount),
592
- pct === undefined ? null : h('span', { style: { opacity: 0.55 } }, `${Number(pct.toFixed(1))}%`),
593
- )
594
- }
595
-
596
- /**
597
- * Account quota and usage, read through the CLI.
598
- *
599
- * This is the same data the Qoder clients show on their account panel: plan,
600
- * percentage used, remaining credits, add-on package, expiry and the
601
- * upgrade/usage links. It is fetched from the host (which asks the CLI), not
602
- * from the provider directly, because only the CLI holds a usable token.
603
- */
604
- function UsageCard({ t, brand, refreshSignal }) {
605
- const [snapshot, setSnapshot] = useState(() => readCache(brand.id, 'usage'))
606
- const [failure, setFailure] = useState(undefined)
607
- const [busy, setBusy] = useState(false)
608
- const ticket = useRef(0)
609
-
610
- const load = useCallback(async (fresh = false) => {
611
- const mine = ++ticket.current
612
- setBusy(true)
613
- setFailure(undefined)
614
- try {
615
- const payload = await api(`/usage?brand=${brand.id}${fresh ? '&fresh=1' : ''}`, { timeout: 45_000 })
616
- if (mine !== ticket.current) return
617
- // A failed account lookup (signed out, endpoint down) must not replace
618
- // the last good reading with an empty card: keep it and say so.
619
- if (payload?.usage === undefined && payload?.error !== undefined) {
620
- setFailure(String(payload.error))
621
- return
622
- }
623
- setSnapshot(payload)
624
- writeCache(brand.id, 'usage', payload)
625
- } catch (err) {
626
- if (mine !== ticket.current) return
627
- setFailure(String(err?.message ?? err))
628
- } finally {
629
- if (mine === ticket.current) setBusy(false)
630
- }
631
- }, [brand.id])
632
-
633
- // `refreshSignal` changes after a CLI install or uninstall, both of which
634
- // make the cached account reading describe a machine state that is gone.
635
- useEffect(() => { void load() }, [load, refreshSignal])
636
-
637
- const usage = snapshot?.usage
638
- const account = snapshot?.account
639
- const error = failure ?? (snapshot?.usage === undefined && snapshot?.error !== undefined ? String(snapshot.error) : undefined)
640
- const pct = percentOf(usage?.totalUsagePercentage)
641
- const plan = account?.subscriptionType ?? usage?.userType ?? t('usageUnknownPlan')
642
- const identity = account?.name ?? account?.email ?? usage?.userId
643
- const exceeded = usage?.isQuotaExceeded === true
644
-
645
- const head = h('div', { style: css.usageHead },
646
- h('h3', { style: css.h3 }, t('usageTitle')),
647
- identity === undefined
648
- ? null
649
- : h('span', { style: { ...css.note, opacity: 0.7 } }, `${t('usageAccount')} ${identity}`),
650
- h('button', {
651
- style: { ...css.btn, marginLeft: 'auto' },
652
- disabled: busy,
653
- onClick: () => void load(true),
654
- }, busy ? t('refreshing') : t('usageRefresh')),
655
- )
656
-
657
- if (snapshot === undefined || usage === undefined) {
658
- return h('div', { style: css.usageCard },
659
- head,
660
- error === undefined
661
- ? h('div', { style: css.note }, t('usageLoading'))
662
- : h('div', { style: css.err }, `${t('usageUnavailable')}:${error}`),
663
- error === undefined
664
- ? null
665
- : h('div', { style: css.bar },
666
- h('button', { style: css.btn, disabled: busy, onClick: () => void load(true) }, t('usageRetry')),
667
- ),
668
- )
669
- }
670
-
671
- const expiry = usage?.expiresAt
672
- return h('div', { style: css.usageCard },
673
- head,
674
- h('div', { style: css.usageLine },
675
- h('span', { style: css.usageLabel }, t('usagePlan')),
676
- h('span', { style: css.usageValue }, plan),
677
- exceeded ? h('span', { style: { ...css.err, fontWeight: 600 } }, t('usageExceeded')) : null,
678
- pct === undefined ? null : h('span', { style: css.usagePct }, `${Number(pct.toFixed(1))}%`),
679
- ),
680
- pct === undefined ? null : h('div', { style: css.progressOuter },
681
- h('div', {
682
- style: { ...css.progressInner, width: `${pct}%`, ...(exceeded ? css.progressDanger : {}) },
683
- }),
684
- ),
685
- h(QuotaLine, { t, label: t('usagePlanQuota'), bucket: usage?.userQuota }),
686
- h(QuotaLine, { t, label: t('usageAddOn'), bucket: usage?.addOnQuota }),
687
- h(QuotaLine, { t, label: t('usageOrgPackage'), bucket: usage?.orgResourcePackage }),
688
- h('div', { style: css.usageFoot },
689
- expiry === undefined || neverExpires(expiry)
690
- ? h('span', null, `${t('usageExpires')} ${t('usageNever')}`)
691
- : h('span', null, `${t('usageExpires')} ${dateLabel(expiry)}`),
692
- snapshot?.at === undefined ? null : h('span', null, `${t('usageUpdated')} ${new Date(snapshot.at).toLocaleTimeString('zh-CN')}`),
693
- typeof usage?.addOnQuota?.detailUrl === 'string'
694
- ? h('a', { href: usage.addOnQuota.detailUrl, target: '_blank', rel: 'noreferrer', style: css.link }, t('usageDetail'))
695
- : null,
696
- typeof usage?.upgradeUrl === 'string' && usage.upgradeUrl !== ''
697
- ? h('a', { href: usage.upgradeUrl, target: '_blank', rel: 'noreferrer', style: css.link }, t('usageUpgrade'))
698
- : null,
699
- failure === undefined
700
- ? null
701
- : h('span', { style: css.err }, `${t('usageStale')}:${failure}`),
702
- ),
703
- )
704
- }
705
-
706
- /**
707
- * CodeBuddy's account card: region choice, browser login/logout and the
708
- * signed-in account.
709
- *
710
- * The region is a config write (the host starts the CLI with it), but the
711
- * card does not wait for it: the target region's snapshot paints first and
712
- * the live account read follows. Both regions keep their own saved login,
713
- * so switching back does not open the browser again.
714
- */
715
- function codeBuddySnapshot(region) {
716
- const cached = readCache('codebuddy', `snapshot:${region}`)
717
- return cached !== null && typeof cached === 'object' ? cached : undefined
718
- }
719
-
720
- function rememberCodeBuddy(region, patch) {
721
- const previous = codeBuddySnapshot(region) ?? {}
722
- writeCache('codebuddy', `snapshot:${region}`, { ...previous, ...patch, at: Date.now() })
723
- }
724
-
725
- function CodeBuddyCard({ t, ctx, brand, refreshSignal, onSignedIn, onAuthChange, onRegionChange }) {
726
- const form = ctx.configForms.get(NS)
727
- const subscribe = useCallback(listener => form.subscribe(listener), [form])
728
- const read = useCallback(() => form.getSnapshot(), [form])
729
- const snapshot = useSyncExternalStore(subscribe, read)
730
- const value = snapshot?.value ?? {}
731
- const configuredRegion = value.codebuddyRegion === 'cn' ? 'cn' : 'global'
732
- const [region, setRegionState] = useState(configuredRegion)
733
- const regionRef = useRef(configuredRegion)
734
- const initial = codeBuddySnapshot(configuredRegion)
735
- const [auth, setAuth] = useState(initial?.auth)
736
- const [account, setAccount] = useState(initial?.account)
737
- const [error, setError] = useState(undefined)
738
- const [busy, setBusy] = useState(false)
739
- const lastRunning = useRef(false)
740
- const signingIn = auth?.running === true
741
- const accountFields = account?.account ?? {}
742
- const accountSignedIn = account?.error === undefined
743
- && ['uid', 'userName', 'email', 'organization', 'subscriptionType']
744
- .some(key => typeof accountFields[key] === 'string' && accountFields[key] !== '')
745
- // The host's status is authoritative once it has answered; the account
746
- // reading only covers the first paint before that answer arrives.
747
- const signedIn = auth === undefined ? accountSignedIn : auth.signedIn === true
748
- const resolved = auth !== undefined || account !== undefined
749
-
750
- const applySnapshot = useCallback(target => {
751
- const cached = codeBuddySnapshot(target)
752
- setAuth(cached?.auth)
753
- setAccount(cached?.account)
754
- }, [])
755
-
756
- const loadAccount = useCallback(async (fresh = false, target = regionRef.current) => {
757
- try {
758
- const payload = await api(`/usage?brand=codebuddy&region=${target}${fresh ? '&fresh=1' : ''}`, { timeout: 45_000 })
759
- if (regionRef.current !== target) return
760
- setAccount(payload)
761
- rememberCodeBuddy(target, { account: payload })
762
- // A quota 401 clears the server's credential; mirror that here so the
763
- // button flips back to 登录 without waiting for a page reload.
764
- if (typeof payload?.signedIn === 'boolean') {
765
- const next = { running: false, region: target, signedIn: payload.signedIn }
766
- setAuth(previous => (previous?.running === true ? previous : next))
767
- rememberCodeBuddy(target, { auth: next })
768
- }
769
- } catch (err) {
770
- if (regionRef.current !== target) return
771
- setAccount({ error: String(err?.message ?? err) })
772
- }
773
- }, [])
774
-
775
- const poll = useCallback(async (target = regionRef.current) => {
776
- try {
777
- const next = await api(`/auth?brand=codebuddy&region=${target}`, { timeout: 10_000 })
778
- if (regionRef.current !== target) return
779
- setAuth(next)
780
- rememberCodeBuddy(target, { auth: next })
781
- if (lastRunning.current && next.running === false) {
782
- lastRunning.current = false
783
- if (next.error === undefined) await loadAccount(true, target)
784
- }
785
- if (next.running === true) lastRunning.current = true
786
- } catch (err) {
787
- if (regionRef.current !== target) return
788
- setError(String(err?.message ?? err))
789
- }
790
- }, [loadAccount])
791
-
792
- // Paint the target region from its snapshot, then verify in the background.
793
- useEffect(() => {
794
- regionRef.current = region
795
- applySnapshot(region)
796
- setError(undefined)
797
- void poll(region)
798
- void loadAccount(false, region)
799
- const timer = setTimeout(() => { void loadAccount(true, region) }, 250)
800
- return () => clearTimeout(timer)
801
- }, [region, refreshSignal, applySnapshot, loadAccount, poll])
802
-
803
- // A config edit from elsewhere (or a reload) becomes the new selection.
804
- useEffect(() => {
805
- if (configuredRegion === regionRef.current) return
806
- setRegionState(configuredRegion)
807
- regionRef.current = configuredRegion
808
- applySnapshot(configuredRegion)
809
- }, [configuredRegion, applySnapshot])
810
-
811
- useEffect(() => {
812
- if (auth?.running !== true) return undefined
813
- const timer = setInterval(() => { void poll(region) }, 1500)
814
- return () => clearInterval(timer)
815
- }, [auth?.running, poll, region])
816
-
817
- useEffect(() => { if (resolved) onAuthChange?.(signedIn) }, [resolved, signedIn, onAuthChange])
818
-
819
- const setRegion = useCallback(next => {
820
- if (next === regionRef.current) return
821
- // Local paint first; the config write is only needed by the adapter.
822
- regionRef.current = next
823
- lastRunning.current = false
824
- setRegionState(next)
825
- applySnapshot(next)
826
- setError(undefined)
827
- onRegionChange?.(next)
828
- void (async () => {
829
- try {
830
- const accepted = await withDeadline(form.set('codebuddyRegion', next), WRITE_TIMEOUT_MS, t('timeout'))
831
- if (accepted === false) throw new Error(t('saveFailed'))
832
- if (regionRef.current === next) onSignedIn?.()
833
- } catch (err) {
834
- if (regionRef.current !== next) return
835
- setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
836
- const fallback = form.getSnapshot()?.value?.codebuddyRegion === 'cn' ? 'cn' : 'global'
837
- regionRef.current = fallback
838
- setRegionState(fallback)
839
- applySnapshot(fallback)
840
- onRegionChange?.(fallback)
841
- }
842
- })()
843
- }, [applySnapshot, form, onRegionChange, onSignedIn, t])
844
-
845
- const startLogin = useCallback(async () => {
846
- const target = regionRef.current
847
- setBusy(true)
848
- setError(undefined)
849
- try {
850
- const next = await api('/auth', {
851
- method: 'POST',
852
- headers: { 'content-type': 'application/json' },
853
- body: JSON.stringify({ brand: 'codebuddy', region: target, action: 'login' }),
854
- timeout: 20_000,
855
- })
856
- if (regionRef.current !== target) return
857
- setAuth(next)
858
- rememberCodeBuddy(target, { auth: next })
859
- if (next.running === true) lastRunning.current = true
860
- } catch (err) {
861
- if (regionRef.current !== target) return
862
- setError(`${t('codebuddyLoginFailed')}:${String(err?.message ?? err)}`)
863
- } finally {
864
- setBusy(false)
865
- }
866
- }, [t])
867
-
868
- const logout = useCallback(async () => {
869
- if (typeof window.confirm === 'function' && !window.confirm(t('codebuddyConfirmLogout'))) return
870
- const target = regionRef.current
871
- setBusy(true)
872
- setError(undefined)
873
- try {
874
- const next = await api('/auth', {
875
- method: 'POST',
876
- headers: { 'content-type': 'application/json' },
877
- body: JSON.stringify({ brand: 'codebuddy', region: target, action: 'logout' }),
878
- timeout: 20_000,
879
- })
880
- if (regionRef.current !== target) return
881
- setAuth(next)
882
- setAccount(undefined)
883
- rememberCodeBuddy(target, { auth: next, account: undefined })
884
- onAuthChange?.(false)
885
- await loadAccount(true, target)
886
- } catch (err) {
887
- if (regionRef.current !== target) return
888
- // The host clears its local credential even when the CLI refuses the
889
- // logout, so the card must not keep presenting the account.
890
- const signedOut = { running: false, region: target, signedIn: false }
891
- setAuth(signedOut)
892
- setAccount(undefined)
893
- rememberCodeBuddy(target, { auth: signedOut, account: undefined })
894
- onAuthChange?.(false)
895
- setError(String(err?.message ?? err))
896
- } finally {
897
- setBusy(false)
898
- }
899
- }, [loadAccount, onAuthChange, t])
900
-
901
- const accountText = account?.account === undefined
902
- ? (account?.error ?? t('codebuddyAccountUnknown'))
903
- : [account.account.email, account.account.organization, account.account.subscriptionType]
904
- .filter(part => typeof part === 'string' && part.length > 0)
905
- .join(' · ')
906
- const quota = account?.quota
907
- const quotaPct = quota !== undefined && quota.total > 0
908
- ? Math.max(0, Math.min(100, (quota.used / quota.total) * 100))
909
- : undefined
910
- const packages = Array.isArray(quota?.packages)
911
- ? [...quota.packages].sort((a, b) => (a.end ?? Number.MAX_SAFE_INTEGER) - (b.end ?? Number.MAX_SAFE_INTEGER)).slice(0, 4)
912
- : []
913
- // The website's own usage page, under the profile the CLI login belongs
914
- // to. Both regions serve it at the same path.
915
- const usageLink = h('a', {
916
- href: region === 'cn'
917
- ? 'https://copilot.tencent.com/profile/plans-usage'
918
- : 'https://www.codebuddy.ai/profile/plans-usage',
919
- target: '_blank',
920
- rel: 'noreferrer',
921
- style: css.link,
922
- }, t('usageDetail'))
923
-
924
- return h('div', { style: css.usageCard },
925
- h('div', { style: css.usageHead },
926
- h('h3', { style: css.h3 }, t('codebuddyAuthTitle')),
927
- h('span', { style: { ...css.note, opacity: 0.7 } }, signedIn ? t('codebuddySignedIn') : t('codebuddyNotLoggedIn')),
928
- signedIn
929
- ? h('button', { style: { ...css.btn, marginLeft: 'auto' }, disabled: busy, onClick: () => void loadAccount(true) }, t('usageRefresh'))
930
- : null,
931
- ),
932
- h('div', { style: css.note }, t('codebuddyAuthHint')),
933
- h('div', { style: css.usageLine },
934
- h('span', { style: css.usageLabel }, t('codebuddyRegionLabel')),
935
- h('select', {
936
- style: css.select,
937
- value: region,
938
- disabled: busy,
939
- onChange: event => { setRegion(event.target.value) },
940
- },
941
- h('option', { key: 'global', value: 'global' }, t('codebuddyRegionGlobal')),
942
- h('option', { key: 'cn', value: 'cn' }, t('codebuddyRegionCn')),
943
- ),
944
- h('button', {
945
- style: signedIn ? { ...css.btn, ...css.btnAlert } : css.btn,
946
- disabled: busy || signingIn,
947
- onClick: () => { if (signedIn) void logout(); else void startLogin() },
948
- }, signingIn ? t('codebuddyLoggingIn') : signedIn ? t('codebuddyLogout') : t('codebuddyLogin')),
949
- ),
950
- signedIn
951
- ? h('div', { style: css.usageLine },
952
- h('span', { style: css.usageLabel }, t('usageAccount')),
953
- h('span', { style: css.usageValue }, accountText),
954
- )
955
- : h('div', { style: css.note }, t('codebuddyLoginPrompt')),
956
- signedIn
957
- ? (quota === undefined
958
- ? (account?.quotaError !== undefined
959
- ? h('div', { style: css.err }, `${t('codebuddyQuotaFailed')}:${account.quotaError}`)
960
- : h('div', { style: css.note }, t('codebuddyNoQuota')))
961
- : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
962
- h('div', { style: css.usageLine },
963
- h('span', { style: css.usageLabel }, t('codebuddyQuotaTitle')),
964
- h('span', { style: css.usageValue },
965
- `${t('usageRemaining')} ${creditsOf(quota.remaining)} ${t('usageOf')} ${creditsOf(quota.total)} ${t('usageCredits')}`),
966
- quotaPct === undefined ? null : h('span', { style: css.usagePct }, `${quotaPct.toFixed(1)}%`),
967
- ),
968
- quotaPct === undefined ? null : h('div', { style: css.progressOuter },
969
- h('div', { style: { ...css.progressInner, width: `${quotaPct}%` } }),
970
- ),
971
- packages.length === 0 ? null : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
972
- h('div', { style: css.note }, t('codebuddyQuotaPackages')),
973
- packages.map((pkg, index) => h('div', { key: `${pkg.name}-${index}`, style: css.usageLine },
974
- h('span', { style: { ...css.usageLabel, minWidth: '160px' } }, pkg.name || '—'),
975
- h('span', null, `${creditsOf(pkg.used)} / ${creditsOf(pkg.total)}`),
976
- pkg.end === undefined ? null : h('span', { style: { opacity: 0.55 } }, dateLabel(pkg.end)),
977
- )),
978
- ),
979
- h('div', { style: css.usageFoot },
980
- quota.cycleEnd === undefined ? null : h('span', null, `${t('codebuddyQuotaExpires')} ${dateLabel(quota.cycleEnd)}`),
981
- usageLink,
982
- ),
983
- ))
984
- : null,
985
- signedIn && quota === undefined
986
- ? h('div', { style: css.usageFoot }, usageLink)
987
- : null,
988
- typeof auth?.url === 'string' && signingIn
989
- ? h('div', { style: css.usageLine },
990
- h('a', { href: auth.url, target: '_blank', rel: 'noreferrer', style: css.link }, t('codebuddyOpenUrl')),
991
- h('span', { style: css.note }, t('codebuddyLoginStarted')),
992
- )
993
- : null,
994
- auth?.error !== undefined ? h('div', { style: css.err }, `${t('codebuddyLoginFailed')}:${auth.error}`) : null,
995
- error !== undefined ? h('div', { style: css.err }, error) : null,
996
- )
997
- }
998
-
999
- /**
1000
- * The model table plus the advanced block.
1001
- *
1002
- * Each change posts and then adopts the host's returned list, so the page
1003
- * shows what the adapter will actually do rather than what the click hoped.
1004
- * A per-request ticket keeps a slow earlier answer from overwriting a newer
1005
- * one when the user clicks quickly.
1006
- */
1007
- function SettingsPage({ ctx, t, brand }) {
1008
- const form = ctx.configForms.get(NS)
1009
- const initialRegion = form.getSnapshot()?.value?.codebuddyRegion === 'cn' ? 'cn' : 'global'
1010
- // Each CodeBuddy region has its own catalog, deny-list and windows; the
1011
- // page key follows the region so switching shows that region's choices.
1012
- const [region, setRegion] = useState(initialRegion)
1013
- const modelsKind = brand.id === 'codebuddy' ? `models:${region}` : 'models'
1014
- const cached = readCache(brand.id, modelsKind)
1015
- const [models, setModels] = useState(() => Array.isArray(cached?.rows) ? cached.rows : undefined)
1016
- const [catalogNotice, setCatalogNotice] = useState(() =>
1017
- typeof cached?.notice === 'string' ? cached.notice : undefined)
1018
- const [signedIn, setSignedIn] = useState(() =>
1019
- brand.id === 'codebuddy'
1020
- ? cached?.signedIn === true || codeBuddySnapshot(initialRegion)?.auth?.signedIn === true
1021
- : undefined)
1022
- const [error, setError] = useState(undefined)
1023
- const [status, setStatus] = useState(undefined)
1024
- const [busy, setBusy] = useState(false)
1025
- const [query, setQuery] = useState('')
1026
- const [onlyEnabled, setOnlyEnabled] = useState(false)
1027
- const [showAdvanced, setShowAdvanced] = useState(false)
1028
- const [usageTick, setUsageTick] = useState(0)
1029
- const ticket = useRef(0)
1030
- /** Separate from `ticket`: `load()` bumps that one, so sharing it would
1031
- * make every write look stale the moment its own refresh landed. */
1032
- const writeTicket = useRef(0)
1033
-
1034
- const subscribe = useCallback(listener => form.subscribe(listener), [form])
1035
- const read = useCallback(() => form.getSnapshot(), [form])
1036
- const snapshot = useSyncExternalStore(subscribe, read)
1037
-
1038
- const configuredRegion = snapshot?.value?.codebuddyRegion === 'cn' ? 'cn' : 'global'
1039
- /**
1040
- * The region the user just picked, until the config write lands.
1041
- *
1042
- * Without this, a snapshot that still carries the old value would pull
1043
- * the selection back mid-switch.
1044
- */
1045
- const pendingRegion = useRef(null)
1046
- useEffect(() => {
1047
- if (brand.id !== 'codebuddy') return
1048
- if (pendingRegion.current !== null) {
1049
- if (pendingRegion.current === configuredRegion) pendingRegion.current = null
1050
- return
1051
- }
1052
- setRegion(current => (current === configuredRegion ? current : configuredRegion))
1053
- }, [brand.id, configuredRegion, region])
1054
-
1055
- const selectRegion = useCallback(next => {
1056
- pendingRegion.current = next
1057
- setRegion(next)
1058
- }, [])
1059
-
1060
- const fields = brand.id === 'codebuddy'
1061
- ? {
1062
- disabled: region === 'cn' ? 'codebuddyCnDisabledModels' : 'codebuddyGlobalDisabledModels',
1063
- windows: region === 'cn' ? 'codebuddyCnModelContextWindows' : 'codebuddyGlobalModelContextWindows',
1064
- }
1065
- : brand.fields
1066
-
1067
- const describeFace = ctx.configForms.describe()
1068
- const describeSubscribe = useCallback(listener => describeFace.subscribe(listener), [describeFace])
1069
- const describeRead = useCallback(() => describeFace.getSnapshot(), [describeFace])
1070
- const describeSnapshot = useSyncExternalStore(describeSubscribe, describeRead)
1071
- useEffect(() => { describeFace.ensure().catch(() => undefined) }, [describeFace])
1072
-
1073
- const fetchModels = useCallback(async (fresh = false) => {
1074
- const regionQuery = brand.id === 'codebuddy' ? `&region=${region}` : ''
1075
- const payload = await api(`/models?brand=${brand.id}${regionQuery}${fresh ? '&fresh=1' : ''}`)
1076
- // Never adopt a table the host answered for another login region.
1077
- if (brand.id === 'codebuddy' && typeof payload?.region === 'string' && payload.region !== region) {
1078
- throw new Error(t('codebuddyRegionMismatch'))
1079
- }
1080
- return {
1081
- rows: Array.isArray(payload?.models) ? payload.models : [],
1082
- notice: typeof payload?.notice === 'string' ? payload.notice : undefined,
1083
- signedIn: brand.id === 'codebuddy' ? payload?.signedIn === true : undefined,
1084
- }
1085
- }, [brand.id, region, t])
1086
-
1087
- /** Adopt one read and remember it for the next visit to this region. */
1088
- const adopt = useCallback((rows, notice, nextSignedIn) => {
1089
- setModels(rows)
1090
- setCatalogNotice(notice)
1091
- setSignedIn(nextSignedIn)
1092
- writeCache(brand.id, modelsKind, { rows, notice, signedIn: nextSignedIn, at: Date.now() })
1093
- }, [brand.id, modelsKind])
1094
-
1095
- /** Read the list. `fresh` asks the host to drop its catalog cache first. */
1096
- const load = useCallback(async (fresh = false) => {
1097
- const requestedKind = modelsKind
1098
- setError(undefined)
1099
- const mine = ++ticket.current
1100
- try {
1101
- const { rows, notice, signedIn: nextSignedIn } = await fetchModels(fresh)
1102
- if (mine !== ticket.current || kindRef.current !== requestedKind) return
1103
- adopt(rows, notice, nextSignedIn)
1104
- } catch (err) {
1105
- if (mine !== ticket.current || kindRef.current !== requestedKind) return
1106
- setError(String(err?.message ?? err))
1107
- setModels(previous => previous ?? [])
1108
- }
1109
- }, [adopt, fetchModels, modelsKind])
1110
-
1111
- /** Latest values for callbacks the account card holds across renders. */
1112
- const loadRef = useRef(load)
1113
- loadRef.current = load
1114
- const kindRef = useRef(modelsKind)
1115
- kindRef.current = modelsKind
1116
- /** The region of the last model read; a change forces a fresh read. */
1117
- const lastLoaded = useRef(undefined)
1118
- const refresh = useCallback(() => { void loadRef.current() }, [])
1119
-
1120
- /**
1121
- * On a region switch, paint that region's remembered table first and
1122
- * then verify it with the host. The read carries the region explicitly,
1123
- * so it stays correct even before the config write commits.
1124
- */
1125
- useEffect(() => {
1126
- if (brand.id === 'codebuddy') {
1127
- const saved = readCache(brand.id, modelsKind)
1128
- setModels(Array.isArray(saved?.rows) ? saved.rows : undefined)
1129
- setCatalogNotice(typeof saved?.notice === 'string' ? saved.notice : undefined)
1130
- // The account snapshot already knows whether this region is signed
1131
- // in, so the locked view does not flash while the catalog boots.
1132
- setSignedIn(saved?.signedIn === true || codeBuddySnapshot(region)?.auth?.signedIn === true)
1133
- setError(undefined)
1134
- }
1135
- // A switch must not be served from the host's cached catalog: the CLI
1136
- // only settles into the new login environment on a fresh read.
1137
- const switched = brand.id === 'codebuddy'
1138
- && lastLoaded.current !== undefined
1139
- && lastLoaded.current !== region
1140
- lastLoaded.current = region
1141
- void load(switched)
1142
- }, [brand.id, modelsKind, region, load])
1143
-
1144
- /** Login/logout flips which catalog the page is allowed to show. */
1145
- const handleAuthChange = useCallback(next => {
1146
- if (brand.id !== 'codebuddy') return
1147
- setSignedIn(next === true)
1148
- if (next === true) {
1149
- refresh()
1150
- return
1151
- }
1152
- setModels([])
1153
- setCatalogNotice(undefined)
1154
- writeCache(brand.id, kindRef.current, { rows: [], notice: undefined, signedIn: false, at: Date.now() })
1155
- }, [brand.id, refresh])
1156
-
1157
- /**
1158
- * Re-read until the list reflects what was just written, or give up.
1159
- *
1160
- * The host commits a volatile config edit into the running plugin before
1161
- * it answers the write, so the first read after `set()` normally already
1162
- * shows the change and this returns immediately. The retries exist for the
1163
- * cases where it does not: a reload that briefly unpublished the route, or
1164
- * a host that answered ahead of its own commit. Spending them turns a
1165
- * transient disagreement into a short wait instead of a wrong answer.
1166
- *
1167
- * @param verify - whether the rows already show the intended change.
1168
- * @param attempts - how many reads to try before accepting what arrived.
1169
- * @returns the last rows read, or undefined when every read failed.
1170
- */
1171
- const loadUntil = useCallback(async (verify, attempts = 5) => {
1172
- let rows
1173
- const requestedKind = kindRef.current
1174
- for (let attempt = 0; attempt < attempts; attempt++) {
1175
- try {
1176
- const read = await fetchModels()
1177
- // A region switch during the save invalidates this verification.
1178
- if (kindRef.current !== requestedKind) return undefined
1179
- rows = read.rows
1180
- adopt(rows, read.notice, read.signedIn)
1181
- } catch (err) {
1182
- setError(String(err?.message ?? err))
1183
- return undefined
1184
- }
1185
- if (verify === undefined || verify(rows)) return rows
1186
- await new Promise(resolve => setTimeout(resolve, 120 + attempt * 120))
1187
- }
1188
- return rows
1189
- }, [adopt, fetchModels])
1190
-
1191
- /**
1192
- * Apply one change through the shared config form, then re-read until the
1193
- * list reflects it.
1194
- *
1195
- * The write goes through `configForms`, not the API route: that form owns
1196
- * the namespace's revision fence, so every change is ordered and a stale
1197
- * editor is refused rather than silently overwriting.
1198
- *
1199
- * `busy` is owned by the newest write alone, and is always cleared in
1200
- * `finally`. It must NOT be gated on the read generation: the read bumps
1201
- * that counter, so gating there would leave `busy` set forever and every
1202
- * control disabled.
1203
- *
1204
- * The host answers only after it has committed the value, so the re-read
1205
- * normally confirms the change on its first attempt. `verify` therefore
1206
- * acts as a real check rather than a wait: if the list still disagrees
1207
- * once the retries are spent, the change was NOT adopted and the page says
1208
- * so instead of reporting a save that did nothing.
1209
- *
1210
- * @param key - the config field to write.
1211
- * @param next - the value, or undefined to clear the field.
1212
- * @param verify - whether the re-read list already shows this change.
1213
- */
1214
- const write = useCallback(async (key, next, verify) => {
1215
- const mine = ++writeTicket.current
1216
- setBusy(true)
1217
- setStatus(t('saving'))
1218
- setError(undefined)
1219
- try {
1220
- const op = next === undefined ? form.unset(key) : form.set(key, next)
1221
- const accepted = await withDeadline(op, WRITE_TIMEOUT_MS, t('timeout'))
1222
- if (accepted === false) throw new Error(t('saveFailed'))
1223
- const rows = await loadUntil(verify)
1224
- if (rows !== undefined && verify !== undefined && !verify(rows)) throw new Error(t('notApplied'))
1225
- if (mine === writeTicket.current) setStatus(t('saved'))
1226
- } catch (err) {
1227
- if (mine !== writeTicket.current) return
1228
- setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
1229
- setStatus(undefined)
1230
- // The rows now hold an optimistic guess; re-read so the page shows what
1231
- // the host actually stored rather than what the click hoped for.
1232
- await load()
1233
- } finally {
1234
- if (mine === writeTicket.current) setBusy(false)
1235
- }
1236
- }, [form, load, loadUntil, t])
1237
-
1238
- /**
1239
- * Write the whole disabled-model list, derived from the rows the user
1240
- * just changed, so rapid toggles cannot lose each other's edits.
1241
- *
1242
- * The row is updated locally first: the host commits the value before it
1243
- * answers, so the re-read confirms this instead of correcting it, and the
1244
- * switch never appears to snap back to where it was.
1245
- */
1246
- const writeDisabled = useCallback((rows, id, enabled) => {
1247
- const next = new Set(rows.filter(m => !m.enabled).map(m => m.id))
1248
- if (enabled) next.delete(id)
1249
- else next.add(id)
1250
- setModels(current => current?.map(m => m.id === id ? { ...m, enabled } : m))
1251
- return write(fields.disabled, [...next], list => list.some(m => m.id === id && m.enabled === enabled))
1252
- }, [fields.disabled, write])
1253
-
1254
- /** Write the whole per-model window map, again showing the choice at once. */
1255
- const writeWindow = useCallback((rows, id, window) => {
1256
- const next = {}
1257
- for (const m of rows) if (m.override !== undefined) next[m.id] = m.override
1258
- if (window === undefined) delete next[id]
1259
- else next[id] = window
1260
- setModels(current => current?.map(m => m.id === id
1261
- ? { ...m, override: window, contextWindow: window ?? m.defaultContextWindow }
1262
- : m))
1263
- return write(
1264
- fields.windows,
1265
- next,
1266
- list => list.some(m => m.id === id
1267
- && (window === undefined ? m.override === undefined : m.override === window)),
1268
- )
1269
- }, [fields.windows, write])
1270
-
1271
- /**
1272
- * Flip every model at once.
1273
- *
1274
- * Enabling all writes an empty deny-list rather than every id, so a model
1275
- * the account publishes later still defaults to on.
1276
- */
1277
- const writeAll = useCallback((enabled) => {
1278
- const ids = (models ?? []).map(m => m.id)
1279
- setModels(current => current?.map(m => ({ ...m, enabled })))
1280
- return write(
1281
- fields.disabled,
1282
- enabled ? [] : ids,
1283
- list => list.every(m => m.enabled === enabled),
1284
- )
1285
- }, [fields.disabled, models, write])
1286
-
1287
- // ── CLI helper ────────────────────────────────────────────────────────
1288
- // The host runs the script, so the page only asks and then reads what it
1289
- // printed. `setup` stays undefined-shaped until the first answer arrives:
1290
- // a host older than this route simply never answers, and the group still
1291
- // renders with both buttons working.
1292
- const [setup, setSetup] = useState(undefined)
1293
- const [setupError, setSetupError] = useState(undefined)
1294
- const [logOpen, setLogOpen] = useState(false)
1295
- const logRef = useRef(null)
1296
-
1297
- const pollSetup = useCallback(async () => {
1298
- try {
1299
- setSetup(await api(`/setup?brand=${brand.id}`, { timeout: 10_000 }))
1300
- } catch {
1301
- /* no run to report, or a host without the route */
1302
- }
1303
- }, [brand.id])
1304
-
1305
- const startCliSetup = useCallback(async (mode) => {
1306
- setSetupError(undefined)
1307
- try {
1308
- setSetup(await api('/setup', {
1309
- method: 'POST',
1310
- headers: { 'content-type': 'application/json' },
1311
- body: JSON.stringify({ brand: brand.id, mode }),
1312
- timeout: 15_000,
1313
- }))
1314
- } catch (err) {
1315
- setSetupError(`${t('cliStartFailed')}:${String(err?.message ?? err)}`)
1316
- }
1317
- }, [brand.id, t])
1318
-
1319
- const setupRunning = setup?.running === true
1320
- const setupCode = setup !== undefined && setup.running === false ? setup.code : undefined
1321
- const setupFinishedAt = setup?.finishedAt
1322
- const setupLines = Array.isArray(setup?.lines) ? setup.lines : []
1323
-
1324
- useEffect(() => { void pollSetup() }, [pollSetup])
1325
- useEffect(() => {
1326
- if (!setupRunning) return undefined
1327
- const timer = setInterval(() => { void pollSetup() }, 1200)
1328
- return () => clearInterval(timer)
1329
- }, [setupRunning, pollSetup])
1330
-
1331
- /**
1332
- * The output panel follows the run, not the history: open while the
1333
- * script is alive, folded away one second after it ends. Pressing 查看
1334
- * 输出 brings the text back, and a finished run from before a reload is
1335
- * never re-expanded, because the panel starts closed.
1336
- */
1337
- useEffect(() => {
1338
- if (setupRunning) {
1339
- setLogOpen(true)
1340
- return undefined
1341
- }
1342
- if (setupFinishedAt === undefined) return undefined
1343
- const timer = setTimeout(() => setLogOpen(false), 1000)
1344
- return () => clearTimeout(timer)
1345
- }, [setupRunning, setupFinishedAt])
1346
-
1347
- // The catalog is read from the CLI, so a helper that just installed,
1348
- // signed into, or removed it changes what the list and quota should show —
1349
- // and the host has already dropped its cached answers for that case.
1350
- useEffect(() => {
1351
- if (setupCode !== 0) return
1352
- void load(true)
1353
- setUsageTick(value => value + 1)
1354
- }, [setupCode, setupFinishedAt, load])
1355
-
1356
- /** Ask before running the destructive CLI action. */
1357
- const uninstallCli = useCallback(() => {
1358
- if (typeof window.confirm !== 'function') return
1359
- if (!window.confirm(t('cliUninstallConfirm'))) return
1360
- void startCliSetup('uninstall')
1361
- }, [startCliSetup, t])
1362
-
1363
- useEffect(() => {
1364
- const node = logRef.current
1365
- if (node !== null) node.scrollTop = node.scrollHeight
1366
- }, [setupLines.length])
1367
-
1368
- const all = models ?? []
1369
- const enabledTotal = all.filter(m => m.enabled).length
1370
-
1371
- const shown = useMemo(() => {
1372
- const q = query.trim().toLowerCase()
1373
- return all.filter(m => {
1374
- if (onlyEnabled && !m.enabled) return false
1375
- if (q === '') return true
1376
- return String(m.name).toLowerCase().includes(q) || String(m.id).toLowerCase().includes(q)
1377
- })
1378
- }, [all, query, onlyEnabled])
1379
-
1380
- const codebuddyLocked = brand.id === 'codebuddy' && signedIn !== true
1381
- const authCard = brand.kind === 'codebuddy'
1382
- ? h(CodeBuddyCard, {
1383
- t, ctx, brand, refreshSignal: usageTick,
1384
- onSignedIn: () => { refresh(); setUsageTick(v => v + 1) },
1385
- onAuthChange: handleAuthChange,
1386
- onRegionChange: selectRegion,
1387
- })
1388
- : null
1389
-
1390
- // Signed out: do not read or show a catalog that the CLI would refuse.
1391
- if (codebuddyLocked) {
1392
- return h('div', { style: css.page },
1393
- h('h2', { style: css.h2 }, t(brand.titleKey)),
1394
- h('p', { style: css.intro }, t(brand.introKey)),
1395
- authCard,
1396
- h('div', { style: css.guide },
1397
- h('div', { style: css.guideText }, t('codebuddyModelsHint')),
1398
- ),
1399
- error !== undefined ? h('div', { style: css.err }, error) : null,
1400
- )
1401
- }
1402
-
1403
- /**
1404
- * Red guidance for "no models", with the one action that can fix it.
1405
- *
1406
- * An empty list is almost always the machine, not the account: the CLI is
1407
- * missing or signed out, so the catalog has nothing to return. Pointing at
1408
- * the helper and offering to run it beats a grey sentence nobody reads.
1409
- */
1410
- const renderGuide = () => h('div', { style: css.guide },
1411
- h('div', { style: css.guideText }, t(brand.noModelsKey)),
1412
- brand.kind === 'codebuddy'
1413
- ? null
1414
- : h('button', {
1415
- style: { ...css.btn, ...css.btnAlert },
1416
- disabled: setupRunning,
1417
- onClick: () => void startCliSetup('configure'),
1418
- }, t('cliRun')),
1419
- )
1420
-
1421
- if (models === undefined) {
1422
- return h('div', { style: css.page },
1423
- h('h2', { style: css.h2 }, t(brand.titleKey)),
1424
- // Same leading shape as the loaded page: a differing child index
1425
- // remounts the account card and makes it snap back to the region the
1426
- // config still holds while the switch is in flight.
1427
- h('p', { style: css.intro }, t(brand.introKey)),
1428
- brand.kind === 'codebuddy' ? authCard : null,
1429
- error === undefined
1430
- ? h('div', { style: css.note }, t('loading'))
1431
- : h('div', null,
1432
- h('div', { style: css.err }, `${t('loadFailed')}:${error}`),
1433
- h('button', { style: { ...css.btn, marginTop: '8px' }, onClick: () => void load(true) }, t('retry')),
1434
- h('div', { style: { marginTop: '10px' } }, renderGuide()),
1435
- ),
1436
- )
1437
- }
1438
-
1439
- const rows = shown.map((m, index) => {
1440
- const choices = Array.isArray(m.contextWindows) ? m.contextWindows : []
1441
- return h('div', {
1442
- key: m.id,
1443
- style: { ...css.row, ...(index === 0 ? css.rowFirst : {}), ...(m.enabled ? {} : css.rowOff) },
1444
- },
1445
- h('input', {
1446
- type: 'checkbox',
1447
- style: css.switch,
1448
- checked: m.enabled === true,
1449
- disabled: busy,
1450
- title: t('colEnabled'),
1451
- onChange: event => { void writeDisabled(all, m.id, event.target.checked) },
1452
- }),
1453
- h('div', { style: css.name },
1454
- h('div', { style: css.nameText },
1455
- m.name,
1456
- m.vision === true ? h('span', { key: 'v', style: { ...css.tag, marginLeft: '6px' } }, t('vision')) : null,
1457
- priceSuffix(t, m.priceFactor) !== ''
1458
- ? h('span', { key: 'p', style: css.price }, ` · ${priceSuffix(t, m.priceFactor)}`)
1459
- : null,
1460
- ),
1461
- h('div', { style: css.id }, m.id),
1462
- ),
1463
- h('select', {
1464
- style: css.select,
1465
- value: m.override === undefined ? '' : String(m.override),
1466
- disabled: busy,
1467
- title: t('windowDefaultHint'),
1468
- onChange: event => {
1469
- const value = event.target.value
1470
- void writeWindow(all, m.id, value === '' ? undefined : Number(value))
1471
- },
1472
- },
1473
- h('option', { key: 'default', value: '' }, `${t('windowDefault')} · ${windowLabel(m.defaultContextWindow)}`),
1474
- choices.map(n => h('option', { key: String(n), value: String(n) }, windowLabel(n))),
1475
- ),
1476
- )
1477
- })
1478
-
1479
- const advanced = buildAdvanced({
1480
- t, form, snapshot,
1481
- fields: ADVANCED[brand.id],
1482
- namespace: describeSnapshot.view?.namespaces?.find(n => n.ns === NS),
1483
- show: showAdvanced,
1484
- onToggle: () => setShowAdvanced(value => !value),
1485
- })
1486
-
1487
- return h('div', { style: css.page },
1488
- h('h2', { style: css.h2 }, t(brand.titleKey)),
1489
- h('p', { style: css.intro }, t(brand.introKey)),
1490
- brand.kind === 'codebuddy'
1491
- ? authCard
1492
- : h(UsageCard, { t, brand, refreshSignal: usageTick }),
1493
-
1494
- // Search row: the field grows, the checkbox sits beside it.
1495
- h('div', { style: css.bar },
1496
- h('input', {
1497
- style: { ...css.input, ...css.search },
1498
- placeholder: t('search'),
1499
- value: query,
1500
- onChange: event => setQuery(event.target.value),
1501
- }),
1502
- h('label', { style: { ...css.note, display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap' } },
1503
- h('input', { type: 'checkbox', checked: onlyEnabled, onChange: event => setOnlyEnabled(event.target.checked) }),
1504
- t('onlyEnabled'),
1505
- ),
1506
- ),
1507
-
1508
- // Action row: all four buttons on one line, count pinned to the right.
1509
- // `nowrap` keeps them together; the count takes the remaining space so
1510
- // nothing wraps to a second line.
1511
- h('div', { style: { ...css.bar, flexWrap: 'nowrap' } },
1512
- h('button', { style: css.btn, disabled: busy, onClick: () => void load(true) }, t('refresh')),
1513
- h('button', {
1514
- style: css.btn,
1515
- disabled: busy || all.every(m => m.enabled),
1516
- onClick: () => void writeAll(true),
1517
- }, t('selectAll')),
1518
- h('button', {
1519
- style: css.btn,
1520
- disabled: busy || enabledTotal === 0,
1521
- onClick: () => void writeAll(false),
1522
- }, t('selectNone')),
1523
- h('span', { style: css.count }, `${t('enabledCount')} ${enabledTotal} / ${all.length}`),
1524
- ),
1525
-
1526
- all.length === 0
1527
- ? renderGuide()
1528
- : h('div', { style: css.list }, rows.length > 0 ? rows : h('div', { style: { ...css.note, padding: '12px 14px' } }, '—')),
1529
-
1530
- catalogNotice !== undefined ? h('div', { style: css.note }, catalogNotice) : null,
1531
- all.length > 0 ? h('div', { style: css.note }, t('windowWarn')) : null,
1532
- error !== undefined ? h('div', { style: css.err }, error) : null,
1533
- status !== undefined && error === undefined ? h('div', { style: css.note }, status) : null,
1534
-
1535
- brand.kind === 'codebuddy' ? null : h('div', { style: css.group },
1536
- h('h3', { style: css.h3 }, t(brand.cliGroupKey)),
1537
- h('div', { style: css.note }, t(brand.cliHintKey)),
1538
- h('div', { style: { ...css.bar, flexWrap: 'nowrap' } },
1539
- h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('configure') }, t('cliRun')),
1540
- h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('login') }, t('cliLogin')),
1541
- h('button', { style: { ...css.btn, ...css.btnAlert }, disabled: setupRunning, onClick: uninstallCli }, t('cliUninstall')),
1542
- setupLines.length > 0 && !setupRunning
1543
- ? h('button', { style: css.btn, onClick: () => setLogOpen(value => !value) }, logOpen ? t('cliHideLog') : t('cliShowLog'))
1544
- : null,
1545
- h('span', { style: css.count }, setupRunning
1546
- ? (setup?.mode === 'uninstall' ? t('cliUninstalling') : t('cliRunning'))
1547
- : setupError !== undefined
1548
- ? setupError
1549
- : setupCode === 0
1550
- ? (setup?.mode === 'uninstall' ? t('cliUninstallOk') : t('cliExitOk'))
1551
- : setupCode === undefined || setupCode === null
1552
- ? ''
1553
- : `${t('cliExitFail')} ${setupCode}`),
1554
- ),
1555
- logOpen && setupLines.length > 0
1556
- ? h('pre', { ref: logRef, style: css.log }, setupLines.join('\n'))
1557
- : null,
1558
- ),
1559
-
1560
- advanced,
1561
- )
1562
- }
1563
-
1564
- /**
1565
- * The two edition switches, contributed to this bundle's page in the plugin
1566
- * manager (`plugins.bundle.config`).
1567
- *
1568
- * They live here rather than on either settings page because they decide
1569
- * whether those pages exist at all: a page cannot own the switch that
1570
- * removes it. The write goes through the shared config form, so it uses the
1571
- * same revision fence as every other setting.
1572
- */
1573
- function BundleSettings({ ctx, t, view }) {
1574
- const form = ctx.configForms.get(NS)
1575
- const subscribe = useCallback(listener => form.subscribe(listener), [form])
1576
- const read = useCallback(() => form.getSnapshot(), [form])
1577
- const snapshot = useSyncExternalStore(subscribe, read)
1578
- const value = snapshot?.value ?? {}
1579
- const writable = snapshot?.writable !== false
1580
- const [busy, setBusy] = useState(false)
1581
- const [status, setStatus] = useState(undefined)
1582
- const [error, setError] = useState(undefined)
1583
- const writeTicket = useRef(0)
1584
-
1585
- const toggle = useCallback(async (key, next) => {
1586
- const mine = ++writeTicket.current
1587
- setBusy(true)
1588
- setStatus(t('saving'))
1589
- setError(undefined)
1590
- try {
1591
- const accepted = await withDeadline(form.set(key, next), WRITE_TIMEOUT_MS, t('timeout'))
1592
- if (accepted === false) throw new Error(t('pluginOptionsRejected'))
1593
- if (mine === writeTicket.current) setStatus(t('saved'))
1594
- } catch (err) {
1595
- if (mine !== writeTicket.current) return
1596
- setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
1597
- setStatus(undefined)
1598
- } finally {
1599
- if (mine === writeTicket.current) setBusy(false)
1600
- }
1601
- }, [form, t])
1602
-
1603
- const labelOf = brand => {
1604
- const key = brand.id === 'cn' ? 'displayName' : brand.id === 'global' ? 'intlDisplayName' : 'codebuddyDisplayName'
1605
- const fallback = brand.id === 'cn' ? t('nav') : brand.id === 'global' ? t('intlNav') : t('codebuddyNav')
1606
- const stored = value[key]
1607
- return typeof stored === 'string' && stored !== '' ? stored : fallback
1608
- }
1609
-
1610
- if (view !== undefined && view !== 'page') {
1611
- const names = BRANDS
1612
- .filter(brand => value[brand.fields.enabled] !== false)
1613
- .map(labelOf)
1614
- return h('span', null, names.join(' · '))
1615
- }
1616
-
1617
- const rows = BRANDS.map((brand, index) => {
1618
- const enabled = value[brand.fields.enabled] !== false
1619
- const name = labelOf(brand)
1620
- return h('div', {
1621
- key: brand.id,
1622
- style: { ...css.optionRow, ...(index === 0 ? css.optionFirst : {}) },
1623
- },
1624
- h('input', {
1625
- type: 'checkbox',
1626
- style: css.switch,
1627
- checked: enabled,
1628
- disabled: busy || !writable,
1629
- title: enabled ? t('pluginOptionsOn') : t('pluginOptionsOff'),
1630
- onChange: event => { void toggle(brand.fields.enabled, event.target.checked) },
1631
- }),
1632
- h('div', { style: css.optionText },
1633
- h('div', { style: css.optionName }, name),
1634
- h('div', { style: css.optionStatus }, enabled ? t('pluginOptionsOn') : t('pluginOptionsOff')),
1635
- ),
1636
- )
1637
- })
1638
-
1639
- return h('div', { style: css.group },
1640
- h('h3', { style: css.h3 }, t('pluginOptionsTitle')),
1641
- h('div', { style: css.note }, t('pluginOptionsHint')),
1642
- rows,
1643
- !writable ? h('div', { style: css.note }, t('pluginOptionsReadOnly')) : null,
1644
- error !== undefined ? h('div', { style: css.err }, error) : null,
1645
- status !== undefined && error === undefined ? h('div', { style: css.note }, status) : null,
1646
- )
1647
- }
1648
-
1649
- /**
1650
- * The collapsed advanced block: the remaining scalars, rendered against the
1651
- * host's schema so labels, bounds and defaults stay in one place.
1652
- */
1653
- function buildAdvanced({ t, form, snapshot, fields, namespace, show, onToggle }) {
1654
- const header = h('div', { style: css.bar },
1655
- h('button', { style: css.btn, onClick: onToggle }, show ? t('hide') : t('show')),
1656
- h('span', { style: css.note }, t('advancedHint')),
1657
- )
1658
- if (!show) {
1659
- return h('div', { style: css.group }, h('h3', { style: css.h3 }, t('advanced')), header)
1660
- }
1661
-
1662
- const value = snapshot?.value ?? {}
1663
- const user = snapshot?.user
1664
- const schema = namespace?.schema
1665
- const refs = schema?.refs
1666
- const root = refs?.[schema?.uid]
1667
- const writable = snapshot?.writable !== false
1668
-
1669
- const set = (key, next) => {
1670
- const op = next === undefined || next === ''
1671
- ? form.unset(key)
1672
- : form.set(key, next)
1673
- op.catch(() => undefined)
1674
- }
1675
-
1676
- const rows = fields.map(([key, kind]) => {
1677
- const node = refs?.[root?.dict?.[key]]
1678
- if (node === undefined) return null
1679
- const labels = t('advancedFields') ?? {}
1680
- const help = typeof node?.meta?.description === 'string' ? node.meta.description : undefined
1681
- const current = value[key]
1682
- const overridden = user !== null && typeof user === 'object' && Object.hasOwn(user, key)
1683
-
1684
- let control
1685
- if (kind === 'json') {
1686
- control = h('input', {
1687
- style: { ...css.input, fontFamily: 'ui-monospace, monospace' },
1688
- defaultValue: current === undefined ? '{}' : JSON.stringify(current),
1689
- disabled: !writable,
1690
- onBlur: event => {
1691
- try { set(key, JSON.parse(event.target.value)) } catch { /* keep the last valid value */ }
1692
- },
1693
- })
1694
- } else {
1695
- control = h('input', {
1696
- style: css.input,
1697
- type: kind === 'number' ? 'number' : 'text',
1698
- value: current === undefined ? '' : String(current),
1699
- min: node?.meta?.min,
1700
- max: node?.meta?.max,
1701
- step: node?.meta?.step,
1702
- disabled: !writable,
1703
- onChange: event => {
1704
- const raw = event.target.value
1705
- if (raw === '') { set(key, undefined); return }
1706
- set(key, kind === 'number' ? Number(raw) : raw)
1707
- },
1708
- })
1709
- }
1710
-
1711
- return h('div', { key, style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
1712
- h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
1713
- h('span', { style: css.advLabel }, labels[key] ?? key),
1714
- overridden && writable
1715
- ? h('button', {
1716
- style: { fontSize: '0.75em', opacity: 0.55, background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline', padding: 0, font: 'inherit', color: 'inherit' },
1717
- onClick: () => set(key, undefined),
1718
- }, t('reset'))
1719
- : null,
1720
- ),
1721
- control,
1722
- help !== undefined ? h('div', { style: css.note }, help) : null,
1723
- )
1724
- }).filter(Boolean)
1725
-
1726
- return h('div', { style: css.group },
1727
- h('h3', { style: css.h3 }, t('advanced')),
1728
- header,
1729
- rows,
1730
- )
1731
- }
1732
-
1733
- /**
1734
- * Register the sections that are currently switched on, and keep that set
1735
- * in step with the two edition switches.
1736
- *
1737
- * A section exists only while its edition does: the plugin page's switches
1738
- * decide whether the settings page, its models and its fields are offered at
1739
- * all. They cannot be registered unconditionally and hidden, because a
1740
- * registered `settings.section` is exactly what puts an entry in the nav.
1741
- */
1742
- function apply(ctx) {
1743
- const t = ctx.locale.bind(NS)
1744
- ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'llm-qoder-cn: dictionaries')
1745
-
1746
- // The two switches live on this bundle's own page in the plugin manager.
1747
- // That page exists whether or not either edition is currently shown.
1748
- ctx.effect(() => ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
1749
- name: 'plugins.bundle.config',
1750
- key: 'dsh-agent-sdk-bridge',
1751
- locale: NS,
1752
- }, props => h(BundleSettings, { ...props, ctx, t }))), 'llm-qoder-cn: bundle options')
1753
-
1754
- ctx.effect(() => ctx.configForms.whileServed([NS], () => {
1755
- const form = ctx.configForms.get(NS)
1756
- const live = new Map()
1757
-
1758
- const sync = () => {
1759
- const snapshot = form.getSnapshot()
1760
- // Wait for the stored config before deciding what to show. Registering
1761
- // optimistically would flash a page the user already switched off.
1762
- if (snapshot.status !== 'ready') return
1763
- const value = snapshot.value ?? {}
1764
- for (const brand of BRANDS) {
1765
- const enabled = value[brand.fields.enabled] !== false
1766
- const current = live.get(brand.id)
1767
- if (enabled && current === undefined) {
1768
- live.set(brand.id, ctx.slots.inject('settings.section', () => ctx.slots.register({
1769
- name: 'settings.section',
1770
- id: brand.settingsId,
1771
- order: brand.order,
1772
- label: () => t(brand.navKey),
1773
- locale: NS,
1774
- }, props => h(SettingsPage, { ...props, ctx, t, brand }))))
1775
- } else if (!enabled && current !== undefined) {
1776
- current()
1777
- live.delete(brand.id)
1778
- }
1779
- }
1780
- }
1781
-
1782
- const unsubscribe = form.subscribe(sync)
1783
- sync()
1784
- return () => {
1785
- unsubscribe()
1786
- for (const off of live.values()) off()
1787
- live.clear()
1788
- }
1789
- }), 'llm-qoder-cn: pages')
1790
- }
1791
-
1792
- exports.apply = apply
1793
- exports.inject = inject
1794
- exports.name = 'dsh-agent-sdk-bridge'
1795
- exports.__test = {
1796
- windowLabel, priceSuffix, ADVANCED, BRANDS, zh, en,
1797
- SettingsPage, BundleSettings, UsageCard, CodeBuddyCard, QuotaLine, creditsOf, neverExpires,
1798
- readCache, writeCache,
1799
- }
1800
- return module.exports
1801
- },
1802
- })
1
+ /**
2
+ * dsh-agent-sdk-bridge — browser half.
3
+ *
4
+ * Contributes one top-level settings section per enabled provider (`qoder-cn`,
5
+ * `qoder-intl`, `codebuddy`), each showing its account card and then the model
6
+ * list: every model the account exposes, with an on/off switch and a
7
+ * context-window choice, plus a collapsed "advanced" area holding the scalars
8
+ * worth reaching without editing YAML. The plugin manager's page for this
9
+ * bundle carries the switches that decide which of those sections exist.
10
+ *
11
+ * The model list cannot come from the config form: it is fetched live from the
12
+ * provider. So the page reads `GET <prefix>/models`, which joins that live
13
+ * catalog with the user's stored choices, while every change goes back through
14
+ * the host's own config form. The host owns the catalog, so the page never
15
+ * derives state the adapter does not share.
16
+ *
17
+ * The page can also start the CLI helper shipped with this package
18
+ * (`POST <prefix>/setup`, then `GET <prefix>/setup` for its output): installing
19
+ * and signing into qoderclicn is a local action a browser cannot perform.
20
+ *
21
+ * Rendering from the schema-driven form alone would be wrong here: the useful
22
+ * controls depend on rows that only exist at runtime.
23
+ *
24
+ * Hand-written ModuleLoader bundle: no build step, no dependency beyond the
25
+ * `react` the shell already provides. Colour comes from theme variables so the
26
+ * page survives a scheme switch.
27
+ */
28
+
29
+ window.__ModuleLoader__.load({
30
+ id: 'dsh-agent-sdk-bridge',
31
+ factory: require => {
32
+ const module = { exports: {} }
33
+ const exports = module.exports
34
+ const React = require('react')
35
+ const { createElement: h, useState, useEffect, useCallback, useMemo, useRef, useSyncExternalStore } = React
36
+
37
+ /** The plugin's config namespace — must equal the profile row id. */
38
+ const NS = 'llm-qoder-cn'
39
+ const inject = ['slots', 'locale', 'configForms']
40
+
41
+ // ── copy ────────────────────────────────────────────────────────────────
42
+ const zh = {
43
+ nav: 'Qoder CN',
44
+ title: 'Qoder CN',
45
+ intro: '勾选要启用的模型,并为需要的模型指定上下文窗口。改动即时生效,无需重启。',
46
+ loading: '正在读取模型列表…',
47
+ loadFailed: '读取模型列表失败',
48
+ retry: '重试',
49
+ refresh: '刷新列表',
50
+ refreshing: '刷新中…',
51
+ saveFailed: '保存失败',
52
+ notApplied: '服务器未报告这次改动,可能被其他窗口覆盖了,请刷新后重试',
53
+ timeout: '保存超时,请重试',
54
+ saved: '已保存',
55
+ saving: '保存中…',
56
+ enabledCount: '已启用',
57
+ noModels: '账号没有返回任何模型:一般是本机 qoderclicn 还没装好,或者还没登录。',
58
+ search: '搜索模型…',
59
+ onlyEnabled: '只看已启用',
60
+ selectAll: '全部启用',
61
+ selectNone: '全部关闭',
62
+ colEnabled: '启用',
63
+ windowDefault: '默认',
64
+ windowDefaultHint: '跟随上游声明的窗口',
65
+ vision: '读图',
66
+ free: '免费',
67
+ advanced: '高级设置',
68
+ advancedHint: '以下为细节参数,通常无需改动。',
69
+ show: '展开',
70
+ hide: '收起',
71
+ reset: '恢复默认',
72
+ windowWarn: '窗口越大,DSH 的自动压缩触发得越晚。若对话经常超限,请选较小的窗口。',
73
+ cliGroup: 'Qoder CN CLI',
74
+ cliHint: '插件复用本机 qoderclicn 的登录态。这里可以直接跑随包附带的配置脚本:缺 CLI 就装,未登录就拉起浏览器登录。',
75
+ cliRun: '一键配置',
76
+ cliLogin: '重新登录',
77
+ cliRunning: '正在执行,输出持续刷新…',
78
+ cliStartFailed: '无法启动配置脚本',
79
+ cliExitOk: '配置脚本执行完成',
80
+ cliExitFail: '配置脚本未通过,退出码',
81
+ cliShowLog: '查看输出',
82
+ cliHideLog: '收起输出',
83
+ cliUninstall: '卸载 CLI',
84
+ cliUninstallConfirm: '确定要卸载本机的 Qoder CLI 吗?卸载后需要重新安装才能继续使用,登录凭证会保留。',
85
+ cliUninstalling: '正在卸载…',
86
+ cliUninstallOk: 'CLI 已卸载',
87
+ intlNav: 'Qoder 国际版',
88
+ intlTitle: 'Qoder 国际版',
89
+ intlIntro: '国际版账户(qoder.com)的模型与额度。勾选要启用的模型,并为需要的模型指定上下文窗口。改动即时生效,无需重启。',
90
+ intlNoModels: '国际版账号没有返回任何模型:一般是本机 qodercli 还没装好,或者还没登录。',
91
+ intlCliGroup: 'Qoder 国际版 CLI',
92
+ intlCliHint: '插件复用本机 qodercli 的登录态。这里可以直接跑随包附带的配置脚本:缺 CLI 就装,未登录就拉起浏览器登录。',
93
+ usageTitle: '额度',
94
+ usageLoading: '正在读取额度…',
95
+ usageRefresh: '刷新额度',
96
+ usageUnavailable: '无法读取额度',
97
+ usageRetry: '重试',
98
+ usageAccount: '账号',
99
+ usagePlan: '套餐',
100
+ usageUsed: '已用',
101
+ usageRemaining: '剩余',
102
+ usageOf: '/',
103
+ usageCredits: 'credits',
104
+ usagePlanQuota: '套餐额度',
105
+ usageAddOn: '加量包',
106
+ usageOrgPackage: '组织资源包',
107
+ usageExpires: '到期',
108
+ usageNever: '长期有效',
109
+ usageDetail: '用量明细',
110
+ usageUpgrade: '升级套餐',
111
+ usageExceeded: '额度已用完',
112
+ usageUpdated: '更新于',
113
+ usageUnknownPlan: '未知套餐',
114
+ usageStale: '显示上次读数,刷新失败',
115
+ pluginOptionsTitle: '启用的版本',
116
+ pluginOptionsHint: '关闭后,对应设置页、模型列表与模型分组都会移除;已保存的模型选择保留,重新打开即可恢复。',
117
+ pluginOptionsOn: '显示中',
118
+ pluginOptionsOff: '已关闭',
119
+ pluginOptionsReadOnly: '当前配置不可写',
120
+ pluginOptionsRejected: '宿主拒绝了这次改动;若刚更新过插件,请重启 DSH 后再试',
121
+ codebuddyNav: 'CodeBuddy',
122
+ codebuddyTitle: 'CodeBuddy',
123
+ codebuddyIntro: '腾讯 CodeBuddy 账户的模型。请先在下方选择登录区域并登录,再勾选要启用的模型。',
124
+ codebuddyNoModels: 'CodeBuddy 账号没有返回任何模型:请确认已选择登录区域并完成登录。',
125
+ codebuddyAuthTitle: '登录',
126
+ codebuddyAuthHint: 'CodeBuddy 分国际版与国内版,两边账号与模型目录独立。企业域名登录不在本插件支持范围内。',
127
+ codebuddyRegionGlobal: '国际版(codebuddy.ai)',
128
+ codebuddyRegionCn: '国内版(copilot.tencent.com)',
129
+ codebuddyRegionLabel: '登录区域',
130
+ codebuddyLogin: '登录',
131
+ codebuddyLogout: '退出登录',
132
+ codebuddyLoggingIn: '请在浏览器中完成登录…',
133
+ codebuddyLoginPrompt: '登录后这里会显示账号与额度信息。',
134
+ codebuddyModelsHint: '请先登录 CodeBuddy,登录后才会读取并显示可用模型。',
135
+ codebuddyRegionMismatch: '宿主返回的模型列表不属于当前区域,请刷新页面后重试。',
136
+ codebuddyLoginStarted: '已打开浏览器,完成登录后这里会自动更新。',
137
+ codebuddyLoginFailed: '登录失败',
138
+ codebuddyOpenUrl: '手动打开登录页',
139
+ codebuddyLoggedOut: '已退出登录',
140
+ codebuddyNotLoggedIn: '未登录',
141
+ codebuddySignedIn: '已登录',
142
+ codebuddyAccountUnknown: '账号信息暂不可用',
143
+ codebuddyNoQuota: '暂时无法读取额度。',
144
+ codebuddyQuotaFailed: '额度读取失败',
145
+ codebuddyQuotaTitle: '积分额度',
146
+ codebuddyQuotaPackages: '积分包',
147
+ codebuddyQuotaExpires: '最近到期',
148
+ codebuddyConfirmLogout: '确定要退出当前区域的 CodeBuddy 登录吗?',
149
+ minimaxNav: 'MiniMax Code',
150
+ minimaxTitle: 'MiniMax Code',
151
+ minimaxIntro: '通过 Agent Client Protocol 接入 MiniMax Code(mcode acp)。选择登录区域并完成登录后,才会读取模型目录。',
152
+ minimaxNoModels: 'MiniMax Code 账号没有返回任何模型:请确认 CLI 已安装、已选择区域并完成登录。',
153
+ minimaxAuthTitle: '登录与 CLI',
154
+ minimaxAuthHint: 'MiniMax Code 分国内站与国际站,模型目录独立。登录由 mcode CLI 完成,凭据保存在本机;CLI 同一时间只允许一个站点登录,切换前请先在另一站点退出登录。',
155
+ minimaxRegionGlobal: '国际站(account.minimax.io)',
156
+ minimaxRegionCn: '国内站(account.minimax.cn)',
157
+ minimaxRegionLabel: '登录区域',
158
+ minimaxLogin: '登录',
159
+ minimaxLogout: '退出登录',
160
+ minimaxLoggingIn: '请在浏览器中完成授权…',
161
+ minimaxLoginPrompt: '登录后这里会显示账号状态与可用模型。',
162
+ minimaxModelsHint: '请先安装并登录 MiniMax Code,登录后才会读取并显示可用模型。',
163
+ minimaxRegionMismatch: '宿主返回的模型列表不属于当前区域,请刷新页面后重试。',
164
+ minimaxLoginStarted: '已打开浏览器,完成授权后这里会自动更新。',
165
+ minimaxLoginFailed: '登录失败',
166
+ minimaxOpenUrl: '手动打开授权页',
167
+ minimaxNotLoggedIn: '未登录',
168
+ minimaxSignedIn: '已登录',
169
+ minimaxConfirmLogout: '确定要退出当前区域的 MiniMax Code 登录吗?',
170
+ minimaxCliGroup: 'MiniMax Code CLI',
171
+ minimaxCliHint: '安装的是 @minimax-ai/code(含 native SQLite)。普通 npm 安装会被 npm 12 拦截安装脚本,导致 mcode 无法启动,这里使用官方要求的参数。',
172
+ minimaxCliInstalled: '已安装',
173
+ minimaxCliMissing: '未安装',
174
+ minimaxCliInstall: '安装 / 更新 CLI',
175
+ minimaxCliUninstall: '卸载 CLI',
176
+ minimaxCliInstalling: '正在安装…',
177
+ minimaxCliUninstalling: '正在卸载…',
178
+ minimaxConfirmUninstall: '确定要卸载全局 MiniMax Code CLI 吗?登录态会保留。',
179
+ minimaxCliFailed: 'CLI 操作失败',
180
+ minimaxShowOutput: '查看输出',
181
+ minimaxHideOutput: '收起输出',
182
+ minimaxNoUsage: '登录后会显示账号、套餐与剩余额度。',
183
+ minimaxCliRequired: '请先安装 MiniMax Code CLI,再登录。',
184
+ minimaxExpires: '凭据到期',
185
+ minimaxAccount: '账号',
186
+ minimaxAccountUnknown: '未知账号',
187
+ minimaxPlan: '当前套餐',
188
+ minimaxPlanTokenPlan: 'Token Plan',
189
+ minimaxPlanCredits: '积分',
190
+ minimaxPlanFree: '免费',
191
+ minimaxCredits: '剩余积分',
192
+ minimaxCreditsPurchased: '其中购买',
193
+ minimaxCreditsFree: '其中赠送',
194
+ minimaxQuotaRemaining: '剩余',
195
+ minimaxQuotaReset: '重置于',
196
+ minimaxQuotaUnlimited: '不限',
197
+ minimaxQuotaNone: '当前账号没有 Token Plan 额度窗口。',
198
+ minimaxRegionBlockedShort: '区域不可用',
199
+ minimaxIpBlocked: '本机 IP 不在 MiniMax 国际站的服务区域,国际站已拒绝连接。请切换到国内站,或更换网络后重试。',
200
+ minimaxSwitchToCn: '切换到国内站',
201
+ minimaxSwitchToGlobal: '切换到国际站',
202
+ minimaxUsageLoading: '正在读取账号与额度…',
203
+ minimaxUsageFailed: '额度读取失败',
204
+ advancedFields: {
205
+ displayName: '分组名称',
206
+ maxSessions: '并发会话数',
207
+ modelCacheTtlSeconds: '模型列表缓存(秒)',
208
+ defaultReasoningEffort: '默认思考档位',
209
+ defaultMaxTokens: '默认输出上限',
210
+ toolResultTimeoutSeconds: '工具结果等待(秒)',
211
+ catalogFetchTimeoutSeconds: '模型列表超时(秒)',
212
+ abortGraceSeconds: '中断宽限(秒)',
213
+ coldMaxTurns: '旁路请求轮次',
214
+ modelAliases: '模型别名',
215
+ intlDisplayName: '国际版分组名称',
216
+ intlModelAliases: '国际版模型别名',
217
+ codebuddyDisplayName: 'CodeBuddy 分组名称',
218
+ codebuddyModelAliases: 'CodeBuddy 模型别名',
219
+ minimaxDisplayName: 'MiniMax 分组名称',
220
+ minimaxModelAliases: 'MiniMax 模型别名',
221
+ },
222
+ }
223
+ const en = {
224
+ nav: 'Qoder CN',
225
+ title: 'Qoder CN',
226
+ intro: 'Tick the models you want available and set a context window where needed. Changes apply immediately.',
227
+ loading: 'Loading models…',
228
+ loadFailed: 'Could not load the model list',
229
+ retry: 'Retry',
230
+ refresh: 'Refresh',
231
+ refreshing: 'Refreshing…',
232
+ saveFailed: 'Save failed',
233
+ notApplied: 'The host did not report this change; another window may have overwritten it. Refresh and retry.',
234
+ timeout: 'Save timed out; please retry',
235
+ saved: 'Saved',
236
+ saving: 'Saving…',
237
+ enabledCount: 'enabled',
238
+ noModels: 'The account returned no models - usually qoderclicn is not installed on this machine, or not signed in.',
239
+ search: 'Search models…',
240
+ onlyEnabled: 'Enabled only',
241
+ selectAll: 'Enable all',
242
+ selectNone: 'Disable all',
243
+ colEnabled: 'On',
244
+ windowDefault: 'Default',
245
+ windowDefaultHint: "Follow upstream's declared window",
246
+ vision: 'Vision',
247
+ free: 'Free',
248
+ advanced: 'Advanced',
249
+ advancedHint: 'Detail parameters; rarely changed.',
250
+ show: 'Show',
251
+ hide: 'Hide',
252
+ reset: 'Reset',
253
+ windowWarn: 'A larger window delays DSH\u2019s auto-compaction. Pick a smaller one if conversations overflow.',
254
+ cliGroup: 'Qoder CN CLI',
255
+ cliHint: 'The plugin reuses this machine\u2019s qoderclicn sign-in. Run the bundled helper from here: it installs the CLI when missing and opens the browser sign-in when signed out.',
256
+ cliRun: 'Configure',
257
+ cliLogin: 'Re-login',
258
+ cliRunning: 'Running, output refreshes…',
259
+ cliStartFailed: 'Could not start the helper',
260
+ cliExitOk: 'Helper finished',
261
+ cliExitFail: 'Helper failed with exit code',
262
+ cliShowLog: 'Show output',
263
+ cliHideLog: 'Hide output',
264
+ cliUninstall: 'Uninstall CLI',
265
+ cliUninstallConfirm: 'Uninstall the Qoder CLI from this machine? It must be installed again to keep using this edition. Sign-in files are kept.',
266
+ cliUninstalling: 'Uninstalling…',
267
+ cliUninstallOk: 'CLI uninstalled',
268
+ intlNav: 'Qoder International',
269
+ intlTitle: 'Qoder International',
270
+ intlIntro: 'Models and quota for the international account (qoder.com). Tick the models you want available and set a context window where needed. Changes apply immediately.',
271
+ intlNoModels: 'The international account returned no models - usually qodercli is not installed on this machine, or not signed in.',
272
+ intlCliGroup: 'Qoder International CLI',
273
+ intlCliHint: 'The plugin reuses this machine\u2019s qodercli sign-in. Run the bundled helper from here: it installs the CLI when missing and opens the browser sign-in when signed out.',
274
+ usageTitle: 'Quota',
275
+ usageLoading: 'Reading quota…',
276
+ usageRefresh: 'Refresh quota',
277
+ usageUnavailable: 'Could not read the quota',
278
+ usageRetry: 'Retry',
279
+ usageAccount: 'Account',
280
+ usagePlan: 'Plan',
281
+ usageUsed: 'Used',
282
+ usageRemaining: 'Remaining',
283
+ usageOf: '/',
284
+ usageCredits: 'credits',
285
+ usagePlanQuota: 'Plan quota',
286
+ usageAddOn: 'Add-on package',
287
+ usageOrgPackage: 'Organization package',
288
+ usageExpires: 'Expires',
289
+ usageNever: 'No expiry',
290
+ usageDetail: 'Usage details',
291
+ usageUpgrade: 'Upgrade',
292
+ usageExceeded: 'Quota exhausted',
293
+ usageUpdated: 'Updated',
294
+ usageUnknownPlan: 'Unknown plan',
295
+ usageStale: 'Showing the last reading; refresh failed',
296
+ pluginOptionsTitle: 'Enabled editions',
297
+ pluginOptionsHint: 'Turning one off removes its settings page, model list, and model group. Saved model choices are kept, so turning it back on restores them.',
298
+ pluginOptionsOn: 'Shown',
299
+ pluginOptionsOff: 'Off',
300
+ pluginOptionsReadOnly: 'This configuration is read-only',
301
+ pluginOptionsRejected: 'The host rejected this change; if you just updated the plugin, restart DSH and retry',
302
+ codebuddyNav: 'CodeBuddy',
303
+ codebuddyTitle: 'CodeBuddy',
304
+ codebuddyIntro: 'Models for your Tencent CodeBuddy account. Choose a login region below and sign in before enabling models.',
305
+ codebuddyNoModels: 'The CodeBuddy account returned no models: make sure a region is selected and the browser login completed.',
306
+ codebuddyAuthTitle: 'Sign in',
307
+ codebuddyAuthHint: 'CodeBuddy has independent international and mainland accounts with their own model catalogs. Enterprise-domain login is out of scope for this plugin.',
308
+ codebuddyRegionGlobal: 'International (codebuddy.ai)',
309
+ codebuddyRegionCn: 'Mainland (copilot.tencent.com)',
310
+ codebuddyRegionLabel: 'Login region',
311
+ codebuddyLogin: 'Sign in',
312
+ codebuddyLogout: 'Sign out',
313
+ codebuddyLoggingIn: 'Finish the sign-in in your browser…',
314
+ codebuddyLoginPrompt: 'Sign in to see the account and quota here.',
315
+ codebuddyModelsHint: 'Sign in to CodeBuddy first; the model catalog is read only after sign-in.',
316
+ codebuddyRegionMismatch: 'The host answered with the other region\'s models; reload the page and try again.',
317
+ codebuddyLoginStarted: 'Browser opened; this card updates when the login completes.',
318
+ codebuddyLoginFailed: 'Sign-in failed',
319
+ codebuddyOpenUrl: 'Open the sign-in page',
320
+ codebuddyLoggedOut: 'Signed out',
321
+ codebuddyNotLoggedIn: 'Not signed in',
322
+ codebuddySignedIn: 'Signed in',
323
+ codebuddyAccountUnknown: 'Account details are unavailable',
324
+ codebuddyNoQuota: 'The quota is temporarily unavailable.',
325
+ codebuddyQuotaFailed: 'Could not read the quota',
326
+ codebuddyQuotaTitle: 'Credits',
327
+ codebuddyQuotaPackages: 'Credit packages',
328
+ codebuddyQuotaExpires: 'Earliest expiry',
329
+ codebuddyConfirmLogout: 'Sign out of CodeBuddy for the selected region?',
330
+ minimaxNav: 'MiniMax Code',
331
+ minimaxTitle: 'MiniMax Code',
332
+ minimaxIntro: 'MiniMax Code over the Agent Client Protocol (mcode acp). Choose a login region and sign in before the catalog is read.',
333
+ minimaxNoModels: 'The MiniMax Code account returned no models: make sure the CLI is installed, a region is selected, and the login completed.',
334
+ minimaxAuthTitle: 'Sign in and CLI',
335
+ minimaxAuthHint: 'MiniMax Code has independent mainland and international catalogs. Login runs through the mcode CLI and the credential stays on this machine; the CLI allows one region at a time, so sign out of the other before switching.',
336
+ minimaxRegionGlobal: 'International (account.minimax.io)',
337
+ minimaxRegionCn: 'Mainland (account.minimax.cn)',
338
+ minimaxRegionLabel: 'Login region',
339
+ minimaxLogin: 'Sign in',
340
+ minimaxLogout: 'Sign out',
341
+ minimaxLoggingIn: 'Finish the authorization in your browser…',
342
+ minimaxLoginPrompt: 'Sign in to see the account state and available models.',
343
+ minimaxModelsHint: 'Install and sign in to MiniMax Code first; the model catalog is read only after sign-in.',
344
+ minimaxRegionMismatch: 'The host answered with the other region\'s models; reload the page and try again.',
345
+ minimaxLoginStarted: 'Browser opened; this card updates when the login completes.',
346
+ minimaxLoginFailed: 'Sign-in failed',
347
+ minimaxOpenUrl: 'Open the authorization page',
348
+ minimaxNotLoggedIn: 'Not signed in',
349
+ minimaxSignedIn: 'Signed in',
350
+ minimaxConfirmLogout: 'Sign out of MiniMax Code for the selected region?',
351
+ minimaxCliGroup: 'MiniMax Code CLI',
352
+ minimaxCliHint: 'Installs @minimax-ai/code (including its native SQLite dependency). npm 12 blocks install scripts by default, which leaves mcode unable to start; the official flags are used here.',
353
+ minimaxCliInstalled: 'Installed',
354
+ minimaxCliMissing: 'Not installed',
355
+ minimaxCliInstall: 'Install / update CLI',
356
+ minimaxCliUninstall: 'Uninstall CLI',
357
+ minimaxCliInstalling: 'Installing…',
358
+ minimaxCliUninstalling: 'Uninstalling…',
359
+ minimaxConfirmUninstall: 'Uninstall the global MiniMax Code CLI? The login state is kept.',
360
+ minimaxCliFailed: 'CLI action failed',
361
+ minimaxShowOutput: 'Show output',
362
+ minimaxHideOutput: 'Hide output',
363
+ minimaxNoUsage: 'Sign in to see the account, plan and remaining quota.',
364
+ minimaxCliRequired: 'Install the MiniMax Code CLI before signing in.',
365
+ minimaxExpires: 'Credential expires',
366
+ minimaxAccount: 'Account',
367
+ minimaxAccountUnknown: 'Unknown account',
368
+ minimaxPlan: 'Plan',
369
+ minimaxPlanTokenPlan: 'Token Plan',
370
+ minimaxPlanCredits: 'Credits',
371
+ minimaxPlanFree: 'Free',
372
+ minimaxCredits: 'Remaining credits',
373
+ minimaxCreditsPurchased: 'purchased',
374
+ minimaxCreditsFree: 'free',
375
+ minimaxQuotaRemaining: 'remaining',
376
+ minimaxQuotaReset: 'resets at',
377
+ minimaxQuotaUnlimited: 'Unlimited',
378
+ minimaxQuotaNone: 'This account has no Token Plan quota windows.',
379
+ minimaxRegionBlockedShort: 'Region unavailable',
380
+ minimaxIpBlocked: 'This machine\'s IP is outside the MiniMax International service region, so the international site refused the connection. Switch to the mainland site or change networks.',
381
+ minimaxSwitchToCn: 'Switch to mainland',
382
+ minimaxSwitchToGlobal: 'Switch to international',
383
+ minimaxUsageLoading: 'Reading the account and quota…',
384
+ minimaxUsageFailed: 'Could not read the quota',
385
+ advancedFields: {
386
+ displayName: 'Group name',
387
+ maxSessions: 'Concurrent sessions',
388
+ modelCacheTtlSeconds: 'Catalog cache (s)',
389
+ defaultReasoningEffort: 'Default reasoning effort',
390
+ defaultMaxTokens: 'Default output cap',
391
+ toolResultTimeoutSeconds: 'Tool result wait (s)',
392
+ catalogFetchTimeoutSeconds: 'Catalog timeout (s)',
393
+ abortGraceSeconds: 'Abort grace (s)',
394
+ coldMaxTurns: 'Side-channel turns',
395
+ modelAliases: 'Model aliases',
396
+ intlDisplayName: 'International group name',
397
+ intlModelAliases: 'International model aliases',
398
+ codebuddyDisplayName: 'CodeBuddy group name',
399
+ codebuddyModelAliases: 'CodeBuddy model aliases',
400
+ minimaxDisplayName: 'MiniMax group name',
401
+ minimaxModelAliases: 'MiniMax model aliases',
402
+ },
403
+ }
404
+
405
+ /**
406
+ * Scalars shown under Advanced, in order, with how to render each.
407
+ *
408
+ * The schema is the source of truth for labels, help text and bounds; this
409
+ * list only decides order and which control each field gets.
410
+ */
411
+ const ADVANCED = {
412
+ cn: [
413
+ ['displayName', 'text'],
414
+ ['maxSessions', 'number'],
415
+ ['modelCacheTtlSeconds', 'number'],
416
+ ['defaultReasoningEffort', 'text'],
417
+ ['defaultMaxTokens', 'number'],
418
+ ['toolResultTimeoutSeconds', 'number'],
419
+ ['catalogFetchTimeoutSeconds', 'number'],
420
+ ['abortGraceSeconds', 'number'],
421
+ ['coldMaxTurns', 'number'],
422
+ ['modelAliases', 'json'],
423
+ ],
424
+ // The shared scalars above already have a home on the CN page; the intl
425
+ // page only adds what is specific to that edition, so the same setting is
426
+ // never edited in two places with two different values.
427
+ global: [
428
+ ['intlDisplayName', 'text'],
429
+ ['intlModelAliases', 'json'],
430
+ ],
431
+ codebuddy: [
432
+ ['codebuddyDisplayName', 'text'],
433
+ ['codebuddyModelAliases', 'json'],
434
+ ],
435
+ minimax: [
436
+ ['minimaxDisplayName', 'text'],
437
+ ['minimaxModelAliases', 'json'],
438
+ ],
439
+ }
440
+
441
+ /**
442
+ * One settings section per provider.
443
+ *
444
+ * They share the page component and the API routes; only the config keys,
445
+ * the API brand and the copy differ.
446
+ */
447
+ const BRANDS = [
448
+ {
449
+ id: 'cn',
450
+ kind: 'qoder',
451
+ settingsId: 'qoder-cn',
452
+ order: 36,
453
+ titleKey: 'title',
454
+ navKey: 'nav',
455
+ introKey: 'intro',
456
+ noModelsKey: 'noModels',
457
+ cliGroupKey: 'cliGroup',
458
+ cliHintKey: 'cliHint',
459
+ fields: {
460
+ enabled: 'cnEnabled',
461
+ disabled: 'disabledModels',
462
+ windows: 'modelContextWindows',
463
+ },
464
+ },
465
+ {
466
+ id: 'global',
467
+ kind: 'qoder',
468
+ settingsId: 'qoder-intl',
469
+ order: 37,
470
+ titleKey: 'intlTitle',
471
+ navKey: 'intlNav',
472
+ introKey: 'intlIntro',
473
+ noModelsKey: 'intlNoModels',
474
+ cliGroupKey: 'intlCliGroup',
475
+ cliHintKey: 'intlCliHint',
476
+ fields: {
477
+ enabled: 'intlEnabled',
478
+ disabled: 'intlDisabledModels',
479
+ windows: 'intlModelContextWindows',
480
+ },
481
+ },
482
+ {
483
+ id: 'codebuddy',
484
+ kind: 'codebuddy',
485
+ settingsId: 'codebuddy',
486
+ order: 38,
487
+ titleKey: 'codebuddyTitle',
488
+ navKey: 'codebuddyNav',
489
+ introKey: 'codebuddyIntro',
490
+ noModelsKey: 'codebuddyNoModels',
491
+ fields: {
492
+ enabled: 'codebuddyEnabled',
493
+ // The page swaps these for the selected login region's own fields.
494
+ disabled: 'codebuddyGlobalDisabledModels',
495
+ windows: 'codebuddyGlobalModelContextWindows',
496
+ },
497
+ },
498
+ {
499
+ id: 'minimax',
500
+ kind: 'minimax',
501
+ settingsId: 'minimax',
502
+ order: 39,
503
+ titleKey: 'minimaxTitle',
504
+ navKey: 'minimaxNav',
505
+ introKey: 'minimaxIntro',
506
+ noModelsKey: 'minimaxNoModels',
507
+ fields: {
508
+ enabled: 'minimaxEnabled',
509
+ // Swapped for the selected region's fields, like CodeBuddy.
510
+ disabled: 'minimaxCnDisabledModels',
511
+ windows: 'minimaxCnModelContextWindows',
512
+ },
513
+ },
514
+ ]
515
+
516
+ const css = {
517
+ page: { maxWidth: '860px', display: 'flex', flexDirection: 'column', gap: '14px', color: 'var(--dsw-alias-label-primary)' },
518
+ h2: { margin: '0', fontSize: '1.25em' },
519
+ intro: { margin: '0', opacity: 0.72, lineHeight: 1.55, fontSize: '0.92em' },
520
+ bar: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' },
521
+ btn: { padding: '6px 12px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'transparent', color: 'inherit', cursor: 'pointer', font: 'inherit', fontSize: '0.88em' },
522
+ input: { padding: '6px 10px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'var(--dsw-alias-bg-base, transparent)', color: 'inherit', font: 'inherit', fontSize: '0.88em' },
523
+ search: { flex: '1 1 180px', minWidth: '140px' },
524
+ count: { fontSize: '0.85em', opacity: 0.7, marginLeft: 'auto' },
525
+ list: { display: 'flex', flexDirection: 'column', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', borderRadius: '10px', overflow: 'hidden' },
526
+ row: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderTop: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.15))' },
527
+ rowFirst: { borderTop: 'none' },
528
+ rowOff: { opacity: 0.5 },
529
+ name: { flex: '1 1 auto', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '2px' },
530
+ nameText: { fontSize: '0.92em', fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
531
+ id: { fontSize: '0.76em', opacity: 0.55, fontFamily: 'ui-monospace, monospace' },
532
+ tag: { fontSize: '0.72em', padding: '1px 6px', borderRadius: '5px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', opacity: 0.75 },
533
+ price: { fontSize: '0.9em', opacity: 0.7, fontWeight: 400 },
534
+ select: { padding: '5px 8px', borderRadius: '7px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.35))', background: 'var(--dsw-alias-bg-base, transparent)', color: 'inherit', font: 'inherit', fontSize: '0.85em', minWidth: '104px' },
535
+ switch: { width: '17px', height: '17px', cursor: 'pointer', accentColor: 'var(--dsw-alias-brand-primary, #4c6ef5)' },
536
+ note: { fontSize: '0.82em', opacity: 0.62, lineHeight: 1.5 },
537
+ err: { fontSize: '0.86em', color: 'var(--dsw-alias-label-danger, #e03131)' },
538
+ guide: { display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap', padding: '12px 14px', borderRadius: '10px', border: '1px solid var(--dsw-alias-label-danger, #e03131)', background: 'rgba(224,49,49,0.07)' },
539
+ guideText: { flex: '1 1 240px', fontSize: '0.88em', lineHeight: 1.5, color: 'var(--dsw-alias-label-danger, #e03131)' },
540
+ btnAlert: { border: '1px solid var(--dsw-alias-label-danger, #e03131)', color: 'var(--dsw-alias-label-danger, #e03131)' },
541
+ group: { display: 'flex', flexDirection: 'column', gap: '10px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', borderRadius: '10px', padding: '14px 16px' },
542
+ advLabel: { fontSize: '0.88em' },
543
+ h3: { margin: 0, fontSize: '0.95em' },
544
+ log: { margin: '0', maxHeight: '240px', overflowY: 'auto', padding: '8px 10px', borderRadius: '8px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', background: 'var(--dsw-alias-bg-base, rgba(128,128,128,0.05))', fontFamily: 'ui-monospace, monospace', fontSize: '0.76em', lineHeight: 1.5, whiteSpace: 'pre-wrap', wordBreak: 'break-word' },
545
+ usageCard: { display: 'flex', flexDirection: 'column', gap: '10px', padding: '14px 16px', borderRadius: '10px', border: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.25))', background: 'var(--dsw-alias-bg-base, rgba(128,128,128,0.03))' },
546
+ usageHead: { display: 'flex', alignItems: 'baseline', gap: '10px', flexWrap: 'wrap' },
547
+ usagePct: { marginLeft: 'auto', fontSize: '0.9em', fontWeight: 600 },
548
+ progressOuter: { height: '8px', borderRadius: '999px', background: 'var(--dsw-alias-border-l2, rgba(128,128,128,0.22))', overflow: 'hidden' },
549
+ progressInner: { height: '100%', borderRadius: '999px', background: 'var(--dsw-alias-brand-primary, #4c6ef5)', transition: 'width .25s ease' },
550
+ progressDanger: { background: 'var(--dsw-alias-label-danger, #e03131)' },
551
+ usageLine: { display: 'flex', alignItems: 'baseline', gap: '8px', flexWrap: 'wrap', fontSize: '0.86em' },
552
+ usageLabel: { opacity: 0.62, minWidth: '72px' },
553
+ usageValue: { fontWeight: 500 },
554
+ link: { color: 'var(--dsw-alias-brand-primary, #4c6ef5)', textDecoration: 'none', fontSize: '0.86em' },
555
+ usageFoot: { display: 'flex', alignItems: 'center', gap: '14px', flexWrap: 'wrap', fontSize: '0.8em', opacity: 0.6 },
556
+ optionRow: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 0', borderTop: '1px solid var(--dsw-alias-border-l2, rgba(128,128,128,0.15))' },
557
+ optionFirst: { borderTop: 'none', paddingTop: 0 },
558
+ optionText: { flex: '1 1 auto', minWidth: 0, display: 'flex', flexDirection: 'column', gap: '2px' },
559
+ optionName: { fontSize: '0.92em', fontWeight: 500 },
560
+ optionStatus: { fontSize: '0.82em', opacity: 0.62 },
561
+ }
562
+
563
+ /**
564
+ * Same-origin API base, resolved against the document so a deployment under
565
+ * a sub-path still reaches its own host.
566
+ */
567
+ const API = (() => {
568
+ try { return new URL('api/llm-qoder-cn', document.baseURI).pathname } catch { return '/api/llm-qoder-cn' }
569
+ })()
570
+
571
+ /**
572
+ * Last successful answer per edition, so reopening a settings page paints
573
+ * the previous content immediately and refreshes behind it.
574
+ *
575
+ * The cache is deliberately stale-while-revalidate: the page never waits on
576
+ * the CLI just to show something it showed a minute ago. Both the model list
577
+ * and the quota reading are cached separately because they are fetched by
578
+ * different cards. `localStorage` keeps the snapshot across a page reload;
579
+ * the in-memory map covers a deployment where storage is unavailable.
580
+ */
581
+ const CACHE_PREFIX = 'dsh-agent-sdk-bridge/cache/v1'
582
+ const cacheMemory = new Map()
583
+
584
+ function cacheKey(brand, kind) {
585
+ return `${CACHE_PREFIX}:${brand}:${kind}`
586
+ }
587
+
588
+ function readCache(brand, kind) {
589
+ const key = cacheKey(brand, kind)
590
+ const held = cacheMemory.get(key)
591
+ if (held !== undefined) return held
592
+ try {
593
+ const raw = window.localStorage.getItem(key)
594
+ if (raw === null) return undefined
595
+ const parsed = JSON.parse(raw)
596
+ cacheMemory.set(key, parsed)
597
+ return parsed
598
+ } catch {
599
+ return undefined
600
+ }
601
+ }
602
+
603
+ function writeCache(brand, kind, value) {
604
+ const key = cacheKey(brand, kind)
605
+ cacheMemory.set(key, value)
606
+ try {
607
+ window.localStorage.setItem(key, JSON.stringify(value))
608
+ } catch {
609
+ /* private mode or a full quota: the in-memory copy still works */
610
+ }
611
+ }
612
+
613
+ /** Call the plugin's model API. */
614
+ async function api(path, options) {
615
+ const { timeout = 30_000, ...rest } = options ?? {}
616
+ const ctrl = new AbortController()
617
+ const timer = setTimeout(() => ctrl.abort(), timeout)
618
+ try {
619
+ const response = await fetch(`${API}${path}`, { ...rest, signal: ctrl.signal })
620
+ const text = await response.text()
621
+ let payload
622
+ try { payload = text === '' ? {} : JSON.parse(text) } catch { payload = { error: text.slice(0, 200) } }
623
+ if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`)
624
+ return payload
625
+ } finally {
626
+ clearTimeout(timer)
627
+ }
628
+ }
629
+
630
+ /**
631
+ * How long a settings write may take before the page gives up on it.
632
+ *
633
+ * A config write is a round trip to the host, which commits the value into
634
+ * the running plugin before it answers, so this is not a normal-path limit —
635
+ * it is a floor under the UI. Without it a wire call that never settles
636
+ * leaves every control disabled forever, which is exactly how this page was
637
+ * previously reported as frozen.
638
+ */
639
+ const WRITE_TIMEOUT_MS = 20_000
640
+
641
+ /** Settle with `promise`, or reject with `message` once `ms` elapse. */
642
+ function withDeadline(promise, ms, message) {
643
+ return new Promise((resolve, reject) => {
644
+ const timer = setTimeout(() => reject(new Error(message)), ms)
645
+ promise.then(
646
+ value => { clearTimeout(timer); resolve(value) },
647
+ error => { clearTimeout(timer); reject(error) },
648
+ )
649
+ })
650
+ }
651
+
652
+ /** Compact label for a token count. */
653
+ function windowLabel(n) {
654
+ if (typeof n !== 'number' || !Number.isFinite(n)) return '—'
655
+ if (n >= 1_000_000) return `${Number((n / 1_000_000).toFixed(n % 1_000_000 === 0 ? 0 : 1))}M`
656
+ if (n >= 1000) return `${Math.round(n / 1000)}K`
657
+ return String(n)
658
+ }
659
+
660
+ /**
661
+ * The credit multiplier upstream quotes, as a short suffix.
662
+ *
663
+ * `0` renders as 免费 rather than `x0`, matching how the Qoder client shows
664
+ * a free model. A model upstream quoted no multiplier for gets no suffix at
665
+ * all — inventing one would misstate its cost.
666
+ */
667
+ function priceSuffix(t, factor) {
668
+ if (typeof factor !== 'number' || !Number.isFinite(factor) || factor < 0) return ''
669
+ if (factor === 0) return t('free')
670
+ return `x${Number(factor.toFixed(4))}`
671
+ }
672
+
673
+ /** A 0–100 percentage, clamped, or undefined when the value is not a number. */
674
+ function percentOf(value) {
675
+ if (typeof value !== 'number' || !Number.isFinite(value)) return undefined
676
+ return Math.max(0, Math.min(100, value))
677
+ }
678
+
679
+ /** A credit count with group separators; dashes for absent values. */
680
+ function creditsOf(value) {
681
+ if (typeof value !== 'number' || !Number.isFinite(value)) return '—'
682
+ return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
683
+ }
684
+
685
+ /**
686
+ * Whether a timestamp means "no expiry".
687
+ *
688
+ * The quota endpoint reports plan end dates as a sentinel far in the future
689
+ * (year 9999). Rendering that as a date is technically true and practically
690
+ * noise, so it is shown as "never".
691
+ */
692
+ function neverExpires(ms) {
693
+ return typeof ms !== 'number' || !Number.isFinite(ms) || ms <= 0 || ms > Date.now() + 50 * 365 * 24 * 3600 * 1000
694
+ }
695
+
696
+ /** A short local date for an epoch-millisecond value. */
697
+ function dateLabel(ms) {
698
+ try { return new Date(ms).toLocaleDateString('zh-CN') } catch { return String(ms) }
699
+ }
700
+
701
+ /**
702
+ * One quota bucket as a line: label, `remaining / total`, percentage.
703
+ *
704
+ * Both editions quote the same shape (`userQuota`, `addOnQuota`,
705
+ * `orgResourcePackage`), so the three render through one function; a bucket
706
+ * the account does not have is simply not passed in.
707
+ */
708
+ function QuotaLine({ t, label, bucket, fallbackUnit }) {
709
+ if (bucket === undefined || bucket === null) return null
710
+ const total = bucket.total ?? bucket.cap
711
+ const remaining = bucket.remaining
712
+ const used = bucket.used
713
+ // A plan bucket the account does not have is reported as all zeros; an
714
+ // empty line describes nothing, so it is omitted rather than rendered.
715
+ if ((total === undefined || total === 0) && remaining === undefined) return null
716
+ const pct = percentOf(bucket.percentage)
717
+ const unit = bucket.unit ?? fallbackUnit ?? t('usageCredits')
718
+ const amount = remaining !== undefined && total !== undefined
719
+ ? `${t('usageRemaining')} ${creditsOf(remaining)} ${t('usageOf')} ${creditsOf(total)} ${unit}`
720
+ : total !== undefined
721
+ ? `${t('usageUsed')} ${creditsOf(used)} ${t('usageOf')} ${creditsOf(total)} ${unit}`
722
+ : '—'
723
+ return h('div', { style: css.usageLine },
724
+ h('span', { style: css.usageLabel }, label),
725
+ h('span', { style: css.usageValue }, amount),
726
+ pct === undefined ? null : h('span', { style: { opacity: 0.55 } }, `${Number(pct.toFixed(1))}%`),
727
+ )
728
+ }
729
+
730
+ /**
731
+ * Account quota and usage, read through the CLI.
732
+ *
733
+ * This is the same data the Qoder clients show on their account panel: plan,
734
+ * percentage used, remaining credits, add-on package, expiry and the
735
+ * upgrade/usage links. It is fetched from the host (which asks the CLI), not
736
+ * from the provider directly, because only the CLI holds a usable token.
737
+ */
738
+ function UsageCard({ t, brand, refreshSignal }) {
739
+ const [snapshot, setSnapshot] = useState(() => readCache(brand.id, 'usage'))
740
+ const [failure, setFailure] = useState(undefined)
741
+ const [busy, setBusy] = useState(false)
742
+ const ticket = useRef(0)
743
+
744
+ const load = useCallback(async (fresh = false) => {
745
+ const mine = ++ticket.current
746
+ setBusy(true)
747
+ setFailure(undefined)
748
+ try {
749
+ const payload = await api(`/usage?brand=${brand.id}${fresh ? '&fresh=1' : ''}`, { timeout: 45_000 })
750
+ if (mine !== ticket.current) return
751
+ // A failed account lookup (signed out, endpoint down) must not replace
752
+ // the last good reading with an empty card: keep it and say so.
753
+ if (payload?.usage === undefined && payload?.error !== undefined) {
754
+ setFailure(String(payload.error))
755
+ return
756
+ }
757
+ setSnapshot(payload)
758
+ writeCache(brand.id, 'usage', payload)
759
+ } catch (err) {
760
+ if (mine !== ticket.current) return
761
+ setFailure(String(err?.message ?? err))
762
+ } finally {
763
+ if (mine === ticket.current) setBusy(false)
764
+ }
765
+ }, [brand.id])
766
+
767
+ // `refreshSignal` changes after a CLI install or uninstall, both of which
768
+ // make the cached account reading describe a machine state that is gone.
769
+ useEffect(() => { void load() }, [load, refreshSignal])
770
+
771
+ const usage = snapshot?.usage
772
+ const account = snapshot?.account
773
+ const error = failure ?? (snapshot?.usage === undefined && snapshot?.error !== undefined ? String(snapshot.error) : undefined)
774
+ const pct = percentOf(usage?.totalUsagePercentage)
775
+ const plan = account?.subscriptionType ?? usage?.userType ?? t('usageUnknownPlan')
776
+ const identity = account?.name ?? account?.email ?? usage?.userId
777
+ const exceeded = usage?.isQuotaExceeded === true
778
+
779
+ const head = h('div', { style: css.usageHead },
780
+ h('h3', { style: css.h3 }, t('usageTitle')),
781
+ identity === undefined
782
+ ? null
783
+ : h('span', { style: { ...css.note, opacity: 0.7 } }, `${t('usageAccount')} ${identity}`),
784
+ h('button', {
785
+ style: { ...css.btn, marginLeft: 'auto' },
786
+ disabled: busy,
787
+ onClick: () => void load(true),
788
+ }, busy ? t('refreshing') : t('usageRefresh')),
789
+ )
790
+
791
+ if (snapshot === undefined || usage === undefined) {
792
+ return h('div', { style: css.usageCard },
793
+ head,
794
+ error === undefined
795
+ ? h('div', { style: css.note }, t('usageLoading'))
796
+ : h('div', { style: css.err }, `${t('usageUnavailable')}:${error}`),
797
+ error === undefined
798
+ ? null
799
+ : h('div', { style: css.bar },
800
+ h('button', { style: css.btn, disabled: busy, onClick: () => void load(true) }, t('usageRetry')),
801
+ ),
802
+ )
803
+ }
804
+
805
+ const expiry = usage?.expiresAt
806
+ return h('div', { style: css.usageCard },
807
+ head,
808
+ h('div', { style: css.usageLine },
809
+ h('span', { style: css.usageLabel }, t('usagePlan')),
810
+ h('span', { style: css.usageValue }, plan),
811
+ exceeded ? h('span', { style: { ...css.err, fontWeight: 600 } }, t('usageExceeded')) : null,
812
+ pct === undefined ? null : h('span', { style: css.usagePct }, `${Number(pct.toFixed(1))}%`),
813
+ ),
814
+ pct === undefined ? null : h('div', { style: css.progressOuter },
815
+ h('div', {
816
+ style: { ...css.progressInner, width: `${pct}%`, ...(exceeded ? css.progressDanger : {}) },
817
+ }),
818
+ ),
819
+ h(QuotaLine, { t, label: t('usagePlanQuota'), bucket: usage?.userQuota }),
820
+ h(QuotaLine, { t, label: t('usageAddOn'), bucket: usage?.addOnQuota }),
821
+ h(QuotaLine, { t, label: t('usageOrgPackage'), bucket: usage?.orgResourcePackage }),
822
+ h('div', { style: css.usageFoot },
823
+ expiry === undefined || neverExpires(expiry)
824
+ ? h('span', null, `${t('usageExpires')} ${t('usageNever')}`)
825
+ : h('span', null, `${t('usageExpires')} ${dateLabel(expiry)}`),
826
+ snapshot?.at === undefined ? null : h('span', null, `${t('usageUpdated')} ${new Date(snapshot.at).toLocaleTimeString('zh-CN')}`),
827
+ typeof usage?.addOnQuota?.detailUrl === 'string'
828
+ ? h('a', { href: usage.addOnQuota.detailUrl, target: '_blank', rel: 'noreferrer', style: css.link }, t('usageDetail'))
829
+ : null,
830
+ typeof usage?.upgradeUrl === 'string' && usage.upgradeUrl !== ''
831
+ ? h('a', { href: usage.upgradeUrl, target: '_blank', rel: 'noreferrer', style: css.link }, t('usageUpgrade'))
832
+ : null,
833
+ failure === undefined
834
+ ? null
835
+ : h('span', { style: css.err }, `${t('usageStale')}:${failure}`),
836
+ ),
837
+ )
838
+ }
839
+
840
+ /**
841
+ * CodeBuddy's account card: region choice, browser login/logout and the
842
+ * signed-in account.
843
+ *
844
+ * The region is a config write (the host starts the CLI with it), but the
845
+ * card does not wait for it: the target region's snapshot paints first and
846
+ * the live account read follows. Both regions keep their own saved login,
847
+ * so switching back does not open the browser again.
848
+ */
849
+ function codeBuddySnapshot(region) {
850
+ const cached = readCache('codebuddy', `snapshot:${region}`)
851
+ return cached !== null && typeof cached === 'object' ? cached : undefined
852
+ }
853
+
854
+ function rememberCodeBuddy(region, patch) {
855
+ const previous = codeBuddySnapshot(region) ?? {}
856
+ writeCache('codebuddy', `snapshot:${region}`, { ...previous, ...patch, at: Date.now() })
857
+ }
858
+
859
+ function CodeBuddyCard({ t, ctx, brand, refreshSignal, onSignedIn, onAuthChange, onRegionChange }) {
860
+ const form = ctx.configForms.get(NS)
861
+ const subscribe = useCallback(listener => form.subscribe(listener), [form])
862
+ const read = useCallback(() => form.getSnapshot(), [form])
863
+ const snapshot = useSyncExternalStore(subscribe, read)
864
+ const value = snapshot?.value ?? {}
865
+ const configuredRegion = value.codebuddyRegion === 'cn' ? 'cn' : 'global'
866
+ const [region, setRegionState] = useState(configuredRegion)
867
+ const regionRef = useRef(configuredRegion)
868
+ const initial = codeBuddySnapshot(configuredRegion)
869
+ const [auth, setAuth] = useState(initial?.auth)
870
+ const [account, setAccount] = useState(initial?.account)
871
+ const [error, setError] = useState(undefined)
872
+ const [busy, setBusy] = useState(false)
873
+ const lastRunning = useRef(false)
874
+ const signingIn = auth?.running === true
875
+ const accountFields = account?.account ?? {}
876
+ const accountSignedIn = account?.error === undefined
877
+ && ['uid', 'userName', 'email', 'organization', 'subscriptionType']
878
+ .some(key => typeof accountFields[key] === 'string' && accountFields[key] !== '')
879
+ // The host's status is authoritative once it has answered; the account
880
+ // reading only covers the first paint before that answer arrives.
881
+ const signedIn = auth === undefined ? accountSignedIn : auth.signedIn === true
882
+ const resolved = auth !== undefined || account !== undefined
883
+
884
+ const applySnapshot = useCallback(target => {
885
+ const cached = codeBuddySnapshot(target)
886
+ setAuth(cached?.auth)
887
+ setAccount(cached?.account)
888
+ }, [])
889
+
890
+ const loadAccount = useCallback(async (fresh = false, target = regionRef.current) => {
891
+ try {
892
+ const payload = await api(`/usage?brand=codebuddy&region=${target}${fresh ? '&fresh=1' : ''}`, { timeout: 45_000 })
893
+ if (regionRef.current !== target) return
894
+ setAccount(payload)
895
+ rememberCodeBuddy(target, { account: payload })
896
+ // A quota 401 clears the server's credential; mirror that here so the
897
+ // button flips back to 登录 without waiting for a page reload.
898
+ if (typeof payload?.signedIn === 'boolean') {
899
+ const next = { running: false, region: target, signedIn: payload.signedIn }
900
+ setAuth(previous => (previous?.running === true ? previous : next))
901
+ rememberCodeBuddy(target, { auth: next })
902
+ }
903
+ } catch (err) {
904
+ if (regionRef.current !== target) return
905
+ setAccount({ error: String(err?.message ?? err) })
906
+ }
907
+ }, [])
908
+
909
+ const poll = useCallback(async (target = regionRef.current) => {
910
+ try {
911
+ const next = await api(`/auth?brand=codebuddy&region=${target}`, { timeout: 10_000 })
912
+ if (regionRef.current !== target) return
913
+ setAuth(next)
914
+ rememberCodeBuddy(target, { auth: next })
915
+ if (lastRunning.current && next.running === false) {
916
+ lastRunning.current = false
917
+ if (next.error === undefined) await loadAccount(true, target)
918
+ }
919
+ if (next.running === true) lastRunning.current = true
920
+ } catch (err) {
921
+ if (regionRef.current !== target) return
922
+ setError(String(err?.message ?? err))
923
+ }
924
+ }, [loadAccount])
925
+
926
+ // Paint the target region from its snapshot, then verify in the background.
927
+ useEffect(() => {
928
+ regionRef.current = region
929
+ applySnapshot(region)
930
+ setError(undefined)
931
+ void poll(region)
932
+ void loadAccount(false, region)
933
+ const timer = setTimeout(() => { void loadAccount(true, region) }, 250)
934
+ return () => clearTimeout(timer)
935
+ }, [region, refreshSignal, applySnapshot, loadAccount, poll])
936
+
937
+ // A config edit from elsewhere (or a reload) becomes the new selection.
938
+ useEffect(() => {
939
+ if (configuredRegion === regionRef.current) return
940
+ setRegionState(configuredRegion)
941
+ regionRef.current = configuredRegion
942
+ applySnapshot(configuredRegion)
943
+ }, [configuredRegion, applySnapshot])
944
+
945
+ useEffect(() => {
946
+ if (auth?.running !== true) return undefined
947
+ const timer = setInterval(() => { void poll(region) }, 1500)
948
+ return () => clearInterval(timer)
949
+ }, [auth?.running, poll, region])
950
+
951
+ useEffect(() => { if (resolved) onAuthChange?.(signedIn) }, [resolved, signedIn, onAuthChange])
952
+
953
+ const setRegion = useCallback(next => {
954
+ if (next === regionRef.current) return
955
+ // Local paint first; the config write is only needed by the adapter.
956
+ regionRef.current = next
957
+ lastRunning.current = false
958
+ setRegionState(next)
959
+ applySnapshot(next)
960
+ setError(undefined)
961
+ onRegionChange?.(next)
962
+ void (async () => {
963
+ try {
964
+ const accepted = await withDeadline(form.set('codebuddyRegion', next), WRITE_TIMEOUT_MS, t('timeout'))
965
+ if (accepted === false) throw new Error(t('saveFailed'))
966
+ if (regionRef.current === next) onSignedIn?.()
967
+ } catch (err) {
968
+ if (regionRef.current !== next) return
969
+ setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
970
+ const fallback = form.getSnapshot()?.value?.codebuddyRegion === 'cn' ? 'cn' : 'global'
971
+ regionRef.current = fallback
972
+ setRegionState(fallback)
973
+ applySnapshot(fallback)
974
+ onRegionChange?.(fallback)
975
+ }
976
+ })()
977
+ }, [applySnapshot, form, onRegionChange, onSignedIn, t])
978
+
979
+ const startLogin = useCallback(async () => {
980
+ const target = regionRef.current
981
+ setBusy(true)
982
+ setError(undefined)
983
+ try {
984
+ const next = await api('/auth', {
985
+ method: 'POST',
986
+ headers: { 'content-type': 'application/json' },
987
+ body: JSON.stringify({ brand: 'codebuddy', region: target, action: 'login' }),
988
+ timeout: 20_000,
989
+ })
990
+ if (regionRef.current !== target) return
991
+ setAuth(next)
992
+ rememberCodeBuddy(target, { auth: next })
993
+ if (next.running === true) lastRunning.current = true
994
+ } catch (err) {
995
+ if (regionRef.current !== target) return
996
+ setError(`${t('codebuddyLoginFailed')}:${String(err?.message ?? err)}`)
997
+ } finally {
998
+ setBusy(false)
999
+ }
1000
+ }, [t])
1001
+
1002
+ const logout = useCallback(async () => {
1003
+ if (typeof window.confirm === 'function' && !window.confirm(t('codebuddyConfirmLogout'))) return
1004
+ const target = regionRef.current
1005
+ setBusy(true)
1006
+ setError(undefined)
1007
+ try {
1008
+ const next = await api('/auth', {
1009
+ method: 'POST',
1010
+ headers: { 'content-type': 'application/json' },
1011
+ body: JSON.stringify({ brand: 'codebuddy', region: target, action: 'logout' }),
1012
+ timeout: 20_000,
1013
+ })
1014
+ if (regionRef.current !== target) return
1015
+ setAuth(next)
1016
+ setAccount(undefined)
1017
+ rememberCodeBuddy(target, { auth: next, account: undefined })
1018
+ onAuthChange?.(false)
1019
+ await loadAccount(true, target)
1020
+ } catch (err) {
1021
+ if (regionRef.current !== target) return
1022
+ // The host clears its local credential even when the CLI refuses the
1023
+ // logout, so the card must not keep presenting the account.
1024
+ const signedOut = { running: false, region: target, signedIn: false }
1025
+ setAuth(signedOut)
1026
+ setAccount(undefined)
1027
+ rememberCodeBuddy(target, { auth: signedOut, account: undefined })
1028
+ onAuthChange?.(false)
1029
+ setError(String(err?.message ?? err))
1030
+ } finally {
1031
+ setBusy(false)
1032
+ }
1033
+ }, [loadAccount, onAuthChange, t])
1034
+
1035
+ const accountText = account?.account === undefined
1036
+ ? (account?.error ?? t('codebuddyAccountUnknown'))
1037
+ : [account.account.email, account.account.organization, account.account.subscriptionType]
1038
+ .filter(part => typeof part === 'string' && part.length > 0)
1039
+ .join(' · ')
1040
+ const quota = account?.quota
1041
+ const quotaPct = quota !== undefined && quota.total > 0
1042
+ ? Math.max(0, Math.min(100, (quota.used / quota.total) * 100))
1043
+ : undefined
1044
+ const packages = Array.isArray(quota?.packages)
1045
+ ? [...quota.packages].sort((a, b) => (a.end ?? Number.MAX_SAFE_INTEGER) - (b.end ?? Number.MAX_SAFE_INTEGER)).slice(0, 4)
1046
+ : []
1047
+ // The website's own usage page, under the profile the CLI login belongs
1048
+ // to. Both regions serve it at the same path.
1049
+ const usageLink = h('a', {
1050
+ href: region === 'cn'
1051
+ ? 'https://copilot.tencent.com/profile/plans-usage'
1052
+ : 'https://www.codebuddy.ai/profile/plans-usage',
1053
+ target: '_blank',
1054
+ rel: 'noreferrer',
1055
+ style: css.link,
1056
+ }, t('usageDetail'))
1057
+
1058
+ return h('div', { style: css.usageCard },
1059
+ h('div', { style: css.usageHead },
1060
+ h('h3', { style: css.h3 }, t('codebuddyAuthTitle')),
1061
+ h('span', { style: { ...css.note, opacity: 0.7 } }, signedIn ? t('codebuddySignedIn') : t('codebuddyNotLoggedIn')),
1062
+ signedIn
1063
+ ? h('button', { style: { ...css.btn, marginLeft: 'auto' }, disabled: busy, onClick: () => void loadAccount(true) }, t('usageRefresh'))
1064
+ : null,
1065
+ ),
1066
+ h('div', { style: css.note }, t('codebuddyAuthHint')),
1067
+ h('div', { style: css.usageLine },
1068
+ h('span', { style: css.usageLabel }, t('codebuddyRegionLabel')),
1069
+ h('select', {
1070
+ style: css.select,
1071
+ value: region,
1072
+ disabled: busy,
1073
+ onChange: event => { setRegion(event.target.value) },
1074
+ },
1075
+ h('option', { key: 'global', value: 'global' }, t('codebuddyRegionGlobal')),
1076
+ h('option', { key: 'cn', value: 'cn' }, t('codebuddyRegionCn')),
1077
+ ),
1078
+ h('button', {
1079
+ style: signedIn ? { ...css.btn, ...css.btnAlert } : css.btn,
1080
+ disabled: busy || signingIn,
1081
+ onClick: () => { if (signedIn) void logout(); else void startLogin() },
1082
+ }, signingIn ? t('codebuddyLoggingIn') : signedIn ? t('codebuddyLogout') : t('codebuddyLogin')),
1083
+ ),
1084
+ signedIn
1085
+ ? h('div', { style: css.usageLine },
1086
+ h('span', { style: css.usageLabel }, t('usageAccount')),
1087
+ h('span', { style: css.usageValue }, accountText),
1088
+ )
1089
+ : h('div', { style: css.note }, t('codebuddyLoginPrompt')),
1090
+ signedIn
1091
+ ? (quota === undefined
1092
+ ? (account?.quotaError !== undefined
1093
+ ? h('div', { style: css.err }, `${t('codebuddyQuotaFailed')}:${account.quotaError}`)
1094
+ : h('div', { style: css.note }, t('codebuddyNoQuota')))
1095
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '10px' } },
1096
+ h('div', { style: css.usageLine },
1097
+ h('span', { style: css.usageLabel }, t('codebuddyQuotaTitle')),
1098
+ h('span', { style: css.usageValue },
1099
+ `${t('usageRemaining')} ${creditsOf(quota.remaining)} ${t('usageOf')} ${creditsOf(quota.total)} ${t('usageCredits')}`),
1100
+ quotaPct === undefined ? null : h('span', { style: css.usagePct }, `${quotaPct.toFixed(1)}%`),
1101
+ ),
1102
+ quotaPct === undefined ? null : h('div', { style: css.progressOuter },
1103
+ h('div', { style: { ...css.progressInner, width: `${quotaPct}%` } }),
1104
+ ),
1105
+ packages.length === 0 ? null : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
1106
+ h('div', { style: css.note }, t('codebuddyQuotaPackages')),
1107
+ packages.map((pkg, index) => h('div', { key: `${pkg.name}-${index}`, style: css.usageLine },
1108
+ h('span', { style: { ...css.usageLabel, minWidth: '160px' } }, pkg.name || '—'),
1109
+ h('span', null, `${creditsOf(pkg.used)} / ${creditsOf(pkg.total)}`),
1110
+ pkg.end === undefined ? null : h('span', { style: { opacity: 0.55 } }, dateLabel(pkg.end)),
1111
+ )),
1112
+ ),
1113
+ h('div', { style: css.usageFoot },
1114
+ quota.cycleEnd === undefined ? null : h('span', null, `${t('codebuddyQuotaExpires')} ${dateLabel(quota.cycleEnd)}`),
1115
+ usageLink,
1116
+ ),
1117
+ ))
1118
+ : null,
1119
+ signedIn && quota === undefined
1120
+ ? h('div', { style: css.usageFoot }, usageLink)
1121
+ : null,
1122
+ typeof auth?.url === 'string' && signingIn
1123
+ ? h('div', { style: css.usageLine },
1124
+ h('a', { href: auth.url, target: '_blank', rel: 'noreferrer', style: css.link }, t('codebuddyOpenUrl')),
1125
+ h('span', { style: css.note }, t('codebuddyLoginStarted')),
1126
+ )
1127
+ : null,
1128
+ auth?.error !== undefined ? h('div', { style: css.err }, `${t('codebuddyLoginFailed')}:${auth.error}`) : null,
1129
+ error !== undefined ? h('div', { style: css.err }, error) : null,
1130
+ )
1131
+ }
1132
+
1133
+ function minimaxSnapshot(region) {
1134
+ const cached = readCache('minimax', `snapshot:${region}`)
1135
+ return cached !== null && typeof cached === 'object' ? cached : undefined
1136
+ }
1137
+
1138
+ function rememberMinimax(region, patch) {
1139
+ const previous = minimaxSnapshot(region) ?? {}
1140
+ writeCache('minimax', `snapshot:${region}`, { ...previous, ...patch, at: Date.now() })
1141
+ }
1142
+
1143
+ /**
1144
+ * MiniMax Code's account card: region, CLI install state and browser login.
1145
+ *
1146
+ * The login is a CLI process: `mcode login` opens the browser and writes an
1147
+ * auth file. The card polls the host while that process runs, then re-reads
1148
+ * the account so the model page can unlock.
1149
+ */
1150
+ function MinimaxCard({ ctx, t, brand, refreshSignal, onAuthChange, onRegionChange, onUsage }) {
1151
+ const form = ctx.configForms.get(NS)
1152
+ const subscribe = useCallback(listener => form.subscribe(listener), [form])
1153
+ const read = useCallback(() => form.getSnapshot(), [form])
1154
+ const snapshot = useSyncExternalStore(subscribe, read)
1155
+ const value = snapshot?.value ?? {}
1156
+ const configuredRegion = value.minimaxRegion === 'global' ? 'global' : 'cn'
1157
+ const [region, setRegionState] = useState(configuredRegion)
1158
+ const regionRef = useRef(configuredRegion)
1159
+ const initial = minimaxSnapshot(configuredRegion)
1160
+ const [auth, setAuth] = useState(initial?.auth)
1161
+ const [usage, setUsage] = useState(initial?.usage)
1162
+ const [setup, setSetup] = useState(undefined)
1163
+ const [showLog, setShowLog] = useState(false)
1164
+ const [busy, setBusy] = useState(false)
1165
+ const [error, setError] = useState(undefined)
1166
+ const lastRunning = useRef(false)
1167
+ /**
1168
+ * The region the account reading was last requested for.
1169
+ *
1170
+ * A switch must re-probe the network instead of serving the previous
1171
+ * region's cached verdict: the user changes region precisely because the
1172
+ * machine was (or is now) on the other side of the border, and the old
1173
+ * reading can be up to a minute stale. The first mount keeps the
1174
+ * snapshot-first behaviour and reads from cache.
1175
+ */
1176
+ const lastUsageRegion = useRef(configuredRegion)
1177
+ const signingIn = auth?.running === true
1178
+ const signedIn = auth?.signedIn === true
1179
+ const runningSetup = setup?.running === true
1180
+ const installed = setup?.installed === true || usage?.installed === true
1181
+
1182
+ const applySnapshot = useCallback(target => {
1183
+ const cached = minimaxSnapshot(target)
1184
+ setAuth(cached?.auth)
1185
+ setUsage(cached?.usage)
1186
+ }, [])
1187
+
1188
+ const loadUsage = useCallback(async (fresh = false, target = regionRef.current) => {
1189
+ try {
1190
+ const payload = await api(`/usage?brand=minimax&region=${target}${fresh ? '&fresh=1' : ''}`, { timeout: 30_000 })
1191
+ if (regionRef.current !== target) return
1192
+ setUsage(payload)
1193
+ rememberMinimax(target, { usage: payload })
1194
+ onUsage?.(payload)
1195
+ if (typeof payload?.signedIn === 'boolean') {
1196
+ setAuth(previous => (previous?.running === true
1197
+ ? previous
1198
+ : { ...previous, running: false, region: target, signedIn: payload.signedIn }))
1199
+ }
1200
+ } catch (err) {
1201
+ if (regionRef.current !== target) return
1202
+ setUsage({ error: String(err?.message ?? err) })
1203
+ }
1204
+ }, [onUsage])
1205
+
1206
+ const pollAuth = useCallback(async (target = regionRef.current) => {
1207
+ try {
1208
+ const next = await api(`/auth?brand=minimax&region=${target}`, { timeout: 10_000 })
1209
+ if (regionRef.current !== target) return
1210
+ setAuth(next)
1211
+ rememberMinimax(target, { auth: next })
1212
+ if (lastRunning.current && next.running === false) {
1213
+ lastRunning.current = false
1214
+ if (next.signedIn === true) {
1215
+ await loadUsage(true, target)
1216
+ onAuthChange?.(true)
1217
+ }
1218
+ }
1219
+ if (next.running === true) lastRunning.current = true
1220
+ } catch (err) {
1221
+ if (regionRef.current !== target) return
1222
+ setError(String(err?.message ?? err))
1223
+ }
1224
+ }, [loadUsage, onAuthChange])
1225
+
1226
+ const pollSetup = useCallback(async () => {
1227
+ try {
1228
+ setSetup(await api('/setup?brand=minimax', { timeout: 10_000 }))
1229
+ } catch {
1230
+ /* a host without the installer route leaves this group empty */
1231
+ }
1232
+ }, [])
1233
+
1234
+ useEffect(() => {
1235
+ regionRef.current = region
1236
+ applySnapshot(region)
1237
+ setError(undefined)
1238
+ const switched = lastUsageRegion.current !== region
1239
+ lastUsageRegion.current = region
1240
+ void pollAuth(region)
1241
+ // `fresh` drops both the 60s account cache and the 30s region-access
1242
+ // verdict, so a switch always re-probes the network before deciding.
1243
+ void loadUsage(switched, region)
1244
+ void pollSetup()
1245
+ }, [region, refreshSignal, applySnapshot, loadUsage, pollAuth, pollSetup])
1246
+
1247
+ useEffect(() => {
1248
+ if (configuredRegion === regionRef.current) return
1249
+ setRegionState(configuredRegion)
1250
+ regionRef.current = configuredRegion
1251
+ applySnapshot(configuredRegion)
1252
+ }, [configuredRegion, applySnapshot])
1253
+
1254
+ useEffect(() => {
1255
+ if (!signingIn) return undefined
1256
+ const timer = setInterval(() => { void pollAuth(region) }, 1500)
1257
+ return () => clearInterval(timer)
1258
+ }, [signingIn, pollAuth, region])
1259
+
1260
+ useEffect(() => {
1261
+ if (!runningSetup) return undefined
1262
+ const timer = setInterval(() => { void pollSetup() }, 1200)
1263
+ return () => clearInterval(timer)
1264
+ }, [runningSetup, pollSetup])
1265
+
1266
+ useEffect(() => {
1267
+ if (!runningSetup && setup?.code === 0) void pollAuth(region)
1268
+ }, [runningSetup, setup?.code, pollAuth, region])
1269
+
1270
+ const authResolved = auth !== undefined
1271
+ useEffect(() => {
1272
+ if (!authResolved) return
1273
+ onAuthChange?.(signedIn)
1274
+ }, [authResolved, signedIn, onAuthChange])
1275
+
1276
+ const setRegion = useCallback(next => {
1277
+ if (next === regionRef.current) return
1278
+ regionRef.current = next
1279
+ lastRunning.current = false
1280
+ setRegionState(next)
1281
+ applySnapshot(next)
1282
+ setError(undefined)
1283
+ onRegionChange?.(next)
1284
+ void (async () => {
1285
+ try {
1286
+ const accepted = await withDeadline(form.set('minimaxRegion', next), WRITE_TIMEOUT_MS, t('timeout'))
1287
+ if (accepted === false) throw new Error(t('saveFailed'))
1288
+ } catch (err) {
1289
+ if (regionRef.current !== next) return
1290
+ setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
1291
+ const fallback = form.getSnapshot()?.value?.minimaxRegion === 'global' ? 'global' : 'cn'
1292
+ regionRef.current = fallback
1293
+ setRegionState(fallback)
1294
+ applySnapshot(fallback)
1295
+ onRegionChange?.(fallback)
1296
+ }
1297
+ })()
1298
+ }, [applySnapshot, form, onRegionChange, t])
1299
+
1300
+ const startLogin = useCallback(async () => {
1301
+ const target = regionRef.current
1302
+ setBusy(true)
1303
+ setError(undefined)
1304
+ try {
1305
+ const next = await api('/auth', {
1306
+ method: 'POST',
1307
+ headers: { 'content-type': 'application/json' },
1308
+ body: JSON.stringify({ brand: 'minimax', region: target, action: 'login' }),
1309
+ timeout: 20_000,
1310
+ })
1311
+ if (regionRef.current !== target) return
1312
+ setAuth(next)
1313
+ rememberMinimax(target, { auth: next })
1314
+ if (next.running === true) lastRunning.current = true
1315
+ } catch (err) {
1316
+ if (regionRef.current !== target) return
1317
+ setError(`${t('minimaxLoginFailed')}:${String(err?.message ?? err)}`)
1318
+ } finally {
1319
+ setBusy(false)
1320
+ }
1321
+ }, [t])
1322
+
1323
+ const logout = useCallback(async () => {
1324
+ if (typeof window.confirm === 'function' && !window.confirm(t('minimaxConfirmLogout'))) return
1325
+ const target = regionRef.current
1326
+ setBusy(true)
1327
+ setError(undefined)
1328
+ try {
1329
+ const next = await api('/auth', {
1330
+ method: 'POST',
1331
+ headers: { 'content-type': 'application/json' },
1332
+ body: JSON.stringify({ brand: 'minimax', region: target, action: 'logout' }),
1333
+ timeout: 30_000,
1334
+ })
1335
+ if (regionRef.current !== target) return
1336
+ setAuth(next)
1337
+ rememberMinimax(target, { auth: next })
1338
+ onAuthChange?.(false)
1339
+ } catch (err) {
1340
+ if (regionRef.current !== target) return
1341
+ setError(`${t('minimaxLoginFailed')}:${String(err?.message ?? err)}`)
1342
+ } finally {
1343
+ setBusy(false)
1344
+ }
1345
+ }, [onAuthChange, t])
1346
+
1347
+ const runSetup = useCallback(async mode => {
1348
+ if (mode === 'uninstall' && typeof window.confirm === 'function' && !window.confirm(t('minimaxConfirmUninstall'))) return
1349
+ setBusy(true)
1350
+ setError(undefined)
1351
+ setShowLog(true)
1352
+ try {
1353
+ setSetup(await api('/setup', {
1354
+ method: 'POST',
1355
+ headers: { 'content-type': 'application/json' },
1356
+ body: JSON.stringify({ brand: 'minimax', mode }),
1357
+ timeout: 15_000,
1358
+ }))
1359
+ } catch (err) {
1360
+ setError(`${t('minimaxCliFailed')}:${String(err?.message ?? err)}`)
1361
+ } finally {
1362
+ setBusy(false)
1363
+ }
1364
+ }, [t])
1365
+
1366
+ const lines = Array.isArray(setup?.lines) ? setup.lines : []
1367
+ const setupBusy = busy || runningSetup
1368
+ const account = usage?.account
1369
+ const plan = usage?.plan
1370
+ const credits = usage?.credits
1371
+ const quotas = Array.isArray(usage?.windows) ? usage.windows : []
1372
+ const planLabel = plan?.kind === 'token-plan'
1373
+ ? t('minimaxPlanTokenPlan')
1374
+ : plan?.kind === 'credits' ? t('minimaxPlanCredits') : t('minimaxPlanFree')
1375
+ const timeLabel = ms => {
1376
+ try {
1377
+ return new Date(ms).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
1378
+ } catch {
1379
+ return String(ms)
1380
+ }
1381
+ }
1382
+
1383
+ const blocked = usage?.regionBlocked === true
1384
+ const hasQuotaData = account !== undefined || plan !== undefined
1385
+ || credits !== undefined || quotas.length > 0
1386
+
1387
+ const quotaBlock = !signedIn
1388
+ ? h('div', { style: css.note }, installed ? t('minimaxNoUsage') : t('minimaxCliRequired'))
1389
+ : blocked
1390
+ ? h('div', { style: css.guide },
1391
+ h('div', { style: css.guideText }, usage?.error ?? t('minimaxIpBlocked')),
1392
+ h('button', {
1393
+ style: { ...css.btn, ...css.btnAlert },
1394
+ disabled: busy,
1395
+ onClick: () => setRegion(region === 'global' ? 'cn' : 'global'),
1396
+ }, region === 'global' ? t('minimaxSwitchToCn') : t('minimaxSwitchToGlobal')),
1397
+ )
1398
+ : usage === undefined
1399
+ ? h('div', { style: css.note }, t('minimaxUsageLoading'))
1400
+ : !hasQuotaData && usage?.error !== undefined
1401
+ ? h('div', { style: css.err }, `${t('minimaxUsageFailed')}:${usage.error}`)
1402
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
1403
+ account === undefined
1404
+ ? null
1405
+ : h('div', { style: css.usageLine },
1406
+ h('span', { style: css.usageLabel }, t('minimaxAccount')),
1407
+ h('span', { style: css.usageValue }, account?.name ?? account?.email ?? t('minimaxAccountUnknown')),
1408
+ ),
1409
+ plan === undefined
1410
+ ? null
1411
+ : h('div', { style: css.usageLine },
1412
+ h('span', { style: css.usageLabel }, t('minimaxPlan')),
1413
+ h('span', { style: css.usageValue }, plan.name ?? planLabel),
1414
+ plan.hasTokenPlan === true ? h('span', { style: { ...css.tag, marginLeft: '6px' } }, t('minimaxPlanTokenPlan')) : null,
1415
+ plan.expiresAt === undefined
1416
+ ? null
1417
+ : h('span', { style: css.note }, `${t('minimaxExpires')} ${dateLabel(plan.expiresAt)}`),
1418
+ ),
1419
+ credits === undefined
1420
+ ? null
1421
+ : h('div', { style: css.usageLine },
1422
+ h('span', { style: css.usageLabel }, t('minimaxCredits')),
1423
+ h('span', { style: css.usageValue }, creditsOf(credits.remaining)),
1424
+ typeof credits.purchasedRemaining === 'number' && credits.purchasedRemaining > 0
1425
+ ? h('span', { style: css.note }, `${t('minimaxCreditsPurchased')} ${creditsOf(credits.purchasedRemaining)}`)
1426
+ : null,
1427
+ typeof credits.freeRemaining === 'number' && credits.freeRemaining > 0
1428
+ ? h('span', { style: css.note }, `${t('minimaxCreditsFree')} ${creditsOf(credits.freeRemaining)}`)
1429
+ : null,
1430
+ ),
1431
+ quotas.length === 0
1432
+ ? h('div', { style: css.note }, t('minimaxQuotaNone'))
1433
+ : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '7px' } },
1434
+ quotas.map(window => {
1435
+ const remaining = typeof window.remainingPercent === 'number' ? window.remainingPercent : undefined
1436
+ const used = remaining === undefined ? undefined : 100 - remaining
1437
+ return h('div', { key: window.id, style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
1438
+ h('div', { style: css.usageLine },
1439
+ h('span', { style: css.usageLabel }, window.label),
1440
+ h('span', { style: css.usageValue }, window.unlimited
1441
+ ? t('minimaxQuotaUnlimited')
1442
+ : remaining === undefined
1443
+ ? (window.remainingCount === undefined ? '—' : `${creditsOf(window.remainingCount)} / ${creditsOf(window.totalCount ?? 0)}`)
1444
+ : `${t('minimaxQuotaRemaining')} ${remaining}%`),
1445
+ typeof window.resetAt === 'number'
1446
+ ? h('span', { style: css.note }, `${t('minimaxQuotaReset')} ${timeLabel(window.resetAt)}`)
1447
+ : null,
1448
+ ),
1449
+ used === undefined || window.unlimited
1450
+ ? null
1451
+ : h('div', { style: css.progressOuter },
1452
+ h('div', {
1453
+ style: {
1454
+ ...css.progressInner,
1455
+ width: `${used}%`,
1456
+ ...(remaining !== undefined && remaining < 20 ? css.progressDanger : {}),
1457
+ },
1458
+ }),
1459
+ ),
1460
+ )
1461
+ }),
1462
+ ),
1463
+ usage?.error !== undefined ? h('div', { style: css.err }, `${t('minimaxUsageFailed')}:${usage.error}`) : null,
1464
+ )
1465
+ return h('div', { style: css.usageCard },
1466
+ h('div', { style: css.usageHead },
1467
+ h('h3', { style: css.h3 }, t('minimaxAuthTitle')),
1468
+ h('span', { style: { ...css.note, opacity: 0.7 } },
1469
+ blocked ? t('minimaxRegionBlockedShort') : signedIn ? t('minimaxSignedIn') : t('minimaxNotLoggedIn')),
1470
+ signedIn
1471
+ ? h('button', { style: { ...css.btn, marginLeft: 'auto' }, disabled: busy, onClick: () => void loadUsage(true) }, t('usageRefresh'))
1472
+ : null,
1473
+ ),
1474
+ h('div', { style: css.note }, t('minimaxAuthHint')),
1475
+ h('div', { style: css.usageLine },
1476
+ h('span', { style: css.usageLabel }, t('minimaxRegionLabel')),
1477
+ h('select', {
1478
+ style: css.select,
1479
+ value: region,
1480
+ disabled: busy,
1481
+ onChange: event => { setRegion(event.target.value) },
1482
+ },
1483
+ h('option', { key: 'cn', value: 'cn' }, t('minimaxRegionCn')),
1484
+ h('option', { key: 'global', value: 'global' }, t('minimaxRegionGlobal')),
1485
+ ),
1486
+ h('button', {
1487
+ style: signedIn ? { ...css.btn, ...css.btnAlert } : css.btn,
1488
+ disabled: busy || signingIn || (!signedIn && !installed),
1489
+ onClick: () => { if (signedIn) void logout(); else void startLogin() },
1490
+ }, signingIn ? t('minimaxLoggingIn') : signedIn ? t('minimaxLogout') : t('minimaxLogin')),
1491
+ ),
1492
+ quotaBlock,
1493
+ typeof auth?.expiresAt === 'number' && !blocked
1494
+ ? h('div', { style: css.usageFoot },
1495
+ h('span', null, `${t('minimaxExpires')} ${dateLabel(auth.expiresAt)}`),
1496
+ )
1497
+ : null,
1498
+ typeof auth?.url === 'string' && signingIn
1499
+ ? h('div', { style: css.usageLine },
1500
+ h('a', { href: auth.url, target: '_blank', rel: 'noreferrer', style: css.link }, t('minimaxOpenUrl')),
1501
+ h('span', { style: css.note }, t('minimaxLoginStarted')),
1502
+ )
1503
+ : null,
1504
+ auth?.error !== undefined ? h('div', { style: css.err }, `${t('minimaxLoginFailed')}:${auth.error}`) : null,
1505
+ h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
1506
+ h('div', { style: css.usageLine },
1507
+ h('span', { style: css.usageLabel }, t('minimaxCliGroup')),
1508
+ h('span', { style: css.usageValue }, installed ? t('minimaxCliInstalled') : t('minimaxCliMissing')),
1509
+ h('button', {
1510
+ style: { ...css.btn, marginLeft: 'auto' },
1511
+ disabled: setupBusy,
1512
+ onClick: () => void runSetup('install'),
1513
+ }, runningSetup && setup?.mode === 'install' ? t('minimaxCliInstalling') : t('minimaxCliInstall')),
1514
+ installed
1515
+ ? h('button', {
1516
+ style: { ...css.btn, ...css.btnAlert },
1517
+ disabled: setupBusy,
1518
+ onClick: () => void runSetup('uninstall'),
1519
+ }, runningSetup && setup?.mode === 'uninstall' ? t('minimaxCliUninstalling') : t('minimaxCliUninstall'))
1520
+ : null,
1521
+ ),
1522
+ h('div', { style: css.note }, t('minimaxCliHint')),
1523
+ lines.length === 0
1524
+ ? null
1525
+ : h('div', null,
1526
+ h('button', {
1527
+ style: css.btn,
1528
+ onClick: () => setShowLog(value => !value),
1529
+ }, showLog ? t('minimaxHideOutput') : t('minimaxShowOutput')),
1530
+ showLog ? h('pre', { style: css.log }, lines.join('\n')) : null,
1531
+ ),
1532
+ ),
1533
+ error !== undefined ? h('div', { style: css.err }, error) : null,
1534
+ )
1535
+ }
1536
+
1537
+ /**
1538
+ * The model table plus the advanced block.
1539
+ *
1540
+ * Each change posts and then adopts the host's returned list, so the page
1541
+ * shows what the adapter will actually do rather than what the click hoped.
1542
+ * A per-request ticket keeps a slow earlier answer from overwriting a newer
1543
+ * one when the user clicks quickly.
1544
+ */
1545
+ function SettingsPage({ ctx, t, brand }) {
1546
+ const form = ctx.configForms.get(NS)
1547
+ /** CodeBuddy and MiniMax both have two login regions and their own catalogs. */
1548
+ const regional = brand.id === 'codebuddy' || brand.id === 'minimax'
1549
+ const initialSnapshot = form.getSnapshot()?.value ?? {}
1550
+ const initialRegion = brand.id === 'minimax'
1551
+ ? (initialSnapshot.minimaxRegion === 'global' ? 'global' : 'cn')
1552
+ : (initialSnapshot.codebuddyRegion === 'cn' ? 'cn' : 'global')
1553
+ const snapshotFor = target => brand.id === 'minimax'
1554
+ ? minimaxSnapshot(target)
1555
+ : codeBuddySnapshot(target)
1556
+ // Each login region has its own catalog, deny-list and windows; the page
1557
+ // key follows the region so switching shows that region's choices.
1558
+ const [region, setRegion] = useState(initialRegion)
1559
+ const modelsKind = regional ? `models:${region}` : 'models'
1560
+ const cached = readCache(brand.id, modelsKind)
1561
+ const [models, setModels] = useState(() => Array.isArray(cached?.rows) ? cached.rows : undefined)
1562
+ const [catalogNotice, setCatalogNotice] = useState(() =>
1563
+ typeof cached?.notice === 'string' ? cached.notice : undefined)
1564
+ const [signedIn, setSignedIn] = useState(() =>
1565
+ regional
1566
+ ? cached?.signedIn === true || snapshotFor(initialRegion)?.auth?.signedIn === true
1567
+ : undefined)
1568
+ const [error, setError] = useState(undefined)
1569
+ const [status, setStatus] = useState(undefined)
1570
+ const [busy, setBusy] = useState(false)
1571
+ const [query, setQuery] = useState('')
1572
+ const [onlyEnabled, setOnlyEnabled] = useState(false)
1573
+ const [showAdvanced, setShowAdvanced] = useState(false)
1574
+ const [usageTick, setUsageTick] = useState(0)
1575
+ const ticket = useRef(0)
1576
+ /** Separate from `ticket`: `load()` bumps that one, so sharing it would
1577
+ * make every write look stale the moment its own refresh landed. */
1578
+ const writeTicket = useRef(0)
1579
+
1580
+ const subscribe = useCallback(listener => form.subscribe(listener), [form])
1581
+ const read = useCallback(() => form.getSnapshot(), [form])
1582
+ const snapshot = useSyncExternalStore(subscribe, read)
1583
+
1584
+ const configuredRegion = brand.id === 'minimax'
1585
+ ? (snapshot?.value?.minimaxRegion === 'global' ? 'global' : 'cn')
1586
+ : (snapshot?.value?.codebuddyRegion === 'cn' ? 'cn' : 'global')
1587
+ /**
1588
+ * The region the user just picked, until the config write lands.
1589
+ *
1590
+ * Without this, a snapshot that still carries the old value would pull
1591
+ * the selection back mid-switch.
1592
+ */
1593
+ const pendingRegion = useRef(null)
1594
+ useEffect(() => {
1595
+ if (!regional) return
1596
+ if (pendingRegion.current !== null) {
1597
+ if (pendingRegion.current === configuredRegion) pendingRegion.current = null
1598
+ return
1599
+ }
1600
+ setRegion(current => (current === configuredRegion ? current : configuredRegion))
1601
+ }, [regional, configuredRegion, region])
1602
+
1603
+ const selectRegion = useCallback(next => {
1604
+ pendingRegion.current = next
1605
+ setRegion(next)
1606
+ }, [])
1607
+
1608
+ const fields = brand.id === 'codebuddy'
1609
+ ? {
1610
+ disabled: region === 'cn' ? 'codebuddyCnDisabledModels' : 'codebuddyGlobalDisabledModels',
1611
+ windows: region === 'cn' ? 'codebuddyCnModelContextWindows' : 'codebuddyGlobalModelContextWindows',
1612
+ }
1613
+ : brand.id === 'minimax'
1614
+ ? {
1615
+ disabled: region === 'cn' ? 'minimaxCnDisabledModels' : 'minimaxGlobalDisabledModels',
1616
+ windows: region === 'cn' ? 'minimaxCnModelContextWindows' : 'minimaxGlobalModelContextWindows',
1617
+ }
1618
+ : brand.fields
1619
+
1620
+ const describeFace = ctx.configForms.describe()
1621
+ const describeSubscribe = useCallback(listener => describeFace.subscribe(listener), [describeFace])
1622
+ const describeRead = useCallback(() => describeFace.getSnapshot(), [describeFace])
1623
+ const describeSnapshot = useSyncExternalStore(describeSubscribe, describeRead)
1624
+ useEffect(() => { describeFace.ensure().catch(() => undefined) }, [describeFace])
1625
+
1626
+ const fetchModels = useCallback(async (fresh = false) => {
1627
+ const regionQuery = regional ? `&region=${region}` : ''
1628
+ const payload = await api(`/models?brand=${brand.id}${regionQuery}${fresh ? '&fresh=1' : ''}`)
1629
+ // Never adopt a table the host answered for another login region.
1630
+ if (regional && typeof payload?.region === 'string' && payload.region !== region) {
1631
+ throw new Error(t(brand.id === 'minimax' ? 'minimaxRegionMismatch' : 'codebuddyRegionMismatch'))
1632
+ }
1633
+ return {
1634
+ rows: Array.isArray(payload?.models) ? payload.models : [],
1635
+ notice: typeof payload?.notice === 'string' ? payload.notice : undefined,
1636
+ signedIn: regional ? payload?.signedIn === true : undefined,
1637
+ }
1638
+ }, [brand.id, regional, region, t])
1639
+
1640
+ /** Adopt one read and remember it for the next visit to this region. */
1641
+ const adopt = useCallback((rows, notice, nextSignedIn) => {
1642
+ setModels(rows)
1643
+ setCatalogNotice(notice)
1644
+ setSignedIn(nextSignedIn)
1645
+ writeCache(brand.id, modelsKind, { rows, notice, signedIn: nextSignedIn, at: Date.now() })
1646
+ }, [brand.id, modelsKind])
1647
+
1648
+ /** Read the list. `fresh` asks the host to drop its catalog cache first. */
1649
+ const load = useCallback(async (fresh = false) => {
1650
+ const requestedKind = modelsKind
1651
+ setError(undefined)
1652
+ const mine = ++ticket.current
1653
+ try {
1654
+ const { rows, notice, signedIn: nextSignedIn } = await fetchModels(fresh)
1655
+ if (mine !== ticket.current || kindRef.current !== requestedKind) return
1656
+ adopt(rows, notice, nextSignedIn)
1657
+ } catch (err) {
1658
+ if (mine !== ticket.current || kindRef.current !== requestedKind) return
1659
+ setError(String(err?.message ?? err))
1660
+ setModels(previous => previous ?? [])
1661
+ }
1662
+ }, [adopt, fetchModels, modelsKind])
1663
+
1664
+ /** Latest values for callbacks the account card holds across renders. */
1665
+ const loadRef = useRef(load)
1666
+ loadRef.current = load
1667
+ const kindRef = useRef(modelsKind)
1668
+ kindRef.current = modelsKind
1669
+ /** The region of the last model read; a change forces a fresh read. */
1670
+ const lastLoaded = useRef(undefined)
1671
+ const refresh = useCallback(() => { void loadRef.current() }, [])
1672
+
1673
+ /** The last region verdict, so recovering from a block reloads the list. */
1674
+ const blockedRegion = useRef(undefined)
1675
+
1676
+ /**
1677
+ * Keep the model list in step with the region verdict.
1678
+ *
1679
+ * A blocked region has no readable catalog, so its remembered table is
1680
+ * dropped. The reverse matters too: a manual refresh re-probes the
1681
+ * network, and if the verdict flips back the list must be read again
1682
+ * without asking the user to switch region and back.
1683
+ */
1684
+ const handleMinimaxUsage = useCallback(payload => {
1685
+ if (brand.id !== 'minimax') return
1686
+ const wasBlocked = blockedRegion.current === region
1687
+ if (payload?.regionBlocked !== true) {
1688
+ if (wasBlocked) {
1689
+ blockedRegion.current = undefined
1690
+ refresh()
1691
+ }
1692
+ return
1693
+ }
1694
+ blockedRegion.current = region
1695
+ const notice = typeof payload.error === 'string' ? payload.error : t('minimaxIpBlocked')
1696
+ setModels([])
1697
+ setCatalogNotice(notice)
1698
+ setError(undefined)
1699
+ writeCache(brand.id, kindRef.current, { rows: [], notice, signedIn: true, at: Date.now() })
1700
+ }, [brand.id, region, refresh, t])
1701
+
1702
+ /**
1703
+ * On a region switch, paint that region's remembered table first and
1704
+ * then verify it with the host. The read carries the region explicitly,
1705
+ * so it stays correct even before the config write commits.
1706
+ */
1707
+ useEffect(() => {
1708
+ if (regional) {
1709
+ const saved = readCache(brand.id, modelsKind)
1710
+ const accountSnapshot = brand.id === 'minimax'
1711
+ ? minimaxSnapshot(region)
1712
+ : codeBuddySnapshot(region)
1713
+ const blocked = brand.id === 'minimax' && accountSnapshot?.usage?.regionBlocked === true
1714
+ if (blocked) {
1715
+ // Never paint a remembered table for a region this machine cannot reach.
1716
+ setModels([])
1717
+ setCatalogNotice(typeof accountSnapshot?.usage?.error === 'string'
1718
+ ? accountSnapshot.usage.error
1719
+ : t('minimaxIpBlocked'))
1720
+ } else {
1721
+ setModels(Array.isArray(saved?.rows) ? saved.rows : undefined)
1722
+ setCatalogNotice(typeof saved?.notice === 'string' ? saved.notice : undefined)
1723
+ }
1724
+ // The account snapshot already knows whether this region is signed
1725
+ // in, so the locked view does not flash while the catalog boots.
1726
+ setSignedIn(saved?.signedIn === true || accountSnapshot?.auth?.signedIn === true)
1727
+ setError(undefined)
1728
+ }
1729
+ // A switch must not be served from the host's cached catalog: the CLI
1730
+ // only settles into the new login environment on a fresh read.
1731
+ const switched = regional
1732
+ && lastLoaded.current !== undefined
1733
+ && lastLoaded.current !== region
1734
+ lastLoaded.current = region
1735
+ void load(switched)
1736
+ }, [brand.id, regional, modelsKind, region, load, t])
1737
+
1738
+ /** Login/logout flips which catalog the page is allowed to show. */
1739
+ const handleAuthChange = useCallback(next => {
1740
+ if (!regional) return
1741
+ setSignedIn(next === true)
1742
+ if (next === true) {
1743
+ refresh()
1744
+ return
1745
+ }
1746
+ setModels([])
1747
+ setCatalogNotice(undefined)
1748
+ writeCache(brand.id, kindRef.current, { rows: [], notice: undefined, signedIn: false, at: Date.now() })
1749
+ }, [brand.id, regional, refresh])
1750
+
1751
+ /**
1752
+ * Re-read until the list reflects what was just written, or give up.
1753
+ *
1754
+ * The host commits a volatile config edit into the running plugin before
1755
+ * it answers the write, so the first read after `set()` normally already
1756
+ * shows the change and this returns immediately. The retries exist for the
1757
+ * cases where it does not: a reload that briefly unpublished the route, or
1758
+ * a host that answered ahead of its own commit. Spending them turns a
1759
+ * transient disagreement into a short wait instead of a wrong answer.
1760
+ *
1761
+ * @param verify - whether the rows already show the intended change.
1762
+ * @param attempts - how many reads to try before accepting what arrived.
1763
+ * @returns the last rows read, or undefined when every read failed.
1764
+ */
1765
+ const loadUntil = useCallback(async (verify, attempts = 5) => {
1766
+ let rows
1767
+ const requestedKind = kindRef.current
1768
+ for (let attempt = 0; attempt < attempts; attempt++) {
1769
+ try {
1770
+ const read = await fetchModels()
1771
+ // A region switch during the save invalidates this verification.
1772
+ if (kindRef.current !== requestedKind) return undefined
1773
+ rows = read.rows
1774
+ adopt(rows, read.notice, read.signedIn)
1775
+ } catch (err) {
1776
+ setError(String(err?.message ?? err))
1777
+ return undefined
1778
+ }
1779
+ if (verify === undefined || verify(rows)) return rows
1780
+ await new Promise(resolve => setTimeout(resolve, 120 + attempt * 120))
1781
+ }
1782
+ return rows
1783
+ }, [adopt, fetchModels])
1784
+
1785
+ /**
1786
+ * Apply one change through the shared config form, then re-read until the
1787
+ * list reflects it.
1788
+ *
1789
+ * The write goes through `configForms`, not the API route: that form owns
1790
+ * the namespace's revision fence, so every change is ordered and a stale
1791
+ * editor is refused rather than silently overwriting.
1792
+ *
1793
+ * `busy` is owned by the newest write alone, and is always cleared in
1794
+ * `finally`. It must NOT be gated on the read generation: the read bumps
1795
+ * that counter, so gating there would leave `busy` set forever and every
1796
+ * control disabled.
1797
+ *
1798
+ * The host answers only after it has committed the value, so the re-read
1799
+ * normally confirms the change on its first attempt. `verify` therefore
1800
+ * acts as a real check rather than a wait: if the list still disagrees
1801
+ * once the retries are spent, the change was NOT adopted and the page says
1802
+ * so instead of reporting a save that did nothing.
1803
+ *
1804
+ * @param key - the config field to write.
1805
+ * @param next - the value, or undefined to clear the field.
1806
+ * @param verify - whether the re-read list already shows this change.
1807
+ */
1808
+ const write = useCallback(async (key, next, verify) => {
1809
+ const mine = ++writeTicket.current
1810
+ setBusy(true)
1811
+ setStatus(t('saving'))
1812
+ setError(undefined)
1813
+ try {
1814
+ const op = next === undefined ? form.unset(key) : form.set(key, next)
1815
+ const accepted = await withDeadline(op, WRITE_TIMEOUT_MS, t('timeout'))
1816
+ if (accepted === false) throw new Error(t('saveFailed'))
1817
+ const rows = await loadUntil(verify)
1818
+ if (rows !== undefined && verify !== undefined && !verify(rows)) throw new Error(t('notApplied'))
1819
+ if (mine === writeTicket.current) setStatus(t('saved'))
1820
+ } catch (err) {
1821
+ if (mine !== writeTicket.current) return
1822
+ setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
1823
+ setStatus(undefined)
1824
+ // The rows now hold an optimistic guess; re-read so the page shows what
1825
+ // the host actually stored rather than what the click hoped for.
1826
+ await load()
1827
+ } finally {
1828
+ if (mine === writeTicket.current) setBusy(false)
1829
+ }
1830
+ }, [form, load, loadUntil, t])
1831
+
1832
+ /**
1833
+ * Write the whole disabled-model list, derived from the rows the user
1834
+ * just changed, so rapid toggles cannot lose each other's edits.
1835
+ *
1836
+ * The row is updated locally first: the host commits the value before it
1837
+ * answers, so the re-read confirms this instead of correcting it, and the
1838
+ * switch never appears to snap back to where it was.
1839
+ */
1840
+ const writeDisabled = useCallback((rows, id, enabled) => {
1841
+ const next = new Set(rows.filter(m => !m.enabled).map(m => m.id))
1842
+ if (enabled) next.delete(id)
1843
+ else next.add(id)
1844
+ setModels(current => current?.map(m => m.id === id ? { ...m, enabled } : m))
1845
+ return write(fields.disabled, [...next], list => list.some(m => m.id === id && m.enabled === enabled))
1846
+ }, [fields.disabled, write])
1847
+
1848
+ /** Write the whole per-model window map, again showing the choice at once. */
1849
+ const writeWindow = useCallback((rows, id, window) => {
1850
+ const next = {}
1851
+ for (const m of rows) if (m.override !== undefined) next[m.id] = m.override
1852
+ if (window === undefined) delete next[id]
1853
+ else next[id] = window
1854
+ setModels(current => current?.map(m => m.id === id
1855
+ ? { ...m, override: window, contextWindow: window ?? m.defaultContextWindow }
1856
+ : m))
1857
+ return write(
1858
+ fields.windows,
1859
+ next,
1860
+ list => list.some(m => m.id === id
1861
+ && (window === undefined ? m.override === undefined : m.override === window)),
1862
+ )
1863
+ }, [fields.windows, write])
1864
+
1865
+ /**
1866
+ * Flip every model at once.
1867
+ *
1868
+ * Enabling all writes an empty deny-list rather than every id, so a model
1869
+ * the account publishes later still defaults to on.
1870
+ */
1871
+ const writeAll = useCallback((enabled) => {
1872
+ const ids = (models ?? []).map(m => m.id)
1873
+ setModels(current => current?.map(m => ({ ...m, enabled })))
1874
+ return write(
1875
+ fields.disabled,
1876
+ enabled ? [] : ids,
1877
+ list => list.every(m => m.enabled === enabled),
1878
+ )
1879
+ }, [fields.disabled, models, write])
1880
+
1881
+ // ── CLI helper ────────────────────────────────────────────────────────
1882
+ // The host runs the script, so the page only asks and then reads what it
1883
+ // printed. `setup` stays undefined-shaped until the first answer arrives:
1884
+ // a host older than this route simply never answers, and the group still
1885
+ // renders with both buttons working.
1886
+ const [setup, setSetup] = useState(undefined)
1887
+ const [setupError, setSetupError] = useState(undefined)
1888
+ const [logOpen, setLogOpen] = useState(false)
1889
+ const logRef = useRef(null)
1890
+
1891
+ const pollSetup = useCallback(async () => {
1892
+ try {
1893
+ setSetup(await api(`/setup?brand=${brand.id}`, { timeout: 10_000 }))
1894
+ } catch {
1895
+ /* no run to report, or a host without the route */
1896
+ }
1897
+ }, [brand.id])
1898
+
1899
+ const startCliSetup = useCallback(async (mode) => {
1900
+ setSetupError(undefined)
1901
+ try {
1902
+ setSetup(await api('/setup', {
1903
+ method: 'POST',
1904
+ headers: { 'content-type': 'application/json' },
1905
+ body: JSON.stringify({ brand: brand.id, mode }),
1906
+ timeout: 15_000,
1907
+ }))
1908
+ } catch (err) {
1909
+ setSetupError(`${t('cliStartFailed')}:${String(err?.message ?? err)}`)
1910
+ }
1911
+ }, [brand.id, t])
1912
+
1913
+ const setupRunning = setup?.running === true
1914
+ const setupCode = setup !== undefined && setup.running === false ? setup.code : undefined
1915
+ const setupFinishedAt = setup?.finishedAt
1916
+ const setupLines = Array.isArray(setup?.lines) ? setup.lines : []
1917
+
1918
+ useEffect(() => { void pollSetup() }, [pollSetup])
1919
+ useEffect(() => {
1920
+ if (!setupRunning) return undefined
1921
+ const timer = setInterval(() => { void pollSetup() }, 1200)
1922
+ return () => clearInterval(timer)
1923
+ }, [setupRunning, pollSetup])
1924
+
1925
+ /**
1926
+ * The output panel follows the run, not the history: open while the
1927
+ * script is alive, folded away one second after it ends. Pressing 查看
1928
+ * 输出 brings the text back, and a finished run from before a reload is
1929
+ * never re-expanded, because the panel starts closed.
1930
+ */
1931
+ useEffect(() => {
1932
+ if (setupRunning) {
1933
+ setLogOpen(true)
1934
+ return undefined
1935
+ }
1936
+ if (setupFinishedAt === undefined) return undefined
1937
+ const timer = setTimeout(() => setLogOpen(false), 1000)
1938
+ return () => clearTimeout(timer)
1939
+ }, [setupRunning, setupFinishedAt])
1940
+
1941
+ // The catalog is read from the CLI, so a helper that just installed,
1942
+ // signed into, or removed it changes what the list and quota should show —
1943
+ // and the host has already dropped its cached answers for that case.
1944
+ useEffect(() => {
1945
+ if (setupCode !== 0) return
1946
+ void load(true)
1947
+ setUsageTick(value => value + 1)
1948
+ }, [setupCode, setupFinishedAt, load])
1949
+
1950
+ /** Ask before running the destructive CLI action. */
1951
+ const uninstallCli = useCallback(() => {
1952
+ if (typeof window.confirm !== 'function') return
1953
+ if (!window.confirm(t('cliUninstallConfirm'))) return
1954
+ void startCliSetup('uninstall')
1955
+ }, [startCliSetup, t])
1956
+
1957
+ useEffect(() => {
1958
+ const node = logRef.current
1959
+ if (node !== null) node.scrollTop = node.scrollHeight
1960
+ }, [setupLines.length])
1961
+
1962
+ const all = models ?? []
1963
+ const enabledTotal = all.filter(m => m.enabled).length
1964
+
1965
+ const shown = useMemo(() => {
1966
+ const q = query.trim().toLowerCase()
1967
+ return all.filter(m => {
1968
+ if (onlyEnabled && !m.enabled) return false
1969
+ if (q === '') return true
1970
+ return String(m.name).toLowerCase().includes(q) || String(m.id).toLowerCase().includes(q)
1971
+ })
1972
+ }, [all, query, onlyEnabled])
1973
+
1974
+ const regionalLocked = regional && signedIn !== true
1975
+ const authCard = brand.kind === 'codebuddy'
1976
+ ? h(CodeBuddyCard, {
1977
+ t, ctx, brand, refreshSignal: usageTick,
1978
+ onSignedIn: () => { refresh(); setUsageTick(v => v + 1) },
1979
+ onAuthChange: handleAuthChange,
1980
+ onRegionChange: selectRegion,
1981
+ })
1982
+ : brand.kind === 'minimax'
1983
+ ? h(MinimaxCard, {
1984
+ t, ctx, brand, refreshSignal: usageTick,
1985
+ onAuthChange: handleAuthChange,
1986
+ onRegionChange: selectRegion,
1987
+ onUsage: handleMinimaxUsage,
1988
+ })
1989
+ : null
1990
+
1991
+ // Signed out: do not read or show a catalog that the CLI would refuse.
1992
+ if (regionalLocked) {
1993
+ return h('div', { style: css.page },
1994
+ h('h2', { style: css.h2 }, t(brand.titleKey)),
1995
+ h('p', { style: css.intro }, t(brand.introKey)),
1996
+ authCard,
1997
+ h('div', { style: css.guide },
1998
+ h('div', { style: css.guideText }, t(brand.id === 'minimax' ? 'minimaxModelsHint' : 'codebuddyModelsHint')),
1999
+ ),
2000
+ error !== undefined ? h('div', { style: css.err }, error) : null,
2001
+ )
2002
+ }
2003
+
2004
+ /**
2005
+ * Red guidance for "no models", with the one action that can fix it.
2006
+ *
2007
+ * An empty list is almost always the machine, not the account: the CLI is
2008
+ * missing or signed out, so the catalog has nothing to return. Pointing at
2009
+ * the helper and offering to run it beats a grey sentence nobody reads.
2010
+ */
2011
+ const renderGuide = () => h('div', { style: css.guide },
2012
+ h('div', { style: css.guideText }, t(brand.noModelsKey)),
2013
+ brand.kind !== 'qoder'
2014
+ ? null
2015
+ : h('button', {
2016
+ style: { ...css.btn, ...css.btnAlert },
2017
+ disabled: setupRunning,
2018
+ onClick: () => void startCliSetup('configure'),
2019
+ }, t('cliRun')),
2020
+ )
2021
+
2022
+ if (models === undefined) {
2023
+ return h('div', { style: css.page },
2024
+ h('h2', { style: css.h2 }, t(brand.titleKey)),
2025
+ // Same leading shape as the loaded page: a differing child index
2026
+ // remounts the account card and makes it snap back to the region the
2027
+ // config still holds while the switch is in flight.
2028
+ h('p', { style: css.intro }, t(brand.introKey)),
2029
+ regional ? authCard : null,
2030
+ error === undefined
2031
+ ? h('div', { style: css.note }, t('loading'))
2032
+ : h('div', null,
2033
+ h('div', { style: css.err }, `${t('loadFailed')}:${error}`),
2034
+ h('button', { style: { ...css.btn, marginTop: '8px' }, onClick: () => void load(true) }, t('retry')),
2035
+ h('div', { style: { marginTop: '10px' } }, renderGuide()),
2036
+ ),
2037
+ )
2038
+ }
2039
+
2040
+ const rows = shown.map((m, index) => {
2041
+ const choices = Array.isArray(m.contextWindows) ? m.contextWindows : []
2042
+ return h('div', {
2043
+ key: m.id,
2044
+ style: { ...css.row, ...(index === 0 ? css.rowFirst : {}), ...(m.enabled ? {} : css.rowOff) },
2045
+ },
2046
+ h('input', {
2047
+ type: 'checkbox',
2048
+ style: css.switch,
2049
+ checked: m.enabled === true,
2050
+ disabled: busy,
2051
+ title: t('colEnabled'),
2052
+ onChange: event => { void writeDisabled(all, m.id, event.target.checked) },
2053
+ }),
2054
+ h('div', { style: css.name },
2055
+ h('div', { style: css.nameText },
2056
+ m.name,
2057
+ m.vision === true ? h('span', { key: 'v', style: { ...css.tag, marginLeft: '6px' } }, t('vision')) : null,
2058
+ priceSuffix(t, m.priceFactor) !== ''
2059
+ ? h('span', { key: 'p', style: css.price }, ` · ${priceSuffix(t, m.priceFactor)}`)
2060
+ : null,
2061
+ ),
2062
+ h('div', { style: css.id }, m.id),
2063
+ ),
2064
+ h('select', {
2065
+ style: css.select,
2066
+ value: m.override === undefined ? '' : String(m.override),
2067
+ disabled: busy,
2068
+ title: t('windowDefaultHint'),
2069
+ onChange: event => {
2070
+ const value = event.target.value
2071
+ void writeWindow(all, m.id, value === '' ? undefined : Number(value))
2072
+ },
2073
+ },
2074
+ h('option', { key: 'default', value: '' }, `${t('windowDefault')} · ${windowLabel(m.defaultContextWindow)}`),
2075
+ choices.map(n => h('option', { key: String(n), value: String(n) }, windowLabel(n))),
2076
+ ),
2077
+ )
2078
+ })
2079
+
2080
+ const advanced = buildAdvanced({
2081
+ t, form, snapshot,
2082
+ fields: ADVANCED[brand.id],
2083
+ namespace: describeSnapshot.view?.namespaces?.find(n => n.ns === NS),
2084
+ show: showAdvanced,
2085
+ onToggle: () => setShowAdvanced(value => !value),
2086
+ })
2087
+
2088
+ return h('div', { style: css.page },
2089
+ h('h2', { style: css.h2 }, t(brand.titleKey)),
2090
+ h('p', { style: css.intro }, t(brand.introKey)),
2091
+ regional
2092
+ ? authCard
2093
+ : h(UsageCard, { t, brand, refreshSignal: usageTick }),
2094
+
2095
+ // Search row: the field grows, the checkbox sits beside it.
2096
+ h('div', { style: css.bar },
2097
+ h('input', {
2098
+ style: { ...css.input, ...css.search },
2099
+ placeholder: t('search'),
2100
+ value: query,
2101
+ onChange: event => setQuery(event.target.value),
2102
+ }),
2103
+ h('label', { style: { ...css.note, display: 'flex', alignItems: 'center', gap: '6px', whiteSpace: 'nowrap' } },
2104
+ h('input', { type: 'checkbox', checked: onlyEnabled, onChange: event => setOnlyEnabled(event.target.checked) }),
2105
+ t('onlyEnabled'),
2106
+ ),
2107
+ ),
2108
+
2109
+ // Action row: all four buttons on one line, count pinned to the right.
2110
+ // `nowrap` keeps them together; the count takes the remaining space so
2111
+ // nothing wraps to a second line.
2112
+ h('div', { style: { ...css.bar, flexWrap: 'nowrap' } },
2113
+ h('button', { style: css.btn, disabled: busy, onClick: () => void load(true) }, t('refresh')),
2114
+ h('button', {
2115
+ style: css.btn,
2116
+ disabled: busy || all.every(m => m.enabled),
2117
+ onClick: () => void writeAll(true),
2118
+ }, t('selectAll')),
2119
+ h('button', {
2120
+ style: css.btn,
2121
+ disabled: busy || enabledTotal === 0,
2122
+ onClick: () => void writeAll(false),
2123
+ }, t('selectNone')),
2124
+ h('span', { style: css.count }, `${t('enabledCount')} ${enabledTotal} / ${all.length}`),
2125
+ ),
2126
+
2127
+ all.length === 0
2128
+ ? renderGuide()
2129
+ : h('div', { style: css.list }, rows.length > 0 ? rows : h('div', { style: { ...css.note, padding: '12px 14px' } }, '—')),
2130
+
2131
+ catalogNotice !== undefined ? h('div', { style: css.note }, catalogNotice) : null,
2132
+ all.length > 0 ? h('div', { style: css.note }, t('windowWarn')) : null,
2133
+ error !== undefined ? h('div', { style: css.err }, error) : null,
2134
+ status !== undefined && error === undefined ? h('div', { style: css.note }, status) : null,
2135
+
2136
+ brand.kind !== 'qoder' ? null : h('div', { style: css.group },
2137
+ h('h3', { style: css.h3 }, t(brand.cliGroupKey)),
2138
+ h('div', { style: css.note }, t(brand.cliHintKey)),
2139
+ h('div', { style: { ...css.bar, flexWrap: 'nowrap' } },
2140
+ h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('configure') }, t('cliRun')),
2141
+ h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('login') }, t('cliLogin')),
2142
+ h('button', { style: { ...css.btn, ...css.btnAlert }, disabled: setupRunning, onClick: uninstallCli }, t('cliUninstall')),
2143
+ setupLines.length > 0 && !setupRunning
2144
+ ? h('button', { style: css.btn, onClick: () => setLogOpen(value => !value) }, logOpen ? t('cliHideLog') : t('cliShowLog'))
2145
+ : null,
2146
+ h('span', { style: css.count }, setupRunning
2147
+ ? (setup?.mode === 'uninstall' ? t('cliUninstalling') : t('cliRunning'))
2148
+ : setupError !== undefined
2149
+ ? setupError
2150
+ : setupCode === 0
2151
+ ? (setup?.mode === 'uninstall' ? t('cliUninstallOk') : t('cliExitOk'))
2152
+ : setupCode === undefined || setupCode === null
2153
+ ? ''
2154
+ : `${t('cliExitFail')} ${setupCode}`),
2155
+ ),
2156
+ logOpen && setupLines.length > 0
2157
+ ? h('pre', { ref: logRef, style: css.log }, setupLines.join('\n'))
2158
+ : null,
2159
+ ),
2160
+
2161
+ advanced,
2162
+ )
2163
+ }
2164
+
2165
+ /**
2166
+ * The two edition switches, contributed to this bundle's page in the plugin
2167
+ * manager (`plugins.bundle.config`).
2168
+ *
2169
+ * They live here rather than on either settings page because they decide
2170
+ * whether those pages exist at all: a page cannot own the switch that
2171
+ * removes it. The write goes through the shared config form, so it uses the
2172
+ * same revision fence as every other setting.
2173
+ */
2174
+ function BundleSettings({ ctx, t, view }) {
2175
+ const form = ctx.configForms.get(NS)
2176
+ const subscribe = useCallback(listener => form.subscribe(listener), [form])
2177
+ const read = useCallback(() => form.getSnapshot(), [form])
2178
+ const snapshot = useSyncExternalStore(subscribe, read)
2179
+ const value = snapshot?.value ?? {}
2180
+ const writable = snapshot?.writable !== false
2181
+ const [busy, setBusy] = useState(false)
2182
+ const [status, setStatus] = useState(undefined)
2183
+ const [error, setError] = useState(undefined)
2184
+ const writeTicket = useRef(0)
2185
+
2186
+ const toggle = useCallback(async (key, next) => {
2187
+ const mine = ++writeTicket.current
2188
+ setBusy(true)
2189
+ setStatus(t('saving'))
2190
+ setError(undefined)
2191
+ try {
2192
+ const accepted = await withDeadline(form.set(key, next), WRITE_TIMEOUT_MS, t('timeout'))
2193
+ if (accepted === false) throw new Error(t('pluginOptionsRejected'))
2194
+ if (mine === writeTicket.current) setStatus(t('saved'))
2195
+ } catch (err) {
2196
+ if (mine !== writeTicket.current) return
2197
+ setError(`${t('saveFailed')}:${String(err?.message ?? err)}`)
2198
+ setStatus(undefined)
2199
+ } finally {
2200
+ if (mine === writeTicket.current) setBusy(false)
2201
+ }
2202
+ }, [form, t])
2203
+
2204
+ const labelOf = brand => {
2205
+ const key = brand.id === 'cn'
2206
+ ? 'displayName'
2207
+ : brand.id === 'global'
2208
+ ? 'intlDisplayName'
2209
+ : brand.id === 'minimax' ? 'minimaxDisplayName' : 'codebuddyDisplayName'
2210
+ const fallback = brand.id === 'cn'
2211
+ ? t('nav')
2212
+ : brand.id === 'global'
2213
+ ? t('intlNav')
2214
+ : brand.id === 'minimax' ? t('minimaxNav') : t('codebuddyNav')
2215
+ const stored = value[key]
2216
+ return typeof stored === 'string' && stored !== '' ? stored : fallback
2217
+ }
2218
+
2219
+ if (view !== undefined && view !== 'page') {
2220
+ const names = BRANDS
2221
+ .filter(brand => value[brand.fields.enabled] !== false)
2222
+ .map(labelOf)
2223
+ return h('span', null, names.join(' · '))
2224
+ }
2225
+
2226
+ const rows = BRANDS.map((brand, index) => {
2227
+ const enabled = value[brand.fields.enabled] !== false
2228
+ const name = labelOf(brand)
2229
+ return h('div', {
2230
+ key: brand.id,
2231
+ style: { ...css.optionRow, ...(index === 0 ? css.optionFirst : {}) },
2232
+ },
2233
+ h('input', {
2234
+ type: 'checkbox',
2235
+ style: css.switch,
2236
+ checked: enabled,
2237
+ disabled: busy || !writable,
2238
+ title: enabled ? t('pluginOptionsOn') : t('pluginOptionsOff'),
2239
+ onChange: event => { void toggle(brand.fields.enabled, event.target.checked) },
2240
+ }),
2241
+ h('div', { style: css.optionText },
2242
+ h('div', { style: css.optionName }, name),
2243
+ h('div', { style: css.optionStatus }, enabled ? t('pluginOptionsOn') : t('pluginOptionsOff')),
2244
+ ),
2245
+ )
2246
+ })
2247
+
2248
+ return h('div', { style: css.group },
2249
+ h('h3', { style: css.h3 }, t('pluginOptionsTitle')),
2250
+ h('div', { style: css.note }, t('pluginOptionsHint')),
2251
+ rows,
2252
+ !writable ? h('div', { style: css.note }, t('pluginOptionsReadOnly')) : null,
2253
+ error !== undefined ? h('div', { style: css.err }, error) : null,
2254
+ status !== undefined && error === undefined ? h('div', { style: css.note }, status) : null,
2255
+ )
2256
+ }
2257
+
2258
+ /**
2259
+ * The collapsed advanced block: the remaining scalars, rendered against the
2260
+ * host's schema so labels, bounds and defaults stay in one place.
2261
+ */
2262
+ function buildAdvanced({ t, form, snapshot, fields, namespace, show, onToggle }) {
2263
+ const header = h('div', { style: css.bar },
2264
+ h('button', { style: css.btn, onClick: onToggle }, show ? t('hide') : t('show')),
2265
+ h('span', { style: css.note }, t('advancedHint')),
2266
+ )
2267
+ if (!show) {
2268
+ return h('div', { style: css.group }, h('h3', { style: css.h3 }, t('advanced')), header)
2269
+ }
2270
+
2271
+ const value = snapshot?.value ?? {}
2272
+ const user = snapshot?.user
2273
+ const schema = namespace?.schema
2274
+ const refs = schema?.refs
2275
+ const root = refs?.[schema?.uid]
2276
+ const writable = snapshot?.writable !== false
2277
+
2278
+ const set = (key, next) => {
2279
+ const op = next === undefined || next === ''
2280
+ ? form.unset(key)
2281
+ : form.set(key, next)
2282
+ op.catch(() => undefined)
2283
+ }
2284
+
2285
+ const rows = fields.map(([key, kind]) => {
2286
+ const node = refs?.[root?.dict?.[key]]
2287
+ if (node === undefined) return null
2288
+ const labels = t('advancedFields') ?? {}
2289
+ const help = typeof node?.meta?.description === 'string' ? node.meta.description : undefined
2290
+ const current = value[key]
2291
+ const overridden = user !== null && typeof user === 'object' && Object.hasOwn(user, key)
2292
+
2293
+ let control
2294
+ if (kind === 'json') {
2295
+ control = h('input', {
2296
+ style: { ...css.input, fontFamily: 'ui-monospace, monospace' },
2297
+ defaultValue: current === undefined ? '{}' : JSON.stringify(current),
2298
+ disabled: !writable,
2299
+ onBlur: event => {
2300
+ try { set(key, JSON.parse(event.target.value)) } catch { /* keep the last valid value */ }
2301
+ },
2302
+ })
2303
+ } else {
2304
+ control = h('input', {
2305
+ style: css.input,
2306
+ type: kind === 'number' ? 'number' : 'text',
2307
+ value: current === undefined ? '' : String(current),
2308
+ min: node?.meta?.min,
2309
+ max: node?.meta?.max,
2310
+ step: node?.meta?.step,
2311
+ disabled: !writable,
2312
+ onChange: event => {
2313
+ const raw = event.target.value
2314
+ if (raw === '') { set(key, undefined); return }
2315
+ set(key, kind === 'number' ? Number(raw) : raw)
2316
+ },
2317
+ })
2318
+ }
2319
+
2320
+ return h('div', { key, style: { display: 'flex', flexDirection: 'column', gap: '4px' } },
2321
+ h('div', { style: { display: 'flex', alignItems: 'center', gap: '8px' } },
2322
+ h('span', { style: css.advLabel }, labels[key] ?? key),
2323
+ overridden && writable
2324
+ ? h('button', {
2325
+ style: { fontSize: '0.75em', opacity: 0.55, background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline', padding: 0, font: 'inherit', color: 'inherit' },
2326
+ onClick: () => set(key, undefined),
2327
+ }, t('reset'))
2328
+ : null,
2329
+ ),
2330
+ control,
2331
+ help !== undefined ? h('div', { style: css.note }, help) : null,
2332
+ )
2333
+ }).filter(Boolean)
2334
+
2335
+ return h('div', { style: css.group },
2336
+ h('h3', { style: css.h3 }, t('advanced')),
2337
+ header,
2338
+ rows,
2339
+ )
2340
+ }
2341
+
2342
+ /**
2343
+ * Register the sections that are currently switched on, and keep that set
2344
+ * in step with the two edition switches.
2345
+ *
2346
+ * A section exists only while its edition does: the plugin page's switches
2347
+ * decide whether the settings page, its models and its fields are offered at
2348
+ * all. They cannot be registered unconditionally and hidden, because a
2349
+ * registered `settings.section` is exactly what puts an entry in the nav.
2350
+ */
2351
+ function apply(ctx) {
2352
+ const t = ctx.locale.bind(NS)
2353
+ ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'llm-qoder-cn: dictionaries')
2354
+
2355
+ // The two switches live on this bundle's own page in the plugin manager.
2356
+ // That page exists whether or not either edition is currently shown.
2357
+ ctx.effect(() => ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
2358
+ name: 'plugins.bundle.config',
2359
+ key: 'dsh-agent-sdk-bridge',
2360
+ locale: NS,
2361
+ }, props => h(BundleSettings, { ...props, ctx, t }))), 'llm-qoder-cn: bundle options')
2362
+
2363
+ ctx.effect(() => ctx.configForms.whileServed([NS], () => {
2364
+ const form = ctx.configForms.get(NS)
2365
+ const live = new Map()
2366
+
2367
+ const sync = () => {
2368
+ const snapshot = form.getSnapshot()
2369
+ // Wait for the stored config before deciding what to show. Registering
2370
+ // optimistically would flash a page the user already switched off.
2371
+ if (snapshot.status !== 'ready') return
2372
+ const value = snapshot.value ?? {}
2373
+ for (const brand of BRANDS) {
2374
+ const enabled = value[brand.fields.enabled] !== false
2375
+ const current = live.get(brand.id)
2376
+ if (enabled && current === undefined) {
2377
+ live.set(brand.id, ctx.slots.inject('settings.section', () => ctx.slots.register({
2378
+ name: 'settings.section',
2379
+ id: brand.settingsId,
2380
+ order: brand.order,
2381
+ label: () => t(brand.navKey),
2382
+ locale: NS,
2383
+ }, props => h(SettingsPage, { ...props, ctx, t, brand }))))
2384
+ } else if (!enabled && current !== undefined) {
2385
+ current()
2386
+ live.delete(brand.id)
2387
+ }
2388
+ }
2389
+ }
2390
+
2391
+ const unsubscribe = form.subscribe(sync)
2392
+ sync()
2393
+ return () => {
2394
+ unsubscribe()
2395
+ for (const off of live.values()) off()
2396
+ live.clear()
2397
+ }
2398
+ }), 'llm-qoder-cn: pages')
2399
+ }
2400
+
2401
+ exports.apply = apply
2402
+ exports.inject = inject
2403
+ exports.name = 'dsh-agent-sdk-bridge'
2404
+ exports.__test = {
2405
+ windowLabel, priceSuffix, ADVANCED, BRANDS, zh, en,
2406
+ SettingsPage, BundleSettings, UsageCard, CodeBuddyCard, QuotaLine, creditsOf, neverExpires,
2407
+ readCache, writeCache,
2408
+ }
2409
+ return module.exports
2410
+ },
2411
+ })