From d602aa812257e3a1d7ac3a1e00e28b29beade670 Mon Sep 17 00:00:00 2001 From: Alfredo Pinto Date: Tue, 1 Dec 2026 00:34:58 -0800 Subject: [PATCH] Deck en la red: avisa cuando el PC se apaga y vuelve solo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El servidor manda un latido cada 3 s y, antes de irse, el motivo (suspensión, apagado, cierre de sesión, FocusWShell cerrado o deck apagado). La página tapa el deck con una pantalla que lo dice, nota en segundos un corte sin aviso, y reintenta sin recargarse hasta que el PC vuelve. --- docs/adr/0021-deck-por-la-red.md | 5 + site/deck-network.md | 8 ++ site/es/deck-red.md | 8 ++ src/FocusWShell.App/App.xaml.cs | 12 ++- src/FocusWShell.App/DeckWeb/DeckWebServer.cs | 104 ++++++++++++++++++- src/FocusWShell.App/DeckWeb/deck.css | 9 ++ src/FocusWShell.App/DeckWeb/deck.js | 99 ++++++++++++++++-- src/FocusWShell.App/DeckWeb/index.html | 1 + 8 files changed, 233 insertions(+), 13 deletions(-) diff --git a/docs/adr/0021-deck-por-la-red.md b/docs/adr/0021-deck-por-la-red.md index ec390d4..35465f9 100644 --- a/docs/adr/0021-deck-por-la-red.md +++ b/docs/adr/0021-deck-por-la-red.md @@ -143,4 +143,9 @@ Hallazgo del Firewall: la primera vez que FocusWShell escucha, Windows pregunta Con el PC bloqueado (2026-11-28), el servidor sólo manda `{"type":"locked"}` (sin apps, foco ni páginas) y rechaza los comandos; la página lo tapa todo y olvida el estado. Lo detecta con `SystemEvents.SessionSwitch`, como Actividad. La tablet no puede bloquear su propia pantalla ni desbloquear el PC. +Cuando el PC se va (2026-12-01), la página lo sabe y lo muestra, sin recargarse nunca (con el PC apagado, recargar deja la página de error del navegador y nada reintenta; guardarla para abrir sin conexión exige un service worker, que sólo funciona con HTTPS, la opción C): +- **Latido:** si pasan 3 s sin mandar nada, el servidor manda `{"type":"ping"}`. La página da la conexión por muerta tras 8 s sin mensajes; así nota en segundos un apagado de golpe o una red caída, que el navegador puede tardar minutos en ver. +- **Despedida:** antes de cerrar, el servidor manda `{"type":"bye","reason":…}`: `sleep` (`PowerModeChanged`), `shutdown` y `logoff` (`SessionEnding` de la app), `closed` (al salir) y `off` (al apagar el deck en la red). Espera como mucho 1 s. Mientras el PC se va, rechaza conexiones nuevas (503) hasta despertar, o 2 minutos si el apagado se canceló. +- **Página:** una pantalla negra con el motivo, desde cuándo y **Reintentar ahora** (48 pt) tapa el deck; un corte sin aviso se muestra sólo si dura más de 2,5 s. Reintenta con espera creciente hasta 8 s el primer minuto y luego cada 30 s, sin rendirse, y de inmediato con `visibilitychange`, `online` y `pageshow` (con la pantalla apagada el navegador frena los temporizadores). Al llegar el estado, se quita sola. + Sigue pendiente el cifrado (opción C): sin él, quien comparta la red puede ver el tráfico, incluido el token. diff --git a/site/deck-network.md b/site/deck-network.md index 87fc525..138cb16 100644 --- a/site/deck-network.md +++ b/site/deck-network.md @@ -48,6 +48,14 @@ The power buttons (lock, sleep, restart, shut down) are not on the network: use For now the page can't keep the tablet's screen on (browsers only allow it over an encrypted connection). Raise the screen timeout in the tablet's settings. +## When the PC turns off or sleeps + +If the PC sleeps, shuts down, restarts, you sign out, or FocusWShell is closed, the tablet shows a black screen that says why. If the PC disappears without warning (the power went out, the Wi-Fi dropped), it notices within a few seconds and says **No connection to the PC**. Either way, it hides the deck so you don't tap buttons that would get nowhere. + +Leave the page open: it keeps trying by itself, and when the PC is back (after turning it on, you have to sign in to Windows), the deck comes back on its own. When you wake the tablet or come back to the page, it tries right away; **Retry now** does the same. + +Don't reload the page while the PC is off: the browser would show its own error page, and that page doesn't retry. If the browser closed the page, open the deck's address again once the PC is on: the tablet stays paired. + ## If the tablet doesn't connect - **Is the network private?** The section **Deck on the network** says so if Windows marks it as public. diff --git a/site/es/deck-red.md b/site/es/deck-red.md index 36c5a62..4f15153 100644 --- a/site/es/deck-red.md +++ b/site/es/deck-red.md @@ -48,6 +48,14 @@ No están en la red los botones de energía (bloquear, suspender, reiniciar, apa Por ahora la página no puede mantener encendida la pantalla de la tablet (los navegadores sólo lo permiten con una conexión cifrada). Sube el tiempo de pantalla en los ajustes de la tablet. +## Cuando el PC se apaga o se suspende + +Si el PC se suspende, se apaga, se reinicia, cierras la sesión o se cierra FocusWShell, la tablet muestra una pantalla negra que dice por qué. Si el PC desaparece sin avisar (se fue la luz, se cayó el wifi), lo nota en unos segundos y dice **Sin conexión con el PC**. En los dos casos tapa el deck, para que no toques botones que no llegarían. + +Deja la página abierta: sigue intentando sola, y cuando el PC vuelve (al encenderlo hay que iniciar sesión en Windows), el deck regresa solo. Al despertar la tablet o volver a la página, lo intenta de inmediato; **Reintentar ahora** hace lo mismo. + +No recargues la página con el PC apagado: el navegador mostraría su propia página de error, y esa no reintenta. Si el navegador cerró la página, abre otra vez la dirección del deck cuando el PC esté encendido: la tablet sigue emparejada. + ## Si la tablet no conecta - **¿La red es privada?** La sección **Deck en la red** lo dice si Windows la marca como pública. diff --git a/src/FocusWShell.App/App.xaml.cs b/src/FocusWShell.App/App.xaml.cs index ad93957..ced97f8 100644 --- a/src/FocusWShell.App/App.xaml.cs +++ b/src/FocusWShell.App/App.xaml.cs @@ -1037,7 +1037,11 @@ private void FreezeSession() } /// Apagar, reiniciar o cerrar sesión desde Windows (no desde el deck). - private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e) => FreezeSession(); + private void OnSessionEnding(object sender, SessionEndingCancelEventArgs e) + { + FreezeSession(); + _deckWeb?.Bye(e.ReasonSessionEnding == ReasonSessionEnding.Logoff ? "logoff" : "shutdown"); // la tablet sabe por qué + } /// La actividad (ADR 0019): se mide sólo si está prendida; se guardan los días que diga la configuración. private void StartActivity() @@ -1086,6 +1090,11 @@ internal async Task SetDeckWeb(bool enabled) _settings.Save(); if (_deckWeb is not null) { + if (!enabled) + { + _deckWeb.Bye("off"); // la tablet muestra que el deck en la red se apagó + } + await _deckWeb.DisposeAsync(); _deckWeb = null; } @@ -1294,6 +1303,7 @@ private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledEx protected override void OnExit(ExitEventArgs e) { + _deckWeb?.Bye("closed"); // antes de irse, la tablet sabe que FocusWShell se cerró _exitWait?.Unregister(null); _exitRequested?.Dispose(); _showWait?.Unregister(null); diff --git a/src/FocusWShell.App/DeckWeb/DeckWebServer.cs b/src/FocusWShell.App/DeckWeb/DeckWebServer.cs index 0d45120..6c933e1 100644 --- a/src/FocusWShell.App/DeckWeb/DeckWebServer.cs +++ b/src/FocusWShell.App/DeckWeb/DeckWebServer.cs @@ -24,7 +24,9 @@ namespace FocusWShell.App.DeckWeb; /// /// /// Protocolo v1. Servidor → página: {"type":"state","state":…}, {"type":"pages",…}, -/// {"type":"ack","seq":n,"ok":bool} y, con el PC bloqueado, sólo {"type":"locked"}. Página → servidor: +/// {"type":"ack","seq":n,"ok":bool}, {"type":"ping"} si pasan 3 s sin otro mensaje, y +/// {"type":"bye","reason":…} antes de cerrar cuando el PC se suspende, se apaga o FocusWShell se cierra +/// (ver ). Con el PC bloqueado, sólo {"type":"locked"} y latidos. Página → servidor: /// {"cmd":…,"seq":n,…} (ver ). Las apps y las páginas viajan con ids opacos que sólo /// el servidor sabe traducir. /// @@ -67,6 +69,52 @@ public DeckWebServer( Devices = devices; Devices.Changed += DropRevoked; SystemEvents.SessionSwitch += OnSessionSwitch; + SystemEvents.PowerModeChanged += OnPowerModeChanged; + } + + /// Cada conexión, con cómo despedirla (manda «bye» con el motivo y cierra). + private readonly ConcurrentDictionary> _leaves = new(); + + /// + /// El PC se va (se suspende, se apaga, se cierra la sesión): no se aceptan conexiones nuevas, para que la página + /// no reconecte en el segundo antes de irse. Se libera al despertar, o a los dos minutos si el apagado se canceló. + /// + private volatile string? _away; + + /// Si en este tiempo no se mandó nada, se manda un latido: la página sabe así que el PC sigue ahí. + private static readonly TimeSpan Heartbeat = TimeSpan.FromSeconds(3); + + private void OnPowerModeChanged(object? sender, PowerModeChangedEventArgs e) + { + if (e.Mode == PowerModes.Suspend) + { + Bye("sleep"); + } + else if (e.Mode == PowerModes.Resume) + { + _away = null; + } + } + + /// + /// Avisa a cada página por qué el PC se va (sleep, shutdown, logoff, closed, + /// off) y cierra sus conexiones. Espera como mucho un segundo: Windows no espera más. + /// + public void Bye(string reason) + { + _away = reason; + var leaves = _leaves.Values.ToList(); + if (leaves.Count > 0) + { + // En otro hilo: quien llama puede ser el de la interfaz, y esperar ahí bloquearía los envíos. + Task.Run(() => Task.WhenAll(leaves.Select(leave => leave(reason)))).Wait(TimeSpan.FromSeconds(1)); + } + + if (reason is "shutdown" or "logoff") + { + // Si una app detuvo el apagado, el deck vuelve. + _ = Task.Delay(TimeSpan.FromMinutes(2)).ContinueWith(_ => { if (_away == reason) { _away = null; } }, TaskScheduler.Default); + } } /// @@ -350,6 +398,13 @@ private async Task Socket(HttpContext context) return; } + // El PC se está yendo: que la página espere a que vuelva. + if (_away is not null) + { + context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; + return; + } + // Pocas conexiones por dispositivo: uno emparejado no puede saturar el PC. if (_sockets.Values.Count(id => id == device.Id) >= MaxSocketsPerDevice) { @@ -363,6 +418,7 @@ private async Task Socket(HttpContext context) using var cancel = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted); var send = new SemaphoreSlim(1); string? last = null; + var lastSent = DateTime.UtcNow; async Task Send(object message) { @@ -371,6 +427,7 @@ async Task Send(object message) try { await socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancel.Token); + lastSent = DateTime.UtcNow; } finally { @@ -378,6 +435,29 @@ async Task Send(object message) } } + async Task Leave(string reason) + { + try + { + await send.WaitAsync(cancel.Token); + try + { + var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "bye", reason }); + await socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancel.Token); + await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, reason, cancel.Token); + } + finally + { + send.Release(); + } + } + catch (Exception ex) when (ex is WebSocketException or OperationCanceledException or InvalidOperationException or ObjectDisposedException) + { + } + } + + _leaves[socket] = Leave; + async Task PushIfChanged() { if (_locked) @@ -400,13 +480,25 @@ async Task PushIfChanged() } } - // El estado al conectar y, cada medio segundo, si cambió: el PC también cambia sin la tablet. + // El estado al conectar y, cada medio segundo, si cambió: el PC también cambia sin la tablet. Si pasan + // 3 s sin mandar nada, un latido: así la página nota en segundos que el PC se apagó o se cayó la red. var pusher = Task.Run(async () => { - while (!cancel.IsCancellationRequested && socket.State == WebSocketState.Open) + try + { + while (!cancel.IsCancellationRequested && socket.State == WebSocketState.Open) + { + await PushIfChanged(); + if (DateTime.UtcNow - lastSent >= Heartbeat && socket.State == WebSocketState.Open) + { + await Send(new { type = "ping" }); + } + + await Task.Delay(500, cancel.Token); + } + } + catch (Exception ex) when (ex is WebSocketException or InvalidOperationException or ObjectDisposedException) { - await PushIfChanged(); - await Task.Delay(500, cancel.Token); } }, cancel.Token); @@ -458,6 +550,7 @@ async Task PushIfChanged() finally { _sockets.TryRemove(socket, out _); + _leaves.TryRemove(socket, out _); await cancel.CancelAsync(); try { @@ -850,6 +943,7 @@ public async ValueTask DisposeAsync() { Devices.Changed -= DropRevoked; SystemEvents.SessionSwitch -= OnSessionSwitch; + SystemEvents.PowerModeChanged -= OnPowerModeChanged; NetworkChange.NetworkAddressChanged -= OnNetworkChanged; _networkDebounce?.Cancel(); _recheck?.Dispose(); diff --git a/src/FocusWShell.App/DeckWeb/deck.css b/src/FocusWShell.App/DeckWeb/deck.css index 45593aa..3278267 100644 --- a/src/FocusWShell.App/DeckWeb/deck.css +++ b/src/FocusWShell.App/DeckWeb/deck.css @@ -162,3 +162,12 @@ body.locked #lockScreen { display: flex; position: fixed; inset: 0; flex-directi #lockScreen div { font-size: 56px; } #lockScreen b { font-size: 20px; color: var(--text); } #lockScreen small { font-size: 14px; } +/* Sin conexión con el PC: tapa todo (y la pantalla de bloqueo), para no tocar botones que no llegan. */ +#offScreen { display: none; } +body.offline #app, body.offline #lockScreen { display: none; } +body.offline #offScreen { display: flex; position: fixed; inset: 0; flex-direction: column; align-items: center; justify-content: center; gap: 10px; background: #000; color: var(--dim); text-align: center; padding: 16px; } +#offScreen #offIcon { font-size: 56px; } +#offScreen b { font-size: 20px; color: var(--text); } +#offScreen small { font-size: 14px; max-width: 420px; } +#offScreen .since { font-size: 12px; opacity: .7; } +#offScreen button { margin-top: 14px; min-height: 48px; padding: 0 22px; font-size: 16px; } diff --git a/src/FocusWShell.App/DeckWeb/deck.js b/src/FocusWShell.App/DeckWeb/deck.js index f5893e4..0ff73d1 100644 --- a/src/FocusWShell.App/DeckWeb/deck.js +++ b/src/FocusWShell.App/DeckWeb/deck.js @@ -16,6 +16,15 @@ const T = { monitors: n => `${n} ${n === 1 ? 'monitor' : 'monitores'}`, apps: n => `${n} apps`, locked: 'El PC está bloqueado', lockedHelp: 'Desbloquéalo en el PC y el deck vuelve solo.', connecting: 'Conectando…', reconnecting: 'Sin conexión con el PC. Reintentando…', sites: 'Sitios', loose: 'Páginas sueltas', + retryNow: 'Reintentar ahora', since: m => m < 1 ? 'Hace un momento' : m < 60 ? `Hace ${m} min` : `Hace ${Math.floor(m / 60)} h`, + away: { + sleep: ['🌙', 'El PC está en suspensión', 'Cuando lo despiertes, el deck vuelve solo.'], + shutdown: ['⏻', 'El PC se está apagando', 'Cuando lo enciendas e inicies sesión, el deck vuelve solo.'], + logoff: ['👋', 'Se cerró la sesión de Windows', 'Cuando inicies sesión otra vez, el deck vuelve solo.'], + closed: ['✕', 'FocusWShell se cerró', 'Cuando lo abras otra vez, el deck vuelve solo.'], + off: ['📴', 'El deck en la red se apagó', 'Cuando lo prendas otra vez en FocusWShell, el deck vuelve solo.'], + lost: ['📡', 'Sin conexión con el PC', 'Puede estar apagado o fuera de la red. Cuando vuelva, el deck vuelve solo.'], + }, privateWindows: 'Ventanas privadas', privateWindow: n => `🕶 Ventana privada · ${n} pestañas`, back: '‹ Sitios', loading: 'Leyendo las páginas…', noPages: 'No hay pestañas que leer en Chrome ni en Edge.', closeAll: 'Cerrar todas', }, @@ -33,6 +42,15 @@ const T = { monitors: n => `${n} ${n === 1 ? 'monitor' : 'monitors'}`, apps: n => `${n} apps`, locked: 'The PC is locked', lockedHelp: 'Unlock it on the PC and the deck comes back by itself.', connecting: 'Connecting…', reconnecting: 'No connection to the PC. Retrying…', sites: 'Sites', loose: 'Single pages', + retryNow: 'Retry now', since: m => m < 1 ? 'Just now' : m < 60 ? `${m} min ago` : `${Math.floor(m / 60)} h ago`, + away: { + sleep: ['🌙', 'The PC is asleep', 'When you wake it up, the deck comes back by itself.'], + shutdown: ['⏻', 'The PC is shutting down', 'When you turn it on and sign in, the deck comes back by itself.'], + logoff: ['👋', 'You signed out of Windows', 'When you sign in again, the deck comes back by itself.'], + closed: ['✕', 'FocusWShell was closed', 'When you open it again, the deck comes back by itself.'], + off: ['📴', 'The deck on the network was turned off', 'When you turn it on again in FocusWShell, the deck comes back by itself.'], + lost: ['📡', 'No connection to the PC', 'It may be off or out of the network. When it\'s back, the deck comes back by itself.'], + }, privateWindows: 'Private windows', privateWindow: n => `🕶 Private window · ${n} tabs`, back: '‹ Sites', loading: 'Reading the pages…', noPages: 'No Chrome or Edge tabs to read.', closeAll: 'Close all', }, @@ -47,7 +65,7 @@ const icon = key => `/icon?key=${encodeURIComponent(key)}`; const img = (key, name) => ``; function noIcon(el) { const s = document.createElement('span'); s.className = 'ph'; s.textContent = el.dataset.i; el.replaceWith(s); } -let state = null, ws = null, seq = 0, retry = 500; +let state = null, ws = null, seq = 0; let moving = null; // null | 'app' | 'panel' let chosen = null; // la app elegida para mover let pinning = false; // modo Anclar: tocar alterna el ancla; sigue prendido hasta tocarlo otra vez @@ -67,20 +85,87 @@ function lock(on) { function status(text, bad) { $('status').textContent = text || ''; $('status').className = 'status' + (bad ? ' bad' : ''); } function send(cmd, data) { if (ws && ws.readyState === 1) ws.send(JSON.stringify({ cmd, seq: ++seq, ...data })); } +// --- Conexión --------------------------------------------------------------------------------------------- +// El PC manda algo al menos cada 3 s (un latido). Si pasan 8 s sin nada, la conexión se da por muerta: así se nota +// en segundos que el PC se apagó o se cayó la red, aunque el navegador no se entere. Cuando el PC puede, avisa +// antes por qué se va («bye»). La página no se recarga nunca: con el PC apagado, recargar deja la página de error +// del navegador y ya nada reintenta. Sólo se vuelve a abrir la conexión, hasta que el PC conteste. +const STALE = 8000; +let alive = false, lastMsg = 0, downSince = 0, why = null, attempt = 0, retryTimer = 0, showTimer = 0, openTimer = 0; + +function offline(on) { + if (document.body.classList.contains('offline') === on) { renderOffline(); return; } + document.body.classList.toggle('offline', on); + if (on) { pagesOpen = false; site = null; clearModes(); } + renderOffline(); +} + +function renderOffline() { + if (!document.body.classList.contains('offline')) return; + const [ico, title, help] = L.away[why] || L.away.lost; + $('offIcon').textContent = ico; $('offTitle').textContent = title; $('offHelp').textContent = help; + $('offSince').textContent = L.since(Math.floor((Date.now() - downSince) / 60000)); +} + +// Llegó el estado (o «bloqueado»): el PC está ahí. +function back() { + clearTimeout(showTimer); showTimer = 0; downSince = 0; why = null; attempt = 0; + offline(false); +} + function connect() { + clearTimeout(retryTimer); retryTimer = 0; + if (ws) return; // ya hay una abriéndose o abierta status(L.connecting); - ws = new WebSocket(`ws://${location.host}/ws${location.search}`); - ws.onopen = () => { retry = 500; status(''); }; - ws.onclose = () => { status(L.reconnecting, true); setTimeout(connect, retry); retry = Math.min(retry * 2, 8000); }; - ws.onmessage = e => { + const s = ws = new WebSocket(`ws://${location.host}/ws${location.search}`); + // Con el PC suspendido, abrir puede tardar mucho en fallar: a los 6 s se da por fallido. + openTimer = setTimeout(() => { if (s.readyState === 0) drop(s); }, 6000); + s.onopen = () => { clearTimeout(openTimer); alive = true; lastMsg = Date.now(); status(''); }; + s.onclose = () => drop(s); + s.onmessage = e => { + lastMsg = Date.now(); const m = JSON.parse(e.data); + if (m.type === 'ping') return; + if (m.type === 'bye') { why = m.reason; drop(s); return; } // Con el PC bloqueado no llega el estado: se tapa todo y se olvida lo que había. - if (m.type === 'locked') { lock(true); return; } - if (m.type === 'state') { lock(false); state = m.state; render(); } + if (m.type === 'locked') { back(); lock(true); return; } + if (m.type === 'state') { back(); lock(false); state = m.state; render(); } if (m.type === 'pages') { pages = m.pages; renderPages(); } }; } +function drop(s) { + if (s !== ws) return; // una conexión vieja + clearTimeout(openTimer); + s.onopen = s.onclose = s.onmessage = null; + try { s.close(); } catch { /* ya cerrada */ } + ws = null; alive = false; + if (!downSince) downSince = Date.now(); + // Si el PC dijo por qué se va, se tapa ya; un corte sin aviso, si dura más de 2,5 s (uno breve no parpadea). + if (why) offline(true); + else if (!showTimer && !document.body.classList.contains('offline')) { + showTimer = setTimeout(() => { showTimer = 0; if (!ws || !alive) { why = why || 'lost'; offline(true); } }, 2500); + } + status(L.reconnecting, true); + // Rápido el primer minuto; después cada 30 s, sin rendirse. + const delay = Date.now() - downSince < 60000 ? Math.min(500 * 2 ** attempt, 8000) : 30000; + attempt++; + clearTimeout(retryTimer); + retryTimer = setTimeout(connect, delay); +} + +// Al volver a la pestaña, a la red o al despertar la tablet, se prueba de inmediato: con la pantalla apagada el +// navegador frena los temporizadores. +function wake() { + if (ws && alive && Date.now() - lastMsg > STALE) drop(ws); + if (!ws) connect(); +} +setInterval(() => { if (ws && alive && Date.now() - lastMsg > STALE) drop(ws); renderOffline(); }, 2000); +document.addEventListener('visibilitychange', () => { if (!document.hidden) wake(); }); +addEventListener('online', wake); +addEventListener('pageshow', wake); +$('retryNow').onclick = () => { attempt = 0; if (ws && !alive) drop(ws); connect(); }; + // --- Izquierda ------------------------------------------------------------------------------------------ function renderLeft() { diff --git a/src/FocusWShell.App/DeckWeb/index.html b/src/FocusWShell.App/DeckWeb/index.html index 4145c91..ae4594f 100644 --- a/src/FocusWShell.App/DeckWeb/index.html +++ b/src/FocusWShell.App/DeckWeb/index.html @@ -63,6 +63,7 @@

🔒
+