Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Address review: v1 auth.json, empty auth content, a 200 without meters
BunBnnuy59edbbf4be74
diff --git a/server/plan-usage.test.ts b/server/plan-usage.test.tsindex d1c0a40e68..879014e20e 100644--- a/server/plan-usage.test.ts+++ b/server/plan-usage.test.ts@@ -32,6 +32,7 @@ function jsonResponse(body: unknown, status = 200): PlanResponse {};}+/** A plan account for one driver, named as the panel names it. */function account(driver: PlanAccount["driver"], extras: Partial<PlanAccount> = {}): PlanAccount {const name = driver === "claude" ? "Claude" : driver === "codex" ? "Codex" : driver === "opencode" ? "OpenCode" : "Grok";return {@@ -499,12 +500,14 @@ describe("plan usage fetcher", () => {]);});+/** An OpenCode instance becomes an account under the driver the panel knows. */it("lists an OpenCode instance under the key its environment carries", () => {expect(planAccountsFromInstances({open: { driver: "opencodeGo", environment: { OPENCODE_API_KEY: SECRET } },})).toEqual([{ id: "open", name: "OpenCode", driver: "opencode", environment: { OPENCODE_API_KEY: SECRET } }]);});+/** The saved key is the Bearer, and the three meters land in their slots. */it("reads OpenCode Go's allowance with the key saved on the instance", async () => {const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({usage: {@@ -532,6 +535,7 @@ describe("plan usage fetcher", () => {expect(JSON.stringify(report)).not.toContain(SECRET);});+/** With no key, the CLI login is used, and the Go entry wins over the Zen one. */it("takes the CLI's OpenCode Go login when no key is saved, before the Zen one", async () => {const goLogin = "opencode-go-fixture-login";const zenLogin = "opencode-zen-fixture-login";@@ -548,6 +552,29 @@ describe("plan usage fetcher", () => {expect(fetchImpl.mock.calls.map((call) => call[1].headers.Authorization)).toEqual([`Bearer ${goLogin}`, `Bearer ${zenLogin}`]);});+ /** The row reads the login the CLI keeps when the environment carries no key and no auth content. */+ it("falls back to the CLI's auth.json when OPENCODE_AUTH_CONTENT is empty", async () => {+ const login = "opencode-file-fixture-login";+ const fetchImpl = vi.fn<PlanFetch>(async () => jsonResponse({ usage: { rolling: { status: "ok", percent: 2, resetsAt: null } } }));+ await fetchPlanUsage([account("opencode", { environment: { OPENCODE_AUTH_CONTENT: " " } })], {+ fetch: fetchImpl,+ now: () => NOW,+ credentials: fileCredentialReader({ now: () => NOW, env: { HOME: tmpdir() }, readText: () => JSON.stringify({ "opencode-go": { access: login } }) }),+ });+ expect(fetchImpl.mock.calls[0]?.[1].headers.Authorization).toBe(`Bearer ${login}`);+ });++ /** A 200 that carries no meter is an unreadable answer, not an empty allowance. */+ it("does not call a 200 without meters a working row", async () => {+ const report = await fetchPlanUsage([account("opencode", { environment: { OPENCODE_API_KEY: SECRET } })], {+ fetch: async () => jsonResponse({}),+ now: () => NOW,+ credentials: fileCredentialReader({ now: () => NOW, env: {}, readText: () => null }),+ });+ expect(report.providers[0]).toMatchObject({ ok: false, error: "OpenCode returned an unexpected usage response" });+ });++/** No Go plan is a quiet row; a refused key is named. */it("keeps the OpenCode row when there is no Go plan, and names a refused key", async () => {const credentials = fileCredentialReader({ now: () => NOW, env: {}, readText: () => null });const instances = [account("opencode", { environment: { OPENCODE_API_KEY: SECRET } })];diff --git a/server/plan-usage.ts b/server/plan-usage.tsindex 8636d6848b..32e61635a4 100644--- a/server/plan-usage.ts+++ b/server/plan-usage.ts@@ -248,8 +248,7 @@ export function parseOpenCodeUsage(body: unknown): PlanWindows {plan: rolling || weekly || monthly ? "Go" : null,fiveHour: rolling ?? closedWindow(),weekly: weekly ?? closedWindow(),- extra: monthly ? [extraLine("Monthly", monthly)] : [],- models: [],+ extra: monthly ? [extraLine("Monthly", monthly)] : [], models: [],};}@@ -855,7 +854,7 @@ function readGrokCredential(return sawExpired ? expiredCredential() : missingCredential();}-/** The key saved in Settings, or the login `opencode auth login` keeps in the CLI's data folder. */+/** The key saved in Settings, or the login `opencode auth login` keeps. `auth.json` is where OpenCode v1 wrote one; v2 keeps credentials in its own database, so this path covers installs migrated from v1 (the saved key covers v2). */function readOpenCodeCredential(env: NodeJS.ProcessEnv,readText: (path: string) => string | null,@@ -863,7 +862,7 @@ function readOpenCodeCredential(): PlanCredential {const key = secretString(env.OPENCODE_API_KEY);if (key) return { token: key, accountId: null, expired: false };- const raw = env.OPENCODE_AUTH_CONTENT ?? openCodeAuthText(env, readText);+ const raw = env.OPENCODE_AUTH_CONTENT?.trim() || openCodeAuthText(env, readText);const stored = asRecord(parseJson(raw));// A Go login lives under "opencode-go", a Zen one under "opencode"; the CLI lists Go first too.const entry = [stored?.["opencode-go"], stored?.opencode].map((value) => asRecord(value))@@ -1045,5 +1044,7 @@ async function fetchOpenCode(account: PlanAccount, token: string, deps: PlanUsagif (!result.ok || result.body === null || typeof result.body !== "object") {return errorRow(account, result.status === 0 || result.status >= 500 ? couldNotReach("opencode") : unexpectedUsage("opencode"));}- return okRow(account, parseOpenCodeUsage(result.body));+ const windows = parseOpenCodeUsage(result.body);+ // A 200 with no meter at all is not an allowance: it is an answer this row cannot read.+ return windows.plan ? okRow(account, windows) : errorRow(account, unexpectedUsage("opencode"));}