Skip to content

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

feat(desktop): redesign LAN WebUI pairing settings

vastsa0bbcbb0e8c88
diff --git a/apps/desktop/electron/main/lan-webui/server.ts b/apps/desktop/electron/main/lan-webui/server.ts
index 37922eb6a..f685b479f 100644
--- a/apps/desktop/electron/main/lan-webui/server.ts
+++ b/apps/desktop/electron/main/lan-webui/server.ts
@@ -24,10 +24,22 @@ const SESSION_COOKIE = "pi_lan";
const PENDING_COOKIE = "pi_lan_pending";
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 RememberedOperation = { grants: LanGrants; result: Promise<unknown> };
+type Device = LanDevice & { token: string; csrf: string; streams: Set<ServerResponse>; idempotent: Map<string, RememberedOperation> };
type Pending = LanPairing & { secret: string; deviceId: string | null };
const secret = () => randomBytes(32).toString("base64url");
+
+function cleanGrants(value: unknown): LanGrants {
+ const input = (value && typeof value === "object" ? value : {}) as Partial<Record<keyof LanGrants, unknown>>;
+ const projectIds = Array.isArray(input.projectIds)
+ ? [...new Set(input.projectIds.filter((id): id is string => typeof id === "string" && id.length > 0 && id.length < 200))]
+ : [];
+ const temporary = input.temporary === true;
+ if (!projectIds.length && !temporary) throw new LanError(400, "INVALID_SCOPE");
+ return { projectIds, temporary, chat: input.chat === true, organize: input.organize === true };
+}
+
const sameSecret = (a: string, b: string) => {
const left = Buffer.from(a);
const right = Buffer.from(b);
@@ -113,6 +125,11 @@ export function createLanServer(options: {
const access = (device: Device): LanAccess => ({ deviceId: device.id, ...device.grants });
+ function requireCurrentGrants(device: Device, grants: LanGrants) {
+ if (!devices.has(device.id)) throw new LanError(401, "UNAUTHORIZED");
+ if (device.grants !== grants) throw new LanError(409, "CONFLICT");
+ }
+
/** DNS rebinding and cross-site request guard; not a TLS check. */
const sameOrigin = (request: IncomingMessage) => {
if (request.headers.host !== host) return false;
@@ -132,15 +149,17 @@ export function createLanServer(options: {
}
async function pair(request: IncomingMessage, response: ServerResponse) {
- prune();
const body = await readBody(request);
+ prune();
const supplied = typeof body.code === "string" ? body.code.trim() : "";
const label = (typeof body.label === "string" ? body.label.trim() : "").slice(0, LABEL_MAX) || "Browser";
if (!code) throw new LanError(403, "PAIRING_CLOSED");
if (!sameSecret(code.value, supplied)) {
code.attempts += 1;
- if (code.attempts >= CODE_ATTEMPTS) code = null;
- changed();
+ if (code.attempts >= CODE_ATTEMPTS) {
+ code = null;
+ changed();
+ }
throw new LanError(403, "PAIRING_FAILED");
}
if (pending.size >= MAX_PENDING) throw new LanError(429, "RATE_LIMITED");
@@ -187,9 +206,10 @@ export function createLanServer(options: {
async function broadcast(change: LanChange) {
for (const device of devices.values()) {
if (!device.streams.size) continue;
+ const grants = device.grants;
let reveal = false;
if (change.sessionId) reveal = await options.handler.mayReveal(access(device), change.sessionId).catch(() => false);
- if (!devices.has(device.id)) continue;
+ if (!devices.has(device.id) || device.grants !== grants) continue;
for (const stream of device.streams) {
const filter = (stream as ServerResponse & { lanSession?: string | null }).lanSession ?? null;
if (filter && change.sessionId !== filter) continue;
@@ -203,6 +223,7 @@ 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 grants = device.grants;
device.lastActiveAt = now();
const method = request.method === "POST" ? "POST" : "GET";
if (url.pathname === "/v1/me" && method === "GET") {
@@ -223,21 +244,29 @@ export function createLanServer(options: {
if (method === "GET" && sessionEvents) {
const sessionId = decodeURIComponent(sessionEvents[1]!);
if (!(await options.handler.mayReveal(access(device), sessionId))) throw new LanError(404, "NOT_FOUND");
+ requireCurrentGrants(device, grants);
return events(device, request, response, sessionId);
}
const body = method === "POST" ? await readBody(request) : {};
+ requireCurrentGrants(device, grants);
const lanRequest: LanRequest = { method, path: url.pathname, query: url.searchParams, body, access: access(device) };
const rawKey = request.headers["idempotency-key"];
const key = typeof rawKey === "string" && /^[A-Za-z0-9_-]{8,80}$/.test(rawKey) ? rawKey : null;
let result: Promise<unknown>;
if (method === "POST" && key) {
- const remembered = device.idempotent.get(`${url.pathname}:${key}`);
+ const cacheKey = `${url.pathname}:${key}`;
+ const remembered = device.idempotent.get(cacheKey);
if (remembered) {
- result = remembered;
+ // A retry from an earlier grant must neither return its result nor execute again.
+ if (remembered.grants !== grants) throw new LanError(409, "CONFLICT");
+ result = remembered.result;
} else {
result = options.handler.handle(lanRequest, key);
- device.idempotent.set(`${url.pathname}:${key}`, result);
- result.catch(() => device.idempotent.delete(`${url.pathname}:${key}`));
+ const entry = { grants, result };
+ device.idempotent.set(cacheKey, entry);
+ result.catch(() => {
+ if (device.idempotent.get(cacheKey) === entry) device.idempotent.delete(cacheKey);
+ });
while (device.idempotent.size > MAX_IDEMPOTENT) {
device.idempotent.delete(device.idempotent.keys().next().value as string);
}
@@ -246,8 +275,7 @@ export function createLanServer(options: {
result = options.handler.handle(lanRequest, null);
}
const value = await result;
- // A device revoked while the request ran gets no data back.
- if (!devices.has(device.id)) throw new LanError(401, "UNAUTHORIZED");
+ requireCurrentGrants(device, grants);
sendJson(response, 200, value);
}
@@ -335,6 +363,7 @@ export function createLanServer(options: {
issueCode(): { value: string; expiresAt: number } {
if (!server) throw new LanError(409, "NOT_RUNNING");
code = { value: String(randomInt(0, 1_000_000)).padStart(6, "0"), expiresAt: now() + CODE_TTL_MS, attempts: 0 };
+ changed();
return { value: code.value, expiresAt: code.expiresAt };
},
@@ -354,6 +383,7 @@ export function createLanServer(options: {
/** Desktop confirmation: the only path that turns a pending browser into a device. */
confirm(id: string, grants: LanGrants): void {
+ prune();
const entry = pending.get(id);
if (!entry || entry.deviceId) throw new LanError(404, "NOT_FOUND");
if (devices.size >= MAX_DEVICES) throw new LanError(429, "RATE_LIMITED");
@@ -361,12 +391,7 @@ export function createLanServer(options: {
id: randomUUID(),
label: entry.label,
lastActiveAt: now(),
- grants: {
- projectIds: [...new Set(grants.projectIds.filter((value) => typeof value === "string"))],
- temporary: grants.temporary === true,
- chat: grants.chat === true,
- organize: grants.organize === true,
- },
+ grants: cleanGrants(grants),
token: secret(),
csrf: secret(),
streams: new Set(),
@@ -377,6 +402,19 @@ export function createLanServer(options: {
changed();
},
+ /** Keep device identity but reauthorize its next request and subscriptions. */
+ update(id: string, grants: LanGrants): void {
+ const device = devices.get(id);
+ if (!device) throw new LanError(404, "NOT_FOUND");
+ const next = cleanGrants(grants);
+ const current = device.grants;
+ if (next.temporary === current.temporary && next.chat === current.chat && next.organize === current.organize
+ && next.projectIds.length === current.projectIds.length && next.projectIds.every((id) => current.projectIds.includes(id))) return;
+ device.grants = next;
+ closeStreams(device);
+ changed();
+ },
+
deny(id: string): void {
pending.delete(id);
changed();
diff --git a/apps/desktop/electron/main/lan-webui/service.ts b/apps/desktop/electron/main/lan-webui/service.ts
index 36849d8b7..370c0f8b7 100644
--- a/apps/desktop/electron/main/lan-webui/service.ts
+++ b/apps/desktop/electron/main/lan-webui/service.ts
@@ -3,7 +3,6 @@ import {
IPC,
type LanAdminAction,
type LanAdminView,
- type LanGrants,
type LanInterface,
} from "@pi-desktop/shared";
import { onLanAgentEvent } from "./agent-tap";
@@ -29,19 +28,6 @@ export function listLanInterfaces(source = networkInterfaces()): LanInterface[]
return result;
}
-function validGrants(value: unknown): LanGrants {
- const input = (value && typeof value === "object" ? value : {}) as Partial<Record<keyof LanGrants, unknown>>;
- const projectIds = Array.isArray(input.projectIds)
- ? input.projectIds.filter((id): id is string => typeof id === "string" && id.length > 0 && id.length < 200)
- : [];
- return {
- projectIds,
- temporary: input.temporary === true,
- chat: input.chat === true,
- organize: input.organize === true,
- };
-}
-
export function createLanWebUiService(deps: {
workspace: Omit<LanWorkspaceDeps, "organization" | "notifyDesktop">;
dataDir: string;
@@ -60,19 +46,19 @@ 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 lastError: string | null = null;
let address: string | null = null;
let port: number | null = null;
+ const notifyAdmin = () => deps.sendToRenderer(IPC.event.lanWebUiChanged, null);
const ensureServer = () => {
- server ??= createLanServer({ handler: workspace, assets: deps.assets() });
+ server ??= createLanServer({ handler: workspace, assets: deps.assets(), onChange: notifyAdmin });
return server;
};
- async function view(): Promise<LanAdminView> {
+ async function view(error: string | null = null): Promise<LanAdminView> {
+ const projects = await workspace.operatorProjects().catch(() => []);
const current = server;
const running = current?.running() === true;
- const projects = await workspace.operatorProjects().catch(() => []);
return {
running,
origin: running ? current!.origin() : null,
@@ -83,12 +69,11 @@ export function createLanWebUiService(deps: {
devices: running ? current!.devices() : [],
interfaces: listLanInterfaces(),
projects,
- error: lastError,
+ error,
};
}
async function admin(action: LanAdminAction): Promise<LanAdminView> {
- lastError = null;
try {
switch (action?.kind) {
case "state":
@@ -101,6 +86,7 @@ export function createLanWebUiService(deps: {
address = bound.address;
port = bound.port;
deps.log("info", "lan webui started", { port: bound.port });
+ notifyAdmin();
break;
}
case "stop":
@@ -108,12 +94,16 @@ export function createLanWebUiService(deps: {
address = null;
port = null;
deps.log("info", "lan webui stopped");
+ notifyAdmin();
break;
case "issueCode":
ensureServer().issueCode();
break;
case "confirm":
- ensureServer().confirm(String(action.id), validGrants(action.grants));
+ ensureServer().confirm(String(action.id), action.grants);
+ break;
+ case "update":
+ ensureServer().update(String(action.id), action.grants);
break;
case "deny":
server?.deny(String(action.id));
@@ -131,8 +121,8 @@ export function createLanWebUiService(deps: {
const code = error instanceof LanError
? error.code
: (error as { code?: unknown })?.code === "EADDRINUSE" ? "PORT_IN_USE" : "FAILED";
- lastError = code;
if (!(error instanceof LanError)) deps.log("warn", "lan webui action failed", { kind: action?.kind, code });
+ return view(code);
}
return view();
}
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
index 6c0d7baaf..7f80bbd45 100644
--- a/apps/desktop/resources/lan-webui/app.js
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -119,7 +119,19 @@
function openEvents() {
closeEvents();
const source = new EventSource("/v1/events");
- source.addEventListener("open", () => (offline.hidden = true));
+ source.addEventListener("open", async () => {
+ try {
+ // Permission edits close the old stream. Refresh grants as well as data
+ // when the browser reconnects with the same device credential.
+ const me = await api("GET", "/v1/me");
+ if (state.events !== source) return;
+ state.me = me;
+ offline.hidden = true;
+ scheduleRefresh();
+ } catch (error) {
+ if (state.events === source) fail(error);
+ }
+ });
source.addEventListener("error", () => {
offline.textContent = t("offline");
offline.hidden = false;
diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx
index 08337551f..5dab879dc 100644
--- a/apps/desktop/src/components/icons.tsx
+++ b/apps/desktop/src/components/icons.tsx
@@ -57,6 +57,7 @@ import {
MessageSquare,
MessageSquarePlus,
Monitor,
+ Smartphone,
Moon,
MoreHorizontal,
Music,
@@ -98,6 +99,7 @@ import {
Video,
Volume2,
Webhook,
+ Wifi,
Workflow,
Wrench,
X,
@@ -245,6 +247,8 @@ export const IconServer = icon(Server);
export const IconSun = icon(Sun);
export const IconMoon = icon(Moon);
export const IconMonitor = icon(Monitor);
+export const IconSmartphone = icon(Smartphone);
+export const IconWifi = icon(Wifi);
export const IconPet = icon(PawPrint);
export const IconSnapshot = icon(RotateCw);
export const IconGear = icon(Settings);
diff --git a/apps/desktop/src/components/settings/LanWebUiSection.tsx b/apps/desktop/src/components/settings/LanWebUiSection.tsx
deleted file mode 100644
index 301d9054d..000000000
--- a/apps/desktop/src/components/settings/LanWebUiSection.tsx
+++ /dev/null
@@ -1,183 +0,0 @@
-import { useCallback, useEffect, useRef, useState } from "react";
-import { useTranslation } from "react-i18next";
-import type { LanAdminAction, LanAdminView, LanGrants } from "@pi-desktop/shared";
-import { api } from "../../lib/api";
-import { Badge, Button, Checkbox, CheckboxGroup, Input } from "../ui";
-import { SettingsCard, SettingsRow } from "../../features/settings/primitives";
-import { SettingsMenuSelect } from "./SettingsMenuSelect";
-
-const DEFAULT_PORT = 37180;
-const POLL_MS = 2000;
-
-const emptyGrants = (): LanGrants => ({ projectIds: [], temporary: false, chat: true, organize: true });
-
-/** Settings → System: start the LAN WebUI, pair devices and revoke them. */
-export function LanWebUiSection() {
- const { t } = useTranslation("lan");
- const [view, setView] = useState<LanAdminView | null>(null);
- const [address, setAddress] = useState("");
- const [port, setPort] = useState(String(DEFAULT_PORT));
- const [busy, setBusy] = useState(false);
- const [copied, setCopied] = useState(false);
- const [drafts, setDrafts] = useState<Record<string, LanGrants>>({});
- const alive = useRef(true);
-
- const run = useCallback(async (action: LanAdminAction) => {
- try {
- const next = await api.lanWebUiAdmin(action);
- if (alive.current) setView(next);
- } catch {
- // The next poll reports the actual state.
- }
- }, []);
-
- useEffect(() => {
- alive.current = true;
- void run({ kind: "state" });
- const timer = setInterval(() => void run({ kind: "state" }), POLL_MS);
- return () => {
- alive.current = false;
- clearInterval(timer);
- };
- }, [run]);
-
- useEffect(() => {
- if (!view || address) return;
- setAddress(view.address ?? view.interfaces[0]?.address ?? "");
- }, [view, address]);
-
- const act = async (action: LanAdminAction) => {
- setBusy(true);
- try {
- await run(action);
- } finally {
- setBusy(false);
- }
- };
-
- const running = view?.running === true;
- // Keys live in the `lan` namespace (locales/lan.ts), not the main catalog.
- const errorText = view?.error ? t(`lan:errors.${view.error}`, { defaultValue: t("lan:errors.FAILED") }) : null;
- const projectOptions = (view?.projects ?? []).map((project) => ({ value: project.id, label: project.label }));
- const draftFor = (id: string) => drafts[id] ?? emptyGrants();
- const setDraft = (id: string, patch: Partial<LanGrants>) =>
- setDrafts((current) => ({ ...current, [id]: { ...(current[id] ?? emptyGrants()), ...patch } }));
-
- return (
- <SettingsCard title={t("title")} caption={t("caption")} description={t("description")}>
- <SettingsRow title={t("status")}>
- <Badge tone={running ? "success" : "neutral"}>{running ? t("running") : t("stopped")}</Badge>
- </SettingsRow>
- <SettingsRow title={t("address")}>
- <SettingsMenuSelect
- label={t("address")}
- value={address}
- disabled={running || busy}
- options={(view?.interfaces ?? []).map((entry) => ({ id: entry.address, label: `${entry.address} · ${entry.name}` }))}
- onChange={setAddress}
- />
- </SettingsRow>
- <SettingsRow title={t("port")}>
- <Input
- aria-label={t("port")}
- inputMode="numeric"
- value={port}
- disabled={running || busy}
- onChange={(event) => setPort(event.target.value.replace(/\D/g, "").slice(0, 5))}
- />
- </SettingsRow>
- <SettingsRow title={running ? t("stop") : t("start")} detail={errorText ? <span role="alert">{errorText}</span> : undefined}>
- {running ? (
- <Button disabled={busy} onClick={() => void act({ kind: "stop" })}>{t("stop")}</Button>
- ) : (
- <Button
- variant="primary"
- disabled={busy || !address}
- onClick={() => void act({ kind: "start", address, port: Number(port) || DEFAULT_PORT })}
- >
- {t("start")}
- </Button>
- )}
- </SettingsRow>
-
- {running && view?.origin ? (
- <>
- <SettingsRow title={t("url")} detail={<code>{view.origin}</code>}>
- <Button
- size="sm"
- onClick={() => {
- void navigator.clipboard?.writeText(view.origin!).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- });
- }}
- >
- {copied ? t("copied") : t("copy")}
- </Button>
- </SettingsRow>
- <SettingsRow
- title={t("pairing")}
- description={t("pairingHint")}
- detail={view.code ? <strong aria-live="polite">{view.code.value}</strong> : undefined}
- >
- <Button size="sm" disabled={busy} onClick={() => void act({ kind: "issueCode" })}>{t("newCode")}</Button>
- </SettingsRow>
-
- {view.pending.map((entry) => {
- const draft = draftFor(entry.id);
- return (
- <SettingsRow
- key={entry.id}
- title={`${t("pending")} · ${entry.label}`}
- detail={
- <div>
- <p>{t("pendingHint", { label: entry.label })}</p>
- {projectOptions.length ? (
- <CheckboxGroup
- label={t("projects")}
- values={draft.projectIds}
- options={projectOptions}
- onChange={(projectIds) => setDraft(entry.id, { projectIds })}
- />
- ) : (
- <p>{t("noProjects")}</p>
- )}
- <Checkbox label={t("temporary")} checked={draft.temporary} onChange={(event) => setDraft(entry.id, { temporary: event.target.checked })} />
- <Checkbox label={t("chat")} checked={draft.chat} onChange={(event) => setDraft(entry.id, { chat: event.target.checked })} />
- <Checkbox label={t("organize")} checked={draft.organize} onChange={(event) => setDraft(entry.id, { organize: event.target.checked })} />
- </div>
- }
- >
- <Button size="sm" disabled={busy} onClick={() => void act({ kind: "deny", id: entry.id })}>{t("deny")}</Button>
- <Button
- size="sm"
- variant="primary"
- disabled={busy || (!draft.projectIds.length && !draft.temporary)}
- onClick={() => void act({ kind: "confirm", id: entry.id, grants: draft })}
- >
- {t("allow")}
- </Button>
- </SettingsRow>
- );
- })}
-
- <SettingsRow title={t("devices")} detail={view.devices.length ? undefined : t("noDevices")}>
- <span />
- </SettingsRow>
- {view.devices.map((device) => (
- <SettingsRow
- key={device.id}
- nested
- title={device.label}
- detail={`${t("scope", { count: device.grants.projectIds.length })} · ${t("lastActive", {
- time: new Date(device.lastActiveAt).toLocaleTimeString(),
- })}`}
- >
- <Button size="sm" disabled={busy} onClick={() => void act({ kind: "revoke", id: device.id })}>{t("revoke")}</Button>
- </SettingsRow>
- ))}
- </>
- ) : null}
- </SettingsCard>
- );
-}
diff --git a/apps/desktop/src/features/lan-webui/LanDialog.tsx b/apps/desktop/src/features/lan-webui/LanDialog.tsx
new file mode 100644
index 000000000..477f48b8d
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/LanDialog.tsx
@@ -0,0 +1,68 @@
+import { useRef, type ReactNode } from "react";
+import { useTranslation } from "react-i18next";
+import { useModalDialog } from "../../lib/use-modal-dialog";
+import { OverlayBackdrop, TooltipButton, portalOverlay } from "../../components/ui";
+import { IconClose } from "../../components/icons";
+
+export function LanDialog({
+ id,
+ title,
+ description,
+ icon,
+ onClose,
+ busy = false,
+ error,
+ children,
+ footer,
+}: {
+ id: string;
+ title: string;
+ description?: string;
+ icon: ReactNode;
+ onClose: () => void;
+ busy?: boolean;
+ error?: string | null;
+ children: ReactNode;
+ footer?: ReactNode;
+}) {
+ const { t } = useTranslation("lan");
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const close = () => { if (!busy) onClose(); };
+ useModalDialog(dialogRef, { onClose: close });
+
+ return portalOverlay(
+ <OverlayBackdrop className="overlay lan-dialog-overlay" role="presentation" onClick={close}>
+ <div
+ ref={dialogRef}
+ tabIndex={-1}
+ className="dialog lan-dialog"
+ role="dialog"
+ aria-modal="true"
+ aria-busy={busy || undefined}
+ aria-labelledby={`${id}-title`}
+ aria-describedby={description ? `${id}-description` : undefined}
+ >
+ <header className="lan-dialog-head">
+ <span className="lan-dialog-icon" aria-hidden="true">{icon}</span>
+ <div className="lan-dialog-heading">
+ <h2 id={`${id}-title`} className="lan-dialog-title">{title}</h2>
+ {description ? <p id={`${id}-description`} className="lan-dialog-description">{description}</p> : null}
+ </div>
+ <TooltipButton
+ type="button"
+ className="icon-btn lan-dialog-close"
+ tooltip={t("close")}
+ ariaLabel={t("close")}
+ aria-disabled={busy || undefined}
+ onClick={close}
+ >
+ <IconClose size={16} />
+ </TooltipButton>
+ </header>
+ <div className="lan-dialog-body">{children}</div>
+ {error ? <p className="lan-error lan-dialog-error" role="alert">{error}</p> : null}
+ {footer ? <footer className="lan-dialog-footer">{footer}</footer> : null}
+ </div>
+ </OverlayBackdrop>,
+ );
+}
diff --git a/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsx b/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsx
new file mode 100644
index 000000000..40b2fc684
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsx
@@ -0,0 +1,122 @@
+import { useId } from "react";
+import { useTranslation } from "react-i18next";
+import type { LanGrants } from "@pi-desktop/shared";
+import { Button, Checkbox } from "../../components/ui";
+import { IconCheck, IconShield } from "../../components/icons";
+
+export const NEW_DEVICE_GRANTS: LanGrants = { projectIds: [], temporary: false, chat: true, organize: true };
+
+/**
+ * What one paired device may see (projects, temporary conversations) and do
+ * (chat, organize). Viewing is always allowed and shown as such.
+ */
+export function LanGrantsEditor({
+ projects,
+ value,
+ onChange,
+ disabled = false,
+}: {
+ projects: Array<{ id: string; label: string }>;
+ value: LanGrants;
+ onChange: (next: LanGrants) => void;
+ disabled?: boolean;
+}) {
+ const { t } = useTranslation("lan");
+ const listId = useId();
+ const allSelected = projects.length > 0 && value.projectIds.length === projects.length;
+
+ const toggleProject = (id: string, on: boolean) =>
+ onChange({
+ ...value,
+ projectIds: on ? [...new Set([...value.projectIds, id])] : value.projectIds.filter((candidate) => candidate !== id),
+ });
+
+ return (
+ <div className="lan-grants">
+ <section className="lan-grants-section" aria-labelledby={`${listId}-projects`}>
+ <div className="lan-grants-section-head">
+ <h3 id={`${listId}-projects`} className="lan-grants-section-title">{t("projects")}</h3>
+ {projects.length ? (
+ <span className="lan-grants-section-meta">
+ {t("selectedCount", { selected: value.projectIds.length, total: projects.length })}
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={disabled}
+ onClick={() => onChange({ ...value, projectIds: allSelected ? [] : projects.map((project) => project.id) })}
+ >
+ {allSelected ? t("selectNone") : t("selectAll")}
+ </Button>
+ </span>
+ ) : null}
+ </div>
+ <div className="lan-grants-list" role="group" aria-labelledby={`${listId}-projects`}>
+ {projects.length ? projects.map((project) => (
+ <Checkbox
+ key={project.id}
+ className="lan-grants-option"
+ label={<span className="lan-grants-option-label">{project.label}</span>}
+ checked={value.projectIds.includes(project.id)}
+ disabled={disabled}
+ onChange={(event) => toggleProject(project.id, event.target.checked)}
+ />
+ )) : <p className="lan-grants-empty">{t("noProjects")}</p>}
+ <Checkbox
+ className="lan-grants-option lan-grants-option-separate"
+ label={
+ <span className="lan-grants-option-copy">
+ <span className="lan-grants-option-label">{t("scopeTemporary")}</span>
+ <span className="lan-grants-option-hint">{t("temporaryHint")}</span>
+ </span>
+ }
+ checked={value.temporary}
+ disabled={disabled}
+ onChange={(event) => onChange({ ...value, temporary: event.target.checked })}
+ />
+ </div>
+ </section>
+
+ <section className="lan-grants-section" aria-labelledby={`${listId}-abilities`}>
+ <div className="lan-grants-section-head">
+ <h3 id={`${listId}-abilities`} className="lan-grants-section-title">{t("abilities")}</h3>
+ </div>
+ <div className="lan-grants-list" role="group" aria-labelledby={`${listId}-abilities`}>
+ <div className="lan-grants-fixed">
+ <IconCheck size={14} aria-hidden="true" />
+ <span className="lan-grants-option-label">{t("alwaysView")}</span>
+ </div>
+ <Checkbox
+ className="lan-grants-option"
+ label={
+ <span className="lan-grants-option-copy">
+ <span className="lan-grants-option-label">{t("chat")}</span>
+ <span className="lan-grants-option-hint">{t("chatHint")}</span>
+ </span>
+ }
+ checked={value.chat}
+ disabled={disabled}
+ onChange={(event) => onChange({ ...value, chat: event.target.checked })}
+ />
+ <Checkbox
+ className="lan-grants-option"
+ label={
+ <span className="lan-grants-option-copy">
+ <span className="lan-grants-option-label">{t("organize")}</span>
+ <span className="lan-grants-option-hint">{t("organizeHint")}</span>
+ </span>
+ }
+ checked={value.organize}
+ disabled={disabled}
+ onChange={(event) => onChange({ ...value, organize: event.target.checked })}
+ />
+ </div>
+ </section>
+
+ <p className="lan-grants-note">
+ <IconShield size={14} aria-hidden="true" />
+ {t("approvalsStayHere")}
+ </p>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/lan-webui/LanPairDialog.tsx b/apps/desktop/src/features/lan-webui/LanPairDialog.tsx
new file mode 100644
index 000000000..5d1ef39f9
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/LanPairDialog.tsx
@@ -0,0 +1,151 @@
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { LanAdminView, LanGrants } from "@pi-desktop/shared";
+import { Button, cx } from "../../components/ui";
+import { IconCheck, IconCopy, IconRefresh, IconSmartphone } from "../../components/icons";
+import { LanDialog } from "./LanDialog";
+import { LanGrantsEditor } from "./LanGrantsEditor";
+import { useCountdown } from "./use-lan-webui-admin";
+
+export function CopyButton({ text }: { text: string }) {
+ const { t } = useTranslation("lan");
+ const [feedback, setFeedback] = useState<"copied" | "copyFailed" | null>(null);
+ useEffect(() => {
+ if (!feedback) return;
+ const timer = setTimeout(() => setFeedback(null), 1800);
+ return () => clearTimeout(timer);
+ }, [feedback]);
+
+ return (
+ <Button
+ type="button"
+ size="sm"
+ aria-live="polite"
+ onClick={async () => {
+ try {
+ await navigator.clipboard.writeText(text);
+ setFeedback("copied");
+ } catch {
+ setFeedback("copyFailed");
+ }
+ }}
+ >
+ {feedback === "copied" ? <IconCheck size={14} aria-hidden="true" /> : <IconCopy size={14} aria-hidden="true" />}
+ {t(feedback ?? "copy")}
+ </Button>
+ );
+}
+
+export function LanPairDialog({ origin, code, busy, error, issueCode, onClose }: {
+ origin: string;
+ code: LanAdminView["code"];
+ busy: boolean;
+ error: string | null;
+ issueCode: () => void;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation("lan");
+ const seconds = useCountdown(code?.expiresAt);
+ const value = code && !busy && seconds > 0 ? code.value : null;
+ const digits = (value ?? "······").split("");
+
+ return (
+ <LanDialog
+ id="lan-pair"
+ title={t("pairTitle")}
+ icon={<IconSmartphone size={18} />}
+ onClose={onClose}
+ error={error}
+ footer={value ? (
+ <p className="lan-pair-waiting" role="status">
+ <span className="lan-pair-waiting-dot" aria-hidden="true" />
+ {t("waiting")}
+ </p>
+ ) : null}
+ >
+ <ol className="lan-pair-steps" role="list">
+ <li className="lan-pair-step">
+ <span className="lan-pair-step-number" aria-hidden="true">1</span>
+ <div className="lan-pair-step-body">
+ <p className="lan-pair-step-title">{t("pairStepOpen")}</p>
+ <div className="lan-pair-url">
+ <code className="lan-pair-url-text">{origin}</code>
+ <CopyButton text={origin} />
+ </div>
+ </div>
+ </li>
+ <li className="lan-pair-step">
+ <span className="lan-pair-step-number" aria-hidden="true">2</span>
+ <div className="lan-pair-step-body">
+ <p className="lan-pair-step-title">{t("pairStepCode")}</p>
+ <span className="sr-only" aria-live="polite">{value ? digits.join(" ") : ""}</span>
+ <div className={cx("lan-code", !value && "is-expired")} aria-hidden="true">
+ {digits.map((digit, index) => <span key={index} className="lan-code-digit">{digit}</span>)}
+ </div>
+ <div className="lan-code-meta">
+ {value ? <span>{t("codeExpiresIn", { seconds })}</span> : (
+ <span role="status">{busy ? t("codeLoading") : !error ? t("codeExpired") : null}</span>
+ )}
+ <Button type="button" size="sm" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : issueCode}>
+ <IconRefresh size={14} aria-hidden="true" />
+ {t("newCode")}
+ </Button>
+ </div>
+ </div>
+ </li>
+ </ol>
+ </LanDialog>
+ );
+}
+
+/** Approve a pending browser, or change what a paired device may do. */
+export function LanAccessDialog({
+ mode, label, projects, initial, busy, error, onSubmit, onDeny, onClose,
+}: {
+ mode: "approve" | "edit";
+ label: string;
+ projects: LanAdminView["projects"];
+ initial: LanGrants;
+ busy: boolean;
+ error: string | null;
+ onSubmit: (grants: LanGrants) => void;
+ onDeny?: () => void;
+ onClose: () => void;
+}) {
+ const { t } = useTranslation("lan");
+ const [draft, setDraft] = useState(initial);
+ const projectIds = projects.filter((project) => draft.projectIds.includes(project.id)).map((project) => project.id);
+ const ready = projectIds.length > 0 || draft.temporary;
+ return (
+ <LanDialog
+ id={`lan-access-${mode}`}
+ title={mode === "approve" ? t("approveTitle", { label }) : t("editTitle", { label })}
+ description={mode === "approve" ? t("approveDescription") : undefined}
+ icon={<IconSmartphone size={18} />}
+ busy={busy}
+ error={error}
+ onClose={onClose}
+ footer={
+ <>
+ {!ready ? <span className="lan-dialog-footer-hint" role="status">{t("needScope")}</span> : null}
+ {mode === "approve" ? (
+ <Button type="button" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : onDeny}>{t("deny")}</Button>
+ ) : (
+ <Button type="button" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : onClose}>{t("cancel")}</Button>
+ )}
+ <Button
+ type="button"
+ variant="primary"
+ disabled={!ready}
+ aria-disabled={busy || undefined}
+ onClick={busy ? undefined : () => onSubmit({ ...draft, projectIds })}
+ >
+ {mode === "approve" ? t("allow") : t("save")}
+ </Button>
+ </>
+ }
+ >
+ <LanGrantsEditor projects={projects} value={{ ...draft, projectIds }} onChange={setDraft} disabled={busy} />
+ </LanDialog>
+ );
+}
diff --git a/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx
new file mode 100644
index 000000000..08e46e24f
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx
@@ -0,0 +1,260 @@
+import { useEffect, useId, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { LanAdminAction } from "@pi-desktop/shared";
+import { Button, Input, SettingsToggle, cx } from "../../components/ui";
+import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";
+import { IconPlus, IconSmartphone, IconWifi } from "../../components/icons";
+import { formatUpdated } from "../../lib/project-archive";
+import { SettingsCard, SettingsRow } from "../settings/primitives";
+import { NEW_DEVICE_GRANTS } from "./LanGrantsEditor";
+import { CopyButton, LanAccessDialog, LanPairDialog } from "./LanPairDialog";
+import { LAN_DEFAULT_PORT, useLanWebUiAdmin } from "./use-lan-webui-admin";
+
+type Dialog =
+ | { kind: "pair"; existingRequests: Set<string> }
+ | { kind: "approve" | "edit"; id: string };
+
+export function LanWebUiSection() {
+ const { t, i18n } = useTranslation("lan");
+ const { view, busy, error, loadFailed, run, refresh, clearError } = useLanWebUiAdmin();
+ const [preferredAddress, setPreferredAddress] = useState("");
+ const [port, setPort] = useState(String(LAN_DEFAULT_PORT));
+ const [portError, setPortError] = useState(false);
+ const [dialog, setDialog] = useState<Dialog | null>(null);
+ const portErrorId = useId();
+ const addDeviceRef = useRef<HTMLButtonElement>(null);
+ const opener = useRef<HTMLButtonElement | null>(null);
+
+ const running = view?.running === true;
+ const interfaces = view?.interfaces ?? [];
+ const address = view?.address ?? interfaces.find((entry) => entry.address === preferredAddress)?.address ?? interfaces[0]?.address;
+ const localOnly = address === "127.0.0.1";
+ const pending = view?.pending;
+ const devices = view?.devices;
+ const request = dialog?.kind === "approve" ? pending?.find((entry) => entry.id === dialog.id) : undefined;
+ const device = dialog?.kind === "edit" ? devices?.find((entry) => entry.id === dialog.id) : undefined;
+
+ useEffect(() => {
+ if (view?.address) setPreferredAddress(view.address);
+ if (view?.port) setPort(String(view.port));
+ }, [view?.address, view?.port]);
+
+ useEffect(() => {
+ if (!dialog) return;
+ if (!running || (dialog.kind === "approve" && !request) || (dialog.kind === "edit" && !device)) {
+ setDialog(null);
+ } else if (dialog.kind === "pair" && !busy) {
+ const received = pending?.find((entry) => !dialog.existingRequests.has(entry.id));
+ if (received) setDialog({ kind: "approve", id: received.id });
+ }
+ }, [busy, device, dialog, pending, request, running]);
+
+ useEffect(() => {
+ if (dialog || busy || !opener.current) return;
+ // A review button is gone after approval; return to Add device instead.
+ const target = opener.current.isConnected ? opener.current : addDeviceRef.current;
+ opener.current = null;
+ target?.focus({ preventScroll: true });
+ }, [busy, dialog]);
+
+ const open = (next: Dialog, trigger: HTMLButtonElement) => {
+ opener.current = trigger;
+ clearError();
+ setDialog(next);
+ };
+ const close = () => {
+ clearError();
+ setDialog(null);
+ };
+ const submit = async (action: LanAdminAction) => {
+ if (await run(action)) close();
+ };
+ const toggle = () => {
+ if (running) {
+ void run({ kind: "stop" });
+ return;
+ }
+ 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 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 list = new Intl.ListFormat(i18n.language || undefined, { style: "short" });
+ const status = loadFailed ? t("statusUnavailable") : !view ? t("statusLoading")
+ : running ? t("statusOn", { count: view.devices.length }) : t("statusOff");
+
+ return (
+ <>
+ <SettingsCard title={t("title")} caption={t("caption")}>
+ <SettingsRow
+ title={t("enable")}
+ description={t("enableHelp")}
+ detail={(
+ <span className="lan-status" role="status">
+ <span className={cx("settings-remote-host-pulse", running && !loadFailed && "is-online")} aria-hidden="true" />
+ {status}
+ </span>
+ )}
+ >
+ {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} />
+ )}
+ </SettingsRow>
+
+ {running && view?.origin ? (
+ <div className="lan-address">
+ <span className="lan-address-icon" aria-hidden="true"><IconWifi size={18} /></span>
+ <div className="lan-address-copy">
+ <div className="lan-address-label">{t("address")}</div>
+ <code className="lan-address-url">{view.origin}</code>
+ <div className="lan-address-hint">{t(localOnly ? "localOnly" : "addressHint")}</div>
+ </div>
+ <CopyButton text={view.origin} />
+ </div>
+ ) : view ? (
+ <>
+ <SettingsRow nested title={t("network")} description={t("networkHelp")}>
+ <SettingsMenuSelect
+ label={t("network")}
+ value={address ?? ""}
+ disabled={busy || !interfaces.length}
+ options={interfaces.map((entry) => ({
+ id: entry.address,
+ label: `${entry.address} · ${entry.address === "127.0.0.1" ? t("localOnly") : entry.name}`,
+ }))}
+ onChange={(next) => { setPreferredAddress(next); clearError(); }}
+ />
+ </SettingsRow>
+ <SettingsRow nested title={t("port")}>
+ <Input
+ className={cx("lan-port-input", !!portErrorText && "is-invalid")}
+ aria-label={t("port")}
+ aria-invalid={!!portErrorText || undefined}
+ aria-describedby={portErrorText ? portErrorId : undefined}
+ inputMode="numeric"
+ value={port}
+ disabled={busy}
+ onChange={(event) => {
+ setPortError(false);
+ clearError();
+ setPort(event.target.value.replace(/\D/g, "").slice(0, 5));
+ }}
+ />
+ </SettingsRow>
+ </>
+ ) : null}
+
+ {!dialog && (portErrorText || errorText) ? (
+ <p id={portErrorId} className="lan-error" role="alert">{portErrorText || errorText}</p>
+ ) : null}
+ </SettingsCard>
+
+ {running && view ? (
+ <SettingsCard
+ title={t("devices")}
+ caption={t("devicesCaption")}
+ action={(
+ <Button ref={addDeviceRef} type="button" variant="primary" disabled={busy} onClick={(event) => {
+ open({ kind: "pair", existingRequests: new Set(view.pending.map((entry) => entry.id)) }, event.currentTarget);
+ void run({ kind: "issueCode" });
+ }}>
+ <IconPlus size={14} aria-hidden="true" />
+ {t("addDevice")}
+ </Button>
+ )}
+ >
+ {view.pending.length || view.devices.length ? (
+ <ul className="lan-devices" role="list" aria-label={t("devices")}>
+ {view.pending.map((entry) => (
+ <li key={entry.id} className="lan-device is-request">
+ <span className="lan-device-icon" aria-hidden="true"><IconSmartphone size={16} /></span>
+ <div className="lan-device-copy">
+ <div className="lan-device-name">{t("requestTitle", { label: entry.label })}</div>
+ <div className="lan-device-meta">{t("requestedAt", { time: time(entry.createdAt) })}</div>
+ </div>
+ <div className="lan-device-actions">
+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void run({ kind: "deny", id: entry.id })}>{t("deny")}</Button>
+ <Button type="button" size="sm" variant="primary" disabled={busy} onClick={(event) => open({ kind: "approve", id: entry.id }, event.currentTarget)}>{t("review")}</Button>
+ </div>
+ </li>
+ ))}
+ {view.devices.map((entry) => {
+ const grants = entry.grants;
+ const actions = [grants.chat ? t("canChat") : "", grants.organize ? t("canOrganize") : ""].filter(Boolean);
+ return (
+ <li key={entry.id} className="lan-device">
+ <span className="lan-device-icon" aria-hidden="true"><IconSmartphone size={16} /></span>
+ <div className="lan-device-copy">
+ <div className="lan-device-name">{entry.label}</div>
+ <div className="lan-device-meta">
+ {[
+ grants.projectIds.length ? t("scope", { count: grants.projectIds.length }) : null,
+ grants.temporary ? t("scopeTemporary") : null,
+ actions.length ? list.format(actions) : t("viewOnly"),
+ t("activeAt", { time: time(entry.lastActiveAt) }),
+ ].filter(Boolean).join(" · ")}
+ </div>
+ </div>
+ <div className="lan-device-actions">
+ <Button type="button" size="sm" disabled={busy} onClick={(event) => open({ kind: "edit", id: entry.id }, event.currentTarget)}>{t("permissions")}</Button>
+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void run({ kind: "revoke", id: entry.id })}>{t("remove")}</Button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <div className="lan-devices-empty" role="status">
+ <IconSmartphone size={18} aria-hidden="true" />
+ {t("noDevices")}
+ </div>
+ )}
+ </SettingsCard>
+ ) : null}
+
+ {dialog?.kind === "pair" && view?.origin ? (
+ <LanPairDialog
+ origin={view.origin}
+ code={view.code}
+ busy={busy}
+ error={errorText}
+ issueCode={() => void run({ kind: "issueCode" })}
+ onClose={close}
+ />
+ ) : null}
+ {request && view ? (
+ <LanAccessDialog
+ key={request.id}
+ mode="approve"
+ label={request.label}
+ projects={view.projects}
+ initial={NEW_DEVICE_GRANTS}
+ busy={busy}
+ error={errorText}
+ onSubmit={(grants) => void submit({ kind: "confirm", id: request.id, grants })}
+ onDeny={() => void submit({ kind: "deny", id: request.id })}
+ onClose={close}
+ />
+ ) : null}
+ {device && view ? (
+ <LanAccessDialog
+ key={device.id}
+ mode="edit"
+ label={device.label}
+ projects={view.projects}
+ initial={device.grants}
+ busy={busy}
+ error={errorText}
+ onSubmit={(grants) => void submit({ kind: "update", id: device.id, grants })}
+ onClose={close}
+ />
+ ) : null}
+ </>
+ );
+}
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
new file mode 100644
index 000000000..ffa2840eb
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/use-lan-webui-admin.ts
@@ -0,0 +1,103 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { IPC, type LanAdminAction, type LanAdminView } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+
+const RUNNING_REFRESH_MS = 30_000;
+export const LAN_DEFAULT_PORT = 37180;
+
+/** Read live state without letting a refresh replace an action's result. */
+export function useLanWebUiAdmin() {
+ const [view, setView] = useState<LanAdminView | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const active = useRef(false);
+ const generation = useRef(0);
+ const acting = useRef(false);
+ const refreshQueued = useRef(false);
+
+ const refresh = useCallback(() => {
+ if (acting.current) {
+ refreshQueued.current = true;
+ return;
+ }
+ const ticket = ++generation.current;
+ void api.lanWebUiAdmin({ kind: "state" }).then(
+ (next) => {
+ if (!active.current || ticket !== generation.current) return;
+ setView(next);
+ setLoadFailed(false);
+ },
+ () => {
+ if (active.current && ticket === generation.current) setLoadFailed(true);
+ },
+ );
+ }, []);
+
+ useEffect(() => {
+ active.current = true;
+ const off = window.piDesktop?.on?.(IPC.event.lanWebUiChanged, refresh);
+ refresh();
+ return () => {
+ active.current = false;
+ generation.current += 1;
+ off?.();
+ };
+ }, [refresh]);
+
+ const running = view?.running === true;
+ useEffect(() => {
+ if (!running) return;
+ // Keep relative activity times and expired requests fresh without fast polling.
+ const timer = setInterval(refresh, RUNNING_REFRESH_MS);
+ return () => clearInterval(timer);
+ }, [running, refresh]);
+
+ const run = useCallback(async (action: LanAdminAction) => {
+ if (acting.current || !active.current) return false;
+ acting.current = true;
+ const ticket = ++generation.current;
+ setBusy(true);
+ setError(null);
+ try {
+ const next = await api.lanWebUiAdmin(action);
+ if (!active.current || ticket !== generation.current) return false;
+ setView(next);
+ setLoadFailed(false);
+ setError(next.error);
+ return next.error === null;
+ } catch {
+ if (active.current && ticket === generation.current) setError("FAILED");
+ return false;
+ } finally {
+ acting.current = false;
+ if (active.current) {
+ setBusy(false);
+ if (refreshQueued.current) {
+ refreshQueued.current = false;
+ refresh();
+ }
+ }
+ }
+ }, [refresh]);
+
+ const clearError = () => setError(null);
+ return { view, busy, error, loadFailed, run, refresh, clearError };
+}
+
+export function useCountdown(expiresAt: number | undefined): number {
+ const [now, setNow] = useState(Date.now);
+ useEffect(() => {
+ if (!expiresAt) return;
+ const start = Date.now();
+ setNow(start);
+ if (start >= expiresAt) return;
+ const timer = setInterval(() => {
+ const tick = Date.now();
+ setNow(tick);
+ if (tick >= expiresAt) clearInterval(timer);
+ }, 1000);
+ return () => clearInterval(timer);
+ }, [expiresAt]);
+ return expiresAt ? Math.max(0, Math.ceil((expiresAt - now) / 1000)) : 0;
+}
diff --git a/apps/desktop/src/features/settings/pages/SystemSettings.tsx b/apps/desktop/src/features/settings/pages/SystemSettings.tsx
index cd543bd0a..fbc4abeaf 100644
--- a/apps/desktop/src/features/settings/pages/SystemSettings.tsx
+++ b/apps/desktop/src/features/settings/pages/SystemSettings.tsx
@@ -10,7 +10,7 @@ import type { AppSettings, ShortcutPlatform } from "@pi-desktop/shared";
import { useTranslation } from "react-i18next";
import { SettingsToggle } from "../../../components/ui";
import { NetworkProxySection } from "../../../components/settings/NetworkProxySection";
-import { LanWebUiSection } from "../../../components/settings/LanWebUiSection";
+import { LanWebUiSection } from "../../lan-webui/LanWebUiSection";
import { CloseBehaviorSection } from "../developer-sections";
import { SettingsCard, SettingsRow } from "../primitives";
import { StorageSettingsSection } from "../StorageSettingsSection";
diff --git a/apps/desktop/src/locales/lan.ts b/apps/desktop/src/locales/lan.ts
index b3c8b1b51..ee5029426 100644
--- a/apps/desktop/src/locales/lan.ts
+++ b/apps/desktop/src/locales/lan.ts
@@ -1,82 +1,156 @@
/** LAN WebUI settings copy (namespace `lan`); English is the fallback. */
export const lanEn = {
title: "LAN WebUI",
- caption: "Use this Desktop from a browser or phone on the same network while the app is running.",
- description: "Plain HTTP on your local network. Only paired devices can see the projects you share; tool approvals stay on this computer. Stopping the service signs out every device.",
- status: "Status",
- running: "Running",
- stopped: "Off",
- address: "Network",
+ 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.",
+ statusOff: "Off",
+ statusLoading: "Checking status…",
+ statusUnavailable: "Status unavailable",
+ retry: "Retry",
+ statusOn_one: "On · {{count}} device",
+ statusOn_other: "On · {{count}} devices",
+ network: "Network",
+ networkHelp: "The address phones on the same Wi-Fi use to reach this computer.",
port: "Port",
- start: "Start",
- stop: "Stop",
- url: "Address",
+ localOnly: "Only on this computer",
+ address: "Address",
+ addressHint: "Open this address in the browser on your phone.",
copy: "Copy",
copied: "Copied",
- pairing: "Pairing code",
- pairingHint: "Open the address on the other device and enter this code. It works once and expires in 5 minutes.",
- newCode: "Show pairing code",
- pending: "Waiting for approval",
- pendingHint: "Choose what {{label}} may access, then allow it.",
- projects: "Shared projects",
- noProjects: "No projects yet.",
- temporary: "Temporary conversations",
- chat: "Send messages and create sessions",
+ copyFailed: "Couldn't copy",
+ devices: "Devices",
+ devicesCaption: "Only devices you approve here can connect.",
+ addDevice: "Add device",
+ noDevices: "No devices paired yet.",
+ requestTitle: "{{label}} wants to connect",
+ requestedAt: "Requested {{time}}",
+ review: "Review request",
+ deny: "Deny",
+ permissions: "Permissions",
+ remove: "Remove",
+ activeAt: "Active {{time}}",
+ scope_one: "{{count}} project",
+ scope_other: "{{count}} projects",
+ scopeTemporary: "Temporary conversations",
+ canChat: "Can send",
+ canOrganize: "Can organize",
+ viewOnly: "View only",
+ pairTitle: "Add a device",
+ pairStepOpen: "On the device, open",
+ pairStepCode: "Enter this pairing code",
+ codeExpiresIn: "Expires in {{seconds}}s",
+ codeExpired: "This code has expired.",
+ codeLoading: "Generating code…",
+ newCode: "New code",
+ waiting: "Waiting for the device…",
+ close: "Close",
+ approveTitle: "Allow {{label}}?",
+ approveDescription: "Choose which projects and actions to share with this device.",
+ editTitle: "{{label}} permissions",
+ projects: "Projects",
+ selectedCount: "{{selected}} of {{total}} selected",
+ selectAll: "Select all",
+ selectNone: "Clear",
+ noProjects: "There are no projects yet.",
+ temporaryHint: "Conversations that are not in a project",
+ abilities: "Allowed actions",
+ alwaysView: "View conversations and replies",
+ chat: "Send messages and start conversations",
+ chatHint: "Also stop a reply or cancel a queued message",
organize: "Rename, pin and archive",
+ organizeHint: "Applies to projects and conversations",
+ approvalsStayHere: "Tool and plan approvals always stay on this computer.",
+ needScope: "Choose at least one project or Temporary conversations.",
allow: "Allow",
- deny: "Deny",
- devices: "Paired devices",
- noDevices: "No paired devices.",
- lastActive: "Last active {{time}}",
- revoke: "Revoke",
- scope: "{{count}} projects",
+ save: "Save",
+ cancel: "Cancel",
errors: {
PORT_IN_USE: "That port is already in use. Choose another port.",
INVALID_ADDRESS: "That network address is no longer available.",
- NOT_RUNNING: "Start the service first.",
- NOT_FOUND: "That request is no longer pending.",
- RATE_LIMITED: "Too many devices. Revoke one first.",
+ INVALID_PORT: "Use a port between 1024 and 65535.",
+ NOT_RUNNING: "Turn the service on first.",
+ NOT_FOUND: "This device or request is no longer available.",
+ INVALID_SCOPE: "Choose at least one project or Temporary conversations.",
+ RATE_LIMITED: "Too many devices. Remove one first.",
FAILED: "The action failed. Try again.",
},
};
export const lanZh: typeof lanEn = {
title: "局域网 WebUI",
- caption: "应用运行时,可在同一网络的浏览器或手机上使用这台电脑上的会话。",
- description: "通过局域网 HTTP 访问。只有已配对的设备能看到你共享的项目;工具审批仍在这台电脑上完成。停止服务会让所有设备退出。",
- status: "状态",
- running: "运行中",
- stopped: "已关闭",
- address: "网络",
+ caption: "在同一 Wi‑Fi 下访问这台电脑。HTTP 不加密,请仅在可信网络中使用。",
+ enable: "允许局域网连接",
+ enableHelp: "仅在 PI-Desktop 运行时可用。关闭后所有设备都会退出。",
+ statusOff: "未开启",
+ statusLoading: "正在读取状态…",
+ statusUnavailable: "无法读取状态",
+ retry: "重试",
+ statusOn_one: "运行中 · {{count}} 台设备",
+ statusOn_other: "运行中 · {{count}} 台设备",
+ network: "网络",
+ networkHelp: "同一 Wi‑Fi 下的手机用这个地址访问这台电脑。",
port: "端口",
- start: "启动",
- stop: "停止",
- url: "访问地址",
+ localOnly: "仅本机可访问",
+ address: "访问地址",
+ addressHint: "在手机浏览器中打开这个地址。",
copy: "复制",
copied: "已复制",
- pairing: "配对码",
- pairingHint: "在另一台设备打开访问地址并输入此码。仅可使用一次,5 分钟后失效。",
- newCode: "显示配对码",
- pending: "等待批准",
- pendingHint: "选择 {{label}} 可以访问的内容,然后允许。",
- projects: "共享的项目",
+ copyFailed: "复制失败",
+ devices: "设备",
+ devicesCaption: "只有在这里批准的设备才能连接。",
+ addDevice: "添加设备",
+ noDevices: "还没有配对的设备。",
+ requestTitle: "{{label}} 请求连接",
+ requestedAt: "{{time}}请求",
+ review: "查看请求",
+ deny: "拒绝",
+ permissions: "权限",
+ remove: "移除",
+ activeAt: "{{time}}活跃",
+ scope_one: "{{count}} 个项目",
+ scope_other: "{{count}} 个项目",
+ scopeTemporary: "临时会话",
+ canChat: "可发消息",
+ canOrganize: "可整理",
+ viewOnly: "仅查看",
+ pairTitle: "添加设备",
+ pairStepOpen: "在设备上打开",
+ pairStepCode: "输入配对码",
+ codeExpiresIn: "{{seconds}} 秒后失效",
+ codeExpired: "配对码已失效。",
+ codeLoading: "正在生成配对码…",
+ newCode: "重新生成",
+ waiting: "等待设备输入配对码…",
+ close: "关闭",
+ approveTitle: "允许 {{label}} 连接?",
+ approveDescription: "选择要共享给这台设备的项目和操作权限。",
+ editTitle: "{{label}} 的权限",
+ projects: "项目",
+ selectedCount: "已选 {{selected}} / {{total}}",
+ selectAll: "全选",
+ selectNone: "清空",
noProjects: "还没有项目。",
- temporary: "临时会话",
- chat: "发送消息和新建会话",
+ temporaryHint: "不属于任何项目的会话",
+ abilities: "允许的操作",
+ alwaysView: "查看会话和回复",
+ chat: "发消息和新建会话",
+ chatHint: "也可以停止回复、取消排队消息",
organize: "重命名、置顶和归档",
+ organizeHint: "适用于项目和会话",
+ approvalsStayHere: "工具和计划审批始终只在这台电脑上完成。",
+ needScope: "至少选择一个项目或“临时会话”。",
allow: "允许",
- deny: "拒绝",
- devices: "已配对设备",
- noDevices: "暂无已配对设备。",
- lastActive: "最近活动 {{time}}",
- revoke: "撤销",
- scope: "{{count}} 个项目",
+ save: "保存",
+ cancel: "取消",
errors: {
PORT_IN_USE: "该端口已被占用,请换一个端口。",
INVALID_ADDRESS: "该网络地址已不可用。",
- NOT_RUNNING: "请先启动服务。",
- NOT_FOUND: "该配对请求已失效。",
- RATE_LIMITED: "设备过多,请先撤销一台。",
+ INVALID_PORT: "请使用 1024 到 65535 之间的端口。",
+ NOT_RUNNING: "请先开启服务。",
+ NOT_FOUND: "该设备或请求已失效。",
+ INVALID_SCOPE: "至少选择一个项目或“临时会话”。",
+ RATE_LIMITED: "设备过多,请先移除一台。",
FAILED: "操作失败,请重试。",
},
};
diff --git a/apps/desktop/src/styles/globals.css b/apps/desktop/src/styles/globals.css
index c42018840..1e2afbf3c 100644
--- a/apps/desktop/src/styles/globals.css
+++ b/apps/desktop/src/styles/globals.css
@@ -23,6 +23,7 @@
@import "./theme-overrides.css";
@import "./composer-menus.css";
@import "./settings.css";
+@import "./lan-webui.css";
@import "./startup-overlays.css";
@import "./destinations.css";
@import "./projects.css";
diff --git a/apps/desktop/src/styles/lan-webui.css b/apps/desktop/src/styles/lan-webui.css
new file mode 100644
index 000000000..08c36fac8
--- /dev/null
+++ b/apps/desktop/src/styles/lan-webui.css
@@ -0,0 +1,424 @@
+/* LAN WebUI connection, devices and pairing dialogs. */
+.lan-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.lan-address,
+.lan-device {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 12px;
+ padding: 14px 16px;
+}
+
+.lan-address {
+ border-radius: var(--radius-md-plus);
+ background: var(--ds-tile);
+}
+
+.lan-address-icon,
+.lan-device-icon,
+.lan-dialog-icon {
+ display: grid;
+ width: 36px;
+ height: 36px;
+ place-items: center;
+ border-radius: var(--radius-md);
+ background: var(--ds-tile-deep);
+ color: var(--ds-text-secondary);
+}
+
+.lan-address-icon,
+.lan-dialog-icon {
+ background: color-mix(in oklab, var(--ds-accent) 12%, var(--ds-tile));
+ color: var(--ds-accent);
+}
+
+.lan-address-copy,
+.lan-device-copy {
+ display: grid;
+ gap: 3px;
+ overflow-wrap: anywhere;
+}
+
+.lan-address-label,
+.lan-device-name {
+ color: var(--ds-text-primary);
+ font-size: var(--text-md);
+ font-weight: var(--font-weight-semibold);
+ line-height: var(--leading-compact);
+}
+
+.lan-address-url,
+.lan-pair-url-text {
+ color: var(--ds-text-primary);
+ font-family: var(--font-mono);
+ font-size: var(--text-md);
+ overflow-wrap: anywhere;
+ user-select: text;
+}
+
+.lan-address-hint,
+.lan-device-meta,
+.lan-dialog-description,
+.lan-dialog-footer-hint,
+.lan-code-meta,
+.lan-pair-waiting,
+.lan-grants-option-hint,
+.lan-grants-note {
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm-plus);
+ line-height: var(--leading-body);
+}
+
+.field-input.lan-port-input {
+ width: min(100%, 9ch);
+ min-height: var(--ds-settings-picker-height);
+ padding-block: 6px;
+ text-align: end;
+ font-variant-numeric: tabular-nums;
+}
+
+.lan-port-input.is-invalid {
+ outline: 1px solid var(--ds-error);
+}
+
+.lan-error {
+ margin: 0;
+ padding: 8px 12px;
+ border-inline-start: 2px solid var(--ds-error);
+ border-radius: var(--radius-sm);
+ background: color-mix(in oklab, var(--ds-error) 8%, transparent);
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm-plus);
+ line-height: var(--leading-body);
+}
+
+.lan-dialog-error {
+ margin: 0 20px 12px;
+}
+
+.lan-devices {
+ container-type: inline-size;
+ border-radius: var(--radius-md-plus);
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.lan-device + .lan-device {
+ border-block-start: 1px solid var(--ds-border-subtle);
+}
+
+
+.lan-device.is-request {
+ background: color-mix(in oklab, var(--ds-accent) 7%, var(--ds-tile));
+}
+
+.lan-device-actions,
+.lan-code-meta,
+.lan-grants-section-meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px 8px;
+}
+
+.lan-devices-empty {
+ display: flex;
+ min-height: 76px;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ padding: 16px;
+ border: 1px dashed var(--ds-border-default);
+ border-radius: inherit;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm-plus);
+ text-align: center;
+}
+
+.lan-devices-empty > svg {
+ flex: 0 0 auto;
+}
+
+@container (max-width: 380px) {
+ .lan-device {
+ grid-template-columns: auto minmax(0, 1fr);
+ }
+
+ .lan-device-actions {
+ grid-column: 2;
+ }
+}
+
+/* The shell keeps the title and actions visible while the contents scroll. */
+.overlay.lan-dialog-overlay {
+ padding: clamp(12px, 4vmin, 24px);
+}
+
+.dialog.lan-dialog {
+ display: flex;
+ flex-direction: column;
+ width: min(100%, 520px);
+ max-height: 100%;
+ padding: 0;
+ overflow: hidden;
+}
+
+.lan-dialog-head {
+ display: flex;
+ align-items: flex-start;
+ gap: 12px;
+ padding: 20px 20px 16px;
+}
+
+.lan-dialog-icon {
+ flex: 0 0 auto;
+}
+
+.lan-dialog-heading {
+ flex: 1;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.lan-dialog-title {
+ margin: 0;
+ color: var(--ds-text-primary);
+ font-size: var(--text-lg);
+ font-weight: var(--font-weight-semibold);
+ line-height: var(--leading-compact);
+}
+
+.lan-dialog-description {
+ margin: 4px 0 0;
+}
+
+.lan-dialog-close {
+ flex: 0 0 auto;
+}
+
+.lan-dialog button[aria-disabled="true"] {
+ opacity: 0.55;
+ cursor: default;
+}
+
+.lan-dialog-body {
+ min-height: 0;
+ padding: 4px 20px 20px;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ scroll-padding-block: 8px;
+}
+
+.lan-dialog-footer {
+ display: flex;
+ align-items: center;
+ justify-content: flex-end;
+ flex-wrap: wrap;
+ gap: 8px;
+ padding: 12px 20px;
+ border-top: 1px solid var(--ds-border-subtle);
+}
+
+.lan-dialog-footer-hint {
+ margin-inline-end: auto;
+}
+
+.lan-pair-steps {
+ display: grid;
+ gap: 20px;
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+.lan-pair-step {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: 10px;
+}
+
+.lan-pair-step-number {
+ display: grid;
+ width: 24px;
+ height: 24px;
+ place-items: center;
+ border-radius: var(--radius-full);
+ background: var(--ds-tile-deep);
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm-plus);
+ font-weight: var(--font-weight-semibold);
+}
+
+.lan-pair-step-body {
+ min-width: 0;
+}
+
+.lan-pair-step-title {
+ margin: 2px 0 8px;
+ color: var(--ds-text-primary);
+ font-size: var(--text-md);
+ font-weight: var(--font-weight-medium);
+}
+
+.lan-pair-url {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px 12px;
+ padding: 8px 10px 8px 12px;
+ border-radius: var(--radius-md);
+ background: var(--ds-tile);
+}
+
+.lan-pair-url-text {
+ min-width: 0;
+}
+
+.lan-code {
+ display: grid;
+ grid-template-columns: repeat(6, minmax(0, 1fr));
+ gap: clamp(3px, 1vw, 8px);
+ max-width: 22rem;
+}
+
+.lan-code-digit {
+ display: grid;
+ min-height: 44px;
+ place-items: center;
+ padding-block: 4px;
+ border: 1px solid var(--ds-border-default);
+ border-radius: var(--radius-md);
+ background: var(--ds-tile);
+ color: var(--ds-text-primary);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xl);
+ font-weight: var(--font-weight-semibold);
+ line-height: var(--leading-tight);
+ font-variant-numeric: tabular-nums;
+ user-select: text;
+}
+
+.lan-code.is-expired .lan-code-digit {
+ color: var(--ds-text-secondary);
+}
+
+.lan-code-meta {
+ justify-content: space-between;
+ gap: 2px 8px;
+ max-width: 22rem;
+ margin-top: 4px;
+ font-variant-numeric: tabular-nums;
+}
+
+.lan-pair-waiting {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 auto 0 0;
+}
+
+.lan-pair-waiting-dot {
+ width: 7px;
+ height: 7px;
+ flex: 0 0 auto;
+ border-radius: var(--radius-full);
+ background: var(--ds-success);
+}
+
+.lan-grants {
+ display: grid;
+ gap: 16px;
+}
+
+.lan-grants-section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 4px 8px;
+ margin-bottom: 6px;
+}
+
+.lan-grants-section-title {
+ margin: 0;
+ color: var(--ds-text-primary);
+ font-size: var(--text-md);
+ font-weight: var(--font-weight-semibold);
+}
+
+.lan-grants-section-meta {
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+
+.lan-grants-list {
+ display: grid;
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-md-plus);
+ background: var(--ds-tile);
+}
+
+/* Keep one scroll region in the dialog; even long project lists share it. */
+.lan-grants-list > :not(:first-child) {
+ border-top: 1px solid var(--ds-border-subtle);
+}
+
+.lan-grants-option.ui-checkbox,
+.lan-grants-empty,
+.lan-grants-fixed {
+ min-height: 40px;
+ padding: 9px 12px;
+}
+
+.lan-grants-option.ui-checkbox {
+ gap: 10px;
+}
+
+.lan-grants-option.ui-checkbox:has(input:checked) {
+ background: color-mix(in oklab, var(--ds-accent) 7%, transparent);
+}
+
+.lan-grants-option.ui-checkbox:hover:not(:has(input:disabled)) {
+ background: var(--ds-tile-hover);
+}
+
+.lan-grants-option-copy {
+ display: grid;
+ gap: 2px;
+}
+
+.lan-grants-option-label {
+ color: var(--ds-text-primary);
+ font-size: var(--text-sm-plus);
+}
+
+.lan-grants-option.ui-checkbox.lan-grants-option-separate {
+ border-top: 1px solid var(--ds-border-default);
+}
+
+.lan-grants-empty {
+ margin: 0;
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm-plus);
+}
+
+.lan-grants-fixed,
+.lan-grants-note {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin: 0;
+}
+
+.lan-grants-fixed > svg,
+.lan-grants-note > svg {
+ flex: 0 0 auto;
+ color: var(--ds-text-secondary);
+}
diff --git a/apps/desktop/test/helpers/lan-webui-fixture.mjs b/apps/desktop/test/helpers/lan-webui-fixture.mjs
index bb7510da1..fd10bd968 100644
--- a/apps/desktop/test/helpers/lan-webui-fixture.mjs
+++ b/apps/desktop/test/helpers/lan-webui-fixture.mjs
@@ -110,9 +110,10 @@ export function desktop() {
export function browser(origin) {
const jar = new Map();
let csrf = "";
+ const cookie = () => [...jar].map(([key, value]) => `${key}=${value}`).join("; ");
const request = async (method, path, body, extra = {}) => {
const headers = { Accept: "application/json", ...extra };
- if (jar.size) headers.Cookie = [...jar].map(([k, v]) => `${k}=${v}`).join("; ");
+ if (jar.size) headers.Cookie = cookie();
if (method === "POST") {
headers["Content-Type"] = "application/json";
if (csrf && !("X-CSRF-Token" in extra)) headers["X-CSRF-Token"] = csrf;
@@ -129,6 +130,7 @@ export function browser(origin) {
};
return {
request,
+ events: (path, signal) => fetch(`${origin}${path}`, { headers: { Cookie: cookie() }, signal }),
async signIn() {
const me = await request("GET", "/v1/me");
csrf = me.body.csrf;
diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
index 924dc7ed0..b6972440a 100644
--- a/apps/desktop/test/lan-webui-browser-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
@@ -1,5 +1,6 @@
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
+import { once } from "node:events";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
@@ -80,7 +81,29 @@ const journey = String.raw`(async () => {
return JSON.stringify(result);
})()`;
-test("a phone pairs, organizes, creates and sends through the real page", { timeout: 60_000 }, async (t) => {
+const afterGrantEdit = String.raw`(async () => {
+ const waitForRow = async (label) => {
+ const deadline = performance.now() + 10_000;
+ while (performance.now() < deadline) {
+ const row = [...document.querySelectorAll(".row")].find((item) => item.querySelector(".row-title")?.textContent === label);
+ if (row) return row;
+ await new Promise(requestAnimationFrame);
+ }
+ throw new Error("Missing row after grant edit: " + label);
+ };
+ const project = await waitForRow("Beta");
+ const projectTitles = [...document.querySelectorAll(".row-title")].map((item) => item.textContent);
+ project.querySelector(".row-main").click();
+ const session = await waitForRow("Second root chat");
+ return {
+ projectTitles,
+ canOrganize: Boolean(session.querySelector(".row-more")),
+ canCreate: Boolean(document.querySelector("main > button.primary")),
+ pairingShown: Boolean(document.getElementById("pair-code")),
+ };
+})()`;
+
+test("a phone pairs, organizes, chats and follows updated grants through the real page", { timeout: 60_000 }, async (t) => {
const { electronBinary } = resolveElectronBinary();
const fake = desktop();
const server = createLanServer({ handler: fake.workspace, assets: await assets() });
@@ -102,6 +125,7 @@ test("a phone pairs, organizes, creates and sends through the real page", { time
await writeFile(join(temp, "main.cjs"), `
const { app, BrowserWindow } = require("electron");
const path = require("node:path");
+const { once } = require("node:events");
app.setPath("userData", path.join(__dirname, "profile"));
app.whenReady().then(async () => {
const window = new BrowserWindow({ show: false, width: 390, height: 844, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
@@ -109,7 +133,11 @@ app.whenReady().then(async () => {
await window.loadURL(${JSON.stringify(`http://127.0.0.1:${port}/`)});
await window.webContents.executeJavaScript("window.__code = ${code};");
const output = await window.webContents.executeJavaScript(${JSON.stringify(journey)});
- process.stdout.write("RESULT " + output + "\\n");
+ const edited = once(process.stdin, "data");
+ process.stdout.write("EDIT_GRANTS\\n");
+ await edited;
+ const afterEdit = await window.webContents.executeJavaScript(${JSON.stringify(afterGrantEdit)});
+ process.stdout.write("RESULT " + JSON.stringify({ ...JSON.parse(output), afterEdit }) + "\\n");
app.exit(0);
} catch (error) {
process.stderr.write(String(error && error.stack || error) + "\\n");
@@ -117,12 +145,22 @@ app.whenReady().then(async () => {
}
});
`);
- const child = spawn(electronBinary, [join(temp, "main.cjs")], { env: { ...process.env, ELECTRON_ENABLE_LOGGING: "0" } });
+ const env = { ...process.env, ELECTRON_ENABLE_LOGGING: "0" };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, signal: t.signal });
let stdout = "";
let stderr = "";
- child.stdout.on("data", (chunk) => (stdout += chunk));
+ let edited = false;
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ if (edited || !stdout.includes("EDIT_GRANTS\n")) return;
+ edited = true;
+ const [device] = server.devices();
+ if (device) server.update(device.id, { projectIds: ["g-b"], temporary: false, chat: false, organize: false });
+ child.stdin.end("updated");
+ });
child.stderr.on("data", (chunk) => (stderr += chunk));
- const exitCode = await new Promise((resolve) => child.on("close", resolve));
+ const [exitCode] = await once(child, "close");
assert.equal(exitCode, 0, stderr);
const line = stdout.split("\n").find((entry) => entry.startsWith("RESULT "));
assert.ok(line, stdout + stderr);
@@ -143,4 +181,5 @@ app.whenReady().then(async () => {
assert.equal(result.horizontalScroll, false);
assert.equal(result.smallTargets, 0);
assert.equal(result.backHash, "#/p/g-a");
+ assert.deepEqual(result.afterEdit, { projectTitles: ["Beta"], canOrganize: false, canCreate: false, pairingShown: false });
});
diff --git a/apps/desktop/test/lan-webui-settings-user-path.test.mjs b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
new file mode 100644
index 000000000..ee7f95dec
--- /dev/null
+++ b/apps/desktop/test/lan-webui-settings-user-path.test.mjs
@@ -0,0 +1,272 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { once } from "node:events";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { createRequire } from "node:module";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const appDir = join(root, "apps/desktop");
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+const fixture = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { SystemSettings } from "./src/features/settings/pages/SystemSettings";
+import { lanEn, lanZh } from "./src/locales/lan";
+import "./src/styles/tokens.css";
+import "./src/styles/base.css";
+import "./src/styles/ui-kit.css";
+import "./src/styles/settings.css";
+import "./src/styles/lan-webui.css";
+
+const admin = "pi-desktop/lan-webui/admin";
+const changed = "pi-desktop/lan-webui/changed";
+const listeners = new Set();
+const writes = [];
+const copied = [];
+const view = {
+ running: false, origin: null, address: null, port: null, code: null, pending: [], devices: [], error: null,
+ interfaces: [{ address: "192.168.1.20", name: "Wi-Fi" }],
+ projects: [{ id: "alpha", label: "Alpha" }, { id: "beta", label: "Beta" }],
+};
+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 }) });
+
+window.piDesktop = {
+ platform: "darwin",
+ on(channel, listener) {
+ if (channel !== changed) return () => {};
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ async invoke(channel, action) {
+ if (channel !== admin) return { ok: true, data: null };
+ if (action.kind === "state") {
+ if (++stateReads === 1) throw new Error("Desktop temporarily unavailable");
+ return snapshot();
+ }
+ writes.push(action);
+ switch (action.kind) {
+ case "start":
+ if (startFails) {
+ startFails = false;
+ 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 });
+ break;
+ case "issueCode":
+ issueCount++;
+ view.code = { value: ["000012", "134209", "512309"][issueCount - 1], expiresAt: Date.now() + (issueCount === 1 ? -1000 : 300_000) };
+ break;
+ case "confirm": {
+ const request = view.pending.find((item) => item.id === action.id);
+ view.pending = view.pending.filter((item) => item.id !== action.id);
+ view.devices.push({ id: "device", label: request.label, grants: action.grants, lastActiveAt: Date.now() });
+ break;
+ }
+ case "update":
+ view.devices.find((item) => item.id === action.id).grants = action.grants;
+ break;
+ case "deny":
+ view.pending = view.pending.filter((item) => item.id !== action.id);
+ break;
+ case "revoke":
+ 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, pending: [], devices: [] });
+ break;
+ default:
+ throw new Error("Unexpected LAN action: " + action.kind);
+ }
+ emit();
+ return snapshot();
+ },
+};
+Object.defineProperty(navigator, "clipboard", { value: { async writeText(text) { copied.push(text); } } });
+
+await i18n.use(initReactI18next).init({
+ lng: "en", fallbackLng: "en", interpolation: { escapeValue: false },
+ resources: { en: { translation: flattenCatalog(catalogs.en), lan: lanEn }, "zh-CN": { lan: lanZh } },
+});
+const rootNode = createRoot(document.getElementById("root"));
+rootNode.render(<SystemSettings settings={{}} saveSettings={async () => {}} platform="darwin" />);
+
+const frame = () => new Promise(requestAnimationFrame);
+async function wait(fn, label) {
+ for (let i = 0; i < 180; i++) {
+ const value = fn();
+ if (value) return value;
+ await frame();
+ }
+ throw new Error("Timed out: " + label);
+}
+const check = (condition, label) => { if (!condition) throw new Error(label); };
+const q = (selector, node = document) => node?.querySelector(selector);
+const section = () => [...document.querySelectorAll(".settings-card-block")].find((card) => q("h3", card)?.textContent === lanEn.title);
+const button = (name, node = document) => [...(node?.querySelectorAll("button") ?? [])].find((el) => el.textContent.trim() === name);
+const dialog = () => q(".lan-dialog[role=dialog]");
+const title = () => q("h2", dialog())?.textContent;
+const toggle = () => q('[role="switch"][aria-label="Allow LAN connections"]');
+const field = () => q('input[aria-label="Port"]');
+const alert = () => q('[role="alert"]', section())?.textContent;
+const checkbox = (name) => [...dialog().querySelectorAll("label")].find((label) => label.textContent.startsWith(name)).querySelector("input");
+const click = (element) => { check(element && !element.disabled, "Missing or disabled control"); element.focus(); element.click(); };
+const press = (key, shiftKey = false) => document.activeElement.dispatchEvent(new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true }));
+const input = (value) => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(field(), value);
+ field().dispatchEvent(new Event("input", { bubbles: true }));
+};
+function fitsDialog() {
+ const node = dialog();
+ const bounds = node.getBoundingClientRect();
+ const body = q(".lan-dialog-body", node);
+ return bounds.left >= 0 && bounds.right <= innerWidth && bounds.top >= 0 && bounds.bottom <= innerHeight
+ && body.scrollWidth <= body.clientWidth + 1 && getComputedStyle(body).overflowY === "auto";
+}
+
+window.lanSettingsProbe = async () => {
+ await wait(() => button(lanEn.retry, section()), "state error and Retry");
+ click(button(lanEn.retry, section()));
+ await wait(() => toggle() && !toggle().disabled, "initial state");
+ check(toggle().getAttribute("aria-checked") === "false" && !button(lanEn.addDevice), "service starts off");
+
+ input("1");
+ await frame();
+ click(toggle());
+ await wait(() => alert() === lanEn.errors.INVALID_PORT, "invalid port");
+ check(field().getAttribute("aria-invalid") === "true" && writes.length === 0, "client validation before start");
+ input("38180");
+ await frame();
+ click(toggle());
+ await wait(() => alert() === lanEn.errors.PORT_IN_USE && stateReads >= 3, "start error survives a state refresh");
+ click(toggle());
+ await wait(() => toggle().getAttribute("aria-checked") === "true" && button(lanEn.addDevice), "listener started");
+ check(!field() && !alert() && q(".lan-address-url").textContent === view.origin, "connection status shows copyable address");
+ click(button(lanEn.copy));
+ await wait(() => button(lanEn.copied), "clipboard feedback");
+
+ view.pending.push({ id: "old", label: "Other phone", createdAt: Date.now() });
+ emit();
+ await wait(() => button(lanEn.review), "pending request from Main");
+ click(button(lanEn.addDevice));
+ await wait(() => title() === lanEn.pairTitle && dialog().textContent.includes(lanEn.codeExpired), "expired pairing code");
+ check(fitsDialog(), "pairing fits a narrow dark window");
+ click(button(lanEn.newCode, dialog()));
+ await wait(() => q(".lan-code")?.textContent === "134209", "replacement code");
+ await wait(() => dialog().contains(document.activeElement), "focus in pair dialog");
+ press("Escape");
+ await wait(() => !dialog() && document.activeElement === button(lanEn.addDevice), "Escape returns focus");
+ click(button(lanEn.addDevice));
+ await wait(() => q(".lan-code")?.textContent === "512309", "fresh code when opened again");
+ view.pending.push({ id: "phone", label: "iPhone", createdAt: Date.now() });
+ view.code = null;
+ emit();
+ await wait(() => title() === "Allow iPhone?", "new request advances directly to approval");
+ await wait(() => dialog().contains(document.activeElement), "focus moves into approval");
+ check(button(lanEn.allow, dialog()).disabled && !checkbox("Alpha").checked && !checkbox("Beta").checked, "no project preselected");
+ q(".lan-dialog-close", dialog()).focus();
+ check(!press("Tab", true) && document.activeElement === button(lanEn.deny, dialog()), "Shift+Tab stays in the approval dialog");
+ click(button(lanEn.selectAll, dialog()));
+ await wait(() => checkbox("Alpha").checked && checkbox("Beta").checked, "select all");
+ click(button(lanEn.selectNone, dialog()));
+ await wait(() => button(lanEn.allow, dialog()).disabled, "clear selection");
+ click(checkbox("Alpha"));
+ await wait(() => !button(lanEn.allow, dialog()).disabled, "selected scope enables approval");
+ click(button(lanEn.allow, dialog()));
+ await wait(() => !dialog() && button(lanEn.permissions) && document.activeElement === button(lanEn.addDevice), "paired device row and restored focus");
+
+ document.documentElement.dataset.theme = "light";
+ click(button(lanEn.permissions));
+ await wait(() => title() === "iPhone permissions", "edit device");
+ check(checkbox("Alpha").checked && !checkbox("Beta").checked && fitsDialog(), "permissions load and fit in a narrow light window");
+ click(checkbox("Alpha"));
+ click(checkbox("Beta"));
+ click(checkbox(lanEn.chat));
+ click(checkbox(lanEn.organize));
+ await wait(() => !button(lanEn.save, dialog()).disabled && !checkbox(lanEn.chat).checked, "view-only edit");
+ click(button(lanEn.save, dialog()));
+ await wait(() => !dialog() && q(".lan-device:not(.is-request)")?.textContent.includes(lanEn.viewOnly), "device updates without re-pairing");
+ click(button(lanEn.deny, q(".lan-device.is-request")));
+ await wait(() => !q(".lan-device.is-request"), "deny pre-existing request");
+ click(button(lanEn.remove));
+ await wait(() => q(".lan-devices-empty")?.textContent === lanEn.noDevices, "device removed");
+ click(toggle());
+ await wait(() => toggle().getAttribute("aria-checked") === "false" && !button(lanEn.addDevice), "service stopped");
+ await i18n.changeLanguage("zh-CN");
+ await wait(() => q('[role="switch"][aria-label="允许局域网连接"]'), "Chinese LAN settings strings");
+ rootNode.unmount();
+ return { writes, copied, remainingListeners: listeners.size };
+};
+`;
+
+test("Desktop Settings starts, pairs, edits and removes a LAN device", {
+ timeout: 60_000,
+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Isolated Electron test requires a display" : false,
+}, async (t) => {
+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "lan-settings-ui-"));
+ t.after(() => rm(temp, { recursive: true, force: true }));
+ await build({
+ stdin: { contents: fixture, resolveDir: appDir, sourcefile: "lan-settings-ui.tsx", loader: "tsx" },
+ outfile: join(temp, "fixture.js"),
+ bundle: true,
+ platform: "browser",
+ format: "esm",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: Object.fromEntries([
+ ["@pi-desktop/i18n", join(root, "packages/i18n/src")],
+ ...["react", "react-dom", "i18next", "react-i18next"].map((name) => [name, join(appDir, "node_modules", name)]),
+ ]),
+ });
+ await writeFile(join(temp, "index.html"), '<!doctype html><html lang="en" data-theme="dark"><meta charset="utf-8"><link rel="stylesheet" href="fixture.css"><div id="root"></div><script type="module" src="fixture.js"></script></html>');
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const { join } = require("node:path");
+app.setPath("userData", join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: false, useContentSize: true, width: 420, height: 520,
+ webPreferences: { sandbox: true, contextIsolation: true, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => { if (event.level === "error") console.error(event.message); });
+ try {
+ await win.loadFile(join(__dirname, "index.html"));
+ const result = await win.webContents.executeJavaScript("window.lanSettingsProbe()");
+ console.log("LAN_SETTINGS " + JSON.stringify(result));
+ app.exit(0);
+ } catch (error) { console.error(error.stack ?? error); app.exit(1); }
+});
+`);
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, signal: t.signal });
+ let output = "";
+ child.stdout.on("data", (chunk) => { output += chunk; });
+ child.stderr.on("data", (chunk) => { output += chunk; });
+ const [code] = await once(child, "close");
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((value) => value.startsWith("LAN_SETTINGS "));
+ assert.ok(line, output.slice(-6000));
+ assert.deepEqual(JSON.parse(line.slice("LAN_SETTINGS ".length)), {
+ writes: [
+ { 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: "confirm", id: "phone", grants: { projectIds: ["alpha"], temporary: false, chat: true, organize: true } },
+ { kind: "update", id: "device", grants: { projectIds: ["beta"], temporary: false, chat: false, organize: false } },
+ { kind: "deny", id: "old" }, { kind: "revoke", id: "device" }, { kind: "stop" },
+ ],
+ copied: ["http://192.168.1.20:38180"],
+ 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 15f56d669..d4e83017a 100644
--- a/apps/desktop/test/lan-webui-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-user-path.test.mjs
@@ -3,9 +3,9 @@ import test from "node:test";
import { request } from "node:http";
import { browser, createLanServer, desktop } from "./helpers/lan-webui-fixture.mjs";
-async function setup(t, grants) {
+async function setup(t, grants, wrapHandler = (workspace) => workspace) {
const fake = desktop();
- const server = createLanServer({ handler: fake.workspace, assets: new Map([["/index.html", { type: "text/html", body: "<p>ok</p>" }]]) });
+ const server = createLanServer({ handler: wrapHandler(fake.workspace), assets: new Map([["/index.html", { type: "text/html", body: "<p>ok</p>" }]]) });
const { port } = await server.start("127.0.0.1", 0);
t.after(async () => {
await server.stop();
@@ -151,3 +151,46 @@ test("temporary conversations need their own grant", async (t) => {
assert.equal(created.status, 200);
assert.deepEqual(calls.find(([c]) => c === "create")[1], [{}], "no project is inherited");
});
+
+test("editing a device applies the new grants without returning data from the old scope", { timeout: 10_000 }, async (t) => {
+ const prepared = Promise.withResolvers();
+ const release = Promise.withResolvers();
+ t.after(() => release.resolve());
+ const { phone, server, calls } = await setup(t, {
+ projectIds: ["g-a", "g-b"], temporary: false, chat: true, organize: true,
+ }, (workspace) => ({
+ ...workspace,
+ async handle(request, key) {
+ const result = await workspace.handle(request, key);
+ if (request.path === "/v1/sessions/s-a1") {
+ prepared.resolve();
+ await release.promise;
+ }
+ return result;
+ },
+ }));
+ const id = server.devices()[0].id;
+ assert.throws(() => server.update(id, { projectIds: [], temporary: false, chat: true, organize: true }), { code: "INVALID_SCOPE" });
+ const mutation = { "Idempotency-Key": "device-edit-create" };
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, mutation)).status, 200);
+ const stream = await phone.events("/v1/sessions/s-a1/events", t.signal);
+ assert.equal(stream.status, 200);
+ const reader = stream.body.getReader();
+ assert.equal((await reader.read()).done, false);
+ const inFlight = phone.request("GET", "/v1/sessions/s-a1");
+ await prepared.promise;
+
+ server.update(id, { projectIds: ["g-b"], temporary: false, chat: false, organize: false });
+ release.resolve();
+ assert.deepEqual(await inFlight, { status: 409, body: { code: "CONFLICT" } });
+ assert.equal((await reader.read()).done, true, "editing grants closes the subscribed stream");
+ assert.equal((await phone.events("/v1/sessions/s-a1/events", t.signal)).status, 404);
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, mutation)).status, 409);
+ assert.equal(calls.filter(([channel]) => channel === "create").length, 1);
+
+ const me = await phone.request("GET", "/v1/me");
+ assert.deepEqual(me.body.access, { deviceId: id, projectIds: ["g-b"], temporary: false, chat: false, organize: false });
+ assert.deepEqual((await phone.request("GET", "/v1/projects")).body.items.map((project) => project.id), ["g-b"]);
+ assert.equal((await phone.request("GET", "/v1/sessions/s-a1")).status, 404);
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-b" })).status, 403);
+});
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
index 0061d6a96..b715d1f8f 100644
--- a/docs/spec/01-product/03-lan-webui-mvp.md
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -44,17 +44,22 @@ numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remo
rebinding) or whose `Origin` is foreign, requires a CSRF token on every
authenticated mutation, and serves a restrictive CSP. Adding HTTPS later must
not change the browser API.
-3. Desktop displays the copyable address and, on request, a 6-digit one-time
- code. Enter it on the page; Desktop then lists the pending device by its
- label. No catalog or history is sent until the user confirms locally and
- chooses the grants and scopes below. Each code is valid for at most five
- minutes and a single device; five failed attempts invalidate it. A browser
- cannot request a fresh code. A QR code of the origin is deferred.
-4. In the same settings section show paired device label, last activity, scopes,
- and **Revoke** / **Turn off for all devices**. The browser has **Disconnect
- this device** (sign out), distinct from closing the tab. Revocation or sign-out
- invalidates its cookie and live streams. Turning off closes the listener and
- invalidates all WebUI grants; turning it back on requires fresh pairing.
+3. Once the listener is on, the connection card shows a copyable address and
+ the Devices card shows pending requests and paired devices. **Add device**
+ opens a two-step dialog with the address, one-time 6-digit code and expiry.
+ A new request while the dialog is open advances it to the grant review;
+ requests already waiting can be reviewed or denied from the Devices card.
+ No catalog or history is sent until the user confirms locally and chooses
+ at least one project or Temporary scope. Each code lasts at most five
+ minutes, is single-use, and expires after five failed attempts. Only the
+ Desktop can generate a replacement code. A QR code is deferred.
+4. Device rows show the label, last activity and access summary. **Permissions**
+ edits scopes and actions without pairing again. The listener closes existing
+ streams and does not return pending or cached results under the old grants.
+ The browser refetches its access and view when it reconnects. **Remove** and
+ browser sign-out invalidate that device's cookie and streams. Turning off
+ closes the listener and invalidates every pairing; turning it back on
+ requires fresh pairing. 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 is not a stop or approval command. Locking the
computer grants no new authority: new pairing and manual approvals still
@@ -70,6 +75,11 @@ unable to reach the Host cannot diagnose why; offer the address and local
network checks, not a false claim that the desktop quit. Never open firewall or
router ports, use UPnP, or set up a tunnel automatically.
+Desktop administration stays on the main-window-only LAN admin IPC channel.
+The `update` action replaces grants for an existing device; the payload-free
+`lanWebUiChanged` event asks the renderer to refetch after listener, pairing or
+device changes. Neither is available through the browser API.
+
## 3. Projects and sessions (W02, W03)
| Surface | Required behavior |
@@ -266,21 +276,22 @@ is part of this product increment.
Code: `apps/desktop/electron/main/lan-webui/` (listener, pairing, scope checks,
workspace edge, organization owner), `apps/desktop/resources/lan-webui/` (phone
-page), `apps/desktop/src/components/settings/LanWebUiSection.tsx` (Desktop
+page), `apps/desktop/src/features/lan-webui/LanWebUiSection.tsx` (Desktop
settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`
(applies browser edits to the open Desktop sidebar without navigating).
| Area | Delivered | Not yet |
|---|---|---|
-| W01 | Off by default; interface + port; one-time code; Desktop confirm with grants; revoke; sign out; stop signs everyone out | QR code; HTTPS (deliberately deferred) |
+| W01 | Off by default; interface + port; guided pairing with local grant review; edit or remove devices; sign out; stop signs everyone out | QR code; HTTPS (deliberately deferred) |
| W02/W03 | Shared-project and temporary scopes; 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) |
-| W06 | Non-owner principal under the remote `ask` ceiling; plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry |
+| W06 | Non-owner principal under the remote `ask` ceiling; plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry; canceling already queued work on scope loss |
| W07 | Phone-first layout, 44 px targets, English and Simplified Chinese, IME-safe Enter | Screen-reader and large-catalog qualification |
| 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-user-path.test.mjs` (real HTTP listener, fake Desktop) and
+`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).
+the shipped page), and `lan-webui-settings-user-path.test.mjs` (Desktop System
+settings in isolated Electron, with a fixture preload boundary).
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index bc21a3614..c7007cf44 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -762,16 +762,18 @@ user's running instance.
- **Preconditions:** Fresh Desktop profile with projects A and B; a real phone
on the selected private LAN. Repeat on iOS Safari and Android Chrome.
-- **Steps:** Check the initial listener state. Choose the interface and start;
- open the shown `http://` address on the phone, show a code on Desktop, enter
- it, and confirm access to A on Desktop. Close/reopen the tab; hide Desktop;
- then stop the service, quit and relaunch Desktop.
+- **Steps:** Choose the interface and start. Open **Add device**, copy the shown
+ `http://` address, and enter the displayed code on the phone. In the review
+ dialog, select A and allow the request. Open and close the dialog with the
+ keyboard, regenerate an expired code, and deny a separate waiting request.
+ Close/reopen the tab, hide Desktop, then stop, quit and relaunch Desktop.
- **Expected:** No listener by default and no project data before confirmation.
- The paired device sees A only; an expired, reused or five-times-wrong code
- fails. Hiding Desktop/closing the tab does not sign out. Stopping closes
- streams, invalidates cookies and releases the port; after relaunch the
- service is off, and a new start requires new pairing. An occupied port or
- isolated Wi-Fi produces actionable guidance, not a silent rebind.
+ A new request advances to review without polling or user refresh. The
+ approval action requires a scope; the paired device sees A only. An expired,
+ reused or five-times-wrong code fails. Hiding Desktop/closing the tab does not
+ sign out. Stopping closes streams, invalidates cookies and releases the port;
+ restarting requires pairing again. An occupied port or isolated Wi-Fi
+ produces actionable guidance, not a silent rebind.
- **Acceptance:** A, E; W01, W06.
### E2E-270: Organize projects and sessions without stealing navigation
@@ -850,15 +852,18 @@ user's running instance.
clock, a second interface and an allowed and a disallowed browser origin.
- **Steps:** Exercise catalog, deep links, history, search/counts, commands and
SSE with those identities. Check wrong Origin/Host, absent CSRF, expired
- cookies, pairing throttles and rejected admin/owner operations. Remove A
- while a stream, a queued turn and an in-flight catalog request exist. Sign
- out/revoke devices and change the desktop network. Inspect fixture logs/cache.
+ cookies, pairing throttles and rejected admin/owner operations. In **Permissions**,
+ replace A with B and switch to View only while a stream, a queued turn and an
+ in-flight catalog request exist. Remove the device and change the desktop
+ network. Inspect fixture logs/cache.
- **Expected:** No out-of-scope metadata, events or writes, even for known IDs;
View cannot mutate. No generic owner/SSH exemption or raw RPC, no leaked
- credentials/content in logs or persistent browser caches. Lost scope closes
- affected streams and cancels its pending queued work; an old cookie or late
- response cannot recover it. Expiry is not extended by a heartbeat. No
- connection on other interfaces or automatic sharing on the new network.
+ credentials/content in logs or persistent browser caches. Permission edits
+ do not require re-pairing and the browser reflects the new access after
+ reconnecting. Lost scope closes affected streams and cancels its pending
+ queued work; a late or cached reply under the old grants cannot recover it.
+ Expiry is not extended by a heartbeat. No connection on other interfaces or
+ automatic sharing on the new network.
- **Acceptance:** D, E; W01, W02, W06.
### E2E-275: Preserve an existing desktop profile and disable cleanly
diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.ts
index e86bbde21..c3fd1b226 100644
--- a/packages/shared/src/lan-webui.ts
+++ b/packages/shared/src/lan-webui.ts
@@ -86,6 +86,8 @@ export type LanAdminAction =
| { kind: "state" | "stop" | "issueCode" }
| { kind: "start"; address: string; port: number }
| { kind: "confirm"; id: string; grants: LanGrants }
+ /** Change what an already paired device may see and do. */
+ | { kind: "update"; id: string; grants: LanGrants }
| { kind: "deny" | "revoke"; id: string }
/** The renderer applied organization patches up to `seq`. */
| { kind: "ack"; seq: number };
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index 744694174..2aac5339d 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -509,6 +509,8 @@ export const IPC = {
},
event: {
lanWebUiCatalogChanged: "pi-desktop/lan-webui/catalogChanged",
+ /** LAN WebUI listener, pairing or device list changed; refetch the admin view. */
+ lanWebUiChanged: "pi-desktop/lan-webui/changed",
pluginChanged: "pi-desktop/event/pluginChanged",
/** Progress of an install or update, while it is still running. */
pluginInstallProgress: "pi-desktop/plugin/event/installProgress",