Skip to content

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.

feat(agentic-ide): replace the Prompt tab with a plain AI chat (#647)

Ruben Lütke232a74212b87
diff --git a/jarvis/agent_chat/catalog.py b/jarvis/agent_chat/catalog.py
index 1d4ca1e8ed..bda6680792 100644
--- a/jarvis/agent_chat/catalog.py
+++ b/jarvis/agent_chat/catalog.py
@@ -412,7 +412,20 @@ def rows_for(surface: str) -> tuple[ProviderRow, ...]:
"""
from jarvis.agent_chat.surface_kits import kit_for
- if kit_for(surface).cli_seats:
+ kit = kit_for(surface)
+ if kit.plain:
+ # A plain chat seats whatever can answer with no tool: every provider
+ # an API key drives, and the CLIs that have a tool-free mode.
+ from jarvis.agent_chat.native_control import TOOL_FREE_RUNNERS
+ from jarvis.agent_chat.runner_api import supports_api_runner
+
+ return tuple(
+ row
+ for row in PROVIDER_ROWS
+ if supports_api_runner(row.id)
+ or (row.runner in TOOL_FREE_RUNNERS and _ide_has(row.agent))
+ )
+ if kit.cli_seats:
return tuple(row for row in PROVIDER_ROWS if not row.agent or _ide_has(row.agent))
from jarvis.agent_chat.runner_api import supports_api_runner
diff --git a/jarvis/agent_chat/native_control.py b/jarvis/agent_chat/native_control.py
index 26c3f91e1b..6c2aeb6a49 100644
--- a/jarvis/agent_chat/native_control.py
+++ b/jarvis/agent_chat/native_control.py
@@ -19,8 +19,20 @@ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
log = logging.getLogger(__name__)
-def disable_cli_tools(plan: Any, runner: str) -> None:
- """A verifier has no tools, including user-installed MCP servers."""
+#: The CLIs ``disable_cli_tools`` can strip of every tool: the Claude Code
+#: shaped ones by flag, Codex by feature switches. The rest only offer a
+#: read-only plan mode, which still reads the checkout.
+_CLAUDE_SHAPED: tuple[str, ...] = ("claude-cli", "glm-cli")
+_CODEX: str = "codex-cli"
+TOOL_FREE_RUNNERS: frozenset[str] = frozenset({*_CLAUDE_SHAPED, _CODEX})
+
+
+def disable_cli_tools(plan: Any, runner: str, *, keep_session: bool = False) -> None:
+ """A verifier has no tools, including user-installed MCP servers.
+
+ ``keep_session`` leaves the CLI's own conversation on disk, so a plain
+ chat can resume it on its next turn; a one-shot verifier leaves it off.
+ """
argv: list[str] = []
it = iter(plan.argv)
for part in it:
@@ -32,14 +44,14 @@ def disable_cli_tools(plan: Any, runner: str) -> None:
argv.extend((part, value))
else:
argv.append(part)
- if runner in ("claude-cli", "glm-cli"):
+ if runner in _CLAUDE_SHAPED:
argv += ["--tools", "", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}']
- if "--resume" not in argv:
+ if "--resume" not in argv and not keep_session:
argv.append("--no-session-persistence")
- elif runner == "codex-cli":
+ elif runner == _CODEX:
# exec ignores only configuration, not the selected account's auth store.
argv += ["--ignore-user-config", "--ignore-rules"]
- if "resume" not in argv:
+ if "resume" not in argv and not keep_session:
argv.append("--ephemeral")
for feature in (
"shell_tool",
diff --git a/jarvis/agent_chat/plain_chat.py b/jarvis/agent_chat/plain_chat.py
new file mode 100644
index 0000000000..2da13d3081
--- /dev/null
+++ b/jarvis/agent_chat/plain_chat.py
@@ -0,0 +1,75 @@
+"""A plain chat on a coding CLI: how the conversation is opened.
+
+A plain surface (``SurfaceKit.plain_chat``) has no tools on any seat. An API
+seat takes the surface's system prompt as its system prompt. A coding CLI run
+tool-free keeps its own, so the surface's instructions travel at the head of
+the first message it is sent, and the CLI's own session carries them from
+there.
+
+"First message" means every time the CLI starts a conversation, not only the
+chat's first turn: a session it can no longer resume (a folder that moved, a
+pruned session, a seat that changed) starts fresh, and the fresh one gets the
+instructions again together with what was said so far. Without that a chat
+would lose its framing for good the first time a resume failed.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+#: Room for what was said before, newest kept. A fresh CLI conversation needs
+#: the thread of the chat, not every word of it.
+TRANSCRIPT_CHARS = 8000
+
+#: Where a tool-free CLI could still write, its sandbox is read-only as well.
+#: Claude Code with no tools has no such path; Codex keeps its patch tool.
+READ_ONLY_MODE: dict[str, str] = {"codex-cli": "read-only"}
+
+
+def transcript(history: list[dict[str, Any]], *, max_chars: int = TRANSCRIPT_CHARS) -> str:
+ """The chat so far as plain lines, bounded from the newest message back."""
+ lines: list[str] = []
+ for event in history:
+ text = str((event.get("payload") or {}).get("text") or "").strip()
+ if not text:
+ continue
+ if event.get("kind") == "user_message":
+ lines.append(f"User: {text}")
+ elif event.get("kind") == "assistant_text":
+ lines.append(f"Assistant: {text}")
+ kept: list[str] = []
+ used = 0
+ for line in reversed(lines):
+ if kept and used + len(line) > max_chars:
+ break
+ kept.append(line[-max_chars:])
+ used += len(line)
+ return "\n\n".join(reversed(kept))
+
+
+def opening(system: str, history: list[dict[str, Any]], user_text: str) -> str:
+ """The message that starts a CLI conversation for a plain chat."""
+ parts = [f"<chat_instructions>\n{system}\n</chat_instructions>"]
+ earlier = transcript(history)
+ if earlier:
+ parts.append(f"<earlier_conversation>\n{earlier}\n</earlier_conversation>")
+ parts.append(user_text)
+ return "\n\n".join(parts)
+
+
+def cli_prompt(handle: Any, user_text: str, resume: str | None) -> str:
+ """What a CLI is sent for this turn: the opening when it starts fresh."""
+ system = str(getattr(handle, "plain_system", "") or "")
+ if not system or resume:
+ return user_text
+ return opening(system, list(getattr(handle, "history", None) or []), user_text)
+
+
+def permission_mode(handle: Any, runner: str, mode: str) -> str:
+ """The permission mode a plain chat's CLI turn is planned with."""
+ if not getattr(handle, "plain_system", ""):
+ return mode
+ return READ_ONLY_MODE.get(runner, mode)
+
+
+__all__ = ["cli_prompt", "opening", "permission_mode", "transcript"]
diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.py
index fefb3ff584..e2ef3e3136 100644
--- a/jarvis/agent_chat/runner_api.py
+++ b/jarvis/agent_chat/runner_api.py
@@ -155,6 +155,9 @@ class TurnHandle:
surface: str = "agent"
stance: str = ""
tools_disabled: bool = False
+ #: A plain chat's whole system prompt (``SurfaceKit.plain_chat``); empty on
+ #: every other surface. With it the turn carries no tools.
+ plain_system: str = ""
gateway_only: bool = False
output_language: str = ""
goal_turn: bool = False
@@ -327,7 +330,9 @@ async def run_api_turn(handle: TurnHandle, user_text: str) -> None:
messages = messages_from_events(handle.history)
messages.append(BrainMessage(role="user", content=user_text))
permission_mode = normalize_permission("api", session.permission_mode)
- system = system_prompt(
+ # Either says it: a turn told to carry no tools never gets the tool set.
+ plain = handle.tools_disabled or bool(handle.plain_system)
+ system = handle.plain_system or system_prompt(
cwd=cwd, assistant_name=handle.assistant_name, plan=permission_mode == "plan"
)
if handle.output_language:
@@ -337,8 +342,11 @@ async def run_api_turn(handle: TurnHandle, user_text: str) -> None:
system += "\n\n" + note.strip()
# Plan mode hands the model only the reading tools: it cannot change a
# thing, and it is told so in the system prompt.
+ # A plain chat hands it none at all: the answer is the whole turn.
tools: tuple[dict[str, Any], ...] = (
- tuple(spec for spec in TOOL_SPECS if spec["name"] in READ_ONLY_TOOLS)
+ ()
+ if plain
+ else tuple(spec for spec in TOOL_SPECS if spec["name"] in READ_ONLY_TOOLS)
if permission_mode == "plan"
else TOOL_SPECS
)
@@ -425,7 +433,7 @@ async def run_api_turn(handle: TurnHandle, user_text: str) -> None:
)
)
- if not tool_calls:
+ if not tool_calls or plain:
break
# Record the assistant round (text + tool_use blocks) for the
diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.py
index 3bc8fbb316..c4281367da 100644
--- a/jarvis/agent_chat/runner_cli.py
+++ b/jarvis/agent_chat/runner_cli.py
@@ -3463,7 +3463,11 @@ async def _run_cli_once(
# A society agent placed on another computer runs its CLI there over SSH.
placement = await placement_for_session(session)
remote_token = _REMOTE_PLANNING.set(placement is not None)
- planned_prompt = user_text
+ from jarvis.agent_chat import plain_chat
+
+ # A plain chat's instructions open every conversation the CLI starts,
+ # the one a lost resume falls back to included.
+ planned_prompt = plain_chat.cli_prompt(handle, user_text, resume)
# Set once planning succeeded; an external runtime's plan holds a turn slot.
plan: CliPlan | None = None
if placement is not None and not getattr(handle, "tools_disabled", False):
@@ -3539,7 +3543,9 @@ async def _run_cli_once(
cwd=cwd,
model=session.model,
effort=effort,
- permission_mode=session.permission_mode,
+ permission_mode=plain_chat.permission_mode(
+ handle, runner, session.permission_mode
+ ),
resume=resume,
identity=identity,
)
@@ -3547,7 +3553,10 @@ async def _run_cli_once(
if getattr(handle, "tools_disabled", False):
from .native_control import disable_cli_tools
- disable_cli_tools(plan, runner)
+ # A plain chat is a conversation: its next turn resumes this one.
+ disable_cli_tools(
+ plan, runner, keep_session=bool(getattr(handle, "plain_system", ""))
+ )
if getattr(handle, "gateway_only", False):
if runner == "claude-cli":
plan.argv += ["--tools", "", "--strict-mcp-config"]
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index 3fa40292a1..06ae43473e 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -1447,6 +1447,13 @@ class AgentChatService:
)
bus = self._bus()
+ # A plain chat's system prompt is the surface's own. Written per
+ # turn, so its workspace notes follow the session's folder.
+ plain_system = (
+ await kit.plain_chat(session, text, self._assistant_name())
+ if kit.plain_chat is not None
+ else ""
+ )
handle = TurnHandle(
session=session,
turn_id=turn_id,
@@ -1456,6 +1463,8 @@ class AgentChatService:
),
cancel=cancel,
history=history,
+ tools_disabled=kit.plain,
+ plain_system=plain_system,
assistant_name=self._assistant_name(),
bus=bus,
surface=session.surface,
diff --git a/jarvis/agent_chat/store.py b/jarvis/agent_chat/store.py
index 52a85bf4cc..3d97760e73 100644
--- a/jarvis/agent_chat/store.py
+++ b/jarvis/agent_chat/store.py
@@ -106,7 +106,9 @@ _PREVIEW_MAX_CHARS = 120
#: session list. ``"society"`` is an agent's one canonical chat (session id
#: ``society:<agent_id>``, see ``jarvis/society/chat_binding.py``): Jarvis'
#: brain runner with the agent's own hands, listed only inside the society.
-SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models", "society")
+#: ``"side"`` is the Agentic IDE's side chat: a plain conversation with no
+#: tools on any seat, listed only in the IDE's side panel.
+SURFACES: Final[tuple[str, ...]] = ("jarvis", "agent", "local-models", "society", "side")
DEFAULT_SURFACE: Final[str] = "agent"
diff --git a/jarvis/agent_chat/surface_kits.py b/jarvis/agent_chat/surface_kits.py
index a047f0ba48..c7e8930134 100644
--- a/jarvis/agent_chat/surface_kits.py
+++ b/jarvis/agent_chat/surface_kits.py
@@ -50,6 +50,8 @@ SessionDirectTools = Callable[[Any], frozenset[str] | None]
#: its own way (a society agent writes its own approval rule); ``False`` =
#: the service falls back to its default (the session flips to auto).
SessionAlwaysAllow = Callable[[Any, str, dict[str, Any]], Awaitable[bool]]
+#: ``(session, user_text, assistant_name) -> system prompt`` of a plain chat.
+PlainChatBuilder = Callable[[Any, str, str], Awaitable[str]]
@dataclass(frozen=True, slots=True)
@@ -116,6 +118,15 @@ class SurfaceKit:
#: block becomes a question card and a finished plan-mode turn a plan card,
#: so every CLI can ask and have its plan approved, not only Claude Code.
turn_prompts: bool = False
+ #: A plain conversation: no tool on any seat. The builder writes the whole
+ #: system prompt; an API seat gets it as its system prompt, a CLI seat at
+ #: the head of every conversation it starts. The picker lists only the seats that can
+ #: answer without tools (``catalog.rows_for``).
+ plain_chat: PlainChatBuilder | None = None
+
+ @property
+ def plain(self) -> bool:
+ return self.plain_chat is not None
def _chat_workspace() -> Path:
@@ -218,6 +229,13 @@ def _society_history_start(session: Any) -> int:
return runtime.conversations.checkpoint(session.session_id)[0] if runtime is not None else 0
+async def _side_chat(session: Any, user_text: str, assistant_name: str) -> str:
+ """The IDE side chat's system prompt (lazy, AP-26)."""
+ from jarvis.agentic_ide.side_chat import system_prompt
+
+ return await system_prompt(session, user_text, assistant_name)
+
+
def _only_local_models(tools: dict[str, Tool]) -> dict[str, Tool]:
"""Its own hands and nothing else.
@@ -301,6 +319,16 @@ _KITS: Final[dict[str, SurfaceKit]] = {
history_start=_society_history_start,
workspace_dir=_chat_workspace,
),
+ # The Agentic IDE's side chat: a plain AI chat beside the terminals. No
+ # tools, no approvals, no workspace - the model answers from the
+ # conversation alone. Subscription CLIs may answer too, run tool-free, so a
+ # person without an API key still has a chat.
+ "side": SurfaceKit(
+ surface="side",
+ cli_seats=True,
+ plain_chat=_side_chat,
+ workspace_dir=_chat_workspace,
+ ),
}
diff --git a/jarvis/agentic_ide/prompt_improver.py b/jarvis/agentic_ide/prompt_improver.py
deleted file mode 100644
index 306807ef38..0000000000
--- a/jarvis/agentic_ide/prompt_improver.py
+++ /dev/null
@@ -1,258 +0,0 @@
-"""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/agentic_ide/side_chat.py b/jarvis/agentic_ide/side_chat.py
new file mode 100644
index 0000000000..5f80b18fa6
--- /dev/null
+++ b/jarvis/agentic_ide/side_chat.py
@@ -0,0 +1,30 @@
+"""The Agentic IDE's side chat: what the model is told.
+
+The side panel's Chat tab is a plain AI chat: the person picks a model, asks
+anything, reads the answer. It is not a coding agent and knows nothing about
+the workspace beside it. The model has no tools on any seat
+(``SurfaceKit.plain_chat``), and this short system prompt is all it is given:
+who it is and how to answer.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+_INSTRUCTIONS = """\
+You are {name}, an AI assistant in a chat. Answer questions on any topic \
+directly and helpfully, in the language the person writes in, as long as the \
+question needs and no longer. Use Markdown where it helps: lists, tables, and \
+fenced code blocks with a language tag.
+
+You have no tools in this chat: you cannot browse the web, open files or run \
+anything. When a question would need that, say so in a sentence and answer \
+from what you know."""
+
+
+async def system_prompt(_session: Any, _user_text: str, assistant_name: str) -> str:
+ """The side chat's whole system prompt. The same for every turn and folder."""
+ return _INSTRUCTIONS.format(name=assistant_name or "the assistant")
+
+
+__all__ = ["system_prompt"]
diff --git a/jarvis/ui/web/agent_chat_routes.py b/jarvis/ui/web/agent_chat_routes.py
index fce24627ea..07366df5c9 100644
--- a/jarvis/ui/web/agent_chat_routes.py
+++ b/jarvis/ui/web/agent_chat_routes.py
@@ -83,17 +83,19 @@ log = logging.getLogger(__name__)
#: The Pydantic twin of ``jarvis.agent_chat.store.SURFACES`` (AP-4; the parity
#: test in tests/unit/agent_chat/test_agent_chat_surface_parity.py pins it).
-SurfaceName = Literal["jarvis", "agent", "local-models", "society"]
+SurfaceName = Literal["jarvis", "agent", "local-models", "society", "side"]
#: The same names, as data — a multipart form field cannot be typed by a
#: ``Literal`` without turning an unknown surface into a 422 on a file the
#: person just dropped.
-SURFACE_NAMES: frozenset[str] = frozenset({"jarvis", "agent", "local-models", "society"})
+SURFACE_NAMES: frozenset[str] = frozenset(
+ {"jarvis", "agent", "local-models", "society", "side"}
+)
#: Surfaces that never appear in an unfiltered session list: an agent's
-#: canonical chat belongs to its model card, not to the IDE's or the front
-#: page's history.
-HIDDEN_SURFACES: frozenset[str] = frozenset({"society"})
+#: canonical chat belongs to its model card, and the IDE's side chat to its
+#: side panel, not to the IDE's threads or the front page's history.
+HIDDEN_SURFACES: frozenset[str] = frozenset({"society", "side"})
router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"])
@@ -492,6 +494,7 @@ def _catalog_rows(
# own: other surfaces keep every seat.
prefs = agent_provider_prefs.load()
agents = surface == agent_provider_prefs.AGENT_SURFACE
+ plain = kit_for(surface).plain
rows: list[dict[str, Any]] = []
for row in rows_for(surface):
d = row.to_dict()
@@ -521,7 +524,8 @@ def _catalog_rows(
# Which characters open the composer's typeahead on this seat —
# decided here, from the runner, so the box never offers a "/" list
# to a seat that would read it as plain text.
- d["typeahead"] = list(typeahead.triggers_for(runner, surface))
+ # A plain chat has nothing to complete against: no commands, no files.
+ d["typeahead"] = [] if plain else list(typeahead.triggers_for(runner, surface))
if agents:
d["enabled"] = prefs.enabled(row.id)
d["hidden_models"] = list(prefs.hidden(row.id))
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx
new file mode 100644
index 0000000000..863a586d3a
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.test.tsx
@@ -0,0 +1,138 @@
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { TimelineItem, TurnBlock, TurnItem, TurnStatus } from "@/components/agentchat/reduce";
+import { useIdeChatStore } from "@/store/ideChat";
+import { SideChatTab } from "./SideChatTab";
+import { useSideChatStore } from "./sideChatStore";
+
+function turn(blocks: TurnBlock[], status: TurnStatus = "done"): TurnItem {
+ return {
+ type: "turn", id: "t1", provider: "fake", model: "", effort: "", runner: "api", status, blocks,
+ startedMs: Date.now(), durationMs: status === "running" ? null : 9000, usage: null, liveUsage: null, costUsd: null, error: null,
+ };
+}
+
+const USER: TimelineItem = { type: "user", id: "u1", text: "improve my prompt", tsMs: Date.now(), attachments: [] } as unknown as TimelineItem;
+const THOUGHT: TurnBlock = { kind: "reasoning", id: "r1", text: "The person wants a goal, not steps.", durationMs: 3000, live: false, startedMs: Date.now() };
+const ANSWER: TurnBlock = { kind: "text", id: "a1", text: "Make the login form accessible." };
+
+const PROVIDER = {
+ id: "fake", label: "Fake", family: "fake", runner: "api", models_source: "curated", curated_models: [{ id: "m1", label: "Model One" }],
+ default_model: "m1", keyless: true, effort_levels: [], default_effort: "", permission_modes: [], default_permission_mode: "", cli_installed: null,
+};
+
+/** The store as it is once the catalog has loaded, with `items` on screen. */
+function seed(items: TimelineItem[], extra: Record<string, unknown> = {}) {
+ const send = vi.fn(async () => "sent" as const);
+ const cancel = vi.fn(async () => undefined);
+ useSideChatStore.setState({
+ catalog: { providers: [PROVIDER], default_cwd: "", shell: "", selection: null },
+ catalogStale: false,
+ connections: [],
+ draft: { provider: "fake", model: "m1", effort: "", permissionMode: "", buildMode: "", cwd: "" },
+ timeline: { items, pendingApprovals: [], lastSeq: 0, sessionPatch: null },
+ sessions: [],
+ activeSessionId: items.length ? "s1" : null,
+ busy: false,
+ lastError: null,
+ catalogError: null,
+ send,
+ cancel,
+ loadCatalog: vi.fn(async () => undefined),
+ loadSessions: vi.fn(async () => undefined),
+ setDraft: vi.fn(async () => undefined),
+ ...extra,
+ } as never);
+ return { send, cancel };
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ useIdeChatStore.setState({ workspace: null });
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+describe("SideChatTab", () => {
+ it("greets an empty chat as a plain chat, with nothing about a workspace or terminals", () => {
+ seed([]);
+ render(<SideChatTab />);
+
+ const empty = screen.getByTestId("side-chat-empty").textContent ?? "";
+ expect(empty).toContain("How can I help?");
+ expect(empty).not.toMatch(/workspace|terminal/i);
+ expect(screen.queryByTestId("side-chat-send-to-terminal")).toBeNull();
+ });
+
+ it("never points the chat at a folder", () => {
+ useIdeChatStore.setState({ workspace: { id: "w1", name: "App", path: "/repo/now" } });
+ const setDraft = vi.fn(async () => undefined);
+ seed([], { setDraft });
+ render(<SideChatTab />);
+ expect(setDraft).not.toHaveBeenCalled();
+ });
+
+ it("sends on Enter, keeps Shift+Enter for a new line, and clears the box", async () => {
+ const { send } = seed([]);
+ render(<SideChatTab />);
+ const input = screen.getByTestId("side-chat-input") as HTMLTextAreaElement;
+
+ fireEvent.change(input, { target: { value: "hello" } });
+ fireEvent.keyDown(input, { key: "Enter", shiftKey: true });
+ expect(send).not.toHaveBeenCalled();
+ fireEvent.keyDown(input, { key: "Enter" });
+
+ await waitFor(() => expect(send).toHaveBeenCalledWith("hello"));
+ expect(input.value).toBe("");
+ });
+
+ it("puts a message that never left back into the box", async () => {
+ seed([], { send: vi.fn(async () => "failed" as const) });
+ render(<SideChatTab />);
+ const input = screen.getByTestId("side-chat-input") as HTMLTextAreaElement;
+
+ fireEvent.change(input, { target: { value: "hello" } });
+ fireEvent.click(screen.getByTestId("side-chat-send"));
+
+ await waitFor(() => expect(input.value).toBe("hello"));
+ });
+
+ it("folds a finished answer's thinking behind the time it took", () => {
+ seed([USER, turn([THOUGHT, ANSWER])]);
+ render(<SideChatTab />);
+
+ expect(screen.getByText("Make the login form accessible.")).toBeTruthy();
+ // An answer offers Copy and nothing that reaches into the IDE.
+ expect(screen.queryByTestId("side-chat-send-to-terminal")).toBeNull();
+ const fold = screen.getByTestId("thread-worked-for");
+ expect(fold.textContent).toContain("Thought for 3.0s");
+ // The thought itself is one click away, not in the way.
+ expect(screen.queryByText("The person wants a goal, not steps.")).toBeNull();
+ fireEvent.click(fold);
+ expect(screen.getByText("The person wants a goal, not steps.")).toBeTruthy();
+ });
+
+ it("shows a stop button while the model answers", () => {
+ const { cancel } = seed([USER, turn([], "running")]);
+ render(<SideChatTab />);
+
+ expect(screen.getByTestId("thread-working").textContent).toContain("Thinking for");
+ fireEvent.click(screen.getByTestId("side-chat-stop"));
+ expect(cancel).toHaveBeenCalled();
+ });
+
+ it("asks for a restart when the running backend does not know the chat yet", () => {
+ seed([], { catalog: null, catalogError: "422: Input should be 'jarvis', 'agent'" });
+ render(<SideChatTab />);
+ expect(screen.getByTestId("side-chat-error").textContent).toContain("Restart the app once");
+ });
+
+ it("keeps the stop button while text is typed during an answer", () => {
+ seed([USER, turn([], "running")]);
+ render(<SideChatTab />);
+ fireEvent.change(screen.getByTestId("side-chat-input"), { target: { value: "next question" } });
+ expect(screen.getByTestId("side-chat-stop")).toBeTruthy();
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx
new file mode 100644
index 0000000000..9039dfa0eb
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/SideChatTab.tsx
@@ -0,0 +1,196 @@
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
+import { ArrowUp, History, Square, SquarePen, Trash2 } from "lucide-react";
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+import { joinProviderOptions } from "@/store/agentChat";
+import { AgentModelPicker, EffortPicker } from "@/components/agentic/threads/ThreadPickers";
+import { ThreadMenuItem, ThreadMenuSeparator, ThreadPopover } from "@/components/agentic/threads/ThreadPopover";
+import { ThreadTimeline } from "@/components/agentic/threads/ThreadTimeline";
+import { shortAge } from "@/components/agentic/threads/threadModel";
+import { useSideChatStore } from "./sideChatStore";
+
+const DRAFT_KEY = "jarvis.agenticIde.sideChat.message.v1";
+/** How many earlier chats the history list shows. */
+const HISTORY_ROWS = 30;
+
+function storedMessage(): string {
+ try {
+ return localStorage.getItem(DRAFT_KEY) ?? "";
+ } catch {
+ return "";
+ }
+}
+
+function persistMessage(value: string): void {
+ try {
+ if (value) localStorage.setItem(DRAFT_KEY, value);
+ else localStorage.removeItem(DRAFT_KEY);
+ } catch {
+ /* a convenience only: the box keeps the text for this session */
+ }
+}
+
+const ICON_BTN =
+ "inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-md 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";
+
+/**
+ * The side panel's Chat surface: a plain AI chat with the model you pick.
+ *
+ * Ask anything, read the answer. It is not a coding agent and knows nothing
+ * about the workspace: no seat on its surface has tools, and the model is told
+ * only how to answer. Answers stream, and a model's thinking folds behind one
+ * line once it is done.
+ */
+export function SideChatTab() {
+ const t = useT();
+ const catalog = useSideChatStore((state) => state.catalog);
+ const connections = useSideChatStore((state) => state.connections);
+ const liveModels = useSideChatStore((state) => state.liveModels);
+ const draft = useSideChatStore((state) => state.draft);
+ const timeline = useSideChatStore((state) => state.timeline);
+ const sessions = useSideChatStore((state) => state.sessions);
+ const activeSessionId = useSideChatStore((state) => state.activeSessionId);
+ const activeSession = useSideChatStore((state) => state.activeSession);
+ const busy = useSideChatStore((state) => state.busy);
+ const lastError = useSideChatStore((state) => state.lastError);
+ const catalogError = useSideChatStore((state) => state.catalogError);
+
+ const [message, setMessageState] = useState(storedMessage);
+ const [historyOpen, setHistoryOpen] = useState(false);
+ const historyAnchor = useRef<HTMLButtonElement | null>(null);
+ const input = useRef<HTMLTextAreaElement | null>(null);
+
+ const setMessage = useCallback((value: string) => {
+ setMessageState(value);
+ persistMessage(value);
+ }, []);
+
+ useEffect(() => {
+ const store = useSideChatStore.getState();
+ if (!store.catalog || store.catalogStale) void store.loadCatalog();
+ void store.loadSessions();
+ }, []);
+
+ // The box grows with what is typed, up to a share of the panel.
+ useLayoutEffect(() => {
+ const box = input.current;
+ if (!box) return;
+ box.style.height = "auto";
+ box.style.height = `${box.scrollHeight}px`;
+ }, [message]);
+
+ const providers = useMemo(
+ () => (catalog ? joinProviderOptions(catalog.providers, connections) : [])
+ .slice()
+ .sort((a, b) => Number(b.connected) - Number(a.connected)),
+ [catalog, connections],
+ );
+ const provider = providers.find((option) => option.id === draft.provider) ?? null;
+ const running = busy || timeline.items.some((item) => item.type === "turn" && item.status === "running");
+ const canSend = message.trim().length > 0 && !running && Boolean(provider?.connected);
+ const started = timeline.items.length > 0;
+
+ const send = useCallback(async () => {
+ const text = message.trim();
+ if (!text || running) return;
+ setMessage("");
+ const outcome = await useSideChatStore.getState().send(text);
+ // A message that never left comes back into the box.
+ if (outcome === "failed") setMessage(text);
+ }, [message, running, setMessage]);
+
+ const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
+ event.preventDefault();
+ void send();
+ };
+
+ const newChat = () => {
+ useSideChatStore.getState().newChat();
+ input.current?.focus();
+ };
+
+ const earlier = useMemo(
+ () => [...sessions].sort((a, b) => b.updated_ms - a.updated_ms).slice(0, HISTORY_ROWS),
+ [sessions],
+ );
+ // A backend from before this chat existed refuses its surface outright:
+ // the app was updated and not yet restarted. Say that, not the refusal.
+ const error = lastError || (catalogError && !catalog ? t("ide_side_panel.chat.needs_restart") : catalogError);
+ // The list is refreshed after every send; the session held from creation has no title yet.
+ const listed = sessions.find((session) => session.session_id === activeSessionId);
+ const title = listed?.title?.trim() || activeSession?.title?.trim() || t("ide_side_panel.chat.new_chat");
+
+ return (
+ <div data-testid="side-chat-tab" className="flex h-full min-h-0 flex-col">
+ <header className="flex h-10 shrink-0 items-center gap-1 border-b border-border/60 px-2">
+ <span className="min-w-0 flex-1 truncate px-1 text-sm text-foreground" data-testid="side-chat-title">{title}</span>
+ <button ref={historyAnchor} type="button" onClick={() => setHistoryOpen((value) => !value)} aria-haspopup="menu" aria-expanded={historyOpen}
+ aria-label={t("ide_side_panel.chat.history")} title={t("ide_side_panel.chat.history")} data-testid="side-chat-history" className={ICON_BTN}>
+ <History className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ <button type="button" onClick={newChat} disabled={!started && !activeSessionId}
+ aria-label={t("ide_side_panel.chat.new_chat")} title={t("ide_side_panel.chat.new_chat")} data-testid="side-chat-new" className={ICON_BTN}>
+ <SquarePen className="h-3.5 w-3.5" aria-hidden />
+ </button>
+ <ThreadPopover anchor={historyAnchor} open={historyOpen} onClose={() => setHistoryOpen(false)} align="end" width={300} label={t("ide_side_panel.chat.history")}>
+ {earlier.length === 0 && <p className="px-2 py-2 text-sm text-muted-foreground">{t("ide_side_panel.chat.history_empty")}</p>}
+ {earlier.map((session) => <ThreadMenuItem key={session.session_id}
+ label={session.title?.trim() || t("ide_side_panel.chat.new_chat")}
+ hint={shortAge(session.updated_ms)}
+ selected={session.session_id === activeSessionId}
+ onSelect={() => { setHistoryOpen(false); useSideChatStore.getState().openSession(session.session_id); }} />)}
+ {activeSessionId && <>
+ <ThreadMenuSeparator />
+ <ThreadMenuItem danger icon={<Trash2 className="h-3.5 w-3.5" />} label={t("ide_side_panel.chat.delete_chat")}
+ onSelect={() => { setHistoryOpen(false); void useSideChatStore.getState().removeSession(activeSessionId); }} />
+ </>}
+ </ThreadPopover>
+ </header>
+
+ {started
+ ? <ThreadTimeline items={timeline.items} sessionId={activeSessionId} bottomInset={0} tone="chat" />
+ : <div className="flex min-h-0 flex-1 flex-col items-center justify-center px-6 text-center" data-testid="side-chat-empty">
+ <h2 className="text-xl font-medium text-foreground-strong">{t("ide_side_panel.chat.empty_title")}</h2>
+ <p className="mt-2 max-w-xs text-sm leading-6 text-muted-foreground">{t("ide_side_panel.chat.empty_hint")}</p>
+ </div>}
+
+ <div className="shrink-0 px-3 pb-3 pt-1">
+ {error && <p role="alert" data-testid="side-chat-error" className="mb-2 px-1 text-xs text-destructive">{error}</p>}
+ <div className="overflow-hidden rounded-3xl border border-border bg-card shadow-[0_8px_24px_-12px_rgb(var(--scrim-rgb)/0.5)] transition-colors focus-within:border-border-strong">
+ <textarea ref={input} value={message} rows={2}
+ onChange={(event) => setMessage(event.target.value)} onKeyDown={onKeyDown}
+ aria-label={t("ide_side_panel.chat.input_aria")} placeholder={t("ide_side_panel.chat.placeholder")}
+ data-testid="side-chat-input"
+ className="block max-h-[36vh] min-h-[64px] w-full resize-none bg-transparent px-4 pb-1 pt-3.5 text-base leading-6 text-foreground outline-none placeholder:text-faint-foreground scrollbar-jarvis" />
+ <div className="flex min-w-0 items-center justify-between gap-2 px-2.5 pb-2.5">
+ <div className="-ms-0.5 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto [scrollbar-width:none]">
+ <AgentModelPicker providers={providers} liveModels={liveModels} draft={draft}
+ lockedProvider={started && activeSessionId ? draft.provider : null}
+ onPick={(nextProvider, model) => void useSideChatStore.getState().setDraft(nextProvider !== draft.provider ? { provider: nextProvider, model } : { model })} />
+ <EffortPicker provider={provider} draft={draft} liveModels={liveModels} separated
+ onPick={(effort) => void useSideChatStore.getState().setDraft({ effort })} />
+ </div>
+ {running
+ ? <button type="button" aria-label={t("ide_side_panel.chat.stop")} title={t("ide_side_panel.chat.stop")} data-testid="side-chat-stop"
+ onClick={() => void useSideChatStore.getState().cancel("side-chat-stop-button")}
+ className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-foreground text-background transition-transform duration-150 hover:scale-105 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <Square className="h-3 w-3 fill-current" />
+ </button>
+ : <button type="button" aria-label={t("ide_side_panel.chat.send")} title={t("ide_side_panel.chat.send")} data-testid="side-chat-send"
+ disabled={!canSend} onClick={() => void send()}
+ className={cn(
+ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-accent text-accent-foreground shadow-[0_1px_2px_rgb(var(--accent-rgb)/0.3)]",
+ "transition-[opacity,transform] duration-150 hover:scale-105 hover:opacity-95 disabled:opacity-40 disabled:hover:scale-100",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ )}>
+ <ArrowUp className="h-4 w-4" />
+ </button>}
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/sideChatStore.ts b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/sideChatStore.ts
new file mode 100644
index 0000000000..dada00f218
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/chat/sideChatStore.ts
@@ -0,0 +1,8 @@
+import { createAgentChatStore } from "@/store/agentChat";
+
+/**
+ * The side panel chat's store: its own sessions, socket and model pick, on the
+ * `side` surface. That surface is a plain conversation; no seat on it has
+ * tools (`jarvis/agent_chat/surface_kits.py`).
+ */
+export const useSideChatStore = createAgentChatStore("side");
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.tsx
deleted file mode 100644
index 7155c3aece..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.test.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-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.tsx
deleted file mode 100644
index 7def83e143..0000000000
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/prompt/PromptTab.tsx
+++ /dev/null
@@ -1,371 +0,0 @@
-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.tsx
index 46c9b28c64..0bc4305b2c 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/sidePanel/sidePanelTabs.tsx
@@ -1,12 +1,12 @@
import type { ReactNode } from "react";
-import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, Globe, Search, Sparkles, type LucideIcon } from "lucide-react";
+import { Bot, Building2, CreditCard, FileDiff, Files, FolderTree, GitBranch, Globe, MessageSquare, Search, type LucideIcon } from "lucide-react";
import type { SidePanelTabId } from "@/store/ideSidePanel";
import { AgentsOverview } from "./AgentsOverview";
import { BrowserTab } from "./browser/BrowserTab";
+import { SideChatTab } from "./chat/SideChatTab";
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";
@@ -89,12 +89,12 @@ export const SIDE_PANEL_TABS: readonly SidePanelTabDef[] = [
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.
+ id: "chat",
+ labelKey: "ide_side_panel.tabs.chat",
+ shortcut: "H",
+ icon: MessageSquare,
+ render: () => <SideChatTab />,
+ // The conversation, its socket and a streaming answer survive a tab switch.
keepAlive: true,
},
{
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx
index a378dd6fe1..d555cbac48 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadPickers.tsx
@@ -2,6 +2,7 @@ import { useMemo } from "react";
import { brainValue, splitBrainValue } from "@/components/agentchat/AgentComposer";
import { ComposerBrainPicker, type BrainSection } from "@/components/agentchat/ComposerBrainPicker";
import { AgentMark } from "@/components/agentic/AgentMark";
+import { ProviderLogo } from "@/components/providers/ProviderLogo";
import { isUnguardedPermissionMode, permissionModeIcon } from "@/components/agentchat/permissionIcons";
import { Combobox, type ComboboxGroup, type ComboboxOption } from "@/components/ui/combobox";
import { useT } from "@/i18n";
@@ -35,6 +36,16 @@ export function agentName(provider: Pick<ProviderOption, "agent" | "label">): st
}
}
+/**
+ * A row's own mark: a coding agent's, or the provider's logo for a seat that
+ * is an API behind a key. Never a letter in a box.
+ */
+function ProviderMark({ provider }: { provider: ProviderOption }) {
+ return provider.agent
+ ? <AgentMark agent={provider.agent} label={provider.label} logoUrl={provider.logoUrl} variant="plain" size="sm" />
+ : <ProviderLogo providerId={provider.id} label={provider.label} size="sm" />;
+}
+
const EFFORTS = new Set(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
/** An effort level in the chat's own words ("" is the agent's default). */
@@ -74,7 +85,7 @@ export function AgentModelPicker({
const locked = lockedProvider !== null && provider.id !== lockedProvider;
const disabled = !provider.connected || locked;
const hint = locked ? newThreadHint : !provider.connected ? (provider.cli_installed === false ? notInstalledHint : connectFirstHint) : undefined;
- const icon = <AgentMark agent={provider.agent ?? ""} label={provider.label} logoUrl={provider.logoUrl} variant="plain" size="sm" />;
+ const icon = <ProviderMark provider={provider} />;
// Whose model a row is, on a quiet second line under its name.
const owner = (note?: string) => <span className="inline-flex min-w-0 items-center gap-1.5">
<span className="inline-flex shrink-0 scale-[0.86]">{icon}</span>
@@ -109,7 +120,7 @@ export function AgentModelPicker({
family: provider.family,
access: provider.keyless ? "local" : isApiRunner(provider.runner) ? "api" : "subscription",
label: agentName(provider),
- icon: <AgentMark agent={provider.agent ?? ""} label={provider.label} logoUrl={provider.logoUrl} variant="plain" size="sm" />,
+ icon: <ProviderMark provider={provider} />,
muted: !provider.connected || (lockedProvider !== null && provider.id !== lockedProvider),
})), [providers, lockedProvider]);
const pickedIcon = providers.find((provider) => provider.id === draft.provider);
@@ -117,7 +128,7 @@ export function AgentModelPicker({
value={brainValue(draft.provider, draft.model)} groups={groups} sections={sections} currentSection={draft.provider}
onChange={(value) => { const [provider, model] = splitBrainValue(value); onPick(provider, model); }}
fallbackLabel={draft.model || (providers.length ? t("ide_threads.choose_agent") : t("ide_threads.loading_agents"))} searchPlaceholder={t("ide_threads.search_agents_models")}
- triggerPrefix={pickedIcon ? <AgentMark agent={pickedIcon.agent ?? ""} label={pickedIcon.label} logoUrl={pickedIcon.logoUrl} variant="plain" size="sm" /> : undefined} />;
+ triggerPrefix={pickedIcon ? <ProviderMark provider={pickedIcon} /> : undefined} />;
}
export function EffortPicker({ provider, draft, liveModels, onPick, separated = false }: {
diff --git a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
index 9618415e38..b8a4cd35fa 100644
--- a/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
+++ b/jarvis/ui/web/frontend/src/components/agentic/threads/ThreadTimeline.tsx
@@ -609,9 +609,9 @@ export function foldFinished(rows: ThreadRow[]): { work: ThreadRow[]; answer: Th
}
/** "Working for 12s" with the ticking clock in place of the duration. */
-function WorkingFor({ since }: { since: number }) {
+function WorkingFor({ since, labelKey = "thread_turn.working_for" }: { since: number; labelKey?: string }) {
const t = useT();
- const [before, after = ""] = t("thread_turn.working_for").split("{duration}");
+ const [before, after = ""] = t(labelKey).split("{duration}");
return <>{before}<Elapsed since={since} />{after}</>;
}
@@ -632,6 +632,13 @@ export interface ThreadTurnProps {
extras?: { key: string; node: ReactNode }[];
/** A quiet note on a finished turn's closing line: tokens, cost. */
receipt?: ReactNode;
+ /**
+ * How the turn's status lines read. A coding thread counts work ("Working
+ * for 12s", "Worked for 40s"); a plain chat has thoughts and an answer, so
+ * it says "Thinking for 3s" until its first line shows and "Thought for
+ * 3s" on the fold, and puts no duration under an answer.
+ */
+ tone?: "work" | "chat";
}
/**
@@ -639,7 +646,7 @@ export interface ThreadTurnProps {
* threads and every agent chat draw their turns with it, so a turn looks and
* behaves the same wherever it is read — streaming, finished or reloaded.
*/
-export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer", onDecide, extras, receipt }: ThreadTurnProps) {
+export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer", onDecide, extras, receipt, tone = "work" }: ThreadTurnProps) {
const t = useT();
const lang = t("trace_report.locale");
const running = turn.status === "running";
@@ -667,12 +674,18 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
const duration = turn.durationMs != null ? traceDuration(turn.durationMs) : "";
const timed = (key: string) => duration ? fill(t(`thread_turn.${key}_after`), { duration }) : t(`thread_turn.${key}`);
const workedFor = duration ? fill(t("thread_turn.worked_for"), { duration }) : "";
+ const chat = tone === "chat";
+ // A chat's fold holds thoughts alone, so it is timed by the thinking, not the whole turn.
+ const thoughtMs = chat ? turn.blocks.reduce((sum, block) => sum + (block.kind === "reasoning" ? block.durationMs ?? 0 : 0), 0) : 0;
+ const thoughtFor = thoughtMs > 0 ? fill(t("work_trace.thought_for"), { duration: traceDuration(thoughtMs) }) : t("work_trace.thought");
+ // A chat's rows are its sign of life; the ticking line only covers the wait before the first one.
+ const quiet = chat && rows.length > 0;
const foldLabel = turn.status === "cancelled" ? timed("stopped")
: turn.status === "error" ? timed("failed")
- : workedFor || t("thread_turn.worked");
+ : chat ? thoughtFor : workedFor || t("thread_turn.worked");
const closing = turn.status === "cancelled" ? timed("stopped")
: turn.status === "error" ? timed("failed")
- : answer ? workedFor : timed("no_answer");
+ : answer ? (chat ? "" : workedFor) : timed("no_answer");
const renderRow = (row: ThreadRow) => {
if (row.kind === "work") return <WorkGroupView key={row.id} group={row} running={running} />;
if (row.kind === "thought") return <ThoughtView key={row.id} text={row.text} />;
@@ -713,8 +726,8 @@ export const ThreadTurn = memo(function ThreadTurn({ turn, prompts = "composer",
{!folded && extraNodes}
{shown.slice(extraAt).map(renderRow)}
{running
- ? <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">
- <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} />
+ ? !quiet && <div className="flex h-6 min-w-0 items-center px-1 text-sm leading-relaxed text-muted-foreground" data-testid="thread-working">
+ <span className="whitespace-nowrap"><WorkingFor since={turn.startedMs} labelKey={chat ? "work_trace.thinking_for" : undefined} />
{agentsWorking > 0 && <> · {fill(t(`thread_turn.subagents_working_${plural(lang, agentsWorking)}`), { count: agentsWorking })}</>}</span>
</div>
: <>
@@ -738,9 +751,9 @@ function ErrorLine({ text }: { text: string }) {
}
/** One item of the conversation, drawn by its kind. */
-function ItemView({ item }: { item: TimelineItem }) {
+function ItemView({ item, tone }: { item: TimelineItem } & Pick<ThreadTurnProps, "tone">) {
if (item.type === "user") return <UserBubble item={item} />;
- if (item.type === "turn") return <ThreadTurn turn={item} />;
+ if (item.type === "turn") return <ThreadTurn turn={item} tone={tone} />;
if (item.type === "error") return <ErrorLine text={item.text} />;
if (item.type === "notice") {
return <p className="text-center text-xs text-muted-foreground">{item.agentName ? `${item.agentName}: ` : ""}{item.text}</p>;
@@ -756,8 +769,10 @@ function ItemView({ item }: { item: TimelineItem }) {
* the bottom and stays put once they scroll up to read; a button brings them
* back down.
*/
-export function ThreadTimeline({ items, sessionId, bottomInset, folder = "", lead }: {
+export function ThreadTimeline({ items, sessionId, bottomInset, folder = "", lead, tone }: {
items: TimelineItem[]; sessionId: string | null; bottomInset: number;
+ /** How every turn's status lines read (see `ThreadTurnProps.tone`). */
+ tone?: ThreadTurnProps["tone"];
/** The thread's project folder; changed files list relative to it. */
folder?: string;
/** What reads above the conversation — an opened sub-agent's header and task. */
@@ -802,7 +817,7 @@ export function ThreadTimeline({ items, sessionId, bottomInset, folder = "", lea
className="h-full overflow-y-auto scrollbar-jarvis">
<div className="mx-auto flex w-full max-w-3xl flex-col gap-5 px-5 pt-6" style={{ paddingBottom: bottomInset + 24 }}>
{lead}
- {items.map((item) => <ItemView key={item.id} item={item} />)}
+ {items.map((item) => <ItemView key={item.id} item={item} tone={tone} />)}
</div>
</div>
{away && <button type="button" aria-label={t("ide_threads.scroll_newest")}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 47b30cec74..f3977cd6e8 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -7605,32 +7605,18 @@
"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.",
+ "chat": {
+ "new_chat": "Neuer Chat",
+ "history": "Chats",
+ "history_empty": "Noch keine früheren Chats.",
+ "delete_chat": "Diesen Chat löschen",
+ "empty_title": "Wie kann ich helfen?",
+ "empty_hint": "Frag, was du willst. Ein einfacher Chat mit dem Modell deiner Wahl.",
+ "placeholder": "Frag etwas",
+ "input_aria": "Nachricht",
"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."
+ "stop": "Stopp",
+ "needs_restart": "Starte die App einmal neu, um den Chat zu nutzen: Sie wurde im laufenden Betrieb aktualisiert."
},
"tabs": {
"browser": "Browser",
@@ -7642,7 +7628,7 @@
"search": "Suche",
"subscriptions": "Abos",
"office": "Dodaios Verse",
- "prompt": "Prompt"
+ "chat": "Chat"
},
"subscriptions": {
"bank": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 50c504528d..616764c171 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -7605,32 +7605,18 @@
"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.",
+ "chat": {
+ "new_chat": "New chat",
+ "history": "Chats",
+ "history_empty": "No earlier chats.",
+ "delete_chat": "Delete this chat",
+ "empty_title": "How can I help?",
+ "empty_hint": "Ask anything. A plain chat with the model you pick.",
+ "placeholder": "Ask anything",
+ "input_aria": "Message",
"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."
+ "stop": "Stop",
+ "needs_restart": "Restart the app once to use the chat: it was updated while it was running."
},
"tabs": {
"browser": "Browser",
@@ -7642,7 +7628,7 @@
"search": "Search",
"subscriptions": "Subscriptions",
"office": "Dodaios Verse",
- "prompt": "Prompt"
+ "chat": "Chat"
},
"subscriptions": {
"bank": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 6fbec2f61b..b2cfc4f68a 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -7605,32 +7605,18 @@
"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.",
+ "chat": {
+ "new_chat": "Nuevo chat",
+ "history": "Chats",
+ "history_empty": "Aún no hay chats anteriores.",
+ "delete_chat": "Eliminar este chat",
+ "empty_title": "¿En qué puedo ayudarte?",
+ "empty_hint": "Pregunta lo que quieras. Un chat sencillo con el modelo que elijas.",
+ "placeholder": "Pregunta lo que quieras",
+ "input_aria": "Mensaje",
"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."
+ "stop": "Detener",
+ "needs_restart": "Reinicia la app una vez para usar el chat: se actualizó mientras estaba en ejecución."
},
"tabs": {
"browser": "Navegador",
@@ -7642,7 +7628,7 @@
"search": "Buscar",
"subscriptions": "Suscripciones",
"office": "Dodaios Verse",
- "prompt": "Prompt"
+ "chat": "Chat"
},
"subscriptions": {
"bank": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/pt.json b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
index 2d5b74188f..aec3fb6e88 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/pt.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/pt.json
@@ -7605,32 +7605,18 @@
"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.",
+ "chat": {
+ "new_chat": "Novo chat",
+ "history": "Chats",
+ "history_empty": "Ainda não há chats anteriores.",
+ "delete_chat": "Excluir este chat",
+ "empty_title": "Como posso ajudar?",
+ "empty_hint": "Pergunte o que quiser. Um chat simples com o modelo que você escolher.",
+ "placeholder": "Pergunte qualquer coisa",
+ "input_aria": "Mensagem",
"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."
+ "stop": "Parar",
+ "needs_restart": "Reinicie o app uma vez para usar o chat: ele foi atualizado enquanto estava em execução."
},
"tabs": {
"browser": "Navegador",
@@ -7642,7 +7628,7 @@
"search": "Pesquisa",
"subscriptions": "Subscrições",
"office": "Dodaios Verse",
- "prompt": "Prompt"
+ "chat": "Chat"
},
"subscriptions": {
"bank": {
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/zh.json b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
index f23306501c..0e29372e23 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/zh.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/zh.json
@@ -7605,32 +7605,18 @@
"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": "无法复制提示词。",
+ "chat": {
+ "new_chat": "新聊天",
+ "history": "聊天记录",
+ "history_empty": "还没有之前的聊天。",
+ "delete_chat": "删除此聊天",
+ "empty_title": "有什么可以帮你?",
+ "empty_hint": "随便问。与你选择的模型进行的普通聊天。",
+ "placeholder": "随便问",
+ "input_aria": "消息",
"send": "发送",
- "sent": "已发送到 {pane}。",
- "not_accepted": "{pane} 没有接收提示词。文本仍在它的输入框中,请在那里按 Enter。",
- "unconfirmed": "{pane} 未显示提示词已到达。请检查该终端。"
+ "stop": "停止",
+ "needs_restart": "请重启一次应用以使用聊天:它是在运行期间更新的。"
},
"tabs": {
"browser": "浏览器",
@@ -7642,7 +7628,7 @@
"search": "搜索",
"subscriptions": "订阅",
"office": "Dodaios Verse",
- "prompt": "提示词"
+ "chat": "聊天"
},
"subscriptions": {
"bank": {
diff --git a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
index 63f67ebc75..44b4fcd6a3 100644
--- a/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
+++ b/jarvis/ui/web/frontend/src/lib/agentChatApi.ts
@@ -144,7 +144,7 @@ export async function fetchVoiceChat(): Promise<VoiceChatBinding> {
* (``jarvis/agent_chat/surface_kits.py``): the front page, the coding
* agents, and the Local models section's setup assistant.
*/
-export type AgentChatSurface = "jarvis" | "agent" | "local-models" | "society";
+export type AgentChatSurface = "jarvis" | "agent" | "local-models" | "society" | "side";
export interface AgentChatSession {
session_id: string;
diff --git a/jarvis/ui/web/frontend/src/lib/promptImproverApi.ts b/jarvis/ui/web/frontend/src/lib/promptImproverApi.ts
deleted file mode 100644
index 6a650a6c72..0000000000
--- a/jarvis/ui/web/frontend/src/lib/promptImproverApi.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-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.ts
index e941790559..08faf55683 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" | "prompt" | "subscriptions" | "office" | `terminal:${string}`;
+export type SidePanelTabId = "browser" | "agents" | "changes" | "files" | "search" | "git" | "skills" | "chat" | "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", "prompt", "subscriptions", "office"];
+export const SIDE_PANEL_TAB_IDS: readonly SidePanelTabId[] = ["browser", "agents", "changes", "files", "search", "git", "skills", "chat", "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.py
deleted file mode 100644
index bde62cfaee..0000000000
--- a/jarvis/ui/web/prompt_improver_routes.py
+++ /dev/null
@@ -1,157 +0,0 @@
-"""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.py
index 266e648f87..876ca6b0e4 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -517,7 +517,6 @@ class WebServer:
from .frontier_routes import router as frontier_router
from .grok_build_routes import router as grok_build_router
from .ide_skills_routes import router as ide_skills_router
- from .prompt_improver_routes import router as prompt_improver_router
from .jarvisx_routes import router as jarvisx_router
from .live_routes import router as live_router
from .local_models_assistant_routes import (
@@ -697,8 +696,6 @@ class WebServer:
app.include_router(team_thread_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 sweep
diff --git a/tests/unit/agent_chat/test_side_chat.py b/tests/unit/agent_chat/test_side_chat.py
new file mode 100644
index 0000000000..f2146c5848
--- /dev/null
+++ b/tests/unit/agent_chat/test_side_chat.py
@@ -0,0 +1,222 @@
+"""The IDE's side chat: a plain conversation, no tools on any seat.
+
+Pinned here: the surface seats only what can answer without tools, an API
+seat's request carries no tool and the surface's own system prompt, a
+tool-free CLI keeps its conversation for the next message and hears the
+instructions whenever it starts one, and the model is told nothing about the
+workspace: this is a plain AI chat.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from jarvis.agent_chat import plain_chat, runner_api, service
+from jarvis.agent_chat.catalog import rows_for
+from jarvis.agent_chat.native_control import TOOL_FREE_RUNNERS, disable_cli_tools
+from jarvis.agent_chat.runner_api import supports_api_runner
+from jarvis.agent_chat.service import AgentChatService
+from jarvis.agent_chat.store import AgentChatStore
+from jarvis.agent_chat.surface_kits import kit_for
+from jarvis.agentic_ide import side_chat
+from jarvis.core.protocols import BrainDelta, BrainRequest
+
+
+class _Brain:
+ """Answers from ``script`` and keeps the requests it was sent."""
+
+ script: list[BrainDelta] = []
+ seen: list[BrainRequest] = []
+
+ def __init__(self, model: str | None = None) -> None:
+ self.model = model
+
+ async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
+ _Brain.seen.append(req)
+ for delta in _Brain.script or [BrainDelta(content="Sure.")]:
+ await asyncio.sleep(0)
+ yield delta
+
+
+def brain(monkeypatch: pytest.MonkeyPatch) -> type[_Brain]:
+ _Brain.script, _Brain.seen = [], []
+ monkeypatch.setitem(
+ runner_api.BRAIN_BY_PROVIDER, "fakeprov", ("tests.unit.agent_chat.test_side_chat", "_Brain")
+ )
+ return _Brain
+
+
+async def _until_finished(queue: asyncio.Queue) -> list[dict[str, Any]]:
+ events: list[dict[str, Any]] = []
+ while True:
+ event = await asyncio.wait_for(queue.get(), timeout=5)
+ events.append(event)
+ if event["kind"] == "turn_finished":
+ return events
+
+
+def test_the_side_chat_seats_only_what_can_answer_without_tools() -> None:
+ assert kit_for("side").plain
+ assert not kit_for("agent").plain
+ rows = rows_for("side")
+ assert rows, "a plain chat still needs seats"
+ for row in rows:
+ assert supports_api_runner(row.id) or row.runner in TOOL_FREE_RUNNERS, row.id
+
+
[email protected]("runner", sorted(TOOL_FREE_RUNNERS))
+def test_every_tool_free_cli_can_drop_its_tools_and_keep_the_conversation(runner: str) -> None:
+ """A chat's next message resumes this one, so the CLI must persist it."""
+ kept = SimpleNamespace(argv=["binary", "exec"])
+ disable_cli_tools(kept, runner, keep_session=True)
+ assert "--no-session-persistence" not in kept.argv and "--ephemeral" not in kept.argv
+
+ one_shot = SimpleNamespace(argv=["binary", "exec"])
+ disable_cli_tools(one_shot, runner)
+ assert "--no-session-persistence" in one_shot.argv or "--ephemeral" in one_shot.argv
+
+
+async def test_an_api_seat_gets_no_tools_and_the_surfaces_own_system_prompt(
+ tmp_path: Path, brain: type[_Brain]
+) -> None:
+ (tmp_path / "frontend").mkdir()
+ # A model that asks for a tool anyway is not handed one.
+ brain.script = [
+ BrainDelta(content="Paris."),
+ BrainDelta(tool_call={"id": "c1", "name": "Read", "input": {"file_path": "x"}}),
+ ]
+ store = AgentChatStore(":memory:")
+ try:
+ svc = AgentChatService(store, assistant_name=lambda: "Testo")
+ session = svc.create_session(provider="fakeprov", cwd=str(tmp_path), surface="side")
+ queue = svc.subscribe(session.session_id)
+
+ await svc.send(session.session_id, "what is the capital of France?")
+ events = await _until_finished(queue)
+
+ request = brain.seen[0]
+ assert request.tools == ()
+ assert "You are Testo" in request.system and "no tools in this chat" in request.system
+ # A plain chat: nothing about the folder the session happens to sit in.
+ assert str(tmp_path) not in request.system and "frontend" not in request.system
+ assert request.messages[-1].content == "what is the capital of France?"
+ kinds = [event["kind"] for event in events]
+ assert "tool_call" not in kinds and "approval_required" not in kinds
+ assert events[-1]["payload"]["status"] == "done"
+ assert len(brain.seen) == 1, "a plain turn is one request"
+ finally:
+ store.close()
+
+
+async def test_a_cli_seat_runs_tool_free_and_carries_the_surfaces_prompt(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ prompts: list[tuple[str, bool, str]] = []
+
+ async def _run_cli_turn(handle: Any, prompt: str, runner: str, **_kwargs: object) -> str:
+ prompts.append((prompt, handle.tools_disabled, handle.plain_system))
+ await handle.emit(
+ service.make_event(
+ "turn_finished",
+ {"turn_id": handle.turn_id, "status": "done", "duration_ms": 1, "usage": {}},
+ )
+ )
+ return "vendor-1"
+
+ monkeypatch.setattr(service, "resolve_runner", lambda provider, **_kwargs: "claude-cli")
+ monkeypatch.setattr(service, "run_cli_turn", _run_cli_turn)
+ store = AgentChatStore(":memory:")
+ try:
+ svc = AgentChatService(store, assistant_name=lambda: "Testo")
+ session = svc.create_session(provider="claude-api", cwd=str(tmp_path), surface="side")
+ queue = svc.subscribe(session.session_id)
+
+ await svc.send(session.session_id, "first question")
+ await _until_finished(queue)
+ await svc.send(session.session_id, "second question")
+ await _until_finished(queue)
+
+ # The runner decides where the instructions go; the service hands it
+ # the person's own words and the surface's prompt beside them.
+ assert [prompt for prompt, _tool_free, _system in prompts] == [
+ "first question",
+ "second question",
+ ]
+ assert all(tool_free for _prompt, tool_free, _system in prompts)
+ assert all("You are Testo" in system for _prompt, _tool_free, system in prompts)
+ finally:
+ store.close()
+
+
+def _handle(system: str = "Be a plain chat.", history: list[dict[str, Any]] | None = None) -> Any:
+ return SimpleNamespace(plain_system=system, history=history or [])
+
+
+def test_a_cli_conversation_opens_with_the_instructions() -> None:
+ prompt = plain_chat.cli_prompt(_handle(), "first question", None)
+ assert prompt.startswith("<chat_instructions>\nBe a plain chat.\n</chat_instructions>")
+ assert prompt.endswith("first question")
+ assert "<earlier_conversation>" not in prompt
+
+
+def test_a_resumed_cli_conversation_gets_the_persons_words_alone() -> None:
+ assert plain_chat.cli_prompt(_handle(), "second question", "vendor-1") == "second question"
+
+
+def test_a_conversation_restarted_after_a_lost_resume_gets_instructions_and_history() -> None:
+ """A fresh CLI session must not leave the chat without its framing."""
+ history = [
+ {"kind": "user_message", "payload": {"text": "what is the plan?"}},
+ {"kind": "reasoning", "payload": {"text": "private thinking"}},
+ {"kind": "assistant_text", "payload": {"text": "Ship the chat."}},
+ ]
+ prompt = plain_chat.cli_prompt(_handle(history=history), "and then?", None)
+ assert prompt.startswith("<chat_instructions>")
+ assert "User: what is the plan?\n\nAssistant: Ship the chat." in prompt
+ assert "private thinking" not in prompt
+ assert prompt.endswith("and then?")
+
+
+def test_a_long_chat_keeps_its_newest_messages_in_the_transcript() -> None:
+ history = [
+ {"kind": "user_message", "payload": {"text": f"message {index} " + "x" * 400}}
+ for index in range(40)
+ ]
+ kept = plain_chat.transcript(history, max_chars=2000)
+ assert "message 39" in kept and "message 0 " not in kept
+ assert len(kept) < 2600
+
+
+def test_a_surface_with_tools_sends_the_cli_the_message_as_it_is() -> None:
+ handle = SimpleNamespace(plain_system="", history=[])
+ assert plain_chat.cli_prompt(handle, "do the work", None) == "do the work"
+ assert plain_chat.permission_mode(handle, "codex-cli", "full-access") == "full-access"
+
+
+def test_a_plain_chat_on_a_cli_that_could_still_write_runs_read_only() -> None:
+ assert plain_chat.permission_mode(_handle(), "codex-cli", "full-access") == "read-only"
+ # No tool at all leaves nothing to sandbox.
+ assert plain_chat.permission_mode(_handle(), "claude-cli", "bypassPermissions") == (
+ "bypassPermissions"
+ )
+
+
+async def test_the_chat_is_told_how_to_answer_and_nothing_about_a_workspace(
+ tmp_path: Path,
+) -> None:
+ (tmp_path / ".git").mkdir()
+ (tmp_path / "src").mkdir()
+
+ prompt = await side_chat.system_prompt(SimpleNamespace(cwd=str(tmp_path)), "hi", "Testo")
+
+ assert prompt.startswith("You are Testo, an AI assistant in a chat.")
+ assert "no tools in this chat" in prompt
+ assert str(tmp_path) not in prompt and "src" not in prompt
+ assert prompt == await side_chat.system_prompt(SimpleNamespace(cwd=""), "other", "Testo")
diff --git a/tests/unit/agentic_ide/test_prompt_improver.py b/tests/unit/agentic_ide/test_prompt_improver.py
deleted file mode 100644
index 1e6c575c65..0000000000
--- a/tests/unit/agentic_ide/test_prompt_improver.py
+++ /dev/null
@@ -1,183 +0,0 @@
-"""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.py
deleted file mode 100644
index e1f8998345..0000000000
--- a/tests/unit/web/test_prompt_improver_route.py
+++ /dev/null
@@ -1,210 +0,0 @@
-"""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)