Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(chat): remember the last model for new chats and voice-created agents (#301)
Ruben Lütkeddb97b5adcea
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.pyindex 07ecd79a97..f2a4bf44f7 100644--- a/jarvis/agent_chat/service.py+++ b/jarvis/agent_chat/service.py@@ -337,6 +337,7 @@ class AgentChatService:permission_mode: str = "",title: str = "",surface: str = DEFAULT_SURFACE,+ account_id: str = "",) -> AgentChatSession:row = provider_row(provider)if row is None and not supports_api_runner(provider):@@ -361,6 +362,7 @@ class AgentChatService:permission_mode=permission_mode,title=title,surface=surface,+ account_id=account_id,)def is_running(self, session_id: str) -> bool:@@ -635,6 +637,12 @@ class AgentChatService:cancel = asyncio.Event()run = _Running(turn_id, cancel)self._running[session_id] = run+ if session.surface == "jarvis" and direct_user and incoming is None and not control_owned:+ from .store import ChatSelection++ self.store.save_chat_selection(+ ChatSelection(session.provider, session.model, session.effort, session.account_id)+ )from jarvis.core.tool_read_only import set_chat_read_onlyset_chat_read_only(session_id, session.permission_mode in ("plan", "read-only"))diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.pyindex 0986eb4d44..8d9b2dd7dc 100644--- a/jarvis/agent_chat/store.py+++ b/jarvis/agent_chat/store.py@@ -64,6 +64,13 @@ CREATE TABLE IF NOT EXISTS agent_chat_permission_overrides ();CREATE INDEX IF NOT EXISTS idx_agent_chat_sessions_updatedON agent_chat_sessions(updated_ms DESC);+CREATE TABLE IF NOT EXISTS jarvis_chat_selection (+ id INTEGER PRIMARY KEY CHECK (id = 1),+ provider TEXT NOT NULL,+ model TEXT NOT NULL DEFAULT '',+ effort TEXT NOT NULL DEFAULT '',+ account_id TEXT NOT NULL DEFAULT ''+);"""_TITLE_MAX_CHARS = 80@@ -89,6 +96,19 @@ SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models", "society"DEFAULT_SURFACE: Final[str] = "agent"+@dataclass(frozen=True, slots=True)+class ChatSelection:+ """The last explicit Jarvis chat pick, independent of viewed history or voice."""++ provider: str+ model: str = ""+ effort: str = ""+ account_id: str = ""++ def to_dict(self) -> dict[str, str]:+ return asdict(self)++@dataclass(slots=True)class AgentChatSession:session_id: str@@ -163,6 +183,44 @@ class AgentChatStore:with self._lock:self._conn.close()+ def chat_selection(self) -> ChatSelection | None:+ with self._lock:+ row = self._conn.execute("SELECT * FROM jarvis_chat_selection WHERE id = 1").fetchone()+ if row is None:+ # Upgrade installs whose last choice exists only in chat history.+ # Agent replies and automatic control turns must not win recency.+ history = self._conn.execute(+ "SELECT s.provider, s.model, s.effort, s.account_id, e.payload "+ "FROM agent_chat_sessions s JOIN agent_chat_events e USING (session_id) "+ "WHERE s.surface = 'jarvis' AND e.kind = 'user_message' "+ "ORDER BY e.ts_ms DESC, e.seq DESC"+ )+ for previous in history:+ if (+ previous["provider"]+ and json.loads(previous["payload"]).get("origin") != "control"+ ):+ row = previous+ break+ if row is None:+ return None+ return ChatSelection(+ **{key: row[key] for key in ("provider", "model", "effort", "account_id")}+ )++ def save_chat_selection(self, selection: ChatSelection) -> None:+ if not selection.provider.strip():+ raise ValueError("A chat selection needs a provider")+ with self._lock:+ self._conn.execute(+ "INSERT INTO jarvis_chat_selection (id, provider, model, effort, account_id) "+ "VALUES (1, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET "+ "provider=excluded.provider, model=excluded.model, "+ "effort=excluded.effort, account_id=excluded.account_id",+ (selection.provider, selection.model, selection.effort, selection.account_id),+ )+ self._conn.commit()+# ------------------------------------------------------------ sessionsdef create_session(diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.pyindex 07179654c6..517760f87f 100644--- a/jarvis/ui/web/agent_chat_routes.py+++ b/jarvis/ui/web/agent_chat_routes.py@@ -93,6 +93,35 @@ HIDDEN_SURFACES: frozenset[str] = frozenset({"society"})router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])+class ChatSelectionBody(BaseModel):+ provider: str = Field(min_length=1)+ model: str = ""+ effort: str = ""+ account_id: str = ""++[email protected]("/selection", summary="Remember the model for new Jarvis chats and agents")+async def save_chat_selection(body: ChatSelectionBody, request: Request) -> dict[str, str]:+ from jarvis.agent_chat.store import ChatSelection++ provider = body.provider.strip().lower()+ if not offers("jarvis", provider):+ raise HTTPException(400, "This provider is not offered on the Jarvis chat")+ if body.account_id:+ from jarvis import agent_accounts+ from jarvis.agent_chat.catalog import provider_row++ account = agent_accounts.resolve(body.account_id)+ row = provider_row(provider)+ if account is None or row is None or account.platform != row.agent:+ raise HTTPException(400, "This subscription account does not belong to the provider")+ selection = ChatSelection(+ provider, body.model.strip(), normalize_effort(provider, body.effort), body.account_id+ )+ _service(request).store.save_chat_selection(selection)+ return selection.to_dict()++@router.get("/commands", summary="List chat slash commands and their availability")def list_chat_commands(request: Request, session_id: str | None = None) -> dict[str, Any]:try:@@ -132,6 +161,7 @@ _WS_PING_S = 20.0class CreateSessionBody(BaseModel):provider: str+ account_id: str = ""model: str = ""effort: str | None = Nonecwd: str | None = None@@ -326,6 +356,11 @@ async def get_catalog("providers": rows,"default_cwd": svc.default_cwd(surface),"shell": shell_label(),+ "selection": (+ selection.to_dict()+ if surface == "jarvis" and (selection := svc.store.chat_selection()) is not None+ else None+ ),}@@ -677,6 +712,14 @@ def list_sessions(@router.post("/sessions", status_code=201)def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:svc = _service(request)+ if body.account_id:+ from jarvis import agent_accounts+ from jarvis.agent_chat.catalog import provider_row++ account = agent_accounts.resolve(body.account_id)+ row = provider_row(body.provider)+ if account is None or row is None or account.platform != row.agent:+ raise HTTPException(400, "This subscription account does not belong to the provider")ladder = ladder_key(body.surface, resolve_runner(body.provider, surface=body.surface))if body.permission_mode and not is_permission_mode(ladder, body.permission_mode):raise HTTPException(@@ -696,9 +739,16 @@ def create_session(body: CreateSessionBody, request: Request) -> dict[str, Any]:permission_mode=normalize_permission(ladder, body.permission_mode),title=body.title,surface=body.surface,+ account_id=body.account_id,)except ValueError as exc:raise HTTPException(status_code=400, detail=str(exc)) from exc+ if session.surface == "jarvis":+ from jarvis.agent_chat.store import ChatSelection++ svc.store.save_chat_selection(+ ChatSelection(session.provider, session.model, session.effort, session.account_id)+ )d = session.to_dict()d["running"] = Falsereturn d@@ -744,6 +794,8 @@ async def patch_session(detail=f"provider {picked!r} is not offered on the {existing.surface!r} chat",)fields["provider"] = picked+ if picked != existing.provider:+ fields["account_id"] = ""# A provider change resets the vendor conversation: the new CLI cannot# resume the old one's id.fields["vendor_session"] = ""@@ -800,6 +852,12 @@ async def patch_session(raise HTTPException(status_code=409, detail="Agent chat is working")session = svc.store.update_session(session_id, **fields)assert session is not None+ if session.surface == "jarvis" and {"provider", "model", "effort"}.intersection(fields):+ from jarvis.agent_chat.store import ChatSelection++ svc.store.save_chat_selection(+ ChatSelection(session.provider, session.model, session.effort, session.account_id)+ )if current.surface == "society" and body.permission_mode is not None:svc.store.set_permission_override(session_id, session.permission_mode)if current.surface == "society":diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.tsindex 4703f1e3f5..8b04ccecb2 100644--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts@@ -66,6 +66,22 @@ export interface AgentChatCatalog {providers: AgentChatProvider[];default_cwd: string;shell: string;+ selection?: ChatSelection | null;+}++export interface ChatSelection {+ provider: string;+ model: string;+ effort: string;+ account_id?: string;+}++export async function saveChatSelection(selection: ChatSelection): Promise<ChatSelection> {+ return json(await fetch("/api/agent-chat/selection", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(selection),+ }), "selection-save-failed");}/**@@ -311,6 +327,7 @@ export async function fetchAgentChatSessions(export interface CreateSessionInput {provider: string;+ account_id?: string;model?: string;effort?: string | null;cwd?: string | null;diff --git a/jarvis/ui/web/frontend/src/store/agentChat.selection.test.ts b/jarvis/ui/web/frontend/src/store/agentChat.selection.test.tsnew file mode 100644index 0000000000..51883a341e--- /dev/null+++ b/jarvis/ui/web/frontend/src/store/agentChat.selection.test.ts@@ -0,0 +1,126 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { waitFor } from "@testing-library/react";+import { createAgentChatStore, draftKey } from "./agentChat";+import type { AgentChatProvider, ChatSelection } from "@/lib/agentChatApi";++const provider: AgentChatProvider = {+ id: "claude-api", label: "Anthropic Claude", runner: "brain", models_source: "curated",+ family: "anthropic", keyless: false, native_resume: true, cli_installed: null,+ curated_models: [], effort_levels: ["high"], default_effort: "high", default_model: "",+ permission_modes: [{ id: "bypass", label: "Bypass", description: "Bypass" }], default_permission_mode: "bypass",+};+const pick: ChatSelection = { provider: "claude-api", model: "claude-sonnet-5-5", effort: "high" };+const draft = { ...pick, cwd: "", permissionMode: "bypass", buildMode: "bypass" };+const reply = (data: unknown) => new Response(JSON.stringify(data), { status: 200 });++class Socket {+ static latest: Socket;+ onmessage: ((event: { data: string }) => void) | null = null;+ constructor() { Socket.latest = this; }+ close() {}+}++function backend(selection: ChatSelection | null = pick) {+ let saved = selection;+ const writes: ChatSelection[] = [];+ const fetch = vi.fn(async (input: string, init?: RequestInit) => {+ if (String(input).startsWith("/api/agent-chat/catalog")) return reply({+ providers: [provider], selection: saved, default_cwd: "", shell: "test",+ });+ if (input === "/api/agent-chat/selection") {+ saved = JSON.parse(String(init?.body));+ writes.push(saved!);+ return reply(saved);+ }+ return reply({ mapping: [], providers: [] });+ });+ vi.stubGlobal("fetch", fetch);+ return { fetch, writes };+}++beforeEach(() => { localStorage.clear(); vi.stubGlobal("WebSocket", Socket); });+afterEach(() => { vi.unstubAllGlobals(); });++describe("remembered Jarvis chat model", () => {+ it("restores the backend pick after local storage is cleared", async () => {+ backend();+ const store = createAgentChatStore("jarvis");+ await store.getState().loadCatalog();+ expect(store.getState().draft).toMatchObject(pick);+ });++ it("saves a pick before a chat exists and restores it for a fresh store", async () => {+ const { writes } = backend(null);+ const store = createAgentChatStore("jarvis");+ await store.getState().loadCatalog();+ await store.getState().setDraft(pick);+ expect(writes.at(-1)).toEqual(pick);+ expect(store.getState().activeSessionId).toBeNull();+ localStorage.clear();+ const restarted = createAgentChatStore("jarvis");+ await restarted.getState().loadCatalog();+ expect(restarted.getState().draft).toMatchObject(pick);+ });++ it("migrates the existing local choice without a paid chat turn", async () => {+ localStorage.setItem(draftKey("jarvis"), JSON.stringify(draft));+ const { writes } = backend(null);+ await createAgentChatStore("jarvis").getState().loadCatalog();+ expect(writes).toEqual([pick]);+ });++ it("reading an old conversation does not become the next chat default", async () => {+ const { writes } = backend();+ const store = createAgentChatStore("jarvis");+ await store.getState().loadCatalog();+ store.getState().openSession("old");+ await waitFor(() => expect(Socket.latest.onmessage).not.toBeNull());+ Socket.latest.onmessage!({ data: JSON.stringify({ type: "snapshot", events: [], session: {+ session_id: "old", provider: "claude-api", model: "old-model", effort: "high",+ permission_mode: "bypass", cwd: "", surface: "jarvis",+ } }) });+ expect(store.getState().draft.model).toBe("old-model");+ store.getState().newChat();+ expect(store.getState().draft.model).toBe(pick.model);+ await waitFor(() => expect(store.getState().catalog).not.toBeNull());+ expect(store.getState().draft.model).toBe(pick.model);+ expect(writes).toEqual([]);+ store.getState().disconnect();+ });++ it("does not let a slow catalog replace a newer explicit selection", async () => {+ const { fetch } = backend();+ let finish!: (response: Response) => void;+ fetch.mockImplementationOnce(() => new Promise<Response>((resolve) => { finish = resolve; }));+ const store = createAgentChatStore("jarvis");+ const loading = store.getState().loadCatalog();+ await store.getState().setDraft({ ...pick, model: "newer-model" });+ finish(reply({ providers: [provider], selection: pick, default_cwd: "", shell: "test" }));+ await loading;+ expect(store.getState().draft.model).toBe("newer-model");+ });++ it("serializes rapid choices so the last click wins in persistent storage", async () => {+ const { fetch, writes } = backend();+ const store = createAgentChatStore("jarvis");+ store.setState({ catalog: { providers: [provider], default_cwd: "", shell: "test" } });+ let release!: () => void;+ const gate = new Promise<void>((resolve) => { release = resolve; });+ const normal = fetch.getMockImplementation()!;+ fetch.mockImplementationOnce(async (...args) => { await gate; return normal(...args); });+ const first = store.getState().setDraft({ ...pick, model: "first" });+ const last = store.getState().setDraft({ ...pick, model: "last" });+ await Promise.resolve();+ expect(writes).toEqual([]);+ release();+ await Promise.all([first, last]);+ expect(writes.map((row) => row.model)).toEqual(["first", "last"]);+ });++ it("never writes a Society or IDE pick into the Jarvis default", async () => {+ const { writes } = backend();+ await createAgentChatStore("agent").getState().setDraft(pick);+ await createAgentChatStore("society").getState().setDraft(pick);+ expect(writes).toEqual([]);+ });+});diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.tsindex 2bac4c389a..eb46735e67 100644--- a/jarvis/ui/web/frontend/src/store/agentChat.ts+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts@@ -17,6 +17,7 @@ import {skipAgentChatQuestion,type QuestionAnswerInput,sendAgentChatMessage,+ saveChatSelection,type AgentChatCatalog,type AgentChatEvent,type AgentChatProvider,@@ -79,6 +80,7 @@ const SESSION_LIST_LIMIT = 500;export interface ComposerDraft {provider: string;+ accountId?: string;model: string;effort: string;permissionMode: string;@@ -252,6 +254,7 @@ function draftFromSession(session: AgentChatSession, prev: ComposerDraft): Compoconst plan = session.permission_mode === "plan";return {provider: session.provider,+ accountId: session.account_id ?? "",model: session.model,effort: session.effort,permissionMode: session.permission_mode,@@ -281,6 +284,8 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =let catalogRequest = 0;const patchQueues = new Map<string, Promise<void>>();const patchRevisions = new Map<string, number>();+ let selectionRevision = 0;+ let selectionWrite: Promise<unknown> = Promise.resolve();let socket: WebSocket | null = null;let socketSession: string | null = null;/** Cancels the reconnect waiting in the shared connect budget. */@@ -360,7 +365,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =timeline: { ...tl, sessionPatch: null },draft: draftFromSession(frame.session, prev.draft),});- writeDraft(DRAFT_KEY, get().draft);+ if (surface !== "jarvis") writeDraft(DRAFT_KEY, get().draft);if (prev.activeSession?.account_id !== frame.session.account_id) void get().loadCatalog();return;}@@ -413,8 +418,10 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =loadCatalog: async () => {const requestId = ++catalogRequest;+ const revision = selectionRevision;const sessionId = get().activeSessionId;try {+ if (surface === "jarvis" && !sessionId) await selectionWrite;const [raw, connections] = await Promise.all([fetchAgentChatCatalog(surface, { sessionId: sessionId ?? undefined, cwd: get().draft.cwd || undefined }),fetchAgentConnections().catch(() => [] as AgentConnectionRow[]),@@ -453,6 +460,9 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =const st = get();const options = st.providerOptions();let draft = st.draft;+ if (surface === "jarvis" && !sessionId && revision === selectionRevision && catalog.selection) {+ draft = { ...draft, provider: catalog.selection.provider, model: catalog.selection.model, effort: catalog.selection.effort, accountId: catalog.selection.account_id ?? "" };+ }const known = options.find((o) => o.id === draft.provider);if (!known) {const pick = options.find((o) => o.active && o.connected) ?? options.find((o) => o.connected) ?? options[0];@@ -489,7 +499,18 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =}if (draft !== st.draft) {set({ draft });- writeDraft(DRAFT_KEY, draft);+ if (surface !== "jarvis" || !sessionId) writeDraft(DRAFT_KEY, draft);+ }+ // Upgrade an existing local pick once, so voice can use it before+ // the person sends another chat message.+ if (surface === "jarvis" && !sessionId && !catalog.selection && known && revision === selectionRevision) {+ const selection = { provider: draft.provider, model: draft.model, effort: draft.effort, ...(draft.accountId ? { account_id: draft.accountId } : {}) };+ selectionWrite = selectionWrite.catch(() => undefined).then(() => saveChatSelection(selection));+ try {+ await selectionWrite;+ } catch (err) {+ set({ lastError: errorText(err) });+ }}if (draft.provider) void get().loadModels(draft.provider);} catch (err) {@@ -547,6 +568,8 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =setDraft: async (patch) => {const st = get();+ const changesSelection = patch.provider !== undefined || patch.model !== undefined || patch.effort !== undefined;+ if (changesSelection) ++selectionRevision;let draft: ComposerDraft = { ...st.draft, ...patch };// A provider change re-seats model / effort / permission on the new// provider's defaults unless the caller set them explicitly.@@ -556,6 +579,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =draft = {...draft,model: patch.model ?? p.default_model,+ accountId: patch.accountId ?? "",effort: patch.effort ?? p.default_effort,permissionMode: patch.permissionMode ?? p.default_permission_mode,buildMode: patch.permissionMode ?? p.default_permission_mode,@@ -569,6 +593,15 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =writeDraft(DRAFT_KEY, draft);// With a session open, the pick applies to it right away.const sid = st.activeSessionId;+ if (surface === "jarvis" && changesSelection && !sid && draft.provider) {+ const selection = { provider: draft.provider, model: draft.model, effort: draft.effort, ...(draft.accountId ? { account_id: draft.accountId } : {}) };+ selectionWrite = selectionWrite.catch(() => undefined).then(() => saveChatSelection(selection));+ try {+ await selectionWrite;+ } catch (err) {+ set({ lastError: errorText(err) });+ }+ }if (sid) {const body: PatchSessionInput = {};if (patch.provider !== undefined) body.provider = draft.provider;@@ -580,8 +613,11 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =if (patch.cwd !== undefined) body.cwd = draft.cwd;const revision = (patchRevisions.get(sid) ?? 0) + 1;patchRevisions.set(sid, revision);- const previous = patchQueues.get(sid) ?? Promise.resolve();+ const previous = surface === "jarvis"+ ? selectionWrite.catch(() => undefined)+ : patchQueues.get(sid) ?? Promise.resolve();const pending = previous.then(() => patchAgentChatSession(sid, body));+ if (surface === "jarvis") selectionWrite = pending;patchQueues.set(sid, pending.then(() => undefined, () => undefined));try {const session = await pending;@@ -627,6 +663,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =closeSocket();++catalogRequest;set({+ ...(surface === "jarvis" ? { draft: readDraft(DRAFT_KEY) } : {}),activeSessionId: null,activeSession: null,timeline: EMPTY_TIMELINE,@@ -677,10 +714,12 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =set({ busy: true, lastError: null });let sid = st.activeSessionId;try {+ await selectionWrite;if (!sid) {const d = st.draft;const session = await createAgentChatSession({provider: d.provider,+ ...(d.accountId ? { account_id: d.accountId } : {}),model: d.model,effort: d.effort,cwd: d.cwd || null,@@ -697,6 +736,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =connect(sid, 0);}await sendAgentChatMessage(sid, content, attachments, toolChoices);+ if (surface === "jarvis") writeDraft(DRAFT_KEY, st.draft);if (get().activeSessionId === sid) void get().loadSessions();return get().activeSessionId === sid ? "sent" : "stale";} catch (err) {@@ -750,7 +790,7 @@ export function createAgentChatStore(surface: AgentChatSurface, draftNamespace =const session = { ...st.activeSession, ...tl.sessionPatch } as AgentChatSession;patch.activeSession = session;patch.draft = draftFromSession(session, st.draft);- writeDraft(DRAFT_KEY, patch.draft);+ if (surface !== "jarvis") writeDraft(DRAFT_KEY, patch.draft);}set(patch);if (event.kind === "turn_finished" || event.kind === "user_message") void st.loadSessions();diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.pyindex 1e67bb24b6..6df8a1561c 100644--- a/jarvis/ui/web/society_routes.py+++ b/jarvis/ui/web/society_routes.py@@ -294,6 +294,19 @@ async def create_agent(body: CreateAgentBody, request: Request) -> dict[str, Any)description = compose_description(body.description, body.model_dump(include=set(BRIEF_FIELDS)))creator = await _creator_from_request(request, rt)+ # Voice has no Society session. Its new agents still inherit the last+ # explicit chat seat, never the realtime credential or the Tool Model.+ if not fields.get("provider") and (creator is None or creator.agent_id == rt.lead_id):+ from .agent_chat_routes import _service_from_state++ svc = _service_from_state(request.app.state)+ if svc is None and getattr(request.app.state, "agent_chat_factory", None) is not None:+ raise HTTPException(503, "The saved Jarvis chat model is temporarily unavailable")+ selection = svc.store.chat_selection() if svc is not None else None+ if selection is not None:+ for key, value in selection.to_dict().items():+ if not fields.get(key):+ fields[key] = valueif creator is not None:from jarvis.society.inherit import inherit_creator_fieldsdiff --git a/tests/unit/agent_chat/test_chat_selection.py b/tests/unit/agent_chat/test_chat_selection.pynew file mode 100644index 0000000000..64a121b503--- /dev/null+++ b/tests/unit/agent_chat/test_chat_selection.py@@ -0,0 +1,300 @@+"""The chat pick survives restart and seats voice-created agents without inference."""++from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agent_chat.service import AgentChatService+from jarvis.agent_chat.store import AgentChatStore, ChatSelection+from jarvis.society.runtime import SocietyRuntime+from jarvis.ui.web import agent_chat_routes+from jarvis.ui.web.society_routes import router as society_router+++def app(tmp_path, monkeypatch):+ async def no_live_models():+ return {}++ monkeypatch.setattr(agent_chat_routes, "_live_cli_models", no_live_models)+ monkeypatch.setattr(agent_chat_routes, "_cli_installed", lambda runner: False)+ monkeypatch.setattr("jarvis.agent_chat.service._claude_cli_installed", lambda: False)+ application = FastAPI()+ application.include_router(agent_chat_routes.router)+ application.include_router(society_router)+ application.state.agent_chat = AgentChatService(AgentChatStore(tmp_path / "chat.db"))+ runtime = SocietyRuntime(tmp_path / "society", seed_starter_team=False)+ application.state.society_factory = lambda: runtime+ return application+++def test_selection_survives_restart_without_creating_a_chat(tmp_path: Path):+ db = tmp_path / "chat.db"+ store = AgentChatStore(db)+ selection = ChatSelection("claude-api", "claude-sonnet-5-5", "high", "account-a")+ store.save_chat_selection(selection)+ store.close()+ reopened = AgentChatStore(db)+ assert reopened.chat_selection() == selection+ assert reopened.list_sessions() == []+ reopened.close()+++def test_legacy_choice_comes_from_the_last_user_chat_not_background_activity():+ store = AgentChatStore()+ earlier = store.create_session(+ provider="openai", model="earlier", effort="", cwd="", surface="jarvis"+ )+ latest = store.create_session(+ provider="ollama", model="last-used", effort="", cwd="", surface="jarvis"+ )+ ide = store.create_session(+ provider="openai-codex", model="ide", effort="", cwd="", surface="agent"+ )+ for session, timestamp, payload in [+ (earlier, 100, {"text": "first"}),+ (latest, 200, {"text": "latest user chat"}),+ (ide, 300, {"text": "unrelated IDE work"}),+ (earlier, 400, {"text": "automatic continuation", "origin": "control"}),+ ]:+ store.append_event(+ session.session_id, {"kind": "user_message", "ts_ms": timestamp, "payload": payload}+ )+ assert store.chat_selection() == ChatSelection("ollama", "last-used")+ store.save_chat_selection(ChatSelection("openai-codex", "explicit-new-choice"))+ assert store.chat_selection() == ChatSelection("openai-codex", "explicit-new-choice")+ store.close()+++ "provider,model",+ [+ ("claude-api", "claude-sonnet-5-5"),+ ("openai-codex", "gpt-5.4"),+ ("ollama", "local-model"),+ ],+)+def test_pick_catalog_and_voice_created_agent_share_the_exact_model(app, provider, model):+ with TestClient(app) as client:+ pick = {"provider": provider, "model": model, "effort": ""}+ response = client.put("/api/agent-chat/selection", json=pick)+ assert response.status_code == 200, response.text+ catalog = client.get("/api/agent-chat/catalog?surface=jarvis").json()+ assert catalog["selection"] == {**pick, "account_id": ""}+ assert client.get("/api/agent-chat/catalog?surface=agent").json()["selection"] is None+ # A voice tool call carries no Society chat header.+ response = client.post("/api/society/agents", json={"name": "Helper"})+ assert response.status_code == 200, response.text+ agent = response.json()["agent"]+ assert (agent["provider"], agent["model"]) == (provider, model)+ runtime = app.state.society+ from jarvis.society.chat_binding import ensure_session+ from jarvis.society.roster import AgentRecord++ bound = ensure_session(app.state.agent_chat, SimpleNamespace(), AgentRecord.from_row(agent))+ assert (bound.provider, bound.model) == (provider, model)+ assert runtime is not None+++def test_explicit_seat_does_not_mix_in_remembered_model_or_account(app):+ app.state.agent_chat.store.save_chat_selection(+ ChatSelection("claude-api", "claude-sonnet-5-5", "high", "claude-account")+ )+ with TestClient(app) as client:+ inherited = client.post("/api/society/agents", json={"name": "Inherited"}).json()["agent"]+ explicit = client.post(+ "/api/society/agents",+ json={+ "name": "Explicit",+ "provider": "openai-codex",+ "model": "gpt-5.4",+ },+ ).json()["agent"]+ assert inherited["account_id"] == "claude-account"+ assert explicit["model"] == "gpt-5.4"+ assert explicit["account_id"] == ""+ assert explicit["effort"] == ""+++def test_unknown_provider_does_not_replace_a_saved_pick(app):+ selection = ChatSelection("openai-codex", "gpt-5.4")+ app.state.agent_chat.store.save_chat_selection(selection)+ with TestClient(app) as client:+ assert (+ client.put("/api/agent-chat/selection", json={"provider": "missing"}).status_code == 400+ )+ assert app.state.agent_chat.store.chat_selection() == selection+++def test_voice_creation_loads_the_saved_selection_before_chat_is_opened(app):+ service = app.state.agent_chat+ service.store.save_chat_selection(ChatSelection("openai-codex", "chat-model"))+ app.state.agent_chat = None+ app.state.agent_chat_factory = lambda: service+ with TestClient(app) as client:+ response = client.post("/api/society/agents", json={"name": "After restart"})+ assert response.status_code == 200, response.text+ assert response.json()["agent"]["model"] == "chat-model"+++def test_unavailable_selection_store_never_falls_back_to_a_different_model(app):+ def unavailable():+ raise OSError("database unavailable")++ app.state.agent_chat = None+ app.state.agent_chat_factory = unavailable+ with TestClient(app) as client:+ response = client.post("/api/society/agents", json={"name": "Must not fall back"})+ assert response.status_code == 503+++def test_chat_account_is_preserved_on_new_session(app, tmp_path, monkeypatch):+ from jarvis import agent_accounts++ monkeypatch.setattr(agent_accounts, "resolve", lambda value: SimpleNamespace(platform="codex"))+ with TestClient(app) as client:+ response = client.post(+ "/api/agent-chat/sessions",+ json={+ "surface": "jarvis",+ "provider": "openai-codex",+ "model": "chat-model",+ "account_id": "chosen-account",+ "cwd": str(tmp_path),+ },+ )+ assert response.status_code == 201, response.text+ assert response.json()["account_id"] == "chosen-account"+ agent = client.post("/api/society/agents", json={"name": "Same account"}).json()["agent"]+ assert agent["account_id"] == "chosen-account"+++def test_selection_contract_matches_sql_api_and_frontend(app):+ import re+ from dataclasses import fields++ from jarvis.ui.web.agent_chat_routes import ChatSelectionBody++ keys = {field.name for field in fields(ChatSelection)}+ assert keys == set(ChatSelectionBody.model_fields)+ columns = app.state.agent_chat.store._conn.execute("PRAGMA table_info(jarvis_chat_selection)")+ assert {column["name"] for column in columns} - {"id"} == keys+ source = Path("jarvis/ui/web/frontend/src/lib/agentChatApi.ts").read_text(encoding="utf-8")+ body = re.search(r"export interface ChatSelection \{([^}]+)\}", source).group(1)+ assert set(re.findall(r"^\s*(\w+)\??:", body, re.MULTILINE)) == keys+ operation = app.openapi()["paths"]["/api/agent-chat/selection"]["put"]+ assert operation["tags"] == ["agent-chat"]+ assert operation["summary"]+++def test_society_creator_keeps_its_own_seat_even_when_jarvis_selected_another(app):+ app.state.agent_chat.store.save_chat_selection(ChatSelection("openai-codex", "jarvis-model"))+ with TestClient(app) as client:+ creator = client.post(+ "/api/society/agents",+ json={+ "name": "Creator",+ "provider": "ollama",+ "model": "creators-model",+ },+ ).json()["agent"]+ response = client.post(+ "/api/society/agents",+ json={"name": "Child"},+ headers={"X-Jarvis-Chat-Session": f"society:{creator['agent_id']}"},+ )+ assert response.status_code == 200, response.text+ child = response.json()["agent"]+ assert (child["provider"], child["model"]) == ("ollama", "creators-model")+++def test_switching_provider_clears_the_previous_subscription_account(app, tmp_path):+ svc = app.state.agent_chat+ session = svc.create_session(+ provider="openai-codex",+ model="chat-model",+ surface="jarvis",+ cwd=str(tmp_path),+ account_id="codex-account",+ )+ with TestClient(app) as client:+ response = client.patch(+ f"/api/agent-chat/sessions/{session.session_id}",+ json={+ "provider": "ollama",+ "model": "local-model",+ "effort": "",+ },+ )+ assert response.status_code == 200, response.text+ assert response.json()["account_id"] == ""+ assert svc.store.chat_selection() == ChatSelection("ollama", "local-model")+++def test_opening_history_and_other_surfaces_do_not_replace_selection(app, tmp_path):+ store = app.state.agent_chat.store+ old = store.create_session(+ provider="openai", model="old", effort="", surface="jarvis", cwd=str(tmp_path)+ )+ selection = ChatSelection("openai-codex", "gpt-5.4")+ store.save_chat_selection(selection)+ with TestClient(app) as client:+ assert client.get(f"/api/agent-chat/sessions/{old.session_id}").status_code == 200+ response = client.post(+ "/api/agent-chat/sessions",+ json={+ "surface": "agent",+ "provider": "openai",+ "model": "ide-model",+ "cwd": str(tmp_path),+ },+ )+ assert response.status_code == 201, response.text+ assert store.chat_selection() == selection+++async def test_chat_send_keeps_its_pick_when_global_worker_differs(app, tmp_path, monkeypatch):+ from jarvis.agent_chat import service+ from jarvis.core import runtime_refs, task_agent++ seen = []++ async def record_turn(handle, prompt, runner, **kwargs):+ session = handle.session+ seen.append((session.provider, session.model, session.effort))++ async def selected_subscription(provider):+ return (provider, "codex-cli")++ monkeypatch.setattr(task_agent, "subscription_seat_off_loop", selected_subscription)+ monkeypatch.setattr(service, "run_cli_turn", record_turn)+ monkeypatch.setattr(+ runtime_refs,+ "get_brain_manager",+ lambda: SimpleNamespace(+ _config=SimpleNamespace(+ brain=SimpleNamespace(+ worker=SimpleNamespace(+ provider="openai",+ model="unwanted-api-model",+ reasoning_effort="low",+ )+ )+ ),+ ),+ )+ svc = app.state.agent_chat+ session = svc.create_session(+ provider="openai-codex",+ model="chat-model",+ effort="high",+ surface="jarvis",+ cwd=str(tmp_path),+ )+ await svc.send(session.session_id, "Hello")+ await svc._running[session.session_id].task+ assert seen == [("openai-codex", "chat-model", "high")]+ assert svc.store.chat_selection() == ChatSelection("openai-codex", "chat-model", "high")