@sixzjd/dsh-workbuddy-connect 0.0.0-stage → 0.3.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,770 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@sixzjd/dsh-workbuddy-connect",
3
+ factory: (require) => {
4
+ const React = require("react");
5
+ const h = React.createElement;
6
+ // The plugin page's own primitives, so a contributed action is the same
7
+ // component, size and icon as the page's built-in Update button rather than
8
+ // a lookalike that drifts when the page's design changes.
9
+ const {
10
+ Button,
11
+ IconRefreshOutlineRegular,
12
+ } = require("@deepseek-ai/dsh-client-ui-primitives");
13
+ window.__WB_ERR__ = window.__WB_ERR__ || [];
14
+ const note = (where, error) => {
15
+ try {
16
+ window.__WB_ERR__.push(where + ": " + String((error && error.stack) || error));
17
+ } catch {}
18
+ };
19
+
20
+ /** Host routes (literal here and in the host half: the two bundles build independently). */
21
+ const BASE = "/plugins/dsh-workbuddy-connect";
22
+ const STATUS_PATH = `${BASE}/status`;
23
+ const LOGIN_PATH = `${BASE}/login`;
24
+ const MODELS_PATH = `${BASE}/models`;
25
+ const AUTH_PATH = `${BASE}/auth`;
26
+ const UPDATE_PATH = `${BASE}/update`;
27
+
28
+ const zh = {
29
+ title: "WorkBuddy",
30
+ subtitle: "接入 WorkBuddy 模型(国际版 / 国内版)。",
31
+ signIn: "登录 WorkBuddy",
32
+ importDesktop: "从桌面 App 导入",
33
+ signInHint: "点击后在新标签页打开 WorkBuddy 授权页,完成登录后回到这里。",
34
+ waiting: "等待授权中…",
35
+ openLogin: "打开授权页面",
36
+ signedIn: "已登录",
37
+ signedOut: "未登录",
38
+ logout: "退出登录",
39
+ nickname: "账号",
40
+ expires: "凭据有效期",
41
+ domain: "域",
42
+ catalog: "模型目录",
43
+ catalogLive: "实时列表",
44
+ catalogSaved: "上次保存的列表",
45
+ catalogFallback: "内置列表",
46
+ catalogUpdated: "更新于",
47
+ catalogError: "最近刷新失败:",
48
+ refresh: "刷新目录",
49
+ refreshing: "刷新中…",
50
+ models: "模型开关",
51
+ modelsHint: "关闭的模型从 DSH 模型选择器中隐藏。",
52
+ search: "搜索模型 / ID",
53
+ enableAll: "全部开启",
54
+ disableAll: "全部关闭",
55
+ freeTag: "免费",
56
+ rateTag: "倍率",
57
+ ctxTag: "上下文",
58
+ imgTag: "图片",
59
+ effortTag: "推理",
60
+ maxWindow: "使用上游声明的最大上下文窗口",
61
+ maxWindowHint: "关闭时按上游的默认窗口发送请求(如 300K),开启时按最大窗口(如 1M)。",
62
+ credits: "额度",
63
+ creditsNone: "暂无额度信息",
64
+ creditsRemain: "剩余",
65
+ creditsTotal: "总量",
66
+ creditsUnlimited: "不限",
67
+ creditsEnd: "到期",
68
+ creditsError: "额度读取失败:",
69
+ identity: "客户端身份",
70
+ errorLoad: "无法读取连接器状态",
71
+ retry: "重试",
72
+ failed: "操作失败",
73
+ signedOutHint: "登录后才会出现模型分组。",
74
+ sessionStale: "上游拒绝了这份凭据:桌面 App 换过会话了。点「从桌面 App 导入」重新接入,或重新登录。",
75
+ updateTitle: "插件更新",
76
+ updateCheck: "检查更新",
77
+ updateChecking: "检查中…",
78
+ updateAvailable: "有新版本",
79
+ updateCurrent: "已是最新",
80
+ updateApply: "更新到此版本",
81
+ updateRunning: "正在更新…",
82
+ updateLocalCopy: "这个安装来自本地目录,没有可比较的远程仓库。",
83
+ updateUnknown: "暂时查不到远程状态:",
84
+ updateHint: "git 版本可以在这里一键检查并更新到上游最新提交;DSH 自己只给官方插件显示「更新」。",
85
+ updateDone: "已更新,重启 App 后生效。",
86
+ accountRestricted: "上游已限制这个账号(不是凭据问题,重新登录或重新导入都无效)。只有申诉才能解除:在 WorkBuddy 里提交反馈。",
87
+ tabGlobal: "国际版",
88
+ tabCN: "国内版",
89
+ };
90
+ const en = {
91
+ title: "WorkBuddy",
92
+ subtitle: "WorkBuddy models (Global / CN) in DSH.",
93
+ signIn: "Sign in to WorkBuddy",
94
+ importDesktop: "Import from the desktop app",
95
+ signInHint: "Opens the WorkBuddy authorization page in a new tab; come back here when it is done.",
96
+ waiting: "waiting for authorization…",
97
+ openLogin: "Open the authorization page",
98
+ signedIn: "Signed in",
99
+ signedOut: "Signed out",
100
+ logout: "Sign out",
101
+ nickname: "Account",
102
+ expires: "Credential expires",
103
+ domain: "Domain",
104
+ catalog: "Model catalog",
105
+ catalogLive: "live list",
106
+ catalogSaved: "saved list",
107
+ catalogFallback: "built-in list",
108
+ catalogUpdated: "updated",
109
+ catalogError: "last refresh failed: ",
110
+ refresh: "Refresh catalog",
111
+ refreshing: "Refreshing…",
112
+ models: "Model toggles",
113
+ modelsHint: "Disabled models are hidden from DSH's model picker.",
114
+ search: "search models / id",
115
+ enableAll: "Enable all",
116
+ disableAll: "Disable all",
117
+ freeTag: "free",
118
+ rateTag: "rate",
119
+ ctxTag: "ctx",
120
+ imgTag: "image",
121
+ effortTag: "reasoning",
122
+ maxWindow: "Use the upstream's maximum context window",
123
+ maxWindowHint: "Off sends the upstream's default window (e.g. 300K); on sends the largest one (e.g. 1M).",
124
+ credits: "Quota",
125
+ creditsNone: "No quota information yet",
126
+ creditsRemain: "remaining",
127
+ creditsTotal: "total",
128
+ creditsUnlimited: "unlimited",
129
+ creditsEnd: "expires",
130
+ creditsError: "Could not read the quota: ",
131
+ identity: "client identity",
132
+ errorLoad: "Cannot read connector status",
133
+ retry: "Retry",
134
+ failed: "Action failed",
135
+ signedOutHint: "The model group appears after you sign in.",
136
+ 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
+ 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
+ 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
+ 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
+ tabGlobal: "Global",
150
+ tabCN: "China",
151
+ };
152
+ const L = typeof navigator !== "undefined" && /^zh/i.test(navigator.language || "") ? zh : en;
153
+
154
+ const css = `
155
+ .wb-card{border:.5px solid var(--dsw-alias-border-l2,#dedee3);border-radius:var(--dsw-radius-panel,12px);background:var(--dsw-alias-bg-layer-1,#fff);overflow:hidden}
156
+ .wb-head{display:flex;align-items:center;gap:10px;width:100%;padding:14px 16px;border:0;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
157
+ .wb-head:hover{background:var(--dsw-alias-interactive-bg-hover,#f1f1f3)}
158
+ .wb-title{font-size:14px;font-weight:600}
159
+ .wb-sub{color:var(--dsw-alias-label-secondary,#74747c);font-size:12px;margin-top:2px}
160
+ .wb-chev{margin-left:auto;color:var(--dsw-alias-label-tertiary,#9a9aa3);transition:transform .15s}
161
+ .wb-chev.wb-open{transform:rotate(90deg)}
162
+ .wb-tabs{display:flex;gap:4px;padding:3px;border-radius:var(--dsw-radius-md,8px);background:var(--dsw-alias-bg-layer-2,#f1f1f3);width:fit-content}
163
+ .wb-tab{display:flex;align-items:center;gap:6px;height:28px;padding:0 12px;border:0;border-radius:6px;background:transparent;color:var(--dsw-alias-label-secondary,#74747c);font:inherit;font-size:13px;cursor:pointer}
164
+ .wb-tab:hover{color:var(--dsw-alias-label-primary,#25252a)}
165
+ .wb-tab[aria-selected="true"]{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary,#25252a);box-shadow:0 .5px 2px rgba(0,0,0,.08)}
166
+ .wb-dot{width:7px;height:7px;border-radius:99px;background:var(--dsw-alias-label-tertiary,#9a9aa3);flex:none}
167
+ .wb-dot.wb-dot-on{background:var(--dsw-alias-state-success-primary,#2f9e44)}
168
+ .wb-dot.wb-dot-load{background:var(--dsw-alias-state-warning-primary,#d98416)}
169
+ .wb-body{padding:2px 16px 16px;display:flex;flex-direction:column;gap:14px}
170
+ .wb-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
171
+ .wb-label{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary,#74747c)}
172
+ .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
+ .wb-badge.wb-good{color:var(--dsw-alias-state-business-primary,#4176e6);border-color:currentColor}
174
+ .wb-badge.wb-free{color:var(--dsw-alias-state-success-primary,#2f9e44);border-color:currentColor}
175
+ .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
+ .wb-input{flex:1;min-width:160px}
177
+ .wb-update-action{display:inline-flex;align-items:center;gap:8px;min-width:0}
178
+ .wb-update-note{color:var(--dsw-alias-label-tertiary,#9a9aa3);font-size:12.5px;line-height:18px;white-space:nowrap}
179
+ .wb-update-note-info{color:var(--dsw-alias-state-business-primary,#4176e6)}
180
+ @media (max-width:720px){.wb-update-note{display:none}}
181
+ .wb-button{cursor:pointer;white-space:nowrap}
182
+ .wb-button:hover{background:var(--dsw-alias-interactive-bg-hover,#f1f1f3)}
183
+ .wb-button:disabled{opacity:.5;cursor:default}
184
+ .wb-button.wb-primary{background:var(--dsw-alias-state-business-primary,#4176e6);border-color:transparent;color:#fff}
185
+ .wb-button.wb-primary:hover{filter:brightness(1.05)}
186
+ .wb-note{font-size:11px;color:var(--dsw-alias-label-tertiary,#9a9aa3);line-height:1.5}
187
+ .wb-error{font-size:12px;color:var(--dsw-alias-state-error-primary,#bd4747)}
188
+ .wb-models{display:flex;flex-direction:column;gap:2px;max-height:280px;overflow:auto;border:.5px solid var(--dsw-alias-border-l2,#dedee3);border-radius:var(--dsw-radius-md,8px);padding:6px}
189
+ .wb-model{display:flex;align-items:center;gap:8px;padding:5px 8px;border-radius:6px;font-size:13px;flex-wrap:nowrap;min-width:0}
190
+ .wb-model:hover{background:var(--dsw-alias-interactive-bg-hover,#f1f1f3)}
191
+ .wb-model input{accent-color:var(--dsw-alias-state-business-primary,#4176e6);flex:none}
192
+ .wb-model-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
193
+ .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
+ .wb-model .wb-badge{flex:none}
195
+ .wb-quota{display:flex;flex-direction:column;gap:6px}
196
+ .wb-quota-row{display:flex;align-items:center;gap:8px;font-size:12px}
197
+ .wb-bar{flex:1;height:6px;border-radius:99px;background:var(--dsw-alias-border-l2,#dedee3);overflow:hidden}
198
+ .wb-bar span{display:block;height:100%;background:var(--dsw-alias-state-business-primary,#4176e6)}
199
+ .wb-check{display:flex;align-items:center;gap:8px;font-size:12px;color:var(--dsw-alias-label-secondary,#74747c);cursor:pointer}
200
+ .wb-check input{accent-color:var(--dsw-alias-state-business-primary,#4176e6)}
201
+ .wb-link{color:var(--dsw-alias-state-business-primary,#4176e6);text-decoration:none;cursor:pointer}
202
+ @media(prefers-reduced-motion:reduce){.wb-chev{transition:none}}
203
+ `;
204
+
205
+ const timeText = (ms) => {
206
+ if (typeof ms !== "number" || !Number.isFinite(ms) || ms <= 0) return ""
207
+ const d = new Date(ms)
208
+ return `${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
209
+ }
210
+
211
+ /** 200,000 tokens reads as 200K, 1,048,576 as 1M — never 195K or 1024K. */
212
+ const ctxText = (n) => {
213
+ if (!Number.isFinite(n) || n <= 0) return ""
214
+ if (n >= 1e6) return `${Math.round(n / 1e5) / 10}M`
215
+ return `${Math.round(n / 1e3)}K`
216
+ }
217
+
218
+ const isStatus = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.status === "ok"
219
+
220
+ /** One row of the model list: the toggle, the name, the id, and its badges. */
221
+ function modelRow(m, rowOptions) {
222
+ const { busy, setModelEnabled } = rowOptions
223
+ return h("label", { key: m.id, className: "wb-model" },
224
+ h("input", {
225
+ type: "checkbox",
226
+ checked: m.enabled !== false,
227
+ disabled: busy,
228
+ onChange: (e) => {
229
+ // The toggle names ONE model and its new state; it never sends a
230
+ // list derived from a snapshot of the page. A snapshot is stale
231
+ // the moment the catalog refreshes, and a complement computed from
232
+ // a stale one can disable every model but the one clicked.
233
+ void setModelEnabled(m.id, e.target.checked)
234
+ },
235
+ }),
236
+ h("span", { className: "wb-model-name", title: m.name }, m.name),
237
+ h("span", { className: "wb-model-id", title: m.id }, m.id),
238
+ m.free ? h("span", { className: "wb-badge wb-free" }, L.freeTag) : null,
239
+ m.rate ? h("span", { className: "wb-badge" }, `${L.rateTag} ${m.rate}`) : null,
240
+ m.rateUnknown ? h("span", { className: "wb-badge" }, "—") : null,
241
+ m.contextWindow ? h("span", { className: "wb-badge" }, `${L.ctxTag} ${ctxText(m.contextWindow)}`) : null)
242
+ }
243
+
244
+ /**
245
+ * One variant's section: sign-in, catalog, model toggles, quota.
246
+ *
247
+ * The status document carries both variants and belongs to the card
248
+ * shell, so switching tabs never refetches and never loses the other
249
+ * variant's data.
250
+ */
251
+ function VariantSection(props) {
252
+ const { provider, status, load, loading } = props
253
+ const [busy, setBusy] = React.useState(false)
254
+ const [notice, setNotice] = React.useState(null)
255
+ const [query, setQuery] = React.useState("")
256
+ const [login, setLogin] = React.useState(null)
257
+ const mounted = React.useRef(true)
258
+ React.useEffect(() => {
259
+ mounted.current = true
260
+ return () => { mounted.current = false }
261
+ }, [])
262
+
263
+ const variant = status?.variants?.[provider]
264
+
265
+ const post = React.useCallback(async (path, body, key) => {
266
+ setBusy(true)
267
+ setNotice(null)
268
+ try {
269
+ const res = await fetch(path, {
270
+ method: "POST",
271
+ headers: { "content-type": "application/json", "x-dsh-workbuddy-connect-key": key ?? "" },
272
+ body: JSON.stringify(body),
273
+ })
274
+ if (!res.ok) throw new Error(String(res.status))
275
+ await load()
276
+ return true
277
+ } catch {
278
+ setNotice(L.failed)
279
+ return false
280
+ } finally {
281
+ setBusy(false)
282
+ }
283
+ }, [load])
284
+
285
+ /** Begin the device-authorization flow and start polling for its outcome. */
286
+ const beginLogin = React.useCallback(async () => {
287
+ setBusy(true)
288
+ setNotice(null)
289
+ try {
290
+ const res = await fetch(LOGIN_PATH, {
291
+ method: "POST",
292
+ headers: { "content-type": "application/json", "x-dsh-workbuddy-connect-key": status?.loginKey ?? "" },
293
+ body: JSON.stringify({ action: "begin", provider }),
294
+ })
295
+ if (!res.ok) throw new Error(String(res.status))
296
+ const doc = await res.json()
297
+ if (!mounted.current) return
298
+ if (doc?.status === "pending" && doc.authUrl) setLogin({ url: doc.authUrl, state: doc.state })
299
+ else setNotice(doc?.error ?? L.failed)
300
+ } catch {
301
+ if (mounted.current) setNotice(L.failed)
302
+ } finally {
303
+ if (mounted.current) setBusy(false)
304
+ }
305
+ }, [provider, status])
306
+
307
+ /** Adopt the session the WorkBuddy desktop app is already signed in to. */
308
+ const importDesktop = React.useCallback(async () => {
309
+ setBusy(true)
310
+ setNotice(null)
311
+ try {
312
+ const res = await fetch(AUTH_PATH, {
313
+ method: "POST",
314
+ headers: { "content-type": "application/json", "x-dsh-workbuddy-connect-key": status?.authKey ?? "" },
315
+ body: JSON.stringify({ action: "import-desktop", provider }),
316
+ })
317
+ if (!res.ok) throw new Error(String(res.status))
318
+ const doc = await res.json()
319
+ if (!mounted.current) return
320
+ if (doc?.ok === true) await load()
321
+ else setNotice(doc?.error ?? L.failed)
322
+ } catch {
323
+ if (mounted.current) setNotice(L.failed)
324
+ } finally {
325
+ if (mounted.current) setBusy(false)
326
+ }
327
+ }, [provider, status, load])
328
+
329
+ /** Poll the pending attempt until the human finishes in the browser. */
330
+ React.useEffect(() => {
331
+ if (!login) return undefined
332
+ let cancelled = false
333
+ const timer = setInterval(async () => {
334
+ try {
335
+ const res = await fetch(LOGIN_PATH, {
336
+ method: "POST",
337
+ headers: { "content-type": "application/json", "x-dsh-workbuddy-connect-key": status?.loginKey ?? "" },
338
+ body: JSON.stringify({ action: "poll", provider, state: login.state }),
339
+ })
340
+ if (!res.ok) throw new Error(String(res.status))
341
+ const doc = await res.json()
342
+ if (cancelled || !mounted.current) return
343
+ if (doc?.status === "complete") {
344
+ setLogin(null)
345
+ await load()
346
+ } else if (doc?.status === "error") {
347
+ setLogin(null)
348
+ setNotice(doc.error ?? L.failed)
349
+ }
350
+ } catch {
351
+ // A transient poll failure is not a failed login: keep polling.
352
+ }
353
+ }, 2500)
354
+ return () => { cancelled = true; clearInterval(timer) }
355
+ }, [login, provider, status, load])
356
+
357
+ const auth = variant?.auth
358
+ const catalog = variant?.catalog
359
+ const models = Array.isArray(catalog?.models) ? catalog.models : []
360
+ const shown = query.trim() === "" ? models : models.filter((m) => `${m.name} ${m.id}`.toLowerCase().includes(query.trim().toLowerCase()))
361
+ // Both mutations name what they change, never a list derived from the
362
+ // page: the server owns the catalog and computes the rest.
363
+ const setModelEnabled = (model, enabled) => post(MODELS_PATH, { action: "set-model", provider, model, enabled }, status?.modelsKey)
364
+ const setAllEnabled = (enabled) => post(MODELS_PATH, { action: "set-all", provider, enabled }, status?.modelsKey)
365
+ const credits = variant?.credits
366
+ const creditAccounts = Array.isArray(credits?.accounts) ? credits.accounts : []
367
+ const creditTotal = credits?.totalSize ?? creditAccounts.reduce((sum, a) => sum + (Number(a.size) || 0), 0)
368
+
369
+ return h(React.Fragment, null,
370
+ h("div", null,
371
+ h("div", { className: "wb-row" },
372
+ 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
+ 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)),
390
+ auth?.state === "signed-in" ? h("div", { className: "wb-note", style: { marginTop: 4 } },
391
+ [auth.domain ? `${L.domain}: ${auth.domain}` : null, auth.expiresAt ? ` · ${L.expires}: ${timeText(auth.expiresAt)}` : null].filter(Boolean).join("")) : null,
392
+ auth?.accountRestricted ? h("div", { className: "wb-error", style: { marginTop: 4 } },
393
+ L.accountRestricted,
394
+ h("div", { className: "wb-note", style: { marginTop: 2 } }, String(auth.accountRestricted))) : null,
395
+ auth?.sessionStale === true && !auth?.accountRestricted ? h("div", { className: "wb-error", style: { marginTop: 4 } }, L.sessionStale) : null,
396
+ auth?.state !== "signed-in" ? h("div", { className: "wb-note", style: { marginTop: 4 } }, L.signedOutHint) : null,
397
+ auth?.reason ? h("div", { className: "wb-error", style: { marginTop: 4 } }, auth.reason) : null,
398
+ login ? h("div", { className: "wb-row", style: { marginTop: 8 } },
399
+ h("span", { className: "wb-note" }, L.waiting),
400
+ h("a", { className: "wb-link", href: login.url, target: "_blank", rel: "noreferrer" }, L.openLogin)) : null),
401
+ variant?.auth?.state === "signed-in" ? h("div", null,
402
+ h("div", { className: "wb-row" },
403
+ 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)),
408
+ catalog.error ? h("div", { className: "wb-error", style: { marginTop: 4 } }, L.catalogError + catalog.error) : null,
409
+ h("div", { className: "wb-row", style: { marginTop: 6 } },
410
+ h("label", { className: "wb-check" },
411
+ h("input", {
412
+ type: "checkbox",
413
+ checked: variant?.useMaximumContextWindow === true,
414
+ disabled: busy,
415
+ onChange: (e) => void post(MODELS_PATH, { action: "set-max-window", provider, enabled: e.target.checked }, status.modelsKey),
416
+ }),
417
+ h("span", null, L.maxWindow)),
418
+ h("span", { className: "wb-note" }, L.maxWindowHint)),
419
+ h("div", { className: "wb-row", style: { marginTop: 10 } },
420
+ h("span", { className: "wb-label" }, L.models),
421
+ h("input", { className: "wb-input", style: { maxWidth: 180, marginLeft: "auto" }, placeholder: L.search, value: query, onChange: (e) => setQuery(e.target.value) })),
422
+ h("div", { className: "wb-note", style: { margin: "4px 0 6px" } }, L.modelsHint),
423
+ h("div", { className: "wb-models" },
424
+ shown.length === 0
425
+ ? h("div", { className: "wb-note" }, "—")
426
+ : shown.map((m) => modelRow(m, { busy, setModelEnabled }))),
427
+ h("div", { className: "wb-row", style: { marginTop: 6 } },
428
+ h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void setAllEnabled(true) }, L.enableAll),
429
+ h("button", { type: "button", className: "wb-button", disabled: busy, onClick: () => void setAllEnabled(false) }, L.disableAll))) : null,
430
+ variant?.auth?.state === "signed-in" ? h("div", null,
431
+ h("div", { className: "wb-row" },
432
+ h("span", { className: "wb-label" }, L.credits),
433
+ variant?.creditsError ? h("span", { className: "wb-badge" }, L.creditsError + variant.creditsError) : null),
434
+ credits && creditAccounts.length > 0 ? h("div", { className: "wb-quota", style: { marginTop: 6 } },
435
+ creditAccounts.map((a, i) => {
436
+ const size = Number(a.size) || 0
437
+ const remain = Number(a.remain) || 0
438
+ const pct = size > 0 ? Math.max(0, Math.min(100, Math.round((remain / size) * 100))) : 0
439
+ return h("div", { key: `${a.packageName}-${i}`, className: "wb-quota-row" },
440
+ h("span", { style: { minWidth: 96, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, title: a.packageName }, a.packageName),
441
+ h("span", { className: "wb-bar" }, h("span", { style: { width: `${pct}%` } })),
442
+ h("span", { style: { whiteSpace: "nowrap" } }, `${remain} / ${size}`),
443
+ a.packageEndTime ? h("span", { className: "wb-note" }, `${L.creditsEnd} ${a.packageEndTime}`) : null)
444
+ }),
445
+ creditTotal > 0 ? h("div", { className: "wb-note" }, `${L.creditsTotal}: ${creditTotal}`) : null)
446
+ : credits ? h("div", { className: "wb-note" }, L.creditsNone) : null) : null,
447
+ notice ? h("div", { className: "wb-error" }, notice) : null)
448
+ }
449
+
450
+ /**
451
+ * The one card for both WorkBuddy editions.
452
+ *
453
+ * One panel with a variant tab, the way the Qoder connector does it: the
454
+ * two editions share a card, a header and a status poll, and only the
455
+ * section under the active tab differs.
456
+ */
457
+ function WorkBuddyCard() {
458
+ const [open, setOpen] = React.useState(false)
459
+ const [active, setActive] = React.useState("workbuddy-global")
460
+ const [status, setStatus] = React.useState(null)
461
+ const [loadError, setLoadError] = React.useState(null)
462
+ const [loading, setLoading] = React.useState(false)
463
+ const mounted = React.useRef(true)
464
+ React.useEffect(() => {
465
+ mounted.current = true
466
+ return () => { mounted.current = false }
467
+ }, [])
468
+
469
+ const load = React.useCallback(async () => {
470
+ setLoading(true)
471
+ try {
472
+ const res = await fetch(STATUS_PATH, { headers: { accept: "application/json" } })
473
+ if (!res.ok) throw new Error(String(res.status))
474
+ const doc = await res.json()
475
+ if (!mounted.current) return
476
+ if (isStatus(doc)) { setStatus(doc); setLoadError(null) }
477
+ else setLoadError(L.errorLoad)
478
+ } catch {
479
+ if (mounted.current) setLoadError(L.errorLoad)
480
+ } finally {
481
+ if (mounted.current) setLoading(false)
482
+ }
483
+ }, [])
484
+
485
+ // The status is cheap (it reads the cached catalog and the stored
486
+ // credential — never the upstream), and the collapsed header shows the
487
+ // sign-in state, so it is loaded whether the card is open or not.
488
+ React.useEffect(() => {
489
+ void load()
490
+ const timer = setInterval(() => void load(), 60_000)
491
+ return () => clearInterval(timer)
492
+ }, [load])
493
+
494
+ const variant = status?.variants?.[active]
495
+ /** A tab's dot: green when that edition is signed in, amber while loading. */
496
+ const dotClass = v => (v?.auth?.state === "signed-in" ? "wb-dot wb-dot-on" : status === null ? "wb-dot wb-dot-load" : "wb-dot")
497
+
498
+ return h("div", { className: "wb-card" },
499
+ h("style", null, css),
500
+ h("button", { type: "button", className: "wb-head", onClick: () => setOpen((v) => !v), "aria-expanded": open },
501
+ h("span", null,
502
+ h("span", { className: "wb-title" }, L.title),
503
+ h("div", { className: "wb-sub" }, L.subtitle)),
504
+ variant?.auth?.state === "signed-in"
505
+ ? h("span", { className: "wb-badge wb-good" }, variant.auth.nickname ?? variant.displayName)
506
+ : status
507
+ ? h("span", { className: "wb-badge" }, L.signedOut)
508
+ : null,
509
+ h("span", { className: `wb-chev${open ? " wb-open" : ""}`, "aria-hidden": "true" }, "›")),
510
+ open ? h("div", { className: "wb-body" },
511
+ h("div", { className: "wb-tabs", role: "tablist", "aria-label": L.title },
512
+ h("button", { type: "button", role: "tab", className: "wb-tab", "aria-selected": active === "workbuddy-global", onClick: () => setActive("workbuddy-global") },
513
+ h("span", { className: dotClass(status?.variants?.["workbuddy-global"]), "aria-hidden": "true" }),
514
+ h("span", null, L.tabGlobal)),
515
+ h("button", { type: "button", role: "tab", className: "wb-tab", "aria-selected": active === "workbuddy", onClick: () => setActive("workbuddy") },
516
+ h("span", { className: dotClass(status?.variants?.["workbuddy"]), "aria-hidden": "true" }),
517
+ h("span", null, L.tabCN))),
518
+ loadError && !status ? h("div", { className: "wb-error" }, loadError, " ", h("button", { type: "button", className: "wb-button", onClick: () => void load() }, L.retry)) : null,
519
+ status ? h(VariantSection, { provider: active, status, load, loading }) : h("div", { className: "wb-note" }, loading ? "…" : "—")) : null)
520
+ }
521
+
522
+ /**
523
+ * Join the shared 《插件设置》 block with the same rendezvous protocol the
524
+ * sibling connect plugins use: wait for the host's `settings.section`,
525
+ * attach to the existing container when one is registered, otherwise
526
+ * register it (falling back to attaching when a sibling wins the race).
527
+ */
528
+ const SHARED_SECTION_SLOT = "settings.section"
529
+ const SHARED_SECTION_ID = "plugin-settings"
530
+ const SHARED_SECTION_ORDER = 900
531
+ const SHARED_ITEM_SLOT = "plugin-settings.item"
532
+ const SHARED_ITEM_ID = "dsh-workbuddy-connect"
533
+ const SHARED_SECTION_LABEL = "插件设置"
534
+
535
+ function PluginSettingsSection(props) {
536
+ return h("ul", {
537
+ style: { display: "flex", flexDirection: "column", gap: 6, padding: 0, listStyle: "none" },
538
+ }, props.renderSlot(SHARED_ITEM_SLOT, {}))
539
+ }
540
+
541
+ /** The package name this card belongs to, as the plugin page reports it. */
542
+ const PACKAGE_NAME = "@sixzjd/dsh-workbuddy-connect";
543
+ /** Names an existing profile may still declare from before the rename. */
544
+ const LEGACY_PACKAGE_NAMES = ["dsh-workbuddy-connect"];
545
+
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"]
687
+
688
+ function apply(ctx) {
689
+ try {
690
+ ctx.slots.inject(SHARED_SECTION_SLOT, () => {
691
+ try {
692
+ /**
693
+ * Register the shared block unless a sibling already owns it.
694
+ *
695
+ * The registrant OWNS the child declaration `plugin-settings.item`,
696
+ * and a slot's entries and its declaration die together: disposing
697
+ * the owner collapses the child slot and cascades every sibling's
698
+ * card away with it. That is why disabling whichever connector
699
+ * happened to register the block first used to remove the whole
700
+ * 《插件设置》 entry, taking the still-enabled connectors' cards with
701
+ * it.
702
+ */
703
+ const registerContainer = () => {
704
+ if (ctx.slots.entries(SHARED_SECTION_SLOT).some((entry) => entry.options?.id === SHARED_SECTION_ID)) return undefined
705
+ try {
706
+ return ctx.slots.register({
707
+ name: SHARED_SECTION_SLOT,
708
+ id: SHARED_SECTION_ID,
709
+ order: SHARED_SECTION_ORDER,
710
+ label: () => SHARED_SECTION_LABEL,
711
+ children: { [SHARED_ITEM_SLOT]: { kind: "list", scope: "root" } },
712
+ }, PluginSettingsSection)
713
+ } catch (error) {
714
+ // A sibling won the race between the check and the register.
715
+ console.error("[dsh-workbuddy-connect] shared plugin-settings block lost the race; attaching to the winner:", error)
716
+ note("container", error)
717
+ return undefined
718
+ }
719
+ }
720
+ // Depends on the ITEM slot, not the container: the item slot's
721
+ // declaration epoch is what changes when an owner collapses, so
722
+ // this re-fires and re-registers the card after a recovery.
723
+ const disposeItem = ctx.slots.inject(SHARED_ITEM_SLOT, () => ctx.slots.register({
724
+ name: SHARED_ITEM_SLOT,
725
+ id: SHARED_ITEM_ID,
726
+ order: 50,
727
+ }, () => h(WorkBuddyCard)))
728
+ let disposeContainer = registerContainer()
729
+ // Recovery: `settings.section` stays declared by the host, so this
730
+ // subscription outlives a sibling's collapse. Re-adopt the block so
731
+ // the survivors' cards come back without a page reload.
732
+ const unsubscribe = ctx.slots.subscribe(SHARED_SECTION_SLOT, () => {
733
+ disposeContainer = registerContainer() ?? disposeContainer
734
+ })
735
+ return () => {
736
+ unsubscribe()
737
+ disposeItem()
738
+ disposeContainer?.()
739
+ }
740
+ } catch (error) {
741
+ console.error("[dsh-workbuddy-connect] could not register the settings item:", error)
742
+ note("section-inject", error)
743
+ }
744
+ })
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
+ } catch (error) {
763
+ console.error("[dsh-workbuddy-connect] could not register the settings card:", error)
764
+ note("apply", error)
765
+ }
766
+ }
767
+
768
+ return { inject, apply }
769
+ },
770
+ })