diff --git a/docs/i18n-inventory.md b/docs/i18n-inventory.md index 929f8bed..2f4c2e09 100644 --- a/docs/i18n-inventory.md +++ b/docs/i18n-inventory.md @@ -1,6 +1,6 @@ # i18n inventory (egdev6/quorb#66) -Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `8d235467a772bea750648b7aa3b4f49a2d4000da` and `src-tauri/src/` = `2d235a658b97631fd394946c7293300ff786d711`. +Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `5e4e9abe1b08e5441dc3f5713f61994638892dba` and `src-tauri/src/` = `c96f1ca56c20ecbac9804effe4fc394a29c9c331`. Any commit whose `git rev-parse :src` and `:src-tauri/src` match has these exact texts. Do not edit by hand: regenerate, or verify with `node scripts/i18n-inventory.mjs --check`. @@ -19,8 +19,8 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a | Area | Distinct texts | Sites | |---|---:|---:| | React (`src/`) | 1120 | 1219 | -| Rust (`src-tauri/src/`) | 581 | 727 | -| Total | 1662 | 1946 | +| Rust (`src-tauri/src/`) | 601 | 739 | +| Total | 1682 | 1958 | ## src-tauri/src/channel.rs @@ -138,19 +138,51 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Ajustes… - Cancel - Cancelar +- Cannot read {path}: {error} +- Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login». +- Codex is authenticated with an API key, not with your ChatGPT account. Run “codex login”. +- Credenciales sin «claudeAiOauth» (¿login con API key?) +- Credentials without “claudeAiOauth” (signed in with an API key?) +- Cursor is not signed in. +- Cursor no tiene sesión iniciada. +- Cursor session expired. Open Cursor to renew it. +- Cursor session not found at {path}. Sign in to Cursor. +- Ejecuta «codex login». +- Ejecuta «grok login». - El consumo observado en {provider} ({meter}) ha bajado por debajo del umbral de aviso configurado en Quorb.\n\nConsumo actual: {percent}. - El consumo observado en {provider} ha alcanzado el {percent} del límite.\n\nSe ha alcanzado el umbral de aviso configurado en Quorb. - El consumo observado en {provider} ha alcanzado el {percent} del {meter}.\n\nSe ha alcanzado el umbral de aviso configurado en Quorb. - El consumo observado en {provider} ha bajado por debajo del umbral de aviso configurado en Quorb.\n\nConsumo actual: {percent}. +- Gemini session rejected. Open Gemini CLI to renew it. +- Google did not renew the Gemini CLI session. Open it and sign in again. +- Google no ha renovado la sesión de Gemini CLI. Ábrelo e inicia sesión de nuevo. +- Inicia sesión en Claude Code. +- Inicia sesión en Gemini CLI con tu cuenta de Google. - Instalar - Instalar Codex - Install - Install Codex +- Invalid JSON in {path}: {error} +- JSON inválido en {path}: {error} +- Keychain authorization did not complete in time. Grant access to “Claude Code-credentials” and wait for the next refresh. +- La autorización del Keychain no se completó a tiempo. Concede el acceso a «Claude Code-credentials» y espera al próximo refresco. +- La sesión de Gemini CLI ha caducado. Ábrelo para renovarla. +- La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo. - Mostrar / ocultar widget +- No credentials found in {distro}: {path} +- No credentials found in {path} +- No credentials found in: {list} +- No encuentro credenciales en {distro}: {path} +- No encuentro credenciales en {path} +- No encuentro credenciales en: {list} +- No encuentro la sesión de Cursor en {path}. Inicia sesión en Cursor. +- No existe {path} +- No puedo leer {path}: {error} - Observed usage in {provider} ({meter}) has dropped below the alert threshold configured in Quorb.\n\nCurrent usage: {percent}. - Observed usage in {provider} has dropped below the alert threshold configured in Quorb.\n\nCurrent usage: {percent}. - Observed usage in {provider} has reached {percent} of the limit.\n\nThe alert threshold configured in Quorb has been reached. - Observed usage in {provider} has reached {percent} of the {meter}.\n\nThe alert threshold configured in Quorb has been reached. +- Path not found: {path} - Quit - Quorb · {provider}: consumo al {percent} - Quorb · {provider}: consumo por debajo del umbral de aviso @@ -161,12 +193,30 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Quorb: prueba explícita de email (sin datos de consumo). - Quorb: usage alert - Refresh now +- Run “codex login”. +- Run “grok login”. - Salir - Se instalará el CLI oficial de Codex solo para Quorb.\n\n• Paquete: @openai/codex@0.162.1 (versión fijada)\n• Registro canónico de npm: https://registry.npmjs.org/\n• Carpeta gestionada: ~/.quorb/tools/codex-0.162.1 (fuera del registro global)\n• Requisito: Node.js 22 o superior ya instalado (no se instala Node ni se pide elevación)\n• Se descargará el binario nativo y se verificará antes de activarlo\n\nNo se modifica el registro global de npm, no se cambia el PATH del sistema ni de otros programas, y no se inicia sesión ni se guardan credenciales: el acceso con tu cuenta de ChatGPT lo haces después con «Iniciar sesión».\n\n¿Instalar Codex ahora? +- Sesión caducada. Ejecuta «codex» para renovarla. +- Sesión caducada. Ejecuta «grok login» para renovarla. +- Sesión de Cursor caducada. Abre Cursor para renovarla. +- Sesión de Gemini rechazada. Abre Gemini CLI para renovarla. +- Session expired. Run “codex” to renew it. +- Session expired. Run “grok login” to renew it. - Settings - Settings… - Show / hide widget +- Sign in to Claude Code. +- Sign in to Gemini CLI with your Google account. +- The Gemini CLI session has expired. Open it to renew it. - The official Codex CLI will be installed only for Quorb.\n\n• Package: @openai/codex@0.162.1 (pinned version)\n• Canonical npm registry: https://registry.npmjs.org/\n• Managed folder: ~/.quorb/tools/codex-0.162.1 (outside the global registry)\n• Requirement: Node.js 22 or newer already installed (Node is not installed and no elevation is requested)\n• The native binary will be downloaded and verified before being activated\n\nThe global npm registry is not modified, the system PATH is not changed for this or any other program, and no sign-in happens nor are credentials stored: you sign in with your ChatGPT account afterwards, using “Sign in”.\n\nInstall Codex now? +- The session has expired. “Renew session” opens Claude Code, which renews it; Quorb updates itself. +- Token rechazado. «Renovar sesión» abre Claude Code para renovarlo; Quorb se actualiza solo. +- Token rejected. “Renew session” opens Claude Code to renew it; Quorb updates itself. +- auth.json has no tokens. Run “codex login”. +- auth.json has no valid credentials. Run “grok login”. +- auth.json sin credenciales válidas. Ejecuta «grok login». +- auth.json sin tokens. Ejecuta «codex login». - billing-cycle limit - daily limit - límite de 5 horas @@ -272,12 +322,9 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Claude - Claude Code-credentials - Credenciales sin accessToken -- Credenciales sin «claudeAiOauth» (¿login con API key?) - El endpoint de uso está limitando peticiones; reintento en el próximo ciclo. - Enterprise - HTTP {code} en el endpoint de uso -- La autorización del Keychain no se completó a tiempo. Concede el acceso a «Claude Code-credentials» y espera al próximo refresco. -- La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo. - Max - Pro - Respuesta inesperada: {e} @@ -288,33 +335,25 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Semana · todos - Sesión · 5 h - Team -- Token rechazado. «Renovar sesión» abre Claude Code para renovarlo; Quorb se actualiza solo. - Uso extra (mes) - WSL: {e:?} - créditos -- {e}. Inicia sesión en Claude Code. -- {m}. Inicia sesión en Claude Code. ## src-tauri/src/providers/codex.rs - ChatGPT · Codex -- Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login». - Créditos disponibles - El endpoint de uso está limitando peticiones. - HTTP {code} en el endpoint de uso - Respuesta inesperada: {e} - Respuesta sin datos de uso (¿ha cambiado el formato?) - Semana -- Sesión caducada. Ejecuta «codex» para renovarla. - Sesión · {} h - Ventana corta - Ventana larga - WSL: {e:?} - auth.json sin access_token -- auth.json sin tokens. Ejecuta «codex login». - créditos -- {e}. Ejecuta «codex login». -- {m}. Ejecuta «codex login». - {} días ## src-tauri/src/providers/copilot.rs @@ -340,9 +379,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a ## src-tauri/src/providers/cursor.rs - Cursor -- Cursor no tiene sesión iniciada. - HTTP {code} en usage-summary -- No encuentro la sesión de Cursor en {}. Inicia sesión en Cursor. - No puedo abrir la base de datos de Cursor: {e} - No reconozco el token de Cursor (¿formato cambiado?). - Pega el token de esta cuenta de Cursor en Ajustes. @@ -352,7 +389,6 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Plan · total - Respuesta inesperada: {e} - SELECT value FROM ItemTable WHERE key = 'cursorAuth/accessToken' -- Sesión de Cursor caducada. Abre Cursor para renovarla. - Sin datos de uso del plan en la respuesta. - User @@ -360,17 +396,12 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - El endpoint de cuotas está limitando peticiones. - Gemini -- Google no ha renovado la sesión de Gemini CLI. Ábrelo e inicia sesión de nuevo. - HTTP {code} en {method} -- La sesión de Gemini CLI ha caducado. Ábrelo para renovarla. - Respuesta de Google sin access_token - Respuesta inesperada: {e} -- Sesión de Gemini rechazada. Abre Gemini CLI para renovarla. - Sin cuotas por modelo en la respuesta (¿cuenta con API key en vez de login de Google?) - WSL: {e:?} - model:{name} -- {e}. Inicia sesión en Gemini CLI con tu cuenta de Google. -- {m}. Inicia sesión en Gemini CLI con tu cuenta de Google. ## src-tauri/src/providers/grok.rs @@ -380,14 +411,10 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - HTTP {code} en el endpoint de uso - Respuesta inesperada: {e} - Respuesta sin datos de uso (¿ha cambiado el formato?) -- Sesión caducada. Ejecuta «grok login» para renovarla. - Uso de créditos - Uso semanal - WSL: {e:?} - auth.json no es un objeto -- auth.json sin credenciales válidas. Ejecuta «grok login». -- {e}. Ejecuta «grok login». -- {m}. Ejecuta «grok login». ## src-tauri/src/providers/minimax.rs @@ -413,11 +440,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Error de red: {e} - Gemini - Grok -- JSON inválido en {}: {e} - La carpeta de la cuenta {} no es válida en modo WSL: {problem} -- No encuentro credenciales en: {} -- No existe {} -- No puedo leer {}: {e} - Proveedor desconocido: {other} - Sin conexión con el servidor - Tiempo de espera agotado @@ -803,10 +826,6 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a ## src-tauri/src/wsl/session.rs -- No encuentro credenciales en {distro}: {} -- No encuentro credenciales en {} -- No puedo leer {display}: {e} -- No puedo leer {}: {e} - WSL: {e:?} ## src/LocalePicker.tsx diff --git a/src-tauri/src/i18n.rs b/src-tauri/src/i18n.rs index 14992148..7d04b19e 100644 --- a/src-tauri/src/i18n.rs +++ b/src-tauri/src/i18n.rs @@ -47,6 +47,61 @@ pub enum Msg { EmailDropSubject, EmailDropBody, EmailDropMeterBody, + /// Proveedor: «No encuentro credenciales en: {list}» (sin ruta explícita + /// y ningún candidato existe; `resolve_path`). + CredentialsNotFound, + /// Proveedor: «No existe {path}» (ruta explícita que no es un fichero). + PathNotFound, + /// Resolvedor de sesión (host): «No encuentro credenciales en {path}». + CredentialsNotFoundAt, + /// Resolvedor de sesión (WSL): «No encuentro credenciales en {distro}: {path}». + CredentialsNotFoundDistro, + /// Lectura de sesión: «No puedo leer {path}: {error}». + CannotRead, + /// Lectura de sesión: «JSON inválido en {path}: {error}». + InvalidJson, + /// Claude: «Inicia sesión en Claude Code.» + SignInClaude, + /// Gemini: «Inicia sesión en Gemini CLI con tu cuenta de Google.» + SignInGemini, + /// Codex: «Ejecuta «codex login».» + SignInCodex, + /// Grok: «Ejecuta «grok login».» + SignInGrok, + /// Cursor: «No encuentro la sesión de Cursor en {path}. Inicia sesión en Cursor.» + CursorSessionNotFound, + /// Cursor: «Sesión de Cursor caducada. Abre Cursor para renovarla.» + CursorSessionExpired, + /// Claude (macOS): el consentimiento del Keychain no llegó a tiempo. + /// Solo se construye en macOS (`KeychainOutcome::TimedOut`); en las demás + /// plataformas el catálogo la mantiene por paridad, sin aviso (patrón de + /// #246 para textos por plataforma). + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + KeychainTimedOut, + /// Cursor: «Cursor no tiene sesión iniciada.» + CursorNoSession, + /// Claude: sesión caducada antes de consultar (el token local expiró). + ClaudeSessionExpired, + /// Claude: el endpoint rechazó el token (401/403). + ClaudeTokenRejected, + /// Claude: credenciales sin `claudeAiOauth` (login con API key). + ClaudeNoOauth, + /// Codex: `auth.json` solo con API key, sin cuenta de ChatGPT. + CodexApiKeyOnly, + /// Codex: `auth.json` sin el objeto `tokens`. + CodexNoTokens, + /// Codex: el endpoint rechazó la sesión (401/403). + CodexSessionExpired, + /// Grok: `auth.json` sin ninguna entrada con token. + GrokNoCredentials, + /// Grok: el endpoint rechazó la sesión (401/403). + GrokSessionExpired, + /// Gemini: sin `refresh_token` y con el token de acceso caducado. + GeminiSessionExpired, + /// Gemini: Google no renovó la sesión con el `refresh_token`. + GeminiRefreshFailed, + /// Gemini: el endpoint de cuotas rechazó la sesión (401). + GeminiSessionRejected, } /// Todas las variantes: los tests de paridad recorren esta lista y el match @@ -71,6 +126,31 @@ pub const ALL_MSGS: &[Msg] = &[ Msg::EmailDropSubject, Msg::EmailDropBody, Msg::EmailDropMeterBody, + Msg::CredentialsNotFound, + Msg::PathNotFound, + Msg::CredentialsNotFoundAt, + Msg::CredentialsNotFoundDistro, + Msg::CannotRead, + Msg::InvalidJson, + Msg::SignInClaude, + Msg::SignInGemini, + Msg::SignInCodex, + Msg::SignInGrok, + Msg::CursorSessionNotFound, + Msg::CursorSessionExpired, + Msg::KeychainTimedOut, + Msg::CursorNoSession, + Msg::ClaudeSessionExpired, + Msg::ClaudeTokenRejected, + Msg::ClaudeNoOauth, + Msg::CodexApiKeyOnly, + Msg::CodexNoTokens, + Msg::CodexSessionExpired, + Msg::GrokNoCredentials, + Msg::GrokSessionExpired, + Msg::GeminiSessionExpired, + Msg::GeminiRefreshFailed, + Msg::GeminiSessionRejected, ]; /// Texto original del diálogo de consentimiento de Codex, byte a byte (nace de @@ -123,6 +203,110 @@ pub fn text(locale: Locale, msg: Msg) -> &'static str { (Locale::En, Msg::EmailDropBody) => "Observed usage in {provider} has dropped below the alert threshold configured in Quorb.\n\nCurrent usage: {percent}.", (Locale::Es, Msg::EmailDropMeterBody) => "El consumo observado en {provider} ({meter}) ha bajado por debajo del umbral de aviso configurado en Quorb.\n\nConsumo actual: {percent}.", (Locale::En, Msg::EmailDropMeterBody) => "Observed usage in {provider} ({meter}) has dropped below the alert threshold configured in Quorb.\n\nCurrent usage: {percent}.", + (Locale::Es, Msg::CredentialsNotFound) => "No encuentro credenciales en: {list}", + (Locale::En, Msg::CredentialsNotFound) => "No credentials found in: {list}", + (Locale::Es, Msg::PathNotFound) => "No existe {path}", + (Locale::En, Msg::PathNotFound) => "Path not found: {path}", + (Locale::Es, Msg::CredentialsNotFoundAt) => "No encuentro credenciales en {path}", + (Locale::En, Msg::CredentialsNotFoundAt) => "No credentials found in {path}", + (Locale::Es, Msg::CredentialsNotFoundDistro) => { + "No encuentro credenciales en {distro}: {path}" + } + (Locale::En, Msg::CredentialsNotFoundDistro) => { + "No credentials found in {distro}: {path}" + } + (Locale::Es, Msg::CannotRead) => "No puedo leer {path}: {error}", + (Locale::En, Msg::CannotRead) => "Cannot read {path}: {error}", + (Locale::Es, Msg::InvalidJson) => "JSON inválido en {path}: {error}", + (Locale::En, Msg::InvalidJson) => "Invalid JSON in {path}: {error}", + (Locale::Es, Msg::SignInClaude) => "Inicia sesión en Claude Code.", + (Locale::En, Msg::SignInClaude) => "Sign in to Claude Code.", + (Locale::Es, Msg::SignInGemini) => { + "Inicia sesión en Gemini CLI con tu cuenta de Google." + } + (Locale::En, Msg::SignInGemini) => "Sign in to Gemini CLI with your Google account.", + (Locale::Es, Msg::SignInCodex) => "Ejecuta «codex login».", + (Locale::En, Msg::SignInCodex) => "Run “codex login”.", + (Locale::Es, Msg::SignInGrok) => "Ejecuta «grok login».", + (Locale::En, Msg::SignInGrok) => "Run “grok login”.", + (Locale::Es, Msg::CursorSessionNotFound) => { + "No encuentro la sesión de Cursor en {path}. Inicia sesión en Cursor." + } + (Locale::En, Msg::CursorSessionNotFound) => { + "Cursor session not found at {path}. Sign in to Cursor." + } + (Locale::Es, Msg::CursorSessionExpired) => { + "Sesión de Cursor caducada. Abre Cursor para renovarla." + } + (Locale::En, Msg::CursorSessionExpired) => { + "Cursor session expired. Open Cursor to renew it." + } + (Locale::Es, Msg::KeychainTimedOut) => "La autorización del Keychain no se completó a tiempo. Concede el acceso a «Claude Code-credentials» y espera al próximo refresco.", + (Locale::En, Msg::KeychainTimedOut) => "Keychain authorization did not complete in time. Grant access to “Claude Code-credentials” and wait for the next refresh.", + (Locale::Es, Msg::CursorNoSession) => "Cursor no tiene sesión iniciada.", + (Locale::En, Msg::CursorNoSession) => "Cursor is not signed in.", + (Locale::Es, Msg::ClaudeSessionExpired) => { + "La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo." + } + (Locale::En, Msg::ClaudeSessionExpired) => { + "The session has expired. “Renew session” opens Claude Code, which renews it; Quorb updates itself." + } + (Locale::Es, Msg::ClaudeTokenRejected) => { + "Token rechazado. «Renovar sesión» abre Claude Code para renovarlo; Quorb se actualiza solo." + } + (Locale::En, Msg::ClaudeTokenRejected) => { + "Token rejected. “Renew session” opens Claude Code to renew it; Quorb updates itself." + } + (Locale::Es, Msg::ClaudeNoOauth) => { + "Credenciales sin «claudeAiOauth» (¿login con API key?)" + } + (Locale::En, Msg::ClaudeNoOauth) => { + "Credentials without “claudeAiOauth” (signed in with an API key?)" + } + (Locale::Es, Msg::CodexApiKeyOnly) => { + "Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login»." + } + (Locale::En, Msg::CodexApiKeyOnly) => { + "Codex is authenticated with an API key, not with your ChatGPT account. Run “codex login”." + } + (Locale::Es, Msg::CodexNoTokens) => "auth.json sin tokens. Ejecuta «codex login».", + (Locale::En, Msg::CodexNoTokens) => "auth.json has no tokens. Run “codex login”.", + (Locale::Es, Msg::CodexSessionExpired) => { + "Sesión caducada. Ejecuta «codex» para renovarla." + } + (Locale::En, Msg::CodexSessionExpired) => { + "Session expired. Run “codex” to renew it." + } + (Locale::Es, Msg::GrokNoCredentials) => { + "auth.json sin credenciales válidas. Ejecuta «grok login»." + } + (Locale::En, Msg::GrokNoCredentials) => { + "auth.json has no valid credentials. Run “grok login”." + } + (Locale::Es, Msg::GrokSessionExpired) => { + "Sesión caducada. Ejecuta «grok login» para renovarla." + } + (Locale::En, Msg::GrokSessionExpired) => { + "Session expired. Run “grok login” to renew it." + } + (Locale::Es, Msg::GeminiSessionExpired) => { + "La sesión de Gemini CLI ha caducado. Ábrelo para renovarla." + } + (Locale::En, Msg::GeminiSessionExpired) => { + "The Gemini CLI session has expired. Open it to renew it." + } + (Locale::Es, Msg::GeminiRefreshFailed) => { + "Google no ha renovado la sesión de Gemini CLI. Ábrelo e inicia sesión de nuevo." + } + (Locale::En, Msg::GeminiRefreshFailed) => { + "Google did not renew the Gemini CLI session. Open it and sign in again." + } + (Locale::Es, Msg::GeminiSessionRejected) => { + "Sesión de Gemini rechazada. Abre Gemini CLI para renovarla." + } + (Locale::En, Msg::GeminiSessionRejected) => { + "Gemini session rejected. Open Gemini CLI to renew it." + } } } @@ -230,6 +414,82 @@ pub fn codex_consent_message(locale: Locale, channel: &str, home_dir: &str) -> S .replace("~/.quorb/", &format!("~/{home_dir}/")) } +/// Sustituye `{nombre}` por su valor en UNA sola pasada sobre la plantilla: +/// lo ya insertado no se vuelve a examinar, así que un valor que contiene +/// `{error}`, `{path}` o `{distro}` viaja literal (rutas y errores externos +/// nunca se reinterpretan, S5.3 de la review de #272). +fn fill(template: &str, values: &[(&str, &str)]) -> String { + let mut out = String::with_capacity(template.len()); + let mut rest = template; + while let Some(open) = rest.find('{') { + out.push_str(&rest[..open]); + rest = &rest[open..]; + let hit = values.iter().find(|(name, _)| { + rest[1..] + .strip_prefix(name) + .is_some_and(|tail| tail.starts_with('}')) + }); + match hit { + Some((name, value)) => { + out.push_str(value); + rest = &rest[name.len() + 2..]; + } + None => { + out.push('{'); + rest = &rest[1..]; + } + } + } + out.push_str(rest); + out +} + +/// «No encuentro credenciales en: {lista}» — sin ruta explícita y ningún +/// candidato existe (`resolve_path`). Las rutas viajan literales (L4, #66). +pub fn credentials_not_found(locale: Locale, list: &str) -> String { + text(locale, Msg::CredentialsNotFound).replace("{list}", list) +} + +/// «No existe {ruta}» — la ruta explícita de la config no es un fichero. +pub fn path_not_found(locale: Locale, path: &str) -> String { + text(locale, Msg::PathNotFound).replace("{path}", path) +} + +/// «No encuentro credenciales en {ruta}» — resolvedor de sesión en host. +pub fn credentials_not_found_at(locale: Locale, path: &str) -> String { + text(locale, Msg::CredentialsNotFoundAt).replace("{path}", path) +} + +/// «No encuentro credenciales en {distro}: {ruta}» — resolvedor en WSL. +pub fn credentials_not_found_in_distro(locale: Locale, distro: &str, path: &str) -> String { + fill( + text(locale, Msg::CredentialsNotFoundDistro), + &[("distro", distro), ("path", path)], + ) +} + +/// «No puedo leer {ruta}: {error}» — el fichero existe pero no se lee; el +/// error del sistema o de WSL viaja literal, sin traducir. +pub fn cannot_read(locale: Locale, path: &str, error: &str) -> String { + fill( + text(locale, Msg::CannotRead), + &[("path", path), ("error", error)], + ) +} + +/// «JSON inválido en {ruta}: {error}» — se leyó pero no es JSON válido. +pub fn invalid_json(locale: Locale, path: &str, error: &str) -> String { + fill( + text(locale, Msg::InvalidJson), + &[("path", path), ("error", error)], + ) +} + +/// «No encuentro la sesión de Cursor en {ruta}. Inicia sesión en Cursor.» +pub fn cursor_session_not_found(locale: Locale, path: &str) -> String { + text(locale, Msg::CursorSessionNotFound).replace("{path}", path) +} + #[cfg(test)] mod tests { use super::*; @@ -331,6 +591,185 @@ mod tests { assert_eq!(codex_consent_buttons(Locale::En), ("Install", "Cancel")); } + /// R6 (#66) para los mensajes de proveedores: el español nace de los + /// literales actuales del backend, byte a byte. + #[test] + fn provider_messages_spanish_are_the_current_literals_verbatim() { + let es = |msg| text(Locale::Es, msg); + assert_eq!( + es(Msg::CredentialsNotFound), + "No encuentro credenciales en: {list}" + ); + assert_eq!(es(Msg::PathNotFound), "No existe {path}"); + assert_eq!( + es(Msg::CredentialsNotFoundAt), + "No encuentro credenciales en {path}" + ); + assert_eq!( + es(Msg::CredentialsNotFoundDistro), + "No encuentro credenciales en {distro}: {path}" + ); + assert_eq!(es(Msg::CannotRead), "No puedo leer {path}: {error}"); + assert_eq!(es(Msg::InvalidJson), "JSON inválido en {path}: {error}"); + assert_eq!(es(Msg::SignInClaude), "Inicia sesión en Claude Code."); + assert_eq!( + es(Msg::SignInGemini), + "Inicia sesión en Gemini CLI con tu cuenta de Google." + ); + assert_eq!(es(Msg::SignInCodex), "Ejecuta «codex login»."); + assert_eq!(es(Msg::SignInGrok), "Ejecuta «grok login»."); + assert_eq!( + es(Msg::CursorSessionNotFound), + "No encuentro la sesión de Cursor en {path}. Inicia sesión en Cursor." + ); + assert_eq!( + es(Msg::CursorSessionExpired), + "Sesión de Cursor caducada. Abre Cursor para renovarla." + ); + assert_eq!( + es(Msg::KeychainTimedOut), + "La autorización del Keychain no se completó a tiempo. Concede el acceso a «Claude Code-credentials» y espera al próximo refresco." + ); + assert_eq!(es(Msg::CursorNoSession), "Cursor no tiene sesión iniciada."); + assert_eq!( + es(Msg::ClaudeSessionExpired), + "La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo." + ); + assert_eq!( + es(Msg::ClaudeTokenRejected), + "Token rechazado. «Renovar sesión» abre Claude Code para renovarlo; Quorb se actualiza solo." + ); + assert_eq!( + es(Msg::ClaudeNoOauth), + "Credenciales sin «claudeAiOauth» (¿login con API key?)" + ); + assert_eq!( + es(Msg::CodexApiKeyOnly), + "Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login»." + ); + assert_eq!( + es(Msg::CodexNoTokens), + "auth.json sin tokens. Ejecuta «codex login»." + ); + assert_eq!( + es(Msg::CodexSessionExpired), + "Sesión caducada. Ejecuta «codex» para renovarla." + ); + assert_eq!( + es(Msg::GrokNoCredentials), + "auth.json sin credenciales válidas. Ejecuta «grok login»." + ); + assert_eq!( + es(Msg::GrokSessionExpired), + "Sesión caducada. Ejecuta «grok login» para renovarla." + ); + assert_eq!( + es(Msg::GeminiSessionExpired), + "La sesión de Gemini CLI ha caducado. Ábrelo para renovarla." + ); + assert_eq!( + es(Msg::GeminiRefreshFailed), + "Google no ha renovado la sesión de Gemini CLI. Ábrelo e inicia sesión de nuevo." + ); + assert_eq!( + es(Msg::GeminiSessionRejected), + "Sesión de Gemini rechazada. Abre Gemini CLI para renovarla." + ); + } + + /// S5.3 (review #272): la sustitución es de una sola pasada; un valor que + /// contiene `{error}`, `{path}` o `{distro}` se inserta literal y nunca se + /// vuelve a sustituir. + #[test] + fn placeholders_inside_values_are_inserted_literally() { + assert_eq!( + cannot_read(Locale::Es, "/tmp/{error}/creds.json", "boom"), + "No puedo leer /tmp/{error}/creds.json: boom" + ); + assert_eq!( + invalid_json(Locale::En, "/tmp/{error}/creds.json", "boom"), + "Invalid JSON in /tmp/{error}/creds.json: boom" + ); + // El error externo también es literal: un `{path}` suyo no se toca. + assert_eq!( + cannot_read(Locale::Es, "/a", "fallo en {path}"), + "No puedo leer /a: fallo en {path}" + ); + assert_eq!( + credentials_not_found_in_distro(Locale::Es, "Ub{path}untu", "/home/u/c.json"), + "No encuentro credenciales en Ub{path}untu: /home/u/c.json" + ); + assert_eq!( + credentials_not_found_in_distro(Locale::En, "Ubuntu", "/home/{distro}/c.json"), + "No credentials found in Ubuntu: /home/{distro}/c.json" + ); + } + + /// Las plantillas con anclas `{…}` tienen las mismas anclas en ambos + /// idiomas: una sustitución no puede quedarse a medias por locale. + #[test] + fn provider_message_templates_keep_same_anchors_in_both_locales() { + fn anchors(s: &str) -> Vec<&str> { + let mut found: Vec<&str> = s + .match_indices('{') + .filter_map(|(i, _)| s[i..].find('}').map(|e| &s[i + 1..i + e])) + .collect(); + found.sort_unstable(); + found + } + for &msg in ALL_MSGS { + let (es, en) = (text(Locale::Es, msg), text(Locale::En, msg)); + assert_eq!(anchors(es), anchors(en), "{msg:?} con anclas dispares"); + } + } + + /// Mensajes de proveedor ensamblados: rutas y errores externos viajan + /// literales; la frase propia respeta la locale. + #[test] + fn provider_messages_assemble_paths_and_errors_verbatim() { + let path = "/home/u/.claude/.credentials.json"; + assert_eq!( + credentials_not_found(Locale::Es, &format!("{path}, /var/c.json")), + "No encuentro credenciales en: /home/u/.claude/.credentials.json, /var/c.json" + ); + assert_eq!( + credentials_not_found(Locale::En, &format!("{path}, /var/c.json")), + "No credentials found in: /home/u/.claude/.credentials.json, /var/c.json" + ); + assert_eq!( + path_not_found(Locale::Es, path), + "No existe /home/u/.claude/.credentials.json" + ); + assert_eq!( + path_not_found(Locale::En, path), + "Path not found: /home/u/.claude/.credentials.json" + ); + assert_eq!( + credentials_not_found_at(Locale::Es, path), + "No encuentro credenciales en /home/u/.claude/.credentials.json" + ); + assert_eq!( + credentials_not_found_in_distro(Locale::En, "Ubuntu", path), + "No credentials found in Ubuntu: /home/u/.claude/.credentials.json" + ); + assert_eq!( + cannot_read(Locale::Es, path, "permiso denegado"), + "No puedo leer /home/u/.claude/.credentials.json: permiso denegado" + ); + assert_eq!( + invalid_json(Locale::En, path, "EOF while parsing"), + "Invalid JSON in /home/u/.claude/.credentials.json: EOF while parsing" + ); + assert_eq!( + cursor_session_not_found(Locale::Es, "C:/Users/u/state.vscdb"), + "No encuentro la sesión de Cursor en C:/Users/u/state.vscdb. Inicia sesión en Cursor." + ); + assert_eq!( + cursor_session_not_found(Locale::En, "C:/Users/u/state.vscdb"), + "Cursor session not found at C:/Users/u/state.vscdb. Sign in to Cursor." + ); + } + /// El mensaje ensamblado con la identidad estable ("Quorb", ".quorb") es el /// literal original byte a byte; en inglés se aplican las mismas /// sustituciones de canal y carpeta. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 63ce30be..561c31f6 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -626,7 +626,12 @@ async fn session_resolver( home } }; - Ok(Some(wsl::SessionResolver::for_wsl(adapter, distro, home))) + Ok(Some(wsl::SessionResolver::for_wsl( + adapter, + distro, + home, + crate::i18n::locale_from_config(&cfg.locale), + ))) } } } diff --git a/src-tauri/src/providers/claude.rs b/src-tauri/src/providers/claude.rs index 479d885b..93b02db1 100644 --- a/src-tauri/src/providers/claude.rs +++ b/src-tauri/src/providers/claude.rs @@ -10,6 +10,7 @@ use super::{home, net_error, read_json, resolve_path, Who}; use crate::config::SubscriptionConfig; +use crate::i18n::{text, Locale, Msg}; use crate::model::{Kind, Meter, Status, UsageReport}; use crate::wsl::{SessionError, SessionResolver}; use serde_json::Value; @@ -171,11 +172,13 @@ fn parse_keychain_secret(raw: &str) -> Option { } serde_json::from_str::(trimmed) .ok() - .and_then(|v| Credentials::parse(&v).ok()) + // El error se descarta: el locale no llega a verse. + .and_then(|v| Credentials::parse(Locale::Es, &v).ok()) } pub async fn fetch( cfg: &SubscriptionConfig, + locale: Locale, who: Who<'_>, http: &reqwest::Client, resolver: Option<&SessionResolver>, @@ -199,16 +202,20 @@ pub async fn fetch( }; match r.read_async(&path).await { Ok(raw) => match serde_json::from_str::(&raw) { - Ok(v) => match Credentials::parse(&v) { + Ok(v) => match Credentials::parse(locale, &v) { Ok(c) => c, Err(e) => { - return report - .fail(Status::Error, format!("{e}. Inicia sesión en Claude Code.")) + return report.fail( + Status::Error, + format!("{}. {}", e, text(locale, Msg::SignInClaude)), + ) } }, Err(e) => { - return report - .fail(Status::Error, format!("{e}. Inicia sesión en Claude Code.")) + return report.fail( + Status::Error, + format!("{}. {}", e, text(locale, Msg::SignInClaude)), + ) } }, // Sin credenciales en el entorno elegido: hace falta login @@ -216,7 +223,7 @@ pub async fn fetch( Err(SessionError::Absent(m)) => { return report.fail( Status::NeedsLogin, - format!("{m}. Inicia sesión en Claude Code."), + format!("{}. {}", m, text(locale, Msg::SignInClaude)), ) } // El fallo es del subsistema o de la distro: la acción @@ -227,8 +234,8 @@ pub async fn fetch( Err(e) => return report.fail(Status::Error, e.to_string()), } } - None => match resolve_path(cfg.credentials_path.as_deref(), &[default_path]) { - Ok(p) => match read_json(&p).and_then(|v| Credentials::parse(&v)) { + None => match resolve_path(locale, cfg.credentials_path.as_deref(), &[default_path]) { + Ok(p) => match read_json(locale, &p).and_then(|v| Credentials::parse(locale, &v)) { Ok(c) => c, Err(e) => return report.fail(Status::Error, e), }, @@ -239,7 +246,7 @@ pub async fn fetch( if !should_fallback_keychain(cfg.credentials_path.as_deref()) { return report.fail( Status::NeedsLogin, - format!("{e}. Inicia sesión en Claude Code."), + format!("{}. {}", e, text(locale, Msg::SignInClaude)), ); } match keychain_fallback().await { @@ -247,15 +254,12 @@ pub async fn fetch( KeychainOutcome::Session(c) => c, #[cfg(target_os = "macos")] KeychainOutcome::TimedOut => { - return report.fail( - Status::Warning, - "La autorización del Keychain no se completó a tiempo. Concede el acceso a «Claude Code-credentials» y espera al próximo refresco.", - ) + return report.fail(Status::Warning, text(locale, Msg::KeychainTimedOut)) } KeychainOutcome::NoSession => { return report.fail( Status::NeedsLogin, - format!("{e}. Inicia sesión en Claude Code."), + format!("{}. {}", e, text(locale, Msg::SignInClaude)), ) } } @@ -267,10 +271,7 @@ pub async fn fetch( report.plan = creds.plan.clone(); if creds.is_expired(chrono::Utc::now().timestamp_millis()) { - return report.fail( - Status::NeedsLogin, - "La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo.", - ); + return report.fail(Status::NeedsLogin, text(locale, Msg::ClaudeSessionExpired)); } let res = http @@ -286,8 +287,15 @@ pub async fn fetch( }; match res.status().as_u16() { 200 => {} - 401 | 403 => return report.fail(Status::NeedsLogin, "Token rechazado. «Renovar sesión» abre Claude Code para renovarlo; Quorb se actualiza solo."), - 429 => return report.fail(Status::Warning, "El endpoint de uso está limitando peticiones; reintento en el próximo ciclo."), + 401 | 403 => { + return report.fail(Status::NeedsLogin, text(locale, Msg::ClaudeTokenRejected)) + } + 429 => { + return report.fail( + Status::Warning, + "El endpoint de uso está limitando peticiones; reintento en el próximo ciclo.", + ) + } code => return report.fail(Status::Error, format!("HTTP {code} en el endpoint de uso")), } let body: Value = match res.json().await { @@ -312,10 +320,10 @@ pub(crate) struct Credentials { } impl Credentials { - pub fn parse(v: &Value) -> Result { + pub fn parse(locale: Locale, v: &Value) -> Result { let o = v .get("claudeAiOauth") - .ok_or("Credenciales sin «claudeAiOauth» (¿login con API key?)")?; + .ok_or_else(|| text(locale, Msg::ClaudeNoOauth).to_string())?; let access_token = o .get("accessToken") .and_then(Value::as_str) @@ -406,7 +414,7 @@ mod tests { #[test] fn parses_credentials() { let v = json!({"claudeAiOauth": {"accessToken": "sk-ant-oat01-x", "refreshToken": "r", "expiresAt": 1_900_000_000_000_i64, "subscriptionType": "max"}}); - let c = Credentials::parse(&v).unwrap(); + let c = Credentials::parse(Locale::Es, &v).unwrap(); assert_eq!(c.plan.as_deref(), Some("Max")); assert!(!c.is_expired(1_800_000_000_000)); assert!(c.is_expired(1_900_000_000_000)); @@ -414,7 +422,7 @@ mod tests { #[test] fn rejects_missing_oauth() { - assert!(Credentials::parse(&json!({})).is_err()); + assert!(Credentials::parse(Locale::Es, &json!({})).is_err()); } /// Sesión real de Claude Code: el fixture es la estructura que escribe @@ -425,7 +433,8 @@ mod tests { fn parses_real_session_fixture() { let raw = include_str!("fixtures/claude-credentials.json"); let v: Value = serde_json::from_str(raw).expect("fixture claude válido"); - let c = Credentials::parse(&v).expect("el fixture debe parsear como sesión real"); + let c = + Credentials::parse(Locale::Es, &v).expect("el fixture debe parsear como sesión real"); assert_eq!(c.access_token, "example-access-token-abcdef"); assert_eq!(c.plan.as_deref(), Some("Pro")); let exp = c.expires_at_ms.expect("el fixture trae expiresAt"); diff --git a/src-tauri/src/providers/codex.rs b/src-tauri/src/providers/codex.rs index c47ffa8b..b6864789 100644 --- a/src-tauri/src/providers/codex.rs +++ b/src-tauri/src/providers/codex.rs @@ -7,6 +7,7 @@ use super::{home, net_error, read_json, resolve_path, unix_to_rfc3339, Who}; use crate::config::SubscriptionConfig; +use crate::i18n::{text, Locale, Msg}; use crate::model::{Kind, Meter, Status, UsageReport, Validity, ValidityKind}; use crate::wsl::{SessionError, SessionResolver}; use base64::Engine; @@ -32,16 +33,21 @@ pub(crate) fn auth_candidates(codex_home: Option<&Path>, home: &Path) -> Vec, codex_home: Option<&Path>, home: &Path, ) -> Result { - resolve_path(credentials_path, &auth_candidates(codex_home, home)) + resolve_path(locale, credentials_path, &auth_candidates(codex_home, home)) } /// `auth_path` leyendo `CODEX_HOME` del entorno (uso real; los tests inyectan). -pub(crate) fn resolved_auth_path(credentials_path: Option<&str>) -> Result { +pub(crate) fn resolved_auth_path( + locale: Locale, + credentials_path: Option<&str>, +) -> Result { auth_path( + locale, credentials_path, std::env::var_os("CODEX_HOME").map(PathBuf::from).as_deref(), &home(), @@ -50,6 +56,7 @@ pub(crate) fn resolved_auth_path(credentials_path: Option<&str>) -> Result, http: &reqwest::Client, resolver: Option<&SessionResolver>, @@ -73,13 +80,19 @@ pub async fn fetch( Ok(raw) => match serde_json::from_str::(&raw) { Ok(v) => v, Err(e) => { - return report.fail(Status::Error, format!("{e}. Ejecuta «codex login».")) + return report.fail( + Status::Error, + format!("{}. {}", e, text(locale, Msg::SignInCodex)), + ) } }, // Sin credenciales en el entorno elegido: hace falta login // AQUÍ (no en otro entorno). Err(SessionError::Absent(m)) => { - return report.fail(Status::NeedsLogin, format!("{m}. Ejecuta «codex login».")) + return report.fail( + Status::NeedsLogin, + format!("{}. {}", m, text(locale, Msg::SignInCodex)), + ) } // El fallo es del subsistema o de la distro: la acción // correcta no es "inicia sesión". @@ -90,19 +103,22 @@ pub async fn fetch( } } None => { - let path = match resolved_auth_path(cfg.credentials_path.as_deref()) { + let path = match resolved_auth_path(locale, cfg.credentials_path.as_deref()) { Ok(p) => p, Err(e) => { - return report.fail(Status::NeedsLogin, format!("{e}. Ejecuta «codex login».")) + return report.fail( + Status::NeedsLogin, + format!("{}. {}", e, text(locale, Msg::SignInCodex)), + ) } }; - match read_json(&path) { + match read_json(locale, &path) { Ok(v) => v, Err(e) => return report.fail(Status::NeedsLogin, e), } } }; - let auth = match Auth::parse(&auth_json) { + let auth = match Auth::parse(locale, &auth_json) { Ok(a) => a, Err(e) => return report.fail(Status::NeedsLogin, e), }; @@ -121,10 +137,7 @@ pub async fn fetch( match res.status().as_u16() { 200 => {} 401 | 403 => { - return report.fail( - Status::NeedsLogin, - "Sesión caducada. Ejecuta «codex» para renovarla.", - ) + return report.fail(Status::NeedsLogin, text(locale, Msg::CodexSessionExpired)) } 429 => { return report.fail( @@ -170,16 +183,15 @@ pub(crate) struct Auth { } impl Auth { - pub fn parse(v: &Value) -> Result { + pub fn parse(locale: Locale, v: &Value) -> Result { let tokens = v.get("tokens").filter(|t| t.is_object()); let Some(tokens) = tokens else { - return Err( - if v.get("OPENAI_API_KEY").and_then(Value::as_str).is_some() { - "Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login».".into() - } else { - "auth.json sin tokens. Ejecuta «codex login».".into() - }, - ); + let msg = if v.get("OPENAI_API_KEY").and_then(Value::as_str).is_some() { + Msg::CodexApiKeyOnly + } else { + Msg::CodexNoTokens + }; + return Err(text(locale, msg).to_string()); }; let access_token = tokens .get("access_token") @@ -398,7 +410,7 @@ mod tests { let codex_auth = codex_home.file("auth.json"); home.file(".codex/auth.json"); assert_eq!( - auth_path(None, Some(codex_home.path()), home.path()).unwrap(), + auth_path(Locale::Es, None, Some(codex_home.path()), home.path()).unwrap(), codex_auth ); } @@ -410,7 +422,7 @@ mod tests { let codex_home = TempDir::new("codexhome-empty"); let home_auth = home.file(".codex/auth.json"); assert_eq!( - auth_path(None, Some(codex_home.path()), home.path()).unwrap(), + auth_path(Locale::Es, None, Some(codex_home.path()), home.path()).unwrap(), home_auth ); } @@ -423,7 +435,13 @@ mod tests { let custom = home.file("custom/auth.json"); let explicit = custom.to_string_lossy().into_owned(); assert_eq!( - auth_path(Some(&explicit), Some(codex_home.path()), home.path()).unwrap(), + auth_path( + Locale::Es, + Some(&explicit), + Some(codex_home.path()), + home.path() + ) + .unwrap(), custom ); } @@ -432,24 +450,32 @@ mod tests { fn auth_path_errors_when_nothing_exists() { let home = TempDir::new("home-empty"); let codex_home = TempDir::new("codexhome-none"); - assert!(auth_path(None, Some(codex_home.path()), home.path()).is_err()); + assert!(auth_path(Locale::Es, None, Some(codex_home.path()), home.path()).is_err()); let missing = home.path().join("missing.json"); - assert!(auth_path(Some(missing.to_string_lossy().as_ref()), None, home.path()).is_err()); + assert!(auth_path( + Locale::Es, + Some(missing.to_string_lossy().as_ref()), + None, + home.path() + ) + .is_err()); } #[test] fn parses_auth() { let v = json!({"OPENAI_API_KEY": null, "tokens": {"id_token": "a", "access_token": "b", "refresh_token": "c", "account_id": "acc"}}); assert_eq!( - Auth::parse(&v).unwrap(), + Auth::parse(Locale::Es, &v).unwrap(), Auth { access_token: "b".into(), account_id: Some("acc".into()) } ); - assert!(Auth::parse(&json!({"OPENAI_API_KEY": "sk-..."})) - .unwrap_err() - .contains("API key")); + assert!( + Auth::parse(Locale::Es, &json!({"OPENAI_API_KEY": "sk-..."})) + .unwrap_err() + .contains("API key") + ); } /// Sesión real de Codex: el fixture es la estructura que escribe @@ -459,7 +485,7 @@ mod tests { fn parses_real_session_fixture() { let raw = include_str!("fixtures/codex-auth.json"); let v: Value = serde_json::from_str(raw).expect("fixture codex válido"); - let auth = Auth::parse(&v).expect("el fixture debe parsear como sesión real"); + let auth = Auth::parse(Locale::Es, &v).expect("el fixture debe parsear como sesión real"); assert_eq!(auth.access_token, "example-access-token-codex"); assert_eq!(auth.account_id.as_deref(), Some("account-example-123")); // El id_token del fixture expira en el año ~2100: a día de hoy es válido. diff --git a/src-tauri/src/providers/cursor.rs b/src-tauri/src/providers/cursor.rs index a44218f8..fb41e3ee 100644 --- a/src-tauri/src/providers/cursor.rs +++ b/src-tauri/src/providers/cursor.rs @@ -8,6 +8,7 @@ use super::{net_error, Who}; use crate::config::SubscriptionConfig; +use crate::i18n::{text, Locale, Msg}; use crate::model::{Kind, Meter, Spend, Status, UsageReport, Validity, ValidityKind}; use crate::secrets; use base64::Engine; @@ -15,7 +16,12 @@ use chrono::DateTime; use serde_json::Value; use std::path::PathBuf; -pub async fn fetch(cfg: &SubscriptionConfig, who: Who<'_>, http: &reqwest::Client) -> UsageReport { +pub async fn fetch( + cfg: &SubscriptionConfig, + locale: Locale, + who: Who<'_>, + http: &reqwest::Client, +) -> UsageReport { let report = who.report("Cursor", Kind::Subscription); // Token: el pegado a mano en Ajustes manda; si no, el de la app de Cursor. @@ -28,7 +34,7 @@ pub async fn fetch(cfg: &SubscriptionConfig, who: Who<'_>, http: &reqwest::Clien "Pega el token de esta cuenta de Cursor en Ajustes.", ); } - None => match read_app_token(cfg.credentials_path.as_deref()) { + None => match read_app_token(locale, cfg.credentials_path.as_deref()) { Ok(t) => t, Err(e) => return report.fail(Status::NeedsLogin, e), }, @@ -55,10 +61,7 @@ pub async fn fetch(cfg: &SubscriptionConfig, who: Who<'_>, http: &reqwest::Clien match res.status().as_u16() { 200 => {} 401 | 403 => { - return report.fail( - Status::NeedsLogin, - "Sesión de Cursor caducada. Abre Cursor para renovarla.", - ) + return report.fail(Status::NeedsLogin, text(locale, Msg::CursorSessionExpired)) } code => return report.fail(Status::Error, format!("HTTP {code} en usage-summary")), } @@ -90,12 +93,12 @@ fn default_db() -> PathBuf { } /// Lee `cursorAuth/accessToken` de la base de datos de Cursor en modo solo lectura. -fn read_app_token(explicit: Option<&str>) -> Result { +fn read_app_token(locale: Locale, explicit: Option<&str>) -> Result { let path = explicit.map(PathBuf::from).unwrap_or_else(default_db); if !path.is_file() { - return Err(format!( - "No encuentro la sesión de Cursor en {}. Inicia sesión en Cursor.", - path.display() + return Err(crate::i18n::cursor_session_not_found( + locale, + &path.display().to_string(), )); } // `immutable=1`: no toca los bloqueos de Cursor aunque esté abierto. @@ -122,12 +125,12 @@ fn read_app_token(explicit: Option<&str>) -> Result { [], |r| r.get(0), ) - .map_err(|_| "Cursor no tiene sesión iniciada.".to_string())?; + .map_err(|_| text(locale, Msg::CursorNoSession).to_string())?; // Según la versión de Cursor el valor es texto o BLOB. let raw = match value { rusqlite::types::Value::Text(t) => t, rusqlite::types::Value::Blob(b) => String::from_utf8_lossy(&b).into_owned(), - _ => return Err("Cursor no tiene sesión iniciada.".into()), + _ => return Err(text(locale, Msg::CursorNoSession).to_string()), }; Ok(raw.trim().trim_matches('"').to_string()) } @@ -331,4 +334,51 @@ mod tests { assert_eq!(user_id_from_jwt(&token).as_deref(), Some("user_01ABC")); assert_eq!(user_id_from_jwt("nope"), None); } + + /// S5.1 (review #272): la base de Cursor existe pero no guarda sesión (ni + /// fila, ni valor de texto/BLOB): el mensaje sigue la locale de la app. + #[test] + fn cursor_without_session_follows_the_app_locale() { + let dir = + std::env::temp_dir().join(format!("quorb-cursor-nosession-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("state.vscdb"); + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute( + "CREATE TABLE ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)", + [], + ) + .unwrap(); + } + let explicit = path.to_string_lossy().into_owned(); + // Sin la fila `cursorAuth/accessToken`. + assert_eq!( + read_app_token(Locale::En, Some(&explicit)), + Err("Cursor is not signed in.".to_string()) + ); + assert_eq!( + read_app_token(Locale::Es, Some(&explicit)), + Err("Cursor no tiene sesión iniciada.".to_string()) + ); + // Con la fila pero con un valor que no es texto ni BLOB. + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute( + "INSERT INTO ItemTable (key, value) VALUES ('cursorAuth/accessToken', 5)", + [], + ) + .unwrap(); + } + assert_eq!( + read_app_token(Locale::En, Some(&explicit)), + Err("Cursor is not signed in.".to_string()) + ); + assert_eq!( + read_app_token(Locale::Es, Some(&explicit)), + Err("Cursor no tiene sesión iniciada.".to_string()) + ); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/src-tauri/src/providers/gemini.rs b/src-tauri/src/providers/gemini.rs index a9224273..0c1408bd 100644 --- a/src-tauri/src/providers/gemini.rs +++ b/src-tauri/src/providers/gemini.rs @@ -12,6 +12,7 @@ use super::{home, net_error, read_json, resolve_path, Who}; use crate::config::SubscriptionConfig; +use crate::i18n::{text, Locale, Msg}; use crate::model::{Kind, Meter, Status, UsageReport}; use crate::wsl::{SessionError, SessionResolver}; use serde_json::{json, Value}; @@ -28,6 +29,7 @@ static CACHED: Mutex> = Mutex::new(BTreeMap::new pub async fn fetch( cfg: &SubscriptionConfig, + locale: Locale, who: Who<'_>, http: &reqwest::Client, resolver: Option<&SessionResolver>, @@ -52,7 +54,7 @@ pub async fn fetch( Err(e) => { return report.fail( Status::Error, - format!("{e}. Inicia sesión en Gemini CLI con tu cuenta de Google."), + format!("{}. {}", e, text(locale, Msg::SignInGemini)), ) } }, @@ -61,7 +63,7 @@ pub async fn fetch( Err(SessionError::Absent(m)) => { return report.fail( Status::NeedsLogin, - format!("{m}. Inicia sesión en Gemini CLI con tu cuenta de Google."), + format!("{}. {}", m, text(locale, Msg::SignInGemini)), ) } // El fallo es del subsistema o de la distro: la acción @@ -74,28 +76,28 @@ pub async fn fetch( } None => { let candidates = vec![home().join(".gemini").join("oauth_creds.json")]; - let path = match resolve_path(cfg.credentials_path.as_deref(), &candidates) { + let path = match resolve_path(locale, cfg.credentials_path.as_deref(), &candidates) { Ok(p) => p, Err(e) => { return report.fail( Status::NeedsLogin, - format!("{e}. Inicia sesión en Gemini CLI con tu cuenta de Google."), + format!("{}. {}", e, text(locale, Msg::SignInGemini)), ) } }; - match read_json(&path) { + match read_json(locale, &path) { Ok(v) => v, Err(e) => return report.fail(Status::Error, e), } } }; - let token = match access_token(&creds, http).await { + let token = match access_token(locale, &creds, http).await { Ok(t) => t, Err(e) => return report.fail(Status::NeedsLogin, e), }; // 1. Proyecto y plan - let load = post(http, &token, "loadCodeAssist", &json!({ + let load = post(locale, http, &token, "loadCodeAssist", &json!({ "metadata": { "ideType": "IDE_UNSPECIFIED", "platform": "PLATFORM_UNSPECIFIED", "pluginType": "GEMINI" } })) .await; @@ -112,7 +114,7 @@ pub async fn fetch( Some(p) => json!({ "project": p }), None => json!({}), }; - let quota = match post(http, &token, "retrieveUserQuota", &body).await { + let quota = match post(locale, http, &token, "retrieveUserQuota", &body).await { Ok(v) => v, Err(e) => return report.fail(e.0, e.1), }; @@ -140,7 +142,11 @@ fn token_needs_refresh(creds: &Value, now_ms: i64) -> bool { expiry - 60_000 <= now_ms } -async fn access_token(creds: &Value, http: &reqwest::Client) -> Result { +async fn access_token( + locale: Locale, + creds: &Value, + http: &reqwest::Client, +) -> Result { let now = chrono::Utc::now().timestamp_millis(); if !token_needs_refresh(creds, now) { return Ok(creds @@ -152,7 +158,7 @@ async fn access_token(creds: &Value, http: &reqwest::Client) -> Result now { @@ -171,10 +177,7 @@ async fn access_token(creds: &Value, http: &reqwest::Client) -> Result Result Err(( diff --git a/src-tauri/src/providers/grok.rs b/src-tauri/src/providers/grok.rs index 8b17750a..3947c176 100644 --- a/src-tauri/src/providers/grok.rs +++ b/src-tauri/src/providers/grok.rs @@ -13,6 +13,7 @@ use super::{home, net_error, read_json, resolve_path, Who}; use crate::config::SubscriptionConfig; +use crate::i18n::{text, Locale, Msg}; use crate::model::{Kind, Meter, Status, UsageReport}; use crate::wsl::{SessionError, SessionResolver}; use chrono::{DateTime, Utc}; @@ -42,16 +43,21 @@ pub(crate) fn auth_candidates(grok_home: Option<&Path>, home: &Path) -> Vec, grok_home: Option<&Path>, home: &Path, ) -> Result { - resolve_path(credentials_path, &auth_candidates(grok_home, home)) + resolve_path(locale, credentials_path, &auth_candidates(grok_home, home)) } /// `auth_path` leyendo `GROK_HOME` del entorno (uso real; los tests inyectan). -pub(crate) fn resolved_auth_path(credentials_path: Option<&str>) -> Result { +pub(crate) fn resolved_auth_path( + locale: Locale, + credentials_path: Option<&str>, +) -> Result { auth_path( + locale, credentials_path, std::env::var_os("GROK_HOME").map(PathBuf::from).as_deref(), &home(), @@ -60,6 +66,7 @@ pub(crate) fn resolved_auth_path(credentials_path: Option<&str>) -> Result, http: &reqwest::Client, resolver: Option<&SessionResolver>, @@ -83,13 +90,19 @@ pub async fn fetch( Ok(raw) => match serde_json::from_str::(&raw) { Ok(v) => v, Err(e) => { - return report.fail(Status::Error, format!("{e}. Ejecuta «grok login».")) + return report.fail( + Status::Error, + format!("{}. {}", e, text(locale, Msg::SignInGrok)), + ) } }, // Sin credenciales en el entorno elegido: hace falta login // AQUÍ (no en otro entorno). Err(SessionError::Absent(m)) => { - return report.fail(Status::NeedsLogin, format!("{m}. Ejecuta «grok login».")) + return report.fail( + Status::NeedsLogin, + format!("{}. {}", m, text(locale, Msg::SignInGrok)), + ) } // El fallo es del subsistema o de la distro: la acción // correcta no es "inicia sesión". @@ -100,20 +113,23 @@ pub async fn fetch( } } None => { - let path = match resolved_auth_path(cfg.credentials_path.as_deref()) { + let path = match resolved_auth_path(locale, cfg.credentials_path.as_deref()) { Ok(p) => p, Err(e) => { - return report.fail(Status::NeedsLogin, format!("{e}. Ejecuta «grok login».")) + return report.fail( + Status::NeedsLogin, + format!("{}. {}", e, text(locale, Msg::SignInGrok)), + ) } }; - match read_json(&path) { + match read_json(locale, &path) { Ok(v) => v, Err(e) => return report.fail(Status::NeedsLogin, e), } } }; let now = Utc::now(); - let auth = match Auth::parse(&auth_json, now) { + let auth = match Auth::parse(locale, &auth_json, now) { Ok(a) => a, Err(e) => return report.fail(Status::NeedsLogin, e), }; @@ -131,12 +147,7 @@ pub async fn fetch( }; match res.status().as_u16() { 200 => {} - 401 | 403 => { - return report.fail( - Status::NeedsLogin, - "Sesión caducada. Ejecuta «grok login» para renovarla.", - ) - } + 401 | 403 => return report.fail(Status::NeedsLogin, text(locale, Msg::GrokSessionExpired)), 429 => { return report.fail( Status::Warning, @@ -194,7 +205,7 @@ impl Auth { /// Elige la entrada del fichero: primero una `auth.x.ai::` no caducada; /// si ninguna, el legado no caducado; si tampoco, la preferida caducada /// (para poder decir «ejecuta grok login» en vez de «no hay credenciales»). - pub fn parse(v: &Value, now: DateTime) -> Result { + pub fn parse(locale: Locale, v: &Value, now: DateTime) -> Result { let obj = v.as_object().ok_or("auth.json no es un objeto")?; let token_of = |e: Option<&Value>| -> Option { e.and_then(|e| e.get("key")) @@ -235,7 +246,7 @@ impl Auth { if let Some(t) = pick(AUTH_LEGACY) { return Ok(Auth { token: t }); } - Err("auth.json sin credenciales válidas. Ejecuta «grok login».".into()) + Err(text(locale, Msg::GrokNoCredentials).to_string()) } } @@ -341,7 +352,10 @@ mod tests { "https://accounts.x.ai/sign-in": {"key": "legacy-token", "expires_at": "2099-01-01T00:00:00Z"}, "https://auth.x.ai::abc123": {"key": "current-token", "expires_at": "2099-01-01T00:00:00Z"} })); - assert_eq!(Auth::parse(&v, now).unwrap().token, "current-token"); + assert_eq!( + Auth::parse(Locale::Es, &v, now).unwrap().token, + "current-token" + ); } #[test] @@ -350,7 +364,10 @@ mod tests { let v = auth_with(json!({ "https://accounts.x.ai/sign-in": {"key": "legacy-token", "expires_at": "2099-01-01T00:00:00Z"} })); - assert_eq!(Auth::parse(&v, now).unwrap().token, "legacy-token"); + assert_eq!( + Auth::parse(Locale::Es, &v, now).unwrap().token, + "legacy-token" + ); } #[test] @@ -361,9 +378,9 @@ mod tests { })); // Caducada: se acepta el token pero el flujo responderá NeedsLogin por // HTTP 401; aquí verificamos que no hay otra entrada que preferir. - assert_eq!(Auth::parse(&v, now).unwrap().token, "old-token"); + assert_eq!(Auth::parse(Locale::Es, &v, now).unwrap().token, "old-token"); let empty = auth_with(json!({})); - assert!(Auth::parse(&empty, now).is_err()); + assert!(Auth::parse(Locale::Es, &empty, now).is_err()); } #[test] diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index a2434a94..d17655ba 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -23,6 +23,7 @@ use crate::config::{ credentials_file_name, Account, ApiCostConfig, AppConfig, CopilotConfig, NanConfig, OpenCodeGoConfig, OpenRouterConfig, SubscriptionConfig, ZaiConfig, }; +use crate::i18n::Locale; use crate::model::{Kind, Status, UsageReport}; use crate::secrets; use crate::wsl::SessionResolver; @@ -118,6 +119,8 @@ pub async fn fetch_all( // Entorno inaccesible: los CLIs reportan el fallo en su orbe (revisión PR // #248); el resto de proveedores se consulta con normalidad. let env_error = access.unavailable(); + // Los mensajes propios de credenciales/login nacen en la locale activa. + let locale = crate::i18n::locale_from_config(&cfg.locale); let mut jobs: Vec>> = vec![]; if cfg.claude.enabled { jobs.push( @@ -126,7 +129,10 @@ pub async fn fetch_all( Some(e) => Who::main("claude") .report("Claude", Kind::Subscription) .fail(Status::Error, e), - None => claude::fetch(&cfg.claude, Who::main("claude"), http, resolver).await, + None => { + claude::fetch(&cfg.claude, locale, Who::main("claude"), http, resolver) + .await + } }] } .boxed(), @@ -139,7 +145,9 @@ pub async fn fetch_all( Some(e) => Who::main("codex") .report("ChatGPT · Codex", Kind::Subscription) .fail(Status::Error, e), - None => codex::fetch(&cfg.codex, Who::main("codex"), http, resolver).await, + None => { + codex::fetch(&cfg.codex, locale, Who::main("codex"), http, resolver).await + } }] } .boxed(), @@ -152,7 +160,10 @@ pub async fn fetch_all( Some(e) => Who::main("gemini") .report("Gemini", Kind::Subscription) .fail(Status::Error, e), - None => gemini::fetch(&cfg.gemini, Who::main("gemini"), http, resolver).await, + None => { + gemini::fetch(&cfg.gemini, locale, Who::main("gemini"), http, resolver) + .await + } }] } .boxed(), @@ -165,7 +176,7 @@ pub async fn fetch_all( Some(e) => Who::main("grok") .report("Grok", Kind::Subscription) .fail(Status::Error, e), - None => grok::fetch(&cfg.grok, Who::main("grok"), http, resolver).await, + None => grok::fetch(&cfg.grok, locale, Who::main("grok"), http, resolver).await, }] } .boxed(), @@ -173,7 +184,7 @@ pub async fn fetch_all( } if cfg.cursor.enabled { jobs.push( - async move { vec![cursor::fetch(&cfg.cursor, Who::main("cursor"), http).await] } + async move { vec![cursor::fetch(&cfg.cursor, locale, Who::main("cursor"), http).await] } .boxed(), ); } @@ -266,32 +277,33 @@ pub async fn fetch_one( } let resolver = access.resolver(); let env_error = access.unavailable(); + let locale = crate::i18n::locale_from_config(&cfg.locale); Some(match id { "claude" => match env_error { Some(e) => Who::main("claude") .report("Claude", Kind::Subscription) .fail(Status::Error, e), - None => claude::fetch(&cfg.claude, Who::main("claude"), http, resolver).await, + None => claude::fetch(&cfg.claude, locale, Who::main("claude"), http, resolver).await, }, "codex" => match env_error { Some(e) => Who::main("codex") .report("ChatGPT · Codex", Kind::Subscription) .fail(Status::Error, e), - None => codex::fetch(&cfg.codex, Who::main("codex"), http, resolver).await, + None => codex::fetch(&cfg.codex, locale, Who::main("codex"), http, resolver).await, }, "gemini" => match env_error { Some(e) => Who::main("gemini") .report("Gemini", Kind::Subscription) .fail(Status::Error, e), - None => gemini::fetch(&cfg.gemini, Who::main("gemini"), http, resolver).await, + None => gemini::fetch(&cfg.gemini, locale, Who::main("gemini"), http, resolver).await, }, "grok" => match env_error { Some(e) => Who::main("grok") .report("Grok", Kind::Subscription) .fail(Status::Error, e), - None => grok::fetch(&cfg.grok, Who::main("grok"), http, resolver).await, + None => grok::fetch(&cfg.grok, locale, Who::main("grok"), http, resolver).await, }, - "cursor" => cursor::fetch(&cfg.cursor, Who::main("cursor"), http).await, + "cursor" => cursor::fetch(&cfg.cursor, locale, Who::main("cursor"), http).await, "copilot" => copilot::fetch(&cfg.copilot, Who::main("copilot"), http).await, "nan" => nan::fetch(&cfg.nan, Who::main("nan"), http).await, "openrouter" => openrouter::fetch(&cfg.openrouter, Who::main("openrouter"), http).await, @@ -312,6 +324,7 @@ pub async fn fetch_one( /// o Gemini (por proveedor) o una adicional (por id). `None` si no usa CLI. /// `home` se inyecta para poder probar con carpetas propias. pub fn session_file(cfg: &AppConfig, id: &str, home: &Path) -> Option { + let locale = crate::i18n::locale_from_config(&cfg.locale); if let Some(a) = cfg.accounts.iter().find(|a| a.id == id) { return a.credentials_file(home); } @@ -328,12 +341,12 @@ pub fn session_file(cfg: &AppConfig, id: &str, home: &Path) -> Option { &cfg.claude, home.join(".claude").join(".credentials.json"), )), - "codex" => codex::resolved_auth_path(cfg.codex.credentials_path.as_deref()).ok(), + "codex" => codex::resolved_auth_path(locale, cfg.codex.credentials_path.as_deref()).ok(), "gemini" => Some(main( &cfg.gemini, home.join(".gemini").join("oauth_creds.json"), )), - "grok" => grok::resolved_auth_path(cfg.grok.credentials_path.as_deref()).ok(), + "grok" => grok::resolved_auth_path(locale, cfg.grok.credentials_path.as_deref()).ok(), _ => None, } } @@ -434,6 +447,7 @@ fn fetch_account<'a>( access: SessionAccess<'a>, ) -> BoxFuture<'a, UsageReport> { let who = Who::extra(a); + let locale = crate::i18n::locale_from_config(&cfg.locale); // Algunas cuentas adicionales son de proveedores sin sesión CLI (Copilot, // APIs…): su fetch no depende del ENTORNO y no le aplica el fallo de WSL // (revisión PR #248). Las de proveedores CLI sí: su sesión vive en la @@ -471,20 +485,25 @@ fn fetch_account<'a>( }; match a.provider.as_str() { "claude" => { - async move { claude::fetch(&session(&cfg.claude), who, http, resolver).await }.boxed() + async move { claude::fetch(&session(&cfg.claude), locale, who, http, resolver).await } + .boxed() } "codex" => { - async move { codex::fetch(&session(&cfg.codex), who, http, resolver).await }.boxed() + async move { codex::fetch(&session(&cfg.codex), locale, who, http, resolver).await } + .boxed() } "gemini" => { - async move { gemini::fetch(&session(&cfg.gemini), who, http, resolver).await }.boxed() + async move { gemini::fetch(&session(&cfg.gemini), locale, who, http, resolver).await } + .boxed() } "grok" => { - async move { grok::fetch(&session(&cfg.grok), who, http, resolver).await }.boxed() + async move { grok::fetch(&session(&cfg.grok), locale, who, http, resolver).await } + .boxed() } // Solo con su token: la sesión de la app de Cursor es la de la cuenta principal. "cursor" => { - async move { cursor::fetch(&SubscriptionConfig::default(), who, http).await }.boxed() + async move { cursor::fetch(&SubscriptionConfig::default(), locale, who, http).await } + .boxed() } "copilot" => { let c = CopilotConfig { @@ -570,8 +589,10 @@ pub(crate) fn unix_to_rfc3339(secs: i64) -> Option { Utc.timestamp_opt(secs, 0).single().map(|d| d.to_rfc3339()) } -/// Ruta explícita si existe; si no, la primera candidata que exista. +/// Ruta explícita si existe; si no, la primera candidata que exista. Los +/// mensajes nacen en la locale activa (L4, #66); las rutas van literales. pub(crate) fn resolve_path( + locale: Locale, explicit: Option<&str>, candidates: &[PathBuf], ) -> Result { @@ -580,7 +601,10 @@ pub(crate) fn resolve_path( return if p.is_file() { Ok(p) } else { - Err(format!("No existe {}", p.display())) + Err(crate::i18n::path_not_found( + locale, + &p.display().to_string(), + )) }; } candidates @@ -589,14 +613,16 @@ pub(crate) fn resolve_path( .cloned() .ok_or_else(|| { let list: Vec = candidates.iter().map(|p| p.display().to_string()).collect(); - format!("No encuentro credenciales en: {}", list.join(", ")) + crate::i18n::credentials_not_found(locale, &list.join(", ")) }) } -pub(crate) fn read_json(path: &Path) -> Result { - let raw = std::fs::read_to_string(path) - .map_err(|e| format!("No puedo leer {}: {e}", path.display()))?; - serde_json::from_str(&raw).map_err(|e| format!("JSON inválido en {}: {e}", path.display())) +pub(crate) fn read_json(locale: Locale, path: &Path) -> Result { + let raw = std::fs::read_to_string(path).map_err(|e| { + crate::i18n::cannot_read(locale, &path.display().to_string(), &e.to_string()) + })?; + serde_json::from_str(&raw) + .map_err(|e| crate::i18n::invalid_json(locale, &path.display().to_string(), &e.to_string())) } /// Huella de los ficheros de sesión de los CLIs (Claude Code, Codex, Gemini) de @@ -620,6 +646,7 @@ pub async fn session_stamp(cfg: &AppConfig, resolver: Option<&SessionResolver>) /// Sello del entorno host: suma de mtimes de los ficheros de sesión. fn host_session_stamp(cfg: &AppConfig) -> u64 { + let locale = crate::i18n::locale_from_config(&cfg.locale); let h = home(); let main = |c: &SubscriptionConfig, default: PathBuf| match c .credentials_path @@ -639,7 +666,7 @@ fn host_session_stamp(cfg: &AppConfig) -> u64 { if cfg.codex.enabled { // Mismo resolver que `codex::fetch`: así el sello observa el fichero // que de verdad se lee (incluido el respaldo ~/.codex/auth.json). - if let Ok(p) = codex::resolved_auth_path(cfg.codex.credentials_path.as_deref()) { + if let Ok(p) = codex::resolved_auth_path(locale, cfg.codex.credentials_path.as_deref()) { files.push(p); } } @@ -652,7 +679,7 @@ fn host_session_stamp(cfg: &AppConfig) -> u64 { if cfg.grok.enabled { // Mismo resolver que `grok::fetch`: el sello observa el fichero que de // verdad se lee (incluido el respaldo ~/.grok/auth.json). - if let Ok(p) = grok::resolved_auth_path(cfg.grok.credentials_path.as_deref()) { + if let Ok(p) = grok::resolved_auth_path(locale, cfg.grok.credentials_path.as_deref()) { files.push(p); } } @@ -765,6 +792,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let cfg = AppConfig { claude: SubscriptionConfig { @@ -800,6 +828,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let cfg = AppConfig { claude: SubscriptionConfig { @@ -835,6 +864,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let cfg = AppConfig { accounts: vec![Account { @@ -891,6 +921,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let cfg = AppConfig { accounts: vec![Account { @@ -993,6 +1024,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let mk = |dir: Option| Account { id: "claude:w1".into(), @@ -1034,6 +1066,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let a = Account { id: "openrouter:w1".into(), @@ -1058,6 +1091,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let mk = |id: &str| Account { id: id.into(), @@ -1210,11 +1244,181 @@ mod tests { PathBuf::from("/home/u/.claude/.credentials.json"), PathBuf::from("/var/lib/creds x.json"), ]; - let err = resolve_path(Some("/no existe/ruta con espacios.json"), &candidates).unwrap_err(); + let err = resolve_path( + Locale::Es, + Some("/no existe/ruta con espacios.json"), + &candidates, + ) + .unwrap_err(); // La ruta con espacios y la lista de candidatos aparecen en el mensaje. assert!(err.contains("/no existe/ruta con espacios.json")); } + /// L4 (#66): los errores de `resolve_path` nacen en la locale activa; + /// las rutas viajan literales en ambos idiomas. + #[test] + fn resolve_path_errors_follow_the_locale() { + let candidates = [PathBuf::from("/home/u/.claude/.credentials.json")]; + assert_eq!( + resolve_path(Locale::Es, None, &candidates).unwrap_err(), + "No encuentro credenciales en: /home/u/.claude/.credentials.json" + ); + assert_eq!( + resolve_path(Locale::En, None, &candidates).unwrap_err(), + "No credentials found in: /home/u/.claude/.credentials.json" + ); + assert_eq!( + resolve_path(Locale::En, Some("/no/hay.json"), &candidates).unwrap_err(), + "Path not found: /no/hay.json" + ); + } + + /// L4 (#66, reporte de ludevdot): con la app en inglés y sin sesión de + /// Claude disponible, tanto el error de credenciales como la indicación + /// de login llegan en inglés; la ruta viaja literal. La ruta explícita + /// inexistente evita el respaldo de Keychain y hace el test hermético. + #[test] + fn claude_login_messages_follow_the_app_locale() { + let cfg = AppConfig { + locale: "en".into(), + claude: SubscriptionConfig { + enabled: true, + credentials_path: Some("/no/existe/quorb-l4-en.json".into()), + ..Default::default() + }, + ..Default::default() + }; + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime de un hilo"); + let http = reqwest::Client::new(); + let report = rt + .block_on(fetch_one(&cfg, "claude", &http, SessionAccess::Host)) + .expect("informe de claude"); + assert_eq!(report.status, Status::NeedsLogin); + assert_eq!( + report.message.as_deref(), + Some("Path not found: /no/existe/quorb-l4-en.json. Sign in to Claude Code.") + ); + } + + /// S5.1 (review #272): consulta `id` con `fetch_one` apuntando su ruta de + /// credenciales a un fichero con `contents`, y la app en `locale`. Ninguna + /// de las rutas probadas llega a la red: el fallo es local. + fn fetch_with_credentials(id: &str, locale: &str, tag: &str, contents: &str) -> UsageReport { + let dir = temp_dir(tag); + let file = dir.join("creds.json"); + std::fs::write(&file, contents).unwrap(); + let sub = SubscriptionConfig { + enabled: true, + credentials_path: Some(file.to_string_lossy().into_owned()), + ..Default::default() + }; + let mut cfg = AppConfig { + locale: locale.into(), + ..Default::default() + }; + match id { + "claude" => cfg.claude = sub, + "codex" => cfg.codex = sub, + "gemini" => cfg.gemini = sub, + "grok" => cfg.grok = sub, + other => panic!("proveedor sin ruta de credenciales en el test: {other}"), + } + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("runtime de un hilo"); + let http = reqwest::Client::new(); + let report = rt + .block_on(fetch_one(&cfg, id, &http, SessionAccess::Host)) + .expect("informe del proveedor"); + let _ = std::fs::remove_dir_all(&dir); + report + } + + /// S5.1: el reporte exacto del revisor — con la app en `en`, un `auth.json` + /// con `{}` mostraba el mensaje en español. Codex y Grok lo dicen en la + /// locale de la app; en `es` el literal original no cambia. + #[test] + fn codex_and_grok_empty_auth_json_follows_the_app_locale() { + for (id, en, es) in [ + ( + "codex", + "auth.json has no tokens. Run “codex login”.", + "auth.json sin tokens. Ejecuta «codex login».", + ), + ( + "grok", + "auth.json has no valid credentials. Run “grok login”.", + "auth.json sin credenciales válidas. Ejecuta «grok login».", + ), + ] { + let report = fetch_with_credentials(id, "en", &format!("{id}-empty-en"), "{}"); + assert_eq!(report.status, Status::NeedsLogin, "{id} en"); + assert_eq!(report.message.as_deref(), Some(en), "{id} en"); + let report = fetch_with_credentials(id, "es", &format!("{id}-empty-es"), "{}"); + assert_eq!(report.status, Status::NeedsLogin, "{id} es"); + assert_eq!(report.message.as_deref(), Some(es), "{id} es"); + } + } + + /// S5.1: Codex con solo API key también sigue la locale. + #[test] + fn codex_api_key_only_auth_json_follows_the_app_locale() { + let raw = "{\"OPENAI_API_KEY\":\"sk-test\"}"; + let en = fetch_with_credentials("codex", "en", "codex-apikey-en", raw); + assert_eq!( + en.message.as_deref(), + Some("Codex is authenticated with an API key, not with your ChatGPT account. Run “codex login”.") + ); + let es = fetch_with_credentials("codex", "es", "codex-apikey-es", raw); + assert_eq!( + es.message.as_deref(), + Some("Codex está autenticado con API key, no con tu cuenta de ChatGPT. Ejecuta «codex login».") + ); + } + + /// S5.1: sesión de Claude caducada (el token local expiró, sin red) y + /// credenciales sin `claudeAiOauth`. + #[test] + fn claude_expired_and_api_key_credentials_follow_the_app_locale() { + let expired = "{\"claudeAiOauth\":{\"accessToken\":\"t\",\"expiresAt\":1}}"; + let en = fetch_with_credentials("claude", "en", "claude-expired-en", expired); + assert_eq!(en.status, Status::NeedsLogin); + assert_eq!( + en.message.as_deref(), + Some("The session has expired. “Renew session” opens Claude Code, which renews it; Quorb updates itself.") + ); + let es = fetch_with_credentials("claude", "es", "claude-expired-es", expired); + assert_eq!( + es.message.as_deref(), + Some("La sesión ha caducado. «Renovar sesión» abre Claude Code, que la renueva; Quorb se actualiza solo.") + ); + let en = fetch_with_credentials("claude", "en", "claude-nooauth-en", "{}"); + assert_eq!( + en.message.as_deref(), + Some("Credentials without “claudeAiOauth” (signed in with an API key?)") + ); + } + + /// S5.1: Gemini sin `refresh_token` y con el acceso caducado (sin red). + #[test] + fn gemini_expired_session_follows_the_app_locale() { + let en = fetch_with_credentials("gemini", "en", "gemini-expired-en", "{}"); + assert_eq!(en.status, Status::NeedsLogin); + assert_eq!( + en.message.as_deref(), + Some("The Gemini CLI session has expired. Open it to renew it.") + ); + let es = fetch_with_credentials("gemini", "es", "gemini-expired-es", "{}"); + assert_eq!( + es.message.as_deref(), + Some("La sesión de Gemini CLI ha caducado. Ábrelo para renovarla.") + ); + } + #[test] fn month_start_is_first_day_midnight() { let now = Utc.with_ymd_and_hms(2026, 10, 6, 15, 30, 0).unwrap(); diff --git a/src-tauri/src/wsl/session.rs b/src-tauri/src/wsl/session.rs index d3af05ca..9c9c8ade 100644 --- a/src-tauri/src/wsl/session.rs +++ b/src-tauri/src/wsl/session.rs @@ -18,6 +18,7 @@ //! disco; ninguno importa el valor a otro lado. use super::{guest_path_problem, join_guest_path, WslAdapter, WslError}; +use crate::i18n::Locale; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -76,19 +77,33 @@ pub struct SessionResolver { adapter: Arc, /// Home del entorno elegido: el del host, o el del usuario de la distro. home: PathBuf, + /// Locale de la app: los mensajes de sesión (`Absent`, `Unreadable`) + /// nacen en el idioma activo (L4, #66). + locale: Locale, } impl SessionResolver { /// `home` es el home del entorno: el del host en modo host, o el del /// usuario por defecto de la distro (lo resuelve `resolve_home`). - pub fn new(env: SessionEnv, adapter: Arc, home: PathBuf) -> Self { - SessionResolver { env, adapter, home } + /// `locale` traduce los mensajes de sesión al idioma activo. + pub fn new( + env: SessionEnv, + adapter: Arc, + home: PathBuf, + locale: Locale, + ) -> Self { + SessionResolver { + env, + adapter, + home, + locale, + } } /// Resolvedor del entorno host: lee del disco local con el home del host. /// El `adapter` no se usa en este modo (queda por si el entorno cambia). - pub fn for_host(adapter: Arc, home: PathBuf) -> Self { - SessionResolver::new(SessionEnv::Host, adapter, home) + pub fn for_host(adapter: Arc, home: PathBuf, locale: Locale) -> Self { + SessionResolver::new(SessionEnv::Host, adapter, home, locale) } /// Resolvedor de la distro elegida (#91): la sesión se resuelve y se lee @@ -98,8 +113,13 @@ impl SessionResolver { /// `resolve_home` (F7): este constructor no hace I/O, así que puede /// fallar quien lo llama con un mensaje acorde al contexto (la UI, la /// línea de comandos) en vez de un error genérico de WSL. - pub fn for_wsl(adapter: Arc, distro: String, home: PathBuf) -> Self { - SessionResolver::new(SessionEnv::Wsl { distro }, adapter, home) + pub fn for_wsl( + adapter: Arc, + distro: String, + home: PathBuf, + locale: Locale, + ) -> Self { + SessionResolver::new(SessionEnv::Wsl { distro }, adapter, home, locale) } /// El home del entorno elegido. @@ -162,23 +182,30 @@ impl SessionResolver { match &self.env { SessionEnv::Host => { if !path.is_file() { - return Err(SessionError::Absent(format!( - "No encuentro credenciales en {}", - path.display() + return Err(SessionError::Absent(crate::i18n::credentials_not_found_at( + self.locale, + &path.display().to_string(), ))); } std::fs::read_to_string(path).map_err(|e| { - SessionError::Unreadable(format!("No puedo leer {}: {e}", path.display())) + SessionError::Unreadable(crate::i18n::cannot_read( + self.locale, + &path.display().to_string(), + &e.to_string(), + )) }) } SessionEnv::Wsl { distro } => match self.adapter.read_file(distro, path) { Ok(contents) => Ok(contents), // El fichero no existe en la distro: es un "necesita login", // no un fallo de WSL. - Err(WslError::FileNotFound(_)) => Err(SessionError::Absent(format!( - "No encuentro credenciales en {distro}: {}", - path.display() - ))), + Err(WslError::FileNotFound(_)) => Err(SessionError::Absent( + crate::i18n::credentials_not_found_in_distro( + self.locale, + distro, + &path.display().to_string(), + ), + )), // Distro desconocida / WSL sin instalar: el fallo es del // subsistema, y la acción correcta es distinta de "login". Err(e) => Err(SessionError::Wsl(e)), @@ -200,8 +227,10 @@ impl SessionResolver { let display = path.display().to_string(); match tokio::task::spawn_blocking(move || me.read(&path)).await { Ok(result) => result, - Err(e) => Err(SessionError::Unreadable(format!( - "No puedo leer {display}: {e}" + Err(e) => Err(SessionError::Unreadable(crate::i18n::cannot_read( + self.locale, + &display, + &e.to_string(), ))), } } @@ -219,6 +248,7 @@ mod tests { SessionEnv::Host, mock.clone(), PathBuf::from("/home/hostuser"), + Locale::Es, ); let f = std::env::temp_dir().join("quorb-session-host-test.json"); std::fs::write(&f, b"{}").expect("escribe fixture"); @@ -233,11 +263,28 @@ mod tests { SessionEnv::Host, mock.clone(), PathBuf::from("/home/hostuser"), + Locale::Es, ); let missing = PathBuf::from("/no/existe/quorb-creds.json"); assert!(matches!(r.read(&missing), Err(SessionError::Absent(_)))); } + /// L4 (#66): el mensaje de «sin credenciales» nace en la locale del + /// resolvedor — inglés cuando la app está en `en`, con la ruta literal. + #[test] + fn absent_messages_follow_the_resolver_locale() { + let mock = Arc::new(MockWslAdapter::new()); + let host = + SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser"), Locale::En); + let missing = PathBuf::from("/no/existe/quorb-creds-en.json"); + assert_eq!( + host.read(&missing), + Err(SessionError::Absent( + "No credentials found in /no/existe/quorb-creds-en.json".into() + )) + ); + } + /// #91 (camino 1): el MISMO path significa dos cosas según el entorno — en /// la distro se lee el fichero de la distro, en el host el del host. Las /// cuentas de un entorno nunca se mezclan con las del otro. @@ -252,13 +299,15 @@ mod tests { "{\"origen\":\"distro\"}".to_string(), ); - let host = SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser")); + let host = + SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser"), Locale::Es); assert_eq!(host.read(&path).expect("lee host"), "{\"origen\":\"host\"}"); let wsl = SessionResolver::for_wsl( mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); assert_eq!( wsl.read(&path).expect("lee distro"), @@ -277,12 +326,14 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); assert_eq!( wsl.default_path(guest_relative(&[".claude", ".credentials.json"]).as_path()), PathBuf::from("/home/user/.claude/.credentials.json") ); - let host = SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser")); + let host = + SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser"), Locale::Es); assert_eq!( host.default_path(guest_relative(&[".codex", "auth.json"]).as_path()), PathBuf::from("/home/hostuser/.codex/auth.json") @@ -300,6 +351,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); for relative in [ ".claude/.credentials.json", @@ -330,6 +382,7 @@ mod tests { }, mock.clone(), PathBuf::from("/home/user"), + Locale::Es, ); let contents = r .read(Path::new("/home/user/.claude/.credentials.json")) @@ -351,6 +404,7 @@ mod tests { }, mock.clone(), PathBuf::from("/home/user"), + Locale::Es, ); // El fichero de Claude no está en la distro: "necesita login", no // un fallo de WSL. @@ -371,6 +425,7 @@ mod tests { }, mock.clone(), PathBuf::from("/home/user"), + Locale::Es, ); let err = r .read(Path::new("/home/user/.claude/.credentials.json")) @@ -385,6 +440,7 @@ mod tests { SessionEnv::Host, mock.clone(), PathBuf::from("/home/hostuser"), + Locale::Es, ); let p = r .resolve( @@ -402,6 +458,7 @@ mod tests { SessionEnv::Host, mock.clone(), PathBuf::from("/home/hostuser"), + Locale::Es, ); let p = r .resolve(Some(" "), Path::new("/home/u/default.json")) @@ -420,6 +477,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); for bad in [ r"\\wsl.localhost\Ubuntu\home\user\.claude\.credentials.json", @@ -442,7 +500,8 @@ mod tests { ) .is_ok()); // En host, la ruta explícita de Windows sigue siendo válida (legado). - let host = SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser")); + let host = + SessionResolver::for_host(mock.clone(), PathBuf::from("/home/hostuser"), Locale::Es); assert_eq!( host.resolve( Some(r"C:\Users\yo\.claude\.credentials.json"), @@ -468,6 +527,7 @@ mod tests { mock.clone(), "Ubuntu-22.04".into(), PathBuf::from("/home/user"), + Locale::Es, ); let path = PathBuf::from("/home/user/.claude/.credentials.json"); let rt = tokio::runtime::Builder::new_current_thread() diff --git a/src/lib/widget-refresh.test.ts b/src/lib/widget-refresh.test.ts index e10d8a57..6e5de3bc 100644 --- a/src/lib/widget-refresh.test.ts +++ b/src/lib/widget-refresh.test.ts @@ -66,6 +66,15 @@ describe('widget refresh discriminator', () => { expect(envKey(null)).toBe(''); }); + it('refreshes when the LANGUAGE changes, and not when it stays the same', () => { + // Revisión PR #272: el backend traduce los mensajes propios al hacer fetch + // y quedan en el informe; sin la locale en la clave el widget seguía + // mostrándolos en el idioma anterior hasta el siguiente sondeo. + const es = cfg({ locale: 'es' } as Partial); + expect(needsRefresh(es, cfg({ locale: 'en' } as Partial))).toBe(true); + expect(needsRefresh(es, cfg({ locale: 'es' } as Partial))).toBe(false); + }); + it('handles a null previous config', () => { expect(dataKey(null)).toBe(''); expect(needsRefresh(null, cfg())).toBe(true); diff --git a/src/lib/widget-refresh.ts b/src/lib/widget-refresh.ts index 85de1ec7..a0a13060 100644 --- a/src/lib/widget-refresh.ts +++ b/src/lib/widget-refresh.ts @@ -9,10 +9,14 @@ import type { AppConfig } from './types'; * El ENTORNO (host/WSL y la distro) también invalida los informes (revisión PR * #248): los datos de un entorno no valen para el otro, y sin esta clave el * widget seguiría mostrando la lectura del entorno anterior. + * + * El IDIOMA también (revisión PR #272): el backend traduce los mensajes + * propios de los proveedores al hacer fetch y quedan guardados en el informe; + * sin la locale en la clave, cambiar de idioma no los refrescaría. */ export function dataKey(c: AppConfig | null): string { return c - ? JSON.stringify([c.sessionEnv, c.wslDistro, c.claude, c.codex, c.gemini, c.cursor, c.grok, c.copilot, c.openrouter, c.anthropicApi, c.openaiApi, c.nan, c.minimax, c.nineRouter, c.zai, c.opencodeGo, c.antigravity]) + ? JSON.stringify([c.locale, c.sessionEnv, c.wslDistro, c.claude, c.codex, c.gemini, c.cursor, c.grok, c.copilot, c.openrouter, c.anthropicApi, c.openaiApi, c.nan, c.minimax, c.nineRouter, c.zai, c.opencodeGo, c.antigravity]) : ''; }