dsh-autorouter 0.0.0-stage → 0.2.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.
package/client.js ADDED
@@ -0,0 +1,1892 @@
1
+ /**
2
+ * AutoRouter settings page.
3
+ *
4
+ * Seat: `settings.section` (id "autorouter", order 16). It talks to the host
5
+ * half over same-origin JSON under `/api/autorouter` — no `remote.settings`
6
+ * dependency, so the page keeps working on any DSH build that serves the
7
+ * plugin's routes.
8
+ *
9
+ * No build step: this file is loaded verbatim by the ModuleLoader.
10
+ */
11
+
12
+ window.__ModuleLoader__.load({
13
+ id: 'dsh-autorouter',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const h = React.createElement
17
+ const { useState, useEffect, useRef } = React
18
+
19
+ const NS = 'settings.autorouter'
20
+ const EFFORTS = ['off', 'minimal', 'low', 'medium', 'high', 'max']
21
+
22
+ const CSS = `
23
+ .ar-root{display:flex;flex-direction:column;gap:14px;padding:2px 2px 40px;font-size:13px;line-height:1.45;color:inherit;max-width:900px}
24
+ .ar-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}
25
+ .ar-title{margin:0;font-size:16px;font-weight:600}
26
+ .ar-sub{margin:3px 0 0;opacity:.62;font-size:12px}
27
+ .ar-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
28
+ .ar-btn{border:1px solid rgba(128,128,128,.32);background:rgba(128,128,128,.08);color:inherit;border-radius:7px;padding:4px 10px;font:inherit;font-size:12px;cursor:pointer;white-space:nowrap}
29
+ .ar-btn:hover:not([disabled]){background:rgba(128,128,128,.17)}
30
+ .ar-btn[disabled]{opacity:.42;cursor:not-allowed}
31
+ .ar-btn.primary{background:#3b82f6;border-color:#3b82f6;color:#fff}
32
+ .ar-btn.primary:hover:not([disabled]){background:#2f6fd8}
33
+ .ar-btn.danger{color:#e5484d;border-color:rgba(229,72,77,.40)}
34
+ .ar-btn.tiny{padding:1px 7px;font-size:11px;border-radius:5px}
35
+ .ar-card{border:1px solid rgba(128,128,128,.22);border-radius:10px;padding:11px 12px;background:rgba(128,128,128,.035);display:flex;flex-direction:column;gap:9px}
36
+ .ar-card-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;cursor:pointer;min-height:24px;padding:2px 0;margin:-2px 0}
37
+ .ar-card-head:hover .ar-chevron{opacity:1}
38
+ .ar-card-body{display:flex;flex-direction:column;gap:9px}
39
+ .ar-chevron{all:unset;cursor:pointer;width:15px;flex:0 0 auto;padding:5px 0;text-align:center;font-size:12px;line-height:1;opacity:.62}
40
+ .ar-chevron:hover{opacity:1}
41
+ .ar-chevron:focus-visible{outline:2px solid rgba(59,130,246,.60);border-radius:4px}
42
+ .ar-card-title{font-weight:600;font-size:13px}
43
+ .ar-muted{opacity:.60}
44
+ .ar-hint{opacity:.55;font-size:11.5px}
45
+ .ar-row{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
46
+ .ar-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:9px 12px}
47
+ .ar-field{display:flex;flex-direction:column;gap:3px;min-width:0}
48
+ .ar-label{font-size:11.5px;opacity:.68}
49
+ .ar-input,.ar-select{background:rgba(128,128,128,.08);border:1px solid rgba(128,128,128,.30);color:inherit;border-radius:6px;padding:3px 6px;font:inherit;font-size:12px;min-width:0}
50
+ .ar-root{color-scheme:inherit}
51
+ .ar-root[data-scheme="dark"]{color-scheme:dark}
52
+ .ar-root[data-scheme="light"]{color-scheme:light}
53
+ .ar-select option{background:#ffffff;color:#1c1c1c}
54
+ .ar-root[data-scheme="dark"] .ar-select option{background:#242424;color:#eaeaea}
55
+ .ar-textarea{color-scheme:inherit}
56
+ .ar-input:focus,.ar-select:focus{outline:2px solid rgba(59,130,246,.45);outline-offset:0}
57
+ .ar-input.num{width:82px}
58
+ .ar-input.wide{width:100%}
59
+ .ar-select.grow{flex:1;min-width:130px}
60
+ .ar-check{display:flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;user-select:none;white-space:nowrap}
61
+ .ar-chain{border:1px solid rgba(128,128,128,.16);border-radius:8px;overflow:hidden}
62
+ .ar-entry{display:flex;flex-direction:column;gap:7px;padding:8px 9px;border-top:1px solid rgba(128,128,128,.16)}
63
+ .ar-entry:first-child{border-top:none}
64
+ .ar-entry.off{opacity:.52}
65
+ .ar-entry-main{display:flex;align-items:center;gap:7px;flex-wrap:wrap}
66
+ .ar-dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex:none}
67
+ .ar-badge{font-size:10.5px;padding:0 6px;border-radius:99px;border:1px solid rgba(128,128,128,.30);opacity:.75;white-space:nowrap}
68
+ .ar-badge.warn{color:#b7791f;border-color:rgba(183,121,31,.45)}
69
+ .ar-badge.bad{color:#e5484d;border-color:rgba(229,72,77,.45)}
70
+ .ar-badge.ok{color:#2f9e44;border-color:rgba(47,158,68,.40)}
71
+ .ar-table{width:100%;border-collapse:collapse;font-size:12px}
72
+ .ar-table th{text-align:left;font-weight:500;opacity:.55;padding:3px 6px;border-bottom:1px solid rgba(128,128,128,.20);white-space:nowrap}
73
+ .ar-table td{padding:4px 6px;border-bottom:1px solid rgba(128,128,128,.12);vertical-align:top}
74
+ .ar-banner{border-radius:8px;padding:7px 10px;font-size:12px;border:1px solid transparent}
75
+ .ar-banner.err{background:rgba(229,72,77,.10);border-color:rgba(229,72,77,.35);color:#e5484d}
76
+ .ar-banner.ok{background:rgba(47,158,68,.10);border-color:rgba(47,158,68,.32);color:#2f9e44}
77
+ .ar-banner.info{background:rgba(59,130,246,.08);border-color:rgba(59,130,246,.28)}
78
+ .ar-tabs{display:flex;gap:2px;border-bottom:1px solid rgba(128,128,128,.22)}
79
+ .ar-tab{border:none;background:none;color:inherit;opacity:.55;font:inherit;font-size:12.5px;padding:6px 11px;cursor:pointer;border-bottom:2px solid transparent;margin-bottom:-1px}
80
+ .ar-tab.on{opacity:1;border-bottom-color:#3b82f6}
81
+ .ar-json{width:100%;min-height:420px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:11.5px;line-height:1.5;background:rgba(128,128,128,.07);border:1px solid rgba(128,128,128,.28);color:inherit;border-radius:8px;padding:9px;resize:vertical}
82
+ .ar-details summary{cursor:pointer;font-size:11.5px;opacity:.62;user-select:none}
83
+ .ar-details[open] summary{opacity:.85}
84
+ .ar-details[open]>.ar-stack,.ar-details[open]>.ar-window,.ar-details[open]>.ar-hint,.ar-details[open]>.ar-muted,.ar-details[open]>.ar-row{margin-top:7px}
85
+ .ar-stack{display:flex;flex-direction:column;gap:8px}
86
+ .ar-window{display:flex;flex-direction:column;gap:6px;padding:8px;border:1px solid rgba(128,128,128,.16);border-radius:8px}
87
+ .ar-section{display:flex;flex-direction:column;gap:8px;padding-top:10px;border-top:1px solid rgba(128,128,128,.18);margin-top:1px}
88
+ .ar-card-body>.ar-section:first-child{padding-top:0;border-top:none}
89
+ .ar-section-head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;min-height:22px}
90
+ .ar-section-head.clickable{cursor:pointer}
91
+ .ar-section-head:hover .ar-chevron{opacity:1}
92
+ .ar-section-title{font-size:12px;font-weight:600;letter-spacing:.01em}
93
+ .ar-section-actions{display:flex;align-items:center;gap:6px;margin-left:auto}
94
+ .ar-section-body{display:flex;flex-direction:column;gap:8px}
95
+ .ar-order-tabs{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
96
+ .ar-empty{padding:26px 12px;text-align:center;border:1px dashed rgba(128,128,128,.30);border-radius:10px}
97
+ .ar-order-preview{font-size:11.5px;line-height:1.5;word-break:break-word}
98
+ `
99
+
100
+ const ZH = {
101
+ nav: 'AutoRouter',
102
+ title: 'AutoRouter 聚合路由',
103
+ subtitle: '一个 provider、一条回退链:严格按顺序在已登记的 provider / model 之间尝试,失败才往后走,思考强度按目标映射。',
104
+ save: '保存',
105
+ saving: '保存中…',
106
+ saveHint: '立即写入配置;已生效的档位会被新配置替换',
107
+ undo: '撤销',
108
+ undoHint: '放弃未保存的改动,回到上次保存的配置',
109
+ reverted: '已撤销未保存的改动',
110
+ dirty: '有未保存的改动',
111
+ saved: '已保存,新配置已生效',
112
+ duplicateProfile: '档位 id 不能重复,否则保存时会丢掉其中一个档位',
113
+ profileIdRequired: '档位 id 不能为空',
114
+ failed: '保存失败',
115
+ conflict: '配置已被其他窗口修改。载入服务器版本后重试。',
116
+ retry: '重试',
117
+ loading: '载入中…',
118
+ unavailable: '无法读取 AutoRouter 状态',
119
+ routes: '路由链',
120
+ policy: '策略',
121
+ json: 'JSON',
122
+ profile: '档位',
123
+ routesHint: '每个档位一张卡片:标识、路由链、时间段与策略都在里面。',
124
+ addProfile: '新建档位',
125
+ removeProfile: '删除档位',
126
+ profileId: '标识',
127
+ profileName: '显示名',
128
+ profileDisabled: '已停用',
129
+ profileEmpty: '空链',
130
+ chain: '回退顺序',
131
+ chainHint: '从上到下依次尝试;勾选控制是否参与。顺序即优先级,冷却中的路由会被跳过。',
132
+ addRoute: '添加路由',
133
+ add: '添加',
134
+ provider: 'Provider',
135
+ model: 'Model',
136
+ cooldownMin: '冷却(分钟)',
137
+ effortMap: '思考强度映射',
138
+ effortInherit: '继承',
139
+ effortDrop: '丢弃',
140
+ test: '探测',
141
+ testing: '探测中…',
142
+ testOk: '可达',
143
+ testBad: '不可达',
144
+ up: '上移',
145
+ down: '下移',
146
+ remove: '删除',
147
+ policyHint: '这些策略只作用于本档位。',
148
+ timeWindows: '时间段',
149
+ addWindow: '添加时段',
150
+ collapseCard: '收起',
151
+ expandCard: '展开',
152
+ timeWindowHint: '每个时段有自己的回退链:在「回退链」里切到该时段,用上下箭头调整顺序。',
153
+ noWindows: '未设置时段,始终按链顺序尝试。',
154
+ windowLabel: '名称',
155
+ windowOrderHint: '本时段的回退顺序',
156
+ addRange: '时间段',
157
+ removeRange: '删除这个时间段',
158
+ removeWindow: '删除时段',
159
+ rangeHint: '同一时段可以有多个不连续的时间段,命中任意一段都算。',
160
+ defaultOrder: '默认顺序',
161
+ orderTabHint: '正在编辑该时段的回退顺序:上下箭头只改这个时段,未列出的路由仍然排在最后兜底。',
162
+ orderEditHint: '在「回退链」上方的时段按钮里调整顺序。',
163
+ noRoutes: '尚未添加路由',
164
+ noProfiles: '还没有档位:点右上角「+ 新建档位」,再从已登记的 provider 里添加路由。',
165
+ sticky: '会话粘性',
166
+ stickyHint: '同一会话尽量复用上一次成功的路由,保护提示缓存。',
167
+ stickinessTtl: '粘性 TTL(分钟)',
168
+ maxSwitches: '单步最大切换',
169
+ cooldown: '失败冷却(分钟)',
170
+ jitter: '冷却抖动比例',
171
+ recovery: '恢复策略',
172
+ recoveryTimer: '定时半开',
173
+ recoveryNever: '永不恢复',
174
+ failureWindow: '失败窗口(分钟)',
175
+ failureThreshold: '失败阈值',
176
+ backoff: '退避基数(毫秒)',
177
+ backoffMax: '退避上限(毫秒)',
178
+ honorRetryAfter: '遵从 Retry-After',
179
+ retryNetwork: '网络错误也重试',
180
+ effortPolicy: '思考强度策略',
181
+ effortPolicyClamp: '收敛(clamp)',
182
+ effortPolicyDrop: '丢弃(drop)',
183
+ effortPolicyFail: '报错(fail)',
184
+ contextPolicy: '上下文窗口策略',
185
+ contextMin: '取最小值(保守压缩)',
186
+ contextMax: '取最大值',
187
+ defaultContext: '未知窗口默认值',
188
+ triggerCodes: '触发切换的错误码',
189
+ triggerCodesHint: '逗号分隔,例如 AUTH,QUOTA,RATE_LIMIT',
190
+ triggerStatuses: '触发切换的 HTTP 状态',
191
+ triggerStatusesHint: '逗号分隔,例如 429,500,503',
192
+ timezone: '时区',
193
+ utcOffset: 'UTC 偏移(分钟)',
194
+ advanced: '高级',
195
+ jsonHint: '整份配置的权威视图。保存时由宿主再次校验并裁剪越界值。',
196
+ applyJson: '应用到表单',
197
+ jsonError: 'JSON 解析失败',
198
+ status: '实时状态',
199
+ stats: '尝试 / 成功 / 失败 / 切换',
200
+ hostVersionHint: '页面与新宿主一致;版本不一致说明宿主还没重启',
201
+ hostVersionUnknown: '宿主没有报告版本,说明运行的还是旧代码',
202
+ lastRoute: '最近路由',
203
+ noSessions: '当前没有固定会话',
204
+ session: '会话',
205
+ age: '距今',
206
+ health: '健康',
207
+ cooling: '冷却中',
208
+ cooled: '冷却',
209
+ healthy: '正常',
210
+ failures: '失败',
211
+ tokens: 'Token',
212
+ clearCooldown: '清除冷却',
213
+ clearAll: '全部清除',
214
+ refresh: '刷新',
215
+ tryOnce: '试一次',
216
+ tryOk: '打通',
217
+ tryFailed: '未打通',
218
+ tryOutdated: '宿主还没重启:这条检查要新版本才有',
219
+ emptyChain: '链路为空。至少添加一条路由后才能接管调用。',
220
+ entryInvalid: 'provider / model 不能为空',
221
+ }
222
+
223
+ const EN = {
224
+ nav: 'AutoRouter',
225
+ title: 'AutoRouter gateway',
226
+ subtitle: 'One provider, one fallback chain: try registered providers and models strictly in order, move on only after a failure, and map reasoning effort per target.',
227
+ save: 'Save',
228
+ saving: 'Saving…',
229
+ saveHint: 'Write the config now; the running profiles pick it up immediately',
230
+ undo: 'Undo',
231
+ undoHint: 'Drop unsaved edits and go back to the last saved config',
232
+ reverted: 'Unsaved edits dropped',
233
+ dirty: 'Unsaved changes',
234
+ saved: 'Saved. The new config is live.',
235
+ duplicateProfile: 'Profile ids must be unique, or saving drops one of them.',
236
+ profileIdRequired: 'A profile id cannot be empty.',
237
+ failed: 'Save failed',
238
+ conflict: 'This config was changed in another window. Load the server version first.',
239
+ retry: 'Retry',
240
+ loading: 'Loading…',
241
+ unavailable: 'Cannot read AutoRouter state',
242
+ routes: 'Chain',
243
+ policy: 'Policy',
244
+ json: 'JSON',
245
+ profile: 'Profile',
246
+ routesHint: 'One card per profile: identity, chain, time windows and policy all live inside it.',
247
+ addProfile: 'New profile',
248
+ removeProfile: 'Delete profile',
249
+ profileId: 'Id',
250
+ profileName: 'Name',
251
+ profileDisabled: 'disabled',
252
+ profileEmpty: 'empty',
253
+ chain: 'Fallback order',
254
+ chainHint: 'Tried top to bottom. Check to include. Position is priority; a cooling route is skipped.',
255
+ addRoute: 'Add route',
256
+ add: 'Add',
257
+ provider: 'Provider',
258
+ model: 'Model',
259
+ cooldownMin: 'Cooldown (min)',
260
+ effortMap: 'Effort map',
261
+ effortInherit: 'inherit',
262
+ effortDrop: 'drop',
263
+ test: 'Probe',
264
+ testing: 'Probing…',
265
+ testOk: 'reachable',
266
+ testBad: 'unreachable',
267
+ up: 'Up',
268
+ down: 'Down',
269
+ remove: 'Remove',
270
+ policyHint: 'Applies to this profile only.',
271
+ timeWindows: 'Time windows',
272
+ addWindow: 'Add window',
273
+ collapseCard: 'Collapse',
274
+ expandCard: 'Expand',
275
+ timeWindowHint: 'Each window has its own fallback chain: switch to it in the chain tabs and reorder with the arrows.',
276
+ noWindows: 'No windows configured; the chain order always applies.',
277
+ windowLabel: 'Label',
278
+ windowOrderHint: 'Fallback order in this window',
279
+ addRange: 'Segment',
280
+ removeRange: 'Remove this segment',
281
+ removeWindow: 'Remove window',
282
+ rangeHint: 'One window may cover several disjoint stretches; any of them keeps it active.',
283
+ defaultOrder: 'Default order',
284
+ orderTabHint: 'Editing this window’s own fallback order: the arrows change this window only, and routes it omits still run last.',
285
+ orderEditHint: 'Reorder it from the window buttons above the chain.',
286
+ noRoutes: 'No routes yet',
287
+ noProfiles: 'No profile yet: use “+ New profile” at the top right, then add routes from your registered providers.',
288
+ sticky: 'Session stickiness',
289
+ stickyHint: 'Reuse the last successful route for a session to protect the prompt cache.',
290
+ stickinessTtl: 'Stickiness TTL (min)',
291
+ maxSwitches: 'Max switches per step',
292
+ cooldown: 'Cooldown after failure (min)',
293
+ jitter: 'Cooldown jitter ratio',
294
+ recovery: 'Recovery',
295
+ recoveryTimer: 'Half-open on timer',
296
+ recoveryNever: 'Never',
297
+ failureWindow: 'Failure window (min)',
298
+ failureThreshold: 'Failure threshold',
299
+ backoff: 'Backoff base (ms)',
300
+ backoffMax: 'Backoff cap (ms)',
301
+ honorRetryAfter: 'Honor Retry-After',
302
+ retryNetwork: 'Retry network errors',
303
+ effortPolicy: 'Effort policy',
304
+ effortPolicyClamp: 'Clamp',
305
+ effortPolicyDrop: 'Drop',
306
+ effortPolicyFail: 'Fail',
307
+ contextPolicy: 'Context window policy',
308
+ contextMin: 'Minimum (conservative compaction)',
309
+ contextMax: 'Maximum',
310
+ defaultContext: 'Default when unknown',
311
+ triggerCodes: 'Trigger error codes',
312
+ triggerCodesHint: 'Comma separated, e.g. AUTH,QUOTA,RATE_LIMIT',
313
+ triggerStatuses: 'Trigger HTTP statuses',
314
+ triggerStatusesHint: 'Comma separated, e.g. 429,500,503',
315
+ timezone: 'Time zone',
316
+ utcOffset: 'UTC offset (min)',
317
+ advanced: 'Advanced',
318
+ jsonHint: 'The authoritative view of the whole config. The host re-validates and bounds it on save.',
319
+ applyJson: 'Apply to form',
320
+ jsonError: 'JSON parse failed',
321
+ status: 'Live status',
322
+ stats: 'attempts / successes / failures / switches',
323
+ hostVersionHint: 'page and host agree; a mismatch means the host was not restarted',
324
+ hostVersionUnknown: 'the host reports no version, so it is still running the old code',
325
+ lastRoute: 'Last route',
326
+ noSessions: 'No pinned sessions',
327
+ session: 'Session',
328
+ age: 'age',
329
+ health: 'Health',
330
+ cooling: 'cooling',
331
+ cooled: 'cooled',
332
+ healthy: 'healthy',
333
+ failures: 'failures',
334
+ tokens: 'tokens',
335
+ clearCooldown: 'Clear cooldown',
336
+ clearAll: 'Clear all',
337
+ refresh: 'Refresh',
338
+ tryOnce: 'Try once',
339
+ tryOk: 'worked',
340
+ tryFailed: 'failed',
341
+ tryOutdated: 'the host has not been restarted: this check needs the new build',
342
+ emptyChain: 'The chain is empty. Add at least one route before it can take over.',
343
+ entryInvalid: 'provider / model must not be empty',
344
+ }
345
+
346
+ function minutesToClock(value) {
347
+ if (typeof value === 'string') {
348
+ const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
349
+ if (match === null) return ''
350
+ return `${match[1].padStart(2, '0')}:${match[2]}`
351
+ }
352
+ if (typeof value !== 'number' || !Number.isFinite(value)) return ''
353
+ const total = ((Math.round(value) % 1440) + 1440) % 1440
354
+ return `${String(Math.floor(total / 60)).padStart(2, '0')}:${String(total % 60).padStart(2, '0')}`
355
+ }
356
+
357
+ /** `HH:MM` or minutes → minutes, so window edges compare as numbers. */
358
+ function clockToMinutes(value) {
359
+ if (typeof value === 'number' && Number.isFinite(value)) return ((Math.round(value) % 1440) + 1440) % 1440
360
+ if (typeof value !== 'string') return 0
361
+ const match = /^(\d{1,2}):(\d{2})$/.exec(value.trim())
362
+ if (match === null) return 0
363
+ return (Number(match[1]) * 60 + Number(match[2])) % 1440
364
+ }
365
+
366
+ /** Same rule as the host: `from === to` means all day, wrap-around included. */
367
+ function rangeMatches(range, minutes) {
368
+ const from = clockToMinutes(range.from)
369
+ const to = clockToMinutes(range.to)
370
+ if (from === to) return true
371
+ return from < to ? minutes >= from && minutes < to : minutes >= from || minutes < to
372
+ }
373
+
374
+ /**
375
+ * A window may be spread over several disjoint stretches (e.g. 00:30–08:30
376
+ * and 22:00–23:30); it is active when any of them matches.
377
+ */
378
+ function windowMatches(window, utcOffsetMinutes) {
379
+ const shifted = new Date(Date.now() + (utcOffsetMinutes ?? 480) * 60_000)
380
+ const minutes = shifted.getUTCHours() * 60 + shifted.getUTCMinutes()
381
+ const ranges = Array.isArray(window.ranges) ? window.ranges : [{ from: window.from, to: window.to }]
382
+ return ranges.some((range) => rangeMatches(range, minutes))
383
+ }
384
+
385
+ /** `00:30–08:30`, or `00:30–08:30 · 22:00–23:30` for a multi-range window. */
386
+ function windowCaption(window) {
387
+ if (typeof window.label === 'string' && window.label.trim() !== '') return window.label.trim()
388
+ const ranges = Array.isArray(window.ranges) ? window.ranges : [{ from: window.from, to: window.to }]
389
+ return ranges.map((range) => `${minutesToClock(range.from)}–${minutesToClock(range.to)}`).join(' · ')
390
+ }
391
+
392
+ /** The window's ranges, normalized for editing, including the legacy shape. */
393
+ function windowRanges(window) {
394
+ const ranges = Array.isArray(window.ranges) ? window.ranges : [{ from: window.from, to: window.to }]
395
+ return ranges.map((range) => ({ from: minutesToClock(range.from) || '00:00', to: minutesToClock(range.to) || '00:00' }))
396
+ }
397
+
398
+ /**
399
+ * A window's order is a complete chain: keys it lists come first in that
400
+ * order, routes it does not list keep their configured order behind them.
401
+ * Same rule the host applies, so the page shows what the host will do.
402
+ */
403
+ function orderByKeys(chain, order) {
404
+ const rank = new Map((order ?? []).map((key, index) => [key, index]))
405
+ const rankOf = (entry) => {
406
+ const key = `${entry.provider}/${entry.model}`
407
+ return rank.has(key) ? rank.get(key) : rank.has(entry.id) ? rank.get(entry.id) : undefined
408
+ }
409
+ return [...chain].sort((left, right) => {
410
+ const leftRank = rankOf(left)
411
+ const rightRank = rankOf(right)
412
+ if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank
413
+ if (leftRank !== undefined) return -1
414
+ if (rightRank !== undefined) return 1
415
+ return 0
416
+ })
417
+ }
418
+
419
+ const S = {
420
+ dot: (color) => ({ width: 7, height: 7, borderRadius: '50%', background: color, display: 'inline-block', flex: 'none' }),
421
+ grow: { flex: 1, minWidth: 0 },
422
+ right: { marginLeft: 'auto' },
423
+ tableWrap: { overflowX: 'auto' },
424
+ }
425
+
426
+ async function api(path, init) {
427
+ const response = await fetch(path, {
428
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
429
+ cache: 'no-store',
430
+ ...init,
431
+ })
432
+ let body = {}
433
+ try {
434
+ body = await response.json()
435
+ } catch {
436
+ body = {}
437
+ }
438
+ if (!response.ok) {
439
+ const error = new Error(body?.error || `HTTP ${response.status}`)
440
+ error.status = response.status
441
+ error.body = body
442
+ throw error
443
+ }
444
+ return body
445
+ }
446
+
447
+ const num = (value, fallback = 0) => {
448
+ const parsed = typeof value === 'number' ? value : Number(value)
449
+ return Number.isFinite(parsed) ? parsed : fallback
450
+ }
451
+ const splitList = (text) =>
452
+ String(text ?? '')
453
+ .split(',')
454
+ .map((item) => item.trim())
455
+ .filter((item) => item !== '')
456
+ const fmtAge = (ms) => {
457
+ const seconds = Math.max(0, Math.round(num(ms) / 1000))
458
+ if (seconds < 60) return `${seconds}s`
459
+ const minutes = Math.round(seconds / 60)
460
+ if (minutes < 60) return `${minutes}m`
461
+ return `${Math.floor(minutes / 60)}h${minutes % 60 ? ` ${minutes % 60}m` : ''}`
462
+ }
463
+
464
+ /**
465
+ * Native select popups are painted by the browser, so they follow the
466
+ * element's `color-scheme`, not our CSS. Prefer an explicit scheme declared
467
+ * by the host, then its dark/light marker, then the page's actual paint,
468
+ * then the OS preference.
469
+ */
470
+ function backgroundLuminance(element) {
471
+ if (element === null || element === undefined) return undefined
472
+ const color = String(getComputedStyle(element).backgroundColor ?? '')
473
+ const match = color.match(/rgba?\(([^)]+)\)/)
474
+ if (match === null) return undefined
475
+ const parts = match[1].split(',').map((part) => Number(part.trim()))
476
+ if (parts.length < 3 || parts.some((part) => !Number.isFinite(part))) return undefined
477
+ if ((parts[3] ?? 1) < 0.5) return undefined
478
+ return (0.2126 * parts[0] + 0.7152 * parts[1] + 0.0722 * parts[2]) / 255
479
+ }
480
+
481
+ function detectScheme() {
482
+ if (typeof window === 'undefined' || typeof document === 'undefined') return 'light'
483
+ try {
484
+ const root = document.documentElement
485
+ const body = document.body
486
+ const declared = String(getComputedStyle(root).colorScheme ?? '').toLowerCase()
487
+ if (declared.includes('dark') && !declared.includes('light')) return 'dark'
488
+ if (declared.includes('light') && !declared.includes('dark')) return 'light'
489
+ for (const element of [root, body]) {
490
+ if (element === null || element === undefined) continue
491
+ const theme = String(element.getAttribute?.('data-theme') ?? '').toLowerCase()
492
+ if (theme === 'dark') return 'dark'
493
+ if (theme === 'light') return 'light'
494
+ if (element.classList?.contains('dark')) return 'dark'
495
+ if (element.classList?.contains('light')) return 'light'
496
+ }
497
+ // DSH may switch themes without declaring color-scheme or a class we can
498
+ // see. The painted background is the last theme-bearing signal.
499
+ for (const element of [body, root]) {
500
+ const luminance = backgroundLuminance(element)
501
+ if (luminance !== undefined) return luminance < 0.5 ? 'dark' : 'light'
502
+ }
503
+ return window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
504
+ } catch {
505
+ return 'light'
506
+ }
507
+ }
508
+
509
+ function Field(props) {
510
+ return h(
511
+ 'label',
512
+ { className: 'ar-field' },
513
+ h('span', { className: 'ar-label' }, props.label),
514
+ props.children,
515
+ props.hint ? h('span', { className: 'ar-hint' }, props.hint) : null,
516
+ )
517
+ }
518
+
519
+ const COLLAPSE_KEY = 'dsh-autorouter:collapsed'
520
+
521
+ function readCollapsed() {
522
+ try {
523
+ const raw = window.localStorage?.getItem(COLLAPSE_KEY)
524
+ const parsed = raw ? JSON.parse(raw) : []
525
+ return new Set(Array.isArray(parsed) ? parsed.filter((item) => typeof item === 'string') : [])
526
+ } catch {
527
+ return new Set()
528
+ }
529
+ }
530
+
531
+ function writeCollapsed(set) {
532
+ try {
533
+ window.localStorage?.setItem(COLLAPSE_KEY, JSON.stringify([...set]))
534
+ } catch {
535
+ // A sandboxed frame may refuse storage; collapsing still works per render.
536
+ }
537
+ }
538
+
539
+ /**
540
+ * A card with a disclosure chevron. Collapse state lives in the page, so a
541
+ * profile card keeps its identity by position rather than by its editable id.
542
+ */
543
+ function Card({ t, open, onToggle, style, head, actions, children }) {
544
+ // The whole head row is the target, not just the chevron: a 15px glyph is
545
+ // a miss-prone click. Controls inside the head keep their own behaviour,
546
+ // which also stops the chevron from toggling twice through bubbling.
547
+ const toggleFromHead = (event) => {
548
+ const target = event?.target
549
+ if (target !== null && typeof target?.closest === 'function' && target.closest('button, input, select, textarea, a, label')) return
550
+ onToggle?.()
551
+ }
552
+ return h(
553
+ 'div',
554
+ { className: `ar-card${open ? '' : ' collapsed'}`, style },
555
+ h(
556
+ 'div',
557
+ {
558
+ className: 'ar-card-head',
559
+ onClick: toggleFromHead,
560
+ title: open ? t('collapseCard') : t('expandCard'),
561
+ },
562
+ h(
563
+ 'button',
564
+ {
565
+ className: 'ar-chevron',
566
+ type: 'button',
567
+ 'aria-expanded': open,
568
+ 'aria-label': open ? t('collapseCard') : t('expandCard'),
569
+ onClick: onToggle,
570
+ },
571
+ open ? '▾' : '▸',
572
+ ),
573
+ head,
574
+ actions === undefined || actions === null
575
+ ? null
576
+ : h('span', { style: S.right, onClick: (event) => event.stopPropagation() }, actions),
577
+ ),
578
+ open ? h('div', { className: 'ar-card-body' }, children) : null,
579
+ )
580
+ }
581
+
582
+ function Toggle(props) {
583
+ return h(
584
+ 'label',
585
+ { className: 'ar-check', title: props.title ?? undefined },
586
+ h('input', { type: 'checkbox', checked: !!props.checked, onChange: (event) => props.onChange(event.target.checked) }),
587
+ h('span', null, props.label),
588
+ )
589
+ }
590
+
591
+ function Tabs(props) {
592
+ const items = [
593
+ ['routes', props.t('routes')],
594
+ ['status', props.t('status')],
595
+ ['json', props.t('json')],
596
+ ]
597
+ return h(
598
+ 'div',
599
+ { className: 'ar-tabs', role: 'tablist' },
600
+ items.map(([id, label]) =>
601
+ h(
602
+ 'button',
603
+ {
604
+ key: id,
605
+ role: 'tab',
606
+ 'aria-selected': props.tab === id,
607
+ className: `ar-tab${props.tab === id ? ' on' : ''}`,
608
+ onClick: () => props.onTab(id),
609
+ },
610
+ label,
611
+ ),
612
+ ),
613
+ )
614
+ }
615
+
616
+ function HealthBadge({ row, t }) {
617
+ const cooling = row.coolingUntil && row.coolingUntil > Date.now()
618
+ if (cooling) return h('span', { className: 'ar-badge bad' }, `${t('cooling')} · ${fmtAge(row.coolingUntil - Date.now())}`)
619
+ if (row.failures > 0) return h('span', { className: 'ar-badge warn' }, `${t('failures')} ${row.failures}`)
620
+ return h('span', { className: 'ar-badge ok' }, t('healthy'))
621
+ }
622
+
623
+ function EntryRow({ entry, index, count, profileIndex, t, onChange, onMove, onRemove, onProbe, probe, catalog }) {
624
+ const provider = catalog.providers.find((item) => item.id === entry.provider)
625
+ const models = provider?.models ?? []
626
+ const effortMap = entry.effortMap ?? {}
627
+ const setEffort = (requested, value) => {
628
+ const next = { ...effortMap }
629
+ if (value === '') delete next[requested]
630
+ else if (value === '-') next[requested] = null
631
+ else next[requested] = value
632
+ onChange({ effortMap: next })
633
+ }
634
+ return h(
635
+ 'div',
636
+ { className: `ar-entry${entry.enabled === false ? ' off' : ''}` },
637
+ h(
638
+ 'div',
639
+ { className: 'ar-entry-main' },
640
+ h('input', {
641
+ type: 'checkbox',
642
+ checked: entry.enabled !== false,
643
+ onChange: (event) => onChange({ enabled: event.target.checked }),
644
+ }),
645
+ h(
646
+ 'select',
647
+ {
648
+ className: 'ar-select',
649
+ value: entry.provider,
650
+ onChange: (event) => {
651
+ const nextProvider = event.target.value
652
+ const nextModel = catalog.providers.find((item) => item.id === nextProvider)?.models[0]?.id ?? entry.model
653
+ onChange({ provider: nextProvider, model: nextModel })
654
+ },
655
+ },
656
+ catalog.providers.map((item) => h('option', { key: item.id, value: item.id }, item.name || item.id)),
657
+ catalog.providers.some((item) => item.id === entry.provider)
658
+ ? null
659
+ : h('option', { value: entry.provider }, entry.provider || '—'),
660
+ ),
661
+ h('span', { className: 'ar-muted' }, '·'),
662
+ h(
663
+ 'select',
664
+ {
665
+ className: 'ar-select grow',
666
+ value: entry.model,
667
+ onChange: (event) => onChange({ model: event.target.value }),
668
+ },
669
+ models.map((item) => h('option', { key: item.id, value: item.id }, item.name || item.id)),
670
+ models.some((item) => item.id === entry.model) ? null : h('option', { value: entry.model }, entry.model || '—'),
671
+ ),
672
+ h(
673
+ 'button',
674
+ {
675
+ className: 'ar-btn tiny',
676
+ type: 'button',
677
+ disabled: probe?.busy,
678
+ onClick: () => onProbe(entry),
679
+ title: `${entry.provider}/${entry.model}`,
680
+ },
681
+ probe?.busy ? t('testing') : probe?.result === true ? `${t('testOk')} · ${probe.ms}ms` : probe?.result === false ? t('testBad') : t('test'),
682
+ ),
683
+ h(
684
+ 'span',
685
+ { style: S.right },
686
+ h('button', { className: 'ar-btn tiny', type: 'button', disabled: index === 0, onClick: () => onMove(-1), title: t('up') }, '↑'),
687
+ h('button', { className: 'ar-btn tiny', type: 'button', disabled: index === count - 1, onClick: () => onMove(1), title: t('down') }, '↓'),
688
+ h('button', { className: 'ar-btn tiny danger', type: 'button', onClick: onRemove, title: t('remove') }, '✕'),
689
+ ),
690
+ ),
691
+ h(
692
+ 'div',
693
+ { className: 'ar-entry-main' },
694
+ h(
695
+ Field,
696
+ { label: t('cooldownMin') },
697
+ h('input', {
698
+ className: 'ar-input num',
699
+ type: 'number',
700
+ min: 0,
701
+ step: 0.5,
702
+ value: Math.round((entry.cooldownMs ?? 300000) / 6000) / 10,
703
+ onChange: (event) => onChange({ cooldownMs: Math.round(num(event.target.value, 5) * 60000) }),
704
+ }),
705
+ ),
706
+ ),
707
+ h(
708
+ 'details',
709
+ { className: 'ar-details' },
710
+ h('summary', null, t('effortMap')),
711
+ h(
712
+ 'div',
713
+ { className: 'ar-grid', style: { marginTop: 7 } },
714
+ EFFORTS.map((requested) =>
715
+ h(
716
+ 'label',
717
+ { key: requested, className: 'ar-field' },
718
+ h('span', { className: 'ar-label' }, requested),
719
+ h(
720
+ 'select',
721
+ {
722
+ className: 'ar-select',
723
+ value: effortMap[requested] === undefined ? '' : effortMap[requested] === null ? '-' : effortMap[requested],
724
+ onChange: (event) => setEffort(requested, event.target.value),
725
+ },
726
+ h('option', { value: '' }, t('effortInherit')),
727
+ h('option', { value: '-' }, t('effortDrop')),
728
+ EFFORTS.map((effort) => h('option', { key: effort, value: effort }, effort)),
729
+ ),
730
+ ),
731
+ ),
732
+ ),
733
+ ),
734
+ )
735
+ }
736
+
737
+ /**
738
+ * One titled block inside a card. Sections carry the divider that keeps
739
+ * identity, chain, time windows and policy readable as parts of a single
740
+ * card, instead of a stack of unrelated disclosures.
741
+ */
742
+ function Section({ t, title, count, actions, open, onToggle, children }) {
743
+ const collapsible = typeof onToggle === 'function'
744
+ return h(
745
+ 'div',
746
+ { className: 'ar-section' },
747
+ h(
748
+ 'div',
749
+ { className: collapsible ? 'ar-section-head clickable' : 'ar-section-head', onClick: collapsible ? onToggle : undefined },
750
+ collapsible
751
+ ? h(
752
+ 'button',
753
+ {
754
+ className: 'ar-chevron',
755
+ type: 'button',
756
+ 'aria-expanded': open !== false,
757
+ 'aria-label': open !== false ? t('collapseCard') : t('expandCard'),
758
+ onClick: onToggle,
759
+ },
760
+ open !== false ? '▾' : '▸',
761
+ )
762
+ : null,
763
+ h('span', { className: 'ar-section-title' }, title),
764
+ typeof count === 'number' && count > 0 ? h('span', { className: 'ar-badge' }, String(count)) : null,
765
+ actions === undefined || actions === null
766
+ ? null
767
+ : h('span', { className: 'ar-section-actions', onClick: (event) => event.stopPropagation() }, actions),
768
+ ),
769
+ open === false ? null : h('div', { className: 'ar-section-body' }, children),
770
+ )
771
+ }
772
+
773
+ function ProfileCard(props) {
774
+ const { profile, index, t, catalog, onEdit, onRemove, onAddRoute, probes, onProbe } = props
775
+ const policy = profile.policy ?? {}
776
+ const windows = policy.timeWindows ?? []
777
+ const chain = profile.chain ?? []
778
+ const setPolicy = (patch) => onEdit({ policy: { ...policy, ...patch } })
779
+ // Which chain is on screen: the configured one, or one window's own
780
+ // fallback order over the same routes.
781
+ const [orderTab, setOrderTab] = useState('default')
782
+ const [provider, setProvider] = useState(catalog.providers[0]?.id ?? '')
783
+ const [model, setModel] = useState(catalog.providers[0]?.models[0]?.id ?? '')
784
+ const models = catalog.providers.find((item) => item.id === provider)?.models ?? []
785
+ useEffect(() => {
786
+ if (catalog.providers.length === 0) return
787
+ if (!catalog.providers.some((item) => item.id === provider)) setProvider(catalog.providers[0].id)
788
+ }, [catalog])
789
+ useEffect(() => {
790
+ if (models.length > 0 && !models.some((item) => item.id === model)) setModel(models[0].id)
791
+ }, [provider, catalog])
792
+
793
+ // A deleted window must not leave the editor on a tab that no longer exists.
794
+ const tab = orderTab !== 'default' && windows.some((window) => window.id === orderTab) ? orderTab : 'default'
795
+ const current = tab === 'default' ? undefined : windows.find((window) => window.id === tab)
796
+ const orderedChain = current === undefined ? chain : orderByKeys(chain, current.order)
797
+ const keyOf = (entry) => `${entry.provider}/${entry.model}`
798
+ const writeOrder = (order) =>
799
+ setPolicy({ timeWindows: windows.map((window) => (window.id === current.id ? { ...window, order } : window)) })
800
+
801
+ function changeEntry(entry, patch) {
802
+ const before = keyOf(entry)
803
+ const next = { ...entry, ...patch }
804
+ const after = keyOf(next)
805
+ const nextChain = chain.map((item) => (item === entry ? next : item))
806
+ if (before === after) {
807
+ onEdit({ chain: nextChain })
808
+ return
809
+ }
810
+ // A renamed route must not linger in a window order under its old key.
811
+ onEdit({
812
+ chain: nextChain,
813
+ policy: {
814
+ ...policy,
815
+ timeWindows: windows.map((window) => ({
816
+ ...window,
817
+ order: (window.order ?? []).map((key) => (key === before ? after : key)),
818
+ })),
819
+ },
820
+ })
821
+ }
822
+
823
+ function moveEntry(entry, delta) {
824
+ if (current === undefined) {
825
+ const at = chain.indexOf(entry)
826
+ const to = at + delta
827
+ if (at < 0 || to < 0 || to >= chain.length) return
828
+ const next = [...chain]
829
+ const [item] = next.splice(at, 1)
830
+ next.splice(to, 0, item)
831
+ onEdit({ chain: next })
832
+ return
833
+ }
834
+ // Moving inside a window rewrites that window's whole order, because a
835
+ // window is a chain of its own rather than a "try these two first" hint.
836
+ const keys = orderedChain.map(keyOf)
837
+ const at = keys.indexOf(keyOf(entry))
838
+ const to = at + delta
839
+ if (at < 0 || to < 0 || to >= keys.length) return
840
+ const next = [...keys]
841
+ const [item] = next.splice(at, 1)
842
+ next.splice(to, 0, item)
843
+ writeOrder(next)
844
+ }
845
+
846
+ function removeEntry(entry) {
847
+ const key = keyOf(entry)
848
+ onEdit({
849
+ chain: chain.filter((item) => item !== entry),
850
+ policy: {
851
+ ...policy,
852
+ timeWindows: windows.map((window) => ({ ...window, order: (window.order ?? []).filter((item) => item !== key) })),
853
+ },
854
+ })
855
+ }
856
+
857
+ return h(
858
+ Card,
859
+ {
860
+ t,
861
+ open: props.open !== false,
862
+ onToggle: props.onToggle,
863
+ head: [
864
+ h('span', { key: 'title', className: 'ar-card-title' }, profile.name || profile.id),
865
+ h('span', { key: 'id', className: 'ar-badge' }, profile.id),
866
+ !profile.enabled ? h('span', { key: 'off', className: 'ar-badge warn' }, t('profileDisabled')) : null,
867
+ profile.chain.length === 0 ? h('span', { key: 'empty', className: 'ar-badge bad' }, t('profileEmpty')) : null,
868
+ ],
869
+ actions: h(
870
+ 'button',
871
+ { className: 'ar-btn tiny danger', type: 'button', onClick: () => onRemove(index), disabled: props.profileCount <= 1 },
872
+ t('removeProfile'),
873
+ ),
874
+ },
875
+ h(
876
+ 'div',
877
+ { className: 'ar-grid' },
878
+ h(
879
+ Field,
880
+ { label: t('profileId') },
881
+ h('input', { className: 'ar-input', value: profile.id, onChange: (event) => onEdit({ id: event.target.value }) }),
882
+ ),
883
+ h(
884
+ Field,
885
+ { label: t('profileName') },
886
+ h('input', { className: 'ar-input', value: profile.name ?? '', onChange: (event) => onEdit({ name: event.target.value }) }),
887
+ ),
888
+ ),
889
+ h(
890
+ Section,
891
+ { title: t('chain') },
892
+ h('div', { className: 'ar-hint' }, t('chainHint')),
893
+ h(
894
+ 'div',
895
+ { className: 'ar-order-tabs' },
896
+ h(
897
+ 'button',
898
+ {
899
+ key: 'default',
900
+ type: 'button',
901
+ className: tab === 'default' ? 'ar-btn tiny primary' : 'ar-btn tiny',
902
+ onClick: () => setOrderTab('default'),
903
+ },
904
+ t('defaultOrder'),
905
+ ),
906
+ windows.map((window, at) => {
907
+ const caption = windowCaption(window)
908
+ const range = windowRanges(window)
909
+ .map((item) => `${item.from} → ${item.to}`)
910
+ .join(' · ')
911
+ return h(
912
+ 'button',
913
+ {
914
+ key: window.id ?? at,
915
+ type: 'button',
916
+ className: tab === window.id ? 'ar-btn tiny primary' : 'ar-btn tiny',
917
+ title: range,
918
+ onClick: () => setOrderTab(window.id),
919
+ },
920
+ windowMatches(window, policy.utcOffsetMinutes) ? `● ${caption}` : caption,
921
+ )
922
+ }),
923
+ ),
924
+ current === undefined
925
+ ? null
926
+ : h('div', { className: 'ar-hint' }, t('orderTabHint')),
927
+ chain.length === 0
928
+ ? h('div', { className: 'ar-banner err' }, t('emptyChain'))
929
+ : h(
930
+ 'div',
931
+ { className: 'ar-chain' },
932
+ orderedChain.map((entry, entryIndex) =>
933
+ h(EntryRow, {
934
+ key: entry.id ?? `${entry.provider}/${entry.model}/${entryIndex}`,
935
+ entry,
936
+ index: entryIndex,
937
+ count: orderedChain.length,
938
+ profileIndex: index,
939
+ t,
940
+ catalog,
941
+ probe: probes[`${profile.id}::${entry.provider}/${entry.model}`],
942
+ onProbe: (target) => onProbe(profile, target),
943
+ onChange: (patch) => changeEntry(entry, patch),
944
+ onMove: (delta) => moveEntry(entry, delta),
945
+ onRemove: () => removeEntry(entry),
946
+ }),
947
+ ),
948
+ ),
949
+ h(
950
+ 'div',
951
+ { className: 'ar-row' },
952
+ h(
953
+ 'select',
954
+ { className: 'ar-select grow', value: provider, onChange: (event) => setProvider(event.target.value) },
955
+ catalog.providers.map((item) => h('option', { key: item.id, value: item.id }, item.name || item.id)),
956
+ ),
957
+ h(
958
+ 'select',
959
+ { className: 'ar-select grow', value: model, onChange: (event) => setModel(event.target.value) },
960
+ models.map((item) => h('option', { key: item.id, value: item.id }, item.name || item.id)),
961
+ ),
962
+ h(
963
+ 'button',
964
+ {
965
+ className: 'ar-btn',
966
+ type: 'button',
967
+ disabled: !provider || !model,
968
+ onClick: () => onAddRoute(profile.id, { provider, model }),
969
+ },
970
+ `+ ${t('addRoute')}`,
971
+ ),
972
+ ),
973
+ ),
974
+ h(TimeWindows, {
975
+ t,
976
+ windows,
977
+ chain,
978
+ onChange: (list) => setPolicy({ timeWindows: list }),
979
+ }),
980
+ h(PolicySection, { t, policy, onChange: setPolicy }),
981
+ )
982
+ }
983
+
984
+ /**
985
+ * Policy belongs to the profile that owns the chain, so it renders inside
986
+ * that profile's card. A page-level policy card had to carry its own
987
+ * profile picker and could silently edit a profile the user was not
988
+ * looking at.
989
+ */
990
+ function PolicySection({ t, policy, onChange }) {
991
+ // Open by default: a collapsed section reads as an empty card, which is
992
+ // exactly how the time windows looked before they moved in here.
993
+ const [open, setOpen] = useState(true)
994
+ return h(
995
+ Section,
996
+ {
997
+ t,
998
+ title: t('policy'),
999
+ open,
1000
+ onToggle: () => setOpen((value) => !value),
1001
+ actions: h('span', { className: 'ar-muted' }, t('policyHint')),
1002
+ },
1003
+ h(PolicyFields, { t, policy, onChange }),
1004
+ )
1005
+ }
1006
+
1007
+ /**
1008
+ * Policy belongs to the profile that owns the chain, so it renders inside
1009
+ * that profile's card. A page-level policy card had to carry its own
1010
+ * profile picker and could silently edit a profile the user was not
1011
+ * looking at.
1012
+ */
1013
+ function PolicyFields({ t, policy, onChange }) {
1014
+ const value = policy ?? {}
1015
+ const set = (patch) => onChange(patch)
1016
+ return h(
1017
+ 'div',
1018
+ { className: 'ar-stack' },
1019
+ h('div', { className: 'ar-hint' }, t('policyHint')),
1020
+ h(
1021
+ 'div',
1022
+ { className: 'ar-grid' },
1023
+ h(
1024
+ Field,
1025
+ { label: t('maxSwitches') },
1026
+ h('input', {
1027
+ className: 'ar-input num',
1028
+ type: 'number',
1029
+ min: 0,
1030
+ max: 50,
1031
+ value: value.maxSwitches ?? 8,
1032
+ onChange: (event) => set({ maxSwitches: Math.max(0, Math.round(num(event.target.value, 8))) }),
1033
+ }),
1034
+ ),
1035
+ h(
1036
+ Field,
1037
+ { label: t('cooldown') },
1038
+ h('input', {
1039
+ className: 'ar-input num',
1040
+ type: 'number',
1041
+ min: 0,
1042
+ step: 0.5,
1043
+ value: Math.round((value.cooldownMs ?? 300000) / 6000) / 10,
1044
+ onChange: (event) => set({ cooldownMs: Math.round(num(event.target.value, 5) * 60000) }),
1045
+ }),
1046
+ ),
1047
+ h(
1048
+ Field,
1049
+ { label: t('jitter') },
1050
+ h('input', {
1051
+ className: 'ar-input num',
1052
+ type: 'number',
1053
+ min: 0,
1054
+ max: 1,
1055
+ step: 0.05,
1056
+ value: value.cooldownJitterRatio ?? 0.2,
1057
+ onChange: (event) => set({ cooldownJitterRatio: Math.min(1, Math.max(0, num(event.target.value, 0.2))) }),
1058
+ }),
1059
+ ),
1060
+ h(
1061
+ Field,
1062
+ { label: t('stickinessTtl') },
1063
+ h('input', {
1064
+ className: 'ar-input num',
1065
+ type: 'number',
1066
+ min: 0,
1067
+ value: Math.round((value.stickinessTtlMs ?? 1800000) / 60000),
1068
+ onChange: (event) => set({ stickinessTtlMs: Math.max(0, Math.round(num(event.target.value, 30) * 60000)) }),
1069
+ }),
1070
+ ),
1071
+ h(
1072
+ Field,
1073
+ { label: t('failureWindow') },
1074
+ h('input', {
1075
+ className: 'ar-input num',
1076
+ type: 'number',
1077
+ min: 0,
1078
+ value: Math.round((value.failureWindowMs ?? 120000) / 60000),
1079
+ onChange: (event) => set({ failureWindowMs: Math.max(0, Math.round(num(event.target.value, 2) * 60000)) }),
1080
+ }),
1081
+ ),
1082
+ h(
1083
+ Field,
1084
+ { label: t('failureThreshold') },
1085
+ h('input', {
1086
+ className: 'ar-input num',
1087
+ type: 'number',
1088
+ min: 1,
1089
+ value: value.failureThreshold ?? 3,
1090
+ onChange: (event) => set({ failureThreshold: Math.max(1, Math.round(num(event.target.value, 3))) }),
1091
+ }),
1092
+ ),
1093
+ h(
1094
+ Field,
1095
+ { label: t('backoff') },
1096
+ h('input', {
1097
+ className: 'ar-input num',
1098
+ type: 'number',
1099
+ min: 0,
1100
+ value: value.backoffBaseMs ?? 1000,
1101
+ onChange: (event) => set({ backoffBaseMs: Math.max(0, Math.round(num(event.target.value, 1000))) }),
1102
+ }),
1103
+ ),
1104
+ h(
1105
+ Field,
1106
+ { label: t('backoffMax') },
1107
+ h('input', {
1108
+ className: 'ar-input num',
1109
+ type: 'number',
1110
+ min: 0,
1111
+ value: value.backoffMaxMs ?? 15000,
1112
+ onChange: (event) => set({ backoffMaxMs: Math.max(0, Math.round(num(event.target.value, 15000))) }),
1113
+ }),
1114
+ ),
1115
+ h(
1116
+ Field,
1117
+ { label: t('recovery') },
1118
+ h(
1119
+ 'select',
1120
+ { className: 'ar-select', value: value.recovery ?? 'timer', onChange: (event) => set({ recovery: event.target.value }) },
1121
+ h('option', { value: 'timer' }, t('recoveryTimer')),
1122
+ h('option', { value: 'never' }, t('recoveryNever')),
1123
+ ),
1124
+ ),
1125
+ h(
1126
+ Field,
1127
+ { label: t('effortPolicy') },
1128
+ h(
1129
+ 'select',
1130
+ { className: 'ar-select', value: value.effortPolicy ?? 'clamp', onChange: (event) => set({ effortPolicy: event.target.value }) },
1131
+ h('option', { value: 'clamp' }, t('effortPolicyClamp')),
1132
+ h('option', { value: 'drop' }, t('effortPolicyDrop')),
1133
+ h('option', { value: 'fail' }, t('effortPolicyFail')),
1134
+ ),
1135
+ ),
1136
+ h(
1137
+ Field,
1138
+ { label: t('contextPolicy') },
1139
+ h(
1140
+ 'select',
1141
+ { className: 'ar-select', value: value.contextPolicy ?? 'min', onChange: (event) => set({ contextPolicy: event.target.value }) },
1142
+ h('option', { value: 'min' }, t('contextMin')),
1143
+ h('option', { value: 'max' }, t('contextMax')),
1144
+ ),
1145
+ ),
1146
+ h(
1147
+ Field,
1148
+ { label: t('defaultContext') },
1149
+ h('input', {
1150
+ className: 'ar-input num',
1151
+ type: 'number',
1152
+ min: 1000,
1153
+ step: 1000,
1154
+ value: value.defaultContextWindow ?? 128000,
1155
+ onChange: (event) => set({ defaultContextWindow: Math.max(1000, Math.round(num(event.target.value, 128000))) }),
1156
+ }),
1157
+ ),
1158
+ h(
1159
+ Field,
1160
+ { label: t('utcOffset'), hint: t('timezone') },
1161
+ h('input', {
1162
+ className: 'ar-input num',
1163
+ type: 'number',
1164
+ min: -720,
1165
+ max: 840,
1166
+ value: value.utcOffsetMinutes ?? 480,
1167
+ onChange: (event) => set({ utcOffsetMinutes: Math.round(num(event.target.value, 480)) }),
1168
+ }),
1169
+ ),
1170
+ ),
1171
+ h(Toggle, { label: t('sticky'), title: t('stickyHint'), checked: value.sticky !== false, onChange: (next) => set({ sticky: next }) }),
1172
+ h(Toggle, { label: t('honorRetryAfter'), checked: value.honorRetryAfter !== false, onChange: (next) => set({ honorRetryAfter: next }) }),
1173
+ h(Toggle, { label: t('retryNetwork'), checked: value.retryOnNetwork !== false, onChange: (next) => set({ retryOnNetwork: next }) }),
1174
+ h(
1175
+ Field,
1176
+ { label: t('triggerCodes'), hint: t('triggerCodesHint') },
1177
+ h('input', {
1178
+ className: 'ar-input wide',
1179
+ value: (value.triggerCodes ?? []).join(','),
1180
+ onChange: (event) => set({ triggerCodes: splitList(event.target.value) }),
1181
+ }),
1182
+ ),
1183
+ h(
1184
+ Field,
1185
+ { label: t('triggerStatuses'), hint: t('triggerStatusesHint') },
1186
+ h('input', {
1187
+ className: 'ar-input wide',
1188
+ value: (value.triggerStatuses ?? []).join(','),
1189
+ onChange: (event) =>
1190
+ set({
1191
+ triggerStatuses: splitList(event.target.value)
1192
+ .map((item) => Math.round(num(item, 0)))
1193
+ .filter((item) => item > 0),
1194
+ }),
1195
+ }),
1196
+ ),
1197
+ )
1198
+ }
1199
+
1200
+ /**
1201
+ * Time windows reorder one profile's own chain, so they live inside that
1202
+ * profile's card: a window is meaningless without the routes it reorders.
1203
+ * Which routes go first is picked from the chain itself — typing
1204
+ * `provider/model` keys by hand was neither discoverable nor checkable.
1205
+ */
1206
+ function TimeWindows({ t, windows, chain, onChange }) {
1207
+ const routes = (chain ?? [])
1208
+ .filter((entry) => entry.enabled !== false && entry.provider && entry.model)
1209
+ .map((entry) => `${entry.provider}/${entry.model}`)
1210
+ const labelOf = (key) => {
1211
+ const entry = (chain ?? []).find((item) => `${item.provider}/${item.model}` === key)
1212
+ return entry === undefined || entry === null ? key : `${entry.provider}/${entry.model}`
1213
+ }
1214
+ const edit = (index, patch) => onChange(windows.map((item, at) => (at === index ? { ...item, ...patch } : item)))
1215
+ const editRange = (index, rangeIndex, patch) =>
1216
+ edit(index, {
1217
+ ranges: windowRanges(windows[index]).map((range, at) => (at === rangeIndex ? { ...range, ...patch } : range)),
1218
+ })
1219
+ const addRange = (index) => {
1220
+ const ranges = windowRanges(windows[index])
1221
+ edit(index, { ranges: [...ranges, { from: '00:00', to: '08:30' }] })
1222
+ }
1223
+ const removeRange = (index, rangeIndex) => {
1224
+ const ranges = windowRanges(windows[index]).filter((_, at) => at !== rangeIndex)
1225
+ // A window without a stretch of the day can never match, so the last
1226
+ // range stays until the whole window is removed.
1227
+ if (ranges.length === 0) return
1228
+ edit(index, { ranges })
1229
+ }
1230
+ // A new window starts as a copy of the configured chain, so it is a
1231
+ // complete fallback chain from the first moment and can be reordered.
1232
+ const add = () =>
1233
+ onChange([
1234
+ ...windows,
1235
+ {
1236
+ id: `window-${windows.length + 1}`,
1237
+ label: '',
1238
+ ranges: [{ from: '00:00', to: '08:30' }],
1239
+ order: [...routes],
1240
+ },
1241
+ ])
1242
+ const remove = (index) => onChange(windows.filter((_, at) => at !== index))
1243
+ return h(
1244
+ Section,
1245
+ {
1246
+ t,
1247
+ title: t('timeWindows'),
1248
+ count: windows.length,
1249
+ actions: [h('button', { key: 'add', className: 'ar-btn tiny', type: 'button', onClick: add }, `+ ${t('addWindow')}`)],
1250
+ },
1251
+ h('div', { className: 'ar-hint' }, t('timeWindowHint')),
1252
+ windows.length === 0
1253
+ ? h('div', { className: 'ar-muted' }, t('noWindows'))
1254
+ : windows.map((window, index) => {
1255
+ const ordered = orderByKeys(chain ?? [], window.order)
1256
+ const ranges = windowRanges(window)
1257
+ return h(
1258
+ 'div',
1259
+ { key: window.id ?? index, className: 'ar-window' },
1260
+ h(
1261
+ 'div',
1262
+ { className: 'ar-row' },
1263
+ h('input', {
1264
+ className: 'ar-input grow',
1265
+ value: window.label ?? '',
1266
+ placeholder: t('windowLabel'),
1267
+ onChange: (event) => edit(index, { label: event.target.value }),
1268
+ }),
1269
+ h(
1270
+ 'button',
1271
+ { className: 'ar-btn tiny danger', type: 'button', onClick: () => remove(index) },
1272
+ t('removeWindow'),
1273
+ ),
1274
+ ),
1275
+ // One named window, several stretches of the day: 00:30–08:30
1276
+ // and 22:00–23:30 are the same fallback chain.
1277
+ ranges.map((range, rangeIndex) =>
1278
+ h(
1279
+ 'div',
1280
+ { key: rangeIndex, className: 'ar-row' },
1281
+ h('input', {
1282
+ className: 'ar-input num',
1283
+ type: 'time',
1284
+ value: range.from,
1285
+ onChange: (event) => editRange(index, rangeIndex, { from: event.target.value }),
1286
+ }),
1287
+ h('span', { className: 'ar-muted' }, '→'),
1288
+ h('input', {
1289
+ className: 'ar-input num',
1290
+ type: 'time',
1291
+ value: range.to,
1292
+ onChange: (event) => editRange(index, rangeIndex, { to: event.target.value }),
1293
+ }),
1294
+ h(
1295
+ 'button',
1296
+ {
1297
+ className: 'ar-btn tiny',
1298
+ type: 'button',
1299
+ title: t('removeRange'),
1300
+ disabled: ranges.length <= 1,
1301
+ onClick: () => removeRange(index, rangeIndex),
1302
+ },
1303
+ '✕',
1304
+ ),
1305
+ ),
1306
+ ),
1307
+ h(
1308
+ 'div',
1309
+ { className: 'ar-row' },
1310
+ h('button', { className: 'ar-btn tiny', type: 'button', onClick: () => addRange(index) }, `+ ${t('addRange')}`),
1311
+ h('span', { className: 'ar-muted' }, t('rangeHint')),
1312
+ ),
1313
+ // Read-only here on purpose: the order is edited on the chain
1314
+ // itself, in the tab this window owns.
1315
+ h('div', { className: 'ar-label' }, t('windowOrderHint')),
1316
+ h(
1317
+ 'div',
1318
+ { className: 'ar-muted ar-order-preview' },
1319
+ ordered.length === 0 ? t('noRoutes') : ordered.map((entry) => labelOf(`${entry.provider}/${entry.model}`)).join(' → '),
1320
+ ),
1321
+ h('div', { className: 'ar-hint' }, t('orderEditHint')),
1322
+ )
1323
+ }),
1324
+ )
1325
+ }
1326
+
1327
+ function AutoRouterSettings(props) {
1328
+ const t = props.t
1329
+ const [loading, setLoading] = useState(true)
1330
+ const [error, setError] = useState('')
1331
+ const [notice, setNotice] = useState('')
1332
+ const [draft, setDraft] = useState(null)
1333
+ const [serverConfig, setServerConfig] = useState(null)
1334
+ const [revision, setRevision] = useState(undefined)
1335
+ const [status, setStatus] = useState(null)
1336
+ const [catalog, setCatalog] = useState({ providers: [] })
1337
+ const [tab, setTab] = useState('routes')
1338
+ const [busy, setBusy] = useState(false)
1339
+ const [dirty, setDirty] = useState(false)
1340
+ const [probes, setProbes] = useState({})
1341
+ const [jsonText, setJsonText] = useState('')
1342
+ const [jsonError, setJsonError] = useState('')
1343
+ const [scheme, setScheme] = useState(() => detectScheme())
1344
+ const [collapsed, setCollapsed] = useState(() => readCollapsed())
1345
+ const alive = useRef(true)
1346
+
1347
+ const toggleCard = (id) => {
1348
+ setCollapsed((previous) => {
1349
+ const next = new Set(previous)
1350
+ if (next.has(id)) next.delete(id)
1351
+ else next.add(id)
1352
+ writeCollapsed(next)
1353
+ return next
1354
+ })
1355
+ }
1356
+ const isOpen = (id) => !collapsed.has(id)
1357
+
1358
+ useEffect(() => {
1359
+ const sync = () => setScheme(detectScheme())
1360
+ sync()
1361
+ const media = window.matchMedia?.('(prefers-color-scheme: dark)')
1362
+ media?.addEventListener?.('change', sync)
1363
+ const observer =
1364
+ typeof MutationObserver === 'function'
1365
+ ? new MutationObserver(sync)
1366
+ : undefined
1367
+ if (observer !== undefined) {
1368
+ const options = { attributes: true, attributeFilter: ['class', 'data-theme', 'style'] }
1369
+ observer.observe(document.documentElement, options)
1370
+ if (document.body) observer.observe(document.body, options)
1371
+ }
1372
+ return () => {
1373
+ media?.removeEventListener?.('change', sync)
1374
+ observer?.disconnect()
1375
+ }
1376
+ }, [])
1377
+
1378
+ const flash = (message) => {
1379
+ setNotice(message)
1380
+ setTimeout(() => {
1381
+ if (alive.current) setNotice('')
1382
+ }, 3500)
1383
+ }
1384
+
1385
+ async function load({ keepDraft = false } = {}) {
1386
+ setLoading(true)
1387
+ setError('')
1388
+ try {
1389
+ const [state, cat] = await Promise.all([api('/api/autorouter/state'), api('/api/autorouter/catalog')])
1390
+ if (!alive.current) return
1391
+ setStatus(state.status ?? null)
1392
+ setRevision(state.revision)
1393
+ setServerConfig(state.config)
1394
+ if (!keepDraft) {
1395
+ setDraft(state.config)
1396
+ setDirty(false)
1397
+ setJsonText(JSON.stringify(state.config, null, 2))
1398
+ }
1399
+ setCatalog(cat)
1400
+ } catch (failure) {
1401
+ if (alive.current) setError(failure.message || t('unavailable'))
1402
+ } finally {
1403
+ if (alive.current) setLoading(false)
1404
+ }
1405
+ }
1406
+
1407
+ async function refreshStatus() {
1408
+ try {
1409
+ const state = await api('/api/autorouter/state')
1410
+ if (!alive.current) return
1411
+ setStatus(state.status ?? null)
1412
+ } catch {
1413
+ /* keep the last snapshot */
1414
+ }
1415
+ }
1416
+
1417
+ /**
1418
+ * Sends one tiny completion through the router itself — the only check that
1419
+ * proves the chain, the credential and the upstream dialect all work.
1420
+ */
1421
+ async function tryOnce() {
1422
+ if (busy) return
1423
+ setBusy(true)
1424
+ setError('')
1425
+ try {
1426
+ const result = await api('/api/autorouter/try', { method: 'POST', body: JSON.stringify({}) })
1427
+ if (!alive.current) return
1428
+ if (result.ok) flash(`${t('tryOk')} · ${result.ms}ms · ${result.route ?? result.profile}`)
1429
+ else setError(`${t('tryFailed')}: ${result.error ?? result.reason ?? ''}`)
1430
+ await refreshStatus()
1431
+ } catch (failure) {
1432
+ if (!alive.current) return
1433
+ // A page that was reloaded while the host kept the old process is the
1434
+ // one case worth naming: the route simply is not there yet.
1435
+ if (failure.status === 404 || failure.status === 405) setError(t('tryOutdated'))
1436
+ else setError(`${t('tryFailed')}: ${failure.message}`)
1437
+ } finally {
1438
+ if (alive.current) setBusy(false)
1439
+ }
1440
+ }
1441
+
1442
+ useEffect(() => {
1443
+ alive.current = true
1444
+ load()
1445
+ return () => {
1446
+ alive.current = false
1447
+ }
1448
+ }, [])
1449
+
1450
+ useEffect(() => {
1451
+ const timer = setInterval(() => {
1452
+ if (document.visibilityState === 'visible') refreshStatus()
1453
+ }, 5000)
1454
+ return () => clearInterval(timer)
1455
+ }, [])
1456
+
1457
+ const profiles = draft?.profiles ?? []
1458
+
1459
+ const switchTab = (next) => {
1460
+ if (next === 'json') setJsonText(JSON.stringify(draft, null, 2))
1461
+ setTab(next)
1462
+ }
1463
+
1464
+ const editDraft = (mutator) => {
1465
+ setDraft((previous) => {
1466
+ const next = structuredClone(previous)
1467
+ mutator(next)
1468
+ return next
1469
+ })
1470
+ setDirty(true)
1471
+ }
1472
+
1473
+ const editProfile = (index, patch) => {
1474
+ editDraft((next) => {
1475
+ next.profiles[index] = { ...next.profiles[index], ...patch }
1476
+ })
1477
+ }
1478
+
1479
+ /**
1480
+ * Discard the draft instead of refetching: the button sits next to Save,
1481
+ * so it has to be the inverse of Save (local, instant, no network) and
1482
+ * never silently throw away edits the user did not ask to drop.
1483
+ */
1484
+ const undo = () => {
1485
+ if (serverConfig === null) return
1486
+ setDraft(structuredClone(serverConfig))
1487
+ setDirty(false)
1488
+ setJsonError('')
1489
+ flash(t('reverted'))
1490
+ }
1491
+
1492
+ async function save() {
1493
+ if (draft === null || busy) return
1494
+ const ids = new Set()
1495
+ for (const item of profiles) {
1496
+ const id = typeof item.id === 'string' ? item.id.trim() : ''
1497
+ if (id === '') {
1498
+ setError(t('profileIdRequired'))
1499
+ return
1500
+ }
1501
+ if (ids.has(id)) {
1502
+ setError(t('duplicateProfile'))
1503
+ return
1504
+ }
1505
+ ids.add(id)
1506
+ }
1507
+ setBusy(true)
1508
+ setError('')
1509
+ try {
1510
+ const body = await api('/api/autorouter/config', { method: 'PUT', body: JSON.stringify({ value: draft, revision }) })
1511
+ if (!alive.current) return
1512
+ setRevision(body.revision)
1513
+ setServerConfig(body.config)
1514
+ setDraft(body.config)
1515
+ setJsonText(JSON.stringify(body.config, null, 2))
1516
+ setDirty(false)
1517
+ flash(t('saved'))
1518
+ // Only the status block needs a refresh: re-reading the config would
1519
+ // write a possibly lagging server projection over what was just saved.
1520
+ await refreshStatus()
1521
+ } catch (failure) {
1522
+ if (!alive.current) return
1523
+ if (failure.status === 409 && failure.body?.config) {
1524
+ setError(t('conflict'))
1525
+ setServerConfig(failure.body.config)
1526
+ setRevision(failure.body.revision)
1527
+ } else {
1528
+ setError(`${t('failed')}: ${failure.message}`)
1529
+ }
1530
+ } finally {
1531
+ if (alive.current) setBusy(false)
1532
+ }
1533
+ }
1534
+
1535
+ function addProfile() {
1536
+ const ids = new Set(profiles.map((item) => item.id))
1537
+ let index = profiles.length + 1
1538
+ while (ids.has(`profile-${index}`)) index += 1
1539
+ const id = `profile-${index}`
1540
+ editDraft((next) => {
1541
+ next.profiles.push({
1542
+ id,
1543
+ name: id,
1544
+ enabled: true,
1545
+ chain: [],
1546
+ policy: structuredClone(next.profiles[next.profiles.length - 1]?.policy ?? {}),
1547
+ })
1548
+ })
1549
+ }
1550
+
1551
+ function removeProfile(index) {
1552
+ if (profiles.length <= 0) return
1553
+ editDraft((next) => {
1554
+ next.profiles.splice(index, 1)
1555
+ })
1556
+ }
1557
+
1558
+ function addRoute(profileId, { provider, model }) {
1559
+ editDraft((next) => {
1560
+ const target = next.profiles.find((item) => item.id === profileId)
1561
+ const key = `${provider}/${model}`
1562
+ target.chain.push({
1563
+ id: key,
1564
+ enabled: true,
1565
+ provider,
1566
+ model,
1567
+ cooldownMs: 300000,
1568
+ effortMap: {},
1569
+ })
1570
+ // Every window keeps a complete order, so a new route has to land in
1571
+ // each of them too — otherwise it would only ever run as a leftover.
1572
+ const windows = target.policy?.timeWindows ?? []
1573
+ for (const window of windows) window.order = [...(window.order ?? []), key]
1574
+ })
1575
+ }
1576
+
1577
+ async function probe(profileTarget, entry) {
1578
+ const key = `${profileTarget.id}::${entry.provider}/${entry.model}`
1579
+ setProbes((previous) => ({ ...previous, [key]: { busy: true } }))
1580
+ try {
1581
+ const result = await api('/api/autorouter/probe', {
1582
+ method: 'POST',
1583
+ body: JSON.stringify({ provider: entry.provider, model: entry.model }),
1584
+ })
1585
+ if (!alive.current) return
1586
+ setProbes((previous) => ({
1587
+ ...previous,
1588
+ [key]: { busy: false, result: result.ok === true, ms: result.ms ?? 0, error: result.error },
1589
+ }))
1590
+ } catch (failure) {
1591
+ if (!alive.current) return
1592
+ setProbes((previous) => ({ ...previous, [key]: { busy: false, result: false, error: failure.message } }))
1593
+ }
1594
+ }
1595
+
1596
+ async function clearCooldown(key) {
1597
+ try {
1598
+ await api('/api/autorouter/cooldown', { method: 'POST', body: JSON.stringify(key ? { key } : {}) })
1599
+ refreshStatus()
1600
+ } catch (failure) {
1601
+ setError(failure.message)
1602
+ }
1603
+ }
1604
+
1605
+ if (loading && draft === null) {
1606
+ return h('div', { className: 'ar-root' }, h('div', { className: 'ar-muted' }, t('loading')))
1607
+ }
1608
+ if (draft === null) {
1609
+ return h(
1610
+ 'div',
1611
+ { className: 'ar-root' },
1612
+ h('h2', { className: 'ar-title' }, t('title')),
1613
+ h('div', { className: 'ar-banner err' }, `${t('unavailable')}: ${error || 'unknown error'}`),
1614
+ h('div', null, h('button', { className: 'ar-btn', type: 'button', onClick: () => load() }, t('retry'))),
1615
+ )
1616
+ }
1617
+
1618
+ const routes = status?.routes ?? []
1619
+ const stats = status?.stats ?? {}
1620
+
1621
+ return h(
1622
+ 'div',
1623
+ { className: 'ar-root', 'data-scheme': scheme, style: { colorScheme: scheme } },
1624
+ h(
1625
+ 'div',
1626
+ { className: 'ar-head' },
1627
+ h(
1628
+ 'div',
1629
+ null,
1630
+ h('h2', { className: 'ar-title' }, t('title')),
1631
+ h('p', { className: 'ar-sub' }, t('subtitle')),
1632
+ ),
1633
+ h(
1634
+ 'div',
1635
+ { className: 'ar-actions' },
1636
+ // No enable switch: the plugin is on when it is installed, and the
1637
+ // JSON tab is the escape hatch for a hand-edited enabled:false.
1638
+ draft.enabled === false ? h('span', { key: 'off', className: 'ar-badge warn' }, t('profileDisabled')) : null,
1639
+ dirty ? h('span', { className: 'ar-badge warn' }, t('dirty')) : null,
1640
+ h(
1641
+ 'button',
1642
+ { className: 'ar-btn primary', type: 'button', disabled: busy, onClick: save, title: t('saveHint') },
1643
+ busy ? t('saving') : t('save'),
1644
+ ),
1645
+ h(
1646
+ 'button',
1647
+ { className: 'ar-btn', type: 'button', disabled: busy || !dirty, onClick: undo, title: t('undoHint') },
1648
+ t('undo'),
1649
+ ),
1650
+ ),
1651
+ ),
1652
+ error ? h('div', { className: 'ar-banner err', role: 'alert' }, error) : null,
1653
+ notice ? h('div', { className: 'ar-banner ok' }, notice) : null,
1654
+ h(Tabs, { tab, t, onTab: switchTab }),
1655
+
1656
+ tab === 'routes'
1657
+ ? h(
1658
+ 'div',
1659
+ { className: 'ar-root', style: { gap: 12 } },
1660
+ h(
1661
+ 'div',
1662
+ { className: 'ar-row' },
1663
+ h('span', { className: 'ar-hint' }, t('routesHint')),
1664
+ h('span', { style: S.right }, h('button', { className: 'ar-btn', type: 'button', onClick: addProfile }, `+ ${t('addProfile')}`)),
1665
+ ),
1666
+ profiles.length === 0
1667
+ ? h('div', { className: 'ar-empty' }, h('div', { className: 'ar-hint' }, t('noProfiles')))
1668
+ : null,
1669
+ profiles.map((item, index) =>
1670
+ h(ProfileCard, {
1671
+ key: index,
1672
+ profile: item,
1673
+ index,
1674
+ open: isOpen(`profile:${index}`),
1675
+ onToggle: () => toggleCard(`profile:${index}`),
1676
+ profileCount: profiles.length,
1677
+ t,
1678
+ catalog,
1679
+ probes,
1680
+ onProbe: probe,
1681
+ onEdit: (patch) => editProfile(index, patch),
1682
+ onRemove: removeProfile,
1683
+ onAddRoute: addRoute,
1684
+ }),
1685
+ ),
1686
+ )
1687
+ : null,
1688
+
1689
+ tab === 'status'
1690
+ ? h(
1691
+ 'div',
1692
+ { className: 'ar-root', style: { gap: 12 } },
1693
+ h(
1694
+ Card,
1695
+ {
1696
+ t,
1697
+ open: isOpen('status'),
1698
+ onToggle: () => toggleCard('status'),
1699
+ head: [
1700
+ h('span', { key: 'title', className: 'ar-card-title' }, t('status')),
1701
+ h('span', { key: 'count', className: 'ar-muted' }, `${routes.length} ${t('routes')}`),
1702
+ ],
1703
+ actions: [
1704
+ h('button', { key: 'try', className: 'ar-btn tiny', type: 'button', onClick: tryOnce, disabled: busy }, t('tryOnce')),
1705
+ h('button', { key: 'refresh', className: 'ar-btn tiny', type: 'button', onClick: refreshStatus }, t('refresh')),
1706
+ h('button', { key: 'clear', className: 'ar-btn tiny', type: 'button', onClick: () => clearCooldown() }, t('clearAll')),
1707
+ ],
1708
+ },
1709
+ h(
1710
+ 'div',
1711
+ { className: 'ar-hint' },
1712
+ `${t('stats')}: ${num(stats.attempts)} / ${num(stats.successes)} / ${num(stats.failures)} / ${num(stats.switches)}`,
1713
+ stats.lastRoute ? ` · ${t('lastRoute')}: ${stats.lastRoute}` : '',
1714
+ ),
1715
+ stats.lastError ? h('div', { className: 'ar-hint', style: { color: '#e5484d' } }, stats.lastError) : null,
1716
+ status?.version
1717
+ ? h('div', { className: 'ar-hint' }, `host v${status.version} · ${t('hostVersionHint')}`)
1718
+ : h('div', { className: 'ar-hint' }, t('hostVersionUnknown')),
1719
+ h(
1720
+ 'div',
1721
+ { style: S.tableWrap },
1722
+ h(
1723
+ 'table',
1724
+ { className: 'ar-table' },
1725
+ h(
1726
+ 'thead',
1727
+ null,
1728
+ h(
1729
+ 'tr',
1730
+ null,
1731
+ h('th', null, t('profile')),
1732
+ h('th', null, t('provider')),
1733
+ h('th', null, t('model')),
1734
+ h('th', null, t('health')),
1735
+ h('th', null, ''),
1736
+ ),
1737
+ ),
1738
+ h(
1739
+ 'tbody',
1740
+ null,
1741
+ routes.map((row) =>
1742
+ h(
1743
+ 'tr',
1744
+ { key: `${row.profileId}/${row.key}` },
1745
+ h('td', null, row.profileId),
1746
+ h('td', null, row.provider),
1747
+ h('td', null, row.model),
1748
+ h('td', null, h(HealthBadge, { row, t })),
1749
+ h(
1750
+ 'td',
1751
+ null,
1752
+ h(
1753
+ 'button',
1754
+ { className: 'ar-btn tiny', type: 'button', onClick: () => clearCooldown(row.key) },
1755
+ t('clearCooldown'),
1756
+ ),
1757
+ ),
1758
+ ),
1759
+ ),
1760
+ ),
1761
+ ),
1762
+ ),
1763
+ h(
1764
+ 'div',
1765
+ { className: 'ar-hint' },
1766
+ (status?.sessions ?? []).length === 0
1767
+ ? t('noSessions')
1768
+ : status.sessions
1769
+ .map((record) => `${record.sessionId.slice(0, 8)} → ${record.profileId}/${record.key} (${fmtAge(record.ageMs)})`)
1770
+ .join(' · '),
1771
+ ),
1772
+ ),
1773
+ )
1774
+ : null,
1775
+
1776
+ tab === 'json'
1777
+ ? h(
1778
+ 'div',
1779
+ { className: 'ar-root', style: { gap: 8 } },
1780
+ h('div', { className: 'ar-hint' }, t('jsonHint')),
1781
+ h('textarea', {
1782
+ className: 'ar-json',
1783
+ spellCheck: false,
1784
+ value: jsonText,
1785
+ onChange: (event) => setJsonText(event.target.value),
1786
+ }),
1787
+ jsonError ? h('div', { className: 'ar-banner err' }, jsonError) : null,
1788
+ h(
1789
+ 'div',
1790
+ { className: 'ar-row' },
1791
+ h(
1792
+ 'button',
1793
+ {
1794
+ className: 'ar-btn',
1795
+ type: 'button',
1796
+ onClick: () => {
1797
+ try {
1798
+ const parsed = JSON.parse(jsonText)
1799
+ setDraft(parsed)
1800
+ setDirty(true)
1801
+ setJsonError('')
1802
+ flash(t('applyJson'))
1803
+ } catch (failure) {
1804
+ setJsonError(`${t('jsonError')}: ${failure.message}`)
1805
+ }
1806
+ },
1807
+ },
1808
+ t('applyJson'),
1809
+ ),
1810
+ h(
1811
+ 'button',
1812
+ {
1813
+ className: 'ar-btn',
1814
+ type: 'button',
1815
+ onClick: () => {
1816
+ if (serverConfig === null) return
1817
+ setJsonText(JSON.stringify(serverConfig, null, 2))
1818
+ setJsonError('')
1819
+ },
1820
+ },
1821
+ t('undo'),
1822
+ ),
1823
+ ),
1824
+ )
1825
+ : null,
1826
+ )
1827
+ }
1828
+
1829
+ /**
1830
+ * Settings navigation glyph: one source fanning out into three routes.
1831
+ * Same contract as the shipped section icons — `{ size }`, 24-unit box,
1832
+ * `currentColor`, so it inherits the sidebar's own colour and dark mode.
1833
+ */
1834
+ function AutoRouterIcon({ size = 16 }) {
1835
+ return h(
1836
+ 'svg',
1837
+ {
1838
+ width: size,
1839
+ height: size,
1840
+ viewBox: '0 0 24 24',
1841
+ fill: 'none',
1842
+ stroke: 'currentColor',
1843
+ strokeWidth: 1.7,
1844
+ strokeLinecap: 'round',
1845
+ strokeLinejoin: 'round',
1846
+ 'aria-hidden': true,
1847
+ },
1848
+ h('circle', { cx: 4.6, cy: 12, r: 1.5 }),
1849
+ h('path', { d: 'M6.5 12h2.6' }),
1850
+ h('path', { d: 'M9.1 12c3.2 0 3.2-6.2 6.4-6.2h2.1' }),
1851
+ h('path', { d: 'M9.1 12h8.4' }),
1852
+ h('path', { d: 'M9.1 12c3.2 0 3.2 6.2 6.4 6.2h2.1' }),
1853
+ h('circle', { cx: 19.2, cy: 5.8, r: 1.4 }),
1854
+ h('circle', { cx: 19.2, cy: 12, r: 1.4 }),
1855
+ h('circle', { cx: 19.2, cy: 18.2, r: 1.4 }),
1856
+ )
1857
+ }
1858
+
1859
+ return {
1860
+ inject: ['slots', 'locale'],
1861
+ apply(ctx) {
1862
+ const style = document.createElement('style')
1863
+ style.dataset.plugin = 'dsh-autorouter'
1864
+ style.textContent = CSS
1865
+ document.head.appendChild(style)
1866
+ ctx.effect(() => () => style.remove(), 'autorouter: styles')
1867
+
1868
+ ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'autorouter: locale')
1869
+ const t = ctx.locale.bind(NS)
1870
+
1871
+ const Page = (props) => h(AutoRouterSettings, { ...props, t })
1872
+
1873
+ ctx.slots.inject('settings.section', () =>
1874
+ ctx.slots.register(
1875
+ {
1876
+ name: 'settings.section',
1877
+ id: 'autorouter',
1878
+ order: 16,
1879
+ label: () => t('nav'),
1880
+ locale: NS,
1881
+ },
1882
+ Page,
1883
+ ),
1884
+ )
1885
+
1886
+ ctx.slots.inject('settings.section.icon', () =>
1887
+ ctx.slots.register({ name: 'settings.section.icon', id: 'autorouter' }, AutoRouterIcon),
1888
+ )
1889
+ },
1890
+ }
1891
+ },
1892
+ })