Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ui): paid API fallback switch for missions under Settings > API Keys

rubenluetke10-beep089502de02d4
diff --git a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx
index a75044fcf0..654c4fae67 100644
--- a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.test.tsx
@@ -4,6 +4,8 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { CapacityDecisionPanel } from "@/components/missions/CapacityDecisionPanel";
import { useI18nStore } from "@/i18n";
+import { MISSION_BILLING_ANCHOR, requestedApiKeysTab, takeApiKeysAnchor, clearApiKeysTabRequest } from "@/lib/apiKeysTab";
+import { useEventStore } from "@/store/events";
import type { MissionState, PaidOffer } from "@/types/missions";
const MISSION_ID = "mission-1";
@@ -15,6 +17,8 @@ const OFFER: PaidOffer = {
cost_cap_usd: 2,
reason: "provider_quota",
open_steps: 1,
+ spent_usd: 0,
+ covers_critic: true,
};
beforeEach(() => {
@@ -116,6 +120,50 @@ describe("CapacityDecisionPanel", () => {
expect((approve as HTMLButtonElement).disabled).toBe(true);
});
+ it("shows what the mission already spent and that the review is covered", async () => {
+ stubServer({ ...OFFER, reason: "paid_cap_reached", spent_usd: 0.85 });
+ renderPanel();
+
+ expect(await screen.findByText("Already spent")).toBeTruthy();
+ expect(screen.getByText("$0.85")).toBeTruthy();
+ expect(screen.getByText("Approved cost cap reached")).toBeTruthy();
+ expect(screen.getByText(/also pays for the checks that review the result/)).toBeTruthy();
+ });
+
+ it("leaves the spent line out while nothing was spent", async () => {
+ stubServer(OFFER);
+ renderPanel();
+
+ await screen.findByText("claude-api");
+ expect(screen.queryByText("Already spent")).toBeNull();
+ });
+
+ it("names the reasons that come from automatic paid use", async () => {
+ stubServer({ ...OFFER, reason: "paid_daily_cap_reached" });
+ renderPanel();
+ expect(await screen.findByText("Daily limit for automatic paid use reached")).toBeTruthy();
+ // The setting is already on; pointing at it would not help.
+ expect(screen.queryByTestId("capacity-settings-hint")).toBeNull();
+
+ cleanup();
+ stubServer({ ...OFFER, reason: "paid_consent_revoked" });
+ renderPanel();
+ expect(await screen.findByText("Automatic paid use was switched off")).toBeTruthy();
+ expect(screen.getByTestId("capacity-settings-hint")).toBeTruthy();
+ });
+
+ it("links to the paid-fallback setting on the API Keys page", async () => {
+ stubServer(OFFER);
+ useEventStore.getState().setActiveSection("visualization");
+ renderPanel();
+
+ fireEvent.click(await screen.findByRole("button", { name: "Always allow this in Settings → API Keys" }));
+ expect(useEventStore.getState().activeSection).toBe("apikeys");
+ expect(requestedApiKeysTab()).toBe("agents");
+ expect(takeApiKeysAnchor(MISSION_BILLING_ANCHOR)).toBe(true);
+ clearApiKeysTabRequest();
+ });
+
it("renders nothing for a mission that is not waiting", () => {
const fetchMock = stubServer(OFFER);
const { container } = renderPanel("RUNNING");
diff --git a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx
index c3eb6b0932..221444389e 100644
--- a/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx
+++ b/jarvis/ui/web/frontend/src/components/missions/CapacityDecisionPanel.tsx
@@ -5,19 +5,28 @@
* Nothing here is automatic. The offer (provider, model, estimated cost, hard
* cap, reason) is shown before any paid use; an approval needs a second,
* explicit confirmation and echoes exactly the offer shown, so a changed
- * offer is rejected by the server instead of silently billed.
+ * offer is rejected by the server instead of silently billed. An approval
+ * also pays for the review of the result, under the same cap.
+ *
+ * Missions can instead continue on an API key by themselves — a setting on
+ * the API Keys page, which the panel links to.
*/
import { useEffect, useState } from "react";
-import { AlertTriangle, Clock3, CreditCard, Loader2, X } from "lucide-react";
+import { AlertTriangle, Clock3, CreditCard, Loader2, Settings2, X } from "lucide-react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { Button } from "@/components/ui/button";
import { fill, useT } from "@/i18n";
+import { MISSION_BILLING_ANCHOR, requestApiKeysTab } from "@/lib/apiKeysTab";
+import { useEventStore } from "@/store/events";
import type { CapacityDecision, MissionState, PaidOffer } from "@/types/missions";
import { decideCapacity, fetchPaidOffer, paidOfferQueryKey } from "./api";
const OFFER_REFRESH_MS = 15_000;
+/** Waits the paid-fallback setting would have avoided; a spent cap is not one. */
+const SETTING_HELPS = new Set(["provider_quota", "provider_auth", "provider_unavailable", "paid_consent_revoked"]);
+
function usd(value: number): string {
return `$${value.toFixed(2)}`;
}
@@ -31,6 +40,7 @@ export function CapacityDecisionPanel({
}) {
const t = useT();
const queryClient = useQueryClient();
+ const setActiveSection = useEventStore((s) => s.setActiveSection);
const waiting = missionId !== null && state === "WAITING_CAPACITY";
const [confirming, setConfirming] = useState<CapacityDecision | null>(null);
useEffect(() => setConfirming(null), [missionId, state]);
@@ -94,6 +104,12 @@ export function CapacityDecisionPanel({
</dd>
<dt className="text-muted-foreground">{t("capacity_decision.cap")}</dt>
<dd className="font-mono text-foreground">{usd(offer.cost_cap_usd)}</dd>
+ {offer.spent_usd > 0 && (
+ <>
+ <dt className="text-muted-foreground">{t("capacity_decision.spent")}</dt>
+ <dd className="font-mono text-foreground">{usd(offer.spent_usd)}</dd>
+ </>
+ )}
<dt className="text-muted-foreground">{t("capacity_decision.reason")}</dt>
<dd className="text-foreground">
{t(`capacity_decision.reasons.${offer.reason}`)}
@@ -112,7 +128,10 @@ export function CapacityDecisionPanel({
</p>
)}
- <p className="text-muted-foreground">{t("capacity_decision.scope")}</p>
+ <p className="text-muted-foreground">
+ {t("capacity_decision.scope")}
+ {offer?.covers_critic ? ` ${t("capacity_decision.covers_review")}` : ""}
+ </p>
{confirming === null ? (
<div className="flex flex-wrap gap-2">
@@ -166,6 +185,21 @@ export function CapacityDecisionPanel({
</div>
)}
+ {offer && SETTING_HELPS.has(offer.reason) && (
+ <button
+ type="button"
+ data-testid="capacity-settings-hint"
+ onClick={() => {
+ requestApiKeysTab("agents", MISSION_BILLING_ANCHOR);
+ setActiveSection("apikeys");
+ }}
+ className="inline-flex items-center gap-1.5 rounded-sm text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Settings2 aria-hidden="true" className="h-3.5 w-3.5" />
+ {t("capacity_decision.settings_hint")}
+ </button>
+ )}
+
{decision.isError && (
<p className="text-destructive">
{fill(t("capacity_decision.error"), { detail: decision.error.message })}
diff --git a/jarvis/ui/web/frontend/src/components/missions/api.ts b/jarvis/ui/web/frontend/src/components/missions/api.ts
index c5f0575977..7be040c50b 100644
--- a/jarvis/ui/web/frontend/src/components/missions/api.ts
+++ b/jarvis/ui/web/frontend/src/components/missions/api.ts
@@ -9,6 +9,7 @@ import type {
CriticVerdictReady,
EventEnvelope,
MissionChanges,
+ MissionBilling,
MissionDetail,
MissionResult,
MissionSummary,
@@ -131,6 +132,44 @@ export async function decideCapacity(
);
}
+export const MISSION_BILLING_KEY = ["mission-billing"] as const;
+
+function isMissionBilling(body: unknown): body is MissionBilling {
+ return (
+ !!body &&
+ typeof body === "object" &&
+ typeof (body as MissionBilling).paid_api_fallback === "boolean" &&
+ typeof (body as MissionBilling).subscription_mode === "boolean"
+ );
+}
+
+/**
+ * Whether missions may continue on a paid API key once every subscription is
+ * used up. `null` when the backend does not offer the setting (an older
+ * server answers 404), so the page leaves the row out instead of guessing.
+ */
+export async function fetchMissionBilling(): Promise<MissionBilling | null> {
+ const res = await fetch("/api/mission-billing", { cache: "no-store" });
+ if (res.status === 404) return null;
+ const body: unknown = await res.json().catch(() => null);
+ if (!res.ok) {
+ const detail = body && typeof body === "object" && "detail" in body ? (body as { detail: unknown }).detail : null;
+ throw new Error(typeof detail === "string" ? detail : `HTTP ${res.status}`);
+ }
+ return isMissionBilling(body) ? body : null;
+}
+
+/** Switch the paid fallback; the answer is the state the server now holds. */
+export async function saveMissionBilling(paidApiFallback: boolean): Promise<MissionBilling> {
+ const body = await requestJson<unknown>("/api/mission-billing", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ paid_api_fallback: paidApiFallback }),
+ });
+ if (!isMissionBilling(body)) throw new Error("Unexpected answer from the server");
+ return body;
+}
+
export async function cancelMission(id: string): Promise<void> {
const res = await fetch(`${API_BASE}/${encodeURIComponent(id)}/cancel`, {
method: "POST",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 24e887bf26..f015b14147 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -4194,8 +4194,10 @@
"files": "Gespeicherte Dateien: {files}.",
"wait": "Die Mission wartet, bis wieder Kapazität verfügbar ist.",
"wait_auth": "Die Mission wartet, bis du dich wieder anmeldest.",
- "paid": "Kostenpflichtige API-Nutzung nur mit deiner ausdrücklichen Freigabe unter „Artefakte“.",
- "paid_cap_reached": "Die freigegebene Kostengrenze für {provider} ist erreicht."
+ "paid": "Kostenpflichtige API-Nutzung nur mit deiner Freigabe unter „Artefakte“ oder wenn du sie unter Einstellungen → API-Keys erlaubst.",
+ "paid_cap_reached": "Die freigegebene Kostengrenze für {provider} ist erreicht.",
+ "paid_daily_cap_reached": "Die automatische kostenpflichtige Nutzung von {provider} hat ihr Tageslimit erreicht.",
+ "paid_consent_revoked": "Die automatische kostenpflichtige Nutzung von {provider} wurde ausgeschaltet."
}
},
"mission_tool_approvals": {
@@ -7046,16 +7048,21 @@
"estimate": "Geschätzte Kosten",
"estimate_value": "ca. {cost} für {steps} offene Teilschritte",
"cap": "Harte Kostengrenze",
+ "spent": "Bereits ausgegeben",
"reason": "Grund",
"reasons": {
"provider_quota": "Abo-Kapazität ausgeschöpft",
"provider_auth": "Abo-Anmeldung abgelaufen",
"provider_unavailable": "Abo momentan nicht nutzbar",
- "paid_cap_reached": "Freigegebene Kostengrenze erreicht"
+ "paid_cap_reached": "Freigegebene Kostengrenze erreicht",
+ "paid_daily_cap_reached": "Tageslimit für automatische kostenpflichtige Nutzung erreicht",
+ "paid_consent_revoked": "Automatische kostenpflichtige Nutzung wurde ausgeschaltet"
},
"no_offer": "Kein kostenpflichtiger API-Zugang mit bekanntem Preis verfügbar. Die Mission wartet auf ihr Abo.",
"over_cap": "Die Schätzung liegt über der Kostengrenze. Die Mission pausiert, sobald die Grenze erreicht ist; der Stand bleibt gesichert.",
- "scope": "Eine Freigabe gilt nur für diese Mission und diesen einen Lauf – keine dauerhafte oder globale Freigabe. Ohne Freigabe wird nichts berechnet.",
+ "scope": "Eine Freigabe gilt nur für diese Mission und diesen einen Lauf, nie für spätere Missionen.",
+ "covers_review": "Die Freigabe deckt auch die Prüfung des Ergebnisses ab.",
+ "settings_hint": "Immer erlauben unter Einstellungen → API-Keys",
"wait": "Warten",
"approve": "Kostenpflichtige API für diese Mission freigeben",
"cancel": "Mission abbrechen",
@@ -7071,6 +7078,7 @@
"cancel": "Entscheidung: abgebrochen."
},
"logged_offer": "{provider} / {model}, geschätzt {cost}, Grenze {cap}.",
- "paid_usage": "Kostenpflichtiger Lauf auf {provider} / {model}: tatsächlich {cost} (geschätzt {estimate}, Grenze {cap})."
+ "paid_usage": "Kostenpflichtiger Lauf auf {provider} / {model}: tatsächlich {cost} (geschätzt {estimate}, Grenze {cap}).",
+ "paid_usage_automatic": "Automatischer kostenpflichtiger Lauf auf {provider} / {model}: tatsächlich {cost} (geschätzt {estimate}, Grenze {cap})."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 015a6ba398..cbe5d90ddf 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -4194,8 +4194,10 @@
"files": "Files saved: {files}.",
"wait": "The mission is waiting until capacity is available again.",
"wait_auth": "The mission is waiting until you sign in again.",
- "paid": "Paid API use only with your explicit approval in Artifacts.",
- "paid_cap_reached": "The approved cost limit for {provider} is reached."
+ "paid": "Paid API use only with your approval in Artifacts, or when you allow it in Settings → API Keys.",
+ "paid_cap_reached": "The approved cost limit for {provider} is reached.",
+ "paid_daily_cap_reached": "Automatic paid use on {provider} reached its daily limit.",
+ "paid_consent_revoked": "Automatic paid use on {provider} was switched off."
}
},
"mission_tool_approvals": {
@@ -7046,16 +7048,21 @@
"estimate": "Estimated cost",
"estimate_value": "about {cost} for {steps} open steps",
"cap": "Hard cost cap",
+ "spent": "Already spent",
"reason": "Reason",
"reasons": {
"provider_quota": "Subscription capacity used up",
"provider_auth": "Subscription sign-in expired",
"provider_unavailable": "Subscription cannot be used right now",
- "paid_cap_reached": "Approved cost cap reached"
+ "paid_cap_reached": "Approved cost cap reached",
+ "paid_daily_cap_reached": "Daily limit for automatic paid use reached",
+ "paid_consent_revoked": "Automatic paid use was switched off"
},
"no_offer": "No paid API access with a known price is available. The mission waits for its subscription.",
"over_cap": "The estimate is above the cost cap. The mission pauses once the cap is reached; its progress stays saved.",
- "scope": "An approval covers only this mission and this one run – no permanent or global approval. Nothing is billed without it.",
+ "scope": "An approval covers only this mission and this one run, never later missions.",
+ "covers_review": "The approval also pays for the checks that review the result.",
+ "settings_hint": "Always allow this in Settings → API Keys",
"wait": "Wait",
"approve": "Approve paid API for this mission",
"cancel": "Cancel mission",
@@ -7071,6 +7078,7 @@
"cancel": "Decision: cancelled."
},
"logged_offer": "{provider} / {model}, estimated {cost}, cap {cap}.",
- "paid_usage": "Paid run on {provider} / {model}: actual {cost} (estimated {estimate}, cap {cap})."
+ "paid_usage": "Paid run on {provider} / {model}: actual {cost} (estimated {estimate}, cap {cap}).",
+ "paid_usage_automatic": "Automatic paid run on {provider} / {model}: actual {cost} (estimated {estimate}, cap {cap})."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index eca4b54ea3..b6cfe91718 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -4194,8 +4194,10 @@
"files": "Archivos guardados: {files}.",
"wait": "La misión espera hasta que vuelva a haber capacidad.",
"wait_auth": "La misión espera hasta que vuelvas a iniciar sesión.",
- "paid": "Uso de API de pago solo con tu aprobación explícita en Artefactos.",
- "paid_cap_reached": "Se alcanzó el límite de coste aprobado para {provider}."
+ "paid": "Uso de API de pago solo con tu aprobación en Artefactos o si lo permites en Ajustes → Claves API.",
+ "paid_cap_reached": "Se alcanzó el límite de coste aprobado para {provider}.",
+ "paid_daily_cap_reached": "El uso de pago automático de {provider} alcanzó su límite diario.",
+ "paid_consent_revoked": "Se desactivó el uso de pago automático de {provider}."
}
},
"mission_tool_approvals": {
@@ -7046,16 +7048,21 @@
"estimate": "Coste estimado",
"estimate_value": "aprox. {cost} para {steps} pasos pendientes",
"cap": "Límite de coste estricto",
+ "spent": "Ya gastado",
"reason": "Motivo",
"reasons": {
"provider_quota": "Capacidad de la suscripción agotada",
"provider_auth": "Sesión de la suscripción caducada",
"provider_unavailable": "La suscripción no se puede usar ahora",
- "paid_cap_reached": "Límite de coste aprobado alcanzado"
+ "paid_cap_reached": "Límite de coste aprobado alcanzado",
+ "paid_daily_cap_reached": "Límite diario de uso de pago automático alcanzado",
+ "paid_consent_revoked": "Se desactivó el uso de pago automático"
},
"no_offer": "No hay acceso de pago a la API con precio conocido. La misión espera a su suscripción.",
"over_cap": "La estimación supera el límite de coste. La misión se pausa al alcanzarlo; el progreso queda guardado.",
- "scope": "Una aprobación vale solo para esta misión y esta ejecución – nunca permanente ni global. Sin ella no se cobra nada.",
+ "scope": "Una aprobación vale solo para esta misión y esta ejecución, nunca para misiones posteriores.",
+ "covers_review": "La aprobación también cubre la revisión del resultado.",
+ "settings_hint": "Permitirlo siempre en Ajustes → Claves API",
"wait": "Esperar",
"approve": "Aprobar API de pago para esta misión",
"cancel": "Cancelar misión",
@@ -7071,6 +7078,7 @@
"cancel": "Decisión: cancelada."
},
"logged_offer": "{provider} / {model}, estimado {cost}, límite {cap}.",
- "paid_usage": "Ejecución de pago en {provider} / {model}: real {cost} (estimado {estimate}, límite {cap})."
+ "paid_usage": "Ejecución de pago en {provider} / {model}: real {cost} (estimado {estimate}, límite {cap}).",
+ "paid_usage_automatic": "Ejecución de pago automática en {provider} / {model}: real {cost} (estimado {estimate}, límite {cap})."
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
index cdf2878d51..9c2dc348d1 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/de.json
@@ -155,5 +155,25 @@
"thinking_pick": "Antwortet und nutzt Werkzeuge während eines Gesprächs",
"voice_ready": "Bereit",
"voice_not_ready": "Nicht eingerichtet"
+ },
+ "mission_billing": {
+ "section": "Missionen",
+ "title": "Mit API-Keys weitermachen, wenn die Abos aufgebraucht sind",
+ "state_off": "Aus · Missionen warten, bis ein Abo wieder frei ist",
+ "state_on": "An · {provider} · höchstens {mission_cap} pro Mission, {daily_cap} pro Tag",
+ "state_on_no_key": "An · noch kein API-Key mit bekanntem Preis",
+ "state_key_only": "Missionen laufen schon über deine API-Keys",
+ "state_no_key": "Braucht einen API-Key mit bekanntem Preis",
+ "spent": "{amount} in den letzten 24 Stunden ausgegeben",
+ "less_than_cent": "weniger als $0.01",
+ "load_error": "Diese Einstellung konnte nicht geladen werden: {detail}",
+ "save_error": "Nicht gespeichert: {detail}",
+ "confirm_title": "Mit deinem API-Key weitermachen?",
+ "confirm_intro": "Wenn alle verbundenen Abos aufgebraucht sind, laufen Missionen mit deinem eigenen API-Key weiter, statt zu warten.",
+ "confirm_billing": "{provider} rechnet jede Anfrage über diesen Key ab:",
+ "confirm_no_key": "Es ist noch kein API-Key mit bekanntem Preis eingerichtet, also kann nichts abgerechnet werden.",
+ "confirm_caps": "Jede Mission stoppt bei {mission_cap}, die gesamte automatische Nutzung bei {daily_cap} pro Tag.",
+ "confirm_off": "Du kannst das jederzeit ausschalten. Es gilt ab der nächsten Anfrage.",
+ "confirm_action": "Einschalten"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
index e5729ad906..5503a4922b 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/en.json
@@ -155,5 +155,25 @@
"thinking_pick": "Answers and uses tools during a call",
"voice_ready": "Ready",
"voice_not_ready": "Not set up"
+ },
+ "mission_billing": {
+ "section": "Missions",
+ "title": "Continue on API keys when subscriptions run out",
+ "state_off": "Off · missions wait until a subscription has room again",
+ "state_on": "On · {provider} · at most {mission_cap} per mission, {daily_cap} a day",
+ "state_on_no_key": "On · no API key with a known price yet",
+ "state_key_only": "Missions already run on your API keys",
+ "state_no_key": "Needs an API key with a known price",
+ "spent": "{amount} spent in the last 24 hours",
+ "less_than_cent": "less than $0.01",
+ "load_error": "This setting could not be loaded: {detail}",
+ "save_error": "Not saved: {detail}",
+ "confirm_title": "Continue on your API key?",
+ "confirm_intro": "When every connected subscription is used up, missions keep running on your own API key instead of waiting.",
+ "confirm_billing": "{provider} bills that key for every request:",
+ "confirm_no_key": "No API key with a known price is set up yet, so nothing can be billed.",
+ "confirm_caps": "Each mission stops at {mission_cap}, and all automatic use stops at {daily_cap} per day.",
+ "confirm_off": "You can switch this off at any time. It applies from the next request on.",
+ "confirm_action": "Turn on"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
index 0019d40356..9deaf94151 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/es.json
@@ -155,5 +155,25 @@
"thinking_pick": "Responde y usa herramientas durante una llamada",
"voice_ready": "Listo",
"voice_not_ready": "Sin configurar"
+ },
+ "mission_billing": {
+ "section": "Misiones",
+ "title": "Seguir con claves API cuando se agoten las suscripciones",
+ "state_off": "Desactivado · las misiones esperan hasta que una suscripción vuelva a tener capacidad",
+ "state_on": "Activado · {provider} · como máximo {mission_cap} por misión, {daily_cap} al día",
+ "state_on_no_key": "Activado · aún no hay una clave API con precio conocido",
+ "state_key_only": "Las misiones ya funcionan con tus claves API",
+ "state_no_key": "Necesita una clave API con precio conocido",
+ "spent": "{amount} gastado en las últimas 24 horas",
+ "less_than_cent": "menos de $0.01",
+ "load_error": "No se pudo cargar este ajuste: {detail}",
+ "save_error": "No se guardó: {detail}",
+ "confirm_title": "¿Seguir con tu clave API?",
+ "confirm_intro": "Cuando todas las suscripciones conectadas se agotan, las misiones siguen funcionando con tu propia clave API en lugar de esperar.",
+ "confirm_billing": "{provider} cobra cada solicitud a esa clave:",
+ "confirm_no_key": "Todavía no hay ninguna clave API con precio conocido, así que no se puede cobrar nada.",
+ "confirm_caps": "Cada misión se detiene en {mission_cap}, y todo el uso automático se detiene en {daily_cap} al día.",
+ "confirm_off": "Puedes desactivarlo en cualquier momento. Se aplica desde la siguiente solicitud.",
+ "confirm_action": "Activar"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/providers/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/providers/zh.json
index 5b4b9f6742..6ad337ef5c 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/providers/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/providers/zh.json
@@ -154,5 +154,25 @@
"thinking_pick": "在通话中回答并使用工具",
"voice_ready": "就绪",
"voice_not_ready": "未设置"
+ },
+ "mission_billing": {
+ "section": "任务",
+ "title": "订阅用完时改用 API 密钥继续",
+ "state_off": "关闭 · 任务会等待,直到某个订阅重新有额度",
+ "state_on": "开启 · {provider} · 每个任务最多 {mission_cap},每天最多 {daily_cap}",
+ "state_on_no_key": "开启 · 还没有价格已知的 API 密钥",
+ "state_key_only": "任务已经在使用你的 API 密钥运行",
+ "state_no_key": "需要一个价格已知的 API 密钥",
+ "spent": "过去 24 小时已花费 {amount}",
+ "less_than_cent": "不到 $0.01",
+ "load_error": "无法加载此设置:{detail}",
+ "save_error": "未保存:{detail}",
+ "confirm_title": "改用你的 API 密钥继续?",
+ "confirm_intro": "当所有已连接的订阅都用完时,任务会使用你自己的 API 密钥继续运行,而不是等待。",
+ "confirm_billing": "{provider} 会按每次请求向该密钥计费:",
+ "confirm_no_key": "还没有设置价格已知的 API 密钥,因此不会产生任何费用。",
+ "confirm_caps": "每个任务在 {mission_cap} 时停止,所有自动使用每天在 {daily_cap} 时停止。",
+ "confirm_off": "你可以随时关闭。从下一次请求开始生效。",
+ "confirm_action": "开启"
}
}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index b7944f98b3..39d6b062f3 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -4196,8 +4196,10 @@
"files": "已保存的文件:{files}。",
"wait": "任务会等待,直到额度重新可用。",
"wait_auth": "任务会等待,直到你重新登录。",
- "paid": "只有在“作品”中明确批准后,才会使用付费 API。",
- "paid_cap_reached": "已达到为 {provider} 批准的费用上限。"
+ "paid": "只有在“作品”中批准,或在 设置 → API 密钥 中允许后,才会使用付费 API。",
+ "paid_cap_reached": "已达到为 {provider} 批准的费用上限。",
+ "paid_daily_cap_reached": "{provider} 的自动付费使用已达到每日上限。",
+ "paid_consent_revoked": "{provider} 的自动付费使用已关闭。"
}
},
"mission_tool_approvals": {
@@ -7048,16 +7050,21 @@
"estimate": "预估费用",
"estimate_value": "约 {cost},用于 {steps} 个未完成步骤",
"cap": "费用硬上限",
+ "spent": "已花费",
"reason": "原因",
"reasons": {
"provider_quota": "订阅额度已用完",
"provider_auth": "订阅登录已过期",
"provider_unavailable": "订阅目前无法使用",
- "paid_cap_reached": "已达到批准的费用上限"
+ "paid_cap_reached": "已达到批准的费用上限",
+ "paid_daily_cap_reached": "自动付费使用已达到每日上限",
+ "paid_consent_revoked": "自动付费使用已关闭"
},
"no_offer": "没有可用且价格已知的付费 API。任务将等待其订阅恢复。",
"over_cap": "预估费用高于费用上限。达到上限时任务会暂停,进度会保留。",
- "scope": "批准只适用于此任务的这一次运行——不会永久或全局生效。未经批准不会产生任何费用。",
+ "scope": "批准只适用于此任务的这一次运行,不适用于之后的任务。",
+ "covers_review": "批准也涵盖对结果的审查。",
+ "settings_hint": "在 设置 → API 密钥 中始终允许",
"wait": "等待",
"approve": "为此任务批准付费 API",
"cancel": "取消任务",
@@ -7073,6 +7080,7 @@
"cancel": "决定:已取消。"
},
"logged_offer": "{provider} / {model},预估 {cost},上限 {cap}。",
- "paid_usage": "在 {provider} / {model} 上的付费运行:实际 {cost}(预估 {estimate},上限 {cap})。"
+ "paid_usage": "在 {provider} / {model} 上的付费运行:实际 {cost}(预估 {estimate},上限 {cap})。",
+ "paid_usage_automatic": "在 {provider} / {model} 上的自动付费运行:实际 {cost}(预估 {estimate},上限 {cap})。"
}
}
diff --git a/jarvis/ui/web/frontend/src/lib/apiKeysTab.ts b/jarvis/ui/web/frontend/src/lib/apiKeysTab.ts
index c525f33ace..4fd2bdbade 100644
--- a/jarvis/ui/web/frontend/src/lib/apiKeysTab.ts
+++ b/jarvis/ui/web/frontend/src/lib/apiKeysTab.ts
@@ -1,12 +1,14 @@
import type { SectionHealth } from "@/hooks/useProviders";
/**
- * Lets another part of the app open the API Keys page on one tab — the
- * first-run guide uses it to land on the Agents tab for subscriptions.
+ * Lets another part of the app open the API Keys page on one tab, and
+ * optionally on one setting of it — a mission waiting for capacity links to
+ * the paid-fallback switch on the Agents tab this way.
*
* The request is remembered, not just announced: the page loads lazily, so
- * it may mount after the event fired. It stays in force until the user picks
- * a tab themselves or the requester clears it.
+ * it may mount after the event fired. The page takes the tab when it mounts
+ * (or right away when it is already open); the setting takes its anchor once
+ * it has rendered.
*/
export const APIKEYS_TAB_EVENT = "jarvis:apikeys-tab";
@@ -14,22 +16,45 @@ export const APIKEYS_TAB_EVENT = "jarvis:apikeys-tab";
export const API_KEYS_TABS = ["realtime", "subagents", "jarvis-key", "advanced"] as const;
export type ApiKeysTab = (typeof API_KEYS_TABS)[number];
+/** The paid-fallback setting on the Agents tab (views/apikeys/MissionBilling). */
+export const MISSION_BILLING_ANCHOR = "mission-billing";
+
let requested: string | null = null;
+let requestedAnchor: string | null = null;
-/** Ask the API Keys page to show `tab`; `null` means its default tab. */
-export function requestApiKeysTab(tab: string | null): void {
+/**
+ * Ask the API Keys page to show `tab` (`null` means its default tab), and
+ * optionally to bring the setting whose element id is `anchor` into view.
+ */
+export function requestApiKeysTab(tab: string | null, anchor: string | null = null): void {
requested = tab;
+ requestedAnchor = anchor;
window.dispatchEvent(new CustomEvent<string | null>(APIKEYS_TAB_EVENT, { detail: tab }));
}
+/** True once for the setting `anchor` names, if it was asked for; clears it. */
+export function takeApiKeysAnchor(anchor: string): boolean {
+ if (requestedAnchor !== anchor) return false;
+ requestedAnchor = null;
+ return true;
+}
+
/** The tab another part of the app asked for, if any. */
export function requestedApiKeysTab(): string | null {
return requested;
}
+/** The tab another part of the app asked for, if any; the page takes it once. */
+export function takeRequestedApiKeysTab(): string | null {
+ const tab = requested;
+ requested = null;
+ return tab;
+}
+
/** Forget a request without moving the page (the user chose a tab). */
export function clearApiKeysTabRequest(): void {
requested = null;
+ requestedAnchor = null;
}
/**
diff --git a/jarvis/ui/web/frontend/src/types/missions.ts b/jarvis/ui/web/frontend/src/types/missions.ts
index 5e3231309e..b1d644c0bf 100644
--- a/jarvis/ui/web/frontend/src/types/missions.ts
+++ b/jarvis/ui/web/frontend/src/types/missions.ts
@@ -203,7 +203,11 @@ export type CapacityWaitReason =
| "provider_quota"
| "provider_auth"
| "provider_unavailable"
- | "paid_cap_reached";
+ | "paid_cap_reached"
+ // Automatic paid use (the setting in Settings → API Keys) hit its rolling
+ // 24 h limit, or was switched off while the mission ran on it.
+ | "paid_daily_cap_reached"
+ | "paid_consent_revoked";
/** Mirror of jarvis.missions.capacity.CapacityDecision. */
export type CapacityDecision = "wait" | "approve_paid" | "cancel";
@@ -225,6 +229,8 @@ export interface MissionPaidUsage extends BasePayload {
cost_usd: number;
cost_cap_usd: number;
estimated_cost_usd: number;
+ /** true = paid through the setting, false = a one-off manual approval. */
+ automatic: boolean;
}
/** GET /api/missions/{id}/paid-offer — what an approval would cover. */
@@ -235,6 +241,25 @@ export interface PaidOffer {
cost_cap_usd: number;
reason: string;
open_steps: number;
+ /** Already spent on paid calls by this mission. */
+ spent_usd: number;
+ /** The approval also pays for the review (critic) calls. */
+ covers_critic: boolean;
+}
+
+/**
+ * GET/PUT /api/mission-billing — whether missions may continue on a paid API
+ * key when every subscription is used up, and the hard limits that apply.
+ */
+export interface MissionBilling {
+ paid_api_fallback: boolean;
+ /** false on an install that never connected a subscription. */
+ subscription_mode: boolean;
+ per_mission_cap_usd: number;
+ daily_cap_usd: number;
+ spent_last_24h_usd: number;
+ /** The key that would be used first; null when no key has a known price. */
+ paid_provider: { provider: string; model: string; price_known: boolean } | null;
}
export interface PaidOfferResponse {
diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
index 5c5a6fbd1e..77f0d39744 100644
--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx
@@ -7,6 +7,7 @@ import { AgentsTab } from "@/views/apikeys/AgentsTab";
import { KeyField } from "@/views/apikeys/KeyField";
import { SettingsGroup } from "@/views/apikeys/settingsUi";
import { useProviders, useSectionHealth } from "@/hooks/useProviders";
+import { APIKEYS_TAB_EVENT, takeRequestedApiKeysTab } from "@/lib/apiKeysTab";
import { useProviderFamilies } from "@/lib/providerFamilies";
import { useLocaleChunk, useT } from "@/i18n";
import { cn } from "@/lib/utils";
@@ -18,7 +19,23 @@ const TABS = ["agents", "voice"] as const;
type Tab = (typeof TABS)[number];
const TAB_STORAGE_KEY = "jarvis.apikeys.tab";
+const isTab = (value: string | null): value is Tab => value !== null && (TABS as readonly string[]).includes(value);
+
+function rememberTab(tab: Tab) {
+ try {
+ localStorage.setItem(TAB_STORAGE_KEY, tab);
+ } catch {
+ // Remembering the tab is a convenience; without storage it resets.
+ }
+}
+
function initialTab(): Tab {
+ // A link from elsewhere in the app (requestApiKeysTab) wins over the last tab.
+ const asked = takeRequestedApiKeysTab();
+ if (isTab(asked)) {
+ rememberTab(asked);
+ return asked;
+ }
try {
const saved = localStorage.getItem(TAB_STORAGE_KEY);
if (saved && (TABS as readonly string[]).includes(saved)) return saved as Tab;
@@ -48,12 +65,20 @@ export function ApiKeysView() {
const [tab, setTab] = useState<Tab>(initialTab);
const choose = (next: Tab) => {
setTab(next);
- try {
- localStorage.setItem(TAB_STORAGE_KEY, next);
- } catch {
- // Remembering the tab is a convenience; without storage it resets.
- }
+ rememberTab(next);
};
+ // A link that arrives while the page is already open moves it too.
+ useEffect(() => {
+ const onRequest = () => {
+ const asked = takeRequestedApiKeysTab();
+ if (isTab(asked)) {
+ setTab(asked);
+ rememberTab(asked);
+ }
+ };
+ window.addEventListener(APIKEYS_TAB_EVENT, onRequest);
+ return () => window.removeEventListener(APIKEYS_TAB_EVENT, onRequest);
+ }, []);
if (!stringsReady) {
return (
diff --git a/jarvis/ui/web/frontend/src/views/MissionsView.tsx b/jarvis/ui/web/frontend/src/views/MissionsView.tsx
index f2dff1ba44..77cd65d6d7 100644
--- a/jarvis/ui/web/frontend/src/views/MissionsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/MissionsView.tsx
@@ -427,7 +427,7 @@ function ReasoningPanel() {
className="rounded border border-border/60 bg-card/30 p-2 text-xs"
>
<p className="text-foreground/90">
- {fill(t("capacity_decision.paid_usage"), {
+ {fill(t(p.automatic ? "capacity_decision.paid_usage_automatic" : "capacity_decision.paid_usage"), {
provider: p.provider,
model: p.model,
cost: `$${p.cost_usd.toFixed(4)}`,
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
index c4444e6c2d..42baee5c39 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.runs.test.tsx
@@ -600,6 +600,8 @@ describe("VisualizationView — a run waiting for capacity", () => {
cost_cap_usd: 2,
reason: "provider_quota",
open_steps: 1,
+ spent_usd: 0,
+ covers_critic: true,
};
/** Outputs as usual, plus the paid-offer and decision endpoints. */
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
index 5dfd10fe8d..18b6a75687 100644
--- a/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
+++ b/jarvis/ui/web/frontend/src/views/apikeys/AgentsTab.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Check, FlaskConical, Loader2, LogIn, LogOut } from "lucide-react";
import { ProviderLogo } from "@/components/providers/ProviderLogo";
@@ -45,6 +45,7 @@ import {
import { cn } from "@/lib/utils";
import { useEventStore } from "@/store/events";
import { KeyField } from "./KeyField";
+import { MissionBilling, type ProviderNamer } from "./MissionBilling";
import { SubscriptionAccounts } from "./SubscriptionAccounts";
import { accessPatch, familyAccess, nextDefault, onPatch, withPatch, type Access, type FamilyAccess } from "./agentAccess";
import { familyState, type FamilyState } from "./providers/familyState";
@@ -194,6 +195,15 @@ export function AgentsTab({
setSelectedId((primary ?? entries.find((fa) => fa.on) ?? entries[0]).family.id);
}, [entries, selectedId]);
const selected = entries.find((fa) => fa.family.id === selectedId) ?? null;
+ const providerName = useCallback<ProviderNamer>(
+ (provider) => {
+ const family = (families ?? []).find(
+ (f) => f.id === provider || f.agent_ids.includes(provider) || f.provider_ids.includes(provider),
+ );
+ return family ? { label: displayName(family), logoId: logoOf(family) } : null;
+ },
+ [families],
+ );
return (
<div className="flex flex-col gap-10" data-testid="apikeys-agents">
@@ -223,6 +233,7 @@ export function AgentsTab({
}
/>
</SettingsSection>
+ <MissionBilling providerName={providerName} />
</div>
);
}
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.test.tsx b/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.test.tsx
new file mode 100644
index 0000000000..5ae921bb06
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.test.tsx
@@ -0,0 +1,212 @@
+/**
+ * The paid-fallback switch bills the user once it is on, so the cases that
+ * matter are the ones where a wrong pixel means money: it starts off, it asks
+ * and explains before anything is saved, a cancel saves nothing, it never
+ * shows on unless the server holds it, and it cannot be turned on where it
+ * would do nothing or where no priced key exists.
+ */
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { loadLocaleChunk, useI18nStore } from "@/i18n";
+import { MISSION_BILLING_ANCHOR, clearApiKeysTabRequest, requestApiKeysTab } from "@/lib/apiKeysTab";
+import type { MissionBilling as Billing } from "@/types/missions";
+import { MissionBilling } from "./MissionBilling";
+
+const BASE: Billing = {
+ paid_api_fallback: false,
+ subscription_mode: true,
+ per_mission_cap_usd: 2,
+ daily_cap_usd: 10,
+ spent_last_24h_usd: 0,
+ paid_provider: { provider: "claude-api", model: "claude-sonnet-4-6", price_known: true },
+};
+
+const providerName = (provider: string) =>
+ provider === "claude-api" ? { label: "Anthropic", logoId: "claude-api" } : null;
+
+let server: Billing | null;
+let failPut: string | null;
+let puts: unknown[];
+
+beforeAll(async () => {
+ useI18nStore.getState().setUi("en", { push: false });
+ await loadLocaleChunk("providers");
+});
+
+beforeEach(() => {
+ server = { ...BASE };
+ failPut = null;
+ puts = [];
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url = String(input);
+ if (url !== "/api/mission-billing") return { ok: false, status: 404, json: async () => ({}) } as Response;
+ if (server === null) return { ok: false, status: 404, json: async () => ({ detail: "Not Found" }) } as Response;
+ if (init?.method === "PUT") {
+ const body = JSON.parse(String(init.body)) as { paid_api_fallback: boolean };
+ puts.push(body);
+ if (failPut) return { ok: false, status: 500, json: async () => ({ detail: failPut }) } as Response;
+ server = { ...server, paid_api_fallback: body.paid_api_fallback };
+ }
+ const snapshot = { ...server };
+ return { ok: true, status: 200, json: async () => snapshot } as Response;
+ }),
+ );
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+ clearApiKeysTabRequest();
+});
+
+function renderBilling() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
+ return render(
+ <QueryClientProvider client={client}>
+ <MissionBilling providerName={providerName} />
+ </QueryClientProvider>,
+ );
+}
+
+const theSwitch = () => screen.getByRole("switch", { name: "Continue on API keys when subscriptions run out", hidden: true });
+
+async function loaded() {
+ await screen.findByText("Off · missions wait until a subscription has room again");
+}
+
+describe("MissionBilling", () => {
+ it("loads the setting and starts off", async () => {
+ renderBilling();
+ await loaded();
+ expect(theSwitch().getAttribute("aria-checked")).toBe("false");
+ expect((theSwitch() as HTMLButtonElement).disabled).toBe(false);
+ expect(puts).toEqual([]);
+ });
+
+ it("explains the costs before anything is saved", async () => {
+ renderBilling();
+ await loaded();
+
+ fireEvent.click(theSwitch());
+ const dialog = await screen.findByRole("dialog");
+ expect(dialog.textContent).toContain("Continue on your API key?");
+ expect(dialog.textContent).toContain(
+ "When every connected subscription is used up, missions keep running on your own API key instead of waiting.",
+ );
+ expect(dialog.textContent).toContain("Anthropic bills that key for every request:");
+ expect(screen.getByTestId("mission-billing-provider").textContent).toContain("claude-sonnet-4-6");
+ expect(dialog.textContent).toContain("Each mission stops at $2, and all automatic use stops at $10 per day.");
+ expect(dialog.textContent).toContain("You can switch this off at any time.");
+ // Nothing is saved and the switch does not pretend to be on.
+ expect(puts).toEqual([]);
+ expect(theSwitch().getAttribute("aria-checked")).toBe("false");
+ // The safe choice holds the focus.
+ expect(document.activeElement?.textContent).toBe("Cancel");
+ });
+
+ it("saves only after the confirmation and then shows on", async () => {
+ renderBilling();
+ await loaded();
+
+ fireEvent.click(theSwitch());
+ fireEvent.click(await screen.findByRole("button", { name: "Turn on" }));
+ await waitFor(() => expect(theSwitch().getAttribute("aria-checked")).toBe("true"));
+ expect(puts).toEqual([{ paid_api_fallback: true }]);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(screen.getByText("On · Anthropic · at most $2 per mission, $10 a day")).toBeTruthy();
+ });
+
+ it("saves nothing when the dialog is cancelled", async () => {
+ renderBilling();
+ await loaded();
+
+ fireEvent.click(theSwitch());
+ fireEvent.click(await screen.findByRole("button", { name: "Cancel" }));
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(puts).toEqual([]);
+ expect(theSwitch().getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("stays off and shows the error when turning on fails", async () => {
+ failPut = "Config is locked";
+ renderBilling();
+ await loaded();
+
+ fireEvent.click(theSwitch());
+ fireEvent.click(await screen.findByRole("button", { name: "Turn on" }));
+ expect(await screen.findByText("Not saved: Config is locked")).toBeTruthy();
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ expect(theSwitch().getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("turns off at once, without a dialog", async () => {
+ server = { ...BASE, paid_api_fallback: true };
+ renderBilling();
+ await screen.findByText("On · Anthropic · at most $2 per mission, $10 a day");
+
+ fireEvent.click(theSwitch());
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(theSwitch().getAttribute("aria-checked")).toBe("false");
+ await waitFor(() => expect(puts).toEqual([{ paid_api_fallback: false }]));
+ await loaded();
+ });
+
+ it("springs back on and shows the error when turning off fails", async () => {
+ server = { ...BASE, paid_api_fallback: true };
+ failPut = "Disk full";
+ renderBilling();
+ await screen.findByText("On · Anthropic · at most $2 per mission, $10 a day");
+
+ fireEvent.click(theSwitch());
+ expect(await screen.findByRole("alert")).toBeTruthy();
+ expect(screen.getByRole("alert").textContent).toBe("Not saved: Disk full");
+ expect(theSwitch().getAttribute("aria-checked")).toBe("true");
+ });
+
+ it("shows what was spent in the last 24 hours", async () => {
+ server = { ...BASE, paid_api_fallback: true, spent_last_24h_usd: 3.456 };
+ renderBilling();
+ expect(
+ await screen.findByText("On · Anthropic · at most $2 per mission, $10 a day · $3.46 spent in the last 24 hours"),
+ ).toBeTruthy();
+ });
+
+ it("cannot be turned on where missions already run on keys", async () => {
+ server = { ...BASE, subscription_mode: false };
+ renderBilling();
+ await screen.findByText("Missions already run on your API keys");
+ expect((theSwitch() as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it("cannot be turned on without a key that has a known price", async () => {
+ server = { ...BASE, paid_provider: null };
+ renderBilling();
+ await screen.findByText("Needs an API key with a known price");
+ expect((theSwitch() as HTMLButtonElement).disabled).toBe(true);
+ });
+
+ it("can always be turned off, even without a priced key", async () => {
+ server = { ...BASE, paid_api_fallback: true, paid_provider: null };
+ renderBilling();
+ await screen.findByText("On · no API key with a known price yet");
+ expect((theSwitch() as HTMLButtonElement).disabled).toBe(false);
+ });
+
+ it("leaves the section out on a backend without the setting", async () => {
+ server = null;
+ const { container } = renderBilling();
+ await waitFor(() => expect(vi.mocked(fetch)).toHaveBeenCalled());
+ await waitFor(() => expect(container.textContent).toBe(""));
+ });
+
+ it("brings the setting into view when a link asked for it", async () => {
+ requestApiKeysTab("agents", MISSION_BILLING_ANCHOR);
+ renderBilling();
+ await loaded();
+ await waitFor(() => expect(document.activeElement).toBe(theSwitch()));
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.tsx b/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.tsx
new file mode 100644
index 0000000000..6b6a98db3e
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/views/apikeys/MissionBilling.tsx
@@ -0,0 +1,259 @@
+import { useCallback, useEffect, useId, useRef, useState } from "react";
+import * as Dialog from "@radix-ui/react-dialog";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { CreditCard, Loader2 } from "lucide-react";
+import { MISSION_BILLING_KEY, fetchMissionBilling, saveMissionBilling } from "@/components/missions/api";
+import { ProviderLogo } from "@/components/providers/ProviderLogo";
+import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import { fill, useT } from "@/i18n";
+import { APIKEYS_TAB_EVENT, MISSION_BILLING_ANCHOR, takeApiKeysAnchor } from "@/lib/apiKeysTab";
+import { SettingsRow, SettingsSection } from "./settingsUi";
+
+/** How a provider slug reads on this page: its company name and mark. */
+export type ProviderNamer = (provider: string) => { label: string; logoId: string } | null;
+
+/** "$2" for a whole amount, "$0.42" otherwise. */
+function usd(value: number): string {
+ return Number.isInteger(value) ? `$${value}` : `$${value.toFixed(2)}`;
+}
+
+/**
+ * Whether missions continue on the user's own API key once every connected
+ * subscription is used up. Off by default: a mission then waits for a
+ * subscription, or for a one-off approval in Artifacts.
+ *
+ * Turning it on bills the user, so it asks first and explains the costs in
+ * the dialog; nothing is saved before the confirmation, and the switch shows
+ * on only once the server holds it. Turning it off saves at once — the safe
+ * direction — and springs back with the error if the save fails.
+ */
+export function MissionBilling({ providerName }: { providerName: ProviderNamer }) {
+ const t = useT();
+ const client = useQueryClient();
+ const statusId = useId();
+ const switchRef = useRef<HTMLButtonElement>(null);
+ const query = useQuery({ queryKey: MISSION_BILLING_KEY, queryFn: fetchMissionBilling, staleTime: 30_000 });
+ const billing = query.data ?? null;
+ const [pending, setPending] = useState<"on" | "off" | null>(null);
+ const [confirming, setConfirming] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [dialogError, setDialogError] = useState<string | null>(null);
+
+ // A "set this up" link from a waiting mission lands here.
+ const loaded = billing !== null;
+ const reveal = useCallback(() => {
+ if (!takeApiKeysAnchor(MISSION_BILLING_ANCHOR)) return;
+ document.getElementById(MISSION_BILLING_ANCHOR)?.scrollIntoView?.({ block: "center", behavior: "smooth" });
+ switchRef.current?.focus({ preventScroll: true });
+ }, []);
+ useEffect(() => {
+ if (!loaded) return;
+ reveal();
+ window.addEventListener(APIKEYS_TAB_EVENT, reveal);
+ return () => window.removeEventListener(APIKEYS_TAB_EVENT, reveal);
+ }, [loaded, reveal]);
+
+ // An older backend has no such setting: leave the section out.
+ if (query.isSuccess && billing === null) return null;
+
+ const saveError = (cause: unknown) =>
+ fill(t("mission_billing.save_error"), { detail: (cause as Error).message || String(cause) });
+
+ async function turnOff() {
+ setError(null);
+ setPending("off");
+ try {
+ client.setQueryData(MISSION_BILLING_KEY, await saveMissionBilling(false));
+ } catch (cause) {
+ setError(saveError(cause));
+ } finally {
+ setPending(null);
+ }
+ }
+
+ async function confirmOn() {
+ setDialogError(null);
+ setPending("on");
+ try {
+ client.setQueryData(MISSION_BILLING_KEY, await saveMissionBilling(true));
+ setConfirming(false);
+ } catch (cause) {
+ setDialogError(saveError(cause));
+ } finally {
+ setPending(null);
+ }
+ }
+
+ const priced = billing?.paid_provider?.price_known ? billing.paid_provider : null;
+ const named = priced ? providerName(priced.provider) : null;
+ const providerLabel = named?.label ?? priced?.provider ?? "";
+ const on = billing !== null && billing.paid_api_fallback && pending !== "off";
+ // Off can always be chosen; on only where it would do something.
+ const canTurnOn = billing !== null && billing.subscription_mode && priced !== null;
+ const caps = billing
+ ? { mission_cap: usd(billing.per_mission_cap_usd), daily_cap: usd(billing.daily_cap_usd) }
+ : { mission_cap: "", daily_cap: "" };
+
+ let status: string;
+ if (query.isError) {
+ status = fill(t("mission_billing.load_error"), { detail: (query.error as Error).message });
+ } else if (!billing) {
+ status = t("providers_page.checking");
+ } else {
+ const parts = [
+ !billing.subscription_mode
+ ? t("mission_billing.state_key_only")
+ : on
+ ? priced
+ ? fill(t("mission_billing.state_on"), { provider: providerLabel, ...caps })
+ : t("mission_billing.state_on_no_key")
+ : priced
+ ? t("mission_billing.state_off")
+ : t("mission_billing.state_no_key"),
+ ];
+ const spent = billing.spent_last_24h_usd;
+ if (spent > 0) {
+ parts.push(
+ fill(t("mission_billing.spent"), {
+ amount: spent < 0.01 ? t("mission_billing.less_than_cent") : usd(Number(spent.toFixed(2))),
+ }),
+ );
+ }
+ status = parts.join(" · ");
+ }
+
+ const title = t("mission_billing.title");
+
+ return (
+ <SettingsSection
+ id={MISSION_BILLING_ANCHOR}
+ title={t("mission_billing.section")}
+ data-testid="mission-billing"
+ className="scroll-mt-6"
+ >
+ <SettingsRow
+ title={title}
+ status={
+ <span className="block space-y-0.5">
+ <span id={statusId} className={query.isError ? "block text-destructive" : "block"}>
+ {status}
+ </span>
+ {error ? (
+ <span role="alert" className="block text-destructive">
+ {error}
+ </span>
+ ) : null}
+ </span>
+ }
+ control={
+ <>
+ {pending === "off" && <Loader2 aria-hidden="true" className="h-4 w-4 animate-spin text-muted-foreground" />}
+ <Switch
+ ref={switchRef}
+ data-testid="mission-billing-switch"
+ checked={on}
+ disabled={billing === null || pending !== null || (!on && !canTurnOn)}
+ onCheckedChange={(next) => {
+ if (next) {
+ setError(null);
+ setDialogError(null);
+ setConfirming(true);
+ } else {
+ void turnOff();
+ }
+ }}
+ aria-label={title}
+ aria-describedby={statusId}
+ />
+ </>
+ }
+ />
+
+ <Dialog.Root
+ open={confirming}
+ onOpenChange={(open) => {
+ if (!open && pending === null) setConfirming(false);
+ }}
+ >
+ <Dialog.Portal>
+ <Dialog.Overlay className="fixed inset-0 z-[80] bg-scrim/60 backdrop-blur-sm data-[state=open]:animate-in data-[state=open]:fade-in-0" />
+ <Dialog.Content
+ data-testid="mission-billing-confirm"
+ onOpenAutoFocus={(event) => {
+ // The safe choice takes the focus: Enter never bills by accident.
+ event.preventDefault();
+ (event.currentTarget as HTMLElement).querySelector<HTMLElement>("[data-billing-cancel]")?.focus();
+ }}
+ className="fixed left-1/2 top-1/2 z-[90] max-h-[calc(100dvh-2rem)] w-[min(440px,calc(100vw-2rem))] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-border bg-popover p-6 text-popover-foreground shadow-2xl data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95"
+ >
+ <div className="flex items-start gap-4">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-warning/10 text-warning">
+ <CreditCard className="h-[18px] w-[18px]" aria-hidden />
+ </div>
+ <div className="min-w-0 flex-1">
+ <Dialog.Title className="text-base font-semibold">{t("mission_billing.confirm_title")}</Dialog.Title>
+ <Dialog.Description className="mt-1.5 text-sm leading-relaxed text-muted-foreground">
+ {t("mission_billing.confirm_intro")}
+ </Dialog.Description>
+ </div>
+ </div>
+
+ <div className="mt-4 space-y-3 text-sm leading-relaxed text-muted-foreground">
+ {priced ? (
+ <div className="space-y-2">
+ <p>{fill(t("mission_billing.confirm_billing"), { provider: providerLabel })}</p>
+ <div
+ data-testid="mission-billing-provider"
+ className="flex min-w-0 items-center gap-2.5 rounded-xl border border-border bg-muted/40 px-3 py-2.5"
+ >
+ <ProviderLogo
+ providerId={named?.logoId ?? priced.provider}
+ label={providerLabel}
+ size="sm"
+ className="h-5 w-5 shrink-0"
+ />
+ <span className="truncate font-medium text-foreground">{providerLabel}</span>
+ <code className="ml-auto min-w-0 truncate font-mono text-xs text-muted-foreground">{priced.model}</code>
+ </div>
+ </div>
+ ) : (
+ <p className="text-warning">{t("mission_billing.confirm_no_key")}</p>
+ )}
+ <p>{fill(t("mission_billing.confirm_caps"), caps)}</p>
+ <p>{t("mission_billing.confirm_off")}</p>
+ {dialogError ? (
+ <p role="alert" className="text-destructive">
+ {dialogError}
+ </p>
+ ) : null}
+ </div>
+
+ <div className="mt-6 flex flex-wrap justify-end gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ data-billing-cancel
+ disabled={pending !== null}
+ onClick={() => setConfirming(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ type="button"
+ size="sm"
+ data-testid="mission-billing-confirm-on"
+ disabled={pending !== null || !canTurnOn}
+ onClick={() => void confirmOn()}
+ >
+ {pending === "on" && <Loader2 className="animate-spin" aria-hidden />}
+ {t("mission_billing.confirm_action")}
+ </Button>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+ </Dialog.Root>
+ </SettingsSection>
+ );
+}