Skip to content

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

feat(desktop): let paired LAN clients choose a session model

vastsaf0f948fdca93
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 9079183ed..76acc064d 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -1,6 +1,6 @@
import { join } from "node:path";
import { dialog, shell, type BrowserWindow, type IpcMain, type IpcMainInvokeEvent } from "electron";
-import { err, ErrorCodes, IPC, ok, type LifecycleDialogChoice, type Result } from "@pi-desktop/shared";
+import { err, ErrorCodes, IPC, ok, type LifecycleDialogChoice, type ModelInfo, type Result } from "@pi-desktop/shared";
import type { AgentHostBridge } from "../agent-host-bridge";
import type { AgentSidecar } from "../agent-sidecar";
import type { HostProcess } from "../host-process";
@@ -607,8 +607,14 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
getHost,
getBridge: () => getAgentHostBridge(),
invoke: (channel, args) => invokeInternal(channel, args),
+ acquireSessionOperation,
+ readCachedModels: async (providerId) => {
+ const result: { models: ModelInfo[] } = await invokeInternal(IPC.invoke.providersListModels, [{ providerId, source: "cache" }]);
+ return result.models;
+ },
channels: {
sessionCreate: IPC.invoke.sessionCreate,
+ sessionConfigure: IPC.invoke.sessionConfigure,
sessionRename: IPC.invoke.sessionRename,
projectGroupRename: IPC.invoke.projectGroupRename,
agentAbort: IPC.invoke.agentAbort,
diff --git a/apps/desktop/electron/main/lan-webui/assets.ts b/apps/desktop/electron/main/lan-webui/assets.ts
index 4f9ff919d..b15135183 100644
--- a/apps/desktop/electron/main/lan-webui/assets.ts
+++ b/apps/desktop/electron/main/lan-webui/assets.ts
@@ -5,6 +5,7 @@ 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 modelPickerJs from "../../../resources/lan-webui/model-picker.js?raw";
import type { LanAsset } from "./server";
export function lanWebUiAssets(): ReadonlyMap<string, LanAsset> {
@@ -14,6 +15,7 @@ export function lanWebUiAssets(): ReadonlyMap<string, LanAsset> {
["/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 }],
+ ["/model-picker.js", { type: "text/javascript; charset=utf-8", body: modelPickerJs }],
["/styles.css", { type: "text/css; charset=utf-8", body: stylesCss }],
]);
}
diff --git a/apps/desktop/electron/main/lan-webui/models.ts b/apps/desktop/electron/main/lan-webui/models.ts
new file mode 100644
index 000000000..a1e575983
--- /dev/null
+++ b/apps/desktop/electron/main/lan-webui/models.ts
@@ -0,0 +1,42 @@
+import {
+ configuredChatModels,
+ imageGenerationBindings,
+ isChatProviderReady,
+ trustedExtensionAgentKeyFromProviderId,
+ type AppSettings,
+ type LanModelOption,
+ type ModelInfo,
+ type ProviderPublic,
+} from "@pi-desktop/shared";
+import type { LanHost } from "./workspace";
+
+export type ReadCachedModels = (providerId: string) => Promise<readonly ModelInfo[]>;
+type CatalogProvider = Pick<ProviderPublic, "id" | "name" | "enabled" | "hasSecret" | "authKind" | "models" | "defaultModelId">;
+
+/** Project only saved Composer choices. No remote discovery or credential reads. */
+export async function readLanModelOptions(
+ host: LanHost,
+ readCachedModels: ReadCachedModels,
+ providerId?: string,
+): Promise<LanModelOption[]> {
+ const [{ providers }, settings] = await Promise.all([
+ host.call<{ providers: CatalogProvider[] }>("providers.list", { includeDisabled: false }),
+ host.call<Pick<AppSettings, "imageGenerationModels" | "imageGeneration">>("settings.get"),
+ ]);
+ const imageGeneration = imageGenerationBindings(settings.imageGenerationModels, settings.imageGeneration);
+ const items: LanModelOption[] = [];
+ for (const provider of providers) {
+ if ((providerId !== undefined && provider.id !== providerId) ||
+ !isChatProviderReady(provider) || trustedExtensionAgentKeyFromProviderId(provider.id)) continue;
+ const cache = await readCachedModels(provider.id);
+ for (const { modelId, binding } of configuredChatModels(provider, cache, imageGeneration)) {
+ items.push({
+ providerId: provider.id,
+ modelId,
+ label: binding?.alias?.trim() || modelId,
+ providerLabel: provider.name,
+ });
+ }
+ }
+ return items;
+}
diff --git a/apps/desktop/electron/main/lan-webui/workspace.ts b/apps/desktop/electron/main/lan-webui/workspace.ts
index 10692abb4..d0e909d9e 100644
--- a/apps/desktop/electron/main/lan-webui/workspace.ts
+++ b/apps/desktop/electron/main/lan-webui/workspace.ts
@@ -1,14 +1,18 @@
import { createHash } from "node:crypto";
import {
LAN_TEMPORARY_PROJECT,
+ modelWireIdsEqual,
+ trustedExtensionAgentKeyFromProviderId,
type AgentEventEnvelope,
type LanConversation,
type LanMessage,
+ type LanModelCatalog,
type LanPage,
type LanProject,
type LanSession,
type ProjectGroupRecord,
} from "@pi-desktop/shared";
+import { readLanModelOptions, type ReadCachedModels } from "./models";
import type { LanMeta, LanOrganization } from "./organization";
import { normalizeProjectKey } from "./organization";
import { LanError, type LanChange, type LanRequest } from "./ports";
@@ -35,7 +39,9 @@ export type LanWorkspaceDeps = {
getHost(): LanHost | null;
getBridge(): LanBridge | null;
invoke(channel: string, args: unknown[]): Promise<unknown>;
- channels: { sessionCreate: string; sessionRename: string; projectGroupRename: string; agentAbort: string };
+ channels: { sessionCreate: string; sessionConfigure: string; sessionRename: string; projectGroupRename: string; agentAbort: string };
+ acquireSessionOperation(sessionId: string): Promise<() => void>;
+ readCachedModels: ReadCachedModels;
activeTurns: ReadonlyMap<string, string>;
organization: Pick<LanOrganization, "read" | "patch">;
/** Ask Desktop to refresh its catalog (and an idle open transcript); never navigates. */
@@ -48,7 +54,10 @@ type HostSession = {
projectPath?: string | null;
mode?: string;
source?: string;
- modelId?: string;
+ providerId?: string | null;
+ modelId?: string | null;
+ scheduledRun?: boolean;
+ remoteWorkspace?: unknown;
updatedAt?: string;
};
type HostMessage = { id: string; role: string; content?: unknown; toolName?: string; parentToolCallId?: string };
@@ -198,7 +207,9 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
if (projectId === undefined) throw new LanError(404, "NOT_FOUND");
const meta = deps.organization.read();
const label = projectId === null ? null : projectLabels(list, meta).get(projectId) ?? null;
- return { session, projectId, meta, view: sessionView(session, projectId, meta, label) };
+ const group = projectId === null ? undefined : list.find((candidate) => candidate.id === projectId);
+ const projectArchived = group !== undefined && projectView(group, meta).archived;
+ return { session, view: sessionView(session, projectId, meta, label), projectArchived };
}
function projectLabels(list: ProjectGroupRecord[], meta: LanMeta): Map<string, string> {
@@ -294,7 +305,8 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
}
async function conversation(sessionId: string): Promise<LanConversation> {
- const { session, view } = await requireLocalSession(sessionId);
+ const local = await requireLocalSession(sessionId);
+ const { session, view } = local;
const [messages, pending] = await Promise.all([
history(sessionId, null),
deps.getBridge()?.pendingInteractiveRequests(sessionId).catch(() => ({ asks: [], permissions: [] })) ??
@@ -313,9 +325,78 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
waiting,
queue,
modelLabel: session.modelId ?? null,
+ canSelectModel: !modelRestriction(local),
};
}
+ type LocalSession = Awaited<ReturnType<typeof requireLocalSession>>;
+ function modelRestriction({ session, view, projectArchived }: LocalSession) {
+ if (view.readOnly || session.remoteWorkspace || session.scheduledRun ||
+ (session.providerId && trustedExtensionAgentKeyFromProviderId(session.providerId))) return "READ_ONLY";
+ if (view.archived || projectArchived) return "ARCHIVED";
+ return null;
+ }
+
+ function modelPrecondition({ session }: LocalSession) {
+ return {
+ projectPath: session.projectPath ?? null,
+ providerId: session.providerId ?? null,
+ modelId: session.modelId ?? null,
+ };
+ }
+
+ async function requireModelSession(sessionId: string) {
+ const local = await requireLocalSession(sessionId);
+ const denied = modelRestriction(local);
+ if (denied) throw new LanError(409, denied);
+ return { ...local, modelRevision: revision(sessionId, local.view.projectId, modelPrecondition(local)) };
+ }
+
+ async function listSessionModels(sessionId: string): Promise<LanModelCatalog> {
+ const local = await requireModelSession(sessionId);
+ const items = await readLanModelOptions(host(), deps.readCachedModels);
+ const activeModelId = local.session.modelId;
+ const selected = activeModelId && items.find(({ providerId, modelId }) =>
+ providerId === local.session.providerId && modelWireIdsEqual(modelId, activeModelId));
+ return { items, selected: selected ? { providerId: selected.providerId, modelId: selected.modelId } : null, revision: local.modelRevision };
+ }
+
+ async function setSessionModel(sessionId: string, body: Record<string, unknown>) {
+ const { providerId, modelId, revision: expectedRevision } = body;
+ if (Object.keys(body).length !== 3 || typeof providerId !== "string" || !providerId ||
+ typeof modelId !== "string" || !modelId || typeof expectedRevision !== "string" ||
+ !/^[A-Za-z0-9_-]{12}$/.test(expectedRevision)) throw new LanError(400, "INVALID_ARGUMENT");
+
+ const release = await deps.acquireSessionOperation(sessionId);
+ try {
+ const before = await requireModelSession(sessionId);
+ if (expectedRevision !== before.modelRevision) throw new LanError(409, "CONFLICT");
+ const options = await readLanModelOptions(host(), deps.readCachedModels, providerId);
+ if (!options.some((option) => option.modelId === modelId)) throw new LanError(409, "MODEL_UNAVAILABLE");
+ const runtime = bridge();
+ const pending = await runtime.pendingInteractiveRequests(sessionId);
+ const local = await requireModelSession(sessionId);
+ if (expectedRevision !== local.modelRevision) throw new LanError(409, "CONFLICT");
+ if (pending.asks.length || pending.permissions.length || deps.activeTurns.has(sessionId) ||
+ runtime.queue.list(sessionId).length) throw new LanError(409, "MODEL_BUSY");
+ // The Host repeats the scope/model comparison under its write lock.
+ await deps.invoke(deps.channels.sessionConfigure, [sessionId, {
+ mode: "agent", providerId, modelId, expectedAgentModel: modelPrecondition(local),
+ }]);
+ deps.notifyDesktop();
+ emit({ sessionId });
+ return { ok: true };
+ } catch (error) {
+ const code = (error as { errorCode?: unknown })?.errorCode;
+ if (code === "CONFLICT") throw new LanError(409, "CONFLICT");
+ if (code === "NOT_FOUND") throw new LanError(404, "NOT_FOUND");
+ if (code === "PLAN_CONFIGURATION_BLOCKED") throw new LanError(409, "MODEL_BUSY");
+ throw error;
+ } finally {
+ release();
+ }
+ }
+
async function createSession(body: Record<string, unknown>) {
const projectId = body.projectId === null ? null : stringField(body, "projectId");
if (projectId === undefined) throw new LanError(400, "INVALID_ARGUMENT");
@@ -430,6 +511,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
if (resource === "projects" && !id) return listProjects(query);
if (resource === "sessions" && !id) return listSessions(query);
if (resource === "sessions" && id && !sub) return conversation(id);
+ if (resource === "sessions" && id && sub === "models" && parts.length === 4) return listSessionModels(id);
if (resource === "sessions" && id && sub === "history") {
await requireLocalSession(id);
return history(id, query.get("cursor"));
@@ -439,6 +521,7 @@ export function createLanWorkspace(deps: LanWorkspaceDeps) {
if (resource === "projects" && id && sub === "organize") return organizeProject(id, body);
if (resource === "sessions" && id && sub === "organize") return organizeSession(id, body);
if (resource === "sessions" && id && sub === "turns") return sendTurn(deviceId, id, body, key);
+ if (resource === "sessions" && id && sub === "model" && parts.length === 4) return setSessionModel(id, body);
if (resource === "turns" && id?.endsWith(":interrupt")) return interrupt(id.slice(0, -10), body);
if (resource === "turns" && id?.endsWith(":cancel")) return cancel(id.slice(0, -7), body);
}
diff --git a/apps/desktop/resources/lan-webui/app.js b/apps/desktop/resources/lan-webui/app.js
index 42ffede1b..4ad44497d 100644
--- a/apps/desktop/resources/lan-webui/app.js
+++ b/apps/desktop/resources/lan-webui/app.js
@@ -162,6 +162,14 @@
notify(errorText(error instanceof ApiError ? error.code : "FAILED"));
}
+ const modelPicker = window.createLanModelPicker({
+ t, errorText,
+ load: (sessionId) => api("GET", `/v1/sessions/${enc(sessionId)}/models`),
+ save: (sessionId, choice) => api("POST", `/v1/sessions/${enc(sessionId)}/model`, choice, newKey()),
+ refresh: (sessionId) => state.route.view === "chat" && state.route.sessionId === sessionId ? render({ refresh: true }) : undefined,
+ onSavingChange: () => state.syncComposer?.(),
+ });
+
async function loadAll(path) {
const items = [];
let cursor = null;
@@ -195,6 +203,7 @@
};
const back = (fallback) => (history.length > 1 ? history.back() : go(fallback));
window.addEventListener("hashchange", (event) => {
+ modelPicker.dismiss();
const prefill = takePairingCode();
if (prefill && !state.me) {
showPair("", prefill);
@@ -700,6 +709,8 @@
: null;
const canChat = !session.readOnly && !session.archived;
+ if (!conversation.canSelectModel || !canChat) modelPicker.dismiss();
+ if (!canChat) state.syncComposer = null;
const composer = canChat ? buildComposer(sessionId, conversation) : null;
const title = session.title || t("untitled");
const head = header({
@@ -707,7 +718,7 @@
backTo: projectHash(session.projectId),
subtitle: [
scopeMeta(session),
- conversation.modelLabel ? { text: conversation.modelLabel, class: "model" } : null,
+ !conversation.canSelectModel && conversation.modelLabel ? { text: conversation.modelLabel, class: "model" } : null,
sessionStatus(conversation.waiting ? "waiting" : running ? "running" : session.status),
].filter(Boolean),
actions: [moreButton(title, organizeActions("sessions", session))],
@@ -729,6 +740,7 @@
function buildComposer(sessionId, conversation) {
const running = Boolean(conversation.activeTurnId);
+ const modelTrigger = conversation.canSelectModel ? modelPicker.trigger(sessionId, conversation.modelLabel) : null;
const input = el("textarea", {
id: "composer-input", rows: "1", "aria-label": t("composer"),
placeholder: running ? t("composerFollowUp") : t("composer"), enterkeyhint: "send",
@@ -752,14 +764,21 @@
const sync = () => {
const hasText = Boolean(input.value.trim());
send.hidden = running && !hasText;
- send.disabled = state.sending || !hasText || !state.online;
+ const savingModel = modelPicker.isSaving(sessionId);
+ send.disabled = state.sending || savingModel || !hasText || !state.online;
+ if (modelTrigger) {
+ const busy = running || conversation.waiting || conversation.queue.length || state.sending;
+ const restriction = !state.online ? "NETWORK" : busy ? "MODEL_BUSY" : null;
+ modelTrigger.disabled = Boolean(restriction) || savingModel;
+ modelPicker.sync(sessionId, restriction);
+ }
};
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 () => {
const text = input.value.trim();
- if (!text || state.sending || !state.online) return;
+ if (!text || state.sending || modelPicker.isSaving(sessionId) || !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 };
@@ -793,7 +812,7 @@
});
setTimeout(fit, 0);
sync();
- return el("div", { class: "composer" }, [input, el("div", { class: "actions" }, [stop, send])]);
+ return el("div", { class: modelTrigger ? "composer has-model-picker" : "composer" }, [input, modelTrigger, el("div", { class: "actions" }, [stop, send])]);
}
async function render(options = {}) {
@@ -832,6 +851,7 @@
}
function showPair(message, prefill = "") {
+ modelPicker.dismiss();
closeEvents();
setOffline(false);
const code = el("input", {
diff --git a/apps/desktop/resources/lan-webui/index.html b/apps/desktop/resources/lan-webui/index.html
index 84db43aa4..20c94732e 100644
--- a/apps/desktop/resources/lan-webui/index.html
+++ b/apps/desktop/resources/lan-webui/index.html
@@ -12,6 +12,7 @@
<script src="/locale.js" defer></script>
<script src="/kit.js" defer></script>
<script src="/markdown.js" defer></script>
+ <script src="/model-picker.js" defer></script>
<script src="/app.js" defer></script>
</head>
<body>
diff --git a/apps/desktop/resources/lan-webui/locale.js b/apps/desktop/resources/lan-webui/locale.js
index 28e5584fb..fbcd94c0b 100644
--- a/apps/desktop/resources/lan-webui/locale.js
+++ b/apps/desktop/resources/lan-webui/locale.js
@@ -42,6 +42,13 @@ window.LAN_LOCALES = {
assistant: "Assistant",
tool: "Tool",
composer: "Message",
+ selectModel: "Choose model",
+ selectModelCurrent: "Choose model, current: {name}",
+ searchModels: "Search models",
+ loadingModels: "Loading models…",
+ savingModel: "Changing model…",
+ noModels: "Set up a chat model in Settings → Models on the computer.",
+ retry: "Try again",
send: "Send",
queue: "Queue",
stop: "Stop",
@@ -72,6 +79,8 @@ window.LAN_LOCALES = {
signOut: "Disconnect this device",
errors: {
BUSY: "A reply is still running. Queue your message or stop it first.",
+ MODEL_BUSY: "Wait for the current and queued work to finish before changing models.",
+ MODEL_UNAVAILABLE: "This model is no longer available. Refresh the list and choose another.",
CONFLICT: "This changed on another device. The latest version is shown; try again.",
ARCHIVED: "Restore it first.",
READ_ONLY: "Continue this conversation on the computer.",
@@ -127,6 +136,13 @@ window.LAN_LOCALES = {
assistant: "助手",
tool: "工具",
composer: "消息",
+ selectModel: "选择模型",
+ selectModelCurrent: "选择模型,当前:{name}",
+ searchModels: "搜索模型",
+ loadingModels: "正在加载模型…",
+ savingModel: "正在切换模型…",
+ noModels: "请在电脑的「设置 → 模型」中配置聊天模型。",
+ retry: "重试",
send: "发送",
queue: "排队",
stop: "停止",
@@ -157,6 +173,8 @@ window.LAN_LOCALES = {
signOut: "断开此设备",
errors: {
BUSY: "回复仍在进行。可以排队发送,或先停止。",
+ MODEL_BUSY: "请等当前任务和排队任务结束后再切换模型。",
+ MODEL_UNAVAILABLE: "此模型已不可用,请刷新列表后重新选择。",
CONFLICT: "已在其他设备上修改,已显示最新内容,请重试。",
ARCHIVED: "请先恢复。",
READ_ONLY: "请在电脑上继续该会话。",
diff --git a/apps/desktop/resources/lan-webui/model-picker.js b/apps/desktop/resources/lan-webui/model-picker.js
new file mode 100644
index 000000000..46fb0d4f0
--- /dev/null
+++ b/apps/desktop/resources/lan-webui/model-picker.js
@@ -0,0 +1,137 @@
+// The model chooser owns its dialog and any in-flight selection.
+"use strict";
+
+(() => {
+ const { el, icon } = window.LanKit;
+
+ window.createLanModelPicker = ({ t, errorText, load, save, refresh, onSavingChange }) => {
+ let current = null;
+ const saving = new Set();
+ const isSaving = (sessionId) => saving.has(sessionId);
+
+ function dismiss(restoreFocus = false) {
+ if (!current) return;
+ const { dialog } = current;
+ current = null;
+ dialog.close();
+ dialog.remove();
+ if (restoreFocus) document.getElementById("model-trigger")?.focus({ preventScroll: true });
+ }
+
+ function open(sessionId) {
+ if (current || isSaving(sessionId)) return;
+ let catalog = null;
+ let failure = null;
+ let restriction = null;
+ let loading = true;
+ const title = el("h2", { id: "model-picker-title", text: t("selectModel") });
+ const close = el("button", {
+ type: "button", class: "icon-btn", "aria-label": t("cancel"), onclick: () => dismiss(true),
+ }, icon("close"));
+ const search = el("input", {
+ type: "search", placeholder: t("searchModels"), "aria-label": t("searchModels"), autocomplete: "off", enterkeyhint: "search",
+ });
+ const status = el("p", { class: "model-picker-status", role: "status" });
+ const retry = el("button", { type: "button", class: "secondary", text: t("retry"), onclick: () => void reload() });
+ const list = el("ul", { class: "model-options", "aria-label": t("selectModel") });
+ const dialog = el("dialog", { class: "model-picker", "aria-labelledby": title.id }, el("div", { class: "model-picker-body" }, [
+ el("div", { class: "model-picker-header" }, [title, close]),
+ search, status, retry, list,
+ ]));
+ const isOpen = () => current?.dialog === dialog;
+
+ function paintStatus() {
+ const blocked = restriction || failure;
+ const busy = isSaving(sessionId);
+ const message = busy ? t("savingModel") : loading ? t("loadingModels") : blocked ? errorText(blocked) :
+ !catalog?.items.length ? t("noModels") : !list.children.length ? t("noMatches") : "";
+ if (status.textContent !== message) status.textContent = message;
+ status.hidden = !message;
+ retry.hidden = !failure || Boolean(restriction) || busy || loading;
+ search.hidden = !catalog?.items.length;
+ for (const button of list.querySelectorAll("button")) button.disabled = busy || Boolean(blocked);
+ }
+
+ function paintOptions() {
+ const query = search.value.trim().toLowerCase();
+ const selected = catalog?.selected;
+ list.replaceChildren(...(catalog?.items ?? []).filter((item) =>
+ [item.label, item.modelId, item.providerLabel].some((value) => value.toLowerCase().includes(query)),
+ ).map((item) => {
+ const checked = selected?.providerId === item.providerId && selected?.modelId === item.modelId;
+ return el("li", {}, el("button", {
+ type: "button", "aria-current": checked ? "true" : null,
+ onclick: () => checked ? dismiss(true) : void choose(item),
+ }, [
+ el("span", { class: "model-option-copy" }, [
+ el("span", { class: "model-option-name", text: item.label }),
+ el("span", { class: "model-option-provider", text: item.providerLabel }),
+ ]),
+ checked ? icon("check", "sm") : null,
+ ]));
+ }));
+ paintStatus();
+ }
+
+ async function reload() {
+ loading = true;
+ failure = null;
+ catalog = null;
+ paintOptions();
+ try {
+ catalog = await load(sessionId);
+ } catch (error) {
+ failure = error.code || "FAILED";
+ } finally {
+ loading = false;
+ if (isOpen()) paintOptions();
+ }
+ }
+
+ async function choose({ providerId, modelId }) {
+ if (!isOpen() || !catalog || failure || restriction || isSaving(sessionId)) return;
+ saving.add(sessionId);
+ paintStatus();
+ onSavingChange();
+ let saved = false;
+ try {
+ await save(sessionId, { providerId, modelId, revision: catalog.revision });
+ saved = true;
+ } catch (error) {
+ if (isOpen()) failure = error.code || "FAILED";
+ } finally {
+ await refresh(sessionId);
+ saving.delete(sessionId);
+ onSavingChange();
+ if (isOpen()) {
+ if (saved) dismiss(true);
+ else paintStatus();
+ }
+ }
+ }
+
+ current = { sessionId, dialog, sync: (code) => { restriction = code; paintStatus(); } };
+ search.addEventListener("input", paintOptions);
+ dialog.addEventListener("cancel", (event) => { event.preventDefault(); dismiss(true); });
+ dialog.addEventListener("click", (event) => { if (event.target === dialog) dismiss(true); });
+ document.body.append(dialog);
+ dialog.showModal();
+ void reload();
+ }
+
+ return {
+ dismiss,
+ isSaving,
+ sync(sessionId, restriction) {
+ if (current?.sessionId === sessionId) current.sync(restriction);
+ },
+ trigger(sessionId, label) {
+ return el("button", {
+ id: "model-trigger", type: "button", class: "model-trigger", "aria-haspopup": "dialog",
+ "aria-label": label ? t("selectModelCurrent", { name: label }) : t("selectModel"),
+ onclick: () => open(sessionId),
+ }, [el("span", { text: label || t("selectModel") }), icon("chevron", "xs")]);
+ },
+ };
+ };
+})();
diff --git a/apps/desktop/resources/lan-webui/styles.css b/apps/desktop/resources/lan-webui/styles.css
index 2db965489..1664f8a68 100644
--- a/apps/desktop/resources/lan-webui/styles.css
+++ b/apps/desktop/resources/lan-webui/styles.css
@@ -1120,6 +1120,110 @@ main > button.fab {
stroke: none;
}
+/* Keep the model choice under the prompt without making the text field narrower. */
+.composer.has-model-picker {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) auto;
+ align-items: center;
+ padding-inline-start: 8px;
+}
+.composer.has-model-picker textarea {
+ grid-column: 1 / -1;
+ padding-inline: 10px;
+}
+.model-trigger {
+ justify-self: start;
+ min-width: var(--tap);
+ max-width: 100%;
+ padding-inline: 10px;
+ border-radius: var(--radius-full);
+ color: var(--ds-text-secondary);
+ font-size: var(--text-md);
+}
+.model-trigger span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.model-trigger .icon {
+ rotate: 90deg;
+}
+
+.model-picker {
+ position: fixed;
+ inset: auto 0 0;
+ width: min(100%, 520px);
+ max-width: none;
+ max-height: min(520px, 85dvh);
+ margin: 0 auto;
+ padding: 0;
+ overflow: hidden;
+ border: 0;
+ border-radius: var(--radius-2xl) var(--radius-2xl) 0 0;
+ background: var(--ds-bg-elevated-opaque);
+ box-shadow: var(--ds-elevation-stroke), var(--ds-shadow-dialog);
+ color: var(--ds-text-primary);
+}
+.model-picker::backdrop {
+ background: var(--ds-scrim);
+}
+.model-picker-body {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ max-height: inherit;
+ padding: 8px max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left));
+}
+.model-picker-header {
+ display: flex;
+ flex: none;
+ align-items: center;
+ justify-content: space-between;
+ padding-inline-start: 8px;
+}
+.model-picker-header h2 {
+ font-size: var(--text-lg);
+ font-weight: var(--font-weight-semibold);
+}
+.model-picker-status {
+ padding: 8px;
+ color: var(--ds-text-secondary);
+}
+.model-options {
+ min-height: 0;
+ margin: 0;
+ padding: 2px;
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ list-style: none;
+}
+.model-options button {
+ justify-content: space-between;
+ width: 100%;
+ padding: 8px 12px;
+ text-align: start;
+}
+.model-options button[aria-current="true"] {
+ background: var(--ds-tile);
+}
+.model-option-copy {
+ display: grid;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+.model-option-provider {
+ color: var(--ds-text-secondary);
+ font-size: var(--text-sm);
+}
+@media (min-width: 640px) {
+ .model-picker {
+ inset: 0;
+ margin: auto;
+ border-radius: var(--radius-2xl);
+ }
+}
+
/* ---------- floating layers ---------- */
.status-pill:not([hidden]) {
position: fixed;
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
index 1c42875a8..41608863c 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerModelMenu.ts
@@ -4,6 +4,7 @@ import type {
SessionThinkingLevel,
} from "@pi-desktop/shared";
import {
+ isChatProviderReady,
imageGenerationBindings,
initialThinkingLevelForBinding,
initialThinkingLevelForUnmatchedModel,
@@ -135,11 +136,7 @@ export function useComposerModelMenu({
const modelGroups = useMemo(
() =>
providers
- .filter(
- (candidate) =>
- candidate.enabled &&
- (candidate.hasSecret || candidate.authKind === "none"),
- )
+ .filter(isChatProviderReady)
.map((candidate) => {
const models = composerModelsForProvider(
candidate,
@@ -256,7 +253,7 @@ export function useComposerModelMenu({
useEffect(() => {
if (!open) return;
for (const candidate of providers) {
- if (candidate.enabled && (candidate.hasSecret || candidate.authKind === "none")) {
+ if (isChatProviderReady(candidate)) {
void loadProviderModels(candidate.id);
}
}
diff --git a/apps/desktop/src/lib/composer-models.ts b/apps/desktop/src/lib/composer-models.ts
index 92131f6b9..9273b8bd0 100644
--- a/apps/desktop/src/lib/composer-models.ts
+++ b/apps/desktop/src/lib/composer-models.ts
@@ -1,5 +1,6 @@
import {
bindingSupportsImages,
+ configuredChatModels,
effectiveContextWindow,
isImageOnlyChatModel,
type ImageGenerationBindings,
@@ -46,16 +47,6 @@ export function composerModelChatEligible(
return !isImageOnlyChatModel(imageGeneration, providerId, modelId, metadata);
}
-function configuredModelIds(provider: ConfiguredProvider): string[] {
- const ids = (provider.models ?? [])
- .map((binding) => binding.id.trim())
- .filter(Boolean);
- if (ids.length > 0) return [...new Set(ids)];
-
- const legacyId = provider.defaultModelId?.trim();
- return legacyId ? [legacyId] : [];
-}
-
/**
* Build the Composer model list from the models explicitly enabled in
* provider settings. Discovery only enriches an exact configured id; it does
@@ -67,21 +58,7 @@ export function composerModelsForProvider(
discovered: readonly ModelInfo[] | undefined,
imageGeneration?: ImageGenerationBindings | null,
): ModelInfo[] {
- return configuredModelIds(provider).filter((modelId) => {
- const metadata = (discovered ?? []).find((model) =>
- sameComposerModelId(model.modelId, modelId),
- );
- // Only a pure image-generation endpoint is excluded: a model the user
- // marked for image generation that also supports conversation stays in
- // the Composer list (#2253).
- return !isImageOnlyChatModel(imageGeneration, provider.id, modelId, metadata)
- && !(discovered ?? []).some((model) =>
- sameComposerModelId(model.modelId, modelId) && model.discoveryState === "unlisted");
- }).map((modelId) => {
- const metadata = (discovered ?? []).find((model) =>
- sameComposerModelId(model.modelId, modelId),
- );
- const binding = composerModelBinding(provider, modelId);
+ return configuredChatModels(provider, discovered, imageGeneration).map(({ modelId, metadata, binding }) => {
const contextWindow = effectiveContextWindow(
metadata?.contextWindow,
binding?.contextWindow,
diff --git a/apps/desktop/test/helpers/lan-webui-fixture.mjs b/apps/desktop/test/helpers/lan-webui-fixture.mjs
index 34aaab5e2..4083a25b4 100644
--- a/apps/desktop/test/helpers/lan-webui-fixture.mjs
+++ b/apps/desktop/test/helpers/lan-webui-fixture.mjs
@@ -55,11 +55,21 @@ export function desktop() {
const turns = [];
const activeTurns = new Map();
const queue = new Map();
+ const providers = [
+ { id: "local-ai", name: "Local AI", enabled: true, authKind: "none", models: [
+ { id: "swift-chat", alias: "Swift" }, { id: "steady-chat", alias: "Steady" },
+ { id: "retired-chat" }, { id: "gpt-image-1" },
+ ], baseUrl: "https://private.example.test" },
+ { id: "inactive", name: "Inactive", enabled: false, hasSecret: true, models: [{ id: "hidden-chat" }] },
+ { id: "signed-out", name: "Signed out", enabled: true, authKind: "oauth", hasSecret: false, models: [{ id: "unavailable-chat" }] },
+ ];
let created = 0;
const host = {
async call(method, params) {
if (method === "project.groups.list") return { groups };
if (method === "session.list") return { sessions };
+ if (method === "providers.list") return { providers };
+ if (method === "settings.get") return { imageGeneration: { providerId: "local-ai", modelId: "gpt-image-1" } };
if (method === "session.get") {
const session = sessions.find((s) => s.id === params.id);
return {
@@ -110,7 +120,9 @@ export function desktop() {
const workspaceDeps = {
getHost: () => host,
getBridge: () => bridge,
- channels: { sessionCreate: "create", sessionRename: "rename", projectGroupRename: "groupRename", agentAbort: "abort" },
+ channels: { sessionCreate: "create", sessionConfigure: "configure", sessionRename: "rename", projectGroupRename: "groupRename", agentAbort: "abort" },
+ acquireSessionOperation: async () => () => {},
+ readCachedModels: async () => [{ modelId: "retired-chat", discoveryState: "unlisted" }, { modelId: "unconfigured-chat" }],
activeTurns,
async invoke(channel, args) {
calls.push([channel, args]);
@@ -119,6 +131,12 @@ export function desktop() {
sessions.push({ id, title: "", projectPath: args[0].projectPath ?? null, mode: "agent", updatedAt: "2026-11-09" });
return { session: { id } };
}
+ if (channel === "configure") {
+ const [id, { providerId, modelId }] = args;
+ const session = sessions.find((s) => s.id === id);
+ Object.assign(session, { providerId, modelId });
+ return { session };
+ }
if (channel === "rename") {
const session = sessions.find((s) => s.id === args[0]);
session.title = args[1];
diff --git a/apps/desktop/test/lan-webui-browser-user-path.test.mjs b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
index cedaf876d..40764a6e2 100644
--- a/apps/desktop/test/lan-webui-browser-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-browser-user-path.test.mjs
@@ -20,6 +20,7 @@ async function assets() {
["/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") }],
+ ["/model-picker.js", { type: "text/javascript; charset=utf-8", body: await read("model-picker.js") }],
["/styles.css", { type: "text/css; charset=utf-8", body: await read("styles.css") }],
]);
}
@@ -156,6 +157,19 @@ const journey = String.raw`(async () => {
result.emptyChat = document.querySelector(".chat-empty-title")?.textContent;
input.value = "hello from phone";
input.dispatchEvent(new Event("input"));
+ // Search and select a configured model before sending the same draft.
+ tap(document.getElementById("model-trigger"));
+ const modelSearch = await wait(() => document.querySelector("dialog[open] input:not([hidden])"), "model search");
+ modelSearch.value = "steady";
+ modelSearch.dispatchEvent(new Event("input"));
+ const matches = document.querySelectorAll("dialog[open] .model-options button");
+ result.modelMatches = Array.from(matches, (button) => button.querySelector(".model-option-name").textContent);
+ tap(matches[0]);
+ await wait(() => !document.querySelector("dialog[open]") && document.getElementById("model-trigger").textContent.includes("steady-chat"), "model saved");
+ result.draftAfterModelChange = document.getElementById("composer-input").value;
+ tap(document.getElementById("model-trigger"));
+ result.checkedModel = (await wait(() => document.querySelector('dialog[open] button[aria-current="true"] .model-option-name'), "selected model")).textContent;
+ tap(document.querySelector("dialog[open] .model-picker-header button"));
tap(document.querySelector(".composer button.primary"));
// The message shows at once, before the Host confirms it.
result.optimistic = document.querySelector(".msg.user.pending")?.textContent.includes("hello from phone") === true;
@@ -165,6 +179,7 @@ const journey = String.raw`(async () => {
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.modelBusy = document.getElementById("model-trigger").disabled;
result.composerRunning = {
sendHidden: document.querySelector(".composer .send").hidden,
stop: Boolean(document.querySelector(".composer .stop")?.offsetParent),
@@ -298,6 +313,11 @@ test("a phone pairs with a formatted paste, uses projects and conversations, and
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.deepEqual(result.modelMatches, ["Steady"]);
+ assert.equal(result.draftAfterModelChange, "hello from phone");
+ assert.equal(result.checkedModel, "Steady");
+ assert.equal(result.modelBusy, true);
+ assert.equal(fake.sessions.find(({ id }) => id === "s-new-1").modelId, "steady-chat");
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 });
diff --git a/apps/desktop/test/lan-webui-user-path.test.mjs b/apps/desktop/test/lan-webui-user-path.test.mjs
index 9ef254f64..967b6dde9 100644
--- a/apps/desktop/test/lan-webui-user-path.test.mjs
+++ b/apps/desktop/test/lan-webui-user-path.test.mjs
@@ -255,3 +255,36 @@ test("the recent list spans every visible scope, lifts running work and names ea
// An unknown explicit project is still not found.
assert.equal((await phone.request("GET", "/v1/sessions?projectId=nope")).status, 404);
});
+
+test("a paired browser can switch only to configured chat models in an idle local session", async (t) => {
+ const { phone, origin, activeTurns, queue, sessions, calls } = await setup(t);
+ const path = "/v1/sessions/s-a1";
+ assert.equal((await browser(origin).request("GET", `${path}/models`)).status, 401);
+ const { status, body: catalog } = await phone.request("GET", `${path}/models`);
+ assert.equal(status, 200);
+ assert.deepEqual(catalog.items, [
+ { providerId: "local-ai", modelId: "swift-chat", label: "Swift", providerLabel: "Local AI" },
+ { providerId: "local-ai", modelId: "steady-chat", label: "Steady", providerLabel: "Local AI" },
+ ]);
+ assert.equal(catalog.selected, null);
+ const choose = { providerId: "local-ai", modelId: "steady-chat", revision: catalog.revision };
+ assert.equal((await phone.request("POST", `${path}/model`, choose, { "X-CSRF-Token": "" })).status, 403);
+ assert.equal((await phone.request("POST", `${path}/model`, { ...choose, mode: "plan" })).body.code, "INVALID_ARGUMENT");
+ assert.equal((await phone.request("POST", `${path}/model`, { ...choose, modelId: "unconfigured-chat" })).body.code, "MODEL_UNAVAILABLE");
+ assert.equal((await phone.request("POST", "/v1/sessions/s-plan/model", choose)).body.code, "READ_ONLY");
+ assert.equal((await phone.request("POST", "/v1/sessions/s-ssh/model", choose)).status, 404);
+ activeTurns.set("s-a1", "active-turn");
+ assert.equal((await phone.request("POST", `${path}/model`, choose)).body.code, "MODEL_BUSY");
+ activeTurns.delete("s-a1");
+ queue.set("s-a1", [{ id: "queued-turn", content: "next" }]);
+ assert.equal((await phone.request("POST", `${path}/model`, choose)).body.code, "MODEL_BUSY");
+ queue.delete("s-a1");
+
+ assert.deepEqual(await phone.request("POST", `${path}/model`, choose), { status: 200, body: { ok: true } });
+ assert.equal((await phone.request("GET", path)).body.modelLabel, "steady-chat");
+ assert.deepEqual((await phone.request("GET", `${path}/models`)).body.selected, { providerId: "local-ai", modelId: "steady-chat" });
+ assert.equal((await phone.request("POST", `${path}/model`, { ...choose, modelId: "swift-chat" })).body.code, "CONFLICT");
+ assert.equal(calls.filter(([channel]) => channel === "configure").length, 1);
+ assert.equal(sessions.find(({ id }) => id === "s-a1").mode, "agent");
+ assert.equal(sessions.find(({ id }) => id === "s-tmp").modelId, undefined);
+});
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 2d756669a..6fc949697 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -12,6 +12,7 @@ mod review_actions_rpc;
mod scheduled_rpc;
mod scheduled_settings;
mod scheduled_tools;
+mod session_configuration;
mod session_display;
mod todos;
mod window_corner_rpc;
@@ -3062,51 +3063,7 @@ async fn handle_request(
todos::get_from(&st, session_id)
}
- "session.configure" => {
- let id = params
- .get("id")
- .and_then(|v| v.as_str())
- .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
- let mode = params
- .get("mode")
- .and_then(|v| v.as_str())
- .ok_or_else(|| rpc_err(1002, "mode required", "INVALID_PARAMS"))?;
- let thinking_level = thinking_level_param(&params)?;
- let fast_mode = fast_mode_param(&params)?;
- let st = state.lock().await;
- let prepared = modes_rpc::prepare_configure(&st, id, mode, &params)?;
- let session = sessions::configure_session_with_mode_snapshot(
- &st.db,
- id,
- mode,
- params.get("providerId").and_then(|v| v.as_str()),
- params.get("modelId").and_then(|v| v.as_str()),
- thinking_level.as_deref(),
- params.get("permissionMode").and_then(|v| v.as_str()),
- fast_mode,
- prepared.snapshot_hash(),
- )
- .map_err(|e| {
- let message = e.to_string();
- if message.starts_with("PLAN_") {
- plan_rpc_err(message)
- } else {
- rpc_err(1002, message, "INVALID_PARAMS")
- }
- })?
- .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
- let paused_run = modes_rpc::finish_configure(&st, prepared)?;
- let session = remote_tools::decorate_session(
- &st.db,
- serde_json::to_value(session)
- .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
- )?;
- drop(st);
- if let Some(run) = paused_run {
- modes_rpc::notify(&tx, &run).await;
- }
- Ok(json!({ "session": session }))
- }
+ "session.configure" => session_configuration::configure(&state, &tx, params).await,
"session.delete" => {
let id = params
.get("id")
diff --git a/crates/host-core/src/rpc/modes_rpc_tests.rs b/crates/host-core/src/rpc/modes_rpc_tests.rs
index d8c9430a3..dcd9b3867 100644
--- a/crates/host-core/src/rpc/modes_rpc_tests.rs
+++ b/crates/host-core/src/rpc/modes_rpc_tests.rs
@@ -623,3 +623,38 @@ async fn completion_report_rpc_completed_keeps_command_gate_and_blocked_settles_
.unwrap();
assert_eq!(run.wire(), settled["run"]);
}
+
+#[tokio::test]
+async fn guarded_model_change_refuses_stale_model_and_mode() {
+ let h = Harness::new("agent");
+ let before = h
+ .call("session.get", json!({ "id": h.session_id }))
+ .await
+ .unwrap();
+ let mut params = json!({
+ "id": h.session_id,
+ "mode": "agent",
+ "providerId": "local-ai",
+ "modelId": "steady-chat",
+ "expectedAgentModel": {
+ "projectPath": before["session"]["projectPath"],
+ "providerId": null,
+ "modelId": null,
+ },
+ });
+ let updated = h.call("session.configure", params.clone()).await.unwrap();
+ assert_eq!(updated["session"]["modelId"], "steady-chat");
+
+ params["modelId"] = json!("swift-chat");
+ let error = h
+ .call("session.configure", params.clone())
+ .await
+ .unwrap_err();
+ assert_eq!(error["data"]["errorCode"], "CONFLICT");
+
+ h.configure("plan", None).await.unwrap();
+ params["expectedAgentModel"]["providerId"] = json!("local-ai");
+ params["expectedAgentModel"]["modelId"] = json!("steady-chat");
+ let error = h.call("session.configure", params).await.unwrap_err();
+ assert_eq!(error["data"]["errorCode"], "CONFLICT");
+}
diff --git a/crates/host-core/src/rpc/session_configuration.rs b/crates/host-core/src/rpc/session_configuration.rs
new file mode 100644
index 000000000..b436aa09c
--- /dev/null
+++ b/crates/host-core/src/rpc/session_configuration.rs
@@ -0,0 +1,112 @@
+//! Session configuration and compare-before-write for LAN model selection.
+
+use serde_json::{json, Value};
+use tokio::sync::{mpsc, Mutex};
+
+use super::JsonRpcError;
+use super::{
+ fast_mode_param, modes_rpc, plan_rpc_err, remote_tools, rpc_err, thinking_level_param,
+};
+use crate::{sessions, state::AppState};
+
+/// The LAN edge has resolved the session and validated the requested model.
+/// Recheck its scope and binding under the same Host lock as the write; a
+/// concurrent Desktop change must never turn a model pick into a mode change.
+fn check_model_precondition(
+ st: &AppState,
+ id: &str,
+ mode: &str,
+ params: &Value,
+) -> Result<(), JsonRpcError> {
+ let Some(expected) = params.get("expectedAgentModel") else {
+ return Ok(());
+ };
+ if mode != "agent"
+ || params.get("providerId").and_then(Value::as_str).is_none()
+ || params.get("modelId").and_then(Value::as_str).is_none()
+ || [
+ "modeSnapshot",
+ "permissionMode",
+ "thinkingLevel",
+ "fastMode",
+ ]
+ .iter()
+ .any(|key| params.get(*key).is_some())
+ {
+ return Err(rpc_err(
+ 1002,
+ "expectedAgentModel only guards a model change",
+ "INVALID_PARAMS",
+ ));
+ }
+ let current = sessions::session_summary(&st.db, id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
+ let actual = json!({
+ "projectPath": current.project_path,
+ "providerId": current.provider_id,
+ "modelId": current.model_id,
+ });
+ if current.mode != "agent"
+ || current.scheduled_run
+ || remote_tools::session_remote_workspace_optional(st, id)?.is_some()
+ || expected != &actual
+ {
+ return Err(rpc_err(
+ 1008,
+ "session configuration has changed",
+ "CONFLICT",
+ ));
+ }
+ Ok(())
+}
+
+pub(super) async fn configure(
+ state: &Mutex<AppState>,
+ tx: &mpsc::UnboundedSender<String>,
+ params: Value,
+) -> Result<Value, JsonRpcError> {
+ let id = params
+ .get("id")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;
+ let mode = params
+ .get("mode")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "mode required", "INVALID_PARAMS"))?;
+ let thinking_level = thinking_level_param(&params)?;
+ let fast_mode = fast_mode_param(&params)?;
+ let st = state.lock().await;
+ check_model_precondition(&st, id, mode, &params)?;
+ let prepared = modes_rpc::prepare_configure(&st, id, mode, &params)?;
+ let session = sessions::configure_session_with_mode_snapshot(
+ &st.db,
+ id,
+ mode,
+ params.get("providerId").and_then(Value::as_str),
+ params.get("modelId").and_then(Value::as_str),
+ thinking_level.as_deref(),
+ params.get("permissionMode").and_then(Value::as_str),
+ fast_mode,
+ prepared.snapshot_hash(),
+ )
+ .map_err(|e| {
+ let message = e.to_string();
+ if message.starts_with("PLAN_") {
+ plan_rpc_err(message)
+ } else {
+ rpc_err(1002, message, "INVALID_PARAMS")
+ }
+ })?
+ .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
+ let paused_run = modes_rpc::finish_configure(&st, prepared)?;
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
+ drop(st);
+ if let Some(run) = paused_run {
+ modes_rpc::notify(tx, &run).await;
+ }
+ Ok(json!({ "session": session }))
+}
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 7c028f7a9..6796724c3 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -28,6 +28,7 @@ git history.
|---|---|---|
| lan-webui-code-pairing | [A one-time code pairs a LAN WebUI device directly](lan-webui-code-pairing.md) | Accepted |
| lan-webui-project-access | [Device confirmation grants access to all local LAN WebUI projects](lan-webui-project-access.md) | Superseded |
+| lan-webui-session-model-selection | [Paired LAN WebUI devices can select a session model](lan-webui-session-model-selection.md) | Accepted |
| codemode-sandbox-boundary | [Codemode sandbox execution boundary](codemode-sandbox-boundary.md) | Accepted |
| mode-definitions | [User-definable modes as staged workflows](mode-definitions.md) | Proposed |
| sidebar-layout-recovery | [Recover sidebar layout independently of Chromium storage](sidebar-layout-recovery.md) | Accepted |
diff --git a/docs/adr/lan-webui-session-model-selection.md b/docs/adr/lan-webui-session-model-selection.md
new file mode 100644
index 000000000..6f9fc6d76
--- /dev/null
+++ b/docs/adr/lan-webui-session-model-selection.md
@@ -0,0 +1,31 @@
+# ADR: Paired LAN WebUI devices can select a session model
+
+- Status: Accepted
+- Date: 2026-11-27
+- Related: [LAN WebUI pairing](lan-webui-code-pairing.md), [LAN WebUI MVP](../spec/01-product/03-lan-webui-mvp.md)
+
+## Context
+
+A person continuing work on the phone needs to choose a model before sending.
+Sending provider configuration to the browser would expose details unrelated to
+that choice. A per-message override would also make the two clients disagree
+about which model the conversation uses next.
+
+## Decision
+
+Expose a scoped list and a model-only mutation for an idle, ordinary local
+Agent session. Use Desktop's saved Composer bindings and local cached model
+metadata; the browser receives only provider/model IDs and display labels, and
+cannot initiate provider discovery. Validate the selection against the same
+catalog on write. Keep configuration at the Host through `session.configure`;
+a compare-before-write guard rejects a concurrently moved, reconfigured, or
+repurposed session. Mode, reasoning, permissions and global settings are not
+part of the browser request.
+
+## Consequences
+
+Both clients see the saved binding and use it for the next turn. The phone
+cannot configure providers, start privileged work, or change running/queued
+sessions through the picker. Pairing, the WebUI permission ceiling and storage
+ownership are unchanged. The browser endpoints and Host guard are additive;
+existing sessions and provider records need no migration.
diff --git a/docs/spec/01-product/03-lan-webui-mvp.md b/docs/spec/01-product/03-lan-webui-mvp.md
index f4bbe7a3d..12e286334 100644
--- a/docs/spec/01-product/03-lan-webui-mvp.md
+++ b/docs/spec/01-product/03-lan-webui-mvp.md
@@ -109,6 +109,13 @@ invalidate stale rows and deep links; do not redirect to a different session.
A new session inherits the configured desktop default; an existing one uses
its own configuration. If no usable model exists, preserve the draft and
point to model setup on Desktop. Never ask the phone for a provider key.
+- In an idle, writable local Agent conversation, tap the model chip under the
+ draft to search the Desktop's configured chat models by model or service.
+ The picker marks the session's saved selection and applies a new choice to
+ that conversation's next turn, without clearing the draft or changing
+ Desktop defaults. Keep the previous binding on failure and let the user
+ reload the choices. Running, queued, waiting, archived, scheduled, and
+ extension-owned sessions cannot be changed from this picker.
- Page older history backwards without losing the reading position. Render
user/assistant text, safe Markdown, code and bounded tool summaries in order.
Unsupported cards or attachments get a typed, non-executable placeholder;
@@ -154,6 +161,14 @@ even when they are not subscribed to that conversation; clients invalidate and
refetch a scoped view rather than streaming every transcript. A deep link
restores only the browser's navigation, after fresh authorization.
+`GET /v1/sessions/:id/models` returns the configured model choices, the saved
+selection when it is still listed, and an opaque revision. The choices carry
+only provider/model IDs and display labels. `POST /v1/sessions/:id/model`
+accepts only `{ providerId, modelId, revision }` and returns `{ ok: true }`.
+The server revalidates session eligibility, idleness, and the binding against
+the current local catalog. A stale selection returns `CONFLICT` rather than
+overwriting a newer edit. See [LAN model selection](../../adr/lan-webui-session-model-selection.md).
+
- Mutations carry a principal-bound idempotency key; organization edits carry
the last observed resource revision and an **explicit desired value**, not
“toggle”. A lost reply is reconciled with the Host; a proven same-key retry
@@ -205,7 +220,7 @@ diagnostics that the safe transcript projection does not already expose.
| Operation | Available after pairing | Not exposed by pairing |
|---|---|---|
| View | Local project and temporary catalogs, safe history, activity and scoped events | Remote project metadata, paths, secrets or arbitrary file reads |
-| Chat | Create, send/queue, interrupt, cancel queued work, answer ordinary typed questions when supported | Shell endpoint, remote approvals, raising permission mode, configuring providers |
+| Chat | Create, select a configured model in an idle local Agent conversation, send/queue, interrupt, cancel queued work, answer ordinary typed questions when supported | Shell endpoint, remote approvals, raising permission mode, configuring providers |
| Organize | Rename, set pin, set archive/restore on eligible objects | Permanent delete, project registration/root editing, granting roles |
Check the device credential, live resource scope, object state, and policy on
@@ -269,8 +284,9 @@ and devices (16); never silently truncate input.
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
+- A conversation names its project and run state in the header and its model
+ in the composer (or the header when it is not editable). 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
diff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.md
index 285ac11fc..6b2f762c6 100644
--- a/docs/spec/03-runtime/06-host-rpc-protocol.md
+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md
@@ -429,7 +429,12 @@ to later refresh and inference; the vendor picker does not collect them.
invalid modes or levels return
`INVALID_PARAMS`; mode is `plan | goal | agent` and changing any session
configuration is allowed only while idle and without a pending/queued/running
- Plan or Goal record
+ Plan or Goal record. An internal model-only caller may pass
+ `expectedAgentModel: { projectPath, providerId, modelId }` (all three keys
+ required, with `null` for unset values). The Host checks that the session is
+ a local, non-scheduled Agent session matching these values under the same
+ lock as the write. A mismatch is `CONFLICT`; guarded requests cannot also
+ update its mode, permissions, thinking level, or fast mode.
- `session.moveProject({ sessionId, projectPath })` moves an idle session to a
project and returns `{ session }` carrying the canonical project path. It
upserts the project row and updates only `sessions.project_id` and
diff --git a/docs/spec/06-delivery/e2e/live-and-remote.md b/docs/spec/06-delivery/e2e/live-and-remote.md
index 2e9a72274..6ea59462c 100644
--- a/docs/spec/06-delivery/e2e/live-and-remote.md
+++ b/docs/spec/06-delivery/e2e/live-and-remote.md
@@ -801,13 +801,16 @@ user's running instance.
### E2E-271: Create and continue the same session on phone and desktop
- **Preconditions:** Desktop is viewing A. The phone is paired. A usable
- fixture model is configured. B has an existing chat with paged history.
+ fixture provider has two saved chat models. B has a chat with paged history.
- **Steps:** Double-tap New session in B, send text, stream a reply, then continue
the same session on Desktop. Queue a second message while busy and cancel it;
interrupt the named active turn. Reopen the older B chat and load older pages.
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.
+ In a new B chat, type a draft, search for and select the other configured
+ model on the phone, and send. Retry during a running or queued turn and
+ after a competing Desktop model change.
From idle, send two different prompts simultaneously from Desktop and the
phone, first without queuing and then with explicit queue admission.
- **Expected:** The initial double-tap/send yields one session and one user
@@ -818,6 +821,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.
+ The selected model is used for the next turn and is visible on Desktop
+ without changing its active conversation or default model. Draft text
+ survives the switch. Running work and a newer model choice are not overwritten.
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.
@@ -862,6 +868,9 @@ user's running instance.
and an SSH-backed project. Use a controlled clock and a second interface.
- **Steps:** Exercise catalog, histories, commands and SSE. Check wrong
Origin/Host, missing CSRF, the device cap and rejected admin/owner operations.
+ Check that an unpaired device cannot list models, and that a paired device
+ cannot select an unconfigured model or alter mode or permissions via the
+ model endpoint. Check that the picker exposes no credentials or endpoints.
Remove one device while a temporary history request and stream are in flight;
sign out on the other, restart Desktop and try the old cookies. Re-pair and
advance the clock to the pairing expiry; change the desktop address. Inspect
diff --git a/packages/shared/src/lan-webui.ts b/packages/shared/src/lan-webui.ts
index a77ff885b..d0a4a7627 100644
--- a/packages/shared/src/lan-webui.ts
+++ b/packages/shared/src/lan-webui.ts
@@ -47,6 +47,22 @@ export interface LanConversation {
waiting: "approval" | "input" | null;
queue: Array<{ id: string; text: string }>;
modelLabel: string | null;
+ /** Whether the session is eligible for model changes when idle. */
+ canSelectModel?: boolean;
+}
+export interface LanModelRef {
+ providerId: string;
+ modelId: string;
+}
+/** An intentionally narrow projection of a configured chat model. */
+export interface LanModelOption extends LanModelRef {
+ label: string;
+ providerLabel: string;
+}
+export interface LanModelCatalog {
+ items: LanModelOption[];
+ selected: LanModelRef | null;
+ revision: string;
}
export interface LanDevice {
id: string;
diff --git a/packages/shared/src/model-catalog.ts b/packages/shared/src/model-catalog.ts
index 6968e49c5..fcb04d3b0 100644
--- a/packages/shared/src/model-catalog.ts
+++ b/packages/shared/src/model-catalog.ts
@@ -11,6 +11,8 @@
* tests share one implementation instead of re-deriving these rules per surface.
*/
+import { isImageOnlyChatModel, type ImageGenerationBindings } from "./image-generation.js";
+import { modelWireIdsEqual } from "./types/models.js";
import { publishedThinkingLevels } from "./thinking-levels.js";
import type {
ModelLimitSource,
@@ -418,3 +420,26 @@ export function formatModelPrice(cost?: ModelInfo["cost"]): string {
: `$${value < 1 ? value.toFixed(2) : String(value)}`;
return `${price(input)} / ${price(output)}`;
}
+
+/** The Composer only offers enabled providers that are ready to run. */
+export function isChatProviderReady(provider: { enabled?: boolean; hasSecret?: boolean; authKind?: string }): boolean {
+ return provider.enabled === true && (provider.hasSecret === true || provider.authKind === "none");
+}
+
+/** Discovery can filter or decorate a configured model; it never adds one. */
+export function configuredChatModels(
+ provider: { id: string; models?: readonly ModelBinding[]; defaultModelId?: string },
+ discovered: readonly ModelInfo[] = [],
+ imageGeneration?: ImageGenerationBindings | null,
+) {
+ const ids = (provider.models ?? []).map(({ id }) => id.trim()).filter(Boolean);
+ const legacyId = provider.defaultModelId?.trim();
+ return [...new Set(ids.length ? ids : legacyId ? [legacyId] : [])].flatMap((modelId) => {
+ const matches = (model: ModelInfo) => modelWireIdsEqual(model.modelId, modelId);
+ const metadata = discovered.find(matches);
+ if (isImageOnlyChatModel(imageGeneration, provider.id, modelId, metadata) ||
+ discovered.some((model) => matches(model) && model.discoveryState === "unlisted")) return [];
+ const binding = provider.models?.find(({ id }) => modelWireIdsEqual(id, modelId));
+ return [{ modelId, metadata, binding }];
+ });
+}