dsh-codearts-dock 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +172 -2
  4. package/SECURITY.md +47 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3519 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +25 -0
  9. package/docs/DETAIL.zh.md +25 -0
  10. package/docs/PUBLISHING.md +43 -0
  11. package/docs/preview.svg +78 -0
  12. package/icons/dsh-connect-codearts-128.png +0 -0
  13. package/icons/dsh-connect-codearts-256.png +0 -0
  14. package/locale/en.json +7 -0
  15. package/locale/zh.json +7 -0
  16. package/package.json +88 -4
  17. package/scripts/build-market-index.mjs +24 -0
  18. package/scripts/check-legal.sh +33 -0
  19. package/scripts/check-release.mjs +29 -0
  20. package/scripts/test.mjs +11 -0
  21. package/src/account.js +217 -0
  22. package/src/accounts.js +481 -0
  23. package/src/adapter.js +742 -0
  24. package/src/backup.js +89 -0
  25. package/src/catalog.js +269 -0
  26. package/src/checkin.js +271 -0
  27. package/src/credentials.js +435 -0
  28. package/src/features.js +79 -0
  29. package/src/gateway.js +521 -0
  30. package/src/health.js +18 -0
  31. package/src/index.js +1108 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +90 -0
  35. package/src/protocol/crypto.js +160 -0
  36. package/src/protocol/sign.js +176 -0
  37. package/src/protocol/sm4.js +264 -0
  38. package/src/protocol/sse.js +134 -0
  39. package/src/sts.js +118 -0
  40. package/src/usage.js +55 -0
  41. package/test/accounts.test.mjs +322 -0
  42. package/test/adapter.test.mjs +234 -0
  43. package/test/assembler.test.mjs +86 -0
  44. package/test/features.test.mjs +257 -0
  45. package/test/live-probe.mjs +55 -0
  46. package/test/protocol.test.mjs +167 -0
  47. package/test/registration.test.mjs +301 -0
  48. package/test/sm4.test.mjs +64 -0
  49. package/test/ui.test.mjs +370 -0
  50. package/test/visual.test.mjs +438 -0
package/client.js ADDED
@@ -0,0 +1,3519 @@
1
+ /**
2
+ * Browser half of the 码道 connector.
3
+ *
4
+ * Two surfaces, both inside slots the Host already allocates:
5
+ *
6
+ * • a settings page (`settings.section`) for credentials, the model
7
+ * catalog, and diagnostics;
8
+ * • a credit chip beside the composer (`conversation.composer.dock`) that
9
+ * stays out of the way unless a 码道 model is selected.
10
+ *
11
+ * The Host half does all gateway work; this file only reads the small JSON
12
+ * routes under `/plugins/dsh-connect-codearts/`. Nothing here touches
13
+ * credentials beyond posting them once.
14
+ *
15
+ * Written as a plain-JS module for the Client module table: React comes from
16
+ * the browser module table, no bundler and no duplicate React install.
17
+ */
18
+
19
+ window.__ModuleLoader__.load({
20
+ id: 'dsh-codearts-dock',
21
+ factory(require) {
22
+ const module = { exports: {} }
23
+ const exports = module.exports
24
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' })
25
+
26
+ const React = require('react')
27
+
28
+ const h = React.createElement
29
+ const { useState, useEffect, useCallback, useRef } = React
30
+
31
+ /** Route root served by the plugin's Host half. */
32
+ const ROUTE = '/plugins/dsh-connect-codearts'
33
+
34
+ /** Provider route this plugin owns; the chip only shows for these models. */
35
+ const PROVIDER_ID = 'codearts'
36
+
37
+ /**
38
+ * The settings-nav glyph.
39
+ *
40
+ * Embedded as a data URL rather than fetched from the package's icon file:
41
+ * a Client module cannot import assets, and fetching at paint time would
42
+ * leave the nav row blank until the request resolved. 64px covers 2x/3x
43
+ * displays; the 128px source would add 26 KB for detail nobody can see at
44
+ * a 16px edge.
45
+ */
46
+ const NAV_ICON = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAhdUlEQVR42l2aeZxcV3Xnzzn3bbV1VXf13upF6m5trcWWtRjjTdgWtsEmhhAGh8SEkAyBEMgwmSWQTCAZ+GRnkhD4AMnABA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I0izhEirkRhC0qG1nN6FFtIhIItyyliIQWbwFzUjAIiABpNthARgBENAUHQkYmtZNrihaQJgq/TsNLiYNcl18zTTT1whGW0dlwQkEAhEBCLAAsrpEgT0CxUEctIIE0T1xFlQoowiJZcKdKi0QTjmngEgTAyRai3NDEsWWdE5d+n2nXW8TomjU0Se/1TaW5OM8s2gV5QIgwi0AIwI9QKQSlUQE3CNGKkKSKUERFI1p8EsJn5qYXdCmALLEMSMpCQcB3/aAYRvCG1NW0QaFGb1wHbN+p+3VQERS1IXkQAmVqHkgiEgAqVodT1CI4YNkBEFYFtEReP0cqay4b/D2MSdw2tNvuhAAAAAElFTkSuQmCC'
47
+
48
+ /** Localisation text, with an English fallback per key. */
49
+ const balanceDismissals = new Map()
50
+
51
+ const STRINGS = {
52
+ 'health.updateHint': ['更新「{name}」:填写同一个 AK 和新的 SK,将更新已有账号。', 'Update {name}: enter the same AK and the new SK to update the existing account.'],
53
+ "features.saved": ["已保存", "Saved"],
54
+ "features.refresh": ["刷新", "Refresh"],
55
+ "reminder.title": ["余额提醒", "Balance alerts"],
56
+ "reminder.enabled": ["启用低余额提醒", "Enable low-balance alerts"],
57
+ "reminder.threshold": ["提醒阈值(积分)", "Alert threshold (credits)"],
58
+ "reminder.hint": ["低于阈值时积分胶囊变色。可用备用账号会在面板中列出,提醒可暂时忽略。", "The credit chip changes color below this threshold. Available backup accounts appear in the panel; alerts can be dismissed."],
59
+ "reminder.low": ["当前账号余额偏低", "The current account has a low balance"],
60
+ "reminder.backups": ["可用备用账号:{count} 个", "Available backup accounts: {count}"],
61
+ "reminder.dismiss": ["暂时忽略", "Dismiss for now"],
62
+ "health.available": ["可用", "Available"],
63
+ "health.insufficient": ["余额不足", "Insufficient credits"],
64
+ "health.credentials": ["凭证失效或权限不足", "Invalid credentials or permissions"],
65
+ "health.rate_limited": ["被限流", "Rate limited"],
66
+ "health.network": ["网络异常", "Network error"],
67
+ "health.gateway": ["上游异常", "Gateway error"],
68
+ "health.unknown": ["状态未确认", "Status unknown"],
69
+ "health.checked": ["最近检查", "Last checked"],
70
+ "health.recheck": ["重新检查", "Recheck"],
71
+ "health.update": ["更新凭证", "Update credentials"],
72
+ "health.switch": ["可切换备用账号", "Switch to a backup account"],
73
+ "models.imagesOnly": ["支持图片", "Image input"],
74
+ "models.reasoningOnly": ["支持推理", "Reasoning"],
75
+ "presets.title": ["模型配置预设", "Model presets"],
76
+ "presets.choose": ["选择预设…", "Choose a preset…"],
77
+ "presets.daily": ["日常低倍率", "Everyday / lower multiplier"],
78
+ "presets.deep": ["深度推理", "Deep reasoning"],
79
+ "presets.images": ["图片任务", "Image tasks"],
80
+ "presets.preview": ["预览配置", "Preview configuration"],
81
+ "presets.previewHint": ["预览:将启用 {count} 个模型。应用后仍需点击保存。", "Preview: {count} models will be enabled. Save after applying."],
82
+ "presets.apply": ["应用到草稿", "Apply to draft"],
83
+ "presets.applied": ["预设已应用到草稿,请确认后保存。", "Preset applied to draft. Review and save."],
84
+ "presets.name": ["预设名称", "Preset name"],
85
+ "presets.save": ["保存当前草稿为预设", "Save current draft as preset"],
86
+ "presets.delete": ["删除预设", "Delete preset"],
87
+ "presets.deleteConfirm": ["删除这个模型预设?当前模型配置不会改变。", "Delete this preset? Current model settings will remain."],
88
+ "presets.noModels": ["这套预设没有可用模型", "No available models for this preset"],
89
+ "presets.missing": ["部分模型已不在当前目录中,应用时只保留可用模型。", "Some models are no longer in the catalog; only available models will be applied."],
90
+ "backup.title": ["配置备份与迁移", "Configuration backup and migration"],
91
+ "backup.hint": ["包含模型选择、能力开关、推理强度、预设和提醒偏好。账号凭证可选,勾选后必须设置密码加密。", "Includes model selection, capabilities, reasoning, presets and alert preferences. Credentials are optional and require password encryption."],
92
+ "backup.export": ["导出配置", "Export configuration"],
93
+ "backup.include": ["包含账号凭证(AK/SK)", "Include account credentials (AK/SK)"],
94
+ "backup.exportPassword": ["加密密码(不含凭证时可留空)", "Encryption password (optional without credentials)"],
95
+ "backup.confirmPassword": ["确认加密密码", "Confirm encryption password"],
96
+ "backup.passwordHint": ["密码至少 8 位,两次输入需一致。请妥善保存密码。", "Use at least 8 characters and matching passwords. Keep the password safe."],
97
+ "backup.download": ["下载备份", "Download backup"],
98
+ "backup.exported": ["备份已生成并开始下载。", "Backup generated; download started."],
99
+ "backup.restore": ["恢复配置", "Restore configuration"],
100
+ "backup.choose": ["选择备份文件", "Choose backup file"],
101
+ "backup.content": ["备份内容(也可粘贴 JSON)", "Backup contents (or paste JSON)"],
102
+ "backup.importPassword": ["解密密码(未加密文件可留空)", "Decryption password (blank for unencrypted files)"],
103
+ "backup.preview": ["读取并预览", "Read and preview"],
104
+ "backup.summary": ["将更新 {settings} 项配置,新增 {added} 个账号,更新 {updated} 个账号。", "Updates {settings} settings, adds {added} accounts and updates {updated} accounts."],
105
+ "backup.mergeHint": ["配置将以备份为准;账号按 AK 合并,不移除现有账号。自动签到开关也会随配置恢复。", "Settings follow the backup; accounts merge by AK without removing existing accounts. The auto-check-in preference is restored too."],
106
+ "backup.changes": ["查看将恢复的配置", "View settings to restore"],
107
+ "backup.confirm": ["确认恢复", "Confirm restore"],
108
+ "backup.restored": ["配置已恢复,新增 {added} 个账号,更新 {updated} 个账号。", "Restored; {added} accounts added and {updated} updated."],
109
+ "backup.failed": ["备份操作失败", "Backup operation failed"],
110
+ "backup.tooLarge": ["备份文件过大(最大 768 KB)", "Backup is too large (maximum 768 KB)"],
111
+ "tab.usage": ["用量", "Usage"],
112
+ "usage.title": ["本机用量记录", "Local usage history"],
113
+ "usage.enabled": ["记录最近 200 次请求", "Record the latest 200 requests"],
114
+ "usage.hint": ["仅保存在本机:模型、时间、耗时、Token 和结果。不记录对话、工具参数或凭证;关闭后停止记录,历史可清空。每次重试单独计数;不估算积分账单。", "Stored locally: model, time, duration, tokens and result. No conversations, tool arguments or credentials. Disable to stop recording or clear history. Retries count separately; credit charges are not estimated."],
115
+ "usage.clear": ["清空记录", "Clear history"],
116
+ "usage.clearConfirm": ["清空本机用量记录?此操作无法撤销。", "Clear local usage history? This cannot be undone."],
117
+ "usage.cleared": ["用量记录已清空", "Usage history cleared"],
118
+ "usage.today": ["今日请求(已保留记录)", "Today (retained records)"],
119
+ "usage.successRate": ["今日成功率(不含取消)", "Today’s success rate (excluding cancellations)"],
120
+ "usage.tokens": ["今日已上报 Token", "Today’s reported tokens"],
121
+ "usage.search": ["按模型搜索记录", "Search records by model"],
122
+ "usage.result": ["结果", "Result"],
123
+ "usage.all": ["全部结果", "All results"],
124
+ "usage.success": ["成功", "Success"],
125
+ "usage.error": ["失败", "Failed"],
126
+ "usage.aborted": ["已取消", "Cancelled"],
127
+ "usage.time": ["时间", "Time"],
128
+ "usage.model": ["模型", "Model"],
129
+ "usage.duration": ["耗时", "Duration"],
130
+ "usage.input": ["输入 Token", "Input tokens"],
131
+ "usage.output": ["输出 Token", "Output tokens"],
132
+ "usage.empty": ["暂无符合条件的记录", "No matching records"],
133
+
134
+ 'meta.title': ['码道连接器', 'CodeArts connector'],
135
+ 'meta.description': [
136
+ '把华为云码道(CodeArts Agent)的模型接入 DSH:原生适配器直连网关,带凭证管理、模型目录与只读积分概览。',
137
+ 'Connects Huawei Cloud CodeArts models to DSH through a native adapter, with credential management, a model catalog, and a read-only credit overview.',
138
+ ],
139
+ 'common.more': ['更多操作', 'More actions'],
140
+ 'pool.current': ['使用中', 'In use'],
141
+ 'pool.allSigned': ['今日全部已签', 'All checked in today'],
142
+ 'pool.manage': ['凭证管理', 'Credential management'],
143
+ 'pool.showSecret': ['显示', 'Show'],
144
+ 'pool.hideSecret': ['隐藏', 'Hide'],
145
+ 'models.search': ['搜索模型名称或 ID', 'Search model name or ID'],
146
+ 'models.all': ['全部', 'All'],
147
+ 'models.enabledOnly': ['已启用', 'Enabled'],
148
+ 'models.selectedCount': ['已启用 {enabled} / {total} 个', '{enabled} of {total} enabled'],
149
+ 'models.sort': ['模型排序', 'Sort models'],
150
+ 'models.sortDefault': ['默认顺序', 'Default order'],
151
+ 'models.sortRatio': ['倍率从低到高', 'Multiplier: low to high'],
152
+ 'models.sortName': ['名称排序', 'Name'],
153
+ 'models.noMatches': ['没有符合条件的模型', 'No matching models'],
154
+ 'models.clearFilters': ['清除筛选', 'Clear filters'],
155
+ 'models.about': ['目录说明与使用帮助', 'About the catalog'],
156
+ 'models.clean': ['所有修改已保存', 'All changes saved'],
157
+ 'models.unsaved': ['有未保存的修改', 'Unsaved changes'],
158
+ 'models.needOne': ['请至少启用一个模型后保存', 'Enable at least one model to save'],
159
+ 'diag.details': ['技术详情', 'Technical details'],
160
+ 'diag.copy': ['复制脱敏诊断信息', 'Copy redacted diagnostics'],
161
+ 'diag.copied': ['已复制脱敏诊断信息', 'Redacted diagnostics copied'],
162
+ 'diag.copyFailed': ['无法自动复制,请从下方手动复制。', 'Could not copy automatically. Copy the report below.'],
163
+ 'diag.configured': ['凭证已配置', 'Credentials configured'],
164
+ 'diag.notConfigured': ['尚未配置凭证', 'Credentials not configured'],
165
+ 'diag.credentialIssue': ['凭证需要检查', 'Check credentials'],
166
+ 'diag.catalogIssue': ['模型目录需要检查', 'Check catalog'],
167
+ 'diag.catalogSynced': ['模型目录已同步', 'Catalog synced'],
168
+ 'diag.catalogFallback': ['正在使用兜底目录', 'Using fallback catalog'],
169
+ 'diag.catalogCached': ['正在使用缓存目录', 'Using cached catalog'],
170
+ 'diag.errors': ['最近错误', 'Recent errors'],
171
+ 'diag.noErrors': ['暂无错误记录', 'No errors reported'],
172
+ 'nav.label': ['码道', 'CodeArts'],
173
+ 'tab.account': ['账号', 'Accounts'],
174
+ 'tab.models': ['模型', 'Models'],
175
+ 'tab.diagnostics': ['诊断', 'Diagnostics'],
176
+
177
+ 'account.title': ['华为云凭证', 'Huawei Cloud credentials'],
178
+ 'account.hint': [
179
+ '填一次永久 AK/SK 即可长期使用:插件会自动换 STS 临时令牌并在到期前续期,不需要你手动维护。不填也行——装过并登录过码道客户端的话,插件会借用它的登录态。',
180
+ 'One permanent AK/SK pair is enough: the plugin exchanges it for STS and renews before expiry. Leaving it empty also works when the CodeArts client is installed and signed in on this machine.',
181
+ ],
182
+ 'account.ak': ['Access Key ID', 'Access Key ID'],
183
+ 'account.sk': ['Secret Access Key', 'Secret Access Key'],
184
+ 'account.placeholdersuffix': ['(要改就整对重填)', ' (re-enter the whole pair to change)'],
185
+ 'account.placeholderAk': ['粘贴 Access Key ID', 'Paste the Access Key ID'],
186
+ 'account.placeholderSk': ['粘贴 Secret Access Key', 'Paste the Secret Access Key'],
187
+ 'account.save': ['保存', 'Save'],
188
+ 'account.saving': ['保存中…', 'Saving…'],
189
+ 'account.saved': ['已保存并立即生效', 'Saved and in effect'],
190
+ 'account.saveFail': ['保存失败', 'Save failed'],
191
+ 'account.clear': ['清除已保存的凭证', 'Clear saved credentials'],
192
+ 'account.clearConfirm': [
193
+ '清除后插件会立刻改用其它凭证来源(环境变量或码道登录态)。确定清除?',
194
+ 'After clearing, the plugin falls back to other credential sources. Clear anyway?',
195
+ ],
196
+ 'account.cleared': ['已清除保存的凭证', 'Saved credentials cleared'],
197
+ 'account.clearFail': ['清除失败', 'Clear failed'],
198
+ 'account.test': ['测试连接', 'Test connection'],
199
+ 'account.testing': ['测试中…', 'Testing…'],
200
+ 'account.refreshing': ['刷新中…', 'Refreshing…'],
201
+ 'account.refresh': ['刷新目录与积分', 'Refresh catalog and credit'],
202
+ 'account.needBoth': ['Access Key ID 和 Secret Access Key 都要填。', 'Both fields are required.'],
203
+ 'account.whereToGet': ['怎么拿到 AK/SK', 'Where to get an AK/SK'],
204
+ 'account.whereToGetBody': [
205
+ '华为云控制台 → 右上角账号名 → 我的凭证 → 访问密钥 → 新增访问密钥。下载的 credentials.csv 里 Access Key Id 和 Secret Access Key 对应上面两栏(Secret 只在创建时显示一次)。不需要填 STS。',
206
+ 'Huawei Cloud console → account menu → My credentials → Access keys → Add access key. The downloaded credentials.csv holds the Access Key Id and Secret Access Key (the secret is shown once). No STS value is needed.',
207
+ ],
208
+ 'account.sourceTitle': ['当前生效的凭证来源', 'Credential source in effect'],
209
+ 'account.sourceNone': ['尚未解析到可用凭证', 'No usable credential resolved yet'],
210
+ 'account.temporary': [
211
+ '正在使用从码道登录态借来的临时凭证,几小时后会失效。失效后打开一次码道客户端让它刷新即可恢复;填上永久 AK/SK 可以免去这一步。',
212
+ 'Running on a temporary credential borrowed from the CodeArts client. It expires in a few hours; opening the client refreshes it. A permanent AK/SK removes this step.',
213
+ ],
214
+ 'account.identity': ['账号', 'Account'],
215
+ 'account.credit': ['积分', 'Credits'],
216
+ 'account.creditBalance': ['剩余 {remain} / 共 {total}', '{remain} of {total} remaining'],
217
+ 'account.creditUnread': ['读不到积分(不影响对话)', 'Credits unreadable (chatting still works)'],
218
+ 'account.roles': ['企业角色', 'Enterprise roles'],
219
+
220
+ 'models.title': ['模型目录', 'Model catalog'],
221
+ 'models.pickerHint': [
222
+ '这些模型会出现在输入框的模型选择器里,分组名是「码道 CodeArts」。若选择器里看不到,先确认本页目录不是「兜底清单」——兜底清单只在连不上网关时使用。',
223
+ 'These models appear in the composer model picker under the group 码道 CodeArts. If the picker does not show them, check this page is not on the fallback list — the fallback is only used when the gateway cannot be reached.',
224
+ ],
225
+ 'models.hint': [
226
+ '目录每次刷新都从网关重新读取,上游上新或调价会自动跟上;下面看到的倍率就是上游此刻给出的。',
227
+ 'The catalog is re-read from the gateway on every refresh, so new models and price changes follow automatically. The multiplier shown is the one upstream reports right now.',
228
+ ],
229
+ 'models.refresh': ['重读模型目录', 'Reload catalog'],
230
+ 'models.source': ['来源', 'Source'],
231
+ 'models.sourceGateway': ['上游网关', 'Upstream gateway'],
232
+ 'models.sourceCache': ['本地缓存', 'Local cache'],
233
+ 'models.sourceFallback': ['兜底清单(未连上网关)', 'Fallback list (gateway unreachable)'],
234
+ 'models.refreshedAt': ['上次刷新', 'Last refreshed'],
235
+ 'models.refreshed': ['已从上游重读模型目录', 'Catalog re-read from upstream'],
236
+ 'models.saved': ['已保存,模型选择器已更新', 'Saved; the model picker has been updated'],
237
+ 'models.savedReloadFailed': ['已保存,暂时无法重读模型目录。', 'Saved, but the catalog could not be reloaded.'],
238
+ 'models.save': ['保存', 'Save'],
239
+ 'models.discard': ['放弃修改', 'Discard'],
240
+ 'models.saveFailed': ['保存失败', 'Save failed'],
241
+ 'models.dirty': ['未保存', 'unsaved'],
242
+ 'models.images': ['图片', 'Image'],
243
+ 'models.allowOff': ['可关闭思考', 'Can disable'],
244
+ 'models.effort': ['默认推理强度', 'Default reasoning'],
245
+ 'models.footnote': [
246
+ '只列上游接口明确公布的模型能力;勾选的模型才会出现在模型选择器里。',
247
+ 'Only capabilities the upstream interface publishes are shown; a model appears in the picker only while it is ticked.',
248
+ ],
249
+ 'models.empty': [
250
+ '上游没有返回任何模型。先确认凭证可用,再重读目录。',
251
+ 'Upstream returned no models. Check the credential, then reload the catalog.',
252
+ ],
253
+ 'models.refreshFailed': ['刷新失败', 'Refresh failed'],
254
+ 'models.count': ['个数', 'Count'],
255
+ 'models.colContext': ['上下文', 'Context'],
256
+ 'models.colOutput': ['输出上限', 'Output cap'],
257
+
258
+ 'diag.title': ['诊断', 'Diagnostics'],
259
+ 'diag.provider': ['Provider 路由', 'Provider route'],
260
+ 'diag.gateway': ['网关', 'Gateway'],
261
+ 'diag.credentialPath': ['凭证文件', 'Credential file'],
262
+ 'diag.catalogError': ['目录错误', 'Catalog error'],
263
+ 'diag.credentialError': ['凭证错误', 'Credential error'],
264
+ 'diag.reportTitle': ['脱敏诊断 JSON', 'Redacted diagnostics JSON'],
265
+ 'diag.reportHint': [
266
+ '仅包含状态、来源类型和数量等诊断字段。',
267
+ 'Includes diagnostic fields such as status, source type, and counts.',
268
+ ],
269
+ 'diag.none': ['(无)', '(none)'],
270
+ 'diag.configSchema': ['Config schema(模型页显示卡片的前提)', 'Config schema (required for the model card)'],
271
+ 'diag.schemaMissing': ['缺失(模型页不会显示本插件的卡片)', 'missing (the model page will not show this provider)'],
272
+ 'diag.gatewayDefault': ['默认(cn-north-4)', 'Default (cn-north-4)'],
273
+
274
+ 'common.loading': ['加载中…', 'Loading…'],
275
+ 'common.retry': ['重试', 'Retry'],
276
+ 'common.retryHint': [
277
+ '读不到宿主的这条路由,可能插件刚装好还没挂上。',
278
+ 'Could not reach this plugin\'s Host route; it may not be mounted yet.',
279
+ ],
280
+ 'pool.title': ['账号池', 'Accounts'],
281
+ 'pool.tagline': [
282
+ '每个账号独立计费与签到;请求只用「当前」那一个。',
283
+ 'Each account bills and checks in on its own; requests use only the current one.',
284
+ ],
285
+ 'pool.inUse': ['当前使用:', 'In use: '],
286
+ 'pool.expiring': ['{amount} 积分即将到期', '{amount} credits expiring'],
287
+ 'pool.expiringHint': [
288
+ '上游会报告有多少积分将要过期,但不下发具体到期时间,所以这里只显示金额。',
289
+ 'The upstream reports how many credits are expiring but never when, so only the amount is shown.',
290
+ ],
291
+ 'pool.colAccount': ['账号', 'Account'],
292
+ 'pool.colCredits': ['积分', 'Credits'],
293
+ 'pool.colCheckin': ['签到', 'Check-in'],
294
+ 'pool.current': ['当前', 'Current'],
295
+ 'pool.rename': ['账号备注', 'Account name'],
296
+ 'pool.renameHint': ['点一下改备注,方便认出是哪个账号', 'Click to rename, so you can tell accounts apart'],
297
+ 'pool.renamePlaceholder': ['例如:个人 / 公司', 'e.g. personal / work'],
298
+ 'pool.renameFailed': ['改备注失败', 'Rename failed'],
299
+ 'pool.use': ['切换', 'Use'],
300
+ 'pool.remove': ['移除', 'Remove'],
301
+ 'pool.removeConfirm': [
302
+ '移除这个账号?它保存的 AK/SK 会从本机删除。',
303
+ 'Remove this account? Its saved AK/SK is deleted from this machine.',
304
+ ],
305
+ 'pool.empty': [
306
+ '还没有账号。在下面填一对 AK/SK,或者从华为云导出的 credentials.csv 导入。',
307
+ 'No accounts yet. Add an AK/SK pair below, or import the credentials.csv exported from the Huawei Cloud console.',
308
+ ],
309
+ 'pool.addTitle': ['添加账号', 'Add an account'],
310
+ 'pool.addLabel': ['名称(可选)', 'Name (optional)'],
311
+ 'pool.addLabelPlaceholder': ['例如:个人 / 公司', 'e.g. personal / work'],
312
+ 'pool.add': ['添加', 'Add'],
313
+ 'pool.importTitle': ['导入', 'Import'],
314
+ 'pool.importHint': [
315
+ '粘贴华为云 console 下载的 credentials.csv 内容、每行一对 AK,SK、或本插件导出的 JSON。',
316
+ 'Paste the contents of a credentials.csv from the Huawei Cloud console, one AK,SK pair per line, or JSON exported by this plugin.',
317
+ ],
318
+ 'pool.importPlaceholder': ['AK,SK(每行一对)', 'AK,SK (one pair per line)'],
319
+ 'pool.import': ['导入', 'Import'],
320
+ 'pool.importResult': [
321
+ '导入完成:新增 {added},更新 {updated},跳过 {skipped}',
322
+ 'Imported: {added} added, {updated} updated, {skipped} skipped',
323
+ ],
324
+ 'pool.importEmpty': ['没有认出任何 AK/SK 对。', 'No AK/SK pair recognised.'],
325
+ 'pool.export': ['导出', 'Export'],
326
+ 'pool.exportHint': [
327
+ '导出的内容含明文密钥,只贴到你自己信任的地方。',
328
+ 'The export contains plain-text keys — only paste it somewhere you trust.',
329
+ ],
330
+ 'pool.exported': ['已导出文件 {name}', 'Saved {name}'],
331
+ 'pool.importHint': [
332
+ '选一个华为云 credentials.csv、每行 AK,SK 的文本、或本插件导出的 JSON。选完会先显示预览,确认后再写入。',
333
+ 'Pick a Huawei Cloud credentials.csv, a text file with one AK,SK per line, or JSON exported by this plugin. You see a preview before anything is written.',
334
+ ],
335
+ 'pool.checkinPending': ['待签', 'Due'],
336
+ 'pool.added': ['已添加账号', 'Account added'],
337
+ 'pool.updated': ['已更新该账号的密钥', 'That account was updated'],
338
+ 'pool.importing': ['导入中…', 'Importing…'],
339
+ 'pool.previewTotal': ['这个文件里有 {total} 个账号,确认后写入:', 'This file holds {total} accounts; confirm to write them:'],
340
+ 'pool.importConfirm': ['导入 {count} 个', 'Import {count}'],
341
+ 'pool.cancel': ['取消', 'Cancel'],
342
+ 'pool.exportFailed': ['导出失败', 'Export failed'],
343
+ 'pool.importShow': ['批量导入', 'Bulk import'],
344
+ 'pool.importHide': ['收起批量导入', 'Hide bulk import'],
345
+ 'pool.checkinClaim': ['签到', 'Check in'],
346
+ 'pool.checkinDone': ['今日已签', 'Checked in'],
347
+ 'pool.checkinUnavailable': ['不可领取', 'Unavailable'],
348
+ 'pool.checkinNone': ['无活动', 'No campaign'],
349
+ 'pool.autoTitle': ['每日自动签到', 'Daily auto check-in'],
350
+ 'pool.checkinAll': ['一键签到', 'Check in now'],
351
+ 'pool.checkinAllHint': ['立刻为所有可签到的账号领取一次(不改变上面的每日开关)', 'Claim once for every account that can right now (the daily switch above is left as it is)'],
352
+ 'pool.checkinClaiming': ['签到中…', 'Claiming…'],
353
+ 'pool.checkinNoneToday': ['今天已没有可领取的签到', 'Nothing left to claim today'],
354
+ 'pool.checkinResult': ['{claimed} 个账号已签到,{failed} 个失败', '{claimed} claimed, {failed} failed'],
355
+ 'pool.checkinFailed': ['签到失败', 'Check-in failed'],
356
+ 'pool.autoToday': ['今天 {done}/{total}', '{done}/{total} today'],
357
+ 'pool.autoRun': ['立刻签到一次', 'Check in now'],
358
+ 'pool.autoRunning': ['签到中…', 'Checking in…'],
359
+ 'pool.autoOff': ['已关闭', 'Off'],
360
+ 'pool.result': ['{claimed} 个账号签到了,{failed} 个失败', '{claimed} checked in, {failed} failed'],
361
+ 'chip.loading': ['读取中…', 'Reading…'],
362
+ 'chip.credits': ['积分', 'credits'],
363
+ 'chip.panelTitle': ['码道账号与积分', 'CodeArts accounts and credits'],
364
+ 'chip.refreshHint': ['重新读取所有账号的积分', 'Re-read every account\'s credits'],
365
+ 'chip.settings': ['设置', 'Settings'],
366
+ 'chip.switchTo': ['切换到 {account}', 'Switch to {account}'],
367
+ 'chip.current': ['当前选用', 'In use'],
368
+ 'chip.refresh': ['刷新', 'Refresh'],
369
+ 'chip.noCredential': ['未配置凭证', 'No credentials'],
370
+ 'chip.noCredentialHint': [
371
+ '还没有可用的码道凭证。到「设置 → 码道」填 AK/SK,或登录码道客户端。',
372
+ 'No usable 码道 credential yet. Add an AK/SK in Settings → 码道, or sign in to the CodeArts client.',
373
+ ],
374
+
375
+ }
376
+
377
+ /**
378
+ * Resolve a string for the active locale.
379
+ *
380
+ * Read from `document.documentElement.lang` rather than the Host's locale
381
+ * service: this module renders inside the same document, and reading the
382
+ * attribute avoids depending on a service whose signature may change.
383
+ */
384
+ /** Whether the surrounding document is in Chinese. */
385
+ function isChinese() {
386
+ const lang = (
387
+ (typeof document !== 'undefined' && document.documentElement.lang) ||
388
+ (typeof navigator !== 'undefined' && navigator.language) ||
389
+ 'en'
390
+ ).toLowerCase()
391
+ return lang.startsWith('zh')
392
+ }
393
+
394
+ function t(key) {
395
+ const entry = STRINGS[key]
396
+ if (!entry) return key
397
+ return isChinese() ? entry[0] : entry[1]
398
+ }
399
+
400
+ /** Fetch one plugin route, tolerating a non-JSON answer. */
401
+ async function getRoute(path, options = {}) {
402
+ const response = await fetch(`${ROUTE}${path}`, { ...options, headers: { accept: 'application/json' } })
403
+ const text = await response.text()
404
+ try {
405
+ const payload = JSON.parse(text)
406
+ if (!response.ok) throw new Error(payload.error ?? `${path}: HTTP ${response.status}`)
407
+ return payload
408
+ } catch (error) {
409
+ if (error instanceof SyntaxError) throw new Error(`${path}: ${response.status} ${text.slice(0, 120)}`)
410
+ throw error
411
+ }
412
+ }
413
+
414
+ /** POST JSON to one plugin route. */
415
+ async function postRoute(path, body) {
416
+ const response = await fetch(`${ROUTE}${path}`, {
417
+ method: 'POST',
418
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
419
+ body: JSON.stringify(body ?? {}),
420
+ })
421
+ const text = await response.text()
422
+ try {
423
+ const payload = JSON.parse(text)
424
+ if (!response.ok) throw new Error(payload.error ?? `${path}: HTTP ${response.status}`)
425
+ return payload
426
+ } catch (error) {
427
+ if (error instanceof SyntaxError) throw new Error(`${path}: ${response.status} ${text.slice(0, 120)}`)
428
+ throw error
429
+ }
430
+ }
431
+
432
+ /** Format an epoch-ms instant in the browser's own zone. */
433
+ function formatTime(ms) {
434
+ if (!ms) return '—'
435
+ try {
436
+ return new Date(ms).toLocaleString()
437
+ } catch {
438
+ return String(ms)
439
+ }
440
+ }
441
+
442
+ /**
443
+ * Render a credit balance.
444
+ *
445
+ * One format string per locale instead of gluing a translated noun between
446
+ * two numbers: word order differs by language, and the previous shape
447
+ * produced "7425.22 剩余 / 7600 共" in Chinese and "7425.22 remaining /
448
+ * 7600 of" in English. Grouping separators keep five-figure balances
449
+ * readable at a glance.
450
+ */
451
+ function formatBalance(credit) {
452
+ if (!credit) return ''
453
+ const remain = Number(credit.remain ?? 0).toLocaleString()
454
+ const total = Number(credit.total ?? 0).toLocaleString()
455
+ return t('account.creditBalance').replace('{remain}', remain).replace('{total}', total)
456
+ }
457
+
458
+ /** Compact a token count: 1048576 -> "1M". */
459
+ function formatTokens(value) {
460
+ if (typeof value !== 'number' || value <= 0) return '—'
461
+ if (value >= 1_000_000) return `${Math.round(value / 100_000) / 10}M`
462
+ if (value >= 1000) return `${Math.round(value / 100) / 10}K`
463
+ return String(value)
464
+ }
465
+
466
+ /**
467
+ * The plugin's stylesheet.
468
+ *
469
+ * The layout rules for the card, the section tabs, the account table and the
470
+ * model rows are taken from dsh-connect-workbuddy (MIT, Copyright (c) 2026
471
+ * LaoDing, https://github.com/dingminhua/dsh-connect-workbuddy) so that the
472
+ * two connector cards read as siblings in the same settings panel. Class
473
+ * names are this plugin's own (`dca-` prefix); the declarations, the values
474
+ * and the reasoning behind them are that project's.
475
+ *
476
+ * Shipped through the Client `styles` builtin rather than as inline style
477
+ * objects: the Client contract cannot import the design system, so the
478
+ * design system is reproduced here in CSS. Inline styles cannot express
479
+ * `:hover`, `:focus-visible`, `:has()` or media queries, which is exactly
480
+ * the feedback a control needs to feel like part of the shell.
481
+ *
482
+ * Every colour is a theme token with a literal fallback, so the page also
483
+ * survives a host that renames one.
484
+ */
485
+ const CSS = `
486
+ /* The app ships no global reset, so a padded, bordered element with width:100%
487
+ overflows its container by exactly its padding plus border. Every box here
488
+ opts in explicitly. */
489
+ .dca-page,.dca-page *{box-sizing:border-box}
490
+
491
+ /* ---- shared shell ------------------------------------------------------ */
492
+ .dca-page{display:flex;flex-direction:column;gap:18px;color:var(--dsw-alias-label-primary,#e6e6e6);font-size:13px;line-height:1.6}
493
+ .dca-head{display:flex;flex-direction:column;gap:4px}
494
+ .dca-title{margin:0;font-size:16px;font-weight:500;line-height:24px}
495
+ .dca-hint{margin:0;color:var(--dsw-alias-label-tertiary,#999);font-size:12px;line-height:18px}
496
+ .dca-card{
497
+ box-sizing:border-box;
498
+ border:1px solid var(--dsw-alias-border-l2,#36373b);
499
+ border-radius:12px;background:var(--dsw-alias-bg-layer-3,#202126);
500
+ padding:14px 16px;display:flex;flex-direction:column;gap:12px;
501
+ transition:border-color .16s;
502
+ }
503
+ .dca-card:hover{border-color:var(--dsw-alias-label-dimmed,#777)}
504
+
505
+ /* ---- account pool rows ------------------------------------------------
506
+ One row per account, two lines each: identity on the first, what the account
507
+ can do right now on the second. The reference lays its pool out this way, so
508
+ a long account name never pushes the figures out of alignment. */
509
+ .dca-pool-card-head{
510
+ display:flex;align-items:center;justify-content:space-between;
511
+ gap:8px 12px;flex-wrap:wrap;
512
+ }
513
+ .dca-pool-actions-group{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
514
+ .dca-pool-card-title{margin:0;font-size:13px;font-weight:600;line-height:20px}
515
+ .dca-pool-tagline{flex:1 1 auto;min-width:0}
516
+ .dca-pool-account-row{display:flex;align-items:center;gap:8px;min-width:0;flex-wrap:wrap}
517
+ /* The account name is a BUTTON that looks like text: the pencil only appears on
518
+ hover or focus, so the table does not read as a form with three inputs a row. */
519
+ .dca-rename-btn{
520
+ appearance:none;font:inherit;display:inline-flex;align-items:center;gap:5px;
521
+ padding:1px 6px;margin:-1px -6px;border:1px solid transparent;border-radius:6px;
522
+ background:transparent;color:var(--dsw-alias-label-primary,#e6e6e6);
523
+ cursor:pointer;min-width:0;max-width:100%;
524
+ }
525
+ .dca-rename-btn:hover{border-color:var(--dsw-alias-border-l2,#3a3d45);background:var(--dsw-alias-bg-layer-2,#232529)}
526
+ .dca-rename-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
527
+ .dca-rename-btn b{font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
528
+ .dca-rename-glyph{
529
+ flex:none;font-size:11px;line-height:16px;
530
+ color:var(--dsw-alias-label-tertiary,#999);opacity:0;transition:opacity .15s;
531
+ }
532
+ .dca-rename-btn:hover .dca-rename-glyph,
533
+ .dca-rename-btn:focus-visible .dca-rename-glyph{opacity:1}
534
+ .dca-rename{max-width:220px;font-family:inherit;font-size:13px}
535
+ .dca-pool-probe{
536
+ display:flex;align-items:center;gap:7px 12px;flex-wrap:wrap;
537
+ font-size:12px;line-height:17px;color:var(--dsw-alias-label-tertiary,#999);
538
+ min-width:0;overflow-wrap:anywhere;
539
+ }
540
+ .dca-pool-probe-cell{grid-area:probe;min-width:0}
541
+ .dca-pool-probe-main{
542
+ font-size:12px;line-height:17px;color:var(--dsw-alias-label-tertiary,#999);
543
+ min-width:0;overflow-wrap:anywhere;
544
+ }
545
+ .dca-pool-credits-row{
546
+ display:flex;flex-direction:row;flex-wrap:wrap;align-items:baseline;
547
+ justify-content:flex-end;gap:0 6px;min-width:0;
548
+ justify-self:end;text-align:right;font-variant-numeric:tabular-nums;
549
+ }
550
+ /* A small state chip on the name line, and a filled pill for "current". */
551
+ .dca-pool-tag{
552
+ flex:none;padding:1px 7px;border-radius:6px;
553
+ background:var(--dsw-alias-bg-layer-3,#2a2c33);
554
+ font-size:10px;line-height:16px;color:var(--dsw-alias-label-tertiary,#999);
555
+ }
556
+ .dca-badge{
557
+ flex:none;padding:2px 9px;border-radius:999px;
558
+ font-size:12px;line-height:18px;font-weight:500;
559
+ color:var(--dsw-alias-brand-primary,#5686fe);
560
+ background:rgba(86,134,254,.12);
561
+ border:1px solid rgba(86,134,254,.32);
562
+ }
563
+
564
+ /* ---- switch row -------------------------------------------------------
565
+ The platform checkbox, sized and drawn by the engine via accent-color. The
566
+ reference never paints its own toggle: that is what makes the box match the
567
+ reader's OS instead of looking like a painted square. */
568
+ /* The file input is visually hidden, not display:none: a display:none input
569
+ cannot be opened by script in every engine, and this one is clicked by the
570
+ button above it. */
571
+ .dca-file-input{
572
+ position:absolute;width:1px;height:1px;padding:0;margin:-1px;
573
+ overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0;
574
+ }
575
+ .dca-transfer-dialog{
576
+ margin-top:8px;padding:10px 12px;
577
+ border:1px solid var(--dsw-alias-border-l2,#3a3d45);
578
+ border-radius:10px;background:var(--dsw-alias-bg-secondary,transparent);
579
+ }
580
+ .dca-transfer-list{
581
+ list-style:none;margin:0 0 8px;padding:0;
582
+ max-height:180px;overflow-y:auto;
583
+ }
584
+ .dca-transfer-list label{
585
+ display:flex;align-items:center;gap:6px;
586
+ font-size:12px;color:var(--dsw-alias-label-primary,#e8e9ed);
587
+ cursor:pointer;padding:2px 0;
588
+ }
589
+ .dca-transfer-list input[type="checkbox"]{flex:none;accent-color:var(--dsw-alias-brand-primary,#5686fe)}
590
+ .dca-transfer-actions{display:flex;gap:8px;justify-content:flex-end;flex-wrap:wrap}
591
+ /* The pool switches: a 38x22 track with a 16px knob that slides 16px. The input
592
+ itself is present but invisible — it keeps the accessible role, the keyboard
593
+ handling and the checked state, while the track and knob are drawn here. */
594
+ .dca-sw{position:relative;display:inline-block;width:38px;height:22px;flex:none;cursor:pointer}
595
+ .dca-sw input{position:absolute;opacity:0;width:0;height:0}
596
+ .dca-sw-track{position:absolute;inset:0;border-radius:999px;background:var(--dsw-alias-border-l2,#3a3d45);transition:background .18s}
597
+ .dca-sw-track::after{
598
+ content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;
599
+ background:#fff;transition:transform .18s;box-shadow:0 1px 3px rgba(0,0,0,.3);
600
+ }
601
+ .dca-sw input:checked + .dca-sw-track{background:var(--dsw-alias-brand-primary,#5686fe)}
602
+ .dca-sw input:checked + .dca-sw-track::after{transform:translateX(16px)}
603
+ .dca-sw input:disabled + .dca-sw-track{opacity:.4}
604
+ .dca-sw input:focus-visible + .dca-sw-track{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:2px}
605
+
606
+ .dca-modebar-label{font-size:13px;font-weight:600;line-height:20px}
607
+
608
+ /* A plain row: no card, no border, no inset padding. It used to carry the
609
+ padding and hairline of the card that wrapped it, and with the card gone those
610
+ would leave a control floating under a stray rule. */
611
+ .dca-switchrow{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
612
+ /* The one-off claim is pushed to the row's end: the switch and its label are the
613
+ preference on the left, the action on the right. */
614
+ .dca-checkin-now{margin-inline-start:auto}
615
+ .dca-switchrow input[type="checkbox"]{
616
+ margin:0;flex:none;width:16px;height:16px;
617
+ accent-color:var(--dsw-alias-brand-primary,#5686fe);
618
+ cursor:pointer;
619
+ }
620
+ .dca-switchrow label{font-weight:600;font-size:13px;line-height:20px;cursor:pointer}
621
+
622
+ /* A dashed strip for secondary tools: "these are utilities, not the table". */
623
+
624
+ /* ---- model rows -------------------------------------------------------
625
+ Line one: enable box, name, ratio, flags on the left; the row's own switches
626
+ on the right. Line two: facts, indented to the name (22px = the box plus its
627
+ 8px gap) so the two lines read as one block. */
628
+ .dca-model-head{
629
+ display:flex;align-items:center;justify-content:space-between;
630
+ flex-wrap:wrap;gap:12px;row-gap:8px;min-width:0;
631
+ }
632
+ .dca-model-controls{
633
+ display:flex;align-items:center;flex-wrap:wrap;
634
+ gap:12px;row-gap:8px;min-width:0;flex:none;
635
+ }
636
+ .dca-model-details{
637
+ display:flex;align-items:center;justify-content:space-between;
638
+ gap:12px;min-width:0;padding-inline-start:22px;
639
+ }
640
+ .dca-model-check{
641
+ margin:0;flex:none;width:16px;height:16px;
642
+ accent-color:var(--dsw-alias-brand-primary,#5686fe);
643
+ }
644
+ .dca-model-ratio{color:var(--dsw-alias-label-tertiary,#999);font-size:11px;font-weight:400;line-height:16px;flex:none}
645
+ .dca-model-flag{
646
+ display:inline-flex;align-items:center;gap:5px;flex:none;
647
+ font-size:11px;line-height:16px;
648
+ color:var(--dsw-alias-label-secondary,#c6c9d0);
649
+ }
650
+ .dca-card-plain{border-color:transparent;background:transparent;padding:0}
651
+ .dca-card-title{margin:0;font-size:13px;font-weight:600;line-height:20px}
652
+ .dca-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
653
+ .dca-fields{display:flex;gap:8px;flex-wrap:wrap}
654
+ /* Every field grows equally and may shrink: a fixed 220px basis forced the row to
655
+ wrap on a narrow card even when the inputs would have fitted. */
656
+ .dca-fields .dca-input{flex:1 1 160px;min-width:120px}
657
+ .dca-label{font-size:12px;color:var(--dsw-alias-label-tertiary,#999);line-height:18px}
658
+ .dca-input{
659
+ box-sizing:border-box;width:100%;
660
+ font-size:12px;line-height:20px;
661
+ font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
662
+ padding:4px 8px;border-radius:6px;
663
+ border:1px solid var(--dsw-alias-border-l2,#3a3d45);
664
+ background:var(--dsw-alias-bg-l1,transparent);
665
+ color:var(--dsw-alias-label-primary,#e8e9ed);
666
+ transition:border-color .15s;
667
+ }
668
+ .dca-input:hover{border-color:var(--dsw-alias-label-dimmed,#777)}
669
+ .dca-input:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px;border-color:var(--dsw-alias-brand-primary,#5686fe)}
670
+
671
+ /* ---- buttons -----------------------------------------------------------
672
+ A shared base plus one modifier per weight, so a row of buttons has one
673
+ height, one radius and one transition instead of three copies. */
674
+ .dca-btn{
675
+ box-sizing:border-box;appearance:none;font:inherit;font-size:13px;line-height:20px;
676
+ padding:5px 14px;border-radius:8px;min-height:32px;font-weight:500;cursor:pointer;
677
+ border:1px solid var(--dsw-alias-border-l2,#3a3d45);
678
+ background:var(--dsw-alias-bg-layer-2,#232529);
679
+ color:var(--dsw-alias-label-primary,#e6e6e6);
680
+ transition:background .15s,border-color .15s,opacity .15s;
681
+ white-space:nowrap;
682
+ }
683
+ .dca-btn:hover:not(:disabled){border-color:var(--dsw-alias-label-dimmed,#777)}
684
+ .dca-btn:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
685
+ .dca-btn:disabled{opacity:.55;cursor:default}
686
+ .dca-btn-primary{
687
+ border-color:transparent;
688
+ /* An INVERTED surface, not a brand fill — the reference's primary is
689
+ label-primary on bg-layer-3, two tokens that are opposite by definition in
690
+ every theme, so the label can never vanish into its own background. */
691
+ background:var(--dsw-alias-label-primary,#e6e6e6);
692
+ color:var(--dsw-alias-bg-layer-3,#2a2c33);
693
+ font-weight:600;
694
+ }
695
+ .dca-btn-primary:hover:not(:disabled){opacity:.9}
696
+ /* If a host omits bg-base, the fallback must follow the theme too, or the
697
+ light theme turns this into dark-on-dark. Inert when the token exists. */
698
+ @media (prefers-color-scheme: light){
699
+ .dca-btn-primary{color:var(--dsw-alias-bg-base,#fff)}
700
+ }
701
+ .dca-btn-quiet{background:transparent;border-color:transparent;color:var(--dsw-alias-label-tertiary,#999)}
702
+ .dca-btn-quiet:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14));color:var(--dsw-alias-label-primary,#e6e6e6)}
703
+
704
+ /* ---- tabs -------------------------------------------------------------
705
+ A TABS STRIP pinned above scrolling content, matched to the reference: 7px
706
+ 11px tabs with a 2px transparent bottom border that the active tab fills with
707
+ the accent, a hairline rule under the strip, and sticky positioning so the
708
+ labels stay put while the panel scrolls. The opaque background is
709
+ load-bearing — without it rows slide under the strip and show through the
710
+ gaps between labels. (An earlier revision drew card-shaped cells here; the
711
+ reference does not, and at four sections the cards read as buttons.) */
712
+ .dca-tabs{
713
+ position:sticky;top:-1px;z-index:2;
714
+ display:flex;align-items:stretch;gap:2px;margin:0;
715
+ border-bottom:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.24));
716
+ background:var(--dsw-alias-bg-layer-1,#17181b);
717
+ }
718
+ .dca-tab{
719
+ appearance:none;font:inherit;cursor:pointer;border:0;background:transparent;
720
+ padding:7px 11px;margin-bottom:-1px;
721
+ border-bottom:2px solid transparent;
722
+ color:var(--dsw-alias-label-tertiary,#999);
723
+ font-size:13px;font-weight:600;line-height:20px;white-space:nowrap;
724
+ transition:color .15s,border-color .15s;
725
+ }
726
+ .dca-tab:hover:not(.dca-tab-on){color:var(--dsw-alias-label-primary,#e6e6e6)}
727
+ .dca-tab:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
728
+ .dca-tab-on{
729
+ color:var(--dsw-alias-label-primary,#e6e6e6);
730
+ border-bottom-color:var(--dsw-alias-brand-primary,#5686fe);
731
+ }
732
+
733
+ /* ---- data table -------------------------------------------------------
734
+ Tabular figures so the multiplier column lines up digit for digit. */
735
+ /* Model rows are CARDS, not table rows — the reference lists models this way and
736
+ a settings column cannot hold six nowrap columns. Each row is a surface on
737
+ bg-layer-2, its facts on one 11px meta line, exactly like the reference. */
738
+ /* One bordered box; its first and last rows receive their own corner radii so
739
+ contextual row menus can extend beyond the table without being clipped. */
740
+ .dca-model-page{min-height:100%;padding-bottom:60px}
741
+ .dca-models{
742
+ display:flex;flex-direction:column;
743
+ border:1px solid var(--dsw-alias-border-l2,#36373b);
744
+ border-radius:10px;overflow:hidden;
745
+ }
746
+ .dca-model{
747
+ box-sizing:border-box;display:grid;grid-template-columns:minmax(0,1fr);gap:7px;
748
+ padding:10px 12px;background:var(--dsw-alias-bg-layer-2,#232529);
749
+ transition:background-color .16s;
750
+ }
751
+ .dca-model + .dca-model{border-top:1px solid var(--dsw-alias-border-l2,#36373b)}
752
+ /* An unticked model stays visible but recedes: it is still a thing you can
753
+ enable, so hiding it would make the catalog feel arbitrary. */
754
+ .dca-model-off{background:var(--dsw-alias-bg-layer-1,#1c1d21)}
755
+ /* The model panel's action bar: always present, disabled when clean. */
756
+ .dca-model-actions{
757
+ display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;
758
+ position:sticky;bottom:0;z-index:3;flex-shrink:0;
759
+ gap:12px;row-gap:8px;
760
+ background:var(--dsw-alias-bg-layer-1,#17181b);
761
+ box-shadow:0 -6px 16px rgba(0,0,0,.04);
762
+ border-top:1px solid var(--dsw-alias-border-l2,#36373b);
763
+ padding:12px 0;
764
+ }
765
+ .dca-model-actions-buttons{display:flex;align-items:center;justify-content:flex-end;gap:8px}
766
+ .dca-dirty{
767
+ margin-left:8px;padding:0 6px;border-radius:6px;
768
+ font-size:10px;line-height:16px;font-weight:600;
769
+ color:var(--dsw-alias-state-warn-primary,#e8b34b);
770
+ border:1px solid currentColor;
771
+ }
772
+ .dca-model-controls label{cursor:pointer}
773
+ .dca-model-controls input[type="checkbox"]{
774
+ margin:0 5px 0 0;width:14px;height:14px;flex:none;
775
+ accent-color:var(--dsw-alias-brand-primary,#5686fe);
776
+ }
777
+ .dca-model-controls input[type="checkbox"]:disabled{cursor:default}
778
+ .dca-model-name{
779
+ display:inline-flex;align-items:baseline;gap:7px;
780
+ color:var(--dsw-alias-label-primary,#e6e6e6);
781
+ font-size:13px;font-weight:500;line-height:19px;
782
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;
783
+ min-width:0;
784
+ }
785
+ .dca-model-name b{font-size:13px;font-weight:500}
786
+ .dca-effort{display:inline-flex;align-items:center;gap:5px;cursor:pointer}
787
+ /* A quiet pill, not a boxed form control: the row already carries two checkboxes,
788
+ and a third bordered control would make a settings table look like a form. */
789
+ .dca-effort-select{
790
+ font:inherit;font-size:11px;line-height:15px;
791
+ color:var(--dsw-alias-label-secondary,#c6c9d0);
792
+ background:rgba(174,179,187,.11);
793
+ border:1px solid transparent;border-radius:999px;
794
+ padding:1px 6px;cursor:pointer;max-width:180px;
795
+ }
796
+ .dca-effort-select:hover:not(:disabled){border-color:var(--dsw-alias-border-l2,#3a3d45)}
797
+ .dca-effort-select:focus-visible{
798
+ outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px;
799
+ }
800
+ .dca-effort-select:disabled{opacity:.55;cursor:default}
801
+ .dca-model-meta{
802
+ display:flex;align-items:center;gap:7px 12px;flex-wrap:wrap;
803
+ color:var(--dsw-alias-label-tertiary,#999);font-size:11px;line-height:16px;
804
+ }
805
+ .dca-model-meta .dca-num{font-variant-numeric:tabular-nums}
806
+ .dca-id{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11px;color:var(--dsw-alias-label-tertiary,#999);line-height:16px}
807
+
808
+ /* ---- pills, key/value, messages --------------------------------------- */
809
+
810
+ /* DIAGNOSTICS: a two-column FACT TABLE, not prose. One row per thing the plugin
811
+ actually read, so a bug report can quote a line instead of paraphrasing the
812
+ UI. No control lives here on purpose — a diagnostics panel that can change
813
+ settings is a settings panel with a worse name. */
814
+ .dca-diag{
815
+ display:flex;flex-direction:column;
816
+ border:1px solid var(--dsw-alias-border-l2,#36373b);
817
+ border-radius:10px;overflow:hidden;
818
+ background:var(--dsw-alias-bg-layer-2,#232529);
819
+ }
820
+ .dca-diag-row{display:flex;align-items:baseline;justify-content:space-between;gap:16px;padding:8px 12px}
821
+ .dca-diag-row + .dca-diag-row{border-top:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.24))}
822
+ .dca-diag-label{flex:none;color:var(--dsw-alias-label-tertiary,#999);font-size:12px;line-height:18px}
823
+ .dca-diag-value{
824
+ min-width:0;color:var(--dsw-alias-label-primary,#e6e6e6);
825
+ font-size:12px;line-height:18px;text-align:right;overflow-wrap:anywhere;
826
+ }
827
+ .dca-diag-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
828
+ .dca-diag-bad{color:var(--dsw-alias-state-warn-primary,#e8b34b)}
829
+ .dca-diag-hint{margin:10px 0 0;color:var(--dsw-alias-label-tertiary,#999);font-size:12px;line-height:18px}
830
+ .dca-msg{font-size:12px;line-height:18px;margin:0;white-space:pre-wrap}
831
+ .dca-msg-error{color:var(--dsw-alias-state-error-primary,#e5534b)}
832
+ .dca-msg-ok{color:var(--dsw-alias-state-success-primary,#3fb950)}
833
+ .dca-msg-warn{color:var(--dsw-alias-state-warn-primary,#d29922)}
834
+ .dca-pre{
835
+ margin:0;padding:10px;border-radius:8px;
836
+ background:var(--dsw-alias-bg-base,#121317);
837
+ border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.24));
838
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;
839
+ font-size:11px;line-height:16px;white-space:pre-wrap;word-break:break-word;
840
+ max-height:240px;overflow:auto;
841
+ }
842
+
843
+ /* ---- account pool -----------------------------------------------------
844
+ A table of accounts, styled like the settings tables around it: one row per
845
+ account, aligned columns, the current one marked rather than reordered.
846
+ Every row is the same height so the check-in buttons line up. */
847
+ .dca-pool{display:flex;flex-direction:column;gap:12px;margin:0;padding:0 0 4px}
848
+ /* A grid table, matched to the reference card: rounded outer frame on
849
+ bg-layer-2, one row per account, uppercase 11px header row on bg-layer-3.
850
+ Not a <table> — the columns reflow to two lines on a narrow panel, which a
851
+ table cannot do. */
852
+ .dca-pool-table{
853
+ box-sizing:border-box;container-type:inline-size;
854
+ border:1px solid var(--dsw-alias-border-l2,#3a3d45);
855
+ border-radius:12px;
856
+ background:var(--dsw-alias-bg-layer-2,#24262c);
857
+ }
858
+ .dca-pool-row{
859
+ display:grid;
860
+ grid-template-columns:minmax(0,1fr) minmax(0,auto) 160px;
861
+ grid-template-areas:
862
+ "account account credits"
863
+ "probe probe actions";
864
+ column-gap:12px;row-gap:4px;align-items:center;
865
+ padding:10px 14px;
866
+ border-top:1px solid var(--dsw-alias-border-l1,#2c2d31);
867
+ font-size:13px;
868
+ }
869
+ .dca-pool-row:first-of-type{border-top:0}
870
+ /* The serving row, findable at a glance: a left accent bar plus a faint tint.
871
+ The bar is what distinguishes it in a long table — a 7% wash alone reads as
872
+ an alternating-row stripe. */
873
+ .dca-pool-row-current{
874
+ /* The ONLY marker for the serving account now: a tint strong enough to read at
875
+ a glance plus the accent bar. A 7% wash alone reads as an alternating-row
876
+ stripe in a long table. */
877
+ background:rgba(86,134,254,.14);
878
+ box-shadow:inset 3px 0 0 var(--dsw-alias-brand-primary,#5686fe);
879
+ }
880
+ .dca-pool-row-head{
881
+ padding:8px 14px;row-gap:1px;
882
+ background:var(--dsw-alias-bg-layer-3,#2a2c33);
883
+ color:var(--dsw-alias-label-tertiary,#999);
884
+ font-size:11px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;
885
+ }
886
+ .dca-pool-col-account{grid-area:account;min-width:0}
887
+ .dca-pool-col-credits{
888
+ grid-area:credits;justify-self:end;text-align:right;font-variant-numeric:tabular-nums;
889
+ }
890
+ .dca-pool-col-actions{grid-area:actions;justify-self:end}
891
+ .dca-pool-card-head{
892
+ display:flex;align-items:center;justify-content:space-between;
893
+ gap:8px 12px;flex-wrap:wrap;
894
+ }
895
+ .dca-pool-tagline{flex:1 1 auto;min-width:0}
896
+ .dca-pool-card-title{margin:0;font-size:13px;font-weight:600;line-height:20px}
897
+
898
+ .dca-pool-sub{display:block;font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary,#999)}
899
+ .dca-pool-actions{display:flex;gap:6px;justify-content:flex-end;align-items:center}
900
+ .dca-btn-xs{
901
+ box-sizing:border-box;appearance:none;font:inherit;font-size:12px;line-height:20px;font-weight:500;
902
+ padding:3px 10px;border-radius:8px;cursor:pointer;white-space:nowrap;
903
+ border:1px solid var(--dsw-alias-border-l2,#3a3d45);
904
+ background:var(--dsw-alias-bg-layer-2,#232529);
905
+ color:var(--dsw-alias-label-primary,#e6e6e6);
906
+ transition:background .15s,border-color .15s,opacity .15s;
907
+ }
908
+ .dca-btn-xs:hover:not(:disabled){border-color:var(--dsw-alias-label-dimmed,#777)}
909
+ .dca-btn-xs:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
910
+ .dca-btn-xs:disabled{opacity:.5;cursor:default}
911
+
912
+ .dca-tag{
913
+ display:inline-flex;align-items:center;padding:1px 8px;border-radius:var(--dsw-radius-xl,20px);
914
+ font-size:11px;line-height:16px;white-space:nowrap;
915
+ border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.24));
916
+ color:var(--dsw-alias-label-tertiary,#999);
917
+ }
918
+ .dca-tag-ok{color:var(--dsw-alias-state-success-primary,#3fb950);border-color:currentColor}
919
+ .dca-tag-warn{color:var(--dsw-alias-state-warn-primary,#d29922);border-color:currentColor}
920
+
921
+
922
+
923
+ /* Compact controls share the host's colors in either theme. */
924
+ .dca-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
925
+ .dca-search{flex:1 1 200px;min-width:140px}
926
+ .dca-filter-group{display:inline-flex;gap:2px;padding:3px;border:1px solid var(--dsw-alias-border-l2,#36373b);border-radius:9px}
927
+ .dca-filter{appearance:none;font:inherit;border:0;border-radius:6px;padding:3px 10px;cursor:pointer;background:transparent;color:var(--dsw-alias-label-secondary,#c6c9d0)}
928
+ .dca-filter[aria-pressed="true"]{background:var(--dsw-alias-label-primary,#e6e6e6);color:var(--dsw-alias-bg-layer-1,#17181b)}
929
+ .dca-filter:focus-visible,.dca-details > summary:focus-visible,.dca-account-menu > summary:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:2px}
930
+ .dca-sort{width:auto;max-width:100%;min-height:32px;font-family:inherit}
931
+ .dca-catalog-meta{display:flex;align-items:center;gap:6px 14px;flex-wrap:wrap;font-size:12px;color:var(--dsw-alias-label-secondary,#c6c9d0)}
932
+ .dca-model-meta{color:var(--dsw-alias-label-secondary,#b6b8be)}
933
+ .dca-model-off .dca-model-controls,.dca-model-off .dca-effort{color:var(--dsw-alias-label-secondary,#b6b8be)}
934
+ .dca-model-controls input:disabled,.dca-effort-select:disabled{opacity:.75}
935
+ .dca-save-status{flex:1 1 180px;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary,#c6c9d0)}
936
+ .dca-save-status-error{color:var(--dsw-alias-state-error-primary,#ef4444)}
937
+ .dca-empty{padding:24px 16px;display:flex;flex-direction:column;align-items:center;gap:10px;text-align:center}
938
+ .dca-details > summary{cursor:pointer;font-size:12px;color:var(--dsw-alias-label-secondary,#c6c9d0);border-radius:4px}
939
+ .dca-details[open] > summary{margin-bottom:12px}
940
+ .dca-details-body{display:flex;flex-direction:column;gap:12px;min-width:0}
941
+ .dca-add-tools > summary{font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary,#e6e6e6)}
942
+ .dca-form-field{display:flex;flex-direction:column;gap:5px;flex:1 1 180px;min-width:0;font-size:12px;color:var(--dsw-alias-label-secondary,#c6c9d0)}
943
+ .dca-form-field .dca-input{width:100%;min-width:0;flex:none}
944
+ .dca-secret-field{display:flex;align-items:center;gap:6px}
945
+ .dca-secret-field .dca-input{flex:1;min-width:0}
946
+ .dca-form{display:flex;flex-direction:column;gap:12px}
947
+ .dca-form .dca-fields{align-items:flex-start}
948
+ .dca-account-menu{position:relative}
949
+ .dca-account-menu > summary{cursor:pointer;list-style:none;padding:3px 10px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:8px;font-size:16px;line-height:20px}
950
+ .dca-account-menu > summary::-webkit-details-marker{display:none}
951
+ .dca-menu-actions{position:absolute;inset-inline-end:0;top:calc(100% + 4px);z-index:4;padding:5px;min-width:110px;border:1px solid var(--dsw-alias-border-l2,#3a3d45);border-radius:8px;background:var(--dsw-alias-bg-overlay,#26282e);box-shadow:0 4px 16px rgba(0,0,0,.12)}
952
+ .dca-menu-actions .dca-btn-xs{width:100%;text-align:left;border-color:transparent}
953
+ .dca-danger{color:var(--dsw-alias-state-error-primary,#ef4444)}
954
+ .dca-pool-row-head{border-radius:11px 11px 0 0}
955
+ .dca-pool-row:last-child{border-radius:0 0 11px 11px}
956
+ .dca-current-tag{display:inline-flex;font-size:11px;font-weight:500;color:var(--dsw-alias-brand-primary,#5686fe)}
957
+ .dca-diagnostic-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(190px,100%),1fr));gap:10px}
958
+ .dca-summary-item{border:1px solid var(--dsw-alias-border-l2,#36373b);border-radius:10px;padding:12px;display:flex;flex-direction:column;gap:5px;min-width:0}
959
+ .dca-summary-item strong{font-size:13px;font-weight:500}
960
+ .dca-summary-item p{overflow-wrap:anywhere}
961
+ .dca-section-error{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
962
+ .dca-section-error .dca-msg{flex:1;min-width:0}
963
+ @media(max-width:640px){
964
+ .dca-model-head{align-items:flex-start;gap:10px}
965
+ .dca-model-controls{justify-content:flex-start;padding-inline-start:24px}
966
+ .dca-model-actions{gap:8px}
967
+ .dca-model-actions-buttons{margin-inline-start:auto}
968
+ .dca-model-meta{gap:4px 10px}
969
+ .dca-pool-row{grid-template-columns:minmax(0,1fr) auto;grid-template-areas:"account credits" "probe actions";padding:10px}
970
+ }
971
+
972
+ .dca-feature-stack{display:flex;flex-direction:column;gap:12px;min-width:0;padding-top:12px}
973
+ .dca-feature-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(210px,100%),1fr));gap:12px}
974
+ .dca-subtitle{font-size:13px;font-weight:600;margin:0}
975
+ .dca-preview-box{border:1px solid var(--dsw-alias-border-l2,#36373b);border-radius:8px;padding:12px;max-width:100%;overflow-wrap:anywhere}
976
+ .dca-health{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px;color:var(--dsw-alias-label-secondary,#b6b8be)}
977
+ .dca-health-bad{color:var(--dsw-alias-state-warn-primary,#d49937)}
978
+ .dca-low-balance{color:var(--dsw-alias-state-warn-primary,#d49937)!important}
979
+ .dca-balance-alert{padding:10px 12px;border:1px solid var(--dsw-alias-state-warn-primary,#d49937);border-radius:8px;font-size:12px;display:flex;flex-direction:column;gap:6px;overflow-wrap:anywhere}
980
+ .dca-usage-table{overflow-x:auto;border:1px solid var(--dsw-alias-border-l2,#36373b);border-radius:8px}
981
+ .dca-usage-table table{width:100%;border-collapse:collapse;font-size:12px;text-align:left}
982
+ .dca-usage-table th,.dca-usage-table td{padding:9px 10px;border-bottom:1px solid var(--dsw-alias-border-l2,#36373b);vertical-align:top;min-width:76px;overflow-wrap:anywhere}
983
+ .dca-usage-table th{font-weight:500;color:var(--dsw-alias-label-secondary,#b6b8be)}
984
+ .dca-usage-table tr:last-child td{border-bottom:0}
985
+ .dca-preset-preview{max-height:180px;overflow:auto;margin:0;padding-inline-start:20px}
986
+ .dca-preset-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
987
+ .dca-preset-row .dca-input{flex:1;min-width:min(180px,100%)}
988
+
989
+ @media(prefers-reduced-motion:reduce){
990
+ .dca-page *,.dca-pop *{animation:none!important;transition:none!important}
991
+ }
992
+
993
+ /* ---- composer pill ----------------------------------------------------
994
+ Plain composer text, no border or fill at rest: this row is a strip of
995
+ compact controls and a boxed pill among them reads as a form field. The
996
+ padding is only the click target, revealed by hover. */
997
+ /* position:relative is load-bearing, not cosmetic: the popover is absolute, and
998
+ without a positioned owner here it anchors to the nearest positioned ancestor
999
+ — the composer card — so it appeared at the card's far-left edge rather than
1000
+ above the trigger the user just clicked. */
1001
+ .dca-chip{position:relative;display:inline-flex;align-items:center;min-width:0}
1002
+ .dca-chip-trigger{
1003
+ appearance:none;display:inline-flex;align-items:center;align-self:stretch;gap:5px;
1004
+ padding:2px 6px;border:0;border-radius:var(--dsw-radius-sm,8px);background:transparent;
1005
+ font-family:inherit;font-size:12px;line-height:18px;
1006
+ color:var(--dsw-alias-label-tertiary,#999);
1007
+ white-space:nowrap;cursor:pointer;font-variant-numeric:tabular-nums;
1008
+ }
1009
+ .dca-chip-trigger:hover{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14))}
1010
+ .dca-chip-trigger:focus-visible{outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:1px}
1011
+ .dca-chip-trigger-on{background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14));color:var(--dsw-alias-label-primary,#e6e6e6)}
1012
+ .dca-chip-mark{opacity:.75;font-size:11px}
1013
+ /* Anchored to .dca-chip. Right-aligned rather than left so a trigger sitting at
1014
+ the right edge of the composer does not push the panel off-screen. */
1015
+ .dca-pop{
1016
+ position:absolute;bottom:calc(100% + 6px);right:0;z-index:20;min-width:250px;max-width:min(340px,80vw);
1017
+ padding:12px;border-radius:var(--dsw-radius-lg,16px);
1018
+ border:1px solid var(--dsw-alias-border-l1,rgba(127,127,127,.24));
1019
+ background:var(--dsw-alias-bg-overlay,#26282e);
1020
+ box-shadow:0 8px 24px rgba(0,0,0,.28);
1021
+ display:flex;flex-direction:column;gap:10px;
1022
+ font-size:12px;line-height:18px;color:var(--dsw-alias-label-primary,#e6e6e6);
1023
+ }
1024
+ .dca-pop-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:8px}
1025
+ /* nowrap: the header is a title plus a small control in a 248px popover, and
1026
+ without it the title broke across two lines the moment the control joined it. */
1027
+ .dca-pop-title{
1028
+ flex:none;white-space:nowrap;
1029
+ font-size:13px;font-weight:600;
1030
+ color:var(--dsw-alias-label-primary,#e6e6e6);
1031
+ }
1032
+ .dca-pop-refresh{
1033
+ appearance:none;flex:none;display:inline-flex;align-items:center;gap:4px;
1034
+ padding:3px 8px 3px 6px;margin-left:auto;
1035
+ border:1px solid transparent;border-radius:999px;background:transparent;
1036
+ color:var(--dsw-alias-label-secondary,#c6c9d0);
1037
+ font:inherit;font-size:11px;line-height:16px;font-weight:500;cursor:pointer;
1038
+ transition:background-color .12s ease,border-color .12s ease,color .12s ease;
1039
+ }
1040
+ .dca-pop-refresh:hover:not(:disabled){
1041
+ background:rgba(127,127,127,.10);
1042
+ border-color:var(--dsw-alias-border-l2,#3a3d45);
1043
+ color:var(--dsw-alias-label-primary,#e6e6e6);
1044
+ }
1045
+ .dca-pop-refresh:disabled{cursor:default;opacity:.6}
1046
+ .dca-pop-refresh-icon{flex:none}
1047
+ .dca-pop-refresh-icon-spin{animation:dca-spin .9s linear infinite}
1048
+ @keyframes dca-spin{to{transform:rotate(360deg)}}
1049
+ /* The settings pill is the one control that LEAVES the panel, so it carries the
1050
+ brand tint while refresh above stays quiet: two equally loud pills would make
1051
+ the header read as a toolbar. */
1052
+ .dca-pop-settings{
1053
+ appearance:none;flex:none;display:inline-flex;align-items:center;gap:4px;
1054
+ padding:3px 8px 3px 6px;
1055
+ border:1px solid rgba(86,134,254,.32);border-radius:999px;
1056
+ background:rgba(86,134,254,.12);
1057
+ color:var(--dsw-alias-brand-primary,#5686fe);
1058
+ font:inherit;font-size:11px;line-height:16px;font-weight:500;cursor:pointer;
1059
+ }
1060
+ .dca-pop-settings:hover{background:rgba(86,134,254,.20)}
1061
+ .dca-pop-settings-icon{font-size:11px;line-height:1}
1062
+ /* A real table so every balance lands in one right-aligned column. */
1063
+ .dca-pop-table{width:100%;border-collapse:collapse;font-size:12px;line-height:18px}
1064
+ .dca-pop-table thead th{
1065
+ padding:0 0 7px;font-weight:500;text-align:left;font-size:11px;
1066
+ color:var(--dsw-alias-label-tertiary,#999);
1067
+ border-bottom:1px solid var(--dsw-alias-border-l1,#2c2d31);
1068
+ }
1069
+ .dca-pop-table thead th.dca-pop-num{padding-right:0}
1070
+ .dca-pop-table tbody td{padding:5px 0;border-top:1px solid transparent;vertical-align:top}
1071
+ .dca-pop-num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
1072
+ /* The row body is a button so switching accounts is one click, but it must read
1073
+ as a row: no border, no fill at rest, the whole cell as the target. */
1074
+ .dca-pop-switch{
1075
+ appearance:none;display:flex;align-items:flex-start;gap:6px;width:100%;
1076
+ /* Negative inline margin so the hover fill reaches the panel's edge while the
1077
+ text stays aligned with the header above it — the padding does the inset. */
1078
+ padding:4px 6px;margin-inline-start:-6px;
1079
+ border:0;border-radius:6px;background:transparent;font:inherit;text-align:left;
1080
+ color:var(--dsw-alias-label-primary,#e6e6e6);cursor:pointer;min-width:0;
1081
+ transition:background-color .12s ease;
1082
+ }
1083
+ /* Hover belongs to the SWITCH, not the row: the credits cell is not clickable, so
1084
+ lighting it up would promise an action it cannot perform. */
1085
+ .dca-pop-switch:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14))}
1086
+ .dca-pop-switch:active:not(:disabled){background:var(--dsw-alias-interactive-bg-pressed,rgba(127,127,127,.20))}
1087
+ /* Keyboard gets the same affordance as the pointer, plus an outline: tabbing to a
1088
+ row must show which one is about to be switched. */
1089
+ .dca-pop-switch:focus-visible{
1090
+ outline:2px solid var(--dsw-alias-brand-primary,#5686fe);outline-offset:-1px;
1091
+ background:var(--dsw-alias-interactive-bg-hover,rgba(127,127,127,.14));
1092
+ }
1093
+ .dca-pop-switch:disabled{cursor:default}
1094
+ /* The serving row is already in use, so it is the one row that must NOT look
1095
+ clickable: it keeps the underline-free quiet treatment. */
1096
+ .dca-pop-row-current .dca-pop-name{font-weight:600}
1097
+ .dca-pop-dot{flex:none;width:7px;height:7px;border-radius:50%;margin-top:6px}
1098
+ .dca-pop-dot-ok{background:var(--dsw-alias-state-success-primary,#22a06b)}
1099
+ .dca-pop-dot-bad{background:var(--dsw-alias-state-error-primary,#ef4444)}
1100
+ .dca-pop-who{display:flex;flex-direction:column;min-width:0}
1101
+ .dca-pop-name{overflow:hidden;text-overflow:ellipsis}
1102
+ /* The state goes UNDER the name: a reason string is long, and beside the name in
1103
+ a 248px panel it would squeeze the name to a few characters. */
1104
+ .dca-pop-mark{display:flex;flex-direction:column;gap:1px;margin-top:1px;font-size:11px;line-height:15px}
1105
+ .dca-pop-mark-current{color:var(--dsw-alias-state-success-primary,#22a06b)}
1106
+ .dca-pop-mark-reason{color:var(--dsw-alias-state-warn-primary,#f59e0b);min-width:0;overflow-wrap:anywhere}
1107
+ /* The lapsing warning sits on its OWN line under the figure: the column is
1108
+ nowrap and tabular, so an inline span would sit beside the balance and stretch
1109
+ the column for every row. */
1110
+ .dca-pop-soon{
1111
+ display:block;margin-top:1px;
1112
+ font-size:11px;line-height:15px;font-weight:400;
1113
+ color:var(--dsw-alias-state-warn-primary,#f59e0b);
1114
+ }
1115
+ .dca-pop-empty{margin:0;color:var(--dsw-alias-label-tertiary,#999);font-size:12px;line-height:18px}
1116
+ `
1117
+
1118
+ /**
1119
+ * The state every tab needs before it can show anything.
1120
+ *
1121
+ * Without this, a tab rendered while the first fetch is still in flight
1122
+ * shows an empty page with no hint that data is on its way — and a failed
1123
+ * fetch looked identical to an account with no data.
1124
+ */
1125
+ function Pending({ error, onRetry }) {
1126
+ if (error) {
1127
+ return h(
1128
+ 'div',
1129
+ { className: 'dca-card' },
1130
+ h('p', { className: 'dca-msg dca-msg-error' }, `${t('common.retryHint')}(${error})`),
1131
+ h(
1132
+ 'div',
1133
+ { className: 'dca-row' },
1134
+ h('button', { type: 'button', className: 'dca-btn', onClick: onRetry }, t('common.retry')),
1135
+ ),
1136
+ )
1137
+ }
1138
+ return h(
1139
+ 'div',
1140
+ { className: 'dca-card' },
1141
+ h('p', { className: 'dca-hint' }, t('common.loading')),
1142
+ )
1143
+ }
1144
+
1145
+ /** Share only known diagnostic fields. Error strings and labels can contain secrets or paths. */
1146
+ function diagnosticReport(status, account) {
1147
+ const catalog = status?.catalog
1148
+ const credential = status?.credential
1149
+ const credentialSources = ['env', 'file', 'codearts']
1150
+ return {
1151
+ provider: PROVIDER_ID,
1152
+ catalog: {
1153
+ source: ['gateway', 'cache', 'fallback'].includes(catalog?.source) ? catalog.source : null,
1154
+ count: Number.isInteger(catalog?.models) ? catalog.models : null,
1155
+ refreshedAt: Number.isFinite(catalog?.refreshedAt) ? catalog.refreshedAt : null,
1156
+ hasError: Boolean(catalog?.error),
1157
+ },
1158
+ credential: {
1159
+ configured: credential?.configured === true,
1160
+ source: credentialSources.includes(credential?.source) ? credential.source : null,
1161
+ savedAkSet: Boolean(credential?.savedAk),
1162
+ savedSkSet: Boolean(credential?.savedSk),
1163
+ hasError: Boolean(credential?.error),
1164
+ },
1165
+ registration: { configSchema: status?.registration?.configSchema === true },
1166
+ account: account ? {
1167
+ ok: account.ok === true,
1168
+ stage: ['credentials', 'gateway'].includes(account.stage) ? account.stage : null,
1169
+ creditAvailable: Boolean(account.credit),
1170
+ } : null,
1171
+ }
1172
+ }
1173
+
1174
+ function catalogSourceLabel(source) {
1175
+ if (source === 'gateway') return t('models.sourceGateway')
1176
+ if (source === 'cache') return t('models.sourceCache')
1177
+ if (source === 'fallback') return t('models.sourceFallback')
1178
+ return '—'
1179
+ }
1180
+
1181
+ /** A small labelled value row. */
1182
+ function KV({ name, children }) {
1183
+ return h(
1184
+ React.Fragment,
1185
+ null,
1186
+ h('span', { className: 'dca-diag-label' }, name),
1187
+ h('span', { className: 'dca-diag-value' }, children),
1188
+ )
1189
+ }
1190
+
1191
+ /**
1192
+ * Add one account, import many, and export the pool.
1193
+ *
1194
+ * Import takes pasted text rather than a file picker: the browser can read
1195
+ * a dropped file, but a paste works for every source a user actually has
1196
+ * (the console's CSV contents, a chat message with a key in it, another
1197
+ * install's export).
1198
+ */
1199
+ /**
1200
+ * Add accounts.
1201
+ *
1202
+ * Two paths, both in the reference's shape: a pair typed by hand (this
1203
+ * plugin's own route has an AK/SK form, which WorkBuddy does not need
1204
+ * because it signs in), and a FILE IMPORT that opens the system picker
1205
+ * directly — no ceremony dialog in front of a dialog the OS is about to show
1206
+ * anyway. The confirmation appears after the file is read, which is the step
1207
+ * that actually needs the user's attention.
1208
+ *
1209
+ * Export downloads a JSON file rather than copying to the clipboard: the
1210
+ * card runs inside the settings panel, where `a[download]` on a same-origin
1211
+ * Blob is the reliable way out, and a file is what a user expects when the
1212
+ * button says 导出.
1213
+ */
1214
+ function AccountTools({ onChanged, onResult, hasAccounts, updateTarget }) {
1215
+ const [expanded, setExpanded] = useState(false)
1216
+ useEffect(() => {
1217
+ if (hasAccounts !== null) setExpanded(!hasAccounts)
1218
+ }, [hasAccounts])
1219
+ const [showSecret, setShowSecret] = useState(false)
1220
+ const [ak, setAk] = useState('')
1221
+ const [sk, setSk] = useState('')
1222
+ const [label, setLabel] = useState('')
1223
+ const [busy, setBusy] = useState(null)
1224
+ const [preview, setPreview] = useState(null)
1225
+ const fileInput = useRef(null)
1226
+ /** The picked file's text, held here: the picker closes immediately, so
1227
+ * there is no File on screen between preview and confirm. */
1228
+ const importText = useRef('')
1229
+ const akInput = useRef(null)
1230
+ useEffect(() => {
1231
+ if (!updateTarget) return
1232
+ setExpanded(true); setLabel(updateTarget.label ?? ''); setAk(''); setSk('')
1233
+ akInput.current?.focus()
1234
+ }, [updateTarget])
1235
+
1236
+ const add = useCallback(async () => {
1237
+ if (ak.trim() === '' || sk.trim() === '') {
1238
+ onResult({ kind: 'error', text: t('account.needBoth') })
1239
+ return
1240
+ }
1241
+ setBusy('add')
1242
+ try {
1243
+ const result = await postRoute('/accounts/add', { ak, sk, label })
1244
+ if (result.ok) {
1245
+ setAk(''); setSk(''); setLabel('')
1246
+ setShowSecret(false)
1247
+ setExpanded(false)
1248
+ onResult({ kind: 'success', text: result.added ? t('pool.added') : t('pool.updated') })
1249
+ await onChanged()
1250
+ } else {
1251
+ onResult({ kind: 'error', text: result.error ?? t('account.saveFail') })
1252
+ }
1253
+ } catch (error) {
1254
+ onResult({ kind: 'error', text: `${t('account.saveFail')}:${error.message}` })
1255
+ } finally { setBusy(null) }
1256
+ }, [ak, sk, label, onChanged, onResult])
1257
+
1258
+ /** Read the picked file and show what it contains before writing. */
1259
+ const readFile = useCallback(async (file) => {
1260
+ setBusy('import')
1261
+ setPreview(null)
1262
+ try {
1263
+ const text = await file.text()
1264
+ importText.current = text
1265
+ const result = await postRoute('/accounts/preview', { text })
1266
+ if (result.ok) {
1267
+ setPreview({ total: result.total, accounts: result.accounts })
1268
+ } else {
1269
+ onResult({ kind: 'error', text: result.error ?? t('pool.importEmpty') })
1270
+ }
1271
+ } catch (error) {
1272
+ onResult({ kind: 'error', text: error.message })
1273
+ } finally { setBusy(null) }
1274
+ }, [onResult])
1275
+
1276
+ const confirmImport = useCallback(async () => {
1277
+ setBusy('import')
1278
+ try {
1279
+ const result = await postRoute('/accounts/import', { text: importText.current })
1280
+ setPreview(null)
1281
+ importText.current = ''
1282
+ if (result.ok) {
1283
+ onResult({
1284
+ kind: 'success',
1285
+ text: t('pool.importResult')
1286
+ .replace('{added}', result.added)
1287
+ .replace('{updated}', result.updated)
1288
+ .replace('{skipped}', result.skipped),
1289
+ })
1290
+ await onChanged()
1291
+ } else {
1292
+ onResult({ kind: 'error', text: result.error ?? t('pool.importEmpty') })
1293
+ }
1294
+ } catch (error) {
1295
+ onResult({ kind: 'error', text: error.message })
1296
+ } finally { setBusy(null) }
1297
+ }, [onChanged, onResult])
1298
+
1299
+
1300
+ return h(
1301
+ 'details',
1302
+ {
1303
+ className: 'dca-card dca-details dca-add-tools',
1304
+ open: expanded,
1305
+ onToggle: (event) => setExpanded(event.currentTarget.open),
1306
+ },
1307
+ h('summary', null, t('pool.addTitle')),
1308
+ updateTarget ? h('p', { className: 'dca-hint' }, t('health.updateHint').replace('{name}', updateTarget.label)) : null,
1309
+ h(
1310
+ 'form',
1311
+ { className: 'dca-form', onSubmit: (event) => { event.preventDefault(); if (busy === null) void add() } },
1312
+ h(
1313
+ 'div',
1314
+ { className: 'dca-fields' },
1315
+ h('label', { className: 'dca-form-field', htmlFor: 'dca-ak2' },
1316
+ t('account.ak'),
1317
+ h('input', {
1318
+ ref: akInput, id: 'dca-ak2', className: 'dca-input', value: ak, autoComplete: 'off',
1319
+ placeholder: t('account.placeholderAk'), disabled: busy !== null,
1320
+ 'aria-label': t('account.ak'), onChange: (event) => setAk(event.target.value),
1321
+ }),
1322
+ ),
1323
+ h('label', { className: 'dca-form-field', htmlFor: 'dca-sk2' },
1324
+ t('account.sk'),
1325
+ h('span', { className: 'dca-secret-field' },
1326
+ h('input', {
1327
+ id: 'dca-sk2', className: 'dca-input', type: showSecret ? 'text' : 'password',
1328
+ value: sk, autoComplete: 'off', placeholder: t('account.placeholderSk'),
1329
+ disabled: busy !== null, 'aria-label': t('account.sk'),
1330
+ onChange: (event) => setSk(event.target.value),
1331
+ }),
1332
+ h('button', {
1333
+ type: 'button', className: 'dca-btn-xs', 'aria-controls': 'dca-sk2',
1334
+ 'aria-pressed': showSecret, 'aria-label': t(showSecret ? 'pool.hideSecret' : 'pool.showSecret'), disabled: busy !== null,
1335
+ onClick: () => setShowSecret((current) => !current),
1336
+ }, t(showSecret ? 'pool.hideSecret' : 'pool.showSecret')),
1337
+ ),
1338
+ ),
1339
+ h('label', { className: 'dca-form-field', htmlFor: 'dca-label' },
1340
+ t('pool.addLabel'),
1341
+ h('input', {
1342
+ id: 'dca-label', className: 'dca-input', value: label, autoComplete: 'off',
1343
+ placeholder: t('pool.addLabelPlaceholder'), disabled: busy !== null,
1344
+ onChange: (event) => setLabel(event.target.value),
1345
+ }),
1346
+ ),
1347
+ ),
1348
+ h('div', { className: 'dca-pool-actions-group' },
1349
+ h('button', {
1350
+ type: 'submit', className: 'dca-btn dca-btn-primary',
1351
+ disabled: busy !== null || !ak.trim() || !sk.trim(),
1352
+ }, busy === 'add' ? t('account.saving') : t('pool.add')),
1353
+ h('button', {
1354
+ type: 'button', className: 'dca-btn', disabled: busy !== null,
1355
+ onClick: () => fileInput.current?.click(),
1356
+ }, busy === 'import' ? t('pool.importing') : t('pool.import')),
1357
+ ),
1358
+ ),
1359
+ h('input', {
1360
+ ref: fileInput, type: 'file', accept: 'application/json,.json,.csv,.txt',
1361
+ className: 'dca-file-input',
1362
+ onChange: (event) => {
1363
+ const file = event.target.files?.[0]
1364
+ event.target.value = ''
1365
+ if (file !== undefined) void readFile(file)
1366
+ },
1367
+ }),
1368
+ preview !== null
1369
+ ? h(
1370
+ 'div',
1371
+ { className: 'dca-transfer-dialog', role: 'dialog', 'aria-label': t('pool.import') },
1372
+ h(
1373
+ 'p',
1374
+ { className: 'dca-hint' },
1375
+ t('pool.previewTotal').replace('{total}', preview.total),
1376
+ ),
1377
+ h(
1378
+ 'ul',
1379
+ { className: 'dca-transfer-list' },
1380
+ ...preview.accounts.map((entry) =>
1381
+ h(
1382
+ 'li',
1383
+ { key: entry.index },
1384
+ h(
1385
+ 'label',
1386
+ null,
1387
+ h('input', { type: 'checkbox', checked: true, readOnly: true }),
1388
+ ' ',
1389
+ entry.label ?? entry.akMasked ?? `#${entry.index}`,
1390
+ ),
1391
+ ),
1392
+ ),
1393
+ ),
1394
+ h(
1395
+ 'div',
1396
+ { className: 'dca-transfer-actions' },
1397
+ h(
1398
+ 'button',
1399
+ {
1400
+ type: 'button',
1401
+ className: 'dca-btn',
1402
+ onClick: () => { setPreview(null); importText.current = '' },
1403
+ },
1404
+ t('pool.cancel'),
1405
+ ),
1406
+ h(
1407
+ 'button',
1408
+ { type: 'button', className: 'dca-btn dca-btn-primary', onClick: confirmImport, disabled: busy !== null },
1409
+ busy === 'import'
1410
+ ? t('pool.importing')
1411
+ : t('pool.importConfirm').replace('{count}', preview.accounts.length),
1412
+ ),
1413
+ ),
1414
+ )
1415
+ : null,
1416
+ h('details', { className: 'dca-details' },
1417
+ h('summary', null, t('account.whereToGet')),
1418
+ h('p', { className: 'dca-hint' }, t('account.whereToGetBody')),
1419
+ ),
1420
+ )
1421
+ }
1422
+
1423
+ /**
1424
+ * The account pool.
1425
+ *
1426
+ * Layout follows the reference card: a title row naming the account in use,
1427
+ * the switch block above the table, then a two-line row per account, then
1428
+ * the batch action. Check-in is ONE button for the whole table — never one
1429
+ * control per account, which would make one daily bonus cost one click per
1430
+ * account and report one outcome per account.
1431
+ */
1432
+ function AccountPool({
1433
+ pool,
1434
+ busyId,
1435
+ busy,
1436
+ onActivate,
1437
+ onRemove,
1438
+ autoOn,
1439
+ onToggleAuto,
1440
+ onCheckinAll,
1441
+ onRename,
1442
+ onExport,
1443
+ onCheck,
1444
+ onUpdateCredentials,
1445
+ }) {
1446
+ /** Which row is being renamed, and its draft text. */
1447
+ const [editingId, setEditingId] = useState(null)
1448
+ const [draftLabel, setDraftLabel] = useState('')
1449
+
1450
+ const beginRename = useCallback((account) => {
1451
+ setEditingId(account.id)
1452
+ // Start from the current name, EXCEPT when it is the derived fallback
1453
+ // (a masked AK): that is a placeholder, not a name the user chose, and
1454
+ // prefilling it would make them delete it before typing.
1455
+ setDraftLabel(account.renameable === false ? '' : (account.label ?? ''))
1456
+ }, [])
1457
+
1458
+ const cancelRename = useCallback(() => {
1459
+ setEditingId(null)
1460
+ setDraftLabel('')
1461
+ }, [])
1462
+
1463
+ const commitRename = useCallback(async (id) => {
1464
+ const next = draftLabel.trim()
1465
+ setEditingId(null)
1466
+ setDraftLabel('')
1467
+ // An unchanged or empty draft is a cancel, not a request.
1468
+ if (next === '') return
1469
+ await onRename(id, next)
1470
+ }, [draftLabel, onRename])
1471
+ const accounts = pool?.accounts ?? []
1472
+ // `busy` is the KIND ('checkin' | 'auto' | null); most checks only care
1473
+ // whether anything is running.
1474
+ const anyBusy = busy !== null && busy !== undefined && busy !== false
1475
+ // Something to claim right now? The button is disabled otherwise, so a
1476
+ // press that cannot do anything never looks like a broken button.
1477
+ const anyClaimable = accounts.some((account) => account.checkin?.claimable)
1478
+ const allSigned = accounts.length > 0 && accounts.every((account) => account.checkin?.claimedToday === true)
1479
+ const active = accounts.find((account) => account.active)
1480
+ return h(
1481
+ 'div',
1482
+ { className: 'dca-pool' },
1483
+
1484
+ h(
1485
+ 'div',
1486
+ { className: 'dca-pool-card-head' },
1487
+ h('h2', { className: 'dca-title' }, t('pool.title')),
1488
+ h('p', { className: 'dca-hint dca-pool-tagline' }, t('pool.tagline')),
1489
+ h('div', { className: 'dca-pool-actions-group' },
1490
+ active ? h('span', { className: 'dca-badge' }, `${t('pool.inUse')}${active.label}`) : null,
1491
+ accounts.length > 0 ? h('button', {
1492
+ type: 'button', className: 'dca-btn-xs', onClick: onExport, disabled: anyBusy || busyId !== null,
1493
+ title: t('pool.exportHint'),
1494
+ }, t('pool.export')) : null,
1495
+ ),
1496
+ ),
1497
+
1498
+ // One switch, no card around it and no explanatory paragraph under it:
1499
+ // the label says what it does, and the paragraph restated the same thing
1500
+ // in a box that made a single control look like a section.
1501
+ h(
1502
+ 'div',
1503
+ { className: 'dca-switchrow' },
1504
+ h(
1505
+ 'label',
1506
+ { className: 'dca-sw' },
1507
+ h('input', {
1508
+ type: 'checkbox',
1509
+ checked: autoOn === true,
1510
+ disabled: anyBusy || busyId !== null,
1511
+ 'aria-label': t('pool.autoTitle'),
1512
+ onChange: () => onToggleAuto(autoOn !== true),
1513
+ }),
1514
+ h('span', { className: 'dca-sw-track' }),
1515
+ ),
1516
+ h('b', { className: 'dca-modebar-label' }, t('pool.autoTitle')),
1517
+ // A one-off claim beside the standing switch, pushed to the row's end.
1518
+ // The switch is a PREFERENCE and this is an ACTION: pressing it must
1519
+ // claim now without opting anyone into daily automation, which is why
1520
+ // it sends `now: true` rather than flipping `enabled`.
1521
+ accounts.length === 0
1522
+ ? null
1523
+ : h(
1524
+ 'button',
1525
+ {
1526
+ type: 'button',
1527
+ className: 'dca-btn dca-btn-xs dca-checkin-now',
1528
+ disabled: anyBusy || busyId !== null || !anyClaimable,
1529
+ title: anyClaimable
1530
+ ? t('pool.checkinAllHint')
1531
+ : t('pool.checkinNoneToday'),
1532
+ onClick: onCheckinAll,
1533
+ },
1534
+ busy === 'checkin' ? t('pool.checkinClaiming') : allSigned ? t('pool.allSigned') : t('pool.checkinAll'),
1535
+ ),
1536
+ ),
1537
+
1538
+ accounts.length === 0
1539
+ ? h('p', { className: 'dca-hint' }, t('pool.empty'))
1540
+ : h(
1541
+ 'div',
1542
+ { className: 'dca-pool-table' },
1543
+ h(
1544
+ 'div',
1545
+ { className: 'dca-pool-row dca-pool-row-head' },
1546
+ h('span', { className: 'dca-pool-col-account' }, t('pool.colAccount')),
1547
+ h('span', { className: 'dca-pool-col-credits' }, t('pool.colCredits')),
1548
+ // An empty cell on purpose: the grid template names an `actions`
1549
+ // area, and without a box the credits label would claim that
1550
+ // track and stop lining up with the values below it. The buttons
1551
+ // speak for themselves, so it carries no text.
1552
+ h('span', { className: 'dca-pool-col-actions', 'aria-hidden': true }),
1553
+ ),
1554
+ ...accounts.map((account) => {
1555
+ const rowBusy = busyId === account.id
1556
+ const checkin = account.checkin
1557
+ return h(
1558
+ 'div',
1559
+ {
1560
+ key: account.id,
1561
+ className: `dca-pool-row${account.active ? ' dca-pool-row-current' : ''}`,
1562
+ },
1563
+ h(
1564
+ 'div',
1565
+ { className: 'dca-pool-col-account' },
1566
+ h(
1567
+ 'div',
1568
+ { className: 'dca-pool-account-row' },
1569
+ account.active ? h('span', { className: 'dca-current-tag' }, t('pool.current')) : null,
1570
+ editingId === account.id
1571
+ ? h('input', {
1572
+ type: 'text',
1573
+ className: 'dca-input dca-rename',
1574
+ value: draftLabel,
1575
+ autoFocus: true,
1576
+ 'aria-label': t('pool.rename'),
1577
+ placeholder: t('pool.renamePlaceholder'),
1578
+ onChange: (event) => setDraftLabel(event.target.value),
1579
+ onKeyDown: (event) => {
1580
+ if (event.key === 'Enter') void commitRename(account.id)
1581
+ // Escape must not save: an accidental click into the
1582
+ // field is the common way a user arrives here.
1583
+ else if (event.key === 'Escape') cancelRename()
1584
+ },
1585
+ onBlur: () => void commitRename(account.id),
1586
+ })
1587
+ : h(
1588
+ 'button',
1589
+ {
1590
+ type: 'button',
1591
+ className: 'dca-rename-btn',
1592
+ title: t('pool.renameHint'),
1593
+ onClick: () => beginRename(account),
1594
+ },
1595
+ h('b', null, account.label),
1596
+ h('span', { className: 'dca-rename-glyph', 'aria-hidden': true }, '✎'),
1597
+ ),
1598
+ ),
1599
+ h(
1600
+ 'div',
1601
+ { className: 'dca-pool-probe' },
1602
+ h('div', { className: `dca-health${account.health?.state && account.health.state !== 'available' ? ' dca-health-bad' : ''}` },
1603
+ h('span', null, t(`health.${account.health?.state ?? 'unknown'}`)),
1604
+ account.health?.checkedAt ? h('span', null, `${t('health.checked')} ${formatTime(account.health.checkedAt)}`) : null,
1605
+ ),
1606
+ account.error
1607
+ ? h('span', { className: 'dca-msg-error' }, account.error)
1608
+ : h('span', null, account.accountName ?? account.akMasked),
1609
+ ),
1610
+ ),
1611
+ h(
1612
+ 'div',
1613
+ { className: 'dca-pool-credits-row' },
1614
+ h('span', { className: account.lowBalance ? 'dca-low-balance' : undefined }, account.credit ? Number(account.credit.remain).toLocaleString() : '—'),
1615
+ account.credit?.plan ? h('span', { className: 'dca-pool-sub' }, account.credit.plan) : null,
1616
+ // Warn about credits that lapse. The amount is real; the
1617
+ // deadline is not knowable from this gateway, so the chip
1618
+ // states the amount and never a date it would have to invent.
1619
+ account.credit?.expiring > 0
1620
+ ? h(
1621
+ 'span',
1622
+ {
1623
+ className: 'dca-tag dca-tag-warn',
1624
+ title: t('pool.expiringHint'),
1625
+ },
1626
+ t('pool.expiring').replace(
1627
+ '{amount}',
1628
+ Number(account.credit.expiring).toLocaleString(),
1629
+ ),
1630
+ )
1631
+ : null,
1632
+ ),
1633
+ h(
1634
+ 'div',
1635
+ { className: 'dca-pool-probe-cell' },
1636
+ h(
1637
+ 'div',
1638
+ { className: 'dca-pool-probe-main' },
1639
+ checkin?.claimedToday
1640
+ ? t('pool.checkinDone')
1641
+ : checkin?.claimable
1642
+ ? t('pool.checkinPending')
1643
+ : '—',
1644
+ ),
1645
+ ),
1646
+ h(
1647
+ 'div',
1648
+ { className: 'dca-pool-col-actions' },
1649
+ h(
1650
+ 'div',
1651
+ { className: 'dca-pool-actions' },
1652
+ h('button', { type: 'button', className: 'dca-btn-xs', disabled: rowBusy || anyBusy || busyId !== null, onClick: () => onCheck(account.id) }, rowBusy ? t('common.loading') : t('health.recheck')),
1653
+ account.health?.state === 'credentials' ? h('button', { type: 'button', className: 'dca-btn-xs', disabled: rowBusy || anyBusy || busyId !== null, onClick: () => onUpdateCredentials(account) }, t('health.update')) : null,
1654
+ account.health?.state === 'insufficient' ? h('span', { className: 'dca-hint' }, t('health.switch')) : null,
1655
+ account.active
1656
+ ? null
1657
+ : h(
1658
+ 'button',
1659
+ {
1660
+ type: 'button',
1661
+ className: 'dca-btn-xs',
1662
+ disabled: rowBusy || anyBusy || busyId !== null,
1663
+ onClick: () => onActivate(account.id),
1664
+ },
1665
+ t('pool.use'),
1666
+ ),
1667
+ h('details', { className: 'dca-account-menu' },
1668
+ h('summary', {
1669
+ 'aria-label': `${t('common.more')} — ${account.label}`,
1670
+ title: t('common.more'),
1671
+ 'aria-disabled': anyBusy || busyId !== null,
1672
+ onClick: (event) => { if (anyBusy || busyId !== null) event.preventDefault() },
1673
+ }, '⋯'),
1674
+ h('div', { className: 'dca-menu-actions' },
1675
+ h('button', {
1676
+ type: 'button', className: 'dca-btn-xs dca-danger',
1677
+ disabled: rowBusy || anyBusy || busyId !== null,
1678
+ onClick: (event) => {
1679
+ event.currentTarget.closest('details').open = false
1680
+ void onRemove(account)
1681
+ },
1682
+ }, t('pool.remove')),
1683
+ ),
1684
+ ),
1685
+ ),
1686
+ ),
1687
+ )
1688
+ }),
1689
+ ),
1690
+
1691
+ )
1692
+ }
1693
+
1694
+ // ── credentials tab ────────────────────────────────────────────────────
1695
+
1696
+ function AccountTab({ status, pool, preferences, onChanged, onPreferencesSaved }) {
1697
+ const [busy, setBusy] = useState(null)
1698
+ const [busyId, setBusyId] = useState(null)
1699
+ const [notice, setNotice] = useState(null)
1700
+ const [updateTarget, setUpdateTarget] = useState(null)
1701
+
1702
+ const credential = status?.credential
1703
+ const reload = onChanged
1704
+
1705
+ /** One place to report an outcome, so every action gets the same voice. */
1706
+ const report = useCallback((next) => setNotice(next), [])
1707
+
1708
+ /** Download the store as a JSON file. */
1709
+ const doExport = useCallback(async () => {
1710
+ setBusy('export')
1711
+ try {
1712
+ const result = await getRoute('/accounts/export')
1713
+ if (!result.ok || typeof result.text !== 'string') {
1714
+ report({ kind: 'error', text: result.error ?? t('pool.exportFailed') })
1715
+ return
1716
+ }
1717
+ if (typeof document === 'undefined' || typeof Blob === 'undefined') {
1718
+ report({ kind: 'error', text: t('pool.exportFailed') })
1719
+ return
1720
+ }
1721
+ const stamp = new Date()
1722
+ const pad = (n) => String(n).padStart(2, '0')
1723
+ const name = `codearts-accounts-${stamp.getFullYear()}-${pad(stamp.getMonth() + 1)}-${pad(stamp.getDate())}.json`
1724
+ const blob = new Blob([result.text], { type: 'application/json' })
1725
+ const url = URL.createObjectURL(blob)
1726
+ const anchor = document.createElement('a')
1727
+ anchor.href = url
1728
+ anchor.download = name
1729
+ document.body.appendChild(anchor)
1730
+ anchor.click()
1731
+ anchor.remove()
1732
+ URL.revokeObjectURL(url)
1733
+ report({ kind: 'success', text: `${t('pool.exported').replace('{name}', name)} · ${t('pool.exportHint')}` })
1734
+ } catch (error) {
1735
+ report({ kind: 'error', text: error.message })
1736
+ } finally { setBusy(null) }
1737
+ }, [report])
1738
+
1739
+
1740
+ const activate = useCallback(async (id) => {
1741
+ setBusyId(id)
1742
+ try {
1743
+ const result = await postRoute('/accounts/activate', { id })
1744
+ if (!result.ok) report({ kind: 'error', text: result.error ?? t('common.retry') })
1745
+ await reload()
1746
+ } catch (error) {
1747
+ report({ kind: 'error', text: error.message })
1748
+ } finally { setBusyId(null) }
1749
+ }, [reload, report])
1750
+
1751
+ const remove = useCallback(async (account) => {
1752
+ const ask = t('pool.removeConfirm')
1753
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function' && !window.confirm(ask)) return
1754
+ setBusyId(account.id)
1755
+ try {
1756
+ await postRoute('/accounts/remove', { id: account.id })
1757
+ report({ kind: 'success', text: t('pool.remove') })
1758
+ await reload()
1759
+ } catch (error) {
1760
+ report({ kind: 'error', text: error.message })
1761
+ } finally { setBusyId(null) }
1762
+ }, [reload, report])
1763
+
1764
+ /**
1765
+ * Claim the daily bonus once, for every account that can.
1766
+ *
1767
+ * `now: true` is what makes this an ACTION rather than a preference: the
1768
+ * host runs one sweep and leaves the standing daily switch exactly as the
1769
+ * user set it. Sending `enabled: true` here would silently opt someone into
1770
+ * daily automation from a button labelled "check in now".
1771
+ */
1772
+ const checkinAll = useCallback(async () => {
1773
+ setBusy('checkin')
1774
+ try {
1775
+ const result = await postRoute('/checkin/auto', { now: true })
1776
+ const summary = result.summary
1777
+ if (summary) {
1778
+ report({
1779
+ kind: summary.failures.length === 0 ? 'success' : 'warn',
1780
+ text: t('pool.checkinResult')
1781
+ .replace('{claimed}', summary.claimed)
1782
+ .replace('{failed}', summary.failures.length),
1783
+ })
1784
+ } else if (result.error) {
1785
+ report({ kind: 'error', text: result.error })
1786
+ }
1787
+ await reload()
1788
+ } catch (error) {
1789
+ report({ kind: 'error', text: `${t('pool.checkinFailed')}:${error.message}` })
1790
+ } finally {
1791
+ setBusy(null)
1792
+ }
1793
+ }, [reload, report])
1794
+
1795
+ /** Rename one account; the pool's inline editor calls this. */
1796
+ const rename = useCallback(async (id, label) => {
1797
+ try {
1798
+ const result = await postRoute('/accounts/rename', { id, label })
1799
+ if (!result.ok) report({ kind: 'error', text: result.error ?? t('pool.renameFailed') })
1800
+ await reload()
1801
+ } catch (error) {
1802
+ report({ kind: 'error', text: `${t('pool.renameFailed')}:${error.message}` })
1803
+ }
1804
+ }, [reload, report])
1805
+
1806
+ const toggleAuto = useCallback(async (enabled) => {
1807
+ setBusy('auto')
1808
+ try {
1809
+ const result = await postRoute('/checkin/auto', { enabled })
1810
+ if (result.summary) {
1811
+ report({
1812
+ kind: result.summary.failures.length === 0 ? 'success' : 'warn',
1813
+ text: t('pool.result')
1814
+ .replace('{claimed}', result.summary.claimed)
1815
+ .replace('{failed}', result.summary.failures.length),
1816
+ })
1817
+ }
1818
+ await reload()
1819
+ } catch (error) {
1820
+ report({ kind: 'error', text: error.message })
1821
+ } finally { setBusy(null) }
1822
+ }, [reload, report])
1823
+
1824
+ const test = useCallback(async () => {
1825
+ setBusy('test')
1826
+ setNotice(null)
1827
+ try {
1828
+ const result = await getRoute('/test')
1829
+ const lines = (result.steps ?? []).map((step) => `${step.ok ? '✓' : '✗'} ${step.step}:${step.detail}`)
1830
+ setNotice({ kind: result.ok ? 'success' : 'error', text: lines.join('\n') || t('diag.none'), pre: true })
1831
+ await onChanged()
1832
+ } catch (error) {
1833
+ setNotice({ kind: 'error', text: error.message })
1834
+ } finally {
1835
+ setBusy(null)
1836
+ }
1837
+ }, [onChanged])
1838
+
1839
+ // Destructive and irreversible from the UI, so it asks first — the button
1840
+ // sits at the same weight as the harmless refresh beside it.
1841
+ const clear = useCallback(async () => {
1842
+ if (typeof window !== 'undefined' && typeof window.confirm === 'function') {
1843
+ if (!window.confirm(t('account.clearConfirm'))) return
1844
+ }
1845
+ setBusy('clear')
1846
+ setNotice(null)
1847
+ try {
1848
+ await postRoute('/clear', {})
1849
+ setNotice({ kind: 'success', text: t('account.cleared') })
1850
+ await onChanged()
1851
+ } catch (error) {
1852
+ setNotice({ kind: 'error', text: `${t('account.clearFail')}:${error.message}` })
1853
+ } finally {
1854
+ setBusy(null)
1855
+ }
1856
+ }, [onChanged])
1857
+
1858
+ const checkAccount = async (id) => {
1859
+ setBusyId(id)
1860
+ try {
1861
+ const result = await postRoute('/accounts/check', { id })
1862
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
1863
+ report({ kind: result.account.health.state === 'available' ? 'success' : 'warn', text: `${result.account.label}:${t(`health.${result.account.health.state}`)}` })
1864
+ await reload()
1865
+ } catch (error) { report({ kind: 'error', text: error.message }) } finally { setBusyId(null) }
1866
+ }
1867
+ const accounts = pool?.accounts ?? []
1868
+ return h(
1869
+ 'div',
1870
+ { className: 'dca-page' },
1871
+ // The pool below renders its own head — title, tagline and the in-use
1872
+ // badge — so the page must not render a second one above it. It did, and
1873
+ // the two read as a duplicated heading with two different sentences
1874
+ // under it.
1875
+
1876
+ // One line for every outcome of every action on this tab, announced.
1877
+ notice
1878
+ ? h(
1879
+ 'p',
1880
+ {
1881
+ className: `dca-msg dca-msg-${
1882
+ notice.kind === 'error' ? 'error' : notice.kind === 'success' ? 'ok' : 'warn'
1883
+ }`,
1884
+ role: notice.kind === 'error' ? 'alert' : 'status',
1885
+ 'aria-live': notice.kind === 'error' ? 'assertive' : 'polite',
1886
+ },
1887
+ notice.text,
1888
+ )
1889
+ : null,
1890
+
1891
+ // The pool renders its own head, its own switch block, the table and the
1892
+ // batch action — the order the reference card uses. The daily switch is
1893
+ // passed in rather than drawn as a separate card, so it sits above the
1894
+ // table where the reference puts it.
1895
+ h(AccountPool, {
1896
+ pool,
1897
+ busyId,
1898
+ // The pool takes the raw kind, not a collapsed boolean: the check-in
1899
+ // button must know whether IT is the one running so it can show
1900
+ // 「签到中…」 — a boolean cannot express that.
1901
+ busy,
1902
+ onActivate: activate,
1903
+ onRemove: remove,
1904
+ autoOn: pool?.autoCheckin === true,
1905
+ onToggleAuto: toggleAuto,
1906
+ onCheckinAll: checkinAll,
1907
+ onRename: rename,
1908
+ onExport: doExport,
1909
+ onCheck: checkAccount,
1910
+ onUpdateCredentials: (account) => setUpdateTarget({ ...account }),
1911
+ }),
1912
+
1913
+ h(AccountTools, { onChanged, onResult: report, hasAccounts: pool ? accounts.length > 0 : null, updateTarget }),
1914
+ preferences ? h(ReminderSettings, { preferences, onSaved: onPreferencesSaved }) : null,
1915
+ h(BackupTools, { onRestored: onChanged }),
1916
+
1917
+ accounts.length === 0 || credential?.error
1918
+ ? null
1919
+ : h(
1920
+ 'div',
1921
+ { className: 'dca-card dca-card-plain' },
1922
+ h(
1923
+ 'div',
1924
+ { className: 'dca-row' },
1925
+ h('button', { type: 'button', className: 'dca-btn', onClick: test, disabled: busy !== null },
1926
+ busy === 'test' ? t('account.testing') : t('account.test')),
1927
+
1928
+ ),
1929
+ h('details', { className: 'dca-details' },
1930
+ h('summary', null, t('pool.manage')),
1931
+ h('button', { type: 'button', className: 'dca-btn dca-danger', onClick: clear, disabled: busy !== null }, t('account.clear')),
1932
+ ),
1933
+ ),
1934
+ )
1935
+ }
1936
+
1937
+ function FeatureNotice({ notice }) {
1938
+ if (!notice) return null
1939
+ return h('p', { className: `dca-msg dca-msg-${notice.kind === 'error' ? 'error' : 'ok'}`, role: notice.kind === 'error' ? 'alert' : 'status' }, notice.text)
1940
+ }
1941
+
1942
+ function downloadJson(value, name) {
1943
+ const url = URL.createObjectURL(new Blob([JSON.stringify(value, null, 2)], { type: 'application/json' }))
1944
+ const anchor = document.createElement('a')
1945
+ anchor.href = url
1946
+ anchor.download = name
1947
+ document.body.appendChild(anchor)
1948
+ anchor.click()
1949
+ anchor.remove()
1950
+ window.setTimeout(() => URL.revokeObjectURL(url), 1000)
1951
+ }
1952
+
1953
+ function ReminderSettings({ preferences, onSaved }) {
1954
+ const [draft, setDraft] = useState(null)
1955
+ const [busy, setBusy] = useState(false)
1956
+ const [notice, setNotice] = useState(null)
1957
+ const enabled = draft?.enabled ?? preferences.lowBalanceEnabled
1958
+ const threshold = draft?.threshold ?? String(preferences.lowBalanceThreshold)
1959
+ const dirty = enabled !== preferences.lowBalanceEnabled || threshold !== String(preferences.lowBalanceThreshold)
1960
+ const valid = threshold.trim() !== '' && Number.isFinite(Number(threshold)) && Number(threshold) >= 0 && Number(threshold) <= 1e9
1961
+ const update = (patch) => { setDraft({ enabled, threshold, ...patch }); setNotice(null) }
1962
+ const save = async (event) => {
1963
+ event.preventDefault()
1964
+ if (!valid || busy) return
1965
+ setBusy(true)
1966
+ try {
1967
+ const result = await postRoute('/preferences/save', { lowBalanceEnabled: enabled, lowBalanceThreshold: Number(threshold) })
1968
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
1969
+ await onSaved()
1970
+ setDraft(null)
1971
+ setNotice({ kind: 'success', text: t('features.saved') })
1972
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(false) }
1973
+ }
1974
+ return h('details', { className: 'dca-card dca-details' },
1975
+ h('summary', null, t('reminder.title')),
1976
+ h('form', { className: 'dca-feature-stack', onSubmit: save },
1977
+ h('label', { className: 'dca-row' }, h('input', { type: 'checkbox', checked: enabled, disabled: busy, onChange: (event) => update({ enabled: event.target.checked }) }), t('reminder.enabled')),
1978
+ h('label', { className: 'dca-form-field' }, t('reminder.threshold'), h('input', { className: 'dca-input', type: 'number', min: 0, max: 1e9, step: 'any', value: threshold, disabled: busy, onChange: (event) => update({ threshold: event.target.value }) })),
1979
+ h('p', { className: 'dca-hint' }, t('reminder.hint')),
1980
+ h(FeatureNotice, { notice }),
1981
+ h('div', { className: 'dca-row' }, h('button', { type: 'submit', className: 'dca-btn', disabled: busy || !dirty || !valid }, busy ? t('account.saving') : t('models.save'))),
1982
+ ),
1983
+ )
1984
+ }
1985
+
1986
+ function BackupTools({ onRestored }) {
1987
+ const [includeCredentials, setIncludeCredentials] = useState(false)
1988
+ const [exportPassword, setExportPassword] = useState('')
1989
+ const [confirmation, setConfirmation] = useState('')
1990
+ const [text, setText] = useState('')
1991
+ const [password, setPassword] = useState('')
1992
+ const [preview, setPreview] = useState(null)
1993
+ const [busy, setBusy] = useState(null)
1994
+ const [notice, setNotice] = useState(null)
1995
+ const fileInput = useRef(null)
1996
+ const validPassword = exportPassword.length >= 8 && exportPassword.length <= 256 && exportPassword === confirmation
1997
+ const exportBackup = async (event) => {
1998
+ event.preventDefault()
1999
+ if (busy || ((includeCredentials || exportPassword) && !validPassword)) return
2000
+ setBusy('export')
2001
+ setNotice(null)
2002
+ try {
2003
+ const result = await postRoute('/backup/export', { includeCredentials, password: exportPassword })
2004
+ if (!result.ok) throw new Error(result.error ?? t('backup.failed'))
2005
+ downloadJson(result.backup, `codearts-backup-${new Date().toISOString().slice(0, 10)}.json`)
2006
+ setExportPassword(''); setConfirmation('')
2007
+ setNotice({ kind: 'success', text: t('backup.exported') })
2008
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2009
+ }
2010
+ const inspect = async () => {
2011
+ if (busy || !text.trim()) return
2012
+ setBusy('preview'); setNotice(null); setPreview(null)
2013
+ try {
2014
+ const result = await postRoute('/backup/preview', { text, password })
2015
+ if (!result.ok) throw new Error(result.error ?? t('backup.failed'))
2016
+ setPreview(result)
2017
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2018
+ }
2019
+ const restore = async () => {
2020
+ if (!preview || busy) return
2021
+ setBusy('restore'); setNotice(null)
2022
+ try {
2023
+ const result = await postRoute('/backup/restore', { text, password })
2024
+ if (!result.ok) throw new Error(result.error ?? t('backup.failed'))
2025
+ setText(''); setPassword(''); setPreview(null)
2026
+ await onRestored()
2027
+ setNotice({ kind: 'success', text: t('backup.restored').replace('{added}', result.added).replace('{updated}', result.updated) })
2028
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2029
+ }
2030
+ return h('details', { className: 'dca-card dca-details' },
2031
+ h('summary', null, t('backup.title')),
2032
+ h('div', { className: 'dca-feature-stack' },
2033
+ h('p', { className: 'dca-hint' }, t('backup.hint')),
2034
+ h(FeatureNotice, { notice }),
2035
+ h('form', { className: 'dca-feature-stack', onSubmit: exportBackup },
2036
+ h('h3', { className: 'dca-subtitle' }, t('backup.export')),
2037
+ h('label', { className: 'dca-row' }, h('input', { type: 'checkbox', checked: includeCredentials, disabled: busy !== null, onChange: (event) => setIncludeCredentials(event.target.checked) }), t('backup.include')),
2038
+ h('div', { className: 'dca-feature-grid' },
2039
+ h('label', { className: 'dca-form-field' }, t('backup.exportPassword'), h('input', { className: 'dca-input', type: 'password', autoComplete: 'new-password', maxLength: 256, value: exportPassword, disabled: busy !== null, onChange: (event) => setExportPassword(event.target.value) })),
2040
+ h('label', { className: 'dca-form-field' }, t('backup.confirmPassword'), h('input', { className: 'dca-input', type: 'password', autoComplete: 'new-password', maxLength: 256, value: confirmation, disabled: busy !== null, onChange: (event) => setConfirmation(event.target.value) })),
2041
+ ),
2042
+ (includeCredentials || exportPassword) && !validPassword ? h('p', { className: 'dca-hint' }, t('backup.passwordHint')) : null,
2043
+ h('div', { className: 'dca-row' }, h('button', { className: 'dca-btn', type: 'submit', disabled: busy !== null || ((includeCredentials || Boolean(exportPassword)) && !validPassword) }, busy === 'export' ? t('common.loading') : t('backup.download'))),
2044
+ ),
2045
+ h('h3', { className: 'dca-subtitle' }, t('backup.restore')),
2046
+ h('div', { className: 'dca-row' },
2047
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null, onClick: () => fileInput.current?.click() }, t('backup.choose')),
2048
+ h('input', { ref: fileInput, type: 'file', accept: '.json,application/json', className: 'dca-file-input', disabled: busy !== null, onChange: async (event) => {
2049
+ const file = event.target.files?.[0]; event.target.value = ''
2050
+ if (!file) return
2051
+ setPreview(null); setNotice(null)
2052
+ try {
2053
+ if (file.size > 768 * 1024) throw new Error(t('backup.tooLarge'))
2054
+ setText(await file.text())
2055
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) }
2056
+ } }),
2057
+ ),
2058
+ h('label', { className: 'dca-form-field' }, t('backup.content'), h('textarea', { className: 'dca-input', rows: 4, maxLength: 786432, value: text, disabled: busy !== null, onChange: (event) => { setText(event.target.value); setPreview(null) } })),
2059
+ h('label', { className: 'dca-form-field' }, t('backup.importPassword'), h('input', { className: 'dca-input', type: 'password', autoComplete: 'off', maxLength: 256, value: password, disabled: busy !== null, onChange: (event) => { setPassword(event.target.value); setPreview(null) } })),
2060
+ h('div', { className: 'dca-row' }, h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null || !text.trim(), onClick: inspect }, busy === 'preview' ? t('common.loading') : t('backup.preview'))),
2061
+ preview ? h('div', { className: 'dca-feature-stack dca-preview-box', role: 'region', 'aria-label': t('backup.preview') },
2062
+ h('p', null, t('backup.summary').replace('{settings}', preview.changes.length).replace('{added}', preview.accounts.added).replace('{updated}', preview.accounts.updated)),
2063
+ h('p', { className: 'dca-hint' }, t('backup.mergeHint')),
2064
+ h('details', { className: 'dca-details' }, h('summary', null, t('backup.changes')), h('pre', { className: 'dca-pre', tabIndex: 0 }, JSON.stringify(preview.preferences, null, 2))),
2065
+ h('div', { className: 'dca-row' },
2066
+ h('button', { type: 'button', className: 'dca-btn dca-btn-primary', disabled: busy !== null, onClick: restore }, busy === 'restore' ? t('common.loading') : t('backup.confirm')),
2067
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null, onClick: () => { setPreview(null); setText(''); setPassword('') } }, t('pool.cancel')),
2068
+ ),
2069
+ ) : null,
2070
+ ),
2071
+ )
2072
+ }
2073
+
2074
+ function UsageTab({ usage, onRefresh, onPreferencesSaved }) {
2075
+ const [busy, setBusy] = useState(null)
2076
+ const [notice, setNotice] = useState(null)
2077
+ const [query, setQuery] = useState('')
2078
+ const [filter, setFilter] = useState('all')
2079
+ const records = usage.records ?? []
2080
+ const visible = records.filter((row) => (filter === 'all' || row.status === filter) && row.model.toLowerCase().includes(query.trim().toLowerCase()))
2081
+ const today = records.filter((row) => new Date(row.at).toDateString() === new Date().toDateString())
2082
+ const completed = today.filter((row) => row.status !== 'aborted')
2083
+ const successRate = completed.length ? `${Math.round(completed.filter((row) => row.status === 'success').length / completed.length * 100)}%` : '—'
2084
+ const action = async (kind) => {
2085
+ if (busy) return
2086
+ if (kind === 'clear' && !window.confirm(t('usage.clearConfirm'))) return
2087
+ setBusy(kind); setNotice(null)
2088
+ try {
2089
+ if (kind === 'toggle') {
2090
+ const result = await postRoute('/preferences/save', { usageEnabled: !usage.enabled })
2091
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
2092
+ await onPreferencesSaved()
2093
+ } else if (kind === 'clear') {
2094
+ const result = await postRoute('/usage/clear', {})
2095
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
2096
+ }
2097
+ await onRefresh()
2098
+ setNotice({ kind: 'success', text: t(kind === 'clear' ? 'usage.cleared' : 'features.saved') })
2099
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2100
+ }
2101
+ return h('div', { className: 'dca-page' },
2102
+ h('div', { className: 'dca-pool-card-head' }, h('h2', { className: 'dca-title' }, t('usage.title')),
2103
+ h('div', { className: 'dca-row' },
2104
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null, onClick: () => action('refresh') }, t('features.refresh')),
2105
+ h('button', { type: 'button', className: 'dca-btn dca-danger', disabled: busy !== null || !records.length, onClick: () => action('clear') }, t('usage.clear')),
2106
+ ),
2107
+ ),
2108
+ h('label', { className: 'dca-row' }, h('input', { type: 'checkbox', checked: usage.enabled === true, disabled: busy !== null, onChange: () => action('toggle') }), t('usage.enabled')),
2109
+ h('p', { className: 'dca-hint' }, t('usage.hint')),
2110
+ h(FeatureNotice, { notice }),
2111
+ h('div', { className: 'dca-diagnostic-summary' },
2112
+ h('div', { className: 'dca-summary-item' }, h('strong', null, t('usage.today')), h('span', { className: 'dca-num' }, String(today.length))),
2113
+ h('div', { className: 'dca-summary-item' }, h('strong', null, t('usage.successRate')), h('span', { className: 'dca-num' }, successRate)),
2114
+ h('div', { className: 'dca-summary-item' }, h('strong', null, t('usage.tokens')), h('span', { className: 'dca-num' }, `${today.reduce((sum, row) => sum + (row.inputTokens ?? 0) + (row.outputTokens ?? 0), 0)}`)),
2115
+ ),
2116
+ h('div', { className: 'dca-toolbar' },
2117
+ h('input', { className: 'dca-input dca-search', type: 'search', value: query, 'aria-label': t('usage.search'), placeholder: t('usage.search'), onChange: (event) => setQuery(event.target.value) }),
2118
+ h('select', { className: 'dca-input', value: filter, 'aria-label': t('usage.result'), onChange: (event) => setFilter(event.target.value) }, ...['all', 'success', 'error', 'aborted'].map((key) => h('option', { key, value: key }, t(`usage.${key}`)))),
2119
+ ),
2120
+ h('div', { className: 'dca-usage-table', role: 'region', tabIndex: 0, 'aria-label': t('usage.title') },
2121
+ h('table', null,
2122
+ h('thead', null, h('tr', null, ...['time', 'model', 'duration', 'input', 'output', 'result'].map((key) => h('th', { key, scope: 'col' }, t(`usage.${key}`))))),
2123
+ h('tbody', null, ...visible.map((row) => h('tr', { key: row.id },
2124
+ h('td', null, formatTime(row.at)), h('td', null, row.model), h('td', { className: 'dca-num' }, `${(row.durationMs / 1000).toFixed(1)}s`),
2125
+ h('td', { className: 'dca-num' }, row.inputTokens ?? '—'), h('td', { className: 'dca-num' }, row.outputTokens ?? '—'),
2126
+ h('td', null, t(`usage.${row.status}`)),
2127
+ ))),
2128
+ ),
2129
+ ),
2130
+ !visible.length ? h('p', { className: 'dca-hint', role: 'status' }, t('usage.empty')) : null,
2131
+ )
2132
+ }
2133
+
2134
+ // ── models tab ─────────────────────────────────────────────────────────
2135
+
2136
+ /**
2137
+ * The model catalog.
2138
+ *
2139
+ * Row layout follows the reference: line one carries the enable checkbox,
2140
+ * the name, its ratio and any badge on the left, with the row's own flags on
2141
+ * the right; line two carries the facts on the left, indented to the name so
2142
+ * the two lines read as one block rather than a checkbox beside two toppled
2143
+ * fragments.
2144
+ */
2145
+ /**
2146
+ * The model catalog.
2147
+ *
2148
+ * Each row carries its own selection checkbox and its own capability
2149
+ * switches, exactly as the reference does — a model row is where a user
2150
+ * decides what this provider may send, so the controls live on the row
2151
+ * rather than behind an edit dialog. Edits are local until saved; the
2152
+ * reference uses the same save/discard posture for this panel.
2153
+ */
2154
+ function ModelsTab({ models, onRefresh, onSaved }) {
2155
+ const [busy, setBusy] = useState(null)
2156
+ const [query, setQuery] = useState('')
2157
+ const [filter, setFilter] = useState('all')
2158
+ const [sort, setSort] = useState('default')
2159
+ const [imagesOnly, setImagesOnly] = useState(false)
2160
+ const [reasoningOnly, setReasoningOnly] = useState(false)
2161
+ const [presetId, setPresetId] = useState('')
2162
+ const [presetName, setPresetName] = useState('')
2163
+ const [presetPreview, setPresetPreview] = useState(null)
2164
+ const [savedPresets, setSavedPresets] = useState(null)
2165
+ useEffect(() => { setSavedPresets(null) }, [models.presets])
2166
+ const [notice, setNotice] = useState(null)
2167
+ /** Local draft: null means "no unsaved edits". */
2168
+ const [enabledIds, setEnabledIds] = useState(null)
2169
+ const [overrides, setOverrides] = useState({})
2170
+
2171
+ const list = models?.models ?? []
2172
+ const selectionIsDefault = models?.enabledIds === null || models?.enabledIds === undefined
2173
+ // The rows as they should LOOK: the draft when there is one, the saved
2174
+ // state otherwise. Without this the first paint after an edit would snap
2175
+ // back to the saved state.
2176
+ const isEnabled = (id) => {
2177
+ if (enabledIds !== null) return enabledIds.includes(id)
2178
+ // No draft: trust what the Host said about the saved selection. When it
2179
+ // sent no list at all, everything is offered.
2180
+ const saved = models?.enabledIds
2181
+ if (Array.isArray(saved)) return saved.includes(id)
2182
+ return true
2183
+ }
2184
+ const dirty = (enabledIds !== null && list.some((model) =>
2185
+ enabledIds.includes(model.id) !== (selectionIsDefault || models.enabledIds.includes(model.id)))) ||
2186
+ Object.entries(overrides).some(([id, patch]) => {
2187
+ const model = list.find((entry) => entry.id === id)
2188
+ if (!model) return false
2189
+ const saved = { images: model.supportsImages, allowOff: model.allowOff !== false, defaultStrength: model.defaultStrength, ...model.overrides }
2190
+ return Object.entries(patch).some(([key, value]) => value !== saved[key])
2191
+ })
2192
+ const selectedIds = list.filter((model) => isEnabled(model.id)).map((model) => model.id)
2193
+ const selectedCount = selectedIds.length
2194
+ const normalizedQuery = query.trim().toLowerCase()
2195
+ const visibleModels = list.filter((model) =>
2196
+ (filter !== 'enabled' || isEnabled(model.id)) &&
2197
+ (!imagesOnly || (overrides[model.id]?.images ?? model.supportsImages) === true) &&
2198
+ (!reasoningOnly || model.strengths?.length > 0) &&
2199
+ (!normalizedQuery || `${model.name} ${model.id}`.toLowerCase().includes(normalizedQuery)))
2200
+ if (sort === 'ratio') {
2201
+ const ratioOf = (model) => {
2202
+ const value = Number.parseFloat(String(model.ratio ?? '').trim().replace(/^x/i, ''))
2203
+ return Number.isFinite(value) ? value : Infinity
2204
+ }
2205
+ visibleModels.sort((left, right) => ratioOf(left) - ratioOf(right))
2206
+ } else if (sort === 'name') {
2207
+ visibleModels.sort((left, right) => left.name.localeCompare(right.name))
2208
+ }
2209
+
2210
+ const toggle = useCallback((id, next) => {
2211
+ setNotice(null)
2212
+ setEnabledIds((current) => {
2213
+ const base = current ?? (selectionIsDefault ? list.map((m) => m.id) : (models?.enabledIds ?? []))
2214
+ return next ? [...new Set([...base, id])] : base.filter((entry) => entry !== id)
2215
+ })
2216
+ }, [list, models, selectionIsDefault])
2217
+
2218
+ const setOverride = useCallback((id, patch) => {
2219
+ setNotice(null)
2220
+ setOverrides((current) => ({
2221
+ ...current,
2222
+ [id]: { ...(current[id] ?? {}), ...patch },
2223
+ }))
2224
+ }, [])
2225
+
2226
+ const save = useCallback(async () => {
2227
+ setBusy('save')
2228
+ try {
2229
+ const payload = {
2230
+ // A draft that matches the whole roster is the same thing as "all",
2231
+ // and storing `null` keeps the user's intent ("everything") intact
2232
+ // so a model the upstream adds later still appears.
2233
+ enabledIds:
2234
+ enabledIds === null
2235
+ ? (selectionIsDefault ? null : (models?.enabledIds ?? []))
2236
+ : selectedIds.length === list.length
2237
+ ? null
2238
+ : selectedIds,
2239
+ overrides: Object.fromEntries(list.map((model) => [model.id, { ...model.overrides, ...overrides[model.id] }])),
2240
+ }
2241
+ const result = await postRoute('/models/select', payload)
2242
+ // NOT just `result.ok`: a mis-routed request can land on a read route
2243
+ // that also answers `ok: true`, which makes a save look successful
2244
+ // while nothing was written. The acknowledgement carries the counts.
2245
+ if (result.ok && typeof result.enabled === 'number') {
2246
+ const reloaded = await onSaved()
2247
+ if (reloaded) {
2248
+ setEnabledIds(null)
2249
+ setOverrides({})
2250
+ }
2251
+ setNotice(reloaded
2252
+ ? { kind: 'success', text: t('models.saved') }
2253
+ : { kind: 'error', text: t('models.savedReloadFailed') })
2254
+ } else {
2255
+ setNotice({ kind: 'error', text: result.error ?? t('models.saveFailed') })
2256
+ }
2257
+ } catch (error) {
2258
+ setNotice({ kind: 'error', text: `${t('models.saveFailed')}:${error.message}` })
2259
+ } finally {
2260
+ setBusy(null)
2261
+ }
2262
+ }, [enabledIds, overrides, list, models, onSaved, selectedIds, selectionIsDefault])
2263
+
2264
+ const discard = useCallback(() => {
2265
+ setEnabledIds(null)
2266
+ setOverrides({})
2267
+ setNotice(null)
2268
+ }, [])
2269
+
2270
+ const refresh = useCallback(async () => {
2271
+ setBusy('refresh')
2272
+ try {
2273
+ const result = await getRoute('/refresh')
2274
+ const reloaded = await onRefresh()
2275
+ setNotice(result.ok && reloaded
2276
+ ? { kind: 'success', text: t('models.refreshed') }
2277
+ : { kind: 'error', text: result.error ?? t('models.refreshFailed') })
2278
+ } catch (error) {
2279
+ setNotice({ kind: 'error', text: `${t('models.refreshFailed')}:${error.message}` })
2280
+ } finally {
2281
+ setBusy(null)
2282
+ }
2283
+ }, [onRefresh])
2284
+
2285
+ const ratioOf = (model) => {
2286
+ const value = Number.parseFloat(String(model.ratio ?? '').trim().replace(/^x/i, ''))
2287
+ return Number.isFinite(value) ? value : Infinity
2288
+ }
2289
+ const makeBuiltin = (id, name, targets, deep = false) => ({
2290
+ id, name, enabledModelIds: targets.map((model) => model.id),
2291
+ modelOverrides: Object.fromEntries(list.map((model) => {
2292
+ const base = model.defaults ?? model
2293
+ const strengths = model.strengths ?? []
2294
+ const strength = deep && targets.some((entry) => entry.id === model.id)
2295
+ ? (strengths.includes('max') ? 'max' : strengths.at(-1))
2296
+ : base.defaultStrength
2297
+ return [model.id, { images: base.supportsImages === true, allowOff: base.allowOff !== false,
2298
+ ...(strengths.includes(strength) ? { defaultStrength: strength } : strengths.length ? { defaultStrength: strengths[0] } : {}),
2299
+ }]
2300
+ })),
2301
+ })
2302
+ const presets = [
2303
+ makeBuiltin('builtin:daily', t('presets.daily'), [...list].sort((a, b) => ratioOf(a) - ratioOf(b)).slice(0, 3)),
2304
+ makeBuiltin('builtin:deep', t('presets.deep'), list.filter((model) => model.strengths?.length), true),
2305
+ makeBuiltin('builtin:images', t('presets.images'), list.filter((model) => (model.defaults ?? model).supportsImages)),
2306
+ ...(savedPresets ?? models.presets ?? []),
2307
+ ]
2308
+ const selectedPreset = presets.find((entry) => entry.id === presetId)
2309
+ const previewIds = presetPreview ? (presetPreview.enabledModelIds ?? list.map((entry) => entry.id)).filter((id) => list.some((entry) => entry.id === id)) : []
2310
+ const snapshotOverrides = () => Object.fromEntries(list.map((model) => {
2311
+ const patch = { ...model.overrides, ...overrides[model.id] }
2312
+ const strengths = model.strengths ?? []
2313
+ const strength = patch.defaultStrength ?? model.defaultStrength
2314
+ return [model.id, { images: patch.images ?? model.supportsImages, allowOff: patch.allowOff ?? model.allowOff ?? true,
2315
+ ...(strengths.length ? { defaultStrength: strengths.includes(strength) ? strength : strengths[0] } : {}),
2316
+ }]
2317
+ }))
2318
+ const savePreset = async () => {
2319
+ if (!presetName.trim() || !selectedCount || busy) return
2320
+ setBusy('preset')
2321
+ try {
2322
+ const result = await postRoute('/presets', { action: 'save', name: presetName.trim(), enabledModelIds: selectedCount === list.length ? null : selectedIds, modelOverrides: snapshotOverrides() })
2323
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
2324
+ setSavedPresets(result.presets); setPresetName('')
2325
+ setNotice({ kind: 'success', text: t('features.saved') })
2326
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2327
+ }
2328
+ const deletePreset = async () => {
2329
+ if (!selectedPreset || selectedPreset.id.startsWith('builtin:') || busy || !window.confirm(t('presets.deleteConfirm'))) return
2330
+ setBusy('preset')
2331
+ try {
2332
+ const result = await postRoute('/presets', { action: 'delete', id: selectedPreset.id })
2333
+ if (!result.ok) throw new Error(result.error ?? t('common.retry'))
2334
+ setSavedPresets(result.presets); setPresetId(''); setPresetPreview(null)
2335
+ setNotice({ kind: 'success', text: t('features.saved') })
2336
+ } catch (error) { setNotice({ kind: 'error', text: error.message }) } finally { setBusy(null) }
2337
+ }
2338
+ const applyPreset = () => {
2339
+ if (!previewIds.length || busy) return
2340
+ setEnabledIds(previewIds)
2341
+ setOverrides(Object.fromEntries(Object.entries(presetPreview.modelOverrides ?? {}).filter(([id]) => list.some((model) => model.id === id))))
2342
+ setPresetPreview(null)
2343
+ setNotice({ kind: 'success', text: t('presets.applied') })
2344
+ }
2345
+
2346
+ const source = catalogSourceLabel(models.source)
2347
+
2348
+ return h(
2349
+ 'div',
2350
+ { className: 'dca-page dca-model-page' },
2351
+ h(
2352
+ 'div',
2353
+ { className: 'dca-pool-card-head' },
2354
+ h(
2355
+ 'div',
2356
+ null,
2357
+ h(
2358
+ 'h2',
2359
+ { className: 'dca-title' },
2360
+ t('models.title'),
2361
+ dirty ? h('span', { className: 'dca-dirty' }, t('models.dirty')) : null,
2362
+ ),
2363
+ ),
2364
+ h(
2365
+ 'div',
2366
+ { className: 'dca-pool-actions-group' },
2367
+ h('span', { className: 'dca-pool-tag' }, source),
2368
+ h(
2369
+ 'button',
2370
+ { type: 'button', className: 'dca-btn', onClick: refresh, disabled: busy !== null },
2371
+ busy === 'refresh' ? t('account.refreshing') : t('models.refresh'),
2372
+ ),
2373
+ ),
2374
+ ),
2375
+ h('div', { className: 'dca-catalog-meta' },
2376
+ h('span', null, t('models.selectedCount').replace('{enabled}', selectedCount).replace('{total}', list.length)),
2377
+ h('span', null, `${t('models.refreshedAt')}:${formatTime(models?.refreshedAt)}`),
2378
+ ),
2379
+ h('div', { className: 'dca-toolbar' },
2380
+ h('input', {
2381
+ type: 'search', className: 'dca-input dca-search', value: query,
2382
+ placeholder: t('models.search'), 'aria-label': t('models.search'),
2383
+ onChange: (event) => setQuery(event.target.value),
2384
+ }),
2385
+ h('div', { className: 'dca-filter-group', role: 'group', 'aria-label': t('models.title') },
2386
+ ...[['all', 'models.all'], ['enabled', 'models.enabledOnly']].map(([value, key]) =>
2387
+ h('button', { type: 'button', key: value, className: 'dca-filter',
2388
+ 'aria-pressed': filter === value, onClick: () => setFilter(value),
2389
+ }, t(key))),
2390
+ ),
2391
+ h('select', { className: 'dca-input dca-sort', value: sort, 'aria-label': t('models.sort'),
2392
+ onChange: (event) => setSort(event.target.value),
2393
+ }, ...[['default', 'models.sortDefault'], ['ratio', 'models.sortRatio'], ['name', 'models.sortName']].map(([value, key]) =>
2394
+ h('option', { key: value, value }, t(key)))),
2395
+ ),
2396
+ h('div', { className: 'dca-row' },
2397
+ h('label', { className: 'dca-row' }, h('input', { type: 'checkbox', checked: imagesOnly, onChange: (event) => setImagesOnly(event.target.checked) }), t('models.imagesOnly')),
2398
+ h('label', { className: 'dca-row' }, h('input', { type: 'checkbox', checked: reasoningOnly, onChange: (event) => setReasoningOnly(event.target.checked) }), t('models.reasoningOnly')),
2399
+ ),
2400
+ h('details', { className: 'dca-card dca-details' },
2401
+ h('summary', null, t('presets.title')),
2402
+ h('div', { className: 'dca-feature-stack' },
2403
+ h('div', { className: 'dca-preset-row' },
2404
+ h('select', { className: 'dca-input', value: presetId, disabled: busy !== null, 'aria-label': t('presets.title'), onChange: (event) => { setPresetId(event.target.value); setPresetPreview(null) } },
2405
+ h('option', { value: '' }, t('presets.choose')), ...presets.map((preset) => h('option', { key: preset.id, value: preset.id }, preset.name)),
2406
+ ),
2407
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null || !selectedPreset, onClick: () => setPresetPreview(selectedPreset) }, t('presets.preview')),
2408
+ selectedPreset && !selectedPreset.id.startsWith('builtin:') ? h('button', { type: 'button', className: 'dca-btn dca-danger', disabled: busy !== null, onClick: deletePreset }, t('presets.delete')) : null,
2409
+ ),
2410
+ presetPreview ? h('div', { className: 'dca-preview-box dca-feature-stack' },
2411
+ h('p', { className: 'dca-hint' }, t('presets.previewHint').replace('{count}', previewIds.length)),
2412
+ !previewIds.length ? h('p', { className: 'dca-hint' }, t('presets.noModels')) : null,
2413
+ presetPreview.enabledModelIds && previewIds.length < presetPreview.enabledModelIds.length ? h('p', { className: 'dca-hint' }, t('presets.missing')) : null,
2414
+ h('ul', { className: 'dca-preset-preview' }, ...previewIds.map((id) => h('li', { key: id }, list.find((model) => model.id === id).name))),
2415
+ h('details', { className: 'dca-details' }, h('summary', null, t('backup.changes')), h('pre', { className: 'dca-pre', tabIndex: 0 }, JSON.stringify(presetPreview.modelOverrides, null, 2))),
2416
+ h('div', { className: 'dca-row' },
2417
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null || !previewIds.length, onClick: applyPreset }, t('presets.apply')),
2418
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null, onClick: () => setPresetPreview(null) }, t('pool.cancel')),
2419
+ ),
2420
+ ) : null,
2421
+ h('div', { className: 'dca-preset-row' },
2422
+ h('input', { className: 'dca-input', value: presetName, maxLength: 48, placeholder: t('presets.name'), 'aria-label': t('presets.name'), disabled: busy !== null, onChange: (event) => setPresetName(event.target.value) }),
2423
+ h('button', { type: 'button', className: 'dca-btn', disabled: busy !== null || !presetName.trim() || !selectedCount, onClick: savePreset }, t('presets.save')),
2424
+ ),
2425
+ ),
2426
+ ),
2427
+ h('details', { className: 'dca-details' },
2428
+ h('summary', null, t('models.about')),
2429
+ h('div', { className: 'dca-details-body' },
2430
+ h('p', { className: 'dca-hint' }, t('models.hint')),
2431
+ h('p', { className: 'dca-hint' }, t('models.pickerHint')),
2432
+ ),
2433
+ ),
2434
+ models?.error ? h('p', { className: 'dca-msg dca-msg-warn' }, models.error) : null,
2435
+ h(
2436
+ 'div',
2437
+ { className: 'dca-models' },
2438
+ list.length === 0
2439
+ ? h('p', { className: 'dca-hint' }, t('models.empty'))
2440
+ : visibleModels.length === 0
2441
+ ? h('div', { className: 'dca-empty', role: 'status' },
2442
+ h('p', { className: 'dca-hint' }, t('models.noMatches')),
2443
+ h('button', { type: 'button', className: 'dca-btn', onClick: () => { setQuery(''); setFilter('all'); setImagesOnly(false); setReasoningOnly(false) } }, t('models.clearFilters')),
2444
+ )
2445
+ : h(
2446
+ React.Fragment,
2447
+ null,
2448
+ ...visibleModels.map((model) => {
2449
+ const on = isEnabled(model.id)
2450
+ const override = { ...model.overrides, ...overrides[model.id] }
2451
+ const images = typeof override.images === 'boolean' ? override.images : model.supportsImages
2452
+ const strengths = model.strengths ?? []
2453
+ const preferredStrength = override.defaultStrength ?? model.defaultStrength
2454
+ const defaultStrength = strengths.includes(preferredStrength) ? preferredStrength : strengths[0]
2455
+ return h(
2456
+ 'div',
2457
+ { key: model.id, className: `dca-model${on ? '' : ' dca-model-off'}` },
2458
+ h(
2459
+ 'div',
2460
+ { className: 'dca-model-head' },
2461
+ h(
2462
+ 'div',
2463
+ { className: 'dca-model-name' },
2464
+ h('input', {
2465
+ type: 'checkbox',
2466
+ checked: on,
2467
+ 'aria-label': model.name,
2468
+ className: 'dca-model-check',
2469
+ disabled: busy !== null,
2470
+ onChange: (event) => toggle(model.id, event.target.checked),
2471
+ }),
2472
+ h('b', null, model.name),
2473
+ model.ratio
2474
+ ? h(
2475
+ 'span',
2476
+ { className: 'dca-model-ratio' },
2477
+ `x${String(model.ratio).replace(/x$/i, '')}`,
2478
+ )
2479
+ : null,
2480
+ ),
2481
+ h(
2482
+ 'div',
2483
+ { className: 'dca-model-controls' },
2484
+ h(
2485
+ 'label',
2486
+ { className: 'dca-model-flag' },
2487
+ h('input', {
2488
+ type: 'checkbox',
2489
+ checked: images === true,
2490
+ disabled: !on || busy !== null,
2491
+ onChange: (event) =>
2492
+ setOverride(model.id, { images: event.target.checked }),
2493
+ }),
2494
+ t('models.images'),
2495
+ ),
2496
+ strengths.length
2497
+ ? h(
2498
+ 'label',
2499
+ { className: 'dca-model-flag' },
2500
+ h('input', {
2501
+ type: 'checkbox',
2502
+ checked: (override.allowOff ?? model.allowOff) !== false,
2503
+ disabled: !on || busy !== null,
2504
+ onChange: (event) =>
2505
+ setOverride(model.id, { allowOff: event.target.checked }),
2506
+ }),
2507
+ t('models.allowOff'),
2508
+ )
2509
+ : null,
2510
+ ),
2511
+ ),
2512
+ h(
2513
+ 'div',
2514
+ { className: 'dca-model-details' },
2515
+ h(
2516
+ 'div',
2517
+ { className: 'dca-model-meta' },
2518
+ h(
2519
+ 'span',
2520
+ { className: 'dca-num' },
2521
+ `${t('models.colContext')} ${formatTokens(model.context)}`,
2522
+ ),
2523
+ h(
2524
+ 'span',
2525
+ { className: 'dca-num' },
2526
+ `${t('models.colOutput')} ${formatTokens(model.maxOutput)}`,
2527
+ ),
2528
+ // The default thinking level is a CHOICE, not a caption:
2529
+ // a user running a reasoning model wants to decide how
2530
+ // much it thinks before each request, and the picker
2531
+ // cannot express a per-model default on its own.
2532
+ strengths.length
2533
+ ? h(
2534
+ 'label',
2535
+ { className: 'dca-effort' },
2536
+ h('span', null, t('models.effort')),
2537
+ h(
2538
+ 'select',
2539
+ {
2540
+ className: 'dca-effort-select',
2541
+ value: defaultStrength,
2542
+ disabled: !on || busy !== null,
2543
+ 'aria-label': `${t('models.effort')} — ${model.name}`,
2544
+ onChange: (event) =>
2545
+ setOverride(model.id, { defaultStrength: event.target.value }),
2546
+ },
2547
+ ...strengths.map((level) =>
2548
+ h('option', { key: level, value: level }, effortLabel(level)),
2549
+ ),
2550
+ ),
2551
+ )
2552
+ : null,
2553
+ h('span', { className: 'dca-id' }, model.id),
2554
+ ),
2555
+ ),
2556
+ )
2557
+ }),
2558
+ ),
2559
+ ),
2560
+ h('p', { className: 'dca-hint' }, t('models.footnote')),
2561
+
2562
+ // The action bar is ALWAYS present and merely disabled when there is
2563
+ // nothing to save. A bar that appears only once something is dirty moves
2564
+ // under the pointer exactly when the user is looking for it.
2565
+ h(
2566
+ 'div',
2567
+ { className: 'dca-model-actions' },
2568
+ h('span', {
2569
+ className: `dca-save-status${notice?.kind === 'error' ? ' dca-save-status-error' : ''}`,
2570
+ role: notice?.kind === 'error' ? 'alert' : 'status', 'aria-live': 'polite',
2571
+ }, busy === 'save' ? t('account.saving') : (notice?.text ?? (selectedCount === 0 ? t('models.needOne') : t(dirty ? 'models.unsaved' : 'models.clean')))),
2572
+ h(
2573
+ 'div',
2574
+ { className: 'dca-model-actions-buttons' },
2575
+ h(
2576
+ 'button',
2577
+ {
2578
+ type: 'button',
2579
+ className: 'dca-btn',
2580
+ disabled: !dirty || busy !== null,
2581
+ onClick: discard,
2582
+ },
2583
+ t('models.discard'),
2584
+ ),
2585
+ h(
2586
+ 'button',
2587
+ {
2588
+ type: 'button',
2589
+ className: 'dca-btn dca-btn-primary',
2590
+ // Never let the last enabled model be removed: an empty picker
2591
+ // has no model to select and no way back from inside the picker.
2592
+ disabled: !dirty || busy !== null || selectedCount === 0,
2593
+ onClick: save,
2594
+ },
2595
+ busy === 'save' ? t('account.saving') : t('models.save'),
2596
+ ),
2597
+ ),
2598
+ ),
2599
+ )
2600
+ }
2601
+
2602
+ // ── diagnostics tab ────────────────────────────────────────────────────
2603
+
2604
+ function DiagnosticsTab({ status, account, accountError }) {
2605
+ const [copyNotice, setCopyNotice] = useState(null)
2606
+ const [reportOpen, setReportOpen] = useState(false)
2607
+ const reportText = JSON.stringify(diagnosticReport(status, account), null, 2)
2608
+ const catalogSummary = status.catalog?.source === 'fallback' ? 'diag.catalogFallback'
2609
+ : status.catalog?.source === 'cache' ? 'diag.catalogCached'
2610
+ : status.catalog?.source === 'gateway' && !status.catalog.error ? 'diag.catalogSynced'
2611
+ : 'diag.catalogIssue'
2612
+
2613
+ const errors = [status?.credential?.error, status?.catalog?.error, account?.error, accountError].filter(Boolean)
2614
+ const copyReport = async () => {
2615
+ try {
2616
+ if (!navigator.clipboard?.writeText) throw new Error('clipboard unavailable')
2617
+ await navigator.clipboard.writeText(reportText)
2618
+ setCopyNotice({ kind: 'success', text: t('diag.copied') })
2619
+ } catch {
2620
+ setReportOpen(true)
2621
+ setCopyNotice({ kind: 'error', text: t('diag.copyFailed') })
2622
+ }
2623
+ }
2624
+ // `mono` marks a machine value a user copies verbatim; `bad` marks a field
2625
+ // that is reporting a failure, so a wall of same-coloured rows still shows
2626
+ // where the problem is. Both are the reference's own conventions.
2627
+ const rows = [
2628
+ { label: t('diag.provider'), value: status?.provider ?? '—' },
2629
+ { label: t('diag.gateway'), value: status?.settings?.gateway ?? t('diag.gatewayDefault'), mono: true },
2630
+ { label: t('diag.credentialPath'), value: status?.credential?.pathInUse ?? status?.credential?.path ?? '—', mono: true },
2631
+ { label: t('models.source'), value: catalogSourceLabel(status?.catalog?.source) },
2632
+ { label: t('models.count'), value: String(status?.catalog?.models ?? 0) },
2633
+ { label: t('models.refreshedAt'), value: formatTime(status?.catalog?.refreshedAt) },
2634
+ {
2635
+ label: t('diag.catalogError'),
2636
+ value: status?.catalog?.error ?? t('diag.none'),
2637
+ bad: Boolean(status?.catalog?.error),
2638
+ },
2639
+ {
2640
+ label: t('diag.credentialError'),
2641
+ value: status?.credential?.error ?? t('diag.none'),
2642
+ bad: Boolean(status?.credential?.error),
2643
+ },
2644
+ // The settings-page gates, reported rather than guessed: without a Config
2645
+ // schema the Host emits no namespace, and Settings → Models then hides
2646
+ // this provider's row with no error anywhere.
2647
+ {
2648
+ label: t('diag.configSchema'),
2649
+ value: status?.registration?.configSchema
2650
+ ? (status.registration.settingsNs ?? t('diag.none'))
2651
+ : t('diag.schemaMissing'),
2652
+ bad: status?.registration?.configSchema !== true,
2653
+ mono: status?.registration?.configSchema === true,
2654
+ },
2655
+ ]
2656
+
2657
+ return h(
2658
+ 'div', { className: 'dca-page' },
2659
+ h('div', { className: 'dca-pool-card-head' },
2660
+ h('h2', { className: 'dca-title' }, t('diag.title')),
2661
+ h('button', { type: 'button', className: 'dca-btn', onClick: copyReport }, t('diag.copy')),
2662
+ ),
2663
+ copyNotice ? h('p', { className: `dca-msg dca-msg-${copyNotice.kind === 'error' ? 'error' : 'ok'}`, role: 'status' }, copyNotice.text) : null,
2664
+ h('div', { className: 'dca-diagnostic-summary' },
2665
+ h('div', { className: 'dca-summary-item' },
2666
+ h('strong', null, t(status?.credential?.error ? 'diag.credentialIssue' : status?.credential?.configured ? 'diag.configured' : 'diag.notConfigured')),
2667
+ h('p', { className: 'dca-hint' }, status?.credential?.sourceLabel ?? t('account.sourceNone')),
2668
+ ),
2669
+ h('div', { className: 'dca-summary-item' },
2670
+ h('strong', null, t(catalogSummary)),
2671
+ h('p', { className: 'dca-hint' }, `${t('models.count')}:${status?.catalog?.models ?? 0}`),
2672
+ h('p', { className: 'dca-hint' }, `${t('models.refreshedAt')}:${formatTime(status?.catalog?.refreshedAt)}`),
2673
+ ),
2674
+ h('div', { className: 'dca-summary-item' },
2675
+ h('strong', null, t('diag.errors')),
2676
+ h('p', { className: errors.length ? 'dca-hint dca-danger' : 'dca-hint' }, errors.join(';') || t(account || accountError ? 'diag.noErrors' : 'common.loading')),
2677
+ ),
2678
+ ),
2679
+ h('details', { className: 'dca-card dca-details' },
2680
+ h('summary', null, t('diag.details')),
2681
+ h('div', { className: 'dca-diag' }, ...rows.map((row) =>
2682
+ h('div', { key: row.label, className: 'dca-diag-row' },
2683
+ h('span', { className: 'dca-diag-label' }, row.label),
2684
+ h('span', { className: `dca-diag-value${row.mono ? ' dca-diag-mono' : ''}${row.bad ? ' dca-diag-bad' : ''}` }, row.value),
2685
+ ),
2686
+ )),
2687
+ ),
2688
+ h('details', { className: 'dca-card dca-details', open: reportOpen, onToggle: (event) => setReportOpen(event.currentTarget.open) },
2689
+ h('summary', null, t('diag.reportTitle')),
2690
+ h('p', { className: 'dca-hint' }, t('diag.reportHint')),
2691
+ h('pre', { className: 'dca-pre', tabIndex: 0 }, reportText),
2692
+ ),
2693
+ )
2694
+ }
2695
+
2696
+ // ── the settings nav glyph ────────────────────────────────────────────
2697
+
2698
+ /**
2699
+ * The row's icon.
2700
+ *
2701
+ * The shell asks for a square edge and says whether this row is selected;
2702
+ * honouring both keeps the glyph on the same rhythm as the built-in rows'
2703
+ * own icons. It is registered under the SAME id as the settings section —
2704
+ * that pairing is how the shell knows which row the glyph belongs to, and an
2705
+ * unmatched id never renders at all.
2706
+ */
2707
+ function NavIcon(props) {
2708
+ const edge = typeof props?.size === 'number' ? props.size : 16
2709
+ return h('img', {
2710
+ src: NAV_ICON,
2711
+ alt: '',
2712
+ 'aria-hidden': true,
2713
+ width: edge,
2714
+ height: edge,
2715
+ style: {
2716
+ display: 'block',
2717
+ borderRadius: '4px',
2718
+ flexShrink: 0,
2719
+ opacity: props?.active === false ? 0.75 : 1,
2720
+ },
2721
+ })
2722
+ }
2723
+
2724
+ // ── the settings page ──────────────────────────────────────────────────
2725
+
2726
+ function SettingsPage() {
2727
+ const [tab, setTab] = useState('account')
2728
+ const [data, setData] = useState({})
2729
+ const [errors, setErrors] = useState({})
2730
+ const requests = useRef(new Map())
2731
+ const tabButtons = useRef({})
2732
+ const panelId = React.useId()
2733
+
2734
+ const loadRoute = useCallback(async (path, background = false) => {
2735
+ const previous = requests.current.get(path)
2736
+ if (previous && background) return false
2737
+ previous?.abort()
2738
+ const controller = new AbortController()
2739
+ requests.current.set(path, controller)
2740
+ setErrors((current) => ({ ...current, [path]: null }))
2741
+ try {
2742
+ const value = await getRoute(path, { signal: controller.signal })
2743
+ if (controller.signal.aborted) return false
2744
+ if (!value || (path !== '/account' && value.ok !== true)) {
2745
+ throw new Error(value?.error ?? t('common.retryHint'))
2746
+ }
2747
+ setData((current) => ({ ...current, [path]: value }))
2748
+ return true
2749
+ } catch (error) {
2750
+ if (!controller.signal.aborted) {
2751
+ setErrors((current) => ({ ...current, [path]: `${path}:${error.message}` }))
2752
+ }
2753
+ return false
2754
+ } finally {
2755
+ if (requests.current.get(path) === controller) requests.current.delete(path)
2756
+ }
2757
+ }, [])
2758
+
2759
+ const loadAll = useCallback((background = false) => Promise.all(
2760
+ ['/status', '/models', '/account', '/accounts', '/preferences', '/usage'].map((path) => loadRoute(path, background)),
2761
+ ), [loadRoute])
2762
+ const loadPreferences = useCallback(async () => {
2763
+ const result = await loadRoute('/preferences')
2764
+ void loadRoute('/status', true)
2765
+ void loadRoute('/accounts', true)
2766
+ return result
2767
+ }, [loadRoute])
2768
+ const loadUsage = useCallback(() => loadRoute('/usage'), [loadRoute])
2769
+ const loadModels = useCallback(() => loadRoute('/models'), [loadRoute])
2770
+ const refreshModels = useCallback(() => {
2771
+ void loadRoute('/status', true)
2772
+ return loadModels()
2773
+ }, [loadModels, loadRoute])
2774
+
2775
+ useEffect(() => {
2776
+ void loadAll(true)
2777
+ const timer = setInterval(() => void loadAll(true), 5 * 60 * 1000)
2778
+ const activeRequests = requests.current
2779
+ return () => {
2780
+ clearInterval(timer)
2781
+ for (const controller of activeRequests.values()) controller.abort()
2782
+ activeRequests.clear()
2783
+ }
2784
+ }, [loadAll])
2785
+
2786
+ const status = data['/status']
2787
+ const models = data['/models']
2788
+ const account = data['/account']
2789
+ const pool = data['/accounts']
2790
+ const preferences = data['/preferences']?.preferences
2791
+ const usage = data['/usage']
2792
+ const tabs = [
2793
+ { id: 'account', paths: ['/accounts', '/preferences'], content: pool && h(AccountTab, { status, pool, preferences, onChanged: loadAll, onPreferencesSaved: loadPreferences }) },
2794
+ { id: 'models', paths: ['/models'], content: models && h(ModelsTab, { models, onRefresh: refreshModels, onSaved: loadModels }) },
2795
+ { id: 'usage', paths: ['/usage', '/preferences'], content: usage && h(UsageTab, { usage, onRefresh: loadUsage, onPreferencesSaved: loadPreferences }) },
2796
+ { id: 'diagnostics', paths: ['/status', '/account'], content: status && h(DiagnosticsTab, { status, account, accountError: errors['/account'] }) },
2797
+ ]
2798
+
2799
+ return h(
2800
+ 'div',
2801
+ { className: 'dca-page' },
2802
+ h(
2803
+ 'div',
2804
+ { role: 'tablist', className: 'dca-tabs', 'aria-label': t('nav.label') },
2805
+ ...tabs.map(({ id }, index) => h(
2806
+ 'button',
2807
+ {
2808
+ key: id,
2809
+ type: 'button',
2810
+ role: 'tab',
2811
+ id: `${panelId}-tab-${id}`,
2812
+ ref: (button) => { tabButtons.current[id] = button },
2813
+ 'aria-selected': tab === id,
2814
+ 'aria-controls': `${panelId}-panel-${id}`,
2815
+ tabIndex: tab === id ? 0 : -1,
2816
+ className: `dca-tab${tab === id ? ' dca-tab-on' : ''}`,
2817
+ onClick: () => setTab(id),
2818
+ onKeyDown: (event) => {
2819
+ let nextIndex
2820
+ switch (event.key) {
2821
+ case 'ArrowRight': nextIndex = (index + 1) % tabs.length; break
2822
+ case 'ArrowLeft': nextIndex = (index - 1 + tabs.length) % tabs.length; break
2823
+ case 'Home': nextIndex = 0; break
2824
+ case 'End': nextIndex = tabs.length - 1; break
2825
+ default: return
2826
+ }
2827
+ event.preventDefault()
2828
+ const next = tabs[nextIndex].id
2829
+ setTab(next)
2830
+ tabButtons.current[next]?.focus()
2831
+ },
2832
+ },
2833
+ t(`tab.${id}`),
2834
+ )),
2835
+ ),
2836
+ // Keep the panels mounted so navigation preserves edits and filters.
2837
+ ...tabs.map(({ id, paths, content }) => {
2838
+ const error = paths.map((path) => errors[path]).filter(Boolean).join(';')
2839
+ const retry = () => Promise.all(paths.filter((path) => !data[path] || errors[path]).map((path) => loadRoute(path)))
2840
+ return h(
2841
+ 'div',
2842
+ { key: id, role: 'tabpanel', id: `${panelId}-panel-${id}`, 'aria-labelledby': `${panelId}-tab-${id}`, hidden: tab !== id, tabIndex: 0 },
2843
+ content ?? h(Pending, { error, onRetry: retry }),
2844
+ content && error ? h('div', { className: 'dca-section-error' },
2845
+ h('p', { className: 'dca-msg dca-msg-error', role: 'alert' }, error),
2846
+ h('button', { type: 'button', className: 'dca-btn', onClick: retry }, t('common.retry')),
2847
+ ) : null,
2848
+ )
2849
+ }),
2850
+ )
2851
+ }
2852
+
2853
+ // ── the composer chip ──────────────────────────────────────────────────
2854
+
2855
+ /**
2856
+ * The credit reading beside the composer.
2857
+ *
2858
+ * Rendered as a slot entry inside the composer dock, so it takes the
2859
+ * space the Host allocates instead of floating over other controls.
2860
+ */
2861
+ /**
2862
+ * Display names for reasoning levels.
2863
+ *
2864
+ * The picker already localises these via the adapter's reasoning metadata;
2865
+ * the model page printed the raw id, so the same level read `high` in one
2866
+ * place and 高 in the other.
2867
+ */
2868
+ const EFFORT_LABELS = {
2869
+ off: ['关闭', 'Off'],
2870
+ low: ['低', 'Low'],
2871
+ medium: ['中', 'Medium'],
2872
+ high: ['高', 'High'],
2873
+ max: ['最高', 'Max'],
2874
+ xhigh: ['极高', 'Extra high'],
2875
+ }
2876
+
2877
+ /** One reasoning level in the active language, falling back to its id. */
2878
+ function effortLabel(id) {
2879
+ const pair = EFFORT_LABELS[id]
2880
+ if (!pair) return id
2881
+ return isChinese() ? pair[0] : pair[1]
2882
+ }
2883
+
2884
+ /** Credits with the grouping a balance deserves: 7,424.92. */
2885
+ function formatCredits(value) {
2886
+ const n = Number(value)
2887
+ if (!Number.isFinite(n)) return '—'
2888
+ return n.toLocaleString(undefined, { maximumFractionDigits: 2 })
2889
+ }
2890
+
2891
+ /**
2892
+ * Which colour the row's dot takes.
2893
+ *
2894
+ * Green means "this account can serve a request right now", red means it
2895
+ * cannot — a failed probe or a credential the gateway rejected. Amber is
2896
+ * reserved for "usable but something to know" (nothing can be claimed, a
2897
+ * balance lapsing), so the panel does not paint a healthy account as broken.
2898
+ */
2899
+ function dotTone(account) {
2900
+ if (account.error) return ' dca-pop-dot-bad'
2901
+ return ' dca-pop-dot-ok'
2902
+ }
2903
+
2904
+ function ComposerChip(props) {
2905
+ const [usage, setUsage] = useState(null)
2906
+ const [open, setOpen] = useState(false)
2907
+ const [, setDismissalVersion] = useState(0)
2908
+ const [busy, setBusy] = useState(false)
2909
+ const container = useRef(null)
2910
+ const openSettings = props?.openSettings
2911
+
2912
+ // Only speak up when this session is actually pointed at a 码道 model.
2913
+ // Without this the readout would sit in every session's composer,
2914
+ // including sessions that can never route a request here — noise for
2915
+ // anyone not using this provider, and a misleading figure for anyone
2916
+ // who is using a different one.
2917
+ //
2918
+ // `next` wins over `lastUsed`: a selection that has landed but not yet
2919
+ // been sent is still the one the composer is displaying. Both are
2920
+ // optional, so a host without this projection simply renders the pill
2921
+ // (fail-open) rather than hiding a working readout.
2922
+ const projection = props?.useProjection ? props.useProjection('modelSelection') : undefined
2923
+ const selected = projection?.next ?? projection?.lastUsed
2924
+ const selectedProvider = typeof selected?.provider === 'string' ? selected.provider : undefined
2925
+ const ownsSelection = selectedProvider === undefined || selectedProvider === PROVIDER_ID
2926
+
2927
+ const load = useCallback(async () => {
2928
+ // Two reads: `/account` is the serving credential and the balance the
2929
+ // pill shows, `/accounts` is the pool the panel lists. Settled rather
2930
+ // than all — a pool read failing must not blank a working pill.
2931
+ const [accountR, poolR] = await Promise.allSettled([
2932
+ getRoute('/account'),
2933
+ getRoute('/accounts'),
2934
+ ])
2935
+ setUsage({
2936
+ ...(accountR.status === 'fulfilled' ? accountR.value : { ok: false }),
2937
+ pool: poolR.status === 'fulfilled' ? poolR.value : null,
2938
+ })
2939
+ }, [])
2940
+
2941
+ useEffect(() => {
2942
+ // Nothing is fetched while another provider is selected: the readout is
2943
+ // hidden then, and a 5-minute poll would ask the gateway on behalf of
2944
+ // every session in the app.
2945
+ if (!ownsSelection) return undefined
2946
+ void load()
2947
+ const timer = setInterval(() => void load(), 5 * 60 * 1000)
2948
+ return () => clearInterval(timer)
2949
+ }, [load, ownsSelection])
2950
+
2951
+ // Closing on an outside click keeps the panel from being modal: it is a
2952
+ // reading, not a task.
2953
+ useEffect(() => {
2954
+ if (!open) return undefined
2955
+ const onDown = (event) => {
2956
+ if (container.current && !container.current.contains(event.target)) setOpen(false)
2957
+ }
2958
+ const onKey = (event) => {
2959
+ if (event.key === 'Escape') setOpen(false)
2960
+ }
2961
+ document.addEventListener('mousedown', onDown)
2962
+ document.addEventListener('keydown', onKey)
2963
+ return () => {
2964
+ document.removeEventListener('mousedown', onDown)
2965
+ document.removeEventListener('keydown', onKey)
2966
+ }
2967
+ }, [open])
2968
+
2969
+ const refresh = useCallback(async () => {
2970
+ setBusy(true)
2971
+ try {
2972
+ await load()
2973
+ } finally {
2974
+ setBusy(false)
2975
+ }
2976
+ }, [load])
2977
+
2978
+ /** Move the pool to another account; the panel's rows call this. */
2979
+ const activateAccount = useCallback(async (account) => {
2980
+ setBusy(true)
2981
+ try {
2982
+ await postRoute('/accounts/activate', { id: account.id })
2983
+ await load()
2984
+ } finally {
2985
+ setBusy(false)
2986
+ }
2987
+ }, [load])
2988
+
2989
+ const accounts = usage?.pool?.accounts ?? []
2990
+ const alertKey = `dca-balance-alert:${usage?.accountId ?? usage?.source ?? 'current'}:${usage?.lowBalanceThreshold ?? 500}`
2991
+ let dismissed = (balanceDismissals.get(alertKey) ?? 0) > Date.now()
2992
+ try { dismissed ||= Number(window.localStorage.getItem(alertKey)) > Date.now() } catch {}
2993
+ useEffect(() => {
2994
+ if (usage && usage.lowBalance === false) {
2995
+ balanceDismissals.delete(alertKey)
2996
+ try { window.localStorage.removeItem(alertKey) } catch {}
2997
+ }
2998
+ }, [alertKey, usage?.lowBalance])
2999
+ const dismissAlert = () => {
3000
+ balanceDismissals.set(alertKey, Date.now() + 86400000)
3001
+ try { window.localStorage.setItem(alertKey, String(Date.now() + 86400000)) } catch {}
3002
+ setDismissalVersion((value) => value + 1)
3003
+ }
3004
+ const lowBalance = usage?.lowBalance === true
3005
+ const backupCount = accounts.filter((account) => !account.active && account.health?.state === 'available' && account.credit?.remain >= (usage?.lowBalanceThreshold ?? 500)).length
3006
+
3007
+ // Nothing to show until the Host answers, and nothing to show when no
3008
+ // credential is configured: an empty pill on every composer would be
3009
+ // noise for anyone not using this provider.
3010
+ if (!usage || usage.composerChip === false) return null
3011
+ if (!ownsSelection) return null
3012
+ // With a 码道 model selected but no usable credential, saying nothing was
3013
+ // the worst option: the user picked this provider and the readout simply
3014
+ // is not there. Show the state and where to fix it instead.
3015
+ const hasCredential = usage?.ok === true || usage?.source || usage?.account
3016
+ if (!hasCredential) {
3017
+ const body = [
3018
+ h('span', { key: 'm', 'aria-hidden': true, className: 'dca-chip-mark' }, '◈'),
3019
+ h('span', { key: 'l' }, t('chip.noCredential')),
3020
+ ]
3021
+ // No credential: the pill becomes the way to fix that. The jump is
3022
+ // soft-probed at press time, so it works whenever the settings shell is
3023
+ // present and does nothing when it is not.
3024
+ return h(
3025
+ 'div',
3026
+ { className: 'dca-chip' },
3027
+ h(
3028
+ 'button',
3029
+ {
3030
+ type: 'button',
3031
+ className: 'dca-chip-trigger',
3032
+ title: usage?.error ?? t('chip.noCredentialHint'),
3033
+ onClick: openSettings,
3034
+ },
3035
+ ...body,
3036
+ ),
3037
+ )
3038
+ }
3039
+
3040
+ const credits = usage.credit
3041
+ const label = credits
3042
+ ? `${t('chip.credits')} ${credits.remain}`
3043
+ : t('chip.loading')
3044
+
3045
+ return h(
3046
+ 'div',
3047
+ { ref: container, className: 'dca-chip' },
3048
+ h(
3049
+ 'button',
3050
+ {
3051
+ type: 'button',
3052
+ title: t('chip.panelTitle'),
3053
+ 'aria-haspopup': 'dialog',
3054
+ 'aria-expanded': open,
3055
+ onClick: () => setOpen((value) => !value),
3056
+ // Borderless at rest (see .dca-chip-trigger): this row is a strip of
3057
+ // compact controls, and a boxed pill among them reads as a form
3058
+ // field. Hover and focus come from the stylesheet, which inline
3059
+ // styles cannot express.
3060
+ className: `dca-chip-trigger${open ? ' dca-chip-trigger-on' : ''}${lowBalance ? ' dca-low-balance' : ''}`,
3061
+ },
3062
+ h('span', { 'aria-hidden': true, className: 'dca-chip-mark' }, '◈'),
3063
+ h('span', null, label),
3064
+ ),
3065
+ open
3066
+ ? h(
3067
+ 'div',
3068
+ {
3069
+ role: 'dialog',
3070
+ 'aria-label': t('chip.panelTitle'),
3071
+ className: 'dca-pop',
3072
+ },
3073
+ h(
3074
+ 'div',
3075
+ { className: 'dca-pop-head' },
3076
+ h('span', { className: 'dca-pop-title' }, t('chip.panelTitle')),
3077
+ h(
3078
+ 'button',
3079
+ {
3080
+ type: 'button',
3081
+ className: 'dca-pop-refresh',
3082
+ disabled: busy,
3083
+ title: t('chip.refreshHint'),
3084
+ 'aria-label': t('chip.refreshHint'),
3085
+ onClick: refresh,
3086
+ },
3087
+ h(
3088
+ 'svg',
3089
+ {
3090
+ className: `dca-pop-refresh-icon${busy ? ' dca-pop-refresh-icon-spin' : ''}`,
3091
+ viewBox: '0 0 16 16',
3092
+ width: 12,
3093
+ height: 12,
3094
+ fill: 'none',
3095
+ 'aria-hidden': 'true',
3096
+ focusable: 'false',
3097
+ },
3098
+ h('path', {
3099
+ d: 'M13.3 8a5.3 5.3 0 1 1-1.55-3.75',
3100
+ stroke: 'currentColor',
3101
+ strokeWidth: 1.5,
3102
+ strokeLinecap: 'round',
3103
+ }),
3104
+ h('path', {
3105
+ d: 'M13.3 2.2v3.1h-3.1',
3106
+ stroke: 'currentColor',
3107
+ strokeWidth: 1.5,
3108
+ strokeLinecap: 'round',
3109
+ strokeLinejoin: 'round',
3110
+ }),
3111
+ ),
3112
+ t('chip.refresh'),
3113
+ ),
3114
+ h(
3115
+ 'button',
3116
+ {
3117
+ type: 'button',
3118
+ className: 'dca-pop-settings',
3119
+ onClick: () => {
3120
+ openSettings()
3121
+ setOpen(false)
3122
+ },
3123
+ },
3124
+ h('span', { 'aria-hidden': true, className: 'dca-pop-settings-icon' }, '⚙'),
3125
+ t('chip.settings'),
3126
+ ),
3127
+ ),
3128
+ lowBalance && !dismissed ? h('div', { className: 'dca-balance-alert', role: 'status' },
3129
+ h('strong', null, t('reminder.low')),
3130
+ h('span', null, t('reminder.backups').replace('{count}', backupCount)),
3131
+ h('button', { type: 'button', className: 'dca-btn-xs', onClick: dismissAlert }, t('reminder.dismiss')),
3132
+ ) : null,
3133
+ // One row per account, in a real table so the balances line up in a
3134
+ // single right-aligned column. The serving account is a row, not a
3135
+ // header: "which account" and "how many credits" are the same fact
3136
+ // about the same thing, and splitting them made the panel read as
3137
+ // two unrelated blocks.
3138
+ accounts.length === 0
3139
+ ? h(
3140
+ 'p',
3141
+ { className: 'dca-pop-empty' },
3142
+ usage.credits ? formatBalance(usage.credits) : t('account.creditUnread'),
3143
+ )
3144
+ : h(
3145
+ 'table',
3146
+ { className: 'dca-pop-table' },
3147
+ h(
3148
+ 'thead',
3149
+ null,
3150
+ h(
3151
+ 'tr',
3152
+ null,
3153
+ h('th', { scope: 'col' }, t('pool.colAccount')),
3154
+ h('th', { scope: 'col', className: 'dca-pop-num' }, t('pool.colCredits')),
3155
+ ),
3156
+ ),
3157
+ h(
3158
+ 'tbody',
3159
+ null,
3160
+ ...accounts.map((account) =>
3161
+ h(
3162
+ 'tr',
3163
+ {
3164
+ key: account.id,
3165
+ // The serving row: bold name, and its switch is
3166
+ // disabled, so it never takes the hover fill either.
3167
+ className: account.active ? 'dca-pop-row-current' : undefined,
3168
+ },
3169
+ h(
3170
+ 'td',
3171
+ null,
3172
+ h(
3173
+ 'button',
3174
+ {
3175
+ type: 'button',
3176
+ className: 'dca-pop-switch',
3177
+ disabled: busy || account.active,
3178
+ title: t('chip.switchTo').replace('{account}', account.label),
3179
+ 'aria-label': t('chip.switchTo').replace('{account}', account.label),
3180
+ onClick: () => void activateAccount(account),
3181
+ },
3182
+ h('span', {
3183
+ className: `dca-pop-dot${dotTone(account)}`,
3184
+ 'aria-hidden': 'true',
3185
+ }),
3186
+ h(
3187
+ 'span',
3188
+ { className: 'dca-pop-who' },
3189
+ h('span', { className: 'dca-pop-name' }, account.label),
3190
+ // The state goes UNDER the name, not beside it: a
3191
+ // reason string ("约 21 小时后恢复") is long, and in a
3192
+ // 248px panel it would squeeze the name to nothing.
3193
+ account.active || account.error || account.checkin
3194
+ ? h(
3195
+ 'span',
3196
+ { className: 'dca-pop-mark' },
3197
+ account.active
3198
+ ? h('span', { className: 'dca-pop-mark-current' }, t('chip.current'))
3199
+ : null,
3200
+ account.health ? h('span', { className: 'dca-pop-mark-reason' }, t(`health.${account.health.state}`)) : null,
3201
+ account.error
3202
+ ? h('span', { className: 'dca-pop-mark-reason' }, account.error)
3203
+ : null,
3204
+ )
3205
+ : null,
3206
+ ),
3207
+ ),
3208
+ ),
3209
+ h(
3210
+ 'td',
3211
+ { className: `dca-pop-num${account.lowBalance ? ' dca-low-balance' : ''}` },
3212
+ account.credit ? formatCredits(account.credit.remain) : '—',
3213
+ account.credit?.expiring > 0
3214
+ ? h(
3215
+ 'span',
3216
+ { className: 'dca-pop-soon' },
3217
+ t('pool.expiring').replace(
3218
+ '{amount}',
3219
+ Number(account.credit.expiring).toLocaleString(),
3220
+ ),
3221
+ )
3222
+ : null,
3223
+ ),
3224
+ ),
3225
+ ),
3226
+ ),
3227
+ ),
3228
+ )
3229
+ : null,
3230
+ )
3231
+ }
3232
+
3233
+ // ── registration ───────────────────────────────────────────────────────
3234
+
3235
+ const name = 'dsh-connect-codearts-client'
3236
+ const inject = ['slots']
3237
+
3238
+ /**
3239
+ * Register both surfaces.
3240
+ *
3241
+ * Every registration is installed through `ctx.slots.inject`, so the Host
3242
+ * disposes it when the owning declaration collapses, and re-installs it
3243
+ * when the declaration returns.
3244
+ *
3245
+ * The stylesheet is mounted FIRST, as a tagged <style> element.
3246
+ *
3247
+ * NOT through a `styles.insert(css)` builtin: that symbol belongs to the
3248
+ * dynamic client-runner lane, which evaluates a definition with
3249
+ * `new Function('React','console','styles',…)`. This file is a Module
3250
+ * Loader bundle — `window.__ModuleLoader__.load({ factory(require) })` —
3251
+ * and no such binding exists here. A `typeof styles` guard would have made
3252
+ * that mistake silent: markup would render with class names that no rule
3253
+ * matches, giving unstyled buttons and a popover in normal flow.
3254
+ *
3255
+ * The tag is claimed by data attributes and re-written in place rather than
3256
+ * appended twice, so a hot reload refreshes the rules instead of stacking
3257
+ * copies of them.
3258
+ */
3259
+ function apply(ctx) {
3260
+ if (typeof document !== 'undefined') {
3261
+ ctx.effect(() => {
3262
+ const cssId = 'dsh-connect-codearts/client.css'
3263
+ const selector = `style[data-plugin-css="${cssId}"]`
3264
+ const existing = document.querySelector(selector)
3265
+ if (existing !== null) {
3266
+ existing.textContent = CSS
3267
+ } else {
3268
+ const tag = document.createElement('style')
3269
+ tag.dataset.plugin = 'dsh-connect-codearts'
3270
+ tag.dataset.pluginCss = cssId
3271
+ tag.textContent = CSS
3272
+ document.head.appendChild(tag)
3273
+ }
3274
+ return () => {
3275
+ const owned = document.querySelector(selector)
3276
+ if (owned !== null) owned.remove()
3277
+ }
3278
+ }, 'dsh-connect-codearts: stylesheet')
3279
+ }
3280
+
3281
+ // The page and its glyph come from ONE callback: the section's
3282
+ // declaration is what makes the glyph addressable, and registering both
3283
+ // here means neither can outlive the other. The glyph is decoration — a
3284
+ // host that declares the section but not its icon seat must still get the
3285
+ // page — so its failure is logged, not thrown.
3286
+ ctx.slots.inject('settings.section', () => {
3287
+ const disposers = [
3288
+ ctx.slots.register(
3289
+ {
3290
+ name: 'settings.section',
3291
+ id: 'dsh-connect-codearts',
3292
+ order: 36,
3293
+ label: () => t('nav.label'),
3294
+ },
3295
+ SettingsPage,
3296
+ ),
3297
+ ]
3298
+ try {
3299
+ const iconInject = ctx.slots.inject('settings.section.icon', () => {
3300
+ const dispose = ctx.slots.register(
3301
+ { name: 'settings.section.icon', id: 'dsh-connect-codearts' },
3302
+ NavIcon,
3303
+ )
3304
+ disposers.push(dispose)
3305
+ return dispose
3306
+ })
3307
+ if (typeof iconInject === 'function') disposers.push(iconInject)
3308
+ } catch (error) {
3309
+ console.error('[dsh-connect-codearts] settings nav icon failed to register (page unaffected):', error)
3310
+ }
3311
+ return () => {
3312
+ for (const dispose of disposers) {
3313
+ try {
3314
+ dispose()
3315
+ } catch {
3316
+ // Already disposed by the slot service.
3317
+ }
3318
+ }
3319
+ }
3320
+ })
3321
+
3322
+ // Where the panel's 「设置」 button goes: this plugin's own section INSIDE
3323
+ // the settings dialog.
3324
+ //
3325
+ // The old route called `pluginNavigation.openBundle(...)`, which asks the
3326
+ // Plugins page to select a bundle — it lands on that bundle's page, not on
3327
+ // this plugin's section, and it only works while that page's own service
3328
+ // exists. The supported route is the settings shell's store seat: read the
3329
+ // `settings.section` entry's store, create its handle, and ask it to open
3330
+ // the section by id. Everything here is soft-probed and wrapped, because it
3331
+ // is another bundle's service on a composed profile.
3332
+ const softGet = (name) => (typeof ctx.get === 'function' ? ctx.get(name) : undefined)
3333
+
3334
+ /**
3335
+ * The shipped slot whose STORE SEAT is the settings shell's state handle.
3336
+ *
3337
+ * Verified against the shipped client, not assumed: ui-settings-general
3338
+ * registers `{ name: 'sidebar.settings', store: shellStore, ... }`, and that
3339
+ * store's actions are `{ open, close, select, openSection }`. NOT
3340
+ * `settings.section` — that slot lists the PAGES and carries no store.
3341
+ *
3342
+ * `openSection` is otherwise handed only to onboarding steps and section
3343
+ * owner props (`close`), so reading a seat the shell published is the
3344
+ * supported way in rather than registering a fake first-run step.
3345
+ */
3346
+ const SETTINGS_SLOT = 'sidebar.settings'
3347
+
3348
+ /**
3349
+ * The panel container. `data-shortcut-modal="settings"` is the shell's OWN
3350
+ * attribute — its shortcut router keys off it — so it is far more stable
3351
+ * than any class name, which is a CSS-module hash.
3352
+ */
3353
+ const SETTINGS_PANEL_SELECTOR = '[data-shortcut-modal="settings"]'
3354
+
3355
+ /** The sidebar's settings trigger: dialog semantics plus an expanded state. */
3356
+ const TRIGGER_SELECTOR = 'button[aria-haspopup="dialog"][aria-expanded]'
3357
+
3358
+ /**
3359
+ * Budget for "panel mounted + nav row rendered". The panel mounts
3360
+ * synchronously on the click, but the nav rows' labels wait for a locale
3361
+ * snapshot, so a same-frame query is often one tick too early.
3362
+ */
3363
+ const RETRY_DELAYS_MS = [0, 60, 70, 80, 90]
3364
+
3365
+ const schedule = (run, ms) => {
3366
+ try {
3367
+ window.setTimeout(run, ms)
3368
+ } catch {
3369
+ run()
3370
+ }
3371
+ }
3372
+
3373
+ /**
3374
+ * Route 1: the shell's own store seat — one call, exact, no timing.
3375
+ *
3376
+ * @returns 'opened' when the dialog is on the right section, 'shell' when
3377
+ * the dialog opened but without preselection (route 2 can still click the
3378
+ * row), and undefined when the seat is absent or unusable.
3379
+ */
3380
+ const openThroughStoreSeat = (get, sectionId) => {
3381
+ let slots
3382
+ try {
3383
+ slots = get('slots')
3384
+ } catch {
3385
+ return undefined
3386
+ }
3387
+ if (slots === undefined || typeof slots.entries !== 'function') return undefined
3388
+
3389
+ let seat
3390
+ try {
3391
+ // A plain ledger read, but it is another bundle's service: a composed
3392
+ // profile can replace `slots` with something that throws here.
3393
+ seat = slots.entries(SETTINGS_SLOT)[0]?.store
3394
+ } catch {
3395
+ return undefined
3396
+ }
3397
+ if (seat === null || typeof seat !== 'object') return undefined
3398
+ if (typeof seat.create !== 'function') return undefined
3399
+
3400
+ try {
3401
+ // The shell pins `create()` to its ONE live instance. A bare handle
3402
+ // would mint a private copy per call, and `openSection` on that copy
3403
+ // would move a dialog nobody renders.
3404
+ const instance = seat.create()
3405
+ const openSection = instance?.actions?.openSection
3406
+ if (typeof openSection === 'function') {
3407
+ openSection(sectionId)
3408
+ return 'opened'
3409
+ }
3410
+ // A shell whose store predates `openSection`. Pressing still opens the
3411
+ // dialog, so hand back 'shell' and let route 2 click the nav row.
3412
+ const open = instance?.actions?.open
3413
+ if (typeof open === 'function') {
3414
+ open()
3415
+ return 'shell'
3416
+ }
3417
+ } catch {
3418
+ // `create()` or a baked action threw. Nothing left here.
3419
+ }
3420
+ return undefined
3421
+ }
3422
+
3423
+ /** Find the nav-row button whose label is this plugin's. */
3424
+ const findSectionRow = (scope, label) => {
3425
+ const want = String(label ?? '').trim()
3426
+ if (want === '') return undefined
3427
+ return Array.from(scope.querySelectorAll('button')).find(
3428
+ (button) => (button.textContent ?? '').trim() === want,
3429
+ )
3430
+ }
3431
+
3432
+ /**
3433
+ * Route 2: drive the chrome — click the trigger, then this plugin's nav row.
3434
+ * Kept for a shell whose store predates the seat: deleting it would trade a
3435
+ * working route for nothing on those hosts.
3436
+ */
3437
+ const openThroughChrome = () => {
3438
+ try {
3439
+ // The panel may ALREADY be open (the user was on another section).
3440
+ // Clicking the trigger then would CLOSE it — the jump would turn into a
3441
+ // disappearing act — so only drive the trigger when it is absent.
3442
+ if (document.querySelector(SETTINGS_PANEL_SELECTOR) === null) {
3443
+ const triggers = Array.from(document.querySelectorAll(TRIGGER_SELECTOR))
3444
+ const collapsed = triggers.find((button) => button.getAttribute('aria-expanded') !== 'true')
3445
+ // No trigger at all: this host has no settings panel to open. Do not
3446
+ // guess — report that nothing was driven.
3447
+ if (collapsed === undefined) return false
3448
+ collapsed.click()
3449
+ }
3450
+
3451
+ let clicked = false
3452
+ for (const delay of RETRY_DELAYS_MS) {
3453
+ schedule(() => {
3454
+ if (clicked) return
3455
+ try {
3456
+ const scope = document.querySelector(SETTINGS_PANEL_SELECTOR) ?? document
3457
+ const row = findSectionRow(scope, t('nav.label'))
3458
+ if (row !== undefined) {
3459
+ clicked = true
3460
+ row.click()
3461
+ }
3462
+ } catch {
3463
+ // Shell shaped differently: this attempt is done, the next runs.
3464
+ }
3465
+ }, delay)
3466
+ }
3467
+ return true
3468
+ } catch {
3469
+ return false
3470
+ }
3471
+ }
3472
+
3473
+ /**
3474
+ * Open Settings on this plugin's section.
3475
+ *
3476
+ * Two routes, best first. Every step is wrapped: this runs from a RENDER
3477
+ * path (a click handler in the composer panel), so a throw here would take
3478
+ * out the whole readout rather than one button. A shell of a different shape
3479
+ * degrades to a silent no-op.
3480
+ *
3481
+ * Probed PER PRESS rather than captured during apply: the seat belongs to
3482
+ * another bundle whose apply order is not ours to assume, and a captured
3483
+ * `undefined` would leave the button dead for the whole session.
3484
+ */
3485
+ const openSettings = () => {
3486
+ let seatResult
3487
+ try {
3488
+ seatResult = openThroughStoreSeat(softGet, 'dsh-connect-codearts')
3489
+ } catch {
3490
+ seatResult = undefined
3491
+ }
3492
+ if (seatResult === 'opened') return
3493
+ try {
3494
+ openThroughChrome()
3495
+ } catch {
3496
+ // A navigation failure must not break the composer row.
3497
+ }
3498
+ }
3499
+
3500
+ ctx.slots.inject('conversation.input.right', () =>
3501
+ ctx.slots.register(
3502
+ {
3503
+ name: 'conversation.input.right',
3504
+ id: 'dsh-connect-codearts-chip',
3505
+ order: 6,
3506
+ inject: () => ({ openSettings }),
3507
+ },
3508
+ ComposerChip,
3509
+ ),
3510
+ )
3511
+ }
3512
+
3513
+ exports.name = name
3514
+ exports.inject = inject
3515
+ exports.apply = apply
3516
+ exports.STRINGS = STRINGS
3517
+ return module.exports
3518
+ },
3519
+ })