From 6b050299e2c069ea32050bb61ea84580704f368f Mon Sep 17 00:00:00 2001 From: jose luis <2064537+sosan@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:53:25 +0100 Subject: [PATCH 1/7] =?UTF-8?q?fix(widget):=20primera=20muestra=20con=20id?= =?UTF-8?q?ioma=20seguro=20mientras=20la=20config=20est=C3=A1=20pendiente?= =?UTF-8?q?=20(#271)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Si `getConfig()` tarda más de 2,5 s al arrancar, la red de seguridad mostraba la tira con `config == null` y `localeFrom(null) === 'es'`: «Cargando…» y los tooltips (Ajustes, Actualizar ahora, arrastrar) salían en español aunque el usuario tuviera otro idioma guardado. La primera interfaz visible ahora usa un estado neutro sin texto localizado hasta que llega la config. - `useWidgetStartup` (nuevo): cableado del arranque de la configuración — retry de `getConfig` con `configFailed`/`configError` (solo se marca el fallo definitivo al agotar los reintentos; un error de refresco/arrastre no desactiva el neutro), listener `config-changed`, y la red de seguridad de 2,5 s como `onReadyToShow` inyectable (el hook no conoce Tauri). Los efectos se registran una sola vez: los callbacks `onReadyToShow`/`onConfigChange` se estabilizan con `useCallback` para que un re-render no reinicie el temporizador ni el retry (justo el arranque lento que este fix protege). - `StripFallback`: estado explícito `pending | ready | failed`. `pending` renderiza un spinner sin texto y gana sobre cualquier error ajeno; `failed` muestra «Reintentar» con el locale por defecto (el error de config en el title); `ready` mantiene «Cargando…»/«Configurar» en el idioma correcto. - `StripTools` (nuevo): herramientas extraídas de `Widget`; solo se montan cuando el idioma es seguro (`configReady` o fallo definitivo), así ningún botón activo queda sin nombre accesible. - `Widget`: usa el hook; `StripFallback`/`StripTools` reciben el estado derivado; títulos del asa y del peek solo con config; `applyConfig` del hook despeja `configFailed` cuando llega una config válida. Tests: SSR de `StripFallback` (pending neutro con error ajeno, failed explícito) y `StripTools` (tooltips por locale, botón de update, integridad de la extracción); cableado de `useWidgetStartup` con fake timers (config pendiente + red de seguridad, resolución a `en`, `configFailed`, fallo de `config-changed` que no marca fallo definitivo, limpieza en `applyConfig`, colocación normal antes del temporizador). `auto-hide.test.ts` actualizado al nuevo orden de hooks (índices de estado) y a la red de seguridad en el hook. --- src/Widget.tsx | 156 ++++++++++---------- src/components/StripFallback.test.tsx | 32 ++++- src/components/StripFallback.tsx | 39 +++-- src/components/StripTools.test.tsx | 67 +++++++++ src/components/StripTools.tsx | 50 +++++++ src/lib/auto-hide.test.ts | 94 ++++++------ src/lib/use-widget-startup.test.ts | 198 ++++++++++++++++++++++++++ src/lib/use-widget-startup.ts | 103 ++++++++++++++ src/styles.css | 14 ++ 9 files changed, 619 insertions(+), 134 deletions(-) create mode 100644 src/components/StripTools.test.tsx create mode 100644 src/components/StripTools.tsx create mode 100644 src/lib/use-widget-startup.test.ts create mode 100644 src/lib/use-widget-startup.ts diff --git a/src/Widget.tsx b/src/Widget.tsx index f7f0cfbf..e9110f4e 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,38 @@ 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`). + const prev = configRef.current; + 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); @@ -345,21 +378,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 +402,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 +423,19 @@ export function Widget() { }), ]; return () => { - controller.abort(); unlisten.forEach((p) => p.then((f) => f())); }; - }, [refresh, applyConfig]); + }, [refresh]); + + // `config-changed` altera `config` (vía el hook): mantener `configRef` al + // día (lo leen `refresh`/`runAlerts`) y refrescar solo 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). + useEffect(() => { + const prev = configRef.current; + configRef.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(), []); @@ -1063,19 +1081,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) => { @@ -1312,7 +1321,7 @@ export function Widget() { ref={peekRef} type="button" className="peek" - aria-label={placementFailed ? `${t(locale, 'widget.retryShow')}${placementReasonText ? `: ${placementReasonText}` : ''}` : t(locale, 'widget.show')} + aria-label={config != null ? (placementFailed ? `${t(locale, 'widget.retryShow')}${placementReasonText ? `: ${placementReasonText}` : ''}` : t(locale, 'widget.show')) : undefined} title={placementFailed ? placementReasonText ?? undefined : undefined} aria-controls="quorb-strip" aria-hidden={phase === 'open' && !peekFocused || undefined} @@ -1343,7 +1352,7 @@ export function Widget() { > ))} {visible.length === 0 && ( - api.openSettings()} /> + api.openSettings()} + /> )} -
- {updaterMode === 'native' && (update.phase === 'available' || update.phase === 'installing') && ( - - )} - - -
+ {/* 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. */} + {(config != null || configFailed) && ( + 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..878eb97e 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,30 @@ 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"'); + }); }); diff --git a/src/components/StripFallback.tsx b/src/components/StripFallback.tsx index 2d5ad256..bf51de4a 100644 --- a/src/components/StripFallback.tsx +++ b/src/components/StripFallback.tsx @@ -1,25 +1,48 @@ // 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; + /** Texto crudo del fallo definitivo de config (solo se usa en `failed`). */ 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 (error) { + 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