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
2 changes: 2 additions & 0 deletions docs/adr/0021-deck-por-la-red.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,6 @@ Antes de publicarlo en una alfa:

Hallazgo del Firewall: la primera vez que FocusWShell escucha, Windows pregunta y crea la regla para el perfil de la red de ese momento. Con el wifi marcado como público, la regla quedó sólo para redes públicas; al marcarlo como privado, el Firewall bloqueaba la tablet y no volvía a preguntar. Se arregla a mano (con permisos de administrador); la sección y el manual lo explican.

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.

Sigue pendiente el cifrado (opción C): sin él, quien comparta la red puede ver el tráfico, incluido el token.
1 change: 1 addition & 0 deletions site/deck-network.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@ For now the page can't keep the tablet's screen on (browsers only allow it over
- After 5 wrong pairing codes, the code is cancelled, and that address has to wait 10 minutes.
- It only accepts requests from its own page: another website open on the tablet can't talk to your PC.
- Each device has its own key, which only the device keeps. Removing it cuts it off at once.
- If you lock the PC, the tablet locks too: it stops showing your apps and pages, and can't do anything. When you unlock the PC, the deck comes back by itself. The tablet never unlocks the PC.
- The connection is not encrypted (plain HTTP). Use it on a network you trust, such as your home Wi-Fi.
1 change: 1 addition & 0 deletions site/es/deck-red.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,4 +65,5 @@ Por ahora la página no puede mantener encendida la pantalla de la tablet (los n
- Tras 5 códigos de emparejamiento equivocados, el código se anula, y esa dirección tiene que esperar 10 minutos.
- Sólo acepta peticiones de su propia página: otra web abierta en la tablet no puede hablarle a tu PC.
- Cada dispositivo tiene su propia llave, que sólo guarda el dispositivo. Quitarlo lo corta al momento.
- Si bloqueas el PC, la tablet también se bloquea: deja de ver tus apps y tus páginas, y no puede hacer nada. Al desbloquear en el PC, el deck vuelve solo. La tablet nunca desbloquea el PC.
- La conexión no va cifrada (HTTP). Úsalo en una red de confianza, como el wifi de tu casa.
48 changes: 45 additions & 3 deletions src/FocusWShell.App/DeckWeb/DeckWebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;

namespace FocusWShell.App.DeckWeb;

Expand All @@ -23,9 +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>. Página → servidor: <c>{"cmd":…,"seq":n,…}</c> con <c>tap</c>,
/// <c>move</c>, <c>previous</c>, <c>toPanel</c>, <c>freeAll</c>, <c>pages</c>, <c>selectPage</c> y
/// <c>closePage</c>. Las apps y las páginas viajan con ids opacos que sólo el servidor sabe traducir.
/// <c>{"type":"ack","seq":n,"ok":bool}</c> y, con el PC bloqueado, sólo <c>{"type":"locked"}</c>. 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>
public sealed class DeckWebServer : IAsyncDisposable
{
Expand Down Expand Up @@ -65,6 +66,25 @@ public DeckWebServer(
_pageTitles = pageTitles;
Devices = devices;
Devices.Changed += DropRevoked;
SystemEvents.SessionSwitch += OnSessionSwitch;
}

/// <summary>
/// El PC está bloqueado (o la sesión, desconectada): la página sólo recibe «bloqueado», sin apps, foco ni
/// páginas, y los comandos se rechazan. Al desbloquear en el PC, el deck vuelve solo.
/// </summary>
private volatile bool _locked;

private void OnSessionSwitch(object? sender, SessionSwitchEventArgs e)
{
if (e.Reason is SessionSwitchReason.SessionLock or SessionSwitchReason.ConsoleDisconnect or SessionSwitchReason.RemoteDisconnect)
{
_locked = true;
}
else if (e.Reason is SessionSwitchReason.SessionUnlock or SessionSwitchReason.ConsoleConnect or SessionSwitchReason.RemoteConnect)
{
_locked = false;
}
}

public DeckWebDevices Devices { get; }
Expand All @@ -81,6 +101,9 @@ public DeckWebServer(
/// <summary>Conexiones abiertas a la vez por dispositivo (una tablet con dos pestañas, más una que reconecta).</summary>
private const int MaxSocketsPerDevice = 3;

/// <summary>Lo último enviado a una conexión cuando fue «bloqueado» (no es JSON de estado: nunca coincide).</summary>
private const string LockedMarker = "locked:";

/// <summary>Las direcciones del PC en las que escucha: sólo las de redes que Windows marca como privadas o de dominio.</summary>
private IReadOnlyList<IPAddress> _addresses = [];

Expand Down Expand Up @@ -357,6 +380,17 @@ async Task Send(object message)

async Task PushIfChanged()
{
if (_locked)
{
if (last != LockedMarker)
{
last = LockedMarker;
await Send(new { type = "locked" });
}

return;
}

var dto = Dto(_state(), device);
var json = JsonSerializer.Serialize(dto);
if (json != last)
Expand Down Expand Up @@ -395,6 +429,13 @@ async Task PushIfChanged()
using var doc = JsonDocument.Parse(buffer.AsMemory(0, received.Count));
var root = doc.RootElement;
int seq = root.TryGetProperty("seq", out var s) ? s.GetInt32() : 0;
if (_locked)
{
await Send(new { type = "ack", seq, ok = false });
await PushIfChanged();
continue; // con el PC bloqueado no se hace nada
}

// Leer las páginas cuesta (UI Automation en cada navegador): como mucho cada 2 s por conexión.
if (root.TryGetProperty("cmd", out var c) && c.GetString() == "pages")
{
Expand Down Expand Up @@ -808,6 +849,7 @@ internal static bool IsPrivate(IPAddress? address)
public async ValueTask DisposeAsync()
{
Devices.Changed -= DropRevoked;
SystemEvents.SessionSwitch -= OnSessionSwitch;
NetworkChange.NetworkAddressChanged -= OnNetworkChanged;
_networkDebounce?.Cancel();
_recheck?.Dispose();
Expand Down
8 changes: 8 additions & 0 deletions src/FocusWShell.App/DeckWeb/deck.css
Original file line number Diff line number Diff line change
Expand Up @@ -154,3 +154,11 @@ small { color: var(--dim); font-size: 11px; }
.screens { display: grid; grid-template-columns: repeat(auto-fit, minmax(110px, 1fr)); gap: 6px; }
.screens button { background: #9b6bd6; padding: 0 8px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.focusTile small.from { color: #dfe8f7; font-size: 12px; font-weight: 400; }

/* El PC bloqueado: la página no muestra nada hasta que se desbloquee en el PC. */
#lockScreen { display: none; }
body.locked #app { display: none; }
body.locked #lockScreen { 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; }
#lockScreen div { font-size: 56px; }
#lockScreen b { font-size: 20px; color: var(--text); }
#lockScreen small { font-size: 14px; }
12 changes: 11 additions & 1 deletion src/FocusWShell.App/DeckWeb/deck.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const T = {
pickApp: 'Toca la app que quieres mover.', pickPanel: 'Toca el panel donde va, o Libres para liberarla.',
free: 'Libres', noFree: 'Sin ventanas libres.', pages: 'Páginas', nothingInFocus: 'Nada en el foco',
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',
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',
Expand All @@ -30,6 +31,7 @@ const T = {
pickApp: 'Tap the app you want to move.', pickPanel: 'Tap the panel where it goes, or Free to free it.',
free: 'Free', noFree: 'No free windows.', pages: 'Pages', nothingInFocus: 'Nothing in focus',
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',
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',
Expand All @@ -56,6 +58,12 @@ const anyMode = () => !!moving || pinning || minimizing || closing || fulling;
function clearModes() { moving = null; chosen = null; pinning = false; minimizing = false; closing = false; fulling = false; fullApp = null; status(''); }
let pagesOpen = false, pages = null, site = null;

function lock(on) {
if (document.body.classList.contains('locked') === on) return;
document.body.classList.toggle('locked', on);
if (on) { state = null; pages = null; pagesOpen = false; site = null; clearModes(); $('monitors').innerHTML = ''; $('free').innerHTML = ''; $('focusTile').innerHTML = ''; $('pagesView').innerHTML = ''; }
}

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 })); }

Expand All @@ -66,7 +74,9 @@ function connect() {
ws.onclose = () => { status(L.reconnecting, true); setTimeout(connect, retry); retry = Math.min(retry * 2, 8000); };
ws.onmessage = e => {
const m = JSON.parse(e.data);
if (m.type === 'state') { state = m.state; render(); }
// 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 === 'pages') { pages = m.pages; renderPages(); }
};
}
Expand Down
1 change: 1 addition & 0 deletions src/FocusWShell.App/DeckWeb/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ <h3 data-t="free"></h3>
</div>
</main>
</div>
<div id="lockScreen"><div>🔒</div><b data-t="locked"></b><small data-t="lockedHelp"></small></div>
<script src="/deck.js"></script>
</body>
</html>
Loading