Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(chat): add slash menus and persistent goal controls
rubenluetke10-beepe7100d7a415c
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsxindex edf2c7d1dd..ca84ef9b84 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentComposer.tsx@@ -1,3 +1,4 @@+import { ChatCommandPanel, useChatCommands } from "./ChatCommands";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {ArrowUp,@@ -173,6 +174,10 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {// seat honours is the catalog row's word (`typeahead`), read from the// runner, so a seat that would take the slash as text never gets a list.const cardRef = useRef<HTMLDivElement | null>(null);+ const commands = useChatCommands({ value, setValue,+ attachments: files.attachments, attachmentsBusy: files.analyzing > 0, onAttachmentsSent: files.clear,+ onModel: () => cardRef.current?.querySelector<HTMLButtonElement>('[data-testid="composer-model"]')?.click(),+ });const triggers = useMemo(() => provider?.typeahead ?? [], [provider]);const typeahead = useComposerTypeahead(textareaRef, value, setValueState, {surface,@@ -186,10 +191,11 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {async function onSend() {const sessionAtSend = activeSessionId;const content = value.trim();+ if (await commands.execute(content)) return;// A message may be files alone: dropping a screenshot and pressing Enter// is a complete gesture, and refusing it would be the composer insisting// on a sentence the picture already is.- if ((!content && files.attachments.length === 0) || running || busy) return;+ if ((!content && files.attachments.length === 0) || (running || busy) && !commands.canSteer) return;if (files.analyzing > 0) return; // a file still being read would be sent without its contentsif (dictating) stopDictation();setValueState("");@@ -426,11 +432,11 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {(provider?.permission_modes ?? []).find((m) => m.id === draft.permissionMode)?.description ?? "";const canSend =- connected &&+ commands.isCommand || connected &&(Boolean(value.trim()) || files.attachments.length > 0) &&files.analyzing === 0 &&- !running &&- !busy &&+ (!running || commands.canSteer) &&+ (!busy || commands.canSteer) &&Boolean(provider?.connected);const placeholder = connected? t("agent_chat.placeholder")@@ -465,6 +471,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {{/* The blue variant of this strip lived here; a running microphone is alive state, not the accent, so it now shares the one green strip. */}<DictationStatus onStop={stopDictation} />+ <ChatCommandPanel control={commands} /><ChatAttachmentStripattachments={files.attachments}analyzing={files.analyzing}@@ -472,7 +479,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {/><ComposerTypeaheadanchorRef={cardRef}- open={typeahead.open}+ open={typeahead.open && !commands.open}trigger={typeahead.token?.trigger ?? null}items={typeahead.items}loading={typeahead.loading}@@ -483,7 +490,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {<ComposerChipFieldref={fieldRef}placeholder={placeholder}- disabled={!connected}+ disabled={!connected && !commands.enabled}autoFocus={autoFocus}onSubmit={() => void onSend()}onDraftChange={(draft) => {@@ -491,6 +498,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {setSelectedTools(draft.choices);}}onKeyDown={(ev) => {+ if (commands.onKeyDown(ev)) return true;pasteRescue.onKeyDown(ev);if (typeahead.onKeyDown(ev)) return true;return false;@@ -700,7 +708,7 @@ export function AgentComposer({ autoFocus = false }: { autoFocus?: boolean }) {>{dictating ? <Square className="h-4 w-4" /> : <Mic className="h-4 w-4" />}</button>- {running ? (+ {running && !commands.isCommand && !(commands.canSteer && value.trim()) ? (<buttontype="button"onClick={() => void cancel()}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsxindex f6264cc644..f9b8d194e6 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/AgentTimeline.tsx@@ -43,6 +43,7 @@ export function AgentTimeline({);}if (item.type === "user") {+ if (item.origin === "control") return <div key={item.id} data-message-id={item.id} className="text-xs text-muted-foreground">{t("slash.control_turn")}{item.attachments.map((file) => <span key={file.name} className="ml-2">{file.name}</span>)}</div>;return (<divkey={item.id}@@ -129,6 +130,7 @@ export function AgentTimeline({);}if (item.type === "notice") {+ if (item.kind === "native_goal_verdict") return <p key={item.id} className="text-xs text-muted-foreground">{t("slash.verifying")}</p>;// The society reporting back on a task Jarvis handed out: the// agent's name as the headline, its summary underneath. Muted and// centred like a stamp — it is not Jarvis speaking.diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.test.tsxnew file mode 100644index 0000000000..e437d5c12b--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.test.tsx@@ -0,0 +1,100 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { useState } from "react";+import { CHAT_COMMAND_NAMES, parseChatCommand, type ChatControlState } from "@/lib/chatControlApi";+import { createAgentChatStore } from "@/store/agentChat";+import { EMPTY_TIMELINE, reduceEvent } from "./reduce";+import { AgentChatStoreProvider } from "./AgentChatStoreContext";+import { ChatCommandPanel, useChatCommands } from "./ChatCommands";+import { useTranscriptViewStore } from "../society/chat/useTranscriptView";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("../society/card/AgentRoutinesList", () => ({ AgentRoutinesList: ({ agentId }: { agentId: string }) => <div>Routines: {agentId}</div> }));+const store = createAgentChatStore("society");+const state: ChatControlState = { session_id: "society:test", mode: "build", permission_mode: "ask",+ previous_permission: "ask", output_language: "en", last_request: "Check tickets", last_status: "done", plan: "", goal: null, revision: 1 };+const model = vi.fn();+let requests: { command: string; request_id: string; arguments: string }[] = [];+let failOnce = false;++function Harness() {+ const [value, setValue] = useState("");+ const commands = useChatCommands({ value, setValue, onModel: model, agentId: "test" });+ return <><ChatCommandPanel control={commands} /><input aria-label="Message" value={value} onChange={(e) => setValue(e.target.value)} onKeyDown={commands.onKeyDown} />+ <button onClick={() => void commands.execute(value)}>Send</button></>;+}+function type(text: string) { fireEvent.change(screen.getByRole("textbox"), { target: { value: text } }); }+function send(text: string) { type(text); fireEvent.click(screen.getByText("Send")); }+beforeEach(() => {+ requests = []; failOnce = false; model.mockClear();+ useTranscriptViewStore.setState({ boundaries: {} });+ store.setState({ activeSessionId: state.session_id, timeline: { ...EMPTY_TIMELINE, items: [+ { type: "user", id: "u-1", text: "Keep this context", attachments: [], tsMs: 1 },+ ] }, busy: false });+ vi.stubGlobal("fetch", vi.fn(async (_url, init) => {+ if (!init?.method) return new Response(JSON.stringify({ state, commands: CHAT_COMMAND_NAMES.map((name) => ({ name, available: true, kind: "control", example: `/${name}` })) }));+ const body = JSON.parse(init.body);+ requests.push(body);+ if (failOnce) { failOnce = false; throw new Error("Connection lost"); }+ return new Response(JSON.stringify({ request_id: body.request_id, command: body.command, status: "done", error: "", state: { ...state, mode: body.command === "plan" ? "plan" : "build", permission_mode: body.command === "plan" ? "plan" : "ask", revision: 2 }, data: { hits: [] } }));+ }));+ render(<AgentChatStoreProvider store={store}><Harness /></AgentChatStoreProvider>);+});+afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++it("offers all sixteen commands and supports keyboard selection", async () => {+ type("/");+ await waitFor(() => expect(screen.getAllByRole("option")).toHaveLength(16));+ type("/go");+ expect(screen.getAllByRole("option")).toHaveLength(1);+ fireEvent.keyDown(screen.getByRole("textbox"), { key: "Tab" });+ expect((screen.getByRole("textbox") as HTMLInputElement).value).toBe("/goal ");+ expect(requests).toHaveLength(0);+});++it("clears and restores only the local view", async () => {+ const original = store.getState().timeline;+ send("/clear");+ await waitFor(() => expect(useTranscriptViewStore.getState().boundaries[state.session_id]).toBeTruthy());+ send("/history");+ await waitFor(() => expect(useTranscriptViewStore.getState().boundaries[state.session_id]).toBeUndefined());+ expect(store.getState().timeline).toBe(original);+ expect(requests).toHaveLength(0);+});++it("runs actual mode changes and keeps a request id across network retries", async () => {+ failOnce = true;+ send("/plan Inspect tickets");+ await screen.findByRole("alert");+ send("/plan Inspect tickets");+ await screen.findByText("slash.plan_active");+ expect(requests).toHaveLength(2);+ expect(requests[0].request_id).toBe(requests[1].request_id);+ expect(requests[1].arguments).toBe("Inspect tickets");+ expect(store.getState().draft.permissionMode).toBe("plan");+});++it("opens existing model and routine controls without sending an agent prompt", async () => {+ send("/model");+ await waitFor(() => expect(model).toHaveBeenCalledOnce());+ send("/routines");+ expect(await screen.findByText("Routines: test")).toBeTruthy();+ expect(requests).toHaveLength(0);+});++it("updates a running goal from the stream and accepts stop while the chat is busy", async () => {+ await waitFor(() => expect(vi.mocked(fetch)).toHaveBeenCalled());+ act(() => store.setState({ busy: true, timeline: reduceEvent(store.getState().timeline, {+ seq: 2, ts_ms: 2, kind: "notice", payload: { kind: "chat_control", state: { ...state, revision: 5,+ goal: { id: "g", objective: "Finish tickets", status: "active", reason: "", engine: "jarvis", steps: 1, stalled_steps: 0, evidence: [], started_ms: 1, updated_ms: 2 } } },+ }) }));+ expect(await screen.findByTestId("chat-goal")).toBeTruthy();+ send("/stop");+ await waitFor(() => expect(requests.at(-1)?.command).toBe("stop"));+ expect(store.getState().timeline.items).toHaveLength(1);+});++it("never interprets quoted commands, attachments, paths or embedded text as actions", () => {+ for (const text of ["Please use /goal later", "```\n/stop\n```", "/clearance", "/tmp/file.txt", "//stop"]) expect(parseChatCommand(text)).toBeNull();+ expect(parseChatCommand(" /message @Agent Hello ")).toEqual({ name: "message", args: "@Agent Hello" });+});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.tsx b/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.tsxnew file mode 100644index 0000000000..6f76cfc24a--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/agentchat/ChatCommands.tsx@@ -0,0 +1,195 @@+import { useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";+import { Loader2, Pause, Play, X } from "lucide-react";+import { useT } from "@/i18n";+import { cn } from "@/lib/utils";+import { createAgentChatSession, type ChatAttachment } from "@/lib/agentChatApi";+import { CHAT_COMMAND_NAMES, fetchChatCommands, parseChatCommand, runChatCommand,+ type ChatCommand, type ChatCommandName, type ChatCommandResult, type ChatControlState, type ChatSearchHit } from "@/lib/chatControlApi";+import { useAgentChat, useAgentChatApi } from "./AgentChatStoreContext";+import { restoreTranscriptView, useTranscriptView } from "../society/chat/useTranscriptView";+import { AgentRoutinesList } from "../society/card/AgentRoutinesList";++interface Options { value: string; setValue: (value: string) => void; onModel: () => void; onClear?: () => void; agentId?: string; attachments?: ChatAttachment[]; attachmentsBusy?: boolean; onAttachmentsSent?: () => void }+const LOCAL = new Set<ChatCommandName>(["help", "clear", "history", "model", "routines"]);++export function useChatCommands({ value, setValue, onModel, onClear, agentId = "jarvis", attachments = [], attachmentsBusy = false, onAttachmentsSent }: Options) {+ const t = useT();+ const localeValue = t("slash.locale");+ const locale = ["en", "de", "es"].includes(localeValue) ? localeValue : "en";+ const store = useAgentChatApi();+ const sid = useAgentChat((s) => s.activeSessionId);+ const surface = useAgentChat((s) => s.surface);+ const items = useAgentChat((s) => s.timeline.items);+ const liveControl = useAgentChat((s) => s.timeline.control);+ const enabled = surface === "jarvis" || surface === "society";+ const view = useTranscriptView(sid, items);+ const [catalog, setCatalog] = useState<ChatCommand[]>([]);+ const [state, setState] = useState<ChatControlState | null>(null);+ const [error, setError] = useState("");+ const [busy, setBusy] = useState(false);+ const [help, setHelp] = useState(false);+ const [panel, setPanel] = useState<"status" | "find" | "routines" | null>(null);+ const [hits, setHits] = useState<ChatSearchHit[]>([]);+ const [result, setResult] = useState<ChatCommandResult | null>(null);+ const [activeIndex, setActiveIndex] = useState(0);+ const sending = useRef(false);+ const pending = useRef(new Map<string, string>());+ const currentSid = useRef(sid);+ currentSid.current = sid;++ useEffect(() => {+ if (!enabled) return;+ const controller = new AbortController();+ setState(null); setPanel(null); setError(""); setResult(null);+ void fetchChatCommands(sid, controller.signal).then((data) => {+ if (!controller.signal.aborted) {+ setCatalog(Array.isArray(data.commands) ? data.commands : []);+ setState((old) => data.state && (!old || data.state.revision >= old.revision) ? data.state : old);+ }+ }).catch(() => {+ if (!controller.signal.aborted) setCatalog([]);+ });+ return () => controller.abort();+ }, [sid, enabled]);++ useEffect(() => {+ if (liveControl?.session_id === sid) setState((old) => !old || liveControl.revision >= old.revision ? liveControl : old);+ }, [liveControl, sid]);++ const commands = useMemo(() => CHAT_COMMAND_NAMES.map((name) => catalog.find((row) => row.name === name) ?? {+ name, kind: LOCAL.has(name) ? "local" as const : "control" as const,+ example: `/${name}`, available: LOCAL.has(name), reason: LOCAL.has(name) ? "" : t("slash.backend_unavailable"),+ }), [catalog, t]);+ const token = /^\/([a-z]*)$/.exec(value.trimStart());+ const matches = commands.filter((row) => help || row.name.startsWith(token?.[1] ?? ""));+ const open = enabled && (help || Boolean(token && matches.length));+ useEffect(() => { setActiveIndex(0); }, [value, help]);+ useEffect(() => { if (value) setHelp(false); }, [value]);++ async function ensureSession(): Promise<string> {+ const current = store.getState();+ if (current.activeSessionId) return current.activeSessionId;+ if (surface !== "jarvis") throw new Error(t("slash.session_loading"));+ const draft = current.draft;+ const session = await createAgentChatSession({ provider: draft.provider, model: draft.model,+ effort: draft.effort, cwd: draft.cwd, permission_mode: draft.permissionMode, surface });+ if (store.getState().activeSessionId) throw new Error(t("slash.session_changed"));+ store.setState((s) => ({ sessions: [session, ...s.sessions] }));+ store.getState().openSession(session.session_id);+ return session.session_id;+ }++ async function remote(name: ChatCommandName, args: string): Promise<ChatCommandResult> {+ const target = await ensureSession();+ const attached = ["plan", "recap", "review", "remember", "message"].includes(name) || name === "goal" && args && args !== "clear" ? attachments : [];+ const key = JSON.stringify([target, name, args, attached]);+ const id = pending.current.get(key) ?? crypto.randomUUID();+ pending.current.set(key, id);+ const response = await runChatCommand(target, name, args, id, locale, attached);+ pending.current.delete(key);+ if (store.getState().activeSessionId === target) {+ setState(response.state); setResult(response);+ store.setState((s) => ({ draft: { ...s.draft, permissionMode: response.state.permission_mode },+ activeSession: s.activeSession ? { ...s.activeSession, permission_mode: response.state.permission_mode } : null }));+ }+ if (response.status === "failed") throw new Error(response.error);+ if (attached.length) onAttachmentsSent?.();+ return response;+ }++ async function execute(text: string): Promise<boolean> {+ const command = enabled ? parseChatCommand(text) : null;+ if (!command) return false;+ if (attachmentsBusy && ["plan", "review", "recap", "goal"].includes(command.name) && command.args !== "clear") {+ setError(t("slash.attachments_loading")); return true;+ }+ if (sending.current && command.name !== "stop") return true;+ if (LOCAL.has(command.name) && command.args) { setError(t("slash.no_arguments")); return true; }+ sending.current = true; setBusy(true); setError(""); setHelp(false); setResult(null);+ try {+ switch (command.name) {+ case "help": setHelp(true); break;+ case "clear": (onClear ?? view.clear)(); setPanel(null); break;+ case "history": restoreTranscriptView(sid); break;+ case "model":+ if (state?.goal?.status === "active") await remote("stop", "");+ onModel(); break;+ case "routines": setPanel("routines"); break;+ default: {+ const response = await remote(command.name, command.args);+ if (command.name === "find") { setHits((response.data.hits ?? []) as ChatSearchHit[]); setPanel("find"); }+ if (command.name === "status" || command.name === "goal" && !command.args) setPanel("status");+ }+ }+ setValue("");+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : String(cause));+ } finally { sending.current = false; setBusy(false); }+ return true;+ }++ function select(row: ChatCommand) {+ if (!row.available) return;+ setHelp(false); setValue(`/${row.name} `);+ }+ function onKeyDown(event: KeyboardEvent): boolean {+ if (!open || !matches.length) return false;+ if (event.key === "Escape") { event.preventDefault(); setHelp(false); setValue(""); return true; }+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault(); setActiveIndex((n) => (n + (event.key === "ArrowDown" ? 1 : -1) + matches.length) % matches.length); return true;+ }+ if (event.key === "Tab" || event.key === "Enter" && value.trim() !== `/${matches[activeIndex]?.name}`) {+ event.preventDefault(); select(matches[activeIndex] ?? matches[0]); return true;+ }+ return false;+ }+ function reveal(hit: ChatSearchHit) {+ restoreTranscriptView(hit.session_id);+ setPanel(null);+ requestAnimationFrame(() => document.querySelector(`[data-chat-item="${CSS.escape(hit.item_id)}"], [data-message-id="${CSS.escape(hit.item_id)}"], [data-turn-id="${CSS.escape(hit.item_id)}"]`)?.scrollIntoView({ block: "center" }));+ }+ return { enabled, open, matches, activeIndex, setActiveIndex, select, execute, onKeyDown,+ isCommand: enabled && parseChatCommand(value) !== null, canSteer: state?.goal?.status === "active",+ state, error, busy, panel, setPanel, hits, reveal, result, agentId };+}++export function ChatCommandPanel({ control }: { control: ReturnType<typeof useChatCommands> }) {+ const t = useT();+ const list = useRef<HTMLDivElement>(null);+ useEffect(() => { list.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" }); }, [control.activeIndex, control.open]);+ if (!control.enabled) return null;+ const goal = control.state?.goal;+ return <div className="relative text-xs" data-testid="chat-commands">+ {control.state?.mode === "plan" ? <div className="mb-2 rounded-md border border-border bg-secondary px-3 py-2">{t("slash.plan_active")}</div> : null}+ {control.state?.mode === "build" ? <div className="mb-2 px-1 text-muted-foreground">{t("slash.build_active")}</div> : null}+ {goal && goal.status !== "cleared" ? <div className="mb-2 rounded-lg border border-border bg-card p-3" data-testid="chat-goal">+ <div className="flex items-center gap-2"><span className="font-medium">{t(`slash.goal_${goal.status}`)}</span>+ <span className="ml-auto text-muted-foreground">{goal.steps} {t("slash.steps")}</span>+ {goal.status === "active" ? <button aria-label={t("slash.stop")} onClick={() => void control.execute("/stop")}><Pause className="h-4 w-4" /></button> : null}+ {goal.status === "paused" || goal.status === "blocked" ? <button aria-label={t("slash.continue")} onClick={() => void control.execute("/continue")}><Play className="h-4 w-4" /></button> : null}+ <button aria-label={t("slash.clear_goal")} onClick={() => void control.execute("/goal clear")}><X className="h-4 w-4" /></button>+ </div><button className="mt-1 line-clamp-3 whitespace-pre-wrap text-left [overflow-wrap:anywhere]" title={goal.objective} onClick={() => control.setPanel("status")}>{goal.objective}</button>+ {goal.reason ? <p className="mt-1 line-clamp-3 text-muted-foreground [overflow-wrap:anywhere]">{goal.reason}</p> : null}+ </div> : null}+ {control.error ? <p role="alert" className="mb-2 text-destructive [overflow-wrap:anywhere]">{control.error}</p> : null}+ {control.busy ? <Loader2 aria-label={t("slash.working")} className="mb-2 h-4 w-4 animate-spin" /> : null}+ {control.panel ? <section role="dialog" aria-label={t(`slash.${control.panel}`)} className="mb-2 max-h-[45vh] overflow-auto rounded-lg border border-border bg-card p-3">+ <button aria-label={t("slash.close")} className="float-right" onClick={() => control.setPanel(null)}><X className="h-4 w-4" /></button>+ {control.panel === "routines" ? <AgentRoutinesList agentId={control.agentId} variant="rail" /> : null}+ {control.panel === "status" ? <div className="space-y-2"><p>{t("slash.mode")}: {control.state?.mode}</p>+ <p>{t("slash.task")}: {control.state?.last_request || t("slash.no_task")}</p>+ {goal ? <><p>{t("slash.goal")}: {goal.objective} — {t(`slash.goal_${goal.status}`)}</p><p>{goal.reason}</p></> : null}</div> : null}+ {control.panel === "find" ? control.hits.length ? control.hits.map((hit) => <button key={hit.seq} onClick={() => control.reveal(hit)} className="block w-full border-b border-border p-2 text-left hover:bg-secondary">+ <span className="text-muted-foreground">#{hit.seq}</span> <span className="whitespace-pre-wrap">{hit.text}</span></button>) : <p>{t("slash.no_matches")}</p> : null}+ </section> : null}+ {control.result?.data.result ? <p className="mb-2 text-muted-foreground" role="status">{t("slash.command_done")}: /{control.result.command}</p> : null}+ {control.open ? <div ref={list} role="listbox" aria-label={t("slash.help")} className="absolute bottom-full left-0 right-0 z-40 mb-2 max-h-80 overflow-auto rounded-xl border border-border bg-popover p-1 shadow-lg">+ {control.matches.map((row, index) => <button key={row.name} role="option" aria-selected={index === control.activeIndex} aria-disabled={!row.available}+ onMouseEnter={() => control.setActiveIndex(index)} onMouseDown={(e) => e.preventDefault()} onClick={() => control.select(row)}+ className={cn("block w-full rounded-lg px-3 py-2 text-left", index === control.activeIndex && "bg-secondary", !row.available && "opacity-50")}>+ <span className="font-medium">/{row.name}</span><span className="ml-3 text-muted-foreground">{t(`slash.commands.${row.name}`)}</span>+ <span className="mt-0.5 block text-[11px] text-muted-foreground">{row.available ? row.example : row.reason}</span>+ </button>)}+ </div> : null}+ </div>;+}diff --git a/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsxindex 1f856f0999..35f8d354af 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/composerTypeahead.test.tsx@@ -4,7 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { AgentComposer } from "@/components/agentchat/AgentComposer";import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";import { EMPTY_TIMELINE } from "@/components/agentchat/reduce";-import { useAgentChatStore } from "@/store/agentChat";+import { useAgentSessionStore as useAgentChatStore } from "@/store/agentChat";import { useEventStore } from "@/store/events";import type { AgentChatCatalog } from "@/lib/agentChatApi";@@ -80,16 +80,20 @@ function composer() {);}-function box(): HTMLTextAreaElement {- return document.querySelector("textarea[data-jarvis-chat-input]") as HTMLTextAreaElement;+function box(): HTMLElement {+ return document.querySelector('[role="textbox"][contenteditable]') as HTMLElement;}/** Type into the box the way a person does: the value lands, the caret sits at its end. */function type(text: string) {const el = box();- fireEvent.change(el, { target: { value: text } });- el.setSelectionRange(text.length, text.length);- fireEvent.select(el);+ el.textContent = text;+ const range = document.createRange();+ range.selectNodeContents(el);+ range.collapse(false);+ const selection = document.getSelection();+ selection?.removeAllRanges(); selection?.addRange(range);+ fireEvent.input(el);}const SLASH_ITEMS = [@@ -151,8 +155,8 @@ describe("composer typeahead", () => {]);expect(screen.getByTestId("composer-typeahead").textContent).toContain("Plugins");const asked = new URL(String(fetchMock.mock.calls[0][0]), "http://x").searchParams;- // The default store speaks for the front page; the IDE's store would say "agent".- expect(asked.get("surface")).toBe("jarvis");+ // Native CLI completions belong to the IDE chat surface.+ expect(asked.get("surface")).toBe("agent");expect(asked.get("provider")).toBe("claude-api");expect(asked.get("cwd")).toBe("C:\\work");@@ -165,7 +169,7 @@ describe("composer typeahead", () => {);expect(screen.getByTestId("composer-typeahead-item").textContent).toContain("/review");fireEvent.keyDown(box(), { key: "Enter" });- await waitFor(() => expect(box().value).toBe("/review "));+ await waitFor(() => expect(box().textContent).toBe("/review "));expect(sent).toEqual([]);expect(screen.queryByTestId("composer-typeahead")).toBeNull();});@@ -187,7 +191,7 @@ describe("composer typeahead", () => {fireEvent.keyDown(box(), { key: "ArrowDown" });fireEvent.keyDown(box(), { key: "ArrowUp" });fireEvent.keyDown(box(), { key: "Tab" });- await waitFor(() => expect(box().value).toBe("look at @src/"));+ await waitFor(() => expect(box().textContent).toBe("look at @src/"));expect(sent).toEqual([]);});diff --git a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts b/jarvis/ui/web/frontend/src/components/agentchat/reduce.tsindex 9622b04d51..dfe89b03c8 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/reduce.ts@@ -1,4 +1,5 @@import type { AgentChatEvent, InternalMessage } from "@/lib/agentChatApi";+import type { ChatControlState } from "@/lib/chatControlApi";import { readToolChoices, type ToolChoice } from "./toolChoices";/**@@ -60,6 +61,7 @@ export type TurnBlock = TextBlock | ReasoningBlock | ToolBlock;export type TurnStatus = "running" | "done" | "cancelled" | "error";export interface UserItem {+ origin?: "control";type: "user";id: string;/**@@ -162,6 +164,7 @@ export interface PendingApproval {}export interface Timeline {+ control?: ChatControlState;items: TimelineItem[];pendingApprovals: PendingApproval[];/** Highest persisted seq folded so far — the `?after=` for a reconnect. */@@ -298,6 +301,7 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {{type: "user",id: `u-${seq || ev.ts_ms}`,+ ...(p.origin === "control" ? { origin: "control" as const } : {}),// `typed` is present only when the message carried files, and it// is the person's own sentence; `text` is the composed prompt.text: str(p.typed) || str(p.text),@@ -614,6 +618,9 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {}case "notice": {+ if (p.kind === "chat_control" && p.state && typeof p.state === "object") {+ return { ...base, control: p.state as ChatControlState };+ }const text = str(p.text);const kind = str(p.kind);if (!text && !kind) return base;diff --git a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsxindex f2489d7704..475ed0b4de 100644--- a/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx+++ b/jarvis/ui/web/frontend/src/components/home/ChatStage.tsx@@ -1,3 +1,4 @@+import { useTranscriptView } from "../society/chat/useTranscriptView";import { PairConversationBoundary } from "@/components/agentchat/PairConversation";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";@@ -62,9 +63,11 @@ function ChatStageContent() {const t = useT();const assistantName = useEventStore((s) => s.assistantName);const surface = useAgentChat((s) => s.surface);- const items = useAgentChat((s) => s.timeline.items);+ const allItems = useAgentChat((s) => s.timeline.items);const cwd = useAgentChat((s) => s.draft.cwd);const activeSessionId = useAgentChat((s) => s.activeSessionId);+ const view = useTranscriptView(surface === "jarvis" ? activeSessionId : null, allItems);+ const items = view.items;const catalog = useAgentChat((s) => s.catalog);const decide = useAgentChat((s) => s.decide);const loadCatalog = useAgentChat((s) => s.loadCatalog);diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 59f9fb9d3a..b052787095 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -59,6 +59,7 @@ import { CodingProjectChoice } from "./CodingProjectChoice";import { MentionPicker } from "./MentionPicker";import { AgentModelPicker } from "./AgentModelPicker";import { mentionChoice, messageChoices } from "./mentionChoices";+import { ChatCommandPanel, useChatCommands } from "@/components/agentchat/ChatCommands";import { useTranscriptView } from "./useTranscriptView";import {buildMentionCatalog,@@ -646,7 +647,7 @@ export function Transcript({const stamp = ts && ts - lastStamp > STAMP_GAP_MS ? ts : 0;if (stamp) lastStamp = ts;return (- <div key={item.id} className="flex flex-col gap-2">+ <div key={item.id} data-chat-item={item.id} className="flex flex-col gap-2">{stamp ? <TimeStamp ms={stamp} /> : null}{item.type === "internal" ? (<InternalMessageBubble@@ -693,6 +694,7 @@ function TimeStamp({ ms }: { ms: number }) {*/function NoticeLine({ item }: { item: NoticeItem }) {const t = useT();+ if (item.kind === "native_goal_verdict") return <p className="py-1 text-xs text-muted-foreground">{t("slash.verifying")}</p>;const headline =item.kind === "society_result"? t(item.status === "done" ? "society.chat.result_done" : "society.chat.result_blocked").replace(@@ -878,8 +880,10 @@ function visibleUserText(text: string): string {}export function UserBubble({ item }: { item: UserItem }) {+ const t = useT();const choices = messageChoices(item);const text = visibleUserText(item.text);+ if (item.origin === "control") return <div className="self-start px-1 py-2 text-xs text-muted-foreground">{t("slash.control_turn")}{item.attachments.map((file) => <span key={file.name} className="ml-2">{file.name}</span>)}</div>;return (<div className="flex max-w-[85%] flex-col items-end gap-1 self-end"><div className="rounded-2xl rounded-br-md bg-secondary px-3.5 py-2 text-sm leading-relaxed text-foreground">@@ -970,6 +974,11 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sconst composerRef = useRef<HTMLDivElement>(null);const fileInput = useRef<HTMLInputElement>(null);const attachments = useChatAttachments({ sessionId, cwd, provider, surface }, (message) => setProblem(message));+ const commands = useChatCommands({ value, agentId: agent.agentId, onClear,+ attachments: attachments.attachments, attachmentsBusy: attachments.analyzing > 0, onAttachmentsSent: attachments.clear,+ setValue: (next) => { setValue(next); fieldRef.current?.setText(next); },+ onModel: () => composerRef.current?.querySelector<HTMLButtonElement>("[data-chat-model-trigger]")?.click(),+ });const dictation = useComposerDictation(value, (next) => {const text = typeof next === "function" ? next(value) : next;setValue(text);@@ -1046,16 +1055,8 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sconst submittedFolder = codingFolder;const selected = selectedTools;const text = draftText;- if (!text || busy || modelSaving) return;- if (text === "/clear" && onClear) {- onClear();- setValue("");- fieldRef.current?.clear();- setSelectedTools([]);- setMention(null);- setProblem(null);- return;- }+ if (await commands.execute(text)) return;+ if (!text || busy && !commands.canSteer || modelSaving) return;const named = mentionsInText(text, catalog);const lines: string[] = [];if (named.agents.length > 0 && surface === "society") {@@ -1096,6 +1097,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, sreturn (<div className="shrink-0 border-t border-border px-3 pb-3 pt-2">+ <div className={CHAT_MEASURE}><ChatCommandPanel control={commands} /></div>{problem ? <p className="mb-1 px-1 text-xs text-destructive">{problem}</p> : null}{mentionOpen && codingError ? <button type="button" className="mb-1 text-xs text-destructive underline" onClick={() => setCodingRetry((n) => n + 1)}>{t("society.chat.coding_retry")}</button> : null}<div className={CHAT_MEASURE}>@@ -1188,11 +1190,12 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s<ComposerChipFieldref={fieldRef}placeholder={t("society.chat.placeholder").replace("{0}", agent.name)}- disabled={busy}+ disabled={false}onSubmit={() => void submit()}onDraftChange={onDraftChange}onPasteFiles={attachments.onPaste}onKeyDown={(e) => {+ if (commands.onKeyDown(e)) return true;if (!pickerOpen) return false;if (e.key === "ArrowDown") {e.preventDefault();@@ -1239,7 +1242,7 @@ export function Composer({ agent, mentionable, busy, sessionId, cwd, provider, s>{dictation.dictating ? <Square className="h-4 w-4" aria-hidden /> : <Mic className="h-4 w-4" aria-hidden />}</button>- {busy ? (+ {busy && !commands.isCommand && !(commands.canSteer && value.trim()) ? (<buttontype="button"onClick={() => void onCancel()}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsxindex 73a7ab9c84..f4e3a701b6 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.tsx@@ -167,7 +167,7 @@ export function AgentModelPicker({ agent, busy, onSavingChange }: {} : {};return <>- <button ref={trigger} type="button" aria-label={t("society.chat.model")} aria-haspopup="menu" aria-expanded={open} aria-controls={open ? menuId : undefined}+ <button ref={trigger} data-chat-model-trigger type="button" aria-label={t("society.chat.model")} aria-haspopup="menu" aria-expanded={open} aria-controls={open ? menuId : undefined}disabled={busy || saving} title={busy ? t("society.chat.model_busy") : t("society.chat.model")}onClick={() => { if (open) close(); else { setSearch(""); setAccounts({}); setExpanded({}); setError(null); setOpen(true); } }}className="flex max-w-full items-center gap-1.5 rounded-full px-2 py-1 text-xs text-muted-foreground hover:bg-secondary hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50">diff --git a/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.ts b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.tsindex 412695d2bf..4fca2c5489 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.ts+++ b/jarvis/ui/web/frontend/src/components/society/chat/useTranscriptView.ts@@ -24,6 +24,20 @@ export const useTranscriptViewStore = create<{ boundaries: Boundaries }>(() => (boundaries: readClearedViews(),}));+export function restoreTranscriptView(sessionId: string | null): void {+ if (!sessionId) return;+ useTranscriptViewStore.setState((state) => {+ const boundaries = { ...state.boundaries };+ delete boundaries[sessionId];+ return { boundaries };+ });+ try {+ localStorage.setItem(STORAGE_KEY, JSON.stringify(useTranscriptViewStore.getState().boundaries));+ } catch {+ // Restoring remains usable for this window if browser preferences cannot be saved.+ }+}+function timestamp(item: TimelineItem): number {return item.type === "turn" ? item.startedMs : item.tsMs;}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex b15b0836fd..4ea6b28f0e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -615,7 +615,6 @@"delivery_sent": "Gesendet","delivery_delivered": "Zugestellt","delivery_failed": "Fehlgeschlagen",-"placeholder": "Frag mich alles …","empty_subtitle": "{name} mit Tastatur — derselbe Assistent, den das Mikrofon erreicht. Das gewählte Modell ist das, worauf {name} in diesem Chat läuft.","empty_subtitle_agent": "Ein Coding-Agent arbeitet an den Dateien in diesem Ordner — nicht an deinem Gedächtnis, deinem Wiki oder deinem Kalender. Modell wählen. Dann fragen.",@@ -5549,12 +5548,63 @@"command": "Befehl ausführen","edit": "Datei bearbeiten","write": "Datei schreiben"-},+ },"chat_media": {"unavailable": "Dieses Medium kann nicht geladen oder abgespielt werden. Du kannst die Datei weiterhin öffnen.","expand": "{file} vergrößern","open_file": "Datei öffnen","download": "Herunterladen","retry": "Erneut versuchen"-}+ },+ "slash": {+ "locale": "de",+ "commands": {+ "help": "Command-Hilfe öffnen",+ "clear": "Ansicht leeren; Kontext behalten",+ "history": "Frühere Nachrichten anzeigen",+ "plan": "Lesen und planen, ohne Änderungen",+ "build": "Den besprochenen Plan umsetzen",+ "goal": "Ein überprüfbares Ziel verfolgen",+ "status": "Aktuelle Aufgabe und Ziel anzeigen",+ "stop": "Arbeit stoppen und Ziel pausieren",+ "continue": "Unterbrochene Arbeit fortsetzen",+ "recap": "Aktuellen Stand zusammenfassen",+ "find": "Diesen Chat durchsuchen",+ "model": "Modell auswählen",+ "remember": "Eine Erinnerung speichern",+ "message": "Eine interne Nachricht senden",+ "review": "Letztes Ergebnis prüfen",+ "routines": "Routinen dieses Agenten verwalten"+ },+ "help": "Chat-Commands",+ "plan_active": "Planmodus · nur lesen",+ "goal_active": "Ziel läuft",+ "goal_paused": "Ziel pausiert",+ "goal_blocked": "Ziel blockiert",+ "goal_complete": "Ziel erreicht",+ "goal_cleared": "Ziel beendet",+ "steps": "Schritte",+ "stop": "Stoppen",+ "continue": "Fortsetzen",+ "clear_goal": "Ziel beenden",+ "working": "Wird ausgeführt",+ "status": "Status",+ "find": "Suchergebnisse",+ "routines": "Routinen",+ "close": "Schließen",+ "mode": "Modus",+ "task": "Aufgabe",+ "no_task": "Keine aktuelle Aufgabe",+ "goal": "Ziel",+ "no_matches": "Keine passenden Nachrichten",+ "command_done": "Command ausgeführt",+ "backend_unavailable": "Diese Commands benötigen die aktualisierte Backend-Verbindung",+ "session_loading": "Der Chat wird noch geladen",+ "session_changed": "Der aktive Chat hat gewechselt",+ "no_arguments": "Dieser Command erwartet keine Argumente",+ "attachments_loading": "Bitte warte, bis die Anhänge verarbeitet sind.",+ "build_active": "Arbeitsmodus",+ "control_turn": "Agentenarbeit",+ "verifying": "Ausführung abgeschlossen; Ergebnis wird geprüft."+ }}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex a1790b284a..50c1b752cb 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -615,7 +615,6 @@"delivery_sent": "Sent","delivery_delivered": "Delivered","delivery_failed": "Failed",-"placeholder": "Ask anything…","empty_subtitle": "{name} with a keyboard — the same assistant the microphone reaches. The model you pick is what {name} runs on for this chat.","empty_subtitle_agent": "A coding agent works on the files in this folder — not on your memory, your wiki or your calendar. Pick a model. Then ask.",@@ -5582,12 +5581,63 @@"command": "Run command","edit": "Edit file","write": "Write file"-},+ },"chat_media": {"unavailable": "This media cannot be loaded or played. You can still open the file.","expand": "Enlarge {file}","open_file": "Open file","download": "Download","retry": "Retry"-}+ },+ "slash": {+ "locale": "en",+ "commands": {+ "help": "Open command help",+ "clear": "Clear the view; keep context",+ "history": "Show earlier messages",+ "plan": "Read and plan without changes",+ "build": "Implement the agreed plan",+ "goal": "Work toward a verifiable goal",+ "status": "Show current task and goal",+ "stop": "Stop work and pause the goal",+ "continue": "Continue interrupted work",+ "recap": "Summarize the current state",+ "find": "Search this chat",+ "model": "Choose a model",+ "remember": "Save a memory",+ "message": "Send an internal message",+ "review": "Review the latest result",+ "routines": "Manage this agent's routines"+ },+ "help": "Chat commands",+ "plan_active": "Plan mode · reads only",+ "goal_active": "Goal running",+ "goal_paused": "Goal paused",+ "goal_blocked": "Goal blocked",+ "goal_complete": "Goal complete",+ "goal_cleared": "Goal cleared",+ "steps": "steps",+ "stop": "Stop",+ "continue": "Continue",+ "clear_goal": "Clear goal",+ "working": "Working",+ "status": "Status",+ "find": "Search results",+ "routines": "Routines",+ "close": "Close",+ "mode": "Mode",+ "task": "Task",+ "no_task": "No current task",+ "goal": "Goal",+ "no_matches": "No matching messages",+ "command_done": "Command completed",+ "backend_unavailable": "These commands need the updated backend connection",+ "session_loading": "The chat is still loading",+ "session_changed": "The active chat changed",+ "no_arguments": "This command takes no arguments",+ "attachments_loading": "Wait until the attachments have finished processing.",+ "build_active": "Build mode",+ "control_turn": "Agent work",+ "verifying": "Execution finished; verifying the result."+ }}diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex d214275403..8cecd2579e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -615,7 +615,6 @@"delivery_sent": "Enviado","delivery_delivered": "Entregado","delivery_failed": "Error",-"placeholder": "Pregunta lo que quieras…","empty_subtitle": "{name} con teclado: el mismo asistente que atiende el micrófono. El modelo que elijas es sobre lo que corre {name} en este chat.","empty_subtitle_agent": "Un agente de código trabaja en los archivos de esta carpeta, no en tu memoria, tu wiki ni tu calendario. Elige un modelo. Luego pregunta.",@@ -5549,12 +5548,63 @@"command": "Ejecutar comando","edit": "Editar archivo","write": "Escribir archivo"-},+ },"chat_media": {"unavailable": "No se puede cargar o reproducir este archivo. Puedes abrirlo directamente.","expand": "Ampliar {file}","open_file": "Abrir archivo","download": "Descargar","retry": "Reintentar"-}+ },+ "slash": {+ "locale": "es",+ "commands": {+ "help": "Abrir la ayuda de comandos",+ "clear": "Vaciar la vista; conservar el contexto",+ "history": "Mostrar mensajes anteriores",+ "plan": "Leer y planificar sin cambios",+ "build": "Implementar el plan acordado",+ "goal": "Trabajar hacia un objetivo verificable",+ "status": "Mostrar la tarea y el objetivo",+ "stop": "Detener el trabajo y pausar el objetivo",+ "continue": "Continuar el trabajo interrumpido",+ "recap": "Resumir el estado actual",+ "find": "Buscar en este chat",+ "model": "Elegir un modelo",+ "remember": "Guardar un recuerdo",+ "message": "Enviar un mensaje interno",+ "review": "Revisar el último resultado",+ "routines": "Gestionar las rutinas del agente"+ },+ "help": "Comandos del chat",+ "plan_active": "Modo plan · solo lectura",+ "goal_active": "Objetivo en curso",+ "goal_paused": "Objetivo pausado",+ "goal_blocked": "Objetivo bloqueado",+ "goal_complete": "Objetivo completado",+ "goal_cleared": "Objetivo eliminado",+ "steps": "pasos",+ "stop": "Detener",+ "continue": "Continuar",+ "clear_goal": "Eliminar objetivo",+ "working": "Ejecutando",+ "status": "Estado",+ "find": "Resultados de búsqueda",+ "routines": "Rutinas",+ "close": "Cerrar",+ "mode": "Modo",+ "task": "Tarea",+ "no_task": "Sin tarea actual",+ "goal": "Objetivo",+ "no_matches": "No hay mensajes coincidentes",+ "command_done": "Comando completado",+ "backend_unavailable": "Estos comandos necesitan la conexión al backend actualizado",+ "session_loading": "El chat sigue cargando",+ "session_changed": "El chat activo ha cambiado",+ "no_arguments": "Este comando no acepta argumentos",+ "attachments_loading": "Espera a que se terminen de procesar los archivos adjuntos.",+ "build_active": "Modo de trabajo",+ "control_turn": "Trabajo del agente",+ "verifying": "Ejecución finalizada; verificando el resultado."+ }}