opencode-next 0.0.0-stage → 1.0.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/lib/ui.js ADDED
@@ -0,0 +1,4587 @@
1
+ /**
2
+ * 狀態頁(browser half)。
3
+ *
4
+ * 這支檔案是在瀏覽器裡執行的,跟 lib/ 其他模組的環境完全不同,所以有幾件事
5
+ * 必須照著固定規則來,否則整頁會靜默地不出現:
6
+ *
7
+ * 1. 檔案外層必須是 `window.__ModuleLoader__.load({ id, factory })` 這個封套。
8
+ * 它不是 ESM,所以**不能**用 import;只能用 `require("react")`。
9
+ * 2. 這個檔案是「宿主外掛」與「瀏覽器外掛」共用一個 package 的後者,必須在
10
+ * package.json 的 `dsh.client` 與 `exports["./client"]` 被指到,宿主才會
11
+ * 把它送進瀏覽器。
12
+ * 3. 掛進 `settings.section` 這個 slot,order 用 14(12 與 13 已被 antigravity
13
+ * 與 agy-next 佔用,15 之後也有人用了)。
14
+ * 4. `locale` 必須列入 inject:DSH 只內建 zh(簡體)與 en,繁中字典要靠
15
+ * addLanguage 自己宣告一個 id 才存在。碰到沒注入的 Cordis 服務會直接讓
16
+ * 外掛啟動失敗,所以這裡不能省。
17
+ *
18
+ * 樣式刻意全部自己帶(不依賴宿主 UI 套件的元件),但顏色一律走宿主的
19
+ * `--dsw-alias-*` 主題變數:這樣淺色/深色主題切換會自動跟著走,而不是把顏色
20
+ * 寫死。自帶樣式的好處是這個檔案只需要 react 一個相依,不會因為宿主套件
21
+ * 版本不同而整頁載入失敗。
22
+ */
23
+
24
+ window.__ModuleLoader__.load({
25
+ id: 'opencode-next',
26
+ factory(require) {
27
+ const React = require('react');
28
+ const h = React.createElement;
29
+
30
+ const API = '/opencode-next/api';
31
+ const NS = 'opencode-next';
32
+ const STYLE_ID = 'opencode-next-settings-style';
33
+
34
+ /* --------------------------------------------------------------- 文案 */
35
+
36
+ const COPY = {
37
+ en: {
38
+ nav: 'OpenCode-Next',
39
+ title: 'OpenCode-Next',
40
+ subtitle: 'Sign-in state, the models this provider serves, and how each one responded to the last probe.',
41
+ refreshing: 'Refreshing…',
42
+ login: 'Sign in',
43
+ loggingIn: 'Waiting for approval…',
44
+ cancelling: 'Cancelling…',
45
+ cancelLogin: 'Cancel sign-in',
46
+ reauth: 'Sign in again',
47
+ importLocal: 'Import from OpenCode Desktop',
48
+ importingLocal: 'Importing…',
49
+ importLocalDone: 'Imported the OpenCode Desktop sign-in as an account.',
50
+ importLocalAlready: 'This OpenCode Desktop sign-in is already imported.',
51
+ logout: 'Sign out',
52
+ reprobe: 'One-click probe',
53
+ reprobeAvailable: 'Probe available ({n})',
54
+ reprobeFiltered: 'Probe list ({n})',
55
+ probing: 'Probing…',
56
+ verify: 'Re-verify credential',
57
+
58
+ sectionAccount: 'Authorization',
59
+ sectionAccounts: 'Accounts', accountAdd: 'Add account', accountLabel: 'Account label', accountLabelPlaceholder: 'Optional label', accountStart: 'Start sign-in', accountCancel: 'Cancel', accountSwitch: 'Switch', accountActive: 'Active', accountExpired: 'Expired', accountExpiry: '{time} left', accountRemove: 'Remove', accountRemoveConfirm: 'Remove this account permanently?', accountCannotRemoveLast: 'At least one account must remain', accountSwitched: 'Switched to {label}', accountNoLabel: 'Unnamed', accountAddHint: 'Authorize a new OpenCode account with device sign-in.',
60
+ sectionModels: 'Models',
61
+ sectionDetails: 'Diagnostics',
62
+ stateReady: 'Ready',
63
+ stateExpiring: 'Expiring soon',
64
+ stateUnprobed: 'Not probed yet',
65
+ stateSignedOut: 'Not signed in',
66
+ stateExpired: 'Expired',
67
+ stateNoModels: 'No model responding',
68
+ stateDegraded: 'Some models unavailable',
69
+ stateUnknown: 'Unknown',
70
+
71
+ hReady: 'The credential is valid and models are responding.',
72
+ hSignedOut: 'Not signed in to OpenCode yet. Complete the device authorization below.',
73
+ hExpired: 'The credential has expired. Sign in again, or re-verify it.',
74
+ hNoModels: 'The credential is fine, but no model responded. The free lane may be blocking requests, or the egress IP may be restricted.',
75
+ hDegraded: 'The credential is valid, but not every model is usable. See the breakdown below.',
76
+ hUnprobed: 'The credential is fine. Model availability has not been probed yet.',
77
+ hExpiring: 'The credential expires soon; it will be refreshed automatically.',
78
+
79
+ credAbsent: 'No credential',
80
+ credSource: 'Source',
81
+ credExpiry: 'Expires',
82
+ credRefreshable: 'Auto-refresh',
83
+ credYes: 'available',
84
+ credNo: 'unavailable',
85
+ srcAccounts: 'Signed-in account',
86
+ srcLocalDb: 'OpenCode Desktop database',
87
+ srcAuthJson: 'OpenCode auth.json',
88
+ srcTokenFile: 'Saved by this plugin',
89
+ srcUnknown: 'unknown source',
90
+
91
+ expiresIn: '{time} left',
92
+ expiresAt: 'at {when}',
93
+ expiresPast: 'already expired',
94
+ expiresNoExpiry: 'no expiry reported',
95
+
96
+ signedOutHint:
97
+ 'No OpenCode credential yet. Sign in below, or sign in with OpenCode Desktop and this plugin will inherit the token automatically.',
98
+ loginHint: 'Open this URL and confirm the code shown there matches:',
99
+ userCode: 'Code',
100
+ openAgain: 'Open the sign-in page again',
101
+ waiting: 'A browser window should have opened. Approve access there; this page updates by itself.',
102
+ loginCancelled: 'That sign-in was cancelled because you signed out. Start it again when you are ready.',
103
+ loginFailed: 'Sign-in did not finish: {message}',
104
+ loginFailedTimeout: 'Sign-in timed out. Start it again when you are ready.',
105
+ loginFailedDenied: 'Sign-in was denied. Start it again if you still want to connect.',
106
+ loginFailedExpired: 'That sign-in code expired. Start again to get a new one.',
107
+ loginFailedNetwork: 'Could not reach OpenCode. Check the network and try again.',
108
+ copy: 'Copy',
109
+ copied: 'Copied',
110
+
111
+ modelsAvailable: '{ok} of {total} responding',
112
+ filterAll: 'All',
113
+ filterAvailable: 'Available',
114
+ filterCount: '{shown} of {total} shown',
115
+ rowDetails: 'Show probe details and context size',
116
+ modelFilters: 'Filter models by availability or probe result',
117
+ probedAgo: 'Last probed: {when} (manual)',
118
+ neverProbed: 'Not probed yet (manual mode)',
119
+ truncatedRateLimit: 'This run stopped after {tested} of {total}: a model hit a rate limit. Untested models keep their previous result.',
120
+ truncatedUnreachable: 'This run stopped after {tested} of {total}: the free lane became unreachable. Untested models keep their previous result.',
121
+ quotaReset: 'Free quota resets {when} (in {in}).',
122
+ quotaResetReady: 'The free quota window has reset. You can probe or chat again.',
123
+ quotaResetUnknown: 'Free quota is exhausted; upstream did not say when it resets.',
124
+ colModel: 'Model',
125
+ colStatus: 'Status',
126
+ colContext: 'Context',
127
+ colLatency: 'Latency',
128
+ statusOk: 'OK',
129
+ statusFail: 'Unavailable',
130
+ statusLimited: 'Throttled',
131
+ statusUnprobed: 'Not probed',
132
+ pickerAvailable: 'In picker',
133
+ pickerHidden: 'Hidden from picker',
134
+ colPicker: 'Show',
135
+ pickerShow: 'Show in picker',
136
+ pickerManual: 'Curated — {n} of {total} shown. New models no longer appear automatically.',
137
+ pickerAuto: 'Auto — every verified model is shown.',
138
+ pickerReset: 'Show all available',
139
+ pickerResetBusy: 'Resetting…',
140
+ pickerAutoShort: 'Auto',
141
+ pickerManualShort: 'Curated',
142
+ modelProbedAt: 'Probed {when}',
143
+ modelFailureStreak: '{count}/2 consecutive failures',
144
+ modelsCaption: 'Availability',
145
+ tabAccount: 'Account',
146
+ tabModels: 'Free Models',
147
+ tabAdvanced: 'Advanced',
148
+ tabGo: 'OpenCode Go',
149
+ unitDay: 'd',
150
+ unitHour: 'h',
151
+ unitMinute: 'm',
152
+ unitLessThanMinute: '<1m',
153
+ showAll: 'Show all {n} models',
154
+ showRest: 'Show the remaining {n} of {total}',
155
+ showLess: 'Show fewer',
156
+ onlyProblems: 'Problems only',
157
+ searchPlaceholder: 'Filter models',
158
+ noMatch: 'No model matches.',
159
+ contextSummary: 'Context window: {effective} tokens · {source}',
160
+ contextSetting: 'Context window',
161
+ contextMode: 'Capacity source',
162
+ contextDefault: 'Follow OpenCode default',
163
+ contextCustom: 'Custom value',
164
+ contextPublished: 'Published/default value: {value} tokens',
165
+ contextSourceOpenCode: 'OpenCode catalog',
166
+ contextSourceFallback: 'Plugin fallback',
167
+ contextSourceCustom: 'Manual override',
168
+ contextValue: 'Context window (tokens)',
169
+ contextHint: 'This value changes DSH’s model budget only. It does not raise OpenCode’s actual limit or change DSH’s compaction policy.',
170
+ contextSave: 'Save',
171
+ contextSaving: 'Saving…',
172
+ contextReset: 'Restore default',
173
+ contextSaved: 'Context setting saved.',
174
+ contextInvalid: 'Enter a whole number from 1,024 to 100,000,000.',
175
+ contextClickToEdit: 'Click to edit context window',
176
+ contextModalTitle: 'Context Window',
177
+ contextModalSub: 'Model: {id}',
178
+ contextDefaultValue: 'Upstream default: {value} tokens',
179
+ contextMaxOutput: 'Max output per reply: {value} tokens',
180
+ contextCustomLabel: 'Custom context window (tokens)',
181
+ contextResetToDefault: 'Restore default',
182
+ contextCancel: 'Cancel',
183
+ contextSaveBtn: 'Save',
184
+ contextCustomBadge: 'Custom',
185
+
186
+ sectionAdvanced: 'Advanced',
187
+ sectionBun: 'Bun runtime',
188
+ bunInstalled: 'Detected',
189
+ bunMissing: 'Not installed',
190
+ bunVersion: 'Version',
191
+ bunPath: 'Executable',
192
+ bunEnabled: 'Inference transport',
193
+ bunUsed: 'Bun',
194
+ bunNode: 'Node.js',
195
+ bunLast: 'Last request',
196
+ bunLastNone: 'No inference request in this process yet',
197
+ bunHint: 'OpenCode free models reject Node.js requests. This plugin uses a separately installed Bun; the OpenCode app does not include a bun executable.',
198
+ bunMissingHint: 'Bun was not found. Install it from bun.sh, then press Rescan — no DSH restart is needed.',
199
+ bunDownload: 'Get Bun',
200
+ bunRescan: 'Rescan',
201
+ bunRescanning: 'Scanning…',
202
+ sectionAnonymous: 'Anonymous channel',
203
+ anonOn: 'On',
204
+ anonOff: 'Off',
205
+ anonEnable: 'Send inference without my account credential',
206
+ anonWarning: 'Unofficial usage: this uses the public anonymous lane, which OpenCode does not promise to keep working. It may stop working or be throttled at any time, and it is still subject to your network exit IP. Use it only when you accept that risk.',
207
+ sectionGo: 'OpenCode Go (Subscription)',
208
+ goStateDisabled: 'Disabled',
209
+ goStateUnconfigured: 'No API key',
210
+ goStateChecking: 'Verifying…',
211
+ goStateConnected: 'Connected',
212
+ goStateInvalidKey: 'Invalid key',
213
+ goStateNoEntitlement: 'No Go plan',
214
+ goStatePermissionPolicy: 'Permission / policy error',
215
+ goStateRateLimited: 'Rate limited',
216
+ goStateTransient: 'Temporary failure',
217
+ goStateRedirectBlocked: 'Redirect blocked',
218
+ goStateInvalidResponse: 'Invalid response',
219
+ goProviderIdLabel: 'Provider ID',
220
+ goCredStatusLabel: 'API key',
221
+ goCredSourceDsh: 'DSH credential service ({ref})',
222
+ goCredSourceEnv: 'Environment variable ({ref})',
223
+ goCredSourceMissing: 'Not found ({ref})',
224
+ goCheckedAt: 'Last verified',
225
+ goUsageSummary: 'Usage windows',
226
+ goWindowRolling: '5h Limit',
227
+ goWindowWeekly: '7D Limit',
228
+ goWindowMonthly: '1M Limit',
229
+ goWindowResetsAt: 'resets {when}',
230
+ goWindowUnavailable: '–',
231
+ goExtraUsageWarn: '⚠ If Extra Usage is enabled in Console, overage may bill your workspace balance.',
232
+ goPreviewHint: 'Verified Go chat/tool models are published to the DSH picker (image input is enabled only for Go endpoint-verified image models; unverified catalog vision, video, reasoning, and non-chat capabilities are not advertised).',
233
+ goDisabledHint: 'OpenCode Go is disabled in plugin config (goSubscription.enabled: false). Re-enable it and provide an OpenCode Console Personal API Key via DSH credentials or OPENCODE_GO_API_KEY.',
234
+ goRefresh: 'Re-verify',
235
+ goRefreshing: 'Verifying…',
236
+ goClear: 'Clear cache',
237
+ goPreviewTitle: 'Workspace model preview ({count})',
238
+ goPreviewEmpty: 'No preview models loaded yet.',
239
+ goModelTypeUnknown: 'type: unknown',
240
+ goContextCap: 'ctx {value}',
241
+ goOutputCap: 'out {value}',
242
+ goCapReasoning: 'reasoning',
243
+ goCapTools: 'tools',
244
+ goCapAttachment: 'attachments',
245
+ goModalityInput: 'in: {list}',
246
+ goKeyFieldLabel: 'OpenCode Console Personal API Key ({ref})',
247
+ goKeyStoredStatus: 'Saved',
248
+ goKeyUnsetStatus: 'Not set',
249
+ goKeyStoredPlaceholder: 'Saved (enter a new key to overwrite)',
250
+ goKeyMissingPlaceholder: 'Enter OpenCode Console Personal API Key',
251
+ goKeySave: 'Save',
252
+ goKeySaving: 'Saving…',
253
+ goKeyChange: 'Replace',
254
+ goKeyCancel: 'Cancel',
255
+ goKeyDrawer: 'API Key',
256
+ goApiOnlyNote: 'OpenCode Go currently supports Console Personal API Key auth only (does not share free OAuth login).',
257
+ goKeyClear: 'Clear',
258
+ goKeyClearing: 'Clearing…',
259
+ goKeySavedMsg: 'OpenCode Go API key saved to DSH credential storage.',
260
+ goKeyClearedMsg: 'Cleared OpenCode Go API key from DSH credential storage.',
261
+ goKeyWriteUnavailable: 'DSH credential write (ctx.credentials.set) is unavailable in this process; the key cannot be saved and will not be written to plugin config or JSON files.',
262
+ goFilterAll: 'All',
263
+ goFilterPicker: 'In picker',
264
+ goFilterPreview: 'Preview only',
265
+ goColType: 'Type',
266
+ goColOutput: 'Output',
267
+ goColCaps: 'Catalog caps',
268
+ goStatusInPicker: 'In picker',
269
+ goStatusPreviewOnly: 'Preview only',
270
+ goReasonInactiveStatus: 'status: {status}',
271
+ goReasonMissingType: 'missing type',
272
+ goReasonUnsupportedType: 'non-chat type ({type})',
273
+ goReasonMissingLimits: 'missing limits',
274
+ goReasonNonTextModality: 'non-text modality',
275
+ goReasonNotConnected: 'subscription not connected',
276
+ goReasonInvalidModel: 'invalid metadata',
277
+ goReasonIneligible: 'not eligible for picker',
278
+ goReasonNotVerified: 'not verified for picker',
279
+ goPickerEligibleNote: 'Verified Go chat model; auto-published to the DSH picker (text + tool calling; no live probing or latency ping).',
280
+ goPreviewOnlyNote: 'Remains preview-only and excluded from the DSH picker: {reasons}.',
281
+ goSupportScopeNote: 'Catalog fields show upstream declarations only. Plugin Go channel supports text chat & tool calling, and automatically enables image input for eligible models whose catalog declares image/image/* input; video, audio, and other attachments remain unsupported.',
282
+ goModelSupportImage: 'Plugin Go support: text chat, tool calling & image input (enabled from upstream catalog image modality; actual runtime support depends on the Go endpoint; video, audio & other attachments are unsupported).',
283
+ goModelSupportTextOnly: 'Plugin Go support: text chat & tool calling only (upstream catalog does not declare image input; attached images will be rejected before sending).',
284
+ goCatalogMetaLabel: 'Catalog metadata: {meta}',
285
+ goExpandModelId: 'ID: {id}',
286
+ goExpandModelName: 'Name: {name}',
287
+ goExpandProvider: 'Owner: {owner}',
288
+ goExpandInputLimit: 'Input limit: {value}',
289
+ goExpandModalityIn: 'In: {list}',
290
+ goExpandModalityOut: 'Out: {list}',
291
+ goNoMatch: 'No Go models match this filter.',
292
+ sectionAutoSwitch: 'Automatic account switching',
293
+ sectionFallback: 'Model fallback',
294
+ autoSwitchEnable: 'Automatically switch account after confirmed credential rejection',
295
+ autoSwitchHint: 'Off by default. Only a 401 after refreshing the same saved account may switch; rate limits and network/model blocks never do.',
296
+ autoSwitchSaved: 'Automatic account switching setting saved.',
297
+ fallbackEnable: 'Switch to the next priority when a model fails',
298
+ fallbackHint: 'Only switches when the failure belongs to that model alone (retired, deprecated, geo-restricted, timed out). A blocked network or invalid sign-in is reported instead of being masked.',
299
+ fallbackSlot: 'Priority {n}',
300
+ fallbackNone: 'Not set',
301
+ fallbackSave: 'Save',
302
+ fallbackSaving: 'Saving…',
303
+ fallbackSaved: 'Fallback settings saved.',
304
+ fallbackOffNote: 'Fallback is off. A failing model returns its error directly.',
305
+ fallbackNeedProbe: 'Probe the models first to pick priorities from the available ones.',
306
+
307
+ rFreeTier: 'Free lane rejected this request',
308
+ rNetworkBlocked: 'Network blocked — turn off VPN/proxy',
309
+ rRegion: 'Region-restricted model',
310
+ rUnauthorized: 'Authorization rejected',
311
+ rForbidden: 'Upstream refused (403)',
312
+ rQuota: 'Quota exhausted',
313
+ rRateLimit: 'Rate limited',
314
+ rUpstream: 'Upstream server error',
315
+ rNotFound: 'Model not found',
316
+ rDeprecated: 'Model retired',
317
+ rUnavailable: 'Model unavailable',
318
+ shortUnavailable: 'Unavailable',
319
+ shortDeprecated: 'Retired',
320
+ shortQuota: 'Quota',
321
+ shortRateLimit: 'Rate limited',
322
+ shortRegion: 'Region',
323
+ shortFreeTier: 'Lane blocked',
324
+ shortNetwork: 'Network',
325
+ shortTransport: 'Offline',
326
+ shortNotFound: 'Not found',
327
+ shortUpstream: 'Upstream',
328
+ shortBadRequest: 'Rejected',
329
+ shortContextOverflow: 'Too long',
330
+ shortUnauthorized: 'Unauthorized',
331
+ shortForbidden: 'Forbidden',
332
+ shortUnknown: 'Unknown',
333
+ rContextOverflow: 'Context length exceeded',
334
+ rBadRequest: 'Rejected (400, no detail)',
335
+ rTransport: 'Connection failed',
336
+ availRatio: '{a}/{b} models usable',
337
+ rUnknown: 'Unknown status',
338
+
339
+ detailProvider: 'Provider id',
340
+ detailVersion: 'Plugin version',
341
+ detailProbeInterval: 'Probe interval',
342
+ detailCatalogPoll: 'Catalog poll',
343
+ detailPixelBudget: 'Image pixel budget',
344
+ detailMaxBytes: 'Image byte cap',
345
+ detailAutoDetect: 'Auto-detect models',
346
+ detailGenerated: 'Snapshot taken',
347
+
348
+ on: 'on',
349
+ off: 'off',
350
+ errorGeneric: 'Something went wrong: {message}',
351
+ loadFailed: 'Could not read the plugin status.',
352
+ intervalHours: '{h} h',
353
+ intervalMinutes: '{m} min',
354
+
355
+ /* Language switcher */
356
+ languageLabel: 'Language',
357
+ languageAuto: 'Follow system',
358
+ languageEn: 'English',
359
+ languageZh: '简体中文',
360
+ languageZhHant: '繁體中文',
361
+ languageOf_en: 'English',
362
+ languageOf_zh: '简体中文',
363
+ 'languageOf_zh-Hant': '繁體中文',
364
+ },
365
+
366
+ zh: {
367
+ nav: 'OpenCode-Next',
368
+ title: 'OpenCode-Next',
369
+ subtitle: '登录授权状态、这个 provider 提供的模型,以及每个模型最近一次探测的响应。',
370
+ refreshing: '正在刷新…',
371
+ login: '登录',
372
+ loggingIn: '等待授权中…',
373
+ cancelling: '正在取消…',
374
+ cancelLogin: '取消登录',
375
+ reauth: '重新登录',
376
+ importLocal: '从 OpenCode Desktop 导入',
377
+ importingLocal: '导入中…',
378
+ importLocalDone: '已把 OpenCode Desktop 的登录状态导入为账号。',
379
+ importLocalAlready: '这组 OpenCode Desktop 登录已经导入过。',
380
+ logout: '退出登录',
381
+ reprobe: '一键探测',
382
+ reprobeAvailable: '探测可用 ({n})',
383
+ reprobeFiltered: '探测清单 ({n})',
384
+ probing: '探测中…',
385
+ verify: '重新验证凭证',
386
+
387
+ sectionAccount: '授权状态',
388
+ sectionAccounts: '账号', accountAdd: '添加账号', accountLabel: '账号标签', accountLabelPlaceholder: '可选标签', accountStart: '开始登录', accountCancel: '取消', accountSwitch: '切换', accountActive: '使用中', accountExpired: '已过期', accountExpiry: '剩余 {time}', accountRemove: '移除', accountRemoveConfirm: '确定移除此账号?此操作无法撤销。', accountCannotRemoveLast: '至少要保留一个账号', accountSwitched: '已切换到 {label}', accountNoLabel: '未命名', accountAddHint: '通过设备授权登录新的 OpenCode 账号。',
389
+ sectionModels: '模型',
390
+ sectionDetails: '诊断信息',
391
+
392
+ stateReady: '正常',
393
+ stateExpiring: '即将过期',
394
+ stateUnprobed: '尚未探测',
395
+ stateSignedOut: '尚未登录',
396
+ stateExpired: '已过期',
397
+ stateNoModels: '没有模型响应',
398
+ stateDegraded: '部分模型不可用',
399
+ stateUnknown: '未知',
400
+
401
+ hReady: '授权有效,模型可用。',
402
+ hSignedOut: '尚未登录 OpenCode,请先完成设备授权。',
403
+ hExpired: '授权已过期,请重新登录或刷新凭证。',
404
+ hNoModels: '授权正常,但目前没有任何模型响应;可能是免费通道被拦截,或出口 IP 受限。',
405
+ hDegraded: '授权有效,但并非所有模型都能用;请看下方的分类统计。',
406
+ hUnprobed: '授权正常,尚未探测模型可用性。',
407
+ hExpiring: '授权即将到期,系统会自动刷新。',
408
+
409
+ credAbsent: '没有凭证',
410
+ credSource: '来源',
411
+ credExpiry: '到期',
412
+ credRefreshable: '自动更新',
413
+ credYes: '可用',
414
+ credNo: '不可用',
415
+ srcAccounts: '已登录账号',
416
+ srcLocalDb: 'OpenCode Desktop 数据库',
417
+ srcAuthJson: 'OpenCode auth.json',
418
+ srcTokenFile: '本插件保存',
419
+ srcUnknown: '未知来源',
420
+
421
+ expiresIn: '剩余 {time}',
422
+ expiresAt: '于 {when}',
423
+ expiresPast: '已过期',
424
+ expiresNoExpiry: '未报告到期时间',
425
+
426
+ signedOutHint: '尚未取得 OpenCode 凭证。可在下方登录,或用 OpenCode Desktop 登录后由本插件自动沿用其 token。',
427
+ loginHint: '打开下列网址,并确认网页上显示的代码与此相同:',
428
+ userCode: '代码',
429
+ openAgain: '再次打开登录页',
430
+ waiting: '应该已打开浏览器窗口,请在该页面同意授权;本页会自动更新。',
431
+ loginCancelled: '这次登录已取消,因为你已退出登录。准备好时再重新开始即可。',
432
+ loginFailed: '登录没有完成:{message}',
433
+ loginFailedTimeout: '登录超时。准备好时再重新开始即可。',
434
+ loginFailedDenied: '授权被拒绝。若仍要连接,请重新开始登录。',
435
+ loginFailedExpired: '这组登录代码已过期。请重新开始以取得新的代码。',
436
+ loginFailedNetwork: '连不到 OpenCode。请检查网络后再试一次。',
437
+ copy: '复制',
438
+ copied: '已复制',
439
+
440
+ modelsAvailable: '{total} 个中有 {ok} 个有响应',
441
+ filterAll: '全部',
442
+ filterAvailable: '可用',
443
+ filterCount: '显示 {shown}/{total}',
444
+ rowDetails: '展开探测细节与上下文大小',
445
+ modelFilters: '依模型可用状态或探测结果筛选',
446
+ probedAgo: '上次探测:{when}(手动)',
447
+ neverProbed: '尚未探测(手动模式)',
448
+ truncatedRateLimit: '本轮只验了 {tested}/{total}:某个模型遇到限流或额度用尽就停手。未验的模型保留上次结果。',
449
+ truncatedUnreachable: '本轮只验了 {tested}/{total}:免费通道中断。未验的模型保留上次结果。',
450
+ quotaReset: '免费额度将于 {when} 重置(还有 {in})。',
451
+ quotaResetReady: '免费额度窗口已重置,可以重新探测或对话。',
452
+ quotaResetUnknown: '免费额度已用尽;上游没有说明何时重置。',
453
+ colModel: '模型',
454
+ colStatus: '状态',
455
+ colContext: '上下文',
456
+ colLatency: '延迟',
457
+ statusOk: '正常',
458
+ statusFail: '不可用',
459
+ statusLimited: '受限',
460
+ statusUnprobed: '未探测',
461
+ pickerAvailable: '在模型清单中',
462
+ pickerHidden: '已从模型清单隐藏',
463
+ colPicker: '显示',
464
+ pickerShow: '在模型清单中显示',
465
+ pickerManual: '手动挑选 — 显示 {n}/{total} 个,新模型不再自动出现。',
466
+ pickerAuto: '自动 — 所有通过验证的模型都会显示。',
467
+ pickerReset: '显示全部可用模型',
468
+ pickerResetBusy: '还原中…',
469
+ pickerAutoShort: '自动',
470
+ pickerManualShort: '手选',
471
+ modelProbedAt: '探测时间:{when}',
472
+ modelFailureStreak: '连续失败 {count}/2 次',
473
+ modelsCaption: '可用状态',
474
+ tabAccount: '账号',
475
+ tabModels: '免费模型',
476
+ tabAdvanced: '进阶',
477
+ tabGo: 'OpenCode Go',
478
+ unitDay: '天',
479
+ unitHour: '小时',
480
+ unitMinute: '分',
481
+ unitLessThanMinute: '不到 1 分钟',
482
+ showAll: '显示全部 {n} 个模型',
483
+ showRest: '显示其余 {n} 个(共 {total} 个)',
484
+ showLess: '收起',
485
+ onlyProblems: '只看有问题的',
486
+ searchPlaceholder: '筛选模型',
487
+ noMatch: '没有匹配的模型。',
488
+ contextSummary: '上下文大小:{effective} tokens · {source}',
489
+ contextSetting: '上下文大小',
490
+ contextMode: '容量来源',
491
+ contextDefault: '跟随 OpenCode 默认值',
492
+ contextCustom: '自定义数值',
493
+ contextPublished: '目录/默认值:{value} tokens',
494
+ contextSourceOpenCode: 'OpenCode 模型目录',
495
+ contextSourceFallback: '插件备用值',
496
+ contextSourceCustom: '手动覆写',
497
+ contextValue: '上下文大小(tokens)',
498
+ contextHint: '此数值只会改变 DSH 的模型预算,不会提高 OpenCode 的实际上限,也不会改变 DSH 的压缩策略。',
499
+ contextSave: '保存',
500
+ contextSaving: '保存中…',
501
+ contextReset: '恢复默认值',
502
+ contextSaved: '上下文设置已保存。',
503
+ contextInvalid: '请输入 1,024 到 100,000,000 之间的整数。',
504
+ contextClickToEdit: '单击设置上下文上限',
505
+ contextModalTitle: '设置上下文上限',
506
+ contextModalSub: '模型:{id}',
507
+ contextDefaultValue: '上游默认值:{value} tokens',
508
+ contextMaxOutput: '单次回复输出上限:{value} tokens',
509
+ contextCustomLabel: '自定义上限(tokens)',
510
+ contextResetToDefault: '恢复默认值',
511
+ contextCancel: '取消',
512
+ contextSaveBtn: '保存',
513
+ contextCustomBadge: '自定义',
514
+
515
+ sectionAdvanced: '进阶设置',
516
+ sectionBun: 'Bun 运行环境',
517
+ bunInstalled: '已检测到',
518
+ bunMissing: '未安装',
519
+ bunVersion: '版本',
520
+ bunPath: '执行文件',
521
+ bunEnabled: '推理传输',
522
+ bunUsed: 'Bun',
523
+ bunNode: 'Node.js',
524
+ bunLast: '最近一次请求',
525
+ bunLastNone: '这个进程还没有发送过推理请求',
526
+ bunHint: 'OpenCode 免费模型会拒绝 Node.js 发出的请求。这个插件使用另外安装的 Bun;OpenCode App 本身不附带可调用的 bun 执行文件。',
527
+ bunMissingHint: '未检测到 Bun。请从 bun.sh 安装,然后按“重新检测”,不需要重启 DSH。',
528
+ bunDownload: '前往下载',
529
+ bunRescan: '重新检测',
530
+ bunRescanning: '检测中…',
531
+ sectionAnonymous: '匿名通道',
532
+ anonOn: '已开启',
533
+ anonOff: '已关闭',
534
+ anonEnable: '不携带我的账号凭证发送推理请求',
535
+ anonWarning: '非官方用法:这会使用公开匿名通道,OpenCode 并未承诺其持续可用。它可能随时失效或被限流,且仍受你的网络出口 IP 限制。请确认能接受风险后再使用。',
536
+ sectionGo: 'OpenCode Go(订阅)',
537
+ goStateDisabled: '已停用',
538
+ goStateUnconfigured: '未配置密钥',
539
+ goStateChecking: '验证中…',
540
+ goStateConnected: '已连接',
541
+ goStateInvalidKey: '密钥无效',
542
+ goStateNoEntitlement: '无 Go 订阅权益',
543
+ goStatePermissionPolicy: '权限或政策受限',
544
+ goStateRateLimited: '速率受限',
545
+ goStateTransient: '暂时故障',
546
+ goStateRedirectBlocked: '已拦截重定向',
547
+ goStateInvalidResponse: '响应格式无效',
548
+ goProviderIdLabel: 'Provider 标识符',
549
+ goCredStatusLabel: 'API 密钥',
550
+ goCredSourceDsh: 'DSH 安全凭证 ({ref})',
551
+ goCredSourceEnv: '环境变量 ({ref})',
552
+ goCredSourceMissing: '未找到 ({ref})',
553
+ goCheckedAt: '上次验证',
554
+ goUsageSummary: '用量窗口',
555
+ goWindowRolling: '5h Limit',
556
+ goWindowWeekly: '7D Limit',
557
+ goWindowMonthly: '1M Limit',
558
+ goWindowResetsAt: '将于 {when} 重置',
559
+ goWindowUnavailable: '–',
560
+ goExtraUsageWarn: '⚠ 若 Console 开启了 Extra Usage,超出订阅额度后可能会扣款工作区余额。',
561
+ goPreviewHint: '已验证的 Go 对话/工具模型会发布到 DSH 选单(仅已实测通过 Go 端点的模型开放图片输入;未验证的图片、影片、推理与非对话协议能力不予开放)。',
562
+ goDisabledHint: '已在插件设置中关闭(goSubscription.enabled: false)。如需启用,请重新开启并通过 DSH 凭证服务或 OPENCODE_GO_API_KEY 提供 OpenCode Console Personal API Key。',
563
+ goRefresh: '重新验证',
564
+ goRefreshing: '验证中…',
565
+ goClear: '清除缓存',
566
+ goPreviewTitle: '工作区模型预览 ({count})',
567
+ goPreviewEmpty: '尚未载入预览模型。',
568
+ goModelTypeUnknown: '类型:未知',
569
+ goContextCap: '上下文 {value}',
570
+ goOutputCap: '输出 {value}',
571
+ goCapReasoning: '推理',
572
+ goCapTools: '工具',
573
+ goCapAttachment: '附件',
574
+ goModalityInput: '输入:{list}',
575
+ goKeyFieldLabel: 'OpenCode Console Personal API Key ({ref})',
576
+ goKeyStoredStatus: '已保存',
577
+ goKeyUnsetStatus: '未设置',
578
+ goKeyStoredPlaceholder: '已保存(输入新密钥即可覆盖)',
579
+ goKeyMissingPlaceholder: '输入 OpenCode Console Personal API Key',
580
+ goKeySave: '保存',
581
+ goKeySaving: '保存中…',
582
+ goKeyChange: '更换密钥',
583
+ goKeyCancel: '取消',
584
+ goKeyDrawer: '密钥',
585
+ goApiOnlyNote: '目前 OpenCode Go 仅支持 Console Personal API Key 授权(不共用免费 OAuth 账号)。',
586
+ goKeyClear: '清除密钥',
587
+ goKeyClearing: '清除中…',
588
+ goKeySavedMsg: '已将 OpenCode Go API key 保存到 DSH 凭证存储。',
589
+ goKeyClearedMsg: '已从 DSH 凭证存储清除 OpenCode Go API key。',
590
+ goKeyWriteUnavailable: '当前 DSH 进程未提供凭证书写接口 (ctx.credentials.set),无法保存密钥,也不会写入插件配置或 JSON 文件。',
591
+ goFilterAll: '全部',
592
+ goFilterPicker: '可用于选单',
593
+ goFilterPreview: '仅预览',
594
+ goColType: '类型',
595
+ goColOutput: '输出上限',
596
+ goColCaps: '目录能力',
597
+ goStatusInPicker: '已进入选单',
598
+ goStatusPreviewOnly: '仅预览',
599
+ goReasonInactiveStatus: '状态:{status}',
600
+ goReasonMissingType: '缺类型',
601
+ goReasonUnsupportedType: '非对话类型 ({type})',
602
+ goReasonMissingLimits: '缺上限',
603
+ goReasonNonTextModality: '非文字模态',
604
+ goReasonNotConnected: '订阅未连接',
605
+ goReasonInvalidModel: '模型资料无效',
606
+ goReasonIneligible: '未符合正式选单资格',
607
+ goReasonNotVerified: '尚未验证选单资格',
608
+ goPickerEligibleNote: '已验证的 Go 对话模型,自动发布到 DSH 选单(支持文字与工具呼叫;无即时探测或延迟测量)。',
609
+ goPreviewOnlyNote: '目前仅供预览,不会进入 DSH 正式选单:{reasons}。',
610
+ goSupportScopeNote: '目录字段仅代表上游声明;本插件 Go 通道支持文字对话与工具呼叫,并会依据上游目录的 image/image/* 声明自动开放图片输入;不支持影片、音频或其他文件附件。',
611
+ goModelSupportImage: '本插件实际支持:文字对话、工具呼叫与图片输入(依上游目录 image 声明自动开放,实际效果以上游端点为准;不支持影片、音频与文件附件)。',
612
+ goModelSupportTextOnly: '本插件实际支持:仅文字对话与工具呼叫(上游目录未声明支持图片输入,附带图片时将于送出前拒绝)。',
613
+ goCatalogMetaLabel: '目录声明:{meta}',
614
+ goExpandModelId: '模型 ID:{id}',
615
+ goExpandModelName: '显示名称:{name}',
616
+ goExpandProvider: '提供者:{owner}',
617
+ goExpandInputLimit: '输入上限:{value}',
618
+ goExpandModalityIn: '输入模态:{list}',
619
+ goExpandModalityOut: '输出模态:{list}',
620
+ goNoMatch: '没有符合目前筛选条件的 Go 模型。',
621
+ sectionAutoSwitch: '自动切换账号',
622
+ sectionFallback: '模型备用',
623
+ autoSwitchEnable: '确认凭证失效后自动切换账号',
624
+ autoSwitchHint: '默认关闭。仅同一已保存账号刷新后仍收到 401 才切换;限流与网络/模型封锁不会触发。',
625
+ autoSwitchSaved: '自动切换账号设置已保存。',
626
+ fallbackEnable: '模型失败时自动切换到下一顺位',
627
+ fallbackHint: '只在这个模型本身出问题时切换(已下线、已下架、地区限制、超时)。网络被挡或授权失效会直接报告,不会被静默跳过。',
628
+ fallbackSlot: '第 {n} 顺位',
629
+ fallbackNone: '未设置',
630
+ fallbackSave: '保存',
631
+ fallbackSaving: '保存中…',
632
+ fallbackSaved: '备用设置已保存。',
633
+ fallbackOffNote: '备用已关闭。模型失败时会直接返回错误。',
634
+ fallbackNeedProbe: '请先探测模型,才能从可用的模型里选择顺位。',
635
+
636
+ rFreeTier: '免费通道拒绝此请求',
637
+ rNetworkBlocked: '网络出口被挡 — 请关闭 VPN/proxy',
638
+ rRegion: '此模型受地区限制',
639
+ rUnauthorized: '授权被拒',
640
+ rForbidden: '上游拒绝(403)',
641
+ rQuota: '额度已用尽',
642
+ rRateLimit: '被限流',
643
+ rUpstream: '上游服务器异常',
644
+ rNotFound: '找不到模型',
645
+ rDeprecated: '模型已下线',
646
+ rUnavailable: '模型当前不可用',
647
+ shortUnavailable: '不可用',
648
+ shortDeprecated: '已下线',
649
+ shortQuota: '额度',
650
+ shortRateLimit: '限流',
651
+ shortRegion: '地区限制',
652
+ shortFreeTier: '通道拒绝',
653
+ shortNetwork: '网络',
654
+ shortTransport: '离线',
655
+ shortNotFound: '未找到',
656
+ shortUpstream: '上游错误',
657
+ shortBadRequest: '请求被拒',
658
+ shortContextOverflow: '超长',
659
+ shortUnauthorized: '未授权',
660
+ shortForbidden: '禁止',
661
+ shortUnknown: '未知',
662
+ rContextOverflow: '内容超过上下文上限',
663
+ rBadRequest: '上游拒绝(400,无说明)',
664
+ rTransport: '连接失败',
665
+ availRatio: '{a}/{b} 个模型可用',
666
+ rUnknown: '未知状态',
667
+
668
+ detailProvider: 'Provider 标识符',
669
+ detailVersion: '插件版本',
670
+ detailProbeInterval: '探测间隔',
671
+ detailCatalogPoll: '目录轮询',
672
+ detailPixelBudget: '图像像素预算',
673
+ detailMaxBytes: '图像字节上限',
674
+ detailAutoDetect: '自动检测模型',
675
+ detailGenerated: '状态采样时间',
676
+
677
+ on: '开启',
678
+ off: '关闭',
679
+ errorGeneric: '发生错误:{message}',
680
+ loadFailed: '无法读取插件状态。',
681
+ intervalHours: '{h} 小时',
682
+ intervalMinutes: '{m} 分钟',
683
+
684
+ /* 语言切换键 */
685
+ languageLabel: '语言',
686
+ languageAuto: '跟随系统',
687
+ languageEn: 'English',
688
+ languageZh: '简体中文',
689
+ languageZhHant: '繁體中文',
690
+ languageOf_en: 'English',
691
+ languageOf_zh: '简体中文',
692
+ 'languageOf_zh-Hant': '繁體中文',
693
+ },
694
+
695
+ 'zh-Hant': {
696
+ nav: 'OpenCode-Next',
697
+ title: 'OpenCode-Next',
698
+ subtitle: '登入授權狀態、這個 provider 提供的模型,以及每個模型最近一次探測的回應。',
699
+ refreshing: '正在重新整理…',
700
+ login: '登入',
701
+ loggingIn: '等待授權中…',
702
+ cancelling: '正在取消…',
703
+ cancelLogin: '取消登入',
704
+ reauth: '重新登入',
705
+ importLocal: '從 OpenCode Desktop 匯入',
706
+ importingLocal: '匯入中…',
707
+ importLocalDone: '已把 OpenCode Desktop 的登入狀態匯入為帳號。',
708
+ importLocalAlready: '這組 OpenCode Desktop 登入已經匯入過。',
709
+ logout: '登出',
710
+ reprobe: '一鍵探測',
711
+ reprobeAvailable: '探測可用 ({n})',
712
+ reprobeFiltered: '探測清單 ({n})',
713
+ probing: '探測中…',
714
+ verify: '重新驗證憑證',
715
+
716
+ sectionAccount: '授權狀態',
717
+ sectionAccounts: '帳號', accountAdd: '新增帳號', accountLabel: '帳號標籤', accountLabelPlaceholder: '可選標籤', accountStart: '開始登入', accountCancel: '取消', accountSwitch: '切換', accountActive: '使用中', accountExpired: '已過期', accountExpiry: '剩餘 {time}', accountRemove: '移除', accountRemoveConfirm: '確定移除這個帳號?此動作無法復原。', accountCannotRemoveLast: '至少要保留一個帳號', accountSwitched: '已切換到 {label}', accountNoLabel: '未命名', accountAddHint: '透過裝置授權登入新的 OpenCode 帳號。',
718
+ sectionModels: '模型',
719
+ sectionDetails: '診斷資訊',
720
+
721
+ stateReady: '正常',
722
+ stateExpiring: '即將過期',
723
+ stateUnprobed: '尚未探測',
724
+ stateSignedOut: '尚未登入',
725
+ stateExpired: '已過期',
726
+ stateNoModels: '沒有模型回應',
727
+ stateDegraded: '部分模型不可用',
728
+ stateUnknown: '未知',
729
+
730
+ hReady: '授權有效,模型可用。',
731
+ hSignedOut: '尚未登入 OpenCode,請先完成裝置授權。',
732
+ hExpired: '授權已過期,請重新登入或重新整理憑證。',
733
+ hNoModels: '授權正常,但目前沒有任何模型回應;可能是免費通道被擋或出口 IP 受限。',
734
+ hDegraded: '授權有效,但並非所有模型都能用;請看下方的分類統計。',
735
+ hUnprobed: '授權正常,尚未探測模型可用性。',
736
+ hExpiring: '授權即將到期,系統會自動重新整理。',
737
+
738
+ credAbsent: '沒有憑證',
739
+ credSource: '來源',
740
+ credExpiry: '到期',
741
+ credRefreshable: '自動更新',
742
+ credYes: '可用',
743
+ credNo: '不可用',
744
+ srcAccounts: '已登入帳號',
745
+ srcLocalDb: 'OpenCode Desktop 資料庫',
746
+ srcAuthJson: 'OpenCode auth.json',
747
+ srcTokenFile: '本外掛儲存',
748
+ srcUnknown: '未知來源',
749
+
750
+ expiresIn: '剩餘 {time}',
751
+ expiresAt: '於 {when}',
752
+ expiresPast: '已過期',
753
+ expiresNoExpiry: '未回報到期時間',
754
+
755
+ signedOutHint: '尚未取得 OpenCode 憑證。可在下方登入,或以 OpenCode Desktop 登入後由本外掛自動沿用其 token。',
756
+ loginHint: '開啟下列網址,並確認網頁上顯示的代碼與此相同:',
757
+ userCode: '代碼',
758
+ openAgain: '再次開啟登入頁',
759
+ waiting: '應該已開啟瀏覽器視窗,請在該頁面同意授權;本頁會自動更新。',
760
+ loginCancelled: '這次登入已取消,因為你已登出。準備好時再重新開始即可。',
761
+ loginFailed: '登入沒有完成:{message}',
762
+ loginFailedTimeout: '登入逾時。準備好時再重新開始即可。',
763
+ loginFailedDenied: '授權被拒絕。若仍要連線,請重新開始登入。',
764
+ loginFailedExpired: '這組登入代碼已過期。請重新開始以取得新的代碼。',
765
+ loginFailedNetwork: '連不到 OpenCode。請檢查網路後再試一次。',
766
+ copy: '複製',
767
+ copied: '已複製',
768
+
769
+ modelsAvailable: '{total} 個中有 {ok} 個有回應',
770
+ filterAll: '全部',
771
+ filterAvailable: '可用',
772
+ filterCount: '顯示 {shown}/{total}',
773
+ rowDetails: '展開探測細節與上下文大小',
774
+ modelFilters: '依模型可用狀態或探測結果篩選',
775
+ probedAgo: '上次探測:{when}(手動)',
776
+ neverProbed: '尚未探測(手動模式)',
777
+ truncatedRateLimit: '本輪只驗了 {tested}/{total}:某個模型遇到限流或額度用盡就停手。未驗的模型保留上次結果。',
778
+ truncatedUnreachable: '本輪只驗了 {tested}/{total}:免費通道中斷。未驗的模型保留上次結果。',
779
+ quotaReset: '免費額度將於 {when} 重置(還有 {in})。',
780
+ quotaResetReady: '免費額度視窗已重置,可以重新探測或對話。',
781
+ quotaResetUnknown: '免費額度已用盡;上游沒有說明何時重置。',
782
+ colModel: '模型',
783
+ colStatus: '狀態',
784
+ colContext: '上下文',
785
+ colLatency: '延遲',
786
+ statusOk: '正常',
787
+ statusFail: '不可用',
788
+ statusLimited: '受限',
789
+ statusUnprobed: '未探測',
790
+ pickerAvailable: '在模型清單中',
791
+ pickerHidden: '已從模型清單隱藏',
792
+ colPicker: '顯示',
793
+ pickerShow: '在模型清單中顯示',
794
+ pickerManual: '手動挑選 — 顯示 {n}/{total} 個,新模型不再自動出現。',
795
+ pickerAuto: '自動 — 所有通過驗證的模型都會顯示。',
796
+ pickerReset: '顯示全部可用模型',
797
+ pickerResetBusy: '還原中…',
798
+ pickerAutoShort: '自動',
799
+ pickerManualShort: '手選',
800
+ modelProbedAt: '探測時間:{when}',
801
+ modelFailureStreak: '連續失敗 {count}/2 次',
802
+ modelsCaption: '可用狀態',
803
+ tabAccount: '帳號',
804
+ tabModels: '免費模型',
805
+ tabAdvanced: '進階',
806
+ tabGo: 'OpenCode Go',
807
+ unitDay: '天',
808
+ unitHour: '小時',
809
+ unitMinute: '分',
810
+ unitLessThanMinute: '不到 1 分鐘',
811
+ showAll: '顯示全部 {n} 個模型',
812
+ showRest: '顯示其餘 {n} 個(共 {total} 個)',
813
+ showLess: '顯示較少',
814
+ onlyProblems: '只看有問題的',
815
+ searchPlaceholder: '篩選模型',
816
+ noMatch: '沒有符合的模型。',
817
+ contextSummary: '上下文大小:{effective} tokens · {source}',
818
+ contextSetting: '上下文大小',
819
+ contextMode: '容量來源',
820
+ contextDefault: '跟隨 OpenCode 預設值',
821
+ contextCustom: '自訂數值',
822
+ contextPublished: '目錄/預設值:{value} tokens',
823
+ contextSourceOpenCode: 'OpenCode 模型目錄',
824
+ contextSourceFallback: '外掛備援值',
825
+ contextSourceCustom: '手動覆寫',
826
+ contextValue: '上下文大小(tokens)',
827
+ contextHint: '此數值只會改變 DSH 的模型預算,不會提高 OpenCode 的實際上限,也不會改變 DSH 的壓縮策略。',
828
+ contextSave: '儲存',
829
+ contextSaving: '儲存中…',
830
+ contextReset: '恢復預設值',
831
+ contextSaved: '上下文設定已儲存。',
832
+ contextInvalid: '請輸入 1,024 到 100,000,000 之間的整數。',
833
+ contextClickToEdit: '按一下設定上下文上限',
834
+ contextModalTitle: '設定上下文上限',
835
+ contextModalSub: '模型:{id}',
836
+ contextDefaultValue: '上游預設值:{value} tokens',
837
+ contextMaxOutput: '單次回覆輸出上限:{value} tokens',
838
+ contextCustomLabel: '自訂上限(tokens)',
839
+ contextResetToDefault: '恢復預設值',
840
+ contextCancel: '取消',
841
+ contextSaveBtn: '儲存',
842
+ contextCustomBadge: '自訂',
843
+
844
+ sectionAdvanced: '進階設定',
845
+ sectionBun: 'Bun 執行環境',
846
+ bunInstalled: '已偵測到',
847
+ bunMissing: '未安裝',
848
+ bunVersion: '版本',
849
+ bunPath: '執行檔',
850
+ bunEnabled: '推論傳輸',
851
+ bunUsed: 'Bun',
852
+ bunNode: 'Node.js',
853
+ bunLast: '最近一次請求',
854
+ bunLastNone: '這個行程還沒有送出推論請求',
855
+ bunHint: 'OpenCode 免費模型會拒絕 Node.js 發出的請求。這個外掛使用另外安裝的 Bun;OpenCode App 本身不附帶可呼叫的 bun 執行檔。',
856
+ bunMissingHint: '未偵測到 Bun。請從 bun.sh 安裝,然後按「重新檢測」,不需要重啟 DSH。',
857
+ bunDownload: '前往下載',
858
+ bunRescan: '重新檢測',
859
+ bunRescanning: '檢測中…',
860
+ sectionAnonymous: '匿名通道',
861
+ anonOn: '已開啟',
862
+ anonOff: '已關閉',
863
+ anonEnable: '不攜帶我的帳號憑證送出推論請求',
864
+ anonWarning: '非官方用法:這會使用公開匿名通道,OpenCode 並未承諾其持續可用。它可能隨時失效或被限流,且仍受你的網路出口 IP 限制。請確認能接受風險後再使用。',
865
+ sectionGo: 'OpenCode Go(訂閱)',
866
+ goStateDisabled: '已停用',
867
+ goStateUnconfigured: '未設定密鑰',
868
+ goStateChecking: '驗證中…',
869
+ goStateConnected: '已連線',
870
+ goStateInvalidKey: '密鑰無效',
871
+ goStateNoEntitlement: '無 Go 訂閱權益',
872
+ goStatePermissionPolicy: '權限或政策受限',
873
+ goStateRateLimited: '速率受限',
874
+ goStateTransient: '暫時故障',
875
+ goStateRedirectBlocked: '已攔截重新導向',
876
+ goStateInvalidResponse: '回應格式無效',
877
+ goProviderIdLabel: 'Provider 識別碼',
878
+ goCredStatusLabel: 'API 密鑰',
879
+ goCredSourceDsh: 'DSH 安全憑證 ({ref})',
880
+ goCredSourceEnv: '環境變數 ({ref})',
881
+ goCredSourceMissing: '未找到 ({ref})',
882
+ goCheckedAt: '上次驗證',
883
+ goUsageSummary: '用量視窗',
884
+ goWindowRolling: '5h Limit',
885
+ goWindowWeekly: '7D Limit',
886
+ goWindowMonthly: '1M Limit',
887
+ goWindowResetsAt: '將於 {when} 重設',
888
+ goWindowUnavailable: '–',
889
+ goExtraUsageWarn: '⚠ 若 Console 開啟 Extra Usage,超出訂閱額度後可能會扣款工作區餘額。',
890
+ goPreviewHint: '已驗證的 Go 對話/工具模型會發佈到 DSH 選單(僅已實測通過 Go 端點的模型開放圖片輸入;未驗證的圖片、影片、推理與非對話協定能力不予開放)。',
891
+ goDisabledHint: '已在外掛設定中停用(goSubscription.enabled: false)。如需啟用,請重新開啟並透過 DSH 憑證服務或 OPENCODE_GO_API_KEY 提供 OpenCode Console Personal API Key。',
892
+ goRefresh: '重新驗證',
893
+ goRefreshing: '驗證中…',
894
+ goClear: '清除快取',
895
+ goPreviewTitle: '工作區模型預覽 ({count})',
896
+ goPreviewEmpty: '尚未載入預覽模型。',
897
+ goModelTypeUnknown: '類型:未知',
898
+ goContextCap: '上下文 {value}',
899
+ goOutputCap: '輸出 {value}',
900
+ goCapReasoning: '推理',
901
+ goCapTools: '工具',
902
+ goCapAttachment: '附件',
903
+ goModalityInput: '輸入:{list}',
904
+ goKeyFieldLabel: 'OpenCode Console Personal API Key ({ref})',
905
+ goKeyStoredStatus: '已儲存',
906
+ goKeyUnsetStatus: '未設定',
907
+ goKeyStoredPlaceholder: '已儲存(輸入新金鑰即可覆蓋)',
908
+ goKeyMissingPlaceholder: '輸入 OpenCode Console Personal API Key',
909
+ goKeySave: '儲存',
910
+ goKeySaving: '儲存中…',
911
+ goKeyChange: '更換金鑰',
912
+ goKeyCancel: '取消',
913
+ goKeyDrawer: '金鑰',
914
+ goApiOnlyNote: '目前 OpenCode Go 僅支援 Console Personal API Key 授權(不共用免費 OAuth 帳號)。',
915
+ goKeyClear: '清除金鑰',
916
+ goKeyClearing: '清除中…',
917
+ goKeySavedMsg: '已將 OpenCode Go API key 儲存至 DSH 憑證服務。',
918
+ goKeyClearedMsg: '已從 DSH 憑證服務清除 OpenCode Go API key。',
919
+ goKeyWriteUnavailable: '目前 DSH 行程未提供憑證寫入介面 (ctx.credentials.set),無法儲存金鑰,也不會寫入外掛設定或 JSON 檔案。',
920
+ goFilterAll: '全部',
921
+ goFilterPicker: '可用於選單',
922
+ goFilterPreview: '僅預覽',
923
+ goColType: '類型',
924
+ goColOutput: '輸出上限',
925
+ goColCaps: '目錄能力',
926
+ goStatusInPicker: '已進入選單',
927
+ goStatusPreviewOnly: '僅預覽',
928
+ goReasonInactiveStatus: '狀態:{status}',
929
+ goReasonMissingType: '缺類型',
930
+ goReasonUnsupportedType: '非對話類型 ({type})',
931
+ goReasonMissingLimits: '缺上限',
932
+ goReasonNonTextModality: '非文字模態',
933
+ goReasonNotConnected: '訂閱未連線',
934
+ goReasonInvalidModel: '模型資料無效',
935
+ goReasonIneligible: '未符合正式選單資格',
936
+ goReasonNotVerified: '尚未驗證選單資格',
937
+ goPickerEligibleNote: '已驗證的 Go 對話模型,自動發佈到 DSH 選單(支援文字與工具呼叫;無即時探測或延遲測量)。',
938
+ goPreviewOnlyNote: '目前僅供預覽,不會進入 DSH 正式選單:{reasons}。',
939
+ goSupportScopeNote: '目錄欄位僅代表上游宣告;本外掛 Go 通道支援文字對話與工具呼叫,並會依上游目錄的 image/image/* 宣告自動開放圖片輸入;不支援影片、音訊或其他檔案附件。',
940
+ goModelSupportImage: '本外掛實際支援:文字對話、工具呼叫與圖片輸入(依上游目錄 image 宣告自動開放,實際可否辨識以上游端點為準;不支援影片、音訊與檔案附件)。',
941
+ goModelSupportTextOnly: '本外掛實際支援:僅文字對話與工具呼叫(上游目錄未宣告圖片輸入,附帶圖片時將於送出前拒絕)。',
942
+ goCatalogMetaLabel: '目錄宣告:{meta}',
943
+ goExpandModelId: '模型 ID:{id}',
944
+ goExpandModelName: '顯示名稱:{name}',
945
+ goExpandProvider: '提供者:{owner}',
946
+ goExpandInputLimit: '輸入上限:{value}',
947
+ goExpandModalityIn: '輸入模態:{list}',
948
+ goExpandModalityOut: '輸出模態:{list}',
949
+ goNoMatch: '沒有符合目前篩選條件的 Go 模型。',
950
+ sectionAutoSwitch: '自動切換帳號',
951
+ sectionFallback: '模型備援',
952
+ autoSwitchEnable: '確認憑證失效後自動切換帳號',
953
+ autoSwitchHint: '預設關閉。僅同一個已儲存帳號刷新後仍收到 401 才切換;限流與網路/模型封鎖不會觸發。',
954
+ autoSwitchSaved: '自動切換帳號設定已儲存。',
955
+ fallbackEnable: '模型失敗時自動切換到下一順位',
956
+ fallbackHint: '只在「這個模型自己出問題」時切換(已下線、已下架、地區限制、逾時)。網路被擋或授權失效會直接回報,不會被靜默跳過。',
957
+ fallbackSlot: '第 {n} 順位',
958
+ fallbackNone: '未設定',
959
+ fallbackSave: '儲存',
960
+ fallbackSaving: '儲存中…',
961
+ fallbackSaved: '備援設定已儲存。',
962
+ fallbackOffNote: '備援已關閉。模型失敗時會直接回傳錯誤。',
963
+ fallbackNeedProbe: '請先探測模型,才能從可用的模型裡選擇順位。',
964
+
965
+ rFreeTier: '免費通道拒絕此請求',
966
+ rNetworkBlocked: '網路出口被擋 — 請關閉 VPN/proxy',
967
+ rRegion: '此模型受地區限制',
968
+ rUnauthorized: '授權遭拒',
969
+ rForbidden: '上游拒絕(403)',
970
+ rQuota: '額度已用盡',
971
+ rRateLimit: '被限流',
972
+ rUpstream: '上游伺服器異常',
973
+ rNotFound: '找不到模型',
974
+ rDeprecated: '模型已下架',
975
+ rUnavailable: '模型目前不可用',
976
+ shortUnavailable: '不可用',
977
+ shortDeprecated: '已下架',
978
+ shortQuota: '額度',
979
+ shortRateLimit: '限流',
980
+ shortRegion: '地區限制',
981
+ shortFreeTier: '通道拒絕',
982
+ shortNetwork: '網路',
983
+ shortTransport: '離線',
984
+ shortNotFound: '未找到',
985
+ shortUpstream: '上游錯誤',
986
+ shortBadRequest: '請求被拒',
987
+ shortContextOverflow: '超長',
988
+ shortUnauthorized: '未授權',
989
+ shortForbidden: '禁止',
990
+ shortUnknown: '未知',
991
+ rContextOverflow: '內容超過上下文上限',
992
+ rBadRequest: '上游拒絕(400,無說明)',
993
+ rTransport: '連線失敗',
994
+ availRatio: '{a}/{b} 個模型可用',
995
+ rUnknown: '未知狀態',
996
+
997
+ detailProvider: 'Provider 識別碼',
998
+ detailVersion: '外掛版本',
999
+ detailProbeInterval: '探測間隔',
1000
+ detailCatalogPoll: '目錄輪詢',
1001
+ detailPixelBudget: '圖片像素預算',
1002
+ detailMaxBytes: '圖片位元組上限',
1003
+ detailAutoDetect: '自動偵測模型',
1004
+ detailGenerated: '狀態取樣時間',
1005
+
1006
+ on: '開啟',
1007
+ off: '關閉',
1008
+ errorGeneric: '發生錯誤:{message}',
1009
+ loadFailed: '無法讀取外掛狀態。',
1010
+ intervalHours: '{h} 小時',
1011
+ intervalMinutes: '{m} 分鐘',
1012
+
1013
+ /* 語言切換鍵 */
1014
+ languageLabel: '語言',
1015
+ languageAuto: '跟隨系統',
1016
+ languageEn: 'English',
1017
+ languageZh: '简体中文',
1018
+ languageZhHant: '繁體中文',
1019
+ languageOf_en: 'English',
1020
+ languageOf_zh: '简体中文',
1021
+ 'languageOf_zh-Hant': '繁體中文',
1022
+ }
1023
+ };
1024
+
1025
+ /* --------------------------------------------------------------- 工具 */
1026
+
1027
+ /* --------------------------------------------------------- 語言選擇
1028
+
1029
+ 四個選項:跟隨系統、English、簡體中文、繁體中文。
1030
+
1031
+ 為什麼不直接用宿主的 `ctx.locale.bind()`:那個 translator 走的是
1032
+ `fallbackChain(snapshot.active)`,而 `snapshot.active` 是**全域** DSH 語言。
1033
+ 用它就等於「切換語言時整個 DSH 都跟著變」,而且 `setLocale()` 會把選擇
1034
+ 寫進 DSH 使用者設定。本外掛要的是「只改自己這一頁」,所以自己維護一份
1035
+ 語言狀態,完全不碰宿主偏好。
1036
+
1037
+ 註:這裡刻意把「簡體中文」寫成繁體字。字典裡的值必須是簡體(那是資料),
1038
+ 但程式碼與註解一律繁體——專案有自動掃描在盯這件事。 */
1039
+
1040
+ /** 語言偏好的儲存鍵(存在外掛自己的檔案,不是 DSH 設定)。 */
1041
+ const LANG_STORAGE_KEY = 'opencode-next.language';
1042
+
1043
+ /** 切換鍵的四個選項。`auto` 代表跟隨系統。 */
1044
+ const LANGUAGE_OPTIONS = [
1045
+ { id: 'auto', label: 'languageAuto' },
1046
+ { id: 'en', label: 'languageEn' },
1047
+ { id: 'zh', label: 'languageZh' },
1048
+ { id: 'zh-Hant', label: 'languageZhHant' }
1049
+ ];
1050
+
1051
+ const SUPPORTED_LOCALES = ['en', 'zh', 'zh-Hant'];
1052
+
1053
+ /**
1054
+ * 把一個 BCP 47 標籤(例如 `zh-TW`、`zh-Hant-HK`、`en-US`)對應到支援的語言。
1055
+ *
1056
+ * 順序刻意是「先看繁中線索」:`zh-Hant-TW`、`zh-TW`、`zh-HK`、`zh-MO` 都算繁中;
1057
+ * 其餘 `zh-*`(`zh-CN`、`zh-SG`、單純 `zh`)算簡中;非中文一律英文。
1058
+ *
1059
+ * 為什麼繁中要先判斷:`zh-Hant-TW` 若先比對主標籤 `zh` 就會被誤判成簡中。
1060
+ *
1061
+ * @param {string} tag 語言標籤;可為空。
1062
+ * @returns {'en'|'zh'|'zh-Hant'|null} 對應的語言 id;非中英文時回 `null`,
1063
+ * 代表「讀到了,但不在支援範圍」,由呼叫端決定要退到哪個語言。
1064
+ */
1065
+ function localeFromTag(tag) {
1066
+ const low = String(tag ?? '').toLowerCase();
1067
+ if (low.startsWith('zh')) {
1068
+ if (/hant|-tw|-hk|-mo/.test(low)) return 'zh-Hant';
1069
+ return 'zh';
1070
+ }
1071
+ if (low.startsWith('en')) return 'en';
1072
+ // 日文、德文等:不支援,而且不該被當成「英文使用者」。
1073
+ return null;
1074
+ }
1075
+
1076
+ /**
1077
+ * 決定這一頁要用哪個語言。
1078
+ *
1079
+ * 優先順序:
1080
+ * 1. 使用者明確選過(存下來的那個)→ 用它
1081
+ * 2. 選「跟隨系統」(或從未選過)→ 用主機端讀到的系統語言
1082
+ * 3. 系統語言讀不到,或**不屬於支援的語言**(例如日文、德文)
1083
+ * → 繁體中文(使用者的偏好語言)
1084
+ *
1085
+ * 第 3 點是刻意的:系統是日文時,顯示中文還是英文都算「猜」,但使用者的
1086
+ * 環境是中文,退到中文比退到英文更貼近實際情況。真要英文的話,切換鍵
1087
+ * 就在同一頁,一次點擊即可。
1088
+ *
1089
+ * 系統語言由主機端提供(`status.systemLocale`),而不是讀 `navigator.language`:
1090
+ * 實測遇過 Windows 是 `zh-TW` 但 Chrome 把 `en-US` 排第一的情況,跟瀏覽器
1091
+ * 會得到英文,不是使用者的介面語言。
1092
+ *
1093
+ * @param {string|null} stored 儲存的偏好(`auto` 或某個語言 id)。
1094
+ * @param {string|null} systemLocale 主機端讀到的系統語言標籤。
1095
+ * @returns {'en'|'zh'|'zh-Hant'}
1096
+ */
1097
+ function resolveLocale(stored, systemLocale) {
1098
+ if (stored && SUPPORTED_LOCALES.includes(stored)) return stored;
1099
+ // stored 是 'auto'、null 或任何不認得的值 → 跟隨系統。
1100
+ if (typeof systemLocale === 'string' && systemLocale) {
1101
+ const mapped = localeFromTag(systemLocale);
1102
+ if (mapped && SUPPORTED_LOCALES.includes(mapped)) return mapped;
1103
+ }
1104
+ // 讀不到,或系統語言不在支援範圍 → 預設繁體中文。
1105
+ return 'zh-Hant';
1106
+ }
1107
+
1108
+ /** 讀取儲存的語言偏好。localStorage 不可用時安靜地回傳 null。 */
1109
+ function readStoredLanguage() {
1110
+ try {
1111
+ const raw = window.localStorage.getItem(LANG_STORAGE_KEY);
1112
+ if (raw === null) return null;
1113
+ if (raw === 'auto' || SUPPORTED_LOCALES.includes(raw)) return raw;
1114
+ return null;
1115
+ } catch {
1116
+ return null;
1117
+ }
1118
+ }
1119
+
1120
+ /** 模型分類篩選的儲存鍵。 */
1121
+ const FILTER_STORAGE_KEY = 'opencode-next.model-filter';
1122
+
1123
+ function readStoredFilter() {
1124
+ try {
1125
+ const raw = window.localStorage.getItem(FILTER_STORAGE_KEY);
1126
+ if (typeof raw === 'string' && raw.trim()) return raw.trim();
1127
+ return null;
1128
+ } catch {
1129
+ return null;
1130
+ }
1131
+ }
1132
+
1133
+ function writeStoredFilter(value) {
1134
+ try {
1135
+ if (typeof value === 'string' && value) {
1136
+ window.localStorage.setItem(FILTER_STORAGE_KEY, value);
1137
+ } else {
1138
+ window.localStorage.removeItem(FILTER_STORAGE_KEY);
1139
+ }
1140
+ return true;
1141
+ } catch {
1142
+ return false;
1143
+ }
1144
+ }
1145
+
1146
+ /** 寫入語言偏好。失敗(例如無痕模式)不影響畫面。 */
1147
+ function writeStoredLanguage(value) {
1148
+ try {
1149
+ window.localStorage.setItem(LANG_STORAGE_KEY, value);
1150
+ return true;
1151
+ } catch {
1152
+ return false;
1153
+ }
1154
+ }
1155
+
1156
+ function translator(locale) {
1157
+ const table = COPY[locale] ?? COPY.en;
1158
+ const lookup = (obj, key) =>
1159
+ key.split('.').reduce((node, part) => (node == null ? undefined : node[part]), obj);
1160
+ return (key, vars) => {
1161
+ const text = String(lookup(table, key) ?? lookup(COPY.en, key) ?? key);
1162
+ return vars
1163
+ ? text.replace(/\{(\w+)\}/g, (m, name) => (name in vars ? String(vars[name]) : m))
1164
+ : text;
1165
+ };
1166
+ }
1167
+
1168
+ async function callApi(pathname, method = 'GET', body) {
1169
+ const res = await fetch(`${API}/${pathname}`, {
1170
+ method,
1171
+ headers: method === 'POST' ? { 'content-type': 'application/json' } : undefined,
1172
+ body: method === 'POST' ? JSON.stringify(body ?? {}) : undefined
1173
+ });
1174
+ const text = await res.text();
1175
+ let data;
1176
+ try {
1177
+ data = JSON.parse(text);
1178
+ } catch {
1179
+ throw new Error(`HTTP ${res.status}`);
1180
+ }
1181
+ if (!data.ok) {
1182
+ const error = new Error(data.message || data.error || `HTTP ${res.status}`);
1183
+ error.code = data.error;
1184
+ throw error;
1185
+ }
1186
+ return data.value;
1187
+ }
1188
+
1189
+ /**
1190
+ * 剩餘時間的人話版本。
1191
+ *
1192
+ * 原本回傳 "26d 15h"、"41m" 這種英文單位,混在整頁中文裡非常突兀
1193
+ * (截圖上「剩餘 26d 15h」就夾在「剩餘 27d 16h」旁邊)。改成呼叫端傳入的
1194
+ * 單位字串,讓每個語言用自己的寫法。
1195
+ *
1196
+ * 保留 `shortDuration` 這個名字與數值邏輯:單位只是最後一層包裝。
1197
+ */
1198
+ function shortDuration(ms, units) {
1199
+ if (ms === null || ms === undefined || !Number.isFinite(ms)) return '–';
1200
+ const negative = ms < 0;
1201
+ const abs = Math.abs(ms);
1202
+ const minutes = Math.floor(abs / 60000);
1203
+ const u = units ?? { d: 'd', h: 'h', m: 'm', lessThanMinute: '<1m' };
1204
+ let out;
1205
+ if (minutes < 1) out = u.lessThanMinute;
1206
+ else if (minutes < 60) out = `${minutes}${u.m}`;
1207
+ else {
1208
+ const hours = Math.floor(minutes / 60);
1209
+ if (hours < 48) out = minutes % 60 ? `${hours}${u.h} ${minutes % 60}${u.m}` : `${hours}${u.h}`;
1210
+ else {
1211
+ const days = Math.floor(hours / 24);
1212
+ out = hours % 24 ? `${days}${u.d} ${hours % 24}${u.h}` : `${days}${u.d}`;
1213
+ }
1214
+ }
1215
+ return negative ? `-${out}` : out;
1216
+ }
1217
+
1218
+ function formatWhen(ms, localeId) {
1219
+ if (!ms) return null;
1220
+ const intl = localeId === 'en' ? 'en' : localeId === 'zh-Hant' ? 'zh-TW' : 'zh-CN';
1221
+ try {
1222
+ return new Intl.DateTimeFormat(intl, {
1223
+ month: 'short',
1224
+ day: 'numeric',
1225
+ hour: '2-digit',
1226
+ minute: '2-digit'
1227
+ }).format(new Date(ms));
1228
+ } catch {
1229
+ return new Date(ms).toLocaleString();
1230
+ }
1231
+ }
1232
+
1233
+ /** 把探測結果的內部 reason 轉成當前語言的說明。 */
1234
+ function reasonKey(reason) {
1235
+ switch (reason) {
1236
+ // 放在最前面:這是最容易被誤讀成「換模型就好」的一種失敗。
1237
+ // 它擋的是整個網路出口,換任何模型都會拿到同一段訊息。
1238
+ case 'network-blocked':
1239
+ return 'rNetworkBlocked';
1240
+ case 'free-lane-blocked':
1241
+ return 'rFreeTier';
1242
+ case 'region-restricted':
1243
+ return 'rRegion';
1244
+ case 'unauthorized':
1245
+ return 'rUnauthorized';
1246
+ case 'forbidden':
1247
+ return 'rForbidden';
1248
+ case 'quota-exceeded':
1249
+ return 'rQuota';
1250
+ case 'rate-limited':
1251
+ case 'rate-limited-explicit':
1252
+ case 'endpoint-unavailable':
1253
+ return 'rRateLimit';
1254
+ case 'upstream-error':
1255
+ return 'rUpstream';
1256
+ case 'not-found':
1257
+ return 'rNotFound';
1258
+ case 'deprecated':
1259
+ return 'rDeprecated';
1260
+ case 'unavailable':
1261
+ return 'rUnavailable';
1262
+ // 400 的三種分支各有各的處置,不可共用一個標籤:
1263
+ // 上下文超限 → 縮短訊息(模型好好的)
1264
+ // 模型不可用 → 換模型
1265
+ // 沒有說明 → 上游只回模型名稱,多半是帳號在該模型上的權限/額度
1266
+ case 'context-overflow':
1267
+ return 'rContextOverflow';
1268
+ case 'bad-request':
1269
+ return 'rBadRequest';
1270
+ case 'transport':
1271
+ return 'rTransport';
1272
+ default:
1273
+ return null;
1274
+ }
1275
+ }
1276
+
1277
+ /**
1278
+ * 分段選單用的短標籤。
1279
+ *
1280
+ * 篩選列是「一排等寬格子」,而失敗原因的完整句子(「模型目前不可用」)
1281
+ * 比「可用」長三倍;同一排混用長短標籤,格寬就會參差、選中項也會跟著
1282
+ * 變寬,看起來像一個塞錯地方的輸入框。這裡給每個原因一個短名詞,
1283
+ * 完整句子仍然留在表格列的狀態底下。
1284
+ */
1285
+ function shortReasonKey(reason) {
1286
+ switch (reason) {
1287
+ case 'network-blocked': return 'shortNetwork';
1288
+ case 'free-lane-blocked': return 'shortFreeTier';
1289
+ case 'region-restricted': return 'shortRegion';
1290
+ case 'unauthorized': return 'shortUnauthorized';
1291
+ case 'forbidden': return 'shortForbidden';
1292
+ case 'quota-exceeded': return 'shortQuota';
1293
+ case 'rate-limited':
1294
+ case 'rate-limited-explicit':
1295
+ case 'endpoint-unavailable': return 'shortRateLimit';
1296
+ case 'upstream-error': return 'shortUpstream';
1297
+ case 'not-found': return 'shortNotFound';
1298
+ case 'deprecated': return 'shortDeprecated';
1299
+ case 'unavailable': return 'shortUnavailable';
1300
+ case 'context-overflow': return 'shortContextOverflow';
1301
+ case 'bad-request': return 'shortBadRequest';
1302
+ case 'transport': return 'shortTransport';
1303
+ default: return null;
1304
+ }
1305
+ }
1306
+
1307
+ function healthChip(health) {
1308
+ switch (health) {
1309
+ case 'ready':
1310
+ return { tone: 'ok', key: 'stateReady' };
1311
+ case 'expiring':
1312
+ return { tone: 'warn', key: 'stateExpiring' };
1313
+ case 'unprobed':
1314
+ return { tone: 'warn', key: 'stateUnprobed' };
1315
+ case 'signed-out':
1316
+ return { tone: 'off', key: 'stateSignedOut' };
1317
+ case 'expired':
1318
+ return { tone: 'off', key: 'stateExpired' };
1319
+ case 'no-models':
1320
+ return { tone: 'off', key: 'stateNoModels' };
1321
+ // 部分模型可用:黃燈。
1322
+ //
1323
+ // 這是舊版最大的盲點——只要還有 1 個模型活著就亮綠燈,於是 45 個壞 34 個
1324
+ // 的時候畫面看起來一切正常。黃燈的意義是「能用,但別當成沒事」。
1325
+ case 'degraded':
1326
+ return { tone: 'warn', key: 'stateDegraded' };
1327
+ default:
1328
+ return { tone: 'warn', key: 'stateUnknown' };
1329
+ }
1330
+ }
1331
+
1332
+ /**
1333
+ * 健康狀態那句話的翻譯鍵。
1334
+ *
1335
+ * 宿主回傳的 `healthMessage` 是一句固定的中文(status.js 不知道瀏覽器當下用
1336
+ * 什麼語言),所以英文介面若直接顯示它就會變成中英夾雜。這裡改成用 `health`
1337
+ * 這個穩定的代碼去查本地字典;只有遇到不認識的代碼時才退回宿主的字串。
1338
+ */
1339
+ function healthMessageKey(health) {
1340
+ switch (health) {
1341
+ case 'ready':
1342
+ return 'hReady';
1343
+ case 'signed-out':
1344
+ return 'hSignedOut';
1345
+ case 'expired':
1346
+ return 'hExpired';
1347
+ case 'no-models':
1348
+ return 'hNoModels';
1349
+ case 'degraded':
1350
+ return 'hDegraded';
1351
+ case 'unprobed':
1352
+ return 'hUnprobed';
1353
+ case 'expiring':
1354
+ return 'hExpiring';
1355
+ default:
1356
+ return null;
1357
+ }
1358
+ }
1359
+
1360
+ /* --------------------------------------------------------------- 樣式 */
1361
+
1362
+ function installStyle() {
1363
+ if (document.getElementById(STYLE_ID)) return;
1364
+ const style = document.createElement('style');
1365
+ style.id = STYLE_ID;
1366
+ // 只使用宿主的主題別名變數(label-*、bg-layer-*、border-l*、state-*),
1367
+ // 這樣淺色/深色會自動跟著切換,而不是把顏色寫死。三個 state token 後面
1368
+ // 的字面值只是狀態色的保險絲:別名不存在時至少還看得出紅/黃/綠。
1369
+ style.textContent = `
1370
+ .ocoa-page {
1371
+ /* 顏色全部取自宿主實際存在的別名變數(已對 app.asar 逐項核對)。
1372
+ 原本用的 accent-primary 與 label-on-accent 在宿主裡根本不存在,
1373
+ 於是主按鈕與選中項的底色是透明的、文字又是白色——看起來就是
1374
+ 「消失的按鈕」。這兩個已經換成 business-primary 系列。 */
1375
+ --ocoa-fg: var(--dsw-alias-label-primary, #0f1115);
1376
+ --ocoa-fg2: var(--dsw-alias-label-secondary, #61666b);
1377
+ --ocoa-fg3: var(--dsw-alias-label-tertiary, #81858c);
1378
+ /* 宿主把 bg-layer-1/2/3 都設成同一個白色,直接拿來堆疊會完全沒有層次。
1379
+ 所以表面色用純白,內凹/表頭改用淺藍灰(bluish-100/200)。 */
1380
+ --ocoa-surface: var(--dsw-alias-bg-layer-1, #fff);
1381
+ --ocoa-sunk: var(--dsw-static-neutral-bluish-100, #ebeef2);
1382
+ --ocoa-sunk2: var(--dsw-static-neutral-bluish-200, #e1e5ee);
1383
+ --ocoa-line: var(--dsw-alias-border-l1, #0000000a);
1384
+ --ocoa-line2: var(--dsw-alias-border-l2, #0000001a);
1385
+ --ocoa-line3: var(--dsw-alias-border-l3, #0000001f);
1386
+ /* 強調色:宿主沒有 accent-primary。button-primary-fill 在淺色主題下
1387
+ 指向 state-error-primary(紅色),拿來當主要動作色會像警告,所以改用
1388
+ state-business-primary(DeepSeek 藍 #4176e6)——它是中性強調色。 */
1389
+ --ocoa-accent: var(--dsw-alias-state-business-primary, #4176e6);
1390
+ --ocoa-on-accent: var(--dsw-alias-bg-layer-1, #fff);
1391
+ --ocoa-hover: var(--dsw-alias-interactive-bg-hover, #f3f4f6);
1392
+ --ocoa-ok: var(--dsw-alias-state-success-primary, #22c55e);
1393
+ --ocoa-off: var(--dsw-alias-state-error-primary, #ec1313);
1394
+ /* 宿主叫 state-warn-*,不是 state-warning-*。寫錯就整個警告色失效。 */
1395
+ --ocoa-warn: var(--dsw-alias-state-warn-label, #dd8629);
1396
+ --ocoa-mono: ui-monospace, "JetBrains Mono", SFMono-Regular, Menlo, Consolas, monospace;
1397
+
1398
+ /* 間距級距。整頁只用這五個值,不再出現 7px / 9px / 13px 這種散落的
1399
+ 任意數字——那正是原本看起來「哪裡怪怪的、說不出哪裡」的原因。 */
1400
+ --ocoa-s1: 4px;
1401
+ --ocoa-s2: 8px;
1402
+ --ocoa-s3: 16px;
1403
+ --ocoa-s4: 24px;
1404
+ --ocoa-s5: 32px;
1405
+
1406
+ display: flex; flex-direction: column;
1407
+ /* 這是工作面板,不是展示頁。區塊之間 12px 就分得開,
1408
+ 再拉到 24px 只是讓眼睛多走一趟,不會比較精緻。 */
1409
+ gap: 12px;
1410
+ padding: 16px 20px;
1411
+ min-width: 0; box-sizing: border-box;
1412
+ color: var(--ocoa-fg);
1413
+ background-color: var(--ocoa-surface);
1414
+ border: 1px solid var(--ocoa-line2);
1415
+ border-radius: 12px;
1416
+ line-height: 1.4;
1417
+ -webkit-font-smoothing: antialiased;
1418
+ }
1419
+ /* 所有子元素都吃 border-box:卡片內距 + 邊框若用 content-box 計算,
1420
+ 在固定寬度的面板裡會把右緣推出邊界(實測截圖就是這樣)。 */
1421
+ .ocoa-page *, .ocoa-page *::before, .ocoa-page *::after { box-sizing: border-box; }
1422
+ .ocoa-head { display: flex; flex-direction: column; gap: var(--ocoa-s2); }
1423
+
1424
+ /* 分頁籤:底線式,不用藥丸。
1425
+ 這是頁面內的分頁,不是主要動作;藥丸會跟下面的篩選按鈕撞在一起,
1426
+ 看起來像同一層級的控制項。 */
1427
+ .ocoa-tabs {
1428
+ display: flex; gap: var(--ocoa-s1); flex-wrap: wrap;
1429
+ border-bottom: 1px solid var(--ocoa-line2);
1430
+ margin: var(--ocoa-s1) 0 0;
1431
+ }
1432
+ .ocoa-tab {
1433
+ appearance: none; font: inherit; cursor: pointer;
1434
+ display: inline-flex; align-items: center; gap: 6px;
1435
+ padding: 6px 12px 7px;
1436
+ border: 0; background: none;
1437
+ color: var(--ocoa-fg2); font-size: 13px; font-weight: 500;
1438
+ border-bottom: 2px solid transparent;
1439
+ margin-bottom: -1px; white-space: nowrap;
1440
+ transition: color .13s ease, border-color .13s ease;
1441
+ }
1442
+ .ocoa-tab:hover { color: var(--ocoa-fg); }
1443
+ .ocoa-tab:focus-visible { outline: 2px solid var(--ocoa-accent); outline-offset: -2px; }
1444
+ .ocoa-tab.is-active { color: var(--ocoa-fg); font-weight: 600; border-bottom-color: var(--ocoa-accent); }
1445
+ .ocoa-tab-badge {
1446
+ font-variant-numeric: tabular-nums; font-size: 11px; font-weight: 600;
1447
+ min-width: 18px; text-align: center;
1448
+ padding: 1px 6px; border-radius: 999px; line-height: 1.5;
1449
+ background: var(--ocoa-sunk); color: var(--ocoa-fg2);
1450
+ }
1451
+ .ocoa-tab.is-active .ocoa-tab-badge { background: var(--ocoa-sunk2); color: var(--ocoa-fg); }
1452
+ .ocoa-pane { display: flex; flex-direction: column; gap: 12px; min-width: 0; }
1453
+ .ocoa-title-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
1454
+ .ocoa-title { font-size: 16px; font-weight: 650; letter-spacing: -.01em; }
1455
+ /* 副標題:只給「這頁在講什麼」一句話。行高放寬、寬度收窄,
1456
+ 讓長句斷在自然的逗號處,而不是橫貫整頁。 */
1457
+ .ocoa-sub {
1458
+ font-size: 12.5px; color: var(--ocoa-fg3);
1459
+ line-height: 1.65; max-width: 62ch;
1460
+ }
1461
+ .ocoa-msg { font-size: 12.5px; color: var(--ocoa-fg2); line-height: 1.55; }
1462
+ /* 探測被熔斷的說明。用警示色而不是一般灰字:它講的是「這次只驗了一部分」,
1463
+ 錯過它就會把 13/4 讀成完整結果。 */
1464
+ .ocoa-msg-warn { color: var(--ocoa-warn, #b45309); }
1465
+
1466
+ /* 分類篩選:淺灰底的分段控制。
1467
+ 選中項用「白底 + 內縮一圈細框」而不是浮起的陰影——陰影會讓它看起來
1468
+ 像浮在控制項外面的輸入框,尤其當它又剛好比較寬時(截圖上就是這樣)。
1469
+ 現在它仍在灰底之內,只是被「挖出來」,不會脫離那一條。 */
1470
+ .ocoa-segments {
1471
+ display: flex; gap: 2px; min-width: 0;
1472
+ padding: 3px; border-radius: 10px;
1473
+ background: var(--ocoa-sunk);
1474
+ overflow-x: auto; overflow-y: hidden;
1475
+ scrollbar-width: none;
1476
+ }
1477
+ .ocoa-segments::-webkit-scrollbar { display: none; }
1478
+ .ocoa-seg {
1479
+ appearance: none; font: inherit; cursor: pointer;
1480
+ display: inline-flex; align-items: baseline; gap: 6px;
1481
+ flex: 1 1 0; justify-content: center;
1482
+ padding: 5px 8px; min-width: 0; border-radius: 7px;
1483
+ font-size: 12px; color: var(--ocoa-fg2);
1484
+ background: transparent; border: 0;
1485
+ white-space: nowrap;
1486
+ transition: background .13s ease, color .13s ease;
1487
+ }
1488
+ .ocoa-seg:hover { color: var(--ocoa-fg); }
1489
+ .ocoa-seg:focus-visible { outline: 2px solid var(--ocoa-accent); outline-offset: -2px; }
1490
+ .ocoa-seg-count {
1491
+ font-variant-numeric: tabular-nums; font-weight: 650;
1492
+ color: var(--ocoa-fg); font-size: 13px;
1493
+ }
1494
+ /* 選中項:白底,但只用極淡的內框界定,不做陰影。 */
1495
+ .ocoa-seg.is-active {
1496
+ background: var(--ocoa-surface);
1497
+ color: var(--ocoa-fg);
1498
+ box-shadow: inset 0 0 0 1px var(--ocoa-line3);
1499
+ }
1500
+ .ocoa-seg.is-active .ocoa-seg-count { color: inherit; }
1501
+ /* 未選取時只有「可用」帶綠色;其餘一律灰字,紅色留給表格裡真正的失敗列。 */
1502
+ .ocoa-seg.is-ok:not(.is-active) .ocoa-seg-count { color: var(--ocoa-ok); }
1503
+ .ocoa-toolbar-count {
1504
+ margin-left: auto; font-size: 12px; color: var(--ocoa-fg3);
1505
+ font-variant-numeric: tabular-nums;
1506
+ }
1507
+
1508
+ .ocoa-chip {
1509
+ display: inline-flex; align-items: center; gap: 6px;
1510
+ padding: 3px 10px; border-radius: 999px; font-size: 12px; font-weight: 600;
1511
+ border: 1px solid var(--ocoa-line2); color: var(--ocoa-fg2);
1512
+ background: var(--ocoa-surface);
1513
+ }
1514
+ .ocoa-chip-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
1515
+ .ocoa-chip.ok { color: var(--ocoa-ok); border-color: color-mix(in srgb, var(--ocoa-ok) 40%, transparent); }
1516
+ .ocoa-chip.warn { color: var(--ocoa-warn); border-color: color-mix(in srgb, var(--ocoa-warn) 40%, transparent); }
1517
+ .ocoa-chip.off { color: var(--ocoa-off); border-color: color-mix(in srgb, var(--ocoa-off) 40%, transparent); }
1518
+
1519
+ /* 卡片:只留一層淡邊框。原本每張卡都有邊框 + 內距 + 表頭底線,
1520
+ 三層一起看就像一堆盒子疊起來——現在靠留白分組,不靠框線。 */
1521
+ .ocoa-card {
1522
+ background: var(--ocoa-surface);
1523
+ border: 1px solid var(--ocoa-line2);
1524
+ border-radius: 10px;
1525
+ padding: 12px 14px;
1526
+ display: flex; flex-direction: column; gap: 10px;
1527
+ min-width: 0;
1528
+ }
1529
+ .ocoa-card-head {
1530
+ display: flex; align-items: center; justify-content: space-between;
1531
+ gap: 8px; flex-wrap: wrap; min-width: 0;
1532
+ }
1533
+ /* 卡片標題用正常字重與深色,而不是灰字:它是區塊的門牌。 */
1534
+ .ocoa-card-title {
1535
+ font-size: 14px; font-weight: 600; letter-spacing: -.005em;
1536
+ color: var(--ocoa-fg);
1537
+ }
1538
+ /* 次區塊標題:同一張卡裡放兩件事時(例如進階裡的備援與診斷),
1539
+ 用比卡片標題小一級的灰字分隔,避免為了兩個小設定再開一張卡。 */
1540
+ /* 次區塊標題:同一張卡裡放兩件事時(例如進階裡的備援與診斷),
1541
+ 用比卡片標題小一級的灰字分隔,避免為了兩個小設定再開一張卡。
1542
+ 給 flex:1 讓它在 card-head 裡撐開,右側的按鈕才會真的靠到最右。 */
1543
+ .ocoa-subhead {
1544
+ font-size: 12.5px; font-weight: 600; color: var(--ocoa-fg2);
1545
+ flex: 1 1 auto; min-width: 0;
1546
+ display: inline-flex; align-items: center; gap: var(--ocoa-s2);
1547
+ }
1548
+ .ocoa-divider { height: 1px; border: 0; background: var(--ocoa-line2); margin: 0; }
1549
+ /* 帳號列:四欄固定寬度,讓「名稱/到期/動作/移除」上下對齊。
1550
+ 原本用 space-between,名稱長度不同時(OpenCode Desktop vs sa03)
1551
+ 後面幾欄的起點就跟著跑掉。
1552
+ 「到期」欄不能給太窄:宿主會顯示「剩餘 26d 15h」這種字串,108px 會
1553
+ 折成兩行、把整列撐高,看起來像沒對齊。 */
1554
+ .ocoa-account-row {
1555
+ display: grid;
1556
+ grid-template-columns: minmax(0, 1fr) 132px 92px 68px;
1557
+ align-items: center;
1558
+ gap: var(--ocoa-s3);
1559
+ min-width: 0;
1560
+ }
1561
+ /* 面板變窄時,固定四欄會把「切換/移除」擠出邊界。名稱先讓位,
1562
+ 動作欄維持看得見——按鈕被裁掉比名稱被省略嚴重得多。 */
1563
+ @media (max-width: 720px) {
1564
+ .ocoa-account-row {
1565
+ grid-template-columns: minmax(0, 1fr) auto auto;
1566
+ gap: var(--ocoa-s2);
1567
+ }
1568
+ /* 窄版把到期時間收進名稱下方,四欄變三欄。 */
1569
+ .ocoa-account-row > .ocoa-badge { grid-column: 1; grid-row: 2; justify-self: start; }
1570
+ .ocoa-account-row > :nth-child(3) { grid-column: 2; }
1571
+ .ocoa-account-row > :nth-child(4) { grid-column: 3; }
1572
+ }
1573
+ /* Keep each control anchored to its grid track. The active marker uses
1574
+ the same switch track as the button, but is centered and never a button. */
1575
+ .ocoa-account-row > :nth-child(2) { justify-self: start; }
1576
+ .ocoa-account-row > :nth-child(3) { justify-self: center; }
1577
+ .ocoa-account-row > :nth-child(4) { justify-self: end; }
1578
+ .ocoa-account-name {
1579
+ display: flex; align-items: center; gap: var(--ocoa-s2); min-width: 0;
1580
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
1581
+ font-size: 13px;
1582
+ }
1583
+ /* 圓點與名稱之間必須有間距。原本只有 flex 而沒有 gap,兩個 span 會黏成
1584
+ 「●eva」——圓點看起來像字的一部分,而不是狀態指示。 */
1585
+ .ocoa-account-dot { flex: none; }
1586
+ /* 欄寬是固定的,內容就不該在格子裡折行去撐高整列。 */
1587
+ .ocoa-account-row .ocoa-badge,
1588
+ .ocoa-account-row .ocoa-chip,
1589
+ .ocoa-account-row .ocoa-btn { white-space: nowrap; }
1590
+ /* 「使用中」不是按鈕,就不該長得像按鈕。這一格講的是狀態,
1591
+ 所以用一顆小圓點加綠字,而不是跟旁邊按鈕搶戲的亮色藥丸框。 */
1592
+ .ocoa-account-active {
1593
+ display: inline-flex; align-items: center; gap: 6px;
1594
+ font-size: 12.5px; font-weight: 560; color: var(--ocoa-ok);
1595
+ }
1596
+ .ocoa-account-active .ocoa-dot {
1597
+ width: 7px; height: 7px; border-radius: 50%;
1598
+ background: currentColor; flex: none;
1599
+ }
1600
+ .ocoa-actions { display: flex; gap: 8px; flex-wrap: wrap; }
1601
+
1602
+ /* 授權狀態的三個事實:橫向一排,窄視窗自動換行。
1603
+ 不用外框包起來,只靠底色與內距分組——外面已經有卡片框了,
1604
+ 再包一層就變成盒中盒。 */
1605
+ .ocoa-facts {
1606
+ display: flex; flex-wrap: wrap; gap: 0; margin: 0;
1607
+ border-radius: 10px;
1608
+ background: var(--ocoa-sunk);
1609
+ overflow: hidden;
1610
+ }
1611
+ .ocoa-fact {
1612
+ flex: 1 1 150px; min-width: 0;
1613
+ padding: 8px 12px;
1614
+ border-left: 1px solid var(--ocoa-line2);
1615
+ }
1616
+ .ocoa-fact:first-child { border-left: 0; }
1617
+ .ocoa-fact-label {
1618
+ font-size: 11.5px; color: var(--ocoa-fg3);
1619
+ margin: 0 0 var(--ocoa-s1); line-height: 1.4;
1620
+ }
1621
+ .ocoa-fact-value {
1622
+ margin: 0; font-size: 13px; color: var(--ocoa-fg);
1623
+ overflow-wrap: anywhere; line-height: 1.5;
1624
+ }
1625
+
1626
+ /* 帳號清單:一條一條的列,列與列之間只有一條細線。 */
1627
+ .ocoa-account-list { display: flex; flex-direction: column; }
1628
+ .ocoa-account-list .ocoa-account-row + .ocoa-account-row {
1629
+ border-top: 1px solid var(--ocoa-line2);
1630
+ }
1631
+ .ocoa-account-row { padding: 6px 0; }
1632
+ .ocoa-account-dot {
1633
+ width: 7px; height: 7px; border-radius: 50%; flex: none;
1634
+ border: 1.5px solid var(--ocoa-line3); background: transparent;
1635
+ }
1636
+ .ocoa-account-dot.is-active { border-color: var(--ocoa-ok); background: var(--ocoa-ok); }
1637
+ .ocoa-account-label { overflow: hidden; text-overflow: ellipsis; }
1638
+
1639
+ .ocoa-btn {
1640
+ font: inherit; font-size: 12.5px; font-weight: 500;
1641
+ padding: 6px 14px; border-radius: 8px; cursor: pointer;
1642
+ border: 1px solid var(--ocoa-line3);
1643
+ background: var(--ocoa-surface); color: var(--ocoa-fg);
1644
+ transition: background .15s ease, border-color .15s ease;
1645
+ white-space: nowrap;
1646
+ /* 按鈕裡的字多半是兩三個中文字,垂直置中比基線對齊穩。 */
1647
+ line-height: 20px;
1648
+ }
1649
+ .ocoa-btn:hover:not(:disabled) { background: var(--ocoa-hover); }
1650
+ .ocoa-btn:disabled { opacity: .45; cursor: default; }
1651
+ /* 主按鈕用同一個強調色,不再另外呼叫宿主的 button-primary-fill:
1652
+ 那個變數在淺色主題下是紅色(state-error-primary),放在設定頁像警告。 */
1653
+ .ocoa-btn.primary {
1654
+ background: var(--ocoa-accent);
1655
+ color: var(--ocoa-on-accent);
1656
+ border-color: transparent;
1657
+ font-weight: 550;
1658
+ }
1659
+ .ocoa-btn.primary:hover:not(:disabled) {
1660
+ background: var(--ocoa-accent);
1661
+ filter: brightness(1.08);
1662
+ }
1663
+ .ocoa-btn.ghost { background: transparent; border-color: transparent; color: var(--ocoa-fg2); }
1664
+ .ocoa-btn.ghost:hover:not(:disabled) { background: var(--ocoa-hover); color: var(--ocoa-fg); }
1665
+ /* 卡片是 flex column,按鈕預設會被拉成整排寬——「顯示較少」於是一條
1666
+ 橫貫整張卡的長條,看起來像分隔線而不是按鈕。 */
1667
+ .ocoa-card > .ocoa-btn { align-self: flex-start; }
1668
+
1669
+ .ocoa-grid { display: grid; grid-template-columns: minmax(120px, max-content) 1fr; gap: var(--ocoa-s2) var(--ocoa-s3); font-size: 12.5px; }
1670
+ .ocoa-grid dd { margin: 0; color: var(--ocoa-fg); overflow-wrap: anywhere; }
1671
+ /* 診斷資訊收在 details 裡:展開後用緊一點的行距,避免一展開就吃掉半頁。 */
1672
+ .ocoa-grid-tight { gap: var(--ocoa-s1) var(--ocoa-s3); margin-top: var(--ocoa-s2); }
1673
+ .ocoa-details > summary {
1674
+ cursor: pointer; list-style: none;
1675
+ display: flex; align-items: center; gap: 6px;
1676
+ }
1677
+ .ocoa-details > summary::-webkit-details-marker { display: none; }
1678
+ /* 箭頭是額外佔位的字元,會把文字往右推、跟上面的次標題對不齊。
1679
+ 用負邊距把整排拉回來,左緣就與卡片內緣切齊。 */
1680
+ .ocoa-details > summary::before {
1681
+ content: '▸'; font-size: 9px; color: var(--ocoa-fg3);
1682
+ flex: none; margin-left: -12px; width: 8px;
1683
+ }
1684
+ .ocoa-details[open] > summary::before { content: '▾'; }
1685
+ .ocoa-mono { font-family: var(--ocoa-mono); font-size: 12px; }
1686
+
1687
+ /* 備援順位:三個並排,視窗太窄時自動換行。 */
1688
+ .ocoa-fallback-slots { display: flex; gap: var(--ocoa-s3); flex-wrap: wrap; }
1689
+ .ocoa-fallback-slot { display: flex; flex-direction: column; gap: var(--ocoa-s1); flex: 1 1 160px; min-width: 140px; }
1690
+ .ocoa-fallback-slot-label { font-size: 12px; color: var(--ocoa-fg3); }
1691
+ .ocoa-fallback-select { width: 100%; }
1692
+
1693
+ /* 提示框:不用虛線框,改成左側一道細色條。
1694
+ 底色刻意比 sunk 更淡:它是卡片裡的補充說明,不是另一個區塊。
1695
+ 太重的灰底會讓整張卡看起來像切成兩塊。 */
1696
+ .ocoa-note {
1697
+ font-size: 12.5px; line-height: 1.65; color: var(--ocoa-fg2);
1698
+ background: color-mix(in srgb, var(--ocoa-sunk) 55%, transparent);
1699
+ border-radius: 0 8px 8px 0;
1700
+ border-left: 2px solid var(--ocoa-line3);
1701
+ padding: var(--ocoa-s2) var(--ocoa-s3);
1702
+ }
1703
+ .ocoa-codebox {
1704
+ display: flex; align-items: center; gap: var(--ocoa-s3); flex-wrap: wrap;
1705
+ background: var(--ocoa-sunk); border-radius: 10px;
1706
+ padding: var(--ocoa-s3) var(--ocoa-s4);
1707
+ }
1708
+ .ocoa-usercode {
1709
+ font-family: var(--ocoa-mono); font-size: 18px; font-weight: 650;
1710
+ letter-spacing: .16em;
1711
+ }
1712
+ .ocoa-url { font-family: var(--ocoa-mono); font-size: 12px; overflow-wrap: anywhere; color: var(--ocoa-fg2); }
1713
+ .ocoa-link { color: var(--ocoa-accent); text-decoration: none; }
1714
+ .ocoa-link:hover { text-decoration: underline; }
1715
+
1716
+ .ocoa-toolbar { display: flex; align-items: center; gap: var(--ocoa-s3); flex-wrap: wrap; min-width: 0; }
1717
+ .ocoa-input {
1718
+ font: inherit; font-size: 12.5px; padding: 6px 12px; border-radius: 8px;
1719
+ border: 1px solid var(--ocoa-line3); background: var(--ocoa-surface); color: var(--ocoa-fg);
1720
+ min-width: 0; width: 240px; max-width: 100%;
1721
+ transition: border-color .13s ease;
1722
+ }
1723
+ .ocoa-input:focus-visible { outline: none; border-color: var(--ocoa-accent); }
1724
+ .ocoa-check { display: inline-flex; align-items: center; gap: 6px; font-size: 12.5px; color: var(--ocoa-fg2); }
1725
+
1726
+ /* 表格是給人掃的,不是給人欣賞留白的。
1727
+ 每一列必須同一高度:失敗原因若換行到狀態底下,那一列就變成兩倍高,
1728
+ 眼睛會在「正常/失敗」之間不停重新對焦。原因改跟狀態同一行,
1729
+ 放不下就省略,全文留在 title。 */
1730
+ .ocoa-table {
1731
+ width: 100%; border-collapse: collapse;
1732
+ font-size: 12px; table-layout: fixed;
1733
+ }
1734
+ .ocoa-table th {
1735
+ text-align: left; font-weight: 600; color: var(--ocoa-fg3);
1736
+ padding: 4px 6px;
1737
+ border-bottom: 1px solid var(--ocoa-line2);
1738
+ font-size: 11px; letter-spacing: .02em;
1739
+ }
1740
+ .ocoa-table td {
1741
+ padding: 3px 6px;
1742
+ border-bottom: 1px solid var(--ocoa-line);
1743
+ vertical-align: middle;
1744
+ }
1745
+ /* 嚴格鎖定單行行高,維持高密度閱讀,不換行折行 */
1746
+ .ocoa-model-row td { height: 26px; }
1747
+ .ocoa-table tr:last-child td { border-bottom: none; }
1748
+ .ocoa-table tbody tr:hover { background: var(--ocoa-hover); }
1749
+ .ocoa-table th:nth-child(1), .ocoa-table td:nth-child(1) { width: 30px; }
1750
+ .ocoa-table th:nth-child(3), .ocoa-table td:nth-child(3) { width: 140px; }
1751
+ .ocoa-table th:nth-child(4), .ocoa-table td:nth-child(4) { width: 68px; text-align: right; }
1752
+ .ocoa-table th:nth-child(5), .ocoa-table td:nth-child(5) { width: 58px; text-align: right; }
1753
+ .ocoa-context-btn {
1754
+ font: inherit; font-size: 11.5px; font-variant-numeric: tabular-nums;
1755
+ background: transparent; border: 1px solid transparent; border-radius: 4px;
1756
+ padding: 1px 5px; cursor: pointer; color: var(--ocoa-fg);
1757
+ display: inline-flex; align-items: center; gap: 3px; justify-content: flex-end;
1758
+ transition: background .12s, border-color .12s;
1759
+ }
1760
+ .ocoa-context-btn:hover {
1761
+ background: var(--ocoa-hover); border-color: var(--ocoa-line2); color: var(--ocoa-accent);
1762
+ }
1763
+ .ocoa-context-btn.is-custom {
1764
+ color: var(--ocoa-accent); font-weight: 550;
1765
+ }
1766
+ .ocoa-modal-backdrop {
1767
+ position: fixed; top: 0; left: 0; right: 0; bottom: 0;
1768
+ background: rgba(0, 0, 0, 0.45); backdrop-filter: blur(2px);
1769
+ display: flex; align-items: center; justify-content: center;
1770
+ z-index: 1000; padding: var(--ocoa-s4);
1771
+ }
1772
+ .ocoa-modal-dialog {
1773
+ background: var(--ocoa-surface); border: 1px solid var(--ocoa-line3);
1774
+ border-radius: 12px; box-shadow: 0 12px 32px rgba(0, 0, 0, 0.2);
1775
+ width: 100%; max-width: 440px; display: flex; flex-direction: column;
1776
+ gap: var(--ocoa-s3); padding: var(--ocoa-s4); color: var(--ocoa-fg);
1777
+ }
1778
+ .ocoa-modal-header {
1779
+ display: flex; align-items: flex-start; justify-content: space-between; gap: var(--ocoa-s2);
1780
+ }
1781
+ .ocoa-modal-title { font-size: 15px; font-weight: 600; line-height: 1.3; margin: 0; color: var(--ocoa-fg); }
1782
+ .ocoa-modal-sub { font-size: 12px; color: var(--ocoa-fg3); margin-top: 2px; font-family: var(--ocoa-mono); word-break: break-all; }
1783
+ .ocoa-modal-close {
1784
+ background: transparent; border: none; cursor: pointer;
1785
+ color: var(--ocoa-fg3); font-size: 16px; line-height: 1; padding: 4px; border-radius: 6px;
1786
+ }
1787
+ .ocoa-modal-close:hover { background: var(--ocoa-hover); color: var(--ocoa-fg); }
1788
+ .ocoa-modal-body { display: flex; flex-direction: column; gap: var(--ocoa-s3); }
1789
+ .ocoa-modal-info {
1790
+ font-size: 12px; line-height: 1.5; color: var(--ocoa-fg2);
1791
+ background: var(--ocoa-sunk); border-radius: 8px; padding: 10px 12px;
1792
+ }
1793
+ .ocoa-modal-footer {
1794
+ display: flex; align-items: center; justify-content: space-between;
1795
+ gap: var(--ocoa-s2); margin-top: var(--ocoa-s2); padding-top: var(--ocoa-s2);
1796
+ border-top: 1px solid var(--ocoa-line2);
1797
+ }
1798
+ /* 勾選框:用 accent-color 直接吃掉宿主主題 */
1799
+ .ocoa-pick { padding-right: 0 !important; padding-left: 4px !important; }
1800
+ .ocoa-pick-box {
1801
+ appearance: auto; width: 14px; height: 14px; margin: 0;
1802
+ accent-color: var(--ocoa-accent); cursor: pointer;
1803
+ vertical-align: middle;
1804
+ }
1805
+ .ocoa-pick-box:disabled { cursor: not-allowed; opacity: .35; }
1806
+ .ocoa-pick-box:focus-visible { outline: 2px solid var(--ocoa-accent); outline-offset: 2px; }
1807
+ .ocoa-picker-mode {
1808
+ display: flex; align-items: baseline; gap: var(--ocoa-s2);
1809
+ font-size: 12px; color: var(--ocoa-fg3);
1810
+ }
1811
+ .ocoa-picker-mode-text { min-width: 0; }
1812
+ .ocoa-picker-mode .ocoa-badge { flex: none; }
1813
+ .ocoa-status {
1814
+ display: flex; flex-direction: row; align-items: center;
1815
+ gap: 6px; min-width: 0; white-space: nowrap; overflow: hidden;
1816
+ }
1817
+ .ocoa-status-reason {
1818
+ font-size: 11px; line-height: 1.2; color: var(--ocoa-fg3);
1819
+ min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
1820
+ }
1821
+ .ocoa-status .ocoa-badge { flex: none; }
1822
+ .ocoa-model { font-family: var(--ocoa-mono); font-size: 12px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1823
+ .ocoa-model-id {
1824
+ display: block; font-family: var(--ocoa-mono); font-size: 12px; line-height: 1.3;
1825
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
1826
+ }
1827
+ .ocoa-model-row.is-open { background: var(--ocoa-sunk); }
1828
+ /* 展開列從「模型」欄的起點開始,不要在勾選欄下方也鋪一條灰底:
1829
+ 灰底跨過勾選欄會讓那一欄看起來像被合併掉了。 */
1830
+ .ocoa-model-expand td { padding: 0 8px var(--ocoa-s3) 34px; border-bottom: 1px solid var(--ocoa-line2); }
1831
+ .ocoa-expand-body {
1832
+ display: grid; gap: var(--ocoa-s2);
1833
+ padding: var(--ocoa-s3); border-radius: 9px;
1834
+ background: var(--ocoa-sunk2);
1835
+ }
1836
+ .ocoa-expand-reason { font-size: 12.5px; font-weight: 600; color: var(--ocoa-off); }
1837
+ .ocoa-num { font-variant-numeric: tabular-nums; color: var(--ocoa-fg2); }
1838
+ .ocoa-badge { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 500; }
1839
+ .ocoa-badge.ok { color: var(--ocoa-ok); }
1840
+ .ocoa-badge.off { color: var(--ocoa-off); }
1841
+ .ocoa-badge.dim { color: var(--ocoa-fg3); font-weight: 400; }
1842
+ /* 限流不是失敗:模型有效,只是額度或速率暫時排不進去。 */
1843
+ .ocoa-badge.warn { color: var(--ocoa-warn); }
1844
+ /* 強調色的徽章只給「這是你設定的模式」用,不是錯誤也不是警告。 */
1845
+ .ocoa-badge.accent { color: var(--ocoa-accent); }
1846
+ .ocoa-diagnostic-meta { margin-top: var(--ocoa-s1); color: var(--ocoa-fg3); font-size: 11.5px; line-height: 1.5; }
1847
+ .ocoa-context-editor { margin-top: var(--ocoa-s2); color: var(--ocoa-fg2); }
1848
+ .ocoa-context-editor summary { cursor: pointer; color: var(--ocoa-accent); font-size: 12px; }
1849
+ .ocoa-context-panel {
1850
+ display: grid; gap: var(--ocoa-s2); margin-top: var(--ocoa-s2); padding: var(--ocoa-s3);
1851
+ border: 1px solid var(--ocoa-line2); border-radius: 9px; background: var(--ocoa-surface);
1852
+ }
1853
+ .ocoa-context-default, .ocoa-context-hint { margin: 0; font-size: 12px; line-height: 1.6; }
1854
+ .ocoa-context-hint { color: var(--ocoa-fg3); }
1855
+ .ocoa-context-field { display: grid; gap: var(--ocoa-s1); font-size: 12px; color: var(--ocoa-fg2); }
1856
+ .ocoa-context-number { width: min(100%, 260px); }
1857
+
1858
+ /* 上游原始回應。刻意用等寬字、縮小一級:這是要拿來複製或搜尋的
1859
+ 原始資料,不是給人閱讀的句子。太長時省略,hover 顯示全文。 */
1860
+ .ocoa-raw {
1861
+ margin-top: 3px;
1862
+ font-size: 11px;
1863
+ line-height: 1.45;
1864
+ color: var(--ocoa-fg3);
1865
+ opacity: 0.85;
1866
+ }
1867
+ .ocoa-raw-label {
1868
+ font-weight: 600;
1869
+ margin-right: 2px;
1870
+ }
1871
+ .ocoa-raw code {
1872
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1873
+ font-size: 10.5px;
1874
+ background: rgba(127, 127, 127, 0.10);
1875
+ border-radius: 3px;
1876
+ padding: 0 3px;
1877
+ word-break: break-all;
1878
+ /* 最多兩行就截斷,避免某個模型回了整頁 HTML 把表格撐爛。 */
1879
+ display: -webkit-box;
1880
+ -webkit-line-clamp: 2;
1881
+ -webkit-box-orient: vertical;
1882
+ overflow: hidden;
1883
+ }
1884
+
1885
+ .ocoa-spin { display: inline-block; animation: ocoa-spin 1s linear infinite; }
1886
+ @keyframes ocoa-spin { to { transform: rotate(360deg); } }
1887
+ .ocoa-loading { color: var(--ocoa-fg3); font-size: 12.5px; padding: 18px 0; }
1888
+ @media (prefers-reduced-motion: reduce) {
1889
+ .ocoa-spin { animation: none; }
1890
+ .ocoa-btn { transition: none; }
1891
+ }
1892
+
1893
+ /* 語言切換鍵:標題列最右側。顏色一律走主題變數,淺色/深色都會跟著換。 */
1894
+ .ocoa-lang {
1895
+ margin-left: auto; /* 推到標題列最右邊 */
1896
+ display: inline-flex;
1897
+ align-items: center;
1898
+ gap: 6px;
1899
+ font-size: 12px;
1900
+ color: var(--dsw-alias-label-tertiary);
1901
+ }
1902
+ .ocoa-lang-label { white-space: nowrap; }
1903
+ .ocoa-lang-select {
1904
+ appearance: auto;
1905
+ font: inherit;
1906
+ font-size: 12px;
1907
+ color: var(--dsw-alias-label-primary);
1908
+ background: var(--dsw-alias-bg-layer-2);
1909
+ border: 1px solid var(--dsw-alias-border-l1);
1910
+ border-radius: 6px;
1911
+ padding: 3px 6px;
1912
+ cursor: pointer;
1913
+ max-width: 220px;
1914
+ }
1915
+ .ocoa-lang-select:hover { background: var(--ocoa-hover); }
1916
+ .ocoa-lang-select:focus-visible {
1917
+ outline: 2px solid var(--ocoa-accent);
1918
+ outline-offset: 1px;
1919
+ }
1920
+ .ocoa-go-list {
1921
+ display: flex;
1922
+ flex-direction: column;
1923
+ gap: 6px;
1924
+ margin-top: 8px;
1925
+ }
1926
+ .ocoa-go-row {
1927
+ padding: 8px 10px;
1928
+ border-radius: 7px;
1929
+ border: 1px solid var(--ocoa-border);
1930
+ background: var(--ocoa-bg-sub);
1931
+ display: flex;
1932
+ flex-direction: column;
1933
+ gap: 4px;
1934
+ }
1935
+ .ocoa-go-head {
1936
+ display: flex;
1937
+ align-items: center;
1938
+ justify-content: space-between;
1939
+ gap: 8px;
1940
+ flex-wrap: wrap;
1941
+ }
1942
+ .ocoa-go-id {
1943
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1944
+ font-size: 11.5px;
1945
+ color: var(--ocoa-fg2);
1946
+ }
1947
+ .ocoa-go-meta {
1948
+ display: flex;
1949
+ flex-wrap: wrap;
1950
+ gap: 6px;
1951
+ font-size: 11px;
1952
+ color: var(--ocoa-fg3);
1953
+ }
1954
+ .ocoa-go-pill {
1955
+ padding: 1px 6px;
1956
+ border-radius: 4px;
1957
+ border: 1px solid var(--ocoa-border);
1958
+ background: var(--dsw-alias-bg-layer-2);
1959
+ color: var(--ocoa-fg2);
1960
+ }
1961
+ .ocoa-go-cred-box {
1962
+ display: grid;
1963
+ gap: 8px;
1964
+ margin-top: 8px;
1965
+ padding: 10px 12px;
1966
+ border-radius: 8px;
1967
+ border: 1px solid var(--ocoa-line2);
1968
+ background: var(--ocoa-sunk);
1969
+ }
1970
+ .ocoa-go-cred-foot {
1971
+ display: flex;
1972
+ align-items: center;
1973
+ justify-content: space-between;
1974
+ gap: 8px;
1975
+ flex-wrap: wrap;
1976
+ padding-top: 8px;
1977
+ border-top: 1px solid var(--ocoa-line2);
1978
+ }
1979
+ .ocoa-go-cred-notes {
1980
+ display: grid;
1981
+ gap: 3px;
1982
+ font-size: 11px;
1983
+ line-height: 1.45;
1984
+ color: var(--ocoa-fg2);
1985
+ }
1986
+ .ocoa-go-cred-head {
1987
+ display: flex;
1988
+ align-items: center;
1989
+ justify-content: space-between;
1990
+ gap: 8px;
1991
+ flex-wrap: wrap;
1992
+ font-size: 12px;
1993
+ color: var(--ocoa-fg2);
1994
+ }
1995
+ .ocoa-go-cred-head .ocoa-chip {
1996
+ flex: none;
1997
+ white-space: nowrap;
1998
+ }
1999
+ .ocoa-go-cred-row {
2000
+ display: flex;
2001
+ gap: 8px;
2002
+ align-items: center;
2003
+ flex-wrap: wrap;
2004
+ }
2005
+ .ocoa-go-cred-input {
2006
+ flex: 1 1 220px;
2007
+ min-width: 180px;
2008
+ }
2009
+ .ocoa-go-cred-collapsed {
2010
+ display: flex;
2011
+ align-items: center;
2012
+ justify-content: space-between;
2013
+ gap: 8px;
2014
+ flex-wrap: wrap;
2015
+ }
2016
+ .ocoa-go-usage-grid {
2017
+ display: grid;
2018
+ grid-template-columns: repeat(3, minmax(0, 1fr));
2019
+ gap: 8px;
2020
+ margin-top: 8px;
2021
+ }
2022
+ .ocoa-go-usage-card {
2023
+ padding: 8px 10px;
2024
+ border-radius: 6px;
2025
+ border: 1px solid var(--ocoa-line2);
2026
+ background: var(--ocoa-surface);
2027
+ display: grid;
2028
+ gap: 5px;
2029
+ min-width: 0;
2030
+ }
2031
+ .ocoa-go-usage-head {
2032
+ display: flex;
2033
+ align-items: baseline;
2034
+ justify-content: space-between;
2035
+ gap: 6px;
2036
+ font-size: 11px;
2037
+ color: var(--ocoa-fg2);
2038
+ }
2039
+ .ocoa-go-usage-pct {
2040
+ font-weight: 700;
2041
+ font-variant-numeric: tabular-nums;
2042
+ }
2043
+ .ocoa-go-usage-pct.is-ok { color: var(--ocoa-ok); }
2044
+ .ocoa-go-usage-pct.is-warn { color: var(--ocoa-warn); }
2045
+ .ocoa-go-usage-pct.is-bad { color: var(--ocoa-off); }
2046
+ .ocoa-go-usage-bar {
2047
+ height: 5px;
2048
+ border-radius: 999px;
2049
+ background: var(--ocoa-sunk);
2050
+ overflow: hidden;
2051
+ }
2052
+ .ocoa-go-usage-fill {
2053
+ height: 100%;
2054
+ border-radius: 999px;
2055
+ }
2056
+ .ocoa-go-usage-fill.is-ok { background: var(--ocoa-ok); }
2057
+ .ocoa-go-usage-fill.is-warn { background: var(--ocoa-warn); }
2058
+ .ocoa-go-usage-fill.is-bad { background: var(--ocoa-off); }
2059
+ .ocoa-go-usage-reset {
2060
+ font-size: 10px;
2061
+ color: var(--ocoa-fg3);
2062
+ white-space: nowrap;
2063
+ overflow: hidden;
2064
+ text-overflow: ellipsis;
2065
+ }
2066
+ .ocoa-go-catalog {
2067
+ display: flex;
2068
+ flex-direction: column;
2069
+ gap: 10px;
2070
+ margin-top: 10px;
2071
+ min-width: 0;
2072
+ }
2073
+ .ocoa-go-table-scroll {
2074
+ width: 100%;
2075
+ max-width: 100%;
2076
+ overflow-x: auto;
2077
+ }
2078
+ .ocoa-go-table {
2079
+ width: 100%;
2080
+ }
2081
+ .ocoa-go-table th:nth-child(1), .ocoa-go-table td:nth-child(1) { width: 42px; text-align: center; }
2082
+ .ocoa-go-table th:nth-child(2), .ocoa-go-table td:nth-child(2) { width: auto; min-width: 0; }
2083
+ .ocoa-go-table th:nth-child(3), .ocoa-go-table td:nth-child(3) { width: 78px; text-align: right; }
2084
+ .ocoa-go-table th:nth-child(4), .ocoa-go-table td:nth-child(4) { width: 78px; text-align: right; }
2085
+ .ocoa-go-table .ocoa-model-expand td {
2086
+ padding: 0 8px var(--ocoa-s3) 8px;
2087
+ text-align: left;
2088
+ width: auto;
2089
+ }
2090
+ .ocoa-go-table .ocoa-go-model-btn .ocoa-model-id,
2091
+ .ocoa-go-table .ocoa-go-model-btn .ocoa-model-toggle {
2092
+ flex: 1 1 auto;
2093
+ min-width: 0;
2094
+ display: block;
2095
+ overflow: hidden;
2096
+ text-overflow: ellipsis;
2097
+ white-space: nowrap;
2098
+ }
2099
+ .ocoa-go-model-btn {
2100
+ appearance: none;
2101
+ background: transparent;
2102
+ border: 0;
2103
+ padding: 0;
2104
+ margin: 0;
2105
+ width: 100%;
2106
+ text-align: left;
2107
+ font: inherit;
2108
+ color: inherit;
2109
+ cursor: pointer;
2110
+ display: flex;
2111
+ align-items: center;
2112
+ gap: 6px;
2113
+ min-width: 0;
2114
+ }
2115
+ .ocoa-go-model-btn:hover { color: var(--ocoa-accent); }
2116
+ .ocoa-go-model-btn:focus-visible { outline: 2px solid var(--ocoa-accent); outline-offset: 2px; border-radius: 4px; }
2117
+ .ocoa-go-caret {
2118
+ flex: none;
2119
+ font-size: 10px;
2120
+ color: var(--ocoa-fg3);
2121
+ width: 10px;
2122
+ }
2123
+ .ocoa-go-caps-cell {
2124
+ font-size: 11.5px;
2125
+ color: var(--ocoa-fg2);
2126
+ overflow: hidden;
2127
+ text-overflow: ellipsis;
2128
+ white-space: nowrap;
2129
+ }
2130
+ `;
2131
+ document.head.appendChild(style);
2132
+ }
2133
+
2134
+ /* --------------------------------------------------------------- 元件 */
2135
+
2136
+ const MODELS_COLLAPSED = 8;
2137
+
2138
+ function Chip({ tone, text }) {
2139
+ return h(
2140
+ 'span',
2141
+ { className: `ocoa-chip ${tone}` },
2142
+ h('span', { className: 'ocoa-chip-dot' }),
2143
+ text
2144
+ );
2145
+ }
2146
+
2147
+ function Row({ label, children }) {
2148
+ return [h('dt', { key: `${label}-k` }, label), h('dd', { key: `${label}-v` }, children)];
2149
+ }
2150
+
2151
+ /**
2152
+ * 橫向事實條的一格:上面是小字標籤,下面是值。
2153
+ *
2154
+ * 為什麼不繼續用 `Row`(dt/dd 直排):憑證來源、到期、可否自動續這三項
2155
+ * 是一組短值,直排會把一張卡撐成兩倍高卻沒有更好讀。橫排讓它們在同一條
2156
+ * 視線上,掃一眼就看完。
2157
+ */
2158
+ function Fact({ label, children }) {
2159
+ return h(
2160
+ 'div',
2161
+ { className: 'ocoa-fact', key: `${label}-fact` },
2162
+ h('dt', { className: 'ocoa-fact-label' }, label),
2163
+ h('dd', { className: 'ocoa-fact-value' }, children)
2164
+ );
2165
+ }
2166
+
2167
+ /**
2168
+ * 語言切換鍵。
2169
+ *
2170
+ * 只改本分頁的語言,不會呼叫宿主的 `setLocale()`——那會把選擇寫進 DSH 的
2171
+ * 使用者設定,連帶換掉整個介面的語言。這裡的選擇存在外掛自己的鍵上。
2172
+ *
2173
+ * 選 `auto`(跟隨系統)時,標題會顯示實際解析出來的語言,讓使用者看得出
2174
+ * 「跟隨系統」目前代表什麼,而不是只有一個抽象的選項名稱。
2175
+ */
2176
+ function LanguageSwitcher({ choice, localeId, t, onChange }) {
2177
+ const autoLabel =
2178
+ choice === 'auto' ? `${t('languageAuto')} · ${t(`languageOf_${localeId}`)}` : t('languageAuto');
2179
+
2180
+ return h(
2181
+ 'label',
2182
+ { className: 'ocoa-lang' },
2183
+ // 視覺上只留 select,但 label 對讀屏與點擊範圍都有用。
2184
+ h('span', { className: 'ocoa-lang-label' }, t('languageLabel')),
2185
+ h(
2186
+ 'select',
2187
+ {
2188
+ className: 'ocoa-lang-select',
2189
+ value: choice,
2190
+ onChange: (event) => onChange(event.target.value),
2191
+ 'aria-label': t('languageLabel')
2192
+ },
2193
+ ...LANGUAGE_OPTIONS.map((option) =>
2194
+ h(
2195
+ 'option',
2196
+ { key: option.id, value: option.id },
2197
+ option.id === 'auto' ? autoLabel : t(option.label)
2198
+ )
2199
+ )
2200
+ )
2201
+ );
2202
+ }
2203
+
2204
+ function loginFailureText(t, failure) {
2205
+ if (!failure || typeof failure.code !== 'string') return '';
2206
+ if (failure.code === 'timeout') return t('loginFailedTimeout');
2207
+ if (failure.code === 'denied') return t('loginFailedDenied');
2208
+ if (failure.code === 'expired') return t('loginFailedExpired');
2209
+ if (failure.code === 'network') return t('loginFailedNetwork');
2210
+ const detail = typeof failure.message === 'string' && failure.message ? failure.message : failure.code;
2211
+ return t('loginFailed', { message: detail });
2212
+ }
2213
+
2214
+ function SettingsPage({ ctx, t: hostT }) {
2215
+ /* ------------------------------------------------------ 語言狀態
2216
+
2217
+ 這一頁的語言完全由自己決定(跟隨系統/英文/簡中/繁中),刻意不採用
2218
+ 宿主的 `t`:那個 translator 綁在 DSH 全域語言上,用它就表示切換語言會
2219
+ 連帶影響整個 DSH。`hostT` 只保留給「本頁還沒有系統語言資訊時」的
2220
+ 暫時過渡,一旦拿到 status 就完全改用本地解析結果。 */
2221
+
2222
+ // 使用者的明確選擇:'auto' 或某個語言 id。null 代表從未選過。
2223
+ const [languageChoice, setLanguageChoice] = React.useState(() => readStoredLanguage());
2224
+
2225
+ const [status, setStatus] = React.useState(null);
2226
+
2227
+ // 主機端讀到的系統語言。拿到 status 之後才有值。
2228
+ const systemLocale = status?.systemLocale ?? null;
2229
+
2230
+ const localeId = React.useMemo(
2231
+ () => resolveLocale(languageChoice, systemLocale),
2232
+ [languageChoice, systemLocale]
2233
+ );
2234
+
2235
+ const t = React.useMemo(() => translator(localeId), [localeId]);
2236
+ const [busy, setBusy] = React.useState('');
2237
+ const [message, setMessage] = React.useState(null);
2238
+ const [copied, setCopied] = React.useState('');
2239
+ // 表格預設整份展開。
2240
+ //
2241
+ // 原本預設收成 8 列,理由是「46 列一進來就全開很嚇人」。實際用起來剛好
2242
+ // 相反:使用者的目的就是掃一遍有哪些能用、要把哪幾個勾起來,收合只是
2243
+ // 逼他先按一次「顯示其餘 38 個」。勾選還需要跨列比較,看不到全部就沒法比。
2244
+ const [showAll, setShowAll] = React.useState(true);
2245
+ // 預設停在「模型」:那是最常進來看的東西。
2246
+ const [tabState, setTabState] = React.useState('models');
2247
+ // 優先讀取上次使用者記下的分類篩選;未儲存過時為 null,
2248
+ // 後續依「有沒有探測結果」自動決定:有結果看可用的,沒結果看全部。
2249
+ const [modelFilter, setModelFilter] = React.useState(() => readStoredFilter());
2250
+ // 一次只展開一列:展開的內容是探測細節與上下文設定,同一時間看兩份只會
2251
+ // 讓表格變成兩倍長,而使用者通常只是在找某一列壞在哪。
2252
+ const [expandedModel, setExpandedModel] = React.useState(null);
2253
+ const [filter, setFilter] = React.useState('');
2254
+ const [loaded, setLoaded] = React.useState(false);
2255
+
2256
+ // 備援設定:主機端是真相,這裡只是它的草稿。
2257
+ //
2258
+ // `fallbackDraft` 是 null 代表「還沒動過」,畫面直接顯示主機端的值;
2259
+ // 使用者一動(勾選或改順位)才變成草稿,等按下儲存才送回主機。
2260
+ // 不這樣做的話,畫面上的值會跟著每 15 秒一次的輪詢被覆蓋掉。
2261
+ const [fallbackDraft, setFallbackDraft] = React.useState(null);
2262
+
2263
+ // 不使用 window.prompt:DSH 的嵌入式設定頁可能不顯示原生對話框,按鈕看起來
2264
+ // 就會像沒有反應。改成頁面內的輸入列,讓 label 可填可留白,且可明確取消。
2265
+ const [addAccountOpen, setAddAccountOpen] = React.useState(false);
2266
+ const [accountLabel, setAccountLabel] = React.useState('');
2267
+ const [contextDrafts, setContextDrafts] = React.useState({});
2268
+ const [contextModalModel, setContextModalModel] = React.useState(null);
2269
+ const [removeAccountModal, setRemoveAccountModal] = React.useState(null);
2270
+ const [contextInputVal, setContextInputVal] = React.useState('');
2271
+ const [goKeyInput, setGoKeyInput] = React.useState('');
2272
+ const [goKeyEditing, setGoKeyEditing] = React.useState(false);
2273
+ const [goFilter, setGoFilter] = React.useState('all');
2274
+ const [goSearch, setGoSearch] = React.useState('');
2275
+ const [goShowAll, setGoShowAll] = React.useState(false);
2276
+ const [goExpandedModel, setGoExpandedModel] = React.useState(null);
2277
+
2278
+ const numberLabel = (value) => Number.isFinite(Number(value))
2279
+ ? Number(value).toLocaleString(localeId)
2280
+ : '–';
2281
+
2282
+ const openContextModal = (model) => {
2283
+ setContextModalModel(model);
2284
+ const current = model.contextOverride ?? model.catalogContextWindow ?? model.contextWindow ?? 200000;
2285
+ setContextInputVal(String(current));
2286
+ };
2287
+ const closeContextModal = () => {
2288
+ setContextModalModel(null);
2289
+ };
2290
+
2291
+ // translator 放進 ref。宿主透過 inject() 給的 t 不保證身分穩定(可能每次
2292
+ // 渲染都重建一次),若直接當成 useCallback 的相依,load 就會跟著每次渲染
2293
+ // 換新,下面那個輪詢 effect 也就在每次渲染重跑一次——變成沒完沒了的請求風暴。
2294
+ const tRef = React.useRef(t);
2295
+ tRef.current = t;
2296
+
2297
+ const load = React.useCallback(async () => {
2298
+ try {
2299
+ setStatus(await callApi('status'));
2300
+ setLoaded(true);
2301
+ } catch (error) {
2302
+ setLoaded(true);
2303
+ setMessage({ kind: 'error', text: tRef.current('errorGeneric', { message: error.message }) });
2304
+ }
2305
+ }, []);
2306
+
2307
+ const pending = status?.pendingLogin ?? null;
2308
+
2309
+ // 有待核准的登入時加快輪詢,讓頁面自己反映出結果,不必使用者按任何東西。
2310
+ // 相依只有 pending,所以平常不會反覆重掛。
2311
+ React.useEffect(() => {
2312
+ let alive = true;
2313
+ const tick = () => {
2314
+ if (alive) load();
2315
+ };
2316
+ tick();
2317
+ const timer = window.setInterval(tick, pending ? 2000 : 15000);
2318
+ return () => {
2319
+ alive = false;
2320
+ window.clearInterval(timer);
2321
+ };
2322
+ }, [load, pending]);
2323
+
2324
+ // 「已複製」的提示會自己消失;計時器隨頁面結束而亡。
2325
+ React.useEffect(() => {
2326
+ if (!copied) return undefined;
2327
+ const timer = window.setTimeout(() => setCopied(''), 1400);
2328
+ return () => window.clearTimeout(timer);
2329
+ }, [copied]);
2330
+
2331
+ const copy = (text, id) => {
2332
+ const write = navigator.clipboard?.writeText?.(String(text));
2333
+ Promise.resolve(write).then(
2334
+ () => setCopied(id),
2335
+ () => {}
2336
+ );
2337
+ };
2338
+
2339
+ const act = async (name, pathname, payload) => {
2340
+ setBusy(name);
2341
+ setMessage(null);
2342
+ try {
2343
+ const value = await callApi(pathname, 'POST', payload);
2344
+ // 登入在等待期間被登出取消:伺服器不會回傳可開啟的驗證網址(見
2345
+ // web-api.js)。這裡明確說明「已取消」,否則畫面會停在忙碌狀態。
2346
+ if ((pathname === 'login' || pathname === 'accounts') && value?.cancelled) {
2347
+ setMessage({ kind: 'info', text: t('loginCancelled') });
2348
+ await load();
2349
+ return;
2350
+ }
2351
+ if (pathname === 'login/cancel') {
2352
+ setMessage({ kind: 'info', text: t('loginCancelled') });
2353
+ await load();
2354
+ return;
2355
+ }
2356
+ if ((pathname === 'login' || pathname === 'accounts') && value?.verificationUrl) {
2357
+ setMessage({ kind: 'info', text: t('waiting') });
2358
+ window.open(value.verificationUrl, '_blank', 'noopener');
2359
+ }
2360
+ if (pathname === 'logout') {
2361
+ setMessage({ kind: 'info', text: value?.note ?? '' });
2362
+ }
2363
+ if (pathname === 'accounts/import-local') {
2364
+ setMessage({
2365
+ kind: 'info',
2366
+ text: value?.alreadyPresent ? t('importLocalAlready') : t('importLocalDone')
2367
+ });
2368
+ }
2369
+ if (pathname === 'go/credential') {
2370
+ setMessage({ kind: 'info', text: t('goKeySavedMsg') });
2371
+ }
2372
+ if (pathname === 'go/credential/clear') {
2373
+ setMessage({ kind: 'info', text: t('goKeyClearedMsg') });
2374
+ }
2375
+ await load();
2376
+ } catch (error) {
2377
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2378
+ } finally {
2379
+ setBusy('');
2380
+ }
2381
+ };
2382
+
2383
+ const beginAddAccount = () => {
2384
+ const label = accountLabel.trim();
2385
+ setAddAccountOpen(false);
2386
+ setAccountLabel('');
2387
+ void act('login', 'accounts', { label });
2388
+ };
2389
+
2390
+ const cancelAddAccount = () => {
2391
+ setAddAccountOpen(false);
2392
+ setAccountLabel('');
2393
+ };
2394
+
2395
+ if (!status) {
2396
+ // 載入中的畫面也要有語言切換鍵。
2397
+ //
2398
+ // 這不只是為了測試好看:使用者第一次開啟這個分頁時,status 還沒回來
2399
+ // (或是讀取失敗),若整個畫面只有一行「正在整理…」,他會找不到切換鍵,
2400
+ // 也就沒辦法在使用者想要語言的那一刻換語言——而那正是他最需要它的時候。
2401
+ return h(
2402
+ 'div',
2403
+ { className: 'ocoa-page' },
2404
+ h(
2405
+ 'div',
2406
+ { className: 'ocoa-head' },
2407
+ h(
2408
+ 'div',
2409
+ { className: 'ocoa-title-row' },
2410
+ h('span', { className: 'ocoa-title' }, t('title')),
2411
+ h(LanguageSwitcher, {
2412
+ choice: languageChoice ?? 'auto',
2413
+ localeId,
2414
+ t,
2415
+ onChange: (value) => {
2416
+ setLanguageChoice(value);
2417
+ writeStoredLanguage(value);
2418
+ }
2419
+ })
2420
+ )
2421
+ ),
2422
+ h(
2423
+ 'p',
2424
+ { className: 'ocoa-loading' },
2425
+ loaded ? t('loadFailed') : t('refreshing')
2426
+ )
2427
+ );
2428
+ }
2429
+
2430
+ const accounts = status.accounts ?? [];
2431
+ const chip = healthChip(status.health);
2432
+ const cred = status.credential ?? {};
2433
+ const models = status.models?.models ?? [];
2434
+ const summary = status.models ?? {};
2435
+ // 勾選功能現狀。舊版主機(或沒接 store 的情境)不會有這個欄位,
2436
+ // 那就整欄不畫,而不是畫一個永遠 disabled 的勾選欄。
2437
+ const picker = status.picker ?? null;
2438
+ const cfg = status.config ?? {};
2439
+
2440
+ const sourceLabel =
2441
+ // `accounts` 是多帳號模式下的憑證來源(token-manager 從帳號清單取用)。
2442
+ // 少了這一個分支,切換過帳號之後這一格就會顯示「未知來源」——明明
2443
+ // 憑證是有效的,卻讓使用者以為來源不明。
2444
+ cred.source === 'accounts'
2445
+ ? t('srcAccounts')
2446
+ : cred.source === 'local-db'
2447
+ ? t('srcLocalDb')
2448
+ : cred.source === 'dsh-token-file'
2449
+ ? t('srcTokenFile')
2450
+ : cred.source === 'local-auth-json'
2451
+ ? t('srcAuthJson')
2452
+ : t('srcUnknown');
2453
+
2454
+ // 到期時間:優先顯示「還剩多久」,因為那才是使用者真正想知道的事;
2455
+ // 絕對時間放在括號裡補充。
2456
+ // 時間單位跟著介面語言走:中文頁不該出現「26d 15h」。
2457
+ const durUnits = {
2458
+ d: t('unitDay'),
2459
+ h: t('unitHour'),
2460
+ m: t('unitMinute'),
2461
+ lessThanMinute: t('unitLessThanMinute')
2462
+ };
2463
+ const dur = (ms) => shortDuration(ms, durUnits);
2464
+
2465
+ let expiryText;
2466
+ if (!cred.present) expiryText = '–';
2467
+ else if (cred.expired) expiryText = t('expiresPast');
2468
+ else if (cred.expiresInSeconds === null || cred.expiresInSeconds === undefined) {
2469
+ expiryText = t('expiresNoExpiry');
2470
+ } else {
2471
+ const when = formatWhen(cred.expiresAt * 1000, localeId);
2472
+ expiryText = when
2473
+ ? `${t('expiresIn', { time: dur(cred.expiresInSeconds * 1000) })}(${t('expiresAt', { when })})`
2474
+ : t('expiresIn', { time: dur(cred.expiresInSeconds * 1000) });
2475
+ }
2476
+
2477
+ const probedWhen = summary.probedAt ? formatWhen(summary.probedAt, localeId) : null;
2478
+
2479
+ const intervalLabel = (ms) => {
2480
+ if (!ms || !Number.isFinite(ms)) return '–';
2481
+ const hours = ms / 3600000;
2482
+ if (hours >= 1) return t('intervalHours', { h: Math.round(hours * 10) / 10 });
2483
+ return t('intervalMinutes', { m: Math.round(ms / 60000) });
2484
+ };
2485
+
2486
+ const byteLabel = (n) =>
2487
+ typeof n === 'number' && Number.isFinite(n) ? `${n.toLocaleString()} B` : '–';
2488
+
2489
+ // 使用者還沒選過分類時顯示全部。
2490
+ //
2491
+ // 刻意不預設「可用」:`available` 只在探測過之後才有意義,憑證剛接好、
2492
+ // 還沒探測時每一筆都是 undefined,預設可用會讓整張表變成空的——那看起來
2493
+ // 像外掛壞了,而不是「還沒探測」。
2494
+ //
2495
+ // 但「記住上次的篩選」會把同一個陷阱變成常態:上次停在「可用」,這次
2496
+ // 開機沒有任何探測資料,於是 46 個候選、0 筆可用、整張表空白。使用者
2497
+ // 看到的是「我的探測紀錄不見了」,實際上只是被一個空集合篩掉。
2498
+ // 所以還原篩選時要驗證它現在有意義:沒有任何一列可用就退回「全部」,
2499
+ // 讓畫面至少說得出「尚未探測」而不是一片空白。
2500
+ const probedRows = models.filter((m) => m.probed === true);
2501
+ const usableRows = probedRows.filter((m) => (m.valid ?? m.available) === true);
2502
+ const storedFilter = modelFilter;
2503
+ const filterHasNoRows =
2504
+ storedFilter !== null &&
2505
+ storedFilter !== 'all' &&
2506
+ (storedFilter === 'available'
2507
+ ? usableRows.length === 0
2508
+ : models.some((m) => m.probed === true) &&
2509
+ models.filter((m) => m.reason === storedFilter).length === 0);
2510
+ const activeFilter = filterHasNoRows ? 'all' : (storedFilter ?? 'all');
2511
+
2512
+ const query = filter.trim().toLowerCase();
2513
+ const matched = models.filter((m) => {
2514
+ // 「可用」=上游認得這個模型。429 只代表這次排不進去,模型本身有效,
2515
+ // 所以算在可用裡。
2516
+ if (activeFilter === 'available' && (m.valid ?? m.available) !== true) return false;
2517
+ if (activeFilter !== 'all' && activeFilter !== 'available' && m.reason !== activeFilter) return false;
2518
+ if (query && !m.id.toLowerCase().includes(query)) return false;
2519
+ return true;
2520
+ });
2521
+
2522
+ // 排序:勾選的排在最上面。
2523
+ //
2524
+ // 理由很直接:勾選是使用者明確表示「我要這個」,那一份就是他實際在
2525
+ // 選擇器裡看到的清單。放在最上面,他掃一眼就能確認「現在有哪些能用」,
2526
+ // 不用在一張 46 列的表裡用眼睛過濾打勾的少數幾列。
2527
+ //
2528
+ // 排序必須是穩定的:同一個勾選狀態內保持目錄原序,否則每次輪詢
2529
+ // 更新資料時列會亂跳,使用者剛看的那一列會跑掉。
2530
+ const filtered = [...matched].sort((a, b) => {
2531
+ const sa = a.shown === true ? 0 : 1;
2532
+ const sb = b.shown === true ? 0 : 1;
2533
+ return sa - sb;
2534
+ });
2535
+ const visible = showAll ? filtered : filtered.slice(0, MODELS_COLLAPSED);
2536
+
2537
+ // 展開中的那一列可能被切在收合邊界之外。
2538
+ //
2539
+ // 使用者的動作是「點開某一列看詳情」,如果那一列剛好落在第 9 列之後,
2540
+ // 收合狀態下它就消失,畫面上只剩一片空白——他會以為「卡片卡住了」。
2541
+ // 這種情況就地展開整份,比默默吃掉他的點擊合理。
2542
+ //
2543
+ // 用純計算而不是呼叫 setShowAll:在渲染期間改 state 會讓 React 反覆
2544
+ // 重跑這個元件(而且是無聲的),畫面會抖。
2545
+ const expandedOutsideWindow = !showAll
2546
+ && expandedModel !== null
2547
+ && filtered.some((m) => m.id === expandedModel)
2548
+ && !visible.some((m) => m.id === expandedModel);
2549
+ const rows = expandedOutsideWindow ? filtered : visible;
2550
+
2551
+ /* ---------------------------------------------------- 備援設定 */
2552
+
2553
+ // 主機端的值(每次輪詢更新)與使用者正在改的草稿。
2554
+ const fallbackSaved = status.fallback ?? { enabled: false, models: [], maxModels: 3 };
2555
+ const fallbackState = fallbackDraft ?? fallbackSaved;
2556
+ const fallbackDirty = fallbackDraft !== null;
2557
+
2558
+ // 可選的模型:只列探測為可用的。把已經確定不通的模型放進下拉選單,
2559
+ // 等於邀請使用者把備援指向一個不會成功的目標。
2560
+ const selectable = models.filter((m) => m.ok);
2561
+
2562
+ const slotValue = (index) => fallbackState.models?.[index] ?? '';
2563
+
2564
+ const setSlot = (index, value) => {
2565
+ const next = [...(fallbackState.models ?? [])];
2566
+ // 清空選項時要真的清掉那個位置,不能留下 undefined——
2567
+ // JSON 化之後它會變成 null,伺服端就得額外處理這個型別。
2568
+ if (value === '' || value === undefined) next.splice(index, 1);
2569
+ else next[index] = value;
2570
+ // 去重時保留先出現的那一個:使用者在第一順位選了 A,
2571
+ // 第三順位就不該還留著 A。
2572
+ const deduped = next.filter((id, i) => id && next.indexOf(id) === i);
2573
+ setFallbackDraft({
2574
+ enabled: fallbackState.enabled,
2575
+ models: deduped,
2576
+ maxModels: fallbackSaved.maxModels ?? 3
2577
+ });
2578
+ };
2579
+
2580
+ const toggleFallback = (enabled) => {
2581
+ setFallbackDraft({
2582
+ enabled,
2583
+ models: [...(fallbackState.models ?? [])],
2584
+ maxModels: fallbackSaved.maxModels ?? 3
2585
+ });
2586
+ };
2587
+
2588
+ const toggleAutoSwitch = async (enabled) => {
2589
+ setBusy('auto-switch');
2590
+ setMessage(null);
2591
+ try {
2592
+ await callApi('auto-switch', 'POST', { enabled });
2593
+ setMessage({ kind: 'info', text: t('autoSwitchSaved') });
2594
+ await load();
2595
+ } catch (error) {
2596
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2597
+ } finally {
2598
+ setBusy('');
2599
+ }
2600
+ };
2601
+
2602
+ const saveFallback = async () => {
2603
+ setBusy('fallback');
2604
+ setMessage(null);
2605
+ try {
2606
+ const value = await callApi('fallback', 'POST', {
2607
+ enabled: fallbackState.enabled,
2608
+ models: fallbackState.models ?? []
2609
+ });
2610
+ // 主機端可能修剪過(未知模型、重複、超過三個),所以存完以它為準。
2611
+ setFallbackDraft(null);
2612
+ setMessage({ kind: 'info', text: t('fallbackSaved') });
2613
+ await load();
2614
+ return value;
2615
+ } catch (error) {
2616
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2617
+ return null;
2618
+ } finally {
2619
+ setBusy('');
2620
+ }
2621
+ };
2622
+
2623
+ // 勾選/取消:一次只改一個模型。
2624
+ //
2625
+ // 走 busy 集中管理(而不是每列各自的 loading):勾選是「表格層級」的
2626
+ // 狀態改變,同一時間只該有一筆在飛,否則快速連點會讓後到的回應覆蓋
2627
+ // 先到的結果。
2628
+ const togglePicker = async (modelId, shown) => {
2629
+ setBusy(`picker:${modelId}`);
2630
+ setMessage(null);
2631
+ try {
2632
+ await callApi('picker', 'POST', { modelId, shown });
2633
+ await load();
2634
+ } catch (error) {
2635
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2636
+ } finally {
2637
+ setBusy('');
2638
+ }
2639
+ };
2640
+
2641
+ // 勾選欄能不能動。
2642
+ //
2643
+ // 判準是「上游有沒有認得這個模型」(valid),不是「這次問不問得到」(ok)。
2644
+ // 429 只是額度或速率受限,模型本身有效,使用者當然有權決定要不要把它
2645
+ // 留在選擇器裡;真正該禁用的只有上游已判定不存在/下架的模型。
2646
+ const pickerEnabled = (m) => (m.valid ?? m.available) === true && busy === '';
2647
+
2648
+ // 回到自動模式:等於「我不要再挑了」,全部可用模型重新顯示。
2649
+ const resetPicker = async () => {
2650
+ setBusy('picker-reset');
2651
+ setMessage(null);
2652
+ try {
2653
+ await callApi('picker', 'POST', { mode: 'auto' });
2654
+ await load();
2655
+ } catch (error) {
2656
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2657
+ } finally {
2658
+ setBusy('');
2659
+ }
2660
+ };
2661
+
2662
+ const contextDraftFor = (model) => contextDrafts[model.id] ?? {
2663
+ mode: model.contextOverride == null ? 'default' : 'custom',
2664
+ value: String(model.contextOverride ?? model.contextWindow ?? '')
2665
+ };
2666
+
2667
+ const updateContextDraft = (model, patch) => {
2668
+ const current = contextDraftFor(model);
2669
+ setContextDrafts({ ...contextDrafts, [model.id]: { ...current, ...patch } });
2670
+ };
2671
+
2672
+ const contextDraftChanged = (model, draft) => draft.mode === 'default'
2673
+ ? model.contextOverride != null
2674
+ : model.contextOverride == null || Number(draft.value) !== model.contextOverride;
2675
+
2676
+ const persistContext = async (model, contextWindow) => {
2677
+ setBusy('context');
2678
+ setMessage(null);
2679
+ try {
2680
+ await callApi('context', 'POST', { modelId: model.id, contextWindow });
2681
+ const nextDrafts = { ...contextDrafts };
2682
+ delete nextDrafts[model.id];
2683
+ setContextDrafts(nextDrafts);
2684
+ setMessage({ kind: 'info', text: t('contextSaved') });
2685
+ await load();
2686
+ } catch (error) {
2687
+ setMessage({ kind: 'error', text: t('errorGeneric', { message: error.message }) });
2688
+ } finally {
2689
+ setBusy('');
2690
+ }
2691
+ };
2692
+
2693
+ const saveContext = async (model) => {
2694
+ const draft = contextDraftFor(model);
2695
+ if (draft.mode === 'default') return persistContext(model, null);
2696
+ const value = Number(draft.value);
2697
+ if (!Number.isSafeInteger(value) || value < 1024 || value > 100000000) {
2698
+ setMessage({ kind: 'error', text: t('contextInvalid') });
2699
+ return;
2700
+ }
2701
+ return persistContext(model, value);
2702
+ };
2703
+
2704
+ const resetContext = (model) => persistContext(model, null);
2705
+
2706
+ const fallbackSlots = [];
2707
+ for (let i = 0; i < (fallbackSaved.maxModels ?? 3); i++) {
2708
+ const current = slotValue(i);
2709
+ const options = [h('option', { key: '__none', value: '' }, t('fallbackNone'))];
2710
+ for (const m of selectable) {
2711
+ // 已經被別的順位選走的模型不再列出來:同一個模型排在
2712
+ // 兩個順位沒有意義,只會讓使用者以為有兩層保險。
2713
+ const takenElsewhere = (fallbackState.models ?? []).some((id, idx) => id === m.id && idx !== i);
2714
+ if (takenElsewhere) continue;
2715
+ options.push(h('option', { key: m.id, value: m.id }, m.id));
2716
+ }
2717
+ fallbackSlots.push(
2718
+ h(
2719
+ 'label',
2720
+ { className: 'ocoa-fallback-slot', key: `slot-${i}` },
2721
+ h('span', { className: 'ocoa-fallback-slot-label' }, t('fallbackSlot', { n: i + 1 })),
2722
+ h(
2723
+ 'select',
2724
+ {
2725
+ className: 'ocoa-input ocoa-fallback-select',
2726
+ value: current,
2727
+ disabled: busy !== '',
2728
+ onChange: (event) => setSlot(i, event.target.value)
2729
+ },
2730
+ options
2731
+ )
2732
+ )
2733
+ );
2734
+ }
2735
+
2736
+ const modelRow = (m) => {
2737
+ const rk = m.probed && !m.ok ? reasonKey(m.reason) : null;
2738
+ // 失敗原因只放進展開區,主列只留狀態。
2739
+ const detail = !m.probed
2740
+ ? t('statusUnprobed')
2741
+ : m.ok
2742
+ ? ''
2743
+ : rk
2744
+ ? t(rk)
2745
+ : m.status
2746
+ ? `HTTP ${m.status}`
2747
+ : t('rUnknown');
2748
+ // 上游原始回應。
2749
+ //
2750
+ // 中文標籤是我們的解讀,而解讀可能錯(實測就錯過:把「上下文超限」
2751
+ // 與「帳號權限」都講成「模型已下線」,害人往錯方向修)。原始文字不會錯,
2752
+ // 而且可以直接拿去搜尋。所以失敗的列一定要把它帶出來。
2753
+ //
2754
+ // 只在失敗時顯示:成功的模型沒有錯誤訊息,佔位子只是雜訊。
2755
+ const raw = !m.probed || m.ok ? '' : (m.detail || '').trim();
2756
+ const contextDraft = contextDraftFor(m);
2757
+ const contextSourceKey = m.contextSource === 'custom'
2758
+ ? 'contextSourceCustom'
2759
+ : m.contextSource === 'opencode'
2760
+ ? 'contextSourceOpenCode'
2761
+ : 'contextSourceFallback';
2762
+ const contextDirty = contextDraftChanged(m, contextDraft);
2763
+ const open = expandedModel === m.id;
2764
+
2765
+ return h(
2766
+ 'tbody',
2767
+ { key: m.id, className: 'ocoa-model-group' },
2768
+ h(
2769
+ 'tr',
2770
+ { key: m.id + ':row', className: `ocoa-model-row${open ? ' is-open' : ''}` },
2771
+ // 勾選欄在最左邊:這是使用者對這張表最主要、也最常做的動作,
2772
+ // 眼睛掃的是「哪幾個打勾」,所以它該站在行的起點。
2773
+ h(
2774
+ 'td',
2775
+ { className: 'ocoa-pick' },
2776
+ h('input', {
2777
+ type: 'checkbox',
2778
+ className: 'ocoa-pick-box',
2779
+ checked: m.shown === true,
2780
+ disabled: !pickerEnabled(m),
2781
+ 'aria-label': `${t('pickerShow')} — ${m.id}`,
2782
+ title: m.available ? t('pickerShow') : t('pickerHidden'),
2783
+ 'data-model-id': m.id,
2784
+ onChange: (event) => togglePicker(m.id, event.target.checked)
2785
+ })
2786
+ ),
2787
+ h(
2788
+ 'td',
2789
+ { className: 'ocoa-model' },
2790
+ h(
2791
+ 'span',
2792
+ {
2793
+ className: open ? 'ocoa-model-toggle' : 'ocoa-model-id',
2794
+ 'aria-expanded': open ? true : undefined,
2795
+ title: m.name && m.name !== m.id ? `${m.name} (${m.id})` : m.id
2796
+ },
2797
+ m.name && m.name !== m.id ? `${m.name} · ${m.id}` : m.id
2798
+ )
2799
+ ),
2800
+ h(
2801
+ 'td',
2802
+ null,
2803
+ h(
2804
+ 'div',
2805
+ { className: 'ocoa-status', title: detail || undefined },
2806
+ h(
2807
+ 'span',
2808
+ {
2809
+ // 三種狀態,而不是原本的兩種。
2810
+ //
2811
+ // 「失敗」對 429 是錯的標籤:模型有效,只是這次排不進去。
2812
+ // 把它染成紅色的「失敗」,使用者會以為模型壞了,去換一個
2813
+ // 其實一樣好的模型。用黃色的「限流」講清楚:模型在,稍等。
2814
+ className: `ocoa-badge ${m.ok ? 'ok' : !m.probed ? 'dim' : (m.valid ? 'warn' : 'off')}`
2815
+ },
2816
+ m.ok
2817
+ ? t('statusOk')
2818
+ : !m.probed
2819
+ ? t('statusUnprobed')
2820
+ : m.valid
2821
+ ? t('statusLimited')
2822
+ : t('statusFail')
2823
+ ),
2824
+ m.probed && !m.ok && detail
2825
+ ? h('span', { className: 'ocoa-status-reason' }, detail)
2826
+ : null
2827
+ )
2828
+ ),
2829
+ h(
2830
+ 'td',
2831
+ { className: 'ocoa-num' },
2832
+ h(
2833
+ 'button',
2834
+ {
2835
+ type: 'button',
2836
+ className: `ocoa-context-btn${m.contextOverride != null ? ' is-custom' : ''}`,
2837
+ title: t('contextClickToEdit'),
2838
+ onClick: (e) => {
2839
+ e.stopPropagation();
2840
+ openContextModal(m);
2841
+ }
2842
+ },
2843
+ h('span', null, numberLabel(m.contextWindow ?? m.catalogContextWindow))
2844
+ )
2845
+ ),
2846
+ h(
2847
+ 'td',
2848
+ { className: 'ocoa-num' },
2849
+ m.ms === null || m.ms === undefined ? '–' : `${m.ms} ms`
2850
+ )
2851
+ ),
2852
+ open
2853
+ ? h(
2854
+ 'tr',
2855
+ { key: m.id + ':expand', className: 'ocoa-model-expand' },
2856
+ h(
2857
+ 'td',
2858
+ { colSpan: 5 },
2859
+ h(
2860
+ 'div',
2861
+ { className: 'ocoa-expand-body' },
2862
+ detail ? h('div', { className: 'ocoa-expand-reason' }, detail) : null,
2863
+ m.probed
2864
+ ? h(
2865
+ 'div',
2866
+ { className: 'ocoa-diagnostic-meta' },
2867
+ t(m.available ? 'pickerAvailable' : 'pickerHidden'),
2868
+ m.status !== null && m.status !== undefined ? ` · HTTP ${m.status}` : '',
2869
+ m.probedAt
2870
+ ? ` · ${t('modelProbedAt', { when: formatWhen(m.probedAt, localeId) })}`
2871
+ : '',
2872
+ m.failureStreak > 0
2873
+ ? ` · ${t('modelFailureStreak', { count: m.failureStreak })}`
2874
+ : ''
2875
+ )
2876
+ : null,
2877
+ raw
2878
+ ? h(
2879
+ 'div',
2880
+ { className: 'ocoa-raw', title: raw },
2881
+ h('span', { className: 'ocoa-raw-label' }, 'HTTP ' + (m.status ?? '?')),
2882
+ ' ',
2883
+ h('code', null, raw)
2884
+ )
2885
+ : null,
2886
+ h(
2887
+ 'details',
2888
+ { className: 'ocoa-context-editor' },
2889
+ h(
2890
+ 'summary',
2891
+ null,
2892
+ t('contextSummary', {
2893
+ effective: numberLabel(m.contextWindow ?? m.catalogContextWindow),
2894
+ source: t(contextSourceKey)
2895
+ })
2896
+ ),
2897
+ h(
2898
+ 'div',
2899
+ { className: 'ocoa-context-panel' },
2900
+ h(
2901
+ 'div',
2902
+ { className: 'ocoa-context-default' },
2903
+ t('contextPublished', { value: numberLabel(m.catalogContextWindow ?? m.contextWindow) })
2904
+ ),
2905
+ // 上游的單次輸出上限。使用者問「最大值是多少」時,問的
2906
+ // 常常是這個而不是上下文;目錄有給(`limit.output`),
2907
+ // 但以前只活在 describe() 裡,畫面上完全看不到。
2908
+ Number.isFinite(m.maxOutputTokens)
2909
+ ? h(
2910
+ 'div',
2911
+ { className: 'ocoa-context-default' },
2912
+ t('contextMaxOutput', { value: numberLabel(m.maxOutputTokens) })
2913
+ )
2914
+ : null,
2915
+ h('p', { className: 'ocoa-context-hint' }, t('contextHint')),
2916
+ h(
2917
+ 'label',
2918
+ { className: 'ocoa-context-field' },
2919
+ h('span', null, t('contextMode')),
2920
+ h(
2921
+ 'select',
2922
+ {
2923
+ className: 'ocoa-input',
2924
+ value: contextDraft.mode,
2925
+ disabled: busy !== '',
2926
+ onChange: (event) => updateContextDraft(m, { mode: event.target.value })
2927
+ },
2928
+ h('option', { value: 'default' }, t('contextDefault')),
2929
+ h('option', { value: 'custom' }, t('contextCustom'))
2930
+ )
2931
+ ),
2932
+ contextDraft.mode === 'custom'
2933
+ ? h(
2934
+ 'label',
2935
+ { className: 'ocoa-context-field' },
2936
+ h('span', null, t('contextValue')),
2937
+ h('input', {
2938
+ className: 'ocoa-input ocoa-context-number',
2939
+ type: 'number',
2940
+ min: 1024,
2941
+ max: 100000000,
2942
+ step: 1,
2943
+ value: contextDraft.value,
2944
+ disabled: busy !== '',
2945
+ onChange: (event) => updateContextDraft(m, { value: event.target.value })
2946
+ })
2947
+ )
2948
+ : null,
2949
+ h(
2950
+ 'div',
2951
+ { className: 'ocoa-actions' },
2952
+ h(
2953
+ 'button',
2954
+ {
2955
+ className: 'ocoa-btn',
2956
+ disabled: busy !== '' || !contextDirty,
2957
+ onClick: () => saveContext(m)
2958
+ },
2959
+ busy === 'context' ? t('contextSaving') : t('contextSave')
2960
+ ),
2961
+ h(
2962
+ 'button',
2963
+ {
2964
+ className: 'ocoa-btn ghost',
2965
+ disabled: busy !== '' || m.contextOverride == null,
2966
+ onClick: () => resetContext(m)
2967
+ },
2968
+ t('contextReset')
2969
+ )
2970
+ )
2971
+ )
2972
+ )
2973
+ )
2974
+ )
2975
+ )
2976
+ : null
2977
+ );
2978
+ };
2979
+
2980
+ const head = h(
2981
+ 'div',
2982
+ { className: 'ocoa-head' },
2983
+ h(
2984
+ 'div',
2985
+ { className: 'ocoa-title-row' },
2986
+ h('span', { className: 'ocoa-title' }, t('title')),
2987
+ h(Chip, { tone: chip.tone, text: t(chip.key) }),
2988
+ // 語言切換鍵推到最右側。只影響本分頁,不動 DSH 全域語言。
2989
+ h(LanguageSwitcher, {
2990
+ choice: languageChoice ?? 'auto',
2991
+ localeId,
2992
+ t,
2993
+ onChange: (value) => {
2994
+ setLanguageChoice(value);
2995
+ writeStoredLanguage(value);
2996
+ }
2997
+ })
2998
+ )
2999
+ );
3000
+
3001
+ /* -------------------------------------------- 授權狀態 + 帳號 */
3002
+ // 這兩件事其實是同一件事:登入的是哪個帳號、那個帳號還有效嗎。
3003
+ // 分成兩張卡時,使用者得在兩張卡之間來回比對「現在生效的」和「有幾個」,
3004
+ // 而且兩張卡的按鈕長得一樣(重新登入 vs 新增帳號),很容易按錯。
3005
+ const accountPane = h(
3006
+ 'div',
3007
+ { className: 'ocoa-card' },
3008
+ h(
3009
+ 'div',
3010
+ { className: 'ocoa-card-head' },
3011
+ h('span', { className: 'ocoa-card-title' }, t('sectionAccount')),
3012
+ h(
3013
+ 'div',
3014
+ { className: 'ocoa-actions' },
3015
+ h(
3016
+ 'button',
3017
+ {
3018
+ className: 'ocoa-btn',
3019
+ onClick: () => act('refresh', 'refresh'),
3020
+ disabled: busy !== ''
3021
+ },
3022
+ busy === 'refresh' ? t('refreshing') : t('verify')
3023
+ ),
3024
+ h(
3025
+ 'button',
3026
+ {
3027
+ className: 'ocoa-btn',
3028
+ onClick: () => act('importLocal', 'accounts/import-local'),
3029
+ disabled: busy !== ''
3030
+ },
3031
+ busy === 'importLocal' ? t('importingLocal') : t('importLocal')
3032
+ ),
3033
+ h(
3034
+ 'button',
3035
+ {
3036
+ className: 'ocoa-btn primary',
3037
+ onClick: () => act('login', 'login'),
3038
+ disabled: busy !== ''
3039
+ },
3040
+ busy === 'login' ? t('loggingIn') : cred.present ? t('reauth') : t('login')
3041
+ ),
3042
+ cred.present
3043
+ ? h(
3044
+ 'button',
3045
+ {
3046
+ className: 'ocoa-btn ghost',
3047
+ onClick: () => act('logout', 'logout'),
3048
+ disabled: busy !== ''
3049
+ },
3050
+ t('logout')
3051
+ )
3052
+ : null
3053
+ )
3054
+ ),
3055
+
3056
+ // 三個事實並排成橫向條:它們是一組的(來源/到期/可否自動續),
3057
+ // 直排會讓一張卡佔掉兩倍高度,卻沒有比較好讀。
3058
+ h(
3059
+ 'dl',
3060
+ { className: 'ocoa-facts' },
3061
+ Fact({ label: t('credSource'), children: cred.present ? sourceLabel : t('credAbsent') }),
3062
+ Fact({ label: t('credExpiry'), children: expiryText }),
3063
+ Fact({
3064
+ label: t('credRefreshable'),
3065
+ children: cred.present ? (cred.hasRefresh ? t('credYes') : t('credNo')) : '–'
3066
+ })
3067
+ ),
3068
+
3069
+ // 憑證有效且一切正常時,這行只是把「可用」再說一次,而模型分類就在
3070
+ // 下面——留著只會多佔一行。只在真的有狀況時顯示。
3071
+ (() => {
3072
+ const hk = healthMessageKey(status.health);
3073
+ if (!hk || status.health === 'ready') return null;
3074
+ return h('div', { className: 'ocoa-msg' }, t(hk));
3075
+ })(),
3076
+
3077
+ !cred.present ? h('div', { className: 'ocoa-note' }, t('signedOutHint')) : null,
3078
+
3079
+ // 登入進行中:顯示裝置代碼與驗證網址。
3080
+ pending
3081
+ ? h(
3082
+ 'div',
3083
+ { className: 'ocoa-codebox' },
3084
+ h('span', null, t('userCode')),
3085
+ h('span', { className: 'ocoa-usercode' }, pending.userCode),
3086
+ h(
3087
+ 'button',
3088
+ { className: 'ocoa-btn ghost', onClick: () => copy(pending.userCode, 'code') },
3089
+ copied === 'code' ? t('copied') : t('copy')
3090
+ ),
3091
+ h(
3092
+ 'a',
3093
+ {
3094
+ className: 'ocoa-link ocoa-url',
3095
+ href: pending.verificationUrl,
3096
+ target: '_blank',
3097
+ rel: 'noopener'
3098
+ },
3099
+ pending.verificationUrl
3100
+ ),
3101
+ h(
3102
+ 'button',
3103
+ {
3104
+ className: 'ocoa-btn ghost',
3105
+ onClick: () => window.open(pending.verificationUrl, '_blank', 'noopener')
3106
+ },
3107
+ t('openAgain')
3108
+ ),
3109
+ h(
3110
+ 'button',
3111
+ {
3112
+ className: 'ocoa-btn ghost',
3113
+ disabled: busy !== '',
3114
+ onClick: () => void act('cancelLogin', 'login/cancel')
3115
+ },
3116
+ busy === 'cancelLogin' ? t('cancelling') : t('cancelLogin')
3117
+ )
3118
+ )
3119
+ : null,
3120
+
3121
+ // 只留下「去哪裡確認」的指示;代碼本身已經在上面用大字顯示,這裡再
3122
+ // 接一次只會讓同一串字在同一張卡片裡出現兩次。
3123
+ pending ? h('div', { className: 'ocoa-note' }, t('loginHint')) : null,
3124
+
3125
+ // 背景輪詢的失敗不會回到當初那次 POST。狀態裡的 loginError 才是
3126
+ // 那一次的結果;進行中的登入仍以裝置碼為準,不把舊失敗疊在上面。
3127
+ !pending && loginFailureText(t, status.loginError)
3128
+ ? h('div', { className: 'ocoa-msg' }, `⚠ ${loginFailureText(t, status.loginError)}`)
3129
+ : null,
3130
+
3131
+ message
3132
+ ? h(
3133
+ 'div',
3134
+ { className: 'ocoa-msg' },
3135
+ message.kind === 'error' ? `⚠ ${message.text}` : `ⓘ ${message.text}`
3136
+ )
3137
+ : null,
3138
+
3139
+ h('hr', { className: 'ocoa-divider' }),
3140
+
3141
+ /* 帳號清單:接在同一張卡的下半部。 */
3142
+ h(
3143
+ 'div',
3144
+ { className: 'ocoa-card-head' },
3145
+ h('span', { className: 'ocoa-subhead' }, t('sectionAccounts')),
3146
+ addAccountOpen
3147
+ ? h(
3148
+ 'div',
3149
+ { className: 'ocoa-actions' },
3150
+ h('input', {
3151
+ className: 'ocoa-input',
3152
+ type: 'text',
3153
+ value: accountLabel,
3154
+ placeholder: t('accountLabelPlaceholder'),
3155
+ 'aria-label': t('accountLabel'),
3156
+ autoFocus: true,
3157
+ onChange: (event) => setAccountLabel(event.target.value)
3158
+ }),
3159
+ h(
3160
+ 'button',
3161
+ { className: 'ocoa-btn primary', disabled: busy !== '', onClick: beginAddAccount },
3162
+ busy === 'login' ? t('loggingIn') : t('accountStart')
3163
+ ),
3164
+ h(
3165
+ 'button',
3166
+ { className: 'ocoa-btn ghost', disabled: busy !== '', onClick: cancelAddAccount },
3167
+ t('accountCancel')
3168
+ )
3169
+ )
3170
+ : h(
3171
+ 'button',
3172
+ {
3173
+ className: 'ocoa-btn',
3174
+ disabled: busy !== '',
3175
+ onClick: () => {
3176
+ setMessage(null);
3177
+ setAddAccountOpen(true);
3178
+ }
3179
+ },
3180
+ busy === 'login' ? t('loggingIn') : t('accountAdd')
3181
+ )
3182
+ ),
3183
+
3184
+ accounts.length > 0
3185
+ ? h(
3186
+ 'div',
3187
+ { className: 'ocoa-account-list' },
3188
+ ...accounts.map((account) => h(
3189
+ 'div',
3190
+ { key: account.id, className: 'ocoa-account-row' },
3191
+ h(
3192
+ 'span',
3193
+ { className: 'ocoa-account-name', title: account.label || t('accountNoLabel') },
3194
+ h('span', {
3195
+ className: `ocoa-account-dot${account.isActive ? ' is-active' : ''}`,
3196
+ 'aria-hidden': 'true'
3197
+ }),
3198
+ h('span', { className: 'ocoa-account-label' }, account.label || t('accountNoLabel'))
3199
+ ),
3200
+ h(
3201
+ 'span',
3202
+ { className: `ocoa-badge ${account.expired ? 'off' : 'ok'}` },
3203
+ account.expired
3204
+ ? t('accountExpired')
3205
+ : account.expiresInSeconds == null
3206
+ ? t('accountActive')
3207
+ : t('accountExpiry', { time: dur(account.expiresInSeconds * 1000) })
3208
+ ),
3209
+ account.isActive
3210
+ ? h(
3211
+ 'span',
3212
+ { className: 'ocoa-account-active', 'aria-label': t('accountActive') },
3213
+ h('span', { className: 'ocoa-dot', 'aria-hidden': 'true' }),
3214
+ t('accountActive')
3215
+ )
3216
+ : h(
3217
+ 'button',
3218
+ {
3219
+ className: 'ocoa-btn',
3220
+ disabled: busy !== '',
3221
+ onClick: async () => {
3222
+ await callApi('accounts/switch', 'POST', { id: account.id });
3223
+ await load();
3224
+ }
3225
+ },
3226
+ t('accountSwitch')
3227
+ ),
3228
+ h(
3229
+ 'button',
3230
+ {
3231
+ className: 'ocoa-btn ghost',
3232
+ disabled: accounts.length <= 1,
3233
+ onClick: () => setRemoveAccountModal(account)
3234
+ },
3235
+ t('accountRemove')
3236
+ )
3237
+ ))
3238
+ )
3239
+ : h('div', { className: 'ocoa-note' }, t('signedOutHint')),
3240
+
3241
+ h('div', { className: 'ocoa-msg' }, t('accountAddHint')),
3242
+
3243
+ // 自動切換本質上是帳號行為,所以留在同一張卡裡;為了一個勾選框再開一張
3244
+ // 卡片只會讓頁面多一個分類。用細線與次標題跟上面的清單分開。
3245
+ h('hr', { className: 'ocoa-divider' }),
3246
+ h('span', { className: 'ocoa-subhead' }, t('sectionAutoSwitch')),
3247
+ h(
3248
+ 'label',
3249
+ { className: 'ocoa-check' },
3250
+ h('input', {
3251
+ type: 'checkbox',
3252
+ checked: status?.autoSwitch?.enabled === true,
3253
+ disabled: busy !== '',
3254
+ onChange: (event) => toggleAutoSwitch(event.target.checked)
3255
+ }),
3256
+ t('autoSwitchEnable')
3257
+ ),
3258
+ h('div', { className: 'ocoa-note' }, t('autoSwitchHint'))
3259
+ );
3260
+
3261
+ /* -------------------------------------------------------- 模型 */
3262
+ const modelsPane = h(
3263
+ 'div',
3264
+ { className: 'ocoa-card' },
3265
+ h(
3266
+ 'div',
3267
+ { className: 'ocoa-card-head' },
3268
+ h(
3269
+ 'span',
3270
+ { className: 'ocoa-card-title' },
3271
+ // 不寫「模型」:頁籤已經寫了,卡片標題再寫一次是同一件事講兩遍。
3272
+ // 改成一句狀態說明,講「這張表現在是什麼」。
3273
+ t('modelsCaption')
3274
+ ),
3275
+ h(
3276
+ 'div',
3277
+ { className: 'ocoa-actions' },
3278
+ // 「顯示全部」只在手動模式出現:自動模式下它已經是事實,
3279
+ // 多一顆按鈕只會讓「現在是哪種模式」更難判斷。
3280
+ picker?.mode === 'manual'
3281
+ ? h(
3282
+ 'button',
3283
+ {
3284
+ className: 'ocoa-btn ghost',
3285
+ onClick: resetPicker,
3286
+ disabled: busy !== ''
3287
+ },
3288
+ busy === 'picker-reset' ? t('pickerResetBusy') : t('pickerReset')
3289
+ )
3290
+ : null,
3291
+ h(
3292
+ 'button',
3293
+ {
3294
+ className: 'ocoa-btn',
3295
+ onClick: () => {
3296
+ const isScoped = (activeFilter === 'available' || activeFilter !== 'all' || query.length > 0) && matched.length > 0;
3297
+ const modelIds = isScoped ? matched.map((m) => m.id) : undefined;
3298
+ act('probe', 'probe', modelIds ? { modelIds } : {});
3299
+ },
3300
+ disabled: busy !== ''
3301
+ },
3302
+ busy === 'probe'
3303
+ ? t('probing')
3304
+ : activeFilter === 'available' && matched.length > 0
3305
+ ? t('reprobeAvailable', { n: matched.length })
3306
+ : (activeFilter !== 'all' || query.length > 0) && matched.length > 0
3307
+ ? t('reprobeFiltered', { n: matched.length })
3308
+ : t('reprobe')
3309
+ )
3310
+ )
3311
+ ),
3312
+
3313
+ // 勾選模式的說明。
3314
+ //
3315
+ // 這一行是必要的:勾選框本身看不出「勾了之後新模型還會不會自動
3316
+ // 冒出來」。手動模式下如果不說清楚,使用者會以為功能壞了——
3317
+ // 他明明期待新模型出現。所以模式要明講,兩個數字也要明講。
3318
+ picker
3319
+ ? h(
3320
+ 'div',
3321
+ { className: 'ocoa-picker-mode' },
3322
+ h(
3323
+ 'span',
3324
+ { className: `ocoa-badge ${picker.mode === 'manual' ? 'accent' : 'dim'}` },
3325
+ picker.mode === 'manual' ? t('pickerManualShort') : t('pickerAutoShort')
3326
+ ),
3327
+ h(
3328
+ 'span',
3329
+ { className: 'ocoa-picker-mode-text' },
3330
+ picker.mode === 'manual'
3331
+ ? t('pickerManual', { n: picker.shown?.length ?? 0, total: summary.available ?? 0 })
3332
+ : t('pickerAuto')
3333
+ )
3334
+ )
3335
+ : null,
3336
+
3337
+ h(
3338
+ 'div',
3339
+ { className: 'ocoa-msg' },
3340
+ (probedWhen ? t('probedAgo', { when: probedWhen }) : t('neverProbed'))
3341
+ + ' · '
3342
+ + t('modelsAvailable', { ok: summary.valid ?? summary.available ?? 0, total: summary.total ?? 0 })
3343
+ ),
3344
+
3345
+ // 上一輪被熔斷時,把範圍講清楚。
3346
+ //
3347
+ // 沒有這行的話,「13 個可用」配上「4 筆探測紀錄」看起來像探測壞掉;
3348
+ // 事實是第 4 個模型撞到限流就停手,剩下 42 個還沿用上次結果。
3349
+ (() => {
3350
+ const cut = summary.truncation;
3351
+ if (!cut || !(cut.total > 0)) return null;
3352
+ const key = cut.stopped === 'unreachable' ? 'truncatedUnreachable' : 'truncatedRateLimit';
3353
+ return h(
3354
+ 'div',
3355
+ { className: 'ocoa-msg ocoa-msg-warn', 'data-probe-truncated': cut.stopped ?? 'unknown' },
3356
+ `⚠ ${t(key, { tested: cut.tested, total: cut.total })}`
3357
+ );
3358
+ })(),
3359
+
3360
+ // 額度解除時間。
3361
+ //
3362
+ // 這是使用者最想要的一個數字:上游 429 會帶 retry-after,換算成
3363
+ // 「今天 08:15 解除(還有 1 小時 30 分)」,他才知道該等還是該換模型。
3364
+ // 上游沒給時誠實說沒給,不要編一個看起來合理的數字。
3365
+ (() => {
3366
+ const quota = status.quota;
3367
+ if (!quota || !Number.isFinite(quota.resetAt)) return null;
3368
+ const remaining = quota.resetAt - Date.now();
3369
+ if (remaining <= 0) {
3370
+ return h(
3371
+ 'div',
3372
+ { className: 'ocoa-msg', 'data-quota-reset': 'expired' },
3373
+ `✓ ${t('quotaResetReady')}`
3374
+ );
3375
+ }
3376
+ return h(
3377
+ 'div',
3378
+ { className: 'ocoa-msg ocoa-msg-warn', 'data-quota-reset': 'pending' },
3379
+ `⏳ ${t('quotaReset', {
3380
+ when: formatWhen(quota.resetAt, localeId),
3381
+ in: shortDuration(remaining, durUnits)
3382
+ })}`
3383
+ );
3384
+ })(),
3385
+
3386
+ // 分類篩選:一條連續的分段選單,而不是散落的標籤。
3387
+ //
3388
+ // 為什麼是一條而不是四顆獨立膠囊:這些選項互斥(一次只看一種),
3389
+ // 互斥的東西就該長成同一個控制項;散開的膠囊會讓人以為可以複選。
3390
+ // 「全部」放在最前面,因為那是預設的認知起點,也是清掉篩選的出口。
3391
+ (() => {
3392
+ const mm = status.models ?? {};
3393
+ const groups = Array.isArray(mm.breakdown) ? mm.breakdown : [];
3394
+ const seg = (key, label, count, filterValue, tone, fullLabel) => h(
3395
+ 'button',
3396
+ {
3397
+ type: 'button',
3398
+ key: key,
3399
+ className: `ocoa-seg${activeFilter === filterValue ? ' is-active' : ''}${tone ? ` is-${tone}` : ''}`,
3400
+ 'data-model-filter': filterValue,
3401
+ 'aria-pressed': activeFilter === filterValue,
3402
+ // 顯示短標籤,但 hover 與讀屏拿得到完整說法。
3403
+ title: fullLabel ?? label,
3404
+ 'aria-label': `${label} (${count})${fullLabel && fullLabel !== label ? ` — ${fullLabel}` : ''}`,
3405
+ onClick: () => {
3406
+ // 換分類時收起「顯示全部」,否則切到只有 3 筆的分類時,
3407
+ // 畫面會停在「顯示較少」的狀態,看起來像還有東西沒展開。
3408
+ setModelFilter(filterValue);
3409
+ writeStoredFilter(filterValue);
3410
+ setShowAll(false);
3411
+ }
3412
+ },
3413
+ count === null
3414
+ ? null
3415
+ : h('span', { className: 'ocoa-seg-count' }, String(count)),
3416
+ h('span', { className: 'ocoa-seg-label' }, label)
3417
+ );
3418
+
3419
+ return h(
3420
+ 'div',
3421
+ { className: 'ocoa-segments', role: 'group', 'aria-label': t('modelFilters') },
3422
+ seg('all', t('filterAll'), mm.total ?? 0, 'all', null),
3423
+ // 數字用 valid(上游有效),不是 available(已發佈給選擇器)。
3424
+ // 這個分類的語意是「哪些模型上游認得」,429 也算。
3425
+ seg('available', t('filterAvailable'), mm.valid ?? mm.available ?? 0, 'available', 'ok'),
3426
+ ...groups.map((group) => {
3427
+ // 用短標籤,不用完整句子:一排等寬格子裡混用「可用」與
3428
+ // 「模型目前不可用」,格寬會參差、選中項也會被撐寬。
3429
+ const sk = shortReasonKey(group.reason);
3430
+ const full = reasonKey(group.reason);
3431
+ return seg(
3432
+ group.reason,
3433
+ sk ? t(sk) : (full ? t(full) : group.label),
3434
+ group.count,
3435
+ group.reason,
3436
+ null,
3437
+ // 完整句子放進 title:短標籤省空間,但不該讓人失去解釋。
3438
+ full ? t(full) : group.label
3439
+ );
3440
+ })
3441
+ );
3442
+ })(),
3443
+
3444
+ h(
3445
+ 'div',
3446
+ { className: 'ocoa-toolbar' },
3447
+ h('input', {
3448
+ className: 'ocoa-input',
3449
+ type: 'search',
3450
+ placeholder: t('searchPlaceholder'),
3451
+ value: filter,
3452
+ onChange: (e) => setFilter(e.target.value)
3453
+ }),
3454
+ // 篩選後仍有幾筆,就寫在這裡。使用者不必自己數表格有幾列,
3455
+ // 也才知道「看不到東西」是篩選太窄還是真的沒有資料。
3456
+ //
3457
+ // 分母用 summary.total(目錄總數)而不是 models.length:後者是
3458
+ // 「這一頁拿到幾筆」,跟分類上的 46 不是同一個數字,並列會自相矛盾。
3459
+ h(
3460
+ 'span',
3461
+ { className: 'ocoa-toolbar-count' },
3462
+ t('filterCount', { shown: filtered.length, total: summary.total ?? models.length })
3463
+ )
3464
+ ),
3465
+
3466
+ rows.length > 0
3467
+ ? h(
3468
+ 'table',
3469
+ { className: 'ocoa-table' },
3470
+ h(
3471
+ 'thead',
3472
+ null,
3473
+ h(
3474
+ 'tr',
3475
+ null,
3476
+ h('th', { className: 'ocoa-pick' }, t('colPicker')),
3477
+ h('th', null, t('colModel')),
3478
+ h('th', null, t('colStatus')),
3479
+ h('th', { className: 'ocoa-num' }, t('colContext')),
3480
+ h('th', { className: 'ocoa-num' }, t('colLatency'))
3481
+ )
3482
+ ),
3483
+ rows.map(modelRow)
3484
+ )
3485
+ : h('div', { className: 'ocoa-note' }, t('noMatch')),
3486
+
3487
+ // 收合時只顯示前 8 列,按鈕要把「還有幾列沒顯示」講清楚。
3488
+ // 原本寫「顯示全部 46 個模型」,但畫面上已經有 8 列,讀起來像
3489
+ // 「上面那些不是全部」——事實是「還有 38 列」。
3490
+ filtered.length > MODELS_COLLAPSED
3491
+ ? h(
3492
+ 'button',
3493
+ { className: 'ocoa-btn ghost', onClick: () => setShowAll((v) => !v) },
3494
+ showAll
3495
+ ? t('showLess')
3496
+ : t('showRest', { n: filtered.length - MODELS_COLLAPSED, total: filtered.length })
3497
+ )
3498
+ : null
3499
+ );
3500
+
3501
+ /* -------------------------------------------------------- 進階 */
3502
+ // 備援與診斷都是「設定一次、之後很少動」的內容;各自一張卡會讓整頁變成
3503
+ // 六個分類。收進同一張卡,用次標題分隔,要找還是找得到。
3504
+ const bun = status.bun ?? {};
3505
+ const anon = status.anonymousChannel ?? {};
3506
+ const bunLast = bun.last
3507
+ ? `${bun.last.transport || 'bun'} · ${bun.last.model || ''}`
3508
+ : t('bunLastNone');
3509
+ const advancedPane = h(
3510
+ 'div',
3511
+ { className: 'ocoa-card' },
3512
+ /* --- 1. Bun 執行環境 --- */
3513
+ h(
3514
+ 'div',
3515
+ { className: 'ocoa-card-head' },
3516
+ h('span', { className: 'ocoa-card-title' }, t('sectionBun')),
3517
+ h(Chip, {
3518
+ tone: bun.installed ? 'ok' : 'off',
3519
+ text: bun.installed ? t('bunInstalled') : t('bunMissing')
3520
+ })
3521
+ ),
3522
+
3523
+ h(
3524
+ 'dl',
3525
+ { className: 'ocoa-facts' },
3526
+ Fact({
3527
+ label: t('bunEnabled'),
3528
+ children: !bun.installed ? t('bunMissing') : (bun.enabled ? t('bunUsed') : t('bunNode'))
3529
+ }),
3530
+ Fact({
3531
+ label: t('bunVersion'),
3532
+ children: bun.version ? `v${bun.version}` : '–'
3533
+ }),
3534
+ Fact({
3535
+ label: t('bunLast'),
3536
+ children: bunLast
3537
+ })
3538
+ ),
3539
+
3540
+ bun.path
3541
+ ? h(
3542
+ 'div',
3543
+ { className: 'ocoa-note ocoa-mono', style: { wordBreak: 'break-all' } },
3544
+ `PATH: ${bun.path}`
3545
+ )
3546
+ : null,
3547
+
3548
+ h('div', { className: 'ocoa-note' }, t('bunHint')),
3549
+
3550
+ bun.installed
3551
+ ? null
3552
+ : h(
3553
+ 'div',
3554
+ { className: 'ocoa-note' },
3555
+ h('div', null, t('bunMissingHint')),
3556
+ h(
3557
+ 'div',
3558
+ { className: 'ocoa-actions', style: { marginTop: '8px' } },
3559
+ h(
3560
+ 'a',
3561
+ {
3562
+ className: 'ocoa-btn',
3563
+ href: 'https://bun.sh',
3564
+ target: '_blank',
3565
+ rel: 'noopener noreferrer'
3566
+ },
3567
+ t('bunDownload')
3568
+ ),
3569
+ h(
3570
+ 'button',
3571
+ {
3572
+ className: 'ocoa-btn',
3573
+ onClick: () => act('bunRescan', 'bun/rescan'),
3574
+ disabled: busy !== ''
3575
+ },
3576
+ busy === 'bunRescan' ? t('bunRescanning') : t('bunRescan')
3577
+ )
3578
+ )
3579
+ ),
3580
+
3581
+ bun.installed
3582
+ ? h(
3583
+ 'div',
3584
+ { className: 'ocoa-actions' },
3585
+ h(
3586
+ 'button',
3587
+ {
3588
+ className: 'ocoa-btn ghost',
3589
+ onClick: () => act('bunRescan', 'bun/rescan'),
3590
+ disabled: busy !== ''
3591
+ },
3592
+ busy === 'bunRescan' ? t('bunRescanning') : t('bunRescan')
3593
+ )
3594
+ )
3595
+ : null,
3596
+
3597
+ h('hr', { className: 'ocoa-divider' }),
3598
+
3599
+ /* --- 1.5 匿名通道 --- */
3600
+ h(
3601
+ 'div',
3602
+ { className: 'ocoa-card-head' },
3603
+ h('span', { className: 'ocoa-subhead' }, t('sectionAnonymous')),
3604
+ h(Chip, {
3605
+ tone: anon.enabled ? 'warn' : 'off',
3606
+ text: anon.enabled ? t('anonOn') : t('anonOff')
3607
+ })
3608
+ ),
3609
+ h(
3610
+ 'label',
3611
+ { className: 'ocoa-check' },
3612
+ h('input', {
3613
+ type: 'checkbox',
3614
+ checked: anon.enabled === true,
3615
+ disabled: busy !== '',
3616
+ onChange: (event) => act('anonymous', 'anonymous-channel', { enabled: event.target.checked })
3617
+ }),
3618
+ t('anonEnable')
3619
+ ),
3620
+ h('div', { className: 'ocoa-note' }, t('anonWarning')),
3621
+
3622
+ h('hr', { className: 'ocoa-divider' }),
3623
+
3624
+ /* --- 2. 模型備援 --- */
3625
+ h(
3626
+ 'div',
3627
+ { className: 'ocoa-card-head' },
3628
+ h('span', { className: 'ocoa-subhead' }, t('sectionFallback')),
3629
+ h(
3630
+ 'div',
3631
+ { className: 'ocoa-actions' },
3632
+ h(
3633
+ 'button',
3634
+ {
3635
+ className: 'ocoa-btn',
3636
+ onClick: saveFallback,
3637
+ disabled: busy !== '' || !fallbackDirty
3638
+ },
3639
+ busy === 'fallback' ? t('fallbackSaving') : t('fallbackSave')
3640
+ )
3641
+ )
3642
+ ),
3643
+
3644
+ h(
3645
+ 'label',
3646
+ { className: 'ocoa-check' },
3647
+ h('input', {
3648
+ type: 'checkbox',
3649
+ checked: fallbackState.enabled === true,
3650
+ disabled: busy !== '',
3651
+ onChange: (event) => toggleFallback(event.target.checked)
3652
+ }),
3653
+ t('fallbackEnable')
3654
+ ),
3655
+
3656
+ fallbackState.enabled
3657
+ ? h('div', { className: 'ocoa-note' }, t('fallbackHint'))
3658
+ : h('div', { className: 'ocoa-note' }, t('fallbackOffNote')),
3659
+
3660
+ fallbackState.enabled
3661
+ ? selectable.length > 0
3662
+ ? h('div', { className: 'ocoa-fallback-slots' }, fallbackSlots)
3663
+ : h('div', { className: 'ocoa-note' }, t('fallbackNeedProbe'))
3664
+ : null,
3665
+
3666
+ h('hr', { className: 'ocoa-divider' }),
3667
+
3668
+ /* --- 3. 診斷資訊 --- */
3669
+ h(
3670
+ 'details',
3671
+ { className: 'ocoa-details' },
3672
+ h('summary', { className: 'ocoa-subhead' }, t('sectionDetails')),
3673
+ h(
3674
+ 'dl',
3675
+ { className: 'ocoa-grid ocoa-grid-tight' },
3676
+ Row({ label: t('detailProvider'), children: status.provider?.id ?? '–' }),
3677
+ Row({ label: t('detailVersion'), children: status.version ?? '–' }),
3678
+ Row({ label: t('detailProbeInterval'), children: intervalLabel(cfg.probeIntervalMs) }),
3679
+ Row({ label: t('detailCatalogPoll'), children: intervalLabel(cfg.catalogPollMs) }),
3680
+ Row({ label: t('detailPixelBudget'), children: cfg.imagePixelBudget ?? '–' }),
3681
+ Row({ label: t('detailMaxBytes'), children: byteLabel(cfg.imageMaxBytes) }),
3682
+ Row({
3683
+ label: t('detailAutoDetect'),
3684
+ children: cfg.autoDetectModels ? t('on') : t('off')
3685
+ }),
3686
+ Row({
3687
+ label: t('detailGenerated'),
3688
+ children: formatWhen(status.generatedAt, localeId) ?? '–'
3689
+ })
3690
+ )
3691
+ )
3692
+ );
3693
+
3694
+ /* ------------------------------------------------------- OpenCode Go 分頁 */
3695
+ const goPane = (() => {
3696
+ const go = status.go ?? {};
3697
+ const goState = go.connectionState || (go.enabled ? 'unconfigured' : 'disabled');
3698
+ const goChipMeta = {
3699
+ disabled: { tone: 'off', label: t('goStateDisabled') },
3700
+ unconfigured: { tone: 'off', label: t('goStateUnconfigured') },
3701
+ checking: { tone: 'warn', label: t('goStateChecking') },
3702
+ connected: { tone: 'ok', label: t('goStateConnected') },
3703
+ 'invalid-key': { tone: 'bad', label: t('goStateInvalidKey') },
3704
+ 'no-entitlement': { tone: 'bad', label: t('goStateNoEntitlement') },
3705
+ 'permission-policy': { tone: 'bad', label: t('goStatePermissionPolicy') },
3706
+ 'rate-limited': { tone: 'warn', label: t('goStateRateLimited') },
3707
+ 'transient-error': { tone: 'warn', label: t('goStateTransient') },
3708
+ 'redirect-blocked': { tone: 'bad', label: t('goStateRedirectBlocked') },
3709
+ 'invalid-response': { tone: 'bad', label: t('goStateInvalidResponse') }
3710
+ }[goState] || { tone: 'off', label: t('goStateDisabled') };
3711
+
3712
+ const goCred = go.credential ?? {};
3713
+ const credRefName = goCred.ref || 'OPENCODE_GO_API_KEY';
3714
+ const canSaveGoCred = goCred.canSave === true;
3715
+ const canClearGoCred = goCred.canClear === true;
3716
+ const hasSavedDshCred = Boolean(goCred.present && goCred.source === 'dsh-credentials');
3717
+
3718
+ const submitGoKeySave = () => {
3719
+ const nextKey = goKeyInput.trim();
3720
+ if (!nextKey || !canSaveGoCred || busy !== '') return;
3721
+ setGoKeyInput('');
3722
+ setGoKeyEditing(false);
3723
+ void act('goCredSave', 'go/credential', { key: nextKey });
3724
+ };
3725
+ const submitGoKeyClear = () => {
3726
+ if (!canClearGoCred || !hasSavedDshCred || busy !== '') return;
3727
+ setGoKeyInput('');
3728
+ setGoKeyEditing(false);
3729
+ void act('goCredClear', 'go/credential/clear', {});
3730
+ };
3731
+
3732
+ const formatReset = (resetsAt) => {
3733
+ if (resetsAt === null || resetsAt === undefined) return null;
3734
+ const ms = typeof resetsAt === 'number' ? resetsAt : Date.parse(resetsAt);
3735
+ if (!Number.isFinite(ms)) return String(resetsAt);
3736
+ return formatWhen(ms, localeId) ?? String(resetsAt);
3737
+ };
3738
+ const formatWin = (label, win) => {
3739
+ if (!win || typeof win.percent !== 'number' || !Number.isFinite(win.percent)) {
3740
+ return `${label}: ${t('goWindowUnavailable')}`;
3741
+ }
3742
+ const parts = [`${label}: ${win.percent}%`];
3743
+ if (typeof win.status === 'string' && win.status.trim()) {
3744
+ parts.push(`(${win.status.trim()})`);
3745
+ }
3746
+ const resetText = formatReset(win.resetsAt);
3747
+ if (resetText) {
3748
+ parts.push(`· ${t('goWindowResetsAt', { when: resetText })}`);
3749
+ }
3750
+ return parts.join(' ');
3751
+ };
3752
+ const windows = go.usage?.windows;
3753
+ const windowLines = windows
3754
+ ? [
3755
+ formatWin(t('goWindowRolling'), windows.rolling),
3756
+ formatWin(t('goWindowWeekly'), windows.weekly),
3757
+ formatWin(t('goWindowMonthly'), windows.monthly)
3758
+ ]
3759
+ : [t('goWindowUnavailable')];
3760
+
3761
+ const previewList = Array.isArray(go.previewModels) ? go.previewModels : [];
3762
+ const isConnectedGo = go.enabled === true && goState === 'connected';
3763
+
3764
+ const mapBackendReason = (code, m) => {
3765
+ switch (code) {
3766
+ case 'inactive-status':
3767
+ return t('goReasonInactiveStatus', { status: m?.status || '?' });
3768
+ case 'missing-type':
3769
+ return t('goReasonMissingType');
3770
+ case 'unsupported-type':
3771
+ return t('goReasonUnsupportedType', { type: m?.type || '?' });
3772
+ case 'missing-limits':
3773
+ return t('goReasonMissingLimits');
3774
+ case 'non-text-modality':
3775
+ return t('goReasonNonTextModality');
3776
+ case 'invalid-model':
3777
+ return t('goReasonInvalidModel');
3778
+ default:
3779
+ return String(code);
3780
+ }
3781
+ };
3782
+
3783
+ const resolveGoModelStatus = (m) => {
3784
+ const rawReasons = Array.isArray(m?.pickerReasons) ? m.pickerReasons : [];
3785
+ const mappedReasons = rawReasons.map((code) => mapBackendReason(code, m));
3786
+ const hasBackendPublish = typeof m?.pickerPublished === 'boolean';
3787
+ const hasBackendEligible = typeof m?.pickerEligible === 'boolean';
3788
+ const eligible = hasBackendEligible ? m.pickerEligible : false;
3789
+ const published = isConnectedGo && (hasBackendPublish ? m.pickerPublished : false);
3790
+
3791
+ if (published) {
3792
+ return { eligible: true, inPicker: true, reasons: [] };
3793
+ }
3794
+ const reasons = [...mappedReasons];
3795
+ if (!isConnectedGo) {
3796
+ reasons.unshift(t('goReasonNotConnected'));
3797
+ } else if (reasons.length === 0) {
3798
+ reasons.push(hasBackendEligible && !eligible ? t('goReasonIneligible') : t('goReasonNotVerified'));
3799
+ }
3800
+ return { eligible: isConnectedGo && eligible, inPicker: false, reasons };
3801
+ };
3802
+
3803
+ const renderGoCatalog = () => {
3804
+ const enriched = previewList.map((m) => ({ model: m, ...resolveGoModelStatus(m) }));
3805
+ const pickerCount = enriched.filter((entry) => entry.inPicker).length;
3806
+ const previewOnlyCount = enriched.length - pickerCount;
3807
+ const goQuery = goSearch.trim().toLowerCase();
3808
+
3809
+ const matchedGo = enriched.filter(({ model: m, inPicker }) => {
3810
+ if (goFilter === 'picker' && !inPicker) return false;
3811
+ if (goFilter === 'preview' && inPicker) return false;
3812
+ if (goQuery) {
3813
+ const hay = `${m.id || ''} ${m.name || ''} ${m.type || ''}`.toLowerCase();
3814
+ if (!hay.includes(goQuery)) return false;
3815
+ }
3816
+ return true;
3817
+ });
3818
+
3819
+ const sortedGo = [...matchedGo].sort((a, b) => {
3820
+ const ea = a.inPicker ? 0 : (a.eligible ? 1 : 2);
3821
+ const eb = b.inPicker ? 0 : (b.eligible ? 1 : 2);
3822
+ return ea - eb;
3823
+ });
3824
+
3825
+ const goVisible = goShowAll ? sortedGo : sortedGo.slice(0, MODELS_COLLAPSED);
3826
+ const goExpandedOutsideWindow = !goShowAll
3827
+ && goExpandedModel !== null
3828
+ && sortedGo.some(({ model: m }) => m.id === goExpandedModel)
3829
+ && !goVisible.some(({ model: m }) => m.id === goExpandedModel);
3830
+ const goRows = goExpandedOutsideWindow ? sortedGo : goVisible;
3831
+
3832
+ const goSeg = (filterValue, label, count, tone) => h(
3833
+ 'button',
3834
+ {
3835
+ type: 'button',
3836
+ key: filterValue,
3837
+ className: `ocoa-seg${goFilter === filterValue ? ' is-active' : ''}${tone ? ` is-${tone}` : ''}`,
3838
+ 'data-go-filter': filterValue,
3839
+ 'aria-pressed': goFilter === filterValue,
3840
+ 'aria-label': `${label} (${count})`,
3841
+ onClick: () => {
3842
+ setGoFilter(filterValue);
3843
+ setGoShowAll(false);
3844
+ }
3845
+ },
3846
+ h('span', { className: 'ocoa-seg-count' }, String(count)),
3847
+ h('span', { className: 'ocoa-seg-label' }, label)
3848
+ );
3849
+
3850
+ const goModelRow = ({ model: m, eligible, inPicker, reasons }) => {
3851
+ const open = goExpandedModel === m.id;
3852
+ const toggleOpen = () => setGoExpandedModel((prev) => (prev === m.id ? null : m.id));
3853
+ const displayLabel = m.name || m.id;
3854
+ const reasonSummary = reasons.join(' · ');
3855
+ const toggleGoShown = (event) => {
3856
+ event.stopPropagation();
3857
+ if (!eligible || busy !== '') return;
3858
+ void act(`go-picker:${m.id}`, 'go/picker', { modelId: m.id, shown: !inPicker });
3859
+ };
3860
+
3861
+ const capLabels = [];
3862
+ if (m.capabilities?.toolCall === true) capLabels.push(t('goCapTools'));
3863
+ if (m.capabilities?.reasoning === true) capLabels.push(t('goCapReasoning'));
3864
+ if (m.capabilities?.attachment === true) capLabels.push(t('goCapAttachment'));
3865
+ const capSummary = capLabels.length > 0 ? capLabels.join(' · ') : '–';
3866
+
3867
+ const pills = [];
3868
+ pills.push(m.type || t('goModelTypeUnknown'));
3869
+ if (Number.isSafeInteger(m.limit?.context)) {
3870
+ pills.push(t('goContextCap', { value: numberLabel(m.limit.context) }));
3871
+ }
3872
+ if (Number.isSafeInteger(m.limit?.output)) {
3873
+ pills.push(t('goOutputCap', { value: numberLabel(m.limit.output) }));
3874
+ }
3875
+ if (m.capabilities?.toolCall === true) pills.push(t('goCapTools'));
3876
+ if (m.capabilities?.reasoning === true) pills.push(t('goCapReasoning'));
3877
+ if (m.capabilities?.attachment === true) pills.push(t('goCapAttachment'));
3878
+ if (Array.isArray(m.modalities?.input) && m.modalities.input.length > 0) {
3879
+ pills.push(t('goModalityInput', { list: m.modalities.input.join(', ') }));
3880
+ }
3881
+
3882
+ const metaParts = [t('goExpandModelId', { id: m.id })];
3883
+ if (m.name && m.name !== m.id) metaParts.push(t('goExpandModelName', { name: m.name }));
3884
+ if (m.ownedBy) metaParts.push(t('goExpandProvider', { owner: m.ownedBy }));
3885
+ if (Number.isSafeInteger(m.limit?.input)) {
3886
+ metaParts.push(t('goExpandInputLimit', { value: numberLabel(m.limit.input) }));
3887
+ }
3888
+ if (Array.isArray(m.modalities?.input) && m.modalities.input.length > 0) {
3889
+ metaParts.push(t('goExpandModalityIn', { list: m.modalities.input.join(', ') }));
3890
+ }
3891
+ if (Array.isArray(m.modalities?.output) && m.modalities.output.length > 0) {
3892
+ metaParts.push(t('goExpandModalityOut', { list: m.modalities.output.join(', ') }));
3893
+ }
3894
+
3895
+ return h(
3896
+ 'tbody',
3897
+ { key: m.id, className: 'ocoa-model-group' },
3898
+ h(
3899
+ 'tr',
3900
+ {
3901
+ key: `${m.id}:row`,
3902
+ className: `ocoa-model-row${open ? ' is-open' : ''}`,
3903
+ onClick: toggleOpen
3904
+ },
3905
+ h(
3906
+ 'td',
3907
+ {
3908
+ className: 'ocoa-col-check',
3909
+ onClick: (event) => event.stopPropagation()
3910
+ },
3911
+ h('input', {
3912
+ type: 'checkbox',
3913
+ className: 'ocoa-checkbox',
3914
+ checked: inPicker,
3915
+ disabled: !eligible || busy !== '',
3916
+ 'aria-label': m.id,
3917
+ title: eligible ? (inPicker ? t('goStatusInPicker') : t('goStatusPreviewOnly')) : reasonSummary,
3918
+ onChange: toggleGoShown
3919
+ })
3920
+ ),
3921
+ h(
3922
+ 'td',
3923
+ { className: 'ocoa-model' },
3924
+ h(
3925
+ 'button',
3926
+ {
3927
+ type: 'button',
3928
+ className: 'ocoa-go-model-btn',
3929
+ 'aria-expanded': open,
3930
+ title: m.name && m.name !== m.id ? `${m.name} (${m.id})` : m.id,
3931
+ onClick: (event) => {
3932
+ event.stopPropagation();
3933
+ toggleOpen();
3934
+ }
3935
+ },
3936
+ h('span', { className: 'ocoa-go-caret', 'aria-hidden': true }, open ? '▾' : '▸'),
3937
+ h('span', { className: open ? 'ocoa-model-toggle' : 'ocoa-model-id' }, displayLabel),
3938
+ !eligible
3939
+ ? h('span', { className: 'ocoa-badge dim', style: { marginLeft: '6px' } }, t('goStatusPreviewOnly'))
3940
+ : null
3941
+ )
3942
+ ),
3943
+ h(
3944
+ 'td',
3945
+ { className: 'ocoa-num' },
3946
+ Number.isSafeInteger(m.limit?.context) ? numberLabel(m.limit.context) : '–'
3947
+ ),
3948
+ h(
3949
+ 'td',
3950
+ { className: 'ocoa-num' },
3951
+ Number.isSafeInteger(m.limit?.output) ? numberLabel(m.limit.output) : '–'
3952
+ )
3953
+ ),
3954
+ open
3955
+ ? h(
3956
+ 'tr',
3957
+ { key: `${m.id}:expand`, className: 'ocoa-model-expand' },
3958
+ h(
3959
+ 'td',
3960
+ { colSpan: 4 },
3961
+ h(
3962
+ 'div',
3963
+ { className: 'ocoa-expand-body' },
3964
+ !inPicker
3965
+ ? h('div', { className: 'ocoa-expand-reason' }, t('goPreviewOnlyNote', { reasons: reasonSummary }))
3966
+ : h('div', { className: 'ocoa-diagnostic-meta' }, t('goPickerEligibleNote')),
3967
+ h(
3968
+ 'div',
3969
+ { className: 'ocoa-diagnostic-meta' },
3970
+ inPicker
3971
+ ? (m.pickerImageSupported === true ? t('goModelSupportImage') : t('goModelSupportTextOnly'))
3972
+ : t('goSupportScopeNote')
3973
+ ),
3974
+ h('div', { className: 'ocoa-diagnostic-meta' }, t('goCatalogMetaLabel', { meta: metaParts.join(' · ') })),
3975
+ h(
3976
+ 'div',
3977
+ { className: 'ocoa-go-meta' },
3978
+ pills.map((p, idx) => h('span', { className: 'ocoa-go-pill', key: `${m.id}-pill-${idx}` }, p))
3979
+ )
3980
+ )
3981
+ )
3982
+ )
3983
+ : null
3984
+ );
3985
+ };
3986
+
3987
+ return h(
3988
+ 'div',
3989
+ { className: 'ocoa-go-catalog' },
3990
+ previewList.length > 0
3991
+ ? [
3992
+ h(
3993
+ 'div',
3994
+ { key: 'go-segments', className: 'ocoa-segments', role: 'group', 'aria-label': t('modelFilters') },
3995
+ goSeg('all', t('goFilterAll'), previewList.length, null),
3996
+ goSeg('picker', t('goFilterPicker'), pickerCount, 'ok'),
3997
+ goSeg('preview', t('goFilterPreview'), previewOnlyCount, null)
3998
+ ),
3999
+ h(
4000
+ 'div',
4001
+ { key: 'go-toolbar', className: 'ocoa-toolbar' },
4002
+ h('input', {
4003
+ className: 'ocoa-input',
4004
+ type: 'search',
4005
+ placeholder: t('searchPlaceholder'),
4006
+ value: goSearch,
4007
+ onChange: (event) => setGoSearch(event.target.value)
4008
+ }),
4009
+ h(
4010
+ 'span',
4011
+ { className: 'ocoa-toolbar-count' },
4012
+ t('filterCount', { shown: sortedGo.length, total: previewList.length })
4013
+ )
4014
+ ),
4015
+ goRows.length > 0
4016
+ ? h(
4017
+ 'div',
4018
+ { key: 'go-table-scroll', className: 'ocoa-go-table-scroll' },
4019
+ h(
4020
+ 'table',
4021
+ { key: 'go-table', className: 'ocoa-table ocoa-go-table' },
4022
+ h(
4023
+ 'thead',
4024
+ null,
4025
+ h(
4026
+ 'tr',
4027
+ null,
4028
+ h('th', { className: 'ocoa-col-check' }, t('colPicker')),
4029
+ h('th', null, t('colModel')),
4030
+ h('th', { className: 'ocoa-num' }, t('colContext')),
4031
+ h('th', { className: 'ocoa-num' }, t('goColOutput'))
4032
+ )
4033
+ ),
4034
+ goRows.map(goModelRow)
4035
+ )
4036
+ )
4037
+ : h('div', { key: 'go-nomatch', className: 'ocoa-note' }, t('goNoMatch')),
4038
+ sortedGo.length > MODELS_COLLAPSED
4039
+ ? h(
4040
+ 'button',
4041
+ {
4042
+ key: 'go-showall',
4043
+ type: 'button',
4044
+ className: 'ocoa-btn ghost',
4045
+ onClick: () => setGoShowAll((v) => !v)
4046
+ },
4047
+ goShowAll
4048
+ ? t('showLess')
4049
+ : t('showRest', { n: sortedGo.length - MODELS_COLLAPSED, total: sortedGo.length })
4050
+ )
4051
+ : null
4052
+ ]
4053
+ : h('div', { className: 'ocoa-note' }, t('goPreviewEmpty'))
4054
+ );
4055
+ };
4056
+
4057
+ const renderUsageCard = (key, label, win) => {
4058
+ const hasPct = Boolean(win && typeof win.percent === 'number' && Number.isFinite(win.percent));
4059
+ const pct = hasPct ? Math.max(0, Math.min(100, win.percent)) : 0;
4060
+ const tone = !hasPct ? 'ok' : (pct >= 90 ? 'bad' : (pct >= 70 ? 'warn' : 'ok'));
4061
+ const resetText = hasPct ? (formatReset(win.resetsAt) || '–') : t('goWindowUnavailable');
4062
+ return h(
4063
+ 'div',
4064
+ { key, className: 'ocoa-go-usage-card' },
4065
+ h(
4066
+ 'div',
4067
+ { className: 'ocoa-go-usage-head' },
4068
+ h('span', null, label),
4069
+ h('span', { className: `ocoa-go-usage-pct is-${tone}` }, hasPct ? `${win.percent}%` : '–')
4070
+ ),
4071
+ h(
4072
+ 'div',
4073
+ { className: 'ocoa-go-usage-bar' },
4074
+ h('div', {
4075
+ className: `ocoa-go-usage-fill is-${tone}`,
4076
+ style: { width: `${hasPct ? Math.max(pct, pct > 0 ? 3 : 0) : 0}%` }
4077
+ })
4078
+ ),
4079
+ h('div', { className: 'ocoa-go-usage-reset', title: resetText }, resetText)
4080
+ );
4081
+ };
4082
+
4083
+ const showKeyDrawer = !hasSavedDshCred || goKeyEditing;
4084
+
4085
+ return h(
4086
+ 'div',
4087
+ { className: 'ocoa-card ocoa-go-section', 'data-go-state': goState },
4088
+ h(
4089
+ 'div',
4090
+ { className: 'ocoa-card-head' },
4091
+ h(
4092
+ 'div',
4093
+ { style: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' } },
4094
+ h('span', { className: 'ocoa-card-title' }, 'OpenCode Go'),
4095
+ h(Chip, { tone: goChipMeta.tone, text: goChipMeta.label }),
4096
+ go.checkedAt
4097
+ ? h('span', { className: 'ocoa-msg', style: { margin: 0 } }, formatWhen(go.checkedAt, localeId) ?? '–')
4098
+ : null
4099
+ ),
4100
+ h(
4101
+ 'div',
4102
+ { className: 'ocoa-actions' },
4103
+ go.enabled && go.picker?.mode === 'manual'
4104
+ ? h(
4105
+ 'button',
4106
+ {
4107
+ type: 'button',
4108
+ className: 'ocoa-btn ghost',
4109
+ disabled: busy !== '',
4110
+ onClick: () => act('go-picker-reset', 'go/picker', { mode: 'auto' })
4111
+ },
4112
+ busy === 'go-picker-reset' ? t('pickerResetBusy') : t('pickerReset')
4113
+ )
4114
+ : null,
4115
+ hasSavedDshCred
4116
+ ? h(
4117
+ 'button',
4118
+ {
4119
+ type: 'button',
4120
+ className: 'ocoa-btn',
4121
+ 'aria-expanded': showKeyDrawer,
4122
+ disabled: busy !== '',
4123
+ onClick: () => {
4124
+ setGoKeyInput('');
4125
+ setGoKeyEditing((v) => !v);
4126
+ }
4127
+ },
4128
+ t('goKeyDrawer')
4129
+ )
4130
+ : null,
4131
+ go.enabled
4132
+ ? h(
4133
+ 'button',
4134
+ {
4135
+ type: 'button',
4136
+ className: 'ocoa-btn',
4137
+ disabled: busy !== '',
4138
+ onClick: () => act('goRefresh', 'go/refresh')
4139
+ },
4140
+ busy === 'goRefresh' ? t('goRefreshing') : t('goRefresh')
4141
+ )
4142
+ : null
4143
+ )
4144
+ ),
4145
+ go.enabled
4146
+ ? (windows
4147
+ ? h(
4148
+ 'div',
4149
+ { className: 'ocoa-go-usage-grid', 'data-go-usage': 'present' },
4150
+ renderUsageCard('rolling', t('goWindowRolling'), windows.rolling),
4151
+ renderUsageCard('weekly', t('goWindowWeekly'), windows.weekly),
4152
+ renderUsageCard('monthly', t('goWindowMonthly'), windows.monthly)
4153
+ )
4154
+ : h('div', { className: 'ocoa-msg', 'data-go-usage': 'absent' }, t('goWindowUnavailable')))
4155
+ : null,
4156
+ go.error?.message
4157
+ ? h('div', { className: 'ocoa-msg bad' }, go.error.message)
4158
+ : null,
4159
+ showKeyDrawer
4160
+ ? h(
4161
+ 'div',
4162
+ { className: 'ocoa-go-cred-box' },
4163
+ h(
4164
+ 'div',
4165
+ { className: 'ocoa-go-cred-head' },
4166
+ h('span', null, t('goKeyFieldLabel', { ref: credRefName })),
4167
+ h(Chip, {
4168
+ tone: hasSavedDshCred ? 'ok' : 'off',
4169
+ text: hasSavedDshCred ? t('goKeyStoredStatus') : t('goKeyUnsetStatus')
4170
+ })
4171
+ ),
4172
+ h(
4173
+ 'div',
4174
+ { className: 'ocoa-go-cred-row' },
4175
+ h('input', {
4176
+ type: 'password',
4177
+ className: 'ocoa-input ocoa-go-cred-input',
4178
+ value: goKeyInput,
4179
+ placeholder: hasSavedDshCred ? t('goKeyStoredPlaceholder') : t('goKeyMissingPlaceholder'),
4180
+ disabled: busy !== '' || !canSaveGoCred,
4181
+ autoComplete: 'off',
4182
+ spellCheck: false,
4183
+ onChange: (event) => setGoKeyInput(event.target.value),
4184
+ onKeyDown: (event) => {
4185
+ if (event.key === 'Enter' && goKeyInput.trim() && canSaveGoCred && busy === '') {
4186
+ event.preventDefault();
4187
+ submitGoKeySave();
4188
+ }
4189
+ },
4190
+ 'aria-label': t('goKeyFieldLabel', { ref: credRefName })
4191
+ }),
4192
+ h(
4193
+ 'button',
4194
+ {
4195
+ type: 'button',
4196
+ className: 'ocoa-btn',
4197
+ disabled: busy !== '' || !canSaveGoCred || !goKeyInput.trim(),
4198
+ onClick: submitGoKeySave
4199
+ },
4200
+ busy === 'goCredSave' ? t('goKeySaving') : t('goKeySave')
4201
+ ),
4202
+ goKeyEditing
4203
+ ? h(
4204
+ 'button',
4205
+ {
4206
+ type: 'button',
4207
+ className: 'ocoa-btn',
4208
+ disabled: busy !== '',
4209
+ onClick: () => {
4210
+ setGoKeyInput('');
4211
+ setGoKeyEditing(false);
4212
+ }
4213
+ },
4214
+ t('goKeyCancel')
4215
+ )
4216
+ : null
4217
+ ),
4218
+ !canSaveGoCred
4219
+ ? h('div', { className: 'ocoa-note' }, t('goKeyWriteUnavailable'))
4220
+ : null,
4221
+ h(
4222
+ 'div',
4223
+ { className: 'ocoa-go-cred-foot' },
4224
+ h(
4225
+ 'div',
4226
+ { className: 'ocoa-go-cred-notes' },
4227
+ h('div', null, t('goApiOnlyNote')),
4228
+ go.enabled ? h('div', null, t('goExtraUsageWarn')) : null
4229
+ ),
4230
+ (hasSavedDshCred || go.enabled)
4231
+ ? h(
4232
+ 'div',
4233
+ { className: 'ocoa-actions' },
4234
+ hasSavedDshCred
4235
+ ? h(
4236
+ 'button',
4237
+ {
4238
+ type: 'button',
4239
+ className: 'ocoa-btn',
4240
+ disabled: busy !== '' || !canClearGoCred,
4241
+ onClick: submitGoKeyClear
4242
+ },
4243
+ busy === 'goCredClear' ? t('goKeyClearing') : t('goKeyClear')
4244
+ )
4245
+ : null,
4246
+ go.enabled
4247
+ ? h(
4248
+ 'button',
4249
+ {
4250
+ type: 'button',
4251
+ className: 'ocoa-btn',
4252
+ disabled: busy !== '' || (previewList.length === 0 && !go.error && !go.checkedAt),
4253
+ onClick: () => act('goClear', 'go/clear')
4254
+ },
4255
+ t('goClear')
4256
+ )
4257
+ : null
4258
+ )
4259
+ : null
4260
+ )
4261
+ )
4262
+ : null,
4263
+ !go.enabled
4264
+ ? h('div', { className: 'ocoa-note' }, t('goDisabledHint'))
4265
+ : null,
4266
+ go.enabled ? renderGoCatalog() : null
4267
+ );
4268
+ })();
4269
+
4270
+ /* ------------------------------------------------------- 分頁 */
4271
+ // 拆成四個頁籤的理由:每個領域各自獨立,互不干擾。
4272
+ // 帳號:登入、換帳號——偶爾才動一次。
4273
+ // 模型:免費通道模型——幾乎每次開這個分頁都是為了它。
4274
+ // 進階:備援與診斷——設定一次就不管了。
4275
+ // OpenCode Go:獨立訂閱憑證、用量視窗與 Go 模型目錄。
4276
+ const TABS = [
4277
+ { id: 'account', label: t('tabAccount'), pane: accountPane },
4278
+ { id: 'models', label: t('tabModels'), pane: modelsPane },
4279
+ { id: 'advanced', label: t('tabAdvanced'), pane: advancedPane },
4280
+ { id: 'go', label: t('tabGo'), pane: goPane }
4281
+ ];
4282
+ const activeTab = TABS.some((tab) => tab.id === tabState) ? tabState : 'models';
4283
+ const currentPane = TABS.find((tab) => tab.id === activeTab)?.pane ?? null;
4284
+
4285
+ const contextModal = contextModalModel
4286
+ ? h(
4287
+ 'div',
4288
+ {
4289
+ className: 'ocoa-modal-backdrop',
4290
+ onClick: (e) => {
4291
+ if (e.target === e.currentTarget && busy !== 'context') closeContextModal();
4292
+ }
4293
+ },
4294
+ h(
4295
+ 'div',
4296
+ { className: 'ocoa-modal-dialog', role: 'dialog', 'aria-modal': true },
4297
+ h(
4298
+ 'div',
4299
+ { className: 'ocoa-modal-header' },
4300
+ h(
4301
+ 'div',
4302
+ null,
4303
+ h('h3', { className: 'ocoa-modal-title' }, t('contextModalTitle')),
4304
+ h('div', { className: 'ocoa-modal-sub' }, t('contextModalSub', { id: contextModalModel.id }))
4305
+ ),
4306
+ h(
4307
+ 'button',
4308
+ {
4309
+ type: 'button',
4310
+ className: 'ocoa-modal-close',
4311
+ title: t('contextCancel'),
4312
+ disabled: busy === 'context',
4313
+ onClick: closeContextModal
4314
+ },
4315
+ '✕'
4316
+ )
4317
+ ),
4318
+ h(
4319
+ 'div',
4320
+ { className: 'ocoa-modal-body' },
4321
+ h(
4322
+ 'div',
4323
+ { className: 'ocoa-modal-info' },
4324
+ h('div', null, t('contextDefaultValue', {
4325
+ value: numberLabel(contextModalModel.catalogContextWindow ?? contextModalModel.contextWindow ?? 200000)
4326
+ })),
4327
+ // 輸出上限也一起顯示:使用者問「最大值是多少」時,問的常常是
4328
+ // 這個而不是上下文。上游目錄有給(`limit.output`),
4329
+ // 但以前只活在 describe() 裡,畫面上看不到。
4330
+ Number.isFinite(contextModalModel.maxOutputTokens)
4331
+ ? h('div', { style: { marginTop: '4px' } }, t('contextMaxOutput', {
4332
+ value: numberLabel(contextModalModel.maxOutputTokens)
4333
+ }))
4334
+ : null,
4335
+ h('div', { style: { marginTop: '4px', opacity: 0.85 } }, t('contextHint'))
4336
+ ),
4337
+ h(
4338
+ 'label',
4339
+ { className: 'ocoa-context-field' },
4340
+ h('span', null, t('contextCustomLabel')),
4341
+ h('input', {
4342
+ className: 'ocoa-input ocoa-context-number',
4343
+ type: 'number',
4344
+ min: 1024,
4345
+ max: 100000000,
4346
+ step: 1,
4347
+ value: contextInputVal,
4348
+ disabled: busy === 'context',
4349
+ autoFocus: true,
4350
+ onChange: (e) => setContextInputVal(e.target.value)
4351
+ })
4352
+ )
4353
+ ),
4354
+ h(
4355
+ 'div',
4356
+ { className: 'ocoa-modal-footer' },
4357
+ h(
4358
+ 'button',
4359
+ {
4360
+ type: 'button',
4361
+ className: 'ocoa-btn ghost',
4362
+ disabled: busy === 'context' || contextModalModel.contextOverride == null,
4363
+ onClick: async () => {
4364
+ await persistContext(contextModalModel, null);
4365
+ closeContextModal();
4366
+ }
4367
+ },
4368
+ t('contextResetToDefault')
4369
+ ),
4370
+ h(
4371
+ 'div',
4372
+ { className: 'ocoa-actions' },
4373
+ h(
4374
+ 'button',
4375
+ {
4376
+ type: 'button',
4377
+ className: 'ocoa-btn ghost',
4378
+ disabled: busy === 'context',
4379
+ onClick: closeContextModal
4380
+ },
4381
+ t('contextCancel')
4382
+ ),
4383
+ h(
4384
+ 'button',
4385
+ {
4386
+ type: 'button',
4387
+ className: 'ocoa-btn primary',
4388
+ disabled: busy === 'context',
4389
+ onClick: async () => {
4390
+ const val = Number(contextInputVal);
4391
+ if (!Number.isSafeInteger(val) || val < 1024 || val > 100000000) {
4392
+ setMessage({ kind: 'error', text: t('contextInvalid') });
4393
+ return;
4394
+ }
4395
+ await persistContext(contextModalModel, val);
4396
+ closeContextModal();
4397
+ }
4398
+ },
4399
+ busy === 'context' ? t('contextSaving') : t('contextSaveBtn')
4400
+ )
4401
+ )
4402
+ )
4403
+ )
4404
+ )
4405
+ : null;
4406
+
4407
+ const removeModal = removeAccountModal
4408
+ ? h(
4409
+ 'div',
4410
+ {
4411
+ className: 'ocoa-modal-backdrop',
4412
+ onClick: (e) => {
4413
+ if (e.target === e.currentTarget && busy !== 'account-remove') setRemoveAccountModal(null);
4414
+ }
4415
+ },
4416
+ h(
4417
+ 'div',
4418
+ { className: 'ocoa-modal-dialog', role: 'dialog', 'aria-modal': true },
4419
+ h(
4420
+ 'div',
4421
+ { className: 'ocoa-modal-header' },
4422
+ h(
4423
+ 'div',
4424
+ null,
4425
+ h('h3', { className: 'ocoa-modal-title' }, t('accountRemove')),
4426
+ h('div', { className: 'ocoa-modal-sub' }, removeAccountModal.label || t('accountNoLabel'))
4427
+ ),
4428
+ h(
4429
+ 'button',
4430
+ {
4431
+ type: 'button',
4432
+ className: 'ocoa-modal-close',
4433
+ title: t('accountCancel'),
4434
+ disabled: busy === 'account-remove',
4435
+ onClick: () => setRemoveAccountModal(null)
4436
+ },
4437
+ '×'
4438
+ )
4439
+ ),
4440
+ h(
4441
+ 'div',
4442
+ { className: 'ocoa-modal-body' },
4443
+ h('p', { className: 'ocoa-msg' }, t('accountRemoveConfirm'))
4444
+ ),
4445
+ h(
4446
+ 'div',
4447
+ { className: 'ocoa-modal-footer' },
4448
+ h(
4449
+ 'button',
4450
+ {
4451
+ type: 'button',
4452
+ className: 'ocoa-btn ghost',
4453
+ disabled: busy === 'account-remove',
4454
+ onClick: () => setRemoveAccountModal(null)
4455
+ },
4456
+ t('accountCancel')
4457
+ ),
4458
+ h(
4459
+ 'button',
4460
+ {
4461
+ type: 'button',
4462
+ className: 'ocoa-btn primary',
4463
+ style: { background: 'var(--ocoa-off, #ec1313)' },
4464
+ disabled: busy === 'account-remove',
4465
+ onClick: async () => {
4466
+ setBusy('account-remove');
4467
+ try {
4468
+ await fetch(`${API}/accounts`, {
4469
+ method: 'DELETE',
4470
+ headers: { 'content-type': 'application/json' },
4471
+ body: JSON.stringify({ id: removeAccountModal.id })
4472
+ });
4473
+ setRemoveAccountModal(null);
4474
+ await load();
4475
+ } finally {
4476
+ setBusy('');
4477
+ }
4478
+ }
4479
+ },
4480
+ busy === 'account-remove' ? '…' : t('accountRemove')
4481
+ )
4482
+ )
4483
+ )
4484
+ )
4485
+ : null;
4486
+
4487
+ return h(
4488
+ 'div',
4489
+ { className: 'ocoa-page' },
4490
+ head,
4491
+ h(
4492
+ 'div',
4493
+ { className: 'ocoa-tabs', role: 'tablist', 'aria-label': t('title') },
4494
+ ...TABS.map((tab) => h(
4495
+ 'button',
4496
+ {
4497
+ key: tab.id,
4498
+ type: 'button',
4499
+ role: 'tab',
4500
+ className: `ocoa-tab${tab.id === activeTab ? ' is-active' : ''}`,
4501
+ 'data-tab': tab.id,
4502
+ 'aria-selected': tab.id === activeTab,
4503
+ onClick: () => setTabState(tab.id)
4504
+ },
4505
+ tab.label,
4506
+ // 模型頁籤帶上可用數,這樣不必切過去也知道有沒有問題。
4507
+ tab.id === 'models' && Number.isFinite(summary.available)
4508
+ ? h('span', { className: 'ocoa-tab-badge' }, String(summary.available))
4509
+ : null
4510
+ ))
4511
+ ),
4512
+ h('div', { className: 'ocoa-pane', role: 'tabpanel' }, currentPane),
4513
+ contextModal,
4514
+ removeModal
4515
+ );
4516
+ }
4517
+
4518
+ /* --------------------------------------------------------------- 註冊 */
4519
+
4520
+ return {
4521
+ // `locale` 必須列入 inject:apply() 要透過它註冊字典,而碰到沒注入的
4522
+ // Cordis 服務會讓外掛啟動失敗,不是回傳 undefined。
4523
+ inject: ['slots', 'locale'],
4524
+ apply(ctx) {
4525
+ installStyle();
4526
+ // style 元素是本外掛擁有的資源,所以它的移除要登記成 effect,
4527
+ // 而不是卸載後留在 DOM 裡。
4528
+ ctx.effect(
4529
+ () => () => {
4530
+ const style = document.getElementById(STYLE_ID);
4531
+ if (style?.parentNode) style.parentNode.removeChild(style);
4532
+ },
4533
+ 'opencode-next: settings style'
4534
+ );
4535
+
4536
+ // DSH 只內建 `zh`(簡體)與 `en` 兩個語言 id,所以繁中字典在宣告之前
4537
+ // 沒有地方可放。addLanguage 會把「繁體中文」加進設定裡的語言清單;
4538
+ // fallback 用 `zh` 而不是 `en` 是刻意的:本外掛還沒翻到的鍵會顯示簡中,
4539
+ // 而不是整頁掉回英文。字典與語言宣告的先後順序不影響結果。
4540
+ //
4541
+ // 兩個呼叫都包了 try:可能已經有別的外掛佔用同一個 id,而這裡一拋錯
4542
+ // 就會讓整個外掛啟動失敗(跟碰到未注入的服務是同一種失敗模式)。
4543
+ for (const [label, setup] of [
4544
+ [
4545
+ 'opencode-next: zh-Hant language',
4546
+ () => ctx.locale?.addLanguage?.({ id: 'zh-Hant', label: '繁體中文', fallback: 'zh' })
4547
+ ],
4548
+ ['opencode-next: dictionaries', () => ctx.locale?.register?.(NS, COPY)]
4549
+ ]) {
4550
+ try {
4551
+ const dispose = setup();
4552
+ if (typeof dispose === 'function') ctx.effect(() => dispose, label);
4553
+ } catch (error) {
4554
+ console.warn(`opencode-next: ${label} skipped —`, error);
4555
+ }
4556
+ }
4557
+
4558
+ /* 側邊欄標籤與頁面語言的關係
4559
+
4560
+ 分頁由宿主自己負責,它的語言是宿主全域語言(DSH 只有 zh/en),
4561
+ 本外掛沒辦法只改那一行而不動整個 DSH。所以這裡刻意**不**傳 `t`
4562
+ 給頁面:頁面內容完全走自己的語言狀態(可在分頁內切換),而側邊欄
4563
+ 那一行則跟隨宿主。這樣「切換本分頁語言」不會影響 DSH 其他部分,
4564
+ 代價是側邊欄標籤可能與頁面內容語言不同——這是刻意的取捨。
4565
+
4566
+ 標籤文字用固定的外掛名稱:它本來就是品牌名,不是需要翻譯的文案,
4567
+ 這樣無論宿主語言是什麼,那一行都是可預期的。 */
4568
+ const navLabel = 'OpenCode-Next';
4569
+
4570
+ ctx.slots.inject('settings.section', () =>
4571
+ ctx.slots.register(
4572
+ {
4573
+ name: 'settings.section',
4574
+ id: 'opencode-next',
4575
+ // 14 是空著的(12 = antigravity、13 = agy-next、15 之後另有其人)。
4576
+ order: 14,
4577
+ label: () => navLabel,
4578
+ locale: NS
4579
+ },
4580
+ // 只傳 ctx;語言由 SettingsPage 自己解析。
4581
+ (props) => h(SettingsPage, { ctx, ...props })
4582
+ )
4583
+ );
4584
+ }
4585
+ };
4586
+ }
4587
+ });