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
claude/prompt improver tab (#597)
Ruben Lütkefdd39930d2f5
diff --git a/jarvis/agentic_ide/prompt_improver.py b/jarvis/agentic_ide/prompt_improver.pynew file mode 100644index 0000000000..306807ef38--- /dev/null+++ b/jarvis/agentic_ide/prompt_improver.py@@ -0,0 +1,258 @@+"""Improve a typed prompt before it goes to a coding agent.++The side panel's Prompt tab: the user types a rough prompt, picks the model+that rewrites it, reads the result and sends it to the pane they choose.++Deliberately not the prompt composer. The composer briefs an agent from a+SPOKEN instruction on the voice turn's clock: a fixed skeleton, a 1.2 s+budget, a deterministic fallback, always English. Here the user typed the+prompt themselves, waits for it on purpose and reads the answer before+anything is sent, so the instruction is one short paragraph they can replace,+the answer keeps their language, and a failure is reported instead of being+papered over with a template.++Two things are fixed whatever the user's instruction says: the prompt states+the goal and leaves the route to the agent (the composer's own rule, imported+so the two cannot drift), and the writer sees the repository the receiving+pane works in.++The model is the user's pick. The caller hands the picked model in as a brain+(the web route builds it from the seat an agent chat on that provider uses), so+this package stays free of the chat and agent packages; with no brain given it+is whoever writes the IDE's task briefs (``writer.resolve_writer``).+"""++from __future__ import annotations++import asyncio+from dataclasses import dataclass+from typing import Any++from loguru import logger++from .folders import ProjectProfile, probe_project+from .prompt_blueprint import GOAL_NOT_IMPLEMENTATION_RULE+from .session import MAX_PROMPT_CHARS++#: What the writer is asked to do when the user gave no instruction of their own.+DEFAULT_INSTRUCTION = (+ "Improve this prompt for the coding agent that will receive it: clear, "+ "complete and easy to act on."+)++#: Longest instruction of the user's own that is passed on.+MAX_INSTRUCTION_CHARS = 1000++#: The whole wait. A subscription CLI pays a cold process start before it+#: thinks at all, and the user is watching a spinner they started themselves.+IMPROVE_TIMEOUT_S = 90.0++#: Room for the file map in the writer's context.+_MAP_CHARS = 2400++#: The usage ledger's name for this work.+USAGE_CALLER = "prompt_improver"++_FIXED_RULES = f"""\+{GOAL_NOT_IMPLEMENTATION_RULE}++Keep everything the prompt asks for - every requirement, file, name and \+boundary. Add nothing it does not ask for: no invented requirement, constraint, \+step list or success criterion, and no general advice (follow the conventions, \+read the instructions, run the tests) - the agent does all of that on its own. \+The repository notes are there so you name things the way this codebase does; \+mention a file only when the notes show it is the place, never as a guess.++Keep it as short as the task allows: plain sentences, and a heading or list \+only when the prompt has several separate parts.++Write in the language the prompt is written in. Answer with the improved \+prompt only: no preamble, no quotes, no code fence."""+++class EmptyPrompt(ValueError):+ """There is nothing to improve."""+++class ImproverUnavailable(RuntimeError):+ """No model can take the job as asked. The message is app-authored."""+++class ImproverFailed(RuntimeError):+ """The chosen model accepted the job and did not deliver.++ Carries the exception type, never its text: a provider's error body must+ not reach a log line or the UI (AP-34).+ """+++@dataclass(frozen=True, slots=True)+class ImprovedPrompt:+ """The rewritten prompt and who wrote it."""++ text: str+ #: Where the writer came from: ``provider:<id>`` for the user's pick, else+ #: the brief writer's own source (``tool_model:…``, ``api``, ``subscription:…``).+ source: str+ #: The writing brain's name, for the "written by" line.+ writer: str+++def system_prompt(instruction: str = "") -> str:+ """The writer's instruction: the user's sentence, then the two fixed rules."""+ asked = " ".join((instruction or "").split())[:MAX_INSTRUCTION_CHARS]+ return f"{asked or DEFAULT_INSTRUCTION}\n\n{_FIXED_RULES}"+++def repo_context(folder: str, prompt: str, profile: ProjectProfile | None = None) -> str:+ """What the writer is told about the repository. Blocking; run in a thread.++ The profile (branch, stack, top-level folders, the skills and subagents the+ repo defines) plus a map of the folders that fit the prompt, taken from the+ workspace's file index when it is already built. Never waits for a walk.+ """+ if not folder:+ return ""+ from .file_index import cached_index++ profile = profile or probe_project(folder)+ lines = profile.summary_lines()+ index = cached_index(folder)+ tree = index.render_map(prompt, max_chars=_MAP_CHARS) if index is not None else ""+ if tree:+ lines += ["", "Files that fit the prompt:", tree]+ return "\n".join(lines)+++def user_block(prompt: str, context: str) -> str:+ """The writer's user turn: the repository, then the prompt to improve."""+ parts = []+ if context:+ parts.append(f"REPOSITORY\n{context}")+ parts.append(f"PROMPT TO IMPROVE\n{prompt}")+ return "\n\n".join(parts)+++def _resolve_default() -> tuple[Any, str]:+ """Whoever writes the IDE's task briefs. Blocking."""+ from .writer import resolve_writer++ brain, source = resolve_writer(cli_timeout_s=IMPROVE_TIMEOUT_S)+ if brain is None:+ raise ImproverUnavailable(+ "No model can write prompts right now. Connect a provider under API "+ "Keys, or pick a model here."+ )+ return brain, source+++def _strip_wrapping(text: str) -> str:+ """Drop a code fence a model put around the whole answer."""+ out = text.strip()+ if out.startswith("```") and out.endswith("```") and out.count("```") == 2:+ out = out[3:-3]+ # ``` may carry a language tag on its own line.+ head, _, rest = out.partition("\n")+ out = rest if rest and " " not in head.strip() else out+ return out.strip()+++async def _write(brain: Any, system: str, block: str) -> str:+ from jarvis.core.protocols import BrainMessage, BrainRequest++ request = BrainRequest(+ messages=(BrainMessage(role="user", content=block),),+ system=system,+ # A rewrite that must carry the user's intent, not a creative draft.+ temperature=0.2,+ # A goal-only prompt is far shorter; the room is for a model that+ # spends part of its budget reasoning before it answers.+ max_tokens=4096,+ stream=True,+ )+ from jarvis.costs.ledger import usage_context++ chunks: list[str] = []+ # One coroutine consumes the whole stream, so the tag is set and reset here.+ with usage_context(USAGE_CALLER):+ async for delta in brain.complete(request):+ if delta.content:+ chunks.append(delta.content)+ return "".join(chunks)+++async def improve(+ prompt: str,+ *,+ folder: str = "",+ profile: ProjectProfile | None = None,+ instruction: str = "",+ brain: Any = None,+ source: str = "",+) -> ImprovedPrompt:+ """Rewrite ``prompt``, knowing the repository in ``folder``.++ ``brain`` is the model the user picked, with ``source`` saying where it+ came from; without one the IDE's configured brief writer answers.++ Raises ``EmptyPrompt`` for an empty prompt, ``ImproverUnavailable`` when no+ model can take the job and ``ImproverFailed`` when the model did not+ deliver. There is no fallback text: the user's own prompt is still in+ front of them, and a template presented as "improved" would be a lie.+ """+ text = (prompt or "").strip()+ if not text:+ raise EmptyPrompt("The prompt is empty.")+ text = text[:MAX_PROMPT_CHARS]++ try:+ context = await asyncio.to_thread(repo_context, folder, text, profile)+ except Exception as exc: # noqa: BLE001 - the notes are a help, never a requirement+ logger.info("Prompt improver: no repository notes ({})", type(exc).__name__)+ context = ""+ if brain is None:+ try:+ brain, source = await asyncio.to_thread(_resolve_default)+ except ImproverUnavailable:+ raise+ except Exception as exc: # noqa: BLE001 - by type; the text may quote the config+ logger.info("Prompt improver: no brief writer ({})", type(exc).__name__)+ raise ImproverUnavailable(+ f"The model that writes prompts could not be prepared ({type(exc).__name__})."+ ) from None++ try:+ raw = await asyncio.wait_for(+ _write(brain, system_prompt(instruction), user_block(text, context)),+ timeout=IMPROVE_TIMEOUT_S,+ )+ except TimeoutError:+ raise ImproverFailed(+ f"The model did not answer within {int(IMPROVE_TIMEOUT_S)} seconds."+ ) from None+ except Exception as exc: # noqa: BLE001 - reported by type; the text may be a provider's+ logger.info("Prompt improver: {} failed ({})", source, type(exc).__name__)+ raise ImproverFailed(f"The model call failed ({type(exc).__name__}).") from None++ improved = _strip_wrapping(raw)+ if not improved:+ raise ImproverFailed("The model returned an empty answer.")+ return ImprovedPrompt(+ text=improved, source=source or "pinned", writer=str(getattr(brain, "name", "") or "")+ )+++__all__ = [+ "DEFAULT_INSTRUCTION",+ "EmptyPrompt",+ "IMPROVE_TIMEOUT_S",+ "MAX_INSTRUCTION_CHARS",+ "USAGE_CALLER",+ "ImprovedPrompt",+ "ImproverFailed",+ "ImproverUnavailable",+ "improve",+ "repo_context",+ "system_prompt",+ "user_block",+]diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.test.tsxnew file mode 100644index 0000000000..7155c3aece--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.test.tsx@@ -0,0 +1,137 @@+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";+import { useIdeSkillsStore } from "@/store/ideSkills";+import { useWorkspacePanesStore } from "@/store/workspacePanes";+import { PromptTab } from "./PromptTab";++function pane(over: Partial<WorkspacePaneRow>): WorkspacePaneRow {+ return {+ workspace_id: "w1", workspace_name: "App", folder: "/repo", workspace_active: true,+ key: "t1", history_id: "h1", name: "T1", agent: "claude", display_name: "Claude Code",+ accepts_prompts: true, status: "live", exit_code: null, activity: "idle", activity_since: 0,+ worked: false, started_at: null, last_output_at: null, last_prompt: "", last_prompt_at: null,+ recap: "", has_resume: false, readable: false, account: null, account_label: null, archived: false,+ ...over,+ } as WorkspacePaneRow;+}++const PANES = [pane({}), pane({ key: "t2", history_id: "h2", name: "T2", agent: "codex", display_name: "Codex" })];++/** An in-memory backend: the improver, the pane list and the pane prompt route. */+function fakeBackend(options: { submitted?: boolean | null; improveStatus?: number } = {}) {+ const calls: { url: string; method: string; body: Record<string, unknown> }[] = [];+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } });+ const fetchFake = async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = init?.method ?? "GET";+ const body = init?.body ? JSON.parse(String(init.body)) : {};+ calls.push({ url, method, body });+ if (url.endsWith("/prompt-improver") && method === "GET") return json({ default_instruction: "Improve this prompt.", max_prompt_chars: 6000, max_instruction_chars: 1000 });+ if (url.endsWith("/prompt-improver") && method === "POST") {+ if (options.improveStatus) return json({ detail: "No model can write prompts right now." }, options.improveStatus);+ return json({ improved: "Make the login form accessible.", source: "tool_model:x", writer: "writer-x", folder: "/repo" });+ }+ if (url.includes("/api/agentic-ide/panes")) return json({ panes: PANES, active_id: "w1" });+ if (url.includes("/terminals/") && url.includes("/prompt")) {+ return json({ terminal: "T2", sent: body.prompt, composed_by: "raw", files: [], submitted: options.submitted === undefined ? true : options.submitted });+ }+ // The model catalog: an empty one leaves the picker on "Automatic".+ return json({ providers: [] });+ };+ return { calls, fetchFake };+}++beforeEach(() => {+ localStorage.clear();+ useWorkspacePanesStore.setState({ panes: PANES });+ useIdeSkillsStore.setState({ target: null });+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe("PromptTab", () => {+ it("improves the typed prompt with the selected pane's repository as context", async () => {+ const backend = fakeBackend();+ vi.stubGlobal("fetch", backend.fetchFake);+ useIdeSkillsStore.setState({ target: { workspaceId: "w1", pane: "t2" } });+ render(<PromptTab />);++ expect(screen.queryByTestId("ide-prompt-result")).toBeNull();+ fireEvent.change(screen.getByTestId("ide-prompt-input"), { target: { value: "login form barrierefrei" } });+ fireEvent.click(screen.getByTestId("ide-prompt-improve"));++ const output = (await screen.findByTestId("ide-prompt-output")) as HTMLTextAreaElement;+ expect(output.value).toBe("Make the login form accessible.");+ const call = backend.calls.find((entry) => entry.method === "POST" && entry.url.endsWith("/prompt-improver"))!;+ expect(call.body).toEqual({ prompt: "login form barrierefrei", provider: "", model: "", instruction: "", workspace: "w1", pane: "t2" });+ // Improving is a preview: nothing was typed into a pane.+ expect(backend.calls.some((entry) => entry.url.includes("/terminals/"))).toBe(false);+ });++ it("sends the edited result, as written, to the chosen terminal", async () => {+ const backend = fakeBackend();+ vi.stubGlobal("fetch", backend.fetchFake);+ useIdeSkillsStore.setState({ target: { workspaceId: "w1", pane: "t2" } });+ render(<PromptTab />);++ fireEvent.change(screen.getByTestId("ide-prompt-input"), { target: { value: "login" } });+ fireEvent.click(screen.getByTestId("ide-prompt-improve"));+ fireEvent.change(await screen.findByTestId("ide-prompt-output"), { target: { value: "Make the login form accessible. Keep the layout." } });+ fireEvent.click(screen.getByTestId("ide-prompt-send"));++ await screen.findByTestId("ide-prompt-notice");+ const sent = backend.calls.find((entry) => entry.url.includes("/terminals/"))!;+ expect(sent.url).toContain("/terminals/t2/prompt?workspace=w1");+ // Never composed a second time: the pane gets the text the user approved.+ expect(sent.body).toMatchObject({ prompt: "Make the login form accessible. Keep the layout.", compose: false });+ expect(screen.getByTestId("ide-prompt-notice").textContent).toContain("T2");+ });++ it("says so when the terminal did not take the prompt", async () => {+ const backend = fakeBackend({ submitted: false });+ vi.stubGlobal("fetch", backend.fetchFake);+ render(<PromptTab />);++ fireEvent.change(screen.getByTestId("ide-prompt-input"), { target: { value: "login" } });+ fireEvent.click(screen.getByTestId("ide-prompt-improve"));+ await screen.findByTestId("ide-prompt-output");+ fireEvent.click(screen.getByTestId("ide-prompt-send"));++ const notice = await screen.findByTestId("ide-prompt-notice");+ expect(notice.textContent).toContain("did not take the prompt");+ });++ it("shows the server's reason when no model can improve the prompt", async () => {+ const backend = fakeBackend({ improveStatus: 409 });+ vi.stubGlobal("fetch", backend.fetchFake);+ render(<PromptTab />);++ fireEvent.change(screen.getByTestId("ide-prompt-input"), { target: { value: "login" } });+ fireEvent.click(screen.getByTestId("ide-prompt-improve"));++ const error = await screen.findByTestId("ide-prompt-error");+ expect(error.textContent).toBe("No model can write prompts right now.");+ expect(screen.queryByTestId("ide-prompt-result")).toBeNull();+ });++ it("passes the user's own instruction and keeps the draft across a remount", async () => {+ const backend = fakeBackend();+ vi.stubGlobal("fetch", backend.fetchFake);+ const first = render(<PromptTab />);+ fireEvent.change(screen.getByTestId("ide-prompt-input"), { target: { value: "login" } });+ fireEvent.change(screen.getByTestId("ide-prompt-instruction"), { target: { value: "Translate it to English." } });+ first.unmount();++ render(<PromptTab />);+ expect((screen.getByTestId("ide-prompt-input") as HTMLTextAreaElement).value).toBe("login");+ fireEvent.click(screen.getByTestId("ide-prompt-improve"));++ await waitFor(() => expect(backend.calls.some((entry) => entry.method === "POST" && entry.url.endsWith("/prompt-improver"))).toBe(true));+ const call = backend.calls.find((entry) => entry.method === "POST" && entry.url.endsWith("/prompt-improver"))!;+ expect(call.body.instruction).toBe("Translate it to English.");+ });+});diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.tsxnew file mode 100644index 0000000000..7def83e143--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.tsx@@ -0,0 +1,371 @@+import { useCallback, useEffect, useMemo, useState, type KeyboardEvent } from "react";+import { ArrowRight, Check, Copy, Loader2, RotateCcw, Sparkles } from "lucide-react";+import { fill, useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { robustCopy } from "@/lib/clipboard";+import { promptTerminal, type WorkspacePaneRow } from "@/lib/agenticIdeApi";+import type { CuratedModel } from "@/lib/agentChatApi";+import { offeredModels, useSavedHiddenModels } from "@/lib/agentProviderPrefs";+import { rankModels } from "@/lib/modelRanking";+import { MAX_INSTRUCTION_CHARS, MAX_PROMPT_CHARS, fetchPromptImproverDefaults, improvePrompt } from "@/lib/promptImproverApi";+import { joinProviderOptions, type ProviderOption } from "@/store/agentChat";+import { useIdeSkillsStore } from "@/store/ideSkills";+import { useWorkspacePanes } from "@/store/workspacePanes";+import { AgentMark } from "@/components/agentic/AgentMark";+import { useThreadChatStore } from "@/components/agentic/threads/threadModel";+import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";++const DRAFT_KEY = "jarvis.agenticIde.promptTab.draft.v1";+const MODEL_KEY = "jarvis.agenticIde.promptTab.model.v1";+const INSTRUCTION_KEY = "jarvis.agenticIde.promptTab.instruction.v1";++/** Joins a provider and one of its models into one picker value; neither id holds a newline. */+const SEP = "\n";+/** The picker value for "whoever writes the IDE's task briefs". */+const AUTO = "";++function stored(key: string): string {+ try {+ return localStorage.getItem(key) ?? "";+ } catch {+ return "";+ }+}++function persist(key: string, value: string): void {+ try {+ if (value) localStorage.setItem(key, value);+ else localStorage.removeItem(key);+ } catch {+ /* a convenience only: the tab keeps the value for this session */+ }+}++const paneId = (pane: Pick<WorkspacePaneRow, "workspace_id" | "key">) => `${pane.workspace_id}${SEP}${pane.key}`;++/** The models a provider row offers: its live list when it has one, else the curated one. */+function modelsOf(provider: ProviderOption, live: Record<string, CuratedModel[]>): CuratedModel[] {+ const rows = live[provider.id];+ return provider.models_source === "live" && rows?.length ? rows : provider.curated_models ?? [];+}++const FIELD =+ "block w-full resize-y rounded-md bg-input px-3 py-2 text-sm leading-6 text-foreground placeholder:text-muted-foreground " ++ "scrollbar-jarvis focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-strong";+const QUIET_BTN =+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md px-2.5 text-sm text-muted-foreground transition-colors " ++ "hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " ++ "disabled:cursor-default disabled:opacity-40 disabled:hover:bg-transparent";+const MAIN_BTN =+ "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-md bg-accent px-3 text-sm font-medium text-accent-foreground " ++ "transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring " ++ "disabled:cursor-default disabled:opacity-40";+const LABEL = "text-xs font-medium text-muted-foreground";++/**+ * The side panel's Prompt surface: type a rough prompt, have a model of your+ * choice rewrite it, then send the result to the terminal you pick.+ *+ * The rewrite states the goal and leaves the route to the agent, and the+ * writer is told about the repository the chosen terminal works in. Nothing+ * reaches a terminal until Send is pressed; the improved text stays editable.+ */+export function PromptTab() {+ const t = useT();+ const [draft, setDraft] = useState(() => stored(DRAFT_KEY));+ const [pick, setPick] = useState(() => stored(MODEL_KEY));+ const [instruction, setInstruction] = useState(() => stored(INSTRUCTION_KEY));+ const [defaultInstruction, setDefaultInstruction] = useState("");+ const [improved, setImproved] = useState<string | null>(null);+ const [writer, setWriter] = useState("");+ const [chosenPane, setChosenPane] = useState<string | null>(null);+ const [busy, setBusy] = useState<"improve" | "send" | null>(null);+ const [error, setError] = useState("");+ const [notice, setNotice] = useState<{ tone: "ok" | "warn"; text: string } | null>(null);+ const [copied, setCopied] = useState(false);++ const catalog = useThreadChatStore((state) => state.catalog);+ const connections = useThreadChatStore((state) => state.connections);+ const liveModels = useThreadChatStore((state) => state.liveModels);+ const savedHidden = useSavedHiddenModels((state) => state.hidden);+ const selected = useIdeSkillsStore((state) => state.target);+ const panes = useWorkspacePanes();++ useEffect(() => {+ const store = useThreadChatStore.getState();+ if (!store.catalog || store.catalogStale) void store.loadCatalog();+ fetchPromptImproverDefaults()+ .then((defaults) => setDefaultInstruction(defaults.default_instruction))+ .catch(() => undefined); // the placeholder stays empty; the backend still applies its default+ }, []);++ const providers = useMemo(+ () => (catalog ? joinProviderOptions(catalog.providers, connections) : [])+ .slice()+ .sort((a, b) => Number(b.connected) - Number(a.connected)),+ [catalog, connections],+ );++ // A provider with a live model list is asked for it once it is known to be connected.+ useEffect(() => {+ for (const provider of providers) {+ if (provider.connected && provider.models_source === "live") void useThreadChatStore.getState().loadModels(provider.id);+ }+ }, [providers]);++ const [pickedProvider, pickedModel = ""] = pick.split(SEP);++ const modelGroups = useMemo<ComboboxGroup[]>(() => {+ const connectHint = t("ide_side_panel.prompt.connect_first");+ const groups: ComboboxGroup[] = [{+ id: "auto",+ options: [{ value: AUTO, label: t("ide_side_panel.prompt.model_auto"), description: t("ide_side_panel.prompt.model_auto_hint") }],+ }];+ for (const provider of providers) {+ const disabled = !provider.connected;+ const icon = <AgentMark agent={provider.agent ?? ""} label={provider.label} logoUrl={provider.logoUrl} variant="plain" size="sm" />;+ const current = provider.id === pickedProvider ? pickedModel : "";+ const models = offeredModels(provider, modelsOf(provider, liveModels), current, savedHidden).filter((model) => model.id);+ const toOption = (model: CuratedModel): ComboboxOption => ({+ value: `${provider.id}${SEP}${model.id}`,+ label: model.label || model.id,+ triggerLabel: `${provider.label} · ${model.label || model.id}`,+ icon,+ hint: disabled ? connectHint : undefined,+ searchText: `${model.id} ${provider.label}`,+ disabled,+ });+ const ranked = rankModels(models);+ groups.push({+ id: provider.id,+ label: provider.label,+ options: [+ { value: provider.id, label: t("ide_side_panel.prompt.model_default"), triggerLabel: provider.label, icon, hint: disabled ? connectHint : undefined, searchText: provider.label, disabled },+ ...ranked.current.map(toOption),+ ],+ more: ranked.older.length ? { label: t("agent_chat.older_models"), options: ranked.older.map(toOption) } : undefined,+ });+ }+ return groups;+ }, [providers, liveModels, savedHidden, pickedProvider, pickedModel, t]);++ // Only a running agent takes a prompt; a plain shell would run the text as a command.+ const targets = useMemo(() => panes.filter((pane) => pane.accepts_prompts && pane.status !== "exited" && pane.status !== "error"), [panes]);+ const target = useMemo(() => {+ const byChoice = chosenPane ? targets.find((pane) => paneId(pane) === chosenPane) : undefined;+ if (byChoice) return byChoice;+ const inGrid = selected+ ? targets.find((pane) => pane.workspace_id === selected.workspaceId && (pane.key === selected.pane || pane.name === selected.pane))+ : undefined;+ return inGrid ?? targets.find((pane) => pane.workspace_active) ?? targets[0] ?? null;+ }, [targets, chosenPane, selected]);++ const paneGroups = useMemo<ComboboxGroup[]>(() => {+ const byWorkspace = new Map<string, { label: string; active: boolean; panes: WorkspacePaneRow[] }>();+ for (const pane of targets) {+ const group = byWorkspace.get(pane.workspace_id) ?? { label: pane.workspace_name, active: pane.workspace_active, panes: [] };+ group.panes.push(pane);+ byWorkspace.set(pane.workspace_id, group);+ }+ const single = byWorkspace.size === 1;+ // The workspace on screen leads; every workspace numbers its terminals from T1,+ // so the closed picker names the workspace too once there is more than one.+ return [...byWorkspace]+ .sort(([, a], [, b]) => Number(b.active) - Number(a.active))+ .map(([id, group]) => ({+ id,+ label: single ? undefined : group.label,+ options: group.panes.map((pane): ComboboxOption => ({+ value: paneId(pane),+ label: pane.name,+ triggerLabel: single ? pane.name : `${group.label} · ${pane.name}`,+ hint: pane.display_name,+ description: pane.recap || undefined,+ icon: <AgentMark agent={pane.agent} label={pane.display_name} variant="plain" size="sm" />,+ searchText: `${pane.display_name} ${group.label} ${pane.recap}`,+ })),+ }));+ }, [targets]);++ const improve = useCallback(async () => {+ const prompt = draft.trim();+ if (!prompt || busy) return;+ setBusy("improve");+ setError("");+ setNotice(null);+ try {+ const result = await improvePrompt({+ prompt,+ provider: pickedProvider,+ model: pickedModel,+ instruction: instruction.trim(),+ workspaceId: target?.workspace_id,+ pane: target?.key,+ });+ setImproved(result.improved);+ setWriter(result.writer);+ } catch (failure) {+ setError(failure instanceof Error ? failure.message : String(failure));+ } finally {+ setBusy(null);+ }+ }, [draft, busy, pickedProvider, pickedModel, instruction, target]);++ const text = (improved ?? "").trim();+ const tooLong = text.length > MAX_PROMPT_CHARS;++ const send = useCallback(async () => {+ if (!text || tooLong || !target || busy) return;+ setBusy("send");+ setError("");+ setNotice(null);+ try {+ const result = await promptTerminal(target.key, text, { compose: false, workspaceId: target.workspace_id });+ // Three answers: it started, the text is provably still in the input box, or nobody can say.+ const key = result.submitted === true ? "sent" : result.submitted === false ? "not_accepted" : "unconfirmed";+ setNotice({ tone: result.submitted === true ? "ok" : "warn", text: fill(t(`ide_side_panel.prompt.${key}`), { pane: target.name }) });+ } catch (failure) {+ setError(failure instanceof Error ? failure.message : String(failure));+ } finally {+ setBusy(null);+ }+ }, [text, tooLong, target, busy, t]);++ const copy = useCallback(() => {+ void robustCopy(text).then((ok) => {+ if (!ok) return setError(t("ide_side_panel.prompt.copy_failed"));+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ });+ }, [text, t]);++ const onModifierEnter = (run: () => void) => (event: KeyboardEvent<HTMLTextAreaElement>) => {+ if (event.key === "Enter" && (event.ctrlKey || event.metaKey)) {+ event.preventDefault();+ run();+ }+ };++ return (+ <div data-testid="ide-prompt-tab" className="h-full min-h-0 overflow-y-auto scrollbar-jarvis">+ <div className="flex flex-col gap-3 p-3">+ <textarea+ value={draft}+ onChange={(event) => { setDraft(event.target.value); persist(DRAFT_KEY, event.target.value); }}+ onKeyDown={onModifierEnter(() => void improve())}+ rows={6}+ maxLength={MAX_PROMPT_CHARS}+ spellCheck={false}+ placeholder={t("ide_side_panel.prompt.placeholder")}+ aria-label={t("ide_side_panel.prompt.input_aria")}+ data-testid="ide-prompt-input"+ className={FIELD}+ />+ <div className="flex min-w-0 items-center gap-2">+ <div className="min-w-0 flex-1">+ <Combobox+ ariaLabel={t("ide_side_panel.prompt.model_aria")}+ testId="ide-prompt-model"+ value={pick}+ groups={modelGroups}+ onChange={(value) => { setPick(value); persist(MODEL_KEY, value); }}+ fallbackLabel={pickedModel || pickedProvider || t("ide_side_panel.prompt.model_auto")}+ searchPlaceholder={t("ide_side_panel.prompt.model_search")}+ triggerHint={false}+ panelMinWidth={300}+ className="h-8 py-0"+ />+ </div>+ <button type="button" onClick={() => void improve()} disabled={!draft.trim() || busy !== null}+ data-testid="ide-prompt-improve" className={MAIN_BTN}>+ {busy === "improve" ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <Sparkles className="h-3.5 w-3.5" aria-hidden />}+ {busy === "improve" ? t("ide_side_panel.prompt.improving") : t("ide_side_panel.prompt.improve")}+ </button>+ </div>++ <details className="group">+ <summary className={cn(LABEL, "cursor-pointer select-none hover:text-foreground")} data-testid="ide-prompt-instruction-toggle">+ {t("ide_side_panel.prompt.instruction")}+ {instruction.trim() && <span className="ms-1.5 text-accent">•</span>}+ </summary>+ <div className="mt-2 flex flex-col gap-1.5">+ <textarea+ value={instruction}+ onChange={(event) => { setInstruction(event.target.value); persist(INSTRUCTION_KEY, event.target.value); }}+ rows={3}+ maxLength={MAX_INSTRUCTION_CHARS}+ placeholder={defaultInstruction}+ aria-label={t("ide_side_panel.prompt.instruction")}+ data-testid="ide-prompt-instruction"+ className={FIELD}+ />+ <div className="flex items-start gap-2">+ <p className="min-w-0 flex-1 text-xs text-muted-foreground">{t("ide_side_panel.prompt.instruction_hint")}</p>+ <button type="button" onClick={() => { setInstruction(""); persist(INSTRUCTION_KEY, ""); }} disabled={!instruction}+ className={cn(QUIET_BTN, "h-7 px-2 text-xs")}>+ <RotateCcw className="h-3 w-3" aria-hidden />+ {t("ide_side_panel.prompt.instruction_reset")}+ </button>+ </div>+ </div>+ </details>++ {improved !== null && (+ <section className="flex flex-col gap-2 border-t border-border/60 pt-3" data-testid="ide-prompt-result">+ <div className="flex items-baseline justify-between gap-2">+ <span className={LABEL}>{t("ide_side_panel.prompt.result")}</span>+ {writer && <span className="min-w-0 truncate text-xs text-muted-foreground">{fill(t("ide_side_panel.prompt.written_by"), { model: writer })}</span>}+ </div>+ <textarea+ value={improved}+ onChange={(event) => { setImproved(event.target.value); setNotice(null); }}+ onKeyDown={onModifierEnter(() => void send())}+ rows={12}+ spellCheck={false}+ aria-label={t("ide_side_panel.prompt.result")}+ data-testid="ide-prompt-output"+ className={FIELD}+ />+ {tooLong && (+ <p role="alert" className="text-xs text-destructive">+ {fill(t("ide_side_panel.prompt.too_long"), { count: text.length, max: MAX_PROMPT_CHARS })}+ </p>+ )}+ <div className="flex min-w-0 items-center gap-2">+ <div className="min-w-0 flex-1">+ <Combobox+ ariaLabel={t("ide_side_panel.prompt.target_aria")}+ testId="ide-prompt-target"+ value={target ? paneId(target) : ""}+ groups={paneGroups}+ onChange={setChosenPane}+ fallbackLabel={t("ide_side_panel.prompt.no_target")}+ disabled={targets.length === 0}+ panelMinWidth={260}+ className="h-8 py-0"+ />+ </div>+ <button type="button" onClick={copy} disabled={!text} data-testid="ide-prompt-copy"+ aria-label={t("ide_side_panel.prompt.copy")} title={t("ide_side_panel.prompt.copy")} className={cn(QUIET_BTN, "w-8 justify-center px-0")}>+ {copied ? <Check className="h-3.5 w-3.5" aria-hidden /> : <Copy className="h-3.5 w-3.5" aria-hidden />}+ </button>+ <button type="button" onClick={() => void send()} disabled={!text || tooLong || !target || busy !== null}+ data-testid="ide-prompt-send" className={MAIN_BTN}>+ {busy === "send" ? <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden /> : <ArrowRight className="h-3.5 w-3.5" aria-hidden />}+ {t("ide_side_panel.prompt.send")}+ </button>+ </div>+ {targets.length === 0 && <p className="text-xs text-muted-foreground">{t("ide_side_panel.prompt.no_target_hint")}</p>}+ </section>+ )}++ {error && <p role="alert" data-testid="ide-prompt-error" className="text-xs text-destructive">{error}</p>}+ {notice && (+ <p role="status" data-testid="ide-prompt-notice" className={cn("text-xs", notice.tone === "ok" ? "text-success" : "text-warning")}>+ {notice.text}+ </p>+ )}+ </div>+ </div>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsxindex f48da60cdf..46c9b28c64 100644--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx@@ -1,11 +1,12 @@import type { ReactNode } from "react";-import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, Globe, Search, type LucideIcon } from "lucide-react";+import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, Globe, Search, Sparkles, type LucideIcon } from "lucide-react";import type { SidePanelTabId } from "@/store/ideSidePanel";import { AgentsOverview } from "./AgentsOverview";import { BrowserTab } from "./browser/BrowserTab";import { ExplorerPanel } from "./explorer/ExplorerPanel";import { GitOverviewTab } from "./git/GitOverviewTab";import { OfficeTab } from "./OfficeTab";+import { PromptTab } from "./prompt/PromptTab";import { SearchPanel } from "./search/SearchPanel";import { SkillsTab } from "./skills/SkillsTab";import { SubscriptionsTab } from "./subscriptions/SubscriptionsTab";@@ -87,6 +88,15 @@ export const SIDE_PANEL_TABS: readonly SidePanelTabDef[] = [icon: Files,render: () => <SkillsTab />,},+ {+ id: "prompt",+ labelKey: "ide_side_panel.tabs.prompt",+ shortcut: "P",+ icon: Sparkles,+ render: () => <PromptTab />,+ // The draft, the improved text and a running rewrite survive a tab switch.+ keepAlive: true,+ },{id: "subscriptions",labelKey: "ide_side_panel.tabs.subscriptions",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex a33569dc60..bc574737d7 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -7539,6 +7539,33 @@"skipped_dirty": "{count} Dateien mit ungespeicherten Änderungen wurden ausgelassen; speichere sie zuerst.","skipped_other": "{count} Dateien ließen sich nicht ändern."},+ "prompt": {+ "placeholder": "Schreib den Prompt so, wie du ihn einem Terminal geben würdest…",+ "input_aria": "Dein Prompt",+ "model_aria": "Modell, das den Prompt verbessert",+ "model_auto": "Automatisch",+ "model_auto_hint": "Das Modell, das deine Aufgaben-Briefings schreibt",+ "model_default": "Standardmodell",+ "model_search": "Modelle suchen",+ "connect_first": "Erst verbinden",+ "improve": "Verbessern",+ "improving": "Wird verbessert…",+ "instruction": "Anweisung",+ "instruction_hint": "Was das Modell mit deinem Prompt tun soll. Es formuliert immer das Ziel, nicht die Umsetzung, und kennt das Repository des gewählten Terminals.",+ "instruction_reset": "Zurücksetzen",+ "result": "Verbesserter Prompt",+ "written_by": "von {model}",+ "too_long": "{count} von {max} Zeichen: zu lang zum Senden.",+ "target_aria": "Terminal, das den Prompt erhält",+ "no_target": "Kein Terminal",+ "no_target_hint": "Öffne ein Terminal mit einem Coding-Agenten, um den Prompt zu senden.",+ "copy": "Kopieren",+ "copy_failed": "Der Prompt konnte nicht kopiert werden.",+ "send": "Senden",+ "sent": "An {pane} gesendet.",+ "not_accepted": "{pane} hat den Prompt nicht angenommen. Der Text steht in seinem Eingabefeld; drück dort Enter.",+ "unconfirmed": "Bei {pane} war nicht zu sehen, dass der Prompt ankam. Sieh in diesem Terminal nach."+ },"tabs": {"browser": "Browser","git": "Git",@@ -7548,7 +7575,8 @@"changes": "Änderungen","search": "Suche","subscriptions": "Abos",- "office": "Dodaios Verse"+ "office": "Dodaios Verse",+ "prompt": "Prompt"},"subscriptions": {"bank": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex c5948d4dd2..0fdcd6f26b 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -7539,6 +7539,33 @@"skipped_dirty": "{count} files with unsaved changes were left out; save them first.","skipped_other": "{count} files could not be changed."},+ "prompt": {+ "placeholder": "Type the prompt the way you would give it to a terminal…",+ "input_aria": "Your prompt",+ "model_aria": "Model that improves the prompt",+ "model_auto": "Automatic",+ "model_auto_hint": "The model that writes your task briefs",+ "model_default": "Default model",+ "model_search": "Search models",+ "connect_first": "Connect first",+ "improve": "Improve",+ "improving": "Improving…",+ "instruction": "Instruction",+ "instruction_hint": "What the model is told to do with your prompt. It always writes the goal, not the implementation, and knows the repository of the chosen terminal.",+ "instruction_reset": "Reset",+ "result": "Improved prompt",+ "written_by": "by {model}",+ "too_long": "{count} of {max} characters: too long to send.",+ "target_aria": "Terminal that receives the prompt",+ "no_target": "No terminal",+ "no_target_hint": "Open a terminal with a coding agent to send the prompt.",+ "copy": "Copy",+ "copy_failed": "Could not copy the prompt.",+ "send": "Send",+ "sent": "Sent to {pane}.",+ "not_accepted": "{pane} did not take the prompt. The text is in its input box; press Enter there.",+ "unconfirmed": "{pane} never showed the prompt arriving. Check that terminal."+ },"tabs": {"browser": "Browser","git": "Git",@@ -7548,7 +7575,8 @@"changes": "Changes","search": "Search","subscriptions": "Subscriptions",- "office": "Dodaios Verse"+ "office": "Dodaios Verse",+ "prompt": "Prompt"},"subscriptions": {"bank": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 8c15427ca7..731eec37c5 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -7539,6 +7539,33 @@"skipped_dirty": "Se omitieron {count} archivos con cambios sin guardar; guárdalos primero.","skipped_other": "{count} archivos no se pudieron cambiar."},+ "prompt": {+ "placeholder": "Escribe el prompt como se lo darías a un terminal…",+ "input_aria": "Tu prompt",+ "model_aria": "Modelo que mejora el prompt",+ "model_auto": "Automático",+ "model_auto_hint": "El modelo que redacta tus encargos",+ "model_default": "Modelo predeterminado",+ "model_search": "Buscar modelos",+ "connect_first": "Conéctalo primero",+ "improve": "Mejorar",+ "improving": "Mejorando…",+ "instruction": "Instrucción",+ "instruction_hint": "Lo que se le pide al modelo que haga con tu prompt. Siempre escribe el objetivo, no la implementación, y conoce el repositorio del terminal elegido.",+ "instruction_reset": "Restablecer",+ "result": "Prompt mejorado",+ "written_by": "por {model}",+ "too_long": "{count} de {max} caracteres: demasiado largo para enviar.",+ "target_aria": "Terminal que recibe el prompt",+ "no_target": "Ningún terminal",+ "no_target_hint": "Abre un terminal con un agente de programación para enviar el prompt.",+ "copy": "Copiar",+ "copy_failed": "No se pudo copiar el prompt.",+ "send": "Enviar",+ "sent": "Enviado a {pane}.",+ "not_accepted": "{pane} no aceptó el prompt. El texto está en su campo de entrada; pulsa Intro allí.",+ "unconfirmed": "{pane} no mostró la llegada del prompt. Revisa ese terminal."+ },"tabs": {"browser": "Navegador","git": "Git",@@ -7548,7 +7575,8 @@"changes": "Cambios","search": "Buscar","subscriptions": "Suscripciones",- "office": "Dodaios Verse"+ "office": "Dodaios Verse",+ "prompt": "Prompt"},"subscriptions": {"bank": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.jsonindex 5c8ee4ccca..7646671ead 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json@@ -7539,6 +7539,33 @@"skipped_dirty": "{count} ficheiros com alterações por guardar foram ignorados; guarda-os primeiro.","skipped_other": "Não foi possível alterar {count} ficheiros."},+ "prompt": {+ "placeholder": "Escreva o prompt como você o daria a um terminal…",+ "input_aria": "Seu prompt",+ "model_aria": "Modelo que melhora o prompt",+ "model_auto": "Automático",+ "model_auto_hint": "O modelo que escreve os seus briefings de tarefa",+ "model_default": "Modelo padrão",+ "model_search": "Buscar modelos",+ "connect_first": "Conecte primeiro",+ "improve": "Melhorar",+ "improving": "Melhorando…",+ "instruction": "Instrução",+ "instruction_hint": "O que o modelo deve fazer com o seu prompt. Ele sempre escreve o objetivo, não a implementação, e conhece o repositório do terminal escolhido.",+ "instruction_reset": "Redefinir",+ "result": "Prompt melhorado",+ "written_by": "por {model}",+ "too_long": "{count} de {max} caracteres: longo demais para enviar.",+ "target_aria": "Terminal que recebe o prompt",+ "no_target": "Nenhum terminal",+ "no_target_hint": "Abra um terminal com um agente de programação para enviar o prompt.",+ "copy": "Copiar",+ "copy_failed": "Não foi possível copiar o prompt.",+ "send": "Enviar",+ "sent": "Enviado para {pane}.",+ "not_accepted": "{pane} não aceitou o prompt. O texto está na caixa de entrada dele; pressione Enter lá.",+ "unconfirmed": "{pane} não mostrou a chegada do prompt. Verifique esse terminal."+ },"tabs": {"browser": "Navegador","git": "Git",@@ -7548,7 +7575,8 @@"changes": "Alterações","search": "Pesquisa","subscriptions": "Subscrições",- "office": "Dodaios Verse"+ "office": "Dodaios Verse",+ "prompt": "Prompt"},"subscriptions": {"bank": {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.jsonindex 5b7e2a5e07..7d6409c045 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json@@ -7539,6 +7539,33 @@"skipped_dirty": "已跳过 {count} 个有未保存更改的文件;请先保存它们。","skipped_other": "有 {count} 个文件无法修改。"},+ "prompt": {+ "placeholder": "像交给终端那样写下你的提示词…",+ "input_aria": "你的提示词",+ "model_aria": "用于优化提示词的模型",+ "model_auto": "自动",+ "model_auto_hint": "为你撰写任务简报的模型",+ "model_default": "默认模型",+ "model_search": "搜索模型",+ "connect_first": "请先连接",+ "improve": "优化",+ "improving": "正在优化…",+ "instruction": "指令",+ "instruction_hint": "告诉模型如何处理你的提示词。它始终只写目标而不写实现方式,并了解所选终端的代码仓库。",+ "instruction_reset": "重置",+ "result": "优化后的提示词",+ "written_by": "由 {model} 撰写",+ "too_long": "{count} / {max} 个字符:太长,无法发送。",+ "target_aria": "接收提示词的终端",+ "no_target": "没有终端",+ "no_target_hint": "打开一个带有编程智能体的终端以发送提示词。",+ "copy": "复制",+ "copy_failed": "无法复制提示词。",+ "send": "发送",+ "sent": "已发送到 {pane}。",+ "not_accepted": "{pane} 没有接收提示词。文本仍在它的输入框中,请在那里按 Enter。",+ "unconfirmed": "{pane} 未显示提示词已到达。请检查该终端。"+ },"tabs": {"browser": "浏览器","git": "Git",@@ -7548,7 +7575,8 @@"changes": "更改","search": "搜索","subscriptions": "订阅",- "office": "Dodaios Verse"+ "office": "Dodaios Verse",+ "prompt": "提示词"},"subscriptions": {"bank": {diff --git a/jarvis/ui/web/frontend/src/lib/promptImproverApi.ts b/jarvis/ui/web/frontend/src/lib/promptImproverApi.tsnew file mode 100644index 0000000000..6a650a6c72--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/promptImproverApi.ts@@ -0,0 +1,72 @@+import { fill, translate } from "@/i18n";++/** The longest prompt a pane takes (`MAX_PROMPT_CHARS` in the backend). */+export const MAX_PROMPT_CHARS = 6000;++/** The longest instruction of the user's own that is passed to the writer. */+export const MAX_INSTRUCTION_CHARS = 1000;++export interface ImproveRequest {+ prompt: string;+ /** A provider id from the agent catalog; "" = whoever writes the IDE's task briefs. */+ provider: string;+ model: string;+ /** The user's own instruction; "" = the default one. */+ instruction: string;+ /** The pane the prompt is meant for: its repository is the writer's context. */+ workspaceId?: string;+ pane?: string;+}++export interface ImprovedPrompt {+ improved: string;+ /** `provider:<id>` for a picked model, else the brief writer's own source. */+ source: string;+ /** The writing model's own name. */+ writer: string;+ /** The repository folder the writer was told about; "" when there was none. */+ folder: string;+}++export interface PromptImproverDefaults {+ default_instruction: string;+ max_prompt_chars: number;+ max_instruction_chars: number;+}++const URL = "/api/agentic-ide/prompt-improver";++async function detail(res: Response): Promise<string> {+ try {+ const body = (await res.json()) as { detail?: unknown };+ if (typeof body?.detail === "string" && body.detail) return body.detail;+ } catch {+ /* fall through */+ }+ return fill(translate("shell_errors.request_failed_status"), { status: res.status });+}++/** The instruction the writer gets when the user typed none. */+export async function fetchPromptImproverDefaults(): Promise<PromptImproverDefaults> {+ const res = await fetch(URL, { cache: "no-store" });+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as PromptImproverDefaults;+}++/** Rewrite one prompt. Nothing is sent to a pane; rejects with the server's own reason. */+export async function improvePrompt(request: ImproveRequest): Promise<ImprovedPrompt> {+ const res = await fetch(URL, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ prompt: request.prompt,+ provider: request.provider,+ model: request.model,+ instruction: request.instruction,+ workspace: request.workspaceId ?? null,+ pane: request.pane ?? null,+ }),+ });+ if (!res.ok) throw new Error(await detail(res));+ return (await res.json()) as ImprovedPrompt;+}diff --git a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts b/jarvis/ui/web/frontend/src/store/ideSidePanel.tsindex f996f5ddd0..e941790559 100644--- a/jarvis/ui/web/frontend/src/store/ideSidePanel.ts+++ b/jarvis/ui/web/frontend/src/store/ideSidePanel.ts@@ -10,7 +10,7 @@ import { create } from "zustand";*//** Every function the panel can show. A new one is a new id plus a registry entry. */-export type SidePanelTabId = "browser" | "agents" | "changes" | "files" | "search" | "git" | "skills" | "subscriptions" | "office" | `terminal:${string}`;+export type SidePanelTabId = "browser" | "agents" | "changes" | "files" | "search" | "git" | "skills" | "prompt" | "subscriptions" | "office" | `terminal:${string}`;export interface SidePanelTerminal {id: `terminal:${string}`;@@ -23,7 +23,7 @@ export interface SidePanelTerminal {export const MAX_TERMINAL_TABS = 16;-export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["browser", "agents", "changes", "files", "search", "git", "skills", "subscriptions", "office"];+export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["browser", "agents", "changes", "files", "search", "git", "skills", "prompt", "subscriptions", "office"];/*** DOM id of the panel host, for the toggle's `aria-controls`.diff --git a/jarvis/ui/web/prompt_improver_routes.py b/jarvis/ui/web/prompt_improver_routes.pynew file mode 100644index 0000000000..bde62cfaee--- /dev/null+++ b/jarvis/ui/web/prompt_improver_routes.py@@ -0,0 +1,157 @@+"""REST API for the Agentic IDE's prompt improver (the side panel's Prompt tab).++Endpoints (mounted by the WebServer in ``_build_app()``):++ GET /api/agentic-ide/prompt-improver → the default instruction and limits.+ POST /api/agentic-ide/prompt-improver → {"improved": ...} for one prompt.++Improving never types into a pane. The tab shows the result and sends it+through ``POST /api/agentic-ide/terminals/{name}/prompt`` when the user says so.+"""+from __future__ import annotations++import asyncio+import logging+from typing import Any++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel, Field++from jarvis.agentic_ide import prompt_improver+from jarvis.agentic_ide.session import MAX_PROMPT_CHARS, get_registry++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/agentic-ide/prompt-improver", tags=["prompt-improver"])+++class ImproveRequest(BaseModel):+ prompt: str = Field(min_length=1, max_length=MAX_PROMPT_CHARS)+ #: A provider id from the agent catalog; empty = the IDE's brief writer.+ provider: str = Field(default="", max_length=100)+ model: str = Field(default="", max_length=200)+ #: The user's own instruction; empty = the default one.+ instruction: str = Field(default="", max_length=prompt_improver.MAX_INSTRUCTION_CHARS)+ #: The pane the prompt is meant for: its repository is the writer's context.+ workspace: str | None = Field(default=None, max_length=200)+ pane: str | None = Field(default=None, max_length=200)+++def _target(workspace: str | None, pane: str | None) -> tuple[str, Any]:+ """``(folder, profile)`` of the pane's repository, or ``("", None)``.++ A worktree pane works in its own folder, which the workspace's cached+ profile does not describe, so the profile is handed on only when the two+ are the same folder.+ """+ registry = get_registry()+ if pane:+ found = registry.find_terminal(pane, workspace or None)+ if found is not None:+ session, term = found+ if term.computer_id:+ # The agent works on another machine; this folder is not its repository.+ return "", None+ folder = term.cwd(session.folder)+ return folder, session.profile if folder == session.folder else None+ session = registry.get(workspace or None)+ if session is None:+ return "", None+ return session.folder, session.profile+++def _seat_for(provider: str, model: str) -> tuple[Any, Any]:+ """``(config, seat)`` for the picked provider. Blocking: a CLI probe, a config load."""+ from jarvis.agent_chat.catalog import offers+ from jarvis.agent_chat.service import resolve_runner+ from jarvis.core.config import load_config+ from jarvis.society.seat_brain import Seat++ if not offers("agent", provider):+ raise prompt_improver.ImproverUnavailable(+ f"'{provider}' is not a model provider this app offers."+ )+ runner = resolve_runner(provider, surface="agent")+ if runner == "unknown":+ raise prompt_improver.ImproverUnavailable(+ f"'{provider}' cannot write prompts on this machine."+ )+ return load_config(), Seat(provider, model, runner)+++async def _picked_brain(provider: str, model: str) -> Any:+ """The user's pick as a brain, on the seat an agent chat on that provider uses.++ The rewrite then runs on the credential the picker showed and on nothing+ else. Raises ``ImproverUnavailable`` with an app-authored message; a+ failure of any other kind is reported by its type, because its text may+ quote the configuration.+ """+ from jarvis.society import seat_brain++ try:+ config, seat = await asyncio.to_thread(_seat_for, provider, model)+ return await seat_brain.seat_brain(config, seat, caller=prompt_improver.USAGE_CALLER)+ except prompt_improver.ImproverUnavailable:+ raise+ except seat_brain.SeatUnavailable as exc:+ raise prompt_improver.ImproverUnavailable(str(exc)) from None+ except Exception as exc: # noqa: BLE001 - reported by type, see the docstring+ log.info(+ "Prompt improver: the %s seat could not be prepared (%s).",+ provider,+ type(exc).__name__,+ )+ raise prompt_improver.ImproverUnavailable(+ f"'{provider}' could not be prepared ({type(exc).__name__})."+ ) from None+++ "",+ summary="Show the prompt improver's defaults",+ openapi_extra={"x-jarvis-readonly": True},+)+def prompt_improver_defaults() -> dict[str, Any]:+ """The instruction used when the user gives none, and the size limits."""+ return {+ "default_instruction": prompt_improver.DEFAULT_INSTRUCTION,+ "max_prompt_chars": MAX_PROMPT_CHARS,+ "max_instruction_chars": prompt_improver.MAX_INSTRUCTION_CHARS,+ }++[email protected]("", summary="Improve a prompt for a coding agent")+async def improve_prompt(req: ImproveRequest) -> dict[str, Any]:+ """Rewrite ``prompt`` as a goal-only prompt, with the target pane's repo as context.++ ``provider``/``model`` name the writing model; without them the IDE's+ configured brief writer answers. Nothing is sent to a pane.+ """+ folder, profile = _target(req.workspace, req.pane)+ provider = req.provider.strip().lower()+ try:+ brain = await _picked_brain(provider, req.model.strip()) if provider else None+ result = await prompt_improver.improve(+ req.prompt,+ folder=folder,+ profile=profile,+ instruction=req.instruction,+ brain=brain,+ source=f"provider:{provider}" if provider else "",+ )+ except prompt_improver.EmptyPrompt as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ except prompt_improver.ImproverUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except prompt_improver.ImproverFailed as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ log.info(+ "Prompt improver: %d -> %d chars via %s.", len(req.prompt), len(result.text), result.source+ )+ return {+ "improved": result.text,+ "source": result.source,+ "writer": result.writer,+ "folder": folder,+ }diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex 8ba81f2882..553e5bf0b0 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -517,6 +517,7 @@ class WebServer:from .frontier_routes import router as frontier_routerfrom .grok_build_routes import router as grok_build_routerfrom .ide_skills_routes import router as ide_skills_router+ from .prompt_improver_routes import router as prompt_improver_routerfrom .jarvisx_routes import router as jarvisx_routerfrom .live_routes import router as live_routerfrom .local_models_assistant_routes import (@@ -693,6 +694,8 @@ class WebServer:app.include_router(agentic_ide_git_router)# The Skills tab's library of saved Markdown prompts (/api/agentic-ide/skills/*).app.include_router(ide_skills_router)+ # The Prompt tab's rewrite of a typed prompt (/api/agentic-ide/prompt-improver).+ app.include_router(prompt_improver_router)app.include_router(agentic_ide_router)# The pane-activity sweep has no bus of its own (the registry is a plain# holder by design); this is the one place that holds one, so the sweepdiff --git a/tests/unit/agentic_ide/test_prompt_improver.py b/tests/unit/agentic_ide/test_prompt_improver.pynew file mode 100644index 0000000000..1e6c575c65--- /dev/null+++ b/tests/unit/agentic_ide/test_prompt_improver.py@@ -0,0 +1,183 @@+"""The Prompt tab's rewrite: the user's prompt, a model they picked, the repo as context.++Pinned here: the goal-not-implementation rule reaches the writer whatever+instruction the user typed, the writer sees the repository of the pane the+prompt is meant for, and a failure is reported as one. There is no template+fallback, because the user's own prompt is still in front of them.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.agentic_ide import prompt_improver, writer+from jarvis.agentic_ide.prompt_blueprint import GOAL_NOT_IMPLEMENTATION_RULE+from jarvis.agentic_ide.prompt_improver import (+ DEFAULT_INSTRUCTION,+ EmptyPrompt,+ ImproverFailed,+ ImproverUnavailable,+ improve,+ repo_context,+ system_prompt,+)+++class _Brain:+ """Answers with ``reply`` and keeps the requests it was sent."""++ name = "fake-writer"++ def __init__(self, reply: str = "Make the login form accessible.") -> None:+ self.reply = reply+ self.requests: list[object] = []++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ self.requests.append(request)+ yield type("Delta", (), {"content": self.reply})()+++class _DeadBrain:+ name = "dead-writer"++ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ raise RuntimeError("401 secret provider body")+ yield # pragma: no cover - makes this an async generator+++def test_the_default_instruction_is_one_sentence_plus_the_goal_rule() -> None:+ prompt = system_prompt()+ assert prompt.startswith(DEFAULT_INSTRUCTION)+ assert GOAL_NOT_IMPLEMENTATION_RULE in prompt+++def test_the_users_instruction_replaces_the_default_but_never_the_goal_rule() -> None:+ prompt = system_prompt(" Translate it to\nEnglish and tighten it. ")+ assert prompt.startswith("Translate it to English and tighten it.")+ assert DEFAULT_INSTRUCTION not in prompt+ assert GOAL_NOT_IMPLEMENTATION_RULE in prompt+++def test_the_repository_notes_describe_the_folder(tmp_path: Path) -> None:+ (tmp_path / ".git").mkdir()+ (tmp_path / ".git" / "HEAD").write_text("ref: refs/heads/feature/login\n", encoding="utf-8")+ (tmp_path / "pyproject.toml").write_text("[project]\nname = 'x'\n", encoding="utf-8")+ (tmp_path / "src").mkdir()++ context = repo_context(str(tmp_path), "fix the login")++ assert str(tmp_path) in context+ assert "feature/login" in context+ assert "src" in context+++def test_no_folder_means_no_repository_notes() -> None:+ assert repo_context("", "anything") == ""+++async def test_the_writer_gets_the_repo_and_the_prompt_and_its_answer_comes_back(+ tmp_path: Path,+) -> None:+ (tmp_path / "frontend").mkdir()+ brain = _Brain(" Make the login form accessible.\n")++ result = await improve("login form barrierefrei machen", folder=str(tmp_path), brain=brain)++ assert result.text == "Make the login form accessible."+ assert result.writer == "fake-writer"+ request = brain.requests[0]+ block = request.messages[0].content+ assert "PROMPT TO IMPROVE\nlogin form barrierefrei machen" in block+ assert str(tmp_path) in block and "frontend" in block+ assert GOAL_NOT_IMPLEMENTATION_RULE in request.system+++async def test_a_code_fence_around_the_whole_answer_is_dropped() -> None:+ brain = _Brain("```markdown\nShip the export.\nKeep the CSV columns.\n```")+ result = await improve("export", brain=brain)+ assert result.text == "Ship the export.\nKeep the CSV columns."+++async def test_an_empty_prompt_is_refused_before_any_model_is_asked() -> None:+ brain = _Brain()+ with pytest.raises(EmptyPrompt):+ await improve(" ", brain=brain)+ assert brain.requests == []+++async def test_an_empty_answer_is_a_failure_not_an_improvement() -> None:+ with pytest.raises(ImproverFailed):+ await improve("fix it", brain=_Brain(" "))+++async def test_a_failed_call_reports_its_type_and_never_the_providers_text() -> None:+ with pytest.raises(ImproverFailed) as caught:+ await improve("fix it", brain=_DeadBrain())+ assert "RuntimeError" in str(caught.value)+ assert "secret provider body" not in str(caught.value)+++async def test_no_pick_and_no_brief_writer_says_so(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(writer, "resolve_writer", lambda **_kwargs: (None, ""))+ with pytest.raises(ImproverUnavailable):+ await improve("fix it")+++async def test_no_pick_uses_the_ides_brief_writer(monkeypatch: pytest.MonkeyPatch) -> None:+ brain = _Brain("Fix the flaky upload test.")+ monkeypatch.setattr(writer, "resolve_writer", lambda **_kwargs: (brain, "tool_model:fake"))++ result = await improve("upload test flaky")++ assert result.text == "Fix the flaky upload test."+ assert result.source == "tool_model:fake"+++async def test_a_brief_writer_that_cannot_be_prepared_is_reported_by_type(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A broken configuration must not put its own text in front of the user."""++ def _broken(**_kwargs: object) -> tuple[object, str]:+ raise ValueError("jarvis.toml: secret detail")++ monkeypatch.setattr(writer, "resolve_writer", _broken)++ with pytest.raises(ImproverUnavailable) as caught:+ await improve("fix it")++ assert "ValueError" in str(caught.value)+ assert "secret detail" not in str(caught.value)+++async def test_unreadable_repository_notes_cost_the_context_never_the_rewrite(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _unreadable(*_args: object) -> str:+ raise OSError("disk went away")++ monkeypatch.setattr(prompt_improver, "repo_context", _unreadable)+ brain = _Brain("Fix it properly.")++ result = await improve("fix it", folder="/gone", brain=brain, source="provider:picked")++ assert result.text == "Fix it properly."+ assert result.source == "provider:picked"+ assert brain.requests[0].messages[0].content == "PROMPT TO IMPROVE\nfix it"+++async def test_the_call_is_filed_under_the_prompt_improver_in_the_usage_ledger() -> None:+ from jarvis.costs.ledger import current_caller++ seen: list[str] = []++ class _Watching(_Brain):+ async def complete(self, request): # noqa: ANN001, ANN202 - protocol fake+ seen.append(current_caller())+ yield type("Delta", (), {"content": "Done."})()++ await improve("fix it", brain=_Watching())++ assert seen == [prompt_improver.USAGE_CALLER]diff --git a/tests/unit/web/test_prompt_improver_route.py b/tests/unit/web/test_prompt_improver_route.pynew file mode 100644index 0000000000..e1f8998345--- /dev/null+++ b/tests/unit/web/test_prompt_improver_route.py@@ -0,0 +1,210 @@+"""The Prompt tab's route: improve a prompt, with the target pane's repo as context.++Pinned here: the writer is told about the folder of the pane the prompt is+meant for, the user's pick and instruction reach it unchanged, nothing is+typed into a pane, and each failure keeps its own status.+"""++from __future__ import annotations++from pathlib import Path++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import prompt_improver+from jarvis.agentic_ide import session as session_mod+from jarvis.agentic_ide.prompt_improver import ImprovedPrompt, ImproverFailed, ImproverUnavailable+from jarvis.agentic_ide.session import Registry+from jarvis.ui.web import prompt_improver_routes+from tests.fakes.fake_pty_manager import FakePtyManager++URL = "/api/agentic-ide/prompt-improver"++[email protected](autouse=True)+def _isolated_recents(+ tmp_path_factory: pytest.TempPathFactory, monkeypatch: pytest.MonkeyPatch+) -> None:+ from jarvis.agentic_ide import recents++ store = tmp_path_factory.mktemp("recents") / "recents.json"+ monkeypatch.setattr(recents, "_store_path", lambda: store)+++def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:+ monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))+ reg = Registry(pty_manager=FakePtyManager())+ monkeypatch.setattr(prompt_improver_routes, "get_registry", lambda: reg)+ return reg+++def client(registry: Registry) -> TestClient:+ app = FastAPI()+ app.include_router(prompt_improver_routes.router)+ return TestClient(app)+++def calls(monkeypatch: pytest.MonkeyPatch) -> list[dict]:+ """Stands in for the writer and keeps what the route asked of it."""+ seen: list[dict] = []++ async def _improve(prompt: str, **kwargs: object) -> ImprovedPrompt:+ seen.append({"prompt": prompt, **kwargs})+ return ImprovedPrompt(text="Improved.", source="provider:picked", writer="fake-writer")++ monkeypatch.setattr(prompt_improver, "improve", _improve)+ return seen+++def test_the_defaults_name_the_instruction_and_the_limits(client: TestClient) -> None:+ body = client.get(URL).json()+ assert body["default_instruction"] == prompt_improver.DEFAULT_INSTRUCTION+ assert body["max_prompt_chars"] == session_mod.MAX_PROMPT_CHARS+++def seats(monkeypatch: pytest.MonkeyPatch) -> list[tuple[object, str]]:+ """Offers one provider, ``picked``, and keeps the seats built for it."""+ from jarvis.agent_chat import catalog, service+ from jarvis.core import config as config_mod+ from jarvis.society import seat_brain++ built: list[tuple[object, str]] = []++ async def _seat_brain(_config: object, seat: object, *, caller: str) -> str:+ built.append((seat, caller))+ return "the-picked-brain"++ monkeypatch.setattr(catalog, "offers", lambda surface, provider: provider == "picked")+ monkeypatch.setattr(service, "resolve_runner", lambda provider, **_kwargs: "api")+ monkeypatch.setattr(config_mod, "load_config", lambda: object())+ monkeypatch.setattr(seat_brain, "seat_brain", _seat_brain)+ return built+++async def test_the_writer_is_told_about_the_target_panes_repository(+ client: TestClient,+ registry: Registry,+ calls: list[dict],+ seats: list[tuple[object, str]],+ tmp_path: Path,+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ assert registry.session is not None+ pane = registry.session.terminals[0]++ response = client.post(+ URL,+ json={+ "prompt": "make it faster",+ "provider": "Picked",+ "model": "model-x",+ "instruction": "Tighten it.",+ "workspace": registry.session.id,+ "pane": pane.key,+ },+ )++ assert response.status_code == 200+ assert response.json() == {+ "improved": "Improved.",+ "source": "provider:picked",+ "writer": "fake-writer",+ "folder": registry.session.folder,+ }+ call = calls[0]+ assert call["prompt"] == "make it faster"+ assert call["folder"] == registry.session.folder+ assert call["profile"] is registry.session.profile+ assert call["instruction"] == "Tighten it."+ # The pick is exactly that provider and model, on its own runner.+ seat, caller = seats[0]+ assert (seat.provider, seat.model, seat.runner) == ("picked", "model-x", "api")+ assert caller == prompt_improver.USAGE_CALLER+ assert (call["brain"], call["source"]) == ("the-picked-brain", "provider:picked")+ # Improving is a preview: the pane was never typed into.+ assert pane.prompts_sent == 0+++def test_a_provider_the_app_does_not_offer_is_refused(+ client: TestClient, calls: list[dict], seats: list[tuple[object, str]]+) -> None:+ response = client.post(URL, json={"prompt": "make it faster", "provider": "nobody"})+ assert response.status_code == 409+ assert calls == [] and seats == []+++def test_a_seat_that_cannot_be_prepared_is_reported_by_type(+ client: TestClient,+ calls: list[dict],+ seats: list[tuple[object, str]],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A broken configuration answers 409 without quoting itself."""+ from jarvis.core import config as config_mod++ def _broken() -> object:+ raise ValueError("jarvis.toml: secret detail")++ monkeypatch.setattr(config_mod, "load_config", _broken)++ response = client.post(URL, json={"prompt": "make it faster", "provider": "picked"})++ assert response.status_code == 409+ assert "ValueError" in response.json()["detail"]+ assert "secret detail" not in response.json()["detail"]+ assert calls == []+++async def test_a_pane_on_another_machine_gets_no_local_repository_notes(+ client: TestClient, registry: Registry, calls: list[dict], tmp_path: Path+) -> None:+ await registry.start(str(tmp_path), [{"agent": "claude"}])+ assert registry.session is not None+ pane = registry.session.terminals[0]+ pane.computer_id = "vps-1"++ response = client.post(+ URL,+ json={"prompt": "make it faster", "workspace": registry.session.id, "pane": pane.key},+ )++ assert response.status_code == 200+ assert calls[0]["folder"] == ""+++def test_without_a_workspace_the_prompt_is_still_improved(+ client: TestClient, calls: list[dict]+) -> None:+ response = client.post(URL, json={"prompt": "make it faster"})+ assert response.status_code == 200+ assert calls[0]["folder"] == ""+ assert response.json()["folder"] == ""+++def test_an_empty_prompt_is_rejected(client: TestClient, calls: list[dict]) -> None:+ assert client.post(URL, json={"prompt": ""}).status_code == 422+ assert calls == []+++ ("error", "status"),+ [(ImproverUnavailable("no model"), 409), (ImproverFailed("it died"), 502)],+)+def test_each_failure_keeps_its_own_status(+ client: TestClient, monkeypatch: pytest.MonkeyPatch, error: Exception, status: int+) -> None:+ async def _improve(_prompt: str, **_kwargs: object) -> ImprovedPrompt:+ raise error++ monkeypatch.setattr(prompt_improver, "improve", _improve)++ response = client.post(URL, json={"prompt": "make it faster"})++ assert response.status_code == status+ assert response.json()["detail"] == str(error)