Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(usage): add the opencode provider, and generalize cookie storage (#15)
eneskircab6ecf2fa53b3
diff --git a/src/core/usage/minimax-cookie.ts b/src/core/usage/minimax-cookie.tsdeleted file mode 100644index 2f70fbf9a..000000000--- a/src/core/usage/minimax-cookie.ts+++ /dev/null@@ -1,53 +0,0 @@-// Storage for the MiniMax browser cookie.-//-// This deliberately does NOT live in settings.json. That file is written with default-// permissions and is treated throughout the app as CONFIG — the `claudeAccounts` list sits-// there precisely because an account list is config, not a credential. A MiniMax session cookie-// is the opposite: it is a live bearer credential that grants access to the user's MiniMax-// account, so it gets its own file with 0600 and never appears in a config blob that is-// world-readable, copied between machines, or pasted into a bug report.-import { promises as fs } from 'fs'-import path from 'path'-import { platform } from '../platform'--const FILE = 'minimax-cookie.json'-/** Owner read/write only. The whole reason this is a separate file. */-const MODE = 0o600--function file(): string {- return path.join(platform().userDataDir, FILE)-}--/** The stored cookie header, or null when MiniMax has not been configured. */-export async function readMinimaxCookie(): Promise<string | null> {- try {- const raw = await fs.readFile(file(), 'utf-8')- const j = JSON.parse(raw) as Record<string, unknown>- return typeof j.cookie === 'string' && j.cookie.trim() ? j.cookie : null- } catch {- return null- }-}--/**- * Store (or, with an empty value, clear) the cookie. Written to a temp file first and renamed,- * so a crash mid-write cannot leave a half-written credential behind — and the temp file is- * created with the restricted mode too, since a rename preserves whatever the source had.- */-export async function writeMinimaxCookie(cookie: string): Promise<void> {- const target = file()- if (!cookie.trim()) {- await fs.rm(target, { force: true })- return- }- const tmp = `${target}.tmp`- await fs.writeFile(tmp, JSON.stringify({ cookie }), { encoding: 'utf-8', mode: MODE })- await fs.rename(tmp, target)- // Belt and braces: an existing temp file from a previous run would keep its own mode.- await fs.chmod(target, MODE).catch(() => undefined)-}--/** Whether a cookie is stored — for the settings UI, which must never read the value back. */-export async function hasMinimaxCookie(): Promise<boolean> {- return (await readMinimaxCookie()) !== null-}diff --git a/src/core/usage/minimax-usage.test.ts b/src/core/usage/minimax-usage.test.tsindex 4f3cdf496..54cf1fd07 100644--- a/src/core/usage/minimax-usage.test.ts+++ b/src/core/usage/minimax-usage.test.ts@@ -10,7 +10,7 @@ import {minimaxRejected,fetchMinimaxUsage} from './minimax-usage'-import { readMinimaxCookie, writeMinimaxCookie, hasMinimaxCookie } from './minimax-cookie'+import { readProviderCookie, writeProviderCookie, hasProviderCookie } from './provider-cookie'import { initPlatform, resetPlatformForTests, type CorePlatform } from '../platform'import { primaryLimit, limitLabel } from '../../shared/usage-limits'@@ -157,40 +157,40 @@ describe('minimax cookie storage', () => {})it('round-trips a cookie', async () => {- await writeMinimaxCookie('_token=abc')- await expect(readMinimaxCookie()).resolves.toBe('_token=abc')- await expect(hasMinimaxCookie()).resolves.toBe(true)+ await writeProviderCookie('minimax', '_token=abc')+ await expect(readProviderCookie('minimax')).resolves.toBe('_token=abc')+ await expect(hasProviderCookie('minimax')).resolves.toBe(true)})it('stores it OUTSIDE settings.json, readable only by the owner', async () => {// The whole reason this is a separate file: settings.json is written with default// permissions, and this value is a live bearer credential, not config.- await writeMinimaxCookie('_token=abc')+ await writeProviderCookie('minimax', '_token=abc')const mode = fs.statSync(path.join(dir, 'minimax-cookie.json')).mode & 0o777expect(mode).toBe(0o600)expect(fs.existsSync(path.join(dir, 'settings.json'))).toBe(false)})it('clears the stored cookie, leaving no file behind', async () => {- await writeMinimaxCookie('_token=abc')- await writeMinimaxCookie('')- await expect(readMinimaxCookie()).resolves.toBeNull()- await expect(hasMinimaxCookie()).resolves.toBe(false)+ await writeProviderCookie('minimax', '_token=abc')+ await writeProviderCookie('minimax', '')+ await expect(readProviderCookie('minimax')).resolves.toBeNull()+ await expect(hasProviderCookie('minimax')).resolves.toBe(false)expect(fs.existsSync(path.join(dir, 'minimax-cookie.json'))).toBe(false)})it('treats a whitespace-only paste as clearing, not as a cookie', async () => {- await writeMinimaxCookie(' ')- await expect(hasMinimaxCookie()).resolves.toBe(false)+ await writeProviderCookie('minimax', ' ')+ await expect(hasProviderCookie('minimax')).resolves.toBe(false)})it('reports no cookie rather than throwing on a corrupt file', async () => {fs.writeFileSync(path.join(dir, 'minimax-cookie.json'), '{{{')- await expect(readMinimaxCookie()).resolves.toBeNull()+ await expect(readProviderCookie('minimax')).resolves.toBeNull()})it('leaves no temp file behind after a write', async () => {- await writeMinimaxCookie('_token=abc')+ await writeProviderCookie('minimax', '_token=abc')expect(fs.readdirSync(dir)).toEqual(['minimax-cookie.json'])})})diff --git a/src/core/usage/opencode-usage.test.ts b/src/core/usage/opencode-usage.test.tsnew file mode 100644index 000000000..9a7829c66--- /dev/null+++ b/src/core/usage/opencode-usage.test.ts@@ -0,0 +1,164 @@+import { describe, it, expect } from 'vitest'+import {+ parseOpencodePage,+ extractUsageBlock,+ topLevelNumber,+ normalizeCookieInput,+ filterAuthCookie,+ parseWorkspaceIds,+ isValidWorkspaceId,+ fetchOpencodeUsage+} from './opencode-usage'+import { primaryLimit } from '../../shared/usage-limits'++/**+ * A miniature of opencode.ai's React Flight wire data. NOTE: not captured from a live account —+ * no opencode session was available on the machine this was written on. It reproduces the+ * documented shape, including the two traps orca hit: a `$R[N]=` reference token between the+ * key and its object, and a null/decoy occurrence of the same key elsewhere on the page.+ */+const PAGE = `+ {billingContext:{monthlyUsage:null,plan:"pro"}}+ {rollingUsage:$R[28]={usagePercent:42,resetInSec:3600,label:"5h"}}+ {weeklyUsage:{usagePercent:77,resetInSec:172800}}+ {monthlyUsage:{usagePercent:15,resetInSec:1209600}}+`++describe('parseOpencodePage', () => {+ it('extracts the rolling, weekly and monthly windows', () => {+ const limits = parseOpencodePage(PAGE)+ expect(limits.map((l) => l.kind)).toEqual(['session', 'weekly_all', 'monthly_all'])+ expect(limits.map((l) => l.usedPercent)).toEqual([42, 77, 15])+ })++ it('reads through a React Flight $R[N]= reference token', () => {+ // The wire format puts a reference between the colon and the brace; a naive `key:{` match+ // would miss rollingUsage entirely.+ expect(parseOpencodePage(PAGE)[0].usedPercent).toBe(42)+ })++ it('skips a decoy occurrence that lacks usage fields', () => {+ // `monthlyUsage:null` appears first, inside billingContext. Matching the key alone would+ // return that and report no monthly window.+ expect(parseOpencodePage(PAGE).find((l) => l.kind === 'monthly_all')?.usedPercent).toBe(15)+ })++ it('turns resetInSec into an absolute timestamp', () => {+ // It is a DURATION from now, not a stamp. Using it raw would put every reset in 1970.+ const before = Date.now()+ const at = parseOpencodePage(PAGE)[0].resetsAt!+ expect(at).toBeGreaterThanOrEqual(before + 3600 * 1000)+ expect(at).toBeLessThan(before + 3600 * 1000 + 5000)+ })++ it('pins the window durations rather than deriving them', () => {+ expect(parseOpencodePage(PAGE).map((l) => l.windowMinutes)).toEqual([300, 10_080, 43_200])+ })++ it('returns NOTHING when the format moves, rather than a partial guess', () => {+ // The whole risk of this provider: the page changes and the parser silently latches onto+ // something else. Both anchors missing must mean "no data", never a lone coincidental match.+ expect(parseOpencodePage('{someOtherShape:{value:5}}')).toEqual([])+ expect(parseOpencodePage('{monthlyUsage:{usagePercent:15,resetInSec:10}}')).toEqual([])+ })++ it('rejects an implausible reset instead of rendering it', () => {+ // A wrong number displayed confidently is worse than no number.+ const limits = parseOpencodePage(+ '{rollingUsage:{usagePercent:10,resetInSec:-5}}{weeklyUsage:{usagePercent:20,resetInSec:99999999}}'+ )+ expect(limits.map((l) => l.resetsAt)).toEqual([null, null])+ })++ it('clamps out-of-range percentages', () => {+ const limits = parseOpencodePage(+ '{rollingUsage:{usagePercent:180,resetInSec:60}}{weeklyUsage:{usagePercent:-4,resetInSec:60}}'+ )+ expect(limits.map((l) => l.usedPercent)).toEqual([100, 0])+ })++ it('refuses an absurdly large payload instead of brace-scanning it', () => {+ expect(parseOpencodePage('x'.repeat(10_000_001))).toEqual([])+ expect(parseOpencodePage('')).toEqual([])+ })++ it('leads with the most constrained window', () => {+ expect(primaryLimit(parseOpencodePage(PAGE))?.kind).toBe('weekly_all')+ })+})++describe('topLevelNumber', () => {+ it('ignores a same-named field nested deeper', () => {+ // Without depth tracking the first textual match wins and returns the wrong number.+ expect(topLevelNumber('{a:{usagePercent:99},usagePercent:5}', 'usagePercent')).toBe(5)+ })++ it('returns null when the field is absent', () => {+ expect(topLevelNumber('{other:1}', 'usagePercent')).toBeNull()+ })+})++describe('extractUsageBlock', () => {+ it('returns null when no occurrence carries both required fields', () => {+ expect(extractUsageBlock('{weeklyUsage:{usagePercent:5}}', 'weeklyUsage')).toBeNull()+ })+})++describe('cookie handling', () => {+ it('wraps a bare token so it does not fail confusingly', () => {+ expect(normalizeCookieInput('Fe26.2**abc')).toBe('auth=Fe26.2**abc')+ })++ it('leaves a real header alone, including a pasted "Cookie:" prefix', () => {+ expect(normalizeCookieInput('Cookie: auth=x; other=y')).toBe('auth=x; other=y')+ })++ it('sends ONLY auth cookies, never unrelated site cookies', () => {+ // Replaying a whole browser header would transmit unrelated sessions to opencode.+ expect(filterAuthCookie('analytics=1; auth=x; tracker=2')).toBe('auth=x')+ expect(filterAuthCookie('__Host-auth=y; ads=3')).toBe('__Host-auth=y')+ })++ it('returns null when nothing recognizable is present', () => {+ expect(filterAuthCookie('analytics=1; tracker=2')).toBeNull()+ })+})++describe('workspace ids', () => {+ it('extracts and de-duplicates ids', () => {+ expect(parseWorkspaceIds('id:"wrk_abc123", id:"wk_def", id:"wrk_abc123"')).toEqual([+ 'wrk_abc123',+ 'wk_def'+ ])+ })++ it('ignores ids that do not match the expected shape', () => {+ expect(parseWorkspaceIds('id:"user_123"')).toEqual([])+ expect(isValidWorkspaceId('wrk_abc')).toBe(true)+ expect(isValidWorkspaceId('nope')).toBe(false)+ })+})++describe('fetchOpencodeUsage', () => {+ it('reports unavailable with no cookie, without touching the network', async () => {+ await expect(fetchOpencodeUsage(null)).resolves.toMatchObject({+ provider: 'opencode',+ status: 'unavailable',+ limits: []+ })+ })++ it('reports unavailable when the paste carries no auth cookie', async () => {+ await expect(fetchOpencodeUsage('analytics=1; tracker=2')).resolves.toMatchObject({+ status: 'unavailable'+ })+ })++ it('reports ERROR, not unavailable, for a malformed workspace override', async () => {+ // The distinction this provider lives or dies by: configured-but-broken must never look+ // like not-configured, or a stale scraper quietly reads as "you have no usage".+ await expect(fetchOpencodeUsage('auth=x', 'not-a-workspace')).resolves.toMatchObject({+ status: 'error'+ })+ })+})diff --git a/src/core/usage/opencode-usage.ts b/src/core/usage/opencode-usage.tsnew file mode 100644index 000000000..25a19906e--- /dev/null+++ b/src/core/usage/opencode-usage.ts@@ -0,0 +1,267 @@+// opencode usage, scraped from opencode.ai's dashboard HTML.+//+// ⚠️ This is the least robust provider here, and knowingly so. opencode publishes no usage API,+// so the numbers are dug out of React Flight wire data embedded in a page we do not control.+// There are three independent things that can break it, none of which fail at compile time:+//+// 1. WORKSPACES_SERVER_ID below is a hash of opencode.ai's own server function. It changes+// when they redeploy. That is why a workspace id can be supplied by the user as an+// override — discovery breaking should not take the whole provider down with it.+// 2. The wire format is a framework implementation detail (`key:$R[28]={...}`), not a+// contract.+// 3. The block parser tracks brace depth and does NOT skip string literals, so a `{` inside a+// string in future output would desynchronize it.+//+// The design rule that follows: when a cookie IS configured but nothing parses, this reports+// 'error', never an empty 'ok'. A broken scraper must look broken. Silently reporting "no+// usage" would be indistinguishable from "not signed in" and would quietly mislead — which is+// exactly the failure mode that got the CLI screen-scraping tier rejected.+import type { ProviderUsage, UsageLimit } from '../../shared/types'++const BASE_URL = 'https://opencode.ai'+const SERVER_URL = `${BASE_URL}/_server`+const FETCH_TIMEOUT_MS = 15_000++/** Server-function hash for the workspaces endpoint. A deployment artifact — see header. */+const WORKSPACES_SERVER_ID =+ 'def39973159c7f0483d8793a822b8dbb10d067e12c65455fcb4608459ba0234f'++/** Only these carry session auth on opencode.ai. Sending the rest would leak unrelated cookies. */+const AUTH_COOKIE_NAMES = new Set(['auth', '__Host-auth'])++const WORKSPACE_ID_RE = /^(?:wrk|wk)_[A-Za-z0-9]+$/++const ROLLING_WINDOW_MINUTES = 300 // 5h+const WEEKLY_WINDOW_MINUTES = 10_080+const MONTHLY_WINDOW_MINUTES = 43_200++/**+ * Users paste either the whole `Cookie:` header or just the bare token value. A bare token is+ * wrapped rather than rejected — otherwise the cookie looks non-empty, carries no recognized+ * name, and fails with a confusing 401.+ */+export function normalizeCookieInput(raw: string): string {+ const trimmed = raw.trim().replace(/^Cookie:\s*/i, '')+ if (!trimmed) return ''+ if (trimmed.includes(';') || /^(?:auth|__Host-auth)=/i.test(trimmed)) return trimmed+ // A bare value with no `=` at all is a token; anything else is left alone so it fails+ // predictably instead of being silently mangled into malformed auth.+ return trimmed.includes('=') ? trimmed : `auth=${trimmed}`+}++/** Keep only the auth cookies, so unrelated site cookies are never transmitted. */+export function filterAuthCookie(cookie: string): string | null {+ const kept: string[] = []+ for (const part of cookie.split(';')) {+ const eq = part.indexOf('=')+ if (eq === -1) continue+ const name = part.slice(0, eq).trim()+ if (AUTH_COOKIE_NAMES.has(name)) kept.push(`${name}=${part.slice(eq + 1).trim()}`)+ }+ return kept.length > 0 ? kept.join('; ') : null+}++/**+ * The balanced `{...}` block assigned to `key`, skipping React Flight's `$R[N]=` reference+ * tokens between the colon and the brace.+ *+ * A key can appear several times — once with real data and once as `null` inside another+ * component's props — so this keeps scanning until it finds a block carrying BOTH+ * `usagePercent` and `resetInSec` as direct (depth-1) numeric fields. Matching on the key alone+ * would happily return a billing-context object that merely shares the name.+ */+export function extractUsageBlock(text: string, key: string): string | null {+ const keyRegex = new RegExp(`\\b${key}\\b\\s*:`, 'g')+ let match: RegExpExecArray | null++ while ((match = keyRegex.exec(text)) !== null) {+ const from = match.index + match[0].length+ // Short window only, so a `{` belonging to the NEXT occurrence is never picked up.+ const braceOffset = text.slice(from, from + 30).indexOf('{')+ if (braceOffset === -1) continue // e.g. `monthlyUsage:null`++ const open = from + braceOffset+ let depth = 0+ let block: string | null = null+ for (let i = open; i < text.length; i++) {+ if (text[i] === '{') depth+++ else if (text[i] === '}') {+ depth--+ if (depth === 0) {+ block = text.slice(open, i + 1)+ break+ }+ }+ }+ if (!block) continue++ if (topLevelNumber(block, 'usagePercent') !== null && topLevelNumber(block, 'resetInSec') !== null) {+ return block+ }+ }+ return null+}++/**+ * A numeric field at depth 1 of `objText`. Depth matters: without it, the first textual match+ * wins regardless of nesting, so a sub-object sharing the field name returns the wrong number.+ */+export function topLevelNumber(objText: string, field: string): number | null {+ const re = new RegExp(`^\\b${field}\\b\\s*:\\s*(-?[0-9]+(?:\\.[0-9]+)?)`)+ let depth = 0+ for (let i = 0; i < objText.length; i++) {+ const ch = objText[i]+ if (ch === '{') {+ depth+++ continue+ }+ if (ch === '}') {+ depth--+ continue+ }+ if (depth === 1) {+ const m = re.exec(objText.slice(i, i + field.length + 30))+ if (m) {+ const n = Number.parseFloat(m[1])+ return Number.isFinite(n) ? n : null+ }+ }+ }+ return null+}++/**+ * `resetInSec` is a DURATION from now, not a timestamp. A negative or absurd value means the+ * parse latched onto the wrong number, so it is rejected rather than rendered as a reset a+ * decade away — a wrong number displayed confidently is worse than no number.+ */+const MAX_RESET_SECONDS = 60 * 60 * 24 * 90++function resetToTimestamp(seconds: number | null): number | null {+ if (seconds === null || seconds < 0 || seconds > MAX_RESET_SECONDS) return null+ return Date.now() + seconds * 1000+}++function limitFrom(+ block: string | null,+ kind: string,+ group: string,+ windowMinutes: number+): UsageLimit | null {+ if (!block) return null+ const percent = topLevelNumber(block, 'usagePercent')+ if (percent === null) return null+ return {+ kind,+ group,+ usedPercent: Math.min(100, Math.max(0, percent)),+ severity: null,+ resetsAt: resetToTimestamp(topLevelNumber(block, 'resetInSec')),+ windowMinutes,+ scopeLabel: null,+ isActive: false+ }+}++/**+ * Parse the dashboard page. Returns [] when nothing usable is found — the caller turns that+ * into an 'error', because a configured provider that yields nothing is broken, not idle.+ */+export function parseOpencodePage(text: string): UsageLimit[] {+ // A page far larger than any dashboard means we fetched something else (a redirect to a+ // marketing page, an error shell); refuse rather than burn time brace-scanning it.+ if (!text || text.length > 10_000_000) return []++ const rolling = limitFrom(extractUsageBlock(text, 'rollingUsage'), 'session', 'session', ROLLING_WINDOW_MINUTES)+ const weekly = limitFrom(extractUsageBlock(text, 'weeklyUsage'), 'weekly_all', 'weekly', WEEKLY_WINDOW_MINUTES)+ const monthly = limitFrom(extractUsageBlock(text, 'monthlyUsage'), 'monthly_all', 'monthly', MONTHLY_WINDOW_MINUTES)++ // Rolling and weekly are the two every plan has. If neither parsed, the format moved under+ // us and a lone `monthly` is more likely a coincidental match than real data.+ if (!rolling && !weekly) return []+ return [rolling, weekly, monthly].filter((l): l is UsageLimit => l !== null)+}++/** Workspace ids embedded in the server-function response. */+export function parseWorkspaceIds(text: string): string[] {+ const out: string[] = []+ for (const m of text.matchAll(/\bid\s*:\s*["']((?:wrk|wk)_[a-zA-Z0-9]+)["']/g)) {+ if (!out.includes(m[1])) out.push(m[1])+ }+ return out+}++export function isValidWorkspaceId(id: string): boolean {+ return WORKSPACE_ID_RE.test(id)+}++function snapshot(limits: UsageLimit[], status: ProviderUsage['status']): ProviderUsage {+ return { provider: 'opencode', limits, account: null, updatedAt: Date.now(), status }+}++async function get(url: string, headers: Record<string, string>): Promise<Response | null> {+ const ctrl = new AbortController()+ const t = setTimeout(() => ctrl.abort(), FETCH_TIMEOUT_MS)+ try {+ return await fetch(url, { headers, signal: ctrl.signal })+ } catch {+ return null+ } finally {+ clearTimeout(t)+ }+}++/**+ * opencode usage.+ *+ * Status semantics are deliberately sharp here: no cookie ⇒ 'unavailable' (nothing to show);+ * cookie present but nothing parsed ⇒ 'error' (something we depend on changed). Collapsing+ * those two would let a broken scraper masquerade as an unconfigured provider.+ */+export async function fetchOpencodeUsage(+ cookie: string | null,+ workspaceIdOverride?: string+): Promise<ProviderUsage> {+ const normalized = normalizeCookieInput(cookie ?? '')+ const authCookie = normalized ? filterAuthCookie(normalized) : null+ if (!authCookie) return snapshot([], 'unavailable')++ try {+ const headers = { cookie: authCookie, accept: 'text/html,application/json' }++ // A user-supplied workspace id skips discovery entirely — the escape hatch for when the+ // hardcoded server-function hash goes stale.+ let workspaceIds: string[] = []+ const override = workspaceIdOverride?.trim()+ if (override) {+ if (!isValidWorkspaceId(override)) return snapshot([], 'error')+ workspaceIds = [override]+ } else {+ const res = await get(`${SERVER_URL}?id=${WORKSPACES_SERVER_ID}`, {+ ...headers,+ 'x-server-id': WORKSPACES_SERVER_ID,+ 'x-server-instance': `server-fn:${WORKSPACES_SERVER_ID}`+ })+ if (!res) return snapshot([], 'error')+ if (res.status === 401 || res.status === 403) return snapshot([], 'unavailable')+ if (!res.ok) return snapshot([], 'error')+ workspaceIds = parseWorkspaceIds(await res.text())+ }+ if (workspaceIds.length === 0) return snapshot([], 'error')++ // Several workspaces can be visible; the first that yields usable numbers wins.+ for (const id of workspaceIds) {+ const page = await get(`${BASE_URL}/workspace/${id}/go`, headers)+ if (!page) continue+ if (page.status === 401 || page.status === 403) return snapshot([], 'unavailable')+ if (!page.ok) continue+ const limits = parseOpencodePage(await page.text())+ if (limits.length > 0) return snapshot(limits, 'ok')+ }++ // Authenticated, workspaces found, nothing parsed: the page shape moved. Report it.+ return snapshot([], 'error')+ } catch {+ return snapshot([], 'error')+ }+}diff --git a/src/core/usage/provider-cookie.ts b/src/core/usage/provider-cookie.tsnew file mode 100644index 000000000..6e9bc60f2--- /dev/null+++ b/src/core/usage/provider-cookie.ts@@ -0,0 +1,68 @@+// Storage for user-pasted browser cookies, per provider.+//+// Some providers (MiniMax, opencode) publish no CLI credential on disk — their quota lives+// behind a web console session — so the only way to read it is to replay a cookie the user+// copies out of DevTools.+//+// These deliberately do NOT live in settings.json. That file is written with default+// permissions and is treated throughout the app as CONFIG — the `claudeAccounts` list sits+// there precisely because an account list is config, not a credential. A session cookie is the+// opposite: a live bearer credential for someone's account. It gets its own file at 0600 and+// never appears in a config blob that is world-readable, copied between machines, or pasted+// into a bug report.+//+// Generalized from the MiniMax-only version once opencode needed exactly the same thing; the+// file naming is unchanged (`<provider>-cookie.json`), so an already-stored MiniMax cookie is+// still found.+import { promises as fs } from 'fs'+import path from 'path'+import { platform } from '../platform'++/** Owner read/write only. The whole reason these are separate files. */+const MODE = 0o600++/** Providers whose usage is read with a pasted browser cookie. */+export const COOKIE_PROVIDERS = ['minimax', 'opencode'] as const+export type CookieProvider = (typeof COOKIE_PROVIDERS)[number]++export function isCookieProvider(v: unknown): v is CookieProvider {+ return typeof v === 'string' && (COOKIE_PROVIDERS as readonly string[]).includes(v)+}++function file(provider: CookieProvider): string {+ return path.join(platform().userDataDir, `${provider}-cookie.json`)+}++/** The stored cookie header, or null when this provider has not been configured. */+export async function readProviderCookie(provider: CookieProvider): Promise<string | null> {+ try {+ const raw = await fs.readFile(file(provider), 'utf-8')+ const j = JSON.parse(raw) as Record<string, unknown>+ return typeof j.cookie === 'string' && j.cookie.trim() ? j.cookie : null+ } catch {+ return null+ }+}++/**+ * Store (or, with an empty value, clear) a provider's cookie. Written to a temp file first and+ * renamed, so a crash mid-write cannot leave a half-written credential behind — and the temp+ * file is created with the restricted mode too, since a rename preserves the source's mode.+ */+export async function writeProviderCookie(provider: CookieProvider, cookie: string): Promise<void> {+ const target = file(provider)+ if (!cookie.trim()) {+ await fs.rm(target, { force: true })+ return+ }+ const tmp = `${target}.tmp`+ await fs.writeFile(tmp, JSON.stringify({ cookie }), { encoding: 'utf-8', mode: MODE })+ await fs.rename(tmp, target)+ // Belt and braces: a temp file left by an earlier run would keep its own mode.+ await fs.chmod(target, MODE).catch(() => undefined)+}++/** Whether a cookie is stored — for the settings UI, which must never read the value back. */+export async function hasProviderCookie(provider: CookieProvider): Promise<boolean> {+ return (await readProviderCookie(provider)) !== null+}diff --git a/src/core/usage/usage-service.ts b/src/core/usage/usage-service.tsindex 5c2257bcc..54f9afec5 100644--- a/src/core/usage/usage-service.ts+++ b/src/core/usage/usage-service.ts@@ -24,7 +24,14 @@ import { fetchGeminiUsage } from './gemini-usage'import { fetchGrokUsage } from './grok-usage'import { fetchKimiUsage } from './kimi-usage'import { fetchMinimaxUsage } from './minimax-usage'-import { readMinimaxCookie, writeMinimaxCookie, hasMinimaxCookie } from './minimax-cookie'+import { fetchOpencodeUsage } from './opencode-usage'+import {+ COOKIE_PROVIDERS,+ isCookieProvider,+ readProviderCookie,+ writeProviderCookie,+ hasProviderCookie+} from './provider-cookie'import { usageCredsPaths } from '../claude-accounts-core'import { claudeConfigDirFor } from '../claude-config-dir'import { platform } from '../platform'@@ -53,8 +60,9 @@ const OTHER_PROVIDERS: { id: string; fetch: () => Promise<ProviderUsage> }[] = [{ id: 'gemini', fetch: fetchGeminiUsage },{ id: 'grok', fetch: fetchGrokUsage },{ id: 'kimi', fetch: fetchKimiUsage },- // MiniMax has no on-disk CLI credential; its cookie is read from our own 0600 store.- { id: 'minimax', fetch: async () => fetchMinimaxUsage(await readMinimaxCookie()) }+ // These two publish no on-disk CLI credential; their cookies come from our own 0600 store.+ { id: 'minimax', fetch: async () => fetchMinimaxUsage(await readProviderCookie('minimax')) },+ { id: 'opencode', fetch: async () => fetchOpencodeUsage(await readProviderCookie('opencode')) }]/** Parse a credentials JSON blob; tokens may sit at top level or under `claudeAiOauth`. */@@ -301,13 +309,20 @@ export function startUsageService(opts: UsageServiceOptions = {}): UsageService// The cookie is write-only from the UI's perspective: it can be set and cleared, and the UI// can ask WHETHER one is stored, but there is no channel that hands the value back. A// credential that never crosses the boundary cannot be leaked by whatever reads it.- platform().handle(IPC.usageSetMinimaxCookie, async (cookie: string) => {- await writeMinimaxCookie(typeof cookie === 'string' ? cookie : '')+ platform().handle(IPC.usageSetProviderCookie, async (provider: string, cookie: string) => {+ // The provider id arrives from the renderer and is used to build a file path — validate it+ // against the known set rather than trusting it into `path.join`.+ if (!isCookieProvider(provider)) return false+ await writeProviderCookie(provider, typeof cookie === 'string' ? cookie : '')// Drop the cache so the next read reflects the new cookie instead of the old snapshot.providersAt = 0- return hasMinimaxCookie()+ return hasProviderCookie(provider)+ })+ platform().handle(IPC.usageCookieProviders, async () => {+ const stored: Record<string, boolean> = {}+ for (const p of COOKIE_PROVIDERS) stored[p] = await hasProviderCookie(p)+ return stored})- platform().handle(IPC.usageHasMinimaxCookie, () => hasMinimaxCookie())platform().handle(IPC.usageProviders, (force?: boolean) => {if (!force && providersAt && Date.now() - providersAt < REFETCH_DEBOUNCE_MS) {diff --git a/src/preload/index.ts b/src/preload/index.tsindex e47e46d05..6dc8d7749 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -326,8 +326,9 @@ const api: NodeTerminalApi = {fetch: (accountId?: string) => ipcRenderer.invoke(IPC.usageFetch, accountId),refresh: (accountId?: string) => ipcRenderer.invoke(IPC.usageRefresh, accountId),providers: (force?: boolean) => ipcRenderer.invoke(IPC.usageProviders, force),- setMinimaxCookie: (cookie: string) => ipcRenderer.invoke(IPC.usageSetMinimaxCookie, cookie),- hasMinimaxCookie: () => ipcRenderer.invoke(IPC.usageHasMinimaxCookie),+ setProviderCookie: (provider: string, cookie: string) =>+ ipcRenderer.invoke(IPC.usageSetProviderCookie, provider, cookie),+ cookieProviders: () => ipcRenderer.invoke(IPC.usageCookieProviders),onUpdate: (listener) => {const handler = (_e: unknown, payload: Parameters<typeof listener>[0]) => listener(payload)ipcRenderer.on(IPC.usageUpdate, handler)diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex 13638fa5b..9ec743dd7 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -227,8 +227,8 @@ export function buildStubApi(): Omit<// Empty, not a reject: "no providers configured" is a real answer and the popover// renders it as nothing. This one needs no cast — the honest type already fits.providers: () => Promise.resolve([]),- setMinimaxCookie: U('usage.setMinimaxCookie'),- hasMinimaxCookie: () => Promise.resolve(false),+ setProviderCookie: U('usage.setProviderCookie'),+ cookieProviders: () => Promise.resolve({}),onUpdate: noopUnsub},claude: {diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex a3b7b6524..4d2c2281b 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -486,9 +486,10 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {client.request(IPC.usageRefresh, accountId) as Promise<ClaudeUsage>,providers: (force?: boolean) =>client.request(IPC.usageProviders, force) as Promise<ProviderUsage[]>,- setMinimaxCookie: (cookie: string) =>- client.request(IPC.usageSetMinimaxCookie, cookie) as Promise<boolean>,- hasMinimaxCookie: () => client.request(IPC.usageHasMinimaxCookie) as Promise<boolean>,+ setProviderCookie: (provider: string, cookie: string) =>+ client.request(IPC.usageSetProviderCookie, provider, cookie) as Promise<boolean>,+ cookieProviders: () =>+ client.request(IPC.usageCookieProviders) as Promise<Record<string, boolean>>,onUpdate: (listener) => client.subscribe(IPC.usageUpdate, listener as Listener)}}diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex f449cea25..6e263ae14 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -46,26 +46,107 @@ const ROWS = {'shift tab']},- minimax: {- title: 'MiniMax usage',- keywords: ['minimax', 'usage', 'quota', 'cookie', 'limits', 'provider']+ cookieProviders: {+ title: 'Usage from web consoles',+ keywords: [+ 'minimax',+ 'opencode',+ 'usage',+ 'quota',+ 'cookie',+ 'limits',+ 'provider',+ 'session'+ ]}}const ENTRIES = Object.values(ROWS)+/**+ * Providers that publish no CLI credential — their quota lives behind a web console session, so+ * the user pastes a cookie. Each row is write-only: it can store or clear a value and can see+ * WHETHER one is stored, but the secret is never read back into the UI.+ */+const COOKIE_PROVIDER_ROWS = [+ {+ id: 'minimax',+ label: 'MiniMax',+ description:+ "MiniMax exposes no CLI credential, so its quota is read with your console session. Open platform.minimax.io/console/usage, copy the request's Cookie header from DevTools, and paste it here.",+ placeholder: 'Cookie: _token=…'+ },+ {+ id: 'opencode',+ label: 'opencode',+ description:+ 'opencode publishes no usage API, so the numbers are read from your dashboard page. Open opencode.ai, copy the Cookie header from DevTools, and paste it here. Because this reads a page rather than an API, it can stop working when opencode changes their site — it will report an error rather than silently showing nothing.',+ placeholder: 'auth=…'+ }+] as const++function CookieProviderRow({+ id,+ label,+ description,+ placeholder,+ stored,+ onChange+}: {+ id: string+ label: string+ description: string+ placeholder: string+ stored: boolean+ onChange: (stored: boolean) => void+}): React.JSX.Element {+ const [value, setValue] = useState('')+ const save = async (next: string): Promise<void> => {+ onChange(await window.nodeTerminal.usage.setProviderCookie(id, next))+ // Never keep the secret in component state once it has been handed over.+ setValue('')+ }+ return (+ <FieldRow+ label={label}+ description={description}+ note={+ stored+ ? 'Stored in a file only your user can read, never in settings.json. It is not shown again — paste a fresh one when your session expires.'+ : 'This is a live session credential. It is stored in a 0600 file, not in settings.json, and is never read back into the UI.'+ }+ control={+ <div className="flex items-center gap-2">+ <input+ type="password"+ className="input w-64"+ placeholder={stored ? '•••••••• stored' : placeholder}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ autoComplete="off"+ spellCheck={false}+ />+ <Button onClick={() => void save(value)} disabled={!value.trim()}>+ Save+ </Button>+ {stored && <Button onClick={() => void save('')}>Clear</Button>}+ </div>+ }+ />+ )+}+export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.Element {const settings = useSettings((s) => s.settings)const update = useSettings((s) => s.update)- // The MiniMax cookie is write-only across the IPC boundary: we can ask WHETHER one is stored- // and set/clear it, but never read the value back — so the input starts empty even when one- // is configured, and is cleared the moment it is handed over.- const [minimaxCookie, setMinimaxCookie] = useState('')- const [minimaxSaved, setMinimaxSaved] = useState(false)+ // Cookie-based providers are write-only across the IPC boundary: we can ask WHICH have one+ // stored and set/clear them, but never read a value back — so an input starts empty even when+ // one is configured, and is cleared the moment it is handed over.+ const [cookieStored, setCookieStored] = useState<Record<string, boolean>>({})useEffect(() => {if (!isActive) returnlet cancelled = false- void window.nodeTerminal.usage.hasMinimaxCookie().then((v) => {- if (!cancelled) setMinimaxSaved(v)+ void window.nodeTerminal.usage.cookieProviders().then((v) => {+ if (!cancelled) setCookieStored(v)})return () => {cancelled = true@@ -138,49 +219,15 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.El})}</div></SearchableRow>- <SearchableRow {...ROWS.minimax}>- <FieldRow- label="Browser cookie"- description="MiniMax exposes no CLI credential, so its quota is read with your console session. In the browser, open platform.minimax.io/console/usage, copy the request's Cookie header, and paste it here."- note={- minimaxSaved- ? 'Stored outside settings.json, in a file only your user can read. It is never shown again — paste a fresh one when your session expires.'- : 'This is a live session credential. It is stored in a 0600 file, not in settings.json, and is never read back into the UI.'- }- control={- <div className="flex items-center gap-2">- <input- type="password"- className="input w-64"- placeholder={minimaxSaved ? '•••••••• stored' : 'Cookie: _token=…'}- value={minimaxCookie}- onChange={(e) => setMinimaxCookie(e.target.value)}- autoComplete="off"- spellCheck={false}- />- <Button- onClick={async () => {- setMinimaxSaved(await window.nodeTerminal.usage.setMinimaxCookie(minimaxCookie))- // Never keep the secret in component state once it has been handed over.- setMinimaxCookie('')- }}- disabled={!minimaxCookie.trim()}- >- Save- </Button>- {minimaxSaved && (- <Button- onClick={async () => {- setMinimaxSaved(await window.nodeTerminal.usage.setMinimaxCookie(''))- setMinimaxCookie('')- }}- >- Clear- </Button>- )}- </div>- }- />+ <SearchableRow {...ROWS.cookieProviders}>+ {COOKIE_PROVIDER_ROWS.map((p) => (+ <CookieProviderRow+ key={p.id}+ {...p}+ stored={!!cookieStored[p.id]}+ onChange={(stored) => setCookieStored((m) => ({ ...m, [p.id]: stored }))}+ />+ ))}</SearchableRow><SearchableRow {...ROWS.permissionMode}><FieldRowdiff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 44f573a38..395774a4a 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -75,10 +75,11 @@ export const IPC = {usageUpdate: 'usage:update',/** Non-Claude providers (codex, …) as one list; Claude keeps its own account-aware channels. */usageProviders: 'usage:providers',- /** Store/clear the MiniMax browser cookie. Write-only: there is no channel that reads it back. */- usageSetMinimaxCookie: 'usage:set-minimax-cookie',- /** Whether a MiniMax cookie is stored — lets the UI show state without handling the value. */- usageHasMinimaxCookie: 'usage:has-minimax-cookie',+ /** Store/clear a provider's browser cookie (minimax, opencode). Write-only: no channel reads+ * it back. */+ usageSetProviderCookie: 'usage:set-provider-cookie',+ /** Which cookie providers have one stored — lets the UI show state without handling secrets. */+ usageCookieProviders: 'usage:cookie-providers',contextUpdate: 'context:update',contextEnsure: 'context:ensure',// Team presence (docs/team-presence.md). `presence:hello` is a REQUEST: its response tells thediff --git a/src/shared/types.ts b/src/shared/types.tsindex 121dd8b68..1ee74d4bc 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1026,11 +1026,11 @@ export interface UsageApi {* `force` to bypass the cache debounce. Providers that aren't signed in come back* 'unavailable' rather than being omitted, so the caller can tell "off" from "broken". */providers(force?: boolean): Promise<ProviderUsage[]>- /** Store (or, with an empty string, clear) the MiniMax browser cookie. Resolves to whether one+ /** Store (or, with an empty string, clear) a provider's browser cookie. Resolves to whether one* is now stored. Write-only by design — nothing reads the value back across this boundary. */- setMinimaxCookie(cookie: string): Promise<boolean>- /** Whether a MiniMax cookie is stored, so the UI can show state without handling the secret. */- hasMinimaxCookie(): Promise<boolean>+ setProviderCookie(provider: string, cookie: string): Promise<boolean>+ /** Which cookie-based providers have one stored, so the UI shows state without the secret. */+ cookieProviders(): Promise<Record<string, boolean>>/** Fires whenever main pushes a new snapshot (poll/refresh). Returns unsubscribe. */onUpdate(listener: (usage: ClaudeUsage) => void): () => void}