A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(chat): switch the model from the chat
Alan Buscagliad0b63ce6367e
diff --git a/docs/design.md b/docs/design.mdindex e2a53f9..7975aad 100644--- a/docs/design.md+++ b/docs/design.md@@ -199,6 +199,14 @@ The user can send files to the assistant (never the other way, L91).- Display: the block is stored with the message in the session file, so `user_message`, `history`, the queue, and titles show the user's own text, and `attachments: {name, size, mime}[]` become chips. A plain `send` is unchanged.- UI: a paper-clip button, drag and drop onto the chat, and pasted images add chips (name, size, ✕). The app checks the limits first and explains a refusal on the chip. Files upload on send with `XMLHttpRequest`, for progress, and an upload error stays on its chip with the message kept. In the desktop panel, HTML5 drops need the window's native drag-and-drop handler off (`disable_drag_drop_handler()` on the panel's `WebviewWindowBuilder`).+### Model picker (S32)++The user changes the main assistant's model from the chat, in the panel and the web UI.++- Messages: `models_list` answers `models {current?, next?, groups, profiles, activeProfile?}`. `groups` are the engine's `get_available_models` (only accounts with a working credential), grouped by provider and named like the Accounts screen; each model carries only `{provider, id, name, images, thinkingLevels?}` (`toModelChoices`, never endpoints, headers, keys, or costs). `thinkingLevels` mirrors the engine's `getSupportedThinkingLevels`: none for a model that does not think, and `xhigh`/`max` only when the model maps them. `profiles` are the saved profiles with their main-assistant route, as quick picks that send `profile_apply`.+- `model_set {provider, id, thinking?}`: a model outside the available list answers `error model_unavailable`, a level the model does not support `error thinking_unavailable`, and nothing changes. Otherwise the daemon saves it as the default (`settings.json` `defaultProvider`/`defaultModel`, and `defaultThinkingLevel` only when given, under the engine's settings lock), because the engine's RPC `set_model` does not persist, then switches live through the same `LiveModelSwitch` as profile apply. During a reply the switch waits for the run to settle (never an abort), and `models.next` says so. Every window gets the new `models`; after the switch the connectors list is sent again so the Computer image note follows `supervisor.modelImages`, as do images on the next attachment. Applying a profile also refreshes `models`.+- UI (`ModelPicker.tsx`): a pill chip above the composer with the model name; it opens a popover with a search box (`aria-activedescendant`), a listbox grouped by account plus a Profiles group, and a Thinking select only when the current model thinks (a new model keeps the level when it supports it). Arrow keys move, Enter picks, Esc closes and returns focus to the chip; the popover calls `preventDefault`, so App.tsx's Esc (leave full screen, then hide the panel) does not run. The picker's errors show inline in the popover, not as notices.+## 5. White-label layer- **Identity**: `--append-system-prompt` with `identity.md`: the assistant is "Gentle Dot", a personal assistant; it must not mention Gentle Shell, Pi, el Gentleman, ODD, or Engram by name, and describes them as "my workflow" and "my memory" when needed. It keeps every behavior.diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 1b403dc..f17e234 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -6,6 +6,8 @@ import {type Features,isThinkingLevel,type MessageQueue,+ type ModelGroup,+ type ModelRef,parseQueue,type RoleRoute,type ServerPayload,@@ -27,6 +29,8 @@ import {ProfileError,type ProfileStore,type SwitchOutcome,+ splitModel,+ toModelChoices,toModelOptions,} from "./profiles.ts";import { DEFAULT_ROTATION, type RotationLimits, SessionRotator } from "./rotation.ts";@@ -360,6 +364,12 @@ export class DotBridge {case "profiles_list":await this.sendProfiles(client);return;+ case "models_list":+ this.deliver(client, await this.modelsPayload());+ return;+ case "model_set":+ await this.setModel(client, message);+ return;case "connectors_list":this.deliver(client, { type: "connectors", connectors: this.requireConnectors().list() });return;@@ -687,6 +697,113 @@ export class DotBridge {private async applyProfile(name: string): Promise<void> {const orchestrator = await this.requireProfiles().apply(name);if (orchestrator) this.reportSwitch(await this.liveSwitch.switchTo(orchestrator));+ // The chat's model picker follows the profile.+ this.broadcastModels();+ }++ /**+ * The model picker's choice (S32): only a model of a connected account, and a thinking level+ * it supports. It is saved like a profile's model and switched live; during a reply the switch+ * waits for the next message instead of stopping the reply.+ */+ private async setModel(client: BridgeClient, message: Extract<ClientMessage, { type: "model_set" }>) {+ const available = await this.supervisor.request({ type: "get_available_models" });+ const model = toModelChoices(available.data).find(+ (m) => m.provider === message.provider && m.id === message.id,+ );+ if (!model) {+ this.deliver(client, {+ type: "error",+ code: "model_unavailable",+ message: "That model is not available. Connect its account in Accounts first.",+ });+ return;+ }+ if (message.thinking && !model.thinkingLevels?.includes(message.thinking)) {+ this.deliver(client, {+ type: "error",+ code: "thinking_unavailable",+ message: "That model does not support that thinking level.",+ });+ return;+ }+ const route: RoleRoute = { model: `${model.provider}/${model.id}` };+ if (message.thinking) route.thinking = message.thinking;+ await this.options.profiles?.setDefaultModel(route);+ const outcome = await this.liveSwitch.switchTo(route);+ if (outcome === "failed") {+ this.deliver(client, {+ type: "error",+ code: "model_switch_failed",+ message: "That model could not be selected. Try another one.",+ });+ }+ if (outcome === "switched") this.afterModelSwitch();+ else this.broadcastModels();+ }++ /** The current model, the connected accounts' models by account, and the profiles as quick picks. */+ private async modelsPayload(): Promise<Extract<ServerPayload, { type: "models" }>> {+ const [available, running, accounts] = await Promise.all([+ this.supervisor.request({ type: "get_available_models" }),+ this.runningModel(),+ this.accountNames(),+ ]);+ const choices = toModelChoices(available.data);+ const groups: ModelGroup[] = [];+ for (const model of choices) {+ let group = groups.find((g) => g.provider === model.provider);+ if (!group) {+ const name = accounts.get(model.provider) ?? model.provider;+ group = { provider: model.provider, name, models: [] };+ groups.push(group);+ }+ group.models.push(model);+ }+ const ref = (provider: string, id: string, thinking?: unknown): ModelRef => {+ const choice = choices.find((m) => m.provider === provider && m.id === id);+ const found: ModelRef = { provider, id, name: choice?.name ?? id };+ if (isThinkingLevel(thinking) && choice?.thinkingLevels) found.thinking = thinking;+ return found;+ };+ const waiting = this.liveSwitch.waiting;+ const target = waiting?.model ? splitModel(waiting.model) : undefined;+ const { profiles, active } = this.savedProfiles();+ return {+ type: "models",+ ...(running ? { current: ref(running.provider, running.id, running.thinking) } : {}),+ ...(target ? { next: ref(target.provider, target.modelId, waiting?.thinking) } : {}),+ groups,+ profiles: profiles.map(({ name, roles }) => ({ name, ...roles.orchestrator })),+ ...(active ? { activeProfile: active } : {}),+ };+ }++ private savedProfiles(): ReturnType<ProfileStore["list"]> {+ try {+ return this.options.profiles?.list() ?? { profiles: [] };+ } catch {+ return { profiles: [] };+ }+ }++ /** Account names by provider id, as the Accounts screen shows them. */+ private async accountNames(): Promise<Map<string, string>> {+ const providers = await (this.options.auth?.providers() ?? Promise.resolve([])).catch(() => []);+ return new Map(providers.map((p) => [p.id, presentText(p.name)]));+ }++ private broadcastModels(): void {+ void this.modelsPayload()+ .then((payload) => this.broadcast(payload))+ .catch((error: Error) => this.log(`could not list models: ${error.message}`));+ }++ /** A new running model: the picker, and the connectors' image note (S24.5), follow it. */+ private afterModelSwitch(): void {+ this.broadcastModels();+ const connectors = this.options.connectors;+ if (connectors) this.broadcast({ type: "connectors", connectors: connectors.list() });}private reportSwitch(outcome: SwitchOutcome): void {@@ -701,12 +818,18 @@ export class DotBridge {/** The main assistant's model and thinking level in the running conversation. */private async runningRoute(): Promise<RoleRoute | undefined> {+ const running = await this.runningModel();+ if (!running) return undefined;+ const route: RoleRoute = { model: `${running.provider}/${running.id}` };+ if (isThinkingLevel(running.thinking)) route.thinking = running.thinking;+ return route;+ }++ private async runningModel(): Promise<{ provider: string; id: string; thinking?: unknown } | undefined> {const response = await this.supervisor.request({ type: "get_state" });const state = response.data as { model?: { provider?: unknown; id?: unknown }; thinkingLevel?: unknown };if (typeof state?.model?.provider !== "string" || typeof state.model.id !== "string") return undefined;- const route: RoleRoute = { model: `${state.model.provider}/${state.model.id}` };- if (isThinkingLevel(state.thinkingLevel)) route.thinking = state.thinkingLevel;- return route;+ return { provider: state.model.provider, id: state.model.id, thinking: state.thinkingLevel };}/** New credentials: refresh every window, and restart the agent once it is idle so it sees new models. */@@ -745,7 +868,10 @@ export class DotBridge {/** A profile applied while the assistant was busy switches the model now. */private settleModelSwitch(): void {- void this.liveSwitch.settle().then((outcome) => this.reportSwitch(outcome));+ void this.liveSwitch.settle().then((outcome) => {+ this.reportSwitch(outcome);+ if (outcome === "switched") this.afterModelSwitch();+ });}private afterConversationChange(page: HistoryPage = { messages: [], hasEarlier: false }): void {diff --git a/packages/daemon/src/profiles.ts b/packages/daemon/src/profiles.tsindex 888c8c9..4da6162 100644--- a/packages/daemon/src/profiles.ts+++ b/packages/daemon/src/profiles.ts@@ -20,12 +20,15 @@ import {type AuthProvider,isThinkingLevel,isValidProfileName,+ type ModelChoice,type ModelOption,type Profile,type ProfileRole,type ProfileRoles,parseProfileRoles,type RoleRoute,+ THINKING_LEVELS,+ type ThinkingLevel,} from "@gentle-dot/protocol";import { presentText } from "./white-label.ts";@@ -231,7 +234,7 @@ async function withFileLock<T>(path: string, fn: () => T): Promise<T> {}}-function splitModel(model: string): { provider: string; modelId: string } | undefined {+export function splitModel(model: string): { provider: string; modelId: string } | undefined {const at = model.indexOf("/");if (at <= 0 || at === model.length - 1) return undefined;return { provider: model.slice(0, at), modelId: model.slice(at + 1) };@@ -388,6 +391,14 @@ export class ProfileStore {});}+ /**+ * Makes `route` the main assistant's saved default (settings.json), so a model chosen in the+ * chat outlasts a restart; a missing thinking level keeps the saved one.+ */+ setDefaultModel(route: RoleRoute): Promise<void> {+ return this.enqueue(() => this.writeOrchestrator(route, false));+ }+/** True when the other setup has at least one profile to bring over. */importable(): boolean {if (this.options.importPath === this.storePath) return false;@@ -442,7 +453,8 @@ export class ProfileStore {writeFileAtomic(this.subagentsPath, jsonText(next));}- private writeOrchestrator(route: RoleRoute): Promise<void> {+ /** Without `clearThinking`, a route with no thinking level leaves the saved one as it is. */+ private writeOrchestrator(route: RoleRoute, clearThinking = true): Promise<void> {const target = route.model ? splitModel(route.model) : undefined;if (!target) throw new ProfileError("settings_invalid");return withFileLock(this.settingsPath, () => {@@ -453,7 +465,7 @@ export class ProfileStore {defaultModel: target.modelId,};if (route.thinking) next.defaultThinkingLevel = route.thinking;- else delete next.defaultThinkingLevel;+ else if (clearThinking) delete next.defaultThinkingLevel;writeFileAtomic(this.settingsPath, jsonText(next));});}@@ -656,6 +668,30 @@ export function toModelOptions(data: unknown): ModelOption[] {});}+/** Levels past `high` only when the model maps them, as the engine's `getSupportedThinkingLevels` does. */+function thinkingLevelsOf(model: Record<string, unknown>): ThinkingLevel[] | undefined {+ if (model.reasoning !== true) return undefined;+ const map = isRecord(model.thinkingLevelMap) ? model.thinkingLevelMap : {};+ return THINKING_LEVELS.filter((level) => {+ if (map[level] === null) return false;+ return level === "xhigh" || level === "max" ? map[level] !== undefined : true;+ });+}++/** Models from `get_available_models` for the chat's model picker: only names and capabilities. */+export function toModelChoices(data: unknown): ModelChoice[] {+ const models = isRecord(data) && Array.isArray(data.models) ? data.models : [];+ return models.flatMap((raw): ModelChoice[] => {+ if (!isRecord(raw) || typeof raw.provider !== "string" || typeof raw.id !== "string") return [];+ const name = presentText(typeof raw.name === "string" && raw.name ? raw.name : raw.id);+ const images = Array.isArray(raw.input) && raw.input.includes("image");+ const choice: ModelChoice = { provider: raw.provider, id: raw.id, name, images };+ const levels = thinkingLevelsOf(raw);+ if (levels) choice.thinkingLevels = levels;+ return [choice];+ });+}+/** The part of the supervisor the live switch needs. */export interface LiveAgent {busy: boolean;@@ -680,6 +716,11 @@ export class LiveModelSwitch {this.log = log;}+ /** The switch waiting for the assistant to finish its reply. */+ get waiting(): RoleRoute | undefined {+ return this.pending;+ }+switchTo(route: RoleRoute): Promise<SwitchOutcome> {this.pending = route;return this.settle("deferred");diff --git a/packages/daemon/test/models-gateway.test.ts b/packages/daemon/test/models-gateway.test.tsnew file mode 100644index 0000000..aae9fee--- /dev/null+++ b/packages/daemon/test/models-gateway.test.ts@@ -0,0 +1,252 @@+import { existsSync, readFileSync } from "node:fs";+import { request } from "node:http";+import { join } from "node:path";+import type { ServerMessage, UploadedFile } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 1, 2, 3]);++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++const lines = (file: string) =>+ existsSync(file)+ ? readFileSync(file, "utf8")+ .split("\n")+ .filter(Boolean)+ .map((line) => JSON.parse(line) as Record<string, unknown>)+ : [];++async function setup() {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const commandsFile = join(dataDir, "commands.jsonl");+ const promptsFile = join(dataDir, "prompts.jsonl");+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentEnv: {+ ...process.env,+ FAKE_AGENT_COMMANDS_FILE: commandsFile,+ FAKE_AGENT_PROMPTS_FILE: promptsFile,+ },+ agentHome,+ profilesImportPath: join(tempDir(), "profiles.json"),+ backoffMs: [50],+ authRuntime: async () => fakeAuthRuntime().runtime,+ });+ daemons.push(d);+ const upload = (name: string, body: Buffer) =>+ new Promise<UploadedFile>((resolve, reject) => {+ const req = request(+ {+ host: "127.0.0.1",+ port: d.port,+ path: "/upload",+ method: "POST",+ headers: { Authorization: `Bearer ${d.token}`, "X-File-Name": encodeURIComponent(name) },+ },+ (res) => {+ let text = "";+ res.on("data", (chunk) => {+ text += chunk;+ });+ res.on("end", () =>+ res.statusCode === 200 ? resolve(JSON.parse(text) as UploadedFile) : reject(new Error(text)),+ );+ },+ );+ req.on("error", reject);+ req.end(body);+ });+ return {+ d,+ upload,+ commands: () => lines(commandsFile),+ prompts: () => lines(promptsFile),+ settings: () =>+ JSON.parse(readFileSync(join(agentHome, "settings.json"), "utf8")) as Record<string, unknown>,+ };+}++async function connect(d: DotDaemon) {+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ const send = (m: object) => ws.send(JSON.stringify(m));+ function find<T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ ) {+ return waitFor(() =>+ messages.find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+ }+ return { messages, send, find };+}++describe("the in-chat model picker (S32)", () => {+ it("lists the current model and thinking, the models by account, and profiles as quick picks, without secrets", async () => {+ const { d } = await setup();+ const client = await connect(d);+ client.send({+ type: "profile_save",+ name: "quick",+ roles: { orchestrator: { model: "fake/fake-fast" }, "gentle-ai-worker": { model: "other/big" } },+ });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "models_list" });+ const list = await client.find("models");+ expect(list.current).toEqual({+ provider: "fake",+ id: "fake-model",+ name: "Fake Model",+ thinking: "medium",+ });+ expect(list.next).toBeUndefined();+ const levels = ["off", "minimal", "low", "medium", "high"];+ expect(list.groups).toEqual([+ {+ provider: "fake",+ name: "fake",+ models: [+ { provider: "fake", id: "fake-model", name: "Fake Model", images: true, thinkingLevels: levels },+ { provider: "fake", id: "fake-fast", name: "Fake Fast", images: false },+ ],+ },+ {+ provider: "other",+ name: "other",+ models: [{ provider: "other", id: "big", name: "Other Big", images: false, thinkingLevels: levels }],+ },+ ]);+ expect(list.profiles).toEqual([{ name: "quick", model: "fake/fake-fast" }]);+ const raw = JSON.stringify(client.messages);+ for (const secret of ["fake-secret-header", "internal.fake.example", "baseUrl", "headers", "cost"])+ expect(raw).not.toContain(secret);+ });++ it("switches the running model and thinking live, tells every window, and keeps the choice", async () => {+ const { d, commands, settings } = await setup();+ const a = await connect(d);+ const b = await connect(d);+ a.send({ type: "model_set", provider: "other", id: "big", thinking: "high" });+ const switched = await b.find("models", (m) => m.current?.id === "big");+ expect(switched.current).toEqual({ provider: "other", id: "big", name: "Other Big", thinking: "high" });+ expect(commands()).toEqual([+ { type: "set_model", provider: "other", modelId: "big", busy: false },+ { type: "set_thinking_level", level: "high", busy: false },+ ]);+ expect(settings()).toEqual({+ defaultProvider: "other",+ defaultModel: "big",+ defaultThinkingLevel: "high",+ });+ // A window that connects now shows the chosen model.+ const c = await connect(d);+ expect(c.messages.find((m) => m.type === "ready")).toMatchObject({ model: "Other Big" });+ expect(a.messages.some((m) => m.type === "error")).toBe(false);+ });++ it("changes only the model when no thinking level is given, keeping the saved thinking default", async () => {+ const { d, commands, settings } = await setup();+ const client = await connect(d);+ client.send({ type: "model_set", provider: "fake", id: "fake-model", thinking: "low" });+ await client.find("models", (m) => m.current?.thinking === "low");+ client.send({ type: "model_set", provider: "fake", id: "fake-fast" });+ await client.find("models", (m) => m.current?.id === "fake-fast");+ expect(commands().slice(2)).toEqual([+ { type: "set_model", provider: "fake", modelId: "fake-fast", busy: false },+ ]);+ expect(settings()).toEqual({+ defaultProvider: "fake",+ defaultModel: "fake-fast",+ defaultThinkingLevel: "low",+ });+ });++ it("applies a switch made during a reply to the next message, without stopping the reply", async () => {+ const { d, commands } = await setup();+ const client = await connect(d);+ client.send({ type: "send", text: "hang" });+ await client.find("agent_state", (m) => m.state === "thinking");+ client.send({ type: "model_set", provider: "other", id: "big" });+ const waiting = await client.find("models", (m) => m.next !== undefined);+ expect(waiting.current?.id).toBe("fake-model");+ expect(waiting.next).toEqual({ provider: "other", id: "big", name: "Other Big" });+ expect(commands()).toEqual([]);+ expect(client.messages.some((m) => m.type === "message_done")).toBe(false);+ client.send({ type: "abort" });+ const after = await client.find("models", (m) => m.current?.id === "big" && m.next === undefined);+ expect(after.current?.name).toBe("Other Big");+ expect(commands()).toEqual([{ type: "set_model", provider: "other", modelId: "big", busy: false }]);+ });++ it("refuses a model that is not available or a thinking level it does not support, inline and unchanged", async () => {+ const { d, commands } = await setup();+ const client = await connect(d);+ client.send({ type: "model_set", provider: "ghost", id: "none" });+ const missing = await client.find("error", (m) => m.code === "model_unavailable");+ expect(missing.message).toBe("That model is not available. Connect its account in Accounts first.");+ client.send({ type: "model_set", provider: "fake", id: "fake-model", thinking: "max" });+ const thinking = await client.find("error", (m) => m.code === "thinking_unavailable");+ expect(thinking.message).toBe("That model does not support that thinking level.");+ client.send({ type: "model_set", provider: "fake", id: "fake-fast", thinking: "high" });+ await client.find("error", (m) => m.code === "thinking_unavailable" && m !== thinking);+ expect(commands()).toEqual([]);+ expect(client.messages.some((m) => m.type === "models" && m.current?.id !== "fake-model")).toBe(false);+ });++ it("sends images only when the chosen model accepts them", async () => {+ const { d, upload, prompts } = await setup();+ const client = await connect(d);+ client.send({ type: "model_set", provider: "fake", id: "fake-fast" });+ await client.find("models", (m) => m.current?.id === "fake-fast");+ const shot = await upload("shot.png", PNG);+ client.send({ type: "send", text: "look", attachments: [{ uploadId: shot.uploadId, name: shot.name }] });+ await client.find("message_done");+ const [prompt] = prompts();+ expect(prompt?.images).toBeUndefined();+ expect(String(prompt?.message)).toContain("shot.png");+ });++ it("still applies a profile exactly as before (regression)", async () => {+ const { d, commands, settings } = await setup();+ const client = await connect(d);+ const roles = { orchestrator: { model: "fake/fake-fast", thinking: "low" } };+ client.send({ type: "profile_save", name: "quick", roles });+ await client.find("profiles", (m) => m.profiles.length === 1);+ client.send({ type: "profile_apply", name: "quick" });+ await client.find("profiles", (m) => m.active === "quick");+ await waitFor(() => commands().length === 2);+ expect(commands()).toEqual([+ { type: "set_model", provider: "fake", modelId: "fake-fast", busy: false },+ { type: "set_thinking_level", level: "low", busy: false },+ ]);+ expect(settings()).toEqual({+ defaultProvider: "fake",+ defaultModel: "fake-fast",+ defaultThinkingLevel: "low",+ });+ // The picker follows the profile.+ const picked = await client.find("models", (m) => m.current?.id === "fake-fast");+ expect(picked.activeProfile).toBe("quick");+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex f5a684c..aceffd1 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -251,10 +251,46 @@ export interface ModelOption {reasoning: boolean;}+/** A model in the chat's model picker (S32); never carries endpoints, headers, keys, or costs. */+export interface ModelChoice {+ provider: string;+ id: string;+ name: string;+ /** It accepts images. */+ images: boolean;+ /** The thinking levels it supports; absent when it does not think. */+ thinkingLevels?: ThinkingLevel[];+}++/** The models of one connected account. */+export interface ModelGroup {+ provider: string;+ /** The account's name, for example "OpenAI". */+ name: string;+ models: ModelChoice[];+}++/** The main assistant's model; `thinking` only when the model thinks. */+export interface ModelRef {+ provider: string;+ id: string;+ name: string;+ thinking?: ThinkingLevel;+}++/** A saved profile offered as a quick pick, with the main assistant's route. */+export interface ProfilePick {+ name: string;+ /** `provider/model-id`. */+ model?: string;+ thinking?: ThinkingLevel;+}+const PROFILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;const RESERVED_NAMES = new Set(["__proto__", "constructor", "prototype"]);const ROLE_ID = /^[A-Za-z0-9._:@/+%-]{1,128}$/;const MODEL_ID = /^[A-Za-z0-9._~:@/+%-]{1,256}$/;+const PROVIDER_ID = /^[A-Za-z0-9._~:@+%-]{1,128}$/;const MAX_ROLES = 200;/** Profile names follow the engine's rule: 1-64 letters, numbers, `.`, `_`, `-`, starting with a letter or number. */@@ -312,6 +348,10 @@ export type ClientMessage =| { type: "profile_apply"; name: string }| { type: "profile_import" }| { type: "profile_save_current"; name: string }+ /** The chat's model picker (S32): the current model, the connected accounts' models, and the profiles. */+ | { type: "models_list" }+ /** Switches the main assistant's model; during a reply it applies to the next message. */+ | { type: "model_set"; provider: string; id: string; thinking?: ThinkingLevel }| { type: "connectors_list" }| {type:@@ -387,6 +427,15 @@ export type ServerPayload =open?: boolean;}| { type: "profiles_imported"; imported: { from: string; to: string }[]; missingProviders: string[] }+ | {+ type: "models";+ current?: ModelRef;+ /** A switch chosen during a reply, waiting for the next message. */+ next?: ModelRef;+ groups: ModelGroup[];+ profiles: ProfilePick[];+ activeProfile?: string;+ }/** Connector sign-ins reuse `auth_event`, `auth_prompt`, and `auth_done`, with flow ids starting `connector-`. */| { type: "connectors"; connectors: ConnectorInfo[]; open?: boolean }| { type: "connector_draft"; draft: ConnectorDraft }@@ -530,6 +579,18 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {case "profile_apply":case "profile_save_current":return isValidProfileName(m.name) ? { type: m.type, name: m.name } : undefined;+ case "model_set": {+ if (!isString(m.provider) || !PROVIDER_ID.test(m.provider)) return undefined;+ if (!isString(m.id) || !MODEL_ID.test(m.id)) return undefined;+ if (!isOptional(m.thinking, isThinkingLevel)) return undefined;+ const set: Extract<ClientMessage, { type: "model_set" }> = {+ type: "model_set",+ provider: m.provider,+ id: m.id,+ };+ if (m.thinking !== undefined) set.thinking = m.thinking as ThinkingLevel;+ return set;+ }case "connector_connect":case "connector_signin":case "connector_setup":@@ -567,6 +628,7 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {case "connectors_list":case "connectors_scan":case "profiles_list":+ case "models_list":case "profile_import":case "abort":case "new_conversation":diff --git a/packages/protocol/test/models.test.ts b/packages/protocol/test/models.test.tsnew file mode 100644index 0000000..aff1e03--- /dev/null+++ b/packages/protocol/test/models.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from "vitest";+import { parseClientMessage } from "../src/index.ts";++const parse = (value: object) => parseClientMessage(JSON.stringify(value));++describe("model picker messages (S32)", () => {+ it("accepts listing the models and choosing one, with an optional thinking level", () => {+ expect(parse({ type: "models_list" })).toEqual({ type: "models_list" });+ expect(parse({ type: "model_set", provider: "openai", id: "gpt-5", extra: 1 })).toEqual({+ type: "model_set",+ provider: "openai",+ id: "gpt-5",+ });+ expect(+ parse({ type: "model_set", provider: "openrouter", id: "anthropic/claude", thinking: "high" }),+ ).toEqual({ type: "model_set", provider: "openrouter", id: "anthropic/claude", thinking: "high" });+ });++ it("refuses a missing or malformed provider, model, or thinking level", () => {+ expect(parse({ type: "model_set", id: "gpt-5" })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "openai" })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "open/ai", id: "gpt-5" })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "openai", id: "" })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "openai", id: "a b" })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "openai", id: "x".repeat(257) })).toBeUndefined();+ expect(parse({ type: "model_set", provider: "openai", id: "gpt-5", thinking: "turbo" })).toBeUndefined();+ });+});diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex f054097..6a22208 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -28,6 +28,7 @@ import {SpeakerOffIcon,} from "./icons.tsx";import { MessageList } from "./MessageList.tsx";+import { ModelPicker } from "./ModelPicker.tsx";import { ProfilesPanel } from "./ProfilesPanel.tsx";import { newRequestId, type Send } from "./types.ts";@@ -348,6 +349,13 @@ export function ChatSurface({</div>) : null}+ <ModelPicker+ models={state.models}+ send={send}+ dispatch={dispatch}+ disabled={!ready}+ {...(state.model ? { model: state.model } : {})}+ /><Composerbusy={isBusy(state.agentState)}disabled={!ready}diff --git a/packages/ui/src/components/ModelPicker.tsx b/packages/ui/src/components/ModelPicker.tsxnew file mode 100644index 0000000..8181b70--- /dev/null+++ b/packages/ui/src/components/ModelPicker.tsx@@ -0,0 +1,239 @@+import type { ModelChoice, ProfilePick, ThinkingLevel } from "@gentle-dot/protocol";+import { type KeyboardEvent, useEffect, useId, useRef, useState } from "react";+import type { DotAction, ModelsState } from "../store.ts";+import type { Send } from "./types.ts";++interface ModelPickerProps {+ /** The running model's name, as `ready` reports it, until the picker's list arrives. */+ model?: string;+ models: ModelsState;+ send: Send;+ dispatch: (action: DotAction) => void;+ disabled?: boolean;+}++type Item =+ | { kind: "model"; key: string; group: string; model: ModelChoice }+ | { kind: "profile"; key: string; pick: ProfilePick };++/** The models and profiles that match the search, in the order the list shows them. */+function visibleItems(models: ModelsState, query: string): Item[] {+ const q = query.trim().toLowerCase();+ const matches = (...texts: string[]) => q === "" || texts.some((t) => t.toLowerCase().includes(q));+ const items: Item[] = [];+ for (const group of models.groups ?? []) {+ for (const model of group.models) {+ if (matches(model.name, model.id, group.name))+ items.push({ kind: "model", key: `${model.provider}/${model.id}`, group: group.name, model });+ }+ }+ for (const pick of models.profiles) {+ if (matches(pick.name)) items.push({ kind: "profile", key: `profile:${pick.name}`, pick });+ }+ return items;+}++/**+ * The chat's model picker (S32): a chip with the running model that opens a searchable list of+ * the connected accounts' models and the saved profiles. Arrow keys move, Enter picks, and Esc+ * closes it without reaching the panel's own Esc (App.tsx).+ */+export function ModelPicker({ model, models, send, dispatch, disabled }: ModelPickerProps) {+ const [open, setOpen] = useState(false);+ const [query, setQuery] = useState("");+ const [active, setActive] = useState(0);+ const chip = useRef<HTMLButtonElement>(null);+ const root = useRef<HTMLDivElement>(null);+ const id = useId();+ const items = open ? visibleItems(models, query) : [];+ const current = models.current;+ const currentKey = current ? `${current.provider}/${current.id}` : undefined;+ const shown = models.next?.name ?? current?.name ?? model;+ const thinking = current+ ? models.groups+ ?.flatMap((g) => g.models)+ .find((m) => m.provider === current.provider && m.id === current.id)?.thinkingLevels+ : undefined;++ // The highlight starts on the running model once the list arrives, not on every update.+ const loaded = models.groups !== undefined;+ // biome-ignore lint/correctness/useExhaustiveDependencies: only when the picker opens or its list arrives+ useEffect(() => {+ if (!open || !loaded) return;+ const index = visibleItems(models, "").findIndex((item) => item.key === currentKey);+ setActive(Math.max(index, 0));+ }, [open, loaded]);++ useEffect(() => {+ if (!open) return;+ const onPointer = (event: PointerEvent) => {+ if (!root.current?.contains(event.target as Node)) setOpen(false);+ };+ document.addEventListener("pointerdown", onPointer);+ return () => document.removeEventListener("pointerdown", onPointer);+ }, [open]);++ const close = () => {+ setOpen(false);+ chip.current?.focus();+ };++ const toggle = () => {+ if (open) {+ setOpen(false);+ return;+ }+ setQuery("");+ dispatch({ type: "models_opened" });+ send({ type: "models_list" });+ setOpen(true);+ };++ const choose = (item: Item | undefined) => {+ if (!item) return;+ if (item.kind === "profile") send({ type: "profile_apply", name: item.pick.name });+ else {+ const { provider, id: modelId, thinkingLevels } = item.model;+ // The thinking level carries over when the new model supports it.+ const level = current?.thinking;+ const keep = level !== undefined && thinkingLevels?.includes(level);+ send({ type: "model_set", provider, id: modelId, ...(keep ? { thinking: level } : {}) });+ }+ close();+ };++ const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key === "Escape") {+ // Handled here, so the panel stays open (App.tsx checks defaultPrevented).+ event.preventDefault();+ close();+ } else if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ if (items.length === 0) return;+ const step = event.key === "ArrowDown" ? 1 : -1;+ setActive((index) => (Math.min(index, items.length - 1) + step + items.length) % items.length);+ } else if (event.key === "Enter" && event.target instanceof HTMLInputElement) {+ event.preventDefault();+ choose(items[Math.min(active, items.length - 1)]);+ }+ };++ const optionId = (index: number) => `${id}-option-${index}`;+ const highlighted = Math.min(active, items.length - 1);+ const groups = [...new Set(items.filter((i) => i.kind === "model").map((i) => i.group))];+ const profiles = items.filter((i) => i.kind === "profile");+ const renderOption = (item: Item) => {+ const index = items.indexOf(item);+ const isCurrent =+ item.kind === "model" ? item.key === currentKey : item.pick.name === models.activeProfile;+ return (+ // biome-ignore lint/a11y/useKeyWithClickEvents: the search box drives the keyboard (aria-activedescendant)+ <div+ key={item.key}+ id={optionId(index)}+ role="option"+ tabIndex={-1}+ aria-selected={index === highlighted}+ aria-current={isCurrent ? "true" : undefined}+ className="model-option"+ onPointerMove={() => setActive(index)}+ onClick={() => choose(item)}+ >+ <span className="model-option-name">{item.kind === "model" ? item.model.name : item.pick.name}</span>+ {item.kind === "profile" && item.pick.model ? (+ <span className="model-option-detail">{item.pick.model}</span>+ ) : null}+ {isCurrent ? <span className="model-option-detail">In use</span> : null}+ </div>+ );+ };+ const renderGroup = (label: string, members: Item[]) => (+ // biome-ignore lint/a11y/useSemanticElements: a listbox groups its options with role="group", not a fieldset+ <div key={label} role="group" aria-label={label} className="model-group">+ <p className="eyebrow" aria-hidden="true">+ {label}+ </p>+ {members.map(renderOption)}+ </div>+ );++ return (+ <div className="model-picker" ref={root}>+ <button+ ref={chip}+ type="button"+ className="model-chip"+ aria-label={`Model: ${shown ?? "not chosen"}`}+ title="Change the model"+ aria-haspopup="dialog"+ aria-expanded={open}+ disabled={disabled}+ onClick={toggle}+ >+ <span className="model-chip-name">{shown ?? "Choose a model"}</span>+ <span aria-hidden="true">▾</span>+ </button>+ {open ? (+ <div className="model-popover" role="dialog" aria-label="Choose a model" onKeyDown={onKeyDown}>+ <input+ type="search"+ className="model-search"+ aria-label="Search models"+ placeholder="Search models"+ aria-controls={`${id}-list`}+ aria-activedescendant={items.length > 0 ? optionId(highlighted) : undefined}+ // biome-ignore lint/a11y/noAutofocus: the popover opens for typing+ autoFocus+ value={query}+ onChange={(event) => {+ setQuery(event.target.value);+ setActive(0);+ }}+ />+ {models.error ? (+ <p className="model-error" role="alert">+ {models.error}+ </p>+ ) : null}+ {models.next ? (+ <p className="model-note">{models.next.name} is used from your next message.</p>+ ) : null}+ {!loaded ? <p className="model-note">Loading models…</p> : null}+ {loaded && items.length === 0 ? <p className="model-note">No models match.</p> : null}+ <div className="model-list" id={`${id}-list`} role="listbox" aria-label="Models">+ {groups.map((group) =>+ renderGroup(+ group,+ items.filter((i) => i.kind === "model" && i.group === group),+ ),+ )}+ {profiles.length > 0 ? renderGroup("Profiles", profiles) : null}+ </div>+ {current && thinking ? (+ <label className="model-thinking">+ <span>Thinking</span>+ <select+ aria-label="Thinking"+ value={current.thinking ?? ""}+ onChange={(event) =>+ send({+ type: "model_set",+ provider: current.provider,+ id: current.id,+ thinking: event.target.value as ThinkingLevel,+ })+ }+ >+ {thinking.map((level) => (+ <option key={level} value={level}>+ {level}+ </option>+ ))}+ </select>+ </label>+ ) : null}+ </div>+ ) : null}+ </div>+ );+}diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex f8b6ef3..5e00437 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -12,8 +12,11 @@ import type {Features,ImportCandidate,MessageQueue,+ ModelGroup,ModelOption,+ ModelRef,Profile,+ ProfilePick,ProfileRole,ServerMessage,VoiceCapability,@@ -62,6 +65,22 @@ export interface ConnectorsState {imports?: ImportCandidate[];}+/** The chat's model picker (S32). */+export interface ModelsState {+ current?: ModelRef;+ /** A switch chosen during a reply, waiting for the next message. */+ next?: ModelRef;+ /** Undefined until the first list arrives. */+ groups?: ModelGroup[];+ profiles: ProfilePick[];+ activeProfile?: string;+ /** Why the last choice did not work, shown in the picker. */+ error?: string;+}++/** Errors about the picker's choice show in the picker, not as a notice. */+const MODEL_ERRORS = new Set(["model_unavailable", "thinking_unavailable", "model_switch_failed"]);+/** The daemon's answer to a voice request, matched by `requestId`. */export type VoiceReply = Extract<ServerMessage,@@ -108,6 +127,7 @@ export interface DotState {auth: AuthState;profiles: ProfilesState;connectors: ConnectorsState;+ models: ModelsState;/** What the daemon can do with voice (an OpenAI API key). */voice: VoiceCapability;/** The latest answers to voice requests, newest last. */@@ -123,6 +143,7 @@ export type DotAction =| { type: "connectors"; open: boolean }| { type: "connector_started"; connectorId: string }| { type: "connector_imports_closed" }+ | { type: "models_opened" }| { type: "auth_started"; providerId: string };export const initialState: DotState = {@@ -139,6 +160,7 @@ export const initialState: DotState = {auth: { open: false },profiles: { open: false, roles: [], models: [], importable: false },connectors: { open: false },+ models: { profiles: [] },voice: { transcribe: false, speak: false },voiceReplies: [],};@@ -178,6 +200,10 @@ export function reduce(state: DotState, action: DotAction): DotState {const { imports: _imports, ...rest } = state.connectors;return { ...state, connectors: rest };}+ case "models_opened": {+ const { error: _error, ...models } = state.models;+ return { ...state, models };+ }case "auth_started":return {...state,@@ -315,6 +341,10 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {const updated = { ...state, profiles: next };return open ? closeConnectors(openProfiles(updated, true), true) : updated;}+ case "models": {+ const { type: _type, seq: _seq, ...models } = message;+ return { ...state, models, model: models.current?.name ?? state.model };+ }case "profiles_imported":return {...state,@@ -349,6 +379,8 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {case "toast":return addNotice(state, message.level, message.message);case "error":+ if (MODEL_ERRORS.has(message.code))+ return { ...state, models: { ...state.models, error: message.message } };return addNotice(state, "error", message.message);}}diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssindex 334d1e7..ecd6d9f 100644--- a/packages/ui/src/styles.css+++ b/packages/ui/src/styles.css@@ -1660,3 +1660,139 @@ html[data-surface="glow"] body {outline: 2px dashed var(--accent-line);outline-offset: -6px;}++/* ---------- Model picker (S32) ---------- */++.model-picker {+ position: relative;+ z-index: 2;+ align-self: flex-start;+ margin: 0 12px 6px;+}++.model-chip {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ max-width: 260px;+ padding: 3px 10px;+ border: 1px solid var(--line);+ border-radius: var(--radius-pill);+ background: var(--surface-2);+ color: var(--muted);+ font: 600 12px / 18px var(--font-mono);+ letter-spacing: 0.04em;+}++.model-chip:hover:not(:disabled),+.model-chip[aria-expanded="true"] {+ border-color: var(--accent-line);+ color: var(--text);+}++.model-chip-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.model-popover {+ position: absolute;+ bottom: calc(100% + 6px);+ left: 0;+ display: flex;+ flex-direction: column;+ gap: 8px;+ width: min(340px, calc(100vw - 24px));+ max-height: min(420px, 70vh);+ padding: 10px;+ border: 1px solid var(--line);+ border-radius: var(--radius-md);+ background: var(--surface);+ box-shadow: 0 16px 40px rgba(0, 0, 0, 0.45);+}++.model-search {+ width: 100%;+ padding: 7px 10px;+ border: 1px solid var(--line);+ border-radius: var(--radius-sm);+ background: var(--bg);+ color: var(--text);+}++.model-search:focus {+ outline: none;+ border-color: var(--accent-line);+ box-shadow: 0 0 0 3px var(--accent-soft);+}++.model-list {+ flex: 1;+ overflow-y: auto;+}++.model-group {+ margin: 0 0 8px;+}++.model-list .eyebrow {+ padding: 4px 8px;+}++.model-option {+ display: flex;+ align-items: baseline;+ gap: 8px;+ padding: 6px 8px;+ border-radius: var(--radius-sm);+ cursor: pointer;+}++.model-option[aria-selected="true"] {+ background: var(--accent-soft);+}++.model-option[aria-current="true"] .model-option-name {+ color: var(--accent);+}++.model-option-detail {+ margin-left: auto;+ color: var(--muted);+ font-size: 12px;+}++.model-note,+.model-error {+ margin: 0;+ font-size: 13px;+ color: var(--muted);+}++.model-error {+ color: var(--red);+}++.model-thinking {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding-top: 8px;+ border-top: 1px solid var(--line);+ color: var(--muted);+ font-size: 13px;+}++.model-thinking select {+ padding: 4px 8px;+ border: 1px solid var(--line);+ border-radius: var(--radius-sm);+ background: var(--surface-2);+ color: var(--text);+}++.chat-fullscreen .model-picker {+ margin-inline: max(12px, calc((100% - var(--reading-width)) / 2));+}diff --git a/packages/ui/test/model-picker.test.tsx b/packages/ui/test/model-picker.test.tsxnew file mode 100644index 0000000..7887a63--- /dev/null+++ b/packages/ui/test/model-picker.test.tsx@@ -0,0 +1,168 @@+import type { ClientMessage, ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import { act, render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useReducer } from "react";+import { describe, expect, it, vi } from "vitest";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { type DotAction, type DotState, initialState, reduce } from "../src/store.ts";++const levels = ["off", "minimal", "low", "medium", "high"] as const;++const models: ServerPayload = {+ type: "models",+ current: { provider: "openai", id: "gpt-5", name: "GPT-5", thinking: "medium" },+ groups: [+ {+ provider: "openai",+ name: "OpenAI",+ models: [+ { provider: "openai", id: "gpt-5", name: "GPT-5", images: true, thinkingLevels: [...levels] },+ { provider: "openai", id: "gpt-4o-mini", name: "GPT-4o mini", images: true },+ ],+ },+ {+ provider: "nan",+ name: "NaN",+ models: [{ provider: "nan", id: "big", name: "NaN Big", images: false, thinkingLevels: [...levels] }],+ },+ ],+ profiles: [{ name: "daily", model: "nan/big" }],+};++const ready: DotState = {+ ...initialState,+ connection: "open",+ agentState: "idle",+ model: "GPT-5",+};++let dispatchServer: (payload: ServerPayload) => void = () => {};++function Harness({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {+ const [state, dispatch] = useReducer(reduce, initial);+ dispatchServer = (payload) =>+ act(() => dispatch({ type: "server", message: { ...payload, seq: 1 } as ServerMessage } as DotAction));+ return <ChatSurface variant="web" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;+}++async function openPicker(send = vi.fn(), initial = ready) {+ render(<Harness initial={initial} send={send} />);+ await userEvent.click(screen.getByRole("button", { name: "Model: GPT-5" }));+ dispatchServer(models);+ return { send, dialog: screen.getByRole("dialog", { name: "Choose a model" }) };+}++const list = () => screen.getByRole("listbox", { name: "Models" });+const option = (name: string) => within(list()).getByRole("option", { name: new RegExp(`^${name}`) });++describe("model picker (S32)", () => {+ it("shows the current model in a compact chip and opens a list grouped by account, with profiles", async () => {+ const { send, dialog } = await openPicker();+ expect(send).toHaveBeenCalledWith({ type: "models_list" });+ expect(screen.getByRole("button", { name: "Model: GPT-5" })).toHaveAttribute("aria-expanded", "true");+ expect(within(dialog).getByRole("searchbox", { name: "Search models" })).toHaveFocus();+ const groups = within(dialog).getAllByRole("group");+ expect(groups.map((g) => g.getAttribute("aria-label"))).toEqual(["OpenAI", "NaN", "Profiles"]);+ expect(within(groups[0] as HTMLElement).getAllByRole("option")).toHaveLength(2);+ expect(within(groups[2] as HTMLElement).getByRole("option", { name: /daily/ })).toBeInTheDocument();+ expect(option("GPT-5")).toHaveAttribute("aria-current", "true");+ });++ it("filters by model or account name as the user types", async () => {+ await openPicker();+ await userEvent.type(screen.getByRole("searchbox", { name: "Search models" }), "nan");+ expect(+ within(list())+ .getAllByRole("option")+ .map((o) => o.textContent),+ ).toEqual([expect.stringContaining("NaN Big")]);+ await userEvent.clear(screen.getByRole("searchbox", { name: "Search models" }));+ await userEvent.type(screen.getByRole("searchbox", { name: "Search models" }), "zzz");+ expect(within(list()).queryAllByRole("option")).toEqual([]);+ expect(screen.getByText("No models match.")).toBeInTheDocument();+ });++ it("selects a model by click, keeping the thinking level when the new model supports it", async () => {+ const { send } = await openPicker();+ await userEvent.click(option("NaN Big"));+ expect(send).toHaveBeenLastCalledWith({+ type: "model_set",+ provider: "nan",+ id: "big",+ thinking: "medium",+ });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ });++ it("moves with the arrow keys and selects with Enter", async () => {+ const { send } = await openPicker();+ const search = screen.getByRole("searchbox", { name: "Search models" });+ // The highlight starts on the current model.+ expect(search).toHaveAttribute("aria-activedescendant", option("GPT-5").id);+ await userEvent.keyboard("{ArrowDown}");+ expect(search).toHaveAttribute("aria-activedescendant", option("GPT-4o mini").id);+ await userEvent.keyboard("{ArrowDown}{ArrowDown}{ArrowUp}");+ expect(search).toHaveAttribute("aria-activedescendant", option("NaN Big").id);+ await userEvent.keyboard("{Enter}");+ expect(send).toHaveBeenLastCalledWith({+ type: "model_set",+ provider: "nan",+ id: "big",+ thinking: "medium",+ });+ });++ it("applies a profile from the quick picks", async () => {+ const { send } = await openPicker();+ await userEvent.click(option("daily"));+ expect(send).toHaveBeenLastCalledWith({ type: "profile_apply", name: "daily" });+ });++ it("closes on Esc and returns focus to the chip, without letting Esc hide the panel", async () => {+ await openPicker();+ const seen: boolean[] = [];+ const onKey = (event: KeyboardEvent) => {+ if (event.key === "Escape") seen.push(event.defaultPrevented);+ };+ window.addEventListener("keydown", onKey);+ await userEvent.keyboard("{Escape}");+ window.removeEventListener("keydown", onKey);+ expect(seen).toEqual([true]);+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Model: GPT-5" })).toHaveFocus();+ });++ it("shows the thinking level only when the current model supports it", async () => {+ const { send } = await openPicker();+ const thinking = screen.getByRole("combobox", { name: "Thinking" });+ expect(+ within(thinking)+ .getAllByRole("option")+ .map((o) => o.textContent),+ ).toEqual([...levels]);+ await userEvent.selectOptions(thinking, "high");+ expect(send).toHaveBeenLastCalledWith({+ type: "model_set",+ provider: "openai",+ id: "gpt-5",+ thinking: "high",+ });+ dispatchServer({ ...models, current: { provider: "openai", id: "gpt-4o-mini", name: "GPT-4o mini" } });+ expect(screen.queryByRole("combobox", { name: "Thinking" })).not.toBeInTheDocument();+ });++ it("follows the chosen model, says when it waits for the next message, and shows errors inline", async () => {+ await openPicker(vi.fn(), { ...ready, agentState: "thinking" });+ dispatchServer({ ...models, next: { provider: "nan", id: "big", name: "NaN Big" } });+ expect(screen.getByText("NaN Big is used from your next message.")).toBeInTheDocument();+ dispatchServer({ type: "error", code: "model_unavailable", message: "That model is not available." });+ expect(within(screen.getByRole("dialog")).getByRole("alert")).toHaveTextContent(+ "That model is not available.",+ );+ // Inline, not a toast as well.+ expect(document.querySelector(".notices")).toBeNull();+ dispatchServer({ ...models, current: { provider: "nan", id: "big", name: "NaN Big", thinking: "low" } });+ expect(screen.getByRole("button", { name: "Model: NaN Big" })).toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ });+});