Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@
"@poracode/ssh-bridge": "file:native/ssh-bridge",
"@sentry/electron": "^7.15.0",
"@sentry/node": "10.63.0",
"@sindresorhus/slugify": "^2.2.1",
"@tanstack/react-router": "^1.170.17",
"@tanstack/react-virtual": "^3.14.5",
"@tiptap/extensions": "^3.27.1",
Expand Down
209 changes: 113 additions & 96 deletions packages/agents-usage/src/collectors/commandcode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,113 +2,107 @@ import { describe, expect, it } from "vitest";
import { createFakeHost, FAKE_NOW_MS } from "../testHost";
import {
collectCommandCode,
COMMANDCODE_AUTH_SESSION_ENDPOINT,
COMMANDCODE_BILLING_CREDITS_ENDPOINT,
COMMANDCODE_BILLING_SUBSCRIPTIONS_ENDPOINT,
COMMANDCODE_USAGE_SUMMARY_ENDPOINT,
COMMANDCODE_WHOAMI_ENDPOINT,
formatCommandCodePlanLabel,
isCommandCodeSessionLive,
parseCommandCodeUsage,
} from "./commandcode";

const PERIOD_START = "2026-06-01T03:37:07.000Z";
const PERIOD_END = "2026-07-01T03:37:07.000Z";

const CREDITS_BODY = JSON.stringify({
credits: {
belowThreshold: false,
creditThreshold: 0,
monthlyCredits: 9.9924,
purchasedCredits: 0,
premiumMonthlyCredits: 0,
opensourceMonthlyCredits: 9.9924,
freeCredits: 0,
},
});

const SUMMARY_BODY = JSON.stringify({
totalCount: 25,
totalCost: 0.0076,
averageCost: 0.000304,
successRate: 100,
completedCount: 25,
failedCount: 0,
totalTokensIn: "172284",
totalTokensOut: "1787",
totalTokens: "174071",
totalCredits: 0.0076,
totalFreeCredits: 0,
totalMonthlyCredits: 0.0076,
totalPurchasedCredits: 0,
});

const SUBSCRIPTIONS_BODY = JSON.stringify({
success: true,
data: {
status: "active",
planId: "individual-go",
currentPeriodStart: "2026-06-01T03:37:07.000Z",
currentPeriodEnd: "2026-07-01T03:37:07.000Z",
cancelAtPeriodEnd: false,
currentPeriodStart: PERIOD_START,
currentPeriodEnd: PERIOD_END,
},
});

function endpointWith(endpoint: string, params: Record<string, string | undefined>): string {
const query = new URLSearchParams();
for (const [key, value] of Object.entries(params)) {
if (value) query.set(key, value);
}
return `${endpoint}?${query.toString()}`;
}

describe("formatCommandCodePlanLabel", () => {
it("maps known planIds to display names", () => {
it("maps the v1.4.1 plan ids to CLI display names", () => {
expect(formatCommandCodePlanLabel("individual-go")).toBe("Go");
expect(formatCommandCodePlanLabel("individual-pro")).toBe("Pro");
expect(formatCommandCodePlanLabel("individual-max")).toBe("Max");
expect(formatCommandCodePlanLabel("individual-provider")).toBe("Provider");
expect(formatCommandCodePlanLabel("individual-ultra")).toBe("Ultra");
expect(formatCommandCodePlanLabel("teams-pro")).toBe("Teams Pro");
expect(formatCommandCodePlanLabel("individual_go_annual")).toBe("Go");
});

it("falls back to the raw value for unknown planIds", () => {
it("falls back to the raw value for unknown plan ids", () => {
expect(formatCommandCodePlanLabel("weird-plan")).toBe("weird-plan");
});

it("returns undefined for missing/blank input", () => {
expect(formatCommandCodePlanLabel(undefined)).toBeUndefined();
expect(formatCommandCodePlanLabel(" ")).toBeUndefined();
});
});

describe("parseCommandCodeUsage", () => {
it("maps the studio responses into a single monthly usd bar", () => {
it("mirrors the CLI's active-plan credit-pool calculation", () => {
const snap = parseCommandCodeUsage(
JSON.parse(CREDITS_BODY),
JSON.parse(SUMMARY_BODY),
JSON.parse(SUBSCRIPTIONS_BODY),
FAKE_NOW_MS,
{ user: { email: "dev@example.com" } },
);

expect(snap.providerId).toBe("commandcode");
expect(snap.status).toBe("ok");
expect(snap.plan).toBe("Go");

const w = snap.windows[0]!;
expect(w.id).toBe("monthly");
expect(w.unit).toBe("usd");
expect(w.currency).toBe("USD");
expect(w.used).toBeCloseTo(0.0076);
expect(w.limit).toBeCloseTo(10.0);
expect(w.usedPercent).toBeCloseTo(0.076);
expect(w.resetsAt).toBe(Date.parse("2026-07-01T03:37:07.000Z"));

// The bar already conveys the full picture, so the snapshot intentionally
// carries no `cost`/`credits`/`tokens` fields — surfacing them in the
// panel's meta block would duplicate the bar.
expect(snap).toMatchObject({
providerId: "commandcode",
status: "ok",
plan: "Go",
authenticatedAs: "dev@example.com",
});
const window = snap.windows[0]!;
expect(window.id).toBe("monthly");
expect(window.unit).toBe("usd");
expect(window.currency).toBe("USD");
expect(window.used).toBeCloseTo(0.0076);
expect(window.limit).toBe(10);
expect(window.usedPercent).toBeCloseTo(0.076);
expect(window.resetsAt).toBe(Date.parse(PERIOD_END));
expect(snap.credits).toBeUndefined();
expect(snap.cost).toBeUndefined();
expect(snap.tokens).toBeUndefined();
});

it("emits only the window when the plan is missing", () => {
it("reconstructs an unknown plan pool from remaining credits plus spend", () => {
const snap = parseCommandCodeUsage(
{ credits: { monthlyCredits: 5 } },
{ credits: { monthlyCredits: 5, purchasedCredits: 1, freeCredits: 0.5 } },
{ totalCost: 2.5 },
{},
FAKE_NOW_MS,
);
expect(snap.status).toBe("ok");
expect(snap.plan).toBeUndefined();
expect(snap.windows[0]!.used).toBe(2.5);
expect(snap.windows[0]!.limit).toBe(7.5);
expect(snap.credits).toBeUndefined();
expect(snap.cost).toBeUndefined();
expect(snap.windows[0]!.limit).toBe(9);
});

it("tolerates completely missing bodies without throwing", () => {
Expand All @@ -117,79 +111,102 @@ describe("parseCommandCodeUsage", () => {
expect(snap.windows[0]!.usedPercent).toBe(0);
expect(snap.windows[0]!.used).toBeUndefined();
expect(snap.windows[0]!.limit).toBeUndefined();
expect(snap.credits).toBeUndefined();
expect(snap.cost).toBeUndefined();
expect(snap.tokens).toBeUndefined();
});
});

describe("isCommandCodeSessionLive", () => {
it("returns true when /auth/get-session returns a non-null JSON object", async () => {
describe("collectCommandCode", () => {
it("returns auth-missing when no CLI API key resolves", async () => {
const snap = await collectCommandCode(createFakeHost());
expect(snap.status).toBe("auth-missing");
expect(snap.windows).toEqual([]);
});

it("uses the v1 bearer endpoints and current-period summary", async () => {
const requests: Array<{ url: string; authorization?: string }> = [];
const summaryEndpoint = endpointWith(COMMANDCODE_USAGE_SUMMARY_ENDPOINT, {
since: PERIOD_START,
});
const host = createFakeHost({
tokens: { commandcode: { accessToken: "cc-api-key" } },
routes: {
[COMMANDCODE_AUTH_SESSION_ENDPOINT]: {
body: JSON.stringify({ user: { id: "u1" }, plan: "go" }),
[COMMANDCODE_WHOAMI_ENDPOINT]: {
body: JSON.stringify({ success: true, user: { userName: "dev" }, org: null }),
},
[COMMANDCODE_BILLING_CREDITS_ENDPOINT]: { body: CREDITS_BODY },
[COMMANDCODE_BILLING_SUBSCRIPTIONS_ENDPOINT]: { body: SUBSCRIPTIONS_BODY },
[summaryEndpoint]: { body: SUMMARY_BODY },
},
onRequest: (request) => {
const authorization = request.headers?.Authorization;
requests.push({
url: request.url,
...(authorization ? { authorization } : {}),
});
},
});
await expect(isCommandCodeSessionLive(host.http, "cc_session=abc")).resolves.toBe(true);
});

it("returns false on a 200 + null body (signed out)", async () => {
const host = createFakeHost({
routes: { [COMMANDCODE_AUTH_SESSION_ENDPOINT]: { body: "null" } },
});
await expect(isCommandCodeSessionLive(host.http, "cc_session=abc")).resolves.toBe(false);
const snap = await collectCommandCode(host);

expect(snap).toMatchObject({ status: "ok", plan: "Go", authenticatedAs: "dev" });
expect(snap.windows[0]!.limit).toBe(10);
expect(requests.map((request) => request.url)).toContain(summaryEndpoint);
expect(requests.every((request) => request.authorization === "Bearer cc-api-key")).toBe(true);
});

it("returns false on a 401", async () => {
it("adds orgId to organization billing requests", async () => {
const orgId = "org-1";
const creditsEndpoint = endpointWith(COMMANDCODE_BILLING_CREDITS_ENDPOINT, { orgId });
const subscriptionsEndpoint = endpointWith(COMMANDCODE_BILLING_SUBSCRIPTIONS_ENDPOINT, {
orgId,
});
const summaryEndpoint = endpointWith(COMMANDCODE_USAGE_SUMMARY_ENDPOINT, {
orgId,
since: PERIOD_START,
});
const requested: string[] = [];
const host = createFakeHost({
routes: { [COMMANDCODE_AUTH_SESSION_ENDPOINT]: { status: 401, body: "" } },
tokens: { commandcode: { accessToken: "cc-api-key" } },
routes: {
[COMMANDCODE_WHOAMI_ENDPOINT]: {
body: JSON.stringify({ user: { userName: "dev" }, org: { id: orgId } }),
},
[creditsEndpoint]: { body: CREDITS_BODY },
[subscriptionsEndpoint]: { body: SUBSCRIPTIONS_BODY },
[summaryEndpoint]: { body: SUMMARY_BODY },
},
onRequest: (request) => requested.push(request.url),
});
await expect(isCommandCodeSessionLive(host.http, "cc_session=abc")).resolves.toBe(false);
});

it("returns false on an empty cookie", async () => {
const host = createFakeHost();
await expect(isCommandCodeSessionLive(host.http, "")).resolves.toBe(false);
expect((await collectCommandCode(host)).status).toBe("ok");
expect(requested).toEqual(
expect.arrayContaining([creditsEndpoint, subscriptionsEndpoint, summaryEndpoint]),
);
});
});

describe("collectCommandCode", () => {
it("returns auth-missing when no cookie has been stored", async () => {
const host = createFakeHost();
const snap = await collectCommandCode(host);
expect(snap.status).toBe("auth-missing");
expect(snap.windows).toEqual([]);
it.each([401, 403])("returns auth-missing when the API key is rejected (%s)", async (status) => {
const host = createFakeHost({
tokens: { commandcode: { accessToken: "expired" } },
routes: { [COMMANDCODE_WHOAMI_ENDPOINT]: { status, body: "" } },
});
expect((await collectCommandCode(host)).status).toBe("auth-missing");
});

it("collects usage from the studio endpoints when a live cookie is present", async () => {
it("returns rate-limited on HTTP 429", async () => {
const host = createFakeHost({
secrets: { commandcode: { cookie: "cc_session=abc" } },
routes: {
[COMMANDCODE_AUTH_SESSION_ENDPOINT]: {
body: JSON.stringify({ user: { id: "u1" } }),
},
[COMMANDCODE_BILLING_CREDITS_ENDPOINT]: { body: CREDITS_BODY },
[COMMANDCODE_USAGE_SUMMARY_ENDPOINT]: { body: SUMMARY_BODY },
[COMMANDCODE_BILLING_SUBSCRIPTIONS_ENDPOINT]: { body: SUBSCRIPTIONS_BODY },
},
tokens: { commandcode: { accessToken: "cc-api-key" } },
routes: { [COMMANDCODE_WHOAMI_ENDPOINT]: { status: 429, body: "" } },
});
const snap = await collectCommandCode(host);
expect(snap.status).toBe("ok");
expect(snap.plan).toBe("Go");
expect(snap.windows[0]!.unit).toBe("usd");
expect(snap.windows[0]!.used).toBeCloseTo(0.0076);
expect(snap.windows[0]!.limit).toBeCloseTo(10.0);
expect(snap.credits).toBeUndefined();
expect((await collectCommandCode(host)).status).toBe("rate-limited");
});

it("returns auth-missing when the session probe fails (expired cookie)", async () => {
it("returns an error when an API endpoint returns invalid JSON", async () => {
const host = createFakeHost({
secrets: { commandcode: { cookie: "cc_session=expired" } },
routes: { [COMMANDCODE_AUTH_SESSION_ENDPOINT]: { status: 401, body: "" } },
tokens: { commandcode: { accessToken: "cc-api-key" } },
routes: { [COMMANDCODE_WHOAMI_ENDPOINT]: { body: "not-json" } },
});
expect(await collectCommandCode(host)).toMatchObject({
status: "error",
error: "invalid JSON response",
});
const snap = await collectCommandCode(host);
expect(snap.status).toBe("auth-missing");
});
});
Loading