Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(desktop): pair LAN WebUI devices directly by code
vastsad8e23a76a08e
diff --git a/apps/desktop/electron/main/lan-webui/ports.ts b/apps/desktop/electron/main/lan-webui/ports.tsindex 334fe5163..3f284754b 100644--- a/apps/desktop/electron/main/lan-webui/ports.ts+++ b/apps/desktop/electron/main/lan-webui/ports.ts@@ -1,5 +1,3 @@-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;@@ -17,7 +15,7 @@ export interface LanRequest {path: string;query: URLSearchParams;body: Record<string, unknown>;- access: LanAccess;+ deviceId: string;}export type LanChange = { sessionId?: string };diff --git a/apps/desktop/electron/main/lan-webui/server.ts b/apps/desktop/electron/main/lan-webui/server.tsindex 41b6e657e..109a6d01e 100644--- a/apps/desktop/electron/main/lan-webui/server.ts+++ b/apps/desktop/electron/main/lan-webui/server.ts@@ -1,47 +1,30 @@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 type { LanDevice } 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>;+ mayReveal(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 RememberedOperation = { grants: LanGrants; result: Promise<unknown> };-type Device = LanDevice & { token: string; csrf: string; streams: Set<ServerResponse>; idempotent: Map<string, RememberedOperation> };-type Pending = LanPairing & { secret: string; deviceId: string | null };+type Device = LanDevice & { token: string; csrf: string; streams: Set<ServerResponse>; idempotent: Map<string, Promise<unknown>> };const secret = () => randomBytes(32).toString("base64url");-function cleanGrants(value: unknown): LanGrants {- const input = (value && typeof value === "object" ? value : {}) as Partial<Record<keyof LanGrants, unknown>>;- // Never reinterpret an older project-id selection as consent to all local projects.- if (input.projectScope !== "all-local") throw new LanError(400, "INVALID_SCOPE");- return {- projectScope: input.projectScope,- temporary: input.temporary === true,- chat: input.chat === true,- organize: input.organize === true,- };-}-const sameSecret = (a: string, b: string) => {const left = Buffer.from(a);const right = Buffer.from(b);@@ -98,7 +81,7 @@ async function readBody(request: IncomingMessage): Promise<Record<string, unknow/*** 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.+ * workspace handler, which checks that resources belong to the local catalog.*/export function createLanServer(options: {handler: LanServerHandler;@@ -110,7 +93,6 @@ export function createLanServer(options: {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;@@ -125,11 +107,8 @@ export function createLanServer(options: {return null;};- const access = (device: Device): LanAccess => ({ deviceId: device.id, ...device.grants });-- function requireCurrentGrants(device: Device, grants: LanGrants) {+ function requireDevice(device: Device) {if (!devices.has(device.id)) throw new LanError(401, "UNAUTHORIZED");- if (device.grants !== grants) throw new LanError(409, "CONFLICT");}/** DNS rebinding and cross-site request guard; not a TLS check. */@@ -144,15 +123,13 @@ export function createLanServer(options: {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);+ function expireCode() {+ if (code && code.expiresAt <= now()) code = null;}async function pair(request: IncomingMessage, response: ServerResponse) {const body = await readBody(request);- prune();+ expireCode();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");@@ -164,30 +141,17 @@ export function createLanServer(options: {}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);+ if (devices.size >= MAX_DEVICES) throw new LanError(429, "RATE_LIMITED");++ // Consume the code and register the device together, without an async gap.+ code = null;+ const device: Device = {+ id: randomUUID(), label, lastActiveAt: now(), token: secret(), csrf: secret(),+ streams: new Set(), idempotent: new Map(),+ };+ devices.set(device.id, device);changed();- sendJson(response, 200, { state: "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)],- });+ sendJson(response, 200, { state: "paired" }, { "Set-Cookie": cookie(SESSION_COOKIE, device.token, 12 * 60 * 60) });}function events(device: Device, request: IncomingMessage, response: ServerResponse, sessionFilter: string | null) {@@ -206,17 +170,14 @@ export function createLanServer(options: {}async function broadcast(change: LanChange) {+ if (![...devices.values()].some((device) => device.streams.size)) return;+ const reveal = change.sessionId && await options.handler.mayReveal(change.sessionId).catch(() => false);+ const data = reveal ? { sessionId: change.sessionId } : {};for (const device of devices.values()) {- if (!device.streams.size) continue;- const grants = device.grants;- let reveal = false;- if (change.sessionId) reveal = await options.handler.mayReveal(access(device), change.sessionId).catch(() => false);- if (!devices.has(device.id) || device.grants !== grants) continue;for (const stream of device.streams) {const filter = (stream as ServerResponse & { lanSession?: string | null }).lanSession ?? null;if (filter && change.sessionId !== filter) continue;if (filter && !reveal) continue;- const data = reveal ? { sessionId: change.sessionId } : {};stream.write(`event: change\ndata: ${JSON.stringify(data)}\n\n`);}}@@ -225,11 +186,12 @@ export function createLanServer(options: {async function api(request: IncomingMessage, response: ServerResponse, url: URL) {const device = deviceFor(request);if (!device) throw new LanError(401, "UNAUTHORIZED");- const grants = device.grants;device.lastActiveAt = now();const method = request.method === "POST" ? "POST" : "GET";if (url.pathname === "/v1/me" && method === "GET") {- return sendJson(response, 200, { csrf: device.csrf, access: access(device), label: device.label });+ // Compatibility metadata for already-open browser tabs; not per-device grants.+ const access = { deviceId: device.id, projectScope: "all-local", temporary: true, chat: true, organize: true };+ return sendJson(response, 200, { csrf: device.csrf, access, label: device.label });}if (method === "POST") {const csrf = String(request.headers["x-csrf-token"] ?? "");@@ -245,13 +207,13 @@ export function createLanServer(options: {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");- requireCurrentGrants(device, grants);+ if (!(await options.handler.mayReveal(sessionId))) throw new LanError(404, "NOT_FOUND");+ requireDevice(device);return events(device, request, response, sessionId);}const body = method === "POST" ? await readBody(request) : {};- requireCurrentGrants(device, grants);- const lanRequest: LanRequest = { method, path: url.pathname, query: url.searchParams, body, access: access(device) };+ requireDevice(device);+ const lanRequest: LanRequest = { method, path: url.pathname, query: url.searchParams, body, deviceId: device.id };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>;@@ -259,15 +221,12 @@ export function createLanServer(options: {const cacheKey = `${url.pathname}:${key}`;const remembered = device.idempotent.get(cacheKey);if (remembered) {- // A retry from an earlier grant must neither return its result nor execute again.- if (remembered.grants !== grants) throw new LanError(409, "CONFLICT");- result = remembered.result;+ result = remembered;} else {result = options.handler.handle(lanRequest, key);- const entry = { grants, result };- device.idempotent.set(cacheKey, entry);+ device.idempotent.set(cacheKey, result);result.catch(() => {- if (device.idempotent.get(cacheKey) === entry) device.idempotent.delete(cacheKey);+ if (device.idempotent.get(cacheKey) === result) device.idempotent.delete(cacheKey);});while (device.idempotent.size > MAX_IDEMPOTENT) {device.idempotent.delete(device.idempotent.keys().next().value as string);@@ -277,7 +236,7 @@ export function createLanServer(options: {result = options.handler.handle(lanRequest, null);}const value = await result;- requireCurrentGrants(device, grants);+ requireDevice(device);sendJson(response, 200, value);}@@ -300,7 +259,11 @@ export function createLanServer(options: {}}if (url.pathname === "/pair" && request.method === "POST") return pair(request, response);- if (url.pathname === "/pair/status" && request.method === "GET") return pairStatus(request, response);+ // Older pages poll this route after pairing. It only checks the live cookie now.+ if (url.pathname === "/pair/status" && request.method === "GET") {+ if (!deviceFor(request)) throw new LanError(401, "UNAUTHORIZED");+ return sendJson(response, 200, { state: "paired" });+ }if (url.pathname.startsWith("/v1/")) return api(request, response, url);throw new LanError(404, "NOT_FOUND");}@@ -349,7 +312,6 @@ export function createLanServer(options: {heartbeat = null;for (const device of devices.values()) closeStreams(device);devices.clear();- pending.clear();code = null;host = "";if (!current) return;@@ -370,55 +332,12 @@ export function createLanServer(options: {},code(): { value: string; expiresAt: number } | null {- prune();+ expireCode();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 {- prune();- const entry = pending.get(id);- if (!entry || entry.deviceId) throw new LanError(404, "NOT_FOUND");- if (devices.size >= MAX_DEVICES) throw new LanError(429, "RATE_LIMITED");- const device: Device = {- id: randomUUID(),- label: entry.label,- lastActiveAt: now(),- grants: cleanGrants(grants),- token: secret(),- csrf: secret(),- streams: new Set(),- idempotent: new Map(),- };- devices.set(device.id, device);- entry.deviceId = device.id;- changed();- },-- /** Keep device identity but reauthorize its next request and subscriptions. */- update(id: string, grants: LanGrants): void {- const device = devices.get(id);- if (!device) throw new LanError(404, "NOT_FOUND");- const next = cleanGrants(grants);- const current = device.grants;- if (next.temporary === current.temporary && next.chat === current.chat && next.organize === current.organize) return;- device.grants = next;- closeStreams(device);- changed();- },-- deny(id: string): void {- pending.delete(id);- changed();+ return [...devices.values()].map(({ id, label, lastActiveAt }) => ({ id, label, lastActiveAt }));},revoke(id: string): void {diff --git a/apps/desktop/electron/main/lan-webui/service.ts b/apps/desktop/electron/main/lan-webui/service.tsindex 4c0ff83e7..6a6b6692a 100644--- a/apps/desktop/electron/main/lan-webui/service.ts+++ b/apps/desktop/electron/main/lan-webui/service.ts@@ -64,7 +64,6 @@ export function createLanWebUiService(deps: {address: running ? address : null,port: running ? port : null,code: running ? current!.code() : null,- pending: running ? current!.pending() : [],devices: running ? current!.devices() : [],interfaces: listLanInterfaces(),error,@@ -97,15 +96,6 @@ export function createLanWebUiService(deps: {case "issueCode":ensureServer().issueCode();break;- case "confirm":- ensureServer().confirm(String(action.id), action.grants);- break;- case "update":- ensureServer().update(String(action.id), action.grants);- break;- case "deny":- server?.deny(String(action.id));- break;case "revoke":server?.revoke(String(action.id));break;diff --git a/apps/desktop/electron/main/lan-webui/workspace.ts b/apps/desktop/electron/main/lan-webui/workspace.tsindex e4ec0a3f9..89cdfa0c2 100644--- a/apps/desktop/electron/main/lan-webui/workspace.ts+++ b/apps/desktop/electron/main/lan-webui/workspace.ts@@ -2,7 +2,6 @@ import { createHash } from "node:crypto";import {LAN_TEMPORARY_PROJECT,type AgentEventEnvelope,- type LanAccess,type LanConversation,type LanMessage,type LanPage,@@ -186,8 +185,8 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {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) {+ /** Resolve only sessions in the current local catalog or temporary workspace. */+ async function requireLocalSession(sessionId: string) {if (!sessionId || sessionId.startsWith("remote:") || sessionId.startsWith("native-pi:")) {throw new LanError(404, "NOT_FOUND");}@@ -195,7 +194,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {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 || (projectId === null && !access.temporary)) throw new LanError(404, "NOT_FOUND");+ if (projectId === undefined) throw new LanError(404, "NOT_FOUND");const meta = deps.organization.read();return { session, projectId, meta, view: sessionView(session, projectId, meta) };}@@ -226,10 +225,9 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return page(list, query.get("cursor"));}- async function listSessions(access: LanAccess, query: URLSearchParams): Promise<LanPage<LanSession>> {+ async function listSessions(query: URLSearchParams): Promise<LanPage<LanSession>> {const requested = query.get("projectId") ?? "";const wantTemporary = requested === LAN_TEMPORARY_PROJECT;- if (wantTemporary && !access.temporary) 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);@@ -273,8 +271,8 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {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);+ async function conversation(sessionId: string): Promise<LanConversation> {+ const { session, view } = await requireLocalSession(sessionId);const [messages, pending] = await Promise.all([history(sessionId, null),deps.getBridge()?.pendingInteractiveRequests(sessionId).catch(() => ({ asks: [], permissions: [] })) ??@@ -296,21 +294,11 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {};}- 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);+ async function createSession(body: Record<string, unknown>) {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 {+ if (projectId !== null) {const { group, view } = await requireLocalProject(projectId);if (view.archived) throw new LanError(409, "ARCHIVED");projectPath = group.primaryPath;@@ -325,8 +313,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return { id };}- async function organizeProject(access: LanAccess, projectId: string, body: Record<string, unknown>) {- requireOrganize(access);+ async function organizeProject(projectId: string, body: Record<string, unknown>) {const [field, value] = oneOrganizeField(body);const { group, view } = await requireLocalProject(projectId);if (body.revision !== view.revision) throw new LanError(409, "CONFLICT");@@ -346,10 +333,9 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return { ok: true };}- async function organizeSession(access: LanAccess, sessionId: string, body: Record<string, unknown>) {- requireOrganize(access);+ async function organizeSession(sessionId: string, body: Record<string, unknown>) {const [field, value] = oneOrganizeField(body);- const { view } = await authorizedSession(access, sessionId);+ const { view } = await requireLocalSession(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;@@ -366,20 +352,19 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return { ok: true };}- async function sendTurn(access: LanAccess, sessionId: string, body: Record<string, unknown>, key: string | null) {- requireChat(access);+ async function sendTurn(deviceId: string, sessionId: string, body: Record<string, unknown>, key: string | null) {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);+ const { view } = await requireLocalSession(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 };+ const principal: Principal = { subject: `lan:${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}` } : {}),+ ...(key ? { idempotencyKey: `lan:${deviceId}:${key}` } : {}),input: { text },context: { requestId: `lan-${Date.now().toString(36)}` },});@@ -395,20 +380,18 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {}}- async function interrupt(access: LanAccess, turnId: string, body: Record<string, unknown>) {- requireChat(access);+ async function interrupt(turnId: string, body: Record<string, unknown>) {const sessionId = stringField(body, "sessionId") ?? "";- await authorizedSession(access, sessionId);+ await requireLocalSession(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);+ async function cancel(turnId: string, body: Record<string, unknown>) {const sessionId = stringField(body, "sessionId") ?? "";- await authorizedSession(access, sessionId);+ await requireLocalSession(sessionId);const queue = bridge().queue;if (!queue.list(sessionId).some((entry) => entry.id === turnId)) return { ok: true, canceled: false };await queue.remove(turnId);@@ -418,29 +401,29 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return {async handle(request: LanRequest, key: string | null): Promise<unknown> {- const { method, path, access, query, body } = request;+ const { method, path, deviceId, 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(query);- if (resource === "sessions" && !id) return listSessions(access, query);- if (resource === "sessions" && id && !sub) return conversation(access, id);+ if (resource === "sessions" && !id) return listSessions(query);+ if (resource === "sessions" && id && !sub) return conversation(id);if (resource === "sessions" && id && sub === "history") {- await authorizedSession(access, id);+ await requireLocalSession(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);+ if (resource === "sessions" && !id) return createSession(body);+ if (resource === "projects" && id && sub === "organize") return organizeProject(id, body);+ if (resource === "sessions" && id && sub === "organize") return organizeSession(id, body);+ if (resource === "sessions" && id && sub === "turns") return sendTurn(deviceId, id, body, key);+ if (resource === "turns" && id?.endsWith(":interrupt")) return interrupt(id.slice(0, -10), body);+ if (resource === "turns" && id?.endsWith(":cancel")) return cancel(id.slice(0, -7), body);}throw new LanError(404, "NOT_FOUND");},- /** Session-scoped change notifications; ids are filtered by the caller's scope. */+ /** Session-scoped change notifications; the listener filters out non-local ids. */subscribe(listener: (change: LanChange) => void): () => void {listeners.add(listener);return () => {@@ -448,10 +431,10 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {};},- /** Whether a change for `sessionId` may be revealed to `access`. */- async mayReveal(access: LanAccess, sessionId: string): Promise<boolean> {+ /** Whether a change for `sessionId` belongs to a visible local session. */+ async mayReveal(sessionId: string): Promise<boolean> {try {- await authorizedSession(access, sessionId);+ await requireLocalSession(sessionId);return true;} catch {return false;diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.jsindex 7f80bbd45..945d873cc 100644--- a/apps/desktop/resources/lan-webui/app.js+++ b/apps/desktop/resources/lan-webui/app.js@@ -121,7 +121,7 @@const source = new EventSource("/v1/events");source.addEventListener("open", async () => {try {- // Permission edits close the old stream. Refresh grants as well as data+ // Revalidate the credential and refresh the view// when the browser reconnects with the same device credential.const me = await api("GET", "/v1/me");if (state.events !== source) return;@@ -182,7 +182,6 @@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");@@ -241,7 +240,7 @@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) {+ if (!filters.archived && !filters.q) {list.append(row({ title: t("temporary"), meta: [], actions: [], onOpen: () => go(`#/p/${TEMP}`) }));}for (const item of items) {@@ -280,24 +279,22 @@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;+ const create = 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;+ }+ },+ });show(header(title, "#/projects"),toolbar((patch) => { Object.assign(filters, patch); render(); }, filters),@@ -363,13 +360,11 @@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,+ 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;- const canChat = state.me.access.chat && !session.readOnly && !session.archived;+ const canChat = !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}`);@@ -460,10 +455,10 @@form.addEventListener("submit", async (event) => {event.preventDefault();submit.disabled = true;+ status.textContent = t("pairConnecting");try {await api("POST", "/pair", { code: code.value.trim(), label: label.value.trim() });- status.textContent = t("pairWaiting");- await waitForApproval(status);+ await start();} catch (error) {submit.disabled = false;const codeName = error instanceof ApiError ? error.code : "FAILED";@@ -474,14 +469,6 @@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 {diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.jsindex 6dc3aa80c..c13d17dc7 100644--- a/apps/desktop/resources/lan-webui/locale.js+++ b/apps/desktop/resources/lan-webui/locale.js@@ -3,11 +3,11 @@ 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.",+ pairHint: "On the computer, open Settings → System → LAN WebUI and choose Add device. Enter the code shown there.",codeLabel: "Pairing code",deviceLabel: "Device name",pairSubmit: "Pair",- pairWaiting: "Waiting for approval on the computer…",+ pairConnecting: "Connecting…",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",@@ -59,6 +59,7 @@ window.LAN_LOCALES = {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.",+ RATE_LIMITED: "Device limit reached. Remove a device on the computer, then try again.",FAILED: "Something went wrong. Try again.",NETWORK: "Cannot reach the computer. Check that it is awake and on the same network.",},@@ -66,11 +67,11 @@ window.LAN_LOCALES = {"zh-CN": {appTitle: "PI-Desktop",pairTitle: "配对此设备",- pairHint: "在电脑上打开 设置 → 系统 → 局域网 WebUI,点击“显示配对码”,然后在这里输入。",+ pairHint: "在电脑的「设置 → 系统 → 局域网 WebUI」中点击「添加设备」,然后输入配对码。",codeLabel: "配对码",deviceLabel: "设备名称",pairSubmit: "配对",- pairWaiting: "等待电脑上批准…",+ pairConnecting: "正在连接…",pairFailed: "配对码错误或已过期,请在电脑上重新显示配对码。",pairClosed: "请先在电脑上显示配对码。",projects: "项目",@@ -122,6 +123,7 @@ window.LAN_LOCALES = {DESKTOP_UNAVAILABLE: "PI-Desktop 尚未就绪,请稍后重试。",PAYLOAD_TOO_LARGE: "消息过长。",UNAUTHORIZED: "此设备已退出,请重新配对。",+ RATE_LIMITED: "设备数量已达上限。请在电脑上移除一台设备后重试。",FAILED: "出错了,请重试。",NETWORK: "无法连接电脑,请确认电脑已唤醒且在同一网络。",},diff --git a/apps/desktop/src/features/lan-webui/LanDialog.tsx b/apps/desktop/src/features/lan-webui/LanDialog.tsxindex 477f48b8d..b472dc928 100644--- a/apps/desktop/src/features/lan-webui/LanDialog.tsx+++ b/apps/desktop/src/features/lan-webui/LanDialog.tsx@@ -10,51 +10,46 @@ export function LanDialog({description,icon,onClose,- busy = false,error,children,footer,}: {id: string;title: string;- description?: string;+ description: string;icon: ReactNode;onClose: () => void;- busy?: boolean;error?: string | null;children: ReactNode;footer?: ReactNode;}) {const { t } = useTranslation("lan");const dialogRef = useRef<HTMLDivElement>(null);- const close = () => { if (!busy) onClose(); };- useModalDialog(dialogRef, { onClose: close });+ useModalDialog(dialogRef, { onClose });return portalOverlay(- <OverlayBackdrop className="overlay lan-dialog-overlay" role="presentation" onClick={close}>+ <OverlayBackdrop className="overlay lan-dialog-overlay" role="presentation" onClick={onClose}><divref={dialogRef}tabIndex={-1}className="dialog lan-dialog"role="dialog"aria-modal="true"- aria-busy={busy || undefined}aria-labelledby={`${id}-title`}- aria-describedby={description ? `${id}-description` : undefined}+ aria-describedby={`${id}-description`}><header className="lan-dialog-head"><span className="lan-dialog-icon" aria-hidden="true">{icon}</span><div className="lan-dialog-heading"><h2 id={`${id}-title`} className="lan-dialog-title">{title}</h2>- {description ? <p id={`${id}-description`} className="lan-dialog-description">{description}</p> : null}+ <p id={`${id}-description`} className="lan-dialog-description">{description}</p></div><TooltipButtontype="button"className="icon-btn lan-dialog-close"tooltip={t("close")}ariaLabel={t("close")}- aria-disabled={busy || undefined}- onClick={close}+ onClick={onClose}><IconClose size={16} /></TooltipButton>diff --git a/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsx b/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsxdeleted file mode 100644index 30f72aa48..000000000--- a/apps/desktop/src/features/lan-webui/LanGrantsEditor.tsx+++ /dev/null@@ -1,58 +0,0 @@-import { useTranslation } from "react-i18next";-import type { LanGrants } from "@pi-desktop/shared";-import { Checkbox } from "../../components/ui";-import { IconCheck, IconShield } from "../../components/icons";--export const NEW_DEVICE_GRANTS: LanGrants = {- projectScope: "all-local",- temporary: false,- chat: true,- organize: true,-};--export function LanGrantsEditor({- value,- onChange,- disabled,-}: {- value: LanGrants;- onChange: (next: LanGrants) => void;- disabled: boolean;-}) {- const { t } = useTranslation("lan");- const options = [- { key: "temporary", label: t("scopeTemporary"), hint: t("temporaryHint") },- { key: "chat", label: t("chat"), hint: t("chatHint") },- { key: "organize", label: t("organize"), hint: t("organizeHint") },- ] as const;-- return (- <div className="lan-grants">- <div className="lan-grants-list" role="group" aria-label={t("permissions")}>- <div className="lan-grants-fixed">- <IconCheck size={14} aria-hidden="true" />- <span className="lan-grants-option-label">{t("scopeAll")}</span>- </div>- {options.map(({ key, label, hint }) => (- <Checkbox- key={key}- className="lan-grants-option"- label={- <span className="lan-grants-option-copy">- <span className="lan-grants-option-label">{label}</span>- <span className="lan-grants-option-hint">{hint}</span>- </span>- }- checked={value[key]}- disabled={disabled}- onChange={(event) => onChange({ ...value, [key]: event.target.checked })}- />- ))}- </div>- <p className="lan-grants-note">- <IconShield size={14} aria-hidden="true" />- {t("approvalsStayHere")}- </p>- </div>- );-}diff --git a/apps/desktop/src/features/lan-webui/LanPairDialog.tsx b/apps/desktop/src/features/lan-webui/LanPairDialog.tsxindex f0084722f..e29ef1661 100644--- a/apps/desktop/src/features/lan-webui/LanPairDialog.tsx+++ b/apps/desktop/src/features/lan-webui/LanPairDialog.tsx@@ -1,10 +1,9 @@import { useEffect, useState } from "react";import { useTranslation } from "react-i18next";-import type { LanAdminView, LanGrants } from "@pi-desktop/shared";+import type { LanAdminView } from "@pi-desktop/shared";import { Button, cx } from "../../components/ui";import { IconCheck, IconCopy, IconRefresh, IconSmartphone } from "../../components/icons";import { LanDialog } from "./LanDialog";-import { LanGrantsEditor } from "./LanGrantsEditor";import { useCountdown } from "./use-lan-webui-admin";export function CopyButton({ text }: { text: string }) {@@ -53,6 +52,7 @@ export function LanPairDialog({ origin, code, busy, error, issueCode, onClose }:<LanDialogid="lan-pair"title={t("pairTitle")}+ description={t("pairDescription")}icon={<IconSmartphone size={18} />}onClose={onClose}error={error}@@ -97,50 +97,3 @@ export function LanPairDialog({ origin, code, busy, error, issueCode, onClose }:</LanDialog>);}--/** Approve a pending browser, or change what a paired device may do. */-export function LanAccessDialog({- mode, label, initial, busy, error, onSubmit, onDeny, onClose,-}: {- mode: "approve" | "edit";- label: string;- initial: LanGrants;- busy: boolean;- error: string | null;- onSubmit: (grants: LanGrants) => void;- onDeny?: () => void;- onClose: () => void;-}) {- const { t } = useTranslation("lan");- const [draft, setDraft] = useState(initial);- return (- <LanDialog- id={`lan-access-${mode}`}- title={mode === "approve" ? t("approveTitle", { label }) : t("editTitle", { label })}- description={mode === "approve" ? t("approveDescription") : undefined}- icon={<IconSmartphone size={18} />}- busy={busy}- error={error}- onClose={onClose}- footer={- <>- {mode === "approve" ? (- <Button type="button" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : onDeny}>{t("deny")}</Button>- ) : (- <Button type="button" variant="ghost" aria-disabled={busy || undefined} onClick={busy ? undefined : onClose}>{t("cancel")}</Button>- )}- <Button- type="button"- variant="primary"- aria-disabled={busy || undefined}- onClick={busy ? undefined : () => onSubmit(draft)}- >- {mode === "approve" ? t("allow") : t("save")}- </Button>- </>- }- >- <LanGrantsEditor value={draft} onChange={setDraft} disabled={busy} />- </LanDialog>- );-}diff --git a/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsxindex d73d83e1d..b36822c17 100644--- a/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx+++ b/apps/desktop/src/features/lan-webui/LanWebUiSection.tsx@@ -1,38 +1,29 @@import { useEffect, useId, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import type { LanAdminAction } from "@pi-desktop/shared";import { Button, Input, SettingsToggle, cx } from "../../components/ui";import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";import { IconPlus, IconSmartphone, IconWifi } from "../../components/icons";import { formatUpdated } from "../../lib/project-archive";import { SettingsCard, SettingsRow } from "../settings/primitives";-import { NEW_DEVICE_GRANTS } from "./LanGrantsEditor";-import { CopyButton, LanAccessDialog, LanPairDialog } from "./LanPairDialog";+import { CopyButton, LanPairDialog } from "./LanPairDialog";import { LAN_DEFAULT_PORT, useLanWebUiAdmin } from "./use-lan-webui-admin";-type Dialog =- | { kind: "pair"; existingRequests: Set<string> }- | { kind: "approve" | "edit"; id: string };-export function LanWebUiSection() {const { t, i18n } = useTranslation("lan");const { view, busy, error, loadFailed, run, refresh, clearError } = useLanWebUiAdmin();const [preferredAddress, setPreferredAddress] = useState("");const [port, setPort] = useState(String(LAN_DEFAULT_PORT));const [portError, setPortError] = useState(false);- const [dialog, setDialog] = useState<Dialog | null>(null);+ const [pairing, setPairing] = useState<ReadonlySet<string> | null>(null);const portErrorId = useId();const addDeviceRef = useRef<HTMLButtonElement>(null);- const opener = useRef<HTMLButtonElement | null>(null);+ const restoreAddFocus = useRef(false);const running = view?.running === true;const interfaces = view?.interfaces ?? [];const address = view?.address ?? interfaces.find((entry) => entry.address === preferredAddress)?.address ?? interfaces[0]?.address;const localOnly = address === "127.0.0.1";- const pending = view?.pending;- const devices = view?.devices;- const request = dialog?.kind === "approve" ? pending?.find((entry) => entry.id === dialog.id) : undefined;- const device = dialog?.kind === "edit" ? devices?.find((entry) => entry.id === dialog.id) : undefined;+ const paired = pairing && !busy && view?.code === null && view.devices.some((entry) => !pairing.has(entry.id));useEffect(() => {if (view?.address) setPreferredAddress(view.address);@@ -40,34 +31,18 @@ export function LanWebUiSection() {}, [view?.address, view?.port]);useEffect(() => {- if (!dialog) return;- if (!running || (dialog.kind === "approve" && !request) || (dialog.kind === "edit" && !device)) {- setDialog(null);- } else if (dialog.kind === "pair" && !busy) {- const received = pending?.find((entry) => !dialog.existingRequests.has(entry.id));- if (received) setDialog({ kind: "approve", id: received.id });- }- }, [busy, device, dialog, pending, request, running]);+ if (pairing && (!running || paired)) setPairing(null);+ }, [paired, pairing, running]);useEffect(() => {- if (dialog || busy || !opener.current) return;- // A review button is gone after approval; return to Add device instead.- const target = opener.current.isConnected ? opener.current : addDeviceRef.current;- opener.current = null;- target?.focus({ preventScroll: true });- }, [busy, dialog]);+ if (pairing || busy || !restoreAddFocus.current) return;+ restoreAddFocus.current = false;+ addDeviceRef.current?.focus({ preventScroll: true });+ }, [busy, pairing]);- const open = (next: Dialog, trigger: HTMLButtonElement) => {- opener.current = trigger;- clearError();- setDialog(next);- };const close = () => {clearError();- setDialog(null);- };- const submit = async (action: LanAdminAction) => {- if (await run(action)) close();+ setPairing(null);};const toggle = () => {if (running) {@@ -83,7 +58,6 @@ export function LanWebUiSection() {const errorText = error ? t(`lan:errors.${error}`, { defaultValue: t("lan:errors.FAILED") }) : null;const portErrorText = portError ? t("lan:errors.INVALID_PORT") : error === "PORT_IN_USE" ? errorText : null;const time = (ts: number) => formatUpdated(ts, i18n.language);- const list = new Intl.ListFormat(i18n.language || undefined, { style: "short" });const status = loadFailed ? t("statusUnavailable") : !view ? t("statusLoading"): running ? t("statusOn", { count: view.devices.length }) : t("statusOff");@@ -150,7 +124,7 @@ export function LanWebUiSection() {</>) : null}- {!dialog && (portErrorText || errorText) ? (+ {!pairing && (portErrorText || errorText) ? (<p id={portErrorId} className="lan-error" role="alert">{portErrorText || errorText}</p>) : null}</SettingsCard>@@ -158,10 +132,11 @@ export function LanWebUiSection() {{running && view ? (<SettingsCardtitle={t("devices")}- caption={t("devicesCaption")}action={(- <Button ref={addDeviceRef} type="button" variant="primary" disabled={busy} onClick={(event) => {- open({ kind: "pair", existingRequests: new Set(view.pending.map((entry) => entry.id)) }, event.currentTarget);+ <Button ref={addDeviceRef} type="button" variant="primary" disabled={busy} onClick={() => {+ clearError();+ restoreAddFocus.current = true;+ setPairing(new Set(view.devices.map((entry) => entry.id)));void run({ kind: "issueCode" });}}><IconPlus size={14} aria-hidden="true" />@@ -169,45 +144,20 @@ export function LanWebUiSection() {</Button>)}>- {view.pending.length || view.devices.length ? (+ {view.devices.length ? (<ul className="lan-devices" role="list" aria-label={t("devices")}>- {view.pending.map((entry) => (- <li key={entry.id} className="lan-device is-request">+ {view.devices.map((entry) => (+ <li key={entry.id} className="lan-device"><span className="lan-device-icon" aria-hidden="true"><IconSmartphone size={16} /></span><div className="lan-device-copy">- <div className="lan-device-name">{t("requestTitle", { label: entry.label })}</div>- <div className="lan-device-meta">{t("requestedAt", { time: time(entry.createdAt) })}</div>+ <div className="lan-device-name">{entry.label}</div>+ <div className="lan-device-meta">{t("activeAt", { time: time(entry.lastActiveAt) })}</div></div><div className="lan-device-actions">- <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void run({ kind: "deny", id: entry.id })}>{t("deny")}</Button>- <Button type="button" size="sm" variant="primary" disabled={busy} onClick={(event) => open({ kind: "approve", id: entry.id }, event.currentTarget)}>{t("review")}</Button>+ <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void run({ kind: "revoke", id: entry.id })}>{t("remove")}</Button></div></li>))}- {view.devices.map((entry) => {- const grants = entry.grants;- const actions = [grants.chat ? t("canChat") : "", grants.organize ? t("canOrganize") : ""].filter(Boolean);- return (- <li key={entry.id} className="lan-device">- <span className="lan-device-icon" aria-hidden="true"><IconSmartphone size={16} /></span>- <div className="lan-device-copy">- <div className="lan-device-name">{entry.label}</div>- <div className="lan-device-meta">- {[- t("scopeAll"),- grants.temporary ? t("scopeTemporary") : null,- actions.length ? list.format(actions) : t("viewOnly"),- t("activeAt", { time: time(entry.lastActiveAt) }),- ].filter(Boolean).join(" · ")}- </div>- </div>- <div className="lan-device-actions">- <Button type="button" size="sm" disabled={busy} onClick={(event) => open({ kind: "edit", id: entry.id }, event.currentTarget)}>{t("permissions")}</Button>- <Button type="button" size="sm" variant="ghost" disabled={busy} onClick={() => void run({ kind: "revoke", id: entry.id })}>{t("remove")}</Button>- </div>- </li>- );- })}</ul>) : (<div className="lan-devices-empty" role="status">@@ -218,7 +168,7 @@ export function LanWebUiSection() {</SettingsCard>) : null}- {dialog?.kind === "pair" && view?.origin ? (+ {pairing && !paired && view?.origin ? (<LanPairDialogorigin={view.origin}code={view.code}@@ -228,31 +178,6 @@ export function LanWebUiSection() {onClose={close}/>) : null}- {request && view ? (- <LanAccessDialog- key={request.id}- mode="approve"- label={request.label}- initial={NEW_DEVICE_GRANTS}- busy={busy}- error={errorText}- onSubmit={(grants) => void submit({ kind: "confirm", id: request.id, grants })}- onDeny={() => void submit({ kind: "deny", id: request.id })}- onClose={close}- />- ) : null}- {device && view ? (- <LanAccessDialog- key={device.id}- mode="edit"- label={device.label}- initial={device.grants}- busy={busy}- error={errorText}- onSubmit={(grants) => void submit({ kind: "update", id: device.id, grants })}- onClose={close}- />- ) : null}</>);}diff --git a/apps/desktop/src/locales/lan.ts b/apps/desktop/src/locales/lan.tsindex 5a5cac4a0..d0975c9d0 100644--- a/apps/desktop/src/locales/lan.ts+++ b/apps/desktop/src/locales/lan.ts@@ -20,22 +20,12 @@ export const lanEn = {copied: "Copied",copyFailed: "Couldn't copy",devices: "Devices",- devicesCaption: "Only devices you approve here can connect.",addDevice: "Add device",noDevices: "No devices paired yet.",- requestTitle: "{{label}} wants to connect",- requestedAt: "Requested {{time}}",- review: "Review request",- deny: "Deny",- permissions: "Permissions",remove: "Remove",activeAt: "Active {{time}}",- scopeAll: "All local projects",- scopeTemporary: "Temporary conversations",- canChat: "Can send",- canOrganize: "Can organize",- viewOnly: "View only",pairTitle: "Add a device",+ pairDescription: "This code lets a device view and change local projects and conversations, including temporary ones.",pairStepOpen: "On the device, open",pairStepCode: "Enter this pairing code",codeExpiresIn: "Expires in {{seconds}}s",@@ -44,26 +34,11 @@ export const lanEn = {newCode: "New code",waiting: "Waiting for the device…",close: "Close",- approveTitle: "Allow {{label}}?",- approveDescription: "This device can view current and future local projects, including archived conversations.",- editTitle: "{{label}} permissions",- temporaryHint: "Conversations that are not in a project",- chat: "Send messages and start conversations",- chatHint: "Also stop a reply or cancel a queued message",- organize: "Rename, pin and archive",- organizeHint: "Applies to projects and conversations",- approvalsStayHere: "Tool and plan approvals always stay on this computer.",- allow: "Allow",- save: "Save",- cancel: "Cancel",errors: {PORT_IN_USE: "That port is already in use. Choose another port.",INVALID_ADDRESS: "That network address is no longer available.",INVALID_PORT: "Use a port between 1024 and 65535.",NOT_RUNNING: "Turn the service on first.",- NOT_FOUND: "This device or request is no longer available.",- INVALID_SCOPE: "This approval uses outdated settings. Restart PI-Desktop and try again.",- RATE_LIMITED: "Too many devices. Remove one first.",FAILED: "The action failed. Try again.",},};@@ -89,22 +64,12 @@ export const lanZh: typeof lanEn = {copied: "已复制",copyFailed: "复制失败",devices: "设备",- devicesCaption: "只有在这里批准的设备才能连接。",addDevice: "添加设备",noDevices: "还没有配对的设备。",- requestTitle: "{{label}} 请求连接",- requestedAt: "{{time}}请求",- review: "查看请求",- deny: "拒绝",- permissions: "权限",remove: "移除",activeAt: "{{time}}活跃",- scopeAll: "所有本机项目",- scopeTemporary: "临时会话",- canChat: "可发消息",- canOrganize: "可整理",- viewOnly: "仅查看",pairTitle: "添加设备",+ pairDescription: "持有此码的设备可直接查看并操作本机项目及临时会话。",pairStepOpen: "在设备上打开",pairStepCode: "输入配对码",codeExpiresIn: "{{seconds}} 秒后失效",@@ -113,26 +78,11 @@ export const lanZh: typeof lanEn = {newCode: "重新生成",waiting: "等待设备输入配对码…",close: "关闭",- approveTitle: "允许 {{label}} 连接?",- approveDescription: "这台设备可查看现有和以后新增的本机项目,包括已归档的会话。",- editTitle: "{{label}} 的权限",- temporaryHint: "不属于任何项目的会话",- chat: "发消息和新建会话",- chatHint: "也可以停止回复、取消排队消息",- organize: "重命名、置顶和归档",- organizeHint: "适用于项目和会话",- approvalsStayHere: "工具和计划审批始终只在这台电脑上完成。",- allow: "允许",- save: "保存",- cancel: "取消",errors: {PORT_IN_USE: "该端口已被占用,请换一个端口。",INVALID_ADDRESS: "该网络地址已不可用。",INVALID_PORT: "请使用 1024 到 65535 之间的端口。",NOT_RUNNING: "请先开启服务。",- NOT_FOUND: "该设备或请求已失效。",- INVALID_SCOPE: "授权设置已过期,请重启 PI-Desktop 后重试。",- RATE_LIMITED: "设备过多,请先移除一台。",FAILED: "操作失败,请重试。",},};diff --git a/apps/desktop/src/styles/lan-webui.css b/apps/desktop/src/styles/lan-webui.cssindex d01516371..ab66e73af 100644--- a/apps/desktop/src/styles/lan-webui.css+++ b/apps/desktop/src/styles/lan-webui.css@@ -65,9 +65,7 @@.lan-device-meta,.lan-dialog-description,.lan-code-meta,-.lan-pair-waiting,-.lan-grants-option-hint,-.lan-grants-note {+.lan-pair-waiting {color: var(--ds-text-secondary);font-size: var(--text-sm-plus);line-height: var(--leading-body);@@ -112,10 +110,6 @@border-block-start: 1px solid var(--ds-border-subtle);}-.lan-device.is-request {- background: color-mix(in oklab, var(--ds-accent) 7%, var(--ds-tile));-}-.lan-device-actions,.lan-code-meta {display: flex;@@ -324,61 +318,3 @@border-radius: var(--radius-full);background: var(--ds-success);}--.lan-grants {- display: grid;- gap: 16px;-}--.lan-grants-list {- display: grid;- border: 1px solid var(--ds-border-subtle);- border-radius: var(--radius-md-plus);- background: var(--ds-tile);-}--.lan-grants-list > :not(:first-child) {- border-top: 1px solid var(--ds-border-subtle);-}--.lan-grants-option.ui-checkbox,-.lan-grants-fixed {- min-height: 40px;- padding: 9px 12px;-}--.lan-grants-option.ui-checkbox {- gap: 10px;-}--.lan-grants-option.ui-checkbox:has(input:checked) {- background: color-mix(in oklab, var(--ds-accent) 7%, transparent);-}--.lan-grants-option.ui-checkbox:hover:not(:has(input:disabled)) {- background: var(--ds-tile-hover);-}--.lan-grants-option-copy {- display: grid;- gap: 2px;-}--.lan-grants-option-label {- color: var(--ds-text-primary);- font-size: var(--text-sm-plus);-}--.lan-grants-fixed,-.lan-grants-note {- display: flex;- align-items: center;- gap: 10px;- margin: 0;-}--.lan-grants-fixed > svg,-.lan-grants-note > svg {- flex: 0 0 auto;- color: var(--ds-text-secondary);-}diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjsindex 2e154673a..1d951bb1c 100644--- a/apps/desktop/test/lan-webui-browser-user-path.test.mjs+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs@@ -40,9 +40,14 @@ const journey = String.raw`(async () => {code.value = window.__code;document.querySelector(".pair button[type=submit]").click();- // Desktop approves the device; both local projects appear, but the SSH project does not.+ // Redeeming the code connects immediately, without a second Desktop action.await wait(() => rowByTitle("Alpha"), "projects");result.projects = [...document.querySelectorAll(".row-title")].map((n) => n.textContent);+ const temporary = await wait(() => rowByTitle("Temporary conversations") ?? rowByTitle("临时会话"), "temporary entry");+ temporary.querySelector(".row-main").click();+ await wait(() => rowByTitle("Scratch") && document.querySelector("main > button.primary"), "temporary conversations");+ history.back();+ await wait(() => rowByTitle("Alpha"), "back to projects");// Open a project and see its sessions.rowByTitle("Alpha").querySelector(".row-main").click();@@ -78,44 +83,23 @@ const journey = String.raw`(async () => {history.back();await wait(() => rowByTitle("Fix login"), "back to sessions");result.backHash = location.hash;- return JSON.stringify(result);-})()`;--const afterGrantEdit = String.raw`(async () => {- const waitForRow = async (label, ready = () => true) => {- const deadline = performance.now() + 10_000;- while (performance.now() < deadline) {- const row = [...document.querySelectorAll(".row")].find((item) => item.querySelector(".row-title")?.textContent === label);- if (row && ready(row)) return row;- await new Promise(requestAnimationFrame);- }- throw new Error("Missing row after grant edit: " + label);- };- const readOnly = (row) => !row.querySelector(".row-more") && !document.querySelector("main > button.primary");- await waitForRow("Fix login", readOnly);history.back();- await waitForRow("Alpha");- const projectTitles = [...document.querySelectorAll(".row-title")].map((item) => item.textContent);- (await waitForRow("Beta")).querySelector(".row-main").click();- const session = await waitForRow("Second root chat");- return { projectTitles, readOnly: readOnly(session), pairingShown: Boolean(document.getElementById("pair-code")) };+ await wait(() => rowByTitle("Alpha"), "back to projects before sign-out");+ document.querySelector("main > button.link").click();+ await wait(() => document.getElementById("pair-code"), "sign-out returns to pairing");+ result.polledApproval = performance.getEntriesByType("resource").some((entry) => new URL(entry.name).pathname === "/pair/status");+ return JSON.stringify(result);})()`;-test("a phone pairs, organizes, chats and follows updated grants through the real page", { timeout: 60_000 }, async (t) => {+test("a phone pairs by code, uses projects and temporary conversations, and signs out", { 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, { projectScope: "all-local", 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 });@@ -123,19 +107,14 @@ test("a phone pairs, organizes, chats and follows updated grants through the reaawait writeFile(join(temp, "main.cjs"), `const { app, BrowserWindow } = require("electron");const path = require("node:path");-const { once } = require("node:events");app.setPath("userData", path.join(__dirname, "profile"));app.whenReady().then(async () => {const window = new BrowserWindow({ show: false, width: 390, height: 844, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });try {await window.loadURL(${JSON.stringify(`http://127.0.0.1:${port}/`)});- await window.webContents.executeJavaScript("window.__code = ${code};");+ await window.webContents.executeJavaScript("window.__code = '${code}';");const output = await window.webContents.executeJavaScript(${JSON.stringify(journey)});- const edited = once(process.stdin, "data");- process.stdout.write("EDIT_GRANTS\\n");- await edited;- const afterEdit = await window.webContents.executeJavaScript(${JSON.stringify(afterGrantEdit)});- process.stdout.write("RESULT " + JSON.stringify({ ...JSON.parse(output), afterEdit }) + "\\n");+ process.stdout.write("RESULT " + output + "\\n");app.exit(0);} catch (error) {process.stderr.write(String(error && error.stack || error) + "\\n");@@ -148,15 +127,7 @@ app.whenReady().then(async () => {const child = spawn(electronBinary, [join(temp, "main.cjs")], { env, signal: t.signal });let stdout = "";let stderr = "";- let edited = false;- child.stdout.on("data", (chunk) => {- stdout += chunk;- if (edited || !stdout.includes("EDIT_GRANTS\n")) return;- edited = true;- const [device] = server.devices();- if (device) server.update(device.id, { projectScope: "all-local", temporary: false, chat: false, organize: false });- child.stdin.end("updated");- });+ child.stdout.on("data", (chunk) => { stdout += chunk; });child.stderr.on("data", (chunk) => (stderr += chunk));const [exitCode] = await once(child, "close");assert.equal(exitCode, 0, stderr);@@ -164,7 +135,8 @@ app.whenReady().then(async () => {assert.ok(line, stdout + stderr);const result = JSON.parse(line.slice(7));- assert.deepEqual(result.projects, ["Alpha", "Beta"]);+ assert.match(result.projects[0], /^(Temporary conversations|临时会话)$/);+ assert.deepEqual(result.projects.slice(1), ["Alpha", "Beta"]);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");@@ -179,5 +151,6 @@ app.whenReady().then(async () => {assert.equal(result.horizontalScroll, false);assert.equal(result.smallTargets, 0);assert.equal(result.backHash, "#/p/g-a");- assert.deepEqual(result.afterEdit, { projectTitles: ["Alpha", "Beta"], readOnly: true, pairingShown: false });+ assert.equal(result.polledApproval, false);+ assert.equal(server.devices().length, 0, "browser sign-out revoked its device");});diff --git a/apps/desktop/test/lan-webui-settings-user-path.test.mjs b/apps/desktop/test/lan-webui-settings-user-path.test.mjsindex 4d5dbdc4e..f0d0e09b2 100644--- a/apps/desktop/test/lan-webui-settings-user-path.test.mjs+++ b/apps/desktop/test/lan-webui-settings-user-path.test.mjs@@ -32,7 +32,7 @@ const listeners = new Set();const writes = [];const copied = [];const view = {- running: false, origin: null, address: null, port: null, code: null, pending: [], devices: [], error: null,+ running: false, origin: null, address: null, port: null, code: null, devices: [], error: null,interfaces: [{ address: "192.168.1.20", name: "Wi-Fi" }],};let stateReads = 0;@@ -68,23 +68,11 @@ window.piDesktop = {issueCount++;view.code = { value: ["000012", "134209", "512309"][issueCount - 1], expiresAt: Date.now() + (issueCount === 1 ? -1000 : 300_000) };break;- case "confirm": {- const request = view.pending.find((item) => item.id === action.id);- view.pending = view.pending.filter((item) => item.id !== action.id);- view.devices.push({ id: "device", label: request.label, grants: action.grants, lastActiveAt: Date.now() });- break;- }- case "update":- view.devices.find((item) => item.id === action.id).grants = action.grants;- break;- case "deny":- view.pending = view.pending.filter((item) => item.id !== action.id);- break;case "revoke":view.devices = view.devices.filter((item) => item.id !== action.id);break;case "stop":- Object.assign(view, { running: false, address: null, port: null, origin: null, code: null, pending: [], devices: [] });+ Object.assign(view, { running: false, address: null, port: null, origin: null, code: null, devices: [] });break;default:throw new Error("Unexpected LAN action: " + action.kind);@@ -120,7 +108,6 @@ const title = () => q("h2", dialog())?.textContent;const toggle = () => q('[role="switch"][aria-label="Allow LAN connections"]');const field = () => q('input[aria-label="Port"]');const alert = () => q('[role="alert"]', section())?.textContent;-const checkbox = (name) => [...dialog().querySelectorAll("label")].find((label) => label.textContent.startsWith(name)).querySelector("input");const click = (element) => { check(element && !element.disabled, "Missing or disabled control"); element.focus(); element.click(); };const press = (key, shiftKey = false) => document.activeElement.dispatchEvent(new KeyboardEvent("keydown", { key, shiftKey, bubbles: true, cancelable: true }));const input = (value) => {@@ -156,44 +143,26 @@ window.lanSettingsProbe = async () => {click(button(lanEn.copy));await wait(() => button(lanEn.copied), "clipboard feedback");- view.pending.push({ id: "old", label: "Other phone", createdAt: Date.now() });- emit();- await wait(() => button(lanEn.review), "pending request from Main");click(button(lanEn.addDevice));await wait(() => title() === lanEn.pairTitle && dialog().textContent.includes(lanEn.codeExpired), "expired pairing code");check(fitsDialog(), "pairing fits a narrow dark window");+ check(dialog().textContent.includes(lanEn.pairDescription), "the code dialog discloses its access");click(button(lanEn.newCode, dialog()));await wait(() => q(".lan-code")?.textContent === "134209", "replacement code");await wait(() => dialog().contains(document.activeElement), "focus in pair dialog");press("Escape");await wait(() => !dialog() && document.activeElement === button(lanEn.addDevice), "Escape returns focus");+ document.documentElement.dataset.theme = "light";click(button(lanEn.addDevice));await wait(() => q(".lan-code")?.textContent === "512309", "fresh code when opened again");- view.pending.push({ id: "phone", label: "iPhone", createdAt: Date.now() });+ check(fitsDialog() && !dialog().querySelector('input[type="checkbox"]'), "pairing fits the light window without permission controls");+ q(".lan-dialog-close", dialog()).focus();+ check(!press("Tab", true) && document.activeElement === button(lanEn.newCode, dialog()), "Shift+Tab stays in the pairing dialog");+ view.devices.push({ id: "device", label: "iPhone", lastActiveAt: Date.now() });view.code = null;emit();- await wait(() => title() === "Allow iPhone?", "new request advances directly to approval");- await wait(() => dialog().contains(document.activeElement), "focus moves into approval");- check(!button(lanEn.allow, dialog()).disabled, "device approval does not require choosing a project");- check(dialog().textContent.includes(lanEn.scopeAll) && dialog().textContent.includes(lanEn.approveDescription), "approval discloses access to all local projects");- check(dialog().querySelectorAll('input[type="checkbox"]').length === 3 && !checkbox(lanEn.scopeTemporary).checked, "only optional permissions are configurable");- q(".lan-dialog-close", dialog()).focus();- check(!press("Tab", true) && document.activeElement === button(lanEn.allow, dialog()), "Shift+Tab stays in the approval dialog");- click(button(lanEn.allow, dialog()));- await wait(() => !dialog() && button(lanEn.permissions) && document.activeElement === button(lanEn.addDevice), "paired device row and restored focus");-- document.documentElement.dataset.theme = "light";- click(button(lanEn.permissions));- await wait(() => title() === "iPhone permissions", "edit device");- check(dialog().textContent.includes(lanEn.scopeAll) && !checkbox(lanEn.scopeTemporary).checked && fitsDialog(), "device permissions fit in a narrow light window");- click(checkbox(lanEn.chat));- click(checkbox(lanEn.organize));- await wait(() => !button(lanEn.save, dialog()).disabled && !checkbox(lanEn.chat).checked, "view-only edit");- click(button(lanEn.save, dialog()));- await wait(() => !dialog() && q(".lan-device:not(.is-request)")?.textContent.includes(lanEn.viewOnly), "device updates without re-pairing");- check(q(".lan-device:not(.is-request)").textContent.includes(lanEn.scopeAll), "project access is retained in view-only mode");- click(button(lanEn.deny, q(".lan-device.is-request")));- await wait(() => !q(".lan-device.is-request"), "deny pre-existing request");+ await wait(() => !dialog() && q(".lan-device-name")?.textContent === "iPhone" && document.activeElement === button(lanEn.addDevice), "paired device appears directly and focus returns");+ check(q(".lan-device").querySelectorAll("button").length === 1, "a paired device can be removed, not configured");click(button(lanEn.remove));await wait(() => q(".lan-devices-empty")?.textContent === lanEn.noDevices, "device removed");click(toggle());@@ -205,7 +174,7 @@ window.lanSettingsProbe = async () => {};`;-test("Desktop Settings starts, pairs, edits and removes a LAN device", {+test("Desktop Settings shows a code, registers the paired device directly, and removes it", {timeout: 60_000,skip: process.platform === "linux" && !process.env.DISPLAY ? "Isolated Electron test requires a display" : false,}, async (t) => {@@ -256,9 +225,7 @@ app.whenReady().then(async () => {{ kind: "start", address: "192.168.1.20", port: 38180 },{ kind: "start", address: "192.168.1.20", port: 38180 },{ kind: "issueCode" }, { kind: "issueCode" }, { kind: "issueCode" },- { kind: "confirm", id: "phone", grants: { projectScope: "all-local", temporary: false, chat: true, organize: true } },- { kind: "update", id: "device", grants: { projectScope: "all-local", temporary: false, chat: false, organize: false } },- { kind: "deny", id: "old" }, { kind: "revoke", id: "device" }, { kind: "stop" },+ { kind: "revoke", id: "device" }, { kind: "stop" },],copied: ["http://192.168.1.20:38180"],remainingListeners: 0,diff --git a/apps/desktop/test/lan-webui-user-path.test.mjs b/apps/desktop/test/lan-webui-user-path.test.mjsindex 96314c418..ac605396c 100644--- a/apps/desktop/test/lan-webui-user-path.test.mjs+++ b/apps/desktop/test/lan-webui-user-path.test.mjs@@ -3,11 +3,9 @@ import test from "node:test";import { request } from "node:http";import { browser, createLanServer, desktop } from "./helpers/lan-webui-fixture.mjs";-const allProjects = { projectScope: "all-local", temporary: false, chat: true, organize: true };--async function setup(t, grants, wrapHandler = (workspace) => workspace) {+async function setup(t, { wrapHandler = (workspace) => workspace, now } = {}) {const fake = desktop();- const server = createLanServer({ handler: wrapHandler(fake.workspace), assets: new Map([["/index.html", { type: "text/html", body: "<p>ok</p>" }]]) });+ const server = createLanServer({ handler: wrapHandler(fake.workspace), now, 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();@@ -15,24 +13,20 @@ async function setup(t, grants, wrapHandler = (workspace) => workspace) {});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");+ assert.equal((await phone.request("GET", "/v1/me")).status, 401);+ assert.equal((await phone.request("GET", "/pair/status")).status, 401);assert.equal((await phone.request("GET", "/v1/projects")).status, 401);- const [pending] = server.pending();- assert.equal(pending.label, "iPhone");- assert.throws(() => server.confirm(pending.id, { projectIds: ["g-a"], temporary: false, chat: true, organize: true }), { code: "INVALID_SCOPE" });- assert.equal((await phone.request("GET", "/pair/status")).body.state, "pending");- server.confirm(pending.id, grants);- assert.equal((await phone.request("GET", "/pair/status")).body.state, "paired");+ const { value: code } = server.issueCode();+ assert.deepEqual(await phone.request("POST", "/pair", { code, label: "iPhone" }), { status: 200, body: { state: "paired" } });+ assert.equal(server.code(), null);+ assert.equal(server.devices()[0].label, "iPhone");await phone.signIn();+ assert.deepEqual(await phone.request("GET", "/pair/status"), { status: 200, body: { state: "paired" } });return { ...fake, server, phone, origin };}test("pair, browse all local projects, create, chat and organize from a phone", async (t) => {- const { phone, calls, turns, activeTurns, meta, server } = await setup(t, allProjects);+ const { phone, calls, turns, activeTurns, meta, server } = await setup(t);// No project choices are required; the SSH-backed group stays hidden.const projects = await phone.request("GET", "/v1/projects?q=");@@ -101,17 +95,14 @@ test("pair, browse all local projects, create, chat and organize from a phone",assert.equal((await phone.request("GET", "/v1/projects")).status, 401);});-test("remote projects, temporary scope, mutation grants and request guards fail closed", async (t) => {- const { phone, origin, server } = await setup(t, { ...allProjects, chat: false, organize: false });+test("remote projects, unregistered sessions and transport guards stay restricted", async (t) => {+ const { phone, origin, server } = await setup(t);- for (const path of ["/v1/sessions?projectId=g-r", "/v1/sessions/s-ssh", "/v1/sessions/s-ungrouped", "/v1/sessions/s-tmp", "/v1/sessions?projectId=__temporary__"]) {+ for (const path of ["/v1/sessions?projectId=g-r", "/v1/sessions/s-ssh", "/v1/sessions/s-ungrouped"]) {assert.equal((await phone.request("GET", path)).status, 404, path);}assert.equal((await phone.request("GET", "/v1/sessions/s-b1")).status, 200);- 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");+ assert.equal((await phone.request("POST", "/v1/permissions/approve", {})).status, 404);// 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");@@ -142,7 +133,7 @@ test("remote projects, temporary scope, mutation grants and request guards fail});test("a paired device sees newly added projects and distinguishes duplicate names without paths", async (t) => {- const { phone, groups } = await setup(t, allProjects);+ const { phone, groups } = await setup(t);assert.deepEqual((await phone.request("GET", "/v1/projects")).body.items.map((project) => project.id), ["g-a", "g-b"]);groups.push({ id: "g-a2", name: "Alpha", primaryPath: "/elsewhere/clone/a", roots: [{ path: "/elsewhere/clone/a", name: "a", position: 0 }], pinned: false, lastOpenedAt: 0, createdAt: 0, updatedAt: 0 });const projects = (await phone.request("GET", "/v1/projects")).body.items;@@ -150,34 +141,55 @@ test("a paired device sees newly added projects and distinguishes duplicate nameassert.equal((await phone.request("GET", "/v1/sessions?projectId=g-a2")).status, 200);});-test("temporary conversations need their own grant", async (t) => {- const { phone, calls } = await setup(t, { ...allProjects, temporary: true, organize: false });+test("pairing grants temporary conversations without a separate permission", async (t) => {+ const { phone, calls, turns } = await setup(t);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, 200);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");+ assert.equal((await phone.request("POST", `/v1/sessions/${created.body.id}/turns`, { text: "hello" })).status, 200);+ assert.equal(turns[0].params.sessionId, created.body.id);+});++test("pairing codes expire and exactly one redemption creates a device", async (t) => {+ let time = Date.now();+ const { server, origin } = await setup(t, { now: () => time });+ const expired = server.issueCode();+ time = expired.expiresAt;+ assert.equal((await browser(origin).request("POST", "/pair", { code: expired.value })).body.code, "PAIRING_CLOSED");++ const { value: code } = server.issueCode();+ const redeem = () => fetch(`${origin}/pair`, {+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ code }),+ });+ const responses = await Promise.all([redeem(), redeem()]);+ assert.deepEqual(responses.map((response) => response.status).sort(), [200, 403]);+ const accepted = responses.find((response) => response.ok);+ const [cookie] = accepted.headers.getSetCookie();+ assert.match(cookie, /^pi_lan=[^;]+; Path=\/; HttpOnly; SameSite=Strict; Max-Age=43200$/);+ assert.equal(responses.find((response) => !response.ok).headers.getSetCookie().length, 0);+ assert.equal(server.devices().length, 2);});-test("editing temporary and mutation grants discards stale results without pairing again", { timeout: 10_000 }, async (t) => {+test("removing a device closes its stream and discards in-flight results", { timeout: 10_000 }, async (t) => {const prepared = Promise.withResolvers();const release = Promise.withResolvers();t.after(() => release.resolve());const { phone, server, calls } = await setup(t, {- ...allProjects, temporary: true,- }, (workspace) => ({- ...workspace,- async handle(request, key) {- const result = await workspace.handle(request, key);- if (request.path === "/v1/sessions/s-tmp") {- prepared.resolve();- await release.promise;- }- return result;- },- }));+ wrapHandler: (workspace) => ({+ ...workspace,+ async handle(request, key) {+ const result = await workspace.handle(request, key);+ if (request.path === "/v1/sessions/s-tmp") {+ prepared.resolve();+ await release.promise;+ }+ return result;+ },+ }),+ });const id = server.devices()[0].id;- assert.throws(() => server.update(id, { projectIds: ["g-a"], temporary: false, chat: true, organize: true }), { code: "INVALID_SCOPE" });const mutation = { "Idempotency-Key": "device-edit-create" };assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, mutation)).status, 200);const stream = await phone.events("/v1/sessions/s-tmp/events", t.signal);@@ -187,17 +199,28 @@ test("editing temporary and mutation grants discards stale results without pairiconst inFlight = phone.request("GET", "/v1/sessions/s-tmp");await prepared.promise;- server.update(id, { ...allProjects, chat: false, organize: false });+ server.revoke(id);release.resolve();- assert.deepEqual(await inFlight, { status: 409, body: { code: "CONFLICT" } });- assert.equal((await reader.read()).done, true, "editing grants closes the subscribed stream");- assert.equal((await phone.events("/v1/sessions/s-tmp/events", t.signal)).status, 404);- assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, mutation)).status, 409);+ assert.deepEqual(await inFlight, { status: 401, body: { code: "UNAUTHORIZED" } });+ assert.equal((await reader.read()).done, true, "removing the device closes the subscribed stream");+ assert.equal((await phone.events("/v1/sessions/s-tmp/events", t.signal)).status, 401);+ assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-a" }, mutation)).status, 401);assert.equal(calls.filter(([channel]) => channel === "create").length, 1);+ assert.equal((await phone.request("GET", "/v1/projects")).status, 401);+});- const me = await phone.request("GET", "/v1/me");- assert.deepEqual(me.body.access, { deviceId: id, ...allProjects, chat: false, organize: false });- assert.deepEqual((await phone.request("GET", "/v1/projects")).body.items.map((project) => project.id), ["g-a", "g-b"]);- assert.equal((await phone.request("GET", "/v1/sessions/s-tmp")).status, 404);- assert.equal((await phone.request("POST", "/v1/sessions", { projectId: "g-b" })).status, 403);+test("direct pairing respects the device limit without disconnecting other devices", async (t) => {+ const { server, origin, phone } = await setup(t);+ for (let index = 1; index < 16; index += 1) {+ const { value: code } = server.issueCode();+ assert.equal((await browser(origin).request("POST", "/pair", { code, label: `Device ${index}` })).status, 200);+ }+ const { value: code } = server.issueCode();+ const next = browser(origin);+ assert.deepEqual(await next.request("POST", "/pair", { code }), { status: 429, body: { code: "RATE_LIMITED" } });+ assert.equal((await next.request("GET", "/v1/me")).status, 401);+ server.revoke(server.devices()[1].id);+ assert.equal((await next.request("POST", "/pair", { code })).status, 200);+ assert.equal((await phone.request("GET", "/v1/projects")).status, 200);+ assert.equal(server.devices().length, 16);});diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 98c208080..7c028f7a9 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -26,7 +26,8 @@ git history.| ID | Title | Status ||---|---|---|-| lan-webui-project-access | [Device confirmation grants access to all local LAN WebUI projects](lan-webui-project-access.md) | Accepted |+| lan-webui-code-pairing | [A one-time code pairs a LAN WebUI device directly](lan-webui-code-pairing.md) | Accepted |+| lan-webui-project-access | [Device confirmation grants access to all local LAN WebUI projects](lan-webui-project-access.md) | Superseded || codemode-sandbox-boundary | [Codemode sandbox execution boundary](codemode-sandbox-boundary.md) | Accepted || mode-definitions | [User-definable modes as staged workflows](mode-definitions.md) | Proposed || sidebar-layout-recovery | [Recover sidebar layout independently of Chromium storage](sidebar-layout-recovery.md) | Accepted |diff --git a/docs/adr/lan-webui-code-pairing.md b/docs/adr/lan-webui-code-pairing.mdnew file mode 100644index 000000000..c9802ab15--- /dev/null+++ b/docs/adr/lan-webui-code-pairing.md@@ -0,0 +1,34 @@+# ADR: A one-time code pairs a LAN WebUI device directly++- Status: Accepted+- Date: 2026-11-26+- Supersedes: [Desktop confirmation for LAN WebUI projects](lan-webui-project-access.md)+- Related: [LAN WebUI MVP](../spec/01-product/03-lan-webui-mvp.md), [ADR 0205](0205-remote-agent-control-boundary.md)++## Context++The LAN WebUI is off by default. Enabling it and sharing a locally generated+code were followed by a second device confirmation and optional per-device+grants. The intended personal LAN workflow should need only the code.++## Decision++Redeeming a current, single-use code immediately issues the authenticated+browser session. The same supported local project and temporary-conversation+operations are available to every paired device. Remove the pending state,+confirmation dialog and editable grants. The code dialog discloses the access+it grants, and Desktop still lists and revokes devices.++Keep the private bind, Host/Origin checks, attempt and device limits, cookie+and CSRF validation, and memory-only credentials. Pairing does not issue an+owner or SSH principal or grant generic IPC. Resource eligibility, the remote+`ask` ceiling, and Desktop-only tool and plan approvals are unchanged.++## Consequences++Anyone who obtains an active code can pair without another prompt. Display it+only for an intended device and use the existing plain-HTTP service only on a+trusted LAN. Stop the service or remove a device to revoke access.++No durable grants are migrated. An app restart invalidates existing pairings;+older open browser tabs can still check the issued cookie with `/pair/status`.diff --git a/docs/adr/lan-webui-project-access.md b/docs/adr/lan-webui-project-access.mdindex d2b49ca53..9a5b860fe 100644--- a/docs/adr/lan-webui-project-access.md+++ b/docs/adr/lan-webui-project-access.md@@ -1,34 +1,17 @@# ADR: Device confirmation grants access to all local LAN WebUI projects-- Status: Accepted+- Status: Superseded by [One-time code pairing](lan-webui-code-pairing.md)- Date: 2026-11-26-- Related: [ADR 0205](0205-remote-agent-control-boundary.md), [LAN WebUI MVP](../spec/01-product/03-lan-webui-mvp.md)## Context-The LAN companion is an opt-in view of the running Desktop. Per-project-allowlists made each new device pairing depend on a second selection, and new-local projects remained hidden from already paired devices.+Individual project allowlists made pairing depend on a second selection.## Decision-The local user still confirms each browser after one-time code pairing. That-confirmation explicitly grants visibility of the current and future eligible-local projects, including archived history, without an individual checklist.-The Desktop edge reads the current local catalog for requests; it does not-snapshot project IDs or include SSH-backed projects. Temporary conversations-remain off by default, and the Chat and Organize grants and the remote `ask`-ceiling still apply. Transport, process ownership, and the RACP role model do-not change.+The original decision shared all local projects after a separate confirmation.+It is superseded by [One-time code pairing](lan-webui-code-pairing.md).## Consequences-A paired device can read a newly registered local project without another-prompt. Keep this visible at confirmation and remove devices that should no-longer share the Desktop's projects. Keep the listener off on untrusted networks.--The private LAN admin contract and the WebUI's access metadata replace the MVP's-project ID list with an explicit `all-local` scope marker. Stale confirmation-or update requests without the marker fail closed. Pairings are memory-only;-updating/restarting Desktop requires a fresh confirmation, not a persisted grant-migration.+See the [LAN WebUI MVP](../spec/01-product/03-lan-webui-mvp.md) for current behavior.diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.mdindex 8fa377c81..9b232804d 100644--- a/docs/spec/01-product/03-lan-webui-mvp.md+++ b/docs/spec/01-product/03-lan-webui-mvp.md@@ -26,7 +26,7 @@ numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remo| 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 |+| W06 | Revoke paired devices and 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 |@@ -44,44 +44,37 @@ numbers refer to the [WebUI acceptance catalog](../06-delivery/e2e/live-and-remorebinding) or whose `Origin` is foreign, requires a CSRF token on everyauthenticated mutation, and serves a restrictive CSP. Adding HTTPS later mustnot change the browser API.-3. Once the listener is on, the connection card shows a copyable address and- the Devices card shows pending requests and paired devices. **Add device**- opens a two-step dialog with the address, one-time 6-digit code and expiry.- A new request while the dialog is open advances it to device confirmation;- requests already waiting can be reviewed or denied from the Devices card.- Confirmation discloses access to all eligible local projects, including- projects added later, and does not require individual project selections.- No catalog or history is sent before confirmation. Each code lasts at most- five minutes, is single-use, and expires after five failed attempts. Only- Desktop can generate a replacement code. A QR code is deferred.-4. Device rows show the label, last activity and access summary. **Permissions**- edits temporary access and actions without pairing again. The listener closes- existing streams and does not return pending or cached results under the old grants.- The browser refetches its access and view when it reconnects. **Remove** and- browser sign-out invalidate that device's cookie and streams. Turning off- closes the listener and invalidates every pairing; turning it back on+3. Once the listener is on, **Add device** shows the address and a one-time+ 6-digit code. The dialog discloses that the code grants access to the local+ WebUI, including temporary conversations and supported changes. A valid+ code immediately issues the device cookie; no additional Desktop approval+ or permission configuration is required. No project data is sent before+ pairing. Each code lasts five minutes at most and is invalidated after use+ or five failed attempts. Only Desktop can generate a code. A QR code is deferred.+4. Devices shows the label and last activity of each paired browser. **Remove**+ and browser sign-out invalidate that device's cookie and streams. Turning+ off closes the listener and signs out every device; a subsequent startrequires fresh pairing. Closing a browser tab is not sign-out.5. Minimizing or hiding Desktop does not stop the service. Phone backgrounding,- Wi-Fi loss or closing a tab is not a stop or approval command. Locking the- computer grants no new authority: new pairing and manual approvals still- 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.+ Wi-Fi loss or closing a tab does not stop it. A browser cannot generate a+ pairing code or submit a tool or plan approval. Sleep makes Desktop+ unreachable. If the bound address changes, restart the service on Desktop.+ Quitting Desktop stops the service; each launch starts **off**. Do not+ 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+wrong/expired code, device limit, revoked device or desktop offline. A phoneunable to reach the Host cannot diagnose why; offer the address and localnetwork checks, not a false claim that the desktop quit. Never open firewall orrouter ports, use UPnP, or set up a tunnel automatically.Desktop administration stays on the main-window-only LAN admin IPC channel.-`confirm` and `update` require `projectScope: "all-local"`, not a list of project-IDs. A stale request without this marker is refused rather than widening a-prior selection. `/v1/me` reports the same marker; `/v1/projects` is the live-catalog, not a snapshot attached to pairing. The payload-free `lanWebUiChanged`-event asks the Desktop renderer to refetch after listener, pairing or device changes.+The payload-free `lanWebUiChanged` event asks the renderer to refetch after+listener, code or device changes. `POST /pair` returns `{ state: "paired" }`+and sets the session cookie in the same response. `/pair/status` checks an+already-established cookie for older browser tabs; there is no pending state.+`/v1/me` retains the former access flags as fixed compatibility metadata.## 3. Projects and sessions (W02, W03)@@ -90,7 +83,7 @@ event asks the Desktop renderer to refetch after listener, pairing or device cha| Projects | Show all eligible local desktop projects, including closed or archived ones and projects added after pairing, not just the visible sidebar. A logical multi-root group is **one** project. Search by display name across the catalog, switch, rename the display name, pin/unpin, archive/restore. Show pinned first, then recent; distinguish “no local projects”, “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. |+| Temporary | Any paired device can list, organize and continue ordinary temporary conversations and create one through the Temporary conversations entry. A temporary conversation has no project and uses normal temporary workspace isolation. It never inherits the last Desktop project. || 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@@ -99,7 +92,7 @@ legacy remote-Agent sessions, and sessions outside a registered project orthe Temporary scope are **not exposed**. In a local project, existing specialsessions (e.g. Plan/Goal) may show safe history and “Continue on Desktop”, butno unsupported mutation. Never convert them to Agent or change their workspace.-Desktop-only deletion, scope removal or a change of project membership must+Desktop-only deletion or a change of project membership mustinvalidate stale rows and deep links; do not redirect to a different session.## 4. Conversation (W04)@@ -186,29 +179,28 @@ Stopping the WebUI removes access, not data.## 6. Access and privacy (W06)-Follow the [LAN WebUI project-access decision](../../adr/lan-webui-project-access.md)+Follow the [code-only pairing decision](../../adr/lan-webui-code-pairing.md)and the applicable [remote permission policy](../05-security/02-remote-control-security.md).-A device that Desktop confirms can-view **all eligible local projects**, including future projects and archived-history. Temporary conversations still require a separate, off-by-default grant.-Label the device and disclose its access before confirmation; Chat and Organize-remain separate from the ability to view projects.+Successful pairing gives every device the same WebUI access: eligible current+and future local projects, archived history, and temporary conversations.+Disclose that scope before displaying a code. Chat and Organize are included+for every paired device, not separate grants.History may contain sensitive text the user or model already put in theconversation; sharing is not an automatic redaction of authored messages.Never enrich it with credential records, absolute workspace paths or raw tooldiagnostics that the safe transcript projection does not already expose.-| Grant | Allowed within eligible scopes | Never implied |+| Operation | Available after pairing | Not exposed by pairing ||---|---|---|-| View | Local project catalog, safe history, current activity and scoped events | Remote project metadata, unauthorized Temporary conversations, 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+| View | Local project and temporary catalogs, safe history, activity and scoped events | Remote project metadata, paths, secrets or arbitrary file reads |+| Chat | Create, send/queue, interrupt, cancel queued work, answer ordinary typed questions when supported | Shell endpoint, remote approvals, raising permission mode, configuring providers |+| Organize | Rename, set pin, set archive/restore on eligible objects | Permanent delete, project registration/root editing, granting roles |++Check the device credential, live resource scope, object state, and policy on+every command, page, attachment placeholder, catalog notification and stream.+Guessing an ID must reveal no more than a missing record. Revoking a device+closes its streams and rejects subsequent requests or in-flight results. The+release also requires canceling its not-started queued work. Already admittedrunning work follows the Host incident policy; never silently replay or undoit. Clear protected views on authorization loss; already seen text cannot beremotely erased. A web turn never gets the SSH-paired-owner exemption: apply@@ -216,8 +208,8 @@ the lower of session policy and the WebUI `ask` ceiling without changing thedesktop 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 against the current local catalog and only writes+`session/archive` and never grants a phone the owner role. The WebUI checks+its organize operations against the current local catalog and only writesthe same Desktop organization record the sidebar uses (§5).Use a Host-issued `HttpOnly`, host-only, `SameSite=Strict` session cookie@@ -227,8 +219,8 @@ only in Desktop memory: stopping the service or quitting Desktop signs everydevice out. No credentials in URLs, local storage or logs. Serve assets locallyunder a restrictive CSP; never cache authenticated data (`no-store`). Logsrecord 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.+cookies. Bound request bodies (300 KiB), prompts (256 KiB), pages (50 items)+and devices (16); never silently truncate input.## 7. Phone usability and service targets (W07)@@ -262,7 +254,7 @@ pending pairings (8) and devices (16); never silently truncate input.transport decision.2. **Deliver the basic workflow:** implement W02–W04 against the same durablerecords, then exercise both clients together, including empty/new/existing- projects and sessions, restricted grants and a lost reply. Do not count an+ projects and sessions, device revocation and a lost reply. Do not count anindependent 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 thecandidate, including physical iPhone/Safari and Android/Chrome on a real@@ -286,11 +278,11 @@ settings) and `apps/desktop/src/features/lan-webui/lan-catalog-sync.ts`| Area | Delivered | Not yet ||---|---|---|-| W01 | Off by default; interface + port; guided pairing with device confirmation; all local projects; edit or remove devices; 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 |+| W01 | Off by default; interface + port; direct one-time-code pairing; remove devices; stop signs everyone out | QR code; HTTPS (deliberately deferred) |+| W02/W03 | Local projects and temporary conversations; search; archived filter; rename, pin, archive/restore with revision conflicts; new session in the explicit project | Reuse of an existing empty session || W04 | Paged history; live assistant text; send; queue; cancel queued; stop the named turn; “waiting on Desktop” for approvals and input | Answering ordinary questions from the browser; model label is the raw model id || W05 | Idempotency keys for every mutation; SSE change notices with refetch; reconnect banner | Cursor-based replay (refetch is used instead) |-| W06 | Non-owner principal under the remote `ask` ceiling; plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry; canceling already queued work on scope loss |+| W06 | Device revocation; non-owner principal under the remote `ask` ceiling; plan/goal and remote sessions read-only or hidden | Idle (30 min) session expiry; canceling already queued work on device revocation || 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 | — |diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.mdindex e526fedb5..0fc491ba0 100644--- a/docs/spec/06-delivery/e2e/live-and-remote.md+++ b/docs/spec/06-delivery/e2e/live-and-remote.md@@ -752,7 +752,7 @@ their separate platform 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+path, pairing guards and organization merge run in`apps/desktop/test/lan-webui-*.test.mjs` (real listener, fake Desktop, ElectronChromium at phone size); real-device steps remain Draft. Use an isolated Desktopprofile, disposable test devices and deterministic fixtures. Do not use a@@ -763,25 +763,23 @@ user's running instance.- **Preconditions:** Fresh Desktop profile with projects A and B; a real phoneon the selected private LAN. Repeat on iOS Safari and Android Chrome.- **Steps:** Choose the interface and start. Open **Add device**, copy the shown- `http://` address, and enter the displayed code on the phone. Confirm the- device without choosing projects. Add project C on Desktop after pairing.- Open and close the dialog with the keyboard, regenerate an expired code,- and deny a separate waiting request. Close/reopen the tab, hide Desktop,- then stop, quit and relaunch Desktop.-- **Expected:** No listener by default and no project data before confirmation.- The request advances to device confirmation, which discloses access to all- local projects. The paired device sees A, B and subsequently C without another- approval; Temporary conversations remain off. An expired, reused or five-times-- wrong code fails. Hiding Desktop/closing the tab does not sign out. Stopping- closes streams, invalidates cookies and releases the port; restarting requires- pairing again. An occupied port or isolated Wi-Fi produces actionable guidance.+ `http://` address, and enter the displayed code on the phone. Do not click+ another Desktop control. Open a local project and a temporary conversation,+ then add project C on Desktop. Test an expired code, a second redemption,+ five wrong attempts and the keyboard flow. Stop, quit and relaunch Desktop.+- **Expected:** No listener by default and no project data before pairing.+ The valid code immediately connects the phone and lists the device on+ Desktop. No approval or per-device grants are required; A, B, C and+ temporary conversations are available. Closing the tab does not sign out.+ Invalid, expired or redeemed codes fail. Stopping invalidates credentials and+ releases the port; restarting requires pairing again.- **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; B is a closed local multi-root group with existing- sessions, one separately archived. Seed a duplicate display name.+- **Preconditions:** Desktop is editing an unsent draft in A. The phone is+ paired. B is a closed 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/restorean idle session. Archive and restore B through the archived filter. Make acompeting rename from Desktop and submit the stale edit from the phone.@@ -795,13 +793,13 @@ user's running instance.### 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.+- **Preconditions:** Desktop is viewing A. The phone is paired. A usable+ fixture model is configured. B has an existing chat with paged history.- **Steps:** Double-tap New session in B, send text, stream a reply, then continuethe 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.+ Create a temporary conversation from its own entry. 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 thephone, first without queuing and then with explicit queue admission.- **Expected:** The initial double-tap/send yields one session and one user@@ -809,8 +807,8 @@ user's running instance.Concurrent sends never start two active turns in a session. A losing send isqueued 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.+ items keeps position, without wrong-project empty reuse or duplicate creates.+ A temporary session has no project and never inherits A or B.Missing model blocks send, preserves text and points to Desktop setup.- **Acceptance:** B, C, D; W03, W04, W05.@@ -846,25 +844,21 @@ user's running instance.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 and- Temporary access, two local projects and an SSH-backed project. 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. In **Permissions**,- turn off Temporary, Chat and Organize while a temporary history request and- stream are in flight. Remove the device and change the desktop network.- Inspect fixture logs/cache.-- **Expected:** No out-of-scope metadata, events or writes, even for known IDs;- View cannot mutate. No generic owner/SSH exemption or raw RPC, no leaked- credentials/content in logs or persistent browser caches. Permission edits- do not require re-pairing or change local project visibility. Temporary scope- loss closes affected streams and cancels its pending queued work; a late or- cached reply under the old grants cannot recover it.- Expiry is not extended by a heartbeat. No connection on other interfaces or- automatic sharing on the new network.+### E2E-274: Enforce the network boundary and device revocation++- **Preconditions:** Two paired devices, local projects, temporary conversations+ and an SSH-backed project. Use a controlled clock and a second interface.+- **Steps:** Exercise catalog, histories, commands and SSE. Check wrong+ Origin/Host, missing CSRF, the device cap and rejected admin/owner operations.+ Remove one device while a temporary history request and stream are in flight;+ then change the desktop network. Inspect fixture logs and caches.+- **Expected:** The SSH-backed project remains hidden. Paired devices have the+ same local WebUI operations, but no generic owner/SSH exemption or raw RPC.+ Removal closes streams and refuses later requests, in-flight results and+ cached mutation results for that device. Other devices remain connected. The+ release also requires canceling revoked devices' not-started queued work.+ Credentials and content do not leak to logs or persistent caches. There is no+ connection on other interfaces or automatic sharing on the new network.- **Acceptance:** D, E; W01, W02, W06.### E2E-275: Preserve an existing desktop profile and disable cleanlydiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex ad83b32b8..0b004ef51 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -5433,3 +5433,10 @@ See ADR 0344.projects. Remove the project checklist, keeping one-time pairing and localconfirmation, the separate Temporary, Chat and Organize grants, and devicerevocation. See [LAN WebUI project access](../../adr/lan-webui-project-access.md).++## 2026-11-26 — LAN WebUI pairs directly with a one-time code (D687)++- A valid code issues the device session immediately. All paired devices can+ use the supported local project and temporary-conversation operations, with+ no separate grant switches. The existing local Agent safety rules and+ device revocation remain. See [Code pairing](../../adr/lan-webui-code-pairing.md).diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.tsindex c146ae92b..b2ace7a36 100644--- a/packages/shared/src/lan-webui.ts+++ b/packages/shared/src/lan-webui.ts@@ -2,19 +2,6 @@* The direct-to-Desktop LAN browser profile (proposed WebUI MVP).* No native paths, host RPC or provider secrets cross this boundary.*/-export interface LanGrants {- /** All eligible local projects, resolved from the current Host catalog. */- projectScope: "all-local";- /** 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;@@ -59,12 +46,6 @@ 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;@@ -76,7 +57,6 @@ export interface LanAdminView {address: string | null;port: number | null;code: { value: string; expiresAt: number } | null;- pending: LanPairing[];devices: LanDevice[];interfaces: LanInterface[];error: string | null;@@ -84,10 +64,7 @@ export interface LanAdminView {export type LanAdminAction =| { kind: "state" | "stop" | "issueCode" }| { kind: "start"; address: string; port: number }- | { kind: "confirm"; id: string; grants: LanGrants }- /** Change what an already paired device may see and do. */- | { kind: "update"; id: string; grants: LanGrants }- | { kind: "deny" | "revoke"; id: string }+ | { kind: "revoke"; id: string }/** The renderer applied organization patches up to `seq`. */| { kind: "ack"; seq: number };