Skip to content

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

feat(desktop): add LAN WebUI companion for the running desktop

vastsa3920f1e532cd
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 0209b8757..9079183ed 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -49,6 +49,8 @@ import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";
import type { createTaskbarUnreadBadge } from "../taskbar-unread-badge";
+import { registerLanWebUiIpc } from "../lan-webui/ipc";
+
export type RegisterIpcDependencies = {
isQuitting: () => boolean;
ipcMain: IpcMain;
@@ -586,9 +588,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
});
registerStartupAnimationIpc({ registrar, dataDir, stripWinLongPrefix });
-
-
- return async (channel: string, args: readonly unknown[] = []) => {
+ const invokeInternal = async (channel: string, args: readonly unknown[] = []) => {
const handler = ipcHandlers.get(channel);
if (!handler) {
throw Object.assign(new Error(`IPC channel is not available to external agents: ${channel}`), {
@@ -597,4 +597,25 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
}
return handler(...args);
};
+
+ registerLanWebUiIpc({
+ registrar,
+ dataDir,
+ sendToRenderer,
+ log: (level, message, data) => logger.app("runtime", level, message, data === undefined ? undefined : { data }),
+ workspace: {
+ getHost,
+ getBridge: () => getAgentHostBridge(),
+ invoke: (channel, args) => invokeInternal(channel, args),
+ channels: {
+ sessionCreate: IPC.invoke.sessionCreate,
+ sessionRename: IPC.invoke.sessionRename,
+ projectGroupRename: IPC.invoke.projectGroupRename,
+ agentAbort: IPC.invoke.agentAbort,
+ },
+ activeTurns,
+ },
+ });
+
+ return invokeInternal;
}
diff --git a/apps/desktop/electron/main/ipc/sidebar-preferences-ipc.ts b/apps/desktop/electron/main/ipc/sidebar-preferences-ipc.ts
index f82452d12..8ef8fada3 100644
--- a/apps/desktop/electron/main/ipc/sidebar-preferences-ipc.ts
+++ b/apps/desktop/electron/main/ipc/sidebar-preferences-ipc.ts
@@ -1,6 +1,7 @@
import { IPC } from "@pi-desktop/shared";
import type { IpcMainInvokeEvent } from "electron";
import { readSidebarBackup, writeSidebarBackup } from "../sidebar-preferences";
+import { getLanOrganization } from "../lan-webui/organization";
import type { IpcRegistrar } from "./types";
export function registerSidebarPreferencesIpc({ registrar, dataDir }: {
@@ -14,12 +15,16 @@ export function registerSidebarPreferencesIpc({ registrar, dataDir }: {
throw Object.assign(new Error("Sidebar preferences require the trusted Main top frame"), { errorCode: "PERMISSION_DENIED" });
}
};
+ // LAN WebUI organization edits not yet applied by the renderer are kept on
+ // top of every renderer snapshot, so a stale write cannot undo them.
+ const organization = getLanOrganization(dataDir);
registrar.handleWithEvent(IPC.invoke.sidebarPreferencesGet, async event => {
assertSender(event);
- return readSidebarBackup(dataDir);
+ return organization.overlay(readSidebarBackup(dataDir));
});
registrar.handleWithEvent(IPC.invoke.sidebarPreferencesSet, async (event, value: unknown) => {
assertSender(event);
- writeSidebarBackup(dataDir, value);
+ writeSidebarBackup(dataDir, organization.overlay(value));
+ organization.rendererWrote();
});
}
diff --git a/apps/desktop/electron/main/lan-webui/agent-tap.ts b/apps/desktop/electron/main/lan-webui/agent-tap.ts
new file mode 100644
index 000000000..7f0f033c4
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/agent-tap.ts
@@ -0,0 +1,22 @@
+import type { AgentEventEnvelope } from "@pi-desktop/shared";
+
+type Listener = (envelope: AgentEventEnvelope) => void;
+const listeners = new Set<Listener>();
+
+/** Fan out one renderer-bound agent event to the LAN WebUI, never throwing. */
+export function publishLanAgentEvent(envelope: AgentEventEnvelope): void {
+ for (const listener of listeners) {
+ try {
+ listener(envelope);
+ } catch {
+ // A browser-side observer must never disturb the desktop event stream.
+ }
+ }
+}
+
+export function onLanAgentEvent(listener: Listener): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+}
diff --git a/apps/desktop/electron/main/lan-webui/assets.ts b/apps/desktop/electron/main/lan-webui/assets.ts
new file mode 100644
index 000000000..b11f10783
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/assets.ts
@@ -0,0 +1,15 @@
+// Bundled into Main by Vite so the packaged app serves the same files.
+import indexHtml from "../../../resources/lan-webui/index.html?raw";
+import appJs from "../../../resources/lan-webui/app.js?raw";
+import stylesCss from "../../../resources/lan-webui/styles.css?raw";
+import localeJs from "../../../resources/lan-webui/locale.js?raw";
+import type { LanAsset } from "./server";
+
+export function lanWebUiAssets(): ReadonlyMap<string, LanAsset> {
+ return new Map<string, LanAsset>([
+ ["/index.html", { type: "text/html; charset=utf-8", body: indexHtml }],
+ ["/app.js", { type: "text/javascript; charset=utf-8", body: appJs }],
+ ["/locale.js", { type: "text/javascript; charset=utf-8", body: localeJs }],
+ ["/styles.css", { type: "text/css; charset=utf-8", body: stylesCss }],
+ ]);
+}
diff --git a/apps/desktop/electron/main/lan-webui/ipc.ts b/apps/desktop/electron/main/lan-webui/ipc.ts
new file mode 100644
index 000000000..6931aedee
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/ipc.ts
@@ -0,0 +1,30 @@
+import { IPC, type LanAdminAction } from "@pi-desktop/shared";
+import { onConfirmedQuit } from "../bootstrap/confirmed-quit";
+import type { IpcRegistrar } from "../ipc/types";
+import { lanWebUiAssets } from "./assets";
+import { createLanWebUiService } from "./service";
+import type { LanWorkspaceDeps } from "./workspace";
+
+/** Desktop-only administration of the LAN WebUI (Settings → System). */
+export function registerLanWebUiIpc(options: {
+ registrar: Pick<IpcRegistrar, "handleWithEvent" | "assertMainWindowSender">;
+ dataDir: string;
+ workspace: Omit<LanWorkspaceDeps, "organization" | "notifyDesktop">;
+ sendToRenderer(channel: string, payload: unknown): void;
+ log(level: "info" | "warn", message: string, data?: unknown): void;
+}): void {
+ const service = createLanWebUiService({
+ workspace: options.workspace,
+ dataDir: options.dataDir,
+ assets: lanWebUiAssets,
+ sendToRenderer: options.sendToRenderer,
+ log: options.log,
+ });
+ options.registrar.handleWithEvent(IPC.invoke.lanWebUiAdmin, async (event, action: LanAdminAction) => {
+ options.registrar.assertMainWindowSender(event);
+ return service.admin(action);
+ });
+ onConfirmedQuit(() => {
+ void service.dispose();
+ });
+}
diff --git a/apps/desktop/electron/main/lan-webui/organization.ts b/apps/desktop/electron/main/lan-webui/organization.ts
new file mode 100644
index 000000000..42cc30bee
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/organization.ts
@@ -0,0 +1,117 @@
+import type { LanCatalogChangedEvent, LanOrganizationPatch } from "@pi-desktop/shared";
+import { readSidebarBackup, writeSidebarBackup } from "../sidebar-preferences";
+
+export type LanProjectMeta = { name?: string; pinned?: boolean; archived?: boolean };
+export type LanSessionMeta = { pinned?: boolean; archived?: boolean; manualTitle?: boolean };
+export type LanMeta = {
+ projectMeta: Record<string, LanProjectMeta>;
+ sessionMeta: Record<string, LanSessionMeta>;
+};
+type SidebarRecord = Record<string, unknown> & {
+ projectMeta: Record<string, Record<string, unknown>>;
+ sessionMeta: Record<string, Record<string, unknown>>;
+};
+
+/** Same normalization as the renderer's sidebar preferences, keyed by path. */
+export function normalizeProjectKey(path: string): string {
+ let value = path.trim().replace(/\\/g, "/");
+ if (/^\/\/\?\/[A-Za-z]:\//.test(value)) value = value.slice(4);
+ value = value.replace(/(?<![A-Za-z]:)\/+$/, "");
+ return value || "/";
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === "object" && !Array.isArray(value);
+}
+
+function applyPatch(target: SidebarRecord, entry: LanOrganizationPatch): void {
+ const bucket = entry.kind === "project" ? target.projectMeta : target.sessionMeta;
+ const key = entry.kind === "project" ? normalizeProjectKey(entry.key) : entry.key;
+ bucket[key] = { ...(isRecord(bucket[key]) ? bucket[key] : {}), ...entry.patch };
+}
+
+/**
+ * Browser-originated organization edits share the Desktop sidebar backup as
+ * their only durable store. The renderer mirrors whole snapshots into that
+ * file, so an edit is kept "pending" and re-applied onto every renderer write
+ * until the renderer acknowledges it has applied the change. IPC from one
+ * renderer is ordered, so a write sent before the acknowledgement may be stale;
+ * a write after it already contains the edit.
+ */
+export function createLanOrganization(options: {
+ dataDir: string;
+ notify?: (event: LanCatalogChangedEvent) => void;
+}) {
+ let seq = 0;
+ const pending: Array<{ seq: number; entry: LanOrganizationPatch }> = [];
+ const writeListeners = new Set<() => void>();
+ let notify = options.notify;
+
+ const backup = (): SidebarRecord | null => {
+ let value: unknown;
+ try {
+ value = readSidebarBackup(options.dataDir);
+ } catch {
+ return null; // A damaged backup is never replaced from here.
+ }
+ if (!isRecord(value) || !isRecord(value.projectMeta) || !isRecord(value.sessionMeta)) return null;
+ return structuredClone(value) as SidebarRecord;
+ };
+
+ const overlay = <T>(value: T): T => {
+ if (!pending.length || !isRecord(value) || !isRecord(value.projectMeta) || !isRecord(value.sessionMeta)) return value;
+ const next = structuredClone(value) as unknown as SidebarRecord;
+ for (const { entry } of pending) applyPatch(next, entry);
+ return next as unknown as T;
+ };
+
+ return {
+ setNotifier(next: (event: LanCatalogChangedEvent) => void) {
+ notify = next;
+ },
+ /** Desktop wrote its sidebar snapshot (organization may have changed). */
+ onRendererWrite(listener: () => void): () => void {
+ writeListeners.add(listener);
+ return () => {
+ writeListeners.delete(listener);
+ };
+ },
+ rendererWrote(): void {
+ for (const listener of writeListeners) listener();
+ },
+ read(): LanMeta {
+ const base = backup() ?? { projectMeta: {}, sessionMeta: {} };
+ const merged = overlay(base);
+ return { projectMeta: merged.projectMeta as LanMeta["projectMeta"], sessionMeta: merged.sessionMeta as LanMeta["sessionMeta"] };
+ },
+ patch(entry: LanOrganizationPatch): void {
+ const next = ++seq;
+ pending.push({ seq: next, entry });
+ const current = backup();
+ if (current) {
+ applyPatch(current, entry);
+ writeSidebarBackup(options.dataDir, current);
+ }
+ notify?.({ seq: next, patches: [entry] });
+ },
+ /** Applied to every trusted renderer write before it reaches disk. */
+ overlay,
+ ack(upTo: number): void {
+ while (pending.length && pending[0]!.seq <= upTo) pending.shift();
+ },
+ pendingCount: () => pending.length,
+ };
+}
+
+export type LanOrganization = ReturnType<typeof createLanOrganization>;
+
+const instances = new Map<string, LanOrganization>();
+/** One organization owner per data directory (one Desktop install). */
+export function getLanOrganization(dataDir: string): LanOrganization {
+ let instance = instances.get(dataDir);
+ if (!instance) {
+ instance = createLanOrganization({ dataDir });
+ instances.set(dataDir, instance);
+ }
+ return instance;
+}
diff --git a/apps/desktop/electron/main/lan-webui/ports.ts b/apps/desktop/electron/main/lan-webui/ports.ts
new file mode 100644
index 000000000..334fe5163
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/ports.ts
@@ -0,0 +1,23 @@
+import type { LanAccess } from "@pi-desktop/shared";
+
+/** A safe, user-facing failure: only `status` and `code` reach the browser. */
+export class LanError extends Error {
+ readonly status: number;
+ readonly code: string;
+ constructor(status: number, code: string) {
+ super(code);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+/** An authenticated browser request after transport checks. */
+export interface LanRequest {
+ method: "GET" | "POST";
+ path: string;
+ query: URLSearchParams;
+ body: Record<string, unknown>;
+ access: LanAccess;
+}
+
+export type LanChange = { sessionId?: string };
diff --git a/apps/desktop/electron/main/lan-webui/server.ts b/apps/desktop/electron/main/lan-webui/server.ts
new file mode 100644
index 000000000..37922eb6a
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/server.ts
@@ -0,0 +1,395 @@
+import { randomBytes, randomInt, randomUUID, timingSafeEqual } from "node:crypto";
+import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
+import type { Socket } from "node:net";
+import type { LanAccess, LanDevice, LanGrants, LanPairing } from "@pi-desktop/shared";
+import { LanError, type LanChange, type LanRequest } from "./ports";
+
+export type LanAsset = { type: string; body: string };
+export type LanServerHandler = {
+ handle(request: LanRequest, key: string | null): Promise<unknown>;
+ subscribe(listener: (change: LanChange) => void): () => void;
+ mayReveal(access: LanAccess, sessionId: string): Promise<boolean>;
+};
+
+const CODE_TTL_MS = 5 * 60_000;
+const CODE_ATTEMPTS = 5;
+const PENDING_TTL_MS = 10 * 60_000;
+const MAX_PENDING = 8;
+const MAX_DEVICES = 16;
+const MAX_BODY = 300 * 1024;
+const MAX_IDEMPOTENT = 200;
+const HEARTBEAT_MS = 25_000;
+const LABEL_MAX = 60;
+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 Pending = LanPairing & { secret: string; deviceId: string | null };
+
+const secret = () => randomBytes(32).toString("base64url");
+const sameSecret = (a: string, b: string) => {
+ const left = Buffer.from(a);
+ const right = Buffer.from(b);
+ return left.length === right.length && timingSafeEqual(left, right);
+};
+
+function cookies(request: IncomingMessage): Map<string, string> {
+ const result = new Map<string, string>();
+ for (const part of (request.headers.cookie ?? "").split(";")) {
+ const index = part.indexOf("=");
+ if (index > 0) result.set(part.slice(0, index).trim(), part.slice(index + 1).trim());
+ }
+ return result;
+}
+
+function cookie(name: string, value: string, maxAgeSeconds: number): string {
+ return `${name}=${value}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${maxAgeSeconds}`;
+}
+
+function sendJson(response: ServerResponse, status: number, body: unknown, headers: Record<string, string | string[]> = {}) {
+ if (response.headersSent) return;
+ response.writeHead(status, {
+ "Content-Type": "application/json; charset=utf-8",
+ "Cache-Control": "no-store",
+ "X-Content-Type-Options": "nosniff",
+ ...headers,
+ });
+ response.end(JSON.stringify(body));
+}
+
+async function readBody(request: IncomingMessage): Promise<Record<string, unknown>> {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ for await (const chunk of request) {
+ const buffer = chunk as Buffer;
+ size += buffer.length;
+ if (size > MAX_BODY) throw new LanError(413, "PAYLOAD_TOO_LARGE");
+ chunks.push(buffer);
+ }
+ if (!size) return {};
+ if (!String(request.headers["content-type"] ?? "").startsWith("application/json")) {
+ throw new LanError(415, "UNSUPPORTED_MEDIA_TYPE");
+ }
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ } catch {
+ throw new LanError(400, "INVALID_ARGUMENT");
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new LanError(400, "INVALID_ARGUMENT");
+ return parsed as Record<string, unknown>;
+}
+
+/**
+ * Plain-HTTP LAN listener for the browser companion. It owns pairing, device
+ * credentials and the event stream; every data operation goes through the
+ * workspace handler, which re-checks the device's scope.
+ */
+export function createLanServer(options: {
+ handler: LanServerHandler;
+ assets: ReadonlyMap<string, LanAsset>;
+ onChange?: () => void;
+ now?: () => number;
+}) {
+ const now = options.now ?? Date.now;
+ let server: Server | null = null;
+ let host = "";
+ let code: { value: string; expiresAt: number; attempts: number } | null = null;
+ const pending = new Map<string, Pending>();
+ const devices = new Map<string, Device>();
+ const sockets = new Set<Socket>();
+ let unsubscribe: (() => void) | null = null;
+ let heartbeat: ReturnType<typeof setInterval> | null = null;
+
+ const changed = () => options.onChange?.();
+
+ const deviceFor = (request: IncomingMessage): Device | null => {
+ const token = cookies(request).get(SESSION_COOKIE);
+ if (!token) return null;
+ for (const device of devices.values()) if (sameSecret(device.token, token)) return device;
+ return null;
+ };
+
+ const access = (device: Device): LanAccess => ({ deviceId: device.id, ...device.grants });
+
+ /** DNS rebinding and cross-site request guard; not a TLS check. */
+ const sameOrigin = (request: IncomingMessage) => {
+ if (request.headers.host !== host) return false;
+ const origin = request.headers.origin;
+ return origin === undefined || origin === `http://${host}`;
+ };
+
+ function closeStreams(device: Device) {
+ for (const stream of device.streams) stream.end();
+ device.streams.clear();
+ }
+
+ function prune() {
+ const time = now();
+ if (code && code.expiresAt <= time) code = null;
+ for (const [id, entry] of pending) if (time - entry.createdAt > PENDING_TTL_MS) pending.delete(id);
+ }
+
+ async function pair(request: IncomingMessage, response: ServerResponse) {
+ prune();
+ const body = await readBody(request);
+ 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();
+ throw new LanError(403, "PAIRING_FAILED");
+ }
+ if (pending.size >= MAX_PENDING) throw new LanError(429, "RATE_LIMITED");
+ code = null; // single use
+ const entry: Pending = { id: randomUUID(), label, createdAt: now(), secret: secret(), deviceId: null };
+ pending.set(entry.id, entry);
+ changed();
+ sendJson(response, 200, { state: "pending" }, { "Set-Cookie": cookie(PENDING_COOKIE, entry.secret, PENDING_TTL_MS / 1000) });
+ }
+
+ function pairStatus(request: IncomingMessage, response: ServerResponse) {
+ prune();
+ const token = cookies(request).get(PENDING_COOKIE);
+ const entry = token ? [...pending.values()].find((candidate) => sameSecret(candidate.secret, token)) : undefined;
+ if (!entry) {
+ const device = deviceFor(request);
+ if (device) return sendJson(response, 200, { state: "paired" });
+ throw new LanError(401, "UNAUTHORIZED");
+ }
+ if (!entry.deviceId) return sendJson(response, 200, { state: "pending" });
+ const device = devices.get(entry.deviceId);
+ pending.delete(entry.id);
+ if (!device) throw new LanError(401, "UNAUTHORIZED");
+ sendJson(response, 200, { state: "paired" }, {
+ "Set-Cookie": [cookie(SESSION_COOKIE, device.token, 12 * 60 * 60), cookie(PENDING_COOKIE, "", 0)],
+ });
+ }
+
+ function events(device: Device, request: IncomingMessage, response: ServerResponse, sessionFilter: string | null) {
+ response.writeHead(200, {
+ "Content-Type": "text/event-stream; charset=utf-8",
+ "Cache-Control": "no-store",
+ Connection: "keep-alive",
+ "X-Content-Type-Options": "nosniff",
+ });
+ response.write(": open\n\n");
+ device.streams.add(response);
+ const remove = () => device.streams.delete(response);
+ request.on("close", remove);
+ response.on("close", remove);
+ (response as ServerResponse & { lanSession?: string | null }).lanSession = sessionFilter;
+ }
+
+ async function broadcast(change: LanChange) {
+ for (const device of devices.values()) {
+ if (!device.streams.size) continue;
+ let reveal = false;
+ if (change.sessionId) reveal = await options.handler.mayReveal(access(device), change.sessionId).catch(() => false);
+ if (!devices.has(device.id)) continue;
+ for (const stream of device.streams) {
+ const filter = (stream as ServerResponse & { lanSession?: string | null }).lanSession ?? null;
+ if (filter && change.sessionId !== filter) continue;
+ if (filter && !reveal) continue;
+ const data = reveal ? { sessionId: change.sessionId } : {};
+ stream.write(`event: change\ndata: ${JSON.stringify(data)}\n\n`);
+ }
+ }
+ }
+
+ async function api(request: IncomingMessage, response: ServerResponse, url: URL) {
+ const device = deviceFor(request);
+ if (!device) throw new LanError(401, "UNAUTHORIZED");
+ device.lastActiveAt = now();
+ const method = request.method === "POST" ? "POST" : "GET";
+ if (url.pathname === "/v1/me" && method === "GET") {
+ return sendJson(response, 200, { csrf: device.csrf, access: access(device), label: device.label });
+ }
+ if (method === "POST") {
+ const csrf = String(request.headers["x-csrf-token"] ?? "");
+ if (!sameSecret(device.csrf, csrf)) throw new LanError(403, "CSRF");
+ }
+ if (url.pathname === "/v1/logout" && method === "POST") {
+ closeStreams(device);
+ devices.delete(device.id);
+ changed();
+ return sendJson(response, 200, { ok: true }, { "Set-Cookie": cookie(SESSION_COOKIE, "", 0) });
+ }
+ if (method === "GET" && url.pathname === "/v1/events") return events(device, request, response, null);
+ const sessionEvents = /^\/v1\/sessions\/([^/]+)\/events$/.exec(url.pathname);
+ if (method === "GET" && sessionEvents) {
+ const sessionId = decodeURIComponent(sessionEvents[1]!);
+ if (!(await options.handler.mayReveal(access(device), sessionId))) throw new LanError(404, "NOT_FOUND");
+ return events(device, request, response, sessionId);
+ }
+ const body = method === "POST" ? await readBody(request) : {};
+ 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}`);
+ if (remembered) {
+ result = remembered;
+ } else {
+ result = options.handler.handle(lanRequest, key);
+ device.idempotent.set(`${url.pathname}:${key}`, result);
+ result.catch(() => device.idempotent.delete(`${url.pathname}:${key}`));
+ while (device.idempotent.size > MAX_IDEMPOTENT) {
+ device.idempotent.delete(device.idempotent.keys().next().value as string);
+ }
+ }
+ } else {
+ 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");
+ sendJson(response, 200, value);
+ }
+
+ async function route(request: IncomingMessage, response: ServerResponse) {
+ const url = new URL(request.url ?? "/", `http://${host || "localhost"}`);
+ if (request.method !== "GET" && request.method !== "POST") throw new LanError(405, "METHOD_NOT_ALLOWED");
+ if (!sameOrigin(request)) throw new LanError(403, "FORBIDDEN_ORIGIN");
+ if (request.method === "GET") {
+ const asset = options.assets.get(url.pathname === "/" ? "/index.html" : url.pathname);
+ if (asset) {
+ response.writeHead(200, {
+ "Content-Type": asset.type,
+ "Cache-Control": "no-cache",
+ "Content-Security-Policy": CSP,
+ "X-Content-Type-Options": "nosniff",
+ "Referrer-Policy": "no-referrer",
+ });
+ response.end(asset.body);
+ return;
+ }
+ }
+ if (url.pathname === "/pair" && request.method === "POST") return pair(request, response);
+ if (url.pathname === "/pair/status" && request.method === "GET") return pairStatus(request, response);
+ if (url.pathname.startsWith("/v1/")) return api(request, response, url);
+ throw new LanError(404, "NOT_FOUND");
+ }
+
+ return {
+ async start(address: string, port: number): Promise<{ address: string; port: number }> {
+ if (server) throw new LanError(409, "ALREADY_RUNNING");
+ const next = createServer((request, response) => {
+ route(request, response).catch((error: unknown) => {
+ const safe = error instanceof LanError ? error : new LanError(500, "FAILED");
+ sendJson(response, safe.status, { code: safe.code });
+ });
+ });
+ next.headersTimeout = 15_000;
+ next.requestTimeout = 60_000;
+ next.on("connection", (socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ });
+ await new Promise<void>((resolve, reject) => {
+ next.once("error", reject);
+ next.listen(port, address, () => {
+ next.off("error", reject);
+ resolve();
+ });
+ });
+ const bound = next.address();
+ const boundPort = typeof bound === "object" && bound ? bound.port : port;
+ server = next;
+ host = `${address}:${boundPort}`;
+ unsubscribe = options.handler.subscribe((change) => void broadcast(change));
+ heartbeat = setInterval(() => {
+ for (const device of devices.values()) for (const stream of device.streams) stream.write(": ping\n\n");
+ }, HEARTBEAT_MS);
+ heartbeat.unref?.();
+ return { address, port: boundPort };
+ },
+
+ /** Stopping invalidates every pairing and device credential. */
+ async stop(): Promise<void> {
+ const current = server;
+ server = null;
+ unsubscribe?.();
+ unsubscribe = null;
+ if (heartbeat) clearInterval(heartbeat);
+ heartbeat = null;
+ for (const device of devices.values()) closeStreams(device);
+ devices.clear();
+ pending.clear();
+ code = null;
+ host = "";
+ if (!current) return;
+ const closed = new Promise<void>((resolve) => current.close(() => resolve()));
+ for (const socket of sockets) socket.destroy();
+ sockets.clear();
+ await closed;
+ },
+
+ running: () => server !== null,
+ origin: () => (host ? `http://${host}` : null),
+
+ 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 };
+ return { value: code.value, expiresAt: code.expiresAt };
+ },
+
+ code(): { value: string; expiresAt: number } | null {
+ prune();
+ return code ? { value: code.value, expiresAt: code.expiresAt } : null;
+ },
+
+ pending(): LanPairing[] {
+ prune();
+ return [...pending.values()].filter((entry) => !entry.deviceId).map(({ id, label, createdAt }) => ({ id, label, createdAt }));
+ },
+
+ devices(): LanDevice[] {
+ return [...devices.values()].map(({ id, label, lastActiveAt, grants }) => ({ id, label, lastActiveAt, grants }));
+ },
+
+ /** Desktop confirmation: the only path that turns a pending browser into a device. */
+ confirm(id: string, grants: LanGrants): void {
+ 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");
+ const device: Device = {
+ 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,
+ },
+ token: secret(),
+ csrf: secret(),
+ streams: new Set(),
+ idempotent: new Map(),
+ };
+ devices.set(device.id, device);
+ entry.deviceId = device.id;
+ changed();
+ },
+
+ deny(id: string): void {
+ pending.delete(id);
+ changed();
+ },
+
+ revoke(id: string): void {
+ const device = devices.get(id);
+ if (!device) return;
+ closeStreams(device);
+ devices.delete(id);
+ changed();
+ },
+ };
+}
+
+export type LanServer = ReturnType<typeof createLanServer>;
diff --git a/apps/desktop/electron/main/lan-webui/service.ts b/apps/desktop/electron/main/lan-webui/service.ts
new file mode 100644
index 000000000..36849d8b7
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/service.ts
@@ -0,0 +1,151 @@
+import { networkInterfaces } from "node:os";
+import {
+ IPC,
+ type LanAdminAction,
+ type LanAdminView,
+ type LanGrants,
+ type LanInterface,
+} from "@pi-desktop/shared";
+import { onLanAgentEvent } from "./agent-tap";
+import { getLanOrganization } from "./organization";
+import { LanError } from "./ports";
+import { createLanServer, type LanAsset } from "./server";
+import { createLanWorkspace, type LanWorkspaceDeps } from "./workspace";
+
+const DEFAULT_PORT = 37180;
+
+/** IPv4 private LAN addresses plus loopback, in that order. */
+export function listLanInterfaces(source = networkInterfaces()): LanInterface[] {
+ const result: LanInterface[] = [];
+ for (const [name, entries] of Object.entries(source)) {
+ for (const entry of entries ?? []) {
+ if (entry.family !== "IPv4" || entry.internal) continue;
+ const [a, b] = entry.address.split(".").map(Number);
+ const isPrivate = a === 10 || (a === 172 && b! >= 16 && b! <= 31) || (a === 192 && b === 168);
+ if (isPrivate) result.push({ address: entry.address, name });
+ }
+ }
+ result.push({ address: "127.0.0.1", name: "loopback" });
+ 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;
+ assets: () => ReadonlyMap<string, LanAsset>;
+ sendToRenderer(channel: string, payload: unknown): void;
+ log(level: "info" | "warn", message: string, data?: unknown): void;
+}) {
+ const organization = getLanOrganization(deps.dataDir);
+ organization.setNotifier((event) => deps.sendToRenderer(IPC.event.lanWebUiCatalogChanged, event));
+ const workspace = createLanWorkspace({
+ ...deps.workspace,
+ organization,
+ notifyDesktop: (sessionId) =>
+ deps.sendToRenderer(IPC.event.sessionsChanged, { reason: "lan.webui", ...(sessionId ? { sessionId } : {}) }),
+ });
+ 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 ensureServer = () => {
+ server ??= createLanServer({ handler: workspace, assets: deps.assets() });
+ return server;
+ };
+
+ async function view(): Promise<LanAdminView> {
+ const current = server;
+ const running = current?.running() === true;
+ const projects = await workspace.operatorProjects().catch(() => []);
+ return {
+ running,
+ origin: running ? current!.origin() : null,
+ address: running ? address : null,
+ port: running ? port : null,
+ code: running ? current!.code() : null,
+ pending: running ? current!.pending() : [],
+ devices: running ? current!.devices() : [],
+ interfaces: listLanInterfaces(),
+ projects,
+ error: lastError,
+ };
+ }
+
+ async function admin(action: LanAdminAction): Promise<LanAdminView> {
+ lastError = null;
+ try {
+ switch (action?.kind) {
+ case "state":
+ break;
+ case "start": {
+ const allowed = listLanInterfaces().some((entry) => entry.address === action.address);
+ const requestedPort = Number.isInteger(action.port) && action.port > 0 && action.port < 65536 ? action.port : DEFAULT_PORT;
+ if (!allowed) throw new LanError(400, "INVALID_ADDRESS");
+ const bound = await ensureServer().start(action.address, requestedPort);
+ address = bound.address;
+ port = bound.port;
+ deps.log("info", "lan webui started", { port: bound.port });
+ break;
+ }
+ case "stop":
+ await server?.stop();
+ address = null;
+ port = null;
+ deps.log("info", "lan webui stopped");
+ break;
+ case "issueCode":
+ ensureServer().issueCode();
+ break;
+ case "confirm":
+ ensureServer().confirm(String(action.id), validGrants(action.grants));
+ break;
+ case "deny":
+ server?.deny(String(action.id));
+ break;
+ case "revoke":
+ server?.revoke(String(action.id));
+ break;
+ case "ack":
+ if (Number.isInteger(action.seq)) organization.ack(action.seq);
+ break;
+ default:
+ throw new LanError(400, "INVALID_ARGUMENT");
+ }
+ } catch (error) {
+ const code = error instanceof LanError
+ ? error.code
+ : (error as { code?: unknown })?.code === "EADDRINUSE" ? "PORT_IN_USE" : "FAILED";
+ lastError = code;
+ if (!(error instanceof LanError)) deps.log("warn", "lan webui action failed", { kind: action?.kind, code });
+ }
+ return view();
+ }
+
+ return {
+ admin,
+ async dispose(): Promise<void> {
+ offAgent();
+ offWrites();
+ await server?.stop();
+ workspace.dispose();
+ },
+ };
+}
+
+export type LanWebUiService = ReturnType<typeof createLanWebUiService>;
diff --git a/apps/desktop/electron/main/lan-webui/workspace.ts b/apps/desktop/electron/main/lan-webui/workspace.ts
new file mode 100644
index 000000000..fb4df0fdd
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/workspace.ts
@@ -0,0 +1,513 @@
+import { createHash } from "node:crypto";
+import {
+ LAN_TEMPORARY_PROJECT,
+ type AgentEventEnvelope,
+ type LanAccess,
+ type LanConversation,
+ type LanMessage,
+ type LanPage,
+ type LanProject,
+ type LanSession,
+ type ProjectGroupRecord,
+} from "@pi-desktop/shared";
+import type { LanMeta, LanOrganization } from "./organization";
+import { normalizeProjectKey } from "./organization";
+import { LanError, type LanChange, type LanRequest } from "./ports";
+
+export type LanHost = { call<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T> };
+type Principal = { subject: string; roles: Array<"viewer" | "controller">; pairedDevice: boolean };
+export type LanBridge = {
+ agentHost: {
+ startTurn(principal: Principal, params: {
+ sessionId: string;
+ admission: "queue" | "reject_if_busy";
+ idempotencyKey?: string;
+ input: { text: string };
+ context: { requestId: string };
+ }): Promise<{ turn: { id: string } }>;
+ };
+ queue: {
+ list(sessionId: string): Array<{ id: string; content: string }>;
+ remove(turnId: string): Promise<void>;
+ };
+ pendingInteractiveRequests(sessionId: string): Promise<{ asks: unknown[]; permissions: unknown[] }>;
+};
+export type LanWorkspaceDeps = {
+ getHost(): LanHost | null;
+ getBridge(): LanBridge | null;
+ invoke(channel: string, args: unknown[]): Promise<unknown>;
+ channels: { sessionCreate: string; sessionRename: string; projectGroupRename: string; agentAbort: string };
+ activeTurns: ReadonlyMap<string, string>;
+ organization: Pick<LanOrganization, "read" | "patch">;
+ /** Ask Desktop to refresh its catalog (and an idle open transcript); never navigates. */
+ notifyDesktop(sessionId?: string): void;
+};
+
+type HostSession = {
+ id: string;
+ title?: string;
+ projectPath?: string | null;
+ mode?: string;
+ source?: string;
+ modelId?: string;
+ updatedAt?: string;
+};
+type HostMessage = { id: string; role: string; content?: unknown; toolName?: string; parentToolCallId?: string };
+type HostDetail = HostSession & { messages?: HostMessage[]; messageStart?: number; hasMoreBefore?: boolean };
+
+const PAGE = 50;
+const HISTORY_PAGE = 50;
+const MAX_TEXT = 64 * 1024;
+const MAX_TOOL_TEXT = 600;
+const MAX_PROMPT = 256 * 1024;
+const MAX_NAME = 120;
+
+const revision = (...parts: unknown[]) =>
+ createHash("sha1").update(JSON.stringify(parts)).digest("base64url").slice(0, 12);
+const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}…` : text);
+
+function stringField(body: Record<string, unknown>, key: string): string | undefined {
+ const value = body[key];
+ return typeof value === "string" ? value : undefined;
+}
+
+function oneOrganizeField(body: Record<string, unknown>): ["name", string] | ["pinned" | "archived", boolean] {
+ const fields = (["name", "pinned", "archived"] as const).filter((key) => body[key] !== undefined);
+ if (fields.length !== 1) throw new LanError(400, "INVALID_ARGUMENT");
+ const field = fields[0]!;
+ const value = body[field];
+ if (field === "name") {
+ const name = typeof value === "string" ? value.trim() : "";
+ if (!name || name.length > MAX_NAME) throw new LanError(400, "INVALID_ARGUMENT");
+ return ["name", name];
+ }
+ if (typeof value !== "boolean") throw new LanError(400, "INVALID_ARGUMENT");
+ return [field, value];
+}
+
+export function createLanWorkspace(deps: LanWorkspaceDeps) {
+ const live = new Map<string, string>();
+ const listeners = new Set<(change: LanChange) => void>();
+ const timers = new Map<string, ReturnType<typeof setTimeout>>();
+
+ const emit = (change: LanChange) => {
+ for (const listener of listeners) listener(change);
+ };
+ const emitSoon = (sessionId: string) => {
+ if (timers.has(sessionId)) return;
+ timers.set(sessionId, setTimeout(() => {
+ timers.delete(sessionId);
+ emit({ sessionId });
+ }, 200));
+ };
+
+ const host = (): LanHost => {
+ const value = deps.getHost();
+ if (!value) throw new LanError(503, "DESKTOP_UNAVAILABLE");
+ return value;
+ };
+ const bridge = (): LanBridge => {
+ const value = deps.getBridge();
+ if (!value) throw new LanError(503, "DESKTOP_UNAVAILABLE");
+ return value;
+ };
+
+ async function groups(): Promise<ProjectGroupRecord[]> {
+ const result = await host().call<{ groups?: ProjectGroupRecord[] }>("project.groups.list");
+ return (result.groups ?? []).filter((group) => !group.remote);
+ }
+
+ function projectView(group: ProjectGroupRecord, meta: LanMeta): LanProject {
+ const own = meta.projectMeta[normalizeProjectKey(group.primaryPath)] ?? {};
+ const label = own.name ?? group.name;
+ const pinned = own.pinned ?? group.pinned;
+ const archived = own.archived === true;
+ return { id: group.id, label, pinned, archived, revision: revision(label, pinned, archived) };
+ }
+
+ /** Root path → group id, so a session can be attributed to one project. */
+ function rootIndex(list: ProjectGroupRecord[]): Map<string, ProjectGroupRecord> {
+ const index = new Map<string, ProjectGroupRecord>();
+ for (const group of list) {
+ index.set(normalizeProjectKey(group.primaryPath), group);
+ for (const root of group.roots ?? []) index.set(normalizeProjectKey(root.path), group);
+ }
+ return index;
+ }
+
+ /** `undefined` = not attributable (hidden); `null` = temporary. */
+ function projectOf(session: HostSession, index: Map<string, ProjectGroupRecord>): string | null | undefined {
+ const path = session.projectPath?.trim();
+ if (!path) return null;
+ return index.get(normalizeProjectKey(path))?.id;
+ }
+
+ const allowed = (access: LanAccess, projectId: string | null | undefined) =>
+ projectId === null ? access.temporary : projectId !== undefined && access.projectIds.includes(projectId);
+
+ function sessionView(session: HostSession, projectId: string | null, meta: LanMeta): LanSession {
+ const own = meta.sessionMeta[session.id] ?? {};
+ const title = session.title?.trim() || "";
+ const pinned = own.pinned === true;
+ const archived = own.archived === true;
+ const running = deps.activeTurns.has(session.id);
+ return {
+ id: session.id,
+ projectId,
+ title,
+ pinned,
+ archived,
+ revision: revision(title, pinned, archived),
+ readOnly: (session.mode ?? "agent") !== "agent" || (session.source !== undefined && session.source !== "desktop"),
+ status: running ? "running" : "idle",
+ updatedAt: session.updatedAt ?? "",
+ };
+ }
+
+ const isLocalDesktopSession = (session: HostSession) =>
+ !session.id.startsWith("remote:") && !session.id.startsWith("native-pi:");
+
+ async function hostSessions(): Promise<HostSession[]> {
+ const result = await host().call<{ sessions?: HostSession[] }>("session.list");
+ return (result.sessions ?? []).filter(isLocalDesktopSession);
+ }
+
+ /** Re-resolves the session's scope on every call; missing and forbidden look alike. */
+ async function authorizedSession(access: LanAccess, sessionId: string) {
+ if (!sessionId || sessionId.startsWith("remote:") || sessionId.startsWith("native-pi:")) {
+ throw new LanError(404, "NOT_FOUND");
+ }
+ const [list, sessions] = await Promise.all([groups(), hostSessions()]);
+ const session = sessions.find((candidate) => candidate.id === sessionId);
+ if (!session) throw new LanError(404, "NOT_FOUND");
+ const projectId = projectOf(session, rootIndex(list));
+ if (projectId === undefined || !allowed(access, projectId)) throw new LanError(404, "NOT_FOUND");
+ const meta = deps.organization.read();
+ return { session, projectId, meta, view: sessionView(session, projectId, meta) };
+ }
+
+ async function authorizedProject(access: LanAccess, projectId: string) {
+ if (!access.projectIds.includes(projectId)) throw new LanError(404, "NOT_FOUND");
+ const group = (await groups()).find((candidate) => candidate.id === projectId);
+ if (!group) throw new LanError(404, "NOT_FOUND");
+ const meta = deps.organization.read();
+ return { group, meta, view: projectView(group, meta) };
+ }
+
+ function page<T>(items: T[], cursor: string | null): LanPage<T> {
+ const start = Math.max(0, Number.parseInt(cursor ?? "0", 10) || 0);
+ const slice = items.slice(start, start + PAGE);
+ return { items: slice, nextCursor: start + PAGE < items.length ? String(start + PAGE) : null };
+ }
+
+ const matches = (text: string, query: string) => !query || text.toLowerCase().includes(query.toLowerCase());
+
+ async function listProjects(access: LanAccess, query: URLSearchParams): Promise<LanPage<LanProject>> {
+ const meta = deps.organization.read();
+ const archivedOnly = query.get("archived") === "1";
+ const q = (query.get("q") ?? "").trim();
+ const list = (await groups())
+ .filter((group) => access.projectIds.includes(group.id))
+ .map((group) => ({ group, view: projectView(group, meta) }))
+ .filter(({ view }) => view.archived === archivedOnly && matches(view.label, q))
+ .sort((a, b) => Number(b.view.pinned) - Number(a.view.pinned) || b.group.lastOpenedAt - a.group.lastOpenedAt)
+ .map(({ view }) => view);
+ return page(list, query.get("cursor"));
+ }
+
+ async function listSessions(access: LanAccess, query: URLSearchParams): Promise<LanPage<LanSession>> {
+ const requested = query.get("projectId") ?? "";
+ const wantTemporary = requested === LAN_TEMPORARY_PROJECT;
+ if (wantTemporary ? !access.temporary : !access.projectIds.includes(requested)) {
+ throw new LanError(404, "NOT_FOUND");
+ }
+ const [list, sessions] = await Promise.all([groups(), hostSessions()]);
+ if (!wantTemporary && !list.some((group) => group.id === requested)) throw new LanError(404, "NOT_FOUND");
+ const index = rootIndex(list);
+ const meta = deps.organization.read();
+ const archivedOnly = query.get("archived") === "1";
+ const q = (query.get("q") ?? "").trim();
+ const items = sessions
+ .filter((session) => projectOf(session, index) === (wantTemporary ? null : requested))
+ .map((session) => sessionView(session, wantTemporary ? null : requested, meta))
+ .filter((view) => view.archived === archivedOnly && matches(view.title, q))
+ .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt));
+ return page(items, query.get("cursor"));
+ }
+
+ function projectMessage(message: HostMessage): LanMessage | null {
+ if (message.parentToolCallId) return null;
+ const text = typeof message.content === "string" ? message.content : "";
+ if (message.role === "user" || message.role === "assistant") {
+ return { id: message.id, role: message.role, text: clip(text, MAX_TEXT) };
+ }
+ if (message.role === "tool") {
+ const label = message.toolName ? `${message.toolName}` : "";
+ return { id: message.id, role: "tool", text: clip(label, MAX_TOOL_TEXT) };
+ }
+ return null;
+ }
+
+ async function history(sessionId: string, cursor: string | null): Promise<LanPage<LanMessage>> {
+ const before = cursor === null ? undefined : Number.parseInt(cursor, 10);
+ if (before !== undefined && (!Number.isInteger(before) || before < 0)) throw new LanError(400, "INVALID_ARGUMENT");
+ const result = await host().call<{ session?: HostDetail | null }>("session.get", {
+ id: sessionId,
+ messageLimit: HISTORY_PAGE,
+ contentLimit: MAX_TEXT,
+ ...(before !== undefined ? { messageBefore: before } : {}),
+ });
+ const detail = result.session;
+ if (!detail) throw new LanError(404, "NOT_FOUND");
+ const items = (detail.messages ?? []).map(projectMessage).filter((m): m is LanMessage => m !== null);
+ const start = detail.messageStart ?? 0;
+ return { items, nextCursor: detail.hasMoreBefore && start > 0 ? String(start) : null };
+ }
+
+ async function conversation(access: LanAccess, sessionId: string): Promise<LanConversation> {
+ const { session, view } = await authorizedSession(access, sessionId);
+ const [messages, pending] = await Promise.all([
+ history(sessionId, null),
+ deps.getBridge()?.pendingInteractiveRequests(sessionId).catch(() => ({ asks: [], permissions: [] })) ??
+ Promise.resolve({ asks: [], permissions: [] }),
+ ]);
+ const waiting = pending.permissions.length ? "approval" : pending.asks.length ? "input" : null;
+ const queue = (deps.getBridge()?.queue.list(sessionId) ?? []).map((entry) => ({
+ id: entry.id,
+ text: clip(entry.content, 2000),
+ }));
+ return {
+ session: { ...view, status: waiting ? "waiting" : view.status },
+ messages,
+ liveText: live.get(sessionId) ?? null,
+ activeTurnId: deps.activeTurns.get(sessionId) ?? null,
+ waiting,
+ queue,
+ modelLabel: session.modelId ?? null,
+ };
+ }
+
+ const requireChat = (access: LanAccess) => {
+ if (!access.chat) throw new LanError(403, "FORBIDDEN");
+ };
+ const requireOrganize = (access: LanAccess) => {
+ if (!access.organize) throw new LanError(403, "FORBIDDEN");
+ };
+
+ async function createSession(access: LanAccess, body: Record<string, unknown>) {
+ requireChat(access);
+ const projectId = body.projectId === null ? null : stringField(body, "projectId");
+ if (projectId === undefined) throw new LanError(400, "INVALID_ARGUMENT");
+ let projectPath: string | undefined;
+ if (projectId === null) {
+ if (!access.temporary) throw new LanError(404, "NOT_FOUND");
+ } else {
+ const { group, view } = await authorizedProject(access, projectId);
+ if (view.archived) throw new LanError(409, "ARCHIVED");
+ projectPath = group.primaryPath;
+ }
+ const created = (await deps.invoke(deps.channels.sessionCreate, [projectPath ? { projectPath } : {}])) as {
+ session?: { id?: string } | null;
+ };
+ const id = created?.session?.id;
+ if (!id) throw new LanError(500, "FAILED");
+ deps.notifyDesktop();
+ emit({});
+ return { id };
+ }
+
+ async function organizeProject(access: LanAccess, projectId: string, body: Record<string, unknown>) {
+ requireOrganize(access);
+ const [field, value] = oneOrganizeField(body);
+ const { group, view } = await authorizedProject(access, projectId);
+ if (body.revision !== view.revision) throw new LanError(409, "CONFLICT");
+ if (field === "archived" && value === true) {
+ const index = rootIndex([group]);
+ const busy = (await hostSessions()).some(
+ (session) => projectOf(session, index) === group.id && deps.activeTurns.has(session.id),
+ );
+ if (busy) throw new LanError(409, "BUSY");
+ }
+ if (field === "name") {
+ await deps.invoke(deps.channels.projectGroupRename, [{ groupId: group.id, name: value }]);
+ }
+ deps.organization.patch({ kind: "project", key: group.primaryPath, patch: { [field]: value } });
+ deps.notifyDesktop();
+ emit({});
+ return { ok: true };
+ }
+
+ async function organizeSession(access: LanAccess, sessionId: string, body: Record<string, unknown>) {
+ requireOrganize(access);
+ const [field, value] = oneOrganizeField(body);
+ const { view } = await authorizedSession(access, sessionId);
+ if (body.revision !== view.revision) throw new LanError(409, "CONFLICT");
+ if (field === "archived" && value === true) {
+ const queued = deps.getBridge()?.queue.list(sessionId).length ?? 0;
+ if (deps.activeTurns.has(sessionId) || queued > 0) throw new LanError(409, "BUSY");
+ }
+ if (field === "name") {
+ await deps.invoke(deps.channels.sessionRename, [sessionId, value]);
+ deps.organization.patch({ kind: "session", key: sessionId, patch: { manualTitle: true } });
+ } else {
+ deps.organization.patch({ kind: "session", key: sessionId, patch: { [field]: value } });
+ }
+ deps.notifyDesktop(sessionId);
+ emit({ sessionId });
+ return { ok: true };
+ }
+
+ async function sendTurn(access: LanAccess, sessionId: string, body: Record<string, unknown>, key: string | null) {
+ requireChat(access);
+ const text = stringField(body, "text")?.trim() ?? "";
+ if (!text) throw new LanError(400, "INVALID_ARGUMENT");
+ if (Buffer.byteLength(text) > MAX_PROMPT) throw new LanError(413, "PAYLOAD_TOO_LARGE");
+ const { view } = await authorizedSession(access, sessionId);
+ if (view.readOnly) throw new LanError(409, "READ_ONLY");
+ if (view.archived) throw new LanError(409, "ARCHIVED");
+ const principal: Principal = { subject: `lan:${access.deviceId}`, roles: ["viewer", "controller"], pairedDevice: false };
+ try {
+ const result = await bridge().agentHost.startTurn(principal, {
+ sessionId,
+ admission: body.queue === true ? "queue" : "reject_if_busy",
+ ...(key ? { idempotencyKey: `lan:${access.deviceId}:${key}` } : {}),
+ input: { text },
+ context: { requestId: `lan-${Date.now().toString(36)}` },
+ });
+ deps.notifyDesktop(sessionId);
+ emitSoon(sessionId);
+ return { id: result.turn.id };
+ } catch (error) {
+ const code = (error as { code?: unknown })?.code;
+ if (code === "AGENT_BUSY") throw new LanError(409, "BUSY");
+ if (code === "FORBIDDEN") throw new LanError(403, "FORBIDDEN");
+ if (code === "AGENT_UNAVAILABLE") throw new LanError(503, "DESKTOP_UNAVAILABLE");
+ throw new LanError(500, "FAILED");
+ }
+ }
+
+ async function interrupt(access: LanAccess, turnId: string, body: Record<string, unknown>) {
+ requireChat(access);
+ const sessionId = stringField(body, "sessionId") ?? "";
+ await authorizedSession(access, sessionId);
+ if (deps.activeTurns.get(sessionId) !== turnId) return { ok: true, stopped: false };
+ await deps.invoke(deps.channels.agentAbort, [{ sessionId, turnId }]);
+ emitSoon(sessionId);
+ return { ok: true, stopped: true };
+ }
+
+ async function cancel(access: LanAccess, turnId: string, body: Record<string, unknown>) {
+ requireChat(access);
+ const sessionId = stringField(body, "sessionId") ?? "";
+ await authorizedSession(access, sessionId);
+ const queue = bridge().queue;
+ if (!queue.list(sessionId).some((entry) => entry.id === turnId)) return { ok: true, canceled: false };
+ await queue.remove(turnId);
+ emitSoon(sessionId);
+ return { ok: true, canceled: true };
+ }
+
+ return {
+ /** Operator-only list for the Desktop pairing dialog. */
+ async operatorProjects(): Promise<Array<{ id: string; label: string }>> {
+ const meta = deps.organization.read();
+ return (await groups()).map((group) => {
+ const view = projectView(group, meta);
+ return { id: view.id, label: view.label };
+ });
+ },
+
+ async handle(request: LanRequest, key: string | null): Promise<unknown> {
+ const { method, path, access, query, body } = request;
+ const parts = path.split("/").filter(Boolean).map(decodeURIComponent); // ["v1", ...]
+ const [, resource, id, sub] = parts;
+ if (method === "GET") {
+ if (resource === "projects" && !id) return listProjects(access, query);
+ if (resource === "sessions" && !id) return listSessions(access, query);
+ if (resource === "sessions" && id && !sub) return conversation(access, id);
+ if (resource === "sessions" && id && sub === "history") {
+ await authorizedSession(access, id);
+ return history(id, query.get("cursor"));
+ }
+ } else {
+ if (resource === "sessions" && !id) return createSession(access, body);
+ if (resource === "projects" && id && sub === "organize") return organizeProject(access, id, body);
+ if (resource === "sessions" && id && sub === "organize") return organizeSession(access, id, body);
+ if (resource === "sessions" && id && sub === "turns") return sendTurn(access, id, body, key);
+ if (resource === "turns" && id?.endsWith(":interrupt")) return interrupt(access, id.slice(0, -10), body);
+ if (resource === "turns" && id?.endsWith(":cancel")) return cancel(access, id.slice(0, -7), body);
+ }
+ throw new LanError(404, "NOT_FOUND");
+ },
+
+ /** Session-scoped change notifications; ids are filtered by the caller's scope. */
+ subscribe(listener: (change: LanChange) => void): () => void {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ },
+
+ /** Whether a change for `sessionId` may be revealed to `access`. */
+ async mayReveal(access: LanAccess, sessionId: string): Promise<boolean> {
+ try {
+ await authorizedSession(access, sessionId);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+
+ /** Catalog changes made on Desktop (or by another device). */
+ catalogChanged(): void {
+ emit({});
+ },
+
+ ingest(envelope: AgentEventEnvelope): void {
+ if (envelope.parentToolCallId) return;
+ const { sessionId, event } = envelope;
+ switch (event.type) {
+ case "message_start":
+ if (event.message.role === "assistant") live.set(sessionId, "");
+ break;
+ case "message_update": {
+ if (event.message.role !== "assistant") break;
+ if (event.stream === "delta") {
+ const base = event.resetText ? "" : live.get(sessionId) ?? "";
+ live.set(sessionId, clip(base + (event.deltaText ?? ""), MAX_TEXT));
+ } else {
+ live.set(sessionId, clip(event.message.content ?? "", MAX_TEXT));
+ }
+ break;
+ }
+ case "message_end":
+ live.delete(sessionId);
+ break;
+ case "agent_end":
+ live.delete(sessionId);
+ deps.notifyDesktop(sessionId);
+ break;
+ case "tool_start":
+ case "tool_end":
+ case "tool_permission_request":
+ case "asktool_request":
+ case "agent_start":
+ case "status":
+ case "user_message_persisted":
+ break;
+ default:
+ return;
+ }
+ emitSoon(sessionId);
+ },
+
+ dispose(): void {
+ for (const timer of timers.values()) clearTimeout(timer);
+ timers.clear();
+ listeners.clear();
+ live.clear();
+ },
+ };
+}
+
+export type LanWorkspace = ReturnType<typeof createLanWorkspace>;
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index 4807f397a..af639f2b0 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -7,6 +7,7 @@ import {
classifySidecarCrash,
sidecarCrashErrorCode,
} from "@pi-desktop/agent-runtime";
+import { publishLanAgentEvent } from "../lan-webui/agent-tap";
import {
assertBuiltinSkillEnabled,
loadBuiltinSkillBody,
@@ -129,6 +130,7 @@ export function createSidecarRuntime({
if (isStaleTerminalEvent(envelope)) return;
runtimeState.agentHostBridge?.ingest(envelope);
sendToRenderer(IPC.event.agentMessage, envelope);
+ publishLanAgentEvent(envelope);
};
const activeToolCalls = new Map<
string,
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
new file mode 100644
index 000000000..f82d0f422
--- /dev/null
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -0,0 +1,497 @@
+// PI-Desktop LAN WebUI. Plain DOM only: every value is set with textContent.
+"use strict";
+
+(() => {
+ const TEMP = "__temporary__";
+ const locales = window.LAN_LOCALES || {};
+ const lang = (navigator.languages || [navigator.language || "en"]).find((code) => code && code.toLowerCase().startsWith("zh"))
+ ? "zh-CN"
+ : "en";
+ const copy = { ...locales.en, ...(locales[lang] || {}), errors: { ...(locales.en || {}).errors, ...((locales[lang] || {}).errors || {}) } };
+ document.documentElement.lang = lang;
+ const t = (key, values) => String(copy[key] ?? key).replace(/\{(\w+)\}/g, (_, name) => String(values?.[name] ?? ""));
+ const errorText = (code) => copy.errors[code] || copy.errors.FAILED;
+
+ const app = document.getElementById("app");
+ const toast = document.getElementById("toast");
+ const offline = document.getElementById("offline");
+ const sheet = document.getElementById("sheet");
+
+ const state = {
+ me: null,
+ route: { view: "projects" },
+ drafts: new Map(),
+ projects: new Map(),
+ events: null,
+ refreshTimer: null,
+ renderToken: 0,
+ sending: false,
+ };
+
+ // ---------- helpers ----------
+ function el(tag, props = {}, children = []) {
+ const node = document.createElement(tag);
+ for (const [key, value] of Object.entries(props)) {
+ if (value === undefined || value === null || value === false) continue;
+ if (key === "text") node.textContent = value;
+ else if (key === "class") node.className = value;
+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);
+ else if (value === true) node.setAttribute(key, "");
+ else node.setAttribute(key, String(value));
+ }
+ for (const child of [].concat(children)) if (child) node.append(child);
+ return node;
+ }
+ let toastTimer = null;
+ function notify(message) {
+ toast.textContent = message;
+ toast.hidden = false;
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => (toast.hidden = true), 4000);
+ }
+ const newKey = () => (crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`).replace(/[^A-Za-z0-9_-]/g, "");
+
+ class ApiError extends Error {
+ constructor(status, code) {
+ super(code);
+ this.status = status;
+ this.code = code;
+ }
+ }
+
+ async function api(method, path, body, key) {
+ const headers = { Accept: "application/json" };
+ if (method === "POST") {
+ headers["Content-Type"] = "application/json";
+ if (state.me?.csrf) headers["X-CSRF-Token"] = state.me.csrf;
+ if (key) headers["Idempotency-Key"] = key;
+ }
+ let response;
+ try {
+ response = await fetch(path, { method, headers, credentials: "same-origin", body: method === "POST" ? JSON.stringify(body || {}) : undefined });
+ } catch {
+ throw new ApiError(0, "NETWORK");
+ }
+ let data = null;
+ try {
+ data = await response.json();
+ } catch {
+ data = null;
+ }
+ if (!response.ok) {
+ const code = data?.code || "FAILED";
+ if (response.status === 401 && path.startsWith("/v1/")) {
+ state.me = null;
+ closeEvents();
+ showPair();
+ }
+ throw new ApiError(response.status, code);
+ }
+ return data;
+ }
+
+ function fail(error) {
+ if (error instanceof ApiError && error.code === "UNAUTHORIZED") return;
+ notify(errorText(error instanceof ApiError ? error.code : "FAILED"));
+ }
+
+ // ---------- routing ----------
+ function parseRoute() {
+ const hash = location.hash.replace(/^#\/?/, "");
+ const [kind, raw] = hash.split("/");
+ const id = raw ? decodeURIComponent(raw) : "";
+ if (kind === "p" && id) return { view: "sessions", projectId: id };
+ if (kind === "s" && id) return { view: "chat", sessionId: id };
+ return { view: "projects" };
+ }
+ const go = (hash) => {
+ if (location.hash === hash) render();
+ else location.hash = hash;
+ };
+ window.addEventListener("hashchange", () => {
+ state.route = parseRoute();
+ render();
+ });
+
+ // ---------- events ----------
+ function openEvents() {
+ closeEvents();
+ const source = new EventSource("/v1/events");
+ source.addEventListener("open", () => (offline.hidden = true));
+ source.addEventListener("error", () => {
+ offline.textContent = t("offline");
+ offline.hidden = false;
+ });
+ source.addEventListener("change", (event) => {
+ let data = {};
+ try {
+ data = JSON.parse(event.data || "{}");
+ } catch {
+ data = {};
+ }
+ const route = state.route;
+ if (route.view === "chat" && data.sessionId && data.sessionId !== route.sessionId) return;
+ scheduleRefresh();
+ });
+ state.events = source;
+ }
+ function closeEvents() {
+ state.events?.close();
+ state.events = null;
+ }
+ function scheduleRefresh() {
+ if (state.refreshTimer) return;
+ state.refreshTimer = setTimeout(() => {
+ state.refreshTimer = null;
+ render({ refresh: true });
+ }, 250);
+ }
+ document.addEventListener("visibilitychange", () => {
+ if (document.visibilityState === "visible" && state.me) scheduleRefresh();
+ });
+
+ // ---------- sheet ----------
+ function openSheet(title, actions) {
+ const list = document.getElementById("sheet-actions");
+ document.getElementById("sheet-title").textContent = title;
+ list.replaceChildren(
+ ...actions.map((action) => el("button", { type: "button", class: action.danger ? "danger" : "", text: action.label, onclick: () => { closeSheet(); action.run(); } })),
+ el("button", { type: "button", text: t("cancel"), onclick: closeSheet }),
+ );
+ sheet.hidden = false;
+ list.querySelector("button")?.focus();
+ }
+ function closeSheet() {
+ sheet.hidden = true;
+ }
+ sheet.addEventListener("click", (event) => { if (event.target === sheet) closeSheet(); });
+ document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !sheet.hidden) closeSheet(); });
+
+ function organizeActions(kind, item) {
+ if (!state.me?.access.organize) return [];
+ const path = `/v1/${kind}/${encodeURIComponent(item.id)}/organize`;
+ const send = (patch) => api("POST", path, { revision: item.revision, ...patch }, newKey()).then(() => render({ refresh: true }), (error) => { fail(error); render({ refresh: true }); });
+ const label = kind === "projects" ? item.label : item.title || t("untitled");
+ return [
+ { label: t("rename"), run: () => { const name = window.prompt(t("renamePrompt"), label); if (name && name.trim() && name.trim() !== label) send({ name: name.trim() }); } },
+ { label: item.pinned ? t("unpin") : t("pin"), run: () => send({ pinned: !item.pinned }) },
+ { label: item.archived ? t("restore") : t("archive"), danger: !item.archived, run: () => send({ archived: !item.archived }) },
+ ];
+ }
+
+ // ---------- views ----------
+ function header(title, back) {
+ return el("header", { class: "header" }, [
+ back ? el("button", { type: "button", "aria-label": t("back"), text: "‹", onclick: () => (history.length > 1 ? history.back() : go(back)) }) : null,
+ el("h1", { text: title }),
+ ]);
+ }
+
+ function toolbar(onSearch, filters) {
+ const search = el("input", { type: "search", placeholder: t("search"), "aria-label": t("search"), value: filters.q });
+ let timer = null;
+ search.addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(() => onSearch({ q: search.value }), 250); });
+ const archived = el("input", { type: "checkbox", checked: filters.archived });
+ archived.addEventListener("change", () => onSearch({ archived: archived.checked }));
+ return el("div", { class: "toolbar" }, [search, el("label", { class: "toggle" }, [archived, document.createTextNode(t("showArchived"))])]);
+ }
+
+ function row({ title, meta, onOpen, actions, moreLabel }) {
+ return el("li", { class: "row" }, [
+ el("button", { type: "button", class: "row-main", onclick: onOpen }, [
+ el("span", { class: "row-title", text: title }),
+ meta.length ? el("span", { class: "row-meta" }, meta.map((text) => el("span", { text }))) : null,
+ ]),
+ actions.length ? el("button", { type: "button", class: "row-more", "aria-label": moreLabel, text: "⋯", onclick: () => openSheet(title, actions) }) : null,
+ ]);
+ }
+
+ const listFilters = { projects: { q: "", archived: false }, sessions: { q: "", archived: false } };
+
+ async function loadAll(path) {
+ const items = [];
+ let cursor = null;
+ for (let page = 0; page < 20; page += 1) {
+ const result = await api("GET", cursor ? `${path}&cursor=${encodeURIComponent(cursor)}` : path);
+ items.push(...result.items);
+ cursor = result.nextCursor;
+ if (!cursor) break;
+ }
+ return items;
+ }
+
+ async function renderProjects(token) {
+ const filters = listFilters.projects;
+ const query = `?q=${encodeURIComponent(filters.q)}${filters.archived ? "&archived=1" : ""}`;
+ const items = await loadAll(`/v1/projects${query}`);
+ if (token !== state.renderToken) return;
+ for (const item of items) state.projects.set(item.id, item.label);
+ const list = el("ul", { class: "list" });
+ if (state.me.access.temporary && !filters.archived && !filters.q) {
+ list.append(row({ title: t("temporary"), meta: [], actions: [], onOpen: () => go(`#/p/${TEMP}`) }));
+ }
+ for (const item of items) {
+ list.append(row({
+ title: item.label,
+ meta: [item.pinned ? t("pinned") : "", item.archived ? t("archived") : ""].filter(Boolean),
+ onOpen: () => go(`#/p/${encodeURIComponent(item.id)}`),
+ actions: organizeActions("projects", item),
+ moreLabel: t("more", { name: item.label }),
+ }));
+ }
+ const empty = !list.children.length ? el("p", { class: "empty", text: filters.q ? t("noMatches") : t("noProjects") }) : null;
+ app.replaceChildren(
+ header(t("projects")),
+ toolbar((patch) => { Object.assign(filters, patch); render(); }, filters),
+ list,
+ empty,
+ el("button", { type: "button", class: "link", text: t("signOut"), onclick: signOut }),
+ );
+ }
+
+ async function renderSessions(token, projectId) {
+ const filters = listFilters.sessions;
+ const query = `?projectId=${encodeURIComponent(projectId)}&q=${encodeURIComponent(filters.q)}${filters.archived ? "&archived=1" : ""}`;
+ const items = await loadAll(`/v1/sessions${query}`);
+ if (token !== state.renderToken) return;
+ const title = projectId === TEMP ? t("temporary") : state.projects.get(projectId) || t("projects");
+ const list = el("ul", { class: "list" });
+ for (const item of items) {
+ const status = item.status === "running" ? t("running") : item.status === "waiting" ? t("waiting") : "";
+ list.append(row({
+ title: item.title || t("untitled"),
+ meta: [status, item.pinned ? t("pinned") : "", item.archived ? t("archived") : "", item.readOnly ? t("readOnly") : ""].filter(Boolean),
+ onOpen: () => go(`#/s/${encodeURIComponent(item.id)}`),
+ actions: organizeActions("sessions", item),
+ moreLabel: t("more", { name: item.title || t("untitled") }),
+ }));
+ }
+ const create = state.me.access.chat
+ ? el("button", {
+ type: "button",
+ class: "primary",
+ text: t("newSession"),
+ onclick: async (event) => {
+ const button = event.currentTarget;
+ button.disabled = true;
+ try {
+ const created = await api("POST", "/v1/sessions", { projectId: projectId === TEMP ? null : projectId }, newKey());
+ go(`#/s/${encodeURIComponent(created.id)}`);
+ } catch (error) {
+ fail(error);
+ button.disabled = false;
+ }
+ },
+ })
+ : null;
+ app.replaceChildren(
+ header(title, "#/projects"),
+ toolbar((patch) => { Object.assign(filters, patch); render(); }, filters),
+ create,
+ list,
+ !items.length ? el("p", { class: "empty", text: filters.q ? t("noMatches") : t("noSessions") }) : null,
+ );
+ }
+
+ const roleLabel = { user: "you", assistant: "assistant", tool: "tool" };
+ function message(item, extraClass = "") {
+ return el("div", { class: `msg ${item.role} ${extraClass}` }, [
+ el("span", { class: "msg-role", text: t(roleLabel[item.role] || "assistant") }),
+ document.createTextNode(item.text),
+ ]);
+ }
+
+ const chatState = { sessionId: null, older: [], olderCursor: undefined };
+
+ async function renderChat(token, sessionId, refresh) {
+ if (chatState.sessionId !== sessionId) Object.assign(chatState, { sessionId, older: [], olderCursor: undefined });
+ const conversation = await api("GET", `/v1/sessions/${encodeURIComponent(sessionId)}`);
+ if (token !== state.renderToken) return;
+ const { session } = conversation;
+ const nextCursor = chatState.olderCursor === undefined ? conversation.messages.nextCursor : chatState.olderCursor;
+ const scroller = document.scrollingElement;
+ const atBottom = !refresh || scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;
+
+ const messages = el("div", { class: "messages" });
+ if (nextCursor) {
+ messages.append(el("button", {
+ type: "button",
+ class: "link",
+ text: t("loadOlder"),
+ onclick: async () => {
+ try {
+ const before = scroller.scrollHeight;
+ const page = await api("GET", `/v1/sessions/${encodeURIComponent(sessionId)}/history?cursor=${encodeURIComponent(nextCursor)}`);
+ chatState.older = [...page.items, ...chatState.older];
+ chatState.olderCursor = page.nextCursor;
+ await render({ refresh: true });
+ scroller.scrollTop += scroller.scrollHeight - before;
+ } catch (error) {
+ fail(error);
+ }
+ },
+ }));
+ }
+ const seen = new Set();
+ for (const item of [...chatState.older, ...conversation.messages.items]) {
+ if (seen.has(item.id)) continue;
+ seen.add(item.id);
+ messages.append(message(item));
+ }
+ if (conversation.liveText) messages.append(message({ role: "assistant", text: conversation.liveText }, "live"));
+
+ const notices = [];
+ if (conversation.waiting === "approval") notices.push(el("p", { class: "banner", role: "status", text: t("waitingApproval") }));
+ if (conversation.waiting === "input") notices.push(el("p", { class: "banner", role: "status", text: t("waitingInput") }));
+ if (session.archived) notices.push(el("p", { class: "banner", text: t("archivedSession") }));
+ if (session.readOnly) notices.push(el("p", { class: "banner", text: t("readOnlySession") }));
+
+ const queue = conversation.queue.length
+ ? el("div", { class: "queue" }, conversation.queue.map((entry) => el("div", { class: "row" }, [
+ el("span", { class: "row-main" }, [el("span", { class: "row-meta", text: t("queued") }), el("span", { class: "row-title", text: entry.text })]),
+ state.me.access.chat
+ ? el("button", { type: "button", "aria-label": t("cancelQueued"), text: "×", onclick: () => api("POST", `/v1/turns/${encodeURIComponent(entry.id)}:cancel`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail) })
+ : null,
+ ])))
+ : null;
+
+ const canChat = state.me.access.chat && !session.readOnly && !session.archived;
+ const composer = canChat ? buildComposer(sessionId, conversation) : null;
+ const actions = organizeActions("sessions", session);
+ const head = header(session.title || t("untitled"), session.projectId ? `#/p/${encodeURIComponent(session.projectId)}` : `#/p/${TEMP}`);
+ if (actions.length) head.append(el("button", { type: "button", "aria-label": t("more", { name: session.title || t("untitled") }), text: "⋯", onclick: () => openSheet(session.title || t("untitled"), actions) }));
+
+ // Preserve focus and the unsent draft across live refreshes.
+ const focused = document.activeElement?.id === "composer-input";
+ const selection = focused ? [document.activeElement.selectionStart, document.activeElement.selectionEnd] : null;
+ app.replaceChildren(head, conversation.modelLabel ? el("p", { class: "row-meta", text: conversation.modelLabel }) : null, messages, ...notices, queue, composer);
+ if (focused) {
+ const input = document.getElementById("composer-input");
+ input?.focus();
+ if (input && selection) input.setSelectionRange(selection[0], selection[1]);
+ }
+ if (atBottom) scroller.scrollTop = scroller.scrollHeight;
+ }
+
+ function buildComposer(sessionId, conversation) {
+ const running = Boolean(conversation.activeTurnId);
+ const input = el("textarea", { id: "composer-input", rows: "2", "aria-label": t("composer"), placeholder: t("composer"), enterkeyhint: "send" });
+ input.value = state.drafts.get(sessionId) || "";
+ const fit = () => { input.style.height = "auto"; input.style.height = `${input.scrollHeight}px`; };
+ input.addEventListener("input", () => { state.drafts.set(sessionId, input.value); fit(); });
+ const submit = async (queue) => {
+ const text = input.value.trim();
+ if (!text || state.sending) return;
+ state.sending = true;
+ try {
+ await api("POST", `/v1/sessions/${encodeURIComponent(sessionId)}/turns`, { text, queue }, newKey());
+ state.drafts.delete(sessionId);
+ input.value = "";
+ await render({ refresh: true });
+ } catch (error) {
+ fail(error);
+ } finally {
+ state.sending = false;
+ }
+ };
+ input.addEventListener("keydown", (event) => {
+ if (event.key !== "Enter" || event.shiftKey || event.isComposing || event.keyCode === 229) return;
+ if (!window.matchMedia("(pointer: fine)").matches && !(event.metaKey || event.ctrlKey)) return;
+ event.preventDefault();
+ void submit(running);
+ });
+ setTimeout(fit, 0);
+ const buttons = el("div", { class: "actions" }, [
+ running
+ ? el("button", { type: "button", text: t("stop"), onclick: () => api("POST", `/v1/turns/${encodeURIComponent(conversation.activeTurnId)}:interrupt`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail) })
+ : null,
+ el("button", { type: "button", class: "primary", text: running ? t("queue") : t("send"), onclick: () => void submit(running) }),
+ ]);
+ return el("div", { class: "composer" }, [input, buttons]);
+ }
+
+ async function render(options = {}) {
+ if (!state.me) return;
+ const token = ++state.renderToken;
+ const route = state.route;
+ try {
+ if (route.view === "projects") await renderProjects(token);
+ else if (route.view === "sessions") await renderSessions(token, route.projectId);
+ else await renderChat(token, route.sessionId, options.refresh === true);
+ } catch (error) {
+ if (token !== state.renderToken) return;
+ if (error instanceof ApiError && error.code === "NOT_FOUND" && route.view !== "projects") {
+ notify(errorText("NOT_FOUND"));
+ go("#/projects");
+ return;
+ }
+ fail(error);
+ }
+ }
+
+ // ---------- pairing ----------
+ function showPair(message) {
+ closeEvents();
+ const code = el("input", { id: "pair-code", class: "code", inputmode: "numeric", autocomplete: "one-time-code", maxlength: "6", required: true });
+ const label = el("input", { id: "pair-label", maxlength: "60", value: /iPhone|iPad|Android/.exec(navigator.userAgent)?.[0] || "Browser" });
+ const status = el("p", { class: "hint", role: "status", text: message || "" });
+ const submit = el("button", { type: "submit", class: "primary", text: t("pairSubmit") });
+ const form = el("form", { class: "pair" }, [
+ el("h1", { text: t("pairTitle") }),
+ el("p", { text: t("pairHint") }),
+ el("label", { for: "pair-code", text: t("codeLabel") }), code,
+ el("label", { for: "pair-label", text: t("deviceLabel") }), label,
+ submit, status,
+ ]);
+ form.addEventListener("submit", async (event) => {
+ event.preventDefault();
+ submit.disabled = true;
+ try {
+ await api("POST", "/pair", { code: code.value.trim(), label: label.value.trim() });
+ status.textContent = t("pairWaiting");
+ await waitForApproval(status);
+ } catch (error) {
+ submit.disabled = false;
+ const codeName = error instanceof ApiError ? error.code : "FAILED";
+ status.textContent = codeName === "PAIRING_CLOSED" ? t("pairClosed") : codeName === "PAIRING_FAILED" ? t("pairFailed") : errorText(codeName);
+ }
+ });
+ app.replaceChildren(form);
+ code.focus();
+ }
+
+ async function waitForApproval(status) {
+ for (;;) {
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ const result = await api("GET", "/pair/status");
+ if (result.state === "paired") return start();
+ status.textContent = t("pairWaiting");
+ }
+ }
+
+ async function signOut() {
+ try {
+ await api("POST", "/v1/logout", {});
+ } catch {
+ // Signed out either way.
+ }
+ state.me = null;
+ showPair();
+ }
+
+ async function start() {
+ try {
+ state.me = await api("GET", "/v1/me");
+ } catch (error) {
+ if (!(error instanceof ApiError && error.code === "UNAUTHORIZED")) showPair(errorText(error instanceof ApiError ? error.code : "FAILED"));
+ else showPair();
+ return;
+ }
+ state.route = parseRoute();
+ openEvents();
+ await render();
+ }
+
+ document.title = t("appTitle");
+ void start();
+})();
diff --git a/apps/desktop/resources/lan-webui/index.html b/apps/desktop/resources/lan-webui/index.html
new file mode 100644
index 000000000..1258181ad
--- /dev/null
+++ b/apps/desktop/resources/lan-webui/index.html
@@ -0,0 +1,24 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <meta name="color-scheme" content="light dark" />
+ <meta name="referrer" content="no-referrer" />
+ <title>PI-Desktop</title>
+ <link rel="stylesheet" href="/styles.css" />
+ <script src="/locale.js" defer></script>
+ <script src="/app.js" defer></script>
+ </head>
+ <body>
+ <div id="offline" class="banner" role="status" hidden></div>
+ <main id="app" aria-live="polite"></main>
+ <div id="toast" class="toast" role="alert" hidden></div>
+ <div id="sheet" class="sheet" hidden>
+ <div class="sheet-panel" role="dialog" aria-modal="true" aria-labelledby="sheet-title">
+ <h2 id="sheet-title" class="sheet-title"></h2>
+ <div id="sheet-actions" class="sheet-actions"></div>
+ </div>
+ </div>
+ </body>
+</html>
diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.js
new file mode 100644
index 000000000..0e245f611
--- /dev/null
+++ b/apps/desktop/resources/lan-webui/locale.js
@@ -0,0 +1,129 @@
+// LAN WebUI copy. English is the source; other locales fall back to it.
+window.LAN_LOCALES = {
+ en: {
+ appTitle: "PI-Desktop",
+ pairTitle: "Pair this device",
+ pairHint: "On the computer, open Settings → System → LAN WebUI, press “Show pairing code”, and enter it here.",
+ codeLabel: "Pairing code",
+ deviceLabel: "Device name",
+ pairSubmit: "Pair",
+ pairWaiting: "Waiting for approval on the computer…",
+ pairFailed: "That code is wrong or expired. Show a new code on the computer.",
+ pairClosed: "Show a pairing code on the computer first.",
+ projects: "Projects",
+ temporary: "Temporary conversations",
+ search: "Search",
+ showArchived: "Archived",
+ noProjects: "No shared projects.",
+ noMatches: "Nothing matches.",
+ noSessions: "No conversations yet.",
+ newSession: "New conversation",
+ untitled: "Untitled",
+ back: "Back",
+ more: "More actions for {name}",
+ rename: "Rename",
+ renamePrompt: "New name",
+ pin: "Pin",
+ unpin: "Unpin",
+ archive: "Archive",
+ restore: "Restore",
+ cancel: "Cancel",
+ pinned: "Pinned",
+ archived: "Archived",
+ running: "Running",
+ waiting: "Waiting",
+ readOnly: "Read-only here",
+ loadOlder: "Load older messages",
+ you: "You",
+ assistant: "Assistant",
+ tool: "Tool",
+ composer: "Message",
+ send: "Send",
+ queue: "Queue",
+ stop: "Stop",
+ queued: "Queued",
+ cancelQueued: "Cancel queued message",
+ waitingApproval: "Waiting for approval on the computer.",
+ waitingInput: "Input needed on the computer.",
+ archivedSession: "This conversation is archived. Restore it to continue.",
+ readOnlySession: "Continue this conversation on the computer.",
+ offline: "Connection lost. Reconnecting…",
+ signOut: "Disconnect this device",
+ errors: {
+ BUSY: "A reply is still running. Queue your message or stop it first.",
+ CONFLICT: "This changed on another device. The latest version is shown; try again.",
+ ARCHIVED: "Restore it first.",
+ READ_ONLY: "Continue this conversation on the computer.",
+ FORBIDDEN: "This device is not allowed to do that.",
+ NOT_FOUND: "This is no longer available.",
+ DESKTOP_UNAVAILABLE: "PI-Desktop is not ready. Try again shortly.",
+ PAYLOAD_TOO_LARGE: "The message is too long.",
+ UNAUTHORIZED: "This device was signed out. Pair again.",
+ FAILED: "Something went wrong. Try again.",
+ NETWORK: "Cannot reach the computer. Check that it is awake and on the same network.",
+ },
+ },
+ "zh-CN": {
+ appTitle: "PI-Desktop",
+ pairTitle: "配对此设备",
+ pairHint: "在电脑上打开 设置 → 系统 → 局域网 WebUI,点击“显示配对码”,然后在这里输入。",
+ codeLabel: "配对码",
+ deviceLabel: "设备名称",
+ pairSubmit: "配对",
+ pairWaiting: "等待电脑上批准…",
+ pairFailed: "配对码错误或已过期,请在电脑上重新显示配对码。",
+ pairClosed: "请先在电脑上显示配对码。",
+ projects: "项目",
+ temporary: "临时会话",
+ search: "搜索",
+ showArchived: "已归档",
+ noProjects: "没有共享的项目。",
+ noMatches: "没有匹配项。",
+ noSessions: "还没有会话。",
+ newSession: "新建会话",
+ untitled: "未命名",
+ back: "返回",
+ more: "{name} 的更多操作",
+ rename: "重命名",
+ renamePrompt: "新名称",
+ pin: "置顶",
+ unpin: "取消置顶",
+ archive: "归档",
+ restore: "恢复",
+ cancel: "取消",
+ pinned: "已置顶",
+ archived: "已归档",
+ running: "运行中",
+ waiting: "等待中",
+ readOnly: "此处只读",
+ loadOlder: "加载更早的消息",
+ you: "你",
+ assistant: "助手",
+ tool: "工具",
+ composer: "消息",
+ send: "发送",
+ queue: "排队",
+ stop: "停止",
+ queued: "排队中",
+ cancelQueued: "取消排队消息",
+ waitingApproval: "等待电脑上审批。",
+ waitingInput: "需要在电脑上输入。",
+ archivedSession: "该会话已归档,恢复后才能继续。",
+ readOnlySession: "请在电脑上继续该会话。",
+ offline: "连接已断开,正在重连…",
+ signOut: "断开此设备",
+ errors: {
+ BUSY: "回复仍在进行。可以排队发送,或先停止。",
+ CONFLICT: "已在其他设备上修改,已显示最新内容,请重试。",
+ ARCHIVED: "请先恢复。",
+ READ_ONLY: "请在电脑上继续该会话。",
+ FORBIDDEN: "此设备没有该权限。",
+ NOT_FOUND: "该内容已不可用。",
+ DESKTOP_UNAVAILABLE: "PI-Desktop 尚未就绪,请稍后重试。",
+ PAYLOAD_TOO_LARGE: "消息过长。",
+ UNAUTHORIZED: "此设备已退出,请重新配对。",
+ FAILED: "出错了,请重试。",
+ NETWORK: "无法连接电脑,请确认电脑已唤醒且在同一网络。",
+ },
+ },
+};
diff --git a/apps/desktop/resources/lan-webui/styles.css b/apps/desktop/resources/lan-webui/styles.css
new file mode 100644
index 000000000..34aaed278
--- /dev/null
+++ b/apps/desktop/resources/lan-webui/styles.css
@@ -0,0 +1,79 @@
+:root {
+ --bg: #f7f7f8;
+ --surface: #ffffff;
+ --text: #17181a;
+ --muted: #5b5f66;
+ --border: #dcdee2;
+ --accent: #2563eb;
+ --on-accent: #ffffff;
+ --danger: #b42318;
+ --user: #e8efff;
+ --radius: 12px;
+ --tap: 44px;
+ font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
+ color: var(--text);
+ background: var(--bg);
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #141416;
+ --surface: #1e1f22;
+ --text: #ececee;
+ --muted: #a3a7ae;
+ --border: #34363b;
+ --accent: #6b9bff;
+ --on-accent: #0b1020;
+ --danger: #ff8a80;
+ --user: #233154;
+ }
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; min-height: 100%; }
+body { overflow-x: hidden; }
+main { max-width: 760px; margin: 0 auto; padding: 0 12px calc(16px + env(safe-area-inset-bottom)); min-height: 100dvh; display: flex; flex-direction: column; }
+:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+button, input, textarea { font: inherit; color: inherit; }
+button { min-height: var(--tap); min-width: var(--tap); padding: 0 14px; border-radius: 10px; border: 1px solid var(--border); background: var(--surface); cursor: pointer; }
+button.primary { background: var(--accent); color: var(--on-accent); border-color: var(--accent); }
+button.danger { color: var(--danger); }
+button:disabled { opacity: .5; cursor: not-allowed; }
+button.link { border: none; background: none; color: var(--accent); }
+input, textarea { width: 100%; min-height: var(--tap); padding: 10px 12px; border-radius: 10px; border: 1px solid var(--border); background: var(--surface); }
+label { display: block; font-weight: 600; margin: 12px 0 6px; }
+.header { position: sticky; top: 0; z-index: 2; display: flex; align-items: center; gap: 8px; padding: calc(8px + env(safe-area-inset-top)) 0 8px; background: var(--bg); }
+.header h1 { flex: 1; min-width: 0; margin: 0; font-size: 18px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.toolbar { display: flex; gap: 8px; align-items: center; margin: 4px 0 8px; }
+.toolbar input[type=search] { flex: 1; }
+.toggle { display: inline-flex; align-items: center; gap: 6px; min-height: var(--tap); font-weight: 400; margin: 0; white-space: nowrap; }
+.toggle input { width: 20px; min-height: 20px; }
+.list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.row { display: flex; align-items: center; gap: 4px; background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); }
+.row-main { flex: 1; min-width: 0; text-align: left; border: none; background: none; padding: 10px 12px; display: flex; flex-direction: column; align-items: flex-start; }
+.row-title { width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
+.row-meta { color: var(--muted); font-size: 14px; display: flex; gap: 8px; flex-wrap: wrap; }
+.row-more { border: none; background: none; font-size: 20px; }
+.empty, .hint { color: var(--muted); text-align: center; padding: 24px 8px; }
+.messages { flex: 1; display: flex; flex-direction: column; gap: 10px; padding: 8px 0 12px; }
+.msg { padding: 10px 12px; border-radius: var(--radius); background: var(--surface); border: 1px solid var(--border); white-space: pre-wrap; word-break: break-word; }
+.msg.user { background: var(--user); align-self: flex-end; max-width: 88%; }
+.msg.tool { color: var(--muted); font-size: 14px; padding: 6px 10px; }
+.msg.live { border-style: dashed; }
+.msg-role { display: block; font-size: 12px; color: var(--muted); margin-bottom: 2px; }
+.banner { padding: 10px 12px; border-radius: var(--radius); background: var(--surface); border: 1px solid var(--border); margin: 6px 0; }
+#offline { position: sticky; top: 0; z-index: 3; margin: 0; border-radius: 0; text-align: center; }
+.queue { display: flex; flex-direction: column; gap: 6px; margin-bottom: 8px; }
+.queue .row { padding-left: 12px; }
+.composer { position: sticky; bottom: 0; background: var(--bg); padding: 8px 0 calc(8px + env(safe-area-inset-bottom)); display: flex; gap: 8px; align-items: flex-end; }
+.composer textarea { flex: 1; resize: none; max-height: 40vh; }
+.composer .actions { display: flex; flex-direction: column; gap: 6px; }
+.toast { position: fixed; left: 12px; right: 12px; bottom: calc(88px + env(safe-area-inset-bottom)); margin: 0 auto; max-width: 520px; padding: 12px 14px; border-radius: var(--radius); background: var(--text); color: var(--bg); z-index: 5; }
+.sheet { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); display: flex; align-items: flex-end; justify-content: center; z-index: 6; }
+.sheet-panel { width: 100%; max-width: 520px; background: var(--surface); border-radius: 16px 16px 0 0; padding: 12px 12px calc(12px + env(safe-area-inset-bottom)); }
+.sheet-title { font-size: 16px; margin: 4px 4px 10px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.sheet-actions { display: flex; flex-direction: column; gap: 8px; }
+.sheet-actions button { width: 100%; }
+.pair { margin: auto 0; padding: 24px 0; }
+.pair h1 { font-size: 22px; }
+.pair .code { letter-spacing: .3em; font-size: 22px; text-align: center; }
+.pair button { width: 100%; margin-top: 16px; }
+@media (prefers-reduced-motion: no-preference) { button { transition: background-color .15s, opacity .15s; } }
diff --git a/apps/desktop/src/components/settings/LanWebUiSection.tsx b/apps/desktop/src/components/settings/LanWebUiSection.tsx
new file mode 100644
index 000000000..301d9054d
--- /dev/null
+++ b/apps/desktop/src/components/settings/LanWebUiSection.tsx
@@ -0,0 +1,183 @@
+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/app/useAppShellRuntime.tsx b/apps/desktop/src/features/app/useAppShellRuntime.tsx
index 36318e323..cb76aef01 100644
--- a/apps/desktop/src/features/app/useAppShellRuntime.tsx
+++ b/apps/desktop/src/features/app/useAppShellRuntime.tsx
@@ -41,6 +41,7 @@ import {
pluginWorkPanelTab,
} from "../../lib/work-panel-tabs";
import { useAppStore } from "../../stores/app-store";
+import { subscribeLanCatalogSync } from "../lan-webui/lan-catalog-sync";
import { useSidebarTransition } from "./useSidebarTransition";
import { useStartupAnimation } from "./useStartupAnimation";
import { useStartupWatchdog } from "./useStartupWatchdog";
@@ -818,6 +819,7 @@ export function useAppShellRuntime() {
.catch(() => undefined);
});
const offRemoteInteractions = subscribeRemoteInteractions();
+ const offLanCatalog = subscribeLanCatalogSync();
const offSessionsChanged = api.onSessionsChanged((event) => {
const store = useAppStore.getState();
const revealImportedProjects =
@@ -996,6 +998,7 @@ export function useAppShellRuntime() {
offComposerSuggestion();
offSessionsChanged();
offRemoteInteractions();
+ offLanCatalog();
offNotificationActivated();
window.removeEventListener("keydown", onKey);
};
diff --git a/apps/desktop/src/features/lan-webui/lan-catalog-sync.ts b/apps/desktop/src/features/lan-webui/lan-catalog-sync.ts
new file mode 100644
index 000000000..e44fa494c
--- /dev/null
+++ b/apps/desktop/src/features/lan-webui/lan-catalog-sync.ts
@@ -0,0 +1,52 @@
+import type { LanCatalogChangedEvent, LanOrganizationPatch } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { saveSidebarPreferences } from "../../lib/sidebar-preferences";
+import { preferencesFromState } from "../../stores/helpers/store-helpers";
+import { useAppStore } from "../../stores/app-store";
+
+/**
+ * Apply one organization edit made from a paired browser through the same
+ * store actions the sidebar uses. Never selects or navigates.
+ */
+export function applyLanOrganizationPatch(entry: LanOrganizationPatch): void {
+ const store = useAppStore.getState();
+ if (entry.kind === "project") {
+ const { name, pinned, archived } = entry.patch;
+ if (name !== undefined) store.renameProject(entry.key, name);
+ if (pinned !== undefined) store.toggleProjectPinned(entry.key, pinned);
+ if (archived === true) store.archiveProject(entry.key);
+ if (archived === false) store.restoreProject(entry.key);
+ return;
+ }
+ const { pinned, archived, manualTitle } = entry.patch;
+ if (pinned !== undefined && (store.sessionMeta[entry.key]?.pinned === true) !== pinned) {
+ store.toggleSessionPinned(entry.key);
+ }
+ if (archived === true) store.archiveSession(entry.key);
+ if (archived === false) store.restoreSession(entry.key);
+ if (manualTitle !== undefined) {
+ useAppStore.setState((state) => ({
+ sessionMeta: {
+ ...state.sessionMeta,
+ [entry.key]: { ...(state.sessionMeta[entry.key] ?? {}), manualTitle },
+ },
+ }));
+ saveSidebarPreferences(preferencesFromState(useAppStore.getState()));
+ }
+}
+
+/** Subscribe the Desktop shell to browser organization edits. */
+export function subscribeLanCatalogSync(): () => void {
+ return api.onLanWebUiCatalogChanged((event: LanCatalogChangedEvent) => {
+ for (const entry of event.patches ?? []) {
+ try {
+ applyLanOrganizationPatch(entry);
+ } catch {
+ // A malformed edit must not break the shell; Main keeps it pending.
+ }
+ }
+ // The sidebar writes above are ordered before this acknowledgement.
+ void api.lanWebUiAdmin({ kind: "ack", seq: event.seq }).catch(() => undefined);
+ void useAppStore.getState().refreshSessions().catch(() => undefined);
+ });
+}
diff --git a/apps/desktop/src/features/settings/pages/SystemSettings.tsx b/apps/desktop/src/features/settings/pages/SystemSettings.tsx
index bbd312c4a..cd543bd0a 100644
--- a/apps/desktop/src/features/settings/pages/SystemSettings.tsx
+++ b/apps/desktop/src/features/settings/pages/SystemSettings.tsx
@@ -10,6 +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 { CloseBehaviorSection } from "../developer-sections";
import { SettingsCard, SettingsRow } from "../primitives";
import { StorageSettingsSection } from "../StorageSettingsSection";
@@ -28,6 +29,8 @@ export function SystemSettings({
<div className="settings-stack">
<NetworkProxySection settings={settings} saveSettings={saveSettings} />
+ <LanWebUiSection />
+
<StorageSettingsSection />
<SettingsCard title={t("settings.power")}>
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 59b30ba54..653fa6cdc 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1,4 +1,4 @@
-import type { ReviewContextLines, ReviewContextResult, ReviewTurnsPage, ReviewChangesPage } from "@pi-desktop/shared";
+import type { LanAdminAction, LanAdminView, LanCatalogChangedEvent, ReviewContextLines, ReviewContextResult, ReviewTurnsPage, ReviewChangesPage } from "@pi-desktop/shared";
type ClipboardDirectoryPaste = {
items: Array<{ kind: "directory"; path: string; name: string } | { kind: "file"; name: string }>;
token: string | null;
@@ -972,6 +972,15 @@ export const api = {
configSyncDisconnect: () => invoke<ConfigSyncState>(IPC.invoke.configSyncDisconnect),
testNetworkProxy: (settings: unknown) =>
invoke<{ ok: boolean; error?: string }>(IPC.invoke.networkProxyTest, settings),
+ /** Desktop administration of the LAN WebUI (pairing, devices, listener). */
+ lanWebUiAdmin: (action: LanAdminAction) => invoke<LanAdminView>(IPC.invoke.lanWebUiAdmin, action),
+ /** Organization edits made from a paired browser; apply, then acknowledge. */
+ onLanWebUiCatalogChanged: (listener: (event: LanCatalogChangedEvent) => void) => {
+ if (!window.piDesktop?.on) return () => undefined;
+ return window.piDesktop.on(IPC.event.lanWebUiCatalogChanged, (payload) =>
+ listener(payload as LanCatalogChangedEvent),
+ );
+ },
/** Installed system font families (Electron main, cached briefly). */
listSystemFonts: () => invoke<string[]>(IPC.invoke.systemFontsList),
listCommandShells: () =>
diff --git a/apps/desktop/src/locales/lan.ts b/apps/desktop/src/locales/lan.ts
new file mode 100644
index 000000000..b3c8b1b51
--- /dev/null
+++ b/apps/desktop/src/locales/lan.ts
@@ -0,0 +1,82 @@
+/** 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",
+ port: "Port",
+ start: "Start",
+ stop: "Stop",
+ url: "Address",
+ 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",
+ organize: "Rename, pin and archive",
+ allow: "Allow",
+ deny: "Deny",
+ devices: "Paired devices",
+ noDevices: "No paired devices.",
+ lastActive: "Last active {{time}}",
+ revoke: "Revoke",
+ scope: "{{count}} projects",
+ 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.",
+ FAILED: "The action failed. Try again.",
+ },
+};
+
+export const lanZh: typeof lanEn = {
+ title: "局域网 WebUI",
+ caption: "应用运行时,可在同一网络的浏览器或手机上使用这台电脑上的会话。",
+ description: "通过局域网 HTTP 访问。只有已配对的设备能看到你共享的项目;工具审批仍在这台电脑上完成。停止服务会让所有设备退出。",
+ status: "状态",
+ running: "运行中",
+ stopped: "已关闭",
+ address: "网络",
+ port: "端口",
+ start: "启动",
+ stop: "停止",
+ url: "访问地址",
+ copy: "复制",
+ copied: "已复制",
+ pairing: "配对码",
+ pairingHint: "在另一台设备打开访问地址并输入此码。仅可使用一次,5 分钟后失效。",
+ newCode: "显示配对码",
+ pending: "等待批准",
+ pendingHint: "选择 {{label}} 可以访问的内容,然后允许。",
+ projects: "共享的项目",
+ noProjects: "还没有项目。",
+ temporary: "临时会话",
+ chat: "发送消息和新建会话",
+ organize: "重命名、置顶和归档",
+ allow: "允许",
+ deny: "拒绝",
+ devices: "已配对设备",
+ noDevices: "暂无已配对设备。",
+ lastActive: "最近活动 {{time}}",
+ revoke: "撤销",
+ scope: "{{count}} 个项目",
+ errors: {
+ PORT_IN_USE: "该端口已被占用,请换一个端口。",
+ INVALID_ADDRESS: "该网络地址已不可用。",
+ NOT_RUNNING: "请先启动服务。",
+ NOT_FOUND: "该配对请求已失效。",
+ RATE_LIMITED: "设备过多,请先撤销一台。",
+ FAILED: "操作失败,请重试。",
+ },
+};
diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx
index f7a369363..44982c3cb 100644
--- a/apps/desktop/src/main.tsx
+++ b/apps/desktop/src/main.tsx
@@ -5,6 +5,7 @@ import { initReactI18next } from "react-i18next";
import { flattenCatalog } from "@pi-desktop/i18n/locale-info";
import { en } from "@pi-desktop/i18n/locales/en";
import { remoteEn, remoteZh } from "./locales/remote";
+import { lanEn, lanZh } from "./locales/lan";
import { MAC_TRAFFIC_LIGHT_EDGE_DIP } from "@pi-desktop/shared";
import App from "./App";
import { ErrorBoundary, RoutePending } from "./features/app/chrome";
@@ -81,12 +82,13 @@ async function startRenderer(): Promise<void> {
resources: {
en: {
remote: remoteEn,
+ lan: lanEn,
translation: flattenCatalog(
en as unknown as Record<string, unknown>,
),
},
- "zh-CN": { remote: remoteZh },
- "zh-TW": { remote: remoteZh },
+ "zh-CN": { remote: remoteZh, lan: lanZh },
+ "zh-TW": { remote: remoteZh, lan: lanZh },
},
interpolation: { escapeValue: false },
});
diff --git a/apps/desktop/test/helpers/lan-webui-fixture.mjs b/apps/desktop/test/helpers/lan-webui-fixture.mjs
new file mode 100644
index 000000000..5dd1e9d32
--- /dev/null
+++ b/apps/desktop/test/helpers/lan-webui-fixture.mjs
@@ -0,0 +1,139 @@
+import { register } from "node:module";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "ts-import-hooks.mjs")));
+const { createLanWorkspace } = await import("../../electron/main/lan-webui/workspace.ts");
+export const { createLanServer } = await import("../../electron/main/lan-webui/server.ts");
+
+/** A fake Desktop: host-core catalog, Agent Host bridge and internal IPC. */
+export function desktop() {
+ const groups = [
+ { id: "g-a", name: "Alpha", primaryPath: "/work/a", roots: [{ path: "/work/a", name: "a", position: 0 }], pinned: false, lastOpenedAt: 2, createdAt: 0, updatedAt: 0 },
+ { id: "g-b", name: "Beta", primaryPath: "/work/b", roots: [{ path: "/work/b", name: "b", position: 0 }, { path: "/work/b2", name: "b2", position: 1 }], pinned: false, lastOpenedAt: 1, createdAt: 0, updatedAt: 0 },
+ { id: "g-r", name: "Remote", primaryPath: "/remote", roots: [], pinned: false, lastOpenedAt: 3, createdAt: 0, updatedAt: 0, remote: { hostKey: "h", path: "/x" } },
+ ];
+ const sessions = [
+ { id: "s-a1", title: "Fix login", projectPath: "/work/a", mode: "agent", updatedAt: "2026-11-01" },
+ { id: "s-b1", title: "Second root chat", projectPath: "/work/b2", mode: "agent", updatedAt: "2026-11-02" },
+ { id: "s-plan", title: "A plan", projectPath: "/work/a", mode: "plan", updatedAt: "2026-10-01" },
+ { id: "s-tmp", title: "Scratch", projectPath: null, mode: "agent", updatedAt: "2026-11-03" },
+ ];
+ const meta = { projectMeta: {}, sessionMeta: {} };
+ const calls = [];
+ const turns = [];
+ const activeTurns = new Map();
+ const queue = new Map();
+ let created = 0;
+ const host = {
+ async call(method, params) {
+ if (method === "project.groups.list") return { groups };
+ if (method === "session.list") return { sessions };
+ if (method === "session.get") {
+ const session = sessions.find((s) => s.id === params.id);
+ return {
+ session: session && {
+ ...session,
+ messageStart: 0,
+ hasMoreBefore: false,
+ messages: [
+ { id: "m1", role: "user", content: "hello" },
+ { id: "m2", role: "assistant", content: "hi there" },
+ { id: "m3", role: "tool", content: "/secret/path output", toolName: "Bash" },
+ { id: "m4", role: "assistant", content: "nested", parentToolCallId: "t1" },
+ ],
+ },
+ };
+ }
+ throw new Error(`unexpected host call ${method}`);
+ },
+ };
+ const bridge = {
+ agentHost: {
+ async startTurn(principal, params) {
+ turns.push({ principal, params });
+ if (activeTurns.has(params.sessionId) && params.admission === "reject_if_busy") {
+ throw Object.assign(new Error("busy"), { code: "AGENT_BUSY" });
+ }
+ const id = `turn-${turns.length}`;
+ if (activeTurns.has(params.sessionId)) queue.set(params.sessionId, [...(queue.get(params.sessionId) ?? []), { id, content: params.input.text }]);
+ else activeTurns.set(params.sessionId, `run-${id}`);
+ return { turn: { id } };
+ },
+ },
+ queue: {
+ list: (sessionId) => queue.get(sessionId) ?? [],
+ async remove(turnId) {
+ for (const [key, entries] of queue) queue.set(key, entries.filter((entry) => entry.id !== turnId));
+ },
+ },
+ pendingInteractiveRequests: async (sessionId) => ({ asks: [], permissions: sessionId === "s-b1" ? [{}] : [] }),
+ };
+ const organization = {
+ read: () => structuredClone(meta),
+ patch(entry) {
+ const bucket = entry.kind === "project" ? meta.projectMeta : meta.sessionMeta;
+ bucket[entry.key] = { ...(bucket[entry.key] ?? {}), ...entry.patch };
+ },
+ };
+ const workspace = createLanWorkspace({
+ getHost: () => host,
+ getBridge: () => bridge,
+ channels: { sessionCreate: "create", sessionRename: "rename", projectGroupRename: "groupRename", agentAbort: "abort" },
+ activeTurns,
+ organization,
+ notifyDesktop: (sessionId) => calls.push(["notify", sessionId ?? null]),
+ async invoke(channel, args) {
+ calls.push([channel, args]);
+ if (channel === "create") {
+ const id = `s-new-${++created}`;
+ sessions.push({ id, title: "", projectPath: args[0].projectPath ?? null, mode: "agent", updatedAt: "2026-11-09" });
+ return { session: { id } };
+ }
+ if (channel === "rename") {
+ const session = sessions.find((s) => s.id === args[0]);
+ session.title = args[1];
+ return {};
+ }
+ if (channel === "abort") {
+ activeTurns.delete(args[0].sessionId);
+ return { ok: true };
+ }
+ return {};
+ },
+ });
+ return { workspace, calls, turns, activeTurns, queue, meta, sessions };
+}
+
+/** A tiny cookie-keeping browser against the real HTTP listener. */
+export function browser(origin) {
+ const jar = new Map();
+ let csrf = "";
+ 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 (method === "POST") {
+ headers["Content-Type"] = "application/json";
+ if (csrf && !("X-CSRF-Token" in extra)) headers["X-CSRF-Token"] = csrf;
+ }
+ const response = await fetch(`${origin}${path}`, { method, headers, body: method === "POST" ? JSON.stringify(body ?? {}) : undefined });
+ for (const raw of response.headers.getSetCookie()) {
+ const [pair] = raw.split(";");
+ const [name, value] = pair.split("=");
+ if (value) jar.set(name, value);
+ else jar.delete(name);
+ }
+ const text = await response.text();
+ return { status: response.status, body: text ? JSON.parse(text) : null };
+ };
+ return {
+ request,
+ async signIn() {
+ const me = await request("GET", "/v1/me");
+ csrf = me.body.csrf;
+ return me;
+ },
+ };
+}
+
diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
new file mode 100644
index 000000000..99e547898
--- /dev/null
+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
@@ -0,0 +1,143 @@
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+import { createLanServer, desktop } from "./helpers/lan-webui-fixture.mjs";
+
+const here = dirname(fileURLToPath(import.meta.url));
+const resources = join(here, "../resources/lan-webui");
+
+async function assets() {
+ const read = (name) => readFile(join(resources, name), "utf8");
+ return new Map([
+ ["/index.html", { type: "text/html; charset=utf-8", body: await read("index.html") }],
+ ["/app.js", { type: "text/javascript; charset=utf-8", body: await read("app.js") }],
+ ["/locale.js", { type: "text/javascript; charset=utf-8", body: await read("locale.js") }],
+ ["/styles.css", { type: "text/css; charset=utf-8", body: await read("styles.css") }],
+ ]);
+}
+
+/** Runs inside the page: the phone user's journey, reported as JSON. */
+const journey = String.raw`(async () => {
+ const wait = async (fn, label) => {
+ for (let i = 0; i < 200; i += 1) {
+ const value = fn();
+ if (value) return value;
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ throw new Error("timed out waiting for " + label);
+ };
+ const rowByTitle = (title) => [...document.querySelectorAll(".row")].find((row) => row.querySelector(".row-title")?.textContent === title);
+ const result = {};
+
+ // Pair with the code shown on Desktop.
+ const code = await wait(() => document.getElementById("pair-code"), "pair form");
+ code.value = window.__code;
+ document.querySelector(".pair button[type=submit]").click();
+
+ // Desktop approves; the shared projects appear (the unshared one does not).
+ await wait(() => rowByTitle("Alpha"), "projects");
+ result.projects = [...document.querySelectorAll(".row-title")].map((n) => n.textContent);
+
+ // Open a project and see its sessions.
+ rowByTitle("Alpha").querySelector(".row-main").click();
+ await wait(() => rowByTitle("Fix login"), "sessions");
+ result.sessions = [...document.querySelectorAll(".row-title")].map((n) => n.textContent);
+ result.projectHash = location.hash;
+
+ // Organize from the row menu: pin.
+ rowByTitle("Fix login").querySelector(".row-more").click();
+ await wait(() => !document.getElementById("sheet").hidden, "sheet");
+ document.querySelectorAll("#sheet-actions button")[1].click();
+ await wait(() => rowByTitle("Fix login")?.querySelector(".row-meta"), "pinned meta");
+ result.pinnedMeta = rowByTitle("Fix login").querySelector(".row-meta").textContent;
+
+ // Create a new conversation in this project and send a message.
+ document.querySelector("main > button.primary").click();
+ const input = await wait(() => document.getElementById("composer-input"), "composer");
+ result.chatHash = location.hash;
+ input.value = "hello from phone";
+ input.dispatchEvent(new Event("input"));
+ document.querySelector(".composer button.primary").click();
+ await wait(() => document.querySelectorAll(".msg").length >= 2 && input.isConnected === false || document.getElementById("composer-input")?.value === "", "sent");
+ result.messages = [...document.querySelectorAll(".msg")].map((n) => n.className.split(" ")[1]);
+ result.leaked = document.body.textContent.includes("/secret/path");
+
+ // Phone layout: no horizontal scroll and touch-sized controls.
+ result.horizontalScroll = document.documentElement.scrollWidth > window.innerWidth;
+ result.smallTargets = [...document.querySelectorAll("button")].filter((b) => b.offsetParent && b.getBoundingClientRect().height < 44).length;
+
+ // Back returns to the project's session list.
+ history.back();
+ await wait(() => rowByTitle("Fix login"), "back to sessions");
+ result.backHash = location.hash;
+ return JSON.stringify(result);
+})()`;
+
+test("a phone pairs, organizes, creates and sends through the real page", { timeout: 60_000 }, async (t) => {
+ const { electronBinary } = resolveElectronBinary();
+ const fake = desktop();
+ const server = createLanServer({ handler: fake.workspace, assets: await assets() });
+ const { port } = await server.start("127.0.0.1", 0);
+ server.issueCode();
+ const code = server.code().value;
+ // Desktop-side approval as soon as the phone asks.
+ const approver = setInterval(() => {
+ const [pending] = server.pending();
+ if (pending) server.confirm(pending.id, { projectIds: ["g-a"], temporary: false, chat: true, organize: true });
+ }, 50);
+ const temp = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "lan-webui-ui-"));
+ t.after(async () => {
+ clearInterval(approver);
+ await server.stop();
+ fake.workspace.dispose();
+ await rm(temp, { recursive: true, force: true });
+ });
+ await writeFile(join(temp, "main.cjs"), `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+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 } });
+ try {
+ 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");
+ app.exit(0);
+ } catch (error) {
+ process.stderr.write(String(error && error.stack || error) + "\\n");
+ app.exit(1);
+ }
+});
+`);
+ const child = spawn(electronBinary, [join(temp, "main.cjs")], { env: { ...process.env, ELECTRON_ENABLE_LOGGING: "0" } });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.on("data", (chunk) => (stdout += chunk));
+ child.stderr.on("data", (chunk) => (stderr += chunk));
+ const exitCode = await new Promise((resolve) => child.on("close", resolve));
+ assert.equal(exitCode, 0, stderr);
+ const line = stdout.split("\n").find((entry) => entry.startsWith("RESULT "));
+ assert.ok(line, stdout + stderr);
+ const result = JSON.parse(line.slice(7));
+
+ assert.deepEqual(result.projects, ["Alpha"]);
+ assert.deepEqual(result.sessions, ["Fix login", "A plan"]);
+ assert.equal(result.projectHash, "#/p/g-a");
+ assert.ok(result.pinnedMeta.length > 0, "the pinned label is shown");
+ assert.equal(fake.meta.sessionMeta["s-a1"].pinned, true);
+ assert.match(result.chatHash, /^#\/s\/s-new-1$/);
+ assert.equal(fake.turns.length, 1);
+ assert.equal(fake.turns[0].params.input.text, "hello from phone");
+ assert.equal(fake.turns[0].params.sessionId, "s-new-1");
+ assert.ok(result.messages.includes("user") && result.messages.includes("assistant"));
+ assert.equal(result.leaked, false);
+ assert.equal(result.horizontalScroll, false);
+ assert.equal(result.smallTargets, 0);
+ assert.equal(result.backHash, "#/p/g-a");
+});
diff --git a/apps/desktop/test/lan-webui-organization.test.mjs b/apps/desktop/test/lan-webui-organization.test.mjs
new file mode 100644
index 000000000..21d04fe6c
--- /dev/null
+++ b/apps/desktop/test/lan-webui-organization.test.mjs
@@ -0,0 +1,76 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { register } from "node:module";
+import { dirname } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
+const { createLanOrganization } = await import("../electron/main/lan-webui/organization.ts");
+const { writeSidebarBackup } = await import("../electron/main/sidebar-preferences.ts");
+
+function profile() {
+ const dataDir = mkdtempSync(join(tmpdir(), "lan-org-"));
+ writeSidebarBackup(dataDir, {
+ openProjectPaths: ["/work/a"],
+ projectMeta: { "/work/a": { name: "Alpha", collapsed: true } },
+ sessionMeta: { s1: { pinned: true, order: 3 } },
+ sessionView: { sort: "recent", archived: false },
+ projectSort: "recent",
+ });
+ return { dataDir, read: () => JSON.parse(readFileSync(join(dataDir, "sidebar-preferences.json"), "utf8")) };
+}
+
+test("a browser edit is durable and keeps unrelated Desktop preferences", (t) => {
+ const { dataDir, read } = profile();
+ t.after(() => rmSync(dataDir, { recursive: true, force: true }));
+ const events = [];
+ const organization = createLanOrganization({ dataDir, notify: (event) => events.push(event) });
+
+ organization.patch({ kind: "session", key: "s1", patch: { archived: true } });
+ organization.patch({ kind: "project", key: "/work/a/", patch: { pinned: true } });
+
+ const disk = read();
+ assert.deepEqual(disk.sessionMeta.s1, { pinned: true, order: 3, archived: true });
+ assert.deepEqual(disk.projectMeta["/work/a"], { name: "Alpha", collapsed: true, pinned: true });
+ assert.deepEqual(disk.openProjectPaths, ["/work/a"]);
+ assert.deepEqual(events.map((event) => event.seq), [1, 2]);
+ assert.equal(organization.read().sessionMeta.s1.archived, true);
+});
+
+test("a stale renderer snapshot cannot undo an unacknowledged browser edit", (t) => {
+ const { dataDir } = profile();
+ t.after(() => rmSync(dataDir, { recursive: true, force: true }));
+ const organization = createLanOrganization({ dataDir });
+ const stale = {
+ openProjectPaths: ["/work/a"],
+ projectMeta: { "/work/a": { name: "Alpha" } },
+ sessionMeta: { s1: { pinned: true }, s2: { pinned: true } },
+ sessionView: { sort: "recent", archived: false },
+ };
+
+ organization.patch({ kind: "session", key: "s1", patch: { pinned: false } });
+ const merged = organization.overlay(stale);
+ assert.equal(merged.sessionMeta.s1.pinned, false, "the browser edit wins over the stale write");
+ assert.equal(merged.sessionMeta.s2.pinned, true, "other Desktop changes in the snapshot are kept");
+ assert.equal(stale.sessionMeta.s1.pinned, true, "the caller's object is not mutated");
+
+ // After the renderer acknowledges, its later snapshots are authoritative again.
+ organization.ack(1);
+ assert.equal(organization.pendingCount(), 0);
+ assert.equal(organization.overlay(stale).sessionMeta.s1.pinned, true);
+});
+
+test("a missing or damaged backup is never replaced from a browser edit", (t) => {
+ const dataDir = mkdtempSync(join(tmpdir(), "lan-org-empty-"));
+ t.after(() => rmSync(dataDir, { recursive: true, force: true }));
+ const organization = createLanOrganization({ dataDir });
+ organization.patch({ kind: "session", key: "s9", patch: { archived: true } });
+ assert.throws(() => readFileSync(join(dataDir, "sidebar-preferences.json")), /ENOENT/);
+ // The edit stays pending and is applied to the first renderer write.
+ const first = organization.overlay({ openProjectPaths: [], projectMeta: {}, sessionMeta: {}, sessionView: {} });
+ assert.equal(first.sessionMeta.s9.archived, true);
+});
diff --git a/apps/desktop/test/lan-webui-user-path.test.mjs b/apps/desktop/test/lan-webui-user-path.test.mjs
new file mode 100644
index 000000000..41b270046
--- /dev/null
+++ b/apps/desktop/test/lan-webui-user-path.test.mjs
@@ -0,0 +1,144 @@
+import assert from "node:assert/strict";
+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) {
+ const fake = desktop();
+ const server = createLanServer({ handler: 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();
+ fake.workspace.dispose();
+ });
+ const origin = `http://127.0.0.1:${port}`;
+ const phone = browser(origin);
+ server.issueCode();
+ const code = server.code().value;
+ assert.equal((await phone.request("POST", "/pair", { code, label: "iPhone" })).status, 200);
+ assert.equal((await phone.request("GET", "/pair/status")).body.state, "pending");
+ assert.equal((await phone.request("GET", "/v1/me")).status, 401, "no data before Desktop confirms");
+ const [pending] = server.pending();
+ assert.equal(pending.label, "iPhone");
+ server.confirm(pending.id, grants);
+ assert.equal((await phone.request("GET", "/pair/status")).body.state, "paired");
+ await phone.signIn();
+ return { ...fake, server, phone, origin };
+}
+
+test("pair, browse shared projects, create, chat and organize from a phone", async (t) => {
+ const { phone, calls, turns, activeTurns, meta, server } = await setup(t, { projectIds: ["g-a", "g-b"], temporary: false, chat: true, organize: true });
+
+ // Only the shared local projects are listed; remote and unshared ones are not.
+ const projects = await phone.request("GET", "/v1/projects?q=");
+ assert.deepEqual(projects.body.items.map((p) => p.id), ["g-a", "g-b"]);
+
+ // A session on a secondary root belongs to its logical group.
+ const beta = await phone.request("GET", "/v1/sessions?projectId=g-b");
+ assert.deepEqual(beta.body.items.map((s) => s.id), ["s-b1"]);
+ const alpha = await phone.request("GET", "/v1/sessions?projectId=g-a");
+ assert.deepEqual(alpha.body.items.map((s) => [s.id, s.readOnly]), [["s-a1", false], ["s-plan", true]]);
+
+ // Conversation projection: no tool output, no nested subagent rows.
+ const chat = await phone.request("GET", "/v1/sessions/s-a1");
+ assert.deepEqual(chat.body.messages.items.map((m) => [m.role, m.text]), [["user", "hello"], ["assistant", "hi there"], ["tool", "Bash"]]);
+ assert.equal(JSON.stringify(chat.body).includes("/secret/path"), false);
+ assert.equal((await phone.request("GET", "/v1/sessions/s-b1")).body.waiting, "approval");
+
+ // New session in the explicit project; a double tap with the same key creates one.
+ const key = "create-key-123";
+ const first = await phone.request("POST", "/v1/sessions", { projectId: "g-b" }, { "Idempotency-Key": key });
+ const again = await phone.request("POST", "/v1/sessions", { projectId: "g-b" }, { "Idempotency-Key": key });
+ assert.equal(first.body.id, again.body.id);
+ assert.equal(calls.filter(([c]) => c === "create").length, 1);
+ assert.deepEqual(calls.find(([c]) => c === "create")[1], [{ projectPath: "/work/b" }]);
+
+ // Send runs under a non-owner principal; busy sessions reject unless queued.
+ const sent = await phone.request("POST", `/v1/sessions/${first.body.id}/turns`, { text: "hi" }, { "Idempotency-Key": "send-key-0001" });
+ assert.equal(sent.status, 200);
+ assert.deepEqual(turns[0].principal, { subject: turns[0].principal.subject, roles: ["viewer", "controller"], pairedDevice: false });
+ const busy = await phone.request("POST", `/v1/sessions/${first.body.id}/turns`, { text: "again" });
+ assert.deepEqual([busy.status, busy.body.code], [409, "BUSY"]);
+ const queued = await phone.request("POST", `/v1/sessions/${first.body.id}/turns`, { text: "later", queue: true });
+ const conversation = await phone.request("GET", `/v1/sessions/${first.body.id}`);
+ assert.deepEqual(conversation.body.queue.map((q) => q.text), ["later"]);
+ assert.equal((await phone.request("POST", `/v1/turns/${queued.body.id}:cancel`, { sessionId: first.body.id })).body.canceled, true);
+ const runId = activeTurns.get(first.body.id);
+ assert.equal((await phone.request("POST", `/v1/turns/${encodeURIComponent(runId)}:interrupt`, { sessionId: first.body.id })).body.stopped, true);
+
+ // Read-only sessions cannot be sent to from the browser.
+ assert.equal((await phone.request("POST", "/v1/sessions/s-plan/turns", { text: "x" })).body.code, "READ_ONLY");
+
+ // Organize with optimistic revisions; a stale revision is a conflict.
+ const before = (await phone.request("GET", "/v1/sessions?projectId=g-a")).body.items.find((s) => s.id === "s-a1");
+ assert.equal((await phone.request("POST", "/v1/sessions/s-a1/organize", { revision: before.revision, pinned: true })).status, 200);
+ assert.equal(meta.sessionMeta["s-a1"].pinned, true);
+ const stale = await phone.request("POST", "/v1/sessions/s-a1/organize", { revision: before.revision, archived: true });
+ assert.deepEqual([stale.status, stale.body.code], [409, "CONFLICT"]);
+ const current = (await phone.request("GET", "/v1/sessions?projectId=g-a")).body.items.find((s) => s.id === "s-a1");
+ await phone.request("POST", "/v1/sessions/s-a1/organize", { revision: current.revision, name: "Fix login flow" });
+ assert.deepEqual(calls.find(([c]) => c === "rename")[1], ["s-a1", "Fix login flow"]);
+ assert.equal(meta.sessionMeta["s-a1"].manualTitle, true);
+
+ // Archive is reversible and hides the session from the default list.
+ const renamed = (await phone.request("GET", "/v1/sessions?projectId=g-a")).body.items.find((s) => s.id === "s-a1");
+ await phone.request("POST", "/v1/sessions/s-a1/organize", { revision: renamed.revision, archived: true });
+ assert.deepEqual((await phone.request("GET", "/v1/sessions?projectId=g-a")).body.items.map((s) => s.id), ["s-plan"]);
+ assert.deepEqual((await phone.request("GET", "/v1/sessions?projectId=g-a&archived=1")).body.items.map((s) => s.id), ["s-a1"]);
+ const project = (await phone.request("GET", "/v1/projects")).body.items[0];
+ await phone.request("POST", "/v1/projects/g-a/organize", { revision: project.revision, pinned: true });
+ assert.equal(meta.projectMeta["/work/a"].pinned, true);
+ assert.ok(calls.some(([c]) => c === "notify"), "Desktop was told to refresh without navigating");
+
+ // Revoking the device ends access immediately.
+ server.revoke(server.devices()[0].id);
+ assert.equal((await phone.request("GET", "/v1/projects")).status, 401);
+});
+
+test("scope, grants and request guards fail closed", async (t) => {
+ const { phone, origin, server } = await setup(t, { projectIds: ["g-a"], temporary: false, chat: false, organize: false });
+
+ for (const path of ["/v1/sessions?projectId=g-b", "/v1/sessions/s-b1", "/v1/sessions/s-tmp", "/v1/sessions?projectId=__temporary__"]) {
+ assert.equal((await phone.request("GET", path)).status, 404, path);
+ }
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" })).body.code, "FORBIDDEN");
+ assert.equal((await phone.request("POST", "/v1/sessions/s-a1/turns", { text: "x" })).body.code, "FORBIDDEN");
+ const session = (await phone.request("GET", "/v1/sessions?projectId=g-a")).body.items[0];
+ assert.equal((await phone.request("POST", `/v1/sessions/${session.id}/organize`, { revision: session.revision, pinned: true })).body.code, "FORBIDDEN");
+
+ // Missing CSRF, foreign Origin and a wrong Host are rejected.
+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, { "X-CSRF-Token": "" })).body.code, "CSRF");
+ assert.equal((await phone.request("GET", "/v1/projects", null, { Origin: "http://evil.example" })).body.code, "FORBIDDEN_ORIGIN");
+ // fetch() refuses to send a custom Host, so use a raw request for rebinding.
+ const rebinding = await new Promise((resolve, reject) => {
+ const url = new URL(`${origin}/v1/projects`);
+ request({ host: url.hostname, port: url.port, path: url.pathname, headers: { Host: "evil.example" } }, (response) => {
+ response.resume();
+ resolve(response.statusCode);
+ }).on("error", reject).end();
+ });
+ assert.equal(rebinding, 403);
+
+ // A wrong code burns attempts and then closes pairing.
+ server.issueCode();
+ const stranger = browser(origin);
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ assert.equal((await stranger.request("POST", "/pair", { code: "000000x", label: "x" })).body.code, "PAIRING_FAILED");
+ }
+ assert.equal(server.code(), null);
+ assert.equal((await stranger.request("POST", "/pair", { code: "123456", label: "x" })).body.code, "PAIRING_CLOSED");
+
+ // Stopping signs every device out.
+ await server.stop();
+ await server.start("127.0.0.1", 0);
+ assert.equal(server.devices().length, 0);
+});
+
+test("temporary conversations need their own grant", async (t) => {
+ const { phone, calls } = await setup(t, { projectIds: [], temporary: true, chat: true, organize: false });
+ assert.deepEqual((await phone.request("GET", "/v1/sessions?projectId=__temporary__")).body.items.map((s) => s.id), ["s-tmp"]);
+ assert.equal((await phone.request("GET", "/v1/sessions/s-a1")).status, 404);
+ const created = await phone.request("POST", "/v1/sessions", { projectId: null });
+ assert.equal(created.status, 200);
+ assert.deepEqual(calls.find(([c]) => c === "create")[1], [{}], "no project is inherited");
+});
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
new file mode 100644
index 000000000..0061d6a96
--- /dev/null
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -0,0 +1,286 @@
+# LAN WebUI MVP: a companion to the running desktop
+
+**Status: MVP implemented behind an off-by-default Desktop setting; real-device
+acceptance is still open (see §9).** “MVP” here
+means the first release of the WebUI, not the frozen [Desktop MVP](../00-baseline.md).
+It does not schedule a public Gateway or change the existing SSH or loopback MCP
+profiles. The [remote rollout](../06-delivery/07-remote-control-rollout.md) and
+[ADR 0205](../../adr/0205-remote-agent-control-boundary.md) remain in force.
+
+## 1. Release promise
+
+A person leaves PI-Desktop running, pairs their phone on the same Wi-Fi, picks
+an **existing** project, creates a session in it, and sends a message. They can
+put the phone away, return to the same conversation on either device, and
+organize it. This is not screen sharing: choosing a project on the phone must
+never switch the desktop user's current project, session, draft or scroll position.
+A computer browser on the same LAN can use the same interface.
+
+The following are **P0 release requirements**, not optional polish. Scenario
+numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remote.md#lan-webui-mvp-acceptance).
+
+| ID | What the user must be able to do | Acceptance |
+|---|---|---|
+| W01 | Enable intentionally, pair over the LAN, disconnect or revoke | E2E-269, E2E-274 |
+| W02 | Find, switch and organize existing shared projects | E2E-270, E2E-274, E2E-275 |
+| W03 | Find, create, rename, pin, archive and restore sessions in the right scope | E2E-270, E2E-271, E2E-275 |
+| W04 | Continue a real desktop chat, see progress, answer ordinary questions and stop work | E2E-271, E2E-272 |
+| W05 | Move between clients, refresh or reconnect without losing or repeating work | E2E-270, E2E-271, E2E-273 |
+| W06 | Control what each paired device sees and does; keep elevated actions on Desktop | E2E-269, E2E-272, E2E-274 |
+| W07 | Complete the journey on a phone, with a keyboard or screen reader, and with long histories | E2E-276 |
+| W08 | Retain existing names, organization, transcripts and local behavior across upgrade and disable | E2E-275 |
+
+## 2. Enable, pair and leave (W01, W06)
+
+1. On Desktop, **Settings → System → LAN WebUI** shows the service off on a
+ fresh install. The user chooses a private IPv4 interface (or loopback) and a
+ port, and sees the exact origin after starting. Bind only the selected
+ address; never fall back to a wildcard, another adapter, or public
+ exposure. IPv6-only networks are outside this first release.
+2. **Transport decision (product owner, 2026-11-25): plain HTTP on the LAN; no
+ certificate or HTTPS validation in the MVP.** Traffic on the local network is
+ therefore not encrypted, and the settings copy says so. In place of TLS the
+ listener rejects any request whose `Host` is not the bound origin (DNS
+ 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.
+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
+ require a local user. Sleep makes the Host unreachable. On network change the
+ bound address disappears and the service must be restarted on Desktop.
+ On full Desktop quit the service ends; on a new
+ app launch it starts **off**. Do not promise active turns survive process exit.
+
+Show actionable failures on the side that can fix them: no eligible interface,
+port occupied, client isolation/firewall,
+wrong/expired code, desktop refusal, revoked device or desktop offline. A phone
+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.
+
+## 3. Projects and sessions (W02, W03)
+
+| Surface | Required behavior |
+|---|---|
+| Projects | Show authorized, existing desktop projects, including eligible closed or archived ones, not just the visible sidebar. A logical multi-root group is **one** project. Search by display name across the authorized catalog, switch, rename the display name, pin/unpin, archive/restore. Show pinned first, then recent; distinguish “nothing shared”, “no matches” and “no sessions”. Do not show absolute paths. |
+| Project sessions | Enter a project to see its sessions; search by title, open history, rename, pin/unpin, archive/restore. Show running, waiting, interrupted or failed status from the Host. Stable IDs, not names or list positions, distinguish equally named records. Use bounded pages; search is not limited to the first loaded page. |
+| New in project | A project's **New session** targets that explicit project, even if the desktop or a second tab is viewing another. Use desktop defaults and the normal local Agent. Only reuse an existing empty conversation if it meets Desktop's pristine, same-scope reuse rule; never attach to a running session or another pending submission. Double-tapping one intent cannot create two sessions. |
+| Temporary | **Temporary conversations** is a separate Desktop share scope, off by default. When granted, list/organize existing ordinary temporary sessions and allow a new temporary session with no project and normal temporary workspace isolation. Otherwise global **New session** opens the shared-project chooser; never inherit the last desktop project or disclose temporary titles/counts. |
+| Archive | Archiving is reversible organization, not deletion, cancellation, folder movement or transcript modification. Inspect archived items via an explicit filter without restoring them. Restore an archived parent project before creating or sending; restore an archived session before sending. Restoring a project preserves each session's own archive/pin state. Decline a web archive if the target session, or a project descendant, is running, queued or waiting for input. Never stop work to make archive succeed. |
+
+Only existing locally owned, local-workspace projects and ordinary local Agent
+sessions are writable in P0. Local-Agent projects backed by an SSH workspace,
+legacy remote-Agent sessions, and undisclosed projects are **not exposed**.
+In a shared local scope, existing special sessions (e.g. Plan/Goal) may show
+safe history and “Continue on Desktop”, but no unsupported mutation. Never
+convert them to Agent or bind them to a different workspace as a fallback.
+Desktop-only deletion, scope removal or a change of project membership must
+invalidate stale rows and deep links; do not redirect to a different session.
+
+## 4. Conversation (W04)
+
+- Show the project and session identity, active model label and run state.
+ A new session inherits the configured desktop default; an existing one uses
+ its own configuration. If no usable model exists, preserve the draft and
+ point to model setup on Desktop. Never ask the phone for a provider key.
+- Page older history backwards without losing the reading position. Render
+ user/assistant text, safe Markdown, code and bounded tool summaries in order.
+ Unsupported cards or attachments get a typed, non-executable placeholder;
+ do not fetch embedded remote images or open local files from transcript text.
+- Send text once, show admission/queued status separately from streaming, and
+ reconcile optimistic text with the Host record. When busy, expose a distinct
+ **Queue message** action if offered; otherwise keep the draft and say busy.
+ Show queued entries and allow cancellation of an authorized, not-yet-started
+ turn. **Stop generation** targets the named active turn (RACP `turn/interrupt`),
+ preserves partial output and never stops a different turn after a race.
+- An ordinary Host-typed question with supported text/choice fields can be
+ answered from a paired chat-capable browser; the first valid answer wins.
+ Tool permissions, Plan/Goal approvals, credential prompts and native dialogs
+ remain **desktop-only**. The phone shows “Waiting for approval on Desktop”
+ or “Input needed on Desktop”, then the actual outcome. Classification comes
+ from the Host, not question text. Disconnect, expiry or dismissal is never consent.
+- Preserve in-progress drafts per session within the open tab across navigation
+ and transient network loss. Do not silently send drafts on reconnect. Refresh
+ restores **accepted** work from the Host, not a promise of offline draft storage.
+
+## 5. Authority, consistency and compatibility (W05, W08)
+
+The web page is another client of the **running desktop's** sessions. The
+network edge is scoped to WebUI operations; it is not a way to call arbitrary
+Electron IPC, `host.proxy`, local MCP, Rust RPC or SQLite. Rust remains the
+only SQLite owner. No second `pi-host` against the desktop profile, second
+transcript store, remote provider copy, or browser-owned execution/queue.
+
+| Shared, authoritative state | Local to each view |
+|---|---|
+| Project/session IDs, membership, labels, pins, archives, transcripts, turns, queue, pending interactions and their resolutions | Selected project/session, route, filters, sidebar expansion, scroll, focus and unsent draft |
+
+The browser API is a small WebUI-specific HTTP/JSON surface with same-origin SSE
+change notices (`/v1/projects`, `/v1/sessions`, `/v1/sessions/:id[/history]`,
+`/v1/sessions/:id/turns`, `/v1/turns/:id:interrupt|:cancel`, `…/organize`). It
+maps onto existing Desktop handlers and Agent Host turn admission rather than
+implementing the full RACP browser profile. Catalog changes reach other clients
+even when they are not subscribed to that conversation; clients invalidate and
+refetch a scoped view rather than streaming every transcript. A deep link
+restores only the browser's navigation, after fresh authorization.
+
+- Mutations carry a principal-bound idempotency key; organization edits carry
+ the last observed resource revision and an **explicit desired value**, not
+ “toggle”. A lost reply is reconciled with the Host; a proven same-key retry
+ returns the original admission/result. Different input on the same key or a
+ stale revision fails, refetches, and allows an explicit new choice. Never
+ blindly resend chat, append duplicate output or claim external tools ran
+ exactly once when their outcome is unknown.
+- Across clients a session has at most one active turn. Distinct simultaneous
+ sends are distinct intents: admit one; queue the other only if its request
+ explicitly allows it, otherwise report busy without dropping the draft.
+ Chat can interrupt the named active turn or cancel a specified queued turn in
+ its authorized session, even if it was submitted on Desktop. Neither action
+ may apply to a different session or a subsequent turn.
+- Change notices carry at most a session id the device may see. On any notice,
+ reconnect or foregrounding the page refetches the authoritative view
+ (committed messages, live assistant text, queue and pending-on-Desktop state);
+ it never reconstructs text by replay. Late results for an old route are
+ discarded.
+- On loss, mark the view stale, keep the visible draft, disable mutations, and
+ reconnect with bounded backoff. Reattach on foregrounding. `UNAUTHORIZED`
+ requires pairing again; scope loss clears affected data; `CONFLICT` refreshes
+ the record; busy/limit responses retain the draft and honor retry hints.
+ Show meaningful terminal state after a desktop restart, not endless “running”.
+
+**Organization ownership.** Pins, archives and display names stay in the
+existing Desktop sidebar record ([ADR 0016](../../adr/0016-sidebar-organization-and-multi-project-tabs.md));
+logical groups keep their [host-owned identities](../../adr/0249-chatgpt-style-logical-project-groups.md).
+A browser edit is written to that record by Electron Main and kept pending until
+the open Desktop renderer acknowledges it, so an older sidebar snapshot cannot
+overwrite it. Session and group renames go through the existing host calls.
+Temporary sessions are created with no project and never inherit the active
+workspace. Existing IDs, group membership, names, pins, archives and transcripts
+are untouched; view-only preferences (collapse, sort, open tabs) stay private.
+Stopping the WebUI removes access, not data.
+
+## 6. Access and privacy (W06)
+
+Follow the [remote security contract](../05-security/02-remote-control-security.md).
+The person at Desktop selects **named projects** and/or the separate Temporary
+scope per device. None are shared by default; newly added projects are not
+implicitly included. In a shared project, make clear that its eligible existing
+and future sessions, including archived history, are visible. Label the device
+and explain what it can read and which model-backed actions may incur usage.
+History may contain sensitive text the user or model already put in the
+conversation; sharing is not an automatic redaction of authored messages.
+Never enrich it with credential records, absolute workspace paths or raw tool
+diagnostics that the safe transcript projection does not already expose.
+
+| Grant | Allowed within the selected scopes | Never implied |
+|---|---|---|
+| View | Catalog, safe history, current activity and scoped events | Other project names/counts, paths, secrets or arbitrary file reads |
+| Chat (explicit, includes View) | Create, send/queue, interrupt, cancel queued work, answer ordinary typed questions | Shell endpoint, remote approvals, raising permission mode, configuring providers |
+| Organize (explicit, includes View) | Rename, set pin, set archive/restore on eligible objects | Permanent delete, project registration/root editing, widening the share or granting roles |
+
+Check the grant, actual current scope, object state, and policy on **every**
+command, page, attachment placeholder, catalog notification and active stream.
+Guessing an ID must reveal no more than a missing record. Revoking a device or
+scope closes its affected subscriptions, rejects subsequent commands and
+cancels its not-started queued work in the revoked scope. Already admitted
+running work follows the Host incident policy; never silently replay or undo
+it. Clear protected views on authorization loss; already seen text cannot be
+remotely erased. A web turn never gets the SSH-paired-owner exemption: apply
+the lower of session policy and the WebUI `ask` ceiling without changing the
+desktop session setting. A browser cannot approve its own escalation.
+
+Session archive is **owner-only** in RACP. The LAN WebUI does not reuse RACP
+`session/archive` and never grants a phone the owner role: its Organize grant
+is checked by the WebUI edge itself, per project, and only writes the same
+Desktop organization record the sidebar uses (§5).
+
+Use a Host-issued `HttpOnly`, host-only, `SameSite=Strict` session cookie
+(12 hours; no `Secure` flag because the MVP is HTTP), exact Host/Origin
+validation, and CSRF tokens for authenticated mutations. Device credentials live
+only in Desktop memory: stopping the service or quitting Desktop signs every
+device out. No credentials in URLs, local storage or logs. Serve assets locally
+under a restrictive CSP; never cache authenticated data (`no-store`). Logs
+record only start/stop and failure codes, not prompts, history, codes or
+cookies. Bound request bodies (300 KiB), prompts (256 KiB), pages (50 items),
+pending pairings (8) and devices (16); never silently truncate input.
+
+## 7. Phone usability and service targets (W07)
+
+- Phone: Projects → Sessions → Conversation is usable with one hand. Browser
+ Back returns to the prior list and position. Put New session and Send in
+ reach, row actions in a labeled menu, and the composer above the keyboard
+ and safe area. Desktop browsers may keep a persistent project/session rail.
+ Do not hijack standard browser navigation, zoom or copy.
+- Support 320 CSS px width, portrait/landscape, 200% zoom, visible keyboard
+ focus, 44 × 44 CSS px action targets, descriptive control names and status
+ text independent of color. Announce actionable state changes, not every
+ token. Preserve Chinese IME composition; Enter for candidate selection must
+ not submit. Ship localized controls/errors via Desktop's catalog conventions,
+ with English fallback; verify English and Simplified Chinese.
+- Qualification: physical iPhone/Safari and Android/Chrome on the same LAN,
+ plus desktop Chromium; record browser/OS/build versions. Qualify listener
+ start, shutdown and restart on every Desktop OS advertised as supported.
+- On a healthy LAN (RTT ≤50 ms, warm assets, fixture provider), test 100
+ projects, 1,000 sessions and one 2,000-message history. Across 30 runs, p95
+ first usable catalog and committed cross-client metadata visibility must each
+ be ≤2 seconds. Initial chat fetch loads at most 100 history items, not the
+ entire transcript. Do not count model latency in these targets.
+
+## 8. Delivery and release decision
+
+1. **Boundary (done):** a WebUI-specific edge in Electron Main calls the
+ existing Desktop handlers (Agent Host turn admission, session create/rename,
+ project rename, abort) and host-core reads. It exposes no generic IPC, RPC or
+ SQLite access. Organization edits use the existing sidebar backup as the one
+ durable record (§5). An ADR is still owed for this boundary and for the HTTP
+ transport decision.
+2. **Deliver the basic workflow:** implement W02–W04 against the same durable
+ records, then exercise both clients together, including empty/new/existing
+ projects and sessions, restricted grants and a lost reply. Do not count an
+ independent headless session or a mock renderer as the real user journey.
+3. **Release gate:** all P0 rows and E2E-269 through E2E-276 must pass on the
+ candidate, including physical iPhone/Safari and Android/Chrome on a real
+ LAN. Use isolated profiles, deterministic model/tool fixtures, no real
+ secrets or paid providers. This document supplies no real-device evidence.
+
+**After P0, not release dependencies:** choosing among desktop-approved models
+on the web, creating/importing projects or editing roots, moving/forking or
+permanently deleting sessions, attachments/files/diffs, Plan/Goal authoring,
+remote approvals, terminal, plugins/settings, notifications and offline sending.
+No public relay, account service, Internet exposure or standalone WebUI Agent
+is part of this product increment.
+
+## 9. Implementation status (MVP)
+
+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
+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) |
+| 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 |
+| 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-browser-user-path.test.mjs` (Electron Chromium at phone size driving
+the shipped page).
diff --git a/docs/spec/01-product/README.md b/docs/spec/01-product/README.md
index c54a17398..e0c3008ed 100644
--- a/docs/spec/01-product/README.md
+++ b/docs/spec/01-product/README.md
@@ -5,3 +5,4 @@
| [00-overview.md](00-overview.md) | Product overview |
| [01-product-scope.md](01-product-scope.md) | In/out of scope |
| [02-non-goals.md](02-non-goals.md) | Explicit non-goals |
+| [03-lan-webui-mvp.md](03-lan-webui-mvp.md) | LAN browser companion (MVP): projects, sessions, chat, pairing and release gates |
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 276ae3a47..2d7f7888c 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -335,6 +335,7 @@ identify the platform validation still needed.
| Post-baseline local automation | E2E-220 |
| Post-baseline local automation (MCP `pi_session_get` large compaction) | E2E-MCP-session-get-projects-large-compaction |
| Post-MVP remote control | E2E-221, E2E-222, E2E-223, E2E-224, E2E-225, E2E-226, E2E-227, E2E-228, E2E-229, E2E-230, E2E-231, E2E-232, E2E-REMOTE-HOST-settings-compact-inventory |
+| [LAN WebUI MVP](../01-product/03-lan-webui-mvp.md) (M6+, partially automated) | [LAN companion scenarios](e2e/live-and-remote.md#lan-webui-mvp-acceptance): E2E-269, E2E-270, E2E-271, E2E-272, E2E-273, E2E-274, E2E-275, E2E-276 |
| Trusted extensions (R7 v1) | E2E-DIALOG-long-text-boundaries, E2E-241, E2E-242, E2E-HOOKS-prompt-chain, E2E-HOOKS-context-every-request, E2E-HOOKS-cancel-and-dispose, E2E-TRUSTED-EXTENSION-custom-agent-stream-and-binding, E2E-243, E2E-TRUSTED-EXTENSION-temporary-session-cwd-is-scratch, E2E-244, E2E-245, E2E-PLUGIN-imported-pi-package-skills, E2E-PLUGIN-import-extension-installs-dependencies, E2E-PLUGIN-import-extension-reports-missing-dependency, E2E-PLUGIN-declared-provider-appears-in-the-native-provider-list, E2E-PLUGIN-provider-catalog-add-service |
| Trusted extensions (R7 v1 npm recovery) | E2E-PLUGIN-import-extension-recovers-missing-npm |
| Post-MVP regression coverage (plugin tool dispatch) | E2E-PLUGIN-slow-tool-is-not-cut-off-by-host-dispatch |
diff --git a/docs/spec/06-delivery/07-remote-control-rollout.md b/docs/spec/06-delivery/07-remote-control-rollout.md
index 7008266ae..e59d2ea9f 100644
--- a/docs/spec/06-delivery/07-remote-control-rollout.md
+++ b/docs/spec/06-delivery/07-remote-control-rollout.md
@@ -29,8 +29,8 @@ around transport breadth:
- issue #100 asks for task completion and approval notifications on
Telegram, WeChat, Slack, or a webhook, plus simple commands back, which is
an outbound integration beside the Host; and
-- no recorded request asks for a browser or phone client of the desktop, so
- the Gateway and browser milestones are unscheduled.
+- at the time of D375 there was no recorded request for a browser or phone
+ client of the desktop, so the Gateway and browser milestones were left unscheduled.
The scheduled order is R0, R1, R2, R3. Milestones marked unscheduled keep
their specifications so the contract does not drift, and they are scheduled
@@ -256,6 +256,11 @@ needs are already covered by the remote-host profile (`session/configure`,
history, workspace reads); a Host-issued session cookie for Gateway-less use
still needs a specification clause. Exit criteria remain those of E2E-228.
+The [LAN WebUI MVP proposal](../01-product/03-lan-webui-mvp.md) records a new,
+direct-to-desktop use case: manage existing projects and sessions from a browser
+on the same LAN. Its acceptance gates do not schedule the general
+browser or Gateway milestone or change the SSH/loopback security profiles.
+
### Reserved — gRPC binding (formerly R5)
`RACP-GRPC` is delivered only when a named native service consumer or
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index 3a6b1a911..bc21a3614 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -746,3 +746,149 @@ ancestor opens after a project switch, and restored local
editing/Browser/editor detection. No model, user profile or external SSH server
participates. Real SSH transport and native Windows/Linux behavior require
their separate platform acceptance.
+
+## LAN WebUI MVP acceptance
+
+These scenarios qualify the [LAN companion](../../01-product/03-lan-webui-mvp.md),
+not the SSH remote Host, a standalone server, or a public Gateway. For all eight:
+**Milestone:** M6+ (WebUI MVP). **Status:** Partially automated — the core user
+path, scope/grant guards and organization merge run in
+`apps/desktop/test/lan-webui-*.test.mjs` (real listener, fake Desktop, Electron
+Chromium at phone size); real-device steps remain Draft. Use an isolated Desktop
+profile, disposable test devices and deterministic fixtures. Do not use a
+user's running instance.
+
+### E2E-269: Enable, pair and shut down
+
+- **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.
+- **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.
+- **Acceptance:** A, E; W01, W06.
+
+### E2E-270: Organize projects and sessions without stealing navigation
+
+- **Preconditions:** Desktop is editing an unsent draft in A. The phone has
+ View and Organize for A and B; B is a closed local multi-root group with
+ existing sessions, one separately archived. Seed a duplicate display name.
+- **Steps:** Search for B, open it, pin and rename it; rename/pin/archive/restore
+ an idle session. Archive and restore B through the archived filter. Make a
+ competing rename from Desktop and submit the stale edit from the phone.
+- **Expected:** One row per group, stable IDs, correct filtered/recent/pinned
+ lists; both clients show committed changes without reloading. Archive is not
+ deletion and does not cascade; restoring B preserves the separately archived
+ session. A stale writer sees the latest value instead of overwriting it.
+ Desktop stays in A with draft, focus and scroll intact. Repeating the archive
+ against a busy target fails without stopping work.
+- **Acceptance:** C, D; W02, W03, W05.
+
+### E2E-271: Create and continue the same session on phone and desktop
+
+- **Preconditions:** Desktop is viewing A. The phone has Chat in B, no Temporary
+ grant, and a usable fixture model. B has an existing chat with paged history.
+- **Steps:** Double-tap New session in B, send text, stream a reply, then continue
+ the same session on Desktop. Queue a second message while busy and cancel it;
+ interrupt the named active turn. Reopen the older B chat and load older pages.
+ Try global New with and without an explicit Temporary grant. Repeat with no
+ configured model, and with a pre-existing eligible empty conversation in B.
+ From idle, send two different prompts simultaneously from Desktop and the
+ phone, first without queuing and then with explicit queue admission.
+- **Expected:** The initial double-tap/send yields one session and one user
+ message. Work runs in B, not A; the other client continues the same ID/history.
+ Concurrent sends never start two active turns in a session. A losing send is
+ queued only by request; otherwise its client sees busy and keeps the draft.
+ Canceled work never runs and stop preserves partial output. Paging older
+ items keeps position. No implicit Temporary disclosure, wrong-project empty
+ reuse, or duplicate creates. An authorized temporary session has no project.
+ Missing model blocks send, preserves text and points to Desktop setup.
+- **Acceptance:** B, C, D; W03, W04, W05.
+
+### E2E-272: Answer ordinary input but leave privileged decisions on Desktop
+
+- **Preconditions:** A Chat-capable phone and Desktop are viewing the same test
+ session; fixtures can ask an ordinary choice question and require a tool
+ permission. Provide an existing Plan/Goal session for the read-only case.
+- **Steps:** Submit an ordinary answer, race a second answer from Desktop, then
+ trigger a gated action. Reload the phone while pending; try a browser approval
+ and permission change, then deny locally. Repeat with local approval and with
+ expiry/cancellation. Inspect the special session on the phone.
+- **Expected:** One ordinary answer is accepted. The phone reports the pending
+ request and actual outcome; only Desktop can approve, including on a session
+ configured for a higher local permission mode. Deny/expiry never executes the
+ gated action, local allow executes the fixture once, and reload grants nothing.
+ Unsupported sessions do not gain writable controls or change mode.
+- **Acceptance:** C, E; W04, W06.
+
+### E2E-273: Resume across lost responses, Wi-Fi loss and changed epochs
+
+- **Preconditions:** Two clients on a running Desktop; fixture can retain or
+ expire cursors, drop a response after admission and pause a streaming turn.
+- **Steps:** Lose a create/send response, background the phone, switch Wi-Fi
+ off/on, refresh and reattach. Exercise same-key retry, a duplicate event,
+ a stale cursor/new epoch and slow-client overflow. Switch sessions while an
+ old history page is outstanding. Separately restart Desktop, re-enable and pair.
+- **Expected:** One original admission per intent, no automatic draft or tool
+ replay. A transient disconnect does not stop the turn. Cursor replay or a
+ replacement snapshot restores committed and partial content, queue and
+ pending input without gaps or duplicates. Late results do not repaint another
+ session. After process restart the phone shows actual host recovery state,
+ not a fabricated completion, continuing stream or automatic new turn.
+- **Acceptance:** C, F; W05.
+
+### E2E-274: Enforce device grants, network boundary and revocation
+
+- **Preconditions:** A View-only device, a second device with Chat/Organize for
+ A only, and unshared B, Temporary and SSH-backed fixtures. Use a controlled
+ 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.
+- **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.
+- **Acceptance:** D, E; W01, W02, W06.
+
+### E2E-275: Preserve an existing desktop profile and disable cleanly
+
+- **Preconditions:** Upgrade fixture from before the feature with group/legacy
+ project identities, renamed/pinned/archived projects and sessions, partial or
+ missing optional preferences, and transcripts. Keep a pre-upgrade inventory.
+- **Steps:** Upgrade without enabling sharing; check Desktop. Enable, pair,
+ compare the authorized inventory, change organization on each surface, restart,
+ and exercise interrupted/repeated metadata import. Disable and use Desktop alone.
+- **Expected:** IDs, membership, labels, pins, archives, transcript contents
+ and recoverable legacy aliases survive; no duplicate group or empty-profile
+ reset. Old sidebar writes do not overwrite newer organization. Private
+ navigation stays private. Changes made on either client remain on Desktop
+ after disable; no extra writer or listener remains.
+- **Acceptance:** C, D, F; W02, W03, W08.
+
+### E2E-276: Phone, keyboard and large-catalog usability
+
+- **Preconditions:** Real iOS Safari and Android Chrome, desktop Chromium,
+ English and Simplified Chinese. Warm assets, LAN RTT ≤50 ms, fixture data:
+ 100 projects, 1,000 sessions, a 2,000-message conversation. Use no paid model.
+- **Steps:** Run Projects → Sessions → New session → Send → Back. Repeat at
+ 320 CSS px and 200% zoom, in both phone orientations, with the soft keyboard,
+ Chinese IME, keyboard-only navigation and a screen reader. Search for a late
+ page, load older history, and measure catalog readiness and peer edits over
+ 30 runs. Record device/browser/OS and Desktop candidate/base revisions.
+- **Expected:** Reachable labeled actions, ≥44 CSS px targets, no obstructed
+ composer, horizontal page scrolling or accidental IME send. Back restores the
+ prior list position. Screen readers announce important states rather than
+ every token. At p95 the initial usable catalog and committed peer changes each
+ take ≤2 seconds; initial history fetch contains at most 100 items.
+- **Acceptance:** C, D; W07.
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index f9fd15be5..c405eedc8 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -11,6 +11,7 @@
- [00-overview.md](01-product/00-overview.md)
- [01-product-scope.md](01-product/01-product-scope.md)
- [02-non-goals.md](01-product/02-non-goals.md)
+- [LAN WebUI MVP](01-product/03-lan-webui-mvp.md)
## 2. Architecture
- [README.md](02-architecture/README.md)
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 3b2bc078e..27e1822cc 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -1,5 +1,6 @@
export * from "./activation.js";
export * from "./protocol.js";
+export * from "./lan-webui.js";
export * from "./file-batches.js";
export * from "./background-jobs.js";
export * from "./errors.js";
diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.ts
new file mode 100644
index 000000000..e86bbde21
--- /dev/null
+++ b/packages/shared/src/lan-webui.ts
@@ -0,0 +1,99 @@
+/**
+ * The direct-to-Desktop LAN browser profile (proposed WebUI MVP).
+ * No native paths, host RPC or provider secrets cross this boundary.
+ */
+export interface LanGrants {
+ /** Host project group ids the device may see. */
+ projectIds: string[];
+ /** Temporary (projectless) conversations. */
+ temporary: boolean;
+ /** Create sessions, send, queue, stop. */
+ chat: boolean;
+ /** Rename, pin, archive and restore. */
+ organize: boolean;
+}
+export interface LanAccess extends LanGrants {
+ deviceId: string;
+}
+export const LAN_TEMPORARY_PROJECT = "__temporary__";
+export interface LanProject {
+ id: string;
+ label: string;
+ pinned: boolean;
+ archived: boolean;
+ revision: string;
+}
+export type LanSessionStatus = "idle" | "running" | "waiting";
+export interface LanSession {
+ id: string;
+ projectId: string | null;
+ title: string;
+ pinned: boolean;
+ archived: boolean;
+ revision: string;
+ /** Visible, but not writable from the browser (e.g. Plan/Goal sessions). */
+ readOnly: boolean;
+ status: LanSessionStatus;
+ updatedAt: string;
+}
+export interface LanPage<T> {
+ items: T[];
+ nextCursor: string | null;
+}
+export interface LanMessage {
+ id: string;
+ role: "user" | "assistant" | "tool";
+ text: string;
+}
+export interface LanConversation {
+ session: LanSession;
+ messages: LanPage<LanMessage>;
+ /** Streaming assistant text of the active turn, not yet persisted. */
+ liveText: string | null;
+ activeTurnId: string | null;
+ waiting: "approval" | "input" | null;
+ queue: Array<{ id: string; text: string }>;
+ modelLabel: string | null;
+}
+export interface LanDevice {
+ id: string;
+ label: string;
+ lastActiveAt: number;
+ grants: LanGrants;
+}
+export interface LanPairing {
+ id: string;
+ label: string;
+ createdAt: number;
+}
+export interface LanInterface {
+ address: string;
+ name: string;
+}
+export interface LanAdminView {
+ running: boolean;
+ origin: string | null;
+ address: string | null;
+ port: number | null;
+ code: { value: string; expiresAt: number } | null;
+ pending: LanPairing[];
+ devices: LanDevice[];
+ interfaces: LanInterface[];
+ projects: Array<{ id: string; label: string }>;
+ error: string | null;
+}
+export type LanAdminAction =
+ | { kind: "state" | "stop" | "issueCode" }
+ | { kind: "start"; address: string; port: number }
+ | { kind: "confirm"; id: string; grants: LanGrants }
+ | { kind: "deny" | "revoke"; id: string }
+ /** The renderer applied organization patches up to `seq`. */
+ | { kind: "ack"; seq: number };
+
+export type LanOrganizationPatch =
+ | { kind: "project"; key: string; patch: { name?: string; pinned?: boolean; archived?: boolean } }
+ | { kind: "session"; key: string; patch: { pinned?: boolean; archived?: boolean; manualTitle?: boolean } };
+export interface LanCatalogChangedEvent {
+ seq: number;
+ patches: LanOrganizationPatch[];
+}
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index eddeae730..744694174 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -205,6 +205,7 @@ export const IPC = {
settingsSet: "pi-desktop/settings/set",
sidebarPreferencesGet: "pi-desktop/sidebar/preferences/get",
sidebarPreferencesSet: "pi-desktop/sidebar/preferences/set",
+ lanWebUiAdmin: "pi-desktop/lan-webui/admin",
configSyncGetState: "pi-desktop/configSync/getState",
backgroundTasksList: "pi-desktop/backgroundTasks/list",
backgroundTasksOutput: "pi-desktop/backgroundTasks/output",
@@ -507,6 +508,7 @@ export const IPC = {
nativeMenuAction: "pi-desktop/menu/nativeAction",
},
event: {
+ lanWebUiCatalogChanged: "pi-desktop/lan-webui/catalogChanged",
pluginChanged: "pi-desktop/event/pluginChanged",
/** Progress of an install or update, while it is still running. */
pluginInstallProgress: "pi-desktop/plugin/event/installProgress",