opencode-codebuddy-quota 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,41 @@
1
- {
2
- "models": {
3
- "deepseek-v4-pro": { "provider": "deepseek", "model": "deepseek-v4-pro" },
4
- "deepseek-v4.1-flash": { "provider": "deepseek", "model": "deepseek-v4-flash" },
5
- "glm-5.3-flash": { "provider": "zhipuai", "model": "glm-5.3-flash" },
6
- "glm-5.3-flashx": { "provider": "zhipuai", "model": "glm-5.3-flashx" },
7
- "minimax-m3.1-flash": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
8
- "step-5-preview": { "provider": "stepfun", "model": "step-5-preview" },
9
- "mimo-v2.6-pro": { "provider": "xiaomi", "model": "mimo-v2.6-pro" },
10
- "hy4std": { "provider": "tencent-tokenhub", "model": "hy4" },
11
- "hy4flash-free": { "provider": "tencent-tokenhub", "model": "hy4" },
12
- "hy4flash": { "provider": "tencent-tokenhub", "model": "hy4" },
13
- "hy4free": { "provider": "tencent-tokenhub", "model": "hy4" },
14
- "hy3": { "provider": "tencent-tokenhub", "model": "hy3" },
15
- "hy3-x": { "provider": "tencent-tokenhub", "model": "hy3" },
16
- "space-bunny": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
17
- "hy4-preview": { "provider": "tencent-tokenhub", "model": "hy4-preview" },
18
- "deepseek-v4.1-flash-sg": { "provider": "deepseek", "model": "deepseek-v4-flash" },
19
- "gpt-6-astra": { "provider": "openai", "model": "gpt-6-astra" },
20
- "gpt-6.1-sol": { "provider": "openai", "model": "gpt-6.1-sol" },
21
- "gpt-6-sol": { "provider": "openai", "model": "gpt-6-sol" },
22
- "gpt-6-luna": { "provider": "openai", "model": "gpt-6-luna" },
23
- "gpt-5.6-sol": { "provider": "openai", "model": "gpt-5.6-sol" },
24
- "gpt-5.6-terra": { "provider": "openai", "model": "gpt-5.6-terra" },
25
- "gpt-5.5": { "provider": "openai", "model": "gpt-5.5" },
26
- "gpt-5.4": { "provider": "openai", "model": "gpt-5.4" },
27
- "gpt-5.6-luna": { "provider": "openai", "model": "gpt-5.6-luna" },
28
- "grok-4.7": { "provider": "xai", "model": "grok-4.7" },
29
- "gemini-3.8-flash": { "provider": "google", "model": "gemini-3.8-flash" },
30
- "glm-5.3": { "provider": "zhipuai", "model": "glm-5.3" },
31
- "glm-5.2": { "provider": "zhipuai", "model": "glm-5.2" },
32
- "kimi-k3.1-pro": { "provider": "moonshotai", "model": "kimi-k3.1-pro" },
33
- "kimi-k3": { "provider": "moonshotai", "model": "kimi-k3" },
34
- "kimi-k3.1-pro-highspeed": { "provider": "moonshotai", "model": "kimi-k3.1-pro-highspeed" }
35
- },
36
- "excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
37
- "package_version": "2.0.90"
38
- }
1
+ {
2
+ "models": {
3
+ "deepseek-v4-pro": { "provider": "deepseek", "model": "deepseek-v4-pro" },
4
+ "deepseek-v4.1-flash": { "provider": "deepseek", "model": "deepseek-v4-flash" },
5
+ "glm-5.3-flash": { "provider": "zhipuai", "model": "glm-5.3-flash" },
6
+ "glm-5.3-flashx": { "provider": "zhipuai", "model": "glm-5.3-flashx" },
7
+ "minimax-m3.1-flash": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
8
+ "step-5-preview": { "provider": "stepfun", "model": "step-5-preview" },
9
+ "mimo-v2.6-pro": { "provider": "xiaomi", "model": "mimo-v2.6-pro" },
10
+ "hy4std": { "provider": "tencent-tokenhub", "model": "hy4" },
11
+ "hy4flash-free": { "provider": "tencent-tokenhub", "model": "hy4" },
12
+ "hy4flash": { "provider": "tencent-tokenhub", "model": "hy4" },
13
+ "hy4free": { "provider": "tencent-tokenhub", "model": "hy4" },
14
+ "hy3": { "provider": "tencent-tokenhub", "model": "hy3" },
15
+ "hy3-x": { "provider": "tencent-tokenhub", "model": "hy3" },
16
+ "space-bunny": { "provider": "minimax-cn", "model": "MiniMax-M3.1-Flash" },
17
+ "hy4-preview": { "provider": "tencent-tokenhub", "model": "hy4-preview" },
18
+ "deepseek-v4.1-flash-sg": { "provider": "deepseek", "model": "deepseek-v4-flash" },
19
+ "gpt-6-astra": { "provider": "openai", "model": "gpt-6-astra" },
20
+ "gpt-6.1-sol": { "provider": "openai", "model": "gpt-6.1-sol" },
21
+ "gpt-6-sol": { "provider": "openai", "model": "gpt-6-sol" },
22
+ "gpt-6-luna": { "provider": "openai", "model": "gpt-6-luna" },
23
+ "gpt-5.6-sol": { "provider": "openai", "model": "gpt-5.6-sol" },
24
+ "gpt-5.6-terra": { "provider": "openai", "model": "gpt-5.6-terra" },
25
+ "gpt-5.5": { "provider": "openai", "model": "gpt-5.5" },
26
+ "gpt-5.4": { "provider": "openai", "model": "gpt-5.4" },
27
+ "gpt-5.6-luna": { "provider": "openai", "model": "gpt-5.6-luna" },
28
+ "grok-4.7": { "provider": "xai", "model": "grok-4.7" },
29
+ "gemini-3.8-flash": { "provider": "google", "model": "gemini-3.8-flash" },
30
+ "glm-5.3": { "provider": "zhipuai", "model": "glm-5.3" },
31
+ "glm-5.4": { "provider": "tencent-token-plan", "model": "glm-5.4" },
32
+ "glm-5.2": { "provider": "zhipuai", "model": "glm-5.2" },
33
+ "kimi-k3.1-pro": { "provider": "moonshotai", "model": "kimi-k3.1-pro" },
34
+ "kimi-k3": { "provider": "moonshotai", "model": "kimi-k3" },
35
+ "kimi-k3.1-pro-highspeed": { "provider": "moonshotai", "model": "kimi-k3.1-pro-highspeed" }
36
+ },
37
+ "excluded_models": ["space-bunny", "hy3", "hy3-x", "auto", "max-model"],
38
+ "package_version": "2.0.90",
39
+ "embedding_model": "bge-m3",
40
+ "local_embedding_model": ""
41
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-codebuddy-quota",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "OpenCode plugin: dual-site (CN/INTL) CodeBuddy providers with dynamic JWT and a quota capsule that switches sites",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -36,6 +36,7 @@
36
36
  "homepage": "https://github.com/lscar/opencode-codebuddy-quota#readme",
37
37
  "bugs": "https://github.com/lscar/opencode-codebuddy-quota/issues",
38
38
  "dependencies": {
39
+ "@huggingface/transformers": "^4.3.2",
39
40
  "@opencode/plugin": "2.2.5"
40
41
  },
41
42
  "devDependencies": {
package/rpc.ts CHANGED
@@ -1,92 +1,92 @@
1
- import { Rpc } from "@opencode/plugin/rpc"
2
-
3
- /**
4
- * The RPC contract between this plugin's server part and its GUI part.
5
- *
6
- * Schemas are written as plain JSON Schema on purpose. The GUI bundle may only
7
- * import `@opencode/plugin/rpc`, which does not re-export `effect`, so an
8
- * Effect `Schema` here would not even bundle. JSON Schema also keeps both
9
- * sides' inferred types at `unknown`, which stops the GUI call from growing a
10
- * phantom required argument.
11
- *
12
- * This file must not import anything but `Rpc`: the server part runs it as
13
- * TypeScript directly, and the GUI part bundles it into a window.
14
- */
15
- const nullableString = { type: ["string", "null"] } as const
16
- const nullableNumber = { type: ["number", "null"] } as const
17
-
18
- const siteEnum = { type: "string", enum: ["cn", "intl"] } as const
19
- const siteInfoSchema = {
20
- type: "object",
21
- properties: {
22
- site: siteEnum,
23
- available: { type: "boolean" },
24
- accounts: {
25
- type: "array",
26
- items: {
27
- type: "object",
28
- properties: { id: { type: "string" }, label: { type: "string" } },
29
- required: ["id", "label"],
30
- additionalProperties: false,
31
- },
32
- },
33
- activeId: nullableString,
34
- },
35
- required: ["site", "available", "accounts", "activeId"],
36
- additionalProperties: false,
37
- } as const
38
-
39
- export const CodebuddyQuota = Rpc.define({
40
- id: "codebuddy-quota",
41
- methods: {
42
- read: {
43
- input: {
44
- type: "object",
45
- properties: { site: siteEnum },
46
- additionalProperties: false,
47
- },
48
- output: {
49
- type: "object",
50
- properties: {
51
- // `ok` is true whenever any reading was ever obtained; `stale` then
52
- // says whether the latest attempt to refresh it failed.
53
- ok: { type: "boolean" },
54
- stale: { type: "boolean" },
55
- // The answer came from the server's 30-second cache, so the numbers are
56
- // real but this call did not reach the upstream.
57
- cached: { type: "boolean" },
58
- ageSeconds: nullableNumber,
59
- remaining: nullableNumber,
60
- used: nullableNumber,
61
- total: nullableNumber,
62
- cycleStart: nullableString,
63
- cycleEnd: nullableString,
64
- resetAt: nullableString,
65
- // When the upstream call that produced these numbers succeeded.
66
- fetchedAt: nullableString,
67
- error: nullableString,
68
- // Which site these numbers belong to, and both sites' availability.
69
- site: siteEnum,
70
- sites: { type: "array", items: siteInfoSchema },
71
- },
72
- required: ["ok", "stale", "cached", "site", "sites"],
73
- additionalProperties: false,
74
- },
75
- },
76
- login: {
77
- input: {
78
- type: "object",
79
- properties: { site: siteEnum },
80
- required: ["site"],
81
- additionalProperties: false,
82
- },
83
- output: {
84
- type: "object",
85
- properties: { ok: { type: "boolean" }, error: nullableString },
86
- required: ["ok", "error"],
87
- additionalProperties: false,
88
- },
89
- },
90
- },
91
- events: {},
92
- })
1
+ import { Rpc } from "@opencode/plugin/rpc"
2
+
3
+ /**
4
+ * The RPC contract between this plugin's server part and its GUI part.
5
+ *
6
+ * Schemas are written as plain JSON Schema on purpose. The GUI bundle may only
7
+ * import `@opencode/plugin/rpc`, which does not re-export `effect`, so an
8
+ * Effect `Schema` here would not even bundle. JSON Schema also keeps both
9
+ * sides' inferred types at `unknown`, which stops the GUI call from growing a
10
+ * phantom required argument.
11
+ *
12
+ * This file must not import anything but `Rpc`: the server part runs it as
13
+ * TypeScript directly, and the GUI part bundles it into a window.
14
+ */
15
+ const nullableString = { type: ["string", "null"] } as const
16
+ const nullableNumber = { type: ["number", "null"] } as const
17
+
18
+ const siteEnum = { type: "string", enum: ["cn", "intl"] } as const
19
+ const siteInfoSchema = {
20
+ type: "object",
21
+ properties: {
22
+ site: siteEnum,
23
+ available: { type: "boolean" },
24
+ accounts: {
25
+ type: "array",
26
+ items: {
27
+ type: "object",
28
+ properties: { id: { type: "string" }, label: { type: "string" } },
29
+ required: ["id", "label"],
30
+ additionalProperties: false,
31
+ },
32
+ },
33
+ activeId: nullableString,
34
+ },
35
+ required: ["site", "available", "accounts", "activeId"],
36
+ additionalProperties: false,
37
+ } as const
38
+
39
+ export const CodebuddyQuota = Rpc.define({
40
+ id: "codebuddy-quota",
41
+ methods: {
42
+ read: {
43
+ input: {
44
+ type: "object",
45
+ properties: { site: siteEnum },
46
+ additionalProperties: false,
47
+ },
48
+ output: {
49
+ type: "object",
50
+ properties: {
51
+ // `ok` is true whenever any reading was ever obtained; `stale` then
52
+ // says whether the latest attempt to refresh it failed.
53
+ ok: { type: "boolean" },
54
+ stale: { type: "boolean" },
55
+ // The answer came from the server's 30-second cache, so the numbers are
56
+ // real but this call did not reach the upstream.
57
+ cached: { type: "boolean" },
58
+ ageSeconds: nullableNumber,
59
+ remaining: nullableNumber,
60
+ used: nullableNumber,
61
+ total: nullableNumber,
62
+ cycleStart: nullableString,
63
+ cycleEnd: nullableString,
64
+ resetAt: nullableString,
65
+ // When the upstream call that produced these numbers succeeded.
66
+ fetchedAt: nullableString,
67
+ error: nullableString,
68
+ // Which site these numbers belong to, and both sites' availability.
69
+ site: siteEnum,
70
+ sites: { type: "array", items: siteInfoSchema },
71
+ },
72
+ required: ["ok", "stale", "cached", "site", "sites"],
73
+ additionalProperties: false,
74
+ },
75
+ },
76
+ login: {
77
+ input: {
78
+ type: "object",
79
+ properties: { site: siteEnum },
80
+ required: ["site"],
81
+ additionalProperties: false,
82
+ },
83
+ output: {
84
+ type: "object",
85
+ properties: { ok: { type: "boolean" }, error: nullableString },
86
+ required: ["ok", "error"],
87
+ additionalProperties: false,
88
+ },
89
+ },
90
+ },
91
+ events: {},
92
+ })
package/server.ts CHANGED
@@ -3,11 +3,19 @@ import { Plugin } from "@opencode/plugin"
3
3
  import { CodebuddyQuota } from "./rpc"
4
4
  import type { Site } from "./src/shared"
5
5
  import { fetchCatalog } from "./src/server/catalog"
6
- import { loadConfig, opencodeConfigPath } from "./src/server/config"
6
+ import { loadConfig, opencodeConfigPath, type QuotaConfig } from "./src/server/config"
7
7
  import { writeProvider } from "./src/server/config-writer"
8
+ import { clearLocalEmbedderMemo, createLocalEmbedder, type LocalEmbedding } from "./src/server/embedding-local"
9
+ import { resolveEmbeddingMode } from "./src/server/embedding-mode"
10
+ import { setupGateway } from "./src/server/gateway-setup"
11
+ import { ensureGateway, releaseGateway } from "./src/server/gateway-owner"
12
+ import type { SiteAuth } from "./src/server/login"
8
13
  import { createDedupedLogger } from "./src/server/logger"
9
14
  import { buildModels } from "./src/server/model-info"
15
+ import { warmLocalModel, type PrewarmDeps } from "./src/server/model-prewarm"
16
+ import { createModelsCache, type ModelsListResponse } from "./src/server/models-endpoint"
10
17
  import { readModelsDevCatalog } from "./src/server/models-dev"
18
+ import type { ModelsDevCatalog } from "./src/server/pricing"
11
19
  import { latestTaggedVersion } from "./src/server/package-version"
12
20
  import { createProxy } from "./src/server/proxy"
13
21
  import { createQuotaSource } from "./src/server/quota-source"
@@ -19,6 +27,84 @@ import { fetchUpstream } from "./src/server/upstream"
19
27
  const PROXY_PORT = 7688
20
28
  const UPSTREAM_TIMEOUT_MS = 15_000
21
29
 
30
+ /** Offline inputs the /v2/models list is built from; injected so the seam is testable. */
31
+ export interface ModelsSourceDeps {
32
+ loadConfig: () => QuotaConfig
33
+ readModelsDevCatalog: () => ModelsDevCatalog | null
34
+ getAuth: (site: Site) => SiteAuth | null
35
+ fetchCatalog: typeof fetchCatalog
36
+ buildModels: typeof buildModels
37
+ log: (message: string) => void
38
+ }
39
+
40
+ /**
41
+ * Build the per-site model source for GET /v2/models. Only offline inputs are
42
+ * resolved: a registry/version lookup would add latency and an npm dependency
43
+ * to a request that only needs the mapped model ids (provider writes still do
44
+ * the version lookup through `importDeps`).
45
+ */
46
+ export function createModelsSource(deps: ModelsSourceDeps): (site: Site) => Promise<ModelsListResponse> {
47
+ const cache = createModelsCache(async (site) => {
48
+ const auth = deps.getAuth(site)
49
+ if (!auth) throw new Error(`no account for ${site}`)
50
+ const catalog = await deps.fetchCatalog({ site, auth })
51
+ return deps.buildModels({
52
+ catalog,
53
+ config: deps.loadConfig(),
54
+ modelsDev: deps.readModelsDevCatalog(),
55
+ log: deps.log,
56
+ })
57
+ })
58
+ return (site) => cache.get(site)
59
+ }
60
+
61
+ /** Injected seams so the startup decision can be tested without a real build. */
62
+ export interface StartPrewarmDeps {
63
+ warmLocalModel: (deps: PrewarmDeps) => Promise<LocalEmbedding>
64
+ createLocalEmbedder: (modelId?: string) => LocalEmbedding
65
+ clearLocalEmbedderMemo: () => void
66
+ log: (message: string) => void
67
+ }
68
+
69
+ /**
70
+ * Decide the embedding mode from one loaded config and, in local mode, start a
71
+ * fire-and-forget model warmup. Pure apart from the injected warmup: it never
72
+ * blocks startup, never throws (rejections are logged and swallowed), and on
73
+ * cloud mode touches no local-model code at all. The returned mode is what the
74
+ * proxy must use so routing and warmup agree on the same config.
75
+ */
76
+ export function startPrewarm(
77
+ config: QuotaConfig,
78
+ deps: StartPrewarmDeps,
79
+ ): ReturnType<typeof resolveEmbeddingMode> {
80
+ const mode = resolveEmbeddingMode(config)
81
+ if (mode === "local") {
82
+ void deps
83
+ .warmLocalModel({
84
+ model: config.local_embedding_model,
85
+ build: async () => {
86
+ // Use the SAME id the cache verifier checks, so the pipeline downloads
87
+ // into the directory that is about to be verified.
88
+ const embedder = deps.createLocalEmbedder(config.local_embedding_model)
89
+ // Trigger the real (memoised) pipeline before handing it back.
90
+ await embedder.embed(["ok"])
91
+ return embedder
92
+ },
93
+ // Delete-and-rebuild repair must re-download: drop the memoised pipeline
94
+ // so the next build above starts fresh. The cold build is untouched and
95
+ // still populates the memo shared with proxy requests.
96
+ onCacheRepair: deps.clearLocalEmbedderMemo,
97
+ log: deps.log,
98
+ })
99
+ .catch((error) =>
100
+ deps.log(
101
+ `[codebuddy-quota] local model prewarm failed: ${String((error as Error)?.message ?? error)}`,
102
+ ),
103
+ )
104
+ }
105
+ return mode
106
+ }
107
+
22
108
  export default Plugin.define({
23
109
  id: "codebuddy-quota",
24
110
  async setup(ctx) {
@@ -39,17 +125,6 @@ export default Plugin.define({
39
125
  },
40
126
  })
41
127
 
42
- // Local reverse proxy: providers point here; the proxy injects the current
43
- // site's JWT on each request. Port conflicts are logged and non-fatal to the
44
- // rest of the panel.
45
- const proxy = createProxy({ store, log })
46
- try {
47
- await proxy.start(PROXY_PORT)
48
- log(`local proxy listening on 127.0.0.1:${PROXY_PORT}`)
49
- } catch (error) {
50
- log(`local proxy could not bind ${PROXY_PORT}: ${String((error as Error)?.message ?? error)}`)
51
- }
52
-
53
128
  /**
54
129
  * Model import: for every site that has an account, fetch its cli-whitelist
55
130
  * catalog with that site's JWT and write a dedicated provider block. The
@@ -68,6 +143,25 @@ export default Plugin.define({
68
143
  }
69
144
  }
70
145
 
146
+ // GET /v2/models is generated locally from the same mapped catalog the
147
+ // provider import uses, so the advertised ids match what OpenCode can call.
148
+ const models = createModelsSource({
149
+ loadConfig,
150
+ readModelsDevCatalog,
151
+ getAuth: (site) => store.get(site),
152
+ fetchCatalog,
153
+ buildModels,
154
+ log,
155
+ })
156
+
157
+ // One config read feeds both the warmup decision and proxy routing, so the
158
+ // two can never disagree. startPrewarm fires the warmup asynchronously and
159
+ // swallows its failures; it never blocks startup.
160
+ const config = loadConfig()
161
+ const embeddingMode = startPrewarm(config, {
162
+ warmLocalModel, createLocalEmbedder, clearLocalEmbedderMemo, log,
163
+ })
164
+
71
165
  /** Import one site's models; reused after login so a new account lands in config. */
72
166
  const importSite = async (
73
167
  site: Site,
@@ -124,13 +218,34 @@ export default Plugin.define({
124
218
  log,
125
219
  afterLogin: async (site) => importSite(site, await importDeps()),
126
220
  })
127
- const registration = await ctx.rpc.register(CodebuddyQuota, handlers)
221
+ // Local reverse proxy: providers point here; the proxy injects the current
222
+ // site's JWT on each request. The first plugin instance binds the port; a
223
+ // reload reuses the process-wide server, so there is no dispose/setup
224
+ // listen gap. Port conflicts are logged by the owner and stay non-fatal.
225
+ // The proxy's lazy fallback must target the configured id too, otherwise a
226
+ // request would build a different model from the one prewarm verified.
227
+ let registration: { dispose(): void } | null = null
228
+ const gw = await setupGateway({
229
+ ensureGateway,
230
+ releaseGateway,
231
+ createServer: () =>
232
+ createProxy({
233
+ store, log, models, embeddingMode,
234
+ localEmbeddingModel: config.local_embedding_model,
235
+ }),
236
+ register: async () => {
237
+ const result = await ctx.rpc.register(CodebuddyQuota, handlers)
238
+ registration = result
239
+ return result
240
+ },
241
+ log,
242
+ })
128
243
 
129
244
  return () => {
130
- registration.dispose()
131
- void proxy.close().catch((error) =>
132
- log(`proxy close failed: ${String((error as Error)?.message ?? error)}`),
133
- )
245
+ registration?.dispose()
246
+ // Only drop our reference; the owner closes the shared server after the
247
+ // last holder is gone and its grace window has elapsed.
248
+ void gw.dispose()
134
249
  }
135
250
  },
136
251
  })
@@ -1,81 +1,81 @@
1
- import type { JSX } from "solid-js"
2
-
3
- export interface BatteryProps {
4
- /** Remaining share, 0..100, already rounded. `null` renders an empty track. */
5
- value: number | null
6
- color: string
7
- /** Stale data: dim the whole capsule and hatch the fill. */
8
- dim?: boolean
9
- }
10
-
11
- const STALE_HATCH = "repeating-linear-gradient(45deg, rgba(0,0,0,.22) 0 3px, transparent 3px 6px)"
12
- const TRACK = "rgba(127, 137, 156, 0.35)"
13
- const TRACK_EMPTY = "rgba(127, 137, 156, 0.22)"
14
-
15
- const clampPct = (value: number | null) =>
16
- value === null ? 0 : Math.max(0, Math.min(100, value))
17
-
18
- /**
19
- * An iOS-style capacity pill: no stroke, one solid rounded track, and the charge
20
- * drawn as a solid block of the same radius sitting flush inside it. The two share
21
- * an edge, so there is no gap to misalign at the rounded ends — the border/arc
22
- * mismatch that a stroke plus an inset fill always produces.
23
- *
24
- * Every style is a getter, not a snapshot, so a live `value`/`color` repaints in
25
- * place instead of freezing at the first paint.
26
- */
27
- export function Battery(props: BatteryProps): JSX.Element {
28
- const empty = () => props.value === null
29
-
30
- const shell = (): JSX.CSSProperties => ({
31
- position: "relative",
32
- display: "inline-flex",
33
- "align-items": "center",
34
- "justify-content": "center",
35
- width: "52px",
36
- height: "18px",
37
- "border-radius": "6px",
38
- // No border: the track itself is the shape, which is what lets the fill meet
39
- // the outline without a seam.
40
- background: empty() ? TRACK_EMPTY : TRACK,
41
- opacity: props.dim ? "0.72" : "1",
42
- "box-sizing": "border-box",
43
- "vertical-align": "middle",
44
- overflow: "hidden",
45
- })
46
-
47
- const fill = (): JSX.CSSProperties => ({
48
- position: "absolute",
49
- left: "0",
50
- top: "0",
51
- height: "100%",
52
- width: `${clampPct(props.value)}%`,
53
- // Same radius as the track, and clipped by its overflow, so the leading edge
54
- // is a perfect half-round and the trailing edge is a crisp vertical cut.
55
- "border-radius": "6px",
56
- background: props.color,
57
- "background-image": props.dim ? STALE_HATCH : undefined,
58
- transition: "width 200ms ease-out, background 200ms ease-out",
59
- })
60
-
61
- const text = (): JSX.CSSProperties => ({
62
- position: "relative",
63
- "font-size": "10px",
64
- "font-weight": "700",
65
- "font-variant-numeric": "tabular-nums",
66
- "line-height": "1",
67
- "letter-spacing": "-0.2px",
68
- // The fill is saturated, so a dark label reads on it; over the bare track the
69
- // label needs to be light instead.
70
- color: empty() ? "#8b90a0" : "#0d1117",
71
- "pointer-events": "none",
72
- "text-shadow": empty() ? "none" : "0 0 2px rgba(0,0,0,.18)",
73
- })
74
-
75
- return (
76
- <span style={shell()}>
77
- <span style={fill()} />
78
- <span style={text()}>{empty() ? "--" : String(props.value)}</span>
79
- </span>
80
- )
81
- }
1
+ import type { JSX } from "solid-js"
2
+
3
+ export interface BatteryProps {
4
+ /** Remaining share, 0..100, already rounded. `null` renders an empty track. */
5
+ value: number | null
6
+ color: string
7
+ /** Stale data: dim the whole capsule and hatch the fill. */
8
+ dim?: boolean
9
+ }
10
+
11
+ const STALE_HATCH = "repeating-linear-gradient(45deg, rgba(0,0,0,.22) 0 3px, transparent 3px 6px)"
12
+ const TRACK = "rgba(127, 137, 156, 0.35)"
13
+ const TRACK_EMPTY = "rgba(127, 137, 156, 0.22)"
14
+
15
+ const clampPct = (value: number | null) =>
16
+ value === null ? 0 : Math.max(0, Math.min(100, value))
17
+
18
+ /**
19
+ * An iOS-style capacity pill: no stroke, one solid rounded track, and the charge
20
+ * drawn as a solid block of the same radius sitting flush inside it. The two share
21
+ * an edge, so there is no gap to misalign at the rounded ends — the border/arc
22
+ * mismatch that a stroke plus an inset fill always produces.
23
+ *
24
+ * Every style is a getter, not a snapshot, so a live `value`/`color` repaints in
25
+ * place instead of freezing at the first paint.
26
+ */
27
+ export function Battery(props: BatteryProps): JSX.Element {
28
+ const empty = () => props.value === null
29
+
30
+ const shell = (): JSX.CSSProperties => ({
31
+ position: "relative",
32
+ display: "inline-flex",
33
+ "align-items": "center",
34
+ "justify-content": "center",
35
+ width: "52px",
36
+ height: "18px",
37
+ "border-radius": "6px",
38
+ // No border: the track itself is the shape, which is what lets the fill meet
39
+ // the outline without a seam.
40
+ background: empty() ? TRACK_EMPTY : TRACK,
41
+ opacity: props.dim ? "0.72" : "1",
42
+ "box-sizing": "border-box",
43
+ "vertical-align": "middle",
44
+ overflow: "hidden",
45
+ })
46
+
47
+ const fill = (): JSX.CSSProperties => ({
48
+ position: "absolute",
49
+ left: "0",
50
+ top: "0",
51
+ height: "100%",
52
+ width: `${clampPct(props.value)}%`,
53
+ // Same radius as the track, and clipped by its overflow, so the leading edge
54
+ // is a perfect half-round and the trailing edge is a crisp vertical cut.
55
+ "border-radius": "6px",
56
+ background: props.color,
57
+ "background-image": props.dim ? STALE_HATCH : undefined,
58
+ transition: "width 200ms ease-out, background 200ms ease-out",
59
+ })
60
+
61
+ const text = (): JSX.CSSProperties => ({
62
+ position: "relative",
63
+ "font-size": "10px",
64
+ "font-weight": "700",
65
+ "font-variant-numeric": "tabular-nums",
66
+ "line-height": "1",
67
+ "letter-spacing": "-0.2px",
68
+ // The fill is saturated, so a dark label reads on it; over the bare track the
69
+ // label needs to be light instead.
70
+ color: empty() ? "#8b90a0" : "#0d1117",
71
+ "pointer-events": "none",
72
+ "text-shadow": empty() ? "none" : "0 0 2px rgba(0,0,0,.18)",
73
+ })
74
+
75
+ return (
76
+ <span style={shell()}>
77
+ <span style={fill()} />
78
+ <span style={text()}>{empty() ? "--" : String(props.value)}</span>
79
+ </span>
80
+ )
81
+ }