Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai): recover exhausted pipes and prompt upgrades (#5864)

Ezra Ellette9723ecf2d4a1
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.test.tsx
index 9b05f4ff1..54553b587 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.test.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.test.tsx
@@ -69,6 +69,7 @@ describe("UpgradeQuotaBanner", () => {
resets_at: "2026-07-31T00:00:00.000Z",
upsell_banner: true,
upgrade_eligible: true,
+ cost_limit_reached: false,
};
mocks.gateState = false;
mocks.seenEligibility = undefined;
@@ -274,6 +275,40 @@ describe("UpgradeQuotaBanner", () => {
expect(mocks.openBusinessUpgradeSurface).not.toHaveBeenCalled();
});
+ it("opens an upgrade modal from polled legacy cost exhaustion on chat entry", async () => {
+ mocks.usageState = {
+ ...mocks.usageState,
+ tier: "subscribed",
+ remaining: 999_876,
+ upsell_banner: false,
+ upgrade_eligible: false,
+ cost_limit_reached: true,
+ hosted_ai: {
+ plan: "business",
+ allowances: null,
+ upgrade: {
+ requiredPlan: "business_max",
+ upgradeUrl:
+ "https://screenpipe.com/account/billing?target_plan=pro_max&interval=month",
+ resetsAt: null,
+ },
+ },
+ };
+
+ render(<UpgradeQuotaBanner />);
+
+ expect(screen.getByTestId("hosted-ai-cost-limit-banner")).toBeTruthy();
+ expect(screen.getByTestId("ai-usage-limit-modal")).toBeTruthy();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Upgrade to Business Max" }),
+ );
+ await waitFor(() =>
+ expect(mocks.openExternalUrl).toHaveBeenCalledWith(
+ "https://screenpipe.com/account/billing?target_plan=pro_max&interval=month",
+ ),
+ );
+ });
+
it("uses the server's Basic target for a Free-plan limit", async () => {
mocks.blockedUpgrade = {
requiredPlan: "basic",
@@ -330,6 +365,7 @@ describe("UpgradeQuotaBanner", () => {
};
render(<UpgradeQuotaBanner />);
+ fireEvent.click(screen.getByRole("button", { name: "not now" }));
fireEvent.click(
screen.getByRole("button", { name: "dismiss AI usage notice" }),
);
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.tsx
index 32d9536f0..ba12996e7 100644
--- a/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.tsx
+++ b/apps/screenpipe-app-tauri/components/chat/standalone/upgrade-quota-banner.tsx
@@ -7,6 +7,14 @@ import { useState } from "react";
import { X, Zap } from "lucide-react";
import posthog from "posthog-js";
import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
import {
formatAllowanceReset,
formatAllowanceWindow,
@@ -44,21 +52,30 @@ export function UpgradeQuotaBanner() {
const upsellEnabled = useModelUpsellGating(usage?.upgrade_eligible);
const blockedUpgrade = useQuotaUpgrade();
const [dismissed, setDismissed] = useState(false);
+ const [dismissedModalKey, setDismissedModalKey] = useState<string | null>(
+ null,
+ );
const [busy, setBusy] = useState(false);
const cloudflareAllowance = usage?.hosted_ai?.allowances
?.filter((allowance) => allowance.remaining_percent <= 0)
.sort((left, right) => left.lane.localeCompare(right.lane))[0] ?? null;
const cloudflareBlocked = !blockedUpgrade && cloudflareAllowance !== null;
- const cloudflareUpgrade = cloudflareBlocked
+ const legacyCostBlocked =
+ !blockedUpgrade &&
+ !cloudflareBlocked &&
+ usage?.cost_limit_reached === true &&
+ usage.hosted_ai?.allowance_managed_by !== "cloudflare";
+ const polledUpgrade = cloudflareBlocked || legacyCostBlocked
? usage?.hosted_ai?.upgrade ?? null
: null;
+ const serverBlocked = cloudflareBlocked || legacyCostBlocked;
if (!blockedUpgrade) {
if (dismissed) return null;
- // A Cloudflare allowance notice is product status, not an upsell. Show the
- // rule's real usage even when upgrade experiments are disabled or the plan
- // has no self-serve next tier.
- if (cloudflareBlocked) {
+ // A live provider-cost allowance notice is product status, not an upsell.
+ // Show it even when upgrade experiments are disabled or the plan has no
+ // self-serve next tier.
+ if (serverBlocked) {
// Continue to rendering below.
} else {
// Proactive prompts require settings, PostHog, and server plan truth. A
@@ -81,17 +98,32 @@ export function UpgradeQuotaBanner() {
const resets = cloudflareBlocked
? formatAllowanceReset(cloudflareAllowance.resets_at)
- : formatResetTime(blockedUpgrade?.resetsAt ?? usage?.resets_at ?? "");
+ : legacyCostBlocked
+ ? ""
+ : formatResetTime(blockedUpgrade?.resetsAt ?? usage?.resets_at ?? "");
const source = blockedUpgrade
? "ai-usage-limit-banner"
: cloudflareBlocked
? "cloudflare-ai-allowance-banner"
- : "ai-quota-banner";
- const showCloudflareUpgrade = cloudflareUpgrade !== null;
- const activeUpgrade = blockedUpgrade ?? cloudflareUpgrade;
+ : legacyCostBlocked
+ ? "hosted-ai-cost-limit-banner"
+ : "ai-quota-banner";
+ const activeUpgrade = blockedUpgrade ?? polledUpgrade;
+ const showUpgradeAction =
+ activeUpgrade !== null || (!blockedUpgrade && !serverBlocked);
+ const modalKey = [
+ source,
+ activeUpgrade?.requiredPlan ?? "no-upgrade",
+ activeUpgrade?.upgradeUrl ?? "",
+ cloudflareAllowance?.lane ?? "",
+ cloudflareAllowance?.resets_at ?? blockedUpgrade?.resetsAt ?? "",
+ ].join(":");
+ const modalOpen = dismissedModalKey !== modalKey;
+ const dismissModal = () => setDismissedModalKey(modalKey);
const onUpgrade = async () => {
if (busy) return;
+ dismissModal();
setBusy(true);
try {
posthog.capture("desktop_upgrade_entry_clicked", {
@@ -116,80 +148,130 @@ export function UpgradeQuotaBanner() {
const blockedTitle = cloudflareBlocked
? `${cloudflareAllowance.lane === "auto" ? "Auto" : "Explicit model"} hosted AI limit reached`
: "Hosted AI usage limit reached";
+ const modalDescription = cloudflareBlocked
+ ? `Your ${cloudflareAllowance.lane === "auto" ? "Auto" : "explicit model"} hosted AI allowance is fully used${resets ? ` until ${resets}` : ""}. ${
+ cloudflareAllowance.lane === "auto"
+ ? "Choose an explicit hosted model, or use a local or own-key preset."
+ : "Switch to Auto, or use a local or own-key preset."
+ }`
+ : legacyCostBlocked || blockedUpgrade
+ ? `Your plan's hosted AI allowance is used up${resets ? ` until ${resets}` : ""}. Switch to a local or own-key AI preset to keep working.`
+ : `You've used today's premium hosted AI allowance${resets ? `; it resets ${resets}` : ""}. Free models still work.`;
return (
- <div
- className="mb-2 border border-border bg-background px-3 py-2.5 shadow-lg shadow-black/5"
- data-testid={
- blockedUpgrade
- ? "cost-limit-upgrade-banner"
- : cloudflareBlocked
- ? "hosted-ai-allowance-banner"
- : "quota-upgrade-banner"
- }
- role={blockedUpgrade || cloudflareBlocked ? "alert" : undefined}
- >
- <div className="flex items-start gap-3">
- <Zap className="mt-0.5 h-4 w-4 shrink-0 text-foreground/70" />
- <div className="min-w-0 flex-1 text-[12px] leading-snug">
- <div className="font-medium">
- {blockedUpgrade || cloudflareBlocked
- ? blockedTitle
- : "You're out of premium AI for today."}
- </div>
- <div className="mt-0.5 text-muted-foreground">
- {cloudflareBlocked ? (
- <>
- {formatUsagePercent(cloudflareAllowance.used_percent)} used for this{" "}
- {formatAllowanceWindow(cloudflareAllowance.window_seconds)}{" "}
- {cloudflareAllowance.technique} period.
- {resets ? ` Resets ${resets}.` : " Usage falls as the window moves."}{" "}
- {cloudflareAllowance.lane === "auto"
- ? "Choose an explicit hosted model, or use a local or own-key preset."
- : "Switch to Auto, or use a local or own-key preset."}
- </>
- ) : blockedUpgrade ? (
- <>
- {resets ? `Resets ${resets}. ` : ""}
- Upgrade to {requiredPlanLabel} for a higher limit, or switch to a
- local or own-key AI preset.
- </>
- ) : (
- <>Free models still work{resets ? ` · resets ${resets}` : ""}.</>
+ <>
+ <Dialog
+ open={modalOpen}
+ onOpenChange={(open) => {
+ if (!open) dismissModal();
+ }}
+ >
+ <DialogContent data-testid="ai-usage-limit-modal">
+ <DialogHeader>
+ <DialogTitle>
+ {showUpgradeAction ? "upgrade hosted AI" : "hosted AI usage limit"}
+ </DialogTitle>
+ <DialogDescription>{modalDescription}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={dismissModal}>
+ not now
+ </Button>
+ {showUpgradeAction && (
+ <Button type="button" onClick={onUpgrade} disabled={busy}>
+ {activeUpgrade
+ ? `Upgrade to ${requiredPlanLabel}`
+ : "View Business"}
+ </Button>
)}
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+
+ <div
+ className="mb-2 border border-border bg-background px-3 py-2.5 shadow-lg shadow-black/5"
+ data-testid={
+ blockedUpgrade
+ ? "cost-limit-upgrade-banner"
+ : cloudflareBlocked
+ ? "hosted-ai-allowance-banner"
+ : legacyCostBlocked
+ ? "hosted-ai-cost-limit-banner"
+ : "quota-upgrade-banner"
+ }
+ role={blockedUpgrade || serverBlocked ? "alert" : undefined}
+ >
+ <div className="flex items-start gap-3">
+ <Zap className="mt-0.5 h-4 w-4 shrink-0 text-foreground/70" />
+ <div className="min-w-0 flex-1 text-[12px] leading-snug">
+ <div className="font-medium">
+ {blockedUpgrade || serverBlocked
+ ? blockedTitle
+ : "You're out of premium AI for today."}
+ </div>
+ <div className="mt-0.5 text-muted-foreground">
+ {cloudflareBlocked ? (
+ <>
+ {formatUsagePercent(cloudflareAllowance.used_percent)} used for this{" "}
+ {formatAllowanceWindow(cloudflareAllowance.window_seconds)}{" "}
+ {cloudflareAllowance.technique} period.
+ {resets ? ` Resets ${resets}.` : " Usage falls as the window moves."}{" "}
+ {cloudflareAllowance.lane === "auto"
+ ? "Choose an explicit hosted model, or use a local or own-key preset."
+ : "Switch to Auto, or use a local or own-key preset."}
+ </>
+ ) : legacyCostBlocked ? (
+ activeUpgrade ? (
+ <>
+ Upgrade to {requiredPlanLabel} for a higher hosted AI allowance,
+ or switch to a local or own-key AI preset.
+ </>
+ ) : (
+ <>Switch to a local or own-key AI preset to keep working.</>
+ )
+ ) : blockedUpgrade ? (
+ <>
+ {resets ? `Resets ${resets}. ` : ""}
+ Upgrade to {requiredPlanLabel} for a higher limit, or switch to a
+ local or own-key AI preset.
+ </>
+ ) : (
+ <>Free models still work{resets ? ` · resets ${resets}` : ""}.</>
+ )}
+ </div>
</div>
- </div>
- <span className="flex shrink-0 items-center gap-1.5">
- {(!cloudflareBlocked || showCloudflareUpgrade) && (
- <Button
+ <span className="flex shrink-0 items-center gap-1.5">
+ {showUpgradeAction && !modalOpen && (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="h-7 text-[12px]"
+ onClick={onUpgrade}
+ disabled={busy}
+ >
+ {activeUpgrade
+ ? `Upgrade to ${requiredPlanLabel}`
+ : "View Business"}
+ </Button>
+ )}
+ <button
type="button"
- size="sm"
- variant="outline"
- className="h-7 text-[12px]"
- onClick={onUpgrade}
- disabled={busy}
+ onClick={() => {
+ if (blockedUpgrade) {
+ clearQuotaUpgrade();
+ } else {
+ setDismissed(true);
+ }
+ }}
+ className="ml-0.5 shrink-0 text-muted-foreground/50 transition-colors hover:text-foreground"
+ aria-label="dismiss AI usage notice"
>
- {activeUpgrade
- ? `Upgrade to ${requiredPlanLabel}`
- : "View Business"}
- </Button>
- )}
- <button
- type="button"
- onClick={() => {
- if (blockedUpgrade) {
- clearQuotaUpgrade();
- } else {
- setDismissed(true);
- }
- }}
- className="ml-0.5 shrink-0 text-muted-foreground/50 transition-colors hover:text-foreground"
- aria-label="dismiss AI usage notice"
- >
- <X className="h-3.5 w-3.5" />
- </button>
- </span>
+ <X className="h-3.5 w-3.5" />
+ </button>
+ </span>
+ </div>
</div>
- </div>
+ </>
);
}
diff --git a/apps/screenpipe-app-tauri/e2e/specs/chat-cost-limit-upgrade.spec.ts b/apps/screenpipe-app-tauri/e2e/specs/chat-cost-limit-upgrade.spec.ts
index 6754bfabd..c1f81e3b7 100644
--- a/apps/screenpipe-app-tauri/e2e/specs/chat-cost-limit-upgrade.spec.ts
+++ b/apps/screenpipe-app-tauri/e2e/specs/chat-cost-limit-upgrade.spec.ts
@@ -8,7 +8,7 @@
* A local OpenAI-compatible provider returns the exact structured 429 contract
* used by the gateway for a Business account. The request travels through Pi and the real
* foreground event bus, proving desktop renders a concise failure message and
- * a recovery card that opens the server-reviewed Business Max billing URL
+ * a recovery modal that opens the server-reviewed Business Max billing URL
* without waiting for `remaining` to hit zero or for the proactive PostHog
* upsell gate.
*/
@@ -191,7 +191,11 @@ describe("Hosted AI usage-limit Business Max recovery", function () {
await banner.waitForDisplayed({ timeout: t(10_000) });
expect(await banner.getText()).toContain("Hosted AI usage limit reached");
expect(await banner.getText()).toContain("Resets");
- const upgrade = await banner.$("button=Upgrade to Business Max");
+
+ const modal = await $('[data-testid="ai-usage-limit-modal"]');
+ await modal.waitForDisplayed({ timeout: t(10_000) });
+ expect(await modal.getText()).toContain("upgrade hosted AI");
+ const upgrade = await modal.$("button=Upgrade to Business Max");
await upgrade.waitForDisplayed({
timeout: t(10_000),
});
diff --git a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-usage-status.test.tsx b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-usage-status.test.tsx
index e1f5504f0..cf1d77839 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-usage-status.test.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/__tests__/use-usage-status.test.tsx
@@ -33,6 +33,7 @@ function usageResponse(upgradeEligible: boolean): Promise<Response> {
resets_at: "2026-07-31T00:00:00.000Z",
upsell_banner: upgradeEligible,
upgrade_eligible: upgradeEligible,
+ cost_limit_reached: false,
hosted_ai: {
plan: upgradeEligible ? "basic" : "business_ultra",
allowance_managed_by: "cloudflare",
@@ -100,6 +101,46 @@ describe("useUsageStatus", () => {
upgradeUrl: "https://screenpi.pe/account/billing",
resetsAt: null,
});
+ expect(result.current?.cost_limit_reached).toBe(false);
+ });
+
+ it("preserves legacy cost exhaustion and its exact server upgrade", async () => {
+ settingsState = {
+ settings: { user: { token: "business.jwt" } },
+ isSettingsLoaded: true,
+ };
+ vi.mocked(fetch).mockResolvedValue({
+ ok: true,
+ json: async () => ({
+ tier: "subscribed",
+ used_today: 12,
+ limit_today: 1_000_000,
+ remaining: 999_988,
+ resets_at: "",
+ upsell_banner: false,
+ upgrade_eligible: false,
+ cost_limit_reached: true,
+ hosted_ai: {
+ plan: "business",
+ required_plan: "business_max",
+ upgrade_url:
+ "https://screenpipe.com/account/billing?target_plan=pro_max&interval=month",
+ },
+ }),
+ } as Response);
+
+ const { result } = renderHook(() => useUsageStatus());
+ await waitFor(() => expect(result.current?.cost_limit_reached).toBe(true));
+ expect(result.current?.hosted_ai).toMatchObject({
+ plan: "business",
+ allowances: null,
+ upgrade: {
+ requiredPlan: "business_max",
+ upgradeUrl:
+ "https://screenpipe.com/account/billing?target_plan=pro_max&interval=month",
+ },
+ });
+ expect(result.current?.hosted_ai?.allowance_managed_by).toBeUndefined();
});
it("clears stale Basic status immediately while a new token is resolving", async () => {
diff --git a/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx b/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx
index c9d5e6035..4a049d95b 100644
--- a/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx
+++ b/apps/screenpipe-app-tauri/lib/hooks/use-usage-status.tsx
@@ -41,7 +41,7 @@ export interface HostedAiAllowance {
export interface HostedAiUsage {
plan: string | null;
- allowance_managed_by: "cloudflare";
+ allowance_managed_by?: "cloudflare";
usage_as_of: string | null;
allowances: HostedAiAllowance[] | null;
upgrade: QuotaUpgradeAction | null;
@@ -59,6 +59,9 @@ export interface UsageStatus {
upsell_banner?: boolean;
/** Server-backed Free/Basic eligibility. Missing or unresolved is false. */
upgrade_eligible?: boolean;
+ /** Provider-cost admission is currently exhausted. Null means the server
+ * could not resolve the live allowance and must not be presented as empty. */
+ cost_limit_reached: boolean | null;
/** Cloudflare allowance utilization for the authenticated user's metadata. */
hosted_ai?: HostedAiUsage;
}
@@ -112,8 +115,8 @@ function parseHostedAiUsage(value: unknown): HostedAiUsage | undefined {
required_plan?: unknown;
upgrade_url?: unknown;
};
- if (candidate.allowance_managed_by !== "cloudflare") return undefined;
- const allowances = candidate.allowances === null
+ const cloudflareManaged = candidate.allowance_managed_by === "cloudflare";
+ const allowances = !cloudflareManaged || candidate.allowances === null
? null
: Array.isArray(candidate.allowances)
? candidate.allowances
@@ -122,7 +125,7 @@ function parseHostedAiUsage(value: unknown): HostedAiUsage | undefined {
: null;
return {
plan: typeof candidate.plan === "string" ? candidate.plan : null,
- allowance_managed_by: "cloudflare",
+ ...(cloudflareManaged ? { allowance_managed_by: "cloudflare" as const } : {}),
usage_as_of:
typeof candidate.usage_as_of === "string" ? candidate.usage_as_of : null,
allowances,
@@ -169,6 +172,10 @@ export function useUsageStatus(): UsageStatus | null {
resets_at: json.resets_at ?? "",
upsell_banner: json.upsell_banner === true,
upgrade_eligible: json.upgrade_eligible === true,
+ cost_limit_reached:
+ typeof json.cost_limit_reached === "boolean"
+ ? json.cost_limit_reached
+ : null,
hosted_ai: parseHostedAiUsage(json.hosted_ai),
},
});
diff --git a/packages/ai-gateway/src/handlers/chat.ts b/packages/ai-gateway/src/handlers/chat.ts
index a97c9b672..a5e4ef789 100644
--- a/packages/ai-gateway/src/handlers/chat.ts
+++ b/packages/ai-gateway/src/handlers/chat.ts
@@ -20,9 +20,8 @@ import {
} from '../services/cloudflare-ai-gateway';
import {
ARGUS_BACKGROUND_FALLBACK_MODEL,
- prepareArgusBackgroundFallbackBody,
isProviderQuotaOrBillingLimitError,
- shouldUseArgusBackgroundFallback,
+ resolveArgusBackgroundFallbackBody,
} from '../services/background-limit-fallback';
import { getHostedAiCapacityUpgrade } from '../services/hosted-ai-policy';
@@ -438,9 +437,9 @@ export async function tryArgusBackgroundFallback(
error: unknown,
attemptModel: typeof tryModel = tryModel,
): Promise<Response | null> {
- if (!shouldUseArgusBackgroundFallback({ enabled, error, body, env })) return null;
+ const fallbackBody = resolveArgusBackgroundFallbackBody({ enabled, error, body, env });
+ if (!fallbackBody) return null;
try {
- const fallbackBody = prepareArgusBackgroundFallbackBody(body);
const response = await attemptModel(
ARGUS_BACKGROUND_FALLBACK_MODEL,
fallbackBody,
diff --git a/packages/ai-gateway/src/index.ts b/packages/ai-gateway/src/index.ts
index a65b371a9..f1307e9b4 100644
--- a/packages/ai-gateway/src/index.ts
+++ b/packages/ai-gateway/src/index.ts
@@ -90,8 +90,7 @@ import {
} from './services/cloudflare-ai-gateway';
import { getCloudflareHostedChatUsage } from './services/cloudflare-ai-gateway-usage';
import {
- ARGUS_BACKGROUND_FALLBACK_MODEL,
- shouldUseArgusBackgroundFallback,
+ resolveArgusBackgroundFallbackBody,
} from './services/background-limit-fallback';
// import { handleTTSWebSocketUpgrade } from './handlers/voice-ws';
@@ -617,14 +616,15 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
status: 429,
code: creditsExhausted ? 'credits_exhausted' : 'daily_limit_exceeded',
};
- if (shouldUseArgusBackgroundFallback({
+ const argusFallbackBody = resolveArgusBackgroundFallbackBody({
enabled: isBackgroundRequest(request) && hasPaidHostedAiPlan(authResult),
error: allowanceError,
body,
env,
- })) {
+ });
+ if (argusFallbackBody) {
legacyArgusFallback = true;
- body = { ...body, model: ARGUS_BACKGROUND_FALLBACK_MODEL };
+ body = argusFallbackBody;
} else return addCorsHeaders(createErrorResponse(429, JSON.stringify({
...buildDailyUsageLimitError(
usage,
@@ -704,14 +704,15 @@ export async function handleRequest(request: Request, env: Env, ctx: ExecutionCo
status: costReservation.response.status,
});
const allowanceError = { status: costReservation.response.status, code: rejectionReason };
- if (shouldUseArgusBackgroundFallback({
+ const argusFallbackBody = resolveArgusBackgroundFallbackBody({
enabled: isBackgroundRequest(request) && hasPaidHostedAiPlan(authResult),
error: allowanceError,
body,
env,
- })) {
+ });
+ if (argusFallbackBody) {
legacyArgusFallback = true;
- body = { ...body, model: ARGUS_BACKGROUND_FALLBACK_MODEL };
+ body = argusFallbackBody;
} else {
if (freeChatLease) await releaseFreeChatLease(env, freeChatLease);
return costReservation.response;
diff --git a/packages/ai-gateway/src/services/background-limit-fallback.ts b/packages/ai-gateway/src/services/background-limit-fallback.ts
index 3fe18e275..0b9f3e121 100644
--- a/packages/ai-gateway/src/services/background-limit-fallback.ts
+++ b/packages/ai-gateway/src/services/background-limit-fallback.ts
@@ -289,3 +289,19 @@ export function shouldUseArgusBackgroundFallback(input: {
isAccountLocalAllowanceError(input.error) ||
isProviderQuotaOrBillingLimitError(input.error));
}
+
+/**
+ * Resolve the complete provider-compatible rescue request in one operation.
+ * Admission gates and provider failures both use this helper so no caller can
+ * select Argus while accidentally skipping its role, context, tool-schema, or
+ * output-token normalization.
+ */
+export function resolveArgusBackgroundFallbackBody(input: {
+ enabled: boolean;
+ error: unknown;
+ body: RequestBody;
+ env: Pick<Env, 'SCREENPIPE_QWEN35_API_KEY' | 'SCREENPIPE_QWEN35_URL'>;
+}): RequestBody | null {
+ if (!shouldUseArgusBackgroundFallback(input)) return null;
+ return prepareArgusBackgroundFallbackBody(input.body);
+}
diff --git a/packages/ai-gateway/src/test/background-argus-fallback.unit.test.ts b/packages/ai-gateway/src/test/background-argus-fallback.unit.test.ts
index 670f8c723..92ef8d7ea 100644
--- a/packages/ai-gateway/src/test/background-argus-fallback.unit.test.ts
+++ b/packages/ai-gateway/src/test/background-argus-fallback.unit.test.ts
@@ -12,6 +12,7 @@ import {
isAccountLocalAllowanceError,
isProviderQuotaOrBillingLimitError,
prepareArgusBackgroundFallbackBody,
+ resolveArgusBackgroundFallbackBody,
shouldUseArgusBackgroundFallback,
} from '../services/background-limit-fallback';
import { HostedChatAllowanceExceededError } from '../services/cloudflare-ai-gateway';
@@ -57,6 +58,34 @@ describe('paid background Pipe Argus fallback', () => {
expect(shouldUseArgusBackgroundFallback({ enabled: true, error: allowanceError, body: imageBody, env })).toBe(false);
});
+ it('resolves eligibility and the complete Argus request shape together', () => {
+ const fallbackBody = resolveArgusBackgroundFallbackBody({
+ enabled: true,
+ error: { status: 429, code: 'daily_cost_limit_exceeded' },
+ body: {
+ ...body,
+ messages: [
+ { role: 'developer', content: 'Run this background Pipe.' } as any,
+ { role: 'user', content: 'Summarize today.' },
+ ],
+ max_completion_tokens: 32_000,
+ },
+ env,
+ });
+
+ expect(fallbackBody).not.toBeNull();
+ expect(fallbackBody?.model).toBe(ARGUS_BACKGROUND_FALLBACK_MODEL);
+ expect(fallbackBody?.messages[0].role).toBe('user');
+ expect(fallbackBody?.max_completion_tokens).toBeUndefined();
+ expect(fallbackBody?.max_tokens).toBe(ARGUS_BACKGROUND_MAX_COMPLETION_TOKENS);
+ expect(resolveArgusBackgroundFallbackBody({
+ enabled: false,
+ error: allowanceError,
+ body,
+ env,
+ })).toBeNull();
+ });
+
it('serves streaming or JSON Pipe responses directly from Argus without Cloudflare metadata', async () => {
for (const stream of [false, true]) {
const attempt = mock(async (