diff --git a/devlog/_plan/260907_lane_d/020_receipt.md b/devlog/_plan/260907_lane_d/020_receipt.md index 7b710df91e..97568c39a8 100644 --- a/devlog/_plan/260907_lane_d/020_receipt.md +++ b/devlog/_plan/260907_lane_d/020_receipt.md @@ -10,3 +10,8 @@ and ordinary validation error remain editable. Screenshot changed disabled input/reset with retry available. Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +Implementation: unknown outcome guards input/reset handlers and submit, and focuses Retry +when saving fails without a receipt. Saved:true remains editable. Transport/body failure +matrix attempts a replacement intent and asserts no second PUT before read-only retry. +Astra Herschel plan verdict PASS. Screenshots and product execution await top CI artifact. diff --git a/devlog/_plan/260907_lane_d/030_account_prices.md b/devlog/_plan/260907_lane_d/030_account_prices.md index 4806657cdb..2ac6e9ccf4 100644 --- a/devlog/_plan/260907_lane_d/030_account_prices.md +++ b/devlog/_plan/260907_lane_d/030_account_prices.md @@ -11,3 +11,17 @@ account rename/removal invalidation. Account aliases never become identity autho Audit determines precise supported historical labels from actual producer evidence. Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +Astra Ohm audit corrections: config-only identity mapping supports selectable Codex +accounts, effective codexAccountLogLabel, exact ID compatibility aliases, and built-in +main/__main__. Generic OAuth stores are separate and excluded; no free-form inference. +Use exact configured provider before canonical account identity, exact override first. +Apply same namespace for context/priority/lower-bound modifiers, preserving attribution. +Include sorted mapping in version signature, but aliases/plan/reordering stay no-ops. + +Implementation: exact selectable account IDs, effective labels and main forms are resolved +from config at overlay refresh. Only identity changes bump cache versions. Exact configured +providers and explicit user rows remain isolated; context/Fast/lower-bound use the selected +price namespace while request attribution is unchanged. Existing memo fast path is retained. +Regression fixtures cover mappings, collisions, ignored aliases/invalid rows, add/remove/ +label invalidation, presentation no-ops, estimate/attempt/combo and tier parity. diff --git a/gui/src/components/ModelDisplayNameDialog.tsx b/gui/src/components/ModelDisplayNameDialog.tsx index 2a57ff8279..09854e104d 100644 --- a/gui/src/components/ModelDisplayNameDialog.tsx +++ b/gui/src/components/ModelDisplayNameDialog.tsx @@ -10,6 +10,7 @@ interface ModelDisplayNameDialogProps { saving: boolean; requestError: string | null; currentNamePending?: boolean; + mutationOutcomeUnknown?: boolean; onRetry?: () => void; onEdit?: () => void; onSave: (displayName: string) => void; @@ -28,6 +29,7 @@ export default function ModelDisplayNameDialog({ saving, requestError, currentNamePending = false, + mutationOutcomeUnknown = false, onRetry, onEdit, onSave, @@ -37,6 +39,7 @@ export default function ModelDisplayNameDialog({ const t = useT(); const dialogRef = useRef(null); const inputRef = useRef(null); + const submitRef = useRef(null); const wasSavingRef = useRef(saving); const titleId = useId(); const helpId = useId(); @@ -55,8 +58,11 @@ export default function ModelDisplayNameDialog({ useEffect(() => { const saveFailed = wasSavingRef.current && !saving && Boolean(requestError); wasSavingRef.current = saving; - if (saveFailed) inputRef.current?.focus(); - }, [requestError, saving]); + if (saveFailed) { + if (mutationOutcomeUnknown) submitRef.current?.focus(); + else inputRef.current?.focus(); + } + }, [requestError, saving, mutationOutcomeUnknown]); // Parent replaces this snapshot only after a confirmed mutation, not typing or polling. // Adjust before committing children, preserving the mounted dialog and its focus refs. @@ -102,6 +108,7 @@ export default function ModelDisplayNameDialog({ event.preventDefault(); if (saving) return; if (onRetry) { onRetry(); return; } + if (mutationOutcomeUnknown) return; const nextValidationKey = modelDisplayNameValidationKey(draft); setValidationKey(nextValidationKey); if (!nextValidationKey) onSave(draft.trim()); @@ -137,8 +144,9 @@ export default function ModelDisplayNameDialog({ placeholder={t("models.displayNamePlaceholder")} aria-describedby={`${helpId}${visibleError ? ` ${errorId}` : ""}`} aria-invalid={validationError ? true : undefined} - disabled={saving} + disabled={saving || mutationOutcomeUnknown} onChange={event => { + if (saving || mutationOutcomeUnknown) return; onEdit?.(); setDraft(event.target.value); setValidationKey(null); @@ -157,15 +165,15 @@ export default function ModelDisplayNameDialog({ - diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index c342866d7e..fc8db5626e 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -2643,6 +2643,7 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; saving={displayNameSaving} requestError={displayNameRequestError} currentNamePending={displayNameCurrentPending} + mutationOutcomeUnknown={displayNameRecovery?.confirmed === false} onRetry={displayNameRecovery ? () => void saveDisplayName(displayNameRecovery.value) : undefined} onEdit={() => setDisplayNameRecovery(null)} onSave={value => void saveDisplayName(value)} diff --git a/gui/tests/models-display-name-editor.test.tsx b/gui/tests/models-display-name-editor.test.tsx index b0656391ed..9d67f986e0 100644 --- a/gui/tests/models-display-name-editor.test.tsx +++ b/gui/tests/models-display-name-editor.test.tsx @@ -448,8 +448,16 @@ describe("Models dashboard discovered display name integration", () => { expect(currentNameText()).toContain("Current name unavailable until refresh"); expect(currentNameText()).not.toContain("Your name"); expect(container.textContent).toContain("The change may have been saved"); + expect(dialogInput().disabled).toBe(true); + expect(dialogButton("Reset name").disabled).toBe(true); expect(dialogButton("Retry").disabled).toBe(false); expect(dialogButton("Cancel").disabled).toBe(false); + await act(async () => { + setInputValue(dialogInput(), "Replacement intent"); + dialogButton("Reset name").dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true })); + }); + expect(dialogButton("Retry").disabled).toBe(false); + expect(mutationBodies).toHaveLength(1); await act(async () => container.querySelector("dialog form")!.dispatchEvent( new testWindow.Event("submit", { bubbles: true, cancelable: true }), )); @@ -522,12 +530,12 @@ describe("Models dashboard discovered display name integration", () => { if (stage === "reload") expect(seenSignals[1]).toBe(seenSignals[0]); await act(async () => deadline.abort(new DOMException("Timed out", "TimeoutError"))); await flush(); - expect(dialogInput().disabled).toBe(false); + expect(dialogInput().disabled).toBe(stage === "mutation"); expect(dialogButton("Cancel").disabled).toBe(false); expect(dialogInput().value).toBe("Possibly saved"); expect(container.textContent).toContain(stage === "mutation" ? "The change may have been saved" : "The change was saved"); - expect(testWindow.document.activeElement).toBe(dialogInput()); + expect(testWindow.document.activeElement).toBe(stage === "mutation" ? dialogButton("Retry") : dialogInput()); stall = false; if (descriptor) Object.defineProperty(AbortSignal, "timeout", descriptor); await act(async () => dialogButton("Retry").click()); diff --git a/src/usage/cost.ts b/src/usage/cost.ts index f7004634c9..2a3b2ae6d3 100644 --- a/src/usage/cost.ts +++ b/src/usage/cost.ts @@ -16,10 +16,10 @@ import { } from "../generated/model-metadata"; import type { AttemptTierOutcome, OcxUsage } from "../types"; import { canonicalFastTierMarker } from "../providers/fastwire"; -import { baseProviderLabel, canonicalUsageProviderLabel } from "../providers/label"; +import { baseProviderLabel } from "../providers/label"; import type { PersistedUsageAttempt, UsageStatus } from "./log"; import { canonicalAntigravityUsageModel } from "../providers/antigravity-models"; -import { activeConfiguredProviders, activeUserCostOverlays, userCostOverlayVersion } from "./user-cost-overlays"; +import { activeAccountPricingProviders, activeConfiguredProviders, activeUserCostOverlays, userCostOverlayVersion } from "./user-cost-overlays"; import { EXPECTED_PRICE_OVERLAYS, findExpectedPriceOverlay, @@ -187,21 +187,18 @@ export function resolveMatchedPrice( userOverlays: readonly ExpectedPriceOverlay[] = activeUserCostOverlays(), options: PriceResolutionOptions = {}, ): MatchedPrice | null { - // User-configured overlays are keyed by the EXACT configured provider name. - // A provider that literally exists in config.providers keeps its own pricing - // namespace: a real custom provider can legitimately end with a label-shaped - // suffix (e.g. acme-pabcdef) and must not inherit the base provider's user - // overlay. Only NON-configured names (generated account log labels) collapse - // to their label base. chatgpt/openai-multi are the same OpenAI usage surface - // and always canonicalize to openai. - const collapsed = baseProviderLabel(provider); - if (collapsed !== provider && (canonicalUsageProviderLabel(provider) !== provider || !activeConfiguredProviders().has(provider))) { + // Literal configured providers win over account identities. Only then use + // config-owned Codex identities, followed by the existing historical suffix + // grammar. Never infer an account by stripping an arbitrary suffix. + const namespace = activeConfiguredProviders().has(provider) + ? provider + : activeAccountPricingProviders().get(provider) ?? baseProviderLabel(provider); + if (namespace !== provider) { + // An exact override (including caller-supplied rows) owns its namespace. + // Unchanged names use the memoized inner lookup's existing user-first order. const exactUserOverlay = userOverlayMatch(provider, modelId, userOverlays); if (exactUserOverlay) return exactUserOverlay; - // Pool/account log suffixes (e.g. google-antigravity-p442fff) must collapse - // before the compiled/overlay lookup; configured providers keep their own - // namespace above. - provider = collapsed; + provider = namespace; } // Memoize by (provider, model): usage summaries iterate hundreds of thousands of // rows that share a handful of provider/model keys, so resolving each time would @@ -466,7 +463,7 @@ function applyContextTier( tier?: ServiceTierInput, ): [Cost4, ContextTierName | undefined, boolean] { if (rawInputTokens === undefined) return [cost4, undefined, false]; - const rule = findContextTier(baseProviderLabel(provider), modelId); + const rule = findContextTier(provider, modelId); if (!rule || !isLongContext(rule, rawInputTokens)) return [cost4, undefined, false]; const confirmedFast = isConfirmedFast(tier); if (confirmedFast && rule.confirmedPriorityRelation === "exclusive") { @@ -494,9 +491,8 @@ function applyPriorityMultiplier( contextTier?: ContextTierName, ): [Cost4, number] { if (canonicalFastTierMarker(tierScalar(serviceTier)) !== "priority") return [cost4, 1]; - const base = baseProviderLabel(provider); - if (contextTier && findContextTier(base, modelId)?.confirmedPriorityRelation !== "stack") return [cost4, 1]; - const rule = findPriorityPricingRule(base, modelId); + if (contextTier && findContextTier(provider, modelId)?.confirmedPriorityRelation !== "stack") return [cost4, 1]; + const rule = findPriorityPricingRule(provider, modelId); if (rule?.requiresResponseConfirmation && !isConfirmedFast(serviceTier)) return [cost4, 1]; const multiplier = rule?.multiplier ?? 1; if (multiplier === 1) return [cost4, 1]; @@ -524,7 +520,7 @@ function isOpenRouterPriorityLowerBound( provider: string, outcome: AttemptTierOutcome | undefined, ): boolean { - return baseProviderLabel(provider) === "openrouter" + return provider === "openrouter" && outcome?.canonical === "priority" && outcome.fastOutcome === "applied" && (outcome.confirmation === "confirmed" || outcome.confirmation === "assumed"); @@ -550,13 +546,13 @@ export function estimateAttemptCost( ? serviceTierContextFromOutcome(attempt.tierOutcome) : serviceTier; const [tieredCost4, contextTier, contextPriorityLowerBound] = applyContextTier( - price.cost4, attempt.provider, attempt.model, attempt.usage.inputTokens, attemptServiceTier, + price.cost4, price.provider, attempt.model, attempt.usage.inputTokens, attemptServiceTier, ); const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, attempt.provider, attempt.model, attemptServiceTier, contextTier, + tieredCost4, price.provider, attempt.model, attemptServiceTier, contextTier, ); const priorityLowerBound = contextPriorityLowerBound - || isOpenRouterPriorityLowerBound(attempt.provider, attempt.tierOutcome); + || isOpenRouterPriorityLowerBound(price.provider, attempt.tierOutcome); return { ordinal: attempt.ordinal, provider: attempt.provider, @@ -635,13 +631,13 @@ export function estimateRequestCost( const price = resolveMatchedPrice(input.provider, input.model, overlays, userOverlays, input); if (!price) return null; const [tieredCost4, contextTier, contextPriorityLowerBound] = applyContextTier( - price.cost4, input.provider, input.model, input.usage.inputTokens, input.serviceTier, + price.cost4, price.provider, input.model, input.usage.inputTokens, input.serviceTier, ); const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, input.provider, input.model, input.serviceTier, contextTier, + tieredCost4, price.provider, input.model, input.serviceTier, contextTier, ); const priorityLowerBound = contextPriorityLowerBound || isOpenRouterPriorityLowerBound( - input.provider, + price.provider, typeof input.serviceTier === "object" ? input.serviceTier.tierOutcome : undefined, ); return { diff --git a/src/usage/user-cost-overlays.ts b/src/usage/user-cost-overlays.ts index 22af57e87a..6024e17596 100644 --- a/src/usage/user-cost-overlays.ts +++ b/src/usage/user-cost-overlays.ts @@ -13,19 +13,23 @@ * must not churn the version (see refreshUserCostOverlays). The configured * provider-name set is part of the change identity: adding or removing a * provider changes which names may collapse to a label base in the resolver, - * so it bumps the version even when no overlay row changed. + * so it bumps the version even when no overlay row changed. Exact selectable + * Codex IDs and effective log labels also participate in that identity. * * Display-time estimation only — these rows never affect billing. */ import type { OcxConfig, OcxProviderConfig, ProviderCostOverlay } from "../types"; import { MAX_COST4_RATE, type ExpectedPriceOverlay } from "./expected-prices"; import { redactSecretString } from "../lib/redact"; +import { isSelectableCodexPoolAccount, MAIN_CODEX_ACCOUNT_ID } from "../codex/account-id"; +import { codexAccountLogLabel } from "../codex/account-label"; const EMPTY: readonly ExpectedPriceOverlay[] = []; let active: readonly ExpectedPriceOverlay[] = EMPTY; let activeSignature = ""; let activeConfigured = new Set(); +let activeAccountProviders = codexAccountProviders([]); let version = 0; let preservedDiskOnlyProviders: Record | null = null; @@ -54,6 +58,24 @@ function providerNames(config: OcxConfig): Set { return new Set(Object.keys(config.providers ?? {})); } +/** Exact config-owned identities only; aliases and generic OAuth stores are not authority. */ +function codexAccountProviders(accounts: OcxConfig["codexAccounts"]): Map { + const identities = new Set(["main", MAIN_CODEX_ACCOUNT_ID]); + for (const account of accounts ?? []) { + if (!isSelectableCodexPoolAccount(account)) continue; + identities.add(account.id); + identities.add(codexAccountLogLabel(account)); + } + const mapping = new Map(); + for (const identity of identities) { + mapping.set(identity, "openai"); + for (const provider of ["openai", "chatgpt", "openai-multi"]) { + mapping.set(`${provider}-${identity}`, "openai"); + } + } + return mapping; +} + /** Register one active live-config owner. Multiple server leases may share one config object. */ export function registerPreservedProviderOwner(config: OcxConfig): void { const tagged = config as PreservationTaggedConfig; @@ -289,12 +311,17 @@ export function refreshUserCostOverlays(config: OcxConfig): void { // removing a provider (even one without an overlay) changes which names are // allowed to collapse to a label base, so the resolver memo and the // /api/usage summary cache must be invalidated on that change as well. + // Sort effective account identities so account order, aliases and plan + // metadata do not churn caches; add/remove/label changes still invalidate. const configuredNames = Object.keys(providers ?? {}).sort(); - const signature = `${JSON.stringify(configuredNames)}\u0000${JSON.stringify(rows)}`; + const accountProviders = codexAccountProviders(config.codexAccounts); + const accountEntries = [...accountProviders].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); + const signature = `${JSON.stringify(configuredNames)}\u0000${JSON.stringify(rows)}\u0000${JSON.stringify(accountEntries)}`; if (signature === activeSignature) return; activeSignature = signature; active = rows; activeConfigured = new Set(configuredNames); + activeAccountProviders = accountProviders; version++; } @@ -303,7 +330,7 @@ export function activeUserCostOverlays(): readonly ExpectedPriceOverlay[] { return active; } -/** Monotonic version bumped on every refresh; used by the estimator memo key. */ +/** Monotonic version bumped on pricing-identity changes; used by the estimator memo key. */ export function userCostOverlayVersion(): number { return version; } @@ -312,3 +339,8 @@ export function userCostOverlayVersion(): number { export function activeConfiguredProviders(): ReadonlySet { return activeConfigured; } + +/** Account pricing identities built at refresh, without reading credential stores. */ +export function activeAccountPricingProviders(): ReadonlyMap { + return activeAccountProviders; +} diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index 387ed3c01d..f234622e07 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1327,6 +1327,184 @@ describe("provider cost overlay (user-configured)", () => { }); }); +describe("Codex account pricing identity", () => { + const modelId = "wp3-synthetic-account-model"; + const account = { id: "cost-account", logLabel: "p123abc", alias: "display-name", email: "fixture@example.test", isMain: false }; + const row: ExpectedPriceOverlay = { + provider: "openai", modelId, cost4: RATE, + source: "fixture", verifiedAt: "2026-09-07", status: "verified", + }; + const config = (accounts = [account], providers = {}) => ({ + providers, codexAccounts: accounts, + }) as unknown as OcxConfig; + const forms = (id: string) => [id, ...["openai", "chatgpt", "openai-multi"].map(provider => `${provider}-${id}`)]; + + afterEach(() => refreshUserCostOverlays(config([]))); + + test("exact selectable IDs, effective labels and built-in main forms resolve without model fallback", () => { + refreshUserCostOverlays(config([ + account, + // SHA-256('abc') begins ba7816: an invalid stored label must use the producer's fallback. + { ...account, id: "abc", logLabel: "invalid-label" }, + ])); + for (const id of [account.id, account.logLabel, "abc", "pba7816", "main", "__main__"]) { + for (const provider of forms(id)) { + expect(resolveMatchedPrice(provider, modelId, [row], [], { allowModelLevelFallback: false })) + .toMatchObject({ provider: "openai", cost4: RATE, source: "expected" }); + } + } + }); + + test("aliases, email, invalid rows, unknown IDs, case variants and non-Codex identities stay unmapped", () => { + refreshUserCostOverlays(config([ + account, + { ...account, id: "invalid/id", logLabel: "p111aaa" }, + { ...account, id: "constructor", logLabel: "p222aaa" }, + { ...account, id: "desktop-row", logLabel: "p333aaa", isMain: true }, + { ...account, id: "abc", logLabel: "invalid-label" }, + ])); + for (const provider of [ + ...forms("unknown-account"), ...forms(account.alias), ...forms(account.email), + ...forms("Cost-account"), ...forms("invalid-label"), ...forms("invalid/id"), + "constructor", "desktop-row", "p111aaa", "p222aaa", "p333aaa", "p123abC", + "Openai-cost-account", "openai-cost-account-extra", "anthropic-cost-account", + "xai-cost-account", "oauth-account", "o123abc", "xai-o123abc", "unrelated-hyphen-provider", + ]) { + expect(resolveMatchedPrice(provider, modelId, [row], [], { allowModelLevelFallback: false })).toBeNull(); + } + }); + + test("configured literal namespaces beat account mapping and historical collapse", () => { + const names = [...forms(account.id), ...forms(account.logLabel), ...forms("main"), ...forms("__main__"), "chatgpt", "openai-multi"]; + refreshUserCostOverlays(config([account], Object.fromEntries(names.map(name => [name, {}])))); + for (const provider of names) { + expect(resolveMatchedPrice(provider, modelId, [row], [])).toBeNull(); + const literal = { ...row, provider, cost4: { ...RATE, input: 7 } }; + expect(resolveMatchedPrice(provider, modelId, [row, literal], [])) + .toMatchObject({ provider, cost4: literal.cost4 }); + } + }); + + test("caller-supplied exact user rows beat both canonical user and compiled rows", () => { + refreshUserCostOverlays(config()); + for (const provider of [...forms(account.id), ...forms(account.logLabel)]) { + const canonicalUser = { ...row, cost4: { ...RATE, input: 11 } }; + const exactUser = { ...row, provider, cost4: { ...RATE, input: 17 } }; + expect(resolveMatchedPrice(provider, modelId, [row], [canonicalUser, exactUser])) + .toMatchObject({ provider, source: "user", cost4: exactUser.cost4 }); + } + }); + + test("only recognized historical phex and main suffixes retain the existing fallback", () => { + refreshUserCostOverlays(config([])); + const custom = { ...row, provider: "legacy" }; + for (const provider of ["legacy-pabcdef", "legacy-main"]) { + expect(resolveMatchedPrice(provider, modelId, [custom], [])?.cost4).toEqual(RATE); + } + for (const provider of ["legacy-unknown", "legacy-pABCDEF", "legacy-pabcde", "legacy-oabcdef", "legacy-__main__"]) { + expect(resolveMatchedPrice(provider, modelId, [custom], [])).toBeNull(); + } + }); + + test("account add, effective-label change and removal invalidate memo; presentation and order do not", () => { + const providers = { openai: { modelCosts: { [modelId]: RATE } } }; + refreshUserCostOverlays(config([], providers)); + expect(resolveMatchedPrice(account.id, modelId)).toBeNull(); + expect(resolveMatchedPrice(account.logLabel, modelId)).toBeNull(); + const before = userCostOverlayVersion(); + const second = { ...account, id: "other-account", logLabel: "p456def" }; + refreshUserCostOverlays(config([account, second], providers)); + expect(userCostOverlayVersion()).toBe(before + 1); + for (const provider of [...forms(account.id), account.logLabel]) { + expect(resolveMatchedPrice(provider, modelId)?.cost4).toEqual(RATE); + } + const rows = activeUserCostOverlays(); + const memo = resolveMatchedPrice(account.id, modelId); + const renamed = { ...account, alias: "new-display", email: "new@example.test", plan: "pro" }; + refreshUserCostOverlays(config([second, renamed], providers)); + expect(userCostOverlayVersion()).toBe(before + 1); + expect(activeUserCostOverlays()).toBe(rows); + expect(resolveMatchedPrice(account.id, modelId)).toBe(memo); + refreshUserCostOverlays(config([{ ...renamed, logLabel: "p789abc" }, second], providers)); + expect(userCostOverlayVersion()).toBe(before + 2); + expect(resolveMatchedPrice(account.logLabel, modelId)).toBeNull(); + expect(resolveMatchedPrice("p789abc", modelId)?.cost4).toEqual(RATE); + refreshUserCostOverlays(config([second], providers)); + expect(userCostOverlayVersion()).toBe(before + 3); + for (const provider of [...forms(account.id), "p789abc"]) { + expect(resolveMatchedPrice(provider, modelId)).toBeNull(); + } + }); + + test("mapped accounts share request, attempt and combo long-context/Fast pricing with original attribution", () => { + refreshUserCostOverlays(config()); + const usage = { inputTokens: 300_000, outputTokens: 10_000 }; + for (const provider of [...forms(account.id), ...forms(account.logLabel), ...forms("__main__")]) { + for (const serviceTier of [undefined, { responseServiceTier: "priority" }, { responseServiceTier: "default", requestedServiceTier: "priority" }]) { + const input = { provider, model: "gpt-6-astra", usageStatus: "reported" as const, usage, serviceTier }; + const request = estimateRequestCost(input)!; + const attempt = estimateAttemptCost({ ...input, ordinal: 1 }, undefined, serviceTier)!; + const combo = estimateComboCost([{ ...input, ordinal: 1 }, { ...input, ordinal: 2 }], undefined, serviceTier)!; + // 300k * $20/M input + 10k * $75/M output; Fast doubles both. + const expected = serviceTier?.responseServiceTier === "priority" ? 13.5 : 6.75; + expect(request.cost.total).toBeCloseTo(expected, 9); + expect(request.contextTier).toBe("long"); + expect(request.priorityMultiplier).toBe(expected === 13.5 ? 2 : undefined); + expect(attempt.cost).toEqual(request.cost); + expect(attempt.contextTier).toBe(request.contextTier); + expect(attempt.priorityMultiplier).toBe(request.priorityMultiplier); + expect(attempt.provider).toBe(provider); + expect(combo.cost.total).toBeCloseTo(expected * 2, 9); + expect(combo.attempts?.map(entry => entry.provider)).toEqual([provider, provider]); + } + } + }); + + test("literal and direct override namespaces do not inherit OpenAI context or Fast modifiers", () => { + const provider = "openai-p123abc"; + const input = { provider, model: "gpt-6-astra", usageStatus: "reported" as const, + usage: { inputTokens: 300_000, outputTokens: 10_000 }, serviceTier: "priority" }; + const literal = { ...row, provider, modelId: input.model }; + refreshUserCostOverlays(config([account], { [provider]: {} })); + for (const estimate of [estimateRequestCost(input, [literal], []), estimateAttemptCost({ ...input, ordinal: 1 }, [literal], "priority", [])]) { + expect(estimate?.cost.total).toBeCloseTo(1.05, 9); + expect(estimate?.contextTier).toBeUndefined(); + expect(estimate?.priorityMultiplier).toBeUndefined(); + } + refreshUserCostOverlays(config()); + const direct = estimateRequestCost(input, [], [literal]); + expect(direct?.cost.total).toBeCloseTo(1.05, 9); + expect(direct?.contextTier).toBeUndefined(); + expect(direct?.priorityMultiplier).toBeUndefined(); + const combo = estimateComboCost([{ ...input, ordinal: 1 }], [], "priority", [literal]); + expect(combo?.cost.total).toBeCloseTo(1.05, 9); + expect(combo?.contextTier).toBeUndefined(); + expect(combo?.priorityMultiplier).toBeUndefined(); + }); + + test("OpenRouter lower-bound uses the selected namespace, including Codex-name collisions", () => { + const provider = "openrouter-p123abc"; + const tracker = createAdapterTierMetadata({ capability: true, eligibility: "eligible", + fastWire: { kind: "service-tier", canonicalToWire: { priority: "priority" }, foreignCallerTiers: "verbatim" }, + demandDecision: "force-fast" }, { kind: "set", value: "priority" }, "service-tier", "priority")!; + tracker.observeResponseServiceTier("priority"); + const input = { provider, model: modelId, usageStatus: "reported" as const, + usage: { inputTokens: 100, outputTokens: 10 }, ordinal: 1, tierOutcome: tracker.outcome }; + const router = { ...row, provider: "openrouter" }; + refreshUserCostOverlays(config([])); + expect(estimateAttemptCost(input, [router], undefined, [])?.priorityLowerBound).toBe(true); + refreshUserCostOverlays(config([{ ...account, id: provider }])); + expect(estimateAttemptCost(input, [row, router], undefined, [])?.priorityLowerBound).toBeUndefined(); + refreshUserCostOverlays(config([], { [provider]: {} })); + const literal = { ...row, provider }; + const request = estimateRequestCost({ ...input, serviceTier: { tierOutcome: tracker.outcome } }, [literal], []); + expect(request).not.toBeNull(); + expect(request?.priorityLowerBound).toBeUndefined(); + expect(estimateAttemptCost(input, [literal], undefined, [])?.priorityLowerBound).toBeUndefined(); + expect(estimateComboCost([input], [literal], undefined, [])?.priorityLowerBound).toBeUndefined(); + }); +}); + describe("aggregator vendor-prefixed model ids (#3136)", () => { test("restricted resolution partitions memoization and only removes vendor fallback", () => { const model = "anthropic/claude-3-haiku-20240307";