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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(credentials): one key per provider family — the first key saved anywhere serves every surface
rubenluetke10-beepc0ddf645baa1
diff --git a/docs/product/personalize-and-connect/providers-and-api-keys.md b/docs/product/personalize-and-connect/providers-and-api-keys.mdindex f2bc14e8f1..58a7f7677c 100644--- a/docs/product/personalize-and-connect/providers-and-api-keys.md+++ b/docs/product/personalize-and-connect/providers-and-api-keys.md@@ -146,6 +146,26 @@ a dedicated key is optional. Dedicated Realtime or worker slots take prioritywhen present, while compatible shared keys keep single-key installationsworking.+### One key per provider++You enter a provider's key once, on whichever card you happen to be on. The+first key saved for a provider family becomes that family's key and serves+every area that uses the provider — Brain, Tool Model, Jarvis-Agents, voice+output, voice input and Realtime. Saving the same key again on another card+changes nothing.++Only a genuinely different second key raises a question:++- On a Realtime, Jarvis-Agents or Codex card while the provider already has a+ key: **Only here** keeps the new key for that area; **Everywhere** replaces+ the provider's key in every area and drops old copies of the replaced key.+- On the main provider card while some areas hold their own different key:+ **Keep their own keys** leaves those areas alone; **Everywhere** makes every+ area follow the new key.++Nothing is written until you answer. Areas that keep their own key show it as+**Key saved**; areas served by the shared key show the covered note.+Brain and Computer Use changes apply to the next request. Voice input appliesto the next transcription. Voice output switches the running Pipeline when itcan, otherwise the saved choice is used when speech starts again. Activating adiff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex f804a69713..dca5bfd660 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3363,6 +3363,33 @@ class DictationConfig(BaseModel):translate_drift_max_shrink: float = Field(default=0.40, ge=0.0, le=1.0)translate_drift_max_growth: float = Field(default=2.50, ge=1.0, le=10.0)+ # ------------------------------------------------------------------+ # Prompt Mode — a dictation comes out as the prompt for a coding agent+ # ------------------------------------------------------------------++ #: Rewrite every dictation into a finished, English prompt for an AI+ #: coding agent: the goal, the stated context and constraints, nothing+ #: invented — the Agentic IDE's own prompt doctrine+ #: (``jarvis/agentic_ide/prompt_blueprint.py``) applied to a transcript.+ #: The writer is the one the Agentic IDE uses (``agentic_ide.prompt_writer``:+ #: the pinned Tool Model, then the API tier, then a connected coding CLI);+ #: no second picker, because "which model turns my words into a prompt"+ #: is one question with one answer.+ #:+ #: Outranks the polish and translate passes while on — a prompt is always+ #: English and always restructured, so neither has anything left to do.+ #: When no writer answers in time the dictation falls through to those+ #: passes exactly as if this switch were off; the raw words are never lost.+ #:+ #: Ships OFF. It changes WHAT the text says, on purpose, and it sends the+ #: words to a cloud writer on most installs. Chosen, never inherited.+ prompt_mode: bool = False++ #: Wall-clock ceiling for one Prompt Mode call. Seconds, not the polish+ #: pass's 1.2 s: this is a thinking-grade writer producing a brief, and+ #: the user chose to wait for it. Clamped, never rejected (AP-16).+ prompt_mode_timeout_ms: int = Field(default=20_000, ge=2_000, le=120_000)+@field_validator("paste_chord", mode="before")@classmethoddef _coerce_paste_chord(cls, value: object) -> str:@@ -3499,6 +3526,11 @@ class DictationConfig(BaseModel):def _clamp_translate_drift_max_growth(cls, value: object) -> float:return _clamped_polish_float(value, default=2.50, low=1.0, high=10.0)+ @field_validator("prompt_mode_timeout_ms", mode="before")+ @classmethod+ def _clamp_prompt_mode_timeout_ms(cls, value: object) -> int:+ return _clamped_polish_int(value, default=20_000, low=2_000, high=120_000)+class MarketplaceConfig(BaseModel):"""Plugin-marketplace connect settings (OAuth redirect mode).@@ -4976,6 +5008,203 @@ def jarvis_agent_secret_slot(provider: str) -> tuple[str, str] | None:return candidates[0] if candidates else None+# ----------------------------------------------------------------------+# One key per provider family (2026-08-24)+# ----------------------------------------------------------------------+#+# Every surface of a provider family (Brain, Tool Model, Jarvis-Agents, TTS,+# STT, Realtime) reads the family's PRIMARY slot through the chains above, and+# the scoped slots (``realtime_*``, ``jarvis_agent_*``, ``codex_*``) only exist+# so a user who WANTS a second key for one surface can have one. The save+# planner below turns that into the rule the user sees: the first key saved+# anywhere becomes the family key, and only a genuinely different second key+# asks "just here, or everywhere?".++# The families that own a primary slot. Realtime/Agent/Codex variants are+# scoped views of one of these, never families of their own.+_SECRET_BASE_FAMILIES: tuple[str, ...] = (+ "claude-api",+ "openai",+ "openrouter",+ "groq",+ "nvidia",+ "gemini",+ "vertex",+ "grok",+)+++@dataclass(frozen=True, slots=True)+class SecretSlotScope:+ """Where one keyring slot sits inside its provider family."""++ family: str+ primary_slot: str+ # True for a surface-scoped slot (realtime / agent / codex); False for the+ # family's primary slot itself.+ dedicated: bool+++def secret_family_primary_slot(family: str) -> str | None:+ """The slot every surface of ``family`` reads first (``gemini_api_key``…)."""+ if family not in _SECRET_BASE_FAMILIES:+ return None+ candidates = PROVIDER_SECRET_CANDIDATES.get(family, ())+ return candidates[0][0] if candidates else None+++def secret_slot_scope(slot: str) -> SecretSlotScope | None:+ """Classify ``slot`` as a family primary, a scoped slot, or neither.++ A scoped slot is the FIRST entry of a resolution chain whose tail contains a+ base family's primary slot (``realtime_gemini_api_key`` → ``gemini``). Legacy+ aliases such as ``google_api_key`` sit in the middle of a chain and belong+ to no scope: they are saved verbatim. Derived from the chains, so a new+ scoped slot is classified the moment its chain is declared (BUG-008 class).+ """+ for family in _SECRET_BASE_FAMILIES:+ primary = secret_family_primary_slot(family)+ if primary == slot:+ return SecretSlotScope(family=family, primary_slot=primary, dedicated=False)+ for chains in (PROVIDER_SECRET_CANDIDATES, JARVIS_AGENT_SECRET_CANDIDATES):+ for candidates in chains.values():+ if not candidates or candidates[0][0] != slot:+ continue+ # A base family's own chain starts with its primary (caught above),+ # so any chain reaching a primary from a different first slot is a+ # scoped view — including the Agent chains, which reuse the family+ # name as their key.+ tail = {candidate_slot for candidate_slot, _env in candidates[1:]}+ for family in _SECRET_BASE_FAMILIES:+ primary = secret_family_primary_slot(family)+ if primary in tail:+ return SecretSlotScope(family=family, primary_slot=primary, dedicated=True)+ return None+++def secret_family_scoped_slots(family: str) -> tuple[str, ...]:+ """Every surface-scoped slot that falls back to ``family``'s primary slot."""+ found: dict[str, None] = {}+ for chains in (PROVIDER_SECRET_CANDIDATES, JARVIS_AGENT_SECRET_CANDIDATES):+ for candidates in chains.values():+ if not candidates:+ continue+ scope = secret_slot_scope(candidates[0][0])+ if scope is not None and scope.dedicated and scope.family == family:+ found.setdefault(candidates[0][0])+ return tuple(found)+++@dataclass(frozen=True, slots=True)+class SecretSavePlan:+ """What a save of one slot should actually write — or the question to ask.++ ``choice_required`` means nothing was decided yet: the caller must ask the+ user whether the new key is for this surface only (``scope="here"``) or+ for every surface of the family (``scope="everywhere"``) and plan again.+ """++ writes: tuple[str, ...]+ deletes: tuple[str, ...] = ()+ choice_required: bool = False+ family: str | None = None+ primary_slot: str | None = None+ # Which question to ask. "dedicated_vs_family": a scoped slot is being+ # saved while the family already has a different key. "family_vs_dedicated":+ # the family key is being replaced while some surfaces hold their own+ # different key.+ choice_kind: str | None = None+ # The scoped slots holding a different key from the one being saved.+ conflicting_slots: tuple[str, ...] = ()+++def plan_secret_save(slot: str, value: str, scope: str | None = None) -> SecretSavePlan:+ """Decide where a key entered on one surface should be stored.++ Rules, in the user's words ("one key per provider, unless I say otherwise"):++ * A slot outside any family (Twilio, ElevenLabs aliases…) is written as-is.+ * Saving on a SCOPED surface (Realtime card, Agent row, Codex) while the+ family has no key yet stores the key as the FAMILY key, so every surface+ of that provider works at once. Same when the family already holds this+ exact key: the scoped copy is redundant and is dropped.+ * Saving a DIFFERENT key on a scoped surface asks: only here, or replace+ the family key everywhere? ``"here"`` writes the scoped slot; ``"everywhere"``+ writes the family slot and drops every scoped copy of the OLD family key+ (so no surface silently keeps running on the key just replaced).+ * Replacing the FAMILY key while some surfaces hold their own different key+ asks whether those keep their key (``"here"``) or follow (``"everywhere"``,+ which drops them). Scoped copies equal to the old family key were never+ a deliberate second key and always follow.++ Pure planning: nothing is written here. ``scope`` is ``None`` (ask if+ needed), ``"here"`` or ``"everywhere"``.+ """+ if scope not in (None, "here", "everywhere"):+ raise ValueError(f"unknown secret save scope: {scope!r}")+ info = secret_slot_scope(slot)+ if info is None:+ return SecretSavePlan(writes=(slot,))+ family, primary = info.family, info.primary_slot++ if info.dedicated:+ family_value = get_secret(primary)+ own_value = get_secret(slot)+ drop_own = (slot,) if own_value else ()+ if not family_value or family_value == value:+ return SecretSavePlan(+ writes=(primary,), deletes=drop_own, family=family, primary_slot=primary+ )+ if scope is None:+ return SecretSavePlan(+ writes=(),+ choice_required=True,+ family=family,+ primary_slot=primary,+ choice_kind="dedicated_vs_family",+ conflicting_slots=(primary,),+ )+ if scope == "here":+ return SecretSavePlan(writes=(slot,), family=family, primary_slot=primary)+ # everywhere: the family key changes; scoped mirrors of the old key+ # follow, a scoped slot holding a third key is a deliberate choice.+ mirrors = tuple(+ s for s in secret_family_scoped_slots(family) if get_secret(s) == family_value+ )+ deletes = tuple(dict.fromkeys((*drop_own, *mirrors)))+ return SecretSavePlan(+ writes=(primary,), deletes=deletes, family=family, primary_slot=primary+ )++ # The family primary itself.+ old_value = get_secret(primary)+ mirrors: list[str] = []+ distinct: list[str] = []+ for scoped in secret_family_scoped_slots(family):+ held = get_secret(scoped)+ if not held or held == value:+ if held:+ mirrors.append(scoped)+ continue+ if old_value and held == old_value:+ mirrors.append(scoped)+ else:+ distinct.append(scoped)+ if distinct and scope is None:+ return SecretSavePlan(+ writes=(),+ choice_required=True,+ family=family,+ primary_slot=primary,+ choice_kind="family_vs_dedicated",+ conflicting_slots=tuple(distinct),+ )+ deletes = tuple(mirrors) if scope != "everywhere" else tuple((*mirrors, *distinct))+ return SecretSavePlan(+ writes=(primary,), deletes=deletes, family=family, primary_slot=primary+ )++@contextmanagerdef override_provider_secrets(overrides: Mapping[str, str | None],diff --git a/jarvis/plugins/stt/__init__.py b/jarvis/plugins/stt/__init__.pyindex ee9a683c1f..1bd7c5d8c4 100644--- a/jarvis/plugins/stt/__init__.py+++ b/jarvis/plugins/stt/__init__.py@@ -38,7 +38,12 @@ _STT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {# collision in the shared model-catalog / provider-spec namespaces."openrouter-stt": (("openrouter_api_key", "OPENROUTER_API_KEY"),),# OpenAI Whisper STT reuses the SAME openai_api_key slot as the OpenAI brain.- "openai-api": (("openai_api_key", "OPENAI_API_KEY"),),+ # The trailing realtime slot is the same last-resort cross-read the brain+ # chain has: a realtime-only OpenAI install must not lose cloud STT.+ "openai-api": (+ ("openai_api_key", "OPENAI_API_KEY"),+ ("realtime_openai_api_key", "JARVIS_REALTIME_OPENAI_API_KEY"),+ ),# Gemini STT reuses the SAME AI-Studio key slots as the Gemini brain/TTS, so# the Gemini-only downloader (the recommended-default persona) gets cloud# voice input with no second credential.@@ -46,6 +51,7 @@ _STT_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {("gemini_api_key", "GEMINI_API_KEY"),("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),("google_api_key", "GOOGLE_API_KEY"),+ ("realtime_gemini_api_key", "JARVIS_REALTIME_GEMINI_API_KEY"),),# Vertex STT reuses the shared Vertex credential — the same slots the Vertex# brain, TTS and realtime tiers read, so one Cloud setup serves the wholediff --git a/jarvis/plugins/tts/__init__.py b/jarvis/plugins/tts/__init__.pyindex 22451fe2ae..be21798a94 100644--- a/jarvis/plugins/tts/__init__.py+++ b/jarvis/plugins/tts/__init__.py@@ -60,9 +60,13 @@ _INWORLD_ALIASES = frozenset({# single-provider resilience, AP-22). Families absent here are left untouched._TTS_SECRET_CANDIDATES: dict[str, tuple[tuple[str, str], ...]] = {"inworld": (("inworld_api_key", "INWORLD_API_KEY"),),+ # Same order as the brain's gemini chain; the trailing realtime slot is the+ # last-resort cross-read so a realtime-only Gemini install keeps its voice."gemini-flash-tts": (("gemini_api_key", "GEMINI_API_KEY"),+ ("google_aistudio_api_key", "GOOGLE_AIStudio_API_KEY"),("google_api_key", "GOOGLE_API_KEY"),+ ("realtime_gemini_api_key", "JARVIS_REALTIME_GEMINI_API_KEY"),),"elevenlabs": (("elevenlabs_api_key", "ELEVENLABS_API_KEY"),diff --git a/jarvis/plugins/tts/gemini_flash_tts.py b/jarvis/plugins/tts/gemini_flash_tts.pyindex e768ab1473..c3c249b223 100644--- a/jarvis/plugins/tts/gemini_flash_tts.py+++ b/jarvis/plugins/tts/gemini_flash_tts.py@@ -205,10 +205,12 @@ class GeminiFlashTTS:"""if self._api_key:return self._api_key- for env_var in ("GEMINI_API_KEY", "GOOGLE_AIStudio_API_KEY", "GOOGLE_API_KEY"):- val = cfg.get_secret(env_var.lower(), env_fallback=env_var)- if val:- return val+ # The family chain (config.PROVIDER_SECRET_CANDIDATES["gemini"]) is the+ # one list of Gemini slots; a private copy here drifted from it and+ # left a realtime-only install without TTS.+ val = cfg.get_provider_secret("gemini")+ if val:+ return valraise RuntimeError("Gemini API key not found. Set GEMINI_API_KEY or ""GOOGLE_AIStudio_API_KEY in .env / Credential Manager."diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsxindex 958f6eca99..54713cdf71 100644--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.test.tsx@@ -9,16 +9,63 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { ApiKeyForm } from "@/components/ApiKeyForm";-import { deleteSecret } from "@/hooks/useProviders";+import { deleteSecret, postSecret } from "@/hooks/useProviders";vi.mock("@/hooks/useProviders", () => ({deleteSecret: vi.fn(async () => undefined),- postSecret: vi.fn(async () => undefined),+ postSecret: vi.fn(async (key: string) => ({ ok: true, key, written: [key] })),}));afterEach(cleanup);beforeEach(() => {vi.mocked(deleteSecret).mockClear();+ vi.mocked(postSecret).mockClear();+});++describe("ApiKeyForm one-key-per-family scope question", () => {+ it("asks 'only here or everywhere' when the family already holds a different key", async () => {+ vi.mocked(postSecret).mockResolvedValueOnce({+ ok: false,+ key: "realtime_gemini_api_key",+ choice_required: true,+ choice_kind: "dedicated_vs_family",+ family_label: "Google Gemini",+ conflicting_labels: ["Google Gemini"],+ });+ render(+ <ApiKeyForm secretKey="realtime_gemini_api_key" dashboardUrl={null} configured={false} />,+ );+ fireEvent.change(screen.getByLabelText(/enter realtime_gemini_api_key/i), {+ target: { value: "AIza-second" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));++ await waitFor(() => expect(screen.getByTestId("secret-scope-choice")).toBeTruthy());+ expect(screen.getByText(/Google Gemini already has a different key/i)).toBeTruthy();++ fireEvent.click(screen.getByRole("button", { name: /everywhere for Google Gemini/i }));+ await waitFor(() =>+ expect(postSecret).toHaveBeenLastCalledWith(+ "realtime_gemini_api_key",+ "AIza-second",+ "everywhere",+ ),+ );+ // The question disappears once the scoped save went through.+ await waitFor(() => expect(screen.queryByTestId("secret-scope-choice")).toBeNull());+ });++ it("saves straight through when no choice is needed", async () => {+ render(<ApiKeyForm secretKey="gemini_api_key" dashboardUrl={null} configured={false} />);+ fireEvent.change(screen.getByLabelText(/enter gemini_api_key/i), {+ target: { value: "AIza-first" },+ });+ fireEvent.click(screen.getByRole("button", { name: /^save$/i }));+ await waitFor(() =>+ expect(postSecret).toHaveBeenCalledWith("gemini_api_key", "AIza-first", undefined),+ );+ expect(screen.queryByTestId("secret-scope-choice")).toBeNull();+ });});describe("ApiKeyForm credential help", () => {diff --git a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsxindex a702ada438..340f73d021 100644--- a/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx+++ b/jarvis/ui/web/frontend/src/components/ApiKeyForm.tsx@@ -1,7 +1,12 @@import { useState } from "react";import { AlertTriangle, CheckCircle2, Eye, EyeOff, ExternalLink, Trash2 } from "lucide-react";import { Button } from "@/components/ui/button";-import { deleteSecret, postSecret } from "@/hooks/useProviders";+import {+ deleteSecret,+ postSecret,+ type SecretSaveResult,+ type SecretSaveScope,+} from "@/hooks/useProviders";import { keyFormatConfirmed, keyMatchesSecret } from "@/lib/keyFormat";import { useEventStore } from "@/store/events";import { cn } from "@/lib/utils";@@ -80,6 +85,9 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelpconst coveredByShared = !configured && Boolean(effectiveConfigured);const [editing, setEditing] = useState(!configured && !effectiveConfigured);const [confirmingDelete, setConfirmingDelete] = useState(false);+ // One key per provider family: when the family already holds a DIFFERENT+ // key, the backend writes nothing and hands back the question instead.+ const [scopeChoice, setScopeChoice] = useState<SecretSaveResult | null>(null);const pushToast = useEventStore((s) => s.pushToast);// Live, client-side format recognition — the entered value never leaves the@@ -87,18 +95,27 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp// hints; never blocks the save.const fmt = value.trim() ? keyMatchesSecret(secretKey, value) : null;- async function handleSave() {+ async function handleSave(scope?: SecretSaveScope) {const trimmed = value.trim();if (!trimmed) return;setPending(true);try {- await postSecret(secretKey, trimmed);+ const result = await postSecret(secretKey, trimmed, scope);+ if (result?.choice_required) {+ setScopeChoice(result);+ return;+ }+ setScopeChoice(null);pushToast("success", t("apikeys_view.key_saved_toast").replace("{0}", secretKey));setValue("");setEditing(false);onChanged?.();onSavedActivate?.();- announceSecretChange(secretKey, "set");+ // The family slot may have been written instead of (or alongside) the+ // card's own slot; every surface reading either must refresh.+ for (const slot of new Set([secretKey, ...(result?.written ?? [])])) {+ announceSecretChange(slot, "set");+ }} catch (e) {pushToast("error", `${t("common.save_failed")}: ${(e as Error).message}`);} finally {@@ -157,6 +174,49 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp</a>) : null;+ // "Just here, or everywhere?" — asked only when a second, different key+ // meets an existing family key. Two plain choices, no default clicked for+ // the user: which one is right lives in their head.+ const familyLabel = scopeChoice?.family_label ?? "";+ const scopeQuestion = scopeChoice ? (+ <div+ data-testid="secret-scope-choice"+ className="space-y-2 rounded-control border border-border bg-background/60 px-3 py-2"+ >+ <p className="text-xs leading-relaxed text-foreground">+ {scopeChoice.choice_kind === "family_vs_dedicated"+ ? t("apikeys_view.scope_family_question")+ .replace("{0}", familyLabel)+ .replace("{1}", (scopeChoice.conflicting_labels ?? []).join(", "))+ : t("apikeys_view.scope_dedicated_question").replace("{0}", familyLabel)}+ </p>+ <div className="flex flex-wrap gap-2">+ <Button+ size="sm"+ onClick={() => void handleSave("everywhere")}+ disabled={pending}+ className="h-8 rounded-control"+ >+ {t("apikeys_view.scope_everywhere").replace("{0}", familyLabel)}+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() => void handleSave("here")}+ disabled={pending}+ className="h-8 rounded-control"+ >+ {scopeChoice.choice_kind === "family_vs_dedicated"+ ? t("apikeys_view.scope_keep_dedicated")+ : t("apikeys_view.scope_here")}+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setScopeChoice(null)} className="h-8">+ {t("common.cancel")}+ </Button>+ </div>+ </div>+ ) : null;+const sharedDeleteConfirm = confirmingDelete ? (<div className="space-y-2 rounded-control border border-destructive/40 bg-destructive/[0.06] px-3 py-2"><p className="flex items-start gap-1.5 text-xs text-destructive">@@ -266,7 +326,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp"focus:outline-none focus:ring-1 focus:ring-primary",)}onKeyDown={(e) => {- if (e.key === "Enter") void handleSave();+ if (e.key === "Enter" && !scopeChoice) void handleSave();}}/><button@@ -281,8 +341,8 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp</div><Buttonsize="sm"- onClick={handleSave}- disabled={pending || !value.trim()}+ onClick={() => void handleSave()}+ disabled={pending || !value.trim() || Boolean(scopeChoice)}className="h-9 rounded-control">{pending ? "…" : t("common.save")}@@ -298,6 +358,7 @@ export function ApiKeyForm({ secretKey, dashboardUrl, configured, credentialHelp</Button>)}</div>+ {scopeQuestion}{fmt && !fmt.match && fmt.detected && (<div className="space-y-1"><p className="flex items-start gap-1 text-xs text-amber-500">diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex 2fa1a6a06c..62be176bbd 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -1094,6 +1094,7 @@ function CodexConnectionCard({secretKey={row.secret_key}dashboardUrl={row.dashboard_url}configured={row.dedicated_key_set}+ effectiveConfigured={row.shared_key_set}credentialHelp={row.credential_help}onChanged={onChanged}/>@@ -1515,6 +1516,7 @@ function ClaudeApiCard({secretKey={row.secret_key}dashboardUrl={row.dashboard_url}configured={row.dedicated_key_set}+ effectiveConfigured={row.shared_key_set}credentialHelp={row.credential_help}onChanged={onChanged}/>@@ -1657,11 +1659,15 @@ function SubagentProviderCard({body={row.secret_key || row.credential_help || !row.key_set ? (<>+ {/* The shared family key already serves this row (the runtime+ falls back to it), so an empty box here asked for a second+ key nobody needs — same "covered" state as the tier cards. */}{row.secret_key && (<ApiKeyFormsecretKey={row.secret_key}dashboardUrl={row.dashboard_url}configured={row.dedicated_key_set}+ effectiveConfigured={row.shared_key_set}credentialHelp={row.credential_help}onChanged={onSwitched}/>diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex c371a3cc11..5dad0aa3f7 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -601,16 +601,43 @@ export function sectionHealthFromProviderTest(};}-export async function postSecret(key: string, value: string): Promise<void> {+/** "here" = this surface only; "everywhere" = the whole provider family. */+export type SecretSaveScope = "here" | "everywhere";++export interface SecretSaveResult {+ ok: boolean;+ key: string;+ /** Nothing was written — the backend needs a scope decision first. */+ choice_required?: boolean;+ choice_kind?: "dedicated_vs_family" | "family_vs_dedicated" | null;+ family_label?: string | null;+ /** Surfaces holding a DIFFERENT key from the one being saved. */+ conflicting_labels?: string[];+ /** Slots actually written — the family slot when a first key was saved on a scoped card. */+ written?: string[];+ restart_required?: boolean;+}++/**+ * One key per provider family: a key saved on any card becomes the family key+ * unless the family already holds a different one — then the backend answers+ * `choice_required` and the caller re-posts with an explicit `scope`.+ */+export async function postSecret(+ key: string,+ value: string,+ scope?: SecretSaveScope,+): Promise<SecretSaveResult> {const res = await fetch(`/api/secrets/${encodeURIComponent(key)}`, {method: "POST",headers: { "Content-Type": "application/json" },- body: JSON.stringify({ value }),+ body: JSON.stringify(scope ? { value, scope } : { value }),});if (!res.ok) {const body = await res.json().catch(() => ({}));throw new Error(body.detail ?? `HTTP ${res.status}`);}+ return (await res.json()) as SecretSaveResult;}export async function deleteSecret(key: string): Promise<void> {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 1ed669d7f3..87ce818cb2 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -596,6 +596,8 @@"build_hint": "Bau-Modus — der Agent darf Dateien ändern. Klick für Plan-Modus.","plan_hint": "Plan-Modus — der Agent liest und plant, ändert nichts. Klick für Bau-Modus.","folder": "Arbeitsordner",+ "jarvis_tools": "Jarvis · {count} Tools",+ "jarvis_tools_hint": "Dieser Chat steuert Jarvis: {count} Jarvis-Tools stehen ihm zur Verfügung — dieselben, die auch per Sprache laufen.","send": "Senden","stop": "Durchgang stoppen","hint_connect": "{provider} ist noch nicht verbunden.",@@ -1573,6 +1575,11 @@"shared_delete_prefix": "Dieser Schlüssel wird auch verwendet von:","shared_delete_suffix": "Beim Löschen werden auch diese Provider deaktiviert.","delete_anyway": "Trotzdem löschen",+ "scope_dedicated_question": "Für {0} ist bereits ein anderer Schlüssel gespeichert. Den neuen Schlüssel nur hier verwenden oder überall ersetzen, wo {0} genutzt wird?",+ "scope_family_question": "Einige Bereiche von {0} haben einen eigenen Schlüssel ({1}). Diese auch ersetzen oder behalten?",+ "scope_everywhere": "Überall bei {0}",+ "scope_here": "Nur hier",+ "scope_keep_dedicated": "Eigene Schlüssel behalten","key_saved_label": "Schlüssel gespeichert","key_saved_toast": "Schlüssel gespeichert ({0})","key_removed_toast": "Schlüssel entfernt ({0})",@@ -4284,7 +4291,7 @@"setup_label": "Arbeitsbereich einrichten","reading_mode": "Darstellung","reading_mode_label": "Darstellung des Arbeitsbereichs",- "view_hint": "Nur die Darstellung ändert sich — Agents, Fenster und Unterhaltungen bleiben gleich, und die Toolbar kann jederzeit wechseln.",+ "view_hint": "Es geht nichts verloren: Die Terminals arbeiten hinter dem Chat weiter, und der Schalter in der Workspace-Leiste wechselt jederzeit zwischen beiden.","selected": "Ausgewählt","workspace": "Arbeitsbereich","opens_as": "Wird geöffnet als",@@ -4295,12 +4302,12 @@"folder": { "label": "Ordner", "title": "Projektordner auswählen", "hint": "Alles, was die Agents tun, bleibt in diesem Ordner." },"layout": { "label": "Layout", "title": "Arbeitsbereich aufteilen", "hint": "Lege fest, wie viele unabhängige Terminal-Fenster geöffnet werden." },"agents": { "label": "Agents" },- "view": { "label": "Ansicht", "title": "Darstellung des Arbeitsbereichs auswählen", "hint": "Die Agents bleiben gleich — die Toolbar kann jederzeit umschalten." },+ "view": { "label": "Ansicht", "title": "Darstellung des Arbeitsbereichs auswählen", "hint": "Danach ist beides einen Klick entfernt — der Schalter sitzt in der Workspace-Leiste." },"review": { "label": "Prüfen", "title": "Vor dem Öffnen prüfen", "hint": "Nichts startet, bevor du den Arbeitsbereich öffnest." }},"views": {"grid": { "title": "Terminal-Raster", "description": "Alle Fenster gleichzeitig nebeneinander — die vollständige Terminal-Wand." },- "chat": { "title": "Chat-Ansicht", "description": "Ein Agent im Mittelpunkt, die anderen in einer Leiste — lesbar wie eine Unterhaltung." }+ "chat": { "title": "Chat", "description": "Der Agenten-Chat, im Ordner dieses Workspaces — schreiben statt Terminals zuschauen." }}},"crowded": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex f44a185cd1..1880fa2775 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -596,6 +596,8 @@"build_hint": "Build mode — the agent may change files. Click for Plan mode.","plan_hint": "Plan mode — the agent reads and plans, changes nothing. Click for Build mode.","folder": "Working folder",+ "jarvis_tools": "Jarvis · {count} tools",+ "jarvis_tools_hint": "This chat drives Jarvis: {count} Jarvis tools are available to it — the same ones the voice path uses.","send": "Send","stop": "Stop the turn","hint_connect": "{provider} is not connected yet.",@@ -1573,6 +1575,11 @@"shared_delete_prefix": "This key is also used by:","shared_delete_suffix": "Deleting it disables those providers too.","delete_anyway": "Delete anyway",+ "scope_dedicated_question": "{0} already has a different key saved. Use this new key only here, or replace it everywhere {0} is used?",+ "scope_family_question": "Some {0} areas have their own key ({1}). Replace those too, or keep them?",+ "scope_everywhere": "Everywhere for {0}",+ "scope_here": "Only here",+ "scope_keep_dedicated": "Keep their own keys","key_saved_label": "Key saved","key_saved_toast": "Key saved ({0})","key_removed_toast": "Key removed ({0})",@@ -4284,7 +4291,7 @@"setup_label": "Workspace setup","reading_mode": "Reading mode","reading_mode_label": "How the workspace opens",- "view_hint": "Only how the workspace is read changes — the agents, panes and conversations stay the same, and the toolbar can switch at any time.",+ "view_hint": "Nothing is given up either way: the terminals keep working behind the chat, and the switch in the workspace bar moves between the two at any time.","selected": "Selected","workspace": "Workspace","opens_as": "Opens as",@@ -4295,12 +4302,12 @@"folder": { "label": "Folder", "title": "Choose the project folder", "hint": "Everything the agents do stays inside this folder." },"layout": { "label": "Layout", "title": "Shape the workspace", "hint": "Choose how many independent terminal panes should open." },"agents": { "label": "Agents" },- "view": { "label": "View", "title": "Choose how to read the workspace", "hint": "The same agents either way — the toolbar can switch at any time." },+ "view": { "label": "View", "title": "Choose how to read the workspace", "hint": "Both are one click apart afterwards — the switch is in the workspace bar." },"review": { "label": "Review", "title": "Review before opening", "hint": "Nothing starts until you open the workspace." }},"views": {"grid": { "title": "Terminal grid", "description": "Every pane on screen at once, side by side — the full wall of terminals." },- "chat": { "title": "Chat view", "description": "One agent at a time on a calm stage, the rest on a rail — read like a conversation." }+ "chat": { "title": "Chat", "description": "The agent chat, running in this workspace's folder — type instead of watching terminals." }}},"crowded": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 60e9ccec13..50b8e0e656 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1573,6 +1573,11 @@"shared_delete_prefix": "Esta clave también la usan:","shared_delete_suffix": "Al eliminarla, esos proveedores también se desactivan.","delete_anyway": "Eliminar de todos modos",+ "scope_dedicated_question": "{0} ya tiene otra clave guardada. ¿Usar la nueva clave solo aquí o reemplazarla en todos los sitios donde se usa {0}?",+ "scope_family_question": "Algunas áreas de {0} tienen su propia clave ({1}). ¿Reemplazarlas también o mantenerlas?",+ "scope_everywhere": "En todas partes para {0}",+ "scope_here": "Solo aquí",+ "scope_keep_dedicated": "Mantener sus propias claves","key_saved_label": "Clave guardada","key_saved_toast": "Clave guardada ({0})","key_removed_toast": "Clave eliminada ({0})",@@ -4284,7 +4289,7 @@"setup_label": "Configurar espacio de trabajo","reading_mode": "Modo de lectura","reading_mode_label": "Cómo se abre el espacio de trabajo",- "view_hint": "Solo cambia la presentación: los agentes, paneles y conversaciones siguen iguales, y la barra permite cambiar en cualquier momento.",+ "view_hint": "No se pierde nada: las terminales siguen trabajando detrás del chat y el conmutador de la barra cambia entre ambas en cualquier momento.","selected": "Seleccionado","workspace": "Espacio de trabajo","opens_as": "Se abre como",@@ -4295,12 +4300,12 @@"folder": { "label": "Carpeta", "title": "Elige la carpeta del proyecto", "hint": "Todo lo que hagan los agentes permanece dentro de esta carpeta." },"layout": { "label": "Diseño", "title": "Diseña el espacio de trabajo", "hint": "Elige cuántos paneles de terminal independientes deben abrirse." },"agents": { "label": "Agentes" },- "view": { "label": "Vista", "title": "Elige cómo leer el espacio", "hint": "Los agentes son los mismos y la barra permite cambiar en cualquier momento." },+ "view": { "label": "Vista", "title": "Elige cómo leer el espacio", "hint": "Después ambas quedan a un clic: el conmutador está en la barra del espacio de trabajo." },"review": { "label": "Revisar", "title": "Revisa antes de abrir", "hint": "Nada empieza hasta que abras el espacio de trabajo." }},"views": {"grid": { "title": "Cuadrícula de terminales", "description": "Todos los paneles a la vez, uno junto a otro: la pared completa de terminales." },- "chat": { "title": "Vista de chat", "description": "Un agente en el centro y los demás en una barra, como una conversación." }+ "chat": { "title": "Chat", "description": "El chat de agentes, en la carpeta de este espacio de trabajo: escribe en lugar de mirar terminales." }}},"crowded": {diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 4314fd5af4..304aed66e1 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -105,6 +105,10 @@ ALLOWED_SECRET_KEYS: frozenset[str] = frozenset(s.key for s in WIZARD_SECRETS)class SecretBody(BaseModel):value: str = Field(..., min_length=1, description="Raw secret value (API key, token, etc.)")+ # One key per provider family: omitted = "ask if the family already holds+ # a different key"; "here" = this surface only; "everywhere" = replace the+ # family key on every surface. See config.plan_secret_save.+ scope: Literal["here", "everywhere"] | None = Field(default=None)class SwitchBody(BaseModel):@@ -3923,18 +3927,71 @@ _RESTART_REQUIRED_SECRET_KEYS: frozenset[str] = frozenset()+def _secret_slot_labels(slots: tuple[str, ...]) -> list[str]:+ """Human names of the surfaces that own ``slots`` (for the scope question)."""+ labels: dict[str, None] = {}+ for slot in slots:+ found = False+ for spec in PROVIDERS:+ if slot in spec.secret_keys:+ labels.setdefault(spec.label)+ found = True+ if not found:+ # Agent rows are not provider specs; name the section instead.+ labels.setdefault("Jarvis-Agents" if slot.startswith("jarvis_agent_") else slot)+ return list(labels)++@router.post("/secrets/{key}", openapi_extra={"x-jarvis-dangerous": True})async def set_secret_value(key: str, body: SecretBody, request: Request) -> dict[str, Any]:+ """Save a key for its whole provider family, or ask which scope was meant.++ The slot in the URL is the surface the user typed on, not necessarily+ where the value lands: the first Gemini key entered on the Realtime card+ becomes ``gemini_api_key`` so Brain, Tool Model, Agents, TTS and STT all+ work at once. Only a genuinely different second key returns+ ``choice_required`` (HTTP 200, nothing written) so the UI can ask+ "just here, or everywhere?" and re-post with ``scope``.+ """if key not in ALLOWED_SECRET_KEYS:raise HTTPException(status_code=404, detail=f"Unknown secret key: {key}")- if not cfg_mod.set_secret(key, body.value):- raise HTTPException(status_code=500, detail="Keyring write failed")- await _emit(request, SecretConfigured(key=key, action="set"))+ plan = cfg_mod.plan_secret_save(key, body.value, body.scope)+ if plan.choice_required:+ family_spec = get_spec(plan.family) if plan.family else None+ return {+ "ok": False,+ "key": key,+ "choice_required": True,+ "choice_kind": plan.choice_kind,+ "family": plan.family,+ "family_label": family_spec.label if family_spec else plan.family,+ "conflicting_labels": _secret_slot_labels(plan.conflicting_slots),+ }+ for slot in plan.writes:+ if not cfg_mod.set_secret(slot, body.value):+ raise HTTPException(status_code=500, detail="Keyring write failed")+ for slot in plan.deletes:+ if not cfg_mod.delete_secret(slot):+ # The new key IS saved; a leftover scoped copy only means one+ # surface keeps its old key. Say so instead of failing the save.+ log.warning(+ "Saved %s but could not remove the superseded scoped copy %s.",+ ", ".join(plan.writes),+ slot,+ )+ touched = (*plan.writes, *plan.deletes)+ for slot in plan.writes:+ await _emit(request, SecretConfigured(key=slot, action="set"))+ for slot in plan.deletes:+ await _emit(request, SecretConfigured(key=slot, action="delete"))_invalidate_section_health_state(request)return {"ok": True,"key": key,- "restart_required": key in _RESTART_REQUIRED_SECRET_KEYS,+ "written": list(plan.writes),+ "removed": list(plan.deletes),+ "family": plan.family,+ "restart_required": any(s in _RESTART_REQUIRED_SECRET_KEYS for s in touched),}diff --git a/tests/integration/test_provider_routes.py b/tests/integration/test_provider_routes.pyindex 67ce094238..f0b039431b 100644--- a/tests/integration/test_provider_routes.py+++ b/tests/integration/test_provider_routes.py@@ -509,6 +509,66 @@ def test_set_secret_emits_event(server_with_brain: WebServer, secret_store: _InMassert any(e.key == "openai_api_key" and e.action == "set" for e in received)+def test_set_secret_on_scoped_card_writes_the_family_slot(+ server_with_brain: WebServer, secret_store: _InMemorySecretStore+) -> None:+ """The first Gemini key typed on the Realtime card serves every Gemini surface."""+ with TestClient(server_with_brain.app) as client:+ resp = client.post("/api/secrets/realtime_gemini_api_key", json={"value": "AIza-1"})+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True+ assert body["written"] == ["gemini_api_key"]+ assert secret_store.data == {"gemini_api_key": "AIza-1"}+++def test_set_secret_asks_before_a_second_different_key(+ server_with_brain: WebServer, secret_store: _InMemorySecretStore+) -> None:+ secret_store.set("gemini_api_key", "AIza-1")+ with TestClient(server_with_brain.app) as client:+ resp = client.post("/api/secrets/jarvis_agent_gemini_api_key", json={"value": "AIza-2"})+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is False and body["choice_required"] is True+ assert body["choice_kind"] == "dedicated_vs_family"+ assert body["family_label"] == "Google Gemini"+ # Nothing was written while the question is open.+ assert secret_store.data == {"gemini_api_key": "AIza-1"}++ here = client.post(+ "/api/secrets/jarvis_agent_gemini_api_key",+ json={"value": "AIza-2", "scope": "here"},+ )+ assert here.json()["written"] == ["jarvis_agent_gemini_api_key"]+ assert secret_store.data["jarvis_agent_gemini_api_key"] == "AIza-2"+ assert secret_store.data["gemini_api_key"] == "AIza-1"+++def test_set_secret_everywhere_replaces_family_and_old_copies(+ server_with_brain: WebServer, secret_store: _InMemorySecretStore+) -> None:+ secret_store.set("openai_api_key", "sk-old")+ secret_store.set("realtime_openai_api_key", "sk-old")+ with TestClient(server_with_brain.app) as client:+ resp = client.post(+ "/api/secrets/realtime_openai_api_key",+ json={"value": "sk-new", "scope": "everywhere"},+ )+ body = resp.json()+ assert body["written"] == ["openai_api_key"]+ assert body["removed"] == ["realtime_openai_api_key"]+ assert secret_store.data == {"openai_api_key": "sk-new"}+++def test_set_secret_rejects_unknown_scope(+ server_with_brain: WebServer, secret_store: _InMemorySecretStore+) -> None:+ with TestClient(server_with_brain.app) as client:+ resp = client.post("/api/secrets/openai_api_key", json={"value": "x", "scope": "there"})+ assert resp.status_code == 422++def test_delete_secret(server_with_brain: WebServer, secret_store: _InMemorySecretStore) -> None:secret_store.set("gemini_api_key", "old")with TestClient(server_with_brain.app) as client:diff --git a/tests/unit/core/test_secret_family_save_plan.py b/tests/unit/core/test_secret_family_save_plan.pynew file mode 100644index 0000000000..b4ddbe021e--- /dev/null+++ b/tests/unit/core/test_secret_family_save_plan.py@@ -0,0 +1,169 @@+"""One key per provider family (2026-08-24).++A key entered on ANY surface (Realtime card, Agent row, Codex, Brain) is the+provider's key everywhere unless the user deliberately keeps a second one.+``plan_secret_save`` is the pure decision; these tests pin its rules with an+in-memory secret store, never the real keyring.+"""+from __future__ import annotations++import pytest++from jarvis.core import config as cfg+++def store(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]:+ data: dict[str, str] = {}++ def _get(key: str, env_fallback: str | None = None) -> str | None:+ return data.get(key)++ monkeypatch.setattr(cfg, "get_secret", _get)+ return data+++# ── classification is derived from the chains ───────────────────────────────+++def test_primary_slots_are_family_primaries() -> None:+ scope = cfg.secret_slot_scope("gemini_api_key")+ assert scope == cfg.SecretSlotScope("gemini", "gemini_api_key", dedicated=False)+++ ("slot", "family"),+ [+ ("realtime_gemini_api_key", "gemini"),+ ("realtime_openai_api_key", "openai"),+ ("realtime_vertex_api_key", "vertex"),+ ("jarvis_agent_gemini_api_key", "gemini"),+ ("jarvis_agent_anthropic_api_key", "claude-api"),+ ("codex_openai_api_key", "openai"),+ ],+)+def test_scoped_slots_point_at_their_family(slot: str, family: str) -> None:+ scope = cfg.secret_slot_scope(slot)+ assert scope is not None and scope.dedicated and scope.family == family+ assert scope.primary_slot == cfg.secret_family_primary_slot(family)+++def test_legacy_aliases_and_foreign_slots_have_no_scope() -> None:+ assert cfg.secret_slot_scope("google_api_key") is None+ assert cfg.secret_slot_scope("elevenlabs_api_key") is None+++def test_family_scoped_slots_enumerate_every_surface() -> None:+ assert set(cfg.secret_family_scoped_slots("gemini")) == {+ "realtime_gemini_api_key",+ "jarvis_agent_gemini_api_key",+ }+ assert set(cfg.secret_family_scoped_slots("openai")) == {+ "realtime_openai_api_key",+ "jarvis_agent_openai_api_key",+ "codex_openai_api_key",+ }+++# ── the first key saved anywhere is the family key ──────────────────────────+++def test_first_key_on_a_scoped_surface_lands_in_the_family_slot(store: dict[str, str]) -> None:+ plan = cfg.plan_secret_save("realtime_gemini_api_key", "AIza-new")+ assert plan.writes == ("gemini_api_key",)+ assert plan.deletes == ()+ assert not plan.choice_required+++def test_same_key_on_a_scoped_surface_drops_the_redundant_copy(store: dict[str, str]) -> None:+ store["gemini_api_key"] = "AIza-one"+ store["realtime_gemini_api_key"] = "AIza-stale"+ plan = cfg.plan_secret_save("realtime_gemini_api_key", "AIza-one")+ assert plan.writes == ("gemini_api_key",)+ assert plan.deletes == ("realtime_gemini_api_key",)+++def test_unscoped_slot_is_written_verbatim(store: dict[str, str]) -> None:+ plan = cfg.plan_secret_save("elevenlabs_api_key", "el-1")+ assert plan.writes == ("elevenlabs_api_key",)+ assert plan.family is None+++# ── a different second key asks the question ────────────────────────────────+++def test_different_key_on_scoped_surface_requires_a_choice(store: dict[str, str]) -> None:+ store["gemini_api_key"] = "AIza-one"+ plan = cfg.plan_secret_save("jarvis_agent_gemini_api_key", "AIza-two")+ assert plan.choice_required+ assert plan.writes == () and plan.deletes == ()+ assert plan.choice_kind == "dedicated_vs_family"+ assert plan.family == "gemini"+++def test_scope_here_keeps_the_second_key_local(store: dict[str, str]) -> None:+ store["gemini_api_key"] = "AIza-one"+ plan = cfg.plan_secret_save("jarvis_agent_gemini_api_key", "AIza-two", "here")+ assert plan.writes == ("jarvis_agent_gemini_api_key",)+ assert plan.deletes == ()+++def test_scope_everywhere_replaces_family_and_drops_old_mirrors(store: dict[str, str]) -> None:+ store["gemini_api_key"] = "AIza-one"+ store["realtime_gemini_api_key"] = "AIza-one" # mirror of the old key+ store["jarvis_agent_gemini_api_key"] = "AIza-third" # deliberate own key+ plan = cfg.plan_secret_save("realtime_gemini_api_key", "AIza-two", "everywhere")+ assert plan.writes == ("gemini_api_key",)+ # The realtime copy of the OLD key goes; the agent's third key is a choice+ # the user made and stays.+ assert plan.deletes == ("realtime_gemini_api_key",)+++# ── replacing the family key ────────────────────────────────────────────────+++def test_family_key_replace_with_no_dedicated_keys_is_plain(store: dict[str, str]) -> None:+ store["openai_api_key"] = "sk-old"+ plan = cfg.plan_secret_save("openai_api_key", "sk-new")+ assert plan.writes == ("openai_api_key",)+ assert plan.deletes == ()+ assert not plan.choice_required+++def test_family_key_replace_drops_mirrors_of_the_old_key(store: dict[str, str]) -> None:+ store["openai_api_key"] = "sk-old"+ store["realtime_openai_api_key"] = "sk-old"+ plan = cfg.plan_secret_save("openai_api_key", "sk-new")+ assert plan.writes == ("openai_api_key",)+ assert plan.deletes == ("realtime_openai_api_key",)+ assert not plan.choice_required+++def test_family_key_replace_asks_about_deliberate_dedicated_keys(store: dict[str, str]) -> None:+ store["openai_api_key"] = "sk-old"+ store["codex_openai_api_key"] = "sk-codex"+ plan = cfg.plan_secret_save("openai_api_key", "sk-new")+ assert plan.choice_required+ assert plan.choice_kind == "family_vs_dedicated"+ assert plan.conflicting_slots == ("codex_openai_api_key",)+++def test_family_key_replace_scope_here_keeps_dedicated_keys(store: dict[str, str]) -> None:+ store["openai_api_key"] = "sk-old"+ store["codex_openai_api_key"] = "sk-codex"+ plan = cfg.plan_secret_save("openai_api_key", "sk-new", "here")+ assert plan.writes == ("openai_api_key",)+ assert plan.deletes == ()+++def test_family_key_replace_scope_everywhere_drops_dedicated_keys(store: dict[str, str]) -> None:+ store["openai_api_key"] = "sk-old"+ store["codex_openai_api_key"] = "sk-codex"+ plan = cfg.plan_secret_save("openai_api_key", "sk-new", "everywhere")+ assert plan.writes == ("openai_api_key",)+ assert plan.deletes == ("codex_openai_api_key",)+++def test_unknown_scope_is_rejected(store: dict[str, str]) -> None:+ with pytest.raises(ValueError):+ cfg.plan_secret_save("openai_api_key", "sk-new", "somewhere")