opencode-codebuddy-quota 0.1.0 → 0.1.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/src/gui/store.ts CHANGED
@@ -1,181 +1,181 @@
1
- import type { Site } from "../shared"
2
- import { normalizeQuota, type Quota } from "./quota"
3
-
4
- /** The shape `ctx.client.rpc(CodebuddyQuota)` satisfies; kept loose so tests can fake it. */
5
- export interface QuotaClient {
6
- read(input: { site?: Site }): Promise<unknown>
7
- login?(input: { site: Site }): Promise<unknown>
8
- }
9
-
10
- export interface QuotaStore {
11
- read(): Quota
12
- subscribe(listener: (q: Quota) => void): () => void
13
- refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
14
- login(site: Site): Promise<boolean>
15
- start(): () => void
16
- }
17
-
18
- /** Background safety net only; the capsule refreshes on hover and the dialog on open. */
19
- const REFRESH_MS = 30 * 60_000
20
- /** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
21
- export const HOVER_MIN_AGE_MS = 60_000
22
- const STALE_AFTER_RESUME_MS = 2 * 60_000
23
-
24
- const idle = (status: "error", error: string | null): Quota => ({
25
- status,
26
- site: "cn",
27
- sites: [
28
- { site: "cn", available: false, accounts: [], activeId: null },
29
- { site: "intl", available: false, accounts: [], activeId: null },
30
- ],
31
- remaining: null,
32
- used: null,
33
- total: null,
34
- usedPct: null,
35
- timePct: null,
36
- diff: null,
37
- cycleStart: null,
38
- cycleEnd: null,
39
- resetAt: null,
40
- fetchedAt: null,
41
- ageSeconds: null,
42
- error,
43
- })
44
-
45
- /**
46
- * One read of the quota over the plugin RPC.
47
- *
48
- * Both a rejection (`RPC is unavailable`, the server restarting) and an explicit
49
- * `ok: false` mean "no answer", but they keep the previous numbers differently:
50
- * a rejection keeps them and marks them stale, because the quota itself is
51
- * probably fine; `ok: false` is the server saying it has nothing, so the old
52
- * numbers are dropped rather than dressed up as merely stale.
53
- */
54
- export async function readQuota(opts: {
55
- client: QuotaClient
56
- fallback?: Quota | null
57
- now?: number
58
- site?: Site
59
- }): Promise<Quota> {
60
- const now = opts.now ?? Date.now()
61
- let body: unknown
62
- try {
63
- body = await opts.client.read(opts.site ? { site: opts.site } : {})
64
- } catch (error) {
65
- const message = String((error as Error)?.message ?? error)
66
- return opts.fallback
67
- ? { ...opts.fallback, status: "stale", error: message }
68
- : idle("error", message)
69
- }
70
- // An explicit "unavailable" must never be dressed up as a stale number, so
71
- // the fallback is deliberately not offered here.
72
- return normalizeQuota(body, { now })
73
- }
74
-
75
- export function createQuotaStore(client: () => QuotaClient): QuotaStore {
76
- let current: Quota = normalizeQuota(null, { now: Date.now() })
77
- let lastAttempt = 0
78
- let inflight: Promise<void> | null = null
79
- let pendingSite: Site | null = null
80
- let started = false
81
- const listeners = new Set<(q: Quota) => void>()
82
-
83
- const emit = (next: Quota) => {
84
- current = next
85
- for (const listener of listeners) listener(next)
86
- }
87
-
88
- /**
89
- * `force` skips every GUI-side age check (the dialog's refresh button); the
90
- * server's own 30-second cache still applies behind it.
91
- * `maxAgeMs` refreshes only when the last attempt is older than that, which is
92
- * how hover keeps working without spamming on every pointer move.
93
- */
94
- const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
95
- // One request at a time: without this, a forced refresh racing a hover refresh
96
- // can land out of order and let the older reading win.
97
- if (inflight) {
98
- // Compare against the IN-FLIGHT site, not current.site (which is the last
99
- // emitted one and is frozen while a read runs). Last explicit request wins.
100
- if (options.site) pendingSite = options.site
101
- return inflight
102
- }
103
- const now = Date.now()
104
- const maxAge = options.force ? 0 : (options.maxAgeMs ?? REFRESH_MS)
105
- if (now - lastAttempt < maxAge) return
106
- lastAttempt = now
107
-
108
- inflight = (async () => {
109
- try {
110
- // Only a reading that actually carried data is worth falling back to.
111
- const usable = current.remaining !== null ? current : null
112
- let next: Quota
113
- try {
114
- // Read the client per request: it changes when the server restarts.
115
- next = await readQuota({ client: client(), fallback: usable, site: options.site })
116
- } catch (error) {
117
- // `client()` itself can throw when the server client is unavailable,
118
- // which is the same situation as a rejected RPC call.
119
- const message = String((error as Error)?.message ?? error)
120
- next = usable ? { ...usable, status: "stale", error: message } : idle("error", message)
121
- }
122
- emit(next)
123
- } finally {
124
- inflight = null
125
- const queued = pendingSite
126
- pendingSite = null
127
- // Re-run only if the last request was for a different site than the one
128
- // that just completed; otherwise it is already served.
129
- if (queued && queued !== current.site) void refresh({ force: true, site: queued })
130
- }
131
- })()
132
-
133
- return inflight
134
- }
135
-
136
- const start = () => {
137
- if (started) return () => {}
138
- started = true
139
- const hasDocument = typeof globalThis.document !== "undefined"
140
- const tick = () => {
141
- // A hidden window must not poll; on return, refresh only if the data aged.
142
- if (hasDocument && globalThis.document.hidden) return
143
- void refresh()
144
- }
145
- const onVisible = () => {
146
- if (globalThis.document.hidden) return
147
- if (Date.now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
148
- }
149
- const timer = setInterval(tick, REFRESH_MS)
150
- if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
151
- // The one place the capsule gets its first number without any interaction.
152
- void refresh({ force: true })
153
- return () => {
154
- clearInterval(timer)
155
- if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
156
- started = false
157
- }
158
- }
159
-
160
- return {
161
- read: () => current,
162
- subscribe(listener) {
163
- listeners.add(listener)
164
- return () => listeners.delete(listener)
165
- },
166
- refresh,
167
- async login(site) {
168
- try {
169
- const loginFn = client().login
170
- if (!loginFn) return false
171
- const result = (await loginFn({ site })) as { ok?: boolean } | null
172
- const ok = result?.ok === true
173
- if (ok) await refresh({ force: true, site })
174
- return ok
175
- } catch {
176
- return false
177
- }
178
- },
179
- start,
180
- }
181
- }
1
+ import type { Site } from "../shared"
2
+ import { normalizeQuota, type Quota } from "./quota"
3
+
4
+ /** The shape `ctx.client.rpc(CodebuddyQuota)` satisfies; kept loose so tests can fake it. */
5
+ export interface QuotaClient {
6
+ read(input: { site?: Site }): Promise<unknown>
7
+ login?(input: { site: Site }): Promise<unknown>
8
+ }
9
+
10
+ export interface QuotaStore {
11
+ read(): Quota
12
+ subscribe(listener: (q: Quota) => void): () => void
13
+ refresh(options?: { force?: boolean; maxAgeMs?: number; site?: Site }): Promise<void>
14
+ login(site: Site): Promise<boolean>
15
+ start(): () => void
16
+ }
17
+
18
+ /** Background safety net only; the capsule refreshes on hover and the dialog on open. */
19
+ const REFRESH_MS = 30 * 60_000
20
+ /** Hover refreshes only when the reading is older than this, so mouse traffic cannot spam. */
21
+ export const HOVER_MIN_AGE_MS = 60_000
22
+ const STALE_AFTER_RESUME_MS = 2 * 60_000
23
+
24
+ const idle = (status: "error", error: string | null): Quota => ({
25
+ status,
26
+ site: "cn",
27
+ sites: [
28
+ { site: "cn", available: false, accounts: [], activeId: null },
29
+ { site: "intl", available: false, accounts: [], activeId: null },
30
+ ],
31
+ remaining: null,
32
+ used: null,
33
+ total: null,
34
+ usedPct: null,
35
+ timePct: null,
36
+ diff: null,
37
+ cycleStart: null,
38
+ cycleEnd: null,
39
+ resetAt: null,
40
+ fetchedAt: null,
41
+ ageSeconds: null,
42
+ error,
43
+ })
44
+
45
+ /**
46
+ * One read of the quota over the plugin RPC.
47
+ *
48
+ * Both a rejection (`RPC is unavailable`, the server restarting) and an explicit
49
+ * `ok: false` mean "no answer", but they keep the previous numbers differently:
50
+ * a rejection keeps them and marks them stale, because the quota itself is
51
+ * probably fine; `ok: false` is the server saying it has nothing, so the old
52
+ * numbers are dropped rather than dressed up as merely stale.
53
+ */
54
+ export async function readQuota(opts: {
55
+ client: QuotaClient
56
+ fallback?: Quota | null
57
+ now?: number
58
+ site?: Site
59
+ }): Promise<Quota> {
60
+ const now = opts.now ?? Date.now()
61
+ let body: unknown
62
+ try {
63
+ body = await opts.client.read(opts.site ? { site: opts.site } : {})
64
+ } catch (error) {
65
+ const message = String((error as Error)?.message ?? error)
66
+ return opts.fallback
67
+ ? { ...opts.fallback, status: "stale", error: message }
68
+ : idle("error", message)
69
+ }
70
+ // An explicit "unavailable" must never be dressed up as a stale number, so
71
+ // the fallback is deliberately not offered here.
72
+ return normalizeQuota(body, { now })
73
+ }
74
+
75
+ export function createQuotaStore(client: () => QuotaClient): QuotaStore {
76
+ let current: Quota = normalizeQuota(null, { now: Date.now() })
77
+ let lastAttempt = 0
78
+ let inflight: Promise<void> | null = null
79
+ let pendingSite: Site | null = null
80
+ let started = false
81
+ const listeners = new Set<(q: Quota) => void>()
82
+
83
+ const emit = (next: Quota) => {
84
+ current = next
85
+ for (const listener of listeners) listener(next)
86
+ }
87
+
88
+ /**
89
+ * `force` skips every GUI-side age check (the dialog's refresh button); the
90
+ * server's own 30-second cache still applies behind it.
91
+ * `maxAgeMs` refreshes only when the last attempt is older than that, which is
92
+ * how hover keeps working without spamming on every pointer move.
93
+ */
94
+ const refresh = async (options: { force?: boolean; maxAgeMs?: number; site?: Site } = {}) => {
95
+ // One request at a time: without this, a forced refresh racing a hover refresh
96
+ // can land out of order and let the older reading win.
97
+ if (inflight) {
98
+ // Compare against the IN-FLIGHT site, not current.site (which is the last
99
+ // emitted one and is frozen while a read runs). Last explicit request wins.
100
+ if (options.site) pendingSite = options.site
101
+ return inflight
102
+ }
103
+ const now = Date.now()
104
+ const maxAge = options.force ? 0 : (options.maxAgeMs ?? REFRESH_MS)
105
+ if (now - lastAttempt < maxAge) return
106
+ lastAttempt = now
107
+
108
+ inflight = (async () => {
109
+ try {
110
+ // Only a reading that actually carried data is worth falling back to.
111
+ const usable = current.remaining !== null ? current : null
112
+ let next: Quota
113
+ try {
114
+ // Read the client per request: it changes when the server restarts.
115
+ next = await readQuota({ client: client(), fallback: usable, site: options.site })
116
+ } catch (error) {
117
+ // `client()` itself can throw when the server client is unavailable,
118
+ // which is the same situation as a rejected RPC call.
119
+ const message = String((error as Error)?.message ?? error)
120
+ next = usable ? { ...usable, status: "stale", error: message } : idle("error", message)
121
+ }
122
+ emit(next)
123
+ } finally {
124
+ inflight = null
125
+ const queued = pendingSite
126
+ pendingSite = null
127
+ // Re-run only if the last request was for a different site than the one
128
+ // that just completed; otherwise it is already served.
129
+ if (queued && queued !== current.site) void refresh({ force: true, site: queued })
130
+ }
131
+ })()
132
+
133
+ return inflight
134
+ }
135
+
136
+ const start = () => {
137
+ if (started) return () => {}
138
+ started = true
139
+ const hasDocument = typeof globalThis.document !== "undefined"
140
+ const tick = () => {
141
+ // A hidden window must not poll; on return, refresh only if the data aged.
142
+ if (hasDocument && globalThis.document.hidden) return
143
+ void refresh()
144
+ }
145
+ const onVisible = () => {
146
+ if (globalThis.document.hidden) return
147
+ if (Date.now() - lastAttempt >= STALE_AFTER_RESUME_MS) void refresh()
148
+ }
149
+ const timer = setInterval(tick, REFRESH_MS)
150
+ if (hasDocument) globalThis.document.addEventListener("visibilitychange", onVisible)
151
+ // The one place the capsule gets its first number without any interaction.
152
+ void refresh({ force: true })
153
+ return () => {
154
+ clearInterval(timer)
155
+ if (hasDocument) globalThis.document.removeEventListener("visibilitychange", onVisible)
156
+ started = false
157
+ }
158
+ }
159
+
160
+ return {
161
+ read: () => current,
162
+ subscribe(listener) {
163
+ listeners.add(listener)
164
+ return () => listeners.delete(listener)
165
+ },
166
+ refresh,
167
+ async login(site) {
168
+ try {
169
+ const loginFn = client().login
170
+ if (!loginFn) return false
171
+ const result = (await loginFn({ site })) as { ok?: boolean } | null
172
+ const ok = result?.ok === true
173
+ if (ok) await refresh({ force: true, site })
174
+ return ok
175
+ } catch {
176
+ return false
177
+ }
178
+ },
179
+ start,
180
+ }
181
+ }
package/src/gui.tsx CHANGED
@@ -1,111 +1,111 @@
1
- import { Plugin, Slot, Style } from "@opencode/plugin/gui"
2
- import { createSignal, onCleanup } from "solid-js"
3
- import { CodebuddyQuota } from "../rpc"
4
- import { Battery } from "./gui/battery"
5
- import { QuotaDialog } from "./gui/dialog"
6
- import { formatPct, paceColor } from "./gui/pace"
7
- import { remainingPercent, remainingShare, type Quota } from "./gui/quota"
8
- import { createQuotaStore, HOVER_MIN_AGE_MS } from "./gui/store"
9
- import dialogCss from "./gui/dialog.css?inline"
10
-
11
- export default Plugin.define({
12
- setup(ctx) {
13
- // Scoped dialog styles. currentColor/color-mix follow the active OpenCode
14
- // theme, so the dialog stays in step with light/dark and custom themes.
15
- ctx.add(Style, dialogCss)
16
-
17
- // The client is read per request, not captured here: it changes when the
18
- // OpenCode server restarts, and a captured one would keep failing.
19
- const store = createQuotaStore(() => ctx.client.rpc(CodebuddyQuota))
20
- const [quota, setQuota] = createSignal<Quota>(store.read())
21
- onCleanup(store.subscribe(setQuota))
22
- onCleanup(store.start())
23
-
24
- const openDetails = () => {
25
- // Refreshing here as well as on the dialog's mount would fire two requests
26
- // for one click, so the dialog owns that refresh.
27
- ctx.dialogs.open((dialog) => {
28
- // The subscription lives in its own component so its owner is the dialog's
29
- // render, not whatever scope `dialogs.open` happens to run in.
30
- const Live = () => {
31
- const [live, setLive] = createSignal<Quota>(store.read())
32
- onCleanup(store.subscribe(setLive))
33
- return (
34
- <QuotaDialog
35
- quota={live()}
36
- ui={ctx.ui}
37
- onRefresh={(site) => store.refresh({ force: true, site })}
38
- onLogin={(site) => store.login(site)}
39
- close={dialog.close}
40
- />
41
- )
42
- }
43
- return <Live />
44
- })
45
- }
46
-
47
- // Hover is the main way this refreshes: the background timer is only a safety
48
- // net, so pointing at the capsule pulls a reading that is older than a minute.
49
- const onHover = () => {
50
- void store.refresh({ maxAgeMs: HOVER_MIN_AGE_MS, site: store.read().site })
51
- }
52
- const SITE_LABEL = { cn: "国内站", intl: "国际站" } as const
53
- // Any site needing login shows an amber dot outside the capsule. Read the
54
- // quota signal, not store.read(): the latter is a plain variable that Solid
55
- // never tracks, so the dot froze on the first "needs login" verdict.
56
- const needsLogin = () => quota().sites.some((s) => !s.available)
57
-
58
- // The capsule lives on the session header row — the only surface the
59
- // side-tabs layout leaves a plugin. See the design notes for why.
60
- //
61
- // Every value is read inside the JSX, not in the render body: a signal read
62
- // outside a tracked expression is evaluated once and then frozen, which is
63
- // why the capsule used to stay on "--" while the dialog showed live numbers.
64
- ctx.add(Slot, {
65
- at: "session.header",
66
- order: 50,
67
- render: () => (
68
- <button
69
- type="button"
70
- title={
71
- remainingShare(quota()) === null
72
- ? `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:暂不可用(点击查看/登录)`
73
- : `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:剩余 ${formatPct(remainingShare(quota()))}`
74
- }
75
- onMouseEnter={onHover}
76
- onFocus={onHover}
77
- onClick={openDetails}
78
- style={{
79
- position: "relative",
80
- background: "transparent",
81
- border: "none",
82
- padding: "2px 6px 2px 0",
83
- "margin-left": "auto",
84
- cursor: "pointer",
85
- "line-height": "0",
86
- }}
87
- >
88
- <Battery
89
- value={remainingPercent(quota())}
90
- color={paceColor(quota())}
91
- dim={quota().status === "stale"}
92
- />
93
- {needsLogin() && (
94
- <span
95
- style={{
96
- position: "absolute",
97
- top: "0",
98
- right: "0",
99
- width: "9px",
100
- height: "9px",
101
- "border-radius": "50%",
102
- background: "#ffb84d",
103
- border: "1.5px solid transparent",
104
- }}
105
- />
106
- )}
107
- </button>
108
- ),
109
- })
110
- },
111
- })
1
+ import { Plugin, Slot, Style } from "@opencode/plugin/gui"
2
+ import { createSignal, onCleanup } from "solid-js"
3
+ import { CodebuddyQuota } from "../rpc"
4
+ import { Battery } from "./gui/battery"
5
+ import { QuotaDialog } from "./gui/dialog"
6
+ import { formatPct, paceColor } from "./gui/pace"
7
+ import { remainingPercent, remainingShare, type Quota } from "./gui/quota"
8
+ import { createQuotaStore, HOVER_MIN_AGE_MS } from "./gui/store"
9
+ import dialogCss from "./gui/dialog.css?inline"
10
+
11
+ export default Plugin.define({
12
+ setup(ctx) {
13
+ // Scoped dialog styles. currentColor/color-mix follow the active OpenCode
14
+ // theme, so the dialog stays in step with light/dark and custom themes.
15
+ ctx.add(Style, dialogCss)
16
+
17
+ // The client is read per request, not captured here: it changes when the
18
+ // OpenCode server restarts, and a captured one would keep failing.
19
+ const store = createQuotaStore(() => ctx.client.rpc(CodebuddyQuota))
20
+ const [quota, setQuota] = createSignal<Quota>(store.read())
21
+ onCleanup(store.subscribe(setQuota))
22
+ onCleanup(store.start())
23
+
24
+ const openDetails = () => {
25
+ // Refreshing here as well as on the dialog's mount would fire two requests
26
+ // for one click, so the dialog owns that refresh.
27
+ ctx.dialogs.open((dialog) => {
28
+ // The subscription lives in its own component so its owner is the dialog's
29
+ // render, not whatever scope `dialogs.open` happens to run in.
30
+ const Live = () => {
31
+ const [live, setLive] = createSignal<Quota>(store.read())
32
+ onCleanup(store.subscribe(setLive))
33
+ return (
34
+ <QuotaDialog
35
+ quota={live()}
36
+ ui={ctx.ui}
37
+ onRefresh={(site) => store.refresh({ force: true, site })}
38
+ onLogin={(site) => store.login(site)}
39
+ close={dialog.close}
40
+ />
41
+ )
42
+ }
43
+ return <Live />
44
+ })
45
+ }
46
+
47
+ // Hover is the main way this refreshes: the background timer is only a safety
48
+ // net, so pointing at the capsule pulls a reading that is older than a minute.
49
+ const onHover = () => {
50
+ void store.refresh({ maxAgeMs: HOVER_MIN_AGE_MS, site: store.read().site })
51
+ }
52
+ const SITE_LABEL = { cn: "国内站", intl: "国际站" } as const
53
+ // Any site needing login shows an amber dot outside the capsule. Read the
54
+ // quota signal, not store.read(): the latter is a plain variable that Solid
55
+ // never tracks, so the dot froze on the first "needs login" verdict.
56
+ const needsLogin = () => quota().sites.some((s) => !s.available)
57
+
58
+ // The capsule lives on the session header row — the only surface the
59
+ // side-tabs layout leaves a plugin. See the design notes for why.
60
+ //
61
+ // Every value is read inside the JSX, not in the render body: a signal read
62
+ // outside a tracked expression is evaluated once and then frozen, which is
63
+ // why the capsule used to stay on "--" while the dialog showed live numbers.
64
+ ctx.add(Slot, {
65
+ at: "session.header",
66
+ order: 50,
67
+ render: () => (
68
+ <button
69
+ type="button"
70
+ title={
71
+ remainingShare(quota()) === null
72
+ ? `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:暂不可用(点击查看/登录)`
73
+ : `CodeBuddy 额度 · ${SITE_LABEL[quota().site]}:剩余 ${formatPct(remainingShare(quota()))}`
74
+ }
75
+ onMouseEnter={onHover}
76
+ onFocus={onHover}
77
+ onClick={openDetails}
78
+ style={{
79
+ position: "relative",
80
+ background: "transparent",
81
+ border: "none",
82
+ padding: "2px 6px 2px 0",
83
+ "margin-left": "auto",
84
+ cursor: "pointer",
85
+ "line-height": "0",
86
+ }}
87
+ >
88
+ <Battery
89
+ value={remainingPercent(quota())}
90
+ color={paceColor(quota())}
91
+ dim={quota().status === "stale"}
92
+ />
93
+ {needsLogin() && (
94
+ <span
95
+ style={{
96
+ position: "absolute",
97
+ top: "0",
98
+ right: "0",
99
+ width: "9px",
100
+ height: "9px",
101
+ "border-radius": "50%",
102
+ background: "#ffb84d",
103
+ border: "1.5px solid transparent",
104
+ }}
105
+ />
106
+ )}
107
+ </button>
108
+ ),
109
+ })
110
+ },
111
+ })