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/README.md CHANGED
@@ -76,6 +76,7 @@ bun run build:gui # 构建桌面端 GUI(dist/gui-experimental.cjs)
76
76
  - 每站本期至多一个账号;数据结构预留了多账号,但本期不提供切换 UI。
77
77
  - 本地代理是 "confused deputy":本机任意进程都能借它用 JWT 调上游,接受此风险。
78
78
  - 模型倍率名称来自上游 `credits` 字段;上游未声明时倍率标签会省略。
79
+ - 7688 网关在同进程的多个 workspace 间共享,且沿用**首个绑定实例**的凭证与配置(store / models / embeddingMode)。因此插件重载后在 GUI 里重新登录或改嵌入配置,代理仍用首实例的旧值;若上游返回 401/403,日志会提示「重启 OpenCode 或重新登录」以刷新凭证。这是单监听实例设计的已知取舍。
79
80
 
80
81
  ## License
81
82
 
@@ -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.3",
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
@@ -1,13 +1,21 @@
1
1
  import { existsSync, writeFileSync } from "node:fs"
2
2
  import { Plugin } from "@opencode/plugin"
3
3
  import { CodebuddyQuota } from "./rpc"
4
- import type { Site } from "./src/shared"
4
+ import { PROXY_PORT, 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"
@@ -16,9 +24,86 @@ import { anySignal, timeoutSignal } from "./src/server/signal"
16
24
  import { createTokenStore } from "./src/server/token-store"
17
25
  import { fetchUpstream } from "./src/server/upstream"
18
26
 
19
- const PROXY_PORT = 7688
20
27
  const UPSTREAM_TIMEOUT_MS = 15_000
21
28
 
29
+ /** Offline inputs the /v2/models list is built from; injected so the seam is testable. */
30
+ export interface ModelsSourceDeps {
31
+ loadConfig: () => QuotaConfig
32
+ readModelsDevCatalog: () => ModelsDevCatalog | null
33
+ getAuth: (site: Site) => SiteAuth | null
34
+ fetchCatalog: typeof fetchCatalog
35
+ buildModels: typeof buildModels
36
+ log: (message: string) => void
37
+ }
38
+
39
+ /**
40
+ * Build the per-site model source for GET /v2/models. Only offline inputs are
41
+ * resolved: a registry/version lookup would add latency and an npm dependency
42
+ * to a request that only needs the mapped model ids (provider writes still do
43
+ * the version lookup through `importDeps`).
44
+ */
45
+ export function createModelsSource(deps: ModelsSourceDeps): (site: Site) => Promise<ModelsListResponse> {
46
+ const cache = createModelsCache(async (site) => {
47
+ const auth = deps.getAuth(site)
48
+ if (!auth) throw new Error(`no account for ${site}`)
49
+ const catalog = await deps.fetchCatalog({ site, auth })
50
+ return deps.buildModels({
51
+ catalog,
52
+ config: deps.loadConfig(),
53
+ modelsDev: deps.readModelsDevCatalog(),
54
+ log: deps.log,
55
+ })
56
+ })
57
+ return (site) => cache.get(site)
58
+ }
59
+
60
+ /** Injected seams so the startup decision can be tested without a real build. */
61
+ export interface StartPrewarmDeps {
62
+ warmLocalModel: (deps: PrewarmDeps) => Promise<LocalEmbedding>
63
+ createLocalEmbedder: (modelId?: string) => LocalEmbedding
64
+ clearLocalEmbedderMemo: () => void
65
+ log: (message: string) => void
66
+ }
67
+
68
+ /**
69
+ * Decide the embedding mode from one loaded config and, in local mode, start a
70
+ * fire-and-forget model warmup. Pure apart from the injected warmup: it never
71
+ * blocks startup, never throws (rejections are logged and swallowed), and on
72
+ * cloud mode touches no local-model code at all. The returned mode is what the
73
+ * proxy must use so routing and warmup agree on the same config.
74
+ */
75
+ export function startPrewarm(
76
+ config: QuotaConfig,
77
+ deps: StartPrewarmDeps,
78
+ ): ReturnType<typeof resolveEmbeddingMode> {
79
+ const mode = resolveEmbeddingMode(config)
80
+ if (mode === "local") {
81
+ void deps
82
+ .warmLocalModel({
83
+ model: config.local_embedding_model,
84
+ build: async () => {
85
+ // Use the SAME id the cache verifier checks, so the pipeline downloads
86
+ // into the directory that is about to be verified.
87
+ const embedder = deps.createLocalEmbedder(config.local_embedding_model)
88
+ // Trigger the real (memoised) pipeline before handing it back.
89
+ await embedder.embed(["ok"])
90
+ return embedder
91
+ },
92
+ // Delete-and-rebuild repair must re-download: drop the memoised pipeline
93
+ // so the next build above starts fresh. The cold build is untouched and
94
+ // still populates the memo shared with proxy requests.
95
+ onCacheRepair: deps.clearLocalEmbedderMemo,
96
+ log: deps.log,
97
+ })
98
+ .catch((error) =>
99
+ deps.log(
100
+ `[codebuddy-quota] local model prewarm failed: ${String((error as Error)?.message ?? error)}`,
101
+ ),
102
+ )
103
+ }
104
+ return mode
105
+ }
106
+
22
107
  export default Plugin.define({
23
108
  id: "codebuddy-quota",
24
109
  async setup(ctx) {
@@ -39,17 +124,6 @@ export default Plugin.define({
39
124
  },
40
125
  })
41
126
 
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
127
  /**
54
128
  * Model import: for every site that has an account, fetch its cli-whitelist
55
129
  * catalog with that site's JWT and write a dedicated provider block. The
@@ -68,6 +142,25 @@ export default Plugin.define({
68
142
  }
69
143
  }
70
144
 
145
+ // GET /v2/models is generated locally from the same mapped catalog the
146
+ // provider import uses, so the advertised ids match what OpenCode can call.
147
+ const models = createModelsSource({
148
+ loadConfig,
149
+ readModelsDevCatalog,
150
+ getAuth: (site) => store.get(site),
151
+ fetchCatalog,
152
+ buildModels,
153
+ log,
154
+ })
155
+
156
+ // One config read feeds both the warmup decision and proxy routing, so the
157
+ // two can never disagree. startPrewarm fires the warmup asynchronously and
158
+ // swallows its failures; it never blocks startup.
159
+ const config = loadConfig()
160
+ const embeddingMode = startPrewarm(config, {
161
+ warmLocalModel, createLocalEmbedder, clearLocalEmbedderMemo, log,
162
+ })
163
+
71
164
  /** Import one site's models; reused after login so a new account lands in config. */
72
165
  const importSite = async (
73
166
  site: Site,
@@ -124,13 +217,34 @@ export default Plugin.define({
124
217
  log,
125
218
  afterLogin: async (site) => importSite(site, await importDeps()),
126
219
  })
127
- const registration = await ctx.rpc.register(CodebuddyQuota, handlers)
220
+ // Local reverse proxy: providers point here; the proxy injects the current
221
+ // site's JWT on each request. The first plugin instance binds the port; a
222
+ // reload reuses the process-wide server, so there is no dispose/setup
223
+ // listen gap. Port conflicts are logged by the owner and stay non-fatal.
224
+ // The proxy's lazy fallback must target the configured id too, otherwise a
225
+ // request would build a different model from the one prewarm verified.
226
+ let registration: { dispose(): void } | null = null
227
+ const gw = await setupGateway({
228
+ ensureGateway,
229
+ releaseGateway,
230
+ createServer: () =>
231
+ createProxy({
232
+ store, log, models, embeddingMode,
233
+ localEmbeddingModel: config.local_embedding_model,
234
+ }),
235
+ register: async () => {
236
+ const result = await ctx.rpc.register(CodebuddyQuota, handlers)
237
+ registration = result
238
+ return result
239
+ },
240
+ log,
241
+ })
128
242
 
129
243
  return () => {
130
- registration.dispose()
131
- void proxy.close().catch((error) =>
132
- log(`proxy close failed: ${String((error as Error)?.message ?? error)}`),
133
- )
244
+ registration?.dispose()
245
+ // Only drop our reference; the owner closes the shared server after the
246
+ // last holder is gone and its grace window has elapsed.
247
+ void gw.dispose()
134
248
  }
135
249
  },
136
250
  })
@@ -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
+ }