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): make the LAN WebUI phone flow answer what matters first
vastsad8c9a864a35d
diff --git a/apps/desktop/electron/main/lan-webui/assets.ts b/apps/desktop/electron/main/lan-webui/assets.tsindex b11f10783..4f9ff919d 100644--- a/apps/desktop/electron/main/lan-webui/assets.ts+++ b/apps/desktop/electron/main/lan-webui/assets.ts@@ -3,6 +3,8 @@ import indexHtml from "../../../resources/lan-webui/index.html?raw";import appJs from "../../../resources/lan-webui/app.js?raw";import stylesCss from "../../../resources/lan-webui/styles.css?raw";import localeJs from "../../../resources/lan-webui/locale.js?raw";+import kitJs from "../../../resources/lan-webui/kit.js?raw";+import markdownJs from "../../../resources/lan-webui/markdown.js?raw";import type { LanAsset } from "./server";export function lanWebUiAssets(): ReadonlyMap<string, LanAsset> {@@ -10,6 +12,8 @@ export function lanWebUiAssets(): ReadonlyMap<string, LanAsset> {["/index.html", { type: "text/html; charset=utf-8", body: indexHtml }],["/app.js", { type: "text/javascript; charset=utf-8", body: appJs }],["/locale.js", { type: "text/javascript; charset=utf-8", body: localeJs }],+ ["/kit.js", { type: "text/javascript; charset=utf-8", body: kitJs }],+ ["/markdown.js", { type: "text/javascript; charset=utf-8", body: markdownJs }],["/styles.css", { type: "text/css; charset=utf-8", body: stylesCss }],]);}diff --git a/apps/desktop/electron/main/lan-webui/workspace.ts b/apps/desktop/electron/main/lan-webui/workspace.tsindex 89cdfa0c2..10692abb4 100644--- a/apps/desktop/electron/main/lan-webui/workspace.ts+++ b/apps/desktop/electron/main/lan-webui/workspace.ts@@ -158,7 +158,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return index.get(normalizeProjectKey(path))?.id;}- function sessionView(session: HostSession, projectId: string | null, meta: LanMeta): LanSession {+ function sessionView(session: HostSession, projectId: string | null, meta: LanMeta, projectLabel: string | null = null): LanSession {const own = meta.sessionMeta[session.id] ?? {};const title = session.title?.trim() || "";const pinned = own.pinned === true;@@ -174,6 +174,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {readOnly: (session.mode ?? "agent") !== "agent" || (session.source !== undefined && session.source !== "desktop"),status: running ? "running" : "idle",updatedAt: session.updatedAt ?? "",+ projectLabel,};}@@ -196,7 +197,12 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {const projectId = projectOf(session, rootIndex(list));if (projectId === undefined) throw new LanError(404, "NOT_FOUND");const meta = deps.organization.read();- return { session, projectId, meta, view: sessionView(session, projectId, meta) };+ const label = projectId === null ? null : projectLabels(list, meta).get(projectId) ?? null;+ return { session, projectId, meta, view: sessionView(session, projectId, meta, label) };+ }++ function projectLabels(list: ProjectGroupRecord[], meta: LanMeta): Map<string, string> {+ return new Map(distinctViews(list, meta).map(({ group, view }) => [group.id, view.label]));}async function requireLocalProject(projectId: string) {@@ -225,20 +231,36 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {return page(list, query.get("cursor"));}+ /**+ * Sessions of one project, of the Temporary scope, or — without a+ * `projectId` — of every visible scope, most recent first with running work+ * lifted to the top. The all-scope list leaves out sessions of archived+ * projects unless archived items are requested.+ */async function listSessions(query: URLSearchParams): Promise<LanPage<LanSession>> {+ const everywhere = !query.has("projectId");const requested = query.get("projectId") ?? "";const wantTemporary = requested === LAN_TEMPORARY_PROJECT;const [list, sessions] = await Promise.all([groups(), hostSessions()]);- if (!wantTemporary && !list.some((group) => group.id === requested)) throw new LanError(404, "NOT_FOUND");+ if (!everywhere && !wantTemporary && !list.some((group) => group.id === requested)) throw new LanError(404, "NOT_FOUND");const index = rootIndex(list);const meta = deps.organization.read();+ const labels = projectLabels(list, meta);const archivedOnly = query.get("archived") === "1";+ const archivedProjects = new Set(list.filter((group) => projectView(group, meta).archived).map((group) => group.id));const q = (query.get("q") ?? "").trim();- const items = sessions- .filter((session) => projectOf(session, index) === (wantTemporary ? null : requested))- .map((session) => sessionView(session, wantTemporary ? null : requested, meta))- .filter((view) => view.archived === archivedOnly && matches(view.title, q))- .sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt));+ const items: LanSession[] = [];+ for (const session of sessions) {+ const projectId = projectOf(session, index);+ if (projectId === undefined) continue;+ if (!everywhere && projectId !== (wantTemporary ? null : requested)) continue;+ if (everywhere && !archivedOnly && projectId !== null && archivedProjects.has(projectId)) continue;+ const view = sessionView(session, projectId, meta, projectId === null ? null : labels.get(projectId) ?? null);+ if (view.archived === archivedOnly && matches(view.title, q)) items.push(view);+ }+ items.sort(everywhere+ ? (a, b) => Number(b.status === "running") - Number(a.status === "running") || b.updatedAt.localeCompare(a.updatedAt)+ : (a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt));return page(items, query.get("cursor"));}diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.jsindex b7d1b91fb..71b77a3ce 100644--- a/apps/desktop/resources/lan-webui/app.js+++ b/apps/desktop/resources/lan-webui/app.js@@ -2,7 +2,10 @@"use strict";(() => {+ const { el, icon, copyText } = window.LanKit;const TEMP = "__temporary__";+ const RECENT_LIMIT = 5;+ const PENDING_TTL = 30_000;const locales = window.LAN_LOCALES || {};const lang = (navigator.languages || [navigator.language || "en"]).find((code) => code && code.toLowerCase().startsWith("zh"))? "zh-CN"@@ -11,6 +14,7 @@document.documentElement.lang = lang;const t = (key, values) => String(copy[key] ?? key).replace(/\{(\w+)\}/g, (_, name) => String(values?.[name] ?? ""));const errorText = (code) => copy.errors[code] || copy.errors.FAILED;+ const enc = encodeURIComponent;const app = document.getElementById("app");const toast = document.getElementById("toast");@@ -20,9 +24,15 @@const state = {me: null,- route: { view: "projects" },+ route: { view: "home", archived: false },+ online: true,drafts: new Map(),+ /** Optimistic user turns per session, shown until the Host records them. */+ pending: new Map(),projects: new Map(),+ /** The last unfiltered list of active projects, for the New conversation picker. */+ catalog: null,+ query: { home: "", sessions: "", project: null },events: null,refreshTimer: null,renderToken: 0,@@ -35,58 +45,6 @@if ("scrollRestoration" in history) history.scrollRestoration = "manual";// ---------- helpers ----------- function el(tag, props = {}, children = []) {- const node = document.createElement(tag);- for (const [key, value] of Object.entries(props)) {- if (value === undefined || value === null || value === false) continue;- if (key === "text") node.textContent = value;- else if (key === "class") node.className = value;- else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);- else if (value === true) node.setAttribute(key, "");- else node.setAttribute(key, String(value));- }- for (const child of [].concat(children)) if (child) node.append(child);- return node;- }-- // Lucide outlines (ISC) on a 24px grid — the icon set Desktop ships.- const SVG_NS = "http://www.w3.org/2000/svg";- const ICONS = {- back: [["path", { d: "m15 18-6-6 6-6" }]],- more: [["circle", { cx: 12, cy: 12, r: 1 }], ["circle", { cx: 19, cy: 12, r: 1 }], ["circle", { cx: 5, cy: 12, r: 1 }]],- close: [["path", { d: "M18 6 6 18" }], ["path", { d: "m6 6 12 12" }]],- search: [["circle", { cx: 11, cy: 11, r: 8 }], ["path", { d: "m21 21-4.3-4.3" }]],- check: [["path", { d: "M20 6 9 17l-5-5" }]],- send: [["path", { d: "m5 12 7-7 7 7" }], ["path", { d: "M12 19V5" }]],- stop: [["rect", { x: 6, y: 6, width: 12, height: 12, rx: 2 }]],- folder: [["path", { d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" }]],- temporary: [["circle", { cx: 12, cy: 12, r: 10 }], ["path", { d: "M12 6v6l4 2" }]],- chat: [["path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }]],- newChat: [["path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }], ["path", { d: "M12 7v6" }], ["path", { d: "M9 10h6" }]],- pin: [["path", { d: "M12 17v5" }], ["path", { d: "M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" }]],- unpin: [["path", { d: "M12 17v5" }], ["path", { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" }], ["path", { d: "m2 2 20 20" }], ["path", { d: "M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11" }]],- pencil: [["path", { d: "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" }], ["path", { d: "m15 5 4 4" }]],- archive: [["rect", { width: 20, height: 5, x: 2, y: 3, rx: 1 }], ["path", { d: "M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" }], ["path", { d: "M10 12h4" }]],- restore: [["rect", { width: 20, height: 5, x: 2, y: 3, rx: 1 }], ["path", { d: "M4 8v11a2 2 0 0 0 2 2h2" }], ["path", { d: "M20 8v11a2 2 0 0 1-2 2h-2" }], ["path", { d: "m9 15 3-3 3 3" }], ["path", { d: "M12 12v9" }]],- laptop: [["path", { d: "M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16" }]],- tool: [["path", { d: "M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" }]],- logout: [["path", { d: "m16 17 5-5-5-5" }], ["path", { d: "M21 12H9" }], ["path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" }]],- pair: [["path", { d: "M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8" }], ["path", { d: "M10 19v-3.96 3.15" }], ["path", { d: "M7 19h5" }], ["rect", { width: 6, height: 10, x: 16, y: 12, rx: 2 }]],- };- function icon(name, size = "") {- const svg = document.createElementNS(SVG_NS, "svg");- svg.setAttribute("viewBox", "0 0 24 24");- svg.setAttribute("class", size ? `icon ${size}` : "icon");- svg.setAttribute("aria-hidden", "true");- svg.setAttribute("focusable", "false");- for (const [tag, attrs] of ICONS[name]) {- const node = document.createElementNS(SVG_NS, tag);- for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value));- svg.append(node);- }- return svg;- }-// DOM replaceChildren() turns null into the text "null"; drop empty slots first.// Re-rendering the same view keeps the focused field, its caret and its draft.function show(view, ...nodes) {@@ -110,21 +68,38 @@return !same;}let toastTimer = null;- function notify(message) {+ function notify(message, duration = 4000) {toast.textContent = message;toast.hidden = false;clearTimeout(toastTimer);- toastTimer = setTimeout(() => (toast.hidden = true), 4000);+ toastTimer = setTimeout(() => (toast.hidden = true), duration);}const announce = (message) => {if (message) announcer.textContent = message;};function setOffline(lost) {+ state.online = !lost;if (lost) offline.replaceChildren(el("span", { class: "dot offline" }), el("span", { text: t("offline") }));offline.hidden = !lost;+ // Mutations wait for the connection; drafts stay where they are.+ for (const button of app.querySelectorAll("[data-mutation]")) button.disabled = lost;+ state.syncComposer?.();}const newKey = () => (crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`).replace(/[^A-Za-z0-9_-]/g, "");+ async function copyWithFeedback(text, button) {+ if (await copyText(text)) {+ notify(t("copied"), 1500);+ if (button?.isConnected) {+ button.replaceChildren(icon("check", "sm"));+ setTimeout(() => button.isConnected && button.replaceChildren(icon("copy", "sm")), 1500);+ }+ } else {+ notify(t("copyFailed"));+ }+ }+ const markdownOptions = { labels: { copyCode: t("copyCode"), image: t("imagePlaceholder") }, onCopy: copyWithFeedback };+const clock = {time: new Intl.DateTimeFormat(lang, { hour: "numeric", minute: "2-digit" }),weekday: new Intl.DateTimeFormat(lang, { weekday: "short" }),@@ -187,16 +162,30 @@notify(errorText(error instanceof ApiError ? error.code : "FAILED"));}+ async function loadAll(path) {+ const items = [];+ let cursor = null;+ for (let page = 0; page < 20; page += 1) {+ const result = await api("GET", cursor ? `${path}&cursor=${enc(cursor)}` : path);+ items.push(...result.items);+ cursor = result.nextCursor;+ if (!cursor) break;+ }+ return items;+ }+// ---------- routing ----------function parseRoute() {const hash = location.hash.replace(/^#\/?/, "");- const [kind, raw] = hash.split("/");+ const [kind, raw, tail] = hash.split("/");const id = raw ? decodeURIComponent(raw) : "";- if (kind === "p" && id) return { view: "sessions", projectId: id };+ if (kind === "archived") return { view: "home", archived: true };+ if (kind === "p" && id) return { view: "sessions", projectId: id, archived: tail === "archived" };if (kind === "s" && id) return { view: "chat", sessionId: id };- return { view: "projects" };+ return { view: "home", archived: false };}const routeKey = (hash) => (hash && hash !== "#" ? hash : "#/projects");+ const projectHash = (projectId) => `#/p/${enc(projectId ?? TEMP)}`;const go = (hash) => {if (location.hash === hash) render();else {@@ -204,6 +193,7 @@location.hash = hash;}};+ const back = (fallback) => (history.length > 1 ? history.back() : go(fallback));window.addEventListener("hashchange", (event) => {const prefill = takePairingCode();if (prefill && !state.me) {@@ -277,7 +267,7 @@type: "button",class: action.danger ? "danger" : "",onclick: () => { closeSheet(false); action.run(); },- }, [icon(action.icon), el("span", { text: action.label })])),+ }, [icon(action.icon), el("span", { class: "sheet-label", text: action.label })])),el("button", { type: "button", class: "cancel", text: t("cancel"), onclick: () => closeSheet() }),], opener || document.activeElement);document.querySelector("#sheet-actions button")?.focus();@@ -292,7 +282,8 @@document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !sheet.hidden) closeSheet(); });function organize(kind, item, patch) {- const path = `/v1/${kind}/${encodeURIComponent(item.id)}/organize`;+ if (!state.online) return notify(errorText("NETWORK"));+ const path = `/v1/${kind}/${enc(item.id)}/organize`;return api("POST", path, { revision: item.revision, ...patch }, newKey()).then(() => render({ refresh: true }), (error) => { fail(error); render({ refresh: true }); });}@@ -326,10 +317,35 @@];}- // ---------- views ----------+ async function createSession(projectId, button) {+ if (!state.online) return notify(errorText("NETWORK"));+ if (button) button.disabled = true;+ try {+ const created = await api("POST", "/v1/sessions", { projectId: projectId === TEMP ? null : projectId }, newKey());+ go(`#/s/${enc(created.id)}`);+ } catch (error) {+ fail(error);+ if (button?.isConnected) button.disabled = false;+ }+ }++ /** From Home, one tap asks only where the conversation should live. */+ async function pickNewConversation(opener) {+ try {+ const projects = state.catalog ?? await loadAll("/v1/projects?q=");+ openSheet(t("newIn"), [+ { icon: "temporary", label: t("temporary"), run: () => void createSession(TEMP) },+ ...projects.map((project) => ({ icon: "folder", label: project.label, run: () => void createSession(project.id) })),+ ], opener);+ } catch (error) {+ fail(error);+ }+ }++ // ---------- shared view parts ----------/** One status/flag entry: a dot or a small icon, always with its text. */function metaItem(entry) {- return el("span", { class: "meta-item" }, [+ return el("span", { class: entry.class ? `meta-item ${entry.class}` : "meta-item" }, [entry.dot ? el("span", { class: `dot ${entry.dot}` }) : entry.icon ? icon(entry.icon, "xs") : null,el("span", { class: "meta-text", text: entry.text }),]);@@ -345,12 +361,15 @@if (status === "waiting") return { dot: "waiting", text: t("waiting") };return null;}+ function scopeMeta(session) {+ if (session.projectId === null) return { icon: "temporary", text: t("temporary"), class: "scope" };+ const label = session.projectLabel || state.projects.get(session.projectId);+ return label ? { icon: "folder", text: label, class: "scope" } : null;+ }- function header({ title, back, subtitle = [], actions = [], root = false }) {+ function header({ title, backTo, subtitle = [], actions = [], root = false }) {return el("header", { class: root ? "header root" : "header" }, [- back- ? el("button", { type: "button", class: "icon-btn", "aria-label": t("back"), onclick: () => (history.length > 1 ? history.back() : go(back)) }, icon("back"))- : null,+ backTo ? el("button", { type: "button", class: "icon-btn", "aria-label": t("back"), onclick: () => back(backTo) }, icon("back")) : null,el("div", { class: "header-title" }, [el("h1", { id: "view-title", tabindex: "-1", text: title }),subtitle.length ? el("p", { class: "header-sub" }, subtitle.map(metaItem)) : null,@@ -366,26 +385,19 @@onclick: (event) => openSheet(name, actions, event.currentTarget),}, icon("more"));- function toolbar(filters, onChange) {+ function searchField(key) {const search = el("input", {id: "list-search", type: "search", placeholder: t("search"), "aria-label": t("search"),- value: filters.q, enterkeyhint: "search", autocomplete: "off",+ value: state.query[key], enterkeyhint: "search", autocomplete: "off",});let timer = null;search.addEventListener("input", () => {- // Keep the latest text in the filter so a re-render never drops keystrokes.- filters.q = search.value;+ // Keep the latest text in the query so a re-render never drops keystrokes.+ state.query[key] = search.value;clearTimeout(timer);- timer = setTimeout(onChange, 250);+ timer = setTimeout(() => render(), 250);});- const archived = el("button", {- id: "filter-archived",- type: "button",- class: "chip",- "aria-pressed": filters.archived ? "true" : "false",- onclick: () => { filters.archived = !filters.archived; onChange(); },- }, [icon(filters.archived ? "check" : "archive", "sm"), el("span", { text: t("showArchived") })]);- return el("div", { class: "toolbar" }, [el("div", { class: "search" }, [icon("search", "sm"), search]), archived]);+ return el("div", { class: "toolbar" }, el("div", { class: "search" }, [icon("search", "sm"), search]));}function row({ icon: iconName, title, meta = [], time = "", onOpen, actions = [], moreLabel }) {@@ -403,99 +415,171 @@: null,]);}+ function sessionRow(item, showScope) {+ const title = item.title || t("untitled");+ return row({+ title,+ meta: [sessionStatus(item.status), showScope ? scopeMeta(item) : null, ...flags(item), item.readOnly ? { icon: "laptop", text: t("readOnly") } : null].filter(Boolean),+ time: when(item.updatedAt),+ onOpen: () => go(`#/s/${enc(item.id)}`),+ actions: organizeActions("sessions", item),+ moreLabel: t("more", { name: title }),+ });+ }+ function projectRow(item) {+ return row({+ icon: "folder",+ title: item.label,+ meta: flags(item),+ onOpen: () => go(projectHash(item.id)),+ actions: organizeActions("projects", item),+ moreLabel: t("more", { name: item.label }),+ });+ }+ const section = (id, label, children) => el("section", { id, class: "section", "aria-label": label }, [el("h2", { class: "section-label", text: label }), ...children]);const emptyState = (text, iconName) => el("div", { class: "empty" }, [icon(iconName, "lg"), el("p", { text })]);+ const archivedLink = (hash) => el("button", { type: "button", class: "footer-link", onclick: () => go(hash) }, [+ icon("archive", "sm"), el("span", { text: t("archivedView") }), icon("chevron", "sm"),+ ]);+ function newConversationButton(onClick) {+ return el("button", {+ type: "button",+ class: "primary fab",+ "data-mutation": "",+ disabled: !state.online,+ onclick: (event) => onClick(event.currentTarget),+ }, [icon("newChat"), el("span", { text: t("newSession") })]);+ }- const listFilters = { projects: { q: "", archived: false }, sessions: { q: "", archived: false } };-- async function loadAll(path) {- const items = [];- let cursor = null;- for (let page = 0; page < 20; page += 1) {- const result = await api("GET", cursor ? `${path}&cursor=${encodeURIComponent(cursor)}` : path);- items.push(...result.items);- cursor = result.nextCursor;- if (!cursor) break;- }- return items;+ async function ensureProjectLabel(projectId) {+ if (projectId === TEMP || state.projects.has(projectId)) return;+ const [active, archived] = await Promise.all([loadAll("/v1/projects?q="), loadAll("/v1/projects?q=&archived=1")]);+ for (const item of [...active, ...archived]) state.projects.set(item.id, item.label);}- async function renderProjects(token) {- const filters = listFilters.projects;- const query = `?q=${encodeURIComponent(filters.q)}${filters.archived ? "&archived=1" : ""}`;- const items = await loadAll(`/v1/projects${query}`);+ // ---------- home ----------+ async function renderHome(token, archived) {+ const q = state.query.home.trim();+ const flag = archived ? "&archived=1" : "";+ const browsing = !archived && !q;+ const [projects, sessions] = await Promise.all([+ loadAll(`/v1/projects?q=${enc(q)}${flag}`),+ browsing ? api("GET", "/v1/sessions?q=").then((page) => page.items) : loadAll(`/v1/sessions?q=${enc(q)}${flag}`),+ ]);if (token !== state.renderToken) return undefined;- for (const item of items) state.projects.set(item.id, item.label);- const temporary = !filters.archived && !filters.q- ? el("ul", { class: "list group" }, row({ icon: "temporary", title: t("temporary"), onOpen: () => go(`#/p/${TEMP}`) }))- : null;- const list = items.length- ? el("ul", { class: "list" }, items.map((item) => row({- icon: "folder",- title: item.label,- meta: flags(item),- onOpen: () => go(`#/p/${encodeURIComponent(item.id)}`),- actions: organizeActions("projects", item),- moreLabel: t("more", { name: item.label }),- })))- : emptyState(filters.q ? t("noMatches") : t("noProjects"), filters.q ? "search" : "folder");+ for (const item of projects) state.projects.set(item.id, item.label);+ if (browsing) state.catalog = projects;++ // Running work always stays visible; otherwise show a short recent list.+ const running = sessions.filter((item) => item.status === "running").length;+ const recent = browsing ? sessions.slice(0, Math.max(RECENT_LIMIT, running)) : sessions;+ const projectRows = projects.map(projectRow);+ if (browsing) projectRows.unshift(row({ icon: "temporary", title: t("temporary"), onOpen: () => go(projectHash(TEMP)) }));++ const parts = [];+ if (recent.length) parts.push(section("section-recent", browsing ? t("recent") : t("conversations"), [el("ul", { class: "list" }, recent.map((item) => sessionRow(item, true)))]));+ if (projectRows.length) {+ parts.push(section("section-projects", t("projects"), [+ el("ul", { class: "list" }, projectRows),+ browsing && !projects.length ? el("p", { class: "hint", text: t("noProjects") }) : null,+ ]));+ }+ if (!parts.length) parts.push(emptyState(archived ? t("noArchived") : t("noMatches"), archived ? "archive" : "search"));+return show(- "projects",- header({ title: t("projects"), root: true }),- toolbar(filters, () => render()),- temporary,- list,- el("button", { type: "button", class: "link signout", onclick: signOut }, [icon("logout", "sm"), el("span", { text: t("signOut") })]),+ archived ? "home:archived" : "home",+ archived ? header({ title: t("archivedView"), backTo: "#/projects" }) : header({ title: t("appTitle"), root: true }),+ searchField("home"),+ ...parts,+ browsing ? el("div", { class: "footer" }, [+ archivedLink("#/archived"),+ el("button", {+ type: "button",+ class: "link signout",+ onclick: (event) => openSheet(t("signOutConfirm"), [{ icon: "logout", label: t("signOut"), danger: true, run: signOut }], event.currentTarget),+ }, [icon("logout", "sm"), el("span", { text: t("signOut") })]),+ ]) : null,+ browsing ? newConversationButton((button) => void pickNewConversation(button)) : null,+ browsing ? el("div", { class: "fab-spacer", "aria-hidden": "true" }) : null,);}- async function renderSessions(token, projectId) {- const filters = listFilters.sessions;- const query = `?projectId=${encodeURIComponent(projectId)}&q=${encodeURIComponent(filters.q)}${filters.archived ? "&archived=1" : ""}`;- const items = await loadAll(`/v1/sessions${query}`);+ // ---------- project sessions ----------+ async function renderSessions(token, projectId, archived) {+ // A search belongs to the project it was typed in.+ if (state.query.project !== projectId) Object.assign(state.query, { sessions: "", project: projectId });+ const q = state.query.sessions.trim();+ const [items] = await Promise.all([+ loadAll(`/v1/sessions?projectId=${enc(projectId)}&q=${enc(q)}${archived ? "&archived=1" : ""}`),+ ensureProjectLabel(projectId),+ ]);if (token !== state.renderToken) return undefined;- const title = projectId === TEMP ? t("temporary") : state.projects.get(projectId) || t("projects");+ const name = projectId === TEMP ? t("temporary") : state.projects.get(projectId) || t("projects");const list = items.length- ? el("ul", { class: "list" }, items.map((item) => row({- title: item.title || t("untitled"),- meta: [sessionStatus(item.status), ...flags(item), item.readOnly ? { icon: "laptop", text: t("readOnly") } : null].filter(Boolean),- time: when(item.updatedAt),- onOpen: () => go(`#/s/${encodeURIComponent(item.id)}`),- actions: organizeActions("sessions", item),- moreLabel: t("more", { name: item.title || t("untitled") }),- })))- : emptyState(filters.q ? t("noMatches") : t("noSessions"), filters.q ? "search" : "chat");- const create = el("button", {- type: "button",- class: "primary fab",- 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;- }- },- }, [icon("newChat"), el("span", { text: t("newSession") })]);+ ? el("ul", { class: "list" }, items.map((item) => sessionRow(item, false)))+ : emptyState(q ? t("noMatches") : archived ? t("noArchived") : t("noSessions"), q ? "search" : archived ? "archive" : "chat");return show(- `sessions:${projectId}`,- header({ title, back: "#/projects" }),- toolbar(filters, () => render()),- create,+ `sessions:${projectId}${archived ? ":archived" : ""}`,+ archived+ ? header({ title: t("archivedView"), backTo: projectHash(projectId), subtitle: [{ icon: projectId === TEMP ? "temporary" : "folder", text: name }] })+ : header({ title: name, backTo: "#/projects" }),+ searchField("sessions"),+ archived ? null : newConversationButton((button) => void createSession(projectId, button)),list,- el("div", { class: "fab-spacer", "aria-hidden": "true" }),+ archived || q ? null : el("div", { class: "footer" }, archivedLink(`${projectHash(projectId)}/archived`)),+ archived ? null : el("div", { class: "fab-spacer", "aria-hidden": "true" }),);}+ // ---------- conversation ----------const roleLabel = { user: "you", assistant: "assistant", tool: "tool" };function message(item, extraClass = "") {const role = roleLabel[item.role] ? item.role : "assistant";- const body = [el("span", { class: "sr-only", text: `${t(roleLabel[role])}: ` })];- if (role === "tool") body.push(icon("tool", "sm"), el("span", { text: item.text }));- else body.push(document.createTextNode(item.text));- return el("div", { class: extraClass ? `msg ${role} ${extraClass}` : `msg ${role}` }, body);+ const classes = ["msg", role, extraClass].filter(Boolean).join(" ");+ const label = el("span", { class: "sr-only", text: `${t(roleLabel[role])}: ` });+ if (role === "assistant") return el("div", { class: `${classes} md` }, [label, window.LanMarkdown.render(item.text, markdownOptions)]);+ if (role === "tool") return el("div", { class: classes }, [label, icon("tool", "sm"), el("span", { text: item.text })]);+ return el("div", { class: classes }, [label, document.createTextNode(item.text)]);+ }+ /** Consecutive tool calls fold into one quiet step summary. */+ function steps(run, open) {+ if (run.length === 1) return message(run[0]);+ const names = [...new Set(run.map((item) => item.text).filter(Boolean))];+ const details = el("details", { class: "steps", open: open.has(run[0].id) }, [+ el("summary", {}, [+ icon("tool", "sm"),+ el("span", { class: "steps-count", text: t("steps", { count: run.length }) }),+ el("span", { class: "steps-names", text: names.join(", ") }),+ icon("chevron", "sm"),+ ]),+ el("div", { class: "steps-list" }, run.map((item) => message(item))),+ ]);+ details.addEventListener("toggle", () => (details.open ? open.add(run[0].id) : open.delete(run[0].id)));+ return details;+ }+ const copyButton = (text) => el("div", { class: "msg-actions" }, el("button", {+ type: "button",+ class: "icon-btn",+ "aria-label": t("copy"),+ onclick: (event) => void copyWithFeedback(text, event.currentTarget),+ }, icon("copy", "sm")));++ function transcript(items, open, running) {+ const nodes = [];+ for (let i = 0; i < items.length; i += 1) {+ const item = items[i];+ if (item.role === "tool") {+ const run = [item];+ while (items[i + 1]?.role === "tool") run.push(items[++i]);+ nodes.push(steps(run, open));+ continue;+ }+ nodes.push(message(item));+ // Copy sits under the last answer of each exchange.+ const next = items.slice(i + 1).find((candidate) => candidate.role !== "tool");+ if (item.role === "assistant" && item.text && (next ? next.role === "user" : !running)) nodes.push(copyButton(item.text));+ }+ return nodes;}function notice({ dot, icon: iconName, text, action }) {@@ -506,17 +590,55 @@]);}- const chatState = { sessionId: null, older: [], olderCursor: undefined, phase: null };+ const userCount = (items, text) => items.filter((item) => item.role === "user" && item.text.trim() === text).length;+ /**+ * Drop optimistic turns the Host has recorded (or queued), or that went stale.+ * `items` is the same merged transcript the send-time baseline was counted in.+ */+ function reconcilePending(sessionId, items, queue) {+ const list = state.pending.get(sessionId);+ if (!list) return [];+ const count = (text) => userCount(items, text);+ const queued = new Set(queue.map((entry) => entry.text.trim()));+ const now = Date.now();+ const left = list.filter((entry) => !(count(entry.text) > entry.seen || queued.has(entry.text) || (entry.acked && now - entry.acked > PENDING_TTL)));+ if (left.length) state.pending.set(sessionId, left);+ else state.pending.delete(sessionId);+ return left;+ }++ const chatState = { sessionId: null, older: [], olderCursor: undefined, phase: null, open: new Set(), items: [] };const phaseText = { running: "running", "waiting-approval": "waitingApproval", "waiting-input": "waitingInput", idle: "replyDone" };+ const nearBottom = () => {+ const scroller = document.scrollingElement;+ return scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 120;+ };+ function syncJump() {+ const jump = document.getElementById("jump-latest");+ if (jump) jump.hidden = nearBottom();+ }+ window.addEventListener("scroll", syncJump, { passive: true });async function renderChat(token, sessionId, refresh) {- if (chatState.sessionId !== sessionId) Object.assign(chatState, { sessionId, older: [], olderCursor: undefined, phase: null });- const conversation = await api("GET", `/v1/sessions/${encodeURIComponent(sessionId)}`);+ if (chatState.sessionId !== sessionId) Object.assign(chatState, { sessionId, older: [], olderCursor: undefined, phase: null, open: new Set(), items: [] });+ const conversation = await api("GET", `/v1/sessions/${enc(sessionId)}`);if (token !== state.renderToken) return undefined;const { session } = conversation;+ if (session.projectId && session.projectLabel) state.projects.set(session.projectId, session.projectLabel);const nextCursor = chatState.olderCursor === undefined ? conversation.messages.nextCursor : chatState.olderCursor;const scroller = document.scrollingElement;- const atBottom = !refresh || scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight < 80;+ const atBottom = !refresh || nearBottom();++ const seen = new Set();+ const items = [];+ for (const item of [...chatState.older, ...conversation.messages.items]) {+ if (seen.has(item.id)) continue;+ seen.add(item.id);+ items.push(item);+ }+ chatState.items = items;+ const pending = reconcilePending(sessionId, items, conversation.queue);+ const running = Boolean(conversation.activeTurnId);const messages = el("div", { class: "messages" });if (nextCursor) {@@ -527,7 +649,7 @@onclick: async () => {try {const before = scroller.scrollHeight;- const page = await api("GET", `/v1/sessions/${encodeURIComponent(sessionId)}/history?cursor=${encodeURIComponent(nextCursor)}`);+ const page = await api("GET", `/v1/sessions/${enc(sessionId)}/history?cursor=${enc(nextCursor)}`);chatState.older = [...page.items, ...chatState.older];chatState.olderCursor = page.nextCursor;await render({ refresh: true });@@ -538,16 +660,22 @@},}));}- const seen = new Set();- for (const item of [...chatState.older, ...conversation.messages.items]) {- if (seen.has(item.id)) continue;- seen.add(item.id);- messages.append(message(item));- }+ messages.append(...transcript(items, chatState.open, running));+ for (const entry of pending) messages.append(message({ role: "user", text: entry.text }, "pending"));if (conversation.liveText) messages.append(message({ role: "assistant", text: conversation.liveText }, "live"));+ else if (running && !conversation.waiting) {+ messages.append(el("div", { class: "working" }, [el("span", { class: "working-dots", "aria-hidden": "true" }, [el("i"), el("i"), el("i")]), el("span", { text: t("working") })]));+ }+ if (!items.length && !pending.length && !conversation.liveText && !running) {+ messages.append(el("div", { class: "chat-empty" }, [+ icon(session.projectId ? "folder" : "temporary", "lg"),+ el("p", { class: "chat-empty-title", text: session.projectId ? session.projectLabel || state.projects.get(session.projectId) || "" : t("temporary") }),+ conversation.modelLabel ? el("p", { class: "chat-empty-sub", text: conversation.modelLabel }) : null,+ ]));+ }// Announce actionable state changes, not every streamed token.- const phase = conversation.waiting ? `waiting-${conversation.waiting}` : conversation.activeTurnId ? "running" : "idle";+ const phase = conversation.waiting ? `waiting-${conversation.waiting}` : running ? "running" : "idle";if (chatState.phase && chatState.phase !== phase) announce(t(phaseText[phase]));chatState.phase = phase;@@ -566,7 +694,7 @@type: "button",class: "icon-btn","aria-label": t("cancelQueued"),- onclick: () => api("POST", `/v1/turns/${encodeURIComponent(entry.id)}:cancel`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail),+ onclick: () => api("POST", `/v1/turns/${enc(entry.id)}:cancel`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail),}, icon("close", "sm")),]))): null;@@ -574,73 +702,98 @@const canChat = !session.readOnly && !session.archived;const composer = canChat ? buildComposer(sessionId, conversation) : null;const title = session.title || t("untitled");- const subtitle = [- conversation.modelLabel ? { text: conversation.modelLabel } : null,- sessionStatus(conversation.waiting ? "waiting" : conversation.activeTurnId ? "running" : session.status),- ].filter(Boolean);const head = header({title,- back: session.projectId ? `#/p/${encodeURIComponent(session.projectId)}` : `#/p/${TEMP}`,- subtitle,+ backTo: projectHash(session.projectId),+ subtitle: [+ scopeMeta(session),+ conversation.modelLabel ? { text: conversation.modelLabel, class: "model" } : null,+ sessionStatus(conversation.waiting ? "waiting" : running ? "running" : session.status),+ ].filter(Boolean),actions: [moreButton(title, organizeActions("sessions", session))],});- const dockItems = [...notices, queue, composer].filter(Boolean);- const changed = show(`chat:${sessionId}`, head, messages, dockItems.length ? el("div", { class: "chat-dock" }, dockItems) : null);+ const jump = el("button", {+ id: "jump-latest",+ type: "button",+ class: "icon-btn jump",+ hidden: true,+ "aria-label": t("jumpLatest"),+ onclick: () => window.scrollTo({ top: scroller.scrollHeight, behavior: "smooth" }),+ }, icon("down", "sm"));+ const dock = el("div", { class: "chat-dock" }, [jump, ...notices, queue, composer]);+ const changed = show(`chat:${sessionId}`, head, messages, dock);if (atBottom) scroller.scrollTop = scroller.scrollHeight;+ syncJump();return changed;}function buildComposer(sessionId, conversation) {const running = Boolean(conversation.activeTurnId);- const input = el("textarea", { id: "composer-input", rows: "1", "aria-label": t("composer"), placeholder: t("composer"), enterkeyhint: "send" });+ const input = el("textarea", {+ id: "composer-input", rows: "1", "aria-label": t("composer"),+ placeholder: running ? t("composerFollowUp") : t("composer"), enterkeyhint: "send",+ });input.value = state.drafts.get(sessionId) || "";const send = el("button", {type: "button",- class: running ? "primary send is-queue" : "primary send",- "aria-label": running ? null : t("send"),- onclick: () => void submit(running),- }, running ? el("span", { text: t("queue") }) : icon("send"));- const sync = () => { send.disabled = state.sending || !input.value.trim(); };+ class: "primary send",+ "aria-label": running ? t("queueMessage") : t("send"),+ onclick: () => void submit(),+ }, icon("send"));+ const stop = running+ ? el("button", {+ type: "button",+ class: "stop",+ "aria-label": t("stop"),+ onclick: () => api("POST", `/v1/turns/${enc(conversation.activeTurnId)}:interrupt`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail),+ }, icon("stop"))+ : null;+ // One obvious action: Stop while a reply runs, Send (or queue) once there is text.+ const sync = () => {+ const hasText = Boolean(input.value.trim());+ send.hidden = running && !hasText;+ send.disabled = state.sending || !hasText || !state.online;+ };state.syncComposer = sync;const fit = () => { input.style.height = "auto"; input.style.height = `${input.scrollHeight}px`; };input.addEventListener("input", () => { state.drafts.set(sessionId, input.value); fit(); sync(); });- const submit = async (queue) => {+ const submit = async () => {const text = input.value.trim();- if (!text || state.sending) return;+ if (!text || state.sending || !state.online) return;state.sending = true;+ // Show the message at once; the Host record replaces it when it lands.+ const entry = { text, seen: userCount(chatState.items, text), acked: 0 };+ state.pending.set(sessionId, [...(state.pending.get(sessionId) ?? []), entry]);+ state.drafts.delete(sessionId);+ input.value = "";+ fit();sync();+ document.querySelector(".chat-empty")?.remove();+ document.querySelector(".messages")?.append(message({ role: "user", text }, "pending"));+ document.scrollingElement.scrollTop = document.scrollingElement.scrollHeight;try {- await api("POST", `/v1/sessions/${encodeURIComponent(sessionId)}/turns`, { text, queue }, newKey());- state.drafts.delete(sessionId);- input.value = "";- await render({ refresh: true });+ await api("POST", `/v1/sessions/${enc(sessionId)}/turns`, { text, queue: running }, newKey());+ entry.acked = Date.now();} catch (error) {+ state.pending.set(sessionId, (state.pending.get(sessionId) ?? []).filter((candidate) => candidate !== entry));+ // Never lose what was typed: put it back for another try.+ const current = state.drafts.get(sessionId) ?? "";+ state.drafts.set(sessionId, current ? `${text}\n${current}` : text);fail(error);} finally {state.sending = false;- state.syncComposer?.();}+ await render({ refresh: true });};input.addEventListener("keydown", (event) => {if (event.key !== "Enter" || event.shiftKey || event.isComposing || event.keyCode === 229) return;if (!window.matchMedia("(pointer: fine)").matches && !(event.metaKey || event.ctrlKey)) return;event.preventDefault();- void submit(running);+ void submit();});setTimeout(fit, 0);sync();- const actions = el("div", { class: "actions" }, [- running- ? el("button", {- type: "button",- class: "stop",- "aria-label": t("stop"),- onclick: () => api("POST", `/v1/turns/${encodeURIComponent(conversation.activeTurnId)}:interrupt`, { sessionId }, newKey()).then(() => render({ refresh: true }), fail),- }, icon("stop"))- : null,- send,- ]);- return el("div", { class: "composer" }, [input, actions]);+ return el("div", { class: "composer" }, [input, el("div", { class: "actions" }, [stop, send])]);}async function render(options = {}) {@@ -649,8 +802,8 @@const route = state.route;try {let changed;- if (route.view === "projects") changed = await renderProjects(token);- else if (route.view === "sessions") changed = await renderSessions(token, route.projectId);+ if (route.view === "home") changed = await renderHome(token, route.archived);+ else if (route.view === "sessions") changed = await renderSessions(token, route.projectId, route.archived);else changed = await renderChat(token, route.sessionId, options.refresh === true);if (changed === undefined) return;if (route.view !== "chat" && !options.refresh) {@@ -661,7 +814,7 @@if (changed) document.getElementById("view-title")?.focus({ preventScroll: true });} catch (error) {if (token !== state.renderToken) return;- if (error instanceof ApiError && error.code === "NOT_FOUND" && route.view !== "projects") {+ if (error instanceof ApiError && error.code === "NOT_FOUND" && route.view !== "home") {notify(errorText("NOT_FOUND"));go("#/projects");return;@@ -734,6 +887,8 @@// Signed out either way.}state.me = null;+ state.pending.clear();+ state.catalog = null;showPair();}diff --git a/apps/desktop/resources/lan-webui/index.html b/apps/desktop/resources/lan-webui/index.htmlindex aa2126aa6..84db43aa4 100644--- a/apps/desktop/resources/lan-webui/index.html+++ b/apps/desktop/resources/lan-webui/index.html@@ -10,6 +10,8 @@<title>PI-Desktop</title><link rel="stylesheet" href="/styles.css" /><script src="/locale.js" defer></script>+ <script src="/kit.js" defer></script>+ <script src="/markdown.js" defer></script><script src="/app.js" defer></script></head><body>diff --git a/apps/desktop/resources/lan-webui/kit.js b/apps/desktop/resources/lan-webui/kit.jsnew file mode 100644index 000000000..8077c325b--- /dev/null+++ b/apps/desktop/resources/lan-webui/kit.js@@ -0,0 +1,94 @@+// LAN WebUI shared helpers: DOM building, Lucide icons and clipboard.+// Plain DOM only: text always goes through textContent, never innerHTML.+"use strict";++(() => {+ function el(tag, props = {}, children = []) {+ const node = document.createElement(tag);+ for (const [key, value] of Object.entries(props)) {+ if (value === undefined || value === null || value === false) continue;+ if (key === "text") node.textContent = value;+ else if (key === "class") node.className = value;+ else if (key.startsWith("on")) node.addEventListener(key.slice(2), value);+ else if (value === true) node.setAttribute(key, "");+ else node.setAttribute(key, String(value));+ }+ for (const child of [].concat(children)) if (child) node.append(child);+ return node;+ }++ // Lucide outlines (ISC) on a 24px grid — the icon set Desktop ships.+ const SVG_NS = "http://www.w3.org/2000/svg";+ const ICONS = {+ back: [["path", { d: "m15 18-6-6 6-6" }]],+ chevron: [["path", { d: "m9 18 6-6-6-6" }]],+ down: [["path", { d: "M12 5v14" }], ["path", { d: "m19 12-7 7-7-7" }]],+ more: [["circle", { cx: 12, cy: 12, r: 1 }], ["circle", { cx: 19, cy: 12, r: 1 }], ["circle", { cx: 5, cy: 12, r: 1 }]],+ close: [["path", { d: "M18 6 6 18" }], ["path", { d: "m6 6 12 12" }]],+ search: [["circle", { cx: 11, cy: 11, r: 8 }], ["path", { d: "m21 21-4.3-4.3" }]],+ check: [["path", { d: "M20 6 9 17l-5-5" }]],+ copy: [["rect", { width: 14, height: 14, x: 8, y: 8, rx: 2 }], ["path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" }]],+ send: [["path", { d: "m5 12 7-7 7 7" }], ["path", { d: "M12 19V5" }]],+ stop: [["rect", { x: 6, y: 6, width: 12, height: 12, rx: 2 }]],+ folder: [["path", { d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z" }]],+ temporary: [["circle", { cx: 12, cy: 12, r: 10 }], ["path", { d: "M12 6v6l4 2" }]],+ chat: [["path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }]],+ newChat: [["path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" }], ["path", { d: "M12 7v6" }], ["path", { d: "M9 10h6" }]],+ pin: [["path", { d: "M12 17v5" }], ["path", { d: "M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" }]],+ unpin: [["path", { d: "M12 17v5" }], ["path", { d: "M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89" }], ["path", { d: "m2 2 20 20" }], ["path", { d: "M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11" }]],+ pencil: [["path", { d: "M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z" }], ["path", { d: "m15 5 4 4" }]],+ archive: [["rect", { width: 20, height: 5, x: 2, y: 3, rx: 1 }], ["path", { d: "M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" }], ["path", { d: "M10 12h4" }]],+ restore: [["rect", { width: 20, height: 5, x: 2, y: 3, rx: 1 }], ["path", { d: "M4 8v11a2 2 0 0 0 2 2h2" }], ["path", { d: "M20 8v11a2 2 0 0 1-2 2h-2" }], ["path", { d: "m9 15 3-3 3 3" }], ["path", { d: "M12 12v9" }]],+ laptop: [["path", { d: "M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16" }]],+ tool: [["path", { d: "M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" }]],+ logout: [["path", { d: "m16 17 5-5-5-5" }], ["path", { d: "M21 12H9" }], ["path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" }]],+ pair: [["path", { d: "M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8" }], ["path", { d: "M10 19v-3.96 3.15" }], ["path", { d: "M7 19h5" }], ["rect", { width: 6, height: 10, x: 16, y: 12, rx: 2 }]],+ image: [["rect", { width: 18, height: 18, x: 3, y: 3, rx: 2 }], ["circle", { cx: 9, cy: 9, r: 2 }], ["path", { d: "m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21" }]],+ };+ function icon(name, size = "") {+ const svg = document.createElementNS(SVG_NS, "svg");+ svg.setAttribute("viewBox", "0 0 24 24");+ svg.setAttribute("class", size ? `icon ${size}` : "icon");+ svg.setAttribute("aria-hidden", "true");+ svg.setAttribute("focusable", "false");+ for (const [tag, attrs] of ICONS[name]) {+ const node = document.createElementNS(SVG_NS, tag);+ for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value));+ svg.append(node);+ }+ return svg;+ }++ /**+ * The page is plain HTTP on the LAN, which is not a secure context, so the+ * async Clipboard API is usually missing. Fall back to a selected textarea+ * and the legacy copy command, which phones still honour inside a tap.+ */+ async function copyText(text) {+ if (window.isSecureContext && navigator.clipboard?.writeText) {+ try {+ await navigator.clipboard.writeText(text);+ return true;+ } catch {+ // Fall through to the legacy path.+ }+ }+ const area = el("textarea", { readonly: true, "aria-hidden": "true", class: "copy-buffer" });+ area.value = text;+ document.body.append(area);+ const active = document.activeElement;+ area.select();+ area.setSelectionRange(0, text.length);+ let copied = false;+ try {+ copied = document.execCommand("copy");+ } catch {+ copied = false;+ }+ area.remove();+ if (active instanceof HTMLElement) active.focus({ preventScroll: true });+ return copied;+ }++ window.LanKit = { el, icon, copyText };+})();diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.jsindex 8648d81f3..28e5584fb 100644--- a/apps/desktop/resources/lan-webui/locale.js+++ b/apps/desktop/resources/lan-webui/locale.js@@ -47,6 +47,22 @@ window.LAN_LOCALES = {stop: "Stop",queued: "Queued",replyDone: "Reply finished",+ recent: "Recent",+ conversations: "Conversations",+ archivedView: "Archived",+ noArchived: "Nothing archived.",+ newIn: "New conversation in",+ signOutConfirm: "Disconnect this device? Pairing again needs a new code.",+ composerFollowUp: "Queue a follow-up",+ queueMessage: "Queue message",+ working: "Working…",+ steps: "{count} steps",+ copy: "Copy",+ copyCode: "Copy code",+ copied: "Copied",+ copyFailed: "Couldn't copy. Long-press the text to select it.",+ imagePlaceholder: "Image",+ jumpLatest: "Jump to latest",cancelQueued: "Cancel queued message",waitingApproval: "Waiting for approval on the computer.",waitingInput: "Input needed on the computer.",@@ -116,6 +132,22 @@ window.LAN_LOCALES = {stop: "停止",queued: "排队中",replyDone: "回复已完成",+ recent: "最近",+ conversations: "会话",+ archivedView: "已归档",+ noArchived: "没有已归档的内容。",+ newIn: "新建会话到",+ signOutConfirm: "断开此设备?重新连接需要新的配对码。",+ composerFollowUp: "排队追加消息",+ queueMessage: "排队发送",+ working: "正在处理…",+ steps: "{count} 个步骤",+ copy: "复制",+ copyCode: "复制代码",+ copied: "已复制",+ copyFailed: "无法复制,请长按文字手动选择。",+ imagePlaceholder: "图片",+ jumpLatest: "回到最新",cancelQueued: "取消排队消息",waitingApproval: "等待电脑上审批。",waitingInput: "需要在电脑上输入。",diff --git a/apps/desktop/resources/lan-webui/markdown.js b/apps/desktop/resources/lan-webui/markdown.jsnew file mode 100644index 000000000..5b8d289d8--- /dev/null+++ b/apps/desktop/resources/lan-webui/markdown.js@@ -0,0 +1,263 @@+// LAN WebUI safe Markdown: a GFM subset rendered straight to DOM nodes.+// No HTML passthrough, no remote fetches (images become placeholders) and+// only absolute http(s) links. Regexes avoid lookbehind for older Safari.+"use strict";++(() => {+ const { el, icon } = window.LanKit;++ // A backtick fence's info string may not contain backticks (GFM).+ const FENCE = /^ {0,3}(?:(`{3,})([^`]*)|(~{3,})(.*))$/;+ const HEADING = /^ {0,3}(#{1,6})\s+(.*?)(?:\s+#+)?\s*$/;+ const RULE = /^ {0,3}([-*_])(?:\s*\1){2,}\s*$/;+ const QUOTE = /^ {0,3}>\s?(.*)$/;+ const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/;+ const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;+ const INLINE = new RegExp([+ /(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/.source, // 1-2 code span+ /!\[([^\]]*)\]\(((?:[^()]|\([^()]*\))*)\)/.source, // 3-4 image+ /\[([^\]]+)\]\(\s*<?((?:[^\s()<>]|\([^\s()<>]*\))+)>?(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/.source, // 5-6 link (one level of balanced parens)+ /\*\*(?=\S)([\s\S]*?\S)\*\*/.source, // 7 strong+ /__(?=\S)([\s\S]*?\S)__/.source, // 8 strong+ /~~(?=\S)([\s\S]*?\S)~~/.source, // 9 strike+ /\*(?=[^\s*])([\s\S]*?[^\s*])\*/.source, // 10 emphasis+ /(https?:\/\/[^\s<>]*[^\s<>.,;:!?'")\]}*_~])/.source, // 11 bare URL+ /\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/.source, // 12 escape+ ].join("|"), "g");+ const MAX_DEPTH = 4;++ const leading = (line) => line.length - line.trimStart().length;+ const text = (value) => document.createTextNode(value);++ function safeHref(href) {+ try {+ const url = new URL(href);+ return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;+ } catch {+ return null;+ }+ }++ function inline(source, options, depth = 0) {+ if (depth > MAX_DEPTH) return [text(source)];+ const out = [];+ const pattern = new RegExp(INLINE.source, "g");+ let last = 0;+ let match;+ while ((match = pattern.exec(source))) {+ if (match.index > last) out.push(text(source.slice(last, match.index)));+ last = pattern.lastIndex;+ const nested = (value) => inline(value, options, depth + 1);+ if (match[1] !== undefined) {+ const code = match[2];+ out.push(el("code", { text: code.length > 2 && code.startsWith(" ") && code.endsWith(" ") ? code.slice(1, -1) : code }));+ } else if (match[4] !== undefined) {+ out.push(el("span", { class: "md-image" }, [icon("image", "xs"), el("span", { text: match[3] || options.labels.image })]));+ } else if (match[5] !== undefined) {+ const href = safeHref(match[6]);+ out.push(href+ ? el("a", { href, target: "_blank", rel: "noopener noreferrer" }, nested(match[5]))+ : el("span", {}, nested(match[5])));+ } else if (match[7] !== undefined || match[8] !== undefined) {+ out.push(el("strong", {}, nested(match[7] ?? match[8])));+ } else if (match[9] !== undefined) {+ out.push(el("del", {}, nested(match[9])));+ } else if (match[10] !== undefined) {+ out.push(el("em", {}, nested(match[10])));+ } else if (match[11] !== undefined) {+ const href = safeHref(match[11]);+ out.push(href ? el("a", { href, target: "_blank", rel: "noopener noreferrer", text: match[11] }) : text(match[11]));+ } else {+ out.push(text(match[12]));+ }+ }+ if (last < source.length) out.push(text(source.slice(last)));+ return out;+ }++ function startsBlock(lines, index) {+ const line = lines[index];+ return FENCE.test(line) || HEADING.test(line) || RULE.test(line) || QUOTE.test(line) || ITEM.test(line) || isTable(lines, index);+ }+ const isTable = (lines, index) => lines[index].includes("|") && index + 1 < lines.length && lines[index + 1].includes("-") && TABLE_SEP.test(lines[index + 1]);++ function paragraph(lines, options) {+ const node = el("p");+ lines.forEach((line, index) => {+ const hard = / {2,}$|\\$/.test(line);+ node.append(...inline(line.replace(/\\$/, "").trim(), options));+ if (index < lines.length - 1) node.append(hard ? el("br") : text("\n"));+ });+ return node;+ }++ function codeBlock(code, lang, options) {+ return el("div", { class: "code-block" }, [+ el("div", { class: "code-head" }, [+ el("span", { class: "code-lang", text: lang.toLowerCase() }),+ el("button", {+ type: "button",+ class: "icon-btn code-copy",+ "aria-label": options.labels.copyCode,+ onclick: (event) => options.onCopy(code, event.currentTarget),+ }, icon("copy", "sm")),+ ]),+ el("pre", {}, el("code", { text: code })),+ ]);+ }++ /** Split a table row on unescaped pipes outside code spans. */+ function cells(row) {+ const trimmed = row.trim().replace(/^\|/, "").replace(/\|$/, "");+ const out = [];+ let current = "";+ let ticks = false;+ for (let i = 0; i < trimmed.length; i += 1) {+ const char = trimmed[i];+ if (char === "\\" && trimmed[i + 1] === "|") {+ current += "|";+ i += 1;+ } else if (char === "`") {+ ticks = !ticks;+ current += char;+ } else if (char === "|" && !ticks) {+ out.push(current.trim());+ current = "";+ } else {+ current += char;+ }+ }+ out.push(current.trim());+ return out;+ }++ function table(lines, start, parent, options) {+ const head = cells(lines[start]);+ const align = cells(lines[start + 1]).map((cell) => (cell.endsWith(":") ? (cell.startsWith(":") ? "center" : "right") : ""));+ const body = el("tbody");+ let i = start + 2;+ while (i < lines.length && lines[i].trim() && lines[i].includes("|")) {+ const row = cells(lines[i]);+ body.append(el("tr", {}, head.map((_, column) => el("td", { class: align[column] ? `align-${align[column]}` : undefined }, inline(row[column] ?? "", options)))));+ i += 1;+ }+ parent.append(el("div", { class: "table-wrap" }, el("table", {}, [+ el("thead", {}, el("tr", {}, head.map((cell, column) => el("th", { class: align[column] ? `align-${align[column]}` : undefined }, inline(cell, options))))),+ body,+ ])));+ return i;+ }++ function list(lines, start, parent, options) {+ const first = ITEM.exec(lines[start]);+ const indent = first[1].length;+ const ordered = /\d/.test(first[2]);+ const node = el(ordered ? "ol" : "ul");+ if (ordered && Number.parseInt(first[2], 10) !== 1) node.setAttribute("start", String(Number.parseInt(first[2], 10)));+ const sameList = (line) => {+ const match = ITEM.exec(line);+ return Boolean(match) && match[1].length === indent && /\d/.test(match[2]) === ordered;+ };+ let i = start;+ while (i < lines.length && sameList(lines[i])) {+ const match = ITEM.exec(lines[i]);+ const contentIndent = match[1].length + match[2].length + 1;+ const body = [match[3]];+ i += 1;+ while (i < lines.length) {+ const line = lines[i];+ if (!line.trim()) {+ if (i + 1 < lines.length && lines[i + 1].trim() && leading(lines[i + 1]) > indent) {+ body.push("");+ i += 1;+ continue;+ }+ break;+ }+ if (leading(line) > indent) {+ body.push(line.slice(Math.min(contentIndent, leading(line))));+ i += 1;+ continue;+ }+ if (startsBlock(lines, i)) break;+ body.push(line);+ i += 1;+ }+ const item = el("li");+ blocks(body, item, options);+ node.append(item);+ let next = i;+ while (next < lines.length && !lines[next].trim()) next += 1;+ if (next < lines.length && sameList(lines[next])) i = next;+ else break;+ }+ parent.append(node);+ return i;+ }++ function blocks(lines, parent, options) {+ let i = 0;+ while (i < lines.length) {+ const line = lines[i];+ if (!line.trim()) {+ i += 1;+ continue;+ }+ const fence = FENCE.exec(line);+ if (fence) {+ const marker = fence[1] ?? fence[3];+ const lang = (fence[2] ?? fence[4]).trim().split(/\s+/)[0];+ const close = new RegExp(`^ {0,3}${marker[0] === "`" ? "`" : "~"}{${marker.length},}\\s*$`);+ const code = [];+ i += 1;+ while (i < lines.length && !close.test(lines[i])) code.push(lines[i++]);+ i += 1;+ parent.append(codeBlock(code.join("\n"), lang, options));+ continue;+ }+ const heading = HEADING.exec(line);+ if (heading) {+ parent.append(el(`h${heading[1].length}`, {}, inline(heading[2], options)));+ i += 1;+ continue;+ }+ if (RULE.test(line)) {+ parent.append(el("hr"));+ i += 1;+ continue;+ }+ if (QUOTE.test(line)) {+ const inner = [];+ while (i < lines.length && lines[i].trim() && QUOTE.test(lines[i])) inner.push(QUOTE.exec(lines[i++])[1]);+ const quote = el("blockquote");+ blocks(inner, quote, options);+ parent.append(quote);+ continue;+ }+ if (ITEM.test(line)) {+ i = list(lines, i, parent, options);+ continue;+ }+ if (isTable(lines, i)) {+ i = table(lines, i, parent, options);+ continue;+ }+ const para = [line];+ i += 1;+ while (i < lines.length && lines[i].trim() && !startsBlock(lines, i)) para.push(lines[i++]);+ parent.append(paragraph(para, options));+ }+ }++ /**+ * @param {string} source+ * @param {{ labels: { copyCode: string, image: string }, onCopy(text: string, button: HTMLElement): void }} options+ */+ function render(source, options) {+ const fragment = document.createDocumentFragment();+ blocks(String(source).replace(/\r\n?/g, "\n").split("\n"), fragment, options);+ return fragment;+ }++ window.LanMarkdown = { render };+})();diff --git a/apps/desktop/resources/lan-webui/styles.css b/apps/desktop/resources/lan-webui/styles.cssindex e9a56afbf..2db965489 100644--- a/apps/desktop/resources/lan-webui/styles.css+++ b/apps/desktop/resources/lan-webui/styles.css@@ -45,11 +45,17 @@--ds-warning: #ff8549;--ds-error: #ff6764;--ds-purple: #c27aff;+ /* One-dark-pro / one-light plates: the same code-card pair as Desktop. */+ --ds-code-bg: #282c34;+ --ds-code-ink: #abb2bf;+ --ds-code-head-bg: color-mix(in oklab, #ffffff 4%, transparent);+ --ds-inline-code-bg: color-mix(in oklab, #ffffff 7%, transparent);--ds-elevation-stroke: 0 0 0 0.5px color-mix(in oklab, #ffffff 12%, transparent);--ds-shadow-dialog: 0 16px 48px rgba(0, 0, 0, 0.55);--ds-shadow-composer: 0 3px 7.5px #0000000a, 0 0 20px #0000000d;--ds-shadow-fab: 0 6px 20px rgba(0, 0, 0, 0.4);+ --radius-3xs: 4px;--radius-xs: 8px;--radius-sm: 10px;--radius-md: 12px;@@ -70,6 +76,7 @@--text-base: 14px;--text-base-plus: 15px;--text-lg: 16px;+ --text-lg-plus: 18px;--text-xl: 20px;--text-2xl: 28px;--font-weight-normal: 400;@@ -125,6 +132,10 @@--ds-warning: #e25507;--ds-error: #e02e2a;--ds-purple: #7c3aed;+ --ds-code-bg: #fafafa;+ --ds-code-ink: #383a42;+ --ds-code-head-bg: color-mix(in oklab, #1a1c1f 3.5%, transparent);+ --ds-inline-code-bg: color-mix(in oklab, #1a1c1f 6%, transparent);--ds-elevation-stroke: 0 0 0 0.5px color-mix(in oklab, #1a1c1f 12%, transparent);--ds-shadow-dialog: 0 16px 48px rgba(0, 0, 0, 0.12);--ds-shadow-fab: 0 6px 20px rgba(0, 0, 0, 0.16);@@ -137,6 +148,16 @@*::after {box-sizing: border-box;}+/* Component display rules must never resurrect a hidden element. */+[hidden] {+ display: none !important;+}+.copy-buffer {+ position: fixed;+ top: 0;+ left: -9999px;+ opacity: 0;+}html {-webkit-text-size-adjust: 100%;text-size-adjust: 100%;@@ -403,6 +424,10 @@ label {.header-sub .meta-item:has(.dot) {flex: none;}+.header-sub .scope {+ flex: none;+ max-width: 50%;+}.header-sub .meta-text {overflow: hidden;text-overflow: ellipsis;@@ -432,18 +457,6 @@ label {padding-left: 40px;border-radius: var(--radius-full);}-.chip {- flex: none;- padding: 0 14px 0 12px;- border-radius: var(--radius-full);- background-color: var(--ds-tile);- color: var(--ds-text-secondary);- font-size: var(--text-md-plus);-}-.chip[aria-pressed="true"] {- background-color: var(--ds-tile-deep);- color: var(--ds-text-primary);-}/* ---------- lists ---------- */.list {@@ -454,11 +467,6 @@ label {padding: 0;list-style: none;}-.list.group {- margin-bottom: 12px;- border-radius: var(--radius-md-plus);- background: var(--ds-tile);-}.row {position: relative;display: flex;@@ -466,9 +474,6 @@ label {border-radius: var(--radius-md);transition: background-color var(--motion-duration-fast) var(--motion-ease-out);}-.list.group .row {- border-radius: var(--radius-md-plus);-}.row:has(.row-main:active) {background-color: var(--ds-bg-active);}@@ -570,13 +575,44 @@ label {color: var(--ds-text-faint);}-main > button.signout {+.section {+ margin-bottom: 16px;+}+.section-label {+ margin: 6px 12px 4px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+ font-weight: var(--font-weight-medium);+ line-height: var(--leading-normal);+}+.hint {+ padding: 4px 12px 8px;+ color: var(--ds-text-muted);+ font-size: var(--text-md);+}+.footer {+ display: flex;+ flex-direction: column;+ margin-top: auto;+ padding: 8px 0 calc(8px + env(safe-area-inset-bottom));+}+.footer-link {+ justify-content: flex-start;+ gap: 12px;+ min-height: 48px;+ padding: 0 12px;+ border-radius: var(--radius-md);+ color: var(--ds-text-secondary);+ font-size: var(--text-base);+ font-weight: var(--font-weight-normal);+}+.footer-link .icon:last-child {+ margin-left: auto;+ color: var(--ds-text-faint);+}+.footer .signout {align-self: center;- margin: auto 0 0;- padding-top: 24px;- padding-bottom: calc(12px + env(safe-area-inset-bottom));- min-height: calc(var(--tap) + 36px + env(safe-area-inset-bottom));- background: transparent;+ margin-top: 12px;color: var(--ds-text-muted);font-size: var(--text-md);font-weight: var(--font-weight-normal);@@ -637,6 +673,9 @@ main > button.fab {.msg.assistant {align-self: stretch;}+.msg.user.pending {+ opacity: 0.6;+}.msg.tool {display: flex;align-items: flex-start;@@ -655,7 +694,8 @@ main > button.fab {color: var(--ds-text-muted);}/* The streaming caret describes work in flight, so it may keep animating. */-.msg.live::after {+.msg.live > :is(p, h1, h2, h3, h4, h5, h6):last-child::after,+.msg.live > :is(ul, ol):last-child > li:last-child > :last-child::after {content: "";display: inline-block;width: 0.5em;@@ -668,6 +708,299 @@ main > button.fab {animation: caret 1s steps(2, jump-none) infinite;}+/* ---------- answer markdown ---------- */+.msg.md {+ white-space: normal;+}+.md > :is(p, h1, h2, h3, h4, h5, h6, ul, ol, blockquote, .code-block, .table-wrap):first-of-type {+ margin-top: 0;+}+.md > :last-child {+ margin-bottom: 0;+}+.md p {+ margin: 0.65em 0;+}+.md :is(h1, h2, h3, h4, h5, h6) {+ margin: 1.15em 0 0.4em;+ font-weight: var(--font-weight-semibold);+ line-height: var(--leading-tight);+ letter-spacing: var(--tracking-tight);+}+.md h1 {+ font-size: var(--text-xl);+}+.md h2 {+ font-size: var(--text-lg-plus);+}+.md h3 {+ font-size: var(--text-lg);+}+.md h4 {+ font-size: var(--text-base-plus);+}+.md :is(h5, h6) {+ color: var(--ds-text-secondary);+ font-size: var(--text-base);+}+.md :is(ul, ol) {+ margin: 0.65em 0;+ padding-left: 1.4em;+}+.md li {+ margin: 0.28em 0;+ padding-left: 0.15em;+}+.md li > p {+ margin: 0.2em 0;+}+.md li::marker {+ color: var(--ds-text-muted);+}+.md blockquote {+ margin: 0.85em 0;+ padding: 0.55em 0.9em;+ border-radius: var(--radius-md);+ background: var(--ds-tile);+ color: var(--ds-text-secondary);+}+.md blockquote > :first-child {+ margin-top: 0;+}+.md blockquote > :last-child {+ margin-bottom: 0;+}+/* A thematic break is pure space: no line is drawn (D297). */+.md hr {+ height: 0;+ margin: 1.4em 0;+ border: 0;+}+.md strong {+ font-weight: var(--font-weight-semibold);+}+.md del {+ color: var(--ds-text-muted);+}+.md a {+ color: var(--ds-text-primary);+ text-decoration-line: underline;+ text-decoration-color: color-mix(in oklab, var(--ds-text-primary) 32%, transparent);+ text-decoration-thickness: 1px;+ text-underline-offset: 3px;+}+.md code {+ padding: 0.14em 0.4em;+ border-radius: var(--radius-3xs);+ background: var(--ds-inline-code-bg);+ font-family: var(--font-mono);+ font-size: var(--text-md);+ font-variant-ligatures: none;+ -webkit-box-decoration-break: clone;+ box-decoration-break: clone;+}+.md-image {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 0 8px;+ border-radius: var(--radius-full);+ background: var(--ds-tile-deep);+ color: var(--ds-text-secondary);+ font-size: var(--text-sm);+ vertical-align: baseline;+}+.code-block {+ margin: 0.9em 0;+ overflow: hidden;+ border-radius: var(--radius-md-plus);+ background: var(--ds-code-bg);+ color: var(--ds-code-ink);+}+.code-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ min-height: 36px;+ padding-left: 14px;+ background: var(--ds-code-head-bg);+}+.code-lang {+ color: color-mix(in oklab, var(--ds-code-ink) 72%, transparent);+ font-family: var(--font-mono);+ font-size: var(--text-xs-plus);+ -webkit-user-select: none;+ user-select: none;+}+/* A 44px target inside a 36px band: the negative margin keeps the band slim. */+.code-copy {+ margin: -4px 0;+ border-radius: var(--radius-xs);+ color: color-mix(in oklab, var(--ds-code-ink) 72%, transparent);+}+.code-block pre {+ margin: 0;+ padding: 12px 14px;+ overflow-x: auto;+ font-family: var(--font-mono);+ font-size: var(--text-md);+ line-height: var(--leading-relaxed);+ white-space: pre;+ -webkit-user-select: text;+ user-select: text;+}+.code-block pre code {+ padding: 0;+ background: none;+ font-size: inherit;+}+.table-wrap {+ margin: 0.9em 0;+ overflow-x: auto;+ border-radius: var(--radius-md-plus);+ background: var(--ds-tile);+}+.md table {+ min-width: 100%;+ border-collapse: collapse;+ font-size: var(--text-md);+ line-height: var(--leading-normal);+}+.md :is(th, td) {+ padding: 8px 12px;+ text-align: left;+ vertical-align: top;+}+.md th {+ background: var(--ds-tile-deep);+ font-weight: var(--font-weight-medium);+ white-space: nowrap;+}+.md tbody tr:nth-child(even) td {+ background: var(--ds-tile);+}+.md .align-center {+ text-align: center;+}+.md .align-right {+ text-align: right;+}++/* ---------- transcript extras ---------- */+.steps {+ align-self: flex-start;+ max-width: 100%;+ border-radius: var(--radius-sm);+ background: var(--ds-tool-row-bg);+ color: var(--ds-text-secondary);+ font-size: var(--text-sm-plus);+}+.steps summary {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: var(--tap);+ padding: 0 10px 0 12px;+ list-style: none;+ cursor: pointer;+ -webkit-user-select: none;+ user-select: none;+}+.steps summary::-webkit-details-marker {+ display: none;+}+.steps summary .icon {+ color: var(--ds-text-muted);+}+.steps summary > .icon:last-child {+ transition: rotate var(--motion-duration-fast) var(--motion-ease-out);+}+.steps[open] summary > .icon:last-child {+ rotate: 90deg;+}+.steps-count {+ flex: none;+ font-weight: var(--font-weight-medium);+}+.steps-names {+ min-width: 0;+ overflow: hidden;+ color: var(--ds-text-muted);+ text-overflow: ellipsis;+ white-space: nowrap;+}+.steps-list {+ display: flex;+ flex-direction: column;+ padding: 0 0 6px;+}+.steps-list .msg.tool {+ padding: 4px 12px;+ background: transparent;+}+.msg-actions {+ display: flex;+ margin: -16px 0 -8px -14px;+}+.msg-actions .icon-btn {+ color: var(--ds-text-muted);+}+.working {+ display: flex;+ align-items: center;+ gap: 10px;+ color: var(--ds-text-muted);+ font-size: var(--text-md-plus);+}+.working-dots {+ display: inline-flex;+ gap: 4px;+}+/* In-flight work may keep animating (design system 4.5). */+.working-dots i {+ width: 6px;+ height: 6px;+ border-radius: var(--radius-round);+ background: currentColor;+ animation: pulse 1.2s ease-in-out infinite;+}+.working-dots i:nth-child(2) {+ animation-delay: 0.15s;+}+.working-dots i:nth-child(3) {+ animation-delay: 0.3s;+}+.chat-empty {+ display: flex;+ flex: 1;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 4px;+ padding: 48px 16px;+ color: var(--ds-text-muted);+ font-size: var(--text-md);+ text-align: center;+}+.chat-empty .icon {+ margin-bottom: 10px;+ color: var(--ds-text-faint);+}+.chat-empty-title {+ color: var(--ds-text-primary);+ font-size: var(--text-lg);+ font-weight: var(--font-weight-semibold);+}+.jump {+ position: absolute;+ bottom: 100%;+ left: 50%;+ translate: -50% -4px;+ background-color: var(--ds-bg-elevated-opaque);+ box-shadow: var(--ds-elevation-stroke), var(--ds-shadow-fab);+ animation: fade-in var(--motion-duration-normal) var(--motion-ease-out);+}+.chat-dock {position: sticky;bottom: 0;@@ -772,14 +1105,6 @@ main > button.fab {.composer .send {width: var(--tap);}-.composer .send.is-queue {- width: auto;- border-radius: var(--radius-full);-}-.composer .send.is-queue > span {- padding: 0 12px;- font-size: var(--text-md-plus);-}.composer .send:disabled {opacity: 1;background-color: var(--ds-send-disabled-bg);@@ -859,12 +1184,20 @@ main > button.fab {animation: rise-in var(--motion-duration-normal) var(--motion-ease-out);}.sheet-title {+ display: -webkit-box;overflow: hidden;padding: 12px 16px 10px;color: var(--ds-text-muted);font-size: var(--text-md);font-weight: var(--font-weight-medium);+ line-height: var(--leading-normal);text-align: center;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;+}+.sheet-label {+ min-width: 0;+ overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}@@ -997,6 +1330,16 @@ main > button.fab {opacity: 0.35;}}+@keyframes pulse {+ 0%,+ 80%,+ 100% {+ opacity: 0.25;+ }+ 40% {+ opacity: 1;+ }+}@keyframes caret {50% {opacity: 0;diff --git a/apps/desktop/test/helpers/lan-webui-fixture.mjs b/apps/desktop/test/helpers/lan-webui-fixture.mjsindex ba5bfd469..1ac67f480 100644--- a/apps/desktop/test/helpers/lan-webui-fixture.mjs+++ b/apps/desktop/test/helpers/lan-webui-fixture.mjs@@ -7,6 +7,34 @@ register(pathToFileURL(join(here, "ts-import-hooks.mjs")));const { createLanWorkspace } = await import("../../electron/main/lan-webui/workspace.ts");export const { createLanServer } = await import("../../electron/main/lan-webui/server.ts");+/** Markdown, consecutive tool steps and unsafe content the page must defuse. */+const richTranscript = [+ { id: "r1", role: "user", content: "How do I run the tests?" },+ { id: "r2", role: "assistant", content: "Checking the scripts." },+ { id: "r3", role: "tool", content: "/secret/path package.json", toolName: "Read" },+ { id: "r4", role: "tool", content: "/secret/path ok", toolName: "Bash" },+ {+ id: "r5",+ role: "assistant",+ content: [+ "Run **all** tests:",+ "",+ "```sh",+ "pnpm test",+ "```",+ "",+ "- unit",+ "- e2e",+ "",+ "See [docs](https://example.com/docs) or [local](file:///etc/passwd).",+ "",+ "",+ "",+ "<script>window.__pwned = true</script>",+ ].join("\n"),+ },+];+/** A fake Desktop: host-core catalog, Agent Host bridge and internal IPC. */export function desktop() {const groups = [@@ -39,7 +67,7 @@ export function desktop() {...session,messageStart: 0,hasMoreBefore: false,- messages: [+ messages: params.id === "s-tmp" ? richTranscript : params.id.startsWith("s-new-") ? [] : [{ id: "m1", role: "user", content: "hello" },{ id: "m2", role: "assistant", content: "hi there" },{ id: "m3", role: "tool", content: "/secret/path output", toolName: "Bash" },diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjsindex fe9de437e..cedaf876d 100644--- a/apps/desktop/test/lan-webui-browser-user-path.test.mjs+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs@@ -18,6 +18,8 @@ async function assets() {["/index.html", { type: "text/html; charset=utf-8", body: await read("index.html") }],["/app.js", { type: "text/javascript; charset=utf-8", body: await read("app.js") }],["/locale.js", { type: "text/javascript; charset=utf-8", body: await read("locale.js") }],+ ["/kit.js", { type: "text/javascript; charset=utf-8", body: await read("kit.js") }],+ ["/markdown.js", { type: "text/javascript; charset=utf-8", body: await read("markdown.js") }],["/styles.css", { type: "text/css; charset=utf-8", body: await read("styles.css") }],]);}@@ -33,6 +35,8 @@ const journey = String.raw`(async () => {throw new Error("timed out waiting for " + label);};const rowByTitle = (title) => [...document.querySelectorAll(".row")].find((row) => row.querySelector(".row-title")?.textContent === title);+ const titles = (selector) => [...document.querySelectorAll(selector + " .row-title")].map((n) => n.textContent);+ const view = () => document.getElementById("app").dataset.view;// A direct control.click() bypasses hit testing and misses full-page interceptors.const tap = (control) => {control.scrollIntoView({ block: "center" });@@ -55,8 +59,11 @@ const journey = String.raw`(async () => {form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));// Redeeming the code connects immediately, without a second Desktop action.+ // Home answers "what was I doing" first: recent conversations across projects.await wait(() => rowByTitle("Alpha"), "projects");- result.projects = [...document.querySelectorAll(".row-title")].map((n) => n.textContent);+ result.projects = titles("#section-projects");+ result.recent = titles("#section-recent");+ result.recentScope = rowByTitle("Scratch").querySelector(".row-meta").textContent;// Searching re-renders the list but keeps the field focused with its text.const search = document.getElementById("list-search");@@ -65,22 +72,59 @@ const journey = String.raw`(async () => {search.dispatchEvent(new Event("input"));await wait(() => rowByTitle("Alpha") && !rowByTitle("Beta"), "filtered projects");result.searchKept = document.activeElement?.id === "list-search" && document.activeElement.value === "Al";+ // One search covers conversations in every project too.+ document.activeElement.value = "login";+ document.activeElement.dispatchEvent(new Event("input"));+ await wait(() => rowByTitle("Fix login") && !rowByTitle("Alpha"), "conversation search");+ result.searchSessions = titles("#section-recent");document.activeElement.value = "";document.activeElement.dispatchEvent(new Event("input"));await wait(() => rowByTitle("Beta"), "cleared search");++ // A recent conversation opens straight from Home and renders safe Markdown.+ tap(rowByTitle("Scratch").querySelector(".row-main"));+ await wait(() => view() === "chat:s-tmp" && document.querySelector(".msg.md strong"), "rich transcript");+ const answer = [...document.querySelectorAll(".msg.md")].pop();+ result.markdown = {+ strong: answer.querySelector("strong")?.textContent,+ codeLang: answer.querySelector(".code-block .code-lang")?.textContent,+ code: answer.querySelector(".code-block pre code")?.textContent,+ items: answer.querySelectorAll("ul > li").length,+ links: [...answer.querySelectorAll("a")].map((a) => [a.getAttribute("href"), a.target, a.rel]),+ localLinkText: answer.textContent.includes("local"),+ image: answer.querySelector(".md-image")?.textContent,+ images: document.querySelectorAll("img").length,+ scripts: document.querySelectorAll("#app script").length,+ pwned: window.__pwned === true,+ rawHtmlShown: answer.textContent.includes("<script>"),+ };+ const steps = document.querySelector("details.steps");+ result.steps = { count: steps?.querySelector(".steps-count")?.textContent, names: steps?.querySelector(".steps-names")?.textContent, open: steps?.open };+ result.copyActions = document.querySelectorAll(".msg-actions button").length;+ result.leakedInSteps = document.body.textContent.includes("/secret/path");+ history.back();+ await wait(() => view() === "home" && rowByTitle("Alpha"), "back to home");+const temporary = await wait(() => rowByTitle("Temporary conversations") ?? rowByTitle("临时会话"), "temporary entry");tap(temporary.querySelector(".row-main"));- await wait(() => rowByTitle("Scratch") && document.querySelector("main > button.primary"), "temporary conversations");+ await wait(() => view() === "sessions:__temporary__" && rowByTitle("Scratch") && document.querySelector("main > button.primary"), "temporary conversations");history.back();- await wait(() => rowByTitle("Alpha"), "back to projects");+ await wait(() => view() === "home" && rowByTitle("Alpha"), "back to projects");// Open a project and see its sessions.tap(rowByTitle("Alpha").querySelector(".row-main"));- await wait(() => rowByTitle("Fix login"), "sessions");+ await wait(() => view() === "sessions:g-a" && rowByTitle("Fix login"), "sessions");result.sessions = [...document.querySelectorAll(".row-title")].map((n) => n.textContent);result.projectHash = location.hash;result.strayText = [document.getElementById("app").innerText];+ // Archived items live behind one quiet entry, not a sticky filter.+ tap(document.querySelector(".footer-link"));+ await wait(() => view() === "sessions:g-a:archived" && document.querySelector(".empty"), "archived view");+ result.archivedHash = location.hash;+ history.back();+ await wait(() => view() === "sessions:g-a" && rowByTitle("Fix login"), "back from archived");+// Organize from the row menu: pin.tap(rowByTitle("Fix login").querySelector(".row-more"));await wait(() => !document.getElementById("sheet").hidden, "sheet");@@ -109,13 +153,28 @@ const journey = String.raw`(async () => {tap(document.querySelector("main > button.primary"));const input = await wait(() => document.getElementById("composer-input"), "composer");result.chatHash = location.hash;+ result.emptyChat = document.querySelector(".chat-empty-title")?.textContent;input.value = "hello from phone";input.dispatchEvent(new Event("input"));tap(document.querySelector(".composer button.primary"));- await wait(() => document.querySelectorAll(".msg").length >= 2 && input.isConnected === false || document.getElementById("composer-input")?.value === "", "sent");+ // The message shows at once, before the Host confirms it.+ result.optimistic = document.querySelector(".msg.user.pending")?.textContent.includes("hello from phone") === true;+ await wait(() => document.querySelector(".composer .stop") && document.querySelector(".working"), "sent");result.messages = [...document.querySelectorAll(".msg")].map((n) => n.className.split(" ")[1]);result.leaked = document.body.textContent.includes("/secret/path");result.strayText.push(document.getElementById("app").innerText);+ // While a reply runs: a working cue, and Stop is the only action until there is text.+ result.working = Boolean(document.querySelector(".working"));+ result.composerRunning = {+ sendHidden: document.querySelector(".composer .send").hidden,+ stop: Boolean(document.querySelector(".composer .stop")?.offsetParent),+ };+ const follow = document.getElementById("composer-input");+ follow.value = "and then?";+ follow.dispatchEvent(new Event("input"));+ result.composerQueue = !document.querySelector(".composer .send").hidden;+ follow.value = "";+ follow.dispatchEvent(new Event("input"));// Phone layout: no horizontal scroll and touch-sized controls.result.horizontalScroll = document.documentElement.scrollWidth > window.innerWidth;@@ -123,11 +182,26 @@ const journey = String.raw`(async () => {// Back returns to the project's session list.history.back();- await wait(() => rowByTitle("Fix login flow"), "back to sessions");+ await wait(() => view() === "sessions:g-a" && rowByTitle("Fix login flow"), "back to sessions");result.backHash = location.hash;history.back();- await wait(() => rowByTitle("Alpha"), "back to projects before sign-out");- tap(document.querySelector("main > button.link"));+ await wait(() => view() === "home" && rowByTitle("Alpha"), "back to projects");++ // From Home, New conversation only asks where it should live.+ tap(document.querySelector("main > button.primary"));+ await wait(() => !document.getElementById("sheet").hidden, "project picker");+ result.picker = [...document.querySelectorAll("#sheet-actions button:not(.cancel)")].map((b) => b.textContent);+ tap([...document.querySelectorAll("#sheet-actions button")].find((b) => b.textContent === "Beta"));+ await wait(() => view()?.startsWith("chat:s-new-2") && document.getElementById("composer-input"), "picked conversation");+ result.pickedHash = location.hash;+ history.back();+ await wait(() => view() === "home" && rowByTitle("Alpha"), "back home before sign-out");++ // Disconnecting asks first, because pairing again needs a new code.+ tap(document.querySelector(".signout"));+ await wait(() => !document.getElementById("sheet").hidden, "sign-out confirmation");+ result.stillSignedIn = !document.getElementById("pair-code");+ tap(document.querySelector("#sheet-actions button.danger"));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");result.pairRequests = performance.getEntriesByType("resource").filter((entry) => new URL(entry.name).pathname === "/pair").length;@@ -192,6 +266,28 @@ test("a phone pairs with a formatted paste, uses projects and conversations, andassert.match(result.projects[0], /^(Temporary conversations|临时会话)$/);assert.deepEqual(result.projects.slice(1), ["Alpha", "Beta"]);+ assert.deepEqual(result.recent, ["Scratch", "Second root chat", "Fix login", "A plan"], "recent conversations span every project");+ assert.match(result.recentScope, /Temporary conversations|临时会话/, "a recent row names where it lives");+ assert.deepEqual(result.searchSessions, ["Fix login"]);+ assert.deepEqual(result.markdown, {+ strong: "all",+ codeLang: "sh",+ code: "pnpm test",+ items: 2,+ links: [["https://example.com/docs", "_blank", "noopener noreferrer"]],+ localLinkText: true,+ image: "diagram",+ images: 0,+ scripts: 0,+ pwned: false,+ rawHtmlShown: true,+ });+ assert.match(result.steps.count, /2/);+ assert.equal(result.steps.names, "Read, Bash");+ assert.equal(result.steps.open, false, "tool steps start folded");+ assert.equal(result.copyActions, 1, "copy sits under the last answer of the exchange");+ assert.equal(result.leakedInSteps, false);+ assert.equal(result.archivedHash, "#/p/g-a/archived");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");@@ -201,10 +297,20 @@ test("a phone pairs with a formatted paste, uses projects and conversations, andassert.equal(result.sheetClosed, true);assert.equal(fake.sessions.find((session) => session.id === "s-a1").title, "Fix login flow");assert.match(result.chatHash, /^#\/s\/s-new-1$/);+ assert.equal(result.emptyChat, "Alpha", "a new conversation shows where it will run");+ assert.equal(result.optimistic, true, "a sent message appears before the Host confirms it");+ assert.equal(result.working, true);+ assert.deepEqual(result.composerRunning, { sendHidden: true, stop: true });+ assert.equal(result.composerQueue, true, "typing while a reply runs offers to queue");+ assert.deepEqual(result.picker.slice(1), ["Alpha", "Beta"]);+ assert.match(result.picker[0], /Temporary conversations|临时会话/);+ assert.equal(result.pickedHash, "#/s/s-new-2");+ assert.deepEqual(fake.calls.filter(([channel]) => channel === "create").map(([, args]) => args[0]), [{ projectPath: "/work/a" }, { projectPath: "/work/b" }]);+ assert.equal(result.stillSignedIn, true, "sign-out waits for confirmation");assert.equal(fake.turns.length, 1);assert.equal(fake.turns[0].params.input.text, "hello from phone");assert.equal(fake.turns[0].params.sessionId, "s-new-1");- assert.ok(result.messages.includes("user") && result.messages.includes("assistant"));+ assert.deepEqual(result.messages, ["user"], "the Host has not recorded the turn yet, so the optimistic bubble stays");assert.equal(result.leaked, false);for (const text of result.strayText) assert.doesNotMatch(text, /\bnull\b|undefined/, "no placeholder text leaks into the page");assert.equal(result.horizontalScroll, false);@@ -281,3 +387,41 @@ test("a legacy pending response tells the user to restart the desktop", { timeou})()`;assert.equal((await runPhone(t, script)).result, true);});++test("the shipped Markdown renderer keeps GFM structure and defuses unsafe input", { timeout: 60_000 }, async (t) => {+ const script = String.raw`(async () => {+ while (!window.LanMarkdown) await new Promise(requestAnimationFrame);+ const options = { labels: { copyCode: "Copy code", image: "Image" }, onCopy() {} };+ const html = (source) => {+ const box = document.createElement("div");+ box.append(window.LanMarkdown.render(source, options));+ return box.innerHTML;+ };+ return JSON.stringify({+ nested: html("- a\n - b\n- c"),+ ordered: html("3. x\n4. y"),+ table: html("| a | b |\n|:-|-:|\n| 1 \\| 2 | ${"`"}x|y${"`"} |"),+ inlineFence: html("${"```"}code${"```"} stays inline"),+ unterminated: html("${"```"}js\nlet a = 1;"),+ quote: html("> **hi**\n> there"),+ unsafeLink: html("[x](javascript:alert(1)) [y](https://ok.test/a)"),+ arithmetic: html("2 * 3 * 4"),+ bareUrl: html("see https://ok.test/path."),+ heading: html("## Title ##"),+ softBreak: html("one\ntwo \nthree"),+ });+ })()`;+ const { result } = await runPhone(t, script);+ assert.equal(result.nested, "<ul><li><p>a</p><ul><li><p>b</p></li></ul></li><li><p>c</p></li></ul>");+ assert.equal(result.ordered, '<ol start="3"><li><p>x</p></li><li><p>y</p></li></ol>');+ assert.match(result.table, /^<div class="table-wrap"><table><thead><tr><th>a<\/th><th class="align-right">b<\/th><\/tr><\/thead>/);+ assert.match(result.table, /<tbody><tr><td>1 \| 2<\/td><td class="align-right"><code>x\|y<\/code><\/td><\/tr><\/tbody>/);+ assert.equal(result.inlineFence, "<p><code>code</code> stays inline</p>");+ assert.match(result.unterminated, /<span class="code-lang">js<\/span>.*<pre><code>let a = 1;<\/code><\/pre>/);+ assert.equal(result.quote, "<blockquote><p><strong>hi</strong>\nthere</p></blockquote>");+ assert.equal(result.unsafeLink, '<p><span>x</span> <a href="https://ok.test/a" target="_blank" rel="noopener noreferrer">y</a></p>');+ assert.equal(result.arithmetic, "<p>2 * 3 * 4</p>");+ assert.equal(result.bareUrl, '<p>see <a href="https://ok.test/path" target="_blank" rel="noopener noreferrer">https://ok.test/path</a>.</p>');+ assert.equal(result.heading, "<h2>Title</h2>");+ assert.equal(result.softBreak, "<p>one\ntwo<br>three</p>");+});diff --git a/apps/desktop/test/lan-webui-user-path.test.mjs b/apps/desktop/test/lan-webui-user-path.test.mjsindex ac605396c..7aae883ae 100644--- a/apps/desktop/test/lan-webui-user-path.test.mjs+++ b/apps/desktop/test/lan-webui-user-path.test.mjs@@ -224,3 +224,34 @@ test("direct pairing respects the device limit without disconnecting other devicassert.equal((await phone.request("GET", "/v1/projects")).status, 200);assert.equal(server.devices().length, 16);});++test("the recent list spans every visible scope, lifts running work and names each project", async (t) => {+ const { phone, activeTurns, meta } = await setup(t);+ activeTurns.set("s-plan", "turn-plan");++ const recent = await phone.request("GET", "/v1/sessions?q=");+ assert.equal(recent.status, 200);+ // Running first, then most recent; SSH and unregistered sessions stay hidden.+ assert.deepEqual(recent.body.items.map((s) => s.id), ["s-plan", "s-tmp", "s-b1", "s-a1"]);+ assert.deepEqual(+ Object.fromEntries(recent.body.items.map((s) => [s.id, s.projectLabel])),+ { "s-plan": "Alpha", "s-tmp": null, "s-b1": "Beta", "s-a1": "Alpha" },+ );+ assert.equal(recent.body.items[0].status, "running");++ // Title search works across projects.+ assert.deepEqual((await phone.request("GET", "/v1/sessions?q=login")).body.items.map((s) => s.id), ["s-a1"]);++ // The conversation names its project, so a deep link still shows where it lives.+ assert.equal((await phone.request("GET", "/v1/sessions/s-b1")).body.session.projectLabel, "Beta");++ // Sessions of an archived project drop out of the recent list, not out of their project.+ const beta = (await phone.request("GET", "/v1/projects")).body.items.find((p) => p.id === "g-b");+ assert.equal((await phone.request("POST", "/v1/projects/g-b/organize", { revision: beta.revision, archived: true })).status, 200);+ assert.ok(meta.projectMeta["/work/b"].archived);+ assert.deepEqual((await phone.request("GET", "/v1/sessions")).body.items.map((s) => s.id), ["s-plan", "s-tmp", "s-a1"]);+ assert.deepEqual((await phone.request("GET", "/v1/sessions?projectId=g-b")).body.items.map((s) => s.id), ["s-b1"]);++ // An unknown explicit project is still not found.+ assert.equal((await phone.request("GET", "/v1/sessions?projectId=nope")).status, 404);+});diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.mdindex f983700a8..04a02f9c9 100644--- a/docs/spec/01-product/03-lan-webui-mvp.md+++ b/docs/spec/01-product/03-lan-webui-mvp.md@@ -140,7 +140,11 @@ The browser API is a small WebUI-specific HTTP/JSON surface with same-origin SSEchange notices (`/v1/projects`, `/v1/sessions`, `/v1/sessions/:id[/history]`,`/v1/sessions/:id/turns`, `/v1/turns/:id:interrupt|:cancel`, `…/organize`). Itmaps onto existing Desktop handlers and Agent Host turn admission rather than-implementing the full RACP browser profile. Catalog changes reach other clients+implementing the full RACP browser profile. `/v1/sessions` without a+`projectId` lists every visible scope (running first, then most recent; sessions+of archived projects only with `archived=1`), and each session carries its+display `projectLabel` (`null` for Temporary) so cross-project rows say where+they live. Catalog changes reach other clientseven when they are not subscribed to that conversation; clients invalidate andrefetch a scoped view rather than streaming every transcript. A deep linkrestores only the browser's navigation, after fresh authorization.@@ -250,6 +254,22 @@ and devices (16); never silently truncate input.capsule pinned within thumb reach, a floating composer pill, and rename inthe action sheet instead of a native prompt. A live refresh keeps thefocused field, caret and draft; Back restores the list scroll position.+- Home leads with Recent conversations across projects (running work always+ listed), then Projects with Temporary first. One search covers project names+ and conversation titles. Archived items sit behind one Archived entry per+ list (`#/archived`, `#/p/:id/archived`) instead of a sticky filter. Home's New+ conversation asks only for the destination. Disconnecting this device asks+ for confirmation.+- A conversation names its project, model and run state in the header; an+ empty one shows where it will run. Answers render the safe Markdown subset+ (no HTML, no remote images, only `http(s)` links opening in a new tab);+ consecutive tool calls fold into one step summary; code blocks and the last+ answer of each exchange offer Copy (with a non-secure-context fallback). A+ sent message appears immediately and yields to the Host record, the queue+ entry, or a 30 s timeout; a failed send restores the text to the draft.+ While a reply runs without streamed text a working cue shows; the composer+ offers Stop alone until text is typed, then Queue. Jump to latest appears+ once the reader scrolls away. Send and New conversation wait while offline.- Qualification: physical iPhone/Safari and Android/Chrome on the same LAN,plus desktop Chromium; record browser/OS/build versions. Qualify listenerstart, shutdown and restart on every Desktop OS advertised as supported.diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.mdindex 19e762e9f..f6acc44a3 100644--- a/docs/spec/06-delivery/e2e/live-and-remote.md+++ b/docs/spec/06-delivery/e2e/live-and-remote.md@@ -783,7 +783,7 @@ user's running instance.- **Steps:** Search for B and tap its row. Open a session's action menu, close it,then tap that session to read its history. Pin and rename B and rename, pin,archive and restore an idle session. Archive and restore B through the- archived filter. Make a competing Desktop rename and submit the stale edit.+ Archived view. Make a competing Desktop rename and submit the stale edit.- **Expected:** One row per group, stable IDs, correct filtered/recent/pinnedlists; both clients show committed changes without reloading. Archive is notdeletion and does not cascade; restoring B preserves the separately archived@@ -801,8 +801,9 @@ user's running instance.- **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.- Create a temporary conversation from its own entry. Repeat with no configured- model and with a pre-existing eligible empty conversation in B.+ Create a temporary conversation from its own entry, and one in B from Home's+ New conversation picker. Reopen B's chat from Home's Recent list. 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@@ -813,6 +814,9 @@ user's running instance.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.+ A sent message shows immediately and is replaced, not duplicated, by the+ Host record; a failed send returns its text to the draft. Recent rows name+ their project, and running sessions stay listed.- **Acceptance:** B, C, D; W03, W04, W05.### E2E-272: Answer ordinary input but leave privileged decisions on Desktopdiff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.tsindex b2ace7a36..a76ec7a2b 100644--- a/packages/shared/src/lan-webui.ts+++ b/packages/shared/src/lan-webui.ts@@ -22,6 +22,12 @@ export interface LanSession {readOnly: boolean;status: LanSessionStatus;updatedAt: string;+ /**+ * Display name of the owning project, so cross-project lists can say where a+ * conversation lives. `null` for temporary conversations. Optional: absent+ * from responses of builds that predate it.+ */+ projectLabel?: string | null;}export interface LanPage<T> {items: T[];