Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/adr/0021-deck-por-la-red.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 8 additions & 0 deletions site/deck-network.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 8 additions & 0 deletions site/es/deck-red.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
12 changes: 11 additions & 1 deletion src/FocusWShell.App/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1037,7 +1037,11 @@ private void FreezeSession()
}

/// <summary>Apagar, reiniciar o cerrar sesión desde Windows (no desde el deck).</summary>
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é
}

/// <summary>La actividad (ADR 0019): se mide sólo si está prendida; se guardan los días que diga la configuración.</summary>
private void StartActivity()
Expand Down Expand Up @@ -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;
}
Expand Down Expand Up @@ -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);
Expand Down
104 changes: 99 additions & 5 deletions src/FocusWShell.App/DeckWeb/DeckWebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ namespace FocusWShell.App.DeckWeb;
/// </summary>
/// <remarks>
/// Protocolo v1. Servidor → página: <c>{"type":"state","state":…}</c>, <c>{"type":"pages",…}</c>,
/// <c>{"type":"ack","seq":n,"ok":bool}</c> y, con el PC bloqueado, sólo <c>{"type":"locked"}</c>. Página → servidor:
/// <c>{"type":"ack","seq":n,"ok":bool}</c>, <c>{"type":"ping"}</c> si pasan 3 s sin otro mensaje, y
/// <c>{"type":"bye","reason":…}</c> antes de cerrar cuando el PC se suspende, se apaga o FocusWShell se cierra
/// (ver <see cref="Bye"/>). Con el PC bloqueado, sólo <c>{"type":"locked"}</c> y latidos. Página → servidor:
/// <c>{"cmd":…,"seq":n,…}</c> (ver <see cref="Handle"/>). Las apps y las páginas viajan con ids opacos que sólo
/// el servidor sabe traducir.
/// </remarks>
Expand Down Expand Up @@ -67,6 +69,52 @@ public DeckWebServer(
Devices = devices;
Devices.Changed += DropRevoked;
SystemEvents.SessionSwitch += OnSessionSwitch;
SystemEvents.PowerModeChanged += OnPowerModeChanged;
}

/// <summary>Cada conexión, con cómo despedirla (manda «bye» con el motivo y cierra).</summary>
private readonly ConcurrentDictionary<WebSocket, Func<string, Task>> _leaves = new();

/// <summary>
/// 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ó.
/// </summary>
private volatile string? _away;

/// <summary>Si en este tiempo no se mandó nada, se manda un latido: la página sabe así que el PC sigue ahí.</summary>
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;
}
}

/// <summary>
/// Avisa a cada página por qué el PC se va (<c>sleep</c>, <c>shutdown</c>, <c>logoff</c>, <c>closed</c>,
/// <c>off</c>) y cierra sus conexiones. Espera como mucho un segundo: Windows no espera más.
/// </summary>
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);
}
}

/// <summary>
Expand Down Expand Up @@ -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)
{
Expand All @@ -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)
{
Expand All @@ -371,13 +427,37 @@ async Task Send(object message)
try
{
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, cancel.Token);
lastSent = DateTime.UtcNow;
}
finally
{
send.Release();
}
}

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)
Expand All @@ -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);

Expand Down Expand Up @@ -458,6 +550,7 @@ async Task PushIfChanged()
finally
{
_sockets.TryRemove(socket, out _);
_leaves.TryRemove(socket, out _);
await cancel.CancelAsync();
try
{
Expand Down Expand Up @@ -850,6 +943,7 @@ public async ValueTask DisposeAsync()
{
Devices.Changed -= DropRevoked;
SystemEvents.SessionSwitch -= OnSessionSwitch;
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
_networkDebounce?.Cancel();
_recheck?.Dispose();
Expand Down
9 changes: 9 additions & 0 deletions src/FocusWShell.App/DeckWeb/deck.css
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Loading
Loading