diff --git a/docs/i18n-inventory.md b/docs/i18n-inventory.md index 145e8d63..4f40566e 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/` = `07e55c6cc614d6914d4f11a998643fdebaf0ccdb` and `src-tauri/src/` = `b521502e120af9343ae15942001605911809f9a2`. +Generated by `node scripts/i18n-inventory.mjs` from the source trees `src/` = `068eb8cb674c4f98515e3eddd63caa858b2d6e80` 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`. diff --git a/src/Widget.tsx b/src/Widget.tsx index f7f0cfbf..3a6696f8 100644 --- a/src/Widget.tsx +++ b/src/Widget.tsx @@ -13,9 +13,10 @@ import { contains, isEdge, isVertical, nearestEdge, panelHeightLimit, stripRect, import { ORB_SIZE, type AppConfig, type UsageReport } from './lib/types'; import { checkForUpdate, emitUpdateAvailable, installUpdate, shouldNotifyUpdate, startUpdatePolling, updateErrorText, type UpdatePhase } from './lib/updater'; import { useUpdaterMode } from './lib/useUpdater'; -import { retryWithBackoff, STARTUP_RETRY, USAGE_RETRY } from './lib/startup'; +import { retryWithBackoff, USAGE_RETRY } from './lib/startup'; import { createSessionMonitor } from './lib/session-monitor'; import { envKey, needsRefresh } from './lib/widget-refresh'; +import { useWidgetStartup } from './lib/use-widget-startup'; import { createWidgetRecovery, shouldAuditNativePosition } from './lib/widget-recovery'; import { placementOutcome, readPlacementWithRetries, reasonKey, samePlacement, type WidgetPlacementReason, type WidgetPlacementReport } from './lib/widget-placement'; import { @@ -44,6 +45,7 @@ import { detectWindowManager } from './lib/wm-detect'; import { t } from './i18n'; import { localeFrom } from './i18n/use-locale'; import { StripFallback } from './components/StripFallback'; +import { StripTools } from './components/StripTools'; const CLOSE_DELAY = 280; /** @@ -167,7 +169,43 @@ const liveRatio = (fallback: number) => { }; export function Widget() { - const [config, setConfig] = useState(null); + // Callbacks ESTABLES para `useWidgetStartup` (revisión PR #271): si se + // pasaran inline, `onReadyToShow`/`onConfigChange` cambiarían de identidad en + // cada render y `useWidgetStartup` re-ejecutaría sus efectos — reiniciando la + // red de seguridad de 2,5 s y el retry de `getConfig` en cada re-render + // (justo lo que hace falta evitar en un arranque lento). + const showStripIfVisible = useCallback(() => { + // La visibilidad es del usuario (#179): una tira oculta desde la bandeja + // no se vuelve a mostrar por nuestra cuenta, ni siquiera por la red de + // seguridad. `shown`/`hiddenByUser` son refs estables: sin closure stale. + if (!shown.current && !hiddenByUser.current) { + shown.current = true; + getCurrentWindow().show().catch(() => {}); + } + }, []); + const clearReportsOnEnvChange = useCallback((c: AppConfig) => { + // La limpieza de informes al cambiar de entorno es de Widget (#248); el + // hook aplica la config y avisa aquí (también para `config-changed`). + // El ref se actualiza de forma SINCRONA (revisión PR #271): `retryStartup` + // y `patchConfig` hacen `applyConfig(...)` y luego leen `configRef` en el + // mismo turno (`refresh`, alertas, locale); un efecto posterior al render + // llegaría tarde. + const prev = configRef.current; + configRef.current = c; + if (prev && envKey(prev) !== envKey(c)) { + reportsRef.current = []; + setReports([]); + } + }, []); + + // Arranque de la configuración (#271): config pendiente → estado neutro; + // reintentos agotados → fallo definitivo; red de seguridad de 2,5 s para + // `show()` (el hook es puro; `Widget` decide la visibilidad real). + const { config, configFailed, configError, applyConfig } = useWidgetStartup({ + onReadyToShow: showStripIfVisible, + onConfigChange: clearReportsOnEnvChange, + }); + const [reports, setReports] = useState([]); const [loading, setLoading] = useState(false); const [updatedAt, setUpdatedAt] = useState(null); @@ -218,6 +256,10 @@ export function Widget() { const detailInsideRef = useRef(false); const insideRef = useRef(false); const configRef = useRef(null); + /** Última config que el efecto `[config, refresh]` ya procesó: `configRef` + * se sobrescribe de forma síncrona en cada `applyConfig`, así que aquí se + * guarda el valor anterior para decidir si hay que volver a pedir datos. */ + const appliedConfigRef = useRef(null); const reportsRef = useRef([]); const geoRef = useRef(null); const inFlight = useRef(false); @@ -345,21 +387,10 @@ export function Widget() { } }, [runAlerts]); - const applyConfig = useCallback((c: AppConfig) => { - const prev = configRef.current; - // Cambio de entorno (host ↔ WSL, o de distro): los informes actuales son - // del otro entorno y no valen (revisión PR #248). Se vacían para que no se - // muestren datos del host como si fueran de la distro (y al revés). - if (prev && envKey(prev) !== envKey(c)) { - reportsRef.current = []; - setReports([]); - } - configRef.current = c; - setConfig(c); - }, []); - const patchConfig = useCallback( async (patch: WidgetPatch) => { + // El hook aplica la config (y avisa vía `onConfigChange` para la + // limpieza de informes por cambio de entorno, #248). applyConfig(await api.patchConfig(patch)); }, [applyConfig], @@ -380,25 +411,12 @@ export function Widget() { }, [applyConfig, refresh]); useEffect(() => { - // La ventana puede montar antes de que el backend registre su estado: sin - // reintento la config no llega y la tira queda vacía o en una posición - // arbitraria hasta un refresco manual. Cancelable al desmontar. - const controller = new AbortController(); - retryWithBackoff(() => api.getConfig(), { ...STARTUP_RETRY, signal: controller.signal }) - .then((c) => { - if (!controller.signal.aborted) applyConfig(c); - }) - .catch((e) => { - if (!controller.signal.aborted) setError(String(e)); - }); + // El retry del primer `getConfig` y el listener `config-changed` viven en + // `useWidgetStartup` (#271). Aquí quedan los eventos de la ventana. + // `config-changed` vuelve a leer la config (el hook aplica el nuevo + // `config`); este efecto detecta ese cambio y refresca solo si cambió + // algo que obliga a pedir datos (mover la tira o cambiar colores no). const unlisten = [ - listen('config-changed', async () => { - const prev = configRef.current; - const next = await api.getConfig(); - applyConfig(next); - // Mover la tira o cambiar colores no debe disparar peticiones a los proveedores. - if (needsRefresh(prev, next)) refresh(); - }), listen('refresh-now', () => refresh()), listen('open-peak', () => openPeakRef.current()), // La visibilidad de la tira es del usuario (#179): cuando la oculta @@ -414,10 +432,22 @@ export function Widget() { }), ]; return () => { - controller.abort(); unlisten.forEach((p) => p.then((f) => f())); }; - }, [refresh, applyConfig]); + }, [refresh]); + + // `config-changed` altera `config` (vía el hook): `configRef` ya se mantiene + // al día de forma SINCRONA en `clearReportsOnEnvChange` (leído por + // `refresh`/`runAlerts` justo después de un `applyConfig`). Este efecto solo + // refresca si la config nueva obliga a pedir datos (revisión PR #271: el + // cambio de idioma no dispara una lectura de proveedores, pero sí + // re-renderiza la UI). `appliedConfigRef` guarda el último valor que este + // efecto ya procesó (configRef ya está sobrescrito al llegar aquí). + useEffect(() => { + const prev = appliedConfigRef.current; + appliedConfigRef.current = config; + if (prev && config && needsRefresh(prev, config)) refresh(); + }, [config, refresh]); // Al desmontar, corta cualquier reintento de uso pendiente (sin setState tardío). useEffect(() => () => refreshAbort.current?.abort(), []); @@ -526,6 +556,10 @@ export function Widget() { const autoHide = config?.autoHide ?? false; const showHandle = autoHide || phase !== 'open'; + // Idioma seguro para controles accesibles (#271): `pending` (config pendiente + // y sin fallo definitivo) no monta botones sin nombre. El peek y las tools + // solo se montan con config válida o fallo definitivo (locale `es`). + const configKnown = config != null || configFailed; useEffect(() => { if (!autoHide) { setCollapsed(false); @@ -1063,19 +1097,10 @@ export function Widget() { }; }, []); - // Red de seguridad: si algo falla al medir/colocar, mostramos igualmente la ventana. - useEffect(() => { - const t = window.setTimeout(() => { - // La visibilidad es del usuario (#179): una tira oculta desde la bandeja - // no se vuelve a mostrar por nuestra cuenta, ni siquiera por la red de - // seguridad. - if (!shown.current && !hiddenByUser.current) { - shown.current = true; - getCurrentWindow().show().catch(() => {}); - } - }, 2500); - return () => window.clearTimeout(t); - }, []); + // La red de seguridad (mostrar la ventana a los 2,5 s si sigue pendiente) + // vive en `useWidgetStartup` (#271): el hook llama `onReadyToShow` y aquí se + // respeta la visibilidad del usuario (#179). La colocación normal también + // muestra la ventana (ver el efecto de colocación), sin depender de esto. // ───── arrastrar la tira y soltar con imán al borde más cercano ───── const enqueueDrag = (job: () => Promise) => { @@ -1308,7 +1333,7 @@ export function Widget() { scheduleClose(); }} > - {showHandle && - )} - - - + {/* Las herramientas solo se montan con idioma seguro: mientras la config + está pendiente no hay botones sin nombre accesible (#271, precisión + 2). En el fallo definitivo se montan con el locale por defecto. */} + {configKnown && ( + api.openSettings()} + onStartUpdate={startUpdate} + icons={{ update: Icon.update, refresh: Icon.refresh, gear: Icon.gear }} + /> + )} diff --git a/src/components/StripFallback.test.tsx b/src/components/StripFallback.test.tsx index 0f5644ff..fc1cfc64 100644 --- a/src/components/StripFallback.test.tsx +++ b/src/components/StripFallback.test.tsx @@ -7,23 +7,23 @@ import { StripFallback } from './StripFallback'; const props = (locale: 'es' | 'en') => ({ locale, + state: 'ready' as const, error: null as string | null, busy: false, - ready: true, onRetry: () => {}, onConfigure: () => {}, }); describe('StripFallback i18n (SSR)', () => { it('renders the Spanish fallbacks verbatim for es', () => { - expect(renderToStaticMarkup(), 'error → Reintentar').toContain('Reintentar'); + expect(renderToStaticMarkup(), 'failed → Reintentar').toContain('Reintentar'); expect(renderToStaticMarkup(), 'busy → Cargando…').toContain('Cargando…'); expect(renderToStaticMarkup(), 'ready → Configurar').toContain('Configurar'); - expect(renderToStaticMarkup()).not.toContain('Retry'); + expect(renderToStaticMarkup()).not.toContain('Retry'); }); it('renders the English fallbacks when the locale is en', () => { - expect(renderToStaticMarkup(), 'error → Retry').toContain('Retry'); + expect(renderToStaticMarkup(), 'failed → Retry').toContain('Retry'); expect(renderToStaticMarkup(), 'busy → Loading…').toContain('Loading…'); expect(renderToStaticMarkup(), 'ready → Configure').toContain('Configure'); expect(renderToStaticMarkup()).not.toContain('Cargando'); @@ -31,8 +31,50 @@ describe('StripFallback i18n (SSR)', () => { it('shows the retry title with the raw error text in both locales', () => { for (const locale of ['es', 'en'] as const) { - const html = renderToStaticMarkup(); + const html = renderToStaticMarkup(); expect(html).toContain('title="sin red"'); } }); + + // Precisión 1 (#271): mientras la config está pendiente, el neutro gana + // incluso si hay un error ajeno (refresco/arrastre); solo `failed` muestra + // el fallback explícito. + it('pending is neutral: no localized text, even with an unrelated error', () => { + for (const locale of ['es', 'en'] as const) { + const html = renderToStaticMarkup(); + expect(html, `pending neutral: ${locale}`).not.toContain('Cargando'); + expect(html, `pending neutral: ${locale}`).not.toContain('Loading'); + expect(html, `pending neutral: ${locale}`).not.toContain('Reintentar'); + expect(html, `pending neutral: ${locale}`).not.toContain('Retry'); + expect(html, `pending neutral: ${locale}`).not.toContain('Configurar'); + expect(html, `pending neutral: ${locale}`).not.toContain('Configure'); + expect(html).toContain('strip__pending'); + } + }); + + it('failed is explicit even with an unrelated busy state', () => { + const html = renderToStaticMarkup(); + expect(html).toContain('Retry'); + expect(html).toContain('title="config unreachable"'); + }); + + // Revisión PR #271 (defecto 1): con la config ya cargada (`ready`), un error + // de uso (refresco, arrastre…) sin orbes visibles se muestra con «Reintentar» + // y el error como tooltip; no se cae a «Configurar». + it('ready with a usage error shows Retry with the error, not Configure', () => { + for (const locale of ['es', 'en'] as const) { + const html = renderToStaticMarkup(); + expect(html, `ready+error es: ${locale}`).toContain(locale === 'es' ? 'Reintentar' : 'Retry'); + expect(html, `ready+error title: ${locale}`).toContain('title="refresh blew up"'); + expect(html, `ready+error no configurar: ${locale}`).not.toContain(locale === 'es' ? 'Configurar' : 'Configure'); + } + }); + + // Revisión PR #271 (menor): el fallo definitivo sin tooltip crudo sigue + // ofreciendo «Reintentar» (el error de un reintento manual llega por `error`). + it('failed without a raw error still offers Retry', () => { + const html = renderToStaticMarkup(); + expect(html).toContain('Retry'); + expect(html).not.toContain('title='); + }); }); diff --git a/src/components/StripFallback.tsx b/src/components/StripFallback.tsx index 2d5ad256..8e2efc7b 100644 --- a/src/components/StripFallback.tsx +++ b/src/components/StripFallback.tsx @@ -1,25 +1,60 @@ // Fallback de la tira cuando no hay orbs visibles (T2c slice 1, #66): -// error de arranque, carga o primera ejecución sin configurar. Extraído de -// Widget.tsx como componente puro con `locale` para probarlo en servidor. +// carga de la configuración pendiente, fallo definitivo de configuración o +// primera ejecución sin configurar. Extraído de Widget.tsx como componente +// puro con `locale` para probarlo en servidor. +// +// Estado explícito del ARRANQUE de la configuración (revisión PR #271): el +// `error` genérico de `Widget` (fallos de refresco, arrastre…) NO decide el +// fallback. `state` distingue: +// - `pending`: la config aún no llegó y no hay fallo definitivo → estado +// NEUTRO sin textos localizados (nadie ve «Cargando…» en el idioma +// equivocado antes de conocer el idioma guardado). +// - `failed`: los reintentos de `getConfig` se agotaron → fallback explícito +// (`widget.retry`) con el locale por defecto; `error` es el texto crudo del +// fallo de config, no un error ajeno. +// - `ready`: la config está disponible → «Cargando…» en el idioma correcto +// mientras `busy`, o «Configurar» cuando no hay orbs. import { t } from '../i18n'; import type { Locale } from '../lib/types'; -export function StripFallback({ error, busy, ready, locale, onRetry, onConfigure }: { +export type StripFallbackState = 'pending' | 'ready' | 'failed'; + +export function StripFallback({ state, error, busy, locale, onRetry, onConfigure }: { + /** Estado del arranque de la configuración (#271). */ + state: StripFallbackState; + /** Último error visible: el de config en `failed`, o un error de uso + * (refresco/arrastre) en `ready`. En `pending` se ignora (neutro). */ error: string | null; + /** Refresco en curso (solo `ready`: la config ya está, el idioma es seguro). */ busy: boolean; - ready: boolean; locale: Locale; onRetry: () => void; onConfigure: () => void; }) { + if (state === 'pending') { + // Neutro y sin texto: hasta que llegue la config no sabemos el idioma + // guardado, así que la primera muestra no puede emitir cadenas localizadas. + return