opencode-codebuddy-quota 0.0.0-stage → 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.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -2
  3. package/config.default.json +41 -0
  4. package/dist/gui-experimental.cjs +1 -0
  5. package/package.json +47 -4
  6. package/rpc.ts +92 -0
  7. package/server.ts +251 -0
  8. package/src/gui/battery.tsx +81 -0
  9. package/src/gui/dialog-helpers.ts +30 -0
  10. package/src/gui/dialog.css +83 -0
  11. package/src/gui/dialog.tsx +262 -0
  12. package/src/gui/pace.ts +76 -0
  13. package/src/gui/quota.ts +198 -0
  14. package/src/gui/store.ts +181 -0
  15. package/src/gui.tsx +111 -0
  16. package/src/server/catalog.ts +264 -0
  17. package/src/server/config-writer.ts +621 -0
  18. package/src/server/config.ts +215 -0
  19. package/src/server/embedding-local.ts +166 -0
  20. package/src/server/embedding-mode.ts +14 -0
  21. package/src/server/gateway-owner.ts +243 -0
  22. package/src/server/gateway-setup.ts +51 -0
  23. package/src/server/headers.ts +72 -0
  24. package/src/server/logger.ts +26 -0
  25. package/src/server/login-gate.ts +21 -0
  26. package/src/server/login.ts +206 -0
  27. package/src/server/model-cache.ts +136 -0
  28. package/src/server/model-info.ts +109 -0
  29. package/src/server/model-prewarm.ts +123 -0
  30. package/src/server/models-dev.ts +77 -0
  31. package/src/server/models-endpoint.ts +74 -0
  32. package/src/server/package-spec.ts +42 -0
  33. package/src/server/package-version.ts +51 -0
  34. package/src/server/pricing.ts +169 -0
  35. package/src/server/proxy.ts +564 -0
  36. package/src/server/quota-source.ts +129 -0
  37. package/src/server/rpc-handlers.ts +87 -0
  38. package/src/server/signal.ts +36 -0
  39. package/src/server/site-select.ts +24 -0
  40. package/src/server/site-state.ts +58 -0
  41. package/src/server/stream-collect.ts +166 -0
  42. package/src/server/token-store.ts +263 -0
  43. package/src/server/upstream.ts +150 -0
  44. package/src/server/wire.ts +67 -0
  45. package/src/shared.ts +20 -0
@@ -0,0 +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
+ }
@@ -0,0 +1,30 @@
1
+ import { signedPp } from "./pace"
2
+ import type { Quota } from "./quota"
3
+
4
+ /** Integer percent for the compact legend, clamped to 0..100. */
5
+ export const pctInt = (v: number | null): string =>
6
+ v === null || !Number.isFinite(v) ? "—" : `${Math.max(0, Math.min(100, Math.round(v)))}%`
7
+
8
+ /**
9
+ * Left offset of the elapsed-time marker on the shared bar. Both the credit
10
+ * fill and the time marker grow from the left edge, so the marker sits at the
11
+ * time percentage itself, not at its mirror.
12
+ */
13
+ export const timeMarkerLeft = (timePct: number | null): number =>
14
+ timePct === null || !Number.isFinite(timePct) ? 0 : Math.max(0, Math.min(100, timePct))
15
+
16
+ /** Direction + magnitude copy for the pace hint, driven only by diff's sign. */
17
+ export const paceHint = (diff: number | null): string => {
18
+ if (diff === null || !Number.isFinite(diff)) return ""
19
+ const dir = diff >= 0 ? "慢于" : "快于"
20
+ return ` · ${dir}时间 ${signedPp(Math.abs(diff))}`
21
+ }
22
+
23
+ export function freshness(q: Quota): { text: string; color: string } {
24
+ if (q.status === "error") return { text: "不可用", color: "#ff7a7a" }
25
+ if (q.status === "cached") {
26
+ return { text: q.ageSeconds === null ? "缓存" : `缓存(${q.ageSeconds} 秒前)`, color: "#ffb84d" }
27
+ }
28
+ if (q.status === "stale") return { text: "过期", color: "#ff7a7a" }
29
+ return { text: "实时", color: "#3ddc97" }
30
+ }
@@ -0,0 +1,83 @@
1
+ /*
2
+ * Scoped to the quota plugin's dialog. Most accents derive from currentColor so
3
+ * they track the active OpenCode theme. The site tags use a dedicated soft
4
+ * accent: currentColor is dark in light themes, which made the selected tag
5
+ * read as black instead of glowing.
6
+ */
7
+ .cq-tag {
8
+ --cq-accent: #5b8cff; /* soft blue; legible in both light and dark themes */
9
+ position: relative;
10
+ overflow: hidden;
11
+ transition: box-shadow 180ms ease, border-color 180ms ease, background 180ms ease, transform 180ms ease;
12
+ }
13
+ /* A soft sheen sweeps across on hover/toggle, then settles. */
14
+ .cq-tag::after {
15
+ content: "";
16
+ position: absolute; inset: 0;
17
+ background: linear-gradient(105deg, transparent 30%, color-mix(in srgb, var(--cq-accent) 22%, transparent) 50%, transparent 70%);
18
+ transform: translateX(-120%);
19
+ pointer-events: none;
20
+ }
21
+ .cq-tag:hover::after { animation: cq-sheen 700ms ease-out; }
22
+ .cq-tag[data-active="true"] {
23
+ background: color-mix(in srgb, var(--cq-accent) 14%, transparent);
24
+ border-color: color-mix(in srgb, var(--cq-accent) 55%, transparent);
25
+ color: color-mix(in srgb, var(--cq-accent) 85%, white);
26
+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--cq-accent) 28%, transparent),
27
+ 0 0 14px -2px color-mix(in srgb, var(--cq-accent) 50%, transparent);
28
+ }
29
+ .cq-tag:active { transform: scale(.97); }
30
+ @keyframes cq-sheen { from { transform: translateX(-120%); } to { transform: translateX(120%); } }
31
+
32
+ /* Freshness dot — gentle halo. */
33
+ .cq-dot {
34
+ box-shadow: 0 0 0 3px color-mix(in oklab, currentColor 14%, transparent);
35
+ }
36
+
37
+ /* Headline number — subtle glow, tabular for stability. */
38
+ .cq-amount {
39
+ font-variant-numeric: tabular-nums;
40
+ text-shadow: 0 0 20px color-mix(in oklab, currentColor 22%, transparent);
41
+ }
42
+
43
+ /* Unified progress track — inset well so the fill reads as lit (SpotlightCard). */
44
+ .cq-track {
45
+ overflow: hidden;
46
+ box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.18);
47
+ }
48
+ .cq-fill {
49
+ /* Oversized animated gradient: a highlight band travels left→right forever. */
50
+ background: linear-gradient(100deg,
51
+ color-mix(in oklab, currentColor 62%, transparent) 0%,
52
+ currentColor 35%,
53
+ color-mix(in oklab, white 45%, currentColor) 50%,
54
+ currentColor 65%,
55
+ color-mix(in oklab, currentColor 62%, transparent) 100%);
56
+ background-size: 220% 100%;
57
+ box-shadow: 0 0 10px -2px color-mix(in oklab, currentColor 65%, transparent);
58
+ transition: width 300ms cubic-bezier(.22,.8,.3,1), background 300ms ease-out;
59
+ animation: cq-flow 2.6s linear infinite;
60
+ }
61
+ @keyframes cq-flow {
62
+ from { background-position: 120% 0; }
63
+ to { background-position: -120% 0; }
64
+ }
65
+ .cq-marker {
66
+ box-shadow: 0 0 6px rgba(255, 255, 255, 0.75);
67
+ }
68
+
69
+ /* Pace hint card — faint tinted panel with a hairline highlight on top. */
70
+ .cq-hint {
71
+ background: color-mix(in oklab, currentColor 6%, transparent);
72
+ box-shadow: inset 0 1px 0 color-mix(in oklab, currentColor 12%, transparent);
73
+ }
74
+
75
+ /* Detail rows — soften the separators, keep numbers crisp. */
76
+ .cq-row {
77
+ border-bottom: 1px solid color-mix(in oklab, currentColor 14%, transparent);
78
+ }
79
+
80
+ @media (prefers-reduced-motion: reduce) {
81
+ .cq-tag, .cq-fill { transition: none; animation: none; }
82
+ .cq-tag::after { display: none; }
83
+ }
@@ -0,0 +1,262 @@
1
+ import type { JSX } from "solid-js"
2
+ import { createSignal, onMount } from "solid-js"
3
+ import type { Ui } from "@opencode/plugin/gui"
4
+ import type { Site, SiteInfo } from "../shared"
5
+ import { formatCredits, paceColor, paceLabel, type PaceLabel } from "./pace"
6
+ import type { Quota } from "./quota"
7
+ import { freshness, paceHint, pctInt, timeMarkerLeft } from "./dialog-helpers"
8
+
9
+ export interface QuotaDialogProps {
10
+ quota: Quota
11
+ onRefresh: (site?: Site) => Promise<void>
12
+ onLogin: (site: Site) => Promise<boolean>
13
+ close: () => void
14
+ /** Only the two host components the dialog draws with. */
15
+ ui: Pick<Ui, "Dialog" | "Button">
16
+ }
17
+
18
+ const labelText: Record<PaceLabel, string> = {
19
+ normal: "节奏正常",
20
+ ahead: "略慢于时间",
21
+ fast: "略快于时间",
22
+ over: "超支",
23
+ unknown: "—",
24
+ }
25
+
26
+ const hintTone: Record<PaceLabel, "normal" | "fast" | "over"> = {
27
+ normal: "normal",
28
+ ahead: "normal",
29
+ fast: "fast",
30
+ over: "over",
31
+ unknown: "fast",
32
+ }
33
+
34
+ const hintColor: Record<"normal" | "fast" | "over", string> = {
35
+ normal: "#3ddc97",
36
+ fast: "#ffb84d",
37
+ over: "#ff7a7a",
38
+ }
39
+
40
+ const row: JSX.CSSProperties = {
41
+ display: "flex",
42
+ "justify-content": "space-between",
43
+ gap: "12px",
44
+ padding: "6px 0",
45
+ "font-size": "12px",
46
+ "border-bottom": "1px dashed rgba(128,128,128,.25)",
47
+ }
48
+ const key: JSX.CSSProperties = { opacity: "0.62" }
49
+ const val: JSX.CSSProperties = { "font-variant-numeric": "tabular-nums" }
50
+
51
+ const SITE_LABEL: Record<Site, string> = { cn: "国内站", intl: "国际站" }
52
+
53
+ export function QuotaDialog(props: QuotaDialogProps): JSX.Element {
54
+ const q = () => props.quota
55
+ const site = () => q().site
56
+ const sites = (): SiteInfo[] => q().sites
57
+ const unusable = () => q().status === "error" || q().remaining === null
58
+ const fresh = () => freshness(q())
59
+ const [busy, setBusy] = createSignal(false)
60
+ const [logging, setLogging] = createSignal<Site | null>(null)
61
+
62
+ const refresh = async (s?: Site) => {
63
+ if (busy()) return
64
+ setBusy(true)
65
+ try {
66
+ await props.onRefresh(s)
67
+ } finally {
68
+ setBusy(false)
69
+ }
70
+ }
71
+
72
+ const login = async (s: Site) => {
73
+ if (logging()) return
74
+ setLogging(s)
75
+ try {
76
+ await props.onLogin(s)
77
+ } finally {
78
+ setLogging(null)
79
+ }
80
+ }
81
+
82
+ const select = (s: Site) => {
83
+ if (s !== site()) void refresh(s)
84
+ }
85
+
86
+ const Dialog = props.ui.Dialog
87
+ const Button = props.ui.Button
88
+
89
+ const tag = (info: SiteInfo): JSX.Element => {
90
+ const selected = info.site === site()
91
+ // The selected look (soft-accent border/glow/text) lives in dialog.css via
92
+ // [data-active]; leave these props off so the class is not overridden by
93
+ // an inline value (inline style always wins over a stylesheet).
94
+ const tagStyle: JSX.CSSProperties = selected
95
+ ? {
96
+ flex: "1", border: "1px solid", "font-size": "12px", padding: "8px 6px",
97
+ "border-radius": "8px", cursor: "pointer", "font-weight": "600",
98
+ }
99
+ : {
100
+ flex: "1", border: "1px solid",
101
+ "border-color": "color-mix(in oklab, currentColor 22%, transparent)",
102
+ background: "color-mix(in oklab, currentColor 5%, transparent)",
103
+ color: "inherit", "font-size": "12px", padding: "8px 6px",
104
+ "border-radius": "8px", cursor: "pointer", "font-weight": "600",
105
+ }
106
+ return (
107
+ <div
108
+ class="cq-tag"
109
+ data-active={selected ? "true" : "false"}
110
+ style={tagStyle}
111
+ onClick={() => (info.available ? select(info.site) : login(info.site))}
112
+ >
113
+ <span
114
+ class="cq-dot"
115
+ style={{
116
+ "display": "inline-block",
117
+ width: "6px",
118
+ height: "6px",
119
+ "border-radius": "50%",
120
+ "margin-right": "6px",
121
+ "vertical-align": "middle",
122
+ background: info.available ? "#3ddc97" : "#ff7a7a",
123
+ }}
124
+ />
125
+ {SITE_LABEL[info.site]}
126
+ {!info.available && (
127
+ <span style={{ "margin-left": "6px", "font-size": "10px", opacity: "0.8" }}>
128
+ {logging() === info.site ? "登录中…" : "· 登录"}
129
+ </span>
130
+ )}
131
+ </div>
132
+ )
133
+ }
134
+
135
+ const body = () => (
136
+ <div style={{ "min-width": "340px" }}>
137
+ <div style={{ display: "flex", gap: "4px", "margin-bottom": "10px" }}>
138
+ {sites().map(tag)}
139
+ </div>
140
+ <div style={{ display: "flex", "align-items": "center", gap: "6px", "font-size": "10px",
141
+ color: fresh().color, "margin-bottom": "12px" }}>
142
+ <span class="cq-dot" style={{ width: "6px", height: "6px", "border-radius": "50%", background: fresh().color }} />
143
+ {fresh().text}
144
+ </div>
145
+
146
+ {unusable() ? (
147
+ <div
148
+ style={{
149
+ padding: "12px",
150
+ "border-radius": "10px",
151
+ background: "color-mix(in oklab, currentColor 5%, transparent)",
152
+ border: "1px dashed color-mix(in oklab, currentColor 24%, transparent)",
153
+ "font-size": "12px",
154
+ "line-height": "1.6",
155
+ "text-align": "center",
156
+ }}
157
+ >
158
+ <div style={{ color: "var(--sub, #aab3c6)", "margin-bottom": "10px" }}>
159
+ <b style={{ color: "#ffb84d" }}>{SITE_LABEL[site()]}未登录</b>或认证已过期
160
+ </div>
161
+ <Button
162
+ variant="contrast"
163
+ busy={logging() === site()}
164
+ onClick={() => login(site())}
165
+ >
166
+ 登录{SITE_LABEL[site()]}
167
+ </Button>
168
+ <div style={{ "font-size": "10px", opacity: "0.6", "margin-top": "10px" }}>
169
+ 打开浏览器授权,插件自行轮询获取凭据;无需安装 CodeBuddy CLI。
170
+ </div>
171
+ </div>
172
+ ) : (
173
+ <>
174
+ <div style={{ display: "flex", "align-items": "baseline", "justify-content": "space-between", "margin-bottom": "2px" }}>
175
+ <span style={{ "font-size": "12px", opacity: "0.72" }}>本周期剩余额度</span>
176
+ <span class="cq-amount" style={{ "font-size": "26px", "font-weight": "750", "font-variant-numeric": "tabular-nums" }}>
177
+ {formatCredits(q().remaining)} <small style={{ "font-size": "12px", "font-weight": "500", opacity: "0.7" }}>积分</small>
178
+ </span>
179
+ </div>
180
+
181
+ {/* Variant A: one bar for both progressions. Fill = credits used,
182
+ white marker = elapsed time. Legend carries the numbers once. */}
183
+ <div class="cq-track" style={{ position: "relative", height: "16px", "border-radius": "6px", background: "color-mix(in oklab, currentColor 12%, transparent)", "margin-top": "10px" }}>
184
+ <div
185
+ class="cq-fill"
186
+ style={{
187
+ position: "absolute", left: "0", top: "0", bottom: "0",
188
+ width: `${Math.max(0, Math.min(100, q().usedPct ?? 0))}%`,
189
+ "border-radius": "6px",
190
+ // The flowing gradient lives in dialog.css (.cq-fill). Setting
191
+ // color here makes currentColor resolve to the pace colour there.
192
+ color: paceColor(q()),
193
+ }}
194
+ />
195
+ {q().timePct !== null && (
196
+ <div
197
+ class="cq-marker"
198
+ style={{
199
+ position: "absolute", top: "-3px", bottom: "-3px",
200
+ left: `${timeMarkerLeft(q().timePct)}%`,
201
+ width: "2px", background: "#fff", "border-radius": "2px", opacity: "0.9",
202
+ }}
203
+ />
204
+ )}
205
+ </div>
206
+ <div style={{ display: "flex", "justify-content": "space-between", "font-size": "10.5px", opacity: "0.8", "margin-top": "8px" }}>
207
+ <span>● 已用进度 {pctInt(q().usedPct)}</span>
208
+ <span>▏时间已过 {pctInt(q().timePct)}</span>
209
+ </div>
210
+
211
+ <div
212
+ class="cq-hint"
213
+ style={{
214
+ display: "flex", gap: "9px", "align-items": "flex-start",
215
+ "border-radius": "9px", padding: "10px 12px", "font-size": "12px",
216
+ border: "1px solid color-mix(in oklab, currentColor 12%, transparent)",
217
+ "margin-top": "12px",
218
+ }}
219
+ >
220
+ <span style={{ "font-weight": "800", color: hintColor[hintTone[paceLabel(q())]] }}>
221
+ {hintTone[paceLabel(q())] === "normal" ? "✓" : "!"}
222
+ </span>
223
+ <div>
224
+ <div style={{ "font-weight": "700", color: hintColor[hintTone[paceLabel(q())]] }}>
225
+ {labelText[paceLabel(q())]}
226
+ {paceHint(q().diff)}
227
+ </div>
228
+ <div style={{ opacity: "0.72", "font-size": "10.5px" }}>
229
+ 积分消耗{q().diff !== null && q().diff! < 0 ? "快于" : "慢于"}时间流逝,按当前速度
230
+ {q().diff !== null && q().diff! < 0 ? "可能在周期末前用完,建议控制用量。" : "可用到周期末。"}
231
+ </div>
232
+ </div>
233
+ </div>
234
+
235
+ <div style={{ "margin-top": "13px", "border-top": "1px solid rgba(255,255,255,.1)", "padding-top": "6px" }}>
236
+ <div class="cq-row" style={row}><span style={key}>已使用</span><span style={val}>{formatCredits(q().used)} 积分</span></div>
237
+ <div class="cq-row" style={row}><span style={key}>总额度</span><span style={val}>{formatCredits(q().total)} 积分</span></div>
238
+ <div style={{ ...row, "border-bottom": "none" }}><span style={key}>到期 / 重置</span><span style={val}>{q().resetAt ?? "—"}</span></div>
239
+ </div>
240
+ </>
241
+ )}
242
+ </div>
243
+ )
244
+
245
+ onMount(() => {
246
+ void refresh(site())
247
+ })
248
+
249
+ return (
250
+ <Dialog
251
+ title={`CodeBuddy 额度 · ${SITE_LABEL[site()]}`}
252
+ size="fit"
253
+ footer={
254
+ <Button variant="neutral" busy={busy()} onClick={() => refresh(site())}>
255
+ 刷新
256
+ </Button>
257
+ }
258
+ >
259
+ {body()}
260
+ </Dialog>
261
+ )
262
+ }
@@ -0,0 +1,76 @@
1
+ import type { Quota } from "./quota"
2
+
3
+ export const GREEN = "#4ade80"
4
+ export const AMBER = "#f5c246"
5
+ export const RED = "#f87171"
6
+ export const NEUTRAL = "#8b90a0"
7
+
8
+ /** Below this share of the cycle, elapsed-time progress is too jumpy to color by. */
9
+ const WARMUP_TIME_PCT = 3
10
+
11
+ type Rgb = [number, number, number]
12
+
13
+ const hex = (value: string): Rgb => [
14
+ parseInt(value.slice(1, 3), 16),
15
+ parseInt(value.slice(3, 5), 16),
16
+ parseInt(value.slice(5, 7), 16),
17
+ ]
18
+
19
+ const mix = (from: string, to: string, t: number): Rgb => {
20
+ const a = hex(from)
21
+ const b = hex(to)
22
+ return [
23
+ Math.round(a[0] + (b[0] - a[0]) * t),
24
+ Math.round(a[1] + (b[1] - a[1]) * t),
25
+ Math.round(a[2] + (b[2] - a[2]) * t),
26
+ ]
27
+ }
28
+
29
+ const toCss = ([r, g, b]: Rgb) => `rgb(${r}, ${g}, ${b})`
30
+
31
+ /**
32
+ * Color by pace, not by absolute remainder: `diff` is time progress minus spend
33
+ * progress. A gap of +5 or more is comfortable, 0 is the amber midline, -5 or
34
+ * more is an overrun, linear in between.
35
+ */
36
+ export function paceColor(q: Quota): string {
37
+ if (q.diff === null || q.timePct === null) return NEUTRAL
38
+ if (q.timePct < WARMUP_TIME_PCT) return GREEN
39
+ const diff = q.diff
40
+ if (diff >= 5) return GREEN
41
+ if (diff <= -5) return RED
42
+ // The gap is negative here, so remap it onto 0..1 for the ramp.
43
+ return toCss(mix(AMBER, diff < 0 ? RED : GREEN, Math.abs(diff) / 5))
44
+ }
45
+
46
+ export type PaceLabel = "normal" | "ahead" | "fast" | "over" | "unknown"
47
+
48
+ export function paceLabel(q: Quota): PaceLabel {
49
+ if (q.diff === null || q.timePct === null) return "unknown"
50
+ // Mirror paceColor's warm-up rule, or the dialog calls "超支" on a capsule that
51
+ // is deliberately green because the cycle just reset.
52
+ if (q.timePct < WARMUP_TIME_PCT) return "normal"
53
+ if (q.diff >= 5) return "normal"
54
+ if (q.diff >= 0) return "ahead"
55
+ if (q.diff > -5) return "fast"
56
+ return "over"
57
+ }
58
+
59
+ export function formatCredits(value: number | null): string {
60
+ return value === null ? "—" : value.toFixed(2)
61
+ }
62
+
63
+ export function formatPct(value: number | null): string {
64
+ return value === null ? "—" : `${value.toFixed(2)}%`
65
+ }
66
+
67
+ /**
68
+ * The gap between time and spend, in percentage points, with the sign kept.
69
+ * Positive means spending lags the clock (the good case); negative means the
70
+ * credits are going faster than the cycle.
71
+ */
72
+ export function signedPp(value: number | null): string {
73
+ if (value === null || !Number.isFinite(value)) return "—"
74
+ if (value === 0) return "0.00 pp"
75
+ return `${value > 0 ? "+" : "-"}${Math.abs(value).toFixed(2)} pp`
76
+ }