From dae64befac1fe8069370bd834d1de95421eac95f Mon Sep 17 00:00:00 2001 From: Yizhou Jiang Date: Sat, 14 Nov 2026 18:28:09 +0800 Subject: [PATCH 1/2] feat(sidebar): percent-only usage, opt-in local cost, /cmd-settings The per-model cost row summed json_extract over session_message on every 5 second poll: a main-thread scan with a disk-spilling sort, which is what made typing lag. Cost now defaults to off and, when enabled, answers from a memo for costMs instead of rescanning per tick. Poll cadence, colour, plan and the cost mode are editable from /cmd-settings, which follows the wallpaper plugin's dialog pattern. --- opencode-plugin/README.md | 12 ++ opencode-plugin/package.json | 2 +- opencode-plugin/src/constants/sidebar.ts | 26 ++- opencode-plugin/src/constants/timing.ts | 6 +- opencode-plugin/src/sidebar/local-cost.ts | 92 +++++++++ opencode-plugin/src/sidebar/prefs.ts | 87 +++++++- opencode-plugin/src/sidebar/settings-rows.ts | 98 +++++++++ opencode-plugin/src/sidebar/settings.tsx | 194 ++++++++++++++++++ opencode-plugin/src/sidebar/useRows.ts | 95 +++++---- opencode-plugin/src/tui-commands.tsx | 124 +++++++++++ opencode-plugin/src/tui.tsx | 118 +---------- opencode-plugin/test/sidebar-prefs.test.ts | 91 +++++++- .../test/sidebar-settings-rows.test.ts | 114 ++++++++++ 13 files changed, 881 insertions(+), 178 deletions(-) create mode 100644 opencode-plugin/src/sidebar/local-cost.ts create mode 100644 opencode-plugin/src/sidebar/settings-rows.ts create mode 100644 opencode-plugin/src/sidebar/settings.tsx create mode 100644 opencode-plugin/src/tui-commands.tsx create mode 100644 opencode-plugin/test/sidebar-settings-rows.test.ts diff --git a/opencode-plugin/README.md b/opencode-plugin/README.md index 24f9281..bb01366 100644 --- a/opencode-plugin/README.md +++ b/opencode-plugin/README.md @@ -65,6 +65,18 @@ What the section shows: Usage comes from `cmduse` polled every 5 seconds, read from opencode's message store for the per-model and per-session rows, and cached from `mpc` for the catalog. Every block remembers its last reading, so a remount, a session switch or a network outage repaints instead of blanking; the model figure is keyed by model and session, so switching models never shows the previous model's numbers. +## Settings + +`/cmd-settings` is a dialog over that same file, so a view option is changed without hand-editing JSON. Five settings, written as you pick them: + +- **Colours** — `off` (default) or `on`: tint status rows green/amber/red; `off` keeps bold and dim only. +- **OpenCode plan** — `go` (default) or `go-plus`: which per-model monthly limits the Go section renders. +- **Refresh** — `2s`, `5s` (default), `10s`, `30s` or `1m`: account poll cadence, one CLI spawn per tick. +- **Local cost rows** — `off` (default), `session` or `window`: where the per-model `$` figure comes from. +- **Cost refresh** — `30s`, `1m` (default) or `5m`: how often that figure is re-scanned; hidden while cost rows are `off`. + +The local cost figure lives inside each message's JSON, so summing it scans the whole store — 0.5-1.9s measured on a 1.3 GiB store, on the UI thread. That is why it defaults to `off`, and why turning it on gives it its own slow interval instead of riding the account poll. + ## Commands Each command passes its arguments through to the CLI that owns it, and each has an agent-facing tool of the same name, so the model can fetch the same text without you typing a slash command. diff --git a/opencode-plugin/package.json b/opencode-plugin/package.json index b4fa737..1e8ab6f 100644 --- a/opencode-plugin/package.json +++ b/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@jeffreyjyz/opencode-command-code", - "version": "0.5.26", + "version": "0.5.27", "description": "Command Code provider + usage dashboard for opencode: two providers (Anthropic wire for Claude, OpenAI wire for everything else) against api.commandcode.ai, live model list, plan gating, /cmd-usage. Requires the cmduse CLI for usage rendering.", "type": "module", "main": "dist/index.js", diff --git a/opencode-plugin/src/constants/sidebar.ts b/opencode-plugin/src/constants/sidebar.ts index 1854f51..8349f00 100644 --- a/opencode-plugin/src/constants/sidebar.ts +++ b/opencode-plugin/src/constants/sidebar.ts @@ -41,9 +41,33 @@ export const FIVE_HOUR_SECS = 5 * 3600; /** Weekly window length in seconds. Mirrors cmduse_core::WEEKLY_SECS. */ export const WEEKLY_SECS = 7 * 86400; +/** Sidebar poll cadences offered by /cmd-settings, in ms. */ +export const POLL_CHOICES = [2_000, 5_000, 10_000, 30_000, 60_000, 300_000] as const; + +/** One tick per 5s is the cadence every build before /cmd-settings shipped. */ +export const POLL_DEFAULT_MS = 5_000; + +/** + * Where the per-model cost row comes from. `off` is the default because that + * figure lives inside each message's JSON: summing it scans the whole + * `session_message` table (0.5-1.9s measured on a 1.3 GiB store) and that scan + * on the TUI thread is what stalled keystrokes. Percent windows come from the + * account API and cost nothing locally. + */ +export const COST_MODES = ["off", "session", "window"] as const; +export type CostMode = (typeof COST_MODES)[number]; +export const COST_MODE_DEFAULT: CostMode = "off"; + +/** Re-scan intervals for the opt-in cost row, in ms. */ +export const COST_REFRESH_CHOICES = [30_000, 60_000, 300_000] as const; +export const COST_REFRESH_DEFAULT_MS = 60_000; + /** Colour is OFF unless asked for; the OpenCode Go plan defaults to `go` (see - * sidebar/prefs.ts). */ + * sidebar/prefs.ts). Declared last because it reads the constants above. */ export const PREF_DEFAULTS: Prefs = { colors: false, ocPlan: OC_PLAN_DEFAULT, + pollMs: POLL_DEFAULT_MS, + cost: COST_MODE_DEFAULT, + costMs: COST_REFRESH_DEFAULT_MS, }; diff --git a/opencode-plugin/src/constants/timing.ts b/opencode-plugin/src/constants/timing.ts index 4ae1bb2..ff1763d 100644 --- a/opencode-plugin/src/constants/timing.ts +++ b/opencode-plugin/src/constants/timing.ts @@ -1,7 +1,5 @@ -// Poll cadences, spawn bounds and cache TTLs. - -/** Sidebar poll cadence: one cmduse/ocuse spawn plus the local store reads. */ -export const POLL_MS = 5_000; +// Poll cadences, spawn bounds and cache TTLs. The sidebar's own cadence is a +// setting (`prefs.pollMs`), so no fixed interval lives here. /** How long one sidebar CLI spawn may run before it is killed. An outage can * leave a fetch hanging through cmduse's retry ladder, and the poll interval diff --git a/opencode-plugin/src/sidebar/local-cost.ts b/opencode-plugin/src/sidebar/local-cost.ts new file mode 100644 index 0000000..8885b05 --- /dev/null +++ b/opencode-plugin/src/sidebar/local-cost.ts @@ -0,0 +1,92 @@ +// Local cost rows, memoised so the panel's poll never pays for the scan. +// Each figure lives in a `session_message` row's JSON, so summing it is an +// account-wide `json_extract … GROUP BY` over 1.3 GiB: 35ms/739ms/1 875ms for +// the 5h/7d/30d windows, with a disk-spilling sort. On the 5s poll that held the +// TUI thread 49.8% busy and lagged typing. `cost: "off"` (default) returns +// before any database is opened; an enabled mode answers from memory for `costMs`. +import { FIVE_HOUR_SECS, WEEKLY_SECS } from "../constants/sidebar"; +import { loadPrefs } from "./prefs"; +import type { ModelUsage } from "./rows"; +import { loadModelUsage, loadModelWindowStart, loadSessionUsage, usageDbPath } from "./usageDb"; +import type { ZenWindowStarts } from "./zen"; + +/** One memoised read: the same key inside `costMs` answers from memory. */ +function memoize() { + let slot: { key: string; at: number; value?: T } | undefined; + return { + read(key: string, costMs: number, now: number, scan: () => T | undefined): T | undefined { + if (slot && slot.key === key && now - slot.at < costMs) return slot.value; + slot = { key, at: now, value: scan() }; + return slot.value; + }, + clear(): void { + slot = undefined; + }, + }; +} + +const sessionMemo = memoize(); +const modelMemo = memoize(); +const windowsMemo = memoize(); + +/** Forget every figure, so the next read scans again. */ +export function resetLocalCost(): void { + sessionMemo.clear(); + modelMemo.clear(); + windowsMemo.clear(); +} + +/** + * This conversation's own totals: one indexed read on `session_v2`, the cheapest + * row the panel has. Undefined when the cost rows are off or the host has not + * resolved a session yet. + */ +export function sessionCost( + sessionID: string | undefined, + now = Date.now(), +): ModelUsage | undefined { + const prefs = loadPrefs(); + if (prefs.cost === "off" || !sessionID) return undefined; + return sessionMemo.read( + sessionID, + prefs.costMs, + now, + () => loadSessionUsage(sessionID) ?? undefined, + ); +} + +/** + * One model's spend inside one conversation. Session scope is required: the + * period-wide figure counts every conversation, and dividing it by this + * session's total read as "over 100% of session". + */ +export function modelCost( + modelID: string | undefined, + sessionID: string | undefined, + now = Date.now(), +): ModelUsage | undefined { + const prefs = loadPrefs(); + if (prefs.cost === "off" || !modelID || !sessionID) return undefined; + return modelMemo.read( + `${sessionID}\u0000${modelID}`, + prefs.costMs, + now, + () => loadModelUsage(modelID, 0, usageDbPath(), sessionID) ?? undefined, + ); +} + +/** + * The active model's rolling-window starts. Account-wide and the most expensive + * read here (two scans, one per window), so it is the `window` mode only. + */ +export function modelWindows( + modelID: string | undefined, + now = Date.now(), +): ZenWindowStarts | undefined { + const prefs = loadPrefs(); + if (prefs.cost !== "window" || !modelID) return undefined; + return windowsMemo.read(modelID, prefs.costMs, now, () => ({ + fiveHour: loadModelWindowStart(modelID, now - FIVE_HOUR_SECS * 1000) ?? undefined, + weekly: loadModelWindowStart(modelID, now - WEEKLY_SECS * 1000) ?? undefined, + })); +} diff --git a/opencode-plugin/src/sidebar/prefs.ts b/opencode-plugin/src/sidebar/prefs.ts index e49c50d..016fb76 100644 --- a/opencode-plugin/src/sidebar/prefs.ts +++ b/opencode-plugin/src/sidebar/prefs.ts @@ -11,17 +11,38 @@ // disk per render), so flipping the file lands on the next poll without a // restart. Nothing here throws: a missing, unreadable or malformed file leaves // the defaults standing, and an unknown plan falls back to `go` with a warning. -import { readFileSync } from "node:fs"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { OPENCODE_DIR, PREFS_FILE } from "../constants/paths"; -import { OC_PLAN_DEFAULT, OC_PLANS, type OcPlan, PREF_DEFAULTS } from "../constants/sidebar"; +import { + COST_MODE_DEFAULT, + COST_MODES, + COST_REFRESH_CHOICES, + COST_REFRESH_DEFAULT_MS, + type CostMode, + OC_PLAN_DEFAULT, + OC_PLANS, + type OcPlan, + POLL_CHOICES, + POLL_DEFAULT_MS, + PREF_DEFAULTS, +} from "../constants/sidebar"; import { PREFS_CACHE_MS } from "../constants/timing"; export interface Prefs { colors: boolean; /** OpenCode Go plan the sidebar renders per-model limits for. */ ocPlan: OcPlan; + /** Sidebar poll cadence in ms; one of `POLL_CHOICES`. */ + pollMs: number; + /** + * Where the per-model cost row reads from. `off` scans nothing: the figure + * sits inside each message's JSON, so summing it stalls the TUI thread. + */ + cost: CostMode; + /** Opt-in cost re-scan interval in ms; one of `COST_REFRESH_CHOICES`. */ + costMs: number; } let cached: { at: number; prefs: Prefs } | undefined; @@ -47,13 +68,71 @@ function planFrom(value: unknown, source: string): OcPlan | undefined { /** Only a literal `true` enables colour; an unknown plan falls back to `go`. */ export function parsePrefs(raw: unknown): Prefs { - const obj = raw as { colors?: unknown; ocPlan?: unknown } | undefined; + const obj = raw as + | { colors?: unknown; ocPlan?: unknown; pollMs?: unknown; cost?: unknown; costMs?: unknown } + | undefined; return { colors: obj?.colors === true, ocPlan: planFrom(obj?.ocPlan, "file") ?? OC_PLAN_DEFAULT, + pollMs: numberFrom(obj?.pollMs, POLL_CHOICES, POLL_DEFAULT_MS, "pollMs"), + cost: costFrom(obj?.cost), + costMs: numberFrom(obj?.costMs, COST_REFRESH_CHOICES, COST_REFRESH_DEFAULT_MS, "costMs"), }; } +/** + * A numeric setting only ever takes a value the settings dialog can produce, + * so a hand-edited file cannot pick a 1ms poll or a 0ms re-scan. + */ +function numberFrom( + value: unknown, + choices: readonly number[], + fallback: number, + name: string, +): number { + if (value === undefined) return fallback; + if (typeof value === "number" && choices.includes(value)) return value; + console.warn(`[command-code] ignoring unknown ${name} ${JSON.stringify(value)}; using ${fallback}`); + return fallback; +} + +function costFrom(value: unknown): CostMode { + if (value === undefined) return COST_MODE_DEFAULT; + if (typeof value === "string" && (COST_MODES as readonly string[]).includes(value)) { + return value as CostMode; + } + console.warn( + `[command-code] ignoring unknown cost mode ${JSON.stringify(value)}; using "${COST_MODE_DEFAULT}"`, + ); + return COST_MODE_DEFAULT; +} + +/** + * Write one or more settings back to the prefs file, keeping keys this build + * does not know yet (the file is shared with the provider half). Atomic: + * a crash mid-write must not leave an unreadable config behind, because every + * read below falls back to defaults and would silently reset the user. + */ +export function savePrefs(patch: Partial, env: NodeJS.ProcessEnv = process.env): Prefs { + const path = prefsPath(env); + let raw: Record = {}; + try { + const parsed: unknown = JSON.parse(readFileSync(path, "utf8")); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { + raw = parsed as Record; + } + } catch { + // absent or malformed: the patch still writes a valid file + } + const next = { ...raw, ...patch }; + mkdirSync(dirname(path), { recursive: true }); + const temporary = `${path}.${process.pid}.tmp`; + writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`, "utf8"); + renameSync(temporary, path); + cached = undefined; + return parsePrefs(next); +} + /** Env override, then the file, then the default. Cached for `PREFS_CACHE_MS`. */ export function loadPrefs(env: NodeJS.ProcessEnv = process.env, now = Date.now()): Prefs { if (cached && now - cached.at < PREFS_CACHE_MS) return cached.prefs; diff --git a/opencode-plugin/src/sidebar/settings-rows.ts b/opencode-plugin/src/sidebar/settings-rows.ts new file mode 100644 index 0000000..e68640b --- /dev/null +++ b/opencode-plugin/src/sidebar/settings-rows.ts @@ -0,0 +1,98 @@ +// Rows of the /cmd-settings dialog, kept free of JSX so both hosts and the +// tests can read them as plain data (the panel does the same for sidebar rows). +// +// Every row is a cycle: `values()` is the label list in display order, `value()` +// is what is stored now, `set()` writes it back to the prefs file. Labels are +// the only strings the dialog shows, so the stored file stays typed and the +// panel keeps its own parsing rules. +import { + COST_MODES, + COST_REFRESH_CHOICES, + POLL_CHOICES, + type CostMode, + type OcPlan, +} from "../constants/sidebar"; +import type { Prefs } from "./prefs"; + +export interface SettingRow { + readonly title: string; + readonly values: () => readonly string[]; + readonly value: () => string; + readonly set: (label: string) => void; + /** A row that only applies while another setting allows it. */ + readonly hidden?: () => boolean; + readonly describe?: (label: string) => string; +} + +/** `5000` reads `5s`, `300000` reads `5m`. */ +export function durationLabel(ms: number): string { + return ms >= 60_000 ? `${ms / 60_000}m` : `${ms / 1_000}s`; +} + +const onOff = (value: boolean): string => (value ? "on" : "off"); + +/** + * The setting list, in the order the dialog shows it. `prefs` is a getter, not + * a snapshot: the dialog re-reads after each change so a hidden row appears the + * moment the cost mode leaves `off`. + */ +export function settingRows(prefs: () => Prefs, save: (patch: Partial) => void): SettingRow[] { + return [ + { + title: "Colours", + values: () => ["off", "on"], + value: () => onOff(prefs().colors), + set: (label) => save({ colors: label === "on" }), + describe: (label) => + label === "on" + ? "Tint status rows green/amber/red; plain text keeps bold and dim only." + : "Plain text only. Bold marks headlines, dim marks labels.", + }, + { + title: "OpenCode plan", + values: () => ["go", "go-plus"], + value: () => prefs().ocPlan, + set: (label) => save({ ocPlan: label as OcPlan }), + describe: (label) => + label === "go-plus" + ? "Per-model monthly limits are the Go Plus ones." + : "Per-model monthly limits are the standard Go ones.", + }, + { + title: "Refresh", + values: () => POLL_CHOICES.map(durationLabel), + value: () => durationLabel(prefs().pollMs), + set: (label) => { + const index = POLL_CHOICES.map(durationLabel).indexOf(label); + if (index !== -1) save({ pollMs: POLL_CHOICES[index] }); + }, + describe: (label) => + `Poll the account API every ${label}. Shorter is fresher and costs one CLI spawn per tick.`, + }, + { + title: "Local cost rows", + values: () => [...COST_MODES], + value: () => prefs().cost, + set: (candidate) => { + if ((COST_MODES as readonly string[]).includes(candidate)) { + save({ cost: candidate as CostMode }); + } + }, + describe: (candidate) => + candidate === "off" + ? "No database reads at all: the panel shows account percentages only." + : "Reads this machine's message store for a $ figure. The scan takes 0.5-1.9s on a large store, so it runs on its own slower interval.", + }, + { + title: "Cost refresh", + values: () => COST_REFRESH_CHOICES.map(durationLabel), + value: () => durationLabel(prefs().costMs), + set: (label) => { + const index = COST_REFRESH_CHOICES.map(durationLabel).indexOf(label); + if (index !== -1) save({ costMs: COST_REFRESH_CHOICES[index] }); + }, + hidden: () => prefs().cost === "off", + describe: (label) => `Re-scan the message store for cost every ${label}.`, + }, + ]; +} diff --git a/opencode-plugin/src/sidebar/settings.tsx b/opencode-plugin/src/sidebar/settings.tsx new file mode 100644 index 0000000..8eb569d --- /dev/null +++ b/opencode-plugin/src/sidebar/settings.tsx @@ -0,0 +1,194 @@ +/** @jsxImportSource @opentui/solid */ +// /cmd-settings dialog: one row per sidebar preference, each cycling through +// the labels `settings-rows.ts` already knows. Rows are data there; this file +// is the only place that knows how a row becomes a terminal line — the same +// split the sidebar panel uses. +// +// Modelled on opencode-wallpapers' Picker: the modal keymap layer is created +// inside the component body, so it lives exactly as long as the dialog and is +// gone when the dialog closes. `esc` closes through `dialog.clear()` because a +// modal layer's own `escape` binding is the one route that always works, even +// when the host dialog has already claimed the key. +// +// Colours come from the theme's `dialog` surface when the host exposes one +// (`theme.surface("dialog")`), otherwise from the base text tokens. The `hue` +// scales are widget colours, not chrome — see sidebar/panel.tsx. +import { RGBA } from "@opentui/core"; +import type { Plugin as TuiPluginNs } from "@opencode/plugin/tui"; +import { createSignal, For } from "solid-js"; +import { loadPrefs, type Prefs, savePrefs } from "./prefs"; +import { type SettingRow, settingRows } from "./settings-rows"; + +/** The slice of theme chrome the dialog draws with, read defensively. */ +interface ThemeView { + readonly text: { + readonly base: RGBA; + readonly muted: RGBA; + readonly action?: { + readonly primary?: { readonly focused?: RGBA }; + }; + }; + readonly background?: { + readonly action?: { + readonly primary?: { readonly focused?: RGBA }; + }; + }; +} + +interface DialogColors { + /** Row title when it is not the selection. */ + readonly base: RGBA; + /** Every value not under the cursor, and the footer hints. */ + readonly muted: RGBA; + /** Title and value of the focused row. */ + readonly accent: RGBA; + /** Focused row's background band. */ + readonly selected: RGBA; +} + +/** `surface` is typed as required on ResolvedTheme, but a host may not carry it. */ +function dialogTheme(ctx: TuiPluginNs.Context): ThemeView { + const theme = ctx.theme as unknown as ThemeView & { + readonly surface?: (name: string) => ThemeView; + }; + return typeof theme.surface === "function" ? theme.surface("dialog") : theme; +} + +function dialogColors(ctx: TuiPluginNs.Context): DialogColors { + const view = dialogTheme(ctx); + return { + base: view.text.base, + muted: view.text.muted, + accent: view.text.action?.primary?.focused ?? view.text.base, + // A theme without an action background still needs a visible band, so the + // band falls back to the accent's own colour at low alpha (pure black + // transparent would make the selection invisible). + selected: + view.background?.action?.primary?.focused ?? + RGBA.fromValues( + view.text.action?.primary?.focused?.r ?? view.text.base.r, + view.text.action?.primary?.focused?.g ?? view.text.base.g, + view.text.action?.primary?.focused?.b ?? view.text.base.b, + 0.25, + ), + }; +} + +/** One row: title left, `‹ value ›` right, a band under the cursor. */ +function Row(props: { + row: SettingRow; + colors: DialogColors; + active: () => boolean; + onClick: () => void; +}) { + const fg = () => (props.active() ? props.colors.accent : props.colors.base); + return ( + + + {props.row.title} + + + {props.active() ? `‹ ${props.row.value()} ›` : props.row.value()} + + + ); +} + +export function SettingsDialog(props: { ctx: TuiPluginNs.Context }) { + const { ctx } = props; + const colors = dialogColors(ctx); + // Initialise from disk once, then trust the signal: `loadPrefs` reads the + // file (or a short cache) and a per-render read would hit the disk on every + // keystroke of a streaming session. + const [prefs, setPrefs] = createSignal(loadPrefs()); + const save = (patch: Partial) => { + savePrefs(patch); + // Re-read rather than patch in memory: `savePrefs` also normalises an + // unknown value back to the default, so the dialog must show what landed. + setPrefs(loadPrefs()); + }; + const rows = settingRows(prefs, save); + const visible = () => rows.filter((row) => !row.hidden?.()); + const [index, setIndex] = createSignal(0); + const current = () => visible()[index()] ?? visible()[0]; + + const move = (direction: number) => { + const list = visible(); + const length = list.length; + if (length === 0) return; + setIndex((at) => (at + direction + length) % length); + }; + const change = (direction: number) => { + const row = current(); + if (!row) return; + const values = row.values(); + if (values.length === 0) return; + const at = values.indexOf(row.value()); + const next = values[(at + direction + values.length) % values.length]; + if (next !== undefined) row.set(next); + }; + + // Created in the component body (like the wallpaper Picker) so the layer is + // disposed with the dialog: a modal layer outliving its dialog swallows + // every arrow key in the prompt. + ctx.keymap.layer(() => ({ + mode: "modal", + commands: [ + { bind: "up", title: "Previous setting", group: "Command Code", run: () => move(-1) }, + { bind: "down", title: "Next setting", group: "Command Code", run: () => move(1) }, + { bind: "right", title: "Next value", group: "Command Code", run: () => change(1) }, + { bind: "return", title: "Next value", group: "Command Code", run: () => change(1) }, + { bind: "left", title: "Previous value", group: "Command Code", run: () => change(-1) }, + { + bind: "escape", + title: "Close settings", + group: "Command Code", + run: () => ctx.ui.dialog.clear(), + }, + ], + })); + + return ( + + + + Command Code settings + + ctx.ui.dialog.clear()}> + esc + + + + {(row, at) => ( + at() === index()} + onClick={() => { + setIndex(at()); + change(1); + }} + /> + )} + + + + {(() => { + const row = current(); + return row?.describe?.(row.value()) ?? ""; + })()} + + + + {"↑/↓ setting"} + {"enter ←/→ change"} + + + ); +} diff --git a/opencode-plugin/src/sidebar/useRows.ts b/opencode-plugin/src/sidebar/useRows.ts index 107b1e3..88c79dc 100644 --- a/opencode-plugin/src/sidebar/useRows.ts +++ b/opencode-plugin/src/sidebar/useRows.ts @@ -12,10 +12,9 @@ import { ZEN_PROVIDER_ID, ZEN_PROVIDER_PREFIX, } from "../constants/providers"; -import { FIVE_HOUR_SECS, WEEKLY_SECS } from "../constants/sidebar"; -import { POLL_MS } from "../constants/timing"; import { type ArkUsage, arkRows } from "./ark"; import { loadArk, loadMeta, loadUsage, loadZen } from "./data"; +import { modelCost, modelWindows as readModelWindows, sessionCost } from "./local-cost"; import { loadPrefs } from "./prefs"; import { actionableAccountError, @@ -29,7 +28,6 @@ import { type Usage, usageRows, } from "./rows"; -import { loadModelUsage, loadModelWindowStart, loadSessionUsage, usageDbPath } from "./usageDb"; import { type ZenUsage, type ZenWindowStarts, zenRows } from "./zen"; /** @@ -234,31 +232,24 @@ export function useRows( .catch(() => {}); }; refreshMeta(); - /** Scan the store for one model in this conversation, and publish it. */ - const refreshModelUsage = (id: string | undefined) => { - if (!id) return; - const session = sessionID(); + /** + * Publish this conversation's totals and the active model's spend in it. + * Both go through `local-cost`, which memoises per `prefs.costMs` and opens + * no database at all while the cost rows are off. + */ + const refreshModelUsage = (id: string | undefined, session: string | undefined) => { + const now = Date.now(); + setSessionUsage(sessionCost(session, now)); // Without a session the scan is period-wide across *every* conversation; - // remembering that figure would divide it by the current session's own - // total and could read over 100%. Wait for the host to resolve the session. - if (!session) return; - const fresh = loadModelUsage(id, 0, usageDbPath(), session); + // dividing that by this session's own total read over 100%. + if (!id || !session) return; + const fresh = modelCost(id, session, now); if (fresh) rememberModelUsage(id, fresh, session); setModelUsage(lastModelUsage); }; - /** - * Re-read the active model's rolling-window starts for the Go/Zen panel. A - * local indexed read — no network, no CLI spawn — the same class as `Usage - * (this model)`. Account-wide like ocuse's own per-model window totals, so it - * takes no session scope; two scans, one per window. - */ + /** Rolling-window starts: same module, `window` mode only, one read per tick. */ const refreshModelWindows = (id: string | undefined) => { - if (!id) return; - const now = Date.now(); - setModelWindows({ - fiveHour: loadModelWindowStart(id, now - FIVE_HOUR_SECS * 1000) ?? undefined, - weekly: loadModelWindowStart(id, now - WEEKLY_SECS * 1000) ?? undefined, - }); + setModelWindows(readModelWindows(id)); }; // One poll in flight at a time. During an outage a single cmduse invocation @@ -274,26 +265,24 @@ export function useRows( const kind = sessionKind(providerID()); const session = sessionID(); refreshMeta(); - // Session totals are provider-agnostic and cheap (one indexed read). - if (session) setSessionUsage(loadSessionUsage(session) ?? undefined); if (kind === "ours") { const snapshot = await loadUsage(); rememberSnapshot(snapshot); setUsage(usageRows(snapshot)); - refreshModelUsage(activeModelId()); } else if (kind === "go" || kind === "zen") { const snapshot = keepAccount(await loadZen(loadPrefs().ocPlan), lastZen); rememberZen(snapshot); setZen(snapshot); - // The store scan is provider-agnostic and needs no network, so the - // Go/Zen panel gets the same `Usage (this model)` row. - refreshModelUsage(activeModelId()); refreshModelWindows(activeModelId()); } else if (kind === "ark") { const snapshot = keepAccount(await loadArk(), lastArk); rememberArk(snapshot); setArk(snapshot); } + // The store-backed rows are provider-agnostic and need no network, so + // every covered section gets them — and pays for them only when the + // cost mode is on. + refreshModelUsage(activeModelId(), session); } catch { // the CLI is missing, offline, or returned its errored defaults: keep // the last snapshot rather than painting "Free" with no windows. @@ -309,31 +298,41 @@ export function useRows( if (!shows(kind)) return; setWasOurs(true); void refresh(); - const timer = setInterval(() => void refresh(), POLL_MS); - onCleanup(() => clearInterval(timer)); + // Re-read the cadence on every tick, so a settings change lands without a + // restart; `loadPrefs` is cached, not a file read per render. + let timer: ReturnType | undefined; + let stopped = false; + const tick = () => { + if (stopped) return; + void refresh(); + timer = setTimeout(tick, loadPrefs().pollMs); + }; + timer = setTimeout(tick, loadPrefs().pollMs); + onCleanup(() => { + stopped = true; + if (timer) clearTimeout(timer); + }); }); // `refresh` above is keyed on the provider, so a switch between two of our - // models waited for the next minute poll — and showed the previous model's - // figure until it landed. Track the model *and* the session, because the - // figure counts this conversation's turns: a tab change keeps the provider, - // so the poll alone would only notice a minute later. The scan is sqlite (no - // process spawn) and the seed keeps the row up while it runs. Runs for the - // Go/Zen sections too: the figure is the same per-model, per-session read. + // models waited for the next poll — and showed the previous model's figure + // until it landed. Track the model *and* the session, because the figure + // counts this conversation's turns: a tab change keeps the provider. Both + // reads are memoised, so this effect cannot become a per-switch scan. createEffect(() => { const id = activeModelId(); const session = sessionID(); const kind = sessionKind(providerID()); - if (!shows(kind) || !id) return; + if (!shows(kind)) return; // Window starts are account-wide and need no session, so they refresh on a // model switch even before the host resolves the conversation. if (kind === "go" || kind === "zen") refreshModelWindows(id); - if (!session) return; - refreshModelUsage(id); + refreshModelUsage(id, session); }); /** Only a figure measured for the current model *and* conversation counts; - * else the seed (same check), else nothing. */ + * else the seed (same check), else nothing. Nothing at all while off. */ const usageFor = (id: string | undefined): ModelUsage | undefined => { + if (loadPrefs().cost === "off") return undefined; const session = sessionID(); const seen = modelUsage(); if ( @@ -351,6 +350,10 @@ export function useRows( if (!shows(kind) && (kind === "other" || !wasOurs())) return []; const id = activeModelId(); const found = id ? (meta().get(modelKey(id)) ?? meta().get(id)) : undefined; + // The store-backed rows are the opt-in half; while the cost mode is off + // they are omitted entirely and the account meters render alone. + const local = loadPrefs().cost !== "off"; + const session = local ? sessionUsage() : undefined; // The session id is the only name available when the catalog is missing; // its vendor prefix is noise, so keep the tail. const fallbackName = id ? (id.split("/").pop() ?? id) : undefined; @@ -359,9 +362,9 @@ export function useRows( zen(), found, usageFor(id), - sessionUsage(), + session, fallbackName, - modelWindows(), + local ? modelWindows() : undefined, ); } if (kind === "ark") { @@ -378,10 +381,6 @@ export function useRows( : undefined; // Account block, a rule, then the model block: two different subjects, and // without the divider the rows read as one long list. - return [ - ...usage(), - separator(), - ...modelRows(model, usageFor(id), sessionUsage(), fallbackName), - ]; + return [...usage(), separator(), ...modelRows(model, usageFor(id), session, fallbackName)]; }); } diff --git a/opencode-plugin/src/tui-commands.tsx b/opencode-plugin/src/tui-commands.tsx new file mode 100644 index 0000000..33433fc --- /dev/null +++ b/opencode-plugin/src/tui-commands.tsx @@ -0,0 +1,124 @@ +/** @jsxImportSource @opentui/solid */ +// The v2 host's slash commands, kept out of tui.tsx so the plugin entry stays +// readable. `registerCommands` is called from inside the app-slot render: +// `keymap.layer()` only works from a render, and the app slot is the mount +// point that is always present (the same claim opencode's own slash commands +// use). Each command keeps its id, because `bindings` below turns a user's +// configured keybind for that id into a live binding. +import type { Plugin as TuiPluginNs } from "@opencode/plugin/tui"; +import { arkuseArgs, ocuseArgs, runArkuse, runCmduse, runOcuse } from "./cli"; +import { + ARKUSE_USAGE_COMMAND_ID, + CMD_USAGE_COMMAND_ID, + OCUSE_USAGE_COMMAND_ID, +} from "./constants/providers"; +import { SettingsDialog } from "./sidebar/settings"; + +/** The /cmd-settings command id (kept beside its siblings, which live in constants). */ +export const SETTINGS_COMMAND_ID = "command-code.settings"; + +const GROUP = "Command Code"; + +export function registerCommands(ctx: TuiPluginNs.Context): void { + ctx.keymap.layer(() => ({ + mode: "global", + priority: 10, + commands: [ + { + id: CMD_USAGE_COMMAND_ID, + title: "Command Code usage", + group: GROUP, + slash: { name: "cmd-usage", arguments: true }, + enabled: () => true, + suggested: true, + run: async (input) => { + let text: string; + try { + text = await runCmduse(input ?? ""); + } catch (error) { + ctx.ui.toast.show({ + title: "cmd-usage failed", + message: error instanceof Error ? error.message : String(error), + variant: "error", + }); + return; + } + await ctx.ui.dialog.alert({ + title: "Command Code usage", + message: text.trimEnd(), + }); + }, + }, + { + id: OCUSE_USAGE_COMMAND_ID, + title: "OpenCode Go/Zen usage", + group: GROUP, + slash: { name: "ocuse-usage", arguments: true }, + enabled: () => true, + suggested: true, + // Empty input defaults to `-1` (see `ocuseArgs`): a bare ocuse is the + // live watch loop and would never resolve the dialog. + run: async (input) => { + let text: string; + try { + text = await runOcuse(ocuseArgs(input)); + } catch (error) { + ctx.ui.toast.show({ + title: "ocuse-usage failed", + message: error instanceof Error ? error.message : String(error), + variant: "error", + }); + return; + } + await ctx.ui.dialog.alert({ + title: "OpenCode Go/Zen usage", + message: text.trimEnd(), + }); + }, + }, + { + id: ARKUSE_USAGE_COMMAND_ID, + title: "Volcengine ARK usage", + group: GROUP, + slash: { name: "arkuse-usage", arguments: true }, + enabled: () => true, + suggested: true, + // Empty input means `-1` (see `arkuseArgs`): a bare arkuse is the + // live watch loop. + run: async (input) => { + let text: string; + try { + text = await runArkuse(arkuseArgs(input)); + } catch (error) { + ctx.ui.toast.show({ + title: "arkuse-usage failed", + message: error instanceof Error ? error.message : String(error), + variant: "error", + }); + return; + } + await ctx.ui.dialog.alert({ + title: "Volcengine ARK usage", + message: text.trimEnd(), + }); + }, + }, + { + id: SETTINGS_COMMAND_ID, + title: "Command Code settings", + group: GROUP, + palette: true, + slash: { name: "cmd-settings" }, + enabled: () => true, + suggested: true, + run: () => ctx.ui.dialog.show(() => ), + }, + ], + bindings: [ + CMD_USAGE_COMMAND_ID, + OCUSE_USAGE_COMMAND_ID, + ARKUSE_USAGE_COMMAND_ID, + SETTINGS_COMMAND_ID, + ], + })); +} diff --git a/opencode-plugin/src/tui.tsx b/opencode-plugin/src/tui.tsx index 25747bf..78a21f2 100644 --- a/opencode-plugin/src/tui.tsx +++ b/opencode-plugin/src/tui.tsx @@ -1,8 +1,8 @@ /** @jsxImportSource @opentui/solid */ // OpenCode TUI half: a "Command Code" session-sidebar section (plan, rolling // windows, period totals, plus the active model's allowance, rates and -// benchmarks), and — on v2 hosts — the /cmd-usage slash command that prints the -// full cmduse dashboard in a dialog. +// benchmarks), and — on v2 hosts — the slash commands (usage dashboards and the +// settings dialog, see tui-commands.tsx). // // Two hosts, two TUI contracts, one module (same shape cmd-provider uses): // v1 `tui(api)` — `api.slots.register({ slots: { sidebar_content } })` @@ -13,16 +13,11 @@ import type { Plugin as TuiPluginNs } from "@opencode/plugin/tui"; import type { RGBA } from "@opentui/core"; import type { JSX } from "@opentui/solid"; -import { arkuseArgs, ocuseArgs, runArkuse, runCmduse, runOcuse } from "./cli"; -import { - ARKUSE_USAGE_COMMAND_ID, - CMD_USAGE_COMMAND_ID, - OCUSE_USAGE_COMMAND_ID, - TUI_ID, -} from "./constants/providers"; +import { TUI_ID } from "./constants/providers"; import { hostColors, legacyColors, mono, Panel, type PanelColors } from "./sidebar/panel"; import { loadPrefs } from "./sidebar/prefs"; import { panelTitle, sessionKind, useRows } from "./sidebar/useRows"; +import { registerCommands } from "./tui-commands"; /** Colour is opt-in (see sidebar/prefs.ts); off, every tone collapses to text. */ const themed = (colors: PanelColors): PanelColors => (loadPrefs().colors ? colors : mono(colors)); @@ -105,108 +100,13 @@ export const commandCodeTui: TuiPluginNs.Definition = { append: "sidebar.content", render: (input) => , }); - // /cmd-usage prints the full cmduse dashboard in a dialog. keymap.layer() - // must run inside a render, so mount a no-op and register from there. - // Return `void` like opencode's own /btw claim: a `null` render leaves an - // empty box that paints a stray line in the prompt area. + // keymap.layer() must run inside a render, so mount a no-op app slot and + // register the commands from there. Return `void` like opencode's own + // /btw claim: a `null` render leaves an empty box that paints a stray + // line in the prompt area. ctx.ui.slot({ append: "app", - render: (() => { - ctx.keymap.layer(() => ({ - mode: "global", - priority: 10, - commands: [ - { - id: CMD_USAGE_COMMAND_ID, - title: "Command Code usage", - group: "Command Code", - slash: { name: "cmd-usage", arguments: true }, - enabled: () => true, - suggested: true, - run: async (input) => { - let text: string; - try { - text = await runCmduse(input ?? ""); - } catch (error) { - ctx.ui.toast.show({ - title: "cmd-usage failed", - message: - error instanceof Error ? error.message : String(error), - variant: "error", - }); - return; - } - await ctx.ui.dialog.alert({ - title: "Command Code usage", - message: text.trimEnd(), - }); - }, - }, - { - id: OCUSE_USAGE_COMMAND_ID, - title: "OpenCode Go/Zen usage", - group: "Command Code", - slash: { name: "ocuse-usage", arguments: true }, - enabled: () => true, - suggested: true, - // Empty input defaults to `-1` (see `ocuseArgs`): a bare - // ocuse is the live watch loop and would never - // resolve the dialog. - run: async (input) => { - let text: string; - try { - text = await runOcuse(ocuseArgs(input)); - } catch (error) { - ctx.ui.toast.show({ - title: "ocuse-usage failed", - message: - error instanceof Error ? error.message : String(error), - variant: "error", - }); - return; - } - await ctx.ui.dialog.alert({ - title: "OpenCode Go/Zen usage", - message: text.trimEnd(), - }); - }, - }, - { - id: ARKUSE_USAGE_COMMAND_ID, - title: "Volcengine ARK usage", - group: "Command Code", - slash: { name: "arkuse-usage", arguments: true }, - enabled: () => true, - suggested: true, - // Empty input means `-1` (see `arkuseArgs`): a bare - // arkuse is the live watch loop. - run: async (input) => { - let text: string; - try { - text = await runArkuse(arkuseArgs(input)); - } catch (error) { - ctx.ui.toast.show({ - title: "arkuse-usage failed", - message: - error instanceof Error ? error.message : String(error), - variant: "error", - }); - return; - } - await ctx.ui.dialog.alert({ - title: "Volcengine ARK usage", - message: text.trimEnd(), - }); - }, - }, - ], - bindings: [ - CMD_USAGE_COMMAND_ID, - OCUSE_USAGE_COMMAND_ID, - ARKUSE_USAGE_COMMAND_ID, - ], - })); - }) as unknown as () => JSX.Element, + render: (() => registerCommands(ctx)) as unknown as () => JSX.Element, }); }, }; diff --git a/opencode-plugin/test/sidebar-prefs.test.ts b/opencode-plugin/test/sidebar-prefs.test.ts index 05ee4dc..d67ae37 100644 --- a/opencode-plugin/test/sidebar-prefs.test.ts +++ b/opencode-plugin/test/sidebar-prefs.test.ts @@ -1,10 +1,16 @@ import { describe, expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { OPENCODE_DIR, PREFS_FILE } from "../src/constants/paths"; -import { OC_PLAN_DEFAULT } from "../src/constants/sidebar"; -import { loadPrefs, parsePrefs, prefsPath } from "../src/sidebar/prefs"; +import { + COST_MODE_DEFAULT, + COST_MODES, + COST_REFRESH_DEFAULT_MS, + OC_PLAN_DEFAULT, + POLL_DEFAULT_MS, +} from "../src/constants/sidebar"; +import { loadPrefs, type Prefs, parsePrefs, prefsPath, savePrefs } from "../src/sidebar/prefs"; /** Distinct `now` values sidestep the loader's short re-read cache. */ const tick = (() => { @@ -18,15 +24,14 @@ const configDir = () => { return { dir, env: { XDG_CONFIG_HOME: dir } }; }; +const DEFAULTS: Prefs = { colors: false, ocPlan: "go", pollMs: 5_000, cost: "off", costMs: 60_000 }; + describe("sidebar prefs", () => { test("colour off and plan `go` unless the file says otherwise", () => { const { dir, env } = configDir(); expect(prefsPath(env)).toBe(join(dir, OPENCODE_DIR, PREFS_FILE)); // Nothing on disk. - expect(loadPrefs(env, tick())).toEqual({ - colors: false, - ocPlan: "go", - }); + expect(loadPrefs(env, tick())).toEqual(DEFAULTS); }); test("the file turns colour on, and only a literal true does", () => { @@ -79,10 +84,7 @@ describe("sidebar prefs", () => { test("malformed json falls back to the default instead of throwing", () => { const { env } = configDir(); writeFileSync(prefsPath(env), "{not json"); - expect(loadPrefs(env, tick())).toEqual({ - colors: false, - ocPlan: "go", - }); + expect(loadPrefs(env, tick())).toEqual(DEFAULTS); }); test("CMD_COLORS overrides the file both ways", () => { @@ -119,4 +121,71 @@ describe("sidebar prefs", () => { // Past the window it is re-read. expect(loadPrefs(env, tick()).colors).toBe(false); }); + + test("poll and cost-refresh intervals only take a value the dialog offers", () => { + const warn = console.warn; + console.warn = () => {}; + try { + expect(parsePrefs({ pollMs: 5_000 }).pollMs).toBe(5_000); + expect(parsePrefs({ pollMs: 60_000 }).pollMs).toBe(60_000); + // A 1ms poll or a 0ms re-scan would hammer the disk, so it falls back. + expect(parsePrefs({ pollMs: 1 }).pollMs).toBe(POLL_DEFAULT_MS); + expect(parsePrefs({ pollMs: 7_000 }).pollMs).toBe(POLL_DEFAULT_MS); + expect(parsePrefs({ costMs: 300_000 }).costMs).toBe(300_000); + expect(parsePrefs({ costMs: 1_000 }).costMs).toBe(COST_REFRESH_DEFAULT_MS); + } finally { + console.warn = warn; + } + expect(parsePrefs({}).pollMs).toBe(POLL_DEFAULT_MS); + expect(parsePrefs({}).costMs).toBe(COST_REFRESH_DEFAULT_MS); + expect(parsePrefs(undefined).pollMs).toBe(POLL_DEFAULT_MS); + }); + + test("cost mode defaults to off and takes the three known values", () => { + expect(parsePrefs({}).cost).toBe(COST_MODE_DEFAULT); + expect(parsePrefs(undefined).cost).toBe("off"); + for (const mode of COST_MODES) expect(parsePrefs({ cost: mode }).cost).toBe(mode); + const warn = console.warn; + console.warn = () => {}; + try { + expect(parsePrefs({ cost: "always" }).cost).toBe(COST_MODE_DEFAULT); + expect(parsePrefs({ cost: 1 }).cost).toBe(COST_MODE_DEFAULT); + } finally { + console.warn = warn; + } + }); + + test("savePrefs patches the file, keeps unknown keys and clears the cache", () => { + const { env } = configDir(); + writeFileSync(prefsPath(env), JSON.stringify({ colors: true, futureKey: "kept" })); + expect(savePrefs({ pollMs: 30_000 }, env).pollMs).toBe(30_000); + // No delay, no tick arithmetic: the cache is dropped by the write itself. + expect(loadPrefs(env, tick())).toEqual({ ...DEFAULTS, colors: true, pollMs: 30_000 }); + expect(JSON.parse(readFileSync(prefsPath(env), "utf8"))).toEqual({ + colors: true, + futureKey: "kept", + pollMs: 30_000, + }); + + // Round-trip of every typed field, with the unknown key still standing. + expect( + savePrefs({ colors: false, ocPlan: "go-plus", cost: "window", costMs: 300_000 }, env), + ).toEqual({ + colors: false, + ocPlan: "go-plus", + pollMs: 30_000, + cost: "window", + costMs: 300_000, + }); + expect(loadPrefs(env, tick()).cost).toBe("window"); + expect(JSON.parse(readFileSync(prefsPath(env), "utf8")).futureKey).toBe("kept"); + }); + + test("a malformed existing file is replaced by valid json", () => { + const { env } = configDir(); + writeFileSync(prefsPath(env), "{not json"); + expect(savePrefs({ colors: true }, env)).toEqual({ ...DEFAULTS, colors: true }); + expect(JSON.parse(readFileSync(prefsPath(env), "utf8"))).toEqual({ colors: true }); + expect(loadPrefs(env, tick()).colors).toBe(true); + }); }); diff --git a/opencode-plugin/test/sidebar-settings-rows.test.ts b/opencode-plugin/test/sidebar-settings-rows.test.ts new file mode 100644 index 0000000..79ae18b --- /dev/null +++ b/opencode-plugin/test/sidebar-settings-rows.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "bun:test"; +import { COST_REFRESH_CHOICES, POLL_CHOICES } from "../src/constants/sidebar"; +import type { Prefs } from "../src/sidebar/prefs"; +import { durationLabel, type SettingRow, settingRows } from "../src/sidebar/settings-rows"; + +const DEFAULTS: Prefs = { + colors: false, + ocPlan: "go", + pollMs: 5_000, + cost: "off", + costMs: 60_000, +}; + +/** A getter over mutable state, so `hidden()` can follow a setting change. */ +const build = (over: Partial = {}) => { + const state: Prefs = { ...DEFAULTS, ...over }; + const calls: Partial[] = []; + const rows = settingRows( + () => state, + (patch) => calls.push(patch), + ); + return { state, rows, calls }; +}; + +const at = (rows: readonly SettingRow[], title: string): SettingRow => { + const row = rows.find((candidate) => candidate.title === title); + if (!row) throw new Error(`no row titled ${title}`); + return row; +}; + +describe("sidebar settings rows", () => { + test("rows come out in display order, each with its own labels", () => { + const { rows } = build(); + expect(rows.map((row) => row.title)).toEqual([ + "Colours", + "OpenCode plan", + "Refresh", + "Local cost rows", + "Cost refresh", + ]); + expect(at(rows, "Colours").values()).toEqual(["off", "on"]); + expect(at(rows, "OpenCode plan").values()).toEqual(["go", "go-plus"]); + expect(at(rows, "Refresh").values()).toEqual(POLL_CHOICES.map(durationLabel)); + expect(at(rows, "Local cost rows").values()).toEqual(["off", "session", "window"]); + expect(at(rows, "Cost refresh").values()).toEqual(COST_REFRESH_CHOICES.map(durationLabel)); + }); + + test("value() reads the prefs it was handed", () => { + const { rows } = build({ + colors: true, + ocPlan: "go-plus", + pollMs: 30_000, + cost: "session", + costMs: 300_000, + }); + expect(at(rows, "Colours").value()).toBe("on"); + expect(at(rows, "OpenCode plan").value()).toBe("go-plus"); + expect(at(rows, "Refresh").value()).toBe("30s"); + expect(at(rows, "Local cost rows").value()).toBe("session"); + expect(at(rows, "Cost refresh").value()).toBe("5m"); + + const off = build().rows; + expect(at(off, "Colours").value()).toBe("off"); + expect(at(off, "Local cost rows").value()).toBe("off"); + }); + + test("set() calls save with the typed patch, never the label string", () => { + const { rows, calls } = build(); + at(rows, "Colours").set("on"); + at(rows, "Colours").set("off"); + at(rows, "OpenCode plan").set("go-plus"); + at(rows, "Refresh").set("1m"); + at(rows, "Local cost rows").set("window"); + at(rows, "Cost refresh").set("5m"); + at(rows, "Cost refresh").set("30s"); + expect(calls).toEqual([ + { colors: true }, + { colors: false }, + { ocPlan: "go-plus" }, + { pollMs: 60_000 }, + { cost: "window" }, + { costMs: 300_000 }, + { costMs: 30_000 }, + ]); + }); + + test("Cost refresh hides while cost rows are off", () => { + const { state, rows } = build({ cost: "off" }); + const costRefresh = at(rows, "Cost refresh"); + expect(costRefresh.hidden?.()).toBe(true); + state.cost = "session"; + expect(costRefresh.hidden?.()).toBe(false); + state.cost = "window"; + expect(costRefresh.hidden?.()).toBe(false); + // Every other row is always visible. + expect(at(rows, "Colours").hidden).toBeUndefined(); + expect(at(rows, "Local cost rows").hidden).toBeUndefined(); + }); + + test("an invalid label writes nothing", () => { + const { rows, calls } = build(); + at(rows, "Refresh").set("nope"); + at(rows, "Local cost rows").set("bogus"); + at(rows, "Cost refresh").set("99s"); + expect(calls).toEqual([]); + }); + + test("durationLabel maps the stored milliseconds to the shown label", () => { + expect(durationLabel(5_000)).toBe("5s"); + expect(durationLabel(60_000)).toBe("1m"); + expect(durationLabel(300_000)).toBe("5m"); + expect(durationLabel(2_000)).toBe("2s"); + }); +}); From 2be74581b886a18cb9c824a88ef2752b9e175ebe Mon Sep 17 00:00:00 2001 From: Yizhou Jiang Date: Sat, 14 Nov 2026 18:30:49 +0800 Subject: [PATCH 2/2] style(sidebar): bun fmt --- opencode-plugin/src/sidebar/prefs.ts | 4 +++- opencode-plugin/src/sidebar/settings-rows.ts | 5 ++++- opencode-plugin/src/sidebar/settings.tsx | 7 ++++++- 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/opencode-plugin/src/sidebar/prefs.ts b/opencode-plugin/src/sidebar/prefs.ts index 016fb76..ab87061 100644 --- a/opencode-plugin/src/sidebar/prefs.ts +++ b/opencode-plugin/src/sidebar/prefs.ts @@ -92,7 +92,9 @@ function numberFrom( ): number { if (value === undefined) return fallback; if (typeof value === "number" && choices.includes(value)) return value; - console.warn(`[command-code] ignoring unknown ${name} ${JSON.stringify(value)}; using ${fallback}`); + console.warn( + `[command-code] ignoring unknown ${name} ${JSON.stringify(value)}; using ${fallback}`, + ); return fallback; } diff --git a/opencode-plugin/src/sidebar/settings-rows.ts b/opencode-plugin/src/sidebar/settings-rows.ts index e68640b..c3a1c61 100644 --- a/opencode-plugin/src/sidebar/settings-rows.ts +++ b/opencode-plugin/src/sidebar/settings-rows.ts @@ -36,7 +36,10 @@ const onOff = (value: boolean): string => (value ? "on" : "off"); * a snapshot: the dialog re-reads after each change so a hidden row appears the * moment the cost mode leaves `off`. */ -export function settingRows(prefs: () => Prefs, save: (patch: Partial) => void): SettingRow[] { +export function settingRows( + prefs: () => Prefs, + save: (patch: Partial) => void, +): SettingRow[] { return [ { title: "Colours", diff --git a/opencode-plugin/src/sidebar/settings.tsx b/opencode-plugin/src/sidebar/settings.tsx index 8eb569d..f5ca9a8 100644 --- a/opencode-plugin/src/sidebar/settings.tsx +++ b/opencode-plugin/src/sidebar/settings.tsx @@ -156,7 +156,12 @@ export function SettingsDialog(props: { ctx: TuiPluginNs.Context }) { return ( - + Command Code settings