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
@ feat(agentic-ide): let the user choose who writes the task briefs
Ruben Lütkef2a09b188ff9
diff --git a/jarvis/agentic_ide/writer.py b/jarvis/agentic_ide/writer.pyindex a566fdf3b2..c8ef90e073 100644--- a/jarvis/agentic_ide/writer.py+++ b/jarvis/agentic_ide/writer.py@@ -9,12 +9,23 @@ The order, and why each rung is where it is:1. **A pin is a pin.** ``api`` never touches a subscription — a user who chosethe API tier must not have their plan quota spent behind their back — and a- named provider or ``subscription`` never quietly falls back to the API key,- which is the same surprise in the other direction. An unhonourable pin- degrades to the caller's deterministic layer, which is at least honest.-2. **``auto`` prefers a connected subscription**, because it is work the user+ named provider, ``tool_model`` or ``subscription`` never quietly falls back+ to the API key, which is the same surprise in the other direction. An+ unhonourable pin degrades to the caller's deterministic layer, which is at+ least honest.+2. **``tool_model`` means the model the user already chose**, in the Tool Model+ tab, for work the assistant does on its own behalf. It resolves through+ ``resolve_tool_model_brain`` and nowhere else: a Tool Model pin that quietly+ landed on a coding CLI would make the setting meaningless.+3. **``auto`` prefers a connected subscription**, because it is work the userhas already paid for, then crosses to the API tier if none answers.-3. **Nothing qualifies → ``(None, "")``**, and the caller says so.+4. **Nothing qualifies → ``(None, "")``**, and the caller says so.++The distinction users actually make here is "an API key I pay per token for"+versus "a coding CLI I already subscribe to" — and which CLI that is differs+per install. Nothing in this module names a vendor: the subscription rung asks+the provider cards which providers bill that way (AP-21/22), so whichever CLI+the user connected is the one that writes.Never raises. Every failure here costs a rougher prompt; none of them may costthe user their instruction.@@ -44,6 +55,12 @@ def _quality(config: Any) -> Any:return resolve_quality_brain(config)+def _tool_model(config: Any) -> Any:+ from jarvis.brain.resolver import resolve_tool_model_brain++ return resolve_tool_model_brain(config)++def _configured_choice(config: Any) -> str:raw = getattr(getattr(config, "agentic_ide", None), "prompt_writer", "auto")return str(raw or "auto").strip() or "auto"@@ -68,6 +85,9 @@ def resolve_writer(*, cli_timeout_s: float | None = None) -> tuple[Any | None, sif choice == "api":return _api_writer(config)+ if choice == "tool_model":+ return _tool_model_writer(config)+subscription = _try_subscription(config, cli_timeout_s)if subscription is not None:name = getattr(subscription, "name", None) or choice@@ -105,4 +125,30 @@ def _api_writer(config: Any) -> tuple[Any | None, str]:return (brain, "api") if brain is not None else (None, "")+def _tool_model_writer(config: Any) -> tuple[Any | None, str]:+ """The user's configured Tool Model, or ``(None, "")``.++ Does NOT fall through to the quality tier when the Tool Model is unset or+ unreachable. "Use the model I picked" and "use whatever is left" are+ different answers, and a user who chose this option to stop briefs being+ written by a coding CLI would be no better off if it silently landed on a+ third model instead. The caller degrades to its deterministic prompt and+ reports that honestly.+ """+ try:+ brain = _tool_model(config)+ except Exception: # noqa: BLE001 - a broken selection costs the brief, not the turn+ logger.info("Agentic IDE tool-model writer unavailable", exc_info=True)+ return None, ""+ if brain is None:+ logger.info(+ "Agentic IDE writer pinned to the Tool Model, but no usable Tool "+ "Model is configured — using the deterministic prompt rather than "+ "silently writing with another model"+ )+ return None, ""+ name = getattr(brain, "name", None) or "tool model"+ return brain, f"tool_model:{name}"++__all__ = ["resolve_writer"]diff --git a/jarvis/brain/resolver.py b/jarvis/brain/resolver.pyindex f2a452dce8..25c19f24b3 100644--- a/jarvis/brain/resolver.py+++ b/jarvis/brain/resolver.py@@ -232,6 +232,92 @@ def resolve_quality_brain(return None+def _tool_model_selection(config: JarvisConfig) -> tuple[str, str | None]:+ """The Tool Model the user picked: ``(provider, model)``.++ Mirrors what the Tool Model settings tab persists and displays, so the two+ can never disagree about which model the user chose. Both halves are read+ the same defensive way that tab reads them:++ * The tier carries the provider, under the canonical ``tool_model`` name+ with ``computer_use`` still accepted as its read-time alias.+ * The MODEL is a per-provider override — a user who picks a provider+ usually means "that provider's tool model", not its chat default — with+ the provider's plain ``model`` as the floor when no override is set.++ ``("auto", None)`` means the user never pinned one; the caller decides what+ that is worth. Never raises: a malformed section reads as unset.+ """+ try:+ brain_cfg = config.brain+ tier = getattr(brain_cfg, "tool_model", None) or getattr(+ brain_cfg, "computer_use", None+ )+ provider = str(getattr(tier, "provider", None) or "auto").strip() or "auto"+ if provider == "auto":+ return "auto", None+ provider_cfg = brain_cfg.providers.get(provider)+ model = (+ getattr(provider_cfg, "tool_model", None)+ or getattr(provider_cfg, "cu_model", None)+ or getattr(provider_cfg, "model", None)+ )+ return provider, (str(model).strip() or None) if model else None+ except Exception: # noqa: BLE001 - an unreadable section is an unset one+ log.info("tool-model selection could not be read", exc_info=True)+ return "auto", None+++def resolve_tool_model_brain(+ config: JarvisConfig,+ *,+ bus: EventBus | None = None,+) -> Brain | None:+ """The user's configured Tool Model as a Brain, or None.++ Exists because "which model does my own work" is a question the user has+ already answered once, in the Tool Model tab, and callers whose OUTPUT is+ the product should be able to honour that answer instead of running a+ separate chain that lands somewhere else. The Agentic IDE's prompt writer+ is the first: a user who deliberately pointed the Tool Model at a strong+ model and then found their task briefs written by whichever coding CLI+ happened to be signed in has been given a setting that does not settle+ anything.++ Deliberately NOT a chain. A tier resolver walks candidates until one+ answers, which is right when the goal is that a core path never dies; here+ the goal is the opposite — do what the user picked, or say you could not.+ Falling through to a different model would reintroduce exactly the silent+ substitution this resolver exists to end.++ Returns None when no Tool Model is pinned (``auto``), when the pinned+ provider is not installed in this build, or when it cannot be instantiated+ — a missing key being the ordinary case. Never raises.+ """+ _ensure_bus_subscription(bus)+ provider, model = _tool_model_selection(config)+ if provider == "auto":+ log.debug("resolve_tool_model_brain: no Tool Model pinned")+ return None++ cache_key = (provider, model or "")+ cached = _cache.get(cache_key)+ if cached is not None:+ return cached+ try:+ brain = _get_registry().instantiate(+ provider, **({"model": model} if model else {}),+ )+ except Exception as exc: # noqa: BLE001 - a caller must degrade, not crash+ log.info(+ "resolve_tool_model_brain: %s/%s not instantiable (%s)",+ provider, model or "<default>", type(exc).__name__,+ )+ return None+ _cache[cache_key] = brain+ return brain++def resolve_vision_brain(config: JarvisConfig,*,diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 769b90af09..4074d0ddaf 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -2542,17 +2542,93 @@ def _current_prompt_writer() -> str:return "auto"+def _provider_label(provider: str) -> str:+ """A provider's own display name, falling back to its id.++ The picker must name the CLI the user actually connected. Reading it from+ the provider card rather than mapping ids here is what keeps that true for+ a CLI this file has never heard of (AP-21).+ """+ try:+ from .provider_spec import get_spec++ spec = get_spec(provider)+ return str(getattr(spec, "label", "") or provider) if spec else provider+ except Exception: # noqa: BLE001 - a label is decoration, the id is the value+ return provider+++def _tool_model_option() -> PromptWriterOption:+ """The "use the model I already picked" option, named so it is recognisable.++ The label carries the actual selection because that is the whole question+ the user is answering. "Tool Model" alone tells someone nothing about which+ model would write their briefs; "Tool Model (Gemini)" does, and an install+ with nothing pinned says so instead of offering a choice that cannot run.+ """+ try:+ from jarvis.brain.resolver import _tool_model_selection+ from jarvis.core.config import load_config++ provider, model = _tool_model_selection(load_config())+ except Exception: # noqa: BLE001 - a settings page must still render+ log.info("prompt-writer: tool-model probe failed", exc_info=True)+ provider, model = "auto", None++ if provider == "auto":+ return PromptWriterOption(+ id="tool_model",+ label="Tool Model (none selected yet)",+ connected=False,+ )+ # Plain ASCII separator: this label is rendered in the desktop UI but also+ # printed by `jarvis api agentic-ide prompt-writer`, and a terminal's+ # encoding is not ours to assume (CLAUDE.md §5, Windows defaults to cp1252).+ detail = f"{_provider_label(provider)}"+ if model:+ detail = f"{detail} - {model}"+ return PromptWriterOption(+ id="tool_model",+ label=f"Tool Model ({detail})",+ connected=_tool_model_usable(provider),+ )+++def _tool_model_usable(provider: str) -> bool:+ """Whether the pinned Tool Model could write right now.++ Checked without instantiating anything: a settings page asks this on every+ render, and the two things that actually block it — the provider not being+ in this build, and its credential being absent — are both cheap to read.+ """+ try:+ from jarvis.brain.app_control import is_credential_present+ from jarvis.brain.provider_registry import BrainProviderRegistry++ from .provider_spec import get_spec++ spec = get_spec(provider)+ if spec is None or provider not in set(BrainProviderRegistry().available()):+ return False+ return bool(is_credential_present(spec))+ except Exception: # noqa: BLE001 - unknown means "do not promise it works"+ log.info("prompt-writer: tool-model usability probe failed", exc_info=True)+ return False++def _writer_options() -> list[PromptWriterOption]:+ candidates = _writer_candidates()options = [PromptWriterOption(id="auto",label="Automatic (a connected subscription, else the API model)",connected=True,),+ _tool_model_option(),PromptWriterOption(id="subscription",- label="Any connected subscription (never an API key)",- connected=any(connected for _id, connected in _writer_candidates()),+ label="Any connected coding CLI (never an API key)",+ connected=any(connected for _id, connected in candidates),),PromptWriterOption(id="api",@@ -2560,9 +2636,11 @@ def _writer_options() -> list[PromptWriterOption]:connected=True,),]- for provider, connected in _writer_candidates():+ for provider, connected in candidates:options.append(- PromptWriterOption(id=provider, label=provider, connected=connected)+ PromptWriterOption(+ id=provider, label=_provider_label(provider), connected=connected+ ))return options@@ -2604,13 +2682,17 @@ async def set_prompt_writer(payload: PromptWriterRequest) -> PromptWriterState:),)if not match.connected:- raise HTTPException(- status_code=409,- detail=(- f"'{requested}' is not signed in on this machine. Connect it "- "first, or choose 'auto'."- ),+ # Name the actual blocker. "Not signed in" is true of a coding CLI and+ # nonsense about a Tool Model, and a user sent to fix the wrong thing+ # gives up on the setting rather than on the diagnosis.+ detail = (+ "No usable Tool Model is configured. Pick one in the Tool Model "+ "settings — with its API key entered — then choose it here."+ if requested == "tool_model"+ else f"'{match.label}' is not signed in on this machine. Connect it "+ "first, or choose 'auto'.")+ raise HTTPException(status_code=409, detail=detail)_persist_prompt_writer(requested)return PromptWriterState(prompt_writer=requested, options=_writer_options())diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex 37f53d23b9..f33d55ef7a 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useState } from "react";import { ArrowUp, Bot, CreditCard, FlaskConical, Laptop, Lock, LogIn, LogOut, Sparkles, Terminal, type LucideIcon } from "lucide-react";import { agentBrandNow, useAgentBrand } from "@/lib/agentBrand";+import { PromptWriterCard } from "@/components/PromptWriterCard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";import { useEventStore } from "@/store/events";@@ -238,6 +239,12 @@ export function JarvisAgentSection({users come back for, so it must not hide below the provider cards. */}<SubagentModelCard status={bridge} onSaved={reload} />+ {/* Who writes the Agentic-IDE briefs. Sits next to the model pin because+ it is the same kind of decision — which model does work on the user's+ behalf — and because the two columns below are exactly the choice it+ is about: a subscription login on the left, an API key on the right. */}+ <PromptWriterCard />+{/* Scoped Agent keys are managed here. Older shared Brain keys remain acompatibility fallback and are labelled honestly on the relevant card. */}<p className="flex items-start gap-2 px-1 text-[11px] leading-relaxed text-muted-foreground">diff --git a/jarvis/ui/web/frontend/src/components/PromptWriterCard.test.tsx b/jarvis/ui/web/frontend/src/components/PromptWriterCard.test.tsxnew file mode 100644index 0000000000..c9fcf7f296--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/PromptWriterCard.test.tsx@@ -0,0 +1,109 @@+/**+ * Component tests for the brief-writer picker.+ *+ * The cases that matter are the ones where a wrong pixel means the wrong thing+ * gets billed, or a user cannot find out why their subscription sits idle:+ * that the CLI is named as the one THIS install connected rather than a vendor+ * this file guessed, that an option which cannot write is visible but+ * unselectable, and that a rejected save shows the server's reason instead of+ * a generic one — the server's reason is the one that names the fix.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";++import { PromptWriterCard } from "@/components/PromptWriterCard";+import { fetchPromptWriter, savePromptWriter } from "@/lib/agenticIdeApi";++vi.mock("@/lib/agenticIdeApi", async () => {+ const actual =+ await vi.importActual<typeof import("@/lib/agenticIdeApi")>("@/lib/agenticIdeApi");+ return { ...actual, fetchPromptWriter: vi.fn(), savePromptWriter: vi.fn() };+});++const mockFetch = vi.mocked(fetchPromptWriter);+const mockSave = vi.mocked(savePromptWriter);++const STATE = {+ prompt_writer: "auto",+ options: [+ { id: "auto", label: "Automatic (a connected subscription, else the API model)", connected: true },+ { id: "tool_model", label: "Tool Model (Google Gemini - gemini-3.6-flash)", connected: true },+ { id: "subscription", label: "Any connected coding CLI (never an API key)", connected: true },+ { id: "api", label: "API model (billed per token)", connected: true },+ { id: "antigravity", label: "Antigravity (Google subscription)", connected: true },+ ],+};++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe("PromptWriterCard", () => {+ it("names the Tool Model and the connected CLI as the server reports them", async () => {+ mockFetch.mockResolvedValue(STATE);+ render(<PromptWriterCard />);++ // The label carries the actual model, so the choice is informed rather+ // than a bare "Tool Model" the user has to go and look up.+ expect(+ await screen.findByText(/Tool Model \(Google Gemini - gemini-3\.6-flash\)/),+ ).toBeTruthy();+ // And the CLI is the one this install connected, under its own name.+ expect(screen.getByText("Antigravity (Google subscription)")).toBeTruthy();+ });++ it("persists the choice the user clicks", async () => {+ mockFetch.mockResolvedValue(STATE);+ mockSave.mockResolvedValue({ ...STATE, prompt_writer: "tool_model" });+ render(<PromptWriterCard />);++ fireEvent.click(await screen.findByText(/Tool Model \(Google Gemini/));++ await waitFor(() => expect(mockSave).toHaveBeenCalledWith("tool_model"));+ });++ it("shows an unusable option, but does not let it be chosen", async () => {+ // Hiding the row is what leaves "why is my subscription not an option?"+ // unanswerable from this screen.+ mockFetch.mockResolvedValue({+ prompt_writer: "auto",+ options: [+ { id: "auto", label: "Automatic", connected: true },+ { id: "tool_model", label: "Tool Model (none selected yet)", connected: false },+ ],+ });+ render(<PromptWriterCard />);++ const row = (await screen.findByText(/Tool Model \(none selected yet\)/)).closest(+ "button",+ );+ expect(row).toBeTruthy();+ expect((row as HTMLButtonElement).disabled).toBe(true);++ fireEvent.click(row as HTMLButtonElement);+ expect(mockSave).not.toHaveBeenCalled();+ });++ it("surfaces the server's own reason when a choice is refused", async () => {+ mockFetch.mockResolvedValue(STATE);+ mockSave.mockRejectedValue(+ new Error("No usable Tool Model is configured. Pick one in the Tool Model settings"),+ );+ render(<PromptWriterCard />);++ fireEvent.click(await screen.findByText(/Tool Model \(Google Gemini/));++ const alert = await screen.findByRole("alert");+ expect(alert.textContent).toContain("Pick one in the Tool Model settings");+ });++ it("says so when it cannot read the current setting", async () => {+ // An empty picker would read as "there are no options", which is a+ // different and wrong story.+ mockFetch.mockRejectedValue(new Error("offline"));+ render(<PromptWriterCard />);++ expect(await screen.findByRole("alert")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/PromptWriterCard.tsx b/jarvis/ui/web/frontend/src/components/PromptWriterCard.tsxnew file mode 100644index 0000000000..264f0f2795--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/PromptWriterCard.tsx@@ -0,0 +1,210 @@+import { useCallback, useEffect, useState } from "react";+import { Check, Loader2, Sparkles, Terminal, Wand2 } from "lucide-react";+import {+ fetchPromptWriter,+ savePromptWriter,+ type PromptWriterOption,+ type PromptWriterState,+} from "@/lib/agenticIdeApi";+import { cn } from "@/lib/utils";+import { useT } from "@/i18n";++/**+ * Who writes Agentic-IDE task briefs: the Tool Model, or a connected coding CLI.+ *+ * The choice exists because the two are billed and sourced completely+ * differently — a coding CLI runs against a subscription the user already pays+ * for, the Tool Model against an API key billed per token — and until now the+ * decision was made for them by a resolver order they could not see. A user who+ * had deliberately pinned a strong Tool Model still found their briefs written+ * by whichever CLI happened to be signed in.+ *+ * Two properties this card has to keep:+ *+ * * **It names the real thing.** Every label comes from the server, which reads+ * it off the provider card — so the CLI shown is the one this install+ * actually connected, and the Tool Model row carries the model the user+ * picked. Nothing here hardcodes a vendor; an install with a CLI this file+ * has never heard of lists it correctly.+ * * **An option that cannot run is disabled, not hidden.** "Why is my+ * subscription not an option" is the question this screen exists to answer,+ * and a silently absent row answers nothing.+ */+export function PromptWriterCard() {+ const t = useT();+ const [state, setState] = useState<PromptWriterState | null>(null);+ const [pending, setPending] = useState<string | null>(null);+ // Two separate failures, because they have different lifetimes. The load+ // error is a property of the current data; the save error is a message from+ // the server about the last thing the user tried, and it has to survive the+ // re-renders that follow. Holding both in one string let a re-render's+ // reload wipe the save error before it could be read.+ const [loadFailed, setLoadFailed] = useState(false);+ const [saveError, setSaveError] = useState("");+ const [loading, setLoading] = useState(true);++ // Deliberately no dependencies: this must run once per mount. Depending on+ // `t` re-ran it on every render, which reset the state mid-interaction.+ const load = useCallback(async () => {+ try {+ setState(await fetchPromptWriter());+ setLoadFailed(false);+ } catch {+ // A settings card that cannot read its own state says so rather than+ // rendering an empty picker that looks like "no options exist".+ setLoadFailed(true);+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void load();+ }, [load]);++ const choose = async (id: string) => {+ if (pending || state?.prompt_writer === id) return;+ setPending(id);+ setSaveError("");+ try {+ setState(await savePromptWriter(id));+ } catch (err) {+ // The server's own message names the blocker — an unsigned CLI, a Tool+ // Model with no key. Showing ours instead would send the user to fix the+ // wrong thing.+ setSaveError(+ err instanceof Error && err.message+ ? err.message+ : t("prompt_writer.save_failed"),+ );+ } finally {+ setPending(null);+ }+ };++ const error = saveError || (loadFailed ? t("prompt_writer.unavailable") : "");++ if (loading) {+ return (+ <div className="card-outline flex items-center gap-2 p-4 text-[11px] text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("prompt_writer.loading")}+ </div>+ );+ }++ const options = state?.options ?? [];+ const modes = options.filter((o) => MODE_IDS.has(o.id));+ const clis = options.filter((o) => !MODE_IDS.has(o.id));++ return (+ <div className="card-outline space-y-3 p-4" data-testid="prompt-writer-card">+ <div className="space-y-1">+ <h4 className="text-[12px] font-medium">{t("prompt_writer.title")}</h4>+ <p className="text-[11px] leading-relaxed text-muted-foreground">+ {t("prompt_writer.description")}+ </p>+ </div>++ <div className="space-y-2">+ {modes.map((option) => (+ <WriterRow+ key={option.id}+ option={option}+ selected={state?.prompt_writer === option.id}+ pending={pending === option.id}+ disabled={pending !== null}+ onSelect={choose}+ />+ ))}+ </div>++ {clis.length > 0 && (+ <div className="space-y-2">+ <p className="px-1 text-[10px] uppercase tracking-wider text-muted-foreground">+ {t("prompt_writer.connected_clis")}+ </p>+ {clis.map((option) => (+ <WriterRow+ key={option.id}+ option={option}+ selected={state?.prompt_writer === option.id}+ pending={pending === option.id}+ disabled={pending !== null}+ onSelect={choose}+ />+ ))}+ </div>+ )}++ {error && (+ <p role="alert" className="text-[11px] leading-relaxed text-destructive">+ {error}+ </p>+ )}+ </div>+ );+}++/** The four selection MODES, as opposed to a concrete connected CLI. */+const MODE_IDS = new Set(["auto", "tool_model", "subscription", "api"]);++function iconFor(id: string) {+ if (id === "auto") return Wand2;+ if (id === "tool_model" || id === "api") return Sparkles;+ return Terminal;+}++function WriterRow({+ option,+ selected,+ pending,+ disabled,+ onSelect,+}: {+ option: PromptWriterOption;+ selected: boolean;+ pending: boolean;+ disabled: boolean;+ onSelect: (id: string) => void;+}) {+ const t = useT();+ const Icon = iconFor(option.id);+ // An unusable option stays visible but unselectable — except when it is+ // already the persisted choice, which the user needs to be able to see and+ // move away from.+ const blocked = !option.connected && !selected;+ return (+ <button+ type="button"+ role="radio"+ aria-checked={selected}+ disabled={blocked || disabled}+ onClick={() => onSelect(option.id)}+ className={cn(+ "flex w-full items-center gap-2.5 rounded-lg border px-3 py-2 text-left transition",+ selected+ ? "border-primary/60 bg-primary/5"+ : "border-border hover:border-primary/40",+ blocked && "cursor-not-allowed opacity-50 hover:border-border",+ )}+ >+ <Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 text-[11px] leading-snug">+ <span className="block truncate">{option.label}</span>+ {blocked && (+ <span className="block text-[10px] text-muted-foreground">+ {option.id === "tool_model"+ ? t("prompt_writer.tool_model_unset")+ : t("prompt_writer.not_connected")}+ </span>+ )}+ </span>+ {pending ? (+ <Loader2 className="h-3.5 w-3.5 shrink-0 animate-spin text-primary" />+ ) : (+ selected && <Check className="h-3.5 w-3.5 shrink-0 text-primary" />+ )}+ </button>+ );+}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 5e7f7c87e5..29121b6352 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -3288,5 +3288,15 @@"confirm": "Ausgewählte schließen","close_failed": "Diese Terminals konnten nicht geschlossen werden: {0}"}+ },+ "prompt_writer": {+ "title": "Wer die Aufgaben-Briefings schreibt",+ "description": "Wenn du einem Fenster eine Anweisung sprichst, macht ein Modell daraus zuerst ein schriftliches Briefing. Wähle welches: dein Tool-Modell, das über seinen API-Schlüssel pro Token abgerechnet wird, oder eine Coding-CLI, die du ohnehin abonniert hast.",+ "connected_clis": "Verbundene Coding-CLIs",+ "not_connected": "Auf diesem Gerät nicht angemeldet",+ "tool_model_unset": "Noch kein Tool-Modell ausgewählt",+ "loading": "Aktuelle Einstellung wird gelesen...",+ "unavailable": "Die aktuelle Einstellung konnte nicht gelesen werden.",+ "save_failed": "Diese Auswahl konnte nicht gespeichert werden."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex d2c3ca5330..59604c4400 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -3289,5 +3289,15 @@"confirm": "Close selected","close_failed": "These terminals could not be closed: {0}"}+ },+ "prompt_writer": {+ "title": "Who writes the task briefs",+ "description": "When you speak an instruction to a pane, a model turns it into a written brief first. Choose which one: your Tool Model, billed per token against its API key, or a coding CLI you are already subscribed to.",+ "connected_clis": "Connected coding CLIs",+ "not_connected": "Not signed in on this machine",+ "tool_model_unset": "No Tool Model selected yet",+ "loading": "Reading the current setting...",+ "unavailable": "The current setting could not be read.",+ "save_failed": "That choice could not be saved."}}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 2461904234..cd2916dc6e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -3288,5 +3288,15 @@"confirm": "Cerrar seleccionados","close_failed": "No se pudieron cerrar estos terminales: {0}"}+ },+ "prompt_writer": {+ "title": "Quién escribe los briefings de tareas",+ "description": "Cuando le hablas una instrucción a un panel, primero un modelo la convierte en un briefing escrito. Elige cuál: tu Modelo de Herramientas, facturado por token con su clave API, o una CLI de programación a la que ya estás suscrito.",+ "connected_clis": "CLIs de programación conectadas",+ "not_connected": "No has iniciado sesión en este equipo",+ "tool_model_unset": "Aún no has seleccionado un Modelo de Herramientas",+ "loading": "Leyendo la configuración actual...",+ "unavailable": "No se pudo leer la configuración actual.",+ "save_failed": "No se pudo guardar esa selección."}}diff --git a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.tsindex 123fc2e689..b4df0314a9 100644--- a/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts+++ b/jarvis/ui/web/frontend/src/lib/agenticIdeApi.ts@@ -1059,3 +1059,37 @@ export async function composePrompt(files: data.files ?? [],};}++// --------------------------------------------------------- prompt writer+/** One choice for who writes Agentic-IDE task briefs. */+export type PromptWriterOption = {+ id: string;+ label: string;+ /** False when this option cannot write right now — an unconnected CLI, or+ * a Tool Model that is unset or missing its key. The picker disables it+ * rather than hiding it, because "why can I not pick that" is the question+ * the user needs answered on this screen. */+ connected: boolean;+};++export type PromptWriterState = {+ prompt_writer: string;+ options: PromptWriterOption[];+};++export function fetchPromptWriter(): Promise<PromptWriterState> {+ return getJson<PromptWriterState>("/api/agentic-ide/prompt-writer");+}++/** Persist who writes the briefs. Rejects with the server's own reason — it+ * names the actual blocker (a CLI that is not signed in, a Tool Model with no+ * key), which is what the user has to act on. */+export async function savePromptWriter(id: string): Promise<PromptWriterState> {+ const res = await fetch("/api/agentic-ide/prompt-writer", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ prompt_writer: id }),+ });+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as PromptWriterState;+}diff --git a/tests/unit/agentic_ide/test_writer_resolution.py b/tests/unit/agentic_ide/test_writer_resolution.pyindex 6ff8d2f416..b848714c67 100644--- a/tests/unit/agentic_ide/test_writer_resolution.py+++ b/tests/unit/agentic_ide/test_writer_resolution.py@@ -147,3 +147,70 @@ def test_both_call_sites_use_this_module() -> None:assert ("resolve_quality_brain" not in source), f"{module.__name__} still resolves its own writer"+++def test_tool_model_pin_uses_the_model_the_user_picked(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The whole point of the setting: honour the Tool Model, nothing else."""+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("tool_model"))+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: "tool-brain")+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")++ brain, source = writer.resolve_writer()++ assert brain == "tool-brain"+ assert source.startswith("tool_model")+++def test_tool_model_pin_never_reaches_a_subscription(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A user picks the Tool Model precisely to stop a coding CLI writing their+ briefs; probing one anyway would spend a plan they chose not to use."""+ probed: list[int] = []+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("tool_model"))+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: "tool-brain")+ monkeypatch.setattr(+ writer, "_subscription", lambda cfg, timeout: probed.append(1) or "sub-brain"+ )++ brain, _source = writer.resolve_writer()++ assert brain == "tool-brain"+ assert not probed+++def test_an_unusable_tool_model_degrades_instead_of_substituting(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """"Use the model I picked" and "use whatever is left" are different+ answers. Landing on a third model would make the setting meaningless in+ exactly the way it was added to fix."""+ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("tool_model"))+ monkeypatch.setattr(writer, "_tool_model", lambda cfg: None)+ monkeypatch.setattr(writer, "_quality", lambda cfg: "api-brain")+ monkeypatch.setattr(writer, "_subscription", lambda cfg, timeout: "sub-brain")++ brain, source = writer.resolve_writer()++ assert brain is None+ assert source == ""+++def test_a_raising_tool_model_costs_the_brief_not_the_turn(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Every failure in this module degrades; none may reach the caller."""++ def _boom(_cfg: object) -> object:+ raise RuntimeError("provider exploded")++ monkeypatch.setattr(writer, "_load_config", lambda: _cfg("tool_model"))+ monkeypatch.setattr(writer, "_tool_model", _boom)++ brain, source = writer.resolve_writer()++ assert brain is None+ assert source == ""diff --git a/tests/unit/brain/test_resolve_tool_model_brain.py b/tests/unit/brain/test_resolve_tool_model_brain.pynew file mode 100644index 0000000000..f7719cfba2--- /dev/null+++ b/tests/unit/brain/test_resolve_tool_model_brain.py@@ -0,0 +1,146 @@+"""resolve_tool_model_brain — do what the user picked, or say you could not.++The Tool Model tab is where a user answers "which model does work on my behalf".+Until callers could resolve THAT answer, the Agentic IDE's brief writer ran its+own order and landed wherever that order ended — so a user who had deliberately+pinned a strong Tool Model still found their task briefs written by whichever+coding CLI happened to be signed in, with no way to tell from the UI.++The guard that matters here is the absence of a chain: this resolver must never+walk on to a second candidate. A tier resolver falls through so a core path+never dies; falling through here would reintroduce exactly the silent+substitution the setting exists to end.+"""+from __future__ import annotations++from typing import Any++import pytest++from jarvis.brain import resolver+from jarvis.core.config import BrainProviderConfig, BrainTierConfig, JarvisConfig+++class _FakeRegistry:+ """Records how each provider was instantiated."""++ def __init__(self, available: list[str], fail: tuple[str, ...] = ()) -> None:+ self._available = list(available)+ self._fail = set(fail)+ self.calls: list[tuple[str, dict[str, Any]]] = []++ def available(self) -> list[str]:+ return list(self._available)++ def instantiate(self, name: str, **kwargs: Any) -> Any:+ self.calls.append((name, dict(kwargs)))+ if name in self._fail:+ raise RuntimeError("not instantiable")+ return f"brain:{name}"++[email protected](autouse=True)+def _clean_cache() -> Any:+ resolver._reset_for_tests()+ yield+ resolver._reset_for_tests()+++def _cfg(provider: str | None, **provider_fields: Any) -> JarvisConfig:+ config = JarvisConfig()+ if provider is not None:+ config.brain.tool_model = BrainTierConfig(provider=provider)+ if provider_fields:+ config.brain.providers[provider] = BrainProviderConfig(**provider_fields)+ return config+++def test_the_pinned_tool_model_is_what_gets_built(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = _FakeRegistry(["gemini", "openai"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)++ brain = resolver.resolve_tool_model_brain(_cfg("gemini", tool_model="pinned-model"))++ assert brain == "brain:gemini"+ assert registry.calls == [("gemini", {"model": "pinned-model"})]+++def test_the_per_provider_tool_model_beats_the_chat_default(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A user who picks a provider means "that provider's TOOL model" — the+ field the Tool Model tab writes — not whatever its chat default happens+ to be."""+ registry = _FakeRegistry(["gemini"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)++ resolver.resolve_tool_model_brain(+ _cfg("gemini", model="chat-default", tool_model="tool-pick")+ )++ assert registry.calls == [("gemini", {"model": "tool-pick"})]+++def test_the_plain_model_is_the_floor_when_no_override_is_set(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ registry = _FakeRegistry(["gemini"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)++ resolver.resolve_tool_model_brain(_cfg("gemini", model="chat-default"))++ assert registry.calls == [("gemini", {"model": "chat-default"})]+++def test_an_unpinned_tool_model_resolves_to_nothing(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """'auto' is the user not having answered the question. Guessing one here+ is what the whole setting exists to stop."""+ registry = _FakeRegistry(["gemini"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)++ assert resolver.resolve_tool_model_brain(_cfg("auto")) is None+ assert resolver.resolve_tool_model_brain(_cfg(None)) is None+ assert registry.calls == []+++def test_an_uninstantiable_pin_never_walks_on_to_another_provider(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The load-bearing guard: no chain. A missing key is the ordinary case,+ and answering it with a DIFFERENT model is the silent substitution this+ resolver was added to end."""+ registry = _FakeRegistry(["gemini", "openai"], fail=("gemini",))+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)++ brain = resolver.resolve_tool_model_brain(_cfg("gemini"))++ assert brain is None+ assert [name for name, _kwargs in registry.calls] == ["gemini"]+++def test_a_malformed_section_reads_as_unset_rather_than_raising() -> None:+ """A caller degrades to a plain prompt; none of them may lose the turn."""++ class _Exploding:+ @property+ def brain(self) -> Any:+ raise RuntimeError("config is broken")++ assert resolver._tool_model_selection(_Exploding()) == ("auto", None)+++def test_the_legacy_computer_use_name_still_resolves(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """`tool_model` is the canonical name; installs written before the rename+ carry `computer_use` and must keep working (AP-16 read-time alias)."""+ registry = _FakeRegistry(["gemini"])+ monkeypatch.setattr(resolver, "_get_registry", lambda: registry)+ config = JarvisConfig()+ config.brain.computer_use = BrainTierConfig(provider="gemini")++ assert resolver.resolve_tool_model_brain(config) == "brain:gemini"diff --git a/tests/unit/web/test_agentic_ide_prompt_writer_route.py b/tests/unit/web/test_agentic_ide_prompt_writer_route.pyindex 9f771b0993..8ba784cb7b 100644--- a/tests/unit/web/test_agentic_ide_prompt_writer_route.py+++ b/tests/unit/web/test_agentic_ide_prompt_writer_route.py@@ -22,7 +22,11 @@ async def test_listing_reports_the_current_choice_and_every_option(assert state.prompt_writer == "auto"ids = [option.id for option in state.options]- assert ids[:3] == ["auto", "subscription", "api"]+ # `tool_model` sits second, directly under `auto`: the two questions a user+ # opens this picker with are "stop guessing for me" and "use the model I+ # already chose", and the second must not be buried under the generic+ # billing modes.+ assert ids[:4] == ["auto", "tool_model", "subscription", "api"]assert "codex" in ids@@ -82,3 +86,96 @@ async def test_a_disconnected_subscription_cannot_be_pinned(assert excinfo.value.status_code == 409assert "not signed in" in str(excinfo.value.detail)+++async def test_the_tool_model_option_names_the_model_it_would_use(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """"Tool Model" alone tells the user nothing about what would write their+ briefs. The label carries the actual selection so the choice is informed."""+ monkeypatch.setattr(routes, "_writer_candidates", lambda: [])+ monkeypatch.setattr(routes, "_tool_model_usable", lambda provider: True)+ monkeypatch.setattr(+ routes, "_provider_label", lambda provider: "Google Gemini"+ )+ monkeypatch.setattr(+ "jarvis.brain.resolver._tool_model_selection",+ lambda config: ("gemini", "gemini-3.6-flash"),+ )++ state = await routes.prompt_writer_state()++ option = next(o for o in state.options if o.id == "tool_model")+ assert "Google Gemini" in option.label+ assert "gemini-3.6-flash" in option.label+ assert option.connected is True+++async def test_an_unpinned_tool_model_is_offered_but_not_selectable(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Hiding the row would leave "why can I not pick my Tool Model" unanswered;+ offering it as usable would persist a choice that writes nothing."""+ monkeypatch.setattr(routes, "_writer_candidates", lambda: [])+ monkeypatch.setattr(+ "jarvis.brain.resolver._tool_model_selection", lambda config: ("auto", None)+ )++ state = await routes.prompt_writer_state()++ option = next(o for o in state.options if o.id == "tool_model")+ assert option.connected is False+++async def test_choosing_an_unusable_tool_model_names_the_real_blocker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """"Not signed in" is true of a coding CLI and nonsense about a Tool Model.+ A user sent to fix the wrong thing gives up on the setting, not the error."""+ monkeypatch.setattr(routes, "_writer_candidates", lambda: [])+ monkeypatch.setattr(+ "jarvis.brain.resolver._tool_model_selection", lambda config: ("auto", None)+ )++ with pytest.raises(HTTPException) as excinfo:+ await routes.set_prompt_writer(+ routes.PromptWriterRequest(prompt_writer="tool_model")+ )++ assert excinfo.value.status_code == 409+ assert "Tool Model" in str(excinfo.value.detail)+ assert "signed in" not in str(excinfo.value.detail)+++async def test_a_usable_tool_model_can_be_chosen(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ saved: list[str] = []+ monkeypatch.setattr(routes, "_writer_candidates", lambda: [])+ monkeypatch.setattr(routes, "_tool_model_usable", lambda provider: True)+ monkeypatch.setattr(+ "jarvis.brain.resolver._tool_model_selection",+ lambda config: ("gemini", "gemini-3.6-flash"),+ )+ monkeypatch.setattr(routes, "_persist_prompt_writer", saved.append)++ state = await routes.set_prompt_writer(+ routes.PromptWriterRequest(prompt_writer="tool_model")+ )++ assert saved == ["tool_model"]+ assert state.prompt_writer == "tool_model"+++async def test_a_connected_cli_is_listed_under_its_own_name(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The picker must name the CLI this install actually connected — read off+ the provider card, never mapped from a list of vendors in this file."""+ monkeypatch.setattr(routes, "_writer_candidates", lambda: [("antigravity", True)])++ state = await routes.prompt_writer_state()++ option = next(o for o in state.options if o.id == "antigravity")+ assert option.label != "antigravity"+ assert option.label.strip()