Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(desktop): restore LAN WebUI settings and paired devices

vastsac27df2e71687
diff --git a/apps/desktop/electron/main/lan-webui/ipc.ts b/apps/desktop/electron/main/lan-webui/ipc.ts
index 6931aedee..a1b94b1dd 100644
--- a/apps/desktop/electron/main/lan-webui/ipc.ts
+++ b/apps/desktop/electron/main/lan-webui/ipc.ts
@@ -25,6 +25,6 @@ export function registerLanWebUiIpc(options: {
return service.admin(action);
});
onConfirmedQuit(() => {
- void service.dispose();
+ void service.dispose().catch(() => options.log("warn", "lan webui disposal failed"));
});
}
diff --git a/apps/desktop/electron/main/lan-webui/server.ts b/apps/desktop/electron/main/lan-webui/server.ts
index 109a6d01e..3f79c83c5 100644
--- a/apps/desktop/electron/main/lan-webui/server.ts
+++ b/apps/desktop/electron/main/lan-webui/server.ts
@@ -1,8 +1,9 @@
-import { randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
+import { createHash, createHmac, randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import type { Socket } from "node:net";
import type { LanDevice } from "@pi-desktop/shared";
import { LanError, type LanChange, type LanRequest } from "./ports";
+import { LABEL_MAX, MAX_DEVICES, type LanPairedDevice } from "./state";
export type LanAsset = { type: string; body: string };
export type LanServerHandler = {
@@ -13,17 +14,20 @@ export type LanServerHandler = {
const CODE_TTL_MS = 5 * 60_000;
const CODE_ATTEMPTS = 5;
-const MAX_DEVICES = 16;
+const COOKIE_TTL_SECONDS = 30 * 24 * 60 * 60;
const MAX_BODY = 300 * 1024;
const MAX_IDEMPOTENT = 200;
const HEARTBEAT_MS = 25_000;
-const LABEL_MAX = 60;
const SESSION_COOKIE = "pi_lan";
const CSP = "default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
-type Device = LanDevice & { token: string; csrf: string; streams: Set<ServerResponse>; idempotent: Map<string, Promise<unknown>> };
+type Device = LanPairedDevice & { streams: Set<ServerResponse>; idempotent: Map<string, Promise<unknown>> };
const secret = () => randomBytes(32).toString("base64url");
+const tokenHash = (token: string) => createHash("sha256").update(token).digest("hex");
+// An open page keeps its CSRF token across restart without persisting a second secret.
+const csrfFor = (token: string) => createHmac("sha256", token).update("pi-lan-csrf-v1").digest("base64url");
+const liveDevice = (paired: LanPairedDevice): Device => ({ ...paired, streams: new Set(), idempotent: new Map() });
const sameSecret = (a: string, b: string) => {
const left = Buffer.from(a);
@@ -88,27 +92,35 @@ export function createLanServer(options: {
assets: ReadonlyMap<string, LanAsset>;
onChange?: () => void;
now?: () => number;
+ pairings?: { devices: readonly LanPairedDevice[]; save: (devices: LanPairedDevice[]) => void };
}) {
const now = options.now ?? Date.now;
let server: Server | null = null;
let host = "";
let code: { value: string; expiresAt: number; attempts: number } | null = null;
const devices = new Map<string, Device>();
+ for (const paired of options.pairings?.devices ?? []) {
+ if (paired.expiresAt > now()) devices.set(paired.id, liveDevice(paired));
+ }
const sockets = new Set<Socket>();
let unsubscribe: (() => void) | null = null;
let heartbeat: ReturnType<typeof setInterval> | null = null;
const changed = () => options.onChange?.();
- const deviceFor = (request: IncomingMessage): Device | null => {
+ const deviceFor = (request: IncomingMessage): { device: Device; token: string } | null => {
const token = cookies(request).get(SESSION_COOKIE);
- if (!token) return null;
- for (const device of devices.values()) if (sameSecret(device.token, token)) return device;
+ if (!token || !/^[A-Za-z0-9_-]{43}$/.test(token)) return null;
+ pruneExpired();
+ const hash = tokenHash(token);
+ for (const device of devices.values()) {
+ if (sameSecret(device.tokenHash, hash)) return { device, token };
+ }
return null;
};
function requireDevice(device: Device) {
- if (!devices.has(device.id)) throw new LanError(401, "UNAUTHORIZED");
+ if (devices.get(device.id) !== device || device.expiresAt <= now()) throw new LanError(401, "UNAUTHORIZED");
}
/** DNS rebinding and cross-site request guard; not a TLS check. */
@@ -123,6 +135,28 @@ export function createLanServer(options: {
device.streams.clear();
}
+ function pruneExpired() {
+ const time = now();
+ for (const device of devices.values()) {
+ if (device.expiresAt > time) continue;
+ devices.delete(device.id);
+ closeStreams(device);
+ }
+ }
+
+ function saveDevices(next: Iterable<LanPairedDevice>) {
+ options.pairings?.save(Array.from(next, ({ id, label, lastActiveAt, tokenHash, expiresAt }) => (
+ { id, label, lastActiveAt, tokenHash, expiresAt }
+ )));
+ }
+
+ function removeDevice(device: Device) {
+ saveDevices([...devices.values()].filter(({ id }) => id !== device.id));
+ devices.delete(device.id);
+ closeStreams(device);
+ changed();
+ }
+
function expireCode() {
if (code && code.expiresAt <= now()) code = null;
}
@@ -141,17 +175,20 @@ export function createLanServer(options: {
}
throw new LanError(403, "PAIRING_FAILED");
}
+ pruneExpired();
if (devices.size >= MAX_DEVICES) throw new LanError(429, "RATE_LIMITED");
- // Consume the code and register the device together, without an async gap.
+ // Save before consuming the code or issuing the cookie, without an async gap.
+ const token = secret();
+ const lastActiveAt = now();
+ const device = liveDevice({
+ id: randomUUID(), label, lastActiveAt, tokenHash: tokenHash(token), expiresAt: lastActiveAt + COOKIE_TTL_SECONDS * 1000,
+ });
+ saveDevices([...devices.values(), device]);
code = null;
- const device: Device = {
- id: randomUUID(), label, lastActiveAt: now(), token: secret(), csrf: secret(),
- streams: new Set(), idempotent: new Map(),
- };
devices.set(device.id, device);
changed();
- sendJson(response, 200, { state: "paired" }, { "Set-Cookie": cookie(SESSION_COOKIE, device.token, 12 * 60 * 60) });
+ sendJson(response, 200, { state: "paired" }, { "Set-Cookie": cookie(SESSION_COOKIE, token, COOKIE_TTL_SECONDS) });
}
function events(device: Device, request: IncomingMessage, response: ServerResponse, sessionFilter: string | null) {
@@ -172,6 +209,7 @@ export function createLanServer(options: {
async function broadcast(change: LanChange) {
if (![...devices.values()].some((device) => device.streams.size)) return;
const reveal = change.sessionId && await options.handler.mayReveal(change.sessionId).catch(() => false);
+ pruneExpired();
const data = reveal ? { sessionId: change.sessionId } : {};
for (const device of devices.values()) {
for (const stream of device.streams) {
@@ -184,23 +222,22 @@ export function createLanServer(options: {
}
async function api(request: IncomingMessage, response: ServerResponse, url: URL) {
- const device = deviceFor(request);
- if (!device) throw new LanError(401, "UNAUTHORIZED");
+ const paired = deviceFor(request);
+ if (!paired) throw new LanError(401, "UNAUTHORIZED");
+ const { device, token } = paired;
device.lastActiveAt = now();
const method = request.method === "POST" ? "POST" : "GET";
if (url.pathname === "/v1/me" && method === "GET") {
// Compatibility metadata for already-open browser tabs; not per-device grants.
const access = { deviceId: device.id, projectScope: "all-local", temporary: true, chat: true, organize: true };
- return sendJson(response, 200, { csrf: device.csrf, access, label: device.label });
+ return sendJson(response, 200, { csrf: csrfFor(token), access, label: device.label });
}
if (method === "POST") {
const csrf = String(request.headers["x-csrf-token"] ?? "");
- if (!sameSecret(device.csrf, csrf)) throw new LanError(403, "CSRF");
+ if (!sameSecret(csrfFor(token), csrf)) throw new LanError(403, "CSRF");
}
if (url.pathname === "/v1/logout" && method === "POST") {
- closeStreams(device);
- devices.delete(device.id);
- changed();
+ removeDevice(device);
return sendJson(response, 200, { ok: true }, { "Set-Cookie": cookie(SESSION_COOKIE, "", 0) });
}
if (method === "GET" && url.pathname === "/v1/events") return events(device, request, response, null);
@@ -296,13 +333,14 @@ export function createLanServer(options: {
host = `${address}:${boundPort}`;
unsubscribe = options.handler.subscribe((change) => void broadcast(change));
heartbeat = setInterval(() => {
+ pruneExpired();
for (const device of devices.values()) for (const stream of device.streams) stream.write(": ping\n\n");
}, HEARTBEAT_MS);
heartbeat.unref?.();
return { address, port: boundPort };
},
- /** Stopping invalidates every pairing and device credential. */
+ /** Close the listener and discard runtime state; the service owns durable intent. */
async stop(): Promise<void> {
const current = server;
server = null;
@@ -337,15 +375,14 @@ export function createLanServer(options: {
},
devices(): LanDevice[] {
+ pruneExpired();
return [...devices.values()].map(({ id, label, lastActiveAt }) => ({ id, label, lastActiveAt }));
},
revoke(id: string): void {
const device = devices.get(id);
if (!device) return;
- closeStreams(device);
- devices.delete(id);
- changed();
+ removeDevice(device);
},
};
}
diff --git a/apps/desktop/electron/main/lan-webui/service.ts b/apps/desktop/electron/main/lan-webui/service.ts
index 6a6b6692a..259ea738c 100644
--- a/apps/desktop/electron/main/lan-webui/service.ts
+++ b/apps/desktop/electron/main/lan-webui/service.ts
@@ -9,10 +9,16 @@ import { onLanAgentEvent } from "./agent-tap";
import { getLanOrganization } from "./organization";
import { LanError } from "./ports";
import { createLanServer, type LanAsset } from "./server";
+import { createLanStateStore, type LanBinding, type LanSavedState } from "./state";
import { createLanWorkspace, type LanWorkspaceDeps } from "./workspace";
const DEFAULT_PORT = 37180;
+function actionError(error: unknown): string {
+ if (error instanceof LanError) return error.code;
+ return (error as NodeJS.ErrnoException)?.code === "EADDRINUSE" ? "PORT_IN_USE" : "FAILED";
+}
+
/** IPv4 private LAN addresses plus loopback, in that order. */
export function listLanInterfaces(source = networkInterfaces()): LanInterface[] {
const result: LanInterface[] = [];
@@ -46,25 +52,80 @@ export function createLanWebUiService(deps: {
const offAgent = onLanAgentEvent((envelope) => workspace.ingest(envelope));
const offWrites = organization.onRendererWrite(() => workspace.catalogChanged());
let server: ReturnType<typeof createLanServer> | null = null;
- let address: string | null = null;
- let port: number | null = null;
+ const store = createLanStateStore(deps.dataDir);
+ let saved: LanSavedState = { enabled: false, binding: null, devices: [] };
+ let restoreError: string | null = null;
+ let disposal: Promise<void> | null = null;
const notifyAdmin = () => deps.sendToRenderer(IPC.event.lanWebUiChanged, null);
- const ensureServer = () => {
- server ??= createLanServer({ handler: workspace, assets: deps.assets(), onChange: notifyAdmin });
- return server;
- };
+ function save(state: LanSavedState) {
+ try {
+ store.write(state);
+ } catch {
+ deps.log("warn", "lan webui could not save local state");
+ throw new LanError(500, "SAVE_FAILED");
+ }
+ saved = state;
+ }
+
+ async function open(binding: LanBinding, remember: boolean) {
+ if (server) throw new LanError(409, "ALREADY_RUNNING");
+ if (!listLanInterfaces().some(({ address }) => address === binding.address)) {
+ throw new LanError(400, "INVALID_ADDRESS");
+ }
+ const sameBinding = saved.binding?.address === binding.address && saved.binding.port === binding.port;
+ const devices = saved.enabled && sameBinding ? saved.devices : [];
+ const next = createLanServer({
+ handler: workspace, assets: deps.assets(), onChange: notifyAdmin,
+ pairings: { devices, save: (devices) => save({ ...saved, devices }) },
+ });
+ try {
+ const bound = await next.start(binding.address, binding.port);
+ if (disposal) throw new LanError(409, "NOT_RUNNING");
+ if (remember) save({ enabled: true, binding: bound, devices });
+ server = next;
+ restoreError = null;
+ deps.log("info", "lan webui started", { port: bound.port });
+ notifyAdmin();
+ } catch (error) {
+ await next.stop();
+ throw error;
+ }
+ }
- function view(error: string | null = null): LanAdminView {
+ async function close() {
const current = server;
- const running = current?.running() === true;
+ server = null;
+ await current?.stop();
+ }
+
+ async function restore() {
+ try {
+ saved = store.read();
+ if (saved.enabled && saved.binding) await open(saved.binding, false);
+ } catch (error) {
+ restoreError = actionError(error);
+ deps.log("warn", "lan webui restore failed", { code: restoreError });
+ }
+ }
+
+ // State reads and start/stop actions wait for restore and for each other.
+ let pending = restore();
+ function enqueue<T>(work: () => Promise<T>): Promise<T> {
+ const result = pending.then(work);
+ pending = result.then(() => undefined, () => undefined);
+ return result;
+ }
+
+ function view(error = restoreError): LanAdminView {
return {
- running,
- origin: running ? current!.origin() : null,
- address: running ? address : null,
- port: running ? port : null,
- code: running ? current!.code() : null,
- devices: running ? current!.devices() : [],
+ enabled: saved.enabled,
+ running: server !== null,
+ origin: server?.origin() ?? null,
+ address: saved.binding?.address ?? null,
+ port: saved.binding?.port ?? null,
+ code: server?.code() ?? null,
+ devices: server?.devices() ?? [],
interfaces: listLanInterfaces(),
error,
};
@@ -72,29 +133,32 @@ export function createLanWebUiService(deps: {
async function admin(action: LanAdminAction): Promise<LanAdminView> {
try {
+ if (disposal) throw new LanError(409, "NOT_RUNNING");
switch (action?.kind) {
case "state":
break;
case "start": {
- const allowed = listLanInterfaces().some((entry) => entry.address === action.address);
- const requestedPort = Number.isInteger(action.port) && action.port > 0 && action.port < 65536 ? action.port : DEFAULT_PORT;
- if (!allowed) throw new LanError(400, "INVALID_ADDRESS");
- const bound = await ensureServer().start(action.address, requestedPort);
- address = bound.address;
- port = bound.port;
- deps.log("info", "lan webui started", { port: bound.port });
- notifyAdmin();
+ const port = Number.isInteger(action.port) && action.port > 0 && action.port < 65_536 ? action.port : DEFAULT_PORT;
+ await open({ address: action.address, port }, true);
break;
}
case "stop":
- await server?.stop();
- address = null;
- port = null;
- deps.log("info", "lan webui stopped");
- notifyAdmin();
+ try {
+ if (saved.enabled) save({ ...saved, enabled: false, devices: [] });
+ restoreError = null;
+ } catch (error) {
+ restoreError = actionError(error);
+ throw error;
+ } finally {
+ // Always stop serving, even when the setting could not be saved.
+ await close();
+ deps.log("info", "lan webui stopped");
+ notifyAdmin();
+ }
break;
case "issueCode":
- ensureServer().issueCode();
+ if (!server) throw new LanError(409, "NOT_RUNNING");
+ server.issueCode();
break;
case "revoke":
server?.revoke(String(action.id));
@@ -106,9 +170,7 @@ export function createLanWebUiService(deps: {
throw new LanError(400, "INVALID_ARGUMENT");
}
} catch (error) {
- const code = error instanceof LanError
- ? error.code
- : (error as { code?: unknown })?.code === "EADDRINUSE" ? "PORT_IN_USE" : "FAILED";
+ const code = actionError(error);
if (!(error instanceof LanError)) deps.log("warn", "lan webui action failed", { kind: action?.kind, code });
return view(code);
}
@@ -116,12 +178,19 @@ export function createLanWebUiService(deps: {
}
return {
- admin,
- async dispose(): Promise<void> {
+ admin: (action: LanAdminAction) => enqueue(() => admin(action)),
+ dispose(): Promise<void> {
+ if (disposal) return disposal;
offAgent();
offWrites();
- await server?.stop();
- workspace.dispose();
+ disposal = enqueue(async () => {
+ try {
+ await close();
+ } finally {
+ workspace.dispose();
+ }
+ });
+ return disposal;
},
};
}
diff --git a/apps/desktop/electron/main/lan-webui/state.ts b/apps/desktop/electron/main/lan-webui/state.ts
new file mode 100644
index 000000000..471ef1404
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/state.ts
@@ -0,0 +1,86 @@
+import { randomUUID } from "node:crypto";
+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
+import { isIPv4 } from "node:net";
+import { join } from "node:path";
+import type { LanDevice } from "@pi-desktop/shared";
+
+export const MAX_DEVICES = 16;
+export const LABEL_MAX = 60;
+
+export type LanBinding = { address: string; port: number };
+export type LanPairedDevice = LanDevice & { tokenHash: string; expiresAt: number };
+export type LanSavedState = {
+ enabled: boolean;
+ binding: LanBinding | null;
+ devices: readonly LanPairedDevice[];
+};
+
+const emptyState: LanSavedState = { enabled: false, binding: null, devices: [] };
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === "object" && !Array.isArray(value);
+const isSafeInteger = (value: unknown): value is number =>
+ typeof value === "number" && Number.isSafeInteger(value);
+
+function parseBinding(value: unknown): LanBinding | null {
+ if (value === null) return null;
+ if (!isRecord(value) || typeof value.address !== "string" || !isIPv4(value.address)
+ || !isSafeInteger(value.port) || value.port < 1 || value.port > 65_535) {
+ throw new Error("Invalid saved LAN WebUI binding");
+ }
+ return { address: value.address, port: value.port };
+}
+
+function parseDevice(value: unknown): LanPairedDevice {
+ if (!isRecord(value) || typeof value.id !== "string" || !/^[0-9a-f-]{36}$/.test(value.id)
+ || typeof value.label !== "string" || !value.label.length || value.label.length > LABEL_MAX
+ || typeof value.tokenHash !== "string" || !/^[0-9a-f]{64}$/.test(value.tokenHash)
+ || !isSafeInteger(value.lastActiveAt) || !isSafeInteger(value.expiresAt) || value.expiresAt <= value.lastActiveAt) {
+ throw new Error("Invalid saved LAN WebUI device");
+ }
+ return { id: value.id, label: value.label, tokenHash: value.tokenHash, lastActiveAt: value.lastActiveAt, expiresAt: value.expiresAt };
+}
+
+function decode(value: unknown): LanSavedState {
+ if (!isRecord(value) || value.version !== 1 || typeof value.enabled !== "boolean"
+ || !Array.isArray(value.devices) || value.devices.length > MAX_DEVICES) {
+ throw new Error("Invalid saved LAN WebUI state");
+ }
+ const binding = parseBinding(value.binding);
+ if (!value.enabled) return { enabled: false, binding, devices: [] };
+ if (!binding) throw new Error("Missing saved LAN WebUI binding");
+ const devices = value.devices.map(parseDevice);
+ if (new Set(devices.map(({ id }) => id)).size !== devices.length
+ || new Set(devices.map(({ tokenHash }) => tokenHash)).size !== devices.length) {
+ throw new Error("Duplicate saved LAN WebUI devices");
+ }
+ return { enabled: true, binding, devices };
+}
+
+/** Machine-local listener intent and cookie verifiers, never synced or exported through IPC. */
+export function createLanStateStore(dataDir: string) {
+ const path = join(dataDir, "lan-webui.json");
+ return {
+ read(): LanSavedState {
+ let source: string;
+ try {
+ source = readFileSync(path, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return emptyState;
+ throw error;
+ }
+ return decode(JSON.parse(source));
+ },
+ write(state: LanSavedState): void {
+ mkdirSync(dataDir, { recursive: true, mode: 0o700 });
+ const temporary = `${path}.${randomUUID()}.tmp`;
+ try {
+ // The file is bounded to a handful of records. Commit it before accepting
+ // a pairing or acknowledging a revocation, with no async mutation gap.
+ writeFileSync(temporary, JSON.stringify({ version: 1, ...state }), { mode: 0o600, flag: "wx", flush: true });
+ renameSync(temporary, path);
+ } finally {
+ rmSync(temporary, { force: true });
+ }
+ },
+ };
+}
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
index 71b77a3ce..42ffede1b 100644
--- a/apps/desktop/resources/lan-webui/app.js
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -883,8 +883,10 @@
async function signOut() {
try {
await api("POST", "/v1/logout", {});
- } catch {
- // Signed out either way.
+ } catch (error) {
+ // A failed revocation must not look like a successful sign-out.
+ fail(error);
+ return;
}
state.me = null;
state.pending.clear();
diff --git a/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx
index b36822c17..75f0d18df 100644
--- a/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx
+++ b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx
@@ -20,8 +20,11 @@ export function LanWebUiSection() {
const restoreAddFocus = useRef(false);
const running = view?.running === true;
+ const enabled = view?.enabled ?? running;
const interfaces = view?.interfaces ?? [];
- const address = view?.address ?? interfaces.find((entry) => entry.address === preferredAddress)?.address ?? interfaces[0]?.address;
+ const selectedAddress = preferredAddress || view?.address;
+ const address = running ? view?.address
+ : selectedAddress ? interfaces.find((entry) => entry.address === selectedAddress)?.address : interfaces[0]?.address;
const localOnly = address === "127.0.0.1";
const paired = pairing && !busy && view?.code === null && view.devices.some((entry) => !pairing.has(entry.id));
@@ -44,22 +47,22 @@ export function LanWebUiSection() {
clearError();
setPairing(null);
};
- const toggle = () => {
- if (running) {
- void run({ kind: "stop" });
- return;
- }
+ const start = () => {
const parsed = Number(port);
const invalid = !Number.isInteger(parsed) || parsed < 1024 || parsed > 65535;
setPortError(invalid);
if (!invalid && address) void run({ kind: "start", address, port: parsed });
};
+ const toggle = () => {
+ if (enabled) void run({ kind: "stop" });
+ else start();
+ };
const errorText = error ? t(`lan:errors.${error}`, { defaultValue: t("lan:errors.FAILED") }) : null;
const portErrorText = portError ? t("lan:errors.INVALID_PORT") : error === "PORT_IN_USE" ? errorText : null;
const time = (ts: number) => formatUpdated(ts, i18n.language);
const status = loadFailed ? t("statusUnavailable") : !view ? t("statusLoading")
- : running ? t("statusOn", { count: view.devices.length }) : t("statusOff");
+ : running ? t("statusOn", { count: view.devices.length }) : enabled ? t("statusNotRunning") : t("statusOff");
return (
<>
@@ -77,7 +80,7 @@ export function LanWebUiSection() {
{loadFailed && !view ? (
<Button type="button" size="sm" onClick={refresh}>{t("retry")}</Button>
) : (
- <SettingsToggle checked={running} label={t("enable")} busy={busy} disabled={!view || !address} onChange={toggle} />
+ <SettingsToggle checked={enabled} label={t("enable")} busy={busy} disabled={!view || (!enabled && !address)} onChange={toggle} />
)}
</SettingsRow>
@@ -127,6 +130,9 @@ export function LanWebUiSection() {
{!pairing && (portErrorText || errorText) ? (
<p id={portErrorId} className="lan-error" role="alert">{portErrorText || errorText}</p>
) : null}
+ {enabled && !running ? (
+ <Button type="button" size="sm" disabled={busy || !address} onClick={start}>{t("retry")}</Button>
+ ) : null}
</SettingsCard>
{running && view ? (
diff --git a/apps/desktop/src/features/lan-webui/use-lan-webui-admin.ts b/apps/desktop/src/features/lan-webui/use-lan-webui-admin.ts
index ffa2840eb..7ae1e6e35 100644
--- a/apps/desktop/src/features/lan-webui/use-lan-webui-admin.ts
+++ b/apps/desktop/src/features/lan-webui/use-lan-webui-admin.ts
@@ -27,6 +27,7 @@ export function useLanWebUiAdmin() {
if (!active.current || ticket !== generation.current) return;
setView(next);
setLoadFailed(false);
+ if (next.error) setError(next.error);
},
() => {
if (active.current && ticket === generation.current) setLoadFailed(true);
diff --git a/apps/desktop/src/locales/lan.ts b/apps/desktop/src/locales/lan.ts
index 354569b4b..7970a5aaa 100644
--- a/apps/desktop/src/locales/lan.ts
+++ b/apps/desktop/src/locales/lan.ts
@@ -3,8 +3,9 @@ export const lanEn = {
title: "LAN WebUI",
caption: "Access this computer from the same Wi-Fi. Use only on trusted networks; HTTP is not encrypted.",
enable: "Allow LAN connections",
- enableHelp: "Works only while PI-Desktop is running. Turning it off signs every device out.",
+ enableHelp: "Restarts with PI-Desktop. Turning it off signs every device out.",
statusOff: "Off",
+ statusNotRunning: "Not running",
statusLoading: "Checking status…",
statusUnavailable: "Status unavailable",
retry: "Retry",
@@ -28,7 +29,7 @@ export const lanEn = {
pairTitle: "Add a device",
pairScan: "Scan with your phone camera",
pairQrLabel: "QR code for this device pairing",
- pairDescription: "This code lets a device view and change local projects and conversations, including temporary ones.",
+ pairDescription: "This code lets a device view and change local projects and conversations, including temporary ones. Pairing lasts 30 days.",
pairStepOpen: "On the device, open",
pairStepCode: "Enter this pairing code",
codeExpiresIn: "Expires in {{seconds}}s",
@@ -42,6 +43,7 @@ export const lanEn = {
INVALID_ADDRESS: "That network address is no longer available.",
INVALID_PORT: "Use a port between 1024 and 65535.",
NOT_RUNNING: "Turn the service on first.",
+ SAVE_FAILED: "Couldn't save the change. Check that the Desktop data folder is writable, then try again.",
FAILED: "The action failed. Try again.",
},
};
@@ -50,8 +52,9 @@ export const lanZh: typeof lanEn = {
title: "局域网 WebUI",
caption: "在同一 Wi‑Fi 下访问这台电脑。HTTP 不加密,请仅在可信网络中使用。",
enable: "允许局域网连接",
- enableHelp: "仅在 PI-Desktop 运行时可用。关闭后所有设备都会退出。",
+ enableHelp: "随 PI-Desktop 自动启动。手动关闭会让所有设备退出。",
statusOff: "未开启",
+ statusNotRunning: "未运行",
statusLoading: "正在读取状态…",
statusUnavailable: "无法读取状态",
retry: "重试",
@@ -75,7 +78,7 @@ export const lanZh: typeof lanEn = {
pairTitle: "添加设备",
pairScan: "用手机相机扫码",
pairQrLabel: "设备配对二维码",
- pairDescription: "持有此码的设备可直接查看并操作本机项目及临时会话。",
+ pairDescription: "持有此码的设备可直接查看并操作本机项目及临时会话。配对有效期为 30 天。",
pairStepOpen: "在设备上打开",
pairStepCode: "输入配对码",
codeExpiresIn: "{{seconds}} 秒后失效",
@@ -89,6 +92,7 @@ export const lanZh: typeof lanEn = {
INVALID_ADDRESS: "该网络地址已不可用。",
INVALID_PORT: "请使用 1024 到 65535 之间的端口。",
NOT_RUNNING: "请先开启服务。",
+ SAVE_FAILED: "无法保存更改。请确认桌面端数据目录可写后重试。",
FAILED: "操作失败,请重试。",
},
};
diff --git a/apps/desktop/test/helpers/lan-webui-fixture.mjs b/apps/desktop/test/helpers/lan-webui-fixture.mjs
index 1ac67f480..34aaab5e2 100644
--- a/apps/desktop/test/helpers/lan-webui-fixture.mjs
+++ b/apps/desktop/test/helpers/lan-webui-fixture.mjs
@@ -107,13 +107,11 @@ export function desktop() {
bucket[entry.key] = { ...(bucket[entry.key] ?? {}), ...entry.patch };
},
};
- const workspace = createLanWorkspace({
+ const workspaceDeps = {
getHost: () => host,
getBridge: () => bridge,
channels: { sessionCreate: "create", sessionRename: "rename", projectGroupRename: "groupRename", agentAbort: "abort" },
activeTurns,
- organization,
- notifyDesktop: (sessionId) => calls.push(["notify", sessionId ?? null]),
async invoke(channel, args) {
calls.push([channel, args]);
if (channel === "create") {
@@ -132,8 +130,13 @@ export function desktop() {
}
return {};
},
+ };
+ const workspace = createLanWorkspace({
+ ...workspaceDeps,
+ organization,
+ notifyDesktop: (sessionId) => calls.push(["notify", sessionId ?? null]),
});
- return { workspace, calls, turns, activeTurns, queue, meta, sessions, groups };
+ return { workspace, workspaceDeps, calls, turns, activeTurns, queue, meta, sessions, groups };
}
/** A tiny cookie-keeping browser against the real HTTP listener. */
diff --git a/apps/desktop/test/lan-webui-restart.test.mjs b/apps/desktop/test/lan-webui-restart.test.mjs
new file mode 100644
index 000000000..1d90a855e
--- /dev/null
+++ b/apps/desktop/test/lan-webui-restart.test.mjs
@@ -0,0 +1,164 @@
+import assert from "node:assert/strict";
+import { once } from "node:events";
+import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { browser, desktop } from "./helpers/lan-webui-fixture.mjs";
+
+const { createLanWebUiService } = await import("../electron/main/lan-webui/service.ts");
+const address = "127.0.0.1";
+
+async function reserve(port = 0) {
+ const socket = createServer().listen(port, address);
+ await once(socket, "listening");
+ return { port: socket.address().port, close: () => new Promise((resolve) => socket.close(resolve)) };
+}
+
+async function setup(t) {
+ const reservation = await reserve();
+ const { port } = reservation;
+ await reservation.close();
+ const dataDir = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "lan-restart-"));
+ const fixture = desktop();
+ const launch = () => createLanWebUiService({ workspace: fixture.workspaceDeps, dataDir, assets: () => new Map(), sendToRenderer: () => {}, log: () => {} });
+ let service = launch();
+ t.after(async () => {
+ await service.dispose();
+ fixture.workspace.dispose();
+ await rm(dataDir, { recursive: true, force: true });
+ });
+ const admin = (action) => service.admin(action);
+ const start = () => admin({ kind: "start", address, port });
+ const state = () => admin({ kind: "state" });
+ const origin = `http://${address}:${port}`;
+ return {
+ origin, port, admin, start, state, file: join(dataDir, "lan-webui.json"),
+ async restart(beforeLaunch = () => {}) {
+ await service.dispose();
+ await beforeLaunch();
+ service = launch();
+ return state();
+ },
+ async pair(label) {
+ const { code } = await admin({ kind: "issueCode" });
+ const response = await fetch(`${origin}/pair`, {
+ method: "POST", headers: { "Content-Type": "application/json", Connection: "close" }, body: JSON.stringify({ code: code.value, label }),
+ });
+ assert.equal(response.status, 200);
+ const [cookie] = response.headers.getSetCookie()[0].split(";");
+ const auth = { Cookie: cookie, Connection: "close" };
+ // Keep the original cookie even after logout to test host-side revocation.
+ const me = await fetch(`${origin}/v1/me`, { headers: auth }).then((response) => response.json());
+ const phone = browser(origin);
+ return { id: me.access.deviceId, auth, csrf: me.csrf, request: (method, path, body, extra) => phone.request(method, path, body, { ...auth, "X-CSRF-Token": me.csrf, ...extra }) };
+ },
+ };
+}
+
+test("enabled LAN WebUI and paired browsers survive a Desktop restart", async (t) => {
+ const lan = await setup(t);
+ assert.equal((await lan.state()).running, false);
+ assert.equal((await lan.start()).origin, lan.origin);
+ const phone = await lan.pair("iPhone");
+ const tablet = await lan.pair("Tablet");
+ const { code } = await lan.admin({ kind: "issueCode" });
+
+ const restored = await lan.restart();
+ assert.equal(restored.origin, lan.origin, "Desktop automatically listens at the same origin");
+ assert.equal(restored.code, null, "unused pairing codes do not survive a restart");
+ assert.deepEqual(restored.devices.map(({ id, label }) => [id, label]), [[phone.id, "iPhone"], [tablet.id, "Tablet"]]);
+ assert.equal((await phone.request("GET", "/pair/status")).status, 200);
+ assert.deepEqual((await phone.request("GET", "/v1/projects")).body.items.map(({ id }) => id), ["g-a", "g-b"]);
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, { "X-CSRF-Token": "" })).body.code, "CSRF");
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" })).status, 200, "the already-open page can still mutate");
+ assert.equal((await browser(lan.origin).request("POST", "/pair", { code: code.value })).body.code, "PAIRING_CLOSED");
+ const saved = await readFile(lan.file, "utf8");
+ assert.equal(saved.includes(phone.auth.Cookie.split("=")[1]), false, "the browser bearer credential is not stored on disk");
+ assert.equal(saved.includes(phone.csrf), false, "CSRF tokens are not stored on disk");
+
+ await lan.admin({ kind: "revoke", id: phone.id });
+ assert.equal((await tablet.request("POST", "/v1/logout", {})).status, 200);
+ assert.equal((await lan.restart()).devices.length, 0);
+ assert.equal((await phone.request("GET", "/v1/me")).status, 401);
+ assert.equal((await tablet.request("GET", "/v1/me")).status, 401, "even the old cookie cannot sign back in");
+
+ const replacement = await lan.pair("New phone");
+ await lan.admin({ kind: "stop" });
+ const stopped = await lan.restart();
+ assert.equal(stopped.running, false);
+ assert.equal(stopped.enabled, false);
+ assert.equal(stopped.port, lan.port);
+ assert.equal((await lan.start()).origin, lan.origin);
+ assert.equal((await replacement.request("GET", "/v1/me")).status, 401, "explicit disable forgets all pairings");
+});
+
+test("a blocked restore retains the exact binding for retry and can be turned off", async (t) => {
+ const lan = await setup(t);
+ assert.equal((await lan.start()).origin, lan.origin);
+ const remembered = await lan.pair("Tablet");
+ let blocker;
+ const blockPort = async () => { blocker = await reserve(lan.port); };
+ try {
+ const unavailable = await lan.restart(blockPort);
+ assert.equal(unavailable.enabled, true);
+ assert.equal(unavailable.running, false);
+ assert.equal(unavailable.port, lan.port);
+ assert.equal(unavailable.error, "PORT_IN_USE");
+ assert.equal(unavailable.origin, null);
+ } finally {
+ await blocker?.close();
+ blocker = null;
+ }
+ assert.equal((await lan.start()).origin, lan.origin);
+ assert.equal((await remembered.request("GET", "/v1/me")).status, 200);
+ try {
+ assert.equal((await lan.restart(blockPort)).error, "PORT_IN_USE");
+ assert.equal((await lan.admin({ kind: "stop" })).enabled, false, "an enabled but unavailable listener can be turned off");
+ } finally {
+ await blocker?.close();
+ }
+ assert.equal((await lan.restart()).running, false);
+});
+
+test("restore refuses an unsafe saved bind address instead of falling back", async (t) => {
+ const lan = await setup(t);
+ const unavailable = await lan.restart(() => writeFile(lan.file, JSON.stringify({
+ version: 1, enabled: true, binding: { address: "0.0.0.0", port: lan.port }, devices: [],
+ })));
+ assert.equal(unavailable.error, "INVALID_ADDRESS");
+ assert.equal(unavailable.origin, null);
+ assert.equal(unavailable.running, false);
+ const reservation = await reserve(lan.port);
+ await reservation.close();
+});
+
+test("expired pairings cannot reopen a session after restart", async (t) => {
+ let now = Date.now();
+ t.mock.method(Date, "now", () => now);
+ const lan = await setup(t);
+ await lan.start();
+ const phone = await lan.pair("iPhone");
+ now += 29 * 86_400_000;
+ assert.equal((await lan.restart()).devices.length, 1);
+ assert.equal((await phone.request("GET", "/v1/me")).status, 200);
+ now += 86_400_000;
+ assert.equal((await phone.request("GET", "/v1/me")).status, 401);
+ assert.equal((await lan.restart()).devices.length, 0);
+ assert.equal((await phone.request("GET", "/v1/me")).status, 401);
+});
+
+test("a pairing is not issued if it cannot be saved", async (t) => {
+ const lan = await setup(t);
+ assert.equal((await lan.start()).origin, lan.origin);
+ await rm(lan.file, { force: true });
+ await mkdir(lan.file); // Atomic replacement cannot write over a directory.
+ const { code } = await lan.admin({ kind: "issueCode" });
+ const response = await fetch(`${lan.origin}/pair`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code: code.value }),
+ });
+ assert.equal(response.status, 500);
+ assert.deepEqual(response.headers.getSetCookie(), []);
+ assert.deepEqual((await lan.state()).devices, []);
+});
diff --git a/apps/desktop/test/lan-webui-settings-user-path.test.mjs b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
index b8d4d318c..dca5c63de 100644
--- a/apps/desktop/test/lan-webui-settings-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
@@ -32,14 +32,14 @@ const listeners = new Set();
const writes = [];
const copied = [];
const view = {
- running: false, origin: null, address: null, port: null, code: null, devices: [], error: null,
+ enabled: false, running: false, origin: null, address: null, port: null, code: null, devices: [], error: null,
interfaces: [{ address: "192.168.1.20", name: "Wi-Fi" }],
};
let stateReads = 0;
let startFails = true;
let issueCount = 0;
const emit = () => { for (const listener of listeners) listener(null); };
-const snapshot = (error = null) => ({ ok: true, data: structuredClone({ ...view, error }) });
+const snapshot = (error = view.error) => ({ ok: true, data: structuredClone({ ...view, error }) });
window.piDesktop = {
platform: "darwin",
@@ -62,7 +62,7 @@ window.piDesktop = {
emit(); // Main can notify before the IPC reply arrives.
return snapshot("PORT_IN_USE");
}
- Object.assign(view, { running: true, address: action.address, port: action.port, origin: "http://" + action.address + ":" + action.port });
+ Object.assign(view, { enabled: true, running: true, address: action.address, port: action.port, origin: "http://" + action.address + ":" + action.port, error: null });
break;
case "issueCode":
issueCount++;
@@ -72,7 +72,7 @@ window.piDesktop = {
view.devices = view.devices.filter((item) => item.id !== action.id);
break;
case "stop":
- Object.assign(view, { running: false, address: null, port: null, origin: null, code: null, devices: [] });
+ Object.assign(view, { enabled: false, running: false, origin: null, code: null, devices: [], error: null });
break;
default:
throw new Error("Unexpected LAN action: " + action.kind);
@@ -173,6 +173,17 @@ window.lanSettingsProbe = async () => {
check(q(".lan-device").querySelectorAll("button").length === 1, "a paired device can be removed, not configured");
click(button(lanEn.remove));
await wait(() => q(".lan-devices-empty")?.textContent === lanEn.noDevices, "device removed");
+
+ const failRestore = () => {
+ Object.assign(view, { running: false, origin: null, error: "PORT_IN_USE" });
+ emit();
+ return wait(() => alert() === lanEn.errors.PORT_IN_USE && q('.lan-status').textContent === lanEn.statusNotRunning, "restore error is visible");
+ };
+ await failRestore();
+ check(toggle().getAttribute("aria-checked") === "true" && field().value === "38180", "enabled preference and port survive a failed bind");
+ click(button(lanEn.retry, section()));
+ await wait(() => button(lanEn.addDevice) && !alert(), "retry uses the saved binding");
+ await failRestore();
click(toggle());
await wait(() => toggle().getAttribute("aria-checked") === "false" && !button(lanEn.addDevice), "service stopped");
await i18n.changeLanguage("zh-CN");
@@ -233,7 +244,8 @@ app.whenReady().then(async () => {
{ kind: "start", address: "192.168.1.20", port: 38180 },
{ kind: "start", address: "192.168.1.20", port: 38180 },
{ kind: "issueCode" }, { kind: "issueCode" }, { kind: "issueCode" },
- { kind: "revoke", id: "device" }, { kind: "stop" },
+ { kind: "revoke", id: "device" },
+ { kind: "start", address: "192.168.1.20", port: 38180 }, { kind: "stop" },
],
copied: ["http://192.168.1.20:38180", "034209"],
remainingListeners: 0,
diff --git a/apps/desktop/test/lan-webui-user-path.test.mjs b/apps/desktop/test/lan-webui-user-path.test.mjs
index 7aae883ae..9ef254f64 100644
--- a/apps/desktop/test/lan-webui-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-user-path.test.mjs
@@ -167,7 +167,7 @@ test("pairing codes expire and exactly one redemption creates a device", async (
assert.deepEqual(responses.map((response) => response.status).sort(), [200, 403]);
const accepted = responses.find((response) => response.ok);
const [cookie] = accepted.headers.getSetCookie();
- assert.match(cookie, /^pi_lan=[^;]+; Path=\/; HttpOnly; SameSite=Strict; Max-Age=43200$/);
+ assert.match(cookie, /^pi_lan=[^;]+; Path=\/; HttpOnly; SameSite=Strict; Max-Age=2592000$/);
assert.equal(responses.find((response) => !response.ok).headers.getSetCookie().length, 0);
assert.equal(server.devices().length, 2);
});
diff --git a/docs/adr/lan-webui-code-pairing.md b/docs/adr/lan-webui-code-pairing.md
index 6882b23c7..12bbfee2e 100644
--- a/docs/adr/lan-webui-code-pairing.md
+++ b/docs/adr/lan-webui-code-pairing.md
@@ -34,5 +34,22 @@ Anyone who obtains an active code can pair without another prompt. Display it
only for an intended device and use the existing plain-HTTP service only on a
trusted LAN. Stop the service or remove a device to revoke access.
-No durable grants are migrated. An app restart invalidates existing pairings;
-older open browser tabs can still check the issued cookie with `/pair/status`.
+The original implementation kept all grants in memory. The amendment below
+supersedes that lifecycle, not the code-only enrollment or its scope.
+
+## Amendment: Remember pairing across Desktop launches (D688)
+
+An app quit is not an explicit revocation. Remember the opt-in and its exact
+address and port alongside the paired devices in the local Desktop profile.
+Restart only if the same binding is still allowed and available. An explicit
+disable, device removal or sign-out durably revokes access; fresh installs
+and profiles with no saved opt-in still start off.
+
+Keeping all state in memory requires repeated pairing, while storing reusable
+cookie values would unnecessarily expose credentials to anyone who can read
+the profile. Store SHA-256 verifiers of random 256-bit cookies instead, limit
+browser cookies and server records to 30 days, and retain the existing CSRF
+and request checks. This trades a longer credential lifetime on unencrypted
+HTTP for reconnect convenience; use it only on trusted networks. Pairing
+codes and live connections still die with the process. There is no state to
+migrate from the previous version; opt in and pair once after upgrading.
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
index 04a02f9c9..f4bbe7a3d 100644
--- a/docs/spec/01-product/03-lan-webui-mvp.md
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -56,13 +56,18 @@ numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remo
attempts for malformed input or duplicate submits while pairing.
4. Devices shows the label and last activity of each paired browser. **Remove**
and browser sign-out invalidate that device's cookie and streams. Turning
- off closes the listener and signs out every device; a subsequent start
- requires fresh pairing. Closing a browser tab is not sign-out.
+ off in Settings closes the listener and revokes every pairing. The next
+ launch stays off and retains only the last binding for manual enablement.
+ Closing a browser tab is not sign-out.
5. Minimizing or hiding Desktop does not stop the service. Phone backgrounding,
Wi-Fi loss or closing a tab does not stop it. A browser cannot generate a
pairing code or submit a tool or plan approval. Sleep makes Desktop
- unreachable. If the bound address changes, restart the service on Desktop.
- Quitting Desktop stops the service; each launch starts **off**. Do not
+ unreachable. Quitting Desktop closes the listener. On its next launch,
+ Desktop tries the last explicitly enabled address and port, and the same
+ browser can reconnect without a new code while its pairing is valid.
+ An unavailable address or port leaves the listener down without changing
+ the saved preference. Settings shows the cause and lets the user retry or
+ turn it off. Selecting a different binding requires fresh pairing. Do not
promise active turns survive process exit.
Show actionable failures on the side that can fix them: no eligible interface,
@@ -219,13 +224,17 @@ Session archive is **owner-only** in RACP. The LAN WebUI does not reuse RACP
its organize operations against the current local catalog and only writes
the same Desktop organization record the sidebar uses (§5).
-Use a Host-issued `HttpOnly`, host-only, `SameSite=Strict` session cookie
-(12 hours; no `Secure` flag because the MVP is HTTP), exact Host/Origin
-validation, and CSRF tokens for authenticated mutations. Device credentials live
-only in Desktop memory: stopping the service or quitting Desktop signs every
-device out. No session credentials in URLs, local storage or logs. A QR may
-include the one-time code in a fragment; the browser removes it before sending
-requests, and submits it only in the pairing POST body. Serve assets locally
+Use a Host-issued `HttpOnly`, host-only, `SameSite=Strict` cookie (no `Secure`
+flag because the MVP is HTTP), exact Host/Origin validation, and CSRF tokens
+for authenticated mutations. Both browser and server expire the pairing after
+30 days from redemption. Desktop stores a verifier of the random cookie, not
+its value, in a machine-local profile file with the listener preference and
+device metadata. Pairing codes, streams and in-flight request state are never
+persisted. An explicit disable, removal or sign-out is saved before it is
+acknowledged. Invalid saved state is not used to open the listener. No session
+credentials in URLs, local storage or logs. A QR may include the one-time
+code in a fragment; the browser removes it before sending requests, and
+submits it only in the pairing POST body. Serve assets locally
under a restrictive CSP; never cache authenticated data (`no-store`). Logs
record only start/stop and failure codes, not prompts, history, codes or
cookies. Bound request bodies (300 KiB), prompts (256 KiB), pages (50 items)
@@ -313,7 +322,7 @@ settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`
| Area | Delivered | Not yet |
|---|---|---|
-| W01 | Off by default; interface + port; one-time-code pairing with copy and QR; remove devices; stop signs everyone out | HTTPS (deliberately deferred) |
+| W01 | Off by default; remembers opt-in, binding and unexpired pairings across launches; one-time-code pairing with copy and QR; explicit disable revokes access | HTTPS (deliberately deferred) |
| W02/W03 | Local projects and temporary conversations; search; archived filter; rename, pin, archive/restore with revision conflicts; new session in the explicit project | Reuse of an existing empty session |
| W04 | Paged history; live assistant text; send; queue; cancel queued; stop the named turn; “waiting on Desktop” for approvals and input | Answering ordinary questions from the browser; model label is the raw model id |
| W05 | Idempotency keys for every mutation; SSE change notices with refetch; reconnect banner | Cursor-based replay (refetch is used instead) |
@@ -322,6 +331,7 @@ settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`
| W08 | Existing names, pins and archives keep working; browser edits survive stale sidebar writes | — |
Automated coverage: `apps/desktop/test/lan-webui-organization.test.mjs`,
+`lan-webui-restart.test.mjs` (saved startup and pairing lifecycle),
`lan-webui-user-path.test.mjs` (real HTTP listener, fake Desktop),
`lan-webui-browser-user-path.test.mjs` (Electron Chromium at phone size driving
the shipped page), and `lan-webui-settings-user-path.test.mjs` (Desktop System
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index f6acc44a3..2e9a72274 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -766,13 +766,17 @@ user's running instance.
and code, then try pasting six digits with spaces or full-width digits. Scan
a fresh QR with the phone camera and submit the prefilled code. Open a project
and a temporary conversation; add project C on Desktop. Repeat with cookies
- blocked, wrong and expired codes, and rapid duplicate submit. Stop and restart.
+ blocked, wrong and expired codes, and rapid duplicate submit. Quit Desktop
+ and launch it again; reopen the same address in the paired browser. Repeat
+ with the saved port in use. Turn off the service in Settings and relaunch.
- **Expected:** No listener by default and no project data before pairing.
A scan opens the bound origin and clears its fragment without submitting;
a valid code connects on one submit. The desktop lists the device without
extra approval. A, B, C and temporary conversations are available. Invalid,
expired or redeemed codes fail, and blocked cookies show a specific error.
- Stopping invalidates credentials and releases the port; restart requires pairing.
+ Desktop restores the exact binding and unexpired pairings, not unused codes.
+ A blocked bind does not fall back and can be retried or disabled. Explicit
+ disable invalidates credentials, releases the port and stays off on relaunch.
- **Acceptance:** A, E; W01, W06.
### E2E-270: Organize projects and sessions without stealing navigation
@@ -842,7 +846,8 @@ user's running instance.
- **Steps:** Lose a create/send response, background the phone, switch Wi-Fi
off/on, refresh and reattach. Exercise same-key retry, a duplicate event,
a stale cursor/new epoch and slow-client overflow. Switch sessions while an
- old history page is outstanding. Separately restart Desktop, re-enable and pair.
+ old history page is outstanding. Separately restart Desktop and reconnect
+ the same paired browser without re-enabling or submitting another code.
- **Expected:** One original admission per intent, no automatic draft or tool
replay. A transient disconnect does not stop the turn. Cursor replay or a
replacement snapshot restores committed and partial content, queue and
@@ -858,14 +863,18 @@ user's running instance.
- **Steps:** Exercise catalog, histories, commands and SSE. Check wrong
Origin/Host, missing CSRF, the device cap and rejected admin/owner operations.
Remove one device while a temporary history request and stream are in flight;
- then change the desktop network. Inspect fixture logs and caches.
+ sign out on the other, restart Desktop and try the old cookies. Re-pair and
+ advance the clock to the pairing expiry; change the desktop address. Inspect
+ the fixture profile, logs and caches.
- **Expected:** The SSH-backed project remains hidden. Paired devices have the
same local WebUI operations, but no generic owner/SSH exemption or raw RPC.
Removal closes streams and refuses later requests, in-flight results and
cached mutation results for that device. Other devices remain connected. The
release also requires canceling revoked devices' not-started queued work.
- Credentials and content do not leak to logs or persistent caches. There is no
- connection on other interfaces or automatic sharing on the new network.
+ Revoked or expired cookies cannot reconnect across a restart. The profile has
+ verifiers, not bearer cookies or codes, and there are no credentials in logs
+ or authenticated response caches. An unavailable saved address is not
+ replaced automatically.
- **Acceptance:** D, E; W01, W02, W06.
### E2E-275: Preserve an existing desktop profile and disable cleanly
diff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.md
index 0b004ef51..dda655edf 100644
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@ -5440,3 +5440,10 @@ See ADR 0344.
use the supported local project and temporary-conversation operations, with
no separate grant switches. The existing local Agent safety rules and
device revocation remain. See [Code pairing](../../adr/lan-webui-code-pairing.md).
+
+## 2026-11-26 — LAN WebUI restores the opted-in listener and paired devices (D688)
+
+- Restart on the exact saved binding and accept unexpired browser cookies from
+ the same pairing. Keep only device metadata and cookie verifiers on Desktop.
+ Explicit disable or revocation persists; first launch still starts off. See
+ the [code pairing amendment](../../adr/lan-webui-code-pairing.md#amendment-remember-pairing-across-desktop-launches-d688).
diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.ts
index a76ec7a2b..a77ff885b 100644
--- a/packages/shared/src/lan-webui.ts
+++ b/packages/shared/src/lan-webui.ts
@@ -58,8 +58,11 @@ export interface LanInterface {
name: string;
}
export interface LanAdminView {
+ /** Saved preference; a failed bind can leave the service enabled but not running. */
+ enabled: boolean;
running: boolean;
origin: string | null;
+ /** Last successfully selected binding, even when unavailable or disabled. */
address: string | null;
port: number | null;
code: { value: string; expiresAt: number } | null;