diff --git a/src/cli/account-api.ts b/src/cli/account-api.ts index 6505399bb..e8169c2e3 100644 --- a/src/cli/account-api.ts +++ b/src/cli/account-api.ts @@ -66,6 +66,12 @@ export interface AccountRow { */ paused?: boolean; pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails; + /** + * Native-main Codex row only, and only when the reader asked for it (`mainCredential`): + * `false` is the server's checked finding that no native Codex login exists, `true` that one + * does. Absent means unknown; no credential value is carried. + */ + hasCredential?: boolean; } export type ClassifyResult = { type: AccountType } | { error: string }; @@ -357,6 +363,18 @@ interface CodexAccountDto { quotaRefresh?: unknown; paused?: boolean; pauseDetails?: import("../types/account-auto-pause").AccountPauseDetails; + hasCredential?: unknown; + reauthReason?: unknown; +} + +/** + * Native-main credential presence as the server observed it. The server sends + * `hasCredential: false` also when it could not check (a passive read, an unavailable claim), + * and names `missing_credential` only for an absence it checked, so `false` needs both. + */ +function mainCredentialPresence(a: CodexAccountDto): Pick { + if (a.hasCredential === true) return { hasCredential: true }; + return a.hasCredential === false && a.reauthReason === "missing_credential" ? { hasCredential: false } : {}; } function projectQuota(quota: CodexQuotaDto | null | undefined): CodexQuotaDto | null { @@ -379,7 +397,7 @@ export async function fetchCodexRows( baseUrl: string, forceRefresh = false, includeQuota = forceRefresh, - options: { refreshAction?: boolean } = {}, + options: { refreshAction?: boolean; mainCredential?: boolean } = {}, ): Promise { const refreshAction = options.refreshAction === true; const accountsPath = `/api/codex-auth/accounts${refreshAction ? "/refresh" : forceRefresh ? "?refresh=1" : ""}`; @@ -437,6 +455,7 @@ export async function fetchCodexRows( paused: a.paused === true, // Unknown display details are dropped defensively; the pause state above is retained. pauseDetails: accountPauseDetailsSchema.safeParse(a.pauseDetails).data, + ...(options.mainCredential === true && a.id === "__main__" ? mainCredentialPresence(a) : {}), ...(includeQuota ? { quota: projectQuota(a.quota), quotaRefresh: projectCodexQuotaRefreshOutcome(a.quotaRefresh), diff --git a/src/server/hub-accounts.ts b/src/server/hub-accounts.ts index cc38c0928..d3dd53143 100644 --- a/src/server/hub-accounts.ts +++ b/src/server/hub-accounts.ts @@ -4,9 +4,10 @@ * `/v1/hub-state` promises a data key never sees quota or account identity, so this route takes * no data key. It takes one dedicated read key from OPENCODEX_HUB_ACCOUNTS_READ_KEY, and without * that variable the route does not exist. The response leaves here already reduced to the last - * four id characters, masked addresses and an allow-list of quota fields. + * four id characters, masked addresses and an allow-list of quota fields. The openai native-main + * slot is left out only when the server checked and found no native Codex login on this hub. */ -import { classifyAccount, fetchRows, type AccountRow } from "../cli/account-api"; +import { classifyAccount, fetchCodexRows, fetchRows, type AccountRow } from "../cli/account-api"; import type { OcxConfig } from "../types"; import { configuredPort, isAllowedRequestOrigin, secretEquals, withCors, type RequestPolicyView } from "./auth-cors"; @@ -44,6 +45,14 @@ function projectQuota(quota: AccountRow["quota"]): Body | null { return out; } +/** + * The native-main slot of a hub without a native Codex login. Only the server's checked absence + * counts; a slot whose credential exists (even one needing reauth) or is unknown stays listed. + */ +function isEmptyNativeMain(row: AccountRow): boolean { + return row.slotKind === "native-main" && row.id === "__main__" && row.hasCredential === false; +} + export function projectHubAccount(row: AccountRow): Body { return { id: String(row.id ?? "").slice(-4), @@ -72,7 +81,7 @@ async function readAccounts(listRows: ListRows, now: number): Promise { const providers: Body = {}; for (const provider of HUB_ACCOUNTS_PROVIDERS) { const rows = await listRows(provider); - providers[provider] = rows.filter(row => row.provider === provider).map(projectHubAccount); + providers[provider] = rows.filter(row => row.provider === provider && !isEmptyNativeMain(row)).map(projectHubAccount); } const body = { schemaVersion: 1, fetchedAt: new Date(now).toISOString(), providers }; cache = { at: now, body }; @@ -98,12 +107,18 @@ export async function answerHubAccounts( } } -/** The same local management read `ocx account list --quota --json` makes. */ +/** + * The same local management read `ocx account list --quota --json` makes; the Codex + * read also carries the native-main credential presence the server reported. + */ function localApiRows(config: OcxConfig): ListRows { return async provider => { const classified = classifyAccount(config, provider); if ("error" in classified) return []; - const result = await fetchRows({ baseUrl: `http://127.0.0.1:${configuredPort()}` }, `http://127.0.0.1:${configuredPort()}`, provider, classified.type, {}); + const base = `http://127.0.0.1:${configuredPort()}`; + const result = classified.type === "codex" + ? await fetchCodexRows({ baseUrl: base }, base, false, true, { mainCredential: true }) + : await fetchRows({ baseUrl: base }, base, provider, classified.type, {}); if (result.networkDown || result.errorJson) throw new Error("account list unavailable"); return result.rows; }; diff --git a/structure/cli-management.md b/structure/cli-management.md index a98136564..2ec7bab18 100644 --- a/structure/cli-management.md +++ b/structure/cli-management.md @@ -153,7 +153,7 @@ Storage policy flags in `src/cli/storage.ts` preserve omitted enable/settings an `src/cli/companion-usage.ts` reads settings and two usage ranges sequentially on a pinned management target through `src/cli/observe-stream.ts`. Its safe projection follows the saved model/provider filters and measured-totals rules in `gui/src/pages/tray-data.ts` without importing GUI runtime code. It retains unknown/incomplete metrics, valid server defaults with null update time, and explicit corrupt/fallback flags. Malformed settings stop before usage reads. Range failure retains the other observed range, labels unavailable data, and returns partial/nonzero; signal cancellation emits no late report. The observation owner supplies a separate 10-second fetch/body deadline after discovery and 32 MiB cap for each fixed GET, not a command-wide budget. Snapshot context supplies truthful retry wording without altering default follow behavior. -`src/cli/account-api.ts` forwards explicit quota/refresh intent to the existing per-key owner; ordinary key listing omits both. Opt-in requests reject redirects. `src/cli/account-key-quota.ts` rebuilds the public ProviderQuota projection, including custom windows and credits, with finite-field validation and no credential or private publication fields. Missing mode evidence is unverified/nonzero. Human rendering separates probe/passive/unsupported, unavailable and unmeasured from actual zero; Codex/OAuth rendering remains separate. This read can invoke upstream quota work but does not change key selection or provider aggregate caches. Account list/current rows additionally project, through `src/cli/account-next-actions.ts`, only an allow-listed server health label, a locally generated recovery command built from shell-safe selectors (never server summary/action text), and the Codex boolean `creditsAfterLimit` as read-only consent readback; empty listings add a fixed next-action note to human output and JSON `notes`. +`src/cli/account-api.ts` forwards explicit quota/refresh intent to the existing per-key owner; ordinary key listing omits both. Opt-in requests reject redirects. `src/cli/account-key-quota.ts` rebuilds the public ProviderQuota projection, including custom windows and credits, with finite-field validation and no credential or private publication fields. Missing mode evidence is unverified/nonzero. Human rendering separates probe/passive/unsupported, unavailable and unmeasured from actual zero; Codex/OAuth rendering remains separate. This read can invoke upstream quota work but does not change key selection or provider aggregate caches. Account list/current rows additionally project, through `src/cli/account-next-actions.ts`, only an allow-listed server health label, a locally generated recovery command built from shell-safe selectors (never server summary/action text), and the Codex boolean `creditsAfterLimit` as read-only consent readback; empty listings add a fixed next-action note to human output and JSON `notes`. Codex rows carry the native-main slot's credential presence (`hasCredential`) only when the reader asks for it with `mainCredential`; `GET /v1/hub-accounts` (`src/server/hub-accounts.ts`) is that reader, and it leaves the slot out only on `false`. `false` requires the server's `missing_credential` reason as well, because the server also reports `hasCredential: false` for a read that could not check; anything else is `true` or absent (unknown). `ocx account` listings never request it, so their rows and JSON are unchanged. The operating guide's eight-domain workflow table is navigation rather than parity measurement. Handwritten JSON, recipe, recovery and target docs qualify bounded windows, model-only search, partial/default results and human-only/session actions. Generated chapter counts still derive exclusively from capability declarations. Each chapter renders mutation and JSON mode together so additive declarations retain all metadata within the chapter line budget. File integration help includes Gentle Shell through the `gentle-shell` client target. diff --git a/tests/server/hub-accounts.test.ts b/tests/server/hub-accounts.test.ts index dd6ccc8b3..b103902b2 100644 --- a/tests/server/hub-accounts.test.ts +++ b/tests/server/hub-accounts.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, test } from "bun:test"; -import type { AccountRow } from "../../src/cli/account-api"; +import { fetchCodexRows, type AccountRow } from "../../src/cli/account-api"; import { answerHubAccounts, resetHubAccountsCacheForTest } from "../../src/server/hub-accounts"; const KEY = "read-key-for-tests"; @@ -7,6 +7,22 @@ const row = (provider: string, extra: Partial = {}): AccountRow => ( provider, type: "oauth", id: "account-identifier-1234", email: "person@example.com", active: true, ...extra, } as AccountRow); +const POOL = { id: "pool-account-5678", email: "pool@example.com", hasCredential: true }; +const nativeMain = (extra: Record) => ({ id: "__main__", email: "Codex App login", ...extra }); + +/** Codex rows mapped from `/api/codex-auth/accounts` DTOs, as the hub read maps them. */ +async function codexRows(accounts: unknown[], mainCredential = true): Promise { + const fetchImpl = (async (url: string | URL | Request) => Response.json(String(url).endsWith("/active") + ? { activeCodexAccountId: null } : { accounts })) as unknown as typeof fetch; + return (await fetchCodexRows({ fetchImpl }, "http://hub.invalid", false, true, { mainCredential })).rows; +} + +async function openaiIds(accounts: unknown[]): Promise { + const rows = await codexRows(accounts); + const { body } = await answerHubAccounts(KEY, KEY, async provider => provider === "openai" ? rows : []); + return (body.providers as Record[]>).openai.map(account => account.id); +} + describe("GET /v1/hub-accounts", () => { beforeEach(resetHubAccountsCacheForTest); @@ -42,6 +58,36 @@ describe("GET /v1/hub-accounts", () => { expect((body.providers as Record).anthropic).toEqual([]); }); + test("leaves out the native-main slot only when the server checked and found no login", async () => { + const missing = nativeMain({ hasCredential: false, needsReauth: true, reauthReason: "missing_credential" }); + // A pool account without its credential is still a pool account, and stays listed. + const emptyPool = { ...POOL, id: "pool-account-9999", hasCredential: false, reauthReason: "missing_credential" }; + expect(await openaiIds([missing, POOL, emptyPool])).toEqual(["5678", "9999"]); + }); + + test("keeps a native-main slot whose login exists, including one needing reauth", async () => { + const reauth = nativeMain({ hasCredential: true, needsReauth: true, reauthReason: "refresh_failed" }); + expect(await openaiIds([reauth, POOL])).toEqual(["in__", "5678"]); + const { body } = await answerHubAccounts(KEY, KEY, async provider => provider === "openai" ? codexRows([reauth]) : [], 99_000); + expect((body.providers as Record[]>).openai[0].needsReauth).toBe(true); + expect(JSON.stringify(body)).not.toContain("hasCredential"); + }); + + test("keeps a native-main slot whose login presence is unknown", async () => { + // A read that could not check sends false without the checked reason; an older server sends nothing. + expect(await openaiIds([nativeMain({ hasCredential: false, needsReauth: false }), POOL])).toEqual(["in__", "5678"]); + resetHubAccountsCacheForTest(); + expect(await openaiIds([nativeMain({ hasCredential: false, needsReauth: true, reauthReason: "refresh_failed" })])).toEqual(["in__"]); + resetHubAccountsCacheForTest(); + expect(await openaiIds([nativeMain({})])).toEqual(["in__"]); + }); + + test("other account lists do not carry the native-main credential presence", async () => { + const missing = nativeMain({ hasCredential: false, reauthReason: "missing_credential" }); + expect((await codexRows([missing], true))[0].hasCredential).toBe(false); + expect(Object.hasOwn((await codexRows([missing], false))[0], "hasCredential")).toBe(false); + }); + test("a failed provider read answers 503 without details and is not cached", async () => { let fail = true; const list = async () => { if (fail) throw new Error("secret detail"); return []; };