Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Chat view: switch provider and model by clicking the model name

Claude741aab2a9a70
diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.ts
index 24aaf55f..185ffe75 100644
--- a/windows/src/core/bridge.ts
+++ b/windows/src/core/bridge.ts
@@ -85,6 +85,14 @@ export const Bridge = {
chatSend: (query: string, context: ChatContext | null) =>
callOrThrow<{ text: string }>("chat_send", { query, context }),
chatReset: () => call<void>("chat_reset"),
+ /**
+ * The models a provider offers, for the picker in the chat view. Rust asks
+ * the provider only when it has a key (or a server address).
+ */
+ chatModels: (provider: string) => callOrThrow<ModelInfo[]>("chat_models", { provider }),
+ /** Settings → Local models → Connect: does the server answer, and with which models? */
+ localConnect: (provider: "ollama" | "lmstudio" | "custom", url: string) =>
+ callOrThrow<LocalServer>("local_connect", { provider, url }),
/** Copies a dropped file into the inbox. */
ingestFile: (path: string) => callOrThrow<DroppedFile>("ingest_file", { path }),
/** Only ever tells you whether a key exists — never its value. */
@@ -112,6 +120,19 @@ export type ChatContext =
| { kind: "file"; name: string; path: string }
| { kind: "window"; appName: string; title: string; url?: string };
+export interface ModelInfo {
+ id: string;
+ label: string;
+}
+
+export interface LocalServer {
+ /** The address as it is stored. */
+ url: string;
+ models: string[];
+ /** The address is this machine. */
+ loopback: boolean;
+}
+
export interface DroppedFile {
name: string;
path: string;
diff --git a/windows/src/core/providers.ts b/windows/src/core/providers.ts
new file mode 100644
index 00000000..346c32c6
--- /dev/null
+++ b/windows/src/core/providers.ts
@@ -0,0 +1,105 @@
+// Who the chat can talk to — the island's side of chat.rs. The Mac's
+// ChatProvider (IslandTypes.swift) plus OpenRouter and any OpenAI-compatible
+// server. Pure data and helpers, so they can be tested without a webview.
+
+import type { Settings } from "./state";
+
+export type ProviderId =
+ | "anthropic" | "openai" | "google" | "openrouter"
+ | "ollama" | "lmstudio" | "custom";
+
+export interface ProviderDef {
+ id: ProviderId;
+ /** Shown on the chip in the chat's model picker. */
+ name: string;
+ accent: string;
+ /** Credential store entry of its key; null for the model servers. */
+ key: string | null;
+ /** Settings field holding a model server's address. */
+ urlField: "ollamaUrl" | "lmstudioUrl" | "customUrl" | null;
+ defaultModel: string;
+ /** When the saved model is not offered, the first one containing this is picked. */
+ prefer: string | null;
+}
+
+export const PROVIDERS: readonly ProviderDef[] = [
+ { id: "anthropic", name: "Anthropic", accent: "#E07950", key: "anthropic-api-key", urlField: null, defaultModel: "claude-opus-5", prefer: "opus" },
+ { id: "google", name: "Google", accent: "#4285F4", key: "google-api-key", urlField: null, defaultModel: "gemini-2.0-flash", prefer: "flash" },
+ { id: "openai", name: "OpenAI", accent: "#10A37F", key: "openai-api-key", urlField: null, defaultModel: "gpt-4o", prefer: "mini" },
+ { id: "openrouter", name: "OpenRouter", accent: "#6467F2", key: "openrouter-api-key", urlField: null, defaultModel: "openrouter/auto", prefer: null },
+ { id: "ollama", name: "Ollama", accent: "#FACC15", key: null, urlField: "ollamaUrl", defaultModel: "", prefer: null },
+ { id: "lmstudio", name: "LM Studio", accent: "#A3E635", key: null, urlField: "lmstudioUrl", defaultModel: "", prefer: null },
+ { id: "custom", name: "Custom server", accent: "#C0C4CC", key: null, urlField: "customUrl", defaultModel: "", prefer: null },
+];
+
+/** Credential store entry of the custom server's optional key. */
+export const CUSTOM_SERVER_KEY = "openai-compatible-key";
+
+export function providerDef(id: string): ProviderDef {
+ return PROVIDERS.find((p) => p.id === id) ?? PROVIDERS[0];
+}
+
+/** The model the chat uses for the active provider. */
+export function activeModel(settings: Settings): string {
+ const p = providerDef(settings.chatProvider);
+ if (p.id === "anthropic") return settings.model || p.defaultModel;
+ return settings.chatModels[p.id] || p.defaultModel;
+}
+
+/** `settings` with `model` picked for `provider`. */
+export function withModel(settings: Settings, provider: ProviderId, model: string): Settings {
+ if (provider === "anthropic") return { ...settings, model };
+ return { ...settings, chatModels: { ...settings.chatModels, [provider]: model } };
+}
+
+/**
+ * The chips of the picker: every cloud provider (one without a key says so
+ * when picked), and a model server once it is connected — or while it is the
+ * active one, so the picker never hides where the chat goes.
+ */
+export function visibleProviders(settings: Settings): ProviderDef[] {
+ return PROVIDERS.filter(
+ (p) => !p.urlField || settings[p.urlField] !== "" || settings.chatProvider === p.id,
+ );
+}
+
+/** The model to keep once the list arrives: the saved one if offered, else a sensible one. */
+export function pickModel(provider: ProviderDef, offered: string[], current: string): string | null {
+ if (offered.length === 0) return null;
+ if (offered.includes(current)) return current;
+ const preferred = provider.prefer ? offered.find((id) => id.includes(provider.prefer!)) : undefined;
+ if (preferred) return preferred;
+ return offered.includes(provider.defaultModel) ? provider.defaultModel : offered[0];
+}
+
+// ── Where an address points ───────────────────────────────────────────────────
+
+/** Mirrors net.rs: this machine, by name or address. */
+export function isLoopbackHost(host: string): boolean {
+ const h = host.replace(/^\[|\]$/g, "").toLowerCase();
+ if (h === "localhost" || h.endsWith(".localhost")) return true;
+ if (/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h)) return true;
+ return h === "0.0.0.0" || h === "::1" || h === "::" || h === "::ffff:127.0.0.1" || h === "::ffff:7f00:1";
+}
+
+/**
+ * Where a server address sends what you type: this machine, another one over
+ * https, another one in clear text (http), or nowhere valid. An empty field
+ * means the usual address on this machine.
+ */
+export type Exposure = "local" | "remote" | "remote-http" | "invalid";
+
+export function urlExposure(raw: string): Exposure {
+ const text = raw.trim();
+ if (!text) return "local";
+ let url: URL;
+ try {
+ url = new URL(text.includes("://") ? text : `http://${text}`);
+ } catch {
+ return "invalid";
+ }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return "invalid";
+ if (!url.hostname || url.username || url.password) return "invalid";
+ if (isLoopbackHost(url.hostname)) return "local";
+ return url.protocol === "https:" ? "remote" : "remote-http";
+}
diff --git a/windows/src/core/state.ts b/windows/src/core/state.ts
index 01236b80..955e4378 100644
--- a/windows/src/core/state.ts
+++ b/windows/src/core/state.ts
@@ -2,6 +2,7 @@
import type { BotEmoteName, BotStateName, IslandMode, IslandViewName } from "./layout";
import type { EyeShape } from "../mochi/engine";
+import type { ProviderId } from "./providers";
export type AgentSource = "claudeCode" | "n8n" | "agent";
export type PillBadge = "approval" | "finished" | "error";
@@ -92,6 +93,14 @@ export interface Settings {
hooksInstalled: boolean;
/** Claude model used by the chat. */
model: string;
+ /** Who the chat talks to (see core/providers.ts); picked in the chat view. */
+ chatProvider: ProviderId;
+ /** The model picked for each provider other than Anthropic, by provider id. */
+ chatModels: Record<string, string>;
+ /** Model server addresses once connected; empty means not connected. */
+ ollamaUrl: string;
+ lmstudioUrl: string;
+ customUrl: string;
}
export const DEFAULT_SETTINGS: Settings = {
@@ -106,6 +115,11 @@ export const DEFAULT_SETTINGS: Settings = {
autostart: false,
hooksInstalled: false,
model: "claude-opus-5",
+ chatProvider: "anthropic",
+ chatModels: {},
+ ollamaUrl: "",
+ lmstudioUrl: "",
+ customUrl: "",
};
type Listener = () => void;
diff --git a/windows/src/style.css b/windows/src/style.css
index 12f19066..1935591a 100644
--- a/windows/src/style.css
+++ b/windows/src/style.css
@@ -977,6 +977,177 @@ input[type="range"]::-webkit-slider-thumb {
50% { transform: scale(1.2); }
}
+/* ── Provider and model switcher (PromptView's model button) ─────────────── */
+
+.model-row {
+ display: flex;
+ justify-content: flex-end;
+ padding: 0 10px;
+}
+
+.model-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ max-width: 100%;
+ padding: 4px 8px;
+ border: 0;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.06);
+ color: #5c6370;
+ cursor: default;
+}
+
+.model-btn:hover:not(:disabled),
+.model-btn.open {
+ background: rgba(255, 255, 255, 0.1);
+}
+
+.model-btn:disabled {
+ opacity: 0.6;
+}
+
+.model-dot {
+ flex: 0 0 6px;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+}
+
+.model-name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font: 500 10.5px var(--font);
+ color: #7b8089;
+}
+
+.picker {
+ display: none;
+ flex: 1 1 auto;
+ min-height: 0;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ border-radius: 12px;
+ background: #16171b;
+ border: 1px solid rgba(255, 255, 255, 0.06);
+}
+
+.chat-body.picking .picker {
+ display: flex;
+}
+
+.chat-body.picking .chat-log,
+.chat-body.picking .chip-row {
+ display: none;
+}
+
+.picker-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.picker-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 10px;
+ border-radius: 999px;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ background: rgba(255, 255, 255, 0.06);
+ font: 400 11.5px var(--font);
+ color: #c8cdd4;
+ cursor: default;
+}
+
+.picker-chip.on {
+ font-weight: 600;
+ color: var(--ink-2);
+ /* Plain fallbacks for WebKitGTK builds without color-mix(). */
+ border-color: rgba(255, 255, 255, 0.3);
+ background: rgba(255, 255, 255, 0.12);
+ border-color: color-mix(in srgb, var(--accent) 50%, transparent);
+ background: color-mix(in srgb, var(--accent) 18%, transparent);
+}
+
+.picker-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--accent);
+}
+
+.picker-rule {
+ flex: 0 0 1px;
+ background: rgba(255, 255, 255, 0.2);
+ opacity: 0.4;
+}
+
+.picker-list {
+ flex: 1 1 auto;
+ min-height: 0;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255, 255, 255, 0.18) transparent;
+}
+
+.picker-model {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: 6px;
+ background: transparent;
+ color: #c8cdd4;
+ font: 400 12px var(--font);
+ text-align: left;
+ cursor: default;
+}
+
+.picker-model:hover {
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.picker-model.on {
+ color: var(--accent);
+ background: rgba(255, 255, 255, 0.06);
+ background: color-mix(in srgb, var(--accent) 10%, transparent);
+}
+
+.picker-model-name {
+ flex: 1 1 auto;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.picker-status {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-wrap: wrap;
+ padding: 4px 0;
+ font: 400 11px var(--font);
+ color: #8a8f98;
+}
+
+.picker-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: #60a5fa;
+ font: inherit;
+ cursor: default;
+}
+
.chat-bar {
display: flex;
align-items: center;
diff --git a/windows/src/views/chat.ts b/windows/src/views/chat.ts
index 6b28965d..9b46b6e9 100644
--- a/windows/src/views/chat.ts
+++ b/windows/src/views/chat.ts
@@ -1,14 +1,33 @@
-// Chat view — DOM port of PromptView / ChatBubble / TypingDotsView from
-// IslandViewContent.swift. Answers are rendered as Markdown (markdown.ts).
+// Chat view — DOM port of PromptView / ChatBubble / TypingDotsView /
+// ModelPickerView from IslandViewContent.swift.
+//
+// Answers are rendered as Markdown (markdown.ts). A local model streams its
+// answer: Rust sends `chat-delta` events with the text visible so far. The
+// model name above the text field opens the picker: provider chips, then the
+// models of the chosen provider, asked for only once it is picked.
import { h, svg, clear } from "./dom";
import { ICONS } from "./icons";
import { renderMarkdown } from "./markdown";
-import { Bridge, type ChatContext } from "../core/bridge";
+import { Bridge, onEvent, type ChatContext, type ModelInfo } from "../core/bridge";
+import {
+ activeModel, pickModel, providerDef, visibleProviders, withModel, type ProviderDef,
+} from "../core/providers";
import { Sound } from "../core/sound";
import { State, type ChatMessage } from "../core/state";
import type { ViewHost } from "./views";
+const STRINGS = {
+ placeholderFirst: "Ask me anything…",
+ placeholderNext: "Continue…",
+ send: "Send",
+ switchModel: "Switch provider or model",
+ noModel: "Choose a model",
+ loading: "Loading models…",
+ noKey: "No API key — add it in Settings.",
+ openSettings: "Open Settings",
+};
+
let nextId = 1;
function bubble(message: ChatMessage): HTMLElement {
@@ -39,33 +58,218 @@ function contextChip(label: string): HTMLElement {
return chip;
}
+function saveSettings() {
+ void Bridge.saveSettings(State.settings);
+}
+
+// ── Model picker ──────────────────────────────────────────────────────────────
+
+interface Picker {
+ el: HTMLElement;
+ open(): void;
+ close(): void;
+ readonly isOpen: boolean;
+}
+
+/** Provider chips, then the chosen provider's models — ModelPickerView. */
+function buildPicker(onChange: () => void): Picker {
+ const chips = h("div", { class: "picker-chips" });
+ const list = h("div", { class: "picker-list" });
+ const el = h("div", { class: "picker" }, chips, h("div", { class: "picker-rule" }), list);
+
+ /** Models already asked for, by provider; a model server is asked again each time. */
+ const cache = new Map<string, ModelInfo[]>();
+ let isOpen = false;
+ let request = 0;
+
+ function drawChips() {
+ clear(chips);
+ for (const p of visibleProviders(State.settings)) {
+ const on = p.id === State.settings.chatProvider;
+ const chip = h(
+ "button",
+ { class: on ? "picker-chip on" : "picker-chip", style: `--accent:${p.accent}` },
+ h("i", { class: "picker-dot" }),
+ h("span", { text: p.name }),
+ );
+ chip.addEventListener("click", () => {
+ if (p.id === State.settings.chatProvider) return;
+ State.settings = { ...State.settings, chatProvider: p.id };
+ saveSettings();
+ Sound.play("pop");
+ drawChips();
+ void loadModels();
+ onChange();
+ });
+ chips.append(chip);
+ }
+ }
+
+ function status(text: string, withSettings = false) {
+ clear(list);
+ const line = h("div", { class: "picker-status", text });
+ if (withSettings) {
+ line.append(
+ h("button", {
+ class: "picker-link",
+ text: STRINGS.openSettings,
+ onclick: () => void Bridge.openSettingsWindow(),
+ }),
+ );
+ }
+ list.append(line);
+ }
+
+ function drawModels(p: ProviderDef, models: ModelInfo[]) {
+ clear(list);
+ const current = activeModel(State.settings);
+ for (const m of models) {
+ const on = m.id === current;
+ const row = h(
+ "button",
+ { class: on ? "picker-model on" : "picker-model", style: `--accent:${p.accent}`, title: m.id },
+ h("span", { class: "picker-model-name", text: m.label }),
+ on ? svg(ICONS.check, 11, { stroke: 2.2 }) : null,
+ );
+ row.addEventListener("click", () => {
+ State.settings = withModel(State.settings, p.id, m.id);
+ saveSettings();
+ Sound.play("blip");
+ close();
+ });
+ list.append(row);
+ }
+ list.querySelector(".picker-model.on")?.scrollIntoView({ block: "nearest" });
+ }
+
+ async function loadModels() {
+ const p = providerDef(State.settings.chatProvider);
+ const ticket = ++request;
+ const cached = p.urlField ? undefined : cache.get(p.id);
+ if (cached) {
+ drawModels(p, cached);
+ return;
+ }
+ // Nothing is asked of a provider that has no key yet.
+ if (p.key && !(await Bridge.secretPresent(p.key))) {
+ if (ticket === request) status(STRINGS.noKey, true);
+ return;
+ }
+ if (ticket !== request) return;
+ status(STRINGS.loading);
+ try {
+ const models = await Bridge.chatModels(p.id);
+ if (ticket !== request) return;
+ if (!p.urlField) cache.set(p.id, models);
+ const keep = pickModel(p, models.map((m) => m.id), activeModel(State.settings));
+ if (keep && keep !== activeModel(State.settings)) {
+ State.settings = withModel(State.settings, p.id, keep);
+ saveSettings();
+ onChange();
+ }
+ drawModels(p, models);
+ } catch (err) {
+ if (ticket === request) status(String(err).replace(/^Error:\s*/, ""), Boolean(p.key));
+ }
+ }
+
+ function open() {
+ isOpen = true;
+ el.classList.add("on");
+ drawChips();
+ onChange();
+ void loadModels();
+ }
+
+ function close() {
+ isOpen = false;
+ request++;
+ el.classList.remove("on");
+ onChange();
+ }
+
+ return {
+ el,
+ open,
+ close,
+ get isOpen() {
+ return isOpen;
+ },
+ };
+}
+
+// ── View ──────────────────────────────────────────────────────────────────────
+
export function buildPrompt(onHeightChange: () => void): ViewHost {
const chipRow = h("div", { class: "chip-row" });
const log = h("div", { class: "chat-log" });
const input = h("input", {
type: "text",
class: "chat-input",
- placeholder: "Ask me anything…",
+ placeholder: STRINGS.placeholderFirst,
spellcheck: "false",
}) as HTMLInputElement;
- const send = h("button", { class: "send-btn", title: "Send" }, svg(ICONS.arrowUp, 11));
+ const send = h("button", { class: "send-btn", title: STRINGS.send }, svg(ICONS.arrowUp, 11));
const bar = h("div", { class: "chat-bar" }, input, send);
- const el = h(
- "div",
- { class: "view" },
- h("div", { class: "card wash chat-card" }, h("div", { class: "chat-body" }, chipRow, log, bar)),
+ const modelDot = h("i", { class: "model-dot" });
+ const modelName = h("span", { class: "model-name" });
+ const modelBtn = h(
+ "button",
+ { class: "model-btn", title: STRINGS.switchModel },
+ modelDot,
+ modelName,
+ svg(ICONS.chevronUpDown, 9, { stroke: 2 }),
);
+ const modelRow = h("div", { class: "model-row" }, modelBtn);
+
+ const body = h("div", { class: "chat-body" });
+ const picker = buildPicker(() => {
+ body.classList.toggle("picking", picker.isOpen);
+ drawModelButton();
+ });
+ body.append(chipRow, log, picker.el, modelRow, bar);
+
+ const el = h("div", { class: "view" }, h("div", { class: "card wash chat-card" }, body));
(el.querySelector(".card") as HTMLElement).style.setProperty("--wash", "rgba(99,102,241,0.5)");
let sending = false;
let renderedCount = -1;
+ // A local model answers token by token: where its text so far is shown.
+ let live: HTMLElement | null = null;
+
+ function drawModelButton() {
+ const p = providerDef(State.settings.chatProvider);
+ modelDot.style.background = p.accent;
+ modelName.textContent = activeModel(State.settings) || STRINGS.noModel;
+ modelBtn.classList.toggle("open", picker.isOpen);
+ modelBtn.disabled = sending;
+ }
+
+ modelBtn.addEventListener("click", () => {
+ if (sending) return;
+ if (picker.isOpen) picker.close();
+ else picker.open();
+ });
+
+ void onEvent<string>("chat-delta", (text) => {
+ if (!sending || !text) return; // nothing visible yet: the dots stay
+ if (!live) {
+ live = h("div", { class: "reply" });
+ log.querySelector(".typing")?.parentElement?.remove();
+ log.append(h("div", { class: "chat-row" }, live));
+ }
+ renderMarkdown(live, text);
+ log.scrollTop = log.scrollHeight;
+ });
async function submit() {
const query = input.value.trim();
if (!query || sending) return;
+ if (picker.isOpen) picker.close();
input.value = "";
sending = true;
+ drawModelButton();
Sound.play("send");
State.chatHistory.push({ id: nextId++, role: "user", content: query });
@@ -89,6 +293,9 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
Sound.play("error");
} finally {
sending = false;
+ live = null;
+ renderedCount = -1; // the finished answer replaces the streamed one
+ drawModelButton();
State.notify();
onHeightChange();
input.focus();
@@ -97,9 +304,13 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
send.addEventListener("click", () => void submit());
input.addEventListener("keydown", (e) => {
- if ((e as KeyboardEvent).key === "Enter") {
+ const key = (e as KeyboardEvent).key;
+ if (key === "Enter") {
e.preventDefault();
void submit();
+ } else if (key === "Escape" && picker.isOpen) {
+ e.preventDefault();
+ picker.close();
}
e.stopPropagation(); // Escape closes the island, not the chat
});
@@ -117,7 +328,7 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
const thinking = State.stateOverride === "thinking";
const count = State.chatHistory.length + (thinking ? 0.5 : 0);
- if (count !== renderedCount) {
+ if (count !== renderedCount && !live) {
renderedCount = count;
clear(log);
for (const m of State.chatHistory) log.append(bubble(m));
@@ -125,7 +336,11 @@ export function buildPrompt(onHeightChange: () => void): ViewHost {
log.scrollTop = log.scrollHeight;
}
- input.placeholder = State.chatHistory.length === 0 ? "Ask me anything…" : "Continue…";
+ // Leaving the chat folds the picker away.
+ if (State.view !== "prompt" && picker.isOpen) picker.close();
+ drawModelButton();
+
+ input.placeholder = State.chatHistory.length === 0 ? STRINGS.placeholderFirst : STRINGS.placeholderNext;
input.disabled = sending;
},
focus() {
diff --git a/windows/tests/chat.test.mjs b/windows/tests/chat.test.mjs
new file mode 100644
index 00000000..ff03d4a7
--- /dev/null
+++ b/windows/tests/chat.test.mjs
@@ -0,0 +1,124 @@
+// The chat view (src/views/chat.ts) on a fake DOM, through the real bridge:
+// the model switcher asks for a provider's models only once it is picked and
+// has a key, picking saves the settings, and a streamed answer grows in place.
+
+import { beforeEach, test } from "node:test";
+import assert from "node:assert/strict";
+import { installFakeDom } from "./fakedom.mjs";
+import { calls, emit, internals, sent } from "./tauri.mjs";
+
+installFakeDom();
+const { buildPrompt } = await import("../src/views/chat.ts");
+const { DEFAULT_SETTINGS, State } = await import("../src/core/state.ts");
+
+/** What the mocked Rust side answers, by command. */
+let answers;
+const plainInvoke = internals.invoke;
+internals.invoke = async (cmd, args) => {
+ const result = await plainInvoke(cmd, args);
+ if (cmd in answers) return typeof answers[cmd] === "function" ? answers[cmd](args) : answers[cmd];
+ return result;
+};
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+let view;
+beforeEach(() => {
+ calls.length = 0;
+ answers = {};
+ State.settings = { ...DEFAULT_SETTINGS, chatModels: {} };
+ State.chatHistory = [];
+ State.stateOverride = null;
+ State.view = "prompt";
+ State.droppedFile = null;
+ view = buildPrompt(() => {});
+ view.sync();
+});
+
+const $ = (cls) => view.el.querySelector(cls);
+const chips = () => view.el.find(".picker-chip").map((c) => c.textContent);
+const models = () => view.el.find(".picker-model").map((m) => m.textContent);
+
+test("the model button shows the active provider's model", () => {
+ assert.equal($(".model-name").textContent, "claude-opus-5");
+ State.settings = { ...State.settings, chatProvider: "google" };
+ view.sync();
+ assert.equal($(".model-name").textContent, "gemini-2.0-flash");
+ State.settings = { ...State.settings, chatProvider: "ollama" };
+ view.sync();
+ assert.equal($(".model-name").textContent, "Choose a model");
+});
+
+test("a provider without a key is never asked for its models", async () => {
+ answers.secret_present = false;
+ $(".model-btn").fire("click");
+ await flush();
+ assert.ok($(".chat-body").classList.contains("picking"));
+ assert.deepEqual(chips(), ["Anthropic", "Google", "OpenAI", "OpenRouter"]);
+ assert.deepEqual(sent("secret_present"), [{ key: "anthropic-api-key" }]);
+ assert.deepEqual(sent("chat_models"), []);
+ assert.match($(".picker-status").textContent, /No API key/);
+});
+
+test("with a key, the models are listed and picking one saves it", async () => {
+ answers.secret_present = true;
+ answers.chat_models = [
+ { id: "claude-opus-5", label: "Claude Opus 5" },
+ { id: "claude-sonnet-5", label: "Claude Sonnet 5" },
+ ];
+ $(".model-btn").fire("click");
+ await flush();
+ assert.deepEqual(sent("chat_models"), [{ provider: "anthropic" }]);
+ assert.deepEqual(models(), ["Claude Opus 5", "Claude Sonnet 5"]);
+ view.el.find(".picker-model")[1].fire("click");
+ assert.equal(State.settings.model, "claude-sonnet-5");
+ assert.equal(sent("save_settings").at(-1).settings.model, "claude-sonnet-5");
+ assert.ok(!$(".chat-body").classList.contains("picking"));
+ assert.equal($(".model-name").textContent, "claude-sonnet-5");
+});
+
+test("switching provider saves it and asks the new provider only", async () => {
+ answers.secret_present = (args) => args.key === "google-api-key";
+ answers.chat_models = (args) => (args.provider === "google" ? [{ id: "gemini-2.5-flash", label: "gemini-2.5-flash" }] : []);
+ $(".model-btn").fire("click");
+ await flush();
+ assert.deepEqual(sent("chat_models"), []);
+ view.el.find(".picker-chip")[1].fire("click");
+ await flush();
+ assert.equal(State.settings.chatProvider, "google");
+ assert.deepEqual(sent("chat_models"), [{ provider: "google" }]);
+ // The saved model was not offered: the flash one is kept instead, and saved.
+ assert.equal(State.settings.chatModels.google, "gemini-2.5-flash");
+ assert.equal(sent("save_settings").at(-1).settings.chatModels.google, "gemini-2.5-flash");
+ assert.deepEqual(models(), ["gemini-2.5-flash"]);
+});
+
+test("a local answer streams into one reply, then the finished text replaces it", async () => {
+ let finish;
+ answers.chat_send = () => new Promise((resolve) => (finish = resolve));
+ const input = $(".chat-input");
+ input.value = "hello";
+ $(".send-btn").fire("click");
+ await flush();
+ view.sync(); // what State.notify() does in the island
+ assert.ok($(".model-btn").disabled, "no switching mid-answer");
+ assert.ok($(".typing"), "dots until the first visible text");
+
+ emit("chat-delta", ""); // still thinking
+ assert.ok($(".typing"));
+ emit("chat-delta", "Hel");
+ emit("chat-delta", "Hello **there**");
+ view.sync(); // another view update mid-stream must not wipe the live answer
+ assert.equal($(".typing"), null);
+ const replies = view.el.find(".reply");
+ assert.equal(replies.length, 1);
+ assert.equal(replies[0].find("STRONG")[0].textContent, "there");
+
+ finish({ text: "Hello **there**!" });
+ await flush();
+ view.sync();
+ assert.equal(view.el.find(".reply").length, 1);
+ assert.equal(view.el.find(".reply")[0].textContent, "Hello there!");
+ assert.deepEqual(State.chatHistory.map((m) => m.role), ["user", "assistant"]);
+ assert.ok(!$(".model-btn").disabled);
+});
diff --git a/windows/tests/providers.test.mjs b/windows/tests/providers.test.mjs
new file mode 100644
index 00000000..1b2b9471
--- /dev/null
+++ b/windows/tests/providers.test.mjs
@@ -0,0 +1,74 @@
+// The island's provider table (src/core/providers.ts): which model the chat
+// uses, which chips the picker shows, and what a server address exposes.
+
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import {
+ PROVIDERS, activeModel, isLoopbackHost, pickModel, providerDef, urlExposure, visibleProviders, withModel,
+} from "../src/core/providers.ts";
+import { DEFAULT_SETTINGS } from "../src/core/state.ts";
+
+const settings = (over = {}) => ({ ...DEFAULT_SETTINGS, ...over });
+
+test("the ids and key names match the Rust side and the Mac", () => {
+ assert.deepEqual(PROVIDERS.map((p) => p.id), ["anthropic", "google", "openai", "openrouter", "ollama", "lmstudio", "custom"]);
+ assert.equal(providerDef("google").key, "google-api-key");
+ assert.equal(providerDef("openai").key, "openai-api-key");
+ assert.equal(providerDef("openrouter").key, "openrouter-api-key");
+ assert.equal(providerDef("ollama").key, null);
+ // An unknown id (an older or newer settings.json) falls back to Claude.
+ assert.equal(providerDef("nope").id, "anthropic");
+});
+
+test("Claude's model is the existing setting; the others are kept per provider", () => {
+ assert.equal(activeModel(settings()), "claude-opus-5");
+ assert.equal(activeModel(settings({ chatProvider: "google" })), "gemini-2.0-flash");
+ assert.equal(activeModel(settings({ chatProvider: "ollama" })), "");
+ let s = withModel(settings({ chatProvider: "openai" }), "openai", "gpt-5-mini");
+ assert.equal(activeModel(s), "gpt-5-mini");
+ assert.equal(s.model, "claude-opus-5");
+ s = withModel(s, "anthropic", "claude-haiku-4-5");
+ assert.equal(s.model, "claude-haiku-4-5");
+ assert.equal(s.chatModels.openai, "gpt-5-mini");
+ // withModel never changes the object it was given.
+ assert.deepEqual(DEFAULT_SETTINGS.chatModels, {});
+});
+
+test("model servers show in the picker once connected, or while in use", () => {
+ const ids = (s) => visibleProviders(s).map((p) => p.id);
+ assert.deepEqual(ids(settings()), ["anthropic", "google", "openai", "openrouter"]);
+ assert.deepEqual(ids(settings({ ollamaUrl: "http://127.0.0.1:11434" })), ["anthropic", "google", "openai", "openrouter", "ollama"]);
+ assert.deepEqual(ids(settings({ chatProvider: "custom" })), ["anthropic", "google", "openai", "openrouter", "custom"]);
+});
+
+test("the saved model is kept when offered, else a sensible one is picked", () => {
+ const google = providerDef("google");
+ assert.equal(pickModel(google, ["gemini-2.5-pro", "gemini-2.0-flash"], "gemini-2.5-pro"), "gemini-2.5-pro");
+ assert.equal(pickModel(google, ["gemini-2.5-pro", "gemini-2.5-flash"], "gone"), "gemini-2.5-flash");
+ assert.equal(pickModel(providerDef("openai"), ["gpt-4o", "gpt-5-mini"], "gone"), "gpt-5-mini");
+ assert.equal(pickModel(providerDef("ollama"), ["llama3.2", "qwen"], ""), "llama3.2");
+ assert.equal(pickModel(providerDef("openrouter"), ["a/b", "openrouter/auto"], "gone"), "openrouter/auto");
+ assert.equal(pickModel(google, [], "x"), null);
+});
+
+test("loopback hosts match net.rs", () => {
+ for (const host of ["localhost", "app.localhost", "127.0.0.1", "127.9.9.9", "[::1]", "::1", "0.0.0.0", "[::]"]) {
+ assert.ok(isLoopbackHost(host), host);
+ }
+ for (const host of ["example.com", "192.168.1.2", "localhost.example.com", "128.0.0.1", "[2001:db8::1]"]) {
+ assert.ok(!isLoopbackHost(host), host);
+ }
+});
+
+test("an address says whether what you type leaves this computer", () => {
+ assert.equal(urlExposure(""), "local");
+ assert.equal(urlExposure("http://localhost:11434"), "local");
+ assert.equal(urlExposure("127.0.0.1:1234/v1"), "local");
+ assert.equal(urlExposure("http://[::1]:8000"), "local");
+ assert.equal(urlExposure("https://llm.example.com"), "remote");
+ assert.equal(urlExposure("http://gpu-box.lan:8000"), "remote-http");
+ assert.equal(urlExposure("192.168.1.20:8000"), "remote-http");
+ assert.equal(urlExposure("ftp://example.com"), "invalid");
+ assert.equal(urlExposure("http://user:[email protected]"), "invalid");
+ assert.equal(urlExposure("http://"), "invalid");
+});