mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-18 15:39:47 +02:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents use a harness, a model, and a credential to run tasks. > - Connections already store credentials and control who can use them. > - Custom providers also need an endpoint and a supported API format. > - A per-agent endpoint would duplicate credentials and access rules. > - This pull request stores routing on the connection and projects it into the harness. > - Isolated credentials and protocol checks keep the selected connection authoritative. ## Linked Issues or Issue Description Refs #37, #13083, #14104, #14565, #12692. #14016 is a reference only. This PR has its own schema, vault persistence, routing validation, runtime projection, and tests. None of the five commits in #14016 is an ancestor of this branch. We do not depend on or plan to merge it. #14967 addresses task-pinned account pools. #14422 addresses another provider integration. This is the first of two linked PRs. Merge this connection change before #15341, which refines agent setup and adds the qualification harness. The split keeps each review below 100 changed files. Provider catalog entries have usable setup forms in this PR. Local browser subscription sign-in is included. ## What Changed - Store non-secret routing metadata on AI connections. Vault provider API keys, including Bedrock bearer API keys. Reject general AWS access keys. - Enforce company, owner, human audience, agent access, connection status, and protocol checks before resolving credentials. Keep reconnect destinations immutable and retain connection identity during key rotation. - Project OpenRouter and compatible custom endpoints into Codex, Claude, OpenCode, and local Hermes. Carry these settings through both legacy and native runner transports. Clear conflicting host credentials and redact keys from diagnostics. - Preserve older OpenRouter accounts and native personal defaults. Add Google API-key accounts and migration `0306` for the two provider-default constraints. - Run local Claude and Codex subscription sign-in behind the existing browser sign-in card. Use private attempt homes and owner-bound completion instead of a copied terminal command. - Seed isolated Gemini authentication and preserve OpenCode workspace permissions. Keep the selected connection authoritative. The independent Gemini and Grok workflow fixes are in #15341. - Keep native OpenCode custom gateway keys in a runner-owned selected-model proxy; the harness config contains only a session-scoped capability. Honor runtime outgoing proxy and certificate settings. Preserve streamed responses and revoke the proxy on close or startup failure. - Allow ordinary members to connect native personal accounts before an agent exists. - Repair routed accounts from task cards using the saved provider destination, protocol, model aliases, and connection identity. - Add provider catalog definitions, model discovery, pinned logos, and complete native and routed setup forms. Allow a personal routed connection before a new agent exists. Keep endpoint authentication keys out of Hermes terminal children. - Recover cancelled or restarted browser sign-in with a clear restart action. Support no-auth endpoints without a vault credential. Add isolation and recovery regressions and runtime documentation. ## Verification - Updated with `origin/master` at `22a3ea341`. Migration `0306` follows the new master migration and passes migration and snapshot checks. - The integrated connection regressions passed 152 tests and 50 native OpenCode driver tests, including key-free child-shell configuration reads, authenticated/no-auth forwarding, streaming, model/path restrictions, cancellation, outgoing proxy routing, and NO_PROXY bypass. Provider setup has 14 passing tests. The pinned real OpenCode 1.18.34 executable also completed a turn through the proxy against a local synthetic provider; the reusable key was absent from its config. A second real-executable smoke passed with an HTTPS CONNECT proxy and runtime-specific synthetic certificate trust. Certificate-file and certificate-directory regressions pass. - Task-card repair passed 48 tests, including OpenRouter, Bedrock, and custom gateway reconnect cases. UI typecheck and token gates passed. - The prior core regression set passed 133 tests across new-agent setup, provider forms, browser sign-in, routing projection, and connection authorization. Token gates and UI typecheck passed. - Full workspace typecheck and production build passed again after the latest integration and credential-proxy fix. The merged deterministic runner E2E suite passed 1,400 Vitest tests and 128 Node tests. - Full workspace typecheck passed on the prior linked combined implementation. Production build, Storybook build, 1,316 browser-harness Vitest tests, and 128 Node tests passed. Head `9d964c8d9` includes the latest master integration and regenerated migration. This exact head passed 54 remote checks with four expected skips and Greptile 5/5; no review threads remain open. An unchanged server fixture had a random six-character issue-prefix collision on its first attempt. All 245 tests passed locally and the single CI retry passed. - A provider-free terminal check used the cited supported Hermes source and dummy keys. Gateway and OpenRouter terminal children could not read the selected key. - The broad local Vitest attempt passed 15,442 tests but was not green. It had an embedded-Postgres startup failure, an HTTP logger timeout, an origin socket error, and a browser cancellation wait timeout. The cancellation wait was corrected. The relevant connection tests and the full origin test file passed separately. Latest-head CI must pass before merge. - Prior credential-backed acceptance exercised task creation, tool use, artifact delivery, completion, and context-dependent follow-up. Claude legacy and native runners passed Bedrock with `us-east-1` and `us.anthropic.claude-sonnet-4-6`. - Historical local qualification retained 43 passing API/gateway cells out of 46. Those attempts span earlier builds. They do not qualify this exact commit or staging. All subscription combinations and staging remain unqualified. - Verify native subscription and API-key setup. Connect a regular provider catalog row. Verify an incompatible harness and a changed reconnect URL are rejected. Use #15341 for the complete browser campaign. ## Risks - Migration `0306` changes two check constraints. It preserves rows and is safe to reapply. It takes normal constraint-change locks. - Credential projection touches several harnesses. CLI upgrades can change provider configuration and session behavior. - The native OpenCode proxy adds a loopback hop, pins requests to the selected model, limits request bodies to 16 MiB, rejects redirects, and expires at session close. It prevents reusable keys in the child configuration; it is not an OS isolation boundary against a process debugger running as the same user. - Custom endpoints must be reachable from the agent environment. Saving a connection does not prove connectivity. Bedrock keys require rotation before expiry. - Gemini CLI 0.58.0 has an upstream ACP new-file error conversion defect. Provider overloads and an unresolved follow-up timeout also affect live Gemini qualification. We have not patched the installed CLI or marked those cases as passing. - OpenClaw Gateway, Hermes Gateway, Claude Managed, AWS AgentCore, Process, HTTP, and legacy ACPX local are excluded. Vertex, ambient AWS identity, arbitrary auth headers, and custom routing for other harnesses are excluded. - These PRs do not establish production or staging qualification for every provider and login method. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, code execution, and browser testing. The exact deployment model ID and context window size were not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
248 lines
17 KiB
TypeScript
248 lines
17 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
import { probeAiConnectionUsage } from "./ai-connection-usage.js";
|
|
|
|
const auth = JSON.stringify({ tokens: { access_token: "selected-access-secret", account_id: "selected-account" } });
|
|
function fixture(body: unknown, status = 200) {
|
|
return vi.fn<typeof fetch>().mockResolvedValue(new Response(JSON.stringify(body), { status }));
|
|
}
|
|
|
|
describe("connection usage probes", () => {
|
|
it("reads every Codex window, preserves percentages and separates model restrictions", async () => {
|
|
const request = fixture({ plan_type: "pro", rate_limit: {
|
|
allowed: true, limit_reached: false,
|
|
primary_window: { used_percent: 0.4, limit_window_seconds: 14400, reset_at: 1800000000 },
|
|
secondary_window: { used_percent: 99.99, limit_window_seconds: 604800 },
|
|
}, additional_rate_limits: [{ limit_name: "Spark", metered_feature: "spark", rate_limit: {
|
|
allowed: false, limit_reached: true, primary_window: { used_percent: 101.2, limit_window_seconds: 7200 },
|
|
} }], credits: { has_credits: true, unlimited: false, balance: "25.5" } });
|
|
const result = await probeAiConnectionUsage({ provider: "openai", method: "subscription" }, auth, { request });
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits).toHaveLength(3);
|
|
expect(result.limits[0]).toMatchObject({ scope: null, usedPercent: 0.4, remainingPercent: 99.6, windowDurationSeconds: 14400, resetsAt: new Date(1800000000000).toISOString() });
|
|
expect(result.limits[1]).toMatchObject({ usedPercent: 99.99, limitReached: false, resetsAt: null });
|
|
expect(result.limits[2]).toMatchObject({ scope: "spark", usedPercent: 101.2, remainingPercent: 0, limitReached: true, allowed: false });
|
|
expect(result.overage).toMatchObject({ enabled: null, available: true, balance: 25.5, unit: "credits" });
|
|
expect(request).toHaveBeenCalledWith("https://chatgpt.com/backend-api/wham/usage", expect.objectContaining({
|
|
redirect: "error", signal: expect.any(AbortSignal),
|
|
headers: { Authorization: "Bearer selected-access-secret", "ChatGPT-Account-Id": "selected-account" },
|
|
}));
|
|
expect(JSON.stringify(result)).not.toContain("selected-access-secret");
|
|
});
|
|
|
|
it("keeps group denial without pretending every Codex window is exhausted", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "openai", method: "subscription" }, auth, { request: fixture({
|
|
rate_limit: { allowed: false, limit_reached: true, primary_window: { used_percent: 100 }, secondary_window: { used_percent: 25 } },
|
|
code_review_rate_limit: { allowed: false, limit_reached: true },
|
|
spend_control: { reached: true }, credits: { has_credits: false, unlimited: false, balance: "0" },
|
|
}) });
|
|
expect(result.limits).toHaveLength(4);
|
|
expect(result.limits[1]).toMatchObject({ limitReached: false, allowed: false });
|
|
expect(result.limits[2]).toMatchObject({ scope: "code_review", limitReached: true });
|
|
expect(result.overage?.available).toBe(false);
|
|
});
|
|
|
|
it("reports all Claude scopes and distinguishes extra-usage settings from availability", async () => {
|
|
const request = fixture({ five_hour: { utilization: 100, resets_at: "2026-10-03T01:00:00Z" },
|
|
seven_day: { utilization: 0.5 }, seven_day_opus: { utilization: null },
|
|
seven_day_oauth_apps: { utilization: 33 }, future_window: { utilization: 10, resets_at: null },
|
|
extra_usage: { is_enabled: true, monthly_limit: 5000, used_credits: 1000, utilization: 20 },
|
|
});
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "claude-selected-secret", { request });
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits).toHaveLength(6);
|
|
expect(result.limits[0]).toMatchObject({ usedPercent: 100, limitReached: true, windowDurationSeconds: 18000 });
|
|
expect(result.limits[1]).toMatchObject({ usedPercent: 0.5, remainingPercent: 99.5, windowDurationSeconds: 604800 });
|
|
expect(result.limits[2]).toMatchObject({ usedPercent: null, limitReached: null });
|
|
expect(result.limits[3].scope).toBe("seven_day_oauth_apps");
|
|
expect(result.overage).toMatchObject({ enabled: true, available: null, remaining: 4000, unit: "cents" });
|
|
expect(request).toHaveBeenCalledWith("https://api.anthropic.com/api/oauth/usage", expect.objectContaining({
|
|
headers: { Authorization: "Bearer claude-selected-secret", "anthropic-beta": "oauth-2025-04-20" },
|
|
}));
|
|
});
|
|
|
|
it.each([
|
|
{ is_enabled: false, available: false },
|
|
{ is_enabled: true, monthly_limit: 100, used_credits: 100, available: false },
|
|
])("reports unavailable Claude overage without inventing remaining allowance", async ({ available, ...extra_usage }) => {
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ five_hour: { utilization: 100 }, extra_usage }),
|
|
});
|
|
expect(result.overage?.available).toBe(available);
|
|
});
|
|
|
|
it("reads Claude's structured limits, merges legacy aliases, and keeps every scoped window", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ five_hour: { utilization: 15 }, seven_day: { utilization: 25 }, seven_day_sonnet: { utilization: 50 },
|
|
limits: [
|
|
{ kind: "session", percent: 16, scope: null, is_active: false },
|
|
{ kind: "weekly_all", percent: 26, scope: null, is_active: true },
|
|
{ kind: "weekly_scoped", percent: 100, scope: { model: { id: "sonnet", display_name: "Sonnet" }, surface: null }, is_active: false },
|
|
{ kind: "weekly_scoped", percent: 40, scope: { model: { id: "sonnet" }, surface: "code" } },
|
|
{ kind: "weekly_scoped", percent: 0, scope: { model: { id: null, display_name: null }, surface: null }, resets_at: "2026-10-05T04:00:00Z" },
|
|
{ kind: "session", group: "other", percent: 12, scope: null },
|
|
{ kind: "future", percent: 0.5, scope: { surface: "chat" } },
|
|
],
|
|
}),
|
|
});
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits).toHaveLength(7);
|
|
expect(result.limits[0]).toMatchObject({ id: "five_hour", usedPercent: 16, scope: null, allowed: null });
|
|
expect(result.limits[1]).toMatchObject({ id: "seven_day", usedPercent: 26, allowed: null });
|
|
expect(result.limits[2]).toMatchObject({ id: "seven_day_sonnet", usedPercent: 100, scope: "model:sonnet", limitReached: true });
|
|
expect(result.limits[3]).toMatchObject({ usedPercent: 40, scope: "model:sonnet · surface:code", windowDurationSeconds: 604800 });
|
|
expect(result.limits[4]).toMatchObject({ scope: "weekly_scoped.4", usedPercent: 0, resetsAt: "2026-10-05T04:00:00.000Z" });
|
|
expect(new Set(result.limits.map((entry) => entry.id)).size).toBe(7);
|
|
expect(result.limits[6]).toMatchObject({ scope: "surface:chat", usedPercent: 0.5, windowDurationSeconds: null });
|
|
});
|
|
|
|
it("reads structured Claude spend when legacy extra_usage is absent, with its currency and exponent", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ limits: [{ kind: "session", percent: 30 }], spend: {
|
|
enabled: true, percent: 25,
|
|
used: { amount_minor: 1250, currency: "USD", exponent: 2 },
|
|
limit: { amount_minor: 5000, currency: "USD", exponent: 2 },
|
|
balance: { amount_minor: 2000, currency: "USD", exponent: 2 },
|
|
} }),
|
|
});
|
|
expect(result.overage).toMatchObject({ enabled: true, available: null, used: 12.5, limit: 50, remaining: 37.5, balance: 20, unit: "USD" });
|
|
expect(result.limits[1]).toMatchObject({ usedPercent: 25, used: 12.5, limit: 50, unit: "USD" });
|
|
});
|
|
|
|
it("keeps exhausted Claude groups separate from account-wide limits and preserves group identity across ordering", async () => {
|
|
const structured = [
|
|
{ kind: "session", group: "chat", percent: 100, scope: null },
|
|
{ kind: "session", group: "code", percent: 25, scope: null },
|
|
{ kind: "weekly_all", group: "chat", percent: 105, scope: null },
|
|
{ kind: "weekly_all", group: "code", percent: 50, scope: null },
|
|
{ kind: "weekly_scoped", group: "code", percent: 60, scope: { model: { id: "sonnet" } } },
|
|
];
|
|
const probe = (limits: unknown[]) => probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ five_hour: { utilization: 10 }, seven_day: { utilization: 20 }, seven_day_sonnet: { utilization: 30 }, limits }),
|
|
});
|
|
const result = await probe(structured);
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits).toHaveLength(8);
|
|
expect(result.limits[0]).toMatchObject({ id: "five_hour", scope: null, usedPercent: 10, limitReached: false });
|
|
expect(result.limits[1]).toMatchObject({ id: "seven_day", scope: null, usedPercent: 20, limitReached: false });
|
|
expect(result.limits[2]).toMatchObject({ id: "seven_day_sonnet", scope: "seven_day_sonnet", usedPercent: 30 });
|
|
expect(result.limits[3]).toMatchObject({ scope: "group:chat", usedPercent: 100, limitReached: true });
|
|
expect(result.limits[4]).toMatchObject({ scope: "group:code", usedPercent: 25, limitReached: false });
|
|
expect(result.limits[7]).toMatchObject({ scope: "group:code · model:sonnet", usedPercent: 60 });
|
|
expect(result.limits[3].label).toContain("chat");
|
|
expect(new Set(result.limits.map((entry) => entry.id)).size).toBe(8);
|
|
const reversed = await probe([...structured].reverse());
|
|
expect(Object.fromEntries(reversed.limits.map((entry) => [entry.id, entry.scope])))
|
|
.toEqual(Object.fromEntries(result.limits.map((entry) => [entry.id, entry.scope])));
|
|
});
|
|
|
|
it("reports a zero extra-usage cap as exhausted without dividing by zero", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ five_hour: { utilization: 10 }, extra_usage: { is_enabled: true, monthly_limit: 0, used_credits: 0 } }),
|
|
});
|
|
expect(result.limits[1]).toMatchObject({ usedPercent: null, remaining: 0, limitReached: true });
|
|
expect(result.overage).toMatchObject({ enabled: true, available: false });
|
|
});
|
|
|
|
const grokAuth = JSON.stringify({ "https://auth.x.ai::00000000-0000-4000-8000-000000000001": { key: "grok-selected-secret", refresh_token: "never-exchange" } });
|
|
it("uses Grok subscription billing and keeps plan credits separate from on-demand credits", async () => {
|
|
const request = fixture({ onDemandEnabled: true, config: {
|
|
creditUsagePercent: 35.5, currentPeriod: { start: "2026-10-01T00:00:00Z", end: "2026-10-08T00:00:00Z" },
|
|
onDemandCap: { val: 200 }, onDemandUsed: { val: 150 }, prepaidBalance: { val: 100 },
|
|
} });
|
|
const result = await probeAiConnectionUsage({ provider: "xai", method: "subscription" }, grokAuth, { request });
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits[0]).toMatchObject({ usedPercent: 35.5, limit: null, windowDurationSeconds: 604800, unit: "cents" });
|
|
expect(result.limits[1]).toMatchObject({ scope: "overage", usedPercent: 75 });
|
|
expect(result.overage).toMatchObject({ enabled: true, available: null, remaining: 50, balance: 100 });
|
|
expect(request).toHaveBeenCalledWith("https://cli-chat-proxy.grok.com/v1/billing?format=credits", expect.objectContaining({
|
|
headers: expect.objectContaining({ Authorization: "Bearer grok-selected-secret", "x-xai-token-auth": "xai-grok-cli" }),
|
|
}));
|
|
});
|
|
it("preserves the live Grok shape's omitted included usage instead of assuming zero", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "xai", method: "subscription" }, grokAuth, {
|
|
request: fixture({ config: {
|
|
currentPeriod: { type: "USAGE_PERIOD_TYPE_WEEKLY", start: "2026-10-01T00:00:00Z", end: "2026-10-08T00:00:00Z" },
|
|
isUnifiedBillingUser: true, onDemandCap: { val: 0 }, onDemandUsed: { val: 0 }, prepaidBalance: { val: 0 },
|
|
} }),
|
|
});
|
|
expect(result.status).toBe("ok");
|
|
expect(result.limits[0]).toMatchObject({ usedPercent: null, used: null, limit: null, limitReached: null, allowed: null, windowDurationSeconds: 604800 });
|
|
expect(result.overage).toMatchObject({ enabled: null, available: false, balance: 0, unit: "cents" });
|
|
});
|
|
|
|
it("uses Grok's legacy used field, proto3 zero messages, and remote settings without conflating prepaid balance", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "xai", method: "subscription" }, grokAuth, {
|
|
request: fixture({ on_demand_enabled: true, subscription_tier: "SuperGrok", config: {
|
|
monthlyLimit: { val: 2000 }, used: { val: 500 }, onDemandCap: {}, onDemandUsed: {}, prepaidBalance: { val: 100 },
|
|
billingPeriodStart: "2026-10-01T00:00:00Z", billingPeriodEnd: "2026-11-01T00:00:00Z",
|
|
} }),
|
|
});
|
|
expect(result.planType).toBe("SuperGrok");
|
|
expect(result.limits[0]).toMatchObject({ used: 500, limit: 2000, usedPercent: 25, remaining: 1500, unit: "cents" });
|
|
expect(result.overage).toMatchObject({ enabled: true, used: 0, limit: 0, remaining: 0, balance: 100, available: null });
|
|
});
|
|
it("does not infer Grok cadence or zero usage from just a reset timestamp", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "xai", method: "subscription" }, grokAuth, {
|
|
request: fixture({ config: { currentPeriod: { end: "2026-10-08T00:00:00Z" } } }),
|
|
});
|
|
expect(result).toMatchObject({ status: "error", errorCode: "invalid_response", limits: [] });
|
|
});
|
|
|
|
it("reads OpenRouter's key cap without dividing all-time usage by a resettable cap", async () => {
|
|
const result = await probeAiConnectionUsage({ provider: "openrouter", method: "api_key" }, "key", {
|
|
request: fixture({ data: { limit: 10, limit_remaining: 2, usage: 500, limit_reset: "weekly",
|
|
free_model_daily_requests: { used: 50, limit: 50, remaining: 0 },
|
|
} }),
|
|
});
|
|
expect(result.limits[0]).toMatchObject({ used: 8, usedPercent: 80, limitReached: false, resetInterval: "weekly", windowDurationSeconds: 604800 });
|
|
expect(result.limits[1]).toMatchObject({ scope: "free_models", limitReached: true });
|
|
expect(result.overage).toBe(null);
|
|
const unknown = await probeAiConnectionUsage({ provider: "openrouter", method: "api_key" }, "key", {
|
|
request: fixture({ data: { limit: 10, usage: 500, limit_reset: "weekly" } }),
|
|
});
|
|
expect(unknown.limits[0]).toMatchObject({ used: null, usedPercent: null, remaining: null, limitReached: null });
|
|
});
|
|
|
|
it("preserves an overdrawn OpenRouter key cap and does not turn an uncapped key into available credits", async () => {
|
|
const overdrawn = await probeAiConnectionUsage({ provider: "openrouter", method: "api_key" }, "key", {
|
|
request: fixture({ data: { limit: 10, limit_remaining: -2, usage: 200 } }),
|
|
});
|
|
expect(overdrawn.limits[0]).toMatchObject({ used: 12, usedPercent: 120, remaining: -2, limitReached: true });
|
|
const unlimited = await probeAiConnectionUsage({ provider: "openrouter", method: "api_key" }, "key", {
|
|
request: fixture({ data: { limit: null, limit_remaining: null, usage: 20 } }),
|
|
});
|
|
expect(unlimited).toMatchObject({ status: "ok", overage: null, limits: [{ used: 20, limit: null, usedPercent: null, limitReached: null }] });
|
|
});
|
|
|
|
it.each(["openai", "anthropic", "xai", "google"] as const)("makes unsupported %s API probes explicit without a request", async provider => {
|
|
const request = fixture({});
|
|
expect(await probeAiConnectionUsage({ provider, method: "api_key" }, "key", { request })).toMatchObject({ status: "unsupported", limits: [], overage: null });
|
|
expect(request).not.toHaveBeenCalled();
|
|
});
|
|
it.each([
|
|
[401, "unavailable", "authentication_required"], [403, "unavailable", "permission_denied"],
|
|
[429, "error", "rate_limited"], [503, "error", "provider_unavailable"],
|
|
])("does not misreport HTTP %s as exhausted subscription capacity", async (status, expected, code) => {
|
|
const result = await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", {
|
|
request: fixture({ error: "echoed-credential-secret" }, status as number),
|
|
});
|
|
expect(result).toMatchObject({ status: expected, errorCode: code, limits: [], overage: null });
|
|
expect(JSON.stringify(result)).not.toContain("echoed-credential-secret");
|
|
});
|
|
it.each([{}, [], { five_hour: { utilization: -1 } }, { five_hour: { utilization: "100" } }])("fails closed on missing or malformed limits: %j", async body => {
|
|
expect(await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", { request: fixture(body) })).toMatchObject({ status: "error", errorCode: "invalid_response" });
|
|
});
|
|
it("sanitizes network exceptions and refuses malformed credentials without a request", async () => {
|
|
const request = vi.fn<typeof fetch>().mockRejectedValue(new Error("Authorization: secret"));
|
|
expect(await probeAiConnectionUsage({ provider: "openai", method: "subscription" }, "not-json", { request })).toMatchObject({ status: "unavailable" });
|
|
expect(request).not.toHaveBeenCalled();
|
|
const result = await probeAiConnectionUsage({ provider: "openai", method: "subscription" }, auth, { request });
|
|
expect(result.status).toBe("error");
|
|
expect(JSON.stringify(result)).not.toContain("Authorization: secret");
|
|
});
|
|
it("bounds provider response bytes", async () => {
|
|
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response(" ".repeat(256 * 1024 + 1)));
|
|
expect(await probeAiConnectionUsage({ provider: "anthropic", method: "subscription" }, "token", { request })).toMatchObject({ status: "error", errorCode: "invalid_response" });
|
|
});
|
|
});
|