Skip to content
Merged
2 changes: 1 addition & 1 deletion docs/i18n-inventory.md
Original file line number Diff line number Diff line change
@@ -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 <commit>:src` and `<commit>:src-tauri/src` match has these exact texts.
Do not edit by hand: regenerate, or verify with `node scripts/i18n-inventory.mjs --check`.

Expand Down
176 changes: 102 additions & 74 deletions src/Widget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
/**
Expand Down Expand Up @@ -167,7 +169,43 @@ const liveRatio = (fallback: number) => {
};

export function Widget() {
const [config, setConfig] = useState<AppConfig | null>(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<UsageReport[]>([]);
const [loading, setLoading] = useState(false);
const [updatedAt, setUpdatedAt] = useState<Date | null>(null);
Expand Down Expand Up @@ -218,6 +256,10 @@ export function Widget() {
const detailInsideRef = useRef(false);
const insideRef = useRef(false);
const configRef = useRef<AppConfig | null>(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<AppConfig | null>(null);
const reportsRef = useRef<UsageReport[]>([]);
const geoRef = useRef<Geo | null>(null);
const inFlight = useRef(false);
Expand Down Expand Up @@ -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],
Expand All @@ -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
Expand All @@ -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(), []);
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<void>) => {
Expand Down Expand Up @@ -1308,7 +1333,7 @@ export function Widget() {
scheduleClose();
}}
>
{showHandle && <button
{showHandle && configKnown && <button
ref={peekRef}
type="button"
className="peek"
Expand Down Expand Up @@ -1343,7 +1368,7 @@ export function Widget() {
>
<span
className="strip__grip"
title={t(locale, 'widget.dragHint')}
title={configKnown ? t(locale, 'widget.dragHint') : undefined}
onPointerDown={onGripDown}
onPointerMove={onGripMove}
onPointerUp={onGripUp}
Expand Down Expand Up @@ -1374,33 +1399,36 @@ export function Widget() {
/>
))}
{visible.length === 0 && (
<StripFallback error={error} busy={loading} ready={config != null} locale={locale} onRetry={retryStartup} onConfigure={() => api.openSettings()} />
<StripFallback
state={configFailed ? 'failed' : config != null ? 'ready' : 'pending'}
// En `ready` el error genérico de uso (refresco/arrastre) se
// muestra, no se oculta; en `failed` el error de un reintento
// manual (`setError`) tiene prioridad sobre el error de config
// viejo (revisión PR #271).
error={configFailed ? (error ?? configError) : error}
busy={loading}
locale={locale}
onRetry={retryStartup}
onConfigure={() => api.openSettings()}
/>
)}
</div>

<div className="strip__tools">
{updaterMode === 'native' && (update.phase === 'available' || update.phase === 'installing') && (
<button
className="icon-btn icon-btn--update"
data-spin={update.phase === 'installing' || undefined}
onClick={startUpdate}
disabled={update.phase === 'installing'}
title={
update.phase === 'installing'
? t(locale, 'widget.updatingTo', { version: update.info.version, detail: update.progress != null ? ` · ${update.progress} %` : '…' })
: t(locale, 'widget.updateTo', { version: update.info.version })
}
>
{Icon.update}
</button>
)}
<button className="icon-btn" data-spin={loading || undefined} onClick={refresh} title={t(locale, 'widget.refreshNow')}>
{Icon.refresh}
</button>
<button className="icon-btn" onClick={() => api.openSettings()} title={t(locale, 'widget.settings')}>
{Icon.gear}
</button>
</div>
{/* 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 && (
<StripTools
locale={locale}
loading={loading}
updaterMode={updaterMode}
update={update}
onRefresh={refresh}
onOpenSettings={() => api.openSettings()}
onStartUpdate={startUpdate}
icons={{ update: Icon.update, refresh: Icon.refresh, gear: Icon.gear }}
/>
)}
</div>

</div>
Expand Down
52 changes: 47 additions & 5 deletions src/components/StripFallback.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,32 +7,74 @@ 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(<StripFallback {...props('es')} error="sin red" />), 'error → Reintentar').toContain('Reintentar');
expect(renderToStaticMarkup(<StripFallback {...props('es')} state="failed" error="sin red" />), 'failed → Reintentar').toContain('Reintentar');
expect(renderToStaticMarkup(<StripFallback {...props('es')} busy />), 'busy → Cargando…').toContain('Cargando…');
expect(renderToStaticMarkup(<StripFallback {...props('es')} />), 'ready → Configurar').toContain('Configurar');
expect(renderToStaticMarkup(<StripFallback {...props('es')} error="sin red" />)).not.toContain('Retry');
expect(renderToStaticMarkup(<StripFallback {...props('es')} state="failed" error="sin red" />)).not.toContain('Retry');
});

it('renders the English fallbacks when the locale is en', () => {
expect(renderToStaticMarkup(<StripFallback {...props('en')} error="no network" />), 'error → Retry').toContain('Retry');
expect(renderToStaticMarkup(<StripFallback {...props('en')} state="failed" error="no network" />), 'failed → Retry').toContain('Retry');
expect(renderToStaticMarkup(<StripFallback {...props('en')} busy />), 'busy → Loading…').toContain('Loading…');
expect(renderToStaticMarkup(<StripFallback {...props('en')} />), 'ready → Configure').toContain('Configure');
expect(renderToStaticMarkup(<StripFallback {...props('en')} busy />)).not.toContain('Cargando');
});

it('shows the retry title with the raw error text in both locales', () => {
for (const locale of ['es', 'en'] as const) {
const html = renderToStaticMarkup(<StripFallback {...props(locale)} error="sin red" />);
const html = renderToStaticMarkup(<StripFallback {...props(locale)} state="failed" error="sin red" />);
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(<StripFallback {...props(locale)} state="pending" error="boom" />);
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(<StripFallback {...props('en')} state="failed" error="config unreachable" busy />);
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(<StripFallback {...props(locale)} state="ready" error="refresh blew up" />);
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(<StripFallback {...props('en')} state="failed" />);
expect(html).toContain('Retry');
expect(html).not.toContain('title=');
});
});
Loading
Loading