AI-native design editor. Open-source Figma alternative.
fix: prevent repeated Keychain prompts and isolate native tests (#664)
Danila Poyarkov6cec1b2c586f
diff --git a/AGENTS.md b/AGENTS.mdindex 2ffdfcba2..ee39d0644 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -161,6 +161,8 @@ Self-review for duplication, named shared types, precise unions, and files approNative desktop interaction checks live under `tests/e2e/native/**` and run through WebdriverIO against an explicit test-only Tauri binary. Use `bun run test:native` to build and run them, or `bun run build:native-test` when only the binary is needed. The embedded WebDriver plugin is compiled only with the `native-test` Cargo feature and must never be enabled in normal development or production binaries.+Native-test builds use a separate application identifier, an ephemeral WebView data store, and process-memory credentials. Never run UI smoke tests against production Keychain entries or clear user recovery data to unblock tests. Tests requiring persistence across application restarts need a dedicated test-owned persistent profile rather than the default ephemeral profile.+Keep responsibilities distinct: engine tests cover state contracts, Playwright browser E2E covers application integration, and native tests answer only whether the real platform WebView and Tauri shell deliver an interaction correctly. Platform-limited checks must skip rather than claim coverage. Synthetic composition tests do not prove real IME behavior, and native clipboard behavior remains a separate acceptance gap unless the test receives trusted OS clipboard events.## Renderingdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 73814a474..fba862f1d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -42,6 +42,8 @@### Fixed+- Avoid macOS Keychain prompts during credential status checks and pause repeated credential access after failures until explicitly retried from Settings.+- Route browser Command/Ctrl plus and minus shortcuts to canvas zoom instead of page zoom.- Resolve `$name` references in imported `.pen` fills, stroke fills, font families, dimensions, and spacing without requiring a `--` prefix. (#563)- Prevent the stock photo tool from replacing text, lines, structural layers, or containers with content while supporting closed shape geometry.diff --git a/desktop/Cargo.lock b/desktop/Cargo.lockindex abf50fc28..e2020bf4a 100644--- a/desktop/Cargo.lock+++ b/desktop/Cargo.lock@@ -3263,6 +3263,7 @@ dependencies = ["font-kit","keyring","reqwest 0.12.28",+ "security-framework","serde","serde_json","tauri",diff --git a/desktop/Cargo.toml b/desktop/Cargo.tomlindex 55837aaa7..17caeea3e 100644--- a/desktop/Cargo.toml+++ b/desktop/Cargo.toml@@ -42,6 +42,9 @@ tauri-plugin-clipboard-manager = "2"keyring = "4.1.5"tauri-plugin-wdio-webdriver = { version = "1.3.0", optional = true }+[target.'cfg(target_os = "macos")'.dependencies]+security-framework = "3"+[target.'cfg(any(target_os = "macos", windows, target_os = "linux"))'.dependencies]tauri-plugin-single-instance = "2"diff --git a/desktop/src/credentials.rs b/desktop/src/credentials.rsindex 59563c00c..3d21cc4c5 100644--- a/desktop/src/credentials.rs+++ b/desktop/src/credentials.rs@@ -1,6 +1,14 @@+use std::sync::Mutex;+use tauri::Emitter;++// Serialize all native operations, including temporary process-wide macOS UI suppression.+static CREDENTIAL_ACCESS: Mutex<Option<CredentialErrorCode>> = Mutex::new(None);++#[cfg(not(feature = "native-test"))]use keyring::{Entry, Error as KeyringError};use serde::{Deserialize, Serialize};+#[cfg(not(feature = "native-test"))]const CREDENTIAL_SERVICE: &str = "net.dannote.open-pencil.credentials";const AVAILABILITY_ACCOUNT: &str = "v1:system:default:availability";const MAX_SEGMENT_LENGTH: usize = 64;@@ -56,6 +64,9 @@ enum BackendError {}trait CredentialBackend {+ fn exists(&self, account: &str) -> Result<bool, BackendError> {+ self.read(account).map(|value| value.is_some())+ }fn read(&self, account: &str) -> Result<Option<String>, BackendError>;fn write(&self, account: &str, value: &str) -> Result<(), BackendError>;fn remove(&self, account: &str) -> Result<(), BackendError>;@@ -63,13 +74,31 @@ trait CredentialBackend {struct NativeCredentialBackend;+#[cfg(not(feature = "native-test"))]impl NativeCredentialBackend {fn entry(account: &str) -> Result<Entry, BackendError> {Entry::new(CREDENTIAL_SERVICE, account).map_err(map_keyring_error)}}+#[cfg(not(feature = "native-test"))]impl CredentialBackend for NativeCredentialBackend {+ #[cfg(target_os = "macos")]+ fn exists(&self, account: &str) -> Result<bool, BackendError> {+ use security_framework::item::{ItemClass, ItemSearchOptions};+ match ItemSearchOptions::new()+ .class(ItemClass::generic_password())+ .service(CREDENTIAL_SERVICE)+ .account(account)+ .load_attributes(true)+ .load_data(false)+ .search()+ {+ Ok(items) => Ok(!items.is_empty()),+ Err(error) if error.code() == -25300 => Ok(false),+ Err(_) => Err(BackendError::Locked),+ }+ }fn read(&self, account: &str) -> Result<Option<String>, BackendError> {match Self::entry(account)?.get_password() {Ok(value) => Ok(Some(value)),@@ -92,6 +121,7 @@ impl CredentialBackend for NativeCredentialBackend {}}+#[cfg(not(feature = "native-test"))]fn map_keyring_error(error: KeyringError) -> BackendError {match error {KeyringError::NoStorageAccess(_) => BackendError::Locked,@@ -102,6 +132,91 @@ fn map_keyring_error(error: KeyringError) -> BackendError {}}+#[cfg(feature = "native-test")]+static TEST_CREDENTIALS: std::sync::LazyLock<Mutex<std::collections::HashMap<String, String>>> =+ std::sync::LazyLock::new(|| Mutex::new(std::collections::HashMap::new()));++#[cfg(feature = "native-test")]+impl CredentialBackend for NativeCredentialBackend {+ fn read(&self, account: &str) -> Result<Option<String>, BackendError> {+ Ok(TEST_CREDENTIALS+ .lock()+ .map_err(|_| BackendError::Failed)?+ .get(account)+ .cloned())+ }+ fn write(&self, account: &str, value: &str) -> Result<(), BackendError> {+ // Reserved fixture value in the memory-only native-test backend.+ if value == "open-pencil-native-test-denied" {+ return Err(BackendError::Locked);+ }+ TEST_CREDENTIALS+ .lock()+ .map_err(|_| BackendError::Failed)?+ .insert(account.to_owned(), value.to_owned());+ Ok(())+ }+ fn remove(&self, account: &str) -> Result<(), BackendError> {+ TEST_CREDENTIALS+ .lock()+ .map_err(|_| BackendError::Failed)?+ .remove(account);+ Ok(())+ }+}++fn access_state() -> std::sync::MutexGuard<'static, Option<CredentialErrorCode>> {+ CREDENTIAL_ACCESS.lock().unwrap_or_else(|error| {+ let mut state = error.into_inner();+ // A backend panic may interrupt bookkeeping; require explicit retry.+ state.get_or_insert(CredentialErrorCode::Failed);+ CREDENTIAL_ACCESS.clear_poison();+ state+ })+}++fn reset_access_state() {+ *access_state() = None;+}++fn credential_operation<T>(+ interactive: bool,+ operation: impl FnOnce() -> Result<T, CredentialError>,+) -> Result<T, CredentialError> {+ let mut denied = access_state();+ if interactive {+ if let Some(code) = *denied {+ return Err(CredentialError {+ code,+ message: "Credential access is paused; retry explicitly from Settings",+ });+ }+ }+ #[cfg(all(target_os = "macos", not(feature = "native-test")))]+ let _interaction = if !interactive {+ Some(+ security_framework::os::macos::keychain::SecKeychain::disable_user_interaction()+ .map_err(|_| public_error(BackendError::Unavailable))?,+ )+ } else {+ None+ };+ let result = operation();+ if interactive+ && result.as_ref().is_err_and(|error| {+ matches!(+ error.code,+ CredentialErrorCode::Locked+ | CredentialErrorCode::Unavailable+ | CredentialErrorCode::Failed+ )+ })+ {+ *denied = result.as_ref().err().map(|error| error.code);+ }+ result+}+fn validate_segment(value: &str) -> bool {!value.is_empty()&& value.len() <= MAX_SEGMENT_LENGTH@@ -175,16 +290,35 @@ fn remove_with(backend.remove(&account).map_err(public_error)}+#[tauri::command]+pub async fn credential_access_paused() -> Result<bool, CredentialError> {+ tauri::async_runtime::spawn_blocking(|| Ok(access_state().is_some()))+ .await+ .map_err(|_| public_error(BackendError::Failed))?+}++#[tauri::command]+pub async fn credential_retry_access() -> Result<(), CredentialError> {+ tauri::async_runtime::spawn_blocking(|| {+ reset_access_state();+ Ok(())+ })+ .await+ .map_err(|_| public_error(BackendError::Failed))?+}+#[tauri::command]pub async fn credential_store_availability() -> Result<CredentialStoreAvailability, CredentialError>{tauri::async_runtime::spawn_blocking(|| {- match NativeCredentialBackend.read(AVAILABILITY_ACCOUNT) {- Ok(_) => Ok(CredentialStoreAvailability::Available),- Err(BackendError::Locked) => Ok(CredentialStoreAvailability::Locked),- Err(BackendError::Unavailable) => Ok(CredentialStoreAvailability::Unavailable),- Err(error) => Err(public_error(error)),- }+ credential_operation(false, || {+ match NativeCredentialBackend.exists(AVAILABILITY_ACCOUNT) {+ Ok(_) => Ok(CredentialStoreAvailability::Available),+ Err(BackendError::Locked) => Ok(CredentialStoreAvailability::Locked),+ Err(BackendError::Unavailable) => Ok(CredentialStoreAvailability::Unavailable),+ Err(error) => Err(public_error(error)),+ }+ })}).await.map_err(|_| public_error(BackendError::Failed))?@@ -195,9 +329,14 @@ pub async fn credential_status(reference: CredentialRef,) -> Result<CredentialStatus, CredentialError> {tauri::async_runtime::spawn_blocking(move || {- match read_with(&NativeCredentialBackend, &reference) {- Ok(Some(_)) => Ok(CredentialStatus::Configured),- Ok(None) => Ok(CredentialStatus::Missing),+ match credential_operation(false, || {+ let account = account_for(&reference)?;+ NativeCredentialBackend+ .exists(&account)+ .map_err(public_error)+ }) {+ Ok(true) => Ok(CredentialStatus::Configured),+ Ok(false) => Ok(CredentialStatus::Missing),Err(CredentialError {code: CredentialErrorCode::Locked,..@@ -213,30 +352,49 @@ pub async fn credential_status(.map_err(|_| public_error(BackendError::Failed))?}+async fn interactive_operation<T: Send + 'static>(+ app: tauri::AppHandle,+ operation: impl FnOnce() -> Result<T, CredentialError> + Send + 'static,+) -> Result<T, CredentialError> {+ let result =+ tauri::async_runtime::spawn_blocking(move || credential_operation(true, operation))+ .await+ .map_err(|_| public_error(BackendError::Failed))?;+ if let Err(error) = app.emit("credential-access-changed", ()) {+ eprintln!("Could not notify credential access change: {error}");+ }+ result+}+#[tauri::command]-pub async fn credential_read(reference: CredentialRef) -> Result<Option<String>, CredentialError> {- tauri::async_runtime::spawn_blocking(move || read_with(&NativeCredentialBackend, &reference))- .await- .map_err(|_| public_error(BackendError::Failed))?+pub async fn credential_read(+ app: tauri::AppHandle,+ reference: CredentialRef,+) -> Result<Option<String>, CredentialError> {+ interactive_operation(app, move || read_with(&NativeCredentialBackend, &reference)).await}#[tauri::command]pub async fn credential_write(+ app: tauri::AppHandle,reference: CredentialRef,value: String,) -> Result<(), CredentialError> {- tauri::async_runtime::spawn_blocking(move || {+ interactive_operation(app, move || {write_with(&NativeCredentialBackend, &reference, &value)}).await- .map_err(|_| public_error(BackendError::Failed))?}#[tauri::command]-pub async fn credential_remove(reference: CredentialRef) -> Result<(), CredentialError> {- tauri::async_runtime::spawn_blocking(move || remove_with(&NativeCredentialBackend, &reference))- .await- .map_err(|_| public_error(BackendError::Failed))?+pub async fn credential_remove(+ app: tauri::AppHandle,+ reference: CredentialRef,+) -> Result<(), CredentialError> {+ interactive_operation(app, move || {+ remove_with(&NativeCredentialBackend, &reference)+ })+ .await}#[cfg(test)]@@ -273,6 +431,87 @@ mod tests {}}+ fn reset_access() {+ reset_access_state();+ }++ static ACCESS_TEST_LOCK: Mutex<()> = Mutex::new(());++ #[test]+ fn backend_panic_pauses_access_and_explicit_retry_recovers() {+ let _guard = ACCESS_TEST_LOCK.lock().unwrap();+ reset_access();+ let panic = std::panic::catch_unwind(|| {+ let _: Result<(), CredentialError> =+ credential_operation(true, || panic!("test backend panic"));+ });+ assert!(panic.is_err());+ assert!(CREDENTIAL_ACCESS.is_poisoned());+ assert!(access_state().is_some());+ assert!(!CREDENTIAL_ACCESS.is_poisoned());+ let called = std::cell::Cell::new(false);+ assert!(credential_operation(true, || {+ called.set(true);+ Ok(())+ })+ .is_err());+ assert!(!called.get());+ assert!(credential_operation(false, || Ok(())).is_ok());+ reset_access_state();+ assert!(credential_operation(true, || Ok(())).is_ok());+ }++ #[test]+ fn concurrent_calls_do_not_repeat_an_interactive_failure() {+ let _guard = ACCESS_TEST_LOCK.lock().unwrap();+ reset_access();+ let calls = std::sync::atomic::AtomicUsize::new(0);+ std::thread::scope(|scope| {+ for _ in 0..8 {+ scope.spawn(|| {+ let _: Result<(), CredentialError> = credential_operation(true, || {+ calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ Err(public_error(BackendError::Locked))+ });+ });+ }+ });+ assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);+ assert!(credential_operation(false, || Ok(())).is_ok());+ reset_access();+ }++ #[test]+ fn denied_access_blocks_queued_operations_until_explicit_retry() {+ let _guard = ACCESS_TEST_LOCK.lock().unwrap();+ reset_access();+ let failure: Result<(), CredentialError> =+ credential_operation(true, || Err(public_error(BackendError::Locked)));+ assert!(failure.is_err());+ let called = std::cell::Cell::new(false);+ let blocked = credential_operation(true, || {+ called.set(true);+ Ok(())+ });+ assert!(blocked.is_err());+ assert!(!called.get());+ reset_access();+ assert!(credential_operation(true, || Ok(())).is_ok());+ }++ #[cfg(feature = "native-test")]+ #[test]+ fn native_test_credentials_are_process_memory_only() {+ let backend = NativeCredentialBackend;+ backend.write("test-memory", "disposable").unwrap();+ assert_eq!(+ backend.read("test-memory").unwrap(),+ Some("disposable".to_owned())+ );+ backend.remove("test-memory").unwrap();+ assert_eq!(backend.read("test-memory").unwrap(), None);+ }+fn reference() -> CredentialRef {CredentialRef {integration_id: "openai-compatible".to_owned(),diff --git a/desktop/src/lib.rs b/desktop/src/lib.rsindex fadb1d037..e65b2304a 100644--- a/desktop/src/lib.rs+++ b/desktop/src/lib.rs@@ -8,7 +8,7 @@ mod menu_events;mod window;use credentials::{- credential_read, credential_remove, credential_status, credential_store_availability,+ credential_access_paused, credential_retry_access, credential_read, credential_remove, credential_status, credential_store_availability,credential_write,};use fig_container::build_fig_file;@@ -142,6 +142,8 @@ pub fn run() {.invoke_handler(tauri::generate_handler![build_fig_file,credential_read,+ credential_access_paused,+ credential_retry_access,credential_remove,credential_status,credential_store_availability,diff --git a/desktop/tauri.native-test.conf.json b/desktop/tauri.native-test.conf.jsonindex 5a55f28a1..d18fe643e 100644--- a/desktop/tauri.native-test.conf.json+++ b/desktop/tauri.native-test.conf.json@@ -1,5 +1,6 @@{"$schema": "https://schema.tauri.app/config/2",+ "identifier": "net.dannote.open-pencil.native-test","build": {"beforeBuildCommand": "bun run generate:tauri-menu && vite build --mode native-test"},@@ -7,6 +8,7 @@"withGlobalTauri": true,"windows": [{+ "incognito": true,"title": "OpenPencil Native Test","width": 1280,"height": 800,diff --git a/packages/vue/src/i18n/locales/de/credentials.json b/packages/vue/src/i18n/locales/de/credentials.jsonindex 6ab54eb9e..00233ac2b 100644--- a/packages/vue/src/i18n/locales/de/credentials.json+++ b/packages/vue/src/i18n/locales/de/credentials.json@@ -5,5 +5,13 @@"backendMemory": "nur diese Sitzung","remember": "Zugangsdaten in diesem Browser speichern","savedReplace": "Schlüssel gespeichert — eingeben, um ihn zu ersetzen",- "getAPIKey": "API-Schlüssel abrufen →"+ "getAPIKey": "API-Schlüssel abrufen →",+ "retryAccess": "Zugriff erneut versuchen",+ "retryFailed": "Der Zugriff konnte nicht zurückgesetzt werden. Versuche es erneut.",+ "settingsTitle": "Gespeicherte Passwörter und API-Schlüssel",+ "accessPaused": "Der Zugriff auf gespeicherte Zugangsdaten ist pausiert.",+ "rememberDevice": "API-Schlüssel auf diesem Gerät speichern",+ "sessionOnly": "Schlüssel werden nur bis zum Ende dieser Sitzung gespeichert.",+ "checkFailed": "Der Zugriff auf gespeicherte Zugangsdaten konnte nicht geprüft werden.",+ "retryCheck": "Erneut prüfen"}diff --git a/packages/vue/src/i18n/locales/es/credentials.json b/packages/vue/src/i18n/locales/es/credentials.jsonindex 459a2536a..94f692827 100644--- a/packages/vue/src/i18n/locales/es/credentials.json+++ b/packages/vue/src/i18n/locales/es/credentials.json@@ -5,5 +5,13 @@"backendMemory": "solo esta sesión","remember": "Recordar credenciales en este navegador","savedReplace": "Clave guardada - introduce una nueva para reemplazarla",- "getAPIKey": "Obtener clave API →"+ "getAPIKey": "Obtener clave API →",+ "retryAccess": "Reintentar acceso",+ "retryFailed": "No se pudo restablecer el acceso. Inténtalo de nuevo.",+ "settingsTitle": "Contraseñas y claves API guardadas",+ "accessPaused": "El acceso a las credenciales guardadas está en pausa.",+ "rememberDevice": "Recordar claves API en este dispositivo",+ "sessionOnly": "Las claves se conservan solo hasta que cierres esta sesión.",+ "checkFailed": "No se pudo comprobar el acceso a las credenciales guardadas.",+ "retryCheck": "Volver a comprobar"}diff --git a/packages/vue/src/i18n/locales/fr/credentials.json b/packages/vue/src/i18n/locales/fr/credentials.jsonindex 53044a9d8..efe579576 100644--- a/packages/vue/src/i18n/locales/fr/credentials.json+++ b/packages/vue/src/i18n/locales/fr/credentials.json@@ -5,5 +5,13 @@"backendMemory": "cette session uniquement","remember": "Mémoriser les identifiants dans ce navigateur","savedReplace": "Clé enregistrée — saisissez-en une pour la remplacer",- "getAPIKey": "Obtenir une clé API →"+ "getAPIKey": "Obtenir une clé API →",+ "retryAccess": "Réessayer l’accès",+ "retryFailed": "Impossible de réinitialiser l’accès. Réessayez.",+ "settingsTitle": "Mots de passe et clés API enregistrés",+ "accessPaused": "L’accès aux identifiants enregistrés est suspendu.",+ "rememberDevice": "Mémoriser les clés API sur cet appareil",+ "sessionOnly": "Les clés sont conservées uniquement jusqu’à la fermeture de cette session.",+ "checkFailed": "Impossible de vérifier l’accès aux identifiants enregistrés.",+ "retryCheck": "Revérifier"}diff --git a/packages/vue/src/i18n/locales/it/credentials.json b/packages/vue/src/i18n/locales/it/credentials.jsonindex 5f48b4c82..af91374d6 100644--- a/packages/vue/src/i18n/locales/it/credentials.json+++ b/packages/vue/src/i18n/locales/it/credentials.json@@ -5,5 +5,13 @@"backendMemory": "solo questa sessione","remember": "Ricorda le credenziali in questo browser","savedReplace": "Chiave salvata — inseriscine una per sostituirla",- "getAPIKey": "Ottieni chiave API →"+ "getAPIKey": "Ottieni chiave API →",+ "retryAccess": "Riprova l’accesso",+ "retryFailed": "Impossibile ripristinare l’accesso. Riprova.",+ "settingsTitle": "Password e chiavi API salvate",+ "accessPaused": "L’accesso alle credenziali salvate è sospeso.",+ "rememberDevice": "Ricorda le chiavi API su questo dispositivo",+ "sessionOnly": "Le chiavi vengono conservate solo fino alla chiusura di questa sessione.",+ "checkFailed": "Impossibile verificare l’accesso alle credenziali salvate.",+ "retryCheck": "Riprova la verifica"}diff --git a/packages/vue/src/i18n/locales/ja/credentials.json b/packages/vue/src/i18n/locales/ja/credentials.jsonindex 50265c772..c268b6ef6 100644--- a/packages/vue/src/i18n/locales/ja/credentials.json+++ b/packages/vue/src/i18n/locales/ja/credentials.json@@ -5,5 +5,13 @@"backendMemory": "このセッションのみ","remember": "このブラウザに認証情報を保存","savedReplace": "キーが保存されました - 上書きするには新しいキーを入力してください",- "getAPIKey": "APIキーを取得 →"+ "getAPIKey": "APIキーを取得 →",+ "retryAccess": "アクセスを再試行",+ "retryFailed": "アクセスをリセットできませんでした。もう一度お試しください。",+ "settingsTitle": "保存済みパスワードとAPIキー",+ "accessPaused": "保存済み認証情報へのアクセスは一時停止中です。",+ "rememberDevice": "このデバイスにAPIキーを保存",+ "sessionOnly": "キーはこのセッションを閉じるまでのみ保持されます。",+ "checkFailed": "保存済み認証情報へのアクセスを確認できませんでした。",+ "retryCheck": "再確認"}diff --git a/packages/vue/src/i18n/locales/pl/credentials.json b/packages/vue/src/i18n/locales/pl/credentials.jsonindex 166528d78..6170a3706 100644--- a/packages/vue/src/i18n/locales/pl/credentials.json+++ b/packages/vue/src/i18n/locales/pl/credentials.json@@ -5,5 +5,13 @@"backendMemory": "tylko ta sesja","remember": "Zapamiętaj dane logowania w tej przeglądarce","savedReplace": "Klucz zapisany — wpisz nowy, aby go zastąpić",- "getAPIKey": "Pobierz klucz API →"+ "getAPIKey": "Pobierz klucz API →",+ "retryAccess": "Ponów dostęp",+ "retryFailed": "Nie udało się zresetować dostępu. Spróbuj ponownie.",+ "settingsTitle": "Zapisane hasła i klucze API",+ "accessPaused": "Dostęp do zapisanych danych logowania jest wstrzymany.",+ "rememberDevice": "Zapamiętaj klucze API na tym urządzeniu",+ "sessionOnly": "Klucze są przechowywane tylko do zamknięcia tej sesji.",+ "checkFailed": "Nie udało się sprawdzić dostępu do zapisanych danych logowania.",+ "retryCheck": "Sprawdź ponownie"}diff --git a/packages/vue/src/i18n/locales/ru/credentials.json b/packages/vue/src/i18n/locales/ru/credentials.jsonindex d8b11234d..655fa3e4b 100644--- a/packages/vue/src/i18n/locales/ru/credentials.json+++ b/packages/vue/src/i18n/locales/ru/credentials.json@@ -5,5 +5,13 @@"backendMemory": "только этот сеанс","remember": "Запомнить учётные данные в этом браузере","savedReplace": "Ключ сохранён — введите новый, чтобы заменить",- "getAPIKey": "Получить API-ключ →"+ "getAPIKey": "Получить API-ключ →",+ "retryAccess": "Повторить доступ",+ "retryFailed": "Не удалось сбросить блокировку доступа. Повторите попытку.",+ "settingsTitle": "Сохранённые пароли и API-ключи",+ "accessPaused": "Доступ к сохранённым учётным данным приостановлен.",+ "rememberDevice": "Запоминать API-ключи на этом устройстве",+ "sessionOnly": "Ключи хранятся только до закрытия этой сессии.",+ "checkFailed": "Не удалось проверить доступ к сохранённым учётным данным.",+ "retryCheck": "Повторить проверку"}diff --git a/packages/vue/src/i18n/locales/zh-cn/credentials.json b/packages/vue/src/i18n/locales/zh-cn/credentials.jsonindex cceaa7635..9ed3e336c 100644--- a/packages/vue/src/i18n/locales/zh-cn/credentials.json+++ b/packages/vue/src/i18n/locales/zh-cn/credentials.json@@ -5,5 +5,13 @@"backendMemory": "仅限本次会话","remember": "在此浏览器中记住凭据","savedReplace": "密钥已保存,输入新密钥以替换",- "getAPIKey": "获取 API 密钥 →"+ "getAPIKey": "获取 API 密钥 →",+ "retryAccess": "重试访问",+ "retryFailed": "无法重置凭据访问。请重试。",+ "settingsTitle": "已保存的密码和 API 密钥",+ "accessPaused": "对已保存凭据的访问已暂停。",+ "rememberDevice": "在此设备上记住 API 密钥",+ "sessionOnly": "密钥仅保留到此会话关闭。",+ "checkFailed": "无法检查对已保存凭据的访问。",+ "retryCheck": "重新检查"}diff --git a/packages/vue/src/i18n/messages/credentials.ts b/packages/vue/src/i18n/messages/credentials.tsindex ba27dbc70..983836ee6 100644--- a/packages/vue/src/i18n/messages/credentials.ts+++ b/packages/vue/src/i18n/messages/credentials.ts@@ -3,6 +3,14 @@ import { params } from '@nanostores/i18n'import { i18n } from '#vue/i18n/create'export const credentialsMessageDefaults = {+ checkFailed: 'Could not check access to saved credentials.',+ retryCheck: 'Retry check',+ retryAccess: 'Retry access',+ settingsTitle: 'Saved passwords and API keys',+ accessPaused: 'Access to saved credentials is paused.',+ rememberDevice: 'Remember API keys on this device',+ sessionOnly: 'Keys are kept only until you close this session.',+ retryFailed: 'Could not reset credential access. Try again.',storage: params('Credentials: {backend}'),backendNative: 'system credential store',backendBrowser: 'encrypted browser storage',diff --git a/src/app/settings/credentials/access-state.ts b/src/app/settings/credentials/access-state.tsnew file mode 100644index 000000000..4378eab48--- /dev/null+++ b/src/app/settings/credentials/access-state.ts@@ -0,0 +1,8 @@+import { ref } from 'vue'++/** Invalidate the native access-state query after credential operations settle. */+export const nativeCredentialAccessRevision = ref(0)++export function invalidateNativeCredentialAccess(): void {+ nativeCredentialAccessRevision.value+++}diff --git a/src/app/settings/credentials/native.ts b/src/app/settings/credentials/native.tsindex e3ea832da..9ac36682b 100644--- a/src/app/settings/credentials/native.ts+++ b/src/app/settings/credentials/native.ts@@ -9,6 +9,8 @@ import {type CredentialStoreAvailability} from '@/app/settings/credentials/types'+import { invalidateNativeCredentialAccess } from './access-state'+type NativeCredentialError = {code?: CredentialErrorCodemessage?: string@@ -46,6 +48,10 @@ export class NativeCredentialStore implements CredentialStore {nativeError.code ?? 'failed',nativeError.message ?? 'System credential operation failed')+ } finally {+ if (['credential_read', 'credential_write', 'credential_remove'].includes(command)) {+ invalidateNativeCredentialAccess()+ }}}}diff --git a/src/app/settings/credentials/preferences/access-check.ts b/src/app/settings/credentials/preferences/access-check.tsnew file mode 100644index 000000000..9249f7964--- /dev/null+++ b/src/app/settings/credentials/preferences/access-check.ts@@ -0,0 +1,25 @@+import { ref } from 'vue'++/** Status retries only inspect access; resetting the denial latch is a separate action. */+export function createCredentialAccessCheck(query: () => Promise<boolean>) {+ const paused = ref(false)+ const checkFailed = ref(false)+ let revision = 0+ async function check() {+ const current = ++revision+ try {+ const value = await query()+ if (current !== revision) return+ paused.value = value+ checkFailed.value = false+ } catch {+ if (current !== revision) return+ paused.value = false+ checkFailed.value = true+ }+ }+ function invalidate() {+ revision+++ }+ return { paused, checkFailed, check, invalidate }+}diff --git a/src/app/settings/credentials/preferences/use.ts b/src/app/settings/credentials/preferences/use.tsnew file mode 100644index 000000000..c24b5578d--- /dev/null+++ b/src/app/settings/credentials/preferences/use.ts@@ -0,0 +1,77 @@+import { invoke } from '@tauri-apps/api/core'+import { listen } from '@tauri-apps/api/event'+import { computed, onMounted, onScopeDispose, ref, watch } from 'vue'++import { IS_TAURI } from '@open-pencil/core/constants'++import { nativeCredentialAccessRevision, invalidateNativeCredentialAccess } from '../access-state'+import { browserCredentialsRemembered } from '../app'+import { setRememberCredentials } from '../media'+import { createCredentialAccessCheck } from './access-check'++export function useCredentialSettings() {+ const busy = ref(false)+ const { paused, checkFailed, check, invalidate } = createCredentialAccessCheck(() =>+ invoke<boolean>('credential_access_paused')+ )+ const failed = ref(false)+ let disposed = false+ let unlisten: (() => void) | undefined+ onScopeDispose(() => {+ disposed = true+ invalidate()+ unlisten?.()+ })+ onMounted(async () => {+ if (!IS_TAURI) return+ try {+ const stop = await listen('credential-access-changed', invalidateNativeCredentialAccess)+ if (disposed) stop()+ else {+ unlisten = stop+ invalidateNativeCredentialAccess()+ }+ } catch {+ if (!disposed) failed.value = true+ }+ })+ const remembered = computed({+ get: () => browserCredentialsRemembered.value,+ set: (value) => {+ void setRememberCredentials(value).catch(() => {+ failed.value = true+ })+ }+ })+ watch(+ nativeCredentialAccessRevision,+ async () => {+ if (IS_TAURI) await check()+ },+ { immediate: true }+ )+ async function retryCheck() {+ if (busy.value) return+ busy.value = true+ try {+ await check()+ } finally {+ busy.value = false+ }+ }+ async function retry() {+ if (busy.value) return+ busy.value = true+ failed.value = false+ try {+ await invoke('credential_retry_access')+ paused.value = false+ invalidateNativeCredentialAccess()+ } catch {+ failed.value = true+ } finally {+ busy.value = false+ }+ }+ return { busy, paused, failed, checkFailed, remembered, retry, retryCheck }+}diff --git a/src/components/settings/SettingsDialog.vue b/src/components/settings/SettingsDialog.vueindex a42b8541f..9c2f91560 100644--- a/src/components/settings/SettingsDialog.vue+++ b/src/components/settings/SettingsDialog.vue@@ -1,11 +1,6 @@<script setup lang="ts">import { DialogClose } from 'reka-ui'-import { computed } from 'vue'import { useI18n } from '@open-pencil/vue'-import { IS_TAURI } from '@open-pencil/core/constants'--import { browserCredentialsRemembered, appCredentialServices } from '@/app/settings/credentials/app'-import { setRememberCredentials } from '@/app/settings/credentials/media'import { settingsDialogOpen, settingsDialogSection } from '@/app/settings/dialog'import DiagnosticsSettingsPanel from '@/components/settings/diagnostics/DiagnosticsSettingsPanel.vue'import GeneralSettingsPanel from '@/components/settings/general/GeneralSettingsPanel.vue'@@ -17,30 +12,13 @@ import StockPhotoKeysSection from '@/components/settings/provider/StockPhotoKeysimport UsageSettingsPanel from '@/components/settings/usage/UsageSettingsPanel.vue'import StorageSettingsPanel from '@/components/settings/storage/StorageSettingsPanel.vue'import VectorizeSettingsSection from '@/components/settings/vectorize/VectorizeSettingsSection.vue'-import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'import { AppDialogFooter, AppDialogHeader, AppDialogRoot } from '@/components/ui/dialog'-const { credentials, settings, common } = useI18n()+const { settings, common } = useI18n()function onOpenChange(open: boolean): void {settingsDialogOpen.value = open}-const rememberCredentials = computed({- get: () => browserCredentialsRemembered.value,- set: (remembered: boolean) => {- void setRememberCredentials(remembered)- }-})--const credentialBackendLabel = computed(() => {- void browserCredentialsRemembered.value- if (appCredentialServices.manager.backend === 'native') return credentials.value.backendNative- if (appCredentialServices.manager.backend === 'browser') {- return credentials.value.backendBrowser- }- return credentials.value.backendMemory-})-const navigationClass ='flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs text-muted transition-colors hover:bg-hover hover:text-surface data-[state=active]:bg-hover data-[state=active]:text-surface'</script>@@ -173,23 +151,7 @@ const navigationClass =</div></div>- <AppDialogFooter :ui="{ footer: 'justify-between' }">- <div class="mr-auto flex items-center gap-2">- <AppSwitch- v-if="!IS_TAURI"- v-model="rememberCredentials"- :label="credentials.remember"- data-test-id="settings-remember-credentials"- />- <div>- <p v-if="!IS_TAURI" class="text-[10px] text-surface">- {{ credentials.remember }}- </p>- <p class="text-[10px] text-muted" data-test-id="settings-credential-backend">- {{ credentials.storage({ backend: credentialBackendLabel }) }}- </p>- </div>- </div>+ <AppDialogFooter><DialogClose as-child><buttontype="button"diff --git a/src/components/settings/credentials/CredentialSettingsSection.vue b/src/components/settings/credentials/CredentialSettingsSection.vuenew file mode 100644index 000000000..6b6c0b9af--- /dev/null+++ b/src/components/settings/credentials/CredentialSettingsSection.vue@@ -0,0 +1,44 @@+<script setup lang="ts">+import { useI18n } from '@open-pencil/vue'+import { IS_TAURI } from '@open-pencil/core/constants'+import { useCredentialSettings } from '@/app/settings/credentials/preferences/use'+import AppButton from '@/components/ui/button/AppButton.vue'+import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'+import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'+import SettingsSectionHeader from '@/components/settings/layout/SettingsSectionHeader.vue'++const { credentials } = useI18n()+const { busy, paused, failed, checkFailed, remembered, retry, retryCheck } = useCredentialSettings()+</script>++<template>+ <template v-if="!IS_TAURI || paused || failed || checkFailed">+ <SettingsSectionHeader>{{ credentials.settingsTitle }}</SettingsSectionHeader>+ <SettingsGroup>+ <label v-if="!IS_TAURI" class="flex items-center justify-between gap-4 px-3 py-2.5">+ <span>+ <span class="block text-xs text-surface">{{ credentials.rememberDevice }}</span>+ <span v-if="!remembered" class="block text-[11px] text-muted">{{+ credentials.sessionOnly+ }}</span>+ </span>+ <AppSwitch v-model="remembered" :label="credentials.rememberDevice" />+ </label>+ <div v-if="checkFailed" class="flex items-center justify-between gap-4 px-3 py-2.5">+ <span role="status" class="text-xs text-surface">{{ credentials.checkFailed }}</span>+ <AppButton size="xs" variant="ghost" :disabled="busy" @click="retryCheck">{{+ credentials.retryCheck+ }}</AppButton>+ </div>+ <div v-else-if="paused" class="flex items-center justify-between gap-4 px-3 py-2.5">+ <span class="text-xs text-surface">{{ credentials.accessPaused }}</span>+ <AppButton size="xs" variant="ghost" :disabled="busy" @click="retry">{{+ credentials.retryAccess+ }}</AppButton>+ </div>+ <p v-if="failed" role="status" class="px-3 py-2 text-xs text-muted">+ {{ credentials.retryFailed }}+ </p>+ </SettingsGroup>+ </template>+</template>diff --git a/src/components/settings/general/GeneralSettingsPanel.vue b/src/components/settings/general/GeneralSettingsPanel.vueindex 600437e28..c108ee8ee 100644--- a/src/components/settings/general/GeneralSettingsPanel.vue+++ b/src/components/settings/general/GeneralSettingsPanel.vue@@ -7,6 +7,7 @@ import { setSnappingPreference } from '@/app/settings/preferences/apply'import { appPreferences } from '@/app/settings/preferences/store'import AppSelect from '@/components/ui/select/AppSelect.vue'import AppSwitch from '@/components/ui/toggle/AppSwitch.vue'+import CredentialSettingsSection from '@/components/settings/credentials/CredentialSettingsSection.vue'import RenderingSettingsSection from '@/components/settings/general/RenderingSettingsSection.vue'import SettingsGroup from '@/components/settings/layout/SettingsGroup.vue'import SettingsSectionHeader from '@/components/settings/layout/SettingsSectionHeader.vue'@@ -130,6 +131,7 @@ const snapToPixelGrid = computed({<p class="text-[10px] text-muted">{{ settings.temporaryDisableSnappingHint }}</p>+ <CredentialSettingsSection /><RenderingSettingsSection /></section></template>diff --git a/tests/e2e/native/credentials.spec.ts b/tests/e2e/native/credentials.spec.tsnew file mode 100644index 000000000..56c278a88--- /dev/null+++ b/tests/e2e/native/credentials.spec.ts@@ -0,0 +1,62 @@+import { strict as assert } from 'node:assert'++import { invokeNative } from '#tests/helpers/tauri/invoke'++const reference = { integrationId: 'native-test', profileId: 'isolation', field: 'api-key' }++describe('native test credential isolation', () => {+ it('uses disposable memory credentials and exposes explicit retry without Keychain access', async function () {+ this.timeout(180_000)+ await browser.waitUntil(+ async () => browser.execute(() => Boolean(window.openPencil?.getStore?.())),+ { timeout: 30_000 }+ )+ const previousLaunch = await browser.execute(() => {+ // Probe the WebView itself, not an adapter, to verify profile isolation.+ // oxlint-disable-next-line open-pencil/no-direct-storage-access+ const previous = localStorage.getItem('native-test-launch-marker')+ // oxlint-disable-next-line open-pencil/no-direct-storage-access+ localStorage.setItem('native-test-launch-marker', 'present')+ return previous+ })+ assert.equal(previousLaunch, null)+ assert.equal(await $('[role="alertdialog"]').isExisting(), false)+ await invokeNative('credential_retry_access')+ assert.equal(await invokeNative('credential_status', { reference }), 'missing')+ await invokeNative('credential_write', { reference, value: 'disposable-test-value' })+ assert.equal(await invokeNative('credential_status', { reference }), 'configured')+ await invokeNative('credential_remove', { reference })+ assert.equal(await invokeNative('credential_status', { reference }), 'missing')+ })++ it('hides credential controls when native access is healthy', async () => {+ await browser.keys([process.platform === 'darwin' ? 'Meta' : 'Control', ','])+ const section = await $('[data-test-id="settings-general-panel"]')+ await section.waitForDisplayed()+ assert.doesNotMatch(+ await section.getText(),+ /system credential store|Saved passwords and API keys/+ )+ assert.equal(await $('button=Retry access').isExisting(), false)+ })++ it('shows a paused section after denial and hides it after retry', async function () {+ this.timeout(180_000)+ await assert.rejects(+ invokeNative('credential_write', { reference, value: 'open-pencil-native-test-denied' })+ )+ assert.equal(await $('[data-test-id="settings-general-panel"]').isDisplayed(), true)+ const retry = await $('button=Retry access')+ await retry.waitForExist()+ await retry.scrollIntoView()+ await browser.execute(() => {+ const panel = document.querySelector('[data-test-id="settings-general-panel"]')+ if (panel?.parentElement) panel.parentElement.scrollTop = panel.parentElement.scrollHeight+ })+ await retry.click()+ await browser.waitUntil(async () => !(await $('button=Retry access').isExisting()))+ assert.equal(await invokeNative('credential_access_paused'), false)+ await invokeNative('credential_write', { reference, value: 'disposable' })+ await invokeNative('credential_remove', { reference })+ })+})diff --git a/tests/e2e/native/settings.spec.ts b/tests/e2e/native/settings.spec.tsindex 2b4580986..2bdf4678f 100644--- a/tests/e2e/native/settings.spec.ts+++ b/tests/e2e/native/settings.spec.ts@@ -1,5 +1,7 @@import { strict as assert } from 'node:assert'+import { invokeNative } from '#tests/helpers/tauri/invoke'+function settingsOpen(): Promise<boolean> {return browser.execute(() =>Boolean(document.querySelector('[data-test-id="app-settings-dialog"]'))@@ -33,10 +35,7 @@ describe('native preferences', () => {async () => browser.execute(() => Boolean(window.openPencil?.getStore?.())),{ timeout: 30_000, timeoutMsg: 'OpenPencil editor did not initialize' })- const initial = await browser.execute(async () => {- const { invoke } = await import('@tauri-apps/api/core')- return invoke<boolean>('native_menu_checked', { id: 'snap-objects' })- })+ const initial = await invokeNative<boolean>('native_menu_checked', { id: 'snap-objects' })assert.equal(initial, true)await browser.executeAsync((done) => {@@ -47,10 +46,7 @@ describe('native preferences', () => {setTimeout(done, 200)})})- const updated = await browser.execute(async () => {- const { invoke } = await import('@tauri-apps/api/core')- return invoke<boolean>('native_menu_checked', { id: 'snap-objects' })- })+ const updated = await invokeNative<boolean>('native_menu_checked', { id: 'snap-objects' })assert.equal(updated, false)})})diff --git a/tests/e2e/settings/credentials.spec.ts b/tests/e2e/settings/credentials.spec.tsindex 5d997e81c..8205e41c1 100644--- a/tests/e2e/settings/credentials.spec.ts+++ b/tests/e2e/settings/credentials.spec.ts@@ -193,3 +193,19 @@ test('remembered browser credentials survive reload and clear centrally', asyncawait page.getByRole('tab', { name: 'AI' }).click()await expect(page.getByTestId('provider-setup-open-settings')).toBeVisible()})++test('browser credential preferences live in General, not the footer', async ({ page }) => {+ await page.goto('/')+ await page.keyboard.press('ControlOrMeta+,')+ const panel = page.getByTestId('settings-general-panel')+ const remember = panel.getByRole('switch', { name: 'Remember API keys on this device' })+ await expect(remember).toBeVisible()+ if ((await remember.getAttribute('aria-checked')) === 'true') await remember.click()+ await expect(remember).toHaveAttribute('aria-checked', 'false')+ await expect(panel.getByText('Keys are kept only until you close this session.')).toBeVisible()+ await remember.click()+ await expect(remember).toHaveAttribute('aria-checked', 'true')+ await expect(panel.getByText('Keys are kept only until you close this session.')).toBeHidden()+ await expect(page.getByText('system credential store', { exact: false })).toHaveCount(0)+ await page.getByTestId('app-settings-done').click()+})diff --git a/tests/engine/app/settings/credentials/access-check.test.ts b/tests/engine/app/settings/credentials/access-check.test.tsnew file mode 100644index 000000000..c2511e62f--- /dev/null+++ b/tests/engine/app/settings/credentials/access-check.test.ts@@ -0,0 +1,38 @@+import { expect, test } from 'bun:test'++import { createCredentialAccessCheck } from '@/app/settings/credentials/preferences/access-check'++test('failed queries do not claim paused access and can be retried', async () => {+ let fails = true+ const state = createCredentialAccessCheck(async () => {+ if (fails) throw new Error('IPC unavailable')+ return false+ })+ await state.check()+ expect(state.checkFailed.value).toBe(true)+ expect(state.paused.value).toBe(false)+ fails = false+ await state.check()+ expect(state.checkFailed.value).toBe(false)+ expect(state.paused.value).toBe(false)+})++test('outdated or disposed queries cannot overwrite the latest state', async () => {+ const pending = Promise.withResolvers<boolean>()+ let calls = 0+ const state = createCredentialAccessCheck(() =>+ ++calls === 1 ? pending.promise : Promise.resolve(true)+ )+ const old = state.check()+ await state.check()+ pending.resolve(false)+ await old+ expect(state.paused.value).toBe(true)+ const next = Promise.withResolvers<boolean>()+ const disposed = createCredentialAccessCheck(() => next.promise)+ const checking = disposed.check()+ disposed.invalidate()+ next.resolve(true)+ await checking+ expect(disposed.paused.value).toBe(false)+})diff --git a/tests/helpers/tauri/invoke.ts b/tests/helpers/tauri/invoke.tsnew file mode 100644index 000000000..2150c9830--- /dev/null+++ b/tests/helpers/tauri/invoke.ts@@ -0,0 +1,16 @@+import type { invoke } from '@tauri-apps/api/core'++type InvokeArguments = Parameters<typeof invoke>[1]++/** Invoke inside the built WebView; package imports cannot execute in serialized callbacks. */+export async function invokeNative<T>(command: string, args?: InvokeArguments): Promise<T> {+ return browser.execute(+ async (command, args) => {+ const core = window.__TAURI__?.core+ if (!core) throw new Error('Native test requires app.withGlobalTauri')+ return core.invoke<T>(command, args)+ },+ command,+ args+ )+}diff --git a/tests/helpers/tauri/native-global.d.ts b/tests/helpers/tauri/native-global.d.tsindex f2df9efcd..c8e9bfc95 100644--- a/tests/helpers/tauri/native-global.d.ts+++ b/tests/helpers/tauri/native-global.d.ts@@ -1,3 +1,5 @@+import type * as TauriAPI from '@tauri-apps/api'+export {}type NativeTestNode = {@@ -33,6 +35,7 @@ type NativeTestStore = {declare global {interface Window {+ __TAURI__?: Pick<typeof TauriAPI, 'core'>openPencil?: {getStore?: () => NativeTestStore}diff --git a/tools/i18n/mixed-script-baseline.txt b/tools/i18n/mixed-script-baseline.txtindex 6f65dde52..4e2e76341 100644--- a/tools/i18n/mixed-script-baseline.txt+++ b/tools/i18n/mixed-script-baseline.txt@@ -219,3 +219,8 @@ zh-cn:updates.upToDateja:ai.copyACPLogzh-cn:ai.copyACPLog++ja:credentials.settingsTitle+ja:credentials.rememberDevice+zh-cn:credentials.settingsTitle+zh-cn:credentials.rememberDevice