dsh-magpie-connector 0.5.1 → 0.6.3
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/CHANGELOG.md +34 -0
- package/README.md +7 -3
- package/README.zh.md +3 -1
- package/docs/SCREENSHOTS.md +6 -4
- package/docs/settings.en.png +0 -0
- package/docs/settings.png +0 -0
- package/docs/usage.en.png +0 -0
- package/docs/usage.png +0 -0
- package/lib/client/SettingsPage.d.ts +8 -0
- package/lib/client/SettingsPage.js +192 -7
- package/lib/client/SidebarUsage.d.ts +22 -0
- package/lib/client/SidebarUsage.js +283 -0
- package/lib/client/UsageCard.d.ts +8 -1
- package/lib/client/UsageCard.js +71 -6
- package/lib/client/api.d.ts +1 -1
- package/lib/client/api.js +7 -1
- package/lib/client/index.d.ts +1 -1
- package/lib/client/index.js +13 -1
- package/lib/client/locales.d.ts +55 -4
- package/lib/client/locales.js +110 -8
- package/lib/client/sidebar-api.d.ts +35 -0
- package/lib/client/sidebar-api.js +62 -0
- package/lib/client/sidebar-preference.d.ts +30 -0
- package/lib/client/sidebar-preference.js +70 -0
- package/lib/client/sidebar-view.d.ts +51 -0
- package/lib/client/sidebar-view.js +80 -0
- package/lib/client/styles.d.ts +1 -6
- package/lib/client/styles.js +101 -3
- package/lib/client/view-model.d.ts +65 -4
- package/lib/client/view-model.js +69 -0
- package/lib/client.js +1224 -38
- package/lib/host/cards.d.ts +34 -1
- package/lib/host/cards.js +94 -26
- package/lib/host/reset.d.ts +68 -0
- package/lib/host/reset.js +243 -0
- package/lib/host/routes.d.ts +3 -1
- package/lib/host/routes.js +23 -6
- package/lib/host/runtime.d.ts +2 -0
- package/lib/host/runtime.js +6 -0
- package/lib/host/settings.d.ts +4 -0
- package/lib/host/transport.js +20 -3
- package/package.json +1 -1
- package/screenshots.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,39 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.6.3 — 2026-11-04
|
|
4
|
+
|
|
5
|
+
- **用上 Codex 重置卡(首个写操作)。** 卡片展开区里最早到期的那一项带「使用…」;周窗口(`7 days`)用量达到 **80%**、且读数新鲜时才可用。host 在准备和提交前各重新读一次该卡并独立校验,不信任浏览器的判断。
|
|
6
|
+
- **只用最早到期的那张。** host 从刚读到的 `resets.each[]` 里挑 `until` 最早、仍可用的一张,把它的 `id` 记进票据;浏览器拿不到也指定不了 `id`。提交前那张已不在可用列表时直接拒绝,不会改用别的卡。
|
|
7
|
+
- **两段确认 + 全插件单飞。** 「使用…」→ 60 秒一次性票据 → 对话框(账号、周用量、所选卡到期时间、不可撤销警告)→ 必须勾选才能提交。同一时刻只允许一个准备/消费;新的准备会作废旧票据。
|
|
8
|
+
- **结果判定。** `reset` 成功并用刷新响应更新卡片;`nothing_to_reset`/`no_credit`/`already_redeemed` 各有文案;4xx(权限不足、409 并发、入口白名单拒绝)说明没花掉,可重来;网络错误/超时/5xx/无法解析一律按「结果不确定」锁定该账号到 host 重启,不自动重试。
|
|
9
|
+
- **传输边界。** 白名单新增 `POST /magpie/quotas/codex-reset`,query 只允许且必须带 `user`、`credit`;其它组合在发出前拒绝。
|
|
10
|
+
- **UI 对齐 subscriptions。** 重置折叠块的箭头从 16px 字符换成 12px SVG(间距 6px),展开条目缩进 18px 与标题文字对齐,行高 28px,「使用…」紧贴「完整重置」。
|
|
11
|
+
- 修复 README(中/英)里 0.5.2 遗留的重复行。规范:`openspec/changes/magpie-codex-reset-redeem/`。
|
|
12
|
+
- 部署提示:线上入口(Cloudflare + 自建 nginx 白名单)放行 `codex-reset` 之前,该功能会如实显示网关的 403/404,卡片与生成不受影响;gateway key 需具备完整权限(只读/受限 key 被网关拒绝)。
|
|
13
|
+
|
|
14
|
+
## 0.6.2 — 2026-11-03
|
|
15
|
+
|
|
16
|
+
- **Accordion instead of an overlay.** Expanding the sidebar usage card no longer covers the session list: the detail grows in flow inside the same card and the list gives up height from the bottom (the list keeps its top anchor, so rows do not jump). No divider line; the card surface and shadow carry the separation.
|
|
17
|
+
- **Header-only interaction.** Only the header row toggles expand/collapse (the refresh button keeps its own action); the card body and the overflow chevron are no longer click targets — the chevron is a passive "more rows" hint.
|
|
18
|
+
- **Configurable auto refresh.** New host setting `sidebarRefreshMinutes` (whole minutes, default `5`, `0` = off, range `0–1440`, non-integers/out-of-range rejected with 400) and a matching "Auto refresh" field in Settings → Magpie → Sidebar usage. The card re-reads silently on that interval, paused while the page is hidden and resumed on visibility; it never sends `POST {all:true}`. With `0` the previous event-driven behaviour (mount, manual refresh, expand, page visible) is unchanged.
|
|
19
|
+
- **README screenshots.** New sidebar usage card screenshot (`usage.png` / `usage.en.png`) and refreshed Settings screenshots showing the sidebar panel with auto refresh; registered in `docs/SCREENSHOTS.md`.
|
|
20
|
+
|
|
21
|
+
## 0.6.1 — 2026-11-03
|
|
22
|
+
|
|
23
|
+
- **重置卡改成和 subscriptions 插件一样的折叠列表。** host 现在把网关 `resets.each[]`(每项只保留 `until`/`window`)与 `resets.byWindow`/`fiveHour`/`weekly` 投影给浏览器;卡片上用「用量限制重置 · 可用 N 次」做摘要行,展开后逐张列出「完整重置」/「5 小时」/「每周」和每张的「{时间} 到期」,最早到期那张附相对提示(`N 天后过期` / 不足 24 小时 `N 小时后过期` / 已过期),缺到期时间显示「到期时间不可用」。按窗口发放重置的计划(GLM Coding)摘要显示「5 小时 N 次 · 每周 M 次」。
|
|
24
|
+
- 仍然只读:没有新增按钮,也不调用任何重置端点;网关不给 `each`/`byWindow` 时退回原来的「次数 + `until`」显示。
|
|
25
|
+
- Codex 卡片只显示一个 `7 days` 窗口是网关数据如此:ChatGPT 的 `/wham/usage` 对当前账号只上报周窗口,插件不会补造 5 小时窗口。
|
|
26
|
+
- 规范:`openspec/changes/magpie-reset-card-detail/`。
|
|
27
|
+
|
|
28
|
+
## 0.6.0 — 2026-11-03
|
|
29
|
+
|
|
30
|
+
- **Sidebar usage card.** Settings → Magpie gains a 「侧边栏额度 / Sidebar usage」 switch (host setting `sidebarUsage`, default off). When on, the sidebar footer shows a dense card above Settings: one row per upstream with its weekly (`7 days`) window, reading and bar; at most five rows, the rest scroll inside the card, and a double chevron (no divider) appears when more exist. Rows keep the gateway's order, a card with an error shows 「读取失败」 instead of a reading, and the whole card has a single refresh (`{all:true}`).
|
|
31
|
+
- **Expands in place.** Clicking the card grows it upward in place: every upstream with every window, reset time, reset chances, balance and the redacted error. The resident card keeps its flow slot, so the session list keeps its height; the expanded layer is an overlay with the same shadow as the resident card, not a layout change. The title row carries one chevron that both expands and collapses.
|
|
32
|
+
- **Balance-only accounts.** An upstream with no quota windows but a gateway-reported balance shows that balance (for example `¥42.50`) instead of a bare dash.
|
|
33
|
+
- **Collapsed sidebar.** With the sidebar in rail mode only a Magpie icon remains (tooltip 「Magpie 额度」); clicking it opens the same content as a 320px anchored popover.
|
|
34
|
+
- **Event-driven reads.** The card reuses `GET /api/dsh-magpie-connector/cards` with a 60s client cache and reads only on mount, manual refresh, expanding, or the page becoming visible again; no timer polling. The settings page is unchanged and keeps per-card refresh.
|
|
35
|
+
- No host request/route changes; the only host addition is the persisted `sidebarUsage` flag.
|
|
36
|
+
|
|
3
37
|
## 0.5.1 — 2026-11-02
|
|
4
38
|
|
|
5
39
|
- README 中英首屏改用 deviceScaleFactor 3 的静态 PNG(3300x1920 / 2400x2400),替换旧的低分辨率图与 GIF;同时改为 markdown 图片写法,商店详情页可直接渲染。
|
package/README.md
CHANGED
|
@@ -6,7 +6,9 @@ English · [简体中文](README.zh.md)
|
|
|
6
6
|
|
|
7
7
|

|
|
8
8
|
|
|
9
|
-
|
|
9
|
+

|
|
10
|
+
|
|
11
|
+
*Top: model picker grouped by upstream provider. Middle: Settings → Magpie — the connection line, the sidebar usage panel (toggle plus auto-refresh interval in minutes) and per-provider model visibility, default effort and usage cards. Bottom: the resident sidebar usage card (click its header to expand every window). Captured from an isolated DSH host (English UI) with a local mock Magpie gateway; gateway address, models, account and readings are synthetic.*
|
|
10
12
|
|
|
11
13
|

|
|
12
14
|
|
|
@@ -23,7 +25,9 @@ English · [简体中文](README.zh.md)
|
|
|
23
25
|
| **Grouped by upstream provider** (signature) | Works on stock DSH, no Host extension needed: the plugin registers one real provider route per gateway `owned_by` (`dsh-magpie-connector-claude`, `-codex`, `-opencode-go`, …; missing or invalid ownership goes to `-other`), so the official model picker shows `Magpie (Claude)`, `Magpie (Codex)`, `Magpie (Opencode-go)`, `Magpie (Other)` groups. Settings and usage cards use the same grouping, and a provider that only appears in usage is never dropped. |
|
|
24
26
|
| **Line panel and latency** | Configured lines start collapsed; click a row header to edit it, and reorder/delete are always-visible DSH product-icon buttons with tooltips. Opening Settings measures every saved line with a parseable address once (parallel TCP connect time, ≤600ms per line, no HTTP, no credentials) and shows a 4-bar signal plus milliseconds; timeouts show a timeout reading and failures or older hosts degrade to a dash. Display-only: it never affects automatic line selection, is not persisted, and never polls. |
|
|
25
27
|
| **Per-line Cloudflare Access** | Each line independently chooses Direct or Cloudflare Access. Access-enabled line requests carry the service token pair plus the bearer key; the token is never sent to a plain-HTTP line. |
|
|
26
|
-
| **
|
|
28
|
+
| **Usage cards** | Each upstream account shows plan, expiry, window readings and, when the gateway provides them, its Codex reset credits: a folded `Usage limit resets · N available` line that expands to each credit with its expiry and how far off the soonest is (`expires in N days`); plans that hand out one kind per window show `2 five-hour · 1 weekly` in the summary instead. Cards are read once when settings open and only re-read when you press **Refresh** on that card; bars turn orange above 70% and red at 90%. |
|
|
29
|
+
| **Use a Codex reset** (0.6.3) | The credit that expires first carries a **Use…** button. It stays inert until the account's weekly usage is at least 80% and the reading is fresh, and the host revalidates against a fresh gateway read before and after you confirm. Confirming spends one credit: a 60-second one-shot ticket, a dialog showing the account, weekly usage and expiry, and a box you must tick first. One reset runs at a time plugin-wide, a 4xx from the gateway means nothing was spent, and an unreadable answer locks that account until the host restarts (check Magpie, do not retry). Needs a full-access gateway key and, behind a self-hosted ingress, an allowlist entry for `POST /magpie/quotas/codex-reset`. |
|
|
30
|
+
| **Sidebar usage card** (0.6.0) | Settings → Magpie has a 「Sidebar usage」 switch (host setting, default off) and an auto-refresh interval (minutes, `0` = off, default 5). When on, a dense card sits above Settings: one weekly (`7 days`) row per upstream with its reading and bar, at most five rows with the rest scrolling inside and a overflow chevron when more exist, and one refresh for the whole card. Clicking the header row toggles an in-flow detail list (every window, reset time/chances, balance, error) that shrinks the session list instead of covering it; in rail mode a single Magpie icon opens the same content as a 320px popover. Reads reuse the existing usage endpoint with a 60s cache; only the configured interval polls, silently and paused while the page is hidden. |
|
|
27
31
|
| **Model visibility and default effort** | Per provider, leave visibility untouched to follow the gateway catalog, or save an explicit allowlist so new models stay hidden. Per model, save a default reasoning effort; DSH applies it on the next request. |
|
|
28
32
|
| **Per-session fast mode** | Models advertising the `priority` service tier get a standard/fast switch next to the composer. The choice is per session and in host memory only; it adds `service_tier: "priority"` to requests. |
|
|
29
33
|
|
|
@@ -67,7 +71,7 @@ Need another method — custom headers, mTLS, another zero-trust gateway? **Issu
|
|
|
67
71
|
- **Only silence ends a stream.** Headers, SSE events and heartbeats all count as liveness; 300 seconds without any data ends the request with `TIMEOUT` (message contains `MAGPIE_STREAM_TIMEOUT`). Long reasoning survives as long as the gateway keeps the stream alive.
|
|
68
72
|
- **Connection changes do not abort work.** A new address or key immediately hides the old catalog and cards, but generations already prepared or running finish with their captured address and key. User cancellation and plugin disposal still stop them.
|
|
69
73
|
- **The transport is deliberately narrow.** Host requests go through a private `undici` dispatcher straight to the configured gateway, never through a global proxy dispatcher. Redirects are rejected; only `GET /models`, `POST /responses`, `POST /chat/completions`, `GET /magpie/quotas/cards` and `POST /magpie/quotas/refresh` are allowed; Magpie GUI `/api/*` management endpoints are never called. Provider egress proxies belong in Magpie.
|
|
70
|
-
- **Not supported:** `stop` sequences fail before any network access (`MAGPIE_STOP_UNSUPPORTED`) because Magpie cannot preserve them across every upstream translation. Usage cards
|
|
74
|
+
- **Not supported:** `stop` sequences fail before any network access (`MAGPIE_STOP_UNSUPPORTED`) because Magpie cannot preserve them across every upstream translation. Usage cards are read-only. Spending a Codex reset is the plugin's only write to a Magpie account: it is manual, two-step, limited to the credit that expires first, and it never touches account-management endpoints.
|
|
71
75
|
- **Secrets stay out of responses and logs.** Gateway-reflected text is redacted with the current key before it can reach the settings API or logs. Files are written `0600`; the settings API reports only `configured` / `writable`.
|
|
72
76
|
- **The interface follows the DSH UI language.** Since 0.5.0 the settings page and the speed menu ship English and Chinese dictionaries and render in the active DSH language (`ctx.locale`); before 0.5.0 the copy was Chinese-only. A host without a locale service (or a unit test) falls back to the Chinese reference set, so stored settings and behaviour are untouched.
|
|
73
77
|
|
package/README.zh.md
CHANGED
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
| **按上游 provider 分组**(特色) | 原版 DSH 即可使用,无需 Host 扩展:插件按网关 `owned_by` 为每个归属注册一个真实 provider route(`dsh-magpie-connector-claude`、`-codex`、`-opencode-go` 等;缺失或不合法归入 `-other`),官方模型选择器因此显示 `Magpie (Claude)`、`Magpie (Codex)`、`Magpie (Opencode-go)`、`Magpie (Other)` 分组。设置页和用量卡片使用同一套分组,只出现在用量里的 provider 也不会被丢弃。 |
|
|
24
24
|
| **线路面板与延迟** | 已配置的线路默认全部收起,点行头部展开编辑;上移 / 下移 / 删除是常驻的 DSH 产品图标按钮(带 tooltip)。打开设置页对每条已保存且地址可解析的线路做一次 TCP 建连测速(并行、单条 ≤600ms、不发 HTTP、不带凭据),用 4 格信号条 + 毫秒显示;超时显示「超时」,旧版宿主或失败显示「—」。只展示当时的网络质量,不参与自动选线、不持久化、不轮询。 |
|
|
25
25
|
| **按线路的 Cloudflare Access** | 每条线路可单独选择「直连」或「Cloudflare Access」。启用后该线路的请求带上服务令牌两项并保留 bearer key;服务令牌永远不会发往明文 HTTP 线路。 |
|
|
26
|
-
|
|
|
26
|
+
| **用量卡片** | 每个上游账号展示计划、到期时间、各窗口读数和 Codex 重置卡(网关提供时):折叠行「用量限制重置 · 可用 N 次」,展开逐张看到期时间与最早一张还剩多久(`N 天后过期`);按窗口发放的计划摘要显示「5 小时 N 次 · 每周 M 次」。打开设置页只读一次,之后只有点单张卡片的「刷新」才会重新读取;用量条超过 70% 变橙、达到 90% 变红。 |
|
|
27
|
+
| **使用 Codex 重置卡**(0.6.3) | 最早到期的那张带「使用…」按钮。周用量 ≥ 80% 且读数新鲜时才可点;确认前后 host 都会重新读一次网关再校验。确认会消耗一次额度:60 秒一次性票据 + 对话框(账号、周用量、到期时间),必须先勾选才能提交。全插件同一时刻只允许一个;网关 4xx 说明没花掉;应答无法解析时该账号锁定到 host 重启(先去 Magpie 核对,不要重试)。需要完整权限的 gateway key;自建入口还需为 `POST /magpie/quotas/codex-reset` 放行。 |
|
|
28
|
+
| **侧栏额度卡**(0.6.0) | 设置 → Magpie 新增「侧边栏额度」开关(host 持久化,默认关闭)与自动刷新间隔(分钟,`0` = 关闭,默认 5)。打开后左侧栏底部常驻一张密集卡片:每个上游一行周窗口(`7 days`)读数与进度条,最多 5 行、多出的在卡内滚动并显示溢出箭头,整张卡只有一个刷新。点标题行在手风琴里展开每个上游的全部窗口、重置时间/机会、余额与错误,占列表高度而不是盖住列表;侧栏收起时只剩一个 Magpie icon,点开是 320px 浮层。读取复用现有用量接口,客户端 60s 缓存,只有配置的间隔会静默轮询,页面隐藏时暂停。 |
|
|
27
29
|
| **模型可见性与默认 effort** | 每个 provider 不设置可见性时跟随网关目录;保存过选择后只显示勾选项,新上架模型默认隐藏。每个模型可保存一个默认推理 effort,DSH 在下一次请求应用。 |
|
|
28
30
|
| **会话级快速档** | 网关声明 `priority` 服务档的模型,输入框旁会出现标准/快速切换。选择按会话保存在 host 内存,快速档会给请求带上 `service_tier: "priority"`。 |
|
|
29
31
|
|
package/docs/SCREENSHOTS.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# Screenshots
|
|
2
2
|
|
|
3
|
-
| model-picker.png | screenshot | 0.
|
|
4
|
-
| settings.png | screenshot | same 0.
|
|
5
|
-
|
|
|
6
|
-
|
|
|
3
|
+
| model-picker.png | screenshot | 0.6.1 build in an isolated DSH_HOME (temp HOME/DSH_HOME under /tmp, port 3255) against a local loopback mock Magpie gateway; Chinese UI; region clip 1100x640 at deviceScaleFactor 3 | 2026-11-02 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: Chinese UI, demo workspace, loopback gateway address, mock models only; no hostname, user, key, path or real session) | 3300x1920, 195233 bytes; model picker open with Magpie (Claude), Magpie (Codex) and Magpie (Deepseek) groups; Chinese README first image |
|
|
4
|
+
| settings.png | screenshot | same 0.6.1 isolated host and mock gateway; Chinese UI; settings dialog region 800x786 at deviceScaleFactor 3 | 2026-11-03 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: Chinese settings copy, demo@example.com account, loopback gateway address, mock models and readings; no hostname, user, key, path or real session) | 2400x2358, 353740 bytes; connection line, sidebar usage panel with auto-refresh minutes, per-provider models, default effort and the Claude usage card; Chinese README second image |
|
|
5
|
+
| usage.png | screenshot | same 0.6.1 isolated host and mock gateway; Chinese UI; sidebar card region clip 256x164 at deviceScaleFactor 3 | 2026-11-03 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: Chinese UI, mock models and readings, synthetic balance; no hostname, user, key, path or real session) | 768x492, 47436 bytes; compact resident card with 5 weekly rows, overflow chevron, balance-only DeepSeek row and an unreadable upstream; Chinese README third image |
|
|
6
|
+
| model-picker.en.png | screenshot | same 0.6.1 isolated host and mock gateway; English UI; region clip 1100x640 at deviceScaleFactor 3 | 2026-11-02 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: English UI, demo workspace, loopback gateway address, mock models only; no hostname, user, key, path or real session) | 3300x1920, 188924 bytes; English README first image |
|
|
7
|
+
| settings.en.png | screenshot | same 0.6.1 isolated host and mock gateway; English UI; settings dialog region 800x786 at deviceScaleFactor 3 | 2026-11-03 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: English settings copy, demo@example.com account, loopback gateway address, mock models and readings; no hostname, user, key, path or real session) | 2400x2358, 366280 bytes; English README second image |
|
|
8
|
+
| usage.en.png | screenshot | same 0.6.1 isolated host and mock gateway; English UI; sidebar card region clip 256x161 at deviceScaleFactor 3 | 2026-11-03 | agent (privacy-reviewed; pending lead acceptance) | pass (reviewed: English UI, mock models and readings, synthetic balance; no hostname, user, key, path or real session) | 768x483, 47039 bytes; English README third image |
|
package/docs/settings.en.png
CHANGED
|
Binary file
|
package/docs/settings.png
CHANGED
|
Binary file
|
|
Binary file
|
package/docs/usage.png
ADDED
|
Binary file
|
|
@@ -16,3 +16,11 @@ export declare function MagpieSettings({ api }: {
|
|
|
16
16
|
}): import("react").DetailedReactHTMLElement<{
|
|
17
17
|
className: string;
|
|
18
18
|
}, HTMLElement>;
|
|
19
|
+
/**
|
|
20
|
+
* Why the host or the gateway said no, in the page's words. The host's codes are
|
|
21
|
+
* fixed strings; anything else falls back to its (already redacted) message.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resetErrorText(response: {
|
|
24
|
+
status: number;
|
|
25
|
+
body: unknown;
|
|
26
|
+
}): string;
|
|
@@ -5,7 +5,8 @@ import { lineLatency, parseLatency } from './latency.js';
|
|
|
5
5
|
import { settingsCss } from './styles.js';
|
|
6
6
|
import { UsageCard } from './UsageCard.js';
|
|
7
7
|
import { t } from './locales.js';
|
|
8
|
-
import {
|
|
8
|
+
import { DEFAULT_REFRESH_MINUTES, MAX_REFRESH_MINUTES, setSidebarPreference } from './sidebar-preference.js';
|
|
9
|
+
import { cacheIds, cardKey, checkDiff, checkSignature, formatTime, parseCards, parseCheck, parseResetOutcome, parseResetTicket, providerOrder, readTime, resetAccount, sameTarget, } from './view-model.js';
|
|
9
10
|
/**
|
|
10
11
|
* Magpie settings section: connection (with an advanced access mode), then
|
|
11
12
|
* per-provider groups (model visibility, DSH-side default effort, read-only
|
|
@@ -71,6 +72,11 @@ export function MagpieSettings({ api }) {
|
|
|
71
72
|
const [usageAlert, setUsageAlert] = useState('');
|
|
72
73
|
const [savingSettings, setSavingSettings] = useState(false);
|
|
73
74
|
const [latency, setLatency] = useState({ phase: 'idle' });
|
|
75
|
+
const [resetConfirm, setResetConfirm] = useState();
|
|
76
|
+
const [resetBusyKey, setResetBusyKey] = useState();
|
|
77
|
+
const [resetConsuming, setResetConsuming] = useState(false);
|
|
78
|
+
const [resetAcknowledged, setResetAcknowledged] = useState(false);
|
|
79
|
+
const [resetStatuses, setResetStatuses] = useState({});
|
|
74
80
|
const settingsRef = useRef(undefined);
|
|
75
81
|
const settingsVersion = useRef(0);
|
|
76
82
|
const settingsLock = useRef(false);
|
|
@@ -267,8 +273,7 @@ export function MagpieSettings({ api }) {
|
|
|
267
273
|
};
|
|
268
274
|
const groups = settings?.groups ?? [];
|
|
269
275
|
const cardList = cards?.cards ?? [];
|
|
270
|
-
const busy = refreshing !== undefined;
|
|
271
|
-
// Catalog first, then an all-provider usage read: the only bulk refresh left, for when no card exists yet.
|
|
276
|
+
const busy = refreshing !== undefined; // Catalog first, then an all-provider usage read: the only bulk refresh left, for when no card exists yet.
|
|
272
277
|
const fetchAll = async () => {
|
|
273
278
|
const result = await mutateSettings({ resync: true });
|
|
274
279
|
if (result?.view)
|
|
@@ -279,16 +284,102 @@ export function MagpieSettings({ api }) {
|
|
|
279
284
|
}
|
|
280
285
|
};
|
|
281
286
|
const groupNote = (provider) => noteScope === provider ? { notice, alert: usageAlert } : {};
|
|
287
|
+
const setResetStatus = (key, status) => setResetStatuses(current => {
|
|
288
|
+
const next = { ...current };
|
|
289
|
+
if (status === undefined)
|
|
290
|
+
delete next[key];
|
|
291
|
+
else
|
|
292
|
+
next[key] = status;
|
|
293
|
+
return next;
|
|
294
|
+
});
|
|
295
|
+
/**
|
|
296
|
+
* Prepare a reset: the host re-reads the card, revalidates the guard and hands
|
|
297
|
+
* back a one-shot ticket. Nothing is spent until the dialog is confirmed.
|
|
298
|
+
*/
|
|
299
|
+
const startReset = async (card) => {
|
|
300
|
+
const account = resetAccount(card);
|
|
301
|
+
if (!account || resetBusyKey !== undefined || resetConsuming)
|
|
302
|
+
return;
|
|
303
|
+
const key = cardKey(card);
|
|
304
|
+
setResetBusyKey(key);
|
|
305
|
+
setResetStatus(key, undefined);
|
|
306
|
+
try {
|
|
307
|
+
const response = await api({ method: 'POST', path: 'reset', body: { action: 'prepare', provider: 'codex', user: account } });
|
|
308
|
+
const ticket = isOk(response) ? parseResetTicket(response.body) : undefined;
|
|
309
|
+
if (!ticket) {
|
|
310
|
+
setResetStatus(key, { text: resetErrorText(response), tone: 'error' });
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
setResetAcknowledged(false);
|
|
314
|
+
setResetConfirm({ card, ...ticket });
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
setResetStatus(key, { text: t('resetUseReadFailed'), tone: 'error' });
|
|
318
|
+
}
|
|
319
|
+
finally {
|
|
320
|
+
setResetBusyKey(undefined);
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
/** Spend the prepared credit. Every answer is reported where the button was. */
|
|
324
|
+
const confirmReset = async () => {
|
|
325
|
+
if (!resetConfirm || !resetAcknowledged || resetConsuming)
|
|
326
|
+
return;
|
|
327
|
+
const key = cardKey(resetConfirm.card);
|
|
328
|
+
setResetConsuming(true);
|
|
329
|
+
try {
|
|
330
|
+
const response = await api({ method: 'POST', path: 'reset', body: { action: 'consume', ticket: resetConfirm.ticket } });
|
|
331
|
+
const outcome = parseResetOutcome(response.body);
|
|
332
|
+
if (!isOk(response) || !outcome) {
|
|
333
|
+
setResetStatus(key, { text: resetErrorText(response), tone: response.status === 502 ? 'warn' : 'error' });
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
if (outcome.outcome === 'reset') {
|
|
337
|
+
if (outcome.cards)
|
|
338
|
+
setCards(parseCards({ status: 'ok', cards: outcome.cards }, 200));
|
|
339
|
+
setResetStatus(key, {
|
|
340
|
+
text: outcome.windows === undefined ? t('resetUseSuccess') : `${t('resetUseSuccess')} · ${t('resetUseResetCode', { windows: outcome.windows })}`,
|
|
341
|
+
tone: 'ok',
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
else if (outcome.outcome === 'uncertain')
|
|
345
|
+
setResetStatus(key, { text: t('resetUseUncertain'), tone: 'warn' });
|
|
346
|
+
else if (outcome.outcome === 'unconsumed')
|
|
347
|
+
setResetStatus(key, { text: t('resetUseUnconsumed', { reason: outcome.error ?? '' }), tone: 'error' });
|
|
348
|
+
else if (outcome.outcome === 'kept')
|
|
349
|
+
setResetStatus(key, { text: t('resetUseKept'), tone: 'ok' });
|
|
350
|
+
else if (outcome.outcome === 'no-credit')
|
|
351
|
+
setResetStatus(key, { text: t('resetUseNoCredit'), tone: 'error' });
|
|
352
|
+
else if (outcome.outcome === 'already')
|
|
353
|
+
setResetStatus(key, { text: t('resetUseAlready'), tone: 'error' });
|
|
354
|
+
else
|
|
355
|
+
setResetStatus(key, { text: t('resetUseUnknown', { code: outcome.code ?? '' }), tone: 'warn' });
|
|
356
|
+
}
|
|
357
|
+
catch {
|
|
358
|
+
// The browser gave up before the host answered: the spend may have happened.
|
|
359
|
+
setResetStatus(key, { text: t('resetUseUncertain'), tone: 'warn' });
|
|
360
|
+
}
|
|
361
|
+
finally {
|
|
362
|
+
setResetConsuming(false);
|
|
363
|
+
setResetConfirm(undefined);
|
|
364
|
+
}
|
|
365
|
+
};
|
|
282
366
|
return h('div', { className: 'dmg-settings' }, h('style', null, settingsCss), h('p', { className: 'dmg-intro' }, t('intro')), settingsError ? h('p', { className: 'dmg-error', role: 'alert' }, t('settingsReadFailed', { error: settingsError })) : null, settings ? h(Connection, { settings, saving: savingSettings, mutateSettings, api, latency, onRefreshLatency: (lineId) => { void readLatency(lineId); },
|
|
283
367
|
usage: h(UsageStatus, { cards, busy, ...(noteScope === undefined ? { notice, alert: usageAlert } : {}), onFetchAll: () => { void fetchAll(); }, saving: savingSettings }) })
|
|
284
|
-
: settingsError ? null : h('p', { role: 'status', className: 'dmg-hint' }, t('readingSettings')), ...providerOrder(groups, cardList).map(provider => h(ProviderGroup, {
|
|
368
|
+
: settingsError ? null : h('p', { role: 'status', className: 'dmg-hint' }, t('readingSettings')), settings ? h(SidebarUsagePreference, { settings, saving: savingSettings, mutateSettings }) : null, ...providerOrder(groups, cardList).map(provider => h(ProviderGroup, {
|
|
285
369
|
key: provider, provider,
|
|
286
370
|
group: groups.find(g => g.provider === provider),
|
|
287
371
|
settings,
|
|
288
372
|
cards: cardList.filter(c => c.provider === provider),
|
|
289
373
|
busy, saving: savingSettings, mutateSettings, ...groupNote(provider),
|
|
374
|
+
resetBusyKey, resetStatuses,
|
|
375
|
+
onReset: (card) => { void startReset(card); },
|
|
290
376
|
onRefresh: (card) => { void refresh({ provider: card.provider, ...(card.user !== undefined ? { user: card.user } : {}) }); },
|
|
291
|
-
}))
|
|
377
|
+
})), h(ResetDialog, {
|
|
378
|
+
confirm: resetConfirm, acknowledged: resetAcknowledged, busy: resetConsuming,
|
|
379
|
+
onAcknowledge: setResetAcknowledged,
|
|
380
|
+
onCancel: () => { setResetConfirm(undefined); setResetAcknowledged(false); },
|
|
381
|
+
onConfirm: () => { void confirmReset(); },
|
|
382
|
+
}));
|
|
292
383
|
}
|
|
293
384
|
/** What to tell the user after a 2xx refresh: unchanged read times, or a still-empty cold start. */
|
|
294
385
|
function noticeAfter(target, before, next) {
|
|
@@ -327,6 +418,42 @@ function UsageStatus({ cards, busy, saving, notice, alert, onFetchAll }) {
|
|
|
327
418
|
return null;
|
|
328
419
|
return h('div', { className: 'dmg-usage', 'data-usage-state': state, 'aria-label': t('usageLabel') }, ...lines, canFetch ? h('div', { className: 'dmg-row' }, h('button', { type: 'button', className: 'dmg-button', disabled: busy || saving, onClick: onFetchAll }, t('fetchModelsAndUsage'))) : null);
|
|
329
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Why the host or the gateway said no, in the page's words. The host's codes are
|
|
423
|
+
* fixed strings; anything else falls back to its (already redacted) message.
|
|
424
|
+
*/
|
|
425
|
+
export function resetErrorText(response) {
|
|
426
|
+
const reason = response.body?.error;
|
|
427
|
+
const code = typeof reason === 'string' ? reason : '';
|
|
428
|
+
if (code === 'MAGPIE_RESET_BUSY')
|
|
429
|
+
return t('resetUseBusy');
|
|
430
|
+
if (code === 'MAGPIE_RESET_UNCERTAIN' || code.startsWith('MAGPIE_RESET_UNCERTAIN:'))
|
|
431
|
+
return t('resetUseUncertain');
|
|
432
|
+
if (code === 'MAGPIE_RESET_GUARD')
|
|
433
|
+
return t('resetUseGuard');
|
|
434
|
+
if (code === 'MAGPIE_RESET_UNAVAILABLE' || code === 'MAGPIE_RESET_CREDIT_GONE')
|
|
435
|
+
return t('resetUseUnavailable');
|
|
436
|
+
if (code === 'MAGPIE_RESET_REFRESH')
|
|
437
|
+
return t('resetUseRefresh');
|
|
438
|
+
if (code === 'MAGPIE_RESET_TICKET_INVALID')
|
|
439
|
+
return t('resetUseTicketInvalid');
|
|
440
|
+
if (code === 'MAGPIE_RESET_TICKET_EXPIRED')
|
|
441
|
+
return t('resetUseTicketExpired');
|
|
442
|
+
if (code.startsWith('MAGPIE_RESET_READ_FAILED'))
|
|
443
|
+
return t('resetUseReadFailed');
|
|
444
|
+
return failureText(response);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* The confirmation of an irreversible spend. Rendered as an open `<dialog>` inside
|
|
448
|
+
* a backdrop: the shell has no modal service, and a plain element keeps the page
|
|
449
|
+
* testable without `showModal`. The confirm button stays inert until the box is ticked.
|
|
450
|
+
*/
|
|
451
|
+
function ResetDialog({ confirm, acknowledged, busy, onAcknowledge, onCancel, onConfirm }) {
|
|
452
|
+
if (!confirm)
|
|
453
|
+
return null;
|
|
454
|
+
const { card } = confirm;
|
|
455
|
+
return h('div', { className: 'dmg-modal-backdrop', 'data-reset-dialog': '' }, h('dialog', { open: true, className: 'dmg-modal', 'aria-labelledby': 'dmg-reset-title' }, h('h3', { id: 'dmg-reset-title' }, t('resetUseConfirmTitle')), h('p', { className: 'dmg-hint', 'data-reset-account': '' }, `${t('resetUseAccount')}:${card.user ?? ''}`), confirm.weeklyUsedPercent === undefined ? null : h('p', { className: 'dmg-hint', 'data-reset-weekly': '' }, `${t('resetUseWeekly')} ${Math.round(confirm.weeklyUsedPercent)}%`), confirm.creditExpiresAt === undefined ? null : h('p', { className: 'dmg-hint', 'data-reset-credit': '' }, t('resetCreditExpires', { date: formatTime(confirm.creditExpiresAt) })), h('p', { className: 'dmg-warn' }, t('resetUseWarning')), h('label', { className: 'dmg-check-row' }, h('input', { type: 'checkbox', checked: acknowledged, 'data-reset-acknowledge': '', onChange: (e) => onAcknowledge(e.target.checked) }), h('span', null, t('resetUseAcknowledge'))), h('div', { className: 'dmg-row' }, h('button', { type: 'button', className: 'dmg-button', onClick: onCancel }, t('cancel')), h('button', { type: 'button', className: 'dmg-button', 'data-reset-confirm': '', disabled: !acknowledged || busy, onClick: onConfirm }, busy ? t('resetUseConfirming') : t('resetUseConfirm')))));
|
|
456
|
+
}
|
|
330
457
|
async function postSettings(api, body) {
|
|
331
458
|
try {
|
|
332
459
|
const response = await api({ method: 'POST', path: 'settings', body });
|
|
@@ -594,7 +721,7 @@ function SyncStatus({ settings }) {
|
|
|
594
721
|
const registration = settings.routeRegistrationError;
|
|
595
722
|
return h('div', { className: 'dmg-meta', 'data-sync': '' }, settings.lastSyncAt ? h('p', null, t('modelsCount', { n: count }), h('time', { dateTime: settings.lastSyncAt }, formatTime(settings.lastSyncAt))) : null, settings.lastSyncError ? h('p', { className: 'dmg-error' }, t('syncFailed', { kind: settings.lastSyncErrorKind ? t('syncFailedKind', { kind: t(SYNC_KIND[settings.lastSyncErrorKind] ?? 'syncKindHttp') }) : '', error: settings.lastSyncError })) : null, registration ? h('p', { className: 'dmg-error', role: 'alert' }, t('routeRegistrationFailed', { code: registration.code, route: registration.route ? `, ${registration.route}` : '' })) : null, settings.knownOwnersReset ? h('p', { className: 'dmg-hint' }, t('ownersReset')) : null, settings.ownerLimitReached ? h('p', { className: 'dmg-hint' }, t('ownerLimitReached', { list: rejected.join(t('listSeparator')) })) : null);
|
|
596
723
|
}
|
|
597
|
-
function ProviderGroup({ provider, group, settings, cards, busy, saving, mutateSettings, onRefresh, notice, alert }) {
|
|
724
|
+
function ProviderGroup({ provider, group, settings, cards, busy, saving, mutateSettings, onRefresh, onReset, resetBusyKey, resetStatuses, notice, alert }) {
|
|
598
725
|
const [error, setError] = useState('');
|
|
599
726
|
const saved = settings?.visibleModels ?? {};
|
|
600
727
|
const following = !Object.hasOwn(saved, provider);
|
|
@@ -628,7 +755,12 @@ function ProviderGroup({ provider, group, settings, cards, busy, saving, mutateS
|
|
|
628
755
|
effort: settings?.defaultEfforts?.[model.id],
|
|
629
756
|
onVisible: (visible) => setVisible(model, visible),
|
|
630
757
|
onEffort: (effort) => { void post({ defaultEffort: { model: model.id, effort } }); },
|
|
631
|
-
}))) : null, cards.length ? h('div', { className: 'dmg-cards' }, ...cards.map(card => h(UsageCard, {
|
|
758
|
+
}))) : null, cards.length ? h('div', { className: 'dmg-cards' }, ...cards.map(card => h(UsageCard, {
|
|
759
|
+
key: cardKey(card), card, busy, disabled: saving,
|
|
760
|
+
resetBusy: resetBusyKey === cardKey(card),
|
|
761
|
+
...(resetStatuses?.[cardKey(card)] === undefined ? {} : { resetStatus: resetStatuses[cardKey(card)] }),
|
|
762
|
+
onRefresh: () => onRefresh(card), onReset: () => onReset(card),
|
|
763
|
+
}))) : null, notice === 'not-reread' ? h('p', { className: 'dmg-hint', role: 'status' }, t('notReread')) : null, alert ? h('p', { className: 'dmg-error', role: 'alert', 'data-usage-alert': '' }, alert) : null, error ? h('p', { className: 'dmg-error', role: 'alert' }, error) : null);
|
|
632
764
|
}
|
|
633
765
|
function ModelLine({ model, visible, effort, disabled, onVisible, onEffort }) {
|
|
634
766
|
const efforts = model.efforts ?? [];
|
|
@@ -640,3 +772,56 @@ function ModelLine({ model, visible, effort, disabled, onVisible, onEffort }) {
|
|
|
640
772
|
value: effort ?? '', onChange: (e) => onEffort(e.target.value === '' ? null : e.target.value),
|
|
641
773
|
}, h('option', { value: '' }, t('defaultEffortNone')), stale ? h('option', { value: effort, disabled: true }, t('effortStale', { effort })) : null, ...efforts.map(id => h('option', { key: id, value: id }, id))) : null);
|
|
642
774
|
}
|
|
775
|
+
/**
|
|
776
|
+
* The sidebar preference: one host-persisted flag. The host is the source of
|
|
777
|
+
* truth; the module store is updated so the already-mounted sidebar card
|
|
778
|
+
* follows the toggle without a reload.
|
|
779
|
+
*/
|
|
780
|
+
function SidebarUsagePreference({ settings, saving, mutateSettings }) {
|
|
781
|
+
const [failed, setFailed] = useState('');
|
|
782
|
+
const enabled = settings.sidebarUsage === true;
|
|
783
|
+
const savedMinutes = settings.sidebarRefreshMinutes ?? DEFAULT_REFRESH_MINUTES;
|
|
784
|
+
const [draft, setDraft] = useState(String(savedMinutes));
|
|
785
|
+
useEffect(() => { setDraft(String(savedMinutes)); }, [savedMinutes]);
|
|
786
|
+
const toggle = async () => {
|
|
787
|
+
setFailed('');
|
|
788
|
+
const next = !enabled;
|
|
789
|
+
const result = await mutateSettings({ sidebarUsage: next });
|
|
790
|
+
if (result?.error) {
|
|
791
|
+
setFailed(result.error);
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
setSidebarPreference({ usage: result?.view === undefined ? next : result.view.sidebarUsage === true });
|
|
795
|
+
};
|
|
796
|
+
const commitMinutes = async () => {
|
|
797
|
+
setFailed('');
|
|
798
|
+
const raw = draft.trim();
|
|
799
|
+
if (!/^\d+$/.test(raw)) {
|
|
800
|
+
setDraft(String(savedMinutes));
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
const minutes = Math.min(MAX_REFRESH_MINUTES, Number(raw));
|
|
804
|
+
if (minutes !== savedMinutes) {
|
|
805
|
+
const result = await mutateSettings({ sidebarRefreshMinutes: minutes });
|
|
806
|
+
if (result?.error) {
|
|
807
|
+
setFailed(result.error);
|
|
808
|
+
setDraft(String(savedMinutes));
|
|
809
|
+
return;
|
|
810
|
+
}
|
|
811
|
+
setSidebarPreference({ refreshMinutes: result?.view === undefined ? minutes : result.view.sidebarRefreshMinutes ?? minutes });
|
|
812
|
+
}
|
|
813
|
+
setDraft(String(minutes));
|
|
814
|
+
};
|
|
815
|
+
return h('section', { className: 'dmg-panel', 'data-sidebar-usage': '' }, h('h3', null, t('sidebarPanelTitle')), h('p', { className: 'dmg-hint' }, t('sidebarToggleHint')), h('div', { className: 'dmg-switch-row' }, h('span', null, t('sidebarToggle')), h('button', {
|
|
816
|
+
type: 'button', className: 'dmg-switch', role: 'switch', disabled: saving,
|
|
817
|
+
'aria-checked': enabled, 'aria-label': t('sidebarToggle'), 'data-sidebar-usage-switch': '',
|
|
818
|
+
onClick: () => { void toggle(); },
|
|
819
|
+
}, h('i', null))), h('div', { className: 'dmg-refresh-row' }, h('span', null, t('sidebarRefreshLabel')), h('span', { className: 'dmg-refresh-control' }, h('input', {
|
|
820
|
+
type: 'number', className: 'dmg-refresh-input', min: 0, max: MAX_REFRESH_MINUTES, step: 1,
|
|
821
|
+
value: draft, disabled: saving, 'data-sidebar-refresh': '', 'aria-label': t('sidebarRefreshLabel'),
|
|
822
|
+
onChange: (event) => setDraft(event.target.value),
|
|
823
|
+
onBlur: () => { void commitMinutes(); },
|
|
824
|
+
onKeyDown: (event) => { if (event.key === 'Enter')
|
|
825
|
+
event.currentTarget.blur(); },
|
|
826
|
+
}), h('span', { className: 'dmg-refresh-unit' }, t('sidebarRefreshUnit')))), h('p', { className: 'dmg-hint' }, t('sidebarRefreshHint')), failed ? h('p', { className: 'dmg-error', role: 'alert' }, failed) : null);
|
|
827
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type Api } from './api.js';
|
|
2
|
+
/**
|
|
3
|
+
* Sidebar usage card (`sidebar.footer.action`, owner prop `wide`).
|
|
4
|
+
*
|
|
5
|
+
* Wide sidebar: an accordion. The header row is the only interactive surface
|
|
6
|
+
* (except the refresh button): clicking it toggles the detail, which grows in
|
|
7
|
+
* flow and takes height away from the session list instead of covering it.
|
|
8
|
+
* Collapsed, it shows one weekly row per upstream (at most five) plus a
|
|
9
|
+
* decorative overflow chevron. Collapsed sidebar: one icon that opens the same
|
|
10
|
+
* content as a 320px anchored popover.
|
|
11
|
+
*
|
|
12
|
+
* Reads are event-driven through `sidebar-api` (60s TTL); no timers.
|
|
13
|
+
*/
|
|
14
|
+
export interface SidebarUsageProps {
|
|
15
|
+
api?: Api;
|
|
16
|
+
wide?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare function SidebarUsage({ api, wide }: SidebarUsageProps): import("react").FunctionComponentElement<import("react").FragmentProps> | import("react").DetailedReactHTMLElement<{
|
|
19
|
+
className: string;
|
|
20
|
+
'data-dmg-sidebar': string;
|
|
21
|
+
'data-open': boolean;
|
|
22
|
+
}, HTMLElement> | null;
|