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.

revert(chat): the terminal workspace is the coding section again

rubenluetke10-beep289272814f40
diff --git a/jarvis/ui/web/frontend/src/components/chat/ChatActivity.tsx b/jarvis/ui/web/frontend/src/components/chat/ChatActivity.tsx
deleted file mode 100644
index 2b3be78c11..0000000000
--- a/jarvis/ui/web/frontend/src/components/chat/ChatActivity.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * What the coding agent is actually doing, as a readable feed.
- *
- * A pane carries a *terminal protocol*, not a log: a coding CLI repaints rows
- * in place, so the raw stream is unreadable and merely stripping the escape
- * codes leaves the surviving text in an order nobody wrote. The backend already
- * solves that — it replays the terminal onto a screen and reads the transcript
- * off it (`jarvis/agentic_ide/transcript.py`) — so this polls THAT and renders
- * the result, rather than inventing a second parser that would be wrong in
- * different ways.
- *
- * The feed is the honest middle ground while the structured per-CLI reader is
- * built: it is what the agent printed, in the order it printed it, with the
- * decoration folded away. It is not a guess, and it is never empty while
- * something is happening.
- */
-import { useEffect, useRef, useState } from "react";
-import { Loader2, TriangleAlert } from "lucide-react";
-
-import { cn } from "@/lib/utils";
-
-/** How often the feed asks. Fast enough to feel live, cheap enough to leave on. */
-const POLL_MS = 1200;
-
-/** How much history the feed carries. Bounded — this is a view, not an archive. */
-const LINES = 200;
-
-interface Report {
- name: string;
- display_name?: string;
- status?: string;
- transcript?: string[];
-}
-
-export interface ChatActivityProps {
- /** Call-sign of the pane to follow. */
- terminal: string;
- /** Is this view on screen? Off-screen polling is stopped rather than throttled. */
- active?: boolean;
-}
-
-export function ChatActivity({ terminal, active = true }: ChatActivityProps) {
- const [report, setReport] = useState<Report | null>(null);
- const [error, setError] = useState<string | null>(null);
- const bottom = useRef<HTMLDivElement | null>(null);
- const scroller = useRef<HTMLDivElement | null>(null);
- /*
- * Follow the tail only while the reader IS at the tail.
- *
- * Scrolling up is a deliberate act — somebody is reading what already
- * happened — and yanking them back down every 1.2 seconds makes the history
- * unreadable. The moment they return to the bottom, following resumes.
- */
- const following = useRef(true);
-
- useEffect(() => {
- if (!active) return;
- let alive = true;
- const tick = async () => {
- try {
- const response = await fetch(
- `/api/agentic-ide/terminals/${encodeURIComponent(terminal)}/report?lines=${LINES}`,
- );
- if (!response.ok) throw new Error(await response.text());
- const body = (await response.json()) as Report;
- if (!alive) return;
- setReport(body);
- setError(null);
- } catch {
- if (!alive) return;
- // A pane that has gone away is a state, not a crash: the chat is still
- // readable and the header says the agent stopped.
- setError("This agent is no longer running.");
- }
- };
- void tick();
- const id = window.setInterval(() => void tick(), POLL_MS);
- return () => {
- alive = false;
- window.clearInterval(id);
- };
- }, [active, terminal]);
-
- useEffect(() => {
- if (following.current) bottom.current?.scrollIntoView({ block: "end" });
- }, [report]);
-
- const lines = report?.transcript ?? [];
-
- return (
- <div
- ref={scroller}
- data-testid="chat-activity"
- onScroll={(event) => {
- const node = event.currentTarget;
- following.current =
- node.scrollHeight - node.scrollTop - node.clientHeight < 48;
- }}
- className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-6 py-4"
- >
- <div className="mx-auto w-full max-w-3xl">
- {error && (
- <div className="mb-3 flex items-center gap-2 rounded-lg border border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-300">
- <TriangleAlert className="h-3.5 w-3.5 shrink-0" aria-hidden />
- {error}
- </div>
- )}
- {!report && !error && (
- <div className="flex items-center gap-2 text-xs text-muted-foreground">
- <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
- Starting the agent…
- </div>
- )}
- {lines.length === 0 && report && !error && (
- <div className="text-xs text-muted-foreground">
- The agent is up and has not printed anything yet.
- </div>
- )}
- {lines.length > 0 && (
- <pre className="whitespace-pre-wrap break-words font-mono text-[12px] leading-relaxed text-foreground/85">
- {lines.join("\n")}
- </pre>
- )}
- <div ref={bottom} />
- </div>
- </div>
- );
-}
-
-/** A small live/idle mark for the chat header. */
-export function ActivityDot({ status }: { status?: string }) {
- const working = status === "running" || status === "working";
- return (
- <span
- title={working ? "Working" : "Idle"}
- aria-label={working ? "Working" : "Idle"}
- className={cn(
- "h-1.5 w-1.5 shrink-0 rounded-full",
- working ? "animate-pulse bg-emerald-400" : "bg-muted-foreground/50",
- )}
- />
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/chat/ChatStream.tsx b/jarvis/ui/web/frontend/src/components/chat/ChatStream.tsx
deleted file mode 100644
index 6b957ae935..0000000000
--- a/jarvis/ui/web/frontend/src/components/chat/ChatStream.tsx
+++ /dev/null
@@ -1,262 +0,0 @@
-/**
- * The conversation, as a conversation.
- *
- * ## Where this reads from, and why it changed
- *
- * It used to read the pane's SCREEN and classify the lines back into a chat.
- * That cannot be made to work, because a TUI is a picture rather than a
- * protocol: it repaints rows in place, wraps to whatever width it happened to
- * have, draws its own logo, and prints spinners. The first version of this view
- * showed a half-rendered ASCII banner, a raw `$ cd … && git diff` line and
- * `Churned for 5s` — all of them faithfully transcribed, none of them anything
- * a person wants to read.
- *
- * So it reads the record the CLI keeps in order to resume itself
- * (`/terminals/{name}/conversation`). There, roles are declared and tool calls
- * carry their name and arguments, so this component renders rather than guesses:
- * prose as Markdown, work as quiet collapsible steps, and nothing at all for
- * the banner — because the banner was never in the conversation to begin with.
- *
- * ## Two sources, on purpose
- *
- * The file says what was SAID; it is written as turns complete. The pane says
- * what is happening RIGHT NOW. So the live status line at the bottom still
- * comes from the pane, and a CLI that keeps no readable record falls back to
- * the pane entirely — honestly, with the terminal offered rather than an error.
- */
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import { ChevronRight, Loader2, TriangleAlert } from "lucide-react";
-import ReactMarkdown from "react-markdown";
-
-import { cn } from "@/lib/utils";
-import {
- fetchConversation,
- type AgentStep,
- type AgentTurn,
-} from "@/lib/agentConversationApi";
-
-/**
- * How often the conversation is re-read.
- *
- * Slower than the pane's own poll: this file changes when a turn COMPLETES, not
- * while it is being typed, so asking four times a second would be four times
- * the disk for the same answer. The live line below it is what moves quickly.
- */
-const POLL_MS = 1500;
-
-export interface ChatStreamProps {
- terminal: string;
- active?: boolean;
- /**
- * Show the raw pane instead. Called when this CLI keeps no readable record —
- * the surface has the terminal and should mount it rather than leave the
- * reader with an empty column.
- */
- onUnavailable?: () => void;
-}
-
-export function ChatStream({ terminal, active = true, onUnavailable }: ChatStreamProps) {
- const [turns, setTurns] = useState<AgentTurn[] | null>(null);
- const [error, setError] = useState<string | null>(null);
- const bottom = useRef<HTMLDivElement | null>(null);
- /*
- * Follow the tail only while the reader IS at the tail. Scrolling up is a
- * deliberate act — somebody is reading what already happened — and yanking
- * them back down on every poll makes the history unreadable.
- */
- const following = useRef(true);
- const reportedUnavailable = useRef(false);
-
- const notifyUnavailable = useCallback(() => {
- if (reportedUnavailable.current) return;
- reportedUnavailable.current = true;
- onUnavailable?.();
- }, [onUnavailable]);
-
- useEffect(() => {
- if (!active) return;
- let alive = true;
- const tick = async () => {
- try {
- const body = await fetchConversation(terminal);
- if (!alive) return;
- // Settled "this CLI keeps no readable record" — hand over to the pane.
- // NOT the same as "no conversation yet": one CLI only reveals its
- // session id after its first turn, and giving up on that would mean a
- // conversation seconds away was never shown.
- if (!body.readable) {
- notifyUnavailable();
- return;
- }
- setTurns(body.available ? body.turns : []);
- setError(null);
- } catch {
- if (!alive) return;
- // A pane that has gone away is a state, not a crash. Said once, in the
- // reader's language of "this stopped", not as a status code.
- setError("This agent is no longer running.");
- }
- };
- void tick();
- const id = window.setInterval(() => void tick(), POLL_MS);
- return () => {
- alive = false;
- window.clearInterval(id);
- };
- }, [active, notifyUnavailable, terminal]);
-
- // Keyed on the turn count and the last turn's length: the tail grows both by
- // gaining turns and by the open turn getting longer, and only those two mean
- // "there is new text below".
- const tailKey = useMemo(() => {
- const last = turns?.[turns.length - 1];
- return `${turns?.length ?? 0}:${last?.text.length ?? 0}:${last?.steps.length ?? 0}`;
- }, [turns]);
-
- useEffect(() => {
- if (following.current) bottom.current?.scrollIntoView({ block: "end" });
- }, [tailKey]);
-
- return (
- <div
- onScroll={(event) => {
- const node = event.currentTarget;
- following.current = node.scrollHeight - node.scrollTop - node.clientHeight < 64;
- }}
- data-testid="chat-stream"
- className="min-h-0 flex-1 overflow-y-auto scrollbar-jarvis px-8 py-8"
- >
- <div className="mx-auto flex w-full max-w-[46rem] flex-col gap-7">
- {error && (
- <div className="flex items-center gap-2 rounded-xl border border-amber-500/25 bg-amber-500/[0.06] px-4 py-3 text-sm text-amber-300">
- <TriangleAlert className="h-4 w-4 shrink-0" aria-hidden />
- {error}
- </div>
- )}
- {turns === null && !error && (
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
- <Loader2 className="h-4 w-4 animate-spin" aria-hidden />
- Reading the conversation…
- </div>
- )}
- {turns !== null && turns.length === 0 && !error && (
- <p className="text-[15px] text-muted-foreground">
- The agent is ready. Say what you want done.
- </p>
- )}
- {(turns ?? []).map((turn, index) => (
- <TurnBlock key={index} turn={turn} />
- ))}
- <div ref={bottom} />
- </div>
- </div>
- );
-}
-
-function TurnBlock({ turn }: { turn: AgentTurn }) {
- if (turn.role === "user") {
- return (
- <div className="flex justify-end">
- <div className="max-w-[80%] whitespace-pre-wrap break-words rounded-2xl bg-foreground/[0.07] px-4 py-2.5 text-[15px] leading-[1.6]">
- {turn.text}
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex flex-col gap-3">
- {turn.text && <Prose text={turn.text} />}
- {turn.steps.length > 0 && (
- <div className="flex flex-col gap-0.5">
- {turn.steps.map((step, index) => (
- <StepRow key={index} step={step} />
- ))}
- </div>
- )}
- </div>
- );
-}
-
-/**
- * The agent's own words, rendered as the Markdown they are.
- *
- * A coding agent writes in Markdown — headings, lists, fenced code — and
- * showing that as preformatted text was half of why the old view looked like a
- * log file. The type scale is a reading scale rather than a terminal one: this
- * is prose, and it is the only thing on this surface anybody reads end to end.
- */
-function Prose({ text }: { text: string }) {
- return (
- <div
- className={cn(
- "text-[15.5px] leading-[1.7] tracking-[-0.003em] text-foreground/90",
- "[&_p]:my-2 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0",
- "[&_ul]:my-2 [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:pl-5",
- "[&_li]:my-0.5",
- "[&_h1]:mb-2 [&_h1]:mt-4 [&_h1]:text-[17px] [&_h1]:font-semibold",
- "[&_h2]:mb-2 [&_h2]:mt-4 [&_h2]:text-[16px] [&_h2]:font-semibold",
- "[&_h3]:mb-1.5 [&_h3]:mt-3 [&_h3]:text-[15px] [&_h3]:font-semibold",
- "[&_strong]:font-semibold [&_strong]:text-foreground",
- "[&_code]:rounded [&_code]:bg-foreground/[0.07] [&_code]:px-1 [&_code]:py-0.5",
- "[&_code]:font-mono [&_code]:text-[13px]",
- "[&_pre]:my-3 [&_pre]:overflow-x-auto [&_pre]:rounded-lg [&_pre]:bg-foreground/[0.05]",
- "[&_pre]:p-3 [&_pre_code]:bg-transparent [&_pre_code]:p-0 [&_pre_code]:text-[12.5px]",
- "[&_a]:underline [&_a]:underline-offset-2",
- "[&_blockquote]:border-l-2 [&_blockquote]:border-border [&_blockquote]:pl-3",
- "[&_blockquote]:text-muted-foreground",
- )}
- >
- <ReactMarkdown>{text}</ReactMarkdown>
- </div>
- );
-}
-
-/**
- * One tool call, at the weight of a footnote.
- *
- * The name the CLI gave the tool and the one argument worth seeing — a path, a
- * command — on a single line that does not wrap. Everything else is behind the
- * disclosure, because the reason to show steps at all is "I can see what it
- * touched", and that question is answered by forty short lines, never by forty
- * pretty-printed JSON objects.
- */
-function StepRow({ step }: { step: AgentStep }) {
- const [open, setOpen] = useState(false);
- const expandable = Boolean(step.detail);
-
- return (
- <div>
- <button
- type="button"
- onClick={() => expandable && setOpen((v) => !v)}
- aria-expanded={expandable ? open : undefined}
- className={cn(
- "flex w-full items-center gap-2 rounded-md px-1.5 py-1 text-left text-[12.5px]",
- "text-muted-foreground transition-colors",
- expandable && "hover:bg-foreground/[0.05] hover:text-foreground/80",
- )}
- >
- <ChevronRight
- className={cn(
- "h-3 w-3 shrink-0 transition-transform",
- open && "rotate-90",
- !expandable && "opacity-0",
- )}
- aria-hidden
- />
- <span className="shrink-0 font-medium text-foreground/70">{step.tool}</span>
- {step.target && (
- <span className="min-w-0 flex-1 truncate font-mono text-[11.5px] text-muted-foreground/80">
- {step.target}
- </span>
- )}
- </button>
- {open && step.detail && (
- <pre className="ml-6 mt-1 max-h-72 overflow-auto scrollbar-jarvis whitespace-pre-wrap break-words rounded-md bg-foreground/[0.04] p-2.5 font-mono text-[11.5px] leading-relaxed text-muted-foreground">
- {step.detail}
- </pre>
- )}
- </div>
- );
-}
diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
index b5060f9311..3f3a338fde 100644
--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx
@@ -89,13 +89,6 @@ const ExtensionsView = lazyView(() =>
const AgenticIdeView = lazyPropView<AgenticIdeViewProps>(() =>
import("@/views/AgenticIdeView").then((m) => ({ default: m.AgenticIdeView })),
);
-// The rebuilt chat surface. Lazy like every other section and NOT sticky: it
-// holds no live terminal of its own yet, so there is nothing to tear down by
-// unmounting it — that changes when the conversation view lands, and the
-// sticky treatment moves with it.
-const ChatWorkspaceView = lazyView(() =>
- import("@/views/ChatWorkspaceView").then((m) => ({ default: m.ChatWorkspaceView })),
-);
const TasksView = lazyView(() =>
import("@/views/TasksView").then((m) => ({ default: m.TasksView })),
);
@@ -226,14 +219,26 @@ function ViewLoadingFallback() {
return <div className="h-full w-full" aria-busy="true" />;
}
+/**
+ * The section ids that all mean "the coding workspace".
+ *
+ * There is ONE coding surface again: the terminal workspace. A separate chat
+ * surface was tried in front of it and taken back out — it rendered a picture of
+ * the agent while the agent itself ran behind it, which is one thing too many
+ * for a screen whose whole job is showing what the agent is doing. The extra
+ * ids stay valid because deep links, voice commands and stored preferences
+ * already point at them, and an id that stops resolving is a dead end for
+ * somebody who never chose either name.
+ */
+const CODING_SECTION_IDS = ["agentic-ide", "agentic-ide-classic", "chat-workspace"] as const;
+
/**
* The one section that is hidden rather than unmounted — see `MainView`.
*
- * It is the CLASSIC terminal grid, not the chat surface that took over the
- * "agentic-ide" id: what makes a section too destructive to unmount is live
- * panes, and the grid is where those live.
+ * What makes a section too destructive to unmount is LIVE PANES, and this is
+ * where those live.
*/
-const STICKY_SECTION = "agentic-ide-classic";
+const STICKY_SECTION = "agentic-ide";
/**
* Main area to the right of the sidebar. Views are switched the classic way
@@ -265,7 +270,7 @@ export function MainView() {
useIdleViewPrefetch();
- const stickyActive = active === STICKY_SECTION;
+ const stickyActive = (CODING_SECTION_IDS as readonly string[]).includes(active);
const [stickyMounted, setStickyMounted] = useState(stickyActive);
useEffect(() => {
if (stickyActive) setStickyMounted(true);
@@ -319,13 +324,6 @@ export function MainView() {
function SwitchOnActiveSection({ active }: { active: string }) {
switch (active) {
- // The rebuilt chat surface IS the coding section now. Both ids reach it:
- // "agentic-ide" because that is where every existing entry point, deep
- // link and voice command already goes, and "chat-workspace" because that
- // is what it is called.
- case "agentic-ide":
- case "chat-workspace":
- return <ChatWorkspaceView />;
case "chats":
return <ChatsView />;
case "agents":
@@ -395,12 +393,15 @@ function SwitchOnActiveSection({ active }: { active: string }) {
return <FeedbackView />;
case "agent-instructions":
return <AgentInstructionsView />;
- // Deliberately nothing: the Agentic IDE is rendered by the STICKY branch in
- // `MainView` above, which keeps it mounted across section changes. This
- // switch is not rendered at all while that section is active, so reaching
- // here would mean two live copies of a workspace's terminals — the second
- // of which would steal every pane's output stream from the first.
- case STICKY_SECTION:
+ // Deliberately nothing: the coding workspace is rendered by the STICKY
+ // branch in `MainView` above, which keeps it mounted across section
+ // changes. This switch is not rendered at all while one of those ids is
+ // active, so reaching here would mean two live copies of a workspace's
+ // terminals — the second of which would steal every pane's output stream
+ // from the first.
+ case "agentic-ide":
+ case "agentic-ide-classic":
+ case "chat-workspace":
return null;
default:
return <ChatsView />;
diff --git a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
index ee7f0bf68c..15c42d7311 100644
--- a/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
+++ b/jarvis/ui/web/frontend/src/components/layout/TopBar.tsx
@@ -39,12 +39,17 @@ const CONFIRM_TIMEOUT_MS = 4000;
export function TopBar() {
const activeSection = useEventStore((s) => s.activeSection);
- // ONLY the classic terminal grid takes the actions into its own row. The
- // rebuilt chat surface has no such row, so hiding the bar there would take
- // Restart — the one control a frontend change is reached through — off the
- // screen entirely. The rule is "the section carries the actions itself",
- // never "the section is called agentic-ide".
- if (activeSection === "agentic-ide-classic") return null;
+ // The coding workspace takes the actions into its own toolbar row, under
+ // every id that reaches it. The rule is "the section carries the actions
+ // itself" — a section that does not would lose Restart, which is the one
+ // control a frontend change is reached through.
+ if (
+ activeSection === "agentic-ide" ||
+ activeSection === "agentic-ide-classic" ||
+ activeSection === "chat-workspace"
+ ) {
+ return null;
+ }
return (
<div className="flex h-10 shrink-0 items-center justify-end gap-2 border-b border-border bg-background/70 px-4 backdrop-blur-sm">
diff --git a/jarvis/ui/web/frontend/src/lib/agentConversationApi.ts b/jarvis/ui/web/frontend/src/lib/agentConversationApi.ts
deleted file mode 100644
index e4f2fac661..0000000000
--- a/jarvis/ui/web/frontend/src/lib/agentConversationApi.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * A pane's conversation, as the coding CLI itself recorded it.
- *
- * The counterpart of `/report`, and the reason it exists: `/report` answers
- * with the pane's SCREEN — the picture a TUI drew, banners and spinners and
- * all — while this answers with the file the CLI keeps in order to be able to
- * resume itself. Roles are declared there, tool calls carry their arguments,
- * and prose is prose, so nothing downstream has to guess what a line was.
- *
- * Two different "no", and the caller must tell them apart. `readable: false`
- * is settled — this CLI keeps no record anyone can read, so switch to the live
- * pane and stay there. `available: false` with `readable: true` is transient —
- * the file appears when the conversation starts, and one CLI only reveals its
- * session id afterwards — so WAIT. Treating the second as the first is how a
- * conversation that was seconds away never gets shown.
- */
-
-/** One thing the agent did between two things it said. */
-export interface AgentStep {
- /** The CLI's own name for the tool — shown as-is, never translated. */
- tool: string;
- /** The one argument worth reading at a glance: a path, a command. */
- target: string;
- /** Everything else about the call, for a reader who opens the step. */
- detail: string;
-}
-
-export interface AgentTurn {
- role: "user" | "assistant";
- text: string;
- steps: AgentStep[];
-}
-
-export interface AgentConversation {
- terminal: string;
- agent: string;
- /** Does this CLI keep a record that can be read at all? Settled, not timing. */
- readable: boolean;
- /** Is there a conversation to show right now? False may simply mean "not yet". */
- available: boolean;
- turns: AgentTurn[];
-}
-
-export async function fetchConversation(
- terminal: string,
- signal?: AbortSignal,
-): Promise<AgentConversation> {
- const response = await fetch(
- `/api/agentic-ide/terminals/${encodeURIComponent(terminal)}/conversation`,
- { signal },
- );
- if (!response.ok) throw new Error(String(response.status));
- return (await response.json()) as AgentConversation;
-}
diff --git a/jarvis/ui/web/frontend/src/views/ChatWorkspaceView.tsx b/jarvis/ui/web/frontend/src/views/ChatWorkspaceView.tsx
deleted file mode 100644
index 9c85cfbded..0000000000
--- a/jarvis/ui/web/frontend/src/views/ChatWorkspaceView.tsx
+++ /dev/null
@@ -1,693 +0,0 @@
-/**
- * The chat surface — projects on the left, one conversation in the middle.
- *
- * The layout is the argument. A coding chat has exactly three things on
- * screen: the list you navigate by, the conversation you are having, and the
- * box you type into. Everything the old surface stacked around those — a
- * workspace bar, an agent column, a pane toolbar, a status strip — is either
- * gone or folded into the composer, which is where the answers to "where is
- * this going?" belong anyway.
- *
- * The middle column belongs to the agent. Before a prompt it holds the
- * project's name as a question and says where the answer will appear; from the
- * first prompt on it IS the agent, live, in that same rectangle. One surface in
- * two states, never a menu of things to click instead.
- */
-import { useCallback, useEffect, useMemo, useState } from "react";
-import {
- FolderOpen,
- LayoutGrid,
- Loader2,
- MessagesSquare,
- SquareTerminal,
- X,
-} from "lucide-react";
-
-import { AgentMark } from "@/components/agentic/AgentMark";
-import { ChatComposer, type ComposerAgent } from "@/components/chat/ChatComposer";
-import { ChatLibrarySidebar } from "@/components/chat/ChatLibrarySidebar";
-import { FolderPicker } from "@/components/agentic/FolderPicker";
-import { PaneResizer } from "@/components/layout/PaneResizer";
-import { useResizablePane } from "@/hooks/useResizablePane";
-import { useEventStore } from "@/store/events";
-import {
- addTerminal,
- fetchIdeAgents,
- fetchIdeState,
- promptTerminal,
- startIdeSession,
-} from "@/lib/agenticIdeApi";
-import { AgenticTerminal } from "@/components/agentic/AgenticTerminal";
-import { ChatStream } from "@/components/chat/ChatStream";
-import { VoiceBubble } from "@/components/agentic/VoiceBubble";
-import { getWSClient } from "@/hooks/useWebSocket";
-import {
- type ChatProject,
- type ChatRow,
- createChat,
- openProject,
- openScratchProject,
- patchChat,
- projectColor,
-} from "@/lib/chatLibraryApi";
-
-interface OpenChat {
- project: ChatProject;
- chat: ChatRow;
-}
-
-/**
- * The last segment of a path, whichever separator this machine uses.
- *
- * Read off the path rather than guessed from the browser: the folder lives on
- * the machine the BACKEND runs on, which is not necessarily the one this window
- * is open on. A path that ends in a separator still answers with its folder.
- */
-function folderName(path: string): string {
- const parts = path.split(/[\\/]/).filter(Boolean);
- return parts[parts.length - 1] || path;
-}
-
-export function ChatWorkspaceView() {
- const pushToast = useEventStore((s) => s.pushToast);
- const setActiveSection = useEventStore((s) => s.setActiveSection);
-
- const [open, setOpen] = useState<OpenChat | null>(null);
- const [lastProject, setLastProject] = useState<ChatProject | null>(null);
- const [picking, setPicking] = useState(false);
- const [pickedPath, setPickedPath] = useState<string | null>(null);
- const [refreshToken, setRefreshToken] = useState(0);
- const [busy, setBusy] = useState(false);
- const [starting, setStarting] = useState(false);
- // Which workspace the live pane belongs to. Sent with the socket so a
- // keystroke reaches the pane it was typed into: several workspaces can be
- // open and the front one changes while sockets are alive.
- const [workspaceId, setWorkspaceId] = useState<string | null>(null);
- // The spoken conversation, as a floating orb over this surface. Held here
- // rather than inside the composer: the conversation belongs to the app, and
- // a bubble mounted inside a component that re-renders per keystroke would
- // reset the orb mid-sentence.
- const [talking, setTalking] = useState(false);
- /*
- * Show the raw pane instead of the conversation.
- *
- * Set by the reader who wants the terminal, and set for them when this CLI
- * keeps no record a conversation can be read from. Reset per chat: it answers
- * "how am I looking at THIS agent", and a CLI without a transcript must not
- * decide how the next one is shown.
- */
- const [rawPane, setRawPane] = useState(false);
-
- const [agents, setAgents] = useState<ComposerAgent[]>([]);
- const [agentId, setAgentId] = useState("");
- const [modelId, setModelId] = useState<string | null>(null);
-
- const list = useResizablePane({
- storageKey: "jarvis.chat.listWidth.v1",
- defaultSize: 272,
- min: 220,
- max: 460,
- });
-
- /*
- * Which coding CLIs this machine actually has.
- *
- * Only installed ones are offered. A picker listing every CLI the registry
- * knows about would let somebody choose one that cannot start, and the
- * failure would arrive after the prompt was written — the worst possible
- * moment to learn that a tool is missing.
- */
- useEffect(() => {
- let alive = true;
- void (async () => {
- try {
- const meta = await fetchIdeAgents();
- if (!alive) return;
- const usable = meta.agents
- .filter((a) => a.installed && (a.kind ?? "cli") === "cli")
- .map<ComposerAgent>((a) => ({ id: a.name, label: a.display_name, models: [] }));
- setAgents(usable);
- setAgentId((current) => current || usable[0]?.id || "");
- } catch {
- // The composer degrades to "no agent chosen" rather than blocking the
- // view: the list is an offer, and the surface is still readable without
- // it (CLAUDE.md §3 — a missing capability never bricks a core path).
- }
- })();
- return () => {
- alive = false;
- };
- }, []);
-
- // A different chat is a different agent, possibly a different CLI. Whether
- // the LAST one had a readable transcript says nothing about this one.
- const openChatId = open?.chat.id ?? null;
- useEffect(() => {
- setRawPane(false);
- }, [openChatId]);
-
- const activeProject = open?.project ?? lastProject;
-
- const addProject = useCallback(async () => {
- if (!pickedPath) return;
- try {
- const project = await openProject(pickedPath);
- setPicking(false);
- setPickedPath(null);
- setLastProject(project);
- setRefreshToken((n) => n + 1);
- } catch (error) {
- pushToast("error", error instanceof Error ? error.message : "Could not add that folder");
- }
- }, [pickedPath, pushToast]);
-
- const startChat = useCallback(
- async (project: ChatProject) => {
- try {
- const chat = await createChat(project.id, { agent: agentId, model: modelId });
- setLastProject(project);
- setOpen({ project, chat });
- setRefreshToken((n) => n + 1);
- } catch (error) {
- pushToast("error", error instanceof Error ? error.message : "Could not start that chat");
- }
- },
- [agentId, modelId, pushToast],
- );
-
- /**
- * Start a chat without choosing a folder first.
- *
- * The agent still runs somewhere — the home directory — because a coding CLI
- * is a process with a working directory and there is no such thing as
- * nowhere. What the user is spared is the decision: a question, a quick
- * script, "which of these two files differs" are all worth asking without
- * first naming a project to ask them in.
- */
- const startSession = useCallback(async () => {
- try {
- const project = await openScratchProject();
- await startChat(project);
- } catch (error) {
- pushToast("error", error instanceof Error ? error.message : "Could not start a session");
- }
- }, [pushToast, startChat]);
-
- /**
- * Send the first prompt of a chat.
- *
- * The chat is created here if the user typed straight into the starting
- * screen, which is the common path: nobody presses "New chat" first, they
- * type. The title comes from what they wrote, so the row in the sidebar is
- * recognisable the moment it appears.
- */
- /**
- * Make sure this chat has a LIVE agent, and say which pane it is.
- *
- * Three cases, in the order they actually happen: the chat is already bound
- * to a running pane and we use it; the workspace is open on this project and
- * we add a pane to it; nothing is open and we start one. The chat records
- * the pane it got, so reopening it later finds the terminal that already
- * holds the conversation instead of starting a second agent beside it.
- */
- /**
- * Wait for a freshly opened pane to be able to receive a prompt.
- *
- * A pane is born ``pending``: the process is spawned but its pseudo-terminal
- * has not attached yet, and a prompt sent into that window is refused
- * outright — which is exactly what happened, and what the user saw as "T2 is
- * not running right now (status: pending) — nothing was sent."
- *
- * So the send waits for ``live`` instead of racing it. Generously bounded: a
- * cold coding CLI on a large repository takes seconds, not milliseconds, and
- * a timeout that fires early would reintroduce the same failure with a nicer
- * message. A pane that dies on the way up says so rather than timing out.
- */
- const waitForPane = useCallback(async (name: string): Promise<void> => {
- const deadline = Date.now() + 45_000;
- while (Date.now() < deadline) {
- const state = await fetchIdeState();
- const pane = state.session?.terminals.find((t) => t.name === name);
- if (!pane) throw new Error(`${name} disappeared before it could start.`);
- if (pane.status === "live") return;
- if (pane.status === "error" || pane.status === "exited") {
- throw new Error(pane.error || `${name} stopped before it could start.`);
- }
- await new Promise((resolve) => window.setTimeout(resolve, 350));
- }
- throw new Error(`${name} did not finish starting. Open the terminal grid to see why.`);
- }, []);
-
- /**
- * Make sure this chat has a LIVE agent, and say which pane it is.
- *
- * Three cases, in the order they actually happen: the chat is already bound
- * to a running pane and we use it; the workspace is open on this project and
- * we add a pane to it; nothing is open and we start one. The chat records
- * the pane it got, so reopening it finds the terminal that already holds the
- * conversation instead of starting a second agent beside it.
- */
- const ensureAgent = useCallback(
- async (project: ChatProject, chat: ChatRow): Promise<string> => {
- const state = await fetchIdeState();
- const session = state.session;
- if (session) setWorkspaceId(session.id);
- const sameFolder =
- session && session.folder.toLowerCase() === project.path.toLowerCase();
-
- if (sameFolder && chat.terminal) {
- const live = session.terminals.find((t) => t.name === chat.terminal);
- // A pane that is still coming up is ours too — waiting for it beats
- // starting a second agent beside it.
- if (live && live.status !== "exited" && live.status !== "error") {
- return live.name;
- }
- }
-
- const agent = chat.agent || agentId || agents[0]?.id;
- if (!agent) throw new Error("No coding CLI is installed on this machine.");
-
- const before = sameFolder ? session.terminals.map((t) => t.name) : [];
- const next = sameFolder
- ? await addTerminal({ agent })
- : (await startIdeSession(project.path, [{ agent }])).session;
- if (!next) throw new Error("The workspace closed while starting the agent.");
-
- // The pane that was NOT there a moment ago is ours. Asked this way rather
- // than by trusting a returned index, because the workspace is shared —
- // another surface can add a pane between these two calls.
- const fresh =
- next.terminals.find((t) => !before.includes(t.name)) ??
- next.terminals[next.terminals.length - 1];
- if (!fresh) throw new Error("The agent started but reported no terminal.");
-
- await patchChat(project.id, chat.id, { terminal: fresh.name });
- return fresh.name;
- },
- [agentId, agents],
- );
-
- /**
- * Send a prompt — for real.
- *
- * The chat is created here if the user typed straight into the starting
- * screen, which is the common path: nobody presses "New chat" first, they
- * type. Then an agent is started if this chat has none, and the prompt goes
- * into it. What the agent does next is on screen a second later, because the
- * feed below is already following that pane.
- */
- const send = useCallback(
- async (text: string) => {
- const project = activeProject;
- if (!project) {
- pushToast("warning", "Pick a project first — a prompt needs a folder to run in.");
- return;
- }
- setBusy(true);
- try {
- let target = open?.chat ?? null;
- if (!target || target.project_id !== project.id) {
- target = await createChat(project.id, { agent: agentId, model: modelId });
- }
- const terminal = await ensureAgent(project, target);
- /*
- * Mount the pane BEFORE waiting for it, then prompt.
- *
- * The order is the fix. A coding CLI is spawned when something attaches
- * to its pseudo-terminal, so a send that waited for "live" before
- * putting the pane on screen was waiting for a process its own silence
- * was preventing — three panes sat at "pending" and every prompt was
- * refused. Showing it first is what starts it.
- */
- const updated = await patchChat(project.id, target.id, {
- title: target.title || text.slice(0, 48),
- terminal,
- });
- setOpen({ project, chat: updated });
- setRefreshToken((n) => n + 1);
- await waitForPane(terminal);
- await promptTerminal(terminal, text);
- } catch (error) {
- pushToast("error", error instanceof Error ? error.message : "Could not send that");
- } finally {
- setBusy(false);
- }
- },
- [activeProject, agentId, ensureAgent, modelId, open, pushToast, waitForPane],
- );
-
- /**
- * Bring a chat back to life when it is opened.
- *
- * Closing the app stops every agent — deliberately, an unwatched agent burns
- * tokens invisibly — so a chat from yesterday has no pane. Clicking it starts
- * one again in the same folder with the same CLI, which is what "open the
- * chat" means to somebody who left it running.
- *
- * A chat that already has a live pane costs nothing here: `ensureAgent`
- * recognises it and returns. Failures are quiet on purpose — the user asked
- * to LOOK at a conversation, and a red box for an agent they have not typed
- * to yet would be noise. The next send reports honestly.
- */
- const reopen = useCallback(
- async (project: ChatProject, chat: ChatRow) => {
- setStarting(true);
- try {
- const terminal = await ensureAgent(project, chat);
- setOpen((current) =>
- current && current.chat.id === chat.id
- ? { project, chat: { ...current.chat, terminal } }
- : current,
- );
- } catch {
- /* see above — the send path is where this is reported */
- } finally {
- setStarting(false);
- }
- },
- [ensureAgent],
- );
-
- // Something was asked for and the agent is not on screen yet — a cold coding
- // CLI on a large repository takes seconds. Said once here so the empty fold
- // and the composer cannot disagree about whether anything is happening.
- const waiting = busy || starting;
-
- const composer = useMemo(
- () =>
- activeProject ? (
- <ChatComposer
- projectName={activeProject.name}
- agents={agents}
- agentId={agentId}
- modelId={modelId}
- onAgentChange={setAgentId}
- onModelChange={setModelId}
- onSend={send}
- onDictate={() => {
- // Speech lands in whichever field has the caret (the app-wide
- // dictation focus tracker decides that), so the box is focused
- // first — a dictation started from a BUTTON has already moved
- // focus onto the button by the time the transcript arrives.
- document
- .querySelector<HTMLTextAreaElement>('[data-dictation-target="true"]')
- ?.focus();
- getWSClient()?.send({
- type: "command",
- action: "stt_dictate",
- payload: { mode: "start" },
- });
- }}
- onTalk={() => setTalking(true)}
- busy={waiting}
- />
- ) : null,
- [activeProject, agentId, agents, modelId, send, waiting],
- );
-
- return (
- <div className="flex h-full min-h-0 w-full" data-testid="chat-workspace">
- <div style={{ width: list.size }} className="h-full min-h-0 shrink-0">
- <ChatLibrarySidebar
- refreshToken={refreshToken}
- activeChatId={open?.chat.id ?? null}
- onOpenChat={(project, chat) => {
- setLastProject(project);
- setOpen({ project, chat });
- void reopen(project, chat);
- }}
- onNewChat={(project) => void startChat(project)}
- onAddProject={() => setPicking(true)}
- onNewSession={() => void startSession()}
- />
- </div>
-
- <PaneResizer
- orientation="vertical"
- onPointerDown={list.startResize}
- onDoubleClick={list.reset}
- onNudge={list.nudge}
- active={list.isResizing}
- title="Drag to resize the chat list — double-click to reset"
- />
-
- <div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
- <header className="flex h-11 shrink-0 items-center gap-2 px-4">
- {open && (
- <>
- <AgentMark
- agent={open.chat.agent}
- label={open.chat.agent || "?"}
- size="sm"
- variant="plain"
- />
- <span className="min-w-0 truncate text-xs font-medium">
- {open.chat.title || "New chat"}
- </span>
- <span className="text-muted-foreground/40">·</span>
- </>
- )}
- {activeProject && (
- <span className="flex min-w-0 items-center gap-1.5 truncate text-xs text-muted-foreground">
- <span
- className="h-1.5 w-1.5 shrink-0 rounded-full"
- style={{ background: projectColor(activeProject) }}
- aria-hidden
- />
- {activeProject.name}
- </span>
- )}
- <div className="flex-1" />
- {/* Which of the two views of the same running agent is on screen.
- The pane is always there and always running; this only decides
- whether you read its conversation or watch it work. */}
- {open?.chat.terminal && (
- <button
- type="button"
- data-testid="toggle-raw-pane"
- onClick={() => setRawPane((v) => !v)}
- title={rawPane ? "Read the conversation" : "Watch the terminal"}
- className="flex h-7 items-center gap-1.5 rounded-md px-2 text-[11px] text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
- >
- {rawPane ? (
- <MessagesSquare className="h-3.5 w-3.5" aria-hidden />
- ) : (
- <SquareTerminal className="h-3.5 w-3.5" aria-hidden />
- )}
- {rawPane ? "Conversation" : "Terminal"}
- </button>
- )}
- {open && (
- <button
- type="button"
- onClick={() => setOpen(null)}
- title="Close this chat"
- aria-label="Close this chat"
- className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
- >
- <X className="h-3.5 w-3.5" aria-hidden />
- </button>
- )}
- <button
- type="button"
- data-testid="open-classic-grid"
- onClick={() => setActiveSection("agentic-ide-classic")}
- title="Open the classic terminal grid"
- className="flex h-7 items-center gap-1.5 rounded-md px-2 text-[11px] text-muted-foreground transition-colors hover:bg-accent/60 hover:text-foreground"
- >
- <LayoutGrid className="h-3.5 w-3.5" aria-hidden />
- Terminal grid
- </button>
- </header>
-
- <div className="flex min-h-0 flex-1 flex-col">
- {open?.chat.terminal ? (
- /*
- * The REAL pane, not a rendering of one.
- *
- * A coding CLI is only spawned when something attaches to its
- * pseudo-terminal — the socket IS the start signal. A surface that
- * merely polled for output therefore watched a process that never
- * began: three panes sat at "pending" forever and every prompt was
- * refused, which is exactly what happened here. Mounting the pane
- * starts the agent AND shows what it is doing, and it brings the
- * years of replay, scroll and resize fixes with it.
- */
- <div className="relative flex min-h-0 flex-1 flex-col">
- {/*
- The pane runs, and is not shown.
-
- A coding agent lives only while something is attached to its
- pseudo-terminal, so the terminal cannot go away — but nobody
- should have to READ one to follow their own agent. It is kept
- mounted underneath at full size (xterm needs real geometry to
- pick its columns; a display:none pane reports zero and the CLI
- wraps its output at nothing) and covered by the conversation.
- Hidden from assistive technology too: the same words are right
- there in the stream, in a better order.
- */}
- <div
- className={
- rawPane
- ? "absolute inset-0 overflow-hidden px-4 pb-2"
- : "pointer-events-none absolute inset-0 -z-10 overflow-hidden opacity-0"
- }
- aria-hidden={!rawPane}
- >
- <AgenticTerminal
- key={open.chat.terminal}
- name={open.chat.terminal}
- workspaceId={workspaceId ?? undefined}
- displayName={open.chat.agent || "Agent"}
- appearance="dark"
- fontSize={13}
- active
- focused={rawPane}
- />
- </div>
- {!rawPane && (
- <ChatStream
- terminal={open.chat.terminal}
- /*
- * Not every CLI keeps a conversation anyone can read. When
- * this one does not, the pane it is already running becomes
- * the view — which is the honest answer, and never an empty
- * column with an apology in it (CLAUDE.md §3).
- */
- onUnavailable={() => setRawPane(true)}
- />
- )}
- </div>
- ) : (
- <div className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto scrollbar-jarvis px-6">
- {activeProject ? (
- /*
- * The same fold the pane will occupy, holding its place.
- *
- * Nothing to click here on purpose: the only thing to do on this
- * screen is say what you want, and the box below already asks
- * for it. What replaces this line is the agent itself, in this
- * exact spot — so the wait reads as "it is coming here", not as
- * "something is missing".
- */
- <div className="flex max-w-md flex-col items-center gap-3 py-8 text-center">
- {waiting ? (
- <Loader2
- className="h-7 w-7 animate-spin text-muted-foreground/70"
- aria-hidden
- />
- ) : (
- <SquareTerminal className="h-7 w-7 text-muted-foreground/70" aria-hidden />
- )}
- <h1 className="text-xl font-semibold tracking-tight">
- What should we build in {activeProject.name}?
- </h1>
- <p className="text-xs text-muted-foreground">
- {waiting
- ? "Starting the agent — it takes over this space in a moment."
- : "Type below. The agent opens right here and works in front of you."}
- </p>
- </div>
- ) : (
- <div className="max-w-md text-center">
- <FolderOpen
- className="mx-auto mb-3 h-8 w-8 text-muted-foreground/60"
- aria-hidden
- />
- <p className="text-sm text-muted-foreground">
- Add a project folder to start your first chat.
- </p>
- <button
- type="button"
- onClick={() => setPicking(true)}
- className="mt-4 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground"
- >
- Add a project
- </button>
- </div>
- )}
- </div>
- )}
-
- {composer}
- </div>
-
- </div>
-
- <VoiceBubble
- open={talking}
- onClose={() => setTalking(false)}
- promptTarget={open?.chat.terminal ?? ""}
- />
-
- {picking && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-background/80 p-6">
- <div className="flex max-h-[80vh] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border bg-card shadow-xl">
- <header className="flex items-center justify-between border-b border-border px-4 py-3">
- <h2 className="text-sm font-semibold">Add a project folder</h2>
- <button
- type="button"
- onClick={() => {
- setPicking(false);
- setPickedPath(null);
- }}
- aria-label="Cancel"
- className="flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-accent/60 hover:text-foreground"
- >
- <X className="h-4 w-4" aria-hidden />
- </button>
- </header>
- <div className="flex min-h-0 flex-1 flex-col overflow-hidden p-3">
- <FolderPicker selected={pickedPath} onSelect={setPickedPath} />
- </div>
- {/*
- What is about to be added, in words, above the button that adds it.
-
- The picker deliberately does not report its own selection — it
- expects the surface around it to, because the answer belongs next
- to the control that acts on it. This dialog did not, so clicking
- a folder produced no visible change anywhere and the only feedback
- was a button going from 40% to 100% opacity. That is what "I
- cannot add a folder" looks like from the outside.
- */}
- <div className="flex min-w-0 items-center gap-2 border-t border-border px-4 py-2 text-xs">
- {pickedPath ? (
- <>
- <span className="shrink-0 text-muted-foreground">Selected</span>
- <code className="min-w-0 truncate font-mono text-foreground">
- {pickedPath}
- </code>
- </>
- ) : (
- <span className="text-muted-foreground">
- Pick a folder above — click one to select it.
- </span>
- )}
- </div>
- <footer className="flex items-center justify-end gap-2 border-t border-border px-4 py-3">
- <button
- type="button"
- onClick={() => {
- setPicking(false);
- setPickedPath(null);
- }}
- className="rounded-md px-3 py-1.5 text-xs text-muted-foreground transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
- >
- Cancel
- </button>
- <button
- type="button"
- data-testid="confirm-add-project"
- disabled={!pickedPath}
- onClick={() => void addProject()}
- className="rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:cursor-not-allowed disabled:opacity-40"
- >
- {pickedPath ? `Add ${folderName(pickedPath)}` : "Add project"}
- </button>
- </footer>
- </div>
- </div>
- )}
- </div>
- );
-}