@sixzjd/dsh-workbuddy-connect 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,6 +47,8 @@ DSH (pi-ai) ──OpenAI 协议──▶ 127.0.0.1 shim ──WorkBuddy 协
47
47
  - **价格倍率与免费标记**:模型名后直接拼上游倍率(`Deepseek-V4.1-Flash · x0.00`),免费模型额外挂一个「免费」角标。活动过期的倍率不会被继续显示为当前价格——插件会把它标成「价格暂不可用」。
48
48
  - **额度明细**:按资源包逐行给出「剩余 / 总量 + 进度条」,标注到期时间与下一轮刷新时间。读的是**周期额度**而不是池额度——池额度在月度资源用完之后仍会报「一点没动、全部还在」。
49
49
  - **上下文窗口开关**:可选择按上游声明的默认窗口(300K)或最大窗口(1M)发请求,两版各自独立保存。
50
+ - **多账号快速切换**:按版本(国服 / 国际)各存一份账号列表,切换即时生效,不需要重新走设备授权。新增账号=登录一次,或从桌面 App 已保存的历史会话里导入某个账号。国服与国际的账号互不可见——两边的令牌不通用,混在一起要到发请求时才失败。登出只登出当前账号,其他账号保留。账号文件以 uid 哈希命名,卡片上只显示 uid 前 8 位,截图不会带出完整标识。
51
+ - **缓存命中率**:卡片直接显示前缀缓存的实际命中率(累计 + 最近一轮 + 统计轮数),数字来自上游每次返回的 `usage`,不是估算。`0 轮` 表示重启后还没请求过,不会显示成 `0%`。
50
52
  - **推理档位**:上游声明了可用档位的模型才有档位可选;上游用单数形态声明的档位会被折算成完整阶梯,而不是整个丢掉。
51
53
 
52
54
  ## 安装
package/client.js CHANGED
@@ -24,6 +24,7 @@ window.__ModuleLoader__.load({
24
24
  const MODELS_PATH = `${BASE}/models`;
25
25
  const AUTH_PATH = `${BASE}/auth`;
26
26
  const UPDATE_PATH = `${BASE}/update`;
27
+ const ACCOUNTS_PATH = `${BASE}/accounts`;
27
28
 
28
29
  const zh = {
29
30
  title: "WorkBuddy",
@@ -48,11 +49,29 @@ window.__ModuleLoader__.load({
48
49
  refresh: "刷新目录",
49
50
  refreshing: "刷新中…",
50
51
  models: "模型开关",
51
- modelsHint: "关闭的模型从 DSH 模型选择器中隐藏。",
52
+ modelsHint: "关闭的模型从 DSH 模型选择器中隐藏。模型后的标签来自上游自己的声明(如「限时免费」「夜间折扣」);上游不提供会员/档位字段,所以这里只显示它真说了什么,不猜。",
52
53
  search: "搜索模型 / ID",
53
54
  enableAll: "全部开启",
54
55
  disableAll: "全部关闭",
55
56
  freeTag: "免费",
57
+ paidTag: "需积分",
58
+ modelCount: "个模型",
59
+ accounts: "当前账号",
60
+ removeCurrent: "删除当前",
61
+ clearAll: "清除全部",
62
+ removeAccount: "移除",
63
+ accountExpired: "已过期",
64
+ accountActive: "当前",
65
+ accountsCurrent: "当前账号",
66
+ addAccount: "添加账号",
67
+ addAccountHint: "添加新账号,当前帐号会被保留",
68
+ accountSwitched: "已切换账号",
69
+ accountRemoved: "已移除账号",
70
+ removeConfirm: "移除这个账号?它的登录信息会从本机删除。",
71
+ cacheHit: "缓存命中",
72
+ cacheLast: "最近一轮",
73
+ cacheTurns: "轮",
74
+ cacheIdle: "本次启动后还没有请求",
56
75
  rateTag: "倍率",
57
76
  ctxTag: "上下文",
58
77
  imgTag: "图片",
@@ -73,16 +92,7 @@ window.__ModuleLoader__.load({
73
92
  signedOutHint: "登录后才会出现模型分组。",
74
93
  sessionStale: "上游拒绝了这份凭据:桌面 App 换过会话了。点「从桌面 App 导入」重新接入,或重新登录。",
75
94
  updateTitle: "插件更新",
76
- updateCheck: "检查更新",
77
- updateChecking: "检查中…",
78
- updateAvailable: "有新版本",
79
- updateCurrent: "已是最新",
80
- updateApply: "更新到此版本",
81
- updateRunning: "正在更新…",
82
- updateLocalCopy: "这个安装来自本地目录,没有可比较的远程仓库。",
83
- updateUnknown: "暂时查不到远程状态:",
84
95
  updateHint: "git 版本可以在这里一键检查并更新到上游最新提交;DSH 自己只给官方插件显示「更新」。",
85
- updateDone: "已更新,重启 App 后生效。",
86
96
  accountRestricted: "上游已限制这个账号(不是凭据问题,重新登录或重新导入都无效)。只有申诉才能解除:在 WorkBuddy 里提交反馈。",
87
97
  tabGlobal: "国际版",
88
98
  tabCN: "国内版",
@@ -110,11 +120,29 @@ window.__ModuleLoader__.load({
110
120
  refresh: "Refresh catalog",
111
121
  refreshing: "Refreshing…",
112
122
  models: "Model toggles",
113
- modelsHint: "Disabled models are hidden from DSH's model picker.",
123
+ modelsHint: "Disabled models are hidden from DSH's model picker. The tags after a model are the upstream's own labels (e.g. “limited-time free”, “night discount”); the upstream exposes no membership or tier field, so only what it actually says is shown.",
114
124
  search: "search models / id",
115
125
  enableAll: "Enable all",
116
126
  disableAll: "Disable all",
117
127
  freeTag: "free",
128
+ paidTag: "uses credits",
129
+ modelCount: "models",
130
+ accounts: "Current account",
131
+ removeCurrent: "Delete current",
132
+ clearAll: "Clear all",
133
+ removeAccount: "Remove",
134
+ accountExpired: "expired",
135
+ accountActive: "active",
136
+ accountsCurrent: "Active account",
137
+ addAccount: "Add account",
138
+ addAccountHint: "Add another account; the current one is kept.",
139
+ accountSwitched: "Account switched",
140
+ accountRemoved: "Account removed",
141
+ removeConfirm: "Remove this account? Its sign-in will be deleted from this machine.",
142
+ cacheHit: "cache hit",
143
+ cacheLast: "latest",
144
+ cacheTurns: "turns",
145
+ cacheIdle: "no requests yet this session",
118
146
  rateTag: "rate",
119
147
  ctxTag: "ctx",
120
148
  imgTag: "image",
@@ -135,16 +163,7 @@ window.__ModuleLoader__.load({
135
163
  signedOutHint: "The model group appears after you sign in.",
136
164
  sessionStale: "The upstream refused this credential — the desktop app rotated its session. Press “Import from the desktop app” again, or sign in once more.",
137
165
  updateTitle: "Plugin update",
138
- updateCheck: "Check for updates",
139
- updateChecking: "Checking…",
140
- updateAvailable: "Update available",
141
- updateCurrent: "Up to date",
142
- updateApply: "Update to this commit",
143
- updateRunning: "Updating…",
144
- updateLocalCopy: "This install comes from a local path, so there is no remote to compare with.",
145
- updateUnknown: "Cannot read the remote right now: ",
146
166
  updateHint: "For a git install this checks upstream and updates to its latest commit in one click; DSH itself only shows Update for official plugins.",
147
- updateDone: "Updated. Restart the app to load it.",
148
167
  accountRestricted: "The upstream has restricted this account — this is not a credential problem, so signing in or importing again will not help. Only an appeal lifts it: submit feedback in WorkBuddy.",
149
168
  tabGlobal: "Global",
150
169
  tabCN: "China",
@@ -168,10 +187,21 @@ window.__ModuleLoader__.load({
168
187
  .wb-dot.wb-dot-load{background:var(--dsw-alias-state-warning-primary,#d98416)}
169
188
  .wb-body{padding:2px 16px 16px;display:flex;flex-direction:column;gap:14px}
170
189
  .wb-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
190
+ /* The account toolbar has to stay on ONE line: with flex-wrap the three
191
+ actions slid onto a second line under the dropdown, so the row read as
192
+ two unrelated groups. */
193
+ .wb-row.wb-row-nowrap{flex-wrap:nowrap;min-width:0}
194
+ .wb-row-nowrap .wb-account-label{flex:none}
195
+ .wb-row-nowrap .wb-dd{flex:0 1 auto;min-width:120px;max-width:280px}
196
+ .wb-row-nowrap .wb-row-actions{flex:none;white-space:nowrap}
197
+ .wb-row-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-left:auto}
171
198
  .wb-label{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#74747c)}
172
199
  .wb-badge{font-size:11px;padding:2px 8px;border-radius:99px;border:.5px solid var(--dsw-alias-border-l2,#dedee3);color:var(--dsw-alias-label-secondary,#74747c);white-space:nowrap}
173
200
  .wb-badge.wb-good{color:var(--dsw-alias-state-business-primary,#4176e6);border-color:currentColor}
174
201
  .wb-badge.wb-free{color:var(--dsw-alias-state-success-primary,#2f9e44);border-color:currentColor}
202
+ /* An upstream-declared label (limit-time free, night discount) is
203
+ information, so it stays quiet rather than warning-coloured. */
204
+ .wb-badge.wb-upstream{color:var(--dsw-alias-state-business-primary,#4176e6);border-color:currentColor}
175
205
  .wb-input,.wb-button{height:30px;padding:0 10px;color:var(--dsw-alias-label-primary,#25252a);background:var(--dsw-alias-bg-layer-1,#fff);border:.5px solid var(--dsw-alias-border-l4,#d4d6db);border-radius:var(--dsw-radius-md,8px);font:inherit;font-size:13px}
176
206
  .wb-input{flex:1;min-width:160px}
177
207
  .wb-update-action{display:inline-flex;align-items:center;gap:8px;min-width:0}
@@ -192,6 +222,34 @@ window.__ModuleLoader__.load({
192
222
  .wb-model-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
193
223
  .wb-model-id{flex:0 1 auto;min-width:0;max-width:38%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-tertiary,#9a9aa3);font-size:11px}
194
224
  .wb-model .wb-badge{flex:none}
225
+ /* Settings-row shape, matching the DSH settings page (and the usage
226
+ dashboard plugin): title + description on the left, one control right. */
227
+ .wb-account-block{margin-top:2px}
228
+ .wb-account-label{display:flex;align-items:center;gap:6px}
229
+ .wb-config-row{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:10px 0;border-bottom:.5px solid var(--dsw-alias-border-l2,#dedee3)}
230
+ .wb-config-label{display:flex;flex-direction:column;gap:2px;min-width:0}
231
+ .wb-config-title{font-size:13px;font-weight:500;line-height:20px;color:var(--dsw-alias-label-primary,#25252a)}
232
+ .wb-config-desc{font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary,#74747c)}
233
+ .wb-config-control{display:flex;align-items:center;gap:8px;flex:none}
234
+ .wb-config-value{font-size:13px;color:var(--dsw-alias-label-primary,#25252a);max-width:220px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
235
+ /* Same dropdown as the DSH usage dashboard: a settings-style trigger and a
236
+ themed panel, rather than the OS-native menu a <select> produces. */
237
+ .wb-dd{position:relative;min-width:0;max-width:100%}
238
+ .wb-dd-trigger{box-sizing:border-box;display:flex;align-items:center;gap:8px;height:32px;padding:0 12px;border:none;border-radius:var(--dsw-radius-md,8px);background-color:var(--dsw-alias-bg-module-platform,#f5f6f7);color:var(--dsw-alias-label-primary,#25252a);font:inherit;font-size:13px;line-height:20px;cursor:pointer;max-width:100%;transition:background-color .15s ease}
239
+ .wb-dd-trigger:hover{background-color:var(--dsw-alias-interactive-bg-hover,#f1f1f3)}
240
+ .wb-dd-trigger:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary,#4176e6);outline-offset:1px}
241
+ .wb-dd-trigger[disabled]{color:var(--dsw-alias-label-tertiary,#9a9aa3);cursor:default}
242
+ .wb-dd-value{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
243
+ .wb-dd-caret{margin-left:auto;flex:none;color:var(--dsw-alias-label-secondary,#74747c);transition:transform .15s ease}
244
+ .wb-dd-open .wb-dd-caret{transform:rotate(180deg)}
245
+ .wb-dd-panel{position:absolute;z-index:40;top:calc(100% + 6px);left:0;min-width:100%;max-height:320px;overflow-y:auto;padding:6px;border-radius:var(--dsw-radius-panel,12px);background:var(--dsw-alias-bg-layer-1,#fff);box-shadow:0 8px 24px rgba(0,0,0,.14);border:.5px solid var(--dsw-alias-border-l2,#dedee3)}
246
+ .wb-dd-option{display:flex;align-items:center;gap:12px;padding:9px 12px;border-radius:var(--dsw-radius-sm,6px);color:var(--dsw-alias-label-primary,#25252a);font-size:13px;line-height:20px;cursor:pointer;white-space:nowrap}
247
+ .wb-dd-option-label{min-width:0;overflow:hidden;text-overflow:ellipsis}
248
+ .wb-dd-active{background:var(--dsw-alias-interactive-bg-hover,#f1f1f3)}
249
+ .wb-dd-selected{font-weight:500}
250
+ .wb-dd-check{margin-left:auto;flex:none;color:var(--dsw-alias-label-primary,#25252a)}
251
+ .wb-button.wb-link{height:auto;padding:0 2px;border:0;background:transparent;color:var(--dsw-alias-state-danger-primary,#d94a4a);font-size:12px}
252
+ .wb-button.wb-link:hover{background:transparent;text-decoration:underline}
195
253
  .wb-quota{display:flex;flex-direction:column;gap:6px}
196
254
  .wb-quota-row{display:flex;align-items:center;gap:8px;font-size:12px}
197
255
  .wb-bar{flex:1;height:6px;border-radius:99px;background:var(--dsw-alias-border-l2,#dedee3);overflow:hidden}
@@ -217,6 +275,90 @@ window.__ModuleLoader__.load({
217
275
 
218
276
  const isStatus = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.status === "ok"
219
277
 
278
+ /**
279
+ * A dropdown shaped exactly like the DSH settings' own select and the usage
280
+ * dashboard's picker: a trigger on the module-platform background, a panel
281
+ * with a check on the selected row. The native <select> rendered the OS menu
282
+ * shown in the screenshot, which does not belong to this theme; keeping the
283
+ * same markup and --dsw-* tokens makes the account switcher read as part of
284
+ * the settings page rather than an embedded widget.
285
+ */
286
+ function Dropdown({ label, value, options, onChange, disabled }) {
287
+ const [open, setOpen] = React.useState(false)
288
+ const [active, setActive] = React.useState(-1)
289
+ const rootRef = React.useRef(null)
290
+ const triggerRef = React.useRef(null)
291
+ const listRef = React.useRef(null)
292
+ const listId = React.useMemo(() => "wb-dd-" + Math.random().toString(36).slice(2, 9), [])
293
+ const current = options.find((option) => option.value === value)
294
+ const choose = (index) => {
295
+ const option = options[index]
296
+ if (option !== undefined) onChange(option.value)
297
+ setOpen(false)
298
+ setActive(-1)
299
+ triggerRef.current?.focus?.()
300
+ }
301
+ const onKeyDown = (event) => {
302
+ if (event.key === "Escape") { setOpen(false); return }
303
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
304
+ event.preventDefault()
305
+ if (!open) { setOpen(true); setActive(Math.max(0, options.findIndex((o) => o.value === value))); return }
306
+ const delta = event.key === "ArrowDown" ? 1 : -1
307
+ setActive((i) => (i + delta + options.length) % options.length)
308
+ return
309
+ }
310
+ if (event.key === "Enter" || event.key === " ") {
311
+ event.preventDefault()
312
+ if (open) choose(active);
313
+ else setOpen(true)
314
+ }
315
+ }
316
+ React.useEffect(() => {
317
+ if (!open) return
318
+ const onPointerDown = (event) => {
319
+ if (!rootRef.current?.contains?.(event.target)) setOpen(false)
320
+ }
321
+ document.addEventListener("pointerdown", onPointerDown)
322
+ return () => document.removeEventListener("pointerdown", onPointerDown)
323
+ }, [open])
324
+ React.useEffect(() => {
325
+ if (!open || active < 0 || listRef.current === null) return
326
+ listRef.current.querySelector(`[data-index="${active}"]`)?.scrollIntoView?.({ block: "nearest" })
327
+ }, [open, active])
328
+
329
+ return h("div", { className: "wb-dd", ref: rootRef },
330
+ h("button", {
331
+ type: "button",
332
+ className: `wb-dd-trigger${open ? " wb-dd-open" : ""}`,
333
+ ref: triggerRef,
334
+ disabled: disabled === true,
335
+ "aria-label": label,
336
+ "aria-haspopup": "listbox",
337
+ "aria-expanded": open,
338
+ onClick: () => setOpen((v) => !v),
339
+ onKeyDown,
340
+ },
341
+ h("span", { className: "wb-dd-value" }, current?.label ?? ""),
342
+ h("svg", { className: "wb-dd-caret", width: 12, height: 12, viewBox: "0 0 12 12", fill: "none", "aria-hidden": "true", focusable: "false" },
343
+ h("path", { d: "M3 4.5L6 7.5L9 4.5", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round" }))),
344
+ open ? h("div", { className: "wb-dd-panel", role: "listbox", ref: listRef, "aria-label": label, "aria-activedescendant": active >= 0 ? `${listId}-${active}` : undefined },
345
+ options.map((option, index) => h("div", {
346
+ key: option.value,
347
+ "data-index": index,
348
+ id: `${listId}-${index}`,
349
+ role: "option",
350
+ "aria-selected": option.value === value,
351
+ className: `wb-dd-option${option.value === value ? " wb-dd-selected" : ""}${index === active ? " wb-dd-active" : ""}`,
352
+ onPointerEnter: () => setActive(index),
353
+ onClick: () => choose(index),
354
+ },
355
+ h("span", { className: "wb-dd-option-label" }, option.label),
356
+ option.value === value
357
+ ? h("svg", { className: "wb-dd-check", width: 16, height: 16, viewBox: "0 0 16 16", fill: "none", "aria-hidden": "true", focusable: "false" },
358
+ h("path", { d: "M3.5 8.5L6.5 11.5L12.5 4.5", stroke: "currentColor", strokeWidth: 1.6, strokeLinecap: "round", strokeLinejoin: "round" }))
359
+ : null))) : null);
360
+ }
361
+
220
362
  /** One row of the model list: the toggle, the name, the id, and its badges. */
221
363
  function modelRow(m, rowOptions) {
222
364
  const { busy, setModelEnabled } = rowOptions
@@ -236,6 +378,11 @@ window.__ModuleLoader__.load({
236
378
  h("span", { className: "wb-model-name", title: m.name }, m.name),
237
379
  h("span", { className: "wb-model-id", title: m.id }, m.id),
238
380
  m.free ? h("span", { className: "wb-badge wb-free" }, L.freeTag) : null,
381
+ // The upstream's own labels (限时免费 / 夜间折扣 / any future 订阅优先)
382
+ // are rendered verbatim. That is the whole point: the plugin shows what
383
+ // the upstream declares rather than guessing at a tier — the same rule
384
+ // the reasoning levels follow.
385
+ ...(Array.isArray(m.badges) ? m.badges.map((b) => h("span", { key: "b-" + b, className: "wb-badge wb-upstream" }, b)) : []),
239
386
  m.rate ? h("span", { className: "wb-badge" }, `${L.rateTag} ${m.rate}`) : null,
240
387
  m.rateUnknown ? h("span", { className: "wb-badge" }, "—") : null,
241
388
  m.contextWindow ? h("span", { className: "wb-badge" }, `${L.ctxTag} ${ctxText(m.contextWindow)}`) : null)
@@ -362,33 +509,107 @@ window.__ModuleLoader__.load({
362
509
  // page: the server owns the catalog and computes the rest.
363
510
  const setModelEnabled = (model, enabled) => post(MODELS_PATH, { action: "set-model", provider, model, enabled }, status?.modelsKey)
364
511
  const setAllEnabled = (enabled) => post(MODELS_PATH, { action: "set-all", provider, enabled }, status?.modelsKey)
512
+ // Guarded: an older host does not send this field at all, and the card must
513
+ // keep working against one. Declared before the handlers below, which read it.
514
+ const accounts = Array.isArray(variant?.accounts) ? variant.accounts : []
515
+ /** Make a stored account active. The server refreshes catalog and credits. */
516
+ const switchAccount = (hash) => post(ACCOUNTS_PATH, { action: "activate", provider, hash }, status?.accountsKey)
517
+ /** Forget one account. Removing the active one promotes another server-side. */
518
+ const removeAccount = (hash) => post(ACCOUNTS_PATH, { action: "remove", provider, hash }, status?.accountsKey)
519
+ /** Delete the active account; server promotes another if one is left. */
520
+ const removeCurrent = () => {
521
+ const current = accounts.find((a) => a.active) ?? accounts[0]
522
+ return current ? removeAccount(current.hash) : Promise.resolve(false)
523
+ }
524
+ /** Clear every account of this edition (never the other realm). */
525
+ const clearAccounts = () => post(ACCOUNTS_PATH, { action: "clear", provider }, status?.accountsKey)
365
526
  const credits = variant?.credits
366
527
  const creditAccounts = Array.isArray(credits?.accounts) ? credits.accounts : []
367
528
  const creditTotal = credits?.totalSize ?? creditAccounts.reduce((sum, a) => sum + (Number(a.size) || 0), 0)
529
+ const cache = variant?.cache
368
530
 
369
531
  return h(React.Fragment, null,
370
532
  h("div", null,
371
533
  h("div", { className: "wb-row" },
372
534
  h("span", { className: "wb-label" }, auth?.state === "signed-in" ? L.signedIn : L.signedOut),
373
- h("span", { className: `wb-badge${auth?.state === "signed-in" ? " wb-good" : ""}` },
374
- auth?.state === "signed-in" ? (auth.nickname ?? variant?.appName) : L.signedOut),
375
535
  auth?.state === "signed-in"
376
- ? h(React.Fragment, null,
377
- h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void post(AUTH_PATH, { action: "logout", provider }, status.authKey) }, L.logout),
378
- // The desktop app re-signs in behind the plugin's back and
379
- // rotates its own session, so adopting that session again has
380
- // to stay reachable while signed in — otherwise a rotated
381
- // credential can only be replaced by signing out first.
382
- variant?.desktopAvailable === true
383
- ? h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void importDesktop() }, L.importDesktop)
384
- : null)
385
- : h(React.Fragment, null,
386
- h("button", { type: "button", className: "wb-button wb-primary", disabled: busy, onClick: () => void beginLogin() }, L.signIn),
387
- variant?.desktopAvailable === true
388
- ? h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void importDesktop() }, L.importDesktop)
389
- : null)),
536
+ ? h("span", { className: "wb-badge wb-good" }, auth.nickname ?? variant?.appName)
537
+ : null,
538
+ h("div", { className: "wb-row-actions" },
539
+ auth?.state === "signed-in"
540
+ ? h(React.Fragment, null,
541
+ h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void post(AUTH_PATH, { action: "logout", provider }, status.authKey) }, L.logout),
542
+ // The desktop app can rotate its session behind the plugin's
543
+ // back, so this stays reachable while signed in.
544
+ variant?.desktopAvailable === true
545
+ ? h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void importDesktop() }, L.importDesktop)
546
+ : null)
547
+ : h(React.Fragment, null,
548
+ h("button", { type: "button", className: "wb-button wb-primary", disabled: busy, onClick: () => void beginLogin() }, L.signIn),
549
+ variant?.desktopAvailable === true
550
+ ? h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void importDesktop() }, L.importDesktop)
551
+ : null))),
390
552
  auth?.state === "signed-in" ? h("div", { className: "wb-note", style: { marginTop: 4 } },
391
553
  [auth.domain ? `${L.domain}: ${auth.domain}` : null, auth.expiresAt ? ` · ${L.expires}: ${timeText(auth.expiresAt)}` : null].filter(Boolean).join("")) : null,
554
+ // The account area.
555
+ //
556
+ // Shaped after the DSH settings rows the usage dashboard uses: a title,
557
+ // a description, and one control — because that is where this card
558
+ // lives and a row that does not match its neighbours reads as an
559
+ // embedded widget rather than part of the page.
560
+ //
561
+ // The switcher is a select, not a list of buttons: with two accounts a
562
+ // list is noisy, and with five it is unusable. "Add account" is always
563
+ // available, including while signed in — that is the only way a second
564
+ // account can ever get in here, and hiding it while signed in was the
565
+ // reason there was no way to add one at all.
566
+ // Account toolbar, in the same shape Qoder uses for its PATs: a
567
+ // labelled dropdown naming the active account, then add / delete
568
+ // current / clear all. The token is an account credential here rather
569
+ // than a PAT, but the management operations are the same four.
570
+ // Both editions render this identical block — only the realm's account
571
+ // list behind it differs.
572
+ h("div", { className: "wb-account-block" },
573
+ h("div", { className: "wb-row wb-row-nowrap" },
574
+ h("span", { className: "wb-label wb-account-label" },
575
+ h("span", { className: "wb-dot wb-dot-on", "aria-hidden": "true" }),
576
+ L.accounts),
577
+ accounts.length > 0
578
+ ? h(Dropdown, {
579
+ label: L.accounts,
580
+ value: (accounts.find((a) => a.active) ?? accounts[0]).hash,
581
+ disabled: busy,
582
+ options: accounts.map((account) => ({
583
+ value: account.hash,
584
+ label: `${account.nickname ?? account.uidShort}${account.expired ? ` · ${L.accountExpired}` : ""}`,
585
+ })),
586
+ onChange: (hash) => void switchAccount(hash),
587
+ })
588
+ : h("span", { className: "wb-config-value" }, "—"),
589
+ h("div", { className: "wb-row-actions" },
590
+ h("button", {
591
+ type: "button",
592
+ className: "wb-button",
593
+ disabled: busy,
594
+ onClick: () => void beginLogin(),
595
+ }, L.addAccount),
596
+ accounts.length > 0
597
+ ? h("button", {
598
+ type: "button",
599
+ className: "wb-button",
600
+ disabled: busy,
601
+ onClick: () => void removeCurrent(),
602
+ }, L.removeCurrent)
603
+ : null,
604
+ accounts.length > 0
605
+ ? h("button", {
606
+ type: "button",
607
+ className: "wb-button",
608
+ disabled: busy,
609
+ onClick: () => void clearAccounts(),
610
+ }, L.clearAll)
611
+ : null)),
612
+ h("div", { className: "wb-note", style: { margin: "4px 0 0" } }, L.addAccountHint)),
392
613
  auth?.accountRestricted ? h("div", { className: "wb-error", style: { marginTop: 4 } },
393
614
  L.accountRestricted,
394
615
  h("div", { className: "wb-note", style: { marginTop: 2 } }, String(auth.accountRestricted))) : null,
@@ -401,10 +622,10 @@ window.__ModuleLoader__.load({
401
622
  variant?.auth?.state === "signed-in" ? h("div", null,
402
623
  h("div", { className: "wb-row" },
403
624
  h("span", { className: "wb-label" }, L.catalog),
404
- h("span", { className: `wb-badge${catalog.source === "live" ? " wb-good" : ""}` },
405
- catalog.source === "live" ? L.catalogLive : catalog.source === "saved" ? L.catalogSaved : L.catalogFallback,
406
- catalog.fetchedAt ? ` · ${L.catalogUpdated} ${timeText(catalog.fetchedAt)}` : ""),
407
- h("button", { type: "button", className: "wb-button", disabled: busy || loading, onClick: () => void post(MODELS_PATH, { action: "refresh", provider }, status.modelsKey) }, loading ? L.refreshing : L.refresh)),
625
+ h("div", { className: "wb-row-actions" },
626
+ // The source/timestamp badge is deliberately gone: it duplicated
627
+ // information and took the whole row hostage. Only the action stays.
628
+ h("button", { type: "button", className: "wb-button", disabled: busy || loading, onClick: () => void post(MODELS_PATH, { action: "refresh", provider }, status.modelsKey) }, loading ? L.refreshing : L.refresh))),
408
629
  catalog.error ? h("div", { className: "wb-error", style: { marginTop: 4 } }, L.catalogError + catalog.error) : null,
409
630
  h("div", { className: "wb-row", style: { marginTop: 6 } },
410
631
  h("label", { className: "wb-check" },
@@ -420,6 +641,19 @@ window.__ModuleLoader__.load({
420
641
  h("span", { className: "wb-label" }, L.models),
421
642
  h("input", { className: "wb-input", style: { maxWidth: 180, marginLeft: "auto" }, placeholder: L.search, value: query, onChange: (e) => setQuery(e.target.value) })),
422
643
  h("div", { className: "wb-note", style: { margin: "4px 0 6px" } }, L.modelsHint),
644
+ // A count, not a badge on every row: nearly every model costs credits,
645
+ // and a tag repeated 22 times carries no information. The free/free
646
+ // distinction is the actionable one, so it is stated once.
647
+ h("div", { className: "wb-note", style: { margin: "0 0 6px" } },
648
+ `${shown.length} ${L.modelCount} · ${L.freeTag} ${shown.filter((m) => m.free).length} · ${L.paidTag} ${shown.filter((m) => m.paid).length}`),
649
+ // The hit rate is what decides whether a long conversation is cheap or
650
+ // expensive, and until now it could only be inferred from a bill. The
651
+ // count of turns is part of the answer: 0 turns is "not measured yet",
652
+ // which must never be rendered as "0%".
653
+ h("div", { className: "wb-note", style: { margin: "0 0 6px" } },
654
+ cache?.turns > 0
655
+ ? `${L.cacheHit} ${(cache.rate * 100).toFixed(1)}% (${L.cacheLast} ${(cache.lastRate * 100).toFixed(1)}% · ${cache.turns} ${L.cacheTurns})`
656
+ : `${L.cacheHit} — (${L.cacheIdle})`),
423
657
  h("div", { className: "wb-models" },
424
658
  shown.length === 0
425
659
  ? h("div", { className: "wb-note" }, "—")
@@ -543,147 +777,7 @@ window.__ModuleLoader__.load({
543
777
  /** Names an existing profile may still declare from before the rename. */
544
778
  const LEGACY_PACKAGE_NAMES = ["dsh-workbuddy-connect"];
545
779
 
546
- /**
547
- * The per-process control key for the update route.
548
- *
549
- * Read from the status document, the same place `authKey` and `modelsKey`
550
- * come from, and cached for the page's lifetime: it is minted once per host
551
- * process, and a failed read is retried rather than remembered as "no key"
552
- * (which would render as a permanent 403).
553
- */
554
- let updateKeyPromise;
555
- function updateKeyOf() {
556
- updateKeyPromise ??= fetch(STATUS_PATH)
557
- .then((res) => (res.ok ? res.json() : undefined))
558
- .then((doc) => {
559
- const key = doc?.updateKey;
560
- return typeof key === "string" && key !== "" ? key : undefined;
561
- })
562
- .catch(() => {
563
- updateKeyPromise = undefined;
564
- return undefined;
565
- });
566
- return updateKeyPromise;
567
- }
568
-
569
- /**
570
- * The contribution to the plugin page's own detail actions.
571
- *
572
- * DSH offers an "Update" button only for the official on-demand catalog —
573
- * `updateAvailable()` in the plugin page requires an `installTarget`, and
574
- * the manager derives that from `OFFICIAL_ON_DEMAND_CATALOG` alone, so a
575
- * community bundle installed from `github:…` never gets one however far
576
- * behind it is. The page does declare `plugins.detail.actions` for exactly
577
- * this situation, so this card supplies the missing button for its own
578
- * package and nothing else.
579
- *
580
- * Installing stays the manager's job: `ctx.remote.pluginManager` owns the
581
- * profile lock, the pnpm run and the reload lifecycle, so this never writes
582
- * to the profile itself.
583
- */
584
- function UpdateActions({ subject, L, manager }) {
585
- const pkg = subject?.kind === "bundle" ? subject.pkg : undefined
586
- const mine = (pkg?.name === PACKAGE_NAME || LEGACY_PACKAGE_NAMES.includes(pkg?.name)) && pkg?.installed === true;
587
- const [report, setReport] = React.useState(null);
588
- const [busy, setBusy] = React.useState(false);
589
- const [message, setMessage] = React.useState(null);
590
- const alive = React.useRef(true);
591
- React.useEffect(() => () => { alive.current = false; }, []);
592
-
593
- const check = React.useCallback(async (force) => {
594
- setBusy(true);
595
- setMessage(null);
596
- try {
597
- // The route is guarded like every other card route, and the key
598
- // arrives with the status document the card already fetches — so it
599
- // is read here rather than assumed absent (this component does not
600
- // receive the settings card's `status` prop).
601
- const key = await updateKeyOf();
602
- const res = await fetch(`${UPDATE_PATH}${force ? "?refresh=1" : ""}`, {
603
- headers: key === undefined ? {} : { "x-dsh-workbuddy-connect-key": key },
604
- });
605
- if (!res.ok) throw new Error(String(res.status));
606
- const doc = await res.json();
607
- if (alive.current) setReport(doc);
608
- } catch (error) {
609
- if (alive.current) setReport({ state: "unknown", reason: String(error?.message ?? error) });
610
- } finally {
611
- if (alive.current) setBusy(false);
612
- }
613
- }, []);
614
-
615
- // Only the package's own page pays for a network round trip, and only
616
- // once: the host caches the answer for six hours anyway.
617
- React.useEffect(() => {
618
- if (mine && report === null && !busy) void check(false);
619
- }, [mine, report, busy, check]);
620
-
621
- const apply = React.useCallback(async () => {
622
- if (report?.targetSpec === undefined) return;
623
- setBusy(true);
624
- setMessage(null);
625
- try {
626
- await reinstallThroughManager(manager, report.targetSpec);
627
- if (alive.current) setMessage(L.updateDone);
628
- } catch (error) {
629
- if (alive.current) setMessage(String(error?.message ?? error));
630
- } finally {
631
- if (alive.current) setBusy(false);
632
- }
633
- }, [report, manager, L]);
634
-
635
- // Nothing to say on another package's page.
636
- if (!mine) return null;
637
-
638
- const state = report?.state;
639
- // The page's own Update control is `Button variant="outline" size="sm"`
640
- // with the refresh glyph; an available version is offered as `primary`.
641
- // Matching both keeps this action reading as part of the page.
642
- const behind = state === "behind";
643
- return h("span", { className: "wb-update-action" },
644
- h(Button, {
645
- variant: behind ? "primary" : "outline",
646
- size: "sm",
647
- icon: h(IconRefreshOutlineRegular, { size: 13 }),
648
- disabled: busy,
649
- title: behind ? (report.targetSpec ?? undefined) : undefined,
650
- "aria-label": behind ? L.updateApply : L.updateCheck,
651
- onClick: () => void (behind ? apply() : check(true)),
652
- }, busy ? (behind ? L.updateRunning : L.updateChecking) : (behind ? L.updateApply : L.updateCheck)),
653
- // The badge carries the same meaning the page's own "Update available"
654
- // tag does, so it is rendered as text beside the action rather than as
655
- // a second control.
656
- behind ? h("span", { className: "wb-update-note wb-update-note-info" }, L.updateAvailable) : null,
657
- state === "current" ? h("span", { className: "wb-update-note" }, L.updateCurrent) : null,
658
- message !== null ? h("span", { className: "wb-update-note" }, message) : null,
659
- state === "local-copy" ? h("span", { className: "wb-update-note" }, L.updateLocalCopy) : null,
660
- state === "unknown" ? h("span", { className: "wb-update-note" }, `${L.updateUnknown}${report.reason ?? ""}`) : null,
661
- );
662
- }
663
-
664
- /**
665
- * Reinstall this package at `spec` through the plugin manager.
666
- *
667
- * `installBundle` refuses a package that is already present
668
- * (`already-installed`), so an update is a removal followed by an install
669
- * pinned to the commit the check resolved — the same pair the page's own
670
- * official Update button performs, on the same remote service. Doing it
671
- * here rather than in the host half is deliberate: the manager owns the
672
- * profile lock, the pnpm run and the reload lifecycle, and reaching it over
673
- * the remote keeps that ownership in one place.
674
- */
675
- async function reinstallThroughManager(manager, spec) {
676
- if (manager === undefined) throw new Error("the plugin manager service is unavailable");
677
- const removed = await manager.removeBundle(PACKAGE_NAME);
678
- if (removed?.ok !== true) throw new Error(removed?.error?.message ?? "the manager refused to remove the package");
679
- const installed = await manager.installBundle(spec, {});
680
- if (installed?.ok !== true) throw new Error(installed?.error?.message ?? "the manager refused to install the package");
681
- }
682
-
683
- // `remote.pluginManager` is the service the plugin page itself injects; a
684
- // card that wants the page's own Update behaviour has to ask for the same
685
- // namespace rather than reaching for a global.
686
- const inject = ["slots", "remote.pluginManager"]
780
+ const inject = ["slots"]
687
781
 
688
782
  function apply(ctx) {
689
783
  try {
@@ -742,23 +836,6 @@ window.__ModuleLoader__.load({
742
836
  note("section-inject", error)
743
837
  }
744
838
  })
745
- // The plugin page's per-package action row. Registered separately and
746
- // defensively: a host without this slot (an older page, or a surface
747
- // that never opens the page) must still get the settings card above.
748
- try {
749
- const manager = ctx.get("remote.pluginManager")
750
- const disposeActions = ctx.slots.inject("plugins.detail.actions", () => ctx.slots.register({
751
- name: "plugins.detail.actions",
752
- id: `${PACKAGE_NAME}-update`,
753
- order: 10,
754
- }, (props) => h(UpdateActions, { ...props, L, manager })))
755
- ctx.effect(() => () => {
756
- disposeActions?.()
757
- }, "dsh-workbuddy-connect: plugin page actions")
758
- } catch (error) {
759
- console.error("[dsh-workbuddy-connect] could not register the plugin page actions:", error)
760
- note("detail-actions", error)
761
- }
762
839
  } catch (error) {
763
840
  console.error("[dsh-workbuddy-connect] could not register the settings card:", error)
764
841
  note("apply", error)