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(permissions): surface macOS Keychain access as a first-class permission
Ruben Lütke7a506e98b82b
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex e4d09738a9..cbd533a1a2 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -2597,6 +2597,13 @@ _FILE_BACKEND_ACTIVE: bool = False# still readable from the OS store, and recovery probes must not mistake the# currently installed file backend for a recovered platform backend._PLATFORM_KEYRING_BACKEND: Any | None = None+# The credential slot whose OS-keyring read failed most recently. On macOS a+# user who clicks "Deny" on the Keychain prompt lands exactly here: the read+# raises, the process degrades to the file backend, and only a fresh read of a+# real existing item makes macOS show the prompt again. The permissions UI+# replays this slot on a user-initiated retry (a probe on a brand-new item+# would silently succeed without ever re-prompting).+_LAST_KEYRING_FAILED_SLOT: str | None = None_SECRET_REVISION_LOCK = threading.Lock()_SECRET_REVISIONS: dict[str, int] = {}@@ -2846,6 +2853,56 @@ def _try_restore_platform_keyring_backend() -> bool:return True+def credential_store_backend() -> str:+ """Report which credential store is live: ``platform`` | ``file`` | ``unavailable``.++ ``platform`` means the OS-encrypted store (macOS Keychain / Windows+ Credential Manager / Secret Service) serves reads and writes. ``file``+ means this process degraded to the local 0600 JSON fallback — on macOS+ that is the observable state after the user declined the Keychain prompt.+ The desktop permissions UI maps this onto its Keychain row.+ """+ _ensure_keyring_backend()+ try:+ import keyring++ backend = keyring.get_keyring()+ except Exception: # noqa: BLE001 -- no keyring module on this install+ return "unavailable"+ if _is_platform_keyring_backend(backend):+ return "platform"+ if getattr(backend, "_jarvis_file_backend", False):+ return "file"+ return "unavailable"+++def try_recover_platform_credential_store() -> bool:+ """User-initiated retry of the OS credential store (macOS Keychain re-prompt).++ Restores the platform keyring backend, then replays the exact read whose+ failure degraded this process to the file fallback. On macOS that replay+ is what makes the Keychain prompt appear again after an earlier "Deny" —+ the restore probe alone touches only a fresh disposable item, which never+ prompts, so without the replay a recovery would be reported that the next+ real read immediately reverts.+ """+ global _LAST_KEYRING_FAILED_SLOT+ if not _try_restore_platform_keyring_backend():+ return False+ slot = _LAST_KEYRING_FAILED_SLOT+ if slot is None:+ return True+ try:+ import keyring++ keyring.get_password(KEYRING_SERVICE, slot)+ except Exception: # noqa: BLE001 -- the user declined the prompt again+ _install_file_cred_backend("credential-store access declined again")+ return False+ _LAST_KEYRING_FAILED_SLOT = None+ return True++def get_secret(key: str, env_fallback: str | None = None) -> str | None:"""Retrieve a secret value from every portable credential source.@@ -2906,6 +2963,8 @@ def get_secret(key: str, env_fallback: str | None = None) -> str | None:# _ensure_keyring_backend saw a viable backend. Degrade to the 0600 file# store and retry once, so a key saved to the file fallback in a prior run# is still visible instead of dead-ending on the locked keyring.+ global _LAST_KEYRING_FAILED_SLOT+ _LAST_KEYRING_FAILED_SLOT = keyif _install_file_cred_backend("keyring read failed"):try:import keyringdiff --git a/jarvis/platform/permissions.py b/jarvis/platform/permissions.pyindex 748264f115..e611efbe88 100644--- a/jarvis/platform/permissions.py+++ b/jarvis/platform/permissions.py@@ -35,6 +35,11 @@ class PermissionId(StrEnum):ACCESSIBILITY = "accessibility"INPUT_MONITORING = "input_monitoring"EVENT_POSTING = "event_posting"+ # Not a TCC grant: the macOS Keychain prompts per item at first access+ # (typically right at app start, when API keys are read). Users who deny+ # it silently land on the file fallback and read the prompt as suspicious+ # unless the UI names and explains it like every other permission.+ CREDENTIAL_STORE = "credential_store"class PermissionState(StrEnum):@@ -61,6 +66,7 @@ FEATURE_REQUIREMENTS: dict[str, tuple[PermissionId, ...]] = {PermissionId.INPUT_MONITORING,),"window_control": (PermissionId.ACCESSIBILITY,),+ "api_keys": (PermissionId.CREDENTIAL_STORE,),}_LABELS: dict[PermissionId, str] = {@@ -69,6 +75,7 @@ _LABELS: dict[PermissionId, str] = {PermissionId.ACCESSIBILITY: "Accessibility",PermissionId.INPUT_MONITORING: "Input Monitoring",PermissionId.EVENT_POSTING: "Input Control",+ PermissionId.CREDENTIAL_STORE: "Keychain (API keys)",}_SETTINGS_URLS: dict[PermissionId, str] = {@@ -120,6 +127,20 @@ def _default_iohid_check(request_type: int) -> int | None:return None+def _default_credential_store_backend() -> str:+ """Ask the config layer which credential backend is live right now."""+ from jarvis.core.config import credential_store_backend++ return credential_store_backend()+++def _default_credential_store_recover() -> bool:+ """Retry the OS credential store; on macOS this re-triggers the prompt."""+ from jarvis.core.config import try_recover_platform_credential_store++ return try_recover_platform_credential_store()++_READY_STATES = frozenset({PermissionState.GRANTED, PermissionState.NOT_REQUIRED})_RESTART_AFTER_CHANGE = frozenset({@@ -185,10 +206,14 @@ class SystemPermissionPort:platform_name: PlatformName | None = None,module_loader: Callable[[str], Any] = importlib.import_module,iohid_check: Callable[[int], int | None] = _default_iohid_check,+ credential_store_backend: Callable[[], str] = _default_credential_store_backend,+ credential_store_recover: Callable[[], bool] = _default_credential_store_recover,) -> None:self._platform_name = platform_nameself._module_loader = module_loaderself._iohid_check = iohid_check+ self._credential_store_backend = credential_store_backend+ self._credential_store_recover = credential_store_recover# This is operation state, not a cached permission probe. The set lives# only for the current process and therefore clears exactly when the# required app restart has happened.@@ -312,9 +337,30 @@ class SystemPermissionPort:return Nonereturn _IOHID_ACCESS_STATES.get(int(raw))+ def _credential_store_state(self) -> PermissionState:+ """Map the live credential backend onto a permission state.++ The macOS Keychain has no TCC preflight; the observable truth is which+ keyring backend serves this process. A declined Keychain prompt makes+ the next read raise, config degrades to the 0600 file fallback, and+ this row turns "not granted" — recoverable through the request flow,+ which replays the failed read so macOS prompts again.+ """+ try:+ backend = self._credential_store_backend()+ except Exception: # noqa: BLE001 - a broken probe fails closed+ return PermissionState.UNAVAILABLE+ if backend == "platform":+ return PermissionState.GRANTED+ if backend == "file":+ return PermissionState.NOT_GRANTED+ return PermissionState.UNAVAILABLE+def _state(self, permission_id: PermissionId) -> PermissionState:if self.platform != "darwin":return PermissionState.NOT_REQUIRED+ if permission_id is PermissionId.CREDENTIAL_STORE:+ return self._credential_store_state()if permission_id is PermissionId.MICROPHONE:return self._microphone_state()if permission_id is PermissionId.SCREEN_RECORDING:@@ -375,6 +421,8 @@ class SystemPermissionPort:)def _requester_available(self, permission_id: PermissionId) -> bool:+ if permission_id is PermissionId.CREDENTIAL_STORE:+ return Trueif permission_id is PermissionId.MICROPHONE:module = self._load("AVFoundation")owner = getattr(module, "AVCaptureDevice", None)@@ -445,6 +493,15 @@ class SystemPermissionPort:})detail = self._detail(state)+ if (+ permission_id is PermissionId.CREDENTIAL_STORE+ and state is PermissionState.NOT_GRANTED+ ):+ detail = (+ "Keychain access was declined, so API keys are kept in a "+ "local file for now. Allow access to store them encrypted "+ "in the macOS Keychain."+ )if restart_pending and state not in _READY_STATES:detail = ("Permission changes made in System Settings take effect "@@ -457,7 +514,9 @@ class SystemPermissionPort:status=state.value,required=required,can_request=can_request,- can_open_settings=eligible,+ # The Keychain has no System Settings pane; its only+ # recovery path is the request flow above.+ can_open_settings=eligible and permission_id in _SETTINGS_URLS,restart_required=restart_pending,detail=detail,)@@ -507,6 +566,12 @@ class SystemPermissionPort:return Nonedef _native_request(self, permission_id: PermissionId) -> None:+ if permission_id is PermissionId.CREDENTIAL_STORE:+ # Replaying the failed Keychain read is the only supported way to+ # make macOS show the prompt again; the outcome (allowed or denied+ # once more) lands honestly in the after-snapshot.+ self._credential_store_recover()+ returnif permission_id is PermissionId.MICROPHONE:av = self._load("AVFoundation")av.AVCaptureDevice.requestAccessForMediaType_completionHandler_(@@ -653,6 +718,18 @@ class SystemPermissionPort:) -> PermissionOperation:"""Open the matching System Settings pane via LaunchServices."""before = self.snapshot()+ if permission_id not in _SETTINGS_URLS:+ return PermissionOperation(+ False,+ permission_id.value,+ "open_settings",+ False,+ dry_run,+ False,+ f"{_LABELS[permission_id]} has no System Settings pane; "+ "use the request flow instead.",+ before,+ )if dry_run:return PermissionOperation(True,diff --git a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsxindex c259e0e72a..7a2bdc3577 100644--- a/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/PermissionsAlertBanner.tsx@@ -4,6 +4,7 @@ import {ChevronDown,ChevronUp,Keyboard,+ KeyRound,Loader2,Mic,Monitor,@@ -25,6 +26,7 @@ const ICONS = {accessibility: Accessibility,input_monitoring: Keyboard,event_posting: MousePointer2,+ credential_store: KeyRound,} satisfies Record<PermissionId, typeof Mic>;// Mirrors the "waiting for System Settings" logic inside usePermissions: adiff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsxindex 0cbd053c16..b6144e4cbd 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.test.tsx@@ -8,6 +8,7 @@ const IDS = ["accessibility","input_monitoring","event_posting",+ "credential_store",] as const;function macSnapshot(overrides: Partial<PermissionSnapshot> = {}): PermissionSnapshot {diff --git a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsxindex 35e36fce8e..61cdb02de4 100644--- a/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx+++ b/jarvis/ui/web/frontend/src/components/onboarding/steps/PermissionsStep.tsx@@ -12,6 +12,7 @@ const EXPECTED_MACOS_PERMISSIONS = new Set<PermissionId>(["accessibility","input_monitoring","event_posting",+ "credential_store",]);export function permissionSnapshotReady(snapshot: PermissionSnapshot | null): boolean {diff --git a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts b/jarvis/ui/web/frontend/src/hooks/usePermissions.tsindex 981e808325..eb59af7366 100644--- a/jarvis/ui/web/frontend/src/hooks/usePermissions.ts+++ b/jarvis/ui/web/frontend/src/hooks/usePermissions.ts@@ -5,7 +5,8 @@ export type PermissionId =| "screen_recording"| "accessibility"| "input_monitoring"- | "event_posting";+ | "event_posting"+ | "credential_store";export type PermissionState =| "granted"diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 4db414e157..8e6b9af9e1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1076,7 +1076,8 @@"screen_recording": { "title": "Bildschirmaufnahme", "description": "Erforderlich, damit Computer-Use alle verbundenen Bildschirme sehen kann." },"accessibility": { "title": "Bedienungshilfen", "description": "Erforderlich für zuverlässige Klicks, Eingaben, Fokus und Fenstersteuerung." },"input_monitoring": { "title": "Eingabeüberwachung", "description": "Erforderlich für globale Push-to-Talk- und Tastaturkurzbefehle." },- "event_posting": { "title": "Eingabesteuerung", "description": "Erforderlich, damit Computer-Use Maus- und Tastaturereignisse senden kann." }+ "event_posting": { "title": "Eingabesteuerung", "description": "Erforderlich, damit Computer-Use Maus- und Tastaturereignisse senden kann." },+ "credential_store": { "title": "Schlüsselbund (API-Keys)", "description": "Speichert deine API-Keys verschlüsselt im macOS-Schlüsselbund statt in einer Klartextdatei — genau dafür fragt macOS beim Start der App. Deine Keys bleiben auf deinem Mac und werden nirgendwohin gesendet." }},"banner": {"title": "Aktion nötig: macOS-Berechtigungen fehlen",@@ -1089,7 +1090,8 @@"voice": "Sprache & Aktivierungswort","computer_use": "Computer-Use","global_hotkeys": "Globale Kurzbefehle",- "window_control": "Fenstersteuerung"+ "window_control": "Fenstersteuerung",+ "api_keys": "Sichere API-Key-Ablage"}},"settings_view": {@@ -1673,7 +1675,7 @@"permissions": {"title": "Zugriff auf diesem Mac erlauben","body": "macOS lässt jede Funktion einzeln bestätigen. Nutze die Schaltflächen unten und kehre danach hierher zurück; der Status wird automatisch aktualisiert.",- "privacy_note": "Diese Abfragen kommen von macOS. Das Installationsprogramm kann sie nicht stillschweigend freigeben, und Personal Jarvis umgeht niemals die Systemeinstellungen.",+ "privacy_note": "Diese Abfragen kommen von macOS. Das Installationsprogramm kann sie nicht stillschweigend freigeben, und Personal Jarvis umgeht niemals die Systemeinstellungen. Die Schlüsselbund-Abfrage beim App-Start bedeutet nur, dass Personal Jarvis deine API-Keys verschlüsselt im macOS-Schlüsselbund speichert — sie verlassen deinen Mac nicht.","continue": "Weiter","text_only": "Nur mit Text fortfahren"},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex fabca2889c..bada8f1618 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1077,7 +1077,8 @@"screen_recording": { "title": "Screen Recording", "description": "Required for Computer-Use to see every connected display." },"accessibility": { "title": "Accessibility", "description": "Required for reliable clicks, typing, focus, and window control." },"input_monitoring": { "title": "Input Monitoring", "description": "Required for global push-to-talk and keyboard shortcuts." },- "event_posting": { "title": "Input control", "description": "Required for Computer-Use to send mouse and keyboard events." }+ "event_posting": { "title": "Input control", "description": "Required for Computer-Use to send mouse and keyboard events." },+ "credential_store": { "title": "Keychain (API keys)", "description": "Stores your API keys encrypted in the macOS Keychain instead of a plain file — that is the Keychain prompt you see when the app starts. Your keys stay on your Mac and are never sent anywhere." }},"banner": {"title": "Action needed: macOS permissions are missing",@@ -1090,7 +1091,8 @@"voice": "Voice & wake word","computer_use": "Computer-Use","global_hotkeys": "Global shortcuts",- "window_control": "Window control"+ "window_control": "Window control",+ "api_keys": "Secure API-key storage"}},"settings_view": {@@ -1674,7 +1676,7 @@"permissions": {"title": "Allow access on this Mac","body": "macOS asks you to approve each capability separately. Use the buttons below, then return here; the status updates automatically.",- "privacy_note": "These prompts come from macOS. The installer cannot silently approve them, and Personal Jarvis never bypasses System Settings.",+ "privacy_note": "These prompts come from macOS. The installer cannot silently approve them, and Personal Jarvis never bypasses System Settings. The Keychain prompt at app start only means Personal Jarvis is saving your API keys encrypted in the macOS Keychain — they never leave your Mac.","continue": "Continue","text_only": "Continue with text only"},diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex b904edf68f..238b68a63a 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1076,7 +1076,8 @@"screen_recording": { "title": "Grabación de pantalla", "description": "Necesario para que Computer-Use vea todas las pantallas conectadas." },"accessibility": { "title": "Accesibilidad", "description": "Necesario para clics, escritura, enfoque y control de ventanas fiables." },"input_monitoring": { "title": "Monitorización de entrada", "description": "Necesario para pulsar para hablar y atajos de teclado globales." },- "event_posting": { "title": "Control de entrada", "description": "Necesario para que Computer-Use envíe eventos de ratón y teclado." }+ "event_posting": { "title": "Control de entrada", "description": "Necesario para que Computer-Use envíe eventos de ratón y teclado." },+ "credential_store": { "title": "Llavero (claves API)", "description": "Guarda tus claves API cifradas en el Llavero de macOS en lugar de un archivo de texto plano — ese es el aviso del Llavero que ves al iniciar la app. Tus claves se quedan en tu Mac y nunca se envían a ningún sitio." }},"banner": {"title": "Acción necesaria: faltan permisos de macOS",@@ -1089,7 +1090,8 @@"voice": "Voz y palabra de activación","computer_use": "Computer-Use","global_hotkeys": "Atajos globales",- "window_control": "Control de ventanas"+ "window_control": "Control de ventanas",+ "api_keys": "Almacenamiento seguro de claves API"}},"settings_view": {@@ -1673,7 +1675,7 @@"permissions": {"title": "Permite el acceso en este Mac","body": "macOS pide aprobar cada capacidad por separado. Usa los botones de abajo y vuelve aquí; el estado se actualizará automáticamente.",- "privacy_note": "Estos avisos proceden de macOS. El instalador no puede aprobarlos de forma silenciosa y Personal Jarvis nunca elude Ajustes del Sistema.",+ "privacy_note": "Estos avisos proceden de macOS. El instalador no puede aprobarlos de forma silenciosa y Personal Jarvis nunca elude Ajustes del Sistema. El aviso del Llavero al iniciar la app solo significa que Personal Jarvis guarda tus claves API cifradas en el Llavero de macOS — nunca salen de tu Mac.","continue": "Continuar","text_only": "Continuar solo con texto"},diff --git a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsxindex 1d220e102f..1cea5026da 100644--- a/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx+++ b/jarvis/ui/web/frontend/src/views/settings/PermissionsPanel.tsx@@ -3,6 +3,7 @@ import {CheckCircle2,CircleAlert,Keyboard,+ KeyRound,Loader2,Mic,Monitor,@@ -28,6 +29,7 @@ const ICONS = {accessibility: Accessibility,input_monitoring: Keyboard,event_posting: MousePointer2,+ credential_store: KeyRound,} satisfies Record<PermissionId, typeof Mic>;const READY_STATES = new Set(["granted", "not_required"]);@@ -175,7 +177,10 @@ function PermissionRow({<Icon className="h-4 w-4 shrink-0 text-primary" /><div className="min-w-[12rem] flex-1"><div className="text-sm font-medium">{t(`permissions.items.${item.id}.title`)}</div>- {!compact && (+ {/* Compact rows drop descriptions to stay scannable — except when+ the grant is missing: a user deciding whether to allow access+ (e.g. the startup Keychain prompt) needs the why right here. */}+ {(!compact || !ready) && (<p className="mt-0.5 text-xs text-muted-foreground">{t(`permissions.items.${item.id}.description`)}</p>diff --git a/tests/unit/core/test_keyring_backend_recovery.py b/tests/unit/core/test_keyring_backend_recovery.pyindex 50acb1323c..fd7d7db312 100644--- a/tests/unit/core/test_keyring_backend_recovery.py+++ b/tests/unit/core/test_keyring_backend_recovery.py@@ -62,6 +62,31 @@ class _LockableBackend(_MemoryBackend):super().delete_password(service, username)+class _CountingBackend(_MemoryBackend):+ """Platform store that records every read for replay assertions."""++ def __init__(self) -> None:+ super().__init__()+ self.reads: list[tuple[str, str]] = []++ def get_password(self, service: str, username: str) -> str | None:+ self.reads.append((service, username))+ return super().get_password(service, username)+++class _DenyingSlotBackend(_MemoryBackend):+ """Platform store where one slot keeps raising — a re-denied Keychain item."""++ def __init__(self, denied_slot: str) -> None:+ super().__init__()+ self.denied_slot = denied_slot++ def get_password(self, service: str, username: str) -> str | None:+ if username == self.denied_slot:+ raise RuntimeError("user denied keychain access")+ return super().get_password(service, username)++@pytest.fixturedef _restore_keyring_backend():original = keyring.get_keyring()@@ -345,6 +370,97 @@ def test_failed_retained_platform_delete_preserves_newer_file_copy(assert cfg.get_secret("google_client_secret", "TEST_GOOGLE_CLIENT_SECRET") == "new-file-value"+def test_credential_store_backend_reports_platform_and_file(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ keyring.set_keyring(_MemoryBackend())+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)++ assert cfg.credential_store_backend() == "platform"++ assert cfg._install_file_cred_backend("test degrade") is True+ assert cfg.credential_store_backend() == "file"+++def test_failed_keyring_read_remembers_the_slot_for_replay(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ keyring.set_keyring(_UnavailableBackend())+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", False)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.setattr(cfg, "_LAST_KEYRING_FAILED_SLOT", None)+ monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)++ cfg.get_secret("openrouter_api_key")++ assert cfg._LAST_KEYRING_FAILED_SLOT == "openrouter_api_key"+ assert cfg._FILE_BACKEND_ACTIVE is True+++def test_recover_replays_the_failed_slot_and_clears_it(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ # The restore probe only touches a fresh disposable item, which never+ # re-triggers the macOS Keychain prompt. Recovery must replay the exact+ # slot whose read failed, or it would report success the next real read+ # immediately reverts.+ file_backend = _MemoryBackend()+ platform_backend = _CountingBackend()+ keyring.set_keyring(file_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.setattr(cfg, "_LAST_KEYRING_FAILED_SLOT", "openrouter_api_key")+ monkeypatch.setattr(+ keyring.core, "init_backend", lambda: keyring.set_keyring(platform_backend)+ )++ assert cfg.try_recover_platform_credential_store() is True++ assert cfg._FILE_BACKEND_ACTIVE is False+ assert cfg._LAST_KEYRING_FAILED_SLOT is None+ assert (cfg.KEYRING_SERVICE, "openrouter_api_key") in platform_backend.reads+ assert cfg.credential_store_backend() == "platform"+++def test_recover_degrades_again_when_the_replayed_read_is_denied(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+ _restore_keyring_backend,+) -> None:+ file_backend = _MemoryBackend()+ denying = _DenyingSlotBackend("openrouter_api_key")+ keyring.set_keyring(file_backend)+ monkeypatch.setattr(cfg, "DATA_DIR", tmp_path)+ monkeypatch.setattr(cfg, "_data_dir_cache", None, raising=False)+ monkeypatch.setattr(cfg, "_KEYRING_BACKEND_READY", True)+ monkeypatch.setattr(cfg, "_FILE_BACKEND_ACTIVE", True)+ monkeypatch.setattr(cfg, "_PLATFORM_KEYRING_BACKEND", None)+ monkeypatch.setattr(cfg, "_LAST_KEYRING_FAILED_SLOT", "openrouter_api_key")+ monkeypatch.setattr(keyring.core, "init_backend", lambda: keyring.set_keyring(denying))++ assert cfg.try_recover_platform_credential_store() is False++ assert cfg._FILE_BACKEND_ACTIVE is True+ assert cfg._LAST_KEYRING_FAILED_SLOT == "openrouter_api_key"+ assert cfg.credential_store_backend() == "file"++def test_marketplace_disconnect_fails_closed_when_platform_token_becomes_locked(monkeypatch: pytest.MonkeyPatch,tmp_path,diff --git a/tests/unit/platform/test_permissions.py b/tests/unit/platform/test_permissions.pyindex 7b2f6c8030..2bc6f0ddf9 100644--- a/tests/unit/platform/test_permissions.py+++ b/tests/unit/platform/test_permissions.py@@ -132,6 +132,8 @@ def _native_modules(def _port(modules: dict[str, object],iohid_check: Callable[[int], int | None] = lambda _type: None,+ credential_backend: Callable[[], str] = lambda: "platform",+ credential_recover: Callable[[], bool] = lambda: True,) -> SystemPermissionPort:def load(name: str) -> object:if name not in modules:@@ -139,8 +141,15 @@ def _port(return modules[name]# iohid_check defaults to "unavailable" so unit runs stay hermetic even on- # a real Mac, where the default probe would read the machine's TCC state.- return SystemPermissionPort(platform_name="darwin", module_loader=load, iohid_check=iohid_check)+ # a real Mac, where the default probe would read the machine's TCC state;+ # the credential stubs keep the host's real keyring untouched the same way.+ return SystemPermissionPort(+ platform_name="darwin",+ module_loader=load,+ iohid_check=iohid_check,+ credential_store_backend=credential_backend,+ credential_store_recover=credential_recover,+ )def _permission(snapshot: dict, permission_id: PermissionId) -> dict:@@ -540,10 +549,14 @@ def test_broken_native_bridge_import_fails_closed() -> None:def broken_loader(_name: str) -> object:raise OSError("incompatible native framework")+ def broken_credential_probe() -> str:+ raise OSError("credential probe unavailable")+port = SystemPermissionPort(platform_name="darwin",module_loader=broken_loader,iohid_check=lambda _type: None,+ credential_store_backend=broken_credential_probe,)snapshot = port.snapshot()@@ -551,3 +564,96 @@ def test_broken_native_bridge_import_fails_closed() -> None:assert snapshot["app_identity"]["stable"] is Falseassert {item["status"] for item in snapshot["permissions"]} == {"unavailable"}assert all(not feature["ready"] for feature in snapshot["features"].values())+++def test_credential_store_reports_granted_while_platform_keyring_serves() -> None:+ modules, _, _ = _native_modules()++ item = _permission(_port(modules).snapshot(), PermissionId.CREDENTIAL_STORE)++ assert item["status"] == "granted"+ assert item["can_open_settings"] is False+++def test_credential_store_file_fallback_is_not_granted_and_requestable() -> None:+ # A declined macOS Keychain prompt degrades config to the 0600 file+ # fallback; the row must surface that honestly and keep the retry alive.+ modules, _, _ = _native_modules()+ port = _port(modules, credential_backend=lambda: "file")++ snapshot = port.snapshot()+ item = _permission(snapshot, PermissionId.CREDENTIAL_STORE)++ assert item["status"] == "not_granted"+ assert item["can_request"] is True+ assert item["can_open_settings"] is False+ assert "Keychain" in (item["detail"] or "")+ assert snapshot["features"]["api_keys"]["ready"] is False+++def test_credential_store_request_replays_recovery_and_reports_live_state() -> None:+ modules, _, _ = _native_modules()+ state = {"backend": "file", "recover_calls": 0}++ def recover() -> bool:+ state["recover_calls"] += 1+ state["backend"] = "platform"+ return True++ port = _port(+ modules,+ credential_backend=lambda: str(state["backend"]),+ credential_recover=recover,+ )++ result = port.request(PermissionId.CREDENTIAL_STORE)++ assert result.ok is True+ assert result.performed is True+ assert result.restart_required is False+ assert state["recover_calls"] == 1+ assert _permission(result.snapshot, PermissionId.CREDENTIAL_STORE)["status"] == "granted"+ assert result.snapshot["restart_required"] is False+++def test_credential_store_declined_again_stays_not_granted() -> None:+ modules, _, _ = _native_modules()+ port = _port(+ modules,+ credential_backend=lambda: "file",+ credential_recover=lambda: False,+ )++ result = port.request(PermissionId.CREDENTIAL_STORE)++ assert result.ok is True+ assert result.performed is True+ assert _permission(result.snapshot, PermissionId.CREDENTIAL_STORE)["status"] == "not_granted"+++def test_credential_store_open_settings_refuses_honestly() -> None:+ # There is no System Settings pane for the Keychain; a silent no-op button+ # would look like the app is broken.+ modules, _, workspace = _native_modules()+ port = _port(modules, credential_backend=lambda: "file")++ result = port.open_settings(PermissionId.CREDENTIAL_STORE)++ assert result.ok is False+ assert "System Settings pane" in result.message+ assert workspace.opened_urls == []+++def test_credential_store_probe_failure_reports_unavailable() -> None:+ modules, _, _ = _native_modules()++ def broken_probe() -> str:+ raise RuntimeError("probe failed")++ item = _permission(+ _port(modules, credential_backend=broken_probe).snapshot(),+ PermissionId.CREDENTIAL_STORE,+ )++ assert item["status"] == "unavailable"+ assert item["can_request"] is False