diff --git a/README.es.md b/README.es.md index 57b48eb..21056f2 100644 --- a/README.es.md +++ b/README.es.md @@ -189,7 +189,7 @@ Las API keys y la sesión de NaN se guardan en el almacén seguro del sistema (W La configuración y el historial se guardan en la carpeta de usuario de cada plataforma (`%APPDATA%\es.egdev.quorb` en Windows, `~/.config/es.egdev.quorb` en Linux). Quorb consulta directamente los endpoints de los proveedores; no requiere un backend separado. El historial cubre hasta 30 días. -Para sesiones en WSL, configurad las rutas de credenciales en Ajustes como **rutas POSIX dentro de la distro** — el guest no puede leer `\\wsl.localhost\…` (UNC) ni `C:\…`; por ejemplo `/home/YOUR_USER/.codex/auth.json` para un usuario de WSL llamado `YOUR_USER`, y el comando de login `wsl codex login` o `wsl claude` según corresponda. +Para sesiones en WSL, elegid la distro en Ajustes y configurad las rutas de credenciales como **rutas POSIX dentro de la distro** — el guest no puede leer `\\wsl.localhost\…` (UNC) ni `C:\…`; por ejemplo `/home/YOUR_USER/.codex/auth.json` para un usuario de WSL llamado `YOUR_USER`. Indicad el comando de login `codex login` o `claude` según corresponda; Quorb lo ejecuta dentro de la distro elegida. Un comando que ya incluya `wsl`, como `wsl codex login`, es solo para el modo host. ### Hoja de ruta diff --git a/README.md b/README.md index 031be99..697eb1b 100644 --- a/README.md +++ b/README.md @@ -187,7 +187,7 @@ API keys and the NaN session are stored in the system's secure store (Windows Cr Configuration and history are stored under the platform user directory (`%APPDATA%\es.egdev.quorb` on Windows, `~/.config/es.egdev.quorb` on Linux). Quorb calls provider endpoints directly; no separate backend is required. History covers up to 30 days. -For WSL sessions, configure the credential file paths in Settings as **POSIX paths inside the distro** — the guest cannot read `\\wsl.localhost\…` (UNC) or `C:\…` paths; for example `/home/YOUR_USER/.codex/auth.json` for a WSL user named `YOUR_USER`, and set the login command to `wsl codex login` or `wsl claude` as appropriate. +For WSL sessions, select the distro in Settings and configure credential file paths as **POSIX paths inside the distro** — the guest cannot read `\\wsl.localhost\…` (UNC) or `C:\…` paths; for example `/home/YOUR_USER/.codex/auth.json` for a WSL user named `YOUR_USER`. Set the login command to `codex login` or `claude` as appropriate; Quorb runs it inside the selected distro. An explicitly wrapped command such as `wsl codex login` is only for host mode. ### Roadmap diff --git a/docs/account-onboarding.md b/docs/account-onboarding.md index a99b8c6..4ed29df 100644 --- a/docs/account-onboarding.md +++ b/docs/account-onboarding.md @@ -112,3 +112,12 @@ En **Avanzado · carpeta de sesión** puedes fijar una carpeta propia. Quorb lee fichero de sesión que haya dentro. Si el widget pide renovar la sesión, usa **Renovar sesión** para abrir el login del CLI. La presencia del fichero no confirma la validez del acceso ni el estado del refresco OAuth de cada proveedor. + +En la cuenta principal, una ruta válida con el nombre estándar del CLI determina +la carpeta de sesión del login. En host, si usas otro nombre con un comando +avanzado, Quorb no impone una carpeta: el comando debe escribir en la ruta +configurada. En WSL se exige una ruta absoluta del guest y el nombre estándar +del CLI. + +Para validar el flujo interactivo de una cuenta adicional en Windows/WSL, sigue +la [guía de validación de login en WSL](./wsl-login-validation.md). diff --git a/docs/i18n-inventory.md b/docs/i18n-inventory.md index 0587a5c..145e8d6 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/` = `5e4e9abe1b08e5441dc3f5713f61994638892dba` and `src-tauri/src/` = `3d3244970ccdb37017a5a1907eee35d098650ce5`. +Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `07e55c6cc614d6914d4f11a998643fdebaf0ccdb` and `src-tauri/src/` = `b521502e120af9343ae15942001605911809f9a2`. 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`. @@ -18,9 +18,9 @@ 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/`) | 601 | 739 | -| Total | 1682 | 1958 | +| React (`src/`) | 1125 | 1227 | +| Rust (`src-tauri/src/`) | 610 | 763 | +| Total | 1696 | 1990 | ## src-tauri/src/channel.rs @@ -244,6 +244,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Abrir el más cargado - Actualizar - Cuenta de NaN no válida +- El modo WSL no usa el instalador de Codex de Windows: instala Codex dentro de la distro (p. ej. `sudo npm i -g @openai/codex`). La instalación automática en WSL queda fuera de alcance. - Idioma / Language · {channel} - La distro «{distro}» no está en marcha: arráncala (o haz login) para leer sus sesiones - La distro «{distro}» no está instalada en WSL @@ -255,6 +256,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - No existe el widget - No existe la ventana de efectos - No hay archivo para el efecto propio de este aviso +- No pude abrir la terminal: {e} - No se pudo aplicar «siempre encima»: {detail} - Surface clip UI callback was dropped - WSL: {e:?} @@ -275,21 +277,30 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Comando de login vacío (revísalo en Ajustes) - Comando de login vacío (revísalo en Ajustes). - El comando de login contiene caracteres de control (revísalo en Ajustes) +- El comando de login de {provider} ya incluye `wsl`: en modo WSL escribe el comando del CLI dentro de la distro (por ejemplo `codex login`) y elige la distro en Ajustes; Quorb lo ejecuta dentro de ella. - El proveedor {other} no tiene login por CLI - Instala Claude Code (curl -fsSL https://claude.ai/install.sh \| bash) o con tu gestor de paquetes (p. ej. sudo apt install claude-code) - Instala Claude Code (en PowerShell: irm https://claude.ai/install.ps1 \| iex) - Instala Gemini CLI con: npm install -g @google/gemini-cli (necesita Node.js) - Instala el CLI de Codex con: npm install -g @openai/codex (necesita Node.js) - Instala su CLI o cambia el comando de login en la cuenta principal +- La carpeta de la cuenta {} no es válida en modo WSL: {problem} - La cuenta «{}» no tiene login por CLI +- La ruta de credenciales de {id} debe terminar en el fichero del CLI ({file}): así el login escribe donde Quorb lee +- La ruta de credenciales de {id} no es válida en modo WSL: {problem} - No encuentro un emulador de terminal (x-terminal-emulator, gnome-terminal o konsole) en este equipo. Instala uno o ejecuta el login a mano en tu terminal. - No encuentro «{program}» en este equipo. {} y vuelve a pulsar «Iniciar sesión». - No pude abrir la terminal ({terminal}): {e} - No pude abrir la terminal: {e} - No pude crear {}: {e} +- WSL no está disponible en esta plataforma +- WSL: la distro «{}» no está instalada +- WSL: {e:?} - export PATH={}:"$PATH"; - export {var}={}; +- mkdir -p -- "$1" && shift && "$@"; exec "${SHELL:-/bin/sh}" - tell application "Terminal" to do script "{}" +- «{program}» no está instalado dentro de «{distro}». Instálalo en la distro (la instalación automática en WSL queda fuera de alcance y aquí no se ejecuta el instalador de Windows). Vuelve a pulsar «Iniciar sesión» una vez instalado. Proveedor: {provider} ## src-tauri/src/providers/anthropic_api.rs @@ -820,6 +831,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Path - getent passwd sin campo home - la distro configurada no aparece en la enumeración; disponibles: {} +- sonda command -v inesperada (exit {}) - wsl.exe devolvió la salida en UTF-16 (WSL_UTF8 no soportado) - wsl.exe no devolvió el usuario por defecto de la distro - wsl.exe no soporta --version (build antigua, sin WSL2) @@ -890,6 +902,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - WSL - Wayland - cloud.nan.builders +- curl -fsSL https://claude.ai/install.sh \| bash - egdev.es - egdev6 - grok login @@ -897,6 +910,9 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - minimaxi.com - nan_community - nan_member +- npm install -g @google/gemini-cli +- npm install -g @openai/codex +- npm install -g @vibe-kit/grok-cli - openrouter.ai › Keys - z.ai - z.ai › API Keys @@ -1325,6 +1341,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - The installer is working in another window. - The month has just started - The resets balance always stays available in the detail panel. +- The session host is WSL: Windows installers do not apply. Install it inside the distro (for example, in a WSL terminal) and press "Sign in" again. - The window has just started - They arrive signed from - They work even when Quorb is not focused. @@ -1354,7 +1371,6 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Video or animated image - Videos only. - WSL distro -- WSL mode: for now the CLI detection and this login use the Windows CLI. Reading the session inside the distro arrives with #92. - Wait for it to finish; Quorb detects it on its own. - We have sent you a link. Copy it (without opening it) and paste it here. - Week @@ -1413,6 +1429,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - {label}: {value}. Press to change it - {name} API key - {name} details +- {name} is missing inside the WSL distro{distro}. - {name} is missing on this computer. - {name}: session expired - · hidden in the widget @@ -1599,6 +1616,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Efecto - Efecto propio - Efecto propio (vídeo o imagen animada) +- El entorno de sesión es WSL: los instaladores de Windows no aplican. Instálalo dentro de la distro (por ejemplo, en una terminal de WSL) y vuelve a pulsar «Iniciar sesión». - El fichero existe, pero no confirma que la sesión siga siendo válida: míralo en la comprobación de abajo. - El instalador está trabajando en otra ventana. - El saldo de resets siempre sigue disponible en el panel de detalle. @@ -1626,6 +1644,7 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Falta Codex CLI en este equipo. - Falta completar un paso - Falta conectar +- Falta {name} dentro de la distro WSL{distro}. - Falta {name} en este equipo. - Fichero auth.json - Fichero de credenciales @@ -1692,7 +1711,6 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Límites de 5 h y semanales de tu plan de ChatGPT en Codex. Quorb lee la sesión que guarda el CLI de Codex. - Límites de sesión (5 h), semanales y por modelo de tu plan. Quorb lee la sesión que guarda Claude Code: no ve tu contraseña ni toca los tokens. - Mediano -- Modo WSL: por ahora la detección del CLI y este login usan el CLI de Windows. Leer la sesión dentro de la distro llega con #92. - Mostrar Quorb - Mostrar cada sub-proveedor como su propia cuenta - Mostrar en el widget @@ -1933,10 +1951,12 @@ tuples (e.g. the `"req"` unit in `providers/nan.rs`) are only listed when they a - Codex CLI - Cuenta ${…} - Gemini CLI +- Grok CLI - Quorb - irm https://claude.ai/install.ps1 \| iex - npm install -g @google/gemini-cli - npm install -g @openai/codex +- npm install -g @vibe-kit/grok-cli ## src/lib/alerts.ts diff --git a/docs/wsl-login-validation.md b/docs/wsl-login-validation.md new file mode 100644 index 0000000..a1a1936 --- /dev/null +++ b/docs/wsl-login-validation.md @@ -0,0 +1,31 @@ +# Validate an additional-account login in WSL + +Real acceptance requires a human to complete the official CLI flow from Quorb's +terminal on Windows/WSL. The synthetic laboratory is not a substitute. + +## Interactive acceptance + +1. Identify the candidate commit and the matching Quorb artifact to test. On + Windows, open that artifact and choose a test distro in Quorb's WSL settings. +2. Choose or add a test additional account in the app, with a session folder + separate from all existing accounts. Note the current result for another + account so it can be checked again later. +3. Start the additional-account login **from Quorb**. In the terminal Quorb + opens, complete the official CLI and browser flow yourself. +4. Use Quorb's account check to confirm the additional account works. Restart + Quorb and check it again; also confirm the other account remains unchanged. + Finding a session file alone does not demonstrate that an account works. +5. Report only sanitized pass/fail metadata: candidate commit/artifact, platform + and distro family/version, and the result of each step. Do not include + credential contents, account IDs, raw logs, or screenshots with personal data. + +## Evidence boundaries + +- Compiling ignored Windows tests does not run them or validate login. The legacy + ignored checks require a disposable, pre-provisioned guest; do not run them on + a personal distro. +- The Unix synthetic lab exercises the generated shell argv and the mocked + session-resolver seam using an isolated fixture. It does not run `wsl.exe`, + launch Quorb's terminal, contact a provider, or prove interactive login. +- S6 / T6 remains pending until a human performs the interactive acceptance + above against the identified candidate and reports sanitized results. diff --git a/odd/tasks/pr253-wsl-review.md b/odd/tasks/pr253-wsl-review.md new file mode 100644 index 0000000..9891e75 --- /dev/null +++ b/odd/tasks/pr253-wsl-review.md @@ -0,0 +1,102 @@ +# Finish PR253 WSL review +Objective: finish the accepted PR253 review corrections, without merging. Branch: `sync/pr253-main`; baseline: `b79fd3c9972ff73bb50195685ba6eb63446b9f5f`; delivery: existing PR253 (`single-pr`). +Runners: direct local Vitest/TypeScript, `cargo test --locked --manifest-path src-tauri/Cargo.toml --lib`, repository script tests; native Windows/live-login evidence stays distinct from Linux or synthetic tests. + +## Specs + +S1. Authorization: user said **“lo terminas?”**, accepting completion of the pending points for https://github.com/egdev6/quorb/pull/253. + +S2. Accepted review, presence ordering: “Con dos respuestas controladas (llega primero `true` del segundo sondeo y luego `false` del primero) se entrega `[true, false]` en vez de `[true]`.” “Falta descartar respuestas de peticiones anteriores del mismo poller y un test que cubra esa secuencia.” Preserve current failure-to-unknown and stop/restart behavior through the exported poller, including slow overlapping requests. Accepted independent verification finding: “After an initial `true`, consecutive failures leave the session-file-found indicator true indefinitely instead of changing it to unknown.” + +S3. Accepted review, host compatibility: “El nombre de archivo estándar sigue siendo obligatorio también en host, así que `C:\work\auth-work.json` con un comando avanzado que genera ese archivo se rechaza antes de ejecutar.” “La restricción tiene sentido en el guest, pero en host rompe una configuración que antes funcionaba.” Preserve standard-file session-directory derivation and guest path validation. + +S4. Accepted review, WSL normalization: “`is_wsl_command` sigue usando `program_of` de host antes del tokenizador POSIX, así que `'wsl' codex login` evade la detección.” “Conviene comprobar el mismo programa normalizado que después se ejecuta, y añadir ese caso al test.” Test detection and launch rejection without guest CLI probes; preserve host parsing and ordinary guest argv handling. + +S5. Accepted review, synthetic laboratory safety: “GAP4 (`login.rs:2216-2294`) no la aporta.” “Es un test ignorado que ejecuta un shim del CLI con `wsl.exe` directamente, sin pasar por el lanzamiento del terminal de la app ni por un login interactivo.” Correct the identified problems: “si falla, imprime el contenido completo de `.credentials.json` en el log”; “usa una cuenta fija (`claude:w2`) en la distro que se le pase, sin aislarla”; “no borra el archivo antes de comprobar el marcador, así que un archivo de una ejecución anterior lo da por bueno.” Do not execute the unsafe existing laboratory or access real credential material. + +S6. Accepted review, real acceptance evidence: “Para cerrar #92 sigue haciendo falta evidencia censurada de un login real de una cuenta adicional dentro de la distro con este flujo.” A shim, compiled ignored test, or file-presence check is not real interactive login proof. Never read, print, copy, transmit, or commit secrets or private credentials. + +## Tasks + +- T1 | S2 | original gentle-ai-worker, one verified-P1 correction batch | done | commit: f1dbcdb07fb61b5138843af176561d3c679e57f6; correction2bbd66bfc48a85918679eaeba62f0cc8d01e0f45 | correction RED3fail/21pass; GREEN24/1029/typecheck; parent24pass; independent P1-only recheck PASS (unchanged probe1pass + original ordering2pass) | Risk: item 4 (ordering concurrent poll responses). +- T2 | S3 | gentle-ai-worker (runtime context backstop; sequential login.rs ownership) | done | commit: 75f975225c8d4a9eeb037588e31b3195b4e63b2a | RED: 3 passed/1 failed; GREEN: 4 main-account tests, 48 login tests, fmt/diff OK | Risk: item 3 (restore advanced host configuration compatibility). +- T3 | S4 | gentle-ai-worker (runtime context backstop; sequential login.rs ownership) | done | commit: 230bcc293a13ced3e82ba66147b1fec7f35bc36d | RED: 48 passed/2 failed; GREEN: 50 login tests, fmt/diff OK | Risk: item 2 (normalized WSL execution guard). +- T4 | S5 | gentle-ai-worker plus authorized parent checks | done | commit: 5ce07174070e16d3d0fe32420265f40c0cfc9b45 | GREEN: 53 login tests including3 hermetic lab tests; fmt OK; previous30s timeout preserved | Risk: item 2 (prevent credential exposure and isolate test effects). +- T5 | S1-S5 | parent suites, one independent gentle-ai-verify plus P1-only scoped recheck | done | commit: e8747082a29b8b32dcf31ef0f8e2c29ec72b5353 | PASS: final frontend1029/scripts298, LinuxRust612/8ignored, WindowsRust610/4ignored, types/format, production bundle/inventory, independent review+P1 recheck,12-case compatibility differential and native embedded-UI validation artifact. +- T6 | S6 | human-assisted real Windows/WSL login with the identified candidate | done | commit: 809ae443d7f097ef56ebf45441f53a56b5632bd4 (human acceptance); validated source2bbd66b | PASS: human confirmed the real login flow and persistence after restart; no agent-performed login or credential access. + +## Log + +L1. Original current request, verbatim: “lo terminas?” Previous request, verbatim: “esta pr estaba lista para merge? https://github.com/egdev6/quorb/pull/253”. + +L2. Accepted context is the four outstanding points in the preceding answer, not approval or merge. Parent response: “Sí. Voy a corregir los puntos pendientes y verificar la PR. Si falta una prueba de login real que requiera tu intervención, te voy a indicar exactamente qué validar. No la mergeo.” + +L3. Exploration: configured read-only explorer `mwf5zlaq-2-oxlf` mapped the corrections. Parent read the exact accepted formal review from `/home/egdev/proyectos/quorb-review-253-272.eAGPDL/pr253/review-body.md`. GitHub refresh job-2 confirmed OPEN, head b79fd3c9972ff73bb50195685ba6eb63446b9f5f, maintainerCanModify=true, BLOCKED/CHANGES_REQUESTED, head repository sosan/quorb, branch feat/wsl-login-92. Worktree `/home/egdev/proyectos/quorb-pr253-sync` is clean and registered. Canonical main is stale and is not modified. + +L4. Classification: large because the original short request and a code diff alone cannot recover the accepted historical review or external real-login proof. Estimated correction slice about 400 authored changed lines, excluding generated inventory; keep coherent behavioral commits in the already-open PR. No parallel writer: poller fix is a small unit; Rust corrections and laboratory share login.rs. Parent owns all source edits. RDD is off; no native assessment or native review is started. Named risks 2/3/4 require one independent verifier after implementation. + +L6. Runtime context backstop fired after the parent added the two overlapping-poll regression cases, before running them. Delegate the remaining T1 reads/RED/fix/checks to the bounded worker; future multi-step units use the same trigger. Parent retains tracking, commits and the final seam check. No writer has run yet. + +L7. Worker mwf680uh-3-e5hn returned interaction_required before running RED: the symlinked node_modules cache/config-loader writes would be outside its Allowed edit surfaces. No worker source edits and zero tests run; preliminary git diff --check passed. Worker proposed A: replace exact Vitest commands with --no-cache --configLoader runner, or B: stop. This is a user-facing blocking envelope, so the parent relays it without selecting for the human; no dependent work starts. Existing cache is preserved. + +L8. Human selected the closed-envelope answer “A — Replace the RED and GREEN commands” (opaque value A). The replacement uses --no-cache --configLoader runner for both Vitest commands, preserving the timeout and subsequent diff check. Return T1 to in_progress and deliver this answer exactly once to the same finished worker. No child is active or uncertain: the worker returned its final interaction_required result. + +L5. Verification policy: observe one meaningful RED per requested deterministic rule, then GREEN and existing touched-path coverage. Run a scratch differential against b79fd3c for unrequested behavior sharing changed helpers; do not commit history-dependent tests. Use existing on-disk Cargo target (not the previously exhausted /tmp target). Do not run the unsafe GAP4 or inspect actual credential files. Tests use synthetic, isolated data only; real login remains a separate human action. + +L9. T1 completed by worker mwf6hlhl-4-28zw: RED exit1 with the two reported stale-order failures, expanded RED four failures; GREEN exit0, focused23/frontend1028 (76 files), TypeScript OK, diff check OK. Parent inspected the full T1 diff and committed f1dbcdb07fb61b5138843af176561d3c679e57f6. T2 starts with narrow sequential ownership of login.rs. Final independent verification remains T5. + +L10. Delivery slice starts at b79fd3c9972ff73bb50195685ba6eb63446b9f5f; T1 correction133 authored changed lines including tracking. Runtime's2417-line branch warning includes114 inherited PR commits, not only these corrections. Preserve the accepted existing-PR single-pr strategy; no new PR chain or merge is created. + +L11. T2 completed by worker mwf6ok7n-5-ttm8. RED exit101, 3 passed/1 expected failure; GREEN4 main-account cases and48 login cases. cargo fmt and diff checks exit0. Parent inspected the complete diff and committed75f975225c8d4a9eeb037588e31b3195b4e63b2a. Synthetic scratch `/tmp/quorb-login-suite.DZKR0G4D` remains task-owned; preserve until final checks or remove only that proven scratch. No real credentials or WSL login used. T3 starts. Correction slice since b79fd3c is276 authored lines including tracking; single existing PR strategy remains unchanged. + +L12. T3 completed by worker mwf7463s-6-sua4, committed230bcc293a13ced3e82ba66147b1fec7f35bc36d after parent inspected the full diff. RED48passed/2failed; GREEN50login tests, fmt/diff exit0. WSL guard now classifies the POSIX-normalized executable; malformed-input fallback preserves the old guard result. This intentionally removes false positives when the actual normalized program is not wsl. Host program_of is unchanged. README English/Spanish now distinguishes selected-distro commands from host wrappers. Synthetic scratch `/tmp/quorb-t3-synthetic.3VCEDC1z` remains task-owned. T4 starts. Correction slice about396 authored lines including tracking; retain existing PR253 single-pr delivery and coherent per-risk commits rather than creating unrelated PRs. + +L13. T4 worker mwf7g7my-7-cuh7 returned partial. Implemented an isolated Unix synthetic shim/resolver-seam fixture plus stale-output/isolation/symlink checks in login.rs, sanitized adjacent GAP2/GAP3 diagnostics, added docs/wsl-login-validation.md and linked it from onboarding. Required cargo test --locked --manifest-path src-tauri/Cargo.toml --lib login:: exceeded the explicit30s foreground limit during compilation; no test totals, success, or Windows compile evidence. No meaningful safe RED existed for the original Windows-only ignored lab, which was not executed. fmt initially failed, was corrected, then passed; diff check passed. No automatic retry/restart/background migration is authorized by that timeout. Leave T4 uncommitted and blocked; T5 verifier/full suites and T6 real login remain pending. + +L14. Parent checked real state after partial T4: all child tasks completed; ps showed no cargo/rustc processes. No timeout retry was performed. Uncommitted surfaces: login.rs, onboarding, new wsl-login-validation.md, parent tracking. T4 scratch `/tmp/quorb-t4-synthetic.0UwSuKyM` is task-owned and remains. Earlier owned scratch from T2/T3 remains too. Recoverable technical issue is insufficient compilation time, not an observed failed test assertion. Separately, native Windows compile/WSL interaction and real sanitized login proof are still unavailable. A fresh human-controlled bounded continuation must name executor, scope, correction limit and checks; it does not reset any prior limit or authorize delivery/merge. + +L15. Human selected “Continuar la implementación y verificación” (opaque value continue_t4_t5_bounded). Authorized scope T4-T5: parent runs long checks in background, maximum10minutes per job; the same worker gets one corrective batch if code fails, then focused/full suites, typecheck/format, compatibility differential and one independent verifier. Previous timeout/failures remain recorded; no push or merge, T6 stays human-assisted. Parent inspected the entire T4 diff before launching the newly authorized check. All children and compiler processes had been confirmed inactive. + +L16. Authorized parent job-3 completed exit0 in1m09s: focused Rust53passed,0failed (3 new synthetic lab tests), fmt exit0. Evidence `/tmp/quorb-pr253-parent-check.9IJUojRS/{focused.stdout,focused.stderr,focused.exit,fmt.stdout,fmt.stderr,fmt.exit,job.exit}`; native wrapper log `/tmp/gpdOEcEU/gentle-jobs-T7ctta/job-3.log`. This resolves T4's Linux verification blocker, not Windows or S6 proof. Parent committed5ce07174070e16d3d0fe32420265f40c0cfc9b45. T5 starts. + +L17. Native Windows interop is available: powershell.exe, Windows cargo/rustc and Node/npm, installed x86_64-pc-windows-msvc. Linux has only x86_64-unknown-linux-gnu. Native Windows checks may use the installed toolchain with offline caches and a new isolated profile; no dependency/toolchain installation is authorized. + +L18. Inventory generation exposed synthetic test strings because its existing scanner does not recognize cfg(all(test,unix)) as a test-only module. Parent made the equivalent existing-convention annotation cfg(test)+cfg(unix), committed4f0a05146284f78131352db1da29ca1e86ac1aa4 after fmt/diff checks. This is test-only structural gating, no behavioral RED is meaningful. Regenerated inventory now changes only4 lines (tree hashes and equivalent error placeholder), --check exit0; generated file remains uncommitted for T5 closure. Parent job-4 is running the exact frontend/script suites, typecheck, production Vite build and inventory with isolated HOME and cache-free runner (10min bound). Native Rust checks wait until that job completes, avoiding concurrent dist regeneration/codegen reads. + +L19. Parent job-4 completed exit0: frontend1028/1028 (76files), repository scripts298/298, TypeScript, Vite production build and inventory all pass. Evidence `/tmp/quorb-pr253-node-check.Zq68wfR7/`; wrapper `/tmp/gpdOEcEU/gentle-jobs-T7ctta/job-4.log`. Expected mocked-UI stderr was retained separately, not treated as a failed test. + +L20. Parent full Linux job-5 compiled the current4f0a051 candidate, then exited101:611passed,1failed,8ignored. Sole failure codex_setup::tests::real_runner_launches_node_with_the_paired_script_and_install_verb: “Node real no encontrado (QUORB_TEST_NODE_EXECUTABLE o PATH)”. This is parent setup: the isolated PATH omitted the installed Node. Preserve original full.stdout/full.stderr/full.exit in `/tmp/quorb-pr253-parent-check.9IJUojRS/`; correct only the check environment by adding the installed Node directory and QUORB_TEST_NODE_EXECUTABLE, then run the required full suite within the already-authorized10min job bound. No source fix or extra worker correction budget is used. Native Windows job-6 has its separate target/profile and is still awaiting its completion event. + +L21. Parent full Linux job-7 completed exit0 after the isolated-Node setup correction:612passed,0failed,8ignored. Evidence full-corrected.stdout/full-corrected.stderr/full-corrected.exit in `/tmp/quorb-pr253-parent-check.9IJUojRS/`; original failed run is preserved. This compiled4f0a051 into `src-tauri/target/debug/deps/quorb_lib-2b3ad1bea34c403d`. + +L22. Native Windows job-6 exited101 before tests: rustc could not create an incremental session lock on the WSL UNC filesystem (os error -2147024895). No code assertion failed and zero tests ran. Original evidence is under Windows temp `quorb-pr253-windows-68060399fdb8481d9319c68fca42dec5/{windows.stdout,windows.stderr,windows.exit}`. Parent job-9 applies one environment correction: a new local NTFS target under that same owned proof directory plus CARGO_INCREMENTAL=0, offline with isolated profile; original UNC cache/logs are preserved. Maximum10min remains enforced. + +L23. One-script compatibility differential job-8 failed during base compilation, before running any probe: scratch copy lacked docs/build-linux.md needed by include_str in an existing library test. Original evidence `/tmp/quorb-pr253-differential.VIPIDXJA/`; base/candidate source copies and the public-interface probe are preserved. Correct this single setup omission by adding that exact public build-input doc from each respective commit, not by editing production code or re-appending probes. Then run the base/candidate script under the existing10min bound and compare12 public-interface observations, exact runtime stderr and exit codes, preserving the failed attempt. No differential success is claimed yet. Independent verifier is launched once over S1-S5; S6 remains human-only. + +L24. Native Windows job-9 completed exit0, compiling the Windows-only ignored lab without executing it. Output windows-local.* in the same owned Windows proof root; native wrapper job-9.log. No real WSL/login used. Linux and Windows Rust code are green; native test totals will be read from the retained stdout. + +L25. Independent verifier mwf8x1in-8-e8nk completed its one full verification. It independently ran copied candidate Rust binary53/53, isolated poller23/23, and3 additional overlap probes. CONFIRMED P1, S2: “If each check takes longer than the three-second interval, a newer request starts before each response arrives. Every completed response is then discarded. After an initial `true`, consecutive failures leave the session-file-found indicator true indefinitely instead of changing it to unknown.” Independent exact slow-failure probe: baseline b79fd3c exit0/1pass, candidate4f0a051 exit1/1fail; expected[null], received[true]. S3-S5 pass for specified cases, S6 unproven. Scratch `/tmp/qv.SXaBCb` is task-owned. Reopen only T1/S2 and order T5 after it. Use the one authorized corrective batch with the original T1 worker, then a recheck LIMITED to this same P1, never a new sweep. Do not add retry budget. Requested out-of-order cases and current-failure-to-unknown must both pass; latest-started suppression while a newer request is merely pending was an implementation assumption, not a requested new behavior. + +L26. Original T1 worker continuation mwf9b7yu-9-u4lm used the one P1 corrective batch. RED exit1:3expected failures/21passed; GREEN exit0:focused24/frontend1029/TypeScript. The regression pins exact calls[true,null,null,null] for slow failures; the two pending-request cases now reflect latest-delivered ordering. Parent inspected the complete diff and independently reran focused24/24 (p1-focused.* in the parent proof directory), then committed2bbd66bfc48a85918679eaeba62f0cc8d01e0f45. T1 stays in_progress until the SAME verifier's P1-only recheck. No new review sweep or correction budget is authorized. + +L27. SAME verifier continuation mwf9gpz6-a-fgl4 completed the one P1-only recheck against2bbd66b: unchanged independent slow-failure probe exit0/1pass; original stale-response tests exit0/2pass/22skipped by the deliberate filter. P1 resolved, S2 met; S1/S3-S5 were not swept again and S6 remains human-only. Probe SHA25650de29b3c5cefd2b5be8bca34c1334a57a5c09ff491a6fef29e6dffa14c9a9d7. New owned scratch `/tmp/qvr.6Xqijd`, prior `/tmp/qv.SXaBCb`. T1 done; resume T5 compatibility setup correction, final frontend bundle/inventory, native candidate build. No further review cycle is added. + +L28. Native Windows retained stdout confirms610passed/0failed/4ignored; Linux full612passed/0failed/8ignored. Backend input tree4f0a051:src-tauri equals2bbd66b:src-tauri (`8c738060194c7b4bb36331391a1910daa108342a`), so the TS-only P1 correction does not invalidate backend checks or the prepared backend differential copies. Cargo metadata accepts --features tauri/custom-protocol without manifest/dependency changes, enabling an embedded-UI validation binary with the installed native toolchain. No development server, app launch or real login is performed by the agent. + +L29. Regenerated inventory for committed2bbd66b; --check and git diff --check pass. Parent final seam job-10 is running frontend/scripts/typecheck/production build/inventory with isolated HOME and cache-free runner. Wait for its completion event before native artifact/differential compilation so dist writes cannot race codegen reads. Required compatibility probe remains pending its one missing-build-doc setup correction; no second review sweep is introduced. + +L30. Final seam job-10 completed exit0 on2bbd66b: frontend1029/1029 (76files), scripts298/298, TypeScript, Vite production build (index-CwEHO-TI.js) and inventory all pass. Evidence `/tmp/quorb-pr253-final-node.3GpKQlMj/`; original warnings/failures remain retained, not hidden. + +L31. Corrected one-script differential job-12 completed exit0: base and candidate compile exits0, both runtime exits0,12 public login::open/cli_status observations identical, runtime stderr equal, rejected guest input has zero adapter calls and rejected input creates no session files. Prepared backend4f0a051 is byte-identical in src-tauri to final2bbd66b; script asserted this. Evidence `/tmp/quorb-pr253-differential.VIPIDXJA/*corrected*`. Only missing docs/build-linux.md build input was added to scratch; original job-8 failure is preserved. No history-dependent test was committed. + +L32. Native embedded-UI build job-11 compiled successfully (Cargo exit0) with --features tauri/custom-protocol, no dev server or app launch. Wrapper exited1 only AFTER the binary was copied because Get-FileHash was unavailable. Parent inspected the successful build.exit and the single owned trial directory, then used .NET SHA256 to verify the EXISTING copy equals the original; no rebuild or repeated copy. Metadata recovery exited0. Artifact: `C:\Users\egdev\AppData\Local\Temp\quorb-pr253-2bbd66b-f7f98b4d\quorb.exe`; SHA256 `45E6E4367D61C78B3DA7DA760D94AAE4A427FE81553B8F0883FD3F35690A354F`; source2bbd66bfc48a85918679eaeba62f0cc8d01e0f45. Record/logs in the owned Windows proof root `quorb-pr253-windows-68060399fdb8481d9319c68fca42dec5`. This is an unsigned validation-only debug binary with embedded UI, not an installer or release. + +L33. T5 implementation checks complete; inventory/evidence commit e8747082a29b8b32dcf31ef0f8e2c29ec72b5353. T6 alone remains blocked on the human: exit existing Quorb from its tray icon, launch the identified candidate, choose WSL/test distro and an additional test account in the app, initiate login FROM Quorb, complete the official CLI/browser flow personally, then confirm usable account, restart persistence and another account unchanged. Return only sanitized pass/fail metadata, never credentials/raw logs/personal data. The agent never launches the app or reads real sessions. No push, PR approval or merge is authorized/performed; GitHub head remains the previously observed b79fd3c until separately authorized delivery. + +L34. Closure disposition: Needs your decision — S1-S5 verified, S6 real interactive proof unavailable to the agent and awaiting the human. Known historical setup failures (Vitest cache authorization,30s Cargo timeout, missing Node in isolated PATH, native UNC incremental lock, missing copied build doc, unavailable Get-FileHash) are preserved with their bounded recoveries. The verifier-found slow-poll P1 is corrected and its scoped independent recheck passes. Linux8/Windows4 ignored tests were not run; no real WSL lab, official login, signing, installer or release was executed. Risk: items2,3,4 (execution/credential guards, shared host compatibility, concurrent poll ordering), independently verified. Preserve all limits and exact task/source/artifact identity on resume. + +L35. Final read-only GitHub checkpoint job-13 exited0: remote remains OPEN at b79fd3c9972ff73bb50195685ba6eb63446b9f5f, feat/wsl-login-92, BLOCKED/CHANGES_REQUESTED. No remote mutation occurred. Every child task is completed and all background completion events were received; no active/uncertain child remains. Removed only the five recorded task-owned worker/verifier scratch directories from L11/L12/L13/L25/L27; retained primary parent evidence, the differential proof copies and the Windows artifact/proof root. Final state: five tasks done, T6 blocked on the human; no failed code check remains unresolved. Correction slice boundary remains b79fd3c; existing PR253 single-pr strategy remains unchanged despite inherited branch-size warnings. + +L36. Human reply, verbatim: “confirmo”. This answers the immediately preceding question “¿Podés confirmar que funciona y sigue conectada tras reiniciar?” after the Windows validation artifact and additional-account WSL login steps were supplied. Record this as HUMAN-REPORTED acceptance of the real login flow and restart persistence for source2bbd66bfc48a85918679eaeba62f0cc8d01e0f45, artifact from L32. The agent did not run authentication, inspect credentials, or independently observe the GUI. No distro/version metadata or separate manual other-account result was supplied; do not invent either. The optional unchanged-account seam already has synthetic/differential coverage. This resolves S6's missing human login proof, not authorization to push, approve, or merge. + +L37. Acceptance recorded in commit809ae443d7f097ef56ebf45441f53a56b5632bd4. S1-S6 are fulfilled and all six tasks are done; the former S6 blocker is resolved by human-reported real-flow/restart confirmation, not by synthetic evidence. This closeout changes only the task record. Structural git diff --check and unchanged application-source identity against validated2bbd66b passed; no new code, build, test rerun, native review or meaningful RED is applicable to recording a human result. Prior automated checks, independent verification, historical recoveries and Linux8/Windows4 ignored-test limits remain as documented. The authorized local feature is closed; publishing, approval and merge remain unauthorized and were not performed. diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 789f4bb..7163ea2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -53,6 +53,9 @@ use tauri::{ }; use tauri::{PhysicalPosition, PhysicalSize}; use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutState}; +// En scope para el dispatch estático del adaptador en `account_session` +// (el de `session_resolver` ya es `dyn` y no lo necesita). +use wsl::WslAdapter; const WIDGET: &str = "widget"; /// Selector de idioma del primer arranque (#235). Ventana aparte de la tira. @@ -609,7 +612,7 @@ async fn session_resolver( match cfg.session_env() { wsl::SessionEnv::Host => Ok(None), wsl::SessionEnv::Wsl { distro } => { - // No despertar la distro en un sondeo (revisión PR #248): si no + // No despertar la distro en un sondeo (revisiones PR #248/#253): si no // está Running, el entorno está inaccesible y NO se lanzan // procesos del guest. `resolve_home` (SÍ despierta) solo se // alcanza con la distro en marcha. @@ -912,10 +915,51 @@ async fn check_provider( /// ¿Está instalado el CLI de login de Claude, Codex y Gemini? /// `async` lo saca del hilo principal: consulta el PATH fresco del registro. +/// `session_env`/`wsl_distro` (opcionales) son el ENTORNO DEL BORRADOR que +/// muestra Ajustes (revisión PR #92, punto 10): si vienen, la detección +/// consulta ese entorno y no la config persistida — así el aviso «falta la +/// CLI» y el estado del botón responden a lo que el usuario ve, no a lo que +/// quedó guardado. Sin override (p. ej. el widget), se usa la persistida. #[tauri::command(async)] -fn cli_status(state: State<'_, AppState>) -> BTreeMap { - let cfg = state.config.lock().unwrap().clone(); - login::cli_status(&cfg) +async fn cli_status( + state: State<'_, AppState>, + session_env: Option, + wsl_distro: Option, +) -> Result, String> { + let mut cfg = state.config.lock().unwrap().clone(); + if let Some(env) = session_env + .as_deref() + .map(str::trim) + .filter(|e| !e.is_empty()) + { + cfg.session_env = if env == "wsl" { + crate::config::SessionEnvConfig::Wsl + } else { + crate::config::SessionEnvConfig::Host + }; + cfg.wsl_distro = wsl_distro.unwrap_or_default(); + } + // #92: la detección en WSL lanza procesos `wsl.exe` (enumeración + `command + // -v`), así que va en un hilo bloqueante: en el hilo del executor + // congelaría la UI (hasta 20 s de timeout por operación). + let map = tauri::async_runtime::spawn_blocking(move || { + let adapter = wsl::RealWslAdapter::new(); + let distro = match cfg.session_env() { + wsl::SessionEnv::Wsl { distro } => Some(distro), + wsl::SessionEnv::Host => None, + }; + let wsl = distro.as_deref().map(|d| login::WslLogin { + adapter: &adapter, + distro: d, + }); + login::cli_status(&cfg, wsl) + .into_iter() + .map(|(p, s)| (p, s.as_str().to_string())) + .collect::>() + }) + .await + .map_err(|e| e.to_string())?; + Ok(map) } /// ¿Existe el fichero de sesión de una cuenta? `home` se inyecta para poder @@ -924,38 +968,143 @@ fn account_session_file_found(cfg: &AppConfig, id: &str, home: &std::path::Path) providers::session_file(cfg, id, home).is_some_and(|p| p.is_file()) } -/// ¿Hay fichero de sesión del CLI para una cuenta adicional? `true` es presencia, -/// no validez de la sesión. +/// ¿Hay fichero de sesión del CLI para una cuenta? `true` es presencia, no +/// validez de la sesión. Sigue al ENTORNO elegido (revisión PR #92): en WSL +/// la sesión vive dentro de la distro y el sondeo debe consultarla ahí — el +/// disco del host no ve la sesión del guest y, peor, daría por buena una +/// sesión de Windows que no tiene relación con el entorno WSL. #[tauri::command] -fn account_session(state: State<'_, AppState>, id: String) -> bool { +async fn account_session(state: State<'_, AppState>, id: String) -> Result { let cfg = state.config.lock().unwrap().clone(); - // En modo WSL este sondeo sigue mirando el HOST (hasta #92): devolver su - // resultado mostraría como «conectada» una sesión de Windows que no tiene - // relación con la distro (revisión PR #248). Sin la integración del guest - // no se confirma nada, y no se despierta la distro. - if matches!(cfg.session_env(), wsl::SessionEnv::Wsl { .. }) { - return false; + let adapter = std::sync::Arc::new(wsl::RealWslAdapter::new()); + match cfg.session_env() { + wsl::SessionEnv::Host => Ok(account_session_file_found(&cfg, &id, &providers::home())), + wsl::SessionEnv::Wsl { distro } => { + // El SONDEO no despierta una distro detenida (contrato W1 §2, + // revisión PR #92): igual que la detección, se consulta el + // estado con `list_distributions` (no lanza nada) y solo se lee + // dentro del guest cuando está Running. Una distro apagada es + // «no hay sesión visible», no una excusa para despertarla cada + // 3 s desde Ajustes. + let running = tauri::async_runtime::spawn_blocking({ + let adapter = adapter.clone(); + let distro = distro.clone(); + move || { + adapter + .list_distributions() + .ok() + .and_then(|ds| { + ds.into_iter() + .find(|d| wsl::distro_name_matches(&distro, &d.name)) + }) + .is_some_and(|d| matches!(d.state, wsl::DistroState::Running)) + } + }) + .await + .map_err(|e| format!("WSL: {e}"))?; + if !running { + return Ok(false); + } + let resolver = session_resolver(&cfg, adapter, &state.wsl_homes).await?; + let Some(r) = resolver else { + // Sin distro resuelta (p. ej. no configurada): nada que + // sondear; no caer al disco del host. + return Ok(false); + }; + tauri::async_runtime::spawn_blocking(move || { + // Cuenta principal (id de proveedor) o adicional: la MISMA + // resolución del entorno (#91). Principal con + // `credentials_path` > ruta por defecto del guest. + let path: Result, String> = + if let Some(a) = cfg.accounts.iter().find(|a| a.id == id) { + crate::providers::account_session_path(a, Some(&r)) + } else { + let kind = match id.as_str() { + "claude" => Some(crate::providers::CliSessionKind::Claude), + "codex" => Some(crate::providers::CliSessionKind::Codex), + "gemini" => Some(crate::providers::CliSessionKind::Gemini), + "grok" => Some(crate::providers::CliSessionKind::Grok), + _ => None, + }; + let Some(kind) = kind else { + return Ok(false); + }; + let c = match id.as_str() { + "claude" => &cfg.claude, + "codex" => &cfg.codex, + "gemini" => &cfg.gemini, + _ => &cfg.grok, + }; + r.resolve( + c.credentials_path.as_deref(), + &r.default_path(crate::providers::session_relative(kind).as_path()), + ) + .map(|p| Some(p.to_string_lossy().into_owned())) + .map_err(|e| format!("WSL: {e:?}")) + }; + match path? { + // Proveedor sin sesión CLI en este entorno. + None => Ok(false), + Some(path) => { + use crate::wsl::SessionError; + match r.read(std::path::Path::new(&path)) { + Ok(_) => Ok(true), + // Sin fichero en la distro: no hay sesión. + Err(SessionError::Absent(_)) => Ok(false), + // El guard de la distro también "lee" el fichero + // de sesión; si falla de otra forma, no es + // "conectada" — se informa para no dar por buena + // una sesión que no se pudo comprobar. + Err(e) => Err(format!("WSL: {e:?}")), + } + } + } + }) + .await + .map_err(|e| format!("WSL: {e}"))? + } } - account_session_file_found(&cfg, &id, &providers::home()) } #[tauri::command] -fn open_login(state: State<'_, AppState>, provider: String) -> Result<(), String> { +async fn open_login(state: State<'_, AppState>, provider: String) -> Result<(), String> { // Single-flight: si hay una apertura en curso para este id, no abrir // una segunda terminal (doble clic / reenvío del frontend). // `unwrap_or_else(into_inner)`: si otro hanco pánicara con el lock tomado, // el mutex queda envenenado y con `unwrap` todos los `open_login` futuros // paniquearían en cascada. Con `into_inner` seguimos operando el set. - let mut inflight = state - .login_in_flight - .lock() - .unwrap_or_else(|p| p.into_inner()); - if !inflight.insert(provider.clone()) { - return Err("Ya hay una apertura de terminal en curso para esta cuenta. Si no se abrió, inténtalo de nuevo.".into()); + // El guard del single-flight vive en un bloque propio: el comando es + // async y `MutexGuard` no es `Send`, así que debe morir antes del await. + { + let mut inflight = state + .login_in_flight + .lock() + .unwrap_or_else(|p| p.into_inner()); + if !inflight.insert(provider.clone()) { + return Err("Ya hay una apertura de terminal en curso para esta cuenta. Si no se abrió, inténtalo de nuevo.".into()); + } } - drop(inflight); // no mantener el lock mientras spawn_terminal corre + // Liberado el single-flight, el login corre fuera del executor. let cfg = state.config.lock().unwrap().clone(); - let r = login::open(&provider, &cfg); + // #92: en WSL el login consulta la distro (y su home), así que son + // procesos bloqueantes: fuera del executor, en un hilo propio. + let provider_for_task = provider.clone(); + let task = tauri::async_runtime::spawn_blocking(move || { + let adapter = wsl::RealWslAdapter::new(); + let distro = match cfg.session_env() { + wsl::SessionEnv::Wsl { distro } => Some(distro), + wsl::SessionEnv::Host => None, + }; + let wsl = distro.as_deref().map(|d| login::WslLogin { + adapter: &adapter, + distro: d, + }); + login::open(&provider_for_task, &cfg, wsl) + }); + let r = match task.await { + Ok(r) => r, + Err(e) => Err(format!("No pude abrir la terminal: {e}")), + }; state .login_in_flight .lock() @@ -980,6 +1129,18 @@ async fn install_codex( app: AppHandle, window: WebviewWindow, ) -> Result { + // #92: en modo WSL no se ofrece el instalador de Windows como solución a + // una CLI ausente dentro de la distro; la instalación automática en WSL + // queda fuera del alcance, y el login ya dirige a instalar allí. + let install_cfg = app.state::().config.lock().unwrap().clone(); + if matches!(install_cfg.session_env(), wsl::SessionEnv::Wsl { .. }) { + return Err( + "El modo WSL no usa el instalador de Codex de Windows: instala Codex dentro \ + de la distro (p. ej. `sudo npm i -g @openai/codex`). La instalación automática \ + en WSL queda fuera de alcance." + .to_string(), + ); + } let label = window.label().to_string(); if !codex_setup::settings_window_ok(&label) { return Err(codex_setup::MSG_WRONG_WINDOW.to_string()); @@ -1981,7 +2142,7 @@ mod tests { assert!(!account_session_file_found(&cfg, "openrouter:w1", &home)); } - /// Revisión PR #248: el SONDEO no despierta una distro detenida. Con la + /// Revisiones PR #248/#253: el SONDEO no despierta una distro detenida. Con la /// distro Stopped, `session_resolver` devuelve error ANTES de `resolve_home` /// (que es quien lanzaría procesos del guest): la única llamada al /// adaptador es la enumeración (F4), que no despierta. @@ -2015,7 +2176,7 @@ mod tests { } /// Con la distro Running, el resolvedor se construye y su home se cachea - /// (revisión PR #248: la transición detenida → en marcha vuelve a leer). + /// (revisiones PR #248/#253: la transición detenida → en marcha vuelve a leer). #[test] fn session_resolver_resolves_when_the_distro_is_running() { use crate::wsl::{distro, DistroState, MockWslAdapter, WslAdapter}; diff --git a/src-tauri/src/login.rs b/src-tauri/src/login.rs index ce6de9c..23f7295 100644 --- a/src-tauri/src/login.rs +++ b/src-tauri/src/login.rs @@ -8,26 +8,25 @@ //! Las cuentas adicionales usan el mismo comando con su propia carpeta de sesión //! (`CLAUDE_CONFIG_DIR`, `CODEX_HOME` o `GEMINI_CLI_HOME`), así no pisan la principal. -use crate::config::AppConfig; +use crate::config::{Account, AppConfig}; +use crate::wsl::{self, ShellStrategy, WslAdapter}; use std::path::{Path, PathBuf}; /// `id`: el proveedor (cuenta principal) o el id de una cuenta adicional. -pub fn open(id: &str, cfg: &AppConfig) -> Result<(), String> { - let mut env = None; - let provider = match cfg.accounts.iter().find(|a| a.id == id) { - Some(a) => { - let var = a - .session_env() - .ok_or_else(|| format!("La cuenta «{}» no tiene login por CLI", a.label))?; - let dir = a.session_dir(&crate::providers::home()); - std::fs::create_dir_all(&dir) - .map_err(|e| format!("No pude crear {}: {e}", dir.display()))?; - env = Some((var, dir)); - a.provider.as_str() - } - None => id, - }; - let command = match provider { +/// Entorno WSL para la detección y el login (#92): la distro elegida y el +/// adaptador (real en producción, mock en los tests) para consultar dentro +/// de ella. `Some` solo cuando la configuración elige el modo WSL. +pub(crate) struct WslLogin<'a> { + pub adapter: &'a dyn WslAdapter, + pub distro: &'a str, +} + +/// `id`: el proveedor (cuenta principal) o el id de una cuenta adicional. +/// En modo WSL (wsl: Some) la CLI se comprueba DENTRO de la distro y el +/// login se lanza allí; en host el flujo de siempre. +pub(crate) fn open(id: &str, cfg: &AppConfig, wsl: Option>) -> Result<(), String> { + let (provider, env) = account_env(id, cfg, wsl.as_ref())?; + let command = match provider.as_str() { "claude" => cfg.claude.login_command.trim(), "codex" => cfg.codex.login_command.trim(), "gemini" => cfg.gemini.login_command.trim(), @@ -38,37 +37,542 @@ pub fn open(id: &str, cfg: &AppConfig) -> Result<(), String> { if command.is_empty() { return Err("Comando de login vacío (revísalo en Ajustes)".into()); } - // Antes de abrir la terminal se comprueba que el CLI está instalado: si no, la - // consola solo diría «no se reconoce como un comando» y no sabrías qué hacer. - let program = program_of(command); - let extra_dir = match find_program(&program) { - Found::OnPath => None, - Found::In(dir) => Some(dir), - Found::Missing => return Err(not_installed(provider, &program)), - }; - spawn_terminal(command, env, extra_dir) + match wsl.as_ref() { + Some(w) => { + let argv = prepare_wsl_login(w, &provider, command, &env)?; + spawn_wsl_terminal(&argv) + } + None => { + // Antes de abrir la terminal se comprueba que el CLI está + // instalado: si no, la consola solo diría «no se reconoce como + // un comando» y no sabrías qué hacer. El MISMO tokenizador que + // la ejecución decide el programa (revisión PR #92): comillas y + // escapes se ven igual aquí y en la terminal. + // En HOST la ruta es del sistema: `C:\tools\codex.cmd` no debe + // leer `\t`/`\c` como escapes POSIX (revisión PR #92, punto 8). + // `program_of` es la heurística de host: primer token por + // espacios o comillas envolventes, sin interpretar backslashes. + let program = program_of(command); + let extra_dir = match find_program(&program) { + Found::OnPath => None, + Found::In(dir) => Some(dir), + Found::Missing => return Err(not_installed(&provider, &program)), + }; + spawn_terminal(command, env, extra_dir) + } + } +} + +/// ¿Está el CLI de login de cada proveedor DENTRO del entorno elegido? +/// +/// En modo WSL se consulta la distro con UNA enumeración y UNA detección de +/// shell para las cuatro CLIs (no 12 invocaciones de `wsl.exe` por +/// refresco); una distro detenida no se despierta (se informa «no +/// disponible»). En host sigue siendo la detección de Windows de siempre. +/// Estado de una CLI de login para la UI (#92, revisión PR). +/// +/// Contrato ampliado a 4 estados: el booleano no distinguía «no instalada» +/// de «distro detenida» o «WSL roto», y la UI no debe proponer instalar la +/// CLI cuando el problema es la distro. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum CliStatus { + /// Instalada y localizable (host o distro Running). + Ready, + /// La distro corre y no tiene esa CLI. + Missing, + /// La distro está detenida/transición: el login explícito puede + /// activarla; el sondeo no la despierta. + Stopped, + /// WSL no disponible, distro inexistente o fallo del subsistema. + Error, +} + +impl CliStatus { + pub(crate) fn as_str(self) -> &'static str { + match self { + CliStatus::Ready => "ready", + CliStatus::Missing => "missing", + CliStatus::Stopped => "stopped", + CliStatus::Error => "error", + } + } } -/// ¿Está instalado el CLI de login de cada proveedor que lo usa? Para avisar en -/// Ajustes antes de que pulses «Iniciar sesión». -pub fn cli_status(cfg: &AppConfig) -> std::collections::BTreeMap { - [ +pub(crate) fn cli_status( + cfg: &AppConfig, + wsl: Option>, +) -> std::collections::BTreeMap { + let providers = [ ("claude", &cfg.claude.login_command), ("codex", &cfg.codex.login_command), ("gemini", &cfg.gemini.login_command), ("grok", &cfg.grok.login_command), - ] - .into_iter() - .map(|(p, c)| { - ( - p.to_string(), - !matches!(find_program(&program_of(c)), Found::Missing), - ) - }) - .collect() + ]; + match &wsl { + Some(w) => { + let distros = w.adapter.list_distributions().ok(); + let situation = match distros.as_ref().and_then(|ds| { + ds.iter() + .find(|d| crate::wsl::distro_name_matches(w.distro, &d.name)) + }) { + // Distro ausente o WSL roto: no es un problema de la CLI. + None => Some(CliStatus::Error), + Some(d) if !matches!(d.state, crate::wsl::DistroState::Running) => { + Some(CliStatus::Stopped) + } + Some(_) => None, + }; + if let Some(situation) = situation { + return providers + .into_iter() + .map(|(p, _)| (p.to_string(), situation)) + .collect(); + } + let shell = w.adapter.shell_strategy(w.distro).ok(); + providers + .into_iter() + .map(|(p, c)| { + // Detección en el GUEST: mismo tokenizador POSIX que la + // ejecución (revisión PR #92, punto 5) — `program_of` es + // la heurística del HOST (punto 8) y aquí no aplica. + // + // Un comando que ya lanza `wsl` por su cuenta no se busca + // dentro del guest (allí no existe `wsl`) ni se envuelve + // (revisión PR #253): se informa como error de + // configuración, que no propone instalar ni bloquea el + // login (el mensaje accionable lo da `open`). + let status = if is_wsl_command(c) { + CliStatus::Error + } else { + match &shell { + Some(shell) => { + let program = + split_login_command(c).map(|(p, _)| p).unwrap_or_default(); + match w.adapter.program_available(w.distro, *shell, &program) { + Ok(true) => CliStatus::Ready, + Ok(false) => CliStatus::Missing, + // Falla el subsistema a media sonda. + Err(_) => CliStatus::Error, + } + } + None => CliStatus::Error, + } + }; + (p.to_string(), status) + }) + .collect() + } + None => providers + .into_iter() + .map(|(p, c)| { + let status = if matches!(find_program(&program_of(c)), Found::Missing) { + CliStatus::Missing + } else { + CliStatus::Ready + }; + (p.to_string(), status) + }) + .collect(), + } +} + +/// Estado de la CLI de login dentro de la distro (#92). +#[derive(Debug, PartialEq, Clone, Copy)] +enum CliCheck { + /// Instalada y la distro está Running. Lleva la ESTRATEGIA de shell + /// detectada: el argv la reutiliza en vez de asumir `bash -lc` + /// (revisión 2 PR #92). + Ready(ShellStrategy), + /// La distro está detenida o en transición: el SONDEO no la despierta, + /// pero el login explícito puede activarla. + Stopped, + /// La distro corre y no tiene esa CLI. + Missing, +} + +/// ¿Está `program` dentro de la distro? (issue #92). +/// +/// No despierta una distro detenida: se consulta el estado con +/// `list_distributions` (no lanza nada) y solo se sondea con `command -v` +/// cuando está Running. Una distro Stopped o en transición devuelve +/// `Stopped` (ni Missing ni error): el sondeo informa sin activarla, y el +/// login explícito decide. +fn cli_check(wsl: &WslLogin<'_>, program: &str) -> Result { + if program.is_empty() { + return Ok(CliCheck::Missing); + } + let distros = wsl + .adapter + .list_distributions() + .map_err(|e| format!("WSL: {e:?}"))?; + match distros + .iter() + .find(|d| wsl::distro_name_matches(wsl.distro, &d.name)) + { + None => Err(format!("WSL: la distro «{}» no está instalada", wsl.distro)), + Some(d) if !matches!(d.state, wsl::DistroState::Running) => Ok(CliCheck::Stopped), + Some(_) => { + let shell = wsl + .adapter + .shell_strategy(wsl.distro) + .map_err(|e| format!("WSL: {e:?}"))?; + // `command -v "$1"` (script constante, F14) con la CLI como dato: + // `command` es un builtin, no se puede `exec` como programa. + let available = wsl + .adapter + .program_available(wsl.distro, shell, program) + .map_err(|e| format!("WSL: {e:?}"))?; + Ok(if available { + CliCheck::Ready(shell) + } else { + CliCheck::Missing + }) + } + } +} + +/// Variables y carpeta de sesión de una cuenta adicional, en el ENTORNO +/// elegido (#92): en WSL la carpeta es la ruta LINUX donde el CLI escribirá +/// y donde el resolvedor de sesiones lee (la misma resolución de #91). +fn account_env( + id: &str, + cfg: &AppConfig, + wsl: Option<&WslLogin<'_>>, +) -> Result<(String, SessionEnv), String> { + if let Some(a) = cfg.accounts.iter().find(|a| a.id == id) { + let var = a + .session_env() + .ok_or_else(|| format!("La cuenta «{}» no tiene login por CLI", a.label))?; + let dir = match wsl { + Some(w) => account_session_dir_linux(a, w)?, + None => { + let d = a.session_dir(&crate::providers::home()); + std::fs::create_dir_all(&d) + .map_err(|e| format!("No pude crear {}: {e}", d.display()))?; + d + } + }; + return Ok((a.provider.to_string(), Some((var, dir)))); + } + // Cuenta PRINCIPAL con `credentials_path` personalizado (revisión PR + // #253): para el nombre estándar del CLI se usa la carpeta que lee + // `account_session`/el fetch. En host, un nombre distinto puede venir + // de un comando avanzado y mantiene el comportamiento sin variable; en + // WSL no se permite porque el CLI debe escribir donde Quorb lee. + let Some(var) = main_session_var(id) else { + return Ok((id.to_string(), None)); + }; + let Some(sub) = main_subscription(cfg, id) else { + return Ok((id.to_string(), None)); + }; + let path = sub.credentials_path.as_deref().map(str::trim).unwrap_or(""); + if path.is_empty() { + return Ok((id.to_string(), None)); + } + if wsl.is_some() { + if let Some(problem) = wsl::guest_path_problem(path) { + return Err(format!( + "La ruta de credenciales de {id} no es válida en modo WSL: {problem}" + )); + } + } + let Some(dir) = main_session_dir(id, path) else { + let file = crate::config::credentials_file_name(id).unwrap_or("…"); + // Un nombre estándar sin carpeta deducible sigue siendo inválido; + // solo los nombres distintos conservan el comando avanzado de host. + if wsl.is_none() + && Path::new(&path.replace('\\', "/")).file_name() != Path::new(file).file_name() + { + return Ok((id.to_string(), None)); + } + return Err(format!( + "La ruta de credenciales de {id} debe terminar en el fichero del CLI ({file}): así el login escribe donde Quorb lee" + )); + }; + if wsl.is_none() { + std::fs::create_dir_all(&dir) + .map_err(|e| format!("No pude crear {}: {e}", dir.display()))?; + } + Ok((id.to_string(), Some((var, dir)))) +} + +/// Config de suscripción de una cuenta principal, por proveedor. +fn main_subscription<'a>( + cfg: &'a AppConfig, + provider: &str, +) -> Option<&'a crate::config::SubscriptionConfig> { + match provider { + "claude" => Some(&cfg.claude), + "codex" => Some(&cfg.codex), + "gemini" => Some(&cfg.gemini), + "grok" => Some(&cfg.grok), + _ => None, + } +} + +/// Variable de entorno de la carpeta de sesión de una cuenta principal. +fn main_session_var(provider: &str) -> Option<&'static str> { + match provider { + "claude" => Some("CLAUDE_CONFIG_DIR"), + "codex" => Some("CODEX_HOME"), + "gemini" => Some("GEMINI_CLI_HOME"), + "grok" => Some("GROK_HOME"), + _ => None, + } +} + +/// Carpeta de la variable de sesión a partir de la ruta de credenciales +/// personalizada: la base que, unida al fichero estándar del CLI, da +/// exactamente esa ruta (`CLAUDE_CONFIG_DIR/<.credentials.json>`, o +/// `GEMINI_CLI_HOME/.gemini/oauth_creds.json`). Si no se puede derivar, el +/// llamador conserva los nombres no estándar en host sin variable adicional +/// y rechaza los demás casos con un mensaje accionable. +fn main_session_dir(provider: &str, credentials_path: &str) -> Option { + let file = crate::config::credentials_file_name(provider)?; + let normalized = credentials_path.trim().replace('\\', "/"); + let suffix = format!("/{}", file.replace('\\', "/")); + let base = normalized.strip_suffix(&suffix)?; + if base.is_empty() { + return None; + } + Some(PathBuf::from(base)) +} + +/// Carpeta de sesión LINUX de una cuenta adicional (#92): la misma regla de +/// `account_session_path` de #91 — `config_dir` absoluto del guest tal cual, +/// y la carpeta por defecto `~/.quorb` compuesta con POSIX; lo que no sea +/// POSIX (separadores de Windows o rutas relativas) se rechaza con un error +/// de configuración accionable. +fn account_session_dir_linux(a: &Account, wsl: &WslLogin<'_>) -> Result { + let home = wsl + .adapter + .resolve_home(wsl.distro) + .map_err(|e| format!("WSL: {e:?}"))?; + match &a.config_dir { + Some(d) => { + let d = d.trim(); + // Regla única de «POSIX absoluta del guest» (wsl::guest_path_problem; + // revisión del mantenedor, 2026-11-06): la misma que usan + // `resolve` y `account_session_path`, para que los mensajes no + // diverjan. + if let Some(problem) = wsl::guest_path_problem(d) { + return Err(format!( + "La carpeta de la cuenta {} no es válida en modo WSL: {problem}", + a.id + )); + } + // `"/"` es válida pero el recorte de barras la deja vacía: en el + // guest `mkdir -p -- ""` falla (revisión PR #92, menor). La raíz + // se queda como raíz. + let trimmed = d.trim_end_matches('/'); + Ok(PathBuf::from(if trimmed.is_empty() { + "/" + } else { + trimmed + })) + } + None => { + // La MISMA carpeta por defecto que el host (revisión del + // mantenedor, 2026-11-06): home_dir del canal + + // `accounts/-`, con POSIX del guest. Así la + // cuenta escribe donde la resolución de #91 lee. + let account_dir = format!("{}-{}", a.provider, a.suffix()); + let rel = wsl::guest_relative(&[ + crate::channel::current().home_dir, + "accounts", + account_dir.as_str(), + ]); + Ok(wsl::join_guest_path(&home, &rel)) + } + } +} + +/// ¿El comando ya lanza WSL por su cuenta (`wsl …` / `wsl.exe …`)? +/// +/// En modo WSL Quorb ya ejecuta el login dentro de la distro elegida: +/// envolver un comando que empieza por `wsl` lo lanzaría dos veces (un +/// segundo `wsl.exe` dentro del guest, que no existe), y buscarlo en el +/// guest da un falso «no instalado» (revisión PR #253). +fn is_wsl_command(command: &str) -> bool { + let program = split_login_command(command) + .map(|(program, _)| program) + // An invalid command cannot execute; retain the previous guard result + // for malformed inputs, including a plain wsl with unclosed arguments. + .unwrap_or_else(|_| program_of(command)); + let file = program + .rsplit(['\\', '/']) + .next() + .unwrap_or(&program) + .to_ascii_lowercase(); + file == "wsl" || file == "wsl.exe" +} + +/// Mensaje de CLI ausente DENTRO de la distro (#92): sin ofrecer el +/// instalador de Windows como solución. +fn not_installed_wsl(provider: &str, program: &str, distro: &str) -> String { + format!( + "«{program}» no está instalado dentro de «{distro}». Instálalo en la distro (la \ + instalación automática en WSL queda fuera de alcance y aquí no se ejecuta el \ + instalador de Windows). Vuelve a pulsar «Iniciar sesión» una vez instalado. \ + Proveedor: {provider}" + ) +} + +/// Prepara el lanzamiento del login en WSL SIN ejecutarlo (puro): el +/// sondeo de la CLI (Ready/Stopped/Missing) y el argv exacto. Separado del +/// spawn para que los tests no abran consolas reales y para tener una única +/// definición de la secuencia «comprobar → tokenizar → lanzar». +fn prepare_wsl_login( + wsl: &WslLogin<'_>, + provider: &str, + command: &str, + env: &SessionEnv, +) -> Result, String> { + // El comando ya lanza `wsl`: envolverlo lo ejecutaría dos veces (otro + // `wsl.exe` dentro del guest) y la sonda buscaría `wsl`, que no existe + // allí (revisión PR #253). Se pide el comando del CLI, sin `wsl`. + if is_wsl_command(command) { + return Err(format!( + "El comando de login de {provider} ya incluye `wsl`: en modo WSL escribe \ + el comando del CLI dentro de la distro (por ejemplo `codex login`) y \ + elige la distro en Ajustes; Quorb lo ejecuta dentro de ella." + )); + } + // El MISMO tokenizador que la ejecución decide el programa de la sonda + // (revisión PR #92): una ruta entre comillas o con escapes se ejecuta + // bien, pero `program_of` la daría por ausente. + let (program, _) = split_login_command(command)?; + match cli_check(wsl, &program)? { + // `Ready(shell)` ya trae la estrategia DETECTADA (no asumimos bash); + // `Stopped` — login explícito: el propio `wsl -d` la activa. Como se + // va a activar de todos modos, aquí sí se resuelve la shell de la + // distro (el sondeo informativo no la despierta; el login sí) y el + // argv la lleva: en una distro sin bash, la CLI aparece «lista» con + // sh y el login debe usar sh, no `bash: not found` (bloqueante 3, + // revisión 2 PR #92). + CliCheck::Ready(shell) => wsl_login_argv(wsl.distro, shell, command, env), + CliCheck::Stopped => { + let shell = wsl + .adapter + .shell_strategy(wsl.distro) + .map_err(|e| format!("WSL: {e:?}"))?; + wsl_login_argv(wsl.distro, shell, command, env) + } + CliCheck::Missing => Err(not_installed_wsl(provider, &program, wsl.distro)), + } +} + +/// Argv de `wsl.exe` que ejecuta el login DENTRO de la distro (#92, F14). +/// +/// El comando configurado se **tokeniza** con `split_login_command` y cada +/// token viaja como argumento POSICIONAL del script constante +/// (`$0=quorb`, `$1..=programa y args`; con cuenta adicional `$1=carpeta`, +/// `$2=programa`…): el guest lo ejecuta con su argv exacto y el host no lo +/// reparsea. Nunca se pasa el comando entero como un único elemento — se +/// trataría como el nombre de un binario con espacios. +/// +/// La carpeta de sesión de una cuenta adicional se asegura (`mkdir -p`) y se +/// aplica con el ejecutable `env` DENTRO del guest +/// (`env VAR=/ruta programa args…`), sin depender de WSLENV: así el CLI +/// escribe donde la resolución de #91 lee. +/// +/// El lanzador usa `-e`/`--exec`, NO `--`: sin `-e`, `wsl.exe` ejecuta el +/// resto de la línea con la shell por defecto de la distro, que procesa las +/// comillas y deja `exec "$@"` en `exec` sin argumentos (`exec: : not +/// found` — hallazgo de la evidencia real en WSL, 2026-11-08). Con `-e` los +/// tokens llegan al guest tal cual y el `"$@"` ve `$@` completo. +/// +/// Al terminar el login NO se cierra la consola: se ejecuta el shell del +/// usuario (`${SHELL:-/bin/sh}`), igual que `SHELL_WRAP` en host — si el +/// CLI falla, el error queda visible en la ventana (revisión PR #92). Con +/// carpeta de sesión de cuenta adicional, `$1` es la ruta y se asegura con +/// `mkdir -p --` ANTES del login: Codex falla si `CODEX_HOME` no existe. +const WSL_LOGIN_WRAP: &str = "\"$@\"; exec \"${SHELL:-/bin/sh}\""; +const WSL_LOGIN_WRAP_MKDIR: &str = + "mkdir -p -- \"$1\" && shift && \"$@\"; exec \"${SHELL:-/bin/sh}\""; + +fn wsl_login_argv( + distro: &str, + shell: ShellStrategy, + login_command: &str, + env: &SessionEnv, +) -> Result, String> { + let (program, args) = split_login_command(login_command)?; + if program.is_empty() { + return Err("Comando de login vacío (revísalo en Ajustes)".into()); + } + // La estrategia de shell DETECTADA decide bash -lc o sh -c (revisión PR + // #92): sin esto, una distro sin bash muestra la CLI como lista (el + // sondeo de `command -v` usa sh) pero el login muere en `bash: not + // found`. Llega explícita: `prepare_wsl_login` la resuelve y la pasa. + let (shell_bin, shell_flag) = match shell { + ShellStrategy::BashLogin => ("bash", "-lc"), + ShellStrategy::ShPosix => ("sh", "-c"), + }; + let mut argv: Vec = vec![ + "wsl.exe".into(), + "-d".into(), + distro.into(), + "-e".into(), + shell_bin.into(), + shell_flag.into(), + WSL_LOGIN_WRAP.into(), + "quorb".into(), + ]; + if let Some((var, dir)) = env { + // `$1` = carpeta a asegurar; detrás `env VAR=/ruta `. + // La ruta viaja como DATO posicional (F14): sin quoting de shell. + argv[6] = WSL_LOGIN_WRAP_MKDIR.into(); + // `PathBuf: Into` directamente (no vía `to_string_lossy`, + // que devuelve `Cow` y no implementa `Into`). + argv.push(dir.clone().into()); + argv.push("env".into()); + argv.push(format!("{var}={}", dir.to_string_lossy()).into()); + } + argv.push(program.into()); + argv.extend(args.into_iter().map(std::ffi::OsString::from)); + Ok(argv) +} + +/// Abre una consola nueva con `wsl.exe` y el argv exacto del login (#92). +/// +/// Los argumentos se pasan con `Command::args` (quoting MSVCRT de +/// CreateProcess), el mismo camino que mide el lab F14: nada de `cmd /C +/// start` ni de quoting manual, así que espacios, no-ASCII y metacaracteres +/// del comando personalizado llegan al guest sin reinterpretarse en el host. +#[cfg(windows)] +fn spawn_wsl_terminal(argv: &[std::ffi::OsString]) -> Result<(), String> { + use std::os::windows::process::CommandExt; + const CREATE_NEW_CONSOLE: u32 = 0x0000_0010; + let mut cmd = std::process::Command::new("wsl.exe"); + cmd.current_dir(dirs::home_dir().unwrap_or_else(|| ".".into())) + .args(argv.iter().skip(1)) + .creation_flags(CREATE_NEW_CONSOLE) + // Revisión PR #92: la terminal hereda el entorno del host y un + // `WSLENV` con, p. ej., `CODEX_HOME/p` desviaría `codex login` + // hacia la carpeta de Windows mientras Quorb lee la del guest. El + // entorno de la sesión se pasa DENTRO del guest vía `env VAR=…` + // (argv posicional, F14), así que WSLENV no aporta nada: se limpia + // para que ni el valor ni las reglas heredadas desvíen la sesión. + .env_remove("WSLENV") + .spawn() + .map(|_| ()) + .map_err(|e| format!("No pude abrir la terminal: {e}")) +} + +#[cfg(not(windows))] +fn spawn_wsl_terminal(_argv: &[std::ffi::OsString]) -> Result<(), String> { + // WSL solo existe en Windows; en este build el adaptador real ya habrá + // fallado en `cli_check` con WslNotInstalled antes de llegar aquí. + Err("WSL no está disponible en esta plataforma".into()) } /// Primer elemento del comando (`codex login` → `codex`), sin comillas. +/// Primer elemento del comando en HOST (#92): sin interpretar backslashes +/// como escapes (en Windows son separadores de carpeta; `C:\tools\codex.cmd` +/// no puede quedar `C:toolscodex.cmd` — revisión PR #92, punto 8). En WSL la +/// detección y la ejecución comparten `split_login_command` (semántica +/// POSIX del guest); son dos dominios con tokenizadores propios. fn program_of(command: &str) -> String { let c = command.trim(); if let Some(rest) = c.strip_prefix('"') { @@ -398,10 +902,9 @@ const SHELL_WRAP: &str = "\"$@\"; exec \"${SHELL:-/bin/sh}\""; /// literal): si el CLI necesita variables, deben definirse fuera del comando. /// Comillas sin cerrar devuelven `Err` y el login se aborta /// (fail-closed): el texto del usuario nunca se interpola como código. -/// Solo lo consumen `spawn_terminal` de Linux (la terminal recibe el login -/// como argv) y los tests: en Windows el comando va dentro de `cmd /K` y en -/// macOS dentro del script de Terminal. -#[cfg(any(test, all(not(windows), not(target_os = "macos"))))] +/// Lo consumen la terminal de Linux, el argv de WSL (#92) y los tests: en +/// Windows (host) el login va dentro de `cmd /K` y en macOS dentro del +/// script de Terminal. fn split_login_command(command: &str) -> Result<(String, Vec), String> { let mut tokens: Vec = Vec::new(); let mut current = String::new(); @@ -616,6 +1119,164 @@ mod tests { } } + /// Revisión PR #253: un comando que ya lanza `wsl` se reconoce (y no se + /// envuelve ni se busca dentro del guest). + #[test] + fn is_wsl_command_detects_wsl_prefixes() { + assert!(is_wsl_command("wsl codex login")); + assert!(is_wsl_command(" WSL.EXE codex login")); + assert!(is_wsl_command( + r#""C:\Windows\System32\wsl.exe" codex login"# + )); + assert!(!is_wsl_command("codex login")); + assert!(!is_wsl_command("wslx codex login")); + assert!(!is_wsl_command("")); + } + + /// Revisión PR #253, punto 2: la carpeta de la variable de sesión sale de + /// la ruta de credenciales personalizada de la cuenta principal, de modo + /// que el login escribe exactamente donde se lee. + #[test] + fn main_session_dir_is_derived_from_the_credentials_path() { + assert_eq!( + main_session_dir("claude", "D:\\trabajo\\.credentials.json"), + Some(PathBuf::from("D:/trabajo")) + ); + assert_eq!( + main_session_dir("codex", "/home/user/.codex/auth.json"), + Some(PathBuf::from("/home/user/.codex")) + ); + // Gemini guarda el fichero en una subcarpeta de su home: la base no es + // el padre del fichero, sino el home que lo contiene. + assert_eq!( + main_session_dir("gemini", "/home/user/.gemini/oauth_creds.json"), + Some(PathBuf::from("/home/user")) + ); + // Una ruta que no termina en el fichero del CLI no permite derivar la + // carpeta; el llamador decide si conserva el comando o rechaza en WSL. + assert_eq!(main_session_dir("claude", "D:\\trabajo\\otra.json"), None); + assert_eq!(main_session_dir("cursor", "/tmp/x"), None); + } + + /// La cuenta principal con `credentials_path` personalizado exporta la + /// variable de sesión apuntando a la carpeta de esa ruta (PR #253). + #[test] + fn main_account_with_custom_credentials_path_passes_the_session_dir() { + let tmp = TempDir::new("principal-custom"); + let custom = tmp.path().join(".credentials.json"); + let mut cfg = AppConfig::default(); + cfg.claude.credentials_path = Some(custom.to_string_lossy().into_owned()); + let (provider, env) = account_env("claude", &cfg, None).expect("env"); + assert_eq!(provider, "claude"); + let (var, dir) = env.expect("la cuenta principal usa la carpeta personalizada"); + assert_eq!(var, "CLAUDE_CONFIG_DIR"); + assert_eq!(dir.as_path(), tmp.path()); + } + + /// Sin ruta personalizada, la principal no exporta nada: el CLI usa su + /// carpeta por defecto (comportamiento de siempre). + #[test] + fn main_account_without_custom_path_passes_nothing() { + let cfg = AppConfig::default(); + let (_, env) = account_env("claude", &cfg, None).expect("env"); + assert!(env.is_none()); + } + + /// Un comando avanzado de host puede escribir un nombre no estándar: no + /// se deduce una carpeta ni se altera el comando configurado. + #[test] + fn main_account_nonstandard_host_filename_keeps_advanced_command_without_override() { + let tmp = TempDir::new("principal-custom-filename"); + let absent_dir = tmp.path().join("not-created"); + let synthetic = absent_dir.join("auth-work.json"); + let paths = [ + r"C:\work\auth-work.json".to_string(), + synthetic.to_string_lossy().into_owned(), + ]; + let mut cfg = AppConfig::default(); + assert!(!absent_dir.exists()); + for path in paths { + let command = format!("custom-login --output \"{path}\""); + cfg.codex.credentials_path = Some(path); + cfg.codex.login_command = command.clone(); + assert_eq!(account_env("codex", &cfg, None), Ok(("codex".into(), None))); + assert_eq!(cfg.codex.login_command, command); + assert!(!absent_dir.exists(), "no se crea una carpeta de sesión"); + } + } + + /// Los nombres estándar conservan su variable y carpeta; el guest rechaza + /// rutas inválidas o nombres distintos antes de consultar el adaptador. + #[test] + fn main_account_standard_filenames_and_guest_validation_are_preserved() { + let tmp = TempDir::new("principal-standard-filenames"); + for (provider, file, var) in [ + ("claude", ".credentials.json", "CLAUDE_CONFIG_DIR"), + ("codex", "auth.json", "CODEX_HOME"), + ("gemini", ".gemini/oauth_creds.json", "GEMINI_CLI_HOME"), + ("grok", "auth.json", "GROK_HOME"), + ] { + let dir = tmp.path().join(provider); + let credentials = dir.join(file); + let mut cfg = AppConfig::default(); + let sub = match provider { + "claude" => &mut cfg.claude, + "codex" => &mut cfg.codex, + "gemini" => &mut cfg.gemini, + "grok" => &mut cfg.grok, + _ => unreachable!(), + }; + sub.credentials_path = Some(credentials.to_string_lossy().into_owned()); + assert_eq!( + account_env(provider, &cfg, None), + Ok((provider.into(), Some((var, dir.clone())))) + ); + assert!(dir.is_dir()); + assert!(!credentials.exists(), "no se crea el fichero de sesión"); + } + + // Un nombre estándar sin carpeta deducible ya se rechazaba en host. + let mut cfg = AppConfig::default(); + cfg.codex.credentials_path = Some("auth.json".into()); + assert_eq!( + account_env("codex", &cfg, None), + Err("La ruta de credenciales de codex debe terminar en el fichero del CLI (auth.json): así el login escribe donde Quorb lee".into()) + ); + + let mock = crate::wsl::MockWslAdapter::new(); + let wsl = WslLogin { + adapter: &mock, + distro: "synthetic-distro", + }; + let mut cfg = AppConfig::default(); + cfg.gemini.credentials_path = Some("/synthetic/session/.gemini/oauth_creds.json".into()); + assert_eq!( + account_env("gemini", &cfg, Some(&wsl)), + Ok(( + "gemini".into(), + Some(("GEMINI_CLI_HOME", PathBuf::from("/synthetic/session"))) + )) + ); + for (path, expected) in [ + ( + r"C:\work\auth-work.json", + r"La ruta de credenciales de codex no es válida en modo WSL: La ruta en modo WSL no puede llevar separadores de Windows (\). Pega la ruta del guest (por ejemplo /home/usuario/...) en su lugar: C:\work\auth-work.json", + ), + ( + "relative/auth.json", + "La ruta de credenciales de codex no es válida en modo WSL: La ruta en modo WSL debe ser absoluta del guest (empieza por '/'), se recibió: relative/auth.json", + ), + ( + "/synthetic/session/auth-work.json", + "La ruta de credenciales de codex debe terminar en el fichero del CLI (auth.json): así el login escribe donde Quorb lee", + ), + ] { + cfg.codex.credentials_path = Some(path.into()); + assert_eq!(open("codex", &cfg, Some(WslLogin { ..wsl })), Err(expected.into())); + assert!(mock.calls().is_empty(), "el guest no recibe llamadas"); + } + } + #[test] fn program_of_keeps_quoted_paths_with_spaces() { assert_eq!(program_of("codex login"), "codex"); @@ -995,3 +1656,1006 @@ mod tests { assert!(dirs.contains(&PathBuf::from("/usr/local/bin"))); } } + +#[cfg(test)] +mod wsl_login_tests { + use super::*; + use crate::cli_process::CommandOutput; + use crate::wsl::{distro, DistroState, MockWslAdapter, ShellStrategy, WslCall}; + + fn wsl_of(mock: &MockWslAdapter) -> WslLogin<'_> { + WslLogin { + adapter: mock, + distro: "Ubuntu-22.04", + } + } + + /// En modo WSL, un comando que ya incluye `wsl` no se envuelve: se pide el + /// comando del CLI con un mensaje accionable (PR #253). + #[test] + fn wsl_login_rejects_a_command_that_already_launches_wsl() { + for command in [ + "wsl codex login", + "WSL.EXE codex login", + r#""C:\Windows\System32\wsl.exe" codex login"#, + "wsl 'unterminated", + "'wsl' codex login", + "'wsl.exe' codex login", + ] { + let mock = MockWslAdapter::new(); + let result = prepare_wsl_login(&wsl_of(&mock), "codex", command, &None); + assert_eq!( + result, + Err("El comando de login de codex ya incluye `wsl`: en modo WSL escribe el comando del CLI dentro de la distro (por ejemplo `codex login`) y elige la distro en Ajustes; Quorb lo ejecuta dentro de ella.".into()), + "{command}" + ); + assert!(mock.calls().is_empty(), "{command}: {:?}", mock.calls()); + } + } + + #[test] + fn cli_status_rejects_normalized_wsl_programs_without_guest_probes() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/synthetic/cli\n".into(), + stderr: String::new(), + }); + let mut cfg = AppConfig::default(); + cfg.claude.login_command = "'wsl' codex login".into(); + cfg.codex.login_command = "'wsl.exe' codex login".into(); + cfg.gemini.login_command = r#""C:\Windows\System32\WSL.EXE" codex login"#.into(); + cfg.grok.login_command = "wsl codex login".into(); + + let status = cli_status(&cfg, Some(wsl_of(&mock))); + assert!( + status.values().all(|s| *s == CliStatus::Error), + "{status:?}" + ); + assert_eq!(status.len(), 4); + assert_eq!( + mock.calls(), + vec![ + WslCall::ListDistributions, + WslCall::ShellStrategy("Ubuntu-22.04".into()), + ] + ); + } + + #[test] + fn ordinary_guest_cli_detection_and_literal_argv_are_preserved() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/synthetic/cli\n".into(), + stderr: String::new(), + }); + let mut cfg = AppConfig::default(); + cfg.codex.login_command = r#""/opt/my tools/codex" login --label "ñ&|;$HOME""#.into(); + + let status = cli_status(&cfg, Some(wsl_of(&mock))); + assert_eq!(status["codex"], CliStatus::Ready); + let expected_probe = WslCall::RunCommand( + "Ubuntu-22.04".into(), + [ + "bash", + "-c", + wsl::SCRIPT_COMMAND_V, + "quorb", + "/opt/my tools/codex", + ] + .into_iter() + .map(String::from) + .collect(), + ); + assert!(mock.calls().contains(&expected_probe), "{:?}", mock.calls()); + + let argv = prepare_wsl_login(&wsl_of(&mock), "codex", &cfg.codex.login_command, &None) + .expect("ordinary guest login argv"); + assert_eq!( + argv, + vec![ + "wsl.exe", + "-d", + "Ubuntu-22.04", + "-e", + "bash", + "-lc", + WSL_LOGIN_WRAP, + "quorb", + "/opt/my tools/codex", + "login", + "--label", + "ñ&|;$HOME", + ] + ); + assert_eq!(mock.calls().last(), Some(&expected_probe)); + } + + /// #92: la CLI se detecta DENTRO de la distro (Running) con `command -v`. + #[test] + fn cli_available_detects_inside_a_running_distro() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/usr/bin/codex\n".into(), + stderr: String::new(), + }); + assert!(matches!( + cli_check(&wsl_of(&mock), "codex").expect("sonda"), + CliCheck::Ready(shell) if shell == ShellStrategy::BashLogin + )); + // CLI ausente dentro de la distro (exit 127 de `command -v`). + mock.set_command_output(CommandOutput { + code: 127, + stdout: String::new(), + stderr: String::new(), + }); + assert!(matches!( + cli_check(&wsl_of(&mock), "codex").expect("sonda"), + CliCheck::Missing + )); + } + + /// #92 (criterio 8): una distro STOPPED no se despierta por un sondeo; + /// se reporta como no disponible sin lanzar nada dentro. + #[test] + fn cli_available_does_not_wake_a_stopped_distro() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Stopped)]); + assert!(matches!( + cli_check(&wsl_of(&mock), "codex").expect("sin despertar"), + CliCheck::Stopped + )); + assert!( + mock.calls() + .iter() + .all(|c| !matches!(c, WslCall::RunCommand(..) | WslCall::ShellStrategy(..))), + "no se sondea una distro parada, llamadas: {:?}", + mock.calls() + ); + } + + /// Distro configurada que no existe en la enumeración: error explícito. + #[test] + fn cli_available_reports_unknown_distro() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Debian", DistroState::Running)]); + let err = cli_check(&wsl_of(&mock), "codex").unwrap_err(); + assert!(err.contains("no está instalada"), "{err}"); + } + + /// F14: el login se TOKENIZA (no viaja como un único elemento) y cada + /// token queda como argumento posicional del script `exec "$@"`; la + /// carpeta de la cuenta viaja con `env` dentro del guest (sin WSLENV). + #[test] + fn wsl_login_argv_tokenizes_program_and_args_and_applies_env_inside() { + let argv = wsl_login_argv( + "Ubuntu 24.04", + ShellStrategy::BashLogin, + "codex login --device-auth", + &None, + ) + .expect("argv"); + assert_eq!( + argv, + vec![ + "wsl.exe", + "-d", + "Ubuntu 24.04", + "-e", + "bash", + "-lc", + // El login corre con `"$@"` y después se abre el shell: la + // consola no se cierra si el CLI falla (revisión PR #92). + "\"$@\"; exec \"${SHELL:-/bin/sh}\"", + "quorb", + "codex", + "login", + "--device-auth", + ] + ); + // AC6: no-ASCII y metacaracteres viajan como DATO (token), no + // interpretados por el host. + let odd = wsl_login_argv( + "Distro Ñandú", + ShellStrategy::BashLogin, + "codex login --label \"ñ&|;$HOME\"", + &None, + ) + .expect("argv"); + assert!(odd.iter().any(|t| t.to_string_lossy() == "Distro Ñandú")); + assert!(odd + .iter() + .any(|t| t.to_string_lossy().contains("ñ&|;$HOME"))); + } + + /// La carpeta de la cuenta adicional se aplica con `env` DENTRO del + /// guest: `env CLAUDE_CONFIG_DIR= claude …` (sin dependencia de + /// WSLENV y sin quoting de shell). + #[test] + fn wsl_login_argv_applies_the_account_folder_inside_the_guest() { + let env = Some(( + "CLAUDE_CONFIG_DIR", + PathBuf::from("/home/user/.quorb/accounts/claude-w1"), + )); + let argv = wsl_login_argv( + "Ubuntu-22.04", + ShellStrategy::BashLogin, + "claude --dangerously-skip-permissions", + &env, + ) + .expect("argv"); + // La carpeta se asegura ANTES del login (`mkdir -p -- "$1"`): Codex + // falla si CODEX_HOME no existe (revisión PR #92). + assert!( + argv.iter().any(|t| t + .to_string_lossy() + .starts_with("mkdir -p -- \"$1\" && shift")), + "el script asegura la carpeta de sesión: {:?}", + argv.iter().nth(6) + ); + // `$1` = carpeta, como dato posicional justo tras el script. + let folder = argv + .iter() + .position(|t| t.to_string_lossy() == "/home/user/.quorb/accounts/claude-w1") + .expect("carpeta como dato posicional"); + assert_eq!(argv[folder - 1], "quorb", "carpeta es $1"); + assert!(argv.iter().any( + |t| t.to_string_lossy() == "CLAUDE_CONFIG_DIR=/home/user/.quorb/accounts/claude-w1" + )); + let pos = argv.iter().position(|t| t == "env").expect("env presente"); + let prog = argv.iter().position(|t| t == "claude").expect("programa"); + assert!(pos < prog, "env precede al programa"); + assert!(folder < pos, "carpeta ($1) precede a env"); + } + + /// La estrategia de shell DETECTADA llega al argv (bloqueante 3, revisión + /// 2 PR #92): `ShPosix` → `sh -c`, no `bash -lc` — en una distro sin bash + /// el login moría en `bash: not found` tras anunciarse la CLI como lista. + #[test] + fn wsl_login_argv_uses_the_detected_shell_strategy() { + let posix = + wsl_login_argv("Ubuntu-22.04", ShellStrategy::ShPosix, "codex", &None).expect("argv"); + let sh = posix + .iter() + .position(|t| t.to_string_lossy() == "sh") + .expect("sh presente"); + assert_eq!(posix[sh + 1].to_string_lossy(), "-c"); + assert!( + !posix.iter().any(|t| t.to_string_lossy() == "bash"), + "sin bash en la distro, el argv no puede invocarlo" + ); + // BashLogin sigue usando `bash -lc`. + let login = + wsl_login_argv("Ubuntu-22.04", ShellStrategy::BashLogin, "codex", &None).expect("argv"); + let bash = login + .iter() + .position(|t| t.to_string_lossy() == "bash") + .expect("bash presente"); + assert_eq!(login[bash + 1].to_string_lossy(), "-lc"); + } + + /// AC7: el comando del usuario se ejecuta DENTRO de la distro y no + /// recibe un `wsl` adicional; la semántica se documenta aquí (el + /// ejecutable `wsl.exe` solo aparece UNA vez, como lanzador del host). + #[test] + fn wsl_login_argv_has_a_single_launcher_and_no_double_wsl() { + let argv = wsl_login_argv( + "Ubuntu-22.04", + ShellStrategy::BashLogin, + "codex login --device-auth", + &None, + ) + .expect("argv"); + assert_eq!( + argv.iter().filter(|t| *t == "wsl.exe").count(), + 1, + "un solo wsl.exe" + ); + // Si el usuario escribiera un comando que YA empieza por wsl, seguiría + // siendo un DATO del guest (no se le antepone otro wsl.exe): el token + // `wsl` vive después de `quorb` (posiciones 2+), nunca como lanzador. + let double = wsl_login_argv( + "Ubuntu-22.04", + ShellStrategy::BashLogin, + "wsl codex login", + &None, + ) + .expect("argv"); + let quorb = double.iter().position(|t| t == "quorb").expect("argv0"); + let guest_wsl = double + .iter() + .position(|t| t == "wsl") + .expect("el token del comando viaja al guest"); + assert!(guest_wsl > quorb, "«wsl» del comando no es el lanzador"); + assert_eq!( + double.iter().filter(|t| *t == "wsl.exe").count(), + 1, + "un solo lanzador wsl.exe" + ); + assert_eq!( + double.last().map(|t| t.to_string_lossy()), + Some("login".into()) + ); + } + + /// `cli_status` consulta la distro cuando el entorno es WSL; en host + /// sigue siendo la detección de Windows de siempre (no rompe). + #[test] + fn cli_status_uses_the_distro_when_wsl_and_keeps_host_otherwise() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/usr/bin/claude\n".into(), + stderr: String::new(), + }); + let mut cfg = AppConfig::default(); + cfg.claude.login_command = "claude".into(); + cfg.codex.login_command = "codex login".into(); + let wsl_status = cli_status(&cfg, Some(wsl_of(&mock))); + assert_eq!(wsl_status["claude"], CliStatus::Ready); + // El mock responde 0 a TODO `command -v`; codex/gemini/grok también + // aparecen detectados (el stub responde igual). + assert!(wsl_status.len() == 4); + // En host la detección depende de las CLIs que tenga instaladas el + // runner; no fijar su resultado. Solo comprobar que devuelve los + // cuatro proveedores y que la ruta host sigue operativa. + let host_status = cli_status(&cfg, None); + assert_eq!(host_status.len(), 4); + assert!(host_status + .values() + .all(|s| matches!(s, CliStatus::Ready | CliStatus::Missing))); + } + + /// El contrato distingue «distro detenida» (Stopped) de «CLI ausente» + /// (Missing): con la distro Stopped la UI NO debe proponer instalar la + /// CLI, y el sondeo NO la despierta (sin `run_command` ni sondeo de + /// shell). Escenario que el booleano anterior mostraba como «no + /// instalada» (revisión PR #92). + #[test] + fn cli_status_reports_stopped_without_waking_the_distro_or_probing() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Stopped)]); + let cfg = AppConfig::default(); + let status = cli_status(&cfg, Some(wsl_of(&mock))); + assert!( + status.values().all(|s| *s == CliStatus::Stopped), + "{status:?}" + ); + assert!(status.len() == 4); + // No se ha ejecutado nada dentro de la distro: solo enumeración. + let calls = mock.calls(); + assert!( + calls + .iter() + .all(|c| matches!(c, crate::wsl::WslCall::ListDistributions)), + "la distro detenida no se despierta: {calls:?}" + ); + } + + /// El contrato distingue WSL roto/distro inexistente (Error) de «CLI + /// ausente»: si la distro no está enumerada, no es un problema de + /// instalación de la CLI. + #[test] + fn cli_status_reports_error_for_an_unknown_distro() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + let cfg = AppConfig::default(); + let status = cli_status( + &cfg, + Some(WslLogin { + adapter: &mock, + distro: "Otra-Distro", + }), + ); + assert!( + status.values().all(|s| *s == CliStatus::Error), + "{status:?}" + ); + } + + /// `wslDistro` vacío (sin configuración) cae a Host: `session_env()` + /// ya lo guarda en config.rs; aquí se verifica que `cli_status`/login + /// nunca ven una distro vacía (menor de la revisión PR #92). + #[test] + fn empty_wsl_distro_never_reaches_the_wsl_path() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + let mut cfg = AppConfig::default(); + // El usuario eligió SESIÓN WSL pero dejó la distro vacía: en + // producción `session_env()` cae a Host (config.rs) y el login/detección + // no deben tocar wsl.exe. Este test cubre ESE caso (revisión PR #92, + // punto 5): antes solo usaba un cfg ya de host. + cfg.session_env = crate::config::SessionEnvConfig::Wsl; + cfg.wsl_distro = "".into(); + assert!(matches!(cfg.session_env(), wsl::SessionEnv::Host)); + let host_status = cli_status(&cfg, None); + assert!(host_status.len() == 4); + let calls = mock.calls(); + assert!( + calls.is_empty(), + "wsl.exe no se toca con distro vacía: {calls:?}" + ); + } + + /// #92: si la CLI no está dentro de la distro, el login falla con un + /// mensaje que dirige a instalarla EN LA DISTRO y NO ofrece el + /// instalador de Windows. + #[test] + fn open_in_wsl_requires_the_cli_inside_the_distro() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 127, + stdout: String::new(), + stderr: String::new(), + }); + let cfg = AppConfig::default(); // codex.login_command por defecto + let env: SessionEnv = None; + let err = prepare_wsl_login( + &wsl_of(&mock), + "codex", + cfg.codex.login_command.trim(), + &env, + ) + .unwrap_err(); + assert!(err.contains("no está instalado dentro"), "{err}"); + assert!( + !err.contains("/K wsl"), + "no se abre la terminal si la CLI falta" + ); + } + + /// La carpeta LINUX de la cuenta adicional: `config_dir` absoluto del + /// guest tal cual; separadores del host o relativos rechazados; sin + /// config_dir → `home_dir` del canal + `accounts/-` + #[test] + fn account_session_dir_linux_uses_config_dir_or_host_layout() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_home("Ubuntu-22.04", PathBuf::from("/home/user")); + let mk = |dir: Option| Account { + id: "claude:w1".into(), + provider: "claude".into(), + config_dir: dir, + enabled: true, + ..Default::default() + }; + assert_eq!( + account_session_dir_linux(&mk(Some("/mnt/c/Users/yo/quorb".into())), &wsl_of(&mock)) + .expect("absoluta del guest"), + PathBuf::from("/mnt/c/Users/yo/quorb") + ); + // Sin config_dir: MISMA carpeta que en host + // (`home_dir` del canal + `accounts/-`). + assert_eq!( + account_session_dir_linux(&mk(None), &wsl_of(&mock)).expect("defecto"), + PathBuf::from("/home/user/.quorb/accounts/claude-w1") + ); + let err = account_session_dir_linux(&mk(Some(r"C:\Users\yo\quorb".into())), &wsl_of(&mock)) + .unwrap_err(); + assert!(err.contains("Windows"), "{err}"); + let err = account_session_dir_linux(&mk(Some("accounts/claude-1".into())), &wsl_of(&mock)) + .unwrap_err(); + assert!(err.contains("absoluta"), "{err}"); + } + + /// #92 (review 2026-11-05): una distro DETENIDA no da un «no instalada» + /// falso: el login explícito la activa (el propio `wsl -d`). El sondeo + /// no la despierta: no hubo `command -v` dentro. + #[test] + fn open_in_wsl_activates_a_stopped_distro_instead_of_saying_missing() { + let mock = MockWslAdapter::new(); + mock.set_installed(true); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Stopped)]); + // El login EXPLÍCITO resuelve la estrategia de shell aunque la + // distro esté detenida (la despierta el propio `wsl -d`): el argv + // reutiliza bash/sh detectado, no asume bash (revisión 2 PR #92). + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + let cfg = AppConfig::default(); + let env: SessionEnv = None; + let argv = prepare_wsl_login( + &wsl_of(&mock), + "codex", + cfg.codex.login_command.trim(), + &env, + ) + .expect("login explícito preparado (la distro se activa al lanzar)"); + assert!(!argv + .iter() + .any(|t| t.to_string_lossy().contains("no está instalado dentro"))); + assert!( + mock.calls() + .iter() + .all(|c| !matches!(c, WslCall::RunCommand(..))), + "el sondeo no despierta la distro, llamadas: {:?}", + mock.calls() + ); + } + + /// Con la CLI presente, el login llega al lanzador (no al error de CLI + /// ausente). + #[test] + fn open_in_wsl_with_the_cli_present_reaches_the_launcher() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/usr/bin/codex\n".into(), + stderr: String::new(), + }); + let cfg = AppConfig::default(); + let env: SessionEnv = None; + let argv = prepare_wsl_login( + &wsl_of(&mock), + "codex", + cfg.codex.login_command.trim(), + &env, + ) + .expect("argv del login"); + assert_eq!( + argv.first().map(|t| t.to_string_lossy().into_owned()), + Some("wsl.exe".into()) + ); + assert!(!argv + .iter() + .any(|t| t.to_string_lossy().contains("no está instalado dentro"))); + } + + /// La detección y la ejecución usan el MISMO tokenizador (revisión 2 PR + /// #92): una ruta entre comillas con espacios se detecta como presente + /// y se ejecuta con su argv exacto — no da por ausente lo que luego se + /// ejecutaría. + #[test] + fn detection_and_execution_agree_on_a_quoted_path_with_spaces() { + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_command_output(CommandOutput { + code: 0, + stdout: "/opt/mis herramientas/claude\n".into(), + stderr: String::new(), + }); + let cmd = "\"/opt/mis herramientas/claude\" login"; + // La sonda recibe el ejecutable tokenizado (con espacios intactos). + assert!( + matches!( + cli_check(&wsl_of(&mock), &program_of(cmd)).expect("sonda"), + CliCheck::Ready(_) + ), + "una ruta entre comillas se detecta como presente" + ); + // Y la ejecución lanza ESE MISMO programa como token del guest. + let argv = prepare_wsl_login(&wsl_of(&mock), "claude", cmd, &None).expect("argv del login"); + assert!( + argv.iter() + .any(|t| t.to_string_lossy() == "/opt/mis herramientas/claude"), + "el ejecutable viaja como token con espacios intactos: {argv:?}" + ); + // El texto del comando NUNCA va como un único elemento (F14). + assert!( + !argv.iter().any(|t| t + .to_string_lossy() + .contains("mis herramientas/claude\" login")), + "el comando no viaja como un solo elemento" + ); + } + + /// El mensaje de CLI ausente no lleva espacios dobles ni saltos Rare + /// (se muestra en la UI). + #[test] + fn missing_cli_message_has_no_double_spaces() { + let msg = not_installed_wsl("codex", "codex", "Ubuntu-22.04"); + assert!(!msg.contains(" "), "{msg}"); + assert!( + msg.contains("no está instalado dentro de «Ubuntu-22.04»"), + "{msg}" + ); + } + + /// `account_env`: en host la carpeta es la de siempre; en WSL, la ruta + /// LINUX de la cuenta (misma regla que la resolución de #91). + #[test] + fn account_env_uses_the_host_folder_and_the_guest_folder() { + let dir = std::env::temp_dir().join(format!("quorb-login-env-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut cfg = AppConfig::default(); + cfg.accounts.push(Account { + id: "claude:w1".into(), + provider: "claude".into(), + config_dir: Some(dir.to_string_lossy().into_owned()), + enabled: true, + ..Default::default() + }); + // Host: la carpeta configurada, tal cual. + let (provider, env) = account_env("claude:w1", &cfg, None).expect("host"); + assert_eq!(provider, "claude"); + let (var, folder) = env.expect("variable de sesión"); + assert_eq!(var, "CLAUDE_CONFIG_DIR"); + assert_eq!(folder, dir); + // El MISMO config_dir (ruta del host con `\` o `C:\`) en modo WSL + // se rechaza: no es una carpeta que el guest pueda leer (diseño de + // #92/#91). + let mock = MockWslAdapter::new(); + mock.set_distributions(vec![distro("Ubuntu-22.04", DistroState::Running)]); + mock.set_shell("Ubuntu-22.04", ShellStrategy::BashLogin); + mock.set_home("Ubuntu-22.04", PathBuf::from("/home/user")); + cfg.accounts[0].config_dir = Some(r"C:\Users\yo\quorb".into()); + let err = account_env("claude:w1", &cfg, Some(&wsl_of(&mock))).unwrap_err(); + assert!( + err.contains("separadores de Windows") || err.contains("absoluta"), + "{err}" + ); + // En WSL, un `config_dir` POSIX del guest se usa tal cual: el login + // escribe donde la resolución de #91 lee. + cfg.accounts[0].config_dir = Some("/mnt/c/Users/yo/quorb".into()); + let (_, env) = account_env("claude:w1", &cfg, Some(&wsl_of(&mock))).expect("wsl"); + let (_, folder) = env.expect("variable de sesión"); + assert_eq!(folder, PathBuf::from("/mnt/c/Users/yo/quorb")); + let _ = std::fs::remove_dir_all(&dir); + } +} + +/// Legacy Windows/WSL integration checks, not interactive-login evidence. +/// +/// These ignored tests require a dedicated, pre-provisioned disposable guest: +/// GAP2 resolves a command by name and GAP3 reads a fixed fixture path. Never +/// point them at a personal distro. GAP4 is replaced below by a hermetic +/// synthetic test; none of these checks opens Quorb's terminal or proves S6. +#[cfg(windows)] +#[cfg(test)] +mod wsl_evidence { + use super::*; + use crate::wsl::{RealWslAdapter, SessionResolver, WslAdapter}; + + fn distro() -> String { + std::env::var("QUORB_WSL_EVIDENCE_DISTRO").expect( + "el workflow debe exportar QUORB_WSL_EVIDENCE_DISTRO (distro real de la evidencia)", + ) + } + + /// GAP1 — Una CLI presente SOLO dentro de la distro se reconoce sin + /// requerir la misma CLI en Windows (AC1). + #[test] + #[ignore = "requiere WSL real (evidencia #92)"] + fn gap1_detects_a_cli_that_only_exists_inside_the_distro() { + let adapter = RealWslAdapter::new(); + let d = distro(); + let wsl = WslLogin { + adapter: &adapter, + distro: &d, + }; + // Los shims se plantan SOLO en el guest (el PATH de Windows no los + // tiene): la detección debe encontrarlos dentro de la distro. + for cli in ["codex", "claude"] { + assert!( + matches!(cli_check(&wsl, cli), Ok(CliCheck::Ready(_))), + "«{cli}» debe estar Ready dentro de la distro" + ); + } + // Y el PATH de Windows no los tiene: la detección no viene de ahí. + let out = std::process::Command::new("where.exe") + .arg("codex") + .output() + .expect("where.exe"); + assert!( + !out.status.success(), + "codex no debe estar en el PATH de Windows (si lo está, el shim no era exclusivo del guest)" + ); + } + + /// GAP2 — El comando de login se ejecuta DENTRO de la distro y escribe + /// allí (AC2/AC3): el shim deja un marker en el guest. + #[test] + #[ignore = "requiere WSL real (evidencia #92)"] + fn gap2_login_command_runs_inside_the_distro() { + let d = distro(); + // Mismo argv que compone la app (script constante + comando como dato). + let argv = + wsl_login_argv(&d, ShellStrategy::BashLogin, "codex", &None).expect("argv del login"); + let out = std::process::Command::new("wsl.exe") + .args(argv.iter().skip(1)) + .output() + .expect("wsl.exe"); + assert!( + out.status.success(), + "el comando debe ejecutarse en la distro (salida omitida)" + ); + // El marker del shim está DENTRO de la distro. + let check = std::process::Command::new("wsl.exe") + .args(["-d", &d, "-e", "test", "-f", "/tmp/quorb-evidence-login"]) + .output() + .expect("wsl.exe"); + assert!( + check.status.success(), + "el shim debe haber escrito dentro de la distro" + ); + } + + /// GAP3 — La lectura de sesión usa la ruta EXACTA que la resolución + /// espera (AC3): `/.quorb/accounts/claude-w1/.credentials.json`. + #[test] + #[ignore = "requiere WSL real (evidencia #92)"] + fn gap3_session_read_uses_the_resolved_path_inside_the_distro() { + let adapter: std::sync::Arc = std::sync::Arc::new(RealWslAdapter::new()); + let d = distro(); + let home = adapter + .resolve_home(&d) + .unwrap_or_else(|_| panic!("no se pudo resolver el home de la distro")); + let r = SessionResolver::for_wsl(adapter, d.clone(), home, crate::i18n::Locale::Es); + let path = r.default_path(&crate::wsl::guest_relative(&[ + ".quorb", + "accounts", + "claude-w1", + ".credentials.json", + ])); + // `read` (no `read_async`) a propósito: este test no tiene runtime + // de tokio, y la evidencia es la ruta resuelta DENTRO de la distro — + // `read` y `read_async` comparten el mismo `adapter.read_file`. + let contents = r + .read(&path) + .unwrap_or_else(|_| panic!("no se pudo leer la sesión sintética")); + assert!(contents.contains("v-evidencia-92"), "marcador ausente"); + } +} + +/// Hermetic replacement for GAP4: run the generated guest shell argv locally +/// against an absolute, test-owned shim, then pass its synthetic output through +/// the WSL session resolver and mock adapter. This is not Windows/WSL or login +/// evidence. No vendor executable, guest resource, or real session is used. +#[cfg(test)] +#[cfg(unix)] +mod synthetic_wsl_login_lab { + use super::*; + use crate::wsl::{MockWslAdapter, SessionResolver, WslCall}; + use std::io::Write; + use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Arc; + + const DISTRO: &str = "synthetic-distro"; + const LITERAL_ARG: &str = "ñ&|;$HOME"; + static NEXT_FIXTURE: AtomicUsize = AtomicUsize::new(0); + + struct Fixture(PathBuf); + + impl Fixture { + fn new() -> Self { + // create_dir is exclusive: never remove or reuse an existing path. + for _ in 0..128 { + let n = NEXT_FIXTURE.fetch_add(1, Ordering::Relaxed); + let root = std::env::temp_dir() + .join(format!("quorb-synthetic-login-{}-{n}", std::process::id())); + match std::fs::DirBuilder::new().mode(0o700).create(&root) { + Ok(()) => { + let fixture = Self(root); + let mut shim = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o700) + .open(fixture.shim()) + .expect("create synthetic shim"); + shim.write_all( + b"#!/bin/sh\ntest \"$2\" = '\xc3\xb1&|;$HOME' || exit 1\nprintf '%s' \"$1\" > \"$CLAUDE_CONFIG_DIR/.credentials.json\" || exit 1\nprintf invoked > \"$3\"\n", + ) + .expect("write synthetic shim"); + return fixture; + } + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(_) => panic!("create synthetic fixture"), + } + } + panic!("could not allocate a unique synthetic fixture") + } + + fn shim(&self) -> PathBuf { + self.0.join("quorb's synthetic shim") + } + + fn session_dir(&self) -> PathBuf { + self.0.join("account Ñ &") + } + + fn session_file(&self) -> PathBuf { + self.session_dir().join(".credentials.json") + } + + fn marker(&self) -> String { + format!( + "synthetic-only-{}", + self.0.file_name().unwrap().to_string_lossy() + ) + } + + fn run(&self) -> Result<(), &'static str> { + // Do not follow a replaced session directory outside the fixture. + match std::fs::symlink_metadata(self.session_dir()) { + Ok(m) if !m.file_type().is_dir() => { + return Err("invalid fixture session directory") + } + Ok(_) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err("cannot inspect fixture session directory"), + } + // Reject even a matching prior marker, before starting the shim. + match std::fs::symlink_metadata(self.session_file()) { + Ok(_) => return Err("synthetic output already exists"), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return Err("cannot inspect synthetic output"), + } + + let adapter = Arc::new(MockWslAdapter::new()); + adapter.set_home(DISTRO, self.0.clone()); + let wsl = WslLogin { + adapter: adapter.as_ref(), + distro: DISTRO, + }; + let cfg = AppConfig { + accounts: vec![Account { + id: "claude:synthetic".into(), + provider: "claude".into(), + config_dir: Some(self.session_dir().to_string_lossy().into_owned()), + enabled: true, + ..Default::default() + }], + ..Default::default() + }; + let (provider, env) = account_env("claude:synthetic", &cfg, Some(&wsl)) + .map_err(|_| "cannot resolve synthetic account environment")?; + if provider != "claude" || env != Some(("CLAUDE_CONFIG_DIR", self.session_dir())) { + return Err("unexpected synthetic account environment"); + } + let resolver = SessionResolver::for_wsl( + adapter.clone(), + DISTRO.into(), + self.0.clone(), + crate::i18n::Locale::Es, + ); + let path = crate::providers::account_session_path(&cfg.accounts[0], Some(&resolver)) + .map_err(|_| "cannot resolve synthetic account path")? + .ok_or("missing synthetic account path")?; + if Path::new(&path) != self.session_file().as_path() { + return Err("login and resolver paths differ"); + } + + let invoked = self.0.join("shim-invoked"); + let command = format!( + "{} {} {} {}", + sh_quote(&self.shim().to_string_lossy()), + sh_quote(&self.marker()), + sh_quote(LITERAL_ARG), + sh_quote(&invoked.to_string_lossy()), + ); + let argv = wsl_login_argv(DISTRO, ShellStrategy::ShPosix, &command, &env) + .map_err(|_| "cannot construct synthetic argv")?; + let expected: Vec = vec![ + "wsl.exe".into(), + "-d".into(), + DISTRO.into(), + "-e".into(), + "sh".into(), + "-c".into(), + WSL_LOGIN_WRAP_MKDIR.into(), + "quorb".into(), + self.session_dir().into(), + "env".into(), + format!("CLAUDE_CONFIG_DIR={}", self.session_dir().display()).into(), + self.shim().into(), + self.marker().into(), + LITERAL_ARG.into(), + invoked.into(), + ]; + if argv != expected { + return Err("unexpected synthetic argv"); + } + // Execute only the guest-shell suffix locally; the absolute shim + // is ours, and no child output or inherited credentials escape. + let status = std::process::Command::new("/bin/sh") + .args(argv.iter().skip(5)) + .env_clear() + .env("HOME", &self.0) + .env("PATH", "/usr/bin:/bin") + // Resolved through PATH: macOS has no /bin/true. + .env("SHELL", "true") + .current_dir(&self.0) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .status() + .map_err(|_| "cannot launch synthetic shell")?; + if !status.success() { + return Err("synthetic shell failed"); + } + let output = std::fs::read_to_string(self.session_file()) + .map_err(|_| "synthetic output missing")?; + if output != self.marker() { + return Err("synthetic output mismatch"); + } + // The mock receives only the newly produced fixture data; the + // resolver must request the exact path calculated by the provider. + adapter.set_file(DISTRO, PathBuf::from(&path), output); + let read = resolver + .read(Path::new(&path)) + .map_err(|_| "cannot read synthetic session through resolver")?; + if read != self.marker() + || !adapter + .calls() + .contains(&WslCall::ReadFile(DISTRO.into(), path.into())) + { + return Err("synthetic resolver mismatch"); + } + Ok(()) + } + } + + impl Drop for Fixture { + fn drop(&mut self) { + // This exact private directory was exclusively created by new(). + let _ = std::fs::remove_dir_all(&self.0); + } + } + + #[test] + fn synthetic_gap4_runs_owned_shim_and_resolves_its_output() { + let fixture = Fixture::new(); + let other = Fixture::new(); + assert_ne!(fixture.session_dir(), other.session_dir()); + std::fs::create_dir(other.session_dir()).expect("create other synthetic account"); + std::fs::write(other.session_file(), "other synthetic session") + .expect("seed other account"); + assert!(fixture.run().is_ok(), "synthetic login seam failed"); + assert!(fixture.0.join("shim-invoked").is_file()); + assert!( + std::fs::read_to_string(other.session_file()).unwrap() == "other synthetic session" + ); + assert!(matches!( + fixture.run(), + Err("synthetic output already exists") + )); + } + + #[test] + fn synthetic_gap4_rejects_a_matching_prior_output_before_running() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.session_dir()).expect("create synthetic account"); + std::fs::write(fixture.session_file(), fixture.marker()).expect("seed stale output"); + assert!(matches!( + fixture.run(), + Err("synthetic output already exists") + )); + assert!(!fixture.0.join("shim-invoked").exists()); + assert!(std::fs::read_to_string(fixture.session_file()).unwrap() == fixture.marker()); + } + + #[test] + fn synthetic_gap4_rejects_a_session_directory_symlink() { + let fixture = Fixture::new(); + let other = Fixture::new(); + std::fs::create_dir(other.session_dir()).expect("create other synthetic account"); + std::fs::write(other.session_file(), "other synthetic session") + .expect("seed other account"); + std::os::unix::fs::symlink(other.session_dir(), fixture.session_dir()) + .expect("create synthetic symlink"); + assert!(matches!( + fixture.run(), + Err("invalid fixture session directory") + )); + assert!(!fixture.0.join("shim-invoked").exists()); + assert!( + std::fs::read_to_string(other.session_file()).unwrap() == "other synthetic session" + ); + } +} diff --git a/src-tauri/src/providers/mod.rs b/src-tauri/src/providers/mod.rs index d17655b..051dafc 100644 --- a/src-tauri/src/providers/mod.rs +++ b/src-tauri/src/providers/mod.rs @@ -389,7 +389,12 @@ pub(crate) fn session_relative(kind: CliSessionKind) -> PathBuf { /// - Sin `config_dir` → la carpeta por defecto (`~/.quorb`) compuesta bajo /// el home del entorno. /// En host devuelve la ruta de `credentials_file` de siempre. -fn account_session_path( +/// +/// La usan el fetch de la cuenta y el SONDEO de presencia (`account_session`, +/// revisión PR #92): con `resolver` la ruta sale del ENTORNO elegido (el +/// guest), no del disco del host — tras un login en WSL, sondear el host +/// daría por buena una sesión de Windows sin relación. +pub(crate) fn account_session_path( a: &Account, resolver: Option<&SessionResolver>, ) -> Result, String> { diff --git a/src-tauri/src/wsl/mod.rs b/src-tauri/src/wsl/mod.rs index d912da6..32445cf 100644 --- a/src-tauri/src/wsl/mod.rs +++ b/src-tauri/src/wsl/mod.rs @@ -17,6 +17,7 @@ mod process; mod real; mod session; pub use mock::{MockWslAdapter, WslCall}; +pub use process::SCRIPT_COMMAND_V; pub use real::{build_wslenv_entry, RealWslAdapter, SESSION_ENV_ALLOWLIST}; pub use session::{SessionEnv, SessionError, SessionResolver}; @@ -123,6 +124,46 @@ pub trait WslAdapter: Send + Sync { env: &[(&str, &str)], ) -> Result; + /// ¿Existe `program` en el PATH de la distro? (#92) + /// + /// `command -v` es un BUILTIN de la shell: no se puede `exec` como + /// programa (`exec command -v …` sale con 127 en WSL real — hallazgo + /// del lab W3, 2026-10-30) y `run_command` toma un PROGRAMA en + /// `args[0]`. La sonda es el script constante `SCRIPT_COMMAND_V` + /// ejecutado por la shell del entorno (bash o sh, según la estrategia) + /// con el nombre del programa como DATO posicional (F14, doble + /// frontera): el host nunca interpola el nombre en un script. + /// + /// `false` significa «la CLI no está en la distro»: `command -v` de un + /// programa ausente sale con exit ≠ 0 y salida vacía — eso NO es un + /// fallo de WSL, y los errores del subsistema (classify) sí se + /// propagan. + /// + /// El default va por `run_command` (suficiente para el mock). Sobre el + /// adaptador REAL hay que implementarla sobre una PRIMITIVA DE SONDA + /// (exit code como parte de la respuesta): `run_scoped`, que usa + /// `run_command`, convierte cualquier exit ≠ 0 en `Err` y haría + /// inalcanzable el `Ok(false)`. `RealWslAdapter` la sobrescribe con + /// `control_raw` (revisión 2026-11-08). + fn program_available( + &self, + distro: &str, + shell: ShellStrategy, + program: &str, + ) -> Result { + let shell_bin = match shell { + ShellStrategy::BashLogin => "bash", + ShellStrategy::ShPosix => "sh", + }; + let out = self.run_command( + distro, + shell, + &[shell_bin, "-c", SCRIPT_COMMAND_V, "quorb", program], + &[], + )?; + Ok(out.code == 0 && !out.stdout.trim().is_empty()) + } + /// Diagnóstico de los 4 estados (F6) con sondas separadas. /// `target` es la distro elegida (si hay): permite producir /// `WslState::DistroUnavailable` (decisión paso 0 #3) y el detalle F2. diff --git a/src-tauri/src/wsl/real.rs b/src-tauri/src/wsl/real.rs index ae24d28..feddef7 100644 --- a/src-tauri/src/wsl/real.rs +++ b/src-tauri/src/wsl/real.rs @@ -335,6 +335,53 @@ impl WslAdapter for RealWslAdapter { }) } + /// Sonda de programa de la distro (#92): `command -v "$1"` con el + /// nombre como dato posicional (F14). + /// + /// NO usa `run_command`: `run_scoped` (con pidfile) convierte CUALQUIER + /// exit ≠ 0 en `Err`, y `command -v` de un programa ausente sale con + /// 1/127 — el estado «no instalado» debe ser `Ok(false)`, no un fallo + /// de WSL (revisión 2026-11-08; el mock, que devuelve `Ok` con el exit + /// code dentro, nunca lo habría visto). Sigue el patrón de sonda de + /// `shell_strategy` (`control_raw`: el exit code ES la respuesta) y sin + /// pidfile: 1 invocación de `wsl.exe` por CLI, nada de crear/limpiar + /// directorios en el guest por sonda. + /// + /// Solo los errores reales del subsistema se propagan (classify): una + /// distro que desapareció entre la enumeración y la sonda NO se + /// confunde con «CLI ausente». + fn program_available( + &self, + distro: &str, + shell: ShellStrategy, + program: &str, + ) -> Result { + let argv = shell_args(Some(distro), shell, SCRIPT_COMMAND_V, &[program]); + let cwd = Self::cwd(); + let output = self + .runner(&self.env, &cwd) + .control_raw(&argv, Some(distro))?; + if let Some(wsl_error) = classify(&output, Some(distro)) { + return Err(wsl_error); + } + // `command -v "$1"` sale con 0 y la ruta en stdout cuando existe; con + // 1 (bash) o 127 (sh) y stdout vacío cuando NO. Cualquier otra cosa + // (exit -1, señal, salida inesperada) es un fallo del subsistema o + // del script, NO «la CLI no está instalada»: reportarlo como error + // evita invitar a instalar algo que ya está o enmascarar WSL roto + // (revisión PR #92, punto 9). + if output.code == 0 && !output.stdout.trim().is_empty() { + return Ok(true); + } + if (output.code == 1 || output.code == 127) && output.stdout.trim().is_empty() { + return Ok(false); + } + Err(WslError::UnparsableOutput(format!( + "sonda command -v inesperada (exit {})", + output.code + ))) + } + /// Ejecuta un comando con el script constante y los datos como /// parámetros posicionales (F14, doble frontera). fn run_command( @@ -647,6 +694,107 @@ mod tests { ); } + /// Sonda de programa: «no instalado» es `Ok(false)`, NO un error. + /// + /// `command -v` de un programa ausente sale con exit 1 (bash) o 127 + /// (sh) y salida vacía. Con `run_command`/`run_scoped` eso se + /// convertía en `Err(UnparsableOutput)`, dejando inalcanzable el + /// estado `Missing` de la detección (#92, revisión 2026-11-08). + #[test] + fn program_available_absent_is_false_not_error() { + for code in [1, 127] { + let runner = FakeRunner::default(); + runner.respond( + "command -v \"$1\"", + CommandOutput { + code, + stdout: String::new(), + stderr: String::new(), + }, + ); + let adapter = adapter(runner.clone()); + assert!( + !adapter + .program_available("Ubuntu-22.04", ShellStrategy::ShPosix, "codex") + .expect("CLI ausente no es error"), + "exit {code} debe ser Ok(false)" + ); + // Una sola invocación y SIN pidfile (mktemp/mkdir): la sonda no + // paga el ciclo de vida del run_scoped. + let calls = runner.calls(); + assert_eq!(calls.len(), 1, "una invocación por sonda"); + let joined = calls[0].join(" "); + assert!(joined.contains("command -v \"$1\""), "{joined}"); + assert!(!joined.contains("mktemp"), "sin pidfile: {joined}"); + } + } + + /// Exit -1 (señal/crash del script o del subsistema) con salida vacía NO + /// es «CLI ausente»: es un fallo y debe propagarse como error para no + /// invitar a instalar algo que ya está (revisión PR #92, punto 9). + #[test] + fn program_available_treats_unexpected_exit_as_error_not_missing() { + let runner = FakeRunner::default(); + runner.respond( + "command -v \"$1\"", + CommandOutput { + code: -1, + stdout: String::new(), + stderr: String::new(), + }, + ); + let adapter = adapter(runner); + let err = adapter + .program_available("Ubuntu-22.04", ShellStrategy::ShPosix, "codex") + .expect_err("exit -1 debe ser Err"); + assert!( + matches!(err, WslError::UnparsableOutput(ref m) if m.contains("exit -1")), + "{err:?}" + ); + } + + /// Sonda de programa: la CLI presente devuelve `Ok(true)` (exit 0 con + /// la ruta impresa por `command -v`). + #[test] + fn program_available_present_is_true() { + let runner = FakeRunner::default(); + runner.respond("command -v \"$1\"", ok("/usr/local/bin/codex\n")); + let adapter = adapter(runner); + assert!( + adapter + .program_available("Ubuntu-22.04", ShellStrategy::BashLogin, "codex") + .expect("sonda"), + "command -v con salida y exit 0 es presente" + ); + } + + /// La sonda NO disfraza un fallo del subsistema de «CLI ausente»: si la + /// distro desapareció, se propaga `DistroNotFound`. + #[test] + fn program_available_propagates_wsl_distro_loss() { + let runner = FakeRunner::default(); + runner.respond( + "command -v \"$1\"", + CommandOutput { + code: -1, + stdout: String::new(), + stderr: concat!( + "The system cannot find the file specified.", + "Error code: Wsl/Service/WSL_E_DISTRO_NOT_FOUND" + ) + .to_string(), + }, + ); + let adapter = adapter(runner); + let err = adapter + .program_available("Ghost-22.04", ShellStrategy::BashLogin, "codex") + .expect_err("debe fallar"); + assert!( + matches!(err, WslError::DistroNotFound(ref d) if d == "Ghost-22.04"), + "debe ser DistroNotFound: {err:?}" + ); + } + /// El diagnóstico distingue WSL ausente de cero distros (F6). #[test] fn diagnose_reports_wsl_not_installed() { diff --git a/src/Settings-accounts-i18n.test.tsx b/src/Settings-accounts-i18n.test.tsx index f3116d5..80f8ed5 100644 --- a/src/Settings-accounts-i18n.test.tsx +++ b/src/Settings-accounts-i18n.test.tsx @@ -9,7 +9,7 @@ import { describe, expect, it } from 'vitest'; import { CLI_INSTALL, defaultSessionDir } from './lib/accounts'; import type { CodexInstallController } from './lib/codex-install'; import type { Account, AccountProvider, Locale } from './lib/types'; -import { AccountEditor, CliConnectView, CliMissing } from './Settings'; +import { AccountEditor, CliConnectView, CliMissing, CliMissingWsl } from './Settings'; const noop = () => {}; @@ -35,8 +35,8 @@ const codexInstall = {} as CodexInstallController; const connect = ( locale: Locale, - provider: 'claude' | 'gemini', - over: { cliMissing?: boolean; persisted?: boolean; extra?: boolean; dirty?: boolean; connected?: boolean; loginError?: string | null } = {}, + provider: 'claude' | 'codex' | 'gemini', + over: { cliMissing?: boolean; persisted?: boolean; extra?: boolean; dirty?: boolean; connected?: boolean; loginError?: string | null; sessionEnv?: 'host' | 'wsl'; wslDistro?: string } = {}, ) => renderToStaticMarkup( { health={health(locale)} codexInstall={codexInstall} onCodexRecheck={noop} + sessionEnv="host" + wslDistro="" />, ); @@ -474,3 +478,53 @@ describe('CLI_INSTALL.whereKey (CliMissing, i18n)', () => { } }); }); + +// CLI ausente en los DOS entornos (revisión 2 PR #92): en host se ofrecen +// los instaladores de Windows; en WSL, instrucciones manuales del guest +// (los instaladores de Windows no aplican dentro de la distro). +describe('Missing CLI per environment (SSR, i18n)', () => { + it('offers Windows installers on host', () => { + const html = connect('es', 'claude', { cliMissing: true, sessionEnv: 'host' }); + expect(html).toContain('Falta Claude Code en este equipo.'); + expect(html).toContain('install.ps1'); + }); + + it('does not offer the Codex host installer inside WSL', () => { + // `-codex` en host montaría `CodexInstall` (useSyncExternalStore, no + // renderizable en SSR); lo que importa es que en WSL NO aparezca. + const html = connect('es', 'codex', { + cliMissing: true, + sessionEnv: 'wsl', + wslDistro: 'Ubuntu-22.04', + }); + expect(html).toContain('Falta Codex CLI dentro de la distro WSL «Ubuntu-22.04».'); + expect(html).toContain('npm install -g @openai/codex'); + expectNone(html, ['Instala Codex', 'install.ps1', 'Código de instalación'], 'es'); + }); + + it('offers guest instructions in WSL instead of Windows installers', () => { + const html = connect('es', 'claude', { + cliMissing: true, + sessionEnv: 'wsl', + wslDistro: 'Ubuntu-22.04', + }); + // Instrucciones del guest, con la distro en el mensaje… + expect(html).toContain('Falta Claude Code dentro de la distro WSL «Ubuntu-22.04».'); + expect(html).toContain('Ubuntu-22.04'); + expect(html).toContain('curl -fsSL https://claude.ai/install.sh | bash'); + // …y NINGÚN instalador de Windows (ni el asistido ni comandos de host). + expectNone(html, ['install.ps1', 'Instala Claude Code en este equipo', 'Instalar'], 'es'); + }); + + it('CliMissingWsl keeps the distro optional and translates to en', () => { + const withDistro = renderToStaticMarkup( + , + ); + expectAll(withDistro, ['is missing inside the WSL distro', 'Ubuntu-24.04', 'npm install -g @openai/codex'], 'en'); + const withoutDistro = renderToStaticMarkup( + , + ); + expectAll(withoutDistro, ['dentro de la distro WSL', 'npm install -g @google/gemini-cli'], 'es'); + expectNone(withoutDistro, ['install.ps1'], 'es'); + }); +}); diff --git a/src/Settings-panels-i18n.test.tsx b/src/Settings-panels-i18n.test.tsx index d8b3a3e..cd91b9a 100644 --- a/src/Settings-panels-i18n.test.tsx +++ b/src/Settings-panels-i18n.test.tsx @@ -66,7 +66,7 @@ const common = (locale: Locale) => ({ healthFor: healthFor(locale), }); -const subscription = (locale: Locale, p: 'claude' | 'codex' | 'gemini' | 'grok', cli: Record = {}) => +const subscription = (locale: Locale, p: 'claude' | 'codex' | 'gemini' | 'grok', cli: Record = {}) => renderToStaticMarkup(); const cursor = (locale: Locale) => renderToStaticMarkup(); const antigravity = (locale: Locale) => renderToStaticMarkup(); @@ -208,9 +208,9 @@ describe('Subscription provider panels (SSR, i18n)', () => { ); }); - it('warns in WSL mode that the CLI detection and login are still the Windows ones (PR #248)', () => { - // Hasta #92, la detección del CLI y el login abren el CLI de HOST: el paso - // de conexión lo declara en vez de presentarse como si corriera en la distro. + it('does not warn that WSL detection/login are Windows-only: #92 already runs them in the distro', () => { + // El aviso de seguimiento de #248 («la detección y el login siguen siendo + // los de Windows hasta #92») ya no aplica en esta rama: es falsa aquí. const wslCfg = { ...cfg, sessionEnv: 'wsl' } as AppConfig; const html = renderToStaticMarkup( { onCodexRecheck={noop} />, ); - expect(html).toContain('Modo WSL'); - expect(html).toContain('usan el CLI de Windows'); - // En host no aparece el aviso. - const hostHtml = subscription('es', 'claude'); - expect(hostHtml).not.toContain('Modo WSL'); + expect(html).not.toContain('usan el CLI de Windows'); }); it('renders the Spanish literals of Cursor copied verbatim from the current code', () => { diff --git a/src/Settings-providers-i18n.test.tsx b/src/Settings-providers-i18n.test.tsx index 7351319..2844483 100644 --- a/src/Settings-providers-i18n.test.tsx +++ b/src/Settings-providers-i18n.test.tsx @@ -502,4 +502,23 @@ describe('Provider cards: aria-current and aria-expanded follow the selection (S expect(count(html, 'aria-current="false"')).toBe(cards(html)); expect(count(html, 'aria-expanded="false"')).toBe(cards(html)); }); + + // El selector de entorno (host/WSL + distro) SIEMPRE abre el login hacia + // `wsl.exe` y las sesiones del guest: solo existe en Windows (revisión PR + // #92). Fuera de Windows no se renderiza la etiqueta ni el campo. + it('hides the session environment selector outside Windows', () => { + for (const platform of ['macos', 'linux'] as const) { + const html = card('es', 'claude', true, platform); + expect(html).not.toContain('Sesión de los CLIs'); + expect(html).not.toContain('Distro WSL'); + expect(html).not.toContain('sessionEnv'); + } + }); + + it('renders the session environment selector on Windows', () => { + const html = card('es', 'claude', true, 'windows'); + expect(html).toContain('Sesión de los CLIs'); + // El campo de distro solo aparece en modo WSL (el helper cfg usa host). + expect(html).not.toContain('Distro WSL'); + }); }); diff --git a/src/Settings.tsx b/src/Settings.tsx index 7ffb7bc..cb47a4a 100644 --- a/src/Settings.tsx +++ b/src/Settings.tsx @@ -1,4 +1,4 @@ -import { createContext, useCallback, useContext, useEffect, useRef, useState, type CSSProperties, type ReactNode, type Ref } from 'react'; +import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type Ref } from 'react'; import { listen } from '@tauri-apps/api/event'; import { emailDefaults, emailReady, patchEmail, persistEmailTestAlerts, sendEmailTest } from './lib/email'; import type { EmailStatus } from './lib/types'; @@ -589,6 +589,55 @@ export function CliMissing({ provider, locale = 'es' }: { provider: AccountProvi ); } +/** Falta la CLI DENTRO de la distro WSL: instrucciones manuales del guest + * (los instaladores de Windows no aplican ahí — revisión PR #92). */ +export function CliMissingWsl({ provider, locale = 'es', wslDistro }: { provider: AccountProvider; locale?: Locale; wslDistro?: string }) { + const how = CLI_INSTALL[provider]; + if (!how) return null; + const distro = wslDistro?.trim(); + // «Ubuntu-22.04» o vacío: el título no debe pegar el nombre sin separador. + const namedDistro = distro ? ` «${distro}»` : ''; + const perProvider: Record = { + claude: `curl -fsSL https://claude.ai/install.sh | bash`, + codex: `npm install -g @openai/codex`, + gemini: `npm install -g @google/gemini-cli`, + grok: `npm install -g @vibe-kit/grok-cli`, + }; + const cmd = perProvider[provider] ?? ''; + return ( +
+ + {t(locale, 'settings.providers.cliMissingWsl.title', { name: how.name, distro: namedDistro })}{' '} + {t(locale, 'settings.providers.cliMissingWsl.body')} + + {cmd && ( + + {cmd} + + + )} +
+ ); +} + +/** Botón de copiar reutilizable para comandos (extraído de CliMissing). */ +function CliCopyButton({ text, locale }: { text: string; locale: Locale }) { + const [copied, setCopied] = useState(false); + const copy = () => + navigator.clipboard + .writeText(text) + .then(() => { + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }) + .catch(() => {}); + return ( + + ); +} + /** Lo que necesita el paso de comprobación: lo guardado, las claves y si hay cambios sin guardar. */ type HealthProps = { /** Config guardada: cuando cambia (al guardar) se vuelve a comprobar. */ @@ -758,24 +807,36 @@ export function HealthStepView({ locale, h, hidden, dirty, busy, saving, loginBu ); } -/** ¿Hay sesión del CLI para esta cuenta? Se mira cada 3 s mientras está abierta. */ -function useCliSession(id: string, active: boolean): boolean { - const [connected, setConnected] = useState(false); +/** ¿Hay sesión del CLI para esta cuenta? Se mira cada 3 s mientras está abierta. + * Los sondeos fallidos se degradan a "no hay fichero confirmado" (revisión PR + * #92, punto 11): jamás se muestra conectada por omisión. */ +function useCliSession(id: string, active: boolean, envKey: string): boolean { + const [connected, setConnected] = useState(false); useEffect(() => { if (!active) { setConnected(false); return; } + // Entorno nuevo (host ↔ WSL o distro distinta): el resultado del sondeo + // anterior ya no vale. Se olvida el estado y se arranca un poller NUEVO, + // cuya generación descarta las respuestas en vuelo del anterior + // (revisión PR #253: dos sondeos solapados no comparten generación). + setConnected(null); // Presencia del fichero, no validez: al desmontar se para el sondeo y las // respuestas en vuelo se descartan (no marca conectada otra cuenta). const poller = createPresencePoller({ exists: () => api.accountSessionFileExists(id), + // Un fallo de sondeo deja `null` (desconocido); jamás "conectada" por + // omisión (revisión PR #92, punto 11). onResult: setConnected, }); poller.start(); return () => poller.stop(); - }, [id, active]); - return connected; + }, [id, active, envKey]); + // `null` (sondeo fallido o entorno recién cambiado) se degrada a "no hay + // fichero confirmado": la UI nunca muestra el botón "conectada" sin una + // prueba vigente del entorno actual. + return connected === true; } /** @@ -794,6 +855,7 @@ function CliConnect({ codexInstall, onCodexRecheck, sessionEnv = 'host', + wslDistro = '', }: { /** Idioma de los pasos. */ locale: Locale; @@ -810,11 +872,16 @@ function CliConnect({ codexInstall: CodexInstallController; /** Relectura del CLI compartida con la raíz tras una instalación. */ onCodexRecheck: () => void; - /** Entorno elegido (revisión PR #248): en WSL, detección y login siguen - * siendo los de Windows hasta que aterrice #92. */ + /** Entorno elegido (revisiones PR #248/#253): en WSL, detección y login + * siguen siendo los de Windows hasta que aterrice #92; el sondeo de + * presencia se reinicia al cambiar de entorno. */ sessionEnv?: 'host' | 'wsl'; + /** Distro WSL elegida (informativa en las instrucciones del guest). */ + wslDistro?: string; }) { - const connected = useCliSession(id, persisted); + // El entorno del BORRADOR forma parte de la identidad del sondeo: al + // cambiarlo, el poller se reinicia con una generación nueva (PR #253). + const connected = useCliSession(id, persisted, `${sessionEnv}\u0000${wslDistro}`); const [busy, setBusy] = useState(false); const [loginError, setLoginError] = useState(null); const connect = async () => { @@ -847,11 +914,12 @@ function CliConnect({ health={health} codexInstall={codexInstall} onCodexRecheck={onCodexRecheck} + sessionEnv={sessionEnv} + wslDistro={wslDistro} connected={connected} busy={busy} loginError={loginError} onConnect={connect} - sessionEnv={sessionEnv} /> ); } @@ -874,6 +942,7 @@ export function CliConnectView({ loginError, onConnect, sessionEnv = 'host', + wslDistro = '', }: { locale: Locale; id: string; @@ -892,26 +961,30 @@ export function CliConnectView({ /** Diagnóstico del último intento de login que falló. */ loginError: string | null; onConnect: () => void; - /** Entorno elegido: en WSL, detección y login aún son los de Windows (#92). */ + /** Entorno elegido (revisiones PR #92/#248): en WSL no se ofrecen los + * instaladores de Windows y se avisa de que detección/login son los de + * Windows hasta #92. */ sessionEnv?: 'host' | 'wsl'; + /** Distro WSL elegida (informativa en las instrucciones del guest). */ + wslDistro?: string; }) { + const wsl = sessionEnv === 'wsl'; return ( <> - {sessionEnv === 'wsl' && ( -
  • - {/* Hasta #92 la detección del CLI y el login abren el CLI de HOST: - no deben presentarse como si ya corrieran dentro de la distro - (revisión PR #248). */} - - {t(locale, 'settings.providers.cliConnect.wslHostOnly')} - -
  • - )} {cliMissing && (
  • - {t(locale, 'settings.providers.cliConnect.installTitle', { name: CLI_INSTALL[provider]?.name ?? t(locale, 'settings.providers.cliConnect.cliFallback') })} - {t(locale, 'settings.providers.cliConnect.installBody')} - {provider === 'codex' ? : } + {wsl ? ( + // Instaladores de host (Codex asistido, comandos de Windows) NO + // aplican dentro de la distro: se ofrecen las instrucciones + // manuales del guest (revisión PR #92). + + ) : ( + <> + {t(locale, 'settings.providers.cliConnect.installTitle', { name: CLI_INSTALL[provider]?.name ?? t(locale, 'settings.providers.cliConnect.cliFallback') })} + {t(locale, 'settings.providers.cliConnect.installBody')} + {provider === 'codex' ? : } + + )}
  • )}
  • @@ -968,6 +1041,7 @@ export function AccountEditor({ codexInstall, onCodexRecheck, sessionEnv = 'host', + wslDistro = '', }: { /** Idioma del editor. */ locale: Locale; @@ -988,9 +1062,12 @@ export function AccountEditor({ /** Instalación asistida de Codex, compartida por la raíz y todas las cuentas. */ codexInstall: CodexInstallController; onCodexRecheck: () => void; - /** Entorno elegido (revisión PR #248): en WSL, detección y login son los de - * Windows hasta #92. */ + /** Entorno elegido (revisiones PR #248/#253): en WSL, detección y login + * son los de Windows hasta #92; el sondeo de presencia se reinicia al + * cambiar de entorno. */ sessionEnv?: 'host' | 'wsl'; + /** Distro WSL elegida (informativa en las instrucciones del guest). */ + wslDistro?: string; }) { const appName = useAppName(); const key = (k: SecretKey) => secretKey(k, a.id); @@ -1026,7 +1103,7 @@ export function AccountEditor({
  • {session && ( - + )} {a.provider === 'cursor' && ( @@ -1321,9 +1398,9 @@ export function ProvidersCard({ locale, cfg, secrets, tab, drawerOpen, onSelectT onRefreshMinutes: (minutes: number) => void; onSessionEnv: (env: 'host' | 'wsl') => void; onWslDistro: (distro: string) => void; - /** Plataforma del proceso (UA): el modo WSL solo existe en Windows (revisión - * PR #248, bloqueante). Fuera de Windows no se ofrece guardar WSL, que el - * widget convertiría en un error de `wsl.exe` en cada refresco. */ + /** Plataforma del proceso (UA): el modo WSL solo existe en Windows + * (revisiones PR #92/#248). Fuera de Windows no se ofrece guardar WSL, que + * el widget convertiría en un error de `wsl.exe` en cada refresco. */ platform?: Os; }) { const providerCard = (p: (typeof PROVIDER_TABS)[number]) => ( @@ -1363,8 +1440,9 @@ export function ProvidersCard({ locale, cfg, secrets, tab, drawerOpen, onSelectT {t(locale, 'settings.providers.wslDistro')} onWslDistro(e.target.value)} /> - {/* WSL sin distro se resuelve como HOST (config.rs; revisión PR - #248): el campo lo dice hasta que se escribe una distro. */} + {/* WSL sin distro se resuelve como HOST (config.rs; + revisiones PR #92/#248): el campo lo dice hasta que se + escribe una distro. */} {cfg.wslDistro.trim() === '' ? t(locale, 'settings.providers.wslDistroMissing') : t(locale, 'settings.providers.wslDistroHint')} @@ -2016,7 +2094,7 @@ export function SubscriptionPanel({ onCodexRecheck, }: Pick & { p: 'claude' | 'codex' | 'gemini' | 'grok'; - cli: Record; + cli: Record; codexInstall: CodexInstallController; onCodexRecheck: () => void; }) { @@ -2070,13 +2148,14 @@ export function SubscriptionPanel({ id={p} provider={p} loginCommand={cfg[p].loginCommand} - cliMissing={cli[p] === false} + cliMissing={cli[p] === "missing"} persisted extra={false} health={healthFor(p, !cfg[p].enabled)} codexInstall={codexInstall} onCodexRecheck={onCodexRecheck} sessionEnv={cfg.sessionEnv} + wslDistro={cfg.wslDistro} />
    @@ -2487,31 +2566,63 @@ export function Settings() { const [secrets, setSecrets] = useState({}); // CLIs de login instalados (Claude Code, Codex, Gemini): se avisa antes de pulsar // «Iniciar sesión» y se detecta solo cuando se instala (cada 5 s o al volver a la ventana). - const [cli, setCli] = useState>({}); + // Estado por proveedor: 'ready' | 'missing' | 'stopped' | 'error' (#92). + // Solo 'missing' propone instalar la CLI: una distro detenida (stopped) o + // un fallo de WSL (error) no se arreglan instalando nada. + const [cli, setCli] = useState>({}); + // El ENTORNO DEL BORRADOR (host/WSL + distro) es el que se detecta (revisión + // PR #92, punto 10): `cli_status` refleja lo que el usuario ve, no la config + // persistida. Cambiar el entorno en el selector re-sondea; el objeto se + // memoiza para que un render no reinicie el sondeo. + const cliSessionEnv = cfg?.sessionEnv; + const cliWslDistro = cfg?.wslDistro; + const cliEnv = useMemo( + () => (cliSessionEnv === undefined ? undefined : { sessionEnv: cliSessionEnv, wslDistro: cliWslDistro ?? '' }), + [cliSessionEnv, cliWslDistro], + ); + // Ref del entorno: el controlador de instalación de Codex se crea una sola + // vez y conserva la clausura del primer render; el recheck debe leer el + // entorno VIGENTE, no el de entonces. + const cliEnvRef = useRef(cliEnv); + cliEnvRef.current = cliEnv; + // UNA secuencia para TODAS las lecturas de `cli_status` — intervalo, foco y + // `cliRecheck` (revisión PR #253): solo la última petición lanzada escribe + // el estado, así una respuesta tardía no pisa la del entorno nuevo ni + // deshabilita «Guardar»/el login con un `missing` viejo. + const cliSeqRef = useRef(0); + const requestCliStatus = useCallback(() => { + const n = ++cliSeqRef.current; + return api + .cliStatus(cliEnvRef.current) + .then((st) => { + if (n === cliSeqRef.current) setCli(st); + }) + .catch(() => {}); + }, []); // Relectura puntual del CLI fuera del intervalo: la usa la instalación asistida // al terminar para habilitar el login sin depender de que la ventana siga abierta. const cliRecheck = useCallback(() => { - api - .cliStatus() - .then(setCli) - .catch(() => {}); - }, []); + void requestCliStatus(); + }, [requestCliStatus]); useEffect(() => { let alive = true; - const check = () => - api - .cliStatus() - .then((st) => alive && setCli(st)) - .catch(() => {}); + // Entorno nuevo: el estado anterior es de otro sitio; no se muestra hasta + // que llegue la lectura vigente (y no puede bloquear el login entremedias). + setCli({}); + const check = () => { + if (alive) void requestCliStatus(); + }; check(); const t = window.setInterval(check, 5000); window.addEventListener('focus', check); return () => { alive = false; + // Descarta lo que esté en vuelo: solo la secuencia nueva escribe. + cliSeqRef.current += 1; window.clearInterval(t); window.removeEventListener('focus', check); }; - }, []); + }, [cliEnv, requestCliStatus]); // Controlador de la instalación asistida de Codex: vive en la raíz de Ajustes // para seguir vivo si el aviso del CLI desaparece (o se desmonta) antes de que // resuelva la instalación. Nunca instala por sí solo: solo lee estado pasivo. @@ -2846,7 +2957,18 @@ export function Settings() { const sectionDirty = (id: string) => { const acc = cfg.accounts.find((a) => a.id === id); const k = configKeyFor(acc?.provider ?? id); - return isConnectionDirty(acc, baseline?.accounts.find((a) => a.id === id), k ? cfg[k] : undefined, k ? baseline?.[k] : undefined); + // El entorno (host/WSL + distro) es parte de la conexión (revisión PR + // #92): cambiarlo y pulsar iniciar sesión sin guardar usaría el entorno + // guardado, no el que se ve. + const envOf = (c: typeof cfg) => ({ sessionEnv: c.sessionEnv, wslDistro: c.wslDistro }); + return isConnectionDirty( + acc, + baseline?.accounts.find((a) => a.id === id), + k ? cfg[k] : undefined, + k ? baseline?.[k] : undefined, + envOf(cfg), + baseline ? envOf(baseline) : undefined, + ); }; const healthFor = (id: string, hidden: boolean): HealthProps => ({ saved: baseline, secretsSig, dirty: sectionDirty(id), hidden, saving, onSave: save, locale }); const panel = { locale, cfg, secrets, set, setVisibility, loadSecrets, healthFor }; @@ -2957,7 +3079,9 @@ export function Settings() { onRemove={() => removeAccount(selAccount)} onSecrets={loadSecrets} health={healthFor(selAccount.id, !selAccount.enabled)} - cliMissing={cli[selAccount.provider] === false} + cliMissing={cli[selAccount.provider] === "missing"} + sessionEnv={cfg.sessionEnv} + wslDistro={cfg.wslDistro} loginCommand={ selAccount.provider === 'claude' || selAccount.provider === 'codex' || selAccount.provider === 'gemini' || selAccount.provider === 'grok' ? cfg[selAccount.provider].loginCommand @@ -2965,7 +3089,6 @@ export function Settings() { } codexInstall={codexInstaller} onCodexRecheck={cliRecheck} - sessionEnv={cfg.sessionEnv} /> )} {!selAccount && ( diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 704f673..019a880 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -271,6 +271,10 @@ export const en = { copy: 'Copy', copied: 'Copied', }, + cliMissingWsl: { + title: '{name} is missing inside the WSL distro{distro}.', + body: 'The session host is WSL: Windows installers do not apply. Install it inside the distro (for example, in a WSL terminal) and press "Sign in" again.', + }, showInWidget: 'Show in the widget', checkTitle: 'Check', apiKey: 'API key', @@ -292,7 +296,6 @@ export const en = { signIn: 'Sign in', saveAndSignIn: 'Save and sign in', checkAuto: 'It runs on its own as soon as you save and sign in.', - wslHostOnly: 'WSL mode: for now the CLI detection and this login use the Windows CLI. Reading the session inside the distro arrives with #92.', }, accountEditor: { kicker: 'Additional account', diff --git a/src/i18n/es.ts b/src/i18n/es.ts index 2220bb2..16d305c 100644 --- a/src/i18n/es.ts +++ b/src/i18n/es.ts @@ -283,6 +283,10 @@ export const es = { copy: 'Copiar', copied: 'Copiado', }, + cliMissingWsl: { + title: 'Falta {name} dentro de la distro WSL{distro}.', + body: 'El entorno de sesión es WSL: los instaladores de Windows no aplican. Instálalo dentro de la distro (por ejemplo, en una terminal de WSL) y vuelve a pulsar «Iniciar sesión».', + }, // Trozos que comparten los pasos por CLI, el editor de cuentas y los paneles // por proveedor (T2c slice 2 C1, #66). showInWidget: 'Mostrar en el widget', @@ -308,7 +312,6 @@ export const es = { signIn: 'Iniciar sesión', saveAndSignIn: 'Guardar e iniciar sesión', checkAuto: 'Se hace sola en cuanto guardes e inicies sesión.', - wslHostOnly: 'Modo WSL: por ahora la detección del CLI y este login usan el CLI de Windows. Leer la sesión dentro de la distro llega con #92.', }, // Editor de una cuenta adicional (`AccountEditor`). Los nombres de plan con // cifra (`Pro · 300`), las opciones de producto (`nan_community`, `GLM Premium`) diff --git a/src/lib/account-health.test.ts b/src/lib/account-health.test.ts index 1007e0c..73de8e0 100644 --- a/src/lib/account-health.test.ts +++ b/src/lib/account-health.test.ts @@ -62,9 +62,161 @@ describe('isConnectionDirty', () => { expect(isConnectionDirty(undefined, undefined, { ...provider, credentialsPath: 'work.json' }, provider)).toBe(true); expect(isConnectionDirty(undefined, undefined, provider, provider)).toBe(false); }); + + // El entorno es parte de la conexión (revisión PR #92): cambiar de + // Windows a WSL — o de una distro a otra — sin guardar deja la sección + // sucia; el login usa lo GUARDADO, no lo que se ve en pantalla. + it('detects a sessionEnv switch from host to wsl', () => { + expect( + isConnectionDirty( + account, + account, + provider, + provider, + { sessionEnv: 'wsl', wslDistro: 'Ubuntu-22.04' }, + { sessionEnv: 'host', wslDistro: '' }, + ), + ).toBe(true); + }); + + it('detects a distro change inside wsl', () => { + expect( + isConnectionDirty( + account, + account, + provider, + provider, + { sessionEnv: 'wsl', wslDistro: 'Ubuntu-24.04' }, + { sessionEnv: 'wsl', wslDistro: 'Ubuntu-22.04' }, + ), + ).toBe(true); + }); + + it('keeps an unchanged environment clean', () => { + expect( + isConnectionDirty( + account, + account, + provider, + provider, + { sessionEnv: 'wsl', wslDistro: 'Ubuntu-22.04' }, + { sessionEnv: 'wsl', wslDistro: 'Ubuntu-22.04' }, + ), + ).toBe(false); + }); }); describe('createPresencePoller', () => { + it.each(['result', 'rejection'] as const)('ignores a stale %s from an overlapping poll', async (stale) => { + const requests: { resolve: (found: boolean) => void; reject: (error: Error) => void }[] = []; + let tick!: () => void; + const onResult = vi.fn(); + const poller = createPresencePoller({ + exists: () => new Promise((resolve, reject) => requests.push({ resolve, reject })), + onResult, + setInterval: (fn) => { tick = fn; return 7; }, + clearInterval: () => {}, + }); + poller.start(); + tick(); + expect(requests).toHaveLength(2); + requests[1].resolve(true); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult.mock.calls).toEqual([[true]]); + if (stale === 'result') requests[0].resolve(false); + else requests[0].reject(new Error('stale poll failed')); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult.mock.calls).toEqual([[true]]); + poller.stop(); + }); + + it.each(['result', 'rejection'] as const)('notifies a completed %s while a newer poll is pending', async (outcome) => { + const requests: { resolve: (found: boolean) => void; reject: (error: Error) => void }[] = []; + let tick!: () => void; + const onResult = vi.fn(); + const poller = createPresencePoller({ + exists: () => new Promise((resolve, reject) => requests.push({ resolve, reject })), + onResult, + setInterval: (fn) => { tick = fn; return 7; }, + clearInterval: () => {}, + }); + poller.start(); + tick(); + expect(requests).toHaveLength(2); + if (outcome === 'result') requests[0].resolve(false); + else requests[0].reject(new Error('poll failed')); + await Promise.resolve(); + await Promise.resolve(); + const first = outcome === 'result' ? false : null; + expect(onResult.mock.calls).toEqual([[first]]); + requests[1].reject(new Error('latest poll failed')); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult.mock.calls).toEqual([[first], [null]]); + poller.stop(); + }); + + it('does not retain a confirmed session when consecutive slow checks fail', async () => { + const requests: { resolve: (found: boolean) => void; reject: (error: Error) => void }[] = []; + let tick!: () => void; + const onResult = vi.fn(); + const poller = createPresencePoller({ + exists: () => new Promise((resolve, reject) => requests.push({ resolve, reject })), + onResult, + setInterval: (fn) => { tick = fn; return 7; }, + clearInterval: () => {}, + }); + const flush = async () => { await Promise.resolve(); await Promise.resolve(); }; + poller.start(); + requests[0].resolve(true); + await flush(); + tick(); + tick(); + requests[1].reject(new Error('slow check failed')); + await flush(); + tick(); + requests[2].reject(new Error('slow check failed')); + await flush(); + tick(); + requests[3].reject(new Error('slow check failed')); + await flush(); + poller.stop(); + expect(requests).toHaveLength(5); + expect(onResult.mock.calls).toEqual([[true], [null], [null], [null]]); + }); + + it('discards old requests and timers after stop and restart', async () => { + const requests: ((found: boolean) => void)[] = []; + const ticks: (() => void)[] = []; + const cleared: number[] = []; + const exists = vi.fn(() => new Promise((resolve) => requests.push(resolve))); + const onResult = vi.fn(); + const poller = createPresencePoller({ + exists, + onResult, + setInterval: (fn) => { ticks.push(fn); return ticks.length; }, + clearInterval: (handle) => cleared.push(handle), + }); + poller.start(); + poller.stop(); + poller.start(); + expect(cleared).toEqual([1]); + ticks[0](); + expect(exists).toHaveBeenCalledTimes(2); + requests[0](false); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult).not.toHaveBeenCalled(); + requests[1](true); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult.mock.calls).toEqual([[true]]); + poller.stop(); + expect(cleared).toEqual([1, 2]); + }); + it('comprueba al arrancar y notifica el resultado vigente', async () => { const onResult = vi.fn(); const poller = createPresencePoller({ exists: async () => true, onResult, setInterval: () => 0, clearInterval: () => {} }); @@ -76,6 +228,35 @@ describe('createPresencePoller', () => { poller.stop(); }); + it('notifica null cuando el sondeo falla (no conserva el último resultado)', async () => { + const onResult = vi.fn(); + let tick: (() => void) | undefined; + let attempt = 0; + const poller = createPresencePoller({ + exists: async () => { + attempt += 1; + if (attempt === 1) return true; + throw new Error('wsl caído'); + }, + onResult, + setInterval: (fn) => { + tick = fn; + return 7; + }, + clearInterval: () => {}, + }); + poller.start(); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult).toHaveBeenCalledWith(true); + // Segunda comprobación que falla → `null` (desconocido), no `true` viejo. + tick?.(); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult).toHaveBeenCalledWith(null); + poller.stop(); + }); + it('descarta una respuesta en vuelo después de stop (desmontaje)', async () => { let resolve!: (value: boolean) => void; const onResult = vi.fn(); @@ -129,20 +310,34 @@ describe('createPresencePoller', () => { poller.stop(); }); - it('un fallo al comprobar no tumba el sondeo', async () => { + it('un fallo al comprobar no tumba el sondeo ni conserva el resultado viejo', async () => { const onResult = vi.fn(); + let tick: (() => void) | undefined; + let fails = 0; const poller = createPresencePoller({ exists: async () => { - throw new Error('boom'); + // El fallo solo ocurre una vez: el sondeo debe seguir tras él. + fails += 1; + if (fails === 1) throw new Error('boom'); + return true; }, onResult, - setInterval: () => 0, + setInterval: (fn) => { + tick = fn; + return 7; + }, clearInterval: () => {}, }); poller.start(); await Promise.resolve(); await Promise.resolve(); - expect(onResult).not.toHaveBeenCalled(); + // El fallo se notifica como desconocido, no se traga en silencio. + expect(onResult).toHaveBeenCalledWith(null); + // Y el sondeo continúa: el siguiente tick vuelve a comprobar. + tick?.(); + await Promise.resolve(); + await Promise.resolve(); + expect(onResult).toHaveBeenCalledWith(true); poller.stop(); }); }); diff --git a/src/lib/account-health.ts b/src/lib/account-health.ts index aeef582..ca360c2 100644 --- a/src/lib/account-health.ts +++ b/src/lib/account-health.ts @@ -10,15 +10,30 @@ export function effectivePersisted(persisted: boolean, dirty: boolean): boolean } /** Incluye la cuenta y los ajustes heredados del proveedor, sin leer credenciales. */ -export function isConnectionDirty(account: unknown, savedAccount: unknown, provider: unknown, savedProvider: unknown): boolean { - return JSON.stringify(account) !== JSON.stringify(savedAccount) || JSON.stringify(provider) !== JSON.stringify(savedProvider); +export function isConnectionDirty( + account: unknown, + savedAccount: unknown, + provider: unknown, + savedProvider: unknown, + env?: { sessionEnv: unknown; wslDistro: unknown }, + savedEnv?: { sessionEnv: unknown; wslDistro: unknown }, +): boolean { + return ( + JSON.stringify(account) !== JSON.stringify(savedAccount) || + JSON.stringify(provider) !== JSON.stringify(savedProvider) || + // El ENTORNO es parte de la conexión (revisión PR #92): cambiar de + // Windows a WSL, o de una distro a otra, sin guardar haría que el login + // usara el entorno guardado, no el que se ve en pantalla. + env?.sessionEnv !== savedEnv?.sessionEnv || + env?.wslDistro !== savedEnv?.wslDistro + ); } export interface PresencePollerOptions { /** Comprueba la presencia del fichero de sesión (no su validez). */ exists: () => Promise; - /** Recibe cada resultado vigente; los descartados no se notifican. */ - onResult: (found: boolean) => void; + /** Recibe cada resultado vigente; `null` indica fallo de sondeo. */ + onResult: (found: boolean | null) => void; /** Intervalo entre sondeos, en ms. Por defecto 3000. */ intervalMs?: number; /** Temporizador inyectable para las pruebas (por defecto `setInterval`). */ @@ -37,22 +52,32 @@ export interface PresencePoller { /** * Sondea la presencia del fichero de sesión mientras la cuenta está abierta. * Una respuesta que llega después de `stop()` (p. ej. al desmontar o al cambiar - * de cuenta) no se notifica: evita marcar como conectada una cuenta equivocada. + * de cuenta), o de un sondeo anterior a otro resultado ya notificado, no se + * notifica: evita estados obsoletos o marcar como conectada una cuenta equivocada. */ export function createPresencePoller(options: PresencePollerOptions): PresencePoller { let generation = 0; + let latestRequest = 0; + let latestDelivered = 0; let running = false; let handle: number | undefined; const timer = options.setInterval ?? ((fn: () => void, ms: number) => globalThis.setInterval(fn, ms)); const clear = options.clearInterval ?? ((h: number) => globalThis.clearInterval(h)); const check = (gen: number) => { if (!running || gen !== generation) return; + const request = ++latestRequest; + const publish = (found: boolean | null) => { + if (running && gen === generation && request >= latestDelivered) { + latestDelivered = request; + options.onResult(found); + } + }; options .exists() - .then((found) => { - if (running && gen === generation) options.onResult(found); - }) - .catch(() => {}); + .then(publish) + // Un fallo de sondeo no puede dejar la última respuesta como verdad: + // se notifica `null` (revisión PR #92) y la UI muestra estado desconocido. + .catch(() => publish(null)); }; return { start() { diff --git a/src/lib/accounts.ts b/src/lib/accounts.ts index 6ae4303..0291dea 100644 --- a/src/lib/accounts.ts +++ b/src/lib/accounts.ts @@ -29,6 +29,7 @@ export const CLI_INSTALL: Partial invoke('account_session', { id }), - /** CLIs de login instalados: `{ claude, codex, gemini }` */ - cliStatus: () => invoke>('cli_status'), + /** + * CLIs de login por proveedor: `{ claude, codex, gemini, grok }`. Cada valor + * es `ready | missing | stopped | error` (#92): solo `missing` significa + * «instalar la CLI»; `stopped` (distro detenida) y `error` (WSL roto) no se + * arreglan instalando nada. `env` es el borrador visible en Ajustes + * (revisión PR #92, punto 10): si se pasa, la detección consulta ese + * entorno y no la config persistida. + */ + cliStatus: (env?: { sessionEnv: 'host' | 'wsl'; wslDistro: string }) => + invoke>('cli_status', { + // `null` explícito: el comando declara `Option` y sin override + // detecta el entorno persistido (widget y llamadas antiguas). + sessionEnv: env?.sessionEnv ?? null, + wslDistro: env?.wslDistro ?? null, + }), /** * Estado pasivo de la instalación asistida de Codex CLI. Solo lee: nunca * ejecuta procesos, red ni escrituras. Comando `codex_setup_status`.